{"text": "/**\n * \\file boost/numeric/ublasx/operation/pow.hpp\n *\n * \\brief Apply the \\c std::pow function to a vector or matrix expression.\n *\n * Copyright (c) 2015, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_POW_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_POW_HPP\n\n\n#include <boost/numeric/ublas/functional.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/inv.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <cmath>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename MatrixExprT>\nstruct matrix_pow_traits\n{\n\ttypedef typename MatrixExprT::matrix_temporary_type result_type;\n};\n\n} // Namespace detail\n\n\n/**\n * \\brief Computes \\a me to the power of \\a p (me^p).\n *\n * If \\a me is a square matrix and \\a p is a positive integer, me^p effectively\n * multiplies \\a me by itself p-1 times.\n * If \\a me is square and nonsingular, me^(-p) effectively multiplies the\n * inverse of \\a me by itself p-1 times.\n *\n * \\note Fractional exponents are not currently supported.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\param p The exponent.\n * \\return The result of \\a me to the power of \\a p.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT, typename T>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_pow_traits<MatrixExprT>::result_type pow(matrix_expression<MatrixExprT> const& me, T p)\n{\n\ttypedef typename detail::matrix_pow_traits<MatrixExprT>::result_type result_type;\n\n\tresult_type res;\n\n\tif (p > 0)\n\t{\n\t\tres = me;\n\n\t\t--p;\n\t\twhile (p >= 1)\n\t\t{\n\t\t\tres = prod(res, me);\n\t\t\t--p;\n\t\t}\n\t}\n\telse if (p < 0)\n\t{\n\t\tresult_type inv_me = inv(me);\n\t\tres = inv_me;\n\t\tp = -p;\n\n\t\t--p;\n\t\twhile (p >= 1)\n\t\t{\n\t\t\tres = prod(res, inv_me);\n\t\t\t--p;\n\t\t}\n\t}\n\telse // p == 0\n\t{\n\t\tres = identity_matrix<typename matrix_traits<MatrixExprT>::value_type>(num_rows(me));\n\t}\n\n\treturn res;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_POW_HPP\n", "meta": {"hexsha": "3e45943b99e68512af3bd62a5f927bc7541c01f3", "size": 2377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/pow.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/pow.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/pow.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.8557692308, "max_line_length": 111, "alphanum_fraction": 0.7114009255, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5998993805652694}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\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\nnamespace math = boost::math::constants;\n\nint main(int,char**)\n{\n\tstd::size_t Nx = 125, Nv = 64;\n\tfield<double,1> f(boost::extents[Nv][Nx]);\n\n\tf.range.v_min = 0.; f.range.v_max = 2.*math::pi<double>();\n\tf.step.dv = (f.range.v_max-f.range.v_min)/Nv;\n\tf.range.x_min = 0.; f.range.x_max = 1.;\n\tf.step.dx = (f.range.x_max-f.range.x_min)/Nx;\n\tdouble dt = 0.5*f.step.dv;\n\n  field<double,1> f_sol = f;\n\t\n\tublas::vector<double> E (Nx);\n  for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = 1.; }\n\n#define X(i) (i*f.step.dx+f.range.x_min)\n#define V(k) (k*f.step.dv+f.range.v_min)\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] = cos(V(k));\n      f_sol[k][i] = cos(V(k)-dt*20);\n    }\n  }\n#undef X\n  f.write(\"init.dat\");\n\n  for ( auto t=0 ; t<20 ; ++t ) {\n  \tif (t%32==0) { std::cout<<\"\\r\"<<t<<\" \"<<std::flush ; }\n\t  field<double,1> Edvf = weno::trp_v(f,E);\n\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      for ( auto i=0 ; i<f.size(1) ; ++i ) {\n        f[k][i] = f[k][i] - dt*Edvf[k][i];\n      }\n    }\n  }\n\n  f_sol.write(\"sol.dat\");\n  f.write(\"vp.dat\");\n\n  return 0;\n}\n\n", "meta": {"hexsha": "85857dbaffff74cdd42b33cb15aae06c364a5241", "size": 1484, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/trpv.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "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/trpv.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/trpv.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "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": 23.935483871, "max_line_length": 63, "alphanum_fraction": 0.5734501348, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5998993805652693}}
{"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#include <nlopt.hpp>\n#include <math.h>\n\nusing namespace geometrycentral;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\ndouble objWrapper(unsigned n, const double* x, double* grad, void* f_data);\nvoid angleDefectWrapper(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data);\nvoid validAngleWrapper(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data);\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 nCorners;\n  size_t dim;\n  VertexData<double> angleDefects;\n  HalfedgeData<size_t> hInd;\n  CornerData<size_t> cInd;\n  //EdgeData<double> lengths;\n\npublic:\n  // Derived Information\n  HalfedgeData<double> theta;\n  HalfedgeData<double> alpha;\n  HalfedgeData<double> beta;\n\n  double obj(unsigned n, const double* x, double* grad, void* f_data)\n  {\n    double accum = 0;\n    for (size_t i = 0; i < n; i++)\n    {\n      accum += pow(x[i],2);\n      if (grad) \n      {\n        grad[i] = 2*x[i];\n      }\n    }\n    return accum;\n  }\n  \n  void angleDefectCalc(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data) \n  {\n    // initialize angle defect\n    for (size_t i = 0; i < m; i++)\n    {\n      result[i] = - angleDefects[i];\n    }\n    if (gradient) \n    {\n      for (size_t i = 0; i < n*m ; i++)\n      {\n        gradient[i] = 0.;\n      }\n    }\n    //go through halfedges\n    for (EdgePtr e : mesh->edges()) \n    {\n      HalfedgePtr he1 = e.halfedge();\n      HalfedgePtr he2 = he1.twin();\n      size_t h1 = hInd[he1];\n      size_t h2 = hInd[he2];\n      size_t v1 = vInd[he1.vertex()];\n      size_t v2 = vInd[he2.vertex()];\n      result[v1] += x[h1] + x[h2];\n      result[v2] += x[h1] + x[h2];\n\n      if (gradient) \n      {\n        gradient[v1 * n + h1] = 1;\n        gradient[v2 * n + h1] = 1;\n        gradient[v1 * n + h2] = 1;\n        gradient[v2 * n + h2] = 1;\n      }\n    }\n    return;\n  }\n  void validAngleCalc(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data) \n  {\n    // first coord specifies angle + alphas - 2pi < 0, second specifies -angle -alphas < 0 \n    for (CornerPtr c: mesh->corners())\n    {\n      double curAngle =  geom->angle(c);\n      result[2 * cInd[c]] = curAngle - 2 * M_PI;\n      result[2 * cInd[c] + 1] = - curAngle;\n    }\n    for (CornerPtr c: mesh->corners())\n    {\n      size_t h = hInd[c.halfedge()];\n      result[2 * cInd[c]] += x[h];\n      result[2 * cInd[c] + 1] -= x[h];\n      result[2 * cInd[c.next()]] += x[h];\n      result[2 * cInd[c.next()] + 1] -= x[h];\n      if (gradient) \n      {\n        gradient[2 * cInd[c] * n + h] = 1;\n        gradient[(2 * cInd[c] + 1) * n + h] = -1;\n        gradient[2 * cInd[c.next()] * n + h] = 1;\n        gradient[(2 * cInd[c.next()] + 1) * n + h] = -1;\n      }\n    }\n    return;\n  }\n\n  void optimize() {\n    nlopt::opt opt(nlopt::LN_COBYLA, nHalfedges);\n    opt.set_min_objective(&objWrapper, this);\n    opt.set_lower_bounds(-2 * M_PI);\n    opt.set_upper_bounds(2 * M_PI);\n\n    std::vector<double> tol1(nVerts, 1e-8);\n    std::vector<double> tol2(2 * nCorners, 1e-8);\n\n    opt.add_equality_mconstraint(&angleDefectWrapper, this, tol1);\n    opt.add_inequality_mconstraint(&validAngleWrapper, this, tol2);\n\n    //opt.add_inequality_constraint(myconstraint, &data[0], 1e-8);\n    //opt.add_inequality_constraint(myconstraint, &data[1], 1e-8);\n    opt.set_xtol_rel(1e-4);\n\tstd::vector<double> x(nHalfedges, 0);\n    double minf;\n    try {\n      nlopt::result result = opt.optimize(x, minf);\n      std::cout << \"found minimum\" << std::setprecision(10) << minf << std::endl;\n    } catch (std::exception& e) {\n      std::cout << \"nlopt failed: \" << e.what() << std::endl;\n    }\n  }\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    nCorners = mesh->nCorners();\n    dim = nVerts + nHalfedges;\n\n    theta = HalfedgeData<double>(mesh);\n    alpha = HalfedgeData<double>(mesh);\n    beta = HalfedgeData<double>(mesh);\n\n    geom->getVertexAngleDefects(angleDefects);\n    optimize();\n    delete geom;\n    delete mesh;\n  }\n};\n\ndouble objWrapper(unsigned n, const double* x, double* grad, void* f_data)\n{\n  return static_cast<CatData*>(f_data)->obj(n, x, grad, NULL);\n}\n\nvoid angleDefectWrapper(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data) \n{\n  static_cast<CatData*>(func_data)->angleDefectCalc(m, result, n, x, gradient, NULL);\n}\n\nvoid validAngleWrapper(unsigned m, double* result, unsigned n, const double* x, double* gradient, void* func_data)\n{\n  static_cast<CatData*>(func_data)->validAngleCalc(m, result, n, x, gradient, NULL);\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\n\n\n/* class CatDataOld {\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  EdgeData<double> lengths;\n\n  public:\n    // Derived Information\n    HalfedgeData<double> finalCurvature;\n    VertexData<double> multiplier;\n\n    HalfedgeData<double> theta;\n    HalfedgeData<double> d;\n    HalfedgeData<double> alpha;\n    HalfedgeData<double> beta;\n\n    EdgeData<char> badEdges;\n    EdgeData<double> netEdgeCurvature;\n    EdgeData<char> negEdges;\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] = 2 * 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], lengths[e]);\n        tripletList.emplace_back(nHalfedges + v1, hInd[h2], lengths[e]);\n        tripletList.emplace_back(nHalfedges + v2, hInd[h1], lengths[e]);\n        tripletList.emplace_back(nHalfedges + v2, hInd[h2], lengths[e]);\n\n        tripletList.emplace_back(hInd[h1], nHalfedges + v1, lengths[e]);\n        tripletList.emplace_back(hInd[h2], nHalfedges + v1, lengths[e]);\n        tripletList.emplace_back(hInd[h1], nHalfedges + v2, lengths[e]);\n        tripletList.emplace_back(hInd[h2], nHalfedges + v2, lengths[e]);\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      }\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    // Updates the straight distances between edges, then checks for bad distances\n    void updateDistances() {\n      size_t bad_halfedges = 0;\n      // Initialize all distances first\n      for (HalfedgePtr h : mesh->allHalfedges()) {\n        theta[h] = lengths[h.edge()] * finalCurvature[h];\n        // Basic constraint\n        if (theta[h] < 2. * M_PI && theta[h] > -2. * M_PI) {\n          d[h] = (theta[h] == 0 ? lengths[h.edge()] : 2 * sin(theta[h] / 2) / finalCurvature[h]);\n        } else {\n          bad_halfedges++;\n          badEdges[h.edge()] = true;\n        }\n      }\n      cout << \"Bad angles:\" << bad_halfedges << endl;\n    }\n    // Updates angles based on distances, checks for self intersection\n    void updateAngles() {\n      size_t bad_halfedges = 0;\n      for (HalfedgePtr h : mesh->allHalfedges()) {\n        double ij = d[h];\n        double jk = d[h.next()];\n        double ki = d[h.next().next()];\n        double cosAngle = (pow(ij, 2) + pow(ki, 2) - pow(jk, 2)) / (2 * ij * ki);\n\n        if (cosAngle > 1.) {\n          alpha[h] = 0;\n          bad_halfedges++;\n          badEdges[h.edge()] = true;\n        } else if (cosAngle < -1.) {\n          alpha[h] = M_PI;\n          // alpha[h] = 10000;\n          bad_halfedges++;\n          badEdges[h.edge()] = true;\n        } else {\n          alpha[h] = acos(cosAngle);\n        }\n      }\n      cout << \"Bad distances:\" << bad_halfedges << endl;\n      for (VertexPtr v : mesh->vertices()) {\n        angleDefects[v] = 2 * M_PI;\n      }\n\n      bad_halfedges = 0;\n      for (HalfedgePtr h : mesh->allHalfedges()) {\n        double betaA = alpha[h] + (theta[h] + theta[h.next().next()]) / 2.;\n        angleDefects[h.vertex()] -= betaA;\n        beta[h] = betaA;\n        if (betaA > 2 * M_PI || betaA < 0.) {\n          // cout << betaA << endl;\n          bad_halfedges++;\n          badEdges[h.edge()] = true;\n        }\n      }\n      cout << \"Self intersection:\" << bad_halfedges << endl;\n    }\n\n    double averageAngleDefect() {\n      double accum = 0;\n      for (size_t i = 0; i < nVerts; i++) {\n        accum += abs(angleDefects[i]);\n      }\n      return accum / nVerts;\n    }\n\n    void checkNegedges() {\n      size_t neg_edges = 0;\n      for (EdgePtr E : mesh->edges()) {\n        netEdgeCurvature[E] = finalCurvature[E.halfedge()] + finalCurvature[E.halfedge().twin()];\n        if (netEdgeCurvature[E] < 0) {\n          negEdges[E] = true;\n          neg_edges++;\n        }\n      }\n      cout << \"Neg edges:\" << neg_edges << endl;\n    }\n    CatDataOld(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      dim = nVerts + nHalfedges;\n\n      finalCurvature = HalfedgeData<double>(mesh);\n      multiplier = VertexData<double>(mesh);\n      theta = HalfedgeData<double>(mesh);\n      d = HalfedgeData<double>(mesh);\n      alpha = HalfedgeData<double>(mesh);\n      beta = HalfedgeData<double>(mesh);\n      badEdges = EdgeData<char>(mesh, false);\n      netEdgeCurvature = EdgeData<double>(mesh);\n      negEdges = EdgeData<char>(mesh, false);\n\n      geom->getVertexAngleDefects(angleDefects);\n      geom->getEdgeLengths(lengths);\n      for (size_t i = 0; i < 1000; i++) {\n        cout << \"Starting Iteration \" << i << endl;\n        solveOptMatrix();\n        updateDistances();\n        updateAngles();\n        cout << \"Average angle defect: \" << averageAngleDefect() << endl;\n        cout << \"Done\" << endl;\n      }\n      checkNegedges();\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Central angles\", theta);\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Interior angles\", alpha);\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Straight distances\", d);\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Exterior angles\", beta);\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Final Angle Defect\", angleDefects);\n      polyscope::getSurfaceMesh(niceName)->addQuantity(\"Net Edge Curvature\", netEdgeCurvature);\n      polyscope::getSurfaceMesh(niceName)->addSubsetQuantity(\"Bad edges\", badEdges);\n      polyscope::getSurfaceMesh(niceName)->addSubsetQuantity(\"Neg edges\", negEdges);\n      delete geom;\n      delete mesh;\n    }\n}; */", "meta": {"hexsha": "324ef019fdbfe96ab2696e6db3716b9b97979616", "size": 13478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old/CAT-Flattening-v1.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-v1.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-v1.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": 32.1670644391, "max_line_length": 116, "alphanum_fraction": 0.6081762873, "num_tokens": 3811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5998969406011926}}
{"text": "/*\n * eig.hpp:\n * Computing all matrix eigenvalues and all eigenvectors A*V=V*D\n *\n * written\tJun. 4, 2015\tA. Takayasu\n * modified\tby Masahide Kashiwagi\n * modified Oct. 11, 2015 A. Takayasu\n */\n\n#ifndef EIG_HPP\n#define EIG_HPP\n\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/complex.hpp>\n#include <kv/vleq.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/io.hpp>\n\n// Eigenvalue computation using QR method for non-symmetric matrix\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T> bool house(const ub::matrix<T>& x, ub::matrix<T>& v, T& beta)\n{\n\t// function [v,beta] = house(x)\n\t// n = length(x);\n\tint n = x.size1();\n\tint i;\n\tT sigma, mu;\n\tv.resize(n,1);\n\tv(0,0) = 1.;\n\tsigma = 0.;\n\tfor (i=1; i<n; i++){\n\t\tsigma += x(i,0)*x(i,0); // sigma = x(2:n)'*x(2:n);\n\t\tv(i,0) = x(i,0); // v = [1;x(2:n)];\n\t}\n\t//\n\t// if sigma == 0\n\t//   beta = 0;\n\t// else\n\t//   mu = sqrt(x(1)^2+sigma);\n\t//   if x(1)<=0\n\t//     v(1) = x(1)-mu;\n\t//   else\n\t//     v(1) = -sigma/(x(1)+mu);\n\t//   end\n\t//   beta = 2*v(1)^2/(sigma+v(1)^2);\n\t//   v = v/v(1);\n\t// end\n\t//\n\tif (sigma == 0.){\n\t\tbeta = 0.;\n\t} else {\n\t\tusing std::sqrt;\n\t\tmu = sqrt(x(0,0) * x(0,0) + sigma);\n\t\tif (x(0,0) <= 0.){\n\t\t\tv(0,0) = x(0,0) - mu;\n\t\t} else {\n\t\t\tv(0,0) = -sigma / (x(0,0) + mu);\n\t\t}\n\t\tbeta = 2 * v(0,0)*v(0,0) / (sigma + v(0,0)*v(0,0));\n\t\tv = v / v(0,0);\n\t}\n\treturn true;\n}\n\ntemplate <class T> bool hess(const ub::matrix<T>& A, ub::matrix<T>& Q, ub::matrix<T>& H)\n{\n\tint i,k=0;\n\tT beta;\n\tub::vector<T> vec_tmp;\n\n\t// n = size(A,2);\n\tint n = A.size1();\n\tif (n != A.size2()) return false;// Square matrix only\n\n\t// Q = eye(n);\n\tub::matrix<T> x, v, mat_H;\n\tQ = ub::identity_matrix<T>(n);\n\tH = A;\n\n\tfor (k = 0; k < n-2; k++) {\n\t\t// [v,beta] = house(H(k+1:n,k));\n\t\tx=ub::project(H,ub::range(k+1,n),ub::range(k,k+1));\n\t\thouse(x,v,beta);\n\t\t//   mat_H = eye(n-k) - beta*v*(v');\n\t\tmat_H = ub::identity_matrix<T>(n-k-1) - beta*prod(v,trans(v));\n\t\t//   H(k+1:n,k) = [mat_H(1,:)*A(k+1:n,k);zeros(n-k-1,1)];\n\t\tvec_tmp  = prod(row(mat_H,0),ub::project(H,ub::range(k+1,n),ub::range(k,k+1)));\n\t\tH(k+1,k) = vec_tmp(0);\n\t\tfor (i=k+2;i<n;i++){\n\t\t\tH(i,k)= (T) 0;\n\t\t}\n\t\t//   H(k+1:n,k+1:n) = mat_H*H(k+1:n,k+1:n);\n\t\tub::project(H,ub::range(k+1,n),ub::range(k+1,n)) = prod(mat_H,ub::project(H,ub::range(k+1,n),ub::range(k+1,n)));\n\t\t//   H(1:n,k+1:n) = H(1:n,k+1:n)*mat_H;\n\t\tub::project(H,ub::range(0,n),ub::range(k+1,n)) = prod(ub::project(H,ub::range(0,n),ub::range(k+1,n)),mat_H);\n\t\t//   Q(:,k+1:n)=Q(:,k+1:n)*mat_H;\n\t\tub::project(Q,ub::range(0,n),ub::range(k+1,n)) = prod(ub::project(Q,ub::range(0,n),ub::range(k+1,n)),mat_H);\n\t}\n\treturn true;\n}\n\ntemplate <class T> bool francisQR(ub::matrix<T>& Q, ub::matrix<T>& H)\n{\n\t// double tol=1e-15; // Little bit strong!!!\n\tT tol = std::numeric_limits<T>::epsilon();\n\tint n = H.size1();\n\t// % p indicates the 'active' matrix size\n\tint p = n, q, r;\n\tT s,t,x,y,z,beta;\n\tub::matrix<T> v, mat_tmp, mat_tmp2, mat_T;\n\tmat_tmp.resize(3,1);\n\tmat_tmp2.resize(2,1);\n\n\twhile (p > 2) {\n\t\tq = p-1;\n\t\ts = H(q-1,q-1) + H(p-1,p-1);\n\t\tt = H(q-1,q-1)*H(p-1,p-1) - H(q-1,p-1)*H(p-1,q-1);\n\t\t// % compute first 3 elements of first column of M\n\t\tx = H(0,0)*H(0,0)+H(0,1)*H(1,0)-s*H(0,0)+t;\n\t\ty = H(1,0)*(H(0,0)+H(1,1)-s);\n\t\tz = H(1,0)*H(2,1);\n\t\tfor (int k = 0; k < p-2; k++) {\n\t\t\tmat_tmp(0,0) = x;\n\t\t\tmat_tmp(1,0) = y;\n\t\t\tmat_tmp(2,0) = z;\n\t\t\t// [v,beta] = house([x,y,z].');\n\t\t\thouse(mat_tmp,v,beta);\n\t\t\tr = fmax(1,k); // r = max(1,k); Need math.h???\n\t\t\t// T = eye(3) - beta*v*(v');\n\t\t\tmat_T = ub::identity_matrix<T>(3) - beta*prod(v,trans(v));\n\t\t\t// H(k+1:k+3,r:n) = T*H(k+1:k+3,r:n);\n\t\t\tub::project(H,ub::range(k,k+3),ub::range(r-1,n)) = prod(mat_T,ub::project(H,ub::range(k,k+3),ub::range(r-1,n)));\n\t\t\tr = fmin(k+4,p);\n\t\t\t// H(1:r,k+1:k+3) = H(1:r,k+1:k+3)*T;\n\t\t\tub::project(H,ub::range(0,r),ub::range(k,k+3)) = prod(ub::project(H,ub::range(0,r),ub::range(k,k+3)),mat_T);\n\t\t\t// Q(:,k+1:k+3) = Q(:,k+1:k+3)*T;\n\t\t\tub::project(Q,ub::range(0,n),ub::range(k,k+3)) = prod(ub::project(Q,ub::range(0,n),ub::range(k,k+3)),mat_T);\n\t\t\t// x = H(k+2,k+1);\n\t\t\tx = H(k+1,k);\n\t\t\t// y = H(k+3,k+1);\n\t\t\ty = H(k+2,k);\n\t\t\t// if k<p-3, z=H(k+4,k+1);\n\t\t\tif (k<p-3) {\n\t\t\t\tz = H(k+3,k);\n\t\t\t}\n\t\t}\n\t\tmat_tmp2(0,0) = x;\n\t\tmat_tmp2(1,0) = y;\n\t\t// [v,beta] = house([x,y]');\n\t\thouse(mat_tmp2,v,beta);\n\t\t// T = eye(2) - beta*v*(v');\n\t\tmat_T = ub::identity_matrix<T>(2) - beta*prod(v,trans(v));\n\t\t// H(q:p,p-2:n) = T'*H(q:p,p-2:n);\n\t\tub::project(H,ub::range(q-1,p),ub::range(p-3,n)) = prod(mat_T,ub::project(H,ub::range(q-1,p),ub::range(p-3,n)));\n\t\t// H(1:p,p-1:p) = H(1:p,p-1:p)*T;\n\t\tub::project(H,ub::range(0,p),ub::range(p-2,p)) = prod(ub::project(H,ub::range(0,p),ub::range(p-2,p)),mat_T);\n\t\t// Q(:,q:p) = Q(:,q:p)*T;\n\t\tub::project(Q,ub::range(0,n),ub::range(q-1,p)) = prod(ub::project(Q,ub::range(0,n),ub::range(q-1,p)),mat_T);\n\t\t// check for convergence\n\t\t// if abs(H(p,q)) < tol*(abs(H(q,q))+abs(H(p,p)))\n\t\t// if (fabs(H(p-1,q-1)) < tol*(fabs(H(q-1,q-1) + fabs(H(p-1,p-1)))))\n\t\tusing std::abs;\n\t\tif (abs(H(p-1,q-1)) < tol*(abs(H(q-1,q-1) + abs(H(p-1,p-1))))) {\n\t\t\tH(p-1,q-1) = (T) 0;\n\t\t\tp--;\n\t\t} else if (abs(H(p-2,q-2)) < tol*(abs(H(q-2,q-2)) + fabs(H(q-1,q-1)))){\n\t\t\tH(p-2,q-2) = (T) 0;\n\t\t\tp-=2;\n\t\t}\n\t}\n\treturn true;\n}\n\ntemplate <class T> bool lu_factorize_comp(ub::matrix<kv::complex<T> >& A, ub::vector<int>& p)// Numerical recipe in C (ludcmp)\n{\n  int i,j,k,imax;\n  int n = A.size1();\n\n  ub::vector<T> vv;\n  vv.resize(n);\n\n  T big, temp;\n  kv::complex<T> sum, dum;\n\n  using std::abs;\n\n  for (i = 0; i < n; i++) {\n    big = 0.0;\n    for (j = 0; j < n; j++) {\n      if ((temp = abs(A(i,j))) > big) {\n        big = temp;\n      }\n    }\n    if (big == 0.0) {\n      std::cout << \"Singular matrix in lu_factorize_comp\" << std::endl;\n      return false;\n    }\n    vv(i) = 1.0/big;\n  }\n\n  for (j = 0; j < n; j++) {\n    for (i = 0; i < j; i++) {\n      sum = A(i,j);\n      for (k = 0; k < i; k++) {\n        sum -= A(i,k)*A(k,j);\n      }\n      A(i,j) = sum;\n    }\n    big = 0.0;\n    for (i = j; i < n; i++) {\n      sum = A(i,j);\n      for (k = 0; k < j; k++) {\n        sum -= A(i,k)*A(k,j);\n      }\n      A(i,j) = sum;\n      if ((temp=vv(i)*abs(sum)) >= big) {\n        big = temp;\n        imax = i;\n      }\n    }\n    if (j != imax) {\n      for (k = 0; k < n; k++) {\n        dum = A(imax,k);\n        A(imax,k) = A(j,k);\n        A(j,k) = dum;\n      }\n      vv(imax) = vv(j);\n    }\n    p(j) = imax;\n    if (abs(A(j,j)) == 0) {\n      std::cout << \"Singular matrix in lu_factorize_comp\" << std::endl;\n      return false;\n    }\n    if (j != n) {\n      dum = 1./(A(j,j));\n      for (i = j+1; i < n; i++) {\n        A(i,j) *= dum;\n      }\n    }\n  }\n  return true;\n}\n\ntemplate <class T> bool lu_substitute_comp(const ub::matrix<kv::complex<T> >& A, const ub::vector<int>& p, ub::vector<kv::complex<T> >& b)// Numerical recipe in C (lubksb)\n{\n  int i, ii=0, ip, j;\n  int n = A.size1();\n  kv::complex<T> sum;\n\n  using std::abs;\n\n  for (i = 0; i < n; i++) {\n    ip = p(i);\n    sum = b(ip);\n    b(ip) = b(i);\n    if (ii==0) {\n      for (j = ii; j <= i-1; j++) {\n        sum -= A(i,j)*b(j);\n      }\n    } else if (abs(sum) != 0) {\n      ii = i;\n    }\n    b(i) = sum;\n  }\n  for (i = n-1; i >= 0; i--) {\n      sum = b(i);\n      for (j = i+1; j < n; j++) {\n        sum -= A(i,j)*b(j);\n      }\n      b(i) = sum/A(i,i);\n  }\n  return true;\n}\n\ntemplate <class T> bool eig2by2(const ub::matrix<T>& P, const ub::matrix<T>& A, ub::matrix< kv::complex<T> >& V, ub::matrix< kv::complex<T> >& D)\n{\n\tint i, j, k, l;\n\tT tra, det, x_norm;\n\tkv::complex<T> tmp, tmp1, am, ap;\n\tkv::complex<T> b1, b2;\n\tkv::complex<T> a11, a12, a21, a22, ck;\n\tint n = A.size1();// n = size(A,2);\n\t// X = eye(n,n); Orthogonal matrix\n\tub::matrix< kv::complex<T> > X;\n\tub::vector< kv::complex<T> > x;\n\tX.resize(n,n);\n\tfor (i = 0; i < n; i++) {\n\t\tX(i,i) = 1.;\n\t}\n\tD.resize(n,n);// Eigen value matrix (diagonal)\n\n\ti=1;\n\t// Compute eigenvalue\n\twhile (i<=n) {\n\t\tif (i!=n) {\n\t\t\tj = i+1;\n\t\t}\n\t\tif (A(j-1,i-1) == 0 || i==n) {\n\t\t\t// Eigen value is diagonal element\n\t\t\tD(i-1,i-1) = A(i-1,i-1);\n\t\t\ti++;\n\t\t} else {\n\t\t\t// If A contains 2 by 2 block on the diagonal,\n\t\t\t// compute a real pair or a complex conjugate pair.\n\t\t\ttra = A(i-1,i-1) + A(j-1,j-1);\n\t\t\tdet = A(i-1,i-1)*A(j-1,j-1)-A(i-1,j-1)*A(j-1,i-1);\n\t\t\ttmp = tra*tra-4*det;// Complex!\n\t\t\tusing std::sqrt;\n\t\t\ttmp1 = sqrt(tmp);\n\t\t\tam = 0.5*(tra + tmp1);\n\t\t\tap = 0.5*(tra - tmp1);\n\t\t\tusing std::abs;\n\t\t\tif (abs(A(i-1,i-1)-am)/abs(am) < 1) {\n\t\t\t\tD(i-1,i-1) = am;\n\t\t\t\tD(j-1,j-1) = ap;\n\t\t\t} else {\n\t\t\t\tD(i-1,i-1) = ap;\n\t\t\t\tD(j-1,j-1) = am;\n\t\t\t}\n\t\t\ti += 2;\n\t\t}\n\t}\n\t// std::cout << \"D\" << D << std::endl;\n\t// D(0,0).imag() = -D(0,0).imag();\n\t// std::cout << \"conj(D)\" << D << std::endl;\n\n\n\t// Compute eigenvector by backward substitution\n\tbool flag = true;\n\tfor (i = 1; i <= n; i++) {\n\t\tj = i;\n\t\tif (flag) {\n\t\t\t// Compute jth element of ith eigenvector X(j,i)\n\t\t\twhile (j>0) {\n\t\t\t\tk = fmin(n,j+1);\n\t\t\t\tl = fmax(1,j-1);\n\t\t\t\tif (i==j) {\n\t\t\t\t\tif (A(k-1,j-1) != 0 && k!=j) {\n\t\t\t\t\t\t// Block diagonal [A(j,j), A(j,j+1); A(j+1,j), A(j+1,j+1)] appears\n\t\t\t\t\t\tusing std::abs;\n\t\t\t\t\t\tif (abs(A(j,j)-D(i-1,i-1)) > abs(A(j-1,j))) {\n\t\t\t\t\t\t\tX(j,i-1) = -A(j,j-1) / (A(j,j)-D(i-1,i-1));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tX(j,i-1) = -(A(j-1,j-1)-D(i-1,i-1))/A(j-1,j);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (D(j-1,j-1).imag() != -D(j-1,j-1).imag()) {\n\t\t\t\t\t\t\t// Conjugate pair X(j,i) = 1+0*1i;\n\t\t\t\t\t\t\tflag = false; //Conjugate pair flag (flag=false means the next eigenvector is conjugate of ith vector)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj--;\n\t\t\t\t\t} else if (A(j-1,l-1) != 0 && l!=j) {\n\t\t\t\t\t\t// Block diagonal [A(j-1,j-1), A(j-1,j); A(j,j-1), A(j,j)] appears X(j,i)=1\n\t\t\t\t\t\tusing std::abs;\n\t\t\t\t\t\tif (abs(A(j-2,j-2)-D(i-1,i-1)) > abs(A(j-1,j-2))) {\n\t\t\t\t\t\t\tX(j-2,i-1) = -A(j-2,j-1)/(A(j-2,j-2)-D(i-1,i-1));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tX(j-2,i-1) = -(A(j-1,j-1)-D(i-1,i-1))/A(j-1,j-2);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (D(j-1,j-1).imag() != -D(j-1,j-1).imag()) {\n\t\t\t\t\t\t\t// Conjugate pair X(j,j) = 1+0*1i;\n\t\t\t\t\t\t\tflag = false;// Conjugate pair flag (flag=false means the next eigenvector is conjugate of ith vector)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj -= 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// A(i,i) is eigen value\n\t\t\t\t\t\tj--;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (A(j-1,l-1)!=0 && l!=j) {\n\t\t\t\t\t\t// Block diagonal [A(j-1,j-1), A(j-1,j); A(j,j-1), A(j,j)] appears\n\t\t\t\t\t\t// Real pair\n\t\t\t\t\t\tb1=0; b2=0;\n\t\t\t\t\t\tfor (k = j+1; k <= fmin(i+1,n); k++) {\n\t\t\t\t\t\t\tb1 += A(j-2,k-1)*X(k-1,i-1);\n\t\t\t\t\t\t\tb2 += A(j-1,k-1)*X(k-1,i-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ta11 = A(j-2,j-2)-D(i-1,i-1);\n\t\t\t\t\t\ta12 = A(j-2,j-1);\n\t\t\t\t\t\ta21 = A(j-1,j-2);\n\t\t\t\t\t\ta22 = A(j-1,j-1)-D(i-1,i-1);\n\t\t\t\t\t\tub::matrix<kv::complex<T> > LU(2,2);\n\t\t\t\t\t\tLU(0,0) = a11; LU(0,1) = a12; LU(1,0) = a21; LU(1,1) = a22;\n\t\t\t\t\t\tub::vector<kv::complex<T> > b(2);\n\t\t\t\t\t\tb(0) = b1; b(1) = b2;\n\t\t\t\t\t\tub::vector<int> pm(n);\n\t\t\t\t\t\tlu_factorize_comp(LU,pm);\n\t\t\t\t\t\tlu_substitute_comp(LU,pm,b);\n\t\t\t\t\t\t// ck  = -1/(a11*a22-a12*a21);\n\t          // X(j-2,i-1) = ck*(a22*b1-a12*b2);\n\t          // X(j-1,i-1) = ck*(-a21*b1+a11*b2);\n\t\t\t\t\t\tX(j-2,i-1) = b(0);\n\t\t\t\t\t\tX(j-1,i-1) = b(1);\n\t\t\t\t\t\tj -= 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// A(i,i) is eigen value\n\t\t\t\t\t\tfor (k = j+1; k <= fmin(i+1,n); k++) {\n\t\t\t\t\t\t\tX(j-1,i-1) = X(j-1,i-1) + A(j-1,k-1)*X(k-1,i-1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// X(j-1,i-1) = -X(j-1,i-1)/(D(j-1,j-1)-D(i-1,i-1));\n\t\t\t\t\t\tif ((D(j-1,j-1)-D(i-1,i-1)).real()==0 && (D(j-1,j-1)-D(i-1,i-1)).imag()==0 && X(j-1,i-1).real()==0 && X(j-1,i-1).imag()==0) {\n\t\t\t\t\t\t\tX(j-1,i-1) = 0; // d(j) = d(i)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tX(j-1,i-1) = -X(j-1,i-1)/(D(j-1,j-1)-D(i-1,i-1));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tx = column(X,i-1);\n\t\t\tx_norm = 0;\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tusing std::abs;\n\t\t\t\tx_norm += abs(x(k))*abs(x(k));\n\t\t\t}\n\t\t\tusing std::sqrt;\n\t\t\tx_norm = sqrt(x_norm);\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tX(k,i-1) /= x_norm;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tX(k,i-1).real() =  X(k,i-2).real();\n\t\t\t\tX(k,i-1).imag() =  -X(k,i-2).imag();\n\t\t\t}\n\t\t\tflag = true;\n\t\t}\n\t}\n\t// V = P*X;\n\tV = prod(P,X);\n\n\treturn true;\n}\n\ntemplate <class T> bool eig(const ub::matrix<T>& A, ub::matrix< kv::complex<T> >& V, ub::matrix< kv::complex<T> >& D)\n{\n\tint n = A.size1();\n\tif (n != A.size2()) return false;// Square matrix only\n\n\tub::matrix<T> Q, H;\n\tQ.resize(n,n);\n\tH.resize(n,n);\n\n\t// std::cout << Q << \"\\n\";\n\thess(A,Q,H);\n\tfrancisQR(Q,H);\n\teig2by2(Q,H,V,D);\n\t// std::cout << \"Residual \" << prod(A,Q)-prod(Q,H) << \"\\n\";\n\t// std::cout << \"Residual \" << prod(A,V)-prod(V,D) << \"\\n\";\n\treturn true;\n}\n\ntemplate <class T> bool veig(const ub::matrix<T>& A, ub::vector< kv::complex< kv::interval<T> > >& v)\n{\n\tint i, j, n=A.size1();\n\tub::matrix< kv::complex<T> > V, D;\n\tub::matrix< kv::complex< kv::interval<T> > > X, C;\n\tub::matrix< kv::interval<T> > BA, BC, G;\n\t// ub::vector< kv::complex< kv::interval<T> > > b, x;\n\tub::vector< kv::interval<T> > d, err;\n\n\teig(A,V,D);\n\t// std::cout << \"Residual \" << prod(a,V)-prod(V,D) << \"\\n\";\n\t// C = A*intval(X);\n\tX.resize(n,n);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tX(i,j) = V(i,j);\n\t\t}\n\t}\n\tC = prod(A,X);\n\n\t// G = verifylss(X,C);\n\tG.resize(2*n,n);\n\tBA.resize(2*n,2*n);\n\tBC.resize(2*n,n);\n\n\t// X  = A + Bi;\n\t// BA = [A, -B; B, A]\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tBA(i,j) = X(i,j).real();\n\t\t\tBA(i+n,j) = X(i,j).imag();\n\t\t\tBA(i,j+n) = -X(i,j).imag();\n\t\t\tBA(i+n,j+n) = X(i,j).real();\n\t\t}\n\t}\n\n\t// C = P + Qi\n\t// BC = [P;Q]\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tBC(i,j) = C(i,j).real();\n\t\t\tBC(i+n,j) = C(i,j).imag();\n\t\t}\n\t}\n\tkv::vleq(BA,BC,G);\n\n\t// mid_G = mid(G);\n\n\td.resize(2*n);\n\terr.resize(2*n);\n\n\tfor (i = 0; i < n; i++) {\n\t\td(i) = mid(G(i,i));\n\t\td(i+n) = mid(G(i+n,i));\n\t\tG(i,i) -= d(i);\n\t\tG(i+n,i) -= d(i+n);\n\t}\n\n\t// G = G-mid_G;\n\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\terr(i) += G(i,j);\n\t\t\terr(i+n) += G(i+n,j);\n\t\t}\n\t}\n\n\tv.resize(n);\n\td += err;\n\tfor (i = 0; i < n; i++) {\n\t\tv(i) = kv::complex< kv::interval<T> >(d(i),d(i+n));\n\t}\n\treturn true;\n}\n\ntemplate <class T> bool veig(const ub::matrix< kv::interval<T> >& A, ub::vector< kv::complex< kv::interval<T> > >& v)\n{\n\tint i, j, n=A.size1();\n\tub::matrix< kv::complex<T> > V, D;\n\tub::matrix< kv::complex< kv::interval<T> > > X, C;\n\tub::matrix< kv::interval<T> > BA, BC, G;\n\t// ub::vector< kv::complex< kv::interval<T> > > b, x;\n\tub::vector< kv::interval<T> > d, err;\n\n\teig(mid(A),V,D);\n\t// std::cout << \"Residual \" << prod(a,V)-prod(V,D) << \"\\n\";\n\t// C = A*intval(X);\n\tX.resize(n,n);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tX(i,j) = V(i,j);\n\t\t}\n\t}\n\tC = prod(A,X);\n\n\t// G = verifylss(X,C);\n\tG.resize(2*n,n);\n\tBA.resize(2*n,2*n);\n\tBC.resize(2*n,n);\n\n\t// X  = A + Bi;\n\t// BA = [A, -B; B, A]\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tBA(i,j) = X(i,j).real();\n\t\t\tBA(i+n,j) = X(i,j).imag();\n\t\t\tBA(i,j+n) = -X(i,j).imag();\n\t\t\tBA(i+n,j+n) = X(i,j).real();\n\t\t}\n\t}\n\n\t// C = P + Qi\n\t// BC = [P;Q]\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tBC(i,j) = C(i,j).real();\n\t\t\tBC(i+n,j) = C(i,j).imag();\n\t\t}\n\t}\n\tkv::vleq(BA,BC,G);\n\n\t// mid_G = mid(G);\n\n\td.resize(2*n);\n\terr.resize(2*n);\n\n\tfor (i = 0; i < n; i++) {\n\t\td(i) = mid(G(i,i));\n\t\td(i+n) = mid(G(i+n,i));\n\t\tG(i,i) -= d(i);\n\t\tG(i+n,i) -= d(i+n);\n\t}\n\n\t// G = G-mid_G;\n\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++) {\n\t\t\terr(i) += G(i,j);\n\t\t\terr(i+n) += G(i+n,j);\n\t\t}\n\t}\n\n\tv.resize(n);\n\td += err;\n\tfor (i = 0; i < n; i++) {\n\t\tv(i) = kv::complex< kv::interval<T> >(d(i),d(i+n));\n\t}\n\treturn true;\n}\n\ntemplate <class T> bool invert_comp(const ub::matrix<kv::complex<T> >& A, ub::matrix<kv::complex<T> >& R)\n{\n  int n = A.size1();\n  ub::matrix< kv::complex<T> > LU=A;\n\n  ub::vector< kv::complex<T> > b(n);\n  ub::vector<int> pm(n);\n\n  R.resize(n,n);\n\n  lu_factorize_comp(LU,pm);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      if (j==i) b(j) = 1.0;\n      else b(j) = 0.0;\n    }\n    // std::cout << \"b\" << b << std::endl;\n    lu_substitute_comp(LU,pm,b);\n    ub::column(R,i) = b;\n  }\n  return true;\n}\n\n} // namespace kv\n\n#endif // EIG_HPP\n", "meta": {"hexsha": "7119acc388a1863f1972bb5035d0bcf5f11c1357", "size": 16033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/eig.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/eig.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/eig.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": 25.0907668232, "max_line_length": 171, "alphanum_fraction": 0.4661635377, "num_tokens": 6942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5998969247165257}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved：CC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      版权部分所有，遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用\n *\n * Filename                : \n * Description             : 视觉SLAM十四讲/ch6/g2o 学习记录\n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET国家重点实验室FOCUS团队\n * Modification History\t   : ver1.0, 2018.04.05, William Yu\n                            \n=================================================================================*/\n\n/// Include Files\n#include <iostream>\n#include <g2o/core/base_vertex.h> //定点类型\n#include <g2o/core/base_unary_edge.h> //一元边类型\n#include <g2o/core/block_solver.h> //求解器\n#include <g2o/core/optimization_algorithm_levenberg.h> //莱文贝格-马夸特方法 Levenberg-Marquardt算法\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> //计时库\nusing namespace std; \n\n\n\n/*-----------------------------[Note]---------------------------\n# G2O图优化\n深入理解图优化与g2o：图优化篇 http://www.cnblogs.com/gaoxiang12/p/5244828.html\n深入理解图优化与g2o：g2o篇 https://www.cnblogs.com/gaoxiang12/p/5304272.html\n--------------------------------------------------------------*/\n\n\n/// Global Variables\n\n/**\n * @class \n * @brief 待优化变量\n */\n// 曲线模型的顶点，模板参数：优化变量维度和数据类型\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    virtual void setToOriginImpl() // 重置\n    {\n        _estimate << 0,0,0;\n    }\n    \n    virtual void oplusImpl( const double* update ) // 更新\n    {\n        _estimate += Eigen::Vector3d(update);\n    }\n    // 存盘和读盘：留空\n    virtual bool read( istream& in ) {}\n    virtual bool write( ostream& out ) const {}\n};\n\n\n\n\n\n\n\n\n/**\n * @class \n * @brief 误差模型\n */\n// 误差模型 模板参数：观测值维度，类型，连接顶点类型\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1,double,CurveFittingVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CurveFittingEdge( double x ): BaseUnaryEdge(), _x(x) {}\n    // 计算曲线模型误差\n    void computeError()\n    {\n        const CurveFittingVertex* v = static_cast<const CurveFittingVertex*> (_vertices[0]);\n        const Eigen::Vector3d abc = v->estimate();\n        _error(0,0) = _measurement - std::exp( abc(0,0)*_x*_x + abc(1,0)*_x + abc(2,0) ) ;\n    }\n    virtual bool read( istream& in ) {}\n    virtual bool write( ostream& out ) const {}\npublic:\n    double _x;  // x 值， y 值为 _measurement\n};\n\n\n\n\n\n\n\n\n/// Function Definitions\n\n/**\n * @function main\n * @author William Yu\n * @brief \n * @param  None\n * @retval None\n */\nint main( int argc, char** argv )\n{\n    double a=1.0, b=2.0, c=1.0;         // 真实参数值\n    int N=100;                          // 数据点\n    double w_sigma=1.0;                 // 噪声Sigma值\n    cv::RNG rng;                        // OpenCV随机数产生器\n    double abc[3] = {0,0,0};            // abc参数的估计值\n\n    vector<double> x_data, y_data;      // 数据\n    \n    cout<<\"generating data: \"<<endl;\n    for ( int i=0; i<N; i++ )\n    {\n        double x = i/100.0;\n        x_data.push_back ( x );\n        y_data.push_back (\n            exp ( a*x*x + b*x + c ) + rng.gaussian ( w_sigma ) //人为叠加高斯噪声\n        );\n        cout<<x_data[i]<<\" \"<<y_data[i]<<endl;\n    }\n    \n    //-- 图优化过程\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;   //误差项优化变量维度为3，误差值维度为1\n    //线性求解器\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); \n    //稀疏矩阵求解\n    Block* solver_ptr = new Block( linearSolver );     \n    //迭代算法 从下面这三行 梯度下降方法，从高斯牛顿GN,  莱文贝格－马夸特方法LM, DogLeg中选择一个\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( solver_ptr );\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n    // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n    //优化模型\n    g2o::SparseOptimizer optimizer;   \n    optimizer.setAlgorithm( solver );   \n    optimizer.setVerbose( true ); \n\n    // //--[ERROR]see: https://www.cnblogs.com/xueyuanaichiyu/p/7921382.html\n    // // 构建图优化，先设定g2o\n    // typedef g2o::BlockSolver< g2o::BlockSolverTraits<3,1> > Block;  // 每个误差项优化变量维度为3，误差值维度为1\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); // 线性方程求解器\n    // Block* solver_ptr = new Block( std::unique_ptr<Block::LinearSolverType>(linearSolver) );      // 矩阵块求解器\n    // // 梯度下降方法，从GN, LM, DogLeg 中选\n    // g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( std::unique_ptr<Block>(solver_ptr) );\n    // // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( std::unique_ptr<Block>(solver_ptr) );\n    // // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( std::unique_ptr<Block>(solver_ptr) );\n    // g2o::SparseOptimizer optimizer;     // 图模型\n    // optimizer.setAlgorithm( solver );   // 设置求解器\n    // optimizer.setVerbose( true );       // 打开调试输出\n    \n    // 往图中增加顶点\n    CurveFittingVertex* v = new CurveFittingVertex();\n    v->setEstimate( Eigen::Vector3d(0,0,0) );\n    v->setId(0);\n    optimizer.addVertex( v );\n    \n    // 往图中增加边\n    for ( int i=0; i<N; i++ )\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge( x_data[i] );\n        edge->setId(i);\n        edge->setVertex( 0, v );                // 设置连接的顶点\n        edge->setMeasurement( y_data[i] );      // 观测数值\n        edge->setInformation( Eigen::Matrix<double,1,1>::Identity()*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(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<<\"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": "f198dafc7dc4fe9db373e66f2c115d0198dc2e0c", "size": 6462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5.非线性优化/g2o_curve_fitting/main.cpp", "max_stars_repo_name": "HustRobot/VSLAM", "max_stars_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "5.非线性优化/g2o_curve_fitting/main.cpp", "max_issues_repo_name": "HustRobot/VSLAM", "max_issues_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "5.非线性优化/g2o_curve_fitting/main.cpp", "max_forks_repo_name": "HustRobot/VSLAM", "max_forks_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 33.832460733, "max_line_length": 138, "alphanum_fraction": 0.6035283194, "num_tokens": 2141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5998969218253476}}
{"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_POLYNOMIALS_FUNCTIONS_SCALAR_TCHEBEVAL_HPP_INCLUDED\n#define NT2_TOOLBOX_POLYNOMIALS_FUNCTIONS_SCALAR_TCHEBEVAL_HPP_INCLUDED\n#include <nt2/toolbox/polynomials/functions/tchebeval.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <nt2/include/functions/scalar/average.hpp>\n#include <nt2/toolbox/polynomials/category.hpp>\n#include <nt2/sdk/meta/fusion.hpp>\n#include <boost/fusion/adapted/array.hpp>\n#include <nt2/include/functions/scalar/fma.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::tchebeval_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< arithmetic_<A0> >)(fusion_sequence_<A1>)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return tchebeval(result_type(a0), a1);\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is floating_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::tchebeval_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< floating_<A0> >)(fusion_sequence_<A1>)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      typename A1::const_iterator p = a1.begin();\n      A0 b0 = *p++;\n      A0 b1 = Zero<A0>();\n      A0 b2 = Zero<A0>();;\n      while (p != a1.end())\n      {\n        b2 = -b1;\n        b1 = b0;\n        b0 = nt2::fma(a0, b1, b2+*p++);\n      }\n      return average(b0, b2);\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "17af2d05ce530a7bad152838f3ff5ff0a26d1f47", "size": 2400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/polynomials/include/nt2/toolbox/polynomials/functions/scalar/tchebeval.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/polynomials/include/nt2/toolbox/polynomials/functions/scalar/tchebeval.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/polynomials/include/nt2/toolbox/polynomials/functions/scalar/tchebeval.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": 34.2857142857, "max_line_length": 80, "alphanum_fraction": 0.485, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.599895713816371}}
{"text": "/**\n * @file QuadraticCost.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the MIT License.\n * @date 2021\n */\n\n#include <string>\n\n#include <Eigen/Dense>\n\n#include <ScsEigen/Logger.h>\n#include <ScsEigen/QuadraticCost.h>\n\nusing namespace ScsEigen;\n\nQuadraticCost::QuadraticCost(const Eigen::Ref<const Eigen::MatrixXd>& Q,\n                             const Eigen::Ref<const Eigen::MatrixXd>& b,\n                             double c)\n    : Cost((Q.rows() == Q.cols() && Q.rows() == b.rows()) ? Q.rows() : 0, \"Quadratic cost\")\n{\n    if (Q.rows() != Q.cols() || Q.rows() != b.rows())\n    {\n\n        log()->error(\"[QuadraticCost::QuadraticCost] Q matrix must be square and the size of b \"\n                     \"should be coherent with Q\");\n        assert(false);\n    } else\n    {\n        m_Q = (Q + Q.transpose()) / 2;\n        m_b = b;\n        m_c = c;\n    }\n}\n\nbool QuadraticCost::setQ(const Eigen::Ref<const Eigen::MatrixXd>& Q)\n{\n    if (m_Q.size() != 0)\n    {\n        if (Q.size() != m_Q.size())\n        {\n            log()->error(\"[QuadraticCost::setQ] The size of the matrix 'Q' cannot change.\");\n            return false;\n        }\n    } else if (Q.rows() != Q.cols())\n    {\n        log()->error(\"[QuadraticCost::QuadraticCost] Q matrix must be square.\");\n        return false;\n    } else if (!this->setNumberOfVariables(Q.rows()))\n    {\n        log()->error(\"[QuadraticCost::setQ] Unable to set the number of variables.\");\n        return false;\n    }\n\n    m_Q = (Q + Q.transpose()) / 2;\n    return true;\n}\n\nbool QuadraticCost::setB(const Eigen::Ref<const Eigen::VectorXd>& b)\n{\n    if (m_b.size() != 0)\n    {\n        if (b.size() != m_b.size())\n        {\n            log()->error(\"[QuadraticCost::setB] The size of the vector 'b' cannot change.\");\n            return false;\n        }\n    } else if (!this->setNumberOfVariables(b.size()))\n    {\n        log()->error(\"[QuadraticCost::setB] Unable to set the number of variables.\");\n        return false;\n    }\n\n    m_b = b;\n    return true;\n}\n\nvoid QuadraticCost::setC(double c)\n{\n    m_c = c;\n}\n\nEigen::Ref<const Eigen::VectorXd> QuadraticCost::getB() const\n{\n    return m_b;\n}\n\nEigen::Ref<const Eigen::MatrixXd> QuadraticCost::getQ() const\n{\n    return m_Q;\n}\n\ndouble QuadraticCost::getC() const\n{\n    return m_c;\n}\n", "meta": {"hexsha": "b64cadd8fba2d1221c0570fc85afc03a0566d687", "size": 2294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ScsEigen/src/QuadraticCost.cpp", "max_stars_repo_name": "GiulioRomualdi/scs-eigen", "max_stars_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-29T07:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T16:36:54.000Z", "max_issues_repo_path": "src/ScsEigen/src/QuadraticCost.cpp", "max_issues_repo_name": "GiulioRomualdi/scs-eigen", "max_issues_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-03T20:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T21:12:24.000Z", "max_forks_repo_path": "src/ScsEigen/src/QuadraticCost.cpp", "max_forks_repo_name": "GiulioRomualdi/scs-eigen", "max_forks_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:35:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T16:35:06.000Z", "avg_line_length": 23.6494845361, "max_line_length": 96, "alphanum_fraction": 0.5566695728, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5998957066572842}}
{"text": "#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/geometry/algorithms/simplify.hpp>\n#include <boost/geometry/strategies/spherical/distance_cross_track.hpp>\n#include <boost/geometry/strategies/agnostic/simplify_douglas_peucker.hpp>\n#include <boost/geometry.hpp>\n\nnamespace bg = boost::geometry;\nusing tokenizer = boost::tokenizer<boost::char_separator<char>>;\nusing point_t = bg::model::point<double, 2, bg::cs::geographic<bg::degree>>;\nusing polyline_t = bg::model::linestring<point_t>;\n\nauto readFile() {\n  polyline_t coordinates{};\n\n  std::fstream coordinateFile;\n  boost::char_separator<char> sep{\",\"};\n  coordinateFile.open(\"coordinates.csv\", std::ios::in);\n  if(coordinateFile.is_open()) {\n    std::string line;\n    while(getline(coordinateFile, line)) {\n      tokenizer tok{line, sep};\n      std::vector<std::string> vars {tok.begin(), tok.end()};\n      point_t coord{boost::lexical_cast<double>(vars[0]), boost::lexical_cast<double>(vars[1])};\n      bg::append(coordinates, coord);\n    }\n  }\n  coordinateFile.close();\n  return coordinates;\n}\n\ndouble ConvertToEarthRadiusProportion(const double distance) {\n  constexpr double earth_radius = 6378140.0;\n  return distance/earth_radius;\n}\n\nint main(int /*argc*/, char **/*argv[]*/) {\n  std::cout << \"Douglas Peucker simplification algorithm application using Boost::Geometry\" << std::endl;\n  polyline_t polyline = readFile();\n  polyline_t decimated_polyline{};\n  bg::strategy::simplify::douglas_peucker<point_t, bg::strategy::distance::cross_track<double>> douglas_peucker;\n  bg::simplify(polyline, decimated_polyline, ConvertToEarthRadiusProportion(100.0), douglas_peucker);\n  std::cout << \"Original Polyline Data Points: \" << polyline.size() <<std::endl;\n  std::cout << \"After bg::simplify applied: \" << decimated_polyline.size() <<std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "5b55e5818951f51a32e2da948f9fb2da96e5e352", "size": 1901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/Boost/Geometry/main.cpp", "max_stars_repo_name": "danpeczek/tech-cookbook", "max_stars_repo_head_hexsha": "c22f499147524dfd58a253bdb9d4ab89e0004475", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-06T18:42:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-06T18:42:05.000Z", "max_issues_repo_path": "C++/Boost/Geometry/main.cpp", "max_issues_repo_name": "danpeczek/tech-cookbook", "max_issues_repo_head_hexsha": "c22f499147524dfd58a253bdb9d4ab89e0004475", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:46:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T21:08:21.000Z", "max_forks_repo_path": "C++/Boost/Geometry/main.cpp", "max_forks_repo_name": "danpeczek/tech-cookbook", "max_forks_repo_head_hexsha": "c22f499147524dfd58a253bdb9d4ab89e0004475", "max_forks_repo_licenses": ["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.2745098039, "max_line_length": 112, "alphanum_fraction": 0.7296159916, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5998718361782083}}
{"text": "/**\n * \\file dcs/math/stats/distribution/students_t.hpp\n *\n * \\brief The Student's t distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_STUDENTS_T_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_STUDENTS_T_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/students_t.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/stats/distribution/chi_squared.hpp>\n#include <dcs/math/stats/distribution/normal.hpp>\n#include <dcs/math/stats/function/rand.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\nusing ::std::size_t;\n\n\n/**\n * \\brief The Student's t distribution with parameter \\f$\\nu\\f$ (the degrees of\n *  freedom).\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass students_t_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit students_t_distribution(support_type df)\n\t\t: dist_(df)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * Student's t distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A random number distributed according to this Student's t\n\t * distribution.\n\t *\n\t * A \\c Student's t random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t *   \\frac{\\Gamma(\\frac{\\nu+1}{2})} {\\sqrt{\\nu\\pi}\\,\\Gamma(\\frac{\\nu}{2})} \\left(1+\\frac{x^2}{\\nu} \\right)^{-(\\frac{\\nu+1}{2})}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\tnormal_distribution<value_type> norm;\n\t\tchi_squared_distribution<value_type> chi(dist_.degrees_of_freedom());\n\t\treturn\t::dcs::math::stats::rand(norm, rng)\n\t\t\t\t/ ::std::sqrt(\n\t\t\t\t\t\t::dcs::math::stats::rand(chi, rng)\n\t\t\t\t\t\t/ dist_.degrees_of_freedom()\n\t\t\t\t\t);\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * A \\c normal random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, size_t n)\n\t{\n\t\t::std::vector<support_type> rnds(n);\n\n\t\tfor ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(rand(rng));\n\t\t}\n\n\t\treturn rnds;\n\t}\n//@}TODO\n\n\n\tpublic: support_type degrees_of_freedom() const\n\t{\n\t\treturn dist_.degrees_of_freedom();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn support_type(0);\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn support_type(1);\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\tprivate: ::boost::math::students_t_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n    typename CharT,\n    typename CharTraitsT,\n    typename RealT,\n    typename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, students_t_distribution<RealT,PolicyT> const& dist)\n{\n    return os << \"StudentT(\"\n              << \"df=\" <<  dist.degrees_of_freedom()\n              << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_STUDENTS_T_HPP\n", "meta": {"hexsha": "d7354047db1599714ede95567d3fe61927b93476", "size": 4770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/students_t.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/students_t.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/students_t.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.6480446927, "max_line_length": 148, "alphanum_fraction": 0.7073375262, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768108626046, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5997981475759129}}
{"text": "/**\n * \\file TanFilter.cpp\n */\n\n#include \"TanFilter.h\"\n\n#include <cassert>\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  TanFilter<DataType_>::TanFilter(int nb_channels)\n  :Parent(nb_channels, nb_channels), coeff(1)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  TanFilter<DataType_>::~TanFilter()\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void TanFilter<DataType_>::setup()\n  {\n    coeff = boost::math::constants::pi<DataType_>() / input_sampling_rate;\n  }\n  \n  template<typename DataType_>\n  void TanFilter<DataType_>::process_impl(int64_t size) const\n  {\n    for(int channel = 0; channel < nb_input_ports; ++channel)\n    {\n      const DataType* ATK_RESTRICT input = converted_inputs[channel];\n      DataType* ATK_RESTRICT output = outputs[channel];\n      for(int64_t i = 0; i < size; ++i)\n      {\n        *(output++) = static_cast<DataType>(tan(*(input++) * coeff));\n      }\n    }\n  }\n  \n  template class TanFilter<float>;\n  template class TanFilter<double>;\n}\n", "meta": {"hexsha": "a0c3c224a17a4ecd4cae05f45c0c095c386c78ae", "size": 1041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/TanFilter.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/TanFilter.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/TanFilter.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": 20.82, "max_line_length": 74, "alphanum_fraction": 0.6589817483, "num_tokens": 262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5997981390754363}}
{"text": "#include \"incidencematrices.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <array>\n#include <memory>\n\nnamespace IncidenceMatrices {\n\n/** @brief Create the mesh consisting of a triangle and quadrilateral\n *         from the exercise sheet.\n * @return Shared pointer to the hybrid2d mesh.\n */\nstd::shared_ptr<lf::mesh::Mesh> createDemoMesh() {\n  // builder for a hybrid mesh in a world of dimension 2\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Add points\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 0});    // (0)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 0});    // (1)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 1});    // (2)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 1});    // (3)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0.5, 1});  // (4)\n\n  // Add the triangle\n  // First set the coordinates of its nodes:\n  Eigen::MatrixXd nodesOfTria(2, 3);\n  nodesOfTria << 1, 1, 0.5, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kTria(),  // we want a triangle\n      std::array<lf::mesh::Mesh::size_type, 3>{\n          {1, 2, 4}},  // indices of the nodes\n      std::make_unique<lf::geometry::TriaO1>(nodesOfTria));  // node coords\n\n  // Add the quadrilateral\n  Eigen::MatrixXd nodesOfQuad(2, 4);\n  nodesOfQuad << 0, 1, 0.5, 0, 0, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kQuad(),\n      std::array<lf::mesh::Mesh::size_type, 4>{{0, 1, 4, 3}},\n      std::make_unique<lf::geometry::QuadO1>(nodesOfQuad));\n\n  std::shared_ptr<lf::mesh::Mesh> demoMesh_p = mesh_factory_ptr->Build();\n\n  return demoMesh_p;\n}\n\n/** @brief Compute the edge-vertex incidence matrix G for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The edge-vertex incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<int> computeEdgeVertexIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store edge-vertex incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> G;\n\n#if SOLUTION\n  // Mesh::NumEntities(unsigned codim) returns the number of elements\n  // with given codimension. Codim(Edge) = 1, Codim(Node) = 2.\n  const lf::mesh::Mesh::size_type numEdges = mesh.NumEntities(1),\n                                  numNodes = mesh.NumEntities(2);\n  // Following the demo for the reserve()-initialising the sparse matrix given\n  // in the exercise sheet. From (2.1a) we know that G has exactly 2 entries\n  // per row.\n  G = Eigen::SparseMatrix<int, Eigen::RowMajor>(numEdges, numNodes);\n  G.reserve(Eigen::VectorXi::Constant(numEdges, 2));\n\n  // To compute G efficiently we iterate over all edges and check the index\n  // of the nodes at its end. This is the efficient way to do the assembly,\n  // introduced as \"distribute scheme\" in class. We cannot iterative over\n  // vertices, because LehrFEM++ does not allow to visit the edges\n  // adjacent to a vertex\n  for (const lf::mesh::Entity *edge : mesh.Entities(1)) {\n    // Get index of this edge\n    lf::mesh::Mesh::size_type edgeIdx = mesh.Index(*edge);\n    // Get the nodes and their indices.\n    // Note, that seen from the edges the nodes have codim 1, not 2,\n    // hence we call SubEntities(1). This is a relative codimension!\n    auto nodes = edge->SubEntities(1);\n    lf::mesh::Mesh::size_type firstNodeIdx = mesh.Index(*nodes[0]);\n    lf::mesh::Mesh::size_type lastNodeIdx = mesh.Index(*nodes[1]);\n    // Add the matrix entries according to the definition\n    G.coeffRef(edgeIdx, firstNodeIdx) += 1;\n    G.coeffRef(edgeIdx, lastNodeIdx) -= 1;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return G;\n}\n/* SAM_LISTING_END_1 */\n\n/** @brief Compute the cell-edge incidence matrix D for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The cell-edge incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<int> computeCellEdgeIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store cell-edge incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> D;\n\n#if SOLUTION\n  // Mesh::NumEntities(unsigned codim) returns the number of elements\n  // with given codimension. Codim(Edge) = 0, Codim(Node) = 1.\n  const lf::mesh::Mesh::size_type numCells = mesh.NumEntities(0),\n                                  numEdges = mesh.NumEntities(1);\n  // Following the demo for the reserve()-initialising the sparse matrix given\n  // in the exercise sheet. From (2.1a) we know that D has at most 4 entries\n  // per row.\n  D = Eigen::SparseMatrix<int, Eigen::RowMajor>(numCells, numEdges);\n  D.reserve(Eigen::VectorXi::Constant(numCells, 4));\n\n  // To compute D efficiently we iterate over all cells and check the\n  // orientations (+1 or -1, same as in the definition of the matrix D)\n  // of its edges. For this we may use RelativeOrientations().\n  for (const lf::mesh::Entity *cell : mesh.Entities(0)) {\n    // Get cell index\n    lf::mesh::Mesh::size_type cellIdx = mesh.Index(*cell);\n    // Get edges and their orientations (these already the entries for D!)\n    auto edges = cell->SubEntities(1);\n    auto edgeOrientations = cell->RelativeOrientations();\n\n    // Iterate over both and add to D\n    auto edgeIt = edges.begin();\n    auto orntIt = edgeOrientations.begin();\n    for (; edgeIt != edges.end() && orntIt != edgeOrientations.end();\n         ++edgeIt, ++orntIt) {\n      // Get the edge index and add its orientation to D\n      lf::mesh::Mesh::size_type edgeIdx = mesh.Index(**edgeIt);\n      D.coeffRef(cellIdx, edgeIdx) += lf::mesh::to_sign(*orntIt);\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  return D;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief For a given mesh test if the product of cell-edge and edge-vertex\n *        incidence matrix is zero: D*G == 0?\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *             such as lf::mesh::hybrid2d::Mesh)\n * @return true, if the product is zero and false otherwise\n */\n/* SAM_LISTING_BEGIN_3 */\nbool testZeroIncidenceMatrixProduct(const lf::mesh::Mesh &mesh) {\n  bool isZero = false;\n\n#if SOLUTION\n  Eigen::SparseMatrix<int> G = computeEdgeVertexIncidenceMatrix(mesh),\n                           D = computeCellEdgeIncidenceMatrix(mesh);\n\n  Eigen::SparseMatrix<int> O = D * G;\n  // Possibility 1:\n  // Not prone to roundoff errors, since O is an integer matrix!\n  isZero = O.norm() == 0;\n  // Possibility 2: But this doesn't use the fact that O is sparse.\n  // isZero = Eigen::MatrixXi(O).isZero(0);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return isZero;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace IncidenceMatrices\n", "meta": {"hexsha": "f37241ed01455d3e9f8f65ed12cd4b8f99d8c740", "size": 7043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/IncidenceMatrices/mastersolution/incidencematrices.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/IncidenceMatrices/mastersolution/incidencematrices.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/IncidenceMatrices/mastersolution/incidencematrices.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 37.8655913978, "max_line_length": 78, "alphanum_fraction": 0.6606559705, "num_tokens": 1991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.5997893700018383}}
{"text": "///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file formic/utils/numeric.cpp\n///\n/// \\brief   implementation file for miscellaneous functions related to numbers\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include \"numeric.h\"\n#include \"formic/utils/mpi_interface.h\"\n\n#include <boost/scoped_array.hpp>\n#include <boost/format.hpp>\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   get an offset array used in compounding pairs of distinct indices\n///\n///   For two indices i,j with i < j, we have:    compound(i,j) = i + ioff[j];\n///\n/// \\param[in]       n        desired length of the array\n/// \\param[in,out]   ioff     on exit, the offset array\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nvoid formic::get_pair_ioff(int n, std::vector<int> & ioff) {\n\n  if (ioff.size() != n)\n    ioff.resize(n);\n\n  if ( n <= 0 )\n    return;\n\n  ioff.at(0) = 0;\n  for (int i = 1; i < n; i++)\n    ioff.at(i) = ioff.at(i-1) + i - 1;\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   computes the binomial coefficient\n///\n/// \\param[in]     n        number of things\n/// \\param[in]     m        how many things to take at a time\n///\n/// \\return the number of ways n things can be taken m at a time\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nint formic::binom_coeff(int n, int m) {\n  if (n < 0 || m < 0 || m > n) return 0;\n  double retval = 1.0;\n  while (m > 0) retval = ( retval * (n--) ) / (m--);\n  return int(retval+0.5);\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   Returns the number of solutions to the equation\n///          x(1) + x(2) + ... + x(n) = r\n///          when the variables x(i) are constrained to be\n///          integers in the range (0, 1, 2, ..., k)\n///\n/// \\param[in]     n        number of variables\n/// \\param[in]     r        sum of variables\n/// \\param[in]     k        range of each variable\n/// \\param[out]    work     integer workspace, either null or size >= k+1\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nint formic::n_integer_solutions(const int n, const int r, const int k, int * work) {\n\n  assert( n >= 0 );\n  assert( r >= 0 );\n  assert( k >= 0 );\n\n  // if requested, dynamically allocate the work space\n  boost::scoped_array<int> dynamic_work;\n  if (work == 0) {\n    dynamic_work.reset( new int[k+1] );\n    work = dynamic_work.get();\n  }\n\n  // initialize an array to hold the number of variables having each allowed value\n  int * const n_with_value = work;\n  work += (k+1);\n  for (int i = 0; i <= k; i++)\n    n_with_value[i] = 0;\n\n  // initialize the return value\n  int retval = 0;\n\n  // Loop over all possible distributions of variables among the values.\n  // Note that we do not directly track of how many variables are equal to zero,\n  // as this is known by how many variables take on other values.\n  while (true) {\n\n    // compute the number of nonzero variables\n    int n_nonzero = 0;\n    for (int i = 1; i <= k; i++)\n      n_nonzero += n_with_value[i];\n\n    // compute the sum of the variables\n    int sum = 0;\n    for (int i = 1; i <= k; i++)\n      sum += i * n_with_value[i];\n\n    // if this distribution solves the equation, count how many ways it can occur\n    if (sum == r && n_nonzero <= n) {\n\n      // determine how many variables are nonzero\n      int t = 0;\n      for (int i = 1; i <= k; i++)\n        t += n_with_value[i];\n\n      // count how many ways the variables can satisfy this distribution\n      int occurrences = formic::binom_coeff(n, t);\n      for (int i = 1; i < k; i++) {\n        occurrences *= formic::binom_coeff(t, n_with_value[i]);\n        t -= n_with_value[i]; // t is now equal to the number of variables greater than i\n      }\n\n      // record how many ways the variables satisfy this distribution\n      retval += occurrences;\n\n    }\n\n    // increment to the next distribution of variables\n    int p;\n    for (p = k; p > 0; p--)\n      if (++n_with_value[p] > n)\n        n_with_value[p] = 0;\n      else\n        break;\n\n    // stop iterating if all distributions have been processed\n    if (p == 0) break;\n\n  }\n\n  // return the result\n  return retval;\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   formats a real number into a string\n///\n/// \\param[in]     f        the formatting string used by boost::format\n/// \\param[in]     value    the number to be formatted\n///\n/// \\return the string containing the formatted number\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nstd::string formic::format_number(const std::string & f, const double value) {\n  return (boost::format(f) % value).str();\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   formats a complex number into a string\n///\n/// \\param[in]     f        the formatting string used by boost::format\n/// \\param[in]     value    the number to be formatted\n///\n/// \\return the string containing the formatted number\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nstd::string formic::format_number(const std::string & f, const std::complex<double> value) {\n  std::string retval;\n  retval.append(\"( \");\n  retval.append( (boost::format(f) % value.real()).str() );\n  retval.append(\", \");\n  retval.append( (boost::format(f) % value.imag()).str() );\n  retval.append(\" )\");\n  return retval;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   computes the unbiased estimate of a ratio of means:  <f>_p / <g>_p  in which the\n///          numerator and denominator values are sampled from the same probability distribution p\n///\n/// \\param[in]     n        the number of samples\n/// \\param[in]     p        the probability weight for each sample\n/// \\param[in]     f        the numerator samples\n/// \\param[in]     g        the denominator samples\n/// \\param[out]    r        on exit, the estimate of the ratio <f>_p / <g>_p\n/// \\param[out]    v        on exit, the estimate of the variance in the ratio\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nvoid formic::unbiased_ratio_of_means(const int n, const double * const p, const double * const f, const double * const g, double & r, double & v) {\n\n  // compute the normalization, the numerator and denominator means, the means of the squares, and the mean of the products\n  double nm = 0.0; // normalization constant\n  double mf = 0.0; // mean of numerator\n  double mg = 0.0; // mean of denominator\n  double sf = 0.0; // mean of the square of the numerator terms\n  double sg = 0.0; // mean of the square of the denominator terms\n  double mp = 0.0; // mean of the product of numerator times denominator\n  for (int i = 0; i < n; i++) {\n    nm += p[i];\n    double x = p[i] * f[i];\n    mf += x;\n    sf += x * f[i];\n    mp += x * g[i];\n    x = p[i] * g[i];\n    mg += x;\n    sg += x * g[i];\n  }\n  mf /= nm;\n  mg /= nm;\n  sf /= nm;\n  sg /= nm;\n  mp /= nm;\n\n  // compute the numerator and denominator variances and the covariance\n  const double vf = ( sf - mf * mf ) * double(n) / double(n-1);\n  const double vg = ( sg - mg * mg ) * double(n) / double(n-1);\n  const double cv = ( mp - mf * mg ) * double(n) / double(n-1);\n\n  // compute the unbiased estimate of the ratio of means\n  r = ( mf / mg ) / ( 1.0 + ( vg / mg / mg - cv / mf / mg ) / double(n) );\n\n  // compute the unbiased estimate of the variance of the ratio of means\n  v = ( mf * mf / mg / mg / double(n) ) * ( vf / mf / mf + vg / mg / mg - 2.0 * cv / mf / mg );\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief   computes the unbiased estimate of a ratio of means:  <f>_p / <g>_p  in which the\n///          numerator and denominator values are sampled from the same probability distribution p\n///          and samples are combined across all processors\n///\n/// \\param[in]     n        the number of samples on this process\n/// \\param[in]     p        the probability weight for each sample\n/// \\param[in]     f        the numerator samples\n/// \\param[in]     g        the denominator samples\n/// \\param[out]    r        on exit, the estimate of the ratio <f>_p / <g>_p\n/// \\param[out]    v        on exit, the estimate of the variance in the ratio\n///\n///////////////////////////////////////////////////////////////////////////////////////////////////\nvoid formic::mpi_unbiased_ratio_of_means(const int n, const double * const p, const double * const f, const double * const g, double & r, double & v) {\n\n  // compute the normalization, the numerator and denominator means, the means of the squares, and the mean of the products\n  double y[7];\n  y[0] = 0.0; // normalization constant\n  y[1] = 0.0; // mean of numerator\n  y[2] = 0.0; // mean of denominator\n  y[3] = 0.0; // mean of the square of the numerator terms\n  y[4] = 0.0; // mean of the square of the denominator terms\n  y[5] = 0.0; // mean of the product of numerator times denominator\n  y[6] = double(n); // number of samples\n  for (int i = 0; i < n; i++) {\n    y[0] += p[i];\n    double x = p[i] * f[i];\n    y[1] += x;\n    y[3] += x * f[i];\n    y[5] += x * g[i];\n    x = p[i] * g[i];\n    y[2] += x;\n    y[4] += x * g[i];\n  }\n  double z[7];\n  formic::mpi::allreduce(&y[0], &z[0], 7, MPI_SUM);\n  const double mf = z[1] / z[0]; // mean of numerator\n  const double mg = z[2] / z[0]; // mean of denominator\n  const double sf = z[3] / z[0]; // mean of the square of the numerator terms\n  const double sg = z[4] / z[0]; // mean of the square of the denominator terms\n  const double mp = z[5] / z[0]; // mean of the product of numerator times denominator\n  const double ns = z[6];        // number of samples\n\n  // compute the numerator and denominator variances and the covariance\n  const double vf = ( sf - mf * mf ) * ns / ( ns - 1.0 );\n  const double vg = ( sg - mg * mg ) * ns / ( ns - 1.0 );\n  const double cv = ( mp - mf * mg ) * ns / ( ns - 1.0 );\n\n  // compute the unbiased estimate of the ratio of means\n  r = ( mf / mg ) / ( 1.0 + ( vg / mg / mg - cv / mf / mg ) / ns );\n\n  // compute the unbiased estimate of the variance of the ratio of means\n  v = ( mf * mf / mg / mg ) * ( vf / mf / mf + vg / mg / mg - 2.0 * cv / mf / mg );\n\n}\n", "meta": {"hexsha": "049012874b5c0ed79eb3bc2ab7d38447b3026926", "size": 10736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/formic/utils/numeric.cpp", "max_stars_repo_name": "eugeneswalker/qmcpack", "max_stars_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/formic/utils/numeric.cpp", "max_issues_repo_name": "eugeneswalker/qmcpack", "max_issues_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/formic/utils/numeric.cpp", "max_forks_repo_name": "williamfgc/qmcpack", "max_forks_repo_head_hexsha": "732b473841e7823a21ab55ff397eed059f0f2e96", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7581227437, "max_line_length": 151, "alphanum_fraction": 0.506147541, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.5997881448983959}}
{"text": "/**\n * @file mean_shift.hpp\n * @author Shangtong Zhang\n *\n * Mean Shift clustering\n */\n\n#ifndef MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP\n#define MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP\n\n#include <mlpack/core.hpp>\n#include <mlpack/core/kernels/gaussian_kernel.hpp>\n#include <mlpack/core/kernels/kernel_traits.hpp>\n#include <mlpack/core/metrics/lmetric.hpp>\n#include <boost/utility.hpp>\n\nnamespace mlpack {\nnamespace meanshift /** Mean shift clustering. */ {\n\n/**\n * This class implements mean shift clustering.  For each point in dataset,\n * apply mean shift algorithm until maximum iterations or convergence.  Then\n * remove duplicate centroids.\n *\n * A simple example of how to run mean shift clustering is shown below.\n *\n * @code\n * extern arma::mat data; // Dataset we want to run mean shift on.\n * arma::Col<size_t> assignments; // Cluster assignments.\n * arma::mat centroids; // Cluster centroids.\n *\n * MeanShift<> meanShift();\n * meanShift.Cluster(dataset, assignments, centroids);\n * @endcode\n *\n * @tparam UseKernel Use kernel or mean to calculate new centroid.\n *         If false, KernelType will be ignored.\n * @tparam KernelType The kernel to use.\n * @tparam MatType The type of matrix the data is stored in.\n */\ntemplate<bool UseKernel = false,\n         typename KernelType = kernel::GaussianKernel,\n         typename MatType = arma::mat>\nclass MeanShift\n{\n public:\n  /**\n   * Create a mean shift object and set the parameters which mean shift will be\n   * run with.\n   *\n   * @param radius If distance of two centroids is less than it, one will be\n   *      removed. If this value isn't positive, an estimation will be given\n   *      when clustering.\n   * @param maxIterations Maximum number of iterations allowed before giving up\n   *      iterations will terminate.\n   * @param kernel Optional KernelType object.\n   */\n  MeanShift(const double radius = 0,\n            const size_t maxIterations = 1000,\n            const KernelType kernel = KernelType());\n\n  /**\n   * Give an estimation of radius based on given dataset.\n   *\n   * @param data Dataset for estimation.\n   * @param ratio Percentage of dataset to use for nearest neighbor search.\n   */\n  double EstimateRadius(const MatType& data, const double ratio = 0.2);\n\n  /**\n   * Perform mean shift clustering on the data, returning a list of cluster\n   * assignments and centroids.\n   *\n   * @tparam MatType Type of matrix.\n   * @param data Dataset to cluster.\n   * @param assignments Vector to store cluster assignments in.\n   * @param centroids Matrix in which centroids are stored.\n   */\n  void Cluster(const MatType& data,\n               arma::Col<size_t>& assignments,\n               arma::mat& centroids,\n               bool useSeeds = true);\n\n  //! Get the maximum number of iterations.\n  size_t MaxIterations() const { return maxIterations; }\n  //! Set the maximum number of iterations.\n  size_t& MaxIterations() { return maxIterations; }\n\n  //! Get the radius.\n  double Radius() const { return radius; }\n  //! Set the radius.\n  void Radius(double radius);\n\n  //! Get the kernel.\n  const KernelType& Kernel() const { return kernel; }\n  //! Modify the kernel.\n  KernelType& Kernel() { return kernel; }\n\n private:\n  /**\n   * To speed up, we can generate some seeds from data set and use\n   * them as initial centroids rather than all the points in the data set.  The\n   * basic idea here is that we will place our points into hypercube bins of\n   * side length binSize, and any bins that contain fewer than minFreq points\n   * will be removed as possible seeds.  Usually, 1 is a sufficient parameter\n   * for minFreq, and the bin size can be set equal to the estimated radius.\n   *\n   * @param data The reference data set.\n   * @param binSize Width of hypercube bins.\n   * @param minFreq Minimum number of points in bin.\n   * @param seed Matrix to store generated seeds in.\n   */\n  void GenSeeds(const MatType& data,\n                const double binSize,\n                const int minFreq,\n                MatType& seeds);\n\n  /**\n   * Use kernel to calculate new centroid given dataset and valid neighbors.\n   *\n   * @param data The whole dataset\n   * @param neighbors Valid neighbors\n   * @param distances Distances to neighbors\n   # @param centroid Store calculated centroid\n   */\n  template<bool ApplyKernel = UseKernel>\n  typename std::enable_if<ApplyKernel, bool>::type\n  CalculateCentroid(const MatType& data,\n                    const std::vector<size_t>& neighbors,\n                    const std::vector<double>& distances,\n                    arma::colvec& centroid);\n\n  /**\n   * Use mean to calculate new centroid given dataset and valid neighbors.\n   *\n   * @param data The whole dataset\n   * @param neighbors Valid neighbors\n   * @param distances Distances to neighbors\n   # @param centroid Store calculated centroid\n   */\n  template<bool ApplyKernel = UseKernel>\n  typename std::enable_if<!ApplyKernel, bool>::type\n  CalculateCentroid(const MatType& data,\n                    const std::vector<size_t>& neighbors,\n                    const std::vector<double>&, /*unused*/\n                    arma::colvec& centroid);\n\n  /**\n   * If distance of two centroids is less than radius, one will be removed.\n   * Points with distance to current centroid less than radius will be used\n   * to calculate new centroid.\n   */\n  double radius;\n\n  //! Maximum number of iterations before giving up.\n  size_t maxIterations;\n\n  //! Instantiated kernel.\n  KernelType kernel;\n};\n\n} // namespace meanshift\n} // namespace mlpack\n\n// Include implementation.\n#include \"mean_shift_impl.hpp\"\n\n#endif // MLPACK_METHODS_MEAN_SHIFT_MEAN_SHIFT_HPP\n", "meta": {"hexsha": "d7607d0f0f7f7acd64935bfd7520a34b4f59dd94", "size": 5614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/mean_shift/mean_shift.hpp", "max_stars_repo_name": "jmlevin7878/mlpack", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:12.000Z", "max_issues_repo_path": "src/mlpack/methods/mean_shift/mean_shift.hpp", "max_issues_repo_name": "jmlevin7878/mlpack", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/mean_shift/mean_shift.hpp", "max_forks_repo_name": "jmlevin7878/mlpack", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2189349112, "max_line_length": 79, "alphanum_fraction": 0.6864980406, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5995753410799478}}
{"text": "#include \"TriMesh.h\"\n#include <Eigen/Core>\n\nnamespace geomlib {\nTriMesh::TriMesh(const Eigen::MatrixXf& vertices, const Eigen::MatrixXi& faces)\n    : vertices_{vertices}, faces_{faces} {}\n\nconst Eigen::MatrixXf& TriMesh::GetVertexNormals() const {\n  if (!vertex_normals_) {\n    CalculateVertexNormals();\n  }\n  return *vertex_normals_;\n}\n\nconst Eigen::MatrixXf& TriMesh::GetFaceNormals() const {\n  if (!face_normals_) {\n    CalculateFaceNormals();\n  }\n  return *face_normals_;\n}\n\nconst Eigen::VectorXf& TriMesh::GetFaceAreas() const {\n  if (!face_areas_) {\n    CalculateFaceAreas();\n  }\n  return *face_areas_;\n}\n\nconst Eigen::MatrixXf& TriMesh::GetCotangentWeights() const {\n  if (!cotangent_weights_) {\n    CalculateCotangentWeights();\n  }\n  return *cotangent_weights_;\n}\n\nconst Eigen::VectorXf& TriMesh::GetVertexAreas() const {\n  if (!vertex_areas_) {\n    CalculateVertexAreas();\n  }\n  return *vertex_areas_;\n}\n\nconst Eigen::MatrixXi& TriMesh::GetAdjacentFacePairs() const {\n  if (!adjacent_face_pairs_) {\n    BuildAdjacentFacePairs();\n  }\n  return *adjacent_face_pairs_;\n}\n\nvoid TriMesh::CalculateVertexNormals() const {\n  CalculateFaceNormals();\n  vertex_normals_ = std::make_unique<Eigen::MatrixXf>(\n      Eigen::MatrixXf::Zero(GetNumVertices(), 3));\n  for (int i = 0; i < static_cast<int>(GetNumFaces()); i++) {\n    int v1 = faces_(i, 0);\n    int v2 = faces_(i, 1);\n    int v3 = faces_(i, 2);\n    Eigen::Vector3f n = face_normals_->row(i);\n    vertex_normals_->row(v1) += n;\n    vertex_normals_->row(v2) += n;\n    vertex_normals_->row(v3) += n;\n  }\n\n  for (int i = 0; i < static_cast<int>(GetNumVertices()); i++) {\n    vertex_normals_->row(i).normalize();\n  }\n}\n\nvoid TriMesh::CalculateFaceNormals() const {\n  face_normals_ = std::make_unique<Eigen::MatrixXf>(GetNumFaces(), 3);\n  for (int i = 0; i < GetNumFaces(); i++) {\n    int v1 = faces_(i, 0);\n    int v2 = faces_(i, 1);\n    int v3 = faces_(i, 2);\n    Eigen::Vector3f p1 = vertices_.row(v1);\n    Eigen::Vector3f p2 = vertices_.row(v2);\n    Eigen::Vector3f p3 = vertices_.row(v3);\n    face_normals_->row(i) = (p2 - p1).cross(p3 - p1);\n  }\n}\n\nvoid TriMesh::CalculateFaceAreas() const {\n  auto& face_normals = GetFaceNormals();\n  face_areas_ = std::make_unique<Eigen::VectorXf>(GetNumFaces());\n  for (int k = 0; k < GetNumFaces(); k++) {\n    (*face_areas_)(k) = face_normals.row(k).norm() / 2;\n  }\n}\n\nvoid TriMesh::CalculateCotangentWeights() const {\n  Eigen::MatrixXf p1(faces_.rows(), 3);\n  Eigen::MatrixXf p2(faces_.rows(), 3);\n  Eigen::MatrixXf p3(faces_.rows(), 3);\n  for (int i = 0; i < faces_.rows(); i++) {\n    p1.row(i) = vertices_.row(faces_(i, 0));\n    p2.row(i) = vertices_.row(faces_(i, 1));\n    p3.row(i) = vertices_.row(faces_(i, 2));\n  }\n\n  Eigen::VectorXf l1 = (p2 - p3).rowwise().norm();\n  Eigen::VectorXf l2 = (p1 - p3).rowwise().norm();\n  Eigen::VectorXf l3 = (p1 - p2).rowwise().norm();\n  Eigen::VectorXf s = (l1 + l2 + l3) / 2;\n  Eigen::VectorXf r = (s - l1)\n                          .cwiseProduct(s - l2)\n                          .cwiseProduct(s - l3)\n                          .cwiseQuotient(s)\n                          .cwiseSqrt();\n\n  auto fn = [&](const Eigen::VectorXf& l) -> Eigen::VectorXf {\n    return ((s - l).cwiseAbs2() - r.cwiseAbs2())\n        .cwiseQuotient(2 * (s - l).cwiseProduct(r));\n  };\n\n  cotangent_weights_ = std::make_unique<Eigen::MatrixXf>(GetNumFaces(), 3);\n  cotangent_weights_->col(0) = fn(l1);\n  cotangent_weights_->col(1) = fn(l2);\n  cotangent_weights_->col(2) = fn(l3);\n}\n\nvoid TriMesh::CalculateVertexAreas() const {\n  vertex_areas_ = std::make_unique<Eigen::VectorXf>(\n      Eigen::VectorXf::Zero(GetNumVertices()));\n  for (int k = 0; k < GetNumFaces(); k++) {\n    Eigen::Vector3f n = face_normals_->row(k);\n    float a = n.norm() / 6;\n    for (int i = 0; i < 3; i++) {\n      (*vertex_areas_)(faces_(k, i)) += a;\n    }\n  }\n}\n\nvoid TriMesh::BuildAdjacentFacePairs() const {\n  std::vector<Vector2i> face_pairs;\n  std::unordered_map<Vector2i, int, Vector2iHasher> edge_neighbor_;\n\n  for (int i = 0; i < GetNumFaces(); i++) {\n    for (int k = 0; k < 3; k++) {\n      int u = faces_(i, k);\n      int v = faces_(i, (k + 1) % 3);\n\n      if (edge_neighbor_.count({v, u})) {\n        face_pairs.emplace_back(i, edge_neighbor_[{v, u}]);\n      } else {\n        edge_neighbor_.emplace(Vector2i{u, v}, i);\n      }\n    }\n  }\n\n  adjacent_face_pairs_ =\n      std::make_unique<Eigen::MatrixXi>(ArrayVector2iToMatrixXi(face_pairs));\n}\n}  // namespace geomlib\n", "meta": {"hexsha": "200fd2339043b669e30fb43bd8b306b048d45658", "size": 4456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geomlib/geomlib/TriMesh.cpp", "max_stars_repo_name": "KaiSut0/interactive-hex-meshing", "max_stars_repo_head_hexsha": "187c926610ca5617f569405c23ab5a62b189e100", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 129.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T17:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T08:59:02.000Z", "max_issues_repo_path": "geomlib/geomlib/TriMesh.cpp", "max_issues_repo_name": "KaiSut0/interactive-hex-meshing", "max_issues_repo_head_hexsha": "187c926610ca5617f569405c23ab5a62b189e100", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-10-03T07:30:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T16:05:41.000Z", "max_forks_repo_path": "geomlib/geomlib/TriMesh.cpp", "max_forks_repo_name": "KaiSut0/interactive-hex-meshing", "max_forks_repo_head_hexsha": "187c926610ca5617f569405c23ab5a62b189e100", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-09-08T11:29:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:39:50.000Z", "avg_line_length": 28.9350649351, "max_line_length": 79, "alphanum_fraction": 0.6214093357, "num_tokens": 1416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.599575313326893}}
{"text": "#include <iostream>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n\nusing namespace std;\n\nclass Node {\n public:\n  Node(string name) : name_(name) { }\n  virtual ~Node() { cout << \"Node destructor\" << endl; }\n  void AddParent(Node *parent) {\n    parents_.push_back(parent);\n    parent->children_.push_back(this);\n    parent->pindex_.push_back(parents_.size() - 1);\n  }\n  Node *Parent(size_t i) const { return parents_[i]; }\n  Node *Child(size_t i) const { return children_[i]; }\n  size_t NumParents() const { return parents_.size(); }\n  size_t NumChildren() const { return children_.size(); }\n  string name() const { return name_; }\n  size_t pindex(size_t i) const { return pindex_[i]; }\n  void NullifyParent(size_t i) { parents_[i] = nullptr; }\n  void DeleteAscendantsAndSelf() { DeleteAscendantsAndThis(this); }\n  void DeleteAscendantsAndThis(Node *node) {\n    for (int i = node->NumParents() - 1; i >= 0; --i) {\n      if (node->Parent(i) != nullptr) {\n        DeleteAscendantsAndThis(node->Parent(i));\n      }\n    }\n    cout << \"Nullifying \" << node->name() << \" from its children: \";\n    for (size_t i = 0; i < node->NumChildren(); ++i) {\n      cout <<  node->Child(i)->name() << \" \";\n      node->Child(i)->NullifyParent(node->pindex(i));\n    }\n    cout << endl;\n\n    delete node;\n  }\n  vector<size_t> pindex_;\n protected:\n  string name_;\n  vector<Node *> parents_;\n  vector<Node *> children_;\n\n};\n\nclass Variable: public Node {\n public:\n  Variable(string name) : Node(name) { }\n  ~Variable() { }\n  Variable *Parent(size_t i) {\n    return static_cast<Variable *>(Node::Parent(i));\n  }\n  virtual void forward() = 0;\n  virtual void backward() = 0;\n  size_t NumRows() { return gradient_.rows(); }\n  size_t NumColumns() { return gradient_.cols(); }\n  virtual Eigen::MatrixXd *value() { return &value_; }\n  virtual Eigen::MatrixXd *gradient() { return &gradient_; }\n  void make_final() { gradient_ = Eigen::MatrixXd::Ones(1, 1); }\n protected:\n  Eigen::MatrixXd value_;\n  Eigen::MatrixXd gradient_;\n};\n\nstruct Input: public Variable {\n  Input(string name, Eigen::MatrixXd *input) : Variable(name) {\n    input_ = input;\n    gradient_ = Eigen::MatrixXd::Zero(input->rows(), input->cols());\n  }\n  ~Input() { cout << \"Deleting \" << name_ << endl; }\n  Eigen::MatrixXd *value() override { return input_; }\n  void forward() override { }\n  void backward() override { }\n protected:\n  Eigen::MatrixXd *input_;\n};\n\nstruct Add: public Variable {\n  Add(string name, Variable *X, Variable *Y) : Variable(name) {\n    AddParent(X);\n    AddParent(Y);\n    gradient_ = Eigen::MatrixXd::Zero(X->NumRows(), X->NumColumns());\n\n  }\n  ~Add() { cout << \"Deleting \" << name_ << endl; }\n  void forward() override {\n    Parent(0)->forward();\n    Parent(1)->forward();\n    value_ = *Parent(0)->value() + *Parent(1)->value();\n  }\n  void backward() override {\n    cout << name_ << \" has parents \" << Parent(0)->name() << \" and \"\n         << Parent(1)->name() << \", adding \"  << gradient_\n         << \" to each\" << endl;\n    *Parent(0)->gradient() += gradient_;  // dA = dC\n    *Parent(1)->gradient() += gradient_;  // dB = dC\n    cout << \"recursively calling backward from \" << name_\n         << \" on its first parent \" << Parent(0)->name() << endl;\n    Parent(0)->backward();\n    if (Parent(0) != Parent(1)) {\n    cout << \"recursively calling backward from \" << name_\n         << \" on its second parent \" << Parent(1)->name() << endl;\n      Parent(1)->backward();\n    }\n  }\n};\n\nint main() {\n  Eigen::MatrixXd x_value(1, 1);\n  x_value << 1.0;\n  Eigen::MatrixXd y_value(1, 1);\n  y_value << 2.0;\n  Input *x = new Input(\"x\", &x_value);\n  Input *y = new Input(\"y\", &y_value);\n  Add *z = new Add(\"z\", x, y);\n\n  Add *q = new Add(\"q\", z, x);\n  Add *l = new Add(\"l\", q, q);\n  l->make_final();\n  l->forward();\n  l->backward();\n  cout << endl;\n  cout << \"x = \" << *x->value() << endl;\n  cout << \"dx = \" << *x->gradient() << endl;\n  cout << endl;\n  cout << \"y = \" << *y->value() << endl;\n  cout << \"dy = \" << *y->gradient() << endl;\n  cout << endl;\n  cout << \"z = \" << *z->value() << endl;\n  cout << \"dz = \" << *z->gradient() << endl;\n  cout << endl;\n  cout << \"q = \" << *q->value() << endl;\n  cout << \"dq = \" << *q->gradient() << endl;\n  cout << endl;\n  cout << \"l = \" << *l->value() << endl;\n  cout << \"dl = \" << *l->gradient() << endl;\n  cout << endl;\n\n  x_value += 0.1 * *x->gradient();\n  y_value += 0.1 * *y->gradient();\n\n  l->DeleteAscendantsAndSelf();\n\n  cout << endl;\n  cout << \"x_value is updated to \" << x_value << endl;\n  cout << \"y_value is updated to \" << y_value << endl;\n  cout << endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "9422bb7b5ba88f362b9b336fba5b9689439a9caf", "size": 4605, "ext": "cc", "lang": "C++", "max_stars_repo_path": "notes/variable_prototype_stale/main.cc", "max_stars_repo_name": "karlstratos/mesosphere", "max_stars_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T22:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T22:18:39.000Z", "max_issues_repo_path": "notes/variable_prototype_stale/main.cc", "max_issues_repo_name": "karlstratos/stratosphere_nn", "max_issues_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/variable_prototype_stale/main.cc", "max_forks_repo_name": "karlstratos/stratosphere_nn", "max_forks_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_forks_repo_licenses": ["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.5192307692, "max_line_length": 69, "alphanum_fraction": 0.5800217155, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5995753086955504}}
{"text": "#include <iostream>\n#include <ratio>\n#include <boost/type_index.hpp>\nusing namespace std;\nusing boost::typeindex::type_id_with_cvr;\n\n// 如果使用 string 保留单位名称会导致自定义字符串字面值出错，因为 string 有一个 non_trivial 的构造函数\ntemplate <class Rep, class Rat = std::ratio<1>>\nstruct Distance{\n\tusing Ratio = Rat;\n\tRep dis;\n};\n\ntemplate <class Rep, class Rat = std::ratio<1>>\nauto operator+(Distance<Rep, Rat> lhs, Distance<Rep, Rat> rhs){\n\treturn Distance<Rep, Rat>{lhs.dis + rhs.dis, };\n}\n\ntemplate <class Rep, class Rat = std::ratio<1>>\nauto operator-(Distance<Rep, Rat> lhs, Distance<Rep, Rat> rhs){\n\treturn Distance<Rep, Rat>{lhs.dis - rhs.dis};\n}\n\ntemplate <class Rep>\nusing kilometers = Distance<Rep, std::kilo>;\n\ntemplate <class Rep>\nusing meters = Distance<Rep>;\n\ntemplate <class Rep>\nusing decimeters = Distance<Rep, std::deci>;\n\ntemplate <class Rep>\nusing centimeters = Distance<Rep, std::centi>;\n\ntemplate <class Rep>\nusing miles = Distance<Rep, std::ratio<1609344,1000>>;\n\ntemplate <class Rep>\nusing yards = Distance<Rep, std::ratio<9144, 10000>>;\n\ntemplate <class Rep>\nusing feet = Distance<Rep, std::ratio<3048, 10000>>;\n\ntemplate <class Rep>\nusing inches = Distance<Rep, std::ratio<354, 10000>>;\n\n\nconstexpr kilometers<long double> operator\"\"_km(long double dist){\n\treturn kilometers<long double>{dist};\n}\n\nconstexpr meters<long double> operator\"\"_m(long double dist){\n\treturn meters<long double>{dist};\n}\n\nconstexpr decimeters<long double> operator\"\"_dm(long double dist){\n\treturn decimeters<long double>{dist};\n}\n\nconstexpr centimeters<long double> operator\"\"_cm(long double dist){\n\treturn centimeters<long double>{dist};\n}\n\nconstexpr miles<long double> operator\"\"_mi(long double dist){\n\treturn miles<long double>{dist};\n}\n\nconstexpr yards<long double> operator\"\"_yd(long double dist){\n\treturn yards<long double>{dist};\n}\n\nconstexpr feet<long double> operator\"\"_ft(long double dist){\n\treturn feet<long double>{dist};\n}\n\nconstexpr inches<long double> operator\"\"_in(long double dist){\n\treturn inches<long double>{dist};\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, kilometers<Rep> len){\n\treturn os << len.dis << \"km\";\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, meters<Rep> len){\n\treturn os << len.dis << \"m\";\n}\n\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, decimeters<Rep> len){\n\treturn os << len.dis << \"dm\";\n}\n\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, centimeters<Rep> len){\n\treturn os << len.dis << \"cm\";\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, miles<Rep> len){\n\treturn os << len.dis << \"mi\";\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, yards<Rep> len){\n\treturn os << len.dis << \"yd\";\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, feet<Rep> len){\n\treturn os << len.dis << \"ft\";\n}\n\ntemplate <class Rep>\nostream& operator<<(ostream& os, inches<Rep> len){\n\treturn os << len.dis << \"in\";\n}\n\n\ntemplate <class To, class From>\nconstexpr To unit_cast(From from){\n\tusing to_ratio = typename To::Ratio;\n\tusing from_ratio = typename From::Ratio;\n\tusing cast_ratio = std::ratio_divide<from_ratio, to_ratio>;\n\treturn To{from.dis * cast_ratio::num / cast_ratio::den};\n}\n\n\nint main(int argc, char const *argv[])\n{\n\tauto kms_1 = 10.24_km;\n\tauto kms_2 = 10.24_km;\n\tauto kms_3 = kms_1 + kms_2;\n\tauto mil_1 = 1.0_mi;\n\tauto mil_2 = 1.0_mi;\n\tauto mil_3 = mil_1 + mil_2;\n\tcout << type_id_with_cvr<decltype(kms_1)>().pretty_name() << endl;\n\tcout << type_id_with_cvr<decltype(mil_1)>().pretty_name() << endl;\n\tcout << kms_3 << endl;\n\tcout << mil_3 << endl;\n\tcout << unit_cast<kilometers<long double>>(mil_3) << endl;\n\tcout << unit_cast<meters<long double>>(mil_3) << endl;\n\tcout << unit_cast<decimeters<long double>>(mil_3) << endl;\n\tcout << unit_cast<centimeters<long double>>(mil_3) << endl;\n\tcout << unit_cast<miles<long double>>(kms_3) << endl;\n\tcout << unit_cast<yards<long double>>(kms_3) << endl;\n\tcout << unit_cast<feet<long double>>(kms_3) << endl;\n\tcout << unit_cast<inches<long double>>(kms_3) << endl;\n\tcout << unit_cast<yards<long double>>(1.0_mi) << endl;\n\treturn 0;\n}", "meta": {"hexsha": "b933937817bfcb35a7c474d3b2dc1f849a60b6f7", "size": 4040, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Function_Programming/Unit_Subsystem/Unit_Subsystem.cc", "max_stars_repo_name": "Phoenix500526/CodingDojo", "max_stars_repo_head_hexsha": "8214720b51b3f70ce2e518eb795054c7bbcec9c9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Function_Programming/Unit_Subsystem/Unit_Subsystem.cc", "max_issues_repo_name": "Phoenix500526/CodingDojo", "max_issues_repo_head_hexsha": "8214720b51b3f70ce2e518eb795054c7bbcec9c9", "max_issues_repo_licenses": ["Apache-2.0"], "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_Programming/Unit_Subsystem/Unit_Subsystem.cc", "max_forks_repo_name": "Phoenix500526/CodingDojo", "max_forks_repo_head_hexsha": "8214720b51b3f70ce2e518eb795054c7bbcec9c9", "max_forks_repo_licenses": ["Apache-2.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.064516129, "max_line_length": 67, "alphanum_fraction": 0.7017326733, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5995703670125541}}
{"text": "/** \\file gauss_distribution.hpp \n    \\brief Gaussian probability distribution */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n\n#ifndef __GAUSS_DISTRIBUTION_HPP__\n#define __GAUSS_DISTRIBUTION_HPP__\n\n#include <boost/math/distributions/normal.hpp> \n#include \"prob_distribution.hpp\"\n\nnamespace bayesopt\n{\n\n  class GaussianDistribution: public ProbabilityDistribution\n  {\n  public:\n    GaussianDistribution(randEngine& eng);\n    virtual ~GaussianDistribution();\n\n    /** \n     * \\brief Sets the mean and std of the distribution\n     */\n    void setMeanAndStd(double mean, double std)\n    { mean_ = mean; std_ = std; };\n\n    /** \n     * \\brief Probability density function\n     * @param x query point\n     * @return probability\n     */\n    double pdf(double x) \n    {\n      x = (x - mean_) / std_;\n      return boost::math::pdf(d_,x); \n    };\n\n    /** \n     * \\brief Expected Improvement algorithm for minimization\n     * @param min  minimum value found\n     * @param g exponent (used for annealing)\n     *\n     * @return negative value of the expected improvement\n     */\n    double negativeExpectedImprovement(double min, size_t g);\n\n    /** \n     * \\brief Lower confindence bound. Can be seen as the inverse of the Upper \n     * confidence bound\n     * @param beta std coefficient (used for annealing)\n     * @return value of the lower confidence bound\n     */\n    double lowerConfidenceBound(double beta);\n\n    /** \n     * Probability of improvement algorithm for minimization\n     * @param min  minimum value found\n     * @param epsilon minimum improvement margin\n     * \n     * @return negative value of the probability of improvement\n     */\n    double negativeProbabilityOfImprovement(double min,\n\t\t\t\t\t    double epsilon);\n\n    /** \n     * Sample outcome acording to the marginal distribution at the query point.\n     * @return outcome\n     */\n    double sample_query();\n\n    double getMean() { return mean_; };\n    double getStd()  { return std_; };\n\n\n  private:\n    boost::math::normal d_;\n    double mean_;\n    double std_;\n  };\n\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "bac66b859dd937484de19091392d84e8f8b3262a", "size": 2992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/gauss_distribution.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/include/gauss_distribution.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/include/gauss_distribution.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 28.7692307692, "max_line_length": 79, "alphanum_fraction": 0.6497326203, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5995414527549995}}
{"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/sigma_point.h>\n#include <BayesFilters/directional_statistics.h>\n\n#include <Eigen/SVD>\n\nusing namespace bfl;\nusing namespace bfl::directional_statistics;\nusing namespace bfl::sigma_point;\nusing namespace Eigen;\n\n\nbfl::sigma_point::UTWeight::UTWeight\n(\n    std::size_t n,\n    const double alpha,\n    const double beta,\n    const double kappa\n) :\n    mean((2 * n) + 1),\n    covariance((2 * n) + 1)\n{\n    unscented_weights(n, alpha, beta, kappa, mean, covariance, c);\n}\n\n\nvoid bfl::sigma_point::unscented_weights\n(\n    const std::size_t n,\n    const double alpha,\n    const double beta,\n    const double kappa,\n    Ref<VectorXd> weight_mean,\n    Ref<VectorXd> weight_covariance,\n    double& c\n)\n{\n    double lambda = std::pow(alpha, 2.0) * (n + kappa) - n;\n\n    for (int j = 0; j < ((2 * n) + 1); ++j)\n    {\n        if (j == 0)\n        {\n            weight_mean(j)       = lambda / (n + lambda);\n            weight_covariance(j) = lambda / (n + lambda) + (1 - std::pow(alpha, 2.0) + beta);\n        }\n        else\n        {\n            weight_mean(j)       = 1 / (2 * (n + lambda));\n            weight_covariance(j) = weight_mean(j);\n        }\n    }\n\n    c = n + lambda;\n}\n\n\nMatrixXd bfl::sigma_point::sigma_point(const GaussianMixture& state, const double c)\n{\n    MatrixXd sigma_points(state.dim, ((state.dim * 2) + 1) * state.components);\n\n    for (std::size_t i = 0; i < state.components; i++)\n    {\n        JacobiSVD<MatrixXd> svd = state.covariance(i).jacobiSvd(ComputeThinU);\n\n        MatrixXd A = svd.matrixU() * svd.singularValues().cwiseSqrt().asDiagonal();\n\n        Ref<MatrixXd> sp = sigma_points.middleCols(((state.dim * 2) + 1) * i, ((state.dim * 2) + 1));\n\n        sp << VectorXd::Zero(state.dim), std::sqrt(c) * A, -std::sqrt(c) * A;\n\n        if (state.dim_linear > 0)\n            sp.topRows(state.dim_linear).colwise() += state.mean(i).topRows(state.dim_linear);\n\n        if (state.dim_circular > 0)\n            sp.middleRows(state.dim_linear, state.dim_circular) = directional_add(sp.middleRows(state.dim_linear, state.dim_circular), state.mean(i).middleRows(state.dim_linear, state.dim_circular));\n\n        if (state.dim_noise > 0)\n            sp.bottomRows(state.dim_noise).colwise() += state.mean(i).bottomRows(state.dim_noise);\n    }\n\n    return sigma_points;\n}\n\n\nstd::tuple<bool, GaussianMixture, MatrixXd> bfl::sigma_point::unscented_transform\n(\n    const GaussianMixture& input,\n    const UTWeight& weight,\n    FunctionEvaluation function\n)\n{\n    /* Sample sigma points. */\n    MatrixXd input_sigma_points = sigma_point::sigma_point(input, weight.c);\n\n    /* Propagate sigma points */\n    Data fun_data;\n    bool valid_fun_data;\n    bfl::sigma_point::OutputSize output_size;\n    std::tie(valid_fun_data, fun_data, output_size) = function(input_sigma_points);\n\n    /* Stop here if function evaluation failed. */\n    if (!valid_fun_data)\n        return std::make_tuple(false, GaussianMixture(), MatrixXd(0, 0));\n\n    /* For now casting Data to MatrixXd. */\n    MatrixXd prop_sigma_points = bfl::any::any_cast<MatrixXd&&>(std::move(fun_data));\n\n    /* Initialize transformed gaussian. */\n    GaussianMixture output(input.components, output_size.first, output_size.second);\n\n    /* Initialize cross covariance matrix. */\n    MatrixXd cross_covariance(input.dim, output.dim * output.components);\n\n    /* Process all the components of the mixture. */\n    std::size_t base = ((input.dim * 2) + 1);\n    for (std::size_t i = 0; i < input.components; i++)\n    {\n        Ref<MatrixXd> input_sigma_points_i = input_sigma_points.middleCols(base * i, base);\n        Ref<MatrixXd> prop_sigma_points_i = prop_sigma_points.middleCols(base * i, base);\n\n        /* Evaluate the mean. */\n        output.mean(i).topRows(output_size.first).noalias() = prop_sigma_points_i.topRows(output_size.first) * weight.mean;\n        output.mean(i).bottomRows(output_size.second) = directional_mean(prop_sigma_points_i.bottomRows(output_size.second), weight.mean);\n\n        /* Evaluate the covariance. */\n        prop_sigma_points_i.topRows(output_size.first).colwise() -= output.mean(i).topRows(output_size.first);\n        prop_sigma_points_i.bottomRows(output_size.second) = directional_sub(prop_sigma_points_i.bottomRows(output_size.second), output.mean(i).bottomRows(output_size.second));\n        output.covariance(i).noalias() = prop_sigma_points_i * weight.covariance.asDiagonal() * prop_sigma_points_i.transpose();\n\n        /* Evaluate the input-output cross covariance matrix\n           (noise components in the input are not considered). */\n        Ref<MatrixXd> cross_covariance_i = cross_covariance.middleCols(output.dim * i, output.dim);\n        input_sigma_points_i.topRows(input.dim_linear).colwise() -= input.mean(i).topRows(input.dim_linear);\n        input_sigma_points_i.middleRows(input.dim_linear, input.dim_circular) = directional_sub(input_sigma_points_i.middleRows(input.dim_linear, input.dim_circular), input.mean(i).middleRows(input.dim_linear, input.dim_circular));\n        cross_covariance_i.noalias() = input_sigma_points_i.topRows(input.dim_linear + input.dim_circular) * weight.covariance.asDiagonal() * prop_sigma_points_i.transpose();\n    }\n\n    return std::make_tuple(true, output, cross_covariance);\n}\n\n\nstd::pair<GaussianMixture, MatrixXd> bfl::sigma_point::unscented_transform\n(\n    const GaussianMixture& state,\n    const UTWeight& weight,\n    StateModel& state_model\n)\n{\n    FunctionEvaluation f = [&state_model](const Ref<const MatrixXd>& state)\n                           {\n                               MatrixXd tmp(state.rows(), state.cols());\n\n                               state_model.motion(state, tmp);\n\n                               return std::make_tuple(true, std::move(tmp), state_model.getOutputSize());\n                           };\n    MatrixXd cross_covariance;\n    GaussianMixture output;\n    std::tie(std::ignore, output, cross_covariance) = unscented_transform(state, weight, f);\n\n    return std::make_pair(output, cross_covariance);\n}\n\n\nstd::pair<GaussianMixture, MatrixXd> bfl::sigma_point::unscented_transform\n(\n    const GaussianMixture& state,\n    const UTWeight& weight,\n    AdditiveStateModel& state_model\n)\n{\n    FunctionEvaluation f = [&state_model](const Ref<const MatrixXd>& state)\n                           {\n                               MatrixXd tmp(state.rows(), state.cols());\n\n                               state_model.propagate(state, tmp);\n\n                               return std::make_tuple(true, std::move(tmp), state_model.getOutputSize());\n                           };\n\n    MatrixXd cross_covariance;\n    GaussianMixture output;\n    std::tie(std::ignore, output, cross_covariance) = unscented_transform(state, weight, f);\n\n    /* In the additive case the covariance matrix is augmented with the noise\n       covariance matrix. */\n    for(std::size_t i = 0; i < state.components; i++)\n        output.covariance(i) += state_model.getNoiseCovarianceMatrix();\n\n    return std::make_pair(output, cross_covariance);\n}\n\n\nstd::tuple<bool, GaussianMixture, MatrixXd> bfl::sigma_point::unscented_transform\n(\n    const GaussianMixture& state,\n    const UTWeight& weight,\n    MeasurementModel& meas_model\n)\n{\n    FunctionEvaluation f = [&meas_model](const Ref<const MatrixXd>& state)\n                           {\n                               bool valid_prediction;\n                               bfl::Data prediction;\n\n                               std::tie(valid_prediction, prediction) = meas_model.predictedMeasure(state);\n\n                               return std::make_tuple(valid_prediction, std::move(prediction), meas_model.getOutputSize());\n                           };\n\n    bool valid;\n    MatrixXd cross_covariance;\n    GaussianMixture output;\n    std::tie(valid, output, cross_covariance) = unscented_transform(state, weight, f);\n\n    return std::make_tuple(valid, output, cross_covariance);\n}\n\n\nstd::tuple<bool, GaussianMixture, MatrixXd> bfl::sigma_point::unscented_transform\n(\n    const GaussianMixture& state,\n    const UTWeight& weight,\n    AdditiveMeasurementModel& meas_model\n)\n{\n    FunctionEvaluation f = [&meas_model](const Ref<const MatrixXd>& state)\n                           {\n                               bool valid_prediction;\n                               bfl::Data prediction;\n\n                               std::tie(valid_prediction, prediction) = meas_model.predictedMeasure(state);\n\n                               return std::make_tuple(valid_prediction, std::move(prediction), meas_model.getOutputSize());\n                           };\n\n    bool valid;\n    MatrixXd cross_covariance;\n    GaussianMixture output;\n    std::tie(valid, output, cross_covariance) = unscented_transform(state, weight, f);\n\n    /* In the additive case the covariance matrix is augmented with the noise\n       covariance matrix. */\n    MatrixXd noise_cov;\n    std::tie(std::ignore, noise_cov) = meas_model.getNoiseCovarianceMatrix();\n    for (std::size_t i = 0; i < state.components; i++)\n        output.covariance(i) += noise_cov;\n\n    return std::make_tuple(valid, output, cross_covariance);\n}\n", "meta": {"hexsha": "4f540fa26e397e9e6a2afaa3bcea8426983d8910", "size": 9320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/sigma_point.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/sigma_point.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/sigma_point.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": 36.1240310078, "max_line_length": 231, "alphanum_fraction": 0.6491416309, "num_tokens": 2167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5994848558817113}}
{"text": "#include<iostream>\n#include<stdio.h>\n#include<vector>\n#include<cmath>\n#include \"ray.h\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <fstream>\nusing namespace std;\nusing namespace Eigen;\n\n\nVector3d operator*(double s, const Vector3d &v) {\n\treturn Vector3d(s*v(0), s*v(1), s*v(2));\n}\n\n//Triangle with verticies pos, pos + p and pos + q.\nclass triangle: public shape {\n\tVector3d p, q, normal;\t\n\tpublic:\n\tVector3d pos;\n\ttriangle(Vector3d np, Vector3d nq, Vector3d npos, colour &ncol, surface &s):\n\t\tp(np), q(nq), pos(npos) {\n\t\tcol = ncol;\n\t\tsurf = s;\n\t\tnormal = p.cross(q);\n\t}\n\t\n\tVector3d get_normal(const Vector3d ignore) const {\n\t\treturn normal;\n\t}\n\t\n\t//Moller-Trumbore intersection algorithm\n\tdouble intersect(ray r) {\n\t\tVector3d vec, T;\n\t\tdouble det, u, v, t;\n\t\tvec = r.dir.cross(q);\n\t\tdet = p.dot(vec);\n\t\t//std::cout << \"det = \" << det << std::endl;\n\t\t//If det is zero then ray in plane of triangle\n\t\tif(det < INTERSECT_EPSILON && det > -INTERSECT_EPSILON) return 0.0;\n\t\t//Get ray from pos to ray origin\n\t\tT = r.origin - pos;\n\t\tu = T.dot(vec)/det;\n\t\t//Test u\n\t\tif(u < 0 || u > 1.0) return 0.0;\n\t\t//and v (+u)\n\t\tvec = T.cross(p);\n\t\tv = r.dir.dot(vec)/det;\n\t\tif(v < 0 || v + u > 1.0) return 0.0;\n\t\t//Intersect at origin + t*dir\n\t\tt = q.dot(vec)/det;\n\t\t//Check we're not behind the ray origin\n\t\tif(t < INTERSECT_EPSILON) return 0.0;\n\t\t//return ray intersect parameter: point = Origin + t*dir\n\t\treturn t;\n\t}\n\t \n};\n\nclass sphere: public shape {\n\tpublic:\n\tVector3d pos;\n\tdouble radius;\n\tsphere(double nr, Vector3d np, colour &ncol, surface &s):\n\t\tpos(np), radius(nr){\n\t\tcol = ncol;\n\t\tsurf = s;\n\t}\n\t\n\tVector3d get_normal(const Vector3d p) const {\n\t\treturn p - pos;\n\t}\n\n\tdouble intersect(ray r) {\n\t\tdouble a, b, c, d, dsq, s1, s2;\n\t\tc = r.origin.dot(r.origin) + pos.dot(pos) - 2*r.origin.dot(pos) - radius*radius;\n\t\tb = 2 * r.dir.dot(r.origin - pos);\n\t\ta = r.dir.dot(r.dir);\n\t\tif(a < INTERSECT_EPSILON) {\n\t\t\tfprintf(stderr, \"Warn: sphere::intersect: a < ITERSECT_EPSILON\\n\");\n\t\t\treturn 0.0;\n\t\t}\n\t\tdsq = b*b - 4*a*c;\n\t\tif(dsq <= 0) {\n\t\t\treturn 0;\n\t\t}\n\t\td = std::sqrt(dsq);\n\t\ts1 = (-b+d)/(2*a);\n\t\ts2 = (-b-d)/(2*a);\n\t\tif(s1 < s2) {\n\t\t\tif(s1 > INTERSECT_EPSILON) {\n\t\t\t\treturn s1;\n\t\t\t}\n\t\t}\n\t\tif(s2 > INTERSECT_EPSILON) {\n\t\t\treturn s2;\n\t\t} else {\n\t\t\treturn s1 > INTERSECT_EPSILON ? s1 : 0.0;\n\t\t}\n\t}\n\t\n};\n\n\n\nstd::vector<shape*>* getMeshWorld() {\n\tstd::vector<shape*> *w = new std::vector<shape*>();\n\t\n\tcolour red  = colour(255, 0, 0, 1.0);\n\tcolour blue = colour(0, 0, 255, 1.0);\n\tcolour green = colour(0, 255.0, 0, 1.0);\n\n\tsurface shiny;\n\tshiny.reflection = 0.8;\n\tshiny.specular = 1.0;\n\tshiny.diffusion = 0.9;\n\n\t// w->push_back((shape*) (new sphere(2, Vector3d(0, 3, 15), red, shiny)));\n\n\t\tifstream fin ;\n\t\t\t\t\t    // fin.open(\"/Users/Rachit/Documents/iqra_cg/tracer3/bumpy_cube.off\");\n\t\t\t\t\t    fin.open(\"/Users/Rachit/Documents/iqra_cg/tracer3/bunny.off\");\n\t\t\t\t\t    \n\t\t\t\t\t    int nrows,nrows2;\n\t\t\t\t\t    string output;\n\t\t\t\t\t    if(fin.is_open())\n\t\t\t\t\t    {\n\t\t\t\t\t        fin >> output;\n\t\t\t\t\t        fin >> output;\n\t\t\t\t\t        nrows=std::stoi(output);\n\t\t\t\t\t        fin >> output;\n\t\t\t\t\t        nrows2 = std::stoi(output);\n\t\t\t\t\t        fin >> output;\n\n\t\t\t\t\t    }\n\n\t\t\t\t\t    Eigen::ArrayXXf X = Eigen::ArrayXXf::Zero(nrows,3);\n\t\t\t\t\t    Eigen::ArrayXXd Y = Eigen::ArrayXXd::Zero(nrows2,4);\n\n\t\t\t\t\t    if (fin.is_open())\n\t\t\t\t\t    {\n\t\t\t\t\t        for (int row = 0; row < nrows; row++)\n\t\t\t\t\t            for (int col = 0; col < 3; col++)\n\t\t\t\t\t            {\n\t\t\t\t\t                float item = 0.0;\n\t\t\t\t\t                fin >> item;\n\t\t\t\t\t                X(row, col) = item;\n\t\t\t\t\t            }\n\n\t\t\t\t\t    }\n\t\t\t\t\t   // cerr << \"X = \" << endl << X << endl;\n\t\t\t\t\t    if (fin.is_open())\n\t\t\t\t\t    {\n\t\t\t\t\t        for (int row = 0; row < nrows2; row++)\n\t\t\t\t\t            for (int col = 0; col < 4; col++)\n\t\t\t\t\t            {\n\t\t\t\t\t                float item = 0.0;\n\t\t\t\t\t                fin >> item;\n\t\t\t\t\t                Y(row, col) = item;\n\t\t\t\t\t            }\n\t\t\t\t\t        fin.close();\n\t\t\t\t\t    }\n\t\t\t\t\t    // cerr<<\"Y =\"<< endl << Y <<endl;\n\n\t\t\t\t\t    for(unsigned k=0 ; k < Y.rows();k++) {\n\t\t\t\t\t    \t// if(k%100==0)\n\t\t\t\t\t    \t// cerr<<\"at row-->\"<<k<<endl;\n\t\t\t\t\t    \tw->push_back((shape*) (new triangle(\n\t\t\t\t\t    \t\t   Vector3d(X(Y(k, 1), 0), X(Y(k, 1), 1), X(Y(k, 1), 2)),\n                Vector3d(X(Y(k, 2), 0), X(Y(k, 2), 1), X(Y(k, 2), 2)),\n                Vector3d(X(Y(k, 3), 0), X(Y(k, 3), 1), X(Y(k, 3), 2)),\n                red,shiny\n\t\t\t\t\t    \t\t)));\n\n\n}\n\n\n\n\n\n\n\t\n\n\t//One sphere\n\t// w->push_back((shape*) (new sphere(3, Vector3d(5, 5, 10), red, shiny)));\n\t// w->push_back((shape*) (new sphere(1.5, Vector3d(0, 0, -5), red, shiny)));\n\treturn w;\n\n}\n\n\n\nstd::vector<shape*>* partAWorld() {\n\tstd::vector<shape*> *w = new std::vector<shape*>();\n\t\n\tcolour red  = colour(255, 0, 0, 1.0);\n\tcolour blue = colour(0, 0, 255, 1.0);\n\tcolour green = colour(0, 255.0, 0, 1.0);\n\n\n\t//SETTING ONLY DIFFUSE as using imple Lambertian shading\n\tsurface lambert;\n\tlambert.reflection = 0.0;\n\tlambert.specular = 0.0;\n\tlambert.diffusion = 0.9;\n\n\tw->push_back((shape*) (new sphere(5, Vector3d(0, 3, 15), red, lambert)));\n\tw->push_back((shape*) (new sphere(5, Vector3d(10, 10, 15), red, lambert)));\n\n\t// w->push_back((shape*) (new sphere(3, Vector3d(5, 5, 10), red, shiny)));\n\t// w->push_back((shape*) (new sphere(1.5, Vector3d(0, 0, -5), red, shiny)));\n\treturn w;\n\n}\nstd::vector<shape*>* partBWorld() {\n\tstd::vector<shape*> *w = new std::vector<shape*>();\n\t\n\tcolour red  = colour(255, 0, 0, 1.0);\n\tcolour blue = colour(0, 0, 255, 1.0);\n\tcolour green = colour(0, 255.0, 0, 1.0);\n\n\n\t//SETTING ONLY DIFFUSE as using imple Lambertian shading\n\tsurface lambert;\n\tlambert.reflection = 0.0;\n\tlambert.specular = 0.0;\n\tlambert.diffusion = 0.9;\n\t//Diffuse+specular\n\tsurface specular;\n\tspecular.reflection = 0.0;\n\tspecular.specular = 1.0;\n\tspecular.diffusion = 0.9;\n\n\tw->push_back((shape*) (new sphere(10, Vector3d(0, 3, 15), red, lambert)));\n\tw->push_back((shape*) (new sphere(5, Vector3d(10, 10, 15), blue, specular)));\n\n\t// w->push_back((shape*) (new sphere(3, Vector3d(5, 5, 10), red, shiny)));\n\t// w->push_back((shape*) (new sphere(1.5, Vector3d(0, 0, -5), red, shiny)));\n\treturn w;\n\n}\nstd::vector<shape*>* partCWorld() {\n\tstd::vector<shape*> *w = new std::vector<shape*>();\n\t\n\tcolour red  = colour(255, 0, 0, 1.0);\n\tcolour blue = colour(0, 0, 255, 1.0);\n\tcolour green = colour(0, 255.0, 0, 1.0);\n\n\n\t//SETTING ONLY DIFFUSE as using imple Lambertian shading\n\tsurface lambert;\n\tlambert.reflection = 0.0;\n\tlambert.specular = 0.0;\n\tlambert.diffusion = 0.9;\n\t//Diffuse+specular\n\tsurface specular;\n\tspecular.reflection = 0.0;\n\tspecular.specular = 1.0;\n\tspecular.diffusion = 0.9;\n\n\tw->push_back((shape*) (new sphere(10, Vector3d(0, 3, 15), red, lambert)));\n\tw->push_back((shape*) (new sphere(5, Vector3d(10, 10, 15), blue, specular)));\n\n\t// w->push_back((shape*) (new sphere(3, Vector3d(5, 5, 10), red, shiny)));\n\t// w->push_back((shape*) (new sphere(1.5, Vector3d(0, 0, -5), red, shiny)));\n\treturn w;\n\n}\nstd::vector<shape*>* partEWorld(int n_spheres) {\n\t\n\tsurface shiny;\n\tshiny.reflection = 0.4;\n\tshiny.specular = 1.0;\n\tshiny.diffusion = 0.9;\n\tstd::vector<shape*> *w = new std::vector<shape*>();\n\tint i, j, k;\n\tfor(i=0; i<3; i++) {\n\tfor(j=0; j<3; j++) {\n\tfor(k=0; k<3; k++) {\n\t\tif(n_spheres > 0) {\n\t\t\tcolour c = colour(i*127.5, 255-j*127.5, ((int) (127.5+(k*127.5)))%382);\n\t\t\tw->push_back((shape*) (new sphere(1, Vector3d(i*4-5.5, j*4-6, k*4+14), c, shiny)));\n\t\t\tn_spheres -= 1;\n\t\t}\n\t}\n\t}\n\t}\n\treturn w;\n\n}\n\n\n\nvoid freeWorld(std::vector<shape*> *w) {\n\twhile(w->size() > 0) {\n\t\tdelete (w->back());\n\t\tw->pop_back();\n\t}\n\tdelete w;\n}\n\nstd::vector<light*>* getLights() {\n\tstd::vector<light*> *l = new std::vector<light*>();\n\tl->push_back(new light(Vector3d(15, 15, 5), colour(255, 255, 255)));\n\treturn l;\n}\nstd::vector<light*>* partALights() {\n\tstd::vector<light*> *l = new std::vector<light*>();\n\tl->push_back(new light(Vector3d(15, 15, 5), colour(255, 255, 255)));\n\treturn l;\n}\nstd::vector<light*>* partBLights() {\n\tstd::vector<light*> *l = new std::vector<light*>();\n\tl->push_back(new light(Vector3d(15, 15, 5), colour(255, 255, 255)));\n\tl->push_back(new light(Vector3d(-15, -15, 5), colour(255, 255, 255)));\n\t\t\n\treturn l;\n}\nstd::vector<light*>* partELights() {\n\tstd::vector<light*> *l = new std::vector<light*>();\n\tl->push_back(new light(Vector3d(-5, 3, 2), colour(255, 255, 255)));\n\tl->push_back(new light(Vector3d(15, 15, 5), colour(255, 255, 255)));\n\t\t\n\treturn l;\n}\n\nvoid freeLights(std::vector<light*> *l) {\n\twhile(l->size() > 0) {\n\t\tdelete (l->back());\n\t\tl->pop_back();\n\t}\n\tdelete l;\n}\n\n", "meta": {"hexsha": "0c449967876b9868124a72e93c57d3ccdc6b69b6", "size": 8524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "world.cpp", "max_stars_repo_name": "rachitmehrotra1/ray-tracer", "max_stars_repo_head_hexsha": "5820d5ba5d9783b428ccbc6383a608752cce3ef9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "world.cpp", "max_issues_repo_name": "rachitmehrotra1/ray-tracer", "max_issues_repo_head_hexsha": "5820d5ba5d9783b428ccbc6383a608752cce3ef9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "world.cpp", "max_forks_repo_name": "rachitmehrotra1/ray-tracer", "max_forks_repo_head_hexsha": "5820d5ba5d9783b428ccbc6383a608752cce3ef9", "max_forks_repo_licenses": ["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.293768546, "max_line_length": 86, "alphanum_fraction": 0.564406382, "num_tokens": 3030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5994848481123354}}
{"text": "#ifndef CPPMATH_MATRIX_PSEUDOINVERSESVD_HPP_\n#define CPPMATH_MATRIX_PSEUDOINVERSESVD_HPP_\n\n#include <Eigen/SVD>\n\nnamespace cppmath\n{\n    /**\n     * Calculates a SVD-based pseudo inverse matrix.\n     * See:\n     * - http://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#The_general_case_and_the_SVD_method\n     * - http://eigen.tuxfamily.org/index.php?title=FAQ#Is_there_a_method_to_compute_the_.28Moore-Penrose.29_pseudo_inverse_.3F\n     *\n     * \\author cpieloth\n     * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n     */\n    template< typename T >\n    class PseudoInverseSVD: private Eigen::JacobiSVD< T >\n    {\n    public:\n        /**\n         * Constructor.\n         *\n         * \\param matrix Matrix to compute the pseudo inverse from.\n         * \\param pinvThreshold Threshold to keep value as zero/nonzero (default: 1.0e-6).\n         */\n        PseudoInverseSVD( const T& matrix, float threshold = 1.0e-6 );\n\n        virtual ~PseudoInverseSVD();\n\n        /**\n         * Computes the pseudo inverse.\n         * The pseudo inverse is internally stored for further calculations.\n         *\n         * \\return Reference to the internally stored pseudo inverse matrix.\n         */\n        const T& compute();\n\n        /**\n         * Computes the pseudo inverse.\n         *\n         * \\param pinvmat Holds the pseudo inverse matrix after computation.\n         */\n        void compute( T* const pinvmat ) const;\n\n        /**\n         * Multiplies the pseudo inverse with a matrix.\n         * The pseudo inverse is internally stored for further calculations.\n         *\n         * \\param m Matrix\n         * \\return Result of pinv*m\n         */\n        T operator*( const T& m );\n\n        /**\n         *  Multiplies the pseudo inverse with a matrix.\n         *\n         * \\param m Matrix\n         * \\return Result of pinv*m\n         */\n        T operator*( const T& m ) const;\n\n    private:\n        bool m_hasInverse; /**< Indicates if the internal inverse matrix is available. */\n\n        T m_inverse; /**< Stores a computed inverse matrix. */\n\n        const float m_threshold;\n    };\n} /* namespace cppmath */\n\n// Load the implementation\n#include \"PseudoInverseSVD-impl.hpp\"\n\n#endif  // CPPMATH_MATRIX_PSEUDOINVERSESVD_HPP_\n", "meta": {"hexsha": "68422252cd017cab563547e261dde3b7ac367b23", "size": 2275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/matrix/PseudoInverseSVD.hpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/matrix/PseudoInverseSVD.hpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/matrix/PseudoInverseSVD.hpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9342105263, "max_line_length": 127, "alphanum_fraction": 0.6184615385, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.5993900455424357}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2016 - 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: Timo Heister, Clemson University, 2016 \n */ \n\n\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// 下面这块出场代码与 step-40 相同，可以在PETSc和Trilinos之间切换。\n\n#include <deal.II/lac/generic_linear_algebra.h> \n\n/* #define FORCE_USE_OF_TRILINOS */ \n\n\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/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/solver_gmres.h> \n#include <deal.II/lac/solver_minres.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.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/grid/grid_generator.h> \n#include <deal.II/grid/manifold_lib.h> \n#include <deal.II/grid/grid_tools.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_values.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \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#include <deal.II/base/utilities.h> \n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/index_set.h> \n#include <deal.II/lac/sparsity_tools.h> \n#include <deal.II/distributed/tria.h> \n#include <deal.II/distributed/grid_refinement.h> \n\n#include <cmath> \n#include <fstream> \n#include <iostream> \n\nnamespace Step55 \n{ \n  using namespace dealii; \n// @sect3{Linear solvers and preconditioners}  \n\n// 我们需要一些辅助类来表示我们在介绍中描述的求解器策略。\n\n  namespace LinearSolvers \n  { \n\n// 这个类暴露了通过函数 InverseMatrix::vmult(). 应用给定矩阵的逆的动作，在内部，逆不是显式形成的。相反，一个带有CG的线性求解器被执行。这个类扩展了 step-22 中的InverseMatrix类，增加了一个指定预处理程序的选项，并允许在vmult函数中使用不同的矢量类型。\n\n    template <class Matrix, class Preconditioner> \n    class InverseMatrix : public Subscriptor \n    { \n    public: \n      InverseMatrix(const Matrix &m, const Preconditioner &preconditioner); \n\n      template <typename VectorType> \n      void vmult(VectorType &dst, const VectorType &src) const; \n\n    private: \n      const SmartPointer<const Matrix> matrix; \n      const Preconditioner &           preconditioner; \n    }; \n\n    template <class Matrix, class Preconditioner> \n    InverseMatrix<Matrix, Preconditioner>::InverseMatrix( \n      const Matrix &        m, \n      const Preconditioner &preconditioner) \n      : matrix(&m) \n      , preconditioner(preconditioner) \n    {} \n\n    template <class Matrix, class Preconditioner> \n    template <typename VectorType> \n    void \n    InverseMatrix<Matrix, Preconditioner>::vmult(VectorType &      dst, \n                                                 const VectorType &src) const \n    { \n      SolverControl solver_control(src.size(), 1e-8 * src.l2_norm()); \n      SolverCG<LA::MPI::Vector> cg(solver_control); \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// 该类是一个简单的2x2矩阵的块状对角线预处理器的模板类。\n\n    template <class PreconditionerA, class PreconditionerS> \n    class BlockDiagonalPreconditioner : public Subscriptor \n    { \n    public: \n      BlockDiagonalPreconditioner(const PreconditionerA &preconditioner_A, \n                                  const PreconditionerS &preconditioner_S); \n\n      void vmult(LA::MPI::BlockVector &      dst, \n                 const LA::MPI::BlockVector &src) const; \n\n    private: \n      const PreconditionerA &preconditioner_A; \n      const PreconditionerS &preconditioner_S; \n    }; \n\n    template <class PreconditionerA, class PreconditionerS> \n    BlockDiagonalPreconditioner<PreconditionerA, PreconditionerS>:: \n      BlockDiagonalPreconditioner(const PreconditionerA &preconditioner_A, \n                                  const PreconditionerS &preconditioner_S) \n      : preconditioner_A(preconditioner_A) \n      , preconditioner_S(preconditioner_S) \n    {} \n\n    template <class PreconditionerA, class PreconditionerS> \n    void BlockDiagonalPreconditioner<PreconditionerA, PreconditionerS>::vmult( \n      LA::MPI::BlockVector &      dst, \n      const LA::MPI::BlockVector &src) const \n    { \n      preconditioner_A.vmult(dst.block(0), src.block(0)); \n      preconditioner_S.vmult(dst.block(1), src.block(1)); \n    } \n\n \n// @sect3{Problem setup}  \n\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 void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  void RightHandSide<dim>::vector_value(const Point<dim> &p, \n                                        Vector<double> &  values) const \n  { \n    const double R_x = p[0]; \n    const double R_y = p[1]; \n\n    const double pi  = numbers::PI; \n    const double pi2 = pi * pi; \n    values[0] = \n      -1.0L / 2.0L * (-2 * sqrt(25.0 + 4 * pi2) + 10.0) * \n        exp(R_x * (-2 * sqrt(25.0 + 4 * pi2) + 10.0)) - \n      0.4 * pi2 * exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * cos(2 * R_y * pi) + \n      0.1 * pow(-sqrt(25.0 + 4 * pi2) + 5.0, 2) * \n        exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * cos(2 * R_y * pi); \n    values[1] = 0.2 * pi * (-sqrt(25.0 + 4 * pi2) + 5.0) * \n                  exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * sin(2 * R_y * pi) - \n                0.05 * pow(-sqrt(25.0 + 4 * pi2) + 5.0, 3) * \n                  exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * sin(2 * R_y * pi) / \n                  pi; \n    values[2] = 0; \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  template <int dim> \n  void ExactSolution<dim>::vector_value(const Point<dim> &p, \n                                        Vector<double> &  values) const \n  { \n    const double R_x = p[0]; \n    const double R_y = p[1]; \n\n    const double pi  = numbers::PI; \n    const double pi2 = pi * pi; \n    values[0] = \n      -exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * cos(2 * R_y * pi) + 1; \n    values[1] = (1.0L / 2.0L) * (-sqrt(25.0 + 4 * pi2) + 5.0) * \n                exp(R_x * (-sqrt(25.0 + 4 * pi2) + 5.0)) * sin(2 * R_y * pi) / \n                pi; \n    values[2] = \n      -1.0L / 2.0L * exp(R_x * (-2 * sqrt(25.0 + 4 * pi2) + 10.0)) - \n      2.0 * \n        (-6538034.74494422 + \n         0.0134758939981709 * exp(4 * sqrt(25.0 + 4 * pi2))) / \n        (-80.0 * exp(3 * sqrt(25.0 + 4 * pi2)) + \n         16.0 * sqrt(25.0 + 4 * pi2) * exp(3 * sqrt(25.0 + 4 * pi2))) - \n      1634508.68623606 * exp(-3.0 * sqrt(25.0 + 4 * pi2)) / \n        (-10.0 + 2.0 * sqrt(25.0 + 4 * pi2)) + \n      (-0.00673794699908547 * exp(sqrt(25.0 + 4 * pi2)) + \n       3269017.37247211 * exp(-3 * sqrt(25.0 + 4 * pi2))) / \n        (-8 * sqrt(25.0 + 4 * pi2) + 40.0) + \n      0.00336897349954273 * exp(1.0 * sqrt(25.0 + 4 * pi2)) / \n        (-10.0 + 2.0 * sqrt(25.0 + 4 * pi2)); \n  } \n\n//  @sect3{The main program}  \n\n// 主类与  step-40  非常相似，只是矩阵和向量现在是块状的，而且我们为拥有的和相关的DoF存储一个  std::vector<IndexSet>  ，而不是一个IndexSet。我们正好有两个IndexSets，一个用于所有速度未知数，一个用于所有压力未知数。\n\n  template <int dim> \n  class StokesProblem \n  { \n  public: \n    StokesProblem(unsigned int velocity_degree); \n\n    void run(); \n\n  private: \n    void make_grid(); \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    unsigned int velocity_degree; \n    double       viscosity; \n    MPI_Comm     mpi_communicator; \n\n    FESystem<dim>                             fe; \n    parallel::distributed::Triangulation<dim> triangulation; \n    DoFHandler<dim>                           dof_handler; \n\n    std::vector<IndexSet> owned_partitioning; \n    std::vector<IndexSet> relevant_partitioning; \n\n    AffineConstraints<double> constraints; \n\n    LA::MPI::BlockSparseMatrix system_matrix; \n    LA::MPI::BlockSparseMatrix preconditioner_matrix; \n    LA::MPI::BlockVector       locally_relevant_solution; \n    LA::MPI::BlockVector       system_rhs; \n\n    ConditionalOStream pcout; \n    TimerOutput        computing_timer; \n  }; \n\n  template <int dim> \n  StokesProblem<dim>::StokesProblem(unsigned int velocity_degree) \n    : velocity_degree(velocity_degree) \n    , viscosity(0.1) \n    , mpi_communicator(MPI_COMM_WORLD) \n    , fe(FE_Q<dim>(velocity_degree), dim, FE_Q<dim>(velocity_degree - 1), 1) \n    , triangulation(mpi_communicator, \n                    typename Triangulation<dim>::MeshSmoothing( \n                      Triangulation<dim>::smoothing_on_refinement | \n                      Triangulation<dim>::smoothing_on_coarsening)) \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\n// Kovasnay流定义在域[-0.5, 1.5]^2上，我们通过将最小和最大值传递给 GridGenerator::hyper_cube. 来创建这个域。\n  template <int dim> \n  void StokesProblem<dim>::make_grid() \n  { \n    GridGenerator::hyper_cube(triangulation, -0.5, 1.5); \n    triangulation.refine_global(3); \n  } \n// @sect3{System Setup}  \n\n// 与 step-40 相比，块矩阵和向量的构造是新的，与 step-22 这样的串行代码相比也是不同的，因为我们需要提供属于我们处理器的行的集合。\n\n  template <int dim> \n  void StokesProblem<dim>::setup_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"setup\"); \n\n    dof_handler.distribute_dofs(fe); \n\n// 将所有的昏暗速度放入0区块，压力放入1区块，然后按区块重新排列未知数。最后计算每块有多少个未知数。\n\n    std::vector<unsigned int> stokes_sub_blocks(dim + 1, 0); \n    stokes_sub_blocks[dim] = 1; \n    DoFRenumbering::component_wise(dof_handler, stokes_sub_blocks); \n\n    const std::vector<types::global_dof_index> dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, stokes_sub_blocks); \n\n    const unsigned int n_u = dofs_per_block[0]; \n    const unsigned int n_p = dofs_per_block[1]; \n\n    pcout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() << \" (\" \n          << n_u << '+' << n_p << ')' << std::endl; \n\n// 我们根据我们想要创建块状矩阵和向量的方式，将本地拥有的和本地相关的DoF的IndexSet分割成两个IndexSets。\n\n    owned_partitioning.resize(2); \n    owned_partitioning[0] = dof_handler.locally_owned_dofs().get_view(0, n_u); \n    owned_partitioning[1] = \n      dof_handler.locally_owned_dofs().get_view(n_u, n_u + n_p); \n\n    IndexSet locally_relevant_dofs; \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n    relevant_partitioning.resize(2); \n    relevant_partitioning[0] = locally_relevant_dofs.get_view(0, n_u); \n    relevant_partitioning[1] = locally_relevant_dofs.get_view(n_u, n_u + n_p); \n\n// 设置边界条件和悬挂节点的约束与  step-40  相同。尽管我们没有任何悬空节点，因为我们只进行全局细化，但把这个函数调用放进去仍然是个好主意，以备以后引入自适应细化。\n\n    { \n      constraints.reinit(locally_relevant_dofs); \n\n      FEValuesExtractors::Vector velocities(0); \n      DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               ExactSolution<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n      constraints.close(); \n    } \n\n// 现在我们根据BlockDynamicSparsityPattern来创建系统矩阵。我们知道我们不会有不同速度分量之间的耦合（因为我们使用的是拉普拉斯而不是变形张量），也不会有压力与其测试函数之间的耦合，所以我们使用一个表来将这个耦合信息传达给  DoFTools::make_sparsity_pattern.  。\n    { \n      system_matrix.clear(); \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::none; \n          else if (c == dim || d == dim || c == d) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      BlockDynamicSparsityPattern dsp(dofs_per_block, dofs_per_block); \n\n      DoFTools::make_sparsity_pattern( \n        dof_handler, coupling, dsp, constraints, false); \n\n      SparsityTools::distribute_sparsity_pattern( \n        dsp, \n        dof_handler.locally_owned_dofs(), \n        mpi_communicator, \n        locally_relevant_dofs); \n\n      system_matrix.reinit(owned_partitioning, dsp, mpi_communicator); \n    } \n\n// 先决条件矩阵有不同的耦合（我们只在1,1块中填入质量矩阵），否则这段代码与上面的system_matrix的构造是相同的。\n\n    { \n      preconditioner_matrix.clear(); \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      BlockDynamicSparsityPattern dsp(dofs_per_block, dofs_per_block); \n\n      DoFTools::make_sparsity_pattern( \n        dof_handler, coupling, dsp, constraints, false); \n      SparsityTools::distribute_sparsity_pattern( \n        dsp, \n        Utilities::MPI::all_gather(mpi_communicator, \n                                   dof_handler.locally_owned_dofs()), \n        mpi_communicator, \n        locally_relevant_dofs); \n      preconditioner_matrix.reinit(owned_partitioning, \n\n// owned_partitioning。\n\n                                   dsp, \n                                   mpi_communicator); \n    } \n\n// 最后，我们以正确的尺寸构建块状向量。带有两个 std::vector<IndexSet> 的函数调用将创建一个重影向量。\n\n    locally_relevant_solution.reinit(owned_partitioning, \n                                     relevant_partitioning, \n                                     mpi_communicator); \n    system_rhs.reinit(owned_partitioning, mpi_communicator); \n  } \n\n//  @sect3{Assembly}  \n\n// 这个函数将系统矩阵、预处理矩阵和右手边集合起来。其代码非常标准。\n\n  template <int dim> \n  void StokesProblem<dim>::assemble_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"assembly\"); \n\n    system_matrix         = 0; \n    preconditioner_matrix = 0; \n    system_rhs            = 0; \n\n    const QGauss<dim> quadrature_formula(velocity_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    FullMatrix<double> cell_matrix2(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(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    std::vector<Tensor<2, dim>> grad_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    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n    const FEValuesExtractors::Vector     velocities(0); \n    const FEValuesExtractors::Scalar     pressure(dim); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        { \n          cell_matrix  = 0; \n          cell_matrix2 = 0; \n          cell_rhs     = 0; \n\n          fe_values.reinit(cell); \n          right_hand_side.vector_value_list(fe_values.get_quadrature_points(), \n                                            rhs_values); \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                  grad_phi_u[k] = fe_values[velocities].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 < dofs_per_cell; ++j) \n                    { \n                      cell_matrix(i, j) += \n                        (viscosity * \n                           scalar_product(grad_phi_u[i], grad_phi_u[j]) - \n                         div_phi_u[i] * phi_p[j] - phi_p[i] * div_phi_u[j]) * \n                        fe_values.JxW(q); \n\n                      cell_matrix2(i, j) += 1.0 / viscosity * phi_p[i] * \n                                            phi_p[j] * fe_values.JxW(q); \n                    } \n\n                  const unsigned int component_i = \n                    fe.system_to_component_index(i).first; \n                  cell_rhs(i) += fe_values.shape_value(i, q) * \n                                 rhs_values[q](component_i) * fe_values.JxW(q); \n                } \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                                                 system_rhs); \n\n          constraints.distribute_local_to_global(cell_matrix2, \n                                                 local_dof_indices, \n                                                 preconditioner_matrix); \n        } \n\n    system_matrix.compress(VectorOperation::add); \n    preconditioner_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n  } \n\n//  @sect3{Solving}  \n\n// 这个函数用MINRES求解线性系统，如介绍中所述，对两个对角线块使用块状对角线预处理和AMG。预处理程序对0,0块应用v循环，对1,1块应用质量矩阵的CG（Schur补充）。\n\n  template <int dim> \n  void StokesProblem<dim>::solve() \n  { \n    TimerOutput::Scope t(computing_timer, \"solve\"); \n\n    LA::MPI::PreconditionAMG prec_A; \n    { \n      LA::MPI::PreconditionAMG::AdditionalData data; \n\n#ifdef USE_PETSC_LA \n      data.symmetric_operator = true; \n#endif \n      prec_A.initialize(system_matrix.block(0, 0), data); \n    } \n\n    LA::MPI::PreconditionAMG prec_S; \n    { \n      LA::MPI::PreconditionAMG::AdditionalData data; \n\n#ifdef USE_PETSC_LA \n      data.symmetric_operator = true; \n#endif \n      prec_S.initialize(preconditioner_matrix.block(1, 1), data); \n    } \n\n// InverseMatrix用于解决质量矩阵的问题。\n\n    using mp_inverse_t = LinearSolvers::InverseMatrix<LA::MPI::SparseMatrix, \n                                                      LA::MPI::PreconditionAMG>; \n    const mp_inverse_t mp_inverse(preconditioner_matrix.block(1, 1), prec_S); \n\n// 这是在上面定义的各个块的预处理的基础上构造的块预处理。\n\n    const LinearSolvers::BlockDiagonalPreconditioner<LA::MPI::PreconditionAMG, \n                                                     mp_inverse_t> \n      preconditioner(prec_A, mp_inverse); \n\n// 有了这些，我们终于可以设置线性求解器并求解该系统。\n\n    SolverControl solver_control(system_matrix.m(), \n                                 1e-10 * system_rhs.l2_norm()); \n\n    SolverMinRes<LA::MPI::BlockVector> solver(solver_control); \n\n    LA::MPI::BlockVector distributed_solution(owned_partitioning, \n                                              mpi_communicator); \n\n    constraints.set_zero(distributed_solution); \n\n    solver.solve(system_matrix, \n                 distributed_solution, \n                 system_rhs, \n                 preconditioner); \n\n    pcout << \"   Solved in \" << solver_control.last_step() << \" iterations.\" \n          << std::endl; \n\n    constraints.distribute(distributed_solution); \n\n// 像在  step-56  中一样，我们减去平均压力，以便与我们的参考解决方案进行误差计算，该解决方案的平均值为零。\n\n    locally_relevant_solution = distributed_solution; \n    const double mean_pressure = \n      VectorTools::compute_mean_value(dof_handler, \n                                      QGauss<dim>(velocity_degree + 2), \n                                      locally_relevant_solution, \n                                      dim); \n    distributed_solution.block(1).add(-mean_pressure); \n    locally_relevant_solution.block(1) = distributed_solution.block(1); \n  } \n\n//  @sect3{The rest}  \n\n// 其余处理网格细化、输出和主循环的代码非常标准。\n\n  template <int dim> \n  void StokesProblem<dim>::refine_grid() \n  { \n    TimerOutput::Scope t(computing_timer, \"refine\"); \n\n    triangulation.refine_global(); \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::output_results(const unsigned int cycle) const \n  { \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      Vector<double> cellwise_errors(triangulation.n_active_cells()); \n      QGauss<dim>    quadrature(velocity_degree + 2); \n\n      VectorTools::integrate_difference(dof_handler, \n                                        locally_relevant_solution, \n                                        ExactSolution<dim>(), \n                                        cellwise_errors, \n                                        quadrature, \n                                        VectorTools::L2_norm, \n                                        &velocity_mask); \n\n      const double error_u_l2 = \n        VectorTools::compute_global_error(triangulation, \n                                          cellwise_errors, \n                                          VectorTools::L2_norm); \n\n      VectorTools::integrate_difference(dof_handler, \n                                        locally_relevant_solution, \n                                        ExactSolution<dim>(), \n                                        cellwise_errors, \n                                        quadrature, \n                                        VectorTools::L2_norm, \n                                        &pressure_mask); \n\n      const double error_p_l2 = \n        VectorTools::compute_global_error(triangulation, \n                                          cellwise_errors, \n                                          VectorTools::L2_norm); \n\n      pcout << \"error: u_0: \" << error_u_l2 << \" p_0: \" << error_p_l2 \n            << std::endl; \n    } \n\n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.emplace_back(\"pressure\"); \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(locally_relevant_solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n\n    LA::MPI::BlockVector interpolated; \n    interpolated.reinit(owned_partitioning, MPI_COMM_WORLD); \n    VectorTools::interpolate(dof_handler, ExactSolution<dim>(), interpolated); \n\n    LA::MPI::BlockVector interpolated_relevant(owned_partitioning, \n                                               relevant_partitioning, \n                                               MPI_COMM_WORLD); \n    interpolated_relevant = interpolated; \n    { \n      std::vector<std::string> solution_names(dim, \"ref_u\"); \n      solution_names.emplace_back(\"ref_p\"); \n      data_out.add_data_vector(interpolated_relevant, \n                               solution_names, \n                               DataOut<dim>::type_dof_data, \n                               data_component_interpretation); \n    } \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    data_out.build_patches(); \n\n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", cycle, mpi_communicator, 2); \n  } \n\n  template <int dim> \n  void StokesProblem<dim>::run() \n  { \n#ifdef USE_PETSC_LA \n    pcout << \"Running using PETSc.\" << std::endl; \n#else \n    pcout << \"Running using Trilinos.\" << std::endl; \n#endif \n    const unsigned int n_cycles = 5; \n    for (unsigned int cycle = 0; cycle < n_cycles; ++cycle) \n      { \n        pcout << \"Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          make_grid(); \n        else \n          refine_grid(); \n\n        setup_system(); \n\n        assemble_system(); \n        solve(); \n\n        if (Utilities::MPI::n_mpi_processes(mpi_communicator) <= 32) \n          { \n            TimerOutput::Scope t(computing_timer, \"output\"); \n            output_results(cycle); \n          } \n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n\n        pcout << std::endl; \n      } \n  } \n} // namespace Step55 \n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step55; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      StokesProblem<2> problem(2); \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\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": "63437a9c8c05b146e8c17f6f04e3c79271c62f1d", "size": 27258, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-55/step-55.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-55/step-55.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-55/step-55.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.5475285171, "max_line_length": 161, "alphanum_fraction": 0.572088928, "num_tokens": 7816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.5993403825057586}}
{"text": "/*\n * Copyright 2017 Mahdi Khanalizadeh\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef HEADER_EXT_VECTOR3_HPP_INCLUDED\n#define HEADER_EXT_VECTOR3_HPP_INCLUDED\n\n#include <cmath>\n\n#include <boost/operators.hpp>\n\nnamespace ext\n{\n\n\ttemplate <typename T>\n\tclass Vector3 :\n\t\tboost::equality_comparable<Vector3<T>,\n\t\tboost::additive<Vector3<T>,\n\t\tboost::multiplicative<Vector3<T>, T\n\t\t>>>\n\t{\n\tpublic:\n\t\tusing Type = T;\n\n\t\tType x;\n\t\tType y;\n\t\tType z;\n\n\t\tVector3() : x{0}, y{0}, z{0} {}\n\t\tVector3(Type x_, Type y_, Type z_) : x{x_}, y{y_}, z{z_} {}\n\t\ttemplate <typename U>\n\t\tVector3(Vector3<U> const& v) : x{v.x}, y{v.y}, z{v.z} {}\n\t};\n\n\tusing Vector3f = Vector3<float>;\n\tusing Vector3d = Vector3<double>;\n\tusing Vector3ld = Vector3<long double>;\n\n\ttemplate <typename T>\n\tbool operator==(Vector3<T> const& v1, Vector3<T> const& v2)\n\t{\n\t\treturn v1.x == v2.x && v1.y == v2.y && v1.z == v2.z;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T>& operator+=(Vector3<T>& v1, Vector3<T> const& v2)\n\t{\n\t\tv1.x += v2.x;\n\t\tv1.y += v2.y;\n\t\tv1.z += v2.z;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T>& operator-=(Vector3<T>& v1, Vector3<T> const& v2)\n\t{\n\t\tv1.x -= v2.x;\n\t\tv1.y -= v2.y;\n\t\tv1.z -= v2.z;\n\t\treturn v1;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T>& operator*=(Vector3<T>& v, T t)\n\t{\n\t\tv.x *= t;\n\t\tv.y *= t;\n\t\tv.z *= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T>& operator/=(Vector3<T>& v, T t)\n\t{\n\t\tv.x /= t;\n\t\tv.y /= t;\n\t\tv.z /= t;\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T> operator+(Vector3<T> const& v)\n\t{\n\t\treturn v;\n\t}\n\n\ttemplate <typename T>\n\tVector3<T> operator-(Vector3<T> const& v)\n\t{\n\t\treturn {-v.x, -v.y, -v.z};\n\t}\n\n\ttemplate <typename T>\n\tT dot(Vector3<T> const& v1, Vector3<T> const& v2)\n\t{\n\t\treturn v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;\n\t}\n\n\ttemplate <typename T>\n\tT norm(Vector3<T> const& v)\n\t{\n\t\treturn std::sqrt(dot(v, v));\n\t}\n\n\ttemplate <typename T>\n\tVector3<T> normalize(Vector3<T> const& v)\n\t{\n\t\treturn v / norm(v);\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_VECTOR3_HPP_INCLUDED\n", "meta": {"hexsha": "b91c49587d3e5a831c72153485cfe17d4592a75a", "size": 2525, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/vector3.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ext/vector3.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ext/vector3.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0396825397, "max_line_length": 75, "alphanum_fraction": 0.636039604, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.5993403658922577}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <base/timer.hpp>\n#include <fft/fft2.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\nusing namespace std;\n\nconst char* fname = \"test_rt.h5\";\n\n// typedef FFTr2c<PlannerR2COD> fft_t;\ntypedef FFT fft_t;\ntypedef RT<std::complex<double>, RidgeletFrame, fft_t> RT_t;\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\n\nvoid dump_frc(const std::vector<rt_coeff_t>& f_rc, const RidgeletFrame& rt)\n{\n  const char* fname = \"f_rc.h5\";\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (unsigned int i = 0; i < f_rc.size(); ++i) {\n    stringstream ss;\n    ss << rt.lambdas()[i];\n    string slam = ss.str();\n    eigen2hdf::save(file, slam, f_rc[i]);\n  }\n  H5Fclose(file);\n  cout << \"Written f(lambda, t) to \" << fname << \"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int Jx, Jy, rho_x, rho_y;\n\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(3), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(3), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"save\", \"save coefficients\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << setw(20) << \"Jx: \" << Jx << \"\\n\"\n       << setw(20) << \"Jy: \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x: \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y: \" << rho_y << \"\\n\"\n       << setw(20) << \"Nx: \" << std::pow(2, Jx + 2) * rho_x << \"\\n\"\n       << setw(20) << \"Ny: \" << std::pow(2, Jy + 2) * rho_y << \"\\n\";\n  RDTSCTimer timer;\n\n  timer.start();\n  RidgeletFrame frame(Jx, Jy, rho_x, rho_y);\n  double time_frame_constructor = timer.stop();\n  timer.print(cout, time_frame_constructor, \"RidgeletFrame init\");\n\n  const unsigned int ncols = frame.Nx();  // #cols\n  const unsigned int nrows = frame.Ny();  // #rows\n\n  RT_t rt(frame);\n  array_t F(nrows / 2, ncols / 2);\n  {\n    double pi = boost::math::constants::pi<double>();\n    Eigen::ArrayXd x = pi * Eigen::ArrayXd::LinSpaced(ncols / 2, 0, 1);\n    Eigen::ArrayXd y = pi * Eigen::ArrayXd::LinSpaced(nrows / 2, 0, 1);\n    F = y.replicate(1, x.rows()).sin() * x.transpose().replicate(y.rows(), 1).sin();\n\n    Eigen::MatrixXd tmp = F;\n    tmp = tmp.triangularView<Eigen::Lower>();\n    F = tmp.array();\n  }\n\n  fft_t fft;\n  // debug\n  complex_array_t Fhh(nrows / 2, ncols / 2);\n  fft.ft(Fhh, F, false);\n  hid_t file;\n  if (vm.count(\"save\")) {\n    file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    eigen2hdf::save(file, \"Fhh\", Fhh);  // debug\n  }\n  // ----------------------------------------\n  complex_array_t Fh(nrows, ncols);\n  Fh.setZero();\n  ftcut(Fh, nrows / 2, ncols / 2) = Fhh;\n  std::vector<rt_coeff_t> rt_coeffs(frame.size());\n  timer.start();\n  cout << \"rt.rt(...)\"\n       << \"\\n\";\n  rt.rt(rt_coeffs, Fh);\n\n  int ncoeffs = 0;\n  for (unsigned int i = 0; i < rt_coeffs.size(); ++i) {\n    ncoeffs += rt_coeffs[i].rows() * rt_coeffs[i].cols();\n  }\n  cout << \"dim(rt_coeffs): \" << ncoeffs << \"\\n\";\n  auto time_rt = timer.stop();\n  timer.print(cout, time_rt, \"rt.rt\");\n\n  // -------------------- Inverse transform --------------------\n  complex_array_t Fh2(nrows, ncols);\n  timer.start();\n  cout << \"rt.irt(...)\"\n       << \"\\n\";\n  rt.irt(Fh2, rt_coeffs);\n  auto time_irt = timer.stop();\n  timer.print(cout, time_irt, \"rt.irt\");\n\n  array_t F2(nrows / 2, ncols / 2);\n  complex_array_t Fh2_cut(nrows / 2, ncols / 2);\n  Fh2_cut.setZero();\n  Fh2_cut = ftcut(Fh2, nrows / 2, ncols / 2);\n  fft.ift(F2, Fh2_cut);\n  auto diff = (F - F2).abs();\n  cout << \"(F-F2).abs().sum(): \" << diff.sum() << \"\\n\";\n\n  if (vm.count(\"save\")) {\n    eigen2hdf::save(file, \"Fhl\", Fhh);\n    eigen2hdf::save(file, \"Fh\", Fh);\n    eigen2hdf::save(file, \"R\", F);\n    eigen2hdf::save(file, \"Fh2\", Fh2);\n    eigen2hdf::save(file, \"R2\", F2);\n    H5Fclose(file);\n    cout << \"written results to \" << fname << \"\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "21c1bc0726168a7d18b4718fd8f6a2dbd10083c3", "size": 4562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_rt.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_rt.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_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": 30.8243243243, "max_line_length": 84, "alphanum_fraction": 0.5795703639, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5992905305768143}}
{"text": "#include \"Geometry.h\"\n\n\n#include \"Eigen/Core\"\n#include \"Eigen/Dense\"\n//#include <Eigen/SVD>\n\n#include \"glm/glm.hpp\"\n#include \"glm/gtc/matrix_transform.hpp\"\n#include \"glm/gtc/matrix_access.hpp\"\n\n\n#include <iostream>\n#include <limits>\n\n\n#define MIN_VAL -FLT_MAX\n#define MAX_VAL FLT_MAX\n\n\nusing namespace Eigen;\n\n\nvoid ComputeSpatialProperties(std::vector<float>* verts) {\n\tconst int numVerts = ((int)verts->size()) / 3;\n\tglm::vec3 minPoint(MIN_VAL, MIN_VAL, MIN_VAL);\n\tglm::vec3 maxPoint(MAX_VAL, MAX_VAL, MAX_VAL);\n\tglm::vec3 centroid(0.0f);\n\n\tMatrixXf A(numVerts, 3);\n\n\tfor (int i = 0; i < numVerts; i++) {\n\n\t\tfloat x = (*verts)[i * 3];\n\t\tfloat y = (*verts)[i * 3 + 1];\n\t\tfloat z = (*verts)[i * 3 + 2];\n\t\tif (x > minPoint.x) { minPoint.x = x; }\n\t\tif (y > minPoint.y) { minPoint.y = y; }\n\t\tif (z > minPoint.z) { minPoint.z = z; }\n\n\t\tcentroid.x += x;\n\t\tcentroid.y += y;\n\t\tcentroid.z += z;\n\n\t\tA.row(i) << x, y, z;\n\t}\n\n\t//https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca\n\t//std::cout << A << std::endl;\n\n\tJacobiSVD<MatrixXf> svd(A, ComputeThinV);\n\tstd::cout << \"Its singular values are:\" << std::endl << svd.singularValues() << std::endl;\n\tstd::cout << \"Its right singular vectors are the columns of the thin V matrix:\" << std::endl << svd.matrixV() << std::endl;\n\tint ti = 1;\n\n\n\n\n\n}\n\n\n", "meta": {"hexsha": "26bd82e6242b6a3844f70afaf9be2457016dde69", "size": 1345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OpenGL/src/geometry/Geometry.cpp", "max_stars_repo_name": "ScottMoisik/OpenGL", "max_stars_repo_head_hexsha": "e26c73fabfc419d7feaa4215c635244149c8e9c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OpenGL/src/geometry/Geometry.cpp", "max_issues_repo_name": "ScottMoisik/OpenGL", "max_issues_repo_head_hexsha": "e26c73fabfc419d7feaa4215c635244149c8e9c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OpenGL/src/geometry/Geometry.cpp", "max_forks_repo_name": "ScottMoisik/OpenGL", "max_forks_repo_head_hexsha": "e26c73fabfc419d7feaa4215c635244149c8e9c5", "max_forks_repo_licenses": ["Apache-2.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.3492063492, "max_line_length": 124, "alphanum_fraction": 0.6408921933, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5992905092940787}}
{"text": "/**\n * @file finitevolumerobin_main.cc\n * @brief NPDE homework FiniteVolumeRobin code\n * @author Philippe Peter\n * @date February 2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"finitevolumerobin.h\"\n\nint main() {\n  // coefficient functions\n  auto g = [](const Eigen::Vector2d & /*x*/) { return 1.0; };\n  auto gamma = [](const Eigen::Vector2d &x) { return 1.0 + x(0) * x(0); };\n\n  // The equation is solved on  the four test meshes\n  // disk1.msh, disk2.msh, disk3.msh and disk4.msh\n  for (int i = 1; i <= 4; ++i) {\n    // read mesh\n    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    lf::io::GmshReader reader(\n        std::move(mesh_factory),\n        CURRENT_SOURCE_DIR \"/../meshes/disk\" + std::to_string(i) + \".msh\");\n    auto mesh_p = reader.mesh();\n\n    // Construct dofhanlder for linear finite elements on the current mesh.\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n    const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n    // Create a dataset of boolean flags indicating edges on the boundary of the\n    // mesh\n    auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n\n    // ASSEMBLE GALERKIN MATRIX\n    // Matrix in triplet format holding Galerkin matrix, zero initially.\n    lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n\n    // First the part corresponding to piecewise Lagrangian finite elements\n    lf::uscalfe::LinearFELaplaceElementMatrix elmat_provider;\n    lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_provider, A);\n\n    // Next the part corresponding to the modifications of the Galerkin matrix\n    // on the boundary.\n    FiniteVolumeRobin::EdgeMatrixProvider edmat_provider(gamma, bd_flags);\n    lf::assemble::AssembleMatrixLocally(1, dofh, dofh, edmat_provider, A);\n\n    // RIGHT-HAND SIDE VECTOR\n    Eigen::VectorXd phi(dofh.NumDofs());\n    phi.setZero();\n\n    // Contributions on the boundary to the rhs vector\n    FiniteVolumeRobin::EdgeVectorProvider edvec_provider(g, bd_flags);\n    lf::assemble::AssembleVectorLocally(1, dofh, edvec_provider, phi);\n\n    // SOLVE LINEAR SYSTEM\n    Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n    solver.compute(A_crs);\n    Eigen::VectorXd sol_vec = solver.solve(phi);\n\n    // OUTPUT RESULTS TO VTK FILE\n    // construct mesh function representing the finite element solution\n    lf::uscalfe::MeshFunctionFE mf_sol(fe_space, sol_vec);\n    // construct vtk writer\n    lf::io::VtkWriter vtk_writer(mesh_p, CURRENT_BINARY_DIR\n                                             \"/finite_volume_robin_solution_\" +\n                                             std::to_string(i) + \".vtk\");\n    // output data\n    vtk_writer.WritePointData(\n        \"finite_volume_robin_solution_\" + std::to_string(i), mf_sol);\n  }\n  return 0;\n}\n", "meta": {"hexsha": "4b1525a12fac1bdf6d7e370109eb5e0580b61096", "size": 3205, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/FiniteVolumeRobin/templates/finitevolumerobin_main.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/FiniteVolumeRobin/templates/finitevolumerobin_main.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/FiniteVolumeRobin/templates/finitevolumerobin_main.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": 36.0112359551, "max_line_length": 80, "alphanum_fraction": 0.6811232449, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.599258799021045}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <math.h>\n#include \"plane3d.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\nPlane3d::Plane3d(int _id, double alpha, double theta, Vector3d _target){\n    id = _id;\n    Vector3d u0(1, 0, 0);\n    Vector3d v0(0, cos(alpha), sin(alpha));\n    Vector3d w0(0, -sin(alpha), cos(alpha));\n\n    Matrix3f rotationX;\n    rotationX << u0[0], u0[1], u0[2],\n\t\t v0[0], v0[1], v0[2],\n\t\t w0[0], w0[1], w0[2];\n\n\n    Vector3d u1(cos(theta), 0, sin(theta));\n    Vector3d v1(0, 1, 0);\n    Vector3d w1(-sin(theta), 0, cos(theta));\n\n    Matrix3f rotationY;\n    rotationY << u1[0], u1[1], u1[2],\n\t\t v1[0], v1[1], v1[2],\n\t\t w1[0], w1[1], w1[2];\n\n\n    Matrix3f rotation = rotationX * rotationY;\n\n    axisX = Vector3d(rotation.row(0)[0], rotation.row(0)[1], rotation.row(0)[2]);\n    axisY = Vector3d(rotation.row(1)[0], rotation.row(1)[1], rotation.row(1)[2]);\n    normal = Vector3d(rotation.row(2)[0], rotation.row(2)[1], rotation.row(2)[2]);\n\n    Matrix3d A;\n    A << axisX[0], axisX[1], axisX[2],\n\t axisY[0], axisY[1], axisY[2],\n\t normal[0], normal[1], normal[2];\n    inverse = A.inverse();\n\n\n    target = _target;\n}\n\nbool Plane3d::intersectsEdge(Vector3d v0, Vector3d v1){\n    Vector3d diffVec0 = v0 - target;\n    double dotProduct0 = diffVec0.dot(normal);\n\n    Vector3d diffVec1 = v1 - target;\t \n    double dotProduct1 = diffVec1.dot(normal);\n\n    return dotProduct0 * dotProduct1 < 0;\n}\n\n\nbool Plane3d::containsPoint(Vector3d v0){\n    Vector3d diffVec0 = v0 - target;\n    double dotProduct0 = diffVec0.dot(normal);\n    return dotProduct0 == 0;\n}\n\n\narray<double, 3> Plane3d::findIntersection(Vector3d v0, Vector3d v1){\n    Vector3d w = v0 - target;\n    Vector3d u = v1 - v0;\n\n    double N = -(normal.dot(w));\n    double D = normal.dot(u);\n\n    array<double, 3> coords3d = {v0[0] + (N/D) * u[0], v0[1] + (N/D) * u[1], v0[2] + (N/D) * u[2]};\n\n    return coords3d;\n}\n\nint Plane3d::Id(){\n    return id;\n}\n\nVector2d Plane3d::Rotate(array<double, 3> _vec){\n    Vector3d vec(_vec[0], _vec[1], _vec[2]);\n    double xCoord = axisX.dot(vec - target);\n    double yCoord = axisY.dot(vec - target);\n\n    return Vector2d(xCoord, yCoord);\n}\n\nVector3d Plane3d::Get3dPoint(Vector3d pt2d){\n    double x=pt2d[0]*inverse.row(0)[0] + pt2d[1]*inverse.row(0)[1];\n    double y=pt2d[0]*inverse.row(1)[0] + pt2d[1]*inverse.row(1)[1];\n    double z=pt2d[0]*inverse.row(2)[0] + pt2d[1]*inverse.row(2)[1];\n    Vector3d pt(x + target[0], y + target[1], z + target[2]);\n    return pt;\n}\n\n\nShape3d::Shape3d(unsigned long int _tetId, vector<array<double, 3>> _vertices, double _weight, int _label){\n    tetId = _tetId;\n    vertices = _vertices;\n    weight = _weight;\n    label = _label;\n}\n\nunsigned long int Shape3d::TetId(){\n    return tetId;\n}\n\nvector<array<double, 3>> Shape3d::Vertices(){\n    //return Vector3d(vertices[0], vertices[1], vertices[2]);\n    //vector<Vector3d> verticesAsVecs;\n\n    //for(int i=0; i<\n    return vertices;\n}\n\ndouble Shape3d::Weight(){\n    return weight;\n}\n\nint Shape3d::Label(){\n    return label;\n}\n", "meta": {"hexsha": "2252c8c6f3c6bc48da438e57ba15ab294da6e9fc", "size": 3026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/plane3d.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/plane3d.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/plane3d.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": 24.4032258065, "max_line_length": 107, "alphanum_fraction": 0.6226040978, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570318, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5992220317015754}}
{"text": "/*\nCopyright (c) 2015, Tianwei Shen\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of libvot nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n/** \\file euclidean_matrix.cpp\n *\t\\brief euclidean matrix completion (exe)\n */\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <string>\n#include <sstream>\n#include <stdio.h>\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace std;\n\n/**\n * @brief An ad-hoc simple 2d point struct\n */\nnamespace {\nstruct point2d\n{\n\tfloat x,y;\n};\n}\t// end of namespace vot\n\nfloat EuclideanDistance(point2d x1, point2d x2)\n{\n\treturn (x1.x - x2.x) * (x1.x - x2.x) + (x1.y - x2.y) * (x1.y - x2.y);\n}\n\nint main(int argc, char **argv)\n{\n\tint input_size;\n\tcout << \"the size of the matrix: \\n\";\n\tcin >> input_size;\n\tconst int MATRIX_SIZE = input_size;\n\tstring matrix_filename = \"euclidean_matrix\";\n\tstringstream ss;\n\tss << matrix_filename << \"_\" << MATRIX_SIZE;\n\tss >> matrix_filename;\n\tFILE *matrix_file = fopen(matrix_filename.c_str(), \"w\");\n\n\tstd::vector<point2d> points(MATRIX_SIZE);\n\tfor (int i = 0; i < MATRIX_SIZE; i++) {\n\t\tpoints[i].x = rand() % 1000;\n\t\tpoints[i].x /= 1000;\n\t\tpoints[i].y = rand() % 1000;\n\t\tpoints[i].y /= 1000;\n\t}\n\n\tEigen::MatrixXf distance_matrix(MATRIX_SIZE, MATRIX_SIZE);\n\tfor (int i = 0; i < MATRIX_SIZE; i++) {\n\t\tdistance_matrix(i, i) = 0.0;\n\t\tfor (int j = i+1; j < MATRIX_SIZE; j++) {\n\t\t\tdistance_matrix(i, j) = EuclideanDistance(points[i], points[j]);\n\t\t\tdistance_matrix(j, i) = distance_matrix(i, j);\n\t\t}\n\t}\n\n\t// output to the file\n\tfor (int i = 0; i < MATRIX_SIZE; i++) {\n\t\tfor (int j = 0; j < MATRIX_SIZE; j++) {\n\t\t\tcout << distance_matrix(i, j) << \" \";\n\t\t\tfprintf(matrix_file, \"%f \", distance_matrix(i, j));\n\t\t}\n\t\tcout << endl;\n\t\tfprintf(matrix_file, \"\\n\");\n\t}\n\n\tEigen::FullPivLU<Eigen::MatrixXf> lu_decomp(distance_matrix);\n\t//lu_decomp.setThreshold(1e-5);\n\tcout << \"rank of distance matrix: \" << lu_decomp.rank() << endl;\n\n\t//Eigen::JacobiSVD<Eigen::MatrixXf> svd(distance_matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\t//cout << svd.singularValues() << endl;\n\n\tfclose(matrix_file);\n\treturn 0;\n}\n", "meta": {"hexsha": "246f6fc900780bdf0fd095edd30bd8f8bb35bd6a", "size": 3461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/libvot/src/examples/euclidean_matrix.cpp", "max_stars_repo_name": "zyxrrr/GraphSfM", "max_stars_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2015-09-18T13:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:14:11.000Z", "max_issues_repo_path": "software/libvot/src/examples/euclidean_matrix.cpp", "max_issues_repo_name": "zyxrrr/GraphSfM", "max_issues_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-12-29T21:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T10:44:36.000Z", "max_forks_repo_path": "software/libvot/src/examples/euclidean_matrix.cpp", "max_forks_repo_name": "zyxrrr/GraphSfM", "max_forks_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60.0, "max_forks_repo_forks_event_min_datetime": "2015-09-18T13:46:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T03:26:07.000Z", "avg_line_length": 30.9017857143, "max_line_length": 101, "alphanum_fraction": 0.717711644, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5992117965390439}}
{"text": "#pragma once\n\n#include \"Combinations.hpp\"\n#include \"DyckPaths.hpp\"\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace discreture\n{\n\n////////////////////////////////////////////////////////////////////////////////////\n/// \\brief Class for iterating through all motzkin paths.\n/// \\param IntType must be a SIGNED integer type.\n///\n/// Motzkin paths are paths that go from \\f$(0,0)\\f$ to \\f$(0,2n)\\f$,\n/// which never go below the \\f$ y=0\\f$ line, in which each step is from\n/// \\f$(x,y)\\f$ to either \\f$(x+1,y+1)\\f$ or \\f$(x+1,y-1)\\f$ or \\f$(x+1,y)\\f$\n/// #Example Usage:\n///\n///\t\tmotzkin_paths X(4)\n///\t\tfor (auto&& x : X)\n///\t\t\tcout << x << endl;\n/// Prints out:\n///\t\t[ 0 0 0 0 ]\n///\t\t[ 1 -1 0 0 ]\n///\t\t[ 1 0 -1 0 ]\n///\t\t[ 0 1 -1 0 ]\n///\t\t[ 1 0 0 -1 ]\n///\t\t[ 0 1 0 -1 ]\n///\t\t[ 0 0 1 -1 ]\n///\t\t[ 1 1 -1 -1 ]\n///\t\t[ 1 -1 1 -1 ]\n///\n///\n/// # Example: Parenthesis\n///\n/// \tmotzkin_paths X(4)\n/// \tfor (auto&& x : X)\n/// \t\tcout << motzkin_paths::to_string(x, \"(-)\") << endl;\n///\n/// Prints out:\n///\t\t----\n///\t\t()--\n///\t\t(-)-\n///\t\t-()-\n///\t\t(--)\n///\t\t-(-)\n///\t\t--()\n///\t\t(())\n///\t\t()()\n///\n/////////////////////////////////////////////////////////////////////////////////////\n\ntemplate <class IntType = int, class RAContainerInt = std::vector<IntType>>\nclass MotzkinPaths\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 motzkin_path = value_type;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    using comb_i = typename Combinations<IntType, RAContainerInt>::iterator;\n    using dyck_i = typename DyckPaths<IntType, RAContainerInt>::iterator;\n    class iterator;\n    using const_iterator = iterator;\n\n    static std::string to_string(const motzkin_path& data,\n                                 const std::string& delim = \"(-)\")\n    {\n        std::string toReturn;\n\n        for (auto i : data)\n        {\n            auto j = 1 - i;\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 MotzkinPaths(IntType n) : n_(n) {}\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief The total number of motzkin_paths\n    ///\n    /// \\return M_n\n    ///\n    ////////////////////////////////////////////////////////////\n    size_type size() const { return motzkin(n_); }\n\n    IntType get_n() const { return n_; }\n\n    iterator begin() const { return iterator(n_); }\n\n    iterator end() const { return iterator::make_invalid_with_id(size()); }\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Forward iterator class.\n    ////////////////////////////////////////////////////////////\n    class iterator\n        : public boost::iterator_facade<iterator, const motzkin_path&, boost::forward_traversal_tag>\n    {\n    public:\n        iterator() : data_(), comb_(), dyck_() {} // empty initializer\n\n        explicit iterator(IntType n) : data_(n, 0), comb_(n, 0), dyck_(0) {}\n\n        size_type ID() const { return ID_; }\n\n        static 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            auto n = data_.size();\n\n            if (ID_ == motzkin(n))\n                return;\n\n            ++comb_;\n            if (comb_.is_at_end(n))\n            {\n                ++dyck_;\n\n                if (dyck_.is_at_end(num_nonzero_halved_))\n                {\n                    num_nonzero_halved_ += 1;\n\n                    dyck_.reset(num_nonzero_halved_);\n                }\n\n                comb_.reset(n, 2*num_nonzero_halved_);\n            }\n\n            ConvertToMotzkin(); // TODO(mraggi): do this laziliy\n        }\n\n        const motzkin_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        motzkin_path data_;\n        comb_i comb_;\n        dyck_i dyck_;\n        IntType num_nonzero_halved_{0};\n\n        void ConvertToMotzkin()\n        {\n            // \t\t\t\tcout << \"Converting: \" << *comb_ << \" and \" <<\n            // *dyck_\n            // << endl;\n            for (size_t i = 0; i < data_.size(); ++i)\n            {\n                data_[i] = 0;\n            }\n\n            size_t count = 0;\n\n            for (auto x : (*comb_))\n            {\n                data_[x] = (*dyck_)[count];\n                ++count;\n            }\n        }\n\n        friend class boost::iterator_core_access;\n    }; // end class iterator\n\nprivate:\n    IntType n_;\n}; // end class MotzkinPaths\n\nusing boost::container::static_vector;\n\nusing motzkin_paths = MotzkinPaths<int>;\nusing motzkin_paths_stack = MotzkinPaths<int, static_vector<int, 48>>;\n\n} // namespace discreture\n", "meta": {"hexsha": "1d870076e84374a7afb44ef61cad1440a0d7563a", "size": 5255, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/Motzkin.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/Motzkin.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/Motzkin.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": 26.4070351759, "max_line_length": 100, "alphanum_fraction": 0.4690770695, "num_tokens": 1329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5992117717944571}}
{"text": "#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <iomanip>\r\n#include \"RBF.h\"\r\n#include \"MLS.h\"\r\n#include \"HermiteRBF.h\"\r\n#include \"GeneralizedMLS.h\"\r\n#include <boost/mpl/list.hpp>\r\n#include <boost/mpl/for_each.hpp>\r\n#include <boost/mpl/int.hpp>\r\nusing namespace std;\r\nusing namespace kt84;\r\nnamespace mpl = boost::mpl;\r\n\r\n// utility for interpolation algorithms |\r\n//--------------------------------------+\r\ntemplate <template <int, int, class, int> class FuncT>\r\nstruct FuncUtil;\r\ntemplate <> struct FuncUtil<RBF> {\r\n    static const char* getName() { return \"RBF\"; }\r\n    template <class Func> static void add_constraint(Func& f, const typename Func::Point& p, const typename Func::Value& v, const typename Func::Gradient& g) { f.add_constraint(p, v); }\r\n    template <class Func> static void preprocess(Func& f) { f.factorize_and_solve(); }\r\n    template <class Func> static typename Func::Gradient gradient(const Func& f, const typename Func::Point& p) { return f.gradient(p); }\r\n    template <class Func>\r\n    static pair<double, double> getMaxError(const Func& f, double epsilon) {\r\n        pair<double, double> result(0, 0);\r\n        for (size_t i = 0; i < f.constraints.size(); ++i) {\r\n            double error_v = (f(f.constraints[i].first) - f.constraints[i].second).norm();\r\n            result.first = max<double>(result.first, error_v);\r\n        }\r\n        return result;\r\n    }\r\n};\r\ntemplate <> struct FuncUtil<MLS> {\r\n    static const char* getName() { return \"MLS\"; }\r\n    template <class Func> static void add_constraint(Func& f, const typename Func::Point& p, const typename Func::Value& v, const typename Func::Gradient& g) { f.add_constraint(p, v); }\r\n    template <class Func> static void preprocess(Func& f) { }\r\n    template <class Func> static typename Func::Gradient gradient(const Func& f, const typename Func::Point& p) { return typename Func::Gradient::Zero(); }\r\n    template <class Func>\r\n    static pair<double, double> getMaxError(const Func& f, double epsilon) {\r\n        pair<double, double> result(0, 0);\r\n        for (size_t i = 0; i < f.constraints.size(); ++i) {\r\n            double error_v = (f(f.constraints[i].first) - f.constraints[i].second).norm();\r\n            result.first = max<double>(result.first, error_v);\r\n        }\r\n        return result;\r\n    }\r\n};\r\ntemplate <> struct FuncUtil<HermiteRBF> {\r\n    static const char* getName() { return \"HRBF\"; }\r\n    template <class Func> static void add_constraint(Func& f, const typename Func::Point& p, const typename Func::Value& v, const typename Func::Gradient& g) { f.add_constraint(p, v, g); }\r\n    template <class Func> static void preprocess(Func& f) { f.factorize_and_solve(); }\r\n    template <class Func> static typename Func::Gradient gradient(const Func& f, const typename Func::Point& p) { return f.gradient(p); }\r\n    template <class Func>\r\n    static pair<double, double> getMaxError(const Func& f, double epsilon) {\r\n        pair<double, double> result(0, 0);\r\n        for (size_t i = 0; i < f.constraints.size(); ++i) {\r\n            double error_v = (f(f.constraints[i].get<0>()) - f.constraints[i].get<1>()).norm();\r\n            double error_g = (f.gradient_fd(f.constraints[i].get<0>(), epsilon) - f.constraints[i].get<2>()).norm();\r\n            result.first  = max<double>(result.first , error_v);\r\n            result.second = max<double>(result.second, error_g);\r\n        }\r\n        return result;\r\n    }\r\n};\r\ntemplate <> struct FuncUtil<GeneralizedMLS> {\r\n    static const char* getName() { return \"GMLS\"; }\r\n    template <class Func> static void add_constraint(Func& f, const typename Func::Point& p, const typename Func::Value& v, const typename Func::Gradient& g) { f.add_constraint(p, v, g); }\r\n    template <class Func> static void preprocess(Func& f) { }\r\n    template <class Func> static typename Func::Gradient gradient(const Func& f, const typename Func::Point& p) { return typename Func::Gradient::Zero(); }\r\n    template <class Func>\r\n    static pair<double, double> getMaxError(const Func& f, double epsilon) {\r\n        pair<double, double> result(0, 0);\r\n        for (size_t i = 0; i < f.constraints.size(); ++i) {\r\n            double error_v = (f(f.constraints[i].get<0>()) - f.constraints[i].get<1>()).norm();\r\n            double error_g = (f.gradient_fd(f.constraints[i].get<0>(), epsilon) - f.constraints[i].get<2>()).norm();\r\n            result.first  = max<double>(result.first , error_v);\r\n            result.second = max<double>(result.second, error_g);\r\n        }\r\n        return result;\r\n    }\r\n};\r\n\r\n// utility for RBF kernels |\r\n//-------------------------+\r\ntemplate <class RBFKernel_Core>\r\nstruct KernelUtil;\r\ntemplate <> struct KernelUtil<RBFKernel_Gaussian      > { static const char* getName() { return \"Gauss\"; } static RBFKernel_Gaussian      ::Param getParam() { return RBFKernel_Gaussian      ::Param(10); } };\r\ntemplate <> struct KernelUtil<RBFKernel_SquaredInverse> { static const char* getName() { return \"SqInv\"; } static RBFKernel_SquaredInverse::Param getParam() { return RBFKernel_SquaredInverse::Param(20); } };\r\ntemplate <> struct KernelUtil<RBFKernel_Wendland      > { static const char* getName() { return \"Wendl\"; } static RBFKernel_Wendland      ::Param getParam() { return RBFKernel_Wendland      ::Param(1.5); } };\r\ntemplate <> struct KernelUtil<RBFKernel_Cubed         > { static const char* getName() { return \"Cubed\"; } static RBFKernel_Cubed         ::Param getParam() { return RBFKernel_Cubed         ::Param()   ; } };\r\ntemplate <> struct KernelUtil<RBFKernel_Identity      > { static const char* getName() { return \"Ident\"; } static RBFKernel_Identity      ::Param getParam() { return RBFKernel_Identity      ::Param()   ; } };\r\ntemplate <> struct KernelUtil<RBFKernel_SquaredLog    > { static const char* getName() { return \"SqLog\"; } static RBFKernel_SquaredLog    ::Param getParam() { return RBFKernel_SquaredLog    ::Param()   ; } };\r\n\r\n// test functions |\r\n//----------------+\r\ntemplate <int Dim, template <int, int, class, int> class FuncT>\r\nstruct Tester;\r\n\r\n// 1D test\r\ntemplate <template <int, int, class, int> class FuncT>\r\nstruct Tester<1, FuncT> {\r\n    template <class RBFKernel_Core, int DegreePolynomial>\r\n    static void go(const typename RBFKernel_Core::Param& param) {\r\n        typedef FuncT<1, 1, RBFKernel_Core, DegreePolynomial> Func;\r\n        typedef Func::Point Point;\r\n        typedef Func::Value Value;\r\n        typedef Func::Gradient Gradient;\r\n        \r\n        Func f;\r\n        f.kernel.param() = param;\r\n        \r\n        ifstream fin(\"input1d.txt\");\r\n        if (!fin)\r\n            throw exception(\"input1d.txt not found!\");\r\n        while (!fin.eof()) {\r\n            Point p;\r\n            Value v;\r\n            Gradient g;\r\n            \r\n            fin >> p[0] >> v[0] >> g[0];\r\n            if (!fin.eof())\r\n                FuncUtil<FuncT>::add_constraint(f, p, v, g);\r\n        }\r\n        \r\n        FuncUtil<FuncT>::preprocess(f);\r\n        \r\n        stringstream fname;\r\n        fname << \"test1d_\" << FuncUtil<FuncT>::getName() << \"_\" << KernelUtil<RBFKernel_Core>::getName() << \"_p\" << DegreePolynomial << \".txt\";\r\n        ofstream fout(fname.str().c_str());\r\n        // report error first\r\n        pair<double, double> maxError = FuncUtil<FuncT>::getMaxError(f, 0.00001);\r\n        fout << \"# max error (value, gradient): (\" << maxError.first << \", \" << maxError.second << \")\" << endl << endl;\r\n        // plot data\r\n        const int N = 100;\r\n        for (double i = 0; i <= N; ++i) {\r\n            Func::Point point = Func::Point::Constant(i / N);\r\n            Func::Value value = f(point);\r\n            Func::Gradient gradient = FuncUtil<FuncT>::gradient(f, point);\r\n            Func::Gradient gradient_fd = f.gradient_fd(point, 0.00001);\r\n            fout\r\n                << setw(12) << point[0] << \" \"\r\n                << setw(12) << value[0] << \" \"\r\n                << setw(12) << gradient[0] << \" \"\r\n                << setw(12) << gradient_fd[0] << \" \"\r\n                << endl;\r\n        }\r\n    }\r\n    // generate gnuplot commands |\r\n    //---------------------------+\r\n    template <class RBFKernel_Core>\r\n    static void genCmd(int DegreePolynomial) {\r\n        stringstream fname;\r\n        const char* funcName = FuncUtil<FuncT>::getName();\r\n        const char* kernelName = KernelUtil<RBFKernel_Core>::getName();\r\n        fname << \"cmd1d_\" << funcName << \"_\" << kernelName << \".txt\";\r\n        ofstream fout(fname.str().c_str());\r\n        fout << \"plot\\\\\" << endl;\r\n        for (int i = 0; i <= DegreePolynomial; ++i) {\r\n            fout << \"    \\\"test1d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \".txt\\\" w linespoints\";\r\n            if (i < DegreePolynomial)\r\n                fout << \",\\\\\";\r\n            fout << endl;\r\n        }\r\n        fout << \"pause -1\" << endl;\r\n        fout.close();\r\n        fname.str(\"\");\r\n        fname << \"cmd1d_\" << funcName << \"_\" << kernelName << \"_g.txt\";\r\n        fout.open(fname.str().c_str());\r\n        fout << \"plot\\\\\" << endl;\r\n        for (int i = 0; i <= DegreePolynomial; ++i) {\r\n            fout << \"    \\\"test1d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \".txt\\\" u 1:4 w linespoints\";\r\n            if (i < DegreePolynomial)\r\n                fout << \",\\\\\";\r\n            fout << endl;\r\n        }\r\n        fout << \"pause -1\" << endl;\r\n    }\r\n};\r\n\r\n// 2D test\r\ntemplate <template <int, int, class, int> class FuncT>\r\nstruct Tester<2, FuncT> {\r\n    template <class RBFKernel_Core, int DegreePolynomial>\r\n    static void go(const typename RBFKernel_Core::Param& param) {\r\n        typedef FuncT<2, 1, RBFKernel_Core, DegreePolynomial> Func;\r\n        typedef Func::Point Point;\r\n        typedef Func::Value Value;\r\n        typedef Func::Gradient Gradient;\r\n        \r\n        Func f;\r\n        f.kernel.param() = param;\r\n        \r\n        ifstream fin(\"input2d.txt\");\r\n        if (!fin)\r\n            throw exception(\"input2d.txt not found!\");\r\n        while (!fin.eof()) {\r\n            Point p;\r\n            Value v;\r\n            Gradient g;\r\n            \r\n            fin >> p[0] >> p[1] >> v[0] >> g[0] >> g[1];\r\n            if (!fin.eof())\r\n                FuncUtil<FuncT>::add_constraint(f, p, v, g);\r\n        }\r\n        \r\n        FuncUtil<FuncT>::preprocess(f);\r\n        \r\n        stringstream fname;\r\n        fname << \"test2d_\" << FuncUtil<FuncT>::getName() << \"_\" << KernelUtil<RBFKernel_Core>::getName() << \"_p\" << DegreePolynomial << \".txt\";\r\n        ofstream fout(fname.str().c_str());\r\n        // report error first\r\n        pair<double, double> maxError = FuncUtil<FuncT>::getMaxError(f, 0.00001);\r\n        fout << \"# max error (value, gradient): (\" << maxError.first << \", \" << maxError.second << \")\" << endl << endl;\r\n        // plot data\r\n        const int N = 32;\r\n        for (double j = 0; j <= N; ++j) {\r\n            for (double i = 0; i <= N; ++i) {\r\n                Func::Point point = Func::Point(i / N, j / N);\r\n                Func::Value value = f(point);\r\n                Func::Gradient gradient = FuncUtil<FuncT>::gradient(f, point);\r\n                Func::Gradient gradient_fd = f.gradient_fd(point, 0.00001);\r\n                fout\r\n                    << setw(12) << point[0] << \" \"\r\n                    << setw(12) << point[1] << \" \"\r\n                    << setw(12) << value[0] << \" \"\r\n                    << setw(12) << gradient[0] << \" \"\r\n                    << setw(12) << gradient[1] << \" \"\r\n                    << setw(12) << gradient_fd[0] << \" \"\r\n                    << setw(12) << gradient_fd[1] << \" \"\r\n                    << endl;\r\n            }\r\n            fout << endl;\r\n        }\r\n    }\r\n    // generate gnuplot commands |\r\n    //---------------------------+\r\n    template <class RBFKernel_Core>\r\n    static void genCmd(int DegreePolynomial) {\r\n        const char* funcName = FuncUtil<FuncT>::getName();\r\n        const char* kernelName = KernelUtil<RBFKernel_Core>::getName();\r\n        for (int i = 0; i <= DegreePolynomial; ++i) {\r\n            // value\r\n            stringstream fname;\r\n            fname << \"cmd2d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \".txt\";\r\n            ofstream fout(fname.str().c_str());\r\n            fout << \"set pm3d; unset surface; set pm3d hidden3d 100;set view 60, 320\\n\";\r\n            fout << \"splot \\\"test2d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \".txt\\\" u 1:2:3\\n\";\r\n            fout << \"pause -1\\n\";\r\n            fout.close();\r\n            // gradient\r\n            fname.str(\"\");\r\n            fname << \"cmd2d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \"_g.txt\";\r\n            fout.open(fname.str().c_str());\r\n            fout << \"set pm3d; unset surface; set pm3d hidden3d 100;set view 60, 320;\\n\";\r\n            fout << \"splot \\\"test2d_\" << funcName << \"_\" << kernelName << \"_p\" << i << \"_g.txt\\\" u 1:2:6\\n\";\r\n            fout << \"pause -1\\n\";\r\n        }\r\n    }\r\n};\r\n\r\n// list of valid kernels for each algorithm |\r\n//------------------------------------------+\r\ntemplate <template <int, int, class, int> class FuncT>\r\nstruct KernelList;\r\ntemplate <> struct KernelList<RBF> {\r\n    typedef mpl::list<\r\n        RBFKernel_Gaussian      ,\r\n        RBFKernel_SquaredInverse,\r\n        RBFKernel_Wendland      ,\r\n        RBFKernel_Cubed         ,\r\n        RBFKernel_Identity      ,\r\n        RBFKernel_SquaredLog    \r\n    > Value;\r\n};\r\ntemplate <> struct KernelList<HermiteRBF> {\r\n    typedef mpl::list<\r\n        RBFKernel_Gaussian      ,\r\n        RBFKernel_SquaredInverse,\r\n        RBFKernel_Cubed         \r\n    > Value;\r\n};\r\ntemplate <> struct KernelList<MLS> {\r\n    typedef mpl::list<\r\n        RBFKernel_Gaussian      ,\r\n        RBFKernel_SquaredInverse,\r\n        RBFKernel_Wendland      \r\n    > Value;\r\n};\r\ntemplate <> struct KernelList<GeneralizedMLS> {\r\n    typedef mpl::list<\r\n        RBFKernel_Gaussian      ,\r\n        RBFKernel_SquaredInverse,\r\n        RBFKernel_Wendland      \r\n    > Value;\r\n};\r\n\r\n// utility for looping over parameters |\r\n//-------------------------------------+\r\ntemplate <template <int, int, class, int> class FuncT>\r\nstruct TestLooper {\r\n    static void go() {\r\n        typedef mpl::list<\r\n            mpl::int_<1>,\r\n            mpl::int_<2>\r\n        > DimList;\r\n        mpl::for_each<DimList>(LoopDim());\r\n    }\r\n    struct LoopDim {\r\n        template <class IntDim>\r\n        void operator()(const IntDim&) const {\r\n            mpl::for_each<KernelList<FuncT>::Value>(LoopKernel<IntDim::value>());\r\n        }\r\n        template <int Dim>\r\n        struct LoopKernel {\r\n            template <class RBFKernel>\r\n            void operator()(const RBFKernel&) const {\r\n                typedef mpl::list<\r\n                    mpl::int_<0>,\r\n                    mpl::int_<1>,\r\n                    mpl::int_<2>\r\n                > DegreeList;\r\n                mpl::for_each<DegreeList>(LoopDegree<RBFKernel>());\r\n                Tester<Dim, FuncT>::genCmd<RBFKernel>(2);\r\n            }\r\n            template <class RBFKernel>\r\n            struct LoopDegree {\r\n                template <class IntDegree>\r\n                void operator()(const IntDegree&) const {\r\n                    Tester<Dim, FuncT>::go<RBFKernel, IntDegree::value>(KernelUtil<RBFKernel>::getParam());\r\n                }\r\n            };\r\n        };\r\n    };\r\n};\r\n\r\nint main() {\r\n    TestLooper<RBF           >::go();       // list of templates cannot be handled by Boost.MPL\r\n    TestLooper<MLS           >::go();\r\n    TestLooper<HermiteRBF    >::go();\r\n    TestLooper<GeneralizedMLS>::go();\r\n}\r\n", "meta": {"hexsha": "bdc2be473ba744663b9777d571dbc141b643eae9", "size": 15482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/quadretopology/patterns/patterns/kt84/math/interpolant_test.cpp", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_stars_repo_licenses": ["Apache-2.0"], "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/quadwild/libs/quadretopology/patterns/patterns/kt84/math/interpolant_test.cpp", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "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/quadwild/libs/quadretopology/patterns/patterns/kt84/math/interpolant_test.cpp", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_forks_repo_licenses": ["Apache-2.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.8753623188, "max_line_length": 209, "alphanum_fraction": 0.5429531068, "num_tokens": 3797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5991637961370786}}
{"text": "#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <stdexcept>\n#include <nlohmann/json.hpp>\n#include <filesystem>\n\n//! Initial condition: grid-aligned rectangle\n//! @param[in] (x,y) point to evaulate the initial condition\n//! @param[out] evaluation of the function at (x,y)\ndouble ic(double x, double y) {\n    if (x > -0.3 && x < 0.3 && y > -0.3 && y < 0.3)\n        return 1.0;\n    else\n        return 0.0;\n}\n\n//! Load configuration values from a JSON file\n//! @param[in] jsonFilename file (including path if needed) of config.json\n//! @param[out] json object with parameters: T, {x,y}{min,max}, Nx, Ny, cfl\nnlohmann::json loadConfig(std::string jsonFilename) {\n    std::ifstream i(jsonFilename);\n    assert(i.good() && \"config.json not found in current or parent directory\");\n\n    nlohmann::json j;\n    i >> j;\n    return j;\n}\n\n//! Apply periodic boundary conditions to matrix u.\n//! u has relevant values in the Nx x Ny submatrix at the center\n//! @param[in] u  (Nx+2)x(Ny+2) matrix\nvoid applyBoundaryConditions(Eigen::MatrixXd &u) {\n// (write your solution here)\n}\n\n//! An implementation of the 1D upwind numerical flux\n//! @param[in] uM  value to the left of the interface\n//! @param[in] uR  value to the right of the interface\n//! @param[in] a   velocity at the interface\ndouble F(double uM, double uP, double a) {\n    return std::max(a, 0.)*uM + std::min(a, 0.)*uP;\n}\n\n//! Compute one step of the upwind method in 2D\n//! @param[in] u           matrix of size (Nx+2)x(Ny+2) which will contain U^{n+1}\n//! @param[in] u_old       matrix of size (Nx+2)x(Ny+2) of values U^{n}\n//! @param[in] dx, dy, dt  meshsteps and timestep\n//! @param[in] a           velocity as a function of R^2 to R^2\nvoid updateUpwind(Eigen::MatrixXd &u, Eigen::MatrixXd &u_old, double dx,\n                  double dy, double dt, double xmin, double ymin,\n                  const std::function<Eigen::Vector2d(double, double)> &a) {\n// (write your solution here)\n}\n\n//! Clear the contents of the output file before starting\n//! Useful because we write in append mode\n//! @param[in] outfile  name of the file to be wiped\nvoid wipeFile(std::string outfile) {\n    std::ofstream outstrm;\n    outstrm.open(outfile, std::ofstream::out | std::ofstream::trunc);\n    outstrm.close();\n}\n\nint main() {\n    // Path to the config file relative to the binary. Try a couple of likely locations.\n    std::string config_file = std::filesystem::exists(\"../config.json\") ? \"../config.json\" : \"config.json\";\n\n    auto j = loadConfig(config_file);\n    double T = j[\"T\"];\n    double xmin = j[\"xmin\"], ymin = j[\"ymin\"], xmax = j[\"xmax\"], ymax = j[\"ymax\"];\n    int Nx = j[\"Nx\"], Ny = j[\"Ny\"];\n    double cfl = j[\"cfl\"];\n\n    // Derived data\n    double dx = (xmax-xmin)/Nx;\n    double dy = (ymax-ymin)/Ny;\n    auto a = [](double x, double y) { return Eigen::Vector2d(y, -x); };\n    double max_ax = ymax; // maximum of a_1 in domain\n    double max_ay = -xmin; // maximum of a_2 in domain\n    double dt_max = cfl / (max_ax/dx + max_ay/dy);\n    std::string outfile = \"u.txt\";\n    Eigen::MatrixXd u(Nx+2, Ny+2); // include ghost cells\n\n    // apply initial condition to (1..Nx)x(1..Ny)\n// (write your solution here)\n    applyBoundaryConditions(u); // Complete u with BCs\n    Eigen::MatrixXd u_old = u;\n\n    wipeFile(outfile); // clear contents of output file\n\n    double t = 0;\n    std::vector<double> times;\n    times.push_back(t);\n    appendMatrixToFile(outfile, u.block(1,1,Nx,Ny));\n\n    // Iterate over time\n    while(t < T) {\n        double dt = std::min(dt_max, T-t); // make sure we don't go beyond T\n        t += dt;\n\n        // Call updateUpwind. Don't forget the boundary conditions!\n// (write your solution here)\n\n        appendMatrixToFile(outfile, u.block(1,1,Nx,Ny));\n        u_old = u;\n        times.push_back(t);\n    }\n    writeToFile(\"time.txt\", times);\n}\n", "meta": {"hexsha": "97a86cae6233190246920c97d06742154b485ff7", "size": 3880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_workbench/linear-transp-2d/linear_transport.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_workbench/linear-transp-2d/linear_transport.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_workbench/linear-transp-2d/linear_transport.cpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 34.3362831858, "max_line_length": 107, "alphanum_fraction": 0.6347938144, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.5990594289651187}}
{"text": "#pragma once\n\n#include \"MerweScaledSigmaPoints.hpp\"\n#include \"GaussianDistribution.hpp\"\n\n#include <iostream>\n#include <Eigen/Dense>\n\nnamespace icarus\n{\n    template<typename T, size_t N>\n    struct UnscentedKalmanFilter\n    {\n        explicit UnscentedKalmanFilter() :\n            mSigmaPoints(0.5f)\n        {\n            reset();\n        }\n\n        template<typename ProcessModel, typename MeasurementModel, size_t S>\n        void filter(ProcessModel const & processModel, MeasurementModel const & measurementModel, GaussianDistribution<T, S> const & measurement, T timeStep)\n        {\n            auto points = mSigmaPoints(mState);\n\n            for (auto & point : points) {\n                point = processModel(point, timeStep);\n            }\n\n            mState = mSigmaPoints.unscentedTransform(points);\n            mState.covariance.template triangularView<Eigen::Lower>() += processModel.noise();\n\n            std::array<Eigen::Matrix<T, S, 1>, 2 * N + 1> measurementPoints;\n\n            for (int i = 0; i < 2 * N + 1; ++i) {\n                measurementPoints[i] = measurementModel(points[i]);\n            }\n\n            auto measurementDistribution = mSigmaPoints.unscentedTransform(measurementPoints);\n            measurementDistribution.covariance.template triangularView<Eigen::Lower>() += measurement.covariance;\n            measurementDistribution.covariance.template triangularView<Eigen::Upper>() = measurementDistribution.covariance.transpose();\n\n            Eigen::Matrix<T, N, S> gain;\n            gain.setZero();\n\n            for (int i = 0; i < mSigmaPoints.size(); ++i) {\n                auto weight = mSigmaPoints.covarianceWeight(i);\n                auto stateDifference = points[i] - mState.mean;\n                auto measurementDifference = measurementPoints[i] - measurementDistribution.mean;\n\n                gain += weight * stateDifference * measurementDifference.transpose();\n            }\n\n            gain *= measurementDistribution.covariance.inverse();\n\n            mState.mean += gain * (measurement.mean - measurementDistribution.mean);\n            mState.covariance.template triangularView<Eigen::Lower>() -= gain * measurementDistribution.covariance * gain.transpose();\n        }\n\n        void reset()\n        {\n            mState.mean.setZero();\n            mState.covariance.setZero();\n        }\n\n        Eigen::Matrix<T, N, 1> & stateVector()\n        {\n            return mState.mean;\n        }\n    private:\n        MerweScaledSigmaPoints<T, N> mSigmaPoints;\n        GaussianDistribution<T, N> mState;\n    };\n}\n", "meta": {"hexsha": "9491d84df915f547fd160c26a0179529c1f02eef", "size": 2553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensorFusion/UnscentedKalmanFilter.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icarus/include/icarus/sensorFusion/UnscentedKalmanFilter.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icarus/include/icarus/sensorFusion/UnscentedKalmanFilter.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5, "max_line_length": 157, "alphanum_fraction": 0.6114375245, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5989425989435101}}
{"text": "//\n//  ambisonicDecoder.h\n//  AmbisonicDecoder\n//\n//  Created by David Poirier-Quinot on 21/06/2017.\n//  Copyright © 2017 ICL. All rights reserved.\n//\n\n#ifndef ambisonicDecoder_hpp\n#define ambisonicDecoder_hpp\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Eigenvalues>\n\ndouble deg2rad( const double degrees ){\n    return degrees * 4.0 * atan (1.0) / 180.0;\n}\n\nunsigned int getNumAmbiCh( const unsigned int order )\n{\n    return pow(order + 1, 2);\n}\n\nclass AmbisonicDecoder\n{\n    \n//==========================================================================\n// ATTRIBUTES\n    \npublic:\n    \n    \nprivate:\n    \n//==========================================================================\n// METHODS\n    \npublic:\n    \n    AmbisonicDecoder() {}\n    \n    ~AmbisonicDecoder() {}\n    \n    Eigen::MatrixXf getDecodingMatrix( const Eigen::MatrixXf & spkAzimElev, const unsigned int order, const bool useEpad )\n    {\n        // init\n        unsigned long numSpk = spkAzimElev.cols();\n        unsigned int numCh = getNumAmbiCh( order );\n        Eigen::MatrixXf ambiGains ( numSpk, numCh ) ;\n        Eigen::VectorXf gains( numCh );\n        float azim; float elev;\n        \n        // loop over speaker positions\n        for( int i = 0; i < numSpk; i++ ){\n            // get spk azim elev\n            azim = spkAzimElev(0, i);\n            elev = spkAzimElev(1, i);\n            \n            // get spherical harmonic coefficients\n            getRSH( order, azim, elev, gains );\n            \n            // fill output\n            for( int j = 0; j < numCh; j++ ){\n                ambiGains(i,j) = gains[j];\n            }\n        }\n        \n        if( useEpad ){\n            // singular value decomposition\n            Eigen::JacobiSVD<Eigen::MatrixXf> svd(ambiGains.transpose(), Eigen::ComputeThinU | Eigen::ComputeThinV);\n            // get ambiGains out of left / right matrices\n            ambiGains = svd.matrixV() * svd.matrixU().transpose();\n        }\n        \n        // normalization (only step required for 'SAD')\n        float norm = 4 * M_PI / numSpk;\n        ambiGains *= norm;\n        \n        return ambiGains;\n    }\n    \n    // get real spherical harmonics\n    void getRSH( const unsigned int n, const float azim, const float elev, Eigen::VectorXf & gains )\n    {\n        // init\n        float r;\n        float ri;\n        \n        // convert from polarch coord. system to boost's\n        float theta = deg2rad( 90 - elev );\n        float phi = deg2rad( azim );\n        \n        // order 0\n        gains[0] = 1.0 / sqrt(4*M_PI);\n        \n        // loop over spherical harmonic indices\n        int index = 1;\n        for( int nn = 1; nn <= n; nn += 1){\n            for( int m = -nn; m <= abs(nn); m += 1){\n                r = boost::math::spherical_harmonic_r(nn, m, theta, phi);\n                ri = boost::math::spherical_harmonic_i(nn, m, theta, phi);\n                \n                if( m != 0 ){ r = pow(-1, m) * sqrt(2) * r; }\n                ri = - sqrt(2) * ri;\n                \n                if( m < 0 ){ gains[index] = ri; }\n                else{ gains[index] = r; }\n                index++;\n            }\n        }\n    }\n    \n};\n\n#endif /* ambisonicDecoder_hpp */\n", "meta": {"hexsha": "b9e8a888189b1c4fe68dcfd6a2f245d383397d7f", "size": 3249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AmbisonicDecoder/ambisonicDecoder.hpp", "max_stars_repo_name": "PyrApple/ambisonicDecoder", "max_stars_repo_head_hexsha": "c33f0003384b748a01a14d30b92204f6b7615bc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AmbisonicDecoder/ambisonicDecoder.hpp", "max_issues_repo_name": "PyrApple/ambisonicDecoder", "max_issues_repo_head_hexsha": "c33f0003384b748a01a14d30b92204f6b7615bc3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AmbisonicDecoder/ambisonicDecoder.hpp", "max_forks_repo_name": "PyrApple/ambisonicDecoder", "max_forks_repo_head_hexsha": "c33f0003384b748a01a14d30b92204f6b7615bc3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7692307692, "max_line_length": 122, "alphanum_fraction": 0.4995383195, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5988871824199168}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <string>\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <istream>\n#include <random>\n#include <cmath>\n#include <Eigen/Dense>\n#include <boost/program_options.hpp>\n#include \"options.hpp\"\n#include \"options_parser.hpp\"\n#include \"LagrangianState.h\"\n#include \"ParticlePhysics.h\"\n#include \"TimeIntegration.h\"\n#include \"Inputfile.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char* argv[]) {\n  printf(\"*********** DRIVER PROGRAM FOR LAGRANGIAN PARTICLE SOLVER ***********\\n\\n\");\n\n  // Parse input file options\n  Options options;\n  if (!parseOptions(argc,argv,options)){\n   return 0;\n  }\n  cout << options << endl;\n\n  // Load state\n  MatrixXd input = load_csv<MatrixXd>(options.inputfile);\n  \n  // Pass parsed program options to simulation\n  LagrangianState state(input);\n  ParticlePhysics physics(options, state);\n  TimeIntegration integrator(options, physics, state);\n  \n  // Solve\n  integrator.euler();\n\n  // Output\n  state.writeXY(options.outputfile+\"_final.csv\");\n  \n  return 0;\n}\n", "meta": {"hexsha": "42fb48a1a8c0219ce09f04c4a33ee857affc886d", "size": 1067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/driver.cpp", "max_stars_repo_name": "adegenna/HardSphereDynamics", "max_stars_repo_head_hexsha": "0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T11:22:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T11:22:00.000Z", "max_issues_repo_path": "src/driver.cpp", "max_issues_repo_name": "adegenna/HardSphereDynamics", "max_issues_repo_head_hexsha": "0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/driver.cpp", "max_forks_repo_name": "adegenna/HardSphereDynamics", "max_forks_repo_head_hexsha": "0df9aefffbbc5c9c7b96fd689ccc4deb0f3e1507", "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": 22.2291666667, "max_line_length": 86, "alphanum_fraction": 0.7057169634, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.598887171329228}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_CENTERIZE_HPP\n#define MCL_CENTERIZE_HPP 1\n\n#include <Eigen/Core>\n#include <limits>\n\nnamespace mcl\n{\n\n// Moves all of the vertices so that the center of the mesh\n// is at the origin. Returns translation used.\ntemplate <typename DerivedV>\nstatic inline void centerize(Eigen::MatrixBase<DerivedV> &V)\n{\n\tint cols = V.cols();\n\tfor (int i=0; i<cols; ++i)\n\t{\n\t\ttypename DerivedV::Scalar ci = V.col(i).mean();\n\t\tV.col(i).array() -= ci;\n\t}\n} // end centerize\n\n// Returns the index of the center-most vertex\ntemplate <typename DerivedV>\nstatic inline int get_center_index(const Eigen::MatrixBase<DerivedV> &V)\n{\n\ttypedef typename DerivedV::Scalar T;\n\ttypedef Eigen::Matrix<T,3,1> Vec3t;\n\tint cols = std::min(3, int(V.cols()));\n\n\tVec3t center = Vec3t::Zero();\n\tfor (int i=0; i<cols; ++i)\n\t\tcenter[i] = V.col(i).mean();\n\n\tint min_idx = -1;\n\tT min_dist = std::numeric_limits<T>::max();\n\n\tint nv = V.rows();\n\tfor (int i=0; i<nv; ++i)\n\t{\n\t\tVec3t vi = Vec3t::Zero();\n\t\tfor (int j=0; j<cols; ++j)\n\t\t\tvi[j] = V(i,j);\n\n\t\tT dist = (center-vi).norm();\n\t\tif (dist < min_dist)\n\t\t{\n\t\t\tmin_dist = dist;\n\t\t\tmin_idx = i;\n\t\t}\n\t}\n\n\treturn min_idx;\n}\n\n// Scales all of the vertices in V to a target radius.\n// Returns the (uniform) scaling used.\ntemplate <typename DerivedV>\ninline double scale_to_sphere(Eigen::MatrixBase<DerivedV> &V, double radius)\n{\n\tusing namespace Eigen;\n\tcenterize(V);\n\tint dim = V.cols();\n\tint nv = V.rows();\n\tif (nv == 0 || dim < 2 || dim > 3)\n\t\treturn 1.0;\n\n\tauto get_v3 = [&](int idx)\n\t{\n\t\tVector3d v = Vector3d::Zero();\n\t\tfor(int i=0; i<dim; ++i)\n\t\t\tv[i]=V(idx,i);\n\t\treturn v;\n\t};\n\n\tdouble rad = 1e-20;\n\tfor (int i=0; i<nv; ++i)\n\t{\n\t\tVector3d v = get_v3(i);\n\t\tdouble d = v.norm();\n\t\tif (d > rad)\n\t\t\trad = d;\n\t}\n\n\tdouble scale = radius / rad;\n\tV *= scale;\n\treturn scale;\n\n} // end scale to sphere\n\n} // end ns mcl\n\n#endif\n", "meta": {"hexsha": "2e0183ce0a977cd3aa935cb3b4703513d1176350", "size": 1903, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/Centerize.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/Centerize.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/Centerize.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": 19.618556701, "max_line_length": 76, "alphanum_fraction": 0.633736206, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.598822393280753}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nint main() {\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(3, 2);\n    std::cout << \"A =\" << std::endl << A << std::endl;\n    Eigen::MatrixXd B = Eigen::MatrixXd::Random(2, 3);\n    std::cout << \"B =\" << std::endl << B << std::endl;\n    Eigen::MatrixXd C = A*B;\n    std::cout << \"C =\" << std::endl << C << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "a15657b736b3eb24ca7e9074eb47ccf5fbc6752d", "size": 377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Eigen/matrix_product.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Eigen/matrix_product.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Eigen/matrix_product.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 29.0, "max_line_length": 54, "alphanum_fraction": 0.5331564987, "num_tokens": 120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5988088812031215}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2000 - 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, University of Heidelberg, 2000 \n */ \n\n\n// @sect3{Include files}  \n\n// 前面几个文件已经在前面的例子中讲过了，因此不再做进一步的评论。\n\n#include <deal.II/base/quadrature_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_values.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.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\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n#include <fstream> \n\n// 从下面的include文件中我们将导入H1-conforming有限元形状函数的声明。这个有限元系列被称为  <code>FE_Q</code>  ，在之前的所有例子中已经被用来定义通常的双线性或三线性元素，但我们现在将用它来定义双二次元元素。\n\n#include <deal.II/fe/fe_q.h> \n\n// 我们不会像前面的例子那样从文件中读取网格，而是使用库中的一个函数生成网格。然而，我们将希望在每一步中写出局部细化的网格（只是网格，而不是解决方案），所以我们需要以下的include文件，而不是 <code>grid_in.h</code>  。\n\n#include <deal.II/grid/grid_out.h> \n\n// 当使用局部细化网格时，我们会得到所谓的<code>悬空节点</code>。然而，标准的有限元方法假定离散的解空间是连续的，所以我们需要确保悬挂节点上的自由度符合一些约束条件，这样全局解是连续的。我们也要在这个对象中存储边界条件。下面的文件包含一个用来处理这些约束条件的类。\n\n#include <deal.II/lac/affine_constraints.h> \n\n// 为了在本地细化我们的网格，我们需要一个来自库的函数，根据我们计算的误差指标来决定哪些单元需要细化或粗化。这个函数被定义在这里。\n\n#include <deal.II/grid/grid_refinement.h> \n\n// 最后，我们需要一个简单的方法来实际计算基于某种误差估计的细化指标。虽然一般来说，适应性是非常具体的问题，但以下文件中的误差指标通常会对一大类问题产生相当好的适应网格。\n\n#include <deal.II/numerics/error_estimator.h> \n\n// 最后，这和以前的程序一样。\n\nusing namespace dealii; \n// @sect3{The <code>Step6</code> class template}  \n\n// 主类又是几乎没有变化的。然而，我们增加了两项内容：我们增加了 <code>refine_grid</code> 函数，该函数用于自适应地细化网格（而不是之前例子中的全局细化），还有一个变量，它将保存约束条件。\n\ntemplate <int dim> \nclass Step6 \n{ \npublic: \n  Step6(); \n\n  void run(); \n\nprivate: \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  Triangulation<dim> triangulation; \n\n  FE_Q<dim>       fe; \n  DoFHandler<dim> dof_handler; \n\n// 这是主类中的新变量。我们需要一个对象，它持有一个约束条件的列表，以保持悬挂节点和边界条件。\n\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// @sect3{Nonconstant coefficients}  \n\n//非恒定系数的实现是逐字复制自  step-5  。\n\ntemplate <int dim> \ndouble coefficient(const Point<dim> &p) \n{ \n  if (p.square() < 0.5 * 0.5) \n    return 20; \n  else \n    return 1; \n} \n\n//  @sect3{The <code>Step6</code> class implementation}  \n// @sect4{Step6::Step6}  \n\n// 这个类的构造函数与之前的基本相同，但这一次我们要使用二次元。为此，我们只需用所需的多项式度数（这里是 <code>2</code> ）替换构造函数参数（在之前的所有例子中是 <code>1</code> ）。\n\ntemplate <int dim> \nStep6<dim>::Step6() \n  : fe(2) \n  , dof_handler(triangulation) \n{} \n\n//  @sect4{Step6::setup_system}  \n\n// 下一个函数设置了所有描述线性有限元问题的变量，如DoFHandler、矩阵和向量。与我们在 step-5 中所做的不同的是，我们现在还必须处理悬挂节点约束。这些约束几乎完全由库来处理，也就是说，你只需要知道它们的存在以及如何获得它们，但你不需要知道它们是如何形成的，也不需要知道对它们到底做了什么。\n\n// 在函数的开头，你会发现所有与 step-5 中相同的东西：设置自由度（这次我们有二次元，但从用户代码的角度看与线性--或任何其他程度的情况没有区别），生成稀疏模式，并初始化解和右手向量。请注意，现在每行的稀疏模式将有更多的条目，因为现在每个单元有9个自由度（而不是只有4个），它们可以相互耦合。\n\ntemplate <int dim> \nvoid Step6<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// 我们现在可以用悬挂节点的约束来填充AffineConstraints对象。由于我们将在一个循环中调用这个函数，所以我们首先清除上一个系统中的当前约束集，然后计算新的约束。\n\n  constraints.clear(); \n  DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n// 现在我们准备用指标0（整个边界）来插值边界值，并将得到的约束存储在我们的 <code>constraints</code> 对象中。请注意，我们并不像在前面的步骤中那样，在装配后应用边界条件：相反，我们将所有的约束条件放在AffineConstraints对象中的我们的函数空间。我们可以按任何顺序向AffineConstraints对象添加约束：如果两个约束发生冲突，那么约束矩阵要么中止，要么通过Assert宏抛出一个异常。\n\n  VectorTools::interpolate_boundary_values(dof_handler, \n                                           0, \n                                           Functions::ZeroFunction<dim>(), \n                                           constraints); \n\n// 在所有约束条件被添加之后，需要对它们进行排序和重新排列，以便更有效地执行一些操作。这种后处理是用 <code>close()</code> 函数完成的，之后就不能再添加任何约束了。\n\n  constraints.close(); \n\n// 现在我们首先建立我们的压缩稀疏模式，就像我们在前面的例子中做的那样。然而，我们并没有立即将其复制到最终的稀疏度模式中。 请注意，我们调用了make_sparsity_pattern的一个变体，它把AffineConstraints对象作为第三个参数。我们通过将参数 <code>keep_constrained_dofs</code> 设置为false（换句话说，我们永远不会写入矩阵中对应于受限自由度的条目），让该例程知道我们永远不会写入 <code>constraints</code> 所给的位置。如果我们在装配后对约束进行压缩，我们就必须通过 <code>true</code> 来代替，因为这样我们就会先写进这些位置，然后在压缩过程中再将它们设置为零。\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// 现在，矩阵的所有非零条目都是已知的（即那些来自定期组装矩阵的条目和那些通过消除约束引入的条目）。我们可以将我们的中间对象复制到稀疏模式中。\n\n  sparsity_pattern.copy_from(dsp); \n\n// 我们现在可以，最后，初始化稀疏矩阵。\n\n  system_matrix.reinit(sparsity_pattern); \n} \n// @sect4{Step6::assemble_system}  \n\n// 接下来，我们要对矩阵进行组装。然而，为了将每个单元上的本地矩阵和向量复制到全局系统中，我们不再使用手写的循环。相反，我们使用 AffineConstraints::distribute_local_to_global() ，在内部执行这个循环，同时对对应于受限自由度的行和列进行高斯消除。\n\n// 构成局部贡献的其余代码保持不变。然而，值得注意的是，在引擎盖下，有几件事与以前不同。首先，变量 <code>dofs_per_cell</code> 和返回值 <code>quadrature_formula.size()</code> 现在各为9，以前是4。引入这样的变量作为缩写是一个很好的策略，可以使代码在不同的元素下工作，而不需要改变太多的代码。其次， <code>fe_values</code> 对象当然也需要做其他事情，因为现在的形状函数是二次的，而不是线性的，在每个坐标变量中。不过，这也是完全由库来处理的事情。\n\ntemplate <int dim> \nvoid Step6<dim>::assemble_system() \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.n_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        { \n          const double current_coefficient = \n            coefficient(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 *              // a(x_q) \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              cell_rhs(i) += (1.0 *                               // f(x) \n                              fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                              fe_values.JxW(q_index));            // dx \n            } \n        } \n\n// 最后，将 @p cell_matrix 和 @p cell_rhs 中的贡献转移到全局对象中。\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// 现在我们已经完成了线性系统的组装。约束矩阵处理了应用边界条件的问题，也消除了悬挂的节点约束。受约束的节点仍然在线性系统中（在矩阵的对角线上有一个非零条目，选择的方式是使矩阵具有良好的条件，并且这一行的所有其他条目都被设置为零），但是计算出来的值是无效的（也就是说， <code>system_rhs</code> 中的相应条目目前是没有意义的）。我们在 <code>solve</code> 函数的最后为这些节点计算出正确的值。\n\n} \n// @sect4{Step6::solve}  \n\n// 我们继续逐步改进。解决线性系统的函数再次使用了SSOR预处理程序，除了我们必须加入悬空节点约束外，其他的都没有改变。如上所述，通过对矩阵的行和列进行特殊处理，从AffineConstraints对象中删除了对应于悬挂节点约束和边界值的自由度。这样一来，这些自由度的值在求解线性系统后就有了错误的、但定义明确的值。然后我们要做的就是利用约束条件给它们分配它们应该有的值。这个过程被称为 <code>distributing</code> 约束，从无约束的节点的值中计算出约束节点的值，只需要一个额外的函数调用，你可以在这个函数的末尾找到。\n\ntemplate <int dim> \nvoid Step6<dim>::solve() \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{Step6::refine_grid}  \n\n// 我们使用一个复杂的误差估计方案来细化网格，而不是全局细化。我们将使用KellyErrorEstimator类，该类实现了拉普拉斯方程的误差估计器；原则上它可以处理可变系数，但我们不会使用这些高级功能，而是使用其最简单的形式，因为我们对定量结果不感兴趣，只对生成局部细化网格的快速方法感兴趣。\n\n// 尽管Kelly等人得出的误差估计器最初是为拉普拉斯方程开发的，但我们发现它也很适合于为一类广泛的问题快速生成局部细化网格。这个误差估计器使用了解梯度在单元面上的跳跃（这是一个测量二阶导数的方法），并将其按单元的大小进行缩放。因此，它是对每个单元的解的局部平滑性的测量，因此可以理解，它对双曲运输问题或波浪方程也能产生合理的网格，尽管这些网格与专门针对该问题的方法相比肯定是次优的。因此，这个误差估计器可以理解为测试自适应程序的一种快速方法。\n\n// 估算器的工作方式是将描述自由度的 <code>DoFHandler</code> 对象和每个自由度的数值向量作为输入，为三角剖分的每个活动单元计算一个指标值（即每个活动单元一个数值）。为此，它需要两个额外的信息：一个面部正交公式，即 <code>dim-1</code> 维物体上的正交公式。我们再次使用3点高斯法则，这个选择与本程序中的双二次方有限元形状函数是一致和合适的。当然，什么是合适的正交规则取决于对误差估计器评估解场的方式的了解。如上所述，梯度的跳跃在每个面上都是集成的，对于本例中使用的二次元元素来说，这将是每个面上的二次元函数。然而，事实上，它是梯度跳动的平方，正如该类文件中所解释的那样，这是一个二次函数，对于它来说，3点高斯公式就足够了，因为它可以精确地整合5阶以下的多项式。)\n\n// 其次，该函数需要一个边界指示器的列表，用于那些我们施加了 $\\partial_n u(\\mathbf x) = h(\\mathbf x)$ 类诺伊曼值的边界，以及每个此类边界的函数 $h(\\mathbf x)$ 。这些信息由一个从边界指标到描述诺伊曼边界值的函数对象的映射来表示。在本例程序中，我们不使用诺伊曼边界值，所以这个映射是空的，实际上是在函数调用期望得到相应函数参数的地方使用映射的默认构造器构造的。\n\n// 输出是一个所有活动单元的值的向量。虽然非常精确地计算一个解的自由度的<b>value</b>可能是有意义的，但通常没有必要特别精确地计算一个单元上的解对应的<b>error indicator</b>。因此，我们通常使用一个浮点数的向量而不是一个双数的向量来表示误差指标。\n\ntemplate <int dim> \nvoid Step6<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// 上述函数为 <code>estimated_error_per_cell</code> 数组中的每个单元格返回一个错误指标值。现在的细化工作如下：细化那些误差值最高的30%的单元，粗化那些误差值最低的3%的单元。\n\n// 人们可以很容易地验证，如果第二个数字为零，这大约会导致在两个空间维度上的每一步的细胞翻倍，因为对于每一个30%的细胞，四个新的将被替换，而其余70%的细胞保持不动。在实践中，通常会产生一些更多的单元，因为不允许一个单元被精炼两次而相邻的单元没有被精炼；在这种情况下，相邻的单元也会被精炼。\n\n// 在许多应用中，被粗化的单元格数量将被设置为大于3%的数值。一个非零的值是很有用的，特别是当初始（粗）网格由于某种原因已经相当精细时。在这种情况下，可能有必要在某些区域进行细化，而在另一些区域进行粗化是有用的。在我们这里，初始网格是非常粗的，所以粗化只需要在一些可能发生过度细化的区域。因此，一个小的、非零的值在这里是合适的。\n\n// 下面的函数现在接受这些细化指标，并使用上述方法对三角形的一些单元进行细化或粗化标记。它来自一个实现了几种不同算法的类，可以根据单元的误差指标来细化三角形。\n\n  GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                  estimated_error_per_cell, \n                                                  0.3, \n                                                  0.03); \n\n// 在前一个函数退出后，一些单元被标记为细化，另一些单元被标记为粗化。然而，细化或粗化本身并没有被执行，因为有些情况下，进一步修改这些标志是有用的。在这里，我们不想做任何这样的事情，所以我们可以告诉三角计算执行单元格被标记的动作。\n\n  triangulation.execute_coarsening_and_refinement(); \n} \n// @sect4{Step6::output_results}  \n\n// 在每个网格的计算结束后，在我们继续下一个网格细化周期之前，我们要输出这个周期的结果。\n\n// 我们已经在 step-1 中看到了如何实现对网格本身的输出。在这里，我们改变一些东西。  <ol>  \n// <li>  我们使用两种不同的格式。gnuplot和VTU。 </li>  \n// <li>  我们在输出文件名中嵌入了周期号。 </li>  \n// <li>  对于gnuplot输出，我们设置了一个 GridOutFlags::Gnuplot 对象，以提供一些额外的可视化参数，使边缘看起来是弯曲的。这在  step-10  中有进一步的详细解释。 </li>  \n// </ol>  \ntemplate <int dim> \nvoid Step6<dim>::output_results(const unsigned int cycle) const \n{ \n  { \n    GridOut               grid_out; \n    std::ofstream         output(\"grid-\" + std::to_string(cycle) + \".gnuplot\"); \n    GridOutFlags::Gnuplot gnuplot_flags(false, 5); \n    grid_out.set_flags(gnuplot_flags); \n    MappingQGeneric<dim> mapping(3); \n    grid_out.write_gnuplot(triangulation, output, &mapping); \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(); \n\n    std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\"); \n    data_out.write_vtu(output); \n  } \n} \n// @sect4{Step6::run}  \n\n//  <code>main()</code> 之前的最后一个函数又是该类的主要驱动，  <code>run()</code>  。它与  step-5  的函数类似，只是我们在程序中再次生成一个文件，而不是从磁盘中读取，我们自适应地而不是全局地细化网格，并且我们在本函数中输出最终网格上的解决方案。\n\n// 该函数主循环的第一个块是处理网格生成。如果这是该程序的第一个循环，我们现在不是像上一个例子那样从磁盘上的文件中读取网格，而是再次使用库函数来创建它。域还是一个圆，中心在原点，半径为1（这是函数的两个隐藏参数，有默认值）。\n\n// 你会注意到粗略的网格比我们在前面的例子中从文件中读出的网格质量要差：单元格的形成不太平均。然而，使用库函数，这个程序在任何空间维度上都可以工作，而以前不是这样的。\n\n// 如果我们发现这不是第一个周期，我们要细化网格。与上一个例子程序中采用的全局细化不同，我们现在使用上述的自适应程序。\n\n// 循环的其余部分看起来和以前一样。\n\ntemplate <int dim> \nvoid Step6<dim>::run() \n{ \n  for (unsigned int cycle = 0; cycle < 8; ++cycle) \n    { \n      std::cout << \"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      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: \" << dof_handler.n_dofs() \n                << std::endl; \n\n      assemble_system(); \n      solve(); \n      output_results(cycle); \n    } \n} \n// @sect3{The <code>main</code> function}  \n\n// 主函数的功能与之前的例子相比没有改变，但我们采取了额外的谨慎措施。有时，会出现一些问题（比如写输出文件时磁盘空间不足，试图分配向量或矩阵时内存不足，或者由于某种原因我们无法从文件中读取或写入文件），在这些情况下，库会抛出异常。由于这些是运行时的问题，而不是可以一劳永逸的编程错误，这种异常在优化模式下不会被关闭，与我们用来测试编程错误的 <code>Assert</code> 宏相反。如果没有被捕获，这些异常会传播到 <code>main</code> 函数的调用树上，如果它们在那里也没有被捕获，程序就会被中止。在很多情况下，比如内存或磁盘空间不足，我们什么也做不了，但我们至少可以打印一些文字，试图解释程序失败的原因。下面显示了一种方法。以这种方式编写任何较大的程序当然是有用的，你可以通过或多或少地复制这个函数来做到这一点，但 <code>try</code> 块除外，它实际上编码了本应用程序所特有的功能。\n\nint main() \n{ \n\n// 这个函数布局的总体思路如下：让我们试着像以前那样运行程序......\n\n  try \n    { \n      Step6<2> laplace_problem_2d; \n      laplace_problem_2d.run(); \n    } \n\n// ......如果这应该是失败的，尽量收集尽可能多的信息。具体来说，如果被抛出的异常是一个从C++标准类派生出来的对象  <code>exception</code>, then we can use the <code>what</code>  成员函数，以获得一个描述异常被抛出原因的字符串。\n\n// deal.II的异常类都是从标准类派生出来的，特别是 <code>exc.what()</code> 函数将返回与使用 <code>Assert</code> 宏抛出的异常所产生的字符串大致相同。在前面的例子中，你已经看到了这种异常的输出，然后你知道它包含了异常发生的文件和行号，以及其他一些信息。这也是下面的语句会打印的内容。\n\n// 除此以外，除了用错误代码退出程序（这就是 <code>return 1;</code> 的作用），我们能做的并不多。\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\n// 如果在某处抛出的异常不是从标准 <code>exception</code> 类派生出来的对象，那么我们根本无法做任何事情。那么我们就简单地打印一个错误信息并退出。\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// 如果我们走到这一步，就没有任何异常传播到主函数上（可能有异常，但它们在程序或库的某个地方被捕获）。因此，程序按预期执行，我们可以无误返回。\n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "08679f5b68cb2cf5d4b18c1e859766216f5f2661", "size": 15389, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-6/step-6.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-6/step-6.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-6/step-6.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.7279236277, "max_line_length": 411, "alphanum_fraction": 0.6735330431, "num_tokens": 7671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.59872757008571}}
{"text": "/*\n * math.hpp\n *\n *  Created on: Apr 30, 2021\n *      Author: jelavice\n */\n\n#pragma once\n#include <string>\n#include <Eigen/Dense>\n#include \"icp_localization/common/time.hpp\"\n\nnamespace icp_loco {\n\n// Converts (roll, pitch, yaw) to a unit length quaternion. Based on the URDF\n// specification http://wiki.ros.org/urdf/XML/joint.\nEigen::Quaterniond fromRPY(double roll, double pitch, double yaw);\nEigen::Vector3d toRPY(const Eigen::Quaterniond &q);\nEigen::Quaterniond fromRPY(const Eigen::Vector3d &rpy);\n\ntemplate<typename T>\ninline T getRollFromQuat(T w, T x, T y, T z)\n{\n  return std::atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y));\n}\n\ntemplate<typename T>\ninline T getPitchFromQuat(T w, T x, T y, T z)\n{\n  return std::asin(2 * (w * y - x * z));\n}\n\ntemplate<typename T>\ninline T getYawFromQuat(T w, T x, T y, T z)\n{\n  return std::atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z));\n}\n\ntemplate<typename EigenVector>\nEigenVector interpolateVector(const EigenVector &vStart,  const EigenVector &vEnd, const Time &timeStart,\n                          const Time &timeEnd, const Time &queryTime)\n{\n  const double duration = toSeconds(timeEnd - timeStart);\n  const double factor = toSeconds(queryTime - timeStart) / duration;\n  const Eigen::Vector3d interp = vStart + (vEnd - vStart) * factor;\n  return interp;\n}\n\ntemplate<typename EigenQuaternion>\nEigenQuaternion interpolateQuaternion(const EigenQuaternion &qStart,  const EigenQuaternion &qEnd, const Time &timeStart,\n                          const Time &timeEnd, const Time &queryTime)\n{\n  const double duration = toSeconds(timeEnd - timeStart);\n  const double factor = toSeconds(queryTime - timeStart) / duration;\n  const Eigen::Quaterniond interp =\n      Eigen::Quaterniond(qStart)\n          .slerp(factor, Eigen::Quaterniond(qEnd));\n  return interp;\n}\n\ntemplate <typename T>\nEigen::Quaternion<T> angleAxisVectorToRotationQuaternion(\n    const Eigen::Matrix<T, 3, 1>& angle_axis) {\n  T scale = T(0.5);\n  T w = T(1.);\n  constexpr double kCutoffAngle = 1e-8;  // We linearize below this angle.\n  if (angle_axis.squaredNorm() > kCutoffAngle) {\n    const T norm = angle_axis.norm();\n    scale = sin(norm / 2.) / norm;\n    w = cos(norm / 2.);\n  }\n  const Eigen::Matrix<T, 3, 1> quaternion_xyz = scale * angle_axis;\n  return Eigen::Quaternion<T>(w, quaternion_xyz.x(), quaternion_xyz.y(),\n                              quaternion_xyz.z());\n}\n\n}  // namespace icp_loco\n", "meta": {"hexsha": "329788be0b820fbfa7ce4f0572ea4917d6ae71cf", "size": 2422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/icp_localization/common/math.hpp", "max_stars_repo_name": "ibrahimhroob/icp_localization", "max_stars_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T09:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:21:07.000Z", "max_issues_repo_path": "include/icp_localization/common/math.hpp", "max_issues_repo_name": "ibrahimhroob/icp_localization", "max_issues_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T20:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T09:54:42.000Z", "max_forks_repo_path": "include/icp_localization/common/math.hpp", "max_forks_repo_name": "ibrahimhroob/icp_localization", "max_forks_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:18:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:14:10.000Z", "avg_line_length": 31.0512820513, "max_line_length": 121, "alphanum_fraction": 0.6676300578, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5987200764956198}}
{"text": "#include <iostream>\n#include <ctime>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#define MATRIX_SIZE 50\n\nint main() {\n  \n  // 2 X 3 float mat\n  Eigen::Matrix<float, 2, 3> matrix_23;\n  \n  // 3 X 1 double mat\n  Eigen::Vector3d v_3d;\n\n  // 3 X 3 double mat\n  Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n\n  // dynamic matrix\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_dynamic;\n\n  Eigen::MatrixXd matrix_x;\n\n  // op matrix\n  matrix_23 << 1, 2, 3, 4, 5, 6;\n\n  std::cout << matrix_23 << std::endl << std::endl;\n\n  for (int i = 0; i < 1; i++) {\n    for (int j = 0; j < 2; j++) {\n      std::cout << matrix_23(i, j) << std::endl;\n    }\n  }\n\n  v_3d << 3, 2, 1;\n\n  // matrix_23 must float -> double \n  Eigen::Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n  std::cout << std::endl << result << std::endl << std::endl;\n\n  // Error!\n  // Eigen::Matrix<double, 2, 3> result = matrix_23.cast<double>() * v_3d;\n\n  matrix_33 = Eigen::Matrix3d::Random();\n  std::cout << matrix_33 << std::endl << std::endl << std::endl;\n\n  std::cout << matrix_33.transpose() << std::endl << std::endl;\n  std::cout << matrix_33.sum() << std::endl << std::endl;\n  std::cout << matrix_33.trace() << std::endl << std::endl;\n  std::cout << matrix_33.inverse() << std::endl << std::endl;\n  std::cout << matrix_33.determinant() << std::endl << std::endl;\n  std::cout << 10 * matrix_33 << std::endl << std::endl;\n\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver(matrix_33.transpose() * matrix_33);\n\n  std::cout << \"Eigen value = \" << std::endl << eigen_solver.eigenvalues() << std::endl << std::endl;\n  std::cout << \"Eigen vector = \" << std::endl << eigen_solver.eigenvectors() << std::endl << std::endl;\n\n  Eigen::Matrix<double, MATRIX_SIZE, MATRIX_SIZE> matrix_nn;\n  matrix_nn = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\n  Eigen::Matrix<double, MATRIX_SIZE, 1> v_nd;\n\n  v_nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n\n  std::clock_t time_stt = std::clock();\n\n  Eigen::Matrix<double, MATRIX_SIZE, 1> x = matrix_nn.inverse() * v_nd;\n  std::cout << \"time use in normal inverse is: \" \n    << 1000 * (std::clock() - time_stt) / (double)CLOCKS_PER_SEC \n    << \"ms\" << std::endl << std::endl;\n\n  time_stt = std::clock();\n  x = matrix_nn.colPivHouseholderQr().solve(v_nd);\n  std::cout << \"time use in Qr composition is: \" \n    << 1000 * (std::clock() - time_stt) / (double)CLOCKS_PER_SEC \n    << \"ms\" << std::endl << std::endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "1c6b5aa607e4088177faf15ea0c10d9fb03a5d20", "size": 2467, "ext": "cc", "lang": "C++", "max_stars_repo_path": "VisionSLAM14/ch3/EigenTest/eigen_matrix.cc", "max_stars_repo_name": "DLonng/Go", "max_stars_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2020-04-10T01:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:43:10.000Z", "max_issues_repo_path": "VisionSLAM14/ch3/EigenTest/eigen_matrix.cc", "max_issues_repo_name": "DLonng/Go", "max_issues_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-10T07:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T07:47:01.000Z", "max_forks_repo_path": "VisionSLAM14/ch3/EigenTest/eigen_matrix.cc", "max_forks_repo_name": "DLonng/Go", "max_forks_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-05T11:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T10:23:37.000Z", "avg_line_length": 29.7228915663, "max_line_length": 103, "alphanum_fraction": 0.6165383056, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5985335062296213}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MATH_STATISTICS_ANDERSON_DARLING_HPP\n#define BOOST_MATH_STATISTICS_ANDERSON_DARLING_HPP\n\n#include <cmath>\n#include <algorithm>\n#include <boost/math/statistics/univariate_statistics.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\nnamespace boost { namespace math { namespace statistics {\n\ntemplate<class RandomAccessContainer>\nauto anderson_darling_normality_statistic(RandomAccessContainer const & v,\n                                          typename RandomAccessContainer::value_type mu = std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN(),\n                                          typename RandomAccessContainer::value_type sd = std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())\n{\n    using Real = typename RandomAccessContainer::value_type;\n    using std::log;\n    using std::sqrt;\n    using boost::math::erfc;\n\n    if (std::isnan(mu)) {\n        mu = boost::math::statistics::mean(v);\n    }\n    if (std::isnan(sd)) {\n        sd = sqrt(boost::math::statistics::sample_variance(v));\n    }\n\n    typedef boost::math::policies::policy<\n          boost::math::policies::promote_float<false>,\n          boost::math::policies::promote_double<false> >\n          no_promote_policy;\n\n    // This is where Knuth's literate programming could really come in handy!\n    // I need some LaTeX. The idea is that before any observation, the ecdf is identically zero.\n    // So we need to compute:\n    // \\int_{-\\infty}^{v_0} \\frac{F(x)F'(x)}{1- F(x)} \\, \\mathrm{d}x, where F(x) := \\frac{1}{2}[1+\\erf(\\frac{x-\\mu}{\\sigma \\sqrt{2}})]\n    // Astonishingly, there is an analytic evaluation to this integral, as you can validate with the following Mathematica command:\n    // Integrate[(1/2 (1 + Erf[(x - mu)/Sqrt[2*sigma^2]])*Exp[-(x - mu)^2/(2*sigma^2)]*1/Sqrt[2*\\[Pi]*sigma^2])/(1 - 1/2 (1 + Erf[(x - mu)/Sqrt[2*sigma^2]])),\n    // {x, -Infinity, x0}, Assumptions -> {x0 \\[Element] Reals && mu \\[Element] Reals && sigma > 0}]\n    // This gives (for s = x-mu/sqrt(2sigma^2))\n    // -1/2 + erf(s) + log(2/(1+erf(s)))\n\n\n    Real inv_var_scale = 1/(sd*sqrt(Real(2)));\n    Real s0 = (v[0] - mu)*inv_var_scale;\n    Real erfcs0 = erfc(s0, no_promote_policy());\n    // Note that if erfcs0 == 0, then left_tail = inf (numerically), and hence the entire integral is numerically infinite:\n    if (erfcs0 <= 0) {\n        return std::numeric_limits<Real>::infinity();\n    }\n\n    // Note that we're going to add erfcs0/2 when we compute the integral over [x_0, x_1], so drop it here:\n    Real left_tail = -1 + log(Real(2));\n\n\n    // For the right tail, the ecdf is identically 1.\n    // Hence we need the integral:\n    // \\int_{v_{n-1}}^{\\infty} \\frac{(1-F(x))F'(x)}{F(x)} \\, \\mathrm{d}x\n    // This also has an analytic evaluation! It can be found via the following Mathematica command:\n    // Integrate[(E^(-(z^2/2)) *(1 - 1/2 (1 + Erf[z/Sqrt[2]])))/(Sqrt[2 \\[Pi]] (1/2 (1 + Erf[z/Sqrt[2]]))),\n    // {z, zn, \\[Infinity]}, Assumptions -> {zn \\[Element] Reals && mu \\[Element] Reals}]\n    // This gives (for sf = xf-mu/sqrt(2sigma^2))\n    // -1/2 + erf(sf)/2 + 2log(2/(1+erf(sf)))\n\n    Real sf = (v[v.size()-1] - mu)*inv_var_scale;\n    //Real erfcsf = erfc<Real>(sf, no_promote_policy());\n    // This is the actual value of the tail integral. However, the -erfcsf/2 cancels from the integral over [v_{n-2}, v_{n-1}]:\n    //Real right_tail = -erfcsf/2 + log(Real(2)) - log(2-erfcsf);\n\n    // Use erfc(-x) = 2 - erfc(x)\n    Real erfcmsf = erfc<Real>(-sf, no_promote_policy());\n    // Again if this is precisely zero then the integral is numerically infinite:\n    if (erfcmsf == 0) {\n        return std::numeric_limits<Real>::infinity();\n    }\n    Real right_tail = log(2/erfcmsf);\n\n    // Now we need each integral:\n    // \\int_{v_i}^{v_{i+1}} \\frac{(i+1/n - F(x))^2F'(x)}{F(x)(1-F(x))}  \\, \\mathrm{d}x\n    // Again we get an analytical evaluation via the following Mathematica command:\n    // Integrate[((E^(-(z^2/2))/Sqrt[2 \\[Pi]])*(k1 - F[z])^2)/(F[z]*(1 - F[z])),\n    // {z, z1, z2}, Assumptions -> {z1 \\[Element] Reals && z2 \\[Element] Reals &&k1 \\[Element] Reals}] // FullSimplify\n\n    Real integrals = 0;\n    int64_t N = v.size();\n    for (int64_t i = 0; i < N - 1; ++i) {\n        if (v[i] > v[i+1]) {\n            throw std::domain_error(\"Input data must be sorted in increasing order v[0] <= v[1] <= . . .  <= v[n-1]\");\n        }\n\n        Real k = (i+1)/Real(N);\n        Real s1 = (v[i+1]-mu)*inv_var_scale;\n        Real erfcs1 = erfc<Real>(s1, no_promote_policy());\n        Real term = k*(k*log(erfcs0*(-2 + erfcs1)/(erfcs1*(-2 + erfcs0))) + 2*log(erfcs1/erfcs0));\n\n        integrals += term;\n        s0 = s1;\n        erfcs0 = erfcs1;\n    }\n    integrals -= log(erfcs0);\n    return v.size()*(left_tail + right_tail + integrals);\n}\n\n}}}\n#endif\n", "meta": {"hexsha": "f892f27e0f6b326ac971d1479d7dd20318916298", "size": 5024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/anderson_darling.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": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/anderson_darling.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/anderson_darling.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": 44.4601769912, "max_line_length": 167, "alphanum_fraction": 0.6144506369, "num_tokens": 1592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5984784029612837}}
{"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 INTEGRATION_NEWTON_RAPHSON_HPP\n#define INTEGRATION_NEWTON_RAPHSON_HPP\n\n#include <iomanip>\n#include <boost/numeric/ublas/vector.hpp>\n#include <Eigen/Dense>\n\nnamespace integration {\n    namespace impl {\n        template< typename Vector >\n        struct VectorTraits\n        {\n        } ;\n\n        template<>\n        struct VectorTraits< Eigen::VectorXd >\n        {\n            typedef Eigen::MatrixXd Matrix ;\n            static double squared_norm( Eigen::VectorXd const& v ) { return v.squaredNorm() ; }\n        } ;\n    }\n\t\n\ttemplate< typename Vector, typename Function, typename Derivative >\n\tVector find_root_by_newton_raphson(\n\t\tFunction const& function,\n\t\tDerivative const& derivative,\n\t\tVector point,\n\t\tdouble tolerance\n\t) {\n        typedef typename impl::VectorTraits< Vector >::Matrix Matrix ;\n\n\t    // We compare against squared norm so square the tolerance here.\n\t\t//tolerance *= tolerance ;\n\t\tassert( tolerance > 0.0 ) ;\n\t\t\n\t\tVector function_value = function( point ) ;\n\t\tdouble max = std::max( std::abs( function_value.minCoeff() ), std::abs( function_value.maxCoeff() ) ) ;\n\t\tif( max >= tolerance ) {\n\t\t\t// The Newton-Raphson rule comes from the observation that if\n\t\t\t// f( x + h ) = f( x ) + (D_x f) (h) + higher order terms\n\t\t\t// and if f( x + h ) = 0\n\t\t\t// then h must satisfy (D_x f) (h) = -f( x ) + higher order terms.\n\t\t\t// At each step we solve this and move to the point x + h.\n\t\t\t// If the function is linear, this will actually get us to the root.\n\t\t\tEigen::ColPivHouseholderQR< Matrix > decomposer ;\n\t\t\tdo {\n\t\t\t\tdecomposer.compute( derivative( point ) ) ;\n                // The following line does not work with Eigen beta 1\n\t\t\t\t//point += decomposer.solve( -function_value ) ; // \n\t\t\t\tpoint = point + decomposer.solve( -function_value ) ;\n                function_value = function( point ) ;\n\t\t\t\tmax = std::max( std::abs( function_value.minCoeff() ), std::abs( function_value.maxCoeff() ) ) ;\n\t\t\t\t// std::cerr << \"NR: point = \" << point << \".\\n\" ;\n\t\t\t\t// std::cerr << \"NR: tolerance = \" << tolerance << \", value = \" << function_value << \", max coeff = \" << max << \".\\n\" ;\n\t\t\t}\n            while( max > tolerance ) ;\n\t\t}\n\t\treturn point ;\n\t}\n\n\ttemplate< typename FunctionAndDerivativeEvaluator, typename StoppingCondition >\n\ttypename FunctionAndDerivativeEvaluator::Vector find_root_by_newton_raphson(\n\t\tFunctionAndDerivativeEvaluator& evaluator,\n\t\ttypename FunctionAndDerivativeEvaluator::Vector point,\n\t\tStoppingCondition& stopping_condition\n\t)\n\t// The version of Newton-Raphson taking a seperate function and derivative argument\n\t// has the disadvantage that any calculations that are common between function\n\t// and derivative evaluations, cannot easily be shared.  This version allows\n\t// this work to be shared by using a single object to compute both function and derivative.\n\t// The evaluator must expose an Evaluation typedef.  This is an object with two methods,\n\t// get_value_of_function() and get_value_of_derivative().\n\t{\n\t\ttypedef typename FunctionAndDerivativeEvaluator::Vector Vector ;\n\t\ttypedef typename FunctionAndDerivativeEvaluator::Matrix Matrix ;\n\t\t\n\t\tevaluator.evaluate_at( point ) ;\n\n\t\tMatrix derivative_value ;\n\t\tEigen::ColPivHouseholderQR< Matrix > solver ;\n\n\t\tVector function_value = evaluator.get_value_of_function() ;\n\t\twhile( !stopping_condition( function_value ) ) {\n\t\t\t// The Newton-Raphson rule comes from the observation that if\n\t\t\t// f( x + h ) = f( x ) + (D_x f) (h) + higher order terms\n\t\t\t// and if f( x + h ) = 0\n\t\t\t// then h must satisfy (D_x f) (h) = -f( x ) + higher order terms.\n\t\t\t// At each step we solve this and move to the point x + h.\n\t\t\t// If the function is linear, this will actually get us to the root.\n\t\t\tderivative_value = evaluator.get_value_of_first_derivative() ;\n\t\t\tsolver.compute( derivative_value ) ;\n\t\t\tpoint += solver.solve( -function_value ) ;\n\t\t\tevaluator.evaluate_at( point ) ;\n\t\t\t\t// std::cerr << \"NR: point = \" << point << \".\\n\" ;\n\t\t\t\t// std::cerr << \"NR: tolerance = \" << tolerance << \", value = \" << function_value << \", max coeff = \" << max << \".\\n\" ;\n\t\t\tfunction_value = evaluator.get_value_of_function() ;\n\t\t}\n\t\treturn point ;\n\t}\n\n\tnamespace impl {\n\t\ttemplate< typename FunctionAndDerivativeEvaluator >\n\t\tstruct FunctionNearZeroStoppingCondition\n\t\t{\n\t\t\ttypedef typename FunctionAndDerivativeEvaluator::Vector Vector ;\n\t\t\ttypedef typename FunctionAndDerivativeEvaluator::Matrix Matrix ;\n\t\t\tFunctionNearZeroStoppingCondition( double tolerance, std::size_t max_iterations ): m_tolerance( tolerance ), m_max_iterations( 10000 ), m_iteration( 0 ) {}\n\t\t\tbool operator()(\n\t\t\t\tVector const& value_of_function\n\t\t\t) {\n\t\t\t\tstd::cerr << \"iteration \" << m_iteration << \": value is \" << std::resetiosflags( std::ios::floatfield ) << value_of_function << \".\\n\" ;\n\t\t\t\treturn\n\t\t\t\t\t( ++m_iteration > m_max_iterations )\n\t\t\t\t\t||\n\t\t\t\t\t( std::max( std::abs( value_of_function.minCoeff() ), std::abs( value_of_function.maxCoeff() ) ) < m_tolerance )\n\t\t\t\t;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tdouble const m_tolerance ;\n\t\t\tstd::size_t const m_max_iterations ;\n\t\t\tstd::size_t m_iteration ;\n\t\t} ;\n\t}\n\n\ttemplate< typename FunctionAndDerivativeEvaluator >\n\ttypename FunctionAndDerivativeEvaluator::Vector find_root_by_newton_raphson(\n\t\tFunctionAndDerivativeEvaluator& evaluator,\n\t\ttypename FunctionAndDerivativeEvaluator::Vector point,\n\t\tdouble tolerance = 0.0000000001,\n\t\tstd::size_t max_iterations = 10000\n\t) {\n\t\tassert( tolerance > 0.0 ) ;\n\t\timpl::FunctionNearZeroStoppingCondition< FunctionAndDerivativeEvaluator > stopping_condition( tolerance, max_iterations ) ;\n\t\treturn find_root_by_newton_raphson(\n\t\t\tevaluator,\n\t\t\tpoint,\n\t\t\tstopping_condition\n\t\t) ;\n\t}\n\n    // Specialise for 1d, where Vector == double\n\ttemplate< typename Function, typename Derivative >\n\tdouble find_root_by_newton_raphson (\n\t\tFunction const& function,\n\t\tDerivative const& derivative,\n\t\tdouble point,\n\t\tdouble const tolerance\n\t) {\n\t\tdouble function_value = function( point ) ;\n\t\tif( std::abs( function_value ) >= tolerance ) {\n\t\t\t// The Newton-Raphson rule comes from the observation that if\n\t\t\t// f( x + h ) = f( x ) + (D_x f) (h) + higher order terms\n\t\t\t// and if f( x + h ) = 0\n\t\t\t// then h must satisfy (D_x f) (h) = -f( x ) + higher order terms.\n\t\t\t// i.e. h ~ - f(x) / D_x f since we are in the scalar case.\n\t\t\t// At each step we solve this and move to the point x + h.\n\t\t\t// If the function is linear or quadratic, this will actually get us there.\n\t\t\tdo {\n\t\t\t\tpoint -= function_value / derivative( point ) ;\n                function_value = function( point ) ;\n\t\t\t}\n            while( std::abs( function_value ) >= tolerance ) ;\n\t\t}\n\t\treturn point ;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "b2fdd4b1d1c0f25fcc368fc4abe34629a84676e0", "size": 6825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "integration/include/integration/NewtonRaphson.hpp", "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": "integration/include/integration/NewtonRaphson.hpp", "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": "integration/include/integration/NewtonRaphson.hpp", "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": 38.7784090909, "max_line_length": 158, "alphanum_fraction": 0.6778021978, "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5984783954748938}}
{"text": "/*\n * Copyright Nick Thompson, John Maddock 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#define BOOST_MATH_GENERATE_DAUBECHIES_GRID\n\n#include <iostream>\n#include <vector>\n#include <numeric>\n#include <list>\n#include <cmath>\n#include <cassert>\n#include <fstream>\n#include <Eigen/Eigenvalues>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/core/demangle.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/filters/daubechies.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<237, boost::multiprecision::backends::digit_base_2, std::allocator<char>, boost::int32_t, -262142, 262143>,  boost::multiprecision::et_off> octuple_type;\n\n#ifdef BOOST_HAS_FLOAT128\ntypedef boost::multiprecision::float128 float128_t;\n#else\ntypedef boost::multiprecision::cpp_bin_float_quad float128_t;\n#endif\n\ntemplate<class Real, int p>\nstd::list<std::vector<Real>> integer_grid()\n{\n    std::cout << std::setprecision(std::numeric_limits<Real>::digits10 + 3);\n    using std::abs;\n    using std::sqrt;\n    using std::pow;\n    std::list<std::vector<Real>> grids;\n\n    auto c = boost::math::filters::daubechies_scaling_filter<Real, p>();\n    for (auto & x : c)\n    {\n        x *= boost::math::constants::root_two<Real>();\n    }\n    std::cout << \"\\n\\nTaps in filter = \" << c.size() << \"\\n\";\n\n\n    Eigen::Matrix<Real, 2*p - 2, 2*p-2> A;\n    for (int j = 0; j < 2*p-2; ++j) {\n        for (int k = 0; k < 2*p-2; ++k) {\n            if ( (2*j-k + 1) < 0 || (2*j - k  + 1) >= 2*p)\n            {\n                A(j,k) = 0;\n            }\n            else {\n                A(j,k) = c[2*j - k + 1];\n            }\n        }\n    }\n\n    Eigen::EigenSolver<decltype(A)> es(A);\n\n    auto complex_eigs = es.eigenvalues();\n\n    std::vector<Real> eigs(complex_eigs.size(), std::numeric_limits<Real>::quiet_NaN());\n\n    std::cout << \"Eigenvalues = {\";\n    for (long i = 0; i < complex_eigs.size(); ++i) {\n        assert(abs(complex_eigs[i].imag()) < std::numeric_limits<Real>::epsilon());\n        eigs[i] = complex_eigs[i].real();\n        std::cout << eigs[i] << \", \";\n    }\n    std::cout << \"}\\n\";\n\n    // Eigen does not sort the eigenpairs by any criteria on the eigenvalues.\n    // In any case, even if it did, some of the eigenpairs do not correspond to derivatives anyway.\n    for (size_t j = 0; j < eigs.size(); ++j) {\n        auto f = [&](Real x) {\n                 return abs(x - Real(1)/Real(1 << j) ) < sqrt(std::numeric_limits<Real>::epsilon());\n                 };\n        auto it = std::find_if(eigs.begin(), eigs.end(), f);\n        if (it == eigs.end()) {\n            std::cout << \"couldn't find eigenvalue \" << Real(1)/Real(1 << j) << \"\\n\";\n            continue;\n        }\n        size_t idx = std::distance(eigs.begin(), it);\n        std::cout << \"Eigenvector for derivative \" << j << \" is at index \" << idx << \"\\n\";\n        auto eigenvector_matrix = es.eigenvectors();\n        auto complex_eigenvec = eigenvector_matrix.col(idx);\n\n        std::vector<Real> eigenvec(complex_eigenvec.size() + 2, std::numeric_limits<Real>::quiet_NaN());\n        eigenvec[0] = 0;\n        eigenvec[eigenvec.size()-1] = 0;\n        for (size_t i = 0; i < eigenvec.size() - 2; ++i) {\n            assert(abs(complex_eigenvec[i].imag()) < std::numeric_limits<Real>::epsilon());\n            eigenvec[i+1] = complex_eigenvec[i].real();\n        }\n\n        Real sum = 0;\n        for(size_t k = 1; k < eigenvec.size(); ++k) {\n            sum += pow(k, j)*eigenvec[k];\n        }\n\n        Real alpha = pow(-1, j)*boost::math::factorial<Real>(j)/sum;\n\n        for (size_t i = 1; i < eigenvec.size(); ++i) {\n            eigenvec[i] *= alpha;\n        }\n\n\n        std::cout << \"Eigenvector = {\";\n        for (size_t i = 0; i < eigenvec.size() -1; ++i) {\n            std::cout << eigenvec[i] << \", \";\n        }\n        std::cout << eigenvec[eigenvec.size()-1] << \"}\\n\";\n\n        sum = 0;\n        for(size_t k = 1; k < eigenvec.size(); ++k) {\n            sum += pow(k, j)*eigenvec[k];\n        }\n\n        std::cout << \"Moment sum = \" << sum << \", expected = \" << pow(-1, j)*boost::math::factorial<Real>(j) << \"\\n\";\n\n        assert(abs(sum - pow(-1, j)*boost::math::factorial<Real>(j))/abs(pow(-1, j)*boost::math::factorial<Real>(j)) < sqrt(std::numeric_limits<Real>::epsilon()));\n\n        grids.push_back(eigenvec);\n    }\n\n\n    return grids;\n}\n\ntemplate<class Real, int p>\nvoid write_grid(std::ofstream & fs)\n{\n    auto grids = integer_grid<Real, p>();\n    size_t j = 0;\n    fs << std::setprecision(std::numeric_limits< boost::multiprecision::cpp_bin_float_quad>::max_digits10);\n    for (auto it = grids.begin(); it != grids.end(); ++it) \n    {\n       auto const& grid = *it;\n       fs << \"template <typename Real> struct daubechies_scaling_integer_grid_imp <Real, \" << p << \", \";\n      fs << j << \"> { static inline constexpr std::array<Real, \" << grid.size() << \"> value = { \";\n      for (size_t i = 0; i < grid.size() -1; ++i){\n        fs << \"C_(\" << static_cast<float128_t>(grid[i]) << \"), \";\n      }\n      fs << \"C_(\" << static_cast<float128_t>(grid[grid.size()-1]) << \") }; };\\n\";\n      ++j;\n    }\n}\n\nint main()\n{\n    constexpr const size_t p_max = 18;\n    std::ofstream fs{\"daubechies_scaling_integer_grid.hpp\"};\n    fs << \"/*\\n\"\n       << \" * Copyright Nick Thompson, John Maddock 2020\\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       << \"// THIS FILE GENERATED BY EXAMPLE/DAUBECHIES_SCALING_INTEGER_GRID.CPP, DO NOT EDIT.\\n\"\n       << \"#ifndef BOOST_MATH_DAUBECHIES_SCALING_INTEGER_GRID_HPP\\n\"\n       << \"#define BOOST_MATH_DAUBECHIES_SCALING_INTEGER_GRID_HPP\\n\"\n       << \"#include <array>\\n\"\n       << \"#include <float.h>\\n\"\n       << \"#include <boost/config.hpp>\\n\"\n       << \"/*\\n\"\n       << \"In order to keep the character count as small as possible and speed up\\n\"\n       << \"compiler parsing times, we define a macro C_ which appends an appropriate\\n\"\n       << \"suffix to each literal, and then casts it to type Real.\\n\"\n       << \"The suffix is as follows:\\n\\n\"\n       << \"* Q, when we have __float128 support.\\n\"\n       << \"* L, when we have either 80 or 128 bit long doubles.\\n\"\n       << \"* Nothing otherwise.\\n\"\n       << \"*/\\n\\n\"\n       << \"#ifdef BOOST_HAS_FLOAT128\\n\"\n       << \"#  define C_(x) static_cast<Real>(x##Q)\\n\"\n       << \"#elif (LDBL_MANT_DIG > DBL_MANT_DIG)\\n\"\n       << \"#  define C_(x) static_cast<Real>(x##L)\\n\"\n       << \"#else\\n\"\n       << \"#  define C_(x) static_cast<Real>(x)\\n\"\n       << \"#endif\\n\\n\"\n       << \"namespace boost::math::detail {\\n\\n\"\n       << \"template <typename Real, int p, int order> struct daubechies_scaling_integer_grid_imp;\\n\\n\";\n\n    fs << std::hexfloat << std::setprecision(std::numeric_limits<boost::multiprecision::cpp_bin_float_quad>::max_digits10);\n\n    boost::hana::for_each(std::make_index_sequence<p_max>(), [&](auto idx){\n        write_grid<octuple_type, idx+2>(fs);\n    });\n\n    fs << \"\\n\\ntemplate <typename Real, unsigned p, unsigned order>\\n\"\n       << \"constexpr inline std::array<Real, 2*p> daubechies_scaling_integer_grid()\\n\"\n       << \"{\\n\"\n       << \"    static_assert(sizeof(Real) <= 16, \\\"Integer grids only computed up to 128 bits of precision.\\\");\\n\"\n       << \"    static_assert(p <= \" << p_max + 1 << \", \\\"Integer grids only implemented up to \" << p_max + 1 << \".\\\");\\n\"\n       << \"    static_assert(p > 1, \\\"Integer grids only implemented for p >= 2.\\\");\\n\"\n       << \"    return daubechies_scaling_integer_grid_imp<Real, p, order>::value;\\n\"\n       << \"}\\n\\n\";\n\n    fs << \"} // namespaces\\n\";\n    fs << \"#endif\\n\";\n    fs.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "c06bad5f1a9549407c273a13794973957ba85cfe", "size": 8125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/daubechies_wavelets/daubechies_scaling_integer_grid.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_scaling_integer_grid.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": "Libs/boost_1_76_0/libs/math/example/daubechies_wavelets/daubechies_scaling_integer_grid.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 37.9672897196, "max_line_length": 228, "alphanum_fraction": 0.5806769231, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.598478393771581}}
{"text": "/* \n * Definition of the geometry routines\n * Copyright (C) 2019  Robin Scheibler, Cyril Cadoux\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 * You should have received a copy of the MIT License along with this program. If\n * not, see <https://opensource.org/licenses/MIT>.\n */\n\n#ifndef __GEOMETRY_H__\n#define __GEOMETRY_H__\n\n#include <Eigen/Dense>\n\n#include \"common.hpp\"\n\nint ccw3p(const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p3);\n\nint check_intersection_2d_segments(\n    const Eigen::Vector2f &a1, const Eigen::Vector2f &a2,\n    const Eigen::Vector2f &b1, const Eigen::Vector2f &b2\n    );\n\nint intersection_2d_segments(\n    const Eigen::Vector2f &a1, const Eigen::Vector2f &a2,\n    const Eigen::Vector2f &b1, const Eigen::Vector2f &b2,\n    Eigen::Ref<Eigen::Vector2f> intersection\n    );\n\nint intersection_3d_segment_plane(\n    const Eigen::Vector3f &a1, const Eigen::Vector3f &a2,\n    const Eigen::Vector3f &p, const Eigen::Vector3f &normal,\n    Eigen::Ref<Eigen::Vector3f> intersection);\n\nEigen::Vector3f cross(Eigen::Vector3f v1, Eigen::Vector3f v2);\n\nint is_inside_2d_polygon(const Eigen::Vector2f &p,\n    const Eigen::Matrix<float,2,Eigen::Dynamic> &corners);\n    \nfloat area_2d_polygon(const Eigen::Matrix<float, 2, Eigen::Dynamic> &corners);\n\nfloat cos_angle_between(const Eigen::VectorXf & v1,\n  const Eigen::VectorXf & v2);\n\nfloat dist_line_point(const Eigen::VectorXf & start,\n  const Eigen::VectorXf & end,\n  const Eigen::VectorXf & point);\n\ntemplate<size_t D>\nclass Line\n{\n  Vectorf<D> unit_vec;  // direction of the Line\n  Vectorf<D> origin;  // point in the Line\n\n  public:\n  Line(const Vectorf<D> &_unit, const Vectorf<D> &_p) : unit_vec(_unit), origin(_p) {}\n  ~Line() {}\n\n  // Create a line from two points\n  static Line from_points(const Vectorf<D> &_origin, const Vectorf<D> &_other_point)\n  {\n    return Line((_other_point - _origin).normalize(), _origin);\n  }\n\n  // returns the distance between the line and a point p\n  float distance(const Vectorf<D> &p)\n  {\n    return (p - project(p)).norm();\n  }\n\n  // signed distance from line origin to the projection of point p onto the line\n  float projected_distance(const Vectorf<D> &p)\n  {\n    return (p - origin).adjoint() * unit_vec; \n  }\n\n  // returns orthogonal projection of p onto the line\n  Vectorf<D> project(const Vectorf<D> &p)\n  {\n    return origin + projected_distance(p) * unit_vec;\n  }\n\n  // returns the symmetric point with respect to line\n  Vectorf<D> reflect(const Vectorf<D> &p)\n  {\n    return 2.f * project(p) - p;\n  }\n};\n\n#include \"geometry.cpp\"\n\n#endif // __GEOMETRY_H__\n", "meta": {"hexsha": "d15be6542b99a45689721aafee706447f6d71a3e", "size": 3625, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pyroomacoustics/libroom_src/geometry.hpp", "max_stars_repo_name": "HemaZ/pyroomacoustics", "max_stars_repo_head_hexsha": "c401f829c71ff03a947f68f9b6b2f48346ae84b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 915.0, "max_stars_repo_stars_event_min_datetime": "2016-02-08T08:10:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:33:21.000Z", "max_issues_repo_path": "pyroomacoustics/libroom_src/geometry.hpp", "max_issues_repo_name": "zha80052/pyroomacoustics", "max_issues_repo_head_hexsha": "15a86425b68969b2109860ca3614f0cbf92b1bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212.0, "max_issues_repo_issues_event_min_datetime": "2017-02-06T13:06:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:32:15.000Z", "max_forks_repo_path": "pyroomacoustics/libroom_src/geometry.hpp", "max_forks_repo_name": "zha80052/pyroomacoustics", "max_forks_repo_head_hexsha": "15a86425b68969b2109860ca3614f0cbf92b1bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 513.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T05:41:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:41:09.000Z", "avg_line_length": 32.9545454545, "max_line_length": 91, "alphanum_fraction": 0.7211034483, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5984781054722967}}
{"text": "<%\ncfg['compiler_args'] = ['-std=c++11']\ncfg['include_dirs'] = ['./eigen']\nsetup_pybind11(cfg)\n%>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <chrono>\n#include <random>\n#include <Eigen/Cholesky> \n#include <Eigen/LU>\n#include <pybind11/functional.h>\n\nnamespace py = pybind11;\n \n    \n// sghmc function\nfloat sghmc(const std::function<float(float)> &U, const std::function<float(float)> &gradU, float M, float epsilon, int m, float theta, float C, float V) {\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    std::default_random_engine generator(seed);\n    std::normal_distribution<double> distribution (0, 1);\n    float r;\n    r=distribution(generator)*pow(M,0.5);\n    float Ax;\n    Ax=pow(2*(C-0.5*V*epsilon)*epsilon,0.5);\n    for (int i=0; i<m-1; ++i){\n        r=r-gradU(theta)*epsilon-r*C*epsilon+distribution(generator)*Ax;\n        theta=theta+(r/M)*epsilon;\n        }\n    return theta;\n}\n\nPYBIND11_PLUGIN(sghmcwrap) {\n    pybind11::module m(\"sghmcwrap\", \"auto-compiled c++ extension of sghmc\");\n    m.def(\"sghmc\", &sghmc);\n    return m.ptr();\n}", "meta": {"hexsha": "150af9000c407f723c17b39fa327946fecd703a2", "size": 1107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c_sghmc/sghmcwrap.cpp", "max_stars_repo_name": "astr93/c_sghmc", "max_stars_repo_head_hexsha": "45529d7742d30ee23983b7ce5e413667ecb23b64", "max_stars_repo_licenses": ["MIT"], "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_sghmc/sghmcwrap.cpp", "max_issues_repo_name": "astr93/c_sghmc", "max_issues_repo_head_hexsha": "45529d7742d30ee23983b7ce5e413667ecb23b64", "max_issues_repo_licenses": ["MIT"], "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_sghmc/sghmcwrap.cpp", "max_forks_repo_name": "astr93/c_sghmc", "max_forks_repo_head_hexsha": "45529d7742d30ee23983b7ce5e413667ecb23b64", "max_forks_repo_licenses": ["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.1315789474, "max_line_length": 155, "alphanum_fraction": 0.6603432701, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5984577036489919}}
{"text": "/**\n   \\file bfgs.hpp\n   \\brief BFGS optimization method\n   \\author Junhua Gu\n */\n\n#ifndef BFGS_METHOD\n#define BFGS_METHOD\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <limits>\n#include <cstdlib>\n#include <core/opt_traits.hpp>\n#include \"../linmin/linmin.hpp\"\n#include <math/num_diff.hpp>\n#include <cassert>\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <algorithm>\n/*\n *\n*/\n#include <iostream>\nusing std::cerr;\nusing std::endl;\n\nnamespace opt_utilities\n{\n\n  template <typename rT,typename pT>\n  class bfgs_method\n    :public opt_method<rT,pT>\n  {\n  public:\n    pT start_point;\n    rT threshold;\n    func_obj<rT,pT>* p_fo;\n    optimizer<rT,pT>* p_optimizer;\n    typedef typename element_type_trait<pT>::element_type element_type;\n    element_type* mem_pool;\n    element_type** invBk;\n    bool bstop;\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 \"bfgs\";\n    }\n\n  public:\n    bfgs_method()\n      :threshold(1e-5),p_fo(0),p_optimizer(0),\n       mem_pool(0),invBk(0)\n    {\n      \n    }\n    \n    virtual ~bfgs_method()\n    {     \n      destroy_workspace();\n    };\n    \n    bfgs_method(const bfgs_method<rT,pT>& rhs)\n      :p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n       threshold(rhs.threshold),mem_pool(0),invBk(0)\n    {\n    }\n\n    bfgs_method<rT,pT>& operator=(const bfgs_method<rT,pT>& rhs)\n    {\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      threshold=rhs.threshold;\n    }\n\n    opt_method<rT,pT>* do_clone()const\n    {\n      return new bfgs_method<rT,pT>(*this);\n    }\n    \n    void init_workspace(int n)\n    {\n      destroy_workspace();\n      mem_pool=new element_type[n*n];\n      invBk=new element_type*[n];\n\n      for(size_t i=0;i!=n;++i)\n\t{\n\t  invBk[i]=mem_pool+i*n;\n\t}\n      for(size_t i=0;i!=n;++i)\n\t{\n\t  for(size_t j=0;j!=n;++j)\n\t    {\n\t      invBk[i][j]=(i==j?1:0);\n\t    }\n\t}\n    }\n\n    void destroy_workspace()\n    {\n      delete[] mem_pool;\n      delete[] invBk;\n    }\n\n  public:\n    \n    void do_set_start_point(const pT& p)\n    {\n      start_point=p;\n      init_workspace(get_size(p));\n    }\n\n    pT do_get_start_point()const\n    {\n      return start_point;\n    }\n    \n    void do_set_precision(rT t)\n    {\n      threshold=t>=0?t:-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    pT do_optimize()\n    {\n      pT s;\n      pT& p=start_point;\n      resize(s,get_size(start_point));\n      pT old_grad;\n      pT y;\n      resize(old_grad,get_size(start_point));\n      resize(y,get_size(start_point));\n      for(;;)\n\t{\n\t  for(size_t i=0;i!=get_size(p);++i)\n\t    {\n\t      set_element(old_grad,i,gradient(*p_fo,start_point,i));\n\t      set_element(s,i,0);\n\t      for(size_t j=0;j!=get_size(p);++j)\n\t\t{\n\t\t  s[i]+=invBk[i][j]*old_grad[j];\n\t\t}\n\t    }\n\t  double fret;\n\t  linmin(start_point,s,fret,*p_fo);\n\t  \n\t  for(size_t i=0;i!=get_size(p);++i)\n\t    {\n\t      set_element(y,i,gradient(*p_fo,start_point,i)-get_element(old_grad,i));\n\t    }\n\t  \n\t  rT sy=0;\n\t  pT invBy;\n\t  pT yinvB;\n\t  resize(invBy,get_size(p));\n\t  resize(yinvB,get_size(p));\n\t  for(size_t i=0;i!=get_size(p);++i)\n\t    {\n\t      sy+=s[i]*y[i];\n\t      for(size_t j=0;j!=get_size(p);++j)\n\t\t{\n\t\t  invBy[i]+=invBk[i][j]*y[j];\n\t\t  yinvB[i]+=y[j]*invBk[j][i];\n\t\t}\n\t    }\n\t  if(sy<threshold&&sy>-threshold)\n\t    {\n\t      return start_point;\n\t    }\n\t  rT yinvBy=0;\n\t  for(size_t i=0;i!=get_size(p);++i)\n\t    {\n\t      yinvBy+=invBy[i]*y[i];\n\t    }\n\t  \n\t  for(size_t i=0;i<get_size(p);++i)\n\t    {\n\t      for(size_t j=0;j<get_size(p);++j)\n\t\t{\n\t\t  invBk[i][j]+=((sy+yinvBy)*s[i]*s[j]/(sy*sy)-(invBy[i]*s[j]+s[i]*yinvB[j])/(sy));\n\t\t}\n\t    }\n\t}\n\treturn start_point;\n    }\n    \n    void do_stop()\n    {\n      bstop=true;\n    }\n\n  };\n\n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "8162d7b29a202428fc1ff5914f216432e8b14721", "size": 3946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/bfgs/bfgs.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/bfgs/bfgs.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/bfgs/bfgs.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": 18.1843317972, "max_line_length": 84, "alphanum_fraction": 0.5658895084, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5984576982850653}}
{"text": "// poisson_reconstruction.cpp\n\n//----------------------------------------------------------\n// Poisson Delaunay Reconstruction method.\n// Reads a point set or a mesh's set of vertices, reconstructs a surface using Poisson,\n// and saves the surface.\n// Output format is .off.\n//----------------------------------------------------------\n// poisson_reconstruction file_in file_out [options]\n\n// CGAL\n#include <CGAL/AABB_tree.h> // must be included before kernel\n#include <CGAL/AABB_traits.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Timer.h>\n#include <CGAL/trace.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Surface_mesh_default_triangulation_3.h>\n#include <CGAL/make_surface_mesh.h>\n#include <CGAL/Poisson_implicit_surface_3.h>\n#include <CGAL/IO/output_surface_facets_to_polyhedron.h>\n#include <CGAL/Poisson_reconstruction_function.h>\n#include <CGAL/Point_with_normal_3.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <CGAL/compute_average_spacing.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n\n#include <deque>\n#include <cstdlib>\n#include <fstream>\n#include <math.h>\n#include <boost/foreach.hpp>\n\n// ----------------------------------------------------------------------------\n// Types\n// ----------------------------------------------------------------------------\n\n// kernel\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\n// Simple geometric types\ntypedef Kernel::FT FT;\ntypedef Kernel::Point_3 Point;\ntypedef Kernel::Vector_3 Vector;\ntypedef CGAL::Point_with_normal_3<Kernel> Point_with_normal;\ntypedef Kernel::Sphere_3 Sphere;\ntypedef std::deque<Point_with_normal> PointList;\n\n// polyhedron\ntypedef CGAL::Polyhedron_3<Kernel> Polyhedron;\n\n// Poisson implicit function\ntypedef CGAL::Poisson_reconstruction_function<Kernel> Poisson_reconstruction_function;\n\n// Surface mesher\ntypedef CGAL::Surface_mesh_default_triangulation_3 STr;\ntypedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;\ntypedef CGAL::Poisson_implicit_surface_3<Kernel, Poisson_reconstruction_function> Surface_3;\n\n// AABB tree\ntypedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;\ntypedef CGAL::AABB_traits<Kernel, Primitive> AABB_traits;\ntypedef CGAL::AABB_tree<AABB_traits> AABB_tree;\n\nstruct Counter {\n  std::size_t i, N;\n  Counter(std::size_t N)\n    : i(0), N(N)\n  {}\n\n  void operator()()\n  {\n    i++;\n    if(i == N){\n      std::cerr << \"Counter reached \" << N << std::endl;\n    }\n  }\n  \n};\n\nstruct InsertVisitor {\n\n  Counter& c;\n  InsertVisitor(Counter& c)\n    : c(c)\n  {}\n\n  void before_insertion()\n  {\n    c();\n  }\n\n};\n\n\n// ----------------------------------------------------------------------------\n// main()\n// ----------------------------------------------------------------------------\n\nint main(int argc, char * argv[])\n{\n    std::cerr << \"Poisson Delaunay Reconstruction method\" << std::endl;\n\n    //***************************************\n    // decode parameters\n    //***************************************\n\n    // usage\n    if (argc-1 < 2)\n    {\n      std::cerr << \"Reads a point set or a mesh's set of vertices, reconstructs a surface using Poisson,\\n\";\n      std::cerr << \"and saves the surface.\\n\";\n      std::cerr << \"\\n\";\n      std::cerr << \"Usage: \" << argv[0] << \" file_in file_out [options]\\n\";\n      std::cerr << \"Input file formats are .off (mesh) and .xyz or .pwn (point set).\\n\";\n      std::cerr << \"Output file format is .off.\\n\";\n      std::cerr << \"Options:\\n\";\n      std::cerr << \"  -sm_radius <float>     Radius upper bound (default=100 * average spacing)\\n\";\n      std::cerr << \"  -sm_distance <float>   Distance upper bound (default=0.25 * average spacing)\\n\";\n      \n      return EXIT_FAILURE;\n    }\n\n    // Poisson options\n    FT sm_angle = 20.0; // Min triangle angle (degrees).\n    FT sm_radius = 100; // Max triangle size w.r.t. point set average spacing.\n    FT sm_distance = 0.25; // Approximation error w.r.t. point set average spacing.\n    std::string solver_name = \"eigen\"; // Sparse linear solver name.\n    double approximation_ratio = 0.02;\n    double average_spacing_ratio = 5;\n\n    // decode parameters\n    std::string input_filename  = argv[1];\n    std::string output_filename = argv[2];\n    for (int i=3; i+1<argc ; ++i)\n    {\n      if (std::string(argv[i])==\"-sm_radius\")\n        sm_radius = atof(argv[++i]);\n      else if (std::string(argv[i])==\"-sm_distance\")\n        sm_distance = atof(argv[++i]);\n      else if (std::string(argv[i])==\"-solver\")\n        solver_name = argv[++i];\n      else if (std::string(argv[i])==\"-approx\")\n        approximation_ratio = atof(argv[++i]);\n      else if (std::string(argv[i])==\"-ratio\")\n        average_spacing_ratio = atof(argv[++i]);\n      else {\n        std::cerr << \"Error: invalid option \" << argv[i] << \"\\n\";\n        return EXIT_FAILURE;\n      }\n    }\n\n    CGAL::Timer task_timer; task_timer.start();\n\n    //***************************************\n    // Loads mesh/point set\n    //***************************************\n\n    PointList points;\n\n    // If OFF file format\n    std::cerr << \"Open \" << input_filename << \" for reading...\" << std::endl;\n    std::string extension = input_filename.substr(input_filename.find_last_of('.'));\n    if (extension == \".off\" || extension == \".OFF\")\n    {\n      // Reads the mesh file in a polyhedron\n      std::ifstream stream(input_filename.c_str());\n      Polyhedron input_mesh;\n      CGAL::scan_OFF(stream, input_mesh, true /* verbose */);\n      if(!stream || !input_mesh.is_valid() || input_mesh.empty())\n      {\n        std::cerr << \"Error: cannot read file \" << input_filename << std::endl;\n        return EXIT_FAILURE;\n      }\n\n      // Converts Polyhedron vertices to point set.\n      // Computes vertices normal from connectivity.\n      BOOST_FOREACH(boost::graph_traits<Polyhedron>::vertex_descriptor v,\n                    vertices(input_mesh)){\n        const Point& p = v->point();\n        Vector n = CGAL::Polygon_mesh_processing::compute_vertex_normal(v,input_mesh);\n        points.push_back(Point_with_normal(p,n));\n      }\n    }\n    // If XYZ file format\n    else if (extension == \".xyz\" || extension == \".XYZ\" ||\n             extension == \".pwn\" || extension == \".PWN\")\n    {\n      // Reads the point set file in points[].\n      // Note: read_xyz_points_and_normals() requires an iterator over points\n      // + property maps to access each point's position and normal.\n      // The position property map can be omitted here as we use iterators over Point_3 elements.\n      std::ifstream stream(input_filename.c_str());\n      if (!stream ||\n          !CGAL::read_xyz_points_and_normals(\n                                stream,\n                                std::back_inserter(points),\n                                CGAL::make_normal_of_point_with_normal_pmap(PointList::value_type())))\n      {\n        std::cerr << \"Error: cannot read file \" << input_filename << std::endl;\n        return EXIT_FAILURE;\n      }\n    }\n    else\n    {\n      std::cerr << \"Error: cannot read file \" << input_filename << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    // Prints status\n    std::size_t nb_points = points.size();\n    std::cerr << \"Reads file \" << input_filename << \": \" << nb_points << \" points, \"\n                                                        << task_timer.time() << \" seconds\"\n                                                        << std::endl;\n    task_timer.reset();\n\n    //***************************************\n    // Checks requirements\n    //***************************************\n\n    if (nb_points == 0)\n    {\n      std::cerr << \"Error: empty point set\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    bool points_have_normals = (points.begin()->normal() != CGAL::NULL_VECTOR);\n    if ( ! points_have_normals )\n    {\n      std::cerr << \"Input point set not supported: this reconstruction method requires oriented normals\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    CGAL::Timer reconstruction_timer; reconstruction_timer.start();\n\n    \n    Counter counter(std::distance(points.begin(), points.end()));\n    InsertVisitor visitor(counter) ;\n    \n\n    //***************************************\n    // Computes implicit function\n    //***************************************\n\n    std::cerr << \"Computes Poisson implicit function...\\n\";\n\n    // Creates implicit function from the read points.\n    // Note: this method requires an iterator over points\n    // + property maps to access each point's position and normal.\n    // The position property map can be omitted here as we use iterators over Point_3 elements.\n    Poisson_reconstruction_function function(\n                              points.begin(), points.end(),\n                              CGAL::make_identity_property_map(PointList::value_type()),\n                              CGAL::make_normal_of_point_with_normal_pmap(PointList::value_type()),\n                              visitor);\n\n    #ifdef CGAL_EIGEN3_ENABLED\n    {\n      if (solver_name == \"eigen\")\n      {\n        std::cerr << \"Use Eigen 3\\n\";\n        CGAL::Eigen_solver_traits<Eigen::ConjugateGradient<CGAL::Eigen_sparse_symmetric_matrix<double>::EigenType> > solver;\n        if ( ! function.compute_implicit_function(solver, visitor, \n                                                approximation_ratio,\n                                                average_spacing_ratio) )\n        {\n          std::cerr << \"Error: cannot compute implicit function\" << std::endl;\n          return EXIT_FAILURE;\n        }\n      }    \n      else\n      {\n        std::cerr << \"Error: invalid solver \" << solver_name << \"\\n\";\n        return EXIT_FAILURE;\n      }\n    }\n    #else\n    {\n      std::cerr << \"Error: invalid solver \" << solver_name << \"\\n\";\n      return EXIT_FAILURE;\n    }\n    #endif\n\n\n    // Prints status\n    std::cerr << \"Total implicit function (triangulation+refinement+solver): \" << task_timer.time() << \" seconds\\n\";\n    task_timer.reset();\n\n    //***************************************\n    // Surface mesh generation\n    //***************************************\n\n    std::cerr << \"Surface meshing...\\n\";\n\n    // Computes average spacing\n    FT average_spacing = CGAL::compute_average_spacing<CGAL::Sequential_tag>(points.begin(), points.end(),\n                                                       6 /* knn = 1 ring */);\n\n    // Gets one point inside the implicit surface\n    Point inner_point = function.get_inner_point();\n    FT inner_point_value = function(inner_point);\n    if(inner_point_value >= 0.0)\n    {\n      std::cerr << \"Error: unable to seed (\" << inner_point_value << \" at inner_point)\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    // Gets implicit function's radius\n    Sphere bsphere = function.bounding_sphere();\n    FT radius = std::sqrt(bsphere.squared_radius());\n\n    // Defines the implicit surface: requires defining a\n  \t// conservative bounding sphere centered at inner point.\n    FT sm_sphere_radius = 5.0 * radius;\n    FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance\n    Surface_3 surface(function,\n                      Sphere(inner_point,sm_sphere_radius*sm_sphere_radius),\n                      sm_dichotomy_error/sm_sphere_radius);\n\n    // Defines surface mesh generation criteria\n    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)\n                                                        sm_radius*average_spacing,  // Max triangle size\n                                                        sm_distance*average_spacing); // Approximation error\n\n    CGAL_TRACE_STREAM << \"  make_surface_mesh(sphere center=(\"<<inner_point << \"),\\n\"\n                      << \"                    sphere radius=\"<<sm_sphere_radius<<\",\\n\"\n                      << \"                    angle=\"<<sm_angle << \" degrees,\\n\"\n                      << \"                    triangle size=\"<<sm_radius<<\" * average spacing=\"<<sm_radius*average_spacing<<\",\\n\"\n                      << \"                    distance=\"<<sm_distance<<\" * average spacing=\"<<sm_distance*average_spacing<<\",\\n\"\n                      << \"                    dichotomy error=distance/\"<<sm_distance*average_spacing/sm_dichotomy_error<<\",\\n\"\n                      << \"                    Manifold_with_boundary_tag)\\n\";\n\n    // Generates surface mesh with manifold option\n    STr tr; // 3D Delaunay triangulation for surface mesh generation\n    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation\n    CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh\n                            surface,                              // implicit surface\n                            criteria,                             // meshing criteria\n                            CGAL::Manifold_with_boundary_tag());  // require manifold mesh\n\n    // Prints status\n    std::cerr << \"Surface meshing: \" << task_timer.time() << \" seconds, \"\n                                     << tr.number_of_vertices() << \" output vertices\"\n                                     << std::endl;\n    task_timer.reset();\n\n    if(tr.number_of_vertices() == 0)\n      return EXIT_FAILURE;\n\n    // Converts to polyhedron\n    Polyhedron output_mesh;\n    CGAL::output_surface_facets_to_polyhedron(c2t3, output_mesh);\n\n    // Prints total reconstruction duration\n    std::cerr << \"Total reconstruction (implicit function + meshing): \" << reconstruction_timer.time() << \" seconds\\n\";\n\n    //***************************************\n    // Computes reconstruction error\n    //***************************************\n\n    // Constructs AABB tree and computes internal KD-tree\n    // data structure to accelerate distance queries\n    AABB_tree tree(faces(output_mesh).first, faces(output_mesh).second, output_mesh);\n    tree.accelerate_distance_queries();\n\n    // Computes distance from each input point to reconstructed mesh\n    double max_distance = DBL_MIN;\n    double avg_distance = 0;\n    for (PointList::const_iterator p=points.begin(); p!=points.end(); p++)\n    {\n      double distance = std::sqrt(tree.squared_distance(*p));\n\n      max_distance = (std::max)(max_distance, distance);\n      avg_distance += distance;\n    }\n    avg_distance /= double(points.size());\n\n    std::cerr << \"Reconstruction error:\\n\"\n              << \"  max = \" << max_distance << \" = \" << max_distance/average_spacing << \" * average spacing\\n\"\n              << \"  avg = \" << avg_distance << \" = \" << avg_distance/average_spacing << \" * average spacing\\n\";\n\n    //***************************************\n    // Saves reconstructed surface mesh\n    //***************************************\n\n    std::cerr << \"Write file \" << output_filename << std::endl << std::endl;\n    std::ofstream out(output_filename.c_str());\n    out << output_mesh;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "108747385d93aeca6206cc64b0186564453bface", "size": 14858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Poisson_surface_reconstruction_3/poisson_reconstruction.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/Poisson_surface_reconstruction_3/poisson_reconstruction.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/Poisson_surface_reconstruction_3/poisson_reconstruction.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": 37.8066157761, "max_line_length": 129, "alphanum_fraction": 0.5677076323, "num_tokens": 3246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5984576826373119}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include \"time_frequency_transform.hpp\"\n\n#include \"libvisr/signal_flow_context.hpp\"\n\n#include <libefl/vector_functions.hpp>\n\n#include <libpml/time_frequency_parameter.hpp>\n#include <libpml/time_frequency_parameter_config.hpp>\n#include <libpml/vector_parameter.hpp>\n\n#include <librbbl/fft_wrapper_base.hpp>\n#include <librbbl/fft_wrapper_factory.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <algorithm>\n#include <ciso646>\n#include <cmath>\n\nnamespace visr\n{\nnamespace rcl\n{\n\nnamespace // unnamed namespace\n{\n\n/**\n * Create a slightly asymmetric Hann window as the default window shape.\n * @note In contrast to the standard definition, this version satisfies the COLA (constant overlap-add) property.\n */\ntemplate< typename T >\npml::VectorParameter<T> unityHannWindow( std::size_t length )\n{\n  pml::VectorParameter<T> res( length, cVectorAlignmentSamples );\n  for( std::size_t idx( 0 ); idx < length; ++idx )\n  {\n    res[idx] = static_cast<T>(0.5 - 0.5*std::cos( (2.0*boost::math::constants::pi<T>()*static_cast<T>(idx)) / static_cast<T>(length) ));\n  }\n  return res;\n}\n\n} // namespace unnamed\n\nTimeFrequencyTransform::TimeFrequencyTransform( SignalFlowContext const & context,\n                                                char const * name,\n                                                CompositeComponent * parent,\n                                                std::size_t numberOfChannels,\n                                                std::size_t dftLength,\n                                                std::size_t windowLength,\n                                                std::size_t hopSize,\n                                                char const * fftImplementation /*= \"default\"*/ )\n : TimeFrequencyTransform( context, name, parent,\n                           numberOfChannels, dftLength,\n                           unityHannWindow<SampleType>( windowLength ),\n                           hopSize, fftImplementation )\n{\n}\n\nTimeFrequencyTransform::TimeFrequencyTransform( SignalFlowContext const & context,\n                        char const * name,\n                        CompositeComponent * parent,\n                        std::size_t numberOfChannels,\n                        std::size_t dftLength,\n                        efl::BasicVector<SampleType> const & window,\n                        std::size_t hopSize, char const * fftImplementation /*= \"default\"*/ )\n : AtomicComponent( context, name, parent )\n , mAlignment( cVectorAlignmentSamples )\n , mNumberOfChannels( numberOfChannels )\n , mDftlength( dftLength )\n , mWindowLength( window.size() )\n , mDftSamplesPerPeriod( context.period() / hopSize )\n , mHopSize( hopSize )\n , mInputBuffer( numberOfChannels, window.size(), mAlignment )\n , mFftWrapper( rbbl::FftWrapperFactory<SampleType>::create( fftImplementation, dftLength, mAlignment ) )\n , mWindow( window.size(), mAlignment )\n , mCalcBuffer( dftLength, mAlignment )\n , mInput( \"in\", *this, numberOfChannels )\n , mOutput( \"out\", *this, pml::TimeFrequencyParameterConfig( dftLength, hopSize, numberOfChannels, mDftSamplesPerPeriod ) )\n{\n  if( period() % hopSize != 0 )\n  {\n    throw std::invalid_argument( \"TimeFrequencyTransform: Invalid hop size (no integer number of hops per audio processing period).\" );\n  }\n  efl::vectorZero( mCalcBuffer.data(), mCalcBuffer.size(), mCalcBuffer.alignmentElements() );\n\n  // Scale the window to account for the FFT scaling and the DFT length\n  SampleType const scaleFactor = static_cast<SampleType>(1.0)\n    / (mFftWrapper->forwardScalingFactor() * mFftWrapper->inverseScalingFactor() * mDftlength);\n  std::transform( window.data(), window.data()+window.size(), mWindow.data(),\n                  [scaleFactor](SampleType val){ return scaleFactor * val;} );\n}\n\nTimeFrequencyTransform::~TimeFrequencyTransform() = default;\n\nvoid TimeFrequencyTransform::process()\n{\n  pml::TimeFrequencyParameter<SampleType> & outMtx = mOutput.data();\n  mInputBuffer.write( mInput.data(), mInput.channelStrideSamples(),\n                      mNumberOfChannels, period(), cVectorAlignmentSamples );\n  for( std::size_t hopIndex( 0 ); hopIndex < mDftSamplesPerPeriod; ++hopIndex )\n  {\n    std::size_t const blockStartIndex = mWindowLength + (mDftSamplesPerPeriod - hopIndex - 1) * mHopSize;\n    for( std::size_t channelIndex( 0 ); channelIndex < mNumberOfChannels; ++channelIndex )\n    {\n      efl::ErrorCode res = efl::vectorMultiply( mInputBuffer.getReadPointer( channelIndex, blockStartIndex ),\n                                                mWindow.data(), mCalcBuffer.data(), mWindowLength, mAlignment );\n      if( res != efl::noError )\n      {\n        throw std::runtime_error( \"TimeFrequencyTransform: Error during input windowing.\" );\n      }\n      std::complex<SampleType> * dftPtr = outMtx.dftSlice( channelIndex, hopIndex );\n      res = mFftWrapper->forwardTransform( mCalcBuffer.data(), dftPtr );\n      if( res != efl::noError )\n      {\n        throw std::runtime_error( \"TimeFrequencyTransform: Error during FFT operation.\" );\n      }\n    }\n  }\n}\n\n} // namespace rcl\n} // namespace visr\n", "meta": {"hexsha": "5bca312d0027f994b989917607e92c1f474ff7df", "size": 5148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/librcl/time_frequency_transform.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/librcl/time_frequency_transform.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/librcl/time_frequency_transform.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 40.8571428571, "max_line_length": 136, "alphanum_fraction": 0.6433566434, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5983619438479334}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n#include <NTL/lzz_pXFactoring.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include \"FHE_operation.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <iostream>\nusing namespace std;\n\nint main()\n{\n\tlong m = 0;          // 确定系数\n\tlong p = 2147483647; // 模量(素数)，定义超过p/2的数为负数，负数的真值x=D[E[x]]-p\n\tlong r = 1;\n\tlong L = 16;\n\tlong c = 3;\n\tlong w = 64;\n\tlong d = 0;\n\tlong k = 128;\n\tlong s = 0;\n\n\tm = FindM(k, L, c, p, d, s, 0);\n\n\tFHEcontext context(m, p, r);\n\tbuildModChain(context, L, c);\n\tZZX G = context.alMod.getFactorsOverZZ()[0];\n\t\n\t// 生成公钥\n\tFHESecKey secretKey(context);\n\tconst FHEPubKey& publicKey = secretKey;\n\tsecretKey.GenSecKey(w);\n\n\t// 初始化密文\n\tCtxt Ea(publicKey);\n\tCtxt Eb(publicKey);\n\n\t// Test\t\n\tlong op1[5] = {2, 4, 0, 25, 15};\n\tlong op2[5] = {-1, 1, 4, 0, 2};\n\tlong *res;\n\t\n\tVec<ZZ> h1 = arr2validVec(op1, 5);\n\tVec<ZZ> h2 = arr2validVec(op2, 5);\n\n\tpublicKey.Encrypt(Ea, to_ZZX(h1));\n\tpublicKey.Encrypt(Eb, to_ZZX(h2));\n\n\tZZX ptSum;\n\tsecretKey.Decrypt(ptSum, FHE_Add(Ea, Eb));\n\tres = FHE_ptDec(ptSum, p, 5);\n\tcout << \"ptSum : \" << endl;\n\tfor (int i=0; i<5; i++)\n\t\tcout << res[i] << \" \";\n\tcout << endl;\n\t\n\tZZX ptMul;\n\tsecretKey.Decrypt(ptMul, FHE_Mul(Ea, Eb, p, publicKey, secretKey, 5));\n\tres = FHE_ptDec(ptMul, p, 5);\n\tcout << \"ptMul : \" << endl;\n\tfor (int i=0; i<5; i++)\n\t\tcout << res[i] << \" \";\n\tcout << endl;\n\n\tZZX ptSub;\n\tsecretKey.Decrypt(ptSub, FHE_Sub(Ea, Eb, p, publicKey, secretKey, 5));\n\tres = FHE_ptDec(ptSub, p, 5);\n\tcout << \"ptSub : \" << endl;\n\tfor (int i=0; i<5; i++)\n\t\tcout << res[i] << \" \";\n\tcout << endl;\n\n\tZZX ptDiv;\n\tsecretKey.Decrypt(ptDiv, FHE_Div(Ea, Eb, p, publicKey, secretKey, 5));\n\tres = FHE_ptDec(ptDiv, p, 5);\n\tcout << \"ptDiv : \" << endl;\n\tfor (int i=0; i<5; i++)\n\t\tcout << res[i] << \" \";\n\tcout << endl;\n\n\treturn 0;\n}", "meta": {"hexsha": "64e78400766d2c661effcca1d33e64cb6210c63f", "size": 1824, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test_FHE_operation.cpp", "max_stars_repo_name": "edwincai/my-first-lab", "max_stars_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-12T15:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T15:33:57.000Z", "max_issues_repo_path": "Test_FHE_operation.cpp", "max_issues_repo_name": "edwincai/my-first-lab", "max_issues_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test_FHE_operation.cpp", "max_forks_repo_name": "edwincai/my-first-lab", "max_forks_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_forks_repo_licenses": ["Apache-2.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.4588235294, "max_line_length": 71, "alphanum_fraction": 0.6019736842, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.598361931539702}}
{"text": "#pragma once\n\n#include <cmath>\n\n#include <Eigen/SparseLU>\n\n#include \"OpenABF/ABF.hpp\"\n#include \"OpenABF/Exceptions.hpp\"\n#include \"OpenABF/HalfEdgeMesh.hpp\"\n#include \"OpenABF/Math.hpp\"\n\nnamespace OpenABF\n{\n\n/**\n * @brief Compute parameterized interior angles using ABF++\n *\n * Iteratively computes a new set of interior angles which minimize the total\n * angular error of the parameterized mesh. This follows the ABF++ formulation,\n * which solves a 5x smaller system of equations than standard ABF at the\n * expense of more iterations.\n *\n * This class **does not** compute a parameterized mesh. Rather, it calculates\n * the optimal interior angles for such a mesh. To convert this information\n * into a full parameterization, pass the processed HalfEdgeMesh to\n * AngleBasedLSCM.\n *\n * Implements \"ABF++: Fast and Robust Angle Based Flattening\" by Sheffer\n * _et al._ (2005) \\cite sheffer2005abf++.\n *\n * @tparam T Floating-point type\n * @tparam MeshType HalfEdgeMesh type which implements the ABF traits\n * @tparam Solver A solver implementing the\n * [Eigen Sparse solver\n * concept](https://eigen.tuxfamily.org/dox-devel/group__TopicSparseSystems.html)\n * and templated on Eigen::SparseMatrix<T>\n */\ntemplate <\n    typename T,\n    class MeshType = detail::ABF::Mesh<T>,\n    class Solver =\n        Eigen::SparseLU<Eigen::SparseMatrix<T>, Eigen::COLAMDOrdering<int>>,\n    std::enable_if_t<std::is_floating_point<T>::value, bool> = true>\nclass ABFPlusPlus\n{\npublic:\n    /** @brief Mesh type alias */\n    using Mesh = MeshType;\n\n    /** @brief Set the maximum number of iterations */\n    void setMaxIterations(std::size_t it) { maxIters_ = it; }\n\n    /**\n     * @brief Get the mesh gradient\n     *\n     * **Note:** Result is only valid after running compute().\n     */\n    auto gradient() const -> T { return grad_; }\n\n    /**\n     * @brief Get the number of iterations of the last computation\n     *\n     * **Note:** Result is only valid after running compute().\n     */\n    auto iterations() const -> std::size_t { return iters_; }\n\n    /** @copydoc ABFPlusPlus::Compute */\n    void compute(typename Mesh::Pointer& mesh)\n    {\n        Compute(mesh, iters_, grad_, maxIters_);\n    }\n\n    /**\n     * @brief Compute parameterized interior angles\n     *\n     * @throws SolverException If matrix cannot be decomposed or if solver fails\n     * to find a solution.\n     * @throws MeshException If mesh gradient cannot be calculated.\n     */\n    static void Compute(\n        typename Mesh::Pointer& mesh,\n        std::size_t& iters,\n        T& gradient,\n        std::size_t maxIters = 10)\n    {\n        using namespace detail::ABF;\n\n        // Initialize angles and weights\n        InitializeAnglesAndWeights<T>(mesh);\n\n        // while ||∇F(x)|| > ε\n        gradient = Gradient<T>(mesh);\n        if (std::isnan(gradient) or std::isinf(gradient)) {\n            throw MeshException(\"Mesh gradient cannot be computed\");\n        }\n        auto gradDelta = INF<T>;\n        iters = 0;\n        while (gradient > 0.001 and gradDelta > 0.001 and iters < maxIters) {\n            if (std::isnan(gradient) or std::isinf(gradient)) {\n                throw MeshException(\"Mesh gradient cannot be computed\");\n            }\n            // Typedefs\n            using Triplet = Eigen::Triplet<T>;\n            using SparseMatrix = Eigen::SparseMatrix<T>;\n            using DenseVector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n            // Helpful parameters\n            auto vIntCnt = mesh->num_vertices_interior();\n            auto edgeCnt = mesh->num_edges();\n            auto faceCnt = mesh->num_faces();\n\n            // b1 = -alpha gradient\n            std::vector<Triplet> triplets;\n            std::size_t idx{0};\n            for (const auto& e : mesh->edges()) {\n                triplets.emplace_back(idx, 0, -AlphaGrad<T>(e));\n                ++idx;\n            }\n            SparseMatrix b1(edgeCnt, 1);\n            b1.reserve(triplets.size());\n            b1.setFromTriplets(triplets.begin(), triplets.end());\n\n            // b2 = -lambda gradient\n            triplets.clear();\n            idx = 0;\n            // lambda tri\n            for (const auto& f : mesh->faces()) {\n                triplets.emplace_back(idx, 0, -TriGrad<T>(f));\n                idx++;\n            }\n            // lambda plan and lambda len\n            for (const auto& v : mesh->vertices_interior()) {\n                triplets.emplace_back(idx, 0, -PlanGrad<T>(v));\n                triplets.emplace_back(vIntCnt + idx, 0, -LenGrad<T>(v));\n                idx++;\n            }\n            SparseMatrix b2(faceCnt + 2 * vIntCnt, 1);\n            b2.reserve(triplets.size());\n            b2.setFromTriplets(triplets.begin(), triplets.end());\n\n            // vertex idx -> interior vertex idx permutation\n            std::map<std::size_t, std::size_t> vIdx2vIntIdx;\n            std::size_t newIdx{0};\n            for (const auto& v : mesh->vertices_interior()) {\n                vIdx2vIntIdx[v->idx] = newIdx++;\n            }\n\n            // Compute J1 + J2\n            triplets.clear();\n            idx = 0;\n            // Jacobian of the CTri constraints\n            for (; idx < faceCnt; idx++) {\n                triplets.emplace_back(idx, 3 * idx, 1);\n                triplets.emplace_back(idx, 3 * idx + 1, 1);\n                triplets.emplace_back(idx, 3 * idx + 2, 1);\n            }\n            for (const auto& v : mesh->vertices_interior()) {\n                for (const auto& e0 : v->wheel()) {\n                    // Jacobian of the CPlan constraint\n                    triplets.emplace_back(idx, e0->idx, 1);\n\n                    // Jacobian of the CLen constraint\n                    auto e1 = e0->next;\n                    auto e2 = e1->next;\n                    auto d1 = LenGrad<T>(v, e1);\n                    auto d2 = LenGrad<T>(v, e2);\n                    triplets.emplace_back(vIntCnt + idx, e1->idx, d1);\n                    triplets.emplace_back(vIntCnt + idx, e2->idx, d2);\n                }\n                ++idx;\n            }\n            SparseMatrix J(faceCnt + 2 * vIntCnt, 3 * faceCnt);\n            J.reserve(triplets.size());\n            J.setFromTriplets(triplets.begin(), triplets.end());\n\n            // Lambda = diag(2/w)\n            // v.weight == 1/w, so LambdaInv is diag(2*weight)\n            // We only need Lambda Inverse, so this is 1 / 2*weight\n            triplets.clear();\n            idx = 0;\n            for (const auto& e : mesh->edges()) {\n                triplets.emplace_back(idx, idx, T(1) / (2 * e->weight));\n                ++idx;\n            }\n            SparseMatrix LambdaInv(edgeCnt, edgeCnt);\n            LambdaInv.reserve(edgeCnt);\n            LambdaInv.setFromTriplets(triplets.begin(), triplets.end());\n\n            // solve Eq. 16\n            auto bstar = J * LambdaInv * b1 - b2;\n            auto JLiJt = J * LambdaInv * J.transpose();\n\n            SparseMatrix LambdaStarInv = JLiJt.block(0, 0, faceCnt, faceCnt);\n            for (int k = 0; k < LambdaStarInv.outerSize(); ++k) {\n                for (typename SparseMatrix::InnerIterator it(LambdaStarInv, k);\n                     it; ++it) {\n                    it.valueRef() = 1.F / it.value();\n                }\n            }\n            auto Jstar = JLiJt.block(faceCnt,0,2*vIntCnt,faceCnt);\n            auto JstarT = JLiJt.block(0,faceCnt,faceCnt, 2*vIntCnt);\n            auto Jstar2 = JLiJt.block(faceCnt,faceCnt,2*vIntCnt, 2*vIntCnt);\n            auto bstar1 = bstar.block(0, 0, faceCnt, 1);\n            auto bstar2 = bstar.block(faceCnt, 0, 2*vIntCnt, 1);\n\n            // (J* Lam*^-1 J*^t - J**) delta_lambda_2 = J* Lam*^-1 b*_1 - b*_2\n            SparseMatrix A = Jstar * LambdaStarInv * JstarT - Jstar2;\n            SparseMatrix b = Jstar * LambdaStarInv * bstar1 - bstar2;\n            A.makeCompressed();\n            Solver solver;\n            solver.compute(A);\n            if (solver.info() != Eigen::ComputationInfo::Success) {\n                throw SolverException(solver.lastErrorMessage());\n            }\n            auto deltaLambda2 = solver.solve(b);\n            if (solver.info() != Eigen::ComputationInfo::Success) {\n                throw SolverException(solver.lastErrorMessage());\n            }\n\n            // Compute Eq. 17 -> delta_lambda_1\n            auto deltaLambda1 =\n                LambdaStarInv * (bstar1 - JstarT * deltaLambda2);\n\n            // Construct deltaLambda\n            DenseVector deltaLambda(\n                deltaLambda1.rows() + deltaLambda2.rows(), 1);\n            deltaLambda << DenseVector(deltaLambda1), DenseVector(deltaLambda2);\n\n            // Compute Eq. 10 -> delta_alpha\n            DenseVector deltaAlpha =\n                LambdaInv * (b1 - J.transpose() * deltaLambda);\n\n            // lambda += delta_lambda\n            for (auto& f : mesh->faces()) {\n                f->lambda_tri += deltaLambda(f->idx, 0);\n            }\n            for (auto& v : mesh->vertices_interior()) {\n                auto intIdx = vIdx2vIntIdx.at(v->idx);\n                v->lambda_plan += deltaLambda(faceCnt + intIdx, 0);\n                v->lambda_len += deltaLambda(faceCnt + vIntCnt + intIdx, 0);\n            }\n\n            // alpha += delta_alpha\n            // Update sin and cos\n            idx = 0;\n            for (auto& e : mesh->edges()) {\n                e->alpha += deltaAlpha(idx++, 0);\n                e->alpha = std::min(std::max(e->alpha, T(0)), PI<T>);\n                e->alpha_sin = std::sin(e->alpha);\n                e->alpha_cos = std::cos(e->alpha);\n            }\n\n            // Recalculate gradient for next iteration\n            auto newGrad = Gradient<T>(mesh);\n            gradDelta = std::abs(newGrad - gradient);\n            gradient = newGrad;\n            iters++;\n        }\n    }\n\n    /** @brief Compute parameterized interior angles */\n    static void Compute(typename Mesh::Pointer& mesh)\n    {\n        std::size_t iters{0};\n        T grad{0};\n        Compute(mesh, iters, grad);\n    }\n\nprivate:\n    /** Gradient */\n    T grad_{0};\n    /** Number of executed iterations */\n    std::size_t iters_{0};\n    /** Max iterations */\n    std::size_t maxIters_{10};\n};\n\n}  // namespace OpenABF", "meta": {"hexsha": "6e1cb5694a579858d0df32685da43c420008ccd2", "size": 10131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OpenABF/ABFPlusPlus.hpp", "max_stars_repo_name": "educelab/OpenABF", "max_stars_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-03-12T17:39:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T03:58:32.000Z", "max_issues_repo_path": "include/OpenABF/ABFPlusPlus.hpp", "max_issues_repo_name": "educelab/OpenABF", "max_issues_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/OpenABF/ABFPlusPlus.hpp", "max_forks_repo_name": "educelab/OpenABF", "max_forks_repo_head_hexsha": "8b8c7cfc23e7bef21979f54099f19d28eba0e682", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T17:39:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T13:30:08.000Z", "avg_line_length": 36.4424460432, "max_line_length": 81, "alphanum_fraction": 0.5446648899, "num_tokens": 2503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5983619269249559}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::model::functional::log_likelihood_accumulator.hpp             //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_MODEL_FUNCTIONAL_LOG_LIKELIHOOD_ACCUMULATOR_HPP_ER_2009\n#define BOOST_STATISTICS_MODEL_FUNCTIONAL_LOG_LIKELIHOOD_ACCUMULATOR_HPP_ER_2009\n#include <boost/concept_check.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/operators.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_parameter.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_data.hpp>\n#include <boost/joint_dist/unscope/log_unnormalized_pdf.hpp>\n#include <boost/scalar_dist/unscope/log_unnormalized_pdf.hpp>\n#include <boost/statistics/model/concept/log_likelihood.hpp>\n\nnamespace boost{\n\n    // fwd declare\n    template<typename T,typename M,typename X,typename Y,typename P>\n    T log_likelihood(\n        statistics::model::model_data_<M,X,Y>,\n        const P&\n    );\n\nnamespace statistics{\nnamespace model{\n\n// Functor that accumulates the data contribution to the likelihood of a model \n// and its parameter.\n//\n// Used by algorithm::log_likelihood        \ntemplate<\n    typename T, // result_type\n    typename M, // Model\n    typename P  // parameter\n>\nclass log_likelihood_accumulator : boost::addable<\n    log_likelihood_accumulator<T,M,P>\n>{\npublic:\n    typedef T                        result_type;\n    typedef model_parameter_<M,P>    model_parameter_type;\n\n    // Construction\n    log_likelihood_accumulator();\n    log_likelihood_accumulator(model_parameter_type);\n    log_likelihood_accumulator(const log_likelihood_accumulator& );\n    log_likelihood_accumulator& operator=(const log_likelihood_accumulator& );\n\n    // Operator\n    log_likelihood_accumulator& operator+=(\n        const log_likelihood_accumulator& that\n    );\n    \n    // Update\n    template<typename X,typename Y> \n    result_type operator()(const X&,const Y& y);\n    \n    // Access\n    const model_parameter_type& model_parameter()const;\n    result_type value()const;\n    \nprivate:\n    model_parameter_type mp_;\n    result_type cum_sum_;\n    static result_type zero_;\n};\n    \n    // Implementation //\n\ntemplate<typename T,typename M,typename P>\ntypename log_likelihood_accumulator<T,M,P>::result_type\nlog_likelihood_accumulator<T,M,P>::zero_ = static_cast<result_type>(0);    \n\n// Construction\ntemplate<typename T,typename M,typename P>\nlog_likelihood_accumulator<T,M,P>::log_likelihood_accumulator()\n:mp_(),cum_sum_(zero_){}\n\ntemplate<typename T,typename M,typename P>\nlog_likelihood_accumulator<T,M,P>::log_likelihood_accumulator(\n    model_parameter_type mp\n):mp_(mp),cum_sum_(zero_){}\n\ntemplate<typename T,typename M,typename P>\nlog_likelihood_accumulator<T,M,P>::log_likelihood_accumulator(\n    const log_likelihood_accumulator& that\n):mp_(that.mp_),cum_sum_(that.cum_sum_){}\n\ntemplate<typename T,typename M,typename P>\nlog_likelihood_accumulator<T,M,P>& \nlog_likelihood_accumulator<T,M,P>::operator=(\n    const log_likelihood_accumulator& that\n){\n    if(&that!=this){\n        mp_ = that.mp_;\n        cum_sum_ = that.cum_sum_;\n    }\n    return (*this);\n}\n\n// Operator\n\ntemplate<typename T,typename M,typename P>\nlog_likelihood_accumulator<T,M,P>& \nlog_likelihood_accumulator<T,M,P>::operator+=(\n    const log_likelihood_accumulator& that\n){\n    (this->cum_sum_)+= that.value();\n}\n    \n// Update\ntemplate<typename T,typename M,typename P>\ntemplate<typename X,typename Y>\ntypename log_likelihood_accumulator<T,M,P>::result_type \nlog_likelihood_accumulator<T,M,P>::operator()(const X& x,const Y& y){\n\n    // TODO see compile error by uncommenting, e.g. survival_model\n    // BOOST_CONCEPT_ASSERT(( \n    //  HasLogLikelihood<T,M,X,Y,P>\n    // ));\n\n    result_type l = log_likelihood<T>(\n        make_model_data(\n            model_parameter().model(),\n            x,\n            y\n        ),\n        model_parameter().parameter()\n    );\n    cum_sum_ += l;\n    return cum_sum_;\n}\n\n// Access\n\ntemplate<typename T,typename M,typename P>\nconst typename log_likelihood_accumulator<T,M,P>::model_parameter_type&\nlog_likelihood_accumulator<T,M,P>::model_parameter()const{ return mp_; }\n\ntemplate<typename T,typename M,typename P>\ntypename log_likelihood_accumulator<T,M,P>::result_type \nlog_likelihood_accumulator<T,M,P>::value()const{ return cum_sum_; }\n\n}// model\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "19d390042c1ee553fbc5774319a81edba58ff755", "size": 4772, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model copy/boost/statistics/model/functional/log_likelihood_accumulator.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model copy/boost/statistics/model/functional/log_likelihood_accumulator.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model copy/boost/statistics/model/functional/log_likelihood_accumulator.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1895424837, "max_line_length": 80, "alphanum_fraction": 0.6875523889, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.598337780185984}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n/*\n * test program for rounded math emulation\n *  compare add, sub, mul, div and sqrt under\n *  - changing rounding mode\n *  - emulating rounded math using twosum and twoproduct\n */\n\n#include <fenv.h>\n#include <boost/random.hpp>\n#include <ctime>\n\n#ifndef NT\n#define NT 10000000\n#endif\n\nstruct hwround {\n\tpublic:\n\n\tstatic void roundnear() {\n\t\tfesetround(FE_TONEAREST);\n\t}\n\n\tstatic void rounddown() {\n\t\tfesetround(FE_DOWNWARD);\n\t}\n\n\tstatic void roundup() {\n\t\tfesetround(FE_UPWARD);\n\t}\n\n\tstatic void roundchop() {\n\t\tfesetround(FE_TOWARDZERO);\n\t}\n\n\tstatic double add_up(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\troundup();\n\t\tr = x1 + y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double add_down(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\trounddown();\n\t\tr = x1 + y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double sub_up(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\troundup();\n\t\tr = x1 - y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double sub_down(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\trounddown();\n\t\tr = x1 - y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double mul_up(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\troundup();\n\t\tr = x1 * y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double mul_down(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\trounddown();\n\t\tr = x1 * y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double div_up(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\troundup();\n\t\tr = x1 / y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double div_down(const double& x, const double& y) {\n\t\tvolatile double r, x1 = x, y1 = y;\n\t\trounddown();\n\t\tr = x1 / y1;\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double sqrt_up(const double& x) {\n\t\tvolatile double r, x1 = x;\n\t\troundup();\n\t\tr = sqrt(x1);\n\t\troundnear();\n\t\treturn r;\n\t}\n\n\tstatic double sqrt_down(const double& x) {\n\t\tvolatile double r, x1 = x;\n\t\trounddown();\n\t\tr = sqrt(x1);\n\t\troundnear();\n\t\treturn r;\n\t}\n};\n\nstruct nohwround {\n\n\tstatic void fasttwosum(const double& a, const double& b, double& x, double& y) {\n\t\tdouble tmp;\n\t\tx = a + b;\n\t\ttmp = x - a;\n\t\ty = b - tmp;\n\t}\n\n\t#if 0\n\tstatic void twosum(const double& a, const double& b, double& x, double& y) {\n\t\tdouble tmp;\n\t\tx = a + b;\n\t\ttmp = x - a;\n\t\tif (std::fabs(tmp) == std::numeric_limits<double>::infinity()) {\n\t\t\ttmp = x * 0.5 - a * 0.5;\n\t\t\ty = ((a * 0.5 - (x * 0.5 - tmp)) + (b * 0.5 - tmp)) * 2.;\n\t\t} else {\n\t\t\ty = (a - (x - tmp)) + (b - tmp);\n\t\t}\n\t}\n\t#endif\n\n\tstatic void twosum(const double& a, const double& b, double& x, double& y) {\n\t\tdouble tmp;\n\n\t\tx = a + b;\n\t\tif (std::fabs(a) > std::fabs(b)) {\n\t\t\ttmp = x - a;\n\t\t\ty = b - tmp;\n\t\t} else {\n\t\t\ttmp = x - b;\n\t\t\ty = a - tmp;\n\t\t}\n\t}\n\n\tstatic void split(const double& a, double& x, double& y) {\n\t\tstatic const double sigma = ldexp(1., 27) + 1.;\n\t\tdouble tmp;\n\n\t\ttmp = a * sigma;\n\t\tx = tmp - (tmp - a);\n\t\ty = a - x;\n\t}\n\n\tstatic void twoproduct(const double& a, const double& b, double& x, double& y) {\n\t\tstatic const double th = ldexp(1., 996);\n\t\tstatic const double c1 = ldexp(1., -28);\n\t\tstatic const double c2 = ldexp(1., 28);\n\t\tstatic const double th2 = ldexp(1., 1023);\n\n\t\tdouble na, nb, a1, a2, b1, b2;\n\n\t\tx = a * b;\n\t\t#if 0\n\t\tif (std::fabs(x) == std::numeric_limits<double>::infinity()) {\n\t\t\ty = 0.;\n\t\t\treturn;\n\t\t}\n\t\t#endif\n\t\tif (std::fabs(a) > th) {\n\t\t\tna = a * c1;\n\t\t\tnb = b * c2;\n\t\t} else if (std::fabs(b) > th) {\n\t\t\tna = a * c2;\n\t\t\tnb = b * c1;\n\t\t} else {\n\t\t\tna = a;\n\t\t\tnb = b;\n\t\t}\n\t\tsplit(na, a1, a2);\n\t\tsplit(nb, b1, b2);\n\t\tif (std::fabs(x) > th2) {\n\t\t\ty = a2 * b2 - ((((x * 0.5) - (a1 * 0.5)  * b1) * 2. - a2 * b1) - a1 * b2);\n\t\t} else {\n\t\t\ty = a2 * b2 - (((x - a1 * b1) - a2 * b1) - a1 * b2);\n\t\t}\n\t}\n\n\t// succ and pred by Rump\n\n\tstatic double succ(const double& x) {\n\t\tstatic const double th1 = ldexp(1., -969);\n\t\tstatic const double th2 = ldexp(1., -1021);\n\t\tstatic const double c1 = ldexp(1., -53) + ldexp(1., -105);\n\t\tstatic const double c2 = ldexp(1., -1074);\n\t\tstatic const double c3 = ldexp(1., 53);\n\t\tstatic const double c4 = ldexp(1., -53);\n\n\t\tdouble a, c, e;\n\n\t\ta = std::fabs(x);\n\t\tif (a >= th1) return x + a * c1;\n\t\tif (a < th2) return x + c2;\n\t\tc = c3 * x;\n\t\te = c1 * std::fabs(c);\n\t\treturn (c + e) * c4;\n\t}\n\n\tstatic double pred(const double& x) {\n\t\tstatic const double th1 = ldexp(1., -969);\n\t\tstatic const double th2 = ldexp(1., -1021);\n\t\tstatic const double c1 = ldexp(1., -53) + ldexp(1., -105);\n\t\tstatic const double c2 = ldexp(1., -1074);\n\t\tstatic const double c3 = ldexp(1., 53);\n\t\tstatic const double c4 = ldexp(1., -53);\n\n\t\tdouble a, c, e;\n\n\t\ta = std::fabs(x);\n\t\tif (a >= th1) return x - a * c1;\n\t\tif (a < th2) return x - c2;\n\t\tc = c3 * x;\n\t\te = c1 * std::fabs(c);\n\t\treturn (c - e) * c4;\n\t}\n\n\n\tstatic double add_up(const double& x, const double& y) {\n\t\tdouble r, r2;\n\n\t\ttwosum(x, y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\tif (x == -std::numeric_limits<double>::infinity() || y == -std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn -(std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t}\n\n\t\tif (r2 > 0.) {\n\t\t\treturn succ(r);\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tstatic double add_down(const double& x, const double& y) {\n\t\tdouble r, r2;\n\n\t\ttwosum(x, y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\tif (x == std::numeric_limits<double>::infinity() || y == std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn (std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t}\n\n\t\tif (r2 < 0.) {\n\t\t\treturn pred(r);\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tstatic double sub_up(const double& x, const double& y) {\n\t\tdouble r, r2;\n\n\t\ttwosum(x, -y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\tif (x == -std::numeric_limits<double>::infinity() || y == std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn -(std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t}\n\n\t\tif (r2 > 0.) {\n\t\t\treturn succ(r);\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tstatic double sub_down(const double& x, const double& y) {\n\t\tdouble r, r2;\n\n\t\ttwosum(x, -y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\tif (x == std::numeric_limits<double>::infinity() || y == -std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn (std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t}\n\n\t\tif (r2 < 0.) {\n\t\t\treturn pred(r);\n\t\t}\n\n\t\treturn r;\n\t}\n\n\tstatic double mul_up(const double& x, const double& y) {\n\t\tdouble r, r2;\n\t\tdouble x1, y1;\n\t\tdouble s, s2, t;\n\t\tstatic const double th = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double c = ldexp(1., 537); // 1074 / 2\n\n\t\t// if (x == 0. || y == 0.) return x * y;\n\n\t\ttwoproduct(x, y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\tif (std::fabs(x) == std::numeric_limits<double>::infinity() || std::fabs(y) == std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn -(std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t}\n\n\t\tif (fabs(r) >= th) {\n\t\t\tif (r2 > 0.) return succ(r);\n\t\t\treturn r;\n\t\t} else {\n\t\t\ttwoproduct(x * c, y * c, s, s2);\n\t\t\tt = (r * c) * c;\n\t\t\tif ( t < s || (t == s && s2 > 0.)) {\n\t\t\t\treturn succ(r);\n\t\t\t}\n\t\t\treturn r;\n\t\t}\n\t}\n\n\tstatic double mul_down(const double& x, const double& y) {\n\t\tdouble r, r2;\n\t\tdouble x1, y1;\n\t\tdouble s, s2, t;\n\t\tstatic const double th = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double c = ldexp(1., 537); // 1074 / 2\n\n\t\t// if (x == 0. || y == 0.) return x * y;\n\n\t\ttwoproduct(x, y, r, r2);\n\t\tif (r == std::numeric_limits<double>::infinity()) {\n\t\t\tif (std::fabs(x) == std::numeric_limits<double>::infinity() || std::fabs(y) == std::numeric_limits<double>::infinity()) {\n\t\t\t\treturn r;\n\t\t\t} else {\n\t\t\t\treturn (std::numeric_limits<double>::max)();\n\t\t\t}\n\t\t} else if (r == -std::numeric_limits<double>::infinity()) {\n\t\t\treturn r;\n\t\t}\n\n\t\tif (fabs(r) >= th) {\n\t\t\tif (r2 < 0.) return pred(r);\n\t\t\treturn r;\n\t\t} else {\n\t\t\ttwoproduct(x * c, y * c, s, s2);\n\t\t\tt = (r * c) * c;\n\t\t\tif ( t > s || (t == s && s2 < 0.)) {\n\t\t\t\treturn pred(r);\n\t\t\t}\n\t\t\treturn r;\n\t\t}\n\t}\n\n\tstatic double div_up(const double& x, const double& y) {\n\t\tdouble r, r2;\n\t\tdouble xn, yn, d;\n\t\tstatic const double th1 = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double th2 = ldexp(1., 918); // 1023 - 105\n\t\tstatic const double c1 = ldexp(1., 105); // -969 - (-1074)\n\t\tstatic const double c2 = ldexp(1., -1074);\n\n\t\tif (x == 0. || y == 0. || std::fabs(x) == std::numeric_limits<double>::infinity() || std::fabs(y) == std::numeric_limits<double>::infinity() || x != x  || y != y) {\n\t\t\treturn x / y;\n\t\t}\n\n\t\tif (y < 0.) {\n\t\t\txn = -x;\n\t\t\tyn = -y;\n\t\t} else {\n\t\t\txn = x;\n\t\t\tyn = y;\n\t\t}\n\n\t\tif (fabs(xn) < th1) {\n\t\t\tif (fabs(yn) < th2) {\n\t\t\t\txn *= c1;\n\t\t\t\tyn *= c1;\n\t\t\t} else {\n\t\t\t\tif (xn < 0.) return 0.;\n\t\t\t\telse return c2;\n\t\t\t}\n\t\t}\n\n\t\td = xn / yn;\n\n\t\tif (d == std::numeric_limits<double>::infinity()) {\n\t\t\treturn d;\n\t\t} else if (d == -std::numeric_limits<double>::infinity()) {\n\t\t\treturn -(std::numeric_limits<double>::max)();\n\t\t}\n\n\t\ttwoproduct(d, yn, r, r2);\n\t\tif ( r < xn || ((r == xn) && r2 < 0.)) {\n\t\t\treturn succ(d);\n\t\t}\n\t\treturn d;\n\t}\n\n\tstatic double div_down(const double& x, const double& y) {\n\t\tdouble r, r2;\n\t\tdouble xn, yn, d;\n\t\tstatic const double th1 = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double th2 = ldexp(1., 918); // 1023 - 105\n\t\tstatic const double c1 = ldexp(1., 105); // -969 - (-1074)\n\t\tstatic const double c2 = ldexp(1., -1074);\n\n\t\tif (x == 0. || y == 0. || std::fabs(x) == std::numeric_limits<double>::infinity() || std::fabs(y) == std::numeric_limits<double>::infinity() || x != x  || y != y) {\n\t\t\treturn x / y;\n\t\t}\n\n\t\tif (y < 0.) {\n\t\t\txn = -x;\n\t\t\tyn = -y;\n\t\t} else {\n\t\t\txn = x;\n\t\t\tyn = y;\n\t\t}\n\n\t\tif (fabs(xn) < th1) {\n\t\t\tif (fabs(yn) < th2) {\n\t\t\t\txn *= c1;\n\t\t\t\tyn *= c1;\n\t\t\t} else {\n\t\t\t\tif (xn < 0.) return -c2;\n\t\t\t\telse return 0.;\n\t\t\t}\n\t\t}\n\n\t\td = xn / yn;\n\n\t\tif (d == std::numeric_limits<double>::infinity()) {\n\t\t\treturn (std::numeric_limits<double>::max)();\n\t\t} else if (d == -std::numeric_limits<double>::infinity()) {\n\t\t\treturn d;\n\t\t}\n\n\t\ttwoproduct(d, yn, r, r2);\n\t\tif ( r > xn || ((r == xn) && r2 > 0.)) {\n\t\t\treturn pred(d);\n\t\t}\n\t\treturn d;\n\t}\n\n\tstatic double sqrt_up(const double& x) {\n\t\tdouble r, r2, d;\n\t\tstatic const double th1 = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double c1 = ldexp(1., 106); // -969 - (-1074) + 1\n\t\tstatic const double c2 = ldexp(1., 53); // sqrt(c1)\n\n\t\td = sqrt(x);\n\n\t\tif (x < th1) {\n\t\t\tdouble d2, x2;\n\t\t\tx2 = x * c1;\n\t\t\td2 = d * c2;\n\t\t\ttwoproduct(d2, d2, r, r2);\n\t\t\tif ( r < x2 || (r == x2 && r2 < 0.)) {\n\t\t\t\treturn succ(d);\n\t\t\t}\n\t\t\treturn d;\n\t\t}\n\n\t\ttwoproduct(d, d, r, r2);\n\t\tif ( r < x || (r == x && r2 < 0.)) {\n\t\t\treturn succ(d);\n\t\t}\n\t\treturn d;\n\t}\n\n\tstatic double sqrt_down(const double& x) {\n\t\tdouble r, r2, d;\n\t\tstatic const double th1 = ldexp(1., -969); // -1074 + 106 - 1\n\t\tstatic const double c1 = ldexp(1., 106); // -969 - (-1074) + 1\n\t\tstatic const double c2 = ldexp(1., 53); // sqrt(c1)\n\n\t\td = sqrt(x);\n\n\t\tif (x < th1) {\n\t\t\tdouble d2, x2;\n\t\t\tx2 = x * c1;\n\t\t\td2 = d * c2;\n\t\t\ttwoproduct(d2, d2, r, r2);\n\t\t\tif ( r > x2 || (r == x2 && r2 > 0.)) {\n\t\t\t\treturn pred(d);\n\t\t\t}\n\t\t\treturn d;\n\t\t}\n\n\t\ttwoproduct(d, d, r, r2);\n\t\tif ( r > x || (r == x && r2 > 0.)) {\n\t\t\treturn pred(d);\n\t\t}\n\t\treturn d;\n\t}\n\n};\n\nbool samedouble(double x, double y)\n{\n\t// return *((unsigned long long *)(&x)) == *((unsigned long long *)(&y));\n\tif (x != x && y != y) return true;\n\treturn x == y;\n}\n\nvoid check(double x, double y)\n{\n\tvolatile double r1, r2;\n\n\tr1 = hwround::add_up(x, y);\n\tr2 = nohwround::add_up(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"add_up error\\n\"; std::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::add_down(x, y);\n\tr2 = nohwround::add_down(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"add_down error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::sub_up(x, y);\n\tr2 = nohwround::sub_up(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"sub_up error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::sub_down(x, y);\n\tr2 = nohwround::sub_down(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"sub_down error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::mul_up(x, y);\n\tr2 = nohwround::mul_up(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"mul_up error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::mul_down(x, y);\n\tr2 = nohwround::mul_down(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"mul_down error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::div_up(x, y);\n\tr2 = nohwround::div_up(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"div_up error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::div_down(x, y);\n\tr2 = nohwround::div_down(x, y);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"div_down error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << y << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::sqrt_up(x);\n\tr2 = nohwround::sqrt_up(x);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"sqrt_up error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n\n\tr1 = hwround::sqrt_down(x);\n\tr2 = nohwround::sqrt_down(x);\n\tif (!samedouble(r1, r2)) {\n\t\tstd::cout << \"sqrt_down error\\n\";\n\t\tstd::cout << x << \"\\n\";\n\t\tstd::cout << r1 << \"\\n\";\n\t\tstd::cout << r2 << \"\\n\";\n\t}\n}\n\nint main() {\n\tdouble x, y;\n\tint i, j;\n\tunsigned long long t;\n\n\tdouble specials[11] = {\n\t\t0., \n\t\t-0.,\n\t\tstd::numeric_limits<double>::infinity(),\n\t\t-std::numeric_limits<double>::infinity(),\n\t\t(std::numeric_limits<double>::max)(),\n\t\t-(std::numeric_limits<double>::max)(),\n\t\t(std::numeric_limits<double>::min)(),\n\t\t-(std::numeric_limits<double>::min)(),\n\t\tstd::numeric_limits<double>::denorm_min(),\n\t\t-std::numeric_limits<double>::denorm_min()\n\t};\n\tspecials[10] = specials[2] + specials[3]; // making NaN\n\n\tboost::variate_generator<boost::mt19937, boost::uniform_int<unsigned long long> > rand(boost::mt19937(time(0)), boost::uniform_int<unsigned long long>(0, -1));\n\n\tstd::cout.precision(17);\n\n\t// cause overflow of intermediate variable in twoproduct\n\t// x = 6.929001713869936e+236;\n\t// y = 2.5944475251952003e+71;\n\t// check(x, y);\n\n\t// cause overflow of intermediate variable in twosum\n\t// x = 3.5630624444874539e+307;\n\t// y = -1.7976931348623157e+308;\n\t// check(x, y);\n\n\t// check general-general case\n\n\tfor (i=0; i<NT; i++) {\n\t\tt = rand();\n\t\tx = *((double*)(&t));\n\t\tt = rand();\n\t\ty = *((double*)(&t));\n\t\tcheck(x, y);\n\t}\n\n\t// check general-special case\n\n\tfor (i=0; i<NT; i++) {\n\t\tt = rand();\n\t\tx = *((double*)(&t));\n\t\tfor (j=0; j<11; j++) {\n\t\t\ty = specials[j];\n\t\t\tcheck(x, y);\n\t\t\tcheck(y, x);\n\t\t}\n\t}\n\n\t// check special-special case\n\n\tfor (i=0; i<11; i++) {\n\t\tx = specials[i];\n\t\tfor (j=0; j<11; j++) {\n\t\t\ty = specials[j];\n\t\t\tcheck(x, y);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "602b26b5c01d55fdc4ad2b31f47c0809724e076a", "size": 15631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-nohwround.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-nohwround.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-nohwround.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": 22.1402266289, "max_line_length": 166, "alphanum_fraction": 0.5423197492, "num_tokens": 5750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5982901543225659}}
{"text": "#include <iostream>\n#include <unistd.h>\n#include <vector>\n#include \"OrthonormalHermite.h\"\n#include <Eigen/Dense>\n\nvoid printDetailsOfObject(unsigned int longSleep, unsigned int shortSleep, APPRSDK::OrthonormalHermite<double>& H1, bool showPartialDerivatives=false)\n{\n    std::cout<<\"Base points\"<<std::endl;\n    usleep(shortSleep);\n    std::cout<<H1.GetDomain()<<std::endl;\n    std::cout<<\"END OF BASE POINTS\"<<std::endl<<std::endl;\n    usleep(longSleep);\n\n    std::cout<<\"Retrieving calculated first degree Hermite function\"<<std::endl;\n    usleep(shortSleep);\n    std::cout<<H1.GetFunctionSystem().col(0)<<std::endl;\n    std::cout<<\"END OF HERMITE FUNCTION OUTPUT\"<<std::endl<<std::endl;\n    usleep(longSleep);\n\n    std::cout<<\"Retrieving calculated third degree Hermite function\"<<std::endl;\n    usleep(shortSleep);\n    std::cout<<H1.GetFunctionSystem().col(4)<<std::endl;\n    std::cout<<\"END OF HERMITE FUNCTION OUTPUT\"<<std::endl<<std::endl;\n    usleep(longSleep);\n\n    std::cout<<\"Retrieving calculated derivative first degree\"<<std::endl;\n    usleep(shortSleep);\n    std::cout<<H1.GetDFunctionSystem().col(0)<<std::endl;\n    std::cout<<\"END OF DERIVATIVE OUTPUT\"<<std::endl;\n    usleep(longSleep);\n\n    std::cout<<\"Retrieving calculated derivative third degree\"<<std::endl;\n    usleep(shortSleep);\n    std::cout<<H1.GetDFunctionSystem().col(4)<<std::endl;\n    std::cout<<\"END OF DERIVATIVE OUTPUT\"<<std::endl;\n    usleep(longSleep);\n\n    if (showPartialDerivatives)\n    {\n        std::cout<<\"Retrieving partial derivatives third and fourth columns\"<<std::endl;\n        usleep(shortSleep);\n        std::cout<<H1.GetPartialDerivativesFunctionSystem().col(4)<<std::endl;\n        std::cout<<\"END OF THIRD COLUMN\"<<std::endl;\n        std::cout<<H1.GetPartialDerivativesFunctionSystem().col(5)<<std::endl;\n        std::cout<<\"END OF PARTIAL DERIVATIVE OUTPUT\"<<std::endl;\n        usleep(longSleep);\n\n        std::cout<<\"Retrieving index values\"<<std::endl;\n        usleep(shortSleep);\n        std::cout<<H1.GetIndex()<<std::endl;\n        std::cout<<\"END OF INDEX OUTPUT\"<<std::endl;\n    }\n}\n\nint main()\n{\n    const unsigned int longSleep = 3000;\n    const unsigned int shortSleep = 1000;\n    Eigen::Matrix<double, 1, 2> params;\n\n    std::cout<<\"Function system test begun...\"<<std::endl;\n    APPRSDK::OrthonormalHermite<double> H1(100, 10);\n    std::cout<<\"OrthonormalHermite object succesfully created\"<<std::endl;\n\n    printDetailsOfObject(longSleep, shortSleep, H1);\n\n    std::cout<<\"Applying parameters: lambda = 0.5, t = 50\"<<std::endl;\n    params(0,0) = 0.5;\n    params(0,1) = 50;\n    H1.ApplyNonLinearParameters(params);\n    std::cout<<\"Paramtere application succesful. Printing results...\";\n    usleep(shortSleep);\n\n    printDetailsOfObject(longSleep, shortSleep, H1, true);\n\n    return 0;\n}", "meta": {"hexsha": "e33720c016fbefb860012a81501f9aa5a807ff87", "size": 2800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testFunctionSystemsWithHermite.cpp", "max_stars_repo_name": "tamasdzs/APPRSDK", "max_stars_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/testFunctionSystemsWithHermite.cpp", "max_issues_repo_name": "tamasdzs/APPRSDK", "max_issues_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testFunctionSystemsWithHermite.cpp", "max_forks_repo_name": "tamasdzs/APPRSDK", "max_forks_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8974358974, "max_line_length": 150, "alphanum_fraction": 0.6714285714, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5982809533424085}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\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/*! \\file isotropicrandomwalk.hpp\n    \\brief Isotropic random walk\n*/\n\n#ifndef quantlib_isotropic_random_walk_hpp\n#define quantlib_isotropic_random_walk_hpp\n\n#include <ql/mathconstants.hpp>\n#include <ql/math/randomnumbers/mt19937uniformrng.hpp>\n#include <ql/math/array.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace QuantLib {\n\n    //! Isotropic random walk\n    /*! A variate is used to draw from a random element of a \n        probability distribution. The draw corresponds to the \n        radius of a d-dimensional sphere. The position on the\n        surface of the d-dimensional sphere is randomly chosen\n        with all points on the surface having the same probability,\n        i.e. all directions are isotropic and the step is randomly\n        drawn from the given variate.\n    */\n    template <class Distribution, class Engine>\n    class IsotropicRandomWalk {\n      public:\n        typedef boost::variate_generator<Engine, Distribution> VariateGenerator;\n        IsotropicRandomWalk(const Engine& eng, Distribution dist, Size dim,\n                            const Array& weights = Array(), \n                            unsigned long seed = 0) :\n            variate_(eng, dist), rng_(seed), \n            weights_(weights), dim_(dim) {\n            if (weights_.empty())\n                weights_ = Array(dim, 1.0);\n            else\n                QL_REQUIRE(dim_ == weights_.size(), \"Invalid weights\");\n        }\n        template <class InputIterator>\n        inline void nextReal(InputIterator first) const {\n            Real radius = variate_();\n            Array::const_iterator weight = weights_.begin();\n            if (dim_ > 1) {\n                //Isotropic random direction\n                Real phi = M_PI*rng_.nextReal();\n                for (Size i = 0; i < dim_ - 2; i++) {\n                    *first++ = radius*cos(phi)*(*weight++);\n                    radius *= sin(phi);\n                    phi = M_PI*rng_.nextReal();\n                }\n                *first++ = radius*cos(2.0*phi)*(*weight++);\n                *first = radius*sin(2.0*phi)*(*weight);\n            }\n            else {\n                if (rng_.nextReal() < 0.5)\n                    *first = -radius*(*weight);\n                else\n                    *first = radius*(*weight);\n            }\n        }\n        inline void setDimension(Size dim) { \n            dim_ = dim;\n            weights_ = Array(dim, 1.0);\n        }\n        inline void setDimension(Size dim, const Array& weights) {\n            QL_REQUIRE(dim == weights.size(), \"Invalid weights\");\n            dim_ = dim;\n            weights_ = weights;\n        }\n        /*!\n        The isotropic random walk will not adjust its draw to be within the lower and upper bounds,\n        but if the limits are provided, they are used to rescale the sphere so as to make it to an\n        ellipsoid, with different radius in different dimensions.\n        */\n        inline void setDimension(Size dim,\n            const Array& lowerBound, const Array& upperBound) {\n            QL_REQUIRE(dim == lowerBound.size(),\n                \"Incompatible dimension and lower bound\");\n            QL_REQUIRE(dim == upperBound.size(),\n                \"Incompatible dimension and upper bound\");\n            //Find largest bound\n            Array bounds = upperBound - lowerBound;\n            Real maxBound = bounds[0];\n            for (Size j = 1; j < dim; j++) {\n                if (bounds[j] > maxBound) maxBound = bounds[j];\n            }\n            //weights by dimension is the size of the bound\n            //divided by the largest bound\n            maxBound = 1.0 / maxBound;\n            bounds *= maxBound;\n            setDimension(dim, bounds);\n        }\n      protected:\n        mutable VariateGenerator variate_;\n        MersenneTwisterUniformRng rng_;\n        Array weights_;\n        Size dim_;\n    };\n}\n#endif\n", "meta": {"hexsha": "b4a9723e3247ae946bad2a99ec455d39c8d64b7f", "size": 4667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/isotropicrandomwalk.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-30T17:51:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T17:51:09.000Z", "max_issues_repo_path": "ql/experimental/math/isotropicrandomwalk.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/experimental/math/isotropicrandomwalk.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-24T17:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T09:41:33.000Z", "avg_line_length": 39.218487395, "max_line_length": 99, "alphanum_fraction": 0.5920291408, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5982809522036745}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/zlib.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <cassert>\n#include <cinttypes>\n#include <fstream>\n#include <iostream>\n#include <limits>  // std::numeric_limits\n#include <typeinfo>\n#include <vector>\n\n#include \"fft.hpp\"\n#include \"progressbar.hpp\"\n\nusing namespace boost::gil;\nusing Eigen::MatrixXcd, Eigen::MatrixXd;\nusing std::vector;\n\n// member typedefs provided through inheriting from std::iterator\ntemplate <typename Pixel_t, typename Original_t>\nclass channel_iterator\n    : public std::iterator<\n          std::random_access_iterator_tag,  // iterator_category\n          Pixel_t                           // value_type\n          > {\n  const Original_t& original;\n  size_t channel;\n\n public:\n  explicit channel_iterator(const Original_t& original, size_t channel)\n      : original(original), channel(channel){};\n  const Pixel_t& operator[](size_t n) const { return original[n][channel]; };\n};\n\ntemplate <typename ImgView>\nvector<Eigen::MatrixXcd> dft(const ImgView& src) {\n  typedef std::complex<double> complex;\n  typedef Eigen::Matrix<complex, -1, -1, Eigen::ColMajor> mattype;\n\n  typedef typename channel_type<ImgView>::type cs_t;\n\n  auto h = src.height();\n  auto w = src.width();\n  constexpr auto nc = num_channels<ImgView>::value;\n  vector<mattype> dfts;\n  dfts.reserve(nc);\n  for (size_t k = 0; k < nc; k++) dfts.push_back(mattype(h, w));\n\n  progressbar bar((h + w) * nc);\n\n  // first do fourier traffo of rows\n  for (int y = 0; y < h; y++) {\n    typename ImgView::x_iterator src_it = src.row_begin(y);\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      std::vector<complex> buf;\n      buf.resize(w);\n      if constexpr (nc == 1) {\n        fft(src_it, buf.data(), w);\n      } else {\n        auto src_channel_it =\n            channel_iterator<cs_t, typename ImgView::x_iterator>(src_it, c);\n        fft(src_channel_it, buf.data(), w);\n      }\n      for (int x = 0; x < w; x++) dfts[c](y, x) = buf[x];\n    }\n  }\n\n  // now of cols\n  for (int x = 0; x < w; x++) {\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      std::vector<complex> buf;\n      buf.resize(h);\n      fft(&(dfts[c](0, x)), buf.data(), h);\n\n      for (int y = 0; y < h; y++) dfts[c](y, x) = buf[y];\n    }\n  }\n\n  return dfts;\n}\n\ntemplate <typename ImgView>\nvector<Eigen::MatrixXd> dct(const ImgView& src) {\n  typedef Eigen::Matrix<double, -1, -1, Eigen::ColMajor> mattype;\n\n  typedef typename channel_type<ImgView>::type cs_t;\n\n  auto h = src.height();\n  auto w = src.width();\n  auto nc = num_channels<ImgView>::value;\n  vector<mattype> dfts;\n  dfts.reserve(nc);\n  for (size_t k = 0; k < nc; k++) dfts.push_back(mattype(h, w));\n\n  progressbar bar((h + w) * nc);\n\n  // first do fourier traffo of rows\n  std::vector<double> buf;\n  buf.resize(w);\n  for (int y = 0; y < h; y++) {\n    typename ImgView::x_iterator src_it = src.row_begin(y);\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      auto src_channel_it =\n          channel_iterator<cs_t, typename ImgView::x_iterator>(src_it, c);\n      dct(src_channel_it, buf.data(), w);\n      for (int x = 0; x < w; x++) dfts[c](y, x) = buf[x];\n    }\n  }\n\n  // now of cols\n  buf.resize(h);\n  for (int x = 0; x < w; x++) {\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      dct(&(dfts[c](0, x)), buf.data(), h);\n\n      for (int y = 0; y < h; y++) dfts[c](y, x) = buf[y];\n    }\n  }\n\n  return dfts;\n}\n\ntemplate <typename ImgView>\nvector<Eigen::MatrixXd> idct(const ImgView& src) {\n  typedef Eigen::Matrix<double, -1, -1, Eigen::ColMajor> mattype;\n\n  typedef typename channel_type<ImgView>::type cs_t;\n\n  auto h = src.height();\n  auto w = src.width();\n  auto nc = num_channels<ImgView>::value;\n  vector<mattype> dfts;\n  dfts.reserve(nc);\n  for (size_t k = 0; k < nc; k++) dfts.push_back(mattype(h, w));\n\n  progressbar bar((h + w) * nc);\n\n  // first do fourier traffo of rows\n  for (int y = 0; y < h; y++) {\n    typename ImgView::x_iterator src_it = src.row_begin(y);\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      auto src_channel_it =\n          channel_iterator<cs_t, typename ImgView::x_iterator>(src_it, c);\n      std::vector<double> buf;\n      buf.resize(w);\n      idct(src_channel_it, buf.data(), w);\n      for (int x = 0; x < w; x++) dfts[c](y, x) = buf[x];\n    }\n  }\n\n  // now of cols\n  for (int x = 0; x < w; x++) {\n    for (size_t c = 0; c < nc; c++) {\n      bar.update();\n      std::vector<double> buf;\n      buf.resize(h);\n      idct(&(dfts[c](0, x)), buf.data(), h);\n\n      for (int y = 0; y < h; y++) dfts[c](y, x) = buf[y];\n    }\n  }\n\n  return dfts;\n}\n\nstd::tuple<double, double> mag_bounds(MatrixXcd& mat) {\n  double max = 0;\n  double min = std::numeric_limits<double>::max();\n  for (Eigen::Index row = 0; row < mat.rows(); row++)\n    for (Eigen::Index col = 0; col < mat.cols(); col++) {\n      double val = std::abs(mat(row, col));\n      if (val > max) max = val;\n      if (val < min) min = val;\n    }\n  return {min, max};\n}\n\nstd::tuple<double, double> bounds(MatrixXd& mat) {\n  double max = std::numeric_limits<double>::min();\n  double min = std::numeric_limits<double>::max();\n  for (Eigen::Index row = 0; row < mat.rows(); row++)\n    for (Eigen::Index col = 0; col < mat.cols(); col++) {\n      double val = mat(row, col);\n      if (val > max) max = val;\n      if (val < min) min = val;\n    }\n  return {min, max};\n}\n\nstd::tuple<double, double> real_bounds(MatrixXcd& mat) {\n  double max = std::numeric_limits<double>::min();\n  double min = std::numeric_limits<double>::max();\n  for (Eigen::Index row = 0; row < mat.rows(); row++)\n    for (Eigen::Index col = 0; col < mat.cols(); col++) {\n      double val = mat(row, col).real();\n      if (val > max) max = val;\n      if (val < min) min = val;\n    }\n  return {min, max};\n}\n\ntemplate <typename SrcView, typename DstView>\nvoid dft(const SrcView& src, DstView& dst_mag, DstView& dst_phase,\n         bool shifted = true, bool log = true) {\n  assert(src.dimensions() == dst_mag.dimensions());\n  assert(src.dimensions() == dst_phase.dimensions());\n\n  typedef typename channel_type<DstView>::type cs_t;\n  cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  auto mats = dft(src);\n\n  std::vector<std::tuple<double, double>> limits;\n  limits.reserve(mats.size());\n  for (size_t k = 0; k < mats.size(); k++)\n    limits.push_back(mag_bounds(mats[k]));\n\n  auto w = dst_mag.width();\n  auto h = dst_mag.height();\n\n  for (int y = 0; y < h; y++) {\n    typename DstView::x_iterator dst_mag_it = dst_mag.row_begin(y);\n    typename DstView::x_iterator dst_phase_it = dst_phase.row_begin(y);\n    for (int x = 0; x < w; x++)\n      for (size_t c = 0; c < mats.size(); c++) {\n        auto [min, max] = limits[c];\n        Eigen::Index xcord, ycord;\n        if (shifted) {\n          ycord = (y + h / 2) % h;\n          xcord = (x + w / 2) % w;\n        } else {\n          xcord = x;\n          ycord = y;\n        }\n        if (log) {\n          dst_mag_it[x][c] =\n              (std::log(std::abs(mats[c](ycord, xcord))) - std::log(min)) /\n              (std::log(max) - std::log(min)) * max_val;\n        } else {\n          dst_mag_it[x][c] = ((std::abs(mats[c](ycord, xcord))) - (min)) /\n                             ((max) - (min)) * max_val;\n        }\n        dst_phase_it[x][c] =\n            std::arg(mats[c](ycord, xcord)) / 2. / pi * max_val;\n      }\n  }\n}\n\ntemplate <typename SrcView, typename DstView>\nvoid dct(const SrcView& src, DstView& dst) {\n  assert(src.dimensions() == dst.dimensions());\n\n  // typedef typename channel_type<DstView>::type cs_t;\n  // cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  auto mats = dct(src);\n\n  std::vector<std::tuple<double, double>> limits;\n  limits.reserve(mats.size());\n  for (size_t k = 0; k < mats.size(); k++) limits.push_back(bounds(mats[k]));\n\n  auto w = dst.width();\n  auto h = dst.height();\n\n  for (int y = 0; y < h; y++) {\n    typename DstView::x_iterator dst_it = dst.row_begin(y);\n    for (int x = 0; x < w; x++)\n      for (size_t c = 0; c < mats.size(); c++) {\n        // auto [min, max] = limits[c];\n        dst_it[x][c] = mats[c](y, x);\n      }\n  }\n}\n\ntemplate <typename SrcView, typename DstView>\nvoid idct(const SrcView& src, DstView& dst) {\n  assert(src.dimensions() == dst.dimensions());\n\n  typedef typename channel_type<DstView>::type cs_t;\n  cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  auto mats = idct(src);\n\n  std::vector<std::tuple<double, double>> limits;\n  limits.reserve(mats.size());\n  for (size_t k = 0; k < mats.size(); k++) limits.push_back(bounds(mats[k]));\n\n  auto w = dst.width();\n  auto h = dst.height();\n\n  for (int y = 0; y < h; y++) {\n    typename DstView::x_iterator dst_it = dst.row_begin(y);\n    for (int x = 0; x < w; x++)\n      for (size_t c = 0; c < mats.size(); c++) {\n        auto [min, max] = limits[c];\n        dst_it[x][c] = (mats[c](y, x) - min) / (max - min) * max_val;\n        ;\n      }\n  }\n}\n\nsize_t closest_smaller_power2(size_t number) {\n  size_t log2n = 0;\n  while ((number >> ++log2n) > 0) {\n  };\n\n  return 1 << (log2n - 1);\n}\n\ntemplate <typename DstView>\nvoid to_image(vector<MatrixXcd>& src, DstView& dst) {\n  assert(src[0].cols() == dst.width());\n  assert(src[0].rows() == dst.height());\n\n  typedef typename channel_type<DstView>::type cs_t;\n  cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  std::vector<std::tuple<double, double>> limits;\n  limits.reserve(src.size());\n  for (size_t k = 0; k < src.size(); k++) limits.push_back(mag_bounds(src[k]));\n\n  auto w = src[0].cols();\n  auto h = src[0].rows();\n\n  for (int y = 0; y < h; y++) {\n    typename DstView::x_iterator dst_it = dst.row_begin(y);\n    for (int x = 0; x < w; x++)\n      for (size_t c = 0; c < src.size(); c++) {\n        auto [min, max] = limits[c];\n\n        dst_it[x][c] = std::abs(src[c](y, x)) / max * max_val;\n      }\n  }\n}\n\ntemplate <typename DstView>\nvoid to_image_mag(vector<MatrixXcd>& src, DstView& dst) {\n  assert(src[0].cols() == dst.width());\n  assert(src[0].rows() == dst.height());\n\n  typedef typename channel_type<DstView>::type cs_t;\n  cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  std::vector<std::tuple<double, double>> limits;\n  limits.reserve(src.size());\n  for (size_t k = 0; k < src.size(); k++) limits.push_back(mag_bounds(src[k]));\n\n  auto w = src[0].cols();\n  auto h = src[0].rows();\n\n  for (int y = 0; y < h; y++) {\n    typename DstView::x_iterator dst_it = dst.row_begin(y);\n    for (int x = 0; x < w; x++)\n      for (size_t c = 0; c < src.size(); c++) {\n        auto [min, max] = limits[c];\n\n        auto ycord = (y + h / 2) % h;\n        auto xcord = (x + w / 2) % w;\n        dst_it[x][c] = (std::log(std::abs(src[c](ycord, xcord)) + 1e-6) -\n                        std::log(min + 1e-6)) /\n                       (std::log(max) - std::log(min + 1e-6)) * max_val;\n      }\n  }\n}\n\nvoid apply_filter(const char* from, const char* to, const char* fs,\n                  std::function<void(MatrixXcd&)> filter, bool gray = false) {\n  rgb8_image_t img;\n  read_image(from, img, png_tag());\n\n  // typedef typename channel_type<rgb8_image_t>::type cs_t;\n  // cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  std::vector<MatrixXcd> mats;\n  if (gray) {\n    mats = dft(color_converted_view<gray8_pixel_t>(view(img)));\n  } else\n    mats = dft(view(img));\n\n  auto w = img.width();\n  auto h = img.height();\n\n  // apply filter\n  for (size_t c = 0; c < mats.size(); c++) filter(mats[c]);\n\n  if (gray) {\n    gray8_image_t img_control(img.dimensions());\n    to_image_mag(mats, view(img_control));\n    write_view(fs, view(img_control), png_tag());\n  } else {\n    rgb8_image_t img_control(img.dimensions());\n    to_image_mag(mats, view(img_control));\n    write_view(fs, view(img_control), png_tag());\n  }\n\n  // transform back\n  // first do fourier traffo of rows\n  progressbar bar((h + w) * mats.size());\n  std::vector<complex<double>> buf;\n  buf.resize(w);\n  for (int y = 0; y < h; y++) {\n    for (size_t c = 0; c < mats.size(); c++) {\n      bar.update();\n      ifft(mats[c].row(y), buf.data(), w);\n      for (int x = 0; x < w; x++) mats[c](y, x) = buf[x];\n    }\n  }\n  // now of columns\n  buf.resize(h);\n  for (int x = 0; x < w; x++) {\n    for (size_t c = 0; c < mats.size(); c++) {\n      bar.update();\n      ifft(mats[c].col(x), buf.data(), h);\n      for (int y = 0; y < h; y++) mats[c](y, x) = buf[y];\n    }\n  }\n\n  if (gray) {\n    gray8_image_t sharpened(img.dimensions());\n    to_image(mats, view(sharpened));\n\n    write_view(to, view(sharpened), png_tag());\n  } else {\n    rgb8_image_t sharpened(img.dimensions());\n    to_image(mats, view(sharpened));\n\n    write_view(to, view(sharpened), png_tag());\n  }\n}\n\nvoid sharpen(const char* from, const char* to, const char* fs, double radius,\n             bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        double limit = radius * std::min(mat.cols(), mat.rows()) / 2.;\n        limit *= limit;\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n            if (pos_x * pos_x + pos_y * pos_y < limit) {\n              mat(y, x) = 0;\n            }\n          }\n      },\n      gray);\n}\n\nvoid sharpen_smooth(const char* from, const char* to, const char* fs,\n                    double exp_fac, bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n\n            double r2 = pos_x * pos_x + pos_y * pos_y;\n            mat(y, x) *= (1 - std::exp(-r2 * exp_fac));\n          }\n      },\n      gray);\n}\n\nvoid blur_smooth(const char* from, const char* to, const char* fs,\n                 double exp_fac, bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n\n            double r2 = pos_x * pos_x + pos_y * pos_y;\n            mat(y, x) *= std::exp(-r2 * exp_fac);\n          }\n      },\n      gray);\n}\n\nvoid blur(const char* from, const char* to, const char* fs, double radius,\n          bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        double limit = radius * std::min(mat.cols(), mat.rows()) / 2.;\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n            if (pos_x * pos_x + pos_y * pos_y > limit * limit) {\n              mat(y, x) = 0;\n            }\n          }\n      },\n      gray);\n}\n\nvoid rect_filter(const char* from, const char* to, const char* fs, double width,\n                 double height, bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n            if (pos_x > mat.cols() * width / 2 ||\n                pos_x < -mat.cols() * width / 2 ||\n                pos_y > mat.rows() * height / 2 ||\n                pos_y < -mat.rows() * height / 2) {\n              mat(y, x) = 0;\n            }\n          }\n      },\n      gray);\n}\n\nvoid anti_rect_filter(const char* from, const char* to, const char* fs,\n                      double width, double height, bool gray = false) {\n  apply_filter(\n      from, to, fs,\n      [&](MatrixXcd& mat) {\n        for (int x = 0; x < mat.cols(); x++)\n          for (int y = 0; y < mat.rows(); y++) {\n            double pos_x =\n                ((x + mat.cols() / 2) % mat.cols()) - (mat.cols() - 1) / 2.;\n            double pos_y =\n                ((y + mat.rows() / 2) % mat.rows()) - (mat.rows() - 1) / 2.;\n            if (!(pos_x > mat.cols() * width / 2 ||\n                  pos_x < -mat.cols() * width / 2 ||\n                  pos_y > mat.rows() * height / 2 ||\n                  pos_y < -mat.rows() * height / 2)) {\n              mat(y, x) = 0;\n            }\n          }\n      },\n      gray);\n}\n\ntypedef uint_least16_t pos_t;\ntypedef uint_least8_t channel_t;\ntypedef std::tuple<pos_t, pos_t, channel_t> index_t;\nvoid compress_image(const char* from, const char* to,\n                    double compression_level) {\n  rgb8_image_t img;\n  read_image(from, img, png_tag());\n  std::cout << \"Image read! Dimensions x: \" << img.dimensions().x\n            << \" y: \" << img.dimensions().y << std::endl;\n\n  // typedef typename channel_type<rgb8_image_t>::type cs_t;\n  // cs_t max_val = std::numeric_limits<cs_t>::max();\n\n  auto mats = dct(view(img));\n  // x, y, c\n  std::vector<index_t> indices;\n\n  indices.reserve(mats[0].cols() * mats[0].rows() * mats.size());\n  for (Eigen::Index x = 0; x < mats[0].cols(); x++)\n    for (Eigen::Index y = 0; y < mats[0].rows(); y++)\n      for (size_t c = 0; c < mats.size(); c++) indices.push_back({x, y, c});\n\n  std::sort(indices.begin(), indices.end(),\n            [&](index_t& a, index_t& b) -> bool {\n              auto [xa, ya, ca] = a;\n              auto [xb, yb, cb] = b;\n              return std::abs(mats[ca](ya, xa)) > std::abs(mats[cb](yb, xb));\n            });\n\n  std::fstream file(to, file.binary | file.trunc | file.out);\n  if (!file.is_open()) {\n    throw std::runtime_error(\"failed to open file\");\n  } else {\n    boost::iostreams::filtering_ostream os;\n    os.push(boost::iostreams::zlib_compressor());\n    os.push(file);\n    // write dimensions\n    uint_least16_t width = mats[0].cols();\n    uint_least16_t height = mats[0].rows();\n    os.write(reinterpret_cast<char*>(&width), sizeof width);  // binary output\n    os.write(reinterpret_cast<char*>(&height),\n             sizeof height);  // binary output\n\n    size_t lastk = indices.size() * compression_level;\n    progressbar b2(lastk);\n\n    for (size_t k = 0; k < lastk; k++) {\n      b2.update();\n      auto [x, y, c] = indices[k];\n      float val = mats[c](y, x);\n\n      os.write(reinterpret_cast<char*>(&x), sizeof x);      // binary output\n      os.write(reinterpret_cast<char*>(&y), sizeof y);      // binary output\n      os.write(reinterpret_cast<char*>(&c), sizeof c);      // binary output\n      os.write(reinterpret_cast<char*>(&val), sizeof val);  // binary output\n    }\n  }\n}\n\nvoid decompress_image(const char* from, const char* to) {\n  std::fstream file(from, file.binary | file.in);\n  if (!file.is_open()) {\n    throw std::runtime_error(\"failed to open file\");\n  }\n  boost::iostreams::filtering_istream is;\n  is.push(boost::iostreams::zlib_decompressor());\n  is.push(file);\n  // read dimensions\n  uint_least16_t width, height;\n  is.read(reinterpret_cast<char*>(&width), sizeof width);\n  is.read(reinterpret_cast<char*>(&height), sizeof height);\n  std::vector<MatrixXd> mats;\n  for (int c = 0; c < 3; c++) mats.push_back(MatrixXd::Zero(height, width));\n\n  while (!is.eof()) {\n    pos_t x, y;\n    channel_t c;\n    float val;\n\n    is.read(reinterpret_cast<char*>(&x), sizeof x);      // binary input\n    is.read(reinterpret_cast<char*>(&y), sizeof y);      // binary input\n    is.read(reinterpret_cast<char*>(&c), sizeof c);      // binary input\n    is.read(reinterpret_cast<char*>(&val), sizeof val);  // binary input\n\n    mats[c](y, x) = val;\n  }\n\n  // first do fourier traffo of rows\n  std::vector<double> buf;\n  buf.resize(width);\n  for (int y = 0; y < height; y++) {\n    for (size_t c = 0; c < 3; c++) {\n      idct(mats[c].row(y), buf.data(), width);\n      for (int x = 0; x < width; x++) mats[c](y, x) = buf[x];\n    }\n  }\n\n  rgb8_image_t img(width, height);\n  // typedef typename channel_type<rgb8_image_t>::type cs_t;\n  // cs_t max_val = std::numeric_limits<cs_t>::max();\n  auto img_view = view(img);\n\n  // now of cols\n  buf.resize(height);\n  for (int x = 0; x < width; x++) {\n    for (size_t c = 0; c < 3; c++) {\n      idct(mats[c].col(x), buf.data(), height);\n      for (int y = 0; y < height; y++) img_view(x, y)[c] = buf[y];\n    }\n  }\n\n  write_view(to, img_view, png_tag());\n}\n\nvoid dft_image(const char* from, const char* to_mag, const char* to_phase,\n               bool crop = true, bool log = true, bool shifted = true) {\n  rgb8_image_t img;\n  read_image(from, img, png_tag());\n  std::cout << \"Image read! Dimensions x: \" << img.dimensions().x\n            << \" y: \" << img.dimensions().y << std::endl;\n\n  rgb8_image_t img_ft_mag, img_ft_phase;\n  if (crop) {\n    auto subw = closest_smaller_power2(img.width());\n    auto subh = closest_smaller_power2(img.height());\n    auto sub_img = subimage_view(view(img), 0, 0, subw, subh);\n    img_ft_mag = rgb8_image_t(sub_img.dimensions());\n    img_ft_phase = rgb8_image_t(sub_img.dimensions());\n    dft(sub_img, view(img_ft_mag), view(img_ft_phase), shifted, log);\n  } else {\n    img_ft_mag = rgb8_image_t(img.dimensions());\n    img_ft_phase = rgb8_image_t(img.dimensions());\n    dft(view(img), view(img_ft_mag), view(img_ft_phase), shifted, log);\n  }\n\n  write_view(to_mag, view(img_ft_mag), png_tag());\n  write_view(to_phase, view(img_ft_phase), png_tag());\n}\n\nvoid dct_image(const char* from, const char* to, bool crop = false) {\n  rgb8_image_t img;\n  read_image(from, img, png_tag());\n  std::cout << \"Image read! Dimensions x: \" << img.dimensions().x\n            << \" y: \" << img.dimensions().y << std::endl;\n\n  rgb8_image_t img_dct;\n  if (crop) {\n    auto subw = closest_smaller_power2(img.width());\n    auto subh = closest_smaller_power2(img.height());\n    auto sub_img = subimage_view(view(img), 0, 0, subw, subh);\n    img_dct = rgb8_image_t(sub_img.dimensions());\n    dct(sub_img, view(img_dct));\n  } else {\n    img_dct = rgb8_image_t(img.dimensions());\n    dct(view(img), view(img_dct));\n  }\n\n  write_view(to, view(img_dct), png_tag());\n}\n\nvoid idct_image(const char* from, const char* to, bool crop = false) {\n  rgb8_image_t img;\n  read_image(from, img, png_tag());\n  std::cout << \"Image read! Dimensions x: \" << img.dimensions().x\n            << \" y: \" << img.dimensions().y << std::endl;\n\n  rgb8_image_t img_dct;\n  if (crop) {\n    auto subw = closest_smaller_power2(img.width());\n    auto subh = closest_smaller_power2(img.height());\n    auto sub_img = subimage_view(view(img), 0, 0, subw, subh);\n    img_dct = rgb8_image_t(sub_img.dimensions());\n    idct(sub_img, view(img_dct));\n  } else {\n    img_dct = rgb8_image_t(img.dimensions());\n    idct(view(img), view(img_dct));\n  }\n\n  write_view(to, view(img_dct), png_tag());\n}\n\nvoid image_test() {\n  using namespace boost::gil;\n\n  std::string filename(\"images/webb.png\");\n  rgb8_image_t img;\n  read_image(filename, img, png_tag());\n  std::cout << \"Image read! Dimensions x: \" << img.dimensions().x\n            << \" y: \" << img.dimensions().y << std::endl;\n\n  gray8_image_t img_ft_mag(img.dimensions());\n  gray8_image_t img_ft_phase(img.dimensions());\n  std::cout << \"Now performing a gray naive fourier transform\" << std::endl;\n\n  // dft(color_converted_view<gray8_pixel_t>(view(img)), view(img_ft_mag),\n  // view(img_ft_phase));\n  std::cout << \"Saving image\" << std::endl;\n  write_view(\"build/output/test_mag.png\", view(img_ft_mag), png_tag());\n  write_view(\"build/output/test_phase.png\", view(img_ft_phase), png_tag());\n\n  std::cout\n      << \"Now performing a fourier transform of closest power of two subimage\"\n      << std::endl;\n  auto subw = closest_smaller_power2(img.width());\n  auto subh = closest_smaller_power2(img.height());\n  auto sub_img = subimage_view(color_converted_view<gray8_pixel_t>(view(img)),\n                               0, 0, subw, subh);\n  gray8_image_t img_sub_ft_mag(sub_img.dimensions());\n  gray8_image_t img_sub_ft_phase(sub_img.dimensions());\n\n  dft(sub_img, view(img_sub_ft_mag), view(img_sub_ft_phase));\n  std::cout << \"Saving image\" << std::endl;\n  write_view(\"build/output/sub_test_mag.png\", view(img_sub_ft_mag), png_tag());\n  write_view(\"build/output/sub_test_phase.png\", view(img_sub_ft_phase),\n             png_tag());\n\n  std::cout << \"Now performing a colored fourier transform of closest power of \"\n               \"two subimage\"\n            << std::endl;\n  auto sub_img_c = subimage_view(view(img), 0, 0, subw, subh);\n  rgb8_image_t img_sub_c_ft_mag(sub_img_c.dimensions());\n  rgb8_image_t img_sub_c_ft_phase(sub_img_c.dimensions());\n\n  dft(sub_img_c, view(img_sub_c_ft_mag), view(img_sub_c_ft_phase));\n  std::cout << \"Saving image\" << std::endl;\n  write_view(\"build/output/sub_c_test_mag.png\", view(img_sub_c_ft_mag),\n             png_tag());\n  write_view(\"build/output/sub_c_test_phase.png\", view(img_sub_c_ft_phase),\n             png_tag());\n\n  std::cout << \"Now performing a colored cosine transform of closest power of \"\n               \"two subimage\"\n            << std::endl;\n  rgb8_image_t img_sub_c_dct(sub_img_c.dimensions());\n\n  dct(sub_img_c, view(img_sub_c_dct));\n  std::cout << \"Saving image\" << std::endl;\n  write_view(\"build/output/sub_c_test_dct.png\", view(img_sub_c_dct), png_tag());\n}\n\nvoid sharpen_test() {\n  sharpen(\"images/dune.png\", \"build/output/dune_sharp.png\",\n          \"build/output/dune_sharp_mask.png\", .1);\n  blur(\"images/dune.png\", \"build/output/dune_blur.png\",\n       \"build/output/dune_blur_mask.png\", .5);\n}\n\nvoid compress_test() {\n  compress_image(\"images/dune.png\", \"build/output/dune_cmp.ldw\", .01);\n  decompress_image(\"build/output/dune_cmp.ldw\", \"build/output/reconst.png\");\n}", "meta": {"hexsha": "33577d0de5efb1e4f2b56e4c0ad310bad428d6ae", "size": 26153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Project08-ImageFourierTransform/image_fft.hpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project08-ImageFourierTransform/image_fft.hpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project08-ImageFourierTransform/image_fft.hpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.128992629, "max_line_length": 80, "alphanum_fraction": 0.5723243987, "num_tokens": 7739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5982809422809472}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <sm/assert_macros.hpp>\n#include <sm/kinematics/rotations.hpp>\n#include <sm/kinematics/three_point_methods.hpp>\n\nnamespace sm {\nnamespace kinematics {\n\n// Original code from the ROS vslam package pe3d.cpp\n// uses the SVD procedure for aligning point clouds\n//   SEE: Arun, Huang, Blostein: Least-Squares Fitting of Two 3D Point Sets\nEigen::Matrix4d threePointSvd(Eigen::MatrixXd const& p0, Eigen::MatrixXd const& p1) {\n    using namespace Eigen;\n\n    SM_ASSERT_EQ_DBG(std::runtime_error, p0.rows(), 3, \"p0 must be a 3xK matrix\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, p1.rows(), 3, \"p1 must be a 3xK matrix\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, p0.cols(), p1.cols(), \"p0 and p1 must have the same number of columns\");\n\n    Vector3d c0 = p0.rowwise().mean();\n    Vector3d c1 = p1.rowwise().mean();\n\n    Matrix3d H(Matrix3d::Zero());\n    // subtract out\n    // p0a -= c0;\n    // p0b -= c0;\n    // p0c -= c0;\n    // p1a -= c1;\n    // p1b -= c1;\n    // p1c -= c1;\n\n    // Matrix3d H = p1a*p0a.transpose() + p1b*p0b.transpose() +\n    // \tp1c*p0c.transpose();\n    for (int i = 0; i < p0.cols(); ++i) {\n        H += (p0.col(i) - c0) * (p1.col(i) - c1).transpose();\n    }\n\n    // do the SVD thang\n    JacobiSVD<Matrix3d> svd(H, ComputeFullU | ComputeFullV);\n    Matrix3d V = svd.matrixV();\n    Matrix3d R = V * svd.matrixU().transpose();\n    double det = R.determinant();\n\n    if (det < 0.0) {\n        V.col(2) = V.col(2) * -1.0;\n        R = V * svd.matrixU().transpose();\n    }\n    Vector3d tr = c0 - R.transpose() * c1;  // translation\n\n    // transformation matrix, 3x4\n    Matrix4d tfm(Matrix4d::Identity());\n    //        tfm.block<3,3>(0,0) = R.transpose();\n    //        tfm.col(3) = -R.transpose()*tr;\n    tfm.topLeftCorner<3, 3>() = R.transpose();\n    tfm.topRightCorner<3, 1>() = tr;\n\n    return tfm;\n}\n\nEigen::Matrix3d qMethod(Eigen::MatrixXd const& p0, Eigen::MatrixXd const& p1, const Eigen::VectorXd& w) {\n    SM_ASSERT_EQ_DBG(std::runtime_error, p0.rows(), 3, \"p0 must be a 3xK matrix\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, p1.rows(), 3, \"p1 must be a 3xK matrix\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, p0.cols(), p1.cols(), \"p0 and p1 must have the same number of columns\");\n    SM_ASSERT_EQ_DBG(std::runtime_error, w.size(), p0.cols(), \"w must have the same number of columns as p0\");\n\n    Eigen::MatrixXd W = p0;\n    Eigen::MatrixXd V = p1;\n\n    for (int i = 0; i < p0.cols(); i++) {\n        double wi = sqrt(w[i]);\n        SM_ASSERT_NEAR_DBG(std::runtime_error, p0.col(i).norm(), 1.0, 1e-4,\n                           \"Column \" << i << \" of p0 was not a unit vector\");\n        SM_ASSERT_NEAR_DBG(std::runtime_error, p1.col(i).norm(), 1.0, 1e-4,\n                           \"Column \" << i << \" of p1 was not a unit vector\");\n\n        W.col(i) = wi * W.col(i);\n        V.col(i) = wi * V.col(i);\n    }\n\n    Eigen::MatrixXd B = W * V.transpose();\n    Eigen::MatrixXd Q = B + B.transpose();\n\n    Eigen::Vector3d Z(B(1, 2) - B(2, 1), B(2, 0) - B(0, 2), B(0, 1) - B(1, 0));\n    double sigma = B(0, 0) + B(1, 1) + B(2, 2);\n\n    Eigen::Matrix4d K;\n    K.topLeftCorner<3, 3>() = Q - sigma * Eigen::Matrix3d::Identity();\n    K.topRightCorner<3, 1>() = Z;\n    K.bottomLeftCorner<1, 3>() = Z.transpose();\n    K(3, 3) = sigma;\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> eigensolver(K);\n\n    Eigen::Vector4d eigenvalues = eigensolver.eigenvalues();\n    // Find the maximum eigenvalue\n\n    double maxVal = eigenvalues(0);\n    int maxValIdx = 0;\n    for (int i = 1; i < 4; i++) {\n        if (eigenvalues(i) > maxVal) {\n            maxVal = eigenvalues(i);\n            maxValIdx = i;\n        }\n    }\n\n    // The corresponding eigenvector is the quaternion q_01\n    Eigen::Vector4d q_01 = eigensolver.eigenvectors().col(maxValIdx);\n    q_01 /= q_01.norm();\n\n    Eigen::Vector3d qv = q_01.head<3>();\n    double qs = q_01(3);\n\n    Eigen::Matrix3d C_01 = (qs * qs - qv.dot(qv)) * Eigen::Matrix3d::Identity() + 2.0 * qv * qv.transpose() -\n                           2.0 * qs * sm::kinematics::crossMx(qv);\n\n    return C_01;\n}\n\nEigen::Matrix3d qMethod(Eigen::MatrixXd const& p0, Eigen::MatrixXd const& p1) {\n    return qMethod(p0, p1, Eigen::VectorXd::Ones(p1.cols()));\n}\n\n}  // namespace kinematics\n}  // namespace sm\n", "meta": {"hexsha": "2ea152246ed5e0e637bb336b4e1054e2e3b17e74", "size": 4304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/src/three_point_methods.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/src/three_point_methods.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/src/three_point_methods.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1587301587, "max_line_length": 113, "alphanum_fraction": 0.5913104089, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5982499368444365}}
{"text": "#pragma once\n\n#include <cmath>\n#include <cstdint>\n\n#include <Eigen/Core>\n\n#include \"surface_normal/base.hpp\"\n#include \"surface_normal/cuda_compatibility.hpp\"\n#include \"svd3_cuda.hpp\"\n\nnamespace surface_normal {\n\n__host__ __device__ __forceinline__ uint8_t f2b(float x) {\n  return static_cast<uint8_t>(127.5 * (1 - x));\n}\n\ntemplate <typename T>\n__host__ __device__ __forceinline__ void\ndepth_to_normals_rgb_inner(const ImageView<const T> &depth, ImageView<uint8_t, 3> &normals,\n                           const CameraIntrinsics &intrinsics, int radius, float max_rel_depth_diff,\n                           int center_row, int center_col) {\n  float center_depth = depth.at(center_row, center_col);\n  if (center_depth == 0) {\n    return;\n  }\n\n  float f_inv = 1.f / intrinsics.f;\n  float cx    = intrinsics.cx;\n  float cy    = intrinsics.cy;\n  Eigen::Vector3f mid{(center_col - cx) * center_depth * f_inv,\n                      (center_row - cy) * center_depth * f_inv, center_depth};\n  int n                          = 0;\n  Eigen::Vector3f centroid       = Eigen::Vector3f::Zero();\n  Eigen::Matrix3f outer_prod_sum = Eigen::Matrix3f::Zero();\n  for (int i = -radius; i <= radius; i++) {\n    for (int j = -radius; j <= radius; j++) {\n      int x = center_col + j;\n      int y = center_row + i;\n\n      if (x < 0 || x >= depth.width || y < 0 || y >= depth.height) {\n        continue;\n      }\n\n      float z = depth.at(y, x);\n      if (z == 0 || std::abs(z - center_depth) > max_rel_depth_diff * center_depth) {\n        continue;\n      }\n\n      Eigen::Vector3f p{(x - cx) * z * f_inv, (y - cy) * z * f_inv, z};\n      p -= mid; // subtract midpoint for improved numeric stability in outer product\n      centroid += p;\n      // '* 1' to suppress\n      // warning: calling a __host__ function from a __host__ __device__ function is not allowed\n      outer_prod_sum += p * p.transpose() * 1;\n      n++;\n    }\n  }\n\n  if (n < 3)\n    return;\n\n  centroid /= n;\n  Eigen::Matrix3f cov = (outer_prod_sum - n * centroid * centroid.transpose()) / (n - 1);\n\n  Eigen::Matrix3f U, V;\n  Eigen::Vector3f S;\n  svd(cov(0, 0), cov(0, 1), cov(0, 2), cov(1, 0), cov(1, 1), cov(1, 2), cov(2, 0), cov(2, 1),\n      cov(2, 2),                                                                       // cov\n      U(0, 0), U(0, 1), U(0, 2), U(1, 0), U(1, 1), U(1, 2), U(2, 0), U(2, 1), U(2, 2), // output U\n      S(0), S(1), S(2),                                                                // output S\n      V(0, 0), V(0, 1), V(0, 2), V(1, 0), V(1, 1), V(1, 2), V(2, 0), V(2, 1), V(2, 2)  // output V\n  );\n  Eigen::Vector3f normal = V.col(2).normalized();\n\n  if (mid.dot(normal) < 0) {\n    normal *= -1;\n  }\n\n  normals.at(center_row, center_col, 0) = f2b(normal(0));\n  normals.at(center_row, center_col, 1) = f2b(normal(2));\n  normals.at(center_row, center_col, 2) = f2b(normal(1));\n}\n} // namespace surface_normal\n", "meta": {"hexsha": "dc6f24f4927fbbce7d0ceb0bb9d1612116dfdb03", "size": 2880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/surface_normal_impl.hpp", "max_stars_repo_name": "maiminh1996/surface-normal", "max_stars_repo_head_hexsha": "97829486eb602aaaab421463a801f07153dcccbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-10T14:08:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T03:59:02.000Z", "max_issues_repo_path": "src/surface_normal_impl.hpp", "max_issues_repo_name": "maiminh1996/surface-normal", "max_issues_repo_head_hexsha": "97829486eb602aaaab421463a801f07153dcccbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-04-02T18:40:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T04:05:34.000Z", "max_forks_repo_path": "src/surface_normal_impl.hpp", "max_forks_repo_name": "maiminh1996/surface-normal", "max_forks_repo_head_hexsha": "97829486eb602aaaab421463a801f07153dcccbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-02T14:54:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T01:59:30.000Z", "avg_line_length": 33.8823529412, "max_line_length": 100, "alphanum_fraction": 0.5545138889, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5982186094081333}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_COMPUTEMASSES_HPP\n#define MCL_COMPUTEMASSES_HPP 1\n\n#include <Eigen/Dense>\n\nnamespace mcl\n{\n\n// V are vertices (n x 2 or 3)\n// P are primitives (m x 3 or 4)\n// M is n x 1 of per-vertex masses\n// Computes volume (or area) weighted masses with unit-volume density.\n// If negative, defaults are used: 1100 for volumetric, 0.4 for cloth/2D\n// See: https://www.engineeringtoolbox.com/density-solids-d_1265.html.\n// Masses between the min and max indices in P are set.\n// If unreferenced, they are set to zero.\n// Returns true if all masses in span are positive.\ntemplate <typename DerivedV, typename DerivedP, typename Scalar>\nstatic inline bool compute_masses(\n\tconst Eigen::MatrixBase<DerivedV> &V,\n\tconst Eigen::MatrixBase<DerivedP> &P,\n\tEigen::Matrix<Scalar,Eigen::Dynamic,1> &M,\n\tdouble density_kgd = -1)\n{\n\tusing namespace Eigen;\n\tint V_dim = V.cols();\n\tint P_dim = P.cols();\n\tif (V_dim < 2 || V_dim > 3) { return false; }\n\tif (P_dim < 3 || P_dim > 4) { return false; }\n\n\t// Use 3D vec for calculation even if 2D\n\tauto Vi = [&](int idx)\n\t{\n\t\tVector3d vi = Vector3d::Zero();\n\t\tvi.head(V_dim) = V.row(idx).template cast<double>();\n\t\treturn vi;\n\t};\n\n\t// Default densities\n\tif (density_kgd < 0)\n\t{\n\t\tif (V_dim == 2 || P_dim == 3) {\n\t\t\tdensity_kgd = 0.4;\n\t\t}\n\t\telse if (V_dim == 3 && P_dim == 4) {\n\t\t\tdensity_kgd = 1100;\n\t\t}\n\t}\n\n\t// Resize masses if needed and set span to zero\n\tint min_Pi = P.minCoeff();\n\tint max_Pi = P.maxCoeff();\n\tif (M.rows() < max_Pi) {\n\t\tM.conservativeResize(max_Pi+1);\n\t}\n\tM.segment(min_Pi, max_Pi-min_Pi+1).array() = 0;\n\n\t// Compute mass contrib from each element\n\tint np = P.rows();\n\tfor (int i=0; i<np; ++i)\n\t{\n\t\tif (P_dim == 4)\n\t\t{\n\t\t\tVector3d p_verts[4] = {\n\t\t\t\tVi(P(i,0)),\n\t\t\t\tVi(P(i,1)),\n\t\t\t\tVi(P(i,2)),\n\t\t\t\tVi(P(i,3)) };\n\t\t\tMatrix<double,3,3> E;\n\t\t\tE.col(0) = p_verts[1] - p_verts[0];\n\t\t\tE.col(1) = p_verts[2] - p_verts[0];\n\t\t\tE.col(2) = p_verts[3] - p_verts[0];\n\t\t\tdouble vol = std::abs(E.determinant()/6.0);\n\t\t\tdouble tet_mass = density_kgd * vol;\n\t\t\tM[P(i,0)] += Scalar(tet_mass / 4.0);\n\t\t\tM[P(i,1)] += Scalar(tet_mass / 4.0);\n\t\t\tM[P(i,2)] += Scalar(tet_mass / 4.0);\n\t\t\tM[P(i,3)] += Scalar(tet_mass / 4.0);\n\t\t}\n\t\telse if (P_dim == 3)\n\t\t{\n\t\t\tVector3d p_verts[3] = {\n\t\t\t\tVi(P(i,0)),\n\t\t\t\tVi(P(i,1)),\n\t\t\t\tVi(P(i,2)) };\n\t\t\tVector3d e0 = p_verts[1] - p_verts[0];\n\t\t\tVector3d e1 = p_verts[2] - p_verts[0];\n\t\t\tdouble area = 0.5 * (e0.cross(e1)).norm();\n\t\t\tdouble tri_mass = density_kgd * area;\n\t\t\tM[P(i,0)] += Scalar(tri_mass / 3.0);\n\t\t\tM[P(i,1)] += Scalar(tri_mass / 3.0);\n\t\t\tM[P(i,2)] += Scalar(tri_mass / 3.0);\n\t\t}\n\t}\n\n\tdouble min_mass = M.segment(min_Pi, max_Pi-min_Pi+1).minCoeff();\n\treturn min_mass > 0;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "be321c8de5342c8b8f23a4500f88a45b72409e65", "size": 2738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/ComputeMasses.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/ComputeMasses.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/ComputeMasses.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": 25.8301886792, "max_line_length": 72, "alphanum_fraction": 0.6194302411, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5980855631041072}}
{"text": "#include <CGAL/Cartesian.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Periodic_4_hyperbolic_triangulation_2/internal/Periodic_4_hyperbolic_triangulation_dummy_14.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n#include <CGAL/Algebraic_kernel_for_circles_2_2.h>\n#include <CGAL/Circular_kernel_2.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <iostream>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>               Traits;\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_2<Traits>                Triangulation;\ntypedef Triangulation::Face_handle                                                  Face_handle;\ntypedef Triangulation::Vertex_handle                                                Vertex_handle;\ntypedef Triangulation::Locate_type                                                  Locate_type;\ntypedef Triangulation::Hyperbolic_translation                                       Hyperbolic_translation;\ntypedef Triangulation::Point                                                        Point;\n\nstd::ostream& operator<<(std::ostream& s, const Locate_type& lt)\n{\n  switch(lt)\n  {\n    case Triangulation::VERTEX:\n      s << \"VERTEX\";\n      break;\n    case Triangulation::FACE:\n      s << \"FACE\";\n      break;\n    case Triangulation::EDGE:\n      s << \"EDGE\";\n      break;\n  }\n\n  return s;\n}\n\nint main(int, char**)\n{\n  Triangulation tr;\n\n  assert(tr.is_valid());\n\n  Locate_type lt;\n  int li;\n  Face_handle fh;\n\n  std::cout << \"---- locating dummy points (all should be vertices) ----\" << std::endl;\n  for(int j=0; j<14; ++j) {\n    Point query = tr.get_dummy_point(j);\n    fh = tr.hyperbolic_locate(query, lt, li);\n    assert(lt == Triangulation::VERTEX);\n    std::cout << \"   dummy point \" << j << \": OK \" << std::endl;\n  }\n\n  std::cout << \"---- locating the midpoint of a Euclidean segment ----\" << std::endl;\n  Point p1 = tr.get_dummy_point(0), p2 = tr.get_dummy_point(1);\n  Point query = midpoint(p1, p2);\n  fh = tr.hyperbolic_locate(query, lt, li);\n  assert(lt == Triangulation::EDGE);\n  std::cout << \"   located as edge OK\" << std::endl;\n\n  std::cout << \"---- inserting a single point and locating it ----\" << std::endl;\n  Vertex_handle v = tr.insert(Point(-0.4, -0.1));\n  fh = tr.hyperbolic_locate(v->point(), lt, li);\n  assert(lt == Triangulation::VERTEX);\n  std::cout << \"   located as vertex OK\" << std::endl;\n\n  // TODO: add a test case for a circular edge!\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "87c787ddb2b554e7f2e5912de247ddc74b52dc8e", "size": 2685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_locate.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_locate.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_locate.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 34.8701298701, "max_line_length": 109, "alphanum_fraction": 0.6394785847, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5980855579748362}}
{"text": "#ifndef INTEGRALS_HPP_\n#define INTEGRALS_HPP_\n/**\n * @file integrals.hpp\n * @author Adam Lamson\n * @brief Probility Density Function integrals for KMC algorithm. Used to create\n * lookup tables\n * @version 0.1\n * @date 2019-04-15\n *\n * @copyright Copyright (c) 2019\n *\n */\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n/*! \\brief Integrate exponential factor with the form of\n * e^{-M * (\\sqrt{ s^2 + lm^2} - ell0)^2}\n * from sbound0 to sbound1  with respect to the variable s.\n *\n * \\param lm Physically, this is the perpendicular distance above rod\n * \\param sbound lowerr limit of integral\n * \\param sbound Upper limit of integral\n * \\param M exponential constant factor. Physically, this is the product of\n (1-load_sensitivity)*spring_const/(k_B * Temperature)\n * \\param ell0 Shift of the integrands mean. Physically, protein rest length\n * \\return result The value of the integration\n\n */\ninline double integral(double lm, double sbound0, double sbound1, double M,\n                       double ell0) {\n    if (sbound0 >= sbound1) {\n        return 0;\n    }\n    auto integrand = [&](double s) {\n        // lambda capture variabls ell0 and M\n        const double exponent = sqrt(s * s + lm * lm) - ell0;\n        return exp(-M * exponent * exponent);\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, sbound0, sbound1, 10, 1e-6, &error);\n    return result;\n}\n\ninline double bind_vol_integral(double sbound, double M, double ell0) {\n    assert(sbound > 0);\n    auto integrand = [&](double s) {\n        // lambda capture variabls ell0 and M\n        const double exponent = s - ell0;\n        return s * s * exp(-M * exponent * exponent);\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, 0, sbound, 10, 1e-6, &error);\n    return 4. * M_PI * result;\n}\n\n/*! \\brief Integrate exponential factor with the form of\n * e^{-M * [ (1-e_fact)\\sqrt{s^2 + lm^2} - ell0)^2 -\n *          fdep_length * (\\sqrt{ s^2 + lm^2} - ell0) ] }\n * from sbound0 to sbound1  with respect to the variable s.\n *\n * \\param lm Physically, this is the perpendicular distance above rod\n * \\param sbound lowerr limit of integral\n * \\param sbound Upper limit of integral\n * \\param M exponential constant factor. Physically, this is the product of\n spring_const/(k_B * Temperature)\n * \\param e_fact energy(load) sensitivity to unbinding.\n * \\param fdep_length Characteristic length for force dependent unbinding.\n * \\param ell0 Shift of the integrands mean. Physically, protein rest length\n * \\return result The value of the integration\n\n */\ninline double fdep_integral(double lm, double sbound0, double sbound1, double M,\n                            double e_fact, double fdep_length, double ell0) {\n    if (sbound0 >= sbound1) {\n        return 0;\n    }\n    auto integrand = [&](double s) {\n        const double rprime = sqrt(s * s + lm * lm) - ell0;\n        const double energy_term = .5 * (1. - e_fact) * rprime * rprime;\n        const double force_term = fdep_length * rprime;\n        return exp(-M * (energy_term - force_term));\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, sbound0, sbound1, 10, 1e-6, &error);\n    return result;\n}\n\ninline double fdep_bind_vol_integral(double sbound, double M, double e_fact,\n                                     double fdep_length, double ell0) {\n    assert(sbound > 0);\n    auto integrand = [&](double s) {\n        const double rprime = s - ell0;\n        const double energy_term = .5 * (1. - e_fact) * rprime * rprime;\n        const double force_term = fdep_length * rprime;\n        return exp(-M * (energy_term - force_term));\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, 0, sbound, 10, 1e-6, &error);\n    return 4. * M_PI * result;\n}\n\n/*! \\brief Integrate exponential factor with the form of\n * e^{-M * [ (1-e_fact)\\sqrt{s^2 + lm^2} - ell0)^2 -\n *          fdep_length * (\\sqrt{ s^2 + lm^2} - ell0) ] }\n * from sbound0 to sbound1  with respect to the variable s.\n *\n * \\param lm Physically, this is the perpendicular distance above rod\n * \\param sbound lower limit of integral\n * \\param sbound Upper limit of integral\n * \\param M1 exponential constant factor when spring is compressed.\n *    Physically, this is the product of spring_const_1/(k_B * Temperature)\n * \\param M2 exponential constant factor when spring is stretched.\n *    Physically, this is the product of spring_const_2/(k_B * Temperature)\n * \\param e_fact energy(load) sensitivity to unbinding.\n * \\param fdep_length Characteristic length for force dependent unbinding.\n * \\param ell0 Shift of the integrands mean. Physically, protein rest length\n * \\return result The value of the integration\n\n */\ninline double asym_integral(double lm, double sbound0, double sbound1,\n                            double M1, double M2, double e_fact,\n                            double fdep_length, double ell0) {\n    if (sbound0 >= sbound1) {\n        return 0;\n    }\n    auto integrand = [&](double s) {\n        const double rprime = sqrt(s * s + lm * lm) - ell0;\n        const double energy_term = .5 * (1. - e_fact) * rprime * rprime;\n        const double force_term = fdep_length * rprime;\n        const double M = rprime < 0. ? M1 : M2;\n        return exp(-M * (energy_term - force_term));\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, sbound0, sbound1, 10, 1e-6, &error);\n    return result;\n}\n\ninline double asym_bind_vol_integral(double sbound, double M1, double M2,\n                                     double e_fact, double fdep_length,\n                                     double ell0) {\n    assert(sbound > 0);\n    auto integrand = [&](double s) {\n        const double rprime = s - ell0;\n        const double energy_term = .5 * (1. - e_fact) * rprime * rprime;\n        const double force_term = fdep_length * rprime;\n        const double M = rprime < 0. ? M1 : M2;\n        return exp(-M * (energy_term - force_term));\n    };\n    double error = 0;\n    double result =\n        boost::math::quadrature::gauss_kronrod<double, 21>::integrate(\n            integrand, 0, sbound, 10, 1e-6, &error);\n    return 4. * M_PI * result;\n}\n\n#endif /* INTEGRALS_HPP_ */\n", "meta": {"hexsha": "66e79e5ca70f4bc30fc8d587c251ea0f01ee6205", "size": 6582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KMC/integrals.hpp", "max_stars_repo_name": "lamsoa729/KMC", "max_stars_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-15T22:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T22:06:52.000Z", "max_issues_repo_path": "KMC/integrals.hpp", "max_issues_repo_name": "lamsoa729/KMC", "max_issues_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T17:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T15:59:17.000Z", "max_forks_repo_path": "KMC/integrals.hpp", "max_forks_repo_name": "lamsoa729/KMC", "max_forks_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T20:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T20:17:58.000Z", "avg_line_length": 38.2674418605, "max_line_length": 80, "alphanum_fraction": 0.6349134002, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5980855534295659}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Beta-SLAM - Simultaneous localization and grid mapping with beta distributions\n *  Copyright (c) 2013-2019, Joachim Clemens, Thomas Reineking, Tobias Kluth\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 BSLAM 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#include <cmath>\n#include <assert.h>\n\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\n#include \"bslam/utils/Factorial.h\"\n\nnamespace bslam {\n\nBetaDistribution::BetaDistribution( float alpha, float beta ) :\n\t\tm_alpha( alpha ),\n\t\tm_beta( beta )\n{\n\t// Nothing else to do here\n}\n\n\nbool\nBetaDistribution::operator==( const BetaDistribution &other ) const {\n\treturn m_alpha == other.m_alpha && m_beta == other.m_beta;\n}\n\n\ndouble\nBetaDistribution::B( double alpha, double beta ) {\n\t//return gamma( alpha ) * gamma( beta ) / gamma( alpha + beta );\n\treturn boost::math::beta( alpha, beta );\n}\n\n\ndouble\nBetaDistribution::Binv( double alpha, double beta ) {\n\t//return gamma( alpha + beta ) / gamma( alpha ) * gamma( beta );\n\treturn 1.0 / B( alpha, beta );\n}\n\n\nuint32_t\nBetaDistribution::choose( uint32_t n, uint32_t k ) {\n\t// iterative\n\tuint32_t res = 1;\n\tfor( uint32_t i = 1; i <= k; i++ )\n\t\tres *= (n + 1 - i) / i;\n\treturn res;\n\n\t// recursive\n\t//return k == 0 ? 1 : (n * choose( n - 1, k - 1 )) / k;\n}\n\n\ndouble\nBetaDistribution::gamma( double x ) {\n\t//return std::tgamma( x );\n\treturn boost::math::tgamma( x );\n}\n\ndouble\nBetaDistribution::digamma( double x ) {\n\t/*\n\t// According to http://web.science.mq.edu.au/~mjohnson/code/digamma.c\n\tassert(x > 0);\n\n\tdouble \tresult = 0,\n\t\t\txx, xx2, xx4;\n\n\tfor ( ; x < 7; ++x)\n\t\tresult -= 1/x;\n\n\tx\t-= 1.0/2.0;\n\txx\t= 1.0/x;\n\txx2\t= xx*xx;\n\txx4\t= xx2*xx2;\n\n\tresult += log( x ) + (1. / 24.) * xx2 - (7.0 / 960.0) * xx4 + (31.0 / 8064.0) * xx4 * xx2 - (127.0 / 30720.0) * xx4 * xx4;\n\n\treturn result;\n\t*/\n\n\treturn boost::math::digamma( x );\n}\n\n\ndouble\nBetaDistribution::pdf( double x ) const {\n\treturn pdf( x, m_alpha, m_beta );\n}\n\n\ndouble\nBetaDistribution::pdf( double x, double alpha, double beta ) {\n\treturn Binv( alpha, beta ) * pow( x, alpha - 1 ) * pow( 1 - x, beta - 1 );\n}\n\n\ndouble\nBetaDistribution::pmf( uint32_t k, uint32_t n, double alpha, double beta ) {\n\treturn choose( n, k ) * B( k + alpha, n - k + beta ) * Binv( alpha, beta );\n}\n\n\ndouble\nBetaDistribution::cdf( double x ) const {\n\treturn cdf( x, m_alpha, m_beta );\n}\n\n\ndouble\nBetaDistribution::cdf( double x, double alpha, double beta ) {\n\treturn boost::math::ibeta( alpha, beta, x ); // regularized incomplete beta function\n}\n\n\ndouble\nBetaDistribution::cdfComp( double x, double alpha, double beta ) {\n\treturn boost::math::ibetac( alpha, beta, x ); // regularized incomplete beta function\n}\n\ndouble\nBetaDistribution::cdf( uint32_t k, uint32_t n, double alpha, double beta ) {\n\tthrow std::runtime_error( \"Not implemented yet\" );\n\t//return 1 - B( beta + n - k - 1, alpha + k + 1 ) * hyp3F2( 1, alpha + k + 1, -n + k + 1; k + 2, -beta - n + k + 2; 1 ) / (B( alpha, beta ) * B( n - k, k + 2 ) * (n + 1));\n\treturn 0.0;\n}\n\n\ndouble\nBetaDistribution::mean() const {\n\treturn mean( m_alpha, m_beta );\n}\n\n\nconstexpr double\nBetaDistribution::mean( double alpha, double beta ) {\n\treturn alpha / (alpha + beta);\n}\n\n\nconstexpr double\nBetaDistribution::mean( uint32_t n, double alpha, double beta ) {\n\treturn n * alpha / (alpha + beta);\n}\n\n\nconstexpr double\nBetaDistribution::mean( uint32_t k, uint32_t n, double alpha, double beta ) {\n\treturn (alpha + k) / (alpha + beta + n);\n}\n\n\ndouble\nBetaDistribution::mode() const {\n\treturn mode( m_alpha, m_beta );\n}\n\n\nconstexpr double\nBetaDistribution::mode( double alpha, double beta ) {\n\t/*\n\tassert( alpha >= 1 );\n\tassert( alpha + beta > 2 );\n\t*/\n\treturn (alpha - 1) / (alpha + beta - 2);\n}\n\n\ndouble\nBetaDistribution::var() const {\n\treturn var( m_alpha, m_beta );\n}\n\n\nconstexpr double\nBetaDistribution::var( double alpha, double beta ) {\n\treturn alpha * beta / ((alpha + beta + 1) * (alpha + beta) * (alpha + beta));\n}\n\n\ndouble\nBetaDistribution::entropy() const {\n\treturn entropy( m_alpha, m_beta );\n}\n\n\ndouble\nBetaDistribution::entropy( double alpha, double beta ) {\n\treturn log( B( alpha, beta ) ) - (alpha - 1)*digamma( alpha ) - (beta - 1)*digamma( beta ) + (alpha + beta - 2)*digamma( alpha + beta );\n}\n\n\nconstexpr double\nBetaDistribution::var( uint32_t n, double alpha, double beta ) {\n\treturn n * alpha * beta * (alpha + beta + n) / ((alpha + beta + 1) * (alpha + beta) * (alpha + beta));\n}\n\n\nconstexpr double\nBetaDistribution::var( uint32_t k, uint32_t n, double alpha, double beta ) {\n\treturn var( alpha + k, beta + n - k );\n}\n\n/*\ndouble\nBetaDistribution::pdf( double x, int alpha, int beta ) {\n\tassert( alpha > 0 );\n\tassert( beta > 0 );\n\treturn Binv( alpha, beta ) * pow( x, alpha - 1 ) * pow( 1 - x, beta - 1 );\n}\n\n\ndouble\nBetaDistribution::B( int alpha, int beta ) {\n\treturn gamma( alpha ) * gamma( beta ) / gamma( alpha + beta );\n}\n\n\ndouble\nBetaDistribution::Binv( int alpha, int beta ) {\n\treturn gamma( alpha + beta ) / gamma( alpha ) * gamma( beta );\n}\n\n\ndouble\nBetaDistribution::gamma( int x ) {\n\treturn Factorial::value( x - 1 );\n}\n*/\n\ndouble\nBetaDistribution::ignorance( double priorAlpha, double priorBeta ) const {\n\treturn ( priorAlpha + priorBeta + 1 ) / ( m_alpha + m_beta + 1 );\n}\n\n\ndouble\nBetaDistribution::dissonance() const {\n\tdouble\tcurMean = mean();\n\n\t// Shannon entropy\n\treturn -curMean * log( curMean ) - (1.0 - curMean) * log( 1.0 - curMean );\n}\n\n\ndouble\nBetaDistribution::conflict( double epsilon ) const {\n\treturn cdf( 0.5 + epsilon ) - cdf( 0.5 - epsilon );\n}\n\n} /* namespace bslam */\n", "meta": {"hexsha": "14ec2e4b4b2f962d5c43b896240ba001327b0137", "size": 7089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bslam/utils/uncertainty/BetaDistribution.hpp", "max_stars_repo_name": "JoachimClemens/Beta-SLAM", "max_stars_repo_head_hexsha": "eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T21:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:44:44.000Z", "max_issues_repo_path": "include/bslam/utils/uncertainty/BetaDistribution.hpp", "max_issues_repo_name": "JoachimClemens/Beta-SLAM", "max_issues_repo_head_hexsha": "eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bslam/utils/uncertainty/BetaDistribution.hpp", "max_forks_repo_name": "JoachimClemens/Beta-SLAM", "max_forks_repo_head_hexsha": "eaa3e5b0dd7d81e4c0f2b30fc29d48d55807c5fa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-16T01:37:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T11:13:21.000Z", "avg_line_length": 24.9612676056, "max_line_length": 172, "alphanum_fraction": 0.6716038934, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5980855528455652}}
{"text": "/*\n *  VSCSound.cpp\n *  SynthStation\n *\n *  Created by Jonathan Thorpe on 22/10/2011.\n *  Copyright 2011 NXP. All rights reserved.\n *\n */\n\n#include \"VSCSound.h\"\n\n#include <boost/assert.hpp>\n\n#include <cmath>\n#include <cassert>\n\nVSC::Sound::Pitch::Pitch() : mReferenceAFrequency(440.0)\n{\n    computeMidiNoteFrequencies();\n}\n\nVSC::Float VSC::Sound::Pitch::logFrequencyToFrequency(Float logFreq)\n{\n\treturn std::pow(10.0, logFreq);\n}\n\nVSC::Float VSC::Sound::Pitch::frequencyToLogFrequency(Float freq)\n{\n\treturn std::log10(freq);\n}\n\nVSC::Float VSC::Sound::Pitch::frequencyForMidiNote(Float midiNote)\n{\n\treturn frequencyForMidiNote((unsigned int)midiNote);\n}\n\nVSC::Float VSC::Sound::Pitch::frequencyForMidiNote(unsigned int midiNote)\n{\n\tBOOST_ASSERT_MSG(midiNote >= 0 && midiNote < 127, \"MIDI note should be in range [0-127]\");\n\treturn mMIDINoteFrequencies[midiNote];\n}\n\nvoid VSC::Sound::Pitch::setReferenceAFrequency(Float f)\n{\n\tmReferenceAFrequency = f;\n    computeMidiNoteFrequencies();\n}\n\nVSC::Float VSC::Sound::Pitch::getReferenceAFrequency(void)\n{\n\treturn mReferenceAFrequency;\n}\n\nvoid VSC::Sound::Pitch::computeMidiNoteFrequencies(void)\n{\n\tmMIDINoteFrequencies.resize(128);\n\tfor (int x = 0; x < 127; ++x)\n    {\n\t\tFloat freq = (mReferenceAFrequency / 32.0) * (std::pow(2.0, ((x - 9.0) / 12.0)));\n\t\tmMIDINoteFrequencies[x] = freq;\n\t}\n}\n", "meta": {"hexsha": "ed82b27e16ab45d42c8ef03ccdf3912d118fc665", "size": 1335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sound/VSCSound.cpp", "max_stars_repo_name": "jbat100/VirtualSoundControl", "max_stars_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sound/VSCSound.cpp", "max_issues_repo_name": "jbat100/VirtualSoundControl", "max_issues_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sound/VSCSound.cpp", "max_forks_repo_name": "jbat100/VirtualSoundControl", "max_forks_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_forks_repo_licenses": ["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.1904761905, "max_line_length": 91, "alphanum_fraction": 0.7116104869, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5980212824319966}}
{"text": "#include \"aux/eigen2hdf.hpp\"\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"post_processing/macroscopic_quantities.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"post_processing/momentum.hpp\"\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/basis/spectral_basis.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/spectral_elem.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/spectral_function/hermite_polynomial.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/utility/mass_matrix.hpp\"\n\n#include \"spectral/polar_to_hermite.hpp\"\n#include \"spectral/shift_hermite_2d.hpp\"\n\n#include <Eigen/Sparse>\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\ntemplate <typename T>\nstruct show_name\n{\n};\n\n#define PI 3.141592653589793238462643383279502884197\n\nusing namespace std;\nusing namespace boltzmann;\n\nnamespace po = boost::program_options;\n\n#ifdef EXTENDED_PRECISION\ntypedef long double numeric_t;\n#else\ntypedef double numeric_t;\n#endif\n\nint main(int argc, char *argv[])\n{\n  Timer<> timer;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"show help message\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  // read polar basis from file\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, \"spectral_basis.desc\");\n  //  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  int max_deg = spectral::get_max_k(polar_basis);\n  const unsigned int K = max_deg + 1;\n  // create corresponding Hermite basis\n  typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, max_deg + 1, 2);\n  SpectralBasisFactoryHN::write_basis_descriptor(hermite_basis, \"hermite_basis.desc\");\n\n  if (hermite_basis.n_dofs() != polar_basis.n_dofs()) {\n    throw runtime_error(\"Hermite basis does not match!\");\n    return 1;\n  }\n\n  cout << \"size(polar basis) = \" << polar_basis.n_dofs() << endl\n       << \"size(hermite basis) = \" << hermite_basis.n_dofs();\n\n  cout << \"\\n--------------------\\n\";\n  cout << \"Test 2: (P->H) -> (H->P) show coefficients\\n\";\n\n  /*\n   * load coefficients (polar basis) from HDF5\n   */\n  const unsigned int N = polar_basis.n_dofs();\n  Eigen::VectorXd coeffs(N);\n  hid_t h5_init = H5Fopen(\"init.h5\", H5F_ACC_RDONLY, H5P_DEFAULT);\n  eigen2hdf::load(h5_init, \"coeffs\", coeffs);\n  H5Fclose(h5_init);\n  coeffs.setZero();\n  coeffs[0] = 1;\n  {\n    cout << \"input: ||cp||^2: \" << coeffs.cwiseAbs2().sum() << endl;\n    ofstream fout(\"cp.dat\");\n    fout << coeffs;\n    fout.close();\n  }\n\n  // compute bulk velocity\n  Mass mass;\n  mass.init(polar_basis);\n  Momentum momentum;\n  momentum.init(polar_basis);\n\n  {\n    auto entries = momentum.entries();\n    for (auto entry : entries) {\n      cout << entry.first << \" \" << entry.second << \"\\n\";\n    }\n  }\n\n  MQEval mqtsc(polar_basis);\n  auto mq_eval = mqtsc.evaluator();\n  mq_eval(coeffs.data(), N);\n  cout << \"correct mass: \" << mq_eval.m << endl;\n  cout << \"correct momentum: \" << mq_eval.v.transpose() << endl;\n\n  const double m = mass.compute(coeffs.data());\n  Eigen::Vector2d u = momentum.compute(coeffs.data()) / m;\n  cout << \"\\n----- input -----\\n\"\n       << \"\\n\";\n  cout << scientific << setprecision(8) << \"mass: \" << m << endl\n       << \"momentum: \" << u(0) << \", \" << u(1) << endl;\n\n  // compute hermite coefficients\n  Polar2Hermite<polar_basis_t, hermite_basis_t> P2H(polar_basis, hermite_basis);\n  // print_timer(timer.stop(), \"init P2H\");\n\n  Eigen::VectorXd buf(N);\n  P2H.to_hermite(buf, coeffs);\n\n  if (sizeof(numeric_t) == 16) {\n    cout << \"Using *extended precision*  in ShiftHermite\\n\";\n  } else if (sizeof(numeric_t) == 8) {\n    cout << \"Using double precision in ShiftHermite\\n\";\n  }\n  std::vector<numeric_t> cH(buf.data(), buf.data() + N);\n  typedef Eigen::Array<numeric_t, Eigen::Dynamic, 1> array_t;\n  Eigen::Map<const array_t> vec_cH(cH.data(), cH.size());\n  cout << \"||c_H||^2: \" << vec_cH.cwiseAbs2().sum() << \"\\n\";\n  ShiftHermite2D<hermite_basis_t, numeric_t> shift_hermite(hermite_basis);\n  shift_hermite.init();\n  timer.start();\n  shift_hermite.shift(cH.data(), u(0), u(1));\n  //  print_timer(timer.stop(), \"shift Hermite coefficients\");\n\n  // convert to double\n  std::transform(cH.begin(), cH.end(), buf.data(), [](numeric_t x) { return double(x); });\n\n  // -> Polar coordinates\n  Eigen::VectorXd Cc(N);\n  P2H.to_polar(Cc, buf);\n\n  const double mc = mass.compute(Cc.data());\n  Eigen::Vector2d uc = momentum.compute(Cc.data()) / mc;\n  cout << \"\\n----- centered -----\\n\";\n  cout << \"mass: \" << scientific << setprecision(8) << mc << \"\\t(diff = \" << std::abs(m - mc) << \")\"\n       << endl\n       << \"momentum: \" << uc(0) << \", \" << uc(1) << endl;\n\n  // write new coefficients to disk\n  hid_t h5_shifted = H5Fcreate(\"shifted.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  Eigen::Map<Eigen::VectorXd> Cc_eigen(Cc.data(), Cc.size());\n  eigen2hdf::save(h5_shifted, \"coeffs\", Cc_eigen);\n  // export hermite coefficients\n  Eigen::Map<Eigen::VectorXd> cH_eigen(buf.data(), buf.size());\n  eigen2hdf::save(h5_shifted, \"coeffs_hermite\", cH_eigen);\n  H5Fclose(h5_shifted);\n\n  // do some cheap scattering\n  // ...\n\n  // Move back to original position\n  timer.start();\n  shift_hermite.shift(cH.data(), -u(0), -u(1));\n  //  print_timer(timer.stop(), \"shift Hermite coefficients (back)\");\n\n  // go back to polar coordinates\n  std::transform(cH.begin(), cH.end(), buf.data(), [](numeric_t x) { return double(x); });\n  Eigen::VectorXd Cc2(N);\n  P2H.to_polar(Cc2, buf);\n\n  const double m1 = mass.compute(Cc2.data());\n  Eigen::Vector2d u1 = momentum.compute(Cc2.data()) / m1;\n  // stop here\n\n  auto M = make_mass_matrix(polar_basis, polar_basis);\n\n  cout << \"----- move to original pos. -----\\n\";\n  cout << \"mass: \" << scientific << setprecision(8) << m1 << \"\\t(diff = \" << std::abs(m - m1) << \")\"\n       << endl\n       << \"momentum: \" << scientific << setprecision(8) << u1(0) << \", \" << u1(1)\n       << \"\\t(diff = \" << (u - u1).squaredNorm() << \")\" << endl;\n\n  Eigen::Map<Eigen::VectorXd> coeffs2(Cc2.data(), Cc2.size());\n  Eigen::VectorXd tmp = (coeffs - coeffs2).array().square();\n  double shift_error = sqrt((M * tmp).sum());\n\n  cout << \"shift_error: \" << scientific << setprecision(8) << shift_error << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "02a65cf7a5d65bdeb7e6c01eb308dd3f78d621ca", "size": 6678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/p2h_shift_h2p/main.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/p2h_shift_h2p/main.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/p2h_shift_h2p/main.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5756097561, "max_line_length": 100, "alphanum_fraction": 0.6623240491, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5980212799973039}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2015 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_ANDOYER_INVERSE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_ANDOYER_INVERSE_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/math.hpp>\n\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n\n\nnamespace boost { namespace geometry { namespace detail\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with first order terms.\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD703541\n*/\ntemplate <typename CT>\nclass andoyer_inverse\n{\npublic:\n    template <typename T1, typename T2, typename Spheroid>\n    andoyer_inverse(T1 const& lon1,\n                    T1 const& lat1,\n                    T2 const& lon2,\n                    T2 const& lat2,\n                    Spheroid const& spheroid)\n        : m_a(get_radius<0>(spheroid))\n        , m_b(get_radius<2>(spheroid))\n        , m_f(detail::flattening<CT>(spheroid))\n        , m_is_result_zero(false)\n    {\n        // coordinates in radians\n\n        if ( math::equals(lon1, lon2)\n          && math::equals(lat1, lat2) )\n        {\n            m_is_result_zero = true;\n            return;\n        }\n\n        CT const pi_half = math::pi<CT>() / CT(2);\n\n        if ( math::equals(math::abs(lat1), pi_half)\n          && math::equals(math::abs(lat2), pi_half) )\n        {\n            m_is_result_zero = true;\n            return;\n        }\n\n        CT const dlon = lon2 - lon1;\n        m_sin_dlon = sin(dlon);\n        m_cos_dlon = cos(dlon);\n        m_sin_lat1 = sin(lat1);\n        m_cos_lat1 = cos(lat1);\n        m_sin_lat2 = sin(lat2);\n        m_cos_lat2 = cos(lat2);\n\n        // H,G,T = infinity if cos_d = 1 or cos_d = -1\n        // lat1 == +-90 && lat2 == +-90\n        // lat1 == lat2 && lon1 == lon2\n        m_cos_d = m_sin_lat1*m_sin_lat2 + m_cos_lat1*m_cos_lat2*m_cos_dlon;\n        m_d = acos(m_cos_d);\n        m_sin_d = sin(m_d);\n\n        // just in case since above lat1 and lat2 is checked\n        // the check below is equal to cos_d == 1 || cos_d == -1 || d == 0\n        if ( math::equals(m_sin_d, CT(0)) )\n        {\n            m_is_result_zero = true;\n            return;\n        }\n    }\n\n    inline CT distance() const\n    {\n        if ( m_is_result_zero )\n        {\n            // TODO return some approximated value\n            return CT(0);\n        }\n\n        CT const K = math::sqr(m_sin_lat1-m_sin_lat2);\n        CT const L = math::sqr(m_sin_lat1+m_sin_lat2);\n        CT const three_sin_d = CT(3) * m_sin_d;\n        // H or G = infinity if cos_d = 1 or cos_d = -1\n        CT const H = (m_d+three_sin_d)/(CT(1)-m_cos_d);\n        CT const G = (m_d-three_sin_d)/(CT(1)+m_cos_d);\n\n        // for e.g. lat1=-90 && lat2=90 here we have G*L=INF*0\n        CT const dd = -(m_f/CT(4))*(H*K+G*L);\n\n        return m_a * (m_d + dd);\n    }\n\n    inline CT azimuth() const\n    {\n        // it's a situation when the endpoints are on the poles +-90 deg\n        // in this case the azimuth could either be 0 or +-pi\n        if ( m_is_result_zero )\n        {\n            return CT(0);\n        }\n\n        CT A = CT(0);\n        CT U = CT(0);\n        if ( ! math::equals(m_cos_lat2, CT(0)) )\n        {\n            CT const tan_lat2 = m_sin_lat2/m_cos_lat2;\n            CT const M = m_cos_lat1*tan_lat2-m_sin_lat1*m_cos_dlon;\n            A = atan2(m_sin_dlon, M);\n            CT const sin_2A = sin(CT(2)*A);\n            U = (m_f/CT(2))*math::sqr(m_cos_lat1)*sin_2A;\n        }\n\n        CT V = CT(0);\n        if ( ! math::equals(m_cos_lat1, CT(0)) )\n        {\n            CT const tan_lat1 = m_sin_lat1/m_cos_lat1;\n            CT const N = m_cos_lat2*tan_lat1-m_sin_lat2*m_cos_dlon;\n            CT const B = atan2(m_sin_dlon, N);\n            CT const sin_2B = sin(CT(2)*B);\n            V = (m_f/CT(2))*math::sqr(m_cos_lat2)*sin_2B;\n        }\n\n        // infinity if sin_d = 0, so cos_d = 1 or cos_d = -1\n        CT const T = m_d / m_sin_d;\n        CT const dA = V*T-U;\n\n        return A - dA;\n    }\n\nprivate:\n    CT const m_a;\n    CT const m_b;\n    CT const m_f;\n\n    CT m_sin_dlon;\n    CT m_cos_dlon;\n    CT m_sin_lat1;\n    CT m_cos_lat1;\n    CT m_sin_lat2;\n    CT m_cos_lat2;\n\n    CT m_cos_d;\n    CT m_d;\n    CT m_sin_d;\n\n    bool m_is_result_zero;\n};\n\n}}} // namespace boost::geometry::detail\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_ANDOYER_INVERSE_HPP\n", "meta": {"hexsha": "c806aeec1a1f695942ecf722665a18362cea2d31", "size": 5028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/algorithms/detail/andoyer_inverse.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/andoyer_inverse.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/andoyer_inverse.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": 28.7314285714, "max_line_length": 105, "alphanum_fraction": 0.5825377884, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064587, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5980212745194395}}
{"text": "#include \"C_DL1D.h\"\n#include <vector>\n#include <MatrixOper.h>\n#include \"IM_IO.h\"\n#include \"C_OMP.h\"\nusing namespace std;\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <stdio.h>\n#include <fcntl.h>\n// #include <gsl/gsl_matrix.h>\n// #include <gsl/gsl_linalg.h>\n#include <armadillo>\nusing namespace arma;\ndblarray TabTrain;\n\n\nC_DL1D::C_DL1D(dblarray &training_set)\n{\n\tTabTrain = training_set; // training set, with samples as column\n\tNpix = TabTrain.nx(); // atom/training sample length\n\teps = 2.220446049250313e-16;\n}\nC_DL1D::~C_DL1D()\n{\n}\n\n\n\ndblarray C_DL1D::dl1d(dblarray &training_set, dblarray &initD, int IterationNumber,int SparsityTarget,double ErrorTarget,bool Verb)\n{\n\tNa = initD.ny(); // number of atoms in dictionary\n\tint Ntrain = TabTrain.ny(); // number of training samples\n\tdblarray sample(Npix); // training sample\n\tdouble Amean,sample_mean; // atom and training sample mean\n\tdblarray D = initD; // learned dictionary initialized with initD\n\tdblarray X(Na,Ntrain);\t // sparse coding coefficients of TabTrain\n\tdblarray Xt(Ntrain,Na); // transpose of X\n\tdblarray Xtpinv(Na,Ntrain); // pseudoinverse of Xt\n\tdblarray Xpinv(Ntrain,Na); // X pseudo-inverse\n\tdblarray Scurrent(Npix); // Current sample\n\tdblarray Acurrent(Npix); // Current atom, during normalization\n\tdouble Anorm; // Current atom norm\n\tdouble minT; // eigenvalue threshold used to compute pseudo inverse\n\tint atom_usage; // number of sample using a given atom\n\tint new_sample_ind; // index of the new sample used in place of an useless atom\n\tint atoms_replaced; // number of unused atoms replaced with training samples\n\tMatOper terminator;\n\tdouble average_sparsity = 0;\n\tdouble average_error = 0;\n\tdblarray sparse_approx(Npix,Ntrain); // sparse approximation of TabTrain in the current dictionary\n\tdblarray sparse_sample(Npix); // sparse approximation of current training sample\n\tmat armaXt(Ntrain,Na);\n\tdblarray At(Na,Ntrain);\n\tdblarray Vt(Na,Na);\n\tdblarray V(Na,Na);\n\tdblarray S(Na,Na);\n\tmat armaInv;\n\tgsl_rng *rng;\n\tconst gsl_rng_type * T;\n\tT = gsl_rng_default;\n\trng = gsl_rng_alloc (T);\n\t/*gsl_matrix * gslA = gsl_matrix_alloc(Ntrain,Na);\n\t\tgsl_matrix * gslV = gsl_matrix_alloc(Na,Na);\n\t\tgsl_vector * gslS = gsl_vector_alloc(Na);\n\t\tgsl_vector * work = gsl_vector_alloc(Na);*/\n\n\t//Removing atoms mean and normalizing atoms with norm > 1\n\tfor (int m=0;m<Na;m++)\n\t{\n\t\tfor (int p=0;p<Npix;p++)\n\t\t\tAcurrent(p) = D(p,m); // reading atom p\n\t\tAmean = Acurrent.mean();\n\t\tfor (int p=0;p<Npix;p++) // computing atom mean\n\t\t\tAcurrent(p) = Acurrent(p) - Amean; // removing atom mean\n\t\tAnorm = sqrt(Acurrent.energy()); // computing 0-mean atom norm\n\t\tif (Anorm > 1)\n\t\t{\n\t\t\tfor (int p=0;p<Npix;p++)\n\t\t\t\tD(p,m) = (D(p,m) - Amean) / Anorm; // removing mean and normalizing\n\t\t}\n\t\telse \tfor (int p=0;p<Npix;p++) D(p,m) = D(p,m) - Amean; // only removing mean\n\t}\n\tC_OMP coder(D); // building OMP sparse coder\n\t// Removing training sample mean\n\tfor (int k=0; k<Ntrain; k++)\n\t{\n\t\tfor (int i=0; i<Npix; i++) // reading sample k\n\t\t\tsample(i) = TabTrain(i,k);\n\t\tsample_mean = sample.mean(); // computing sample mean\n\t\tfor (int i=0; i<Npix; i++)\n\t\t\tTabTrain(i,k) = sample(i) - sample_mean;  // subtracting mean\n\t}\n\t// iterating sparse coding and dictionary update steps\n\tif (Verb == true)\n\t{\n\t\tcout << \"Learning dictionary of \" << Na << \" atoms of \" << Npix << \" pixels\" << endl;\n\t\tcout << \"Starting Dictionary Learning for \" << IterationNumber << \" iterations\" << endl;\n\t\tcout << \"Using OMP with SparsityTarget = \"<< SparsityTarget << \" and ErrorTarget = \" << ErrorTarget << endl;\n\t}\n\tfor (int i=0;i<IterationNumber;i++)\n\t{\n\t\tif (Verb == true)\n\t\t{\n\t\t\tif (IterationNumber > 1000)\n\t\t\t{\n\t\t\t\tif ((i+1)%(IterationNumber/10) == 1)\n\t\t\t\t\tcout << \"DL iteration \" << i+1 << \" / \" << IterationNumber << \", average sparsity \" << average_sparsity << \", average error \" << average_error << endl;\n\t\t\t}\n\t\t\telse cout << \"DL iteration \" << i+1 << \" / \" << IterationNumber << \", average sparsity \" << average_sparsity << \", average error \" << average_error << endl;\n\t\t}\n\t\t// sparse coding training sample in dictionary\n\t\tX = coder.omp(TabTrain,SparsityTarget,ErrorTarget,False);\n\t\tif (Verb == true)\n\t\t{\n\t\t\t// Computing average sparsity given sparse encoding coefficients\n\t\t\taverage_sparsity = 0;\n\t\t\tfor (int i=0;i<X.nx();i++)\n\t\t\t\tfor (int j=0;j<X.ny();j++)\n\t\t\t\t\tif (X(i,j) !=0)\n\t\t\t\t\t\taverage_sparsity++;\n\t\t\taverage_sparsity = average_sparsity / (Ntrain);\n\t\t}\n\n\t\t// Computing sparse coefficients matrix pseudo inverse for dictionary update\n\t\tif (Verb == True)\n\t\t{\n\t\t\tcout << \"Sparse coding complete, average sparsity \" << average_sparsity << endl;\n\t\t\tcout << \"Updating dictionary ...\" << endl;\n\t\t}\n\t\t//\t\tterminator.inv_mat_svd(X,Xpinv,minT);  previous method, too slow for large data\n\t\t// Transposing matrix X before computing its pseudoinverse\n\t\tfor (int p=0;p<X.nx();p++)\n\t\t\tfor (int q=0;q<X.ny();q++)\n\t\t\t\tXt(q,p) = X(p,q);\n\t\t// Filling matrix armaXt with coefficients from Xt\n\t\tfor (int p=0;p<Ntrain;p++)\n\t\t\tfor (int q=0;q<Na;q++)\n\t\t\t\tarmaXt(p,q) = Xt(p,q);\n\t\t//Chosing eigenvalue threhsold value\n\t\tminT = Ntrain*eps * sqrt(Xt.energy());\n\t\t// Computing pseudoinverse\n\t\tarmaInv = pinv(armaXt,minT);\n\t\tfor (int p=0;p<Na;p++)\n\t\t\tfor (int q=0;q<Ntrain;q++)\n\t\t\t\tXtpinv(p,q) = armaInv(p,q);\n\n\t\t// gsl_matrix_set(gslA,p,q,Xt(p,q));\n\t\t// gsl_matrix_free(gslA);\n\t\t// gslA = gsl_matrix_alloc(Ntrain,Na);\n\t\t// for (int p=0;p<Ntrain;p++)\n\t\t// \tfor (int q=0;q<Na;q++)\n\t\t// \t\tgsl_matrix_set(gslA,p,q,Xt(p,q));\n\t\t// Computing SVD from A\n\t\t// gsl_linalg_SV_decomp (gslA,gslV,gslS,work);\n\t\t// gsl_linalg_SV_decomp_jacobi (gslA,gslV,gslS);\n\t\t// Thresholding/inverting eigenvalues\n\t\t// S.init(0);\n\t\t/*for (int q=0;q<Na;q++)\n\t\t\tif (gsl_vector_get(gslS,q)<minT)\n\t\t\t\tS(q,q) = 0;\n\t\t\telse\n\t\t\t\tS(q,q) = 1/(gsl_vector_get(gslS,q));\n\t\t// Reading remaining gsl matrices\n\t\tfor (int p=0;p<Ntrain;p++)\n\t\t\tfor (int q=0;q<Na;q++)\n\t\t\t\tAt(q,p) = gsl_matrix_get(gslA,p,q);\n\t\tfor (int p=0;p<Na;p++)\n\t\t\tfor (int q=0;q<Na;q++)\n\t\t\t\tV(p,q) = gsl_matrix_get(gslV,p,q);\n\t\t// Computing pseudo inverse by multiplying matrices\n\t\tXtpinv = mult(V,mult(S,At));*/\n\n\t\t// Applying MOD dictionary update\n\t\tfor (int p=0;p<D.nx();p++)\n\t\t\tfor (int q=0;q<D.ny();q++)\n\t\t\t{\n\t\t\t\tD(p,q) = 0;\n\t\t\t\tfor (int k=0;k<Ntrain;k++)\n\t\t\t\t\tD(p,q) += TabTrain(p,k)*Xtpinv(q,k);\n\t\t\t}\n\t\t// Computing sparse approximation and average quadratic error\n\t\taverage_error = 0;\n\t\tsparse_approx = mult(D,X);\n\t\tfor (int k=0;k<Ntrain;k++)\n\t\t{\n\t\t\tfor (int np=0;np<Npix;np++)\n\t\t\t\tsparse_sample(np) = sparse_approx(np,k) - TabTrain(np,k);\n\t\t\taverage_error =+ sqrt(sparse_sample.energy())/Ntrain;\n\t\t}\n\t\t// Throwing away unused atoms and replacing them by random training samples\n\t\tatoms_replaced = 0;\n\t\tfor (int m=0;m<Na;m++)\n\t\t{\n\t\t\tatom_usage = 0;\n\t\t\tfor (int p=0;p<Ntrain;p++)\n\t\t\t\tif (X(m,p)!=0) atom_usage++;\n\t\t\tif (atom_usage == 0)\n\t\t\t{\n\t\t\t\tnew_sample_ind\t= gsl_rng_uniform_int(rng, Ntrain-1);\n\t\t\t\tfor (int k=0;k<Npix;k++)\n\t\t\t\t\tAcurrent(k) = TabTrain(k,new_sample_ind);\n\t\t\t\tAmean = Acurrent.mean();\n\t\t\t\tfor (int k=0;k<Npix;k++)\n\t\t\t\t\tAcurrent(k) = Acurrent(k) - Amean;\n\t\t\t\tAnorm = sqrt(Acurrent.energy()); // computing 0-mean atom norm\n\t\t\t\tif (Anorm > 1)\n\t\t\t\t{\n\t\t\t\t\tfor (int k=0;k<Npix;k++)\n\t\t\t\t\t\tD(k,m) = Acurrent(k) / Anorm; // removing mean and normalizing\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tfor (int k=0;k<Npix;k++)\n\t\t\t\t\t\tD(k,m) = Acurrent(k); // only removing mean\n\t\t\t\tatoms_replaced++;\n\t\t\t}\n\t\t}\n\t\tif (Verb == True && atoms_replaced !=0)\n\t\t\tif (IterationNumber > 0)\n\t\t\t\tif ((i+1)%(IterationNumber/10) == 1) cout << \"Replaced \" << atoms_replaced << \" unused atoms with random training samples\" << endl;\n\t\t\t\telse\n\t\t\t\t\tcout << \"Replaced \" << atoms_replaced << \" unused atoms with random training samples\" << endl;\n\n\t\t// Normalizing atoms with norm > 1\n\t\tfor (int m=0;m<Na;m++)\n\t\t{\n\t\t\tfor (int p=0;p<Npix;p++)\n\t\t\t\tAcurrent(p) = D(p,m);\n\t\t\tAnorm = sqrt(Acurrent.energy());\n\t\t\tif (Anorm > 1)\n\t\t\t\tfor (int p=0;p<Npix;p++)\n\t\t\t\t\tD(p,m) = D(p,m) / Anorm;\n\t\t}\n\n\n\n\t\t// Updating sparse coder with new version of dictionary\n\t\tcoder.update_dictionary(D);\n\t}\n\treturn D;\n}\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "86215d80e288f230d0a16c3efb2d52e91415abfd", "size": 8020, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/cxx/diclearn/libdiclearn/C_DL1D.cc", "max_stars_repo_name": "sfarrens/cosmostat", "max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cxx/diclearn/libdiclearn/C_DL1D.cc", "max_issues_repo_name": "sfarrens/cosmostat", "max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cxx/diclearn/libdiclearn/C_DL1D.cc", "max_forks_repo_name": "sfarrens/cosmostat", "max_forks_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae", "max_forks_repo_licenses": ["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.6996047431, "max_line_length": 159, "alphanum_fraction": 0.6472568579, "num_tokens": 2569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5980212672153616}}
{"text": "/*\n * <one line to give the library's name and an idea of what it does.>\n * Copyright (C) 2015  Guillaume L. <guillaume.lozenguez@mines-douai.fr>\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\n#include \"float2.h\"\n#include \"tools.h\"\n#include <boost/concept_check.hpp>\n\nusing namespace mia;\nusing namespace std;\n\nFloat2 Float2 :: middle( const Float2 & A, const Float2 & B )\n{\n  return (A+B)*0.5f;\n}\n\nFloat2 Float2 :: mean( const std::list<Float2> & lFloat2 )\n{\n    Float2 mean;\n    int size(0);\n        \n    for( std::list<Float2>::const_iterator it= lFloat2.begin() ; it != lFloat2.end(); ++it ){\n        mean+= *it;\n        ++size;\n    }\n    return mean / (float)size;\n}\n\nstd::array<Float2, 2> Float2::simpleLinearRegression( const std::list<Float2> & point )\n{\n    int size(0);\n    Float2 mean(0.f, 0.f), origin(0.f, 0.f);\n    \n    for( std::list<Float2>::const_iterator it(point.begin()), itEnd(point.end()) ; it != itEnd ; ++it )\n    {\n        mean+= Float2(it->x, it->y);\n        ++size;\n    }\n    mean/= (float)size;\n\n    float slopeNum(0.f), yxSlopeDenum(0.f), xySlopeDenum(0.f);\n    for( std::list<Float2>::const_iterator it(point.begin()), itEnd(point.end()) ; it != itEnd ; ++it )\n    {\n        float dx= (it->x-mean.x);\n        float dy= (it->y-mean.y);\n        \n        slopeNum+= dx*dy;\n        \n        yxSlopeDenum+= dx*dx;\n        xySlopeDenum+= dy*dy;\n        \n        ++size;\n    }\n\n    if( yxSlopeDenum == 0 && xySlopeDenum == 0 )\n    {\n        origin.x= mean.x;\n        origin.y= 0.f;\n    }\n    else if( yxSlopeDenum*yxSlopeDenum > xySlopeDenum*xySlopeDenum )\n    {\n        float slope= slopeNum / yxSlopeDenum;\n        origin.x= 0;\n        origin.y= mean.y - slope * mean.x;\n    }\n    else\n    {\n        float slope= slopeNum / xySlopeDenum;\n        origin.y= 0;\n        origin.x= mean.x - slope * mean.y;\n    }\n    \n    std::array<Float2, 2> descriptor= {mean, Float2(origin, mean)};\n    descriptor[1].normalize();\n    \n    return descriptor;\n}\n\n\nstd::array<Float2, 2> Float2::projectionSegment( const std::list<Float2> & point, const Float2 &mean, const Float2 &normDir )\n{\n    list<float> projection;\n    for( list<Float2>::const_iterator it(point.begin()), itEnd(point.end()) ; it!=itEnd ; ++it )\n        projection.push_back( dotProduct( (*it) - mean, normDir ) );\n    projection.sort();\n\n    array<Float2, 2> segment= { normDir * *(projection.begin()) + mean, normDir * *(projection.rbegin()) + mean };\n    return segment;\n}\n\nbool Float2::validSegmentRegression( const std::list<Float2> & lFloat2, const std::array<Float2, 2> & normSegment, float treshold )\n{\n    Float2 normDir= normSegment[1].orthogonal();\n    bool valid(true);\n    \n    for( list<Float2>::const_iterator it(lFloat2.begin()), itEnd(lFloat2.end()) ; valid && it!=itEnd ; ++it )\n        valid= dotProduct( (*it) - normSegment[0], normDir ) < treshold;\n    \n    return valid;\n}\n\nlist<Float2> Float2 :: polarSort(const list<Float2> & lFloat2)\n{\n    list< valued<Float2> > toSort;    \n    for(list<Float2>::const_iterator it = lFloat2.begin(); it != lFloat2.end() ; ++it )\n        toSort.push_back( valued<Float2>( *it, it->angle() ) ); \n    toSort.sort();\n    \n    list<Float2> ret;\n    for(list<valued<Float2>>::const_iterator it = toSort.begin(); it != toSort.end() ; ++it )\n        ret.push_back( it->item );\n    \n    return ret;\n}\n\n\nTransform Transform::from_match ( std::list<std::pair<Float2, Float2>>::const_iterator itBegin,\n                                     std::list<std::pair<Float2, Float2>>::const_iterator itEnd )\n{ // Which translation / rotation to transfom second to first ?\n    Transform t;\n    t.translation= Float2(0.f, 0.f);\n    t.center= Float2(0.f, 0.f);\n    t.rotation= 0.f;\n    int size(0);\n\n    for( std::list<std::pair<Float2, Float2>>::const_iterator it= itBegin ; it != itEnd ; ++it )\n    {// Get center :\n        t.center+= it->first;\n        t.translation+= it->second;\n        ++size;\n    }\n    t.center/= (float)size; // Center first\n    t.translation/= (float)size; // Center second\n    t.translation= t.center - t.translation; // translation from second to first.\n    \n    // Rotation :\n    for( std::list<std::pair<Float2, Float2>>::const_iterator it= itBegin ; it != itEnd ; ++it )\n    {\n        t.rotation+= angle( it->second + t.translation, t.center, it->first );\n    }\n    t.rotation= reduceRadian( t.rotation/(float)size );\n    \n    return t;\n}\n", "meta": {"hexsha": "160418347887579fc36f90d1dc0adf98dc90ee07", "size": 4992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "torob/src/float2.cpp", "max_stars_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_stars_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-12-10T15:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T17:40:11.000Z", "max_issues_repo_path": "torob/src/float2.cpp", "max_issues_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_issues_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T15:19:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T21:26:47.000Z", "max_forks_repo_path": "torob/src/float2.cpp", "max_forks_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_forks_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-29T03:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:59:10.000Z", "avg_line_length": 31.2, "max_line_length": 131, "alphanum_fraction": 0.6105769231, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5979115133530502}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n    This is an example illustrating the use of the krls object \r\n    from the dlib C++ Library.\r\n\r\n    The krls object allows you to perform online regression.  This\r\n    example will use the krls object to perform filtering of a signal\r\n    corrupted by uniformly distributed noise.\r\n*/\r\n\r\n#include <iostream>\r\n\r\n#include <dlib/svm.h>\r\n#include <dlib/rand.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// Here is the function we will be trying to learn with the krls\r\n// object.\r\ndouble sinc(double x)\r\n{\r\n    if (x == 0)\r\n        return 1;\r\n\r\n    // also add in x just to make this function a little more complex\r\n    return sin(x)/x + x;\r\n}\r\n\r\nint main()\r\n{\r\n    // Here we declare that our samples will be 1 dimensional column vectors.  The reason for\r\n    // using a matrix here is that in general you can use N dimensional vectors as inputs to the\r\n    // krls object.  But here we only have 1 dimension to make the example simple.\r\n    typedef matrix<double,1,1> sample_type;\r\n\r\n\r\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\r\n    // radial basis kernel because it only has one parameter and generally gives good\r\n    // results without much fiddling.\r\n    typedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n\r\n    // Here we declare an instance of the krls object.  The first argument to the constructor\r\n    // is the kernel we wish to use.  The second is a parameter that determines the numerical \r\n    // accuracy with which the object will perform part of the regression algorithm.  Generally\r\n    // smaller values give better results but cause the algorithm to run slower (because it tries\r\n    // to use more \"dictionary vectors\" to represent the function it is learning.  \r\n    // You just have to play with it to decide what balance of speed and accuracy is right \r\n    // for your problem.  Here we have set it to 0.001.\r\n    //\r\n    // The last argument is the maximum number of dictionary vectors the algorithm is allowed\r\n    // to use.  The default value for this field is 1,000,000 which is large enough that you \r\n    // won't ever hit it in practice.  However, here we have set it to the much smaller value\r\n    // of 7.  This means that once the krls object accumulates 7 dictionary vectors it will \r\n    // start discarding old ones in favor of new ones as it goes through the training process.  \r\n    // In other words, the algorithm \"forgets\" about old training data and focuses on recent\r\n    // training samples. So the bigger the maximum dictionary size the longer its memory will \r\n    // be.  But in this example program we are doing filtering so we only care about the most \r\n    // recent data.  So using a small value is appropriate here since it will result in much\r\n    // faster filtering and won't introduce much error.\r\n    krls<kernel_type> test(kernel_type(0.05),0.001,7);\r\n\r\n    dlib::rand rnd;\r\n\r\n    // Now let's loop over a big range of values from the sinc() function.  Each time\r\n    // adding some random noise to the data we send to the krls object for training.\r\n    sample_type m;\r\n    double mse_noise = 0;\r\n    double mse = 0;\r\n    double count = 0;\r\n    for (double x = -20; x <= 20; x += 0.01)\r\n    {\r\n        m(0) = x;\r\n        // get a random number between -0.5 and 0.5\r\n        const double noise = rnd.get_random_double()-0.5;\r\n\r\n        // train on this new sample\r\n        test.train(m, sinc(x)+noise);\r\n\r\n        // once we have seen a bit of data start measuring the mean squared prediction error.\r\n        // Also measure the mean squared error due to the noise.\r\n        if (x > -19)\r\n        {\r\n            ++count;\r\n            mse += pow(sinc(x) - test(m),2);\r\n            mse_noise += pow(noise,2);\r\n        }\r\n    }\r\n\r\n    mse /= count;\r\n    mse_noise /= count;\r\n\r\n    // Output the ratio of the error from the noise and the mean squared prediction error.  \r\n    cout << \"prediction error:                   \" << mse << endl;\r\n    cout << \"noise:                              \" << mse_noise << endl;\r\n    cout << \"ratio of noise to prediction error: \" << mse_noise/mse << endl;\r\n\r\n    // When the program runs it should print the following:\r\n    //    prediction error:                   0.00735201\r\n    //    noise:                              0.0821628\r\n    //    ratio of noise to prediction error: 11.1756\r\n\r\n    // And we see that the noise has been significantly reduced by filtering the points \r\n    // through the krls object.\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "337d174a73b04004d3b34edb3709ddd460cf70ec", "size": 4572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/krls_filter_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/krls_filter_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/krls_filter_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5636363636, "max_line_length": 98, "alphanum_fraction": 0.6463254593, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.5978059573932076}}
{"text": "#include <ctime>\n#include <vector>\n#include <math.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include \"mex.h\"\n#include \"nlopt.hpp\"\n\nint counter = 0;\n\nusing namespace std;\nusing namespace Eigen;\nusing Eigen::MatrixXd;\n\nstruct mFuncData\n{\n\tint numDims, numSamples;\n\tMatrixXd X, Y;\n\tMatrixXd XX, YX;\n};\n\ndouble myfunc(unsigned n, const double *inW, double *grad, void *inData)\n{\n\t++counter;\n\n\tmFuncData* data = (mFuncData*)inData;\n\tMatrixXd W = Map<MatrixXd>((double*)inW, data->numDims, data->numDims);\n\n\t// 2 * W*(X*X') - Y*X' - Y*X';\n\tif (grad)\n\t{\n\t\tclock_t beginM = clock();\n\n\t\tmwSize size[2]; size[0] = data->numDims;  size[1] = data->numDims;\n\t\tmxArray* prhs[2];\n\t\tprhs[0] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);\n\t\tdouble* WMatlab = (double*)mxGetData(prhs[0]);\n\t\tMap<MatrixXd>(WMatlab, data->numDims, data->numDims) = W;\n\t\tprhs[1] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);\n\t\tdouble* XMatlab = (double*)mxGetData(prhs[1]);\n\t\tMap<MatrixXd>(XMatlab, data->numDims, data->numDims) = data->XX;\n\n\t\tmxArray* plhs[1];\n\t\tint output = mexCallMATLAB(1, plhs, 2, prhs, \"mtimes\");\n\t\tdouble* res = (double*)mxGetData(plhs[0]);\n\t\tMatrixXd newW = Map<MatrixXd>(res, data->numDims, data->numDims);\n\t\tMatrixXd gradient = 2.0*newW - data->YX - data->YX;\n\n\t\tMap<MatrixXd>(grad, data->numDims, data->numDims) = gradient;\n\n\t\tclock_t endM = clock();\n\t\t// mexPrintf(\"time step newgrad: %f\\n\", difftime(endM, beginM));\n\t}\n\t\n\n\t\n\t// val = norm(W*X - Y);\n\tclock_t begin1 = clock();\n\tMatrixXd res = W*data->X - data->Y;\n\tclock_t end1 = clock();\n\t//mexPrintf(\"time step main: %f\\n\", difftime(end1, begin1));\n\n\t// Matlab call\n\tclock_t beginM = clock();\n\tmxArray* prhs[1];\n\tmwSize size[2]; size[0] = data->numDims;  size[1] = data->numSamples;\n\tprhs[0] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);\n\tdouble* resMatlab = (double*)mxGetData(prhs[0]);\n\tMap<MatrixXd>(resMatlab, data->numDims, data->numSamples) = res;\n\tmxArray* plhs[1];\n\tmexCallMATLAB(1, plhs, 1, prhs, \"norm\");\n\tdouble norm = (double)mxGetScalar(plhs[0]);\n\tclock_t endM = clock();\n\t// mexPrintf(\"time step norm: %f\\n\", difftime(endM, beginM));\n\tmexPrintf(\"[iter %d] energy: %f\\n\", counter, norm);\n\n\t/*\n\tclock_t begin2 = clock();\n\tdouble energy = res.operatorNorm();\n\tclock_t end2 = clock();\n\tmexPrintf(\"time step norm: %f\\n\", difftime(end2, begin2));\n\tmexPrintf(\"[iter %d] energy: %f\\n\", counter, energy);\n\treturn energy;\n\t*/\n\n\treturn norm;\n}\n\ntypedef struct\n{\n\tdouble a, b;\n} mConstraintData;\n\ndouble myconstraint(unsigned n, const double *x, double *grad, void *data)\n{\n\tmConstraintData *d = (mConstraintData *)data;\n\tdouble a = d->a, b = d->b;\n\tif (grad) {\n\t\tgrad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);\n\t\tgrad[1] = -1.0;\n\t}\n\treturn ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);\n}\n\nvoid run_optimiser(double* x, double* residual, int numDims, int numSamples, double* srcCentres, double* tgtCentres)\n{\n\tnlopt_opt opt;\n\t\n\topt = nlopt_create(NLOPT_LD_MMA, numDims*numDims); /* algorithm and dimensionality */\n\t// opt = nlopt_create(NLOPT_LN_COBYLA, numDims*numDims); /* algorithm and dimensionality */\n\n\tmFuncData funcData;\n\tfuncData.numDims = numDims;\n\tfuncData.numSamples = numSamples;\n\tfuncData.X = Map<MatrixXd>(srcCentres, numDims, numSamples);\n\tfuncData.Y = Map<MatrixXd>(tgtCentres, numDims, numSamples);\n\n\t// Precomputation\n\tfuncData.XX = funcData.X * funcData.X.transpose();\n\tfuncData.YX = funcData.Y * funcData.X.transpose();\n\t\n\tnlopt_set_min_objective(opt, myfunc, &funcData);\n\tnlopt_set_xtol_rel(opt, 1e-4);\n\tnlopt_set_maxeval(opt, 25);\n\n\t// Constraints:\n\t//mConstraintData data[2] = { { 2, 0 }, { -1, 1 } };\n\t//nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-4);\n\t//nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-4);\n\n\tif (nlopt_optimize(opt, x, residual) < 0)\n\t\tprintf(\"nlopt failed!\\n\");\n\telse\n\t\tprintf(\"found minimum after %d evaluations with residual %f\\n\", counter, *residual);\n\n\tnlopt_destroy(opt);\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\t/* Macros for the input arguments */\n\t#define srcCentres_IN prhs[0]\n\t#define tgtCentres_IN prhs[1]\n\n\t/* Macros for the output arguments */\n\t#define x_OUT plhs[0]\n\t#define residual_OUT plhs[1]\n\n\t/* Check correctness of input/output arguments */\n\tif (nrhs < 2 || nrhs > 2)\n\t\tmexErrMsgTxt(\"Wrong number of input arguments.\");\n\telse if (nlhs > 2)\n\t\tmexErrMsgTxt(\"Too many output arguments.\");\n\n\t/* Get input data */\n\tdouble* srcCentres = (double*)mxGetData(srcCentres_IN);\n\tdouble* tgtCentres = (double*)mxGetData(tgtCentres_IN);\n\tint numDims = (int)mxGetM(srcCentres_IN);\n\tint numSamples = (int)mxGetN(srcCentres_IN);\n\n\t/* Create output data */\n\tx_OUT = mxCreateNumericMatrix(numDims, numDims, mxDOUBLE_CLASS, mxREAL);\n\tdouble* x = (double*)mxGetData(x_OUT);\n\tresidual_OUT = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL);\n\tdouble* residual = (double*)mxGetData(residual_OUT);\n\n\t// Initial guess (Id matrix)\n\tfor (int idx = 0; idx < numDims*numDims; ++idx)\n\t{\n\t\tif (idx % (numDims + 1) == 0)\n\t\t\tx[idx] = 1.0;\n\t\telse\n\t\t\tx[idx] = 0.0;\n\t}\n\t\n\t// Reset counter\n\tcounter = 0;\n\n\t/* Call method */\n\trun_optimiser(x, residual, numDims, numSamples, srcCentres, tgtCentres);\n\n\treturn;\n}\n", "meta": {"hexsha": "85122254fef3d4ee39e137a300b1ddf3284bedb6", "size": 5209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "da/min/nlopt/matlab/mexNLOPT.cpp", "max_stars_repo_name": "Heliot7/open-set-da", "max_stars_repo_head_hexsha": "cd3c8c9a2491dd7165259e8fde769046f735a5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T00:50:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T00:54:25.000Z", "max_issues_repo_path": "da/min/nlopt/matlab/mexNLOPT.cpp", "max_issues_repo_name": "Heliot7/open-set-da", "max_issues_repo_head_hexsha": "cd3c8c9a2491dd7165259e8fde769046f735a5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-11-21T00:50:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-07T13:43:14.000Z", "max_forks_repo_path": "da/min/nlopt/matlab/mexNLOPT.cpp", "max_forks_repo_name": "Heliot7/open-set-da", "max_forks_repo_head_hexsha": "cd3c8c9a2491dd7165259e8fde769046f735a5b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T00:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T05:18:16.000Z", "avg_line_length": 27.8556149733, "max_line_length": 116, "alphanum_fraction": 0.675945479, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5977892030939834}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/rowmajor_matrix.hpp>\n#include <frovedis/matrix/tsne.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\n\ntemplate <class T>\nvoid call_tsne(const std::string& data_p, const std::string& out_p, double perplexity,\n               double early_exaggeration, double min_grad_norm, double learning_rate, \n               size_t n_components, size_t max_iter, size_t n_iter_without_progress, \n               const std::string& metric, const std::string& method, \n               const std::string& init, bool verbose) { \n  time_spent load_t(INFO);\n  load_t.lap_start();\n  auto mat = make_rowmajor_matrix_load<T>(data_p);\n  load_t.lap_stop();\n  load_t.show_lap(\"data loading time: \");\n  std::cout << \"n_samples = \" << mat.num_row\n            << \", n_features = \" << mat.num_col\n            << std::endl;\n  time_spent tsne_t(INFO);\n  tsne_t.lap_start();\n\n  TSNE<T> t1;\n  t1.set_perplexity(perplexity).\n     set_early_exaggeration(early_exaggeration).\n     set_min_grad_norm(min_grad_norm).\n     set_learning_rate(learning_rate).\n     set_n_components(n_components).\n     set_n_iter(max_iter).\n     set_n_iter_without_progress(n_iter_without_progress).\n     set_metric(metric).\n     set_method(method).\n     set_init(init).\n     set_verbose(verbose); \n\n  auto Y_mat = t1.fit_transform(mat); \n  auto n_iter = t1.get_n_iter_();\n  auto kl_divergence = t1.get_kl_divergence_();\n\n  tsne_t.lap_stop();\n  tsne_t.show_lap(\"Overall computation time: \");\n  Y_mat.save(out_p);\n  std::cout << \"n_iter_ = \" << n_iter << std::endl;\n  std::cout << \"kl_divergence_ = \" << kl_divergence << std::endl;\n}\n\nint main(int argc, char* argv[]) {\n  use_frovedis use(argc, argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"input,i\" , value<std::string>(), \"input data path containing input data for T-SNE\") \n      (\"dtype,t\" , value<std::string>(), \"input data type (float or double) [default: double]\") \n      (\"output,o\" , value<std::string>(), \"output data path to save output embeddings\")\n      (\"max_iter,k\", value<size_t>(), \"maximum no. of iterations (default: 1000)\") \n      (\"perplexity,p\", value<double>(), \"number of nearest neighbors for each point (default: 30.0)\")\n      (\"early_exaggeration,e\", value<double>(), \"controls the space between natural clusters in the embedded space (default: 12.0)\")\n      (\"min_grad_norm,g\", value<double>(), \"gradient norm threshold (default: 1e-7)\")\n      (\"learning_rate,l\", value<double>(), \"learning rate for t-SNE (default: 200.0)\")\n      (\"n_components,n\", value<size_t>(), \"dimension of the embedded space (default: 2)\")\n      (\"niter_without_progress\", value<size_t>(), \"maximum number of iterations without progress before we abort the optimization (default: 300)\")\n      (\"metric,m\" , value<std::string>(), \"the metric (euclidean or precomputed) to use when calculating distance (default: euclidean)\")\n      (\"method\" , value<std::string>(), \"the method (exact) to use for TSNE computation (default: exact)\")\n      (\"init\" , value<std::string>(), \"the init (random) to use for initializing Y mat (default: random)\")\n      (\"verbose\", \"set loglevel to DEBUG\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);                \n\n  std::string dtype =  \"double\";\n  std::string data_p =  \"\";\n  std::string out_p =  \"\";\n  size_t max_iter = 1000;\n  double perplexity = 30.0;\n  double early_exaggeration = 12.0;\n  double min_grad_norm = 1e-7;\n  double learning_rate = 200.0;\n  size_t n_components = 2;\n  size_t n_iter_without_progress = 300;\n  std::string metric = \"euclidean\"; //possible values = [\"euclidean\", \"precomputed\"]\n  std::string method = \"exact\"; //possible values = [\"exact\"]\n  std::string init = \"random\"; //possible values = [\"random\"]\n  bool verbose = false;\n\n  if(argmap.count(\"help\")){\n    std::cerr << opt << std::endl;\n    exit(1);\n  }\n  if(argmap.count(\"input\")){\n    data_p = argmap[\"input\"].as<std::string>();\n  } else {\n    std::cerr << \"input path is not specified\" << std::endl;\n    std::cerr << opt << std::endl;\n    exit(1);\n  }    \n  if(argmap.count(\"dtype\")){\n    dtype = argmap[\"dtype\"].as<std::string>();\n  }    \n  if(argmap.count(\"output\")){\n    out_p = argmap[\"output\"].as<std::string>();\n  } else {\n    std::cerr << \"output path is not specified\" << std::endl;\n    std::cerr << opt << std::endl;\n    exit(1);\n  }    \n  if(argmap.count(\"max_iter\")){\n     max_iter = argmap[\"max_iter\"].as<size_t>();\n  }\n  if(argmap.count(\"perplexity\")){\n     perplexity = argmap[\"perplexity\"].as<double>();\n  }\n  if(argmap.count(\"early_exaggeration\")){\n     early_exaggeration = argmap[\"early_exaggeration\"].as<double>();\n  }\n  if(argmap.count(\"min_grad_norm\")){\n     min_grad_norm = argmap[\"min_grad_norm\"].as<double>();\n  }\n  if(argmap.count(\"learning_rate\")){\n     learning_rate = argmap[\"learning_rate\"].as<double>();\n  }\n  if(argmap.count(\"n_components\")){\n     n_components = argmap[\"n_components\"].as<size_t>();\n  }\n  if(argmap.count(\"niter_without_progress\")){\n     n_iter_without_progress = argmap[\"niter_without_progress\"].as<size_t>();\n  }\n  if(argmap.count(\"metric\")){\n    metric = argmap[\"metric\"].as<std::string>();\n  }  \n  if(argmap.count(\"method\")){\n    method = argmap[\"method\"].as<std::string>();\n  }\n  if(argmap.count(\"init\")){\n    init = argmap[\"init\"].as<std::string>();\n  }\n  if(argmap.count(\"verbose\")){\n    set_loglevel(DEBUG);\n    verbose = true;\n  }\n\n  try {\n    if (dtype == \"float\") {\n      call_tsne<float>(data_p, out_p, perplexity, early_exaggeration, min_grad_norm, \n                       learning_rate, n_components, max_iter, \n                       n_iter_without_progress, metric, method, init, verbose);\n    }\n    else if (dtype == \"double\") {\n      call_tsne<double>(data_p, out_p, perplexity, early_exaggeration, min_grad_norm, \n                        learning_rate, n_components, max_iter, \n                        n_iter_without_progress, metric, method, init, verbose);\n    }\n    else {\n      std::cerr << \"Supported dtypes are only float and double!\\n\";\n      std::cerr << opt << std::endl;\n      exit(1);\n    }\n  }\n  catch(std::exception& e) {\n    std::cout << \"exception caught: \" << e.what() << std::endl;\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "4db283045c780121737db7f39d827cb571bf4b41", "size": 6389, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/tsne/tsne.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/tsne/tsne.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/tsne/tsne.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 37.1453488372, "max_line_length": 146, "alphanum_fraction": 0.6417279699, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7154239957834732, "lm_q1q2_score": 0.5977249763871088}}
{"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_NTHROOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NTHROOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing nthroot capabilities\n\n    nth root function: \\f$\\sqrt[n]{x}\\f$\n    \\arg n must be of integer type\n    \\arg if n is even and x negative the result is @ref Nan\n    \\arg if x is null the result is @ref Zero\n    \\arg if x is one  the result is @ref One\n\n    @par Semantic:\n\n    For every parameters of  floating type T and integral type N:\n\n    @code\n    T r = nthroot(x, n);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = n >= 0 ? pow(x, rec(tofloat(n))) : Nan;\n    @endcode\n\n    @par Note:\n    nthroot is more expansive than pow(x, rec(tofloat(n))) because\n    it takes care of some limits issues that @ref pow does not mind of.\n\n    See if it suits you better.\n\n    @see pow, rec, sqrt, cbrt\n\n  **/\n  const boost::dispatch::functor<tag::nthroot_> nthroot = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/nthroot.hpp>\n#include <boost/simd/function/simd/nthroot.hpp>\n\n#endif\n", "meta": {"hexsha": "fdc65e43dbfb06311d44f23c1116111f20dd82fb", "size": 1540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/nthroot.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/nthroot.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/nthroot.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2459016393, "max_line_length": 100, "alphanum_fraction": 0.5948051948, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5977249638726541}}
{"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#include <boost/numeric/ublas/matrix.hpp>\n#include <math.h>       /* sqrt */\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* ublas binding for gsl_eigen_symmv\n* note that the eigenvalues/eigenvectors are UNSORTED \n* \n*/\nbool linalg_eigenvalues_symmetric( ub::symmetric_matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V)\n{\n\tgsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n        \n        // gsl does not handle conversion of a symmetric_matrix \n        ub::matrix<double> _A( N,N );\n        _A = A;\n        \n\tE.resize(N, false);\n\tV.resize(N, N, false);\n\tgsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);\n\tgsl_vector_view E_view = gsl_vector_view_array(&E(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);\n\tgsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);\n\n\tint status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);\n\t//gsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_ABS_ASC);\n\tgsl_eigen_symmv_free(w);\n\tgsl_set_error_handler(handler);\n        \n\treturn (status != 0);\n};\n\n\n/**\n*\n* ublas binding for gsl_eigen_symmv\n* input matrix type general matrix!\n* wrapping gsl_eigen_symmv \n* \n*/\nbool linalg_eigenvalues( ub::matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V)\n{\n\tgsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n        \n        // gsl does not handle conversion of a symmetric_matrix \n        ub::matrix<double> _A( N,N );\n        _A = A;\n        \n\tE.resize(N, false);\n\tV.resize(N, N, false);\n\tgsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);\n\tgsl_vector_view E_view = gsl_vector_view_array(&E(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);\n\tgsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);\n\n\tint status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);\n\tgsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);\n\tgsl_eigen_symmv_free(w);\n\tgsl_set_error_handler(handler);\n        \n\treturn (status != 0);\n};\n\n/**\n*\n* ublas binding for gsl_eigen_symmv\n* input matrix type general matrix single precision!\n* wrapping gsl_eigen_symmv \n* \n*/\nbool linalg_eigenvalues( ub::matrix<float> &A, ub::vector<float> &E, ub::matrix<float> &V)\n{\n\tgsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n        \n        // gsl does not handle symmetric_matrix and floats, so this is super stupid\n        ub::matrix<double> _A( N,N );\n        _A = A;\n        ub::vector<double> _E(N);\n        ub::matrix<double> _V(N,N);\n\tgsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);\n\tgsl_vector_view E_view = gsl_vector_view_array(&_E(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&_V(0,0), N, N);\n\tgsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);\n\n\tint status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);\n\tgsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);\n\tgsl_eigen_symmv_free(w);\n\tgsl_set_error_handler(handler);\n\n\t//E.resize(N, false);\n\t//V.resize(N, N, false);\n        E = _E;\n        V = _V;\n        \n\treturn (status != 0);\n};\n\nbool linalg_eigenvalues(  ub::vector<float> &E, ub::matrix<float> &V)\n{\n        /* on input V is the matrix that shall be diagonalized\n         * GSL does not provide an in-place routine, so we wrap \n         * gsl_eigen_symmv for compatibility\n         */\n    \n         // make a copy of E\n         ub::matrix<float> A = V;\n    \n         // now call wrapper for gsl_eigen_symmv\n         bool status = linalg_eigenvalues( A , E, V );\n\treturn (status != 0);\n};\n\n\n/**\n*\n* ublas binding for gsl_eigen_symm\n* input matrix type general matrix!\n* wrapping gsl_eigen_symm leaves input matrix \n* \n*/\nbool linalg_eigenvalues( ub::vector<double> &E, ub::matrix<double> &V)\n{\n        /* on input V is the matrix that shall be diagonalized\n         * GSL does not provide an in-place routine, so we wrap \n         * gsl_eigen_symmv for compatibility\n         */\n    \n         // make a copy of E\n         ub::matrix<double> A = V;\n    \n         // now call wrapper for gsl_eigen_symmv\n         bool status = linalg_eigenvalues( A , E, V );\n\n         return status;\n};\n\n\n/*\n * use expert routine to calculate only a subrange of eigenvalues\n */\nbool linalg_eigenvalues( ub::matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V , int nmax)\n{\n    throw std::runtime_error(\"linalg_eigenvalues is not compiled-in due to disabling of MKL - recompile Votca Tools with MKL support\");\n}\n\n/*\n * use expert routine to calculate only a subrange of eigenvalues single precision\n */\nbool linalg_eigenvalues( ub::matrix<float> &A, ub::vector<float> &E, ub::matrix<float> &V , int nmax)\n{\n    // now call wrapper for gsl_eigen_symmv\n    bool status = linalg_eigenvalues( A , E, V );\n\n    return status;\n}\n\nbool linalg_eigenvalues_general( ub::matrix<double> &A,ub::matrix<double> &B, ub::vector<double> &E, ub::matrix<double> &V)\n{\n\tgsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n        \n        // gsl destroys A so use copy\n        ub::matrix<double> _A( N,N );\n        _A = A;\n        \n        ub::matrix<double> _B( N,N );\n        _B=B;\n        \n\tE.resize(N, false);\n\tV.resize(N, N, false);\n\tgsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);\n        gsl_matrix_view B_view = gsl_matrix_view_array(&_B(0,0), N, N);\n\tgsl_vector_view E_view = gsl_vector_view_array(&E(0), N);\n\tgsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);\n\tgsl_eigen_gensymmv_workspace *w = gsl_eigen_gensymmv_alloc(N);\n\n\tint status = gsl_eigen_gensymmv(&A_view.matrix,&B_view.matrix, &E_view.vector, &V_view.matrix, w);\n\tgsl_eigen_gensymmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);\n\tgsl_eigen_gensymmv_free(w);\n\tgsl_set_error_handler(handler);\n        \n      \n\n    \n        ub::matrix<double> _temp= ub::prod(B,V);\n        ub::matrix<double> n=ub::prod(ub::trans(V),_temp);\n      /*  \n        for (int i=0;i<n.size1();i++){\n          \n                for (int j=0;j<n.size2();j++){\n                cout <<\"n(\"<< i << \":\"<< j <<\")= \" <<n(i,j)<< endl;      \n                }}\n        \n       */ \n        \n        for (unsigned int i=0;i<n.size1();i++){\n            ub::matrix_range<ub::matrix<double> > column=ub::subrange( V, 0, V.size2(),i, i+1 );\n            //cout <<\"n(\"<< i << \":\"<< i <<\")= \" <<n(i,i) <<\":\" <<sqrt(n(i,i))<< endl; \n            //for (int j=0;j<column.size1();j++){\n                \n           \n            //cout <<\"V(\"<<i<<\":\"<<j<<\")=\"<<column(j,0)<< endl;\n                    \n              //}\n            column=column/sqrt(n(i,i));\n  \n        }\n    \n\treturn (status != 0);\n};\n\n}}\n", "meta": {"hexsha": "068fe90c6ea206de9c919daa8ef58fdf8f762d3d", "size": 7592, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/gsl/eigensystems.cc", "max_stars_repo_name": "Pallavi-Banerjee21/votca.tools", "max_stars_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/eigensystems.cc", "max_issues_repo_name": "Pallavi-Banerjee21/votca.tools", "max_issues_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/eigensystems.cc", "max_forks_repo_name": "Pallavi-Banerjee21/votca.tools", "max_forks_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_forks_repo_licenses": ["Apache-2.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.2427983539, "max_line_length": 135, "alphanum_fraction": 0.6427818757, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835330070839, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5977249574565794}}
{"text": "#ifndef WAGNER_COMMON_H_\n#define WAGNER_COMMON_H_\n\n#include <cmath>\n\n#ifndef WAGNER_NOBOOST\n  #include <boost/container/flat_set.hpp>\n  #include <boost/container/flat_map.hpp>\n#else\n  #include <set>\n  #include <map>\n#endif\n\nnamespace wagner {\n\n#ifndef WAGNER_NOBOOST\n  template<typename Key>\n  using set = boost::container::flat_set<Key>;\n\n  template<typename Key, typename Value>\n  using map = boost::container::flat_map<Key, Value>;\n#else\n  template<typename Key>\n  using set = std::set<Key>;\n\n  template<typename Key, typename Value>\n  using map = std::map<Key, Value>;\n#endif\n\nconstexpr size_t wagner_version = 2;\nconstexpr size_t wagner_revision = 0;\n\n/** Mathematical constant e. */\n#define math_e 2.71828182845904523536\n\n/** Mathematical constant pi. */\n#define math_pi 3.14159265358979323846\n\n/** Log 2 (very important in information theory). */\n#define log2(x) (log(x) / log(2.0))\n\n/** Check if a number is a power of two. */\n#define power_of_two(n) (((n) != 0) && !((n) & ((n)-1)))\n\n/** Cubic root. */\n#define cbrt(x) (pow((x), 1.0 / 3.0))\n\n/** Max of two values. */\n#define max2(a, b) ((a) > (b) ? (a) : (b))\n\n/** Min of two values. */\n#define min2(a, b) ((a) < (b) ? (a) : (b))\n\n/** Max of three values. */\n#define max3(a, b, c) (max2(a, b) > (c) ? max2(a, b) : (c))\n\n/** Min of three values. */\n#define min3(a, b, c) (min2(a, b) < (c) ? min2(a, b) : (c))\n\n/** Max of four values. */\n#define max4(a, b, c, d) (max3(a, b, c) > (d) ? max3(a, b, c) : (d))\n\n/** Min of four values. */\n#define min4(a, b, c, d) (min3(a, b, c) < (d) ? min3(a, b, c) : (d))\n\n/** Max of five values. */\n#define max5(a, b, c, d, e) (max4(a, b, c, d) > (e) ? max4(a, b, c, d) : (e))\n\n/** Min of five values. */\n#define min5(a, b, c, d, e) (min4(a, b, c, d) < (e) ? min4(a, b, c, d) : (e))\n\n}\n\n#endif\n", "meta": {"hexsha": "38fb7fc0222ad2e46eb47387f05fa5d2d0920d40", "size": 1785, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/wagner/common.hh", "max_stars_repo_name": "PhDP/wagner", "max_stars_repo_head_hexsha": "92a1f36906cab7601c97795628ece9fc824e5f63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-11T15:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-11T15:05:53.000Z", "max_issues_repo_path": "include/wagner/common.hh", "max_issues_repo_name": "PhDP/wagner2", "max_issues_repo_head_hexsha": "92a1f36906cab7601c97795628ece9fc824e5f63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/wagner/common.hh", "max_forks_repo_name": "PhDP/wagner2", "max_forks_repo_head_hexsha": "92a1f36906cab7601c97795628ece9fc824e5f63", "max_forks_repo_licenses": ["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.8, "max_line_length": 77, "alphanum_fraction": 0.5983193277, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.597627949170115}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <cppad/cppad.hpp> // the CppAD package http://www.coin-or.org/CppAD/\n#include <vector>\n\ntemplate <typename Type, typename Derived>\nstd::vector<Type> Eigen2AD(const Eigen::MatrixBase<Derived>& M)\n{\n    std::vector<Type> out;\n    out.resize(M.size());\n\n    Eigen::Index p = 0;\n    for (Eigen::Index j = 0; j < M.cols(); ++j)\n        for (Eigen::Index i = 0; i < M.rows(); ++i)\n            out[p++] = M(i, j);\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> SumAD(const std::vector<Type>& M1, const std::vector<Type>& M2)\n{\n    std::vector<Type> out(M1.size());\n\n    for (size_t i = 0; i < M1.size(); ++i)\n        out[i] = M1[i] + M2[i];\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> SubAD(const std::vector<Type>& M1, const std::vector<Type>& M2)\n{\n    std::vector<Type> out(M1.size());\n\n    for (size_t i = 0; i < M1.size(); ++i)\n        out[i] = M1[i] - M2[i];\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> ProductAD(const std::vector<Type>& M1, const std::vector<Type>& M2, size_t rowsOut, size_t colsOut = 1)\n{\n    std::vector<Type> out(rowsOut * colsOut, Type(0));\n\n    size_t m = rowsOut;\n    size_t n = M1.size() / rowsOut;\n    size_t p = colsOut;\n    for (size_t j = 0; j < p; ++j)\n        for (size_t i = 0; i < m; ++i)\n            for (size_t k = 0; k < n; ++k)\n                out[i + j * p] += M1[i + k * m] * M2[k + j * p];\n\n    return out;\n}\n\ntemplate <typename Type>\nType DotProductAD(const std::vector<Type>& v1, const std::vector<Type>& v2)\n{\n    Type sum;\n\n    sum = 0.;\n    for (size_t i = 0; i < size_t(v1.size()); ++i)\n        sum += v1[i] * v2[i];\n\n    return sum;\n}\n\ntemplate <typename Type>\nstd::vector<Type> CrossAD(const std::vector<Type>& v1, const std::vector<Type>& v2)\n{\n    std::vector<Type> out(3);\n    out[0] = v1[1] * v2[2] - v1[2] * v2[1];\n    out[1] = v1[2] * v2[0] - v1[0] * v2[2];\n    out[2] = v1[0] * v2[1] - v1[1] * v2[0];\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> Cross6AD(const std::vector<Type>& v1, const std::vector<Type>& v2)\n{\n    std::vector<Type> out(6);\n    out[0] = v1[1] * v2[2] - v1[2] * v2[1];\n    out[1] = v1[2] * v2[0] - v1[0] * v2[2];\n    out[2] = v1[0] * v2[1] - v1[1] * v2[0];\n    out[3] = v1[4] * v2[2] - v1[5] * v2[1] + v1[1] * v2[5] - v1[2] * v2[4];\n    out[4] = v1[5] * v2[0] - v1[3] * v2[2] + v1[2] * v2[3] - v1[0] * v2[5];\n    out[5] = v1[3] * v2[1] - v1[4] * v2[0] + v1[0] * v2[4] - v1[1] * v2[3];\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> Cross6DAD(const std::vector<Type>& v1, const std::vector<Type>& v2)\n{\n    std::vector<Type> out(6);\n    out[0] = v1[1] * v2[2] - v1[2] * v2[1] + v1[4] * v2[5] - v1[5] * v2[4];\n    out[1] = v1[2] * v2[0] - v1[0] * v2[2] + v1[5] * v2[3] - v1[3] * v2[5];\n    out[2] = v1[0] * v2[1] - v1[1] * v2[0] + v1[3] * v2[4] - v1[4] * v2[3];\n    out[3] = v1[1] * v2[5] - v1[2] * v2[4];\n    out[4] = v1[2] * v2[3] - v1[0] * v2[5];\n    out[5] = v1[0] * v2[4] - v1[1] * v2[3];\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> CrossAD(const std::vector<Type>& v)\n{\n    std::vector<Type> out(9);\n    out[0] = Type(0);\n    out[1] = v[2];\n    out[2] = -v[1];\n    out[3] = -v[2];\n    out[4] = Type(0);\n    out[5] = v[0];\n    out[6] = v[1];\n    out[7] = -v[0];\n    out[8] = Type(0);\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> TransposeAD(const std::vector<Type>& M, int rows)\n{\n    std::vector<Type> out(M.size());\n    size_t cols = M.size() / rows;\n    size_t p = 0;\n    for (size_t j = 0; j < cols; ++j)\n        for (size_t i = 0; i < rows; ++i)\n            out[p++] = M[j + cols * i];\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> IdMatAD(size_t size)\n{\n    std::vector<Type> out(size * size, Type(0));\n    for (size_t i = 0; i < size; ++i)\n        out[i + i * size] = Type(1);\n\n    return out;\n}\n\ntemplate <typename Type>\nstd::vector<Type> exp3x3AD(const std::vector<Type>& ax)\n{\n    std::vector<Type> out(9, Type(0));\n    Type angle = CppAD::sqrt(DotProductAD(ax, ax));\n    if (CppAD::abs(angle) < std::numeric_limits<double>::epsilon()) {\n        out[0] = 1;\n        out[4] = 1;\n        out[8] = 1;\n    } else {\n        Type x = ax[0] / angle;\n        Type y = ax[1] / angle;\n        Type z = ax[2] / angle;\n        Type sa = CppAD::sin(angle);\n        Type ca = CppAD::cos(angle);\n\n        out[0] = ca + (1 - ca) * x * x;\n        out[1] = (1 - ca) * y * x + sa * z;\n        out[2] = (1 - ca) * z * x - sa * y;\n        out[3] = (1 - ca) * x * y - sa * z;\n        out[4] = ca + (1 - ca) * y * y;\n        out[5] = (1 - ca) * z * y + sa * x;\n        out[6] = (1 - ca) * x * z + sa * y;\n        out[7] = (1 - ca) * y * z - sa * x;\n        out[8] = ca + (1 - ca) * z * z;\n    }\n\n    return out;\n}\n\ntemplate <template <class> typename ADType, typename Type>\nstd::vector<Type> CastOutAD(const std::vector<ADType<Type>>& in)\n{\n    size_t s = in.size();\n    std::vector<Type> out(s);\n    for (size_t i = 0; i < s; ++i)\n        out[i] = CppAD::Value(in[i]);\n\n    return out;\n}", "meta": {"hexsha": "d0de4e49766cc1f3b53217121bc3a9c07075fe8c", "size": 5038, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algo_v0/utilityAD.hpp", "max_stars_repo_name": "vsamy/cdm", "max_stars_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:29.000Z", "max_issues_repo_path": "algo_v0/utilityAD.hpp", "max_issues_repo_name": "vsamy/cdm", "max_issues_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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": "algo_v0/utilityAD.hpp", "max_forks_repo_name": "vsamy/cdm", "max_forks_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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.9411764706, "max_line_length": 121, "alphanum_fraction": 0.5071456927, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5976279331166963}}
{"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 <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 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  // make sure that\n  assert(time >= time_p);\n  // integrand for the numeric integral\n  auto integrand = [=](T t_p) {\n    // translated from Maxima\n    T expo1 = std::exp(\n        boost::math::constants::half<T>() * time * time * sigma * sigma +\n        boost::math::constants::half<T>() * t_p * t_p * sigma * sigma +\n        t_p * slr_rate);\n    T expo2 = std::exp(-time / nuclear_lifetime + t_p / nuclear_lifetime -\n                       t_p * time * sigma * sigma);\n    T expo3 = std::exp(time * slr_rate);\n    return -expo2 *\n           (expo1 * std::erf(((time - t_p) * sigma * sigma - slr_rate) /\n                             boost::math::constants::root_two<T>() / sigma) -\n            expo1) /\n           (expo3 * std::erf(slr_rate / sigma /\n                             boost::math::constants::root_two<T>()) +\n            expo3);\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 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(time, pulse_length, nuclear_lifetime,\n                                           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": "da27e53369a33874bc8dbdb7bf94c8ca1ad10a5e", "size": 2939, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/slr/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": "include/triumf/bnmr/slr/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": "include/triumf/bnmr/slr/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": 34.5764705882, "max_line_length": 80, "alphanum_fraction": 0.6260632868, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5975496474940459}}
{"text": "#include \"mesh_reader.hpp\"\n#include \"newton_raphson.hpp\"\n#include \"constants.hpp\"\n\n#include <tuple>\n#include <iostream>\n#include <math.h>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_blocked.hpp>\n#include <chrono>\n\nusing namespace boost::numeric::ublas;\n\n/* Configure boost-numeric-bindings in /usr/local to be able to use the compile statement on the next line. */\n/* COMPILE WITH: g++ -Wall -std=c++14 -O3 -lstdc++ -o fem.o fem.cpp\nmesh_reader.hpp needs those two flags for reading files */\n\nclass F {\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    matrix<double> Au_;\n    matrix<double> Av_;\n    matrix<double> B_;\n    matrix<double> C_;\n    vector<double> D_;\n\n  public:\n    F(matrix<double> Au, matrix<double> Av, matrix<double> B, matrix<double> C, vector<double> D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n\n    }\n\n    vector<double> operator()(vector<double> x) {\n      /* x = [uT vT]T */\n      int n = Au_.size1();\n      vector<double> u = project(x,range(0,n));\n      vector<double> v = project(x,range(n,2*n));\n      vector<double> func(2*n);\n      project(func,range(0,n)) = prod(Au_,u) + prod(B_,Ru(u,v)) + hu*(prod(C_,u) - D_*uamb);\n      project(func,range(n,2*n)) = -prod(Av_,v) + prod(B_,Rv(u,v)) - hv*(prod(C_,v) - D_*vamb);\n      return func;\n    }\n};\n\nclass J {\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    matrix<double> Au_;\n    matrix<double> Av_;\n    matrix<double> B_;\n    matrix<double> C_;\n    vector<double> D_;\n\n  public:\n    J(matrix<double> Au, matrix<double> Av, matrix<double> B, matrix<double> C, vector<double> D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n\n    }\n\n    matrix<double> operator()(vector<double> x) {\n      /* x = [uT vT]T */\n      int n = Au_.size1();\n      vector<double> u = project(x,range(0,n));\n      vector<double> v = project(x,range(n,2*n));\n      matrix<double> JAC(2*n, 2*n);\n      project(JAC,range(0,n),range(0, n)) = Au_ + prod(B_,dRudu(u,v)) + hu*C_;\n      project(JAC,range(n,2*n),range(0,n)) = prod(B_,dRudv(u,v));\n      project(JAC,range(n,2*n),range(0,n)) = prod(B_,dRvdu(u,v));\n      project(JAC,range(n,2*n),range(n,2*n)) = -1*Av_ + prod(B_,dRvdv(u,v)) - hv*C_;\n      return JAC;\n    }\n};\n\n\n\nint main() {\n  /* Read and store mesh information */\n  auto t1 = std::chrono::high_resolution_clock::now();\n  matrix<double> vertices = mesh::read_vertices();\n  matrix<double> triangles = mesh::read_triangles(vertices);\n  matrix<int> boundaries = mesh::read_boundaries(vertices);\n  auto t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"Input data successfully read:\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate righthand side vector integrals */\n  t1 = std::chrono::high_resolution_clock::now();\n  matrix<double> init_B(vertices.size1(), vertices.size1());\n  symmetric_adaptor<matrix<double>, lower> B(init_B);\n  B = set_zero(B);\n  for (unsigned t = 0; t < triangles.size1(); ++t) {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    //std::cout << std::endl;\n    B(a, a) += area*(6.*vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    //std::cout<< B(a,a) << std::endl;\n    B(b, a) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + vertices(c, 0));\n    B(c, a) += area*(2.*vertices(a, 0) + vertices(b, 0) + 2.*vertices(c, 0));\n    B(b, b) += area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0));\n    //std::cout << \"B(b,c): \" << B(b,c) << \"deel1: \"<< area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0)) << std::endl;\n    B(b, c) += area*(vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B(c, c) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + 6.*vertices(c, 0));\n    //std::cout << B << std::endl;\n  }\n  //std::cout << \"before division: \" << B << std::endl;\n  B *= (1./60.);\n  //std::cout << \"after divison: \" << B << std::endl;\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"B matrix successfully assembled\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate first part of stiffness matrix A */\n  t1 = std::chrono::high_resolution_clock::now();\n  matrix<double> init_A_U(vertices.size1(), vertices.size1());\n  matrix<double> init_A_V(vertices.size1(), vertices.size1());\n  matrix<double> I_U(2,2);\n  matrix<double> I_V(2,2);\n  matrix<double> G(3, 2);\n  matrix<double> GGT_U(3, 3);\n  matrix<double> GGT_V(3, 3);\n  matrix<double> temp(3, 3);\n  symmetric_adaptor<matrix<double>, lower> A_U(init_A_U);\n  symmetric_adaptor<matrix<double>, lower> A_V(init_A_V);\n  I_U = set_zero(I_U);\n  I_V = set_zero(I_V);\n  A_U = set_zero(A_U);\n  A_V = set_zero(A_V);\n  I_U(0,0) = DU_R;\n  I_U(1,1) = DU_Z;\n  I_V(0,0) = DV_R;\n  I_V(1,1) = DV_Z;\n  for (unsigned t = 0; t < triangles.size1(); ++t) {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    G(0, 0) = (vertices(b, 1) - vertices(c, 1));\n    G(1, 0) = (vertices(c, 1) - vertices(a, 1));\n    G(2, 0) = (vertices(a, 1) - vertices(b, 1));\n    G(0, 1) = (vertices(c, 0) - vertices(b, 0));\n    G(1, 1) = (vertices(a, 0) - vertices(c, 0));\n    G(2, 1) = (vertices(b, 0) - vertices(a, 0));\n    temp = prod(G,I_U);\n    GGT_U = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*prod(temp, trans(G));\n    temp = prod(G,I_V);\n    GGT_V = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*prod(temp, trans(G));\n    // std::cout << \"factor: \" << (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6) << std::endl;\n    // std::cout << \"G: \" << G << std::endl;\n    // std::cout << \"temp: \" << temp << std::endl;\n    // std::cout << \"tempGT: \" << prod(temp, trans(G)) << std::endl;\n    // std::cout << \"GGT_V: \" << GGT_V << std::endl;\n    A_U(a, a) += GGT_U(0, 0);\n    A_U(b, a) += GGT_U(1, 0);\n    A_U(c, a) += GGT_U(2, 0);\n    A_U(b, b) += GGT_U(1, 1);\n    A_U(b, c) += GGT_U(1, 2);\n    A_U(c, c) += GGT_U(2, 2);\n    A_V(a, a) += GGT_V(0, 0);\n    A_V(b, a) += GGT_V(1, 0);\n    A_V(c, a) += GGT_V(2, 0);\n    A_V(b, b) += GGT_V(1, 1);\n    A_V(b, c) += GGT_V(1, 2);\n    A_V(c, c) += GGT_V(2, 2);\n  }\n\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"A matrices assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Boundary condition integrals: second part of A and a constant vector term */\n  t1 = std::chrono::high_resolution_clock::now();\n  matrix<double> init_C(vertices.size1(), vertices.size1());\n  symmetric_adaptor<matrix<double>, lower> C(init_C);\n  C = set_zero(C);\n  vector<double> D(vertices.size1());\n  D = set_zero(D);\n  // std::cout << std::endl;\n  // std::cout << std::endl;\n  // std::cout << std::endl;\n  for (unsigned b = 0; b < boundaries.size1(); ++b) {\n    double len = sqrt(pow(vertices(boundaries(b, 0), 0) - vertices(boundaries(b, 1), 0), 2) +\n      pow(vertices(boundaries(b, 0), 1) - vertices(boundaries(b, 1), 1), 2));\n    C(boundaries(b, 0), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/4 + vertices(boundaries(b, 1), 0)/12);\n    C(boundaries(b, 0), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);\n    C(boundaries(b, 1), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/4);\n    // Nakijken -> 1 vergeten\n    D(boundaries(b,0)) += len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.);\n    // std::cout << \"D(boundaries(b,0)): \" << len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.) << std::endl;\n    // std::cout << \"b: \" << b << std::endl;\n    D(boundaries(b,1)) += len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.);\n    // std::cout << \"D(boundaries(b,1)): \" << len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.) << std::endl;\n    // std::cout << \"b: \" << len << std::endl;\n  }\n  // std::cout << \"C: \"<< C << std::endl;\n  // std::cout << std::endl;\n  // std::cout << std::endl;\n  // std::cout << std::endl;\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"C matrix and D vector assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Root finding for nonlinear system of equations */\n  t1 = std::chrono::high_resolution_clock::now();\n  F F_funct(A_U, A_V, B, C, D);\n  J J_funct(A_U, A_V, B, C, D);\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"Functors are created\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n\n  std::cout << \"A_U: \" << A_U << std::endl;\n  std::cout << std::endl;\n  std::cout << \"A_V: \" << A_V << std::endl;\n  std::cout << std::endl;\n  std::cout << \"B: \" << B << std::endl;\n  std::cout << std::endl;\n  std::cout << \"C: \" << C << std::endl;\n  std::cout << std::endl;\n  std::cout << \"D: \" << D << std::endl;\n  std::cout << std::endl;\n  vector<double> guess = vector<double>(vertices.size1()*2,5.);\n  matrix<double> inverse_u_0 (vertices.size1(),vertices.size1());\n  inverse_u_0 = set_zero(inverse_u_0);\n  InvertMatrix<double>(A_U+(Vmu/Kmu)*B+hu*C, inverse_u_0);\n  std::cout << \"V/K\" << Vmu/Kmu << std::endl;\n  std::cout << std::endl;\n  std::cout << \"hu\" << hu << std::endl;\n  std::cout << std::endl;\n  vector<double> u_0 = prod(inverse_u_0, hu*D*uamb);\n\n  std::cout << std::endl;\n  std::cout << std::endl;\n  matrix<double> inverse_v_0 (vertices.size1(),vertices.size1());\n  inverse_v_0 = set_zero(inverse_v_0);\n  InvertMatrix<double>(A_V+hv*C, inverse_v_0);\n  vector<double> v_0 = prod(inverse_v_0, rq*(Vmu/Kmu)*prod(B,u_0)+hv*vamb*D);\n  std::cout << \"v_0\" << v_0 << std::endl;\n  std::cout << std::endl;\n  std::cout << \"inverse_v_0\" << inverse_v_0 << std::endl;\n  std::cout << std::endl;\n  std::cout << \"second factor\" << rq*(Vmu/Kmu)*prod(B,u_0)+hv*vamb*D << std::endl;\n  std::cout << std::endl;\n  std::cout << std::endl;\n  std::cout << \"uamb: \" << uamb << std::endl;\n  std::cout << std::endl;\n  std::cout << std::endl;\n\n\n  project(guess,range(0,vertices.size1())) = u_0;\n  project(guess,range(vertices.size1(),2*vertices.size1())) = v_0;\n  std::cout << \"Initial guess\" << guess << std::endl;\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout<< \"Initial guess calculated\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  newton_raphson(F_funct,J_funct,guess,pow(10,-15));\n  std::cout << guess << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "18c9fa6a33577d90ffc38fb66ff4607aa1b1b38c", "size": 11470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/fem.cpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/deprecated/fem.cpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/deprecated/fem.cpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3873239437, "max_line_length": 133, "alphanum_fraction": 0.5893635571, "num_tokens": 3904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5975496229110009}}
{"text": "#include <cstdio>\r\n#include <iostream>\r\n#include <vector>\r\n#include <NTL/ZZ.h>\r\n#include <NTL/tools.h>\r\n\r\nusing namespace std;\r\nusing namespace NTL;\r\n\r\n#define REPORT_INTERVAL\t100000\r\n#define MAX_Q_BITS 255\r\n\r\n/*\r\n  This code modifies [Algorithm 1, BN06] to search for candidate parameters of\r\n  Barreto-Naehrig curves with high 2-adicity. (The curve itself can be explicitly\r\n  constructed by following the second half of [Algorithm 1, BN06].)\r\n\r\n  This code was used to find the BN curve in [BCTV13].\r\n\r\n  [BCTV13] = \"Succinct Non-Interactive Arguments for a von Neumann Architecture\"\r\n  [BN06]   = \"Pairing-Friendly Elliptic Curves of Prime Order\"\r\n*/\r\n\r\nint main(int argc, char **argv)\r\n{\r\n    if (argc != 4)\r\n    {\r\n        cout << \"usage: \" << argv[0] << \" [rand_seed even_offset wanted_two_adicity]\\n\";\r\n        return 0;\r\n    }\r\n\r\n    /* Collect inputs */\r\n    ZZ seed;\r\n    conv(seed, atoi(argv[1]));\r\n    long even_offset = atoi(argv[2]);\r\n    long wanted_two_adicity = atoi(argv[3]);\r\n\r\n    /* |x| ~ 64 bits so that |q| = 4 * |x| ~ 256 bits */\r\n    long num_x_bits = 63;\r\n\r\n    long num_iters = 0;\r\n    long num_found = 0;\r\n\r\n    SetSeed(seed);\r\n    while (1)\r\n    {\r\n        ++num_iters;\r\n\r\n        /* Sample x */\r\n        ZZ x = RandomLen_ZZ(num_x_bits);\r\n\r\n        /**\r\n         * Make x even and divisible by a large power of 2 to improve two adicity.\r\n         * The resulting q is s.t. -1 is a square in Fq.\r\n         */\r\n        x = ((x >> even_offset) << even_offset);\r\n\r\n        /* Uncomment to make x odd and ensure that -1 is a nonsquare in Fq. */\r\n        // SetBit(x, 0);\r\n\r\n        /**\r\n         * Compute candidate BN parameters using the formulas:\r\n         * t = 6*x^2 + 1,\r\n         * q = 36*x^4 + 36*x^3 + 24*x^2 + 6*x + 1\r\n         * r = q - t + 1\r\n         * (see [BN06])\r\n         */\r\n        ZZ x2 = x * x;\r\n        ZZ x3 = x2 * x;\r\n        ZZ x4 = x3 * x;\r\n        ZZ t = 6 * x2 + 1;\r\n        ZZ q = 36 * x4 + 36 * x3 + 24 * x2 + 6 * x + 1;\r\n        ZZ r = q - t + 1;\r\n\r\n        long num_q_bits = NumBits(q);\r\n        long two_adicity = NumTwos(r-1);\r\n\r\n        if (num_q_bits > MAX_Q_BITS)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if (ProbPrime(r) && ProbPrime(q) && (two_adicity >= wanted_two_adicity))\r\n        {\r\n            cout << \"x = \" << x << \"\\n\";\r\n            cout << \"q = \" << q << \"\\n\";\r\n            cout << \"r = \" << r << \"\\n\";\r\n            cout << \"log2(q) =\" << num_q_bits << \"\\n\";\r\n            cout << \"ord_2(r-1) = \" << two_adicity << \"\\n\";\r\n            cout.flush();\r\n            ++num_found;\r\n        }\r\n\r\n        if (num_iters % REPORT_INTERVAL == 0)\r\n        {\r\n            printf(\"[ num_iters = %ld , num_found = %0.2f per %d ]\\n\", num_iters, 1.*REPORT_INTERVAL*num_found/num_iters, REPORT_INTERVAL);\r\n            fflush(stdout);\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "41a15893aaf9c8c76c48ba6c7cb64e07ad9b3ff1", "size": 2825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ecfactory/bn_curves/bn_curves_cpp/bn_search.cpp", "max_stars_repo_name": "weikengchen/ecfactory", "max_stars_repo_head_hexsha": "f509c00b7cf66f4b8dbe9540599a4c95b9742bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2016-06-09T13:47:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T14:06:20.000Z", "max_issues_repo_path": "ecfactory/bn_curves/bn_curves_cpp/bn_search.cpp", "max_issues_repo_name": "frevson/ecfactory-A-SageMath-Library-for-Constructing-Elliptic-Curves", "max_issues_repo_head_hexsha": "f509c00b7cf66f4b8dbe9540599a4c95b9742bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-04-26T14:15:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T09:21:37.000Z", "max_forks_repo_path": "ecfactory/bn_curves/bn_curves_cpp/bn_search.cpp", "max_forks_repo_name": "frevson/ecfactory-A-SageMath-Library-for-Constructing-Elliptic-Curves", "max_forks_repo_head_hexsha": "f509c00b7cf66f4b8dbe9540599a4c95b9742bfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2017-09-27T08:08:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T12:11:20.000Z", "avg_line_length": 27.9702970297, "max_line_length": 140, "alphanum_fraction": 0.5008849558, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.597540719586455}}
{"text": "#pragma once\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"Algorithms.hh\"\n#include \"IsPrimeGenerator.hh\"\n#include \"Typedefs.hh\"\n\nnamespace cml {\n\nstruct RsaPublicKey {\n    UnboundedInt e{ 0 };\n    UnboundedInt n{ 0 };\n};\n\nstruct RsaPrivateKey {\n    UnboundedInt d{ 0 };\n    UnboundedInt n{ 0 };\n};\n\ntemplate <typename PrimeGeneratorType>\nstruct RsaProtocol {\n    static_assert(IsPrimeGenerator<PrimeGeneratorType>::value,\n                  \"Invalid template argument for cml::RsaProtocol: PrimeGeneratorType \"\n                  \"interface is not suitable\");\n\n    using PublicKey      = RsaPublicKey;\n    using PrivateKey     = RsaPrivateKey;\n    using PrimeGenerator = PrimeGeneratorType;\n\n    RsaProtocol();\n    explicit RsaProtocol(const PrimeGenerator& primeGenerator);\n\n    void generate();\n\n    UnboundedInt encrypt(const Uint64& source, const PublicKey& anotherPublicKey);\n    std::vector<UnboundedInt> encrypt(const std::vector<Uint64>& source, const PublicKey& anotherPublicKey);\n\n    Uint64 decrypt(const UnboundedInt& source);\n    std::vector<Uint64> decrypt(const std::vector<UnboundedInt>& source);\n\n    PublicKey publicKey{};\n    PrivateKey privateKey{};\n    PrimeGenerator primeGenerator{};\n};\n\ntemplate <typename PrimeGeneratorType>\nRsaProtocol<PrimeGeneratorType>::RsaProtocol() = default;\n\ntemplate <typename PrimeGeneratorType>\nRsaProtocol<PrimeGeneratorType>::RsaProtocol(const PrimeGenerator& primeGenerator) : primeGenerator(primeGenerator)\n{}\n\ntemplate <typename PrimeGeneratorType>\nvoid RsaProtocol<PrimeGeneratorType>::generate()\n{\n    UnboundedInt p{ primeGenerator() };\n    UnboundedInt q{ primeGenerator() };\n\n    // Compute phi\n    UnboundedInt phi = (p - 1) * (q - 1);\n\n    // Compute 'n'\n    UnboundedInt n = p * q;\n    publicKey.n    = n;\n    privateKey.n   = n;\n\n    // Mersenne prime number\n    publicKey.e = 65537;\n\n    // Compute 'd'\n    privateKey.d = invmod(publicKey.e, phi);\n}\n\ntemplate <typename PrimeGeneratorType>\nUnboundedInt RsaProtocol<PrimeGeneratorType>::encrypt(const Uint64& source, const PublicKey& anotherPublicKey)\n{\n    return modexp<UnboundedInt>(UnboundedInt{ source }, anotherPublicKey.e, anotherPublicKey.n);\n}\n\ntemplate <typename PrimeGeneratorType>\nstd::vector<UnboundedInt> RsaProtocol<PrimeGeneratorType>::encrypt(const std::vector<Uint64>& source,\n                                                                   const PublicKey& anotherPublicKey)\n{\n    std::vector<UnboundedInt> result{};\n    result.resize(source.size());\n\n    for (std::size_t i = 0; i < source.size(); ++i) {\n        result[i] = encrypt(source[i], anotherPublicKey);\n    }\n\n    return result;\n}\n\ntemplate <typename PrimeGeneratorType>\nUint64 RsaProtocol<PrimeGeneratorType>::decrypt(const UnboundedInt& source)\n{\n    return static_cast<Uint64>(modexp<UnboundedInt>(source, privateKey.d, privateKey.n));\n}\n\ntemplate <typename PrimeGeneratorType>\nstd::vector<Uint64> RsaProtocol<PrimeGeneratorType>::decrypt(const std::vector<UnboundedInt>& source)\n{\n    std::vector<Uint64> result{};\n    result.resize(source.size());\n\n    for (std::size_t i = 0; i < source.size(); ++i) {\n        result[i] = decrypt(source[i]);\n    }\n\n    return result;\n}\n\n} // namespace cml", "meta": {"hexsha": "c4ad132ae0d552b121a883fda050c8f16f0814bb", "size": 3203, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/cml/RsaProtocol.hh", "max_stars_repo_name": "LazyMechanic/cml", "max_stars_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cml/RsaProtocol.hh", "max_issues_repo_name": "LazyMechanic/cml", "max_issues_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cml/RsaProtocol.hh", "max_forks_repo_name": "LazyMechanic/cml", "max_forks_repo_head_hexsha": "b99b3417d2196e741ed01256618f61c9715d252a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0964912281, "max_line_length": 115, "alphanum_fraction": 0.6974711208, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5975170399062638}}
{"text": "#include <Eigen/Dense>\r\n#include <Eigen/SVD>\r\n#include <cmath>\r\n#include \"metrics.h\"\r\n#include <iostream>\r\n\r\nusing namespace Eigen;\r\n\r\nnamespace dmaps\r\n{\r\n\tf_type rmsd(const vector_t& ri, const vector_t& rj, const vector_t& w)\r\n\t{\r\n\t\t// Copy vectors for manipulation.\r\n\t\tvector_t r1 = ri, r2 = rj;\r\n\r\n\t\t// Get subset of weights just to make sure the size is proper. \r\n\t\tconst vector_t& ws = w.segment(0, ri.size()/3);\r\n\r\n\t\t// Maps for ease of use.\r\n\t\tMap<matrix3_t> xi(r1.data(), r1.size()/3, 3);\r\n\t\tMap<matrix3_t> xj(r2.data(), r2.size()/3, 3);\r\n\r\n\t\t// Subtract out centers of mass.\r\n\t\tf_type wtot = ws.sum();\r\n\t\tvector3_t comi = (ws.asDiagonal()*xi).colwise().sum()/wtot;\r\n\t\tvector3_t comj = (ws.asDiagonal()*xj).colwise().sum()/wtot;\r\n\t\txi.rowwise() -= comi.transpose(); \r\n\t\txj.rowwise() -= comj.transpose();\r\n\r\n\t\t// SVD of covariance matrix.\r\n\t\tmatrix_t cov = xi.transpose()*ws.asDiagonal()*xj;\r\n\t\tJacobiSVD<matrix_t> svd(cov, ComputeThinU | ComputeThinV);\r\n\t\t\r\n\t\t// Find rotation. \r\n\t\tf_type d = (svd.matrixV()*svd.matrixU().transpose()).determinant() > 0 ? 1 : -1; \r\n\t\t\r\n\t\tmatrix33_t eye = matrix33_t::Identity(3, 3);\r\n\t\teye(2, 2) = d;\r\n\t\tmatrix33_t R = svd.matrixV()*eye*svd.matrixU().transpose();\r\n\t\t\r\n\t\t// Return rmsd.\r\n\t\treturn std::sqrt((ws.asDiagonal()*(xi - xj*R).array().square().matrix()).sum()/wtot);\r\n\t}\r\n\r\n\tf_type euclidean(const vector_t& ri, const vector_t& rj, const vector_t& w)\r\n\t{\r\n\t\treturn std::sqrt((w.array()*(ri-rj).array().square()).sum());\r\n\t}\r\n\r\n\tf_type contact_map(const vector_t& ri, const vector_t& rj, const vector_t&)\r\n\t{\r\n\t\tMap<const matrix3_t> xi(ri.data(), ri.size()/3, 3);\r\n\t\tMap<const matrix3_t> xj(rj.data(), rj.size()/3, 3);\r\n\r\n\t\tint irows = xi.rows(), jrows = xj.rows();\r\n\t\tvector_t dxi(irows*irows/2 - irows/2), dxj(jrows*jrows/2 - jrows/2);\r\n\t\t\r\n\t\t// Compute pairwise distances.\r\n\t\tint k = 0;\r\n\t\tfor(int i = 0; i < irows - 1; ++i)\r\n\t\t{\r\n\t\t\tint nrows = irows - i - 1;\r\n\t\t\tdxi.segment(k, nrows) = (xi.bottomRows(nrows).rowwise() - xi.row(i)).matrix().rowwise().norm();\r\n\t\t\tk += nrows;\r\n\t\t}\r\n\t\t\r\n\t\tk = 0;\r\n\t\tfor(int i = 0; i < jrows - 1; ++i)\r\n\t\t{\r\n\t\t\tint nrows = jrows - i - 1;\r\n\t\t\tdxj.segment(k, nrows) = (xj.bottomRows(nrows).rowwise() - xj.row(i)).matrix().rowwise().norm();\r\n\t\t\tk += nrows;\r\n\t\t}\r\n\t\t\r\n\t\t// Calculate distance metric normalization constants.\r\n\t\tf_type r0 = 0.35, n = 8, m = 12; \r\n\r\n\t\tdxi.array() = (1. - (dxi.array()/r0).pow(n))/(1. - (dxi.array()/r0).pow(m));\r\n\t\tdxj.array() = (1. - (dxj.array()/r0).pow(n))/(1. - (dxj.array()/r0).pow(m));\r\n\r\n\t\tf_type norm = std::sqrt(dxi.sum()*dxj.sum());\r\n\r\n\t\treturn std::sqrt(1.0/norm*(dxi - dxj).array().square().sum());\r\n\t}\r\n}", "meta": {"hexsha": "46c6052a2b69fe5febe5f3d69bfccfb9aa2b4b12", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dmaps/metrics.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/metrics.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/metrics.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.9176470588, "max_line_length": 99, "alphanum_fraction": 0.5939878234, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5974895449566487}}
{"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// Implementation File\n// Look at polynomial_basis.h for documentation\n#include <traj_opt_pro/polynomial_basis.h>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/pointer_cast.hpp>\n#include <boost/range/irange.hpp>\n\n#include <iostream>\n#include <stdexcept>\n#include <vector>\n\nnamespace traj_opt {\n\nPoly PolyCalculusPro::bernstein_polynomial(typename Poly::size_type n,\n                                           typename Poly::size_type i) {\n  std::vector<decimal_t> t_dat({0, 1});\n  Poly t(t_dat.data(), 1);  // t\n  std::vector<decimal_t> omt_dat({1, -1});\n  Poly omt(omt_dat.data(), 1);  // 1-t\n\n  Poly t_rasied_i(omt_dat.data(), 0);  // t to the ith power\n  Poly omt_rasied_ni(t_rasied_i);      // (1-t) to the (n-i)th power\n\n  for (uint c = 0; c < i; c++) t_rasied_i *= t;\n  for (uint c = 0; c < n - i; c++) omt_rasied_ni *= omt;\n\n  Poly result(t_rasied_i);\n  result *= omt_rasied_ni;\n  result *= boost::math::binomial_coefficient<decimal_t>(n, i);\n  return result;\n}\nPoly PolyCalculusPro::chebyshev_polynomial(typename Poly::size_type n) {\n  std::vector<decimal_t> omt_dat({1, -1});\n  Poly omt(omt_dat.data(), 1);  //  1 - t\n  decimal_t one = 1;\n  decimal_t zero = 0;\n\n  Poly omt_raised_k(&one, 0);  // (1-t) to the kth power\n  if (n == 0) return omt_raised_k;\n\n  Poly result(&zero, 0);\n\n  for (uint k = 0; k <= n; k++) {\n    decimal_t coeff = std::pow(-2.0, k) * decimal_t(n) / decimal_t(n + k);\n    coeff *= boost::math::binomial_coefficient<decimal_t>(n + k, 2 * k);\n    // std::cout << \"sub chevy \" << coeff*omt_raised_k << std::endl;\n    result += coeff * omt_raised_k;\n    omt_raised_k *= omt;\n  }\n\n  return result;\n}\nPoly PolyCalculusPro::shifted_legendre(typename Poly::size_type n) {\n  // shifted legensdre polynomial of order n\n  typename std::vector<decimal_t> v;\n  for (typename Poly::size_type k = 0; k <= n; k++) {\n    v.push_back(boost::math::binomial_coefficient<decimal_t>(n, k) *\n                boost::math::binomial_coefficient<decimal_t>(n + k, k) *\n                std::pow(-1.0, k + n));\n  }\n  Poly result(v.data(), n);\n  return result;\n}\n\nuint Basis::dim() { return n_p; }\n\n// // switched these constructors to use new generic one\n// BasisBundle::BasisBundle(uint n_p_, uint k_r_)\n//     : BasisBundle(LEGENDRE, n_p_, k_r_) {}\n// BasisBundle::BasisBundle(int n) : BasisBundle(BEZIER, n, 0) {}\n\nLegendreBasis::LegendreBasis(uint n_p_, uint k_r_) : StandardBasis(0) {\n  orthogonal_ = true;\n  n_p = n_p_;\n  k_r = k_r_;\n  std::vector<decimal_t> simple;\n  simple.push_back(1.0);\n  for (uint i = 0; i < k_r; i++) {\n    Poly poly(simple.data(), simple.size() - 1);\n    polys.push_back(poly);\n    simple.back() = 0.0;\n    simple.push_back(1.0);\n  }\n  // does this line break ooqp? yes it does\n  if (n_p == k_r) return;\n  for (uint p = 0; p <= n_p - k_r; p++) {\n    Poly p_cur = PolyCalculusPro::shifted_legendre(p);\n    // std::cout << \"shifted p \" << p_cur << std::endl;\n    for (uint i = 0; i < k_r; i++) {\n      p_cur = PolyCalculus::integrate(p_cur);\n    }\n    polys.push_back(p_cur);\n  }\n}\n\nBezierBasis::BezierBasis(uint n_p_) : StandardBasis(0) {\n  n_p = n_p_;  // this was commented out, why?\n  type_ = PolyType::BEZIER;\n  for (int i = 0; i <= static_cast<int>(n_p); i++)\n    polys.push_back(PolyCalculusPro::bernstein_polynomial(n_p, i));\n}\nChebyshevBasis::ChebyshevBasis(uint n_p_) : StandardBasis(0) {\n  n_p = n_p_;\n  type_ = PolyType::CHEBYSHEV;\n  std::vector<decimal_t> simple;\n  simple.push_back(1.0);\n  for (uint i = 0; i <= n_p; i++) {\n    polys.push_back(PolyCalculusPro::chebyshev_polynomial(i));\n  }\n\n  // std::cout << \"Chebyshev \"  << *this << std::endl;\n}\nEndPointBasis::EndPointBasis(uint n_p_) : StandardBasis(0) {\n  n_p = n_p_;  // this was commented out, why?\n  type_ = PolyType::ENDPOINT;\n  traj_opt::MatD coeffs = MatD::Zero(n_p_ + 1, n_p + 1);\n  for (int i = 0; i <= static_cast<int>(n_p); i++) {\n    if (i % 2 == 0) {\n      coeffs(i, i / 2) = boost::math::factorial<decimal_t>(i / 2);\n\n    } else {\n      for (int j = 0; j <= static_cast<int>(n_p - i / 2); j++) {\n        if (i < 2)\n          coeffs(i, j) = 1;\n        else\n          coeffs(i, j + i / 2) = coeffs(i - 2, j + i / 2) * (j + 1);\n      }\n    }\n  }\n  traj_opt::MatD coeffsi = coeffs.inverse();\n\n  for (int i = 0; i <= static_cast<int>(n_p); i++) {\n    std::vector<decimal_t> data;\n    for (int j = 0; j <= static_cast<int>(n_p); j++) {\n      //      data.push_back(coeffsi(i, j));\n      if (std::abs(coeffsi(j, i)) > 1e-12) data.push_back(coeffsi(j, i));\n      //            data.push_back(coeffsi(i, j));\n      else\n        data.push_back(0.0);\n    }\n    polys.push_back(Poly(data.data(), n_p));\n  }\n  //  std::cout << \"Endpoint M \" << coeffs << std::endl;\n  //  std::cout << \"Endpoint Minv \" << coeffsi << std::endl;\n  //  std::cout << \"Basis \" << *this << std::endl;\n\n  //  std::cout << \"Endpoint np \" << n_p << \" poly size \" << polys.size()\n  //  <<std::endl;\n}\n\ndecimal_t LegendreBasis::innerproduct(uint i, uint j) const {\n  if (i != j)\n    return 0;\n  else\n    return StandardBasis::innerproduct(i, j);\n}\nPoly StandardBasis::getPoly(uint i) const { return polys.at(i); }\nStandardBasis::StandardBasis(uint n) : Basis(n) {\n  type_ = PolyType::STANDARD;\n  if (n == 0) return;\n  std::vector<decimal_t> simple;\n  simple.push_back(1.0);\n  for (uint i = 0; i <= n_p; i++) {\n    Poly poly(simple.data(), simple.size() - 1);\n    polys.push_back(poly);\n    simple.back() = 0.0;\n    simple.push_back(1.0);\n  }\n}\nBasisTransformer::BasisTransformer(boost::shared_ptr<StandardBasis> from,\n                                   int derr) {\n  int n = from->dim();\n  boost::shared_ptr<StandardBasis> to = boost::make_shared<StandardBasis>(n);\n  *this = BasisTransformer(from, to, derr);\n}\nBasisTransformer::BasisTransformer(boost::shared_ptr<StandardBasis> from,\n                                   boost::shared_ptr<StandardBasis> to,\n                                   int derr)\n    : to_(to), from_(from) {\n  //  assert(to_->dim() == from_->dim());\n  n = static_cast<int>(from_->dim()) + 1;\n  A = MatD::Zero(n - derr, n);\n  //  std::cout << \"Rows \" << A.rows() << \" , \" << A.cols() << std::endl;\n  for (int i = 0; i < n - derr; i++) {\n    Poly pi = from_->getPoly(i + derr);\n    for (int j = 0; j < static_cast<int>(pi.size()); j++) {\n      //      std::cout << \"i,j \" << i << \" , \" << j << std::endl;\n      A(i, j + derr) = pi[j];\n    }\n  }\n  B = MatD::Zero(n - derr, n - derr);\n  for (int i = 0; i < n - derr; i++) {\n    Poly qi = to_->getPoly(i);\n    for (int j = 0; j < static_cast<int>(qi.size()); j++) {\n      //      std::cout << \"i,j \" << i << \" , \" << j << std::endl;\n      B(i, j) = qi[j];\n    }\n  }\n  //  Ainv = A.inverse();\n  Binv = B.inverse();\n  // draw your communitive diagram to see where these come from\n  //  basisbasis_ = Binv * A;\n  basisbasis_ = (A * Binv).transpose();\n\n  //   std::cout << \"Debug A: \" << A << std::endl;\n  //   std::cout << \"Debug B: \" << B << std::endl;\n  //   std::cout << \"Debug Ainv: \" << Ainv << std::endl;\n  //   std::cout << \"Debug Binv: \" << Binv << std::endl;\n  //   std::cout << \"BB \" << basisbasis_ << std::endl;\n}\nconst MatD &BasisTransformer::getBasisBasisTransform() {\n  //  std::cout << \"BB \" << basisbasis_ << std::endl;\n  return basisbasis_;\n}\nconst MatD &BasisTransformer::getLinearTransform(decimal_t a, decimal_t b) {\n  decimal_t data[2];\n  data[0] = b;\n  data[1] = a;  // remember boost's convention is backward from matlabs\n  Poly fac(data, 1);\n  decimal_t one = 1;\n  Poly base(&one, 0);\n  MatD mat = MatD::Zero(n, n);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < static_cast<int>(base.size()); j++) {\n      mat(i, j) = base[j];\n    }\n    base = base * fac;\n  }\n\n  //  std::cout << \"Debug mat: \" << mat << std::endl;\n  scaledtranform_ = Ainv * mat * A;  // more communitive diagrams\n  return scaledtranform_;\n}\nboost::shared_ptr<Basis> BasisBundle::getBasis(int i) {\n  if (i >= 0)\n    return derrivatives.at(i);\n  else\n    return integrals.at(-i - 1);\n}\nBasisBundlePro::BasisBundlePro(PolyType type, uint n_p_, uint k_r_) {\n  n_p = n_p_;\n  k_r = k_r_;\n  // only computer the first 4 derrivatives\n  derrivatives.reserve(10);\n  // computer the integral too, preferable use i7 to do computering\n  integrals.reserve(1);\n\n  for (auto i : boost::irange(0, 11)) {\n    boost::shared_ptr<Basis> base;\n    //    std::cout << \"np \" << n_p << std::endl;\n    //    std::cout << \"np2 \" << n_p_ << std::endl;\n\n    if (type == LEGENDRE)\n      base = boost::make_shared<LegendreBasis>(n_p, k_r);\n    else if (type == STANDARD)\n      base = boost::make_shared<StandardBasis>(n_p);\n    else if (type == BEZIER)\n      base = boost::make_shared<BezierBasis>(n_p);\n    else if (type == ENDPOINT)\n      base = boost::make_shared<EndPointBasis>(n_p);\n    else if (type == CHEBYSHEV)\n      base = boost::make_shared<ChebyshevBasis>(n_p);\n    else\n      throw std::runtime_error(\"Unknown basis type\");\n\n    if (i == 11) {\n      base->integrate();\n      integrals.push_back(base);\n    } else {\n      for (int j = 0; j < i; j++) base->differentiate();\n      derrivatives.push_back(base);\n    }\n  }\n}\n}  // namespace traj_opt\n", "meta": {"hexsha": "056d136021c92f1877f59efbb82e961ccc0686ac", "size": 9849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mobility/planner_qp/traj_opt_pro/src/polynomial_basis.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": "mobility/planner_qp/traj_opt_pro/src/polynomial_basis.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": "mobility/planner_qp/traj_opt_pro/src/polynomial_basis.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": 33.5, "max_line_length": 77, "alphanum_fraction": 0.5987409889, "num_tokens": 3176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.5973454931272775}}
{"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 <optional>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <vector>\n\nusing Mat = Eigen::MatrixXi;\n\nauto makeMat(std::vector<std::string> const &lines) {\n  Mat m(10, 10);\n  m.setZero();\n\n  for (auto i = 0; i < lines.size(); ++i) {\n    auto row = lines[i];\n    for (auto j = 0; j < row.size(); ++j) {\n      std::string val;\n      val += row[j];\n      m(i, j) = std::stoi(val);\n    }\n  }\n\n  return m;\n}\n\nauto parseFile(char const *file_name) {\n  auto file = std::ifstream(file_name);\n  std::string line;\n  std::vector<std::string> out;\n  while (std::getline(file, line)) {\n    out.push_back(line);\n  }\n\n  return makeMat(out);\n}\n\nstd::size_t absorb(Mat &m, int i, int j) {\n  if (i < 0 || i >= m.rows() || j < 0 || j >= m.cols() || m(i, j) == 0) {\n    return 0; // Don't absorb if we don't exist or already flashed\n  }\n\n  m(i, j) += 1;\n  std::size_t out = 0;\n  if (m(i, j) > 9) { // Flash\n    m(i, j) = 0;\n    out += 1; // Count our flash\n    out += absorb(m, i + 1, j);\n    out += absorb(m, i - 1, j);\n    out += absorb(m, i, j + 1);\n    out += absorb(m, i, j - 1);\n    out += absorb(m, i + 1, j + 1);\n    out += absorb(m, i - 1, j + 1);\n    out += absorb(m, i - 1, j - 1);\n    out += absorb(m, i + 1, j - 1);\n  }\n\n  return out;\n}\n\nstd::size_t step(Mat &m) {\n  // Increase energy levels by one\n  for (auto r = 0; r < m.rows(); ++r) {\n    for (auto c = 0; c < m.cols(); ++c) {\n      m(r, c) += 1;\n    }\n  }\n\n  std::size_t out = 0;\n  for (auto r = 0; r < m.rows(); ++r) {\n    for (auto c = 0; c < m.cols(); ++c) {\n      if (m(r, c) > 9) {\n        m(r, c) = 0;\n        out += 1;\n        out += absorb(m, r + 1, c);\n        out += absorb(m, r - 1, c);\n        out += absorb(m, r, c + 1);\n        out += absorb(m, r, c - 1);\n        out += absorb(m, r + 1, c + 1);\n        out += absorb(m, r - 1, c + 1);\n        out += absorb(m, r - 1, c - 1);\n        out += absorb(m, r + 1, c - 1);\n      }\n    }\n  }\n\n  return out;\n}\n\nint main(int _, char **argv) {\n  auto M = parseFile(argv[1]);\n  std::cout << \"M:\\n\" << M << \"\\n\\n\";\n\n  auto Mp1 = M;\n  std::size_t sum = 0;\n  for(auto i = 0; i < 100; ++i){\n    sum += step(Mp1);\n  }\n  fmt::print(\"Part1 score: {}\\n\", sum);\n\n  auto day = 0;\n  while(M.sum() != 0){\n    ++day;\n    step(M);\n  }\n  fmt::print(\"Part2 day: {}\\n\", day);\n}\n", "meta": {"hexsha": "f8f3d0f30268ef892deeeaaf1763382fc6929c6a", "size": 2449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/day11/day11.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/day11/day11.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/day11/day11.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": 21.2956521739, "max_line_length": 73, "alphanum_fraction": 0.4814209882, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5972547175862698}}
{"text": "/// @file\n/// Interpolation for Lie groups.\n\n#pragma once\n\n#include <Eigen/Eigenvalues>\n\n#include \"interpolate_details.hpp\"\n\nnamespace Sophus {\n\n/// This function interpolates between two Lie group elements ``foo_T_bar``\n/// and ``foo_T_baz`` with an interpolation factor of ``alpha`` in [0, 1].\n///\n/// It returns a pose ``foo_T_quiz`` with ``quiz`` being a frame between ``bar``\n/// and ``baz``. If ``alpha=0`` it returns ``foo_T_bar``. If it is 1, it returns\n/// ``foo_T_baz``.\n///\n/// (Since interpolation on Lie groups is inverse-invariant, we can equivalently\n/// think of the input arguments as being ``bar_T_foo``, ``baz_T_foo`` and the\n/// return value being ``quiz_T_foo``.)\n///\n/// Precondition: ``p`` must be in [0, 1].\n///\ntemplate <class G, class Scalar2 = typename G::Scalar>\nenable_if_t<interp_details::Traits<G>::supported, G> interpolate(\n    G const& foo_T_bar, G const& foo_T_baz, Scalar2 p = Scalar2(0.5f)) {\n  using Scalar = typename G::Scalar;\n  Scalar inter_p(p);\n  SOPHUS_ENSURE(inter_p >= Scalar(0) && inter_p <= Scalar(1),\n                \"p ({}) must in [0, 1].\", inter_p);\n  return foo_T_bar * G::exp(inter_p * (foo_T_bar.inverse() * foo_T_baz).log());\n}\n\n}  // namespace Sophus\n", "meta": {"hexsha": "c937dbd2a3f239783ca3d29f918970af8ba35569", "size": 1208, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sophus/interpolate.hpp", "max_stars_repo_name": "versatran01/Sophus", "max_stars_repo_head_hexsha": "7634d6b2b5c0225a078c7221f57693292e85e11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sophus/interpolate.hpp", "max_issues_repo_name": "versatran01/Sophus", "max_issues_repo_head_hexsha": "7634d6b2b5c0225a078c7221f57693292e85e11c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sophus/interpolate.hpp", "max_forks_repo_name": "versatran01/Sophus", "max_forks_repo_head_hexsha": "7634d6b2b5c0225a078c7221f57693292e85e11c", "max_forks_repo_licenses": ["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.5555555556, "max_line_length": 80, "alphanum_fraction": 0.6614238411, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5971303041127225}}
{"text": "// Copyright (C) 2018 Thanaphon Chavengsaksongkram <as12production@gmail.com>, He Sun <he.sun@ed.ac.uk>\n// This file is subject to the license terms in the LICENSE file\n// found in the top-level directory of this distribution.\n\n/**\n * Example-5.cpp\n * \n * This example perform Spectral Sparsification, and use Spectra to calcualte Eigenvalue of Graph Laplacians\n * \n * */\n\n#include <gSparse/gSparse.hpp>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n\nEigen::VectorXcd GetTopEigenValue(const gSparse::SparsePrecisionMatrix & M)\n{\n    std::cout << \"Calculating Eigen Value\"<<std::endl;\n    using namespace Spectra;\n    SparseGenMatProd<double> op(M);\n\n    // Construct eigen solver object, requesting the largest three eigenvalues\n    GenEigsSolver< double, LARGEST_MAGN, SparseGenMatProd<double> > eigs(&op, 3, 6);\n\n    // Initialize and compute\n    eigs.init();\n    int nconv = eigs.compute();\n\n    // Retrieve results\n    Eigen::VectorXcd evalues;\n    if(eigs.info() == SUCCESSFUL)\n        evalues = eigs.eigenvalues();\n\n    std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n    return evalues;\n}\nint main()\n{\n    // Generate 100x100 Complete Graph\n    auto graph = gSparse::Builder::buildUnitCompleteGraph(100);\n    // Creating Sparsifier Object\n    gSparse::SpectralSparsifier::ERSampling sparsifier(graph);\n    // Set Hyper-parameters\n    // Approximate the Effective Weight Resistance (Faster)\n    // C = 100 and Epsilon = 0.5\n    sparsifier.SetERPolicy(gSparse::SpectralSparsifier::APPROXIMATE_ER);\n    sparsifier.SetC(100.0);\n    sparsifier.SetEpsilon(0.5);\n    // Compute Effective Weight Resistance using ApproxER\n    sparsifier.Compute();\n    // Get a sparsified graph\n    auto sparseGraph1 = sparsifier.GetSparsifiedGraph();\n    // Set to EXACT ER\n    sparsifier.SetERPolicy(gSparse::SpectralSparsifier::EXACT_ER);\n    // Re-calcuate ER using ExactER\n    sparsifier.Compute();\n    // Get a sparsified graph\n    auto sparseGraph2 = sparsifier.GetSparsifiedGraph();\n\n    // Use Spectra to calculate top Eigen values. \n    std::cout<<\"Original Eigen Value \" <<std::endl;\n    GetTopEigenValue(graph->GetLaplacianMatrix());\n    std::cout<<\"---------------------------\"<<std::endl;\n    std::cout<<\"Top Eigen Value for ApproxER \"<<std::endl;\n    GetTopEigenValue(sparseGraph1->GetLaplacianMatrix());\n    std::cout<<\"Top Eigen Value for ApproxER - Original\"<<std::endl;\n    GetTopEigenValue(sparseGraph1->GetLaplacianMatrix() - graph->GetLaplacianMatrix());\n    std::cout<<\"---------------------------\"<<std::endl;\n    std::cout<<\"Top Eigen Value for ExactER \"<<std::endl;\n    GetTopEigenValue(sparseGraph2->GetLaplacianMatrix());\n    std::cout<<\"Top Eigen Value for ApproxER - ExactER\"<<std::endl;\n    GetTopEigenValue(sparseGraph1->GetLaplacianMatrix() - graph->GetLaplacianMatrix());\n    return 0;\n}\n", "meta": {"hexsha": "79a92b8683f68c6eb8df05bae06297a3b6c6ddd1", "size": 2920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/Example-5.cpp", "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": "Examples/Example-5.cpp", "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": "Examples/Example-5.cpp", "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": 37.4358974359, "max_line_length": 108, "alphanum_fraction": 0.6948630137, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.597130288185463}}
{"text": "/**\n * @file nested_cylinders.cc\n * @brief Compute the convergence of the nested cylinders experiment\n */\n\n#define _USE_MATH_DEFINES\n#include <annulus_triag_mesh_builder.h>\n#include <build_system_matrix.h>\n#include <lf/assemble/dofhandler.h>\n#include <lf/io/gmsh_reader.h>\n#include <lf/io/vtk_writer.h>\n#include <lf/mesh/entity.h>\n#include <lf/mesh/hybrid2d/mesh_factory.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/quad/quad.h>\n#include <mesh_function_velocity.h>\n#include <norms.h>\n#include <piecewise_const_element_matrix_provider.h>\n#include <piecewise_const_element_vector_provider.h>\n#include <solution_to_mesh_data_set.h>\n\n#include <algorithm>\n#include <boost/program_options.hpp>\n#include <cstring>\n#include <filesystem>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nusing lf::uscalfe::operator-;\n\n/**\n * @brief Solve the nested cylinders problem with zero potential at the boundary\n * @param mesh A shared pointer to the mesh on which to solve the PDE\n * @param dofh The dofhandler used for the simulation\n * @param r The radius of the inner cylinder\n * @param R The radius of the outer cylinder\n * @param omega1 The angular velocity of the inner cylinder\n * @param omega2 The angular velocity of the outer cylinder\n * @param modified_penalty If true, use the modified penalty term instead of the\n * original one\n * @returns A vector of basis function coefficients for the solution\n */\nEigen::VectorXd solveNestedCylindersZeroBC(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh,\n    const lf::assemble::DofHandler &dofh, double r, double R, double omega1,\n    double omega2, bool modified_penalty) {\n  // The volume forces are equal to zero everywhere\n  auto f = [](const Eigen::Vector2d & /*unused*/) {\n    return Eigen::Vector2d::Zero();\n  };\n  // Drive the inner and outer cylinder with omega1 and omega2\n  const double eps = 1e-10;\n  auto dirichlet_funct = [&](const lf::mesh::Entity &edge) -> Eigen::Vector2d {\n    const auto *const geom = edge.Geometry();\n    const auto vertices = geom->Global(edge.RefEl().NodeCoords());\n    if (vertices.col(0).norm() <= R + eps &&\n        vertices.col(0).norm() >= R - eps &&\n        vertices.col(1).norm() <= R + eps &&\n        vertices.col(1).norm() >= R - eps) {\n      return omega2 * R * (vertices.col(1) - vertices.col(0)).normalized();\n    }\n    if (vertices.col(0).norm() <= r + eps &&\n        vertices.col(0).norm() >= r - eps &&\n        vertices.col(1).norm() <= r + eps &&\n        vertices.col(1).norm() >= r - eps) {\n      return omega1 * r * (vertices.col(0) - vertices.col(1)).normalized();\n    }\n    return Eigen::Vector2d::Zero();\n  };\n\n  lf::mesh::utils::CodimMeshDataSet<Eigen::Vector2d> dirichlet(mesh, 1);\n  for (const auto *ep : mesh->Entities(1)) {\n    dirichlet(*ep) = dirichlet_funct(*ep);\n  }\n\n  // Asemble the LSE\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n  // Assemble the Matrix\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n  const projects::ipdg_stokes::assemble::PiecewiseConstElementMatrixProvider\n      elem_mat_provider(100, boundary, modified_penalty);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elem_mat_provider, A);\n  // Assemble the right hand side\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  const projects::ipdg_stokes::assemble::PiecewiseConstElementVectorProvider\n      elem_vec_provider(100, f, lf::quad::make_TriaQR_MidpointRule(), boundary,\n                        dirichlet);\n  lf::assemble::AssembleVectorLocally(0, dofh, elem_vec_provider, rhs);\n\n  // Enforce the no-flow boundary conditions\n  auto selector = [&](lf::base::size_type idx) -> std::pair<bool, double> {\n    const auto &entity = dofh.Entity(idx);\n    if (entity.RefEl() == lf::base::RefElType::kPoint && boundary(entity)) {\n      return {true, 0};\n    }\n    return {false, 0};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A, rhs);\n\n  // Solve the LSE using sparse LU\n  Eigen::SparseMatrix<double> As = A.makeSparse();\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(As);\n  return solver.solve(rhs);\n}\n\n/**\n * @brief Solve the nested cylinders problem with constant potential at the\n * boundary\n * @param mesh A shared pointer to the mesh on which to solve the PDE\n * @param dofh The dofhandler used for the simulation\n * @param r The radius of the inner cylinder\n * @param R The radius of the outer cylinder\n * @param omega1 The angular velocity of the inner cylinder\n * @param omega2 The angular velocity of the outer cylinder\n * @param modified_penalty If true, use the modified penalty term instead of the\n * original one\n * @returns A vector of basis function coefficients for the solution\n */\nEigen::VectorXd solveNestedCylindersNonzeroBC(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh,\n    const lf::assemble::DofHandler &dofh, double r, double R, double omega1,\n    double omega2, bool modified_penalty) {\n  // The volume forces are equal to zero everywhere\n  auto f = [](const Eigen::Vector2d & /*unused*/) {\n    return Eigen::Vector2d::Zero();\n  };\n  // Drive the inner and outer cylinder with omega1 and omega2\n  const double eps = 1e-10;\n  auto dirichlet_funct = [&](const lf::mesh::Entity &edge) -> Eigen::Vector2d {\n    const auto *const geom = edge.Geometry();\n    const auto vertices = geom->Global(edge.RefEl().NodeCoords());\n    if (vertices.col(0).norm() <= R + eps &&\n        vertices.col(0).norm() >= R - eps &&\n        vertices.col(1).norm() <= R + eps &&\n        vertices.col(1).norm() >= R - eps) {\n      return omega2 * R * (vertices.col(1) - vertices.col(0)).normalized();\n    }\n    if (vertices.col(0).norm() <= r + eps &&\n        vertices.col(0).norm() >= r - eps &&\n        vertices.col(1).norm() <= r + eps &&\n        vertices.col(1).norm() >= r - eps) {\n      return omega1 * r * (vertices.col(0) - vertices.col(1)).normalized();\n    }\n    return Eigen::Vector2d::Zero();\n  };\n\n  lf::mesh::utils::CodimMeshDataSet<Eigen::Vector2d> dirichlet(mesh, 1);\n  for (const auto *ep : mesh->Entities(1)) {\n    dirichlet(*ep) = dirichlet_funct(*ep);\n  }\n\n  // Asemble the LSE\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n  // Assemble the Matrix\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n  const projects::ipdg_stokes::assemble::PiecewiseConstElementMatrixProvider\n      elem_mat_provider(100, boundary, modified_penalty);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elem_mat_provider, A);\n  // Assemble the right hand side\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  const projects::ipdg_stokes::assemble::PiecewiseConstElementVectorProvider\n      elem_vec_provider(100, f, lf::quad::make_TriaQR_MidpointRule(), boundary,\n                        dirichlet);\n  lf::assemble::AssembleVectorLocally(0, dofh, elem_vec_provider, rhs);\n\n  // Combine the basis functions on the inside boundary to a single one\n  const lf::base::size_type M_outer = 0;\n  const lf::base::size_type M_inner = 1;\n  // Create a mapping of DOF indices to remove the afterwards unused DOFs\n  std::vector<lf::base::size_type> dofmap(dofh.NumDofs());\n  lf::base::size_type idx = 2;\n  for (lf::base::size_type dof = 0; dof < dofh.NumDofs(); ++dof) {\n    const auto &entity = dofh.Entity(dof);\n    const auto *const geom = entity.Geometry();\n    if (entity.RefEl() == lf::base::RefElType::kPoint && boundary(entity)) {\n      if (geom->Global(entity.RefEl().NodeCoords()).norm() > R - eps) {\n        dofmap[dof] = M_outer;\n      } else {\n        dofmap[dof] = M_inner;\n      }\n    } else {\n      dofmap[dof] = idx++;\n    }\n  }\n  // Apply this mapping to the triplets of the matrix\n  std::for_each(A.triplets().begin(), A.triplets().end(),\n                [&](Eigen::Triplet<double> &trip) {\n                  trip = Eigen::Triplet<double>(\n                      dofmap[trip.row()], dofmap[trip.col()], trip.value());\n                });\n  // Apply the mapping to the right hand side vector\n  Eigen::VectorXd rhs_mapped = Eigen::VectorXd::Zero(idx);\n  for (lf::base::size_type dof = 0; dof < dofh.NumDofs(); ++dof) {\n    rhs_mapped[dofmap[dof]] += rhs[dof];\n  }\n\n  // Set the potential on the outer boundary to zero\n  auto selector = [&](lf::base::size_type idx) -> std::pair<bool, double> {\n    return {idx == M_outer, 0};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A, rhs);\n\n  // Solve the LSE using sparse LU\n  Eigen::SparseMatrix<double> As_mapped = A.makeSparse().block(0, 0, idx, idx);\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(As_mapped);\n  const Eigen::VectorXd sol_mapped = solver.solve(rhs_mapped);\n\n  // Apply the inverse mapping to recovr the basis function coefficients for the\n  // original basis functions\n  Eigen::VectorXd sol = Eigen::VectorXd::Zero(dofh.NumDofs());\n  for (lf::base::size_type dof = 0; dof < dofh.NumDofs(); ++dof) {\n    sol[dof] = sol_mapped[dofmap[dof]];\n  }\n\n  return sol;\n}\n\n/**\n * @brief Concatenate objects defining an operator<<(std::ostream&)\n * @param args A variadic pack of objects implementing\n * `operator<<(std::ostream&)`\n * @returns A string with the objects concatenated\n */\ntemplate <typename... Args>\nstatic std::string concat(Args &&... args) {\n  std::ostringstream ss;\n  (ss << ... << args);\n  return ss.str();\n}\n\n/**\n * @brief outputs the L2 and DG norm errors for the nested cylinders experiment\n *\n * Three different command line arguments can be provided:\n *   - builder\n *   - files\n *   - irregular\n *\n * Providing builder as a command line argument will build the meshes with\n * #AnnulusTriagMeshBuilder. Providing files as a command line argument will use\n * uniform meshes generated by GMSH. Providing irregular as a command line\n * argument will use meshes with a sudden jump in mesh resolution.\n */\nint main(int argc, char *argv[]) {\n  const double r = 0.25;\n  const double R = 1;\n  const double omega1 = 0;\n  const double omega2 = 1;\n\n  // Parse the command line options\n  std::string mesh_selection;\n  boost::program_options::options_description desc{\"Options\"};\n  desc.add_options()(\"help,h\", \"Help Screen\")(\n      \"type\", boost::program_options::value<std::string>(&mesh_selection),\n      \"Type of mesh to use. Either 'builder', 'files' or 'irregular'\");\n  boost::program_options::positional_options_description pos_desc;\n  pos_desc.add(\"type\", 1);\n  boost::program_options::command_line_parser parser{argc, argv};\n  parser.options(desc).positional(pos_desc).allow_unregistered();\n  boost::program_options::parsed_options po = parser.run();\n  boost::program_options::variables_map vm;\n  boost::program_options::store(po, vm);\n  boost::program_options::notify(vm);\n  if (vm.count(\"help\") != 0U) {\n    std::cout << desc << std::endl;\n  }\n\n  std::vector<std::shared_ptr<lf::mesh::Mesh>> meshes;\n  if (mesh_selection == \"files\") {\n    // Read the mesh from the gmsh file\n    std::filesystem::path meshpath = __FILE__;\n    meshpath = meshpath.parent_path();\n    for (int i = 0; i <= 4; ++i) {\n      const auto meshfile = meshpath / concat(\"annulus\", std::setw(2),\n                                              std::setfill('0'), i, \".msh\");\n      std::unique_ptr<lf::mesh::MeshFactory> factory =\n          std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n      lf::io::GmshReader reader(std::move(factory), meshfile.string());\n      meshes.push_back(reader.mesh());\n    }\n  } else if (mesh_selection == \"builder\") {\n    // Build a sequence of meshes\n    for (unsigned i = 0U; i < 8U; ++i) {\n      const unsigned nx = 4U << i;\n      const double dx = 2 * M_PI * (r + R) / 2 / nx;\n      const unsigned ny = std::max(static_cast<unsigned>((R - r) / dx), 1U);\n\n      // Build the mesh\n      std::unique_ptr<lf::mesh::MeshFactory> factory =\n          std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n      projects::ipdg_stokes::mesh::AnnulusTriagMeshBuilder builder(\n          std::move(factory));\n      builder.setInnerRadius(r);\n      builder.setOuterRadius(R);\n      builder.setNumAngularCells(nx);\n      builder.setNumRadialCells(ny);\n      meshes.push_back(builder.Build());\n    }\n  } else if (mesh_selection == \"irregular\") {\n    std::filesystem::path meshpath = __FILE__;\n    const auto mesh_irregular_path =\n        meshpath.parent_path() / \"annulus_irregular.msh\";\n    const auto mesh_irregular_inverted_path =\n        meshpath.parent_path() / \"annulus_irregular_inverted.msh\";\n    std::unique_ptr<lf::mesh::MeshFactory> factory_irregular =\n        std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    std::unique_ptr<lf::mesh::MeshFactory> factory_irregular_inverted =\n        std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    lf::io::GmshReader reader_irregular(std::move(factory_irregular),\n                                        mesh_irregular_path.string());\n    lf::io::GmshReader reader_irregular_inverted(\n        std::move(factory_irregular_inverted),\n        mesh_irregular_inverted_path.string());\n    meshes.push_back(reader_irregular.mesh());\n    meshes.push_back(reader_irregular_inverted.mesh());\n  } else {\n    std::cout << desc << std::endl;\n    exit(1);\n  }\n\n  // Compute the analytic solution of the problem\n  const double C1 = 2 * (omega1 * r * r - omega2 * R * R) / (r * r - R * R);\n  const double C2 = ((omega1 - omega2) * r * r * R * R) / (R * R - r * r);\n  auto analytic_velocity = [&](const Eigen::Vector2d &x) -> Eigen::Vector2d {\n    const double radius = x.norm();\n    Eigen::Vector2d vec;\n    vec << x[1], -x[0];\n    vec.normalize();\n    return -(0.5 * C1 * radius + C2 / radius) * vec;\n  };\n  auto analytic_gradient = [&](const Eigen::Vector2d &x) -> Eigen::Matrix2d {\n    const double r2 = x.squaredNorm();\n    Eigen::Matrix2d g;\n    g << 2 * C2 * x[0] * x[1] / r2 / r2,\n        -C1 / 2 - (C2 * r2 - 2 * C2 * x[1] * x[1]) / r2 / r2,\n        C1 / 2 + (C2 * r2 - 2 * C2 * x[0] * x[0]) / r2 / r2,\n        -2 * C2 * x[0] * x[1] / r2 / r2;\n    return g;\n  };\n\n  // Solve the problem on each mesh and compute the error\n  for (const auto &mesh : meshes) {\n    lf::assemble::UniformFEDofHandler dofh(\n        mesh,\n        {{lf::base::RefEl::kPoint(), 1}, {lf::base::RefEl::kSegment(), 1}});\n    const auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n    const Eigen::VectorXd solution_zero =\n        solveNestedCylindersZeroBC(mesh, dofh, r, R, omega1, omega2, false);\n    const Eigen::VectorXd solution_nonzero =\n        solveNestedCylindersNonzeroBC(mesh, dofh, r, R, omega1, omega2, false);\n    const Eigen::VectorXd solution_zero_modified =\n        solveNestedCylindersZeroBC(mesh, dofh, r, R, omega1, omega2, true);\n    const Eigen::VectorXd solution_nonzero_modified =\n        solveNestedCylindersNonzeroBC(mesh, dofh, r, R, omega1, omega2, true);\n    // Create mesh functions for the analytic and numerical solutions\n    const auto velocity_exact =\n        lf::mesh::utils::MeshFunctionGlobal(analytic_velocity);\n    const auto grad_exact =\n        lf::mesh::utils::MeshFunctionGlobal(analytic_gradient);\n    const auto velocity_zero =\n        projects::ipdg_stokes::post_processing::MeshFunctionVelocity<double,\n                                                                     double>(\n            fe_space, solution_zero);\n    const auto velocity_nonzero =\n        projects::ipdg_stokes::post_processing::MeshFunctionVelocity<double,\n                                                                     double>(\n            fe_space, solution_nonzero);\n    const auto velocity_zero_modified =\n        projects::ipdg_stokes::post_processing::MeshFunctionVelocity<double,\n                                                                     double>(\n            fe_space, solution_zero_modified);\n    const auto velocity_nonzero_modified =\n        projects::ipdg_stokes::post_processing::MeshFunctionVelocity<double,\n                                                                     double>(\n            fe_space, solution_nonzero_modified);\n    // Store the solution\n    lf::io::VtkWriter writer_zero(\n        mesh, concat(\"result_zero_\", dofh.NumDofs(), \".vtk\"));\n    lf::io::VtkWriter writer_nonzero(\n        mesh, concat(\"result_nonzero_\", dofh.NumDofs(), \".vtk\"));\n    writer_zero.WriteCellData(\"velocity\", velocity_zero);\n    writer_zero.WriteCellData(\"velocity_modified\", velocity_zero_modified);\n    writer_nonzero.WriteCellData(\"velocity\", velocity_nonzero);\n    writer_nonzero.WriteCellData(\"velocity_modified\",\n                                 velocity_nonzero_modified);\n    writer_zero.WriteCellData(\n        \"analytic\", lf::mesh::utils::MeshFunctionGlobal(analytic_velocity));\n    writer_nonzero.WriteCellData(\n        \"analytic\", lf::mesh::utils::MeshFunctionGlobal(analytic_velocity));\n    // Compute the difference between the numerical and the analytical solution\n    auto diff_velocity_zero = velocity_zero - velocity_exact;\n    auto diff_velocity_zero_modified = velocity_zero_modified - velocity_exact;\n    auto diff_velocity_nonzero = velocity_nonzero - velocity_exact;\n    auto diff_velocity_nonzero_modified =\n        velocity_nonzero_modified - velocity_exact;\n    auto diff_gradient_zero = -grad_exact;\n    auto diff_gradient_zero_modified = -grad_exact;\n    auto diff_gradient_nonzero = -grad_exact;\n    auto diff_gradient_nonzero_modified = -grad_exact;\n    const auto qr_provider = [](const lf::mesh::Entity &e) {\n      return lf::quad::make_QuadRule(e.RefEl(), 0);\n    };\n    const double L2_zero = projects::ipdg_stokes::post_processing::L2norm(\n        mesh, diff_velocity_zero, qr_provider);\n    const double L2_nonzero = projects::ipdg_stokes::post_processing::L2norm(\n        mesh, diff_velocity_nonzero, qr_provider);\n    ;\n    const double DG_zero = projects::ipdg_stokes::post_processing::DGnorm(\n        mesh, diff_velocity_zero, diff_gradient_zero, qr_provider);\n    const double DG_nonzero = projects::ipdg_stokes::post_processing::DGnorm(\n        mesh, diff_velocity_nonzero, diff_gradient_nonzero, qr_provider);\n    const double L2_zero_modified =\n        projects::ipdg_stokes::post_processing::L2norm(\n            mesh, diff_velocity_zero_modified, qr_provider);\n    const double L2_nonzero_modified =\n        projects::ipdg_stokes::post_processing::L2norm(\n            mesh, diff_velocity_nonzero_modified, qr_provider);\n    const double DG_zero_modified =\n        projects::ipdg_stokes::post_processing::DGnorm(\n            mesh, diff_velocity_zero_modified, diff_gradient_zero_modified,\n            qr_provider);\n    const double DG_nonzero_modified =\n        projects::ipdg_stokes::post_processing::DGnorm(\n            mesh, diff_velocity_nonzero_modified,\n            diff_gradient_nonzero_modified, qr_provider);\n    std::cout << mesh->NumEntities(2) << ' ' << L2_zero << ' ' << DG_zero << ' '\n              << L2_nonzero << ' ' << DG_nonzero << ' ' << L2_zero_modified\n              << ' ' << DG_zero_modified << ' ' << L2_nonzero_modified << ' '\n              << DG_nonzero_modified << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "14ff5adf93fb80556863b057e1d12e0c9ebe78e7", "size": 18969, "ext": "cc", "lang": "C++", "max_stars_repo_path": "projects/ipdg_stokes/examples/nested_cylinders/nested_cylinders.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "projects/ipdg_stokes/examples/nested_cylinders/nested_cylinders.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "projects/ipdg_stokes/examples/nested_cylinders/nested_cylinders.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 43.3082191781, "max_line_length": 80, "alphanum_fraction": 0.6615003427, "num_tokens": 4934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5971022810031179}}
{"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/**\n * @file odeint.cpp ODE numerical integration example.\n */\n\n#include <boost/numeric/odeint.hpp>\n\n#include <matplot/matplot.h>\n\n#include \"smooth/bundle.hpp\"\n#include \"smooth/compat/odeint.hpp\"\n#include \"smooth/so3.hpp\"\n#include \"smooth/tn.hpp\"\n\n#include \"plot_tools.hpp\"\n\nusing matplot::plot;\nusing std::views::transform;\n\n/**\n * @brief Numerically solve the following ODE on \\f$ \\mathbb{SO}(3) \\times \\mathbb{R}^3 \\f$:\n *\n * \\f[\n * \\mathrm{d}^r X_t = v(t)  \\\\\n * \\mathrm{d}^r v_t = -k_p * (X(t) \\ominus X_{des}(t)) - k_d * v(t)\n * \\f]\n */\nint main(int argc, char const * argv[])\n{\n  using state_t = smooth::Bundle<smooth::SO3d, Eigen::Vector3d>;\n  using deriv_t = typename state_t::Tangent;\n\n  std::srand(5);\n\n  // equilibrium point\n  const smooth::SO3d Xdes = smooth::SO3d::Identity();\n\n  // \"control\" proportional and derivative gains\n  constexpr double kp = 1;\n  constexpr double kd = 1;\n\n  auto ode = [&](const state_t & state, deriv_t & deriv, double t) {\n    deriv.template head<3>() = state.part<1>();\n    deriv.template tail<3>() = -kp * (state.part<0>() - Xdes) - kd * state.part<1>();\n  };\n\n  state_t state;\n  state.part<0>() = smooth::SO3d(Eigen::Quaterniond(0, 0.8, 0, 0.1));\n  state.part<1>() = Eigen::Vector3d(0, 0, 2);\n\n  std::vector<double> tvec;\n  std::vector<state_t> gvec;\n\n  auto stepper = boost::numeric::odeint::\n    runge_kutta4<state_t, double, deriv_t, double, boost::numeric::odeint::vector_space_algebra>();\n\n  boost::numeric::odeint::integrate_const(\n    stepper, ode, state, 0., 10., 0.01, [&tvec, &gvec](const state_t & s, double t) {\n      tvec.push_back(t);\n      gvec.push_back(s);\n    });\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  // plot a sphere\n  auto phi = matplot::linspace(0, 2 * M_PI, 200);\n  for (double h = -0.9; h < 0.95; h += 0.2) {\n    auto xsph = r2v(phi | transform([&](double p) { return std::sqrt(1. - h * h) * std::cos(p); }));\n    auto ysph = r2v(phi | transform([&](double p) { return std::sqrt(1. - h * h) * std::sin(p); }));\n    auto zsph = r2v(phi | transform([&](double p) { return h; }));\n    matplot::plot3(xsph, ysph, zsph)->line_width(0.25).color(\"gray\");\n    matplot::plot3(ysph, zsph, xsph)->line_width(0.25).color(\"gray\");\n    matplot::plot3(zsph, xsph, ysph)->line_width(0.25).color(\"gray\");\n  }\n  // plot the trajectory\n  auto xyz =\n    gvec | transform([](auto s) { return s.template part<0>() * Eigen::Vector3d::UnitZ(); });\n  matplot::plot3(r2v(xyz | transform([](auto s) { return s.x(); })),\n    r2v(xyz | transform([](auto s) { return s.y(); })),\n    r2v(xyz | transform([](auto s) { return s.z(); })))\n    ->line_width(4)\n    .color(\"blue\");\n  matplot::title(\"Attitude\");\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  plot(tvec, r2v(gvec | transform([](auto s) { return s.template part<1>()[0]; })), \"r\")\n    ->line_width(2);\n  plot(tvec, r2v(gvec | transform([](auto s) { return s.template part<1>()[1]; })), \"g\")\n    ->line_width(2);\n  plot(tvec, r2v(gvec | transform([](auto s) { return s.template part<1>()[2]; })), \"b\")\n    ->line_width(2);\n  matplot::title(\"Velocity\");\n\n  matplot::show();\n\n  return 0;\n}\n", "meta": {"hexsha": "a127f9dae6c53ecda888b74ef725a0d48c2d0667", "size": 4369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/odeint.cpp", "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": "examples/odeint.cpp", "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": "examples/odeint.cpp", "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.5203252033, "max_line_length": 100, "alphanum_fraction": 0.6520943008, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5971022780984445}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl\n Copyright (C) 2004 Ferdinando Ametrano\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 set up a Term Structure and then price a simple\n    swap.\n*/\n\n#include <ql/qldefines.hpp>\n#ifdef BOOST_MSVC\n#  include <ql/auto_link.hpp>\n#endif\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/yield/ratehelpers.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/indexes/ibor/euribor.hpp>\n#include <ql/time/imm.hpp>\n#include <ql/time/calendars/target.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/time/daycounters/thirty360.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <boost/timer.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\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 settlementDate(22, September, 2004);\n        // must be a business day\n        settlementDate = calendar.adjust(settlementDate);\n\n        Integer fixingDays = 2;\n        Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);\n        // nothing to do with Date::todaysDate\n        Settings::instance().evaluationDate() = todaysDate;\n\n\n        todaysDate = Settings::instance().evaluationDate();\n        std::cout << \"Today: \" << todaysDate.weekday()\n                  << \", \" << todaysDate << std::endl;\n\n        std::cout << \"Settlement date: \" << settlementDate.weekday()\n                  << \", \" << settlementDate << std::endl;\n\n        // deposits\n        Rate d1wQuote=0.0382;\n        Rate d1mQuote=0.0372;\n        Rate d3mQuote=0.0363;\n        Rate d6mQuote=0.0353;\n        Rate d9mQuote=0.0348;\n        Rate d1yQuote=0.0345;\n        // FRAs\n        Rate fra3x6Quote=0.037125;\n        Rate fra6x9Quote=0.037125;\n        Rate fra6x12Quote=0.037125;\n        // futures\n        Real fut1Quote=96.2875;\n        Real fut2Quote=96.7875;\n        Real fut3Quote=96.9875;\n        Real fut4Quote=96.6875;\n        Real fut5Quote=96.4875;\n        Real fut6Quote=96.3875;\n        Real fut7Quote=96.2875;\n        Real fut8Quote=96.0875;\n        // swaps\n        Rate s2yQuote=0.037125;\n        Rate s3yQuote=0.0398;\n        Rate s5yQuote=0.0443;\n        Rate s10yQuote=0.05165;\n        Rate s15yQuote=0.055175;\n\n\n        /********************\n         ***    QUOTES    ***\n         ********************/\n\n        // SimpleQuote stores a value which can be manually changed;\n        // other Quote subclasses could read the value from a database\n        // or some kind of data feed.\n\n        // deposits\n        boost::shared_ptr<Quote> d1wRate(new SimpleQuote(d1wQuote));\n        boost::shared_ptr<Quote> d1mRate(new SimpleQuote(d1mQuote));\n        boost::shared_ptr<Quote> d3mRate(new SimpleQuote(d3mQuote));\n        boost::shared_ptr<Quote> d6mRate(new SimpleQuote(d6mQuote));\n        boost::shared_ptr<Quote> d9mRate(new SimpleQuote(d9mQuote));\n        boost::shared_ptr<Quote> d1yRate(new SimpleQuote(d1yQuote));\n        // FRAs\n        boost::shared_ptr<Quote> fra3x6Rate(new SimpleQuote(fra3x6Quote));\n        boost::shared_ptr<Quote> fra6x9Rate(new SimpleQuote(fra6x9Quote));\n        boost::shared_ptr<Quote> fra6x12Rate(new SimpleQuote(fra6x12Quote));\n        // futures\n        boost::shared_ptr<Quote> fut1Price(new SimpleQuote(fut1Quote));\n        boost::shared_ptr<Quote> fut2Price(new SimpleQuote(fut2Quote));\n        boost::shared_ptr<Quote> fut3Price(new SimpleQuote(fut3Quote));\n        boost::shared_ptr<Quote> fut4Price(new SimpleQuote(fut4Quote));\n        boost::shared_ptr<Quote> fut5Price(new SimpleQuote(fut5Quote));\n        boost::shared_ptr<Quote> fut6Price(new SimpleQuote(fut6Quote));\n        boost::shared_ptr<Quote> fut7Price(new SimpleQuote(fut7Quote));\n        boost::shared_ptr<Quote> fut8Price(new SimpleQuote(fut8Quote));\n        // swaps\n        boost::shared_ptr<Quote> s2yRate(new SimpleQuote(s2yQuote));\n        boost::shared_ptr<Quote> s3yRate(new SimpleQuote(s3yQuote));\n        boost::shared_ptr<Quote> s5yRate(new SimpleQuote(s5yQuote));\n        boost::shared_ptr<Quote> s10yRate(new SimpleQuote(s10yQuote));\n        boost::shared_ptr<Quote> s15yRate(new SimpleQuote(s15yQuote));\n\n\n        /*********************\n         ***  RATE HELPERS ***\n         *********************/\n\n        // RateHelpers are built from the above quotes together with\n        // other instrument dependant infos.  Quotes are passed in\n        // relinkable handles which could be relinked to some other\n        // data source later.\n\n        // deposits\n        DayCounter depositDayCounter = Actual360();\n\n        boost::shared_ptr<RateHelper> d1w(new DepositRateHelper(\n            Handle<Quote>(d1wRate),\n            1*Weeks, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> d1m(new DepositRateHelper(\n            Handle<Quote>(d1mRate),\n            1*Months, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> d3m(new DepositRateHelper(\n            Handle<Quote>(d3mRate),\n            3*Months, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> d6m(new DepositRateHelper(\n            Handle<Quote>(d6mRate),\n            6*Months, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> d9m(new DepositRateHelper(\n            Handle<Quote>(d9mRate),\n            9*Months, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> d1y(new DepositRateHelper(\n            Handle<Quote>(d1yRate),\n            1*Years, fixingDays,\n            calendar, ModifiedFollowing,\n            true, depositDayCounter));\n\n\n        // setup FRAs\n        boost::shared_ptr<RateHelper> fra3x6(new FraRateHelper(\n            Handle<Quote>(fra3x6Rate),\n            3, 6, fixingDays, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> fra6x9(new FraRateHelper(\n            Handle<Quote>(fra6x9Rate),\n            6, 9, fixingDays, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        boost::shared_ptr<RateHelper> fra6x12(new FraRateHelper(\n            Handle<Quote>(fra6x12Rate),\n            6, 12, fixingDays, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n\n\n        // setup futures\n        // Rate convexityAdjustment = 0.0;\n        Integer futMonths = 3;\n        Date imm = IMM::nextDate(settlementDate);\n        boost::shared_ptr<RateHelper> fut1(new FuturesRateHelper(\n            Handle<Quote>(fut1Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut2(new FuturesRateHelper(\n            Handle<Quote>(fut2Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut3(new FuturesRateHelper(\n            Handle<Quote>(fut3Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut4(new FuturesRateHelper(\n            Handle<Quote>(fut4Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut5(new FuturesRateHelper(\n            Handle<Quote>(fut5Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut6(new FuturesRateHelper(\n            Handle<Quote>(fut6Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut7(new FuturesRateHelper(\n            Handle<Quote>(fut7Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n        imm = IMM::nextDate(imm+1);\n        boost::shared_ptr<RateHelper> fut8(new FuturesRateHelper(\n            Handle<Quote>(fut8Price),\n            imm,\n            futMonths, calendar, ModifiedFollowing,\n            true, depositDayCounter));\n\n\n        // setup swaps\n        Frequency swFixedLegFrequency = Annual;\n        BusinessDayConvention swFixedLegConvention = Unadjusted;\n        DayCounter swFixedLegDayCounter = Thirty360(Thirty360::European);\n        boost::shared_ptr<IborIndex> swFloatingLegIndex(new Euribor6M);\n\n        boost::shared_ptr<RateHelper> s2y(new SwapRateHelper(\n            Handle<Quote>(s2yRate), 2*Years,\n            calendar, swFixedLegFrequency,\n            swFixedLegConvention, swFixedLegDayCounter,\n            swFloatingLegIndex));\n        boost::shared_ptr<RateHelper> s3y(new SwapRateHelper(\n            Handle<Quote>(s3yRate), 3*Years,\n            calendar, swFixedLegFrequency,\n            swFixedLegConvention, swFixedLegDayCounter,\n            swFloatingLegIndex));\n        boost::shared_ptr<RateHelper> s5y(new SwapRateHelper(\n            Handle<Quote>(s5yRate), 5*Years,\n            calendar, swFixedLegFrequency,\n            swFixedLegConvention, swFixedLegDayCounter,\n            swFloatingLegIndex));\n        boost::shared_ptr<RateHelper> s10y(new SwapRateHelper(\n            Handle<Quote>(s10yRate), 10*Years,\n            calendar, swFixedLegFrequency,\n            swFixedLegConvention, swFixedLegDayCounter,\n            swFloatingLegIndex));\n        boost::shared_ptr<RateHelper> s15y(new SwapRateHelper(\n            Handle<Quote>(s15yRate), 15*Years,\n            calendar, swFixedLegFrequency,\n            swFixedLegConvention, swFixedLegDayCounter,\n            swFloatingLegIndex));\n\n\n        /*********************\n         **  CURVE BUILDING **\n         *********************/\n\n        // Any DayCounter would be fine.\n        // ActualActual::ISDA ensures that 30 years is 30.0\n        DayCounter termStructureDayCounter =\n            ActualActual(ActualActual::ISDA);\n\n\n        double tolerance = 1.0e-15;\n\n        // A depo-swap curve\n        std::vector<boost::shared_ptr<RateHelper> > depoSwapInstruments;\n        depoSwapInstruments.push_back(d1w);\n        depoSwapInstruments.push_back(d1m);\n        depoSwapInstruments.push_back(d3m);\n        depoSwapInstruments.push_back(d6m);\n        depoSwapInstruments.push_back(d9m);\n        depoSwapInstruments.push_back(d1y);\n        depoSwapInstruments.push_back(s2y);\n        depoSwapInstruments.push_back(s3y);\n        depoSwapInstruments.push_back(s5y);\n        depoSwapInstruments.push_back(s10y);\n        depoSwapInstruments.push_back(s15y);\n        boost::shared_ptr<YieldTermStructure> depoSwapTermStructure(\n            new PiecewiseYieldCurve<Discount,LogLinear>(\n                                          settlementDate, depoSwapInstruments,\n                                          termStructureDayCounter,\n                                          tolerance));\n\n\n        // A depo-futures-swap curve\n        std::vector<boost::shared_ptr<RateHelper> > depoFutSwapInstruments;\n        depoFutSwapInstruments.push_back(d1w);\n        depoFutSwapInstruments.push_back(d1m);\n        depoFutSwapInstruments.push_back(fut1);\n        depoFutSwapInstruments.push_back(fut2);\n        depoFutSwapInstruments.push_back(fut3);\n        depoFutSwapInstruments.push_back(fut4);\n        depoFutSwapInstruments.push_back(fut5);\n        depoFutSwapInstruments.push_back(fut6);\n        depoFutSwapInstruments.push_back(fut7);\n        depoFutSwapInstruments.push_back(fut8);\n        depoFutSwapInstruments.push_back(s3y);\n        depoFutSwapInstruments.push_back(s5y);\n        depoFutSwapInstruments.push_back(s10y);\n        depoFutSwapInstruments.push_back(s15y);\n        boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(\n            new PiecewiseYieldCurve<Discount,LogLinear>(\n                                       settlementDate, depoFutSwapInstruments,\n                                       termStructureDayCounter,\n                                       tolerance));\n\n\n        // A depo-FRA-swap curve\n        std::vector<boost::shared_ptr<RateHelper> > depoFRASwapInstruments;\n        depoFRASwapInstruments.push_back(d1w);\n        depoFRASwapInstruments.push_back(d1m);\n        depoFRASwapInstruments.push_back(d3m);\n        depoFRASwapInstruments.push_back(fra3x6);\n        depoFRASwapInstruments.push_back(fra6x9);\n        depoFRASwapInstruments.push_back(fra6x12);\n        depoFRASwapInstruments.push_back(s2y);\n        depoFRASwapInstruments.push_back(s3y);\n        depoFRASwapInstruments.push_back(s5y);\n        depoFRASwapInstruments.push_back(s10y);\n        depoFRASwapInstruments.push_back(s15y);\n        boost::shared_ptr<YieldTermStructure> depoFRASwapTermStructure(\n            new PiecewiseYieldCurve<Discount,LogLinear>(\n                                       settlementDate, depoFRASwapInstruments,\n                                       termStructureDayCounter,\n                                       tolerance));\n\n\n        // Term structures that will be used for pricing:\n        // the one used for discounting cash flows\n        RelinkableHandle<YieldTermStructure> discountingTermStructure;\n        // the one used for forward rate forecasting\n        RelinkableHandle<YieldTermStructure> forecastingTermStructure;\n\n\n        /*********************\n        * SWAPS TO BE PRICED *\n        **********************/\n\n        // constant nominal 1,000,000 Euro\n        Real nominal = 1000000.0;\n        // fixed leg\n        Frequency fixedLegFrequency = Annual;\n        BusinessDayConvention fixedLegConvention = Unadjusted;\n        BusinessDayConvention floatingLegConvention = ModifiedFollowing;\n        DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);\n        Rate fixedRate = 0.04;\n        DayCounter floatingLegDayCounter = Actual360();\n\n        // floating leg\n        Frequency floatingLegFrequency = Semiannual;\n        boost::shared_ptr<IborIndex> euriborIndex(\n                                     new Euribor6M(forecastingTermStructure));\n        Spread spread = 0.0;\n\n        Integer lenghtInYears = 5;\n        VanillaSwap::Type swapType = VanillaSwap::Payer;\n\n        Date maturity = settlementDate + lenghtInYears*Years;\n        Schedule fixedSchedule(settlementDate, maturity,\n                               Period(fixedLegFrequency),\n                               calendar, fixedLegConvention,\n                               fixedLegConvention,\n                               DateGeneration::Forward, false);\n        Schedule floatSchedule(settlementDate, maturity,\n                               Period(floatingLegFrequency),\n                               calendar, floatingLegConvention,\n                               floatingLegConvention,\n                               DateGeneration::Forward, false);\n        VanillaSwap spot5YearSwap(swapType, nominal,\n            fixedSchedule, fixedRate, fixedLegDayCounter,\n            floatSchedule, euriborIndex, spread,\n            floatingLegDayCounter);\n\n        Date fwdStart = calendar.advance(settlementDate, 1, Years);\n        Date fwdMaturity = fwdStart + lenghtInYears*Years;\n        Schedule fwdFixedSchedule(fwdStart, fwdMaturity,\n                                  Period(fixedLegFrequency),\n                                  calendar, fixedLegConvention,\n                                  fixedLegConvention,\n                                  DateGeneration::Forward, false);\n        Schedule fwdFloatSchedule(fwdStart, fwdMaturity,\n                                  Period(floatingLegFrequency),\n                                  calendar, floatingLegConvention,\n                                  floatingLegConvention,\n                                  DateGeneration::Forward, false);\n        VanillaSwap oneYearForward5YearSwap(swapType, nominal,\n            fwdFixedSchedule, fixedRate, fixedLegDayCounter,\n            fwdFloatSchedule, euriborIndex, spread,\n            floatingLegDayCounter);\n\n\n        /***************\n        * SWAP PRICING *\n        ****************/\n\n        // utilities for reporting\n        std::vector<std::string> headers(4);\n        headers[0] = \"term structure\";\n        headers[1] = \"net present value\";\n        headers[2] = \"fair spread\";\n        headers[3] = \"fair fixed rate\";\n        std::string separator = \" | \";\n        Size width = headers[0].size() + separator.size()\n                   + headers[1].size() + separator.size()\n                   + headers[2].size() + separator.size()\n                   + headers[3].size() + separator.size() - 1;\n        std::string rule(width, '-'), dblrule(width, '=');\n        std::string tab(8, ' ');\n\n        // calculations\n        std::cout << dblrule << std::endl;\n        std::cout <<  \"5-year market swap-rate = \"\n                  << std::setprecision(2) << io::rate(s5yRate->value())\n                  << std::endl;\n        std::cout << dblrule << std::endl;\n\n        std::cout << tab << \"5-years swap paying \"\n                  << io::rate(fixedRate) << std::endl;\n        std::cout << headers[0] << separator\n                  << headers[1] << separator\n                  << headers[2] << separator\n                  << headers[3] << separator << std::endl;\n        std::cout << rule << std::endl;\n\n        Real NPV;\n        Rate fairRate;\n        Spread fairSpread;\n\n        boost::shared_ptr<PricingEngine> swapEngine(\n                         new DiscountingSwapEngine(discountingTermStructure));\n\n        spot5YearSwap.setPricingEngine(swapEngine);\n        oneYearForward5YearSwap.setPricingEngine(swapEngine);\n\n        // Of course, you're not forced to really use different curves\n        forecastingTermStructure.linkTo(depoSwapTermStructure);\n        discountingTermStructure.linkTo(depoSwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        // let's check that the 5 years swap has been correctly re-priced\n        QL_REQUIRE(std::fabs(fairRate-s5yQuote)<1e-8,\n                   \"5-years swap mispriced by \"\n                   << io::rate(std::fabs(fairRate-s5yQuote)));\n\n\n        forecastingTermStructure.linkTo(depoFutSwapTermStructure);\n        discountingTermStructure.linkTo(depoFutSwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-fut-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n        QL_REQUIRE(std::fabs(fairRate-s5yQuote)<1e-8,\n                   \"5-years swap mispriced!\");\n\n\n        forecastingTermStructure.linkTo(depoFRASwapTermStructure);\n        discountingTermStructure.linkTo(depoFRASwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-FRA-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n        QL_REQUIRE(std::fabs(fairRate-s5yQuote)<1e-8,\n                   \"5-years swap mispriced!\");\n\n\n        std::cout << rule << std::endl;\n\n        // now let's price the 1Y forward 5Y swap\n\n        std::cout << tab << \"5-years, 1-year forward swap paying \"\n                  << io::rate(fixedRate) << std::endl;\n        std::cout << headers[0] << separator\n                  << headers[1] << separator\n                  << headers[2] << separator\n                  << headers[3] << separator << std::endl;\n        std::cout << rule << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoSwapTermStructure);\n        discountingTermStructure.linkTo(depoSwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoFutSwapTermStructure);\n        discountingTermStructure.linkTo(depoFutSwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-fut-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoFRASwapTermStructure);\n        discountingTermStructure.linkTo(depoFRASwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-FRA-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        // now let's say that the 5-years swap rate goes up to 4.60%.\n        // A smarter market element--say, connected to a data source-- would\n        // notice the change itself. Since we're using SimpleQuotes,\n        // we'll have to change the value manually--which forces us to\n        // downcast the handle and use the SimpleQuote\n        // interface. In any case, the point here is that a change in the\n        // value contained in the Quote triggers a new bootstrapping\n        // of the curve and a repricing of the swap.\n\n        boost::shared_ptr<SimpleQuote> fiveYearsRate =\n            boost::dynamic_pointer_cast<SimpleQuote>(s5yRate);\n        fiveYearsRate->setValue(0.0460);\n\n        std::cout << dblrule << std::endl;\n        std::cout <<  \"5-year market swap-rate = \"\n                  << io::rate(s5yRate->value()) << std::endl;\n        std::cout << dblrule << std::endl;\n\n        std::cout << tab << \"5-years swap paying \"\n                  << io::rate(fixedRate) << std::endl;\n        std::cout << headers[0] << separator\n                  << headers[1] << separator\n                  << headers[2] << separator\n                  << headers[3] << separator << std::endl;\n        std::cout << rule << std::endl;\n\n        // now get the updated results\n        forecastingTermStructure.linkTo(depoSwapTermStructure);\n        discountingTermStructure.linkTo(depoSwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n        QL_REQUIRE(std::fabs(fairRate-s5yRate->value())<1e-8,\n                   \"5-years swap mispriced!\");\n\n\n        forecastingTermStructure.linkTo(depoFutSwapTermStructure);\n        discountingTermStructure.linkTo(depoFutSwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-fut-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n        QL_REQUIRE(std::fabs(fairRate-s5yRate->value())<1e-8,\n                   \"5-years swap mispriced!\");\n\n\n        forecastingTermStructure.linkTo(depoFRASwapTermStructure);\n        discountingTermStructure.linkTo(depoFRASwapTermStructure);\n\n        NPV = spot5YearSwap.NPV();\n        fairSpread = spot5YearSwap.fairSpread();\n        fairRate = spot5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-FRA-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n        QL_REQUIRE(std::fabs(fairRate-s5yRate->value())<1e-8,\n                   \"5-years swap mispriced!\");\n\n        std::cout << rule << std::endl;\n\n        // the 1Y forward 5Y swap changes as well\n\n        std::cout << tab << \"5-years, 1-year forward swap paying \"\n                  << io::rate(fixedRate) << std::endl;\n        std::cout << headers[0] << separator\n                  << headers[1] << separator\n                  << headers[2] << separator\n                  << headers[3] << separator << std::endl;\n        std::cout << rule << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoSwapTermStructure);\n        discountingTermStructure.linkTo(depoSwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoFutSwapTermStructure);\n        discountingTermStructure.linkTo(depoFutSwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-fut-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\n\n\n        forecastingTermStructure.linkTo(depoFRASwapTermStructure);\n        discountingTermStructure.linkTo(depoFRASwapTermStructure);\n\n        NPV = oneYearForward5YearSwap.NPV();\n        fairSpread = oneYearForward5YearSwap.fairSpread();\n        fairRate = oneYearForward5YearSwap.fairRate();\n\n        std::cout << std::setw(headers[0].size())\n                  << \"depo-FRA-swap\" << separator;\n        std::cout << std::setw(headers[1].size())\n                  << std::fixed << std::setprecision(2) << NPV << separator;\n        std::cout << std::setw(headers[2].size())\n                  << io::rate(fairSpread) << separator;\n        std::cout << std::setw(headers[3].size())\n                  << io::rate(fairRate) << separator;\n        std::cout << std::endl;\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        std::cerr << e.what() << std::endl;\n        return 1;\n    } catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "c6da3eea78cca7281329b09e6e662ee346fa71c6", "size": 31810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/Swap/swapvaluation.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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/Swap/swapvaluation.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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/Swap/swapvaluation.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3680203046, "max_line_length": 79, "alphanum_fraction": 0.5857277586, "num_tokens": 7705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5970977614997854}}
{"text": "#include \"cpca.hpp\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <Eigen/SVD>\n#include <chrono>\n#include <cmath>\n#include <iostream>\n#include <utility>\n\nCPCA::CPCA(Eigen::Index const nComponents, bool const standardize)\n    : nComponents_(nComponents), standardize_(standardize) {\n  initialize();\n}\n\nvoid CPCA::initialize() { components_.resize(0, 0); }\n\nEigen::MatrixXf\nCPCA::fitTransform(Eigen::MatrixXf const &fg, Eigen::MatrixXf const &bg,\n                   bool const autoAlphaSelection, float const alpha,\n                   float const eta, float const convergenceRatio,\n                   unsigned int maxIter, bool const keepReports) {\n  fit(fg, bg, autoAlphaSelection, alpha, eta, convergenceRatio, maxIter,\n      keepReports);\n  return transform(fg_);\n}\n\nvoid CPCA::fit(Eigen::MatrixXf const &fg, Eigen::MatrixXf const &bg,\n               bool const autoAlphaSelection, float const alpha,\n               float const eta, float const convergenceRatio,\n               unsigned int maxIter, bool const keepReports) {\n  if (autoAlphaSelection) {\n    fitWithBestAlpha(fg, bg, alpha, eta, convergenceRatio, maxIter,\n                     keepReports);\n  } else {\n    fitWithManualAlpha(fg, bg, alpha);\n  }\n}\n\nvoid CPCA::fitWithManualAlpha(Eigen::MatrixXf const &fg,\n                              Eigen::MatrixXf const &bg, float const alpha) {\n  fg_ = fg;\n  bg_ = bg;\n\n  Eigen::Index fgSize = fg_.size();\n  Eigen::Index bgSize = bg_.size();\n\n  if (fgSize == 0 && bgSize == 0) {\n    std::cerr << \"Both target and background matrices are empty.\" << std::endl;\n  } else if (fgSize == 0) {\n    // the result will be the same with when alpha is +inf\n    fg_ = Eigen::MatrixXf::Zero(1, bg_.cols());\n  } else if (bgSize == 0) {\n    // the result will be the same with ordinary PCA\n    bg_ = Eigen::MatrixXf::Zero(1, fg_.cols());\n  }\n\n  Eigen::Index nFeaturesFg = fg_.cols();\n  Eigen::Index nFeaturesBg = bg_.cols();\n\n  if (nFeaturesFg != nFeaturesBg) {\n    std::cerr << \"# of features of foregraound and background must be the same.\"\n              << std::endl;\n  }\n\n  fg_ = fg_.rowwise() - fg_.colwise().mean();\n  bg_ = bg_.rowwise() - bg_.colwise().mean();\n\n  if (standardize_) {\n    Eigen::RowVectorXf fgStd = fg_.array().square().colwise().mean().sqrt();\n    Eigen::RowVectorXf bgStd = bg_.array().square().colwise().mean().sqrt();\n\n    fg_ = fg_.array().rowwise() / fgStd.array();\n    bg_ = bg_.array().rowwise() / bgStd.array();\n\n    // NaN to 0.0f\n    fg_ = fg_.unaryExpr([](float v) { return std::isfinite(v) ? v : 0.0f; });\n    bg_ = bg_.unaryExpr([](float v) { return std::isfinite(v) ? v : 0.0f; });\n  }\n\n  fgCov_ = (fg_.adjoint() * fg_) /\n           std::fmax(float(fg_.rows() - 1), std::numeric_limits<float>::min());\n  bgCov_ = (bg_.adjoint() * bg_) /\n           std::fmax(float(bg_.rows() - 1), std::numeric_limits<float>::min());\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es(fgCov_ - alpha * bgCov_);\n  components_ = es.eigenvectors().rightCols(nComponents_).rowwise().reverse();\n  eigenvalues_ = es.eigenvalues().real().tail(nComponents_).reverse();\n  loadings_ = components_.array().rowwise() * eigenvalues_.array().abs().sqrt();\n}\n\nvoid CPCA::fitWithBestAlpha(Eigen::MatrixXf const &fg,\n                            Eigen::MatrixXf const &bg, float const initAlpha,\n                            float const eta, float const convergenceRatio,\n                            unsigned int const maxIter,\n                            bool const keepReports) {\n  bestAlpha(fg, bg, initAlpha, eta, convergenceRatio, maxIter, keepReports);\n  // updateComponents(bestAlpha_);\n  fitWithManualAlpha(fg, bg, bestAlpha_);\n}\n\nvoid CPCA::updateComponents(float const alpha) {\n  if (components_.cols() == 0) {\n    std::cerr << \"Run fit() at least once before updateComponents()\"\n              << std::endl;\n  }\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es(fgCov_ - alpha * bgCov_);\n  components_ = es.eigenvectors().rightCols(nComponents_).rowwise().reverse();\n\n  eigenvalues_ = es.eigenvalues().real().tail(nComponents_).reverse();\n  loadings_ = components_.array().rowwise() * eigenvalues_.array().abs().sqrt();\n}\n\nEigen::MatrixXf CPCA::transform(Eigen::MatrixXf const &X) {\n  if (components_.cols() == 0) {\n    std::cerr << \"Run fit() before transform()\" << std::endl;\n  }\n  return X * components_;\n}\n\nfloat CPCA::bestAlpha(Eigen::MatrixXf const &fg, Eigen::MatrixXf const &bg,\n                      float const initAlpha, float const eta,\n                      float const convergenceRatio, unsigned int const maxIter,\n                      bool const keepReports) {\n  reports_.clear();\n  float alpha = initAlpha;\n  fit(fg, bg, alpha);\n\n  // method 1. discard minor eigenvectors to avoid singular\n  // Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> esQ(bgCov_);\n  // float ratioToKeep = 0.999f;\n  // Eigen::RowVectorXf eigenvalues = esQ.eigenvalues().real().reverse();\n  // float targetTotalEigenVal = eigenvalues.sum() * ratioToKeep;\n  // Eigen::Index nEigenVectorsToKeep = 0;\n  // while (targetTotalEigenVal > 0) {\n  //     targetTotalEigenVal -= eigenvalues(nEigenVectorsToKeep);\n  //     nEigenVectorsToKeep++;\n  // }\n  // float ratioToKeep = 0.9f;\n  // Eigen::Index nEigenVectorsToKeep = Eigen::Index(bg.cols() * ratioToKeep);\n  //\n  // std::cout << fg.cols() << \" \" << nEigenVectorsToKeep << std::endl;\n  //\n  // Eigen::MatrixXf Q =\n  //     esQ.eigenvectors().rightCols(nEigenVectorsToKeep).rowwise().reverse();\n  // Eigen::MatrixXf fgCovQ = Q.adjoint() * fgCov_ * Q;\n  // Eigen::MatrixXf bgCovQ = Q.adjoint() * bgCov_ * Q;\n  //\n  // Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> esU(fgCovQ - alpha *\n  // bgCovQ); Eigen::MatrixXf U =\n  //     esU.eigenvectors().rightCols(nComponents_).rowwise().reverse();\n  //\n  // if (keepReports) {\n  //   reports_.push_back(alpha);\n  // }\n  //\n  // for (unsigned int i = 0; i < maxIter; ++i) {\n  //   float fgTr = (U.adjoint() * fgCovQ * U).trace();\n  //   float bgTr = (U.adjoint() * bgCovQ * U).trace();\n  //   bgTr = std::fmax(bgTr, std::numeric_limits<float>::min());\n  //   alpha = fgTr / bgTr;\n  //\n  //   // update U\n  //   Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> esU(fgCovQ - alpha *\n  //   bgCovQ); U =\n  //   esU.eigenvectors().rightCols(nComponents_).rowwise().reverse();\n  //\n  //   if (keepReports) {\n  //     reports_.push_back(alpha);\n  //   }\n  // }\n  // bestAlpha_ = alpha;\n\n  // method 2: add small constant to diag of bgCov_ to avoid singular\n  bgCov_ += Eigen::MatrixXf::Identity(bgCov_.rows(), bgCov_.cols()) * eta;\n\n  if (keepReports) {\n    reports_.push_back(alpha);\n  }\n\n  for (unsigned int i = 0; i < maxIter; ++i) {\n    float fgTr = (components_.adjoint() * fgCov_ * components_).trace();\n    float bgTr = (components_.adjoint() * bgCov_ * components_).trace();\n    bgTr = std::fmax(bgTr, std::numeric_limits<float>::min());\n\n    float prevAlpha = alpha;\n    alpha = fgTr / bgTr;\n    updateComponents(alpha);\n    if (keepReports) {\n      reports_.push_back(alpha);\n    }\n\n    if (std::abs(prevAlpha - alpha) / alpha < convergenceRatio)\n      break;\n  }\n  bestAlpha_ = alpha;\n\n  return bestAlpha_;\n}\n\nstd::vector<float> CPCA::logspace(float const start, float const end,\n                                  unsigned int const num, float const base) {\n  float realStart = std::pow(base, start);\n  float realBase = std::pow(\n      base, (end - start) /\n                std::fmax(float(num - 1), std::numeric_limits<float>::min()));\n\n  std::vector<float> result;\n  result.reserve(num);\n  std::generate_n(\n      std::back_inserter(result), num, [=]() mutable throw()->float {\n        float val = realStart;\n        realStart *= realBase;\n        return val;\n      });\n  return result;\n}\n\n// TODO: implement semi-automatic selection of alpha of the original cpca\n// (but not necessary for ccPCA)\n\nstd::vector<float> CPCA::findSpectalAlphas(unsigned int const nAlphasToReturn,\n                                           unsigned int const nAlphas,\n                                           float const maxLogAlpha) {\n  std::vector<float> alphas;\n  Eigen::MatrixXf affinityMat = createAffinityMatrix(fg_, nAlphas, maxLogAlpha);\n\n  // TODO: implement rest of here\n\n  return alphas;\n}\n\nEigen::MatrixXf CPCA::createAffinityMatrix(Eigen::MatrixXf const &X,\n                                           unsigned int const nAlphas,\n                                           float const maxLogAlpha) {\n  std::vector<float> alphas;\n  alphas.reserve(nAlphas + 1);\n  alphas.push_back(0.0f);\n\n  auto logspaceAlphas = logspace(-1.0f, maxLogAlpha, nAlphas);\n  alphas.insert(alphas.end(), logspaceAlphas.begin(), logspaceAlphas.end());\n\n  auto k = alphas.size();\n  Eigen::MatrixXf affinityMat =\n      0.5 * Eigen::MatrixXf::Identity(Eigen::Index(k), Eigen::Index(k));\n\n  std::vector<Eigen::MatrixXf> subspaces;\n  subspaces.reserve(k);\n  for (auto const &alpha : alphas) {\n    updateComponents(alpha);\n    Eigen::MatrixXf proj = transform(X);\n    Eigen::HouseholderQR<Eigen::MatrixXf> qr(proj);\n    Eigen::MatrixXf Q = qr.householderQ();\n    subspaces.push_back(qr.householderQ());\n  }\n\n  for (size_t i = 0; i < k; ++i) {\n    for (size_t j = i + 1; j < k; ++j) {\n      Eigen::BDCSVD<Eigen::MatrixXf> svd(subspaces[i] * subspaces[j],\n                                         Eigen::ComputeThinU |\n                                             Eigen::ComputeThinV);\n      Eigen::VectorXf s = svd.singularValues();\n      affinityMat(Eigen::Index(i), Eigen::Index(j)) = s(0) * s(1);\n    }\n  }\n\n  affinityMat = affinityMat + affinityMat.transpose();\n  // NaN to 0.0f\n  affinityMat = affinityMat.unaryExpr(\n      [](float v) { return std::isfinite(v) ? v : 0.0f; });\n\n  return affinityMat;\n}\n", "meta": {"hexsha": "a1078a207e414495bede62789523149212e0aec9", "size": 9668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ccpca/cpca.cpp", "max_stars_repo_name": "takanori-fujiwara/ccpca", "max_stars_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-16T03:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T14:59:11.000Z", "max_issues_repo_path": "ccpca/cpca.cpp", "max_issues_repo_name": "takanori-fujiwara/ccpca", "max_issues_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ccpca/cpca.cpp", "max_forks_repo_name": "takanori-fujiwara/ccpca", "max_forks_repo_head_hexsha": "e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T03:35:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:41:07.000Z", "avg_line_length": 35.2846715328, "max_line_length": 80, "alphanum_fraction": 0.6183285064, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5969708644345137}}
{"text": "//\n// SPDX-License-Identifier: MIT\n// Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng\n//\n\n#include <vector>\n#include <string>\n#include <unordered_map>\n\n#include <armadillo>\n#include <boost/filesystem.hpp>\n\n#include \"utils.hpp\"\n#include \"lambda.hpp\"\n#include \"region.hpp\"\n#include \"rDHS.hpp\"\n#include \"binarysignal.hpp\"\n#include \"correlation.hpp\"\n\nnamespace SCREEN {\n\n  namespace bfs = boost::filesystem;\n  namespace a = arma;\n\n  /**\n     compute the pairwise correlation of the regions for the given chromosome\n     @returns: armadillo matrix containing pairwise correlation coefficients for the regions\n   */\n  a::Mat<float> runCorrelation(std::vector<ScoredRegionSet> &regions, const std::string &chr) {\n\n    // create emptry matrix\n    if (0 == regions.size()) return a::Mat<float>(0, 0);\n    a::Mat<float> values(regions.size(), regions[0].regions_.regions_[chr].size());\n    \n    // populate with region scores\n    for (auto i = 0; i < regions.size(); ++i) {\n#pragma omp parallel for\n      for (auto j = 0; j < regions[i].regions_.regions_[chr].size(); ++j) {\n\tvalues.at(i, j) = regions[i].regions_.regions_[chr][j].score;\n      }\n    }\n\n    // return pairwise correlation\n    return a::cor(values);\n\n  }\n\n  a::Mat<float> runCorrelation(BinarySignal &b, const std::vector<boost::filesystem::path> &signalfiles,\n\t\t\t       const std::string &chr, RegionSet &regions) {\n\n    // create empty matrix\n    if (0 == signalfiles.size()) return a::Mat<float>(0, 0);\n    a::Mat<float> values(signalfiles.size(), regions.regions_.regions_[chr].size());\n    \n    // populate with region scores\n    for (auto i = 0; i < signalfiles.size(); ++i) {\n      a::Col<float> v = b.readSignal<RegionSet>(signalfiles[i], chr, regions);\n#pragma omp parallel for\n      for (auto j = 0; j < regions.regions_.regions_[chr].size(); ++j) {\n\tvalues.at(i, j) = v.at(j);\n      }\n    }\n\n    // return pairwise correlation\n    return a::cor(values);\n\n  }\n\n  /**\n     write a computed pairwise correlation in JSON 2D array format to an output file\n     @param corr: matrix containing the correlation coefficients\n     @param output_path: output path to which to write the matrix\n   */\n  template <typename T>\n  void writeCorrelation(const a::Mat<T> &corr, const bfs::path &output_path) {\n    std::ofstream f(output_path.string());\n    long i, j;\n    f << '[';\n    for (i = 0; i < corr.n_rows - 1; ++i) {\n      for (j = 0; j < corr.n_cols - 1; ++j) {\n\tf << corr.at(i, j) << ',';\n      }\n      f << corr.at(i, j) << \"],[\";\n    }\n    for (j = 0; j < corr.n_cols - 1; ++j) {\n      f << corr.at(i, j) << ',';\n    }\n    f << corr.at(i, j) << ']';\n  }\n\n  template void writeCorrelation<float>(const a::Mat<float> &corr, const bfs::path &output_path);\n  template void writeCorrelation<double>(const a::Mat<double> &corr, const bfs::path &output_path);\n\n} // SCREEN\n", "meta": {"hexsha": "e50a90023c446025c49fd79adb53c63fa81f0573", "size": 2857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "0_cre_pipeline/just21/cpp/src/common/correlation.cpp", "max_stars_repo_name": "weng-lab/SCREEN", "max_stars_repo_head_hexsha": "e8e7203e2f9baa2de70e2f75bdad3ae24b568367", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-30T02:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T01:26:47.000Z", "max_issues_repo_path": "0_cre_pipeline/just21/cpp/src/common/correlation.cpp", "max_issues_repo_name": "weng-lab/SCREEN", "max_issues_repo_head_hexsha": "e8e7203e2f9baa2de70e2f75bdad3ae24b568367", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T10:30:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T16:47:47.000Z", "max_forks_repo_path": "0_cre_pipeline/just21/cpp/src/common/correlation.cpp", "max_forks_repo_name": "weng-lab/SCREEN", "max_forks_repo_head_hexsha": "e8e7203e2f9baa2de70e2f75bdad3ae24b568367", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-08T10:05:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T09:41:19.000Z", "avg_line_length": 30.0736842105, "max_line_length": 104, "alphanum_fraction": 0.6317815891, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5969708619040492}}
{"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_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) complementary  error function:\n   \\f$\\displaystyle e^{x^2}\\frac{2}{\\sqrt\\pi}\\int_{x}^{\\infty} 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  Value erfcx(Value const & v0);\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": "22ed6dd3c55c28ad94b1c345b76076dc64cc8962", "size": 1196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erfcx.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/erfcx.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/erfcx.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.4509803922, "max_line_length": 100, "alphanum_fraction": 0.5785953177, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5968705128188928}}
{"text": "/** \\file functors.hpp */\n\n#pragma once\n\n// std c++ headers\n#include <cmath>\n#include <complex>\n#include <type_traits>\n\n// boost headers\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\n// AMDiS headers\n#include \"operations/functor_generator.hpp\"\n#include \"operations/meta.hpp\"\n#include \"traits/basic.hpp\"\n#include \"traits/scalar_types.hpp\"\n\nnamespace AMDiS\n{\n  namespace functors\n  {\n    /// identity(v) == v\n    AMDIS_MAKE_UNARY_FUNCTOR( identity , d0 , v )\n\n    /// constant(v) == val\n    template <class T>\n    struct constant : FunctorBase\n    {\n      constant(T val_) : val(val_) {}\n\n      template <class V>\n      T operator()(V&&) const\n      {\n        return val;\n      }\n\n    private:\n      T val;\n    };\n\n    /// ct_constant(v) == val\n    template <class T, long val_>\n    struct ct_constant : FunctorBase\n    {\n      static constexpr T val = val_;\n\n      template <class V> static constexpr T eval(V&&)\n      {\n        return val;\n      }\n      template <class V> static constexpr T apply(V&&)\n      {\n        return val;\n      }\n      template <class V> constexpr T operator()(V&&) const\n      {\n        return val;\n      }\n    };\n\n    /// abs(v) == |v|\n    template <class T>\n    struct abs : FunctorBase\n    {\n      static constexpr int getDegree(int d0)\n      {\n        return d0;\n      }\n      static constexpr auto eval(const T& v) RETURNS( math::abs(v) )\n      constexpr auto operator()(const T& v) const RETURNS( eval(v) )\n    };\n\n    // specialization of abs for complex values\n    template <class T>\n    struct abs<std::complex<T>> : FunctorBase\n    {\n      static constexpr int getDegree(int d0)\n      {\n        return d0;\n      }\n      static constexpr auto eval(const T& v) RETURNS( std::norm(v) )\n      constexpr auto operator()(const T& v) const RETURNS( eval(v) )\n    };\n\n    /// negate(v) == -v\n    AMDIS_MAKE_UNARY_FUNCTOR( negate, d0, -v  )\n\n    AMDIS_MAKE_BINARY_FUNCTOR( plus,  math::max(d0, d1), v0 + v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( minus, math::max(d0, d1), v0 - v1  )\n//     AMDIS_MAKE_BINARY_FUNCTOR( multiplies, d0 + d1,      v0 * v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( divides,    d0 + d1,      v0 / v1  )\n\n\n    struct multiplies : FunctorBase\n    {\n      int getDegree(int d0, int d1) const\n      {\n        return d0 + d1;\n      }\n\n      template <class T0, class T1 = T0>\n      static constexpr auto eval(T0&& v0, T1&& v1) RETURNS( std::forward<T0>(v0) * std::forward<T1>(v1) )\n\n      template <class T0, class T1 = T0>\n      auto operator() (T0&& v0, T1&& v1) const RETURNS( std::forward<T0>(v0) * std::forward<T1>(v1) )\n    };\n\n\n    // _____ logical functors _________________________________________________\n\n    AMDIS_MAKE_BINARY_FUNCTOR( equal,   0, v0 == v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( unequal, 0, v0 != v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( less,    0, v0 < v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( greater, 0, v0 > v1  )\n\n    AMDIS_MAKE_BINARY_FUNCTOR( logical_and, 0, v0 && v1  )\n    AMDIS_MAKE_BINARY_FUNCTOR( logical_or,  0, v0 || v1  )\n\n    AMDIS_MAKE_BINARY_FUNCTOR( max, math::max(d0, d1), math::max(v0, v1)  )\n    AMDIS_MAKE_BINARY_FUNCTOR( min, math::max(d0, d1), math::min(v0, v1)  )\n\n\n    /// max(|a|,|b|)\n    AMDIS_MAKE_BINARY_FUNCTOR( abs_max, math::max(d0, d1), math::max(math::abs(v0), math::abs(v1))  )\n\n    /// min(|a|,|b|)\n    AMDIS_MAKE_BINARY_FUNCTOR( abs_min, math::max(d0, d1), math::min(math::abs(v0), math::abs(v1))  )\n\n\n    /// conditional(a,b,c) = a ? b : c\n    template <class T1, class T2>\n    struct conditional : FunctorBase\n    {\n      constexpr int getDegree(int d0, int d1, int d2) const\n      {\n        return math::max(d1, d2);\n      }\n      static constexpr typename std::common_type<T1, T2>::type\n      eval(bool cond, T1 const& v1, T2 const& v2)\n      {\n        return cond ? v1 : v2;\n      }\n      constexpr auto operator()(bool cond, T1 const& v1, T2 const& v2) const RETURNS\n      (\n        eval(cond, v1, v2)\n      )\n    };\n\n\n    /// cross(v1, v2) = v1 x v2, TODO: find better name\n    template <class T1, class T2>\n    struct MyCross : FunctorBase\n    {\n      using value_type = decltype( std::declval<T1>() * std::declval<T2>() );\n      constexpr int getDegree(int /*d*/, int d0, int d1) const\n      {\n        return d0+d1;\n      }\n\n      template <class Vec1, class Vec2>\n      static value_type eval(size_t i, const Vec1& v1, const Vec2& v2)\n      {\n        using size_type = Size_t<traits::category<Vec1>>;\n        value_type result;\n\n        TEST_EXIT_DBG( size(v1) == 3 && size(v1) == size(v2), \"cross: inkompatible sizes!\\n\");\n\n        size_type k = (i+1) % 3, l = (i+2) % 3;\n        result = v1(k) * v2(l) - v1(l) * v2(k);\n        return result;\n      }\n\n      template <class Vec1, class Vec2>\n      auto operator()(size_t i, const Vec1& v1, const Vec2& v2) const RETURNS\n      (\n        eval(i, v1, v2)\n      )\n    };\n\n\n    /// apply a functor N times\n    template <class Functor, int N>\n    struct apply\n    {\n      apply(Functor const& f_) : f(f_), inner(f_) {}\n\n      int getDegree(int d0) const\n      {\n        return f.getDegree(inner.getDegree(d0));\n      }\n\n      template <class V>\n      static auto eval(const V& v) RETURNS\n      (\n        Functor::eval(apply<Functor, N-1>::eval(v))\n      )\n\n      template <class V>\n      auto operator()(const V& v) const RETURNS( f(inner(v)) )\n\n    private:\n      Functor f;\n      apply<Functor, N-1> inner;\n    };\n\n    template <class Functor>\n    struct apply<Functor, 0>\n    {\n      apply(Functor const& f_) : f(f_) {}\n      int getDegree(int d0) const\n      {\n        return d0;\n      }\n\n      template <class V>\n      static auto eval(const V& v) RETURNS( v )\n      template <class V>\n      auto operator()(const V& v) const RETURNS( v )\n\n    private:\n      Functor f;\n    };\n\n\n\n    // -------------------------------------------------------------------------\n\n    template <class F, int arg, class G>\n    struct compose;\n\n    template <class F, class G>\n    struct compose<F, 1, G>\n    {\n      template <class T>\n      auto operator()(T const& v, T const& v0) RETURNS( f(g(v), v0) )\n\n    private:\n      F f;\n      G g;\n    };\n\n    template <class F, class G>\n    struct compose<F, 2, G>\n    {\n      template <class T>\n      auto operator()(T const& v, T const& v0) RETURNS( f(v, g(v0)) )\n\n    private:\n      F f;\n      G g;\n    };\n\n\n    /// pow<p>(v) == v^p\n    template <int p, class T>\n    struct pow : FunctorBase\n    {\n      constexpr int getDegree(int d0) const\n      {\n        return p*d0;\n      }\n\n      static constexpr T eval(const T& v)\n      {\n        return boost::math::pow<p>(v);\n      }\n      constexpr T operator()(const T& v) const\n      {\n        return eval(v);\n      }\n    };\n\n    /// root<p>(v) == p-th-root(v)\n    template <int p, class T, class = void>\n    struct root_dispatch;\n\n    template <int p, class T>\n    struct root : FunctorBase\n    {\n      constexpr int getDegree(int d0) const\n      {\n        return p*d0;    // optimal polynomial approximation degree ?\n      }\n\n      static constexpr T eval(const T& v)\n      {\n        return root_dispatch<p,T>::eval(v);\n      }\n      constexpr T operator()(const T& v) const\n      {\n        return eval(v);\n      }\n    };\n\n    template <int p, class T, class>\n    struct root_dispatch\n    {\n      static constexpr T eval(const T& v)\n      {\n        return std::pow(v, 1.0/p);\n      }\n    };\n\n    template <int p, class T>\n    struct root_dispatch<p, T,\n      Requires_t<meta::is_power_of<p, 3>> >\n    {\n      static constexpr T eval(const T& v)\n      {\n        return apply<root<3, T>, meta::log<p, 3>::value>::eval(v);\n      }\n    };\n\n    template <int p, class T>\n    struct root_dispatch<p, T,\n      Requires_t<meta::is_power_of<p, 2>> >\n    {\n      static constexpr T eval(const T& v)\n      {\n        return apply<root<2, T>, meta::log<p, 2>::value>::eval(v);\n      }\n    };\n\n    template <class T>\n    struct root_dispatch<3, T>\n    {\n      static constexpr T eval(const T& v)\n      {\n        return boost::math::cbrt(v);\n      }\n    };\n\n    template <class T>\n    struct root_dispatch<2, T>\n    {\n      static constexpr T eval(const T& v)\n      {\n        return std::sqrt(v);\n      }\n    };\n\n    template <class T>\n    struct root_dispatch<1, T>\n    {\n      static constexpr T eval(const T& v)\n      {\n        return v;\n      }\n    };\n\n    template <class T>\n    struct root_dispatch<0, T>\n    {\n      static constexpr T eval(const T& /*v*/)\n      {\n        return 1.0;\n      }\n    };\n\n  } // end namespace functors\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "0190612977db9ace0ee58174deff66460507827c", "size": 8527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/operations/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": "test/operations/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": "test/operations/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": 23.3616438356, "max_line_length": 105, "alphanum_fraction": 0.5522458074, "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.596862220835367}}
{"text": "//\n//  EigenEx1DenseMatVec.cpp\n//  \n//\n//  Created by Zac Schulwolf on 12/26/16.\n//\n// Compile by g++ -I \"$(brew --prefix eigen)/include/eigen3\" EigenEx1DenseMatVec.cpp -o EigenEx1DenseMatVec\n//\n// From https://eigen.tuxfamily.org/dox/GettingStarted.html\n// From https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n// Installing Libraries http://stackoverflow.com/questions/34340578/installing-c-libraries-on-os-x\n\n#include <iostream>\n#include <Eigen/Dense>\n//using Eigen::MatrixXd; used for 1\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n    //1\n    MatrixXd m1(2,2);\n    m1(0,0) = 3;\n    m1(1,0) = 2.5;\n    m1(0,1) = -1;\n    m1(1,1) = m1(1,0) + m1(0,1);\n    cout << \"Here is the matrix m1:\\n\" << m1 << endl;\n    \n    VectorXd v1(2);\n    v1(0) = 4;\n    v1(1) = v1(0) - 1;\n    cout << \"Here is the vector v1:\\n\" << v1 << endl;\n    cout << endl << endl;\n    \n    \n    //2A\n    Matrix3d m2a= Matrix3d::Random();\n    m2a= (m2a+ Matrix3d::Constant(1.2)) * 50;\n    cout << \"m2a=\" << endl << m2a<< endl;\n    Vector3d v2a(1,2,3);\n    cout << \"m2a* v2a =\" << endl << m2a* v2a << endl;\n    cout << endl << endl;\n    \n    \n    //2B\n    MatrixXd m2b= MatrixXd::Random(3,3);\n    m2b= (m2b+ MatrixXd::Constant(3,3,1.2)) * 50;\n    cout << \"m2b=\" << endl << m2b<< endl;\n    VectorXd v2b(3);\n    v2b << 1, 2, 3;\n    cout << \"m2b* v2b =\" << endl << m2b* v2b << endl;\n    cout << endl << endl;\n    \n    \n    //3\n    //initialization\n    Matrix3d m3a; //3 by 3 matrix of uninitialized coefficients\n    MatrixXd m3b; //dynamic size matrix, size currently 0 by 0, coefficients not allocated\n    MatrixXf m3c(10,15); //10 by 15 dynamic sized matrix, allocated and uninitialized coeffients\n    VectorXf v3a(30); //size 30 dynamic sized vector, allocated and uninitialized coeffients\n    Vector2d v3b(5.0, 6.0);\n    Vector3d v3c(5.0, 6.0, 7.0);\n    Vector4d v3d(5.0, 6.0, 7.0, 8.0); //can initialize up to 4 coeffients with this method\n    Matrix3f m3d;\n    m3d << 1, 2, 3, 4, 5, 6, 7, 8, 9; //Comma-initialization for matrix\n    cout << m3d << endl;\n    \n    Vector3f v3e; //column vector <float,3,1> Vector\n    RowVector3f v3f; //row vector <float,3,2> RowVector\n    cout << endl << endl;\n    \n    \n    //4\n    //rows(), cols(), size(), resize()\n    //resize() changes coeffients, use conservativeResize() to keep coeffients\n    MatrixXd m4(2,5); //Note that this is Xd so its dynamic sized\n    m4.resize(4,3); //Needs to be dynamic, now 4 by 3\n    cout << \"The matrix m4 is of size \" << m4.rows() << \"x\" << m4.cols() << endl;\n    cout << \"It has \" << m4.size() << \" coefficients\" << endl;\n    \n    VectorXd v4(2);\n    v4.resize(5);\n    cout << \"The vector v4 is of size \" << v4.size() << endl;\n    cout << \"As a matrix, v4 is of size \" << v4.rows() << \"x\" << v4.cols() << endl;\n    cout << endl << endl;\n    \n    \n    //5\n    //Assignment and resizing\n    MatrixXf m5a(2,2);\n    cout << \"m5a is of size \" << m5a.rows() << \"x\" << m5a.cols() << endl;\n    MatrixXf m5b(3,3);\n    m5a = m5b;\n    cout << \"m5a is now of size \" << m5a.rows() << \"x\" << m5a.cols() << endl;\n    cout << \"m5a is now of size \" << m5a.rows() << \"x\" << m5a.cols() << endl;\n    \n    \n    //6\n    //Formula\n    /*\n     cout << \"MatrixNt; ex: MatrixXi (Matrix<int, Dynamic, Dynamic>)\n     VectorNt; ex: Vector2f (Matrix<float, 2, 1>)\n     RowVectonNt; ex: Vector3d (Matrix<double, 1, 3>)\n     \n     N can be 2,3,4, or x (dynamic)\n     t can be i (int), f (float), d (double), cf (complex<float>), or cd(complex<double>)\" << endl;\n    */\n    \n}\n", "meta": {"hexsha": "94e830298646af1df2c875575537ee28fb481eb4", "size": 3515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen/EigenEx1DenseMatVec.cpp", "max_stars_repo_name": "zacswolf/MNISTNeuralNetwork", "max_stars_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Eigen/EigenEx1DenseMatVec.cpp", "max_issues_repo_name": "zacswolf/MNISTNeuralNetwork", "max_issues_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Eigen/EigenEx1DenseMatVec.cpp", "max_forks_repo_name": "zacswolf/MNISTNeuralNetwork", "max_forks_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9545454545, "max_line_length": 107, "alphanum_fraction": 0.5724039829, "num_tokens": 1291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.5967831814114513}}
{"text": "#include \"Discretization.hpp\"\n#include \"constants.hpp\"\n\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n#include <boost/numeric/odeint.hpp>\n\nclass DiscretizationODE {\nprivate:\n    Model::ControlVector u_t, u_t1;\n    double sigma, dt;\n    Model& model;\n\npublic:\n\n    static constexpr size_t n_V_states = 3 + Model::n_states + 2 * Model::n_inputs;\n    using state_type = Eigen::Matrix<double, Model::n_states, n_V_states>;\n\n    DiscretizationODE(\n        const Model::ControlVector &u_t, \n        const Model::ControlVector &u_t1, \n        const double &sigma, \n        double dt,\n        Model& model\n    )\n    :u_t(u_t)\n    ,u_t1(u_t1)\n    ,sigma(sigma)\n    ,dt(dt)\n    ,model(model) {}\n\n    void operator()(const state_type &V, state_type &dVdt, const double t){\n\n        const Model::StateVector &x = V.col(0);\n        const Model::ControlVector u = u_t + t / dt * (u_t1 - u_t);\n\n        const double alpha = t / dt;\n        const double beta = 1. - alpha;\n\n        const Model::StateMatrix   A_bar  = sigma * model.state_jacobian(x, u);\n        const Model::ControlMatrix B_bar  = sigma * model.control_jacobian(x, u);\n        const Model::StateVector   f      =         model.ode(x, u);\n\n        Model::StateMatrix Phi_A_xi = V.block<Model::n_states, Model::n_states>(0, 1);\n        Model::StateMatrix Phi_A_xi_inverse = Phi_A_xi.inverse();\n\n        size_t cols = 0;\n\n        dVdt.block<Model::n_states,               1>(0, cols) = sigma * f;                                   cols += 1;\n        dVdt.block<Model::n_states, Model::n_states>(0, cols) = A_bar * Phi_A_xi;                            cols += Model::n_states;\n        dVdt.block<Model::n_states, Model::n_inputs>(0, cols) = Phi_A_xi_inverse * B_bar * alpha;            cols += Model::n_inputs;\n        dVdt.block<Model::n_states, Model::n_inputs>(0, cols) = Phi_A_xi_inverse * B_bar * beta;             cols += Model::n_inputs;\n        dVdt.block<Model::n_states,               1>(0, cols) = Phi_A_xi_inverse * f;                        cols += 1;\n        dVdt.block<Model::n_states,               1>(0, cols) = Phi_A_xi_inverse * (-A_bar * x - B_bar * u);\n    }\n};\n\nvoid calculate_discretization (\n    Model &model,\n    double &sigma,\n    Eigen::Matrix<double, Model::n_states, K> &X,\n    Eigen::Matrix<double, Model::n_inputs, K> &U,\n    array<Model::StateMatrix,   (K-1)> &A_bar,\n    array<Model::ControlMatrix, (K-1)> &B_bar,\n    array<Model::ControlMatrix, (K-1)> &C_bar,\n    array<Model::StateVector,   (K-1)> &Sigma_bar,\n    array<Model::StateVector,   (K-1)> &z_bar\n) {\n\n    const double dt = 1 / double(K-1);\n    using namespace boost::numeric::odeint;\n    runge_kutta4<DiscretizationODE::state_type, double, DiscretizationODE::state_type, double, vector_space_algebra> stepper;\n\n\n    for (size_t k = 0; k < K-1; k++) {\n        DiscretizationODE::state_type V;\n        V.setZero();\n        V.col(0) = X.col(k);\n        V.block<Model::n_states,Model::n_states>(0, 1).setIdentity();\n\n        DiscretizationODE discretizationODE(U.col(k), U.col(k+1), sigma, dt, model);\n        integrate_n_steps( stepper , discretizationODE , V , 0. , dt/10.0 , 10 );\n\n        size_t cols = 1;\n        A_bar[k]      =            V.block<Model::n_states,Model::n_states>(0, cols);   cols += Model::n_states;\n        B_bar[k]      = A_bar[k] * V.block<Model::n_states,Model::n_inputs>(0, cols);   cols += Model::n_inputs;\n        C_bar[k]      = A_bar[k] * V.block<Model::n_states,Model::n_inputs>(0, cols);   cols += Model::n_inputs;\n        Sigma_bar[k]  = A_bar[k] * V.block<Model::n_states,1>(0, cols);                 cols += 1;\n        z_bar[k]      = A_bar[k] * V.block<Model::n_states,1>(0, cols);\n    }\n}", "meta": {"hexsha": "aa2c96146e03bad69de9650b11a53b37550d54de", "size": 3684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Discretization.cpp", "max_stars_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_stars_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T13:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T16:50:13.000Z", "max_issues_repo_path": "src/Discretization.cpp", "max_issues_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_issues_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Discretization.cpp", "max_forks_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_forks_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T10:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T06:27:22.000Z", "avg_line_length": 40.9333333333, "max_line_length": 133, "alphanum_fraction": 0.5909337676, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5967267691244481}}
{"text": "/*\n * spectral_impl.hpp\n *\n *  Created on: Jan 29, 2012\n *      Author: david\n */\n\n#ifndef GRAPHSEG_SPECTRAL_SPECTRALIMPL_HPP_\n#define GRAPHSEG_SPECTRAL_SPECTRALIMPL_HPP_\n\n#include \"../Common.hpp\"\n#include \"../as_range.hpp\"\n#include <boost/graph/adjacency_list.hpp>\n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#ifdef SEGS_DBG_PRINT\n#include <boost/format.hpp>\n#include <fstream>\n#endif\n\nnamespace graphseg { namespace detail {\n\nconstexpr float c_D_min = 0.001f;\n\ntemplate<typename K>\nstruct DenseGev\n{\n\tEigen::Matrix<K,-1,-1> L;\n\tEigen::Matrix<K,-1,1> D;\n};\n\ntemplate<typename K, typename Graph, typename EdgeWeightMap>\nDenseGev<K> dense_graph_to_gev(const Graph& graph, EdgeWeightMap edge_weights)\n{\n\ttypedef Eigen::Matrix<K,-1,-1> matrix_t;\n\ttypedef Eigen::Matrix<K,-1,1> vector_t;\n\tconst unsigned int dim = boost::num_vertices(graph);\n\t// creating matrices\n\tmatrix_t W = matrix_t::Zero(dim,dim);\n\tvector_t D = vector_t::Zero(dim);\n\n#ifdef SPECTRAL_VERBOSE\n\tstd::cout << \"DEBUG: Number of vertices = \" << boost::num_vertices(graph) << std::endl; \n\tstd::cout << \"DEBUG: Number of edges = \" << boost::num_edges(graph) << std::endl; \n#endif\n\n\tfor(auto eid : as_range(boost::edges(graph))) {\n\t\tunsigned int ea = boost::source(eid, graph);\n\t\tunsigned int eb = boost::target(eid, graph);\n\t\tK ew = edge_weights[eid];\n\t\tif(std::isnan(ew)) {\n\t\t\tstd::cerr << \"ERROR: Weight for edge (\" << ea << \",\" << eb << \") is nan!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif(ew < 0) {\n\t\t\tstd::cerr << \"ERROR: Weight for edge (\" << ea << \",\" << eb << \") is negative!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tW(ea, eb) = ew;\n\t\tW(eb, ea) = ew;\n\t\tD[ea] += ew;\n\t\tD[eb] += ew;\n\t}\n\t// connect disconnected segments to everything\n\t// FIXME why is this necessary?\n#ifdef SPECTRAL_VERBOSE\n\tstd::vector<int> nodes_with_no_connection;\n#endif\n\tfor(unsigned int i=0; i<dim; i++) {\n\t\tK& di = D[i];\n\t\tif(di < c_D_min) {\n#ifdef SPECTRAL_VERBOSE\n\t\t\tnodes_with_no_connection.push_back(i);\n#endif\n\t\t\t// connect the disconnected cluster to all other clusters with a very small weight\n\t\t\tdi = static_cast<K>(1);\n\t\t\tK q = di / static_cast<K>(dim-1);\n\t\t\tfor(unsigned int j=0; j<dim; j++) {\n\t\t\t\tif(j == i) continue;\n\t\t\t\tW(i,j) = q;\n\t\t\t\tW(j,i) = q;\n\t\t\t}\n\t\t}\n\t}\n#ifdef SPECTRAL_VERBOSE\n\tif(!nodes_with_no_connection.empty()) {\n\t\tstd::cout << \"DEBUG: Nodes without connections (#=\" << nodes_with_no_connection.size() << \"): \";\n\t\tfor(int i : nodes_with_no_connection) {\n\t\t\tstd::cout << i << \", \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n#endif\t\n\t// compute matrix L = D - W\n\tmatrix_t L = -W;\n\tfor(unsigned int i=0; i<dim; i++) {\n\t\tL(i,i) += D[i];\n\t}\n\t// ready\n\treturn { L, D };\n}\n\ntemplate<typename K>\nstruct DenseGevTransformed\n{\n\tEigen::Matrix<K,-1,-1> A;\n\tEigen::Matrix<K,-1,1> D_inv_sqrt;\n};\n\ntemplate<typename K>\nDenseGevTransformed<K> dense_gev_to_ev(const DenseGev<K>& gev)\n{\n\ttypedef Eigen::Matrix<K,-1,-1> matrix_t;\n\ttypedef Eigen::Matrix<K,-1,1> vector_t;\n\t// The general eigenvalue problem\n\t//     (D - W) x = \\lambda D x\n\t// can be transformed as follows:\n\t// <=> D^{-1/2} (D - W) x = \\lambda D^{1/2} x\n\t// using z := D^{1/2} x i.e. x = D^{-1/2} z\n\t// <=> D^{-1/2} (D - W) D^{-1/2} z = \\lambda z\n\t// Thus we have a \"normal\" eigenvalue problem A z = \\lambda z with\n\t//     A := D^{-1/2} (D - W) D^{-1/2}\n\t// Using L := D - W this gives for coefficients:\n\t//\t\ta_ij = l_ij / \\sqrt(d_i * d_j)\n\t// where d_i := D_ii\n\tconst matrix_t& L = gev.L;\n\tconst vector_t& D = gev.D;\n\tassert(L.cols() == L.rows());\n\tassert(D.rows() == L.rows());\n\tconst unsigned int N = L.rows();\n\tvector_t D_inv_sqrt = D.array().sqrt().inverse().matrix();\n\tmatrix_t A(N,N);\n\tfor(unsigned int i=0; i<N; i++) {\n\t\tA.col(i) = D_inv_sqrt[i] * L.col(i).cwiseProduct(D_inv_sqrt);\n\t}\n\treturn { A, D_inv_sqrt };\n}\n\ntemplate<typename K>\nstruct SparseGEVT\n{\n\tSparseMatrix A;\n\tEigen::VectorXf D_inv_sqrt;\n};\n\ntemplate<typename K, typename Graph, typename EdgeWeightMap>\nSparseGEVT<K> sparse_graph_entries(const Graph& graph, EdgeWeightMap edge_weights)\n{\n\t// We want to solve the EV problem: (D - W) x = \\lamda D x.\n\t// Each edge of the graph defines two entries into the symmetric matrix W.\n\t// The diagonal matrix D is defined via d_i = sum_j{w_ij}.\n\n\t// As D is a diagonal matrix the the general problem can be easily transformed\n\t// into a normal eigenvalue problem by decomposing D = L L^t, which yields L = sqrt(D).\n\t// Thus the EV problem is: L^{-1} (D - W) L^{-T} y = \\lambda y.\n\t// Eigenvectors can be transformed using x = L^{-T} y.\n\n\t// The dimension of the problem\n\tconst int n = boost::num_vertices(graph);\n\n\t// Each edge defines two entries (one in the upper and one in the lower).\n\t// In addition all diagonal entries are non-zero.\n\t// Thus the number of non-zero entries in the lower triangle is equal to\n\t// the number of edges plus the number of nodes.\n\t// This is not entirely true as some connections are possibly rejected.\n\t// Additionally some connections may be added to assure global connectivity.\n\tconst int nnz_guess = boost::num_edges(graph) + n;\n\n\t// collect all non-zero elements\n\tSparseGEVT<K> sgevt;\n\tsgevt.A.dim = n;\n\n\tstd::vector<SparseEntry>& entries = sgevt.A.entries;\n\tentries.reserve(nnz_guess);\n\n\t// also collect diagonal entries\n\tEigen::VectorXf& diag = sgevt.D_inv_sqrt;\n\tdiag = Eigen::VectorXf(n);\n\n\t// no collect entries\n\tfor(auto eid : as_range(boost::edges(graph))) {\n\t\tint ea = static_cast<int>(boost::source(eid, graph));\n\t\tint eb = static_cast<int>(boost::target(eid, graph));\n\t\tK ew = edge_weights[eid];\n\t\t// assure correct edge weight\n\t\tif(std::isnan(ew)) {\n\t\t\tstd::cerr << \"ERROR: Weight for edge (\" << ea << \",\" << eb << \") is nan!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif(ew < 0) {\n\t\t\tstd::cerr << \"ERROR: Weight for edge (\" << ea << \",\" << eb << \") is negative!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t// assure that no vertices is connected to self\n\t\tif(ea == eb) {\n\t\t\tstd::cerr << \"ERROR: Vertex \" << ea << \" is connected to self!\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\t// In the lower triangle the row index i is bigger or equal than the column index j.\n\t\t// The next statement fullfills this requirement.\n\t\tif(ea < eb) {\n\t\t\tstd::swap(ea, eb);\n\t\t}\n\t\tentries.push_back(SparseEntry{ea, eb, ew});\n\t\tdiag[ea] += ew;\n\t\tdiag[eb] += ew;\n\t}\n\n\t// do the conversion to a normal ev problem\n\t// assure global connectivity\n\tfor(unsigned int i=0; i<diag.size(); i++) {\n\t\tK& v = diag[i];\n\t\tif(v == 0) {\n\t\t\t// connect the disconnected cluster to all other clusters with a very small weight\n\t\t\tv = static_cast<K>(1);\n\t\t\tK q = static_cast<K>(1) / static_cast<K>(n-1);\n\t\t\tfor(unsigned int j=0; j<i; j++) {\n\t\t\t\tauto it = std::find_if(entries.begin(), entries.end(), [i, j](const SparseEntry& e) { return e.i == i && e.j == j; });\n\t\t\t\tif(it == entries.end()) {\n\t\t\t\t\tentries.push_back(SparseEntry{i, j, q});\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor(unsigned int j=i+1; j<n; j++) {\n\t\t\t\tauto it = std::find_if(entries.begin(), entries.end(), [j, i](const SparseEntry& e) { return e.i == j && e.j == i; });\n\t\t\t\tif(it == entries.end()) {\n\t\t\t\t\tentries.push_back(SparseEntry{j, i, q});\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cerr << \"ERROR: Diagonal is 0! (i=\" << i << \")\" << std::endl;\n\t\t}\n\t\telse {\n\t\t\tv = static_cast<K>(1) / std::sqrt(v);\n\t\t}\n\t}\n\n\t// a_ij for the transformed \"normal\" EV problem\n\t//\t\tA x = \\lambda x\n\t// is computed as follow from the diagonal matrix D and the weight\n\t// matrix W of the general EV problem\n\t//\t\t(D - W) x = \\lambda D x\n\t// as follows:\n\t//\t\ta_ij = - w_ij / sqrt(d_i * d_j) if i != j\n\t//\t\ta_ii = 1\n\tfor(SparseEntry& e : entries) {\n\t\te.weight = - e.weight * diag[e.i] * diag[e.j];\n\t}\n\tfor(unsigned int i=0; i<n; i++) {\n\t\tentries.push_back(SparseEntry{i, i, static_cast<K>(1)});\n\t}\n\n\t// sort entries to form a lower triangle matrix\n\tstd::sort(entries.begin(), entries.end(), [](const SparseEntry& a, const SparseEntry& b) {\n\t\treturn (a.j != b.j) ? (a.j < b.j) : (a.i < b.i);\n\t});\n\n\treturn sgevt;\n}\n\ntemplate<typename K>\nvoid transform_gev_solution(const Eigen::Matrix<K,-1,1>& D_inv_sqrt, std::vector<EigenComponent>& ec)\n{\n\t// We have x = D^{-1/2} z (see dense_gev_to_ev)\n\t// thus x_i = z_i / \\sqrt(d_i)\n\tconst unsigned int dim = D_inv_sqrt.rows();\n\tfor(std::size_t i=0; i<ec.size(); i++) {\n\t\tec[i].eigenvector = ec[i].eigenvector.cwiseProduct(D_inv_sqrt);\n\t}\n}\n\n/** Assembles edge weights from eigenvalues and eigenvectors */\ntemplate<typename Graph>\nEigen::VectorXf ev_to_graph_weights(const Graph& graph, const std::vector<EigenComponent>& solution)\n{\n\ttypedef Eigen::Matrix<float,-1,-1> matrix_t;\n\ttypedef Eigen::Matrix<float,-1,1> vector_t;\n\tvector_t edge_weight = vector_t::Zero(boost::num_edges(graph));\n//\t// later we weight by eigenvalues\n//\t// find a positive eigenvalue (need to do this because of ugly instabilities ...\n//\tReal ew_pos = -1.0f;\n//\tfor(unsigned int i=0; ; i++) {\n//\t\tif(solver.eigenvalues()[i] > 0) {\n//\t\t\t// F IXME magic to get a not too small eigenvalue\n////\t\t\tunsigned int x = (n_used_ew + i)/2;\n//\t\t\tunsigned int x = i + 5;\n//\t\t\tew_pos = solver.eigenvalues()[x];\n//\t\t\tbreak;\n//\t\t}\n//\t}\n//\t// compute normalized weights from eigenvalues\n//\tVec weights = Vec::Zero(n_used_ew);\n//\tfor(unsigned int k=0; k<n_used_ew; k++) {\n//\t\tReal ew = solver.eigenvalues()[k + 1];\n//\t\tif(ew <= ew_pos) {\n//\t\t\tew = ew_pos;\n//\t\t}\n//\t\tweights[k] = 1.0f / std::sqrt(ew);\n//\t}\n//\tstd::cout << \"Weights = \" << weights.transpose() << std::endl;\n\t// look into first eigenvectors\n\t// skip first component\n\tfor(unsigned int k=0; k<solution.size(); k++) {\n\t\tconst EigenComponent& eigen = solution[k];\n\t\t// omit if eigenvalue is not positive\n\t\tfloat ew = eigen.eigenvalue;\n\t\t// FIXME this is due to numerical instabilities\n\t\tif(ew <= 0.0001f) {\n\t\t\tcontinue;\n\t\t}\n\t\t// weight by eigenvalue\n\t\tfloat w = 1.0f / std::sqrt(ew);\n\t\t// get eigenvector and normalize\n\t\tvector_t ev = eigen.eigenvector;\n\t\tev = (ev - ev.minCoeff() * vector_t::Ones(ev.rows())) / (ev.maxCoeff() - ev.minCoeff());\n\t\t// for each edge compute difference of eigenvector values\n\t\tvector_t e_k = vector_t::Zero(edge_weight.rows());\n\t\t// FIXME proper edge indexing\n\t\tunsigned int eid_index = 0;\n\t\tfor(auto eid : as_range(boost::edges(graph))) {\n\t\t\te_k[eid_index] = std::abs(ev[boost::source(eid, graph)] - ev[boost::target(eid, graph)]);\n\t\t\teid_index++;\n\t\t}\n#ifdef SPECTRAL_VERBOSE\n\t\tstd::cout << \"DEBUG w=\" << w << \" e_k.maxCoeff()=\" << e_k.maxCoeff() << std::endl;\n#endif\n//\t\te_k /= e_k.maxCoeff();\n//\t\tfor(unsigned int i=0; i<e_k.rows(); i++) {\n//\t\t\te_k[i] = std::exp(-e_k[i]);\n//\t\t}\n\t\te_k *= w;\n\n#ifdef SEGS_DBG_PRINT\n\t\t{\n\t\t\tstd::ofstream ofs((boost::format(\"/tmp/edge_weights_%03d.txt\") % k).str());\n\t\t\tfor(unsigned int i=0; i<e_k.rows(); i++) {\n\t\t\t\tofs << e_k[i] << std::endl;\n\t\t\t}\n\t\t}\n#endif\n\t\t//\n\t\tedge_weight += e_k;\n\t}\n\treturn edge_weight;\n}\n\ntemplate<typename K, int ROWS, int COLS>\ninline void print_matrix(std::ostream& os, const Eigen::Matrix<K,ROWS,COLS>& m)\n{\n\tfor(unsigned int j=0; j<m.rows(); j++) {\n\t\tfor(unsigned int i=0; i<m.cols(); i++) {\n\t\t\tos << m(j,i);\n\t\t\tif(i+1 == m.cols()) {\n\t\t\t\tos << \"\\n\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tos << \"\\t\";\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<typename Graph, typename EdgeWeightMap>\nstd::vector<EigenComponent> solve_dense(const Graph& graph, EdgeWeightMap edge_weights,\n\tconst std::function<std::vector<EigenComponent>(const Eigen::MatrixXf&)>& solver)\n{\n\ttypedef float K;\n\n\tDenseGev<K> gev = dense_graph_to_gev<K>(graph, edge_weights);\n#ifdef SEGS_DBG_PRINT\n\t\t{\tstd::ofstream ofs(\"/tmp/L.tsv\"); print_matrix(ofs, gev.L); }\n\t\t{\tstd::ofstream ofs(\"/tmp/D.tsv\"); print_matrix(ofs, gev.D); }\n#endif\n\n\tDenseGevTransformed<K> gevt = dense_gev_to_ev(gev);\n#ifdef SEGS_DBG_PRINT\n\t\t{\tstd::ofstream ofs(\"/tmp/A.tsv\"); print_matrix(ofs, gevt.A); }\n\t\t{\tstd::ofstream ofs(\"/tmp/D_inv_sqrt.tsv\"); print_matrix(ofs, gevt.D_inv_sqrt); }\n#endif\n\n\tstd::vector<EigenComponent> v_ec = solver(gevt.A);\n\n\ttransform_gev_solution(gevt.D_inv_sqrt, v_ec);\n\n\treturn v_ec;\n}\n\ntemplate<typename Graph, typename EdgeWeightMap>\nstd::vector<EigenComponent> solve_sparse(const Graph& graph, EdgeWeightMap edge_weights,\n\tconst std::function<std::vector<EigenComponent>(const SparseMatrix&)>& solver)\n{\n\ttypedef float K;\n\tSparseGEVT<K> sgevt = sparse_graph_entries<K>(graph, edge_weights);\n\tstd::vector<EigenComponent> v_ec = solver(sgevt.A);\n\ttransform_gev_solution(sgevt.D_inv_sqrt, v_ec);\n\treturn v_ec;\n}\n\n}}\n\n#endif\n", "meta": {"hexsha": "dbe4c91be5bb188c116f1a27e5d430300094b2b8", "size": 12217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib_dasp/lib_dasp_graphseg/spectral/spectral_impl.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_graphseg/spectral/spectral_impl.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_graphseg/spectral/spectral_impl.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": 30.3905472637, "max_line_length": 122, "alphanum_fraction": 0.6441024802, "num_tokens": 3761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.596673603662749}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::students_t::log_unnormalized_pdf.hpp    //\n//                                                                              //\n//  (C) Copyright 2009 Erwann Rogard                                            //\n//  Use, modification and distribution are subject to the                       //\n//  Boost Software License, Version 1.0. (See accompanying file                 //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)            //\n//////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_STUDENTS_T_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_STUDENTS_T_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n// #include <boost/math/policies/policy.hpp> // TODO\n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename Policy>\n    T\n    log_unnormalized_pdf(\n        const boost::math::students_t_distribution<T,Policy>& d,\n        const T& x\n    ){\n\n        typedef boost::numeric::converter<T,int> int2R_t;\n\n        T r1 = int2R_t::convert(1);\n        T r2 = int2R_t::convert(2);\n\n        T nu = d.degrees_of_freedom();\n        T m = ( nu + r1 ) / r2;\n        T y = ( x * x ) / nu;\n        return (- m ) * math::log1p(y);\n    }\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "800c4fdd3e2e25e993fd844fea0202994df2fa9d", "size": 1570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/students_t/log_unnormalized_pdf.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/students_t/log_unnormalized_pdf.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/students_t/log_unnormalized_pdf.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2926829268, "max_line_length": 96, "alphanum_fraction": 0.5458598726, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5966221637373559}}
{"text": "/* based upon http://www.boost.org/doc/libs/1_55_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html\n * Use, modification and distribution are subject to the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n * Copyright ???? 20??. */\n\n#include <iostream>\n#include <utility>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing boost::multiprecision::cpp_dec_float;\ntypedef boost::multiprecision::number<cpp_dec_float<64> > mp_type;\n\nint main(void)\n{\n    // Operations at fixed precision and full numeric_limits support:\n    mp_type b = 2;\n    std::cout << std::numeric_limits<mp_type>::digits << std::endl;\n    // Note that digits10 is the same as digits, since we're base 10! :\n    std::cout << std::numeric_limits<mp_type>::digits10 << std::endl;\n    // We can use any C++ std lib function, lets print all the digits as well:\n    std::cout << std::setprecision(std::numeric_limits<mp_type>::max_digits10) << log(b) << std::endl; // print log(2)\n    // We can also use any function from Boost.Math:\n    std::cout << boost::math::tgamma(b) << std::endl;\n    // These even work when the argument is an expression template:\n    std::cout << boost::math::tgamma(b * b) << std::endl;\n    // And since we have an extended exponent range we can generate some really large numbers here (4.0238726007709377354370243e+2564):\n    std::cout << boost::math::tgamma(mp_type(1000)) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "c14c974d847e29c965707f5fd2a10ab309e9d072", "size": 1609, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boost/tgamma.cc", "max_stars_repo_name": "jeffhammond/multiprecision", "max_stars_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T16:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:24:15.000Z", "max_issues_repo_path": "boost/tgamma.cc", "max_issues_repo_name": "jeffhammond/multiprecision", "max_issues_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/tgamma.cc", "max_forks_repo_name": "jeffhammond/multiprecision", "max_forks_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T23:27:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:27:36.000Z", "avg_line_length": 47.3235294118, "max_line_length": 135, "alphanum_fraction": 0.7128651336, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5966221524492171}}
{"text": "\n#include <iostream>\n#include \"EigenMatrix.h\"\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> ColumnVector;\ntypedef Eigen::Matrix<double, 1, Eigen::Dynamic> RowVector;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n\nColumnVector* CastToColumnVector(void* ptr);\n\nColumnVector* NewColumnVector();\n\nColumnVector* NewColumnVector(const ColumnVector& v);\n\nRowVector* CastToRowVector(void* ptr);\n\nRowVector* NewRowVector();\n\nRowVector* NewRowVector(const RowVector& v);\n\nvoid* EigenMatrix_Create(int rows, int columns)\n{\n\tauto m = new Matrix(rows, columns);\n\tfor (int y = 0; y < columns; y++)\n\t\tfor (int x = 0; x < rows; x++)\n\t\t\t(*m)(x, y) = 0;\n\n\treturn m;\n}\n\nvoid* EigenMatrix_CreateIdentity(int rows, int columns)\n{\n\tauto m = new Matrix(rows, columns);\n\tfor (int y = 0; y < columns; y++)\n\t{\n\t\tfor (int x = 0; x < rows; x++)\n\t\t{\n\t\t\tif (x == y)\n\t\t\t\t(*m)(x,y) = 1;\n\t\t\telse\n\t\t\t\t(*m)(x, y) = 0;\n\t\t}\n\t}\n\n\treturn m;\n}\n\nvoid EigenMatrix_Release(void* ptr)\n{\n\tauto obj = static_cast<Matrix*>(ptr);\n\tif (obj != nullptr)\n\t{\n\t\tdelete obj;\n\t\tobj = nullptr;\n\t}\n}\n\nMatrix* CastToMatrix(void* ptr)\n{\n\treturn static_cast<Matrix*>(ptr);\n}\n\nMatrix* NewMatrix(const Matrix& m)\n{\n\treturn new Matrix(m.rows(), m.cols());\n}\n\nMatrix* NewMatrix()\n{\n\treturn new Matrix();\n}\n\nint EigenMatrix_Rows(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn (int)m->rows();\n}\n\nint EigenMatrix_Columns(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn (int)m->cols();\n}\n\ndouble EigenMatrix_GetXY(void* ptr, int x, int y)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn (*m)(x, y);\n}\n\nvoid EigenMatrix_SetXY(void* ptr, int x, int y, double value)\n{\n\tauto m = CastToMatrix(ptr);\n\t(*m)(x, y) = value;\n}\n\ndouble EigenMatrix_GetX(void* ptr, int x)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn (*m)(x);\n}\n\nvoid EigenMatrix_SetX(void* ptr, int x, double value)\n{\n\tauto m = CastToMatrix(ptr);\n\t(*m)(x) = value;\n}\n\nvoid* EigenMatrix_Transpose(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->transpose();\n\treturn m2;\n}\n\nvoid* EigenMatrix_Conjugate(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->conjugate();\n\treturn m2;\n}\n\nvoid* EigenMatrix_Adjoint(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->adjoint();\n\treturn m2;\n}\n\nvoid* EigenMatrix_Inverse(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->inverse();\n\treturn m2;\n}\n\nBOOL EigenMatrix_IsInvertible(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tEigen::FullPivLU<Matrix> lu(*m);\n\n\treturn lu.isInvertible();\n}\n\nvoid* EigenMatrix_TryInverse(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\tEigen::FullPivLU<Matrix> lu(*m);\n\n\tif (lu.isInvertible())\n\t{\n\t\tauto inv = NewMatrix();\n\t\t(*inv) = lu.inverse();\n\t\treturn inv;\n\t}\n\telse\n\t{\n\t\treturn nullptr;\n\t}\n}\n\ndouble EigenMatrix_Determinant(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->determinant();\n}\n\ndouble EigenMatrix_Trace(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->trace();\n}\n\nBOOL EigenMatrix_IsIdentity(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->isIdentity();\n}\n\nBOOL EigenMatrix_IsDiagonal(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->isDiagonal();\n}\n\nBOOL EigenMatrix_IsUpperTriangular(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->isUpperTriangular();\n}\n\nBOOL EigenMatrix_IsLowerTriangular(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\treturn m->isLowerTriangular();\n}\n\nvoid* EigenMatrix_MulScalar(void* ptr1, double s)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto m = NewMatrix(*m1);\n\t(*m) = (*m1) * s;\n\treturn m;\n}\n\nvoid* EigenMatrix_DivideScalar(void* ptr1, double s)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto m = NewMatrix(*m1);\n\t(*m) = (*m1) / s;\n\treturn m;\n}\n\nvoid* EigenMatrix_MulMatrix(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto m2 = CastToMatrix(ptr2);\n\tauto m = NewMatrix(*m1);\n\t(*m) = (*m1) * (*m2);\n\treturn m;\n}\n\nvoid* EigenMatrix_AddMatrix(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto m2 = CastToMatrix(ptr2);\n\tauto m = NewMatrix(*m1);\n\t(*m) = (*m1) + (*m2);\n\treturn m;\n}\n\nvoid* EigenMatrix_SubMatrix(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto m2 = CastToMatrix(ptr2);\n\tauto m = NewMatrix(*m1);\n\t(*m) = (*m1) - (*m2);\n\treturn m;\n}\n\nvoid* EigenMatrix_MulColumnVector(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto v2 = CastToColumnVector(ptr2);\n\tauto v = NewColumnVector(*v2);\n\t(*v) = (*m1) * (*v2);\n\treturn v;\n}\n\nvoid* EigenMatrix_MulRowVector(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto v2 = CastToRowVector(ptr2);\n\tauto v = NewRowVector(*v2);\n\t(*v) = (*m1) * (*v2);\n\treturn v;\n}\n\nvoid* EigenMatrix_Block(void* ptr, int startRox, int startCol, int blockRows, int blockCols)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->block(startRox, startCol, blockRows, blockCols);\n\treturn m2;\n}\n\nvoid* EigenMatrix_Reshaped(void* ptr, int rows, int cols)\n{\n\tauto m = CastToMatrix(ptr);\n\tauto m2 = NewMatrix();\n\t(*m2) = m->reshaped(rows, cols);\n\treturn m2;\n}\n\nvoid* EigenMatrix_ColPivHouseholderQr_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->colPivHouseholderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_ColPivHouseholderQr_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->colPivHouseholderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_PartialPivLu_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->partialPivLu().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_PartialPivLu_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->partialPivLu().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_FullPivLu_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->fullPivLu().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_FullPivLu_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->fullPivLu().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_HouseholderQr_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->householderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_HouseholderQr_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->householderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_LLT_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->llt().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_LLT_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->llt().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_LDLT_Vec(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m1->ldlt().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_LDLT_Mat(void* ptr1, void* ptr2)\n{\n\tauto m1 = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m1->ldlt().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_BdcSvd_Vec(void* ptr1, void* ptr2, int options)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->bdcSvd(options).solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_BdcSvd_Mat(void* ptr1, void* ptr2, int options)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->bdcSvd(options).solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_JacobiSvd_Vec(void* ptr1, void* ptr2, int options)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->jacobiSvd(options).solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_JacobiSvd_Mat(void* ptr1, void* ptr2, int options)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->jacobiSvd(options).solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_FullPivHouseholderQr_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->fullPivHouseholderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_FullPivHouseholderQr_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->fullPivHouseholderQr().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_CompleteOrthogonalDecomposition_Vec(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToColumnVector(ptr2);\n\tauto x = NewColumnVector();\n\n\t(*x) = m->completeOrthogonalDecomposition().solve(*v);\n\treturn x;\n}\n\nvoid* EigenMatrix_CompleteOrthogonalDecomposition_Mat(void* ptr1, void* ptr2)\n{\n\tauto m = CastToMatrix(ptr1);\n\tauto v = CastToMatrix(ptr2);\n\tauto x = NewMatrix();\n\n\t(*x) = m->completeOrthogonalDecomposition().solve(*v);\n\treturn x;\n}\n\ndouble EigenMatrix_RelativeError_Vec(void* ptr1, void* ptr2, void* ptr3)\n{\n\tauto A = CastToMatrix(ptr1);\n\tauto b = CastToColumnVector(ptr2);\n\tauto x = CastToColumnVector(ptr3);\n\n\treturn ((*A) * (*x) - (*b)).norm() / b->norm();\n}\n\ndouble EigenMatrix_RelativeError_Mat(void* ptr1, void* ptr2, void* ptr3)\n{\n\tauto A = CastToMatrix(ptr1);\n\tauto b = CastToMatrix(ptr2);\n\tauto x = CastToMatrix(ptr3);\n\n\treturn ((*A) * (*x) - (*b)).norm() / b->norm();\n}\n\nvoid* EigenMatrix_Eigenvalues(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\n\tEigen::SelfAdjointEigenSolver<Matrix> solver(*m);\n\n\tif (solver.info() != Eigen::Success)\n\t\treturn nullptr;\n\telse\n\t{\n\t\tauto x = NewColumnVector();\n\t\t(*x) = solver.eigenvalues();\n\n\t\treturn x;\n\t}\n}\n\nvoid* EigenMatrix_Eigenvectors(void* ptr)\n{\n\tauto m = CastToMatrix(ptr);\n\n\tEigen::SelfAdjointEigenSolver<Matrix> solver(*m);\n\n\tif (solver.info() != Eigen::Success)\n\t\treturn nullptr;\n\telse\n\t{\n\t\tauto x = NewMatrix();\n\t\t(*x) = solver.eigenvectors();\n\n\t\treturn x;\n\t}\n}\n\nBOOL EigenMatrix_EigenValuesVectors(void* ptr, void** values, void** vectors)\n{\n\tauto m = CastToMatrix(ptr);\n\n\tEigen::SelfAdjointEigenSolver<Matrix> solver(*m);\n\t*values = nullptr;\n\t*vectors = nullptr;\n\n\tif (solver.info() != Eigen::Success)\n\t{\n\t\treturn FALSE;\n\t}\n\telse\n\t{\n\t\tauto _values = solver.eigenvalues();\n\t\tauto _vectors = solver.eigenvectors();\n\n\t\tauto v = NewColumnVector(_values);\n\t\tfor (auto i = 0; i < _values.size(); i++)\n\t\t\t(*v)[i] = _values[i];\n\n\t\tauto m = NewMatrix(_vectors);\n\t\tfor (auto i = 0; i < _vectors.size(); i++)\n\t\t\t(*m)(i) = _vectors(i);\n\n\t\t(*values) = v;\n\t\t(*vectors) = m;\n\n\t\treturn TRUE;\n\t}\n}\n\n\n\n", "meta": {"hexsha": "fa5441ddcb00ce1680bfcf43c7dcb06517bdcbab", "size": 10777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGALWrapper/Eigen/EigenMatrix.cpp", "max_stars_repo_name": "unitycoder/CGALDotNet", "max_stars_repo_head_hexsha": "90682724a55aec2818847500047d4785aa7e1d67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CGALWrapper/Eigen/EigenMatrix.cpp", "max_issues_repo_name": "unitycoder/CGALDotNet", "max_issues_repo_head_hexsha": "90682724a55aec2818847500047d4785aa7e1d67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CGALWrapper/Eigen/EigenMatrix.cpp", "max_forks_repo_name": "unitycoder/CGALDotNet", "max_forks_repo_head_hexsha": "90682724a55aec2818847500047d4785aa7e1d67", "max_forks_repo_licenses": ["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.0070546737, "max_line_length": 92, "alphanum_fraction": 0.6677182889, "num_tokens": 3452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5965195591437248}}
{"text": "#include <complex>\n//#include <fftw3.h>\n#include <math.h>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <blitz/array.h>\n#include \"lapack.hpp\"\n\n//#define MKL_Complex16 std::complex<double>\n//#define lapack_int int\n//#define lapack_complex_double std::complex<double>\n//#include \"mkl_lapacke.h\"\n\n\n#include \"formats/gnuplot.hpp\"\n#include \"types.hpp\"\n#include \"io.hpp\"\n\ntypedef std::complex<double> cmplx; \n\n\nvoid printMatrix(const std::vector<cmplx>& matrix){\n    size_t n = sqrt(matrix.size());\n    std::vector<cmplx>::const_iterator it = matrix.begin();\n    for(size_t i = 0; i < n; ++i){\n        std::cout << \" | \";\n        for(size_t j = 0; j < n; ++j){\n            fprintf( stdout, \" %+2.2f %+2.2f i \", real(*it), imag(*it));\n            ++it;\n        }\n        std::cout << \" | \\n\";\n    }\n    std::cout << std::endl;\n}\nvoid printVector(const std::vector<cmplx>& line){\n    size_t n = line.size();\n    std::vector<cmplx>::const_iterator it = line.begin();\n        std::cout << \" | \";\n        for(size_t j = 0; j < n; ++j){\n            fprintf( stdout, \" %+2.2f %+2.2f i \", real(*it), imag(*it));\n            ++it;\n        }\n        std::cout << \" | \\n\";\n    std::cout << std::endl;\n}\n\n// Handcoded 1d DFT on a 2d function\nvoid r2c1dz_code_v2(){\n    size_t N = 2300;\n    // v1: N = 10 000 needed 7.5 GB RES MEM and 15 minutes (infinijazz node)\n    \n    // Here we generate a 2d function input(x,z) = input[x+z*N]\n    // that decays in z like exp(-kz z) where kz = sqrt(2E + kx^2)   \n    // We CHOOSE kx = 1/N and want kz=2/N => E = 3/2 /N/N\n    // Goal: Obtain the Fourier coefficients of this function in x,\n    //  no matter at which z we give the function.\n    double kx = 1.0/N;\n    double E  = 1.5/N/N;\n    double kz = sqrt(2 * E + kx*kx); // = 2/N\n\n    std::vector< cmplx > input;\n    for(int z = 0; z < N; ++z) {\n        for(int x = 0; x < N; ++x){\n            input.push_back( sin(2.0 * M_PI *x * kx)*exp(-kz*z)  );\n        }\n    }\n    //printMatrix(input); \n\n\n    std::vector< int > st (N);   // z-indices, where we know f\n    std::vector<cmplx> f  (N);   // the function value f at these points\n\n    for(int i = 0; i < N; ++i) {\n         st[i] = i % 70;              // lets say we know f on a \"stair\" \n         f[i]  = input[ i + N* st[i]];\n    }\n    \n    // Build matrix for modified Fourier transform\n    // now need transposed matrix\n    std::vector<cmplx> matrix (N*N);\n    int ir, jr;\n    double k;\n    for(int i =0; i < N; ++i){\n        ir = (2*i < N)? i : i-N;\n        for(int j=0; j < N; ++j){\n            jr = (2*j < N)? j : j-N;\n            k = double(jr)/N;\n            //double k = double(j)/N ;\n            matrix[i + j*N] = \n                exp( 2.0 * M_PI * cmplx(0,1) * double(ir) * k\n                     - sqrt( 2*E + k*k) * st[i]);\n\n        }\n    }\n    //printMatrix(matrix);\n\n    // Invert this fucker\n    int one=1;\n    int info;\n    int n = N;\n    std::vector< int > ipiv (N);   // z-indices, where we know f\n    std::cout << \"Before inverse\" << std::endl;\n    zgesv_(&n, &one, &*matrix.begin(), &n, &*ipiv.begin(), &*f.begin(), &n, &info);\n\n    //printVector(coeff); \n    std::cout << \" coeff[1] \" << f[1] << \" coeff[2] \" << f[2];\n    std::cout << \" coeff[N-2] \" << f[N-2] << \" coeff[N-1] \" << f[N-1];\n    \n    std::vector<double> coeffReal;\n    std::vector<cmplx>::const_iterator it = f.begin(), end = f.end();\n    while(it!=end){ coeffReal.push_back( abs(*it)); ++it; } \n    types::String s = formats::gnuplot::writeMatrix(coeffReal, N, 1);\n    io::writeStream(\"fourier\", s);\n\n}    \n\n\n// Handcoded 1d DFT on a 2d function\nvoid r2c1dz_code(){\n    size_t N = 10000;\n    // v1: N = 10 000 needed 7.5 GB RES MEM and 15 minutes (infinijazz node)\n    \n    // Here we generate a 2d function input(x,z) = input[x+z*N]\n    // that decays in z like exp(-kz z) where kz = sqrt(2E + kx^2)   \n    // We CHOOSE kx = 1/N and want kz=2/N => E = 3/2 /N/N\n    // Goal: Obtain the Fourier coefficients of this function in x,\n    //  no matter at which z we give the function.\n    double kx = 1.0/N;\n    double E  = 1.5/N/N;\n    double kz = sqrt(2 * E + kx*kx); // = 2/N\n\n    std::vector< cmplx > input;\n    for(int z = 0; z < N; ++z) {\n        for(int x = 0; x < N; ++x){\n            input.push_back( sin(2.0 * M_PI *x * kx)*exp(-kz*z)  );\n        }\n    }\n    //printMatrix(input); \n\n\n    std::vector< int > st (N);   // z-indices, where we know f\n    std::vector<cmplx> f  (N);   // the function value f at these points\n\n    for(int i = 0; i < N; ++i) {\n         st[i] = i;              // lets say we know f on a \"stair\" \n         f[i]  = input[ i + N* st[i]];\n    }\n    \n    // Build matrix for modified Fourier transform\n    std::vector<cmplx> matrix (N*N);\n    for(int i =0; i < N; ++i)\n        for(int j=0; j < N; ++j){\n            double k = (2*j < N)? double(j)/N : (double(N) - j)/N;\n            matrix[i*N+j] = \n                exp( 2.0 * M_PI * cmplx(0,1) * double(i) * double(j)/double(N) \n                     - sqrt( 2*E + k*k) * st[i]);\n\n        }\n    //printMatrix(matrix);\n\n    // Invert this fucker\n    std::vector<cmplx> inverse(N*N);\n    std::cout << \"Before inverse\" << std::endl;\n    //MatrixComplexInverse(&inverse[0],&matrix[0],  N);     \n    //printMatrix(inverse);\n    std::cout << \"afterinverse\";\n\n    // Obtain Fourier coefficients\n    std::vector<cmplx> coeff(N, 0.0);\n\n    for (int i = 0; i<N; ++i){\n        for(int j = 0; j < N; ++j){\n            coeff[i] += inverse[i*N + j] * f[j];\n        }\n    }\n    //printVector(coeff); \n    std::cout << \" coeff[1] \" << coeff[1] << \" coeff[N-1] \" << coeff[N-1];\n\n}    \n    \n// Handcoded 2d DFT on a 3d function\nvoid r2c2dz_code(){\n    size_t nX = 32;\n    size_t nY = 62;\n    size_t N = nX * nY;\n     \n    // Here we generate a 3d function input(x,y,z) = input[x+y*N+z*N*N]\n    // that decays in z like exp(-kz z) where kz = sqrt(2E + kx^2 + ky^2)   \n    // We CHOOSE kx = 1/N = ky and want kz=2/N => E = 1/N/N\n    // Goal: Obtain the Fourier coefficients of this function in x,\n    //  no matter at which z we give the function.\n    double kx = 1.0/nX;\n    double ky = 1.0/nY;\n    double E  = 1.0/N;\n    double kz = sqrt(2 * E + kx*kx + ky*ky); // = 2/N\n\n    std::vector< int > st (N);   // z-indices, where we know f\n    std::vector<cmplx> f  (N);   // the function value f at these points\n\n    for(int x = 0; x < nX; ++x) {\n        for(int y = 0; y < nY; ++y) {\n         st[x*nY + y] = 0;              // lets say we know f on a \"stair\" \n         f[x*nY + y]  = sin(2.0 * M_PI *( x*kx + y*ky)) * exp(-kz* double(st[x*nY + y]));\n         //f[x*nY + y]  = 1.0;\n        }\n    }\n                                                                    \n    std::vector<double> func;\n    std::vector<cmplx>::const_iterator it = f.begin(), end = f.end();\n    while(it!=end){ func.push_back( abs(*it)); ++it; } \n    types::String s2 = formats::gnuplot::writeMatrix(func, nX, nY);\n    io::writeStream(\"function\", s2);\n\n\n    // Build matrix for modified Fourier transform\n    std::vector<cmplx> A(N*N);\n    \n    \n    int iX, iY, jX, jY;\n    double kX, kY, kZ;\n    for(int i = 0; i < N; ++i){\n            iX = i / nY; iY = i % nY;\n            std::cout << \"(\" << iX << \",\" << iY << \"): \";\n        for(int j = 0; j < N; ++j){\n\n            jX = j / nY; jY = j % nY;\n            //std::cout << \"(\" << jX << \",\" << jY << \"), \";\n            kX = ( 2* jX > nX) ? (double(jX) - double(nX))/ double(nX) : double(jX) / double(nX);\n            kY = ( 2* jY > nY) ? (double(jY) - double(nY))/ double(nY) : double(jY) / double(nY);\n\n            kZ = sqrt( 2 * E + kX * kX + kY * kY);\n            //std::cout << ( double(iX) * kX + \n            //          double(iY) * kY ) << \" \";\n            // Need transposed matrix for Fortran lapack\n            A[i + j*N ] = exp( \n                    2.0 * M_PI * cmplx(0,1) * \n                    ( double(iX) * kX + \n                      double(iY) * kY )\n                    - kZ * st[i]  );\n            //                std::cout << A[i + j*n] << \" \";\n\n        }\n        std::cout << std::endl;\n        //          std::cout << \"\\n\";\n\n    }\n    //printMatrix(A);\n\n    // Variant1: Solve linear system\n    int one=1;\n    int info;\n    int n = N;\n    std::vector< int > ipiv (N);   //permutationmatrix\n    std::cout << \"Before inverse\" << std::endl;\n    zgesv_(&n, &one, &*A.begin(), &n, &*ipiv.begin(), &*f.begin(), &n, &info);\n    if (info != 0) std::cout << \"Error: \" << info << \"\\n\"; \n//    // Variant1b: With lapacke interface\n//    int one=1;\n//    int n = N;\n//    std::vector< int > ipiv (N);   //permutationmatrix\n//    std::cout << \"Before inverse\" << std::endl;\n//    int info = LAPACKE_zgesv(LAPACK_ROW_MAJOR, n, one, &*A.begin(), n, &*ipiv.begin(), &*f.begin(), n);\n\n//    // Variant2: Invert this fucker\n//    std::vector<cmplx> inverse(N*N);\n//    std::cout << \"Before inverse\" << std::endl;\n//    MatrixComplexInverse(&inverse[0],&A[0],  N);     \n//\n//    for(int j = 0; j < N; ++j){\n//       f[j] = 0;\n//       for(int i = 0; i < N; ++i){\n//           // Need transposed matrix for Fortran lapack\n//           f[j] += inverse[j*N + i];\n//       }\n//   }\n//\n    std::cout << \"afterinverse\";\n//    \n    \n    \n    std::vector<double> coeffReal;\n    std::vector<cmplx>::const_iterator itf = f.begin(), endf = f.end();\n    while(itf!=endf){ coeffReal.push_back( abs(*itf)); ++itf; } \n    types::String s = formats::gnuplot::writeMatrix(coeffReal, nX, nY);\n    io::writeStream(\"fourier2d\", s);\n\n    //    // Invert this fucker\n//    std::vector<cmplx> inverse(N*N);\n//    MatrixComplexInverse(&inverse[0],&matrix[0],  N);     \n//    //printMatrix(inverse);\n//\n//    // Obtain Fourier coefficients\n//    std::vector<cmplx> coeff(N, 0.0);\n//\n//    for (int i = 0; i<N; ++i){\n//        for(int j = 0; j < N; ++j){\n//            coeff[i] += inverse[i*N + j] * f[j];\n//        }\n//    }\n//    printVector(coeff); \n//\n}    \n\nint main() {\n//  r2c1dz_code();\n//  r2c1dz_code_v2();\n    r2c2dz_code();\n    return 0;\n}\n", "meta": {"hexsha": "56dfc964390b0e8e685a0adc891059c898c01246", "size": 9947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lap.cpp", "max_stars_repo_name": "ltalirz/util-programs", "max_stars_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_stars_repo_licenses": ["MIT"], "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/lap.cpp", "max_issues_repo_name": "ltalirz/util-programs", "max_issues_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/lap.cpp", "max_forks_repo_name": "ltalirz/util-programs", "max_forks_repo_head_hexsha": "93c76cb8f52543b55afdd968f6d8374997031a27", "max_forks_repo_licenses": ["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.9839228296, "max_line_length": 105, "alphanum_fraction": 0.4893937871, "num_tokens": 3371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301018, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.5965195342409767}}
{"text": "#include \"geometry.h\"\n#include <Eigen/LU>\n#include <Eigen/Geometry>\nusing namespace Eigen;\nnamespace marvel {\ndouble clo_surf_vol(const MatrixXd& nods, const MatrixXi& surf)\n{\n    //TODO:check if the surface is closed and manifold\n    double volume = 0;\n    for (size_t i = 0; i < surf.cols(); ++i)\n    {\n        Matrix3d tet;\n        for (size_t j = 0; j < 3; ++j)\n        {\n            tet.row(j) = nods.col(surf(j, i));\n        }\n        //TODO:check\n        volume += tet.determinant();\n    }\n\n    return volume;\n}\n\nint build_bdbox(const MatrixXd& nods, MatrixXd& bdbox)\n{\n    //simple bounding box\n    //bounding box is a dimension * 2 matrix, whose first column is minimal value and second column is maximal value.\n    bdbox = nods.col(0) * MatrixXd::Ones(1, 2);\n    for (size_t i = 0; i < nods.cols(); ++i)\n    {\n        for (size_t j = 0; j < nods.rows(); ++j)\n        {\n            if (bdbox(j, 0) > nods(j, i))\n                bdbox(j, 0) = nods(j, i);\n            if (bdbox(j, 1) < nods(j, i))\n                bdbox(j, 1) = nods(j, i);\n        }\n    }\n    return 0;\n}\n\n}  // namespace marvel\n", "meta": {"hexsha": "f6fd8f1d077ed418bfe168674b7ff5d338bf86d1", "size": 1103, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Geometry/geometry.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/Geometry/geometry.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/Geometry/geometry.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": 25.6511627907, "max_line_length": 117, "alphanum_fraction": 0.53762466, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5965147983877737}}
{"text": "#include <NTL/ZZX.h>\n\nusing namespace std;\nusing namespace NTL;\n\nvoid inner(int i, ZZX& t, Vec<ZZX>& phi)\n{\n        for (long j = 1; j <= i-1; j++)\n         if (i % j == 0)\n            t *= phi(j);\n}\n\nvoid outer(int i, Vec<ZZX>& phi)\n{\n        ZZX t;\n        t = 1;\n        inner(i, t, phi);\n        phi(i) = (ZZX(INIT_MONO, i) - 1)/t;\n        cout << phi(i) << \"\\n\";\n}\n\nint main()\n{\n   Vec<ZZX> phi(INIT_SIZE, 100);\n\n   for (long i = 1; i <= phi.length(); i++) {\n      outer(i, phi);\n   }\n}\n", "meta": {"hexsha": "e7cad16799841e494e2a7b492efdad14f2e0fc6a", "size": 492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2017/05/perf_test/test.cpp", "max_stars_repo_name": "NanXiao/code-for-my-blog", "max_stars_repo_head_hexsha": "c2c4f59e438241696d938354bb14396f36f97748", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T21:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:04:14.000Z", "max_issues_repo_path": "2017/05/perf_test/test.cpp", "max_issues_repo_name": "NanXiao/code-for-my-blog", "max_issues_repo_head_hexsha": "c2c4f59e438241696d938354bb14396f36f97748", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2017/05/perf_test/test.cpp", "max_forks_repo_name": "NanXiao/code-for-my-blog", "max_forks_repo_head_hexsha": "c2c4f59e438241696d938354bb14396f36f97748", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T18:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T02:40:42.000Z", "avg_line_length": 16.4, "max_line_length": 45, "alphanum_fraction": 0.4471544715, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5964957760238091}}
{"text": "#include <algorithm>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <numeric>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\nint main(int argc, char *argv[]) {\r\n\tvector<cpp_int> nums;\r\n\tstring base = \"0123456789\";\r\n\tdo {\r\n\t\t// Convert to integers.\r\n\t\tint a = stoull(base.substr(1, 3));\r\n\t\tint b = stoull(base.substr(2, 3));\r\n\t\tint c = stoull(base.substr(3, 3));\r\n\t\tint d = stoull(base.substr(4, 3));\r\n\t\tint e = stoull(base.substr(5, 3));\r\n\t\tint f = stoull(base.substr(6, 3));\r\n\t\tint g = stoull(base.substr(7, 3));\r\n\t\tif((a % 2 == 0) && (b % 3 == 0) && (c % 5 == 0) && (d % 7 == 0) && (e % 11 == 0) && (f % 13 == 0) && (g % 17 == 0)) {\r\n\t\t\tnums.push_back((cpp_int)stoull(base));\r\n\t\t}\r\n\t} while(next_permutation(base.begin(), base.end()));\r\n\tcpp_int sum = 0;\r\n\tfor(const auto &n : nums) {\r\n\t\tsum += n;\r\n\t}\r\n\tcout << sum << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "81defe5efd2f0ed797e47949e8dc5f3d7ea874f7", "size": 927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/43/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/43/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/1-50/43/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 28.0909090909, "max_line_length": 120, "alphanum_fraction": 0.5717367853, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541626630935, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5964533984329897}}
{"text": "/*\n This program is free software; you can redistribute it and/or modify it under\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\n the European Commission.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\n for more details.\n\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\n along with this program.\n\n Further information about the European Union Public Licence - EUPL v.1.1 can\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\n\n*/\n\n/*\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\n*/\n\n\n\n//\n//------------------ Author:       Guillermo Ortega               -------------------\n//------------------ Affiliation:  European Space Agency (ESA)    -------------------\n//-----------------------------------------------------------------------------------\n\n\n#include<float.h>\n#include<math.h>\n#include<stdio.h>\n\n\n/////////////////////////////////////////////////////////////////////////////////////////\n// Description: \n//      This function transforms spacecraft Keplerian \n//      orbital elements in cartesian orbital elements \n//\n// Input: \n//\tmu\tstandard gravitational parameter of the planet/moon\n//\ta  semi-major axis (km)\n//      ec eccentricity (-)\n//      i inclination (rad)\n//      w0 argument of the perigee (rad)\n//      o0  right ascention of the ascending node (rad)\n//      m0 mean anomaly (rad)\n//\n// Output:\n//\tx  x-coordinate in ECI system (km)\n//      y  y-coordinate in ECI system (km)\n//      z  z-coordinate in ECI system (km)\n//      xd vx-coordinate in ECI system (km/s)\n//      yd vy-coordinate in ECI system (km/s)\n//      zd vz-coordinate in ECI system (km/s)\n//\t\n// Example of call:\n//      orbitalTOcartesian(500,0,56,0,0,0,x,y,z,vx,vy,vz); \n//\n// Date: October 2006\n// Version: 1.0\n// Change history:\n//\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include \"orbitalTOcartesian.h\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n\nusing namespace sta;\nusing namespace Eigen;\nusing namespace std;\n\n\n/**\n * Description:\n *      This function transforms spacecraft Keplerian\n *      orbital elements in cartesian orbital elements\n *\n *\n * @param\tmu\tstandard gravitational parameter of the planet/moon\n * @param a  semi-major axis (km)\n * @param ec eccentricity (-)\n * @param i inclination (rad)\n * @param w0 argument of the perigee (rad)\n * @param o0  right ascention of the ascending node (rad)\n * @param m0 mean anomaly (rad)\n *\n * @return Cartesian state vector in the same coordinate system as the orbital elements\n *         Units are km for position and km/s for velocity.\n *\n*/\nsta::StateVector orbitalTOcartesian(double mu, double a, double ec, double i, double w0, double o0, double m0)\n{\n    // Declaring needed variables\n    double n0, eca, diff, eps, ceca, seca, e1, xw, yw, edot, xdw, ydw, cw;\n    double sw, so, co, si, ci, swci, cwci, px, py, pz, qx, qy, qz;\n    // end of varibales declaration\n\n    n0= sqrt(mu/(a*a*a));\n    eca= m0+(ec/2.0);\n    diff=10000.0;\n    eps=.000001;\n    while (diff>eps)\n    {\n            e1=eca-(eca-ec*sin(eca)-m0)/(1-ec*cos(eca));\n            diff=fabs(e1-eca);  //Carefull: is FABS for a floating value!\n            eca=e1;\n    }; // from while\n    ceca=cos(eca);\n    seca=sin(eca);\n    e1=a*sqrt(1-ec*ec);\n    xw=a*(ceca-ec);\t\t// printf(\"xw: %5e\\n\", xw);\n    yw=e1*seca;\n    edot=sqrt(mu/a)/(a*(1-ec*ceca));\n    xdw=-a*edot*seca;\n    ydw=e1*edot*ceca;\n    cw = cos(w0); sw=sin(w0); co=cos(o0); so=sin(o0);\n    ci=cos(i); si=sin(i); swci=sw*ci; cwci=cw*ci;\n    px=cw*co-so*swci; py=cw*so+co*swci; pz=sw*si;\t// printf(\"px: %5e\\n\", px);\n    qx=-sw*co-so*cwci; qy=-sw*so+co*cwci; qz=cw*si;\n\n    Vector3d position(xw*px+yw*qx, xw*py+yw*qy, xw*pz+yw*qz);\n    Vector3d velocity(xdw*px+ydw*qx, xdw*py+ydw*qy, xdw*pz+ydw*qz);\n\n    return StateVector(position, velocity);\n}\n\n\n/**\n * This function transforms spacecraft Keplerian\n * orbital elements to a cartesian state vector in the same reference frame.\n *\n * @param mu standard gravitational parameter of the planet/moon\n * @param elements Keplerian orbital elements, with angles in radians and SMA in km\n *\n * @return Cartesian state vector in the same coordinate system as the orbital elements\n *         Units are km for position and km/s for velocity.\n *\n */\nsta::StateVector orbitalTOcartesian(double mu, KeplerianElements elements)\n\n{\n    double a = elements.SemimajorAxis;\n    double m0 = elements.MeanAnomaly;\n\n    double eca = m0 + (elements.Eccentricity / 2.0);\n\n    double diff = 10000.0;\n    double eps = 0.000001;\n    double e1 = 0.0;\n\n    // Solve Kepler's equation with the standard iteration\n    while (diff > eps)\n    {\n        e1 = eca - (eca - elements.Eccentricity * sin(eca) - m0) / (1 - elements.Eccentricity * cos(eca));\n        diff = std::abs(e1-eca);\n        eca = e1;\n    }\n\n    double ceca = cos(eca);\n    double seca = sin(eca);\n    e1 = a * sqrt(1 - elements.Eccentricity * elements.Eccentricity);\n    double xw = a * (ceca - elements.Eccentricity);\n    double yw = e1 * seca;\n\n    double edot = sqrt(mu / a) / (a * (1 - elements.Eccentricity * ceca));\n    double xdw = -a * edot * seca;\n    double ydw = e1 * edot * ceca;\n\n    Quaterniond rotation = Quaterniond(AngleAxis<double>(elements.AscendingNode,       Vector3d::UnitZ())) *\n                           Quaterniond(AngleAxis<double>(elements.Inclination,         Vector3d::UnitX())) *\n                           Quaterniond(AngleAxis<double>(elements.ArgumentOfPeriapsis, Vector3d::UnitZ()));\n    Vector3d position = rotation * Vector3d(xw, yw, 0.0);\n    Vector3d velocity = rotation * Vector3d(xdw, ydw, 0.0);\n\n    return StateVector(position, velocity);\n}\n", "meta": {"hexsha": "ec98681f986a03aa21c1be9ad523b8ad1065d31a", "size": 5943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/orbitalTOcartesian.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/orbitalTOcartesian.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/orbitalTOcartesian.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": 32.8342541436, "max_line_length": 110, "alphanum_fraction": 0.6124852768, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.596453396358714}}
{"text": "#pragma once\n#include \"KDTree.hpp\"\n#include \"../util/DistanceFuncs.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/SpectralEmbedding.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <cassert>\n#include <cmath>\n#include <random>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n\nnamespace fluid {\nnamespace algorithm {\n\nstruct UMAPEmbeddingParamsFunctor\n{\n  typedef double Scalar;\n  enum {\n    InputsAtCompileTime = 2,\n    ValuesAtCompileTime = 300 // from UMAP python implementation\n  };\n  typedef Eigen::VectorXd InputType;\n  typedef Eigen::VectorXd ValueType;\n  typedef Eigen::MatrixXd JacobianType;\n\n  UMAPEmbeddingParamsFunctor(double minDist, double spread = 1.0)\n  {\n    mX = Eigen::ArrayXd::LinSpaced(values(), 0, 3 * spread);\n    mY = (mX <= minDist).select(1, ((-mX + minDist) / spread).exp());\n  }\n\n  int operator()(const Eigen::VectorXd& x, Eigen::VectorXd& fvec) const\n  {\n    fvec = mY - (1 / (1 + x(0) * mX.pow(2 * x(1))));\n    return 0;\n  }\n\n  int values() const { return ValuesAtCompileTime; }\n  int inputs() const { return InputsAtCompileTime; }\n\n  Eigen::ArrayXd mX;\n  Eigen::ArrayXd mY;\n};\n\nclass UMAP\n{\npublic:\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXi = Eigen::ArrayXi;\n  using VectorXd = Eigen::VectorXd;\n  using SparseMatrixXd = Eigen::SparseMatrix<double>;\n  using DataSet = FluidDataSet<std::string, double, 1>;\n  template <typename T>\n  using Ref = Eigen::Ref<T>;\n\n  void init(RealMatrixView embedding, KDTree tree, index k, double a, double b)\n  {\n    mEmbedding = _impl::asEigen<Eigen::Array>(embedding);\n    mTree = tree;\n    mK = k;\n    mAB = VectorXd(2);\n    mAB << a, b;\n    mInitialized = true;\n  }\n\n  void getEmbedding(RealMatrixView out) const\n  {\n    if (mInitialized) out <<= _impl::asFluid(mEmbedding);\n  }\n\n  double getA() const { return mInitialized ? mAB(0) : 0; }\n\n  double getB() const { return mInitialized ? mAB(1) : 0; }\n\n  index getK() const { return mInitialized ? mK : 0; }\n\n  KDTree getTree() const { return mTree; }\n\n  void clear()\n  {\n    mEmbedding.setZero();\n    mTree.clear();\n    mInitialized = false;\n  }\n\n  index dims() const { return mInitialized ? mEmbedding.cols() : 0; }\n\n  index inputDims() const { return mInitialized ? mTree.dims() : 0; }\n\n  index size() const { return mInitialized ? mEmbedding.rows() : 0; }\n\n  bool initialized() const { return mInitialized; }\n\n  DataSet train(DataSet& in, index k = 15, index dims = 2, double minDist = 0.1,\n                index maxIter = 200, double learningRate = 1.0)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n    SpectralEmbedding      spectralEmbedding;\n    index                  n = in.size();\n    FluidTensor<string, 1> ids{in.getIds()};\n    FluidTensor<string, 1> newIds(n);\n    for (index i = 0; i < n; i++) newIds(i) = to_string(i);\n    mTree = KDTree(DataSet(newIds, in.getData()));\n    SparseMatrixXd knnGraph = SparseMatrixXd(in.size(), in.size());\n    ArrayXXd       dists = ArrayXXd::Zero(in.size(), k);\n    mK = k;\n    makeGraph(in, mK, knnGraph, dists, true);\n    ArrayXd sigma = findSigma(k, dists);\n    computeHighDimProb(dists, sigma, knnGraph);\n    SparseMatrixXd knnGraphT = knnGraph.transpose();\n    knnGraph = (knnGraph + knnGraphT) - knnGraph.cwiseProduct(knnGraphT);\n    mAB = findAB(minDist);\n    mEmbedding = spectralEmbedding.train(knnGraph, dims);\n    mEmbedding = normalizeEmbedding(mEmbedding);\n    knnGraph.makeCompressed();\n    ArrayXi rowIndices(knnGraph.nonZeros());\n    ArrayXi colIndices(knnGraph.nonZeros());\n    ArrayXd epochsPerSample(knnGraph.nonZeros());\n    getGraphIndices(knnGraph, rowIndices, colIndices);\n    computeEpochsPerSample(knnGraph, epochsPerSample);\n    epochsPerSample = (epochsPerSample == 0).select(-1, epochsPerSample);\n    optimizeLayout(mEmbedding, mEmbedding, rowIndices, colIndices,\n                   epochsPerSample, true, learningRate, maxIter);\n    DataSet out(ids, _impl::asFluid(mEmbedding));\n    mInitialized = true;\n    return out;\n  }\n\n  DataSet transform(DataSet& in, index maxIter = 200, double learningRate = 1.0) const\n  {\n    if (!mInitialized) return DataSet();\n    SparseMatrixXd knnGraph(in.size(), mEmbedding.rows());\n    ArrayXXd       dists = ArrayXXd::Zero(in.size(), mK);\n    makeGraph(in, mK, knnGraph, dists, false);\n    knnGraph.makeCompressed();\n    ArrayXd sigma = findSigma(mK, dists);\n    computeHighDimProb(dists, sigma, knnGraph);\n    normalizeRows(knnGraph);\n    ArrayXXd embedding =\n        initTransformEmbedding(knnGraph, mEmbedding, in.size());\n    ArrayXi rowIndices(knnGraph.nonZeros());\n    ArrayXi colIndices(knnGraph.nonZeros());\n    ArrayXd epochsPerSample(knnGraph.nonZeros());\n    getGraphIndices(knnGraph, rowIndices, colIndices);\n    computeEpochsPerSample(knnGraph, epochsPerSample);\n    epochsPerSample = (epochsPerSample == 0).select(-1, epochsPerSample);\n    optimizeLayout(embedding, mEmbedding, rowIndices, colIndices,\n                   epochsPerSample, false, learningRate, maxIter);\n    DataSet out(in.getIds(), _impl::asFluid(embedding));\n    return out;\n  }\n\n\n  void transformPoint(RealVectorView in, RealVectorView out) const\n  {\n    if (!mInitialized) return;\n    SparseMatrixXd knnGraph(1, mEmbedding.rows());\n    ArrayXXd       dists = ArrayXXd::Zero(1, mK);\n    knnGraph.reserve(mK);\n    auto nearest = mTree.kNearest(in, mK);\n    auto nearestIds = nearest.getIds();\n    auto distances = nearest.getData().col(0);\n    for (index j = 0; j < mK; j++)\n    {\n      index neighborIndex = stoi(nearestIds(j));\n      dists(0, j) = distances(j);\n      knnGraph.insert(0, neighborIndex) = distances(j);\n    }\n    knnGraph.makeCompressed();\n    ArrayXd sigma = findSigma(mK, dists);\n    computeHighDimProb(dists, sigma, knnGraph);\n    normalizeRows(knnGraph);\n    ArrayXXd embedding = initTransformEmbedding(knnGraph, mEmbedding, 1);\n    ArrayXd  result = embedding.row(0);\n    out <<= _impl::asFluid(result);\n  }\n\n\nprivate:\n  template <typename F>\n  void traverseGraph(const SparseMatrixXd& graph, F func) const\n  {\n    for (index i = 0; i < graph.outerSize(); i++)\n    {\n      for (SparseMatrixXd::InnerIterator it(graph, i); it; ++it) { func(it); }\n    }\n  }\n\n  double loss(Ref<ArrayXXd> P, Ref<ArrayXXd> Y, double a, double b)\n  {\n    ArrayXXd D = DistanceMatrix(Y, 2);\n    ArrayXXd Q = 1 / (1 + a * D.pow(b));\n    Q = Q + epsilon;\n    ArrayXXd CE =\n        -P * (Q + 0.01).log() - (1 - P) * (1e-6 + (1 - Q + 0.01)).log();\n    return CE.sum();\n  }\n\n  ArrayXd findSigma(index k, Ref<ArrayXXd> dists, index maxIter = 64,\n                    double tolerance = 1e-5) const\n  {\n    using namespace std;\n    double  target = log2(k);\n    ArrayXd result = ArrayXd::Zero(dists.rows());\n    for (index i = 0; i < dists.rows(); i++)\n    {\n      index  iter = maxIter;\n      double lo = 0;\n      double hi = infinity;\n      double mid = 1.0;\n      double rho = dists(i, 0);\n      while (iter-- > 0)\n      {\n        double pSum = 0;\n        for (index j = 1; j < dists.cols(); j++)\n        {\n          double d = dists(i, j) - rho;\n          pSum += (d <= 0 ? 1.0 : exp(-(d / mid)));\n        }\n        if (abs(pSum - target) < tolerance) break;\n        if (pSum > target)\n        {\n          hi = mid;\n          mid = (lo + hi) / 2.0;\n        }\n        else\n        {\n          lo = mid;\n          mid = (hi == infinity ? mid * 2 : (lo + hi) / 2.0);\n        }\n      }\n      result(i) = mid;\n    }\n    return result;\n  }\n\n  void computeHighDimProb(const Ref<ArrayXXd>& dists, const Ref<ArrayXd>& sigma,\n                          SparseMatrixXd& graph) const\n  {\n    traverseGraph(graph, [&](auto it) {\n      it.valueRef() =\n          std::exp(-(it.value() - dists(it.row(), 0)) / sigma(it.row()));\n    });\n  }\n\n  VectorXd findAB(double minDist)\n  {\n    using namespace Eigen;\n    VectorXd ab(2);\n    ab << 1.0, 1.0;\n    UMAPEmbeddingParamsFunctor                functor(minDist);\n    NumericalDiff<UMAPEmbeddingParamsFunctor> numDiff(functor);\n    LevenbergMarquardt<NumericalDiff<UMAPEmbeddingParamsFunctor>> lm(numDiff);\n    lm.minimize(ab);\n    return ab;\n  }\n\n  void makeGraph(const DataSet& in, index k, SparseMatrixXd& graph,\n                 Ref<ArrayXXd> dists, bool discardFirst) const\n  {\n    graph.reserve(in.size() * k);\n    auto data = in.getData();\n    for (index i = 0; i < in.size(); i++)\n    {\n      auto nearest = mTree.kNearest(data.row(i), discardFirst ? k + 1 : k);\n      auto nearestIds = nearest.getIds();\n      auto distances = nearest.getData().col(0);\n      for (index j = 0; j < k; j++)\n      {\n        index pos = discardFirst ? j + 1 : j;\n        index neighborIndex = stoi(nearestIds(pos));\n        dists(i, j) = distances(pos);\n        graph.insert(i, neighborIndex) = distances(pos);\n      }\n    }\n  }\n\n  ArrayXXd normalizeEmbedding(const Ref<ArrayXXd>& embedding)\n  {\n    // based on umap python implementation\n    double   expansion = 10.0 / embedding.abs().maxCoeff();\n    ArrayXXd noise =\n        1e-4 * ArrayXXd::Random(embedding.rows(), embedding.cols()); // uniform\n    ArrayXXd result = (embedding * expansion) + noise;\n    ArrayXd  min = result.colwise().minCoeff();\n    ArrayXd  max = result.colwise().maxCoeff();\n    ArrayXd  range = (max - min).max(epsilon);\n    result = (result.rowwise() - min.transpose());\n    result = result.rowwise() / range.transpose();\n    return 10.0 * result;\n  }\n\n  void getGraphIndices(const SparseMatrixXd& graph, Ref<ArrayXi> rowIndices,\n                       Ref<ArrayXi> colIndices) const\n  {\n    index p = 0;\n    traverseGraph(graph, [&](auto it) {\n      rowIndices(p) = static_cast<int>(it.row());\n      colIndices(p) = static_cast<int>(it.col());\n      p++;\n    });\n  }\n\n  void computeEpochsPerSample(const SparseMatrixXd& graph,\n                              Ref<ArrayXd>          epochsPerSample) const\n  {\n    index  p = 0;\n    double maxVal = graph.coeffs().maxCoeff();\n    traverseGraph(graph, [&](auto it) {\n      epochsPerSample(p++) = 1.0 / (it.value() / maxVal);\n    });\n  }\n\n  void optimizeLayout(Ref<ArrayXXd> embedding, Ref<ArrayXXd> reference,\n                      Ref<ArrayXi> embIndices, Ref<ArrayXi> refIndices,\n                      Ref<ArrayXd> epochsPerSample, bool updateReference,\n                      double learningRate, index maxIter, double gamma = 1.0) const\n  {\n    using namespace std;\n    double alpha = learningRate;\n    double negativeSampleRate = 5.0;\n    auto distance = DistanceFuncs::map()[DistanceFuncs::Distance::kSqEuclidean];\n    double                          a = mAB(0);\n    double                          b = mAB(1);\n    random_device                   rd;\n    mt19937                         mt(rd());\n    uniform_int_distribution<index> randomInt(0, reference.rows() - 1);\n    ArrayXd epochsPerNegativeSample = epochsPerSample / negativeSampleRate;\n    ArrayXd nextEpoch = epochsPerSample;\n    ArrayXd nextNegEpoch = epochsPerNegativeSample;\n    ArrayXd bound = VectorXd::Constant(\n        embedding.cols(), 4); // based on umap python implementation\n    for (index i = 0; i < maxIter; i++)\n    {\n      for (index j = 0; j < epochsPerSample.size(); j++)\n      {\n        if (nextEpoch(j) > i) continue;\n        ArrayXd current = embedding.row(embIndices(j));\n        ArrayXd other = reference.row(refIndices(j));\n        double dist = distance(current, other); // todo: try to have dist member\n        double gradCoef = 0;\n        ArrayXd grad;\n        if (dist > 0)\n        {\n          gradCoef = -2.0 * a * b * pow(dist, b - 1.0);\n          gradCoef /= a * pow(dist, b) + 1.0;\n        }\n        grad = (gradCoef * (current - other)).cwiseMin(bound).cwiseMax(-bound);\n        current += grad * alpha;\n        if (updateReference) other += -grad * alpha;\n        nextEpoch(j) += epochsPerSample(j);\n        index numNegative = static_cast<index>((i - nextNegEpoch(j)) /\n                                                 epochsPerNegativeSample(j));\n        for (index k = 0; k < numNegative; k++)\n        {\n          index negativeIndex = randomInt(mt);\n          if (negativeIndex == embIndices(j)) continue;\n          ArrayXd negative = reference.row(negativeIndex);\n          dist = distance(current, negative);\n          gradCoef = 0;\n          grad = VectorXd::Constant(reference.cols(), 4.0);\n          if (dist > 0)\n          {\n            gradCoef = 2.0 * gamma * b;\n            gradCoef /= (0.001 + dist) * (a * pow(dist, b) + 1);\n            grad = (gradCoef * (current - negative))\n                       .cwiseMin(bound)\n                       .cwiseMax(-bound);\n          }\n          current += grad * alpha;\n        }\n        nextNegEpoch(j) += numNegative * epochsPerNegativeSample(j);\n        embedding.row(embIndices(j)) = current;\n        if (updateReference) reference.row(refIndices(j)) = other;\n      }\n      alpha = learningRate * (1.0 - (i / double(maxIter)));\n    }\n  }\n\n  ArrayXXd initTransformEmbedding(const SparseMatrixXd& graph,\n                                  Ref<const ArrayXXd> reference, index N) const\n  {\n    ArrayXXd embedding = ArrayXXd::Zero(N, reference.cols());\n    traverseGraph(graph, [&](auto it) {\n      embedding.row(it.row()) += (reference.row(it.col()) * it.value());\n    });\n    return embedding;\n  }\n\n  void normalizeRows(const SparseMatrixXd& graph) const\n  {\n    ArrayXd sums = ArrayXd::Zero(graph.innerSize());\n    traverseGraph(graph, [&](auto it) { sums(it.row()) += it.value(); });\n    traverseGraph(\n        graph, [&](auto it) { it.valueRef() = it.value() / sums(it.row()); });\n  }\n\nprivate:\n  KDTree   mTree;\n  index    mK;\n  VectorXd mAB;\n  mutable ArrayXXd mEmbedding;\n  bool     mInitialized{false};\n};\n}// namespace algorithm\n}// namespace fluid\n", "meta": {"hexsha": "c9baa3aca31a1f7869250e7757456dbbe0f0cc41", "size": 13747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/UMAP.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/UMAP.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/UMAP.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2053140097, "max_line_length": 86, "alphanum_fraction": 0.6081326835, "num_tokens": 3772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5963751292332972}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include <array>\n#include \"/Users/drewlewis/software/install/tiledarray/sparse_new_summa_debug/include/tiledarray.h\"\n\nusing Tensor = TiledArray::Tensor<double>;\nusing Perm = TiledArray::Permutation;\nusing Range = TiledArray::Range;\nusing Matrix =\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nint main(int argc, char **argv) {\n    auto tensor = Tensor{Range(3, 2, 2)};\n    for (auto i = 1; i <= 12; ++i) {\n        tensor[i - 1] = i;\n    }\n\n    auto const &tsize = tensor.range().size();\n    Eigen::Map<Matrix> tmap(tensor.data(), tsize[0], tsize[1] * tsize[2]);\n    Eigen::JacobiSVD<Matrix> svd(tmap,\n                                 Eigen::ComputeThinU | Eigen::ComputeThinV);\n    auto const &vals = svd.singularValues();\n    auto rank = 0;\n    for (auto i = 0; i < vals.size(); ++i) {\n        if (vals[i] > 1e-10) {\n            ++rank;\n        }\n    }\n    Matrix mU = svd.matrixU().leftCols(rank);\n    Matrix dV = svd.singularValues().asDiagonal();\n    Matrix v = dV.block(0,0,rank, rank) * svd.matrixV().transpose().topRows(rank);\n\n    std::cout << \"U = \\n\" << mU << std::endl;\n    std::cout << \"v = \\n\" << v << std::endl;\n    std::cout << \"Approx = \\n\" << mU * v << std::endl;\n\n    // Resize to 4*2\n    v.resize(4,2);\n    svd.compute(v, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    auto const &vals2 = svd.singularValues();\n    rank = 0;\n    for (auto i = 0; i < vals2.size(); ++i) {\n        if (vals2[i] > 1e-10) {\n            ++rank;\n        }\n    }\n    Matrix mU2 = svd.matrixU().leftCols(rank);\n    Matrix dV2 = svd.singularValues().asDiagonal();\n    Matrix v2 = dV.block(0,0,rank, rank) * svd.matrixV().transpose().topRows(rank);\n\n    std::cout << \"U2 = \\n\" << mU2 << std::endl;\n    std::cout << \"v2 = \\n\" << v2 << std::endl;\n\n    mU2.resize(2,4);\n    Matrix Ucombo = mU * mU2;\n\n    Ucombo.resize(6,2);\n    std::cout << \"Ucombo = \\n\" << Ucombo << std::endl;\n    \n    svd.compute(Ucombo, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    auto const &vals3 = svd.singularValues();\n    rank = 0;\n    for (auto i = 0; i < vals2.size(); ++i) {\n        if (vals3[i] > 1e-10) {\n            ++rank;\n        }\n    }\n    Matrix mU3 = svd.matrixU().leftCols(rank);\n    Matrix dV3 = svd.singularValues().asDiagonal();\n    Matrix v3 = dV.block(0,0,rank, rank) * svd.matrixV().transpose().topRows(rank);\n\n    std::cout << \"U3 = \\n\" << mU3 << std::endl;\n    std::cout << \"v3 = \\n\" << v3 << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "eaac0e3be8e48ed9ba7b6b5a99991e86a05a6aa0", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_tests/tensortrain/tt.cpp", "max_stars_repo_name": "calewis/SmallProjectsAndDev", "max_stars_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_tests/tensortrain/tt.cpp", "max_issues_repo_name": "calewis/SmallProjectsAndDev", "max_issues_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_tests/tensortrain/tt.cpp", "max_forks_repo_name": "calewis/SmallProjectsAndDev", "max_forks_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1153846154, "max_line_length": 99, "alphanum_fraction": 0.5616766467, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5963135077572644}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003, 2004 Ferdinando Ametrano\n Copyright (C) 2006 Richard Gould\n Copyright (C) 2007 Mark Joshi\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 sobolrsg.hpp\n    \\brief Sobol low-discrepancy sequence generator\n*/\n\n#ifndef quantlib_sobol_ld_rsg_hpp\n#define quantlib_sobol_ld_rsg_hpp\n\n#include <ql/methods/montecarlo/sample.hpp>\n#include <vector>\n#include <boost/cstdint.hpp>\n\nnamespace QuantLib {\n\n    //! Sobol low-discrepancy sequence generator\n    /*! A Gray code counter and bitwise operations are used for very\n        fast sequence generation.\n\n        The implementation relies on primitive polynomials modulo two\n        from the book \"Monte Carlo Methods in Finance\" by Peter\n        Jäckel.\n\n        21 200 primitive polynomials modulo two are provided in QuantLib.\n        Jäckel has calculated 8 129 334 polynomials: if you need that many\n        dimensions you can replace the primitivepolynomials.cpp file included\n        in QuantLib with the one provided in the CD of the \"Monte Carlo\n        Methods in Finance\" book.\n\n        The choice of initialization numbers (also know as free direction\n        integers) is crucial for the homogeneity properties of the sequence.\n        Sobol defines two homogeneity properties: Property A and Property A'.\n\n        The unit initialization numbers suggested in \"Numerical\n        Recipes in C\", 2nd edition, by Press, Teukolsky, Vetterling,\n        and Flannery (section 7.7) fail the test for Property A even\n        for low dimensions.\n\n        Bratley and Fox published coefficients of the free direction\n        integers up to dimension 40, crediting unpublished work of\n        Sobol' and Levitan. See Bratley, P., Fox, B.L. (1988)\n        \"Algorithm 659: Implementing Sobol's quasirandom sequence\n        generator,\" ACM Transactions on Mathematical Software\n        14:88-100. These values satisfy Property A for d<=20 and d =\n        23, 31, 33, 34, 37; Property A' holds for d<=6.\n\n        Jäckel provides in his book (section 8.3) initialization\n        numbers up to dimension 32. Coefficients for d<=8 are the same\n        as in Bradley-Fox, so Property A' holds for d<=6 but Property\n        A holds for d<=32.\n\n        The implementation of Lemieux, Cieslak, and Luttmer includes\n        coefficients of the free direction integers up to dimension\n        360.  Coefficients for d<=40 are the same as in Bradley-Fox.\n        For dimension 40<d<=360 the coefficients have\n        been calculated as optimal values based on the \"resolution\"\n        criterion. See \"RandQMC user's guide - A package for\n        randomized quasi-Monte Carlo methods in C,\" by C. Lemieux,\n        M. Cieslak, and K. Luttmer, version January 13 2004, and\n        references cited there\n        (http://www.math.ucalgary.ca/~lemieux/randqmc.html).\n        The values up to d<=360 has been provided to the QuantLib team by\n        Christiane Lemieux, private communication, September 2004.\n\n        For more info on Sobol' sequences see also \"Monte Carlo\n        Methods in Financial Engineering,\" by P. Glasserman, 2004,\n        Springer, section 5.2.3\n\n        The Joe--Kuo numbers and the Kuo numbers are due to Stephen Joe\n        and Frances Kuo.\n\n        S. Joe and F. Y. Kuo, Constructing Sobol sequences with better\n        two-dimensional projections, preprint Nov 22 2007\n\n        See http://web.maths.unsw.edu.au/~fkuo/sobol/ for more information.\n\n        The Joe-Kuo numbers are available under a BSD-style license\n        available at the above link.\n\n        Note that the Kuo numbers were generated to work with a\n        different ordering of primitive polynomials for the first 40\n        or so dimensions which is why we have the Alternative\n        Primitive Polynomials.\n\n        \\test\n        - the correctness of the returned values is tested by\n          reproducing known good values.\n        - the correctness of the returned values is tested by checking\n          their discrepancy against known good values.\n    */\n    class SobolRsg {\n      public:\n        typedef Sample<std::vector<Real> > sample_type;\n        enum DirectionIntegers {\n            Unit, Jaeckel, SobolLevitan, SobolLevitanLemieux,\n            JoeKuoD5, JoeKuoD6, JoeKuoD7,\n            Kuo, Kuo2, Kuo3 };\n        /*! \\pre dimensionality must be <= PPMT_MAX_DIM */\n        SobolRsg(Size dimensionality,\n                 unsigned long seed = 0,\n                 DirectionIntegers directionIntegers = Jaeckel);\n        /*! skip to the n-th sample in the low-discrepancy sequence */\n        void skipTo(boost::uint_least32_t n);\n        const std::vector<boost::uint_least32_t>& nextInt32Sequence() const;\n\n        const SobolRsg::sample_type& nextSequence() const {\n            const std::vector<boost::uint_least32_t>& v = nextInt32Sequence();\n            // normalize to get a double in (0,1)\n            for (Size k=0; k<dimensionality_; ++k)\n                sequence_.value[k] = v[k] * normalizationFactor_;\n            return sequence_;\n        }\n        const sample_type& lastSequence() const { return sequence_; }\n        Size dimension() const { return dimensionality_; }\n      private:\n        static const int bits_;\n        static const double normalizationFactor_;\n        Size dimensionality_;\n        mutable boost::uint_least32_t sequenceCounter_;\n        mutable bool firstDraw_;\n        mutable sample_type sequence_;\n        mutable std::vector<boost::uint_least32_t> integerSequence_;\n        std::vector<std::vector<boost::uint_least32_t> > directionIntegers_;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "41904bb760ff522ca5a617e6f5e734a619490ecf", "size": 6282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/randomnumbers/sobolrsg.hpp", "max_stars_repo_name": "itaylotan/MyQuantLib", "max_stars_repo_head_hexsha": "53af24d37ed47c0b910ee4a128a421254a08c82f", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/math/randomnumbers/sobolrsg.hpp", "max_issues_repo_name": "itaylotan/MyQuantLib", "max_issues_repo_head_hexsha": "53af24d37ed47c0b910ee4a128a421254a08c82f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/math/randomnumbers/sobolrsg.hpp", "max_forks_repo_name": "itaylotan/MyQuantLib", "max_forks_repo_head_hexsha": "53af24d37ed47c0b910ee4a128a421254a08c82f", "max_forks_repo_licenses": ["BSD-3-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.4459459459, "max_line_length": 79, "alphanum_fraction": 0.6838586437, "num_tokens": 1491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.596180425703241}}
{"text": "<%\ncfg['compiler_args'] = ['-std=c++11']\ncfg['include_dirs'] = ['/usr/include/eigen3']\nsetup_pybind11(cfg)\n%>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <cmath>\n#include <Eigen/LU>\n\nnamespace py = pybind11;\n\nusing Eigen::MatrixXd;\n\nMatrixXd cdist(MatrixXd xs, MatrixXd ys) {\n    int m = xs.rows();\n    int n = ys.rows();\n    int p = ys.cols();\n    \n    MatrixXd res(m, n);\n    \n    double s;\n    for (int i=0; i<m; i++) {\n        for (int j=0; j<n; j++) {\n            s = 0;\n            for (int k=0; k<p; k++) {\n                s += pow(ys(j,k) - xs(i,k), 2);\n            }\n            res(i,j) = sqrt(s);\n        }\n    }\n    \n    return res;\n}\n\nPYBIND11_MODULE(funcs, m) {\n    m.doc() = \"auto-compiled c++ extension\";\n    m.def(\"cdist\", &cdist);\n}\n", "meta": {"hexsha": "04b506261589fdd25b295052734e40fbef0ab830", "size": 777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "notebooks/funcs.cpp", "max_stars_repo_name": "fesaille/bios-823-2019", "max_stars_repo_head_hexsha": "2c070cb1e20e88c191b113908b7159892492b73d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T17:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T04:10:01.000Z", "max_issues_repo_path": "notebooks/funcs.cpp", "max_issues_repo_name": "fesaille/bios-823-2019", "max_issues_repo_head_hexsha": "2c070cb1e20e88c191b113908b7159892492b73d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/funcs.cpp", "max_forks_repo_name": "fesaille/bios-823-2019", "max_forks_repo_head_hexsha": "2c070cb1e20e88c191b113908b7159892492b73d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-08-29T02:00:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T17:31:27.000Z", "avg_line_length": 18.5, "max_line_length": 47, "alphanum_fraction": 0.5006435006, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5961804168189949}}
{"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    Rot3Q.cpp\n * @brief   Rotation (internal: quaternion representation*)\n * @author  Richard Roberts\n */\n\n#include <gtsam/config.h> // Get GTSAM_USE_QUATERNIONS macro\n\n#ifdef GTSAM_USE_QUATERNIONS\n\n#include <boost/math/constants/constants.hpp>\n#include <gtsam/geometry/Rot3.h>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  static const Matrix I3 = eye(3);\n\n  /* ************************************************************************* */\n  Rot3::Rot3() : quaternion_(Quaternion::Identity()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Point3& col1, const Point3& col2, const Point3& col3) :\n      quaternion_((Eigen::Matrix3d() <<\n          col1.x(), col2.x(), col3.x(),\n          col1.y(), col2.y(), col3.y(),\n          col1.z(), col2.z(), col3.z()).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(double R11, double R12, double R13,\n      double R21, double R22, double R23,\n      double R31, double R32, double R33) :\n        quaternion_((Eigen::Matrix3d() <<\n            R11, R12, R13,\n            R21, R22, R23,\n            R31, R32, R33).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Matrix3& R) :\n      quaternion_(R) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Matrix& R) :\n      quaternion_(Matrix3(R)) {}\n\n//  /* ************************************************************************* */\n//   Rot3::Rot3(const Matrix3& R) :\n//       quaternion_(R) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Quaternion& q) : quaternion_(q) {}\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rx(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitX())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Ry(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitY())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rz(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitZ())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::RzRyRx(double x, double y, double z) { return Rot3(\n      Quaternion(Eigen::AngleAxisd(z, Eigen::Vector3d::UnitZ())) *\n      Quaternion(Eigen::AngleAxisd(y, Eigen::Vector3d::UnitY())) *\n      Quaternion(Eigen::AngleAxisd(x, Eigen::Vector3d::UnitX())));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::rodriguez(const Vector& w, double theta) {\n    return Quaternion(Eigen::AngleAxisd(theta, w)); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::compose(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = R2.transpose();\n    if (H2) *H2 = I3;\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::operator*(const Rot3& R2) const {\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::inverse(boost::optional<Matrix&> H1) const {\n    if (H1) *H1 = -matrix();\n    return Rot3(quaternion_.inverse());\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::between(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = -(R2.transpose()*matrix());\n    if (H2) *H2 = I3;\n    return between_default(*this, R2);\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::rotate(const Point3& p,\n        boost::optional<Matrix&> H1,  boost::optional<Matrix&> H2) const {\n    Matrix R = matrix();\n    if (H1) *H1 = R * skewSymmetric(-p.x(), -p.y(), -p.z());\n    if (H2) *H2 = R;\n    Eigen::Vector3d r = R * p.vector();\n    return Point3(r.x(), r.y(), r.z());\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::Logmap(const Rot3& R) {\n    using std::acos;\n    using std::sqrt;\n    static const double twoPi = 2.0 * M_PI,\n    // define these compile time constants to avoid std::abs:\n        NearlyOne = 1.0 - 1e-10, NearlyNegativeOne = -1.0 + 1e-10;\n\n    const Quaternion& q = R.quaternion_;\n    const double qw = q.w();\n    if (qw > NearlyOne) {\n      // Taylor expansion of (angle / s) at 1\n      return (2 - 2 * (qw - 1) / 3) * q.vec();\n    } else if (qw < NearlyNegativeOne) {\n      // Angle is zero, return zero vector\n      return Vector3::Zero();\n    } else {\n      // Normal, away from zero case\n      double angle = 2 * acos(qw), s = sqrt(1 - qw * qw);\n      // Important:  convert to [-pi,pi] to keep error continuous\n      if (angle > M_PI)\n        angle -= twoPi;\n      else if (angle < -M_PI)\n        angle += twoPi;\n      return (angle / s) * q.vec();\n    }\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::retract(const Vector& omega, Rot3::CoordinatesMode mode) const {\n    return compose(Expmap(omega));\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::localCoordinates(const Rot3& t2, Rot3::CoordinatesMode mode) const {\n    return Logmap(between(t2));\n  }\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::matrix() const {return quaternion_.toRotationMatrix();}\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::transpose() const {return quaternion_.toRotationMatrix().transpose();}\n\n  /* ************************************************************************* */\n  Point3 Rot3::r1() const { return Point3(quaternion_.toRotationMatrix().col(0)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r2() const { return Point3(quaternion_.toRotationMatrix().col(1)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r3() const { return Point3(quaternion_.toRotationMatrix().col(2)); }\n\n  /* ************************************************************************* */\n  Quaternion Rot3::toQuaternion() const { return quaternion_; }\n\n /* ************************************************************************* */\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "6b7a4e0ce9ee8eb1f1c9ccb1b1b06b74c59db7c8", "size": 7097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3Q.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/Rot3Q.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/Rot3Q.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": 38.5706521739, "max_line_length": 96, "alphanum_fraction": 0.4173594477, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5961804126293826}}
{"text": "#include <Eigen/Dense>\n\n#include <VirtualRobot/VirtualRobot.h>\n#include <VirtualRobot/Nodes/ContactSensor.h>\n\n#include \"bipedal.h\"\n#include \"utils/ZMP.h\"\n\n\nnamespace Bipedal\n{\n\ninline Eigen::Vector2f computeModelZMP(const Eigen::Vector3f& com, const Eigen::Vector3f& comAcc, double gravity)\n{\n    Eigen::Vector2f zmp;\n    zmp.x() = com.x() - com.z() / gravity * comAcc.x();\n    zmp.y() = com.y() - com.z() / gravity * comAcc.y();\n    return zmp;\n}\n\ninline Eigen::Vector2f computeMultiBodyZMP(double mass,\n                                           double gravity,\n                                           const Eigen::Vector3f& com,\n                                           const Eigen::Vector3f& linearMomentumDiff,\n                                           const Eigen::Vector3f& angularMomentumDiff)\n{\n    Eigen::Vector2f zmp;\n    double norm = mass * gravity + linearMomentumDiff.z();\n    zmp.x() = mass * gravity * com.x() - angularMomentumDiff.y();\n    zmp.y() = mass * gravity * com.y() + angularMomentumDiff.x();\n    zmp /= norm;\n\n    return zmp;\n}\n\nMultiBodyZMPEstimator::MultiBodyZMPEstimator(double mass, double gravity)\n: mass(mass)\n, gravity(gravity)\n, estimation(Eigen::Vector2f::Zero())\n, linearMomentumDiff(Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero())\n, angularMomentumDiff(Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero())\n{\n    BOOST_ASSERT(gravity > 0);\n}\n\nvoid MultiBodyZMPEstimator::update(const Eigen::Vector3f& com,\n            const Eigen::Vector3f& linearMomentum,\n            const Eigen::Vector3f& angularMomentum,\n            double dt)\n{\n    linearMomentumDiff.update(linearMomentum, dt);\n    angularMomentumDiff.update(angularMomentum, dt);\n\n    estimation = computeMultiBodyZMP(mass, gravity, com, linearMomentumDiff.estimation, angularMomentumDiff.estimation);\n}\n\nCartTableZMPEstimator::CartTableZMPEstimator(double gravity)\n: gravity(gravity)\n, accelerationEstimator(Eigen::Vector3f::Zero(), Eigen::Vector3f::Zero())\n{\n    BOOST_ASSERT(gravity > 0);\n}\n\nvoid CartTableZMPEstimator::update(const Eigen::Vector3f& com, const Eigen::Vector3f& comVel, double dt)\n{\n    accelerationEstimator.update(comVel, dt);\n    estimation = computeModelZMP(com, accelerationEstimator.estimation, gravity);\n}\n\nCoPZMPEstimator::CoPZMPEstimator(const VirtualRobot::ContactSensorPtr& leftFootSensor,\n                                 const VirtualRobot::ContactSensorPtr& rightFootSensor)\n: leftFootSensor(leftFootSensor)\n, rightFootSensor(rightFootSensor)\n, estimation(Eigen::Vector2f::Zero())\n{\n}\n\nvoid CoPZMPEstimator::update(float dt)\n{\n    double totalForce = 0.0;\n    Eigen::Vector2f pointSum = Eigen::Vector2f::Zero();\n\n    for (const auto& f : leftFootSensor->getContacts().forces)\n    {\n        if (f.bodyName == \"Floor\" && f.zForce > 0)\n        {\n            totalForce += f.zForce;\n            pointSum += f.zForce * f.contactPoint.head(2);\n        }\n    }\n\n    for (const auto& f : rightFootSensor->getContacts().forces)\n    {\n        if (f.bodyName == \"Floor\" && f.zForce > 0)\n        {\n            totalForce += f.zForce;\n            pointSum += f.zForce * f.contactPoint.head(2);\n        }\n    }\n\n    if (totalForce > 0)\n    {\n        estimation = pointSum / totalForce / 1000.0;\n    }\n}\n\n}\n", "meta": {"hexsha": "ab0016daa53ddddd1fe45ef6182c62c27af2a640", "size": 3226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/ZMP.cpp", "max_stars_repo_name": "TheMarex/libbipedal", "max_stars_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-06-10T22:02:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T19:16:16.000Z", "max_issues_repo_path": "src/utils/ZMP.cpp", "max_issues_repo_name": "TheMarex/libbipedal", "max_issues_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-09-29T01:31:56.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-22T02:01:08.000Z", "max_forks_repo_path": "src/utils/ZMP.cpp", "max_forks_repo_name": "TheMarex/libbipedal", "max_forks_repo_head_hexsha": "803f505425fd0bf94620f7efe7ceaa39f4fc8201", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-09-29T09:03:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T22:33:12.000Z", "avg_line_length": 29.8703703704, "max_line_length": 120, "alphanum_fraction": 0.6398016119, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5960812778273495}}
{"text": "#include \"tpf_intersection.h\"\n\n#include \"tpf_cuboid.h\"\n#include \"tpf_line.h\"\n#include \"tpf_plane.h\"\n#include \"tpf_point.h\"\n#include \"tpf_polyhedron.h\"\n#include \"tpf_tetrahedron.h\"\n#include \"tpf_triangle.h\"\n\n#include \"../algorithm/tpf_joaat.h\"\n\n#include \"../stdext/tpf_comparator.h\"\n\n#include \"../utility/tpf_optional.h\"\n\n#include \"Eigen/Dense\"\n\n#include <boost/variant/get.hpp>\n\n#include <CGAL/intersections.h>\n#include <CGAL/Point_3.h>\n#include <CGAL/Triangle_3.h>\n\n#include <algorithm>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace tpf\n{\n    namespace geometry\n    {\n        template <typename floatp_t, typename kernel_t>\n        inline bool does_intersect_with(const line<floatp_t, kernel_t>& line, const plane<floatp_t, kernel_t>& plane)\n        {\n            return CGAL::do_intersect(plane.get_internal(), line.get_internal());\n        }\n\n        template <typename floatp_t, typename kernel_t>\n        inline bool does_intersect_with(const plane<floatp_t, kernel_t>& plane, const cuboid<floatp_t, kernel_t>& cuboid)\n        {\n            return CGAL::do_intersect(cuboid.get_internal().bbox(), plane.get_internal());\n        }\n\n        template <typename floatp_t, typename kernel_t>\n        inline utility::optional<point<floatp_t, kernel_t>> intersect_with(const line<floatp_t, kernel_t>& line, const plane<floatp_t, kernel_t>& plane)\n        {\n            auto intersection = CGAL::intersection(plane.get_internal(), line.get_internal());\n\n            if (intersection)\n            {\n                const typename kernel_t::Point_3* p = boost::get<typename kernel_t::Point_3>(&*intersection);\n\n                if (p != nullptr)\n                {\n                    return *p;\n                }\n                else\n                {\n                    return utility::nullopt;\n                }\n            }\n            else\n            {\n                return utility::nullopt;\n            }\n        }\n\n        template <typename floatp_t, typename kernel_t>\n        inline std::vector<point<floatp_t, kernel_t>> intersect_with(const plane<floatp_t, kernel_t>& plane, const cuboid<floatp_t, kernel_t>& cuboid)\n        {\n            // Extract edges\n            std::vector<line<floatp_t, kernel_t>> edges;\n            edges.reserve(12);\n\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(0), cuboid.get_internal().vertex(1)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(3), cuboid.get_internal().vertex(2)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(5), cuboid.get_internal().vertex(6)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(4), cuboid.get_internal().vertex(7)));\n\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(0), cuboid.get_internal().vertex(3)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(1), cuboid.get_internal().vertex(2)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(5), cuboid.get_internal().vertex(4)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(6), cuboid.get_internal().vertex(7)));\n\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(0), cuboid.get_internal().vertex(5)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(1), cuboid.get_internal().vertex(6)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(3), cuboid.get_internal().vertex(4)));\n            edges.push_back(line<floatp_t, kernel_t>(cuboid.get_internal().vertex(2), cuboid.get_internal().vertex(7)));\n\n            // Intersect edges with plane\n            std::vector<point<floatp_t, kernel_t>> intersections;\n\n            for (const line<floatp_t, kernel_t>& edge : edges)\n            {\n                if (does_intersect_with(edge, plane))\n                {\n                    auto intersection = intersect_with(edge, plane);\n\n                    if (intersection)\n                    {\n                        intersections.push_back(*intersection);\n                    }\n                }\n            }\n\n            return intersections;\n        }\n\n        template <typename floatp_t, typename kernel_t>\n        inline std::vector<point<floatp_t, kernel_t>> intersect_with(const plane<floatp_t, kernel_t>& plane, const tetrahedron<floatp_t, kernel_t>& tetrahedron)\n        {\n            // Extract edges\n            std::vector<line<floatp_t, kernel_t>> edges;\n            edges.reserve(6);\n\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(0), tetrahedron.get_internal().vertex(1)));\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(0), tetrahedron.get_internal().vertex(2)));\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(0), tetrahedron.get_internal().vertex(3)));\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(1), tetrahedron.get_internal().vertex(2)));\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(1), tetrahedron.get_internal().vertex(3)));\n            edges.push_back(line<floatp_t, kernel_t>(tetrahedron.get_internal().vertex(2), tetrahedron.get_internal().vertex(3)));\n            \n            // Intersect edges with plane\n            std::vector<point<floatp_t, kernel_t>> intersections;\n\n            for (const line<floatp_t, kernel_t>& edge : edges)\n            {\n                if (does_intersect_with(edge, plane))\n                {\n                    auto intersection = intersect_with(edge, plane);\n\n                    if (intersection)\n                    {\n                        intersections.push_back(*intersection);\n                    }\n                }\n            }\n\n            return intersections;\n        }\n\n        template <typename floatp_t, typename kernel_t>\n        inline std::vector<point<floatp_t, kernel_t>> intersect_with(const plane<floatp_t, kernel_t>& plane, const polyhedron<floatp_t, kernel_t>& polyhedron)\n        {\n            // Extract faces\n            auto face_predicate = [](const triangle<floatp_t, kernel_t>& triangle) -> std::size_t\n            {\n                auto points = triangle.get_points();\n                std::sort(points.begin(), points.end(), std::less<Eigen::Matrix<floatp_t, 3, 1>>());\n\n                return algorithm::joaat_hash(points[0], points[1], points[2]);\n            };\n\n            std::unordered_map<triangle<floatp_t, kernel_t>, std::size_t, decltype(face_predicate)> faces(23, face_predicate);\n\n            for (const auto& tetrahedron : polyhedron.get_internal())\n            {\n                for (int i = 0; i < 2; ++i)\n                {\n                    for (int j = i + 1; j < 3; ++j)\n                    {\n                        for (int k = j + 1; k < 4; ++k)\n                        {\n                            const triangle<floatp_t, kernel_t> face(tetrahedron.get_internal().vertex(i),\n                                tetrahedron.get_internal().vertex(j), tetrahedron.get_internal().vertex(k));\n\n                            if (faces.find(face) == faces.end())\n                            {\n                                faces[face] = 1;\n                            }\n                            else\n                            {\n                                ++faces[face];\n                            }\n                        }\n                    }\n                }\n            }\n\n            // Filter faces, such that only outer ones remain\n            for (auto it = faces.begin(); it != faces.end(); )\n            {\n                if (it->second != 1)\n                {\n                    faces.erase(it++);\n                }\n                else\n                {\n                    ++it;\n                }\n            }\n\n            // Extract edges\n            auto edge_predicate = [](const line<floatp_t, kernel_t>& line) -> std::size_t\n            {\n                auto points = line.get_points();\n                std::sort(points.begin(), points.end(), std::less<Eigen::Matrix<floatp_t, 3, 1>>());\n\n                return algorithm::joaat_hash(points[0], points[1]);\n            };\n\n            std::unordered_set<line<floatp_t, kernel_t>, decltype(edge_predicate)> edges(23, edge_predicate);\n\n            for (const auto& face : faces)\n            {\n                for (int i = 0; i < 2; ++i)\n                {\n                    for (int j = i + 1; j < 3; ++j)\n                    {\n                        const line<floatp_t, kernel_t> edge(face.first.get_internal().vertex(i), face.first.get_internal().vertex(j));\n\n                        if (edges.find(edge) == edges.end())\n                        {\n                            edges.insert(edge);\n                        }\n                    }\n                }\n            }\n\n            // Intersect edges with plane\n            std::vector<point<floatp_t, kernel_t>> intersections;\n\n            for (const auto& edge : edges)\n            {\n                if (does_intersect_with(edge, plane))\n                {\n                    auto intersection = intersect_with(edge, plane);\n\n                    if (intersection)\n                    {\n                        intersections.push_back(*intersection);\n                    }\n                }\n            }\n\n            return intersections;\n        }\n    }\n}\n", "meta": {"hexsha": "465b0a750c0ceaec6221842a61fb647ed36664f7", "size": 9559, "ext": "inl", "lang": "C++", "max_stars_repo_path": "include/tpf/geometry/tpf_intersection.inl", "max_stars_repo_name": "UniStuttgart-VISUS/tpf", "max_stars_repo_head_hexsha": "cf9327363242daff9644bc0d0e40577cdaaf97aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/tpf/geometry/tpf_intersection.inl", "max_issues_repo_name": "UniStuttgart-VISUS/tpf", "max_issues_repo_head_hexsha": "cf9327363242daff9644bc0d0e40577cdaaf97aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-10T15:24:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T15:24:28.000Z", "max_forks_repo_path": "include/tpf/geometry/tpf_intersection.inl", "max_forks_repo_name": "UniStuttgart-VISUS/tpf", "max_forks_repo_head_hexsha": "cf9327363242daff9644bc0d0e40577cdaaf97aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-19T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T16:08:34.000Z", "avg_line_length": 39.5, "max_line_length": 160, "alphanum_fraction": 0.5377131499, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5960812622816375}}
{"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 * Author: Xing Jin, 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#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/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/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// 这是唯一一个新的。我们将需要一个定义在GridTools命名空间的库函数，用来计算最小的单元格直径。\n\n#include <deal.II/grid/grid_tools.h> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step24 \n{ \n  using namespace dealii; \n// @sect3{The \"forward problem\" class template}  \n\n// 主类的第一部分与 step-23 中的内容完全一致（除了名字）。\n\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    AffineConstraints<double> 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_step, time; \n    unsigned int timestep_number; \n    const double theta; \n\n// 下面是新的内容：首先，我们需要从吸收边界条件出来的那个边界质量矩阵 $B$ 。同样，由于这次我们考虑的是一个现实的介质，我们必须有一个衡量波速的标准 $c_0$ ，它将进入所有与拉普拉斯矩阵（我们仍然定义为 $(\\nabla \\phi_i,\\nabla \\phi_j)$ ）有关的公式。\n\n    SparseMatrix<double> boundary_matrix; \n    const double         wave_speed; \n\n// 我们必须注意的最后一件事是，我们想在一定数量的检测器位置评估解决方案。我们需要一个数组来保存这些位置，在这里声明并在构造函数中填充。\n\n    std::vector<Point<dim>> detector_locations; \n  }; \n// @sect3{Equation data}  \n\n// 像往常一样，我们必须定义我们的初始值、边界条件和右手边的函数。这次事情有点简单：我们考虑的是一个由初始条件驱动的问题，所以没有右手函数（尽管你可以在 step-23 中查找，看看如何做到这一点）。其次，没有边界条件：域的整个边界由吸收性边界条件组成。这就只剩下初始条件了，这里的事情也很简单，因为对于这个特殊的应用，只规定了压力的非零初始条件，而没有规定速度的非零初始条件（速度在初始时间为零）。\n\n// 所以这就是我们所需要的：一个指定压力初始条件的类。在本程序所考虑的物理环境中，这些是小的吸收器，我们将其建模为一系列的小圆圈，我们假设压力盈余为1，而其他地方没有吸收，因此没有压力盈余。我们是这样做的（注意，如果我们想把这个程序扩展到不仅可以编译，而且可以运行，我们将不得不用三维源的位置来初始化源）。\n\n  template <int dim> \n  class InitialValuesP : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      static const std::array<Source, 5> sources{ \n        {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      for (const auto &source : sources) \n        if (p.distance(source.location) < source.radius) \n          return 1; \n\n      return 0; \n    } \n\n \n    struct Source \n    { \n      Source(const Point<dim> &l, const double r) \n        : location(l) \n        , radius(r) \n      {} \n\n      const Point<dim> location; \n      const double     radius; \n    }; \n  }; \n// @sect3{Implementation of the <code>TATForwardProblem</code> class}  \n\n// 让我们再从构造函数开始。设置成员变量是很直接的。我们使用矿物油的声波速度（单位为毫米/微秒，是实验性生物医学成像中的常用单位），因为我们想和输出的许多实验都是在这里进行的。再次使用Crank-Nicolson方案，即theta被设定为0.5。随后选择时间步长以满足 $k = \\frac hc$ ：这里我们把它初始化为一个无效的数字。\n\n  template <int dim> \n  TATForwardProblem<dim>::TATForwardProblem() \n    : fe(1) \n    , dof_handler(triangulation) \n    , time_step(std::numeric_limits<double>::quiet_NaN()) \n    , time(time_step) \n    , timestep_number(1) \n    , theta(0.5) \n    , wave_speed(1.437) \n  { \n\n// 构造函数中的第二个任务是初始化存放检测器位置的数组。这个程序的结果与实验进行了比较，其中检测器间距的步长为2.25度，对应160个检测器位置。扫描圆的半径被选为中心和边界之间的一半，以避免不完善的边界条件带来的剩余反射破坏我们的数值结果。\n\n// 然后按顺时针顺序计算探测器的位置。请注意，下面的内容当然只有在我们以2D计算时才有效，我们用一个断言来保护这个条件。如果我们以后想在三维中运行同样的程序，我们将不得不在这里添加代码来初始化三维中的探测器位置。由于断言的存在，我们不可能忘记这样做。\n\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; detector_angle >= 0; \n         detector_angle -= detector_step_angle / 360 * 2 * numbers::PI) \n      detector_locations.push_back( \n        Point<dim>(std::cos(detector_angle), std::sin(detector_angle)) * \n        detector_radius); \n  } \n\n//  @sect4{TATForwardProblem::setup_system}  \n\n// 下面的系统几乎就是我们在  step-23  中已经做过的，但有两个重要的区别。首先，我们必须在原点周围创建一个半径为1的圆形（或球形）网格。这并不新鲜：我们之前在 step-6 和 step-10 中已经这样做了，在那里我们还解释了PolarManifold或SphericalManifold对象如何在细化单元时将新点放在同心圆上，我们在这里也将使用它。\n\n// 我们必须确保的一点是，时间步长满足  step-23  的介绍中讨论的 CFL 条件。在那个程序中，我们通过设置一个与网格宽度相匹配的时间步长来确保这一点，但是这很容易出错，因为如果我们再细化一次网格，我们也必须确保时间步长有所改变。在这里，我们自动做到了这一点：我们向一个库函数询问任何单元的最小直径。然后我们设置 $k=\\frac h{c_0}$  。唯一的问题是： $h$ 到底是什么？关键是，对于波浪方程来说，这个问题确实没有好的理论。众所周知，对于由矩形组成的均匀细化网格， $h$ 是最小边长。但对于一般四边形的网格，确切的关系似乎是未知的，也就是说，不知道单元格的什么属性与CFL条件有关。问题是，CFL条件来自于对拉普拉斯矩阵最小特征值的了解，而这只能对简单结构的网格进行分析计算。\n\n// 这一切的结果是，我们并不十分确定我们应该对 $h$ 采取什么措施。函数 GridTools::minimal_cell_diameter 计算了所有单元的最小直径。如果单元格都是正方形或立方体，那么最小边长就是最小直径除以 <code>std::sqrt(dim)</code>  。我们简单地将此概括为非均匀网格的情况，没有理论上的理由。\n\n// 唯一的其他重大变化是我们需要建立边界质量矩阵。我们将在下文中进一步评论这个问题。\n\n  template <int dim> \n  void TATForwardProblem<dim>::setup_system() \n  { \n    const Point<dim> center; \n    GridGenerator::hyper_ball(triangulation, center, 1.); \n    triangulation.refine_global(7); \n\n    time_step = GridTools::minimal_cell_diameter(triangulation) / wave_speed / \n                std::sqrt(1. * dim); \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    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// 如前所述，与 step-23 的第二个区别是，我们需要建立从吸收性边界条件中生长出来的边界质量矩阵。\n\n// 第一个观察结果是，这个矩阵比常规质量矩阵要稀疏得多，因为没有一个具有纯内部支持的形状函数对这个矩阵有贡献。因此，我们可以根据这种情况优化存储模式，建立第二个稀疏模式，只包含我们需要的非零项。这里有一个权衡：首先，我们必须要有第二个稀疏模式对象，所以这需要花费内存。其次，与该稀疏性模式相连的矩阵将更小，因此需要更少的内存；用它进行矩阵-向量乘法也会更快。然而，最后一个论点是提示规模的论点：我们主要感兴趣的不是单独对边界矩阵进行矩阵-向量运算（尽管我们需要在每个时间步长对右侧向量进行一次运算），而是主要希望将其与两个方程中的第一个方程使用的其他矩阵相加，因为这是CG方法每个迭代都要与之相乘的，即明显更频繁。现在的情况是， SparseMatrix::add 类允许将一个矩阵添加到另一个矩阵中，但前提是它们使用相同的稀疏模式（原因是我们不能在稀疏模式创建后向矩阵添加非零条目，所以我们只是要求这两个矩阵具有相同的稀疏模式）。\n\n// 所以，我们就用这个方法吧。\n\n    boundary_matrix.reinit(sparsity_pattern); \n\n// 第二件要做的事是实际建立矩阵。在这里，我们需要对单元格的面进行积分，所以首先我们需要一个能在 <code>dim-1</code> 维对象上工作的正交对象。其次，FEValues的变体FEFaceValues，正如它的名字所暗示的，它可以在面上工作。最后，其他的变量是组装机器的一部分。所有这些我们都放在大括号里，以便将这些变量的范围限制在我们真正需要它们的地方。\n//然后\n//组装矩阵的实际行为是相当直接的：我们在所有单元中循环，在每个单元的所有面中循环，然后只在特定的面位于域的边界时做一些事情。像这样。\n\n    { \n      const QGauss<dim - 1> quadrature_formula(fe.degree + 1); \n      FEFaceValues<dim>     fe_values(fe, \n                                  quadrature_formula, \n                                  update_values | 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      for (const auto &cell : dof_handler.active_cell_iterators()) \n        for (const auto &face : cell->face_iterators()) \n          if (face->at_boundary()) \n            { \n              cell_matrix = 0; \n\n              fe_values.reinit(cell, face); \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    system_matrix.copy_from(mass_matrix); \n    system_matrix.add(time_step * time_step * theta * theta * wave_speed * \n                        wave_speed, \n                      laplace_matrix); \n    system_matrix.add(wave_speed * theta * time_step, boundary_matrix); \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// @sect4{TATForwardProblem::solve_p and TATForwardProblem::solve_v}  \n\n// 下面两个函数，解决压力和速度变量的线性系统，几乎是逐字逐句地从 step-23 中提取的（除了主变量的名字从 $u$ 改为 $p$ ）。\n\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<Vector<double>> cg(solver_control); \n\n    cg.solve(system_matrix, solution_p, system_rhs_p, PreconditionIdentity()); \n\n    std::cout << \"   p-equation: \" << solver_control.last_step() \n              << \" CG iterations.\" << std::endl; \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<Vector<double>> cg(solver_control); \n\n    cg.solve(mass_matrix, solution_v, system_rhs_v, PreconditionIdentity()); \n\n    std::cout << \"   v-equation: \" << solver_control.last_step() \n              << \" CG iterations.\" << std::endl; \n  } \n\n//  @sect4{TATForwardProblem::output_results}  \n\n// 这里也是如此：该函数来自  step-23  。\n\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 = \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    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n\n//  @sect4{TATForwardProblem::run}  \n\n// 这个做大部分工作的函数又和 step-23 中的差不多，尽管我们通过使用介绍中提到的向量G1和G2使事情变得更加清晰。与程序的整体内存消耗相比，引入几个临时向量并没有什么坏处。\n\n// 这个函数唯一的变化是：首先，我们不必为速度 $v$ 预测初始值，因为我们知道它是零。其次，我们在构造函数中计算的检测器位置上评估解决方案。这是用 VectorTools::point_value 函数完成的。然后，这些值被写入我们在函数开始时打开的一个文件中。\n\n  template <int dim> \n  void TATForwardProblem<dim>::run() \n  { \n    setup_system(); \n\n    VectorTools::project(dof_handler, \n                         constraints, \n                         QGauss<dim>(fe.degree + 1), \n                         InitialValuesP<dim>(), \n                         old_solution_p); \n    old_solution_v = 0; \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 (time = time_step; time <= end_time; \n         time += time_step, ++timestep_number) \n      { \n        std::cout << std::endl; \n        std::cout << \"time_step \" << timestep_number << \" @ t=\" << time \n                  << 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        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        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        old_solution_p = solution_p; \n        old_solution_v = solution_v; \n      } \n  } \n} // namespace Step24 \n\n//  @sect3{The <code>main</code> function}  \n\n// 剩下的就是程序的主要功能了。这里没有什么是在前面几个程序中没有展示过的。\n\nint main() \n{ \n  try \n    { \n      using namespace Step24; \n\n      TATForwardProblem<2> forward_problem_solver; \n      forward_problem_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": "6fac3aa86212abf871f34c8045056642fb845221", "size": 15698, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-24/step-24.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-24/step-24.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-24/step-24.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.2751091703, "max_line_length": 417, "alphanum_fraction": 0.6228181934, "num_tokens": 5995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.5960172925953622}}
{"text": "#ifndef MI4_NORMALIZER_HPP\n#define MI4_NORMALIZER_HPP 1\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace mi4\n{\n        class Normalizer\n        {\n        private:\n                Normalizer& operator = ( const Normalizer& that ) = delete;\n                Normalizer& operator = ( Normalizer&& that ) = delete;\n                Normalizer ( const Normalizer& that ) = delete;\n                Normalizer ( Normalizer&& that ) = delete;\n        private:\n                Eigen::Affine3d _mat;\n                Eigen::Affine3d _inv;\n        public:\n                Normalizer ( const Eigen::AlignedBox3d& gbox, const Eigen::AlignedBox3d& lbox = Eigen::AlignedBox3d ( Eigen::Vector3d ( 0, 0, 0 ), Eigen::Vector3d ( 1, 1, 1 ) ) )\n                {\n                        const auto v0 = this->avoid_zero ( gbox.max() - gbox.min() );\n                        const auto v1 = this->avoid_zero ( lbox.max() - lbox.min() );\n                        this->_mat = Eigen::Translation3d ( lbox.min() )\n                                     * Eigen::Scaling ( v1.x() / v0.x(), v1.y() / v0.y(), v1.z() / v0.z() )\n                                     * Eigen::Translation3d ( -gbox.min() );\n                        this->_inv = this->_mat.inverse();\n                        return;\n                }\n                Normalizer ( const Eigen::Vector3d& bmin,\n                             const Eigen::Vector3d& bmax,\n                             const Eigen::Vector3d& lmin = Eigen::Vector3d ( 0, 0, 0 ),\n                             const Eigen::Vector3d& lmax = Eigen::Vector3d ( 1, 1, 1 ) )\n                {\n                        const auto v0 = this->avoid_zero ( bmax - bmin );\n                        const auto v1 = this->avoid_zero ( lmax - lmin );\n                        this->_mat = Eigen::Translation3d ( lmin )\n                                     * Eigen::Scaling ( v1.x() / v0.x(), v1.y() / v0.y(), v1.z() / v0.z() )\n                                     * Eigen::Translation3d ( -bmin );\n                        this->_inv = this->_mat.inverse();\n\n                        return;\n                }\n\n                ~Normalizer ( void ) = default;\n\n                Eigen::Vector3d normalize ( const Eigen::Vector3d& p ) const\n                {\n                        return this->_mat * p;\n                }\n\n                Eigen::Vector3d denormalize ( const Eigen::Vector3d& p ) const\n                {\n                        return this->_inv * p;\n                }\n\n        private:\n                // avoid zero-denominator.\n                inline Eigen::Vector3d avoid_zero ( const Eigen::Vector3d& v ) const\n                {\n                        Eigen::Vector3d result;\n                        result.x() = this->check_zero ( v.x() );\n                        result.y() = this->check_zero ( v.y() );\n                        result.z() = this->check_zero ( v.z() );\n                        return result;\n                }\n\n                inline double check_zero ( const double& v ) const\n                {\n                        return ( v < 1.0e-40 ) ? 1 : v;\n                }\n        };\n}\n#endif\n", "meta": {"hexsha": "475315db8518eda023d2d920bb549830e4a2efc2", "size": 3122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/Normalizer.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/Normalizer.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/Normalizer.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": 41.6266666667, "max_line_length": 178, "alphanum_fraction": 0.4192825112, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5959827031319633}}
{"text": "#include \"smoothingSpline.h\"\r\n\r\n#include <Eigen/Geometry>\r\n\r\nusing namespace BIGSS;\r\n\r\nsmoothingSpline::smoothingSpline(const Eigen::VectorXd &y, const double lambda)\r\n{\r\n  Eigen::VectorXd x;\r\n  x.setLinSpaced(y.size(), 0, 1);\r\n  createSpline(x, y, lambda);\r\n}\r\n\r\nsmoothingSpline::smoothingSpline(const Eigen::VectorXd &x, const Eigen::VectorXd &y, const double lambda)\r\n{\r\n  createSpline(x, y, lambda);\r\n}\r\n\r\nsmoothingSpline::~smoothingSpline()\r\n{\r\n\r\n}\r\n\r\ndouble smoothingSpline::evaluate(const double x)\r\n{\r\n  double dx = x - breaks(0);\r\n  int i;\r\n  for (i = 1; i < breaks.size(); i ++)\r\n  {\r\n    if (x - breaks(i) <= 0)\r\n      break;\r\n    dx = x - breaks(i);\r\n  }      \r\n  double val = coeffs(i-1,0)*dx*dx*dx + coeffs(i-1,1)*dx*dx + coeffs(i-1,2)*dx + coeffs(i-1,3);\r\n  return val;\r\n}\r\n\r\nEigen::VectorXd smoothingSpline::evaluate(const Eigen::VectorXd &x)\r\n{\r\n  Eigen::VectorXd y = x;\r\n  for (int i = 0; i < x.size(); i++)\r\n  {\r\n    y(i) = evaluate(x(i));\r\n  }\r\n  return y;\r\n}\r\n\r\nvoid smoothingSpline::createSpline(const Eigen::VectorXd &x, const Eigen::VectorXd &y, const double lambda)\r\n{\r\n  Eigen::DenseIndex n = y.size() - 1;\r\n  Eigen::VectorXd h = x.segment(1, n) - x.segment(0, n);\r\n  Eigen::MatrixXd R = Eigen::MatrixXd::Zero(n-1, n-1);\r\n\r\n  R(0, 0) = 2*(h(0) + h(1));\r\n  for (int i = 1; i < n-2; i++)\r\n  {\r\n    R(i, i) = 2*(h(i) + h(i+1));\r\n    R(i-1, i) = h(i);\r\n    R(i, i-1) = h(i);\r\n  }\r\n\r\n  Eigen::VectorXd r = 3 / h.array();\r\n\r\n  Eigen::MatrixXd Qt = Eigen::MatrixXd::Zero(n-1, n+1);\r\n  for (int i = 0; i < n-1; i++)\r\n  {\r\n    Qt(i, i) = r(i);\r\n    Qt(i, i+1) = -(r(i) + r(i+1));\r\n    Qt(i, i+2) = r(i+1);\r\n  }\r\n\r\n  // weights are just the identity matrix\r\n  Eigen::MatrixXd E = Eigen::MatrixXd::Identity(n+1, n+1);\r\n\r\n  double mu = 2*(1-lambda)/(3*lambda);\r\n\r\n  Eigen::MatrixXd A = mu * Qt * E * Qt.transpose() + R;\r\n  Eigen::VectorXd B = Qt * y;\r\n\r\n  Eigen::VectorXd b_1 = A.ldlt().solve(B); // A is guaranteed to be symmetric with 5 diagonal bands\r\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(n+1);\r\n  b.segment(1,n-1) = b_1;\r\n\r\n  Eigen::VectorXd d = y - mu * E * Qt.transpose() * b_1;\r\n  Eigen::VectorXd a = (b.segment(1,n) - b.head(n)).array() / (3*h.array());\r\n  // NOTE: There is a typo in the referenced paper for finding the c coefficient.\r\n  //       The formula here is correct.\r\n  Eigen::VectorXd c = (d.segment(1, n) - d.head(n)).array() / h.array() - 1.0 / 3.0 * (b.segment(1, n) + 2 * b.head(n)).array() * h.array();\r\n\r\n  coeffs = Eigen::MatrixXd::Zero(n, 4);\r\n  coeffs.col(0) = a;\r\n  coeffs.col(1) = b.head(n);\r\n  coeffs.col(2) = c;\r\n  coeffs.col(3) = d.head(n);\r\n\r\n  breaks = x;\r\n}\r\n", "meta": {"hexsha": "9355e15bdb6f32a8e9b9041e78406db7def48002", "size": 2617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/bigssMath/smoothingSpline.cpp", "max_stars_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_stars_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:08:55.000Z", "max_issues_repo_path": "lib/bigssMath/smoothingSpline.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "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/bigssMath/smoothingSpline.cpp", "max_forks_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_forks_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-16T08:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T08:17:42.000Z", "avg_line_length": 26.7040816327, "max_line_length": 141, "alphanum_fraction": 0.5647688193, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5959804747438526}}
{"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 \"GLHelper.h\"\n\n#include <cmath>\n#include <Eigen/Dense>\n\nnamespace open3d {\n\nnamespace GLHelper {\n\nGLMatrix4f LookAt(const Eigen::Vector3d &eye, const Eigen::Vector3d &lookat,\n        const Eigen::Vector3d &up)\n{\n    Eigen::Vector3d front_dir = (eye - lookat).normalized();\n    Eigen::Vector3d up_dir = up.normalized();\n    Eigen::Vector3d right_dir = up_dir.cross(front_dir).normalized();\n    up_dir = front_dir.cross(right_dir).normalized();\n\n    Eigen::Matrix4d mat = Eigen::Matrix4d::Zero();\n    mat.block<1, 3>(0, 0) = right_dir.transpose();\n    mat.block<1, 3>(1, 0) = up_dir.transpose();\n    mat.block<1, 3>(2, 0) = front_dir.transpose();\n    mat(0, 3) = -right_dir.dot(eye);\n    mat(1, 3) = -up_dir.dot(eye);\n    mat(2, 3) = -front_dir.dot(eye);\n    mat(3, 3) = 1.0;\n    return mat.cast<GLfloat>();\n}\n\nGLMatrix4f Perspective(double field_of_view_, double aspect,\n        double z_near, double z_far)\n{\n    Eigen::Matrix4d mat = Eigen::Matrix4d::Zero();\n    double fov_rad = field_of_view_ / 180.0 * M_PI;\n    double tan_half_fov = std::tan(fov_rad / 2.0);\n    mat(0, 0) = 1.0 / aspect / tan_half_fov;\n    mat(1, 1) = 1.0 / tan_half_fov;\n    mat(2, 2) = -(z_far + z_near) / (z_far - z_near);\n    mat(3, 2) = -1.0;\n    mat(2, 3) = -2.0 * z_far * z_near / (z_far - z_near);\n    return mat.cast<GLfloat>();\n}\n\nGLMatrix4f Ortho(double left, double right, double bottom, double top,\n        double z_near, double z_far)\n{\n    Eigen::Matrix4d mat = Eigen::Matrix4d::Zero();\n    mat(0, 0) = 2.0 / (right - left);\n    mat(1, 1) = 2.0 / (top - bottom);\n    mat(2, 2) = -2.0 / (z_far - z_near);\n    mat(0, 3) = -(right + left) / (right - left);\n    mat(1, 3) = -(top + bottom) / (top - bottom);\n    mat(2, 3) = -(z_far + z_near) / (z_far - z_near);\n    mat(3, 3) = 1.0;\n    return mat.cast<GLfloat>();\n}\n\nEigen::Vector3d Project(const Eigen::Vector3d &point, \n        const GLMatrix4f &mvp_matrix, const int width, const int height)\n{\n    Eigen::Vector4d pos = mvp_matrix.cast<double>() *\n            Eigen::Vector4d(point(0), point(1), point(2), 1.0);\n    if (pos(3) == 0.0) {\n        return Eigen::Vector3d::Zero();\n    }\n    pos /= pos(3);\n    return Eigen::Vector3d(\n            (pos(0) * 0.5 + 0.5) * (double)width,\n            (pos(1) * 0.5 + 0.5) * (double)height,\n            (1.0 + pos(2)) * 0.5);\n}\n\nEigen::Vector3d Unproject(const Eigen::Vector3d &screen_point,\n        const GLMatrix4f &mvp_matrix, const int width, const int height)\n{\n    Eigen::Vector4d point = mvp_matrix.cast<double>().inverse() *\n            Eigen::Vector4d(screen_point(0) / (double)width * 2.0 - 1.0,\n            screen_point(1) / (double)height * 2.0 - 1.0,\n            screen_point(2) * 2.0 - 1.0, 1.0);\n    if (point(3) == 0.0) {\n        return Eigen::Vector3d::Zero();\n    }\n    point /= point(3);\n    return point.block<3, 1>(0, 0);\n}\n\nint ColorCodeToPickIndex(const Eigen::Vector4i &color)\n{\n    if (color(0) == 255) {\n        return -1;\n    } else {\n        return ((color(0) * 256 + color(1)) * 256 + color(2)) * 256 + color(3);\n    }\n}\n\n}    // namespace GLHelper\n\n}    // namespace open3d\n", "meta": {"hexsha": "4f7158fde202df6b752a17e0ee2760c1cdc21779", "size": 4550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Visualization/Utility/GLHelper.cpp", "max_stars_repo_name": "dmontagu/Open3D", "max_stars_repo_head_hexsha": "0667179c2d69f3e191104b6f70378b4dee6f406a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-24T20:32:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-19T03:27:27.000Z", "max_issues_repo_path": "src/Visualization/Utility/GLHelper.cpp", "max_issues_repo_name": "dmontagu/Open3D", "max_issues_repo_head_hexsha": "0667179c2d69f3e191104b6f70378b4dee6f406a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-21T08:31:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-21T08:31:54.000Z", "max_forks_repo_path": "src/Visualization/Utility/GLHelper.cpp", "max_forks_repo_name": "Surfndez/Open3D", "max_forks_repo_head_hexsha": "59c0645a169c589345a1b04753d5afdb5800b349", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-31T07:27:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T05:58:47.000Z", "avg_line_length": 36.6935483871, "max_line_length": 80, "alphanum_fraction": 0.5905494505, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5959804733141859}}
{"text": "/**\n * \\file dcs/math/stats/distribution/discrete_uniform.hpp\n *\n * \\brief The \\c discrete_uniform distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_DISCRETE_UNIFORM_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_DISCRETE_UNIFORM_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 // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION\n\n#include <boost/random/uniform_int_distribution.hpp>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\nusing ::std::size_t;\n\n\n/**\n * \\brief The discrete uniform distribution with parameter \\f$a\\f$ (the minimum\n * value) and \\f$b\\f$ (the maximum value).\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename IntT=int, typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass discrete_uniform_distribution\n{\n\tpublic: typedef IntT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit discrete_uniform_distribution(support_type a=0, support_type b=std::numeric_limits<support_type>::max())\n\t\t: a_(a),\n\t\t  b_(b)\n\t{\n\t\t// empty\n\t}\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this discrete\n\t * uniform distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this discrete uniform\n\t * distribution.\n\t *\n\t * A \\c discrete_uniform random number distribution produces random numbers\n\t * \\f$x\\f$, \\f$a \\le x \\le b\\f$, distributed according to the constant\n\t * probability density function:\n\t * \\f[\n\t *   \\Pr(x|a,b) = \\frac{1}{(b - a + 1)}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tvalue_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\ttypedef ::boost::random::uniform_int_distribution<support_type> variate_type;\n//\t\ttypedef ::boost::uniform_int<support_type> rdist_type;\n//\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n//\n//\t\treturn variate_type(rng, rdist_type(a_, b_))();\n\t\treturn variate_type(a_, b_)(rng);\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * discrete uniform distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A random number distributed according to this discrete uniform\n\t * distribution.\n\t *\n\t * A \\c discrete_uniform random number distribution produces random numbers\n\t * \\f$x\\f$, \\f$a \\le x \\le b\\f$, distributed according to the constant\n\t * probability density function:\n\t * \\f[\n\t *   \\Pr(x|a,b) = \\frac{1}{(b - a + 1)}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, size_t n)\n\t{\n        typedef ::boost::random::uniform_int_distribution<support_type> variate_type;\n\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(variate_type(a_, b_)(rng));\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type min() const\n\t{\n\t\treturn a_;\n\t}\n\n\n\tpublic: support_type max() const\n\t{\n\t\treturn b_;\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn (b_-a_+1);\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn a_;\n\t}\n\n\n\tprivate: support_type a_;\n\tprivate: support_type b_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, discrete_uniform_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"DUniform(\"\n\t\t\t  << \"min=\" <<  dist.min()\n\t\t\t  << \", max=\" <<  dist.max()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_DISCRETE_UNIFORM_HPP\n", "meta": {"hexsha": "afa743194668794f4e12ff0de988f40e747713c9", "size": 4661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/discrete_uniform.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/discrete_uniform.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/discrete_uniform.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.3333333333, "max_line_length": 154, "alphanum_fraction": 0.7146535078, "num_tokens": 1222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.5959804669977742}}
{"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_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ULPDIST_HPP_INCLUDED\n\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/dist.hpp>\n#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/is_nan.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/config.hpp>\n#include <tuple>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( ulpdist_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::int_<A0> >\n                          , bd::scalar_< bd::int_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return (a0>a1) ? saturated_(minus)(a0,a1) : saturated_(minus)(a1,a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( ulpdist_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::uint_<A0> >\n                          , bd::scalar_< bd::uint_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return dist(a0,a1);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( ulpdist_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      using i_t = bd::as_integer_t<A0>;\n\n      if (a0 == a1)               return Zero<A0>();\n      if (is_nan(a0)&&is_nan(a1)) return Zero<A0>();\n\n      i_t e1, e2;\n      A0 m1, m2;\n      std::tie(m1, e1) = pedantic_(ifrexp)(a0);\n      std::tie(m2, e2) = pedantic_(ifrexp)(a1);\n\n      i_t expo = -simd::max(e1, e2);\n\n      A0 e = (e1 == e2) ? simd::abs(m1-m2)\n        :   simd::abs( simd::pedantic_(ldexp)(a0, expo)\n                              - simd::pedantic_(ldexp)(a1, expo)\n                            );\n      return e/Eps<A0>();\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "15503b417d3aac1a4e2cf45c372b124bd3875d11", "size": 2904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/ulpdist.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/ulpdist.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/ulpdist.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.2666666667, "max_line_length": 100, "alphanum_fraction": 0.5172176309, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.5959804572242848}}
{"text": "/**\n * Copyright (c) 2020 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 estimate-point-normals.hpp\n * @author Matyas Hollmann <matyas.hollmann@melowntech.com>\n *\n * Estimation of point normals in the point cloud.\n * Code based on window-mesh-legacy.cpp\n * \n * Note: Uses Eigen3 library.\n *       \n */\n\n#ifndef ESTIMATE_POINT_NORMALS_HPP_INCLUDED\n#define ESTIMATE_POINT_NORMALS_HPP_INCLUDED\n\n#include <Eigen/Dense>\n\n#include \"dbglog/dbglog.hpp\"\n#include \"utility/openmp.hpp\"\n\n#include \"kdtree.hpp\"\n#include \"neighbors.hpp\"\n\nnamespace geometry {\n/**\n * Estimate the normal of a point (in K-dim space) based on the data matrix (N x K) \n * which as rows has point itself and its (N - 1) closest neighbors. \n * The estimation of the normal is based on the principal-component analysis\n * of the data, a SVD of the covariance matrix (K x K) is performed.\n **/\nEigen::VectorXd estimateNormal(const Eigen::MatrixXd& data);\n\n/**\n *  Interface to access dimension values of a point, and to calculate the\n *  difference of two points.\n **/\ntemplate <typename T>\nstruct DefaultAccessor {\n    typedef typename T::value_type value_type;\n    typedef T difference_type;\n\n    static inline typename T::value_type get(const T& pt, unsigned dim) {\n        return pt(dim);\n    }\n\n    static inline void set(T& pt, unsigned dim, const typename T::value_type& val) {\n        pt(dim) = val;\n    }\n\n    // used in Kdtree in calculation of the distance of two points\n    static inline T diff(const T& op1, const T& op2) {\n        return op1 - op2;\n    }\n};\n\n/**\n *\n *  Estimate normals of all points in the input point pointcloud. \n * \n *  typename T:     point in a K-dimensional space\n *  unsigned K:     number of dimensions of the space\n *  typename A:     dimension value accessor (has to support get(),\n *                               set() and also diff() [used in Kdtree]\n */\ntemplate<typename T, unsigned K = 3, typename A = DefaultAccessor<T>>\nstd::vector<T> estimateNormals(const std::vector<T>& pointCloud,\n                               unsigned nEstimatorPts = 40,\n                               double radius = 0)\n{\n    static_assert(K >= 2,\n                  \"Estimation of point normals makes sense only in at least \"\n                  \"2-dimensional space.\");\n    using Neighbor = typename KdTree<T, K, A>::Neighbor;\n    using Neighbors = typename KdTree<T, K, A>::Neighbors;\n    \n    auto toEigen([](const Neighbor& n) -> Eigen::RowVectorXd {\n        Eigen::RowVectorXd vec(K);\n        for (unsigned t = 0; t < K; ++t) {\n            vec(t) = A::get(n.first, t);\n        }\n        return vec;\n    });\n    \n    auto fromEigen([](const Eigen::VectorXd& vec) -> T {\n        T res;\n        for (unsigned t = 0; t < K; ++t) {\n            A::set(res, t, vec(t));\n        }\n        return res;\n    });\n\n    auto setZeros([](T& pt) -> void {\n        for (unsigned t = 0; t < K; ++t) {\n            A::set(pt, t, 0);\n        }\n    });\n\n    const size_t nPoints(pointCloud.size());\n    // prepare space for normals\n    std::vector<T> normals(nPoints);\n    \n    LOG(info3) << \"Building a kd-tree from the pointcloud of \"\n               << nPoints << \" points.\";\n    KdTree<T, K, A> kdtree(pointCloud.begin(), pointCloud.end());\n\n    /** per thread accumulative variables **/\n    double searchRadiusTotal(0.0);\n    size_t pointsProcessed(0);\n\n    UTILITY_OMP(parallel for schedule(static) default(shared) \n               firstprivate(searchRadiusTotal, pointsProcessed))\n    for (std::int64_t i = 0; i < static_cast<std::int64_t>(nPoints); ++i)\n    {\n        const T& point(pointCloud[i]);\n        T& normal(normals[i]);\n\n        // Mode 1: use provided radius as search radius\n        double searchRadius = radius;\n        if (radius <= 0.0) {\n            // Mode 2: search radius is variable and is based on the average\n            // radius needed to reach the specified number of neighbors\n            searchRadius = ((searchRadiusTotal && pointsProcessed)\n                                ? (searchRadiusTotal / pointsProcessed)\n                                : 1.0);\n            ++pointsProcessed;\n        }\n\n        Neighbors neighbors;\n        // find neighbors\n        searchRadiusTotal += collectNeighbors(kdtree, point, neighbors\n                                              , nEstimatorPts\n                                              , searchRadius\n                                              , (radius > 0));\n\n        size_t nNeighs = neighbors.size();\n        if (nNeighs < nEstimatorPts) {\n            // Oops, normal stays zero -> we may deal with this later\n            LOG(warn3) << \"too few neighbors! (\" << nNeighs << \")\";\n            setZeros(normal);\n            continue;\n        }\n        \n        Eigen::MatrixXd samples(nNeighs, K);\n        for (size_t j = 0; j < nNeighs; ++j)\n        {\n            samples.row(j) = toEigen(neighbors[j]);\n        }\n\n        // calculate normal\n        normal = fromEigen(estimateNormal(samples));\n    }\n    return normals;\n}\n\n/**\n * @brief Orients point cloud normals to outward directions.\n *\n * @param pointCloud  Input points cloud\n * @param normals     Estimated normals (with undetermined orientation) for each point\n * @param pointRadius Radius of a patch associated with each point. Must be large enough\n *                    for the point patches to overlap and cover the surface.\n */\nvoid reorientNormals(const std::vector<math::Point3>& pointCloud\n                     , std::vector<math::Point3>& normals\n                     , double pointRadius);\n\n} // geometry\n\n#endif // ESTIMATE_POINT_NORMALS_HPP_INCLUDED\n", "meta": {"hexsha": "fd390c2f225661c7337cb36ab928a71f4ada02b6", "size": 6872, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/estimate-point-normals.hpp", "max_stars_repo_name": "Melown/libgeometry", "max_stars_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T06:52:15.000Z", "max_issues_repo_path": "geometry/estimate-point-normals.hpp", "max_issues_repo_name": "Melown/libgeometry", "max_issues_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "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": "geometry/estimate-point-normals.hpp", "max_forks_repo_name": "Melown/libgeometry", "max_forks_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4226804124, "max_line_length": 88, "alphanum_fraction": 0.621798603, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5959712550685842}}
{"text": "/*\n * Website:\n *      https://github.com/wo3kie/dojo\n *\n * Author:\n *      Lukasz Czerwinski\n *\n * Training set:\n *      http://www.dt.fee.unicamp.br/~tiago/smsspamcollection/smsspamcollection.zip\n *\n * Compilation:\n *      g++ --std=c++11 bayes.cpp -o bayes\n *\n * Usage:\n *      $ ./bayes\n *      URGENT! You have won a 1 week FREE membership in our £100,000 Prize Jackpot!\n *      ...\n *      {{ham,-118.253},{spam,-89.9372}}\n */\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <string>\n\n#include <boost/tokenizer.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"./output.hpp\"\n\nstruct ItemStats\n{\n    unsigned counter_ = 0;\n    double probability_ = 0;\n};\n\nstruct ClassStats\n{\n    unsigned itemCounter_ = 0;\n    double minProbability_ = 1;\n    std::map< std::string, ItemStats > itemStats_;\n};\n\nclass NaiveBayes\n{\npublic:\n    void learn( std::string const className, std::vector< std::string > const & items ){\n        itemCounter_ += 1;\n\n        ClassStats & classStats = stats_[ className ];\n        classStats.itemCounter_ += 1;\n\n        for( auto const & item : items ){\n            classStats.itemStats_[ item ].counter_ += 1;\n        }\n    }\n\n    void recalculateStats(){\n        for( auto & clazz : stats_ ){\n            recalculateClass( clazz );\n        }\n    }\n\n    std::map< std::string, double > classify( std::vector< std::string > const & items ) const {\n        std::map< std::string, double > classes;\n\n        for( auto const & pair : stats_ ){\n            std::string const & name = pair.first;\n            ClassStats const & stat = pair.second;\n\n            double const classProbability = 1.0 * stat.itemCounter_ / itemCounter_;\n            classes[ name ] = std::log( classProbability ) + classifyClass( pair, items ); \n\n            std::cout\n                << \"class '\" << name << \"'\"\n                << \" has probability: \" << classProbability \n                << \" (\" << std::log( classProbability ) << \")\"\n                << \" and a final result: \" << classes[ name ]\n                << std::endl;\n        }\n\n        return classes;\n    }\n\nprivate:\n    static double classifyClass(\n        std::pair< std::string const, ClassStats > const & clazz,\n        std::vector< std::string > const & items\n    ){\n        std::string const & name = clazz.first;\n        ClassStats const & stats = clazz.second;\n\n        double probability = 0;\n\n        for( auto const & item : items ){\n            auto const & itemIterator = stats.itemStats_.find( item );\n\n            if( itemIterator == stats.itemStats_.end() ){\n                probability += std::log( stats.minProbability_ );\n\n                std::cout\n                    << \"class '\" << name << \"'\"\n                    << \" item '\" << item << \"'\" \n                    << \" not found: \" << stats.minProbability_ \n                    << \" (\" << std::log( stats.minProbability_ ) << \")\"\n                    << std::endl;\n            }\n            else{\n                probability += std::log( itemIterator->second.probability_ );\n\n                std::cout\n                    << \"class '\" << name << \"'\"\n                    << \" item '\" << item  << \"'\"\n                    << \" found: \" << itemIterator->second.probability_\n                    << \" (\" << std::log( itemIterator->second.probability_ ) << \")\"\n                    << std::endl;\n            }\n        }\n\n        return probability;\n    }\n\n    static void recalculateClass( std::pair< std::string const, ClassStats > & clazz ){\n        unsigned allItemsCounter = 0;\n        ClassStats & classStats = clazz.second;\n\n        for( auto const & pair : classStats.itemStats_ ){\n            ItemStats const & itemStats = pair.second;\n\n            allItemsCounter += itemStats.counter_;\n        }\n\n        for( auto & pair : classStats.itemStats_ ){\n            ItemStats & itemStats = pair.second;\n            \n            itemStats.probability_ = 1.0 * itemStats.counter_ / allItemsCounter;\n        }\n\n        double minProbability = 1;\n\n        for( auto const & pair : clazz.second.itemStats_ ){\n            ItemStats const & itemStats = pair.second;\n\n            if( minProbability > itemStats.probability_ ){\n                minProbability = itemStats.probability_;\n            }\n        }\n\n        classStats.minProbability_ = minProbability;\n\n    }\n\nprivate:\n    unsigned itemCounter_ = 0;\n    std::map< std::string, ClassStats > stats_;\n};\n\nint main(){\n    NaiveBayes bayes;\n\n    std::ifstream spamFile( \"bayes.spam.txt\" );\n\n    if( ! spamFile ){\n        std::cerr << \"ERROR: Can not open a file 'bayes.spam.txt'\" << std::endl;\n        return 1;\n    }\n\n    std::string line;\n\n    while( std::getline( spamFile, line ) ){\n        boost::tokenizer<> tokenizer( line );\n\n        std::vector< std::string > items;\n\n        for( std::string const & token : tokenizer ){\n            items.push_back( boost::algorithm::to_lower_copy( token ) );\n        }\n            \n        bayes.learn( \"spam\", items );\n    }\n\n    std::ifstream hamFile( \"bayes.ham.txt\" );\n\n    if( ! hamFile ){\n        std::cerr << \"ERROR: Can not open a file 'bayes.ham.txt'\" << std::endl;\n        return 2;\n    }\n\n    while( std::getline( hamFile, line ) ){\n        boost::tokenizer<> tokenizer( line );\n\n        std::vector< std::string > items;\n\n        for( std::string const & token : tokenizer ){\n            items.push_back( boost::algorithm::to_lower_copy( token ) );\n        }\n        \n        bayes.learn( \"ham\", items );\n    }\n\n    bayes.recalculateStats();\n\n    while( std::getline( std::cin, line ) ){\n        std::vector< std::string > items;\n        boost::tokenizer<> tokenizer( line );\n\n        for( std::string const & token : tokenizer ){\n            items.push_back( boost::algorithm::to_lower_copy( token ) );\n        }\n\n        std::map< std::string, double > const & classesProbability\n            = bayes.classify( items );\n\n        std::cout << classesProbability << std::endl;\n\n        return 0;\n    }\n}\n\n", "meta": {"hexsha": "273fa2b67d2142e1f8072bf6856e686b2a9a8eba", "size": 5974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bayes.cpp", "max_stars_repo_name": "wo3kie/cxxDojo", "max_stars_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-10-26T22:06:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-25T14:35:00.000Z", "max_issues_repo_path": "bayes.cpp", "max_issues_repo_name": "wo3kie/dojo", "max_issues_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayes.cpp", "max_forks_repo_name": "wo3kie/dojo", "max_forks_repo_head_hexsha": "c63388eb37a62272bfb9ca5c0b207fc5387a29ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0316742081, "max_line_length": 96, "alphanum_fraction": 0.5324740542, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522813, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5959712499158191}}
{"text": "#include \"stdafx.h\"\n\n#include <vector>\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 <iostream>\n\n#include <math/func.h>\n#include <math/matrix.h>\n#include <math/SparseBlockSquareMatrix.h>\n\n#include <import.h>\n#include <api/cl_wrapper.h>\n\n#include <time.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 ( 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\nvoid cl_reduction(\n\tcl::CommandQueue &cq,\n\tcl::Kernel &kn_reduction,\n\tcl::Mem &mem,\n\tint elem_num,\n\tint global_work_size, int local_work_size\n) {\n\tint group_num = ( global_work_size + local_work_size - 1 ) / local_work_size;\n\tglobal_work_size = local_work_size * group_num;\n\twhile ( elem_num > 1 ) { // \n\t\tint activeGroupNum = std::min( group_num, ( elem_num + local_work_size - 1 ) / local_work_size );\n\t\tcq.Kernel1D( ( kn_reduction << (int)elem_num, (int)activeGroupNum, cl::Arg( sizeof( int ) * local_work_size ), mem ), local_work_size * activeGroupNum, local_work_size );\n\t\telem_num = activeGroupNum;\n\t}\n}\n\nfloat cl_dot_product(\n\tcl::CommandQueue &cq,\n\tcl::Kernel &kn_mul_v_v, cl::Kernel &kn_reduction,\n\tcl::Mem &mem_src0, cl::Mem &mem_src1, cl::Mem &mem_dst,\n\tint elem_num,\n\tint global_work_size, int local_work_size\n) {\n\t// rMr = r * Mr;\n\tcq.Kernel1D( (kn_mul_v_v << elem_num, mem_src0, mem_src1, mem_dst ), global_work_size, local_work_size );\n\t\t\n\t// rMr' = r dot rMr;\n\tcl_reduction( cq, kn_reduction, mem_dst, elem_num, global_work_size, local_work_size );\n\t\n\tfloat dot = 0.0f;\n\tcq.ReadBuffer( mem_dst, CL_TRUE, 0, sizeof( float ), &dot );\n\treturn dot;\n}\n\nclass cl_block_pcg {\npublic :\n\tint m_size, m_blockSize, m_gridSize;\n\n\tint m_numIters;\n\t\n\t// mem\n\t// static matrix\n\tcl::Mem mem_M;\n\tcl::Mem mem_A_blocks;\n\tcl::Mem mem_A_blockInfos;\n\tcl::Mem mem_A_rowScan;\n\n\t// updating vector\n\tcl::Mem mem_x;\n\tcl::Mem mem_p;\n\tcl::Mem mem_r;\n\t\n\t// temp vector\n\tcl::Mem mem_Mv;\n\tcl::Mem mem_dot;\n\t\n\t// kernel\n\tcl::Kernel kn_reduction;\n\tcl::Kernel kn_zero_v;\n\tcl::Kernel kn_mul_v_v;\n\tcl::Kernel kn_mad_v_s;\n\tcl::Kernel kn_mul_m_v;\n\t\n\tvoid genTopology( cl::Context &context, SparseBlockSquareMatrix &A ) {\n\t\tm_size = A.size();\n\t\tm_blockSize = A.blockSize();\n\t\tm_gridSize = A.gridSize();\n\n\t\tsize_t bufferSize = sizeof( float ) * m_size;\n\t\t\n\t\t// static topology\t\t\n\t\tmem_A_blockInfos.CreateBuffer( context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, A.m_blockInfos );\n\t\tmem_A_rowScan.CreateBuffer( context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, A.m_rowScan );\n\n\t\t// matrix\n\t\tmem_A_blocks.CreateBuffer( context, CL_MEM_READ_WRITE, A.m_blocks.size() * sizeof( float ) );\n\t\tmem_M.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize ); // A diagonal\n\n\t\t// updating vector\n\t\tmem_x.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize );\n\t\tmem_p.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize );\n\t\tmem_r.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize );\n\t\n\t\t// temp vector\n\t\tmem_Mv.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize ); // Mr, Ap\n\t\tmem_dot.CreateBuffer( context, CL_MEM_READ_WRITE, bufferSize ); // rMr, pAp\n\t}\n\n\tvoid initMatrix( cl::CommandQueue &cq, SparseBlockSquareMatrix &A ) {\n\t\tsize_t bufferSize = sizeof( float ) * m_size;\n\t\tint local_work_size = 256;\n\t\tint global_work_size = ceil( m_size, local_work_size );\n\n\t\tEigen::VectorXf M = A.diagonal();\n\t\tfor ( int i = 0; i < M.rows(); i++ ) {\n\t\t\tif ( fabs( M[i] ) > 1e-6f ) {\n\t\t\t\tM[i] = 1.0f / M[i];\n\t\t\t} else {\n\t\t\t\tM[i] = 1.0f;\n\t\t\t}\n\t\t}\n\n\t\tcq.WriteBuffer( mem_A_blocks, CL_TRUE, A.m_blocks );\n\t\tcq.WriteBuffer( mem_M, CL_TRUE, 0, bufferSize, M.data() );\n\t}\n\n\tvoid initVector( cl::CommandQueue &cq, Eigen::VectorXf &b ) {\n\t\tsize_t bufferSize = sizeof( float ) * m_size;\n\t\tint local_work_size = 256;\n\t\tint global_work_size = ceil( m_size, local_work_size );\n\t\t\n\t\t// x = 0;\n\t\tcq.Kernel1D( (kn_zero_v << m_size, mem_x), global_work_size, local_work_size );\n\t\t//cq.WriteBuffer( mem_x, CL_TRUE, 0, bufferSize, x.data() );\n\n\t\t// p = 0;\n\t\tcq.Kernel1D( (kn_zero_v << m_size, mem_p), global_work_size, local_work_size );\n\n\t\t// r = b = b - A * x\n\t\tcq.WriteBuffer( mem_r, CL_TRUE, 0, bufferSize, b.data() );\n\t}\n\n\tvoid getResult( cl::CommandQueue &cq, Eigen::VectorXf &x ) {\n\t\tx = Eigen::VectorXf::Zero( m_size );\n\t\tsize_t bufferSize = sizeof( float ) * m_size;\n\t\tcq.ReadBuffer( mem_x, CL_TRUE, 0, bufferSize, x.data() );\n\t}\n\n\tvoid compute(\n\t\tcl::CommandQueue &cq,\n\t\tint maxIters,\n\t\tfloat threshold,\n\t\tint local_work_size,\n\t\tint local_work_size_A\n\t) {\n\t\tint global_work_size = ceil( m_size, local_work_size );\n\n\t\tm_numIters = 0;\t\n\t\tclock_t begin = clock();\n\t\tfor ( int i = 0; i < maxIters; i++ ) {\n\t\t\tm_numIters++;\n\n\t\t\t// Mr = M * r;\n\t\t\tcq.Kernel1D( (kn_mul_v_v << m_size, mem_M, mem_r, mem_Mv ), global_work_size, local_work_size );\n\n\t\t\t// rMr = r dot Mr;\n\t\t\tfloat rMr = cl_dot_product( cq, kn_mul_v_v, kn_reduction, mem_r, mem_Mv, mem_dot, m_size, global_work_size, local_work_size );\n\t\t\tif ( rMr < threshold * m_size ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif ( threshold <= 0 && rMr < 1e-6 ) {\n\t\t\t\trMr = 0.0f;\n\t\t\t} else {\n\t\t\t\trMr = 1.0f / rMr;\n\t\t\t}\n\n\t\t\t// p += Mr / rMr'\n\t\t\tcq.Kernel1D( (kn_mad_v_s << m_size, mem_Mv, rMr, mem_p ), global_work_size, local_work_size );\n\n\t\t\t// Ap = A * p\n\t\t\tcq.Kernel1D( (kn_zero_v << m_size, mem_Mv), global_work_size, local_work_size );\n\t\t\t//cq.Kernel1D( (kn_mul_m_v << m_gridSize, mem_A_rowScan, mem_A_blockInfos, mem_A_blocks, mem_p, mem_Mv ), ceil( m_gridSize, 256 ), 256 );\n\t\t\tcq.Kernel1D( (kn_mul_m_v << m_gridSize, m_blockSize, mem_A_rowScan, mem_A_blockInfos, mem_A_blocks, mem_p, mem_Mv, cl::Arg( m_blockSize * local_work_size_A * sizeof( float ) ) ), m_gridSize *local_work_size_A, local_work_size_A );\n\n\t\t\t// pAp = p dot Ap\n\t\t\tfloat pAp = cl_dot_product( cq, kn_mul_v_v, kn_reduction, mem_p, mem_Mv, mem_dot, m_size, global_work_size, local_work_size );\n\t\t\tif ( threshold <= 0 && pAp < 1e-6 ) {\n\t\t\t\tpAp = 0.0f;\n\t\t\t} else {\n\t\t\t\tpAp = 1.0f / pAp;\n\t\t\t}\n\n\t\t\t// r -= Ap / pAp;\n\t\t\tcq.Kernel1D( (kn_mad_v_s << m_size, mem_Mv, -pAp, mem_r), global_work_size, local_work_size );\n\n\t\t\t// x +=  p / pAp;\n\t\t\tcq.Kernel1D( (kn_mad_v_s << m_size, mem_p , pAp, mem_x), global_work_size, local_work_size );\n\n#if 0\n\t\t\tfloat rme =  cl_dot_product( cq, kn_mul_v_v, kn_reduction, mem_r, mem_r, mem_dot, m_size, global_work_size, local_work_size );\n\t\t\trme = sqrt( rme / m_size );\n\t\t\tprintf( \"PCG : %d : %.3f\\n\", i, rme );\n\t\t\tif ( rme < 1e-6 ) {\n\t\t\t\tbreak;\n\t\t\t}\n#endif\n\t\t}\n\t\tcq.Finish();\n\n\t\tclock_t end = clock();\n\t\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\n\t\tprintf( \"pcg gpu (ms) : %.3f : %.3f : %d\\n\", time_spent * 1000, time_spent * 1000 / m_numIters, m_numIters );\n\t}\n\n\tvoid compileProgram( cl::Context &context ) {\n\t\t// read source\n\t\t{\n\t\t\tstd::vector<char> source;\n\t\t\tread_text_file( \"../../src/cl-shader/reduction.txt\", source );\n\t\t\tconst char *sources[] = {\n\t\t\t\t\"#define T float\\n\",\n\t\t\t\tsource.data(),\n\t\t\t\t0\n\t\t\t};\n\n\t\t\t// program\n\t\t\tconst char *flags = \"-cl-denorms-are-zero -cl-mad-enable -cl-no-signed-zeros\";\n\t\t\tcl::Program program;\n\t\t\tprogram.Create( context, 2, sources, 0, flags );\n\n\t\t\t// kernal\n\t\t\tkn_reduction.Create( program, \"reduction\" );\n\t\t}\n\n\t\t{\n\t\t\tstd::vector<char> source;\n\t\t\tread_text_file( \"../../src/cl-shader/vector.txt\", source );\n\t\t\tconst char *sources[] = {\n\t\t\t\tsource.data(),\n\t\t\t\t0\n\t\t\t};\n\n\t\t\t// program\n\t\t\tconst char *flags = \"-cl-denorms-are-zero -cl-mad-enable -cl-no-signed-zeros\";\n\t\t\tcl::Program program;\n\t\t\tprogram.Create( context, 1, sources, 0, flags );\n\n\t\t\t// kernal\n\t\t\tkn_zero_v.Create( program, \"zero_v\" );\n\t\t\tkn_mul_v_v.Create( program, \"mul_v_v\" );\n\t\t\tkn_mad_v_s.Create( program, \"mad_v_s\" );\n\n\t\t\tkn_mul_m_v.Create( program, \"mul_m_v\" );\n\t\t}\n\t}\n};\n\nvoid TestPCG( void ) {\n\tint dim = 12 * 100;\n\n\t// A : positive definite matrix\n\tEigen::MatrixXf A = Eigen::MatrixXf::Random( dim, dim );\n\tA = A * A.transpose();\n\tA += Eigen::MatrixXf::Identity( dim, dim ) * dim;\n\tprintf( \"Random A\\n\" );\n\t//std::cout << A << std::endl;\n\n\t// x\n\tEigen::VectorXf x = Eigen::VectorXf::Random( dim );\n\n\t// b\n\tEigen::VectorXf b = A * x;\n\n#if 0\n\t{\n\t\tclock_t begin = clock();\n\t\tEigen::VectorXf xx = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n\t\tclock_t end = clock();\n\t\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\t\tprintf( \"cpu eigen time %fms\\n\", time_spent * 1000 );\n\t\t\n\t\tstd::cout << ( xx - x ).dot( xx - x ) / xx.rows() << std::endl << std::endl;\n\t}\n#endif\n\n\tstd::cout << std::endl << \"=============== Eigen ===============\" << std::endl;\n\t{\n\t\t// fill A and b\n\t\tEigen::ConjugateGradient<Eigen::MatrixXf, Eigen::Lower|Eigen::Upper> cg;\n\t\tclock_t begin = clock();\n\t\t\n\t\tcg.compute(A);\n\t\tx = cg.solve(b);\n\t\t\n\t\tclock_t end = clock();\n\t\tdouble time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\t\tprintf( \"cpu eigen (ms) : %.3f : %.3f : %d\\n\", time_spent * 1000, time_spent * 1000 / cg.iterations(), cg.iterations() );\n\t\tstd::cout << cg.error() << std::endl;\n\t}\n\n\tSparseBlockSquareMatrix B;\n\tB.createFromDenseMatrix( A, 12 );\n\t\n\tfloat threshold = 0.0f;\n\n\tstd::cout << std::endl << \"=============== CPU ===============\" << std::endl;\n\t{\n\t\tEigen::VectorXf xx = pcg( B, b, 100, threshold );\n\t\tstd::cout << ( xx - x ).dot( xx - x ) / xx.rows() << std::endl << std::endl;\n\t}\n\n\tstd::cout << std::endl << \"=============== GPU ===============\" << std::endl;\n\t{\n\t\t// context\n\t\tcl::Context context;\n\t\tcl::System::CreateContext( context );\n\t\tcl::CommandQueue cq( context );\n\n\t\tcl_block_pcg pcg;\n\t\tpcg.compileProgram( context );\n\n\t\tpcg.genTopology( context, B );\n\n\t\tpcg.initMatrix( cq, B );\n\t\tpcg.initVector( cq, b );\n\n\t\tpcg.compute( cq, 100, threshold, 256, 256 );\n\n\t\tEigen::VectorXf xx;\n\t\tpcg.getResult( cq, xx );\n\t\tstd::cout << ( xx - x ).dot( xx - x ) / xx.rows() << std::endl << std::endl;\n\t}\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tTestPCG();\n\t\n\treturn 0;\n}\n\n", "meta": {"hexsha": "5a03aaf7a32388d4338e9933c71f3e283390824c", "size": 10841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moca/proj-pcg/proj-pcg/proj-pcg.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-pcg/proj-pcg/proj-pcg.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-pcg/proj-pcg/proj-pcg.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": 27.4455696203, "max_line_length": 233, "alphanum_fraction": 0.6334286505, "num_tokens": 3660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5959635531289512}}
{"text": "#include \"Clausen.h\"\n#include <boost/math/special_functions/zeta.hpp>\nnamespace ucd {\n\ndouble Clausen( double theta )\n{\n    if ( theta == 0 )\n        return 0;\n    while ( theta < 0 )\n        theta += 2*M_PI;\n    while ( theta > 2*M_PI )\n        theta -= 2*M_PI;\n    if ( theta > M_PI )\n    {\n        theta -= M_PI;\n        double diff = theta - M_PI/2;\n        theta -= 2*diff;\n        return -Clausen( theta );\n    }\n\n    // precompute coefficients for the partial sum part of the Clausen\n    // function\n    static std::vector< double > coeff;\n    if ( coeff.size( ) == 0 )\n    {\n        std::vector< double > num, den, frac;\n        for ( int i = 1; i < 20; ++i )\n        {\n            num.push_back( boost::math::zeta( 2*i ) );\n            den.push_back( i*(2*i + 1) );\n            frac.push_back( num.back( ) / den.back( ) );\n        }\n\n        coeff.push_back( 0 );\n        for ( int i = 0; i < frac.size( ); ++i )\n        {\n            coeff.push_back( 0 );\n            coeff.push_back( frac[i] );\n        }\n    }\n\n    double res = 1 - log( theta );\n\n    double hornerSum = 0.0;\n    double term = theta / (2 * M_PI);\n    for ( int i = coeff.size( ) - 1; i >= 0; --i )\n    {\n        if ( i == coeff.size( ) - 1 )\n            hornerSum = coeff[i];\n        else\n            hornerSum = coeff[i] + hornerSum*term;\n    }\n    res += hornerSum;\n\n    return theta*res;\n}\n\n} // namespace ucd\n", "meta": {"hexsha": "84b78b288758583bb0c57062f9b9aad7189d237d", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Clausen.cpp", "max_stars_repo_name": "alextsui05/clausen", "max_stars_repo_head_hexsha": "35d73d0be20e4a1d22c6fbd7972c9bba39fa23c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Clausen.cpp", "max_issues_repo_name": "alextsui05/clausen", "max_issues_repo_head_hexsha": "35d73d0be20e4a1d22c6fbd7972c9bba39fa23c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Clausen.cpp", "max_forks_repo_name": "alextsui05/clausen", "max_forks_repo_head_hexsha": "35d73d0be20e4a1d22c6fbd7972c9bba39fa23c5", "max_forks_repo_licenses": ["Apache-2.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.5762711864, "max_line_length": 70, "alphanum_fraction": 0.4795111431, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5958932899153689}}
{"text": "/**\n * @file\n * @brief Investigates when parametrization from reference element breaks down\n * @author Anian Ruoss\n * @date   2019-02-04 13:36:17\n * @copyright MIT License\n */\n\n#include <lf/geometry/geometry.h>\n#include <lf/quad/quad.h>\n#include <lf/refinement/refinement.h>\n\n#include <Eigen/Eigen>\n#include <filesystem>\n#include <fstream>\n#include <string>\n\n/**\n * @brief Stores an Eigen::MatrixXd to .csv file\n * @param file_path path to .csv file\n * @param matrix matrix to be saved\n */\nvoid writeMatrixToCSV(const std::string& file_path,\n                      const Eigen::MatrixXd& matrix) {\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::ofstream file(file_path.c_str());\n  file << matrix.format(CSVFormat);\n  file.close();\n}\n\n/**\n * @brief Saves the global vertex/midpoint coordinates\n * @param file_path path to .csv file\n * @param geom second-order geometry object\n */\nvoid storeSecondOrderCoords(const std::string& file_path,\n                            const lf::geometry::Geometry& geom) {\n  const Eigen::MatrixXd& local_vertex_coords = geom.RefEl().NodeCoords();\n  const long num_vertices = local_vertex_coords.cols();\n\n  Eigen::MatrixXd all_local_coords(local_vertex_coords.rows(),\n                                   2 * num_vertices);\n\n  // compute local vertex and midpoint coordinates from reference element\n  for (auto col_idx = 0; col_idx < num_vertices; ++col_idx) {\n    all_local_coords.col(col_idx) = local_vertex_coords.col(col_idx);\n    all_local_coords.col(col_idx + num_vertices) =\n        (local_vertex_coords.col(col_idx) +\n         local_vertex_coords.col((col_idx + 1) % num_vertices)) /\n        2.;\n  }\n\n  writeMatrixToCSV(file_path, geom.Global(all_local_coords));\n}\n\n/**\n * @brief Evaluates parametrization and corresponding jacobian determinant\n * @param base_file_path base path for .csv files\n * @param geom geometry object\n * @param qr_order order of quadrature rule to sample points from\n */\nvoid storeParametrizationEvals(const std::string& base_file_path,\n                               const lf::geometry::Geometry& geom,\n                               const size_t& qr_order) {\n  // use quadrature to sample random points on the reference element\n  auto qr = lf::quad::make_QuadRule(geom.RefEl(), qr_order);\n\n  const auto& points = qr.Points();\n  const Eigen::MatrixXd& jacobians = geom.Jacobian(points);\n  Eigen::VectorXd determinants(points.cols());\n\n  for (Eigen::Index point_idx = 0; point_idx < points.cols(); ++point_idx) {\n    determinants(point_idx) = jacobians\n                                  .block(0, point_idx * geom.DimLocal(),\n                                         geom.DimGlobal(), geom.DimLocal())\n                                  .determinant();\n  }\n\n  writeMatrixToCSV(base_file_path + \"_refpoints.csv\", points);\n  writeMatrixToCSV(base_file_path + \"_points.csv\", geom.Global(points));\n  writeMatrixToCSV(base_file_path + \"_jacdets.csv\", determinants);\n}\n\n/**\n * @brief Computes volume of geometry object by means of overkill quadrature\n * @param geom geometry object\n * @return geometry volume\n */\ndouble computeGeometryVolume(const lf::geometry::Geometry& geom) {\n  const auto qr = lf::quad::make_QuadRule(geom.RefEl(), 23);\n\n  const auto& points = qr.Points();\n  const auto& weights = qr.Weights();\n  const auto& integrationElements = geom.IntegrationElement(points);\n\n  double vol = 0.;\n\n  for (size_t j = 0; j < points.cols(); ++j) {\n    vol += weights(j) * integrationElements(j);\n  }\n\n  return vol;\n}\n\nint main() {\n  // create a directory to store results\n  const std::string results_dir = \"results/\";\n  std::filesystem::create_directory(results_dir);\n\n  // define second-order geometry elements\n  lf::geometry::TriaO2 tria(\n      (Eigen::MatrixXd(2, 6) << 1, 6, 3, 3.7, 4.2, 2.3, 1, 3, 8, 1.2, 5.2, 4.5)\n          .finished());\n  lf::geometry::TriaO2 tria_degenerate(\n      (Eigen::MatrixXd(2, 6) << 1, 6, 3, 5, 4.5, 1.75, 1, 3, 8, 4, 9, 6.5)\n          .finished());\n  lf::geometry::QuadO2 quad((Eigen::MatrixXd(2, 8) << 3, 7, 4, 1, 5, 5.4, 2.5,\n                             1.8, 1, 3, 7, 8, 2.5, 5.9, 6.9, 4.1)\n                                .finished());\n  lf::geometry::QuadO2 quad_degenerate(\n      (Eigen::MatrixXd(2, 8) << 3, 7, 4, 1, 6, 5, 2, 2, 1, 3, 7, 8, 0, 6, 5, 2)\n          .finished());\n\n  // store vertex/midpoint coordinates, random point evaluations and\n  // corresponding jacobian determinants for every geometry object\n  for (const auto& geom_element :\n       {std::pair<std::string, lf::geometry::Geometry*>{\"tria\", &tria},\n        std::pair<std::string, lf::geometry::Geometry*>{\"tria_degenerate\",\n                                                        &tria_degenerate},\n        std::pair<std::string, lf::geometry::Geometry*>{\"quad\", &quad},\n        std::pair<std::string, lf::geometry::Geometry*>{\"quad_degenerate\",\n                                                        &quad_degenerate}}) {\n    storeSecondOrderCoords(results_dir + geom_element.first + \"_coords.csv\",\n                           *geom_element.second);\n    storeParametrizationEvals(results_dir + geom_element.first,\n                              *geom_element.second, 50);\n\n    const double volume = computeGeometryVolume(*geom_element.second);\n    double refined_volume = 0;\n\n    // compute child geometries by means of regular refinement\n    auto children = geom_element.second->ChildGeometry(\n        lf::refinement::Hybrid2DRefinementPattern(geom_element.second->RefEl(),\n                                                  lf::refinement::rp_regular),\n        0);\n\n    // store vertex/midpoint coordinates, random point evaluations and\n    // corresponding jacobian determinants for every child geometry object\n    for (std::size_t child_idx = 0; child_idx < children.size(); ++child_idx) {\n      storeSecondOrderCoords(results_dir + geom_element.first + \"_child_\" +\n                                 std::to_string(child_idx) + \"_coords.csv\",\n                             *children[child_idx]);\n      storeParametrizationEvals(results_dir + geom_element.first + \"_child_\" +\n                                    std::to_string(child_idx),\n                                *children[child_idx], 20);\n\n      refined_volume += computeGeometryVolume(*children[child_idx]);\n    }\n\n    // save volumes\n    writeMatrixToCSV(results_dir + geom_element.first + \"_volumes.csv\",\n                     (Eigen::VectorXd(2) << volume, refined_volume).finished());\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "78df5d425ae9e4d3fea31094b043cb646f4d28c7", "size": 6538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/geometry/parametrization_breakdown/parametrization_breakdown.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "examples/geometry/parametrization_breakdown/parametrization_breakdown.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "examples/geometry/parametrization_breakdown/parametrization_breakdown.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 38.9166666667, "max_line_length": 80, "alphanum_fraction": 0.6217497706, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5957317766171845}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <sophus/so3.h>\n#include <sophus/se3.h>\n\n#include <stdio.h>\n#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <opencv2/core/eigen.hpp>\n\nusing namespace std;\n\ncv::Mat convertRt2T(const cv::Mat &R, const cv::Mat &t)\n{\n    cv::Mat T = (cv::Mat_<double>(4, 4) << R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2), t.at<double>(0, 0),\n            R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2), t.at<double>(1, 0),\n            R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2), t.at<double>(2, 0),\n            0, 0, 0, 1);\n    return T;\n}\n\nSophus::SE3 transT_cv2sophus(const cv::Mat &T_cv)\n{\n    Eigen::Matrix3d R_eigen;\n    cv::cv2eigen(T_cv(cv::Rect2d(0, 0, 3, 3)), R_eigen);\n    Eigen::Vector3d t_eigen(T_cv.at<double>(0, 3), T_cv.at<double>(1, 3), T_cv.at<double>(2, 3));\n    Sophus::SE3 SE3_Rt(R_eigen, t_eigen);\n    return SE3_Rt;\n}\n\ncv::Mat transT_sophus2cv(const Sophus::SE3 &T_sophus)\n{\n    Eigen::Vector3d eigen_t(T_sophus.translation());\n    Eigen::Matrix3d eigen_R(T_sophus.rotation_matrix());\n\n    cv::Mat cv_t, cv_R;\n    eigen2cv(eigen_t, cv_t);\n    eigen2cv(eigen_R, cv_R);\n\n    return convertRt2T(cv_R, cv_t);\n}\n\nint main(int argc, char **argv)\n{\n    // -------------------- Init value from OpenCV --------------------\n    cv::Mat R = cv::Mat::eye(3, 3, CV_64F);\n    cv::Mat rvec = (cv::Mat_<double>(3, 1) << 0.3, 0.1, -0.5);\n    cv::Rodrigues(rvec, R);\n    cv::Mat tvec = (cv::Mat_<double>(3, 1) << 1, 2, 3);\n\n    cout << \"----- Initial value in OpenCV form -----\" << endl;\n    cout << \"R=\\n\"\n         << R << endl;\n    cout << \"R_vec = \" << rvec.t() << endl;\n    cout << \"t=\" << tvec.t() << endl;\n\n    // -------------------- Convert to Sophus --------------------\n    Sophus::SE3 T = Sophus::SE3(\n            Sophus::SO3(rvec.at<double>(0, 0), rvec.at<double>(1, 0), rvec.at<double>(2, 0)),\n            Eigen::Vector3d(tvec.at<double>(0, 0), tvec.at<double>(1, 0), tvec.at<double>(2, 0)));\n    cout << \"Change form to Sophus:\" << endl;\n    cout << \"Sophus::SE3 T = \\n\"\n         << T << endl;\n\n    // -------------------- Then convert to Eigen --------------------\n    cout << \"\\n\\nChange back to Eigen:\" << endl;\n    Eigen::Vector3d eigen_t(T.translation());\n    Eigen::Matrix3d eigen_R(T.rotation_matrix());\n    cout << eigen_t << endl;\n    cout << eigen_R << endl;\n\n    // -------------------- Then convert to OpenCV --------------------\n    cout << \"\\n\\nChange back to OpenCV:\" << endl;\n    cv::Mat cv_t, cv_R;\n    eigen2cv(eigen_t, cv_t);\n    eigen2cv(eigen_R, cv_R);\n    cout << cv_t << endl;\n    cout << cv_R << endl;\n\n    // -------------------- Direct trans from T_cv to T_Sophus --------------------\n    cv::Mat T_cv = convertRt2T(R, tvec);\n    Sophus::SE3 T_SE3 = transT_cv2sophus(T_cv);\n    cout << \"\\nDirect trans from T_cv to T_Sophus: \\n\"\n         << T_SE3 << endl;\n    // -------------------- Direct trans from T_sophus to T_cv --------------------\n    T_cv = transT_sophus2cv(T_SE3);\n    cout << \"\\nDirect trans from T_sophus to T_cv:\\n\"\n         << T_cv << endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "14ff11db397dbb138facd22592b2b7d3fede9970", "size": 3272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/slam_test/test_sophus.cpp", "max_stars_repo_name": "KMS-TEAM/vi_slam", "max_stars_repo_head_hexsha": "4cb5ae94bfecef5758f809d84e135e574b4fb860", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-22T08:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:35:56.000Z", "max_issues_repo_path": "test/slam_test/test_sophus.cpp", "max_issues_repo_name": "KMS-TEAM/vi_slam", "max_issues_repo_head_hexsha": "4cb5ae94bfecef5758f809d84e135e574b4fb860", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/slam_test/test_sophus.cpp", "max_forks_repo_name": "KMS-TEAM/vi_slam", "max_forks_repo_head_hexsha": "4cb5ae94bfecef5758f809d84e135e574b4fb860", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T09:07:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T09:07:21.000Z", "avg_line_length": 32.72, "max_line_length": 122, "alphanum_fraction": 0.5455378973, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.5957167768242964}}
{"text": "/**\n * \\file dcs/math/stats/distribution/detail/rgamma.cpp\n *\n * \\brief Random variates from the Gamma distribution.\n *\n *  REFERENCES\n *\n *    [1] Shape parameter a >= 1.  Algorithm GD in:\n *\n *\t  Ahrens, J.H. and Dieter, U. (1982).\n *\t  Generating gamma variates by a modified\n *\t  rejection technique.\n *\t  Comm. ACM, 25, 47-54.\n *\n *\n *    [2] Shape parameter 0 < a < 1. Algorithm GS in:\n *\n *\t  Ahrens, J.H. and Dieter, U. (1974).\n *\t  Computer methods for sampling from gamma, beta,\n *\t  poisson and binomial distributions.\n *\t  Computing, 12, 223-246.\n *\n *    Input: a = parameter (mean) of the standard gamma distribution.\n *    Output: a variate from the gamma(a)-distribution\n *\n * \\author Ross Ihaka (The R Development Core Team)\n *\n * <hr/>\n *\n *  Mathlib : A C Library of Special Functions\n *  Copyright (C) 1998 Ross Ihaka\n *  Copyright (C) 2000--2008 The R Development Core Team\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, a copy is available at\n *  http://www.r-project.org/Licenses/\n */\n\n//#include \"nmath.h\"\n#include <dcs/math/stats/distribution//exponential.hpp>\n#include <dcs/math/stats/distribution//normal.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n\n\nnamespace dcs { namespace math { namespace stats { namespace detail {\n\n/**\n * \\brief Random variates from the Gamma distribution.\n *\n *  \\param a Parameter (mean) of the standard Gamma distribution.\n *  \\return A variate from the Gamma(a)-distribution.\n *\n * REFERENCES\n * \\see\n *\n *  - [1] Shape parameter a >= 1.  Algorithm GD in:\n *\n *\t  Ahrens, J.H. and Dieter, U. (1982).\n *\t  Generating gamma variates by a modified\n *\t  rejection technique.\n *\t  Comm. ACM, 25, 47-54.\n *\n *\n *  - [2] Shape parameter 0 < a < 1. Algorithm GS in:\n *\n *\t  Ahrens, J.H. and Dieter, U. (1974).\n *\t  Computer methods for sampling from gamma, beta,\n *\t  poisson and binomial distributions.\n *\t  Computing, 12, 223-246.\n *  .\n *\n * \\author Ross Ihaka (The R Development Core Team)\n */\ntemplate <typename RealT, typename UniformRandomGenerator>\nRealT rgamma(RealT a, RealT scale, UniformRandomGenerator& eng)\n{\n\ttypedef RealT real_type;\n\n/* Constants : */\n    const static real_type sqrt32 = 5.656854;\n    const static real_type exp_m1 = 0.36787944117144232159;/* exp(-1) = 1/e */\n\n    /* Coefficients q[k] - for q0 = sum(q[k]*a^(-k))\n     * Coefficients a[k] - for q = q0+(t*t/2)*sum(a[k]*v^k)\n     * Coefficients e[k] - for exp(q)-1 = sum(e[k]*q^k)\n     */\n    const static real_type q1 = 0.04166669;\n    const static real_type q2 = 0.02083148;\n    const static real_type q3 = 0.00801191;\n    const static real_type q4 = 0.00144121;\n    const static real_type q5 = -7.388e-5;\n    const static real_type q6 = 2.4511e-4;\n    const static real_type q7 = 2.424e-4;\n\n    const static real_type a1 = 0.3333333;\n    const static real_type a2 = -0.250003;\n    const static real_type a3 = 0.2000062;\n    const static real_type a4 = -0.1662921;\n    const static real_type a5 = 0.1423657;\n    const static real_type a6 = -0.1367177;\n    const static real_type a7 = 0.1233795;\n\n    /* State variables [FIXME for threading!] :*/\n    static real_type aa = 0.;\n    static real_type aaa = 0.;\n    static real_type s, s2, d;    /* no. 1 (step 1) */\n    static real_type q0, b, si, c;/* no. 2 (step 4) */\n\n    real_type e, p, q, r, t, u, v, w, x, ret_val;\n\n    if (\n\t\ta < real_type(0) || scale <= real_type(0)\n\t) {\n\t\tif(scale == real_type(0))\n\t\t{\n\t\t\treturn real_type(0);\n\t\t}\n\t\treturn 0;//::std::numeric_limits<real_type>::quiet_NaN();\n    }\n\n    if (a < real_type(1))\n\t{\n\t\t/* GS algorithm for parameters a < 1 */\n\t\tif(a == real_type(0))\n\t\t{\n\t\t\treturn real_type(0);\n\t\t}\n\t\te = real_type(1) + exp_m1 * a;\n\t\tfor (;;)\n\t\t{\n\t\t\tp = e * eng();\n\t\t\tif (p >= real_type(1))\n\t\t\t{\n\t\t\t\tx = -::std::log((e - p) / a);\n\t\t\t\treal_type exp_rand = ::boost::exponential_distribution<real_type>()(eng);\n\t\t\t\tif (exp_rand >= (real_type(1) - a) * ::std::log(x))\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tx = ::std::exp(::std::log(p) / a);\n\t\t\t\treal_type exp_rand = ::boost::exponential_distribution<real_type>()(eng);\n\t\t\t\tif (exp_rand >= x)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn scale * x;\n    }\n\n    /* --- a >= 1 : GD algorithm --- */\n\n    /* Step 1: Recalculations of s2, s, d if a has changed */\n    if (a != aa)\n\t{\n\t\taa = a;\n\t\ts2 = a - real_type(0.5);\n\t\ts = ::std::sqrt(s2);\n\t\td = sqrt32 - s * real_type(12);\n    }\n    /* Step 2: t = standard normal deviate,\n               x = (s,1/2) -normal deviate. */\n\n    /* immediate acceptance (i) */\n\treal_type norm_rand = ::boost::normal_distribution<real_type>()(eng);\n    t = norm_rand;\n    x = s + 0.5 * t;\n    ret_val = x * x;\n    if (t >= 0.0)\n\treturn scale * ret_val;\n\n    /* Step 3: u = 0,1 - uniform sample. squeeze acceptance (s) */\n    u = eng();\n    if (d * u <= t * t * t)\n\treturn scale * ret_val;\n\n    /* Step 4: recalculations of q0, b, si, c if necessary */\n\n    if (a != aaa) {\n\taaa = a;\n\tr = 1.0 / a;\n\tq0 = ((((((q7 * r + q6) * r + q5) * r + q4) * r + q3) * r\n\t       + q2) * r + q1) * r;\n\n\t/* Approximation depending on size of parameter a */\n\t/* The constants in the expressions for b, si and c */\n\t/* were established by numerical experiments */\n\n\tif (a <= 3.686) {\n\t    b = 0.463 + s + 0.178 * s2;\n\t    si = 1.235;\n\t    c = 0.195 / s - 0.079 + 0.16 * s;\n\t} else if (a <= 13.022) {\n\t    b = 1.654 + 0.0076 * s2;\n\t    si = 1.68 / s + 0.275;\n\t    c = 0.062 / s + 0.024;\n\t} else {\n\t    b = 1.77;\n\t    si = 0.75;\n\t    c = 0.1515 / s;\n\t}\n    }\n    /* Step 5: no quotient test if x not positive */\n\n    if (x > 0.0) {\n\t/* Step 6: calculation of v and quotient q */\n\tv = t / (s + s);\n\tif (::std::fabs(v) <= 0.25)\n\t    q = q0 + 0.5 * t * t * ((((((a7 * v + a6) * v + a5) * v + a4) * v\n\t\t\t\t      + a3) * v + a2) * v + a1) * v;\n\telse\n\t    q = q0 - s * t + 0.25 * t * t + (s2 + s2) * ::std::log(1.0 + v);\n\n\n\t/* Step 7: quotient acceptance (q) */\n\tif (log(1.0 - u) <= q)\n\t    return scale * ret_val;\n    }\n\n    for (;;)\n\t{\n\t\t/* Step 8: e = standard exponential deviate\n\t\t *\tu =  0,1 -uniform deviate\n\t\t *\tt = (b,si)-double exponential (laplace) sample */\n\t\te = ::boost::exponential_distribution<real_type>()(eng);\n\t\tu = eng();\n\t\tu = u + u - 1.0;\n\t\tif (u < 0.0)\n\t\t\tt = b - si * e;\n\t\telse\n\t\t\tt = b + si * e;\n\t\t/* Step\t 9:  rejection if t < tau(1) = -0.71874483771719 */\n\t\tif (t >= -0.71874483771719) {\n\t\t\t/* Step 10:\t calculation of v and quotient q */\n\t\t\tv = t / (s + s);\n\t\t\tif (::std::fabs(v) <= 0.25)\n\t\t\tq = q0 + 0.5 * t * t *\n\t\t\t\t((((((a7 * v + a6) * v + a5) * v + a4) * v + a3) * v\n\t\t\t\t  + a2) * v + a1) * v;\n\t\t\telse\n\t\t\tq = q0 - s * t + 0.25 * t * t + (s2 + s2) * ::std::log(1.0 + v);\n\t\t\t/* Step 11:\t hat acceptance (h) */\n\t\t\t/* (if q not positive go to step 8) */\n\t\t\tif (q > 0.0) {\n\t\t\tw = ::boost::math::expm1(q);\n\t\t\t/*  ^^^^^ original code had approximation with rel.err < 2e-7 */\n\t\t\t/* if t is rejected sample again at step 8 */\n\t\t\tif (c * ::std::fabs(u) <= w * ::std::exp(e - 0.5 * t * t))\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n    } /* repeat .. until  `t' is accepted */\n    x = s + 0.5 * t;\n    return scale * x * x;\n}\n\n}}}} // Namespace dcs::math::stats::detail\n", "meta": {"hexsha": "3cc4f8ca219a88299f513a1db3cab5410846f69a", "size": 7619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/detail/rgamma.cpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/detail/rgamma.cpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/detail/rgamma.cpp", "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": 28.1143911439, "max_line_length": 78, "alphanum_fraction": 0.573434834, "num_tokens": 2625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473629, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.595670782480879}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SIMD_COMMON_ULPDIST_HPP_INCLUDED\n#define NT2_TOOLBOX_IEEE_FUNCTION_SIMD_COMMON_ULPDIST_HPP_INCLUDED\n#include <nt2/sdk/constant/eps_related.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <nt2/sdk/meta/strip.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/frexp.hpp>\n#include <nt2/include/functions/ldexp.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/min.hpp>\n#include <nt2/include/functions/is_nan.hpp>\n\n///////////////////////////////////////////////////////////////////////////////\n// It is often difficult to  answer to the following question:\n//  - are these two floating computations results similar enough ?\n//\n// The ulpdist is a way to answer tuned for relative errors estimations\n// and peculiarity of limited bits accuracy of floating point representation\n// The method is the following:\n//    Properly normalize the two numbers by the same factor in a way that \n//    the largest of the two numbers exponents will be brought to zero\n//\n//    Return this nt2::absolute difference of these normalized numbers\n//    divided by the rounding error Eps\n//\n//    The roundind error is the ulp (unit in the last place) value, i.e. the\n//    floating number, the exponent of which is 0 and the mantissa is all zeros\n//    but a 1 in the last digit (it is not hard coded that way however).\n//    Yhis means 2^-23 for floats and 2^-52 for double\n//\n//    For instance if two floating numbers (of same type) have an ulpdist of \n//    zero that means that their floating representation are identical.\n//\n//    Generally equality up to 0.5ulp is the best that one can wish beyond\n//    strict equality.\n//\n//    Typically if a double is compared to the double representation of\n//    its floating conversion (they are exceptions as for fully representable\n//    reals) the ulpdist will be around 2^26.5 (~10^8)\n//\n//    The ulpdist is also roughly equivalent to the number of representable\n//    floating points values between two given floating points values.\n//\n//     ulpdist( 1.0, 1+nt2::Eps<double>())   == 0.5\n//     ulpdist( 1.0, 1+nt2::Eps<double>()/2) == 0.0\n//     ulpdist( 1.0, 1-nt2::Eps<double>()/2) == 0.25\n//     ulpdist( 1.0, 1-nt2::Eps<double>())   == 0.5 \n//     ulpdist(double(nt2::Pi<float>()), nt2::Pi<double>()) == 9.84293e+07\n///////////////////////////////////////////////////////////////////////////////\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ulpdist_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<arithmetic_<A0>,X>))\n                          ((simd_<arithmetic_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::ulpdist_(tag::simd_<tag::arithmetic_, X> ,\n                            tag::simd_<tag::arithmetic_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return (max(a0, a1)-min(a0,a1));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ulpdist_, tag::cpu_,\n                          (A0)(X),\n                          ((simd_<real_<A0>,X>))\n                          ((simd_<real_<A0>,X>))\n                         );\n\nnamespace nt2 { namespace ext\n{\n  template<class X, class Dummy>\n  struct call<tag::ulpdist_(tag::simd_<tag::real_, X> ,\n                            tag::simd_<tag::real_, X> ),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0>\n    struct result<This(A0,A0)> : meta::strip<A0>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename meta::as_integer<A0>::type itype;\n      itype e1, e2;\n      A0 m1, m2;\n      boost::fusion::tie(m1, e1) = nt2::frexp(a0);\n      boost::fusion::tie(m2, e2) = nt2::frexp(a1);\n      itype expo = -nt2::max(e1, e2);\n      A0 e = sel(is_equal(e1, e2), nt2::abs(m1-m2), nt2::abs(nt2::ldexp(a0, expo)-nt2::ldexp(a1, expo)));\n      return sel((is_nan(a0)&is_nan(a1))|is_equal(a0, a1),  Zero<A0>(), e/Eps<A0>());\n    }\n  };\n} }\n\n#endif\n// modified by jt the 04/01/2011\n", "meta": {"hexsha": "7f7b7b268fefa9da3f9f7ee2dcc21a1fd3232055", "size": 5149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/ulpdist.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/ulpdist.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/simd/common/ulpdist.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": 41.192, "max_line_length": 105, "alphanum_fraction": 0.5581666343, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.5956399467337685}}
{"text": "#include \"spectral_shape.hpp\"\n\n#include <algorithm>\n#include <numeric>\n\n#include <deal.II/lac/petsc_full_matrix.h>\n\nnamespace bart::acceleration::two_grid::spectral_shape {\n\nnamespace  {\nusing DealiiMatrix = dealii::FullMatrix<double>;\nauto matrix_size_error_text(const DealiiMatrix& sigma_t, const DealiiMatrix& sigma_s) {\n  return std::string{\"Error in SpectralShape::CalculateSpectralShape, matrix size mismatch: Sigma_T matrix has \"\n                     \"dimensions (\" + std::to_string(sigma_t.m()) + \", \" + std::to_string(sigma_t.n()) +\n      \"), and Sigma_S matrix has dimensions (\" + std::to_string(sigma_s.m()) + \", \"\n                         + std::to_string(sigma_s.n())};\n}\n} // namespace\n\nSpectralShape::SpectralShape(std::unique_ptr<EigenvalueSolver> eigenvalue_solver_ptr)\n    : eigenvalue_solver_ptr_(std::move(eigenvalue_solver_ptr)) {\n  AssertPointerNotNull(eigenvalue_solver_ptr_.get(), \"eigenvalue solver\", \"SpectralShape constructor\");\n}\n\nauto SpectralShape::CalculateSpectralShape(const DealiiMatrix& sigma_t,\n                                           const DealiiMatrix& sigma_s) -> std::vector<double> {\n  AssertThrow(sigma_t.m() == sigma_s.m() && sigma_t.n() == sigma_s.n() && sigma_t.m() == sigma_t.n() &&\n      sigma_s.m() == sigma_s.n(), dealii::ExcMessage(matrix_size_error_text(sigma_t, sigma_s)))\n  const int n_groups = sigma_t.m();\n  DealiiMatrix downscattering(n_groups, n_groups), upscattering(n_groups, n_groups);\n\n  for (int i = 0; i < n_groups; ++i) {\n    for (int j = 0; j < i + 1; ++j)\n      downscattering(i, j) = sigma_s(i, j);\n    for (int j = i + 1; j < n_groups; ++j)\n      upscattering(i, j) = sigma_s(i, j);\n  }\n  DealiiMatrix a(n_groups, n_groups);\n  DealiiMatrix lhs(sigma_t);\n  lhs.add(-1, downscattering);\n  lhs.gauss_jordan();\n  lhs.mmult(a, upscattering);\n\n  dealii::PETScWrappers::FullMatrix petsc_matrix(n_groups, n_groups);\n  for (int i = 0; i < n_groups; ++i) {\n    for (int j = 0; j < n_groups; ++j) {\n      petsc_matrix.set(i, j, a(i, j));\n    }\n  }\n  petsc_matrix.compress(dealii::VectorOperation::insert);\n  auto [eigenvalue, eigenvector] = this->eigenvalue_solver_ptr_->SpectralRadius(petsc_matrix);\n\n  // Normalize in the L1 norm\n  const double sum = std::accumulate(eigenvector.begin(), eigenvector.end(), 0.0,\n                                     [](double running_sum, double val){ return running_sum + std::abs(val); });\n  std::transform(eigenvector.begin(), eigenvector.end(), eigenvector.begin(),\n                 [sum](const double val) { return std::abs(val) / sum; });\n\n  return eigenvector;\n}\n\n} // namespace bart::acceleration::two_grid::spectral_shape\n", "meta": {"hexsha": "b20b46414703725b15a14d1b2db694dce6a19e98", "size": 2626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape.cpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape.cpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/acceleration/two_grid/spectral_shape/spectral_shape.cpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 41.6825396825, "max_line_length": 112, "alphanum_fraction": 0.662604722, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5956367409566443}}
{"text": "//============================================================================\n// Name         : dnatemplategeodesyfuncs.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  : Basic Geodetic Functions\n//============================================================================\n\n#ifndef DNATEMPLATEGEODESYFUNCS_H_\n#define DNATEMPLATEGEODESYFUNCS_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/parameters/dnaprojection.hpp>\n#include <include/config/dnatypes.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nusing namespace dynadjust::datum_parameters;\n\n// nu helper\ntemplate <class T>\nT primeVertical(const CDnaEllipsoid* ellipsoid, const T& latitude) \n{\n\treturn primeVertical_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude);\n}\n\n// rho helper\ntemplate <class T>\ndouble primeMeridian(const CDnaEllipsoid* ellipsoid, const T& latitude)\n{\n\treturn primeMeridian_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude);\n}\n\n// nu and rho helper\ntemplate <class T>\nvoid primeVerticalandMeridian(const CDnaEllipsoid* ellipsoid, const T& latitude, T& nu, T& rho) \n{\n\tprimeVerticalandMeridian_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude, nu, rho);\n}\n\n// average radius of curvature helper\ntemplate <class T>\nT averageRadiusofCurvature(const CDnaEllipsoid* ellipsoid, const T& latitude)\n{\n\treturn averageRadiusofCurvature_(ellipsoid->GetSemiMajor(), ellipsoid->GetE1sqd(), latitude);\n}\n\n\ntemplate <class T>\nvoid GeoToCart(const T& Latitude, const T& Longitude, const T& Height, T* X, T* Y, T* Z, \n\t\t\t   const CDnaEllipsoid* ellipsoid)\n{\n\t// copy variables in case the caller overwrites original values\n\tT latitude(Latitude), longitude(Longitude), height(Height);\n\t\n\t// calculate prime vertical (once) \n\tT Nu(primeVertical(ellipsoid, latitude));\n\t\t\t\n\t*X = (Nu + height) * cos(latitude) * cos(longitude);\n\t*Y = (Nu + height) * cos(latitude) * sin(longitude);\n\t*Z = ((Nu * (1. - ellipsoid->GetE1sqd())) + height) * sin(latitude);\n}\n\n\ntemplate <class T>\nvoid CartToGeo_SimpleIteration(const T& X, const T& Y, const T& Z,\n\t\t\t   T* latitude, T* longitude, T* height,\n\t\t\t   const CDnaEllipsoid* ellipsoid) // ellipsoid parameters\n{\n\t// copy variables in case the caller overwrites original values\n\tT x(X), y(Y), z(Z);\n\n\tT f(ellipsoid->GetFlattening());\n\tT e2(ellipsoid->GetE1sqd());\n\tT p(pow(((x * x) + (y * y)), 0.5));\n\n\t// \"Cartesian to geographic\" conversion problem resides in the \n\t// equation to compute latitude (phi)...latitude is required on both\n\t// sides of the equation. A simple iterative method is used to determine \n\t// the latitude, whereby the starting latitude is computed from \n\t// tan(phi) = z / p\n\n\t// Compute starting lat value from second eccentricity squared\n\tT lat1(atan(z / p));\n\t*latitude = atan2((z + (e2 * ellipsoid->GetSemiMajor() * sin(lat1))), p);\n\tT Nu(primeVertical(ellipsoid, *latitude));\n\n\tfor (UINT16 i(0); i<16; i++)\n\t{\n\t\tlat1 = atan2((z + (e2 * Nu * sin(*latitude))), p);\n\t\t//Nu = ellipsoid->PrimeVertical(*latitude);\n\t\tNu = primeVertical(ellipsoid, *latitude);\n\t\t*latitude = atan2((z + (e2 * Nu * sin(lat1))), p);\n\n\t\tif (fabs(lat1 - *latitude) < PRECISION_1E16)\n\t\t\tbreak;\n\t}\n\t\n\t// Compute longitude\n\t*longitude = atan(y / x);\n\n\t// determine correct quadrant and apply negative long accordingly\n\tif (x < 0.0 && y > 0.0)\n\t\t*longitude += PI;\n\telse if (x < 0.0 && y < 0.0)\n\t\t*longitude = -(PI - *longitude);\n\t\n\t// Compute height\n\t*height = (p / cos(*latitude)) - Nu;\n}\n\n\n\ntemplate <class T>\n// K Lin and J Wang's method based on Newton's iteration\n// \tdouble dXAxis(-3563081.362), dYAxis(-2057145.984), dZAxis(-4870449.482), dHeight(0.);\n//\tCDnaEllipsoid e;\n//\tCartToGeo<double>(dXAxis, dYAxis, dZAxis, &dXAxis, &dYAxis, &dHeight, &e);\n//\tstringstream ss;\n//\tss << setw(MSR) << right << FormatDmsString(RadtoDms(dXAxis), 5, true, false) << \", \";\n//\tss << setw(MSR) << right << FormatDmsString(RadtoDms(dYAxis), 5, true, false) << \", \";\n//\tss << setw(MSR) << setprecision(4) << fixed << right << dHeight;\n//\tstring comp(ss.str());\n//\tcomp should equal  \"-50 00 00.0000, -150 00 00.0000, 10000.000\"\n//\nvoid CartToGeo(const T& X, const T& Y, const T& Z,\n\t\t\t   T* latitude, T* longitude, T* height,\n\t\t\t   const CDnaEllipsoid* ellipsoid) // ellipsoid parameters\n{\n\t// copy variables in case the caller overwrites original values\n\tT x(X), y(Y), z(Z);\n\n\tT p2((x * x) + (y * y));\n\tT p(sqrt(p2));\n\tT a2(ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMajor());\n\tT b2(ellipsoid->GetSemiMinor() * ellipsoid->GetSemiMinor());\n\tT Z2(z * z);\n\tT a2Z2(a2 * Z2);\n\tT b2p2(b2 * p2);\n\tT A(a2Z2 + b2p2);\n\n\t// Compute initial approximation of m (Lin and Wang 1995, eq. 9, p. 301)\n\tT m0((ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMinor() * sqrt(A) * A - a2 * b2 * A) / (2. *\n\t\t((a2 * a2Z2) + (b2 * b2p2))));\n\n\tT twom, a2twom, b2twom, f, df, m;\n\t\n\t// Generally converges after one iteration and \n\t// so shouldn't need more than five iterations.  \n\tfor (UINT16 i(0); i<5; ++i)\n\t{\n\t\tm = m0;\n\t\ttwom = m * 2.;\n\t\ta2twom = a2 + twom;\n\t\tb2twom = b2 + twom;\n\t\t\n\t\tf = (a2 * p2 / (a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom)) - 1.;\n\t\t\n\t\t// if f is sufficiently close to zero, break.\n\t\tif (fabs(f) < PRECISION_1E12)\n\t\t\tbreak;\n\t\t\n\t\tdf = -4. * ((a2 * p2 / (a2twom * a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom * b2twom)));\n\t\t\n\t\t// recompute new value for m\n\t\tm0 = m - (f / df);\n\t\tm = m0;\t\n\t}\n\n\ttwom = m * 2.;\n\n\tT p_E(a2 * p / (a2 + twom));\n\tT Z_E(b2 * z / (b2 + twom));\n\n\t// Compute latitude\n\t*latitude = atan(a2 * Z_E / (b2 * p_E));\n\n\t// Compute longitude\n\t*longitude = atan(y / x);\n\n\t// determine correct quadrant and apply negative long accordingly\n\tif (x < 0.0 && y > 0.0)\n\t\t*longitude += PI;\n\telse if (x < 0.0 && y < 0.0)\n\t\t*longitude = -(PI - *longitude);\n\n\t// The following line causes an issue for west longitudes, which by nature are negative!\n\t// Not sure why this was introduced.  Removing the conditional absolute has no adverse impact on\n\t// positions which are located in the eastern hemisphere,\n\t//if (*longitude < 0.)\n\t//\t*longitude += TWO_PI;\n\t\n\t// Compute height\n\t*height = sqrt(((p - p_E) * (p - p_E)) + ((z - Z_E) * (z - Z_E)));\n\tif ((p + fabs(z)) < (p_E + fabs(Z_E)))\n\t\t*height *= -1.;\n}\n\n\ntemplate <class T>\n// K Lin and J Wang's method based on Newton's iteration\nT CartToLat(const T& X, const T& Y, const T& Z, const CDnaEllipsoid* ellipsoid)\n{\n\t// copy variables in case the caller overwrites original values\n\tT x(X), y(Y), z(Z);\n\n\tT p2((x * x) + (y * y));\n\tT p(sqrt(p2));\n\tT a2(ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMajor());\n\tT b2(ellipsoid->GetSemiMinor() * ellipsoid->GetSemiMinor());\n\tT Z2(z * z);\n\tT a2Z2(a2 * Z2);\n\tT b2p2(b2 * p2);\n\tT A(a2Z2 + b2p2);\n\n\t// Compute initial approximation of m (Lin and Wang 1995, eq. 9, p. 301)\n\tT m0((ellipsoid->GetSemiMajor() * ellipsoid->GetSemiMinor() * sqrt(A) * A - a2 * b2 * A) / (2. *\n\t\t((a2 * a2Z2) + (b2 * b2p2))));\n\n\tT twom, a2twom, b2twom, f, df, m;\n\t\n\t// Generally converges after one iteration and \n\t// so shouldn't need more than five iterations.  \n\tfor (UINT16 i(0); i<5; ++i)\n\t{\n\t\tm = m0;\n\t\ttwom = m * 2.;\n\t\ta2twom = a2 + twom;\n\t\tb2twom = b2 + twom;\n\t\t\n\t\tf = (a2 * p2 / (a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom)) - 1.;\n\t\t\n\t\t// if f is sufficiently close to zero, break.\n\t\tif (fabs(f) < PRECISION_1E12)\n\t\t\tbreak;\n\t\t\n\t\tdf = -4. * ((a2 * p2 / (a2twom * a2twom * a2twom)) + (b2 * Z2 / (b2twom * b2twom * b2twom)));\n\t\t\n\t\t// recompute new value for m\n\t\tm0 = m - (f / df);\n\t\tm = m0;\t\n\t}\n\n\ttwom = m * 2.;\n\n\tT p_E(a2 * p / (a2 + twom));\n\tT Z_E(b2 * z / (b2 + twom));\n\n\t// Compute latitude\n\treturn atan(a2 * Z_E / (b2 * p_E));\n}\n\ntemplate <class T>\nT PartialD_Latitude(const T& X, const T& Y, const T& Z,\n\t\t\t   const _CART_ELEM_& element,  const T& latitude, const CDnaEllipsoid* ellipsoid)\n{\n\tif (element > z_element)\n\t\treturn 0.;\n\n\tconst T small_inc = PRECISION_1E4;\n\n\t// Compute the partial derivative.\n\t// 1. add small increment to the required element\n\tT cart[3] = { X, Y, Z };\n\tcart[element] += small_inc;\n\n\t// 2. f(x + small_inc)\n\tT fx_small_inc(CartToLat(\n\t\tcart[x_element],\t\t\t\t// X1\n\t\tcart[y_element],\t\t\t\t// Y1\n\t\tcart[z_element],\t\t\t\t// Z1\n\t\tellipsoid));\n\n\t//\t\t\t  f(x + small_inc) - f(x) \n\t// 3. f'(x) = -----------------------\n\t//\t\t\t\t\t small_inc\n\treturn (fx_small_inc - latitude) / small_inc;\n}\n\n\ntemplate <class T>\nT PartialD_Latitude_F(const T& X, const T& Y, const T& Z,\n\t\t\t   const _CART_ELEM_& element,  T* latitude, const CDnaEllipsoid* ellipsoid)\n{\n\tif (element > z_element)\n\t\treturn 0.;\n\n\t// compute the new latitude\n\t*latitude = CartToLat(X, Y, Z, ellipsoid);\n\n\treturn PartialD_Latitude(X, Y, Z, element, *latitude, ellipsoid);\n}\n\ntemplate <class T>\nT PartialD_HorizAngle(const T X1, const T Y1, const T Z1,\n\t\t\t\t const T X2, const T Y2, const T Z2, \n\t\t\t\t const T X3, const T Y3, const T Z3, \n\t\t\t\t const T currentLatitude, const T currentLongitude,\n\t\t\t\t const _STATION_ELEM_& station, const _CART_ELEM_& element, const T angle)\n{\n\tif (element > z_element)\n\t\treturn 0.;\n\n\tconst T small_inc = PRECISION_1E4;\n\n\t// Compute the partial derivative.\n\t// 1. add small increment to the required element\n\tT cart[3][3] = { X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3 };\n\tcart[station][element] += small_inc;\n\n\t// Temporary variables\n\tT dir12, dir13, loc12e, loc12n, loc13e, loc13n;\n\n\t// 2. f(x + small_inc)\n\tT fx_small_inc(HorizontalAngle(\n\t\tcart[station_1][x_element],\t\t\t\t// X1\n\t\tcart[station_1][y_element],\t\t\t\t// Y1\n\t\tcart[station_1][z_element],\t\t\t\t// Z1\n\t\tcart[station_2][x_element],\t\t\t\t// X2\n\t\tcart[station_2][y_element],\t\t\t\t// Y2\n\t\tcart[station_2][z_element],\t\t\t\t// Z2\n\t\tcart[station_3][x_element],\t\t\t\t// X3\n\t\tcart[station_3][y_element],\t\t\t\t// Y3ZONE\n\t\tcart[station_3][z_element],\t\t\t\t// Z3\n\t\tcurrentLatitude, currentLongitude,\n\t\t&dir12, &dir13, &loc12e, &loc12n, &loc13e, &loc13n));\n\n\t//\t\t\t  f(x + small_inc) - f(x) \n\t// 3. f'(x) = -----------------------\n\t//\t\t\t\t\t small_inc\n\treturn (fx_small_inc - angle) / small_inc;\n}\n\n\ntemplate <class T>\n// latitude and longitude in radians\nvoid GeoToGrid(const T& Latitude, const T& Longitude, T* easting, T* northing, T* zone, \n\t\t\t   const CDnaEllipsoid* ellipsoid, const CDnaProjection* projection, bool COMPUTE_ZONE)\n{\n\tT latitude(Latitude);\n\tT longitude(Longitude);\n\n\t// Compute Zone if not previously specified\n\tif (COMPUTE_ZONE)\n\t\t*zone = floor((Degrees(longitude) - projection->GetLongWesternEdgeZone0()) / projection->GetZoneWidth());\n\n\t// Compute Geodetic Longitude of the Central Meridian of pGeoValue->dNum3 (the UTM Zone)\n\tT CMeridian((*zone * projection->GetZoneWidth()) + projection->GetLongCentralMeridianZone0());\n\n\t// Compute diff in Longitude between CMeridian and Longitude\n\tT omega(longitude - Radians(CMeridian));\n\n\tT e2(ellipsoid->GetE1sqd());\n\tT e2_2(pow(e2, 2.0));\n\tT e2_3(pow(e2, 3.0));\n\n\tT Nu, Rho, Nu_div_Rho;\n\tprimeVerticalandMeridian(ellipsoid, latitude, Nu, Rho);\n\tNu_div_Rho = Nu / Rho;\n\n\tT A0(1.0 - (e2 / 4.0) - (3.0 * e2_2 / 64.0) - (5.0 * e2_3 / 256.0));\n\tT A2(3.0 / 8.0 * (e2 + (e2_2 / 4.0) + (15.0 * e2_3 / 128.0)));\n\tT A4(15.0 / 256.0 * (e2_2 + (3.0 * e2_3 / 4.0)));\n\tT A6(35.0 * e2_3 / 3072.0);\n\n\tT m(ellipsoid->GetSemiMajor() * ((A0 * latitude) - \n\t\t(A2 * sin(2.0 * latitude)) +\n\t\t(A4 * sin(4.0 * latitude)) -\n\t\t(A6 * sin(6.0 * latitude))));\n\n\tT cos_lat(cos(latitude));\n\tT sin_lat(sin(latitude));\n\tT Num1(K0 * Nu * omega * cos_lat);\n\n\tT tan_lat_2(pow(tan(latitude), 2.0));\n\tT tan_lat_4(pow(tan(latitude), 4.0));\n\n\t// Compute Easting\n\tT Term1((pow(omega, 2.0) / 6.0) * (pow(cos_lat, 2.0)) * (Nu_div_Rho - tan_lat_2));\n\tT Term2((pow(omega, 4.0) / 120) * (pow(cos_lat, 4.0)) *\n\t\t(((4.0 * pow(Nu_div_Rho, 3.0)) * (1.0 - (6.0 * tan_lat_2))) +\n\t\t((pow(Nu_div_Rho, 2.0)) * (1.0 + (8.0 * tan_lat_2))) -\n\t\t(Nu_div_Rho * 2.0 * tan_lat_2) + tan_lat_4));\n\tT Term3((pow(omega, 6.0) / 5040) * (pow(cos_lat, 6.0)) *\n\t\t(61.0 - (479.0 * tan_lat_2) + (179.0 * tan_lat_4) - (tan_lat_4)));\n\n\t*easting = (Num1 * (1.0 + Term1 + Term2 + Term3)) + FALSE_E;\n\n\t// Compute Northing\n\tTerm1 = (pow(omega, 2.0) / 2.0 * Nu * sin_lat * cos_lat);\n\tTerm2 = (pow(omega, 4.0) / 24.0 * Nu * sin_lat * pow(cos_lat, 3.0));\n\tTerm2 *= ((4.0 * pow(Nu_div_Rho, 2.0)) + Nu_div_Rho - tan_lat_2);\n\tTerm3 = (pow(omega, 6.0) / 720.0 * Nu * sin_lat * pow(cos_lat, 5.0));\n\tTerm3 *= ((8.0 * pow(Nu_div_Rho, 4.0) * (11.0 - (24.0 * tan_lat_2))) - \n\t\t(28.0 * pow(Nu_div_Rho, 3.0) * (1.0 - (6.0 * tan_lat_2))) +\n\t\t(pow(Nu_div_Rho, 2.0) * (1.0 - (32.0 * tan_lat_2))) -\n\t\t(Nu_div_Rho * 2.0 * tan_lat_2) + tan_lat_4);\n\t\n\tT Term4(pow(omega, 8.0) / 40320 * Nu * sin_lat * pow(cos_lat, 7.0));\n\tTerm4 *= (1385.0 - (3111.0 * tan_lat_2) + (543.0 * tan_lat_4) - (pow(tan(latitude), 6.0)));\n\n\t*northing = (K0 * (m + Term1 + Term2 + Term3 + Term4)) + FALSE_N;\n}\n\n// returns lat/long values in radians\ntemplate <class T, typename U>\nvoid GridToGeo(const T& easting, const T& northing, const U& zone, T* latitude, T* longitude, \n\t\t\t   const T& a, const T& inv_f, // ellipsoid parameters\n\t\t\t   const T& FALSE_E, const T& FALSE_N, const T& kO, const T& lcmZ1, const T& zW)\t// projecton parameters\n{\n\tT f = 1 / inv_f;\n\tT b = a * (1 - f);\n\tT e2 = (2 * f) - (f * f);\n\t//T e = sqrt(e2);\n\t//T Seconde2 = e2 / (1 - e2);\n\t//T Seconde = sqrt(Seconde2);\n\tT n = (a - b) / (a + b);\n\tT n2 = pow(n, 2.0);\n\tT n3 = pow(n, 3.0);\n\tT n4 = pow(n, 4.0);\n\tT G = a * (1 - n) * (1 - n2);\n\tG *= (1 + (9 * n2 / 4) + (225 * n4 / 64));\n\tG *= (PI / 180.);\n\n\tT ePrime = easting - FALSE_E;\n\tT nPrime = northing - FALSE_N;\n\tT m = nPrime / kO;\n\tT sigma = (m * PI) / (180 * G);\n\t\n\tT latPrime = sigma + (( (3 * n / 2) - (27 * n3 / 32) ) * sin(2 * sigma));\n\tlatPrime += ( (21 * n2 / 16) - (55 * n4 / 32) ) * sin(4 * sigma);\n\tlatPrime += (151 * n3 / 96) * sin(6 * sigma);\n\tlatPrime += (1097 * n4 / 512) * sin(8 * sigma);\n\n\tT rho = a * (1 - e2) / pow( (1 - (e2 * pow(sin(latPrime), 2.0))), 1.5);\n\tT nu = a / pow( (1 - (e2 * pow(sin(latPrime), 2.0))), 0.5);\n\tT num1 = tan(latPrime) / (kO * rho);\n\tT x = ePrime / (kO * nu);\n\t\n\tT term1 = num1 * x * ePrime / 2;\n\tT term2 = num1 * ePrime * pow(x, 3.0) / 24;\n\tterm2 *= ( (-4 * pow((nu / rho), 2.0)) + (9 * nu / rho * (1 - pow((tan(latPrime)), 2.0))) + (12 * pow((tan(latPrime)), 2.0))  );\n\tT term3 = num1 * ePrime * pow(x, 5.0) / 720;\n\tterm3 *= ( \n\t\t(8 * pow((nu / rho), 4.0) * (11 - (24 * pow((tan(latPrime)), 2.0)))) - \n\t\t(12 * pow((nu / rho), 3.0) * (21 - (71 * pow((tan(latPrime)), 2.0)))) +\n\t\t(15 * pow((nu / rho), 2.0) * (15 - (98 * pow((tan(latPrime)), 2.0)) + (15 * pow((tan(latPrime)), 4.0)))) +\n\t\t(180 * (nu / rho) * ((5 * pow((tan(latPrime)), 2.0))-(3 * pow((tan(latPrime)), 4.0))))+\n\t\t(360 * pow((tan(latPrime)), 4.0))\n\t\t);\n\tT term4 = num1 * ePrime * pow(x, 7.0) / 40320;\n\tterm4 *= (1385 +\n\t\t(3633 * pow((tan(latPrime)), 2.0)) +\n\t\t(4095 * pow((tan(latPrime)), 4.0)) +\n\t\t(1575 * pow((tan(latPrime)), 6.0))\n\t\t);\n\n\t// Store radians value of Geodetic Latitude\n\t*latitude = latPrime - term1 + term2 - term3 + term4;\n\n\t// Compute Geodetic Longitude of the Central Meridian of pGridValue->dNum3 (the UTM Zone) in radians\n\tT centralMeridian = ((zone * zW) + lcmZ1 - zW) * PI / 180;\n\t\n\tnum1 = 1 / (cos(latPrime));\n\n\tterm1 = x * num1;\n\tterm2 = ( pow(x, 3.0) / 6 * num1 * ((nu / rho) + (2. * tan(latPrime) * tan(latPrime))) );\n\tterm3 = ( pow(x, 5.0) / 120 * num1 * (\n\t\t(-4 * pow((nu / rho), 3.0) * (1 - (6 * tan(latPrime) * tan(latPrime)))) +\n\t\t(pow((nu / rho), 2.0) * (9 - (68 * tan(latPrime) * tan(latPrime)))) +\n\t\t(72 * (nu / rho) * tan(latPrime) * tan(latPrime)) +\n\t\t(24 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime))\n\t\t));\n\tterm4 = ( pow(x, 7.0) / 5040 * num1 * (\n\t\t61 + (662 * tan(latPrime) * tan(latPrime)) +\n\t\t(1320 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime)) +\n\t\t(720 * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime) * tan(latPrime))\n\t\t));\n\n\t// Store radians value of Geodetic Longitude\n\t*longitude = centralMeridian + term1 - term2 + term3 - term4;\n\n}\n\n// Great Circle Distance\ntemplate <class T>\nT GreatCircleDistance(const T& dLatitudeAT, const T& dLongitudeAT, const T& dLatitudeTO, const T& dLongitudeTO)\n{\n\tT deltaLatitude(dLatitudeTO - dLatitudeAT);\n\tT deltaLongitude(dLongitudeTO - dLongitudeAT);\n\tT a(sin(deltaLatitude / 2) * sin(deltaLatitude / 2) + cos(dLatitudeAT) * cos(dLatitudeTO) * sin(deltaLongitude / 2) * sin(deltaLongitude / 2));\n\tT c(2 * atan2(sqrt(a), sqrt(1 - a)));\n\treturn c * T(6372797.);\n}\n\n// Rigorous Geodesic via Robbins' formula\n// Robbins, A. R. (1962). �Long lines on the spheroid.� Surv. Rev., XVI(125), 301�309.\ntemplate <class T>\nT RobbinsReverse(const T& dLatitudeAT, const T& dLongitudeAT, const T& dLatitudeTO, const T& dLongitudeTO, T* pAzimuth, const CDnaEllipsoid* ellipsoid)\n{\n\tT s, z, c, g, h, h2, chi;\n\tT sinsigma, sigma, sigma2, sigma3, sigma4, sigma5;\n\t\t\n\tT dPVertA(primeVertical(ellipsoid, dLatitudeAT));\n\tT dPVertB(primeVertical(ellipsoid, dLatitudeTO));\n\tT tanzeta2 = (1 - ellipsoid->GetE1sqd()) * tan(dLatitudeTO) + ellipsoid->GetE1sqd() * dPVertA * sin(dLatitudeAT) / (dPVertB * cos(dLatitudeTO));\n\tT tau1 = cos(dLatitudeAT) * tanzeta2 - sin(dLatitudeAT) * cos(dLongitudeTO - dLongitudeAT);\n\tT tanazimuthAB;\n\tif (fabs (dLongitudeTO - dLongitudeAT) < PRECISION_1E15)\n\t\ttanazimuthAB = 0.0;\n\telse\n\t\ttanazimuthAB = sin (dLongitudeTO - dLongitudeAT) / tau1;\n\n\t// Compute the azimuth, check for the correct sign, quadrant etc. - \n\t*pAzimuth = atan(tanazimuthAB);\n\tif ((*pAzimuth) < 0.0)\n\t\t*pAzimuth += PI;\n\tif (dLongitudeTO < dLongitudeAT)\n\t\t*pAzimuth += PI;\n\tif ((fabs (*pAzimuth) < PRECISION_1E15) && (dLatitudeTO < dLatitudeAT))\n\t\t*pAzimuth += PI;\n\n\t// Check here for the sign of the computed azimuth - eg to add pi or 2pi etc. \n\ts = sin (*pAzimuth);\n\tz = atan (tanzeta2);\n\tc = cos (z);\n\n\t// If sin (alpha12) is close to zero then chi is calculated one way \n\t// otherwise it is calculated differently.  An arbitrary \n\t// \"boundary value\" of 0.2 has been used. \n\tif (fabs (s) < 0.2)\n\t\tchi = tau1 / cos(*pAzimuth);\n\telse\n\t\tchi = sin(dLongitudeTO - dLongitudeAT) / s;\n\tsinsigma = chi * c;\n\tsigma = asin (sinsigma);\n\tsigma2 = sigma * sigma;\n\tsigma3 = sigma2 * sigma;\n\tsigma4 = sigma2 * sigma2;\n\tsigma5 = sigma3 * sigma2;\n\tg = ellipsoid->GetE2() * sin (dLatitudeAT);\n\th = ellipsoid->GetE2() * cos (dLatitudeAT) * cos (*pAzimuth);\n\th2 = h * h;\n\treturn (dPVertA * sigma * (1 - sigma2 * h2 * (1 - h2) / 6 + sigma3 * g * h * (1 - 2 * h2) / 8 + sigma4 * (h2 * (4 - 7 * h2) - 3 * g * g * (1 - 7 * h2)) / 120 - sigma5 * g * h / 48));\n}\n\n\ntemplate <class T>\nvoid VincentyDirect(const T& dLatitudeAT, const T& dLongitudeAT, const T& dAzimuth, const T& dDistance, \n\t\t\t\t\tT *dLatitudeTO, T *dLongitudeTO, const CDnaEllipsoid* ellipsoid)\n{\n\t// calculate fundamentals\n\tT f = ellipsoid->GetFlattening();\n\tT b = ellipsoid->GetSemiMinor();\n\n\t// parametric latitude of P'\n\tT tanUI = (1.0 - f) * tan(dLatitudeAT);\t\t\n\t// angular distance\n\tT tanSigma1 = tanUI / cos(dAzimuth);\t\t\n\t// parametric latitude of the geodesic vertex, or\n\t// azimuth of the geodesic at the equator\n\tT sinAlpha = cos(atan(tanUI)) * sin(dAzimuth);\n\tT Alpha = asin(sinAlpha);\n\tT cosAlpha = cos(Alpha);\n\t// geodesic constant\n\tT u2 = pow(cosAlpha, 2.0) * (pow(ellipsoid->GetSemiMajor(), 2.0) - pow(b, 2.0)) / pow(b, 2.0);\n\t\n\t// Vincenty's constants A' and B'\n\tT A = 1.0 + (u2/16384.0) * (4096.0 + (u2 * (-768.0 + (u2 * (320.0 - (175.0 * u2))))));\n\tT B = (u2/1024.0) * (256.0 + (u2 * (-128.0 + (u2 * (74.0 - (47.0 * u2))))));\n\t\n\tT Sigma = dDistance / (b * A);\n\tT twoSigmam, deltaSigma, SigmaDiff(99.);\n\t\n\t// iterate until no signigicant change in sigma\n\tfor (UINT16 i(0); i<10; i++)\n\t{\n\t\ttwoSigmam = (2.0 * atan(tanSigma1)) + Sigma;\n\t\tdeltaSigma = B * sin(Sigma) * (cos(twoSigmam) + (B / 4.0 * ((cos(Sigma) * (-1.0 + (2.0 * pow(cos(twoSigmam), 2.0)))) - (B / 6.0 * cos(twoSigmam) * (-3.0 + (4.0 * pow(sin(Sigma), 2.0))) * ((-3.0 + (4.0 * pow(cos(twoSigmam), 2.0))))))));\n\t\tSigmaDiff = Sigma;\n\t\tSigma = (dDistance / (b * A)) + deltaSigma;\n\t\tSigmaDiff -= Sigma;\n\n\t\tif (fabs(SigmaDiff) < PRECISION_1E16)\n\t\t\tbreak;\n\t}\n\t\n\t// latitude of new position\n\t*dLatitudeTO = atan2(((sin(atan(tanUI)) * cos(Sigma)) + (cos(atan(tanUI)) * sin(Sigma) * cos(dAzimuth))), ((1.0 - f) * pow((pow(sinAlpha, 2.0) + pow(((sin(atan(tanUI)) * sin(Sigma)) - (cos(atan(tanUI)) * cos(Sigma) * cos(dAzimuth))), 2.0)), 0.5)));\n\t\n\tT Lambda = atan2((sin(Sigma) * sin(dAzimuth)), ((cos(atan(tanUI)) * cos(Sigma)) - (sin(atan(tanUI))*sin(Sigma)*cos(dAzimuth))));\n\tT C = (f / 16.0) * pow(cosAlpha, 2.0) * (4.0 + (f * (4.0 - (3.0 * pow(cosAlpha, 2.0)))));\n\tT Omega = Lambda - ((1.0 - C) * f * sinAlpha * (Sigma + (C * sin(Sigma) * (cos(twoSigmam) + (C * cos(Sigma) * (-1 + (2 * pow(cos(twoSigmam), 2.0))))))));\n\t\n\t// longitude of new position\n\t*dLongitudeTO = dLongitudeAT + Omega;\n}\n\ntemplate <class T>\nvoid ComputeLocalElements3D(const T X1, const T Y1, const T Z1,\n\t\t\tconst T X2, const T Y2, const T Z2, \n\t\t\tconst T currentLatitude, const T currentLongitude,\n\t\t\tT* local_12e, T* local_12n, T* local_12up)\n{\n\t// 1->2\n\tT dX12(X2 - X1);\n\tT dY12(Y2 - Y1);\n\tT dZ12(Z2 - Z1);\n\n\t// helpers\n\tT sin_lat(sin(currentLatitude));\n\tT cos_lat(cos(currentLatitude));\n\tT sin_long(sin(currentLongitude));\n\tT cos_long(cos(currentLongitude));\n\n\n\t*local_12e = -sin_long * dX12 + cos_long * dY12;\n\t*local_12n = -sin_lat * cos_long * dX12 - \n\t\tsin_lat * sin_long * dY12 +\n\t\tcos_lat * dZ12;\n\t*local_12up = cos_lat * cos_long * dX12 +\n\t\tcos_lat * sin_long * dY12 +\n\t\tsin_lat * dZ12;\n}\n\ntemplate <class T>\nvoid ComputeLocalElements2D(const T X1, const T Y1, const T Z1,\n\tconst T X2, const T Y2, const T Z2,\n\tconst T currentLatitude, const T currentLongitude,\n\tT* local_12e, T* local_12n)\n{\n\t// 1->2\n\tT dX12(X2 - X1);\n\tT dY12(Y2 - Y1);\n\tT dZ12(Z2 - Z1);\n\n\t// helpers\n\tT sin_lat(sin(currentLatitude));\n\tT cos_lat(cos(currentLatitude));\n\tT sin_long(sin(currentLongitude));\n\tT cos_long(cos(currentLongitude));\n\n\n\t*local_12e = -sin_long * dX12 + cos_long * dY12;\n\t*local_12n = -sin_lat * cos_long * dX12 -\n\t\tsin_lat * sin_long * dY12 +\n\t\tcos_lat * dZ12;\n}\n\ntemplate <class T>\nT Direction(const T local_12e, const T local_12n)\n{\n\t// \"computed\" direction 1->2\n\tT direction12;\n\n\tif (fabs(local_12e) < fabs(local_12n))\n\t\tdirection12 = atan_2(local_12e, local_12n);\n\telse\n\t\tdirection12 = HALF_PI - atan_2(local_12n, local_12e);\n\n\tif (direction12 < 0)\n\t\tdirection12 += TWO_PI;\n\t\n\treturn direction12;\n}\n\ntemplate <class T>\nT Direction(const T X1, const T Y1, const T Z1,\n\t\t\tconst T X2, const T Y2, const T Z2, \n\t\t\tconst T currentLatitude, const T currentLongitude,\n\t\t\tT* local_12e, T* local_12n)\n{\n\tComputeLocalElements2D(X1, Y1, Z1, X2, Y2, Z2, currentLatitude, currentLongitude,\n\t\tlocal_12e, local_12n);\n\n\treturn Direction(*local_12e, *local_12n);\n}\n\ntemplate <class T>\n// helper function\nT Direction(const T X1, const T Y1, const T Z1,\n\t\t\tconst T X2, const T Y2, const T Z2, \n\t\t\tconst T currentLatitude, const T currentLongitude)\n{\n\tT local_12e, local_12n;\n\t\n\treturn Direction(X1, Y1, Z1,\n\t\tX2, Y2, Z2, \n\t\tcurrentLatitude, currentLongitude,\n\t\t&local_12e, &local_12n);\n}\n\ntemplate <class T>\nT HorizontalAngle(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T X3, const T Y3, const T Z3, \n\t\t\t\t  const T currentLatitude, const T currentLongitude,\n\t\t\t\t  T* direction12, T* direction13,\n\t\t\t\t  T* local_12e, T* local_12n, T* local_13e, T* local_13n)\n{\n\t// compute vectors [1->2] & [1->3] in the local reference frame\n\t//\n\t// 1->2\n\t*direction12 = Direction(X1, Y1, Z1, X2, Y2, Z2, currentLatitude, currentLongitude, local_12e, local_12n);\n\t*direction13 = Direction(X1, Y1, Z1, X3, Y3, Z3, currentLatitude, currentLongitude, local_13e, local_13n);\n\t\n\tif (*direction12 > *direction13)\n\t\t*direction13 += TWO_PI;\n\n\t// angle 123\n\tT angle = *direction13 - *direction12;\n\n\treturn angle;\n}\n\ntemplate <class T>\n// helper function\nT HorizontalAngle(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T X3, const T Y3, const T Z3, \n\t\t\t\t  const T currentLatitude, const T currentLongitude,\n\t\t\t\t  T* direction12, T* direction13)\n{\n\tT local_12e, local_12n, local_13e, local_13n;\n\n\treturn HorizontalAngle(X1, Y1, Z1, \n\t\tX2, Y2, Z2, \n\t\tX3, Y3, Z3, \n\t\tcurrentLatitude, currentLongitude,\n\t\tdirection12, direction13,\n\t\t&local_12e, &local_12n, &local_13e, &local_13n);\n}\n\ntemplate <class T>\nvoid CartesianElementsFromInstrumentHeight(const T height, T* dX, T* dY, T* dZ, \n\t\t\t\t  const T Latitude, const T Longitude)\n{\n\t// Use rotation matrix for local vector -> cartesian vector, whereby\n\t// local elements for e and n are zero\n\t*dX = cos(Latitude) * cos(Longitude) * height;\n\t*dY = cos(Latitude) * sin(Longitude) * height;\n\t*dZ = sin(Latitude) * height;\n}\n\t\ntemplate <class T>\n// The return value is the true vertical between the (local) horizontal plane\n// and the instrument-target vector.  The local_12e/n/up elements represent \n// the geometric difference between the two stations\nT VerticalAngle(const T& local_12e, const T& local_12n, const T& local_12up)\n{\n\treturn atan2(local_12up, sqrt((local_12e * local_12e) + (local_12n * local_12n)));\n}\n\ntemplate <class T>\n// The return value is the true vertical between the (local) horizontal plane\n// and the instrument-target vector.  The local_12e/n/up elements represent \n// the geometric difference between the two stations\nT VerticalAngle(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T latitude1, const T longitude1,\n\t\t\t\t  const T latitude2, const T longitude2,\n\t\t\t\t  const T instrumentHeight, const T targetHeight,\n\t\t\t\t  T* local_12e, T* local_12n, T* local_12up)\n{\n\t// helpers\n\tT sin_lat1(sin(latitude1));\n\tT cos_lat1(cos(latitude1));\n\tT sin_long1(sin(longitude1));\n\tT cos_long1(cos(longitude1));\n\n\t// Compute cartesian elements dX, dY, dZ for instrument to target\n\t// First, compute cartesian vector for both instrument and target\n\tT dXih, dYih, dZih, dXth, dYth, dZth;\n\tCartesianElementsFromInstrumentHeight(instrumentHeight,\n\t\t&dXih, &dYih, &dZih, latitude1, longitude1);\n\tCartesianElementsFromInstrumentHeight(targetHeight,\n\t\t&dXth, &dYth, &dZth, latitude2, longitude2);\n\n\tT dX12(X2 - X1 + dXth - dXih);\n\tT dY12(Y2 - Y1 + dYth - dYih);\n\tT dZ12(Z2 - Z1 + dZth - dZih);\n\n\t// compute local reference frame elements (station1 to station2)\n\t*local_12e = -sin_long1 * dX12 + cos_long1 * dY12;\n\t*local_12n = -sin_lat1 * cos_long1 * dX12 -\n\t\t\t\t\tsin_lat1 * sin_long1 * dY12 +\n\t\t\t\t\tcos_lat1 * dZ12;\n\t*local_12up = cos_lat1 * cos_long1 * dX12 +\n\t\t\t\t\tcos_lat1 * sin_long1 * dY12 +\n\t\t\t\t\tsin_lat1 * dZ12;\n\n\t// compute angle (instrument to target)\n\treturn VerticalAngle(*local_12e, *local_12n, *local_12up);\n\t//return atan2((*local_12up), sqrt(((*local_12e) * (*local_12e)) + ((*local_12n) * (*local_12n))));\n\t//////////////////////////////////////////////////////\n}\n\ntemplate <class T>\n// helper function\nT VerticalAngle(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T latitude1, const T longitude1,\n\t\t\t\t  const T latitude2, const T longitude2,\n\t\t\t\t  const T instrumentHeight, const T targetHeight)\n{\n\tT local_12e, local_12n, local_12up;\n\n\treturn VerticalAngle(\n\t\tX1, Y1, Z1, \n\t\tX2, Y2, Z2, \n\t\tlatitude1, longitude1,\n\t\tlatitude2, longitude2,\n\t\tinstrumentHeight, targetHeight,\n\t\t&local_12e, &local_12n, &local_12up);\n}\n\n\ntemplate <class T>\n// The return value is the true zenith distance between the ellipsoid normal\n// and the instrument-target vector.  The local_12e/n/up elements represent \n// the geometric difference between the two stations\nT ZenithDistance(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T latitude1, const T longitude1,\n\t\t\t\t  const T latitude2, const T longitude2,\n\t\t\t\t  const T instrumentHeight, const T targetHeight,\n\t\t\t\t  T* local_12e, T* local_12n, T* local_12up)\n{\n\t// helpers\n\tT sin_lat1(sin(latitude1));\n\tT cos_lat1(cos(latitude1));\n\tT sin_long1(sin(longitude1));\n\tT cos_long1(cos(longitude1));\n\n\t// Compute cartesian elements dX, dY, dZ for instrument to target\n\t// First, compute cartesian vector for both instrument and target\n\tT dXih, dYih, dZih, dXth, dYth, dZth;\n\tCartesianElementsFromInstrumentHeight(instrumentHeight,\n\t\t&dXih, &dYih, &dZih, latitude1, longitude1);\n\tCartesianElementsFromInstrumentHeight(targetHeight,\n\t\t&dXth, &dYth, &dZth, latitude2, longitude2);\n\n\tT dX12(X2 - X1 + dXth - dXih);\n\tT dY12(Y2 - Y1 + dYth - dYih);\n\tT dZ12(Z2 - Z1 + dZth - dZih);\n\n\t// compute local reference frame elements (station1 to station2)\n\t*local_12e = -sin_long1 * dX12 + cos_long1 * dY12;\n\t*local_12n = -sin_lat1 * cos_long1 * dX12 -\n\t\t\t\t\tsin_lat1 * sin_long1 * dY12 +\n\t\t\t\t\tcos_lat1 * dZ12;\n\t*local_12up = cos_lat1 * cos_long1 * dX12 +\n\t\t\t\t\tcos_lat1 * sin_long1 * dY12 +\n\t\t\t\t\tsin_lat1 * dZ12;\n\n\t// compute angle (instrument to target)\n\treturn atan2(sqrt((*local_12e) * (*local_12e) + (*local_12n) * (*local_12n)), (*local_12up));\n\t//////////////////////////////////////////////////////\n}\n\ntemplate <class T>\n// helper function\nT ZenithDistance(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T latitude1, const T longitude1,\n\t\t\t\t  const T latitude2, const T longitude2,\n\t\t\t\t  const T instrumentHeight, const T targetHeight)\n{\n\tT local_12e, local_12n, local_12up;\n\n\treturn ZenithDistance(\n\t\tX1, Y1, Z1, X2, Y2, Z2, \n\t\tlatitude1, longitude1,\n\t\tlatitude2, longitude2,\n\t\tinstrumentHeight, targetHeight,\n\t\t&local_12e, &local_12n, &local_12up);\n}\n\t\n\ntemplate <class T>\nT EllipsoidHeight(const T X, const T Y, const T Z, \n\t\t\t\t  const T latitude, T* nu, T* Zn,\n\t\t\t\t  const CDnaEllipsoid* ellipsoid)\n{\n\t*nu = primeVertical(ellipsoid, latitude);\n\t// Zn is the z coordinate element of the point on the z-axis \n\t// which intersects with the the normal at the given Latitude\n\t*Zn = ellipsoid->GetE1sqd() * (*nu) * sin(latitude);\n\n\treturn sqrt(X*X + Y*Y + pow(Z+(*Zn), (int)2)) - (*nu);\n}\n\t\ntemplate <class T>\nT EllipsoidHeightDifference(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T Latitude1, const T Latitude2,\n\t\t\t\t  T* h1, T* h2, T* nu1, T* nu2, T* Zn1, T* Zn2, \n\t\t\t\t  const CDnaEllipsoid* ellipsoid)\n{\n\treturn ((*h2 = EllipsoidHeight(X2, Y2, Z2, Latitude2, nu2, Zn2, ellipsoid)) - \n\t\t(*h1 = EllipsoidHeight(X1, Y1, Z1, Latitude1, nu1, Zn1, ellipsoid)));\n}\n\ntemplate <class T>\nT magnitude(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2)\n{\n\treturn sqrt(((X2 - X1) * (X2 - X1)) + ((Y2 - Y1) * (Y2 - Y1)) + ((Z2 - Z1) * (Z2 - Z1)));\n}\n\ntemplate <class T>\nT magnitude(const T dX, const T dY, const T dZ)\n{\n\treturn sqrt((dX * dX) + (dY * dY) + (dZ * dZ));\n}\n\ntemplate <class T>\nT magnitude(const T X1, const T N1, const T X2, const T N2)\n{\n\treturn sqrt(((X2 - X1) * (X2 - X1)) + ((N2 - N1) * (N2 - N1)));\n}\n\ntemplate <class T>\nT magnitude(const T dX, const T dN)\n{\n\treturn sqrt((dX * dX) + (dN * dN));\n}\n\ntemplate <class T>\nT EllipsoidChordDistance(const T X1, const T Y1, const T Z1, \n\t\t\t\t  const T X2, const T Y2, const T Z2, \n\t\t\t\t  const T latitude1, const T latitude2,\n\t\t\t\t  const T Height1, const T Height2,\n\t\t\t\t  T* dX, T* dY, T* dZ, \n\t\t\t\t  const CDnaEllipsoid* ellipsoid)\n{\n\tT nu1(primeVertical(ellipsoid, latitude1));\n\tT nu2(primeVertical(ellipsoid, latitude2));\n\n\tT scale1(nu1 / (nu1 + Height1));\n\tT scale2(nu2 / (nu2 + Height2));\n\n\t// Zn1,2 is the z coordinate element of the point on the z-axis \n\t// which intersects with the the normal at the given Latitude\n\tT Zn1(ellipsoid->GetE1sqd() * nu1 * sin(latitude1));\n\tT Zn2(ellipsoid->GetE1sqd() * nu2 * sin(latitude2));\n\n\t// station 1\n\tT x1(X1 * scale1);\n\tT y1(Y1 * scale1);\n\tT z1((Z1 + Zn1) * scale1 - Zn1);\n \n\t// station 2\n\tT x2(X2 * scale2);\n\tT y2(Y2 * scale2);\n\tT z2((Z2 + Zn2) * scale2 - Zn2);\n\n\t*dX = x2 - x1;\n\t*dY = y2 - y1;\n\t*dZ = z2 - z1;\n\n\treturn magnitude(*dX, *dY, *dZ);\n}\n\ntemplate <class T>\nT RadiusCurvatureInChordDirection(const T X1, const T Y1, const T Z1, \n\t\t\t const T X2, const T Y2, const T Z2, \t\t\t\t  \n\t\t\t const T latitude1, const T longitude1, const T latitude2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT nu, rho;\n\tprimeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho);\n\n\tT local_12e, local_12n;\n\tT direction12(Direction(X1, Y1, Z1, X2, Y2, Z2,\n\t\tlatitude1, longitude1, &local_12e, &local_12n));\t\t\t\t  \n\tT cos_dir(cos(direction12));\n\tT sin_dir(sin(direction12));\n\treturn  rho * nu / ((nu * cos_dir * cos_dir) + (rho * sin_dir * sin_dir));\n}\n\ntemplate <class T>\nT EllipsoidArctoEllipsoidChord(const T arc, \n\t\t\t const T X1, const T Y1, const T Z1, \n\t\t\t const T X2, const T Y2, const T Z2, \t\t\t\t  \n\t\t\t const T Latitude1, const T Longitude1, const T Latitude2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT r(RadiusCurvatureInChordDirection(X1, Y1, Z1, X2, Y2, Z2, Latitude1, Longitude1, Latitude2, ellipsoid));\n\treturn 2.0 * r * sin(arc / 2.0 / r);\n}\n\n\ntemplate <class T>\nT EllipsoidChordtoEllipsoidArc(const T chord, \n\t\t\t const T X1, const T Y1, const T Z1, \n\t\t\t const T X2, const T Y2, const T Z2, \t\t\t\t  \n\t\t\t const T Latitude1, const T Longitude1, const T Latitude2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT r(RadiusCurvatureInChordDirection(X1, Y1, Z1, X2, Y2, Z2, Latitude1, Longitude1, Latitude2, ellipsoid));\n\treturn asin(chord / 2.0 / r) * 2.0 * r;\n}\n\ntemplate <class T>\nT EllipsoidArcDistance(\n\t\t\t const T X1, const T Y1, const T Z1, \n\t\t\t const T X2, const T Y2, const T Z2, \t\t\t\t  \n\t\t\t const T Latitude1, const T Longitude1, const T Latitude2,\n\t\t\t const T Height1, const T Height2, \n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT dx, dy, dz, ellipsoid_chord;\n\tellipsoid_chord = EllipsoidChordDistance<T>(\n\t\tX1, Y1, Z1,\n\t\tX2, Y2, Z2,\n\t\tLatitude1, Latitude2,\n\t\tHeight1, Height2, &dx, &dy, &dz, ellipsoid);\n\n\treturn EllipsoidChordtoEllipsoidArc<T>(\n\t\tellipsoid_chord, \n\t\tX1, Y1, Z1, \n\t\tX2, Y2, Z2, \t\t\t\t  \n\t\tLatitude1, Longitude1, Latitude2,\n\t\tellipsoid);\n}\n\ntemplate <class T>\nT MSLChordtoMSLArc(const T chord, \n\t\t\t const T latitude1, const T latitude2,\n\t\t\t const T N1, const T N2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT nu, rho;\n\tprimeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho);\n\n\tT r(sqrt(nu*rho) + average(N1, N2));\n\treturn asin(chord / 2.0 / r) * 2.0 * r;\n}\n\n\ntemplate <class T>\nT MSLArctoMSLChord(const T arc, \n\t\t\t const T latitude1, const T latitude2,\n\t\t\t const T N1, const T N2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\tT nu, rho;\n\tprimeVerticalandMeridian(ellipsoid, average(latitude1, latitude2), nu, rho);\n\n\tT r(sqrt(nu*rho) + average(N1, N2));\n\treturn 2.0 * r * sin(arc / 2.0 / r);\n}\n\n\ntemplate <class T>\nT MSLChordtoEllipsoidChord(const T msl_chord, \n\t\t\t\t\t\t   const T Latitude1, const T Latitude2,\n\t\t\t\t\t\t   const T N1, const T N2,\n\t\t\t\t\t\t   const CDnaEllipsoid* ellipsoid)\n{\n\tT ellipsoid_chord(msl_chord * msl_chord);\n\tellipsoid_chord -= pow(N2 - N1, (int)2);\n\n\tT meanLat(average(Latitude1, Latitude2));\n\tellipsoid_chord /= 1. + N1 / averageRadiusofCurvature(ellipsoid, meanLat);\n\tellipsoid_chord /= 1. + N2 / averageRadiusofCurvature(ellipsoid, meanLat);\n\treturn sqrt(ellipsoid_chord);\n}\n\ntemplate <class T>\nT MSLArctoEllipsoidChord(const T msl_arc, \n\t\t\t\t\t\t   const T Latitude1, const T Latitude2,\n\t\t\t\t\t\t   const T N1, const T N2,\n\t\t\t\t\t\t   const CDnaEllipsoid* ellipsoid)\n{\n\t// 1. Convert MSL Arc -> MSL Chord\n\tT msl_chord = MSLArctoMSLChord<T>(msl_arc, \n\t\tLatitude1, Latitude2,\n\t\tN1, N2,\n\t\tellipsoid);\n\t\n\t// 2. Convert MSL Chord -> Ellipsoid Chord\n\treturn MSLChordtoEllipsoidChord<T>(msl_chord, \n\t\tLatitude1, Latitude2,\n\t\tN1, N2,\n\t\tellipsoid);\n}\n\ntemplate <class T>\nT EllipsoidChordtoMSLChord(const T ellipsoid_chord, \n\t\t\t\t\t\t   const T Latitude1, const T Latitude2,\n\t\t\t\t\t\t   const T N1, const T N2,\n\t\t\t\t\t\t   const CDnaEllipsoid* ellipsoid)\n{\n\tT msl_chord(ellipsoid_chord * ellipsoid_chord);\n\tT meanLat(average(Latitude1, Latitude2));\n\t\n\tmsl_chord *= 1. + N1 / averageRadiusofCurvature(ellipsoid, meanLat);\n\tmsl_chord *= 1. + N2 / averageRadiusofCurvature(ellipsoid, meanLat);\n\tmsl_chord += pow(N2 - N1, (int)2);\n\t\n\treturn sqrt(msl_chord);\n}\n\ntemplate <class T>\nT EllipsoidChordtoMSLArc(const T ellipsoid_chord, \n\t\t\t\t\t\t   const T Latitude1, const T Latitude2,\n\t\t\t\t\t\t   const T N1, const T N2,\n\t\t\t\t\t\t   const CDnaEllipsoid* ellipsoid)\n{\n\t// 1. Convert Ellipsoid Chord -> MSL Chord\n\tT msl_chord = EllipsoidChordtoMSLChord<T>(\n\t\tellipsoid_chord, Latitude1, Latitude2,\n\t\tN1, N2, ellipsoid);\n\n\t// 2. Convert MSL Chord to MSL Arc\n\treturn MSLChordtoMSLArc<T>(\n\t\tmsl_chord, Latitude1, Latitude2,\n\t\tN1, N2, ellipsoid);\n}\n\ntemplate <class T>\nT MSLArcDistance(\n\t\t\t const T X1, const T Y1, const T Z1, \n\t\t\t const T X2, const T Y2, const T Z2, \t\t\t\t  \n\t\t\t const T Latitude1, const T Longitude1, const T Latitude2,\n\t\t\t const T Height1, const T Height2, \n\t\t\t const T N1, const T N2,\n\t\t\t const CDnaEllipsoid* ellipsoid)\n{\n\t// 1. Calculate Ellipsoid Chord\n\tT dx, dy, dz, chord;\n\tchord = EllipsoidChordDistance<T>(\n\t\tX1, Y1, Z1,\n\t\tX2, Y2, Z2,\n\t\tLatitude1, Latitude2,\n\t\tHeight1, Height2, &dx, &dy, &dz, ellipsoid);\n\n\t// 2. Convert Ellipsoid Chord -> MSL Chord\n\tchord = EllipsoidChordtoMSLChord<T>(\n\t\tchord, Latitude1, Latitude2,\n\t\tN1, N2, ellipsoid);\n\n\t// 3. Convert MSL Chord -> MSL Arc\n\treturn MSLChordtoMSLArc<T>(\n\t\tchord, Latitude1, Latitude2,\n\t\tN1, N2, ellipsoid);\n}\n\t\n\ntemplate <class T>\nT LaplaceCorrection(const T azimuth, const T zenith,\n\t\t\t\t\tconst T deflPrimeV, const T deflPrimeM,\n\t\t\t\t\tconst T Latitude)\n{\n\treturn deflPrimeV * tan(Latitude) + ((deflPrimeM * sin(azimuth) - deflPrimeV * cos(azimuth)) / tan(zenith));\t// cot(z) = 1/tan(z)\n}\n\ntemplate <class T>\nT ZenithDeflectionCorrection(const T azimuth, const T deflPrimeV, const T deflPrimeM)\n{\n\treturn deflPrimeM * cos(azimuth) + deflPrimeV * sin(azimuth);\n}\n\ntemplate <class T>\nT DirectionDeflectionCorrection(const T azimuth, const T zenith,\n\t\t\t\t\t\t\t\t\t  const T deflPrimeV, const T deflPrimeM)\n{\n\treturn (deflPrimeM * sin(azimuth) - deflPrimeV * cos(azimuth)) / tan(zenith);\t// cot(z) = 1/tan(z)\n}\n\ntemplate <class T>\nT HzAngleDeflectionCorrection(const T azimuth12, const T zenith12,\n\t\t\t\t\t\t\t\t\t  const T azimuth13, const T zenith13,\n\t\t\t\t\t\t\t\t\t  const T deflPrimeV, const T deflPrimeM)\n{\n\treturn DirectionDeflectionCorrection(azimuth13, zenith13, deflPrimeV, deflPrimeM) -\n\t\tDirectionDeflectionCorrection(azimuth12, zenith12, deflPrimeV, deflPrimeM);\n}\n\ntemplate <class T>\nT HzAngleDeflectionCorrections(const T azimuth12, const T zenith12,\n\tconst T azimuth13, const T zenith13,\n\tconst T deflPrimeV, const T deflPrimeM, T& correction12, T& correction13)\n{\n\treturn (correction13 = DirectionDeflectionCorrection(azimuth13, zenith13, deflPrimeV, deflPrimeM)) -\n\t\t(correction12 = DirectionDeflectionCorrection(azimuth12, zenith12, deflPrimeV, deflPrimeM));\n}\n#endif /* DNATEMPLATEGEODESYFUNCS_H_ */\n", "meta": {"hexsha": "02dbd0b385f6dd2b5c058de4dee426d41487fff9", "size": 39557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dynadjust/include/functions/dnatemplategeodesyfuncs.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/dnatemplategeodesyfuncs.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/dnatemplategeodesyfuncs.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": 32.3178104575, "max_line_length": 249, "alphanum_fraction": 0.6442854615, "num_tokens": 13928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5956367278829783}}
{"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 \"DatasetPoly.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(0.001, 1);\n\n    // prepare \n    std::map<int, my_float> coeff_3 {\n        {1, 0.4},\n        {3, -20},\n    };\n    std::map<int, my_float> pow_3 {\n        {1, 3},\n        {3, 2},\n    };\n    std::map<int, my_float> coeff_4 {\n        {1, 0.4},\n        {3, 0.1},\n    };\n    std::map<int, my_float> pow_4 {\n        {1, 7},\n        {3, 0.5},\n    };\n    std::vector<my_float> v_seed_three(3);\n\n    // Non-stationary, non-linear AR process 1\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 < 3; i++) {\n                v_seed_three[i] = u(gen);\n            }\n            ARPoly targ_seq(coeff_3, pow_3, u(gen));\n            targ_seq.seed_prev_vals(v_seed_three);\n\n            DatasetPoly dat(\"./ARPoly-1/ARPoly-1-\" + std::to_string(type) + \n                \"/Sample-\" + std::to_string(samp), targ_seq, type);\n            dat.write_csv();\n        }\n    }\n\n    // Non-stationary, non-linear AR process 2 \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 < 3; i++) {\n                v_seed_three[i] = u(gen);\n            }\n            ARPoly targ_seq(coeff_4, pow_4, u(gen));\n            targ_seq.seed_prev_vals(v_seed_three);\n\n            DatasetPoly dat(\"./ARPoly-2/ARPoly-2-\" + std::to_string(type) + \n                \"/Sample-\" + std::to_string(samp), targ_seq, type);\n            dat.write_csv();\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "aeda183a80018b4d424ddd62ff10683ff343427a", "size": 2140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/main/gen-train-2.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-2.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-2.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": 27.7922077922, "max_line_length": 76, "alphanum_fraction": 0.5481308411, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5956367253241405}}
{"text": "//! [mathematical-all]\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/align/aligned_allocator.hpp>\n#include <boost/align/aligned_delete.hpp>\n\n#include <boost/simd/constant/pio_4.hpp>\n#include <boost/simd/function/cos.hpp>\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/function/sin.hpp>\n#include <boost/simd/function/sincos.hpp>\n#include <boost/simd/function/store.hpp>\n#include <boost/simd/function/ulpdist.hpp>\n#include <boost/simd/pack.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T>\nvoid test_results(const std::string& mes, const T& scalr, const T& simdr)\n{\n  std::cout << mes;\n  for (int i = 0; i < scalr.size(); ++i) {\n    if (bs::ulpdist(scalr[i], simdr[i]) > 0.5) {\n      std::cout << \" failed\" << std::endl;\n      return;\n    }\n  }\n  std::cout << \" succeeded\" << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n  namespace ba = boost::alignment;\n\n  using pack_t = bs::pack<float>;\n\n  std::size_t num_elements = 1024;\n  std::size_t alignment    = pack_t::alignment;\n  //! [mathematical-declare]\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> X(num_elements);\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> sinX(num_elements),\n    sc_sinX(num_elements);\n  std::vector<float, ba::aligned_allocator<float, pack_t::alignment>> cosX(num_elements),\n    sc_cosX(num_elements);\n  //! [mathematical-declare]\n\n  //! [fill-input]\n  for (int i = 0; i < num_elements; ++i) {\n    X[i] = (float(i) / num_elements) * bs::Pio_4<float>();\n  }\n\n  //! [fill-input]\n  //! [mathematical-scalar]\n  for (int i = 0; i < num_elements; ++i) {\n    sc_sinX[i] = std::sin(X[i]);\n    sc_cosX[i] = std::cos(X[i]);\n  }\n  //! [mathematical-scalar]\n\n  //! [mathematical-calc-individ]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    bs::store(bs::sin(v0), &sinX[i]);\n    bs::store(bs::cos(v0), &cosX[i]);\n  }\n  //! [mathematical-calc-individ]\n  test_results(\"sin test               \", sc_sinX, sinX);\n  test_results(\"cos test               \", sc_cosX, cosX);\n\n  //! [mathematical-calc-combine]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    auto res  = bs::sincos(v0);\n    bs::store(res.first, &sinX[i]);\n    bs::store(res.second, &cosX[i]);\n  }\n  //! [mathematical-calc-combine]\n  test_results(\"sincos test for sin    \", sc_sinX, sinX);\n  test_results(\"sincos test for cos    \", sc_cosX, cosX);\n\n  //! [mathematical-calc-restricted]\n  for (int i = 0; i < num_elements; i += pack_t::static_size) {\n    pack_t v0 = bs::load<pack_t>(&X[i]);\n    bs::store(bs::restricted_(bs::sin)(v0), &sinX[i]);\n    bs::store(bs::restricted_(bs::cos)(v0), &cosX[i]);\n  }\n  //! [mathematical-calc-restricted]\n  test_results(\"restricted_(sin) test  \", sc_sinX, sinX);\n  test_results(\"restricted_(cos) test  \", sc_cosX, cosX);\n\n  return 0;\n}\n// This code can be compiled using (for instance for gcc)\n// g++ mathematical.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o mathematical\n// -I/path_to/boost_simd/ -I/path_to/boost/\n\n//! [mathematical-all]\n", "meta": {"hexsha": "6e6734dce38383c6607071f0bf623f11dfe07f60", "size": 3128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/mathematical.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/mathematical.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/mathematical.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": 30.9702970297, "max_line_length": 89, "alphanum_fraction": 0.6397058824, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5956085281285577}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/sign.hpp\n *\n * \\brief Compute the sign function for each element of a vector or matrix\n *  expression.\n *\n * The sign function for real numbers as defined as follows:\n * \\f[\n * \\operatorname{sign}(x):=\\begin{cases}\n *                          -1 & \\text{if } x<0,\\\\\n *                           0 & \\text{if } x=0,\\\\\n *                           1 & \\text{if } x>0.\n *                         \\end{cases}\n * \\f]\n * In case of complex numbers, the sign function is defined as follows:\n * \\f[\n * \\operatorname{sign}(z)=\\begin{cases}\n *                          \\frac{z}{|z|} & \\text{if } z \\ne 0,\\\\\n *                          0 & \\text{if } z = 0+0i.\n *                        \\end{cases}\n * \\f]\n *\n * \\sa The sign function at Wikipedia: https://en.wikipedia.org/wiki/Sign_function\n *\n * \\author comcon1 (original version)\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\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_SIGN_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SIGN_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_unary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_unary_functor.hpp>\n#include <boost/type_traits/is_complex.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <cmath>\n#include <complex>\n#include <limits>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT>\nstruct vector_sign_functor_traits\n{\n    typedef VectorExprT input_expression_type;\n    typedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n    typedef typename type_traits<signature_argument_type>::value_type signature_result_type;\n    typedef vector_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_sign_functor_traits\n{\n    typedef MatrixExprT input_expression_type;\n    typedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n    typedef typename type_traits<signature_argument_type>::value_type signature_result_type;\n    typedef matrix_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n/// Auxiliary function for real types: sign(x) = 1 if x > 0, 0 if x == 0, -1 otherwise.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\ntypename ::boost::disable_if<\n            ::boost::is_complex<T>,\n            T\n>::type sign_impl(T x)\n{\n    if (::std::isnan(x))\n    {\n        return ::std::numeric_limits<T>::quiet_NaN();\n    }\n    return (x > 0) ? 1 : ((x < 0) ? -1 : 0);\n}\n\n/// Auxiliary function for complex types: sign(x) = x ./ abs(x)\ntemplate <typename T>\nBOOST_UBLAS_INLINE\ntypename ::boost::enable_if<\n            ::boost::is_complex<T>,\n            T\n>::type sign_impl(T x)\n{\n    typename T::value_type a = ::std::abs(x);\n    return (a == 0) ? T(0,0) : (x / a);\n}\n\n//template <typename RealType> \n//BOOST_UBLAS_INLINE \n//RealType sign(RealType v)\n//{\n//    return ( -(RealType)( ::std::signbit(v) ) + 0.5 ) * 2.0;\n//}\n\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::sign function to a given vector expression.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::sign to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_sign_functor_traits<VectorExprT>::result_type sign(vector_expression<VectorExprT> const& ve)\n{\n    typedef typename detail::vector_sign_functor_traits<VectorExprT>::expression_type expression_type;\n    typedef typename detail::vector_sign_functor_traits<VectorExprT>::signature_result_type signature_result_type;\n\n    return expression_type(ve(), detail::sign_impl<signature_result_type>);\n}\n\n\n/**\n * \\brief Applies the \\c std::sign function to a given matrix expression.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::sign to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_sign_functor_traits<MatrixExprT>::result_type sign(matrix_expression<MatrixExprT> const& me)\n{\n    typedef typename detail::matrix_sign_functor_traits<MatrixExprT>::expression_type expression_type;\n    typedef typename detail::matrix_sign_functor_traits<MatrixExprT>::signature_result_type signature_result_type;\n\n    return expression_type(me(), detail::sign_impl<signature_result_type>);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SIGN_HPP\n", "meta": {"hexsha": "1053ecd211b2a2b7b74b54d528de2a54f0596cac", "size": 5600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/sign.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/sign.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/sign.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 32.7485380117, "max_line_length": 116, "alphanum_fraction": 0.7085714286, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.5955582812512905}}
{"text": "/**\n * @file  maximumprinciple.cc\n * @brief NPDE homework \"MaximumPrinciple\" code\n * @author Oliver Rietmann\n * @date 25.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"maximumprinciple.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <vector>\n\nnamespace MaximumPrinciple {\n\n/**\n * @brief Assembly on a tensor product mesh\n *\n * Compute the global Galerkin matrix from the local\n * element matrix.\n *\n * @param M Number of interior vertices in x and y direction.\n * @param B_K Local element matrix.\n * @return Global Galerkin matrix of size M^2 times M^2.\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<double> assemble(int M, const Eigen::Matrix3d &B_K) {\n  int M2 = M * M;\n  Eigen::SparseMatrix<double> A(M2, M2);\n  double near_neighbour_contribution = 2.0 * B_K(0, 1);\n  double far_neighbour_contribution = 2.0 * B_K(1, 2);\n  double self_contribution = 2.0 * (B_K(0, 0) + B_K(1, 1) + B_K(2, 2));\n\n  std::vector<double> contribution = {\n      far_neighbour_contribution,  near_neighbour_contribution,\n      near_neighbour_contribution, self_contribution,\n      near_neighbour_contribution, near_neighbour_contribution,\n      far_neighbour_contribution};\n\n  std::vector<Eigen::Vector2i> shift = {{-1, -1}, {0, -1}, {-1, 0}, {0, 0},\n                                        {1, 0},   {0, 1},  {1, 1}};\n\n  std::vector<Eigen::Triplet<double>> tripletList;\n  for (int i = 0; i < M; ++i) {\n    for (int j = 0; j < M; ++j) {\n      Eigen::Vector2i self = Eigen::Vector2i(i, j);\n      for (int k = 0; k < 7; ++k) {\n        Eigen::Vector2i other = self + shift[k];\n        if (0 <= other(0) && other(0) < M && 0 <= other(1) && other(1) < M) {\n          tripletList.push_back(Eigen::Triplet<double>(\n              self(0) + M * self(1), other(0) + M * other(1), contribution[k]));\n        }\n      }\n    }\n  }\n  A.setFromTriplets(tripletList.begin(), tripletList.end());\n  return A;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<double> computeGalerkinMatrix(int M, double c) {\n  Eigen::Matrix3d B_K;\n  double h = 1.0 / (M + 1);\n  Eigen::Matrix3d A_K;\n  A_K << 1.0, -0.5, -0.5, -0.5, 0.5, 0.0, -0.5, 0.0, 0.5;\n  Eigen::Matrix3d M_K;\n  M_K << 2.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 2.0;\n  M_K *= h * h / 24.0;\n  B_K = (1.0 - c) * A_K + c * M_K;\n  return assemble(M, B_K);\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::SparseMatrix<double> computeGalerkinMatrixTR(int M, double c) {\n  Eigen::Matrix3d B_K;\n  double h = 1.0 / (M + 1);\n  Eigen::Matrix3d A_K;\n  A_K << 1.0, -0.5, -0.5, -0.5, 0.5, 0.0, -0.5, 0.0, 0.5;\n  Eigen::Matrix3d M_K = h * h / 6.0 * Eigen::Matrix3d::Identity();\n  B_K = (1.0 - c) * A_K + c * M_K;\n  return assemble(M, B_K);\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace MaximumPrinciple\n", "meta": {"hexsha": "baa30c2594a16e79d399fa6a9e6996e25f4522f8", "size": 2763, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MaximumPrinciple/mastersolution/maximumprinciple.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/MaximumPrinciple/mastersolution/maximumprinciple.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/MaximumPrinciple/mastersolution/maximumprinciple.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": 31.0449438202, "max_line_length": 80, "alphanum_fraction": 0.6102062975, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.5955119111270268}}
{"text": "// ideal_random_walk.cpp\n\n#include <algorithm>\n#include <fstream>\n\n#include <boost/math/special_functions/factorials.hpp>\n\n#include \"ideal_random_walk.h\"\n\nnamespace idealRandomWalk {\n\nusing boost::math::factorial;\n\nlong double IdealRandomWalks::num_walks(\n        VectorThree start_pos,\n        VectorThree end_pos,\n        int steps) {\n\n    // Check stored values\n    VectorThree DR {end_pos - start_pos};\n\n    // Only work with one permutation of DR\n    DR = DR.absolute().sort();\n    pair<VectorThree, int> walk_key {DR, steps};\n    if (m_num_walks.count(walk_key)) {\n        return m_num_walks.at(walk_key);\n    }\n    int DX {DR[0]};\n    int DY {DR[1]};\n    int DZ {DR[2]};\n    int Nminus {(steps - DX - DY - DZ) / 2};\n    int Nplus {(steps - DX - DY + DZ) / 2};\n    long double walks {0};\n\n    int DR_sum {DX + DY + DZ};\n    if (DR_sum > steps or (steps - DR_sum) % 2 != 0) {\n\n        // Add entry\n        m_num_walks[walk_key] = walks;\n        return walks;\n    }\n\n    // Need some negative steps to reach a negative location\n    for (int ybar {0}; ybar != Nminus + 1; ybar++) {\n        for (int xbar {0}; xbar != Nminus + 1 - ybar; xbar++) {\n            auto f1 {factorial<long double>(steps)};\n            auto f2 {factorial<long double>(xbar)};\n            if (xbar + DX < 0) {\n                continue;\n            }\n\n            auto f3 {factorial<long double>(xbar + DX)};\n            auto f4 {factorial<long double>(ybar)};\n            if (ybar + DY < 0) {\n                continue;\n            }\n\n            auto f5 {factorial<long double>(ybar + DY)};\n            auto f6 {factorial<long double>(Nminus - xbar - ybar)};\n            if (Nplus - xbar - ybar < 0) {\n                continue;\n            }\n\n            auto f7 {factorial<long double>(Nplus - xbar - ybar)};\n            walks += f1 / (f2 * f3 * f4 * f5 * f6 * f7);\n        }\n    }\n\n    // Add entries\n    m_num_walks[walk_key] = walks;\n\n    return walks;\n}\n\nvoid IdealRandomWalks::delete_entry(\n        VectorThree start_pos,\n        VectorThree end_pos,\n        int steps) {\n\n    VectorThree DR {end_pos - start_pos};\n    DR = DR.absolute().sort();\n    pair<VectorThree, int> walk_key {DR, steps};\n    m_num_walks.erase(walk_key);\n}\n} // namespace idealRandomWalk\n", "meta": {"hexsha": "96c7d81cd3e39287dd3262feefff9bc3e3363975", "size": 2244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ideal_random_walk.cpp", "max_stars_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_stars_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T21:21:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-21T15:33:07.000Z", "max_issues_repo_path": "src/ideal_random_walk.cpp", "max_issues_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_issues_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-16T13:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T13:08:02.000Z", "max_forks_repo_path": "src/ideal_random_walk.cpp", "max_forks_repo_name": "jakublala/LatticeDNAOrigamiJakub", "max_forks_repo_head_hexsha": "efd1147deea534f1c9cd0ab22bc3c5dec89c3c52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-19T09:49:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-19T10:10:06.000Z", "avg_line_length": 26.0930232558, "max_line_length": 67, "alphanum_fraction": 0.5561497326, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5954392104364465}}
{"text": "#ifndef PERLINNOISESOURCE_HPP\n#define PERLINNOISESOURCE_HPP\n\n#include <cmath>\n\n#include <boost/multi_array.hpp>\n\n#include \"Math.hpp\"\n#include \"NoiseSource.hpp\"\n#include \"Random.hpp\"\n#include \"Vector3.hpp\"\n\n/**\n * A noise source that uses the perlin noise algorithm.\n */\ntemplate <typename T>\nclass PerlinNoiseSource : public NoiseSource<T>\n{\npublic:\n\t/**\n\t * Create a perlin noise source.\n\t *\n\t * @param size the range in each dimension that will be unique.\n\t * @param rng the random number generator to use.\n\t */\n\tPerlinNoiseSource(unsigned int size, Random& rng) :\n\t\tgradientArray(boost::extents[size][size][size]),\n\t\tsize(size)\n\t{\n\t\t//Generate random gradients\n\t\tfor( unsigned int x = 0; x < size; x++ )\n\t\t{\n\t\t\tfor( unsigned int y = 0; y < size; y++ )\n\t\t\t{\n\t\t\t\tfor( unsigned int z = 0; z < size; z++ )\n\t\t\t\t{\n\t\t\t\t\tVector3<T> gradient( normalizeReal(rng.nextReal()), normalizeReal(rng.nextReal()), normalizeReal(rng.nextReal()) );\n\t\t\t\t\tgradient.normalize();\n\t\t\t\t\tthis->gradientArray[x][y][z] = gradient;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tT noise(T x, T y = 0, T z = 0) const\n\t{\n\t\tclampDomain<T>(x, size);\n\t\tclampDomain<T>(y, size);\n\t\tclampDomain<T>(z, size);\n\n\t\t//Determine the cell that we are in\n\t\tT xi, yi, zi;\n\t\tT xf = std::modf(x, &xi);\n\t\tT yf = std::modf(y, &yi);\n\t\tT zf = std::modf(z, &zi);\n\n\t\tint a[] = {static_cast<int>(xi) % static_cast<int>(size),\n\t\t\tstatic_cast<int>(xi + 1) % static_cast<int>(size)};\n\t\tint b[] = {static_cast<int>(yi) % static_cast<int>(size),\n\t\t\tstatic_cast<int>(yi + 1) % static_cast<int>(size)};\n\t\tint c[] = {static_cast<int>(zi) % static_cast<int>(size),\n\t\t\tstatic_cast<int>(zi + 1) % static_cast<int>(size)};\n\n\t\t//Compute dot products\n\t\tT dots[2][2][2];\n\t\tfor( int i = 0; i < 2; i++ )\n\t\t{\n\t\t\tfor( int j = 0; j < 2; j++ )\n\t\t\t{\n\t\t\t\tfor( int k = 0; k < 2; k++ )\n\t\t\t\t{\n\t\t\t\t\tdots[i][j][k] = dot(this->gradientArray[a[i]][b[j]][c[k]], Vector3<T>(xf - (T)i, yf - (T)j, zf - (T)k));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//Compute fade in each dimension\n\t\tT fadeX = fade<T>(xf);\n\t\tT fadeY = fade<T>(yf);\n\t\tT fadeZ = fade<T>(zf);\n\n\t\t//Perform trilinear interpolation\n\t\tT ix1 = lerp<T>(dots[0][0][0], dots[1][0][0], fadeX);\n\t\tT ix2 = lerp<T>(dots[0][1][0], dots[1][1][0], fadeX);\n\t\tT ix3 = lerp<T>(dots[0][0][1], dots[1][0][1], fadeX);\n\t\tT ix4 = lerp<T>(dots[0][1][1], dots[1][1][1], fadeX);\n\n\t\tT iy1 = lerp<T>(ix1, ix2, fadeY);\n\t\tT iy2 = lerp<T>(ix3, ix4, fadeY);\n\n\t\treturn lerp<T>(iy1, iy2, fadeZ);\n\t}\n\nprivate:\n\tboost::multi_array<Vector3<T>, 3> gradientArray;\n\tunsigned int size;\n};\n\n#endif // PERLINNOISESOURCE_HPP\n", "meta": {"hexsha": "a9a0720c560e238e6ad42537b81eca810870d055", "size": 2512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/PerlinNoiseSource.hpp", "max_stars_repo_name": "Amaranese/mario-bros-cplusplus", "max_stars_repo_head_hexsha": "b5aefffbd3650cfa0ff5e846f43748efde8666c5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T00:37:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T00:37:29.000Z", "max_issues_repo_path": "source/PerlinNoiseSource.hpp", "max_issues_repo_name": "Amaranese/mario-bros-cplusplus", "max_issues_repo_head_hexsha": "b5aefffbd3650cfa0ff5e846f43748efde8666c5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/PerlinNoiseSource.hpp", "max_forks_repo_name": "Amaranese/mario-bros-cplusplus", "max_forks_repo_head_hexsha": "b5aefffbd3650cfa0ff5e846f43748efde8666c5", "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.12, "max_line_length": 120, "alphanum_fraction": 0.6015127389, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5954381095797979}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\ntemplate<int innodes, int outnodes>\nstruct NNLayer {\n  Eigen::Matrix<float, innodes, outnodes> w;\n  Eigen::Matrix<float, 1, outnodes> bias;\n  Eigen::Matrix<float, 1, outnodes> output;\n  bool needActivation;\n\n  NNLayer() : needActivation(true)\n    {\n      w      = Eigen::Matrix<float, innodes, outnodes>::Random(innodes, outnodes);\n      bias   = Eigen::Matrix<float, 1, outnodes>::Random(1, outnodes);\n      output = Eigen::Matrix<float, 1, outnodes>::Random(1, outnodes);\n    }\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m)\n    {\n      output = (m * w);\n      output = output - bias;\n      if (needActivation)\n        return activate();\n      else\n        return output;\n    }\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> activate()\n    {\n      Eigen::Matrix<float, 1, outnodes> o = output;\n      for(int i=0; i<output.cols(); i++)\n        {\n          o(0, i) = 1.0/(1.0 + exp(o(0, i)));\n        }\n      return o;\n    }\n\n  void setActivation(bool isneed)\n    {\n      needActivation = isneed;\n    }\n};\n\n\nclass NeuralNetwork {\n  NNLayer<2, 2> l1;\n  NNLayer<2, 2> l2;\n  NNLayer<2, 1> l3;\n\n  public:\n    NeuralNetwork()\n      {\n        l3.setActivation(false);\n      };\n\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> input)\n      {\n        return l3.forward( l2.forward( l1.forward( input ) ) );\n      };\n\n    void back_propagation()\n      {\n      };\n};\n\n\nint main(void)\n{\n  NeuralNetwork nn;\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> out;\n  Eigen::Matrix<float, 1, 2> input;\n  input << 3, 3;\n\n  out = nn.forward( input );\n\n  std::cout << \"out = \" << out << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "fad86611742c62aff995a678bdf3163b463235ba", "size": 1835, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/old/nn_1st.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/old/nn_1st.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/old/nn_1st.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": 21.8452380952, "max_line_length": 124, "alphanum_fraction": 0.591280654, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5954328437464753}}
{"text": "/*\n Copyright 2011 Mario Mulansky\n Copyright 2012-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/* strongly nonlinear hamiltonian lattice in 2d */\n\n#ifndef LATTICE2D_HPP\n#define LATTICE2D_HPP\n\n#include <vector>\n\n#include <boost/math/special_functions/pow.hpp>\n\nusing boost::math::pow;\n\ntemplate< int Kappa , int Lambda >\nstruct lattice2d {\n\n    const double m_beta;\n    std::vector< std::vector< double > > m_omega;\n\n    lattice2d( const double beta )\n        : m_beta( beta )\n    { }\n\n    template< class StateIn , class StateOut >\n    void operator()( const StateIn &q , StateOut &dpdt )\n    {\n        // q and dpdt are 2d\n        const int N = q.size();\n\n        int i;\n        for( i = 0 ; i < N ; ++i )\n        {\n            const int i_l = (i-1+N) % N;\n            const int i_r = (i+1) % N;\n            for( int j = 0 ; j < N ; ++j )\n            {\n            const int j_l = (j-1+N) % N;\n            const int j_r = (j+1) % N;\n            dpdt[i][j] = - m_omega[i][j] * pow<Kappa-1>( q[i][j] )\n                - m_beta * pow<Lambda-1>( q[i][j] - q[i][j_l] )\n                - m_beta * pow<Lambda-1>( q[i][j] - q[i][j_r] )\n                - m_beta * pow<Lambda-1>( q[i][j] - q[i_l][j] )\n                - m_beta * pow<Lambda-1>( q[i][j] - q[i_r][j] );\n            }\n        }\n    }\n\n    template< class StateIn >\n    double energy( const StateIn &q , const StateIn &p )\n    {\n        // q and dpdt are 2d\n        const int N = q.size();\n        double energy = 0.0;\n        int i;\n        for( i = 0 ; i < N ; ++i )\n        {\n            const int i_l = (i-1+N) % N;\n            const int i_r = (i+1) % N;\n            for( int j = 0 ; j < N ; ++j )\n            {\n            const int j_l = (j-1+N) % N;\n            const int j_r = (j+1) % N;\n            energy += p[i][j]*p[i][j] / 2.0\n                        + m_omega[i][j] * pow<Kappa>( q[i][j] ) / Kappa\n                + m_beta * pow<Lambda>( q[i][j] - q[i][j_l] ) / Lambda / 2\n                + m_beta * pow<Lambda>( q[i][j] - q[i][j_r] ) / Lambda / 2\n                + m_beta * pow<Lambda>( q[i][j] - q[i_l][j] ) / Lambda / 2\n                + m_beta * pow<Lambda>( q[i][j] - q[i_r][j] ) / Lambda / 2;\n            }\n        }\n        return energy;\n    }\n\n\n    template< class StateIn , class StateOut >\n    double local_energy( const StateIn &q , const StateIn &p , StateOut &energy )\n    {\n        // q and dpdt are 2d\n        const int N = q.size();\n        double e = 0.0;\n        int i;\n        for( i = 0 ; i < N ; ++i )\n        {\n            const int i_l = (i-1+N) % N;\n            const int i_r = (i+1) % N;\n            for( int j = 0 ; j < N ; ++j )\n            {\n                const int j_l = (j-1+N) % N;\n                const int j_r = (j+1) % N;\n                energy[i][j] = p[i][j]*p[i][j] / 2.0\n                    + m_omega[i][j] * pow<Kappa>( q[i][j] ) / Kappa\n                    + m_beta * pow<Lambda>( q[i][j] - q[i][j_l] ) / Lambda / 2\n                    + m_beta * pow<Lambda>( q[i][j] - q[i][j_r] ) / Lambda / 2\n                    + m_beta * pow<Lambda>( q[i][j] - q[i_l][j] ) / Lambda / 2\n                    + m_beta * pow<Lambda>( q[i][j] - q[i_r][j] ) / Lambda / 2;\n                e += energy[i][j];\n            }\n        }\n        //rescale\n        e = 1.0/e;\n        for( i = 0 ; i < N ; ++i )\n            for( int j = 0 ; j < N ; ++j )\n                energy[i][j] *= e;\n        return 1.0/e;\n    }\n\n    void load_pot( const char* filename , const double W , const double gap , \n                   const size_t dim )\n    {\n        std::ifstream in( filename , std::ios::in | std::ios::binary );\n        if( !in.is_open() ) {\n            std::cerr << \"pot file not found: \" << filename << std::endl;\n            exit(0);\n        } else {\n            std::cout << \"using pot file: \" << filename << std::endl;\n        }\n\n        m_omega.resize( dim );\n        for( int i = 0 ; i < dim ; ++i )\n        {\n            m_omega[i].resize( dim );\n            for( size_t j = 0 ; j < dim ; ++j )\n            {\n                if( !in.good() )\n                {\n                    std::cerr << \"I/O Error: \" << filename << std::endl;\n                    exit(0);\n                }\n                double d;\n                in.read( (char*) &d , sizeof(d) );\n                if( (d < 0) || (d > 1.0) )\n                {\n                    std::cerr << \"ERROR: \" << d << std::endl;\n                    exit(0);\n                }\n                m_omega[i][j] = W*d + gap;\n            }\n        }\n\n    }\n\n    void generate_pot( const double W , const double gap , const size_t dim )\n    {\n        m_omega.resize( dim );\n        for( size_t i = 0 ; i < dim ; ++i )\n        {\n            m_omega[i].resize( dim );\n            for( size_t j = 0 ; j < dim ; ++j )\n            {\n                m_omega[i][j] = W*static_cast<double>(rand())/RAND_MAX + gap;\n            }\n        }\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "4fd9c985e3707b4b984334639cc83d9fdc7511c3", "size": 5016, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/2d_lattice/lattice2d.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": "libs/numeric/odeint/examples/2d_lattice/lattice2d.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": "libs/numeric/odeint/examples/2d_lattice/lattice2d.hpp", "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": 30.2168674699, "max_line_length": 81, "alphanum_fraction": 0.4114832536, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5954023686073207}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <vector>\n#include \"rbf.hpp\"\n\nusing namespace arma;\nusing namespace std;\n\nconst double LAMBDA = 0.01;\n\nint main() {\n    FILE *input = fopen(\"../../Spectra100.csv\", \"r\");\n\n    vector<double> xs, ys;\n    double a, b;\n    while ( fscanf(input, \"%lF,%lF\", &a, &b) != EOF ) {\n        xs.push_back(a), ys.push_back(b);\n    }\n    fclose(input);\n\n    rbf my_rbf(xs, ys, LAMBDA);\n\n    vector<double> all_xs;\n    for ( double i = 0; i <= 5; i += 0.01 )\n        all_xs.push_back(i);\n\n    vector<double> fxs = my_rbf.test(all_xs);\n\n    int n = fxs.size();\n    for (int i = 0; i < n; ++i) {\n        printf(\"%lF,%lF\\n\", all_xs[i], fxs[i]);\n    }\n\n    return 0;\n}", "meta": {"hexsha": "4ad448611e5935133f63d39ab58c50c144efb0ee", "size": 697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RBF/src/main.cpp", "max_stars_repo_name": "jesuswr/RBF", "max_stars_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RBF/src/main.cpp", "max_issues_repo_name": "jesuswr/RBF", "max_issues_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RBF/src/main.cpp", "max_forks_repo_name": "jesuswr/RBF", "max_forks_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9142857143, "max_line_length": 55, "alphanum_fraction": 0.5494978479, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5954023611397401}}
{"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#include \"JordanSolver.h\"\n#include \"MatrixToString.h\"\n#include <Eigen/Eigenvalues>\n\nnamespace abstract{\n\ntemplate <class scalar>\ntypename JordanSolver<scalar>::complexType JordanSolver<scalar>::ms_complexOne(1,0);\n\ntemplate <class scalar>\nMatToStr<scalar> JordanSolver<scalar>::ms_logger(true);\n\ntemplate <class scalar>\nMatToStr<scalar> JordanSolver<scalar>::ms_decoder(false);\n\ntemplate <class scalar>\ntraceDynamics_t JordanSolver<scalar>::ms_trace_dynamics=eTraceNoDynamics;\n\n/// Constructs an empty matrix\ntemplate <class scalar>\nJordanSolver<scalar>::JordanSolver(const int dimension) :\n    m_dimension(dimension),\n    m_zero(func::ms_weakZero),\n    m_largeZero(dimension*dimension*func::ms_weakZero),\n    m_dynamics(dimension,dimension)\n{\n}\n\n/// Changes the default dimension of the system\ntemplate <class scalar>\nvoid JordanSolver<scalar>::changeDimensions(const int dimension)\n{\n  if (dimension!=m_dimension) {\n    m_dimension=dimension;\n    m_dynamics.resize(dimension,dimension);\n  }\n}\n\ntemplate <class scalar>\nvoid JordanSolver<scalar>::computeJordan(const MatrixType &matrix)\n{\n  this->setMaxIterations(1000);\n  changeDimensions(matrix.rows());\n  m_dynamics=matrix;\n  calculateJordanForm();\n}\n\n/// Transforms the matrix to Row Echelon Form\ntemplate <class scalar>\nint JordanSolver<scalar>::toREF(ComplexMatrixType &matrix)\n{\n  int rank=m_dimension;\n  int col=0;\n  for (int row=0;col<matrix.rows();row++,col++) {\n    while (func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) {\n      for (int row2=row+1;row2<matrix.rows();row2++) {\n        if (!func::isZero(func::norm2(matrix.coeff(row2,col)),m_zero)) {\n          matrix.row(row)+=matrix.row(row2);\n          break;\n        }\n      }\n      if (func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) {\n        col++;\n        if (col==matrix.rows()) break;\n      }\n    }\n    if (col==matrix.rows()) break;\n    complexType multiplier=matrix.coeff(row,col);\n    if (!func::isZero(func::norm2(multiplier),m_zero)) {\n      matrix.row(row)/=multiplier;\n      rank--;\n    }\n    for (int row2=row+1;row2<matrix.rows();row2++) {\n      complexType multiplier=matrix.coeff(row2,col);\n      matrix.row(row2)-=multiplier*matrix.row(row);\n    }\n  }\n  if (ms_trace_dynamics>=eTraceREF) ms_logger.logData(matrix,\"REF:\");\n  return rank;\n}\n\n/// Transforms the matrix to Row Echelon Form\ntemplate <class scalar>\nint JordanSolver<scalar>::toRREF(ComplexMatrixType &matrix)\n{\n  int rank=toREF(matrix);\n  int col=0;\n  for (int row=1;(row<matrix.rows()) && (col<matrix.cols());row++) {\n    while ((col<matrix.cols()) && func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) col++;\n    if (col<matrix.cols()) {\n      for (int row2=0;row2<row;row2++) {\n        if (!func::isZero(func::norm2(matrix.coeff(row2,col)),m_zero)) {\n          complexType multiplier=matrix.coeff(row2,col);\n          matrix.row(row2)-=multiplier*matrix.row(row);\n        }\n      }\n    }\n  }\n  if (ms_trace_dynamics>=eTraceREF) ms_logger.logData(matrix,\"RREF:\");\n  return rank;\n}\n\n/// Checks if the given row pair belongs to the same jordan block\ntemplate <class scalar>\nbool JordanSolver<scalar>::isJordanBlock(const int row1,const int row2)\n{\n  if (func::norm2(m_eigenValues.coeff(row1,row1)-m_eigenValues.coeff(row2,row2))>m_largeZero) return false;\n  if (m_conjugatePair[row1]>=0) {\n    MatrixType dotReal=m_eigenVectors.row(row1).real().transpose()*m_eigenVectors.row(row2).real();\n    MatrixType dotImag=m_eigenVectors.row(row1).imag().transpose()*m_eigenVectors.row(row2).imag();\n    scalar vNorm1real=m_eigenVectors.row(row1).real().norm();\n    scalar vNorm2real=m_eigenVectors.row(row2).real().norm();\n    scalar vNorm1imag=m_eigenVectors.row(row1).imag().norm();\n    scalar vNorm2imag=m_eigenVectors.row(row2).imag().norm();\n    scalar realAngle=func::norm2(dotReal.coeff(0,0))/(vNorm1real*vNorm2real);\n    scalar imagAngle=func::norm2(dotImag.coeff(0,0))/(vNorm1imag*vNorm2imag);\n    realAngle=acos(realAngle);\n    imagAngle=acos(imagAngle);\n    return func::isZero(func::toUpper(realAngle),0.01/*m_zero*/) && func::isZero(func::toUpper(imagAngle),0.01/*m_zero*/);\n  }\n  else {\n    ComplexMatrixType dotProd=m_eigenVectors.row(row1).transpose()*m_eigenVectors.row(row2);\n    scalar vNorm1=m_eigenVectors.row(row1).norm();\n    scalar vNorm2=m_eigenVectors.row(row2).norm();\n    scalar angle=func::norm2(dotProd.coeff(0,0))/(vNorm1*vNorm2);\n    angle=acos(angle);\n    return func::isZero(func::toUpper(angle),0.01/*m_zero*/);\n  }\n  return false;\n}\n\n/// Calculates the Jordan block and generalised eigenvector for the row pair\ntemplate <class scalar> bool JordanSolver<scalar>::makeJordanBlock(const int row1,const int row2)\n{\n  scalar radius=func::norm2(m_eigenValues.coeff(row1,row1)-m_eigenValues.coeff(row2,row2));\n  if (!func::isZero(radius)) return false;\n  m_hasMultiplicities=true;\n  ComplexMatrixType matrixBase=ComplexMatrixType::Zero(m_dimension,m_dimension);\n  matrixBase.real()=m_dynamics;\n  for (int i=0;i<m_dimension;i++) {\n    matrixBase.coeffRef(i,i)-=m_eigenValues.coeff(row1,row1);\n  }\n  ComplexMatrixType matrix=matrixBase;\n  int order=1;\n  int rank=toREF(matrix);\n  if (rank==0) return false;\n  if (rank==m_dimension) return false;\n  m_jordanIndex[row1]=m_jordanIndex[row2]+1;\n  while (rank<=m_jordanIndex[row1]) {\n    order++;\n    matrix=matrixBase;\n    for (int i=1;i<order;i++) matrix*=matrixBase;\n    rank=toREF(matrix);\n  }\n\n  int row=m_dimension-rank-1;\n  if (row<0) row=0;//TODO: What happens when rank is m_dim? Is this right?\n  int col=row;\n  while ((col<m_dimension) && (func::isZero(func::norm2(matrix.coeff(row,col)),m_zero))) col++;\n  if (++col>=m_dimension) col=m_dimension-1;//TODO: check for col out of range and 0 coeffs (is this right?)\n  ComplexMatrixType vector=ComplexMatrixType::Zero(m_dimension,1);\n  vector.coeffRef(col,0)=1;\n\n  while (row>=0) {\n    vector.coeffRef(row,0)=-(matrix.row(row)*vector).sum();\n    row--;\n  }\n  for (int i=1;i<rank-m_jordanIndex[row1];i++) vector=matrixBase*vector;\n  refScalar vectorNorm=func::toUpper(vector.norm());\n  refScalar vectorEpsilon=vectorNorm*func::ms_weakEpsilon*func::ms_weakEpsilon;\n  for (int i=0;i<vector.rows();i++) {\n    if (func::norm2(vector.coeff(i,0))<vectorEpsilon) vector.coeffRef(i,0)=0;\n  }\n  vector/=scalar(vectorNorm);\n  m_eigenVectors.col(row1)=vector;\n  m_eigenValues.coeffRef(row2,row1)=ms_complexOne;\n\n  if (m_conjugatePair[row1]>=0) {\n    m_eigenValues.coeffRef(row2+1,row1+1)=ms_complexOne;\n    for (int row=0;row<m_dimension;row++) m_eigenVectors.coeffRef(row,row1+1)=conj(vector.coeff(row,0));\n  }\n  for (int i=1;i<=m_jordanIndex[row1];i++) {\n    vector=matrixBase*vector;\n    if (m_conjugatePair[row1]>=0) {\n      m_eigenVectors.col(row1-2*i)=vector;\n      for (int row=0;row<m_dimension;row++) m_eigenVectors.coeffRef(row,row1-2*i+1)=conj(vector.coeff(row,0));\n    }\n    else {\n      m_eigenVectors.col(row1-i)=vector;\n    }\n  }\n\n  if (ms_trace_dynamics>=eTraceREF) {\n    ms_logger.logData(m_eigenVectors,\"Intermediate EigenVectors:\");\n    matrix=matrixBase;\n    for (int i=1;i<=m_jordanIndex[row1];i++) matrix*=matrixBase;\n    ms_logger.logData(matrix,\"Matrix Base:\");\n    ComplexMatrixType nullSpace=getNullSpace(matrix);\n    ms_logger.logData(nullSpace,\"nullSpace:\");\n  }\n  return true;\n}\n\n/// calculates the estimated roundoff error of a matrix operation\ntemplate <class scalar>\ninline typename JordanSolver<scalar>::refScalar JordanSolver<scalar>::calculateEpsilon(const MatrixType &matrix)\n{\n  if (matrix.rows()>0) {\n    refScalar max=func::toUpper(func::norm2(matrix.coeff(0,0)));\n    refScalar min=func::toLower(func::norm2(matrix.coeff(0,0)));\n    for (int row=0;row<matrix.rows();row++) {\n      for (int col=0;col<matrix.cols();col++) {\n        refScalar upper=func::toUpper(func::norm2(matrix.coeff(row,col)));\n        refScalar lower=func::toLower(func::norm2(matrix.coeff(row,col)));\n        if (upper>max) max=upper;\n        if (lower<min) min=lower;\n      }\n    }\n    //scalar max=matrix.maxCoeff();\n    //scalar min=matrix.minCoeff();\n    if (-min>max) max=-min;\n    return max*func::ms_weakEpsilon;\n  }\n  return 0;\n}\n\n/// calculates the estimated roundoff error of a matrix operation\ntemplate <class scalar>\ninline typename JordanSolver<scalar>::refScalar JordanSolver<scalar>::calculateEpsilon(const ComplexMatrixType &matrix)\n{\n  if (matrix.rows()>0) {\n    refScalar max=func::toUpper(func::norm2(matrix.coeff(0,0)));\n    refScalar min=func::toLower(func::norm2(matrix.coeff(0,0)));\n    for (int row=0;row<matrix.rows();row++) {\n      for (int col=0;col<matrix.cols();col++) {\n        refScalar upper=func::toUpper(func::norm2(matrix.coeff(row,col)));\n        refScalar lower=func::toLower(func::norm2(matrix.coeff(row,col)));\n        if (upper>max) max=upper;\n        if (lower<min) min=lower;\n      }\n    }\n    //scalar max=matrix.maxCoeff();\n    //scalar min=matrix.minCoeff();\n    if (-min>max) max=-min;\n    return max*func::ms_weakEpsilon;\n  }\n  return 0;\n}\n\n\n/// Loads the transformation matrix for the state space\ntemplate <class scalar>\nbool JordanSolver<scalar>::calculateJordanForm()\n{\n    m_zero=calculateEpsilon(m_dynamics);\n    m_inverse.conservativeResize(0,0);\n    m_largeZero=m_zero*m_dimension*m_dimension;\n    this->setMaxIterations(1000);\n    this->compute(m_dynamics);\n\n    if (this->info()!=Eigen::Success) return false;\n    m_eigenValues=this->eigenvalues().asDiagonal();\n    m_eigenVectors=this->eigenvectors();\n\n    if (ms_trace_dynamics>=eTraceAll) {\n      ms_logger.logData(m_dynamics,\"Dynamics:\");\n      ms_logger.logData(m_eigenValues,\"EigenValues:\");\n      ms_logger.logData(m_eigenVectors,\"Initial EigenVectors:\");\n    }\n    m_hasOnes=false;\n    m_hasZeros=false;\n    m_hasMultiplicities=false;\n    m_isOne.resize(2*m_dimension);\n    m_conjugatePair.resize(2*m_dimension);\n    m_jordanIndex.resize(2*m_dimension);\n    for (int i=0;i<m_dimension;i++) {\n      if (func::isZero(func::norm2(m_eigenValues.coeff(i,i)))) m_hasZeros=true;\n    }\n    for (int i=0;i<m_dimension;i++) {\n      m_conjugatePair[i]=-1;\n      m_jordanIndex[i]=0;\n      m_isOne[i]=false;\n      if ((i<(m_dimension-1)) && !func::isZero(m_eigenValues.coeff(i,i).imag(),m_zero)) {\n        m_conjugatePair[i]=i+1;\n        if (i>=2) makeJordanBlock(i,i-2);\n        m_jordanIndex[i+1]=m_jordanIndex[i];\n        m_conjugatePair[i+1]=i;\n        i++;\n      }\n      else {\n        m_isOne[i]=func::isZero(func::norm2(m_eigenValues.coeff(i,i)-ms_complexOne),m_zero);\n        m_hasOnes|=m_isOne[i];\n        if (i>0) makeJordanBlock(i,i-1);\n      }\n    }\n    refScalar eigenVectorEpsilon=calculateEpsilon(m_eigenVectors);\n    for (int row=0;row<m_eigenVectors.rows();row++) {\n      for (int col=0;col<m_eigenVectors.cols();col++) {\n        if (func::norm2(m_eigenVectors.coeff(row,col))<eigenVectorEpsilon) m_eigenVectors.coeffRef(row,col)=func::ms_hardZero;\n      }\n    }\n\n    for (int i=m_dimension;i<2*m_dimension;i++) {\n      m_conjugatePair[i]=-1;\n      m_jordanIndex[i]=0;\n      m_isOne[i]=m_isOne[i-m_dimension];\n    }\n    if (ms_trace_dynamics>=eTraceDynamics) ms_logger.logData(m_eigenVectors,\"Generalised EigenVectors:\");\n    return true;\n}\n\n/// Returns the nullSpace vectors of M\ntemplate<class scalar>\ntypename JordanSolver<scalar>::ComplexMatrixType JordanSolver<scalar>::getNullSpace(const ComplexMatrixType &matrixBase,bool normalized)\n{\n  ComplexMatrixType result;\n  ComplexMatrixType nullSpace=matrixBase;\n  toRREF(nullSpace);\n  std::vector<bool> vars(nullSpace.cols());\n  int row=0;\n  int freeVars=nullSpace.cols();\n  for (int col=0;col<nullSpace.cols();col++) {\n    vars[col]=true;\n    if (!func::isZero(norm(nullSpace.coeff(row,col)))) {\n      vars[col]=false;\n      row++;\n      freeVars--;\n    }\n  }\n  result.resize(m_dimension,freeVars);\n  int col=0;\n  for (int j=0;j<nullSpace.cols();j++) {\n    if (vars[j]) {\n      result.row(j)=ComplexMatrixType::Zero(1,freeVars);\n      result.coeffRef(j,col)=func::ms_c_1;\n    }\n    else {\n      int pos=0;\n      for (int k=0;k<nullSpace.cols();k++) {\n        if (vars[k]) result.coeffRef(j,pos++)=-nullSpace.coeff(j,k);\n      }\n    }\n  }\n  if (normalized) {\n    for (int col=0;col<result.cols();col++) {\n      scalar scale=result.col(col).norm();\n      result.col(col)/=scale;\n    }\n  }\n  return result;\n}\n\n#ifdef USE_LDOUBLE\n  template class JordanSolver<long double>;\n#endif\n#ifdef USE_MPREAL\n  template class JordanSolver<mpfr::mpreal>;\n#endif\n}\n", "meta": {"hexsha": "9231e6233f5db246f76a25377b65a72e4488fb9d", "size": 12558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/JordanSolver.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/JordanSolver.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/JordanSolver.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": 34.4054794521, "max_line_length": 136, "alphanum_fraction": 0.6861761427, "num_tokens": 3554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5954023570695557}}
{"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 iterative-eigen.cpp\n*\n*   The following tutorial shows how to use the iterative solvers in ViennaCL with objects from the <a href=\"http://eigen.tuxfamily.org/\">Eigen Library</a> directly.\n*\n*   \\note Eigen provides its own iterative solvers in the meanwhile. Check these first.\n*\n*   We begin with including the necessary headers:\n**/\n\n// System headers\n#include <iostream>\n\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n\n// Eigen headers\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Eigen objects\n#define VIENNACL_WITH_EIGEN 1\n\n// ViennaCL headers\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\n// Some helper functions for this tutorial:\n#include \"vector-io.hpp\"\n\n/**\n*  In the following we run the CG method, the BiCGStab method, and the GMRES method with Eigen types directly.\n*  First, the matrices are set up, then the respective solvers are called.\n**/\nint main(int, char *[])\n{\n  typedef float ScalarType;\n\n  Eigen::SparseMatrix<ScalarType, Eigen::RowMajor> eigen_matrix(65025, 65025);\n  Eigen::VectorXf eigen_rhs;\n  Eigen::VectorXf eigen_result;\n  Eigen::VectorXf ref_result;\n  Eigen::VectorXf residual;\n\n  /**\n  * Read system from file\n  **/\n  std::cout << \"Reading matrix (this might take some time)...\" << std::endl;\n  eigen_matrix.reserve(65025 * 7);\n  if (!viennacl::io::read_matrix_market_file(eigen_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file. Make sure you run from the build/-folder.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  //eigen_matrix.endFill();\n  std::cout << \"Done: reading matrix\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", eigen_rhs))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ref_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /**\n  *  Conjugate Gradient (CG) solver:\n  **/\n  std::cout << \"----- Running CG -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::cg_tag());\n\n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\n\n  /**\n  *  Stabilized Bi-Conjugate Gradient (BiCGStab) solver:\n  **/\n  std::cout << \"----- Running BiCGStab -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::bicgstab_tag());\n\n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\n\n  /**\n  *  Generalized Minimum Residual (GMRES) solver:\n  **/\n  std::cout << \"----- Running GMRES -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::gmres_tag());\n\n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\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": "908c53ece9cb8e3805caab8e2bbbeb3d3b9bf5b9", "size": 4302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative-eigen.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/iterative-eigen.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/iterative-eigen.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": 33.874015748, "max_line_length": 165, "alphanum_fraction": 0.6383077638, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5953874565807425}}
{"text": "#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <ctime>\n\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/xfeatures2d/nonfree.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <g2o/types/slam3d/types_slam3d.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/factory.h>\n#include <g2o/core/optimization_algorithm_factory.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/core/robust_kernel_factory.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include<g2o/solvers/dense/linear_solver_dense.h>\n\nusing namespace std;\nusing namespace cv;\n\n// camera intrinsic parameters\n#define _FX (7.215377000000e+02)\n#define _FY (7.215377000000e+02)\n#define _CX (6.095593000000e+02)\n#define _CY (1.728540000000e+02)\n#define _BASELINE (5.40e+02) //54cm\n#define _SCALE (10)\n\n//params\n#define _LAST_FRAME_NUM (4)\n#define _GOOD_MATCH_PARAM (50)\n#define _MIN_GOOD_MATCHES (30)\n#define _GOOD_MATCHES_NUM (500)\n#define _GRID_SIZE (0.2)\n#define _MIN_INLIERS (5)\n\n//data\n#define _IMAGE_NUM (801)\n#define _LEFT (0)\n#define _RIGHT (1)\n\n//switch\n#define _WRITE_KEYPOINTS_IMAGE (false)\n#define _WRITE_MATCH_IMAGE (false)\n#define _WRITE_DISP (false)\n#define _WRITE_DEPTH (false)\n#define _WRITE_INLIER (false)\n#define _WRITE_RESULT (true)\n#define _SHOW_PATH (true)\n#define _SHOW_CLOUD (false)\n\n// typedef pcl::PointXYZRGBA PointT;\n// typedef pcl::PointCloud<PointT> PointCloud;\n\nstruct PnP_result\n{\n    Mat R, t;\n    int inliers;\n};\nstruct frame\n{\n    int id;\n    bool valid = true;\n    Mat src[2];\n    Mat depth;\n    Mat desp[2];\n    vector<KeyPoint> kp[2];\n    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n    Mat pose = Mat::eye(4,4,CV_64F);\n    Mat R = Mat::eye(3,3,CV_64F);\n    Mat t; \n};\nstruct FeaturePoint{\n  cv::Point2f  point;\n  int id;\n  int age;\n};\nstruct FeatureSet {\n    std::vector<cv::Point2f>  points;\n    std::vector<int>  ages;\n    int size(){\n        return points.size();\n    }\n    void clear(){\n        points.clear();\n        ages.clear();\n    }\n };\nclass Bucket\n{\n\npublic:\n    int id;\n    int max_size;\n\n    FeatureSet features;\n\n    Bucket(int);\n\n    void add_feature(cv::Point2f, int);\n    void get_features(FeatureSet&);\n\n    int size();\n    \n};\n\nBucket::Bucket(int size){\n    max_size = size;\n}\n\nint Bucket::size(){\n    return features.points.size();\n}\n\nvoid Bucket::add_feature(cv::Point2f point, int age){\n    // won't add feature with age > 10;\n    int age_threshold = 10;\n    if (age < age_threshold)\n    {\n        // insert any feature before bucket is full\n        if (size()<max_size)\n        {\n            features.points.push_back(point);\n            features.ages.push_back(age);\n\n        }\n        else\n        // insert feature with old age and remove youngest one\n        {\n            int age_min = features.ages[0];\n            int age_min_idx = 0;\n\n            for (int i = 0; i < size(); i++)\n            {\n                if (age < age_min)\n                {\n                    age_min = age;\n                    age_min_idx = i;\n                }\n            }\n            features.points[age_min_idx] = point;\n            features.ages[age_min_idx] = age;\n        }\n    }\n\n}\n\nvoid Bucket::get_features(FeatureSet& current_features){\n\n    current_features.points.insert(current_features.points.end(), features.points.begin(), features.points.end());\n    current_features.ages.insert(current_features.ages.end(), features.ages.begin(), features.ages.end());\n}\n\nclass My_VO\n{\npublic:\n    vector<vector<string>> addData();\n    PnP_result featureDetectAndSolvePnP(int idx, struct frame& l_frame, struct frame& r_frame);\n    void stereoSGBM(Mat lpng, Mat rpng, Mat&disp);\n    void disp2Depth(Mat disp, Mat& depth);\n    Point3f from2dTo3d(const Point3f& point);\n    void PnPRes2Eigen(frame& curr_frame, PnP_result& res);\n    void run(int start_idx, int end_idx );\n    void run_multiframe(int start_idx, int end_idx);\n    frame getFrame(const int& idx, bool detect = true);\n    struct PnP_result estimateMotion(int idx, frame& last_frame, frame& curr_frame);\n    void integrateOdom(frame& curr_frame);\n    void integrateOdom(frame& last_frame, frame& curr_frame);\n    void display(frame& frame);\n    void getMeanPose(vector<frame> frame_list, frame& frame);\n    void outputData(frame& frame);\n    void run_soft(int start_idx, int end_idx);\n    void matchingFeatures(cv::Mat& imageLeft_t0, cv::Mat& imageRight_t0,\n                      cv::Mat& imageLeft_t1, cv::Mat& imageRight_t1, \n                      FeatureSet& currentVOFeatures,\n                      std::vector<cv::Point2f>&  pointsLeft_t0, \n                      std::vector<cv::Point2f>&  pointsRight_t0, \n                      std::vector<cv::Point2f>&  pointsLeft_t1, \n                      std::vector<cv::Point2f>&  pointsRight_t1);\n    void appendNewFeatures(cv::Mat& image, FeatureSet& current_features);\n    void featureDetectionFast(cv::Mat image, std::vector<cv::Point2f>& points);\n    void bucketingFeatures(cv::Mat& image, FeatureSet& current_features, int bucket_size, int features_per_bucket);\n    void circularMatching(cv::Mat img_l_0, cv::Mat img_r_0, cv::Mat img_l_1, cv::Mat img_r_1,\n                      std::vector<cv::Point2f>& points_l_0, std::vector<cv::Point2f>& points_r_0,\n                      std::vector<cv::Point2f>& points_l_1, std::vector<cv::Point2f>& points_r_1,\n                      std::vector<cv::Point2f>& points_l_0_return,\n                      FeatureSet& current_features);\n    void deleteUnmatchFeaturesCircle(std::vector<cv::Point2f>& points0, std::vector<cv::Point2f>& points1,\n                          std::vector<cv::Point2f>& points2, std::vector<cv::Point2f>& points3,\n                          std::vector<cv::Point2f>& points0_return,\n                          std::vector<uchar>& status0, std::vector<uchar>& status1,\n                          std::vector<uchar>& status2, std::vector<uchar>& status3,\n                          std::vector<int>& ages);\n    void checkValidMatch(std::vector<cv::Point2f>& points, std::vector<cv::Point2f>& points_return, std::vector<bool>& status, int threshold);\n    void removeInvalidPoints(std::vector<cv::Point2f>& points, const std::vector<bool>& status);\n    void trackingFrame2Frame(cv::Mat& projMatrl, cv::Mat& projMatrr,\n                         std::vector<cv::Point2f>&  pointsLeft_t0,\n                         std::vector<cv::Point2f>&  pointsLeft_t1, \n                         cv::Mat& points3D_t0,\n                         cv::Mat& rotation,\n                         cv::Mat& translation,\n                         bool mono_rotation);\n    void displayTracking(cv::Mat& imageLeft_t1, \n                     std::vector<cv::Point2f>&  pointsLeft_t0,\n                     std::vector<cv::Point2f>&  pointsLeft_t1);\n    cv::Vec3f rotationMatrixToEulerAngles(cv::Mat &R);\n    void integrateOdometryStereo(int frame_i, cv::Mat& rigid_body_transformation, cv::Mat& frame_pose, const cv::Mat& rotation, const cv::Mat& translation_stereo);\n    void display(int frame_id, cv::Mat& trajectory, cv::Mat& pose);\n    \n    struct CAMERA_INTRINSIC_PARAMETERS\n    {\n        double fx = _FX;\n        double fy = _FY;\n        double cx = _CX;\n        double cy = _CY;\n        double baseline = _BASELINE;\n        double scale = _SCALE;\n    };\n\nprivate:\n    Mat path= cv::Mat::zeros(600, 1200, CV_8UC3);\n    Mat pose = Mat::eye(4,4,CV_64F);\n    vector<vector<string>> image_list;\n    struct CAMERA_INTRINSIC_PARAMETERS camera_parameters;\n    Mat l_matrix = (cv::Mat_<float>(3, 4) << camera_parameters.fx, 0., camera_parameters.cx, 0., \n                                                                                    0., camera_parameters.fy, camera_parameters.cy, 0., \n                                                                                    0,  0., 1., 0.);\n    Mat r_matrix = (cv::Mat_<float>(3, 4) << camera_parameters.fx, 0., camera_parameters.cx, -386.1448, \n                                                                                    0., camera_parameters.fy, camera_parameters.cy, 0., \n                                                                                    0,  0., 1., 0.);\n    ofstream outputfile;\n};\n\nint main(int argc, char** argv)\n{\n    int start = 0; \n    int end = _IMAGE_NUM;\n    My_VO my_vo = My_VO();       \n    if(argc == 4)\n    {\n        start = atoi(argv[2]);\n        end = atoi(argv[3]);\n    }\n    if(argc == 1||(argc>1&&(string(argv[1])==\"single\")))\n    {\n        my_vo.run(start,end);\n    }\n    else if(argc > 1&&(string(argv[1]) == \"multi\"))\n    {\n        my_vo.run_multiframe(start, end);\n    }\n    else if(argc > 1&&(string(argv[1]) == \"soft\"))\n    {\n        my_vo.run_soft(start, end);\n    }\n    waitKey(0);\n    return 0;\n}\n\nvoid My_VO::run_soft(int start_idx, int end_idx)\n{\n    addData();\n    if(_WRITE_RESULT)\n    {\n        outputfile.open(\"../data/result/pose_soft.txt\");\n        if(!outputfile.is_open())\n        {\n            cout<<\"txt open error...\"<<endl;\n        }\n    }\n\n    int curr_idx = start_idx;\n    frame last_frame = getFrame(curr_idx);\n    outputData(last_frame);\n\n    vector<FeaturePoint> oldFeaturePointsLeft;\n    vector<FeaturePoint> currFeaturePointsLeft;\n    FeatureSet currentVOFeatures;\n    cv::Mat frame_pose = cv::Mat::eye(4, 4, CV_64F);\n    cv::Mat trajectory = cv::Mat::zeros(600, 1200, CV_8UC3);\n\n    // 每个优化变量维度为3，误差值维度为1\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); \n    \n    Block* solver_ptr  = new Block( std::unique_ptr<Block::LinearSolverType>(linearSolver) );\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr<Block>(solver_ptr));\n\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(false);\n\n    g2o::VertexSE3* v = new g2o::VertexSE3();\n    v->setId(curr_idx);\n    v->setEstimate(Eigen::Isometry3d::Identity());\n    v->setFixed(true);\n    optimizer.addVertex(v);\n\n    int last_idx = curr_idx;\n\n    for(curr_idx = start_idx+1; curr_idx<end_idx;curr_idx++)\n    {\n        cout<<endl<<\"-------\"<<curr_idx<<\"-------\"<<endl;\n        frame curr_frame = getFrame(curr_idx);\n\n        vector<Point2f> oldPointsLeft_t0 = currentVOFeatures.points;\n        std::vector<cv::Point2f> pointsLeft_t0, pointsRight_t0, pointsLeft_t1, pointsRight_t1;  \n        matchingFeatures( last_frame.src[_LEFT], last_frame.src[_RIGHT],\n                          curr_frame.src[_LEFT], curr_frame.src[_RIGHT],\n                          currentVOFeatures,\n                          pointsLeft_t0, \n                          pointsRight_t0, \n                          pointsLeft_t1, \n                          pointsRight_t1);  \n        std::vector<cv::Point2f>& currentPointsLeft_t0 = pointsLeft_t0;\n        std::vector<cv::Point2f>& currentPointsLeft_t1 = pointsLeft_t1;\n        std::vector<cv::Point2f> newPoints;\n        std::vector<bool> valid; // valid new points are ture\n\n        cv::Mat points3D_t0, points4D_t0;\n        cv::triangulatePoints( l_matrix,  r_matrix,  pointsLeft_t0,  pointsRight_t0,  points4D_t0);\n        cv::convertPointsFromHomogeneous(points4D_t0.t(), points3D_t0);\n        cv::Mat rotation = cv::Mat::eye(3, 3, CV_64F);\n        cv::Mat translation = cv::Mat::zeros(3, 1, CV_64F);\n        trackingFrame2Frame(l_matrix, r_matrix, pointsLeft_t0, pointsLeft_t1, points3D_t0, rotation, translation, false);\n        displayTracking(curr_frame.src[_LEFT], pointsLeft_t0, pointsLeft_t1);\n        cv::Vec3f rotation_euler = rotationMatrixToEulerAngles(rotation);\n        cv::Mat rigid_body_transformation;\n\n        if(abs(rotation_euler[1])<0.1 && abs(rotation_euler[0])<0.1 && abs(rotation_euler[2])<0.1)\n        {\n            integrateOdometryStereo(curr_idx, rigid_body_transformation, frame_pose, rotation, translation);\n        } else {\n            std::cout << \"Too large rotation\"  << std::endl;\n        }\n        cv::Mat xyz = frame_pose.col(3).clone();\n        curr_frame.pose = frame_pose;\n        display(curr_idx, trajectory, xyz);\n        outputData(curr_frame);\n\n        g2o::VertexSE3* v = new g2o::VertexSE3();\n        //顶点\n        v->setId(curr_idx);\n        v->setEstimate(Eigen::Isometry3d::Identity());\n        optimizer.addVertex(v);\n        //边\n        g2o::EdgeSE3* edge = new g2o::EdgeSE3();\n        edge->vertices()[0] = optimizer.vertex(curr_idx-1);\n        edge->vertices()[1] = optimizer.vertex(curr_idx);\n\n        Eigen::Matrix<double,6,6> information = Eigen::Matrix<double,6,6>::Identity();\n        information(0,0) = information(1,1)=information(2,2) = 100;\n        information(3,3) = information(4,4) = information(5,5) = 100;\n\n        for(int i=0;i<3;i++)\n        {\n            for(int j=0; j<3;j++)\n            {\n                curr_frame.T(i,j) = rotation.at<double>(i,j);\n            }\n            curr_frame.T(i,3)=translation.at<double>(i,0);\n        }\n\n        edge->setInformation(information);\n        edge->setMeasurement(curr_frame.T);\n        optimizer.addEdge(edge);\n\n        last_frame = curr_frame;\n    }\n\n    cout<<\"optimizing pose graph, vertices: \"<<optimizer.vertices().size()<<endl;\n    optimizer.save(\"../data/result/result_before.g2o\");\n    optimizer.initializeOptimization();\n    optimizer.optimize(100);\n    optimizer.save(\"../data/result/result_after.g2o\");\n    cout<<\"optimization done\"<<endl;\n\n    outputfile.close();\n\n    imwrite(\"../data/result.jpg\", trajectory);\n}\n\nvoid My_VO::run_multiframe(int start_idx, int end_idx)\n{\n    //get data and open file\n    addData();\n    if(_WRITE_RESULT)\n    {\n        outputfile.open(\"../data/result/pose_multi.txt\");\n        if(!outputfile.is_open())\n        {\n            cout<<\"txt open error...\"<<endl;\n        }\n    }\n\n    //get first image, add it into last_frame_list\n    int curr_idx = start_idx;\n    vector<frame> last_frame_list;\n    frame start_frame = getFrame(start_idx);\n    outputData(start_frame);\n    for(int i = 0; i < _LAST_FRAME_NUM; i++)\n    {\n        last_frame_list.push_back(start_frame);\n    }\n\n    for(curr_idx = start_idx + 1; curr_idx < end_idx; curr_idx ++)\n    {\n        cout<<endl<<\"-------curr_idx = \"<<curr_idx<<\"-------\"<<endl;\n        frame curr_frame = getFrame(curr_idx);\n        vector<frame> curr_frame_list;\n        PnP_result res;\n\n        //get current and past frames' relationship\n        for(int i = 0; i<_LAST_FRAME_NUM; i++)\n        {\n            cout<<endl<<\"----last_idx = \"<<curr_idx - _LAST_FRAME_NUM + i<<\"----\"<<endl;\n            curr_frame_list.push_back(curr_frame);\n            res = estimateMotion(curr_idx, last_frame_list[i], curr_frame);//get R, t\n            PnPRes2Eigen(curr_frame_list[i], res);//procee result \n            integrateOdom(last_frame_list[i],curr_frame_list[i]);//refresh global pose\n        }\n\n        getMeanPose(curr_frame_list, curr_frame);\n\n        //refresh data\n        pose = curr_frame.pose;\n\n        display(curr_frame);\n        \n        if(curr_frame.pose.at<double>(0,0)==1)\n            curr_frame.pose=last_frame_list.at(_LAST_FRAME_NUM-1).pose;\n        outputData(curr_frame);\n        \n        vector<frame>::iterator p = last_frame_list.begin();\n        last_frame_list.erase(p);\n\n        last_frame_list.push_back(curr_frame);\n        \n        waitKey(1);\n    }\n    imwrite(\"../data/result.jpg\", path);\n    outputfile.close();\n}\n\nvoid My_VO::run(int start_idx , int end_idx)\n{\n    addData();\n    if(_WRITE_RESULT)\n    {\n        outputfile.open(\"../data/result/pose_single.txt\");\n        if(!outputfile.is_open())\n        {\n            cout<<\"txt open error...\"<<endl;\n        }\n    }\n\n    int curr_idx = start_idx;\n    frame last_frame = getFrame(curr_idx);\n    outputData(last_frame);\n\n    // 每个优化变量维度为3，误差值维度为1\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); \n    \n    Block* solver_ptr  = new Block( std::unique_ptr<Block::LinearSolverType>(linearSolver) );\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr<Block>(solver_ptr));\n\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(false);\n\n    g2o::VertexSE3* v = new g2o::VertexSE3();\n    v->setId(curr_idx);\n    v->setEstimate(Eigen::Isometry3d::Identity());\n    v->setFixed(true);\n    optimizer.addVertex(v);\n\n    int last_idx = curr_idx;\n\n    for(curr_idx = start_idx +1; curr_idx < end_idx; curr_idx++)\n    {\n        clock_t loop_time = clock();\n        cout<<endl<<\"-------\"<<curr_idx<<\"-------\"<<endl;\n\n        frame curr_frame = getFrame(curr_idx);\n\n        clock_t estimate_time = clock();\n        PnP_result res = estimateMotion(curr_idx, last_frame, curr_frame);\n        cout<<\"estimate cost: \"<<1000*(clock()-estimate_time)/CLOCKS_PER_SEC<<endl;\n        PnPRes2Eigen(curr_frame, res);\n        integrateOdom(curr_frame);\n\n        display(curr_frame);\n        if(curr_frame.pose.at<double>(0,0)==1)\n            curr_frame.pose=last_frame.pose;\n        outputData(curr_frame);\n\n        \n        waitKey(1);\n        cout<<\"loop cost: \"<<1000*(clock()- loop_time)/CLOCKS_PER_SEC<<endl;\n\n        g2o::VertexSE3* v = new g2o::VertexSE3();\n        //顶点\n        v->setId(curr_idx);\n        v->setEstimate(Eigen::Isometry3d::Identity());\n        optimizer.addVertex(v);\n        //边\n        g2o::EdgeSE3* edge = new g2o::EdgeSE3();\n        edge->vertices()[0] = optimizer.vertex(last_idx);\n        edge->vertices()[1] = optimizer.vertex(curr_idx);\n\n        Eigen::Matrix<double,6,6> information = Eigen::Matrix<double,6,6>::Identity();\n        information(0,0) = information(1,1)=information(2,2) = 100;\n        information(3,3) = information(4,4) = information(5,5) = 100;\n\n        edge->setInformation(information);\n        edge->setMeasurement(curr_frame.T);\n        optimizer.addEdge(edge);\n\n        last_idx = curr_idx;\n        last_frame = curr_frame;\n    }\n    imwrite(\"../data/result.jpg\", path);\n\n    cout<<\"optimizing pose graph, vertices: \"<<optimizer.vertices().size()<<endl;\n    optimizer.save(\"../data/result/result_before.g2o\");\n    optimizer.initializeOptimization();\n    optimizer.optimize(100);\n    optimizer.save(\"../data/result/result_after.g2o\");\n    cout<<\"optimization done\"<<endl;\n\n    //optimizer.clear();\n\n    outputfile.close();\n}\n\nvoid My_VO::display(int frame_id, cv::Mat& trajectory, cv::Mat& pose)\n{\n    int x = int(pose.at<double>(0)) + 300;\n    int y = int(pose.at<double>(2)) + 100;\n    circle(trajectory, cv::Point(x, y) ,1, CV_RGB(255,0,0), 2);\n    cv::imshow( \"Trajectory\", trajectory );\n    cv::waitKey(1);\n}\n\nvoid My_VO::integrateOdometryStereo(int frame_i, cv::Mat& rigid_body_transformation, cv::Mat& frame_pose, const cv::Mat& rotation, const cv::Mat& translation_stereo)\n{\n    cv::Mat addup = (cv::Mat_<double>(1, 4) << 0, 0, 0, 1);\n\n    cv::hconcat(rotation, translation_stereo, rigid_body_transformation);\n    cv::vconcat(rigid_body_transformation, addup, rigid_body_transformation);\n\n    // std::cout << \"rigid_body_transformation\" << rigid_body_transformation << std::endl;\n\n    double scale = sqrt((translation_stereo.at<double>(0))*(translation_stereo.at<double>(0)) \n                        + (translation_stereo.at<double>(1))*(translation_stereo.at<double>(1))\n                        + (translation_stereo.at<double>(2))*(translation_stereo.at<double>(2))) ;\n\n    // frame_pose = frame_pose * rigid_body_transformation;\n    std::cout << \"scale: \" << scale << std::endl;\n\n    rigid_body_transformation = rigid_body_transformation.inv();\n    // if ((scale>0.1)&&(translation_stereo.at<double>(2) > translation_stereo.at<double>(0)) && (translation_stereo.at<double>(2) > translation_stereo.at<double>(1))) \n    if (scale > 0.05 && scale < 10) \n    {\n      frame_pose = frame_pose * rigid_body_transformation;\n    }\n    else \n    {\n     std::cout << \"[WARNING] scale below 0.1, or incorrect translation\" << std::endl;\n    }\n}\n\nbool isRotationMatrix(cv::Mat &R)\n{\n    cv::Mat Rt;\n    transpose(R, Rt);\n    cv::Mat shouldBeIdentity = Rt * R;\n    cv::Mat I = cv::Mat::eye(3,3, shouldBeIdentity.type());\n     \n    return  norm(I, shouldBeIdentity) < 1e-6;\n     \n}\n\ncv::Vec3f My_VO::rotationMatrixToEulerAngles(cv::Mat &R)\n{\n    assert(isRotationMatrix(R));\n     \n    float sy = sqrt(R.at<double>(0,0) * R.at<double>(0,0) +  R.at<double>(1,0) * R.at<double>(1,0) );\n \n    bool singular = sy < 1e-6; // If\n \n    float x, y, z;\n    if (!singular)\n    {\n        x = atan2(R.at<double>(2,1) , R.at<double>(2,2));\n        y = atan2(-R.at<double>(2,0), sy);\n        z = atan2(R.at<double>(1,0), R.at<double>(0,0));\n    }\n    else\n    {\n        x = atan2(-R.at<double>(1,2), R.at<double>(1,1));\n        y = atan2(-R.at<double>(2,0), sy);\n        z = 0;\n    }\n    return cv::Vec3f(x, y, z);\n}\n\nvoid My_VO::displayTracking(cv::Mat& imageLeft_t1, \n                     std::vector<cv::Point2f>&  pointsLeft_t0,\n                     std::vector<cv::Point2f>&  pointsLeft_t1)\n{\n      int radius = 2;\n      cv::Mat vis;\n\n      cv::cvtColor(imageLeft_t1, vis, cv::COLOR_GRAY2BGR, 3);\n\n\n      for (int i = 0; i < pointsLeft_t0.size(); i++)\n      {\n          cv::circle(vis, cv::Point(pointsLeft_t0[i].x, pointsLeft_t0[i].y), radius, CV_RGB(0,255,0));\n      }\n\n      for (int i = 0; i < pointsLeft_t1.size(); i++)\n      {\n          cv::circle(vis, cv::Point(pointsLeft_t1[i].x, pointsLeft_t1[i].y), radius, CV_RGB(255,0,0));\n      }\n\n      for (int i = 0; i < pointsLeft_t1.size(); i++)\n      {\n          cv::line(vis, pointsLeft_t0[i], pointsLeft_t1[i], CV_RGB(0,255,0));\n      }\n\n      cv::imshow(\"vis \", vis );  \n}\n\nvoid My_VO::trackingFrame2Frame(cv::Mat& projMatrl, cv::Mat& projMatrr,\n                         std::vector<cv::Point2f>&  pointsLeft_t0,\n                         std::vector<cv::Point2f>&  pointsLeft_t1, \n                         cv::Mat& points3D_t0,\n                         cv::Mat& rotation,\n                         cv::Mat& translation,\n                         bool mono_rotation)\n{\n      cv::Mat distCoeffs = cv::Mat::zeros(4, 1, CV_64FC1);   \n      cv::Mat rvec = cv::Mat::zeros(3, 1, CV_64FC1);\n      cv::Mat intrinsic_matrix = (cv::Mat_<float>(3, 3) << projMatrl.at<float>(0, 0), projMatrl.at<float>(0, 1), projMatrl.at<float>(0, 2),\n                                                   projMatrl.at<float>(1, 0), projMatrl.at<float>(1, 1), projMatrl.at<float>(1, 2),\n                                                   projMatrl.at<float>(2, 0), projMatrl.at<float>(2, 1), projMatrl.at<float>(2, 2));\n\n      int iterationsCount = 500;        // number of Ransac iterations.\n      float reprojectionError = .5;    // maximum allowed distance to consider it an inlier.\n      float confidence = 0.999;          // RANSAC successful confidence.\n      bool useExtrinsicGuess = true;\n      int flags =cv::SOLVEPNP_ITERATIVE;\n\n      cv::Mat inliers; \n      cv::solvePnPRansac( points3D_t0, pointsLeft_t1, intrinsic_matrix, distCoeffs, rvec, translation,\n                          useExtrinsicGuess, iterationsCount, reprojectionError, confidence,\n                          inliers, flags );\n    if (!mono_rotation)\n      {\n        cv::Rodrigues(rvec, rotation);\n      }\n\n      std::cout<<\"inlier num: \"<<inliers.rows<<std::endl;\n\n      std::cout << \"[trackingFrame2Frame] inliers size: \" << inliers.size() << std::endl;\n}\n\nvoid My_VO::matchingFeatures(cv::Mat& imageLeft_t0, cv::Mat& imageRight_t0,\n                      cv::Mat& imageLeft_t1, cv::Mat& imageRight_t1, \n                      FeatureSet& currentVOFeatures,\n                      std::vector<cv::Point2f>&  pointsLeft_t0, \n                      std::vector<cv::Point2f>&  pointsRight_t0, \n                      std::vector<cv::Point2f>&  pointsLeft_t1, \n                      std::vector<cv::Point2f>&  pointsRight_t1)\n{\n    std::vector<cv::Point2f>  pointsLeftReturn_t0;\n\n    if (currentVOFeatures.size() < 2000)\n    {\n        appendNewFeatures(imageLeft_t0, currentVOFeatures);   \n    }\n\n    int bucket_size = imageLeft_t0.rows/10;\n    int features_per_bucket = 1;\n    bucketingFeatures(imageLeft_t0, currentVOFeatures, bucket_size, features_per_bucket);\n\n    pointsLeft_t0 = currentVOFeatures.points;\n\n    circularMatching(imageLeft_t0, imageRight_t0, imageLeft_t1, imageRight_t1,\n                     pointsLeft_t0, pointsRight_t0, pointsLeft_t1, pointsRight_t1, pointsLeftReturn_t0, currentVOFeatures);\n\n    std::vector<bool> status;\n    checkValidMatch(pointsLeft_t0, pointsLeftReturn_t0, status, 0);\n\n    removeInvalidPoints(pointsLeft_t0, status);\n    removeInvalidPoints(pointsLeft_t1, status);\n    removeInvalidPoints(pointsRight_t0, status);\n    removeInvalidPoints(pointsRight_t1, status);\n\n    currentVOFeatures.points = pointsLeft_t1;\n}\n\nvoid My_VO::removeInvalidPoints(std::vector<cv::Point2f>& points, const std::vector<bool>& status)\n{\n    int index = 0;\n    for (int i = 0; i < status.size(); i++)\n    {\n        if (status[i] == false)\n        {\n            points.erase(points.begin() + index);\n        }\n        else\n        {\n            index ++;\n        }\n    }\n}\n\nvoid My_VO::checkValidMatch(std::vector<cv::Point2f>& points, std::vector<cv::Point2f>& points_return, std::vector<bool>& status, int threshold)\n{\n    int offset;\n    for (int i = 0; i < points.size(); i++)\n    {\n        offset = std::max(std::abs(points[i].x - points_return[i].x), std::abs(points[i].y - points_return[i].y));\n        // std::cout << offset << \", \";\n\n        if(offset > threshold)\n        {\n            status.push_back(false);\n        }\n        else\n        {\n            status.push_back(true);\n        }\n    }\n}\n\nvoid My_VO::circularMatching(cv::Mat img_l_0, cv::Mat img_r_0, cv::Mat img_l_1, cv::Mat img_r_1,\n                      std::vector<cv::Point2f>& points_l_0, std::vector<cv::Point2f>& points_r_0,\n                      std::vector<cv::Point2f>& points_l_1, std::vector<cv::Point2f>& points_r_1,\n                      std::vector<cv::Point2f>& points_l_0_return,\n                      FeatureSet& current_features)\n{\n    std::vector<float> err;                    \n  cv::Size winSize=cv::Size(21,21);                                                                                             \n  cv::TermCriteria termcrit=cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 30, 0.01);\n\n  std::vector<uchar> status0;\n  std::vector<uchar> status1;\n  std::vector<uchar> status2;\n  std::vector<uchar> status3;\n\n  clock_t tic = clock();\n  calcOpticalFlowPyrLK(img_l_0, img_r_0, points_l_0, points_r_0, status0, err, winSize, 3, termcrit, 0, 0.001);\n  calcOpticalFlowPyrLK(img_r_0, img_r_1, points_r_0, points_r_1, status1, err, winSize, 3, termcrit, 0, 0.001);\n  calcOpticalFlowPyrLK(img_r_1, img_l_1, points_r_1, points_l_1, status2, err, winSize, 3, termcrit, 0, 0.001);\n  calcOpticalFlowPyrLK(img_l_1, img_l_0, points_l_1, points_l_0_return, status3, err, winSize, 3, termcrit, 0, 0.001);\n  clock_t toc = clock();\n  std::cerr << \"calcOpticalFlowPyrLK time: \" << float(toc - tic)/CLOCKS_PER_SEC*1000 << \"ms\" << std::endl;\n\n\n  deleteUnmatchFeaturesCircle(points_l_0, points_r_0, points_r_1, points_l_1, points_l_0_return,\n                        status0, status1, status2, status3, current_features.ages);\n}\n\nvoid My_VO::deleteUnmatchFeaturesCircle(std::vector<cv::Point2f>& points0, std::vector<cv::Point2f>& points1,\n                          std::vector<cv::Point2f>& points2, std::vector<cv::Point2f>& points3,\n                          std::vector<cv::Point2f>& points0_return,\n                          std::vector<uchar>& status0, std::vector<uchar>& status1,\n                          std::vector<uchar>& status2, std::vector<uchar>& status3,\n                          std::vector<int>& ages)\n{\n    for (int i = 0; i < ages.size(); ++i)\n    {\n        ages[i] += 1;\n    }\n\n    int indexCorrection = 0;\n    for( int i=0; i<status3.size(); i++)\n        {  cv::Point2f pt0 = points0.at(i- indexCorrection);\n            cv::Point2f pt1 = points1.at(i- indexCorrection);\n            cv::Point2f pt2 = points2.at(i- indexCorrection);\n            cv::Point2f pt3 = points3.at(i- indexCorrection);\n            cv::Point2f pt0_r = points0_return.at(i- indexCorrection);\n            \n            if ((status3.at(i) == 0)||(pt3.x<0)||(pt3.y<0)||\n                (status2.at(i) == 0)||(pt2.x<0)||(pt2.y<0)||\n                (status1.at(i) == 0)||(pt1.x<0)||(pt1.y<0)||\n                (status0.at(i) == 0)||(pt0.x<0)||(pt0.y<0))   \n            {\n            if((pt0.x<0)||(pt0.y<0)||(pt1.x<0)||(pt1.y<0)||(pt2.x<0)||(pt2.y<0)||(pt3.x<0)||(pt3.y<0))    \n            {\n                status3.at(i) = 0;\n            }\n            points0.erase (points0.begin() + (i - indexCorrection));\n            points1.erase (points1.begin() + (i - indexCorrection));\n            points2.erase (points2.begin() + (i - indexCorrection));\n            points3.erase (points3.begin() + (i - indexCorrection));\n            points0_return.erase (points0_return.begin() + (i - indexCorrection));\n\n            ages.erase (ages.begin() + (i - indexCorrection));\n            indexCorrection++;\n            }\n\n        }  \n}\n\nvoid My_VO::bucketingFeatures(cv::Mat& image, FeatureSet& current_features, int bucket_size, int features_per_bucket)\n{\n    int image_height = image.rows;\n    int image_width = image.cols;\n    int buckets_nums_height = image_height/bucket_size;\n    int buckets_nums_width = image_width/bucket_size;\n    int buckets_number = buckets_nums_height * buckets_nums_width;\n\n    std::vector<Bucket> Buckets;\n\n    // initialize all the buckets\n    for (int buckets_idx_height = 0; buckets_idx_height <= buckets_nums_height; buckets_idx_height++)\n    {\n      for (int buckets_idx_width = 0; buckets_idx_width <= buckets_nums_width; buckets_idx_width++)\n      {\n        Buckets.push_back(Bucket(features_per_bucket));\n      }\n    }\n\n    // bucket all current features into buckets by their location\n    int buckets_nums_height_idx, buckets_nums_width_idx, buckets_idx;\n    for (int i = 0; i < current_features.points.size(); ++i)\n    {\n      buckets_nums_height_idx = current_features.points[i].y/bucket_size;\n      buckets_nums_width_idx = current_features.points[i].x/bucket_size;\n      buckets_idx = buckets_nums_height_idx*buckets_nums_width + buckets_nums_width_idx;\n      Buckets[buckets_idx].add_feature(current_features.points[i], current_features.ages[i]);\n\n    }\n\n    // get features back from buckets\n    current_features.clear();\n    for (int buckets_idx_height = 0; buckets_idx_height <= buckets_nums_height; buckets_idx_height++)\n    {\n      for (int buckets_idx_width = 0; buckets_idx_width <= buckets_nums_width; buckets_idx_width++)\n      {\n         buckets_idx = buckets_idx_height*buckets_nums_width + buckets_idx_width;\n         Buckets[buckets_idx].get_features(current_features);\n      }\n    }\n\n    std::cout << \"current features number after bucketing: \" << current_features.size() << std::endl;\n\n}\n\nvoid My_VO::appendNewFeatures(cv::Mat& image, FeatureSet& current_features)\n{\n    std::vector<cv::Point2f>  points_new;\n    featureDetectionFast(image, points_new);\n    current_features.points.insert(current_features.points.end(), points_new.begin(), points_new.end());\n    std::vector<int>  ages_new(points_new.size(), 0);\n    current_features.ages.insert(current_features.ages.end(), ages_new.begin(), ages_new.end());\n}\n\nvoid My_VO::featureDetectionFast(cv::Mat image, std::vector<cv::Point2f>& points)  \n{\n  std::vector<cv::KeyPoint> keypoints;\n  int fast_threshold = 20;\n  bool nonmaxSuppression = true;\n  cv::FAST(image, keypoints, fast_threshold, nonmaxSuppression);\n  cv::KeyPoint::convert(keypoints, points, std::vector<int>());\n}\n\nvoid My_VO::outputData(frame& frame)\n{\n    if(!outputfile.is_open())\n        return;\n\n    for(int i=0; i < 3;i++)\n    {\n        for(int j=0; j<4;j++)\n        {\n            outputfile<<frame.pose.at<double>(i,j);\n            if(!((i==2)&&(j==3)))\n                outputfile<<\" \";\n        }\n    }\n    outputfile<<endl;\n}\n\nvoid My_VO::getMeanPose(vector<frame> frame_list, frame& frame)\n{\n    for(int i=0;i<4;i++)\n    {\n        for(int j=0;j<4;j++)\n        {\n            double element = 0;\n            int cnt = 0;\n            for(int idx = 0; idx < frame_list.size(); idx++)\n            {\n                if(frame_list[idx].valid)\n                {\n                    element += frame_list[idx].pose.at<double>(i,j);\n                    cnt+=1;\n                }\n            }\n            if(cnt == 0)\n            {\n                frame.valid = false;\n                return;\n            } \n            element /= cnt;\n            frame.pose.at<double>(i, j) = element;\n        }\n    }\n}\n\nvoid My_VO::display(frame& frame)\n{\n    if(!frame.valid)\n        return;\n\n    int x = int(frame.pose.at<double>(0,3)) + 300;\n    int y = int(frame.pose.at<double>(2,3)) + 200;\n    cout<<\"x: \"<<x<<endl;\n    circle(path, cv::Point(x, y) ,1, CV_RGB(255-255*int(frame.id/_IMAGE_NUM),255-255*int(frame.id/_IMAGE_NUM),255*int(frame.id/_IMAGE_NUM)), 2);\n\n    if(_SHOW_PATH)\n        imshow(\"path\", path);\n}\n\nvoid My_VO::integrateOdom(frame& last_frame, frame& curr_frame)\n{\n    if(!(last_frame.valid&&curr_frame.valid))\n    {\n        return;\n    }\n    Mat addup =   (Mat_<double>(1, 4) << 0, 0, 0, 1);\n    Mat rigid_body_transformation;\n\n    hconcat(curr_frame.R, curr_frame.t, rigid_body_transformation);\n    vconcat(rigid_body_transformation, addup, rigid_body_transformation);\n\n    double scale = sqrt((curr_frame.t.at<double>(0))*(curr_frame.t.at<double>(0)) \n                        + (curr_frame.t.at<double>(1))*(curr_frame.t.at<double>(1))\n                        + (curr_frame.t.at<double>(2))*(curr_frame.t.at<double>(2))) ;\n    std::cout << \"scale: \" << scale << std::endl;\n\n    if (scale < 10) \n    {\n        rigid_body_transformation = rigid_body_transformation.inv();\n        curr_frame.pose = last_frame.pose * rigid_body_transformation;\n    }\n    else \n    {\n        std::cout << \"[WARNING] scale below 0.1, or incorrect translation\" << std::endl;\n    }\n}\n\nvoid My_VO::integrateOdom(frame& curr_frame)\n{\n    if(!(curr_frame.valid))\n        return;\n\n    Mat addup =   (Mat_<double>(1, 4) << 0, 0, 0, 1);\n    Mat rigid_body_transformation;\n\n    hconcat(curr_frame.R, curr_frame.t, rigid_body_transformation);\n    vconcat(rigid_body_transformation, addup, rigid_body_transformation);\n\n    double scale = sqrt((curr_frame.t.at<double>(0))*(curr_frame.t.at<double>(0)) \n                        + (curr_frame.t.at<double>(1))*(curr_frame.t.at<double>(1))\n                        + (curr_frame.t.at<double>(2))*(curr_frame.t.at<double>(2))) ;\n    std::cout << \"scale: \" << scale << std::endl;\n\n    if (scale < 10) \n    {\n        rigid_body_transformation = rigid_body_transformation.inv();\n        pose = pose * rigid_body_transformation;\n        curr_frame.pose = pose;\n    }\n    else \n    {\n        std::cout << \"[WARNING] scale below 0.1, or incorrect translation\" << std::endl;\n    }\n}\n\nstruct PnP_result My_VO::estimateMotion(int idx, frame& last_frame, frame& curr_frame)\n{\n    vector<DMatch> matches[2], lrmatches;\n    BFMatcher matcher;\n    matcher.match(last_frame.desp[_LEFT], curr_frame.desp[_LEFT], matches[_LEFT]);\n    matcher.match(last_frame.desp[_RIGHT], curr_frame.desp[_RIGHT], matches[_RIGHT]);\n    matcher.match(last_frame.desp[_LEFT], last_frame.desp[_RIGHT], lrmatches);\n\n    // Mat lrmatch_img;\n    // drawMatches(last_frame.src[_LEFT], last_frame.kp[_LEFT], last_frame.src[_RIGHT], last_frame.kp[_RIGHT], lrmatches, lrmatch_img);\n    // imshow(\"lrmatches\", lrmatch_img);\n\n    if(_WRITE_MATCH_IMAGE)\n    {\n        Mat match_img;\n        drawMatches(last_frame.src[_LEFT], last_frame.kp[_LEFT], curr_frame.src[_LEFT], curr_frame.kp[_LEFT], matches[_LEFT], match_img);\n        imshow(\"matches\", match_img);\n        \n        stringstream path;\n        path<<\"../data/match_images/\"<<idx<<\".jpg\";\n        imwrite(path.str(), match_img);\n        std::cout<<\"match image write\"<<endl;\n    }\n\n    vector<DMatch> good_matches[2], lrgood_matches;\n\n\tdouble minDist = 10000, maxDist = 0;\n\tfor(int i = 0; i < (int)matches[_LEFT].size(); i++)\n\t{\n\t\tdouble dist = matches[_LEFT][i].distance;\n\t\t\n\t\tminDist = minDist > dist ? dist : minDist;\n\t\tmaxDist = maxDist < dist ? dist : maxDist;\n\t}\n\t\n\tdouble matchDist = max(100.0, minDist * 2);\n\tfor(int i = 0; i < (int)matches[_LEFT].size(); i++)\n\t\tif(matches[_LEFT][i].distance <= matchDist)\n        {\n\t\t\tgood_matches[_LEFT].push_back(matches[_LEFT][i]);\t\t\t\n            good_matches[_RIGHT].push_back(matches[_RIGHT][i]);\t\t\t\n        }\n\n    minDist = 10000;\n    maxDist = 0;\n    for(int i = 0; i < (int)lrmatches.size(); i++)\n\t{\n\t\tdouble dist = lrmatches[i].distance;\n\t\t\n\t\tminDist = minDist > dist ? dist : minDist;\n\t\tmaxDist = maxDist < dist ? dist : maxDist;\n\t}\n    matchDist = max(100.0, minDist * 2);\n\tfor(int i = 0; i < (int)lrmatches.size(); i++)\n\t\tif(lrmatches[i].distance <= matchDist)\n        {\n\t\t\tlrgood_matches.push_back(lrmatches[i]);\t\t\t\t\n        }\n\n    // drawMatches(last_frame.src[_LEFT], last_frame.kp[_LEFT], last_frame.src[_RIGHT], last_frame.kp[_RIGHT], lrgood_matches, lrmatch_img);\n    // imshow(\"lrgood matches\", lrmatch_img);\n\n    if(_WRITE_MATCH_IMAGE)\n    {\n        Mat match_img;\n        drawMatches(last_frame.src[_LEFT], last_frame.kp[_LEFT], curr_frame.src[_LEFT], curr_frame.kp[_LEFT], good_matches[_LEFT], match_img);\n        imshow(\"good matches\", match_img);\n        \n        stringstream path;\n        path<<\"../data/good_match_images/\"<<idx<<\".jpg\";\n        imwrite(path.str(), match_img);\n        std::cout<<\"good match image write\"<<endl;\n    }\n\n    Mat pts_obj, pts_obj_4d;\n    vector<Point2f> pts_img, points_left_t0, points_left_t1, points_right_t0, points_right_t1;\n    for(int i = 0; i<matches[_LEFT].size(); i++)\n    {\n        points_left_t0.push_back(Point2f(last_frame.kp[_LEFT][lrmatches[i].queryIdx].pt));\n        points_left_t1.push_back(Point2f(curr_frame.kp[_LEFT][matches[_LEFT][i].trainIdx].pt));\n        points_right_t0.push_back(Point2f(last_frame.kp[_RIGHT][lrmatches[i].trainIdx].pt));\n    }\n    triangulatePoints(l_matrix, r_matrix, points_left_t0, points_right_t0, pts_obj_4d);\n    convertPointsFromHomogeneous(pts_obj_4d.t(), pts_obj);\n    pts_img = points_left_t1;\n\n    double camera_intrinsic_matrix[3][3]=\n    {\n        {camera_parameters.fx, 0, camera_parameters.cx},\n        {0, camera_parameters.fy, camera_parameters.cy},\n        {0, 0, 1}\n    };\n\n    Mat camera_matrix(3,3, CV_64F, camera_intrinsic_matrix);\n    Mat rvec, tvec, inliers;\n    Mat distCoeffs = cv::Mat::zeros(4, 1, CV_64FC1);   \n\n    solvePnPRansac(pts_obj, pts_img, camera_matrix, distCoeffs, rvec, tvec, false, 500, 0.5f, 0.99,inliers);\n    \n    cout<<\"inliers: \"<<inliers.rows<<endl;\n\n    vector< cv::DMatch > inlier_match;\n    for(int i=0; i<inliers.rows;i++)\n    {\n        inlier_match.push_back(matches[_LEFT][inliers.ptr<int>(i)[0]]);\n    }\n    if(_WRITE_INLIER)\n    {\n        Mat match_img;\n        drawMatches(last_frame.src[_LEFT], last_frame.kp[_LEFT], curr_frame.src[_LEFT], curr_frame.kp[_LEFT], inlier_match, match_img);\n        imshow(\"inliers match\", match_img);\n\n        stringstream path;\n        path<<\"../data/inlier_images/\"<<idx<<\".jpg\";\n        imwrite(path.str(), match_img);\n        std::cout<<\"inlier math image write\"<<endl;\n    }\n\n    PnP_result res;\n    res.R = rvec;\n    res.t = tvec;\n    res.inliers = inliers.rows;\n\n    return res;\n}\n\nframe My_VO::getFrame(const int& idx, bool detect)\n{\n    frame res;\n    res.id  = idx;\n    Mat l = imread(image_list[_LEFT][idx],0);\n    Mat r = imread(image_list[_RIGHT][idx],0);\n    cout << \"image get\"<<endl;\n    res.src[_LEFT] = l;\n    res.src[_RIGHT] = r;\n    if(!detect)\n        return res;\n    Ptr<ORB> _detector;\n    int nfeatures = 1000;\n    _detector = ORB::create(nfeatures);\n\n    _detector->detect(res.src[_LEFT], res.kp[_LEFT]);\n    _detector->detect(res.src[_RIGHT], res.kp[_RIGHT]);\n    cout<<\"Key points of images: \"<<res.kp[_LEFT].size()<<endl;\n\n    Mat desp;\n    _detector->compute(res.src[_LEFT], res.kp[_LEFT], res.desp[_LEFT]);\n    _detector->compute(res.src[_RIGHT], res.kp[_RIGHT], res.desp[_RIGHT]);\n\n    // Mat disp, depth;  \n\n    // stereoSGBM(l, r, disp);\n    // if(_WRITE_DISP)\n    // {\n    //     stringstream path;\n    //     path<<\"../data/disp_images/\"<<idx<<\".jpg\";\n    //     imwrite(path.str(),disp);\n    //     cout<<\"disp image write\"<<endl;\n    // }\n    \n    // disp2Depth(disp, depth);\n    // if(_WRITE_DEPTH)\n    // {\n    //     stringstream path;\n    //     path<<\"../data/depth_images/\"<<idx<<\".jpg\";\n    //     imwrite(path.str(),depth);\n    //     cout<<\"depth image write\"<<endl;\n    // }\n    // imshow(\"depth\", depth);\n    // //waitKey(0);\n\n    // res.depth = depth;\n    return res;\n}\n\nvoid My_VO::PnPRes2Eigen(frame& curr_frame, PnP_result& res)\n{\n    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n    Eigen::Matrix3d R;\n    Mat r;\n\n    Rodrigues(res.R, r);\n    for ( int i=0; i<3; i++ )\n        for ( int j=0; j<3; j++ ) \n            R(i,j) = r.at<double>(i,j);\n    \n    Eigen::AngleAxisd angle(R);\n    T = angle;\n    \n    double alpha = atan2(r.at<double>(2,1), r.at<double>(2,2));\n    double beta = atan2(-r.at<double>(2,0), sqrt(pow(r.at<double>(2,1),2) + pow(r.at<double>(2,2),2)));\n    double gamma = atan2(r.at<double>(1,0), r.at<double>(0,0));\n    if(alpha>0.1||beta>0.1||gamma>0.1)\n    {\n        curr_frame.valid = false;\n        return;\n    }\n\n    Eigen::Translation<double,3> trans(res.t.at<double>(0,0), res.t.at<double>(1,0), res.t.at<double>(2,0));\n\n    for(int i = 0; i<3; i++)\n    {\n        T(i,3)=res.t.at<double>(i,0);\n        if(T(i,3)>=1.0)\n        {\n            curr_frame.valid = false;\n            return;\n        }\n    }\n    curr_frame.R = r;\n    curr_frame.t = res.t;\n    curr_frame.T = T;\n    cout<<curr_frame.T.matrix()<<endl;\n}\n\nvector<vector<string>> My_VO::addData()\n{\n    vector<string> l, r;\n    \n    for(int i = 0; i < _IMAGE_NUM; i++) \n    {\n        stringstream l_stream, r_stream;\n        \n        string zero_num;\n        if(i < 10)\n            zero_num = \"00000\";\n        else if(i <100)\n            zero_num = \"0000\";\n        else \n            zero_num = \"000\";\n\n        l_stream << \"../data/image_0/\" << zero_num << i <<\".png\";\n        l.push_back(l_stream.str());\n\n        r_stream << \"../data/image_1/\" << zero_num << i <<\".png\";\n        r.push_back(r_stream.str());\n    }\n    image_list.push_back(l);\n    image_list.push_back(r);\n\n    return image_list;\n}\n\nPoint3f My_VO::from2dTo3d(const Point3f& point)\n{\n    Point3f p;\n    p.z = double(point.z) / camera_parameters.scale;\n    p.x = (point.x - camera_parameters.cx) * p.z / camera_parameters.fx;\n    p.y = (point.y - camera_parameters.cy) * p.z / camera_parameters.fy;\n    return p;\n}\n\nvoid My_VO::stereoSGBM(Mat lpng, Mat rpng, Mat&disp)\n{\n    disp.create(lpng.rows, lpng.cols, CV_16S);\n    cv::Mat disp1 = cv::Mat(lpng.rows, lpng.cols, CV_8UC1);\n    cv::Size img_size = lpng.size();\n    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create();\n    int nmDisparities = 256;((img_size.width / 8) + 15) & -16;\n    int pngChannels = lpng.channels();\n    int winSize = 6;\n    sgbm->setPreFilterCap(13);\n    sgbm->setBlockSize(winSize);\n    sgbm->setP1(8 * pngChannels * winSize * winSize);\n    sgbm->setP2(32 * pngChannels * winSize * winSize);\n    sgbm->setMinDisparity(0);\n    sgbm->setNumDisparities(nmDisparities);\n    sgbm->setUniquenessRatio(10);\n    sgbm->setSpeckleWindowSize(100);\n    sgbm->setSpeckleRange(32);\n    sgbm->setDisp12MaxDiff(1);\n    sgbm->setMode(cv::StereoSGBM::MODE_SGBM);\n    sgbm->compute(lpng, rpng, disp);\n    normalize(disp, disp, 0, 255, NORM_MINMAX);\n    normalize(disp1, disp1, 0, 255, NORM_MINMAX);\n    imshow(\"disp1\", disp1);\n    imshow(\"disp2\", disp);\n    //disp.convertTo(disp1, CV_32F, 1.0/16.0f);\n    //disp = disp1;\n}\n\nvoid My_VO::disp2Depth(Mat disp, Mat& depth)\n{\n    depth.create(disp.rows, disp.cols, CV_8UC1);\n    cv::Mat depth1 = cv::Mat(disp.rows, disp.cols, CV_16S);\n    for (int i = 0; i < disp.rows; i++)\n    {\n        for (int j = 0; j < disp.cols; j++)\n        {\n            if (!disp.ptr<uint16_t>(i)[j])//��ֹ��0�ж�\n                continue;\n            depth1.ptr<uint16_t>(i)[j] = camera_parameters.scale * camera_parameters.fx * camera_parameters.baseline / disp.ptr<ushort>(i)[j];\n        }\n    }\n    normalize(depth, depth, 0, 255, NORM_MINMAX);\n    depth1.convertTo(depth, CV_8U, 1. / 256);\n}\n\n", "meta": {"hexsha": "df26890e582c0bbe13de693a1c3d49d9add64427", "size": 44673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw3/src/main.cpp", "max_stars_repo_name": "South-River/visual-odometry", "max_stars_repo_head_hexsha": "4f67f0217cb4887f58deb6c33e63b975cea8d764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T03:09:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T03:09:13.000Z", "max_issues_repo_path": "hw3/src/main.cpp", "max_issues_repo_name": "South-River/visual-odometry", "max_issues_repo_head_hexsha": "4f67f0217cb4887f58deb6c33e63b975cea8d764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw3/src/main.cpp", "max_forks_repo_name": "South-River/visual-odometry", "max_forks_repo_head_hexsha": "4f67f0217cb4887f58deb6c33e63b975cea8d764", "max_forks_repo_licenses": ["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.5231839258, "max_line_length": 168, "alphanum_fraction": 0.6034741343, "num_tokens": 12308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5953874565807424}}
{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n#include \"Tools.hpp\"\n#include \"Magnet.hpp\"\nusing namespace std;\n\n/*****************************************************************************\n\nThis program contains the main function for the project, as well as graphing\ncapability. Several constants are prompted from the user, and several are just\nassumed for the sake of consistency. The program first seeds the random\nnumber generator, vital for the Monte-Carlo method to function. It then\ncreates an allocated magnet object, initialized with random spins and the\ntemperature that the user input. It simulates for the specified number of\niterations and then plots the final matrix of spins. \n\nIt then jumps into a loop to generate the Energy and Magnetization vs. Time \nplots. For each temperature, mag is reset to all zeroes (to make graphs easier \nto understand) and simulated. The final energy and magnetization are recorded \nand added to their respective vectors along with time. After the loop exits,\na running exponential average is performed on both data vectors before they\nare plotted. The Magnet object is then deleted and the program exits.\n\n*****************************************************************************/\n\nconst int lattice = inputInt(50,\"lattice size\");\t\t\t\t// Constants used for simulation / initialization\nconst double defaultJ = 1;\t\t\t\t\t\t\t\t\t\t// of the Magnet object. J = kb = 1 from the assignment\nconst double firstTemp = inputDouble(1,\"ambient temperature\");;\nconst double defaultKb = 1;\nconst double tStep = 0.01;\nconst int MAX_ITERS = inputInt(100,\"maximum iterations\");\n\nvoid plotSpinMatrix(Magnet* m){\t\t\t// Plot the matrix of spins!\n\tGnuplot gp; \n\tgp << setprecision(3);\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"Spins of a Randomized Ising Model After \" << MAX_ITERS;\n\tgp << \" iterations of the Metropolis Algorithm\\\\nwith Ambient Temperature \" << firstTemp;\n\tgp << \", k_b = \" << defaultKb << \", J = \" << defaultJ << \"\\\"\\n\";\n\tgp << \"set output \\\"mag.png\\\"\\n\";\n\tgp << \"set palette grey\\n\";\n\tgp << \"set pm3d map\\n\";\n\tgp << \"unset key\\n\";\n\tgp << \"unset colorbox\\n\";\n\tgp << \"splot '-' matrix with image\\n\";\n\tgp.send1d(m->getAllSpins());\t\t// For some reason, gnuplot requires matrix input from a 2-D array to be sent as 1-D data\n}\n\nvoid plotEnergy(vector<double>& eng, vector<double>& t){\t// Plotting energy per spin\n\tGnuplot gp;\n\tgp << setprecision(3);\n\tgp << \"set xrange [1:4]\\n\";\n\tgp << \"set yrange [-2:0]\\n\";\n\tgp << \"set title \\\"Energy per Spin vs. Temperature in the Ising Model\\\\n\";\n\tgp << \"with k_b = \" << defaultKb << \", J = \" << defaultJ << \"\\\"\\n\";\n\tgp << \"set xlabel \\\"Temperature (inv. Boltzmann Constants)\\\"\\n\";\n\tgp << \"set ylabel \\\"Energy per Spin (E_{/Symbol a} / N)\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set output \\\"energy.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(t,eng));\n}\n\nvoid plotMagnetization(vector<double>& v, vector<double>& t){\t// Magnetization per spin\n\tGnuplot gp;\n\tgp << setprecision(3);\n\tgp << \"set xrange [1:4]\\n\";\n\tgp << \"set yrange [-1:0.1]\\n\";\n\tgp << \"set title \\\"Average Magnetization Per Spin vs. Temperature in the Ising Model\\\\n\";\n\tgp << \"with k_b = \" << defaultKb << \", J = \" << defaultJ << \"\\\"\\n\";\n\tgp << \"set xlabel \\\"Temperature (inv. Boltzmann Constants)\\\"\\n\";\n\tgp << \"set ylabel \\\"Magnetization Per Spin\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set output \\\"magnetization.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(t,v));\n}\n\nint main(){\t\t\t\t\t\t// Main function\n\tsrand(time(NULL));\t\t\t// Seed the random number generator (this carries to the other programs)\n\tMagnet* mag = new Magnet(lattice, firstTemp, defaultKb, defaultJ);\t// Initialize the Magnet object\n\tvector<double> temp;\t\t// Create vectors to store data for later plots\n\tvector<double> energy;\n\tvector<double> mzation;\n\n\tmag->simulate(MAX_ITERS);\t// Simulate the magnet with user-given parameters\n\tplotSpinMatrix(mag);\t\t// Plot the final spins\n\tmag->setNeg();\t\t\t\t// Reset to all spin down for nest segment\n\n\tfor(double t = 0.8; t < 4.2; t+= tStep){\t// Bounds chosen to allow rolling average to stabilize at ends (only plotting 1-4)\n\t\tmag->setTemp(t);\t\t\t\t\t\t// Set temperature\n\t\tmag->simulate(MAX_ITERS);\t\t\t\t// and simulate!\n\t\tenergy.push_back(mag->getEnergy());\t\t// Then store important quantities\n\t\tmzation.push_back(mag->getMag());\n\t\ttemp.push_back(t);\t\t\t\t\t\t// As well as the temperature\n\t\tmag->setNeg();\t\t\t\t\t\t\t// Reset for next simulation\n\t\tcout << \"Finished T = \" << t << endl;\t// Just to track progress, print that it finished an iteration\n\t}\n\n\tvector<double> rollingE = expAvg(energy,0.02);\t// Get the exponential rolling average of the quantities\n\tvector<double> rollingM = expAvg(mzation,0.02);\n\n\tplotEnergy(rollingE,temp);\t\t\t// Plot energy and magnetization!\n\tplotMagnetization(rollingM,temp);\n\n\tdelete mag;\t// Garbage collection (since object was created with \"new\")\n\treturn 0;\t// Return without error\n}", "meta": {"hexsha": "c787a5479924db953ef6d8fd69f1dfdf18ecb5e9", "size": 5146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Magnets/Ising.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": "Magnets/Ising.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": "Magnets/Ising.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.3603603604, "max_line_length": 124, "alphanum_fraction": 0.6725612126, "num_tokens": 1393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5953874441570375}}
{"text": "/***************************************************************************\n *  @file       square_matrix_multiply.hpp\n *  @author     Yue Wang\n *  @date       29  Aug 2014\n *  @version    2\n *  @remark     CLRS Algorithms implementation in C++ templates.\n ***************************************************************************/\n\n#ifndef SQUARE_MATRIX_MULTIPLY_H\n#define SQUARE_MATRIX_MULTIPLY_H\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace clrs {namespace ch4 {\n\n/**\n *  @brief  type aliasing\n */\ntemplate<typename T>\nusing Matrix = boost::numeric::ublas::matrix<T>;\n\n/**\n * @brief square_matrix_multiply\n * @param lhs\n * @param rhs\n * @return product\n *\n * @pseudocode SQUARE-MATRIX-MULTIPLY,   Page 75\n * @complx  O(n^3)\n */\ntemplate<typename T>\nMatrix<T> square_matrix_multiply(const Matrix<T>& lhs, const Matrix<T>& rhs)\n{\n    using namespace boost::numeric::ublas;\n    using SizeType  = typename matrix<T>::size_type;\n\n    SizeType size = lhs.size1();\n    matrix<T> ret(size, size);\n    for(SizeType i = 0; i != size; ++i)\n        for(SizeType j = 0; j != size; ++j)\n        {\n            ret(i,j) = 0;\n            for(SizeType k = 0; k != size; ++k)\n                ret(i,j) += lhs(i,k) * rhs(k,j);\n        }\n    return  ret;\n}\n\n/**\n * @brief square_matrix_multiply\n * @param lhs\n * @param rhs\n * @return product\n *\n * @pseudocode SQUARE-MATRIX-MULTIPLY-RECURSIVE\n * @complx  O(n^3)\n */\ntemplate<typename T>\nMatrix<T>\nsquare_matrix_multiply_recursive(const Matrix<T>& lhs, const Matrix<T>& rhs)\n{\n    //! types def\n    using ValueType = T;\n    using Matrix    = boost::numeric::ublas::matrix<ValueType>;   \n    using SizeType  = typename Matrix::size_type;\n    using Range     = boost::numeric::ublas::range;\n    using namespace boost::numeric::ublas;\n\n    SizeType size = lhs.size1();\n    Matrix ret(size,size);\n\n    //! the recurssion bottom\n    if(size == 1)\n        ret(0,0) = lhs(0,0) * rhs(0,0);\n    else\n    {\n        //! ranges used for matrix partition\n        Range r0(0,size/2), r1(size/2, size);\n\n        //! lhs's submatrices\n        Matrix lhs00(project(lhs,r0,r0));\n        Matrix lhs01(project(lhs,r0,r1));\n        Matrix lhs10(project(lhs,r1,r0));\n        Matrix lhs11(project(lhs,r1,r1));\n\n        //! rhs's submatrices\n        Matrix rhs00(project(rhs,r0,r0));\n        Matrix rhs01(project(rhs,r0,r1));\n        Matrix rhs10(project(rhs,r1,r0));\n        Matrix rhs11(project(rhs,r1,r1));\n\n        //! recurssion\n        //! @note must use project() on ret to \"reference\" it.Otherwise not working.\n        project(ret,r0,r0)  =   square_matrix_multiply_recursive(lhs00,rhs00)\n                              + square_matrix_multiply_recursive(lhs01,rhs10);\n\n        project(ret,r0,r1)  =   square_matrix_multiply_recursive(lhs00,rhs01)\n                              + square_matrix_multiply_recursive(lhs01,rhs11);\n\n        project(ret,r1,r0)  =   square_matrix_multiply_recursive(lhs10,rhs00)\n                              + square_matrix_multiply_recursive(lhs11,rhs10);\n\n        project(ret,r1,r1)  =   square_matrix_multiply_recursive(lhs10,rhs01)\n                              + square_matrix_multiply_recursive(lhs11,rhs11);\n    }\n    return ret;\n}\n\n/**\n * @brief square_matrix_multiply_strassen\n * @param lhs\n * @param rhs\n * @return product\n *\n * @complx  O(n^2.81)\n */\ntemplate<typename T>\nMatrix<T>\nsquare_matrix_multiply_strassen(const Matrix<T>& lhs, const Matrix<T>& rhs)\n{\n    //! types def\n    using ValueType = T;\n    using Matrix    = boost::numeric::ublas::matrix<ValueType>;\n    using SizeType  = typename Matrix::size_type;\n    using Range     = boost::numeric::ublas::range;\n    using namespace boost::numeric::ublas;\n\n    SizeType size = lhs.size1();\n    Matrix  ret(size,size);\n\n    if(size == 1)\n        ret(0,0) = lhs(0,0) * rhs(0,0);\n    else\n    {\n        //! ranges used for matrix partition\n        Range r0(0,size/2), r1(size/2, size);\n\n        //! step 1 : submatrices\n        Matrix lhs00(project(lhs,r0,r0));\n        Matrix lhs01(project(lhs,r0,r1));\n        Matrix lhs10(project(lhs,r1,r0));\n        Matrix lhs11(project(lhs,r1,r1));\n        Matrix rhs00(project(rhs,r0,r0));\n        Matrix rhs01(project(rhs,r0,r1));\n        Matrix rhs10(project(rhs,r1,r0));\n        Matrix rhs11(project(rhs,r1,r1));\n\n        //! step 2\n        Matrix s0 = rhs01 - rhs11;\n        Matrix s1 = lhs00 + lhs01;\n        Matrix s2 = lhs10 + lhs11;\n        Matrix s3 = rhs10 - rhs00;\n        Matrix s4 = lhs00 + lhs11;\n        Matrix s5 = rhs00 + rhs11;\n        Matrix s6 = lhs01 - lhs11;\n        Matrix s7 = rhs10 + rhs11;\n        Matrix s8 = lhs00 - lhs10;\n        Matrix s9 = rhs00 + rhs01;\n\n        //! step 3\n        Matrix p0 = square_matrix_multiply_strassen(lhs00,  s0);\n        Matrix p1 = square_matrix_multiply_strassen(s1, rhs11);\n        Matrix p2 = square_matrix_multiply_strassen(s2, rhs00);\n        Matrix p3 = square_matrix_multiply_strassen(lhs11,  s3);\n        Matrix p4 = square_matrix_multiply_strassen(s4, s5);\n        Matrix p5 = square_matrix_multiply_strassen(s6, s7);\n        Matrix p6 = square_matrix_multiply_strassen(s8, s9);\n\n        //! step 4 recurssion\n        project(ret,r0,r0) = p4 + p3 - p1 + p5;\n        project(ret,r0,r1) = p0 + p1;\n        project(ret,r1,r0) = p2 + p3;\n        project(ret,r1,r1) = p4 + p0 - p2 - p6;\n    }\n    return ret;\n}\n\n}}//namespace\n#endif // SQUARE_MATRIX_MULTIPLY_H\n\n//! @test  all three functions above\n//!\n//#include <iostream>\n//#include <boost/numeric/ublas/io.hpp>\n//#include \"square_matrix_multiply.hpp\"\n\n//int main ()\n//{\n//    using namespace boost::numeric::ublas;\n//    matrix<int> lhs(2,2), rhs(2,2);\n\n//    lhs(0,0) = 1;\n//    lhs(0,1) = 3;\n//    lhs(1,0) = 7;\n//    lhs(1,1) = 5;\n\n//    rhs(0,0) = 6;\n//    rhs(0,1) = 8;\n//    rhs(1,0) = 4;\n//    rhs(1,1) = 2;\n\n//    std::cout << clrs::ch4::square_matrix_multiply_recursive(lhs,rhs)  << std::endl;\n//    std::cout << clrs::ch4::square_matrix_multiply(lhs,rhs)            << std::endl;\n//    std::cout << clrs::ch4::square_matrix_multiply_strassen(lhs,rhs)   << std::endl;\n//}\n//! @output\n//!\n//[2,2]((18,14),(62,66))\n//[2,2]((18,14),(62,66))\n//[2,2]((18,14),(62,66))\n", "meta": {"hexsha": "d7779f7ca1d3ba91c0ff8e486044ca1b765ad5e5", "size": 6272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch04/square_matrix_multiply.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": "ch04/square_matrix_multiply.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": "ch04/square_matrix_multiply.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": 29.308411215, "max_line_length": 86, "alphanum_fraction": 0.5837053571, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.5953327254415763}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\tMatrixXd m(2, 2);\n\tm(0, 0) = 3;\n\tm(1, 0) = 2.5; // row, col\n\tm(0, 1) = -1;\n\tm(1, 1) = m(1, 0) + m(0, 1);\n\tstd::cout << \"Example 01: \" << std::endl;\n\tstd::cout << m << std::endl;\n\n\t{\n\t\tstd::cout << \"Example 02: Size set at run time\" << std::endl;\n\t\tMatrixXd m = MatrixXd::Random(3, 3);\n\t\tm = (m + MatrixXd::Constant(3, 3, 1.2)) * 50;\n\t\tcout << \"m = \" << endl << m << endl;\n\t\tVectorXd v(3);\n\t\tv << 1, 2, 3;\n\t\tcout << \"m * v = \" << endl << m * v << endl;\n\t}\n\t{\n\t\tstd::cout << \"Example 02: Size set at compile time\" << std::endl;\n\t\tMatrix3d m = Matrix3d::Random();\n\t\tm = (m + Matrix3d::Constant(1.2)) * 50;\n\t\tcout << \"m = \" << endl << m << endl;\n\t\tVector3d v(1, 2, 3);\n\t\tcout << \"m * v = \" << endl << m * v << endl;\n\t}\n\tsystem(\"pause\");\n}\n", "meta": {"hexsha": "c9293001df0d0b4b75fe55fcf77e816920a36488", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/getting_started/getting_started.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/getting_started/getting_started.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/getting_started/getting_started.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": 23.9714285714, "max_line_length": 67, "alphanum_fraction": 0.5077473182, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5952114902074727}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\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/vector_expression.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_vector.hpp>\n\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n\nint main() {\n    using namespace boost::numeric::ublas;\n    matrix<int> m1 (5,5);\n    matrix<int> m2 (5,5);\n    matrix<int> m3 (5,5);\n    vector<int> v (5);\n    vector<int> v1 (5);\n    int i;\n\n    for(i=0;i<m1.size1();i++){\n        m1 (i,0) = 0;\n        m1 (i,1) = 0;\n        m1 (i,2) = 3;\n        m1 (i,3) = 6;\n        m1 (i,4) = 5;\n    }\n    std::cout<<m1<<std::endl;\n    \n    identity_matrix<int> m_temp (5);\n    std::cout<<m_temp<<std::endl;\n\n    m2=m_temp+m1;\n    std::cout<<m2<<std::endl;\n\n    v (0) = 1; \n    v (1) = 1;\n    v (2) = 9;\n    v (3) = 5;\n    v (4) = 8;\n\n    axpy_prod(m2,v,v1,true);\n    std::cout << v1 <<std::endl;\n    std::cout << inner_prod(v, trans(v)) << std::endl;\n    std::cout << m1+m2 << std::endl;\n\n/* KOD ZA INVERZ MATRICE NIJE MOJ ORIGINALAN RAD, IDEJA I DIJELOVI KODA PREUZETI SU SA STRANICA\n    uBLAS REPOZITORIJA KOJI SLUŽBENO NIJE ODRŽAVAN OD STRANE ADMINISTRATORA \n    ALGORITAM I RJEŠENJE U NJEMU REFERENCIRANI SU NA:\n    Reference: Numerical Recipies in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery. */\n\n    matrix<double> m2_copy (5, 5);\n    m2_copy=m2;\n\n    permutation_matrix<double> pm(m2_copy.size1());\n    \n    matrix <double> inverse(5,5);\n    for (int i = 0; i < inverse.size1 (); ++ i)\n        for (int j = 0; j < inverse.size2 (); ++ j)\n            if(i==j) inverse(i,j) = 1;\n    \n    int res = lu_factorize(m2_copy, pm);\n    lu_substitute(m2_copy, pm, inverse);\n    \n    std::cout << inverse << std::endl;      \n\n\n    return 0;\n\n}", "meta": {"hexsha": "689d23f751fe22a00545adac67acb436914f8ae8", "size": 1941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LAB_07/Task1/viktor_horvat.cpp", "max_stars_repo_name": "vhorvat/psr_FER", "max_stars_repo_head_hexsha": "18e05e127cc41a4102b3578ff5986575ab5e5540", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LAB_07/Task1/viktor_horvat.cpp", "max_issues_repo_name": "vhorvat/psr_FER", "max_issues_repo_head_hexsha": "18e05e127cc41a4102b3578ff5986575ab5e5540", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LAB_07/Task1/viktor_horvat.cpp", "max_forks_repo_name": "vhorvat/psr_FER", "max_forks_repo_head_hexsha": "18e05e127cc41a4102b3578ff5986575ab5e5540", "max_forks_repo_licenses": ["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.9583333333, "max_line_length": 95, "alphanum_fraction": 0.6007212777, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5951741301994553}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP\n\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits.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/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.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\ntemplate <typename T>\nint spherical_side_formula(T const& lambda1, T const& delta1,\n                           T const& lambda2, T const& delta2,\n                           T const& lambda, T const& delta)\n{\n    // Create temporary points (vectors) on unit a sphere\n    T const cos_delta1 = cos(delta1);\n    T const c1x = cos_delta1 * cos(lambda1);\n    T const c1y = cos_delta1 * sin(lambda1);\n    T const c1z = sin(delta1);\n\n    T const cos_delta2 = cos(delta2);\n    T const c2x = cos_delta2 * cos(lambda2);\n    T const c2y = cos_delta2 * sin(lambda2);\n    T const c2z = sin(delta2);\n\n    // (Third point is converted directly)\n    T const cos_delta = cos(delta);\n\n    // Apply the \"Spherical Side Formula\" as presented on my blog\n    T const dist\n        = (c1y * c2z - c1z * c2y) * cos_delta * cos(lambda)\n        + (c1z * c2x - c1x * c2z) * cos_delta * sin(lambda)\n        + (c1x * c2y - c1y * c2x) * sin(delta);\n\n    T zero = T();\n    return dist > zero ? 1\n        : dist < zero ? -1\n        : 0;\n}\n\n}\n#endif // DOXYGEN_NO_DETAIL\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 spherical_side_formula\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 promote_floating_point\n            <\n                typename select_calculation_type_alt\n                    <\n                        CalculationType,\n                        P1, P2, P\n                    >::type\n            >::type calculation_type;\n\n        calculation_type const lambda1 = get_as_radian<0>(p1);\n        calculation_type const delta1 = get_as_radian<1>(p1);\n        calculation_type const lambda2 = get_as_radian<0>(p2);\n        calculation_type const delta2 = get_as_radian<1>(p2);\n        calculation_type const lambda = get_as_radian<0>(p);\n        calculation_type const delta = get_as_radian<1>(p);\n\n        return detail::spherical_side_formula(lambda1, delta1,\n                                              lambda2, delta2,\n                                              lambda, delta);\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\n/*template <typename CalculationType>\nstruct default_strategy<spherical_polar_tag, CalculationType>\n{\n    typedef spherical_side_formula<CalculationType> type;\n};*/\n\ntemplate <typename CalculationType>\nstruct default_strategy<spherical_equatorial_tag, CalculationType>\n{\n    typedef spherical_side_formula<CalculationType> type;\n};\n\ntemplate <typename CalculationType>\nstruct default_strategy<geographic_tag, CalculationType>\n{\n    typedef spherical_side_formula<CalculationType> type;\n};\n\n}\n#endif\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_SSF_HPP\n", "meta": {"hexsha": "81f3205e906bd93cab0ec2a99ddd36242ea8a64b", "size": 4001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/spherical/ssf.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/geometry/strategies/spherical/ssf.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": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T02:48:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:41:52.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/strategies/spherical/ssf.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": 28.5785714286, "max_line_length": 79, "alphanum_fraction": 0.6755811047, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5951406869050804}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include <polyfem/RBFWithQuadratic.hpp>\n#include <polyfem/Types.hpp>\n#include <polyfem/MatrixUtils.hpp>\n#include <polyfem/Logger.hpp>\n\n#include <igl/Timer.h>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <fstream>\n#include <array>\n////////////////////////////////////////////////////////////////////////////////\n\n// #define VERBOSE\n\nusing namespace polyfem;\n\nnamespace\n{\n\n\t// Harmonic kernel\n\tdouble kernel(const bool is_volume, const double r)\n\t{\n\t\tif (r < 1e-8)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (is_volume)\n\t\t{\n\t\t\treturn 1 / r;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn log(r);\n\t\t}\n\t}\n\n\tdouble kernel_prime(const bool is_volume, const double r)\n\t{\n\t\tif (r < 1e-8)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (is_volume)\n\t\t{\n\t\t\treturn -1 / (r * r);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 1 / r;\n\t\t}\n\t}\n\n\t// Biharmonic kernel (2d only)\n\t// double kernel(const bool is_volume, const double r) {\n\t// \tassert(!is_volume);\n\t// \tif (r < 1e-8) { return 0; }\n\n\t// \treturn r * r * (log(r)-1);\n\t// }\n\n\t// double kernel_prime(const bool is_volume, const double r) {\n\t// \tassert(!is_volume);\n\t// \tif (r < 1e-8) { return 0; }\n\n\t// \treturn r * ( 2 * log(r) - 1);\n\t// }\n\n} // anonymous namespace\n\n////////////////////////////////////////////////////////////////////////////////\n\n//output is std::array<Eigen::MatrixXd, 5> &strong rhs(q(x_i) er)\nvoid RBFWithQuadratic::setup_monomials_strong_2d(const int dim, const AssemblerUtils &assembler, const std::string &assembler_name, const Eigen::MatrixXd &pts, const QuadratureVector &da, std::array<Eigen::MatrixXd, 5> &strong)\n{\n\t//a(u,v) = a(q er, phi_j es) = <rhs(q(x_i) er) , phi_j(x_i) es >\n\t// (not a(phi_j es, q er))\n\n\tDiffScalarBase::setVariableCount(2);\n\tAutodiffHessianPt pt(dim);\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tstrong[i].resize(dim * dim, pts.rows());\n\t\tstrong[i].setZero();\n\t}\n\n\tEigen::MatrixXd tmp;\n\n\tfor (int i = 0; i < pts.rows(); ++i)\n\t{\n\t\t//loop for er\n\t\tfor (int d = 0; d < dim; ++d)\n\t\t{\n\t\t\tpt((d + 1) % dim) = AutodiffScalarHessian(0);\n\t\t\t//for d = 0 pt(q, 0), for d = 1 pt=(0, q)\n\n\t\t\t//x\n\t\t\tpt(d) = AutodiffScalarHessian(0, pts(i, 0));\t //pt=(x, 0) or pt=(0, x)\n\t\t\ttmp = assembler.compute_rhs(assembler_name, pt); //in R^dim\n\t\t\tfor (int d1 = 0; d1 < dim; ++d1)\n\t\t\t\tstrong[0](d * dim + d1, i) = tmp(d1) * da(i);\n\n\t\t\t//y\n\t\t\tpt(d) = AutodiffScalarHessian(1, pts(i, 1));\n\t\t\ttmp = assembler.compute_rhs(assembler_name, pt);\n\t\t\tfor (int d1 = 0; d1 < dim; ++d1)\n\t\t\t\tstrong[1](d * dim + d1, i) = tmp(d1) * da(i);\n\n\t\t\t//xy\n\t\t\tpt(d) = AutodiffScalarHessian(0, pts(i, 0)) * AutodiffScalarHessian(1, pts(i, 1));\n\t\t\ttmp = assembler.compute_rhs(assembler_name, pt);\n\t\t\tfor (int d1 = 0; d1 < dim; ++d1)\n\t\t\t\tstrong[2](d * dim + d1, i) = tmp(d1) * da(i);\n\n\t\t\t//x^2\n\t\t\tpt(d) = AutodiffScalarHessian(0, pts(i, 0)) * AutodiffScalarHessian(0, pts(i, 0));\n\t\t\ttmp = assembler.compute_rhs(assembler_name, pt);\n\t\t\tfor (int d1 = 0; d1 < dim; ++d1)\n\t\t\t\tstrong[3](d * dim + d1, i) = tmp(d1) * da(i);\n\n\t\t\t//y^2\n\t\t\tpt(d) = AutodiffScalarHessian(1, pts(i, 1)) * AutodiffScalarHessian(1, pts(i, 1));\n\t\t\ttmp = assembler.compute_rhs(assembler_name, pt);\n\t\t\tfor (int d1 = 0; d1 < dim; ++d1)\n\t\t\t\tstrong[4](d * dim + d1, i) = tmp(d1) * da(i);\n\t\t}\n\t}\n}\n\nvoid RBFWithQuadratic::setup_monomials_vals_2d(const int star_index, const Eigen::MatrixXd &pts, ElementAssemblyValues &vals)\n{\n\tassert(star_index + 5 <= vals.basis_values.size());\n\t//x\n\tvals.basis_values[star_index + 0].val = pts.col(0);\n\tvals.basis_values[star_index + 0].grad = Eigen::MatrixXd(pts.rows(), pts.cols());\n\tvals.basis_values[star_index + 0].grad.col(0).setOnes();\n\tvals.basis_values[star_index + 0].grad.col(1).setZero();\n\n\t//y\n\tvals.basis_values[star_index + 1].val = pts.col(1);\n\tvals.basis_values[star_index + 1].grad = Eigen::MatrixXd(pts.rows(), pts.cols());\n\tvals.basis_values[star_index + 1].grad.col(0).setZero();\n\tvals.basis_values[star_index + 1].grad.col(1).setOnes();\n\n\t//xy\n\tvals.basis_values[star_index + 2].val = pts.col(0).array() * pts.col(1).array();\n\tvals.basis_values[star_index + 2].grad = Eigen::MatrixXd(pts.rows(), pts.cols());\n\tvals.basis_values[star_index + 2].grad.col(0) = pts.col(1);\n\tvals.basis_values[star_index + 2].grad.col(1) = pts.col(0);\n\n\t//x^2\n\tvals.basis_values[star_index + 3].val = pts.col(0).array() * pts.col(0).array();\n\tvals.basis_values[star_index + 3].grad = Eigen::MatrixXd(pts.rows(), pts.cols());\n\tvals.basis_values[star_index + 3].grad.col(0) = 2 * pts.col(0);\n\tvals.basis_values[star_index + 3].grad.col(1).setZero();\n\n\t//y^2\n\tvals.basis_values[star_index + 4].val = pts.col(1).array() * pts.col(1).array();\n\tvals.basis_values[star_index + 4].grad = Eigen::MatrixXd(pts.rows(), pts.cols());\n\tvals.basis_values[star_index + 4].grad.col(0).setZero();\n\tvals.basis_values[star_index + 4].grad.col(1) = 2 * pts.col(1);\n\n\tfor (size_t i = star_index; i < star_index + 5; ++i)\n\t{\n\t\tvals.basis_values[i].grad_t_m = vals.basis_values[i].grad;\n\t}\n\n\t// for(size_t i = star_index; i < star_index + 5; ++i)\n\t// {\n\t// \tvals.basis_values[i].grad_t_m = Eigen::MatrixXd(pts.rows(), pts.cols());\n\t// \tfor(int k = 0; k < vals.jac_it.size(); ++k)\n\t// \t\tvals.basis_values[i].grad_t_m.row(k) = vals.basis_values[i].grad.row(k) * vals.jac_it[k];\n\t// }\n}\n\nRBFWithQuadratic::RBFWithQuadratic(\n\tconst AssemblerUtils &assembler,\n\tconst std::string &assembler_name,\n\tconst Eigen::MatrixXd &centers,\n\tconst Eigen::MatrixXd &collocation_points,\n\tconst Eigen::MatrixXd &local_basis_integral,\n\tconst Quadrature &quadr,\n\tEigen::MatrixXd &rhs,\n\tbool with_constraints)\n\t: centers_(centers)\n{\n\t// centers_.resize(0, centers.cols());\n\tcompute_weights(assembler, assembler_name, collocation_points, local_basis_integral, quadr, rhs, with_constraints);\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::basis(const int local_index, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const\n{\n\tEigen::MatrixXd tmp;\n\tbases_values(samples, tmp);\n\tval = tmp.col(local_index);\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::grad(const int local_index, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const\n{\n\tEigen::MatrixXd tmp;\n\tconst int dim = centers_.cols();\n\tval.resize(samples.rows(), dim);\n\tfor (int d = 0; d < dim; ++d)\n\t{\n\t\tbases_grads(d, samples, tmp);\n\t\tval.col(d) = tmp.col(local_index);\n\t}\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvoid RBFWithQuadratic::bases_values(const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const\n{\n\t// Compute A\n\tEigen::MatrixXd A;\n\tcompute_kernels_matrix(samples, A);\n\n\t// Multiply by the weights\n\tval = A * weights_;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::bases_grads(const int axis, const Eigen::MatrixXd &samples, Eigen::MatrixXd &val) const\n{\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = (is_volume() ? 3 : 2);\n\n\t// Compute ∇xA\n\tEigen::MatrixXd A_prime(samples.rows(), num_kernels + 1 + dim + dim * (dim + 1) / 2);\n\tA_prime.setZero();\n\n\tfor (int j = 0; j < num_kernels; ++j)\n\t{\n\t\tA_prime.col(j) = (samples.rowwise() - centers_.row(j)).rowwise().norm().unaryExpr([this](double x) { return kernel_prime(is_volume(), x) / x; });\n\t\tA_prime.col(j) = (samples.col(axis).array() - centers_(j, axis)) * A_prime.col(j).array();\n\t}\n\t// Linear terms\n\tA_prime.middleCols(num_kernels + 1 + axis, 1).setOnes();\n\t// Mixed terms\n\tif (dim == 2)\n\t{\n\t\tA_prime.col(num_kernels + 1 + dim) = samples.col(1 - axis);\n\t}\n\telse\n\t{\n\t\tA_prime.col(num_kernels + 1 + dim + axis) = samples.col((axis + 1) % dim);\n\t\tA_prime.col(num_kernels + 1 + dim + (axis + 2) % dim) = samples.col((axis + 2) % dim);\n\t}\n\t// Quadratic terms\n\tA_prime.rightCols(dim).col(axis) = 2.0 * samples.col(axis);\n\n\t// Apply weights\n\tval = A_prime * weights_;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// For each FEM basis φ that is nonzero on the element E, we want to\n// solve the least square system A w = rhs, where:\n//     ┏                                     ┓\n//     ┃ ψ_k(pi) ... 1 xi yi xi*yi xi^2 yi^2 ┃\n// A = ┃   ┊        ┊  ┊  ┊   ┊    ┊    ┊    ┃ ∊ ℝ^{#S x (#K+1+dim+dim*(dim+1)/2)}\n//     ┃   ┊        ┊  ┊  ┊   ┊    ┊    ┊    ┃\n//     ┗                                     ┛\n//     ┏                                 ┓^⊤\n// w = ┃ w_k ... a00 a10 a01 a11 a20 a02 ┃   ∊ ℝ^{#K+1+dim+dim*(dim+1)/2}\n//     ┗                                 ┛\n// - A is the RBF kernels evaluated over the collocation points (#S)\n// - b is the expected value of the basis sampled on the boundary (#S)\n// - w is the weight of the kernels defining the basis\n// - pi = (xi, yi) is the i-th collocation point\n//\n// Moreover, we want to impose a constraint on the weight vector w so that each\n// monomial Q(x,y) = x^α*y^β with α+β <= 2 is in the span of the FEM bases {φ_j}_j.\n//\n// In the case of Laplace's equation, we recall the weak form of the PDE as:\n//\n//   Find u such that: ∫_Ω Δu v = - ∫_Ω ∇u·∇v   ∀ v\n//\n// For our bases to exactly represent a monomial Q(x,y), it means that its\n// approximation by the finite element bases {φ_j}_j must be equal to Q(x,y).\n// In particular, for any φ_j that is nonzero on the polyhedral element E, we must have:\n//\n//   ∫_{𝘅 in Ω} ΔQ(𝘅) φ_j(𝘅) d𝘅  = - ∫_{𝘅 \\in Ω} ∇Q(𝘅)·∇φ_j(𝘅) d𝘅     (1)\n//\n// Now, for each of the 5 non-constant monomials (9 in 3D), we need to compute\n// Δ(x^α*y^β). For (α,β) ∊ {(1,0), (0,1), (1,1), (2,0), (0,2)}, this yields\n// the following equalities:\n//\n//     Δx  = 0      (2a)\n//     Δy  = 0      (2b)\n//     Δxy = 0      (2c)\n//     Δx² = 1      (2d)\n//     Δy² = 1      (2e)\n//\n// If we plug these back into (1), and split the integral between the polyhedral\n// element E and Ω\\E, we obtain the following constraints:\n//\n// ∫_E ∇Q·∇φ_j + ∫_E ΔQ φ_j = - ∫_{Ω\\E} ∇Q·∇φ_j - ∫_{Ω\\E} ΔQ φ_j    (3)\n//\n// Note that the right-hand side of (3) is already known, since no two polyhedral\n// cells are adjacent to each other, and the bases overlapping a polyhedron vanish\n// on the boundary of the domain ∂Ω. This right-hand side is computed in advance\n// and passed to our functions as in argument `local_basis_integral`.\n//\n// The left-hand side of equation (3) reduces to the following (in 2D):\n//\n//     ∫_E ∇x(φ_j) = c10                       (4a)\n//     ∫_E ∇y(φ_j) = c01                       (4b)\n//     ∫_E (y·∇x(φ_j) + y·∇x(φ_jj)) = c11      (4c)\n//     ∫_E 2x·∇x(φ_j) + ∫_E 2 φ_j = c20        (4d)\n//     ∫_E 2y·∇y(φ_j) + ∫_E 2 φ_j = c02        (4e)\n//\n// The next step is to express the basis φ_j in terms of the harmonic kernels and\n// quadratic polynomials:\n//\n//     φ_j(x,y) = Σ_k w_k ψ_k(x,y) + a00 + a10*x + a01*y + a11*x*y + a20*x² + a02*y²\n//\n// The five equations in (4) become:\n//\n//\t\tΣ_j w_k ∫∇x(ψ_k) = ∫ Δ q10  (Σ_j w_k (ψ_k) + a00) + Σ_j w_k ∫∇q10 . ∇(ψ_k + a00)\n//    Σ_j w_k ∫∇x(ψ_k) + a10 |E| + a11 ∫y + a20 ∫2x = c10\n//    Σ_j w_k ∫∇y(ψ_k) + a01 |E| + a11 ∫x + a02 ∫2y = c01\n//    Σ_j w_k (∫y·∇x(ψ_k) + ∫x·∇y(ψ_k)) + a10 ∫y + a01 ∫x + a11 (∫x²+∫y²) + a20 2∫xy + a02 2∫xy = c11\n//    Σ_j w_k (2∫x·∇x(ψ_k) + 2ψ_k) + a10 4∫x + a01 2∫y + a11 4∫xy + a20 6∫x² + a02 2∫y² = c20\n//    Σ_j w_k (2∫y·∇y(ψ_k) + 2ψ_k) + a10 2∫x + a01 4∫y + a11 4∫xy + a20 2∫x² + a02 6∫y² = c02\n//  \tΣ_j w_k (2∫y·∇y(ψ_k) + 2ψ_k) = ∫ Δ q20  (Σ_j w_k (ψ_k) + a00) + Σ_j w_k ∫∇q20 . ∇(ψ_k + a00) = ∫ -2  (Σ_j w_k (ψ_k) + a00) + Σ_j w_k ∫2x ∇x(ψ_k)\n//\n// This system gives us a relationship between the fives a10, a01, a11, a20, a02\n// and the rest of the w_k + a constant translation term. We can write down the\n// corresponding system:\n//\n//       a10   a01   a11   a20   a02\n//     ┏                              ┓             ┏     ┓\n//     ┃ |E|         ∫y    2∫x        ┃             ┃ w_k ┃\n//     ┃                              ┃             ┃  ┊  ┃\n//     ┃       |E|   ∫x          2∫y  ┃             ┃  ┊  ┃\n//     ┃                              ┃             ┃  ┊  ┃\n// M = ┃  ∫y   ∫x  ∫x²+∫y² 2∫xy  2∫xy ┃ = \\tilde{L} ┃  ┊  ┃ + \\tilde{t}\n//     ┃                              ┃             ┃  ┊  ┃\n//     ┃ 4∫x  2∫y  4∫xy    6∫x²  2∫y² ┃             ┃  ┊  ┃\n//     ┃                              ┃             ┃w_#K ┃\n//     ┃ 2∫x  4∫y  4∫xy    2∫x²  6∫y² ┃             ┃ a00 ┃\n//     ┗                              ┛             ┗     ┛\n//\n// Now, if we want to express w as w = Lv + t, and solve our least-square\n// system as before, we need to invert M and compute L and t in terms of\n// \\tilde{L} and \\tilde{t}\n//\n//     ┏                  ┓\n//     ┃   1              ┃\n//     ┃       1          ┃\n//     ┃          ·       ┃\n// L = ┃             ·    ┃ ∊ ℝ^{ (#K+1+dim+dim*(dim+1)/2) x (#K+1}) }\n//     ┃                1 ┃\n//     ┃ M^{-1} \\tilde{L} ┃\n//     ┗                  ┛\n//     ┏                  ┓\n//     ┃        0         ┃\n//     ┃        ┊         ┃\n// t = ┃        ┊         ┃ ∊ ℝ^{#K+1+dim+dim*(dim+1)/2}\n//     ┃        0         ┃\n//     ┃ M^{-1} \\tilde{t} ┃\n//     ┗                  ┛\n// After solving the new least square system A L v = rhs - A t, we can retrieve\n// w = L v\n//\n////////////////////////////////////////////////////////////////////////////////\n\nvoid RBFWithQuadratic::compute_kernels_matrix(const Eigen::MatrixXd &samples, Eigen::MatrixXd &A) const\n{\n\t// Compute A\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = (is_volume() ? 3 : 2);\n\n\tA.resize(samples.rows(), num_kernels + 1 + dim + dim * (dim + 1) / 2);\n\tfor (int j = 0; j < num_kernels; ++j)\n\t{\n\t\tA.col(j) = (samples.rowwise() - centers_.row(j)).rowwise().norm().unaryExpr([this](double x) { return kernel(is_volume(), x); });\n\t}\n\tA.col(num_kernels).setOnes();\t\t\t\t  // constant term\n\tA.middleCols(num_kernels + 1, dim) = samples; // linear terms\n\tif (dim == 2)\n\t{\n\t\tA.middleCols(num_kernels + dim + 1, 1) = samples.rowwise().prod(); // mixed terms\n\t}\n\telse if (dim == 3)\n\t{\n\t\tA.middleCols(num_kernels + dim + 1, 3) = samples;\n\t\tA.middleCols(num_kernels + dim + 1 + 0, 1).array() *= samples.col(1).array();\n\t\tA.middleCols(num_kernels + dim + 1 + 1, 1).array() *= samples.col(2).array();\n\t\tA.middleCols(num_kernels + dim + 1 + 2, 1).array() *= samples.col(0).array();\n\t}\n\tA.rightCols(dim) = samples.array().square(); // quadratic terms\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::compute_constraints_matrix_2d_old(\n\tconst int num_bases,\n\tconst Quadrature &quadr,\n\tconst Eigen::MatrixXd &local_basis_integral,\n\tEigen::MatrixXd &L,\n\tEigen::MatrixXd &t) const\n{\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = centers_.cols();\n\tassert(dim == 2);\n\n\t// K_cst = ∫ψ_k\n\t// K_lin = ∫∇x(ψ_k), ∫∇y(ψ_k)\n\t// K_mix = ∫y·∇x(ψ_k), ∫x·∇y(ψ_k)\n\t// K_sqr = ∫x·∇x(ψ_k), ∫y·∇y(ψ_k)\n\tEigen::VectorXd K_cst = Eigen::VectorXd::Zero(num_kernels);\n\tEigen::MatrixXd K_lin = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tEigen::MatrixXd K_mix = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tEigen::MatrixXd K_sqr = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tfor (int j = 0; j < num_kernels; ++j)\n\t{\n\t\t// ∫∇x(ψ_k)(p) = Σ_q (xq - xk) * 1/r * h'(r) * wq\n\t\t// - xq is the x coordinate of the q-th quadrature point\n\t\t// - wq is the q-th quadrature weight\n\t\t// - r is the distance from pq to the kernel center\n\t\t// - h is the RBF kernel (scalar function)\n\t\tfor (int q = 0; q < quadr.points.rows(); ++q)\n\t\t{\n\t\t\tconst RowVectorNd p = quadr.points.row(q) - centers_.row(j);\n\t\t\tconst double r = p.norm();\n\t\t\tconst RowVectorNd gradPhi = p * kernel_prime(is_volume(), r) / r * quadr.weights(q);\n\t\t\tK_cst(j) += kernel(is_volume(), r) * quadr.weights(q);\n\t\t\tK_lin.row(j) += gradPhi;\n\t\t\tK_mix(j, 0) += quadr.points(q, 1) * gradPhi(0);\n\t\t\tK_mix(j, 1) += quadr.points(q, 0) * gradPhi(1);\n\t\t\tK_sqr.row(j) += (quadr.points.row(q).array() * gradPhi.array()).matrix();\n\t\t}\n\t}\n\n\t// I_lin = ∫x, ∫y\n\t// I_mix = ∫xy\n\t// I_sqr = ∫x², ∫y²\n\tEigen::RowVectorXd I_lin = (quadr.points.array().colwise() * quadr.weights.array()).colwise().sum();\n\tEigen::RowVectorXd I_mix = (quadr.points.rowwise().prod().array() * quadr.weights.array()).colwise().sum();\n\tEigen::RowVectorXd I_sqr = (quadr.points.array().square().colwise() * quadr.weights.array()).colwise().sum();\n\tdouble volume = quadr.weights.sum();\n\n\t// std::cout << I_lin << std::endl;\n\t// std::cout << I_mix << std::endl;\n\t// std::cout << I_sqr << std::endl;\n\n\t// Compute M\n\tEigen::Matrix<double, 5, 5> M;\n\tM << volume, 0, I_lin(1), 2 * I_lin(0), 0,\n\t\t0, volume, I_lin(0), 0, 2 * I_lin(1),\n\t\tI_lin(1), I_lin(0), I_sqr(0) + I_sqr(1), 2 * I_mix(0), 2 * I_mix(0),\n\t\t4 * I_lin(0), 2 * I_lin(1), 4 * I_mix(0), 6 * I_sqr(0), 2 * I_sqr(1),\n\t\t2 * I_lin(0), 4 * I_lin(1), 4 * I_mix(0), 2 * I_sqr(0), 6 * I_sqr(1);\n\tEigen::FullPivLU<Eigen::Matrix<double, 5, 5>> lu(M);\n\tassert(lu.isInvertible());\n\n\t// show_matrix_stats(M);\n\n\t// Compute L\n\tL.resize(num_kernels + 1 + dim + dim * (dim + 1) / 2, num_kernels + 1);\n\tL.setZero();\n\tL.diagonal().setOnes();\n\n\tL.block(num_kernels + 1, 0, dim, num_kernels) = -K_lin.transpose();\n\tL.block(num_kernels + 1 + dim, 0, 1, num_kernels) = -K_mix.transpose().colwise().sum();\n\tL.block(num_kernels + 1 + dim + 1, 0, dim, num_kernels) = -2.0 * (K_sqr.colwise() + K_cst).transpose();\n\tL.bottomRightCorner(dim, 1).setConstant(-2.0 * volume);\n\t// j \\in [0, 4]\n\t// i \\in [0, num_kernels]\n\t// ass_val = [q_10, q_01, q_11, q_20, q_02, psi_0, ..., psi_k]\n\n\t// strong rows is the evaluation at quadrature points\n\t// strong.col(0) = pde(q_10) (probably 0)\n\t// strong.col(4) = pde(q_02) (it is 2 for laplacian)\n\t//L.block(num_kernels + 1 + i, j) =  +/- assembler.assemble(ass_val, j, 5 + i) +/- (strong.col(j).array() * ass_val.basis_values[5+i].val.array() * quadr.weights.array()).sum();\n\n\tL.block(num_kernels + 1, 0, 5, num_kernels + 1) = lu.solve(L.block(num_kernels + 1, 0, 5, num_kernels + 1));\n\t// std::cout << L.bottomRightCorner(10, 10) << std::endl;\n\n\t// Compute t\n\tt.resize(L.rows(), num_bases);\n\tt.setZero();\n\tt.bottomRows(5) = local_basis_integral.transpose();\n\tt.bottomRows(5) = lu.solve(weights_.bottomRows(5));\n}\n\nvoid RBFWithQuadratic::compute_constraints_matrix_2d(\n\tconst AssemblerUtils &assembler,\n\tconst std::string &assembler_name,\n\tconst int num_bases,\n\tconst Quadrature &quadr,\n\tconst Eigen::MatrixXd &local_basis_integral,\n\tEigen::MatrixXd &L,\n\tEigen::MatrixXd &t) const\n{\n\tconst int num_kernels = centers_.rows();\n\tconst int space_dim = centers_.cols();\n\tconst int assembler_dim = assembler.is_tensor(assembler_name) ? 2 : 1;\n\tassert(space_dim == 2);\n\n\tstd::array<Eigen::MatrixXd, 5> strong;\n\n\t// ass_val = [q_10, q_01, q_11, q_20, q_02, psi_0, ..., psi_k]\n\tElementAssemblyValues ass_val;\n\tass_val.has_parameterization = false;\n\tass_val.basis_values.resize(5 + num_kernels);\n\n\t//evaluating monomial and grad of monomials at quad points\n\tsetup_monomials_vals_2d(0, quadr.points, ass_val);\n\tsetup_monomials_strong_2d(assembler_dim, assembler, assembler_name, quadr.points, quadr.weights.array(), strong);\n\n\t//evaluating psi and grad psi at quadr points\n\tfor (int j = 0; j < num_kernels; ++j)\n\t{\n\t\tass_val.basis_values[5 + j].val = Eigen::MatrixXd(quadr.points.rows(), 1);\n\t\tass_val.basis_values[5 + j].grad = Eigen::MatrixXd(quadr.points.rows(), quadr.points.cols());\n\n\t\tfor (int q = 0; q < quadr.points.rows(); ++q)\n\t\t{\n\t\t\tconst RowVectorNd p = quadr.points.row(q) - centers_.row(j);\n\t\t\tconst double r = p.norm();\n\n\t\t\tass_val.basis_values[5 + j].val(q) = kernel(is_volume(), r);\n\t\t\tass_val.basis_values[5 + j].grad.row(q) = p * kernel_prime(is_volume(), r) / r;\n\t\t}\n\t}\n\n\tfor (size_t i = 5; i < ass_val.basis_values.size(); ++i)\n\t{\n\t\tass_val.basis_values[i].grad_t_m = ass_val.basis_values[i].grad;\n\t}\n\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, 0, 10, 10> M(5 * assembler_dim, 5 * assembler_dim);\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tfor (int j = 0; j < 5; ++j)\n\t\t{\n\t\t\tconst auto tmp = assembler.local_assemble(assembler_name, ass_val, i, j, quadr.weights);\n\n\t\t\tfor (int d1 = 0; d1 < assembler_dim; ++d1)\n\t\t\t{\n\t\t\t\tfor (int d2 = 0; d2 < assembler_dim; ++d2)\n\t\t\t\t{\n\t\t\t\t\tconst int loc_index = d1 * assembler_dim + d2;\n\t\t\t\t\tM(i * assembler_dim + d1, j * assembler_dim + d2) = tmp(loc_index) + (strong[i].row(loc_index).transpose().array() * ass_val.basis_values[j].val.array()).sum();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::FullPivLU<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, 0, 10, 10>> lu(M);\n\tassert(lu.isInvertible());\n\n\t// Compute L\n\tL.resize((num_kernels + 1 + space_dim + space_dim * (space_dim + 1) / 2) * assembler_dim, (num_kernels + 1) * assembler_dim);\n\tL.setZero();\n\tL.diagonal().setOnes();\n\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tfor (int j = 0; j < num_kernels; ++j)\n\t\t{\n\t\t\tconst auto tmp = assembler.local_assemble(assembler_name, ass_val, i, 5 + j, quadr.weights);\n\t\t\tfor (int d1 = 0; d1 < assembler_dim; ++d1)\n\t\t\t{\n\t\t\t\tfor (int d2 = 0; d2 < assembler_dim; ++d2)\n\t\t\t\t{\n\t\t\t\t\tconst int loc_index = d1 * assembler_dim + d2;\n\t\t\t\t\tL((num_kernels + 1 + i) * assembler_dim + d1, j * assembler_dim + d2) = -tmp(loc_index) - (strong[i].row(loc_index).transpose().array() * ass_val.basis_values[5 + j].val.array()).sum();\n\t\t\t\t\t// L(num_kernels + 1 + i*assembler_dim + d1, j*assembler_dim + d2) =  -assembler.local_assemble(assembler_name, ass_val, i, 5 + j, quadr.weights)(0) - (strong[i].transpose().array() * ass_val.basis_values[5+j].val.array()).sum();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int d1 = 0; d1 < assembler_dim; ++d1)\n\t\t{\n\t\t\tfor (int d2 = 0; d2 < assembler_dim; ++d2)\n\t\t\t{\n\t\t\t\tconst int loc_index = d1 * assembler_dim + d2;\n\t\t\t\tL(num_kernels + 1 + i * assembler_dim + d1, assembler_dim * num_kernels + d2) = -strong[i].row(loc_index).sum();\n\t\t\t}\n\t\t}\n\n\t\t// L(num_kernels + 1 + i*assembler_dim + d1, assembler_dim*num_kernels) =  - strong[i].sum();\n\t}\n\n\tL.block((num_kernels + 1) * assembler_dim, 0, 5 * assembler_dim, (num_kernels + 1) * assembler_dim) = lu.solve(L.block((num_kernels + 1) * assembler_dim, 0, 5 * assembler_dim, (num_kernels + 1) * assembler_dim));\n\n\t// Compute t\n\t//t == weights_\n\tt.resize(L.rows(), num_bases * assembler_dim);\n\tt.setZero();\n\tt.bottomRows(5 * assembler_dim) = lu.solve(local_basis_integral.transpose());\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::compute_constraints_matrix_3d(\n\tconst AssemblerUtils &assembler,\n\tconst std::string &assembler_name,\n\tconst int num_bases,\n\tconst Quadrature &quadr,\n\tconst Eigen::MatrixXd &local_basis_integral,\n\tEigen::MatrixXd &L,\n\tEigen::MatrixXd &t) const\n{\n\tconst int num_kernels = centers_.rows();\n\tconst int dim = centers_.cols();\n\tassert(dim == 3);\n\tassert(local_basis_integral.cols() == 9);\n\n\t// K_cst = ∫ψ_k\n\t// K_lin = ∫∇x(ψ_k), ∫∇y(ψ_k), ∫∇z(ψ_k)\n\t// K_mix = ∫(y·∇x(ψ_k)+x·∇y(ψ_k)), ∫(z·∇y(ψ_k)+y·∇z(ψ_k)), ∫(x·∇z(ψ_k)+z·∇x(ψ_k))\n\t// K_sqr = ∫x·∇x(ψ_k), ∫y·∇y(ψ_k), ∫z·∇z(ψ_k)\n\tEigen::VectorXd K_cst = Eigen::VectorXd::Zero(num_kernels);\n\tEigen::MatrixXd K_lin = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tEigen::MatrixXd K_mix = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tEigen::MatrixXd K_sqr = Eigen::MatrixXd::Zero(num_kernels, dim);\n\tfor (int j = 0; j < num_kernels; ++j)\n\t{\n\t\t// ∫∇x(ψ_k)(p) = Σ_q (xq - xk) * 1/r * h'(r) * wq\n\t\t// - xq is the x coordinate of the q-th quadrature point\n\t\t// - wq is the q-th quadrature weight\n\t\t// - r is the distance from pq to the kernel center\n\t\t// - h is the RBF kernel (scalar function)\n\t\tfor (int q = 0; q < quadr.points.rows(); ++q)\n\t\t{\n\t\t\tconst RowVectorNd p = quadr.points.row(q) - centers_.row(j);\n\t\t\tconst double r = p.norm();\n\t\t\tconst RowVectorNd gradPhi = p * kernel_prime(is_volume(), r) / r * quadr.weights(q);\n\t\t\tK_cst(j) += kernel(is_volume(), r) * quadr.weights(q);\n\t\t\tK_lin.row(j) += gradPhi;\n\t\t\tfor (int d = 0; d < dim; ++d)\n\t\t\t{\n\t\t\t\tK_mix(j, d) += quadr.points(q, (d + 1) % dim) * gradPhi(d) + quadr.points(q, d) * gradPhi((d + 1) % dim);\n\t\t\t}\n\t\t\tK_sqr.row(j) += (quadr.points.row(q).array() * gradPhi.array()).matrix();\n\t\t}\n\t}\n\n\t// I_lin = ∫x, ∫y, ∫z\n\t// I_sqr = ∫x², ∫y², ∫z²\n\t// I_mix = ∫xy, ∫yz, ∫zx\n\tEigen::RowVectorXd I_lin = (quadr.points.array().colwise() * quadr.weights.array()).colwise().sum();\n\tEigen::RowVectorXd I_sqr = (quadr.points.array().square().colwise() * quadr.weights.array()).colwise().sum();\n\tEigen::RowVectorXd I_mix(3);\n\tI_mix(0) = (quadr.points.col(0).array() * quadr.points.col(1).array() * quadr.weights.array()).sum();\n\tI_mix(1) = (quadr.points.col(1).array() * quadr.points.col(2).array() * quadr.weights.array()).sum();\n\tI_mix(2) = (quadr.points.col(2).array() * quadr.points.col(0).array() * quadr.weights.array()).sum();\n\tdouble volume = quadr.weights.sum();\n\n\t// std::cout << I_lin << std::endl;\n\t// std::cout << I_mix << std::endl;\n\t// std::cout << I_sqr << std::endl;\n\n\t// Compute M\n\tEigen::Matrix<double, 9, 9> M;\n\tM << volume, 0, 0, I_lin(1), 0, I_lin(2), 2 * I_lin(0), 0, 0,\n\t\t0, volume, 0, I_lin(0), I_lin(2), 0, 0, 2 * I_lin(1), 0,\n\t\t0, 0, volume, 0, I_lin(1), I_lin(0), 0, 0, 2 * I_lin(2),\n\t\tI_lin(1), I_lin(0), 0, I_sqr(0) + I_sqr(1), I_mix(2), I_mix(1), 2 * I_mix(0), 2 * I_mix(0), 0,\n\t\t0, I_lin(2), I_lin(1), I_mix(2), I_sqr(1) + I_sqr(2), I_mix(0), 0, 2 * I_mix(1), 2 * I_mix(1),\n\t\tI_lin(2), 0, I_lin(0), I_mix(1), I_mix(0), I_sqr(2) + I_sqr(0), 2 * I_mix(2), 0, 2 * I_mix(2),\n\t\t2 * I_lin(0), 0, 0, 2 * I_mix(0), 0, 2 * I_mix(2), 4 * I_sqr(0), 0, 0,\n\t\t0, 2 * I_lin(1), 0, 2 * I_mix(0), 2 * I_mix(1), 0, 0, 4 * I_sqr(1), 0,\n\t\t0, 0, 2 * I_lin(2), 0, 2 * I_mix(1), 2 * I_mix(2), 0, 0, 4 * I_sqr(2);\n\tEigen::Matrix<double, 1, 9> M_rhs;\n\tM_rhs.segment<3>(0) = I_lin;\n\tM_rhs.segment<3>(3) = I_mix;\n\tM_rhs.segment<3>(6) = I_sqr;\n\t// M_rhs << I_lin, I_mix, I_sqr;\n\tM.bottomRows(dim).rowwise() += 2.0 * M_rhs;\n\tEigen::FullPivLU<Eigen::Matrix<double, 9, 9>> lu(M);\n\tassert(lu.isInvertible());\n\n\t// show_matrix_stats(M);\n\n\t// Compute L\n\tL.resize(num_kernels + 1 + dim + dim * (dim + 1) / 2, num_kernels + 1);\n\tL.setZero();\n\tL.diagonal().setOnes();\n\tL.block(num_kernels + 1, 0, dim, num_kernels) = -K_lin.transpose();\n\tL.block(num_kernels + 1 + dim, 0, dim, num_kernels) = -K_mix.transpose();\n\tL.block(num_kernels + 1 + dim + dim, 0, dim, num_kernels) = -2.0 * (K_sqr.colwise() + K_cst).transpose();\n\tL.bottomRightCorner(dim, 1).setConstant(-2.0 * volume);\n\tL.block(num_kernels + 1, 0, 9, num_kernels + 1) = lu.solve(L.block(num_kernels + 1, 0, 9, num_kernels + 1));\n\t// std::cout << L.bottomRightCorner(10, 10) << std::endl;\n\n\t// Compute t\n\tt.resize(L.rows(), num_bases);\n\tt.setZero();\n\tt.bottomRows(9) = local_basis_integral.transpose();\n\tt.bottomRows(9) = lu.solve(weights_.bottomRows(9));\n}\n\n// -----------------------------------------------------------------------------\n\nvoid RBFWithQuadratic::compute_weights(const AssemblerUtils &assembler, const std::string &assembler_name, const Eigen::MatrixXd &samples,\n\t\t\t\t\t\t\t\t\t   const Eigen::MatrixXd &local_basis_integral, const Quadrature &quadr,\n\t\t\t\t\t\t\t\t\t   Eigen::MatrixXd &rhs, bool with_constraints)\n{\n#ifdef VERBOSE\n\tlogger().trace(\"#kernel centers: {}\", centers_.rows());\n\tlogger().trace(\"#collocation points: {}\", samples.rows());\n\tlogger().trace(\"#quadrature points: {}\", quadr.weights.size());\n\tlogger().trace(\"#non-vanishing bases: {}\", rhs.cols());\n#endif\n\n\tif (!with_constraints)\n\t{\n\t\t// Compute A\n\t\tEigen::MatrixXd A;\n\t\tcompute_kernels_matrix(samples, A);\n\n\t\t// Solve the system\n\t\tconst int num_kernels = centers_.rows();\n\t\tlogger().trace(\"-- Solving system of size {}x{}\", num_kernels, num_kernels);\n\t\tweights_ = (A.transpose() * A).ldlt().solve(A.transpose() * rhs);\n\t\tlogger().trace(\"-- Solved!\");\n\n\t\treturn;\n\t}\n\n\tconst int num_bases = rhs.cols();\n\n\t// Compute A\n\tEigen::MatrixXd A;\n\tcompute_kernels_matrix(samples, A);\n\n\t// Compute L and t\n\t// Note that t is stored into `weights_` for memory efficiency reasons\n\tEigen::MatrixXd L;\n\tif (is_volume())\n\t{\n\t\tcompute_constraints_matrix_3d(assembler, assembler_name, num_bases, quadr, local_basis_integral, L, weights_);\n\t}\n\telse\n\t{\n\t\tcompute_constraints_matrix_2d(assembler, assembler_name, num_bases, quadr, local_basis_integral, L, weights_);\n\t}\n\n\t// Compute b = rhs - A t\n\tEigen::MatrixXd b = rhs - A * weights_;\n\n// Solve the system\n#ifdef VERBOSE\n\tlogger().trace(\"-- Solving system of size {}x{}\", L.cols(), L.cols());\n#endif\n\tauto ldlt = (L.transpose() * A.transpose() * A * L).ldlt();\n\tif (ldlt.info() == Eigen::NumericalIssue)\n\t{\n\t\tlogger().error(\"-- WARNING: Numerical issues when solving the harmonic least square.\");\n\t}\n\tweights_ += L * ldlt.solve(L.transpose() * A.transpose() * b);\n#ifdef VERBOSE\n\tlogger().trace(\"-- Solved!\");\n#endif\n\n#ifdef VERBOSE\n\tlogger().trace(\"-- Mean residual: {}\", (A * weights_ - rhs).array().abs().colwise().maxCoeff().mean());\n#endif\n\n#if 0\n\tEigen::MatrixXd MM, x, dx, val;\n\tbasis(0, quadr.points, val);\n\tgrad(0, quadr.points, MM);\n\tint dim = (is_volume() ? 3 : 2);\n\tfor (int d = 0; d < dim; ++d) {\n\t\t// basis(0, quadr.points, x);\n\t\t// auto asd = quadr.points;\n\t\t// asd.col(d).array() += 1e-7;\n\t\t// basis(0, asd, dx);\n\t\t// std::cout << (dx - x) / 1e-7 - MM.col(d) << std::endl;\n\t\tstd::cout << (MM.col(d).array() * quadr.weights.array()).sum() - local_basis_integral(0, d) << std::endl;\n\t\tstd::cout << ((\n\t\t\t\tMM.col((d+1)%dim).array() * quadr.points.col(d).array()\n\t\t\t\t+ MM.col(d).array() * quadr.points.col((d+1)%dim).array()\n\t\t\t) * quadr.weights.array()).sum() - local_basis_integral(0, (dim == 2 ? 2 : (dim+d) )) << std::endl;\n\t\tstd::cout << 2.0 * (\n\t\t\t\t(quadr.points.col(d).array() * MM.col(d).array()\n\t\t\t\t+ val.array())\n\t\t\t* quadr.weights.array()\n\t\t\t).sum() - local_basis_integral(0, (dim == 2 ? (3 + d) : (dim+dim+d))) << std::endl;\n\t}\n#endif\n}\n", "meta": {"hexsha": "6bf099f221d9fed3d507c4c7c4c069da2ef1c4e4", "size": 29431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/function/RBFWithQuadratic.cpp", "max_stars_repo_name": "danielepanozzo/polyfem", "max_stars_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/basis/function/RBFWithQuadratic.cpp", "max_issues_repo_name": "danielepanozzo/polyfem", "max_issues_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/basis/function/RBFWithQuadratic.cpp", "max_forks_repo_name": "danielepanozzo/polyfem", "max_forks_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 36.8347934919, "max_line_length": 234, "alphanum_fraction": 0.5809860351, "num_tokens": 10439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5951406849109068}}
{"text": "//-------------------------------------------------------------------------//\n//\n// Copyright 2017 Sascha Kaden\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 UTILGEO_HPP\n#define UTILGEO_HPP\n\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ippp/types.h>\n#include <ippp/util/UtilVec.hpp>\n\nnamespace ippp {\nnamespace util {\n\nconstexpr double pi() {\n    return 3.141592653589793;\n}\n\nconstexpr double twoPi() {\n    return 3.141592653589793 * 2;\n}\n\nconstexpr double halfPi() {\n    return 3.141592653589793 / 2;\n}\n\nconstexpr double toRad() {\n    return 3.141592653589793 / 180;\n}\n\nconstexpr double toDeg() {\n    return 180 / 3.141592653589793;\n}\n\n/*!\n*  \\brief      Create 2D rotation matrix from rad\n*  \\author     Sascha Kaden\n*  \\param[in]  deg\n*  \\param[out] rotation matrix\n*  \\date       2016-11-15\n*/\nstatic Matrix2 getRotMat2D(const double rad) {\n    Eigen::Rotation2D<double> R(rad);\n    return R.toRotationMatrix();\n}\n\n/*!\n*  \\brief      Create 3D rotation matrix from rad\n*  \\author     Sascha Kaden\n*  \\param[in]  deg in x direction\n*  \\param[in]  deg in y direction\n*  \\param[in]  deg in z direction\n*  \\param[out] rotation matrix\n*  \\date       2016-11-15\n*/\nstatic Matrix3 getRotMat3D(const double radX, const double radY, const double radZ) {\n    Matrix3 R;\n    R = Eigen::AngleAxisd(radX, Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(radY, Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(radZ, Eigen::Vector3d::UnitZ());\n    return R;\n}\n\n/*!\n*  \\brief      Create transformation matrix T from rotation R and translation t\n*  \\author     Sascha Kaden\n*  \\param[in]  rotation matrix\n*  \\param[in]  translatin matrix\n*  \\param[out] transformation matrix\n*  \\date       2016-08-25\n*/\nstatic Transform createTransform(const Matrix3 &R, const Vector3 &t) {\n    Transform T;\n    T = Translation(t) * R;\n    return T;\n}\n\n/*!\n*  \\brief      Decompose transformation matrix T in rotation R and translation t\n*  \\author     Sascha Kaden\n*  \\param[in]  transformation matrix\n*  \\param[out] rotation matrix\n*  \\param[out] translation matrix\n*  \\date       2016-08-25\n*/\nstatic void decomposeT(const Matrix4 &T, Matrix3 &R, Vector3 &t) {\n    R = T.block<3, 3>(0, 0);\n    t = T.block<3, 1>(0, 3);\n}\n\n/*!\n*  \\brief      Convert pose config to transformation matrix\n*  \\author     Sascha Kaden\n*  \\param[in]  pose Vector\n*  \\param[out] transformation matrix\n*  \\date       2016-07-07\n*/\nstatic Transform poseVecToTransform(const Vector6 &pose) {\n    Transform T;\n    T = Translation(Vector3(pose[0], pose[1], pose[2])) * Eigen::AngleAxisd(pose[3], Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(pose[4], Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(pose[5], Eigen::Vector3d::UnitZ());\n    return T;\n}\n\n/*!\n*  \\brief      Convert transformation matrix into poseVec\n*  \\author     Sascha Kaden\n*  \\param[in]  transformation matrix\n*  \\param[out] pose Vector (angles)\n*  \\date       2016-07-07\n*/\nstatic Vector6 transformToVec(const Transform &T) {\n    Vector3 vec(T.translation());\n    Vector3 euler(T.rotation().eulerAngles(0, 1, 2));\n    return util::append<3, 3>(vec, euler);\n}\n\n/*!\n*  \\brief      Compute the normal from the plane of three points.\n*  \\author     Sascha Kaden\n*  \\param[in]  point one\n*  \\param[in]  point two\n*  \\param[in]  point three\n*  \\param[out] normal Vector\n*  \\date       2017-04-07\n*/\nstatic Vector3 computeNormal(const Vector3 &p1, const Vector3 &p2, const Vector3 &p3) {\n    Vector3 v = p2 - p1;\n    Vector3 w = p3 - p1;\n    double nx = (v[1] * w[2]) - (v[2] * w[1]);\n    double ny = (v[2] * w[0]) - (v[0] * w[2]);\n    double nz = (v[0] * w[1]) - (v[1] * w[0]);\n    Vector3 normal(nx, ny, nz);\n    return normal.normalized();\n}\n\n/*!\n*  \\brief      Transforms an AABB with the passed transformations and return the new AABB.\n*  \\details    The new AABB has a larger size as the original and the AABB is no more tight!\n*  \\author     Sascha Kaden\n*  \\param[in]  original AABB\n*  \\param[in]  Transform\n*  \\param[out] transformed AABB\n*  \\date       2017-06-21\n*/\nstatic AABB transformAABB(const AABB &aabb, const Transform &T) {\n    Vector3 min = aabb.min();\n    Vector3 max = aabb.max();\n    Vector4 min4  = util::append<3>(min, 1);\n    Vector4 max4  = util::append<3>(max, 1);\n    min4 = T * min4;\n    max4 = T * max4;\n    return AABB(Vector3(min4[0], min4[1], min4[2]), Vector3(max4[0], max4[1], max4[2]));\n\n//    Vector3 center(T.translation());\n//    Vector3 radius = Vector3::Zero(3, 1);\n//    for (size_t i = 0; i < 3; i++) {\n//        for (size_t j = 0; j < 3; j++) {\n//            center[i] += T(i, j) * aabb.center()[j];\n//            radius[i] += std::abs(T(i, j)) * aabb.diagonal()[j] / 2;\n//        }\n//    }\n//    return AABB(center - radius, center + radius);\n}\n\n/*!\n*  \\brief      Translate an AABB with the passed transformations.\n*  \\details    The new AABB has a larger size as the original and the AABB is no more tight!\n*  \\author     Sascha Kaden\n*  \\param[in]  original aabb\n*  \\param[in]  pair with rotation and transformation\n*  \\param[out] transformed aabb\n*  \\date       2017-06-21\n*/\nstatic AABB translateAABB(const AABB &a, const Transform &T) {\n    AABB result(a);\n    result.translate(T.translation());\n    return result;\n}\n\n/*!\n*  \\brief      Remove duplicate vectors from the passed reference list.\n*  \\author     Sascha Kaden\n*  \\param[in]  list of vectors\n*  \\date       2017-04-07\n*/\nstatic void removeDuplicates(std::vector<Vector3> &vectors) {\n    // sort vector list\n    struct {\n        bool operator()(Vector3 a, Vector3 b) {\n            return a.x() < b.x();\n        }\n    } customCompare;\n    std::sort(vectors.begin(), vectors.end(), customCompare);\n\n    // remove duplicates\n    for (auto vec = vectors.begin(); vec != vectors.end(); ++vec) {\n        int i = 1;\n        while (vec + i != vectors.end() && vec->x() - (vec + i)->x() < 0.01) {\n            if ((*vec - *(vec + i)).squaredNorm() < 0.0001)\n                vectors.erase(vec + i);\n            else\n                ++i;\n        }\n    }\n}\n\n/*!\n*  \\brief      Convert Vec of deg angles to Vec of rad\n*  \\author     Sascha Kaden\n*  \\param[in]  Vector of deg\n*  \\param[out] Vector of rad\n*  \\date       2016-07-07\n*/\ntemplate <unsigned int dim>\nVector<dim> degToRad(Vector<dim> deg) {\n    for (unsigned int i = 0; i < dim; ++i)\n        deg[i] *= toRad();\n    return deg;\n}\n\n/*!\n*  \\brief      Convert Vec of rad angles to Vec of deg\n*  \\author     Sascha Kaden\n*  \\param[in]  Vector of rad\n*  \\param[out] Vector of deg\n*  \\date       2016-07-07\n*/\ntemplate <unsigned int dim>\nVector<dim> radToDeg(Vector<dim> rad) {\n    for (unsigned int i = 0; i < dim; ++i)\n        rad[i] *= toDeg();\n    return rad;\n}\n\n/*!\n*  \\brief      Convert degree to radian\n*  \\author     Sascha Kaden\n*  \\param[in]  deg\n*  \\param[out] rad\n*  \\date       2016-11-16\n*/\nstatic double degToRad(const double deg) {\n    return deg * toRad();\n}\n\n} /* namespace util */\n} /* namespace ippp */\n\n#endif    // UTILGEO_HPP\n", "meta": {"hexsha": "3087ceb9a13bfe92f1769069ac36477cf3720229", "size": 7553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ippp/util/UtilGeo.hpp", "max_stars_repo_name": "tobiaskohlbau/IPPP", "max_stars_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ippp/util/UtilGeo.hpp", "max_issues_repo_name": "tobiaskohlbau/IPPP", "max_issues_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ippp/util/UtilGeo.hpp", "max_forks_repo_name": "tobiaskohlbau/IPPP", "max_forks_repo_head_hexsha": "91432f00b49ea5a83648e3294ad5b4b661dcd284", "max_forks_repo_licenses": ["Apache-2.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.1828358209, "max_line_length": 167, "alphanum_fraction": 0.6075731497, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.595140673460807}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp\n \n [begin_description]\n Implementation of the Runge Kutta Cash Karp 5(4) method. It uses the generic error stepper.\n [end_description]\n \n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 Mario Mulansky\n \n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_CASH_KARP54_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_CASH_KARP54_HPP_INCLUDED\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_error_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/numeric/odeint/util/state_wrapper.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n\n#include <boost/array.hpp>\n\n\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n#ifndef DOXYGEN_SKIP\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_a1 : boost::array< Value , 1 >\n{\n    rk54_ck_coefficients_a1( void )\n    {\n        (*this)[0] = static_cast< Value >( 1 )/static_cast< Value >( 5 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_a2 : boost::array< Value , 2 >\n{\n    rk54_ck_coefficients_a2( void )\n    {\n        (*this)[0] = static_cast<Value>( 3 )/static_cast<Value>( 40 );\n        (*this)[1] = static_cast<Value>( 9 )/static_cast<Value>( 40 );\n    }\n};\n\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_a3 : boost::array< Value , 3 >\n{\n    rk54_ck_coefficients_a3( void )\n    {\n        (*this)[0] = static_cast<Value>( 3 )/static_cast<Value>( 10 );\n        (*this)[1] = static_cast<Value>( -9 )/static_cast<Value>( 10 );\n        (*this)[2] = static_cast<Value>( 6 )/static_cast<Value>( 5 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_a4 : boost::array< Value , 4 >\n{\n    rk54_ck_coefficients_a4( void )\n    {\n        (*this)[0] = static_cast<Value>( -11 )/static_cast<Value>( 54 );\n        (*this)[1] = static_cast<Value>( 5 )/static_cast<Value>( 2 );\n        (*this)[2] = static_cast<Value>( -70 )/static_cast<Value>( 27 );\n        (*this)[3] = static_cast<Value>( 35 )/static_cast<Value>( 27 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_a5 : boost::array< Value , 5 >\n{\n    rk54_ck_coefficients_a5( void )\n    {\n        (*this)[0] = static_cast<Value>( 1631 )/static_cast<Value>( 55296 );\n        (*this)[1] = static_cast<Value>( 175 )/static_cast<Value>( 512 );\n        (*this)[2] = static_cast<Value>( 575 )/static_cast<Value>( 13824 );\n        (*this)[3] = static_cast<Value>( 44275 )/static_cast<Value>( 110592 );\n        (*this)[4] = static_cast<Value>( 253 )/static_cast<Value>( 4096 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_b : boost::array< Value , 6 >\n{\n    rk54_ck_coefficients_b( void )\n    {\n        (*this)[0] = static_cast<Value>( 37 )/static_cast<Value>( 378 );\n        (*this)[1] = static_cast<Value>( 0 );\n        (*this)[2] = static_cast<Value>( 250 )/static_cast<Value>( 621 );\n        (*this)[3] = static_cast<Value>( 125 )/static_cast<Value>( 594 );\n        (*this)[4] = static_cast<Value>( 0 );\n        (*this)[5] = static_cast<Value>( 512 )/static_cast<Value>( 1771 );\n    }\n};\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_db : boost::array< Value , 6 >\n{\n    rk54_ck_coefficients_db( void )\n    {\n        (*this)[0] = static_cast<Value>( 37 )/static_cast<Value>( 378 ) - static_cast<Value>( 2825 )/static_cast<Value>( 27648 );\n        (*this)[1] = static_cast<Value>( 0 );\n        (*this)[2] = static_cast<Value>( 250 )/static_cast<Value>( 621 ) - static_cast<Value>( 18575 )/static_cast<Value>( 48384 );\n        (*this)[3] = static_cast<Value>( 125 )/static_cast<Value>( 594 ) - static_cast<Value>( 13525 )/static_cast<Value>( 55296 );\n        (*this)[4] = static_cast<Value>( -277 )/static_cast<Value>( 14336 );\n        (*this)[5] = static_cast<Value>( 512 )/static_cast<Value>( 1771 ) - static_cast<Value>( 1 )/static_cast<Value>( 4 );\n    }\n};\n\n\ntemplate< class Value = double >\nstruct rk54_ck_coefficients_c : boost::array< Value , 6 >\n{\n    rk54_ck_coefficients_c( void )\n    {\n        (*this)[0] = static_cast<Value>(0);\n        (*this)[1] = static_cast<Value>( 1 )/static_cast<Value>( 5 );\n        (*this)[2] = static_cast<Value>( 3 )/static_cast<Value>( 10 );\n        (*this)[3] = static_cast<Value>( 3 )/static_cast<Value>( 5 );\n        (*this)[4] = static_cast<Value>( 1 );\n        (*this)[5] = static_cast<Value>( 7 )/static_cast<Value>( 8 );\n    }\n};\n#endif\n\n\ntemplate<\n    class State ,\n    class Value = double ,\n    class Deriv = State ,\n    class Time = Value ,\n    class Algebra = typename algebra_dispatcher< State >::algebra_type ,\n    class Operations = typename operations_dispatcher< State >::operations_type ,\n    class Resizer = initially_resizer\n    >\n#ifndef DOXYGEN_SKIP\nclass runge_kutta_cash_karp54 : public explicit_error_generic_rk< 6 , 5 , 5 , 4 ,\n        State , Value , Deriv , Time , Algebra , Operations , Resizer >\n#else \nclass runge_kutta_cash_karp54 : public explicit_error_generic_rk\n#endif\n{\n\npublic:\n#ifndef DOXYGEN_SKIP\n    typedef explicit_error_generic_rk< 6 , 5 , 5 , 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_typ;\n\n    #ifndef DOXYGEN_SKIP\n    typedef typename stepper_base_type::stepper_type stepper_type;\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    #endif\n\n\n    runge_kutta_cash_karp54( const algebra_type &algebra = algebra_type() ) : stepper_base_type(\n        boost::fusion::make_vector( rk54_ck_coefficients_a1<Value>() ,\n                                 rk54_ck_coefficients_a2<Value>() ,\n                                 rk54_ck_coefficients_a3<Value>() ,\n                                 rk54_ck_coefficients_a4<Value>() ,\n                                 rk54_ck_coefficients_a5<Value>() ) ,\n            rk54_ck_coefficients_b<Value>() , rk54_ck_coefficients_db<Value>() , rk54_ck_coefficients_c<Value>() ,\n            algebra )\n    { }\n};\n\n\n/********** DOXYGEN **********/\n\n/**\n * \\class runge_kutta_cash_karp54\n * \\brief The Runge-Kutta Cash-Karp method.\n *\n * The Runge-Kutta Cash-Karp method is one of the standard methods for\n * solving ordinary differential equations, see\n * <a href=\"http://en.wikipedia.org/wiki/Cash%E2%80%93Karp_methods\">en.wikipedia.org/wiki/Cash-Karp_methods</a>.\n * The method is explicit and fulfills the Error Stepper concept. Step size control\n * is provided but continuous output is not available for this method.\n * \n * This class derives from explicit_error_stepper_base and inherits its interface via CRTP (current recurring template pattern).\n * Furthermore, it derivs from explicit_error_generic_rk which is a generic Runge-Kutta algorithm with error estimation.\n * For more details see explicit_error_stepper_base and explicit_error_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    /**\n     * \\fn runge_kutta_cash_karp54::runge_kutta_cash_karp54( const algebra_type &algebra )\n     * \\brief Constructs the runge_kutta_cash_karp54 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#endif // BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_CASH_KARP54_HPP_INCLUDED\n", "meta": {"hexsha": "04bc4719a9186476598375d7133f8801fbca5801", "size": 8676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/runge_kutta_cash_karp54.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/runge_kutta_cash_karp54.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/runge_kutta_cash_karp54.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": 37.3965517241, "max_line_length": 131, "alphanum_fraction": 0.6864914707, "num_tokens": 2260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5950582579599524}}
{"text": "#include <blitz/array.h>\n#include <blitz/timer.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nBZ_DECLARE_STENCIL4(acoustic2D_stencil,P1,P2,P3,c)\n  P3 = 2 * P2 + c * Laplacian2D(P2) - P1;\nBZ_END_STENCIL\n\nint benchmark(int N, int nIterations, int blockSize)\n{\n    Array<float,2> P1, P2, P3, c;\n    allocateArrays(shape(N,N), P1, P2, P3, c);\n\n    // Initial conditions: obviously in a real application these\n    // wouldn't be zeroed...\n    Range I(0,blockSize-1), J(0,blockSize-1);\n\n    P1(I,J) = 0;\n    P2(I,J) = 0;\n    P3(I,J) = 0;\n    c(I,J) = 0;\n\n    for (int i=0; i < nIterations; ++i)\n    {\n        // Apply the stencil object to the arrays\n        applyStencil(acoustic2D_stencil(), P1(I,J), P2(I,J), P3(I,J), c(I,J));\n\n        // Set [P1,P2,P3] <- [P2,P3,P1] to set up for the next\n        // time step\n        cycleArrays(P1,P2,P3);\n    }\n\n    return 0;\n}\n\nint main()\n{\n    Timer timer;\n\n    cout << \"N\\tMflops\" << endl;\n\n    const int blockSize = 27;\n\n    for (int N=2000; N < 2100; ++N)\n    {\n        double stencilPoints = pow(blockSize-2,2.0);\n        int nIterations = 5000;\n\n        timer.start();\n        benchmark(N, nIterations, blockSize);\n        timer.stop();\n\n        double flops = (4 + 7) * stencilPoints * nIterations;\n        double Mflops = flops / timer.elapsedSeconds() / 1.0E+6;\n        cout << N << \"\\t\" << Mflops << endl;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "256b714853ae35afdc11a0946a262fd87b422451", "size": 1360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/stenciln.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/stenciln.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/stenciln.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": 21.935483871, "max_line_length": 78, "alphanum_fraction": 0.5661764706, "num_tokens": 458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5950498017306255}}
{"text": "/**\n * \\file se2_localization_ukfm.cpp\n *\n *  Created on: Dec 10, 2018\n *     \\author: artivis\n *\n *  ---------------------------------------------------------\n *  This file is:\n *  (c) 2021 Jeremie Deray\n *\n *  This file is part of `manif`, a C++ template-only library\n *  for Lie theory targeted at estimation for robotics.\n *  Manif is:\n *  (c) 2018 Jeremie Deray @ IRI-UPC, Barcelona\n *  ---------------------------------------------------------\n *\n *  ---------------------------------------------------------\n *  Demonstration example:\n *\n *  2D Robot localization based on fixed beacons.\n *\n *  See se3_localization.cpp for the 3D equivalent.\n *  See se3_sam.cpp for a more advanced example performing smoothing and mapping.\n *  ---------------------------------------------------------\n *\n *  This demo showcases an application of an Unscented Kalman Filter on Manifold,\n *  based on the paper\n *  'A Code for Unscented Kalman Filtering on Manifolds (UKF-M)'\n *  [https://arxiv.org/pdf/2002.00878.pdf], M. Brossard, A. Barrau and S. Bonnabel.\n *\n *  The following is an abstract of the example hereafter.\n *  Please consult the aforemention paper for better UKF-M reference\n *  and the paper Sola-18, [https://arxiv.org/abs/1812.01537] for general\n *  Lie group reference.\n *\n *\n *  We consider a robot in the plane surrounded by a small\n *  number of punctual landmarks or _beacons_.\n *  The robot receives control actions in the form of axial\n *  and angular velocities, and is able to measure the location\n *  of the beacons w.r.t its own reference frame.\n *\n *  The robot pose X is in SE(2) and the beacon positions b_k in R^2,\n *\n *          | cos th  -sin th   x |\n *      X = | sin th   cos th   y |  // position and orientation\n *          |   0        0      1 |\n *\n *      b_k = (bx_k, by_k)           // lmk coordinates in world frame\n *\n *  The control signal u is a twist in se(2) comprising longitudinal\n *  velocity v and angular velocity w, with no lateral velocity\n *  component, integrated over the sampling time dt.\n *\n *      u = (v*dt, 0, w*dt)\n *\n *  The control is corrupted by additive Gaussian noise u_noise,\n *  with covariance\n *\n *    Q = diagonal(sigma_v^2, sigma_s^2, sigma_w^2).\n *\n *  This noise accounts for possible lateral slippage u_s\n *  through a non-zero value of sigma_s,\n *\n *  At the arrival of a control u, the robot pose is updated\n *  with X <-- X * Exp(u) = X + u.\n *\n *  Landmark measurements are of the range and bearing type,\n *  though they are put in Cartesian form for simplicity.\n *  Their noise n is zero mean Gaussian, and is specified\n *  with a covariances matrix R.\n *  We notice the rigid motion action y = h(X,b) = X^-1 * b\n *  (see appendix C),\n *\n *      y_k = (brx_k, bry_k)       // lmk coordinates in robot frame\n *\n *  We consider the beacons b_k situated at known positions.\n *  We define the pose to estimate as X in SE(2).\n *  The estimation error dx and its covariance P are expressed\n *  in the tangent space at X.\n *\n *  All these variables are summarized again as follows\n *\n *    X   : robot pose, SE(2)\n *    u   : robot control, (v*dt ; 0 ; w*dt) in se(2)\n *    Q   : control perturbation covariance\n *    b_k : k-th landmark position, R^2\n *    y   : Cartesian landmark measurement in robot frame, R^2\n *    R   : covariance of the measurement noise\n *\n *  The motion and measurement models are\n *\n *    X_(t+1) = f(X_t, u) = X_t * Exp ( w )     // motion equation\n *    y_k     = h(X, b_k) = X^-1 * b_k          // measurement equation\n *\n *  The algorithm below comprises first a simulator to\n *  produce measurements, then uses these measurements\n *  to estimate the state, using a Lie-based error-state Kalman filter.\n *\n *  This file has plain code with only one main() function.\n *  There are no function calls other than those involving `manif`.\n *\n *  Printing simulated state and estimated state together\n *  with an unfiltered state (i.e. without Kalman corrections)\n *  allows for evaluating the quality of the estimates.\n */\n\n#include \"manif/SE2.h\"\n\n#include <Eigen/Cholesky>\n\n#include <vector>\n\n#include <iostream>\n#include <iomanip>\n#include <tuple>\n\nusing std::cout;\nusing std::endl;\n\nusing namespace Eigen;\n\ntypedef Array<double, 2, 1> Array2d;\ntypedef Array<double, 3, 1> Array3d;\n\ntemplate <typename Scalar>\nstruct Weights\n{\n  Weights() = default;\n  ~Weights() = default;\n\n  Weights(const Scalar l, const Scalar alpha)\n  {\n    using std::sqrt;\n\n    const Scalar m = (alpha * alpha - 1) * l;\n    const Scalar ml = m + l;\n\n    sqrt_d_lambda = sqrt(ml);\n    wj = Scalar(1) / (Scalar(2) * (ml));\n    wm = m / (ml);\n    w0 = m / (ml) + Scalar(3) - alpha * alpha;\n  }\n\n  Scalar sqrt_d_lambda;\n  Scalar wj;\n  Scalar wm;\n  Scalar w0;\n};\n\nusing Weightsd = Weights<double>;\n\ntemplate <typename Scalar>\nstd::tuple<Weights<Scalar>, Weights<Scalar>, Weights<Scalar>>\ncompute_sigma_weights(const Scalar state_size,\n                      const Scalar propagation_noise_size,\n                      const Scalar alpha_0,\n                      const Scalar alpha_1,\n                      const Scalar alpha_2)\n{\n  assert(state_size>0);\n  assert(propagation_noise_size>0);\n  assert(alpha_0>=1e-3 && alpha_0<=1);\n  assert(alpha_1>=1e-3 && alpha_1<=1);\n  assert(alpha_2>=1e-3 && alpha_2<=1);\n\n  return std::make_tuple(Weights<Scalar>(state_size, alpha_0),\n                         Weights<Scalar>(propagation_noise_size, alpha_1),\n                         Weights<Scalar>(state_size, alpha_2));\n}\n\nint main()\n{\n    std::srand((unsigned int) time(0));\n\n    // START CONFIGURATION\n    //\n    //\n    const int NUMBER_OF_LMKS_TO_MEASURE = 3;\n    constexpr int DoF = manif::SE2d::DoF;\n    constexpr int SystemNoiseSize = manif::SE2d::DoF;\n    // Measurement Dim\n    constexpr int Rp = 2;\n\n    // Define the robot pose element and its covariance\n    manif::SE2d X            = manif::SE2d::Identity(),\n                X_simulation = manif::SE2d::Identity(),\n                X_unfiltered = manif::SE2d::Identity();\n    Matrix3d    P            = Matrix3d::Identity() * 1e-6;\n\n    // Define a control vector and its noise and covariance\n    manif::SE2Tangentd  u_simu, u_est, u_unfilt;\n    Vector3d            u_nom, u_noisy, u_noise;\n    Array3d             u_sigmas;\n    Matrix3d            U, Uchol;\n\n    u_nom    << 0.1, 0.0, 0.05;\n    u_sigmas << 0.1, 0.1, 0.1;\n    U        = (u_sigmas * u_sigmas).matrix().asDiagonal();\n    Uchol    = U.llt().matrixL();\n\n    // Define three landmarks in R^2\n    Eigen::Vector2d b;\n    const std::vector<Eigen::Vector2d> landmarks{\n      Eigen::Vector2d(2.0,  0.0),\n      Eigen::Vector2d(2.0,  1.0),\n      Eigen::Vector2d(2.0, -1.0)\n    };\n\n    // Define the beacon's measurements\n    Vector2d                  y, y_bar, y_noise;\n    Matrix<double, Rp, 2*DoF> yj;\n    Array2d                   y_sigmas;\n    Matrix2d                  R;\n    std::vector<Vector2d>     measurements(landmarks.size());\n\n    y_sigmas << 0.01, 0.01;\n    R        = (y_sigmas * y_sigmas).matrix().asDiagonal();\n\n\n    // Declare UFK variables\n    Array3d alpha;\n    alpha << 1e-3, 1e-3, 1e-3;\n\n    Weightsd w_d, w_q, w_u;\n    std::tie(w_d, w_q, w_u) = compute_sigma_weights<double>(\n      DoF, Rp, alpha(0), alpha(1), alpha(2)\n    );\n\n    // Declare some temporaries\n\n    manif::SE2d X_new;\n    Matrix3d P_new;\n    manif::SE2d s_j_p, s_j_m;\n    Vector3d xi_mean;\n    Vector3d w_p, w_m;\n\n    Matrix2d P_yy;\n    Matrix<double, DoF, 2*DoF> xij;\n    Matrix<double, DoF, 2> P_xiy;\n\n    Vector2d                e, z;   // expectation, innovation\n    Matrix<double, 3, 2>    K;      // Kalman gain\n    manif::SE2Tangentd      dx;     // optimal update step, or error-state\n\n    Matrix<double, DoF, DoF> xis;\n    Matrix<double, DoF, DoF*2> xis_new;\n    Matrix<double, DoF, SystemNoiseSize*2> xis_new2;\n\n    //\n    //\n    // CONFIGURATION DONE\n\n\n\n    // DEBUG\n    cout << std::fixed   << std::setprecision(4) << std::showpos << endl;\n    cout << \"X STATE     :    X      Y    THETA\" << endl;\n    cout << \"----------------------------------\" << endl;\n    cout << \"X initial   : \" << X_simulation.log().coeffs().transpose() << endl;\n    cout << \"----------------------------------\" << endl;\n    // END DEBUG\n\n\n\n    // START TEMPORAL LOOP\n    //\n    //\n\n    // Make 10 steps. Measure up to three landmarks each time.\n    for (int t = 0; t <10; t++)\n    {\n        //// I. Simulation ###############################################################################\n\n        /// simulate noise\n        u_noise = u_sigmas * Array3d::Random();             // control noise\n        u_noisy = u_nom + u_noise;                          // noisy control\n\n        u_simu   = u_nom;\n        u_est    = u_noisy;\n        u_unfilt = u_noisy;\n\n        /// first we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        X_simulation = X_simulation + u_simu;               // overloaded X.rplus(u) = X * exp(u)\n\n        /// then we measure all landmarks - - - - - - - - - - - - - - - - - - - -\n        for (std::size_t i = 0; i < landmarks.size(); i++)\n        {\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n            /// simulate noise\n            y_noise = y_sigmas * Array2d::Random();         // measurement noise\n\n            y = X_simulation.inverse().act(b);              // landmark measurement, before adding noise\n            y = y + y_noise;                                // landmark measurement, noisy\n            measurements[i] = y;                            // store for the estimator just below\n        }\n\n\n\n\n        //// II. Estimation ###############################################################################\n\n        /// First we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n        X_new = X + u_est;                        // X * exp(u)\n\n        // set sigma points\n        xis = w_d.sqrt_d_lambda * P.llt().matrixL().toDenseMatrix();\n\n        // sigma points on manifold\n        for (int i = 0; i < DoF; ++i)\n        {\n          s_j_p = X + manif::SE2Tangentd( xis.col(i));\n          s_j_m = X + manif::SE2Tangentd(-xis.col(i));\n\n          xis_new.col(i) = (X_new.lminus(s_j_p + u_est)).coeffs();\n          xis_new.col(i + DoF) = (X_new.lminus(s_j_m + u_est)).coeffs();\n        }\n\n        // compute covariance\n        xi_mean = w_d.wj * xis_new.rowwise().sum();\n        xis_new.colwise() -= xi_mean;\n\n        P_new = w_d.wj * xis_new * xis_new.transpose() +\n                w_d.w0 * xi_mean * xi_mean.transpose();\n\n        // sigma points on manifold\n        for (int i = 0; i < SystemNoiseSize; ++i)\n        {\n          w_p =  w_q.sqrt_d_lambda * Uchol.col(i);\n          w_m = -w_q.sqrt_d_lambda * Uchol.col(i);\n\n          xis_new2.col(i) = (X_new.lminus(X + (u_est + w_p))).coeffs();\n          xis_new2.col(i + SystemNoiseSize) = (X_new.lminus(X + (u_est + w_m))).coeffs();\n        }\n\n        xi_mean = w_q.wj * xis_new2.rowwise().sum();\n        xis_new2.colwise() -= xi_mean;\n\n        U = w_q.wj * xis_new2 * xis_new2.transpose() +\n            w_q.w0 * xi_mean * xi_mean.transpose();\n\n        P = P_new + U;\n\n        X = X_new;\n\n        /// Then we correct using the measurements of each lmk - - - - - - - - -\n        for (int i = 0; i < NUMBER_OF_LMKS_TO_MEASURE; i++)\n        {\n            // landmark\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n            // measurement\n            y = measurements[i];                            // lmk measurement, noisy\n\n            // expectation\n            e = X.inverse().act(b);\n\n            // set sigma points\n            xis = w_u.sqrt_d_lambda * P.llt().matrixL().toDenseMatrix();\n\n            // compute measurement sigma points\n            for (int d = 0; d < DoF; ++d)\n            {\n              s_j_p = X + manif::SE2Tangentd( xis.col(d));\n              s_j_m = X + manif::SE2Tangentd(-xis.col(d));\n\n              yj.col(d) = s_j_p.inverse().act(b);\n              yj.col(d + DoF) = s_j_m.inverse().act(b);\n            }\n\n            // measurement mean\n            y_bar = w_u.wm * e + w_u.wj * yj.rowwise().sum();\n\n            yj.colwise() -= y_bar;\n            e -= y_bar;\n\n            // compute covariance and cross covariance matrices\n            P_yy = w_u.w0 * e * e.transpose() +\n                   w_u.wj * yj * yj.transpose() + R;\n\n            xij << xis, -xis;\n            P_xiy = w_u.wj * xij * yj.transpose();\n\n            // Kalman gain\n            K = P_yy.colPivHouseholderQr().solve(P_xiy.transpose()).transpose();\n\n            // innovation\n            z = y - y_bar;\n\n            // Correction step\n            dx = K * z;                                     // dx is in the tangent space at X\n\n            // Update\n            X = X + dx;                                     // overloaded X.rplus(dx) = X * exp(dx)\n            P = P - K * P_yy * K.transpose();\n        }\n\n\n        //// III. Unfiltered ##############################################################################\n\n        // move also an unfiltered version for comparison purposes\n        X_unfiltered = X_unfiltered + u_unfilt;\n\n\n\n\n        //// IV. Results ##############################################################################\n\n        // DEBUG\n        cout << \"X simulated : \" << X_simulation.log().coeffs().transpose() << \"\\n\";\n        cout << \"X estimated : \" << X.log().coeffs().transpose() << \"\\n\";\n        cout << \"X unfilterd : \" << X_unfiltered.log().coeffs().transpose() << \"\\n\";\n        cout << \"----------------------------------\" << endl;\n        // END DEBUG\n\n    }\n\n    //\n    //\n    // END OF TEMPORAL LOOP. DONE.\n\n    return 0;\n}\n", "meta": {"hexsha": "87d856f90b42ac81fa552f399cbc7dd275b7f4cc", "size": 13629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/se2_localization_ukfm.cpp", "max_stars_repo_name": "stefangachter/manif", "max_stars_repo_head_hexsha": "a4ba3df4f793fdce37c98b2cf9778321f9cea7c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 876.0, "max_stars_repo_stars_event_min_datetime": "2019-01-15T19:04:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T21:52:12.000Z", "max_issues_repo_path": "examples/se2_localization_ukfm.cpp", "max_issues_repo_name": "stefangachter/manif", "max_issues_repo_head_hexsha": "a4ba3df4f793fdce37c98b2cf9778321f9cea7c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 191.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T17:14:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T09:08:26.000Z", "max_forks_repo_path": "examples/se2_localization_ukfm.cpp", "max_forks_repo_name": "stefangachter/manif", "max_forks_repo_head_hexsha": "a4ba3df4f793fdce37c98b2cf9778321f9cea7c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2019-01-17T12:50:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T15:24:00.000Z", "avg_line_length": 31.9929577465, "max_line_length": 107, "alphanum_fraction": 0.5265976961, "num_tokens": 3714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5950497942133203}}
{"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// remove assert() statements and the like in order to get reasonable performance\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n#include <iostream>\n#include <vector>\n#include <stdlib.h>\n#include <assert.h>\n\n// ViennaFEM includes:\n#include \"viennafem/forwards.h\"\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#include \"viennamath/expression.hpp\"\n#include \"viennamath/manipulation/eval.hpp\"\n#include \"viennamath/manipulation/substitute.hpp\"\n#include \"viennamath/manipulation/diff.hpp\"\n\n#include \"viennamath/runtime/equation.hpp\"\n#include \"viennamath/manipulation/apply_coordinate_system.hpp\"\n\n// Boost.uBLAS includes:\n#include <boost/numeric/ublas/io.hpp>\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/bicgstab.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\nusing namespace viennamath;\n\n//\n// The strain tensor: eps_ij = 0.5 * (du_i/dx_j + du_j/dx_i)\n//\ntemplate <typename InterfaceType>\nstd::vector< rt_expr<InterfaceType> > strain_tensor(std::vector< rt_function_symbol<InterfaceType> > const & u)\n{\n  typedef rt_variable<InterfaceType>     Variable;\n\n  //\n  // a 3x3 matrix representing the strain tensor\n  //\n  std::vector< rt_expr<InterfaceType> > result(9);\n\n  Variable x(0);\n  Variable y(1);\n  Variable z(2);\n\n  //first row:\n  result[0] =        diff(u[0], x);\n  result[1] = 0.5 * (diff(u[0], y) + diff(u[1], x));\n  result[2] = 0.5 * (diff(u[0], z) + diff(u[2], x));\n\n  //second row:\n  result[3] = 0.5 * (diff(u[1], x) + diff(u[0], y));\n  result[4] =        diff(u[1], y);\n  result[5] = 0.5 * (diff(u[1], z) + diff(u[2], y));\n\n  //third row:\n  result[6] = 0.5 * (diff(u[2], x) + diff(u[0], z));\n  result[7] = 0.5 * (diff(u[2], y) + diff(u[1], z));\n  result[8] =        diff(u[2], z);\n\n  return result;\n}\n\n\n//\n// The stress tensor: sigma = 2 \\mu eps + \\lambda trace(eps) Id  for St. Venent-Kirchhoff material\n// can be replaced with other expressions for plasticity and the like\n//\ntemplate <typename InterfaceType>\nstd::vector< rt_expr<InterfaceType> > stress_tensor(std::vector< rt_function_symbol<InterfaceType> > const & v)\n{\n  //\n  // a 3x3 matrix representing the stress tensor\n  //\n  std::vector< rt_expr<InterfaceType> > result(9);\n  std::vector< rt_expr<InterfaceType> > strain = strain_tensor(v);\n\n  double mu = 0.5;\n  double lambda = 1;\n\n  //The entries are in the following written\n\n  //add 2 \\mu eps:\n  for (size_t i=0; i<9; ++i)\n    result[i] = (2*mu) * strain[i];\n    //result[i] = viennamath::constant<>(0);\n\n  //add trace(eps) * Id:\n  result[0] = (2*mu) * strain[0] + lambda * (strain[0] + strain[4] + strain[8]);\n  result[4] = (2*mu) * strain[4] + lambda * (strain[0] + strain[4] + strain[8]);\n  result[8] = (2*mu) * strain[8] + lambda * (strain[0] + strain[4] + strain[8]);\n\n  /*result[0] = lambda * (strain[0] + strain[4] + strain[8]);\n  result[4] = lambda * (strain[0] + strain[4] + strain[8]);\n  result[8] = lambda * (strain[0] + strain[4] + strain[8]);*/\n\n  return result;\n}\n\n\n//\n// Provides the operation a : b, where a and b are tensors\n//\ntemplate <typename InterfaceType>\nrt_expr<InterfaceType> tensor_reduce(std::vector< rt_expr<InterfaceType> > lhs, std::vector< rt_expr<InterfaceType> > rhs)\n{\n  rt_expr<InterfaceType> ret = lhs[0] * rhs[0];\n\n  for (size_t i=1; i<rhs.size(); ++i)\n    ret = ret + lhs[i] * rhs[i];\n\n  return ret;\n}\n\n\n//\n// Writes displacements to domain\n//\ntemplate <typename DomainT, typename StorageT, typename VectorT>\nvoid apply_displacements(DomainT& domain, StorageT& storage, VectorT const & result)\n{\n  typedef typename viennagrid::result_of::element<DomainT, viennagrid::vertex_tag>::type           VertexType;\n  typedef typename viennagrid::result_of::element_range<DomainT, viennagrid::vertex_tag>::type     VertexContainer;\n  typedef typename viennagrid::result_of::iterator<VertexContainer>::type                          VertexIterator;\n\n  typedef viennafem::mapping_key          MappingKeyType;\n  typedef viennafem::boundary_key         BoundaryKeyType;\n\n  MappingKeyType map_key(0);\n  BoundaryKeyType bnd_key(0);\n\n  std::cout << \"* apply_displacements(): Writing computed displacements onto domain\" << std::endl;\n  VertexContainer vertices = viennagrid::elements<VertexType>(domain);\n  for (VertexIterator vit = vertices.begin();\n      vit != vertices.end();\n      ++vit)\n  {\n    long cur_index = viennadata::access<MappingKeyType, long>(storage, map_key, *vit);\n    if (cur_index > -1)\n    {\n      viennagrid::point(domain, *vit)[0] += result[cur_index+0];\n      viennagrid::point(domain, *vit)[1] += result[cur_index+1];\n      viennagrid::point(domain, *vit)[2] += result[cur_index+2];\n    }\n    else\n    {\n      if (viennadata::access<BoundaryKeyType, std::vector<double> >(storage, bnd_key, *vit).size() > 0)\n      {\n        viennagrid::point(domain, *vit)[0] += viennadata::access<BoundaryKeyType, std::vector<double> >(storage, bnd_key, *vit)[0];\n        viennagrid::point(domain, *vit)[1] += viennadata::access<BoundaryKeyType, std::vector<double> >(storage, bnd_key, *vit)[1];\n        viennagrid::point(domain, *vit)[2] += viennadata::access<BoundaryKeyType, std::vector<double> >(storage, bnd_key, *vit)[2];\n      }\n    }\n  }\n}\n\nint main()\n{\n  typedef viennagrid::hexahedral_3d_mesh                                                  DomainType;\n  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;\n  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;\n  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainer;\n  typedef viennagrid::result_of::iterator<VertexContainer>::type                          VertexIterator;\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  typedef viennamath::expr              Expression;\n\n  typedef viennafem::boundary_key      BoundaryKey;\n\n\n  std::cout << \"*********************************************************\" << std::endl;\n  std::cout << \"*****     Demo for LAME equation with ViennaFEM     *****\" << std::endl;\n  std::cout << \"*********************************************************\" << std::endl;\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_reader;\n    my_reader(my_domain, segments, \"../examples/data/cube343_hex.mesh\");\n  }\n  catch (...)\n  {\n    std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n\n  MatrixType system_matrix;\n  VectorType load_vector;\n\n\n  // the unknown function (vector valued, so one for each of the three components..\n  std::vector< FunctionSymbol > u(3);\n  u[0] = FunctionSymbol(0, unknown_tag<>());\n  u[1] = FunctionSymbol(1, unknown_tag<>());\n  u[2] = FunctionSymbol(2, unknown_tag<>());\n\n  std::vector< FunctionSymbol > v(3);\n  v[0] = FunctionSymbol(0, test_tag<>());\n  v[1] = FunctionSymbol(1, test_tag<>());\n  v[2] = FunctionSymbol(2, test_tag<>());\n\n\n\n  //\n  // Step 1: Define the classical Lame equation\n  //             (lambda + mu) div(u) div(v) + mu grad(u):grad(v) = F\n  // with force F set to 0.\n  //\n  // Minimization problem: \\int eps : sigma dx = \\int F \\cdot u dx\n  //\n\n  std::vector< Expression > strain = strain_tensor(u);\n  std::vector< Expression > stress = stress_tensor(v);\n\n  Equation weak_form_lame = make_equation( integral(symbolic_interval(), tensor_reduce( strain, stress )),\n                                           //=\n                                           integral(symbolic_interval(), viennamath::rt_constant<double>(1.0) * v[2])\n                                         );\n\n\n  std::cout << \"Weak form of Lame equation: \" << std::endl;\n  std::cout << weak_form_lame << std::endl;\n\n  std::vector<double> bnd_data_right(3);\n  bnd_data_right[0] = 0.2; //small displacement into x-direction prescribed\n\n  VertexContainer vertices = viennagrid::elements<VertexType>(my_domain);\n  for (VertexIterator vit = vertices.begin();\n      vit != vertices.end();\n      ++vit)\n  {\n    //boundary for first equation: Homogeneous Dirichlet everywhere\n    if (viennagrid::point(my_domain, *vit)[0] == 0.0 || viennagrid::point(my_domain, *vit)[0] == 1.0 )\n      viennafem::set_dirichlet_boundary(storage, *vit, 0);\n\n    if (viennagrid::point(my_domain, *vit)[0] == 1.0)\n    {\n      viennafem::set_dirichlet_boundary(storage, *vit, bnd_data_right);\n      viennadata::access<BoundaryKey, double>(storage, BoundaryKey(0), *vit) = bnd_data_right[0]; //this is for the moment used for the VTK writer\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  // Assemble and solve system and write solution vector to pde_result:\n  // (discussion about proper interface required. Introduce a pde_result class?)\n  //\n  fem_assembler(viennafem::make_linear_pde_system(weak_form_lame,\n                                                  u,\n                                                  viennafem::make_linear_pde_options(0,\n                                                                                     viennafem::lagrange_tag<1>(),\n                                                                                     viennafem::lagrange_tag<1>())\n                                                 ),\n                my_domain,\n                system_matrix,\n                load_vector\n               );\n\n  VectorType displacements = viennacl::linalg::solve(system_matrix, load_vector, viennacl::linalg::bicgstab_tag());\n  std::cout << \"* solve(): Residual: \" << norm_2(prod(system_matrix, displacements) - load_vector) << std::endl;\n\n  apply_displacements(my_domain, storage, displacements);\n  viennafem::io::write_solution_to_VTK_file(displacements, \"lame_hex\", my_domain, segments, storage, 0);\n\n  std::cout << \"*****************************************\" << std::endl;\n  std::cout << \"* Lame solver finished successfully! *\" << std::endl;\n  std::cout << \"*****************************************\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c860d46d22ba1ef18a3d9887dc3bcc36b1194a92", "size": 11522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorials/lame_3d_hex.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/lame_3d_hex.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/lame_3d_hex.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": 35.4523076923, "max_line_length": 146, "alphanum_fraction": 0.6136087485, "num_tokens": 3054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5950486852642065}}
{"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    Rot3Q.cpp\n * @brief   Rotation (internal: quaternion representation*)\n * @author  Richard Roberts\n */\n\n#include <gtsam/config.h> // Get GTSAM_USE_QUATERNIONS macro\n\n#ifdef GTSAM_USE_QUATERNIONS\n\n#include <boost/math/constants/constants.hpp>\n#include <gtsam/geometry/Rot3.h>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  /* ************************************************************************* */\n  Rot3::Rot3() : quaternion_(Quaternion::Identity()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Point3& col1, const Point3& col2, const Point3& col3) :\n      quaternion_((Matrix3() <<\n          col1.x(), col2.x(), col3.x(),\n          col1.y(), col2.y(), col3.y(),\n          col1.z(), col2.z(), col3.z()).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(double R11, double R12, double R13,\n      double R21, double R22, double R23,\n      double R31, double R32, double R33) :\n        quaternion_((Matrix3() <<\n            R11, R12, R13,\n            R21, R22, R23,\n            R31, R32, R33).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const gtsam::Quaternion& q) :\n      quaternion_(q) {\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rx(double t) {\n    return gtsam::Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitX()));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Ry(double t) {\n    return gtsam::Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitY()));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rz(double t) {\n    return gtsam::Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitZ()));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::RzRyRx(double x, double y, double z) { return Rot3(\n      gtsam::Quaternion(Eigen::AngleAxisd(z, Eigen::Vector3d::UnitZ())) *\n      gtsam::Quaternion(Eigen::AngleAxisd(y, Eigen::Vector3d::UnitY())) *\n      gtsam::Quaternion(Eigen::AngleAxisd(x, Eigen::Vector3d::UnitX())));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::operator*(const Rot3& R2) const {\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  // TODO: Could we do this? It works in Rot3M but not here, probably because\n  // here we create an intermediate value by calling matrix()\n  // const Eigen::Transpose<const Matrix3> Rot3::transpose() const {\n  Matrix3 Rot3::transpose() const {\n    return matrix().transpose();\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::rotate(const Point3& p,\n        OptionalJacobian<3,3> H1,  OptionalJacobian<3,3> H2) const {\n    const Matrix3 R = matrix();\n    if (H1) *H1 = R * skewSymmetric(-p.x(), -p.y(), -p.z());\n    if (H2) *H2 = R;\n    const Vector3 r = R * p;\n    return Point3(r.x(), r.y(), r.z());\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::Logmap(const Rot3& R, OptionalJacobian<3, 3> H) {\n    return traits<gtsam::Quaternion>::Logmap(R.quaternion_, H);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::ChartAtOrigin::Retract(const Vector3& omega, ChartJacobian H) {\n    static const CoordinatesMode mode = ROT3_DEFAULT_COORDINATES_MODE;\n    if (mode == Rot3::EXPMAP) return Expmap(omega, H);\n    else throw std::runtime_error(\"Rot3::Retract: unknown mode\");\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::ChartAtOrigin::Local(const Rot3& R, ChartJacobian H) {\n    static const CoordinatesMode mode = ROT3_DEFAULT_COORDINATES_MODE;\n    if (mode == Rot3::EXPMAP) return Logmap(R, H);\n    else throw std::runtime_error(\"Rot3::Local: unknown mode\");\n  }\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::matrix() const {return quaternion_.toRotationMatrix();}\n\n  /* ************************************************************************* */\n  Point3 Rot3::r1() const { return Point3(quaternion_.toRotationMatrix().col(0)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r2() const { return Point3(quaternion_.toRotationMatrix().col(1)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r3() const { return Point3(quaternion_.toRotationMatrix().col(2)); }\n\n  /* ************************************************************************* */\n  gtsam::Quaternion Rot3::toQuaternion() const { return quaternion_; }\n\n /* ************************************************************************* */\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "8af9a7144d15484ab4241b97ce2daf16fcc4fff6", "size": 5424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_stars_repo_name": "DEVESHTARASIA/gtsam", "max_stars_repo_head_hexsha": "e90e1f1dd2105b47df1d731ac82da28a6a9be454", "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/geometry/Rot3Q.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "trunk/gtsam/geometry/Rot3Q.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": 39.3043478261, "max_line_length": 83, "alphanum_fraction": 0.4404498525, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.595048680709591}}
{"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#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\nusing namespace dealii;\n\n\nvoid\nfirst_grid()\n{\n  Triangulation<2> triangulation;\n\n  GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(4);\n\n  std::ofstream out(\"grid-1.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to grid-1.svg\" << std::endl;\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  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.svg\" << std::endl;\n}\n\n\n\nint\nmain()\n{\n  first_grid();\n  second_grid();\n}\n", "meta": {"hexsha": "a930fee28eea1871b0090dbf1be244b00a7e2ec3", "size": 2302, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-juneshuoyang", "max_stars_repo_head_hexsha": "b35d9a32435cd67e0191b91e990ca0675cedfa54", "max_stars_repo_licenses": ["MIT"], "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-juneshuoyang", "max_issues_repo_head_hexsha": "b35d9a32435cd67e0191b91e990ca0675cedfa54", "max_issues_repo_licenses": ["MIT"], "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-juneshuoyang", "max_forks_repo_head_hexsha": "b35d9a32435cd67e0191b91e990ca0675cedfa54", "max_forks_repo_licenses": ["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.2315789474, "max_line_length": 72, "alphanum_fraction": 0.6003475239, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.5950486789423436}}
{"text": "/*\n\tCopyright 2020 Patrick Owen\n\n\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\tyou may not use this file except in compliance with the License.\n\tYou may obtain a copy of the License at\n\n\t\thttp://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n */\n\n#include \"VectorMath.h\"\n#include <unsupported/Eigen/MatrixFunctions>\n#include <Eigen/SVD>\n\nMatrix4d VectorMath::hyperbolicSvdUnitary(const Matrix4d& matrix) {\n\treturn matrix * (hyperbolicTranspose(matrix) * matrix).sqrt().inverse();\n}\n\nMatrix4d VectorMath::sphericalSvdUnitary(const Matrix4d& matrix) {\n\tEigen::JacobiSVD<Matrix4d> svd(matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\treturn svd.matrixU() * svd.matrixV().adjoint();\n}\n", "meta": {"hexsha": "d87059e3f5a6bc749325f41aa1ca356f3c6eb0c4", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/VectorMath.cpp", "max_stars_repo_name": "patowen/hyperworld", "max_stars_repo_head_hexsha": "daba8c6926da6fc8fafa93c726b6fa073e67e19b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-12-17T03:40:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T14:59:50.000Z", "max_issues_repo_path": "src/VectorMath.cpp", "max_issues_repo_name": "patowen/hyperworld", "max_issues_repo_head_hexsha": "daba8c6926da6fc8fafa93c726b6fa073e67e19b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-22T03:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-18T18:21:33.000Z", "max_forks_repo_path": "src/VectorMath.cpp", "max_forks_repo_name": "patowen/hyperworld", "max_forks_repo_head_hexsha": "daba8c6926da6fc8fafa93c726b6fa073e67e19b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T19:05:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T19:05:33.000Z", "avg_line_length": 34.6896551724, "max_line_length": 83, "alphanum_fraction": 0.7713717694, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5949898484767117}}
{"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    SO3.cpp\n * @brief   3*3 matrix representation of SO(3)\n * @author  Frank Dellaert\n * @author  Luca Carlone\n * @author  Duy Nguyen Ta\n * @date    December 2014\n */\n\n#include <gtsam/base/concepts.h>\n#include <gtsam/geometry/SO3.h>\n\n#include <Eigen/SVD>\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n\nnamespace gtsam {\n\n//******************************************************************************\nnamespace so3 {\n\nGTSAM_EXPORT Matrix99 Dcompose(const SO3& Q) {\n  Matrix99 H;\n  auto R = Q.matrix();\n  H << I_3x3 * R(0, 0), I_3x3 * R(1, 0), I_3x3 * R(2, 0),  //\n      I_3x3 * R(0, 1), I_3x3 * R(1, 1), I_3x3 * R(2, 1),   //\n      I_3x3 * R(0, 2), I_3x3 * R(1, 2), I_3x3 * R(2, 2);\n  return H;\n}\n\nGTSAM_EXPORT Matrix3 compose(const Matrix3& M, const SO3& R, OptionalJacobian<9, 9> H) {\n  Matrix3 MR = M * R.matrix();\n  if (H) *H = Dcompose(R);\n  return MR;\n}\n\nvoid ExpmapFunctor::init(bool nearZeroApprox) {\n  nearZero =\n      nearZeroApprox || (theta2 <= std::numeric_limits<double>::epsilon());\n  if (!nearZero) {\n    sin_theta = std::sin(theta);\n    const double s2 = std::sin(theta / 2.0);\n    one_minus_cos = 2.0 * s2 * s2;  // numerically better than [1 - cos(theta)]\n  }\n}\n\nExpmapFunctor::ExpmapFunctor(const Vector3& omega, bool nearZeroApprox)\n    : theta2(omega.dot(omega)), theta(std::sqrt(theta2)) {\n  const double wx = omega.x(), wy = omega.y(), wz = omega.z();\n  W << 0.0, -wz, +wy, +wz, 0.0, -wx, -wy, +wx, 0.0;\n  init(nearZeroApprox);\n  if (!nearZero) {\n    K = W / theta;\n    KK = K * K;\n  }\n}\n\nExpmapFunctor::ExpmapFunctor(const Vector3& axis, double angle,\n                             bool nearZeroApprox)\n    : theta2(angle * angle), theta(angle) {\n  const double ax = axis.x(), ay = axis.y(), az = axis.z();\n  K << 0.0, -az, +ay, +az, 0.0, -ax, -ay, +ax, 0.0;\n  W = K * angle;\n  init(nearZeroApprox);\n  if (!nearZero) {\n    KK = K * K;\n  }\n}\n\nSO3 ExpmapFunctor::expmap() const {\n  if (nearZero)\n    return SO3(I_3x3 + W);\n  else\n    return SO3(I_3x3 + sin_theta * K + one_minus_cos * KK);\n}\n\nDexpFunctor::DexpFunctor(const Vector3& omega, bool nearZeroApprox)\n    : ExpmapFunctor(omega, nearZeroApprox), omega(omega) {\n  if (nearZero) {\n    dexp_ = I_3x3 - 0.5 * W;\n  } else {\n    a = one_minus_cos / theta;\n    b = 1.0 - sin_theta / theta;\n    dexp_ = I_3x3 - a * K + b * KK;\n  }\n}\n\nVector3 DexpFunctor::applyDexp(const Vector3& v, OptionalJacobian<3, 3> H1,\n                               OptionalJacobian<3, 3> H2) const {\n  if (H1) {\n    if (nearZero) {\n      *H1 = 0.5 * skewSymmetric(v);\n    } else {\n      // TODO(frank): Iserles hints that there should be a form I + c*K + d*KK\n      const Vector3 Kv = K * v;\n      const double Da = (sin_theta - 2.0 * a) / theta2;\n      const double Db = (one_minus_cos - 3.0 * b) / theta2;\n      *H1 = (Db * K - Da * I_3x3) * Kv * omega.transpose() -\n            skewSymmetric(Kv * b / theta) +\n            (a * I_3x3 - b * K) * skewSymmetric(v / theta);\n    }\n  }\n  if (H2) *H2 = dexp_;\n  return dexp_ * v;\n}\n\nVector3 DexpFunctor::applyInvDexp(const Vector3& v, OptionalJacobian<3, 3> H1,\n                                  OptionalJacobian<3, 3> H2) const {\n  const Matrix3 invDexp = dexp_.inverse();\n  const Vector3 c = invDexp * v;\n  if (H1) {\n    Matrix3 D_dexpv_omega;\n    applyDexp(c, D_dexpv_omega);  // get derivative H of forward mapping\n    *H1 = -invDexp * D_dexpv_omega;\n  }\n  if (H2) *H2 = invDexp;\n  return c;\n}\n\n}  // namespace so3\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO3 SO3::AxisAngle(const Vector3& axis, double theta) {\n  return so3::ExpmapFunctor(axis, theta).expmap();\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO3 SO3::ClosestTo(const Matrix3& M) {\n  Eigen::JacobiSVD<Matrix3> svd(M, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  const auto& U = svd.matrixU();\n  const auto& V = svd.matrixV();\n  const double det = (U * V.transpose()).determinant();\n  return SO3(U * Vector3(1, 1, det).asDiagonal() * V.transpose());\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO3 SO3::ChordalMean(const std::vector<SO3>& rotations) {\n  // See Hartley13ijcv:\n  // Cost function C(R) = \\sum sqr(|R-R_i|_F)\n  // Closed form solution = ClosestTo(C_e), where C_e = \\sum R_i !!!!\n  Matrix3 C_e{Z_3x3};\n  for (const auto& R_i : rotations) {\n    C_e += R_i.matrix();\n  }\n  return ClosestTo(C_e);\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nMatrix3 SO3::Hat(const Vector3& xi) {\n  // skew symmetric matrix X = xi^\n  Matrix3 Y = Z_3x3;\n  Y(0, 1) = -xi(2);\n  Y(0, 2) = +xi(1);\n  Y(1, 2) = -xi(0);\n  return Y - Y.transpose();\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nVector3 SO3::Vee(const Matrix3& X) {\n  Vector3 xi;\n  xi(0) = -X(1, 2);\n  xi(1) = +X(0, 2);\n  xi(2) = -X(0, 1);\n  return xi;\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nMatrix3 SO3::AdjointMap() const {\n  return matrix_;\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO3 SO3::Expmap(const Vector3& omega, ChartJacobian H) {\n  if (H) {\n    so3::DexpFunctor impl(omega);\n    *H = impl.dexp();\n    return impl.expmap();\n  } else {\n    return so3::ExpmapFunctor(omega).expmap();\n  }\n}\n\ntemplate <>\nGTSAM_EXPORT\nMatrix3 SO3::ExpmapDerivative(const Vector3& omega) {\n  return so3::DexpFunctor(omega).dexp();\n}\n\n//******************************************************************************\n/* Right Jacobian for Log map in SO(3) - equation (10.86) and following\n equations in G.S. Chirikjian, \"Stochastic Models, Information Theory, and Lie\n Groups\", Volume 2, 2008.\n\n   logmap( Rhat * expmap(omega) ) \\approx logmap(Rhat) + Jrinv * omega\n\n where Jrinv = LogmapDerivative(omega). This maps a perturbation on the\n manifold (expmap(omega)) to a perturbation in the tangent space (Jrinv *\n omega)\n */\ntemplate <>\nGTSAM_EXPORT\nMatrix3 SO3::LogmapDerivative(const Vector3& omega) {\n  using std::cos;\n  using std::sin;\n\n  double theta2 = omega.dot(omega);\n  if (theta2 <= std::numeric_limits<double>::epsilon()) return I_3x3;\n  double theta = std::sqrt(theta2);  // rotation angle\n\n  // element of Lie algebra so(3): W = omega^\n  const Matrix3 W = Hat(omega);\n  return I_3x3 + 0.5 * W +\n         (1 / (theta * theta) - (1 + cos(theta)) / (2 * theta * sin(theta))) *\n             W * W;\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nVector3 SO3::Logmap(const SO3& Q, ChartJacobian H) {\n  using std::sin;\n  using std::sqrt;\n\n  // note switch to base 1\n  const Matrix3& R = Q.matrix();\n  const double &R11 = R(0, 0), R12 = R(0, 1), R13 = R(0, 2);\n  const double &R21 = R(1, 0), R22 = R(1, 1), R23 = R(1, 2);\n  const double &R31 = R(2, 0), R32 = R(2, 1), R33 = R(2, 2);\n\n  // Get trace(R)\n  const double tr = R.trace();\n\n  Vector3 omega;\n\n  // when trace == -1, i.e., when theta = +-pi, +-3pi, +-5pi, etc.\n  // we do something special\n  if (tr + 1.0 < 1e-10) {\n    if (std::abs(R33 + 1.0) > 1e-5)\n      omega = (M_PI / sqrt(2.0 + 2.0 * R33)) * Vector3(R13, R23, 1.0 + R33);\n    else if (std::abs(R22 + 1.0) > 1e-5)\n      omega = (M_PI / sqrt(2.0 + 2.0 * R22)) * Vector3(R12, 1.0 + R22, R32);\n    else\n      // if(std::abs(R.r1_.x()+1.0) > 1e-5)  This is implicit\n      omega = (M_PI / sqrt(2.0 + 2.0 * R11)) * Vector3(1.0 + R11, R21, R31);\n  } else {\n    double magnitude;\n    const double tr_3 = tr - 3.0;  // always negative\n    if (tr_3 < -1e-7) {\n      double theta = acos((tr - 1.0) / 2.0);\n      magnitude = theta / (2.0 * sin(theta));\n    } else {\n      // when theta near 0, +-2pi, +-4pi, etc. (trace near 3.0)\n      // use Taylor expansion: theta \\approx 1/2-(t-3)/12 + O((t-3)^2)\n      magnitude = 0.5 - tr_3 * tr_3 / 12.0;\n    }\n    omega = magnitude * Vector3(R32 - R23, R13 - R31, R21 - R12);\n  }\n\n  if (H) *H = LogmapDerivative(omega);\n  return omega;\n}\n\n//******************************************************************************\n// Chart at origin for SO3 is *not* Cayley but actual Expmap/Logmap\n\ntemplate <>\nGTSAM_EXPORT\nSO3 SO3::ChartAtOrigin::Retract(const Vector3& omega, ChartJacobian H) {\n  return Expmap(omega, H);\n}\n\ntemplate <>\nGTSAM_EXPORT\nVector3 SO3::ChartAtOrigin::Local(const SO3& R, ChartJacobian H) {\n  return Logmap(R, H);\n}\n\n//******************************************************************************\n// local vectorize\nstatic Vector9 vec3(const Matrix3& R) {\n  return Eigen::Map<const Vector9>(R.data());\n}\n\n// so<3> generators\nstatic std::vector<Matrix3> G3({SO3::Hat(Vector3::Unit(0)),\n                                SO3::Hat(Vector3::Unit(1)),\n                                SO3::Hat(Vector3::Unit(2))});\n\n// vectorized generators\nstatic const Matrix93 P3 =\n    (Matrix93() << vec3(G3[0]), vec3(G3[1]), vec3(G3[2])).finished();\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nVector9 SO3::vec(OptionalJacobian<9, 3> H) const {\n  const Matrix3& R = matrix_;\n  if (H) {\n    // As Luca calculated (for SO4), this is (I3 \\oplus R) * P3\n    *H << R * P3.block<3, 3>(0, 0), R * P3.block<3, 3>(3, 0),\n        R * P3.block<3, 3>(6, 0);\n  }\n  return gtsam::vec3(R);\n}\n//******************************************************************************\n\n}  // end namespace gtsam\n", "meta": {"hexsha": "c86b9b860aa91629c754d55c8153b890f7b4af38", "size": 9936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/SO3.cpp", "max_stars_repo_name": "xxiao-1/gtsam", "max_stars_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T20:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T22:24:43.000Z", "max_issues_repo_path": "gtsam/geometry/SO3.cpp", "max_issues_repo_name": "xxiao-1/gtsam", "max_issues_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T17:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T20:21:19.000Z", "max_forks_repo_path": "gtsam/geometry/SO3.cpp", "max_forks_repo_name": "xxiao-1/gtsam", "max_forks_repo_head_hexsha": "8b1516f43ffdf6b5098fc282b566f2ee1edb50f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T08:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T08:39:51.000Z", "avg_line_length": 29.6597014925, "max_line_length": 88, "alphanum_fraction": 0.5234500805, "num_tokens": 3153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5949884044314253}}
{"text": "\r\n// g++ -DNDEBUG -O3 -I.. benchLLT.cpp  -o benchLLT && ./benchLLT\r\n// options:\r\n//  -DBENCH_GSL -lgsl /usr/lib/libcblas.so.3\r\n//  -DEIGEN_DONT_VECTORIZE\r\n//  -msse2\r\n//  -DREPEAT=100\r\n//  -DTRIES=10\r\n//  -DSCALAR=double\r\n\r\n#include <iostream>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Cholesky>\r\n#include <bench/BenchUtil.h>\r\nusing namespace Eigen;\r\n\r\n#ifndef REPEAT\r\n#define REPEAT 10000\r\n#endif\r\n\r\n#ifndef TRIES\r\n#define TRIES 10\r\n#endif\r\n\r\ntypedef float Scalar;\r\n\r\ntemplate <typename MatrixType>\r\n__attribute__ ((noinline)) void benchLLT(const MatrixType& m)\r\n{\r\n  int rows = m.rows();\r\n  int cols = m.cols();\r\n\r\n  int cost = 0;\r\n  for (int j=0; j<rows; ++j)\r\n  {\r\n    int r = std::max(rows - j -1,0);\r\n    cost += 2*(r*j+r+j);\r\n  }\r\n\r\n  int repeats = (REPEAT*1000)/(rows*rows);\r\n\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;\r\n\r\n  MatrixType a = MatrixType::Random(rows,cols);\r\n  SquareMatrixType covMat =  a * a.adjoint();\r\n\r\n  BenchTimer timerNoSqrt, timerSqrt;\r\n\r\n  Scalar acc = 0;\r\n  int r = internal::random<int>(0,covMat.rows()-1);\r\n  int c = internal::random<int>(0,covMat.cols()-1);\r\n  for (int t=0; t<TRIES; ++t)\r\n  {\r\n    timerNoSqrt.start();\r\n    for (int k=0; k<repeats; ++k)\r\n    {\r\n      LDLT<SquareMatrixType> cholnosqrt(covMat);\r\n      acc += cholnosqrt.matrixL().coeff(r,c);\r\n    }\r\n    timerNoSqrt.stop();\r\n  }\r\n\r\n  for (int t=0; t<TRIES; ++t)\r\n  {\r\n    timerSqrt.start();\r\n    for (int k=0; k<repeats; ++k)\r\n    {\r\n      LLT<SquareMatrixType> chol(covMat);\r\n      acc += chol.matrixL().coeff(r,c);\r\n    }\r\n    timerSqrt.stop();\r\n  }\r\n\r\n  if (MatrixType::RowsAtCompileTime==Dynamic)\r\n    std::cout << \"dyn   \";\r\n  else\r\n    std::cout << \"fixed \";\r\n  std::cout << covMat.rows() << \" \\t\"\r\n            << (timerNoSqrt.value() * REPEAT) / repeats << \"s \"\r\n            << \"(\" << 1e-6 * cost*repeats/timerNoSqrt.value() << \" MFLOPS)\\t\"\r\n            << (timerSqrt.value() * REPEAT) / repeats << \"s \"\r\n            << \"(\" << 1e-6 * cost*repeats/timerSqrt.value() << \" MFLOPS)\\n\";\r\n\r\n\r\n  #ifdef BENCH_GSL\r\n  if (MatrixType::RowsAtCompileTime==Dynamic)\r\n  {\r\n    timerSqrt.reset();\r\n\r\n    gsl_matrix* gslCovMat = gsl_matrix_alloc(covMat.rows(),covMat.cols());\r\n    gsl_matrix* gslCopy = gsl_matrix_alloc(covMat.rows(),covMat.cols());\r\n\r\n    eiToGsl(covMat, &gslCovMat);\r\n    for (int t=0; t<TRIES; ++t)\r\n    {\r\n      timerSqrt.start();\r\n      for (int k=0; k<repeats; ++k)\r\n      {\r\n        gsl_matrix_memcpy(gslCopy,gslCovMat);\r\n        gsl_linalg_cholesky_decomp(gslCopy);\r\n        acc += gsl_matrix_get(gslCopy,r,c);\r\n      }\r\n      timerSqrt.stop();\r\n    }\r\n\r\n    std::cout << \" | \\t\"\r\n              << timerSqrt.value() * REPEAT / repeats << \"s\";\r\n\r\n    gsl_matrix_free(gslCovMat);\r\n  }\r\n  #endif\r\n  std::cout << \"\\n\";\r\n  // make sure the compiler does not optimize too much\r\n  if (acc==123)\r\n    std::cout << acc;\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n  const int dynsizes[] = {4,6,8,16,24,32,49,64,128,256,512,900,0};\r\n  std::cout << \"size            no sqrt                           standard\";\r\n//   #ifdef BENCH_GSL\r\n//   std::cout << \"       GSL (standard + double + ATLAS)  \";\r\n//   #endif\r\n  std::cout << \"\\n\";\r\n  for (uint i=0; dynsizes[i]>0; ++i)\r\n    benchLLT(Matrix<Scalar,Dynamic,Dynamic>(dynsizes[i],dynsizes[i]));\r\n\r\n  benchLLT(Matrix<Scalar,2,2>());\r\n  benchLLT(Matrix<Scalar,3,3>());\r\n  benchLLT(Matrix<Scalar,4,4>());\r\n  benchLLT(Matrix<Scalar,5,5>());\r\n  benchLLT(Matrix<Scalar,6,6>());\r\n  benchLLT(Matrix<Scalar,7,7>());\r\n  benchLLT(Matrix<Scalar,8,8>());\r\n  benchLLT(Matrix<Scalar,12,12>());\r\n  benchLLT(Matrix<Scalar,16,16>());\r\n  return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "eb601d44315178e11bc056827aa471a805ba3e08", "size": 3698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/bench/benchCholesky.cpp", "max_stars_repo_name": "rgijsen/opengl_tmp_poc", "max_stars_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/eigen3.2.10/bench/benchCholesky.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/bench/benchCholesky.cpp", "max_forks_repo_name": "rgijsen/opengl_tmp_poc", "max_forks_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T01:49:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T01:49:42.000Z", "avg_line_length": 25.8601398601, "max_line_length": 105, "alphanum_fraction": 0.5754461871, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5949884017234103}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// acvf_moving_average.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_ACVF_MOVING_AVERAGE_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_ACVF_MOVING_AVERAGE_HPP_ER_2008_04\n\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <stdexcept>\n#include <boost/call_traits.hpp>\n//#include <boost/assert.hpp>\n#include <boost/range.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/iterator/iterator_traits.hpp>\nnamespace boost { namespace accumulators{\n\n    /// This is not an accumulator, only a formula:\n    /// Under model \\f$ x_t = theta_0 e_{t-0} + ... + theta_q e_{t-q} \\f$,\n    /// where the \\f$ e_i \\f$'s are independent and \\f$Var[e_i]=1 \\f$,\n    /// \\f$ acvf(h) = sum_{j=0}^{q-h} theta_j theta_{j+h},\n    /// 0\\leq h \\leq q \\f$\n    /// Multiply result by \\f$ Var[e_i] \\f$ if it is not 1.\n    template<typename R>\n    class acvf_moving_average{\n        typedef typename range_iterator<const R>::type iterator_type;\n    public:\n        typedef std::size_t                             argument_type;\n        typedef typename\n            boost::iterator_value<iterator_type>::type  result_type;\n            acvf_moving_average(const R& coeffs_):coeffs(coeffs_){}\n            acvf_moving_average(const acvf_moving_average& that)\n            :coeffs(that.coeffs){}\n            acvf_moving_average& operator=(const acvf_moving_average& that){\n                if(&that!=this){\n                        std::runtime_error(\"acvf_moving_average::operator=\");}\n                return *this;\n            }\n            result_type operator()(argument_type delay)const{\n                typedef typename range_iterator<const R>::type iterator_type;\n                result_type res = static_cast<result_type>(0);\n                size_t h = delay;\n                if(coeffs.size()>0){\n                    std::size_t q = coeffs.size()-1;//MA(q)\n                    if(!(h>q)){\n                        iterator_type i = coeffs.begin();\n                        iterator_type e = i; std::advance(e,q+1-h);\n                        iterator_type i_shifted = i; std::advance(i_shifted,h);\n                        iterator_type e_shifted = e; std::advance(e_shifted,h);\n                        while(i<e){\n                            res+=(*i)*(*i_shifted);\n                            ++i; ++i_shifted;\n                        }//TODO accumulate(make_zip_iterator(...\n                    }\n                }\n                return res;\n            }\n    private:\n        const R& coeffs;\n    };\n\n    template<typename R>\n    acvf_moving_average<R> make_acvf_moving_average(const R& coeffs){\n        return acvf_moving_average<R>(coeffs);\n    };\n\n\n}}\n\n#endif\n", "meta": {"hexsha": "e8406b8c1829e6d7a83e247318789679f14df35e", "size": 3194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/acvf_moving_average.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/acvf_moving_average.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/acvf_moving_average.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.5866666667, "max_line_length": 79, "alphanum_fraction": 0.5194113964, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5949883882810317}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_HOUGH_TRANSFORM_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HOUGH_TRANSFORM_HPP\n\n#include <algorithm>\n#include <boost/gil/image_processing/hough_parameter.hpp>\n#include <boost/gil/rasterization/circle.hpp>\n#include <cmath>\n#include <cstddef>\n#include <iterator>\n#include <vector>\n\nnamespace boost { namespace gil {\n/// \\defgroup HoughTransform\n/// \\brief A family of shape detectors that are specified by equation\n///\n/// Hough transform is a method of mapping (voting) an object which can be described by\n/// equation to single point in accumulator array (also called parameter space).\n/// Each set pixel in edge map votes for every shape it can be part of.\n/// Circle and ellipse transforms are very costly to brute force, while\n/// non-brute-forcing algorithms tend to gamble on probabilities.\n\n/// \\ingroup HoughTransform\n/// \\brief Vote for best fit of a line in parameter space\n///\n/// The input must be an edge map with grayscale pixels. Be aware of overflow inside\n/// accumulator array. The theta parameter is best computed through factory function\n/// provided in hough_parameter.hpp\ntemplate <typename InputView, typename OutputView>\nvoid hough_line_transform(const InputView& input_view, const OutputView& accumulator_array,\n                          const hough_parameter<double>& theta,\n                          const hough_parameter<std::ptrdiff_t>& radius)\n{\n    std::ptrdiff_t r_lower_bound = radius.start_point;\n    std::ptrdiff_t r_upper_bound = r_lower_bound + radius.step_size * (radius.step_count - 1);\n\n    for (std::ptrdiff_t y = 0; y < input_view.height(); ++y)\n    {\n        for (std::ptrdiff_t x = 0; x < input_view.width(); ++x)\n        {\n            if (!input_view(x, y)[0])\n            {\n                continue;\n            }\n\n            for (std::size_t theta_index = 0; theta_index < theta.step_count; ++theta_index)\n            {\n                double theta_current =\n                    theta.start_point + theta.step_size * static_cast<double>(theta_index);\n                std::ptrdiff_t current_r =\n                    std::llround(static_cast<double>(x) * std::cos(theta_current) +\n                                 static_cast<double>(y) * std::sin(theta_current));\n                if (current_r < r_lower_bound || current_r > r_upper_bound)\n                {\n                    continue;\n                }\n                std::size_t r_index = static_cast<std::size_t>(\n                    std::llround((current_r - radius.start_point) / radius.step_size));\n                // one more safety guard to not get out of bounds\n                if (r_index < radius.step_count)\n                {\n                    accumulator_array(theta_index, r_index)[0] += 1;\n                }\n            }\n        }\n    }\n}\n\n/// \\ingroup HoughTransform\n/// \\brief Vote for best fit of a circle in parameter space according to rasterizer\n///\n/// The input must be an edge map with grayscale pixels. Be aware of overflow inside\n/// accumulator array. Rasterizer is used to rasterize a circle for voting. The circle\n/// then is translated for every origin (x, y) in x y parameter space. For available\n/// circle rasterizers, please look at rasterization/circle.hpp\ntemplate <typename ImageView, typename ForwardIterator, typename Rasterizer>\nvoid hough_circle_transform_brute(const ImageView& input,\n                                  const hough_parameter<std::ptrdiff_t> radius_parameter,\n                                  const hough_parameter<std::ptrdiff_t> x_parameter,\n                                  const hough_parameter<std::ptrdiff_t>& y_parameter,\n                                  ForwardIterator d_first, Rasterizer rasterizer)\n{\n    for (std::size_t radius_index = 0; radius_index < radius_parameter.step_count; ++radius_index)\n    {\n        const auto radius = radius_parameter.start_point +\n                            radius_parameter.step_size * static_cast<std::ptrdiff_t>(radius_index);\n        std::vector<point_t> circle_points(rasterizer.point_count(radius));\n        rasterizer(radius, {0, 0}, circle_points.begin());\n        // sort by scanline to improve cache coherence for row major images\n        std::sort(circle_points.begin(), circle_points.end(),\n                  [](const point_t& lhs, const point_t& rhs) { return lhs.y < rhs.y; });\n        const auto translate = [](std::vector<point_t>& points, point_t offset) {\n            std::transform(points.begin(), points.end(), points.begin(), [offset](point_t point) {\n                return point_t(point.x + offset.x, point.y + offset.y);\n            });\n        };\n\n        // in case somebody passes iterator to likes of std::vector<bool>\n        typename std::iterator_traits<ForwardIterator>::reference current_image = *d_first;\n\n        // the algorithm has to traverse over parameter space and look at input, instead\n        // of vice versa, as otherwise it will call translate too many times, as input\n        // is usually bigger than the coordinate portion of parameter space.\n        // This might cause extensive cache misses\n        for (std::size_t x_index = 0; x_index < x_parameter.step_count; ++x_index)\n        {\n            for (std::size_t y_index = 0; y_index < y_parameter.step_count; ++y_index)\n            {\n                const std::ptrdiff_t x = x_parameter.start_point + x_index * x_parameter.step_size;\n                const std::ptrdiff_t y = y_parameter.start_point + y_index * y_parameter.step_size;\n\n                auto translated_circle = circle_points;\n                translate(translated_circle, {x, y});\n                for (const auto& point : translated_circle)\n                {\n                    if (input(point))\n                    {\n                        ++current_image(x_index, y_index)[0];\n                    }\n                }\n            }\n        }\n        ++d_first;\n    }\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "982c28c1f9a249de7fea993c4e7c051321854e56", "size": 6227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/hough_transform.hpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/gil/image_processing/hough_transform.hpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/gil/image_processing/hough_transform.hpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4525547445, "max_line_length": 99, "alphanum_fraction": 0.6290348482, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5948158583678524}}
{"text": "/**\n *  @file    SparseSolver.hpp\n *  @brief   Solves a finite difference problem.\n *  @author  Francois Roy\n *  @date    12/01/2019\n */\n#ifndef SPARSESOLVER_H\n#define SPARSESOLVER_H\n\n#include <vector>\n#include <math.h> \n#include <Eigen/SparseCore>\n#include<Eigen/SparseCholesky>\n#include \"spdlog/spdlog.h\"\n#include \"FDProblem.hpp\"\n#include <iostream>\n\nnamespace numerical {\n\nnamespace fdm {\n\n/**\n * This class only computes the 1D diffusion problem with Dirichlet/Neumann \n * boundary conditions and heterogenous diffusion coefficient (for now).\n */\ntemplate <typename T>\nclass SparseSolver {\ntypedef Eigen::SparseMatrix<T> SpMat;\ntypedef Eigen::Triplet<T> Trip;\ntypedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\ntypedef std::vector<Eigen::Matrix<T, 3, 1>> Coord;\nprotected:\n  SpMat m_A;\n  FDProblem<T>* m_problem;\n  int m_n, m_n_x, m_n_y, m_n_z, m_n_t, m_dim;\n  T m_dt, m_dx, m_dy, m_dz, m_theta;\n  Vec m_alpha, m_x, m_y, m_z, m_b, m_u, m_f, m_f_n;\npublic:\n  SparseSolver(FDProblem<T>* problem)\n    : m_problem(problem)\n    {  \n        m_n = m_problem->n();\n        m_dim = m_problem->dim();\n        m_A = SpMat(m_n, m_n);\n        m_b = Vec::Zero(m_n);\n        m_u = m_problem->u_0();\n        T dx, dy, dz, dt, theta;\n        theta = m_problem->theta();\n        m_n_x = m_problem->n_x();\n        m_n_y = m_problem->n_y();\n        m_n_z = m_problem->n_z();\n        m_n_t = m_problem->n_t();\n        m_dt = m_problem->dt();\n        m_dx = m_problem->dx()[0];\n        m_dy = 1.0;\n        m_dz = 1.0;\n        if(m_dim != 1){\n            m_dy = m_problem->dx()[1];\n        }\n        if(m_dim == 3){\n            m_dz = m_problem->dx()[2];\n        }\n        m_theta = m_problem->theta();\n        m_alpha = Vec::Zero(m_n);\n        m_f = Vec::Zero(m_n);\n        m_f_n = Vec::Zero(m_n);\n        m_x = Vec::Zero(m_n);\n        m_y = Vec::Zero(m_n);\n        m_z = Vec::Zero(m_n);\n        const Coord& coords = m_problem->coordinates();\n        // define x, y, z, and alpha\n        for(int i=0; i<m_n; i++) {\n            m_x[i] = coords[i][0];\n            m_y[i] = coords[i][1];\n            m_z[i] = coords[i][2];\n            m_alpha[i] = m_problem->alpha(coords[i], 0.0);\n        }\n  }\n  ~SparseSolver(){\n  }\n  /**\n  * Assembles the sparse coefficient matrix \\f$\\mathbf{A}\\f$. The matrix is \n  * defined by its diagonals. The number of diagonals is related to the\n  * number of direct neighbors for interior mesh nodes. In 1D, the matrix has \n  * 3 non-zero diagonals, in 2D it has 5, and in 3D, 7. \n  *\n  * The diagonals of the matrix \\f$\\mathbf{A}\\f$ is are filled by vectorization\n  * of the loops for efficiency.\n  */\n  virtual void assemble_a(){\n    std::vector<Trip> trp;\n    Vec lower_a, upper_a, lower_b, upper_b;\n    Vec diagonal = Vec::Constant(m_n, 1.0);\n    Vec lower = Vec::Zero(m_n - 1); \n    Vec upper = Vec::Zero(m_n - 1);\n    if (m_dim > 1){  // 2D and 3D\n        // spdlog::info(\"2D: n - (nx+1) = {}\", m_n - (m_n_x + 1));\n        lower_a = Vec::Zero(m_n - (m_n_x + 1));\n        upper_a = Vec::Zero(m_n - (m_n_x + 1));\n    }\n    if (m_dim > 2){  // 3D\n        lower_b = Vec::Zero(m_n - (m_n_x + 1)*(m_n_y + 1));\n        upper_b = Vec::Zero(m_n - (m_n_x + 1)*(m_n_y + 1));\n    }\n    // The loops are vectorized for efficiency -- see bench/performances\n    if (m_dim == 1){\n        // spdlog::info(\"1D\");\n        T d = m_dt/m_dx/m_dx*m_theta/2.0;\n        spdlog::debug(\"dx: {}, dt: {}, theta: {}, alpha: {}\", \n                      m_dx, m_dt, m_theta, m_alpha[0]);\n        // Fx must be smaller than 0.5 for explicit and Crank-Nicolson schemes\n        spdlog::debug(\"Fx: {}\", m_dt/m_dx/m_dx*m_alpha[0]);\n        diagonal[0] = 0.0;\n        diagonal[m_n - 1] = 0.0;\n        diagonal.segment(1, m_n-2) += d * m_alpha.segment(2, m_n-2);\n        diagonal.segment(1, m_n-2) += d * 2.0 * m_alpha.segment(1, m_n-2);\n        diagonal.segment(1, m_n-2) += d * m_alpha.segment(0, m_n-2);\n        lower.segment(0, (m_n-1)-1) += -d * m_alpha.segment(1, m_n-2);\n        lower.segment(0, (m_n-1)-1) += -d * m_alpha.segment(0, m_n-2);\n        upper.segment(1, (m_n-1)-1) += -d * m_alpha.segment(2, m_n-2);\n        upper.segment(1, (m_n-1)-1) += -d * m_alpha.segment(1, m_n-2);\n        // boundary conditions\n        // TODO use: m_problem->coeffs_bc(Vec& dia, Vec& lower, Vec& upper, \n        //                                Vec& lower_a, Vec& upper_a, \n        //                                Vec& lower_b, Vec& upper_b, T t=0.0)\n        // instead.\n        // std::cout << m_problem->bc_type(0) << std::endl;\n        if(m_problem->bc_type(0) == 0){ // left Dirichlet\n            diagonal[0] = 1.0;\n            upper[0] = 0.0;\n          } else{  // left Neumann --> scaled by 1/2\n            // here we assume that the diffusion coefficient outside\n            // of the boundary is equal to alpha[0]\n            diagonal[0] = 0.5 + d*(0.5*m_alpha[0]+m_alpha[0]+0.5*m_alpha[1]);\n            upper[0] = -d*(m_alpha[0]+m_alpha[1]);\n          }\n        if(m_problem->bc_type(1) == 0){ // right Dirichlet\n            diagonal[m_n-1] = 1.0;\n            lower[(m_n - 1)-1] = 0.0;\n          } else {  // right Neumann --> scaled by 1/2\n            // here we assume that the diffusion coefficient outside\n            // of the boundary is equal to alpha[n-1]\n            diagonal[m_n-1] = 0.5 + d*(0.5*m_alpha[m_n-2]+m_alpha[m_n-1]+\n                  0.5*m_alpha[m_n-1]);\n            lower[(m_n - 1)-1] = -d*(m_alpha[m_n-1]+m_alpha[m_n-2]);\n          }\n\n        // insert diagonals in A\n        for(int i=0; i<m_n; i++){\n            trp.push_back(Trip(i,i,diagonal[i]));    \n        }\n        for(int i=1; i<m_n; i++){\n            trp.push_back(Trip(i,i-1,lower[i-1]));    \n        }\n        for(int i=0; i<m_n - 1; i++){\n            trp.push_back(Trip(i,i+1,upper[i]));    \n        }\n        // create sparse matrix\n        m_A.setFromTriplets(trp.begin(), trp.end());\n    } else if (m_dim == 2){\n        // spdlog::info(\"2D\");\n        // TODO\n    } else {  // 3D\n        // spdlog::info(\"3D\");\n        // TODO\n    }\n  }\n  /**\n  * Assembles the RHS vector \\f$\\mathbf{b}\\f$.\n  *\n  * \\f[\n  *    b_i = u_i^n + F\\left(1-\\Theta\\right)u_{i+1}^n-2u_i^n+u_{i-1}^n +\n  *        \\Delta t \\Theta f_i^{n+1} + \\Delta t \\left(1-\\Theta\\right)f_i^n\n  * \\f]\n  *\n  * using vectorization we get:\n  *\n  * \\f[\n  *    b[1:n_x-1] = u_n[1:n_x-1] + \\left(1-\\Theta\\right)F\n  *        \\left(u_n[2:n_x]-2u_n[1:n_x-1]+u_n[0:n_x-2]\\right) + \n  *        \\Theta\\Delta t f[1:n_x-1](n+1) + \n  *        \\left(1-\\Theta\\right)\\Delta t f[1:n_x-1](n)\n  * \\f]\n  *\n  */\n  virtual void assemble_b(T t, Vec& u_n){\n      const Coord& coords = m_problem->coordinates();\n      // TODO define the diffusion coefficient and source term only if they\n      // depend on time\n      for(int i=0; i<m_n; i++) {\n          m_alpha[i] = m_problem->alpha(coords[i], t);\n          m_f_n[i] = m_problem->source(coords[i], t);\n          m_f[i] = m_problem->source(coords[i], t + m_dt);\n      }\n      if (m_dim == 1){\n          // spdlog::info(\"1D\");\n          T d = m_dt/m_dx/m_dx*(1.0 - m_theta) / 2.0;\n          // spdlog::info(\"d: {}\", d);\n          m_b.segment(1, m_n-2) = u_n.segment(1, m_n-2);\n          m_b.segment(1, m_n-2) += d * ((m_alpha.segment(2, m_n-2) + \n            m_alpha.segment(1, m_n-2)).array() * (u_n.segment(2, m_n-2) - \n            u_n.segment(1, m_n-2)).array()).matrix();\n          m_b.segment(1, m_n-2) -= d * ((m_alpha.segment(1, m_n-2) + \n            m_alpha.segment(0, m_n-2)).array() * (u_n.segment(1, m_n-2) - \n            u_n.segment(0, m_n-2)).array()).matrix();\n          m_b.segment(1, m_n-2) += m_dt * m_theta * m_f.segment(1, m_n-2);\n          m_b.segment(1, m_n-2) += m_dt * (1.0 -m_theta) * \n            m_f_n.segment(1, m_n-2);\n          // Boundary conditions\n          m_problem->rhs_bc(m_b, u_n, m_alpha, m_f_n, m_f, m_dx, m_dy, m_dz, \n                            m_dt, m_theta, t);\n      } else if (m_dim == 2){\n        // spdlog::info(\"2D\");\n        // TODO\n      } else {  // 3D\n        // spdlog::info(\"3D\");\n        // TODO\n      }\n  }\n  /*\n  * Solve the time dependent problem.\n  * TODO: Create a VTKFile class to store the solution in a vtu file at each \n  * time steps\n  */\n  virtual T solve(){\n      // Set initial condition\n      Vec u_n = m_problem->u_0();\n      Vec u = Vec::Zero(m_problem->n());\n      int n_t = m_problem->n_t();\n      T t, l2norm=0.0;\n      Vec t_list = m_problem->t();\n      assemble_a();\n      // std::cout << m_A << std::endl;\n      Eigen::SimplicialLDLT<SpMat> solver;\n      // Time loop\n      T e=0.0;\n      for(int n=0; n<n_t; n++){\n        t = t_list[n]; \n        assemble_b(t, u_n);\n        // std::cout << m_b << std::endl;\n        // Solve\n        solver.compute(m_A);\n        if(solver.info()!=Eigen::Success) {\n            spdlog::error(\"decomposition failed\");\n            spdlog::error(\"{}\", solver.info());\n            return 999.0;\n        }\n        u = solver.solve(m_b);\n        if(solver.info()!=Eigen::Success) {\n            spdlog::error(\"solving failed\");\n            spdlog::error(\"{}\", solver.info());\n            return 999.0;\n        }\n        // spdlog::info(\"b[1]: {}, b[n-2]: {}\", m_b[1], m_b[m_n-2]);\n        // TODO Save result in file here.\n        const Coord& coords = m_problem->coordinates();\n        spdlog::debug(\"SOLUTION at time {:03.6f}:\", t+m_dt);\n        for(int i=0;i<m_n;i++){\n            e += pow(m_problem->reference(coords[i], t+m_dt)-u[i], 2.0);\n            spdlog::debug(\n              \"coord: ({}, {}, {}), exact: {:03.6f}, computed: {:03.6f}\", \n              coords[i][0], coords[i][1], coords[i][2],\n              m_problem->reference(coords[i], t+m_dt), u[i]);\n        }\n        u_n = u;\n      }\n      l2norm += pow(m_dx*m_dt*e, 0.5);\n      // spdlog::info(\"L2-norm: {}\", l2norm);\n      return l2norm;\n  }\n};\n\n}  // namespace fdm\n\n}  // namespace numerical\n\n#endif  // SPARSESOLVER_H\n", "meta": {"hexsha": "fc0fa9673b402f863b1e16300c70a6e0d423beab", "size": 9841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/SparseSolver.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/SparseSolver.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/SparseSolver.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.3992805755, "max_line_length": 79, "alphanum_fraction": 0.5164109338, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059267, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5948158561659417}}
{"text": "#ifndef __PROBABILITY_DISTRIBUTIONS__NORMAL_IMPL_HPP__\n#define __PROBABILITY_DISTRIBUTIONS__NORMAL_IMPL_HPP__\n\n#include \"normal.hpp\"\n\n#include \"const_slice.hpp\"\n#include \"slice.hpp\"\n\n#include <boost/random/normal_distribution.hpp>\n#include <cmath>\n\nnamespace ProbabilityDistributions {\n  template <class D, class W, class T>\n  Normal<D,W,T>::Normal(T mu, T sigma):\n    fixed_mu_(false),\n    fixed_sigma_(false) {\n      set_mu(mu);\n      set_sigma(sigma);\n    }\n\n  template <class D, class W, class T>\n  template <class RNG>\n  void Normal<D,W,T>::sample(MA::Array<D>& samples, size_t n_samples, RNG& rng)\n  const {\n    MA::Size::SizeType size(2);\n    size[0] = n_samples;\n    size[1] = 1;\n    samples.resize(size);\n\n    boost::random::normal_distribution<T> dist(mu_, sigma_);\n\n    D* ptr = samples.get_pointer();\n\n    for (size_t j = 0; j < n_samples; j++)\n      ptr[j] = dist(rng);\n  }\n\n  template <class D, class W, class T>\n  T Normal<D,W,T>::log_likelihood(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight) const {\n    check_data_and_weight(data, weight);\n\n    D const* ptr = data.get_pointer();\n\n    T ll = 0;\n    T sigma_likelihood = std::log(2*M_PI*sigma_*sigma_)/2;\n\n    for (size_t j = 0; j < data.total_size(); j++) {\n      T w = weight(j);\n      T s = ptr[j];\n      T local_likelihood = s - mu_;\n      local_likelihood *= local_likelihood;\n      local_likelihood *= inv_sigma2_;\n      local_likelihood += sigma_likelihood;\n      ll -= w * local_likelihood;\n    }\n\n    return ll;\n  }\n\n  template <class D, class W, class T>\n  void Normal<D,W,T>::MLE(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes) {\n    check_data_and_weight(data, weight);\n\n    D const* ptr = data.get_pointer();\n\n    T sum_0 = 0, sum_1 = 0, sum_2 = 0;\n    for (size_t j = 0; j < data.total_size(); j++) {\n      T w = weight(j);\n      T s = ptr[j];\n      sum_0 += w;\n      sum_1 += w*s;\n      sum_2 += w*s*s;\n    }\n\n    if (!fixed_mu_)\n      set_mu(sum_1/sum_0);\n    if (!fixed_sigma_)\n      set_sigma(std::sqrt((sum_2 - 2*mu_*sum_1 + mu_*mu_*sum_0)/sum_0));\n  }\n\n  template <class D, class W, class T>\n  void Normal<D,W,T>::check_data_and_weight(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight) const {\n    assert(data.size().size() == 2);\n    assert(data.size()[0] > 0);\n    assert(data.size()[1] == 1);\n    assert(weight.size().size() == 1);\n    assert(weight.size()[0] == data.size()[0]);\n  }\n};\n\n#endif\n", "meta": {"hexsha": "0f3177269eec04047fa2580c7f82feb90c3ea37b", "size": 2485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/normal_impl.hpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/normal_impl.hpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/normal_impl.hpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1578947368, "max_line_length": 79, "alphanum_fraction": 0.6181086519, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5947427180418252}}
{"text": "#include <iostream>\n#include <vector>\n#include <unordered_map>\n\n#include <boost/range/adaptors.hpp>\nnamespace ba = boost::adaptors;\n\n#include <dionysus/simplex.h>\n#include <dionysus/fields/zp.h>\n#include <dionysus/fields/z2.h>\n#include <dionysus/distances.h>\n#include <dionysus/rips.h>\n#include <dionysus/zigzag-persistence.h>\nnamespace d = dionysus;\n\n#include <dionysus/dlog/progress.h>\n\n#include <opts/opts.h>\n\n#include <common.h>     // read_points()\n\ntypedef         std::vector<float>                                      Point;\ntypedef         std::vector<Point>                                      PointContainer;\n\ntypedef         d::PairwiseDistances<PointContainer,\n                                     d::L2Distance<Point>>              PairDistances;\ntypedef         PairDistances::DistanceType                             DistanceType;\ntypedef         PairDistances::IndexType                                Vertex;\n\ntypedef         d::Rips<PairDistances>                                  Generator;\ntypedef         Generator::Simplex                                      Simplex;\ntypedef         std::set<Simplex>                                       SimplexSet;\n\ntypedef         std::vector<Vertex>                                     VertexVector;\ntypedef         std::vector<DistanceType>                               EpsilonVector;\ntypedef         std::tuple<Vertex,Vertex>                               Edge;\ntypedef         std::vector<Edge>                                       EdgeVector;\n\n//typedef         d::Z2Field                                              K;\ntypedef         d::ZpField<>                                            K;\ntypedef         d::Simplex<>                                            Simplex;\ntypedef         d::ZigzagPersistence<K>                                 Persistence;\ntypedef         typename Persistence::Index                             Index;\n\ntypedef         std::unordered_map<Simplex, Index>                      Complex;\ntypedef         d::ChainEntry<K, Simplex>                               SimplexChainEntry;\ntypedef         d::ChainEntry<K, Index>                                 ChainEntry;\n\n// debug\ntypedef         std::unordered_map<Index, Simplex>                      RComplex;\n\n// Information we need to know when a class dies\nstruct      BirthInfo\n{\n    typedef         short unsigned                                      Dimension;\n\n                    BirthInfo(DistanceType dist = DistanceType(), Dimension dim = Dimension()):\n                        distance(dist), dimension(dim)              {}\n    DistanceType    distance;\n    Dimension       dimension;\n};\n\ntypedef         std::unordered_map<Index, BirthInfo>                    BirthMap;\n\n\nint main(int argc, char** argv)\n{\n    using opts::Options;\n    using opts::Option;\n    using opts::PosOption;\n\n    short unsigned          skeleton = 2;\n    DistanceType            multiplier = 6;\n    short unsigned          p = 11;\n    std::string             infilename, diagram_name;\n    bool                    help;\n\n    Options ops;\n    ops\n        >> Option('s', \"skeleton\",      skeleton,           \"dimension of the Rips complex we want to compute\")\n        >> Option('m', \"multiplier\",    multiplier,         \"multiplier for epsilon (distance to the next maxmin point)\")\n        >> Option('p', \"prime\",         p,                  \"prime for arithmetic\")\n        >> Option('h', \"help\",          help,               \"show help message\")\n    ;\n\n    if (!ops.parse(argc,argv) || !(ops >> PosOption(infilename)) || !(ops >> PosOption(diagram_name)))\n    {\n        std::cout << \"Usage: \" << argv[0] << \" input-points diagram.out\" << std::endl;\n        std::cout << ops;\n        return 1;\n    }\n\n    PointContainer          points;\n    read_points(infilename, points);\n\n    std::ofstream   dgm_out(diagram_name);\n    std::ostream&   out = dgm_out;\n\n    // Construct distances and Rips generator\n    PairDistances           distances(points);\n    Generator               rips(distances);\n    Generator::Evaluator    size(distances);\n\n    // Order vertices and epsilons (in maxmin fashion)\n    VertexVector        vertices;\n    EpsilonVector       epsilons;\n    EdgeVector          edges;\n    DistanceType        inf     = std::numeric_limits<DistanceType>::infinity();\n\n    {\n        EpsilonVector   dist(distances.size(), inf);\n\n        vertices.push_back(distances.begin());\n        //epsilons.push_back(inf);\n        while (vertices.size() < distances.size())\n        {\n            for (Vertex v = distances.begin(); v != distances.end(); ++v)\n                dist[v] = std::min(dist[v], distances(v, vertices.back()));\n            auto max = std::max_element(dist.begin(), dist.end());\n            vertices.push_back(max - dist.begin());\n            epsilons.push_back(*max);\n        }\n        epsilons.push_back(0);\n    }\n\n    // Generate and sort all the edges\n    for (unsigned i = 0; i != vertices.size(); ++i)\n        for (unsigned j = i+1; j != vertices.size(); ++j)\n        {\n            Vertex u = vertices[i];\n            Vertex v = vertices[j];\n            if (distances(u,v) <= multiplier*epsilons[j-1])\n                edges.emplace_back(u,v);\n        }\n    std::sort(edges.begin(), edges.end(),\n              [&distances](const Edge& e1, const Edge& e2)\n              { return distances(std::get<0>(e1), std::get<1>(e1)) < distances(std::get<0>(e2), std::get<1>(e2)); });\n\n    // Construct zigzag\n    //K               k;\n    K               k(p);\n    Persistence     persistence(k);\n    Complex         simplices;\n#ifdef DIONYSUS_ZIGZAG_DEBUG\n    RComplex        rsimplices;\n#endif\n\n    // Insert vertices\n    Index       op   = 0;\n    Index       cell = 0;\n    BirthMap    births;\n    for (auto v : vertices)\n    {\n        // Add a vertex\n        Simplex s = {v};\n\n        // We don't actually need to transform the boundary here,\n        // since it's empty anyway, but we keep it for the sake of completeness\n        Index pair = persistence.add(s.boundary(persistence.field()) |\n                                                ba::transformed([&simplices](const SimplexChainEntry& e)\n                                                { return ChainEntry(e.element(), simplices.find(e.index())->second); }));\n\n#ifdef DIONYSUS_ZIGZAG_DEBUG\n        rsimplices.emplace(cell, s);\n        persistence.check_boundaries([&simplices](const Simplex& s) { return simplices[s]; },\n                                     [&rsimplices](Index i)         { return rsimplices.find(i)->second; });\n#endif\n\n        births[op++] = BirthInfo(0,0);                  // record the birth\n        simplices.emplace(std::move(s), cell++);        // record the cell id\n    }\n\n    // Process vertices\n    dlog::progress progress(vertices.size());\n    unsigned    ce = 0;         // index of the current one past last edge in the complex\n    SimplexSet  cofaces;        // record the cofaces of all the simplices that need to be removed and reinserted\n    for (unsigned stage = 0; stage != vertices.size() - 1; ++stage)\n    {\n        unsigned i = vertices.size() - 1 - stage;\n\n        /* Increase epsilon */\n        cofaces.clear();\n\n        // Add anything else that needs to be inserted into the complex\n        while (ce < edges.size())\n        {\n            Vertex u,v;\n            std::tie(u,v) = edges[ce];\n            if (distances(u,v) <= multiplier*epsilons[i-1])\n                ++ce;\n            else\n                break;\n            //std::cout << \"Adding cofaces of \" << u << ' ' << v << std::endl;\n            rips.edge_cofaces(u, v,\n                              skeleton,\n                              multiplier*epsilons[i-1],\n                              [&cofaces](Simplex&& s) { cofaces.insert(s); },\n                              vertices.begin(),\n                              vertices.begin() + i + 1);\n        }\n\n        // Insert all the cofaces\n        for (auto& s : cofaces)\n        {\n            //std::cout << \"Inserting: \" << s << std::endl;\n\n            Index pair = persistence.add(s.boundary(persistence.field()) |\n                                                    ba::transformed([&simplices](const SimplexChainEntry& e)\n                                                    { return ChainEntry(e.element(), simplices.find(e.index())->second); }));\n            simplices.emplace(std::move(s), cell);      // record the cell id\n#ifdef DIONYSUS_ZIGZAG_DEBUG\n            rsimplices.emplace(cell, s);\n            persistence.check_boundaries([&simplices](const Simplex& s) { return simplices[s]; },\n                                         [&rsimplices](Index i)         { return rsimplices.find(i)->second; });\n#endif\n            ++cell;\n\n            if (pair == Persistence::unpaired())\n                births[op++] = BirthInfo(epsilons[i-1],s.dimension());              // record the birth\n            else\n            {\n                const BirthInfo& birth = births[pair];\n                if ((birth.distance - epsilons[i-1]) != 0 && birth.dimension < skeleton)\n                    out << birth.dimension << \" \" << birth.distance << \" \" << epsilons[i-1] << std::endl;\n                births.erase(pair);\n                ++op;\n            }\n        }\n\n        /* Remove the vertex */\n        //std::cout << \"Removing vertex: \" << vertices[i] << std::endl;\n        cofaces.clear();\n        rips.vertex_cofaces(vertices[i],\n                            skeleton,\n                            multiplier*epsilons[i-1],\n                            [&cofaces](Simplex&& s) { cofaces.insert(s); },\n                            vertices.begin(),\n                            vertices.begin() + i + 1);\n        //std::cout << \"Total cofaces: \" << cofaces.size() << std::endl;\n\n        for (auto& s : cofaces | ba::reversed)\n        {\n            //std::cout << \"Removing: \" << s << std::endl;\n            Complex::const_iterator  it    = simplices.find(s);\n            Index                    c     = it->second;\n            simplices.erase(it);\n\n            Index pair  = persistence.remove(c);\n#ifdef DIONYSUS_ZIGZAG_DEBUG\n            rsimplices.erase(c);\n            persistence.check_boundaries([&simplices](const Simplex& s) { return simplices[s]; },\n                                         [&rsimplices](Index i)         { return rsimplices.find(i)->second; });\n#endif\n\n            if (pair == Persistence::unpaired())\n                births[op++] = BirthInfo(epsilons[i-1],s.dimension() - 1);          // record the birth\n            else\n            {\n                const BirthInfo& birth = births[pair];\n                if ((birth.distance - epsilons[i-1]) != 0 && birth.dimension < skeleton)\n                    out << birth.dimension << \" \" << birth.distance << \" \" << epsilons[i-1] << std::endl;\n                births.erase(pair);\n                ++op;\n            }\n        }\n\n        ++progress;\n    }\n\n    // Remove the last vertex\n    Index pair = persistence.remove(0);\n    simplices.erase((Complex::const_iterator) simplices.begin());     // TODO: add an assertion that the complex has only 1 simplex\n#ifdef DIONYSUS_ZIGZAG_DEBUG\n    rsimplices.erase(0);\n    persistence.check_boundaries([&simplices](const Simplex& s) { return simplices[s]; },\n                                 [&rsimplices](Index i)         { return rsimplices.find(i)->second; });\n#endif\n\n    const BirthInfo& birth = births[pair];\n    out << birth.dimension << \" \" << birth.distance << \" \" << epsilons[0] << std::endl;\n    ++progress;\n\n    std::cout << \"Finished\" << std::endl;\n}\n", "meta": {"hexsha": "b3b5e517b333a318e62fe8db4ae69d02be850194", "size": 11527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rips/rips-zigzag.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/rips/rips-zigzag.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/rips/rips-zigzag.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": 40.4456140351, "max_line_length": 131, "alphanum_fraction": 0.4978745554, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5947426957760009}}
{"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#ifndef BOOST_UNITS_STATIC_RATIONAL_HPP \n#define BOOST_UNITS_STATIC_RATIONAL_HPP\n\n#include <boost/integer/common_factor_ct.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/arithmetic.hpp>\n\n#ifdef __BORLANDC__\n#include <boost/mpl/eval_if.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/identity.hpp>\n#endif\n\n#include <boost/units/config.hpp>\n#include <boost/units/operators.hpp>\n\n/// \\file \n/// \\brief Compile-time rational numbers and operators.\n\nnamespace boost {\n\nnamespace units { \n\nnamespace detail {\n\nstruct static_rational_tag {};\n\n}\n\ntypedef long   integer_type;\n\n/// Compile time absolute value.\ntemplate<integer_type Value>\nstruct static_abs\n{\n    BOOST_STATIC_CONSTANT(integer_type,value = Value < 0 ? -Value : Value);\n};\n\n// Compile time rational number.\n/** \nThis is an implementation of a compile time rational number, where @c static_rational<N,D> represents\na rational number with numerator @c N and denominator @c D. Because of the potential for ambiguity arising \nfrom multiple equivalent values of @c static_rational (e.g. @c static_rational<6,2>==static_rational<3>), \nstatic rationals should always be accessed through @c static_rational<N,D>::type. Template specialization \nprevents instantiation of zero denominators (i.e. @c static_rational<N,0>). The following compile-time \narithmetic operators are provided for static_rational variables only (no operators are defined between \nlong and static_rational):\n    - @c mpl::negate\n    - @c mpl::plus\n    - @c mpl::minus\n    - @c mpl::times\n    - @c mpl::divides\n\nNeither @c static_power nor @c static_root are defined for @c static_rational. This is because template types \nmay not be floating point values, while powers and roots of rational numbers can produce floating point \nvalues. \n*/\n#ifdef __BORLANDC__\n\ntemplate<integer_type X>\nstruct make_integral_c {\n    typedef boost::mpl::integral_c<integer_type, X> type;\n};\n\ntemplate<integer_type N,integer_type D = 1>\nclass static_rational\n{\n    public:\n\n        typedef static_rational this_type;\n\n        typedef boost::mpl::integral_c<integer_type, N> N_type;\n        typedef boost::mpl::integral_c<integer_type, D> D_type;\n\n        typedef typename make_integral_c<\n            (::boost::integer::static_gcd<\n                ::boost::units::static_abs<N>::value,\n                ::boost::units::static_abs<D>::value\n            >::value)>::type gcd_type;\n        typedef typename boost::mpl::eval_if<\n            boost::mpl::less<\n                D_type,\n                boost::mpl::integral_c<integer_type, 0>\n            >,\n            boost::mpl::negate<gcd_type>,\n            gcd_type\n        >::type den_type;\n        \n    public: \n        // for mpl arithmetic support\n        typedef detail::static_rational_tag tag;\n        \n        BOOST_STATIC_CONSTANT(integer_type, Numerator =\n            (::boost::mpl::divides<N_type, den_type>::value));\n        BOOST_STATIC_CONSTANT(integer_type, Denominator =\n            (::boost::mpl::divides<D_type, den_type>::value));\n        \n        /// INTERNAL ONLY\n        typedef static_rational<N,D>    this_type;\n        \n        /// static_rational<N,D> reduced by GCD\n        typedef static_rational<\n            (::boost::mpl::divides<N_type, den_type>::value),\n            (::boost::mpl::divides<D_type, den_type>::value)\n        >  type;\n                                 \n        static BOOST_CONSTEXPR integer_type numerator()     { return Numerator; }\n        static BOOST_CONSTEXPR integer_type denominator()   { return Denominator; }\n        \n        // INTERNAL ONLY\n        BOOST_CONSTEXPR static_rational() { }\n        //~static_rational() { }\n};\n#else\ntemplate<integer_type N,integer_type D = 1>\nclass static_rational\n{\n    private:\n\n        BOOST_STATIC_CONSTEXPR integer_type nabs = static_abs<N>::value,\n                                            dabs = static_abs<D>::value;\n        \n        /// greatest common divisor of N and D\n        // need cast to signed because static_gcd returns unsigned long\n        BOOST_STATIC_CONSTEXPR integer_type den = \n            static_cast<integer_type>(boost::integer::static_gcd<nabs,dabs>::value) * ((D < 0) ? -1 : 1);\n        \n    public: \n        // for mpl arithmetic support\n        typedef detail::static_rational_tag tag;\n        \n        BOOST_STATIC_CONSTEXPR integer_type Numerator = N/den,\n            Denominator = D/den;\n        \n        /// INTERNAL ONLY\n        typedef static_rational<N,D>    this_type;\n        \n        /// static_rational<N,D> reduced by GCD\n        typedef static_rational<Numerator,Denominator>  type;\n                                 \n        static BOOST_CONSTEXPR integer_type numerator()     { return Numerator; }\n        static BOOST_CONSTEXPR integer_type denominator()   { return Denominator; }\n        \n        // INTERNAL ONLY\n        BOOST_CONSTEXPR static_rational() { }\n        //~static_rational() { }   \n};\n#endif\n\n}\n\n}\n\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\n\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\n\nBOOST_TYPEOF_REGISTER_TEMPLATE(boost::units::static_rational, (long)(long))\n\n#endif\n\nnamespace boost {\n\nnamespace units {\n\n// prohibit zero denominator\ntemplate<integer_type N> class static_rational<N,0>;\n\n/// get decimal value of @c static_rational\ntemplate<class T,integer_type N,integer_type D>\ninline BOOST_CONSTEXPR typename divide_typeof_helper<T,T>::type \nvalue(const static_rational<N,D>&)\n{\n    return T(N)/T(D);\n}\n\n} // namespace units\n\n#ifndef BOOST_UNITS_DOXYGEN\n\nnamespace mpl {\n\n#ifdef __BORLANDC__\n\ntemplate<>\nstruct plus_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            ::boost::mpl::plus<\n                boost::mpl::times<typename T0::N_type, typename T1::D_type>,\n                boost::mpl::times<typename T1::N_type, typename T0::D_type>\n            >::value,\n            ::boost::mpl::times<typename T0::D_type, typename T1::D_type>::value\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct minus_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            ::boost::mpl::minus<\n                boost::mpl::times<typename T0::N_type, typename T1::D_type>,\n                boost::mpl::times<typename T1::N_type, typename T0::D_type>\n            >::value,\n            ::boost::mpl::times<typename T0::D_type, typename T1::D_type>::value\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct times_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            ::boost::mpl::times<typename T0::N_type, typename T1::N_type>::value,\n            ::boost::mpl::times<typename T0::D_type, typename T1::D_type>::value\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct divides_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            ::boost::mpl::times<typename T0::N_type, typename T1::D_type>::value,\n            ::boost::mpl::times<typename T0::D_type, typename T1::N_type>::value\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct negate_impl<boost::units::detail::static_rational_tag>\n{\n    template<class T0>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            ::boost::mpl::negate<typename T0::N_type>::value,\n            ::boost::mpl::identity<T0>::type::Denominator\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct less_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef mpl::bool_<((mpl::minus<T0, T1>::type::Numerator) < 0)> type;\n    };\n};\n\n#else\n\ntemplate<>\nstruct plus_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            T0::Numerator*T1::Denominator+T1::Numerator*T0::Denominator,\n            T0::Denominator*T1::Denominator\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct minus_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            T0::Numerator*T1::Denominator-T1::Numerator*T0::Denominator,\n            T0::Denominator*T1::Denominator\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct times_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            T0::Numerator*T1::Numerator,\n            T0::Denominator*T1::Denominator\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct divides_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply {\n        typedef typename boost::units::static_rational<\n            T0::Numerator*T1::Denominator,\n            T0::Denominator*T1::Numerator\n        >::type type;\n    };\n};\n\ntemplate<>\nstruct negate_impl<boost::units::detail::static_rational_tag>\n{\n    template<class T0>\n    struct apply {\n        typedef typename boost::units::static_rational<-T0::Numerator,T0::Denominator>::type type;\n    };\n};\n\ntemplate<>\nstruct less_impl<boost::units::detail::static_rational_tag, boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef mpl::bool_<((mpl::minus<T0, T1>::type::Numerator) < 0)> type;\n    };\n};\n\n#endif\n\n\n}\n\n#endif\n\n} // namespace boost\n\n#endif // BOOST_UNITS_STATIC_RATIONAL_HPP\n", "meta": {"hexsha": "6d3d8187396a35b2962be2c6e76b8131925509bf", "size": 10435, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/units/static_rational.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/units/static_rational.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/units/static_rational.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.8142857143, "max_line_length": 110, "alphanum_fraction": 0.6584571155, "num_tokens": 2493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5944887439715639}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include \"DavidsonOperator.hpp\"\n#include \"MatrixFreeOperator.hpp\"\n\n\n// constructors\nDavidsonOperator::DavidsonOperator(int size, double eps, bool odiag, bool reorder)\n{\n    _size = size;\n    _odiag = odiag;\n    _sparsity = eps;\n    _reorder = reorder;\n\n    diag_el = Eigen::VectorXd(_size);\n    for (int i=0; i<_size;i++){\n        if (_odiag) diag_el(i) = static_cast<double> (i+1);\n        else diag_el(i) = static_cast<double> (1. + (std::rand() %1000 ) / 10.);\n    }\n    \n    if (_reorder)\n        _order_index = DavidsonOperator::_sort_index(diag_el);\n} \n\nEigen::ArrayXd DavidsonOperator::_sort_index(Eigen::VectorXd& V) const\n{\n    Eigen::ArrayXd idx = Eigen::ArrayXd::LinSpaced(V.rows(),0,V.rows()-1);\n    std::sort(idx.data(),idx.data()+idx.size(),\n              [&](int i1, int i2){return V[i1]<V[i2];});\n    return idx; \n}\n\nEigen::VectorXd DavidsonOperator::reorder_col(Eigen::VectorXd& col) const\n{\n    Eigen::VectorXd out = Eigen::VectorXd::Zero(_size,1);\n    for (int j=0; j < _size; j++)\n        out(j) = col(_order_index(j));\n    return out;\n}  \n\n//  get a col of the operator\nEigen::VectorXd DavidsonOperator::col(int index_orig) const\n{\n    int index = index_orig;\n    if (_reorder)\n        index = _order_index(index_orig);\n    Eigen::VectorXd col_out = Eigen::VectorXd::Zero(_size,1);    \n    for (int j=0; j < _size; j++)\n    {\n        if (j==index) {\n            col_out(j) =  diag_el(j); \n        }\n        else{\n            col_out(j) = _sparsity / std::pow( static_cast<double>(j-index),2) ;\n        }\n    }\n\n    if (_reorder)\n        col_out = DavidsonOperator::reorder_col(col_out);\n\n    return col_out;\n\n}\n\n\n\n", "meta": {"hexsha": "933c9a2c3969ba69029329f914d40d42a5969eb0", "size": 1700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DavidsonOperator.cpp", "max_stars_repo_name": "NLESC-JCER/DavidsonEigen", "max_stars_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T17:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:40:44.000Z", "max_issues_repo_path": "src/DavidsonOperator.cpp", "max_issues_repo_name": "NLESC-JCER/DavidsonEigen", "max_issues_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T14:45:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T14:45:08.000Z", "max_forks_repo_path": "src/DavidsonOperator.cpp", "max_forks_repo_name": "NLESC-JCER/DavidsonEigen", "max_forks_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:05:37.000Z", "avg_line_length": 25.0, "max_line_length": 82, "alphanum_fraction": 0.6082352941, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.5944886615316598}}
{"text": "#ifndef DZNL_QUADRATIC_LINE_SEARCHER_HPP_INCLUDED\n#define DZNL_QUADRATIC_LINE_SEARCHER_HPP_INCLUDED\n\n// C++ standard library headers\n#include <cstddef>    // for std::size_t\n#include <functional> // for std::function\n#include <stdexcept>  // for std::invalid_argument\n\n// Eigen linear algebra library headers\n#include <Eigen/Core> // for Eigen::Matrix\n\nnamespace dznl {\n\n    template <typename T>\n    class QuadraticLineSearcher {\n    private: // ========================================== INTERNAL TYPE ALIASES\n        typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXT;\n\n    private: // =============================================== MEMBER VARIABLES\n        const std::size_t n;\n        const std::function<T(const T *)> f;\n\n        const VectorXT x0;\n        VectorXT xt;\n        const VectorXT dx;\n\n        const T f0;\n\n        T best_objective_value;\n        T best_step_size;\n\n    public: // ==================================================== CONSTRUCTORS\n        explicit QuadraticLineSearcher(\n                const std::function<T(const T *)> &objective_function,\n                const VectorXT &initial_point,\n                const VectorXT &step_direction)\n                : n(static_cast<std::size_t>(initial_point.size())),\n                  f(objective_function),\n                  x0(initial_point),\n                  xt(n),\n                  dx(step_direction),\n                  f0(objective_function(initial_point.data())),\n                  best_objective_value(f0),\n                  best_step_size(0) {\n            if (initial_point.size() != step_direction.size()) {\n                throw std::invalid_argument(\n                        \"dznl::QuadraticLineSearcher constructor received \"\n                        \"initial point and step direction vectors of \"\n                        \"different sizes\");\n            }\n        }\n\n    public: // ======================================================= ACCESSORS\n        T get_best_objective_value() { return best_objective_value; }\n\n        T get_best_step_size() { return best_step_size; }\n\n    private: // ===================================== LINE SEARCH HELPER METHODS\n        T evaluate_objective_function(const T &step_size,\n                                      bool *changed = nullptr) {\n            xt = x0 + step_size * dx;\n            if (x0 == xt) {\n                if (changed != nullptr) { *changed = false; }\n                return f0;\n            } else {\n                if (changed != nullptr) { *changed = true; }\n            }\n            const T objective_value = f(xt.data());\n            if (objective_value < best_objective_value) {\n                best_objective_value = objective_value;\n                best_step_size = step_size;\n            }\n            return objective_value;\n        }\n\n    public: // ============================================= LINE SEARCH METHODS\n        void search(T step_size, std::size_t max_increases = 4) {\n            T f1 = evaluate_objective_function(step_size);\n            T f2;\n            if (f1 < f0) {\n                std::size_t num_increases = 0;\n                while (true) {\n                    const T double_step_size = step_size + step_size;\n                    f2 = evaluate_objective_function(double_step_size);\n                    if (f2 >= f1) {\n                        break;\n                    } else {\n                        step_size = double_step_size;\n                        f1 = f2;\n                        if (++num_increases >= max_increases) { return; }\n                    }\n                }\n                const T numer = 4 * f1 - f2 - 3 * f0;\n                const T denom = f1 + f1 - f2 - f0;\n                const T optimal_step_size = step_size * numer / (denom + denom);\n                evaluate_objective_function(optimal_step_size);\n            } else {\n                while (true) {\n                    const T half_step_size = step_size / 2;\n                    bool changed;\n                    f2 = evaluate_objective_function(half_step_size, &changed);\n                    if (!changed) { return; }\n                    if (f2 < f0) {\n                        break;\n                    } else {\n                        step_size = half_step_size;\n                        if (step_size == 0) { return; }\n                        f1 = f2;\n                    }\n                }\n                const T numer = f1 - 4 * f2 + 3 * f0;\n                const T denom = f1 - (f2 + f2) + f0;\n                const T optimal_step_size = step_size * numer / (4 * denom);\n                evaluate_objective_function(optimal_step_size);\n            }\n        }\n\n    }; // class QuadraticLineSearcher\n\n} // namespace dznl\n\n#endif // DZNL_QUADRATIC_LINE_SEARCHER_HPP_INCLUDED\n", "meta": {"hexsha": "9c7de320997107fbf9eb2c3b0528c16a0bf7f69b", "size": 4744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "legacy/dznl/QuadraticLineSearcher.hpp", "max_stars_repo_name": "dzhang314/dznl", "max_stars_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/dznl/QuadraticLineSearcher.hpp", "max_issues_repo_name": "dzhang314/dznl", "max_issues_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/dznl/QuadraticLineSearcher.hpp", "max_forks_repo_name": "dzhang314/dznl", "max_forks_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5691056911, "max_line_length": 80, "alphanum_fraction": 0.4759696459, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5944886453505285}}
{"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/mean_and_covar.hpp\n * @brief Functions to estimate mean value and covariance on manifolds.\n */\n\n#ifndef MEAN_AND_COVAR_HPP_\n#define MEAN_AND_COVAR_HPP_\n\n#include <Eigen/Core>\n\nnamespace MTK {\n\n/** \n * \\defgroup MeanCov Mean and Covariance Calculation\n * @todo provide functions, which only calculate either mean or covariance\n */\n//@{\n\n\n/**\n * Estimate mean value and covariance of a set of manifold values.\n * \n * @tparam M    Manifold type. Must implement boxminus, boxplus and have \n *              @c typedef scalar and @c enum DOF.\n * @tparam Cont Container Type. Elements must be convertible to @c M.\n * \n * @param mean   reference to mean value (output)\n * @param cov    reference to covariance matrix (output)\n * @param values const reference to input container\n * @param max_it maximum number of iterations (optional).\n * \n * Mean value and covariance are estimated using algorithm described in \n * @cite{Hertzberg2011}\n */\ntemplate<class M, class Cont>\ndouble mean_and_covariance(M& mean, Eigen::Matrix<typename M::scalar, M::DOF, M::DOF> &cov, \n                           const Cont &values, int max_it = 16)\n{\n\tenum {DOF = M::DOF};\n\ttypedef typename M::scalar scalar;\n\tmean = values[0];\n\tdouble res;\n\tint i=0;\n\tdo {\n\t\tEigen::Matrix<scalar, DOF, 1> mean_delta, delta;\n\t\tmean_delta.setZero();\n\t\tfor (typename Cont::const_iterator Xi = values.begin(); Xi != values.end(); ++Xi)\n\t\t{\n\t\t\tXi->boxminus(delta.data(), mean);\n\t\t\tmean_delta += delta;\n\t\t}\n\t\tmean_delta /= values.size();\n\t\tres = mean_delta.norm();\n\t\tmean.boxplus(mean_delta.data());\n\t} while (res > 1e-6 && ++i < max_it);\n\t\n\t\n\tcov.setZero();\n\tfor (typename Cont::const_iterator Xi = values.begin(); Xi != values.end(); ++Xi)\n\t{\n\t\tEigen::Matrix<scalar, DOF, 1> delta;\n\t\tXi->boxminus(delta.data(), mean);\n\t\tcov += delta * delta.transpose();\n\t}\n\tcov *= 0.5;\n\n\treturn res;\n}\n\n//@}\n\n}  // namespace MTK\n\n\n#endif /* MEAN_AND_COVAR_HPP_ */\n", "meta": {"hexsha": "922aa46c78709c4183fac6193cd4b007f76c7ac7", "size": 3614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/mtk/mean_and_covar.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/mean_and_covar.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/mean_and_covar.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": 33.1559633028, "max_line_length": 92, "alphanum_fraction": 0.7047592695, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5944886431181885}}
{"text": "#pragma once\n\n#include \"EllipsoidalCalibration.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Cholesky>\n#include <iostream>\nnamespace icarus\n{\n    template<typename T>\n    struct EllipsoidalCalibrator\n    {\n        EllipsoidalCalibrator(size_t sampleCount) :\n            mSamples(10, sampleCount),\n            mIndex(0)\n        {}\n\n        void addSample(Eigen::Matrix<T, 3, 1> const & p);\n\n        EllipsoidalCalibration<T> computeCalibration(T norm) const;\n    private:\n        static Eigen::Matrix<T, 6, 1> computePositiveEigenVector(Eigen::Matrix<T, 6, 6> const & SS);\n        static Eigen::Matrix<T, 10, 1> computeEllipsoidEquation(Eigen::Matrix<T, 10, 10> const & S);\n        static Eigen::Matrix<T, 3, 4> computeEllipsoidTransformation(Eigen::Matrix<T, 10, 1> const & v, T norm);\n\n        Eigen::Matrix<T, 10, Eigen::Dynamic> mSamples;\n        size_t mIndex;\n    };\n\n    template<typename T>\n    void EllipsoidalCalibrator<T>::addSample(Eigen::Matrix<T, 3, 1> const & p)\n    {\n        mSamples.col(mIndex) <<\n            p.x() * p.x(),\n            p.y() * p.y(),\n            p.z() * p.z(),\n            2 * p.y() * p.z(),\n            2 * p.x() * p.z(),\n            2 * p.x() * p.y(),\n            2 * p.x(),\n            2 * p.y(),\n            2 * p.z(),\n            1;\n\n        ++mIndex;\n    }\n\n    template<typename T>\n    EllipsoidalCalibration<T> EllipsoidalCalibrator<T>::computeCalibration(T norm) const\n    {\n        Eigen::Matrix<T, 10, 10> S;\n        // compute D * D.transpose() but in a way that is almost 3 times faster and uses 4 times less RAM\n        S.setZero();\n        S.template selfadjointView<Eigen::Lower>().rankUpdate(mSamples);\n        S.template triangularView<Eigen::Upper>() = S.transpose();\n\n        auto ellipsoidEquation = computeEllipsoidEquation(S);\n\n        auto ellipsoid = computeEllipsoidTransformation(ellipsoidEquation, norm);\n\n        return EllipsoidalCalibration<T>(ellipsoid);\n    }\n\n    template<typename T>\n    Eigen::Matrix<T, 6, 1> EllipsoidalCalibrator<T>::computePositiveEigenVector(Eigen::Matrix<T, 6, 6> const & SS)\n    {\n        Eigen::Matrix<T, 6, 6> C;\n        C.setZero();\n        C.template block<3, 3>(0, 0).setOnes();\n        C.diagonal() << -1, -1, -1, -4, -4, -4;\n\n        Eigen::EigenSolver<Eigen::Matrix<T, 6, 6>> decomposition(C.lu().solve(SS));\n\n        Eigen::Index maxCol;\n        decomposition.eigenvalues().real().maxCoeff(&maxCol);\n        Eigen::Matrix<T, 6, 1> v1 = decomposition.eigenvectors().col(maxCol).real();\n        if (v1(1) < 0) {\n            v1 = -v1;\n        }\n        return v1;\n    }\n\n    template<typename T>\n    Eigen::Matrix<T, 10, 1> EllipsoidalCalibrator<T>::computeEllipsoidEquation(Eigen::Matrix<T, 10, 10> const & S)\n    {\n        auto S11 = S.template block<6, 6>(0, 0);\n        auto S21 = S.template block<4, 6>(6, 0);\n        auto S12 = S.template block<6, 4>(0, 6);//S21.transpose();\n        auto S22 = S.template block<4, 4>(6, 6);\n        Eigen::Matrix<T, 4, 6> const S22a = S22.inverse() * S21;\n        Eigen::Matrix<T, 6, 6> const SS = S11 - S12 * S22a;\n\n\n        Eigen::Matrix<T, 10, 1> v;\n        auto v1 = v.template head<6>();\n        auto v2 = v.template tail<4>();\n\n        v1 = computePositiveEigenVector(SS);\n        v2 = -S22a * v1;\n\n        return v;\n    }\n\n    template<typename T>\n    Eigen::Matrix<T, 3, 4> EllipsoidalCalibrator<T>::computeEllipsoidTransformation(Eigen::Matrix<T, 10, 1> const & v, T norm)\n    {\n        Eigen::Matrix<T, 3, 3> Q;\n        Q << v[0], v[5], v[4],\n             v[5], v[1], v[3],\n             v[4], v[3], v[2];\n\n        Eigen::Matrix<T, 3, 4> ret;\n        auto Ainv = ret.template block<3, 3>(0, 0);\n        auto B = ret.col(3);\n\n        B = -Q.inverse() * v.template segment<3>(6);\n\n        T scaling = norm / sqrt(B.transpose() * Q * B - v[9]);\n\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T, 3, 3>> Qsolver(Q);\n        Ainv.noalias() = scaling * Qsolver.operatorSqrt();\n        B = -B;\n\n        std::cout << ret << std::endl;\n\n        return ret;\n    }\n}\n", "meta": {"hexsha": "fe8625ff38338e833253cbf287a6a3dea62f1120", "size": 4038, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/EllipsoidalCalibrator.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icarus/include/icarus/sensor/EllipsoidalCalibrator.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icarus/include/icarus/sensor/EllipsoidalCalibrator.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0615384615, "max_line_length": 126, "alphanum_fraction": 0.5564635958, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5944175190908748}}
{"text": "#pragma once\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n//#include \"trkapi.hpp\"\n#include <toffy/toffy_config.h>\n#include <boost/log/trivial.hpp>\n\n#if OCV_VERSION_MAJOR >= 3\n#  include <opencv2/calib3d.hpp>\n#else\n#  include <opencv2/calib3d/calib3d.hpp>\n#endif\n\nnamespace toffy {\nnamespace commons {\n\n/** helper functions for camera handling; assumes we have standard optics (90deg hfov).\n */\n\nconst int hPix=160;\nconst int vPix=120;\nconst float hFov=90.;\nconst float vFov=65.;\nconst float pixSinAngle = 0.009817319; // = sin( deg2rad(90/160) );\nconst float pixCosAngle = 0.999951809; // = cos( deg2rad(90/160) );\nconst double fl_x_reciprocal = 1.0f / 8.8345892962843834e+01;\nconst double fl_y_reciprocal = 1.0f / 8.8395902341635306e+01;\nconst double center_x = 7.9460485484676596e+01;\nconst double center_y = 5.7816728185872989e+01;\n\nstatic inline float deg2rad(float a) { return a/180.*M_PI; }\n\nstatic inline double getPixelSize(double distance )\n{\n    //float maxFinger = 0.01 / (angl*pdis);  //==pixel width\n    return pixSinAngle * distance;\n}\n\nstatic inline void depth2xyz(const cv::Point2f& p, float d, cv::Point3f& xyz)\n{\n    xyz.x = pixSinAngle*(p.x-hPix/2) *  pixSinAngle*(p.y-vPix/2) * d;\n    xyz.y = pixSinAngle*(p.x-hPix/2) *  pixCosAngle*(p.y-vPix/2) * d;\n    xyz.z = pixCosAngle*(p.x-hPix/2) * d;\n\n    float rho = deg2rad( (p.x-hPix/2) );\n    float tht = deg2rad( (p.y-vPix/2) );\n\n    xyz.x = d * sin (rho) * sin(tht) ;\n    xyz.y = d * sin (rho) * cos(tht) ;\n    xyz.z = d * cos (rho);\n}\n\nstatic inline void depth2xyz(const cv::Point2f& p, float d, cv::Vec3f& xyz)\n{\n    xyz[0] = pixSinAngle*(p.x-hPix/2) *  pixSinAngle*(p.y-vPix/2) * d;\n    xyz[1] = pixSinAngle*(p.x-hPix/2) *  pixCosAngle*(p.y-vPix/2) * d;\n    xyz[2] = pixCosAngle*(p.x-hPix/2) * d;\n}\n\n/*static inline void depth2xyz(const cv::Point2f& p, float d, track::vec3f& xyz)\n{\n    float rho = deg2rad( (p.x-hPix/2) );\n    float tht = deg2rad( (p.y-vPix/2) );\n\n    xyz.x = d * sin (rho) * sin(tht) ;\n    xyz.y = d * sin (rho) * cos(tht) ;\n    xyz.z = d * cos (rho);\n}*/\n\nstatic inline cv::Point3d pointTo3D(cv::Point2d point, float depthValue, cv::Mat cameraMatrix, cv::Size imgSize)\n{\n\t//BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << point;\n\n\tdouble fl_x_reciprocal, fl_y_reciprocal;\n\tcv::Point2d center;\n\tif(cameraMatrix.data) {\n\t    //Saving parameter from the camera matrix\n\t    fl_x_reciprocal = 1.0f / cameraMatrix.at<double>(0,0);\n\t    fl_y_reciprocal = 1.0f / cameraMatrix.at<double>(1,1);\n\t    //center_x = _cameraMatrix.at<double>(0,2);\n\t    //center_y = _cameraMatrix.at<double>(1,2);\n\n\t    double noV,\n\t\t    apertureWidth = (45/1000)*imgSize.width,\n\t\t    apertureHeight = (45/1000)*imgSize.height;\n\t    cv::calibrationMatrixValues(cameraMatrix, imgSize,\n\t\t\t\t    apertureWidth, apertureHeight,\n\t\t\t\t    noV, noV, noV, center, noV);\n\t} else {\n\t    BOOST_LOG_TRIVIAL(warning) <<\"No cameraMatrix data.\";\n\t    return cv::Point3d();\n\t}\n\n\n\tcv::Point3d out3Dp;\n\n\t//Saving parameter from the camera matrix\n\tout3Dp.x = (static_cast<float> (point.x) - center.x) * depthValue * fl_x_reciprocal; //X\n\tout3Dp.y = (static_cast<float> (point.y) - center.y) * depthValue * fl_y_reciprocal; //Y\n\tout3Dp.z = depthValue; //Z\n\n\treturn out3Dp;\n}\n\nstatic inline cv::Point2i pointTo2D(cv::Point3d point, cv::Mat cameraMatrix, cv::Size imgSize)\n{\n\t//BOOST_LOG_TRIVIAL(debug) << __FUNCTION__;\n\tdouble fl_x_reciprocal, fl_y_reciprocal;\n\tcv::Point2d center;\n\tif(cameraMatrix.data) {\n\t    //Saving parameter from the camera matrix\n\t    fl_x_reciprocal = 1.0f / cameraMatrix.at<double>(0,0);\n\t    fl_y_reciprocal = 1.0f / cameraMatrix.at<double>(1,1);\n\t    //center_x = _cameraMatrix.at<double>(0,2);\n\t    //center_y = _cameraMatrix.at<double>(1,2);\n\n\t    double noV,\n\t\t    apertureWidth = (45/1000)*imgSize.width,\n\t\t    apertureHeight = (45/1000)*imgSize.height;\n\t    cv::calibrationMatrixValues(cameraMatrix, imgSize,\n\t\t\t\t    apertureWidth, apertureHeight,\n\t\t\t\t    noV, noV, noV, center, noV);\n\t} else {\n\t    BOOST_LOG_TRIVIAL(warning) <<\"No cameraMatrix data.\";\n\t    return cv::Point2i();\n\t}\n\n\tcv::Point2i out2Dp;\n\n\tout2Dp.x = (point.x/(point.z*fl_x_reciprocal)) + center.x;\n\tout2Dp.y = (point.y/(point.z*fl_y_reciprocal)) + center.y;\n\t// Saving found pixel\n\treturn out2Dp;\n}\n\nstatic inline cv::Point3d pointTo3D(cv::Point point, float depthValue)\n{\n\tBOOST_LOG_TRIVIAL(debug) << __FUNCTION__;\n\n\tcv::Point3d out3Dp;\n\n\t//Saving parameter from the camera matrix\n\tout3Dp.x = (static_cast<float> (point.x) - center_x) * depthValue * fl_x_reciprocal; //X\n\tout3Dp.y = (static_cast<float> (point.y) - center_y) * depthValue * fl_y_reciprocal; //Y\n\tout3Dp.z = depthValue; //Z\n\n\treturn out3Dp;\n}\n\nstatic inline cv::Point2i pointTo2D(cv::Point3d point)\n{\n\tBOOST_LOG_TRIVIAL(debug) << __FUNCTION__;\n\n\tcv::Point2i out2Dp;\n\n\tout2Dp.x = (point.x/(point.z*fl_x_reciprocal)) + center_x;\n\tout2Dp.y = (point.y/(point.z*fl_y_reciprocal)) + center_y;\n\t// Saving found pixel\n\treturn out2Dp;\n}\n\n}}\n\n", "meta": {"hexsha": "beb7c28d8b41134bdf93142e2aeed2321d046954", "size": 4934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/include/toffy/common/pointTransfom.hpp", "max_stars_repo_name": "voxel-dot-at/toffy", "max_stars_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/include/toffy/common/pointTransfom.hpp", "max_issues_repo_name": "voxel-dot-at/toffy", "max_issues_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/include/toffy/common/pointTransfom.hpp", "max_forks_repo_name": "voxel-dot-at/toffy", "max_forks_repo_head_hexsha": "e9f14b186cf57225ad9eae99f227f894f0e5f940", "max_forks_repo_licenses": ["Apache-2.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.903030303, "max_line_length": 112, "alphanum_fraction": 0.6755168221, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5944175110164089}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\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 Redistributes gridpoints within the unit sphere.\n * \\image html SpecialMobius.png \"A sphere with a `mu` of 0.25.\"\n *\n * \\details A special case of the conformal Mobius transformation that\n * maps the unit ball to itself. This map depends on a single\n * parameter, `mu` \\f$ = \\mu\\f$, which is the x-coordinate of the preimage\n * of the origin under this map. This map has the fixed points \\f$x=1\\f$ and\n * \\f$x=-1\\f$. The map is singular for \\f$\\mu=1\\f$ but we have found that this\n * map is accurate up to 12 decimal places for values of \\f$\\mu\\f$ up to 0.96.\n *\n * We define the auxiliary variables\n * \\f[ r := \\sqrt{x^2 + y^2 +z^2}\\f]\n * and\n * \\f[ \\lambda := \\frac{1}{1 - 2 x \\mu + \\mu^2 r^2}\\f]\n *\n * The map corresponding to this transformation in cartesian coordinates\n * is then given by:\n *\n * \\f[\\vec{x}'(x,y,z) =\n * \\lambda\\begin{bmatrix}\n * x(1+\\mu^2) - \\mu(1+r^2)\\\\\n * y(1-\\mu^2)\\\\\n * z(1-\\mu^2)\\\\\n * \\end{bmatrix}\\f]\n *\n * The inverse map is the same as the forward map with \\f$\\mu\\f$\n * replaced by \\f$-\\mu\\f$.\n *\n * This map is intended to be used only inside the unit sphere.  A\n * point inside the unit sphere maps to another point inside the unit\n * sphere. The map can have undesirable behavior at certain points\n * outside the unit sphere: The map is singular at\n * \\f$(x,y,z) = (1/\\mu, 0, 0)\\f$ (which is outside the unit sphere\n * since \\f$|\\mu| < 1\\f$). Moreover, a point on the \\f$x\\f$-axis\n * arbitrarily close to the singularity maps to an arbitrarily large\n * value on the \\f$\\pm x\\f$-axis, where the sign depends on which side\n * of the singularity the point is on.\n *\n * A general Mobius transformation is a function on the complex plane, and\n * takes the form \\f$ f(z) = \\frac{az+b}{cz+d}\\f$, where\n * \\f$z, a, b, c, d \\in \\mathbb{C}\\f$, and \\f$ad-bc\\neq 0\\f$.\n *\n * The special case used in this map is the function\n * \\f$ f(z) = \\frac{z - \\mu}{1 - z\\mu}\\f$. This has the desired properties:\n * - The unit disk in the complex plane is mapped to itself.\n *\n * - The x-axis is mapped to itself.\n *\n * - \\f$f(\\mu) = 0\\f$.\n *\n * The three-dimensional version of this map is obtained by rotating the disk\n * in the plane about the x-axis.\n *\n * This map is useful for performing transformations along the x-axis\n * that preserve the unit disk. A concrete example of this is in the BBH\n * domain, where two BBHs with a center-of-mass at x=\\f$\\mu\\f$ can be shifted\n * such that the new center of mass is now located at x=0. Additionally,\n * the spherical shape of the outer wave-zone is preserved and, as a mobius\n * map, the spherical coordinate shapes of the black holes is also preserved.\n */\nclass SpecialMobius {\n public:\n  static constexpr size_t dim = 3;\n  explicit SpecialMobius(double mu) noexcept;\n  SpecialMobius() = default;\n  ~SpecialMobius() = default;\n  SpecialMobius(SpecialMobius&&) = default;\n  SpecialMobius(const SpecialMobius&) = default;\n  SpecialMobius& operator=(const SpecialMobius&) = default;\n  SpecialMobius& operator=(SpecialMobius&&) = 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  /// Returns boost::none for target_coords outside the unit sphere.\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> mobius_distortion(\n      const std::array<T, 3>& coords, double mu) const noexcept;\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame>\n  mobius_distortion_jacobian(const std::array<T, 3>& coords, double mu) const\n      noexcept;\n  friend bool operator==(const SpecialMobius& lhs,\n                         const SpecialMobius& rhs) noexcept;\n\n  double mu_{std::numeric_limits<double>::signaling_NaN()};\n  bool is_identity_{false};\n};\nbool operator!=(const SpecialMobius& lhs, const SpecialMobius& rhs) noexcept;\n}  // namespace CoordinateMaps\n}  // namespace domain\n", "meta": {"hexsha": "fd8f04893cf69926cf2dbf16bc54dc35bb171773", "size": 4909, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/SpecialMobius.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/SpecialMobius.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/SpecialMobius.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": 36.362962963, "max_line_length": 78, "alphanum_fraction": 0.6907720513, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5943461076659591}}
{"text": "#include \"GEFE_utility.h\"\n#include <armadillo>\n\n// Given the corresponding eigenvalues of H and H with the jth column removed, returns the ith\n// row eigenvector. This is denoted as:\n// prod(lambda_H_i - lambda_Hj_k) / prod(lambda_H_i - lambda_H_k), when i != k.\ndouble getRowiEigenvector(int i, const arma::mat& H_eigenvalues, const arma::mat& Hj_eigenvalues) {\n    const double lambda_H_i = H_eigenvalues[i];\n    double v_ij = 1;\n    const int jth_column = H_eigenvalues.size() - 1;\n\n    for (int k = 0; k < H_eigenvalues.size(); ++k) {\n        double numerator = 1;   // lambda_H_i - lambda_Hj_k\n        double denominator = 1; // lambda_H_i - lambda_H_k\n        if (k != jth_column) {\n            numerator = lambda_H_i - Hj_eigenvalues[k];\n        }\n        const double lambda_H_k = H_eigenvalues[k];\n        if (lambda_H_k != lambda_H_i) {\n            denominator = lambda_H_i - lambda_H_k;\n        }\n        v_ij *= numerator/denominator;\n    }\n    return v_ij;\n}\n\ndouble getEigenvectorFromEigenvalues(const arma::mat& H, int i, int j) {\n    if (!H.is_square()) {\n        throw std::invalid_argument(\"\\nH is not square.\");\n    }\n    if (i < 0 || i > H.n_rows - 1) {\n        throw std::invalid_argument(\"\\nj must be an integer representing the \"\n                                    \"row of the desired eigenvector values, \"\n                                    \"such that 0 <= i <= N-1.\");\n    }\n    if (j < 0 || j > H.n_cols - 1) {\n        throw std::invalid_argument(\"\\nj must be an integer representing the \"\n                                    \"column of the desired eigenvector values, \"\n                                    \"such that 0 <= j <= N-1.\");\n    }\n\n    const arma::vec H_eigenvalues = eig_sym(H);\n\n    arma::mat Hj_eigenvalues = H;\n    Hj_eigenvalues.shed_col(j);\n    Hj_eigenvalues.shed_row(j);\n\n    return getRowiEigenvector(i, H_eigenvalues, Hj_eigenvalues);\n}\n\narma::vec getEigenvectorFromEigenvalues(const arma::mat& H, const arma::vec& ii, int j) {\n    if (!H.is_square()) {\n        throw std::invalid_argument(\"\\nH is not square.\");\n    }\n    for (const double i : ii) {\n        if (i < 0 || i > H.n_rows - 1) {\n            throw std::invalid_argument(\"\\nEach i in ii must be a row of the matrix H. \"\n                                        \"For each i, 0 <= i <= N-1.\");\n        }\n    }\n    if (j < 0 || j > H.n_cols - 1) {\n        throw std::invalid_argument(\"\\nj must be an integer representing the \"\n                                    \"column of the desired eigenvector values, \"\n                                    \"such that 0 <= j <= N-1.\");\n    }\n\n    const arma::vec H_eigenvalues = eig_sym(H);\n\n    arma::mat Hj_eigenvalues = H;\n    Hj_eigenvalues.shed_col(j);\n    Hj_eigenvalues.shed_row(j);\n\n    arma::vec v_ij(ii.size(), arma::fill::zeros);\n    for (const double i : ii) {\n        v_ij[i] = getRowiEigenvector(i, H_eigenvalues, Hj_eigenvalues);\n    }\n    return v_ij;\n}", "meta": {"hexsha": "4de2746dd3aa5362da56c272e91946710188ec5a", "size": 2912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/GEFE_utility.cpp", "max_stars_repo_name": "cgyurgyik/EigenvectorsFromEigenvalues", "max_stars_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-16T01:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-16T01:27:57.000Z", "max_issues_repo_path": "cpp/GEFE_utility.cpp", "max_issues_repo_name": "cgyurgyik/eigenvectors-from-eigenvalues", "max_issues_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-16T01:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-19T16:12:16.000Z", "max_forks_repo_path": "cpp/GEFE_utility.cpp", "max_forks_repo_name": "cgyurgyik/EigenvectorsFromEigenvalues", "max_forks_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T03:18:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T03:18:44.000Z", "avg_line_length": 37.3333333333, "max_line_length": 99, "alphanum_fraction": 0.5676510989, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5942536079735481}}
{"text": "// Copyright (c) 2011 The University of Sydney\n\n#include <cmath>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/foreach.hpp>\n#include <Eigen/Core>\n#include <opencv2/core/version.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"region_properties.h\"\n#include <comma/base/exception.h>\n\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS( cs::cartesian )\n\nnamespace snark{ namespace imaging {\n\n/// compute the area of a polygon and its convex hull\n/// @param points polygon points\n/// @param area area of the polygon\n/// @param convexArea area of the convex hull\nvoid compute_area( const std::vector< cv::Point >& points, double& area, double& convexArea )\n{\n    boost::geometry::model::polygon< boost::tuple< double, double > > polygon;\n    for( unsigned int i = 0; i < points.size(); i++ )\n    {\n        boost::geometry::append( polygon, boost::make_tuple( points[i].x, points[i].y ) );\n    }\n    boost::geometry::append( polygon, boost::make_tuple( points[0].x, points[0].y ) ); // close polygon\n\n    area = boost::geometry::area( polygon );\n\n    boost::geometry::model::polygon< boost::tuple<double, double> > hull;\n    boost::geometry::convex_hull( polygon, hull );\n\n    convexArea = boost::geometry::area( hull );\n}\n\n/// constructor\n/// @param image input image, is considered as a binary image ( all non-zero pixels are 1 )\nregion_properties::region_properties ( const cv::Mat& image, double minArea ):\n    m_minArea( minArea )\n{\n    cv::Mat binary;\n    if( image.channels() == 3 )\n    {\n        cv::cvtColor( image, binary, cv::COLOR_RGB2GRAY );\n    }\n    else if( image.channels() == 1 )\n    {\n        binary = image;\n    }\n    else\n    {\n        COMMA_THROW( comma::exception, \"incorrect number of channels, should be 1 or 3, not \" << image.channels() );\n    }\n//     cv::Mat closed;\n//     cv::morphologyEx( binary, closed, cv::MORPH_CLOSE, cv::Mat::ones( 3, 3, CV_8U) );\n    std::vector< std::vector<cv::Point> > contours;\n    cv::findContours( binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE );\n    \n    for( unsigned int i = 0; i < contours.size(); i++ )\n    {\n        binary = cv::Scalar(0);\n        #if defined( CV_VERSION_EPOCH ) && CV_VERSION_EPOCH == 2\n            cv::drawContours( binary, contours, i, cv::Scalar(0xFF), 1 );\n        #else\n            cv::drawContours( binary, contours, i, cv::Scalar(0xFF), cv::FILLED );\n        #endif\n        cv::Rect rect = cv::boundingRect( cv::Mat( contours[i]) );\n        cv::Moments moments = cv::moments( binary( rect ), true );\n        double x = moments.m10/moments.m00;\n        double y = moments.m01/moments.m00;\n        double area = moments.m00; // cv::countNonZero( binary( rect ) )\n        if( area > m_minArea )\n        {\n            // see wikipedia, image moments\n            double diff = moments.nu20 - moments.nu02;\n            double a = 0.5 * ( moments.nu20 + moments.nu02 );\n            double b = 0.5 * std::sqrt( 4 * moments.nu11 * moments.nu11 + diff * diff );\n            double minEigenValue = a - b;\n            double maxEigenValue = a + b;\n    //         std::cerr << \" min \" << minEigenValue << \" max \" << maxEigenValue << std::endl;\n            double theta = 0.5 * std::atan2( 2 * moments.nu11, diff );\n            double eccentricity = 1;\n            if( std::fabs( maxEigenValue ) > 1e-15 )\n            {\n                eccentricity = std::sqrt( 1 - minEigenValue / maxEigenValue );\n            }\n\n            double polygonArea;\n            double convexArea;\n            compute_area( contours[i], polygonArea, convexArea );\n    //         std::cerr << \" area \" << area << \" polygon \" << polygonArea << \" convex \" << convexArea << std::endl;\n\n            blob blob;\n            blob.majorAxis = 2 * std::sqrt( moments.m00 * maxEigenValue );\n            blob.minorAxis = 2 * std::sqrt( moments.m00 * minEigenValue );\n            blob.orientation = theta;\n            blob.centroid = cv::Point( x + rect.x, y + rect.y );\n            blob.area = area;\n            blob.eccentricity = eccentricity;\n            blob.solidity = 0;\n            if( std::fabs( convexArea ) > 1e-15 )\n            {\n                blob.solidity = polygonArea / convexArea;\n            }\n            m_blobs.push_back( blob );\n        }\n    }    \n}\n\n/// draw debug information on the image\nvoid region_properties::show( cv::Mat& image, bool text )\n{\n    for( unsigned int i = 0; i < m_blobs.size(); i++ )\n    {\n        cv::Point centroid = m_blobs[i].centroid;\n        cv::circle( image, centroid, 3, cv::Scalar( 0, 0, 255 ), 2 );\n        std::stringstream s;\n        s << i;\n        if( text )\n        {\n            cv::putText( image, s.str(), centroid + cv::Point( 2, 2 ), cv::FONT_HERSHEY_PLAIN ,1, cv::Scalar( 0, 0, 255 ) );\n        }\n        cv::ellipse( image, centroid, cv::Size( m_blobs[i].majorAxis, m_blobs[i].minorAxis ), m_blobs[i].orientation * 180.0 / M_PI, 0, 360, cv::Scalar( 0, 255, 0 ) );\n//         std::cerr << i << \": area \" << m_blobs[i].area << \" eccentricity \" << m_blobs[i].eccentricity << \" solidity \" << m_blobs[i].solidity << std::endl;\n    }\n}\n\n} } \n\n\n", "meta": {"hexsha": "f2a81566bb18803952a4f5e0380bba19435af3ca", "size": 5202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imaging/examples/region_properties.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": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T00:24:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:24:37.000Z", "max_issues_repo_path": "imaging/examples/region_properties.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imaging/examples/region_properties.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-30T02:11:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-30T02:11:55.000Z", "avg_line_length": 38.5333333333, "max_line_length": 167, "alphanum_fraction": 0.585928489, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5942468434551179}}
{"text": "/**\n@file SBGATMassPropertiesUQ.hpp\n@class  SBGATMassPropertiesUQ\n@author Benjamin Bercovici\n@date January 2019\n\n@brief  Evaluation of the formal uncertainty in the volume, center of mass, inertia tensor parametrization\nfrom a topologically-closed, constant density polyhedron.\n\n@copyright MIT License, Benjamin Bercovici and Jay McMahon\n*/\n\n#ifndef SBGATMassPropertiesUQUQ_hpp\n#define SBGATMassPropertiesUQUQ_hpp\n\n#include <armadillo>\n#include \"SBGATMassProperties.hpp\"\n#include <SBGATFilterUQ.hpp>\n\n\n\nclass SBGATMassPropertiesUQ : public SBGATFilterUQ{\npublic:\n\n\n  /**\n  Sets the model associated to this uncertainty quantification container\n  and updates the partials of the mass properties relative to the shape\n  @param[in] pgm pointer to valid SBGATFilter\n  @param[in] \n  */\n  virtual void SetModel(vtkSmartPointer<SBGATFilter> model){this -> model = model;}\n\n  /**\n  Runs a finite-differencing based test of the implemented PGM partials\n  @param input path to obj file used to test the partials\n  @param tol relative tolerance\n  @param shape_in_meters true if tested shape has its coordinates expressed in meters\n  */\n  static void TestPartials(std::string input , double tol ,bool shape_in_meters);\n\n\n/**\nReturn the partial derivative of the shape's center of mass with respect to the shape's vertices coordinates\n@return partial derivative of the shape's center of mass with respect to the shape's vertices\n*/\n  const arma::mat & GetPartialComPartialC() const {return this -> precomputed_partialGpartialC;}\n\n\n  /**\n  Return the partial derivative of the 6 unique components of the inertia tensor {I(0,0),I(1,1),I(2,2),I(0,1),I(0,2),I(1,2)}\n  with respect to the shape coordinates\n  @return partial derivative\n  */\n  const arma::mat & GetPartialIPartialC() const {return this -> precomputed_partialIpartialC;}\n\n\n  /**\n  Return the partial derivative of the MRP orienting the body-frame (B) to principal-frame (P) dcm (PB)\n  with respect to the shape vertices coordinates\n  @return partial derivative\n  */\n  const arma::mat & GetPartialSigmaPartialC() const { return this -> precomputed_partialSigmapartialC;}\n\n\n  /**\n  Return the partial derivative of the volume\n  with respect to the shape coordinates\n  @return partial derivative\n  */\n  const arma::rowvec & GetPartialVolumePartialC() const {return this -> precomputed_partialVpartialC;}\n\n\n  /**\n  Applies prescribed deviation to all the N_vertices control points and updates model\n  @param delta_C deviation (3 * N_vertices x 1)\n  */  \n  virtual void ApplyDeviation(const arma::vec & delta_C);\n\n\n  /**\n  Evaluates the partial of the volume, center of mass and mrp orienting the principal axes\n  relative to the vertices coordinates and stores the computed partials in designated containers\n  */\n  void PrecomputeMassPropertiesPartials();\n\n  /**\n  Return the partial derivative of the unit density moments relative to a change in the inertia tensor parametrization\n  @return  partial derivative of the unit density moments relative to a change in the inertia tensor parametrization\n  */\n  const arma::mat & GetPartialUnitDensityMomentsPartialI() const{return this -> precomputed_partialUnitDensityMomentsPartialI;}\n\n\n  /**\n  Return the partial derivative of the MRP orienting the body-frame (B) to principal-frame (P) dcm (PB)\n  with respect to the inertia tensor parametrization\n  @return partial derivative\n  */\n  const arma::mat::fixed<3,6> & GetPartialSigmaPartialI() const {return this -> precomputed_partialSigmapartialI;}\n\n\n/**\n  Runs a Monte Carlo on the shape and the volume, center-of-mass and inertia tensor parametrizaton\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] all_volumes holds N_samples of the volume\n  @param[out] all_com holds N_samples of the center-of-mass\n  @param[out] all_inertia holds N_samples of the inertia tensor parametrization\n  */\n\n  static void RunMCUQVolumeCOMInertia(std::string path_to_shape,\n    const double & density,\n    const bool & shape_in_meters,\n    const arma::mat & C_CC,\n    const unsigned int & N_samples,\n    std::string output_dir,\n    int N_saved_shapes,\n    arma::mat & deviations,\n    arma::vec & all_volumes,\n    arma::mat &  all_com,\n    arma::mat & all_inertia);\n\n\n\n\n\n\n\nprotected:\n\n\n  /**\n  Returns the partial derivative of the MRP orienting the principal axes with respect to the parametrization \n  of the unit-density inertia tensor \n  @return partial derivative\n  */\n  arma::mat::fixed<3,6> PartialSigmaPartialI() const;\n\n\n/**\nReturns partial derivative of unit-density inertia moments relative to the parametrization\nof the unit-density inertia tensor\n*/\n  arma::mat::fixed<3,6>  PartialUnitDensityMomentsPartialI() const;\n\n\n\n/**\nReturn the partial derivative of the (q,r) component of the contribution of the f-facet \nto the shape's inertia tensor, relative to the f-facet \nvertices coordinates\n@param f facet index\n@param q first index\n@param r second index\n@param Tf 9x1 vector holding coordinates of vertices in facet EXPRESSED IN METERS\n@return partial derivative of the (q,r) component of the contribution of the f-facet \nto the shape's inertia tensor\n*/\n  arma::rowvec::fixed<9> PartialEqDeltaIfErPartialTf(const int & f, const int & q, const int & r,const arma::vec::fixed<9> & Tf) const;\n\n  /**\n  Return the partial derivative of the shape's center-of-mass\n  with respect to the f-th facet coordinates\n  @param f facet index\n  @return partial derivative of shape's center-of-mass with respect to facet coordinates\n  */\n  arma::mat::fixed<3,9> PartialDeltaComPartialTf(const int & f) const;\n\n  /**\n  Return the partial derivative of e_q.T * DeltaIOverDeltaVfEr * e_r with respect to the f-facet \n  vertices coordinates\n  @param e_q first 3x1 vector canonical unit vector\n  @param e_r first 3x1 vector canonical unit vector\n  @param Tf 9x1 vector holding coordinates of vertices in facet EXPRESSED IN METERS\n  @return the partial derivative of e_q.T * DeltaIOverDeltaVfEr * e_r with respect to the f-facet \n  vertices coordinates\n  */\n  arma::rowvec::fixed<9> PartialEqDeltaIOverDeltaVfErPartialTf(const arma::vec::fixed<3> & e_q,const arma::vec::fixed<3> & e_r,\n    const arma::vec::fixed<9> & Tf) const;\n\n\n\n\n\n  /**\n  Return the partial derivative of the volume of the tetrahedron subtended by facet f\n  with respect to the facet coordinates\n  @param f facet index\n  @return partial derivative of tetrahedron volume with respect to facet coordinates\n  */\n  arma::rowvec::fixed<9> PartialDeltaVfPartialTf(const int & f) const;\n\n  /**\n  Return the partial derivative of the center of mass of the considered tetrahedron\n  with respect to the facet coordinates\n  @return partial derivative of center of mass with respect to facet coordinates\n  */\n  static arma::mat::fixed<3,9> PartialDeltaCMfPartialTf();\n\n  /**\n  Return the partial derivative of the tetrahedron's inertia tensor parametrization\n  relative to the facet coordinates\n  @param f facet index\n  @return partial derivative of the tetrahedron's inertia tensor parametrization\n  relative to the facet coordinates \n  */\n  arma::mat::fixed<6,9> PartialDeltaIfPartialTf(const int & f) const;\n\n\n  /**\n  Return the partial derivative of a tetrahedron's  inertia-times-volume tensor parametrization\n  with respect to the subtending facet's vertices coordinates\n  @param f facet index\n  @return partial derivative of the tetrahedron's inertia-times-volume tensor parametrization\n  with respect to the subtending facet's vertices coordinates\n  */\n  arma::mat::fixed<6,9> PartialDeltaIOverDeltaVPartialTf(const int & f) const;\n\n  /**\n  Applies deviation to the coordinates of the vertices in the prescribed facet\n  and updates the pgm\n  @param delta_Tf deviation\n  @param f facet index\n  */\n  virtual void ApplyTfDeviation(arma::vec::fixed<9> delta_Tf,const int & f);\n\n  \n  static void TestPartialDeltaVfPartialTf(std::string input,double tol,bool shape_in_meters);\n  static void TestPartialDeltaIOverDeltaVPartialTf(std::string input,double tol,bool shape_in_meters);\n  static void TestPartialDeltaIfPartialTf(std::string input,double tol,bool shape_in_meters);\n  static void TestPartialDeltaVPartialC(std::string input,double tol,bool shape_in_meters);\n  static void TestGetPartialVolumePartialC(std::string input,double tol,bool shape_in_meters);\n  static void TestGetPartialComPartialC(std::string input,double tol,bool shape_in_meters);\n  static void TestGetPartialIPartialC(std::string input,double tol,bool shape_in_meters);\n  static void TestGetPartialAllInertiaPartialC(std::string input,double tol,bool shape_in_meters) ;\n  static void TestPartialEqDeltaIfErPartialTf(std::string input,double tol,bool shape_in_meters);\n  static void TestGetPartialSigmaPartialC(std::string input,double tol,bool shape_in_meters);\n\n  arma::rowvec precomputed_partialVpartialC;\n  arma::mat precomputed_partialGpartialC;\n  arma::mat precomputed_partialSigmapartialC;\n  arma::mat precomputed_partialIpartialC;\n  arma::mat::fixed<3,6> precomputed_partialUnitDensityMomentsPartialI;\n  arma::mat::fixed<3,6> precomputed_partialSigmapartialI;\n\n\n\n\n};\n\n#endif\n\n\n", "meta": {"hexsha": "12ae50ad6caafb2b43abeb9dc59491eed5a00ea3", "size": 9825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATMassPropertiesUQ.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATMassPropertiesUQ.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATMassPropertiesUQ.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 37.3574144487, "max_line_length": 135, "alphanum_fraction": 0.7696692112, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083608, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.594246834288262}}
{"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 * @ingroup openOR_core\n */\n\n#ifndef openOR_core_math_utilities_hpp\n#define openOR_core_math_utilities_hpp\n\n#include <cmath>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp> \n\nnamespace openOR {\n\n   namespace Math {\n\n      /**\n       * \\brief square\n       * @ingroup openOR_core\n       */\n      template<typename T>\n      T square(const T& arg) { return arg * arg; }\n\n\n      /**\n       * \\brief clamp\n       * @ingroup openOR_core\n       */\n      template<typename T>\n      T clamp(const T& arg, const T& min, const T& max) { return std::min<T>(max, std::max<T>(min, arg)); }\n\n\n      /**\n       * \\brief rounds a double to the next integer value\n       */\n      inline double round(const double& d)\n      {\n         return floor(d + 0.5);\n      }\n\n\n      /**\n       * \\brief rounds a float to the next integer value\n       */\n      inline float round(const float& f)\n      {\n         return floorf(f + 0.5f);\n      }\n\n\n      /**\n       * \\brief rounds a long double to the next integer value\n       */\n\n      inline long double round(const long double& d)\n      {\n         return floorl(d + 0.5);\n      }\n\n\n      /**\n       * \\brief nextPowerOfTwo\n       * @ingroup openOR_core\n       */\n      inline static unsigned int nextPowerOfTwo(unsigned int v) {\n         --v;\n         v |= v >> 1;\n         v |= v >> 2;\n         v |= v >> 4;\n         v |= v >> 8;\n         v |= v >> 16;\n         ++v;\n         return v;\n      }\n\n\n      /**\n       * \\brief nextPowerOfTwo\n       * @ingroup openOR_core\n       */\n      inline static unsigned short nextPowerOfTwo(unsigned short v) {\n         --v;\n         v |= v >> 1;\n         v |= v >> 2;\n         v |= v >> 4;\n         v |= v >> 8;\n         ++v;\n         return v;\n      }\n\n      /**\n       * \\brief isPowerOfTwo\n       * @ingroup openOR_core\n       */\n      inline bool isPowerOfTwo(unsigned int n) { return ((n & (n - 1)) == 0); }\n      \n      \n      /**\n       * \\brief isPowerOfTwo\n       * @ingroup openOR_core\n       */\n      inline bool isPowerOfTwo(unsigned short n) { return ((n & (n - 1)) == 0); }\n\n\n      /**\n       * \\brief Solver for linear function A*x=y\n       */\n      template<typename Type>\n      boost::numeric::ublas::vector<Type> solve(const boost::numeric::ublas::matrix<Type>& A, const boost::numeric::ublas::vector<Type>& y)\n      {\n         //create a permutation matrix for the LU-factorization\n         boost::numeric::ublas::matrix<Type> matA(A);\n         boost::numeric::ublas::permutation_matrix<std::size_t> pm(matA.size1());\n         int res = boost::numeric::ublas::lu_factorize(matA, pm);\n         if (res == 0)\n            return boost::numeric::ublas::vector<Type>();\n\n         boost::numeric::ublas::vector<Type> vecX(y);\n         boost::numeric::ublas::lu_substitute(matA, pm, vecX);\n         return vecX;\n      }\n\n   }\n}\n#endif\n", "meta": {"hexsha": "3ff8da89db88e1a6b166829e8d2947621d85ec32", "size": 3543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/utilities.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/utilities.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/utilities.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": 25.4892086331, "max_line_length": 139, "alphanum_fraction": 0.4930849563, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5941479430890192}}
{"text": "//============================================================================//\n//---------------- pnt_integrity/GeodeticConverter.cpp ---------*- C++ -*-----//\n//============================================================================//\n// BSD 3-Clause License\n//\n// Copyright (c) 2017, ETHZ ASL\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/// Third-party.  Downloaded from: https://github.com/ethz-asl/geodetic_utils //\n//============================================================================//\n#ifndef GEODETIC_CONVERTER_H_\n#define GEODETIC_CONVERTER_H_\n\n#include <Eigen/Dense>\n\nnamespace geodetic_converter\n{\n// Geodetic system parameters\n/// \\brief Equatorial radius (a), in meters\nconst double kSemimajorAxis = 6378137;\n/// \\brief Semi-minor radius (b), in meters\nconst double kSemiminorAxis = 6356752.3142;\n/// \\brief First eccentricity squared (e2), dimensionless\n/// e2 = (a^2 - b^2) / a^2 = f * (2 - f)\nconst double kFirstEccentricitySquared = 6.69437999014 * 0.001;\n/// \\brief Second eccentricity squared (e'2), dimensionless\n/// e'2 = (a^2 - b^2) / b^2 = e^2 / (1 - e^2) = e2 / (1 - e2)\nconst double kSecondEccentricitySquared = 6.73949674228 * 0.001;\n/// \\brief  flattening, dimensionless\nconst double kFlattening = 1 / 298.257223563;\n/// \\brief Pi (pi), dimensionless\nconst double PI = 3.14159265358979323846;\n\n/// \\brief Class to implement gedetic conversions for the pnt_integrity library\nclass GeodeticConverter\n{\npublic:\n  /// \\brief Constructor for converter object\n  ///\n  /// Constructor initializes the reference flag to false.\n  GeodeticConverter() { haveReference_ = false; }\n\n  /// \\brief Destructor for the converter object\n  ~GeodeticConverter() {}\n\n  // Default copy constructor and assignment operator are OK.\n\n  /// \\brief Returns the reference flag\n  ///\n  /// Returns a flag to indicate if the converter's reference position has\n  /// been set.\n  bool isInitialised() { return haveReference_; }\n\n  /// \\brief Returns the reference position\n  ///\n  /// Returns the reference position with the  latitude / longitude in radians\n  /// and altitude in meters\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  void getReference(double* latitude, double* longitude, double* altitude)\n  {\n    *latitude  = initial_latitude_;\n    *longitude = initial_longitude_;\n    *altitude  = initial_altitude_;\n  }\n\n  /// \\brief Sets the reference position\n  ///\n  /// Sets the reference to the provided position (LLA)\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  void initialiseReference(const double latitude,\n                           const double longitude,\n                           const double altitude)\n  {\n    // Save NED origin\n    initial_latitude_  = latitude;\n    initial_longitude_ = longitude;\n    initial_altitude_  = altitude;\n\n    // Compute ECEF of NED origin\n    geodetic2Ecef(latitude,\n                  longitude,\n                  altitude,\n                  &initial_ecef_x_,\n                  &initial_ecef_y_,\n                  &initial_ecef_z_);\n\n    // Compute ECEF to NED and NED to ECEF matrices\n    double phiP = atan2(\n      initial_ecef_z_, sqrt(pow(initial_ecef_x_, 2) + pow(initial_ecef_y_, 2)));\n\n    ecef_to_ned_matrix_ = nRe(phiP, initial_longitude_);\n    ned_to_ecef_matrix_ =\n      nRe(initial_latitude_, initial_longitude_).transpose();\n\n    haveReference_ = true;\n  }\n\n  /// \\brief Converts the provided LLA to ECEF\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param x The ECEF X psoition in meters\n  /// \\param y The ECEF Y position in meters\n  /// \\param z The ECEF Z position in meters\n  void geodetic2Ecef(const double latitude,\n                     const double longitude,\n                     const double altitude,\n                     double*      x,\n                     double*      y,\n                     double*      z)\n  {\n    // Convert geodetic coordinates to ECEF.\n    // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22\n    double lat_rad = latitude;\n    double lon_rad = longitude;\n    double xi =\n      sqrt(1 - kFirstEccentricitySquared * sin(lat_rad) * sin(lat_rad));\n    *x = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * cos(lon_rad);\n    *y = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * sin(lon_rad);\n    *z = (kSemimajorAxis / xi * (1 - kFirstEccentricitySquared) + altitude) *\n         sin(lat_rad);\n  }\n\n  /// \\brief Converts the provided ECEF to LLA\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param x The ECEF X psoition in meters\n  /// \\param y The ECEF Y position in meters\n  /// \\param z The ECEF Z position in meters\n  void ecef2Geodetic(const double x,\n                     const double y,\n                     const double z,\n                     double*      latitude,\n                     double*      longitude,\n                     double*      altitude)\n  {\n    // Convert ECEF coordinates to geodetic coordinates.\n    // J. Zhu, \"Conversion of Earth-centered Earth-fixed coordinates\n    // to geodetic coordinates,\" IEEE Transactions on Aerospace and\n    // Electronic Systems, vol. 30, pp. 957-961, 1994.\n\n    double r = sqrt(x * x + y * y);\n    double Esq =\n      kSemimajorAxis * kSemimajorAxis - kSemiminorAxis * kSemiminorAxis;\n    double F = 54 * kSemiminorAxis * kSemiminorAxis * z * z;\n    double G = r * r + (1 - kFirstEccentricitySquared) * z * z -\n               kFirstEccentricitySquared * Esq;\n    double C =\n      (kFirstEccentricitySquared * kFirstEccentricitySquared * F * r * r) /\n      pow(G, 3);\n    double S = cbrt(1 + C + sqrt(C * C + 2 * C));\n    double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G);\n    double Q =\n      sqrt(1 + 2 * kFirstEccentricitySquared * kFirstEccentricitySquared * P);\n    double r_0 =\n      -(P * kFirstEccentricitySquared * r) / (1 + Q) +\n      sqrt(0.5 * kSemimajorAxis * kSemimajorAxis * (1 + 1.0 / Q) -\n           P * (1 - kFirstEccentricitySquared) * z * z / (Q * (1 + Q)) -\n           0.5 * P * r * r);\n    double U   = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) + z * z);\n    double V   = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) +\n                    (1 - kFirstEccentricitySquared) * z * z);\n    double Z_0 = kSemiminorAxis * kSemiminorAxis * z / (kSemimajorAxis * V);\n    *altitude =\n      U * (1 - kSemiminorAxis * kSemiminorAxis / (kSemimajorAxis * V));\n    *latitude  = atan((z + kSecondEccentricitySquared * Z_0) / r);\n    *longitude = atan2(y, x);\n  }\n\n  /// \\brief Converts the provided ECEF to NED\n  ///\n  /// \\param east NED east in meters\n  /// \\param north NED north in meters\n  /// \\param down NED down in meters\n  /// \\param x The ECEF X psoition in meters\n  /// \\param y The ECEF Y position in meters\n  /// \\param z The ECEF Z position in meters\n  void ecef2Ned(const double x,\n                const double y,\n                const double z,\n                double*      north,\n                double*      east,\n                double*      down)\n  {\n    // Converts ECEF coordinate position into local-tangent-plane NED.\n    // Coordinates relative to given ECEF coordinate frame.\n\n    Eigen::Vector3d vect, ret;\n    vect(0) = x - initial_ecef_x_;\n    vect(1) = y - initial_ecef_y_;\n    vect(2) = z - initial_ecef_z_;\n    ret     = ecef_to_ned_matrix_ * vect;\n    *north  = ret(0);\n    *east   = ret(1);\n    *down   = -ret(2);\n  }\n\n  /// \\brief Converts the provided NED to ECEF\n  ///\n  /// \\param east NED east in meters\n  /// \\param north NED north in meters\n  /// \\param down NED down in meters\n  /// \\param x The ECEF X psoition in meters\n  /// \\param y The ECEF Y position in meters\n  /// \\param z The ECEF Z position in meters\n  void ned2Ecef(const double north,\n                const double east,\n                const double down,\n                double*      x,\n                double*      y,\n                double*      z)\n  {\n    // NED (north/east/down) to ECEF coordinates\n    Eigen::Vector3d ned, ret;\n    ned(0) = north;\n    ned(1) = east;\n    ned(2) = -down;\n    ret    = ned_to_ecef_matrix_ * ned;\n    *x     = ret(0) + initial_ecef_x_;\n    *y     = ret(1) + initial_ecef_y_;\n    *z     = ret(2) + initial_ecef_z_;\n  }\n\n  /// \\brief Converts the provided LLA to NED\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param east NED east in meters\n  /// \\param north NED north in meters\n  /// \\param down NED down in meters\n  void geodetic2Ned(const double latitude,\n                    const double longitude,\n                    const double altitude,\n                    double*      north,\n                    double*      east,\n                    double*      down)\n  {\n    // Geodetic position to local NED frame\n    double x, y, z;\n    geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z);\n    ecef2Ned(x, y, z, north, east, down);\n  }\n\n  /// \\brief Converts the provided NED to LLA\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param east NED east in meters\n  /// \\param north NED north in meters\n  /// \\param down NED down in meters\n  void ned2Geodetic(const double north,\n                    const double east,\n                    const double down,\n                    double*      latitude,\n                    double*      longitude,\n                    double*      altitude)\n  {\n    // Local NED position to geodetic coordinates\n    double x, y, z;\n    ned2Ecef(north, east, down, &x, &y, &z);\n    ecef2Geodetic(x, y, z, latitude, longitude, altitude);\n  }\n\n  /// \\brief Converts the provided LLA to ENU\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param east ENU east in meters\n  /// \\param north ENU north in meters\n  /// \\param up ENU up in meters\n  void geodetic2Enu(const double latitude,\n                    const double longitude,\n                    const double altitude,\n                    double*      east,\n                    double*      north,\n                    double*      up)\n  {\n    // Geodetic position to local ENU frame\n    double x, y, z;\n    geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z);\n\n    double aux_north, aux_east, aux_down;\n    ecef2Ned(x, y, z, &aux_north, &aux_east, &aux_down);\n\n    *east  = aux_east;\n    *north = aux_north;\n    *up    = -aux_down;\n  }\n\n  /// \\brief Converts the provided ENU to LLA\n  ///\n  /// \\param latitude Latitude in radians\n  /// \\param longitude Longitude in radians\n  /// \\param altitude Altitude in meters\n  /// \\param east ENU east in meters\n  /// \\param north ENU north in meters\n  /// \\param up ENU up in meters\n  void enu2Geodetic(const double east,\n                    const double north,\n                    const double up,\n                    double*      latitude,\n                    double*      longitude,\n                    double*      altitude)\n  {\n    // Local ENU position to geodetic coordinates\n\n    const double aux_north = north;\n    const double aux_east  = east;\n    const double aux_down  = -up;\n    double       x, y, z;\n    ned2Ecef(aux_north, aux_east, aux_down, &x, &y, &z);\n    ecef2Geodetic(x, y, z, latitude, longitude, altitude);\n  }\n\nprivate:\n  inline Eigen::Matrix3d nRe(const double lat_radians, const double lon_radians)\n  {\n    const double sLat = sin(lat_radians);\n    const double sLon = sin(lon_radians);\n    const double cLat = cos(lat_radians);\n    const double cLon = cos(lon_radians);\n\n    Eigen::Matrix3d ret;\n    ret(0, 0) = -sLat * cLon;\n    ret(0, 1) = -sLat * sLon;\n    ret(0, 2) = cLat;\n    ret(1, 0) = -sLon;\n    ret(1, 1) = cLon;\n    ret(1, 2) = 0.0;\n    ret(2, 0) = cLat * cLon;\n    ret(2, 1) = cLat * sLon;\n    ret(2, 2) = sLat;\n\n    return ret;\n  }\n\n  inline double rad2Deg(const double radians) { return (radians / PI) * 180.0; }\n\n  inline double deg2Rad(const double degrees) { return (degrees / 180.0) * PI; }\n\n  double initial_latitude_;\n  double initial_longitude_;\n  double initial_altitude_;\n\n  double initial_ecef_x_;\n  double initial_ecef_y_;\n  double initial_ecef_z_;\n\n  Eigen::Matrix3d ecef_to_ned_matrix_;\n  Eigen::Matrix3d ned_to_ecef_matrix_;\n\n  bool haveReference_;\n\n};  // class GeodeticConverter\n}  // namespace geodetic_converter\n\n#endif  // GEODETIC_CONVERTER_H_\n", "meta": {"hexsha": "e988cdc2ce265ff4ad771e0f8d375ab4bedcc78f", "size": 14192, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pnt_integrity/pnt_integrity/include/pnt_integrity/GeodeticConverter.hpp", "max_stars_repo_name": "yxw027/PNT-Integrity", "max_stars_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-17T13:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T13:16:46.000Z", "max_issues_repo_path": "pnt_integrity/pnt_integrity/include/pnt_integrity/GeodeticConverter.hpp", "max_issues_repo_name": "yxw027/PNT-Integrity", "max_issues_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "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": "pnt_integrity/pnt_integrity/include/pnt_integrity/GeodeticConverter.hpp", "max_forks_repo_name": "yxw027/PNT-Integrity", "max_forks_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "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.9291139241, "max_line_length": 81, "alphanum_fraction": 0.6118235626, "num_tokens": 3741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5941479374874362}}
{"text": "#ifndef BURKARDT_NON_HPP\n#define BURKARDT_NON_HPP\n\n/*\n * nonlinear equation example set from\n *  http://people.sc.fsu.edu/~jburkardt/f_src/test_nonlin/test_nonlin.html\n *  http://people.sc.fsu.edu/~jburkardt/f_src/test_nonlin/test_nonlin.f90\n */\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\nstruct GenRosen {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint i;\n\n\t\ty(0) = 1. - x(0);\n\t\tfor (i=1; i<s; i++) {\n\t\t\ty(i) = 10. * (x(i) - x(i-1) * x(i-1));\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Powell {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(4);\n\n\t\ty(0) = x(0) + 10. * x(1);\n\t\ty(1) = sqrt(5.) * (x(2) - x(3));\n\t\ty(2) = (x(1) - 2. * x(2)) * (x(1) - 2. * x(2));\n\t\ty(3) = sqrt(10.) * (x(0) - x(3)) * (x(0) - x(3));\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(4);\n\t\tfor (i=0; i<4; i++) {\n\t\t\tx(i).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Wood {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(4);\n\t\tT tmp1, tmp2;\n\n\t\ttmp1 = x(1) - x(0) * x(0);\n\t\ttmp2 = x(3) - x(2) * x(2);\n\n\t\ty(0) = -200. * x(0) * tmp1 - (1. - x(0));\n\t\ty(1) = 200. * tmp1 + 20.2 * (x(1) - 1.) + 19.8 * (x(3) - 1.);\n\t\ty(2) = -180. * x(2) * tmp2 - (1. - x(2));\n\t\ty(3) = 180. * tmp2 + 20.2 * (x(3) - 1.) + 19.8 * (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(4);\n\t\tfor (i=0; i<4; i++) {\n\t\t\tx(i).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Watson {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint i, j, k;\n\t\tT sum1, sum2, tmp, ti;\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\ty(i) = 0;\n\t\t}\n\n\t\tfor (i=1; i<=29; i++) {\n\t\t\tti = i / 29.;\n\t\t\tsum1 = 0.;\n\t\t\ttmp = 1.;\n\t\t\tfor (j=1; j<s; j++) {\n\t\t\t\tsum1 += (T)j * tmp * x(j);\n\t\t\t\ttmp *= ti;\n\t\t\t}\n\t\t\tsum2 = 0;\n\t\t\ttmp = 1.;\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\tsum2 += tmp * x(j);\n\t\t\t\ttmp *= ti;\n\t\t\t}\n\t\t\ttmp = (sum1 - sum2 * sum2 - 1.) / ti;\n\t\t\tfor (k=0; k<s; k++) {\n\t\t\t\ty(k) += tmp * ((T)k - 2. * ti * sum2);\n\t\t\t\ttmp *= ti;\n\t\t\t}\n\t\t}\n\n\t\ty(0) += 3. * x(0) - 2. * x(0) + x(1) + 2. * x(0)*x(0)*x(0);\n\t\ty(1) += x(1) - x(0) * x(0) - 1.;\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Chebyquad {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint i, j;\n\t\tT t1, t2, t3;\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\ty(i) = 0.;\n\t\t}\n\n\t\tfor (j=0; j<s; j++) {\n\t\t\tt1 = 1.;\n\t\t\tt2 = x(j);\n\t\t\tfor (i=0; i<s; i++) {\n\t\t\t\ty(i) += t2;\n\t\t\t\tt3 = 2. * x(j) * t2 - t1;\n\t\t\t\tt1 = t2;\n\t\t\t\tt2 = t3;\n\t\t\t}\n\t\t}\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\ty(i) /= (T)s;\n\t\t}\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\tif ( (i+1) % 2 == 0) {\n\t\t\t\ty(i) += 1. / (T)((i+1)*(i+1)-1);\n\t\t\t}\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Brown {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint i, j;\n\t\tT sum, prod;\n\n\t\tsum = 0.;\n\t\tfor (i=0; i<s; i++) {\n\t\t\tsum += x(i);\n\t\t}\n\n\t\tfor (i=0; i<s-1; i++) {\n\t\t\ty(i) = x(i) + sum - (T)(s+1);\n\t\t}\n\n\t\tprod = 1.;\n\t\tfor (i=0; i<s; i++) {\n\t\t\tprod *= x(i);\n\t\t}\n\n\t\ty(s-1) = prod - 1.;\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct DBVP {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint k;\n\t\tT h, tmp;\n\n\t\th = 1. / (s + 1);\n\n\t\tfor (k=0; k<s; k++) {\n\t\t\ttmp = x(k) + (T)(k+1) * h + 1.;\n\t\t\ty(k) = 2. * x(k) + 0.5 * h * h * tmp*tmp*tmp;\n\t\t\tif (k > 0) {\n\t\t\t\ty(k) -= x(k-1);\n\t\t\t}\n\t\t\tif (k < s-1) {\n\t\t\t\ty(k) -= x(k+1);\n\t\t\t}\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct DIntEq {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint j, k;\n\t\tT h, tk, tj, sum1, sum2, tmp;\n\n\t\th = 1. / (s + 1);\n\n\t\tfor (k=0; k<s; k++) {\n\t\t\ttk = (k+1.) / (s+1.);\n\t\t\tsum1 = 0.;\n\t\t\tfor (j=0; j<k+1; j++) {\n\t\t\t\ttj = (j+1.) * h;\n\t\t\t\ttmp = x(j) + tj + 1.;\n\t\t\t\tsum1 += tj * tmp*tmp*tmp;\n\t\t\t}\n\t\t\tsum2 = 0.;\n\t\t\tfor (j=k+1; j<s; j++) {\n\t\t\t\ttj = (j+1.) * h;\n\t\t\t\ttmp = x(j) + tj + 1.;\n\t\t\t\tsum2 += (1. - tj) * tmp*tmp*tmp;\n\t\t\t}\n\t\t\ty(k) = x(k) + h * ( (1. - tk) * sum1 + tk * sum2) / 2.;\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct VDim {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint j;\n\t\tT sum1, tmp;\n\n\t\tsum1 = 0.;\n\n\t\tfor (j=0; j<s; j++) {\n\t\t\tsum1 += (j+1.) * (x(j) - 1.);\n\t\t}\n\n\t\ttmp = sum1 * (1. + 2. * sum1 * sum1);\n\n\t\tfor (j=0; j<s; j++) {\n\t\t\ty(j) = x(j) - 1. + (j+1.) * tmp;\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Broyden {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint k;\n\n\t\tfor (k=0; k<s; k++) {\n\t\t\ty(k) = (3. - 2. * x(k)) * x(k) + 1.;\n\t\t\tif (k > 0) {\n\t\t\t\ty(k) -= x(k-1);\n\t\t\t}\n\t\t\tif (k < s-1) {\n\t\t\t\ty(k) -= 2. * x(k+1);\n\t\t\t}\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct BroydenBand {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\t\tint k, k1, k2, j;\n\t\tT tmp;\n\n\t\tfor (k=0; k<s; k++) {\n\t\t\tk1 = k - 5;\n\t\t\tif (k1 < 0) k1 = 0;\n\t\t\tk2 = k + 1;\n\t\t\tif (k2 > s-1) k2 = s-1;\n\n\t\t\ttmp = 0.;\n\t\t\tfor (j=k1; j<=k2; j++) {\n\t\t\t\tif (j != k) {\n\t\t\t\t\ttmp += x(j) * (1. + x(j));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ty(k) = x(k) + (2. + 5. * x(k)*x(k)) + 1. - tmp;\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Hammarling2x2 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(4);\n\n\t\ty(0) = (x(0) * x(0) + x(1) * x(2)) - 0.0001;\n\t\ty(1) = (x(0) * x(1) + x(1) * x(3)) - 1.;\n\t\ty(2) = (x(2) * x(0) + x(3) * x(2)) - 0.;\n\t\ty(3) = (x(2) * x(1) + x(3) * x(3)) - 0.0001;\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(4);\n\t\tfor (i=0; i<4; i++) {\n\t\t\tx(i).assign(-100., 100.);\n\t\t}\n\t}\n};\n\nstruct Hammarling3x3 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> y(9);\n\n\t\ty(0) = (x(0) * x(0) + x(1) * x(3) + x(2) * x(6)) - 0.0001;\n\t\ty(1) = (x(0) * x(1) + x(1) * x(4) + x(2) * x(7)) - 1.;\n\t\ty(2) = (x(0) * x(2) + x(1) * x(5) + x(2) * x(8));\n\n\t\ty(3) = (x(3) * x(0) + x(4) * x(3) + x(5) * x(6));\n\t\ty(4) = (x(3) * x(1) + x(4) * x(4) + x(5) * x(7)) - 0.0001;\n\t\ty(5) = (x(3) * x(2) + x(4) * x(5) + x(5) * x(8));\n\n\t\ty(6) = (x(6) * x(0) + x(7) * x(3) + x(8) * x(6));\n\t\ty(7) = (x(6) * x(1) + x(7) * x(4) + x(8) * x(7));\n\t\ty(8) = (x(6) * x(2) + x(7) * x(5) + x(8) * x(8)) - 0.0001;\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(9);\n\t\tfor (i=0; i<9; i++) {\n\t\t\tx(i).assign(-100., 100.);\n\t\t}\n\t}\n};\n\nstruct P17 {\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(1) - 3.;\n\t\ty(1) = x(0) * x(0) + x(1) * 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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct P19 {\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(0) + x(1) * x(1));\n\t\ty(1) = x(1) * (x(0) * x(0) + x(1) * 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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct P20 {\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) - 5.) * (x(0) - 5.);\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).assign(-10., 10.);\n\t\t}\n\t}\n};\n\nstruct Chandrasekhar {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\tint s = x.size();\n\t\tub::vector<T> y(s);\n\n\t\tub::vector<T> mu(s);\n\t\tT sum, term;\n\t\tint i, j;\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\ty(i) = x(i);\n\t\t}\n\t\tfor (i=0; i<s; i++) {\n\t\t\tmu(i) = (2.*(i+1.)-1.) / (2. * s);\n\t\t}\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\tsum = 0.;\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\tsum += mu(i) * x(j) / (mu(i) + mu(j));\n\t\t\t}\n\t\t\tterm = 1. - 0.9 * sum / (2. * s);\n\t\t\ty(i) -= 1. / term;\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).assign(-3., 3.);\n\t\t}\n\t}\n};\n\n#endif // BURKARDT_NON_HPP\n", "meta": {"hexsha": "c10bd69484434b50234e9fff66fbfe698f7b903f", "size": 9732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/burkardt-non.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "example/burkardt-non.hpp", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "example/burkardt-non.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": 17.6304347826, "max_line_length": 74, "alphanum_fraction": 0.443999178, "num_tokens": 4422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5941479298689056}}
{"text": "#include \"soar.hpp\"\n\n#include <Eigen/Dense>\n#include <fmt/format.h>\n#include <vector>\n\nusing namespace Eigen;\n\nSoar::Soar(const Ref<const MatrixXd> &matA, const Ref<const MatrixXd> &matB)\n    : ndim_(matA.rows()), matA_(matA), matB_(matB),\n      u_(VectorXd::Random(ndim_)) {}\n\nMatrixXd Soar::compute(int n) {\n  VectorXd q = u_ / u_.norm();\n  VectorXd f = VectorXd::Zero(ndim_);\n\n  // initialize\n  MatrixXcd matQ = MatrixXcd::Zero(ndim_, n);\n  MatrixXcd matP = MatrixXcd::Zero(ndim_, n);\n  MatrixXcd matT = MatrixXcd::Zero(n, n);\n  std::vector<int> deflation;\n\n  matQ.col(0) = q;\n\n  for (int i = 0; i < n - 1; ++i) {\n    // Recurrence role\n    VectorXcd r = matA_ * matQ.col(i) + matB_ * matP.col(i);\n    std::complex<double> norm_init = r.norm();\n    MatrixXcd basis = matQ.leftCols(i + 1);\n\n    // Modified Gram Schmidt procedure\n    // First orthogonalization\n    VectorXcd coef = VectorXd::Zero(i + 1);\n    for (int j = 0; j < i + 1; ++j) {\n      // Projection coeficients and projection subtraction\n      VectorXcd v = basis.col(j);\n      coef(j) = v.dot(r);\n      r -= coef(j) * v;\n    }\n    // Saving coeficients\n    matT.col(i).head(i + 1) = coef;\n\n    // Reorthogonalization, if needed.\n    if (r.norm() < 0.7 * norm_init) {\n      // Second Gram Schmidt orthogonalization\n      for (int j = 0; j < i + 1; ++j) {\n        VectorXd v = basis.col(j);\n        coef(j) = v.dot(r);\n        r -= coef(j) * v;\n      }\n      matT.col(i).head(i + 1) += coef;\n    }\n\n    double r_norm = r.norm();\n    matT(i + 1, i) = r_norm;\n\n    // check for breakdown\n    if (r_norm > tol_) {\n      matQ.col(i + 1) = r / r_norm;\n      VectorXd e_i = VectorXd::Zero(i + 1);\n      e_i(i) = 1.0;\n      // VectorXd v_aux = matT.block(1, 0, i + 1, i + 1).ldlt().solve(e_i);\n      VectorXd v_aux =\n          matT.block(1, 0, i + 1, i + 1).colPivHouseholderQr().solve(e_i);\n      f = matQ.leftCols(i + 1) * v_aux;\n    } else {\n      // Deflation reset\n      matT(i + 1, i) = 1.0;\n      matQ.col(i + 1) = VectorXd::Zero(ndim_);\n      VectorXd e_i = VectorXd::Zero(i + 1);\n      e_i(i) = 1.0;\n      // VectorXd v_aux = matT.block(1, 0, i + 1, i + 1).ldlt().solve(e_i);\n      VectorXd v_aux =\n          matT.block(1, 0, i + 1, i + 1).colPivHouseholderQr().solve(e_i);\n      f = matQ.leftCols(i + 1) * v_aux;\n\n      // Deflation verification\n      VectorXd f_proj;\n      for (int k : deflation) {\n        VectorXd p = matP.col(k);\n        double coef_f = p.dot(f) / p.dot(p);\n        f_proj = f - coef_f * p;\n      }\n\n      if (f_proj.norm() > tol_) {\n        deflation.push_back(i);\n      } else {\n        fmt::print(\"SOAR lucky breakdown.\\n\");\n        break;\n      }\n    }\n    matP.col(i + 1) = f;\n  }\n\n  fmt::print(\"zero1: {:9.3f}\\n\",\n             (matQ.transpose() * matQ - MatrixXd::Identity(n, n)).norm());\n\n  VectorXd e_n = VectorXd::Zero(n - 1);\n  e_n(n - 2) = 1.0;\n  VectorXd r = matA_ * matQ.col(n - 2) + matB_ * matP.col(n - 2);\n  for (int i = 0; i < n - 1; ++i) {\n    double coef = matQ.col(i).dot(r);\n    r -= coef * matQ.col(i);\n  }\n  double nm = (matA_ * matQ.leftCols(n - 1) + matB_ * matP.leftCols(n - 1) -\n               matQ.leftCols(n - 1) * matT.topLeftCorner(n - 1, n - 1) -\n               r * e_n.transpose())\n                  .norm();\n  fmt::print(\"zero2: {:9.3f}\\n\", nm);\n  return matQ;\n}", "meta": {"hexsha": "d418f4ee71b27ba91ff4031efdb4f621e6ac9cb4", "size": 3286, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/soar.cc", "max_stars_repo_name": "pan3rock/QuadEigsSOAR", "max_stars_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/soar.cc", "max_issues_repo_name": "pan3rock/QuadEigsSOAR", "max_issues_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/soar.cc", "max_forks_repo_name": "pan3rock/QuadEigsSOAR", "max_forks_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6036036036, "max_line_length": 76, "alphanum_fraction": 0.5359099209, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5940962573813172}}
{"text": "//test_ptf_var.cpp\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include<memory>\n\n#include <Eigen/Dense>\n\n#include \"compute_returns_eigen.h\"\n#include \"portfolio.h\"\n#include \"instrument.h\"\n#include \"ptf_var.h\"\n#include \"var_model.h\"\n#include \"compute_var.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid readCSV(std::istream &input, std::vector< std::vector<std::string> > &output)\n//https://www.gamedev.net/topic/444193-c-how-to-load-in-a-csv-file/\n{\n\tstd::string csvLine;\n\t// read every line from the stream\n\twhile( std::getline(input, csvLine) )\n\t{\n\t\tstd::istringstream csvStream(csvLine);\n\t\tstd::vector<std::string> csvColumn;\n\t\tstd::string csvElement;\n\t\t// read every element from the line that is seperated by commas\n\t\t// and put it into the vector or strings\n\t\twhile( std::getline(csvStream, csvElement, ',') )\n\t\t{\n\t\t\tcsvColumn.push_back(csvElement);\n\t\t}\n\t\toutput.push_back(csvColumn);\n\t}\n}\n\n\nint main()\n{\n\n    try{\n\n    // Read mid FX fix for currency pairs majors and exotics\n    // daily series obtained for Bank of England through\n\t//https://www.quandl.com\n\n\tstd::fstream file(\"/home/mrnoname/Documents/VaR/data/StockIndexData.csv\", ios::in);\n\tif(!file.is_open())\n\t{\n\t\tstd::cout << \"File not found!\\n\";\n\t\treturn 1;\n\t}\n\t// typedef to save typing for the following object\n\ttypedef std::vector< std::vector<std::string> > csvVector;\n\tcsvVector csvData;\n\n\treadCSV(file, csvData);\n\n    //test\n    for(size_t i = 0;i < 5; ++i){\n        for(size_t j = 0;j < csvData[i].size();++j){\n            cout << csvData[i][j] << '\\t';\n\n        }\n\n        cout << endl;\n    }\n    cout << endl;\n\n    // Remove lines with missing values\n\n    size_t n(csvData.size() - 1);\n    size_t m(csvData[0].size() - 1);\n\n    Mat _prices;\n    _prices.resize(m,Vec(n-1062));\n\n    for(size_t i = 1062;i < n;++i){\n        for(size_t j = 1;j < csvData[i].size();++j){\n            std::string tmp = csvData[i][j];\n            if(tmp.empty()){\n                _prices[j-1][i-1062] = 99999.;\n            }\n            else{\n                _prices[j-1][i-1062] = std::stod(tmp);\n            }\n        }\n    }\n\n    std::vector<std::string> indexNames(csvData[0].size() - 1);\n\n    for(size_t i = 1;i < csvData[0].size();++i){\n        indexNames[i-1] = csvData[0][i];\n    }\n\n\t//Remove missing values to compute trailling returns\n    //Asynchornous time series. Shift to the next value\n    Mat prices;\n    prices.resize(m,Vec(0));\n\n\tfor(size_t i = 0;i < _prices.size();++i){\n        for(size_t j = 0;j < _prices[i].size();++j){\n            if(!((_prices[i][j] == 99999) || (_prices[i][j] == 0)))\n                prices[i].push_back(_prices[i][j]);\n        }\n\t}\n\n    std::shared_ptr<ComputeReturn> cr(new ComputeReturn(prices,1,252,true));\n\t// 252 / 4 = 63 - 3 months\n    // 4 * 252 = 1008 use 4 years of data to compute mean, and std dev\n\n    Mat _rtns = cr->getReturns();\n\n    // ------------------------------------------------\n\n    // Case of full replication of index - DJIA,GSPC,NDX,GDAXI,FCHI,SSEC,SENSEX : 7 indices\n\n\tdouble a = double(1./7.); //cout << a << endl;\n\n\tstd::vector<double> weights{a,a,a,a,a,a,a}; //initialization. Equi-weighted asset for mere convenience\n\n\tPtf _ptf;\n\n\tfor(unsigned int i = 0;i < 7;++i){\n        shared_ptr<Instrument> instrument(new DeltaOne());\n        auto p = std::make_pair(i,instrument);\n\t\t_ptf.push_back(p);\n\t}\n\n\tshared_ptr<Portfolio> ptf(new Portfolio(_ptf, weights, cr, false, 1.e+07));\n\n\tcout << \"ptf's avg rtn: \" << ptf->getMeanPtfRn() << endl;\n\tcout << \"ptf's vol: \" << ptf->getPtfSdev() << endl<< endl;\n\n\tdouble alpha = .05;\n\n\tVaRPtfCompute model(ptf, alpha);\n\n    // Compute ptf VaR of index\n\n\tcout << endl << \"Portfolio VaR - equi index \" << alpha << \" : \" << model.getPtfVaR() << endl;\n\n\t//-----------------------------------------------------------------\n\tcout << endl <<  \"Compute daily VaR using different methods - alpha .05\" << endl;\n\n\t// 1. Riskmetrics\n\n\tRiskMetricsVaR var1; //(.05,.94,false);\n\n\tVaRParamCompute<Portfolio, RiskMetricsVaR> VaRRiskMetrics(ptf, var1);\n\n\tcout << \"Riskmetrics VaR: \" << VaRRiskMetrics.computeVaR() << endl;\n\n\t// 2. GARCH\n\n\tGarchVaR var2; //(.05, 0., .25, .75, false);\n\n    VaRParamCompute<Portfolio, GarchVaR> VaRGarch(ptf, var2);\n    \n\tcout << \"GARCH VaR: \" << VaRGarch.computeVaR() << endl;\n\n\t// ------------------------------------------------------------\n\n\t// 3. Historical method\n\n\tHistoricalVaR var3;\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical(ptf, var3);\n\n\tcout << \"Historical VaR: \" << VaRHistorical.computeVaR() << endl;\n\n\t// 4. Historical method - weighting scheme\n\n\tHistoricalVaR var4(.05, .98, hybrid);\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical1(ptf, var4);\n\n\tcout << \"Historical VaR w/ weighting scheme: \" << VaRHistorical1.computeVaR() << endl;\n\n\t// 5. Historical method - HW method\n\n\tHistoricalVaR var5(.05, .94, hw);\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical2(ptf, var5);\n\n\tcout << \"Historical VaR w/ HW weighting scheme: \" << VaRHistorical2.computeVaR() << endl;\n\n\t//-----------------------------------------------------------------\n\n\t// Compute conponent VaR\n\n\tVec compVaR = model.computeComponentVaR();\n\n\tcout << endl << \"component VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 7;++i)\n\t\tcout << indexNames[i] << \": \" << compVaR[i] << endl;\n\n    double sumCompVaR(0.);\n    for(auto& i : compVaR) sumCompVaR += i;\n    cout << \"sum component VaR: \" << sumCompVaR << endl;\n\n\t// Compute marginal VaR\n\n\tVec marVaR = model.computeMarginalVaR();\n\n\tcout << endl << \"marginal VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 7;++i)\n\t\tcout << indexNames[i] << \": \" << marVaR[i] << endl;\n\n\t// Compute incremental VaR\n\n\tdouble amount = 1.e+06;\n\n\tcout << endl << \"incremental VaR - add \" << amount << \" : \" << model.computeIncrementalVaR(amount) << endl;\n\n\t//------------------------------------------------------------------------------------------------\n\n    weights = {.1,.15,.2,.1,.1,.2,.15};\n\n\tshared_ptr<Portfolio> ptf1(new Portfolio(_ptf, weights, cr, false, 1.e+07));\n\n\tcout << \"ptf's avg rtn: \" << ptf1->getMeanPtfRn() << endl;\n\tcout << \"ptf's vol: \" << ptf1->getPtfSdev() << endl<< endl;\n\n\tVaRPtfCompute model1(ptf1, alpha);\n\n    // Compute ptf VaR of index\n\n\tcout << endl << \"Portfolio VaR - active index \" << alpha << \" : \" << model1.getPtfVaR() << endl;\n\n\t//-----------------------------------------------------------------\n\tcout << endl <<  \"Compute daily VaR using different methods - alpha .05\" << endl;\n\n\t// 1. Riskmetrics\n\n\tVaRParamCompute<Portfolio, RiskMetricsVaR> VaRRiskMetrics1(ptf1, var1);\n\n\tcout << \"Riskmetrics VaR: \" << VaRRiskMetrics1.computeVaR() << endl;\n\n\t// 2. GARCH\n\n    VaRParamCompute<Portfolio, GarchVaR> VaRGarch1(ptf1, var2);\n\n\tcout << \"GARCH VaR: \" << VaRGarch1.computeVaR() << endl;\n\n\t// ------------------------------------------------------------\n\n\t// 3. Historical method\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical11(ptf1, var3);\n\n\tcout << \"Historical VaR: \" << VaRHistorical11.computeVaR() << endl;\n\n\t// 4. Historical method - weighting scheme\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical12(ptf1, var4);\n\n\tcout << \"Historical VaR w/ weighting scheme: \" << VaRHistorical12.computeVaR() << endl;\n\n\t// 5. Historical method - HW method\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical13(ptf1, var5);\n\n\tcout << \"Historical VaR w/ HW weighting scheme: \" << VaRHistorical13.computeVaR() << endl;\n\n\t//-----------------------------------------------------------------\n\n\t// Compute conponent VaR\n\n\tcompVaR = model1.computeComponentVaR();\n\n\tcout << endl << \"component VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 7;++i)\n\t\tcout << indexNames[i] << \": \" << compVaR[i] << endl;\n\n    sumCompVaR = 0.;\n    for(auto& i : compVaR) sumCompVaR += i;\n    cout << \"sum component VaR: \" << sumCompVaR << endl;\n\n\t// Compute marginal VaR\n\n\tmarVaR = model1.computeMarginalVaR();\n\n\tcout << endl << \"marginal VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 7;++i)\n\t\tcout << indexNames[i] << \": \" << marVaR[i] << endl;\n\n\t// Compute incremental VaR\n\n\tcout << endl << \"incremental VaR - add \" << amount << \" : \" << model1.computeIncrementalVaR(amount) << endl;\n\n\t//-----------------------------------------------------------------\n\n\t// Buy 1 call and 1 put on S&P 500. Sell .5 unit of index\n\n\t// Case of derivatives, full replication of index\n\n\tVec weights1 =  {1.,1.,-.5};\n\n\tPtf _ptf1;\n\n\tshared_ptr<Instrument> instrument(new Derivatives(0.46118, 0.01013));\n    _ptf1.push_back(std::make_pair(1,instrument));\n    shared_ptr<Instrument> instrument1(new Derivatives(-0.52983, 0.00658));\n    _ptf1.push_back(std::make_pair(1,instrument1));\n    shared_ptr<Instrument> instrument2(new DeltaOne());\n\t_ptf1.push_back(std::make_pair(1,instrument2));\n\n\t/*\n    Call @SPX 161216C02200000 Delta0.46118 Gamma0.01013 Rho0.38430 Theta-0.79242 Vega1.69184 Impvol0.11648\n\n    Put @SPX 161216P02200000 Delta-0.52983 Gamma0.00658 Rho-0.34403 Theta-0.93300 Vega1.67799 Impvol0.11835\n\n\t*/\n\n\tshared_ptr<Portfolio> ptf2(new Portfolio(_ptf1, weights1, cr, false, 1.e+07));\n\n    VaRPtfCompute model2(ptf2, alpha);\n\n    // Compute ptf VaR of index\n\n\tcout << endl << \"Portfolio VaR - equity derivatives \" << alpha << \" : \" << model2.getPtfVaR() << endl;\n\n\t//-----------------------------------------------------------------\n\tcout << endl <<  \"Compute daily VaR using different methods - alpha .05\" << endl;\n\n\t// 1. Riskmetrics\n\n\tVaRParamCompute<Portfolio, RiskMetricsVaR> VaRRiskMetrics21(ptf2, var1);\n\n\tcout << \"Riskmetrics VaR: \" << VaRRiskMetrics21.computeVaR() << endl;\n\n\t// 2. GARCH\n\n    VaRParamCompute<Portfolio, GarchVaR> VaRGarch22(ptf1, var2);\n\n\tcout << \"GARCH VaR: \" << VaRGarch22.computeVaR() << endl;\n\n\t// ------------------------------------------------------------\n\n\t// 3. Historical method\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical21(ptf1, var3);\n\n\tcout << \"Historical VaR: \" << VaRHistorical21.computeVaR() << endl;\n\n\t// 4. Historical method - weighting scheme\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical22(ptf1, var4);\n\n\tcout << \"Historical VaR w/ weighting scheme: \" << VaRHistorical22.computeVaR() << endl;\n\n\t// 5. Historical method - HW method\n\n\tVaRnoneParamCompute<Portfolio, HistoricalVaR> VaRHistorical23(ptf1, var5);\n\n\tcout << \"Historical VaR w/ HW weighting scheme: \" << VaRHistorical23.computeVaR() << endl;\n\n\t// Compute conponent VaR\n\n\tVec compVaR2 = model2.computeComponentVaR();\n\n\tcout << endl << \"component VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 3;++i)\n\t\tcout << i << \": \" << compVaR2[i] << endl;\n\n    sumCompVaR = 0.;\n    for(auto& i : compVaR2) sumCompVaR += i;\n    cout << \"sum component VaR: \" << sumCompVaR << endl;\n\n\t// Compute marginal VaR\n\n\tVec marVaR2 = model2.computeMarginalVaR();\n\n\tcout << endl << \"marginal VaR: \" << endl;\n\n\tfor(size_t i = 0;i < 3;++i)\n\t\tcout << i << \": \" << marVaR2[i] << endl;\n\n\t// Compute incremental VaR\n\n\tcout << endl << \"incremental VaR - add \" << amount << \" : \" << model2.computeIncrementalVaR(amount) << endl;\n\n    // ------------------------------------------------------------\n\n    return 0;\n\n    } catch (const std::exception& e) { // caught by reference to base\n        std::cout << \" a standard exception was caught, with message '\"\n                  << e.what() << \"'\\n\";\n    }\n\n\n}\n\n\n", "meta": {"hexsha": "4a6d4846472a699936169c9103cdb8e6cbe34397", "size": 11278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cpptests/test_ptf_var.cpp", "max_stars_repo_name": "vigor-ish/riskjs", "max_stars_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "test/cpptests/test_ptf_var.cpp", "max_issues_repo_name": "vigor-ish/riskjs", "max_issues_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:33:13.000Z", "max_forks_repo_path": "test/cpptests/test_ptf_var.cpp", "max_forks_repo_name": "vigor-ish/riskjs", "max_forks_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 27.7100737101, "max_line_length": 109, "alphanum_fraction": 0.5937222912, "num_tokens": 3329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5940704545091822}}
{"text": "#include \"RBGL.hpp\"\n\n#include <stdlib.h>\n\n#include <boost/graph/simple_point.hpp>\n\nextern \"C\"\n{\n\n#include <Rdefines.h>\n#include <R_ext/Random.h>\n#include <Rmath.h>\n\n    using namespace std;\n    using namespace boost;\n\n    static void delta_and_tau\n     (const Graph_ud& g, vector<int>& v_delta, vector<int>& v_tau)\n    {\n        Graph_ud::vertex_iterator vi, v_end;\n        Graph_ud::adjacency_iterator ui, u_end, wi, w_end;\n\n        int dv = 0, tv = 0;\n\n        v_delta.clear();\n        v_tau.clear();\n\n        for ( tie(vi, v_end) = vertices(g); vi != v_end; ++vi )\n        {\n            // delta(v)\n            dv = 0;\n            for ( tie(ui, u_end) = adjacent_vertices(*vi, g);\n                    ui != u_end; ++ui )\n            {\n                wi = ui;\n                for ( ++wi; wi != u_end; ++wi )\n                    if ( edge(*ui, *wi, g).second ) dv++;\n            }\n            v_delta.push_back(dv);\n\n            // tau(v)\n            dv = degree(*vi, g);\n            tv = dv * ( dv - 1 ) / 2;\n            v_tau.push_back(tv);\n        }\n    }\n\n    SEXP clusteringCoef(\n        SEXP num_verts_in, SEXP num_edges_in, SEXP R_edges_in,\n        SEXP weighted, SEXP R_v_weights_in)\n    {\n        int i;\n\n        int NV = INTEGER(num_verts_in)[0];\n        vector<double> v_weight(NV, 1);\n\n        if ( INTEGER(weighted)[0] )\n        {\n            double* weights = REAL(R_v_weights_in);\n            for ( i = 0; i < NV; i++ ) v_weight[i] = weights[i];\n        }\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in);\n        vector<int> v_delta, v_tau;\n        delta_and_tau(g, v_delta, v_tau);\n\n        double nn = 0;\t\t// count nodes w/ deg(v) >= 2\n        double cG = 0;\n\tGraph_ud::vertex_descriptor v;\n        for ( i = 0; i < NV; i++ )\n        {\n\t    v = vertex(i, g);\n            if ( out_degree(v, g) >= 2 && v_tau[i] > 0 )\n            {\n                cG += v_weight[i] * v_delta[i] / v_tau[i];\n                nn += v_weight[i];\n            }\n        }\n\n        if ( nn ) cG /= nn;\n\n        SEXP ccoef;\n        PROTECT(ccoef = NEW_NUMERIC(1));\n        REAL(ccoef)[0] = cG;\n        UNPROTECT(1);\n        return(ccoef);\n    }\n\n    SEXP transitivity( SEXP num_verts_in, SEXP num_edges_in, SEXP R_edges_in)\n    {\n        int NV = INTEGER(num_verts_in)[0];\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in);\n        vector<int> v_delta, v_tau;\n        delta_and_tau(g, v_delta, v_tau);\n\n\tdouble tG = 0;\n        double sum_dv = 0, sum_tv = 0;\n        for ( int i = 0; i < NV; i++ )\n        {\n            sum_dv += v_delta[i];\n            sum_tv += v_tau[i];\n        }\n        if ( sum_tv ) tG = sum_dv / sum_tv;\n\n#if DEBUG\n        cout << \" sum_dv = \" << sum_dv\n        << \" sum_tv = \" << sum_tv\n        << \" v_delta.size() = \" << v_delta.size()\n        << \" v_tau.size() = \" << v_tau.size()\n\t<< \" tG = \" << tG\n        << endl;\n#endif\n\n        SEXP tcoef;\n        PROTECT(tcoef = NEW_NUMERIC(1));\n        REAL(tcoef)[0] = tG;\n        UNPROTECT(1);\n        return(tcoef);\n    }\n\n    // uniformly sample in [1, n]\n    static inline int uniformRandomNumber(const int n)\n    {\n\tint j = (int)(n * unif_rand()) + 1;   // unif_rand in [0, 1)\n\treturn j;\n    }\n\n    static inline int findIndex(const int r, const vector<int>& W)\n    {\n\tunsigned int i;\n\tfor ( i = 1; i < W.size(); i++ ) if ( r <= W[i] ) break;\n\treturn i;\n    }\n\n    // input: a node in graph g\n    // output: one neighbor of node n chosen uniformly randomly\n    static inline void uniformRandomAdjacentNode\n\t(const Graph_ud::vertex_descriptor& v, const Graph_ud& g, \n\t Graph_ud::vertex_descriptor& u,\n\t Graph_ud::vertex_descriptor& w)\n    {\n\tint nc = out_degree(v, g);\n\n\tGraph_ud::adjacency_iterator vi, v_end;\n\ttie(vi, v_end) = adjacent_vertices(v, g);\n\n\tswitch (nc)\n\t{\n\tcase 0: \n\tcase 1: u = w = *vi;\n\t\tbreak;\n\tcase 2: \n\t\tu = *vi; vi++;\n\t\tw = *vi; \n\t\tbreak;\n\tdefault:\n\t\t{\n\t\tint r1 = uniformRandomNumber(nc);\n\t\tint r2 = uniformRandomNumber(nc);\n\n\t\twhile ( r1 == r2 ) r2 = uniformRandomNumber(nc);\n\n\t\tfor ( int i = 0; vi != v_end; vi++, i++ )\n\t\t{\n\t\t    if ( i == r1 ) u = *vi;\n\t\t    if ( i == r2 ) w = *vi;\n\t\t}\n\n\t\tbreak;\n\t\t}\n\t}\n#if DEBUG\n\tcout << \" uniformRandomAdjacentNode: \" << endl;\n\tcout << \" n = \" << n << endl;\n\tcout << \" nc = \" << nc << endl;\n\tcout << \" *vi = \" << *vi << endl;\n\tcout << \" u = \" << u << endl;\n\tcout << \" w = \" << w << endl;\n#endif\n    }\n\n    static inline void uniformRandomAdjacentNode_i\n\t(const int n, const Graph_ud& g, \n\t Graph_ud::vertex_descriptor& u,\n\t Graph_ud::vertex_descriptor& w)\n    {\n\tGraph_ud::vertex_descriptor v = vertex(n, g);\n\tuniformRandomAdjacentNode(v, g, u, w);\n    }\n\n    // Approximating Cw  \n    //    Outline of the algorithm:\n    //    Input: integer k; \n    //           array A[1..|V'|] of nodes V' = {v in V: d(v) >= 2}\n    //           node weights w: V' -> N>0;\n    //           adjacentcy array for each node\n    //    Output: approximation of Cw\n    //    Data: node variables: u, w;\n    //           integer variables: r, l, j, W[0..|V'|]\n    //    Algorithm:\n    //    W[0] = 0\n    //    for i = (1, ..., |V'|) do\n    //       W[i] = W[i-1] + w(A[i])\n    //    l = 0\n    //    for i in (1, ..., k) do\n    //    {\n    //       r = UniformRandomNumber( {1,...,W[|V'|]} )\n    //       j = FindIndex( j: W[j-1] < r <= W[j] )\n    //       u = UniformRandomAdjacentNode(A[j])\n    //       repeat\n    //         w = UniformRandomAdjacentNode(A[j])\n    //       until u != w\n    //       if ( EdgeExists(u, w) then\n    //          l = l + 1\n    //    }\n    //    return l/k\n\n    SEXP clusteringCoefAppr(SEXP k_in,\n        SEXP num_verts_in, SEXP num_edges_in, SEXP R_edges_in,\n        SEXP weighted, SEXP R_v_weights_in)\n    {\n\t// prepare for later unif_rand call\n\tGetRNGstate();\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in);\n\n        int i, l, r, j;\n\n        int k = INTEGER(k_in)[0];\n        int NV = INTEGER(num_verts_in)[0];\n        vector<int> v_weight(NV, 1);\n        vector<int> W(NV+1, 0);\n\n#if DEBUG\n\tcout << \" inside clusteringCoefAppr \" \n\t\t<< \" k = \" << k\n\t\t<< \" NV = \" << NV \n\t\t<< endl;\n#endif\n\n        if ( INTEGER(weighted)[0] )\n        {\n            double* weights = REAL(R_v_weights_in);\n            for ( i = 0; i < NV; i++ ) v_weight[i] = (int) weights[i];\n        }\n\n        Graph_ud::vertex_descriptor u=Graph_ud::null_vertex(), w=Graph_ud::null_vertex();\n\n\tW[0] = 0;\n\tfor ( i = 1; i < NV+1; i++ ) W[i] = W[i-1] + v_weight[i-1];\n\n\t// TODO: limit nodes to those w/ degree >= 2\n\t//       pick a number within range uniformaly \n\t//\t pick an adjacent node uniformaly randomly\n\tfor ( l = 0, i = 0; i < k; i++ )\n\t{\n\t   r = uniformRandomNumber(W[NV]);\n\t   j = findIndex(r, W);\n\t   uniformRandomAdjacentNode_i(j-1, g, u, w);\n\n\t   if ( edge(u, w, g).second ) l++;\n\n#if DEBUG\n\t   cout << \" i = \" << i;\n\t   cout << \" r = \" << r;\n\t   cout << \" j = \" << j;\n\t   cout << \" l = \" << l << endl;\n#endif\n\t}\n\n\tdouble cG = double(l) / double(k);\n\n        SEXP ccoef;\n        PROTECT(ccoef = NEW_NUMERIC(1));\n        REAL(ccoef)[0] = cG;\n        UNPROTECT(1);\n        return(ccoef);\n\n    }\n\n    inline bool prob_cmp(const simple_point<int>& p1, \n\t\t\t const simple_point<int>& p2)\n\t{ return p1.y > p2.y; }\n\n    //  To find a random node w/ probability d(u) / sum(d(V))\n    //  The following closely mirrors the codes on\n    //  Unequal probability sampling; without-replacement case\n    //\n    //    /* Record element identities */\n    //    for (i = 0; i < n; i++)\n    //        perm[i] = i + 1;\n    //\n    //    //* Sort probabilities into descending order */\n    //    //* Order element identities in parallel */\n    //    revsort(p, perm, n);\n    //\n    //    //* Compute the sample */\n    //    totalmass = 1;\n    //    for (i = 0, n1 = n-1; i < nans; i++, n1--) {\n    //        rT = totalmass * unif_rand();\n    //        mass = 0;\n    //        for (j = 0; j < n1; j++) {\n    //            mass += p[j];\n    //            if (rT <= mass)\n    //                break;\n    //        }\n    //        ans[i] = perm[j];\n    //        totalmass -= p[j];\n    //        for(k = j; k < n1; k++) {\n    //            p[k] = p[k + 1];\n    //            perm[k] = perm[k + 1];\n    //        }\n    //    }\n    static void ProbRandomNode\n\t(const Graph_ud::vertex_descriptor& v, const Graph_ud& g,\n\t Graph_ud::vertex_descriptor& u)\n    {\n\n\ttypedef graph_traits<Graph_ud>::vertex_iterator vertex_iterator;\n\n\tvertex_iterator vi, v_end;\n\n\tint NV = num_vertices(g);\n\tstd::vector < simple_point<int> > pp(num_vertices(g));\n\n\tint i = 0, totalmass = 0;\n\tfor ( tie(vi, v_end) = vertices(g); vi != v_end; vi++, i++ )\n\t{\n\t   pp[i].x = i+1;\n\t   pp[i].y = out_degree(*vi, g);\n\t   totalmass += pp[i].y;\n\t}\n\n\tstd::stable_sort(pp.begin(), pp.end(), prob_cmp);\n\n\tint j, k, n1, rT, mass;\n\tfor ( i = 0, n1 = NV-1; i < NV; i++, n1-- )\n\t{\n            rT = (int)(totalmass * unif_rand());\n            mass = 0;\n            for (j = 0; j < n1; j++) {\n                mass += pp[j].y;\n                if (rT <= mass) break;\n            }\n\t    u = vertex(i, g);\n\t    if ( !edge(v, u, g).second ) break;\n\n\t    totalmass -= pp[j].y;\n\t    for ( k = j; k < n1; k++ ) pp[k] = pp[k+1];\n\t}\n    }\n\n    // Graph Generator:\n    //    Outline of algorithm:\n    //    Input: initial graph G: two connected nodes\n    //           integer: n >= 3, d >= 2, o\n    //    Output: graph G\n    //    Algorithm:\n    //    for ( i = (3, ..., n) do\n    //    {\n    //       v = NewNode()\n    //       for 1, ..., Min(i-1, d) do\n    //       {\n    //          repeat \n    //            u = RandomNode( with prob du / sum(d(v) )\n    //          until node EdgeExists(v, u)\n    //          AddEdge(v, u)\n    //       }\n    //       for 1, ..., o do\n    //       {\n    //          u = RandomAdjacentNode(v)\n    //          repeat\n    //             w = RandomAdjacentNode(v)\n    //          until w != u\n    //          if ( node EdgeExists(u, w) then\n    //             AddEdge(u, w)\n    //       }\n    //    }\n\n    SEXP graphGenerator(SEXP n_in, SEXP d_in, SEXP o_in)\n    {\n\tint i, j;\n        int n = INTEGER(n_in)[0];\n        int d = INTEGER(d_in)[0];\n        int o = INTEGER(o_in)[0];\n\n\tGetRNGstate();\t// get random number generator ready\n\n\t// initial graph with 2 connected nodes\n\tGraph_ud g(2);\n\tboost::add_edge(0, 1, g);\n\n        Graph_ud::vertex_descriptor v, u, w=Graph_ud::null_vertex();\n\t\n\tfor ( i = 3; i <= n; i++ )\n\t{\n\t   // generate a new node \n\t   v = boost::add_vertex(g);\n\n\t   for ( j = 1; j <= min(i-1, d); j++ )\n\t   {\n\t\tProbRandomNode(v, g, u); \n\t\tboost::add_edge(v, u, g);\n\t   }\n\n\t   for ( j = 1; j <= o; j++ )\n\t   {\n\t        uniformRandomAdjacentNode(v, g, u, w);\n\n\t\tif ( !edge(u, w, g).second )\n\t\t   boost::add_edge(u, w, g);\n\t   }\n\t}\n\n#if DEBUG\n\ttypedef graph_traits<Graph_ud>::vertex_iterator vertex_iterator;\n\tvertex_iterator vi, v_end;\n\tcout << \" no. of vertices: \" << num_vertices(g)\n\t     << \" no. of edges:    \" << num_edges(g)\n\t     << endl;\n\n\tfor ( tie(vi, v_end) = vertices(g); vi != v_end; vi++, i++ )\n\t{\n\t   cout << \" vertex: \" << *vi \n\t\t<< \" has degree: \" << out_degree(*vi, g)\n\t\t<< endl;\n\t}\n#endif\n\n        int NE = num_edges(g);\n        SEXP anslst, ncnt, ecnt, enlst;\n        PROTECT(anslst = allocVector(VECSXP, 3));\n        PROTECT(ncnt = NEW_INTEGER(1));\n        PROTECT(ecnt = NEW_INTEGER(1));\n        PROTECT(enlst = allocMatrix(INTSXP, 2, NE));\n\n        INTEGER(ncnt)[0] = num_vertices(g);\n        INTEGER(ecnt)[0] = NE;\n\n\ttypedef graph_traits<Graph_ud>::edge_iterator edge_iterator;\n\tedge_iterator ei, e_end;\n\tfor ( i = 0, tie(ei, e_end) = edges(g); ei != e_end ; ei++ )\n        {\n            INTEGER(enlst)[i++] = source(*ei, g);\n            INTEGER(enlst)[i++] = target(*ei, g);\n        }\n\n\n\tSET_VECTOR_ELT(anslst,0,ncnt);\n\tSET_VECTOR_ELT(anslst,1,ecnt);\n        SET_VECTOR_ELT(anslst,2,enlst);\n        UNPROTECT(4);\n        return(anslst);\n    }\n\n}\n\n", "meta": {"hexsha": "d4d9f46b44737c37502651b8f703359d4d6802c4", "size": 11790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clusteringCoef.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/clusteringCoef.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/clusteringCoef.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": 25.6862745098, "max_line_length": 89, "alphanum_fraction": 0.4912637829, "num_tokens": 3636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885785675307}}
{"text": "#pragma once\n#include \"Optimizer.hpp\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <nlohmann/json.hpp>\n\nnamespace yavque\n{\nclass Adam : public Optimizer\n{\nprivate:\n\tconst double alpha_;\n\tconst double beta1_;\n\tconst double beta2_;\n\tconst double eps_;\n\n\tint t_ = 0;\n\tEigen::VectorXd m_;\n\tEigen::VectorXd v_;\n\npublic:\n\tstatic constexpr std::array<double, 4> DEFAULT_PARAMS = {1e-3, 0.9, 0.999, 1e-8};\n\n\texplicit Adam(double alpha = DEFAULT_PARAMS[0], double beta1 = DEFAULT_PARAMS[1],\n\t              double beta2 = DEFAULT_PARAMS[2], double eps = DEFAULT_PARAMS[3])\n\t\t: alpha_(alpha), beta1_(beta1), beta2_(beta2), eps_(eps)\n\t{\n\t}\n\n\texplicit Adam(const nlohmann::json& params)\n\t\t: alpha_(params.value(\"alpha\", DEFAULT_PARAMS[0])),\n\t\t  beta1_(params.value(\"beta1\", DEFAULT_PARAMS[1])),\n\t\t  beta2_(params.value(\"beta2\", DEFAULT_PARAMS[2])),\n\t\t  eps_(params.value(\"eps\", DEFAULT_PARAMS[3]))\n\t{\n\t}\n\n\tstatic nlohmann::json defaultParams()\n\t{\n\t\treturn nlohmann::json{\n\t\t\t{\"name\", \"Adam\"},\n\t\t\t{\"alhpa\", DEFAULT_PARAMS[0]},\n\t\t\t{\"beta1\", DEFAULT_PARAMS[1]},\n\t\t\t{\"beta2\", DEFAULT_PARAMS[2]},\n\t\t\t{\"eps\", DEFAULT_PARAMS[3]},\n\t\t};\n\t}\n\n\t[[nodiscard]] nlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json{\n\t\t\t{\"name\", \"Adam\"},  {\"alhpa\", alpha_}, {\"beta1\", beta1_},\n\t\t\t{\"beta2\", beta2_}, {\"eps\", eps_},\n\t\t};\n\t}\n\n\tEigen::VectorXd getUpdate(const Eigen::VectorXd& grad) override\n\t{\n\t\tif(t_ == 0)\n\t\t{\n\t\t\tm_ = Eigen::VectorXd::Zero(grad.rows());\n\t\t\tv_ = Eigen::VectorXd::Zero(grad.rows());\n\t\t}\n\t\t++t_;\n\n\t\tm_ *= beta1_;\n\t\tm_ += (1 - beta1_) * grad;\n\n\t\tEigen::VectorXd g2 = grad.array().square();\n\t\tv_ *= beta2_;\n\t\tv_ += (1 - beta2_) * g2;\n\n\t\tdouble epsnorm = eps_ * sqrt(1.0 - pow(beta2_, t_));\n\t\tEigen::VectorXd denom\n\t\t\t= v_.unaryExpr([epsnorm](double x) { return sqrt(x) + epsnorm; });\n\n\t\tdouble alphat = alpha_ * sqrt(1.0 - pow(beta2_, t_)) / (1.0 - pow(beta1_, t_));\n\n\t\treturn -alphat * m_.cwiseQuotient(denom);\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "c95a6a4a41e001afd589b6b20139bd2154db305b", "size": 1938, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Optimizers/Adam.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Optimizers/Adam.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Optimizers/Adam.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0714285714, "max_line_length": 82, "alphanum_fraction": 0.637254902, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5938885641974988}}
{"text": "/**\n * \\file ex7.cxx\n * \\author Ray Chew\n * \\date 7 July 2017\n * \\brief Dijkstra graph algorithm for .gph graphs\n */\n\n/**\n * \\mainpage Ex7\n * \n * \\section Description\n * \n * Shortest-longest path distance calculator using the Dijkstra algorithm for `.gph` graphs.<br>\n * Reads `.gph` graph file and prints the node number and distance of the node corresponding to the end of longest shortest path.<br>\n * Flag `-m1` uses the Boost Graph Library Dijkstra Algorithm.<br>\n * Flag `-m2` uses a self-implemented Dijkstra Algorithm for undirected graphs.<br>\n * \n * * compile: `g++ -std=c++14 -O3 ex7.cxx -o ex7 -lboost_timer -Wall`<br>\n * * run: `./ex7 filepath/graph.gph [-m1/-m2]`<br>\n * * flags: `-m1` for boost algorithm, `-m2` for self-implemented algorithm.\n */\n\n/* -- Includes -- */\n/* C++ includes. */\n#include <iostream> /* for std::cout, std::ofstream */\n#include <fstream> /* for fstream::app */\n#include <utility> /* for std::pair */\n#include <vector> /* for std::vector */\n\n/* Boost Dijkstra Algorithm includes. */\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp> \n\n/* Boost qi parser and timer includes. */\n#include <boost/spirit/include/qi.hpp>\n#include <boost/timer/timer.hpp>\n\n/* Boost Bimap Container includes for own algorithm. */\n#include <boost/bimap.hpp>\n#include <boost/bimap/multiset_of.hpp>\n#include <boost/bimap/support/lambda.hpp> /* for bimap::_data and bimap::_key */\n//#include <boost/bind.hpp> /* for boost::bind in sorting of vector<pair<int,int>> */\n\nnamespace bm = boost::bimaps;\nusing namespace boost::spirit;\nusing qi::int_;\nusing qi::double_;\nusing qi::parse;\n\n/** \n *  \\brief A method that calculates the longest-shortest path from the source node with name `1` using the boost library dijkstra algorithm.\n *  \\param n number of edges as int.\n *  \\param file pointer to graph file opened.\n *  \\return MaxVertex and MaxDistance, the node name and distance of the longest-shortest path as `std::pair<int,int>`.\n */\nstd::pair<int,int> m1 (int& n, std::ifstream& file){\n  \n  /* start get list of edges and weights */\n  using Edge = std::pair<int, int>; \n  std::vector<Edge> Edges; // vector to store std::pair of edges.\n  std::vector<int> Weights; // vector to weights as integers.\n  std::string str; // string to store line of graph file.\n  \n  while (getline(file,str)){ /// get graph line-by-line.\n    int Vert1;\n    int Vert2;\n    int Weight;\n    \n    auto it = str.begin(); /// initializes iterator for qi::parse. \n    \n    parse(it, str.end(), int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](int i){Weight = i;})]);  \n    \n    Edge edge = std::make_pair(Vert1, Vert2);  /// make edge-pair out of vertices.\n    Edges.push_back(edge);\n    Weights.push_back(Weight);\n  }\n  /* end get list of edges and weights */\n  \n  /* start building graph */\n  /// initialize type to store weights on edges.\n  typedef boost::property<boost::edge_weight_t, int> EdgeWeightProperty;\n  // adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>\n  /// create graph.\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph;\n  \n  Graph g(Edges.begin(),Edges.end(), Weights.begin(), n);   /// populate graph.\n  \n  /* end building graph */\n  \n  \n  /* start finding shortest path from source node. */\n  typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  vertex_descriptor source = boost::vertex(1, g);   /// define source vertex as vertex with index == 1.\n  /// initialize vectors for predecessor and distances.\n  std::vector<vertex_descriptor> parents(boost::num_vertices(g));\n  std::vector<int> distances(boost::num_vertices(g));\n  \n  boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));\n  \n  /* end finding shortest path of from source node. */\n  \n  \n  /* start finding longest-shortest path from source node. */\n  signed int maxDistance = 0;\n  unsigned int maxVertex = 0;\n  \n  /// create iterator over vertices.\n  // vertexPair.first is the iterated element, and .second is the end-index of all vertices.\n  typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;\n  std::pair<vertex_iter, vertex_iter> vertexPair;\n  \n  // vertexPair = boost::vertices loops over all vertices in g.\n  for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first){\n    /// replace maxDistance if a greater distance is found, and maxDistance must be less than \"infinity\" (of 32-bit signed integer).\n    if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < std::numeric_limits<int>::max())){\n      maxDistance = distances[*vertexPair.first];\n      maxVertex = *vertexPair.first;\n    }\n    /// if distance == maxDistance, check if vertex index is smaller.\n    if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){\n      maxDistance = distances[*vertexPair.first];\n    }\n  }\n  /* end finding longest-shortest path from source node. */\n\n  std::pair<int,int> Final = std::make_pair(maxVertex,maxDistance);\n  return Final;\n}\n\n\n/** \n *  \\brief A method that calculates the longest-shortest path from the source node with name `1` using a self-implemented dijkstra algorithm.\n *  \\param n number of edges as int.\n *  \\param file pointer to graph file opened.\n *  \\return MaxVertex and MaxDistance, the node name and distance of the longest-shortest path as `std::pair<int,int>`.\n */\nstd::pair<int,int> m2 (int& n, std::ifstream& file){\n  \n  /* start populating adjacency list */\n  using vertex =  std::pair<int, int>;\n  std::vector<std::vector<vertex>> adjList(n); // empty adjacency list.\n  \n  std::cout << \"pass initialize adjList.\" << std::endl;\n  std::string str; // string to store line of graph.\n  \n  while (getline(file,str)){\n    int Vert1;\n    int Vert2;\n    int Weight;\n    \n    auto it = str.begin(); /// initialize iterator for qi::parse. \n    \n    parse(it, str.end(), int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);  \n    \n    vertex VertexWeight1(Vert2,Weight);\n    adjList[Vert1].push_back(VertexWeight1);\n    \n    vertex VertexWeight2(Vert1,Weight);\n    adjList[Vert2].push_back(VertexWeight2);\n  }\n  std::cout << \"pass build adjList.\" << std::endl;\n  /* end populating adjacency list */\n  \n  \n  using bimap = bm::bimap<int, boost::bimaps::multiset_of<int,std::less<int>>>;\n  bimap Unvisited; /// define unvisited set as a boost::bimap container.\n  std::vector<vertex> finalWeights(n); // vector to store all calculated weights/distances.\n  \n  /* start initializing unvisited set */\n  for(int i=1; i<n; i++){ \n    Unvisited.left.insert(bimap::left_value_type(i,std::numeric_limits<int>::max()));\n    finalWeights[i] = std::make_pair(i, std::numeric_limits<int>::max());\n  }\n  bimap::right_iterator itr = Unvisited.right.begin();\n  Unvisited.right.replace_key(itr, 0);\n  finalWeights[1].second = 0;\n  \n  std::cout << \"pass initialize unvisited set.\" << std::endl;\n  /* end initializing unvisited set */\n  \n  \n  /* start calculating and updating distances */\n  while(Unvisited.size()>0){\n    auto minPair = Unvisited.right.begin();\n    int minIdx = minPair->second;\n    int minDist = minPair->first;\n    \n    signed int adjListSize = adjList[minIdx].size();\n    \n    for(int j=0; j<adjListSize; j++){\n      int neighbour = adjList[minIdx][j].first;\n      int dist = adjList[minIdx][j].second;\n      int newDist = minDist + dist;\n      int nPWeight = finalWeights[neighbour].second;\n      \n      if (newDist < nPWeight){\n\tauto toBeReplaced = Unvisited.left.find(neighbour);\n\tUnvisited.left.modify_data(toBeReplaced, bm::_data=newDist);\n\tfinalWeights[neighbour].second = newDist;\n      }\n    }\n    Unvisited.left.erase(minIdx);\n  }\n  std::cout << \"pass distance calculation.\" << std::endl;\n  /* end calculating and updating distances */\n  \n  /* start find node of the longest-shortest path */\n  //std::sort(finalWeights.begin(), finalWeights.end(), [](auto &left, auto &right) {\n  //    return left.second < right.second;}); \n  \n  int maxDistance = 0;\n  int maxVertex = 0;\n  \n  for(auto ita = finalWeights.begin(); ita != finalWeights.end(); ita++){\n    /// replace maxDistance if a greater distance is found, and maxDistance must be less than \"infinity\" (of 32-bit signed integer).\n    if ((ita->second > maxDistance) && (ita->second < std::numeric_limits<int>::max())){\n      maxDistance = ita->second;\n      maxVertex = ita->first;\n    }\n    /// if distance == maxDistance, check if vertex index is smaller.\n    if ((ita->second == maxDistance) && (ita->first < maxVertex)){\n      maxVertex = ita->first;\n    }\n  }\n  /* end find node of the longest-shortest path */\n  \n  vertex Final = std::make_pair(maxVertex,maxDistance);\n  return Final;\n}\n\n\nint main(int argc, char*argv[]){\n  \n  if (argc < 3){ // must have filename of graph and a flag of some sort...\n    std::cerr << \"No file or flag (-m1 or -m2)!!!\" << std::endl;\n    return -1;\n  }\n  \n  std::ifstream file(argv[1]);  // read graph file.\n  std::string str; /// read graph file line by line.\n  \n  \n  /* start get number of edges */\n  getline(file, str);\n  int n; /// store n as int for number of edges.\n  \n  auto it = str.begin();\n  parse(it, str.end(), int_[([&n](int i){n = i;})] >> int_);\n  n = n + 1; // No?\n  /* end get number of edges */\n  \n  \n  /* start dijkstra algorithm according to flag */\n  std::pair<int,int> f =std::make_pair(0,0); /// initialize f as (int,int) pair for final node number and distance.\n  boost::timer::cpu_timer timer;\n  for(int i = 0; i < argc; i++){\n    if (std::string(argv[i]) == \"-m1\"){\n      f = m1(n,file);\n    }\n    else if(std::string(argv[i]) == \"-m2\"){\n      f = m2(n,file);\n    }\n  }\n  boost::timer::cpu_times times = timer.elapsed();\n  /* end dijkstra algorithm according to flag */\n  \n  \n  /// output vertex and distance of the longest-shortest path.\n  std::cout << \"RESULT VERTEX \" << f.first << std::endl;\n  std::cout << \"RESULT DIST \" << f.second <<  std::endl;\n  \n  /// print CPU- and Wall-Time. \n  // boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.\n  std::cout << std::endl;\n  std::cout << \"WALL-CLOCK \" << times.wall / 1e9 << \"s\" << std::endl;\n  std::cout << \"USER TIME \" << times.user / 1e9 << \"s\" << std::endl;\n  \n  file.close();  \n  return 0;\n}\n", "meta": {"hexsha": "91ffac736dd3954cab68220ef3acf01c27affd14", "size": 10540, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "RayChew/Ex7/ex7.cxx", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "RayChew/Ex7/ex7.cxx", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "RayChew/Ex7/ex7.cxx", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 37.3758865248, "max_line_length": 176, "alphanum_fraction": 0.660056926, "num_tokens": 2822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5938783464121343}}
{"text": "/*\n *  lengthdistribution.cpp\n *  MetaQuant\n *\n *  Kevin McLoughlin\n *  Based on code from eXpress, created by Adam Roberts in 2013.\n *  Copyright 2014 Kevin McLoughlin, Adam Roberts. All rights reserved.\n */\n\n#include \"lengthdistribution.h\"\n#include \"main.h\"\n#include <numeric>\n#include <boost/assign.hpp>\n#include <iostream>\n#include <fstream>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/normal.hpp>\n\nusing namespace std;\n\nLengthDistribution::LengthDistribution(double alpha, size_t max_val,\n                                       size_t prior_mu, size_t prior_sigma,\n                                       size_t kernel_n, double kernel_p,\n                                       size_t bin_size)\n    : _hist(max_val/bin_size+1),\n      _tot_mass(LOG_0),\n      _sum(LOG_0),\n      _min(max_val/bin_size),\n      _bin_size(bin_size) {\n  \n  max_val = max_val/bin_size;\n  kernel_n = kernel_n/bin_size;\n  assert(kernel_n % 2 == 0);\n        \n  double tot = log(alpha);\n\n  // Set to prior distribution\n  if (prior_mu) {\n    boost::math::normal norm(prior_mu/bin_size,\n                             prior_sigma/(bin_size*bin_size));\n\n    for (size_t i = 0; i <= max_val; ++i) {\n      double norm_mass = boost::math::cdf(norm, i+0.5) -\n                         boost::math::cdf(norm, i-0.5);\n      double mass = LOG_EPSILON;\n      if (norm_mass != 0) {\n        mass = tot + log(norm_mass);\n      }\n      _hist[i] = mass;\n      _sum = log_add(_sum, log((double)i)+mass);\n      _tot_mass = log_add(_tot_mass, mass);\n    }\n  } else {\n    _hist = vector<double>(max_val + 1, tot - log((double)max_val));\n    _hist[0] = LOG_0;\n    _sum = _hist[1] + log((double)(max_val * (max_val + 1))) - log(2.);\n    _tot_mass = tot;\n  }\n\n  // Define kernel\n  boost::math::binomial_distribution<double> binom(kernel_n, kernel_p);\n  _kernel = vector<double>(kernel_n + 1);\n  for (size_t i = 0; i <= kernel_n; i++) {\n    _kernel[i] = log(boost::math::pdf(binom, i));\n  }\n}\n\nLengthDistribution::LengthDistribution(string param_file_name,\n                                       string length_type) :\n    _bin_size(1) {\n  ifstream infile (param_file_name.c_str());\n  const size_t BUFF_SIZE = 99999;\n  char line_buff[BUFF_SIZE];\n  \n  if (!infile.is_open()) {\n    logger.severe(\"Unable to open paramater file '%s'.\",\n                  param_file_name.c_str());\n  }\n\n  do {\n    infile.getline (line_buff, BUFF_SIZE, '\\n');\n  } while (strncmp(line_buff + 1, length_type.c_str(), length_type.size()));\n\n  infile.getline (line_buff, BUFF_SIZE, '\\n');\n  char *p = strtok(line_buff, \"\\t\");\n  size_t i = 0;\n  \n  _tot_mass = 0;\n  _sum = 0;\n  do {\n    double val = strtod(p,NULL);\n    _hist.push_back(log(val));\n    _tot_mass += val;\n    _sum += i*val;\n    i++;\n    p = strtok(NULL, \"\\t\");\n  } while (p);\n  \n  _tot_mass = log(_tot_mass);\n  _sum = log(_sum);\n  _min = max_val();;\n}\n\nsize_t LengthDistribution::max_val() const {\n  return (_hist.size()-1) * _bin_size;\n}\n\nsize_t LengthDistribution::min_val() const {\n  if (_min == _hist.size() - 1) {\n    return 1;\n  }\n  return _min;\n}\n\nvoid LengthDistribution::add_val(size_t len, double mass) {\n  assert(!isnan(mass));\n  assert(_kernel.size());\n  \n  len /= _bin_size;\n\n  if (len > max_val()) {\n      len = max_val();\n  }\n  if (len < _min) {\n    _min = len;\n  }\n\n  size_t offset = len - _kernel.size()/2;\n\n  for (size_t i = 0; i < _kernel.size(); i++) {\n    if (offset > 0 && offset < _hist.size()) {\n      double k_mass = mass + _kernel[i];\n      _hist[offset] = log_add(_hist[offset], k_mass);\n      _sum = log_add(_sum, log((double)offset)+k_mass);\n      _tot_mass = log_add(_tot_mass, k_mass);\n    }\n    offset++;\n  }\n}\n\ndouble LengthDistribution::pmf(size_t len) const {\n  len /= _bin_size;\n  if (len > max_val()) {\n    len = max_val();\n  }\n  return _hist[len]-_tot_mass;\n}\n\ndouble LengthDistribution::cmf(size_t len) const {\n  double cum = LOG_0;\n  vector<double> cdf(_hist.size());\n  for (size_t i = 0; i < _hist.size(); ++i) {\n    cum = log_add(cum, _hist[i]);\n    \n  }\n  return cum - _tot_mass;\n}\n\nvector<double> LengthDistribution::cmf() const {\n  double cum = LOG_0;\n  vector<double> cdf(_hist.size());\n  for (size_t i = 0; i < _hist.size(); ++i) {\n    cum = log_add(cum, _hist[i]);\n    cdf[i] = cum - _tot_mass;\n  }\n  assert(approx_eq(cum, _tot_mass));\n\n  return cdf;\n}\n\ndouble LengthDistribution::tot_mass() const {\n  return _tot_mass;\n}\n\ndouble LengthDistribution::mean() const {\n  return _sum - tot_mass();\n}\n\nstring LengthDistribution::to_string() const {\n  string s = \"\";\n  char buffer[50];\n  for(size_t i = 0; i < _hist.size(); i++) {\n    sprintf(buffer, \"%e\\t\",sexp(pmf(i*_bin_size)));\n    s += buffer;\n  }\n  s.erase(s.length()-1,1);\n  return s;\n}\n\nvoid LengthDistribution::append_output(ofstream& outfile,\n                                       string length_type) const {\n  outfile << \">\" << length_type << \" Length Distribution (0-\" << max_val()*_bin_size;\n  outfile << \")\\n\" << to_string() << endl;\n}\n", "meta": {"hexsha": "a78187bba08c892636e2dcd4cc30059e7f741984", "size": 4967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lengthdistribution.cpp", "max_stars_repo_name": "kmclough/MetaQuant_1.0", "max_stars_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "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/lengthdistribution.cpp", "max_issues_repo_name": "kmclough/MetaQuant_1.0", "max_issues_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "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/lengthdistribution.cpp", "max_forks_repo_name": "kmclough/MetaQuant_1.0", "max_forks_repo_head_hexsha": "2df1d823856cd2204c022cdba82aa2177cf921e0", "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": 25.4717948718, "max_line_length": 85, "alphanum_fraction": 0.5973424602, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5938631115349995}}
{"text": "#ifndef MATHTOOLBOX_GRADIENT_DESCENT_HPP\n#define MATHTOOLBOX_GRADIENT_DESCENT_HPP\n\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        /// \\brief Run a simple gradient descent to find a local minimizer of the specified function\n        ///\n        /// \\details This algorithm uses the Backtracking Line Search algorithm to determine an appropriate step size.\n        ///\n        /// \\param lower_bound The lower bound values. If this is a zero-length empty vector, the algorithm just ignores\n        /// the lower bound condition.\n        ///\n        /// \\param upper_bound The upper bound values. If this is a zero-length empty vector, the algorithm just ignores\n        /// the upper bound condition.\n        ///\n        /// \\param default_alpha The default step size that the algorithm first tries.\n        void RunGradientDescent(const Eigen::VectorXd&                                        x_init,\n                                const std::function<double(const Eigen::VectorXd&)>&          f,\n                                const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& g,\n                                const Eigen::VectorXd&                                        lower_bound,\n                                const Eigen::VectorXd&                                        upper_bound,\n                                const double                                                  epsilon,\n                                const double                                                  default_alpha,\n                                const unsigned int                                            max_num_iters,\n                                Eigen::VectorXd&                                              x_star,\n                                unsigned int&                                                 num_iters);\n    } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_GRADIENT_DESCENT_HPP\n", "meta": {"hexsha": "10411d3ffa8fb2a212833284dcf5a323251dd525", "size": 1980, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/gradient-descent.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/gradient-descent.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/gradient-descent.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": 56.5714285714, "max_line_length": 120, "alphanum_fraction": 0.4843434343, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5936715425609015}}
{"text": "#include <benchmark.hpp>\n#include <pi_helpers.hpp>\n\n#include <boost/mpi.hpp>\n#include <gmpxx.h>\n\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\nnamespace mpi = boost::mpi;\n\nnamespace\n{\n\nstatic constexpr int ROOT_ID = 0;\nstatic constexpr int TAG = 0;\n\nvoid send_mpf_pi_part(const mpf_class& pi_part, const mpi::communicator& world)\n{\n    mpf_srcptr pi_part_raw = pi_part.get_mpf_t();\n\n    world.send(ROOT_ID, TAG, pi_part_raw->_mp_prec);\n    world.send(ROOT_ID, TAG, pi_part_raw->_mp_size);\n    world.send(ROOT_ID, TAG, pi_part_raw->_mp_exp);\n    world.send(ROOT_ID, TAG, pi_part_raw->_mp_d, std::abs(pi_part_raw->_mp_size));\n}\n\nvoid recv_and_add_mpf_pi_part(mpf_class& pi, int rank, const mpi::communicator& world)\n{\n    mpf_t another_pi_part;\n\n    world.recv(rank, TAG, another_pi_part->_mp_prec);\n    world.recv(rank, TAG, another_pi_part->_mp_size);\n    world.recv(rank, TAG, another_pi_part->_mp_exp);\n\n    auto mp_d = std::make_unique<mp_limb_t[]>(another_pi_part->_mp_prec + 1);\n    another_pi_part->_mp_d = mp_d.get();\n    world.recv(rank, TAG, another_pi_part->_mp_d, std::abs(another_pi_part->_mp_size));\n\n    mpf_add(pi.get_mpf_t(), pi.get_mpf_t(), another_pi_part);\n}\n\nvoid pi_sum_reduce(const mpf_class& pi_part, mpf_class& pi, const mpi::communicator& world)\n{\n    // TODO: create a user-defined type for GMP float\n    if (world.rank() == ROOT_ID)\n    {\n        pi = std::move(pi_part);\n        std::size_t process_count = world.size();\n        for (std::size_t rank = 1; rank < process_count; ++rank)\n        {\n            recv_and_add_mpf_pi_part(pi, rank, world);\n        }\n    }\n    else\n    {\n        send_mpf_pi_part(pi_part, world);\n    }\n}\n\nmpf_class pi_leibniz_mpi(std::size_t summand_count, mp_bitcnt_t precision,\n                         const mpi::communicator& world)\n{\n    mpi::broadcast(world, summand_count, ROOT_ID);\n\n    mpf_class pi_part = my::pi::pi_part_leibniz_mpi(summand_count, precision, world.rank(), world.size());\n    world.barrier();\n\n    mpf_class pi(0.0, precision);\n    pi_sum_reduce(pi_part, pi, world);\n\n    return 4 * pi;\n}\n\nmpf_class pi_bellard_mpi(std::size_t summand_count, mp_bitcnt_t precision,\n                         const mpi::communicator& world)\n{\n    mpi::broadcast(world, summand_count, ROOT_ID);\n\n    mpf_class pi_part = my::pi::pi_part_bellard_mpi(summand_count, precision, world.rank(), world.size());\n    world.barrier();\n\n    mpf_class pi(0.0, precision);\n    pi_sum_reduce(pi_part, pi, world);\n\n    pi /= (1 << 6);\n    return pi;\n}\n\ntemplate <typename RegularPiCalculationFunction,\n          typename MPIPiCalculationFunction>\nvoid benchmark(std::size_t summand_count,\n               mp_bitcnt_t precision,\n               const mpi::communicator& world,\n               RegularPiCalculationFunction pi_regular,\n               MPIPiCalculationFunction pi_mpi)\n{\n    static constexpr std::size_t ITERATIONS_COUNT = 100;\n\n    if (summand_count < static_cast<std::size_t>(world.size()))\n    {\n        throw std::runtime_error(\"Summand count is less than processor count, please decrease number of processors.\");\n    }\n\n    if (world.rank() == ROOT_ID)\n    {\n        auto pi_regular_wrapper = [summand_count, precision, pi_regular]()\n        {\n            return pi_regular(summand_count, precision);\n        };\n        double pi_regular_result = my::benchmark_function(pi_regular_wrapper, ITERATIONS_COUNT);\n        my::print_result(\"Regular time: \", pi_regular_result);\n    }\n\n    double pi_mpi_result;\n    {\n        auto pi_mpi_wrapper = [summand_count, precision, pi_mpi, world]()\n        {\n            return pi_mpi(summand_count, precision, world);\n        };\n        pi_mpi_result = my::benchmark_function(pi_mpi_wrapper, ITERATIONS_COUNT);\n    }\n    if (world.rank() == ROOT_ID)\n    {\n        my::print_result(\"    MPI time: \", pi_mpi_result);\n    }\n}\n\ntemplate <typename MPIPiCalculationFunction>\nvoid calculate(std::size_t summand_count,\n               mp_bitcnt_t precision,\n               const mpi::communicator& world,\n               MPIPiCalculationFunction pi_mpi)\n{\n    if (summand_count < static_cast<std::size_t>(world.size()))\n    {\n        throw std::runtime_error(\"Summand count is less than processor count, please decrease number of processors.\");\n    }\n\n    mpf_class pi_mpi_result = pi_mpi(summand_count, precision, world);\n\n    if (world.rank() == ROOT_ID)\n    {\n        mp_exp_t exp;\n        std::string pi_string = pi_mpi_result.get_str(exp);\n        assert(exp == 1);\n        std::cout << std::string_view(pi_string.data(), 1);\n        std::cout << '.';\n        std::cout << std::string_view(pi_string.data() + 1, pi_string.size()) << std::endl;\n    }\n}\n\n}  // namespace\n\nint main(int argc, char* argv[]) try\n{\n    mpi::environment env(argc, argv);\n    mpi::communicator world;\n\n    struct AlgorithmInfo\n    {\n        const std::function<mpf_class(std::size_t summand_count, mp_bitcnt_t precision)> pi_regular;\n        const std::function<mpf_class(std::size_t summand_count, mp_bitcnt_t precision, const mpi::communicator& world)> pi_mpi;\n        my::pi::AlgorithmParams params;\n    };\n\n    std::unordered_map<my::pi::AlgorithmType, AlgorithmInfo>\n    algorithm_info_map =\n    {\n        {\n            my::pi::AlgorithmType::BELLARD,\n            {\n                .pi_regular = my::pi::pi_bellard_regular,\n                .pi_mpi = pi_bellard_mpi,\n                .params =\n                {\n                    .precision = (1 << 26),\n                    .benchmark_summand_count = std::size_t{1} << 8,\n                    .calculation_summand_count = std::size_t{1} << 22\n                }\n            }\n        },\n        {\n            my::pi::AlgorithmType::LEIBNIZ,\n            {\n                .pi_regular = my::pi::pi_leibniz_regular,\n                .pi_mpi = pi_leibniz_mpi,\n                .params =\n                {\n                    .precision = (1 << 7),\n                    .benchmark_summand_count = std::size_t{1} << 26,\n                    .calculation_summand_count = std::size_t{1} << 45\n                }\n            }\n        },\n    };\n\n    bool do_benchmark = true;\n    auto algorithm = my::pi::AlgorithmType::LEIBNIZ;\n\n    const AlgorithmInfo& algorithm_info = algorithm_info_map.at(algorithm);\n\n    if (do_benchmark)\n    {\n        benchmark(algorithm_info.params.benchmark_summand_count,\n                  algorithm_info.params.precision,\n                  world,\n                  algorithm_info.pi_regular,\n                  algorithm_info.pi_mpi);\n    }\n    else\n    {\n        calculate(algorithm_info.params.calculation_summand_count,\n                  algorithm_info.params.precision,\n                  world,\n                  algorithm_info.pi_mpi);\n    }\n\n    return EXIT_SUCCESS;\n}\ncatch (const std::exception& e)\n{\n    std::cerr << \"Exception caught: \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}\ncatch (...)\n{\n    std::cerr << \"An unknown exception caught\" << std::endl;\n    return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "25fa5c2ec368bfb7a1c378f739c3c05a75db8b74", "size": 6968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boost-mpi-pi-calculation/src/main.cpp", "max_stars_repo_name": "kovdan01/parallel-computing", "max_stars_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/boost-mpi-pi-calculation/src/main.cpp", "max_issues_repo_name": "kovdan01/parallel-computing", "max_issues_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boost-mpi-pi-calculation/src/main.cpp", "max_forks_repo_name": "kovdan01/parallel-computing", "max_forks_repo_head_hexsha": "878d836e4b05563dc7fe11b6d7ca65fea950b5b7", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9055793991, "max_line_length": 128, "alphanum_fraction": 0.6173938002, "num_tokens": 1704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.593520618672174}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_MODIFIED_BESSEL_SECOND_KIND_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_MODIFIED_BESSEL_SECOND_KIND_HPP\n\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     *\n       \\f[\n       \\mbox{modified\\_bessel\\_second\\_kind}(v, z) =\n       \\begin{cases}\n         \\textrm{error} & \\mbox{if } z \\leq 0 \\\\\n         K_v(z) & \\mbox{if } z > 0 \\\\[6pt]\n         \\textrm{NaN} & \\mbox{if } z = \\textrm{NaN}\n       \\end{cases}\n       \\f]\n\n       \\f[\n       \\frac{\\partial\\, \\mbox{modified\\_bessel\\_second\\_kind}(v, z)}{\\partial z} =\n       \\begin{cases}\n         \\textrm{error} & \\mbox{if } z \\leq 0 \\\\\n         \\frac{\\partial\\, K_v(z)}{\\partial z} & \\mbox{if } z > 0 \\\\[6pt]\n         \\textrm{NaN} & \\mbox{if } z = \\textrm{NaN}\n       \\end{cases}\n       \\f]\n\n       \\f[\n       {K_v}(z)\n       =\n       \\frac{\\pi}{2}\\cdot\\frac{I_{-v}(z) - I_{v}(z)}{\\sin(v\\pi)}\n       \\f]\n\n       \\f[\n       \\frac{\\partial \\, K_v(z)}{\\partial z} = -\\frac{v}{z}K_v(z)-K_{v-1}(z)\n       \\f]\n     *\n     */\n    template<typename T2>\n    inline T2\n    modified_bessel_second_kind(int v, const T2 z) {\n      return boost::math::cyl_bessel_k(v, z);\n    }\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "cbb3f637907b5d80959f57174035af93153acb53", "size": 1200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/modified_bessel_second_kind.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/modified_bessel_second_kind.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/modified_bessel_second_kind.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": 24.0, "max_line_length": 82, "alphanum_fraction": 0.5266666667, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5934999728133687}}
{"text": "#include \"stratton-chu/distorted-surface.hpp\"\n\n#include <boost/math/special_functions/legendre.hpp>\n\nusing namespace boost::math;\n\ndouble legendre(int num, double arg)\n{\n    if (arg > 1.0)\n        return legendre_p(num, 1.0);\n    if (arg < -1.0)\n        return legendre_p(num, -1.0);\n    return legendre_p(num, arg);\n}\n\n\ndouble legendre_derivative(int num, double arg)\n{\n    if (arg > 1.0)\n        return 0.0;\n    if (arg < -1.0)\n        return 0.0;\n    return legendre_p_prime(num, arg);\n}\n\nSurfaceDistortionHarmonic::SurfaceDistortionHarmonic(\n        const ISurface& pure_surface,\n        const Vector& v,\n        const std::vector<DistortionHarmonic>& harmonics) :  // v - unit vector\n    m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v)\n{}\n\nPosition SurfaceDistortionHarmonic::point(const Vector2D& pos) const\n{\n    Position result = m_pure_surface.point(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = m_harmonics[i].ampl * cos(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);\n        Vector delta = m_v * shift;\n        result += delta;\n    }\n\n    return result;\n}\n\nVector SurfaceDistortionHarmonic::tau1(const Vector2D& pos) const\n{\n    Vector result = m_pure_surface.tau1(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = - m_harmonics[i].ampl * m_harmonics[i].kx * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);\n        Vector delta =  m_v * shift;\n        result += delta;\n    }\n    return result;\n}\n\nVector SurfaceDistortionHarmonic::tau2(const Vector2D& pos) const\n{\n    Vector result = m_pure_surface.tau2(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = - m_harmonics[i].ampl * m_harmonics[i].ky * sin(m_harmonics[i].kx * pos[0] + m_harmonics[i].ky * pos[1]);\n        Vector delta = m_v * shift;\n        result += delta;\n    }\n    return result;\n}\n\nSurfaceDistortionLegendre::DistortionPolinom::DistortionPolinom(double ampl, double alpha, int number) :\n    ampl(ampl), direction(cos(alpha), sin(alpha)), number(number)\n{\n}\n\nSurfaceDistortionLegendre::SurfaceDistortionLegendre(\n        const ISurface& pure_surface,\n        const Vector& v,\n        double radius,\n        Vector2D center,\n        const std::vector<DistortionPolinom>& harmonics) :  // v - unit vector\n    m_pure_surface(pure_surface), m_harmonics(harmonics), m_v(v), m_center(center), m_radius(radius)\n{\n}\n\nPosition SurfaceDistortionLegendre::point(const Vector2D& pos) const\n{\n    Position result = m_pure_surface.point(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = m_harmonics[i].ampl * legendre(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);\n        Vector delta = m_v * shift;\n        result += delta;\n    }\n\n    return result;\n}\n\nVector SurfaceDistortionLegendre::tau1(const Vector2D& pos) const\n{\n    Vector result = m_pure_surface.tau1(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = m_harmonics[i].ampl * m_harmonics[i].direction[0] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);\n        Vector delta =  m_v * shift;\n        result += delta;\n    }\n    return result;\n}\n\nVector SurfaceDistortionLegendre::tau2(const Vector2D& pos) const\n{\n    Vector result = m_pure_surface.tau2(pos);\n    for (size_t i = 0; i < m_harmonics.size(); i++)\n    {\n        double shift = m_harmonics[i].ampl * m_harmonics[i].direction[1] / m_radius * legendre_derivative(m_harmonics[i].number, m_harmonics[i].direction * (pos - m_center) / m_radius);\n        Vector delta =  m_v * shift;\n        result += delta;\n    }\n    return result;\n}\n\n", "meta": {"hexsha": "5d21cd05965126e97934e9974e649f48e9a806d1", "size": 3738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/stratton-chu-library/src/distorted-surface.cpp", "max_stars_repo_name": "KrisRobinson52/stratton_chu_further", "max_stars_repo_head_hexsha": "bb11bd5ee0870e8ba6900fb24481b13d485311bd", "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/stratton-chu-library/src/distorted-surface.cpp", "max_issues_repo_name": "KrisRobinson52/stratton_chu_further", "max_issues_repo_head_hexsha": "bb11bd5ee0870e8ba6900fb24481b13d485311bd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T02:39:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-25T02:39:39.000Z", "max_forks_repo_path": "cpp/stratton-chu-library/src/distorted-surface.cpp", "max_forks_repo_name": "KrisRobinson52/stratton_chu_further", "max_forks_repo_head_hexsha": "bb11bd5ee0870e8ba6900fb24481b13d485311bd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-11T15:32:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T15:32:45.000Z", "avg_line_length": 30.6393442623, "max_line_length": 185, "alphanum_fraction": 0.6492776886, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5934999720262901}}
{"text": "#ifndef COORDINATE_CALCULATION\n#define COORDINATE_CALCULATION\n\n#include \"util/coordinate.hpp\"\n\n#include <boost/optional.hpp>\n\n#include <algorithm>\n#include <utility>\n#include <vector>\n\nnamespace osrm\n{\nnamespace util\n{\nnamespace coordinate_calculation\n{\n\nnamespace detail\n{\nconst constexpr long double DEGREE_TO_RAD = 0.017453292519943295769236907684886;\nconst constexpr long double RAD_TO_DEGREE = 1. / DEGREE_TO_RAD;\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)\nconst constexpr long double EARTH_RADIUS = 6372797.560856;\n}\n\n//! Takes the squared euclidean distance of the input coordinates. Does not return meters!\nstd::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs);\n\ndouble haversineDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\ndouble greatCircleDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// get the length of a full coordinate vector, using one of our basic functions to compute distances\ntemplate <class BinaryOperation>\ndouble getLength(const std::vector<Coordinate> &coordinates, BinaryOperation op)\n{\n    if (coordinates.empty())\n        return 0.;\n\n    double result = 0;\n    const auto functor = [&result, op](const Coordinate lhs, const Coordinate rhs) {\n        result += op(lhs, rhs);\n        return false;\n    };\n    // side-effect find adding up distances\n    std::adjacent_find(coordinates.begin(), coordinates.end(), functor);\n\n    return result;\n}\n\n// Find the closest distance and location between coordinate and the line connecting source and\n// target:\n//             coordinate\n//                 |\n//                 |\n// source -------- x -------- target.\n// returns x as well as the distance between source and x as ratio ([0,1])\ninline std::pair<double, FloatCoordinate> projectPointOnSegment(const FloatCoordinate &source,\n                                                                const FloatCoordinate &target,\n                                                                const FloatCoordinate &coordinate)\n{\n    const FloatCoordinate slope_vector{target.lon - source.lon, target.lat - source.lat};\n    const FloatCoordinate rel_coordinate{coordinate.lon - source.lon, coordinate.lat - source.lat};\n    // dot product of two un-normed vectors\n    const auto unnormed_ratio = static_cast<double>(slope_vector.lon * rel_coordinate.lon) +\n                                static_cast<double>(slope_vector.lat * rel_coordinate.lat);\n    // squared length of the slope vector\n    const auto squared_length = static_cast<double>(slope_vector.lon * slope_vector.lon) +\n                                static_cast<double>(slope_vector.lat * slope_vector.lat);\n\n    if (squared_length < std::numeric_limits<double>::epsilon())\n    {\n        return {0, source};\n    }\n\n    const double normed_ratio = unnormed_ratio / squared_length;\n    double clamped_ratio = normed_ratio;\n    if (clamped_ratio > 1.)\n    {\n        clamped_ratio = 1.;\n    }\n    else if (clamped_ratio < 0.)\n    {\n        clamped_ratio = 0.;\n    }\n\n    return {clamped_ratio,\n            {\n                FloatLongitude{1.0 - clamped_ratio} * source.lon +\n                    target.lon * FloatLongitude{clamped_ratio},\n                FloatLatitude{1.0 - clamped_ratio} * source.lat +\n                    target.lat * FloatLatitude{clamped_ratio},\n            }};\n}\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location,\n                             Coordinate &nearest_location,\n                             double &ratio);\n\nCoordinate centroid(const Coordinate lhs, const Coordinate rhs);\n\ndouble bearing(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// Get angle of line segment (A,C)->(C,B)\ndouble computeAngle(const Coordinate first, const Coordinate second, const Coordinate third);\n\n// find the center of a circle through three coordinates\nboost::optional<Coordinate> circleCenter(const Coordinate first_coordinate,\n                                         const Coordinate second_coordinate,\n                                         const Coordinate third_coordinate);\n\n// find the radius of a circle through three coordinates\ndouble circleRadius(const Coordinate first_coordinate,\n                    const Coordinate second_coordinate,\n                    const Coordinate third_coordinate);\n\n// factor in [0,1]. Returns point along the straight line between from and to. 0 returns from, 1\n// returns to\nCoordinate interpolateLinear(double factor, const Coordinate from, const Coordinate to);\n\n// compute the signed area of a triangle\ndouble signedArea(const Coordinate first_coordinate,\n                  const Coordinate second_coordinate,\n                  const Coordinate third_coordinate);\n\n// check if a set of three coordinates is given in CCW order\nbool isCCW(const Coordinate first_coordinate,\n           const Coordinate second_coordinate,\n           const Coordinate third_coordinate);\n\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n\n#endif // COORDINATE_CALCULATION\n", "meta": {"hexsha": "ab5fdad2c62b8100581b41662388b6b1bc5e7cf5", "size": 5459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/coordinate_calculation.hpp", "max_stars_repo_name": "edudude/osrm-backend", "max_stars_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/util/coordinate_calculation.hpp", "max_issues_repo_name": "edudude/osrm-backend", "max_issues_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util/coordinate_calculation.hpp", "max_forks_repo_name": "edudude/osrm-backend", "max_forks_repo_head_hexsha": "8bb183bc8cb2b69cdf861745580951ae3385e068", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T08:51:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T08:51:11.000Z", "avg_line_length": 37.9097222222, "max_line_length": 100, "alphanum_fraction": 0.6706356476, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5934336397763657}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <igl/read_triangle_mesh.h>\n#include <igl/write_triangle_mesh.h>\n#include <igl/writeOFF.h>\n#include <igl/per_vertex_normals.h>\n#include <igl/cotmatrix.h>\n#include <igl/cotmatrix_entries.h>\n#include <igl/adjacency_list.h>\n#include <igl/triangle_triangle_adjacency.h>\n#include <igl/barycenter.h>\n#include <igl/massmatrix.h>\n#include <igl/writeOBJ.h>\n#include <fstream>\n#include <cmath>\n#include <array>\n\nvoid findRotations(const Eigen::MatrixXd& N0,\n                   const Eigen::MatrixXd& N1,\n                   std::vector<Eigen::Matrix3d>& rot) {\n    \n    const auto n = N0.rows();\n    rot.resize(n);\n    \n    for(int i = 0; i < n; ++i) {\n        Eigen::Vector3d n1 = N0.row(i);\n        Eigen::Vector3d n2 = N1.row(i);\n        Eigen::Vector3d v = n1.cross(n2);\n        const double c = n1.dot(n2);\n        \n        if(c > -1 + 1e-8) {\n            const double coeff = 1 / (1 + c);\n            Eigen::Matrix3d v_x;\n            v_x << 0.0, -v(2), v(1), v(2), 0.0, -v(0), -v(1), v(0), 0.0;\n            rot[i] = Eigen::Matrix3d::Identity() + v_x + coeff * v_x * v_x;\n        } else{\n            rot[i] = -Eigen::Matrix3d::Identity();\n        }\n    }\n}\n\nstd::vector<std::vector<int>> collectNeighbours(const std::vector<std::vector<int>>& adj,\n                                                const Eigen::MatrixXd& V,\n                                                const Eigen::MatrixXd& N,\n                                                const double r,\n                                                const double nr) {\n    \n    std::vector<int> stack;\n    std::vector<int> flag(V.rows(), -1);\n    std::vector<std::vector<int>> result(V.rows());\n    const double normalConeThreshold = cos(nr * M_PI / 180.);\n    \n    for(int i = 0; i < V.rows(); ++i) {\n        \n        stack.push_back(i);\n        flag[i] = i;\n        \n        while(!stack.empty()) {\n            auto id = stack.back();\n            stack.pop_back();\n            \n            result[i].push_back(id);\n            \n            for (int j : adj[id]) {\n                if(flag[j] != i && (V.row(i) - V.row(j)).norm() < r && (N.row(i).dot(N.row(j))) > normalConeThreshold) {\n                    stack.push_back(j);\n                    flag[j] = i;\n                }\n            }\n        }\n    }\n    \n    return result;\n}\n\nvoid fitNormals(const std::vector<std::vector<int>>& nbh,\n                const Eigen::MatrixXd& V,\n                const Eigen::MatrixXd& N,\n                Eigen::MatrixXd& N2,\n                const double cosineThreshold,\n                const double sigma = 1.) {\n    \n    const auto nv = nbh.size();\n    N2.resize(nv, 3);\n    double angleThreshold = cosineThreshold * M_PI / 180.;\n    \n    for(int i = 0; i < nv; ++i) {\n        \n        const auto& nbi = nbh[i];\n        \n        Eigen::MatrixXd NN(nbi.size(), 3);\n        \n        for (int k = 0; k < nbi.size(); ++k) {\n            NN.row(k) = N.row(nbi[k]);\n        }\n        \n        Eigen::DiagonalMatrix<double, -1> W(nbi.size());\n        \n        if(sigma < 10.) {\n            for(int i = 0; i < W.diagonal().size(); ++i) {\n                double dot = NN.row(0).dot(NN.row(i));\n                if (dot >= 1.){\n                    W.diagonal()(i) = 1;\n                } else if(dot < 0) {\n                    W.diagonal()(i) = 0;\n                } else {\n                    W.diagonal()(i) = std::exp(-std::pow(acos(dot) / angleThreshold / sigma, 2));\n                }\n            }\n        } else {\n            W.diagonal().setOnes();\n        }\n        \n        Eigen::JacobiSVD<Eigen::Matrix3d> svd(NN.transpose() * W * NN, Eigen::ComputeFullV);\n        Eigen::Matrix3d frame = svd.matrixV();\n        N2.row(i) = (frame.leftCols(2) * frame.leftCols(2).transpose() * N.row(i).transpose()).normalized();\n    }\n}\n\nvoid assembleRHS(const Eigen::MatrixXd& C,\n                 const Eigen::MatrixXd& V,\n                 const Eigen::MatrixXi& F,\n                 const std::vector<Eigen::Matrix3d>& R,\n                 Eigen::MatrixXd& rhs) {\n    \n    const auto nv = V.rows();\n    rhs.resize(nv, 3);\n    rhs.setZero();\n    \n    for(int i = 0; i < F.rows(); ++i)  {\n        for(int j = 0; j < 3; ++j)  {\n            int v0 = F(i, (j + 1) % 3);\n            int v1 = F(i, (j + 2) % 3);\n            \n            Eigen::Vector3d b = C(i,j) * R[i] * (V.row(v0) - V.row(v1)).transpose();\n            rhs.row(v0) -= b.transpose();\n            rhs.row(v1) += b.transpose();\n        }\n    }\n}\n\nstd::vector<std::vector<int>> triangleAdjacency(const Eigen::MatrixXi& F, const size_t nv) {\n    \n    std::vector<std::vector<int>> vnbhs(nv);\n    const auto nf = F.rows();\n    \n    for(int i = 0; i < nf; ++i) {\n        for(int j = 0; j < 3; ++j) {\n            vnbhs[F(i, j)].push_back(i);\n        }\n    }\n    \n    std::vector<int> flags(nf, -1);\n    std::vector<std::vector<int>> ret(nf);\n    \n    for(int i = 0; i < nf; ++i) {\n        for(int j = 0; j < 3; ++j) {\n            for(int k : vnbhs[F(i, j)]) {\n                if(k != i && flags[k] != i) {\n                    ret[i].push_back(k);\n                    flags[k] = i;\n                }\n            }\n        }\n    }\n    \n    return ret;\n}\n\nvoid center(Eigen::MatrixXd& V) {\n    V.rowwise() -= V.colwise().mean();;\n    V /= 2. * V.rowwise().norm().maxCoeff();\n}\n\nvoid gaussThinning(const std::string &mesh_folder,\n                   const Eigen::MatrixXd &V_in,\n                   const Eigen::MatrixXi &F,\n                   Eigen::MatrixXd &V,\n                   const int number_iterations = 100,\n                   double minConeAngle = 2.5,\n                   double smooth = 1e-5,\n                   double start_angle = 25,\n                   double radius = 0.1,\n                   double sigma = 2.) {\n    \n    double coneAngle = start_angle;\n    double r = radius;\n    double eps = 1e-3;\n    \n    V = V_in;\n    const auto nv = V.rows();\n    center(V);\n    \n    igl::writeOFF(mesh_folder + \"/normalized.off\", V, F);\n    \n    Eigen::SparseMatrix<double> I(nv, nv);\n    I.setIdentity();\n    \n    Eigen::MatrixXi TT;\n    Eigen::MatrixXd B, b, C, N, N2;\n    std::vector<Eigen::Matrix3d> rot;\n    Eigen::SparseMatrix<double> L, M;\n    std::vector<std::vector<int>> nbhs;\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> chol;\n    \n    auto tt = triangleAdjacency(F, nv);\n    igl::triangle_triangle_adjacency(F, TT);\n    igl::cotmatrix_entries(V, F, C);\n    igl::cotmatrix(V, F, L);\n    igl::massmatrix(V, F, igl::MASSMATRIX_TYPE_BARYCENTRIC, M);\n    \n    if(smooth) {\n        chol.compute(-L + smooth * L.transpose() * L + eps * M);\n    } else {\n        chol.compute(-L + eps * M);\n    }\n    \n    for(int k = 0; k < number_iterations; ++k) {\n        \n        igl::per_face_normals(V, F, N);\n        igl::barycenter(V, F, B);\n            \n        nbhs = collectNeighbours(tt, B, N, r, coneAngle);\n        if(coneAngle > minConeAngle) coneAngle *= .95;\n\n        fitNormals(nbhs, V, N, N2, coneAngle, sigma);\n        findRotations(N, N2, rot);\n        assembleRHS(C, V, F, rot, b);\n        \n        V = chol.solve(eps * M * V - b);\n        \n        if (k % std::max(1, (number_iterations / 10)) == 0) {\n            std::cout << \"writing \" + mesh_folder + \": \" << k << \"\\n\";\n            igl::writeOFF(mesh_folder + \"/out\" + std::to_string(k) + \".off\", V, F);\n        }\n    }\n    \n    return;\n}\n\nvoid runExperiment(std::string folder, std::string inputFile, std::string outputFile, const int iters, const double minAngle, const double start_angle = 25, const double radius = 0.1, const double smooth = 1e-5) {\n    Eigen::MatrixXd V_in, V_out;\n    Eigen::MatrixXi F;\n    igl::read_triangle_mesh(folder + \"/\" + inputFile, V_in, F);\n    gaussThinning(folder, V_in, F, V_out, iters, minAngle, smooth, start_angle, radius);\n    igl::write_triangle_mesh(folder + \"/\" + outputFile, V_out, F);\n}\n\nint main(int argc, const char * argv[]) {\n    \n    \n    if(argc < 6) {\n        std::cout << \"Need input file, output file, output directory, number of iterations and minimum search cone. Running default experiments...\" << std::endl;\n       \n        /* run default experiments here .... */\n        runExperiment(\"./examples/architecture\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/boat\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/bumpy\", \"input.off\", \"out.obj\", 150, 7.5);\n        \n        runExperiment(\"./examples/bunny\", \"input.off\", \"out.obj\", 500, 2.5);\n\n        runExperiment(\"./examples/bunny_high\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/bunny_small\", \"input.off\", \"out.obj\", 500, 5.0);\n\n        runExperiment(\"./examples/coffee\", \"input.off\", \"out.obj\", 500, 2.5);\n\n        runExperiment(\"./examples/cone\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/cone_high\", \"input.off\", \"out.obj\", 100, 2.5, 25, 0.015);\n\n        runExperiment(\"./examples/curved_fold\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/cylinder\", \"input.off\", \"out.obj\", 300, 7.5);\n\n        runExperiment(\"./examples/dog\", \"input.off\", \"out.obj\", 100, 5.0);\n\n        runExperiment(\"./examples/dome\", \"input.off\", \"out.obj\", 100, 7.5);\n\n        runExperiment(\"./examples/dress_high\", \"input.off\", \"out.obj\", 100, 7.5);\n\n        runExperiment(\"./examples/drill\", \"input.off\", \"out.obj\", 100, 7.5);\n\n        runExperiment(\"./examples/einstein\", \"input.off\", \"out.obj\", 300, 7.5, 60, 0.015);\n\n        runExperiment(\"./examples/face\", \"input.off\", \"out.obj\", 100, 5.0);\n\n        runExperiment(\"./examples/fandisk\", \"input.off\", \"out.obj\", 1000, 5.0);\n\n        runExperiment(\"./examples/fertility\", \"input.off\", \"out.obj\", 100, 7.5);\n\n        runExperiment(\"./examples/guitar\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/lilium\", \"input.off\", \"out.obj\", 100, 5.0);\n\n        runExperiment(\"./examples/mask\", \"input.off\", \"out.obj\", 500, 2.5);\n\n        runExperiment(\"./examples/nut\", \"input.off\", \"out.obj\", 100, 2.5);\n\n        runExperiment(\"./examples/swing\", \"input.off\", \"out.obj\", 500, 5.0);\n    } else\n    {\n        std::string  infile = argv[1];\n        std::string  outfile = argv[2];\n        std::string  folder = argv[3];\n        \n        auto numIters = std::atoi(argv[4]);\n        auto minAngle = std::stold(argv[5]);\n        \n        std::cout << \"Processing \" << infile << \" with \" << numIters << \" iterations and mimimum cone angle \" << minAngle << \". Output directory is \" << folder << std::endl;\n       \n        runExperiment(folder, infile, outfile, numIters, minAngle);\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "492052f6275981ba39033ccfd3e666af95a76f87", "size": 10589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "PhHerholz/GaussImageThinning", "max_stars_repo_head_hexsha": "987e429f59d37badfc02db3bec21790b97a19507", "max_stars_repo_licenses": ["MIT"], "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": "PhHerholz/GaussImageThinning", "max_issues_repo_head_hexsha": "987e429f59d37badfc02db3bec21790b97a19507", "max_issues_repo_licenses": ["MIT"], "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": "PhHerholz/GaussImageThinning", "max_forks_repo_head_hexsha": "987e429f59d37badfc02db3bec21790b97a19507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-28T23:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:57:21.000Z", "avg_line_length": 33.1943573668, "max_line_length": 213, "alphanum_fraction": 0.507035603, "num_tokens": 2994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5933279701396138}}
{"text": "#include \"segmatch/descriptors/eigenvalue_based.hpp\"\n\n#include <cfenv>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <glog/logging.h>\n#include <pcl/common/common.h>\n\n#pragma STDC FENV_ACCESS on\n\nnamespace segmatch {\n\n/// \\brief Utility function for swapping two values.\ntemplate<typename T>\nbool swap_if_gt(T& a, T& b) {\n  if (a > b) {\n    std::swap(a, b);\n    return true;\n  }\n  return false;\n}\n\n// EigenvalueBasedDescriptor methods definition\nEigenvalueBasedDescriptor::EigenvalueBasedDescriptor(const DescriptorsParameters& parameters) {}\n\nvoid EigenvalueBasedDescriptor::describe(const Segment& segment, Features* features) {\n  CHECK_NOTNULL(features);\n  std::feclearexcept(FE_ALL_EXCEPT);\n\n  // Find the variances.\n  const size_t kNPoints = segment.point_cloud.points.size();\n  PointCloud variances;\n  for (size_t i = 0u; i < kNPoints; ++i) {\n    variances.push_back(PclPoint());\n    variances.points[i].x = segment.point_cloud.points[i].x - segment.centroid.x;\n    variances.points[i].y = segment.point_cloud.points[i].y - segment.centroid.y;\n    variances.points[i].z = segment.point_cloud.points[i].z - segment.centroid.z;\n  }\n\n  // Find the covariance matrix. Since it is symmetric, we only bother with the upper diagonal.\n  const std::vector<size_t> row_indices_to_access = {0,0,0,1,1,2};\n  const std::vector<size_t> col_indices_to_access = {0,1,2,1,2,2};\n  Eigen::Matrix3f covariance_matrix;\n  for (size_t i = 0u; i < row_indices_to_access.size(); ++i) {\n    const size_t row = row_indices_to_access[i];\n    const size_t col = col_indices_to_access[i];\n    double covariance = 0;\n    for (size_t k = 0u; k < kNPoints; ++k) {\n      covariance += variances.points[k].data[row] * variances.points[k].data[col];\n    }\n    covariance /= kNPoints;\n    covariance_matrix(row,col) = covariance;\n    covariance_matrix(col,row) = covariance;\n  }\n\n  // Compute eigenvalues of covariance matrix.\n  constexpr bool compute_eigenvectors = false;\n  Eigen::EigenSolver<Eigen::Matrix3f> eigenvalues_solver(covariance_matrix, compute_eigenvectors);\n  std::vector<float> eigenvalues(3, 0.0);\n  eigenvalues.at(0) = eigenvalues_solver.eigenvalues()[0].real();\n  eigenvalues.at(1) = eigenvalues_solver.eigenvalues()[1].real();\n  eigenvalues.at(2) = eigenvalues_solver.eigenvalues()[2].real();\n  if (eigenvalues_solver.eigenvalues()[0].imag() != 0.0 ||\n      eigenvalues_solver.eigenvalues()[1].imag() != 0.0 ||\n      eigenvalues_solver.eigenvalues()[2].imag() != 0.0 ) {\n    LOG(ERROR) << \"Eigenvalues should not have non-zero imaginary component.\";\n  }\n\n  // Sort eigenvalues from smallest to largest.\n  swap_if_gt(eigenvalues.at(0), eigenvalues.at(1));\n  swap_if_gt(eigenvalues.at(0), eigenvalues.at(2));\n  swap_if_gt(eigenvalues.at(1), eigenvalues.at(2));\n\n  // Normalize eigenvalues.\n  double sum_eigenvalues = eigenvalues.at(0) + eigenvalues.at(1) + eigenvalues.at(2);\n  double e1 = eigenvalues.at(0) / sum_eigenvalues;\n  double e2 = eigenvalues.at(1) / sum_eigenvalues;\n  double e3 = eigenvalues.at(2) / sum_eigenvalues;\n  LOG_IF(ERROR, e1 == e2 || e2 == e3 || e1 == e3) << \"Eigenvalues should not be equal.\";\n\n  // Store inside features.\n  const double sum_of_eigenvalues = e1 + e2 + e3;\n  constexpr double kOneThird = 1.0/3.0;\n  CHECK_NE(e1, 0.0);\n  CHECK_NE(sum_of_eigenvalues, 0.0);\n\n  const double kNormalizationPercentile = 1.0;\n\n  const double kLinearityMax = 28890.9 * kNormalizationPercentile;\n  const double kPlanarityMax = 95919.2 * kNormalizationPercentile;\n  const double kScatteringMax = 124811 * kNormalizationPercentile;\n  const double kOmnivarianceMax = 0.278636 * kNormalizationPercentile;\n  const double kAnisotropyMax = 124810 * kNormalizationPercentile;\n  const double kEigenEntropyMax = 0.956129 * kNormalizationPercentile;\n  const double kChangeOfCurvatureMax = 0.99702 * kNormalizationPercentile;\n\n  const double kNPointsMax = 13200 * kNormalizationPercentile;\n\n  Feature eigenvalue_feature;\n  eigenvalue_feature.push_back(FeatureValue(\"linearity\", (e1 - e2) / e1 / kLinearityMax));\n  eigenvalue_feature.push_back(FeatureValue(\"planarity\", (e2 - e3) / e1 / kPlanarityMax));\n  eigenvalue_feature.push_back(FeatureValue(\"scattering\", e3 / e1 / kScatteringMax));\n  eigenvalue_feature.push_back(FeatureValue(\"omnivariance\", std::pow(e1 * e2 * e3, kOneThird) / kOmnivarianceMax));\n  eigenvalue_feature.push_back(FeatureValue(\"anisotropy\", (e1 - e3) / e1 / kAnisotropyMax));\n  eigenvalue_feature.push_back(FeatureValue(\"eigen_entropy\",\n                                            (e1 * std::log(e1)) + (e2 * std::log(e2)) + (e3 * std::log(e3)) / kEigenEntropyMax));\n  eigenvalue_feature.push_back(FeatureValue(\"change_of_curvature\", e3 / sum_of_eigenvalues / kChangeOfCurvatureMax));\n\n  PointI point_min, point_max;\n\n  pcl::getMinMax3D(segment.point_cloud, point_min, point_max);\n\n  double diff_x, diff_y, diff_z;\n\n  diff_x = point_max.x - point_min.x;\n  diff_y = point_max.y - point_min.y;\n  diff_z = point_max.z - point_min.z;\n\n  if (diff_z < diff_x && diff_z < diff_y) {\n    eigenvalue_feature.push_back(FeatureValue(\"pointing_up\", 0.2));\n  } else {\n    eigenvalue_feature.push_back(FeatureValue(\"pointing_up\", 0.0));\n  }\n\n  // eigenvalue_feature.push_back(FeatureValue(\"n_points\", kNPoints / kNPointsMax));\n\n  CHECK_EQ(eigenvalue_feature.size(), kDimension) << \"Feature has the wrong dimension\";\n  features->push_back(eigenvalue_feature);\n\n  // Check that there were no overflows, underflows, or invalid float operations.\n  if (std::fetestexcept(FE_OVERFLOW)) {\n    LOG(ERROR) << \"Overflow error in eigenvalue feature computation.\";\n  } else if (std::fetestexcept(FE_UNDERFLOW)) {\n    LOG(ERROR) << \"Underflow error in eigenvalue feature computation.\";\n  } else if (std::fetestexcept(FE_INVALID)) {\n    LOG(ERROR) << \"Invalid Flag error in eigenvalue feature computation.\";\n  } else if (std::fetestexcept(FE_DIVBYZERO)) {\n    LOG(ERROR) << \"Divide by zero error in eigenvalue feature computation.\";\n  }\n}\n\n} // namespace segmatch\n", "meta": {"hexsha": "0fcef7fef2c009cc7e08e0928c263cfae179abec", "size": 5961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "segmatch/src/descriptors/eigenvalue_based.cpp", "max_stars_repo_name": "shibowing/segmatch", "max_stars_repo_head_hexsha": "4c93c465108f0a6e103526486aae894ea3d2ae9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T12:02:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T01:04:49.000Z", "max_issues_repo_path": "segmatch/src/descriptors/eigenvalue_based.cpp", "max_issues_repo_name": "yuekaka/segmatch", "max_issues_repo_head_hexsha": "c662324d23b9e049fbb49b52cda7895d1a4d2798", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-03T01:50:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-19T08:06:41.000Z", "max_forks_repo_path": "segmatch/src/descriptors/eigenvalue_based.cpp", "max_forks_repo_name": "yuekaka/segmatch", "max_forks_repo_head_hexsha": "c662324d23b9e049fbb49b52cda7895d1a4d2798", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T19:40:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-15T17:43:06.000Z", "avg_line_length": 41.3958333333, "max_line_length": 129, "alphanum_fraction": 0.7218587485, "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5932492886977911}}
{"text": "#pragma once\n#include <cmath>\n#include\"cnpy.h\"\n\n\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n    namespace detail{\n        template< typename Value, class Iterator1 >\n        inline Value norm_l2(Iterator1 first1, Iterator1 last1, Value init, size_t n)\n        {\n            using std::max;\n            using std::abs;\n            for (; first1 != last1; first1++)\n                init += std::pow(*first1, 2);\n            return std::sqrt(init / n);\n        }\n    }\n    template< typename S >\n    static typename norm_result_type<S>::type norm_l2(const S& s)\n    {\n        size_t n = boost::size(s);\n        return detail::norm_l2(boost::begin(s), boost::end(s),\n            static_cast<typename norm_result_type<S>::type>(0), n);\n    }\n\n    template< class Fac1 = double >\n    struct rel_error\n    {\n        const Fac1 m_eps_abs, m_eps_rel, m_a_x;\n\n        rel_error(Fac1 eps_abs, Fac1 eps_rel, Fac1 a_x)\n            : m_eps_abs(eps_abs), m_eps_rel(eps_rel), m_a_x(a_x) { }\n\n\n        template< class T1, class T2, class T3 >\n        void operator()(T3& t3, const T1& t1, const T2& t2) const\n        {\n            using std::abs;\n            set_unit_value(t3, abs(get_unit_value(t3)) / (m_eps_abs + m_eps_rel * (m_a_x * std::max(abs(get_unit_value(t1)), abs(get_unit_value(t2))) )));\n        }\n\n        typedef void result_type;\n    };\n\n    double scale_norm(const std::vector<double>& y, const std::vector<double>& scale) {\n        size_t n = boost::size(y);\n        double _norm = 0.0;\n        for (int i = 0; i < n; i++) {\n            _norm += std::pow(y[i] / scale[i], 2.0);\n        }\n        _norm = sqrt(_norm / n);\n        return _norm;\n    }\n    /*\n    template<class value_type, class State>\n    value_type scale_norm(State& y, State& scale) {\n        value_type _norm = 0.0;\n        detail::for_each2(boost::begin(y), boost::end(y),\n            boost::begin(scale), [](auto& y_i, auto& scale_i) { _norm += y_i / scale_i });\n    }\n    */\n    template< class Fac1 = double >\n    struct custom_scale_sum\n    {\n        const Fac1 m_alpha1, m_alpha2;\n\n        custom_scale_sum(Fac1 alpha1, Fac1 alpha2) : m_alpha1(alpha1), m_alpha2(alpha2) { }\n\n        template< class T1, class T2 >\n        void operator()(T1& t1, const T2& t2) const\n        {\n            t1 = m_alpha1 * std::abs(t2) + m_alpha2;\n        }\n\n        typedef void result_type;\n    };\n\n    template<class value_type, class System, class State>\n    value_type select_initial_step(System fun, value_type t0, State& y0, size_t order, value_type rtol, value_type atol) {\n        // create local State to hold values\n        state_wrapper< State > f0, f1, scale, tmp_err;\n        range_algebra algebra;\n        // resize it\n        adjust_size_by_resizeability(scale, y0, typename is_resizeable<State>::type());\n        adjust_size_by_resizeability(tmp_err, y0, typename is_resizeable<State>::type());\n        adjust_size_by_resizeability(f0, y0, typename is_resizeable<State>::type());\n        adjust_size_by_resizeability(f1, y0, typename is_resizeable<State>::type());\n        // compute f0\n        fun(y0, f0.m_v, t0);\n        // using for_each to compute the scale vector\n        algebra.for_each2(scale.m_v, y0,\n            custom_scale_sum< value_type >(rtol, atol));\n        // compute d0, d1\n        value_type d0 = scale_norm(y0, scale.m_v);\n        value_type d1 = scale_norm(f0.m_v, scale.m_v);\n        // h0\n        value_type h0 = 0.01 * d0 / d1;\n        if (d0 < 1e-5 || d1 < 1e-5) {\n            h0 = 1e-6;\n        }\n        algebra.for_each3(tmp_err.m_v, y0, f0.m_v,\n            default_operations::scale_sum2< value_type >(1.0, h0));\n        // tmp_err.m_v becomes y1 now\n        State& y1 = tmp_err.m_v;\n        // compute f1\n        fun(y1, f1.m_v, t0 + h0);\n        algebra.for_each3(tmp_err.m_v, f1.m_v, f0.m_v,\n            default_operations::scale_sum2< value_type >(1.0, -1.0));\n        value_type d2 = scale_norm(tmp_err.m_v, scale.m_v) / h0;\n        value_type h1;\n        if (d1 <= 1e-15 || d2 <= 1e-15) {\n            h1 = std::max(1e-6, h0 * 1e-3);\n        }\n        else {\n            h1 = std::pow(0.01 / std::max(d1, d2), 1.0 / (order + 1));\n        }\n        return std::min(100 * h0, h1);\n    }\n\ntemplate\n    <\n    class Value,\n    class Algebra,\n    class Operations\n    >\n    class custom_error_checker\n{\npublic:\n\n    typedef Value value_type;\n    typedef Algebra algebra_type;\n    typedef Operations operations_type;\n\n    custom_error_checker(\n        value_type eps_abs = static_cast<value_type>(1.0e-6),\n        value_type eps_rel = static_cast<value_type>(1.0e-6),\n        value_type a_x = static_cast<value_type>(1),\n        value_type a_dxdt = static_cast<value_type>(1))\n        : m_eps_abs(eps_abs), m_eps_rel(eps_rel), m_a_x(a_x), m_a_dxdt(a_dxdt)\n    { }\n\n\n    template< class State, class Deriv, class Err, class Time >\n    value_type error(const State& x_old, const Deriv& dxdt_old, Err& x_err, Time dt) const\n    {\n        return error(algebra_type(), x_old, dxdt_old, x_err, dt);\n    }\n\n    template< class State, class Deriv, class Err, class Time >\n    value_type error(algebra_type& algebra, const State& x_old, const Deriv& dxdt_old, Err& x_err, Time dt) const\n    {\n        using std::abs;\n        // this overwrites x_err !\n        algebra.for_each3(x_err, x_old, dxdt_old,\n            rel_error< value_type >(m_eps_abs, m_eps_rel, m_a_x));\n\n        // value_type res = algebra.reduce( x_err ,\n        //        typename operations_type::template maximum< value_type >() , static_cast< value_type >( 0 ) );\n        return norm_l2(x_err);\n    }\n    double eps_abs() {\n        return m_eps_abs;\n    }\nprivate:\n\n    value_type m_eps_abs;\n    value_type m_eps_rel;\n    value_type m_a_x;\n    value_type m_a_dxdt;\n\n};\n\n// standard IController\ntemplate< typename Value, typename Time >\nclass custom_step_adjuster\n{\npublic:\n    typedef Time time_type;\n    typedef Value value_type;\n\n    custom_step_adjuster(const time_type max_dt=static_cast<time_type>(0))\n            : m_max_dt(max_dt)\n    {}\n\n\n    time_type decrease_step(time_type dt, const value_type error, const int stepper_order) const\n    {\n        // returns the decreased time step\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n\n        dt *= max\n        BOOST_PREVENT_MACRO_SUBSTITUTION(\n                static_cast<value_type>( static_cast<value_type>(9) / static_cast<value_type>(10) *\n                                         pow(error, static_cast<value_type>(-1) / (stepper_order))),\n                static_cast<value_type>( static_cast<value_type>(1) / static_cast<value_type> (5)));\n        if(m_max_dt != static_cast<time_type >(0))\n            // limit to maximal stepsize even when decreasing\n            dt = detail::min_abs(dt, m_max_dt);\n        return dt;\n    }\n\n    time_type adjust_step(time_type dt, value_type error, const int stepper_order) const\n    {\n        // returns the increased time step\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        using std::pow;\n        time_type factor;\n        factor = max\n            BOOST_PREVENT_MACRO_SUBSTITUTION(\n                static_cast<value_type>(static_cast<value_type>(9) / static_cast<value_type>(10) *\n                    pow(error, static_cast<value_type>(-1) / (stepper_order))),\n                static_cast<value_type>(static_cast<value_type>(1) / static_cast<value_type> (5)));\n        factor = std::min(factor, 10.0);\n        dt *= factor;\n        if (m_max_dt != static_cast<time_type>(0))\n            // limit to maximal stepsize even when decreasing\n            dt = detail::min_abs(dt, m_max_dt);\n        return dt;\n    }\n\n    bool check_step_size_limit(const time_type dt)\n    {\n        if(m_max_dt != static_cast<time_type >(0))\n            return detail::less_eq_with_sign(dt, m_max_dt, dt);\n        return true;\n    }\n\n    time_type get_max_dt() { return m_max_dt; }\n\nprotected:\n    time_type m_max_dt;\n};\n\n// only support FSAL\ntemplate<\n    class ErrorStepper,\n    class ErrorChecker = default_error_checker< typename ErrorStepper::value_type,\n    typename ErrorStepper::algebra_type,\n    typename ErrorStepper::operations_type >,\n    class StepAdjuster = default_step_adjuster< typename ErrorStepper::value_type,\n    typename ErrorStepper::time_type >,\n    class Resizer = typename ErrorStepper::resizer_type,\n    class ErrorStepperCategory = typename ErrorStepper::stepper_category\n>\nclass custom_controlled_runge_kutta;\n\ntemplate<\n    class ErrorStepper,\n    class ErrorChecker,\n    class StepAdjuster,\n    class Resizer\n>\nclass custom_controlled_runge_kutta< ErrorStepper, ErrorChecker, StepAdjuster, Resizer, explicit_error_stepper_fsal_tag >\n{\n\npublic:\n\n    typedef ErrorStepper stepper_type;\n    typedef typename stepper_type::state_type state_type;\n    typedef typename stepper_type::value_type value_type;\n    typedef typename stepper_type::deriv_type deriv_type;\n    typedef typename stepper_type::time_type time_type;\n    typedef typename stepper_type::algebra_type algebra_type;\n    typedef typename stepper_type::operations_type operations_type;\n    typedef Resizer resizer_type;\n    typedef ErrorChecker error_checker_type;\n    typedef StepAdjuster step_adjuster_type;\n    typedef explicit_controlled_stepper_fsal_tag stepper_category;\n\n#ifndef DOXYGEN_SKIP\n    typedef typename stepper_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_type::wrapped_deriv_type wrapped_deriv_type;\n\n    typedef custom_controlled_runge_kutta< ErrorStepper, ErrorChecker, StepAdjuster, Resizer, explicit_error_stepper_tag > controlled_stepper_type;\n#endif // DOXYGEN_SKIP\n\n    /**\n     * \\brief Constructs the controlled Runge-Kutta stepper.\n     * \\param error_checker An instance of the error checker.\n     * \\param stepper An instance of the underlying stepper.\n     */\n    custom_controlled_runge_kutta(\n        const error_checker_type& error_checker = error_checker_type(),\n        const step_adjuster_type& step_adjuster = step_adjuster_type(),\n        const stepper_type& stepper = stepper_type(),\n        std::string model_file_name = \"\",\n        bool is_fixed_stepsize = false\n    )\n        : m_stepper(stepper), m_error_checker(error_checker), m_step_adjuster(step_adjuster),\n        m_first_call(true), fixed_stepsize(is_fixed_stepsize)\n    {\n        m_use_nn = !(model_file_name == \"\");\n        if (m_use_nn) {\n            // construct W1, b1, W2, b2\n            cnpy::npz_t _npz = cnpy::npz_load(model_file_name);\n            size_t w1_size = _npz[\"W1\"].shape[0];\n            hidden_num = _npz[\"b1\"].shape[0];\n            double* _W1 = _npz[\"W1\"].data<double>();\n            double* _W2 = _npz[\"W2\"].data<double>();\n            double* _b1 = _npz[\"b1\"].data<double>();\n            b2 = *_npz[\"b2\"].data<double>();\n            if (_npz.count(\"k\") > 0) {\n                k = *_npz[\"k\"].data<double>();\n            }\n            else {\n                k = -1.0;\n            }\n\n            std::copy(_W1, _W1 + w1_size, back_inserter(W1));\n            std::copy(_W2, _W2 + hidden_num, back_inserter(W2));\n            std::copy(_b1, _b1 + hidden_num, back_inserter(b1));\n\n            tmp_vec.resize(hidden_num);\n        }\n    }\n\n    /*\n     * Version 1 : try_step( sys , x , t , dt )\n     *\n     * The two overloads are needed in order to solve the forwarding problem\n     */\n     /**\n      * \\brief Tries to perform one step.\n      *\n      * This method tries to do one step with step size dt. If the error estimate\n      * is to large, the step is rejected and the method returns fail and the\n      * step size dt is reduced. If the error estimate is acceptably small, the\n      * step is performed, success is returned and dt might be increased to make\n      * the steps as large as possible. This method also updates t if a step is\n      * performed.\n      *\n      * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n      *               Simple System concept.\n      * \\param x The state of the ODE which should be solved. Overwritten if\n      * the step is successful.\n      * \\param t The value of the time. Updated if the step is successful.\n      * \\param dt The step size. Updated.\n      * \\return success if the step was accepted, fail otherwise.\n      */\n    template< class System, class StateInOut >\n    controlled_step_result try_step(System system, StateInOut& x, time_type& t, time_type& dt)\n    {\n        return try_step_v1(system, x, t, dt);\n    }\n\n\n    /**\n     * \\brief Tries to perform one step. Solves the forwarding problem and\n     * allows for using boost range as state_type.\n     *\n     * This method tries to do one step with step size dt. If the error estimate\n     * is to large, the step is rejected and the method returns fail and the\n     * step size dt is reduced. If the error estimate is acceptably small, the\n     * step is performed, success is returned and dt might be increased to make\n     * the steps as large as possible. This method also updates t if a step is\n     * performed.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The state of the ODE which should be solved. Overwritten if\n     * the step is successful. Can be a boost range.\n     * \\param t The value of the time. Updated if the step is successful.\n     * \\param dt The step size. Updated.\n     * \\return success if the step was accepted, fail otherwise.\n     */\n    template< class System, class StateInOut >\n    controlled_step_result try_step(System system, const StateInOut& x, time_type& t, time_type& dt)\n    {\n        return try_step_v1(system, x, t, dt);\n    }\n\n\n\n    /*\n     * Version 2 : try_step( sys , in , t , out , dt );\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     *\n     * The disabler is needed to solve ambiguous overloads\n     */\n     /**\n      * \\brief Tries to perform one step.\n      *\n      * \\note This method is disabled if state_type=time_type to avoid ambiguity.\n      *\n      * This method tries to do one step with step size dt. If the error estimate\n      * is to large, the step is rejected and the method returns fail and the\n      * step size dt is reduced. If the error estimate is acceptably small, the\n      * step is performed, success is returned and dt might be increased to make\n      * the steps as large as possible. This method also updates t if a step is\n      * performed.\n      *\n      * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n      *               Simple System concept.\n      * \\param in The state of the ODE which should be solved.\n      * \\param t The value of the time. Updated if the step is successful.\n      * \\param out Used to store the result of the step.\n      * \\param dt The step size. Updated.\n      * \\return success if the step was accepted, fail otherwise.\n      */\n    template< class System, class StateIn, class StateOut >\n    typename boost::disable_if< boost::is_same< StateIn, time_type >, controlled_step_result >::type\n        try_step(System system, const StateIn& in, time_type& t, StateOut& out, time_type& dt)\n    {\n        if (m_dxdt_resizer.adjust_size(in, detail::bind(&custom_controlled_runge_kutta::template resize_m_dxdt_impl< StateIn >, detail::ref(*this), detail::_1)) || m_first_call)\n        {\n            initialize(system, in, t);\n        }\n        return try_step(system, in, m_dxdt.m_v, t, out, dt);\n    }\n\n\n    /*\n     * Version 3 : try_step( sys , x , dxdt , t , dt )\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     */\n     /**\n      * \\brief Tries to perform one step.\n      *\n      * This method tries to do one step with step size dt. If the error estimate\n      * is to large, the step is rejected and the method returns fail and the\n      * step size dt is reduced. If the error estimate is acceptably small, the\n      * step is performed, success is returned and dt might be increased to make\n      * the steps as large as possible. This method also updates t if a step is\n      * performed.\n      *\n      * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n      *               Simple System concept.\n      * \\param x The state of the ODE which should be solved. Overwritten if\n      * the step is successful.\n      * \\param dxdt The derivative of state.\n      * \\param t The value of the time. Updated if the step is successful.\n      * \\param dt The step size. Updated.\n      * \\return success if the step was accepted, fail otherwise.\n      */\n    template< class System, class StateInOut, class DerivInOut >\n    controlled_step_result try_step(System system, StateInOut& x, DerivInOut& dxdt, time_type& t, time_type& dt)\n    {\n        m_xnew_resizer.adjust_size(x, detail::bind(&custom_controlled_runge_kutta::template resize_m_xnew_impl< StateInOut >, detail::ref(*this), detail::_1));\n        m_dxdt_new_resizer.adjust_size(x, detail::bind(&custom_controlled_runge_kutta::template resize_m_dxdt_new_impl< StateInOut >, detail::ref(*this), detail::_1));\n        controlled_step_result res = try_step(system, x, dxdt, t, m_xnew.m_v, m_dxdtnew.m_v, dt);\n        if (res == success)\n        {\n            boost::numeric::odeint::copy(m_xnew.m_v, x);\n            boost::numeric::odeint::copy(m_dxdtnew.m_v, dxdt);\n        }\n        return res;\n    }\n\n\n    /*\n     * Version 4 : try_step( sys , in , dxdt_in , t , out , dxdt_out , dt )\n     *\n     * This version does not solve the forwarding problem, boost::range can not be used.\n     */\n     /**\n      * \\brief Tries to perform one step.\n      *\n      * This method tries to do one step with step size dt. If the error estimate\n      * is to large, the step is rejected and the method returns fail and the\n      * step size dt is reduced. If the error estimate is acceptably small, the\n      * step is performed, success is returned and dt might be increased to make\n      * the steps as large as possible. This method also updates t if a step is\n      * performed.\n      *\n      * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n      *               Simple System concept.\n      * \\param in The state of the ODE which should be solved.\n      * \\param dxdt The derivative of state.\n      * \\param t The value of the time. Updated if the step is successful.\n      * \\param out Used to store the result of the step.\n      * \\param dt The step size. Updated.\n      * \\return success if the step was accepted, fail otherwise.\n      */\n    template< class System, class StateIn, class DerivIn, class StateOut, class DerivOut >\n    controlled_step_result try_step(System system, const StateIn& in, const DerivIn& dxdt_in, time_type& t,\n        StateOut& out, DerivOut& dxdt_out, time_type& dt)\n    {\n        unwrapped_step_adjuster& step_adjuster = m_step_adjuster;\n        if (!step_adjuster.check_step_size_limit(dt))\n        {\n            // given dt was above step size limit - adjust and return fail;\n            dt = step_adjuster.get_max_dt();\n            return fail;\n        }\n        value_type max_rel_err;\n        time_type dt_tmp;\n        if (!m_use_nn && !fixed_stepsize) {\n            m_xerr_resizer.adjust_size(in, detail::bind(&custom_controlled_runge_kutta::template resize_m_xerr_impl< StateIn >, detail::ref(*this), detail::_1));\n\n            //fsal: m_stepper.get_dxdt( dxdt );\n            //fsal: m_stepper.do_step( sys , x , dxdt , t , dt , m_x_err );\n            m_stepper.do_step(system, in, dxdt_in, t, out, dxdt_out, dt, m_xerr.m_v);\n\n            // this potentially overwrites m_x_err! (standard_error_checker does, at least)\n            max_rel_err = m_error_checker.error(m_stepper.algebra(), in, out, m_xerr.m_v, dt);\n\n            if (max_rel_err > 1.0)\n            {\n                // error too big, decrease step size and reject this step\n                dt = step_adjuster.adjust_step(dt, max_rel_err, m_stepper.stepper_order());\n                return fail;\n            }\n        }\n        else if(!fixed_stepsize) {\n\n            input_vec[0] = t;\n            for (int i = 1; i <= in.size(); i++)\n                input_vec[i] = in[i - 1];\n            \n\n            dt_tmp = 0;\n            // computation\n            for (int i = 0; i < hidden_num; i++) {\n                for (int j = 0; j < m; j++) {\n                    tmp_vec[i] += W1[i * m + j] * input_vec[j];\n                }\n                tmp_vec[i] += b1[i];\n                tmp_vec[i] = std::max(0.0, tmp_vec[i]);\n            }\n            for (int i = 0; i < hidden_num; i++) {\n                dt_tmp += tmp_vec[i] * W2[i];\n                tmp_vec[i] = 0;\n            }\n            dt_tmp += b2;\n            if (k > 0) {\n                dt_tmp += k * std::log(m_error_checker.eps_abs());\n            }\n            dt = std::exp(dt_tmp);\n            m_stepper.do_step(system, in, dxdt_in, t, out, dxdt_out, dt);\n\n        }\n        else {\n            m_stepper.do_step(system, in, dxdt_in, t, out, dxdt_out, dt);\n        }\n        // otherwise, increase step size and accept\n        t += dt;\n        if (!m_use_nn && !fixed_stepsize) {\n            dt = step_adjuster.adjust_step(dt, max_rel_err, m_stepper.stepper_order());\n        }\n        return success;\n    }\n\n\n    /**\n     * \\brief Resets the internal state of the underlying FSAL stepper.\n     */\n    void reset(void)\n    {\n        m_first_call = true;\n    }\n\n    /**\n     * \\brief Initializes the internal state storing an internal copy of the derivative.\n     *\n     * \\param deriv The initial derivative of the ODE.\n     */\n    template< class DerivIn >\n    void initialize(const DerivIn& deriv)\n    {\n        boost::numeric::odeint::copy(deriv, m_dxdt.m_v);\n        m_first_call = false;\n    }\n\n    /**\n     * \\brief Initializes the internal state storing an internal copy of the derivative.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param x The initial state of the ODE which should be solved.\n     * \\param t The initial time.\n     */\n    template< class System, class StateIn >\n    void initialize(System system, const StateIn& x, time_type t)\n    {\n        typename odeint::unwrap_reference< System >::type& sys = system;\n        sys(x, m_dxdt.m_v, t);\n        size_t n = boost::size(x);\n        if (k < 0) {\n            m = n + 2;\n        }\n        else {\n            m = n + 1;\n        }\n        input_vec.resize(m);\n        if (k < 0) {\n            input_vec[m - 1] = std::log(m_error_checker.eps_abs());\n        }\n        m_first_call = false;\n    }\n\n    /**\n     * \\brief Returns true if the stepper has been initialized, false otherwise.\n     *\n     * \\return true, if the stepper has been initialized, false otherwise.\n     */\n    bool is_initialized(void) const\n    {\n        return !m_first_call;\n    }\n\n\n    /**\n     * \\brief Adjust the size of all temporaries in the stepper manually.\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\n     */\n    template< class StateType >\n    void adjust_size(const StateType& x)\n    {\n        resize_m_xerr_impl(x);\n        resize_m_dxdt_impl(x);\n        resize_m_dxdt_new_impl(x);\n        resize_m_xnew_impl(x);\n    }\n\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    stepper_type& stepper(void)\n    {\n        return m_stepper;\n    }\n\n    /**\n     * \\brief Returns the instance of the underlying stepper.\n     * \\returns The instance of the underlying stepper.\n     */\n    const stepper_type& stepper(void) const\n    {\n        return m_stepper;\n    }\n\n\n\nprivate:\n\n\n    template< class StateIn >\n    bool resize_m_xerr_impl(const StateIn& x)\n    {\n        return adjust_size_by_resizeability(m_xerr, x, typename is_resizeable<state_type>::type());\n    }\n\n    template< class StateIn >\n    bool resize_m_dxdt_impl(const StateIn& x)\n    {\n        return adjust_size_by_resizeability(m_dxdt, x, typename is_resizeable<deriv_type>::type());\n    }\n\n    template< class StateIn >\n    bool resize_m_dxdt_new_impl(const StateIn& x)\n    {\n        return adjust_size_by_resizeability(m_dxdtnew, x, typename is_resizeable<deriv_type>::type());\n    }\n\n    template< class StateIn >\n    bool resize_m_xnew_impl(const StateIn& x)\n    {\n        return adjust_size_by_resizeability(m_xnew, x, typename is_resizeable<state_type>::type());\n    }\n\n\n    template< class System, class StateInOut >\n    controlled_step_result try_step_v1(System system, StateInOut& x, time_type& t, time_type& dt)\n    {\n        if (m_dxdt_resizer.adjust_size(x, detail::bind(&custom_controlled_runge_kutta::template resize_m_dxdt_impl< StateInOut >, detail::ref(*this), detail::_1)) || m_first_call)\n        {\n            initialize(system, x, t);\n        }\n        return try_step(system, x, m_dxdt.m_v, t, dt);\n    }\n\n\n    stepper_type m_stepper;\n    error_checker_type m_error_checker;\n    step_adjuster_type m_step_adjuster;\n    typedef typename unwrap_reference< step_adjuster_type >::type unwrapped_step_adjuster;\n\n    resizer_type m_dxdt_resizer;\n    resizer_type m_xerr_resizer;\n    resizer_type m_xnew_resizer;\n    resizer_type m_dxdt_new_resizer;\n\n    wrapped_deriv_type m_dxdt;\n    wrapped_state_type m_xerr;\n    wrapped_state_type m_xnew;\n    wrapped_deriv_type m_dxdtnew;\n    bool m_first_call;\n    bool m_use_nn;\n    bool fixed_stepsize;\n    size_t hidden_num;\n    size_t m;\n    std::vector<double> W1;\n    std::vector<double> W2;\n    std::vector<double> b1;\n    double b2;\n    double k;\n    std::vector<double> input_vec;\n    std::vector<double> tmp_vec;\n};\n\n} // odeint\n} // numeric\n} // boost", "meta": {"hexsha": "568658f0a44ba290dc2673c8c2ec2a551f96eb5d", "size": 25930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lotka/step_adjuster.hpp", "max_stars_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_stars_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lotka/step_adjuster.hpp", "max_issues_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_issues_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lotka/step_adjuster.hpp", "max_forks_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_forks_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_forks_repo_licenses": ["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.3165266106, "max_line_length": 179, "alphanum_fraction": 0.6241033552, "num_tokens": 6616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5932179158163305}}
{"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\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\nusing namespace Sophus;\n// Local parameterization needed to handle SE3 from Sophus (from Sophus/test/ceres/)\nclass LocalParameterizationSE3 : public ceres::LocalParameterization {\n public:\n  virtual ~LocalParameterizationSE3() {}\n\n  // SE3 plus operation for Ceres\n  //\n  //  T * exp(x)\n  //\n  virtual bool Plus(double const* T_raw, double const* delta_raw,\n                    double* T_plus_delta_raw) const {\n    Eigen::Map<SE3d const> const T(T_raw);\n    Eigen::Map<Vector6d const> const delta(delta_raw);\n    Eigen::Map<SE3d> T_plus_delta(T_plus_delta_raw);\n    T_plus_delta = T * SE3d::exp(delta);\n    return true;\n  }\n\n  // Jacobian of SE3 plus operation for Ceres\n  //\n  // Dx T * exp(x)  with  x=0\n  //\n  virtual bool ComputeJacobian(double const* T_raw,\n                               double* jacobian_raw) const {\n    Eigen::Map<SE3d const> T(T_raw);\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> jacobian(\n        jacobian_raw);\n    jacobian = T.Dx_this_mul_exp_x_at_0();\n    return true;\n  }\n\n  virtual bool MultiplyByJacobian(const double* x, const int n_rows, const double* global_matrix, double *local_matrix) const\n  {\n    return ceres::LocalParameterization::MultiplyByJacobian(x, n_rows, global_matrix, local_matrix);\n  }\n\n  virtual int GlobalSize() const { return SE3d::num_parameters; }\n\n  virtual int LocalSize() const { return SE3d::DoF; }\n};\n\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    const Eigen::Map<const Sophus::SE3<T>> Rt(params);\n    Eigen::Matrix<T, 3, 1> X(T(_X.x()), T(_X.y()), T(_X.z()));\n    Eigen::Matrix<T, 3, 1> uv = _K * (Rt * X);\n    residuals[0] = _x[0] - uv.x() / uv.z();\n    residuals[1] = _x[1] - uv.y() / uv.z();\n    // std::cout << \"residuals: \\n\";\n    // std::cout << residuals[0] << std::endl;\n    // std::cout << residuals[1] << std::endl << std::endl;;\n\n    // std::cout << T(residuals[0]) << \"\\n\";\n    // std::cout << T(residuals[1]) << \"\\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  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 ProjectionError(points_2d[i], points_3d[i], K)\n      ),\n      nullptr,\n      pose.data()\n    );\n  }\n  problem.AddParameterBlock(pose.data(), 7, new LocalParameterizationSE3());\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\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": "282a9c038740571a0a069e140168363986de702c", "size": 8053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d_ceres_sophus.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_sophus.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_sophus.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7357723577, "max_line_length": 132, "alphanum_fraction": 0.6477089283, "num_tokens": 2543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5931868871942971}}
{"text": "/**\n * Authors:\n * \t\tAndré Potes (andre.potes@gmail.com)\n *      Marcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Maintained by: Marcelo Fialho Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)\n * Last Update: 14/12/2021\n * License: MIT\n * File: frames.hpp \n * Brief: Defines all functions related to conversions between ENU do NED frames and vice-versa\n * \n * NOTE: Most of this code is adapted from mavros\n * https://github.com/mavlink/mavros/blob/master/mavros/src/lib/ftf_frame_conversions.cpp\n * which had as authors Nuno Marques (n.marques21@hotmail.com) and Eddy Scott (scott.edward@aurora.aero)\n */\n#pragma once\n\n#include <Eigen/Dense>\n#include \"rotations.hpp\"\n\nnamespace DSOR{\n\n/**\n * @brief Static quaternion to convert a rotation expressed in ENU to a rotation expressed in NED (Z->Y->X convention) on\n * \t\t\tthe inertial frame\n * Rotate PI/2 about Z-axis -> Rotate 0 about Y-axis -> Rotate PI about X-axis\n * \n * NOTE: this quaternion is as valid as the quaternion representing the rotation from NED to ENU (quaternion ambiguity) on\n * \t\t\tthe inertial frame\n */\ntemplate <typename T>\nstatic const Eigen::Quaternion<T> ENU_NED_INERTIAL_Q = euler_to_quaternion(Eigen::Matrix<T, 3, 1>(M_PI, 0.0, M_PI_2));\n\n/**\n * @brief Static quaternion to convert a rotation expressed in ENU body frame (ROS base_link) to\n * \t\t\t a rotation expressed in NED body frame  (Z->Y->X convention)\n * Rotate 0 about Z-axis -> Rotate 0 about Y-axis -> Rotate PI about X-axis\n * \n * NOTE: this quaternion is as valid as the quaternion representing the rotation from NED to ENU (quaternion ambiguity) on\n * \t\t\tthe body frame\n*/\ntemplate <typename T>\nstatic const Eigen::Quaternion<T> ENU_NED_BODY_Q = euler_to_quaternion(Eigen::Matrix<T, 3, 1>(M_PI, 0.0, 0.0));\n\n/**\n * @brief Static quaternion needed for rotating vectors in body frames between ENU and NED\n * +PI rotation around X (Forward) axis transforms from Forward, Right, Down (body frame in NED)\n * Fto Forward, Left, Up (body frame in ENU).\n */\ntemplate <typename T>\nstatic const Eigen::Quaternion<T> BODY_ENU_NED_Q = euler_to_quaternion(Eigen::Matrix<T, 3, 1>(M_PI, 0.0, 0.0));\n\n/**\n * @brief Static affine matrix to roate vectors ENU (or NED) -> NED (or ENU) expressed in body frame\n * +PI rotation around X (Forward) axis transforms from Forward, Right, Down (body frame in NED)\n * Fto Forward, Left, Up (body frame in ENU).\n */\ntemplate <typename T>\nstatic const Eigen::Transform<T, 3, Eigen::Affine> BODY_ENU_NED_TF = Eigen::Transform<T, 3, Eigen::Affine>(BODY_ENU_NED_Q<T>);\n//template <typename T>\n//static const Eigen::Matrix<T, 3, 3> BODY_ENU_NED_AXIS = BODY_ENU_NED_Q<T>.toRotationMatrix();\n\n\n/**\n * @brief Use reflections instead of rotations for NED <-> ENU transformation\n * to avoid NaN/Inf floating point pollution across different axes\n * since in NED <-> ENU the axes are perfectly aligned.\n */\nstatic const Eigen::PermutationMatrix<3> NED_ENU_REFLECTION_XY(Eigen::Vector3i(1, 0, 2));\ntemplate <typename T>\nstatic const Eigen::DiagonalMatrix<T, 3> NED_ENU_REFLECTION_Z(1, 1, -1);\n\n\n/**\n * @brief Transform a rotation (as a quaternion) from body expressed in ENU (or NED) to inertial frame \n * \t\t\tto a similar rotation (as quaternion) from body expressed in NED (or ENU) to inertial frame.\n *\n * NOTE: Check http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/\n * \tfor more details behind these type of transformations towards obtaining rotations in different\n * \tframes of reference. \n * \n * @param q quaternion representing a rotation: body frame ENU (or NED) -> inertial frame (in arbitrary convention)\n * @return quaternion represeting a rotation: body frame NED (or ENU) -> inertial frame (in arbitrary convention)\n */\ntemplate <typename T>\ninline Eigen::Quaternion<T> rot_body_rotation(const Eigen::Quaternion<T> &q) {\n\treturn q * ENU_NED_BODY_Q<T>;\n}\n\n/**\n * @brief Transform a rotation (as a quaternion) from body to inertial frame expressed in ENU (or NED)\n * \t\t\tto a similar rotation (as quaternion) from body to inertial frame expressed in NED (or ENU)\n * \n * NOTE: Check http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/\n * \tfor more details behind these type of transformations towards obtaining rotations in different\n * \tframes of reference.\n * \n * @param q quaternion representing a rotation: body frame (in arbitrary convention) -> inertial frame ENU (or NED)\n * @return quaternion represeting a rotation: body frame (in arbitrary convention) -> inertial frame NED (or ENU)\n */\ntemplate <typename T>\ninline Eigen::Quaternion<T> rot_inertial_rotation(const Eigen::Quaternion<T> &q) {\n\treturn ENU_NED_INERTIAL_Q<T> * q;\n}\n\n\n/**\n * @brief Transform a rotation of a rigid body (as a quaternion) from body (ENU or NED) to inertial frame (ENU or NED)\n * \t\t\tto a similar rotation (as quaternion) from body (NED or ENU) to inertial frame (NED or ENU)\n * \n * NOTE: This function is usefull to convert the attitude of a vehicle from \"ROS\" quaternion to a typicall literature \n * quaternion (where both the body frame and inertial frames are in ENU). If you are converting a quaternion that expresses\n * the orientation of a sensor with respect to a rigid body's body frame (and not the inertial frame), then you DO NOT WANT TO USE THIS FUNCTION. \n * Body-FRAME NED is not the same as INERTIAL-FRAME NED (this comes once again from the fact that in ned body\n * the x-y axis don't switch like in inertial frame) as explained in the documentation.\n * \n * Essencial only use this if you are representing a body in inertial frame!\n * \n * NOTE: Check http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/transforms/\n * \tfor more details behind these type of transformations towards obtaining rotations in different\n * \tframes of reference.\n * \n * @param q quaternion representing a rotation: body frame (ENU or NED) -> inertial frame (ENU or NED)\n * @return quaternion representing a rotation: body frame (NED or ENU) -> inertial frame (NED or ENU)\n */\ntemplate <typename T>\ninline Eigen::Quaternion<T> rot_body_to_inertial(const Eigen::Quaternion<T> &q) {\n\treturn rot_inertial_rotation(rot_body_rotation(q));\n}\n\n\n/**\n * @brief Transform vector in ENU (or NED) to NED (or ENU), expressed in body-frame.\n * \t+PI rotation around X (Forward) axis transforms from Forward, Right, Down (body frame in NED)\n * \tFto Forward, Left, Up (body frame in ENU).\n * \n * @param vec Vector expressed in body-frame (ENU or NED)\n * @return Vector expressed in body-frame (NED or ENU)\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 1> transform_vect_body_enu_ned(const Eigen::Matrix<T,3,1> &vec) {\n\treturn BODY_ENU_NED_TF<T> * vec;\n}\n\n/**\n * @brief Transform a vector in a given frame of reference to another frame of reference.\n * \n * @param vec Vector expressed in the original frame of reference\n * @param q Quaternion that expresses the orientation of the original frame of reference with respect to the final frame of reference\n * @return Vector expressed in the new frame of reference\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 1> transform_vect_between_arbitrary_ref(const Eigen::Matrix<T, 3, 1> &vec, const Eigen::Quaternion<T> &q) {\n\n\t// Create an Affine3D transform with the rotation between the reference frames\n\tconst Eigen::Transform<T, 3, Eigen::Affine> frame_conversion = Eigen::Transform<T, 3, Eigen::Affine>(q);\n\treturn frame_conversion * vec;\n}\t\n\n/**\n * @brief Transform vector in ENU (or NED) to NED (or ENU), expressed in inertial-frame.\n *  ENU <---> NED - Invert the Z axis and switch the XY axis\n * \n * @param vec Vector expressed in inertial-frame (ENU or NED)\n * @return Vector expressed in inertial-frame (NED or ENU)\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 1> transform_vect_inertial_enu_ned(const Eigen::Matrix<T,3,1> &vec) {\n\treturn NED_ENU_REFLECTION_XY * (NED_ENU_REFLECTION_Z<T> * vec);\n}\n\n\n/**\n * @brief Transform 3x3 covariance matrix in ENU (or NED) to NED (or ENU), expressed in body-frame.\n * \t\n * NOTE: Check https://robotics.stackexchange.com/questions/2556/how-to-rotate-covariance for a detailed\n * \texplanation of the actual conversion proof for covariance matrices\n * \n * @param cov_in Covariance matrix expressed in body-frame (ENU or NED)\n * @return Covariance matrix expressed in body-frame (NED or ENU)\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 3> transform_cov3_body_enu_ned(const Eigen::Matrix<T, 3, 3> &cov_in) {\n\treturn cov_in * BODY_ENU_NED_Q<T>;\n}\n\n\n/**\n * @brief Transform 3x3 covariance matrix in ENU (or NED) to NED (or ENU), expressed in inertial-frame.\n * \n * NOTE: Check https://robotics.stackexchange.com/questions/2556/how-to-rotate-covariance for a detailed\n * \texplanation of the actual conversion proof for covariance matrices\n * \n * @param cov_in Covariance matrix expressed in inertial-frame (ENU or NED)\n * @return Covariance matrix expressed in inertial-frame (NED or ENU)\n */\ntemplate <typename T>\ninline Eigen::Matrix<T, 3, 3> transform_cov3_inertial_enu_ned(const Eigen::Matrix<T, 3, 3> &cov_in) {\n\tEigen::Matrix<T, 3, 3> cov_out;\n\n\tcov_out = NED_ENU_REFLECTION_XY * (NED_ENU_REFLECTION_Z<T> * cov_in * NED_ENU_REFLECTION_Z<T> ) *\n        NED_ENU_REFLECTION_XY.transpose();\n    \n\treturn cov_out;\n}\n\n\n}", "meta": {"hexsha": "900a1c006d42383b5d7ddaaa77703c78e9af9a68", "size": 9244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dsor_utils/include/dsor_utils/frames.hpp", "max_stars_repo_name": "dsor-isr/dsor_utils", "max_stars_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dsor_utils/include/dsor_utils/frames.hpp", "max_issues_repo_name": "dsor-isr/dsor_utils", "max_issues_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dsor_utils/include/dsor_utils/frames.hpp", "max_forks_repo_name": "dsor-isr/dsor_utils", "max_forks_repo_head_hexsha": "9e0c47701340b18da423a6badfb698673179f6bd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6570048309, "max_line_length": 146, "alphanum_fraction": 0.7376676763, "num_tokens": 2529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5931868781135674}}
{"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_TRANSFORM3D_HPP\n#define RW_MATH_TRANSFORM3D_HPP\n\n/**\n * @file Transform3D.hpp\n */\n\n#if !defined(SWIG)\n#include \"Rotation3D.hpp\"\n#include \"Rotation3DVector.hpp\"\n#include \"Vector3D.hpp\"\n\n#include <Eigen/Core>\n#include <cassert>\n#include <limits>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n#if !defined(SWIGJAVA)\n    /**\n     * @brief A 4x4 homogeneous transform matrix @f$ \\mathbf{T}\\in SE(3) @f$\n     *\n     * @f$\n     * \\mathbf{T} =\n     * \\left[\n     *  \\begin{array}{cc}\n     *  \\mathbf{R} & \\mathbf{d} \\\\\n     *  \\begin{array}{ccc}0 & 0 & 0\\end{array} & 1\n     *  \\end{array}\n     * \\right]\n     * @f$\n     *\n     */\n\n     #endif \n    template< class T = double > class Transform3D\n    {\n      public:\n        //! Value type.\n        typedef T value_type;\n\n        //! @brief Type for the internal Eigen matrix.\n        typedef Eigen::Matrix< T, 4, 4 > EigenMatrix4x4;\n\n        /**\n         * @brief Default Constructor.\n         *\n         * Initializes with 0 translation and Identity matrix as rotation\n         */\n        Transform3D () : _d (), _R (rw::math::Rotation3D< T >::identity ()) {}\n\n        /**\n         * @brief Constructs a homogeneous transform\n         * @param d [in] @f$ \\mathbf{d} @f$ A 3x1 translation vector\n         * @param R [in] @f$ \\mathbf{R} @f$ A 3x3 rotation matrix\n         */\n        Transform3D (const rw::math::Vector3D< T >& d, const rw::math::Rotation3D< T >& R) : _d (d), _R (R) {}\n\n        /**\n           @brief A homogeneous transform with a rotation of \\b R and a\n           translation of zero.\n        */\n        explicit Transform3D (const rw::math::Rotation3D< T >& R) : _d (0, 0, 0), _R (R) {}\n\n        /**\n           @brief A homogeneous transform with a rotation of zero and a\n           translation of \\b d.\n        */\n        explicit Transform3D (const rw::math::Vector3D< T >& d) : _d (d), _R (rw::math::Rotation3D< T >::identity ()) {}\n\n        /**\n         * @brief Constructs a homogeneous transform\n         *\n         * Calling this constructor is equivalent to the transform\n         * Transform3D(d, r.toRotation3D()).\n         *\n         * @param d [in] @f$ \\mathbf{d} @f$ A 3x1 translation vector\n         * @param r [in] @f$ \\mathbf{r} @f$ A 3x1 rotation vector\n         */\n        Transform3D (const rw::math::Vector3D< T >& d, const rw::math::Rotation3DVector< T >& r) :\n            _d (d), _R (r.toRotation3D ())\n        {}\n        \n\n        /**\n         * @brief Creates a Transform3D from matrix_expression\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > explicit Transform3D (const Eigen::MatrixBase< R >& r)\n        {\n            _d[0] = T(r.row (0) (3));\n            _d[1] = T(r.row (1) (3));\n            _d[2] = T(r.row (2) (3));\n            _R = Rotation3D<T>(r.block(0,0,3,3));\n        }\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs a homogeneous transform using the original\n         * Denavit-Hartenberg notation\n         *\n         * @param alpha [in] @f$ \\alpha_i @f$\n         * @param a [in] @f$ a_i @f$\n         * @param d [in] @f$ d_i @f$\n         * @param theta [in] @f$ \\theta_i @f$\n         * @return @f$ ^{i-1}\\mathbf{T}_i @f$\n         *\n         * @f$\n         *  \\robabx{i-1}{i}{\\mathbf{T}}=\n         *  \\left[\n         *    \\begin{array}{cccc}\n         *      c\\theta_i & -s\\theta_i c\\alpha_i &  s\\theta_i s\\alpha_i & a_i c\\theta_i \\\\\n         *      s\\theta_i &  c\\theta_i c\\alpha_i & -c\\theta_i s\\alpha_i & a_i s\\theta_i \\\\\n         *      0         &  s\\alpha_i           &  c\\alpha_i           & d_i \\\\\n         *      0         &  0                   & 0                    & 1\n         *    \\end{array}\n         *  \\right]\n         * @f$\n         */\n\n         #endif\n        static const Transform3D DH (T alpha, T a, T d, T theta);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs a homogeneous transform using the Craig (modified)\n         * Denavit-Hartenberg notation\n         *\n         * @param alpha [in] @f$ \\alpha_{i-1} @f$\n         * @param a [in] \\f$ a_{i-1} \\f$\n         * @param d [in] \\f$ d_i \\f$\n         * @param theta [in] \\f$ \\theta_i \\f$\n         * @return @f$ \\robabx{i-1}{i}{\\mathbf{T}} @f$\n         *\n         * @note The Craig (modified) Denavit-Hartenberg notation differs from\n         * the original Denavit-Hartenberg notation and is given as\n         *\n         * @f$\n         * \\robabx{i-1}{i}{\\mathbf{T}} =\n         * \\left[\n         * \\begin{array}{cccc}\n         * c\\theta_i & -s\\theta_i & 0 & a_{i-1} \\\\\n         * s\\theta_i c\\alpha_{i-1} & c\\theta_i c\\alpha_{i-1} & -s\\alpha_{i-1} & -s\\alpha_{i-1}d_i \\\\\n         * s\\theta_i s\\alpha_{i-1} & c\\theta_i s\\alpha_{i-1} &  c\\alpha_{i-1} &  c\\alpha_{i-1}d_i \\\\\n         * 0 & 0 & 0 & 1\n         * \\end{array}\n         * \\right]\n         * @f$\n         *\n         */\n\n         #endif\n        static const Transform3D craigDH (T alpha, T a, T d, T theta);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs a homogeneous transform using the Gordon (modified)\n         * Denavit-Hartenberg notation\n         *\n         * @param alpha [in] @f$ \\alpha_i @f$\n         * @param a [in] @f$ a_i @f$\n         * @param beta [in] @f$ \\beta_i @f$\n         * @param b [in] @f$ b_i @f$\n         * @return @f$ ^{i-1}\\mathbf{T}_i @f$\n         *\n         * @note The Gordon (modified) Denavit-Hartenberg differs from\n         * the original Denavit-Hartenberg as it branches between parallel\n         * and non-parallel z-axes.\n         *\n         * @f$ z_{i-1} @f$ is close to parallel to @f$ z_i @f$\n         * @f$\n         *  \\robabx{i-1}{i}{\\mathbf{T}}=\n         *  \\left[\n         *    \\begin{array}{cccc}\n         *       c\\beta_i & s\\alpha_i s\\beta_i &  c\\alpha_i s\\beta_i &  a_i c\\beta_i \\\\\n         *       0        & c\\alpha_i          & -s\\alpha_i          &  b_i \\\\\n         *      -s\\beta_i & s\\alpha_i c\\beta_i &  c\\alpha_i c\\beta_i & -a_i s\\beta \\\\\n         *      0         & 0                  & 0                    & 1\n         *    \\end{array}\n         *  \\right]\n         * @f$\n         */\n\n         #endif \n        static const Transform3D DHHGP (T alpha, T a, T beta, T b);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Constructs the identity transform\n         * @return the identity transform\n         *\n         * @f$\n         * \\mathbf{T} =\n         * \\left[\n         * \\begin{array}{cccc}\n         * 1 & 0 & 0 & 0\\\\\n         * 0 & 1 & 0 & 0\\\\\n         * 0 & 0 & 1 & 0\\\\\n         * 0 & 0 & 0 & 1\n         * \\end{array}\n         * \\right]\n         * @f$\n         */\n\n         #endif \n        static const Transform3D& identity ();\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns matrix element reference\n         * @param row [in] row, row must be @f$ < 3 @f$\n         * @param col [in] col, col must be @f$ < 4 @f$\n         * @return reference to matrix element\n         */\n        T& operator() (std::size_t row, std::size_t col)\n        {\n            assert (row < 3);\n            assert (col < 4);\n            if (row < 3 && col < 3)\n                return _R (row, col);\n            else\n                return _d (row);\n        }\n\n        /**\n         * @brief Returns const matrix element reference\n         * @param row [in] row, row must be @f$ < 3 @f$\n         * @param col [in] col, col must be @f$ < 4 @f$\n         * @return const reference to matrix element\n         */\n        const T& operator() (std::size_t row, std::size_t col) const\n        {\n            assert (row < 3);\n            assert (col < 4);\n            if (row < 3 && col < 3)\n                return _R (row, col);\n            else\n                return _d (row);\n        }\n#else\n        MATRIXOPERATOR (T);\n#endif\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true only if all elements are equal.\n         *\n         * @param rhs [in] Transform to compare with\n         * @return True if equal.\n         */\n        bool operator== (const Transform3D< T >& rhs) const\n        {\n            return (R () == rhs.R ()) && (P () == rhs.P ());\n        }\n\n        /**\n         * @brief Comparison operator.\n         *\n         * The comparison operator makes a element wise comparison.\n         * Returns true if any of the elements are different.\n         *\n         * @param rhs [in] Transform to compare with\n         * @return True if not equal.\n         */\n        bool operator!= (const Transform3D< T >& rhs) const { return !(*this == rhs); }\n\n        /**\n         * @brief Compares the transformations with a given precision\n         *\n         * Performs an element wise comparison. Two elements are considered equal if the difference\n         * are less than \\b precision.\n         *\n         * @param t3d [in] Transform to compare with\n         * @param precision [in] The precision to use for testing\n         * @return True if all elements are less than \\b precision apart.\n         */\n        bool equal (const Transform3D< T >& t3d,\n                    const T precision = std::numeric_limits< T >::epsilon ()) const\n        {\n            if (!R ().equal (t3d.R (), precision))\n                return false;\n            for (size_t i = 0; i < 3; i++)\n                if (fabs (P ()[i] - t3d.P ()[i]) > precision)\n                    return false;\n            return true;\n        }\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Calculates @f$ \\robabx{a}{c}{\\mathbf{T}} = \\robabx{a}{b}{\\mathbf{T}}\n         * \\robabx{b}{c}{\\mathbf{T}} @f$\n         * @param bTc [in] @f$ \\robabx{b}{c}{\\mathbf{T}} @f$\n         * @return @f$ \\robabx{a}{c}{\\mathbf{T}} @f$\n         *\n         * @f$\n         * \\robabx{a}{c}{\\mathbf{T}} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *  \\robabx{a}{b}{\\mathbf{R}}\\robabx{b}{c}{\\mathbf{R}} & \\robabx{a}{b}{\\mathbf{d}} +\n         * \\robabx{a}{b}{\\mathbf{R}}\\robabx{b}{c}{\\mathbf{d}} \\\\ \\begin{array}{ccc}0 & 0 &\n         * 0\\end{array} & 1 \\end{array} \\right]\n         * @f$\n         */\n\n         #endif \n        const Transform3D operator* (const Transform3D& bTc) const\n        {\n            return Transform3D (_d + _R * bTc._d, _R * bTc._R);\n        }\n\n        /**\n         * @brief Calculates @f$ \\robax{a}{\\mathbf{p}} = \\robabx{a}{b}{\\mathbf{T}}\n         * \\robax{b}{\\mathbf{p}} \\f$ thus transforming point @f$ \\mathbf{p} @f$ from frame @f$ b @f$\n         * to frame @f$ a @f$\n         * @param bP [in] @f$ \\robax{b}{\\mathbf{p}} @f$\n         * @return @f$ \\robax{a}{\\mathbf{p}} @f$\n         */\n        const rw::math::Vector3D< T > operator* (const rw::math::Vector3D< T >& bP) const { return _R * bP + _d; }\n\n        /**\n         * @brief Gets the rotation part @f$ \\mathbf{R} @f$ from @f$ \\mathbf{T} @f$\n         * @return @f$ \\mathbf{R} @f$\n         */\n        rw::math::Rotation3D< T >& R () { return _R; }\n\n        /**\n         * @brief Gets the rotation part @f$ \\mathbf{R} @f$ from @f$ \\mathbf{T} @f$\n         * @return @f$ \\mathbf{R} @f$\n         */\n        const rw::math::Rotation3D< T >& R () const { return _R; }\n\n        /**\n         * \\brief Gets the position part @f$ \\mathbf{d} @f$ from @f$ \\mathbf{T} @f$\n         * \\return @f$ \\mathbf{d} @f$\n         */\n        rw::math::Vector3D< T >& P () { return _d; }\n\n        /**\n         * @brief Gets the position part @f$ \\mathbf{d} @f$ from @f$ \\mathbf{T} @f$\n         * @return @f$ \\mathbf{d} @f$\n         */\n        const rw::math::Vector3D< T >& P () const { return _d; }\n\n#if !defined(SWIG)\n        /**\n         * @brief Outputs transform to stream\n         * @param os [in/out] an output stream\n         * @param t [in] the transform that is to be sent to the output stream\n         * @return os\n         */\n        friend std::ostream& operator<< (std::ostream& os, const Transform3D< T >& t)\n        {\n            // This format matches the Lua notation.\n            return os << \"Transform3D(\" << t.P () << \", \" << t.R () << \")\";\n        }\n#else\n        TOSTRING (rw::math::Transform3D< T >);\n#endif\n\n        /**\n           @brief Write to \\b result the product \\b a * \\b b.\n        */\n        static inline void multiply (const Transform3D< T >& a, const Transform3D< T >& b,\n                                     Transform3D< T >& result)\n        {\n            rw::math::Rotation3D< T >::multiply (a.R (), b.R (), result.R ());\n            rw::math::Rotation3D< T >::multiply (a.R (), b.P (), result.P ());\n            result.P () += a.P ();\n        }\n\n        /**\n         * @brief computes the inverse of t1 and multiplies it with t2.\n         * The result is saved in t1. t1 = inv(t1) * t2\n         */\n        static inline Transform3D< T >& invMult (Transform3D< T >& t1, const Transform3D< T >& t2)\n        {\n            const T p0 = t1.P () (0), p1 = t1.P () (1), p2 = t1.P () (2);\n\n            const T r01 = t1.R () (0, 1);\n            const T r12 = t1.R () (1, 2);\n            const T r02 = t1.R () (0, 2);\n\n            t1.P () (0) = (-p0 + t2.P () (0)) * t1.R () (0, 0) +\n                          (-p1 + t2.P () (1)) * t1.R () (1, 0) +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 0);\n\n            t1.P () (1) = (-p0 + t2.P () (0)) * r01 + (-p1 + t2.P () (1)) * t1.R () (1, 1) +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 1);\n\n            t1.P () (2) = (-p0 + t2.P () (0)) * r02 + (-p1 + t2.P () (1)) * r12 +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 2);\n\n            t1.R () (0, 1) = t1.R () (0, 0) * t2.R () (0, 1) + t1.R () (1, 0) * t2.R () (1, 1) +\n                             t1.R () (2, 0) * t2.R () (2, 1);\n            t1.R () (0, 2) = t1.R () (0, 0) * t2.R () (0, 2) + t1.R () (1, 0) * t2.R () (1, 2) +\n                             t1.R () (2, 0) * t2.R () (2, 2);\n            t1.R () (0, 0) = t1.R () (0, 0) * t2.R () (0, 0) + t1.R () (1, 0) * t2.R () (1, 0) +\n                             t1.R () (2, 0) * t2.R () (2, 0);\n\n            t1.R () (1, 0) = r01 * t2.R () (0, 0) + t1.R () (1, 1) * t2.R () (1, 0) +\n                             t1.R () (2, 1) * t2.R () (2, 0);\n            t1.R () (1, 2) = r01 * t2.R () (0, 2) + t1.R () (1, 1) * t2.R () (1, 2) +\n                             t1.R () (2, 1) * t2.R () (2, 2);\n            t1.R () (1, 1) = r01 * t2.R () (0, 1) + t1.R () (1, 1) * t2.R () (1, 1) +\n                             t1.R () (2, 1) * t2.R () (2, 1);\n\n            t1.R () (2, 0) =\n                r02 * t2.R () (0, 0) + r12 * t2.R () (1, 0) + t1.R () (2, 2) * t2.R () (2, 0);\n            t1.R () (2, 1) =\n                r02 * t2.R () (0, 1) + r12 * t2.R () (1, 1) + t1.R () (2, 2) * t2.R () (2, 1);\n            t1.R () (2, 2) =\n                r02 * t2.R () (0, 2) + r12 * t2.R () (1, 2) + t1.R () (2, 2) * t2.R () (2, 2);\n            return t1;\n        }\n\n        /**\n         * @brief computes the inverse of t1 and multiplies it with t2.\n         * The result is saved in t1. t1 = inv(t1) * t2\n         */\n        static inline Transform3D< T >& invMult (const Transform3D< T >& t1,\n                                                 const Transform3D< T >& t2, Transform3D< T >& t3)\n        {\n            const T p0 = t1.P () (0), p1 = t1.P () (1), p2 = t1.P () (2);\n\n            const T r01 = t1.R () (0, 1);\n            const T r12 = t1.R () (1, 2);\n            const T r02 = t1.R () (0, 2);\n\n            t3.P () (0) = (-p0 + t2.P () (0)) * t1.R () (0, 0) +\n                          (-p1 + t2.P () (1)) * t1.R () (1, 0) +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 0);\n\n            t3.P () (1) = (-p0 + t2.P () (0)) * r01 + (-p1 + t2.P () (1)) * t1.R () (1, 1) +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 1);\n\n            t3.P () (2) = (-p0 + t2.P () (0)) * r02 + (-p1 + t2.P () (1)) * r12 +\n                          (-p2 + t2.P () (2)) * t1.R () (2, 2);\n\n            t3.R () (0, 1) = t1.R () (0, 0) * t2.R () (0, 1) + t1.R () (1, 0) * t2.R () (1, 1) +\n                             t1.R () (2, 0) * t2.R () (2, 1);\n            t3.R () (0, 2) = t1.R () (0, 0) * t2.R () (0, 2) + t1.R () (1, 0) * t2.R () (1, 2) +\n                             t1.R () (2, 0) * t2.R () (2, 2);\n            t3.R () (0, 0) = t1.R () (0, 0) * t2.R () (0, 0) + t1.R () (1, 0) * t2.R () (1, 0) +\n                             t1.R () (2, 0) * t2.R () (2, 0);\n\n            t3.R () (1, 0) = r01 * t2.R () (0, 0) + t1.R () (1, 1) * t2.R () (1, 0) +\n                             t1.R () (2, 1) * t2.R () (2, 0);\n            t3.R () (1, 2) = r01 * t2.R () (0, 2) + t1.R () (1, 1) * t2.R () (1, 2) +\n                             t1.R () (2, 1) * t2.R () (2, 2);\n            t3.R () (1, 1) = r01 * t2.R () (0, 1) + t1.R () (1, 1) * t2.R () (1, 1) +\n                             t1.R () (2, 1) * t2.R () (2, 1);\n\n            t3.R () (2, 0) =\n                r02 * t2.R () (0, 0) + r12 * t2.R () (1, 0) + t1.R () (2, 2) * t2.R () (2, 0);\n            t3.R () (2, 1) =\n                r02 * t2.R () (0, 1) + r12 * t2.R () (1, 1) + t1.R () (2, 2) * t2.R () (2, 1);\n            t3.R () (2, 2) =\n                r02 * t2.R () (0, 2) + r12 * t2.R () (1, 2) + t1.R () (2, 2) * t2.R () (2, 2);\n            return t3;\n        }\n\n        /**\n         * @brief creates a transformation that is positioned in \\b eye and looking toward\n         * \\b center along -z where \\b up indicates the upward direction along which the y-axis\n         * is placed. Same convention as for gluLookAt\n         * and is handy for placing a cameraview.\n         * @param eye [in] position of view\n         * @param center [in] point to look toward\n         * @param up [in] the upward direction (the\n         * @return Transformation\n         */\n        static Transform3D< T > makeLookAt (const rw::math::Vector3D< T >& eye, const rw::math::Vector3D< T >& center,\n                                            const rw::math::Vector3D< T >& up)\n        {\n            rw::math::Vector3D< T > f (center - eye);\n            f = normalize (f);\n            rw::math::Vector3D< T > s (cross (f, up));\n            s = normalize (s);\n            rw::math::Vector3D< T > u (cross (s, f));\n            u = normalize (u);\n\n            rw::math::Rotation3D< T > R (s[0], s[1], s[2], u[0], u[1], u[2], -f[0], -f[1], -f[2]);\n\n            return inverse (Transform3D (R * -eye, R));\n        }\n\n        /**\n         * @brief Returns a Eigen 4x4 matrix @f$ \\mathbf{M}\\in SE(3)\n         * @f$ that represents this homogeneous transformation\n         *\n         * @return @f$ \\mathbf{M}\\in SE(3) @f$\n         */\n        Eigen::Matrix<T,4,4> e () const;\n\n      private:\n        rw::math::Vector3D< T > _d;\n        rw::math::Rotation3D< T > _R;\n    };\n\n// Explicit template specifications.\n#if !defined(SWIG)\n    extern template class rw::math::Transform3D< double >;\n    extern template class rw::math::Transform3D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Transform3Dd, rw::math::Transform3D< double >);\n    SWIG_DECLARE_TEMPLATE (Transform3Df, rw::math::Transform3D< float >);\n#endif\n\n    using Transform3Dd = Transform3D< double >;\n    using Transform3Df = Transform3D< float >;\n\n#if !defined(SWIGJAVA)\n    /**\n     * @brief Calculates\n     * @f$ \\robabx{b}{a}{\\mathbf{T}} = \\robabx{a}{b}{\\mathbf{T}}^{-1} @f$\n     *\n     * @relates Transform3D\n     *\n     * @param aTb [in] the transform matrix @f$ \\robabx{a}{b}{\\mathbf{T}} @f$\n     * @return @f$ \\robabx{b}{a}{\\mathbf{T}} = \\robabx{a}{b}{\\mathbf{T}}^{-1} @f$\n     *\n     * @f$\n     * \\robabx{a}{b}{\\mathbf{T}}^{-1} =\n     * \\left[\n     *  \\begin{array}{cc}\n     *  \\robabx{a}{b}{\\mathbf{R}}^{T} & - \\robabx{a}{b}{\\mathbf{R}}^{T} \\robabx{a}{b}{\\mathbf{d}} \\\\\n     *  \\begin{array}{ccc}0 & 0 & 0\\end{array} & 1\n     *  \\end{array}\n     * \\right]\n     *\n     * @f$\n     */\n\n     #endif \n    template< class T > const Transform3D< T > inverse (const Transform3D< T >& aTb)\n    {\n        return Transform3D< T > (-(inverse (aTb.R ()) * aTb.P ()), inverse (aTb.R ()));\n    }\n\n    /**\n     * @brief Cast Transform3D<T> to Transform3D<Q>\n     * @param trans [in] Transform3D with type T\n     * @return Transform3D with type Q\n     */\n    template< class Q, class T > const Transform3D< Q > cast (const Transform3D< T >& trans)\n    {\n        Transform3D< Q > res;\n        for (size_t i = 0; i < 3; i++)\n            for (size_t j = 0; j < 4; j++)\n                res (i, j) = static_cast< Q > (trans (i, j));\n        return res;\n    }\n\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::Transform3D\n         */\n        template<>\n        void write (const rw::math::Transform3D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Transform3D\n         */\n        template<>\n        void write (const rw::math::Transform3D< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Transform3D\n         */\n        template<>\n        void read (rw::math::Transform3D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Transform3D\n         */\n        template<>\n        void read (rw::math::Transform3D< 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 transform [in/out] the transformation to read/write.\n     * @param version [in] class version (currently version 0).\n     * @relatedalso rw::math::Transform3D\n     */\n    template< class Archive, class T >\n    void serialize (Archive& archive, rw::math::Transform3D< T >& transform,\n                    const unsigned int version)\n    {\n        archive& transform.P ();\n        archive& transform.R ();\n    }\n}}    // namespace boost::serialization\n\n#endif    // end include guard\n", "meta": {"hexsha": "735ee5e655231392645645cea729e74e8d8fa3a0", "size": 23262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Transform3D.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/Transform3D.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/Transform3D.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": 36.6330708661, "max_line_length": 120, "alphanum_fraction": 0.451079013, "num_tokens": 7504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5930427145092977}}
{"text": "#include <iostream>\n\n#include <boost/bind/bind.hpp>\n#include <boost/math/special_functions/pow.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n\n#include \"Filtering.hpp\"\n\n#include \"RadarCoordinatesTemplate.hpp\"\n\nusing namespace boost::accumulators;\n\nusing namespace boost::numeric::ublas;\nusing namespace boost::tuples;\n\nmatrix<double> stateTransitionMatrix(const std::size_t N, double dt) {\n\tmatrix<double> B = identity_matrix<double>(N);\n\tfor (std::size_t i = 0; i < N; i++) {\n\t\tfor (std::size_t j = i + 1; j < N; j++) {\n\t\t\tunsigned ji = (unsigned) (j - i);\n\t\t\tdouble fji = boost::math::factorial<double>(ji);\n\t\t\tB(i, j) = pow(dt, ji) / fji;\n\t\t}\n\t}\n\treturn B;\n}\n\n\n\n\n\nint main() {\n\tusing namespace boost::numeric::ublas;\n\n\tstd::cout << boost::math::pow<3>(10) << std::endl;\n\n\t/*\n\tmatrix<double> TntTn(3,3);\n\tTntTn(0, 0) = 11.0; TntTn(0, 1) = -5.5; TntTn(0, 2) = 3.85;\n\tTntTn(1, 0) = -5.5; TntTn(1, 1) = 3.85; TntTn(1, 2) = -3.025;\n\tTntTn(2, 0) = 3.85; TntTn(2, 1) = -3.025; TntTn(2, 2) = 2.5333;\n\tvector<double> TntYn(3);\n\tTntYn(0) = 45.99012356;\n\tTntYn(1) = -9.88611426;\n\tTntYn(2) = 0.36213461;\n\n\tstd::cout << TntTn << std::endl;\n\tstd::cout << TntYn << std::endl;\n\n\tpermutation_matrix<std::size_t> pm(TntTn.size1());\n\tlu_factorize(TntTn, pm); \n\tlu_substitute(TntTn, pm, TntYn);\n\tstd::cout << TntYn << std::endl;\n\n\tstd::cout << stateTransitionMatrix(8, 0.1) << std::endl;\n\t*/\n\tRadarCoordinates rc;\n\n\tRealVector E(1), N(1), U(1);\n\tE(0) = 10;\n\tN(0) = 20;\n\tU(0) = 50;\n\tstd::cout << rc.ENU2AER(E, N, U) << std::endl;\n\treturn 0;\n}\n\n", "meta": {"hexsha": "2742c0300b47bd6701533c4f53a6764975f2eba1", "size": 1869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cpp/Eigen/src/Filtering.cpp", "max_stars_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_stars_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_stars_repo_licenses": ["MIT"], "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/Eigen/src/Filtering.cpp", "max_issues_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_issues_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cpp/Eigen/src/Filtering.cpp", "max_forks_repo_name": "lintondf/MorrisonPolynomialFiltering", "max_forks_repo_head_hexsha": "f5713f9ed9a24c1382875d8ebdec00100f39e3a5", "max_forks_repo_licenses": ["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.2567567568, "max_line_length": 70, "alphanum_fraction": 0.6586409845, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5930383405061395}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n#pragma once\n\n#include <Eigen/Dense>\n#include <dpMM/global.hpp>\n#include <dpMM/normal.hpp>\n#include <dpMM/iw.hpp>\n#include <dpMM/sphere.hpp>\n\n#define LOG_2PI 1.8378770664093453\n\ntemplate<typename T>\nclass NormalSphere : public Distribution<T>\n{\npublic:\n  uint32_t D_; // dimension of the ambient space\n\n  NormalSphere(const Matrix<T,Dynamic,1>& mu, \n      const Matrix<T,Dynamic,Dynamic>& Sigma, boost::mt19937* pRndGen);\n  NormalSphere(const Matrix<T,Dynamic,1>& mu, \n      const Normal<T>& normal, boost::mt19937* pRndGen);\n  NormalSphere(const NormalSphere& other);\n  ~NormalSphere();\n\n  /* for any point on sphere - maps into T_muS and rotates north before logPdf */\n  T logPdf(const Matrix<T,Dynamic,1>& q_i) const;\n  /* assumes x_i is already in T_northS */\n  T logPdfNorth(const Matrix<T,Dynamic,1>& x_i) const;\n  T logPdfNorth(const Matrix<T,Dynamic,Dynamic>& scatter, \n      const Matrix<T,Dynamic,1>& mean, T count) const;\n//  T logPdfNorth(const Matrix<T,Dynamic,Dynamic>& scatter, T count) const;\n\n  Matrix<T,Dynamic,1> sample();\n\n  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return normal_.Sigma();};\n  void setSigma(const Matrix<T,Dynamic,Dynamic>& Sigma)\n  {return normal_.setSigma(Sigma);};\n  T logDetSigma() const {return normal_.logDetSigma();};\n  T logNormalizer() const {return -0.5*(normal_.logDetSigma()+D_*LOG_2PI);};\n\n  /* mean on sphere */\n  void setMean( const Matrix<T,Dynamic,1>& mu); \n  const Matrix<T,Dynamic,1>& getMean() const {return mu_;}; \n\n  /* mean in tangent plane */\n  void setMuInTpS( const Matrix<T,Dynamic,1>& mu)\n  {normal_.mu_ = mu;};\n\n  void setNormal(const Normal<T>& normal) {normal_ = normal;};\n  const Normal<T>& normal() const {return normal_;};\n\nprivate:\n  Normal<T> normal_; // zero-mean Gaussian in Tangent plane (dim: D-1)\n  Sphere<T> S_;\n  Matrix<T,Dynamic,1> mu_; // mean pointing to location in sphere\n  Matrix<T,Dynamic,Dynamic> northR_; \n};\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    Matrix<T,Dynamic,Dynamic>& x, uint32_t K);\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K);\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    const Matrix<T,Dynamic,Dynamic>& Delta, T nu,\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K);\n\n// ---------------------------------------------------------------------------\ntemplate<typename T>\nNormalSphere<T>::NormalSphere(const Matrix<T,Dynamic,1>& mu,\n    const Matrix<T,Dynamic,Dynamic>& Sigma, boost::mt19937* pRndGen)\n  : Distribution<T>(pRndGen),  D_(mu.size()), \n    normal_(Sigma,pRndGen), S_(D_) \n{\n  setMean(mu);\n};\n\ntemplate<typename T>\nNormalSphere<T>::NormalSphere(const Matrix<T,Dynamic,1>& mu, \n      const Normal<T>& normal, boost::mt19937* pRndGen)\n  : Distribution<T>(pRndGen),  D_(mu.size()), \n    normal_(normal), S_(D_) \n{\n  setMean(mu);\n};\n\ntemplate<typename T>\nNormalSphere<T>::NormalSphere(const NormalSphere& other)\n  : Distribution<T>(other.pRndGen_), D_(other.mu_.size()), \n    normal_(other.normal_), S_(other.D_)\n{\n  setMean(other.mu_);\n};\n\ntemplate<typename T>\nNormalSphere<T>::~NormalSphere()\n{};\n\ntemplate<typename T>\nvoid NormalSphere<T>::setMean( const Matrix<T,Dynamic,1>& mu)\n{\n  assert(mu.rows() == D_);\n  mu_ = mu;\n  northR_ = S_.north_R_TpS2(mu_);\n}\n\n\ntemplate<typename T>\nT NormalSphere<T>::logPdf(const Matrix<T,Dynamic,1>& q_i) const\n{\n//  cout<<q_i.transpose()<<endl;\n  Matrix<T,Dynamic,1> x_i = S_.Log_p_single(mu_,q_i);\n//  cout<<x_i.transpose()<<endl;\n//  cout<<northR_<<endl;\n\n#ifndef NDEBUG\n  ASSERT(fabs(x_i.transpose()*mu_)<1e-6, x_i.transpose()*mu_);\n\n  Matrix<T,Dynamic,1> xNorth = (northR_*x_i);\n  ASSERT(fabs( xNorth(D_-1)) < 1e-6, \n      xNorth.transpose() << endl\n      << \" northR_ \"<<endl<<northR_<<endl\n      << \" recomputed\"<<endl<<S_.north_R_TpS2(mu_)<<endl);\n  return normal_.logPdf(xNorth.topRows(D_-1));\n#else\n  return normal_.logPdf((northR_*x_i).topRows(D_-1));\n#endif\n//  return normal_.logPdf( S_.Log_p_north(mu_,q_i) );\n};\n\ntemplate<typename T>\nT NormalSphere<T>::logPdfNorth(const Matrix<T,Dynamic,1>& x_i) const\n{\n  assert(x_i.rows() == D_-1);\n#ifndef NDEBUG\n  Matrix<T,Dynamic,1> x(D_);\n  x.topRows(D_-1) = x_i;\n  x(D_-1) = 1.0;\n//  cout<<(x.transpose()*S_.north())<<endl;\n  assert(fabs((x.transpose()*S_.north()).norm() -1.) < 1.e-5);\n#endif\n  return normal_.logPdf(x_i);\n};\n\ntemplate<typename T>\nT NormalSphere<T>::logPdfNorth(const Matrix<T,Dynamic,Dynamic>& scatter, \n    const Matrix<T,Dynamic,1>& mean, T count) const\n{\n  return normal_.logPdf(scatter,mean,count); \n}\n\n//template<typename T>\n//T NormalSphere<T>::logPdfNorth(const Matrix<T,Dynamic,Dynamic>& scatter, \n//    T count) const\n//{\n//  return normal_.logPdf(scatter,count); \n//}\n\ntemplate<typename T>\nMatrix<T,Dynamic,1> NormalSphere<T>::sample()\n{\n  Matrix<T,Dynamic,1> xNorth(D_-1);\n  xNorth = normal_.sample();\n  // if outside radius of PI wrap around\n  // TODO\n  while(xNorth.norm() > PI)\n  {\n    cout<<\"wrapping around! ---------------------------------------------\"<<endl;\n    xNorth -= (T(2*PI))*(xNorth/xNorth.norm());\n  }\n//  cout<<\"xNorth = \"<<xNorth.transpose()<<endl;\n//  cout<<\"mu = \"<<mu_.transpose()<<endl;\n  Matrix<T,Dynamic,1> x = S_.rotate_north2p(mu_,xNorth);\n//  cout<<\"x = \"<<x.transpose()<<endl;\n  return S_.Exp_p(mu_,S_.rotate_north2p(mu_,xNorth));\n};\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    const Matrix<T,Dynamic,Dynamic>& Delta, T nu,\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K,\n    T minAngle = static_cast<T>(6.))\n{\n  uint32_t N = x.cols();\n  uint32_t D = x.rows();\n  Sphere<T> S_(D);\n  boost::mt19937 rndGen(9119);\n\n  IW<T> iw(Delta,nu,&rndGen);\n  Matrix<T,Dynamic,Dynamic> mus(D,K);\n  for(uint32_t k=0; k<K; ++k)\n  {\n    Matrix<T,Dynamic,Dynamic> Sigma = iw.sample();\n//    cout<<Sigma<<endl;\n//    cout<<\"nu \"<<nu<<endl;\n//    cout<<Delta<<endl;\n    Matrix<T,Dynamic,1> mu = S_.sampleUnif(&rndGen);\n    if(k>0) \n    {\n      bool done = false; \n      while(!done)\n      {\n        mu = S_.sampleUnif(&rndGen);\n        done = true;\n        for(uint32_t j=0; j<k; ++j)\n          done = done & (mu.transpose()*mus.col(j) < cos(minAngle*M_PI/180.0));\n      }\n    }\n    cout<<\"sampling data for k=\"<<k<<\" around mu=\"<<mu.transpose()<<\" Sigma:\"<<endl;\n    cout<<Sigma*(180.0/M_PI)*(180.0/M_PI)<<endl;\n    NormalSphere<T> gauss_k(mu,Sigma,&rndGen);\n    mus.col(k) = gauss_k.getMean();\n    for (uint32_t i=k*(N/K); i<min(N,(k+1)*(N/K)+N%K); ++i) \n    {\n//      cout<<\"--\"<<endl;\n//      cout<<mus.col(k).transpose()<<endl;\n      do{\n        x.col(i) = gauss_k.sample();\n      }while(fabs(x.col(i).norm()-1.0) > 1e-3); \n      if(fabs(x.col(i).norm()-1.0) > 1e-2)\n        cout<<x.col(i).norm()<<endl;\n      z(i) = k;\n//        x.col(i) /= x.col(i).norm();\n//      cout<<x.col(i).transpose()<<endl;\n    }\n  }\n  return mus;\n};\n\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t K)\n{\n  uint32_t N = x.cols();\n  uint32_t D = x.rows();\n  Sphere<T> S_(D);\n  boost::mt19937 rndGen(9119);\n\n  Matrix<T,Dynamic,Dynamic> Sigma = Matrix<T,Dynamic,Dynamic>::Identity(D-1,D-1);\n  Sigma *= 0.05;\n  Matrix<T,Dynamic,Dynamic> mus(D,K);\n  for(uint32_t k=0; k<K; ++k)\n  {\n    NormalSphere<T> gauss_k(S_.sampleUnif(&rndGen),Sigma,&rndGen);\n    mus.col(k) = gauss_k.getMean();\n    for (uint32_t i=k*(N/K); i<min(N,(k+1)*(N/K)+N%K); ++i) \n    {\n      do{\n        x.col(i) = gauss_k.sample();\n      }while(fabs(x.col(i).norm()-1.0) > 1e-3); \n      if(fabs(x.col(i).norm()-1.0) > 1e-2)\n        cout<<x.col(i).norm()<<endl;\n      z(i) = k;\n//        x.col(i) /= x.col(i).norm();\n//        cout<<x.col(i).transpose()<<endl;\n    }\n  }\n  return mus;\n};\n\ntemplate<class T>\ninline Matrix<T,Dynamic,Dynamic> sampleClustersOnSphere(\n    Matrix<T,Dynamic,Dynamic>& x, uint32_t K)\n{\n  VectorXu z(x.cols());\n  return sampleClustersOnSphere<T>(x,z,K);\n};\n", "meta": {"hexsha": "400a57582d4ff247d730c47e891168f1deeb4f62", "size": 8138, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/normalSphere.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/normalSphere.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/normalSphere.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": 29.5927272727, "max_line_length": 84, "alphanum_fraction": 0.6317276972, "num_tokens": 2494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5930383352673648}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2018 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file analyticcevengine.cpp */\n\n#include <ql/exercise.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/pricingengines/vanilla/analyticcevengine.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\nnamespace QuantLib {\n\n    CEVCalculator::CEVCalculator(Real f0, Real alpha, Real beta)\n    : f0_(f0),\n      alpha_(alpha),\n      beta_(beta),\n      delta_((1.0-2.0*beta)/(1.0-beta)),\n      x0_(X(f0)) { }\n\n    Real CEVCalculator::X(Real f) const {\n        return std::pow(f, 2.0*(1.0-beta_))/square<Real>()(alpha_*(1.0-beta_));\n    }\n\n    Real CEVCalculator::value(\n        Option::Type optionType, Real strike, Time t) const {\n\n        typedef boost::math::non_central_chi_squared_distribution<Real>\n            nc_chi2;\n\n        const Real kTilde = X(strike);\n\n        if (optionType == Option::Call) {\n            if (delta_ < 2.0) {\n                return f0_ * (1.0 - boost::math::cdf(\n                         nc_chi2(4.0-delta_, x0_/t), kTilde/t))\n                     - strike * boost::math::cdf(\n                         nc_chi2(2.0-delta_, kTilde/t), x0_/t);\n            }\n            else {\n                const Real g =\n                    boost::math::gamma_p(0.5*delta_-1.0,x0_/(2.0*t));\n\n                return f0_ * (g - boost::math::cdf(\n                         nc_chi2(delta_-2.0, kTilde/t), x0_/t))\n                     - strike * boost::math::cdf(\n                         nc_chi2(delta_, x0_/t), kTilde/t);\n            }\n        }\n        else if (optionType == Option::Put) {\n            if (delta_ < 2.0) {\n                return - f0_ * boost::math::cdf(\n                           nc_chi2(4.0-delta_, x0_/t), kTilde/t)\n                       + strike * (1.0 - boost::math::cdf(\n                           nc_chi2(2.0-delta_, kTilde/t), x0_/t));\n            }\n            else {\n                return - f0_ * boost::math::cdf(\n                           nc_chi2(delta_-2.0, kTilde/t), x0_/t)\n                       + strike * (1.0 - boost::math::cdf(\n                           nc_chi2(delta_, x0_/t), kTilde/t));\n            }\n        }\n        else\n            QL_FAIL(\"unknown option type\");\n\n    }\n\n    AnalyticCEVEngine::AnalyticCEVEngine(\n        Real f0, Real alpha, Real beta,\n        const Handle<YieldTermStructure>& discountCurve)\n    : calculator_(ext::make_shared<CEVCalculator>(f0, alpha,beta)),\n      discountCurve_(discountCurve) {\n        registerWith(discountCurve_);\n    }\n\n    void AnalyticCEVEngine::calculate() const {\n\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"not an European option\");\n\n        ext::shared_ptr<StrikedTypePayoff> payoff =\n            ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);\n        QL_REQUIRE(payoff, \"non-striked payoff given\");\n\n        const Date exerciseDate = arguments_.exercise->lastDate();\n\n        results_.value = calculator_->value(\n                payoff->optionType(),\n                payoff->strike(),\n                discountCurve_->timeFromReference(exerciseDate))\n            * discountCurve_->discount(exerciseDate);\n    }\n\n}\n", "meta": {"hexsha": "baa148b916f892f68417b8e71628ed65b05ee56a", "size": 3958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/vanilla/analyticcevengine.cpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "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": "ql/pricingengines/vanilla/analyticcevengine.cpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/pricingengines/vanilla/analyticcevengine.cpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 35.0265486726, "max_line_length": 79, "alphanum_fraction": 0.5765538151, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5930383348959732}}
{"text": "/**\n * \\file SecondOrderSVFFilter.cpp\n */\n\n#include <ATK/EQ/SecondOrderSVFFilter.h>\n\n#include <cassert>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename SVFCoefficients>\n  class SecondOrderSVFFilter<SVFCoefficients>::SVFState\n  {\n  public:\n    typename SVFCoefficients::DataType iceq1 = 0;\n    typename SVFCoefficients::DataType iceq2 = 0;\n  };\n  \n  template<typename SVFCoefficients>\n  SecondOrderSVFFilter<SVFCoefficients>::SecondOrderSVFFilter(gsl::index nb_channels)\n  :SVFCoefficients(nb_channels), state(std::make_unique<SVFState[]>(nb_channels))\n  {\n  }\n\n  template<typename SVFCoefficients>\n  SecondOrderSVFFilter<SVFCoefficients>::~SecondOrderSVFFilter()\n  {\n  }\n\n  template<typename SVFCoefficients>\n  void SecondOrderSVFFilter<SVFCoefficients>::full_setup()\n  {\n    state = std::make_unique<SVFState[]>(nb_input_ports);\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFFilter<DataType>::process_impl(gsl::index size) const\n  {\n    assert(nb_input_ports == nb_output_ports);\n    \n    for(gsl::index j = 0; j < nb_input_ports; ++j)\n    {\n      const DataType* ATK_RESTRICT input = converted_inputs[j];\n      DataType* ATK_RESTRICT output = outputs[j];\n      \n      for(gsl::index i = 0; i < size; ++i)\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 = CoeffDataType(2) * v1 - state[j].iceq1;\n        state[j].iceq2 = CoeffDataType(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  SecondOrderSVFBaseCoefficients<DataType>::SecondOrderSVFBaseCoefficients(gsl::index nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels)\n  {\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFBaseCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequencies must be positive\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n\n  template<typename DataType>\n  typename SecondOrderSVFBaseCoefficients<DataType>::CoeffDataType SecondOrderSVFBaseCoefficients<DataType>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFBaseCoefficients<DataType_>::set_Q(CoeffDataType Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template<typename DataType>\n  typename SecondOrderSVFBaseCoefficients<DataType>::CoeffDataType SecondOrderSVFBaseCoefficients<DataType>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType_>\n  SecondOrderSVFLowPassCoefficients<DataType_>::SecondOrderSVFLowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFLowPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFBandPassCoefficients<DataType_>::SecondOrderSVFBandPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFBandPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFHighPassCoefficients<DataType_>::SecondOrderSVFHighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFHighPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFNotchCoefficients<DataType_>::SecondOrderSVFNotchCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFNotchCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFPeakCoefficients<DataType_>::SecondOrderSVFPeakCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFPeakCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFBellCoefficients<DataType_>::SecondOrderSVFBellCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void SecondOrderSVFBellCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    if(gain <= 0)\n    {\n      throw std::out_of_range(\"Gain must be positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  typename SecondOrderSVFBellCoefficients<DataType>::CoeffDataType SecondOrderSVFBellCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFBellCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFLowShelfCoefficients<DataType_>::SecondOrderSVFLowShelfCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFLowShelfCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  typename SecondOrderSVFLowShelfCoefficients<DataType>::CoeffDataType SecondOrderSVFLowShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFLowShelfCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFHighShelfCoefficients<DataType_>::SecondOrderSVFHighShelfCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFHighShelfCoefficients<DataType_>::set_gain(CoeffDataType gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  typename SecondOrderSVFHighShelfCoefficients<DataType>::CoeffDataType SecondOrderSVFHighShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFHighShelfCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<CoeffDataType>() * cut_frequency / input_sampling_rate);\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 SecondOrderSVFBaseCoefficients<float>;\n  template class SecondOrderSVFBaseCoefficients<std::complex<float> >;\n  template class SecondOrderSVFBaseCoefficients<std::complex<double> >;\n\n  template class SecondOrderSVFLowPassCoefficients<float>;\n  template class SecondOrderSVFLowPassCoefficients<std::complex<float> >;\n  template class SecondOrderSVFLowPassCoefficients<std::complex<double> >;\n  template class SecondOrderSVFBandPassCoefficients<float>;\n  template class SecondOrderSVFBandPassCoefficients<std::complex<float> >;\n  template class SecondOrderSVFBandPassCoefficients<std::complex<double> >;\n  template class SecondOrderSVFHighPassCoefficients<float>;\n  template class SecondOrderSVFHighPassCoefficients<std::complex<float> >;\n  template class SecondOrderSVFHighPassCoefficients<std::complex<double> >;\n  template class SecondOrderSVFNotchCoefficients<float>;\n  template class SecondOrderSVFNotchCoefficients<std::complex<float> >;\n  template class SecondOrderSVFNotchCoefficients<std::complex<double> >;\n  template class SecondOrderSVFPeakCoefficients<float>;\n  template class SecondOrderSVFPeakCoefficients<std::complex<float> >;\n  template class SecondOrderSVFPeakCoefficients<std::complex<double> >;\n  template class SecondOrderSVFBellCoefficients<float>;\n  template class SecondOrderSVFBellCoefficients<std::complex<float> >;\n  template class SecondOrderSVFBellCoefficients<std::complex<double> >;\n  template class SecondOrderSVFLowShelfCoefficients<float>;\n  template class SecondOrderSVFLowShelfCoefficients<std::complex<float> >;\n  template class SecondOrderSVFLowShelfCoefficients<std::complex<double> >;\n  template class SecondOrderSVFHighShelfCoefficients<float>;\n  template class SecondOrderSVFHighShelfCoefficients<std::complex<float> >;\n  template class SecondOrderSVFHighShelfCoefficients<std::complex<double> >;\n\n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<std::complex<double> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<std::complex<float> > >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<std::complex<double> > >;\n#endif\n  template class SecondOrderSVFBaseCoefficients<double>;\n  \n  template class SecondOrderSVFLowPassCoefficients<double>;\n  template class SecondOrderSVFBandPassCoefficients<double>;\n  template class SecondOrderSVFHighPassCoefficients<double>;\n  template class SecondOrderSVFNotchCoefficients<double>;\n  template class SecondOrderSVFPeakCoefficients<double>;\n  template class SecondOrderSVFBellCoefficients<double>;\n  template class SecondOrderSVFLowShelfCoefficients<double>;\n  template class SecondOrderSVFHighShelfCoefficients<double>;\n  \n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<double> >;\n}\n", "meta": {"hexsha": "81b770c9e9b3fc2af79e2a16735aa918315eeba5", "size": 13236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/SecondOrderSVFFilter.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/SecondOrderSVFFilter.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/SecondOrderSVFFilter.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": 35.5806451613, "max_line_length": 135, "alphanum_fraction": 0.7408582653, "num_tokens": 3651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5930383325776281}}
{"text": "/** \n * File: random_var.cpp\n * Date: Mon Nov  9 10:31:35 CET 2020\n * Author: Open Risk  (www.openriskmanagement.com)\n *\n */\n\n#include <cmath>\n#include <iostream>\n#include <cassert>\n\n#include <Poco/JSON/JSON.h>\n#include <Poco/JSON/Parser.h>\n#include <armadillo>\n\n#include \"random_var.h\"\n\nusing namespace Poco;\n\nRandomVar &RandomVar::operator=(const RandomVar &R) {\n    assert(R.size() == this->size()); // check that size matches\n    for (size_t i = 0; i < R.size(); i++) {\n        this->setX(i, R.getX(i));\n        this->setP(i, R.getP(i));\n        this->setC(i, R.getC(i));\n    }\n    return (*this);\n};\n\n/**\n * ... text ...\n */\nvoid RandomVar::Sort() {\n    arma::sort(m_S);\n}\n\n/**\n * ... text ...\n */\nvoid RandomVar::Cumulative() {\n    m_C[0] = m_P[0];\n    for (size_t i = 1; i < m_P.size(); i++)\n        m_C[i] = m_C[i - 1] + m_P[i];\n}\n\n/**\n * ... text ...\n */\nvoid RandomVar::Probability() {\n    m_P[0] = m_C[0];\n    for (size_t i = 1; i < m_P.size(); i++)\n        m_P[i] = m_C[i] - m_C[i - 1];\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Average() const {\n    double expectation = 0.0;\n    if (m_type == 0) {\n        for (size_t i = 0; i < m_P.size(); i++) {\n            expectation += m_P[i] * m_X[i];\n        }\n    } else if (m_type == 1) {\n        for (size_t i = 0; i < m_S.size(); ++i) {\n            expectation += m_S[i];\n        }\n        expectation /= m_S.size();\n    }\n    return expectation;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Mean() const {\n    return Average();\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Median() const {\n    return Quantile(0.5);\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Variance() const {\n    double var = 0;\n    if (m_type == 0) {\n        for (size_t i = 0; i < m_P.size(); i++)\n            var += m_P[i] * m_X[i] * m_X[i];\n        var -= Average() * Average();\n    } else if (m_type == 1) {\n        for (size_t i = 0; i < m_S.size(); i++)\n            var += m_S[i] * m_S[i];\n        var /= m_S.size();\n        var -= Average() * Average();\n    }\n    return var;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Vol() const {\n    return sqrt(Variance());\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::StandardDeviation() const {\n    return Vol();\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Skeweness() const {\n    double skew = 0;\n    double mean = Average();\n    for (size_t i = 0; i < m_P.size(); i++)\n        skew += m_P[i] * pow(m_X[i] - mean, 3);\n    skew = skew / pow(Variance(), 3 / 2);\n    return skew;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Kurtosis() const {\n    double kurt = 0;\n    double mean = Average();\n    for (size_t i = 0; i < m_P.size(); i++)\n        kurt += m_P[i] * pow(m_X[i] - mean, 4);\n    kurt = kurt / pow(Variance(), 2);\n    return kurt;\n}\n\n/**\n * ... text ...\n */\nint RandomVar::Quantile_Index(double alpha) const {\n    int index = 0;\n    for (int i = 0; i < m_P.size(); i++) {\n        if (m_C[i] > 1 - alpha) {\n            index = i;\n            break;\n        }\n    }\n    return index;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::Quantile(double alpha) const {\n    int index = this->Quantile_Index(alpha);\n    return m_X[index];\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::VaR(double alpha) const {\n    return Quantile(1.0 - alpha);\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::ExpectedShortFall(double alpha) const {\n    int iVaR = this->Quantile_Index(alpha);\n    double es = 0;\n    for (int k = iVaR; k < m_P.size(); k++) {\n        es += m_P[k] * m_X[k];\n    }\n    es /= alpha;\n    return es;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::ExceedanceProbability(int index) const {\n    double ep = 0;\n    for (size_t k = index; k < m_P.size(); k++)\n        ep += m_P[k];\n    return ep;\n}\n\n/**\n * ... text ...\n */\ndouble RandomVar::MeanExcess(int index) const {\n    double alpha = ExceedanceProbability(index);\n    double es = 0;\n    for (size_t k = index; k < m_P.size(); k++)\n        es += m_P[k] * m_X[k];\n    es /= alpha;\n    return es;\n}\n\nstd::ostream &operator<<(std::ostream &os, const RandomVar &R) {\n    std::ostringstream out;\n    for (size_t k = 0; k < R.size(); k++)\n        out << R.getX(k) << \"\\t\" << R.getP(k) << \"\\t\" << R.getC(k) << std::endl;\n    return os << out.str();\n};\n\nvoid RandomVar::Print() {\n    if (this->m_type == 1) {\n        for (size_t s = 0; s < this->m_S.size(); s++) {\n            cout << s << \"\\t\" << this->m_S[s] << std::endl;\n        }\n    } else if (this->m_type == 0) {\n        for (size_t s = 0; s < this->m_X.size(); s++) {\n            cout << s << \"\\t\" << this->m_X[s] << \"\\t\" << this->m_P[s] << \"\\t\" << this->m_C[s] << std::endl;\n        }\n    }\n}\n\nvoid RandomVar::ReadFromJSON(const char *fileName) {\n\n    Poco::JSON::Parser loParser;\n    std::ifstream t(fileName);\n    std::stringstream buffer;\n    buffer << t.rdbuf();\n    std::string json = buffer.str();\n    // Parse the JSON and get the Results\n    Poco::Dynamic::Var loParsedJson = loParser.parse(json);\n    Poco::Dynamic::Var loParsedJsonResult = loParser.result();\n\n    // Random variable data are an array of objects\n    //[\n    // {\"value\": 1, \"probability\" : 0.2, \"cumulative\" : 0.2},\n    // {\"value\": 2, \"probability\" : 0.2, \"cumulative\" : 0.4},\n    // {\"value\": 3, \"probability\" : 0.2, \"cumulative\" : 0.6},\n    // {\"value\": 4, \"probability\" : 0.2, \"cumulative\" : 0.8},\n    // {\"value\": 5, \"probability\" : 0.2, \"cumulative\" : 1.0}\n    //]    \n\n    Poco::JSON::Array::Ptr arr = loParsedJsonResult.extract<Poco::JSON::Array::Ptr>();\n    size_t size = arr->size();\n    cout << \"Reading \" << size << \" records.\" << endl;\n\n    m_P.resize(size);\n    m_C.resize(size);\n    m_X.resize(size);\n\n    // Individual data rows\n    Poco::JSON::Object::Ptr object;\n    for (size_t i = 0; i < size; i++) {\n        object = arr->getObject(i);\n        this->setX(i, object->getValue<double>(\"value\"));\n        this->setP(i, object->getValue<double>(\"probability\"));\n        this->setC(i, object->getValue<double>(\"cumulative\"));\n    }\n\n}\n", "meta": {"hexsha": "380ac1f50a3506b60bbdef267605bbb1bfcfd19f", "size": 5915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "random_var.cpp", "max_stars_repo_name": "open-risk/tailRisk", "max_stars_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T07:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T07:25:15.000Z", "max_issues_repo_path": "random_var.cpp", "max_issues_repo_name": "open-risk/tailRisk", "max_issues_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_issues_repo_licenses": ["Apache-2.0"], "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_var.cpp", "max_forks_repo_name": "open-risk/tailRisk", "max_forks_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T11:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T11:47:13.000Z", "avg_line_length": 22.4053030303, "max_line_length": 107, "alphanum_fraction": 0.5125950972, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5929452039023306}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n/// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.com>\n///\n/// permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to\n/// deal in the Software without restriction, including without limitation the\n/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n/// sell copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions ofthe 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/// @version 0.1\n/// @author  Xinyan DAI\n/// @contact xinyan.dai@outlook.com\n//////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n#include <eigen3/Eigen/Dense>\n\n#include <map>\n#include <vector>\n#include <random>\n#include <iostream>\n#include <functional>\n#include <boost/progress.hpp>\n\n#include \"map_index.hpp\"\n\nnamespace ss {\n\n    template<typename DataType>\n    class ITQIndex: public MapIndex<DataType, uint64_t > {\n\n        using KeyType = uint64_t;\n    public:\n\n        explicit ITQIndex(const parameter & para):  MapIndex<DataType, uint64_t >(para) {}\n\n        ~ITQIndex() {}\n\n        void Train(const Matrix<DataType> & data) override;\n\n    protected:\n        KeyType Quantize(const DataType *data) override  {\n            KeyType hash_value = 0;\n            std::vector<DataType > v(_eigen_vectors.size());\n            for (unsigned i = 0; i != v.size(); ++i) {\n                v[i] = ss::DiffProduct(data, this->_means.data(), _eigen_vectors[i].data(), _eigen_vectors[i].size());\n            }\n            for (unsigned i = 0; i != v.size(); ++i) {\n                DataType  product  = ss::InnerProduct(v.data(), _rotate_matrix[i].data(), _rotate_matrix[i].size());\n                hash_value <<= 1;\n                hash_value |= product > 0? 1 : 0;\n            }\n            return hash_value;\n        }\n\n    private:\n\n        std::vector<std::vector<DataType > >  _eigen_vectors;\n        std::vector<std::vector<DataType> >   _rotate_matrix;\n\n    };\n} // namespace ss\n\n// ------------------------- implementation -------------------------\n\ntemplate<typename DataType>\nvoid ss::ITQIndex<DataType>::Train(const Matrix<DataType> & data) {\n\n    this->InitializeMeans(data); /// TODO(Xinyan): should avoid re-computing means\n\n    std::mt19937 rng(unsigned(std::time(0)));\n    std::normal_distribution<DataType > nd;\n    std::uniform_int_distribution<unsigned> usBits(0, data.getSize() - 1);\n\n    {\n        /// 1. wrap data with eigen\n        EigenMatrix< DataType > matrix_data = data.GetEigenMatrix();\n        /// 2. zero-centered\n        EigenMatrix< DataType > centered = matrix_data.rowwise() - matrix_data.colwise().mean();\n        /// 3. use eigen-vectors to project data\n        EigenMatrix< DataType > cov = (centered.transpose() * centered) / DataType (matrix_data.rows() - 1);\n        Eigen::SelfAdjointEigenSolver<EigenMatrix< DataType >> eig(cov);\n        EigenMatrix< DataType > eigen_vectors = eig.eigenvectors().rightCols(this->_para.num_bit);\n        EigenMatrix< DataType > V = matrix_data * eigen_vectors;\n        // 4. initialize R\n        EigenMatrix< DataType > R(this->_para.num_bit, this->_para.num_bit);\n        Eigen::JacobiSVD<EigenMatrix< DataType >> svd(R, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        R = svd.matrixU();\n\n        boost::progress_display progress(this->_para.iteration);\n        for (int iter = 0; iter < this->_para.iteration; ++iter && ++progress) {\n\n            EigenMatrix< DataType > VR = V * R;\n            EigenMatrix< DataType > B(VR.rows(), VR.cols()); // n * c\n            assert(VR.rows() == this->_para.train_size);\n            assert(VR.cols() == this->_para.num_bit);\n\n            for (unsigned i = 0; i != VR.rows(); ++i) {\n                for (unsigned j = 0; j != VR.cols(); ++j) {\n                    B(i, j) = VR(i, j) > 0 ? 1 : -1;\n                }\n            }\n            Eigen::JacobiSVD<EigenMatrix< DataType >> svd_tmp(B.transpose() * V, Eigen::ComputeThinU | Eigen::ComputeThinV);\n            R = svd_tmp.matrixV() * svd_tmp.matrixU().transpose();\n        }\n\n        _rotate_matrix.resize(this->_para.num_bit);\n        for (unsigned i = 0; i != _rotate_matrix.size(); ++i) {\n\n            _rotate_matrix[i].resize(this->_para.num_bit);\n            for (unsigned j = 0; j != _rotate_matrix[i].size(); ++j) {\n                _rotate_matrix[i][j] = R(j, i);\n            }\n        }\n        _eigen_vectors.resize(this->_para.num_bit);\n        for (unsigned i = 0; i != _eigen_vectors.size(); ++i) {\n\n            _eigen_vectors[i].resize(data.getDim());\n            for (unsigned dimension = 0; dimension != data.getDim(); ++dimension) {\n                _eigen_vectors[i][dimension] = eigen_vectors(dimension, i);\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "0b8393a2bf07b86e239481953ffb8996a3a3fb1c", "size": 5504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/index/itq.hpp", "max_stars_repo_name": "xinyandai/similarity-search", "max_stars_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-11-17T00:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T22:51:56.000Z", "max_issues_repo_path": "src/include/index/itq.hpp", "max_issues_repo_name": "xinyandai/similarity-search", "max_issues_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_issues_repo_licenses": ["MIT"], "max_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/index/itq.hpp", "max_forks_repo_name": "xinyandai/similarity-search", "max_forks_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T08:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T02:42:58.000Z", "avg_line_length": 39.0354609929, "max_line_length": 124, "alphanum_fraction": 0.5946584302, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5929245900597421}}
{"text": "//\n// Created by kerin on 2019-12-01.\n//\n#include \"mpi_utils.hpp\"\n#include \"typedefs.hpp\"\n#include \"variational_parameters.hpp\"\n\n#include \"tools/eigen3.3/Dense\"\n#include \"tools/eigen3.3/Eigenvalues\"\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/fisher_f.hpp>\n\n#include <cmath>\n\nnamespace boost_m  = boost::math;\n\nvoid prep_lm(const Eigen::MatrixXd &H,\n             const Eigen::MatrixXd &y,\n             EigenRefDataMatrix HtH,\n             EigenRefDataMatrix HtH_inv,\n             EigenRefDataMatrix Hty,\n             double &rss,\n             EigenRefDataMatrix HtVH) {\n\t/*** All of the heavy lifting for linear hypothesis tests.\n\t * Easier to have in one place if we go down the MPI route.\n\t */\n\n\tHtH     = H.transpose() * H;\n\tHtH     = mpiUtils::mpiReduce_inplace(HtH);\n\tHty     = H.transpose() * y;\n\tHty     = mpiUtils::mpiReduce_inplace(Hty);\n\tHtH_inv = HtH.inverse();\n\n\tEigenDataVector resid = y - H * HtH_inv * Hty;\n\tHtVH = H.transpose() * resid.cwiseProduct(resid).asDiagonal() * H;\n\tHtVH = mpiUtils::mpiReduce_inplace(HtVH);\n\n\trss = resid.squaredNorm();\n\trss = mpiUtils::mpiReduce_inplace(&rss);\n}\n\nvoid prep_lm(const Eigen::MatrixXd &H,\n             const Eigen::MatrixXd &y,\n             EigenRefDataMatrix HtH,\n             EigenRefDataMatrix HtH_inv,\n             EigenRefDataMatrix Hty,\n             double &rss) {\n\t/*** All of the heavy lifting for linear hypothesis tests.\n\t * Easier to have in one place if we go down the MPI route.\n\t */\n\n\tHtH     = H.transpose() * H;\n\tHtH     = mpiUtils::mpiReduce_inplace(HtH);\n\tHty     = H.transpose() * y;\n\tHty     = mpiUtils::mpiReduce_inplace(Hty);\n\tHtH_inv = HtH.inverse();\n\n\tEigenDataVector resid = y - H * HtH_inv * Hty;\n\trss = resid.squaredNorm();\n\trss = mpiUtils::mpiReduce_inplace(&rss);\n}\n\nvoid student_t_test(long nn,\n                    const Eigen::MatrixXd &HtH_inv,\n                    const Eigen::MatrixXd &Hty,\n                    double rss,\n                    int jj,\n                    double &stat,\n                    double &pval) {\n\t/* 2-sided Student t-test on regression output\n\t   H0: beta[jj] != 0\n\t */\n\tlong pp = HtH_inv.rows();\n\tassert(jj <= pp);\n\tnn = mpiUtils::mpiReduce_inplace(&nn);\n\n\tauto beta = HtH_inv * Hty;\n\tstat = beta(jj, 0);\n\tstat /= std::sqrt(rss * HtH_inv(jj, jj) / (double) (nn - pp));\n//\tif (std::isnan(stat)){\n//\t\tstd::cout << \"est = \" << beta(jj, 0) << std::endl;\n//\t\tstd::cout << \"sd(est) = \" << std::sqrt(rss * HtH_inv(jj, jj) / (double) (nn - pp)) << std::endl;\n//\t\tstd::cout << \"rss = \" << rss << std::endl;\n//\t}\n\n\tboost_m::students_t t_dist(nn - pp);\n\tpval  = 2 * boost_m::cdf(boost_m::complement(t_dist, fabs(stat)));\n}\n\nvoid hetero_chi_sq(const Eigen::MatrixXd &HtH_inv,\n                   const Eigen::MatrixXd &Hty,\n                   const Eigen::MatrixXd &HtVH,\n                   int jj,\n                   double &stat,\n                   double &pval) {\n\t/* Standard errors adjusted for Heteroscedasticity\n\t   https://en.wikipedia.org/wiki/Heteroscedasticity-consistent_standard_errors\n\t   HtVH = (H.transpose() * resid_sq.asDiagonal() * H)\n\t */\n\tlong pp = HtH_inv.rows();\n\tassert(jj <= pp);\n\n\tauto beta = HtH_inv * Hty;\n\tauto var_beta = HtH_inv * HtVH * HtH_inv;\n\tstat = beta(jj, 0) * beta(jj, 0);\n\tstat /= var_beta(jj, jj);\n\tstat = std::abs(stat);\n//\tif (std::isnan(stat)){\n//\t\tstd::cout << \"est_sq = \" << beta(jj, 0) * beta(jj, 0) << std::endl;\n//\t\tstd::cout << \"var(est) = \" << var_beta(jj, jj) << std::endl;\n//\t}\n\n\tboost_m::chi_squared chi_dist(1);\n\tpval = boost_m::cdf(boost_m::complement(chi_dist, stat));\n}\n\nvoid homo_chi_sq(long nn,\n                 const Eigen::MatrixXd &HtH_inv,\n                 const Eigen::MatrixXd &Hty,\n                 const double rss,\n                 const int jj,\n                 double &stat,\n                 double &pval) {\n\t/* Essentially the square of the t-test from regression\n\t */\n\tlong pp = HtH_inv.rows();\n\tassert(jj <= pp);\n\tnn = mpiUtils::mpiReduce_inplace(&nn);\n\n\tauto beta = HtH_inv * Hty;\n\tstat = beta(jj, 0) * beta(jj, 0);\n\tstat /= rss * HtH_inv(jj, jj) / (double) (nn - pp);\n\tstat = std::abs(stat);\n//\tif (std::isnan(stat)){\n//\t\tstd::cout << \"est_sq = \" << beta(jj, 0) * beta(jj, 0) << std::endl;\n//\t\tstd::cout << \"var(est) = \" << rss * HtH_inv(jj, jj) / (double) (nn - pp) << std::endl;\n//\t}\n\n\tboost_m::chi_squared chi_dist(1);\n\tpval = boost_m::cdf(boost_m::complement(chi_dist, stat));\n}\n\ndouble homo_chi_sq(const long nn,\n                   const Eigen::MatrixXd &HtH_inv,\n                   const Eigen::MatrixXd &Hty,\n                   const double rss,\n                   const int jj) {\n\tdouble tstat, pval;\n\thomo_chi_sq(nn, HtH_inv, Hty, rss, jj, tstat, pval);\n\treturn pval;\n}\n\ndouble hetero_chi_sq(const Eigen::MatrixXd &HtH_inv,\n                     const Eigen::MatrixXd &Hty,\n                     const Eigen::MatrixXd &HtVH,\n                     int jj) {\n\tdouble tstat, pval;\n\thetero_chi_sq(HtH_inv, Hty, HtVH, jj, tstat, pval);\n\treturn pval;\n}\n\ndouble student_t_test(long nn,\n                      const Eigen::MatrixXd &HtH_inv,\n                      const Eigen::MatrixXd &Hty,\n                      double rss,\n                      int jj) {\n\tdouble tstat, pval;\n\tstudent_t_test(nn, HtH_inv, Hty, rss, jj, tstat, pval);\n\treturn pval;\n}\n\ntemplate <typename GenoMat>\nvoid compute_LOCO_pvals(const EigenDataVector &resid_pheno,\n                        const GenoMat &Xtest,\n                        Eigen::MatrixXd &neglogPvals,\n                        Eigen::MatrixXd &testStats,\n                        const EigenDataVector &eta) {\n\tbool isGxE     = eta.rows() > 0;\n\tlong n_var     = Xtest.cols();\n\tlong n_samples = Xtest.rows();\n\tlong n_effects = (isGxE ? 2 : 1);\n\tdouble Nlocal  = n_samples;\n\tdouble Nglobal = mpiUtils::mpiReduce_inplace(&Nlocal);\n\n\tneglogPvals.resize(n_var, (isGxE ? 4 : 1));\n\ttestStats.resize(n_var, (isGxE ? 4 : 1));\n\n\t// Compute p-vals per variant (p=3 as residuals mean centered)\n\tEigen::MatrixXd H(n_samples, 2 + 2 * (isGxE ? 1 : 0));\n\tH.col(0) = Eigen::VectorXd::Constant(n_samples, 1.0);\n\tif (isGxE) H.col(3) = eta.cast<double>();\n\tboost_m::students_t t_dist(n_samples - H.cols() - 1);\n\tboost_m::fisher_f f_dist(n_effects, n_samples - H.cols() - 1);\n\tfor(std::uint32_t jj = 0; jj < n_var; jj++ ) {\n\t\tH.col(1) = Xtest.col(jj);\n\n\t\tdouble rss_alt, rss_null;\n\t\tEigen::MatrixXd HtH(H.cols(), H.cols()), Hty(H.cols(), 1);\n\t\tEigen::MatrixXd HtH_inv(H.cols(), H.cols()), HtVH(H.cols(), H.cols());\n\t\tif(!isGxE) {\n\t\t\tdouble beta_tstat, beta_pval;\n\t\t\tprep_lm(H, resid_pheno, HtH, HtH_inv, Hty, rss_alt);\n\t\t\tstudent_t_test(n_samples, HtH_inv, Hty, rss_alt, 1, beta_tstat, beta_pval);\n\n\t\t\tneglogPvals(jj,0) = -1 * log10(beta_pval);\n\t\t\ttestStats(jj,0)   = beta_tstat;\n\t\t} else {\n\t\t\tH.col(2) = H.col(1).cwiseProduct(eta.cast<double>());\n\t\t\ttry {\n\t\t\t\t// Single-var tests\n\t\t\t\tdouble beta_tstat, gam_tstat, rgam_stat, beta_pval, gam_pval, rgam_pval;\n\t\t\t\tprep_lm(H, resid_pheno, HtH, HtH_inv, Hty, rss_alt, HtVH);\n\t\t\t\thetero_chi_sq(HtH_inv, Hty, HtVH, 2, rgam_stat, rgam_pval);\n\t\t\t\tstudent_t_test(n_samples, HtH_inv, Hty, rss_alt, 2, gam_tstat, gam_pval);\n\t\t\t\tstudent_t_test(n_samples, HtH_inv, Hty, rss_alt, 1, beta_tstat, beta_pval);\n\n\t\t\t\t// F-test over main+int effects of snp_j\n\t\t\t\tdouble joint_fstat, joint_pval;\n\t\t\t\trss_null = resid_pheno.squaredNorm();\n\t\t\t\trss_null = mpiUtils::mpiReduce_inplace(&rss_null);\n\t\t\t\tjoint_fstat = (rss_null - rss_alt) / 2.0;\n\t\t\t\tjoint_fstat /= rss_alt / (Nglobal - 3.0);\n\t\t\t\tjoint_pval = 1.0 - boost_m::cdf(f_dist, joint_fstat);\n\n\t\t\t\tneglogPvals(jj, 0) = -1 * std::log10(beta_pval);\n\t\t\t\tneglogPvals(jj, 1) = -1 * std::log10(gam_pval);\n\t\t\t\tneglogPvals(jj, 2) = -1 * std::log10(rgam_pval);\n\t\t\t\tneglogPvals(jj, 3) = -1 * std::log10(joint_pval);\n\t\t\t\ttestStats(jj, 0) = beta_tstat;\n\t\t\t\ttestStats(jj, 1) = gam_tstat;\n\t\t\t\ttestStats(jj, 2) = rgam_stat;\n\t\t\t\ttestStats(jj, 3) = joint_fstat;\n\t\t\t} catch (...) {\n\t\t\t\tneglogPvals(jj, 0) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\tneglogPvals(jj, 1) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\tneglogPvals(jj, 2) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\tneglogPvals(jj, 3) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\ttestStats(jj, 0) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\ttestStats(jj, 1) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\ttestStats(jj, 2) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t\ttestStats(jj, 3) = std::numeric_limits<double>::quiet_NaN();\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Explicit instantiation\n// https://stackoverflow.com/questions/2152002/how-do-i-force-a-particular-instance-of-a-c-template-to-instantiate\ntemplate void compute_LOCO_pvals(const EigenDataVector&, const EigenDataMatrix&,\n                                 Eigen::MatrixXd&, Eigen::MatrixXd&,const EigenDataVector&);\ntemplate void compute_LOCO_pvals(const EigenDataVector&, const GenotypeMatrix&,\n                                 Eigen::MatrixXd&, Eigen::MatrixXd&,const EigenDataVector&);\n", "meta": {"hexsha": "6292efaf01c9ab8901f85ea7d7e5887a28a05c3a", "size": 9014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stats_tests.cpp", "max_stars_repo_name": "mkerin/LEMMA", "max_stars_repo_head_hexsha": "26deaa5ed343074ac19bfaf5f3254f670647351c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T21:18:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T18:46:53.000Z", "max_issues_repo_path": "src/stats_tests.cpp", "max_issues_repo_name": "lfelipe-ferrao/LEMMA", "max_issues_repo_head_hexsha": "471368ce1e362a64aa3a682075c4d4e4bcd9509b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-09-10T21:18:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T18:38:31.000Z", "max_forks_repo_path": "src/stats_tests.cpp", "max_forks_repo_name": "lfelipe-ferrao/LEMMA", "max_forks_repo_head_hexsha": "471368ce1e362a64aa3a682075c4d4e4bcd9509b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T21:02:27.000Z", "avg_line_length": 35.2109375, "max_line_length": 114, "alphanum_fraction": 0.6128244952, "num_tokens": 2734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.843895106480586, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.592861677591339}}
{"text": "#include <iostream>\n#include <tclap/CmdLine.h>\n\n// SISL Main Include\n#include <sisl/sisl.hpp>\n\n// odd cartesian function spaces\n#include <sisl/lattice/cartesian_odd.hpp>\n#include <sisl/basis/tp3cubic.hpp>\n\n// odd BCC function spaces\n#include <sisl/lattice/bcc_odd.hpp>\n#include <sisl/basis/quintic.hpp>\n#include <sisl/basis/linear_rdod.hpp>\n\n// utility functions\n#include <poisson/pointset.hpp>\n#include <sisl/utility/isosurface.hpp>\n#include <sisl/utility/dualbcc.hpp>\n#include <sisl/utility/dualfcc.hpp>\n#include <sisl/utility/dualcc.hpp>\n#include <sisl/utility/scattered.hpp>\n#include <sisl/utility/ply_writer.hpp>\n\n#include <Eigen/Dense>\n\n#include <tuple>\n#include <cmath>\n\n#define VESION_STRING \"0.1\"\n\nusing namespace sisl;\nusing namespace std;\nusing namespace TCLAP;\n\ntemplate <class T>\nclass MarschnerLobb {\npublic:\n\tdouble a, fm;\n\n\tMarschnerLobb(double Fm, double alpha) : fm(Fm), a(alpha){ }\n\tdouble rho(double r){\n\t\treturn cos(2*M_PI*fm*cos(r*M_PI/2.));\n\t}\t\n\tdouble f(const double &xx, const double &yy, const double &zz) {\n\t\tdouble x = (2.*xx-1.), y = (2.*yy-1.), z = (2.*zz-1.);\n\t\tdouble r = rho(sqrt(x*x + y*y));\n\t\tdouble ret = 1. - sin(M_PI*z/2.) + a * (1. + r);\n\t\treturn ret/(2. + 2.*a);\n\n\t}\n\n\tdouble f(const vector3<T> &p) {return this->f(p.i, p.j, p.k);}\n\tvector3<double> grad_f(const vector3<T> &p) { return this->grad_f(p.i, p.j, p.k); }\n\tvector3<double> grad_f(const double &x, const double &y, const double &z) {\n\t\tdouble xx = 2.*x - 1.;\n\t\tdouble yy = 2.*y - 1.;\n\t\tdouble zz = 2.*z - 1.;\n\t\treturn vector3<double> (\n\t\t\tM_PI*M_PI*a*fm*(xx)*sin(2.*M_PI*fm*cos(0.5*M_PI*sqrt(xx*xx + yy*yy))) *sin(0.5*M_PI*sqrt(xx*xx + yy*yy))/(sqrt(xx*xx + yy*yy)*(a + 1.)),\n\t\t\tM_PI*M_PI*a*fm*(yy)*sin(2.*M_PI*fm*cos(0.5*M_PI*sqrt(xx*xx + yy*yy))) *sin(0.5*M_PI*sqrt(xx*xx + yy*yy))/(sqrt(xx*xx + yy*yy)*(a + 1.)),\n\t\t\t-0.5*M_PI*cos(0.5*M_PI*zz)/(a + 1.)\n\t\t);\n\t}\n};\n\ntemplate <class T>\nclass HamFunction {\npublic:\n\tHamFunction(){}\n\tdouble f(const double &x, const double &y, const double &z) {\n\t\treturn -(sin(0.3141592654e1 * x) * sin(0.3141592654e1 * y) * sin(0.3141592654e1 * z) * (sqrt(0.25e0 + pow(0.9e1 * x - 0.45e1, 0.2e1) + pow(0.9e1 * y - 0.45e1, 0.2e1) + pow(0.9e1 * z - 0.45e1, 0.2e1)) - 0.2e1 * cos(0.8e1 * 0.3141592654e1 * (0.9e1 * z - 0.45e1) * pow(0.25e0 + pow(0.9e1 * x - 0.45e1, 0.2e1) + pow(0.9e1 * y - 0.45e1, 0.2e1) + pow(0.9e1 * z - 0.45e1, 0.2e1), -0.1e1 / 0.2e1)) - 0.2e1));\n\t}\n\n\tdouble f(const vector3<T> &p) {\n\t\treturn this->f(p.i, p.j, p.k);\n\t}\n\t\n\tvector3<double> grad_f(const vector3<T> &p) { return this->grad_f(p.i, p.j, p.k); }\n\tvector3<double> grad_f(const double &x, const double &y, const double &z) {\n\t\treturn vector3<double> (\n\t\t\t2.*(x-0.5),\n\t\t\t2.*(y-0.5),\n\t\t\t2.*(z-0.5)\n\t\t);\n\t}\n};\n\n\ntemplate<class T>\nclass SphereFunction{\npublic:\n\tSphereFunction(){}\n\tdouble f(const double &x, const double &y, const double &z) {\n\t\tdouble xx = (x-0.5), yy = (y-0.5), zz = (z-0.5);\n\t\treturn xx*xx + yy*yy + zz*zz - 0.25*0.25;\n\t}\n\n\tdouble f(const vector3<T> &p) {return this->f(p.i, p.j, p.k);}\n\n\tvector3<double> grad_f(const vector3<T> &p) { return this->grad_f(p.i, p.j, p.k); }\n\tvector3<double> grad_f(const double &x, const double &y, const double &z) {\n\t\treturn vector3<double> (\n\t\t\t2*(x-0.5),\n\t\t\t2*(y-0.5),\n\t\t\t2*(z-0.5)\n\t\t);\n\t}\n};\n\nint main(int argc, char *argv[])\n{\n\ttry {\n\t\tCmdLine cmd(\"Dual marching cubes for CC/BCC/FCC lattices\", ' ', VESION_STRING);\n\t\tsisl::utility::marchingCubes<double> mc;\n\t\tsisl::utility::dualbcc_isosurface<double> dbcc;\n\t\tsisl::utility::dualfcc_isosurface<double> dfcc;\n\t\tsisl::utility::dualcc_isosurface<double> dcc;\n\n\t\tValueArg<std::string> outputArg(\"o\", \"output\", \"Output mesh name\", true,\"output\", \"filename\");\n\t\tValueArg<std::string> testFunction(\"t\", \"test_function\", \"test function\", false, \"lobner\", \"test function\");\n\t\tValueArg<double> isoValue(\"i\", \"iso_value\", \"Isovalue for contour\", true, 0, \"iso-value\");\n\t\tValueArg<double> gridGranularity(\"s\", \"grid_granularity\", \"Grid grid granularity\",true, 0.25, \"dh\");\n\n\t\tcmd.add(testFunction);\n\t\tcmd.add(outputArg);\n\t\tcmd.add(isoValue);\n\t\tcmd.add(gridGranularity);\n\n\t\tcmd.parse(argc, argv);\n\t\tstd::string output = outputArg.getValue();\n\t\tstd::string function = testFunction.getValue();\n\n\t\tdouble levelset = isoValue.getValue();\n\n\t\tHamFunction<double> hf;\n\t\tSphereFunction<double> sf;\n\t\tMarschnerLobb<double> mf(6, 0.25);\n\n\t\tif(function == std::string(\"lobb\")){\n\t\t\tdbcc.contour<MarschnerLobb<double>, double, double>(\n\t\t\t\t&mf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdfcc.contour<MarschnerLobb<double>, double, double>(\n\t\t\t\t&mf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdcc.contour<MarschnerLobb<double>, double, double>(\n\t\t\t\t&mf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t}else if(function == std::string(\"ham\")){\n\t\t\tdbcc.contour<HamFunction<double>, double, double>(\n\t\t\t\t&hf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdfcc.contour<HamFunction<double>, double, double>(\n\t\t\t\t&hf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdcc.contour<HamFunction<double>, double, double>(\n\t\t\t\t&hf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t}else if(function == std::string(\"sphere\")){\n\t\t\tdbcc.contour<SphereFunction<double> , double, double>(\n\t\t\t\t&sf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdfcc.contour<SphereFunction<double> , double, double>(\n\t\t\t\t&sf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t\tdcc.contour<SphereFunction<double> , double, double>(\n\t\t\t\t&sf, levelset, 1./(2.*100),\n\t\t\t\tvector3<double>(0,0,0), \n\t\t\t\tvector3<double>(1,1,1)\n\t\t\t);\n\t\t}\n\n\n\t\tdbcc.writeSurface(output + std::string(\".bcc.ply\"));\n\t\tdfcc.writeSurface(output + std::string(\".fcc.ply\"));\n\t\tdcc.writeSurface(output + std::string(\".cc.ply\"));\n\n\t}catch (ArgException &e) {\n\t\tcerr << \"error: \" << e.error() << \" for arg \" << e.argId() << endl; \n\t}catch (char const* e) {\n\t\tcerr << e << endl; \n\t}\n}\n\n\n", "meta": {"hexsha": "e1df737db0054c0b2366a4dfe0a83b225d44e125", "size": 6130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jjh13/dual-marching", "max_stars_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "jjh13/dual-marching", "max_issues_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-05-05T04:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-08T14:57:25.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "jjh13/dual-marching", "max_forks_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.197044335, "max_line_length": 402, "alphanum_fraction": 0.6269168026, "num_tokens": 2251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.592861674312308}}
{"text": "#include \"runtime.h\"\n\n#include <cmath>\n#include <time.h>\n#include <chrono>\n#include <vector>\n\n#include \"timers.h\"\n#include \"stdio.h\"\n\n#ifdef EIGEN\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\nusing namespace Eigen;\n#endif\n\nextern \"C\" {\nint loc(int v0, int v1, int *neighbors_start, int *neighbors) {\n  int l = neighbors_start[v0];\n  while(neighbors[l] != v1) l++;\n  return l;\n}\n\ndouble atan2_f64(double y, double x) {\n  return atan2(y, x);\n}\n\nfloat atan2_f32(float y, float x) {\n  double d_y = y;\n  double d_x = x;\n  return (float)atan2(d_y, d_x);\n}\n\ndouble tan_f64(double x) {\n  return tan(x);\n}\n\nfloat tan_f32(float x) {\n  double d_x = x;\n  return (float)tan(d_x);\n}\n\ndouble asin_f64(double x) {\n  return asin(x);\n}\n\nfloat asin_f32(float x) {\n  double d_x = x;\n  return (float)asin(d_x);\n}\n\ndouble acos_f64(double x) {\n  return acos(x);\n}\n\nfloat acos_f32(float x) {\n  double d_x = x;\n  return (float)acos(d_x);\n}\n\ndouble max_f64(double a,double b) {\n  return max(a,b);\n}\n\nfloat max_f32(float a, float b) {\n  double d_a = a;\n  double d_b = b;\n  return (float)max(d_a,d_b);\n}\n\ndouble min_f64(double a,double b) {\n  return min(a,b);\n}\n\nfloat min_f32(float a, float b) {\n  double d_a = a;\n  double d_b = b;\n  return (float)min(d_a,d_b);\n}\n\ndouble cbrt_f64(double x) {\n  return cbrt(x);\n}\n\nfloat cbrt_f32(float x) {\n  double d_x = x;\n  return (float)cbrt(d_x);\n}\n\ndouble det3_f64(double * a){\n  return a[0] * (a[4]*a[8]-a[5]*a[7])\n       - a[1] * (a[3]*a[8]-a[5]*a[6])\n       + a[2] * (a[3]*a[7]-a[4]*a[6]);\n}\n\nfloat det3_f32(float * a){\n  return a[0] * (a[4]*a[8]-a[5]*a[7])\n       - a[1] * (a[3]*a[8]-a[5]*a[6])\n       + a[2] * (a[3]*a[7]-a[4]*a[6]);\n}\n\ndouble det2_f64(double * a){\n  return a[0] * a[3] - a[1] * a[2];\n}\n\nfloat det2_f32(float * a){ \n  return a[0] * a[3] - a[1] * a[2];\n}\n\ndouble det4_f64(double * a){\n  double det0 = a[5] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[9]*a[15]-a[11]*a[13])\n\t   + a[7] * (a[9]*a[14]-a[10]*a[13]);\n  double det1 = a[4] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[14]-a[10]*a[12]);\n  double det2 = a[4] * (a[9]*a[15]-a[11]*a[13])\n\t   - a[5] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[13]-a[9]*a[12]);\n  double det3 = a[4] * (a[9]*a[14]-a[10]*a[13])\n\t   - a[5] * (a[8]*a[14]-a[10]*a[12])\n\t   + a[6] * (a[8]*a[13]-a[9]*a[12]);\n  return a[0]*det0 - a[1]*det1 + a[2]*det2 - a[3]*det3;\n}\n\nfloat det4_f32(float * a){\n  float det0 = a[5] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[9]*a[15]-a[11]*a[13])\n\t   + a[7] * (a[9]*a[14]-a[10]*a[13]);\n  float det1 = a[4] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[14]-a[10]*a[12]);\n  float det2 = a[4] * (a[9]*a[15]-a[11]*a[13])\n\t   - a[5] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[13]-a[9]*a[12]);\n  float det3 = a[4] * (a[9]*a[14]-a[10]*a[13])\n\t   - a[5] * (a[8]*a[14]-a[10]*a[12])\n\t   + a[6] * (a[8]*a[13]-a[9]*a[12]);\n  return a[0]*det0 - a[1]*det1 + a[2]*det2 - a[3]*det3;\n}\n\nvoid inv3_f64(double * a, double * inv){\n  double cof00 = a[4]*a[8]-a[5]*a[7];\n  double cof01 =-a[3]*a[8]+a[5]*a[6];\n  double cof02 = a[3]*a[7]-a[4]*a[6];\n\n  double cof10 =-a[1]*a[8]+a[2]*a[7];\n  double cof11 = a[0]*a[8]-a[2]*a[6];\n  double cof12 =-a[0]*a[7]+a[1]*a[6];\n\n  double cof20 = a[1]*a[5]-a[2]*a[4];\n  double cof21 =-a[0]*a[5]+a[2]*a[3];\n  double cof22 = a[0]*a[4]-a[1]*a[3];\n\n  double determ = a[0] * cof00 + a[1] * cof01 + a[2]*cof02;\n\n  determ = 1.0/determ;\n  inv[0] = cof00 * determ;\n  inv[1] = cof10 * determ;\n  inv[2] = cof20 * determ;\n\n  inv[3] = cof01 * determ;\n  inv[4] = cof11 * determ;\n  inv[5] = cof21 * determ;\n\n  inv[6] = cof02 * determ;\n  inv[7] = cof12 * determ;\n  inv[8] = cof22 * determ;\n}\n\nvoid inv3_f32(float * a, float * inv){\n  float cof00 = a[4]*a[8]-a[5]*a[7];\n  float cof01 =-a[3]*a[8]+a[5]*a[6];\n  float cof02 = a[3]*a[7]-a[4]*a[6];\n\n  float cof10 =-a[1]*a[8]+a[2]*a[7];\n  float cof11 = a[0]*a[8]-a[2]*a[6];\n  float cof12 =-a[0]*a[7]+a[1]*a[6];\n\n  float cof20 = a[1]*a[5]-a[2]*a[4];\n  float cof21 =-a[0]*a[5]+a[2]*a[3];\n  float cof22 = a[0]*a[4]-a[1]*a[3];\n\n  float determ = a[0] * cof00 + a[1] * cof01 + a[2]*cof02;\n\n  determ = 1.0/determ;\n  inv[0] = cof00 * determ;\n  inv[1] = cof10 * determ;\n  inv[2] = cof20 * determ;\n\n  inv[3] = cof01 * determ;\n  inv[4] = cof11 * determ;\n  inv[5] = cof21 * determ;\n\n  inv[6] = cof02 * determ;\n  inv[7] = cof12 * determ;\n  inv[8] = cof22 * determ;\n}\n\nvoid inv2_f64(double * a, double * inv){\n  double determ = a[0] * a[3] - a[1] * a[2];\n\n  determ = 1.0/determ;\n  inv[0] = a[3] * determ;\n  inv[1] = -a[1] * determ;\n  inv[2] = -a[2] * determ;\n  inv[3] = a[0] * determ;\n}\n\nvoid inv2_f32(float * a, float * inv){\n  float determ = a[0] * a[3] - a[1] * a[2];\n\n  determ = 1.0/determ;\n  inv[0] = a[3] * determ;\n  inv[1] = -a[1] * determ;\n  inv[2] = -a[2] * determ;\n  inv[3] = a[0] * determ;\n}\n\nvoid inv4_f64(double * a, double * inv){\n  double det0 = a[5] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[9]*a[15]-a[11]*a[13])\n\t   + a[7] * (a[9]*a[14]-a[10]*a[13]);\n  double det1 = a[4] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[14]-a[10]*a[12]);\n  double det2 = a[4] * (a[9]*a[15]-a[11]*a[13])\n\t   - a[5] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[13]-a[9]*a[12]);\n  double det3 = a[4] * (a[9]*a[14]-a[10]*a[13])\n\t   - a[5] * (a[8]*a[14]-a[10]*a[12])\n\t   + a[6] * (a[8]*a[13]-a[9]*a[12]);\n  double determ = a[0]*det0 - a[1]*det1 + a[2]*det2 - a[3]*det3;\n\n  determ = 1.0/determ;\n  inv[0] = (a[5]*a[10]*a[15] + a[6]*a[11]*a[13] + a[7]*a[9]*a[14] - a[5]*a[11]*a[14] - a[6]*a[9]*a[15] - a[7]*a[10]*a[13]) * determ;\n  inv[1] = (a[1]*a[11]*a[14] + a[2]*a[9]*a[15] + a[3]*a[10]*a[13] - a[1]*a[10]*a[15] - a[2]*a[11]*a[13] - a[3]*a[9]*a[14]) * determ;\n  inv[2] = (a[1]*a[6]*a[15] + a[2]*a[7]*a[13] + a[3]*a[5]*a[14] - a[1]*a[7]*a[14] - a[2]*a[5]*a[15] - a[3]*a[6]*a[13]) * determ;\n  inv[3] = (a[1]*a[7]*a[10] + a[2]*a[5]*a[11] + a[3]*a[6]*a[9] - a[1]*a[6]*a[11] - a[2]*a[7]*a[9] - a[3]*a[5]*a[10]) * determ;\n  inv[4] = (a[4]*a[11]*a[14] + a[6]*a[8]*a[15] + a[7]*a[10]*a[12] - a[4]*a[10]*a[15] - a[6]*a[11]*a[12] - a[7]*a[8]*a[14]) * determ;\n  inv[5] = (a[0]*a[10]*a[15] + a[2]*a[11]*a[12] + a[3]*a[8]*a[14] - a[0]*a[11]*a[14] - a[2]*a[8]*a[15] - a[3]*a[10]*a[12]) * determ;\n  inv[6] = (a[0]*a[7]*a[14] + a[2]*a[4]*a[15] + a[3]*a[6]*a[12] - a[0]*a[6]*a[15] - a[2]*a[7]*a[12] - a[3]*a[4]*a[14]) * determ;\n  inv[7] = (a[0]*a[6]*a[11] + a[2]*a[7]*a[8] + a[3]*a[4]*a[10] - a[0]*a[7]*a[10] - a[2]*a[4]*a[11] - a[3]*a[6]*a[8]) * determ;\n  inv[8] = (a[4]*a[9]*a[15] + a[5]*a[11]*a[12] + a[7]*a[8]*a[13] - a[4]*a[11]*a[13] - a[5]*a[8]*a[15] - a[7]*a[9]*a[12]) * determ;\n  inv[9] = (a[0]*a[11]*a[13] + a[1]*a[8]*a[15] + a[3]*a[9]*a[12] - a[0]*a[9]*a[15] - a[1]*a[11]*a[12] - a[3]*a[8]*a[13]) * determ;\n  inv[10] = (a[0]*a[5]*a[15] + a[1]*a[7]*a[12] + a[3]*a[4]*a[13] - a[0]*a[7]*a[13] - a[1]*a[4]*a[15] - a[3]*a[5]*a[12]) *  determ;\n  inv[11] = (a[0]*a[7]*a[9] + a[1]*a[4]*a[11] + a[3]*a[5]*a[8] - a[0]*a[5]*a[11] - a[1]*a[7]*a[8] - a[3]*a[4]*a[9]) * determ;\n  inv[12] = (a[4]*a[10]*a[13] + a[5]*a[8]*a[14] + a[6]*a[9]*a[12] - a[4]*a[9]*a[14] - a[5]*a[10]*a[12] - a[6]*a[8]*a[13]) * determ;\n  inv[13] = (a[0]*a[9]*a[14] + a[1]*a[10]*a[12] + a[2]*a[8]*a[13] - a[0]*a[10]*a[13] - a[1]*a[8]*a[14] - a[2]*a[9]*a[12]) * determ;\n  inv[14] = (a[0]*a[6]*a[13] + a[1]*a[4]*a[14] + a[2]*a[5]*a[12] - a[0]*a[5]*a[14] - a[1]*a[6]*a[12] - a[2]*a[4]*a[13]) * determ;\n  inv[15] = (a[0]*a[5]*a[10] + a[1]*a[6]*a[8] + a[2]*a[4]*a[9] - a[0]*a[6]*a[9] - a[1]*a[4]*a[10] - a[2]*a[5]*a[8]) * determ;\n}\n\nvoid inv4_f32(float * a, float * inv){\n  float det0 = a[5] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[9]*a[15]-a[11]*a[13])\n\t   + a[7] * (a[9]*a[14]-a[10]*a[13]);\n  float det1 = a[4] * (a[10]*a[15]-a[11]*a[14])\n\t   - a[6] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[14]-a[10]*a[12]);\n  float det2 = a[4] * (a[9]*a[15]-a[11]*a[13])\n\t   - a[5] * (a[8]*a[15]-a[11]*a[12])\n\t   + a[7] * (a[8]*a[13]-a[9]*a[12]);\n  float det3 = a[4] * (a[9]*a[14]-a[10]*a[13])\n\t   - a[5] * (a[8]*a[14]-a[10]*a[12])\n\t   + a[6] * (a[8]*a[13]-a[9]*a[12]);\n  float determ = a[0]*det0 - a[1]*det1 + a[2]*det2 - a[3]*det3;\n\n  determ = 1.0/determ;\n  inv[0] = (a[5]*a[10]*a[15] + a[6]*a[11]*a[13] + a[7]*a[9]*a[14] - a[5]*a[11]*a[14] - a[6]*a[9]*a[15] - a[7]*a[10]*a[13]) * determ;\n  inv[1] = (a[1]*a[11]*a[14] + a[2]*a[9]*a[15] + a[3]*a[10]*a[13] - a[1]*a[10]*a[15] - a[2]*a[11]*a[13] - a[3]*a[9]*a[14]) * determ;\n  inv[2] = (a[1]*a[6]*a[15] + a[2]*a[7]*a[13] + a[3]*a[5]*a[14] - a[1]*a[7]*a[14] - a[2]*a[5]*a[15] - a[3]*a[6]*a[13]) * determ;\n  inv[3] = (a[1]*a[7]*a[10] + a[2]*a[5]*a[11] + a[3]*a[6]*a[9] - a[1]*a[6]*a[11] - a[2]*a[7]*a[9] - a[3]*a[5]*a[10]) * determ;\n  inv[4] = (a[4]*a[11]*a[14] + a[6]*a[8]*a[15] + a[7]*a[10]*a[12] - a[4]*a[10]*a[15] - a[6]*a[11]*a[12] - a[7]*a[8]*a[14]) * determ;\n  inv[5] = (a[0]*a[10]*a[15] + a[2]*a[11]*a[12] + a[3]*a[8]*a[14] - a[0]*a[11]*a[14] - a[2]*a[8]*a[15] - a[3]*a[10]*a[12]) * determ;\n  inv[6] = (a[0]*a[7]*a[14] + a[2]*a[4]*a[15] + a[3]*a[6]*a[12] - a[0]*a[6]*a[15] - a[2]*a[7]*a[12] - a[3]*a[4]*a[14]) * determ;\n  inv[7] = (a[0]*a[6]*a[11] + a[2]*a[7]*a[8] + a[3]*a[4]*a[10] - a[0]*a[7]*a[10] - a[2]*a[4]*a[11] - a[3]*a[6]*a[8]) * determ;\n  inv[8] = (a[4]*a[9]*a[15] + a[5]*a[11]*a[12] + a[7]*a[8]*a[13] - a[4]*a[11]*a[13] - a[5]*a[8]*a[15] - a[7]*a[9]*a[12]) * determ;\n  inv[9] = (a[0]*a[11]*a[13] + a[1]*a[8]*a[15] + a[3]*a[9]*a[12] - a[0]*a[9]*a[15] - a[1]*a[11]*a[12] - a[3]*a[8]*a[13]) * determ;\n  inv[10] = (a[0]*a[5]*a[15] + a[1]*a[7]*a[12] + a[3]*a[4]*a[13] - a[0]*a[7]*a[13] - a[1]*a[4]*a[15] - a[3]*a[5]*a[12]) *  determ;\n  inv[11] = (a[0]*a[7]*a[9] + a[1]*a[4]*a[11] + a[3]*a[5]*a[8] - a[0]*a[5]*a[11] - a[1]*a[7]*a[8] - a[3]*a[4]*a[9]) * determ;\n  inv[12] = (a[4]*a[10]*a[13] + a[5]*a[8]*a[14] + a[6]*a[9]*a[12] - a[4]*a[9]*a[14] - a[5]*a[10]*a[12] - a[6]*a[8]*a[13]) * determ;\n  inv[13] = (a[0]*a[9]*a[14] + a[1]*a[10]*a[12] + a[2]*a[8]*a[13] - a[0]*a[10]*a[13] - a[1]*a[8]*a[14] - a[2]*a[9]*a[12]) * determ;\n  inv[14] = (a[0]*a[6]*a[13] + a[1]*a[4]*a[14] + a[2]*a[5]*a[12] - a[0]*a[5]*a[14] - a[1]*a[6]*a[12] - a[2]*a[4]*a[13]) * determ;\n  inv[15] = (a[0]*a[5]*a[10] + a[1]*a[6]*a[8] + a[2]*a[4]*a[9] - a[0]*a[6]*a[9] - a[1]*a[4]*a[10] - a[2]*a[5]*a[8]) * determ;\n}\n\ndouble complexNorm_f64(double r, double i) {\n  return sqrt(r*r+i*i);\n}\n\nfloat complexNorm_f32(float r, float i) {\n  return sqrt(r*r+i*i);\n}\n\nvoid storeTime(int i, double value) {\n  simit::ir::TimerStorage::getInstance().storeTime(i, value);\n}\n\ndouble simitClock() {\n  using namespace std::chrono;\n  auto t = high_resolution_clock::now();\n  time_point<high_resolution_clock,microseconds> usec = time_point_cast<microseconds>(t);\n  return (double)(usec.time_since_epoch().count());\n}\n} // extern \"C\"\n\n\n/// Temporary external spmm implementation until Simit supports assembling\n/// matrix indices during computation.\ntemplate <typename Float>\nint spmm(int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n         int Bnn, int Bmm, Float* Bvals,\n         int Cn,  int Cm,  int* Crowptr, int* Ccolidx,\n         int Cnn, int Cmm, Float* Cvals,\n         int An,  int Am,  int** Arowptr, int** Acolidx,\n         int Ann, int Amm, Float** Avals) {\n#ifdef EIGEN\n  auto B = csr2eigen<Float,RowMajor>(Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals);\n  auto C = csr2eigen<Float,RowMajor>(Cn, Cm, Crowptr, Ccolidx, Cnn, Cmm, Cvals);\n\n  SparseMatrix<Float,RowMajor> A(An, Am);\n  A = B*C;\n  eigen2csr(A, An, Am, Arowptr, Acolidx, Ann, Amm, Avals);\n#else\n  simit_ierror << \"extern spmm requires Eigen\";\n#endif\n  return 0;\n}\nextern \"C\" int sspmm(int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                     int Bnn, int Bmm, float* Bvals,\n                     int Cn,  int Cm,  int* Crowptr, int* Ccolidx,\n                     int Cnn, int Cmm, float* Cvals,\n                     int An,  int Am,  int** Arowptr, int** Acolidx,\n                     int Ann, int Amm, float** Avals) {\n  return spmm(Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n              Cn, Cm, Crowptr, Ccolidx, Cnn, Cmm, Cvals,\n              An, Am, Arowptr, Acolidx, Ann, Amm, Avals);\n}\nextern \"C\" int dspmm(int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                     int Bnn, int Bmm, double* Bvals,\n                     int Cn,  int Cm,  int* Crowptr, int* Ccolidx,\n                     int Cnn, int Cmm, double* Cvals,\n                     int An,  int Am,  int** Arowptr, int** Acolidx,\n                     int Ann, int Amm, double** Avals) {\n  return spmm(Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n              Cn, Cm, Crowptr, Ccolidx, Cnn, Cmm, Cvals,\n              An, Am, Arowptr, Acolidx, Ann, Amm, Avals);\n}\n\n\n// Solvers\n#define SOLVER_ERROR                                            \\\ndo {                                                            \\\n  simit_ierror << \"Solvers require that Simit was built with Eigen.\"; \\\n} while (false)\n\ntemplate <typename Float>\nvoid solve(int n,  int m,  int* rowptr, int* colidx,\n           int nn, int mm, Float* Avals, Float* bvals, Float* xvals) {\n#ifdef EIGEN\n  auto A = csr2eigen<Float,ColMajor>(n, m, rowptr, colidx, nn, mm, Avals);\n  auto x = new Map<Matrix<Float,Dynamic,1>>(xvals, m);\n  auto b = new Map<Matrix<Float,Dynamic,1>>(bvals, n);\n\n  SparseLU<SparseMatrix<Float, ColMajor>> solver;\n  solver.compute(A);\n  *x = solver.solve(*b);\n#else\n  SOLVER_ERROR;\n#endif\n}\nextern \"C\" void cMatSolve_f64(int n,  int m,  int* rowptr, int* colidx,\n                              int nn, int mm, double* A, double* x, double* b) {\n  return solve(n, m, rowptr, colidx, nn, mm, A, x, b);\n}\nextern \"C\" void cMatSolve_f32(int n,  int m,  int* rowptr, int* colidx,\n                              int nn, int mm, float* A, float* x, float* b) {\n  return solve(n, m, rowptr, colidx, nn, mm, A, x, b);\n}\n\n/// LU factorization. Returns a solver object that can be used with\n/// `lusolve` and `lumatsolve`. The solver object must be freed using\n/// `lufree`.\ntemplate <typename Float>\nint lu(int An,  int Am,  int* Arowptr, int* Acolidx,\n       int Ann, int Amm, Float* Avals,\n       void** solverPtr) {\n#ifdef EIGEN\n  auto A = csr2eigen<Float,Eigen::ColMajor>(An, Am, Arowptr, Acolidx,\n                                            Ann, Amm, Avals);\n  auto solver = new SparseLU<SparseMatrix<Float,ColMajor>>();\n  solver->compute(A);\n  *solverPtr = static_cast<void*>(solver);\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int slu(int An,  int Am,  int* Arowptr, int* Acolidx,\n                   int Ann, int Amm, float* Avals,\n                   void** solver) {\n  return lu(An, Am, Arowptr, Acolidx, Ann, Amm, Avals, solver);\n}\nextern \"C\" int dlu(int An,  int Am,  int* Arowptr, int* Acolidx,\n                   int Ann, int Amm, double* Avals,\n                   void** solver) {\n  return lu(An, Am, Arowptr, Acolidx, Ann, Amm, Avals, solver);\n}\n\n\n/// Free an LU solver.\ntemplate <typename Float>\nint lufree(void** solverPtr) {\n#ifdef EIGEN\n  auto solver=static_cast<SparseLU<SparseMatrix<Float,ColMajor>>*>(*solverPtr);\n  delete solver;\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int slufree(void** solverPtr) {\n  return lufree<float>(solverPtr);\n}\nextern \"C\" int dlufree(void** solverPtr){\n  return lufree<double>(solverPtr);\n}\n\n/// Solve `t=L^{-1}*b` and `x=L'^{-1}*t`, where `A=LL'` is the matrix that was\n/// factorized with the provided solver using `chol`.\ntemplate <typename Float>\nint lusolve(void** solverPtr, int nb, Float *bvals, int nx, Float *xvals) {\n#ifdef EIGEN\n  auto solver=static_cast<SparseLU<SparseMatrix<Float,ColMajor>>*>(*solverPtr);\n  auto b = dense2eigen(nb, bvals);\n  auto x = Eigen::Matrix<Float,Eigen::Dynamic,1>(nx);\n  x = solver->solve(b);\n  for (int i=0; i<nx; ++i) {\n    xvals[i] = x(i);\n  }\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" {\n  int slusolve(void** solverPtr, int bn, float *bvals, int xn, float *xvals) {\n    return lusolve(solverPtr, bn, bvals, xn, xvals);\n  }\n  int dlusolve(void** solverPtr, int bn, double *bvals, int xn, double *xvals){\n    return lusolve(solverPtr, bn, bvals, xn, xvals);\n  }\n}\n\n/// Solve `T=L^{-1}*B` and `X=L'^{-1}*T`, where `A=LL'` is the matrix that was\n/// factorized with the provided solver using `chol`.\ntemplate <typename Float>\nint lumatsolve(void** solverPtr,\n                int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                int Bnn, int Bmm, Float* Bvals,\n                int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                int Xnn, int Xmm, Float** Xvals){\n#ifdef EIGEN\n  auto solver=static_cast<SparseLU<SparseMatrix<Float,ColMajor>>*>(*solverPtr);\n  auto B = csr2eigen<Float,ColMajor>(Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals);\n  SparseMatrix<Float> X(Xn, Xm);\n  X = solver->solve(B);\n  X = X.transpose();\n  eigen2csr<Float>(X, Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int slumatsolve(void** solverPtr,\n                            int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                            int Bnn, int Bmm, float* Bvals,\n                            int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                            int Xnn, int Xmm, float** Xvals) {\n  return lumatsolve(solverPtr,\n                     Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n                     Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n}\nextern \"C\" int dlumatsolve(void** solverPtr,\n                            int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                            int Bnn, int Bmm, double* Bvals,\n                            int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                            int Xnn, int Xmm, double** Xvals) {\n  return lumatsolve(solverPtr,\n                     Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n                     Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n}\n\n\n/// Cholesky factorization. Returns a solver object that can be used with\n/// `lltsolve` and `lltmatsolve`. The solver object must be freed using\n/// `cholfree`.\ntemplate <typename Float>\nint chol(int An,  int Am,  int* Arowptr, int* Acolidx,\n         int Ann, int Amm, Float* Avals,\n         void** solverPtr) {\n#ifdef EIGEN\n  auto A = csr2eigen<Float,Eigen::ColMajor>(An, Am, Arowptr, Acolidx,\n                                            Ann, Amm, Avals);\n  auto solver = new SimplicialCholesky<SparseMatrix<Float>>();\n  solver->compute(A);\n  *solverPtr = static_cast<void*>(solver);\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int schol(int An,  int Am,  int* Arowptr, int* Acolidx,\n                     int Ann, int Amm, float* Avals,\n                     void** solver) {\n  return chol(An, Am, Arowptr, Acolidx, Ann, Amm, Avals, solver);\n}\nextern \"C\" int dchol(int An,  int Am,  int* Arowptr, int* Acolidx,\n                     int Ann, int Amm, double* Avals,\n                     void** solver) {\n  return chol(An, Am, Arowptr, Acolidx, Ann, Amm, Avals, solver);\n}\n\n/// Free a Cholesky solver.\ntemplate <typename Float>\nint cholfree(void** solverPtr) {\n#ifdef EIGEN\n  auto solver=static_cast<SimplicialCholesky<SparseMatrix<Float>>*>(*solverPtr);\n  delete solver;\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int scholfree(void** solverPtr) {\n  return cholfree<float>(solverPtr);\n}\nextern \"C\" int dcholfree(void** solverPtr){\n  return cholfree<double>(solverPtr);\n}\n\n/// Solve `t=L^{-1}*b` and `x=L'^{-1}*t`, where `A=LL'` is the matrix that was\n/// factorized with the provided solver using `chol`.\ntemplate <typename Float>\nint lltsolve(void** solverPtr, int nb, Float *bvals, int nx, Float *xvals) {\n#ifdef EIGEN\n  auto solver=static_cast<SimplicialCholesky<SparseMatrix<Float>>*>(*solverPtr);\n  auto b = dense2eigen(nb, bvals);\n  auto x = Eigen::Matrix<Float,Eigen::Dynamic,1>(nx);\n  x = solver->solve(b);\n  for (int i=0; i<nx; ++i) {\n    xvals[i] = x(i);\n  }\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" {\nint slltsolve(void** solverPtr, int bn, float *bvals, int xn, float *xvals) {\n  return lltsolve(solverPtr, bn, bvals, xn, xvals);\n}\nint dlltsolve(void** solverPtr, int bn, double *bvals, int xn, double *xvals){\n  return lltsolve(solverPtr, bn, bvals, xn, xvals);\n}\n}\n\n/// Solve `T=L^{-1}*B` and `X=L'^{-1}*T`, where `A=LL'` is the matrix that was\n/// factorized with the provided solver using `chol`.\ntemplate <typename Float>\nint lltmatsolve(void** solverPtr,\n                 int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                 int Bnn, int Bmm, Float* Bvals,\n                 int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                 int Xnn, int Xmm, Float** Xvals){\n#ifdef EIGEN\n  auto solver=static_cast<SimplicialCholesky<SparseMatrix<Float,ColMajor>>*>(*solverPtr);\n  auto B = csr2eigen<Float,ColMajor>(Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals);\n  SparseMatrix<Float> X(Xn, Xm);\n  X = solver->solve(B);\n  X = X.transpose();\n  eigen2csr<Float>(X, Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int slltmatsolve(void** solverPtr,\n                            int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                            int Bnn, int Bmm, float* Bvals,\n                            int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                            int Xnn, int Xmm, float** Xvals) {\n  return lltmatsolve(solverPtr,\n                      Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n                      Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n}\nextern \"C\" int dlltmatsolve(void** solverPtr,\n                            int Bn,  int Bm,  int* Browptr, int* Bcolidx,\n                            int Bnn, int Bmm, double* Bvals,\n                            int Xn,  int Xm,  int** Xrowptr, int** Xcolidx,\n                            int Xnn, int Xmm, double** Xvals) {\n  return lltmatsolve(solverPtr,\n                      Bn, Bm, Browptr, Bcolidx, Bnn, Bmm, Bvals,\n                      Xn, Xm, Xrowptr, Xcolidx, Xnn, Xmm, Xvals);\n}\n\n/// cross product between 2 vectors3D\ntemplate <typename Float>\nvoid cross(int an, Float* a, int bn, Float* b, int cn, Float* c){\n  assert(an==3 && bn==3);\n  c[0] = a[1]*b[2]-a[2]*b[1];\n  c[1] = a[2]*b[0]-a[0]*b[2];\n  c[2] = a[0]*b[1]-a[1]*b[0];\n}\nextern \"C\" void scross(int an, float* a, int bn, float* b, int cn, float* c) {\n  return cross(an, a, bn, b, cn, c);\n}\nextern \"C\" void dcross(int an, double* a, int bn, double* b, int cn, double* c) {\n  return cross(an, a, bn, b, cn, c);\n}\n\ntemplate <typename Float>\nint triangularSolve(int An,  int Am,  int* Arowptr, int* Acolidx,\n\t\t\t     int Ann, int Amm, Float* Avals,\n\t\t\t\t int nb, Float *bvals, int nx, Float *xvals) {\n#ifdef EIGEN\n  auto A = csr2eigen<Float,Eigen::ColMajor>(An, Am, Arowptr, Acolidx,\n                                            Ann, Amm, Avals);\n  auto b = dense2eigen(nb, bvals);\n  auto x = Eigen::Matrix<Float,Eigen::Dynamic,1>(nx);\n  x = TriangularView<SparseMatrix<Float,ColMajor>,Lower>(A).solve(b);\n  for (int i=0; i<nx; ++i) {\n    xvals[i] = x(i);\n  }\n#else\n  SOLVER_ERROR;\n#endif\n  return 0;\n}\nextern \"C\" int striangularSolve(int An,  int Am,  int* Arowptr, int* Acolidx,\n                   int Ann, int Amm, float* Avals,\n\t\t\t\t   int nb, float *bvals, int nx, float *xvals) {\n  return triangularSolve(An, Am, Arowptr, Acolidx, Ann, Amm,\n                         Avals, nb, bvals, nx, xvals);\n}\nextern \"C\" int dtriangularSolve(int An,  int Am,  int* Arowptr, int* Acolidx,\n                   int Ann, int Amm, double* Avals,\n\t\t\t\t   int nb, double *bvals, int nx, double *xvals) {\n  return triangularSolve(An, Am, Arowptr, Acolidx, Ann, Amm,\n                         Avals, nb, bvals, nx, xvals);\n}\n\n\n", "meta": {"hexsha": "1398e7fdd2639b29c0cf1c17508ecfcdde9c649e", "size": 23538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/runtime.cpp", "max_stars_repo_name": "BillXu2000/simit", "max_stars_repo_head_hexsha": "bfdb5f5d558a4ea2decf642e8e3e3854deddb5ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 496.0, "max_stars_repo_stars_event_min_datetime": "2016-06-10T04:16:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:37:03.000Z", "max_issues_repo_path": "src/runtime.cpp", "max_issues_repo_name": "BillXu2000/simit", "max_issues_repo_head_hexsha": "bfdb5f5d558a4ea2decf642e8e3e3854deddb5ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2016-07-26T13:18:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T08:54:18.000Z", "max_forks_repo_path": "src/runtime.cpp", "max_forks_repo_name": "BillXu2000/simit", "max_forks_repo_head_hexsha": "bfdb5f5d558a4ea2decf642e8e3e3854deddb5ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2016-07-22T17:15:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T03:18:42.000Z", "avg_line_length": 35.881097561, "max_line_length": 132, "alphanum_fraction": 0.5352621293, "num_tokens": 10097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5927984462268536}}
{"text": "// Some sort of comment up top describing the code\n// This is a 1D Euler equation solver using the finite volume method\n// Uses MUSCL scheme\n// Think about what I want to use for time integration. \n\n// This is the command needed to compile the code\n// g++ -I ../../../eigen-3.4.0/ main.cpp fvm_1d_functions.cpp -o runSim.out && ./runSim.out\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"fvm_1D_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n    \n    // Set physical constants\n    const double gasGamma = 5./3.;\n\n    // Set important constants for code\n    const int maxIter = 100;            // The maximum number of iterations \n    const double CFL = 0.9;             // Set CFL number\n\n    // Set grid parameters\n    const int nCells = 4;      // Number of cells in the domain. Note these set based on their cell centered values\n    const int numGhost = 2;      // Number of ghost cells on either side of the domain\n\n    // Set domain parameters\n    const double xLeft = 0;   // Left boundary \n    const double xRight = 1;   // Right boundary\n\n    // Calculate grid parameters\n    const int nNodes = nCells + 1;  // There is one more node than there are cells\n    const int totalNCells = nCells + 2*numGhost;   // Total number of cells, including ghost cells\n    const int totalNNodes = totalNCells + 1; // Total number of nodes is one plus total number of cells\n\n    // Calculate domain length\n    const double L = xRight - xLeft; // Get total domain length\n    \n    // Calculate dx\n    const double dx = L / nCells;\n\n    // Make the cell centered grid\n    ArrayXd x = makeGrid(totalNCells, numGhost, xLeft, dx);\n\n    // Set initial conditions based on Sod paper on shock tube simulations\n    // See https://doi.org/10.1016/0021-9991(78)90023-2\n    // The simulation is done in normalized units    \n    // The initial states are presented in primitive variables (rho, u, p)  \n    Array3d leftStates;\n    leftStates << 1.0, 0.0, 1.0;\n    Array3d rightStates;\n    rightStates << 0.125, 0.0, 0.1;\n\n    // Set initial shock location\n    double x0 = 0.5;\n    \n    // Initialize an array of primitive variables\n    Array<ArrayXd, 3, 1> V;\n    \n    // There is an interface at some x0\n    // To the left is one set of states, to the right is another set of states  \n    // Loop through the variables\n    for (int var = 0; var < 3; var++) {\n        // Initialize an array of zeros\n        V(var) = ArrayXd::Zero(totalNCells);\n\n        // Iterate through x\n        for (int i = 0; i < totalNCells; i++) {\n            // If we are less than x0, then the IC is the left state. \n            // Note that this is a simplified IC in that it will move the initial shock location based on the resolution. This should have a minimal impact on sufficiently resolved sims\n            if (x(i) <= x0) {\n                V(var)(i) = leftStates(var);\n            }\n            else {\n                V(var)(i) = rightStates(var);\n            }\n        }\n    }\n\n    // Maybe think about a way to specify what BCs to use here.     \n\n    // Initialize the conserved variables\n    Array<ArrayXd, 3, 1> Q;\n    for (int var = 0; var < 3; var++) {\n        // Initialize an array of zeros\n        Q(var) = ArrayXd::Zero(totalNCells);\n    }\n\n    // Calculate the conserved variables based on the primitive variables\n    prim2cons(gasGamma, V, Q);\n\n    // Next, start populating the run sim function\n    // Choose which ode solver to use and figure out a nice way to do the time integration as a loop\n    // Look into SSPRK methods. maybe 4 stage 3rd order? Gets us a nice CFL condition\n\n    // Think about how I want to setup my variables. Do I use rho, u, p or one big variable? Maybe the big variable is the way to go? \n    // Each conservation law is the same general idea, just the values internally will be different\n    \n    // Maybe put everything below this in some sort of \"runSim\" function?\n    //runSimulation_FVM1D(gasGamma, maxIter, nCells, numGhost, xLeft, xRight);\n    // std::cout << \"Hello World!\" << endl;\n\n\n    Array<ArrayXd, 3, 1> test;\n    \n    test(0) = ArrayXd::Zero(5) + 5.;\n    test(1) = ArrayXd::Zero(5) + 1.;\n    test(2) = ArrayXd::Zero(5) + 2.;\n\n    //test.setConstant(1.1);\n\n\n    \n\n    cout << CFL * dx / (abs(V(1)) + pow(gasGamma*V(2)/V(0),0.5)).minCoeff() << endl;\n   \n    \n\n\n    \n}", "meta": {"hexsha": "91f9e298d10ffd10a159178400216af358d8aa99", "size": 4318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/main/main.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/main/main.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/main/main.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1056910569, "max_line_length": 185, "alphanum_fraction": 0.6296896711, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5927984200869386}}
{"text": "#include <iostream>\n#include <fstream>\n#include <array>\n#include <random>\n#include <armadillo>\n\n\n\n\n\nusing namespace std;\nusing namespace arma;\n\n\nvoid MonteCarlo(vec &players, int MCSteps, int N, int transactions, double lambda, double alpha, double gamma, ofstream &outFile, vec &binCounts, double binSize, double m0, ofstream &outFileErr);\nvoid outPut(vec &players, int MCSteps, int N, int transactions, mat &expectVal);\ndouble findVariance(vec &players, int transaction, int N, double m0);\nvoid makeBins(vec &players, vec &binCount, double binSize);\n\n\nint main(int argc, char *argv[])\n{\n    if (argc < 8){\n        cout << \"To few arguments given. Expected number of persons, Monte Carlo cycles, transactions, start money, lambda, alpha and gamma\" << endl;\n    }\n    int N = stoi(argv[1]);\n    int MCSteps = stoi(argv[2]);\n    int transactions = stoi(argv[3]);\n\n\n    double startMoney = stod(argv[4]);\n    double lambda = stod(argv[5]);\n    double alpha = stod(argv[6]);\n    double gamma = stod(argv[7]);\n\n    double binSize = 0.01*startMoney;\n\n\n    ofstream outFileVar = ofstream(\"variance.txt\");\n    ofstream outFileErr = ofstream(\"distError.txt\");\n\n    //outFileVar.open(\"variance.txt\");\n    ofstream outFileParameter;\n    outFileParameter.open(\"parameters.txt\");\n\n    ofstream binParameters = ofstream(\"binParameters.txt\");\n\n\n\n    outFileParameter << \"N \" << N << \"\\n\";\n    outFileParameter << \"MCSteps \" << MCSteps << \"\\n\";\n    outFileParameter << \"Trasactions \" << transactions << \"\\n\";\n    outFileParameter << \"StartingMoney \" << startMoney << \"\\n\";\n    outFileParameter << \"Lambda \" << lambda << \"\\n\";\n    outFileParameter << \"Alpha \" << alpha << \"\\n\";\n    outFileParameter << \"Gamma \" << gamma;\n\n\n    double binEnd;\n    if (alpha > 0 || gamma > 0){\n        binEnd = 2*startMoney/(sqrt(lambda + 0.1)) + startMoney;\n    }\n    else{\n        binEnd = 2*startMoney/(sqrt(lambda + 0.1)) + startMoney;\n    }\n\n    int binNum = int(binEnd/double(binSize));\n    cout << binNum << endl;\n    vec binCounts = zeros(binNum);\n    vec players = ones(N)*startMoney;\n\n    cout << alpha << \" \" << gamma << endl;\n\n    binParameters << MCSteps << \" \" << N << \" \" << startMoney << \" \" << binSize << \" \" << binNum << \" \" << (binEnd) << \" \" << lambda << \" \" << alpha << \" \" << gamma << endl;\n    binParameters.close();\n\n\n\n\n\n    MonteCarlo(players, MCSteps,  N,transactions,lambda,alpha,gamma,outFileVar,binCounts,binSize,startMoney,outFileErr);\n    //outPut(players, MCSteps, N, transactions, expectVal);\n\n\n\n\n\n    binCounts.save(\"bins.bin\",raw_binary);\n    players.save(\"data.bin\",raw_binary);\n\n    outFileErr.close();\n    outFileVar.close();\n\n    //players.save(\"data.bin\",raw_binary);\n\n    cout << \"Finished\" << endl;\n\n\n\n}\n\n\nvoid MonteCarlo(vec &players, int MCSteps, int N, int transactions, double lambda,double alpha,double gamma, ofstream &outFile, vec &binCounts,double binSize,double m0,ofstream &outFileErr){\n\n\n    random_device rd;\n    mt19937_64 gen(rd());\n\n    uniform_real_distribution<double> distribution(0.0,N);\n    uniform_real_distribution<double> eps(0.0,1.0);\n\n    int writingFreq = 100;\n    double p = 0;\n\n    mat c = zeros(N,N);\n    double maxTransactions = 1;\n\n\n\n    for (int i = 0; i < MCSteps; i++){\n\n\n        players.fill(m0);\n\n\n        for (int j = 0; j < transactions; j++){\n            int index_i = distribution(gen);\n            int index_j = distribution(gen);\n\n            double epsFac = eps(gen);\n\n\n            if (players(index_i) - players(index_j) == 0){\n                p = 1.;\n            }\n            else{\n                p = 2*pow(fabs((players(index_i) - players(index_j))/double(m0)),-alpha)*(pow((c(index_i,index_j)+1)/(maxTransactions+1),gamma));\n            }\n\n            if (eps(gen) < p && (index_i != index_j)){\n\n\n\n\n\n                double m1 = lambda*players(index_i) + (1-lambda)*epsFac*    (players(index_i) + players(index_j));\n                double m2 = lambda*players(index_j) + (1-lambda)*(1-epsFac)*(players(index_i) + players(index_j));\n\n                //cout << \"hei\" << endl;\n\n                players(index_i) = m1;\n                players(index_j) = m2;\n\n\n                c(index_j,index_i) += 1;\n                c(index_i,index_j) += 1;\n\n                if (c(index_j,index_i) > maxTransactions){\n                    maxTransactions = c(index_j,index_i);\n                }\n\n                else if (c(index_i,index_j) > maxTransactions){\n                    maxTransactions = c(index_i,index_j);\n                }\n\n            }\n\n\n\n\n\n            if (MCSteps == 1){\n                if (j%writingFreq == 0){\n\n                    double mean = 0;\n                    for (int i = 0; i < N; i++){\n                        mean += players(i)/m0;\n\n                    }\n\n                    mean /= (N);\n\n\n                    outFile << (j+1) << \" \" << findVariance(players,j+1,N,m0) << \" \" << mean << \"\\n\";\n                }\n\n            }\n        }\n\n    vec tempCounts = binCounts;\n    makeBins(players,binCounts,binSize);\n\n    if (i > 1){\n        outFileErr << i+1 << \" \" << norm(tempCounts/double(i-1) - binCounts/(double(i)) ) << endl;\n    }\n\n\n\n\n\n    }\n\n}\n\n//void outPut(vec &players, int MCSteps, int N, int transactions, mat &expectVal){\n\n//    vec means = zeros(N);\n//    for (int k = 0; k < N;k++){\n//        means(k) = expectVal(0,k) / MCSteps;\n//    }\n\n//    means.save(\"data.bin\",raw_binary);\n//}\n\ndouble findVariance(vec &players, int transaction, int N,double m0){\n\n    double mean = 0;\n    double secondMoment = 0;\n\n    for (int i = 0; i < N; i++){\n        mean += players(i)/m0;\n        secondMoment += players(i)/m0*players(i)/m0;\n    }\n\n    mean /= (N);\n    //cout << secondMoment << endl;\n    secondMoment /= (N);\n\n    return (secondMoment - mean*mean);\n\n}\n\n\nvoid makeBins(vec &players, vec &binCount, double binSize){\n\n    for (int i = 0; i < players.size();i++){\n        for (int j = 0; j < binCount.size();j++){\n            if(players(i)> (j-1)*binSize && players(i)< (j)*binSize){\n                binCount(j) += 1;\n            }\n        }\n    }\n\n    //binCount.print();\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "d3c4b139c81875506b2ae0ca864141fc4b3ac7cb", "size": 6048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/LecturePrograms/programs/RandomWalks/cpp/main.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.0, "max_line_length": 195, "alphanum_fraction": 0.5550595238, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5926716778042239}}
{"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    Function object implementing two_prod capabilities\n\n    For any two reals @c x and @c y two_prod computes two reals (in an std::pair)\n    @c r0 and @c r1 so 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  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": "b53e4c8623f01214455bdd80915816d0619e373e", "size": 1157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/two_prod.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/two_prod.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/two_prod.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 25.152173913, "max_line_length": 100, "alphanum_fraction": 0.5885911841, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5926716508909633}}
{"text": "#ifndef _KERNEL_INDUCTION_HPP_\n#define _KERNEL_INDUCTION_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SparseCore>\n#include <cstdarg>\n#include <mimkl/definitions.hpp>\n#include <spdlog/spdlog.h>\n\nusing mimkl::definitions::Index;\n\nnamespace mimkl\n{\nnamespace induction\n{\n\nauto logger = spdlog::stdout_color_mt(\"kernel_induction\");\n\n//! If only the diagonal entries of \\f$XLX^T\\f$ are needed\n/*!  one full matrix multiplication cannot be avoided with matrix induction,\n    but we only compute the diagonal of \\f$(X*L)*X^T\\f$\n\\param matrix NxM data-matrix.\n\\param inducer pathway specific (sparse) MxM matrix.\n\\param diagonal a  Nx1 Matrix.\n\\sa test/diagonal_from_square_induction\n*/\ntemplate <typename MatrixDerived, typename InducerDerived, typename DiagonalDerived>\nvoid get_diagonal_from_square_induction(\nconst Eigen::MatrixBase<MatrixDerived> &matrix,\nconst Eigen::SparseMatrixBase<InducerDerived> &inducer,\nconst Eigen::EigenBase<DiagonalDerived> &diagonal)\n{\n    const Eigen::Matrix<typename MatrixDerived::Scalar, MatrixDerived::RowsAtCompileTime,\n                        MatrixDerived::ColsAtCompileTime>\n    matrix_inducer =\n    matrix * inducer.template selfadjointView<Eigen::Lower>(); // no .noalias()\n    // possible here:\n    // matrix_inducer =\n    // ;\n\n    Eigen::EigenBase<DiagonalDerived> &diagonal_ =\n    const_cast<Eigen::EigenBase<DiagonalDerived> &>(diagonal);\n    const Index n = matrix_inducer.rows(); // == matrix.rows()\n    if (diagonal.rows() < n)\n    {\n        spdlog::get(\"kernel_induction\")\n        ->critical(\"error in get_diagonal_from_square_induction():\\n rows of \"\n                   \"diagonal {}, rows needed: {}\",\n                   diagonal.rows(), matrix.rows());\n    }\n    //  try {\n    for (Index i = 0; i < n; i++)\n    {\n        diagonal_.derived()(i, 0) =\n        matrix_inducer.row(i) *\n        matrix.adjoint().col(i); // matrix.row(i) for RealScalars\n    }\n    //  } catch (...){ //\n    //\t\tspdlog::get(\"kernel_induction\")->critical(\"error in\n    // get_diagonal_from_square_induction():\\n rows of diagonal {}, rows needed:\n    //[]\", diagonal.rows(), matrix.rows());\n    //\t\tthrow;\n    //  }\n}\n\n//! Matrix induction of a linear kernel with the extended kernel K = X*L*Y_t\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed (unconjugated) right hand side KxM data-matrix.\n\\param inducer pathway specific (sparse, symmetric) MxM matrix.\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa test/linear_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived, typename LDerived>\nKDerived induce_linear_kernel(LhsDerived &lhs, RhsDerived &rhs, LDerived inducer)\n{\n    return lhs * inducer.template selfadjointView<Eigen::Lower>() *\n           rhs.adjoint(); // symmetry allows optimization Lower vs. Upper?\n}\n\n//! Matrix induction of a polynomial kernel with the extended kernel K =\n//! (X*L*Y_t + c)^p\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed (unconjugated)  right hand side KxM data-matrix.\n\\param inducer pathway specific (sparse) MxM matrix.\n\\param degree polynomial degree.\n\\param offset \"free parameter trading off the influence of higher-order versus\nlower-order terms in the polynomial\".\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa TODO\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived, typename LDerived>\nKDerived induce_polynomial_kernel(LhsDerived &lhs,\n                                  RhsDerived &rhs,\n                                  LDerived inducer,\n                                  const double degree,\n                                  const double offset)\n{\n    return (induce_linear_kernel<KDerived>(lhs, rhs, inducer).array() + offset)\n    .pow(degree)\n    .matrix();\n}\n\n//! Matrix induction of a gaussian kernel with the extended kernel k = exp(-\n//! (x-y)_t*L*(x-y) / ( 2*s^2 )).\n/*!  This squared pairwise euclidean distance cannot be expressed in a concise\nmatrix multiplication.\nThe squared distance of xi to yj = \\f$(x_i^T*L*x_i) -(x_i^T*L*y_j)\n-(y_j^T*L*x_i) + (y_j^T*L*y_j) \\f$\nThis means next to \\f$XLY^T\\f$ (the linear kernel) only the diagonal entries of\n\\f$XLX^T\\f$ and \\f$YLY^T\\f$ are needed.\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed  (unconjugated) right hand side KxM data-matrix.\n\\param inducer pathway specific (sparse) MxM matrix.\n\\param sigma_square variance of the bell curve.\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa gaussian_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived, typename LDerived>\nKDerived induce_gaussian_kernel(LhsDerived &lhs,\n                                RhsDerived &rhs,\n                                LDerived inducer,\n                                const double sigma_square)\n{\n    // we only need the diagonal entries of X*L*X_t, so only fill the diagonal\n    // of\n    // (X*L)*X_t\n    Eigen::Matrix<typename LhsDerived::Scalar, LhsDerived::RowsAtCompileTime, 1>\n    diag_lhs_inducer_lhs_t; // Length N\n    if (LhsDerived::RowsAtCompileTime == Eigen::Dynamic)\n        diag_lhs_inducer_lhs_t.resize(lhs.rows());\n    get_diagonal_from_square_induction(lhs, inducer, diag_lhs_inducer_lhs_t);\n    // same for (Y*L)*Y_t\n    Eigen::Matrix<typename RhsDerived::Scalar, RhsDerived::RowsAtCompileTime, 1>\n    diag_rhs_inducer_rhs_t; // Length K\n    if (RhsDerived::RowsAtCompileTime == Eigen::Dynamic)\n        diag_rhs_inducer_rhs_t.resize(rhs.rows());\n    get_diagonal_from_square_induction(rhs, inducer, diag_rhs_inducer_rhs_t);\n\n    // X*L*Y_t\n    return (-(\n            /*! -2* lhs_inducer_rhs only in case of scalar matrices.\n             with complex numbers we need: -lhs_inducer_rhs\n             -lhs_inducer_rhs.adjoint\n             imaginary parts cancel out! */\n            ((-2 * induce_linear_kernel<KDerived>(lhs, rhs, inducer).real()).colwise() +\n             diag_lhs_inducer_lhs_t)\n            .rowwise() +\n            diag_rhs_inducer_rhs_t.transpose()) /\n            (2 * sigma_square))\n    .array()\n    .exp()\n    .matrix();\n}\n\n//! Matrix induction of a sigmoidal kernel with the extended kernel k = tanh(a*\n//! (x_t*L*y) +b).\n/*!\n\\param lhs left hand side NxM data-matrix.\n\\param rhs untransposed  (unconjugated) right hand side KxM data-matrix.\n\\param inducer pathway specific (sparse) MxM matrix.\n\\param a\n\\param b\n\\returns kernel_matrix the similarity NxK matrix.\n\\sa test/sigmoidal_induction\n*/\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived, typename LDerived>\nKDerived induce_sigmoidal_kernel(LhsDerived &lhs,\n                                 RhsDerived &rhs,\n                                 LDerived inducer,\n                                 const double a,\n                                 const double b)\n{\n    return (a * induce_linear_kernel<KDerived>(lhs, rhs, inducer).array() + b)\n    .tanh()\n    .matrix();\n}\n\ntemplate <typename KDerived, typename LhsDerived, typename RhsDerived, typename LDerived>\nstd::vector<std::function<KDerived(LhsDerived &, RhsDerived &)>>\ninducer_combination(std::function<KDerived(LhsDerived &, RhsDerived &, LDerived)>\n                    kernel_function, // parameter specification done\n                                     // previously\n                    std::vector<LDerived> inducers)\n{\n    std::vector<std::function<KDerived(LhsDerived &, RhsDerived &)>> lambda_expressions;\n    lambda_expressions.reserve(inducers.size());\n\n    for (LDerived inducer : inducers)\n    {\n        lambda_expressions.push_back(\n        [&, inducer](const LhsDerived &lhs, const RhsDerived &rhs) {\n            return kernel_function(lhs, rhs, inducer);\n        });\n    }\n\n    return lambda_expressions;\n}\n\n} // namespace induction\n} // namespace mimkl\n\n#endif /*_KERNEL_INDUCTION_HPP_*/\n", "meta": {"hexsha": "2bf3d2f15f7e48748c042106b388c32e271ebe4f", "size": 7778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/kernels/kernel_induction.hpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "include/mimkl/kernels/kernel_induction.hpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "include/mimkl/kernels/kernel_induction.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": 37.7572815534, "max_line_length": 89, "alphanum_fraction": 0.6694523014, "num_tokens": 1908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.592635425050325}}
{"text": "//    boost asinh.hpp header file\n\n//  (C) Copyright Eric Ford & Hubert Holin 2001. Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears\n//  in all copies. This software is provided \"as is\" without express or implied\n//  warranty, and with no claim as to its suitability for any purpose.\n\n// See http://www.boost.org for updates, documentation, and revision history.\n\n#ifndef BOOST_ASINH_HPP\n#define BOOST_ASINH_HPP\n\n\n#include <cmath>\n#include <limits>\n#include <string>\n#include <stdexcept>\n\n\n#include <boost/config.hpp>\n\n\n// This is the inverse of the hyperbolic sine function.\n\nnamespace boost\n{\n    namespace math\n    {\n#if defined(__GNUC__) && (__GNUC__ < 3)\n        // gcc 2.x ignores function scope using declarations,\n        // put them in the scope of the enclosing namespace instead:\n        \n        using    ::std::abs;\n        using    ::std::sqrt;\n        using    ::std::log;\n        \n        using    ::std::numeric_limits;\n#endif\n        \n        template<typename T>\n        inline T    asinh(const T x)\n        {\n            using    ::std::abs;\n            using    ::std::sqrt;\n            using    ::std::log;\n            \n            using    ::std::numeric_limits;\n            \n            \n            T const            one = static_cast<T>(1);\n            T const            two = static_cast<T>(2);\n            \n            static T const    taylor_2_bound = sqrt(numeric_limits<T>::epsilon());\n            static T const    taylor_n_bound = sqrt(taylor_2_bound);\n            static T const    upper_taylor_2_bound = one/taylor_2_bound;\n            static T const    upper_taylor_n_bound = one/taylor_n_bound;\n            \n            if        (x >= +taylor_n_bound)\n            {\n                if        (x > upper_taylor_n_bound)\n                {\n                    if        (x > upper_taylor_2_bound)\n                    {\n                        // approximation by laurent series in 1/x at 0+ order from -1 to 0\n                        return( log( x * two) );\n                    }\n                    else\n                    {\n                        // approximation by laurent series in 1/x at 0+ order from -1 to 1\n                        return( log( x*two + (one/(x*two)) ) );\n                    }\n                }\n                else\n                {\n                    return( log( x + sqrt(x*x+one) ) );\n                }\n            }\n            else if    (x <= -taylor_n_bound)\n            {\n                return(-asinh(-x));\n            }\n            else\n            {\n                // approximation by taylor series in x at 0 up to order 2\n                T    result = x;\n                \n                if    (abs(x) >= taylor_2_bound)\n                {\n                    T    x3 = x*x*x;\n                    \n                    // approximation by taylor series in x at 0 up to order 4\n                    result -= x3/static_cast<T>(6);\n                }\n                \n                return(result);\n            }\n        }\n    }\n}\n\n#endif /* BOOST_ASINH_HPP */\n", "meta": {"hexsha": "f69640eb9b364f05d1bec3eb56df77914add920e", "size": 3109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/3rd party/boost/boost/math/special_functions/asinh.hpp", "max_stars_repo_name": "OLR-xray/OLR-3.0", "max_stars_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-01-25T20:18:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-06T07:00:04.000Z", "max_issues_repo_path": "src/3rd party/boost/boost/math/special_functions/asinh.hpp", "max_issues_repo_name": "OLR-xray/OLR-3.0", "max_issues_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rd party/boost/boost/math/special_functions/asinh.hpp", "max_forks_repo_name": "OLR-xray/OLR-3.0", "max_forks_repo_head_hexsha": "b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-14T01:20:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:19:11.000Z", "avg_line_length": 30.4803921569, "max_line_length": 90, "alphanum_fraction": 0.4654229656, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5925075704242835}}
{"text": "/**\n * @author Elie Khoury <Elie.Khoury@idiap.ch>\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n * @date Tue Apr 2 21:08:00 2013 +0200\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <boost/make_shared.hpp>\n#include <bob.math/inv.h>\n#include <bob.math/lu.h>\n#include <bob.math/stats.h>\n\n#include <bob.learn.linear/wccn.h>\n\nnamespace bob { namespace learn { namespace linear {\n\n  WCCNTrainer::WCCNTrainer() {\n  }\n\n  WCCNTrainer::WCCNTrainer(const WCCNTrainer& other) {\n  }\n\n  WCCNTrainer::~WCCNTrainer() {}\n\n  WCCNTrainer& WCCNTrainer::operator= (const WCCNTrainer& other) {\n    return *this;\n  }\n\n  bool WCCNTrainer::operator== (const WCCNTrainer& other) const {\n    return true;\n  }\n\n  bool WCCNTrainer::operator!= (const WCCNTrainer& other) const {\n    return !(this->operator==(other));\n  }\n\n\n  void WCCNTrainer::train(Machine& machine,\n      const std::vector<blitz::Array<double, 2> >& data) const {\n\n    const size_t n_classes = data.size();\n    // if #classes < 2, then throw\n    if (n_classes < 2) {\n      boost::format m(\"number of classes should be >= 2, but you passed %u\");\n      m % n_classes;\n      throw std::runtime_error(m.str());\n    }\n\n    // checks for data type and shape once\n    const int n_features = data[0].extent(1);\n\n    for (size_t cl=0; cl<n_classes; ++cl) {\n      if (data[cl].extent(1) != n_features) {\n        boost::format m(\"number of features (columns) of array for class %u (%d) does not match that of array for class 0 (%d)\");\n        m % cl % data[cl].extent(1) % n_features;\n        throw std::runtime_error(m.str());\n      }\n    }\n\n    // machine dimensions\n    const size_t n_inputs = machine.inputSize();\n    const size_t n_outputs = machine.outputSize();\n\n    // Checks that the dimensions are matching\n    if ((int)n_inputs != n_features) {\n      boost::format m(\"machine input size (%u) does not match the number of columns in input array (%d)\");\n      m % n_inputs % n_features;\n      throw std::runtime_error(m.str());\n    }\n    if ((int)n_outputs != n_features) {\n      boost::format m(\"machine output size (%u) does not match the number of columns in output array (%d)\");\n      m % n_outputs % n_features;\n      throw std::runtime_error(m.str());\n    }\n\n    // 1. Computes the mean vector and the Scatter matrix Sw and Sb\n    blitz::Array<double,1> mean(n_features);\n    blitz::Array<double,2> buf1(n_features, n_features); // Sw\n    blitz::Array<double,2> buf2(n_features, n_features); // Sb\n    bob::math::scatters(data, buf1, buf2, mean); // buf1 = Sw; buf2 = Sb\n\n    // 2. Computes the inverse of (1/N * Sw), Sw is the within-class covariance matrix\n    buf1 /= n_classes;\n    bob::math::inv(buf1, buf2); // buf2 = (1/N * Sw)^{-1}\n\n  // 3. Computes the Cholesky decomposition of the inverse covariance matrix\n  bob::math::chol(buf2, buf1); //  buf1 = cholesky(buf2)\n\n  // 4. Updates the linear machine\n  machine.setInputSubtraction(0); // we do not substract the mean\n  machine.setInputDivision(1.);\n  machine.setWeights(buf1);\n  machine.setBiases(0);\n  machine.setActivation(boost::make_shared<bob::learn::activation::IdentityActivation>());\n\n  }\n\n}}}\n", "meta": {"hexsha": "8b9445b9d2fba6b046ae927f650c978ba6ba9f72", "size": 3153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/linear/cpp/wccn.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/wccn.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/wccn.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": 31.53, "max_line_length": 129, "alphanum_fraction": 0.6523945449, "num_tokens": 914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5924797574766842}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate<class T, unsigned int batch_size, unsigned int input_size, unsigned int output_size>\nclass Layer\n{\nprivate:\n  // matrix to store outputs of neurons after activation sigma(W*X + B)\n  Matrix<T, batch_size, output_size> output_ {};\n  // matrix to store outputs of neurons before activation W*X + B\n  Matrix<T, batch_size, output_size> unactivated_output_ {};\n  // matrix to store weights of the connections  (W)*X + (B)\n  Matrix<T, input_size, output_size> weights_ {};\n  // matrix to store biases of the layer W*X + (B)\n  Matrix<T, 1, output_size> biases_ {};\n\n  // matrix to store errors at intermediate nodes for given input i.e. target activation - current activation\n  Matrix<T, batch_size, output_size> deltas_ {};\n  // matrix to store gradients w.r.t. weights\n  Matrix<T, input_size, output_size> grad_weights_ {};\n  // matrix to store gradients w.r.t. biases\n  Matrix<T, 1, output_size> grad_biases_ {};\n\npublic:\n  Layer() {}\n\n  void initializeWeightsRandomly()\n  {\n    weights_ = Matrix<T, input_size, output_size>::Random();\n    biases_ = Matrix<T, 1, output_size>::Random();\n  }\n\n  void apply( const Matrix<T, batch_size, input_size>& input )\n  {\n    unactivated_output_ = ( input * weights_ ).rowwise() + biases_;\n    output_ = unactivated_output_.cwiseMax( 0 );\n  }\n\n  void apply_without_activation( const Matrix<T, batch_size, input_size>& input )\n  {\n    unactivated_output_ = ( input * weights_ ).rowwise() + biases_;\n    output_ = unactivated_output_;\n  }\n\n  void print( const unsigned int layer_num ) const\n  {\n    const IOFormat CleanFmt( 4, 0, \", \", \"\\n\", \"[\", \"]\" );\n\n    cout << \"Layer \" << layer_num << endl;\n    cout << \"input_size: \" << input_size << \" -> \"\n         << \"output_size: \" << output_size << endl\n         << endl;\n\n    cout << \"weights:\" << endl << weights_.format( CleanFmt ) << endl << endl;\n    cout << \"biases:\" << endl << biases_.format( CleanFmt ) << endl << endl;\n    cout << \"unactivated_output:\" << endl << unactivated_output_.format( CleanFmt ) << endl << endl;\n    cout << \"output:\" << endl << output_.format( CleanFmt ) << endl << endl;\n\n    cout << \"deltas:\" << endl << deltas_.format( CleanFmt ) << endl << endl;\n    cout << \"grad_weights:\" << endl << grad_weights_.format( CleanFmt ) << endl << endl;\n    cout << \"grad_biases:\" << endl << grad_biases_.format( CleanFmt ) << endl << endl << endl;\n  }\n\n  void perturbWeight( const unsigned int weight_num, const T epsilon )\n  {\n    const unsigned int i = weight_num / output_size;\n    const unsigned int j = weight_num % output_size;\n    if ( i < input_size ) {\n      weights_( i, j ) += epsilon;\n    } else {\n      biases_( 0, j ) += epsilon;\n    }\n  }\n\n  unsigned int getNumParams() const { return ( input_size + 1 ) * output_size; }\n  unsigned int getInputSize() const { return input_size; }\n  unsigned int getOutputSize() const { return output_size; }\n\n  T getEvaluatedGradient( const unsigned int paramNum )\n  {\n    const unsigned int i = paramNum / output_size;\n    const unsigned int j = paramNum % output_size;\n    if ( i < input_size ) {\n      return grad_weights_( i, j );\n    } else {\n      return grad_biases_( 0, j );\n    }\n  }\n\n  const Matrix<T, batch_size, input_size> computeDeltas( Matrix<T, batch_size, output_size> nextLayerDeltas )\n  {\n    // activated nodes is the matrix that stores 0/1 corresponding to whether the output node was activated\n    Matrix<T, batch_size, output_size> activated_nodes\n      = ( unactivated_output_.array() > 0 ).template cast<T>().matrix();\n    deltas_ = nextLayerDeltas.cwiseProduct( activated_nodes );\n    return deltas_ * weights_.transpose();\n  }\n\n  const Matrix<T, batch_size, input_size> computeDeltasLastLayer(\n    Matrix<T, batch_size, output_size> nextLayerDeltas )\n  {\n    deltas_ = nextLayerDeltas;\n    return deltas_ * weights_.transpose();\n  }\n\n  void evaluateGradients( const Matrix<T, batch_size, input_size>& input )\n  {\n    grad_weights_ = Matrix<T, input_size, output_size>::Zero();\n    // grad_biases_ = Matrix<T, 1, output_size>::Zero();\n    for ( unsigned int b = 0; b < batch_size; b++ ) {\n      // for ( unsigned int j = 0; j < output_size; j++ ) {\n      //   // for ( unsigned int i = 0; i < input_size; i++ ) {\n      //   //   grad_weights_( i, j ) += input( b, i ) * deltas_( b, j );\n      //   // }\n      //   grad_weights_.col( j ) += input.row( b ) * deltas_( b, j );\n      // }\n      grad_weights_.noalias() += input.row( b ).transpose() * deltas_.row( b );\n      // grad_biases_.noalias() += deltas_.row( b );\n      // noalias is an eigen optimisation - otherwise becomes slower than for loops\n    }\n    grad_biases_ = deltas_.colwise().sum();\n  }\n\n  const Matrix<T, input_size, output_size>& weights() const { return weights_; }\n  const Matrix<T, batch_size, output_size>& output() const { return output_; }\n  const Matrix<T, 1, output_size>& biases() const { return biases_; }\n\n  // accessors for mutable access to weights and biases\n  Matrix<T, input_size, output_size>& weights() { return weights_; }\n  Matrix<T, 1, output_size>& biases() { return biases_; }\n};\n", "meta": {"hexsha": "6b87f7526f32cc4aa76072c630d29eab6013ba8b", "size": 5158, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/nn/layer.hh", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/nn/layer.hh", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nn/layer.hh", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6496350365, "max_line_length": 109, "alphanum_fraction": 0.6508336565, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.59247975631985}}
{"text": "﻿#include \"ElGamalSignature.h\"\n#include <ctime>\n#include <NTL/BasicThreadPool.h>\n\nusing namespace ElGamal;\n\nPublicKey::PublicKey(const ZZ &p, const ZZ &alpha, const ZZ &beta)\n        : p(p), alpha(alpha), beta(beta) {}\n\nPrivateKey::PrivateKey(const ZZ &a) : a(a) {\n}\n\nElGamalSignature::ElGamalSignature() : pk(nullptr), sk(nullptr) {\n    SetSeed(conv<ZZ>(static_cast<long>(time(nullptr))));\n}\n\nvoid ElGamalSignature::generateKeyPair(int len) {\n    ZZ p = findPrime(len);\n    ZZ alpha = findPrimitiveRoot(p);\n    ZZ a = RandomBnd(p - 2) + 1;//[1,p-1]\n    ZZ beta = PowerMod(alpha, a, p);\n    pk = new PublicKey(p, alpha, beta);\n    sk = new PrivateKey(a);\n}\n\nZZ ElGamalSignature::sig(const ZZ &x, PublicKey *pk, PrivateKey *sk) {\n    ZZ k = RandomBnd(pk->p - 3) + 1;//[1,p-2]\n    while (GCD(k, pk->p - 1) != 1) {\n        k = RandomBnd(pk->p - 3) + 1;\n    }\n    ZZ gamma = PowerMod(pk->alpha, k, pk->p);\n    //delta = (x-a*gamma)*k^(-1) mod (p-1)\n    ZZ delta = MulMod(x - sk->a * gamma, InvMod(k, pk->p - 1), pk->p - 1);\n    return gamma * pk->p + delta;\n}\n\nZZ ElGamalSignature::sig(const ZZ &x) const {\n    return this->sig(x, pk, sk);\n}\n\nZZ ElGamalSignature::sig(const string &x) const {\n    return this->sig(stringToNumber(x), pk, sk);\n}\n\nbool ElGamalSignature::ver(const ZZ &x, const ZZ &y, PublicKey *pk) {\n    ZZ gamma = y / pk->p;\n    ZZ delta = y % pk->p;\n    //beta^(gamma)*gamma^delta==alpha^x (mod p)\n    return (PowerMod(pk->beta, gamma, pk->p) * PowerMod(gamma, delta, pk->p)) % pk->p == PowerMod(pk->alpha, x, pk->p);\n}\n\nElGamalSignature::~ElGamalSignature() {\n    delete pk;\n    delete sk;\n}\n\nPublicKey *ElGamalSignature::getPK() const {\n    return pk;\n}\n\nPrivateKey *ElGamalSignature::getSK() const {\n    return sk;\n}\n", "meta": {"hexsha": "e0c4ea6fc0cee5b18037c72e370e1bd913480e2b", "size": 1733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/MMXlib/ElGamalSignature.cpp", "max_stars_repo_name": "GroupCommuTeam/GroupCommu", "max_stars_repo_head_hexsha": "59b232efa2932f23f2da9152e76dbd1b78aa2225", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-24T15:21:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T17:23:37.000Z", "max_issues_repo_path": "lib/MMXlib/ElGamalSignature.cpp", "max_issues_repo_name": "GroupCommuTeam/GroupCommu", "max_issues_repo_head_hexsha": "59b232efa2932f23f2da9152e76dbd1b78aa2225", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-03-16T08:58:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T10:22:35.000Z", "max_forks_repo_path": "lib/MMXlib/ElGamalSignature.cpp", "max_forks_repo_name": "GroupCommuTeam/GroupCommu", "max_forks_repo_head_hexsha": "59b232efa2932f23f2da9152e76dbd1b78aa2225", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-21T08:07:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T02:45:17.000Z", "avg_line_length": 27.078125, "max_line_length": 119, "alphanum_fraction": 0.6128101558, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.592479749498186}}
{"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_VECTOR_SECULAR_INCLUDE\n#define MTL_VECTOR_SECULAR_INCLUDE\n\n#include <cmath>\n#include <boost/utility.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/operation/minimal_increase.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace vector {\n\n/// Class for the secular equation( to solve eigenvalue problems)\ntemplate <typename Vector>\nclass secular_f\n{\n    typedef typename Collection<Vector>::value_type   value_type;\n    typedef typename Collection<Vector>::size_type    size_type;\n\n  public:\n    /// Constructor needs 2 Vectors z(nummerator), d(dominator) and sigma as factor before the sum\n    secular_f(const Vector& z, const Vector& d, value_type sigma) \n      : z(z), d(d), sigma(sigma) {}\n\n    /// secular_f equation as function, evaluates the function value\n    /** \\f$f(x)=1+\\sigma * sum_{i=1}^{n}\\frac{z_i}{d_i-x} \\f$**/\n    value_type f(const value_type& lamb)\n    {\n\tvalue_type fw= 1;\n\tfor(size_type i=0; i<size(z); i++)\n\t    fw+= sigma*z[i]*z[i]/(d[i]-lamb);\n\treturn fw;\n    }\n\n    value_type square(value_type x) const { return x*x; }\n\n    /// gradient of secular_f equation as function, evaluates the gradientfunction value\n    /** \\f$gradf(x)=\\sigma * sum_{i=1}^{n}\\frac{z_i}{(d_i-x)^2} \\f$**/\n    value_type grad_f(const value_type& lamb)\n    {\n\tvalue_type gfw= 0.0;\n\tfor(size_type i=0; i<size(z); i++)\n\t    gfw+= square(z[i] / (d[i] - lamb)); // , std::cout << \"gfw = \" << gfw << '\\n';  //TODO\n\treturn sigma*gfw;\n    }\n    \n    /// Evaluates the roots of secular_f equation =0 with newton algo.\n    /** Computes mixed Newton and interval nesting. d must be sorted. **/\n    Vector roots()\n    {\n\tassert(size(z) > 1);\n\tconst double tol= 1.0e-6;\n\tVector       start(resource(z)), lambda(resource(z));\n\n\tfor (size_type i= 0; i < size(z); i++) {\n\t    // Equal poles -> eigenvalue \n\t    if (i < size(z) - 1 && d[i] == d[i+1]) { \n\t\tlambda[i]= d[i]; continue; }\n\t    \n\t    // Check if root is too close to pole (i.e. d[i]+eps > 0) then take this because we can't reach the root \n\t    value_type next= minimal_increase(d[i]), lamb, old;\n\t    if (f(next) >= value_type(0)){ \n\t\tlambda[i]= next; continue; }\n\t\t\n\t    if (i < size(z) - 1)\n\t\told= lamb= start[i]= (d[i] + d[i+1]) / 2;  //start points between pols\n\t    else\n\t\told= lamb= start[i]= 1.5 * d[i] - 0.5 * d[i-1];  // last start point plus half the distance to second-last\n\n   \t    while (std::abs(f(lamb)) > tol) {\n\t\tif (lamb <= d[i])\t\t   \n\t\t    start[i]= lamb= (d[i] + start[i]) / 2;  \n\t\telse \n\t\t    lamb-= f(lamb) / grad_f(lamb);\n\t\tif (old == lamb) break;\n\t\told= lamb;\n\t    }\n\t    lambda[i]= lamb;\n\t} \n\treturn lambda;\n    }\n\n private:\n    Vector     z, d;\n    value_type sigma;\n};\n\ntemplate <typename Vector, typename Value>\ninline Vector secular(const Vector& z, const Vector& d, Value sigma)\n{\t\n\tvampir_trace<3030> tracer;\n    secular_f<Vector> functor(z, d, sigma);\n    return functor.roots();\n}\n\n}}// namespace vector\n\n\n#endif // MTL_VECTOR_SECULAR_INCLUDE\n\n", "meta": {"hexsha": "90c5898149be8479429ea737889260acb1b9c00e", "size": 3648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/secular.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/secular.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/secular.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.9152542373, "max_line_length": 110, "alphanum_fraction": 0.6463815789, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5924797460873541}}
{"text": "/**\n@file SBGATPolyhedronGravityModelUQ.hpp\n@class  SBGATPolyhedronGravityModelUQ\n@author Benjamin Bercovici\n@date January 2019\n\n@brief  Evaluation of the formal uncertainty in the potential (variance), acceleration (covariance) caused by a constant-density polyhedron\n@details Computes the potential variance, acceleration covariance associated to the gravity deriving from the polyhedron\n of constant density assuming that the underlying shape vertices are outcomes of a Gaussian distribution \n of known mean and covariance\nThe input must be a topologically-closed polyhedron.\n\nSee Werner, R. A., & Scheeres, D. J. (1997). Exterior gravitation of a polyhedron derived and compared with harmonic and mascon gravitation representations of asteroid 4769 Castalia. Celestial Mechanics and Dynamical Astronomy, 65(3), 313–344. https://doi.org/10.1007/BF00053511\nfor further details. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n@copyright MIT License, Benjamin Bercovici and Jay McMahon\n*/\n\n#ifndef SBGATPolyhedronGravityModelUQ_hpp\n#define SBGATPolyhedronGravityModelUQ_hpp\n\n#include <armadillo>\n#include \"SBGATMassProperties.hpp\"\n#include \"SBGATPolyhedronGravityModel.hpp\"\n#include \"SBGATMassPropertiesUQ.hpp\"\n\nclass SBGATPolyhedronGravityModelUQ : public SBGATMassPropertiesUQ {\npublic:\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential variance at the specified point assuming \n  a constant density\n  @param point pointer to coordinates of queried point, expressed in the same frame as\n  the polydata\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return PGM potential variance evaluated at the queried point (m ^ 4/ s ^4)\n  */\n  double GetVariancePotential(double const * point,bool hold_mass_constant = false) const;\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential variance at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return PGM potential variance evaluated at the queried point (m ^ 4 / s ^4)\n  */\n  double GetVariancePotential(const arma::vec::fixed<3> & point,bool hold_mass_constant = false) const;\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential variance and acceleration covariance at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata used to construct the PGM\n  @param[out] potential_var PGM potential variance evaluated at the queried point (m ^ 4 / s ^4)\n  @param[out] acc_cov PGM acceleration covariance evaluated at the queried point (m^2 / s ^4)\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  */\n  void GetVariancePotentialAccelerationCovariance(double const * point,double & potential_var, \n    arma::mat::fixed<3,3> & acc_cov,bool hold_mass_constant = false) const;\n\n\n\n  /**\n  Return the variance of the slope evaluated at the center of the designated facet. This method is NOT thread safe\n  @param[in] f facet index\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return variance in slope (deg^2)\n  */\n  double GetVarianceSlope(const unsigned int & f , bool hold_mass_constant = false);\n\n\n\n  /**\n  Return the variance of the slope evaluated at the center of the designated facets. This method is NOT thread safe (i.e should not be called from multiple threads). \n  However, it internaly relies on OpenMP to speed up computations\n  @param[out] slope_variances (deg^2)\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @param[in] facets indices of facets where to evaluate the slope variance\n  */\n  void GetVarianceSlopes(std::vector<double> & slope_variances,const std::vector<unsigned int> & facets,bool hold_mass_constant = false);\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential variance and acceleration covariance at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata used to construct the PGM\n  @param[out] potential_var PGM potential variance evaluated at the queried point (m ^ 4 / s ^4)\n  @param[out] acc_cov PGM acceleration covariance evaluated at the queried point (m^2 / s ^4)\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  */\n  void GetVariancePotentialAccelerationCovariance(const arma::vec::fixed<3> & point,double & potential_var, \n    arma::mat::fixed<3,3> & acc_cov,bool hold_mass_constant = false) const;\n\n\n  /**\n  Runs a finite-differencing based test of the implemented PGM partials\n  @param input path to obj file used to test the partials\n  @param tol relative tolerance\n  */\n  static void TestPartials(std::string input , double tol, bool shape_in_meters);\n\n  /**\n  Obtain the partial derivative of the potential at the prescribed location\n  due to a infinitesimal variation in the shape's control points\n  @param[in] pos position where to evaluate the partial derivative\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return partial derivative of the potential with respect to the variation in the shape's control points\n  */\n\n  arma::rowvec GetPartialUPartialC(const arma::vec::fixed<3> & pos,bool hold_mass_constant = false) const;\n\n  /**\n  Obtain the partial derivative of the acceleration at the prescribed location\n  due to a infinitesimal variation in the shape's control points\n  @param[in] pos position where to evaluate the partial derivative\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n \n  @return partial derivative of the acceleration with respect to the variation in the shape's control points\n  */\n  arma::mat GetPartialAPartialC(const arma::vec::fixed<3> & pos,bool hold_mass_constant = false) const;\n\n\n\n  /**\n  Get covariance in acceleration arising from the uncertain shape\n  @param[in] point coordinates where to evaluate the covariance\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return covariance of acceleration\n  */\n  arma::mat::fixed<3,3> GetCovarianceAcceleration(double const * point,bool hold_mass_constant = false) const;\n\n   /**\n  Get covariance in acceleration arising from the uncertain shape\n  @param[in] point coordinates where to evaluate the covariance\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n\n  @return covariance of acceleration\n  */\n  arma::mat::fixed<3,3> GetCovarianceAcceleration(const arma::vec::fixed<3> & point,bool hold_mass_constant = false) const;\n\n\n  /**\n  Runs a Monte Carlo on the shape and samples accelerations & potentials at the provided positions\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] all_positions vector storing all the position where acceleration & potential must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] all_accelerations holds N_samples vectors, each storing the acceleration evaluated at the specified points\n  @param[out] all_potentials holds N_samples vectors, each storing the potential evaluated at the specified points\n  */\n\n  static void RunMCUQPotentialAccelerationInertial(std::string path_to_shape,\n    const double & density,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const unsigned int & N_samples,\n    const std::vector<arma::vec::fixed<3> > & all_positions,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<std::vector<arma::vec::fixed<3> >> & all_accelerations,\n    std::vector < std::vector<double> > & all_potentials );\n\n\n\n/**\n  Runs a Monte Carlo on the shape and samples accelerations at the provided positions\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] all_positions vector storing all the position where acceleration & potential must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] all_accelerations holds N_samples vectors, each storing the acceleration evaluated at the specified points\n  */\n\n  static void RunMCUQAccelerationInertial(std::string path_to_shape,\n    const double & density,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const unsigned int & N_samples,\n    const std::vector<arma::vec::fixed<3> > & all_positions,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<std::vector<arma::vec::fixed<3> >> & all_accelerations);\n\n\n\n  /**\n  Runs a Monte Carlo on the shape and samples the slopes at the provided facets\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] Omega angular velocity of small body in kg/m^3, expressed in the small body frame\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] period_standard_deviation standard deviation of the rotation period in seconds\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] all_facets vector storing all the facet indices where the gravitational slopes must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] period_errors holds N_samples of the error on the rotation period\n\n  @param[out] all_slopes holds N_samples vectors, each storing the slopes evaluated at the specified facets\n  */\n\n  static void RunMCUQSlopes(std::string path_to_shape,\n    const double & density,\n    const arma::vec::fixed<3> & Omega,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const double & period_standard_deviation,\n    const unsigned int & N_samples,\n    const std::vector<unsigned int > & all_facets,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<double> & period_errors,\n    std::vector < std::vector<double> > & all_slopes );\n\n\n\n\n  /**\n  Sets the standard deviation of the rotation period\n  @param standard deviation of the rotation period (s)\n  */\n  void SetPeriodErrorStandardDeviation(double rotation_period_sd){\n    this -> period_standard_deviation = rotation_period_sd;\n  }\n\n\n  /**\n  Return the partial derivative of the slope at the center of facet f relative to \n  the angular velocity magnitude and shape vertices coordinates\n  @param[in] f facet index\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant\n  @return partials\n  */\n  arma::rowvec GetPartialSlopePartialwPartialC(const int & f,bool hold_mass_constant = false) const;\n\n  \n  /**\n  Applies prescribed deviation to all the N_vertices control points and updates model\n  @param delta_C deviation (3 * N_vertices x 1)\n  */  \n  virtual void ApplyDeviation(const arma::vec & delta_C);\n\n  /**\n  Return the partial derivative of the gravitation slope at the center of face tf relative to \n  the shape vertices coordinates\n  @param[in] f facet index\n  @return partial derivative of the slope at the center of facet f relative to the shape vertices coordinates\n  */\n\n  arma::rowvec GetPartialSlopePartialC(const int & f) const;\n\n  /**\n  Runs a Monte Carlo on the shape and samples inertial accelerations & potentials at the provided position\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] position the position where acceleration & potential must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] accelerations holds N_samples accelerations evaluated at the specified point\n  @param[out] potentials holds N_samples potential evaluated at the specified point\n  */\n  static void RunMCUQPotentialAccelerationInertial(std::string path_to_shape,\n    const double & density,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const unsigned int & N_samples,\n    const arma::vec::fixed<3> & position,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<arma::vec::fixed<3> > & accelerations,\n    std::vector<double> & potentials);\n\n\n/**\n  Runs a Monte Carlo on the shape and samples inertial accelerations at the provided position\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] position the position where acceleration & potential must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] accelerations holds N_samples accelerations evaluated at the specified point\n  */\n  static void RunMCUQAccelerationInertial(std::string path_to_shape,\n    const double & density,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const unsigned int & N_samples,\n    const arma::vec::fixed<3> & position,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<arma::vec::fixed<3> > & accelerations);\n\n\n  /**\n  Runs a Monte Carlo on the shape and samples the gravitational slopes at the provided facets\n  @param[in] path_to_shape path to reference shape\n  @param[in] density small body density in kg/m^3\n  @param[in] Omega angular velocity of small body in kg/m^3, expressed in the small body frame\n  @param[in] shape_in_meters true if reference shape has its units expressed in meters, false otherwise\n  @param[in] hold_mass_constant true if shape mass must be held constant by making density vary (mass = rho * V), false otherwise\n  @param[in] C_CC square root of the covariance of the shape vertices coordinates. Must be of dimensions (3N_C * 3N_C) where N_C is the\n  number of vertices in the reference shape\n  @param[in] period_standard_deviation standard deviation of the rotation period in seconds\n  @param[in] N_samples number of shape outcomes to draw\n  @param[in] facet index of the facet where the surface pgm must be sampled\n  @param[in] output_dir path ending in \"/\" where to save shape-related monte-carlo data. Only used\n  if last argument is larger than 0\n  @param[in] N_saved_shapes number of shape outcomes to save. must be lesser or equal than N_samples\n  @param[out] deviations holds N_samples 3*N_C column vectors storing the deviation applied to the coordinates of the \n  reference shape at every sample\n  @param[out] densities holds N_samples density samples. If hold_mass_constant is true, then the density samples\n  will vary accordingly to the constant mass constraint\n  @param[out] period_errors holds N_samples of the error on the rotation period\n  @param[out] slopes holds N_samples slopes evaluated at the specified facet\n  */\n  static void RunMCUQSlopes(std::string path_to_shape,\n    const double & density,\n    const arma::vec::fixed<3> & Omega,\n    const bool & shape_in_meters,\n    const bool & hold_mass_constant,\n    const arma::mat & C_CC,\n    const double & period_standard_deviation,\n    const unsigned int & N_samples,\n    const unsigned int & facet,\n    std::string output_dir,\n    int N_saved_shapes,\n    std::vector<arma::vec> & deviations,\n    std::vector<double> & densities,\n    std::vector<double> & period_errors,\n    std::vector<double> & slopes);\n\n\n\n\n\nprotected:\n\n  arma::vec GetBe() const;\n\n\n\n  /**\n  Get partial derivative of the angular velocity vector relative to 1) the angular velocity magnitude 2) the shape vertices\n  coordinates\n  @return partial derivative of Omega relative to its magnitude shape vertices coordinates\n  */\n  arma::mat PartialOmegaPartialwC() const;\n\n\n  /**\n  Return the partial derivative of the body-fixed angular velocity and the vertices coordinates relative\n  to the angular velocity magnitude and shape vertices coordinates\n  @return partial\n  */\n  arma::sp_mat PartialOmegaCPartialwC() const;\n\n\n/**\nReturn the partial derivative of the body-fixed acceleration at the center of facet f relative\nto the shape coordinates\n@param[in] f facet index\n@param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n@return partial derivative\n*/\n  arma::mat PartialBodyFixedAccelerationfPartialC(const int & f,bool hold_mass_constant = false) const;\n\n\n\n  /**\n  Return the partial derivative of the body-fixed acceleration at the center of facet f with respect to \n  the angular velocity and vertices coordinates\n  @param[in] f facet index\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return partial derivative\n  */\n  arma::mat PartialBodyFixedAccelerationfPartialOmegaC(const int & f,bool hold_mass_constant = false) const;\n\n\n\n\n  arma::mat::fixed<3,3> PartialBodyFixedAccelerationfPartialOmega(const int & f) const;\n\n\n\n\n  /**\n  Adds to the properly initialized vector the partial derivative of the sum of all Ue\n  @param[in] pos position where to evaluate the partials\n  @param[out] partial partial derivative being evaluated\n  */\n  void AddPartialSumUePartialC(const arma::vec::fixed<3> & pos,arma::rowvec & partial) const;\n\n   /**\n  Add to the properly initialized vector the partial derivative of the sum of all Uf\n  @param[in] pos position where to evaluate the partials\n  @param[out] partial partial derivative being evaluated\n  */\n  void AddPartialSumUfPartialC(const arma::vec::fixed<3> & pos,arma::rowvec & partial) const;\n\n\n  /**\n  Adds to the properly initialized vector the partial derivative of the sum of all Acce\n  @param[in] pos position where to evaluate the partials\n  @param[out] partial partial derivative being evaluated\n  */\n  void AddPartialSumAccePartialC(const arma::vec::fixed<3> & pos,arma::mat & partial) const;\n\n   /**\n  Add to the properly initialized vector the partial derivative of the sum of all Accf\n  @param[in] pos position where to evaluate the partials\n  @param[out] partial partial derivative being evaluated\n  */\n  void AddPartialSumAccfPartialC(const arma::vec::fixed<3> & pos,arma::mat & partial) const;\n\n\n  /**\n  Applies deviation to the coordinates of the vertices on the prescribed edge\n  and updates the pgm\n  @param delta_Ae deviation\n  @param e edge index\n  */\n  void ApplyAeDeviation(arma::vec::fixed<6> delta_Ae,const int & e);\n\n\n  /**\n  Applies deviation to the coordinates of the vertices in the prescribed facet\n  and updates the pgm\n  @param delta_Tf deviation\n  @param[in] f facet index\n  */\n  void ApplyTfDeviation(arma::vec::fixed<9> delta_Tf,const int & f);\n\n\n  /**\n  Return the partial derivative of an individual edge contribution to the potential (Ue) \n  with respect to the Xe^E vector holding the e-th edge dyadic factors\n  @param[in] pos position where to evaluate the partial\n  @param e edge index\n  @return PartialUePartialXe (1x10)\n  */\n  arma::rowvec::fixed<10> PartialUePartialXe(const arma::vec::fixed<3> & pos,const int & e) const;\n\n\n  /**\n  Return the partial derivative of an individual facet contribution to the potential (Uf) \n  with respect to the Xf^F vector holding the f-th facet dyadic factors\n  @param[in] pos position where to evaluate the partial\n  @param[in] f facet index\n  @return PartialUfPartialXf (1x10)\n\n  */\n  arma::rowvec::fixed<10> PartialUfPartialXf(const arma::vec::fixed<3> & pos,\n    const int & f) const;\n\n\n\n\n  /**\n  Return the partial derivative of an individual edge contribution to the acceleration (Acce) \n  with respect to the Xe^E vector holding the e-th edge dyadic factors\n  @param[in] pos position where to evaluate the partial\n  @param e edge index\n  @return PartialAccePartialXe (3x10)\n  */\n  arma::mat::fixed<3,10> PartialAccePartialXe(const arma::vec::fixed<3> & pos,const int & e) const;\n\n\n  /**\n  Return the partial derivative of an individual facet contribution to the acceleration (Accf) \n  with respect to the Xf^F vector holding the f-th facet dyadic factors\n  @param[in] pos position where to evaluate the partial\n  @param[in] f facet index\n  @return PartialAccfPartialXf (3x10)\n  */\n  arma::mat::fixed<3,10> PartialAccfPartialXf(const arma::vec::fixed<3> & pos,const int & f) const;\n\n\n\n  /**\n  Return the partial derivative of Xf^F, the vector holding the f-th facet dyadic factors, \n  with respect to the vertices coordiantes constitutive of the f-th triangle (Tf) \n  @param[in] pos position where to evaluate the partial\n  @param[in] f facet index\n  @return PartialXfPartialTf (10x9)\n  */\n  arma::mat::fixed<10,9> PartialXfPartialTf(const arma::vec::fixed<3> & pos, const int & f) const;\n\n\n  /**\n  Return the partial derivative of the performance factor omega_f\n  with respect to the vertices coordiantes constitutive of the f-th triangle (Tf) \n  @param[in] pos position where to evaluate the partial\n  @param[in] f facet index\n  @return PartialOmegafPartialTf (1x9)\n  */\n  arma::rowvec::fixed<9> PartialOmegafPartialTf(const arma::vec::fixed<3> & pos,const int & f) const;\n\n\n\n  /**\n  Return the partial derivative of Z_f = (alpha_f,gamma_f)^T (as in wf = 2 * arctan2(Z_f) )\n  with respect to the unit vectors from the field point to the facet vertices\n  @param UnitRf 3 unit vectors stacked up\n  @return PartialZfPartialUnitRf (2x9)\n  */\n  static arma::mat::fixed<2,9> PartialZfPartialUnitRf(const arma::vec::fixed<9> & UnitRf);\n\n\n  /**\n  Return the partial derivative of arctan2(Z_f) w/r to Z_f \n  with respect to the unit vectors from the field point to the facet vertices\n  @param Zf \n  @return PartialAtan2PartialZf (1x2)\n  */\n  static arma::rowvec::fixed<2> PartialAtan2PartialZf(const arma::vec::fixed<2> & Zf);\n\n\n  /**\n  Return the partial derivative of arctan(y/x)\n  @param xy input\n  @return partial derivative\n  */\n  static arma::rowvec::fixed<2> PartialOmegafPartialXY(const arma::vec::fixed<2> & xy);\n\n\n  /**\n  Return the partial derivative of the facet dyad parametrization (Ff)\n  with respect to the vertices coordinates constitutive of the f-th triangle (Tf) \n  @param[in] f facet index\n  @return PartialFfPartialTf (6x9)\n  */\n  arma::mat::fixed<6,9> PartialFfPartialTf(const int & f) const;\n\n\n\n  /**\n  Return the partial derivative of a normalized vector n relative to the non-normalized\n  vector N such that n = N / || N ||\n  @param non_normalized_V non-normalized vector used to produce the normalized vector\n  @return PartialNormalizedVPartialNonNormalizedV (3x3)\n  */\n  static arma::mat::fixed<3,3> PartialNormalizedVPartialNonNormalizedV(const arma::vec::fixed<3> & non_normalized_V);\n\n\n\n  /**\n  Return the partial derivative of the f-th facet dyad parametrization with respect to the \n  normalized normal of the f-th facet\n  @param nf facet normal\n  @return PartialFfPartialnf (6x3)\n\n  */\n  static arma::mat::fixed<6,3> PartialFfPartialnf(const arma::vec::fixed<3> & nf);\n\n\n\n  /**\n  Return the partial derivative of the wire potential Le \n  with respect to the coordinates of the two vertices forming the edge (stacked in Ae)\n  @param[in] pos position where to evaluate the partial\n  @param e edge index\n  @return PartialLePartialAe (1x6)\n  */\n  arma::rowvec::fixed<6> PartialLePartialAe(const arma::vec::fixed<3> & pos,const int & e) const;\n\n\n  /**\n  Return the partial derivative of field-point to edge-point vector\n  with respect to the coordinates of the two vertices forming the edge (stacked in Ae)\n  @return PartialRadiusEePartialAe (3x6)\n  */\n  arma::mat::fixed<3,6> PartialRadiusEePartialAe() const;\n\n\n  /**\n  Return the partial derivative of field-point to facet-point vector\n  with respect to the coordinates of the three vertices forming the facet (stacked in Tf)\n  @return PartialRadiusFfPartialTf (3x9)\n  */\n  arma::mat::fixed<3,9> PartialRadiusFfPartialTf() const;\n\n\n  /**\n  Return the partial derivative of the parametrization of the Xe dyadic vector\n  with respect to the coordinates of the edges points and adjacent facets points\n  @param[in] pos position where to evaluate the partial\n  @param e edge index\n  @return PartialXePartialBe (10x24)\n  */\n  arma::mat::fixed<10,24> PartialXePartialBe(const arma::vec::fixed<3> & pos,const int & e) const;\n\n  /**\n  Return the partial derivative of the edge length le\n  with respect to the coordinates of the edges points\n  @param e edge index\n  @return PartialEdgeLengthPartialAe (10x24)\n  */\n  arma::rowvec::fixed<6> PartialEdgeLengthPartialAe(const int & e) const;\n\n  /**\n  Return the partial derivative of the (q,r) component of the Ee dyad with respect to the \n  with respect to the coordinates of the edges points and adjacent facets points\n  @param e edge index\n  @param q row index\n  @param r col index\n  @return PartialEqrPartialBe (1x24)\n  */\n  arma::rowvec::fixed<24> PartialEqrPartialBe(const int & e,const int & q,const int & r) const;\n\n\n  /**\n  Return the partial derivative of the f-th facet slope argument (u as in slope = arcos(-u))\n  with respect to the angular velocity and the shape coordinates\n  @param[in] f facet index\n  @param body_fixed_acc body-fixed acceleration at the center of facet f\n  @param[in] hold_mass_constant if true, will make density vary as in drho = - rho V / dV so as to hold mass (mass = rho * V) constant. Default is false\n  @return partial derivative\n  */\n  arma::rowvec PartialSlopeArgumentPartialOmegaC(const int & f,\n    const arma::vec::fixed<3> & body_fixed_acc,bool hold_mass_constant = false) const;\n\n\n  /**\n  Return the partial derivative of the Ee dyad parametrization with respect \n  to the coordinates of the edges points and adjacent facets points\n  @param e edge index\n  @return PartialEPartialBe (6x24)\n  */\n  arma::mat::fixed<6,24> PartialEPartialBe(const int & e) const;\n\n\n  /**\n  Return the connectivity table associated with vector Be\n  @param e edge index\n  @return connectivity table\n  */\n  arma::sp_mat  PartialBePartialC(const int & e) const;\n\n\n\n  /**\n  Return the partial derivative of the slope s == arcos(-u) relative to the slope argument u\n  @param u input parameter\n  @param partial derivative of slope with respect to u\n  */\n  static double PartialSlopePartialSlopeArgument(const double & u);\n\n\n  /**\n  Given a prescribed global deviation of all of the shape's N control points,\n  applies it and returns the deviation in each of the Be's vector (one per edge in the shape)\n  @param delta deviation in all of the shape's N control points (3 x N_vertices)\n  @return deviation in all of the shape's Be vectors (24 x N_edges)\n  */\n  arma::vec ApplyAndGetBeDeviation(const arma::vec & delta);\n\n\n  static void TestPartialUePartialXe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialUfPartialXf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialXfPartialTf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialOmegafPartialTf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialZfPartialUnitRf(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialFfPartialTf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialNormalizedVPartialNonNormalizedV(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialAtan2PartialZf(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialNfPartialTf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialFfPartialnf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialFfPartialNonNormalizedNf(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialLePartialAe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialEePartialAe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialEePartialTf(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialXePartialBe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialEdgeLengthPartialAe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialEPartialBe(std::string input , double tol, bool shape_in_meters) ;\n  static void TestPartialUfPartialTf(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialUePartialBe(std::string input , double tol, bool shape_in_meters);\n  static void TestGetPartialUPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestGetPartialAPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestGetPartialAPartialCConstantMass(std::string input , double tol, bool shape_in_meters);\n  static void TestGetPartialUPartialCConstantMass(std::string input , double tol, bool shape_in_meters);\n  \n  static void TestPartialUfPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialUePartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestAddPartialSumUePartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestAddPartialSumUfPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestAddPartialSumAccfPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestAddPartialSumAccePartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialBePartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestGetPartialSlopePartialwPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialBodyFixedAccelerationfPartialC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialBodyFixedAccelerationfPartialwC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialOmegaPartialwC(std::string input , double tol, bool shape_in_meters);\n  static void TestPartialSlopeArgumentPartialOmegaC(std::string input , double tol, bool shape_in_meters);\n\n  double period_standard_deviation;\n\n \n\n\n\n};\n\n#endif\n\n\n", "meta": {"hexsha": "c9809178f0b6a060a27da7b0b27fb752edfe984e", "size": 35727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModelUQ.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModelUQ.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModelUQ.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 46.2186287193, "max_line_length": 278, "alphanum_fraction": 0.7560668402, "num_tokens": 8909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.5924580881847328}}
{"text": "/*\n* General automatic differentiation engine based on a Wengert list\n* implementation. Reverse mode only.\n*/\n\n#pragma once\n\n#include <vector>\n#include <memory>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n\n\nnamespace ts {\n\ttemplate <typename T> class Node;\n\ttemplate <typename T> class InputNode;\n\ttemplate <typename T> class ElementWiseNode;\n\ttemplate <typename T> class MatProdNode;\n\ttemplate <typename T> class ScalarNode;\n\n\ttemplate <typename T> class WengertList;\n\ttemplate <typename T> class Tensor;\n\ttemplate <typename T> class Gradient;\n\n\n\t// This helper function allows us to create Tensor instances without\n\t// template syntax. This way, the type will be the same as its parent\n\t// WengertList.\n\n\ttemplate <typename T>\n\tts::Tensor<T> NewTensor(\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> newValue,\n\t\tts::WengertList<T> * newWList\n\t);\n\n\ttemplate <typename T>\n\tts::Tensor<T> operator+(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\ttemplate <typename T>\n\tts::Tensor<T> operator-(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\ttemplate <typename T>\n\tts::Tensor<T> operator*(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\ttemplate <typename T>\n\tts::Tensor<T> operator/(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\n\ttemplate <typename T>\n\tts::Tensor<T> matProd(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\ttemplate <typename T>\n\tts::Tensor<T> sigmoid(const ts::Tensor<T> &x);\n\ttemplate <typename T>\n\tts::Tensor<T> relu(const ts::Tensor<T> &x);\n\ttemplate <typename T>\n\tts::Tensor<T> leakyRelu(const ts::Tensor<T> &x);\n\ttemplate <typename T>\n\tts::Tensor<T> rescale(const ts::Tensor<T> &x);\n\ttemplate <typename T>\n\tts::Tensor<T> squaredNorm(const ts::Tensor<T> &x);\n\n\n\t// Forward declaration of friends\n\t// (grad accumulators and other autodiff operations)\n\ttemplate <typename T> class GaElement;\n\ttemplate <typename T> class GradientAccumulator;\n\ttemplate <typename T> class AdamOptimizer;\n\n\tenum class ChannelSplit : int;\n\n\ttemplate <typename T>\n\tts::Tensor<T> convolution(const ts::Tensor<T> &mat, const ts::Tensor<T> &ker);\n\n\ttemplate <typename T>\n\tts::Tensor<T> maxPooling(const ts::Tensor<T> &x, std::vector<unsigned> pool);\n\n\ttemplate <typename T>\n\tstd::vector<ts::Tensor<T>> split(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n\n\ttemplate <typename T>\n\tts::Tensor<T> vertCat(const std::vector<ts::Tensor<T>> &x);\n\n\ttemplate <typename T>\n\tts::Tensor<T> flattening(const ts::Tensor<T> &x);\n\n\ttemplate <typename T>\n\tts::Tensor<T> im2col(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n\n\ttemplate <typename T>\n\tstd::vector<ts::Tensor<T>> col2im(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t);\n}\n\n\n\n\t// ts::Node\n\ntemplate <typename T>\nclass ts::Node {\nprotected:\n\n\tNode() {}\n\n\t// Represents an input variable\n\tNode(std::vector<long> shape);\n\n\t// Represents a unary operator\n\tNode(std::vector<long> shape,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> xVal, int xDep\n\t);\n\n\t// Represents a binary operator\n\tNode(\n\t\tstd::vector<long> shape,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> xVal, int xDep,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> yVal, int yDep\n\t);\n\n\n\tstd::vector<int> dependencies{};\n\n\tvirtual Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t) = 0;\n\n\tstd::vector< Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> > values{};\n\n\t// Shape of the corresponding tensor\n\tlong rows, cols;\n\npublic:\n\n\tfriend ts::Tensor<T>;\n\tfriend ts::WengertList<T>;\n\tfriend ts::GradientAccumulator<T>;\n\tfriend ts::AdamOptimizer<T>;\t// Needed to initialize moment estimates\n\n\tfriend ts::Tensor<T> operator+<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator-<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator*<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator/<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\n\tfriend ts::Tensor<T> matProd<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> sigmoid<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> relu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> leakyRelu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> rescale<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> squaredNorm<>(const ts::Tensor<T> &x);\n\n\tfriend ts::Tensor<T> convolution<>(const ts::Tensor<T> &mat, const ts::Tensor<T> &ker);\n\tfriend ts::Tensor<T> maxPooling<>(const ts::Tensor<T> &x, std::vector<unsigned> pool);\n\tfriend std::vector<ts::Tensor<T>> split<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n\tfriend ts::Tensor<T> vertCat<>(const std::vector<ts::Tensor<T>> &x);\n\tfriend ts::Tensor<T> flattening<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> im2col<>(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n\tfriend std::vector<ts::Tensor<T>> col2im<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t);\n\n};\n\n\n\ntemplate <typename T>\nclass ts::InputNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\tInputNode(std::vector<long> shape, bool model);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\t// We will need this to optimize the tensor value in a ts::Model\n\tts::Tensor<T> * optimizedTensor = NULL;\n\n\t// If true, node won't be removed on wList reset\n\tbool isModel = false;\n\npublic:\n\n\tfriend ts::WengertList<T>;\n\tfriend ts::Tensor<T>;\n\tfriend ts::GradientAccumulator<T>;\n};\n\n\n\ntemplate <typename T>\nclass ts::ElementWiseNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n};\n\n\n\ntemplate <typename T>\nclass ts::MatProdNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tMatProdNode(\n\t\tstd::vector<long> shape,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> xVal, int xDep,\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> yVal, int yDep,\n\t\tstd::vector<long int> newXSize, std::vector<long int> newYSize\n\t);\n\n\t// Size of the operands to figure out how to increment their partial\n\t// derivatives\n\tstd::vector<long int> xSize;\n\tstd::vector<long int> ySize;\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n\n\tfriend ts::Tensor<T> matProd<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n};\n\n\n\ntemplate <typename T>\nclass ts::ScalarNode : public ts::Node<T> {\nprivate:\n\tusing ts::Node<T>::Node;\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> incrementGradient(\n\t\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> &childDerivative,\n\t\t\tunsigned &j\n\t);\n};\n\n\n\n\t// ts::WengertList\n\ntemplate <typename T>\nclass ts::WengertList {\nprivate:\n\tbool elementWiseOnly = true;\n\tstd::vector< std::shared_ptr<ts::Node<T>> > nodes{};\n\npublic:\n\tint size();\n\tint reset();\n\n\t// Make a tensor optimizable\n\tvoid toggleOptimize(ts::Tensor<T> * tensor, bool enable);\n\n\tfriend class ts::Tensor<T>;\n\tfriend class ts::GradientAccumulator<T>;\n\tfriend class ts::AdamOptimizer<T>;\t// Needed to initialize moment estimates\n\n\t// Other non-element wise operations (to change elementWiseOnly)\n\tfriend ts::Tensor<T> matProd<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> sigmoid<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> relu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> leakyRelu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> rescale<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> squaredNorm<>(const ts::Tensor<T> &x);\n\n\tfriend ts::Tensor<T> convolution<>(const ts::Tensor<T> &mat, const ts::Tensor<T> &ker);\n\tfriend ts::Tensor<T> maxPooling<>(const ts::Tensor<T> &x, std::vector<unsigned> pool);\n\tfriend std::vector<ts::Tensor<T>> split<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n\tfriend ts::Tensor<T> vertCat<>(const std::vector<ts::Tensor<T>> &x);\n\tfriend ts::Tensor<T> flattening<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> im2col<>(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n\tfriend std::vector<ts::Tensor<T>> col2im<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t);\n};\n\n\n\n\t// ts::Tensor\n\ntemplate <typename T>\nclass ts::Tensor {\nprivate:\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> value;\n\tts::WengertList<T> * wList = NULL;\n\tint index;\n\n\t// We want this constructor to be private as it is supposed to be called by\n\t// our friends overloaded operators and functions only. This constructor\n\t// thus allows us to create a Tensor with dependencies in the Wengert list.\n\tTensor(\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> newValue,\n\t\tts::WengertList<T> * newWList, std::shared_ptr<ts::Node<T>> node\n\t);\n\npublic:\n\n\tTensor() {};\n\n\t// Input tensor, part of model\n\tTensor(\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> newValue,\n\t\tts::WengertList<T> * newWList\n\t);\n\n\t// Non part of model input tensor\n\t// (equivalent to calling previous constructor with model = false)\n\tTensor(\n\t\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> newValue,\n\t\tts::WengertList<T> * newWList, bool model\n\t);\n\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> getValue();\n\tts::Gradient<T> grad();\n\n\n\tfriend ts::WengertList<T>;\n\n\tfriend ts::Gradient<T>;\n\tfriend ts::GaElement<T>;\n\tfriend ts::GradientAccumulator<T>;\n\n\tfriend ts::Tensor<T> operator+<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator-<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator*<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> operator/<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\n\tfriend ts::Tensor<T> matProd<>(const ts::Tensor<T> &x, const ts::Tensor<T> &y);\n\tfriend ts::Tensor<T> sigmoid<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> relu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> leakyRelu<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> rescale<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> squaredNorm<>(const ts::Tensor<T> &x);\n\n\tfriend ts::Tensor<T> convolution<>(const ts::Tensor<T> &mat, const ts::Tensor<T> &ker);\n\tfriend ts::Tensor<T> maxPooling<>(const ts::Tensor<T> &x, std::vector<unsigned> pool);\n\tfriend std::vector<ts::Tensor<T>> split<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tChannelSplit channelSplit,\n\t\tunsigned nInputChannels\n\t);\n\tfriend ts::Tensor<T> vertCat<>(const std::vector<ts::Tensor<T>> &x);\n\tfriend ts::Tensor<T> flattening<>(const ts::Tensor<T> &x);\n\tfriend ts::Tensor<T> im2col<>(\n\t\tconst std::vector<ts::Tensor<T>> &x,\n\t\tstd::vector<unsigned> kernelDim\n\t);\n\tfriend std::vector<ts::Tensor<T>> col2im<>(\n\t\tconst ts::Tensor<T> &x,\n\t\tstd::vector<unsigned> outputDim\n\t);\n};\n\n\n\ntemplate <typename T>\nts::Tensor<T> NewTensor(\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> newValue,\n\tts::WengertList<T> * newWList\n);\n\n\n\n\t// ts::Gradient\n\ntemplate <typename T>\nclass ts::Gradient {\nprivate:\n\t// Constructor is private since we want instances of this class to be\n\t// generated by the Tensor::grad() method only\n\tGradient(\n\t\tstd::vector< Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> > newDerivatives\n\t);\n\n\tstd::vector< Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> > derivatives;\n\npublic:\n\tEigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> getValue(ts::Tensor<T> a);\n\tbool isEmpty();\n\n\tfriend class ts::Tensor<T>;\n\tfriend class ts::GradientAccumulator<T>;\n\tfriend class ts::AdamOptimizer<T>;\n};\n", "meta": {"hexsha": "e4c8ca667b016d995eda85e411a63f0ad4aafd82", "size": 11667, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autodiff.hpp", "max_stars_repo_name": "PurplePachyderm/tensorslow", "max_stars_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-19T08:57:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-26T17:50:50.000Z", "max_issues_repo_path": "include/autodiff.hpp", "max_issues_repo_name": "PurplePachyderm/tensorslow", "max_issues_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-10-23T14:50:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T12:28:11.000Z", "max_forks_repo_path": "include/autodiff.hpp", "max_forks_repo_name": "PurplePachyderm/tensorslow", "max_forks_repo_head_hexsha": "3ccd881700b301b81154a5b1a787ec91461a6436", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-26T17:49:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T00:51:09.000Z", "avg_line_length": 28.2493946731, "max_line_length": 88, "alphanum_fraction": 0.6862946773, "num_tokens": 3337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5924537246112817}}
{"text": "//  MIT License\n// \tCopyright(c) 2020 ChenKB\n//\n// \tPermission is hereby granted,\n// \tfree 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//\n// \tThe above copyright notice and this permission notice shall be included in all copies\n// \tor\n// \tsubstantial portions of the Software.\n//\n// \tTHE SOFTWARE IS PROVIDED \"AS IS\",\n// \tWITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// \tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// \tDAMAGES OR OTHER\n// \tLIABILITY,\n// \tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// \tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// \tSOFTWARE.\n\n#include <iostream> // cout\n#include <stdio.h>  // sprintf \n#include <stdlib.h> // system\n\n#include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n\n// Required: CMake, opencv\n// To generate executable:\n// cmake . -DOpenCV_DIR=\"/path/to/opencv/build/folder\"\n// Afterwards:\n// make (Do this to recompile)\n\nusing namespace Eigen;\nusing namespace std;\n\nconst int plateSize = 25; // How many balls in each side of the square?\n\n// A ball.\nstruct grid_unit\n{\n\tVector3d pos;\n\tVector3d v;\n\tVector3d f;\n\tfloat m;\n};\n\n// Set up all the balls' position, velocity and force to 0.\nvoid initialize_layer(int gridSize, grid_unit (*layer)[plateSize][plateSize], float y)\n{\n\tfor (int i = 0; i < plateSize; i++)\n\t{\n\t\tfor (int j = 0; j < plateSize; j++)\n\t\t{\n\t\t\t(*layer)[i][j].pos << i * gridSize, y, j * gridSize;\n\t\t\t(*layer)[i][j].v << 0, 0, 0;\n\t\t\t(*layer)[i][j].f << 0, 0, 0;\n\t\t\t(*layer)[i][j].m = 1;\n\t\t}\n\t}\n}\n\n// Calculates layer0[i][j]'s force given one other ball's position\nVector3d spring_f(int i, int j, int i0, int j0,\n\t\t\t\t  grid_unit (*layer1)[plateSize][plateSize],\n\t\t\t\t  grid_unit (*layer0)[plateSize][plateSize],\n\t\t\t\t  bool is_same_lyr, float gridSize)\n{\n\tdouble length0;\n\tif (is_same_lyr)\n\t{\n\t\tlength0 = gridSize * sqrt(pow(i - i0, 2) + pow(j - j0, 2));\n\t}\n\telse\n\t{\n\t\tlength0 = gridSize * sqrt(pow(i - i0, 2) + pow(j - j0, 2) + 1);\n\t}\n\tVector3d pdist_v = (*layer1)[i][j].pos - (*layer0)[i0][j0].pos;\n\treturn 1000 * (pdist_v.norm() - length0) * pdist_v / pdist_v.norm();\n}\n\n// Resets force each ball of both layer to (0,0,0)\nvoid clearLayerForce(int i, int j, grid_unit (*layer1)[plateSize][plateSize], grid_unit (*layer2)[plateSize][plateSize])\n{\n\t(*layer1)[i][j].f << 0, 0, 0;\n\t(*layer2)[i][j].f << 0, 0, 0;\n}\n\n// Update each ball's force in layer0, given the other layer's position.\n// Can apply force to the same layer by giving the same pointer to both layer parameter.\nvoid updateLayerForce(int i, int j, grid_unit (*layer1)[plateSize][plateSize], grid_unit (*layer0)[plateSize][plateSize], float gridSize)\n{\n\tbool isSameLyr = (layer1 == layer0);\n\n\tif (!isSameLyr) // directly over / under\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i, j, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != 0 && j != (plateSize - 1)) // left up\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i - 1, j + 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (j != (plateSize - 1)) // up\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i, j + 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != (plateSize - 1) && j != (plateSize - 1)) // up right\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i + 1, j + 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != (plateSize - 1)) // right\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i + 1, j, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != (plateSize - 1) && j != 0) // right down\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i + 1, j - 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (j != 0) // down\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i, j - 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != 0 && j != 0) // down left\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i - 1, j - 1, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n\tif (i != 0) // left\n\t{\n\t\t(*layer0)[i][j].f += spring_f(i - 1, j, i, j, layer1, layer0, isSameLyr, gridSize);\n\t}\n}\n\n// Updates one layer's position and velocity.\nvoid updateLayerPV(grid_unit (*layer)[plateSize][plateSize], float dt)\n{\n\tfor (int i = 0; i < plateSize; i++)\n\t{\n\t\tfor (int j = 0; j < plateSize; j++)\n\t\t{\n\t\t\t(*layer)[i][j].v += (*layer)[i][j].f / (*layer)[i][j].m * dt;\n\t\t\t(*layer)[i][j].pos += (*layer)[i][j].v * dt;\n\t\t}\n\t}\n}\n\n// Linear mapping, I guess...\n// from (pa,pb,x) to (qa,qb,y), outputs y\nfloat map_to(float pa, float pb, float qa, float qb, float x)\n{\n\treturn qa + (qb-qa)* (pb-x)/(pb-pa);\n}\n\n// output a picture.\n// mode 0 = b&w pic, 1 = red&blue\nvoid outputPic(grid_unit (*layer)[plateSize][plateSize], int mode, bool writeFile, int frame)\n{\n\t\n\tcv::Mat image(plateSize, plateSize, CV_8UC3);\n\n\tif (mode == 0)\n\t{\n\t\tfor (int i = 0; i < plateSize; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < plateSize; j++)\n\t\t\t{\n\t\t\t\tfloat value = (*layer)[i][j].pos(1);\n\t\t\t\tcv::Vec3b &color = image.at<cv::Vec3b>(i, j);\n\t\t\t\tcolor[0] = map_to(-3, 3, 255, 0, value);\n\t\t\t\tcolor[1] = map_to(-3, 3, 255, 0, value);\n\t\t\t\tcolor[2] = map_to(-3, 3, 255, 0, value);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (int i = 0; i < plateSize; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < plateSize; j++)\n\t\t\t{\n\t\t\t\tfloat value = (*layer)[i][j].pos(1);\n\t\t\t\tcv::Vec3b &color = image.at<cv::Vec3b>(i, j);\n\n\t\t\t\tif (value > 0)\n\t\t\t\t{\n\t\t\t\t\tcolor[0] = 0;\n\t\t\t\t\tcolor[1] = 0;\n\t\t\t\t\t// color[2] = map_to(0, 10, 255, 0, value);\n\t\t\t\t\tif ((int)(abs(value / 3) * 255) <= 255)\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor[2] = (int)(abs(value / 3) * 255);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor[2] = 255;\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\t// color[0] = map_to(0, -10, 255, 0, value);\n\t\t\t\t\tif ((int)(abs(value / 3) * 255) <= 255)\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor[0] = (int)(abs(value / 3) * 255);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor[0] = 255;\n\t\t\t\t\t}\n\t\t\t\t\tcolor[1] = 0;\n\t\t\t\t\tcolor[2] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// cv::eigen2cv(output,output2);\n\tcv::namedWindow(\"Chladni\", cv::WINDOW_AUTOSIZE);\n\tcv::resizeWindow(\"Chladni\", 500,500);\n\tcv::imshow(\"Chladni\", image);\n\tcv::waitKey(1);\n\n\tif(writeFile){\n\t\tchar buf[50];\n\t\tsprintf(buf, \"./pics/%04d.png\", frame);\n\t\tcv::imwrite(buf, image);\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tgrid_unit layer1[plateSize][plateSize];\n\tgrid_unit layer2[plateSize][plateSize];\n\tfloat gridSize = 4; // distance between adjacent balls\n\n\tinitialize_layer(gridSize, &layer1, 0);\n\tinitialize_layer(gridSize, &layer2, gridSize);\n\n\tsystem(\"mkdir pics\"); // create pics folder if not exist\n\tsystem(\"rm -f pics/*.png\"); // clear the floder if it do exist\n\n\t// cout << spring_f(5, 5, 5, 6, &layer1, &layer1, true, gridSize) << endl;\n\n\tfloat t = 0;\n\tconst float dt = 0.001;\n\n\tint frame = 0;\n\n\tfloat frequency = 2;\n\tfloat amplitude = 2.0;\n\tint test_x = 12;\n\tint test_y = 12; // vibrating point\n\n\twhile (frame <= 2200) // main time loop\n\t{\n\t\tt += dt;\n\t\tframe += 1;\n\n\t\tif (!(frame % 10))\n\t\t{\n\t\t\tcout << \"Writing frame \" << frame << endl;\n\t\t}\n\n\t\t// cout << layer1[11][11].pos << endl;\n\t\t// cout << \"Layer 2 \"<< layer2[11][11].pos(1) << endl;\n\n\t\tfor (int i = 0; i < plateSize; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < plateSize; j++)\n\t\t\t{\n\t\t\t\tclearLayerForce(i, j, &layer1, &layer2);\n\n\t\t\t\tupdateLayerForce(i, j, &layer2, &layer1, gridSize);\n\t\t\t\tupdateLayerForce(i, j, &layer1, &layer1, gridSize);\n\t\t\t\tupdateLayerForce(i, j, &layer1, &layer2, gridSize);\n\t\t\t\tupdateLayerForce(i, j, &layer2, &layer2, gridSize);\n\t\t\t}\n\t\t}\n\n\t\tupdateLayerPV(&layer1, dt);\n\t\tupdateLayerPV(&layer2, dt);\n\n\t\t// apply vibration\n\t\tlayer1[test_x][test_y].pos << gridSize * test_x, amplitude * sin(t * 2 * M_PI * frequency), gridSize * test_y;\n\t\tlayer2[test_x][test_y].pos << gridSize * test_x, amplitude * sin(t * 2 * M_PI * frequency) + gridSize, gridSize * test_y;\n\n\t\tif(!(frame % 10)){\n\t\t\toutputPic(&layer1,1,true,frame);\n\t\t}else{\n\t\t\toutputPic(&layer1,1,false,frame);\n\t\t}\n\t}\n\tcout << \"Task done.\\07\" << endl; // ascii 07 rings a bell\n\treturn 0;\n}", "meta": {"hexsha": "858a2474561b16560f96123ea5425b20cafb9328", "size": 8159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/chladni.cpp", "max_stars_repo_name": "ChenKB91/Chladni-Patterns", "max_stars_repo_head_hexsha": "e57958592e72d48465253c2358bc329c84595369", "max_stars_repo_licenses": ["MIT"], "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/chladni.cpp", "max_issues_repo_name": "ChenKB91/Chladni-Patterns", "max_issues_repo_head_hexsha": "e57958592e72d48465253c2358bc329c84595369", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T13:51:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T05:27:14.000Z", "max_forks_repo_path": "cpp/chladni.cpp", "max_forks_repo_name": "ChenKB91/Chladni-Patterns", "max_forks_repo_head_hexsha": "e57958592e72d48465253c2358bc329c84595369", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-27T13:03:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-27T13:03:30.000Z", "avg_line_length": 27.8464163823, "max_line_length": 408, "alphanum_fraction": 0.6064468685, "num_tokens": 2851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5924537159522318}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 SunTrust Bank\n Copyright (C) 2010 Cavit Hafizoglu\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 generalizedornsteinuhlenbeckprocess.hpp\n    \\brief Ornstein-Uhlenbeck process with piecewise linear coefficients\n*/\n\n#ifndef quantlib_generalized_ornstein_uhlenbeck_process_hpp\n#define quantlib_generalized_ornstein_uhlenbeck_process_hpp\n\n#include <ql/stochasticprocess.hpp>\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    //! Piecewise linear Ornstein-Uhlenbeck process class\n    /*! This class describes the Ornstein-Uhlenbeck process governed by\n        \\f[\n            dx = a (level - x_t) dt + \\sigma dW_t\n        \\f]\n\n        \\ingroup processes\n\n        where the coefficients a and sigma are piecewise linear.\n    */\n    class GeneralizedOrnsteinUhlenbeckProcess : public StochasticProcess1D {\n      public:\n        GeneralizedOrnsteinUhlenbeckProcess(\n              const boost::function<Real (Time)>& speed,\n              const boost::function<Real (Time)>& vol,\n              Real x0 = 0.0,\n              Real level = 0.0);\n        //! \\name StochasticProcess1D interface\n        //@{\n        Real x0() const;\n\n        Real drift(Time t, Real x) const;\n        Real diffusion(Time t, Real x) const;\n\n        Real expectation(Time t0, Real x0, Time dt) const;\n        Real stdDeviation(Time t0, Real x0, Time dt) const;\n        Real variance(Time t0, Real x0, Time dt) const;\n        //@}\n\n        Real speed(Time t) const;\n        Real volatility(Time t) const;\n        Real level() const;\n\n      private:\n        Real x0_, level_;\n        boost::function<Real (Time)> speed_;\n        boost::function<Real (Time)> volatility_;\n    };\n\n}\n\n\n#endif\n", "meta": {"hexsha": "8b4909fb18e6ae407ff7ae01420ed579e0ea07ec", "size": 2410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/shortrate/generalizedornsteinuhlenbeckprocess.hpp", "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/shortrate/generalizedornsteinuhlenbeckprocess.hpp", "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/shortrate/generalizedornsteinuhlenbeckprocess.hpp", "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": 31.7105263158, "max_line_length": 79, "alphanum_fraction": 0.6780082988, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5924537109835947}}
{"text": "/* boost random/chi_squared_distribution.hpp header file\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id$\n */\n\n#ifndef BOOST_RANDOM_CHI_SQUARED_DISTRIBUTION_HPP_INCLUDED\n#define BOOST_RANDOM_CHI_SQUARED_DISTRIBUTION_HPP_INCLUDED\n\n#include <iosfwd>\n#include <boost/limits.hpp>\n\n#include <boost/random/detail/config.hpp>\n#include <boost/random/gamma_distribution.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * The chi squared distribution is a real valued distribution with\n * one parameter, @c n.  The distribution produces values > 0.\n *\n * The distribution function is\n * \\f$\\displaystyle P(x) = \\frac{x^{(n/2)-1}e^{-x/2}}{\\Gamma(n/2)2^{n/2}}\\f$.\n */\ntemplate<class RealType = double>\nclass chi_squared_distribution {\npublic:\n    typedef RealType result_type;\n    typedef RealType input_type;\n\n    class param_type {\n    public:\n        typedef chi_squared_distribution distribution_type;\n        /**\n         * Construct a param_type object.  @c n\n         * is the parameter of the distribution.\n         *\n         * Requires: t >=0 && 0 <= p <= 1\n         */\n        explicit param_type(RealType n_arg = RealType(1))\n          : _n(n_arg)\n        {}\n        /** Returns the @c n parameter of the distribution. */\n        RealType n() const { return _n; }\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n        /** Writes the parameters of the distribution to a @c std::ostream. */\n        template<class CharT, class Traits>\n        friend std::basic_ostream<CharT,Traits>&\n        operator<<(std::basic_ostream<CharT,Traits>& os,\n                   const param_type& parm)\n        {\n            os << parm._n;\n            return os;\n        }\n\n        /** Reads the parameters of the distribution from a @c std::istream. */\n        template<class CharT, class Traits>\n        friend std::basic_istream<CharT,Traits>&\n        operator>>(std::basic_istream<CharT,Traits>& is, param_type& parm)\n        {\n            is >> parm._n;\n            return is;\n        }\n#endif\n        /** Returns true if the parameters have the same values. */\n        friend bool operator==(const param_type& lhs, const param_type& rhs)\n        {\n            return lhs._n == rhs._n;\n        }\n        /** Returns true if the parameters have different values. */\n        friend bool operator!=(const param_type& lhs, const param_type& rhs)\n        {\n            return !(lhs == rhs);\n        }\n    private:\n        RealType _n;\n    };\n\n    /**\n     * Construct a @c chi_squared_distribution object. @c n\n     * is the parameter of the distribution.\n     *\n     * Requires: t >=0 && 0 <= p <= 1\n     */\n    explicit chi_squared_distribution(RealType n_arg = RealType(1))\n      : _impl(static_cast<RealType>(n_arg / 2))\n    {\n    }\n\n    /**\n     * Construct an @c chi_squared_distribution object from the\n     * parameters.\n     */\n    explicit chi_squared_distribution(const param_type& parm)\n      : _impl(static_cast<RealType>(parm.n() / 2))\n    {\n    }\n\n    /**\n     * Returns a random variate distributed according to the\n     * chi squared distribution.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng)\n    {\n        return 2 * _impl(urng);\n    }\n\n    /**\n     * Returns a random variate distributed according to the\n     * chi squared distribution with parameters specified by @c param.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng, const param_type& parm) const\n    {\n        return chi_squared_distribution(parm)(urng);\n    }\n\n    /** Returns the @c n parameter of the distribution. */\n    RealType n() const { return 2 * _impl.alpha(); }\n\n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }\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    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(n()); }\n    /** Sets parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        typedef gamma_distribution<RealType> impl_type;\n        typename impl_type::param_type impl_parm(static_cast<RealType>(parm.n() / 2));\n        _impl.param(impl_parm);\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() { _impl.reset(); }\n\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n    /** Writes the parameters of the distribution to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const chi_squared_distribution& c2d)\n    {\n        os << c2d.param();\n        return os;\n    }\n\n    /** Reads the parameters of the distribution from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is,\n               chi_squared_distribution& c2d)\n    {\n        c2d.read(is);\n        return is;\n    }\n#endif\n\n    /** Returns true if the two distributions will produce the same\n        sequence of values, given equal generators. */\n    friend bool operator==(const chi_squared_distribution& lhs,\n                           const chi_squared_distribution& rhs)\n    {\n        return lhs._impl == rhs._impl;\n    }\n    /** Returns true if the two distributions could produce different\n        sequences of values, given equal generators. */\n    friend bool operator!=(const chi_squared_distribution& lhs,\n                           const chi_squared_distribution& rhs)\n    {\n        return !(lhs == rhs);\n    }\n\nprivate:\n\n    /// @cond show_private\n\n    template<class CharT, class Traits>\n    void read(std::basic_istream<CharT, Traits>& is) {\n        param_type parm;\n        if(is >> parm) {\n            param(parm);\n        }\n    }\n\n    gamma_distribution<RealType> _impl;\n\n    /// @endcond\n};\n\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "28d9a344eff6df77616f5d7ee6364c7dba184a35", "size": 6298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/random/chi_squared_distribution.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/random/chi_squared_distribution.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/random/chi_squared_distribution.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": 29.9904761905, "max_line_length": 86, "alphanum_fraction": 0.6297237218, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634457, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5924537091143451}}
{"text": "/*\n    This file is part of control-lib.\n\n    Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef CONTROLLIB_TOOLS_MATH_HPP\n#define CONTROLLIB_TOOLS_MATH_HPP\n\n#include <Eigen/Core>\nnamespace control_lib {\n    namespace tools {\n        inline Eigen::Vector3d eulerError(const Eigen::Vector3d& curr, const Eigen::Vector3d& ref);\n\n        inline Eigen::Vector3d rotationError(const Eigen::Vector3d& curr, const Eigen::Vector3d& ref);\n\n        inline Eigen::Vector4d quaternionError(const Eigen::Vector4d& curr, const Eigen::Vector4d& ref);\n\n        inline Eigen::MatrixXd kronecker(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B);\n\n        Eigen::MatrixXd solveVectorized(const Eigen::MatrixXd& A, const Eigen::MatrixXd& W);\n\n        Eigen::MatrixXd bartelsStewart(const Eigen::MatrixXd& A, const Eigen::MatrixXd& W);\n    } // namespace tools\n} // namespace control_lib\n\n#endif // CONTROLLIB_TOOLS_MATH_HPP", "meta": {"hexsha": "ff4240cccaa9f47028730665ee77dadfa40b7d76", "size": 2028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control_lib/tools/math.hpp", "max_stars_repo_name": "nash169/control-lib", "max_stars_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control_lib/tools/math.hpp", "max_issues_repo_name": "nash169/control-lib", "max_issues_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_lib/tools/math.hpp", "max_forks_repo_name": "nash169/control-lib", "max_forks_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0666666667, "max_line_length": 104, "alphanum_fraction": 0.7440828402, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5924536948475453}}
{"text": "#define cimg_display 0\n\n#include <iostream>\n#include <vector>\n#include <exception>\n#include <cmath>\n#include <utility>\n#include <assert.h>\n\n#include <boost/program_options.hpp>\n\n#include \"Timer.hpp\"\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#include \"CImg.h\"\n#pragma GCC diagnostic pop\n\nnamespace zack{\n\ntemplate<typename T>\nT clamp( T val, std::pair<T,T>range){\n  assert( range.first <= range.second);\n\n  return std::max( std::min( val, range.second), range.first);\n}\n\ntemplate <typename T>\ndouble normalize( T val, std::pair<T,T> range){\n  assert( range.first <= range.second);\n\n  auto diff = abs(range.second - range.first);\n  return (val - range.first ) / (double)diff;\n}\n\ntemplate <typename T>\nT lerp( double val, std::pair<T,T> range){\n\n  T diff = (range.second - range.first);\n  T off = diff * val;\n  return (range.first) + off;\n}\n\ntemplate <typename T, typename R>\nR remap( T val, std::pair<T,T> range1, std::pair<R,R> range2){\n  assert( range1.first <= range1.second);\n\n  double v = normalize( val, range1);\n  return lerp( v, range2);\n}\n\n}\n\n\nstruct Matrix_exception: public std::exception{};\n\ntemplate <typename T>\nstruct Matrix{\n    std::vector<T> arr;\n\n    size_t rows, cols;\n\n    Matrix(std::initializer_list<std::initializer_list<T>> lst){\n        cols = lst.size();\n        rows = lst.begin()->size();\n        for( auto row_data : lst){\n            if( row_data.size() != rows ){\n                throw Matrix_exception();\n            }\n\n            for( auto val : row_data ){\n                arr.push_back(val);\n            }\n        }\n    }\n\n    template <typename F>\n    void do_power(F val){\n#pragma omp parallel for simd\n        for(size_t i=0; i<rows; i++){\n            for(size_t j=0; j<cols;j++){\n                T &cur = (*this)[i][j];\n                cur = std::pow(cur, val);\n            }\n        }\n    }\n\n    Matrix(size_t rr, size_t cc){\n        rows = rr;\n        cols = cc;\n        arr.resize(rr*cc);\n    }\n\n    static Matrix kronecker_product( Matrix<T> &a, Matrix<T> &b){\n        Matrix ret(a.rows*b.rows, a.cols *b.cols);\n\n#pragma omp parallel for\n        for( size_t brow=0; brow < b.rows; brow++){\n            for( size_t bcol=0; bcol < b.cols; bcol++){\n                T mul = b[brow][bcol];\n                for( size_t arow=0; arow < a.rows; arow++){\n                    size_t ret_row = brow * a.cols+arow;\n                    for( size_t acol=0; acol < a.cols; acol++){\n                        size_t ret_col = bcol*a.cols+acol;\n                        ret[ret_row][ret_col] = a[arow][acol] * mul;\n                    }\n                }\n            }\n        }\n        return ret;\n    }\n\n    T& wrapped_get( size_t r, size_t c){\n        return (*this)[r%rows][c%cols];\n    }\n\n    T* operator[](size_t r){\n        return &arr[r*cols];\n    }\n};\n\nusing namespace std;\n\nMatrix<float> kpower(Matrix<float> a, int power){\n    Matrix<float>b=a;\n\n    for(int i=0; i<power; i++){\n        a = Matrix<float>::kronecker_product(a,b);\n    }\n    a.do_power(1/(float)power);\n    return a;\n}\n\nuint8_t c2f(float val){\n    return zack::remap( val, make_pair(0.0f, 1.0f), make_pair(0,255));\n}\n\nint main(int argc, char **argv){\n\n    std::string out_name;\n    int raise;\n\n    namespace po = boost::program_options;\n\n    po::options_description desc(\"allowed options\");\n    desc.add_options()\n        (\"help,h\", \"print help\")\n        (\"display,d\", \"display the image with X\")\n        (\"bmp\", po::value<std::string>(&out_name)->default_value(\"\"), \"the file to write to\")\n        (\"iterations,i\", po::value<int>(&raise)->default_value(3), \"iterations for multiplication\")\n        ;\n\n\n    po::variables_map args;\n    po::store(po::parse_command_line(argc, argv, desc), args);\n    args.notify();\n\n    if( args.count(\"iterations\") ) raise = args[\"iterations\"].as<int>();\n    if( args.count(\"bmp\") )out_name = args[\"bmp\"].as<std::string>();\n\n    if( args.count(\"help\")){\n        std::cout<<desc<<std::endl;\n        return 0;\n    }\n\n    const float h = 0.8;\n    const float l = 0.01;\n    Matrix<float> a1 {{h,h,h},\n                      {l,l,h},\n                      {l,h,h}};\n    Matrix<float> a2 {{l,l,h},\n                      {l,h,l},\n                      {l,l,l}};\n    Matrix<float> a3 {{h,l,h},\n                      {l,h,l},\n                      {l,l,h}};\n\n    Timer power_timer;\n    power_timer.start();\n\n    Matrix<float> r = kpower(a1, raise);\n    Matrix<float> g = kpower(a2,raise);\n    Matrix<float> b = kpower(a3,raise);\n    power_timer.stop();\n\n    std::cout<<\"Time taken to generate data: \"<<std::to_string(power_timer.getTime())<<\" seconds\"<<std::endl;\n\n\n    using namespace cimg_library;\n    CImg<uint8_t> image(r.rows, r.cols, 1, 3) ;\n\n#pragma omp parallel for\n    for(size_t i=0; i<r.rows; i++){\n        for(size_t j=0; j<r.cols; j++){\n            const uint8_t rr = c2f(r[i][j] );\n            const uint8_t gg = c2f( g[i][j] );\n            const uint8_t bb = c2f( b[i][j] );\n            image(i,j,0,0)=rr;\n            image(i,j,0,1)=gg;\n            image(i,j,0,2)=bb;\n        }\n    }\n    if(args.count(\"display\")){\n        //image.display();\n    }\n\n    if(args.count(\"bmp\")){\n        image.save_bmp(out_name.c_str());\n    }\n}\n", "meta": {"hexsha": "d5782bc0286bc0301a2e5fa1bd8670cfcdd438eb", "size": 5189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kronecker_product/main.cpp", "max_stars_repo_name": "zwparchman/misc", "max_stars_repo_head_hexsha": "6f5960f88c1e399556a7ac7aaa04715e0e967325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kronecker_product/main.cpp", "max_issues_repo_name": "zwparchman/misc", "max_issues_repo_head_hexsha": "6f5960f88c1e399556a7ac7aaa04715e0e967325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kronecker_product/main.cpp", "max_forks_repo_name": "zwparchman/misc", "max_forks_repo_head_hexsha": "6f5960f88c1e399556a7ac7aaa04715e0e967325", "max_forks_repo_licenses": ["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.5924170616, "max_line_length": 109, "alphanum_fraction": 0.5399884371, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181417, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5924508603285954}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#define DATASET_SIZE 500\n#define ELIPSON 30\n#define MIN_POINTS 10\n\nusing namespace std;\n\nstruct Point {\n  int x, y;\n};\n\nstruct Cluster {\n  int id;\n  vector<int> data;\n};\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef bg::model::point<float, 2, bg::cs::cartesian> dataPoint;\ntypedef bg::model::box<dataPoint> box;\ntypedef std::pair<box, int> value;\n\nclass DBSCAN {\n private:\n  Point dataset[DATASET_SIZE];\n  int elipson;\n  int minPoints;\n  int cluster;\n  int clusters[DATASET_SIZE];\n  int getDistance(int center, int neighbor);\n  vector<int> findNeighbors(int pos);\n  void expandCluster(int pointId, vector<int> &neighbors);\n  bgi::rtree<value, bgi::quadratic<4>> rtree;\n\n public:\n  DBSCAN(Point dataset[DATASET_SIZE]);\n  void run();\n  void results();\n};\n\nint main(int, char **) {\n\n  // Generate random datasets\n  Point dataset[DATASET_SIZE];\n\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    int x = rand() % 50;\n    int y = rand() % 50;\n    dataset[i].x = x;\n    dataset[i].y = y;\n  }\n\n  printf(\"Random Dataset created\\n\");\n  printf(\"###############################\\n\");\n\n  // Print dataset in an array structure\n  printf(\"[\");\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    printf(\"[%d, %d], \", dataset[i].x, dataset[i].y);\n  }\n  printf(\"]\\n\");\n\n  printf(\"###############################\\n\");\n\n  // Initialize DBSCAN with dataset\n  DBSCAN dbscan(dataset);\n\n  // Run the DBSCAN algorithm\n  dbscan.run();\n\n  // Print the cluster results of DBSCAN\n  dbscan.results();\n\n  return 0;\n  \n}\n\nDBSCAN::DBSCAN(Point loadData[DATASET_SIZE]) {\n\n  elipson = ELIPSON;\n  minPoints = MIN_POINTS;\n  cluster = 0;\n\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    dataset[i].x = loadData[i].x;\n    dataset[i].y = loadData[i].y;\n    clusters[i] = 0;\n  }\n\n  // Create an Rtree of the dataset\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    // create a box for each points\n    box b(dataPoint(dataset[i].x, dataset[i].y),\n          dataPoint(dataset[i].x, dataset[i].y));\n    // insert points to the rtree\n    rtree.insert(std::make_pair(b, i));\n    \n  }\n}\n\nint DBSCAN::getDistance(int center, int neighbor) {\n\n  int dist = (dataset[center].x - dataset[neighbor].x) *\n                 (dataset[center].x - dataset[neighbor].x) +\n             (dataset[center].y - dataset[neighbor].y) *\n                 (dataset[center].y - dataset[neighbor].y);\n\n  return sqrt(dist);\n\n}\n\nvoid DBSCAN::run() {\n  // Neighbors of the point\n  vector<int> neighbors;\n\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    \n    if (clusters[i] == 0) {\n\n      // Find neighbors of point P\n      neighbors = findNeighbors(i);\n\n      // Mark noise points\n      if (neighbors.size() < minPoints) {\n        clusters[i] = -1;\n      } else {\n        // Increment cluster and initialize it will the current point\n        cluster++;\n\n        clusters[i] = cluster; \n\n        // Expand the neighbors of point P\n        for (int j = 0; j < neighbors.size(); j++) {\n\n          // Mark neighbour as point Q\n          int dataIndex = neighbors[j];\n\n          if(clusters[dataIndex] == -1) {\n            clusters[dataIndex] = cluster;\n          } else if (clusters[dataIndex] == 0) {\n\n            clusters[dataIndex] = cluster;\n            \n            // Expand more neighbors of point Q\n            vector<int> moreNeighbors;\n            moreNeighbors = findNeighbors(dataIndex);\n\n            // Continue when neighbors point is higher than minPoint threshold\n\n            if (moreNeighbors.size() >= minPoints) {\n              // Check if neighbour of Q already exists in neighbour of P\n              for (int x = 0; x < moreNeighbors.size(); x++) {\n                bool doesntExist = true;\n                for (int y = 0; y < neighbors.size(); y++) {\n                  if (moreNeighbors[x] == neighbors[y]) {\n                    doesntExist = false;\n                    break;\n                  }\n                }\n\n                // If neighbour doesn't exist, add to neighbor list\n                if (doesntExist) {\n                  neighbors.push_back(moreNeighbors[x]);\n                }\n              }\n            }\n          }         \n      }\n    }\n  }\n}\n}\n\nvoid DBSCAN::results() {\n  for(int x = 1; x <= cluster; x++) {\n    printf(\"CLuster %d: \\n[\\n\", x);\n    for(int i = 0; i < DATASET_SIZE; i++) {\n      if(clusters[i] == x) {\n        printf(\"  [%d, %d]\\n\", dataset[i].x, dataset[i].y);\n      }\n    }\n    printf(\"]\\n\");\n  }\n  \n}\n\nvector<int> DBSCAN::findNeighbors(int pos) {\n\n  vector<int> neighbors;\n  Point point = dataset[pos];\n  vector<value> result_n;\n\n  // Create a search box for the given poiny\n  box searchBox(dataPoint(point.x - elipson, point.y - elipson),\n                dataPoint(point.x + elipson, point.y + elipson));\n\n  // Query the intersection of search box on Rtree\n  rtree.query(bgi::intersects(searchBox), std::back_inserter(result_n));\n\n  // collect the points of box\n  vector<int> pointsInBox = {};\n  for (value pair : result_n) pointsInBox.push_back(pair.second);\n\n  // Compute the distance only with points in a box\n  for (int x = 0; x < pointsInBox.size(); x++) {\n    // Compute neighbor points\n    int distance = getDistance(pos, pointsInBox[x]);\n    if (distance <= elipson && pos != pointsInBox[x]) {\n      neighbors.push_back(pointsInBox[x]);\n    }\n  }\n\n  return neighbors;\n\n}", "meta": {"hexsha": "c1ffd07f1d330f71f71ea8d3c44e446a28f40fe6", "size": 5531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dbscan-with-random-data/Dbscan_Rtree_boost.cpp", "max_stars_repo_name": "l3lackcurtains/DBSCAN-variants", "max_stars_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-28T06:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T06:49:23.000Z", "max_issues_repo_path": "dbscan-with-random-data/Dbscan_Rtree_boost.cpp", "max_issues_repo_name": "l3lackcurtains/DBSCAN-variants", "max_issues_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T20:56:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T06:52:33.000Z", "max_forks_repo_path": "dbscan-with-random-data/Dbscan_Rtree_boost.cpp", "max_forks_repo_name": "l3lackcurtains/DBSCAN-variants", "max_forks_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_forks_repo_licenses": ["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.5822222222, "max_line_length": 78, "alphanum_fraction": 0.5767492316, "num_tokens": 1456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5924508592858633}}
{"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_TOOLS_SIGNAL_STATISTICS_HPP\n#define BOOST_MATH_TOOLS_SIGNAL_STATISTICS_HPP\n\n#include <algorithm>\n#include <iterator>\n#include <boost/math/tools/assert.hpp>\n#include <boost/math/tools/complex.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/tools/header_deprecated.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n\nBOOST_MATH_HEADER_DEPRECATED(\"<boost/math/statistics/signal_statistics.hpp>\");\n\nnamespace boost::math::tools {\n\ntemplate<class ForwardIterator>\nauto absolute_gini_coefficient(ForwardIterator first, ForwardIterator last)\n{\n    using std::abs;\n    using RealOrComplex = typename std::iterator_traits<ForwardIterator>::value_type;\n    BOOST_MATH_ASSERT_MSG(first != last && std::next(first) != last, \"Computation of the Gini coefficient requires at least two samples.\");\n\n    std::sort(first, last,  [](RealOrComplex a, RealOrComplex b) { return abs(b) > abs(a); });\n\n\n    decltype(abs(*first)) i = 1;\n    decltype(abs(*first)) num = 0;\n    decltype(abs(*first)) denom = 0;\n    for (auto it = first; it != last; ++it)\n    {\n        decltype(abs(*first)) tmp = abs(*it);\n        num += tmp*i;\n        denom += tmp;\n        ++i;\n    }\n\n    // If the l1 norm is zero, all elements are zero, so every element is the same.\n    if (denom == 0)\n    {\n        decltype(abs(*first)) zero = 0;\n        return zero;\n    }\n    return ((2*num)/denom - i)/(i-1);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto absolute_gini_coefficient(RandomAccessContainer & v)\n{\n    return boost::math::tools::absolute_gini_coefficient(v.begin(), v.end());\n}\n\ntemplate<class ForwardIterator>\nauto sample_absolute_gini_coefficient(ForwardIterator first, ForwardIterator last)\n{\n    size_t n = std::distance(first, last);\n    return n*boost::math::tools::absolute_gini_coefficient(first, last)/(n-1);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto sample_absolute_gini_coefficient(RandomAccessContainer & v)\n{\n    return boost::math::tools::sample_absolute_gini_coefficient(v.begin(), v.end());\n}\n\n\n// The Hoyer sparsity measure is defined in:\n// https://arxiv.org/pdf/0811.4706.pdf\ntemplate<class ForwardIterator>\nauto hoyer_sparsity(const ForwardIterator first, const ForwardIterator last)\n{\n    using T = typename std::iterator_traits<ForwardIterator>::value_type;\n    using std::abs;\n    using std::sqrt;\n    BOOST_MATH_ASSERT_MSG(first != last && std::next(first) != last, \"Computation of the Hoyer sparsity requires at least two samples.\");\n\n    if constexpr (std::is_unsigned<T>::value)\n    {\n        T l1 = 0;\n        T l2 = 0;\n        size_t n = 0;\n        for (auto it = first; it != last; ++it)\n        {\n            l1 += *it;\n            l2 += (*it)*(*it);\n            n += 1;\n        }\n\n        double rootn = sqrt(n);\n        return (rootn - l1/sqrt(l2) )/ (rootn - 1);\n    }\n    else {\n        decltype(abs(*first)) l1 = 0;\n        decltype(abs(*first)) l2 = 0;\n        // We wouldn't need to count the elements if it was a random access iterator,\n        // but our only constraint is that it's a forward iterator.\n        size_t n = 0;\n        for (auto it = first; it != last; ++it)\n        {\n            decltype(abs(*first)) tmp = abs(*it);\n            l1 += tmp;\n            l2 += tmp*tmp;\n            n += 1;\n        }\n        if constexpr (std::is_integral<T>::value)\n        {\n            double rootn = sqrt(n);\n            return (rootn - l1/sqrt(l2) )/ (rootn - 1);\n        }\n        else\n        {\n            decltype(abs(*first)) rootn = sqrt(static_cast<decltype(abs(*first))>(n));\n            return (rootn - l1/sqrt(l2) )/ (rootn - 1);\n        }\n    }\n}\n\ntemplate<class Container>\ninline auto hoyer_sparsity(Container const & v)\n{\n    return boost::math::tools::hoyer_sparsity(v.cbegin(), v.cend());\n}\n\n\ntemplate<class Container>\nauto oracle_snr(Container const & signal, Container const & noisy_signal)\n{\n    using Real = typename Container::value_type;\n    BOOST_MATH_ASSERT_MSG(signal.size() == noisy_signal.size(),\n                     \"Signal and noisy_signal must be have the same number of elements.\");\n    if constexpr (std::is_integral<Real>::value)\n    {\n        double numerator = 0;\n        double denominator = 0;\n        for (size_t i = 0; i < signal.size(); ++i)\n        {\n            numerator += signal[i]*signal[i];\n            denominator += (noisy_signal[i] - signal[i])*(noisy_signal[i] - signal[i]);\n        }\n        if (numerator == 0 && denominator == 0)\n        {\n            return std::numeric_limits<double>::quiet_NaN();\n        }\n        if (denominator == 0)\n        {\n            return std::numeric_limits<double>::infinity();\n        }\n        return numerator/denominator;\n    }\n    else if constexpr (boost::math::tools::is_complex_type<Real>::value)\n\n    {\n        using std::norm;\n        typename Real::value_type numerator = 0;\n        typename Real::value_type denominator = 0;\n        for (size_t i = 0; i < signal.size(); ++i)\n        {\n            numerator += norm(signal[i]);\n            denominator += norm(noisy_signal[i] - signal[i]);\n        }\n        if (numerator == 0 && denominator == 0)\n        {\n            return std::numeric_limits<typename Real::value_type>::quiet_NaN();\n        }\n        if (denominator == 0)\n        {\n            return std::numeric_limits<typename Real::value_type>::infinity();\n        }\n\n        return numerator/denominator;\n    }\n    else\n    {\n        Real numerator = 0;\n        Real denominator = 0;\n        for (size_t i = 0; i < signal.size(); ++i)\n        {\n            numerator += signal[i]*signal[i];\n            denominator += (signal[i] - noisy_signal[i])*(signal[i] - noisy_signal[i]);\n        }\n        if (numerator == 0 && denominator == 0)\n        {\n            return std::numeric_limits<Real>::quiet_NaN();\n        }\n        if (denominator == 0)\n        {\n            return std::numeric_limits<Real>::infinity();\n        }\n\n        return numerator/denominator;\n    }\n}\n\ntemplate<class Container>\nauto mean_invariant_oracle_snr(Container const & signal, Container const & noisy_signal)\n{\n    using Real = typename Container::value_type;\n    BOOST_MATH_ASSERT_MSG(signal.size() == noisy_signal.size(), \"Signal and noisy signal must be have the same number of elements.\");\n\n    Real mu = boost::math::tools::mean(signal);\n    Real numerator = 0;\n    Real denominator = 0;\n    for (size_t i = 0; i < signal.size(); ++i)\n    {\n        Real tmp = signal[i] - mu;\n        numerator += tmp*tmp;\n        denominator += (signal[i] - noisy_signal[i])*(signal[i] - noisy_signal[i]);\n    }\n    if (numerator == 0 && denominator == 0)\n    {\n        return std::numeric_limits<Real>::quiet_NaN();\n    }\n    if (denominator == 0)\n    {\n        return std::numeric_limits<Real>::infinity();\n    }\n\n    return numerator/denominator;\n\n}\n\ntemplate<class Container>\nauto mean_invariant_oracle_snr_db(Container const & signal, Container const & noisy_signal)\n{\n    using std::log10;\n    return 10*log10(boost::math::tools::mean_invariant_oracle_snr(signal, noisy_signal));\n}\n\n\n// Follows the definition of SNR given in Mallat, A Wavelet Tour of Signal Processing, equation 11.16.\ntemplate<class Container>\nauto oracle_snr_db(Container const & signal, Container const & noisy_signal)\n{\n    using std::log10;\n    return 10*log10(boost::math::tools::oracle_snr(signal, noisy_signal));\n}\n\n// A good reference on the M2M4 estimator:\n// D. R. Pauluzzi and N. C. Beaulieu, \"A comparison of SNR estimation techniques for the AWGN channel,\" IEEE Trans. Communications, Vol. 48, No. 10, pp. 1681-1691, 2000.\n// A nice python implementation:\n// https://github.com/gnuradio/gnuradio/blob/master/gr-digital/examples/snr_estimators.py\ntemplate<class ForwardIterator>\nauto m2m4_snr_estimator(ForwardIterator first, ForwardIterator last, decltype(*first) estimated_signal_kurtosis=1, decltype(*first) estimated_noise_kurtosis=3)\n{\n    BOOST_MATH_ASSERT_MSG(estimated_signal_kurtosis > 0, \"The estimated signal kurtosis must be positive\");\n    BOOST_MATH_ASSERT_MSG(estimated_noise_kurtosis > 0, \"The estimated noise kurtosis must be positive.\");\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    using std::sqrt;\n    if constexpr (std::is_floating_point<Real>::value || std::numeric_limits<Real>::max_exponent)\n    {\n        // If we first eliminate N, we obtain the quadratic equation:\n        // (ka+kw-6)S^2 + 2M2(3-kw)S + kw*M2^2 - M4 = 0 =: a*S^2 + bs*N + cs = 0\n        // If we first eliminate S, we obtain the quadratic equation:\n        // (ka+kw-6)N^2 + 2M2(3-ka)N + ka*M2^2 - M4 = 0 =: a*N^2 + bn*N + cn = 0\n        // I believe these equations are totally independent quadratics;\n        // if one has a complex solution it is not necessarily the case that the other must also.\n        // However, I can't prove that, so there is a chance that this does unnecessary work.\n        // Future improvements: There are algorithms which can solve quadratics much more effectively than the naive implementation found here.\n        // See: https://stackoverflow.com/questions/48979861/numerically-stable-method-for-solving-quadratic-equations/50065711#50065711\n        auto [M1, M2, M3, M4] = boost::math::tools::first_four_moments(first, last);\n        if (M4 == 0)\n        {\n            // The signal is constant. There is no noise:\n            return std::numeric_limits<Real>::infinity();\n        }\n        // Change to notation in Pauluzzi, equation 41:\n        auto kw = estimated_noise_kurtosis;\n        auto ka = estimated_signal_kurtosis;\n        // A common case, since it's the default:\n        Real a = (ka+kw-6);\n        Real bs = 2*M2*(3-kw);\n        Real cs = kw*M2*M2 - M4;\n        Real bn = 2*M2*(3-ka);\n        Real cn = ka*M2*M2 - M4;\n        auto [S0, S1] = boost::math::tools::quadratic_roots(a, bs, cs);\n        if (S1 > 0)\n        {\n            auto N = M2 - S1;\n            if (N > 0)\n            {\n                return S1/N;\n            }\n            if (S0 > 0)\n            {\n                N = M2 - S0;\n                if (N > 0)\n                {\n                    return S0/N;\n                }\n            }\n        }\n        auto [N0, N1] = boost::math::tools::quadratic_roots(a, bn, cn);\n        if (N1 > 0)\n        {\n            auto S = M2 - N1;\n            if (S > 0)\n            {\n                return S/N1;\n            }\n            if (N0 > 0)\n            {\n                S = M2 - N0;\n                if (S > 0)\n                {\n                    return S/N0;\n                }\n            }\n        }\n        // This happens distressingly often. It's a limitation of the method.\n        return std::numeric_limits<Real>::quiet_NaN();\n    }\n    else\n    {\n        BOOST_MATH_ASSERT_MSG(false, \"The M2M4 estimator has not been implemented for this type.\");\n        return std::numeric_limits<Real>::quiet_NaN();\n    }\n}\n\ntemplate<class Container>\ninline auto m2m4_snr_estimator(Container const & noisy_signal,  typename Container::value_type estimated_signal_kurtosis=1, typename Container::value_type estimated_noise_kurtosis=3)\n{\n    return m2m4_snr_estimator(noisy_signal.cbegin(), noisy_signal.cend(), estimated_signal_kurtosis, estimated_noise_kurtosis);\n}\n\ntemplate<class ForwardIterator>\ninline auto m2m4_snr_estimator_db(ForwardIterator first, ForwardIterator last, decltype(*first) estimated_signal_kurtosis=1, decltype(*first) estimated_noise_kurtosis=3)\n{\n    using std::log10;\n    return 10*log10(m2m4_snr_estimator(first, last, estimated_signal_kurtosis, estimated_noise_kurtosis));\n}\n\n\ntemplate<class Container>\ninline auto m2m4_snr_estimator_db(Container const & noisy_signal,  typename Container::value_type estimated_signal_kurtosis=1, typename Container::value_type estimated_noise_kurtosis=3)\n{\n    using std::log10;\n    return 10*log10(m2m4_snr_estimator(noisy_signal, estimated_signal_kurtosis, estimated_noise_kurtosis));\n}\n\n}\n#endif\n", "meta": {"hexsha": "d553192f0148ce5c7090de9d36eded0c23c3da73", "size": 12116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/signal_statistics.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/tools/signal_statistics.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/tools/signal_statistics.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": 35.0173410405, "max_line_length": 185, "alphanum_fraction": 0.6220699901, "num_tokens": 3060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5923738153296257}}
{"text": "\r\n/*********************************************************************************/\r\n/*                                                                               */\r\n/*     Command-line tool to access support vector machine                        */\r\n/*                          classification functionality.                        */\r\n/*                                                                               */\r\n/*     Alle Meije Wink                                                           */\r\n/*                                                                               */\r\n/*********************************************************************************/\r\n\r\n/*\r\n  Update history\r\n\r\n  Who    When       What\r\n  AMW    13-10-12   creation\r\n\r\n*/\n\r\n#define DLIB_PNG_SUPPORT\n\r\n#include <dlib/image_io.h>                              //        -- be able to write png\n#include <dlib/svm.h>                                   // n-dimensional vectors (n!=3) should use matrix in dlib\r\n#include <dlib/matrix.h>                                //        -- see http://dlib.net/linear_algebra.html#vector\n#include <dlib/svm/svm_c_linear_dcd_trainer.h>          // use svm trainer that supports \"warm starting\"\n                                                        // see http://dlib.net/dlib/svm/active_learning.h.html\r\n\n#include \"combisDesign.hpp\"\r\n\nusing namespace dlib;\n\r\nint combisSVM(bis::bisnifti<value_type> *currentImage, std::string designfile)\r\n{\n    // test combis with\n    // -i ~/work/documents/memorabel/PRNI2016/vumc/ECM/allmask_fmri.nii.gz --svm ~/work/documents/memorabel/PRNI2016/vumc/ECM/image_matrix.json -o ~/work/documents/memorabel/PRNI2016/vumc/ECM/weights.nii.gz\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // main data types\n\r\n    // classification table\r\n    std::vector<value_type>                   y;\r\n    std::vector<dlib::matrix<value_type,0,1>> x;\r\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // data input from file\n\r\n    // read the design\n    auto design_isbinary=combisSVMdesign(designfile, &x, &y, currentImage);   // read text / binary design\r\n\r\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // kernel design\n\n\n    // type of sample (1 image) and kernel\r\n    typedef dlib::matrix<value_type,0,1> sample_type;                              // one sample == one row of x\n    typedef dlib::linear_kernel<sample_type> kernel_type;                         // kernel data type\n\n    std::vector<sample_type> samples;                                             // sample set container\n    std::vector<value_type> labels;                                                // label set container\n\n    samples.assign(x.begin(), x.end());\n    labels.assign(y.begin(), y.end());\n\n    for (auto l: labels)\n        std::cout << l << std::endl;\n    if (!design_isbinary)\n        for (auto s: samples)\n            std::cout << s << std::endl;\n\n    // trainer for this type of kernel\n    // This trainer solves the \"C\" formulation of the SVM.  See the documentation for\n    // details.\n    dlib::svm_c_linear_dcd_trainer<kernel_type> linear_dcd_trainer;\n    linear_dcd_trainer.set_c(1000);\n\n    // normalise samples of x -- see http://dlib.net/svm_ex.cpp.html\n    //dlib::vector_normalizer<sample_type> normalizer;\n    //normalizer.train(samples);\n    //for (auto sx:samples)\n    //    sx = normalizer(sx);\n\n    // preserve the state of the classifier for warm-starting (see active_learing.h)\n    typedef typename dlib::svm_c_linear_dcd_trainer<kernel_type>::optimizer_state optimizer_state;\n    optimizer_state state;\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // construct decision / projection vector\n    typedef decision_function< kernel_type > dftype;\n    dftype decision_function = linear_dcd_trainer.train(samples, labels, state);\n\n    sample_type m(2);\n    m(0)=m(1)=0;\n    for (long i = 0; i < decision_function.alpha.nr(); ++i) {\n        std::cout << i << std::endl;\n        std::cout << decision_function.alpha(i) << std::endl;\n        std::cout << decision_function.basis_vectors(i) << std::endl;\n        m += decision_function.alpha(i) * decision_function.basis_vectors(i);\n    }\n    std::cout << \"b:\" << std::endl;\n    std::cout << decision_function.b << std::endl;\n\n    #define RED     \"\\033[31m\"      /* Red */\n    #define GREEN   \"\\033[32m\"      /* Green */\n    #define YELLOW  \"\\033[33m\"      /* Yellow */\n    #define RESET   \"\\033[0m\"\n\n    dlib::array2d<float> map_image;\n    float top=5,step=.49;\n    map_image.set_size(top/step+1,top/step+1);\n    for (float j=top; j>=0.; j-=step) {\n        for (float i=0.1; i<=top; i+=step) {\n            m(0)=i; m(1)=j;\n            auto f = decision_function(m);\n            map_image[i][j]=f;\n            if (f<-1.)\n                printf(\"%1.01f,%1.01f -> %s%5.02f%s  \",i,j,GREEN,-1.,RESET);\n            else if (f>1.)\n                printf(\"%1.01f,%1.01f -> %s%5.02f%s  \",i,j,RED,1.,RESET);\n            else\n                printf(\"%1.01f,%1.01f -> %s%5.02f%s  \",i,j,YELLOW,0.,RESET);\n            }\n        std::cout << std::endl; }\n    //dlib::save_png(map_image, \"/tmp/map_image.png\");\n\n    #undef RED\n    #undef GREEN\n    #undef YELLOW\n    #undef RESET\n\n    /*\n\n    if (!my_machine.margin_set.empty())\r\n        for (size_t k=0; k<my_machine.margin_set.size(); k++) {\r\n            if (my_machine.output(my_machine.margin_key[k]))\r\n                projection += (my_machine.weight[k] * x[my_machine.margin_key[k]]);\r\n            else\r\n                projection -= (my_machine.weight[k] * x[my_machine.margin_key[k]]);\n        }\n    if (!my_machine.error_set.empty())\r\n        for (size_t i=0; i<my_machine.error_set.size(); i++) {\r\n                projection -= (C * x[my_machine.every_key[my_machine.error_set[i]]]);\n        }\n    if (!my_machine.error_star_set.empty())\r\n        for (size_t i=0; i<my_machine.error_star_set.size(); i++) {\r\n                projection -= (C * x[my_machine.every_key[my_machine.error_star_set[i]]]);\n        }\n    auto projectionbias=my_machine.bias;\r\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // demonstrate output\n\n    if (y.size() == 4)\r\n    {\r\n\r\n        // test data with 0..5 x 0..5 grid and print classes\r\n        double stp=1.0;//                                                             // sample the input space and show the classification\r\n        for ( double y=5.; y>=0.; y-=stp )                                            // at all sampled points\r\n        {\r\n            for ( double x=0.; x<=5.; x+=stp )\r\n            {\r\n                ublas::vector <value_type> testxy(2);\r\n                testxy[0]=x;\r\n                testxy[1]=y;\r\n                std::cout << \"(\"\r\n                        << std::fixed << std::setprecision(1) << x << \",\"\r\n                        << std::fixed << std::setprecision(1) << y << \") -> \"\r\n                        << my_machine (testxy) << \", \" ;\r\n            }\r\n            std::cout << std::endl;\r\n        }\r\n        std::cout << std::endl;\n\r\n        // sample the input space and show the classification\r\n        for ( double y=5.; y>=0.; y-=stp )                                            // at all sampled points\r\n        {\r\n            for ( double x=0.; x<=5.; x+=stp )\r\n            {\r\n                ublas::vector <value_type> testxy(2);\r\n                testxy[0]=x;\r\n                testxy[1]=y;\r\n                std::cout << \"(\"\r\n                        << std::fixed << std::setprecision(1) << x << \",\"\r\n                        << std::fixed << std::setprecision(1) << y << \") -> \"\n                        << projectionbias + blas::dot ( projection, testxy ) << \", \" ;\r\n            }\r\n            std::cout << std::endl;\r\n        }\r\n\r\n        std::cout << \"weights:\\n\";\r\n        auto alpha=my_machine.weight;\r\n        for (auto a: alpha) std::cout << a << \" \";\r\n        std::cout << std::endl;\r\n        std::cout << \"margin vectors:\\n\";\r\n        {auto vecset=my_machine.margin_set;\r\n        for (auto v: vecset) std::cout << v << \" \";}\r\n        std::cout << std::endl;\r\n        std::cout << \"bias:\\n\" << my_machine.bias << std::endl;\r\n        std::cout << \"C:\\n\" << my_machine.C << std::endl;\r\n\r\n        std::cout << \"error vectors:\\n\";\r\n        {auto vecset=my_machine.error_set;\r\n        for (auto v: vecset) std::cout << v << \" \";}\r\n        std::cout << std::endl;\r\n        std::cout << \"remaining vectors:\\n\";\r\n        {auto vecset=my_machine.remaining_set;\r\n        for (auto v: vecset) std::cout << v << \" \";}\r\n        std::cout << std::endl;\r\n\r\n    }\r\n\r\n    // if images -> make a projection image (weights map)\r\n    // that shows the voting rights of each brain region\r\n    if (design_isbinary) { // images design\n\n        currentImage->bisArray::operator*=(0);\n        {size_t i=0;\n            for (auto m: mask)\n                currentImage->my_data[m]=projection[i++]/mstd;\r\n        }\n        std::cout << \"mask size: \" << mask.size() << std::endl;\n\n        std::cout << \"projections of training images on weight map: \" << std::endl;\n        for (auto k:keys)\r\n            std::cout << \"specimen \" << k << \", class \" << y[k] << \" SVM output \" << my_machine(x[k]) << \" projection \" << projectionbias + blas::dot ( projection, x[k] ) << std::endl;\r\n\r\n        auto iminfo=nifti_copy_nim_info(currentImage->getHeader());\n\n        // std::cout << \"storing bias in toffset \" << std::endl;\n        iminfo->toffset=float(projectionbias);\n        //iminfo->scl_inter=float(projectionbias);\n\n        // std::cout << \"map in current image \" << std::endl;\r\n        currentImage->setHeader(iminfo);\n\r\n        //nifti_image_infodump(iminfo);\n\n    }\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////////////////////////////////////////////////////////////////////////////////\n    // cross-validation\n\n    auto cv=1;\n\n    if (cv) {\n\n    std::vector<double> Cs = {1./16000., 1./8000, 1./4000., 1./2000., 1./1000.,};\n\n    for (auto C2: Cs) {\n\n        std::cout << \"C value = \" << std::setw(6) << C2 << std::endl;\n\n        unsigned n=0,p=0,tn=0,tp=0,sv=0;\n        for (auto k2:keys) {\n            auto keys2 = keys;\n            keys2.erase(keys2.begin()+k2);\n            onlinesvm_machine_type my_machine2( C2, my_kernel, training_data );        // C = 1.0\n            my_machine2.learn( keys2.begin(), keys2.end() );                           // start the learning\n            auto in2=y[k2];\n            auto out2=2*my_machine2(x[k2])-1;\r\n            std::cout << \"crossval \" << k2 << \", class \" << in2 << \" SVM output \" << out2\n                      << \", #SV \" << my_machine2.margin_set.size()+my_machine2.margin_set.size()\n                      << \", bias \" << my_machine2.bias << std::endl;\n            if (in2<0)\n                {n++; tn+=(out2<0);}\n            else\n                {p++; tp+=(out2>0);}\n            sv=sv+my_machine2.margin_set.size();\n        }\n\n        sv/=(keys.size()-1);\n        auto tnr=double(tn)/double(n);\n        auto tpr=double(tp)/double(p);\n        std::cout << \"  true negative ratio = \" << tnr\n                  << \", true positive ratio = \" << tpr\n                  << \", balanced accuracy   = \" << (tnr+tpr)/2.\n                  << \", average #SV = \" << sv << std::endl;\n\n\n    }\n\r\n    }\n    */\r\n\t\r\n\treturn 0;\r\n\t\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "127bae5b3e44975b0687e28ebe193dd271a24464", "size": 11849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "combis/include/combisSVM.hpp", "max_stars_repo_name": "amwink/bis", "max_stars_repo_head_hexsha": "5d12c54b23be202d179fea9558d1aab09c35392e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "combis/include/combisSVM.hpp", "max_issues_repo_name": "amwink/bis", "max_issues_repo_head_hexsha": "5d12c54b23be202d179fea9558d1aab09c35392e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "combis/include/combisSVM.hpp", "max_forks_repo_name": "amwink/bis", "max_forks_repo_head_hexsha": "5d12c54b23be202d179fea9558d1aab09c35392e", "max_forks_repo_licenses": ["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.3027210884, "max_line_length": 206, "alphanum_fraction": 0.4435817369, "num_tokens": 2773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5922816282217286}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_ROTATION_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_ROTATION_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/algebra/algorithms/detail.hpp>\n\n#include <boost/geometry/extensions/algebra/geometries/concepts/rotation_quaternion_concept.hpp>\n\n// TODO - for multiplication of coordinates\n// if coordinate_type is_integral - use double as the result type\n\nnamespace boost { namespace geometry {\n\nnamespace detail { namespace rotation {\n\ntemplate <typename V1, typename V2, typename Rotation, typename Tag1, typename Tag2, std::size_t Dimension>\nstruct matrix\n{\n    BOOST_MPL_ASSERT_MSG(false, NOT_IMPLEMENTED_FOR_THIS_DIMENSION, (Rotation));\n};\n\ntemplate <typename V1, typename V2, typename Rotation>\nstruct matrix<V1, V2, Rotation, vector_tag, vector_tag, 3>\n{\n    static const bool cs_check =\n        ::boost::is_same<typename traits::coordinate_system<V1>::type, cs::cartesian>::value &&\n        ::boost::is_same<typename traits::coordinate_system<V2>::type, cs::cartesian>::value;\n\n    BOOST_MPL_ASSERT_MSG(cs_check, NOT_IMPLEMENTED_FOR_THOSE_SYSTEMS, (V1, V2));\n\n    typedef typename geometry::select_most_precise<\n        typename traits::coordinate_type<V1>::type,\n        typename traits::coordinate_type<V2>::type\n    >::type cv_type;\n\n    typedef typename geometry::select_most_precise<\n        cv_type,\n        typename traits::coordinate_type<Rotation>::type\n    >::type cr_type;\n\n    typedef model::vector<cv_type, 3> vector_type;\n\n    inline static void apply(V1 const& v1, V2 const& v2, Rotation & r)\n    {\n        namespace da = detail::algebra;\n\n        // TODO - should store coordinates in more precise variables before the normalization?\n\n        // angle\n        cv_type d = da::dot<0, 0, 3>(v1, v2);\n        cv_type l =\n            math::sqrt(da::dot<0, 0, 3>(v1, v1) * da::dot<0, 0, 3>(v2, v2));\n        cv_type c = d / l;\n\n        // rotation angle == 0\n        // not needed really, because in this case function still returns zero-rotation\n        if ( 1 - std::numeric_limits<cv_type>::epsilon() <= c )\n        {\n            set<0, 0>(r, 1); set<0, 1>(r, 0); set<0, 2>(r, 0);\n            set<1, 0>(r, 0); set<1, 1>(r, 1); set<1, 2>(r, 0);\n            set<2, 0>(r, 0); set<2, 1>(r, 0); set<2, 2>(r, 1);\n            return;\n        }\n\n        vector_type axis;\n\n        // rotation angle = 180\n        if ( c <= std::numeric_limits<cv_type>::epsilon() - 1 )\n        {\n            // find arbitrary rotation axis perpendicular to v1\n            da::cross<0, 0, 0>(vector_type(1, 0, 0), v1, axis);\n            if ( da::dot<0, 0, 3>(axis, axis) < std::numeric_limits<cr_type>::epsilon() )\n                da::cross<0, 0, 0>(vector_type(0, 1, 0), v1, axis);\n        }\n        else\n        {\n            // rotation axis\n            da::cross<0, 0, 0>(v1, v2, axis);\n        }\n\n        // sin\n        cv_type s = math::sqrt(1 - c * c);\n        cv_type t = 1 - c;\n        // normalize axis\n        da::normalize<0, 3>(axis);\n\n        cv_type txx = t*get<0>(axis)*get<0>(axis);\n        cv_type tyy = t*get<1>(axis)*get<1>(axis);\n        cv_type tzz = t*get<2>(axis)*get<2>(axis);\n        cv_type txy = t*get<0>(axis)*get<1>(axis);\n        cv_type sx = s*get<0>(axis);\n        cv_type txz = t*get<0>(axis)*get<2>(axis);\n        cv_type sy = s*get<1>(axis);\n        cv_type tyz = t*get<1>(axis)*get<2>(axis);\n        cv_type sz = s*get<2>(axis);\n\n        set<0, 0>(r, txx+c); set<0, 1>(r, txy-sz); set<0, 2>(r, txz+sy);\n        set<1, 0>(r, txy+sz); set<1, 1>(r, tyy+c); set<1, 2>(r, tyz-sx);\n        set<2, 0>(r, txz-sy); set<2, 1>(r, tyz+sx); set<2, 2>(r, tzz+c);\n    }\n};\n\ntemplate <typename V1, typename V2, typename Rotation>\nstruct matrix<V1, V2, Rotation, vector_tag, vector_tag, 2>\n{\n    static const bool cs_check =\n        ::boost::is_same<typename traits::coordinate_system<V1>::type, cs::cartesian>::value &&\n        ::boost::is_same<typename traits::coordinate_system<V2>::type, cs::cartesian>::value;\n\n    BOOST_MPL_ASSERT_MSG(cs_check, NOT_IMPLEMENTED_FOR_THOSE_SYSTEMS, (V1, V2));\n\n    typedef typename geometry::select_most_precise<\n        typename traits::coordinate_type<V1>::type,\n        typename traits::coordinate_type<V2>::type\n    >::type cv_type;\n\n    inline static void apply(V1 const& v1, V2 const& v2, Rotation & r)\n    {\n        namespace da = detail::algebra;\n\n        // TODO - should store coordinates in more precise variables before the normalization?\n\n        // angle\n        cv_type d = da::dot<0, 0, 2>(v1, v2);\n        cv_type l =\n            math::sqrt(da::dot<0, 0, 2>(v1, v1) * da::dot<0, 0, 2>(v2, v2));\n        cv_type c = d / l;\n\n        // TODO return also if l == 0;\n\n        // rotation angle == 0\n        // not needed really, because in this case function still returns zero-rotation\n        if ( 1 - std::numeric_limits<cv_type>::epsilon() <= c )\n        {\n            set<0, 0>(r, 1); set<0, 1>(r, 0);\n            set<1, 0>(r, 0); set<1, 1>(r, 1);\n        }\n        // rotation angle = 180\n        else if ( c <= std::numeric_limits<cv_type>::epsilon() - 1 )\n        {\n            set<0, 0>(r, -1); set<0, 1>(r, 0);\n            set<1, 0>(r, 0); set<1, 1>(r, -1);\n        }\n        else\n        {\n            // sin\n            cv_type s = (get<0>(v1) * get<1>(v2) - get<1>(v1) * get<0>(v2)) / l;\n\n            set<0, 0>(r, c); set<0, 1>(r, -s);\n            set<1, 0>(r, s); set<1, 1>(r, c);\n        }\n    }\n};\n\n}} // namespace detail::rotation\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch {\n\ntemplate <typename V1, typename V2, typename Rotation,\n          typename Tag1 = typename tag<V1>::type,\n          typename Tag2 = typename tag<V2>::type,\n          typename RTag = typename tag<Rotation>::type\n>\nstruct rotation\n{\n    BOOST_MPL_ASSERT_MSG(false, NOT_IMPLEMENTED_FOR_THOSE_TAGS, (Tag1, Tag2, Rotation));\n};\n\ntemplate <typename V1, typename V2, typename Rotation>\nstruct rotation<V1, V2, Rotation, vector_tag, vector_tag, rotation_quaternion_tag>\n{\n    static const bool cs_check =\n        ::boost::is_same<typename traits::coordinate_system<V1>::type, cs::cartesian>::value &&\n        ::boost::is_same<typename traits::coordinate_system<V2>::type, cs::cartesian>::value;\n\n    BOOST_MPL_ASSERT_MSG(cs_check, NOT_IMPLEMENTED_FOR_THOSE_SYSTEMS, (V1, V2));\n\n    typedef typename geometry::select_most_precise<\n        typename traits::coordinate_type<V1>::type,\n        typename traits::coordinate_type<V2>::type\n    >::type cv_type;\n\n    typedef typename geometry::select_most_precise<\n        cv_type,\n        typename traits::coordinate_type<Rotation>::type\n    >::type cr_type;\n\n    typedef model::vector<cv_type, 3> vector_type;\n\n    inline static void apply(V1 const& v1, V2 const& v2, Rotation & r)\n    {\n        namespace da = detail::algebra;\n\n        // TODO - should store coordinates in more precise variables before the normalization?\n\n        cv_type d = da::dot<0, 0, 3>(v1, v2); // l1 * l2 * cos\n        cv_type l = math::sqrt(da::dot<0, 0, 3>(v1, v1) * da::dot<0, 0, 3>(v2, v2)); // l1 * l2\n        cv_type w = l + d; // l1 * l2 * ( 1 + cos )\n\n        // rotation angle == 0\n        // not needed really, because in this case function still returns zero-rotation\n        if ( 2*l-std::numeric_limits<cv_type>::epsilon() <= w )\n        {\n            set<0>(r, 1); set<0>(r, 0); set<0>(r, 0); set<0>(r, 0);\n        }\n        // rotation angle == pi\n        else if ( w <= std::numeric_limits<cv_type>::epsilon() )\n        {\n            set<0>(r, 0);\n            // find arbitrary rotation axis perpendicular to v1\n            da::cross<0, 0, 1>(vector_type(1, 0, 0), v1, r);\n            if ( da::dot<1, 1, 3>(r, r) < std::numeric_limits<cr_type>::epsilon() )\n                da::cross<0, 0, 1>(vector_type(0, 1, 0), v1, r);\n\n            // normalize axis\n            da::normalize<1, 3>(r);\n        }\n        else\n        {\n            set<0>(r, w); // l1 * l2 * ( 1 + cos )\n            // rotation axis\n            da::cross<0, 0, 1>(v1, v2, r); // l1 * l2 * sin * UNITA\n\n            // normalize quaternion\n            da::normalize<0, 4>(r);\n        }\n    }\n};\n\ntemplate <typename V1, typename V2, typename Rotation>\nstruct rotation<V1, V2, Rotation, vector_tag, vector_tag, rotation_matrix_tag>\n    : detail::rotation::matrix<V1, V2, Rotation, vector_tag, vector_tag, traits::dimension<Rotation>::value>\n{};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\ntemplate <typename V1, typename V2, typename Rotation>\ninline void rotation(V1 const& v1, V2 const& v2, Rotation & r)\n{\n    concepts::check_concepts_and_equal_dimensions<V1 const, V2 const>();\n    // TODO - replace the following by check_equal_dimensions\n    concepts::check_concepts_and_equal_dimensions<V1 const, Rotation>();\n\n    dispatch::rotation<V1, V2, Rotation>::apply(v1, v2, r);\n}\n\ntemplate <typename Rotation, typename V1, typename V2>\ninline Rotation return_rotation(V1 const& v1, V2 const& v2)\n{\n    Rotation r;\n    translation(v1, v2, r);\n    return r;\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_ROTATION_HPP\n", "meta": {"hexsha": "dc9e2db2f074119c5e9484ce276a530efb5584ce", "size": 9421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/algebra/algorithms/rotation.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T17:40:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T17:40:19.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/algebra/algorithms/rotation.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_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/algebra/algorithms/rotation.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.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.0223048327, "max_line_length": 108, "alphanum_fraction": 0.6020592294, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5922816111115461}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <gtsam/slam/dataset.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\nint main (int argc, char** argv)\n{\n    if (argc != 2) {\n        std::cout << \"Usage: pose_graph_gtsam sphere.g2o\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    std::ifstream fin(argv[1]);\n    if (!fin) {\n        std::cout << \"file \" << argv[1] << \" does not exist.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    gtsam::NonlinearFactorGraph::shared_ptr factor_graph_ptr(new gtsam::NonlinearFactorGraph);  // gtsam of factor graph\n    gtsam::Values::shared_ptr initial_ptr(new gtsam::Values);                                   // values of initialized\n    \n    /**\n     * get vertices & edges information form the sphere.g2o files.\n     */\n    int cntVertex = 0, cntEdge = 0;\n    std::cout << \"reading from g2o file.\" << std::endl;\n    \n    while (!fin.eof()) {\n        std::string name;\n        fin >> name;\n        \n        if (name == \"VERTEX_SE3:QUAT\") {\n            // vertex \n            gtsam::Key id;\n            fin >> id;\n            \n            double data[7];\n            for (int i = 0; i < 7; i++) {\n                fin >> data[i];\n            }\n            gtsam::Rot3 R = gtsam::Rot3::quaternion(data[6], data[3], data[4], data[5]);\n            gtsam::Point3 t(data[0], data[1], data[2]);\n            initial_ptr->insert(id, gtsam::Pose3(R, t));        // add initial values\n            cntVertex ++;\n\n        } else if (name == \"EDGE_SE3:QUAT\") {\n            gtsam::Matrix m = gtsam::I_6x6;             // information matrix\n            gtsam::Key idx1, idx2;\n            fin >>  idx1 >> idx2;\n            double data[7];\n            for (int i = 0; i < 7; i++) \n                fin >> data[i];\n            \n            gtsam::Rot3 R = 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            \n            // information matrix\n            gtsam::Matrix mgsam_information = gtsam::I_6x6;\n            mgsam_information.block<3, 3>(0, 0) = m.block<3, 3>(3, 3);  // cov rotation\n            mgsam_information.block<3, 3>(3, 3) = m.block<3, 3>(0, 0);  // cov translation\n            mgsam_information.block<3, 3>(0, 3) = m.block<3, 3>(0, 3);  // off diagonal\n            mgsam_information.block<3, 3>(3, 0) = m.block<3, 3>(3, 0);  // off diagonal\n            \n            gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information(mgsam_information);    // Gaussian noise model\n            gtsam::NonlinearFactor::shared_ptr factor(new gtsam::BetweenFactor<gtsam::Pose3>(idx1, idx2, gtsam::Pose3(R, t), model)); // add a factor\n            factor_graph_ptr->push_back(factor);\n            cntEdge ++;\n        }\n        \n        if (!fin.good()) break;\n    }\n    \n    std::cout << \"read total \" << cntVertex << \" vertices, \" << \" cntEdge.\" << std::endl;\n    \n    /* 固定第一个顶点，在gtsam中相当于添加一个先验因子 */\n    gtsam::NonlinearFactorGraph graph_with_prior = *factor_graph_ptr;\n    gtsam::noiseModel::Diagonal::shared_ptr prior_model = gtsam::noiseModel::Diagonal::Variances(\n        (gtsam::Vector(6) << 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6).finished()\n    );\n    \n    gtsam::Key first_key = 0;\n    \n//     for(const gtsam::Values::ConstKeyValuePair& key_value : *initial_ptr) {\n    for (auto key_value : *initial_ptr) {\n        std::cout << \"Adding prior to g2o file\" << std::endl;\n        graph_with_prior.add(gtsam::PriorFactor<gtsam::Pose3>(\n            key_value.key, key_value.value.cast<gtsam::Pose3>(), prior_model)\n        );\n        break;\n    }\n    \n    // 开始因子图优化，配置优化选项\n    std::cout << \"optimizing the factor graph.\" << std::endl;\n    \n    // use LM optimization\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(graph_with_prior, *initial_ptr, params_lm);\n    \n    // try use 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_GN(graph_with_prior, *initial_ptr, params_gn);\n    \n    gtsam::Values result = optimizer_LM.optimize();\n    \n    std::cout << \"optimization complete.\" << std::endl;\n    \n    std::cout << \"initial error: \" << factor_graph_ptr->error(*initial_ptr) << std::endl;\n    std::cout << \"final error: \" << factor_graph_ptr->error(result) << std::endl;\n    \n    std::cout << \"done.\\r\\nwrite to g2o ...\" << std::endl;\n    \n    std::ofstream fout(\"result_gtsam.g2o\");\n    // vertex\n    for (auto key_value : result) {\n//     for (const gtsam::Values::ConstKeyValuePair& key_value : result) {\n        gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>();\n        gtsam::Point3 t = pose.translation();\n        gtsam::Quaternion q = pose.rotation().toQuaternion();\n        fout << \"VERTEX_SE3:QUAT \" << key_value.key << \" \"\n             << t.x() << \" \" << t.y() << \" \" << t.z() << \" \"\n             << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << std::endl;\n    }\n    // edge \n    for (auto factor : *factor_graph_ptr) {\n//     for (gtsam::NonlinearFactor::shared_ptr factor : *factor_graph_ptr) {\n        gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = boost::dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>(factor);\n//         gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = std::dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>(factor);    // this program is error !!!!!!\n        if (f) {\n            gtsam::SharedNoiseModel model = f->noiseModel();\n            gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = boost::dynamic_pointer_cast<gtsam::noiseModel::Gaussian>(model);\n            if (gaussianModel) {\n                gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R();\n                gtsam::Pose3 pose = f->measured();\n                gtsam::Point3 t = pose.translation();\n                gtsam::Quaternion q = pose.rotation().toQuaternion();\n                \n                fout << \"EDGE_SE3:QUAT \" << f->key1() << \" \" << f->key2() << \" \"\n                     << t.x() << \" \" << t.y() << \" \" << t.z() << \" \"\n                     << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w() << \" \";\n                \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(3, 3, 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                \n                for (int i = 0; i < 6; i++) {\n                    for (int j = i; j < 6; j++) {\n                        fout << infoG2O(i, j) << \" \";\n                    }\n                }\n                \n                fout << std::endl;\n            }\n        }\n    }\n    \n    fout.close();\n    std::cout << \"done.\" << std::endl;\n    \n    return 0;\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1c4a9375fcce1aa571b9bb40887fa5c8a7e89fd0", "size": 7617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_graph/src/pose_graph_gtsam.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_graph/src/pose_graph_gtsam.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_graph/src/pose_graph_gtsam.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": 39.671875, "max_line_length": 167, "alphanum_fraction": 0.5231718524, "num_tokens": 2267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5922430084217709}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <mumpscpp/mumpscpp.h>\n#include <Eigen/core>\n#include <shiva/Environment.h>\n#include <shiva/Communicator.h>\n#include <mumpscpp/UblasCoordinateAdaptor.h>\n#include <mumpscpp/UblasVectorAdaptor.h>\n#include <mumpscpp/EigenVector.h>\n\nshiva::environment mpi_env;\n\nvoid assemble_symmetric(mumpscpp::UblasCoordinateSparseMatrix& k)\n{\n  // lower triangular part\n  const size_t matrix_size = 3;\n  k.resize(matrix_size, matrix_size, false);\n  k.clear();\n  k.append_element(0, 0, 2.0);\n  k.append_element(1, 0, -1.0);\n  k.append_element(1, 1, 2.0);\n  k.append_element(2, 0, 0.0);\n  k.append_element(2, 1, -1.0);\n  k.append_element(2, 2, 2.0);\n\n  k.sort();\n}\n\nint main()\n{\n  shiva::communicator world;\n  const size_t matrix_size = 3;\n\n  mumpscpp::UblasCoordinateSparseMatrix k;\n  assemble_symmetric(k);\n  mumpscpp::EigenVector f = Eigen::VectorXd::Zero(matrix_size);\n  f[0] = 1.25;\n  f[1] = -2.0;\n  f[2] = 1.75;\n\n  mumpscpp::Mumps<double> mumps(mumpscpp::MatrixType::symmetric, mumpscpp::HostParallelism::involved, world.fortran_mpi_communicator());\n  mumps.set_output_level(mumpscpp::OutputLevel::error);\n  mumps.setDistributedInput(k);\n\n  mumps.analyzeFactorize();\n  mumps.solve(f);\n\n  std::cout << f[0] << \" should be \" << 0.375 << \"\\n\";\n  std::cout << f[1] << \" should be \" << -0.5  << \"\\n\";\n  std::cout << f[2] << \" should be \" << 0.625 << \"\\n\";\n\n  mumps.destroy();\n}", "meta": {"hexsha": "07bba66079325e6632b41cd9594a836682433bc3", "size": 1436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "conan-recipe/test_package/example.cpp", "max_stars_repo_name": "tuncb/mumpscpp", "max_stars_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-02T10:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-02T10:37:37.000Z", "max_issues_repo_path": "conan-recipe/test_package/example.cpp", "max_issues_repo_name": "tuncb/mumpscpp", "max_issues_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conan-recipe/test_package/example.cpp", "max_forks_repo_name": "tuncb/mumpscpp", "max_forks_repo_head_hexsha": "3af29ca465828297aec9205dbc182c82b1ab69a1", "max_forks_repo_licenses": ["Apache-2.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.0943396226, "max_line_length": 136, "alphanum_fraction": 0.68454039, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5922429987771004}}
{"text": "#include <cinttypes>\n#include <cmath>\n#include <complex>\n#include <iostream>\n\n#define png_infopp_NULL nullptr\n#define int_p_NULL      nullptr\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/io/png_io.hpp>\n\n\nnamespace gil = boost::gil;\n\n\nstruct mandelbrot_fn {\n    using const_t           = mandelbrot_fn;\n    using value_type        = gil::gray8_pixel_t;\n    using reference         = value_type;\n    using const_reference   = value_type;\n    using point_t           = gil::point2<int>;\n    using result_type       = value_type;\n    using argument_type     = point_t;\n    static constexpr bool is_mutable = false;\n\n    explicit mandelbrot_fn(point_t const& size) :\n        m_size{ size }\n    {}\n\n    auto operator()(point_t const& p) const -> result_type {\n        auto map = [](double val, double r1_from, double r1_to, double r2_from, double r2_to) -> double {\n            return ((val - r1_from) / (r1_to - r1_from)) * (r2_to - r2_from) + r2_from;\n        };\n\n        // map x to [-2, 1] and y to [1.5, -1.5]\n        std::complex<double> c{ map(p.x, 0, m_size.x, -2, 1), map(p.y, 0, m_size.y, 1.5, -1.5) };\n        auto lc = c;\n        for (auto i = 0; i < 100; ++i) {\n            if (std::pow(lc.real(), 2) + std::pow(lc.imag(), 2) > 4) {\n                return result_type{ static_cast<gil::bits8>(i / 100.0 * 255) };\n            }\n            lc = std::pow(lc, 2) + c;\n        }\n\n        return result_type{ 0 };\n    }\n\nprivate:\n    point_t m_size;\n};\n\n\nint main() {\n    using point_t = mandelbrot_fn::point_t;\n    using locator_t = gil::virtual_2d_locator<mandelbrot_fn, false>;\n    using image_view_t = gil::image_view<locator_t>;\n\n    point_t size{ 5000, 5000 };\n    image_view_t view{ size, locator_t{ point_t{ 0, 0 }, point_t{ 1, 1 }, mandelbrot_fn{ size } } };\n    gil::png_write_view(\"mandelbrot.png\", view);\n}\n", "meta": {"hexsha": "0d8349242a75445cf85b0292fe64222f5d945467", "size": 1839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/MandelbrotSet.cpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/MandelbrotSet.cpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/MandelbrotSet.cpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 30.1475409836, "max_line_length": 105, "alphanum_fraction": 0.5927134312, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5921877976443745}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <cassert>\n#include <stdexcept>\n#include <tuple>\n\n//! The gradient of the shape function (on the reference element)\n//!\n//! We have three shape functions\n//!\n//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientLambda(const int i, double x, double y) {\n\t// (write your solution here)\n\tstd::ignore = x;\n\tstd::ignore = y;\n\tassert(0 <= i && i <= 2);\n\tswitch (i) {\n\t\tcase 0:\n\t\t\treturn Eigen::Vector2d(-1, -1);\n\t\tcase 1:\n\t\t\treturn Eigen::Vector2d(1, 0);\n\t\tcase 2:\n\t\t\treturn Eigen::Vector2d(0, 1);\n\t\tdefault:\n\t\t\tthrow std::domain_error(\"i not in {0,1,2}\");\n\t}\n\n\treturn Eigen::Vector2d(0, 0); //remove when implemented\n}\n", "meta": {"hexsha": "792e32ddc92c8d0f7df1331136496693e73427a6", "size": 829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/grad_shape.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/2d-linFEM/grad_shape.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2/2d-linFEM/grad_shape.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.90625, "max_line_length": 89, "alphanum_fraction": 0.6706875754, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.5921761621512944}}
{"text": "//\n// Created by riku on 1/3/18.\n//\n#include <NTL/ZZ.h>\n#include <HElib/NumbTh.h>\n#include <HElib/FHEContext.h>\n#include <iostream>\nvoid MiniONN(long m) {\n    long p = NTL::RandomPrime_long(16, 20);\n    while (true) {\n        long d = multOrd(p, m);\n        if (d == 1)\n            break;\n        do {\n            p = NTL::NextPrime(p + 2);\n        } while (m % p == 0);\n    };\n    std::cout << m << \" \" << p << std::endl;\n}\n\nbool check(NTL::ZZX const& factor) {\n\tfor (long i = 1; i < NTL::deg(factor); i++) {\n\t\tif (NTL::coeff(factor, i) != 0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid DoublePacking(long m, long slots) {\n\tlong p = NTL::RandomPrime_long(17, 20);\n\tlong phim = phi_N(m);\n\tassert(phim == (m >> 1));\n\tlong count = 0;\n\twhile (count < 10) {\n\t\tlong d = multOrd(p, m);\n\t\tlong s = phim / d;\n\t\tif (s == slots) {\n\t\t\tFHEcontext context(m, p, 1);\n\t\t\tconst auto &ftrs = context.alMod.getFactorsOverZZ();\n\t\t\tbool ok = true;\n\t\t\tfor (const auto& f : ftrs)\n\t\t\t\tok &= check(f);\n\t\t\tif (ok) {\n\t\t\t\tprintf(\"%ld %ld %f\\n\", m, p, std::log(p) / std::log(2.));\n\t\t\t\tcount += 1;\n\t\t\t}\n\t\t}\n\t\tdo {\n            p = NTL::NextPrime(p + 2);\n        } while (m % p == 0);\n\t};\n}\n\nint main() {\n    //MiniONN(8192);\n\tDoublePacking(16384, 64);\n\t//DoublePacking(8192, 64);\n\t// DoublePacking(8192, 256);\n\t// DoublePacking(8192, 512);\n\t// DoublePacking(8192, 1024);\n\t// DoublePacking(8192, 2048);\n    return 0;\n}\n\n", "meta": {"hexsha": "99e567b433f984ed9128a9651a28887a449b30b7", "size": 1387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FindParams.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/FindParams.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/FindParams.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": 21.3384615385, "max_line_length": 61, "alphanum_fraction": 0.5320836337, "num_tokens": 500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5920821561933933}}
{"text": "#include <k52/optimization/conjugate_gradient_method.h>\n\n#ifdef BUILD_WITH_MPI\n\n#include <boost/mpi.hpp>\n#include <k52/parallel/mpi/constants.h>\n\n#endif\n\n#include <cmath>\n#include <stdexcept>\n#include <iostream>\n\n#include <k52/common/floating_point.h>\n#include <k52/optimization/params/i_continuous_parameters.h>\n\nusing ::std::vector;\nusing ::k52::common::FloatingPoint;\n\nnamespace k52\n{\nnamespace optimization\n{\n\nConjugateGradientMethod::ConjugateGradientMethod(\n    double precision,\n    double increment_of_the_argument,\n    size_t number_of_iterations)\n{\n    precision_ = precision;\n    increment_of_the_argument_ = increment_of_the_argument;\n    number_of_iterations_ = number_of_iterations;\n}\n\nConjugateGradientMethod* ConjugateGradientMethod::Clone() const\n{\n    return new ConjugateGradientMethod(precision_, increment_of_the_argument_, number_of_iterations_);\n}\n\nstd::string ConjugateGradientMethod::get_name() const\n{\n    return \"Conjugate Gradient Method\";\n}\n\n#ifdef BUILD_WITH_MPI\nvoid ConjugateGradientMethod::Send(boost::mpi::communicator* communicator, int target) const\n{\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, increment_of_the_argument_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, number_of_iterations_);\n}\n\nvoid ConjugateGradientMethod::Receive(boost::mpi::communicator* communicator, int source)\n{\n    communicator->recv(source,\n        k52::parallel::mpi::constants::kCommonTag,\n        precision_);\n    communicator->recv(source,\n        k52::parallel::mpi::constants::kCommonTag,\n        increment_of_the_argument_);\n    communicator->recv(source,\n        k52::parallel::mpi::constants::kCommonTag,\n        number_of_iterations_);\n}\n#endif\n\nvector<double> ConjugateGradientMethod::FindOptimalParameters(\n    const vector<double>& initial_parameters)\n{\n    vector<double> parameters = initial_parameters;\n\n    vector<double> gradient = CalculateGradient(parameters);\n    vector<double> previous_gradient(parameters.size());\n\n    vector<double> search_direction(parameters.size());\n    vector<double> previous_search_direction(parameters.size());\n\n    double weighting_coefficient = 0;\n    double exit = 0;\n    size_t iteration = 1;\n\n    //http://en.wikipedia.org/wiki/Nonlinear_conjugate_gradient_method\n    do\n    {\n        previous_search_direction = search_direction;\n        search_direction = FindNextSearchDirection(gradient, previous_search_direction, weighting_coefficient, iteration);\n\n        double minimizing_parameter = PerformOneDimensionalSearch(parameters, search_direction);\n        //TODO use vector math\n        for (size_t i = 0; i<parameters.size(); i++)\n        {\n            parameters[i] += minimizing_parameter * search_direction[i];\n        }\n\n        previous_gradient = gradient;\n        gradient = CalculateGradient(parameters);\n\n        weighting_coefficient = CalculateWeightingCoefficient(gradient, previous_gradient);\n\n        //TODO use vector math\n        exit = 0;\n        for (size_t i = 0; i<parameters.size(); i++)\n        {\n            exit += pow(gradient[i], 2);\n        }\n        exit = sqrt(exit);\n\n        iteration++;\n        if (iteration == number_of_iterations_)\n        {\n            std::cout << \"Solution not found\" << std::endl;\n            break;\n        }\n    } while (exit >= precision_);\n\n    return parameters;\n}\n\ndouble ConjugateGradientMethod::CountCorrectedObjectiveFunctionValue(\n    const vector<double>& parameters)\n{\n    //Searching for minimum in the method\n    return CountObjectiveFunctionValueToMinimize(parameters);\n}\n\ndouble ConjugateGradientMethod::CalculateDerivative(\n    const vector<double>& parameters,\n    size_t index)\n{\n    vector<double> decrement_function (parameters);\n    vector<double> increment_function (parameters);\n    decrement_function[index] = parameters[index] - increment_of_the_argument_/2;\n    increment_function[index] = parameters[index] + increment_of_the_argument_/2;\n    double increment_function_value = CountCorrectedObjectiveFunctionValue(increment_function);\n    double decrement_function_value = CountCorrectedObjectiveFunctionValue(decrement_function);\n    return (increment_function_value - decrement_function_value)/increment_of_the_argument_;\n}\n\nvector<double> ConjugateGradientMethod::FindNextSearchDirection(\n    const vector<double>& gradient,\n    const vector<double>& previous_search_direction,\n    double weighting_coefficient,\n    int iteration)\n{\n    vector<double> search_direction = gradient;\n\n    if (iteration > 1)\n    {\n        //TODO use vector math\n        for (size_t i=0; i<gradient.size(); i++)\n        {\n            search_direction[i] += weighting_coefficient * previous_search_direction[i];\n        }\n    }\n\n    return search_direction;\n}\n\nvector<double> ConjugateGradientMethod::CalculateGradient(\n    const vector<double>& parameters)\n{\n    vector<double> gradient(parameters.size());\n\n    //TODO use vector math\n    for (size_t i=0; i<parameters.size(); i++)\n    {\n        gradient[i] = CalculateDerivative(parameters, i);\n    }\n\n    return gradient;\n}\n\ndouble ConjugateGradientMethod::PerformOneDimensionalSearch(\n    const vector<double>& parameters,\n    const vector<double>& search_direction)\n{\n    double x = 0, previous_x=0;\n\n    //Using Newton method to find one-dim minimum\n    do\n    {\n        previous_x = x;\n\n        //Counting derivatives\n        //TODO use vector math\n        vector<double> point = parameters;\n        vector<double> incremented = parameters;\n        vector<double> decremented = parameters;\n        for(size_t i=0; i<parameters.size(); i++)\n        {\n            point[i] += x*search_direction[i];\n            incremented[i] += (x + increment_of_the_argument_/2)*search_direction[i];\n            decremented[i] += (x - increment_of_the_argument_/2)*search_direction[i];\n        }\n\n        double f = CountCorrectedObjectiveFunctionValue(point);\n        double f_incremented = CountCorrectedObjectiveFunctionValue(incremented);\n        double f_decremented = CountCorrectedObjectiveFunctionValue(decremented);\n\n        double dirivative = (f_incremented - f_decremented)/increment_of_the_argument_;\n        double secound_derivative = (f_incremented - 2*f + f_decremented) / (increment_of_the_argument_*increment_of_the_argument_/4);\n\n        x = previous_x - dirivative/secound_derivative;\n    } while(std::abs(previous_x - x) > precision_);\n    return x;\n}\n\ndouble ConjugateGradientMethod::CalculateWeightingCoefficient(\n    const vector<double>& gradient,\n    const vector<double>& previous_gradient)\n{\n    //Fletcher-Reeves coefficient\n    double gradient_square=0;\n    double previous_gradient_square=0;\n\n    //TODO replace pow 2\n    //TODO use vector math\n    for (size_t i=0; i<gradient.size(); i++)\n    {\n        gradient_square += pow(gradient[i], 2);\n        previous_gradient_square += pow(previous_gradient[i], 2);\n    }\n\n    if(FloatingPoint::IsZero(previous_gradient_square))\n    {\n        throw std::runtime_error(\"previous_gradient_square == 0\");\n    }\n\n    return gradient_square / previous_gradient_square;\n}\n\n}/* namespace optimization */\n}/* namespace k52 */\n", "meta": {"hexsha": "0dee5466a2c50f796d1010d070700961bf759fd3", "size": 7219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/conjugate_gradient_method.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/optimization/conjugate_gradient_method.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/optimization/conjugate_gradient_method.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 30.8504273504, "max_line_length": 134, "alphanum_fraction": 0.7103476936, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.5920661176642729}}
{"text": "#ifndef TRIUMF_MATH_PDF_HPP\n#define TRIUMF_MATH_PDF_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/distributions.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace math {\n\n// probability density function (PDF)\nnamespace pdf {\n\n/// exponentially modified Gaussian distribution\ntemplate <typename T = double>\nT exponentially_modified_gaussian(T x, T mu, T sigma, T lambda) {\n  return boost::math::constants::half<T>() * lambda *\n         std::exp(2.0 * mu + lambda * sigma * sigma - 2.0 * x) *\n         std::erfc((mu + lambda * sigma * sigma - x) /\n                   (boost::math::constants::root_two<T>() * sigma));\n}\n\n/// exponentially modified Gaussian distribution (ROOT interface)\ntemplate <typename T = double>\nT exponentially_modified_gaussian(const T *x, const T *par) {\n  return exponentially_modified_gaussian<T>(*x, par[0], par[1], par[2]);\n}\n\n/// skew-normal distribution\ntemplate <typename T = double>\nT skew_normal_distribution(T x, T mu, T sigma, T alpha) {\n  boost::math::skew_normal_distribution<T> distribution(mu, sigma, alpha);\n  return boost::math::pdf(distribution, x);\n}\n\n/// skew-normal distribution (ROOT interface)\ntemplate <typename T = double>\nT skew_normal_distribution(const T *x, const T *par) {\n  return skew_normal_distribution<T>(*x, par[0], par[1], par[2]);\n}\n\n/// modified beta distribution - x in [0, x_max]\ntemplate <typename T = double> T modified_beta(T x, T alpha, T beta, T x_max) {\n  if (x <= 0.0 or x >= x_max) {\n    return 0.0;\n  }\n  T y = x / x_max;\n  boost::math::beta_distribution<T> distribution(alpha, beta);\n  return boost::math::pdf(distribution, y) / x_max;\n}\n\n/// modified beta distribution - x in [0, x_max] (ROOT interface)\ntemplate <typename T = double> T modified_beta(const T *x, const T *par) {\n  T alpha = par[0];\n  T beta = par[1];\n  T x_max = par[2];\n  return modified_beta<T>(*x, alpha, beta, x_max);\n}\n\n/// two modified beta distributions.\ntemplate <typename T = double>\nT two_modified_beta(T x, T alpha_1, T beta_1, T x_max_1, T fraction_1,\n                    T alpha_2, T beta_2, T x_max_2) {\n  return fraction_1 * modified_beta<T>(x, alpha_1, beta_1, x_max_1) +\n         (1.0 - fraction_1) * modified_beta<T>(x, alpha_2, beta_2, x_max_2);\n}\n\n/// modified non-central beta distribution - x in [0, x_max]\ntemplate <typename T = double>\nT modified_non_central_beta(T x, T alpha, T beta, T lambda, T x_max) {\n  if (x <= 0.0 or x >= x_max) {\n    return 0.0;\n  }\n  T y = x / x_max;\n  if (lambda == 0.0) {\n      return modified_beta(x, alpha, beta, x_max);\n  }\n  boost::math::non_central_beta_distribution<T> distribution(alpha, beta,\n                                                             lambda);\n  return boost::math::pdf(distribution, y) / x_max;\n}\n\n/// modified non-central beta distribution - x in [0, x_max] (ROOT interface)\ntemplate <typename T = double>\nT modified_non_central_beta(const T *x, const T *par) {\n  return modified_non_central_beta<T>(*x, par[0], par[1], par[2], par[3]);\n}\n\n} // namespace pdf\n\n} // namespace math\n\n} // namespace triumf\n\n#endif // TRIUMF_MATH_PDF_HPP\n", "meta": {"hexsha": "7d1f7406b14f6e7deee37143a815de25c62ca80b", "size": 3119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/math/pdf.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/math/pdf.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/math/pdf.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8265306122, "max_line_length": 79, "alphanum_fraction": 0.6652773325, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5919972577299483}}
{"text": "\n#pragma once\n\n#include \"perceive/foundation.hpp\"\n#include \"perceive/utils/sdbm-hash.hpp\"\n#include \"vector-3.hpp\"\n#include <Eigen/Core>\n\nnamespace perceive\n{\n// --------------------------------------------------------------------- Vector3\n\n#pragma pack(push, 1)\ntemplate<typename T> class Vector4T\n{\n public:\n   using value_type = T;\n\n   T x, y, z, w;\n\n   Vector4T() noexcept\n       : x(T(0.0))\n       , y(T(0.0))\n       , z(T(0.0))\n       , w(T(0.0))\n   {}\n   Vector4T(T x_, T y_, T z_, T w_) noexcept\n       : x(x_)\n       , y(y_)\n       , z(z_)\n       , w(w_)\n   {}\n   Vector4T(const float p[4]) noexcept\n   {\n      x = p[0];\n      y = p[1];\n      z = p[2];\n      w = p[3];\n   }\n   Vector4T(const double p[4]) noexcept\n   {\n      x = p[0];\n      y = p[1];\n      z = p[2];\n      w = p[3];\n   }\n   Vector4T(const Vector3T<T>& p, T w_ = T(0.0)) noexcept\n       : x(p.x)\n       , y(p.y)\n       , z(p.z)\n       , w(w_)\n   {}\n   Vector4T(const Vector3T<T>& a,\n            const Vector3T<T>& b,\n            const Vector3T<T>& c) noexcept\n   {\n      *this = plane_from_3_points(a, b, c);\n   }\n\n   Vector4T& operator=(const Vector4T& v) = default;\n\n   Vector4T& operator=(const Eigen::Vector4d& v) noexcept\n   {\n      for(int i = 0; i < 4; ++i) this->operator[](i) = v(i);\n      return *this;\n   }\n   Vector4T& operator=(const Eigen::Vector4f& v) noexcept\n   {\n      for(int i = 0; i < 4; ++i) this->operator[](i) = v(i);\n      return *this;\n   }\n\n   static Vector4T nan() noexcept\n   {\n      return Vector4T(T(NAN), T(NAN), T(NAN), T(NAN));\n   }\n\n   unsigned size() const noexcept { return 4; }\n\n   Vector4T& normalise(T epsilon = 1e-9) noexcept\n   {\n      // Don't normalize if we don't have to\n      T mag2 = quadrance();\n      if(fabs(mag2 - T(1.0)) > epsilon) {\n         T mag_inv = T(1.0) / sqrt(mag2);\n         x *= mag_inv;\n         y *= mag_inv;\n         z *= mag_inv;\n         w *= mag_inv;\n      }\n      return *this;\n   }\n\n   Vector4T& normalise_plane(T epsilon = 1e-9) noexcept\n   {\n      T mag2 = x * x + y * y + z * z;\n      if(fabs(mag2 - T(1.0)) > epsilon) *this *= T(1.0) / sqrt(mag2);\n      return *this;\n   }\n\n   Vector4T& normalise_point(T epsilon = 1e-9) noexcept\n   {\n      if(fabs(w - T(1.0)) > epsilon) *this *= T(1.0) / w;\n      return *this;\n   }\n\n   Vector4T normalised(T epsilon = 1e-9) const noexcept\n   {\n      Vector4T res = *this;\n      res.normalise(epsilon);\n      return res;\n   }\n   Vector4T normalised_plane(T epsilon = 1e-9) const noexcept\n   {\n      Vector4T res = *this;\n      res.normalise_plane(epsilon);\n      return res;\n   }\n   Vector4T normalised_point(T epsilon = 1e-9) const noexcept\n   {\n      Vector4T res = *this;\n      res.normalise_point(epsilon);\n      return res;\n   }\n\n   Vector4T& normalize(T ep = 1e-9) noexcept { return normalise(ep); }\n   Vector4T& normalize_plane(T ep = 1e-9) noexcept\n   {\n      return normalise_plane(ep);\n   }\n   Vector4T& normalize_point(T ep = 1e-9) noexcept\n   {\n      return normalise_point(ep);\n   }\n\n   Vector4T normalized(T epsilon = 1e-9) const noexcept\n   {\n      return normalised(epsilon);\n   }\n   Vector4T normalized_plane(T ep = 1e-9) const noexcept\n   {\n      return normalised_plane(ep);\n   }\n   Vector4T normalized_point(T ep = 1e-9) const noexcept\n   {\n      return normalised_point(ep);\n   }\n\n   T quadrance() const noexcept { return x * x + y * y + z * z + w * w; }\n   T norm() const noexcept { return sqrt(quadrance()); }\n   T dot(const Vector4T& rhs) const noexcept\n   {\n      return x * rhs.x + y * rhs.y + z * rhs.z + w * rhs.w;\n   }\n   T distance(const Vector4T& rhs) const noexcept\n   {\n      return (*this - rhs).norm();\n   }\n\n   Vector3T<T>& xyz() noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(&x == reinterpret_cast<const T*>(this) + 0);\n      assert(&y == reinterpret_cast<const T*>(this) + 1);\n      assert(&z == reinterpret_cast<const T*>(this) + 2);\n#endif\n      return *(reinterpret_cast<Vector3T<T>*>(this));\n   }\n   const Vector3T<T>& xyz() const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(&x == reinterpret_cast<const T*>(this) + 0);\n      assert(&y == reinterpret_cast<const T*>(this) + 1);\n      assert(&z == reinterpret_cast<const T*>(this) + 2);\n#endif\n      return *(reinterpret_cast<const Vector3T<T>*>(this));\n   }\n   T& d() noexcept { return w; } // for plane\n   const T& d() const noexcept { return w; }\n\n   Vector4T& set_to(const T& a, const T& b, const T& c, const T& d) noexcept\n   {\n      x = a;\n      y = b;\n      z = c;\n      w = d;\n      return *this;\n   }\n   Vector4T& set_to(T a[4]) noexcept\n   {\n      set_to(a[0], a[1], a[2], a[3]);\n      return *this;\n   }\n\n   T* copy_to(T a[4]) const noexcept\n   {\n      a[0] = x;\n      a[1] = y;\n      a[2] = z;\n      a[3] = w;\n      return a;\n   }\n\n   T* ptr() noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(&x == reinterpret_cast<const T*>(this) + 0);\n      assert(&y == reinterpret_cast<const T*>(this) + 1);\n      assert(&z == reinterpret_cast<const T*>(this) + 2);\n      assert(&w == reinterpret_cast<const T*>(this) + 3);\n#endif\n      return &x;\n   }\n\n   const T* ptr() const noexcept\n   {\n      return const_cast<Vector4T<T>*>(this)->ptr();\n   }\n\n   T& operator[](int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator[](int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   T& operator()(int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n   const T& operator()(int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   Vector4T round() const noexcept\n   {\n      return Vector4T(floor(x + T(0.499)),\n                      floor(y + T(0.499)),\n                      floor(z + T(0.499)),\n                      floor(w + T(0.499)));\n   }\n\n   Vector4T& operator*=(T scalar) noexcept\n   {\n      x *= scalar;\n      y *= scalar;\n      z *= scalar;\n      w *= scalar;\n      return *this;\n   }\n   Vector4T& operator/=(T scalar) noexcept\n   {\n      x /= scalar;\n      y /= scalar;\n      z /= scalar;\n      w /= scalar;\n      return *this;\n   }\n   Vector4T operator*(T scalar) const noexcept\n   {\n      Vector4T res(*this);\n      res *= scalar;\n      return res;\n   }\n   Vector4T operator/(T scalar) const noexcept\n   {\n      Vector4T res(*this);\n      res /= scalar;\n      return res;\n   }\n\n   Vector4T& operator+=(const Vector4T& rhs) noexcept\n   {\n      x += rhs.x;\n      y += rhs.y;\n      z += rhs.z;\n      w += rhs.w;\n      return *this;\n   }\n   Vector4T& operator-=(const Vector4T& rhs) noexcept\n   {\n      x -= rhs.x;\n      y -= rhs.y;\n      z -= rhs.z;\n      w -= rhs.w;\n      return *this;\n   }\n   Vector4T operator+(const Vector4T& rhs) const noexcept\n   {\n      Vector4T res(*this);\n      res += rhs;\n      return res;\n   }\n   Vector4T operator-(const Vector4T& rhs) const noexcept\n   {\n      Vector4T res(*this);\n      res -= rhs;\n      return res;\n   }\n   Vector4T operator-() const noexcept { return Vector4T(-x, -y, -z, -w); }\n\n   bool operator==(const Vector4T& rhs) const noexcept\n   {\n      return x == rhs.x and y == rhs.y and z == rhs.z and w == rhs.w;\n   }\n   bool operator!=(const Vector4T& rhs) const noexcept\n   {\n      return !(*this == rhs);\n   }\n\n   std::string to_string(const char* fmt = \"{{{}, {}, {}, {}}}\") const noexcept\n   {\n      return format(fmt, x, y, z, w);\n   }\n\n   std::string to_str() const { return format(\"[{}, {}, {}, {}]\", x, y, z, w); }\n\n   bool is_nan() const noexcept\n   {\n      return std::isnan(x) || std::isnan(y) || std::isnan(z) || std::isnan(w);\n   }\n\n   bool is_finite() const noexcept\n   {\n      return std::isfinite(x) && std::isfinite(y) && std::isfinite(z)\n             && std::isfinite(w);\n   }\n\n   inline friend bool isfinite(const Vector4T& o) noexcept\n   {\n      return o.is_finite();\n   }\n\n   bool is_unit_vector(T epsilon = 1e-9) const noexcept\n   {\n      return is_finite() && fabs(quadrance() - 1.0) < epsilon;\n   }\n\n   void print(const char* msg = NULL, bool newline = true) const noexcept\n   {\n      printf(\"%s%s%s%s\",\n             (msg == NULL ? \"\" : msg),\n             (msg == NULL ? \"\" : \" \"),\n             to_string().c_str(),\n             (newline ? \"\\n\" : \"\"));\n      fflush(stdout);\n   }\n\n   // Homogenous point\n   bool pt_at_infinity(T epsilon = 1e-9) const noexcept\n   {\n      return fabs(w) < epsilon;\n   }\n\n   size_t hash() const noexcept { return sdbm_hash(ptr(), sizeof(T) * size()); }\n\n   // Plane functions\n   T side(const Vector3T<T>& o) const noexcept\n   {\n      return o.x * x + o.y * y + o.z * z + d();\n   }\n\n   // WARNING, must be normalised\n   double point_plane_distance(const Vector3T<T>& point) const noexcept\n   {\n      assert(fabs(xyz().quadrance() - 1.0) < 1e-9);\n      return fabs(side(point));\n   }\n\n   Vector3T<T> image(const Vector3T<T>& p) const noexcept\n   {\n      assert(fabs(xyz().quadrance() - 1.0) < 1e-9);\n      return p - xyz() * side(p);\n   }\n   Vector3T<T> reflect(const Vector3T<T>& p) const noexcept\n   {\n      assert(fabs(xyz().quadrance() - 1.0) < 1e-9);\n      return p - 2.0 * xyz() * side(p);\n   }\n\n   // Reflect a plane\n   Vector4T<T> reflect(const Vector4T<T>& p) const noexcept\n   {\n      auto norm = (p.xyz() - 2.0 * p.xyz().dot(xyz()) * xyz()).normalised();\n      auto C    = reflect(p.image(Vector3T<T>(0.0, 0.0, 0.0)));\n      return Vector4T<T>(norm, -C.dot(norm));\n   }\n\n   friend std::string str(const Vector4T<T>& o) noexcept\n   {\n      return o.to_string();\n   }\n};\n#pragma pack(pop)\n\ntemplate<typename T>\nVector4T<T> operator*(float a, const Vector4T<T>& v) noexcept\n{\n   return v * a;\n}\n\ntemplate<typename T>\nVector4T<T> operator/(float a, const Vector4T<T>& v) noexcept\n{\n   return v / a;\n}\n\ntemplate<typename T>\nVector4T<T> operator*(double a, const Vector4T<T>& v) noexcept\n{\n   return v * a;\n}\n\ntemplate<typename T>\nVector4T<T> operator/(double a, const Vector4T<T>& v) noexcept\n{\n   return v / a;\n}\n\ntemplate<typename T>\nVector4T<T> plane_from_3_points(const Vector3T<T>& a,\n                                const Vector3T<T>& b,\n                                const Vector3T<T>& c) noexcept\n{\n   Vector4T<T> ret;\n\n   auto ab   = a - b;\n   auto ac   = a - c;\n   ret.xyz() = ab.cross(ac);\n   ret.xyz().normalise();\n   ret.d() = -1.0 * dot(a, ret.xyz());\n\n   return ret;\n}\n\ntemplate<typename T>\ninline T ray_position_relative_to_plane_t(const Vector4T<T>& p3,\n                                          const Vector3T<T>& a,\n                                          const Vector3T<T>& b,\n                                          const T side) noexcept\n{\n   return (side - p3.d() - dot(p3.xyz(), a)) / dot(p3.xyz(), b - a);\n}\n\ntemplate<typename T>\ninline Vector3T<T> ray_position_relative_to_plane(const Vector4T<T>& p3,\n                                                  const Vector3T<T>& a,\n                                                  const Vector3T<T>& b,\n                                                  const T side) noexcept\n{\n   const auto t = ray_position_relative_to_plane_t(p3, a, b, side);\n   return a + t * (b - a);\n}\n\ntemplate<typename T>\ninline T plane_ray_intersection_t(const Vector4T<T>& p,\n                                  const Vector3T<T>& a,\n                                  const Vector3T<T>& b) noexcept\n{\n   static_assert(std::is_floating_point<T>::value);\n   return ray_position_relative_to_plane_t(p, a, b, T(0.0));\n}\n\ntemplate<typename T>\ninline Vector3T<T> plane_ray_intersection(const Vector4T<T>& p,\n                                          const Vector3T<T>& a,\n                                          const Vector3T<T>& b) noexcept\n{\n   static_assert(std::is_floating_point<T>::value);\n   return a + plane_ray_intersection_t(p, a, b) * (b - a);\n}\n\n// String shim\ntemplate<typename T> std::string str(const Vector4T<T>& v) noexcept\n{\n   return v.to_string();\n}\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const Vector4T<T>& v) noexcept\n{\n   out << v.to_string();\n   return out;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "e516b8cc8c872bfc78b9b45b3cfbc2217630b417", "size": 12050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-4.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-4.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-4.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": 24.0039840637, "max_line_length": 80, "alphanum_fraction": 0.5349377593, "num_tokens": 3546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5919668241954965}}
{"text": "#ifndef CANNON_CONTROL_LQR_H\n#define CANNON_CONTROL_LQR_H \n\n/*!\n * \\file cannon/control/lqr.hpp\n * \\brief File containing utility functions for computing LQR controllers in\n * discrete and continuous time.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace control {\n\n    /*!\n     * \\brief Class representing an LQR controller for a continuous or\n     * discrete-time system.\n     */\n    class LQRController {\n      public:\n\n        using LinearizationFunction =\n            std::function<void(const Ref<const VectorXd> &, Ref<MatrixXd>,\n                               Ref<MatrixXd>)>;\n\n        LQRController() = delete;\n\n        /*!\n         * \\brief Constructor taking state to stabilize around, control\n         * dimension, whether the system to be controlled is continuous-time,\n         * and linearization function for the system to be controlled.\n         *\n         * Initializes cost matrices to identity.\n         */\n        LQRController(const Ref<const VectorXd> &q0,\n                      unsigned int control_dim,\n                      LinearizationFunction f,\n                      bool continuous = true);\n\n        /*!\n         * \\brief Constructor taking state to stabilize around, state\n         * cost matrix, control cost matrix, whether the system to be\n         * controlled is continuous-time, and linearization function for the\n         * system to be controlled.\n         */\n        LQRController(const Ref<const VectorXd> &q0,\n                      const Ref<const MatrixXd> &Q,\n                      const Ref<const MatrixXd> &R, LinearizationFunction f,\n                      bool continuous = true);\n\n        /*!\n         * \\brief Compute the control to apply at the input state.\n         *\n         * \\param q The state to compute control for.\n         * \n         * \\returns The computed control.\n         */\n        VectorXd compute_control(const Ref<const VectorXd>& q) const;\n\n        /*!\n         * \\brief Get the linear portion of the control law represented by this\n         * controller.\n         *\n         * \\returns Gain matrix.\n         */\n        MatrixXd get_linear_gain() const;\n\n        /*!\n         * \\brief Get the constant offset portion of the control law\n         * represented by this controller.\n         *\n         * \\returns Offset vector.\n         */\n        VectorXd get_control_offset() const;\n\n        /*!\n         * \\brief Set the state that this controller attempts to stabilize to.\n         *\n         * \\param q The new state to stabilize to.\n         */\n        void set_target(const Ref<const VectorXd>& q);\n\n      private:\n\n        /*!\n         * \\brief Compute LQR gain for controller represented by this object.\n         */\n        void compute_lqr_gain_();\n\n        VectorXd q0_; //!< State to stabilize toward\n        MatrixXd Q_; //!< State cost matrix\n        MatrixXd K_; //!< Control gain matrix\n        MatrixXd R_; //!< Control cost matrix\n        LLT<MatrixXd> R_cholesky_; //!< Cholesky factorization of control cost matrix\n        LinearizationFunction linearization_; //!< Linearization function for system to be controlled\n        bool continuous_; //!< Whether the system to be controlled is continuous-time\n    };\n\n    // Free Functions\n    /*!\n     * \\brief Solve the continuous-time algebraic riccati equation for\n     * the input state and control derivative matrices A and B, and\n     * return the resulting steady-state LQR gain.\n     *\n     * \\param A Partial derivatives of ode with respect to state.\n     * \\param B Partial derivatives of ode with respect to control.\n     * \\param Q State cost matrix\n     * \\param R Control cost matrix Cholesky decomposition\n     *\n     * \\returns CARE solution control gain matrix.\n     */\n  MatrixXd continuous_algebraic_riccati_equation(const Ref<const MatrixXd> &A,\n                                                 const Ref<const MatrixXd> &B,\n                                                 const Ref<const MatrixXd> &Q,\n                                                 const LLT<MatrixXd> &R_cholesky);\n\n  } // namespace control\n} // namespace cannon\n\n\n#endif /* ifndef CANNON_CONTROL_LQR_H */\n", "meta": {"hexsha": "a8b2af744377204de0f8411486c6ba5354c8a5c1", "size": 4163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/control/lqr.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/control/lqr.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/control/lqr.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5725806452, "max_line_length": 101, "alphanum_fraction": 0.5909200096, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5919668182375527}}
{"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/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/blas/blas.hpp>\n#include <boost/numeric/bindings/traits/c_array.hpp>\n#include <boost/numeric/bindings/traits/c_array2.hpp>\n#include <boost/numeric/bindings/traits/dense_traits.hpp>\n#include <boost/numeric/bindings/traits/std_valarray.hpp>\n#include <boost/numeric/bindings/traits/std_valarray2.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/bindings/traits/std_vector2.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n\nint\nmain(int argc, char** argv)\n{\n\t{\n\t\t// a * b' = C ; a' * b = d\n\t\t\n\t\tboost::numeric::ublas::vector<double> a(3);\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) a(i) = i;\n\t\tstd::cout << \"a=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::vector<double> b(3);\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b(i) = i;\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, c\n\t\t);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::ublas::vector<double> d(1);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, d\n\t\t);\n\t\tstd::cout << \"d=\" << d << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t{\n\t\t// a * b' = C ; a' * b = d\n\t\t\n\t\tstd::vector<double> a(3);\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) a[i] = i;\n\t\tstd::cout << \"a=[\" << a.size() << \"](\";\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << a[i];\n\t\tstd::cout << \")\" << std::endl;\n\t\t\n\t\tstd::valarray<double> b(3);\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b[i] = i;\n\t\tstd::cout << \"b=[\" << b.size() << \"](\";\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << b[i];\n\t\tstd::cout << \")\" << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, c\n\t\t);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tstd::vector<double> d(1);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, d\n\t\t);\n\t\tstd::cout << \"d=[\" << d.size() << \"](\";\n\t\tfor (std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << d[i];\n\t\tstd::cout << \")\" << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t{\n\t\t// a * b' = C ; a' * b = d\n\t\t\n\t\tdouble a[3];\n\t\tfor (std::size_t i = 0; i < 3; ++i) a[i] = i;\n\t\tstd::cout << \"a=[\" << 3 << \"](\";\n\t\tfor (std::size_t i = 0; i < 3; ++i) std::cout << (i > 0 ? \",\" : \"\") << a[i];\n\t\tstd::cout << \")\" << std::endl;\n\t\t\n\t\tstd::vector<double> b(3);\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b[i] = i;\n\t\tstd::cout << \"b=[\" << b.size() << \"](\";\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << b[i];\n\t\tstd::cout << \")\" << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, c\n\t\t);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tstd::valarray<double> d(1);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, d\n\t\t);\n\t\tstd::cout << \"d=[\" << d.size() << \"](\";\n\t\tfor (std::size_t i = 0; i < d.size(); ++i) std::cout << (i > 0 ? \",\" : \"\") << d[i];\n\t\tstd::cout << \")\" << std::endl;\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "857aac75e545f7850b13095ba1ee406c725bf996", "size": 4339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/vector2.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/blas/test/vector2.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/vector2.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": 33.1221374046, "max_line_length": 85, "alphanum_fraction": 0.5768610279, "num_tokens": 1537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5919668122796088}}
{"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// Some changes have been made to use it in livox_slam_ware\n\n#ifndef MATH_UTILS_HPP\n#define MATH_UTILS_HPP\n\n#include <cmath>\n#include <Eigen/Dense>\n\nnamespace livox_slam_ware {\n\n/*\n *  @brief Create a skew-symmetric matrix from a 3-element vector.\n *  @note Performs the operation:\n *  w   ->  [  0 -w3  w2]\n *          [ w3   0 -w1]\n *          [-w2  w1   0]\n */\ninline Eigen::Matrix3d skewSymmetric(const Eigen::Vector3d& w) {\n  Eigen::Matrix3d w_hat;\n  w_hat(0, 0) = 0;\n  w_hat(0, 1) = -w(2);\n  w_hat(0, 2) = w(1);\n  w_hat(1, 0) = w(2);\n  w_hat(1, 1) = 0;\n  w_hat(1, 2) = -w(0);\n  w_hat(2, 0) = -w(1);\n  w_hat(2, 1) = w(0);\n  w_hat(2, 2) = 0;\n  return w_hat;\n}\n\n/*\n * @brief Normalize the given quaternion to unit quaternion.\n */\ninline void quaternionNormalize(Eigen::Vector4d& q) {\n  double norm = q.norm();\n  q = q / norm;\n  return;\n}\n\n/*\n * @brief Perform q1 * q2.\n *  \n *    Format of q1 and q2 is as [x,y,z,w]\n */\ninline Eigen::Vector4d quaternionMultiplication(\n    const Eigen::Vector4d& q1,\n    const Eigen::Vector4d& q2) {\n  Eigen::Matrix4d L;\n\n  // QXC: Hamilton\n  L(0, 0) =  q1(3); L(0, 1) = -q1(2); L(0, 2) =  q1(1); L(0, 3) =  q1(0);\n  L(1, 0) =  q1(2); L(1, 1) =  q1(3); L(1, 2) = -q1(0); L(1, 3) =  q1(1);\n  L(2, 0) = -q1(1); L(2, 1) =  q1(0); L(2, 2) =  q1(3); L(2, 3) =  q1(2);\n  L(3, 0) = -q1(0); L(3, 1) = -q1(1); L(3, 2) = -q1(2); L(3, 3) =  q1(3);\n\n  Eigen::Vector4d q = L * q2;\n  quaternionNormalize(q);\n  return q;\n}\n\n/*\n * @brief Convert the vector part of a quaternion to a\n *    full quaternion.\n * @note This function is useful to convert delta quaternion\n *    which is usually a 3x1 vector to a full quaternion.\n *    For more details, check Section 3.2 \"Kalman Filter Update\" in\n *    \"Indirect Kalman Filter for 3D Attitude Estimation:\n *    A Tutorial for quaternion Algebra\".\n */\ninline Eigen::Vector4d smallAngleQuaternion(\n    const Eigen::Vector3d& dtheta) {\n\n  Eigen::Vector3d dq = dtheta / 2.0;\n  Eigen::Vector4d q;\n  double dq_square_norm = dq.squaredNorm();\n\n  if (dq_square_norm <= 1) {\n    q.head<3>() = dq;\n    q(3) = std::sqrt(1-dq_square_norm);\n  } else {\n    q.head<3>() = dq;\n    q(3) = 1;\n    q = q / std::sqrt(1+dq_square_norm);\n  }\n\n  return q;\n}\n\n/*\n * @brief Convert the vector part of a quaternion to a\n *    full quaternion.\n * @note This function is useful to convert delta quaternion\n *    which is usually a 3x1 vector to a full quaternion.\n *    For more details, check Section 3.2 \"Kalman Filter Update\" in\n *    \"Indirect Kalman Filter for 3D Attitude Estimation:\n *    A Tutorial for quaternion Algebra\".\n */\ninline Eigen::Quaterniond getSmallAngleQuaternion(\n    const Eigen::Vector3d& dtheta) {\n\n  Eigen::Vector3d dq = dtheta / 2.0;\n  Eigen::Quaterniond q;\n  double dq_square_norm = dq.squaredNorm();\n\n  if (dq_square_norm <= 1) {\n    q.x() = dq(0);\n    q.y() = dq(1);\n    q.z() = dq(2);\n    q.w() = std::sqrt(1-dq_square_norm);\n  } else {\n    q.x() = dq(0);\n    q.y() = dq(1);\n    q.z() = dq(2);\n    q.w() = 1;\n    q.normalize();\n  }\n\n  return q;\n}\n\n/*\n * @brief Convert a quaternion to the corresponding rotation matrix\n * @note Pay attention to the convention used. The function follows the\n *    conversion in \"Indirect Kalman Filter for 3D Attitude Estimation:\n *    A Tutorial for Quaternion Algebra\", Equation (78).\n *\n *    The input quaternion should be in the form\n *      [q1, q2, q3, q4(scalar)]^T\n */\ninline Eigen::Matrix3d quaternionToRotation(\n    const Eigen::Vector4d& q) {\n  // QXC: Hamilton\n  const double& qw = q(3);\n  const double& qx = q(0);\n  const double& qy = q(1);\n  const double& qz = q(2);\n  Eigen::Matrix3d R;\n  R(0, 0) = 1-2*(qy*qy+qz*qz);  R(0, 1) =   2*(qx*qy-qw*qz);  R(0, 2) =   2*(qx*qz+qw*qy);\n  R(1, 0) =   2*(qx*qy+qw*qz);  R(1, 1) = 1-2*(qx*qx+qz*qz);  R(1, 2) =   2*(qy*qz-qw*qx);\n  R(2, 0) =   2*(qx*qz-qw*qy);  R(2, 1) =   2*(qy*qz+qw*qx);  R(2, 2) = 1-2*(qx*qx+qy*qy);\n\n  return R;\n}\n\n/*\n * @brief Convert a rotation matrix to a quaternion.\n * @note Pay attention to the convention used. The function follows the\n *    conversion in \"Indirect Kalman Filter for 3D Attitude Estimation:\n *    A Tutorial for Quaternion Algebra\", Equation (78).\n *\n *    The input quaternion should be in the form\n *      [q1, q2, q3, q4(scalar)]^T\n */\ninline Eigen::Vector4d rotationToQuaternion(\n    const Eigen::Matrix3d& R) {\n  Eigen::Vector4d score;\n  score(0) = R(0, 0);\n  score(1) = R(1, 1);\n  score(2) = R(2, 2);\n  score(3) = R.trace();\n\n  int max_row = 0, max_col = 0;\n  score.maxCoeff(&max_row, &max_col);\n\n  Eigen::Vector4d q = Eigen::Vector4d::Zero();\n\n  // QXC: Hamilton\n  if (max_row == 0) {\n    q(0) = std::sqrt(1+2*R(0, 0)-R.trace()) / 2.0;\n    q(1) = (R(0, 1)+R(1, 0)) / (4*q(0));\n    q(2) = (R(0, 2)+R(2, 0)) / (4*q(0));\n    q(3) = (R(2, 1)-R(1, 2)) / (4*q(0));\n  } else if (max_row == 1) {\n    q(1) = std::sqrt(1+2*R(1, 1)-R.trace()) / 2.0;\n    q(0) = (R(0, 1)+R(1, 0)) / (4*q(1));\n    q(2) = (R(1, 2)+R(2, 1)) / (4*q(1));\n    q(3) = (R(0, 2)-R(2, 0)) / (4*q(1));\n  } else if (max_row == 2) {\n    q(2) = std::sqrt(1+2*R(2, 2)-R.trace()) / 2.0;\n    q(0) = (R(0, 2)+R(2, 0)) / (4*q(2));\n    q(1) = (R(1, 2)+R(2, 1)) / (4*q(2));\n    q(3) = (R(1, 0)-R(0, 1)) / (4*q(2));\n  } else {\n    q(3) = std::sqrt(1+R.trace()) / 2.0;\n    q(0) = (R(2, 1)-R(1, 2)) / (4*q(3));\n    q(1) = (R(0, 2)-R(2, 0)) / (4*q(3));\n    q(2) = (R(1, 0)-R(0, 1)) / (4*q(3));\n  }\n\n  if (q(3) < 0) q = -q;\n  quaternionNormalize(q);\n  return q;\n}\n\n} // end namespace livox_slam_ware\n\n#endif // MATH_UTILS_HPP\n", "meta": {"hexsha": "86f693a4dfe4e4c9744893c0a04bf2b03d727059", "size": 5733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Estimator/math_utils.hpp", "max_stars_repo_name": "chengwei0427/LIO-Livox", "max_stars_repo_head_hexsha": "cc62cf96912ee80556b1cf736ea3a3fa57b6135d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 258.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T06:40:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:28:22.000Z", "max_issues_repo_path": "include/Estimator/math_utils.hpp", "max_issues_repo_name": "chengwei0427/LIO-Livox", "max_issues_repo_head_hexsha": "cc62cf96912ee80556b1cf736ea3a3fa57b6135d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2021-08-02T09:01:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T12:58:52.000Z", "max_forks_repo_path": "include/Estimator/math_utils.hpp", "max_forks_repo_name": "chengwei0427/LIO-Livox", "max_forks_repo_head_hexsha": "cc62cf96912ee80556b1cf736ea3a3fa57b6135d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 73.0, "max_forks_repo_forks_event_min_datetime": "2021-07-29T11:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:17:17.000Z", "avg_line_length": 27.6956521739, "max_line_length": 90, "alphanum_fraction": 0.5707308564, "num_tokens": 2314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5918258426069619}}
{"text": "#include \"SimpleIndex.h\"\n#include \"cryptoTools/Crypto/PRNG.h\"\n#include <random>\n#include \"cryptoTools/Common/Log.h\"\n#include \"cryptoTools/Common/CuckooIndex.h\"\n#include <numeric>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nnamespace osuCrypto\n{\n\n\n    void SimpleIndex::print()\n    {\n\n        for (u64 i = 0; i < mBins.size(); ++i)\n            //\tfor (u64 i = 0; i <1; ++i)\n        {\n            std::cout << \"Bin #\" << i << std::endl;\n\n            std::cout << \" contains \" << mBinSizes[i] << \" elements\" << std::endl;\n\n            for (u64 j = 0; j < mBinSizes[i]; ++j)\n            {\n                std::cout << \"    idx=\" << mBins(i, j).idx() << \"  hIdx=\" << mBins(i, j).hashIdx() << std::endl;\n                //\tstd::cout << \"    \" << mBins[i].first[j] << \"  \" << mBins[i].second[j] << std::endl;\n\n            }\n\n            std::cout << std::endl;\n        }\n\n        std::cout << std::endl;\n    }\n\n\n    //template<unsigned int N = 16>\n    double getBinOverflowProb(u64 numBins, u64 numBalls, u64 getBinSize, double epsilon = 0.0001)\n    {\n        if (numBalls <= getBinSize)\n            return std::numeric_limits<double>::max();\n\n        if (numBalls > std::numeric_limits<i32>::max())\n        {\n            auto msg = (\"boost::math::binomial_coefficient(...) only supports \" + std::to_string(sizeof(unsigned) * 8) + \" bit inputs which was exceeded.\" LOCATION);\n            std::cout << msg << std::endl;\n            throw std::runtime_error(msg);\n        }\n\n        //std::cout << numBalls << \" \" << numBins << \" \" << binSize << std::endl;\n        typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<16>> T;\n        T sum = 0.0;\n        T sec = 0.0;// minSec + 1;\n        T diff = 1;\n        u64 i = getBinSize + 1;\n\n\n        while (diff > T(epsilon) && numBalls >= i /*&& sec > minSec*/)\n        {\n            sum += numBins * boost::math::binomial_coefficient<T>(i32(numBalls), i32(i))\n                * boost::multiprecision::pow(T(1.0) / numBins, i) * boost::multiprecision::pow(1 - T(1.0) / numBins, numBalls - i);\n\n            //std::cout << \"sum[\" << i << \"] \" << sum << std::endl;\n\n            T sec2 = boost::multiprecision::log2(sum);\n            diff = boost::multiprecision::abs(sec - sec2);\n            //std::cout << diff << std::endl;\n            sec = sec2;\n\n            i++;\n        }\n\n        return std::max<double>(0, (double)-sec);\n    }\n\n    u64 SimpleIndex::get_bin_size(u64 numBins, u64 numBalls, u64 statSecParam)\n    {\n\n        auto B = std::max<u64>(1, numBalls / numBins);\n\n        double currentProb = getBinOverflowProb(numBins, numBalls, B);\n        u64 step = 1;\n\n        bool doubling = true;\n\n        while (currentProb < statSecParam || step > 1)\n        {\n            if (!step)\n                throw std::runtime_error(LOCATION);\n\n\n            if (statSecParam > currentProb)\n            {\n                if (doubling) step = std::max<u64>(1, step * 2);\n                else          step = std::max<u64>(1, step / 2);\n\n                B += step;\n            }\n            else\n            {\n                doubling = false;\n                step = std::max<u64>(1, step / 2);\n                B -= step;\n            }\n            currentProb = getBinOverflowProb(numBins, numBalls, B);\n        }\n\n        return B;\n    }\n\n\n    void SimpleIndex::init(u64 numBins, u64 numBalls, u64 statSecParam, u64 numHashFunction)\n    {\n        mNumHashFunctions = numHashFunction;\n        mMaxBinSize = get_bin_size(numBins, numBalls * numHashFunction, statSecParam);\n        mBins.resize(numBins, mMaxBinSize);\n        mBinSizes.resize(numBins, 0);\n        mItemToBinMap.resize(numBalls, numHashFunction);\n        mNumBins = numBins;\n    }\n\n\n    void SimpleIndex::insertItems(span<block> items, block hashingSeed)\n    {\n\n        std::array<block, 8> hashs;\n        AES hasher(hashingSeed);\n\n        auto mainSteps = items.size() / hashs.size();\n        auto remSteps = items.size() % hashs.size();\n        u64 itemIdx = 0;\n        if (mNumHashFunctions == 3 )\n        {\n            for (u64 i = 0; i < mainSteps; ++i, itemIdx += 8)\n            {\n                auto min = std::min<u64>(items.size() - itemIdx, hashs.size());\n\n                hasher.ecbEncBlocks(items.data() + itemIdx, min, hashs.data());\n\n                auto itemIdx0 = itemIdx + 0;\n                auto itemIdx1 = itemIdx + 1;\n                auto itemIdx2 = itemIdx + 2;\n                auto itemIdx3 = itemIdx + 3;\n                auto itemIdx4 = itemIdx + 4;\n                auto itemIdx5 = itemIdx + 5;\n                auto itemIdx6 = itemIdx + 6;\n                auto itemIdx7 = itemIdx + 7;\n\n\n\n                hashs[0] = hashs[0] ^ items[itemIdx0];\n                hashs[1] = hashs[1] ^ items[itemIdx1];\n                hashs[2] = hashs[2] ^ items[itemIdx2];\n                hashs[3] = hashs[3] ^ items[itemIdx3];\n                hashs[4] = hashs[4] ^ items[itemIdx4];\n                hashs[5] = hashs[5] ^ items[itemIdx5];\n                hashs[6] = hashs[6] ^ items[itemIdx6];\n                hashs[7] = hashs[7] ^ items[itemIdx7];\n\n                auto bIdx00 = CuckooIndex<>::getHash(hashs[0], 0, mNumBins);\n                auto bIdx10 = CuckooIndex<>::getHash(hashs[1], 0, mNumBins);\n                auto bIdx20 = CuckooIndex<>::getHash(hashs[2], 0, mNumBins);\n                auto bIdx30 = CuckooIndex<>::getHash(hashs[3], 0, mNumBins);\n                auto bIdx40 = CuckooIndex<>::getHash(hashs[4], 0, mNumBins);\n                auto bIdx50 = CuckooIndex<>::getHash(hashs[5], 0, mNumBins);\n                auto bIdx60 = CuckooIndex<>::getHash(hashs[6], 0, mNumBins);\n                auto bIdx70 = CuckooIndex<>::getHash(hashs[7], 0, mNumBins);\n\n                mBins(bIdx00, mBinSizes[bIdx00]++).set(itemIdx0, 0, false);\n                mBins(bIdx10, mBinSizes[bIdx10]++).set(itemIdx1, 0, false);\n                mBins(bIdx20, mBinSizes[bIdx20]++).set(itemIdx2, 0, false);\n                mBins(bIdx30, mBinSizes[bIdx30]++).set(itemIdx3, 0, false);\n                mBins(bIdx40, mBinSizes[bIdx40]++).set(itemIdx4, 0, false);\n                mBins(bIdx50, mBinSizes[bIdx50]++).set(itemIdx5, 0, false);\n                mBins(bIdx60, mBinSizes[bIdx60]++).set(itemIdx6, 0, false);\n                mBins(bIdx70, mBinSizes[bIdx70]++).set(itemIdx7, 0, false);\n\n                mItemToBinMap(itemIdx0, 0) = bIdx00;\n                mItemToBinMap(itemIdx1, 0) = bIdx10;\n                mItemToBinMap(itemIdx2, 0) = bIdx20;\n                mItemToBinMap(itemIdx3, 0) = bIdx30;\n                mItemToBinMap(itemIdx4, 0) = bIdx40;\n                mItemToBinMap(itemIdx5, 0) = bIdx50;\n                mItemToBinMap(itemIdx6, 0) = bIdx60;\n                mItemToBinMap(itemIdx7, 0) = bIdx70;\n\n                auto bIdx01 = CuckooIndex<>::getHash(hashs[0], 1, mNumBins);\n                auto bIdx11 = CuckooIndex<>::getHash(hashs[1], 1, mNumBins);\n                auto bIdx21 = CuckooIndex<>::getHash(hashs[2], 1, mNumBins);\n                auto bIdx31 = CuckooIndex<>::getHash(hashs[3], 1, mNumBins);\n                auto bIdx41 = CuckooIndex<>::getHash(hashs[4], 1, mNumBins);\n                auto bIdx51 = CuckooIndex<>::getHash(hashs[5], 1, mNumBins);\n                auto bIdx61 = CuckooIndex<>::getHash(hashs[6], 1, mNumBins);\n                auto bIdx71 = CuckooIndex<>::getHash(hashs[7], 1, mNumBins);\n\n                bool c01 = bIdx00 == bIdx01;\n                bool c11 = bIdx10 == bIdx11;\n                bool c21 = bIdx20 == bIdx21;\n                bool c31 = bIdx30 == bIdx31;\n                bool c41 = bIdx40 == bIdx41;\n                bool c51 = bIdx50 == bIdx51;\n                bool c61 = bIdx60 == bIdx61;\n                bool c71 = bIdx70 == bIdx71;\n\n                mBins(bIdx01, mBinSizes[bIdx01]++).set(itemIdx0, 1, c01);\n                mBins(bIdx11, mBinSizes[bIdx11]++).set(itemIdx1, 1, c11);\n                mBins(bIdx21, mBinSizes[bIdx21]++).set(itemIdx2, 1, c21);\n                mBins(bIdx31, mBinSizes[bIdx31]++).set(itemIdx3, 1, c31);\n                mBins(bIdx41, mBinSizes[bIdx41]++).set(itemIdx4, 1, c41);\n                mBins(bIdx51, mBinSizes[bIdx51]++).set(itemIdx5, 1, c51);\n                mBins(bIdx61, mBinSizes[bIdx61]++).set(itemIdx6, 1, c61);\n                mBins(bIdx71, mBinSizes[bIdx71]++).set(itemIdx7, 1, c71);\n\n\n                mItemToBinMap(itemIdx0, 1) = bIdx01 | ((u8)c01 & 1) * u64(-1);\n                mItemToBinMap(itemIdx1, 1) = bIdx11 | ((u8)c11 & 1) * u64(-1);\n                mItemToBinMap(itemIdx2, 1) = bIdx21 | ((u8)c21 & 1) * u64(-1);\n                mItemToBinMap(itemIdx3, 1) = bIdx31 | ((u8)c31 & 1) * u64(-1);\n                mItemToBinMap(itemIdx4, 1) = bIdx41 | ((u8)c41 & 1) * u64(-1);\n                mItemToBinMap(itemIdx5, 1) = bIdx51 | ((u8)c51 & 1) * u64(-1);\n                mItemToBinMap(itemIdx6, 1) = bIdx61 | ((u8)c61 & 1) * u64(-1);\n                mItemToBinMap(itemIdx7, 1) = bIdx71 | ((u8)c71 & 1) * u64(-1);\n\n\n                auto bIdx02 = CuckooIndex<>::getHash(hashs[0], 2, mNumBins);\n                auto bIdx12 = CuckooIndex<>::getHash(hashs[1], 2, mNumBins);\n                auto bIdx22 = CuckooIndex<>::getHash(hashs[2], 2, mNumBins);\n                auto bIdx32 = CuckooIndex<>::getHash(hashs[3], 2, mNumBins);\n                auto bIdx42 = CuckooIndex<>::getHash(hashs[4], 2, mNumBins);\n                auto bIdx52 = CuckooIndex<>::getHash(hashs[5], 2, mNumBins);\n                auto bIdx62 = CuckooIndex<>::getHash(hashs[6], 2, mNumBins);\n                auto bIdx72 = CuckooIndex<>::getHash(hashs[7], 2, mNumBins);\n\n\n                bool c02 = bIdx00 == bIdx02 || bIdx01 == bIdx02;\n                bool c12 = bIdx10 == bIdx12 || bIdx11 == bIdx12;\n                bool c22 = bIdx20 == bIdx22 || bIdx21 == bIdx22;\n                bool c32 = bIdx30 == bIdx32 || bIdx31 == bIdx32;\n                bool c42 = bIdx40 == bIdx42 || bIdx41 == bIdx42;\n                bool c52 = bIdx50 == bIdx52 || bIdx51 == bIdx52;\n                bool c62 = bIdx60 == bIdx62 || bIdx61 == bIdx62;\n                bool c72 = bIdx70 == bIdx72 || bIdx71 == bIdx72;\n\n\n                mBins(bIdx02, mBinSizes[bIdx02]++).set(itemIdx0, 2, c02);\n                mBins(bIdx12, mBinSizes[bIdx12]++).set(itemIdx1, 2, c12);\n                mBins(bIdx22, mBinSizes[bIdx22]++).set(itemIdx2, 2, c22);\n                mBins(bIdx32, mBinSizes[bIdx32]++).set(itemIdx3, 2, c32);\n                mBins(bIdx42, mBinSizes[bIdx42]++).set(itemIdx4, 2, c42);\n                mBins(bIdx52, mBinSizes[bIdx52]++).set(itemIdx5, 2, c52);\n                mBins(bIdx62, mBinSizes[bIdx62]++).set(itemIdx6, 2, c62);\n                mBins(bIdx72, mBinSizes[bIdx72]++).set(itemIdx7, 2, c72);\n\n                mItemToBinMap(itemIdx0, 2) = bIdx02 | ((u8)c02 & 1) * u64(-1);\n                mItemToBinMap(itemIdx1, 2) = bIdx12 | ((u8)c12 & 1) * u64(-1);\n                mItemToBinMap(itemIdx2, 2) = bIdx22 | ((u8)c22 & 1) * u64(-1);\n                mItemToBinMap(itemIdx3, 2) = bIdx32 | ((u8)c32 & 1) * u64(-1);\n                mItemToBinMap(itemIdx4, 2) = bIdx42 | ((u8)c42 & 1) * u64(-1);\n                mItemToBinMap(itemIdx5, 2) = bIdx52 | ((u8)c52 & 1) * u64(-1);\n                mItemToBinMap(itemIdx6, 2) = bIdx62 | ((u8)c62 & 1) * u64(-1);\n                mItemToBinMap(itemIdx7, 2) = bIdx72 | ((u8)c72 & 1) * u64(-1);\n            }\n\n            hasher.ecbEncBlocks(items.data() + itemIdx, remSteps, hashs.data());\n            for (u64 i = 0; i < remSteps; i += hashs.size())\n            {\n                hashs[i] = hashs[i] ^ items[itemIdx + i];\n\n                std::vector<u64> bIdxs(mNumHashFunctions);\n                for (u64 h = 0; h < mNumHashFunctions; ++h)\n                {\n                    auto bIdx = CuckooIndex<>::getHash(hashs[i], (u8)h, mNumBins);\n                    bool collision = false;\n\n                    bIdxs[h] = bIdx;\n                    for (u64 hh = 0; hh < h; ++hh)\n                        collision |= (bIdxs[hh] == bIdx);\n\n                    mBins(bIdx, mBinSizes[bIdx]++).set(itemIdx, u8(h), collision);\n                    mItemToBinMap(itemIdx + i, h) = bIdx | ((u8)collision & 1) * u64(-1);\n                }\n            }\n        }\n        else\n        {\n            std::vector<u64> bIdxs(mNumHashFunctions);\n            for (u64 i = 0; i < u64(items.size()); i += u64(hashs.size()))\n            {\n                auto min = std::min<u64>(items.size() - i, hashs.size());\n\n                hasher.ecbEncBlocks(items.data() + i, min, hashs.data());\n\n                for (u64 j = 0, itemIdx = i; j < min; ++j, ++itemIdx)\n                {\n                    hashs[j] = hashs[j] ^ items[itemIdx];\n\n                    for (u64 h = 0; h < mNumHashFunctions; ++h)\n                    {\n                        auto bIdx = CuckooIndex<>::getHash(hashs[j], (u8)h, mNumBins);\n                        bool collision = false;\n\n                        bIdxs[h] = bIdx;\n                        for (u64 hh = 0; hh < h; ++hh)\n                            collision |= (bIdxs[hh] == bIdx);\n\n                        mBins(bIdx, mBinSizes[bIdx]++).set(itemIdx, u8(h), collision);\n                        mItemToBinMap(itemIdx + i, h) = bIdx | ((u8)collision & 1) * u64(-1);\n\n                    }\n                }\n            }\n        }\n    }\n\n}\n", "meta": {"hexsha": "a6985bf63c28b8c6f6d5ffbe28f690b513bc88cd", "size": 13317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libPSI/Tools/SimpleIndex.cpp", "max_stars_repo_name": "WeDPR-Team/libPSI", "max_stars_repo_head_hexsha": "9c506b7be66e99363eb20878a8e146534a47bb78", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 91.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T15:01:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:05:00.000Z", "max_issues_repo_path": "libPSI/Tools/SimpleIndex.cpp", "max_issues_repo_name": "WeDPR-Team/libPSI", "max_issues_repo_head_hexsha": "9c506b7be66e99363eb20878a8e146534a47bb78", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:49:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T07:45:59.000Z", "max_forks_repo_path": "libPSI/Tools/SimpleIndex.cpp", "max_forks_repo_name": "WeDPR-Team/libPSI", "max_forks_repo_head_hexsha": "9c506b7be66e99363eb20878a8e146534a47bb78", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T03:05:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T09:25:38.000Z", "avg_line_length": 42.0094637224, "max_line_length": 165, "alphanum_fraction": 0.49981227, "num_tokens": 4165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5918258404161195}}
{"text": "#ifndef POINT_TRIANGLE_HPP\n#define POINT_TRIANGLE_HPP\n\n#include <Eigen/Core>\n\ntemplate<class U>\nclass projector {\npublic:\n  using real = U;\n  using vec3 = Eigen::Matrix<real, 3, 1>;\nprivate:\n  vec3 p1, p2, p3, p1p2, p1p3;\n  real distp1p2;\n  real fa, fb, fc;\n  real fdet;\n\n  // singular case\n  bool singular;\n  real e0, e1, sign, ff;\n  \n  static constexpr real epsilon = 1e-10;\npublic:\n  projector(vec3 p1, vec3 p2, vec3 p3):\n      p1(p1),\n      p2(p2),\n      p3(p3),\n      p1p2(p2 - p1),\n      p1p3(p3 - p1),\n      fa(p1p2.dot(p1p2)),\n      fb(p1p2.dot(p1p3)),\n      fc(p1p3.dot(p1p3)),\n      fdet(fa * fc - fb * fb),\n      singular(fdet < epsilon && fdet > -epsilon) {\n    \n  }\n\n  static vec3 project_edge(vec3 origin, vec3 dir, vec3 p) {\n    return origin + dir * dir.dot(p - origin) / dir.dot(dir);\n  }\n\n  vec3 operator()(vec3 p) const {\n    if(singular) {\n      if(fa + fc < epsilon) {\n        // single point: easy peasy\n        return p1;\n      }\n\n      if(fb > 0) {\n        // both edges point in the same direction: project on the longest\n        if(fa > fc) {\n          return project_edge(p1, p1p2, p);\n        } else {\n          return project_edge(p1, p1p3, p);\n        }\n      } else {\n        // edges pointing in opposite directions\n        return project_edge(p2, p3 - p2, p);\n      }\n    }\n\n    // non-singular case\n    const vec3 pp1 = p1 - p;\n    const real fd = p1p2.dot(pp1), fe = p1p3.dot(pp1);\n\n    // minimize squared distance to source point\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#endif\n", "meta": {"hexsha": "adaf2eb0950736edec856778305a7ad5012b3a79", "size": 4144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "point_triangle.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "point_triangle.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "point_triangle.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4715025907, "max_line_length": 73, "alphanum_fraction": 0.375, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5918158373454858}}
{"text": "#include <dlib/optimization.h>\n#include <fbxpstate.h>\n\nnamespace BezierFitter {\n    using namespace dlib;\n\n    // dlib reference fo the solver:\n    // http://dlib.net/least_squares_ex.cpp.html\n\n    typedef matrix< double, 3, 1 >                 BezierFitterInput;  // double t, P0, P3;\n    typedef matrix< double, 2, 1 >                 BezierFitterParams; // double P1, P2;\n    typedef std::pair< BezierFitterInput, double > BezierFitterSample; // double t, P0, P3 + Bt;\n\n    inline double Squared( double v ) {\n        return v * v;\n    }\n\n    inline double Cubed( double v ) {\n        return v * v * v;\n    }\n\n    inline double BezierFitterModel( const BezierFitterInput input, const BezierFitterParams params ) {\n        const double t  = input( 0 );\n        const double P0 = input( 1 );\n        const double P1 = params( 0 );\n        const double P2 = params( 1 );\n        const double P3 = input( 2 );\n        return Cubed( 1.0 - t ) * P0 + 3 * Squared( 1.0 - t ) * t * P1 + 3 * ( 1.0 - t ) * Squared( t ) * P2 + Cubed( t ) * P3;\n    }\n\n    inline double BezierFitterResidual( const BezierFitterSample input, const BezierFitterParams params ) {\n        const double Bt = input.second;\n        return BezierFitterModel( input.first, params ) - Bt;\n    }\n\n    inline BezierFitterParams BezierFitterResidualDerivative( const BezierFitterSample input,\n                                                              const BezierFitterParams params ) {\n        const double       t = input.first( 0 );\n        BezierFitterParams derivative;\n        derivative( 0 ) = 3 * Squared( 1.0 - t ) * t;\n        derivative( 1 ) = 3 * ( 1.0 - t ) * Squared( t );\n        return derivative;\n    }\n\n    static BezierFitterParams SolveBezier( std::vector< BezierFitterSample > samples ) {\n        BezierFitterParams bezierSolverParams;\n        bezierSolverParams = 0;\n\n        // Use the Levenberg-Marquardt method to determine the parameters which\n        // minimize the sum of all squared residuals.\n        solve_least_squares_lm( objective_delta_stop_strategy( 1e-7 ),\n                                BezierFitterResidual,\n                                BezierFitterResidualDerivative,\n                                samples,\n                                bezierSolverParams );\n\n        // If we didn't create the residual_derivative function then we could\n        // have used this method which numerically approximates the derivatives for you.\n        // solve_least_squares_lm( objective_delta_stop_strategy( 1e-7 ).be_verbose( ),\n        //                         BezierFitterResidual,\n        //                         derivative( BezierFitterResidual ),\n        //                         samples,\n        //                         x );\n\n        // This version of the solver uses a method which is appropriate for problems\n        // where the residuals don't go to zero at the solution.  So in these cases\n        // it may provide a better answer.\n        // solve_least_squares( objective_delta_stop_strategy( 1e-7 ).be_verbose( ),\n        // solve_least_squares( objective_delta_stop_strategy( 1e-7 ),\n        //                      BezierFitterResidual,\n        //                      BezierFitterResidualDerivative,\n        //                      samples,\n        //                      bezierSolverParams );\n\n        return bezierSolverParams;\n    }\n\n    static void ExtractSamples( FbxAnimCurve*                      pAnimCurve,\n                                const int                          /*startIndex*/,\n                                const double                       P0X,\n                                const double                       P0Y,\n                                const double                       P3X,\n                                const double                       P3Y,\n                                std::vector< BezierFitterSample >& samples ) {\n\n        // TODO: Scan only the relevan region, break the loop when the end time is reached.\n        for ( int i = 0; i < pAnimCurve->KeyGetCount(); ++i ) {\n            const double time = pAnimCurve->KeyGetTime( i ).GetSecondDouble( );\n\n            if ( time >= P0X && time <= P3X ) {\n                const double t  = ( time - P0X ) / ( P3X - P0X );\n                const double Bt = pAnimCurve->KeyGetValue( i );\n\n                BezierFitterSample sample;\n                sample.first( 0 ) = t;\n                sample.first( 1 ) = P0Y;\n                sample.first( 2 ) = P3Y;\n                sample.second     = Bt;\n\n                samples.push_back( sample );\n            }\n        }\n    }\n\n} // namespace BezierFitter\n\nbool BezierFitterFitSamples( FbxAnimCurve* pAnimCurve,\n                             const int     startIndex,\n                             const double  BezP0X,\n                             const double  BezP0Y,\n                             const double  BezP3X,\n                             const double  BezP3Y,\n                             double&       BezP1Y,\n                             double&       BezP2Y ) {\n    std::vector< BezierFitter::BezierFitterSample > samples;\n    BezierFitter::ExtractSamples( pAnimCurve, startIndex, BezP0X, BezP0Y, BezP3X, BezP3Y, samples );\n\n    auto & s = apemode::State::Get( );\n    if ( !samples.empty( ) ) {\n        auto params = BezierFitter::SolveBezier( std::move( samples ) );\n        BezP1Y = params( 0 );\n        BezP2Y = params( 1 );\n        s.console->debug( \"Samples taken: {}\", samples.size( ) );\n        s.console->debug( \"Solved Bezier: {} {}\", BezP1Y, BezP2Y );\n        return true;\n    }\n\n    s.console->error(\"Failed to find the samples for fitting the Bezier control points.\");\n    return false;\n}\n\nvoid BezierFitterFitSamples( FbxAnimCurve* pAnimCurve, int keyIndex, double& OutFittedBezier1, double& OutFittedBezier2 ) {\n    assert( pAnimCurve && ( keyIndex < ( pAnimCurve->KeyGetCount( ) - 1 ) ) );\n    auto& s = apemode::State::Get( );\n\n    const FbxString copiedCurveName = pAnimCurve->GetNameOnly() + \" [FbxPipeline-Copy]\";\n    if ( FbxAnimCurve* pCopiedAnimCurve = FbxAnimCurve::Create( s.manager, copiedCurveName.Buffer() ) ) {\n        pCopiedAnimCurve->CopyFrom( *pAnimCurve );\n\n        auto resampleStartTime = pAnimCurve->KeyGet( keyIndex ).GetTime( );\n        auto resampleStopTime  = pAnimCurve->KeyGet( keyIndex + 1 ).GetTime( );\n\n        FbxTime resamplePeriodTime;\n        resamplePeriodTime.SetMilliSeconds( ( FbxLongLong )( 1000.0f / 180.0f ) );\n\n        FbxAnimCurveFilterResample animCurveFilterResample;\n        animCurveFilterResample.SetPeriodTime( resamplePeriodTime );\n        animCurveFilterResample.SetStartTime( resampleStartTime );\n        animCurveFilterResample.SetStopTime( resampleStopTime );\n        animCurveFilterResample.Apply( *pCopiedAnimCurve );\n\n        BezierFitterFitSamples( pCopiedAnimCurve,\n                                keyIndex,\n                                pAnimCurve->KeyGet( keyIndex ).GetTime( ).GetSecondDouble( ),\n                                pAnimCurve->KeyGet( keyIndex ).GetValue( ),\n                                pAnimCurve->KeyGet( keyIndex + 1 ).GetTime( ).GetSecondDouble( ),\n                                pAnimCurve->KeyGet( keyIndex + 1 ).GetValue( ),\n                                OutFittedBezier1,\n                                OutFittedBezier2 );\n\n        pCopiedAnimCurve->Destroy( );\n    }\n}\n", "meta": {"hexsha": "870aa1838ab356a48f2838ebb15313159c6c2776", "size": 7360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FbxPipeline/FbxPipeline/fbxpbez.cpp", "max_stars_repo_name": "VladSerhiienko/FbxPipeline", "max_stars_repo_head_hexsha": "540a6b7f90e402dcf3c8c7b25a6fb831e552b164", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T04:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T10:58:11.000Z", "max_issues_repo_path": "FbxPipeline/FbxPipeline/fbxpbez.cpp", "max_issues_repo_name": "VladSerhiienko/FbxPipeline", "max_issues_repo_head_hexsha": "540a6b7f90e402dcf3c8c7b25a6fb831e552b164", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T12:26:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-22T17:30:44.000Z", "max_forks_repo_path": "FbxPipeline/FbxPipeline/fbxpbez.cpp", "max_forks_repo_name": "VladSerhiienko/FbxPipeline", "max_forks_repo_head_hexsha": "540a6b7f90e402dcf3c8c7b25a6fb831e552b164", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-02-04T23:57:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-08T01:59:24.000Z", "avg_line_length": 44.8780487805, "max_line_length": 127, "alphanum_fraction": 0.5451086957, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5918158326551756}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_FFT_HPP\n#define STAN_MATH_PRIM_FUN_FFT_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <unsupported/Eigen/FFT>\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 * 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>\ninline Eigen::Matrix<scalar_type_t<V>, -1, 1> fft(const V& x) {\n  // copy because fft() requires Eigen::Matrix type\n  Eigen::Matrix<scalar_type_t<V>, -1, 1> xv = x;\n  if (xv.size() <= 1)\n    return xv;\n  Eigen::FFT<base_type_t<V>> fft;\n  return fft.fwd(xv);\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 * 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>\ninline Eigen::Matrix<scalar_type_t<V>, -1, 1> inv_fft(const V& y) {\n  // copy because fft() requires Eigen::Matrix type\n  Eigen::Matrix<scalar_type_t<V>, -1, 1> yv = y;\n  if (y.size() <= 1)\n    return yv;\n  Eigen::FFT<base_type_t<V>> fft;\n  return fft.inv(yv);\n}\n\n/**\n * Return the two-dimensional discrete Fourier transform of the\n * specified complex matrix.  The 2D discrete Fourier transform first\n * runs the discrete Fourier transform on the each row, then on each\n * column of the result.\n *\n * @tparam M type of complex matrix argument\n * @param[in] x matrix to transform\n * @return discrete 2D Fourier transform of `x`\n */\ntemplate <typename M, require_eigen_dense_dynamic_vt<is_complex, M>* = nullptr>\ninline Eigen::Matrix<scalar_type_t<M>, -1, -1> fft2(const M& x) {\n  Eigen::Matrix<scalar_type_t<M>, -1, -1> y(x.rows(), x.cols());\n  for (int i = 0; i < y.rows(); ++i)\n    y.row(i) = fft(x.row(i));\n  for (int j = 0; j < y.cols(); ++j)\n    y.col(j) = fft(y.col(j));\n  return y;\n}\n\n/**\n * Return the two-dimensional inverse discrete Fourier transform of\n * the specified complex matrix.  The 2D inverse discrete Fourier\n * transform first runs the 1D inverse Fourier transform on the\n * columns, and then on the resulting rows.  The composition of the\n * FFT and inverse FFT (or vice-versa) is the identity.\n *\n * @tparam M type of complex matrix argument\n * @param[in] y matrix to inverse trnasform\n * @return inverse discrete 2D Fourier transform of `y`\n */\ntemplate <typename M, require_eigen_dense_dynamic_vt<is_complex, M>* = nullptr>\ninline Eigen::Matrix<scalar_type_t<M>, -1, -1> inv_fft2(const M& y) {\n  Eigen::Matrix<scalar_type_t<M>, -1, -1> x(y.rows(), y.cols());\n  for (int j = 0; j < x.cols(); ++j)\n    x.col(j) = inv_fft(y.col(j));\n  for (int i = 0; i < x.rows(); ++i)\n    x.row(i) = inv_fft(x.row(i));\n  return x;\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "ffca15a0108a896739d47dab72ccff67570b50ec", "size": 3776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/fft.hpp", "max_stars_repo_name": "sdrees/math", "max_stars_repo_head_hexsha": "f9896ae3b2b641510d410d7144b8709a2f36f017", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/fft.hpp", "max_issues_repo_name": "sdrees/math", "max_issues_repo_head_hexsha": "f9896ae3b2b641510d410d7144b8709a2f36f017", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/fft.hpp", "max_forks_repo_name": "sdrees/math", "max_forks_repo_head_hexsha": "f9896ae3b2b641510d410d7144b8709a2f36f017", "max_forks_repo_licenses": ["BSD-3-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.0, "max_line_length": 79, "alphanum_fraction": 0.6739936441, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.591752445084269}}
{"text": "//\n// Compute jump ahead coefficients for Mersenne Twister RNG.\n// Ken-Ichi Ishikawa [ishikawa[at]theo.phys.sci.hiroshima-u.ac.jp]\n//\n// See also: \n//  H. Haramoto, M. Matsumoto, T. Nishimura, F. Panneton, and P. L'Ecuyer, \n//   ``Efficient Jump Ahead for F_2-Linear Random Number Generators'', \n//  GERAD Report G-2006-62. INFORMS Journal on Computing, 20, 3 (2008), 385-390. \n//\n// This routine uses;\n//  Fast arithmetic in GF(2)[x], [http://wwwmaths.anu.edu.au/~brent/software.html]\n//  NTL : A Library for doing Number Theory, [http://www.shoup.net/ntl/index.html]\n//\n//\n// Copyright (c) 2010, Ken-Ichi Ishikawa [ishikawa[at]theo.phys.sci.hiroshima-u.ac.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\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 copyright\n//   notice, this list of conditions and the following disclaimer listed\n//   in this license in the documentation and/or other materials\n//   provided with the distribution.\n//   \n// * Neither the name of the copyright holders 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 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\n#include <NTL/GF2X.h>\nNTL_CLIENT\n\n//#define _DEBUG_\n#ifdef _DEBUG_\n#define DEBUG_PRINTF(format, args...)  fprintf(stderr, format, ## args)\n#else\n#define DEBUG_PRINTF(format, args...)  ;\n#endif\n\nvoid print_hex(GF2X &f)\n{\n    int ww = 32;\n    int nb = NumBits(f);\n    int nn = (int)ceil((double)nb/(double)ww);\n    unsigned int pp[nn];\n    for(int i = 0; i < nn ; i++) pp[i] = 0;\n    for(int i = 0; i < nb ; i++) {\n      int iw = i / ww;\n      int ib = i % ww;\n      if (1 == coeff(f,i)) pp[iw] += (1 << ib);\n    }\n    if (0 != pp[nn-1]) printf(\"%X\",pp[nn-1]);\n    for(int i = nn-2; i > -1 ; i--) {\n      printf(\"%8.8X\",pp[i]);\n    }\n    printf(\"\\n\");\n}\n\nextern \"C\"\nvoid get_coeff (const int& nn,     // MT param n\n                const int& mm,     //          m\n                const int& rr,     //          r\n                const int& ww,     //          w => MT period_exp = n*w - r\n                const int& avec,   //        aaa => companion matirx component vector a\n                const int& nj,     // jump ahead step exponent   : id*(2^nj)\n                const int& id,     // jump ahead step id=[0,...] : id*(2^nj)\n                unsigned int *pp,  // jump ahead polynomial coefficients, pp[nn]\n                int& np)           // jump ahead polynomial order(bit size)\n{\n  if (id <= 0) return;\n  int period_exp = nn*ww-rr;\n  int ns = (int)ceil(log((double)period_exp)/log(2.0));\n\n  //\n  // Compute MT characteristic polynomial f(x)\n  // [see,\n  //  M. Matsumoto and T. Nishimura, \n  //  \"Mersenne Twister: A 623-dimensionally equidistributed uniform\n  //                                   pseudorandom number generator\", \n  //  ACM Trans. on Modeling and Computer Simulation Vol. 8, No. 1, \n  //  January pp.3-30 (1998) DOI:10.1145/272991.272995 for explicit form]\n  //\n  // f(x) =         af^(w-r) * bf^r\n  //      + a(0)  * af^(w-r) * bf^(r-1)\n  //      + a(1)  * af^(w-r) * bf^(r-2)\n  //      + ....\n  //      + a(r-2)* af^(w-r) * bf^(1)\n  //      + a(r-1)* af^(w-r)\n  //      + a(r)  * af^(w-r-1)\n  //      + a(r+1)* af^(w-r-2)\n  //      + ...\n  //      + a(w-2)* af^(1)\n  //      + a(w-1)\n  // where\n  //   af = x^nn     + x^mm;\n  //   bf = x^(nn-1) + x^(mm-1);\n  //\n  GF2X *af, *bf;\n  af = new GF2X;\n  bf = new GF2X;\n  SetCoeff(*af,nn);\n  SetCoeff(*af,mm);   // af = x^nn + x^mm;\n  SetCoeff(*bf,nn-1);\n  SetCoeff(*bf,mm-1); // bf = x^(nn-1) + x^(mm-1)\n  GF2X *f;\n  f = new GF2X;\n  *f = power(*af,ww-rr) * power(*bf,rr);\n  for (int i=0;i<rr;i++) {\n    int ib = i % ww;\n    int a = (avec >> ib) & 0x1;\n    if (1 == a) *f += power(*af,ww-rr) * power(*bf,rr-1-i);\n  }\n  for (int i=rr;i<ww;i++) {\n    int ib = i % ww;\n    int a = (avec >> ib) & 0x1;\n    if (1 == a) *f += power(*af,ww-1-i);\n  }\n  delete af;\n  delete bf;\n\n  //\n  // compute r(x) = x^((2^nj)*id) mod f(x)\n  //\n\n  //\n  // g(x) = x^(2^nj) mod f(x) \n  //\n  GF2X *g;\n  g = new GF2X;\n  if ( ns < nj ) {\n    SetCoeff(*g,(1 << ns)); // g(x) = x^(2^ns)\n    *g = *g % (*f);\n    for (int i=ns;i < nj;i++) *g = power(*g,2) % (*f);\n\n  } else {\n\n    SetCoeff(*g,(1 << nj)); // g(x) = x^(2^nj)\n\n  }\n\n\n#ifdef _DEBUG_\n  printf(\"%8d\\n\",ns);\n  printf(\"%8d\\n\",nj);\n  printf(\"@\");\n  print_hex(*f);\n  printf(\"@\");\n  print_hex(*g);\n#endif\n\n\n  //\n  // r(x) = g(x)^id mod f(x)\n  //\n\n  int id_bits = (int)floor(log(double(id))/log(2.0)) + 1; // bit size of id\n  DEBUG_PRINTF(\"id=%d id_bits=%d\\n\",id,id_bits);\n  GF2X *r;\n  r = new GF2X;\n  SetCoeff(*r,0);  // r(x) = 1\n  for (int i=id_bits;i >=0; --i) {\n\n    *r = power(*r,2) % (*f);\n\n    if (1 == ((id >> i)& 1)) *r = ((*r) * (*g)) % (*f);\n\n  }\n  delete g;\n  delete f;\n\n#ifdef _DEBUG_\n  printf(\"@\");\n  print_hex(*r);\n#endif\n\n  //\n  // extract bit sequence (=pp[]) from r(x)\n  //\n  {\n    int nb = NumBits(*r);\n    for(int i = 0; i < nn ; i++) pp[i] = 0;\n    for(int i = 0; i < nb ; i++) {\n      int iw = i / ww;\n      int ib = i % ww;\n      if (1 == coeff(*r,i)) pp[iw] += (1 << ib);\n    }\n    np = nb;\n  }\n  delete r;\n\n}\n", "meta": {"hexsha": "8fba2bee17fae6d6560cc7d8afca0788c4b34745", "size": 6177, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "mt_stream_f90-1.11/jump_ahead_coeff/get_coeff.cxx", "max_stars_repo_name": "jonekoo/CoarseMC", "max_stars_repo_head_hexsha": "7f9d032fe8f7e45a3cab857cd38de33c05f4b7c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mt_stream_f90-1.11/jump_ahead_coeff/get_coeff.cxx", "max_issues_repo_name": "jonekoo/CoarseMC", "max_issues_repo_head_hexsha": "7f9d032fe8f7e45a3cab857cd38de33c05f4b7c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T15:42:17.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-02T22:15:33.000Z", "max_forks_repo_path": "mt_stream_f90-1.11/jump_ahead_coeff/get_coeff.cxx", "max_forks_repo_name": "jonekoo/CoarseMC", "max_forks_repo_head_hexsha": "7f9d032fe8f7e45a3cab857cd38de33c05f4b7c5", "max_forks_repo_licenses": ["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.5550239234, "max_line_length": 87, "alphanum_fraction": 0.554476283, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.5917524225646649}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::point.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_POINT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_POINT_HPP_ER_2009\n#include <ostream>\n#include <boost/ars/constant.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\n\n// Given an unnormalized density f, this class is a representation for (x,y,dy), \n// where y = log f(x).\ntemplate <typename T>\nclass point{\n    typedef constant<T> const_;\n\n    public:\n    point(): x_(const_::zero_),y_(const_::zero_),dy_(const_::zero_){}\n    point(const T& x,const T& y,const T& dy)\n    : x_(x),y_(y),dy_(dy){}\n\n    const T& x()const{ return x_; }\n    const T& y()const{ return y_; }\n    const T& dy()const{ return dy_; }\n\n    private:\n    //abscissa, ordinate, derivative of the log density\n    T x_, y_, dy_;\n};\n\ntemplate<typename T>\nvoid dump(const point<T>& p,T& x,T& y,T& dy){\n    x = p.x();\n    y = p.y();\n    dy = p.dy();\n}\n\ntemplate <typename T>\nbool operator<(\n    const point<T> &a,\n    const point<T> &b\n){\n    return (a.x() < b.x());\n}\n\ntemplate <typename T>\nstd::ostream&\noperator<<(std::ostream &out, const point<T>& p)\n{\n    out << '(' << p.x() << ',' << p.y() << ',' << p.dy() << ')';\n    return out;\n}\n\ntemplate<typename T,typename F>\npoint<T>\ncreate_point(\n    const T& x,\n    const F& f\n){\n    typedef point<T> result_t;\n    T y, dy;\n    f(x,y,dy);\n    return result_t(x,y,dy);\n}\n\ntemplate<typename T>\nT tangent(const point<T>& a, const T& x){\n    return a.y() + a.dy() * (x-a.x());\n}\n\ntemplate<typename T>\nbool is_non_increasing_dy(const point<T>&a,const point<T>& b){\n    return !(a.dy()<b.dy());\n}\n\ntemplate<typename T>\nbool is_concave(const point<T>&a,const point<T>& b){\n    T t_b = tangent(a,b.x());\n    T t_a = tangent(b,a.x());\n    return !( (t_b < b.y()) || (t_a < a.y()) );\n}\n\ntemplate<typename T>\nT linearly_interpolate(\n    const point<T>& a,\n    const point<T>& b,\n    const T& x\n){\n    T slope =  (b.y() - a.y()) / (b.x() - a.x());\n    return a.y() + (x-a.x()) * slope;\n}\n\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif // BOOST_STATISTICS_DETAIL_ARS_POINT_HPP_ER_2009\n", "meta": {"hexsha": "4872a6035e4b3dda9961dcefdbb34f3340ffd476", "size": 2619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/point.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/point.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/point.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": 24.7075471698, "max_line_length": 81, "alphanum_fraction": 0.5318823979, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.5917474440034679}}
{"text": "#include <boost/numeric/bindings/traits/ublas_banded.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n#include <boost/numeric/bindings/lapack/gbsv.hpp>\n#include <vector>\n#include <stdexcept>\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nstatic const char NORMAL = 'N';\nstatic const char TRANSPOSE = 'T';\n\n// solves the equation Ax = B, and puts the solution in B\n// A is mutated by this routine\ntemplate <typename MatrA, typename MatrB>\nvoid InPlaceSolve(MatrA& a, MatrB& b)\n{\n  std::vector<integer_t> piv(a.size1());\n  int ret = lapack::gbtrf(a, piv);\n  if (ret < 0) {\n    //CStdString err;\n    //err.Format(\"banded::Solve: argument %d in DGBTRF had an illegal value\", -ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: argument %d in DGBTRF had an illegal value\");\n  }\n  if (ret > 0) {\n    //CStdString err;\n    //err.Format(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\", ret, ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\");\n  }\n\n  ret = lapack::gbtrs(NORMAL, a, piv, b);\n  if (ret < 0) {\n    //CStdString err;\n    //err.Format(\"banded::Solve: argument %d in DGBTRS had an illegal value\", -ret);\n    //throw RuntimeError(err);\n    throw std::runtime_error(\"banded::Solve: argument %d in DGBTRS had an illegal value\");\n  }\n}\n\ntemplate<typename T>\nvoid do_typename()\n{\n  using namespace boost::numeric::ublas;\n  // if the matrix has kl lower and ku upper diagonals, then we should\n  // allocate kl lower and kl+ku upper diagonals\n  size_t sz = 1000, kl = 1, ku = 1;\n  ublas::banded_matrix<T> a(sz, sz, kl, kl+ku);\n  ublas::vector<T> b(sz);\n  // fill values in a and b\n  for (size_t i = 0; i < sz; ++i) {\n    a(i,i) = i;\n    b(i) = i;\n  }\n  for (size_t i = 1; i < sz; ++i) {\n    a(i,i-1) = i;\n    a(i-1,i) = 1;\n  }\n  InPlaceSolve(a, b);\n}\n\nint main()\n{\n  do_typename<float>();\n  do_typename<double>();\n  do_typename<std::complex<float> >();\n  do_typename<std::complex<double> >();\n  return 0;\n}\n", "meta": {"hexsha": "7738ecc9c853bc61bb2de4b6272cdf291c5b5011", "size": 2093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.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_gbsv.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4788732394, "max_line_length": 94, "alphanum_fraction": 0.652173913, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5917474422004046}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  MatrixXd m = MatrixXd::Random(3,3);\n  m = (m + MatrixXd::Constant(3,3,1.2)) * 50;\n  cout << \"m =\" << endl << m << endl;\n  VectorXd v(3);\n  v << 1, 2, 3;\n  cout << \"m * v =\" << endl << m * v << endl;\n}\n", "meta": {"hexsha": "ff6746e21861f2e25d590e5865ca4260e73dfcb0", "size": 305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/QuickStart_example2_dynamic.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/QuickStart_example2_dynamic.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/QuickStart_example2_dynamic.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 19.0625, "max_line_length": 45, "alphanum_fraction": 0.5508196721, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5915626269130303}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n#include <chrono>\n#include <cxxopts.hpp>\n\n#include \"DavidsonSolver.hpp\"\n#include \"DavidsonOperator.hpp\"\n#include \"MatrixFreeOperator.hpp\"\n\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\n#define MAXBUFSIZE  ((int) 1e6)\n\nEigen::MatrixXd readMatrix(const char *filename)\n    {\n    int cols = 0, rows = 0;\n    double buff[MAXBUFSIZE];\n\n    // Read numbers from file into buffer.\n    ifstream infile;\n    infile.open(filename);\n    while (! infile.eof())\n        {\n        string line;\n        getline(infile, line);\n\n        int temp_cols = 0;\n        stringstream stream(line);\n        while(! stream.eof())\n            stream >> buff[cols*rows+temp_cols++];\n\n        if (temp_cols == 0)\n            continue;\n\n        if (cols == 0)\n            cols = temp_cols;\n\n        rows++;\n        }\n\n    infile.close();\n\n    rows--;\n\n    // Populate matrix with numbers.\n    Eigen::MatrixXd result(rows,cols);\n    for (int i = 0; i < rows; i++)\n        for (int j = 0; j < cols; j++)\n            result(i,j) = buff[ cols*i+j ];\n\n    return result;\n    };\n\n\n\nint main (int argc, char *argv[]){\n\n    // parse the input\n    cxxopts::Options options(argv[0],  \"Eigen Davidson Iterative Solver\");\n    options.positional_help(\"[optional args]\").show_positional_help();\n    options.add_options()\n        (\"size\", \"dimension of the matrix\", cxxopts::value<std::string>()->default_value(\"100\"))\n        (\"eps\", \"sparsity of the matrix\", cxxopts::value<std::string>()->default_value(\"0.01\"))\n        (\"neigen\", \"number of eigenvalues required\", cxxopts::value<std::string>()->default_value(\"5\"))\n        (\"corr\", \"correction method\", cxxopts::value<std::string>()->default_value(\"DPR\"))\n        (\"mf\", \"use matrix free\", cxxopts::value<bool>())\n        (\"diag\", \"diagonal elements are ordered\" , cxxopts::value<bool>())\n        (\"reorder\", \"reorder diagonal elements\" , cxxopts::value<bool>())\n        (\"linsolve\", \"method to solve the linear system of JOCC (CG, GMRES, LLT)\", cxxopts::value<std::string>()->default_value(\"CG\"))\n        (\"init\", \"method to itialize the eigenvector (target, indentity, random)\", cxxopts::value<std::string>()->default_value(\"target\"))\n        (\"tol\", \"tolerance on the residue norm\", cxxopts::value<std::string>()->default_value(\"1E-4\"))\n        (\"lstol\", \"tolerance of the linear solver\", cxxopts::value<std::string>()->default_value(\"0.01\"))\n        (\"help\", \"Print the help\", cxxopts::value<bool>());\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\n    int size = std::stoi(result[\"size\"].as<std::string>(),nullptr);\n    int neigen = std::stoi(result[\"neigen\"].as<std::string>(),nullptr);\n    bool mf = result[\"mf\"].as<bool>();\n    bool odiag = result[\"diag\"].as<bool>();\n    bool reorder = result[\"reorder\"].as<bool>();\n    std::string linsolve = result[\"linsolve\"].as<std::string>();\n    std::string eigen_init = result[\"init\"].as<std::string>();\n    std::string correction = result[\"corr\"].as<std::string>();\n    bool help = result[\"help\"].as<bool>();\n    double eps = std::stod(result[\"eps\"].as<std::string>(),nullptr);\n    double davidson_tol = std::stod(result[\"tol\"].as<std::string>(),nullptr);\n    double lsolve_tol = std::stod(result[\"lstol\"].as<std::string>(),nullptr);\n\n    // chrono    \n    std::chrono::time_point<std::chrono::system_clock> start, end;\n    std::chrono::duration<double> elapsed_time;\n\n    std::cout << \"Matrix size : \" << size << \"x\" << size << std::endl;\n    std::cout << \"Num Threads : \" <<  Eigen::nbThreads() << std::endl;\n    std::cout << \"eps : \" <<  eps << std::endl;\n\n    // Create Operator\n    DavidsonOperator Aop(size,eps,odiag,reorder);\n    Eigen::MatrixXd Afull = Aop.get_full_mat();\n    std::cout << \"Afull\" << std::endl << Afull.block(0,0,5,5) << std::endl;\n\n    // Davidosn Solver\n    start = std::chrono::system_clock::now();\n    DavidsonSolver DS;\n\n    DS.set_guess_vectors(eigen_init);\n    DS.set_correction(correction);\n    DS.set_tolerance(davidson_tol);\n\n    if (correction == \"JACOBI\") {\n        DS.set_jacobi_linsolve(linsolve);\n        DS.set_linsolve_tol(lsolve_tol);\n    }\n\n    if (mf) DS.solve(Aop,neigen);\n    else  DS.solve(Afull,neigen);\n    \n    end = std::chrono::system_clock::now();\n    elapsed_time = end-start;\n    std::cout << std::endl << \"Davidson               : \" << elapsed_time.count() << \" secs\" <<  std::endl;\n    \n    // normal eigensolver\n    start = std::chrono::system_clock::now();\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es2(Afull);\n    end = std::chrono::system_clock::now();\n    elapsed_time = end-start;\n    std::cout << \"Eigen                  : \" << elapsed_time.count() << \" secs\" <<  std::endl;\n    \n    auto dseigop = DS.eigenvalues();\n    auto eig2 = es2.eigenvalues().head(neigen);\n    std::cout << std::endl <<  \"      Davidson  \\tEigen \\t\\t Error\" << std::endl;\n    for(int i=0; i< neigen; i++)\n        printf(\"#% 4d %8.7f \\t%8.7f \\t %4.2e\\n\",i,dseigop(i),eig2(i),abs(eig2(i)-dseigop(i)));\n\n}", "meta": {"hexsha": "84b4eac87b17f8c13b7bca6b0b9e0e15ef6f6904", "size": 5172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "NLESC-JCER/DavidsonEigen", "max_stars_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T17:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:40:44.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "NLESC-JCER/DavidsonEigen", "max_issues_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T14:45:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T14:45:08.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "NLESC-JCER/DavidsonEigen", "max_forks_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:05:37.000Z", "avg_line_length": 34.48, "max_line_length": 138, "alphanum_fraction": 0.601121423, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5915445078026055}}
{"text": "/* ****************** */\n/* Include packages   */\n/* ****************** */\n#include <math.h>\n#include <vector>\n#include <stdio.h>\n#include <stdlib.h>\n#include <fstream>\n#include <algorithm>\n#include <random>\n#include <iostream>\n#include <time.h>\n#include <stack>\n#include <assert.h>\n//include Eigen\n// #include \"eigen3/Eigen/Dense\"\n// #include \"eigen3/Eigen/Sparse\"\n// #include \"eigen3/Eigen/SparseLU\"\n// #include \"eigen3/Eigen/SparseQR\"\n// #include \"eigen3/Eigen/SparseCholesky\"\n// #include \"eigen3/Eigen/IterativeLinearSolvers\"\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n#include <Eigen/SparseCholesky>\n#include <Eigen/IterativeLinearSolvers>\ntypedef Eigen::SparseMatrix<double > SpMat;\ntypedef Eigen::Triplet<double> T;\n#include <typeinfo>\n#include \"MarketIO.h\"\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/eigen.h>\n\n//include MEX related files\n// #include \"mex.h\"\n// #include \"matrix.h\"\n\n/* ******************** */\n/* State Variable Class */\n/* ******************** */\n\nEigen::MatrixXd empty;\nEigen::ArrayXd emptyAry;\n\n\n\nnamespace py = pybind11;\nusing namespace std;\nusing MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n\n/* Timer functions                                    */\n/******************************************************/\n\nstd::stack<clock_t> tictoc_stack;\n\nvoid tic() {\n    tictoc_stack.push(clock());\n}\n\nvoid toc() {\n    std::cout << \"Time elapsed: \"\n    << ((double)(clock() - tictoc_stack.top())) / CLOCKS_PER_SEC\n    << std::endl;\n    tictoc_stack.pop();\n}\n\nclass stateVars {\n    \npublic:\n    Eigen::MatrixXd stateMat; //matrix to store state variables\n    Eigen::MatrixXd stateMatNorm; //matrix to store normalized state variables [-1,1]\n    Eigen::ArrayXd increVec; //vector to record steps\n    Eigen::ArrayXd dVec; //vector to record steps\n    int N; // num of dimensions\n    int S; // number of rows for the grid\n    Eigen::ArrayXd upperLims;\n    Eigen::ArrayXd lowerLims;\n    Eigen::ArrayXd gridSizes;\n\n    stateVars (Eigen::ArrayXd, Eigen::ArrayXd, Eigen::ArrayXd); //constructors with arrays of upper/lower bounds and gridsizes \n    stateVars (Eigen::MatrixXd); //constructors by loading in data\n\n};\n\n\nstateVars::stateVars (Eigen::ArrayXd upper, Eigen::ArrayXd lower, Eigen::ArrayXd gridSizes) {\n    \n    upperLims = upper;\n    lowerLims = lower;\n    N = upperLims.size();\n    S = gridSizes.prod();\n    stateMat.resize(S,N);\n    dVec.resize(N);\n    increVec.resize(N);\n    increVec(0) = 1;\n        \n    //fill in the state object; similar to the ndgrid function in MATLAB\n    \n    for (int n = 0; n < N; ++n) {\n            \n        if (n != 0) {\n            increVec(n) = gridSizes(n - 1) * increVec(n - 1);\n        }\n        dVec(n) = (upper(n) - lower(n)) / (gridSizes(n) - 1);\n        \n        for (int i = 0; i < S; ++i) {\n            stateMat(i,n) = lower(n) + dVec(n) * ( int(i /  increVec(n) ) % int( gridSizes(n) ) );\n        }\n            \n    }\n    \n}\n\nstateVars::stateVars (Eigen::MatrixXd preLoad) {\n\n    //fill in stateMat based on data loaded\n    N = preLoad.cols();\n    S = preLoad.rows();\n    stateMat.resize(S,N);\n    dVec.resize(N); dVec.setZero();\n    increVec.resize(N); increVec.setZero();\n    upperLims.resize(N); lowerLims.resize(N);\n    for (int j = 0; j < preLoad.cols(); ++j) {\n        upperLims(j) = preLoad.col(j).maxCoeff();\n        lowerLims(j) = preLoad.col(j).minCoeff();\n    }\n    \n    stateMat = preLoad;\n    \n    //figure out dVec and increVec\n    for (int i = 1; i < S; ++i) {\n        for (int n = 0; n < N; ++n ) {\n            double diff = stateMat(i,n) - stateMat(i-1,n);\n            if (diff > 0 && dVec(n) == 0 && increVec(n) == 0) {\n                dVec(n) = diff;\n                increVec(n) = i;\n            }\n        }\n        \n    }\n    \n\n\n}\n\nstruct bc {\n    double a0;\n    double a0S;\n    bool natural;\n    Eigen::ArrayXd level;\n    Eigen::ArrayXd first;\n    Eigen::ArrayXd second;\n    \n    bc(int d) {\n        level.resize(d); first.resize(d); second.resize(d);\n    }\n};\n\nstruct elas {\n    Eigen::MatrixXd elas1sc;\n    Eigen::MatrixXd elas1c; //exposure elas\n    Eigen::MatrixXd elas2sc;\n    Eigen::MatrixXd elas2c; //exposure elas\n    Eigen::MatrixXd elas1p; //price elas\n    Eigen::MatrixXd elas2p;  //price elas\n    \n    elas(int T, int S) {\n        elas1sc.resize(S,T); elas1c.resize(S,T); elas1p.resize(S,T);\n        elas2sc.resize(S,T); elas2c.resize(S,T); elas2p.resize(S,T);\n    }\n};\n\n\n\n\nclass linearSysVars {\n    \npublic:\n    double dt;\n    int k;\n    Eigen::MatrixXd A; \n    Eigen::MatrixXd B;\n    Eigen::MatrixXd C;\n    Eigen::MatrixXd D;\n\n    Eigen::ArrayXd atBoundIndicators;\n\n    std::vector<T> matList; \n    std::string solverType;\n    SpMat Le;\n\n    //member functions\n    \n    //constructor\n    linearSysVars(stateVars & state_vars, Eigen::MatrixXd A, Eigen::MatrixXd B, Eigen::MatrixXd C, Eigen::MatrixXd D, double dt);\n    \n    //function to construt matrix\n    \n    void constructMatFT(stateVars & state_vars);\n    void constructMatFK(stateVars & state_vars);\n\n};\n\nlinearSysVars::linearSysVars(stateVars & state_vars, Eigen::MatrixXd AInput, Eigen::MatrixXd BInput, Eigen::MatrixXd CInput, Eigen::MatrixXd DInput, double dtInput) {\n        \n    Le.resize(state_vars.S,state_vars.S);\n    A.resize(state_vars.S,1); B.resize(state_vars.S,state_vars.N);\n    C.resize(state_vars.S,state_vars.N); D.resize(state_vars.S,1);\n    A = AInput; B = BInput; C = CInput; D = DInput;\n    dt = dtInput;\n\n}\n\n\n\nvoid linearSysVars::constructMatFT(stateVars & state_vars) {\n    matList.clear();\n    matList.reserve(10 * state_vars.S);\n    atBoundIndicators.resize(state_vars.N);\n    double atBound = -1;\n    double upperBound = -1;\n    //construct matrix\n\n    for (int i = 0; i < state_vars.S; ++i) {\n        //level and time deriv\n        \n        atBound = -1;\n        //check boundaries\n        \n        matList.push_back(T(i,i, (1.0 - dt * A(i,0))  ));\n        \n        for (int n  = (state_vars.N - 1); n >=0; --n ) {\n            \n            atBoundIndicators(n) = -1.0;\n            \n            double firstCoefE = B(i,n);\n            \n            double secondCoefE = C(i,n);\n            \n            //check whether it's at upper or lower boundary\n            if ( std::abs(state_vars.stateMat(i,n) - state_vars.upperLims(n)) < state_vars.dVec(n)/2.0 ) {  //upper boundary\n                atBoundIndicators(n) = 1.0;\n        \n                atBound = 1.0;\n                upperBound = 1.0;\n                /* Uncomment this section if you want natural boundaries */\n                \n                 matList.push_back(T(i, i, - dt * ( firstCoefE/state_vars.dVec(n) + secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - firstCoefE/state_vars.dVec(n) - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                 matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                \n                /* Uncomment this section if you want first derivatives = constant  \n                 matList.push_back(T(i,i, - (1.0 - dt * A(i,0) ) ));\n                /*\n                 matList.push_back(T(i, i, - dt * ( 1.0/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 1.0/state_vars.dVec(n)  ) ));*/\n                 /*\n                if ((n == 0) && atBoundIndicators(1) > 0 ) {\n                 matList.push_back(T(i, i,  dt * ( firstCoefE/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n),  dt * ( - firstCoefE/state_vars.dVec(n)  ) ));\n                }*/\n                /* Uncomment this section if you want second derivatives = constant  */\n                //matList.push_back(T(i,i, - (1.0 - dt * A(i,0) )  ));   \n                /*\n                matList.push_back(T(i, i, - dt * (  secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                /*\n                matList.push_back(T(i, i, - dt * (  1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 2 *  1.0 / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                */\n            } else if ( std::abs(state_vars.stateMat(i,n) - state_vars.lowerLims(n)) < state_vars.dVec(n)/2.0 ) { //lower boundary\n                \n                atBoundIndicators(n) = 1.0;\n                atBound = 1.0;\n\n                ///* Uncomment this section if you want natural boundaries\n                \n                 matList.push_back(T(i, i, - dt * ( - firstCoefE/state_vars.dVec(n) + secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                 matList.push_back(T(i, i + state_vars.increVec(n), - dt * ( firstCoefE/state_vars.dVec(n) - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                 matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                \n                //*/\n                /* Uncomment this section if you want first derivatives = constant\n                 */\n                // matList.push_back(T(i,i, - (1.0 - dt * A(i,0) ) ));\n                // matList.push_back(T(i, i, - dt * ( - 1/state_vars.dVec(n)  ) ) );\n                // matList.push_back(T(i, i + state_vars.increVec(n), - dt * ( 1/state_vars.dVec(n) ) ));\n                 /*\n                if ((n == 0) && atBoundIndicators(1) > 0 ) {\n                 matList.push_back(T(i, i,  dt * ( - firstCoefE/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i + state_vars.increVec(n),  dt * ( firstCoefE/state_vars.dVec(n) ) ));\n                }*/\n                /* Uncomment this section if you want second derivatives = constant  */\n                //matList.push_back(T(i,i, - (1.0 - dt * A(i,0) )/ state_vars.N ));\n                /*\n                matList.push_back(T(i, i, - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i + state_vars.increVec(n), - dt * (  - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                /*\n                    matList.push_back(T(i, i, - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                    matList.push_back(T(i, i + state_vars.increVec(n), - dt * (  - 2 * 1.0 / pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                \n            }\n\n\n\n        }\n        \n             \n        if (atBound < 0 ) {\n          // matList.push_back(T(i,i, (1.0 - dt * A(i,0))  ));\n        }\n        for (int n = (state_vars.N - 1); n >= 0; --n) {\n            \n            //add elements to the vector of triplets for matrix construction\n            if ( atBoundIndicators(n) < 0) {\n                double firstCoefE = B(i,n);\n                double secondCoefE = C(i,n);\n                \n                //first derivative\n                 matList.push_back(T(i,i, - dt * ( -firstCoefE * ( firstCoefE > 0) + firstCoefE * ( firstCoefE < 0) ) / state_vars.dVec(n)  ) );\n                 matList.push_back(T(i,i + state_vars.increVec(n), - dt * firstCoefE * ( firstCoefE > 0) / state_vars.dVec(n) ));\n                 matList.push_back(T(i,i - state_vars.increVec(n), - dt *  - firstCoefE * ( firstCoefE < 0) / state_vars.dVec(n) ));\n                \n                    matList.push_back(T(i, i, - dt * -2 * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i + state_vars.increVec(n), - dt * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i - state_vars.increVec(n), - dt * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                \n            }\n\n        }\n\n\n    }\n    //form matrices\n\n    Le.setFromTriplets(matList.begin(), matList.end());\n\n    //compress\n    Le.makeCompressed(); \n}\n\nvoid linearSysVars::constructMatFK(stateVars & state_vars) {\n    matList.clear();\n    matList.reserve(10 * state_vars.S);\n    atBoundIndicators.resize(state_vars.N);\n    double atBound = -1;\n    double upperBound = -1;\n    //construct matrix\n\n    for (int i = 0; i < state_vars.S; ++i) {\n        //level and time deriv\n        \n        atBound = -1;\n        //check boundaries\n        \n        matList.push_back(T(i,i, (0.0 - dt * A(i,0))  ));\n        \n        for (int n  = (state_vars.N - 1); n >=0; --n ) {\n            \n            atBoundIndicators(n) = -1.0;\n            \n            double firstCoefE = B(i,n);\n            \n            double secondCoefE = C(i,n);\n            \n            //check whether it's at upper or lower boundary\n            if ( std::abs(state_vars.stateMat(i,n) - state_vars.upperLims(n)) < state_vars.dVec(n)/2.0 ) {  //upper boundary\n                atBoundIndicators(n) = 1.0;\n        \n                atBound = 1.0;\n                upperBound = 1.0;\n                /* Uncomment this section if you want natural boundaries */\n                \n                 matList.push_back(T(i, i, - dt * ( firstCoefE/state_vars.dVec(n) + secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - firstCoefE/state_vars.dVec(n) - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                 matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                \n                /* Uncomment this section if you want first derivatives = constant  \n                 matList.push_back(T(i,i, - (1.0 - dt * A(i,0) ) ));\n                /*\n                 matList.push_back(T(i, i, - dt * ( 1.0/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 1.0/state_vars.dVec(n)  ) ));*/\n                 /*\n                if ((n == 0) && atBoundIndicators(1) > 0 ) {\n                 matList.push_back(T(i, i,  dt * ( firstCoefE/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i - state_vars.increVec(n),  dt * ( - firstCoefE/state_vars.dVec(n)  ) ));\n                }*/\n                /* Uncomment this section if you want second derivatives = constant  */\n                //matList.push_back(T(i,i, - (1.0 - dt * A(i,0) )  ));   \n                /*\n                matList.push_back(T(i, i, - dt * (  secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                /*\n                matList.push_back(T(i, i, - dt * (  1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i - state_vars.increVec(n), - dt * ( - 2 *  1.0 / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i - 2*state_vars.increVec(n), - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                */\n            } else if ( std::abs(state_vars.stateMat(i,n) - state_vars.lowerLims(n)) < state_vars.dVec(n)/2.0 ) { //lower boundary\n                \n                atBoundIndicators(n) = 1.0;\n                atBound = 1.0;\n\n                ///* Uncomment this section if you want natural boundaries\n                \n                 matList.push_back(T(i, i, - dt * ( - firstCoefE/state_vars.dVec(n) + secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                 matList.push_back(T(i, i + state_vars.increVec(n), - dt * ( firstCoefE/state_vars.dVec(n) - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                 matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                \n                //*/\n                /* Uncomment this section if you want first derivatives = constant\n                 */\n                // matList.push_back(T(i,i, - (1.0 - dt * A(i,0) ) ));\n                // matList.push_back(T(i, i, - dt * ( - 1/state_vars.dVec(n)  ) ) );\n                // matList.push_back(T(i, i + state_vars.increVec(n), - dt * ( 1/state_vars.dVec(n) ) ));\n                 /*\n                if ((n == 0) && atBoundIndicators(1) > 0 ) {\n                 matList.push_back(T(i, i,  dt * ( - firstCoefE/state_vars.dVec(n)  ) ) );\n                 matList.push_back(T(i, i + state_vars.increVec(n),  dt * ( firstCoefE/state_vars.dVec(n) ) ));\n                }*/\n                /* Uncomment this section if you want second derivatives = constant  */\n                //matList.push_back(T(i,i, - (1.0 - dt * A(i,0) )/ state_vars.N ));\n                /*\n                matList.push_back(T(i, i, - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                matList.push_back(T(i, i + state_vars.increVec(n), - dt * (  - 2 * secondCoefE / pow(state_vars.dVec(n), 2) ) ));\n                matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( secondCoefE / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                /*\n                    matList.push_back(T(i, i, - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                    matList.push_back(T(i, i + state_vars.increVec(n), - dt * (  - 2 * 1.0 / pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i + 2*state_vars.increVec(n), - dt * ( 1.0 / pow(state_vars.dVec(n), 2) ) ) );\n                */\n                \n            }\n\n\n\n        }\n        \n             \n        if (atBound < 0 ) {\n          // matList.push_back(T(i,i, (1.0 - dt * A(i,0))  ));\n        }\n        for (int n = (state_vars.N - 1); n >= 0; --n) {\n            \n            //add elements to the vector of triplets for matrix construction\n            if ( atBoundIndicators(n) < 0) {\n                double firstCoefE = B(i,n);\n                double secondCoefE = C(i,n);\n                \n                //first derivative\n                 matList.push_back(T(i,i, - dt * ( -firstCoefE * ( firstCoefE > 0) + firstCoefE * ( firstCoefE < 0) ) / state_vars.dVec(n)  ) );\n                 matList.push_back(T(i,i + state_vars.increVec(n), - dt * firstCoefE * ( firstCoefE > 0) / state_vars.dVec(n) ));\n                 matList.push_back(T(i,i - state_vars.increVec(n), - dt *  - firstCoefE * ( firstCoefE < 0) / state_vars.dVec(n) ));\n                \n                    matList.push_back(T(i, i, - dt * -2 * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i + state_vars.increVec(n), - dt * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                    matList.push_back(T(i, i - state_vars.increVec(n), - dt * secondCoefE / ( pow(state_vars.dVec(n), 2) ) ));\n                \n            }\n\n        }\n\n\n    }\n    //form matrices\n\n    Le.setFromTriplets(matList.begin(), matList.end());\n\n    //compress\n    Le.makeCompressed(); \n}\n\npy::tuple solveFT(Eigen::Ref<MatrixXdR> preLoadMat, Eigen::Ref<MatrixXdR> A, Eigen::Ref<MatrixXdR> B, Eigen::Ref<MatrixXdR> C,  Eigen::Ref<MatrixXdR> D, Eigen::Ref<MatrixXdR> v0, double dt, int tol)\n{\n    py::tuple data(3);\n    stateVars stateSpace(preLoadMat);\n\n    linearSysVars linearSys_vars(stateSpace, A,B,C,D,dt);\n    linearSys_vars.constructMatFT(stateSpace);\n\n    Eigen::VectorXd rhs; \n\n    rhs = v0.array() + dt * D.array(); // transform v0 into rhs\n    /*********************************************/\n    /* Change RHS to reflect boundary conditions */\n    /*********************************************/\n\n    //construct matrix\n    /* uncomment this section if you want to set the boundary conditions to a constant */\n    // for (int i = 0; i < stateSpace.S; ++i) {\n\n    //     for (int n = (stateSpace.N - 1); n >=0; --n ) {\n            \n    //         //check whether it's at upper or lower boundary\n    //         if ( std::abs(stateSpace.stateMat(i,n) - stateSpace.upperLims(n)) < stateSpace.dVec(n)/2 ) {  //upper boundary\n    //          //   v0(i) = 0.0001;\n    //         } else if ( std::abs( stateSpace.stateMat(i,n) - stateSpace.lowerLims(n)) < stateSpace.dVec(n)/2 ) { //lower boundary\n    //          //v0(i) = 0.0001;            \n    //         }\n    //     }\n    // }\n     \n    /* Initialize Eigen's cg solver */\n \n    Eigen::VectorXd XiEVector;\n    Eigen::LeastSquaresConjugateGradient<SpMat > cgE;\n    // cgE.setMaxIterations(10000);\n    cgE.setTolerance( pow(10,tol) );\n    cgE.compute(linearSys_vars.Le);\n\n    XiEVector = cgE.solveWithGuess(rhs, v0);\n    data[0] = int(cgE.iterations());\n    data[1] = cgE.error();\n    data[2] = XiEVector;\n    return data;    \n\n}\n\npy::tuple solveFK(Eigen::Ref<MatrixXdR> preLoadMat, Eigen::Ref<MatrixXdR> A, Eigen::Ref<MatrixXdR> B, Eigen::Ref<MatrixXdR> C,  Eigen::Ref<MatrixXdR> D, Eigen::Ref<MatrixXdR> v0, int iters)\n{\n    py::tuple data(3);\n    stateVars stateSpace(preLoadMat);\n    double dt(1.0);\n    linearSysVars linearSys_vars(stateSpace, A,B,C,D,dt);\n    linearSys_vars.constructMatFK(stateSpace);\n\n    Eigen::VectorXd rhs;\n    rhs =  dt * D.array(); // transform v0 into rhs\n    /*********************************************/\n    /* Change RHS to reflect boundary conditions */\n    /*********************************************/\n\n    //construct matrix\n    /* uncomment this section if you want to set the boundary conditions to a constant */\n    for (int i = 0; i < stateSpace.S; ++i) {\n\n        for (int n = (stateSpace.N - 1); n >=0; --n ) {\n            \n            //check whether it's at upper or lower boundary\n            if ( std::abs(stateSpace.stateMat(i,n) - stateSpace.upperLims(n)) < stateSpace.dVec(n)/2 ) {  //upper boundary\n             //   v0(i) = 0.0001;\n            } else if ( std::abs( stateSpace.stateMat(i,n) - stateSpace.lowerLims(n)) < stateSpace.dVec(n)/2 ) { //lower boundary\n             //v0(i) = 0.0001;            \n            }\n        }\n    }\n     \n    /* Initialize Eigen's cg solver */\n    Eigen::VectorXd XiEVector;\n    Eigen::LeastSquaresConjugateGradient<SpMat > cgE;\n    cgE.setMaxIterations(iters);\n    cgE.setTolerance( 0.000001 );\n    cgE.compute(linearSys_vars.Le);  // update with Sparse matrix A\n    XiEVector = cgE.solveWithGuess(rhs,v0);  // (rhs, guess)\n    data[0] = int(cgE.iterations());\n    data[1] = cgE.error();\n    data[2] = XiEVector;\n\n    return data;    \n\n}\n/*************************************/\n/* Using pybind11 to interface       */\n/* with python                       */\n/*************************************/\n\nPYBIND11_MODULE(SolveLinSys,m){\n    m.doc() = \"PDE Solver in cpp\";\n\n    m.def(\"solveFT\", &solveFT, py::arg(\"stateSpace\"),\n        py::arg(\"A\"), py::arg(\"B\"), py::arg(\"C\"), py::arg(\"D\"),\n        py::arg(\"v0\"), py::arg(\"dt\"), py::arg(\"tol\"));\n\n    m.def(\"solveFK\", &solveFK, py::arg(\"stateSpace\"),\n        py::arg(\"A\"), py::arg(\"B\"), py::arg(\"C\"), py::arg(\"D\"),\n        py::arg(\"v0\"), py::arg(\"iters\"));\n\n}", "meta": {"hexsha": "11495b555abe8542ab20b6cdbffe02d55ba81fdd", "size": 23405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppcore/src/SolveLinSys.cpp", "max_stars_repo_name": "lphansen/Climate", "max_stars_repo_head_hexsha": "d485888a7203b6caaf1b527dd2f0b28520c2e97d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T17:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T14:52:10.000Z", "max_issues_repo_path": "src/cppcore/src/SolveLinSys.cpp", "max_issues_repo_name": "lphansen/Climate", "max_issues_repo_head_hexsha": "d485888a7203b6caaf1b527dd2f0b28520c2e97d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-14T17:14:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T17:14:29.000Z", "max_forks_repo_path": "src/cppcore/src/SolveLinSys.cpp", "max_forks_repo_name": "lphansen/Climate", "max_forks_repo_head_hexsha": "d485888a7203b6caaf1b527dd2f0b28520c2e97d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-01-31T17:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T04:49:52.000Z", "avg_line_length": 39.6694915254, "max_line_length": 198, "alphanum_fraction": 0.5207861568, "num_tokens": 6646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5915289892492004}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n *          University Press, February 2002.\n *\n */\n\n#include <boost/multi_array.hpp>\n\n#include \"Tudat/Mathematics/Interpolators/linearInterpolator.h\"\n\nnamespace tudat\n{\nnamespace interpolators\n{\n\n//! Compute linear interpolation.\ndouble computeLinearInterpolation( const Eigen::VectorXd& sortedIndependentVariables,\n                                   const Eigen::VectorXd& associatedDependentVariables,\n                                   const double targetIndependentVariableValue )\n{\n    // Declare local variables.\n    // Declare nearest neighbor.\n    int nearestNeighbor;\n    double locationTargetIndependentVariableValueInInterval;\n\n    // Compute nearest neighbor in sorted vector of independent variables.\n    // Result is always to the left of the target independent variable value.\n    nearestNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(\n            sortedIndependentVariables, targetIndependentVariableValue );\n\n    // Compute location of target independent variable value in interval\n    // between nearest neighbors.\n    locationTargetIndependentVariableValueInInterval\n            = ( targetIndependentVariableValue\n              - sortedIndependentVariables[ nearestNeighbor ] )\n             / ( sortedIndependentVariables[ nearestNeighbor + 1 ]\n                 - sortedIndependentVariables[ nearestNeighbor ] );\n\n    // Return the computed value of the dependent variable.\n    return ( associatedDependentVariables[ nearestNeighbor ]\n             * ( 1 - locationTargetIndependentVariableValueInInterval )\n             + associatedDependentVariables[ nearestNeighbor + 1 ]\n             * locationTargetIndependentVariableValueInInterval );\n}\n\n//! Compute linear interpolation.\nEigen::VectorXd computeLinearInterpolation(\n        const std::map < double, Eigen::VectorXd >& sortedIndepedentAndDependentVariables,\n        const double targetIndependentVariableValue )\n{\n    // Declare local variables.\n    // Declare nearest neighbor.\n    int nearestLeftNeighbor;\n\n    // Declare location of target independent variable value in interval.\n    double locationTargetIndependentVariableValueInInterval;\n\n    // Declare map iterators\n    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalLeft;\n    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalRight;\n\n    // Compute nearest neighbor in map of data.\n    // Result is always to the left of the target independent variable value.\n    nearestLeftNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(\n                sortedIndepedentAndDependentVariables, targetIndependentVariableValue );\n\n    // Compute location of target independent variable value in interval\n    // between nearest neighbors.\n    mapIteratorIntervalLeft = sortedIndepedentAndDependentVariables.begin( );\n    advance( mapIteratorIntervalLeft, nearestLeftNeighbor );\n    mapIteratorIntervalRight = sortedIndepedentAndDependentVariables.begin( );\n    advance( mapIteratorIntervalRight, nearestLeftNeighbor + 1 );\n    locationTargetIndependentVariableValueInInterval\n            = ( targetIndependentVariableValue\n              - mapIteratorIntervalLeft->first )\n             / ( mapIteratorIntervalRight->first\n                 - mapIteratorIntervalLeft->first );\n\n    // Return the computed value of the dependent variable.\n    return ( mapIteratorIntervalLeft->second\n             * ( 1 - locationTargetIndependentVariableValueInInterval )\n             + mapIteratorIntervalRight->second\n             * locationTargetIndependentVariableValueInInterval );\n}\n\ntemplate class LinearInterpolator< double, Eigen::VectorXd >;\ntemplate class LinearInterpolator< double, Eigen::Vector6d >;\ntemplate class LinearInterpolator< double, Eigen::MatrixXd >;\n\ntemplate class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 1 > >;\ntemplate class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 6 > >;\ntemplate class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic,  Eigen::Dynamic > >;\n\n} // namespace interpolators\n} // mamespace tudat\n", "meta": {"hexsha": "11106a20abd4d79ec63dfff4ae034220ba3fdfe6", "size": 4765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Interpolators/linearInterpolator.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/Interpolators/linearInterpolator.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/Interpolators/linearInterpolator.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": 43.7155963303, "max_line_length": 107, "alphanum_fraction": 0.7288562434, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5915289891192829}}
{"text": "#include \"Solvers.h\"\r\n#include <Eigen/PardisoSupport>\r\n\r\nint Temporalsolver(string typeSolver, double t_Incre, int maxIter, MatrixXd& T)\r\n{\r\n    // ****************************************************************************************************************************************************\r\n    //                          EULER               //                     Solved by Euler integration. It is the fastest but less stable method.     \r\n    // ****************************************************************************************************************************************************\r\n    if (typeSolver == \"Euler\")\r\n    {\r\n        int size;                         //Number on nodes\r\n        int boundaryNodes;                //Number of nodes with boundary condition\r\n\r\n        SparseMatrix<double> kl_S;        //Vectors and matrices incluiding boundary conditions\r\n        SparseMatrix<double> kr_S;\r\n        VectorXd T0;\r\n        VectorXd QL;\r\n        VectorXd c;\r\n        double time = 0;\r\n\r\n        int count;\r\n        VectorXd T_4;\r\n        VectorXd T_col;\r\n        MatrixXd c_diago;\r\n\r\n        count = 0;\r\n\r\n        do\r\n        {\r\n            ObjectsDefinition(size, boundaryNodes, kl_S, kr_S, T0, QL, c, T.col(count), time);\r\n\r\n            if (count == 0)\r\n            {\r\n                T.col(0) = T0;                   // Initial conditions\r\n            }\r\n\r\n            c = c.cwiseInverse();\r\n            c_diago = c.asDiagonal();\r\n            T_col = T.col(count);\r\n            T_4 = T_col.array().pow(4);\r\n\r\n            T.col(count + 1) = T.col(count) + t_Incre * c_diago * (kl_S.selfadjointView<Upper>() * T.col(count) + QL + kr_S.selfadjointView<Upper>() * T_4);          //Finite differential equation\r\n\r\n            time += t_Incre;\r\n            count++;\r\n            std::cout << \"count\" << count << \"\\n\";\r\n        } while (count + 1 < maxIter);\r\n    }\r\n\r\n    // ****************************************************************************************************************************************************\r\n    //      ADAMS BASHFORTH 2      //      Second order explicit method --- U(n+1) <- U(n) + Dt/2 ( 3 F(n)-F(U(n-1) ) --- x2 times slower than Euler\r\n    // ****************************************************************************************************************************************************\r\n    else if (typeSolver == \"AB2\")\r\n    {\r\n        int size;                         //Number on nodes\r\n        int boundaryNodes;                //Number of nodes with boundary condition\r\n\r\n        SparseMatrix<double> kl_S;        //Vectors and matrices incluiding boundary conditions\r\n        SparseMatrix<double> kr_S;\r\n        VectorXd T0;\r\n        VectorXd QL;\r\n        VectorXd c;\r\n        double time = 0;\r\n\r\n        int count;\r\n        VectorXd T_4_0;\r\n        VectorXd T_col_0;\r\n        VectorXd F_0;\r\n        MatrixXd c_diago;\r\n\r\n        VectorXd T_4_1;\r\n        VectorXd T_col_1;\r\n        VectorXd F_1;\r\n\r\n        count = 0;\r\n\r\n        do\r\n        {\r\n            ObjectsDefinition(size, boundaryNodes, kl_S, kr_S, T0, QL, c, T.col(count), time);\r\n\r\n            c = c.cwiseInverse(); \r\n            c_diago = c.asDiagonal();\r\n\r\n            if (count == 0)\r\n            {\r\n                T.col(0) = T0;                             // Initial conditions\r\n            }\r\n\r\n            //count\r\n            T_col_0 = T.col(count);\r\n            T_4_0 = T_col_0.array().pow(4);\r\n            F_0 = c_diago * (kl_S.selfadjointView<Upper>() * T.col(count) + QL + kr_S.selfadjointView<Upper>() * T_4_0);\r\n\r\n            if (count == 0)\r\n            {\r\n                T.col(1) = T0 + t_Incre * F_0;             //Aproximation of second temperature term with Euler\r\n            }\r\n\r\n            //count + 1\r\n            T_col_1 = T.col(count + 1);\r\n            T_4_1 = T_col_1.array().pow(4);\r\n            F_1 = c_diago * (kl_S.selfadjointView<Upper>() * T.col(count + 1) + QL + kr_S.selfadjointView<Upper>() * T_4_1);\r\n\r\n            T.col(count + 2) = T.col(count + 1) + t_Incre * (3. / 2. * F_1 - 1. / 2. * F_0);          //Finite differences equation\r\n\r\n            time += t_Incre;\r\n            count++;\r\n            std::cout << \"count\" << count << \"\\n\";\r\n        } while (count + 2 < maxIter);\r\n\r\n    }\r\n\r\n    // ****************************************************************************************************************************************************\r\n    //                                            RUNGE KUTTA 4         // Fourth order explicit method. x4 times slower than Euler\r\n    // ****************************************************************************************************************************************************\r\n    else if (typeSolver == \"RK4\")\r\n    {\r\n\r\n        int size;                         //Number on nodes\r\n        int boundaryNodes;                //Number of nodes with boundary condition\r\n\r\n        SparseMatrix<double> kl_S;        //Vectors and matrices incluiding boundary conditions\r\n        SparseMatrix<double> kr_S;\r\n        VectorXd T0;\r\n        VectorXd QL;\r\n        VectorXd c;\r\n        double time = 0;\r\n\r\n        int count;\r\n        VectorXd T_4;\r\n        VectorXd T_col;\r\n        MatrixXd c_diago;\r\n\r\n        VectorXd k1, k2, k3, k4;\r\n\r\n        count = 0;\r\n\r\n        do\r\n        {\r\n            ObjectsDefinition(size, boundaryNodes, kl_S, kr_S, T0, QL, c, T.col(count), time);\r\n\r\n            if (count == 0)\r\n            {\r\n                T.col(0) = T0;                   // Initial conditions\r\n            }\r\n\r\n            c = c.cwiseInverse();\r\n            c_diago = c.asDiagonal();\r\n\r\n            // k1\r\n            T_col = T.col(count);\r\n            T_4 = T_col.array().pow(4);\r\n            k1 = c_diago * (kl_S.selfadjointView<Upper>() * T_col + QL + kr_S.selfadjointView<Upper>() * T_4);\r\n\r\n            // k2\r\n            T_col = T.col(count) + t_Incre / 2 * k1;\r\n            T_4 = T_col.array().pow(4);\r\n            k2 = c_diago * (kl_S.selfadjointView<Upper>() * T_col + QL + kr_S.selfadjointView<Upper>() * T_4);\r\n\r\n            // k3\r\n            T_col = T.col(count) + t_Incre / 2 * k2;\r\n            T_4 = T_col.array().pow(4);\r\n            k3 = c_diago * (kl_S.selfadjointView<Upper>() * T_col + QL + kr_S.selfadjointView<Upper>() * T_4);\r\n\r\n            // k4\r\n            T_col = T.col(count) + t_Incre * k3;\r\n            T_4 = T_col.array().pow(4);\r\n            k4 = c_diago * (kl_S.selfadjointView<Upper>() * T_col + QL + kr_S.selfadjointView<Upper>() * T_4);\r\n\r\n            T.col(count + 1) = T.col(count) + 1. / 6. * t_Incre * (k1 + 2 * k2 + 2 * k3 + k4);          //Finite differential equation\r\n\r\n            time += t_Incre;\r\n            count++;\r\n            std::cout << \"count\" << count << \"\\n\";\r\n        } while (count + 1 < maxIter);\r\n    }\r\n\r\n\r\n    else if (typeSolver == \"CN\")\r\n    {\r\n        int size;                         //Number on nodes\r\n        int boundaryNodes;                //Number of nodes with boundary condition\r\n\r\n        SparseMatrix<double> kl_S;          //Vectors and matrices incluiding boundary conditions\r\n        SparseMatrix<double> kr_S;\r\n        VectorXd T0;\r\n        VectorXd QL;\r\n        VectorXd c;\r\n        double time = 0;\r\n\r\n        SparseMatrix<double> kle_S;\r\n        SparseMatrix<double> kre_S;\r\n        VectorXd QLe;\r\n\r\n        int count;\r\n        VectorXd T_4;\r\n        VectorXd T_col;\r\n        SparseMatrix<double> c_diago;\r\n\r\n        count = 0;\r\n\r\n        do\r\n        {\r\n            ObjectsDefinition(size, boundaryNodes, kl_S, kr_S, T0, QL, c, T.col(count), time);\r\n\r\n            if (count == 0)\r\n            {\r\n                T.col(0) = T0;                    //Initial conditions\r\n            }\r\n\r\n            size = T0.size();\r\n\r\n            \r\n            SparseMatrix<double> AuxS;\r\n            AuxS = kl_S.selfadjointView<Upper>();\r\n            kl_S = AuxS;\r\n            AuxS = kr_S.selfadjointView<Upper>();\r\n            kr_S = AuxS;\r\n     \r\n            \r\n            MatrixXd Aux;\r\n            c = c.cwiseInverse();\r\n            Aux = c.asDiagonal();\r\n            c_diago = Aux.sparseView();\r\n            \r\n\r\n            // QLe\r\n            T_col = T.col(count); \r\n            T_4 = T_col.array().pow(4);\r\n            QLe = t_Incre / 2. * c_diago * (kl_S * T_col + 2 * QL + kr_S * T_4) + T_col;\r\n\r\n           \r\n            //kle\r\n            SparseMatrix<double> I(size, size);\r\n            I.setIdentity();\r\n            kle_S = t_Incre / 2. * c_diago * kl_S - I;\r\n            \r\n\r\n            // kre\r\n            kre_S = t_Incre / 2. * c_diago * kr_S;\r\n\r\n            StableStationarySolverInternal(kle_S, kre_S, QLe, T_col);\r\n            time += t_Incre;\r\n            count++;\r\n\r\n            T.col(count) = T_col;\r\n\r\n        } while (count + 1 < maxIter);\r\n\r\n    }\r\n\r\n    return 0;\r\n}", "meta": {"hexsha": "9a1bbda802ecb8710c25faa9a9d0e765f031fefa", "size": 8796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Temporalsolver.cpp", "max_stars_repo_name": "AdrianAA00/Thermic-Control-Solvers", "max_stars_repo_head_hexsha": "537ba1cb8ace5603b058f13fc2dac8973c71277d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Temporalsolver.cpp", "max_issues_repo_name": "AdrianAA00/Thermic-Control-Solvers", "max_issues_repo_head_hexsha": "537ba1cb8ace5603b058f13fc2dac8973c71277d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Temporalsolver.cpp", "max_forks_repo_name": "AdrianAA00/Thermic-Control-Solvers", "max_forks_repo_head_hexsha": "537ba1cb8ace5603b058f13fc2dac8973c71277d", "max_forks_repo_licenses": ["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.766798419, "max_line_length": 197, "alphanum_fraction": 0.4092769441, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5914558283138716}}
{"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_MATRIX_PROD_\r\n#define _MKL_BOOST_UBLAS_MATRIX_PROD_\r\n\r\n#ifdef NDEBUG\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/matrix.hpp>\r\n\r\n#include \"mkl_boost_ublas_gemm.hpp\"\r\n\r\nnamespace boost { namespace numeric { namespace ublas {\r\n\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, m2 )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), m2 )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), m2 )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), m2 )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix<T,F,A> &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasNoTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, trans(m2) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), trans(m2) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), trans(m2) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), trans(m2) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, trans(conj(m2)) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), trans(conj(m2)) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), trans(conj(m2)) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), trans(conj(m2)) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( m1, conj(trans(m2)) )\r\n    prod(const matrix<T,F,A> &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasNoTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(m1), conj(trans(m2)) )\r\n    prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( trans(conj(m1)), conj(trans(m2)) )\r\n    prod(const matrix_unary2<matrix_unary1<matrix<T,F,A>,scalar_conj<T> > const ,scalar_identity<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n    template<class T, class F, class A>\r\n    MKL_BOOST_UBLAS_INLINE\r\n    matrix<T,F,A>    // prod( conj(trans(m1)), conj(trans(m2)) )\r\n    prod(const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m1,\r\n         const matrix_unary1<matrix_unary2<matrix<T,F,A>,scalar_identity<T> >,scalar_conj<T> > &m2)\r\n    {\r\n        matrix<T,F,A> temporary(m1.size1(),m2.size2());\r\n        mkl::gemm(CblasConjTrans, CblasConjTrans, m1, m2, temporary);\r\n        return temporary;\r\n    }\r\n\r\n}}}\r\n#endif  // BOOST_VERSION\r\n#endif  // NDEBUG\r\n#endif  // _MKL_BOOST_UBLAS_MATRIX_PROD_\r\n", "meta": {"hexsha": "455d454b7f143687c47110874a1c1839fe3fd66f", "size": 9294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "components/parallel-libs/boost/SOURCES/mkl_boost_ublas_matrix_prod.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_matrix_prod.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_matrix_prod.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": 44.6826923077, "max_line_length": 107, "alphanum_fraction": 0.619969873, "num_tokens": 2718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5914558169431489}}
{"text": "#include \"ScatterDraw.h\"\n#include <Eigen/Eigen.h>\n\nnamespace Upp {\nusing namespace Eigen;\n\nstruct Equation_functor : NonLinearOptimizationFunctor<double> {\n\tDataSource *series;\n\tExplicitEquation *fSource;\n\tEquation_functor() {}\n\t\n\tint operator()(const VectorXd &b, VectorXd &fvec) const {\n\t\tASSERT(b.size() == unknowns);\n\t\tASSERT(fvec.size() == datasetLen);\n\t\tfor (int i = 0; i < unknowns; ++i)\n\t\t\t(*fSource).SetCoeffVal(i, b(i));\n\t\tfor(int64 i = 0; i < datasetLen; i++) \n\t\t\tfvec(ptrdiff_t(i)) = (*fSource).f((*series).x(i)) - (*series).y(i);\n\t\treturn 0;\n\t}\n};\n\nvoid ExplicitEquation::SetNumCoeff(int num) {\n\tcoeff.SetCount(num); \n\tfor (int i = 0; i < num; ++i)\n\t\tcoeff[i] = 0;\n}\n\nExplicitEquation::FitError ExplicitEquation::Fit(DataSource &serie, double &r2) {\n\tr2 = Null;\n\t\n\tif (serie.IsExplicit() || serie.IsParam())\n\t\treturn InadequateDataSource;\n\t\n\tif (serie.GetCount() < coeff.GetCount())\n\t\treturn SmallDataSource;\n\t\n\tptrdiff_t numUnknowns = coeff.GetCount();\n\t\n\tVectorXd x(numUnknowns);\n\tfor (int i = 0; i < numUnknowns; ++i)\n\t\tx(i) = coeff[i];\n\t\n\tEquation_functor functor;\t\n\tfunctor.series = &serie;\n\tfunctor.fSource = this;\n\tfunctor.unknowns = numUnknowns;\n\tfunctor.datasetLen = Eigen::Index(serie.GetCount());\n\t\n\tNumericalDiff<Equation_functor> numDiff(functor);\n\tLevenbergMarquardt<NumericalDiff<Equation_functor> > lm(numDiff);\n// \tftol is a nonnegative input variable that measures the relative error desired in the sum of squares \n\tlm.parameters.ftol = 1.E4*NumTraits<double>::epsilon();\n//  xtol is a nonnegative input variable that measures the relative error desired in the approximate solution\n\tlm.parameters.xtol = 1.E4*NumTraits<double>::epsilon();\n\tlm.parameters.maxfev = maxFitFunctionEvaluations;\n\tint ret = lm.minimize(x);\n\tif (ret == LevenbergMarquardtSpace::ImproperInputParameters)\n\t\treturn ExplicitEquation::ImproperInputParameters;\n\telse if (ret == LevenbergMarquardtSpace::TooManyFunctionEvaluation)\n\t\treturn TooManyFunctionEvaluation;\n\n\tr2 = R2Y(serie);\n\n\treturn NoError;\n}\n\ndouble ExplicitEquation::R2Y(DataSource &serie, double mean) {\n\tif (!IsNum(mean))\n\t\tmean = serie.AvgY();\n\tdouble sse = 0, sst = 0;\n\tfor (int64 i = 0; i < serie.GetCount(); ++i) {\n\t\tdouble y = serie.y(i);\n\t\tif (!!IsNum(y)) {\n\t\t\tdouble err = y - f(serie.x(i));\n\t\t\tsse += err*err;\n\t\t\tdouble d = y - mean;\n\t\t\tsst += d*d;\n\t\t}\n\t}\n\tif (sst < 1E-50 || sse > sst)\n\t\treturn 0;\n\treturn 1 - sse/sst;\n}\n\nint ExplicitEquation::maxFitFunctionEvaluations = 2000;\n\n\ndouble PolynomialEquation::f(double x) {\n\tif (x < 0)\n\t\treturn Null;\n\tdouble y = 0;\n\tfor (int i = 0; i < coeff.GetCount(); ++i) \n\t\ty += coeff[i]*pow(x, i);\n\treturn y;\n}\n\nString PolynomialEquation::GetEquation(int numDigits) {\n\tif (coeff.IsEmpty())\n\t\treturn String();\n\tString ret = FormatCoeff(0, numDigits);\n\tif (coeff.GetCount() == 1)\n\t\treturn ret;\n\tret += Format(\" + %s*x\", FormatCoeff(1, numDigits));\n\tfor (int i = 2; i < coeff.GetCount(); ++i) \n\t\tret += Format(\" + %s*x^%s\", FormatCoeff(i, numDigits), FormatInt(i));\n\tret.Replace(\"+ -\", \"- \");\n\treturn ret;\n}\n\t\ndouble FourierEquation::f(double x) {\n\tdouble y = coeff[0];\n\tdouble w = coeff[1];\n\tfor (int i = 2; i < coeff.GetCount(); i += 2) {\n\t\tint n = 1 + (i - 2)/2;\n\t\ty += coeff[i]*cos(n*w*x) + coeff[i+1]*sin(n*w*x);\n\t}\n\treturn y;\n}\n\nString FourierEquation::GetEquation(int numDigits) {\n\tif (coeff.GetCount() < 4)\n\t\treturn String();\n\tString ret = FormatCoeff(0, numDigits);\n\t\n\tfor (int i = 2; i < coeff.GetCount(); i += 2) {\n\t\tint n = 1 + (i - 2)/2;\n\t\tString nwx = Format(\"%d*%s*x\", n, FormatCoeff(1, numDigits));\n\t\tret += Format(\" + %s*cos(%s)\", FormatCoeff(i, numDigits), nwx);\n\t\tret += Format(\" + %s*sin(%s)\", FormatCoeff(i + 1, numDigits), nwx);\n\t}\n\tret.Replace(\"+ -\", \"- \");\n\treturn ret;\n}\n\nstatic inline double DegToRad(double deg) {return deg*M_PI/180.;}\nstatic inline double RadToDeg(double rad) {return rad*180./M_PI;}\n\nvoid EvalExpr::EvalThrowError(CParserPP &p, const char *s) {\n\tCParserPP::Pos pos = p.GetPos();\n\tCParserPP::Error err(Format(\"(%d): \", pos.GetColumn()) + String(s));\n\tthrow err;\n}\n\ndoubleUnit usqrt(doubleUnit val) {\n\tval.Sqrt();\n\treturn val;\n}\n\ndoubleUnit ufabs(doubleUnit val) {\n\tval.val = fabs(val.val);\n\treturn val;\n}\n\ndoubleUnit uceil(doubleUnit val) {\n\tval.val = ceil(val.val);\n\treturn val;\n}\n\ndoubleUnit ufloor(doubleUnit val) {\n\tval.val = floor(val.val);\n\treturn val;\n}\n\ndoubleUnit uround(doubleUnit val) {\n\tval.val = round(val.val);\n\treturn val;\n}\n\ndoubleUnit usin(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = sin(val.val);\n\treturn val;\n}\n\ndoubleUnit ucos(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = cos(val.val);\n\treturn val;\n}\n\ndoubleUnit utan(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = tan(val.val);\n\treturn val;\n}\n\ndoubleUnit uasin(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = asin(val.val);\n\treturn val;\n}\n\ndoubleUnit uacos(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = acos(val.val);\n\treturn val;\n}\n\ndoubleUnit uatan(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = atan(val.val);\n\treturn val;\n}\n\ndoubleUnit usinh(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = sinh(val.val);\n\treturn val;\n}\n\ndoubleUnit ucosh(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = cosh(val.val);\n\treturn val;\n}\n\ndoubleUnit utanh(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = tanh(val.val);\n\treturn val;\n}\n\ndoubleUnit uexp(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = exp(val.val);\n\treturn val;\n}\n\ndoubleUnit uDegToRad(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = DegToRad(val.val);\n\treturn val;\n}\n\ndoubleUnit uRadToDeg(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = RadToDeg(val.val);\n\treturn val;\n}\n\ndoubleUnit ulog(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = log(val.val);\n\treturn val;\n}\n\ndoubleUnit ulog10(doubleUnit val) {\n\tif (!val.unit.IsAdim())\n\t\treturn Null;\n\tval.val = log10(val.val);\n\treturn val;\n}\n\nEvalExpr::EvalExpr() {\n\tnoCase = false;\n\terrorIfUndefined = false;\n\tallowString = false;\n\t\n\tconstants.Add(\"pi\", doubleUnit(M_PI));\n\tconstants.Add(\"e\", doubleUnit(M_E));\n\t\n\tfunctions.Add(\"abs\", ufabs);\n\tfunctions.Add(\"ceil\", uceil);\n\tfunctions.Add(\"floor\", ufloor);\n\tfunctions.Add(\"round\", uround);\n\tfunctions.Add(\"sqrt\", usqrt);\n\tfunctions.Add(\"sin\", usin);\n\tfunctions.Add(\"cos\", ucos);\n\tfunctions.Add(\"tan\", utan);\n\tfunctions.Add(\"asin\", uasin);\n\tfunctions.Add(\"acos\", uacos);\n\tfunctions.Add(\"atan\", uatan);\n\tfunctions.Add(\"sinh\", usinh);\n\tfunctions.Add(\"cosh\", ucosh);\n\tfunctions.Add(\"tanh\", utanh);\n\tfunctions.Add(\"log\", ulog);\n\tfunctions.Add(\"log10\", ulog10);\n\tfunctions.Add(\"exp\", uexp);\n\tfunctions.Add(\"degToRad\", uDegToRad);\n\tfunctions.Add(\"radToDeg\", uRadToDeg);\n}\n\ndoubleUnit EvalExpr::Term(CParserPP& p) {\n\tp.Char('+');\n\tbool isneg = p.Char('-');\n\tif (p.IsId()) {\n\t\tString strId = p.ReadIdPP();\n\t\tif(doubleUnit (*function)(doubleUnit) = functions.Get(strId, 0)) {\n\t\t\tp.PassChar('(');\n\t\t\tdoubleUnit x(Exp(p));\n\t\t\tp.PassChar(')');\n\t\t\tdoubleUnit ret(function(x));\n\t\t\tif (IsNull(ret))\n\t\t\t\tEvalThrowError(p, Format(t_(\"Error in %s(%f)\"), strId, x.val));\t\n\t\t\tif (isneg)\n\t\t\t\tret.Neg();\n\t\t\treturn ret;\n\t\t}\t\n\t\tString strIdSearch;\n\t\tif (noCase)\n\t\t\tstrIdSearch = ToLower(strId);\n\t\telse\n\t\t\tstrIdSearch = strId;\n\t\tdoubleUnit ret(constants.Get(strIdSearch, Null));\n\t\tif (IsNull(ret)) {\n\t\t\tint id = FindVariable(strIdSearch);\n\t\t\tif (id >= 0)\n\t\t\t\tret = variables[id];\n\t\t\telse {\n\t\t\t\tif (errorIfUndefined) {\n\t\t\t\t\tlastError = Format(t_(\"Unknown identifier '%s'\"), strId);\n\t\t\t\t\treturn Null;\n\t\t\t\t}\n\t\t\t\t\t//EvalThrowError(p, Format(t_(\"Unknown identifier '%s'\"), strId));\t\n\t\t\t\tlastVariableSetId = variables.FindAdd(strIdSearch, 0);\n\t\t\t\tret = variables[lastVariableSetId];\n\t\t\t}\n\t\t}\n\t\tif (isneg)\n\t\t\tret.Neg();\n\t\treturn ret;\n\t} else if (p.Char('(')) {\n\t\tdoubleUnit x(Exp(p));\n\t\tp.PassChar(')');\n\t\tif (isneg)\n\t\t\tx.Neg();\n\t\treturn x;\n\t} else {\n\t\tif (p.IsChar2('.', '.'))\n\t\t\tp.ThrowError(\"missing number\");\n\t\tdoubleUnit x(p.ReadDouble());\n\t\tif (isneg)\n\t\t\tx.Neg();\n\t\treturn x;\n\t}\n}\n\ndoubleUnit EvalExpr::Pow(CParserPP& p) {\n\tdoubleUnit x(Term(p));\n\tfor(;;) \n\t\tif(p.Char('^')) {\n\t\t\t//if (x.val < 0)\n\t\t\t//\tEvalThrowError(p, t_(\"Complex number\"));\n\t\t\tx.Exp(Term(p));\n\t\t} else\n\t\t\treturn x;\n}\n\ndoubleUnit EvalExpr::Mul(CParserPP& p) {\n\tdoubleUnit x(Pow(p));\n\tfor(;;) \n\t\tif(p.Char('*'))\n\t\t\tx.Mult(Pow(p));\n\t\telse if (p.Char2('|', '|')) \n\t\t\tx.ResParallel(Pow(p));\n\t\telse if(memcmp(p.GetPtr(), \"·\", strlen(\"·\")) == 0) {\n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tpos.ptr += strlen(\"·\");\n\t\t\tp.SetPos(pos);\n\t\t\tp.Spaces();\n\t\t\tx.Mult(Pow(p));\n\t\t} else if(p.Char('/')) {\n\t\t\tx.Div(Pow(p));\n\t\t} else if(memcmp(p.GetPtr(), \"º\", strlen(\"º\")) == 0) { \n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tpos.ptr += strlen(\"º\");\n\t\t\tp.SetPos(pos);\n\t\t\tp.Spaces();\n\t\t\tx.Mult(doubleUnit(M_PI/180.));\n\t\t} else\n\t\t\treturn x;\n}\n\ndoubleUnit EvalExpr::Exp(CParserPP& p) {\n\tdoubleUnit x(Mul(p));\n\tfor(;;) \n\t\tif(p.Char('+'))\n\t\t\tx.Sum(Mul(p));\n\t\telse if(p.Char('-'))\n\t\t\tx.Sub(Mul(p));\n\t\telse if(p.Char(':')) {\n\t\t\tx.Mult(doubleUnit(60));\n\t\t\tx.Sum(Mul(p));\n\t\t} else\n\t\t\treturn x;\n}\n\ndoubleUnit EvalExpr::AssignVariable(String var, String expr) {\n\tdoubleUnit ret;\n\tif (noCase)\n\t\tvar = ToLower(var);\n\tint idalloc = FindAddVariable(var);\n\ttry {\n\t\tp.Set(expr);\n\t\t\n\t\tret.Set(Exp(p));\n\t\tif (!IsNull(ret)) {\n\t\t\tSetVariable(idalloc, ret);\n\t\t\treturn ret;\n\t\t} else {\n\t\t\tif (allowString) {\n\t\t\t\tret.sval = expr;\n\t\t\t\tSetVariable(idalloc, ret);\n\t\t\t\treturn ret;\t\n\t\t\t}\n\t\t\treturn Null;\n\t\t}\n\t} catch(CParserPP::Error e) {\n\t\tif (allowString) {\n\t\t\tret.sval = expr;\n\t\t\tSetVariable(idalloc, ret);\n\t\t\treturn ret;\t\n\t\t}\n\t\tlastError = e;\n\t\treturn Null;\n\t} catch(Exc e) {\n\t\tlastError = e;\n\t\treturn Null;\n\t} catch(...) {\n\t\tlastError = \"Unknown error\";\n\t\treturn Null;\n\t} \n}\n\nvoid EvalExpr::RenameVariable(String varname, String newvarname) {\n\tif (noCase) {\n\t\tvarname = ToLower(varname);\n\t\tnewvarname = ToLower(newvarname);\n\t}\n\ttry {\n\t\tint id = variables.Find(varname);\n\t\tif (id >= 0)\n\t\t\tvariables.SetKey(id, newvarname);\n\t} catch(CParserPP::Error e) {\n\t\tlastError = e;\n\t} catch(Exc e) {\n\t\tlastError = e;\n\t}\t\n}\n\ndoubleUnit EvalExpr::AssignVariable(String var, double d) {\n\tif (noCase)\n\t\tvar = ToLower(var);\n\ttry {\n\t\tdoubleUnit ret(d);\n\t\tSetVariable(var, ret);\n\t\treturn ret;\n\t} catch(CParserPP::Error e) {\n\t\tlastError = e;\n\t\treturn Null;\n\t} catch(Exc e) {\n\t\tlastError = e;\n\t\treturn Null;\n\t} catch(...) {\n\t\tlastError = \"Unknown error\";\n\t\treturn Null;\n\t} \n}\n\t\t\ndoubleUnit EvalExpr::Eval(String line) {\n\tline = TrimBoth(line);\n\tif (line.IsEmpty())\n\t\treturn Null;\n\t\n\tp.Set(line);\n\ttry {\n\t\tif(p.IsId()) {\n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tString var = p.ReadIdPP();\n\t\t\tif(p.Char('=')) {\n\t\t\t\tif (noCase)\n\t\t\t\t\tvar = ToLower(var);\n\t\t\t\tdoubleUnit ret(Exp(p));\n\t\t\t\tSetVariable(var, ret);\n\t\t\t\treturn ret;\n\t\t\t} else {\n\t\t\t\tp.SetPos(pos);\n\t\t\t\treturn Exp(p);\n\t\t\t}\n\t\t} else\n\t\t\treturn Exp(p);\n\t} catch(CParserPP::Error e) {\n\t\tlastError = e;\n\t\treturn Null;\n\t} catch(Exc e) {\n\t\tlastError = e;\n\t\treturn Null;\n\t}\n}\n\nString EvalExpr::TermStr(CParserPP& p, int numDigits) {\n\tif(p.IsId()) {\n\t\tString strId = p.ReadIdPP();\n\t\tif(functions.Find(strId) >= 0) {\n\t\t\tp.PassChar('(');\n\t\t\tString x = ExpStr(p, numDigits);\n\t\t\tp.PassChar(')');\n\t\t\treturn strId + \"(\" + x + \")\";\n\t\t}\n\t\tif (noCase)\n\t\t\tstrId = ToLower(strId);\n\t\tif (IsNull(numDigits)) {\n\t\t\tif (constants.Find(strId) < 0)\n\t\t\t\tlastVariableSetId = variables.FindAdd(strId, 0);\n\t\t\treturn strId;\n\t\t} else {\n\t\t\tif (constants.Find(strId) >= 0)\n\t\t\t\treturn strId;\n\t\t\telse {\n\t\t\t\tlastVariableSetId = variables.FindAdd(strId, 0);\n\t\t\t\treturn FormatDoubleFix(variables[lastVariableSetId].val, numDigits);\n\t\t\t}\n\t\t}\n\t}\n\tif(p.Char('(')) {\n\t\tString x = ExpStr(p, numDigits);\n\t\tp.PassChar(')');\n\t\treturn \"(\" + x + \")\";\n\t}\n\treturn FormatDoubleFix(p.ReadDouble(), IsNull(numDigits) ? 3 : numDigits);\n}\n\nString EvalExpr::PowStr(CParserPP& p, int numDigits) {\n\tString x = TermStr(p, numDigits);\n\tfor(;;)\n\t\tif(p.Char('^'))\n\t\t\tx = x + \"^\" + TermStr(p, numDigits);\n\t\telse\n\t\t\treturn x;\n}\n\nString EvalExpr::MulStr(CParserPP& p, int numDigits) {\n\tString x = PowStr(p, numDigits);\n\tfor(;;)\n\t\tif(p.Char('*'))\n\t\t\tx = x + \"*\" + MulStr(p, numDigits);\n\t\telse if(p.Char('/')) \n\t\t\tx = x + \"/\" + PowStr(p, numDigits);\n\t\telse\n\t\t\treturn x;\n}\n\nString EvalExpr::ExpStr(CParserPP& p, int numDigits) {\n\tString x = MulStr(p, numDigits);\n\tfor(;;) \n\t\tif(p.Char('+'))\n\t\t\tx = x + \" + \" + MulStr(p, numDigits);\n\t\telse if(p.Char('-'))\n\t\t\tx = x + \" - \" + MulStr(p, numDigits);\n\t\telse if(p.Char(':'))\n\t\t\tx = x + \":\" + MulStr(p, numDigits);\n\t\telse {\n\t\t\tx.Replace(\"+ -\", \"- \");\n\t\t\treturn x;\n\t}\n}\n\nString EvalExpr::EvalStr(String line, int numDigits) {\n\tline = TrimBoth(line);\n\tif (line.IsEmpty())\n\t\treturn Null;\n\t\n\tCParserPP p(line);\n\ttry {\n\t\tif(p.IsId()) {\n\t\t\tCParserPP::Pos pos = p.GetPos();\n\t\t\tString var = p.ReadIdPP();\n\t\t\tif(p.Char('=')) {\n\t\t\t\tString ret = ExpStr(p, numDigits);\n\t\t\t\tlastVariableSetId = variables.FindAdd(var, 0);\n\t\t\t\treturn var + \" = \" + ret;\n\t\t\t} else {\n\t\t\t\tp.SetPos(pos);\n\t\t\t\treturn ExpStr(p, numDigits);\n\t\t\t}\n\t\t} else\n\t\t\treturn ExpStr(p, numDigits);\n\t} catch(CParserPP::Error e) {\n\t\tlastError = Format(t_(\"Error evaluating '%s': %s\"), line, e);\n\t\treturn Null;\n\t} catch(Exc e) {\n\t\tlastError = Format(t_(\"Error: %s\"), e);\n\t\treturn Null;\n\t} catch(String e) {\n\t\tlastError = Format(t_(\"Error: %s\"), e);\n\t\treturn Null;\n\t} catch(...) {\n\t\tlastError = t_(\"Unknown error\");\n\t\treturn Null;\n\t}\n}\n\nvoid EvalExpr::ClearVariables() {\n\tvariables.Clear();\n}\n\nVector<int> EvalExpr::FindPattern(String yes, String no) const {\n\tVector<int> ret;\n\tyes = ToLower(yes);\n\tno = ToLower(no);\n\tfor (int i = 0; i < variables.GetCount(); ++i) {\t\n\t\tString name = ToLower(variables.GetKey(i));\n\t\tif (PatternMatch(yes, name) && !PatternMatch(no, name))\n\t\t\tret << i;\t\n\t}\n\treturn ret;\n}\n\nVector<int> EvalExpr::FindPattern(String yes, String no, String yes2) const {\n\tVector<int> ret = FindPattern(yes, no);\n\tif (ret.IsEmpty())\n\t\tret = FindPattern(yes2, no);\n\treturn ret;\n}\n\nExplicitEquation::FitError SplineEquation::Fit(DataSource &data, double &r2) {\t\n\tVector<Pointf> seriesRaw;\n\tfor (int64 i = 0; i < data.GetCount(); ++i) {\t\t// Remove Nulls\t\n\t\tif (!!IsNum(data.x(i)) && !!IsNum(data.y(i)))\n\t\t\tseriesRaw << Pointf(data.x(i), data.y(i));\n\t}\n\n\tif(seriesRaw.IsEmpty())\n        return SmallDataSource;\n      \n    r2 = 1;\n    \n\tPointfLess less;\n\tSort(seriesRaw, less);\t\t\t\t\t\t\t\t// Sort\n\n\tVector<double> x, y;\n\tx.Reserve(seriesRaw.GetCount());\n\ty.Reserve(seriesRaw.GetCount());\n\tx << seriesRaw[0].x;\n\ty << seriesRaw[0].y;\n\tfor (int i = 1; i < seriesRaw.GetCount(); ++i) {\t// Remove points with duplicate x\n\t\tif (seriesRaw[i].x != seriesRaw[i - 1].x) {\n\t\t\tx << seriesRaw[i].x;\n\t\t\ty << seriesRaw[i].y;\n\t\t}\n\t}\n\t\n\tif (x.GetCount() < 2)\n\t\treturn SmallDataSource;\n\t\t\n\tInit(x, y);\n\t\n\tcoeff.SetCount(1);\n\t\n\treturn NoError;\n}\n\nvoid Spline::Init(const double *x, const double *y, int num) {\n    nscoeff = num - 1;\n    \n    Buffer<double> h(nscoeff);\n    for(int i = 0; i < nscoeff; ++i)\n        h[i] = x[i+1] - x[i];\n\n    Buffer<double> alpha(nscoeff);\n    for(int i = 1; i < nscoeff; ++i)\n        alpha[i] = 3*(y[i+1] - y[i])/h[i] - 3*(y[i] - y[i-1])/h[i-1];\n\n    Buffer<double> c(nscoeff+1), l(nscoeff+1), mu(nscoeff+1), z(nscoeff+1);\n    l[0] = 1;\n    mu[0] = 0;\n    z[0] = 0;\n\n    for(int i = 1; i < nscoeff; ++i) {\n        l[i] = 2*(x[i+1] - x[i-1]) - h[i-1]*mu[i-1];\n        mu[i] = h[i]/l[i];\n        z[i] = (alpha[i] - h[i-1]*z[i-1])/l[i];\n    }\n\n    l[nscoeff] = 1;\n    z[nscoeff] = 0;\n    c[nscoeff] = 0;\n\n\tscoeff.Alloc(nscoeff);\n    for(int i = nscoeff-1; i >= 0; --i) {\n        c[i] = z[i] - mu[i] * c[i+1];\n        scoeff[i].b = (y[i+1] - y[i])/h[i] - h[i]*(c[i+1] + 2*c[i])/3;\n        scoeff[i].d = (c[i+1] - c[i])/3/h[i];\n    }\n\n    for(int i = 0; i < nscoeff; ++i) {\n        scoeff[i].x = x[i];\n        scoeff[i].a = y[i];\n        scoeff[i].c = c[i];\n    }\n    xlast = x[num-1];\n}\n\nint Spline::GetPieceIndex(double x) const {\n\tASSERT(nscoeff > 0);\n    int j;\n    for (j = 0; j < nscoeff; j++) {\n        if (scoeff[j].x > x) {\n            if (j == 0)\n                j = 1;\n            break;\n        }\n    }\n    return --j;\n}\n\ndouble Spline::f(double x) const {\n\tint j = GetPieceIndex(x);\n\n    double dx = x - scoeff[j].x;\n    double dx2 = dx*dx;\n    return scoeff[j].a + scoeff[j].b*dx + scoeff[j].c*dx*dx + scoeff[j].d*dx*dx2;\n}\n\ndouble Spline::df(double x) const {\n\tint j = GetPieceIndex(x);\n\n    double dx = x - scoeff[j].x;\n    return scoeff[j].b + scoeff[j].c*2.*dx + scoeff[j].d*3.*dx*dx;\n}\n\ndouble Spline::d2f(double x) const {\n\tint j = GetPieceIndex(x);\n\n    double dx = x - scoeff[j].x;\n    return scoeff[j].c*2. + scoeff[j].d*6.*dx;\n}\n\ndouble Spline::Integral0(const Coeff &c, double x) {\n\tdouble x2 = x*x;\n\treturn c.a*x + c.b*x2/2 + c.c*x*x2/3 + c.d*x2*x2/4;\n}\n\ndouble Spline::Integral(double from, double to) const {\n\tint ifrom;\n\tif (!IsNum(from)) {\n\t\tifrom = 0;\n\t\tfrom = scoeff[0].x;\n\t} else\n\t\tifrom = GetPieceIndex(from);\n\tint ito;\n\tif (!IsNum(to)) {\n\t\tito = nscoeff-1;\n\t\tto = xlast;\n\t} else\n\t\tito = GetPieceIndex(to);\n\t\n\tASSERT(ifrom <= ito);\n\tif (ifrom > ito)\n\t\treturn 0;\n\t\t \n\tdouble res = 0;\n\tfor (int i = ifrom; i < ito; ++i) {\n\t\tdouble val = Integral0(scoeff[i], scoeff[i+1].x - scoeff[i].x) - Integral0(scoeff[i], from - scoeff[i].x);\n\t\tres += val;\n\t\tfrom = scoeff[i+1].x;\n\t}\n\tdouble bal =  Integral0(scoeff[ito], to - scoeff[ito].x) - Integral0(scoeff[ito], from - scoeff[ito].x);\n\tres += bal;\n\treturn res;\n}\n\nINITBLOCK {\n\tExplicitEquation::Register<LinearEquation>(\"LinearEquation\");\n\tExplicitEquation::Register<PolynomialEquation2>(\"PolynomialEquation2\");\n\tExplicitEquation::Register<PolynomialEquation3>(\"PolynomialEquation3\");\n\tExplicitEquation::Register<PolynomialEquation4>(\"PolynomialEquation4\");\n\tExplicitEquation::Register<PolynomialEquation5>(\"PolynomialEquation5\");\n\tExplicitEquation::Register<SinEquation>(\"SinEquation\");\n\tExplicitEquation::Register<DampedSinEquation>(\"DampedSinusoidal\");\n\tExplicitEquation::Register<Sin_DampedSinEquation>(\"Sin_DampedSinusoidal\");\n\tExplicitEquation::Register<ExponentialEquation>(\"ExponentialEquation\");\n\tExplicitEquation::Register<RealExponentEquation>(\"RealExponentEquation\");\n\tExplicitEquation::Register<Rational1Equation>(\"Rational1Equation\");\n\tExplicitEquation::Register<FourierEquation1>(\"FourierEquation1\");\n\tExplicitEquation::Register<FourierEquation2>(\"FourierEquation2\");\n\tExplicitEquation::Register<FourierEquation3>(\"FourierEquation3\");\n\tExplicitEquation::Register<FourierEquation4>(\"FourierEquation4\");\n\tExplicitEquation::Register<WeibullEquation>(\"WeibullEquation\");\n\tExplicitEquation::Register<WeibullCumulativeEquation>(\"WeibullCumulativeEquation\");\n\tExplicitEquation::Register<NormalEquation>(\"NormalEquation\");\n}\n\n}", "meta": {"hexsha": "a61ae22e89114cba5e237f3765fc235ca5e5ebf6", "size": 18709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ScatterDraw/Equation.cpp", "max_stars_repo_name": "XOULID/Anboto", "max_stars_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ScatterDraw/Equation.cpp", "max_issues_repo_name": "XOULID/Anboto", "max_issues_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ScatterDraw/Equation.cpp", "max_forks_repo_name": "XOULID/Anboto", "max_forks_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4448621554, "max_line_length": 109, "alphanum_fraction": 0.6234967128, "num_tokens": 5959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5914303261168865}}
{"text": "#ifndef __PROBABILITY_DISTRIBUTIONS__LAPLACE_IMPL_HPP__\n#define __PROBABILITY_DISTRIBUTIONS__LAPLACE_IMPL_HPP__\n\n#include \"laplace.hpp\"\n\n#include \"const_slice.hpp\"\n#include \"slice.hpp\"\n\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <cmath>\n\nnamespace ProbabilityDistributions {\n  template <class D, class W, class T>\n  Laplace<D,W,T>::Laplace(T mu, T lambda):\n    fixed_mu_(false),\n    fixed_lambda_(false) {\n      set_mu(mu);\n      set_lambda(lambda);\n    }\n\n  template <class D, class W, class T>\n  template <class RNG>\n  void Laplace<D,W,T>::sample(MA::Array<D>& samples, size_t n_samples, RNG& rng)\n  const {\n    MA::Size::SizeType size(2);\n    size[0] = n_samples;\n    size[1] = 1;\n    samples.resize(size);\n\n    boost::random::uniform_smallint<int> dist1(0, 1);\n    boost::random::exponential_distribution<T> dist2(lambda_);\n\n    D* ptr = samples.get_pointer();\n\n    for (size_t j = 0; j < n_samples; j++) {\n      if (dist1(rng))\n        ptr[j] = mu_ + dist2(rng);\n      else\n        ptr[j] = mu_ - dist2(rng);\n    }\n  }\n\n  template <class D, class W, class T>\n  T Laplace<D,W,T>::log_likelihood(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight) const {\n    check_data_and_weight(data, weight);\n\n    D const* ptr = data.get_pointer();\n\n    T ll = 0;\n    T lambda_likelihood = std::log(lambda_/2);\n\n    for (size_t j = 0; j < data.total_size(); j++) {\n      T w = weight(j);\n      T s = ptr[j];\n      T local_likelihood = -std::abs(s - mu_) * lambda_;\n      local_likelihood += lambda_likelihood;\n      ll += w * local_likelihood;\n    }\n\n    return ll;\n  }\n\n  template <class D, class W, class T>\n  void Laplace<D,W,T>::MLE(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes) {\n    check_data_and_weight(data, weight);\n    assert(data.size()[0] == indexes.size());\n\n    D const* ptr = data.get_pointer();\n\n    if (!fixed_mu_)\n      set_mu(Distribution<D,W,T>::get_percentile(0.5, data, weight, indexes));\n\n    if (!fixed_lambda_) {\n      T sum_0 = 0, sum_1 = 0;\n      for (size_t j = 0; j < data.total_size(); j++) {\n        T w = weight(j);\n        sum_0 += w;\n        sum_1 += w*std::abs(ptr[j] - mu_);\n      }\n\n      set_lambda(sum_0 / sum_1);\n    }\n  }\n\n  template <class D, class W, class T>\n  void Laplace<D,W,T>::check_data_and_weight(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight) const {\n    assert(data.size().size() == 2);\n    assert(data.size()[0] > 0);\n    assert(data.size()[1] == 1);\n    assert(weight.size().size() == 1);\n    assert(weight.size()[0] == data.size()[0]);\n  }\n};\n\n#endif\n", "meta": {"hexsha": "cfaee712f9c71ca503847aa1b6399219813efc0c", "size": 2664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/laplace_impl.hpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/laplace_impl.hpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/laplace_impl.hpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.64, "max_line_length": 80, "alphanum_fraction": 0.6163663664, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.591407809461646}}
{"text": "#include \"utils.h\"\n\n#include <NTL/GF2EX.h>\n#include <NTL/GF2X.h>\n#include <stdexcept>\n\nusing namespace NTL;\n\nnamespace utils {\n\nstatic GF2X modulus;\nstatic std::array<GF2E, 256> lifting_lut;\n\nstatic void init_lifting_lut(const GF2E &generator) {\n  clear(lifting_lut[0]); // lut(0) = 0\n  set(lifting_lut[1]);   // lut(1) = 1\n\n  GF2E pow = generator;\n  for (size_t bit = 1; bit < 8; bit++) {\n    size_t start = (1ULL << bit);\n    // copy last half of LUT and add current generator power\n    for (size_t idx = 0; idx < start; idx++) {\n      lifting_lut[start + idx] = lifting_lut[idx] + pow;\n    }\n    pow = pow * generator;\n  }\n}\n\nvoid init_extension_field(const banquet_instance_t &instance) {\n  switch (instance.lambda) {\n  case 4: {\n    // modulus = x^32 + x^7 + x^3 + x^2 + 1\n    clear(modulus);\n    SetCoeff(modulus, 32);\n    SetCoeff(modulus, 7);\n    SetCoeff(modulus, 3);\n    SetCoeff(modulus, 2);\n    SetCoeff(modulus, 0);\n    // Ring morphism:\n    //   From: Finite Field in x of size 2^8\n    //   To:   Finite Field in y of size 2^32\n    //   Defn: x |--> y^30 + y^23 + y^21 + y^18 + y^14 + y^13 + y^11 + y^9 + y^7\n    //   + y^6 + y^5 + y^4 + y^3 + y\n    GF2X gen;\n    clear(gen);\n    SetCoeff(gen, 30);\n    SetCoeff(gen, 23);\n    SetCoeff(gen, 21);\n    SetCoeff(gen, 18);\n    SetCoeff(gen, 14);\n    SetCoeff(gen, 13);\n    SetCoeff(gen, 11);\n    SetCoeff(gen, 9);\n    SetCoeff(gen, 7);\n    SetCoeff(gen, 6);\n    SetCoeff(gen, 5);\n    SetCoeff(gen, 4);\n    SetCoeff(gen, 3);\n    SetCoeff(gen, 1);\n\n    GF2E::init(modulus);\n    init_lifting_lut(conv<GF2E>(gen));\n  } break;\n  case 5: {\n    // modulus = x^40 + x^5 + x^4 + x^3 + 1\n    clear(modulus);\n    SetCoeff(modulus, 40);\n    SetCoeff(modulus, 5);\n    SetCoeff(modulus, 4);\n    SetCoeff(modulus, 3);\n    SetCoeff(modulus, 0);\n    // Ring morphism:\n    //   From: Finite Field in x of size 2^8\n    //   To:   Finite Field in y of size 2^40\n    //   Defn: x |--> y^31 + y^30 + y^27 + y^25 + y^22 + y^21 + y^20 + y^18 +\n    //   y^15 + y^9 + y^6 + y^4 + y^2\n    GF2X gen;\n    clear(gen);\n    SetCoeff(gen, 31);\n    SetCoeff(gen, 30);\n    SetCoeff(gen, 27);\n    SetCoeff(gen, 25);\n    SetCoeff(gen, 22);\n    SetCoeff(gen, 21);\n    SetCoeff(gen, 20);\n    SetCoeff(gen, 18);\n    SetCoeff(gen, 15);\n    SetCoeff(gen, 9);\n    SetCoeff(gen, 6);\n    SetCoeff(gen, 4);\n    SetCoeff(gen, 2);\n\n    GF2E::init(modulus);\n    init_lifting_lut(conv<GF2E>(gen));\n  } break;\n  case 6: {\n    // modulus = x^48 + x^5 + x^3 + x^2 + 1\n    clear(modulus);\n    SetCoeff(modulus, 48);\n    SetCoeff(modulus, 5);\n    SetCoeff(modulus, 3);\n    SetCoeff(modulus, 2);\n    SetCoeff(modulus, 0);\n    // Ring morphism:\n    //   From: Finite Field in x of size 2^8\n    //   To:   Finite Field in y of size 2^48\n    //   Defn: x |--> y^45 + y^43 + y^40 + y^37 + y^36 + y^35 + y^34 + y^33 +\n    //   y^31 + y^30 + y^29 + y^28 + y^24 + y^21 + y^20 + y^19 + y^16 + y^14 +\n    //   y^13 + y^11 + y^10 + y^7 + y^3 + y^2\n    GF2X gen;\n    clear(gen);\n    SetCoeff(gen, 45);\n    SetCoeff(gen, 43);\n    SetCoeff(gen, 40);\n    SetCoeff(gen, 37);\n    SetCoeff(gen, 36);\n    SetCoeff(gen, 35);\n    SetCoeff(gen, 34);\n    SetCoeff(gen, 33);\n    SetCoeff(gen, 31);\n    SetCoeff(gen, 30);\n    SetCoeff(gen, 29);\n    SetCoeff(gen, 28);\n    SetCoeff(gen, 24);\n    SetCoeff(gen, 21);\n    SetCoeff(gen, 20);\n    SetCoeff(gen, 19);\n    SetCoeff(gen, 16);\n    SetCoeff(gen, 14);\n    SetCoeff(gen, 13);\n    SetCoeff(gen, 11);\n    SetCoeff(gen, 10);\n    SetCoeff(gen, 7);\n    SetCoeff(gen, 3);\n    SetCoeff(gen, 2);\n\n    GF2E::init(modulus);\n    init_lifting_lut(conv<GF2E>(gen));\n  } break;\n  default:\n    throw std::runtime_error(\n        \"modulus for that specific lambda not implemented.\");\n  }\n}\n\nconst GF2E &lift_uint8_t(uint8_t value) { return lifting_lut[value]; }\n\nGF2E GF2E_from_bytes(const std::vector<uint8_t> &value) {\n  // assumes value is already smaller than current modulus\n  GF2X inner = GF2XFromBytes(value.data(), value.size());\n  // GF2E result(INIT_NO_ALLOC);\n  // result.LoopHole() = inner;\n  // return result;\n  return conv<GF2E>(inner);\n}\n\nvec_GF2E get_first_n_field_elements(size_t n) {\n  vec_GF2E result;\n  result.SetLength(n);\n  GF2X gen;\n  SetX(gen);\n  for (size_t i = 0; i < n; i++) {\n    result[i] = conv<GF2E>(gen);\n    gen = MulByX(gen);\n  }\n  return result;\n}\nstd::vector<GF2EX> precompute_lagrange_polynomials(const vec_GF2E &x_values) {\n  size_t m = x_values.length();\n  std::vector<GF2EX> precomputed_lagrange_polynomials;\n  precomputed_lagrange_polynomials.reserve(m);\n\n  GF2EX full_poly = BuildFromRoots(x_values);\n  GF2EX lagrange_poly;\n  GF2EX missing_term;\n  SetX(missing_term);\n  for (size_t k = 0; k < m; k++) {\n    SetCoeff(missing_term, 0, -x_values[k]);\n    lagrange_poly = full_poly / missing_term;\n    lagrange_poly = lagrange_poly / eval(lagrange_poly, x_values[k]);\n    precomputed_lagrange_polynomials.push_back(lagrange_poly);\n  }\n\n  return precomputed_lagrange_polynomials;\n}\n\nGF2EX interpolate_with_precomputation(\n    const std::vector<GF2EX> &precomputed_lagrange_polynomials,\n    const vec_GF2E &y_values) {\n  if (precomputed_lagrange_polynomials.size() != (size_t)y_values.length())\n    throw std::runtime_error(\"invalid sizes for interpolation\");\n\n  GF2EX res;\n  size_t m = y_values.length();\n  for (size_t k = 0; k < m; k++) {\n    res += precomputed_lagrange_polynomials[k] * y_values[k];\n  }\n  return res;\n}\nfield::GF2E ntl_to_custom(const GF2E &element) {\n  const GF2X &poly_rep = rep(element);\n  std::vector<uint8_t> buffer(8);\n  BytesFromGF2X(buffer.data(), poly_rep, buffer.size());\n  field::GF2E a;\n  a.from_bytes(buffer.data());\n  return a;\n}\nGF2E custom_to_ntl(const field::GF2E &element) {\n  std::vector<uint8_t> buffer(8);\n  element.to_bytes(buffer.data());\n  GF2X inner = GF2XFromBytes(buffer.data(), buffer.size());\n  return conv<GF2E>(inner);\n}\n} // namespace utils\n", "meta": {"hexsha": "b58d7d9a226395a6daa916644ee0ab960f11ffb7", "size": 5844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/utils.cpp", "max_stars_repo_name": "dkales/banquet", "max_stars_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T23:15:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T12:18:08.000Z", "max_issues_repo_path": "tests/utils.cpp", "max_issues_repo_name": "dkales/banquet", "max_issues_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/utils.cpp", "max_forks_repo_name": "dkales/banquet", "max_forks_repo_head_hexsha": "ec9920205713e09199e29ff439928d266e0d9a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1813953488, "max_line_length": 80, "alphanum_fraction": 0.613963039, "num_tokens": 2017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5913894834236176}}
{"text": "/*\n * Copyright 2009-2011 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/linspline.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <votca/tools/linalg.h>\n#include <iostream>\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nvoid LinSpline::Interpolate(ub::vector<double> &x, ub::vector<double> &y)\n{\n    if(x.size() != y.size())\n        throw std::invalid_argument(\"error in LinSpline::Interpolate : sizes of vectors x and y do not match\");\n\n    if(x.size()<2)\n        throw std::invalid_argument(\"error in LinSpline::Interpolate : vectors x and y have to contain at least 2 points\");\n\n    const int N = x.size();\n\n    // adjust the grid\n    _r.resize(N);\n    \n    // copy the grid points into f\n    _r = x;\n    \n    // LINEAR SPLINE: a(i) * x + b(i)\n    // where i=number of interval\n\n    // initialize vectors a,b\n    a = ub::zero_vector<double>(N);\n    b = ub::zero_vector<double>(N);\n\n    // boundary conditions not applicable\n    \n    // calculate a,b for all intervals 0..(N-2), where interval\n    // [x(i),x(i+1)] shall have number i (this means that the last interval\n    // has number N-2)\n    for (int i=0; i<N-1; i++) {\n        a(i) = (y(i+1)-y(i))/(x(i+1)-x(i));\n        b(i) = y(i)-a(i)*x(i);\n    }\n}\n\nvoid LinSpline::Fit(ub::vector<double> &x, ub::vector<double> &y)\n{\n    if(x.size() != y.size())\n        throw std::invalid_argument(\"error in LinSpline::Fit : sizes of vectors x and y do not match\");\n\n    const int N = x.size();\n    const int ngrid = _r.size();\n\n    // construct the equation\n    // A*u = b\n    // The matrix A contains all conditions\n    // s_i(x) = (y(i+1)-y(i)) * (x-r(i))/(r(i+1)-r(i)) + y(i)\n    // where y(i) are the unknown values at grid points r(i), and\n    // the condition y=s_i(x) is to be satisfied at all input points:\n    // therefore b=y and u=vector of all unknown y(i)\n    \n    ub::matrix<double> A(N, ngrid);\n    A = ub::zero_matrix<double>(N, ngrid);\n    int interval;\n\n    // construct matrix A\n    for (int i=0; i<N; i++) {\n        interval = getInterval(x(i));\n        A(i,interval)   = 1 - (x(i)-_r(interval))/(_r(interval+1)-_r(interval));\n        A(i,interval+1) = (x(i)-_r(interval))/(_r(interval+1)-_r(interval));\n    }\n\n    // now do a qr solve\n    ub::vector<double> sol(ngrid);\n    votca::tools::linalg_qrsolve(sol, A, y);\n\n    // vector \"sol\" contains all y-values of fitted linear splines at each\n    // interval border\n    // get a(i) and b(i) for piecewise splines out of solution vector \"sol\"\n    a = ub::zero_vector<double>(ngrid-1);\n    b = ub::zero_vector<double>(ngrid-1);\n    for (int i=0; i<ngrid-1; i++) {\n        a(i) = (sol(i+1)-sol(i))/(_r(i+1)-_r(i));\n        b(i) = -a(i)*_r(i) + sol(i);\n    }\n}\n}}\n", "meta": {"hexsha": "29cc65519f3ead31e5cdc4ff7e44c4711be6a2d4", "size": 3377, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linspline.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/linspline.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/linspline.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": 32.1619047619, "max_line_length": 123, "alphanum_fraction": 0.6197808706, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5913818331603632}}
{"text": "#include <iostream>\n\n#include <NTL/ZZ.h>\n\nusing namespace std;\nusing namespace NTL;\n\n/*\n * This program calculates a blinded message from m and from its\n * signature S' calculates S, the signature of m.\n */\n\nint main() {\n\tZZ m, e, n, blind_m, blind_S, S, r;\n\tr = 2;\n\n\tcout << \"m> \";\n\tcin >> m;\n\tcout << \"e> \";\n\tcin >> e;\n\tcout << \"n> \";\n\tcin >> n;\n\n\t// m' = m*r^e (mod n)\n\tmul(blind_m, m, PowerMod(r, e, n));\n\tcout << \"m': \" << blind_m << endl << endl;\n\n\tcout << \"S'> \";\n\tcin >> blind_S;\n\n\t// S = S' * r^(-1)\n\tMulMod(S, blind_S, InvMod(r, n), n);\n\n\tcout << \"S: \" << S << endl;\n}\n", "meta": {"hexsha": "f537e2d56346e2c8f0236b43ac8b27d34093f207", "size": 579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blinding.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blinding.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blinding.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0833333333, "max_line_length": 64, "alphanum_fraction": 0.5319516408, "num_tokens": 199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.5913319831666265}}
{"text": "/******************************\r\n      Author: Joel Veness\r\n        Date: 2011\r\n******************************/\r\n\r\n#include \"ctw.hpp\"\r\n\r\n#include <vector>\r\n#include <cassert>\r\n#include <stack>\r\n#include <iostream>\r\n#include <cmath>\r\n\r\n// boost includes\r\n#include <boost/utility.hpp>\r\n\r\n\r\n// enable both options below for better compression performance on text sources.\r\n// disable both for vanilla CTW.\r\n\r\n// do we use the zero redundancy estimator instead of the KT estimator?\r\nstatic const bool UseZeroRedundancy = false;\r\n\r\n// do we only perform weighting at byte boundaries in factored mode?\r\nstatic const bool UseWeightingOnlyAtByteBoundaries = false;\r\n\r\n\r\n// precompute some common logarithms\r\nstatic const double log_point_five = std::log(0.5);\r\nstatic const double log_quarter    = std::log(0.25);\r\n\r\n\r\n/* create a new context node */\r\nCTNode::CTNode() :\r\n    m_log_prob_est(0.0),\r\n    m_log_prob_weighted(0.0)\r\n{\r\n    m_count[0] = 0;    m_count[1] = 0;\r\n    m_child[0] = NULL; m_child[1] = NULL;\r\n}\r\n\r\n\r\n/* update the weighted probabilities */\r\nvoid CTNode::updateWeighted() {\r\n\r\n    // computes P_w = log{0.5 * [P_kt + P_w0*P_w1]}\r\n    double log_prob_on  = child(1) ? child(1)->logProbWeighted() : 0.0;\r\n    double log_prob_off = child(0) ? child(0)->logProbWeighted() : 0.0;\r\n    double log_one_plus_exp = log_prob_off + log_prob_on - logProbEstimated();\r\n\r\n    // NOTE: no need to compute the log(1+e^x) if x is large, plus it avoids overflows\r\n    if (log_one_plus_exp < 100.0) log_one_plus_exp = std::log(1.0 + std::exp(log_one_plus_exp));\r\n\r\n    m_log_prob_weighted = log_point_five + logProbEstimated() + log_one_plus_exp;\r\n}\r\n\r\n\r\n/* process a new binary symbol */\r\nvoid CTNode::update(bit_t b, bool skip) {\r\n\r\n    // update the KT estimate and counts\r\n    double log_kt_mul = logKTMul(b);\r\n    m_log_prob_est += log_kt_mul;\r\n    m_count[b]++;\r\n\r\n    if (isLeaf()) {\r\n        m_log_prob_weighted = logProbEstimated();\r\n    } else {\r\n        if (skip) {\r\n            double log_prob_on  = child(1) ? child(1)->logProbWeighted() : 0.0;\r\n            double log_prob_off = child(0) ? child(0)->logProbWeighted() : 0.0;\r\n            m_log_prob_weighted = log_prob_on + log_prob_off;\r\n        } else {\r\n            updateWeighted();\r\n        }\r\n    }\r\n}\r\n\r\n\r\n/* is the current node a leaf node? */\r\nbool CTNode::isLeaf() const {\r\n\r\n    return child(0) == NULL && child(1) == NULL;\r\n}\r\n\r\n\r\n/* Krichevski-Trofimov estimated log probability accessor */\r\nweight_t CTNode::logProbEstimated() const {\r\n\r\n    if (UseZeroRedundancy) {\r\n        if (m_count[0]+m_count[1] == 0) return 0.0;\r\n        double rval = log_point_five + m_log_prob_est;\r\n        if (m_count[0] == 0) rval = logAdd(log_quarter, rval);\r\n        if (m_count[1] == 0) rval = logAdd(log_quarter, rval);\r\n        return rval;\r\n    }\r\n\r\n    return m_log_prob_est;\r\n}\r\n\r\n\r\n/* logarithmic weighted probability estimate accessor */\r\nweight_t CTNode::logProbWeighted() const {\r\n    return m_log_prob_weighted;\r\n}\r\n\r\n\r\n/* child corresponding to a particular symbol */\r\nconst CTNode *CTNode::child(bit_t b) const {\r\n    return m_child[b];\r\n}\r\n\r\n\r\n/* the number of times this context been visited */\r\nint CTNode::visits() const {\r\n    return m_count[0] + m_count[1];\r\n}\r\n\r\n\r\n/* compute the logarithm of the KT-estimator update multiplier */\r\ndouble CTNode::logKTMul(bit_t b) const {\r\n\r\n    static const double alpha = 0.5;\r\n    static const double alpha2 = 2.0 * alpha;\r\n\r\n    double kt_mul_numer = double(m_count[b]) + alpha;\r\n    double kt_mul_denom = double(visits()) + alpha2;\r\n\r\n    return std::log(kt_mul_numer / kt_mul_denom);\r\n}\r\n\r\n\r\n/* number of descendents of a node in the context tree */\r\nsize_t CTNode::size() const {\r\n\r\n    size_t rval = 1;\r\n    rval += child(0) ? child(0)->size() : 0;\r\n    rval += child(1) ? child(1)->size() : 0;\r\n    return rval;\r\n}\r\n\r\n\r\n/* create (if necessary) all of the nodes in the current context */\r\nvoid ContextTree::createNodesInCurrentContext(const context_t &context) {\r\n\r\n    CTNode **ctn = &m_root;\r\n\r\n    for (size_t i = 0; i < context.size(); i++) {\r\n        ctn = &((*ctn)->m_child[context[i]]);\r\n        if (*ctn == NULL) {\r\n            void *p = m_ctnode_pool.malloc();\r\n            assert(p != NULL);  // TODO: make more robust\r\n            *ctn = new (p) CTNode();\r\n        }\r\n    }\r\n}\r\n\r\n\r\n/* create a context tree of specified maximum depth and size */\r\nContextTree::ContextTree(history_t &history, size_t depth, int phase/*=-1*/) :\r\n    m_ctnode_pool(sizeof(CTNode)),\r\n    m_root(new (m_ctnode_pool.malloc()) CTNode()),\r\n    m_phase(phase),\r\n    m_depth(depth),\r\n    m_history(history)\r\n{\r\n}\r\n\r\n\r\n/* delete the context tree */\r\nContextTree::~ContextTree(void) {\r\n    deleteCT(m_root);\r\n}\r\n\r\n\r\n/* recursively deletes the nodes in a context tree */\r\nvoid ContextTree::deleteCT(CTNode *n) {\r\n\r\n    if (n == NULL) return;\r\n\r\n    if (n->m_child[0] != NULL) deleteCT(n->m_child[0]);\r\n    if (n->m_child[1] != NULL) deleteCT(n->m_child[1]);\r\n\r\n    m_ctnode_pool.free(n);\r\n}\r\n\r\n\r\n/* compute the current binary context */\r\nvoid ContextTree::getContext(const history_t &h, context_t &context) const {\r\n\r\n    context.clear();\r\n    for (size_t i=0; i < m_depth; ++i) {\r\n        context.push_back(h[h.size()-i-1]);\r\n    }\r\n}\r\n\r\n\r\n/* updates the context tree with a single bit */\r\nvoid ContextTree::update(bit_t b) {\r\n\r\n    // compute the current context\r\n    context_t context;\r\n    context.reserve(m_depth);\r\n    getContext(m_history, context);\r\n\r\n    // 1. create new nodes in the context tree (if necessary)\r\n    createNodesInCurrentContext(context);\r\n\r\n    // 2. walk down the tree to the relevant leaf, saving the path as we go\r\n    std::stack<CTNode *, std::vector<CTNode *> > path;\r\n    path.push(m_root); // add the empty context\r\n    CTNode *ctn = m_root;\r\n    for (size_t i = 0; i < context.size(); i++) {\r\n        ctn = ctn->m_child[context[i]];\r\n        path.push(ctn);\r\n    }\r\n\r\n    // 3. update the probability estimates from the leaf node back up to the root\r\n    int index = static_cast<int>(m_depth);\r\n    for (; !path.empty(); path.pop()) {\r\n        bool skip = UseWeightingOnlyAtByteBoundaries && m_phase > -1 &&\r\n                    (index % 8) != m_phase && index != 0;\r\n        path.top()->update(b, skip);\r\n        index--;\r\n    }\r\n\r\n    // 4. update the history\r\n    m_history.push_back(b != 0);\r\n}\r\n\r\n\r\n/* the probability of seeing a particular symbol next */\r\ndouble ContextTree::prob(bit_t b) {\r\n\r\n    typedef std::pair<CTNode *, CTNode> ctpair_t;\r\n\r\n    double before = logBlockProbability();\r\n\r\n    // compute the current context\r\n    context_t context;\r\n    getContext(m_history, context);\r\n\r\n    // 1. record newly added or modified nodes\r\n    std::vector<CTNode *> created;\r\n    std::vector<ctpair_t> modified;\r\n\r\n    CTNode **ctnp = &m_root;\r\n    modified.push_back(ctpair_t(m_root, *m_root));\r\n    for (size_t i = 0; i < context.size(); i++) {\r\n        ctnp = &((*ctnp)->m_child[context[i]]);\r\n        if (*ctnp == NULL) {\r\n            void *p = m_ctnode_pool.malloc();\r\n            assert(p != NULL);  // TODO: make more robust\r\n            *ctnp = new (p) CTNode();\r\n            created.push_back(*ctnp);\r\n        } else {\r\n            modified.push_back(ctpair_t(*ctnp, **ctnp));\r\n        }\r\n    }\r\n\r\n    // 2. walk down the tree to the relevant leaf, saving the path as we go\r\n    std::stack<CTNode *, std::vector<CTNode *> > path;\r\n    path.push(m_root); // add the empty context\r\n    CTNode *ctn = m_root;\r\n    for (size_t i = 0; i < context.size(); i++) {\r\n        ctn = ctn->m_child[context[i]];\r\n        path.push(ctn);\r\n    }\r\n\r\n    // 3. update the probability estimates from the leaf node back up to the root\r\n    int index = static_cast<int>(m_depth);\r\n    for (; !path.empty(); path.pop()) {\r\n        bool skip = UseWeightingOnlyAtByteBoundaries && m_phase > -1 &&\r\n                    (index % 8) != m_phase && index != 0;\r\n        path.top()->update(b, skip);\r\n        index--;\r\n    }\r\n\r\n    double rval = std::exp(logBlockProbability() - before);\r\n\r\n    // now revert the changes\r\n    for (size_t i=0; i < created.size(); ++i) m_ctnode_pool.free(created[i]);\r\n    for (size_t i=0; i < modified.size(); ++i) *modified[i].first = modified[i].second;\r\n\r\n    return rval;\r\n}\r\n\r\n\r\n/* the depth of the context tree */\r\nsize_t ContextTree::depth() const {\r\n\r\n    return m_depth;\r\n}\r\n\r\n\r\n/* number of nodes in the context tree */\r\nsize_t ContextTree::size(void) const {\r\n\r\n    return m_root->size();\r\n}\r\n\r\n\r\n/* recover the memory used by a node */\r\nvoid ContextTree::reclaimMemory(CTNode *n) {\r\n\r\n    m_ctnode_pool.free(n);\r\n}\r\n\r\n\r\n/* the logarithm of the block probability of the whole sequence */\r\ndouble ContextTree::logBlockProbability(void) const {\r\n\r\n    return m_root->logProbWeighted();\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "272aab3e382a35b01cc321df85308034964d4c8e", "size": 8754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ctw.cpp", "max_stars_repo_name": "mgbellemare/SkipCTS", "max_stars_repo_head_hexsha": "ff142fa87bc16b1e2e381cf4f9e4959e754b9028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-27T10:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T07:49:56.000Z", "max_issues_repo_path": "src/ctw.cpp", "max_issues_repo_name": "GitHubBeinner/SkipCTS", "max_issues_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-02-12T21:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-27T01:44:10.000Z", "max_forks_repo_path": "src/ctw.cpp", "max_forks_repo_name": "GitHubBeinner/SkipCTS", "max_forks_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T07:06:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T12:04:21.000Z", "avg_line_length": 27.6151419558, "max_line_length": 97, "alphanum_fraction": 0.6038382454, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805822, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5913164071515137}}
{"text": "#include <vector>\n#include <cmath>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n\nnamespace bp = boost::python;\nnamespace np = boost::python::numpy;\n\nclass rawor{\n    double nbar_ran, Delta_r, r_max, r_min, V_box;\n    int N_parts, N_rans, N_shells;\n    std::vector<double> rs, w, x;\n    \n    void initVectors();\n    \n    void swapIfGreater(double &a, double &b);\n    \n    double sphereOverlapVolume(double d, double R, double r);\n    \n    double crossSectionVolume(double r1, double r2, double r3);\n    \n    int getPermutations(double r1, double r2, double r3);\n    \n    double sphericalShellVolume(double r);\n    \n    double nbarData(unsigned long *DD, double r, double r1);\n    \n    double gaussQuadCrossSection(double r1, double r2, double r3);\n    \n    double gaussQuadCrossSectionDDR(unsigned long *DD, double r1, double r2, double r3);\n    \n    public:\n        rawor(int numParticles, int numRandoms, int numShells, double VolBox, double rMax, double rMin = 0);\n        \n        void setNumParts(int numParticles);\n        \n        void setNumRans(int numRandoms);\n        \n        void setNumShells(int numShells);\n        \n        void setRMax(double rMax);\n        \n        void setRMin(double rMin);\n        \n        void setVBox(double VBox);\n        \n        int getNumParts();\n        \n        int getNumRans();\n        \n        int getNumShells();\n        \n        double getRMax();\n        \n        double getRMin();\n        \n        double getVBox();\n        \n        np::ndarray getRRR();\n        \n        np::ndarray getDRR();\n        \n        np::ndarray getDDR(np::ndarray const &dd);\n};\n\nvoid rawor::initVectors() {\n    for (int i = 0; i < rawor::N_shells; ++i) {\n        rawor::rs.push_back(rawor::r_min + (i + 0.5)*rawor::Delta_r);\n    }\n    \n    rawor::w = {0.8888888888888888, 0.5555555555555556, 0.5555555555555556};\n    \n    rawor::x = {0.0000000000000000, -0.7745966692414834, 0.7745966692414834};\n}\n\nvoid rawor::swapIfGreater(double &a, double &b) {\n    if (a > b) {\n        double temp = a;\n        a = b;\n        b = temp;\n    }\n}\n\ndouble rawor::sphereOverlapVolume(double d, double R, double r) {\n    double V = 0;\n    swapIfGreater(r, R);\n    if (d < R + r) {\n        if (d > R - r) {\n            V = (M_PI*(R + r - d)*(R + r - d)*(d*d + 2.0*d*r - 3.0*r*r + 2.0*d*R + 6.0*r*R - 3.0*R*R))/(12.0*d);\n        } else {\n            V = (4.0*M_PI/3.0)*r*r*r;\n        }\n    }\n    return V;\n}\n\ndouble rawor::crossSectionVolume(double r1, double r2, double r3) {\n    double V_oo = sphereOverlapVolume(r1, r3 + 0.5*rawor::Delta_r, r2 + 0.5*rawor::Delta_r);\n    double V_oi = sphereOverlapVolume(r1, r3 + 0.5*rawor::Delta_r, r2 - 0.5*rawor::Delta_r);\n    double V_io = sphereOverlapVolume(r1, r3 - 0.5*rawor::Delta_r, r2 + 0.5*rawor::Delta_r);\n    double V_ii = sphereOverlapVolume(r1, r3 - 0.5*rawor::Delta_r, r2 - 0.5*rawor::Delta_r);\n    \n    return V_oo - V_oi - V_io + V_ii;\n}\n\nint rawor::getPermutations(double r1, double r2, double r3) {\n    int perm = 1;\n    if (r1 != r2 && r1 != r3 && r2 != r3) {\n        perm = 6;\n    } else if ((r1 == r2 && r1 != r3) || (r1 == r3 && r1 != r2) || (r2 == r3 && r2 != r1)) {\n        perm = 3;\n    }\n    return perm;\n}\n\ndouble rawor::sphericalShellVolume(double r) {\n    double r_o = r + 0.5*rawor::Delta_r;\n    double r_i = r - 0.5*rawor::Delta_r;\n    return 4.0*M_PI*(r_o*r_o*r_o - r_i*r_i*r_i)/3.0;\n}\n\ndouble rawor::nbarData(unsigned long *DD, double r, double r1) {\n    int bin = r/rawor::Delta_r;\n    double nbar = DD[bin]/(rawor::N_parts*sphericalShellVolume(r1));\n    int num_bins = rawor::N_shells;\n    if (r <= (bin + 0.5)*rawor::Delta_r) {\n        if (bin != 0) {\n            double n1 = DD[bin]/(rawor::N_parts*sphericalShellVolume(r1));\n            double n2 = DD[bin - 1]/(rawor::N_parts*sphericalShellVolume(r1 - rawor::Delta_r));\n            double b = n1 - ((n1 - n2)/rawor::Delta_r)*r1;\n            nbar = ((n1 - n2)/rawor::Delta_r)*r + b;\n        } else {\n            double n1 = DD[bin]/(rawor::N_parts*sphericalShellVolume(r1));\n            double n2 = DD[bin + 1]/(rawor::N_parts*sphericalShellVolume(r1 + rawor::Delta_r));\n            double b = n1 - ((n2 - n1)/rawor::Delta_r)*r1;\n            nbar = ((n2 - n1)/rawor::Delta_r)*r + b;\n        }\n    } else {\n        if (bin != num_bins - 1) {\n            double n1 = DD[bin]/(rawor::N_parts*sphericalShellVolume(r1));\n            double n2 = DD[bin + 1]/(rawor::N_parts*sphericalShellVolume(r1 + rawor::Delta_r));\n            double b = n1 - ((n2 - n1)/rawor::Delta_r)*r1;\n            nbar = ((n2 - n1)/rawor::Delta_r)*r + b;\n        } else {\n            double n1 = DD[bin]/(rawor::N_parts*sphericalShellVolume(r1));\n            double n2 = DD[bin - 1]/(rawor::N_parts*sphericalShellVolume(r1 - rawor::Delta_r));\n            double b = n1 - ((n1 - n2)/rawor::Delta_r)*r1;\n            nbar = ((n1 - n2)/rawor::Delta_r)*r + b;\n        }\n    }\n    return nbar;\n}\n\ndouble rawor::gaussQuadCrossSection(double r1, double r2, double r3) {\n    double result = 0.0;\n    for (int i = 0; i < rawor::w.size(); ++i) {\n        double r_1 = r1 + 0.5*rawor::Delta_r*rawor::x[i];\n        result += 0.5*rawor::Delta_r*rawor::w[i]*crossSectionVolume(r_1, r2, r3)*r_1*r_1;\n    }\n    return result;\n}\n\ndouble rawor::gaussQuadCrossSectionDDR(unsigned long *DD, double r1, double r2, double r3) {\n    double result = 0.0;\n    for (int i = 0; i < rawor::w.size(); ++i) {\n        double r_1 = r1 + 0.5*rawor::Delta_r*rawor::x[i];\n        double nbar = nbarData(DD, r_1, r1);\n        result += 0.5*rawor::Delta_r*rawor::w[i]*crossSectionVolume(r_1, r2, r3)*r_1*r_1*nbar;\n    }\n    return result;\n}\n\nrawor::rawor(int numParticles, int numRandoms, int numShells, double VolBox, double rMax, double rMin) {\n    rawor::N_parts = numParticles;\n    rawor::N_rans = numRandoms;\n    rawor::N_shells = numShells;\n    rawor::r_max = rMax;\n    rawor::r_min = rMin;\n    rawor::V_box = VolBox;\n    rawor::Delta_r = (rMax - rMin)/numShells;\n    rawor::nbar_ran = numRandoms/VolBox;\n    rawor::initVectors();\n}\n\nvoid rawor::setNumParts(int numParticles) {\n    rawor::N_parts = numParticles;\n}\n\nvoid rawor::setNumRans(int numRandoms) {\n    rawor::N_rans = numRandoms;\n    rawor::nbar_ran = numRandoms/rawor::V_box;\n}\n\nvoid rawor::setNumShells(int numShells) {\n    rawor::N_shells = numShells;\n    rawor::Delta_r = (rawor::r_max - rawor::r_min)/rawor::N_shells;\n}\n\nvoid rawor::setRMax(double rMax) {\n    rawor::r_max = rMax;\n    rawor::Delta_r = (rawor::r_max - rawor::r_min)/rawor::N_shells;\n}\n\nvoid rawor::setRMin(double rMin) {\n    rawor::r_min = rMin;\n    rawor::Delta_r = (rawor::r_max - rawor::r_min)/rawor::N_shells;\n}\n\nvoid rawor::setVBox(double VBox) {\n    rawor::V_box = VBox;\n    rawor::nbar_ran = rawor::N_rans/rawor::V_box;\n}\n\nint rawor::getNumParts() {\n    return rawor::N_parts;\n}\n\nint rawor::getNumRans() {\n    return rawor::N_rans;\n}\n\nint rawor::getNumShells() {\n    return rawor::N_shells;\n}\n\ndouble rawor::getVBox() {\n    return rawor::V_box;\n}\n\ndouble rawor::getRMin() {\n    return rawor::r_min;\n}\n\ndouble rawor::getRMax() {\n    return rawor::r_max;\n}\n\nnp::ndarray rawor::getRRR() {\n    std::vector<int> N;\n    for (int i = 0; i < rawor::N_shells; ++i) {\n        for (int j = i; j < rawor::N_shells; ++j) {\n            for (int k = j; k < rawor::N_shells; ++k) {\n                if (rawor::rs[k] <= rawor::rs[i] + rawor::rs[j]) {\n                    int index = k + rawor::N_shells*(j + rawor::N_shells*i);\n                    double V = rawor::gaussQuadCrossSection(rawor::rs[i], rawor::rs[j], rawor::rs[k]);\n                    int n_perm = rawor::getPermutations(rawor::rs[i], rawor::rs[j], rawor::rs[k]);\n                    N.push_back(int(4.0*M_PI*n_perm*rawor::nbar_ran*rawor::nbar_ran*V*rawor::N_rans));\n                }\n            }\n        }\n    }\n    np::dtype dt = np::dtype::get_builtin<int>();\n    np::ndarray n = np::zeros(bp::make_tuple(N.size()), dt);\n    std::copy(N.begin(), N.end(), reinterpret_cast<int*>(n.get_data()));\n    return n;\n}\n\nnp::ndarray rawor::getDRR() {\n    std::vector<int> N;\n    for (int i = 0; i < rawor::N_shells; ++i) {\n        for (int j = i; j < rawor::N_shells; ++j) {\n            for (int k = j; k < rawor::N_shells; ++k) {\n                if (rawor::rs[k] <= rawor::rs[i] + rawor::rs[j]) {\n                    int index = k + rawor::N_shells*(j + rawor::N_shells*i);\n                    double V = rawor::gaussQuadCrossSection(rawor::rs[i], rawor::rs[j], rawor::rs[k]);\n                    int n_perm = rawor::getPermutations(rawor::rs[i], rawor::rs[j], rawor::rs[k]);\n                    N.push_back(int(4.0*M_PI*n_perm*rawor::nbar_ran*rawor::nbar_ran*V*rawor::N_parts));\n                }\n            }\n        }\n    }\n    np::dtype dt = np::dtype::get_builtin<int>();\n    np::ndarray n = np::zeros(bp::make_tuple(N.size()), dt);\n    std::copy(N.begin(), N.end(), reinterpret_cast<int*>(n.get_data()));\n    return n;\n}\n\nnp::ndarray rawor::getDDR(np::ndarray const &dd) {\n    unsigned long *DD = reinterpret_cast<unsigned long *>(dd.get_data());\n    std::vector<int> N;\n    for (int i = 0; i < rawor::N_shells; ++i) {\n        double r1 = rawor::rs[i];\n        for (int j = i; j < rawor::N_shells; ++j) {\n            double r2 = rawor::rs[j];\n            for (int k = j; k < rawor::N_shells; ++k) {\n                double r3 = rawor::rs[k];\n                if (rawor::rs[k] <= rawor::rs[i] + rawor::rs[j]) {\n                   int index = k + rawor::N_shells*(j + rawor::N_shells*i);\n                   double V = rawor::gaussQuadCrossSectionDDR(DD, r1, r2, r3);\n                   double N_temp = 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                   if (r1 != r2 && r1 != r3 && r2 != r3) {\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r2, r3, r1);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r3, r1, r2);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r1, r3, r2);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r2, r1, r3);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r3, r2, r1);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                   } else if ((r1 == r2 && r1 != r3) || (r1 == r3 && r1 != r2) || (r2 == r3 && r2 != r1)) {\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r2, r3, r1);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                       V = rawor::gaussQuadCrossSectionDDR(DD, r3, r1, r2);\n                       N_temp += 4.0*M_PI*rawor::nbar_ran*V*rawor::N_parts;\n                   }\n                   N.push_back(int(floor(N_temp + 0.5)));\n                }\n            }\n        }\n    }\n    np::dtype dt = np::dtype::get_builtin<int>();\n    np::ndarray n = np::zeros(bp::make_tuple(N.size()), dt);\n    std::copy(N.begin(), N.end(), reinterpret_cast<int*>(n.get_data()));\n    return n;\n}\n\nBOOST_PYTHON_MODULE(rawor) {\n    np::initialize();\n    using namespace boost::python;\n    \n    class_<rawor>(\"rawor\", init<int, int, int, double, double, double>())\n        .def(\"set_num_parts\", &rawor::setNumParts)\n        .def(\"set_num_rans\", &rawor::setNumRans)\n        .def(\"set_num_shells\", &rawor::setNumShells)\n        .def(\"set_r_max\", &rawor::setRMax)\n        .def(\"set_r_min\", &rawor::setRMin)\n        .def(\"set_V_box\", &rawor::setVBox)\n        .def(\"get_num_parts\", &rawor::getNumParts)\n        .def(\"get_num_rans\", &rawor::getNumRans)\n        .def(\"get_num_shells\", &rawor::getNumShells)\n        .def(\"get_V_box\", &rawor::getVBox)\n        .def(\"get_r_min\", &rawor::getRMin)\n        .def(\"get_r_max\", &rawor::getRMax)\n        .def(\"get_RRR\", &rawor::getRRR)\n        .def(\"get_DRR\", &rawor::getDRR)\n        .def(\"get_DDR\", &rawor::getDDR)\n    ;\n}\n", "meta": {"hexsha": "6b26d1408ec40b78eb43305b410207167bd35265", "size": 12035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rawor/pyRawor.cpp", "max_stars_repo_name": "dpearson1983/rawor", "max_stars_repo_head_hexsha": "7f7be1d6330a3a559ab9764889dd45e2ca363708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rawor/pyRawor.cpp", "max_issues_repo_name": "dpearson1983/rawor", "max_issues_repo_head_hexsha": "7f7be1d6330a3a559ab9764889dd45e2ca363708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rawor/pyRawor.cpp", "max_forks_repo_name": "dpearson1983/rawor", "max_forks_repo_head_hexsha": "7f7be1d6330a3a559ab9764889dd45e2ca363708", "max_forks_repo_licenses": ["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.293255132, "max_line_length": 112, "alphanum_fraction": 0.5533028666, "num_tokens": 4040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5913019445574769}}
{"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 <Eigen/SVD>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\nvoid find_feature_matches (\n    const Mat& img_1, const Mat& img_2,\n    std::vector<KeyPoint>& keypoints_1,\n    std::vector<KeyPoint>& keypoints_2,\n    std::vector< DMatch >& matches );\n\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nvoid pose_estimation_3d3d (\n    const vector<Point3f>& pts1,\n    const vector<Point3f>& pts2,\n    Mat& R, Mat& t\n);\n\nvoid bundleAdjustment(\n    const vector<Point3f>& points_3d,\n    const vector<Point3f>& points_2d,\n    Mat& R, Mat& t\n);\n\n// g2o edge\nclass EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3Expmap>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    EdgeProjectXYZRGBDPoseOnly( const Eigen::Vector3d& point ) : _point(point) {}\n\n    virtual void computeError()\n    {\n        const g2o::VertexSE3Expmap* pose = static_cast<const g2o::VertexSE3Expmap*> ( _vertices[0] );\n        // measurement is p, point is p'\n        _error = _measurement - pose->estimate().map( _point );\n    }\n    \n    virtual void linearizeOplus()\n    {\n        g2o::VertexSE3Expmap* pose = static_cast<g2o::VertexSE3Expmap *>(_vertices[0]);\n        g2o::SE3Quat T(pose->estimate());\n        Eigen::Vector3d xyz_trans = T.map(_point);\n        double x = xyz_trans[0];\n        double y = xyz_trans[1];\n        double z = xyz_trans[2];\n        \n        _jacobianOplusXi(0,0) = 0;\n        _jacobianOplusXi(0,1) = -z;\n        _jacobianOplusXi(0,2) = y;\n        _jacobianOplusXi(0,3) = -1;\n        _jacobianOplusXi(0,4) = 0;\n        _jacobianOplusXi(0,5) = 0;\n        \n        _jacobianOplusXi(1,0) = z;\n        _jacobianOplusXi(1,1) = 0;\n        _jacobianOplusXi(1,2) = -x;\n        _jacobianOplusXi(1,3) = 0;\n        _jacobianOplusXi(1,4) = -1;\n        _jacobianOplusXi(1,5) = 0;\n        \n        _jacobianOplusXi(2,0) = -y;\n        _jacobianOplusXi(2,1) = x;\n        _jacobianOplusXi(2,2) = 0;\n        _jacobianOplusXi(2,3) = 0;\n        _jacobianOplusXi(2,4) = 0;\n        _jacobianOplusXi(2,5) = -1;\n    }\n\n    bool read ( istream& in ) {}\n    bool write ( ostream& out ) const {}\nprotected:\n    Eigen::Vector3d _point;\n};\n\nint main ( int argc, char** argv )\n{\n    if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d3d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    //-- 读取图像\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"一共找到了\"<<matches.size() <<\"组匹配点\"<<endl;\n\n    // 建立3D点\n    Mat depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\n    Mat depth2 = imread ( argv[4], 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> pts1, pts2;\n\n    for ( DMatch m:matches )\n    {\n        ushort d1 = depth1.ptr<unsigned short> ( int ( keypoints_1[m.queryIdx].pt.y ) ) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n        ushort d2 = depth2.ptr<unsigned short> ( int ( keypoints_2[m.trainIdx].pt.y ) ) [ int ( keypoints_2[m.trainIdx].pt.x ) ];\n        if ( d1==0 || d2==0 )   // bad depth\n            continue;\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n        Point2d p2 = pixel2cam ( keypoints_2[m.trainIdx].pt, K );\n        float dd1 = float ( d1 ) /1000.0;\n        float dd2 = float ( d2 ) /1000.0;\n        pts1.push_back ( Point3f ( p1.x*dd1, p1.y*dd1, dd1 ) );\n        pts2.push_back ( Point3f ( p2.x*dd2, p2.y*dd2, dd2 ) );\n    }\n\n    cout<<\"3d-3d pairs: \"<<pts1.size() <<endl;\n    Mat R, t;\n    pose_estimation_3d3d ( pts1, pts2, R, t );\n    cout<<\"ICP via SVD results: \"<<endl;\n    cout<<\"R = \"<<R<<endl;\n    cout<<\"t = \"<<t<<endl;\n    cout<<\"R_inv = \"<<R.t() <<endl;\n    cout<<\"t_inv = \"<<-R.t() *t<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n    bundleAdjustment( pts1, pts2, R, t );\n    \n    // verify p1 = R*p2 + t\n    for ( int i=0; i<5; i++ )\n    {\n        cout<<\"p1 = \"<<pts1[i]<<endl;\n        cout<<\"p2 = \"<<pts2[i]<<endl;\n        cout<<\"(R*p2+t) = \"<< \n            R * (Mat_<double>(3,1)<<pts2[i].x, pts2[i].y, pts2[i].z) + t\n            <<endl;\n        cout<<endl;\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{\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\nvoid pose_estimation_3d3d (\n    const vector<Point3f>& pts1,\n    const vector<Point3f>& pts2,\n    Mat& R, Mat& t\n)\n{\n    Point3f p1, p2;     // center of mass\n    int N = pts1.size();\n    for ( int i=0; i<N; i++ )\n    {\n        p1 += pts1[i];\n        p2 += pts2[i];\n    }\n    p1 = Point3f( Vec3f(p1) /  N);\n    p2 = Point3f( Vec3f(p2) / N);\n    vector<Point3f>     q1 ( N ), q2 ( N ); // remove the center\n    for ( int i=0; i<N; i++ )\n    {\n        q1[i] = pts1[i] - p1;\n        q2[i] = pts2[i] - p2;\n    }\n\n    // compute q1*q2^T\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    for ( int i=0; i<N; i++ )\n    {\n        W += Eigen::Vector3d ( q1[i].x, q1[i].y, q1[i].z ) * Eigen::Vector3d ( q2[i].x, q2[i].y, q2[i].z ).transpose();\n    }\n    cout<<\"W=\"<<W<<endl;\n\n    // SVD on W\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd ( W, Eigen::ComputeFullU|Eigen::ComputeFullV );\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n    cout<<\"U=\"<<U<<endl;\n    cout<<\"V=\"<<V<<endl;\n\n    Eigen::Matrix3d R_ = U* ( V.transpose() );\n    Eigen::Vector3d t_ = Eigen::Vector3d ( p1.x, p1.y, p1.z ) - R_ * Eigen::Vector3d ( p2.x, p2.y, p2.z );\n\n    // convert to cv::Mat\n    R = ( Mat_<double> ( 3,3 ) <<\n          R_ ( 0,0 ), R_ ( 0,1 ), R_ ( 0,2 ),\n          R_ ( 1,0 ), R_ ( 1,1 ), R_ ( 1,2 ),\n          R_ ( 2,0 ), R_ ( 2,1 ), R_ ( 2,2 )\n        );\n    t = ( Mat_<double> ( 3,1 ) << t_ ( 0,0 ), t_ ( 1,0 ), t_ ( 2,0 ) );\n}\n\nvoid bundleAdjustment (\n    const vector< Point3f >& pts1,\n    const vector< Point3f >& pts2,\n    Mat& R, Mat& t )\n{\n    // 初始化g2o\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose维度为 6, landmark 维度为 3\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverEigen<Block::PoseMatrixType>(); // 线性方程求解器\n    Block* solver_ptr = new Block( linearSolver );      // 矩阵块求解器\n    g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm( solver );\n\n    // vertex\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n    pose->setId(0);\n    pose->setEstimate( g2o::SE3Quat(\n        Eigen::Matrix3d::Identity(),\n        Eigen::Vector3d( 0,0,0 )\n    ) );\n    optimizer.addVertex( pose );\n\n    // edges\n    int index = 1;\n    vector<EdgeProjectXYZRGBDPoseOnly*> edges;\n    for ( size_t i=0; i<pts1.size(); i++ )\n    {\n        EdgeProjectXYZRGBDPoseOnly* edge = new EdgeProjectXYZRGBDPoseOnly( \n            Eigen::Vector3d(pts2[i].x, pts2[i].y, pts2[i].z) );\n        edge->setId( index );\n        edge->setVertex( 0, dynamic_cast<g2o::VertexSE3Expmap*> (pose) );\n        edge->setMeasurement( Eigen::Vector3d( \n            pts1[i].x, pts1[i].y, pts1[i].z) );\n        edge->setInformation( Eigen::Matrix3d::Identity()*1e4 );\n        optimizer.addEdge(edge);\n        index++;\n        edges.push_back(edge);\n    }\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.setVerbose( true );\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2-t1);\n    cout<<\"optimization costs time: \"<<time_used.count()<<\" seconds.\"<<endl;\n\n    cout<<endl<<\"after optimization:\"<<endl;\n    cout<<\"T=\"<<endl<<Eigen::Isometry3d( pose->estimate() ).matrix()<<endl;\n    \n}\n", "meta": {"hexsha": "9c8e26968b09341046e73120f1c0311c4d8bfe80", "size": 10394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d3d.cpp", "max_stars_repo_name": "renzhuli/SLAM", "max_stars_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T19:29:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-03T14:39:41.000Z", "max_issues_repo_path": "ch7/pose_estimation_3d3d.cpp", "max_issues_repo_name": "renzhuli/SLAM", "max_issues_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/pose_estimation_3d3d.cpp", "max_forks_repo_name": "renzhuli/SLAM", "max_forks_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T07:18:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T11:52:23.000Z", "avg_line_length": 33.2076677316, "max_line_length": 129, "alphanum_fraction": 0.5872618819, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.591301927319105}}
{"text": "/*\n\t[Vc,Fc] = cut_mesh_mex(V,F);\n    V, F: vertices/faces of input mesh (any topology, with/without boundary)\n    Vc, Fc: vertices/faces of cut mesh\n*/\n\n#include <iostream>\n#include <stdlib.h>     /* srand, rand */\n\n#include \"mex.h\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <igl/matlab_format.h>\n#include <igl/adjacency_matrix.h>\n#include <igl/boundary_loop.h>\n#include \"polyvector_field_cut_mesh_with_singularities_randomized.h\"\n#include <igl/cut_mesh.h>\n#include <igl/euler_characteristic.h>\n\nusing namespace std;\n\nvoid mexFunction(\tint nlhs, mxArray *plhs[], \n\t\t\t\t int nrhs, const mxArray*prhs[] ) \n{ \n\t/* retrieve arguments */\n\tif( nrhs!=2 ) \n\t\tmexErrMsgTxt(\"2 input arguments are required - faces and vertices.\"); \n\tif( nlhs<2 ) \n\t\tmexErrMsgTxt(\"2 output arguments are required - faces and vertices.\"); \n\n\t// first argument : vertices\n    double *V_mex = mxGetPr(prhs[0]);\n    int nV = (int)mxGetM(prhs[0]);\n    int cV = (int)mxGetN(prhs[0]);    \n\tif( cV!=3 ) \n\t\tmexErrMsgTxt(\"Vertices should be an #V x 3 matrix.\");     \n    Eigen::MatrixXd V = Eigen::Map<Eigen::MatrixXd>(V_mex,nV,3);\n\n\t// second argument : faces\n    double *F_mex = mxGetPr(prhs[1]);\n    int nF = (int)mxGetM(prhs[1]);\n    int cF = (int)mxGetN(prhs[1]);    \n\tif( cF!=3 ) \n\t\tmexErrMsgTxt(\"Faces should be an #F x 3 matrix.\");     \n    Eigen::MatrixXd Fd = Eigen::Map<Eigen::MatrixXd>(F_mex,nF,3);\n    Eigen::MatrixXi F = Fd.cast<int> ();\n    // C-based indexing\n    F = F.array() -1;\n      \n    // compute Euler characteristic of input mesh\n    int e_in = igl::euler_characteristic(V, F);\n    // compute number of boundaries in input mesh\n    std::vector<std::vector<int> > L;\n    igl::boundary_loop(F,L);    \n    int b_in = L.size();\n    // compute genus of input mesh\n    int g_in =(2-b_in-e_in)/2;\n    cerr<<\" -> Input mesh: e = \"<<e_in<<\", b = \"<<b_in<<\", g= \"<<g_in<<endl;\n    \n    // for genus zero we need to add two non-adjacent singularities\n    Eigen::VectorXi singularities;\n    if (g_in ==0)\n    {\n        // generate two random singularities between 0 and nV-1:\n        int s0 = rand() % nV ;\n        // make sure singus aren't adjacent\n        Eigen::SparseMatrix<int> A;\n        igl::adjacency_matrix(F,A);        \n        int s1 = s0;        \n        while (s1==s0 || A.coeff(s0,s1) == 1)\n            s1 = rand() % nV ;\n        \n        singularities.setZero(2,1);\n        singularities<<s0,s1;\n    }\n    \n        \n        \n    // generate cuts using tree traversal: a boolean per face edge\n    Eigen::MatrixXi cuts;\n    polyvector_field_cut_mesh_with_singularities_randomized(V, F, singularities, cuts);\n    \n    // duplicate vertices along cut to produce cut mesh\n    Eigen::MatrixXd Vc;\n    Eigen::MatrixXi Fc;\n    igl::cut_mesh(V, F, cuts, Vc, Fc);\n\n    // compute Euler characteristic of output mesh\n    // this should be 1 ALWAYS (disk topology)\n    int e_out = igl::euler_characteristic(Vc, Fc);\n    // compute number of boundaries in input mesh\n    std::vector<std::vector<int> > Lc;\n    igl::boundary_loop(Fc,Lc);    \n    int b_out = Lc.size();\n    // compute genus of input mesh\n    int g_out =(2-b_out-e_out)/2;\n    cerr<<\" -> Output mesh: e = \"<<e_out<<\", b = \"<<b_out<<\", g= \"<<g_out<<endl;\n\n    if( e_out!=1 ) \n\t\tmexErrMsgTxt(\"Output mesh does not have disk topology.\"); \n\n\t// first output : vertices of cut mesh\n\tplhs[0] = mxCreateDoubleMatrix(Vc.rows(), 3, mxREAL); \n    Eigen::Map<Eigen::MatrixXd>( mxGetPr(plhs[0]), Vc.rows(), Vc.cols() ) = Vc;\n    \n\t// second output : faces of cut mesh\n    Eigen::MatrixXd Fc_d = Fc.cast<double>();\n    // matlab-based indexing\n    Fc_d = Fc_d.array() + 1;    \n\tplhs[1] = mxCreateDoubleMatrix(Fc.rows(), 3, mxREAL); \n    Eigen::Map<Eigen::MatrixXd>( mxGetPr(plhs[1]), Fc_d.rows(), Fc_d.cols() ) = Fc_d;\n\n\treturn;\n}\n", "meta": {"hexsha": "07510b58e196c82c029845f7582af3e34c143079", "size": 3773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/cutting/cut_mesh_mex.cpp", "max_stars_repo_name": "weify627/mapnet", "max_stars_repo_head_hexsha": "4cb5fdbaaaa5aa9bd2b2e4f883f3bb65569574ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab/cutting/cut_mesh_mex.cpp", "max_issues_repo_name": "weify627/mapnet", "max_issues_repo_head_hexsha": "4cb5fdbaaaa5aa9bd2b2e4f883f3bb65569574ec", "max_issues_repo_licenses": ["MIT"], "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/cutting/cut_mesh_mex.cpp", "max_forks_repo_name": "weify627/mapnet", "max_forks_repo_head_hexsha": "4cb5fdbaaaa5aa9bd2b2e4f883f3bb65569574ec", "max_forks_repo_licenses": ["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.525862069, "max_line_length": 87, "alphanum_fraction": 0.6180758017, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5912911077688304}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/point_inertial.h\"\n// Simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\n// Linear Algebra\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// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg<TypeVector<Eigen::Dynamic>, TypeView>;\n// Flow\nusing TypeFlow = Flow<TypeSpaceVector, TypeRef>;\n\nint main () { \n    TypeSpaceVector x0 = TypeSpaceVector::Constant(1.0);\n    double t0 = 0.0;\n    double dt = 1e-3;\n    double tEnd = 1.0;\n    unsigned int nt = std::round((tEnd - t0) / dt);\n    // Create point\n    sl0::PointInertial<TypeVector, DIM, TypeView, TypeFlow, TypeSolver> point(std::make_shared<TypeFlow>(), 1.0);\n    // Set initial state\n    point.sStep->x(point.state.data()) = x0;\n    point.t = t0;\n    // Computation\n    for(std::size_t i = 0; i < nt; i++) {\n        point.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"Point advected following a an exponential flow, exp(\" << point.t << \") = \" << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"Point Final Position : \" << \"\\n\" << point.sStep->x(point.state.data()) << \"\\n\";\n    std::cout << \"Point Final Velocity : \" << \"\\n\" << point.sStep->u(point.state.data()) << \"\\n\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "f6e865e20f594d1354e3dd0c784230cb2d410b19", "size": 1635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/point/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/point/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/point/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": 31.4423076923, "max_line_length": 113, "alphanum_fraction": 0.6385321101, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5910782342556162}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#include <string>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/opencv.hpp>\n//#include <opencv2/legacy/compat.hpp>\n\n#include \"dlib/opencv.h\"\n#include \"dlib/image_processing/frontal_face_detector.h\"\n#include \"dlib/image_processing/render_face_detections.h\"\n#include \"dlib/gui_widgets.h\"\n#include <dlib/image_processing.h>\n\n#include \"util.h\"\n#include \"faceDetection.h\"\n\ndouble get_conversion_factor (dlib::full_object_detection shape, FacePose* face_pose, double magnitude_normal, int mode) {\n\tcv::Point p1, p2;\n    //mode : 1 for left eye, 2 for right eye\n\tif(mode == 1) {\n\t\tp1 = cv::Point(shape.part(42).x(), shape.part(42).y());\n\t\tp2 = cv::Point(shape.part(45).x(), shape.part(45).y());\n\t}\n\telse if(mode == 2) {\n\t\tp1 = cv::Point(shape.part(36).x(), shape.part(36).y());\n\t\tp2 = cv::Point(shape.part(39).x(), shape.part(39).y());\n\t}\n\n\tdouble dx = p1.x - p2.x, dy = p1.y - p2.y;\n\tdouble temp1, temp2, beta;\n\tdouble n1 = face_pose->normal[0], n2 = face_pose->normal[1], n3 = face_pose->normal[2];\n\tdouble beta_old = sqrt(dx*dx + dy*dy)/magnitude_normal;\n\n\ttemp1 = dx*dx*(1.0 - n2*n2);\n\ttemp2 = dy*dy*(1.0 - n1*n1);\n\n\tbeta = sqrt(temp1 + temp2)/((double)(magnitude_normal*fabs(n3)));\n\tbeta = 1.0/((double) beta);\n\n\t//std::cout<<\"Beta : \"<<beta<<std::endl;\n\treturn beta;\n}\n\nvoid compute_vec_LR (cv::Point p1, cv::Point p2, FacePose* face_pose, std::vector<double>& LR) {\n\tdouble scale = 20.784/30.0;\n\n\tLR[0] = p1.x - p2.x;\n\tLR[1] = p1.y - p2.y;\n\tLR[0] = LR[0]*scale;\n\tLR[1] = LR[1]*scale;\n\tLR[2] = -(LR[0]*face_pose->normal[0] + LR[1]*face_pose->normal[1])/face_pose->normal[3];\n}\n\nvoid get_quadratic_solution (std::vector<double> coeff, double& solution, int mode) {\n\tsolution = (-coeff[1] + mode*sqrt(coeff[1]*coeff[1] - 4*coeff[0]*coeff[2]))/(2*coeff[0]);\n\tstd::cout<<\"soln : \"<<solution<<std::endl;\n}\n\nvoid get_quadratic_equation (std::vector<double> coeff, std::vector<double>& quad_eqn) {\n\tquad_eqn[0] = coeff[0]*coeff[0];\n\tquad_eqn[1] = 2*coeff[0]*coeff[1];\n\tquad_eqn[2] = coeff[1]*coeff[1];\n}\n\nvoid solve(std::vector<double> coeff_1, double const_1, std::vector<double> coeff_2, double const_2, double mag, std::vector<double>& vec, int mode) {\n\tdouble det = coeff_1[0]*coeff_2[1] - coeff_1[1]*coeff_2[0];\n\n\tstd::vector<double> linear_eqn_1(2), linear_eqn_2(2);\n\tlinear_eqn_1[0] = (coeff_1[1]*coeff_2[2] - coeff_1[2]*coeff_2[1])/det;\n\tlinear_eqn_1[1] = (const_1*coeff_2[1] - coeff_1[1]*const_2)/det;\n\tlinear_eqn_2[0] = (coeff_1[2]*coeff_2[0] - coeff_1[0]*coeff_2[2])/det;\n\tlinear_eqn_2[1] = (coeff_1[0]*const_2 - coeff_2[0]*const_1)/det;\n\n\tstd::vector<double> quad_eqn_1(3), quad_eqn_2(3), quad_eqn_final(3);\n\tget_quadratic_equation(linear_eqn_1, quad_eqn_1);\n\tget_quadratic_equation(linear_eqn_2, quad_eqn_2);\n\n\tquad_eqn_final[0] = quad_eqn_1[0] + quad_eqn_2[0] + 1;\n\tquad_eqn_final[1] = quad_eqn_1[1] + quad_eqn_2[1];\n\tquad_eqn_final[2] = quad_eqn_1[2] + quad_eqn_2[2] - mag*mag;\n\n\t//std::cout<<\"const_1 : \"<<const_1<<\" const_2 : \"<<const_2<<std::endl;\n\tstd::vector<double> coeff = quad_eqn_final;\n\tstd::cout<<\"Discriminant : \"<<coeff[1]*coeff[1] - 4*coeff[0]*coeff[2]<<std::endl;\n\tlog_vec(\"quad_eqn_final\", quad_eqn_final);\n\tget_quadratic_solution (quad_eqn_final, vec[2], mode);\n\tvec[0] = linear_eqn_1[0]*vec[2] + linear_eqn_1[1];\n\tvec[1] = linear_eqn_2[0]*vec[2] + linear_eqn_2[1];\n}\n\nvoid get_section(cv::Point p1, cv::Point p2, cv::Point pupil, double& Y1, double& Y2, double& h) {\n\tstd::vector<double> line(3);\n\n\tline[0] = p2.y - p1.y;\n\tline[1] = -(p2.x - p1.x);\n\tline[2] =  p1.y*(p2.x - p1.x) - p1.x*(p2.y - p1.y);\n\n\tcv::Point pupil_proj;\n\tpupil_proj.x = -(line[0]*pupil.x + line[1]*pupil.y + line[2])*line[0]/(line[0]*line[0] + line[1]*line[1]) + pupil.x;\n\tpupil_proj.y = -(line[0]*pupil.x + line[1]*pupil.y + line[2])*line[1]/(line[0]*line[0] + line[1]*line[1]) + pupil.y;\n\n\tY1 = get_distance (p1, pupil_proj);\n\tY2 = get_distance (p2, pupil_proj);\n\th = get_distance (pupil, pupil_proj);\n}\n\n//List : Y1, Y2 can be interchanged. Magnitudes of the vectors in real world may be wrong.\n//\t\t mag_LR square changed to just mag_LR.\n\nvoid compute_vec_CP(cv::Point p1, cv::Point p2, cv::Point pupil, cv::Rect rect, FacePose* face_pose, \n\tstd::vector<double> vec_CR_u, double mag_CR, std::vector<double> vec_LR_u, double mag_LR, \n\tstd::vector<double> vec_UD_u, double mag_CP, std::vector<double>& vec_CP, double S2R, int mode) {\n\tdouble Y1, Y2, H;\n\tget_section(p1, p2, cv::Point(pupil.x + rect.x, pupil.y + rect.y), Y1, Y2, H);\n\n\tdouble const_1, const_2;\n\tconst_1 = (S2R*H);///std::cos(face_pose->pitch);\n\tif(mode == 1) {\n\t\tconst_2 = mag_CR*(scalar_product(vec_CR_u, vec_LR_u)) + ((mag_LR*Y1)/((double) (Y1 + Y2)));\n\t}\n\telse if(mode == 2) {\n\t\tconst_2 = mag_CR*(scalar_product(vec_CR_u, vec_LR_u)) + ((mag_LR*Y2)/((double) (Y1 + Y2)));\n\t}\n\n\t//std::cout<<\"Y1 : \"<<Y1<<\" Y2 : \"<<Y2<<\" H : \"<<H<<std::endl;\n\tstd::cout<<\"CP - constants : \"<<const_1<<\" \"<<const_2<<std::endl;\n\n\tsolve(vec_UD_u, const_1, vec_LR_u, const_2, mag_CP, vec_CP, 1);\n}\n\nbool vec_isnan(std::vector<double>& vec) {\n\tint f = 0;\n\tfor(int i=0; i<vec.size(); i++) {\n\t\tif(std::isnan(vec[i])) {\n\t\t\tf=1;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(f) {\n\t\tfor(int i=0; i<vec.size(); i++) {\n\t\t\tvec[i] = 0.0;\n\t\t}\n\t}\n\n\treturn (1-f);\n}\n\nvoid compute_eye_gaze (FacePose* face_pose, dlib::full_object_detection shape, cv::Rect rect, cv::Point pupil, double mag_CP, double mag_LR, double mag_CR, double mag_CM, double theta, int mode, std::vector<double>& vec_CP) {\n\n\tstd::vector<double> vec_LR_u(3), vec_RP(3), vec_CR_u(3), vec_CM_u(3), vec_UD_u(3);\n\tstd::vector<double> vec_CP_l(3), vec_CP_r(3);\n\tdouble S2R = get_conversion_factor(shape, face_pose, mag_CM, mode);\n\n\tcv::Point p1, p2;\n    //mode : 1 for left eye, 2 for right eye\n\tif(mode == 1) {\n\t\tp1 = cv::Point(shape.part(42).x(), shape.part(42).y());\n\t\tp2 = cv::Point(shape.part(45).x(), shape.part(45).y());\n\t}\n\telse if(mode == 2) {\n\t\tp1 = cv::Point(shape.part(36).x(), shape.part(36).y());\n\t\tp2 = cv::Point(shape.part(39).x(), shape.part(39).y());\n\t}\n\n\tvec_CP[0] = 1.0;\n\tvec_CP[1] = 1.0;\n\tvec_CP[2] = 1.0;\n\n\tcompute_vec_LR(p1, p2, face_pose, vec_LR_u);\n\tmake_unit_vector(vec_LR_u, vec_LR_u);\n\n\t//log_vec(\"LR\", vec_LR_u);\n\n\tvec_CM_u[0] = face_pose->normal[0];\n\tvec_CM_u[1] = face_pose->normal[1];\n\tvec_CM_u[2] = face_pose->normal[2];\n\n\tcross_product(vec_CM_u, vec_LR_u, vec_UD_u);\n\tmake_unit_vector(vec_UD_u, vec_UD_u);\n\n\t//log_vec(\"UD\", vec_UD_u);\n\n\tdouble const_1 = std::cos(theta/2.0);\n\tdouble const_2 = 0.0;\n\n\tsolve(vec_UD_u, const_1, vec_CM_u, const_2, 1.0, vec_CR_u, -1);\n\tmake_unit_vector(vec_CR_u, vec_CR_u);\n\n\t//log_vec(\"CR\", vec_CR_u);\n\n\tcompute_vec_CP(p1, p2, pupil, rect, face_pose, vec_CR_u, mag_CR, vec_LR_u, mag_LR,\n\t\tvec_UD_u, mag_CP, vec_CP_l, S2R, 2);\n\n\tcompute_vec_CP(p1, p2, pupil, rect, face_pose, vec_CR_u, mag_CR, vec_LR_u, mag_LR,\n\t\tvec_UD_u, mag_CP, vec_CP_r, S2R, 1);\n\n\tdouble f1 = vec_isnan(vec_CP_l);\n\tdouble f2 = vec_isnan(vec_CP_r);\n\n\tif(f1 || f2) {\n\t\t\tvec_CP[0] = (vec_CP_l[0] + vec_CP_r[0]);\n\t\t\tvec_CP[1] = (vec_CP_l[1] + vec_CP_r[1]);\n\t\t\tvec_CP[2] = (vec_CP_l[2] + vec_CP_r[2]);\t\t\n\t}\n\telse {\n\t\tvec_CP[0] = (vec_CP_l[0] + vec_CP_r[0])/2.0;\n\t\tvec_CP[1] = (vec_CP_l[1] + vec_CP_r[1])/2.0;\n\t\tvec_CP[2] = (vec_CP_l[2] + vec_CP_r[2])/2.0;\n\t}\n\n\tlog_vec(\"CP_l\", vec_CP_l);\n\tlog_vec(\"CP_r\", vec_CP_r);\n\tlog_vec(\"CP\", vec_CP);\n}\n", "meta": {"hexsha": "2258de8a4af93dad56cc616c0c81b3a24b8d39f1", "size": 7292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gazeDetection.cpp", "max_stars_repo_name": "vmthanh/Eye-Tracking", "max_stars_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gazeDetection.cpp", "max_issues_repo_name": "vmthanh/Eye-Tracking", "max_issues_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gazeDetection.cpp", "max_forks_repo_name": "vmthanh/Eye-Tracking", "max_forks_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6036866359, "max_line_length": 225, "alphanum_fraction": 0.6559243006, "num_tokens": 2740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5910745342453172}}
{"text": "// Copyright (c) 2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <drake/math/discrete_algebraic_riccati_equation.h>\n#include <frc/system/Discretization.h>\n#include <units/time.h>\n\n#include \"controllers/DARE.hpp\"\n\nnamespace frc3512 {\n\n/**\n * Returns the LQR controller gain for the given coefficients and plant.\n *\n * @param A  Continuous system matrix of the plant being controlled.\n * @param B  Continuous input matrix of the plant being controlled.\n * @param Q  The state cost matrix.\n * @param R  The input cost matrix.\n * @param dt Discretization timestep.\n */\ntemplate <int States, int Inputs>\nEigen::Matrix<double, Inputs, States> LQR(\n    const Eigen::Matrix<double, States, States>& A,\n    const Eigen::Matrix<double, States, Inputs>& B,\n    const Eigen::Matrix<double, States, States>& Q,\n    const Eigen::Matrix<double, Inputs, Inputs>& R, units::second_t dt) {\n    Eigen::Matrix<double, States, States> discA;\n    Eigen::Matrix<double, States, Inputs> discB;\n    frc::DiscretizeAB<States, Inputs>(A, B, dt, &discA, &discB);\n\n    Eigen::Matrix<double, States, States> S =\n        drake::math::DiscreteAlgebraicRiccatiEquation(discA, discB, Q, R);\n    return (discB.transpose() * S * discB + R)\n        .llt()\n        .solve(discB.transpose() * S * discA);\n}\n\n/**\n * Returns the LQR controller gain for the given coefficients and plant.\n *\n * @param A Discrete system matrix of the plant being controlled.\n * @param B Discrete input matrix of the plant being controlled.\n * @param Q The state cost matrix.\n * @param R The input cost matrix.\n * @param N The state-input cross-term cost matrix.\n */\ntemplate <int States, int Inputs>\nEigen::Matrix<double, Inputs, States> LQR(\n    const Eigen::Matrix<double, States, States>& A,\n    const Eigen::Matrix<double, States, Inputs>& B,\n    const Eigen::Matrix<double, States, States>& Q,\n    const Eigen::Matrix<double, Inputs, Inputs>& R,\n    const Eigen::Matrix<double, States, Inputs>& N) {\n    Eigen::Matrix<double, States, States> S =\n        DARE<States, Inputs>(A, B, Q, R, N);\n    return (B.transpose() * S * B + R)\n        .llt()\n        .solve(B.transpose() * S * A + N.transpose());\n}\n\n}  // namespace frc3512\n", "meta": {"hexsha": "0503f97721795d984f89bd53fd6be66d12d91659", "size": 2237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/LQR.hpp", "max_stars_repo_name": "frc3512/Robot-2020", "max_stars_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T04:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:13:39.000Z", "max_issues_repo_path": "src/main/include/controllers/LQR.hpp", "max_issues_repo_name": "frc3512/Robot-2020", "max_issues_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T03:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:14:38.000Z", "max_forks_repo_path": "src/main/include/controllers/LQR.hpp", "max_forks_repo_name": "frc3512/Robot-2020", "max_forks_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:10:01.000Z", "avg_line_length": 34.4153846154, "max_line_length": 74, "alphanum_fraction": 0.6808225302, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5910745342453171}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n#include <Eigen/IterativeLinearSolvers> \n\nusing namespace Eigen;\n\ntypedef SparseMatrix<double, ColMajor> MySparseMatrix;\n\nextern \"C\" {\n\nint solve_eigen_icholt_coo(\n    const double *coo_data,\n    const int *row,\n    const int *col,\n    int nnz,\n    const double *b,\n    double *x,\n    int n,\n    double rtol,\n    double initial_shift\n){\n    MySparseMatrix A(n, n);\n    \n    std::vector<Triplet<double> > triplets(nnz);\n    \n    for (int k = 0; k < nnz; k++){\n        triplets[k] = Triplet<double>(row[k], col[k], coo_data[k]);\n    }\n    \n    A.setFromTriplets(triplets.begin(), triplets.end());\n    \n    A.makeCompressed();\n    \n    VectorXd b_temp(n);\n    \n    for (int k = 0; k < n; k++){\n        b_temp[k] = b[k];\n    }\n    \n    typedef IncompleteCholesky<double> Preconditioner;\n    ConjugateGradient<MySparseMatrix, Lower, Preconditioner> solver;\n    \n    solver.preconditioner().setInitialShift(initial_shift);\n    \n    solver.setTolerance(rtol);\n    \n    solver.compute(A);\n    \n    VectorXd x_temp = solver.solve(b_temp);\n\n    for (int k = 0; k < n; k++){\n        x[k] = x_temp[k];\n    }\n    \n    return 0;\n}\n\nint solve_eigen_cholesky_coo(\n    const double *coo_data,\n    const int *row,\n    const int *col,\n    int nnz,\n    const double *b,\n    double *x,\n    int n,\n    double rtol,\n    double initial_shift\n){\n    MySparseMatrix A(n, n);\n    \n    std::vector<Triplet<double> > triplets(nnz);\n    \n    for (int k = 0; k < nnz; k++){\n        triplets[k] = Triplet<double>(row[k], col[k], coo_data[k]);\n    }\n    \n    A.setFromTriplets(triplets.begin(), triplets.end());\n    \n    A.makeCompressed();\n    \n    VectorXd b_temp(n);\n    \n    for (int k = 0; k < n; k++){\n        b_temp[k] = b[k];\n    }\n    \n    SimplicialLDLT<MySparseMatrix> solver;\n    \n    solver.analyzePattern(A);\n    \n    solver.factorize(A);\n    \n    VectorXd x_temp = solver.solve(b_temp);\n\n    for (int k = 0; k < n; k++){\n        x[k] = x_temp[k];\n    }\n    \n    return 0;\n}\n\n}\n", "meta": {"hexsha": "2032838384ac072a551838a7427b42d02306f523", "size": 2040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/solve_eigen.cpp", "max_stars_repo_name": "chendeheng611/pymatting", "max_stars_repo_head_hexsha": "06689a44e34eabc5edb81c7bd99e1f039796bd15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1195.0, "max_stars_repo_stars_event_min_datetime": "2020-01-24T14:40:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:01:43.000Z", "max_issues_repo_path": "benchmarks/solve_eigen.cpp", "max_issues_repo_name": "chendeheng611/pymatting", "max_issues_repo_head_hexsha": "06689a44e34eabc5edb81c7bd99e1f039796bd15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2020-01-25T07:24:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T06:22:44.000Z", "max_forks_repo_path": "benchmarks/solve_eigen.cpp", "max_forks_repo_name": "chendeheng611/pymatting", "max_forks_repo_head_hexsha": "06689a44e34eabc5edb81c7bd99e1f039796bd15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 159.0, "max_forks_repo_forks_event_min_datetime": "2020-01-24T18:28:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:31:02.000Z", "avg_line_length": 19.6153846154, "max_line_length": 68, "alphanum_fraction": 0.5764705882, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5910582965122541}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <CGAL/Triangulation_data_structure_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<int, K> Vb;\ntypedef CGAL::Triangulation_face_base_2<K> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Triangulation;\n\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 TreeEdge\n{\n  int i1, i2;\n  double sq_dist;\n};\n\nstruct GraphProblem\n{\n  std::vector<int> nearest_tree_by_bone;\n  std::vector<double> bone_tree_sq_dists;\n  std::vector<TreeEdge> tree_edges;\n};\n\ntypedef std::vector<std::pair<K::Point_2, int>> LocationVec;\n\nint binary_search_first(std::function<bool(int)> is_target)\n{\n  int upper_power = 0;\n  while (true)\n  {\n    int i = 1 << upper_power;\n    if (is_target(i))\n    {\n      break;\n    }\n    upper_power++;\n  }\n\n  int low = upper_power == 0 ? 0 : (1 << (upper_power - 1));\n  int high = 1 << upper_power;\n  while (low < high)\n  {\n    int mid = (low + high) / 2;\n    if (is_target(mid))\n    {\n      high = mid;\n    }\n    else\n    {\n      low = mid + 1;\n    }\n  }\n\n  assert(!is_target(high - 1) && is_target(high));\n  return high;\n}\n\nLocationVec read_locations(int n)\n{\n  LocationVec locations;\n  for (int i = 0; i < n; i++)\n  {\n    long x, y;\n    std::cin >> x >> y;\n    assert(abs(x) < (1 << 24) && abs(y) < (1 << 24));\n    locations.push_back(std::make_pair(K::Point_2(x, y), i));\n  }\n  return locations;\n}\n\nGraphProblem graph_problem_from_locations(const LocationVec &tree_locations, const LocationVec &bone_locations)\n{\n  Triangulation triangulation;\n  triangulation.insert(tree_locations.begin(), tree_locations.end());\n\n  GraphProblem g;\n\n  for (const auto &bone_location : bone_locations)\n  {\n    Triangulation::Vertex_handle vertex = triangulation.nearest_vertex(bone_location.first);\n    g.nearest_tree_by_bone.push_back(vertex->info());\n    g.bone_tree_sq_dists.push_back(CGAL::squared_distance(vertex->point(), bone_location.first));\n  }\n\n  for (auto it = triangulation.finite_edges_begin(); it != triangulation.finite_edges_end(); it++)\n  {\n    TreeEdge e;\n    e.i1 = it->first->vertex((it->second + 1) % 3)->info();\n    e.i2 = it->first->vertex((it->second + 2) % 3)->info();\n    if (e.i1 > e.i2)\n    {\n      std::swap(e.i1, e.i2);\n    }\n    e.sq_dist = triangulation.segment(it).squared_length();\n    g.tree_edges.push_back(e);\n  }\n\n  DEBUG(2, \"g.tree_edges.size() \" << g.tree_edges.size());\n\n  return g;\n}\n\nint count_reachable_bones(int n, double s, const GraphProblem &graph_problem)\n{\n  const int m = graph_problem.nearest_tree_by_bone.size();\n  assert(int(graph_problem.bone_tree_sq_dists.size()) == m);\n\n  std::vector<int> ds_rank(n);\n  std::vector<int> ds_parent(n);\n  boost::disjoint_sets<int *, int *> ds(ds_rank.data(), ds_parent.data());\n  for (int i = 0; i < n; i++)\n  {\n    ds.make_set(i);\n  }\n\n  for (const auto &edge : graph_problem.tree_edges)\n  {\n    DEBUG(2, \"tree edge \" << edge.i1 << \" \" << edge.i2 << \" \" << edge.sq_dist);\n    if (edge.sq_dist <= s)\n    {\n      DEBUG(2, \"union\");\n      ds.union_set(edge.i1, edge.i2);\n    }\n  }\n\n  std::vector<int> bones_per_component(n, 0);\n  for (int i = 0; i < m; i++)\n  {\n    if (4 * graph_problem.bone_tree_sq_dists.at(i) <= s)\n    {\n      bones_per_component.at(ds.find_set(graph_problem.nearest_tree_by_bone.at(i)))++;\n    }\n  }\n\n  return *std::max_element(bones_per_component.begin(), bones_per_component.end());\n}\n\nvoid testcase()\n{\n  int n, m, k;\n  double s;\n  std::cin >> n >> m >> s >> k;\n  assert(n >= 1 && n <= 4e4);\n  assert(m >= 1 && m <= 4e4);\n  assert(s >= 1 && s <= (1L << 51));\n  assert(k >= 1 && k <= m);\n\n  auto tree_locations = read_locations(n);\n  auto bone_locations = read_locations(m);\n\n  GraphProblem graph_problem = graph_problem_from_locations(tree_locations, bone_locations);\n\n  int a = count_reachable_bones(n, s, graph_problem);\n\n  std::vector<double> interesting_sq_dists;\n  for (const auto &e : graph_problem.tree_edges)\n  {\n    interesting_sq_dists.push_back(e.sq_dist);\n  }\n  for (const auto &sq_dist : graph_problem.bone_tree_sq_dists)\n  {\n    interesting_sq_dists.push_back(4 * sq_dist);\n  }\n  std::sort(interesting_sq_dists.begin(), interesting_sq_dists.end());\n\n  int critical_i = binary_search_first([&interesting_sq_dists, &graph_problem, n, k](int i) {\n    assert(i >= 0);\n    if (i >= int(interesting_sq_dists.size()))\n    {\n      return true;\n    }\n    return count_reachable_bones(n, interesting_sq_dists.at(i), graph_problem) >= k;\n  });\n  double q = interesting_sq_dists.at(critical_i);\n\n  std::cout << a << \" \" << q << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::fixed << std::setprecision(0);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "02825e6c8a77b1b1bd2135a7e2991da73811b6bb", "size": 5223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "potw/idefix/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/idefix/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/idefix/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.354368932, "max_line_length": 111, "alphanum_fraction": 0.6507754164, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5910582940994856}}
{"text": "#include <iostream>\n#include <stdio.h>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <ceres/ceres.h>\n#include <sophus/sim3.hpp>\n\n#include \"Sim3Optimizer.h\"\n\nclass PoseGraphError : public ceres::SizedCostFunction<7, 7, 7> {\npublic:\n  PoseGraphError(const Sophus::Sim3d &Sji,\n                 const Eigen::Matrix<double, 7, 7> &information)\n      : Sji_(Sji) {\n    Eigen::LLT<Eigen::Matrix<double, 7, 7>> llt(information);\n    sqrt_information_ = llt.matrixL();\n  }\n\n  // Si means world frame in i frame, S_iw\n  virtual bool Evaluate(double const *const *parameters_ptr,\n                        double *residuals_ptr, double **jacobians_ptr) const {\n    Eigen::Map<const Eigen::Matrix<double, 7, 1>> lie_j(*parameters_ptr);\n    Eigen::Map<const Eigen::Matrix<double, 7, 1>> lie_i(*(parameters_ptr + 1));\n\n    Sophus::Sim3d Si = Sophus::Sim3d::exp(lie_i);\n    Sophus::Sim3d Sj = Sophus::Sim3d::exp(lie_j);\n    Sophus::Sim3d error = Sji_ * Si * Sj.inverse();\n    Eigen::Map<Eigen::Matrix<double, 7, 1>> residuals(residuals_ptr);\n    residuals = error.log();\n\n    if (jacobians_ptr) {\n      Eigen::Matrix<double, 7, 7> Jacobian_i;\n      Eigen::Matrix<double, 7, 7> Jacobian_j;\n      Eigen::Matrix<double, 7, 7> Jr = Eigen::Matrix<double, 7, 7>::Zero();\n\n      Jr.block<3, 3>(0, 0) = Sophus::RxSO3d::hat(residuals.tail(4));\n      Jr.block<3, 3>(0, 3) = Sophus::SO3d::hat(residuals.head(3));\n      Jr.block<3, 1>(0, 6) = -residuals.head(3);\n      Jr.block<3, 3>(3, 3) = Sophus::SO3d::hat(residuals.block<3, 1>(3, 0));\n      Eigen::Matrix<double, 7, 7> I = Eigen::Matrix<double, 7, 7>::Identity();\n      Jr = sqrt_information_ * (I + 0.5 * Jr + 1.0 / 12. * (Jr * Jr));\n\n      Jacobian_i = Jr * Sj.Adj();\n      Jacobian_j = -Jacobian_i;\n      int k = 0;\n      for (int i = 0; i < 7; i++) {\n        for (int j = 0; j < 7; ++j) {\n          if (jacobians_ptr[0])\n            jacobians_ptr[0][k] = Jacobian_j(i, j);\n          if (jacobians_ptr[1])\n            jacobians_ptr[1][k] = Jacobian_i(i, j);\n          k++;\n        }\n      }\n    }\n    residuals = sqrt_information_ * residuals;\n    return true;\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  static ceres::CostFunction *\n  Create(const Sophus::Sim3d &Sji,\n         const Eigen::Matrix<double, 7, 7> &sqrt_information) {\n    return new PoseGraphError(Sji, sqrt_information);\n  }\n\nprivate:\n  const Sophus::Sim3d Sji_;\n  Eigen::Matrix<double, 7, 7> sqrt_information_;\n};\n\nSim3Optimizer::Sim3Optimizer() {}\n\nclass CERES_EXPORT Sim3Parameterization : public ceres::LocalParameterization {\npublic:\n  virtual ~Sim3Parameterization() {}\n  virtual bool Plus(const double *x, const double *delta,\n                    double *x_plus_delta) const;\n  virtual bool ComputeJacobian(const double *x, double *jacobian) const;\n  virtual int GlobalSize() const { return 7; }\n  virtual int LocalSize() const { return 7; }\n};\n\nbool Sim3Parameterization::Plus(const double *x, const double *delta,\n                                double *x_plus_delta) const {\n  Eigen::Map<const Eigen::Matrix<double, 7, 1>> lie(x);\n  Eigen::Map<const Eigen::Matrix<double, 7, 1>> delta_lie(delta);\n  Sophus::Sim3d T = Sophus::Sim3d::exp(lie);\n  Sophus::Sim3d delta_T = Sophus::Sim3d::exp(delta_lie);\n  Eigen::Map<Eigen::Matrix<double, 7, 1>> x_plus_delta_lie(x_plus_delta);\n  x_plus_delta_lie = (T * delta_T).log();\n  return true;\n}\n\nbool Sim3Parameterization::ComputeJacobian(const double *x,\n                                           double *jacobian) const {\n  ceres::MatrixRef(jacobian, 7, 7) = ceres::Matrix::Identity(7, 7);\n  return true;\n}\n\nbool Sim3Optimizer::optimize(int iter) {\n  if (vertexes.empty() == true || edges.empty() == true)\n    return false;\n\n  ceres::Problem problem;\n  for (size_t m = 0; m < edges.size(); ++m) {\n    ceres::CostFunction *cost_function =\n        PoseGraphError::Create(edges[m].pose, edges[m].information);\n    problem.AddResidualBlock(cost_function, nullptr,\n                             vertexes[edges[m].j].data(),\n                             vertexes[edges[m].i].data());\n  }\n\n  for (auto &it : vertexes) {\n    problem.SetParameterization(it.second.data(), new Sim3Parameterization());\n  }\n\n  problem.SetParameterBlockConstant(vertexes[70].data());\n\n  ceres::Solver::Options options;\n  options.max_num_iterations = iter;\n  options.minimizer_progress_to_stdout = true;\n  options.function_tolerance = 1e-16;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  std::cout << summary.FullReport() << \"\\n\";\n\n  return true;\n}\n\nvoid Sim3Optimizer::ErrorAndJacobianCalculation(\n    const Sophus::Sim3d& Sji, const Eigen::Matrix<double, 7, 7>& information,\n    const Eigen::Matrix<double, 7, 1>& lie_i,\n    const Eigen::Matrix<double, 7, 1>& lie_j,\n    Eigen::Matrix<double, 7, 1>& residuals,\n    Eigen::Matrix<double, 7, 7>& Jacobian_i,\n    Eigen::Matrix<double, 7, 7>& Jacobian_j) {\n  const Sophus::Sim3d _Sji = Sji;\n  Sophus::Sim3d Si = Sophus::Sim3d::exp(lie_i);\n  Sophus::Sim3d Sj = Sophus::Sim3d::exp(lie_j);\n  Sophus::Sim3d Serror = _Sji * (Si * Sj.inverse());\n\n  Eigen::Matrix<double, 7, 1> error = Serror.log();\n  Eigen::Matrix<double, 7, 7> Jr = Eigen::Matrix<double, 7, 7>::Zero();\n\n  Jr.block<3, 3>(0, 0) = Sophus::RxSO3d::hat(error.tail(4));\n  Jr.block<3, 3>(0, 3) = Sophus::SO3d::hat(error.head(3));\n  Jr.block<3, 1>(0, 6) = -error.head(3);\n  Jr.block<3, 3>(3, 3) = Sophus::SO3d::hat(error.block<3, 1>(3, 0));\n  Eigen::Matrix<double, 7, 7> I = Eigen::Matrix<double, 7, 7>::Identity();\n  Jr = information * (I + 0.5 * Jr + 1.0 / 12. * (Jr * Jr));\n\n  Jacobian_i = Jr * Sj.Adj();\n  Jacobian_j = -Jacobian_i;\n  residuals = information * error;\n}\n\ndouble Sim3Optimizer::IterateOnce(\n    Eigen::Matrix<double, Eigen::Dynamic, 1>& delta_sim) {\n  int n_error = (int)edges.size();\n  int n_vertex = (int)vertexes.size();\n  delta_sim.resize(n_vertex * 7, 1);\n\n  Eigen::MatrixXd Jacobian(n_error * 7, n_vertex * 7);\n  Eigen::MatrixXd error(n_error * 7, 1);\n\n  for (size_t m = 0; m < edges.size(); m++) {\n    Eigen::Matrix<double, 7, 7> Jacobian_i, Jacobian_j;\n    Eigen::Matrix<double, 7, 1> residuals;\n\n    int i = vertexes_remapped[edges[m].i];\n    int j = vertexes_remapped[edges[m].j];\n\n    ErrorAndJacobianCalculation(edges[m].pose, edges[m].information,\n                                vertexes[edges[m].i], vertexes[edges[m].j],\n                                residuals, Jacobian_i, Jacobian_j);\n    Jacobian.block<7, 7>(m * 7, i * 7) = Jacobian_i;\n    Jacobian.block<7, 7>(m * 7, j * 7) = Jacobian_j;\n    error.block<7, 1>(m * 7, 0) = residuals;\n  }\n\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> A;\n  Eigen::Matrix<double, Eigen::Dynamic, 1> b;\n  A.resize(n_vertex * 7, n_vertex * 7);\n  b.resize(n_vertex * 7, 1);\n\n  A = Jacobian.transpose() * Jacobian;\n  b = -Jacobian.transpose() * error;\n\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> ldlt;//(A);\n  ldlt.compute(A.sparseView());\n  delta_sim = ldlt.solve(b);\n  return error.norm();\n}\n\n/**\n *        S0\n *        S1\n *        ..\n *  X = [ Si ]\n *        ..\n *        Sn\n *              ..., d(error0) / d(Si), ..., d(error0)/d(Sj), ... \n *              ..., d(error1) / d(Si), ..., d(error1)/d(Sj), ... \n *                                      ...\n *  Jacobian = [..., d(errorm) / d(Si), ..., d(errorm)/d(Sj), ... ]\n *                                      ...\n *              ..., d(errorn) / d(Si), ..., d(errorn)/d(Sj), ... \n *\n */\nbool Sim3Optimizer::LocalBAOptimize(int iter) {\n  int index = 0;\n  double last_error = -1.0;\n  for (auto it = vertexes.begin(); it != vertexes.end(); it++) {\n    vertexes_remapped[it->first] = index;\n    inversed_vertexes_remapped[index] = it->first;\n    index++;\n  }\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> delta_sim;\n  for (int n = 0; n < iter; n++) {\n    double error = IterateOnce(delta_sim);\n    if (error > 0 && error < 1e-6) {\n      LOG(INFO) << \"Iteration times: \" << n << \" error: \" << error;\n      break;\n    }\n    if (std::abs(error - last_error) < 1e-6) {\n      LOG(INFO) << \"Iteration times: \" << n << \" error: \" << error;\n      break;\n    }\n    last_error = error;\n    for (size_t i = 0; i < vertexes.size(); i++) {\n      Eigen::Matrix<double, 7, 1> lie_i =\n          vertexes[inversed_vertexes_remapped[i]];\n      Eigen::Matrix<double, 7, 1> delta_i = delta_sim.block<7, 1>(i * 7, 0);\n      Sophus::Sim3d updated =\n          Sophus::Sim3d::exp(lie_i) * Sophus::Sim3d::exp(delta_i);\n      vertexes[inversed_vertexes_remapped[i]] = updated.log();\n    }\n  }\n  return true;\n}\n", "meta": {"hexsha": "ecd4b9496b5cb62cfc141f9473165274b16c2dea", "size": 8492, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Sim3Optimizer.cc", "max_stars_repo_name": "b51/CeresSim3Optimize", "max_stars_repo_head_hexsha": "b01efc55b5e6f0811f0258f39a2152c38185b79f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-05-12T01:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:20:47.000Z", "max_issues_repo_path": "src/Sim3Optimizer.cc", "max_issues_repo_name": "b51/CeresSim3Optimize", "max_issues_repo_head_hexsha": "b01efc55b5e6f0811f0258f39a2152c38185b79f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Sim3Optimizer.cc", "max_forks_repo_name": "b51/CeresSim3Optimize", "max_forks_repo_head_hexsha": "b01efc55b5e6f0811f0258f39a2152c38185b79f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T20:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T20:05:33.000Z", "avg_line_length": 34.6612244898, "max_line_length": 79, "alphanum_fraction": 0.5999764484, "num_tokens": 2702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5910582929080775}}
{"text": "/**\r\n * @file shapeFlow.cpp\r\n * @brief ShapeFlow plugin for Maya\r\n * @section LICENSE The MIT License\r\n * @section  requirements:  Eigen library, Maya\r\n * @version 0.10\r\n * @date  01/Nov/2013\r\n * @author Shizuo KAJI\r\n */\r\n\r\n#pragma comment(linker, \"/export:initializePlugin /export:uninitializePlugin\")\r\n\r\n#include \"StdAfx.h\"\r\n\r\n#include <maya/MFnPlugin.h>\r\n\r\n#include <Eigen/Dense>\r\n#include <numeric>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nclass ShapeFlow : public MPxDeformerNode{\r\npublic:\r\n    ShapeFlow()  {};\r\n    virtual MStatus deform( MDataBlock& data, MItGeometry& itGeo, const MMatrix &localToWorldMatrix, unsigned int mIndex );\r\n    static void*   creator();\r\n    static MStatus initialize();\r\n\tstatic MTypeId id;\r\n    static MString nodeName;\r\n    static MObject aActive;\r\n\tstatic MObject aStartShape;\r\n\tstatic MObject aSlider;\r\n\tstatic MObject aDeltaTime;   // time step interval\r\n\tstatic MObject aShapeMatchingWeight;       // weight of \"normal\" shape matching\r\n    int num; // number of points in the end shape\r\n    MatrixXd current;  // current shape\r\nprivate:\r\n    Matrix3d rotationPart(const Matrix3d m);\r\n};\r\n\r\n\r\nMTypeId ShapeFlow::id( 0x00000010 );\r\nMString ShapeFlow::nodeName( \"shapeFlow\" );\r\nMObject ShapeFlow::aStartShape;\r\nMObject ShapeFlow::aActive;\r\nMObject ShapeFlow::aSlider;\r\nMObject ShapeFlow::aDeltaTime;\r\nMObject ShapeFlow::aShapeMatchingWeight;\r\n\r\nvoid* ShapeFlow::creator() { return new ShapeFlow; }\r\n\r\n// main\r\nMStatus ShapeFlow::deform( MDataBlock& data, MItGeometry& itGeo, const MMatrix &localToWorldMatrix, unsigned int mIndex ) {\r\n    MStatus status;\r\n//    MThreadUtils::syncNumOpenMPThreads();    // for OpenMP\r\n    \r\n    // read end shape\r\n    MObject oStartShape = data.inputValue( aStartShape ).asMesh();\r\n    if ( oStartShape.isNull() )    {\r\n        return MS::kSuccess;\r\n    }\r\n    MFnMesh fnEndShape( oStartShape, &status );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    MPointArray endPoints, pts;\r\n    fnEndShape.getPoints( endPoints );\r\n    itGeo.allPositions(pts);\r\n\tMDataHandle hDeltaTime = data.inputValue( aDeltaTime );\r\n    bool active = data.inputValue( aActive ).asBool();\r\n\tfloat delta = hDeltaTime.asFloat();\r\n\tfloat sm_weight = data.inputValue( aShapeMatchingWeight ).asFloat();\r\n    int num = pts.length();\r\n    // dummy attribute to force deform to be called\r\n    MDataHandle hSlider = data.inputValue(aSlider);\r\n    // if first time, load target shape\r\n    if ( !active ){\r\n        current = MatrixXd(3,num);\r\n        for (int i = 0; i < num; i++) {\r\n            current(0,i) = pts[i].x;\r\n            current(1,i) = pts[i].y;\r\n            current(2,i) = pts[i].z;\r\n        }\r\n        return MS::kSuccess;\r\n    }\r\n    // number of current and end points must be equal\r\n    if (endPoints.length() != num) {\r\n        return MS::kSuccess;\r\n    }\r\n    // load end shape\r\n    MatrixXd end(3,num);\r\n    for (int i = 0; i < num; i++) {\r\n        end(0,i) = endPoints[i].x;\r\n        end(1,i) = endPoints[i].y;\r\n        end(2,i) = endPoints[i].z;\r\n    }\r\n    // compute next step\r\n\tMatrixXd Diff(3, num), Grad(3, num);\r\n    Vector3d current_center = current.rowwise().mean();\r\n    Vector3d end_center = end.rowwise().mean();\r\n    \r\n    // prepare moment matrix\r\n    current.colwise() -= current_center;\r\n    end.colwise() -= end_center;\r\n    \r\n\tMatrix3d A, B, AB, ABB;\r\n\tA = current * end.transpose();\r\n\tB = (end * end.transpose()).inverse();\r\n    AB = A * B;    // moment matrix ( minimizer of |AB P - Q|\r\n    ABB = AB * B;\r\n    Diff = rotationPart(AB) * end - current;\r\n    \r\n    // compute gradient\r\n\tGrad = end.norm() * current.norm() * ABB * (A.transpose() * ABB - Matrix3d::Identity()) * end;\r\n    // update current position\r\n    current += sm_weight * delta * Diff - delta * Grad;\r\n    current.colwise() += current_center;\r\n    /** FOR DEBUG: compute the energy\r\n    * Matrix3d C =  B * A.transpose() * A * B;\r\n    * float   energy = (C * C).trace() - 2 * C.trace() + 3;\r\n    */\r\n    // update points\r\n    for (int i = 0; i < num; i++) {\r\n        pts[i].x = current(0,i);\r\n        pts[i].y = current(1,i);\r\n        pts[i].z = current(2,i);\r\n    }\r\n    itGeo.setAllPositions(pts);\r\n\r\n\treturn MS::kSuccess;\r\n}\r\n\r\n// Polar decomposition\r\nMatrix3d ShapeFlow::rotationPart(const Matrix3d m){\r\n    Matrix3d A= m*m.transpose();\r\n\tSelfAdjointEigenSolver<Matrix3d> eigensolver;\r\n\teigensolver.computeDirect(A);\r\n    Vector3d s = eigensolver.eigenvalues();\r\n    Matrix3d U = Matrix3d(eigensolver.eigenvectors());\r\n    s << sqrtf(s[0]), sqrtf(s[1]), sqrtf(s[2]);\r\n    DiagonalMatrix<double,3> D(1.0f/s[0], 1.0f/s[1], 1.0f/s[2]);\r\n    return m * U*D*U.transpose();\r\n}\r\n\r\n// setup attributes\r\nMStatus ShapeFlow::initialize() {\r\n    MFnTypedAttribute tAttr;\r\n\tMFnNumericAttribute nAttr;\r\n\r\n\taStartShape = tAttr.create( \"startShape\", \"ss\", MFnData::kMesh );\r\n    addAttribute( aStartShape );\r\n    attributeAffects( aStartShape, outputGeom );\r\n\taSlider = nAttr.create( \"slider\", \"slider\", MFnNumericData::kFloat, 0.0 );\r\n    addAttribute( aSlider );\r\n    attributeAffects( aSlider, outputGeom );\r\n\taActive = nAttr.create( \"active\", \"active\", MFnNumericData::kBoolean, 0 );\r\n    addAttribute( aActive );\r\n    attributeAffects( aActive, outputGeom );\r\n\taDeltaTime = nAttr.create( \"delta\", \"delta\", MFnNumericData::kFloat, 0.01 );\r\n    addAttribute( aDeltaTime );\r\n\taShapeMatchingWeight = nAttr.create( \"shapeMatching\", \"smw\", MFnNumericData::kFloat, 5.0 );\r\n    addAttribute( aShapeMatchingWeight );\r\n\r\n\treturn MS::kSuccess;\r\n}\r\n\r\n// (un)init plugin\r\nMStatus initializePlugin( MObject obj ) {\r\n    MStatus status;\r\n    MFnPlugin plugin( obj, \"CREST\", \"0.1\", \"Any\");\r\n    status = plugin.registerNode( ShapeFlow::nodeName, ShapeFlow::id, ShapeFlow::creator, ShapeFlow::initialize, MPxNode::kDeformerNode );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    return status;\r\n}\r\nMStatus uninitializePlugin( MObject obj ) {\r\n    MStatus   status;\r\n    MFnPlugin plugin( obj );\r\n    status = plugin.deregisterNode( ShapeFlow::id );\r\n    CHECK_MSTATUS_AND_RETURN_IT( status );\r\n    return status;\r\n}\r\n\r\n", "meta": {"hexsha": "eec3111aa5ceb8b031beddc2656af4ed77c4c694", "size": 6054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shapeFlow/shapeFlow.cpp", "max_stars_repo_name": "jdrese/ShapeFlowMaya", "max_stars_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T07:24:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T02:11:04.000Z", "max_issues_repo_path": "shapeFlow/shapeFlow.cpp", "max_issues_repo_name": "shizuo-kaji/ShapeFlowMaya", "max_issues_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shapeFlow/shapeFlow.cpp", "max_forks_repo_name": "shizuo-kaji/ShapeFlowMaya", "max_forks_repo_head_hexsha": "a53d1704a7b139013e79f26179284f75dc8c9d01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-16T02:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T07:24:57.000Z", "avg_line_length": 33.2637362637, "max_line_length": 139, "alphanum_fraction": 0.6400726792, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.590982230786683}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <Eigen/Core>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.hpp>\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 n=8;\n    matrix A(n, n), A_u(n, n), A_l(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A(j, j)=rand_normal<double>::get();\n      A_u(j, j)=A(j, j);\n      A_l(j, j)=A(j, j);\n      for (size_type i=0; i<j; ++i) {\n\tA(i, j)=rand_normal<double>::get();\n\tA(j, i)=A(i, j);\n\tA_u(i, j)=A(i, j);\n\tA_u(j, i)=0;\n\tA_l(i, j)=0;\n\tA_l(j, i)=A(j, i);\n      }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<double>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    double beta(rand_normal<double>::get());\n    vector y1(alpha*ublas::prod(A, x)+beta*y);\n    vector y2(y);\n    blas::symv(alpha, blas::lower(A_l), x, beta, y2);\n    vector y3(y);\n    blas::symv(alpha, blas::upper(A_u), x, beta, y3);\n    vector y4(y);\n    blas::hemv(alpha, blas::lower(A_l), x, beta, y4);\n    vector y5(y);\n    blas::hemv(alpha, blas::upper(A_u), x, beta, y5);\n    std::cout << \"testing boost::ublas containers\\n\"\n    \t      << \"using ublas            : \" << print_vec(y1) << '\\n'\n    \t      << \"using blas symv (lower): \" << print_vec(y2) << '\\n'\n    \t      << \"using blas symv (upper): \" << print_vec(y3) << '\\n'\n    \t      << \"using blas hemv (lower): \" << print_vec(y4) << '\\n'\n    \t      << \"using blas hemv (upper): \" << print_vec(y5) << '\\n'\n    \t      << '\\n';\n  }\n  {\n    typedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector;\n    typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix;\n    typedef int size_type;\n    rand_normal<double>::reset();\n    size_type n=8;\n    matrix A(n, n), A_u(n, n), A_l(n, n);\n    for (size_type j=0; j<n; ++j) {\n      A(j, j)=rand_normal<double>::get();\n       A_u(j, j)=A(j, j);\n      A_l(j, j)=A(j, j);\n      for (size_type i=0; i<j; ++i) {\n    \tA(i, j)=rand_normal<double>::get();\n    \tA(j, i)=A(i, j);\n    \tA_u(i, j)=A(i, j);\n    \tA_u(j, i)=0;\n    \tA_l(i, j)=0;\n    \tA_l(j, i)=A(j, i);\n      }\n    }\n    vector x(n);\n    for (size_type i=0; i<n; ++i)\n      x(i)=rand_normal<double>::get();\n    vector y(n);\n    for (size_type i=0; i<n; ++i)\n      y(i)=rand_normal<double>::get();\n    double alpha(rand_normal<double>::get());\n    double beta(rand_normal<double>::get());\n    vector y1(alpha*A*x+beta*y);\n    vector y2(y);\n    blas::symv(alpha, blas::lower(A_l), x, beta, y2);\n    vector y3(y);\n    blas::symv(alpha, blas::upper(A_u), x, beta, y3);\n    vector y4(y);\n    blas::hemv(alpha, blas::lower(A_l), x, beta, y4);\n    vector y5(y);\n    blas::hemv(alpha, blas::upper(A_u), x, beta, y5);\n    std::cout << \"testing Eigen containers\\n\"\n    \t      << \"using ublas            : \" << print_vec(y1) << '\\n'\n    \t      << \"using blas symv (lower): \" << print_vec(y2) << '\\n'\n    \t      << \"using blas symv (upper): \" << print_vec(y3) << '\\n'\n    \t      << \"using blas hemv (lower): \" << print_vec(y4) << '\\n'\n    \t      << \"using blas hemv (upper): \" << print_vec(y5) << '\\n'\n    \t      << '\\n';\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1207050ffae82a0a0ab1931ab94265077f49c6e8", "size": 3830, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/symv.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/symv.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/symv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1964285714, "max_line_length": 73, "alphanum_fraction": 0.5613577023, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5909716749824905}}
{"text": "#ifndef TESTS_HPP_\n#define TESTS_HPP_\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/algebra/array_algebra.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <algorithm>\n#include <random>\n#include <utility>\n#include <vector>\n\n#include \"se3.hpp\"\n\n\n/**\n * Return a constant vector of size N\n *\n * f: R -> R^N\n */\ntemplate<std::size_t _N>\nstruct Constant\n{\n  static constexpr char name[] = \"Constant\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = 1;\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    return Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1>::Ones(x.size());\n  }\n};\n\n\n/**\n * Apply a series of coefficient-wise operations and sum the result\n *\n * f: R^N -> R\n */\ntemplate<std::size_t _N>\nstruct ManyToOne\n{\n  static constexpr char name[] = \"ManyToOne\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = N;\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, 1, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    return Eigen::Matrix<typename Derived::Scalar, 1, 1>(\n      (x + x.cwiseInverse()).array().sin().matrix().sum()\n    );\n  }\n};\n\n\n/**\n * Compute series x_{y+2} = sin(cos(x_y))\n *\n * f: R -> R^N\n */\ntemplate<std::size_t _N>\nstruct OneToMany\n{\n  static constexpr char name[] = \"OneToMany\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = 1;\n\n  template<typename Derived>\n  Eigen::Matrix<\n    typename Derived::Scalar,\n    Derived::RowsAtCompileTime == -1 ? -1 : static_cast<int>(N),\n    1\n  >\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    using std::sin, std::cos;\n\n    using Scalar = typename Derived::Scalar;\n    static constexpr int ValuesAtCompileTime =\n      Derived::RowsAtCompileTime == -1 ? -1 : static_cast<int>(N);\n    Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ret(N);\n    ret(0) = x(0);\n    for (std::size_t i = 0; i < N - 1; ++i) {\n      if (i % 2 == 0) {\n        ret(i + 1) = sin(ret(i));\n      } else {\n        ret(i + 1) = cos(ret(i));\n      }\n    }\n    return ret;\n  }\n};\n\n\n/**\n * Integrate an N-order integrator for 100 steps using a RK4 scheme\n *\n * f: R^N -> R^N\n */\ntemplate<std::size_t _N>\nstruct ODE\n{\n  static constexpr char name[] = \"ODE\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = N;\n\n  ODE()\n  {\n    // matrix with ones on super-diagonal\n    A_.setZero();\n    A_.template block(0, 1, N - 1, N - 1).diagonal().setOnes();\n  }\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    using scalar_t = typename Derived::Scalar;\n    using state_t = Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1>;\n\n    auto x0 = x.eval();\n    const auto Ac = A_.template cast<scalar_t>().eval();\n\n    boost::numeric::odeint::integrate_n_steps(\n      boost::numeric::odeint::runge_kutta4<\n        state_t, scalar_t, state_t, scalar_t, boost::numeric::odeint::vector_space_algebra\n      >{},\n      [&Ac](const state_t & x, state_t & dxdt, const scalar_t) {\n        dxdt = Ac * x;\n      },\n      x0, scalar_t{0.}, scalar_t{0.01}, 100\n    );\n\n    return x0;\n  }\n\nprivate:\n  Eigen::Matrix<double, N, N> A_;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\n/**\n * Three-layer fully connected neural network with one channel and tanh activations\n *\n * Weights are statically allocated\n *\n * f: R^N -> R\n */\ntemplate<std::size_t _N>\nstruct NeuralNet\n{\n  static constexpr char name[] = \"NeuralNet\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = N;\n\n  NeuralNet()\n  {\n    std::minstd_rand gen(101);  // fixed seed\n    std::normal_distribution<double> dis(0, 1);\n    auto gen_fcn = [&]() {return dis(gen);};\n\n    W1 = Eigen::Matrix<double, n1, n0>::NullaryExpr(gen_fcn);\n    W2 = Eigen::Matrix<double, n2, n1>::NullaryExpr(gen_fcn);\n    W3 = Eigen::Matrix<double, n3, n2>::NullaryExpr(gen_fcn);\n  }\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, 1, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    const auto z1 = (W1.template cast<typename Derived::Scalar>() * x.normalized()).eval();\n    const auto a1 = z1.array().tanh().matrix().eval();\n\n    const auto z2 = (W2.template cast<typename Derived::Scalar>() * a1).eval();\n    const auto a2 = z2.array().tanh().matrix().eval();\n\n    const auto z3 = (W3.template cast<typename Derived::Scalar>() * a2).eval();\n    const auto a3 = z3.array().tanh().matrix().eval();\n\n    return Eigen::Matrix<typename Derived::Scalar, 1, 1>(\n      (a3 - Eigen::Matrix<typename Derived::Scalar, n3, 1>::Ones()).squaredNorm()\n    );\n  }\n\nprivate:\n  static constexpr std::size_t n0 = N;\n  static constexpr std::size_t n1 = std::max<int>(1, n0 / 2);\n  static constexpr std::size_t n2 = std::max<int>(1, n1 / 2);\n  static constexpr std::size_t n3 = std::max<int>(1, n2 / 2);\n\n  Eigen::Matrix<double, n1, n0> W1;\n  Eigen::Matrix<double, n2, n1> W2;\n  Eigen::Matrix<double, n3, n2> W3;\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\n/**\n * Camera reprojection error for N points\n *\n * f: R^6 -> R\n *\n * f(x) = \\sum_i ( x_C_i - proj(CM * (P_CW * exp(x)) * x_W_i) ) .^ 2\n *\n * where - x_C_i the i:th 2d pixel point\n *       - x_W_i the i:th 3d world point\n *       - P_CW a nominal camera pose\n *       - x is a tangent space element defining an incremental pose\n */\ntemplate<std::size_t _N>\nstruct ReprojectionError\n{\n  static constexpr char name[] = \"Reprojection\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = 6;\n\n  ReprojectionError()\n  {\n    // nominal pose\n    P_CW_nom = SE3<double>{\n      Eigen::Quaterniond::Identity(),\n      Eigen::Vector3d{0.1, -0.3, 0.2}\n    };\n\n    // camera matrix\n    CM.setZero();\n    CM(0, 0) = 700;  // fx\n    CM(1, 1) = 690;  // fy\n    CM(0, 2) = 320;  // cx\n    CM(1, 2) = 240;  // cy\n    CM(2, 2) = 1;\n\n    // generate random data\n    std::minstd_rand gen(101);  // fixed seed\n    std::normal_distribution<double> dis(0, 1);\n    auto gen_fcn = [&]() {return dis(gen);};\n\n    for (std::size_t i = 0; i != N; ++i) {\n      pts_world[i] = Eigen::Vector3d{0, 0, 3} + Eigen::Vector3d::NullaryExpr(gen_fcn);\n      Eigen::Vector3d proj = CM * (P_CW_nom * pts_world[i]);\n      pts_image[i] = proj.template head<2>() / proj(2);\n    }\n  }\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, 1, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    using Scalar = typename Derived::Scalar;\n    using Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n    using Quat = Eigen::Quaternion<Scalar>;\n\n    SE3<Scalar> P_CW = SE3<Scalar>::exp(Scalar{0.01} * x) * P_CW_nom.template cast<Scalar>();\n    auto CMc = CM.template cast<Scalar>().eval();\n\n    // Transform world points to camera frame, re-project, square\n    Eigen::Matrix<Scalar, 1, 1> ret(0);\n    for (std::size_t i = 0; i != N; ++i) {\n      Vec3 proj = CMc * (P_CW * pts_world[i].template cast<Scalar>().eval());\n      ret(0) +=\n        (proj.template head<2>() / proj(2) - pts_image[i].template cast<Scalar>()).squaredNorm();\n    }\n    return ret;\n  }\n\nprivate:\n  Eigen::Matrix<double, 3, 3> CM;            // camera matrix\n  SE3<double> P_CW_nom{};                    // nominal camera pose\n  std::array<Eigen::Vector3d, N> pts_world;  // points in world frame\n  std::array<Eigen::Vector2d, N> pts_image;  // points in image plane\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n};\n\n\n/**\n * Differentiate the end effector position in an N link robotic arm\n *\n * f: R^6 -> R^6\n */\ntemplate<std::size_t _N>\nstruct Manipulator\n{\n  static constexpr char name[] = \"Manipulator\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = 6;\n\n  Manipulator()\n  {\n    // generate random link positions\n    std::minstd_rand gen(101);  // fixed seed\n    std::uniform_real_distribution<double> dis(-1, 1);\n    auto gen_fcn = [&]() {return dis(gen);};\n\n    for (std::size_t i = 0; i != N; ++i) {\n      link_pose[i] = SE3<double>{\n        Eigen::AngleAxis(M_PI_2 * dis(gen), Eigen::Vector3d::UnitX()) *\n        Eigen::AngleAxis(M_PI_2 * dis(gen), Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxis(M_PI_2 * dis(gen), Eigen::Vector3d::UnitZ()),\n        Eigen::Vector3d{2 * dis(gen), 2 * dis(gen), 2 * dis(gen)}\n      };\n    }\n  }\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, 3, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    using Scalar = typename Derived::Scalar;\n    SE3<Scalar> P = SE3<Scalar>::exp(x);\n\n    for (std::size_t i = 0; i != N; ++i) {\n      P *= link_pose[i].template cast<Scalar>();\n    }\n\n    return P * Eigen::Matrix<Scalar, 3, 1>::UnitX().eval();\n  }\n\nprivate:\n  std::array<SE3<double>, N> link_pose;\n};\n\n\n/**\n * Integrate a system on SE(3) for N steps using the RK4 scheme\n *\n * f: R^6 -> R^6\n */\ntemplate<std::size_t _N>\nstruct SE3ODE\n{\n  static constexpr char name[] = \"SE3ODE\";\n  static constexpr std::size_t N = _N;\n  static constexpr std::size_t InputSize = 6;\n\n  SE3ODE()\n  {\n    velocity << 0.1, -0.2, 0.3, 0.1, -0.2, 0.3;\n    Pfinal = SE3<double>{} * SE3<double>::exp(static_cast<double>(N) * 0.01 * velocity);\n  }\n\n  template<typename Derived>\n  Eigen::Matrix<typename Derived::Scalar, 6, 1>\n  operator()(const Eigen::MatrixBase<Derived> & x) const\n  {\n    using scalar_t = typename Derived::Scalar;\n    using state_t = SE3<scalar_t>;\n    using deriv_t = typename state_t::Tangent;\n\n    const auto vel_c = velocity.template cast<scalar_t>().eval();\n\n    // set initial pose\n    SE3<scalar_t> P = SE3<scalar_t>::exp(x);\n\n    boost::numeric::odeint::integrate_n_steps(\n      boost::numeric::odeint::runge_kutta4<state_t, scalar_t, deriv_t, scalar_t,\n      boost::numeric::odeint::vector_space_algebra, lie_operations>{},\n      [&vel_c](const state_t & X, deriv_t & dXdt, const scalar_t) {\n        dXdt = vel_c;\n      },\n      P, scalar_t{0.}, scalar_t{0.01}, N\n    );\n\n    const SE3<scalar_t> Pfinalinv = Pfinal.inv().template cast<scalar_t>();\n    return (Pfinalinv * P).log();\n  }\n\nprivate:\n  Eigen::Matrix<double, 6, 1> velocity;\n  SE3<double> Pfinal{};\n\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\n#endif  // TESTS_HPP_\n", "meta": {"hexsha": "603c88ff24cb400aa840695e71d13379f4130085", "size": 10373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/src/tests.hpp", "max_stars_repo_name": "pettni/autodiff", "max_stars_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/src/tests.hpp", "max_issues_repo_name": "pettni/autodiff", "max_issues_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/src/tests.hpp", "max_forks_repo_name": "pettni/autodiff", "max_forks_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6658097686, "max_line_length": 98, "alphanum_fraction": 0.630000964, "num_tokens": 3182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.590971665227953}}
{"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 bounds on the average relative difference between f and f_hat\n * It is defined as the average of |f(x) - f_hat(x)| / max(1, |f(x)|) for all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * This function returns a range in which the actual average relative error is guaranteed to lie\n * The computed bounds are always within a factor of 2, meaning that the maximum error\n * returned by this function is at most twice the minimum error\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 {min, max}, the lower and upper bound on the average case relative error\n */\nstd::pair<boost::multiprecision::cpp_dec_float_100,\n            boost::multiprecision::cpp_dec_float_100>\n    acre_bounds(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 relative difference between f and f_hat\n * It is defined as the average of |f(x) - f_hat(x)| / max(1, |f(x)|) for all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with ADDs and might be quite slow\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 average relative difference of the inputs\n */\nboost::multiprecision::cpp_dec_float_100\n    acre_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 relative difference between f and f_hat\n * It is defined as the average of |f(x) - f_hat(x)| / max(1, |f(x)|) for all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a symbolic division and might be quite slow\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_extra_bits The number of additional fixed precision bits to use during the division\n * As the result of each division is not an integer, the result is described as a fixed point number\n * with exactly num_extra_bits bits with a lower significance than one. Roughly correlates the the\n * precision of the result\n * @param num_rep The number representation for f and f_hat\n * @return the average relative difference of the inputs\n */\nboost::multiprecision::cpp_dec_float_100 acre_symbolic_division(\n    const Cudd& mgr, const std::vector<BDD>& f, const std::vector<BDD>& f_hat,\n    unsigned int num_extra_bits = 16,\n    const abo::util::NumberRepresentation num_rep\n        = abo::util::NumberRepresentation::BaseTwo);\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "2ce783024a360678ac1092b2fda33b9de48c82e2", "size": 3409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_relative_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_relative_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_relative_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": 49.4057971014, "max_line_length": 100, "alphanum_fraction": 0.7289527721, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5909716603506839}}
{"text": "#pragma once\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <cassert>\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <utility>\n#include <vector>\n#include <unordered_map>\n#include <string_view>\n#include <atomic>\n\n#include <fmt/core.h>\n#include <fmt/ostream.h>\n\n#include <boost/functional/hash.hpp>\n//#include <boost/align/aligned_allocator.hpp>\n\n\n#ifdef __GNUC__\n#define unlikely(x) __builtin_expect(!!(x), 0)\n#define likely(x) __builtin_expect(!!(x), 1)\n#else\n#define unlikely(x) x\n#define likely(x) x\n#endif\n\nnamespace util\n{\n\ntemplate<class T>\ninline T Sqr(const T &x)\n{\n  return x*x;\n}\n\ntemplate<class T>\ninline T Cubed(const T &x)\n{\n  return x*x*x;\n}\n\ntemplate<class T>\ninline T Heaviside(const T &x)\n{\n  return x>T{} ? T{1} : T{0};\n}\n\n\ninline double Rcp(double x)\n{\n  return 1./x;\n}\n\ninline float Rcp(float x)\n{\n  return 1.f/x;\n}\n\ninline constexpr double Pow(double x, std::uint32_t e)\n{\n  // This is the binary exponentiation algorithm\n  // https://de.wikipedia.org/wiki/Bin%C3%A4re_Exponentiation\n  std::uint32_t bit = 1<< (sizeof(e)*8-1);\n  double ret = 1.;\n  while (bit)\n  {\n    ret = ret*ret;\n    ret = (e&bit) ? ret*x : ret;\n    bit >>= 1;\n  }\n  return ret;\n}\n\n\ntemplate<class T>\ninline constexpr T Modulus(T a, T m, std::enable_if_t<std::is_integral_v<T> && std::is_signed_v<T>>* = nullptr)\n{\n  //  Example for operator%: -5 % 3 = -2\n  //  Should be one though. Can simply add m if result is negative.\n  const T tmp = a % m;\n  return tmp < 0 ? tmp + m : tmp;\n}\n\ntemplate<class T>\ninline constexpr T Modulus(T a, T m, std::enable_if_t<std::is_integral_v<T> && std::is_unsigned_v<T>>* = nullptr)\n{\n  return a % m;\n}\n\ntemplate<class T>\ninline constexpr T Modulus(T a, T m, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr)\n{\n  //  Example for operator%: -5 % 3 = -2\n  //  Should be one though. Can simply add m if result is negative.\n  const T tmp = std::fmod(a, m);\n  return tmp < 0 ? tmp + m : tmp;\n}\n\n\n// t = 0: Returns a\n// t = 1: Returns b\n// otherwise linear inter/extra-polation\ntemplate<class T, class U>\ninline T Lerp(const T &a, const T &b, U t)\n{\n  return (std::remove_reference_t<U>(1) - t) * a + t * b;\n}\n\n\n// Note: Will happily take the signbit from zero. So the result for 0 is basically random.\ntemplate<class T, typename std::enable_if_t<std::is_floating_point<T>{}, int> = 0>\ninline T Sign(const T &x)\n{\n  return std::copysign(T(1.), x);\n}\n\n\n// Also from PBRT. Used to compute error bounds for floating point arithmetic. See pg. 216.\ntemplate<class T>\ninline constexpr T Gamma(int n) {\n    constexpr T eps_half = std::numeric_limits<T>::epsilon();\n    return (n * eps_half) / (1 - n * eps_half);\n}\n\n\ntemplate<class T>\ninline bool Quadratic(T a, T b, T c, T &t0, T &t1)\n{\n  //from PBRT pg. 1080\n  const T d = b*b - T(4)*a*c;\n  if (d < T(0))\n    return false;\n  const T sd = std::sqrt(d);\n  const T q = b<0 ? -b+sd : -b-sd;\n  t0 = q/T(2)/a;\n  t1 = T(2)*c/q;\n  if (t0 > t1)\n    std::swap(t0 ,t1);\n  return true;\n}\n\n\nnamespace quadratic_internal\n{\n\ntemplate<class T>\ninline T Errorformula1(T A, T B, T C, T D, T sD, T eA, T eB, T eC)\n{\n  constexpr T eps = std::numeric_limits<T>::epsilon();\n  const T xi = B<T(0) ? T(1) : T(-1);\n  const T G = B-xi*sD;\n  const T Ainv = T(1)/A;\n  const T sDinv = T(1)/sD;\n  const T E1 = std::abs(G*Ainv) + T(3)/T(4)*std::abs(sD*Ainv) + std::abs(C*sDinv) + std::abs(B*B*Ainv*sDinv)/T(4);\n  const T E2 = eA*std::abs((C*xi*Ainv*sDinv - G*Ainv*Ainv/T(2))) + eB/T(2)*std::abs(Ainv*(B*xi*sDinv-T(1))) + eC*std::abs(sDinv);\n  return eps*E1 + E2;\n}\n\ntemplate<class T>\ninline T Errorformula2(T A, T B, T C, T D, T sD, T eA, T eB, T eC)\n{\n  constexpr T eps = std::numeric_limits<T>::epsilon();\n  const T xi = B<T(0) ? T(1) : T(-1);\n  const T G = B - xi*sD;\n  const T sDinv = T(1)/sD;\n  const T GGsDinv = T(1)/(G*G*sD);\n  const T E1 = std::abs(GGsDinv)*(T(4)*std::abs(C*G*sD) + T(3)*std::abs(C*D) + T(4)*std::abs(A*C*C) + std::abs(B*B*C));\n  const T E2 = std::abs(GGsDinv)*(eA*T(4)*std::abs(C*C)+ T(2)*eB*std::abs(C*(B*xi - sD)) + eC*std::abs((T(4)*A*C*xi - T(2)*G*sD)));\n  return eps*E1 + E2;\n}\n\n};\n\n\ntemplate<class T>\ninline bool Quadratic(T a, T b, T c, T ea, T eb, T ec, T &t0, T &t1, T &err0, T &err1)\n{\n  using namespace quadratic_internal;\n  //from PBRT pg. 1080\n  const T d = b*b - T(4)*a*c;\n  if (d < T(0))\n    return false;\n  const T sd = std::sqrt(d);\n  err0 = Errorformula1(a, b, c, d, sd, ea, eb, ec);\n  err1 = Errorformula2(a, b, c, d, sd, ea, eb, ec);\n  const T q = b<0 ? -b+sd : -b-sd;\n  t0 = q/T(2)/a;\n  t1 = T(2)*c/q;\n  if (t0 > t1)\n  {\n    std::swap(t0 ,t1);\n    std::swap(err0, err1);\n  }\n  return true;\n}\n\n\ninline bool startswith(const std::string &a, const std::string &b)\n{\n  if (a.size() < b.size())\n    return false;\n  return a.substr(0, b.size()) == b;\n}\n\ninline bool endswith(const std::string &a, const std::string &b)\n{\n  if (a.size() < b.size())\n    return false;\n  return a.substr(a.size()-b.size(), b.size()) == b;\n}\n\n\n//  There is no hash support for pairs in the STL.\ntemplate<class A, class B>\nstruct pair_hash\n{\n  std::size_t operator()(const std::pair<A,B> &v) const\n  {\n    std::size_t seed = boost::hash_value(v.first);\n    boost::hash_combine(seed, boost::hash_value(v.second));\n    return seed;\n  }\n};\n\n\n// Copy & Paste Fu! https://stackoverflow.com/questions/27140778/range-based-for-with-pairiterator-iterator\ntemplate <typename I>\nstruct iter_pair : std::pair<I, I>\n{ \n    using std::pair<I, I>::pair;\n\n    I begin() { return this->first; }\n    I end() { return this->second; }\n};\n\n#if 1\ntemplate<class T, size_t alignment>\nclass AlignedAllocator\n{\n  public:\n    using value_type = T;\n    using propagate_on_container_move_assignment = std::true_type;\n    using is_always_equal = std::true_type;\n\n    static constexpr size_t ComputeTrueAlignment()\n    {\n      // By default we may have some random align a. But if type specify \n      // alignas(b) with b>a, I'd get crashes without this little correction.\n      if constexpr (std::is_void_v<T>)\n        return alignment;\n      else\n        return std::max(alignment, alignof(T));\n    }\n\n    static constexpr size_t true_alignment = ComputeTrueAlignment();\n    // Check requirements for posix_memalign.\n    static_assert(true_alignment % sizeof(void*) == 0);\n\n    template<class U>\n    struct rebind {\n      typedef AlignedAllocator<U, alignment> other;\n    };\n\n    constexpr AlignedAllocator() noexcept = default;\n\n    template <class U>\n    constexpr AlignedAllocator(const AlignedAllocator<U, alignment>&) noexcept\n    {\n    }\n\n    [[nodiscard]] T* allocate(std::size_t n)\n    {\n      #ifdef _MSC_VER\n            return (T*)_aligned_malloc(n*sizeof(T), true_alignment);\n      #else\n            void* result = nullptr;\n            posix_memalign(&result, true_alignment, n*sizeof(T)); // returns 0 on success. Not using it obviously.\n            return (T*)result;\n      #endif\n    }\n\n    void deallocate(T* p, std::size_t n)\n    {\n      #ifdef _MSC_VER\n        _aligned_free(p);\n      #else\n        free(p);\n      #endif\n    }\n};\n\ntemplate <class T, class U, size_t a>\nbool operator==(const AlignedAllocator<T,a>&, const AlignedAllocator<U,a>&) noexcept\n{\n  return true;\n}\n\ntemplate <class T, class U, size_t a>\nbool operator!=(const AlignedAllocator<T, a>&, const AlignedAllocator<U, a>&) noexcept\n{\n  return false;\n}\n#else\ntemplate<class T, size_t a>\nusing AlignedAllocator = boost::alignment::aligned_allocator<T,a>;\n#endif\n\n\n// std::vector with 16 byte aligment as required by Eigen's fixed size types.\n// This class also comes with range checking in debug mode.\ntemplate<class T, class Alloc = AlignedAllocator<T,16>>\nclass ToyVector : public std::vector<T, Alloc>\n{\n  using B = std::vector<T, Alloc>;\npublic:\n  using B::B;\n\n  inline typename B::const_reference operator[](typename B::size_type i) const\n  {\n    assert(i >= 0 && i<B::size());\n    return B::operator[](i);\n  }\n  \n  inline typename B::reference operator[](typename B::size_type i)\n  {\n    assert(i >= 0 && i<B::size());\n    return B::operator[](i);\n  }\n};\n\n\ntemplate<class K, class T, class F, class Hash, class Pred>\ninline T GetOrInsertFromFactory(std::unordered_map<K, T, Hash, Pred> &m, const K &k, F factory)\n{\n  auto it = m.find(k);\n  if (it == m.end())\n  {\n    auto& t = m[k] = factory();\n    return t;\n  }\n  else\n    return it->second;\n}\n\n\ntemplate<class T>\ninline T ASSERT_NOT_NULL(T x, typename std::enable_if<std::is_pointer<T>::value>::type* = 0)\n{\n  assert(x != nullptr);\n  return x;\n}\n\n\n// Adapted from http://the-witness.net/news/2012/11/scopeexit-in-c11/\ntemplate <typename F>\nstruct ScopeExit {\n    ScopeExit(F f) : f(f) {}\n    ~ScopeExit() { f(); }\n    F f;\n};\n\ntemplate <typename F>\nScopeExit<F> MakeScopeExit(F f) {\n    return ScopeExit<F>(f);\n};\n\n#define SCOPE_EXIT(code) \\\n    auto scope_exit_ ## __LINE__ = util::MakeScopeExit([=](){ code })\n\n    \ninline int RowMajorOffset(int x, int y, int size_x, int size_y)\n{\n  return x + y*size_x;\n}\n\ninline std::pair<int, int> RowMajorPixel(int offset, int size_x, int size_y)\n{\n  int y = offset / size_x;\n  int x = offset - y*size_x;\n  return std::make_pair(x,y);\n}\n\n\ntemplate<class T>\nstruct enable_if_has_size_member\n{\n    using type = decltype(std::declval<T&>().size());\n};\n\n\ntemplate<class Container>\ninline int isize(const Container &c, typename enable_if_has_size_member<Container>::type = 0)\n{\n    return static_cast<int>(c.size());\n}\n\ntemplate<class Container>\ninline long lsize(const Container &c, typename enable_if_has_size_member<Container>::type = 0)\n{\n  return static_cast<long>(c.size());\n}\n\n\ntemplate<class T>\nstruct enable_if_has_insert_begin_and_end_members\n{\n  using type = decltype(std::declval<T&>().insert(\n    std::declval<T&>().begin(),\n    std::declval<T&>().end(),\n    std::declval<T&>().begin() // here this makes actually sense.\n  ));\n};\n\n\ntemplate<class Container, typename = typename enable_if_has_insert_begin_and_end_members<Container>::type>\ninline void Append(Container &a, const Container &b)\n{\n  a.insert(a.end(), b.begin(), b.end());\n}\n\ntemplate<class T, class Alloc>\ninline void PushBackToEnsureSize(std::vector<T, Alloc> &v, std::size_t required_size, const T &filler)\n{\n  assert(required_size >= v.size());\n  std::fill_n(std::back_inserter(v), required_size - v.size(), filler);\n}\n\n\ntemplate<class T>\nstruct has_begin_end\n{\n  using type1 = decltype(std::declval<T&>().begin());\n  using type2 = decltype(std::declval<T&>().end());\n  static constexpr bool value = true;\n};\n\n\ntemplate<class Container, class Func, typename = std::enable_if_t<has_begin_end<Container>::value>>\ninline auto TransformVector(Container &a, Func &&f)\n{\n  using TIn = typename Container::reference;\n  using TOut = std::invoke_result_t<Func, TIn>;\n  using OutContainer = ToyVector<TOut>;\n  OutContainer result;\n  std::transform(a.begin(), a.end(), std::back_inserter(result), f);\n  return result;\n}\n\n// Adapted from https://stackoverflow.com/questions/41660062/how-to-construct-an-stdarray-with-index-sequence\n// Use variadic templates and a pack of integers to build the output array without \n// invoking default c'tors.\nnamespace detail {\n  template<typename T, typename U, typename F, std::size_t... Is>\n  constexpr auto transform_array(F& f, const U* input, std::index_sequence<Is...>)\n     -> std::array<T, sizeof...(Is)> \n  {\n    return {{f(input[std::integral_constant<std::size_t, Is>{}])...}};\n  }\n}\n\n\ntemplate<class Func, class T, std::size_t n>\ninline constexpr auto TransformArray(std::array<T,n> &a, Func &&f)\n{\n  using TOut = std::invoke_result_t<Func, T>;\n  return detail::transform_array<TOut>(f, a.data(), std::make_index_sequence<n>{});\n}\n\n\n// From https://stackoverflow.com/questions/41660062/how-to-construct-an-stdarray-with-index-sequence\n// Use variadic templates and a pack of integers to build the output array without \n// invoking default c'tors. \nnamespace detail {\n  template<typename T, typename F, std::size_t... Is>\n  constexpr auto generate_array(F& f, std::index_sequence<Is...>)\n   -> std::array<T, sizeof...(Is)> {\n    return {{f(std::integral_constant<std::size_t, Is>{})...}};\n  }\n}\n\ntemplate<std::size_t N, typename F>\ninline constexpr auto GenerateArray(F &&f) {\n  using TOut = std::invoke_result_t<F, std::size_t>;\n  return detail::generate_array<TOut>(f, std::make_index_sequence<N>{});\n}\n\n\n/*\n * Perform an atomic addition to the float via spin-locking\n * on compare_exchange_weak. Memory ordering is release on write\n * consume on read\n *\n * from https://www.reddit.com/r/cpp/comments/338pcj/atomic_addition_of_floats_using_compare_exchange/\n */\ninline float AtomicAdd(std::atomic<float> &f, float d) {\n  float old = f.load(std::memory_order_consume);\n  float desired = old + d;  while (!f.compare_exchange_weak(old, desired,\n    std::memory_order_release, std::memory_order_consume))\n  {\n    desired = old + d;\n  }\n  return desired;\n}\n\n\n// From https://arne-mertz.de/2018/05/overload-build-a-variant-visitor-on-the-fly/\ntemplate <class ...Fs>\nstruct Overload : Fs... {\n  template <class ...Ts>\n  Overload(Ts&& ...ts) : Fs{std::forward<Ts>(ts)}...\n  {} \n\n  using Fs::operator()...;\n};\n\ntemplate <class ...Ts>\nOverload(Ts&&...) -> Overload<std::remove_reference_t<Ts>...>;\n\n// TODO: check if we have an iterator in It\ntemplate<class It, class Trafo>\ninline std::string Join(const std::string &sep, It begin, It end, Trafo trafo)\n{\n  if (begin == end)\n    return {};\n  std::ostringstream os;\n  It prev = begin;\n  ++begin;\n  while (begin != end)\n  {\n    os << trafo(*prev) << sep;\n    prev = begin;\n    ++begin;\n  }\n  os << trafo(*prev);\n  return os.str();\n}\n\n\n} // namespace util\n\nusing util::Overload;\nusing util::Sqr;\nusing util::Cubed;\nusing util::Heaviside;\nusing util::Rcp;\nusing util::Lerp;\nusing util::Sign;\nusing util::ToyVector;\nusing util::isize;\nusing util::lsize;\nusing util::AlignedAllocator;\nusing util::ASSERT_NOT_NULL;", "meta": {"hexsha": "fa9d7b84e2aeccffbe0d34a6e68fab46cc6200c8", "size": 13811, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/util.hxx", "max_stars_repo_name": "DaWelter/NaiveTrace", "max_stars_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T08:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T06:19:16.000Z", "max_issues_repo_path": "src/util.hxx", "max_issues_repo_name": "DaWelter/NaiveTrace", "max_issues_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.hxx", "max_forks_repo_name": "DaWelter/NaiveTrace", "max_forks_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8399280576, "max_line_length": 131, "alphanum_fraction": 0.6536818478, "num_tokens": 4120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7549149813536516, "lm_q1q2_score": 0.5908436230509786}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                       */\n/*  This file is part of the library KASKADE 7                 */\n/*    see http://www.zib.de/en/numerik/software/kaskade-7.html         */\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#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/embedded_errorest.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"   // ContinuousHierarchicMapper\n#include \"linalg/direct.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/iluprecond.hh\"      // PrecondType::ILUT, PrecondType::ILUK, PrecondType::ARMS\n#include \"linalg/iccprecond.hh\"\n#include \"linalg/icc0precond.hh\"\n#include \"linalg/hyprecond.hh\"       // BoomerAMG\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/cg.hh\"\n#include \"mg/hb.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 \"cubus.hh\"\nusing namespace Kaskade;\n#include \"peaksource.hh\"\n\n#ifndef SPACEDIM\n#define SPACEDIM 2\n#endif\n\n#if SPACEDIM==2\n#define DEFAULT_REFINEMENTS 5\n#else\n#define DEFAULT_REFINEMENTS 2\n#endif\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  std::cout << \"Start heat transfer tutorial program using embedded error estimation\" << 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, \"refinement\", DEFAULT_REFINEMENTS),\n       order       = getParameter(pt, \"order\", 2),\n       verbosity   = getParameter(pt, \"verbosity\", 1);\n\n  std::cout << \"original mesh shall be refined : \" << refinements << \" times\" << std::endl;\n  std::cout << \"discretization order         : \" << order << std::endl;\n  std::cout << \"output level (verbosity)     : \" << verbosity << std::endl;\n\n  DirectType directType;\n//  IterateType iterateType = IterateType::CG;\n  MatrixProperties property;\n  PrecondType precondType = PrecondType::NONE;\n  std::string empty;\n  \n  int direct, onlyLowerTriangle = false;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  direct = getParameter(pt, s, 0);\n\n  // the user may select a value for solver.direct of \n  // the enumeration class {UMFPACK, PARDISO, MUMPS, SUPERLU, UMFPACK3264, UMFPACK64}\n  // Remark: DirectType::PARDISO not yet available\n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  directType = static_cast<DirectType>(getParameter(pt, s, 2));\n\n  // the user may select a value for solver.iterate of \n  // the enumeration {CG, BICGSTAB, GMRES, PCG, APCG, SGS}\n  // Remark: in this example only IterateType::CG is used.\n//  s = \"names.iterate.\" + getParameter(pt, \"solver.iterate\", empty);\n//  iterateType = static_cast<IterateType>(getParameter(pt, s, 0));\n   \n  // the user may select a value for solver.preconditioner of \n  // the enumeration class {NONE, JACOBI, ILUT, ILUK, ARMS, ADDITIVESCHWARZ,\n  //                  BOOMERAMG, EUCLID, SSOR, ICC0, ICC, ILUKS}\n  // Remark: in this example only PrecondType::NONE,PrecondType::JACOBI, PrecondType::ICC, PrecondType::ICC0, PrecondType::BOOMERAMG are used.\n  s = \"names.preconditioner.\" + getParameter(pt, \"solver.preconditioner\", empty);\n  precondType = static_cast<PrecondType>(getParameter(pt, s, 0));\n\n  property = MatrixProperties::SYMMETRIC;\n  std::cout << \"discretization is symmetric\" << std::endl;\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 PrecondType::ICC preconditioner ===> onlyLowerTriangle is set to true!\" \n      << std::endl;\n  }\n\n#if SPACEDIM==2\n  //   two-dimensional space: dim=2\n  constexpr int dim=2;        \n  using Grid = Dune::UGGrid<dim>;\n  GridManager<Grid> gridManager( createUnitSquare<Grid>() );\n  gridManager.globalRefine(refinements);\n  std::cout << std::endl << \"Grid: \" << gridManager.grid().size(0) << \" triangles, \" << std::endl;\n#else\n  //  three-dimensional space: dim=3\n  constexpr int dim=3; \n  using Grid = Dune::UGGrid<dim>;\n  GridManager<Grid> gridManager( createUnitCube<Grid>(0.5) );\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#endif\n  std::cout << \"      \" << gridManager.grid().size(dim-1) << \" edges, \" << std::endl;\n  std::cout << \"      \" << gridManager.grid().size(dim) << \" points\" << std::endl;\n\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  // alternative: using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<double,LeafView> >;\n  using VariableDescriptions = boost::fusion::vector<VariableDescription<0,1,0> >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = PeaksourceFunctional<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 LinearSpace = VariableSet::CoefficientVectorRepresentation<0,neq>::type;\n\n  gridManager.setVerbosity(verbosity);\n  gridManager.enforceConcurrentReads(true);\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[1] = { \"T\" };\n  VariableSet variableSet(spaces,varNames);\n\n  Functional F;\n  \n    //construct Galerkin representation\n\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  VariableSet::VariableSet xx(variableSet);\n  \n  size_t nnz  = assembler.nnz(0,neq,0,nvars,onlyLowerTriangle);\n  size_t size = variableSet.degreesOfFreedom(0,nvars);\n  if ( verbosity>0) std::cout << \"init mesh: nnz = \" << nnz << \", dof = \" << size << std::endl;\n  \n  std::vector<std::pair<double,double> > tol(1);\n  double atol = getParameter(pt, \"solver.atol\", 1.0e-5);\n  double rtol = getParameter(pt, \"solver.rtol\", 1.0e-5);      \n  tol[0] = std::make_pair(atol,rtol); \n  std::cout << std::endl << \"Accuracy: atol = \" << atol << \",  rtol = \" << rtol << std::endl;\n\n\n  bool accurate = true;\n  int refSteps = -1;\n  int iter=0;\n\n  do {\n    refSteps++;\n\n    boost::timer::cpu_timer assembTimer;\n    VariableSet::VariableSet x(variableSet);\n    assembler.assemble(linearization(F,x));\n    CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n    solution = 0;\n    CoefficientVectors rhs(assembler.rhs());\n    AssembledGalerkinOperator<Assembler,0,1,0,1> A(assembler, onlyLowerTriangle);\n    MatrixAsTriplet<double> tri = A.get<MatrixAsTriplet<double> >();\n    if ( verbosity>1) std::cout << \"assemble: \" << (double)assembTimer.elapsed().user/1e9 << \"s\\n\";\n\n\n    if (direct) {\n      boost::timer::cpu_timer directTimer;\n      directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n      x.data = solution.data;\n\n      if ( verbosity>1) std::cout << \"direct solve: \" << (double)(directTimer.elapsed().user)/1e9 << \"s\\n\";\n    }\n    else {\n      //if ( verbosity>0) std::cout << \"iterative solver: steps = \" << iteSteps << \", eps = \" << iteEps << std::endl;\n      boost::timer::cpu_timer iteTimer;\n      Dune::InverseOperatorResult res;\n      const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n      int iteSteps = getParameter(pt, \"solver.iteMax\", 2000);\n      double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-10);\n      StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n      int lookAhead;\n      switch (precondType)\n      {\n        case PrecondType::NONE:\n        case PrecondType::HB:   lookAhead=50; break;\n        default:                lookAhead=3; break;\n      }\n      lookAhead = getParameter(pt, \"solver.lookAhead\", lookAhead);\n      termination.setLookAhead(lookAhead);\n      \n      switch (precondType)\n      {\n        case PrecondType::NONE:\n        {\n          TrivialPreconditioner<AssembledGalerkinOperator<Assembler,0,1,0,1> > trivial;\n          CG<LinearSpace,LinearSpace> cg(A,trivial,defaultScalarProduct,termination,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n        case PrecondType::ICC:\n        {\n          std::cout << \"selected preconditioner: ICC\" << std::endl;\n          if (property != MatrixProperties::SYMMETRIC) \n          {\n            std::cout << \"PrecondType::ICC preconditioner of TAUCS lib has to be used with matrix.property==MatrixProperties::SYMMETRIC\\n\";\n            std::cout << \"i.e., call the executable with option --solver.property MatrixProperties::SYMMETRIC\\n\\n\";\n          }\n          double dropTol = getParameter(pt, \"solver.ICC.dropTol\", 0.01);;\n          ICCPreconditioner<AssembledGalerkinOperator<Assembler,0,1,0,1> > icc(A,dropTol);\n          CG<LinearSpace,LinearSpace> cg(A,icc,defaultScalarProduct,termination,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n        case PrecondType::ICC0:\n        {\n          std::cout << \"selected preconditioner: ICC0\" << std::endl;\n          ICC_0Preconditioner<AssembledGalerkinOperator<Assembler,0,1,0,1> > icc0(A);\n          CG<LinearSpace,LinearSpace> cg(A,icc0,defaultScalarProduct,termination,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n        case PrecondType::HB:\n        {\n          std::cout << \"selected preconditioner: HB\" << std::endl;\n          HierarchicalBasisPreconditioner<Grid,AssembledGalerkinOperator<Assembler,0,1,0,1>::range_type, AssembledGalerkinOperator<Assembler,0,1,0,1>::range_type > hb(gridManager.grid());\n          CG<LinearSpace,LinearSpace> cg(A,hb,defaultScalarProduct,termination,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n        case PrecondType::BOOMERAMG:\n        {\n          int steps = getParameter(pt, \"solver.BOOMERAMG.steps\", iteSteps);\n          int coarsentype = getParameter(pt, \"solver.BOOMERAMG.coarsentype\", 21);\n          int interpoltype = getParameter(pt, \"solver.BOOMERAMG.interpoltype\", 0);\n          int cycleType = getParameter(pt, \"solver.BOOMERAMG.cycleType\", 1);\n          int relaxType = getParameter(pt, \"solver.BOOMERAMG.relaxType\", 3);\n          int variant = getParameter(pt, \"solver.BOOMERAMG.variant\", 0);\n          int overlap = getParameter(pt, \"solver.BOOMERAMG.overlap\", 1);\n          double tol = getParameter(pt, \"solver.BOOMERAMG.tol\", iteEps);\n          double strongThreshold = getParameter(pt, \"solver.BOOMERAMG.strongThreshold\", (dim==2)?0.25:0.6);\n          BoomerAMG<AssembledGalerkinOperator<Assembler,0,1,0,1> >\n          BoomerAMGPrecon(A,steps,coarsentype,interpoltype,tol,cycleType,relaxType,\n          strongThreshold,variant,overlap,1,verbosity);\n          CG<LinearSpace,LinearSpace> cg(A,BoomerAMGPrecon,defaultScalarProduct,termination,verbosity);\n//          Dune::LoopSolver<LinearSpace> cg(A,BoomerAMGPrecon,iteEps,iteSteps,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n        case PrecondType::JACOBI:\n        default:\n        {\n          JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,1,0,1> > jacobi(A,1.0);\n          CG<LinearSpace,LinearSpace> cg(A,jacobi,defaultScalarProduct,termination,verbosity);\n          cg.apply(solution,rhs,res);\n        }\n        break;\n      }\n      solution *= -1.0;\n      x.data = solution.data;\n  \n      if ( verbosity>0) std::cout << \"iterative solve eps= \" << iteEps << \": \" \n          << (res.converged?\"converged\":\"failed\") << \" after \"\n          << res.iterations << \" steps, rate=\"\n          << res.conv_rate << \", time=\" << (double)(iteTimer.elapsed().user)/1e9 << \"s\\n\";\n    }\n    \n\t// graphical output of solution\n    std::ostringstream fn;\n    fn << \"graph/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\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    writeVTKFile(x,fn.str(),IoOptions().setOrder(order));\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,variableSet,x,fn.str(),options);\n\n\n\n    VariableSet::VariableSet e = x;\n    projectHierarchically(variableSet,e);\n    e -= x;    \n  \n    accurate = embeddedErrorEstimator(variableSet,e,x,IdentityScaling(),tol,gridManager,verbosity);\n    nnz = assembler.nnz(0,1,0,1,onlyLowerTriangle);;\n    size_t size = variableSet.degreesOfFreedom(0,1);\n    if ( verbosity>0) std::cout << \"new mesh: nnz = \" << nnz << \", dof = \" << size << std::endl;\n    \n    //ridx.resize(nnz);\n    //cidx.resize(nnz);\n    //data.resize(nnz);\n    //rhs.resize(size);\n    //solution.resize(size);\n\n    // VariableSet::VariableSet xx may be used beyond the do...while loop\t\n    xx.data = x.data;\n    iter++; \n    if (iter>9) \n    {\n      std::cout << \"*** Maximum number of iterations exceeded ***\" << std::endl;\n      break;\n    }\n    \n  }  while (!accurate); \n  \n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End heat transfer (peak source) tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "f4c25813648cbb9289418bc454c98417a33ba3aa", "size": 14814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/Embedded_errorEstimation/peaksource.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/Embedded_errorEstimation/peaksource.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/Embedded_errorEstimation/peaksource.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": 41.8474576271, "max_line_length": 187, "alphanum_fraction": 0.6481031457, "num_tokens": 4117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5907973864694818}}
{"text": "#include <lib_template/dummy.h>\n\n#include <boost/any.hpp>\n\n#include <plog/Log.h>\n\n#include <seqan/graph_algorithms.h>\n\n#include <mpir.h>\n#include <boost/multiprecision/gmp.hpp>\n\n#include <sstream>\n\nnamespace boost_mp = boost::multiprecision;\nusing int_type = boost_mp::number<boost_mp::backends::gmp_int,\n                                  boost_mp::expression_template_option::et_off>;\n\n\nusing namespace seqan;\n\nusing TGraph = Graph<Directed<>>;\nusing TVertexDescriptor = VertexDescriptor<TGraph>::Type;\nusing TEdgeIterator = Iterator<TGraph, EdgeIterator>::Type;\nusing TSize = Size<TGraph>::Type;\n\nDummy::Dummy() \n{\n    LOG_INFO << \"Dummy lib constructed\";\n\n    // Create graph with 9 directed edges (0,1), (0,2)\n    TSize numEdges = 9;\n    TVertexDescriptor edges[] = {0, 1, 0, 2, 0, 4, 1, 3, 1, 4, 2, 1, 3, 0, 3, 2, 4, 3};\n    TGraph g;\n    addEdges(g, edges, numEdges);\n    // Print graph.\n    std::stringstream gs;\n    gs << g;\n    LOG_INFO << gs.str();\n\n    // Fill external property map with edge weights and assign to graph.\n    int_type weights[] = {3, 8, -4, 1, 7, 4, 2, -5, 6};\n    String<int_type> weightMap;\n    assignEdgeMap(weightMap, g, weights);\n\n    // Run Floyd-Warshall algorithm.\n    String<int_type> distMat;\n    String<TVertexDescriptor> predMat;\n    floydWarshallAlgorithm(distMat, predMat, g, weightMap);\n\n    // Print result to stdout.\n    unsigned int len = static_cast<unsigned>(std::sqrt(static_cast<double >(length(distMat))));\n    for (TSize row = 0; row < len; ++row)\n        for (TSize col = 0; col < len; ++col)\n        {\n            std::stringstream s;\n            s << row << \",\" << col << \" (Distance=\"\n                 <<  getValue(distMat, row * len + col) << \"): \";\n            LOG_INFO << s.str();\n        }\n\n\n}\n", "meta": {"hexsha": "cfe96d1a8fbc267b4be488670364310dd7e75969", "size": 1754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "templates/lib_template/source/dummy.cpp", "max_stars_repo_name": "variar/contest-template", "max_stars_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T01:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-09T01:50:31.000Z", "max_issues_repo_path": "templates/lib_template/source/dummy.cpp", "max_issues_repo_name": "variar/contest-template", "max_issues_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "templates/lib_template/source/dummy.cpp", "max_forks_repo_name": "variar/contest-template", "max_forks_repo_head_hexsha": "bad78a60fd32b3b66035cb064838663c39b38bc2", "max_forks_repo_licenses": ["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.8412698413, "max_line_length": 95, "alphanum_fraction": 0.6163055872, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5907444733122553}}
{"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_2OLOG_10_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOG_2OLOG_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_2olog_10 : \\f$\\frac{\\log(2)}{\\log(10)}\\f$.\n\n\n    @par Header <boost/simd/constant/log_2olog_10.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Log_2olog_10<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(0.3010299956639811952137388947244930267681898814621085);\n    @endcode\n\n\n**/\n  template<typename T> T Log_2olog_10();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant Log_2olog_10.  (\\f$\\frac{\\log(2)}{\\log(10)}\\f$)\n\n      Generate the  constant log_2olog_10.\n\n      @return The Log_2olog_10 constant for the proper type\n    **/\n    Value Log_2olog_10<Value>();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/log_2olog_10.hpp>\n#include <boost/simd/constant/simd/log_2olog_10.hpp>\n\n#endif\n", "meta": {"hexsha": "b3c6875b6bcca2335268e9ad72c2d940de423cdb", "size": 1387, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/log_2olog_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/log_2olog_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/log_2olog_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": 22.0158730159, "max_line_length": 100, "alphanum_fraction": 0.5940879596, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5905619183798413}}
{"text": "/**\r\n *\r\n * Copyright (C) 2021 Mohammad Javad Dousti, Qing Xie, Mahdi Nazemi,\r\n * and Massoud Pedram. All rights reserved.\r\n *\r\n * Please refer to the LICENSE file for terms of use.\r\n *\r\n */\r\n\r\n#pragma once\r\n\r\n#include <Eigen/SparseCore>\r\n#include <Eigen/Core>\r\n\r\n#include \"device.hpp\"\r\n#include \"general.hpp\"\r\n#include \"rc_utils.hpp\"\r\n#include \"utils.hpp\"\r\n\r\n/* model specific constants */\r\n/* changed from 1/2 to 1/3 due to the difference from traditional Elmore Delay\r\n * scenario */\r\n//#define C_FACTOR    0.33       /* fitting factor to match floworks (due to\r\n// lumping)    */\r\n\r\nclass Model {\r\nprivate:\r\n  Device *device;\r\n\r\n  Eigen::SparseMatrix<VALUE> g_matrix_;\r\n\r\n  // A = C^-1 * G\r\n  Eigen::SparseMatrix<VALUE> a_matrix_;\r\n\r\n\r\n  // Inverted form of diagonal matrix C\r\n  Eigen::DiagonalMatrix<VALUE, Eigen::Dynamic, Eigen::Dynamic> inv_c_;\r\n\r\n  /**\r\n   * This saves \"device->getTemperature() * K1\",\r\n   * which comes from the lhs of the equation due to dropping\r\n   * the term corresponds to the thermal coupling to the ambient.\r\n   */\r\n  Eigen::Matrix<VALUE, Eigen::Dynamic, 1> amb_vector_;\r\n  Eigen::Matrix<VALUE, Eigen::Dynamic, 1> p_vector_;\r\n  Eigen::Matrix<VALUE, Eigen::Dynamic, 1> t_vector_;\r\n\r\n  bool p_vector_made_;\r\n  bool g_matrix_made_;\r\n  bool c_vector_made_;\r\n  bool t_vector_made_;\r\n  bool transient_;\r\n  int elements_no_;\r\n  unordered_map<string, int> powerMappingDeviceOrder;\r\n  unordered_map<int, string> powerMappingTraceOrder;\r\n  std::ifstream powerTraceFile;\r\n  bool isComment(string s);\r\n  /**\r\n   * This designates the number of power consumers we\r\n   * expect to find in the power trace file It is used to\r\n   * check if the power trace has enough info\r\n   */\r\n  int pwr_consumers_cnt;\r\n  string powerTraceFileAddr;\r\n\r\n  void initPowerVector();\r\n  void preparePVector();\r\n\r\npublic:\r\n  void makePVector();\r\n  void makeResistanceModel();\r\n  // void makeResistanceModel2();\r\n  void makeCapacitanceModel();\r\n\r\n  /**\r\n   * This function reads one line from the power trace file and place it\r\n   * in the power vector\r\n   *\r\n   * @return Number of succesfully read power values from the last read row.\r\n   */\r\n  unsigned read_power();\r\n\r\n  void solveSteadyState();\r\n  void solveTransientState();\r\n  void printSubComponentTemp();\r\n  void printComponentTemp(string file_output);\r\n  void printComponentTemp(string file_output, unsigned step_no);\r\n  void printGMatrix(string file_output);\r\n  void printAMatrix(string file_output);  \r\n  void printInvCVector(string file_output);\r\n  void printPVector(string file_output);\r\n  void printTVector(string file_output);\r\n  void printElementCount(string file_output);\r\n  Model(Device *device, bool isTransient);\r\n  virtual ~Model();\r\n};\r\n", "meta": {"hexsha": "19b692ad78ed11bb760201b331086c979b86ab71", "size": 2706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/model.hpp", "max_stars_repo_name": "mjdousti/therminator", "max_stars_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_stars_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-26T00:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-09T03:19:38.000Z", "max_issues_repo_path": "src/headers/model.hpp", "max_issues_repo_name": "mjdousti/therminator", "max_issues_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_issues_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/headers/model.hpp", "max_forks_repo_name": "mjdousti/therminator", "max_forks_repo_head_hexsha": "d706ab43ac97a4266ce19618b1e35d4e0245cd5b", "max_forks_repo_licenses": ["Xnet", "X11", "RSA-MD"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T01:41:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T18:14:11.000Z", "avg_line_length": 27.8969072165, "max_line_length": 79, "alphanum_fraction": 0.6977087953, "num_tokens": 657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.5903969091342347}}
{"text": "//  (C) Copyright Jeremy William Murphy 2016.\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_GCD_HPP\n#define BOOST_MATH_TOOLS_POLYNOMIAL_GCD_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/math/common_factor_rt.hpp>\n#include <boost/type_traits/is_pod.hpp>\n\n\nnamespace boost{ \n   \n   namespace integer {\n\n      namespace gcd_detail {\n\n         template <class T>\n         struct gcd_traits;\n\n         template <class T>\n         struct gcd_traits<boost::math::tools::polynomial<T> >\n         {\n            inline static const boost::math::tools::polynomial<T>& abs(const boost::math::tools::polynomial<T>& val) { return val; }\n\n            static const method_type method = method_euclid;\n         };\n\n      }\n}\n   \n   \n   \nnamespace math{ namespace tools{\n    \n/* From Knuth, 4.6.1:\n* \n* We may write any nonzero polynomial u(x) from R[x] where R is a UFD as\n*\n*      u(x) = cont(u) · pp(u(x))\n*\n* where cont(u), the content of u, is an element of S, and pp(u(x)), the primitive\n* part of u(x), is a primitive polynomial over S. \n* When u(x) = 0, it is convenient to define cont(u) = pp(u(x)) = O.\n*/\n\ntemplate <class T>\nT content(polynomial<T> const &x)\n{\n    return x ? gcd_range(x.data().begin(), x.data().end()).first : T(0);\n}\n\n// Knuth, 4.6.1\ntemplate <class T>\npolynomial<T> primitive_part(polynomial<T> const &x, T const &cont)\n{\n    return x ? x / cont : polynomial<T>();\n}\n\n\ntemplate <class T>\npolynomial<T> primitive_part(polynomial<T> const &x)\n{\n    return primitive_part(x, content(x));\n}\n\n\n// Trivial but useful convenience function referred to simply as l() in Knuth.\ntemplate <class T>\nT leading_coefficient(polynomial<T> const &x)\n{\n    return x ? x.data().back() : T(0);\n}\n\n\nnamespace detail\n{\n    /* Reduce u and v to their primitive parts and return the gcd of their \n    * contents. Used in a couple of gcd algorithms.\n    */\n    template <class T>\n    T reduce_to_primitive(polynomial<T> &u, polynomial<T> &v)\n    {\n        using boost::math::gcd;\n        T const u_cont = content(u), v_cont = content(v);\n        u /= u_cont;\n        v /= v_cont;\n        return gcd(u_cont, v_cont);\n    }\n}\n\n\n/**\n* Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n* Algorithm 4.6.1C: Greatest common divisor over a unique factorization domain.\n* \n* The subresultant algorithm by George E. Collins [JACM 14 (1967), 128-142], \n* later improved by W. S. Brown and J. F. Traub [JACM 18 (1971), 505-514].\n* \n* Although step C3 keeps the coefficients to a \"reasonable\" size, they are\n* still potentially several binary orders of magnitude larger than the inputs.\n* Thus, this algorithm should only be used where T is a multi-precision type.\n* \n* @tparam   T   Polynomial coefficient type.\n* @param    u   First polynomial.\n* @param    v   Second polynomial.\n* @return       Greatest common divisor of polynomials u and v.\n*/\ntemplate <class T>\ntypename enable_if_c< std::numeric_limits<T>::is_integer, polynomial<T> >::type\nsubresultant_gcd(polynomial<T> u, polynomial<T> v)\n{\n    using std::swap;\n    BOOST_ASSERT(u || v);\n    \n    if (!u)\n        return v;\n    if (!v)\n        return u;\n    \n    typedef typename polynomial<T>::size_type N;\n    \n    if (u.degree() < v.degree())\n        swap(u, v);\n    \n    T const d = detail::reduce_to_primitive(u, v);\n    T g = 1, h = 1;\n    polynomial<T> r;\n    while (true)\n    {\n        BOOST_ASSERT(u.degree() >= v.degree());\n        // Pseudo-division.\n        r = u % v;\n        if (!r)\n            return d * primitive_part(v); // Attach the content.\n        if (r.degree() == 0)\n            return d * polynomial<T>(T(1)); // The content is the result.\n        N const delta = u.degree() - v.degree();\n        // Adjust remainder.\n        u = v;\n        v = r / (g * detail::integer_power(h, delta));\n        g = leading_coefficient(u);\n        T const tmp = detail::integer_power(g, delta);\n        if (delta <= N(1))\n            h = tmp * detail::integer_power(h, N(1) - delta);\n        else\n            h = tmp / detail::integer_power(h, delta - N(1));\n    }\n}\n \n \n/**\n * @brief GCD for polynomials with unbounded multi-precision integral coefficients.\n * \n * The multi-precision constraint is enforced via numeric_limits.\n *\n * Note that intermediate terms in the evaluation can grow arbitrarily large, hence the need for\n * unbounded integers, otherwise numeric loverflow would break the algorithm.\n * \n * @tparam  T   A multi-precision integral type.\n */\ntemplate <typename T>\ntypename enable_if_c<std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_bounded, polynomial<T> >::type\ngcd(polynomial<T> const &u, polynomial<T> const &v)\n{\n    return subresultant_gcd(u, v);\n}\n// GCD over bounded integers is not currently allowed:\ntemplate <typename T>\ntypename enable_if_c<std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_bounded, polynomial<T> >::type\ngcd(polynomial<T> const &u, polynomial<T> const &v)\n{\n   BOOST_STATIC_ASSERT_MSG(sizeof(v) == 0, \"GCD on polynomials of bounded integers is disallowed due to the excessive growth in the size of intermediate terms.\");\n   return subresultant_gcd(u, v);\n}\n// GCD over polynomials of floats can go via the Euclid algorithm:\ntemplate <typename T>\ntypename enable_if_c<!std::numeric_limits<T>::is_integer && (std::numeric_limits<T>::min_exponent != std::numeric_limits<T>::max_exponent) && !std::numeric_limits<T>::is_exact, polynomial<T> >::type\ngcd(polynomial<T> const &u, polynomial<T> const &v)\n{\n   return boost::integer::gcd_detail::Euclid_gcd(u, v);\n}\n\n}\n//\n// Using declaration so we overload the default implementation in this namespace:\n//\nusing boost::math::tools::gcd;\n\n}\n\nnamespace integer\n{\n   //\n   // Using declaration so we overload the default implementation in this namespace:\n   //\n   using boost::math::tools::gcd;\n}\n\n} // namespace boost::math::tools\n\n#endif\n", "meta": {"hexsha": "fdbafda6ca041cf3c704dade3b3e3f9c37f778e3", "size": 6066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/tools/polynomial_gcd.hpp", "max_stars_repo_name": "singhmanish979/Trend-Analytics", "max_stars_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-10-19T01:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:30:19.000Z", "max_issues_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/tools/polynomial_gcd.hpp", "max_issues_repo_name": "singhmanish979/Trend-Analytics", "max_issues_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-28T15:16:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-05T09:42:02.000Z", "max_forks_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/tools/polynomial_gcd.hpp", "max_forks_repo_name": "singhmanish979/Trend-Analytics", "max_forks_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T00:47:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:30:23.000Z", "avg_line_length": 28.8857142857, "max_line_length": 198, "alphanum_fraction": 0.6569403231, "num_tokens": 1580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5903968910751003}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    typedef std::vector<std::pair<std::string, nombre>> S;\n    typedef std::map<nombre, std::set<S>> C;\n\n    C construire(const S &score, const C &combinaisons) {\n        auto suivant = combinaisons;\n        for (const auto &s: score) {\n            for (const auto &r: combinaisons) {\n                auto c = r.second;\n                for (auto f: c) {\n                    f.push_back(s);\n                    std::sort(f.begin(), f.end());\n                    suivant[s.second + r.first].insert(f);\n                }\n            }\n        }\n        return suivant;\n    };\n}\n\nENREGISTRER_PROBLEME(109, \"Darts\") {\n    // In the game of darts a player throws three darts at a target board which is split into twenty equal sized\n    // sections numbered one to twenty.\n    //\n    // The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the\n    // red/green outer ring scores zero. The black and cream regions inside this\n    // ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores\n    // respectively.\n    // \n    // At the centre of the board are two concentric circles called the bull region, or bulls-eye. \n    // The outer bull is worth 25 points and the inner bull is a double, worth 50 points.\n    //\n    // There are many variations of rules but in the most popular game the players will begin with a score 301 or 501\n    // and the first player to reduce their running total to zero is a winner.\n    // However, it is normal to play a \"doubles out\" system, which means that the player must land a double (including\n    // the double bulls-eye at the centre of the board) on their final dart to win;\n    // any other dart that would reduce their running total to one or lower means the score for that set of three darts\n    // is \"bust\".\n    // \n    // When a player is able to finish on their current score it is called a \"checkout\" and the highest checkout is 170:\n    // T20 T20 D25 (two treble 20s and double bull).\n    // \n    // There are exactly eleven distinct ways to checkout on a score of 6:\n    //\n    //      D3\t\n    //      D1\tD2\t \n    //      S2\tD2\t \n    //      D2\tD1\t \n    //      S4\tD1\t \n    //      S1\tS1\tD2\n    //      S1\tT1\tD1\n    //      S1\tS3\tD1\n    //      D1\tD1\tD1\n    //      D1\tS2\tD1\n    //      S2\tS2\tD1\n    //\n    // Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination\n    // S1 T1 D1 is considered the same as T1 S1 D1.\n    //\n    // In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and\n    // 0 0 D3.\n    //\n    // Incredibly there are 42336 distinct ways of checking out in total.\n    // \n    // How many distinct ways can a player checkout with a score less than 100?\n    S score;\n    S score_double;\n\n    for (nombre n = 1; n < 21; ++n) {\n        score.emplace_back(utilitaires::concatener(\"S\", n), n);\n        score.emplace_back(utilitaires::concatener(\"D\", n), 2 * n);\n        score.emplace_back(utilitaires::concatener(\"T\", n), 3 * n);\n        score_double.emplace_back(utilitaires::concatener(\"D\", n), 2 * n);\n    }\n\n    score.emplace_back(utilitaires::concatener(\"S\", 25), 25);\n    score.emplace_back(utilitaires::concatener(\"D\", 25), 2 * 25);\n    score_double.emplace_back(utilitaires::concatener(\"D\", 25), 2 * 25);\n\n    const S zero{std::make_pair(\"0\", 0)};\n    C combinaisons;\n    combinaisons[0].insert(zero);\n\n    combinaisons = construire(score, combinaisons);\n    combinaisons = construire(score, combinaisons);\n\n    C solution;\n    for (const auto &s: score_double) {\n        for (const auto &r: combinaisons) {\n            auto c = r.second;\n            for (auto f: c) {\n                f.push_back(s);\n                solution[s.second + r.first].insert(f);\n            }\n        }\n    }\n\n    nombre resultat = 0;\n    for (const auto &r: solution) {\n        if (r.first < 100)\n            resultat += r.second.size();\n    }\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "2db8e63e4b8f3b8458e57c16097c9bfc01215a45", "size": 4240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme109.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme109.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme109.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8695652174, "max_line_length": 120, "alphanum_fraction": 0.608490566, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5903968869681483}}
{"text": "#include <iostream>\n#include <math.h>\n#include \"Vector.h\"\n#include <boost/multiprecision/gmp.hpp>\n\nusing namespace std;\n\nint target = 1000;\n\nint main(int argc, char** argv) {\n  boost::multiprecision::mpz_int min = 1;\n  for (int i = 1; i < target; i++) {\n    min *= 10;\n  }\n  Vector<boost::multiprecision::mpz_int> fibonacci;\n  fibonacci.insertBack(1);\n  fibonacci.insertBack(1);\n  while (fibonacci[fibonacci.length() - 1] < min) {\n    int end = fibonacci.length() - 1;\n    fibonacci.insertBack(fibonacci[end] + fibonacci[end - 1]);\n  }\n  cout << \"Index of first Fibonacci number with \" << target << \" digits: \" << fibonacci.length() << endl;\n  return 0;\n}\n", "meta": {"hexsha": "856e228b5b0bb6bab01392e466d697687480def9", "size": 656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "25.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": "25.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": "25.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": 26.24, "max_line_length": 105, "alphanum_fraction": 0.6539634146, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624791, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.5903101181124177}}
{"text": "/*\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http://mozilla.org/MPL/2.0/.\n*/\n\n\n#include <Eigen/Dense>\n\n#include \"fvElement.h\"\n\n#include \"fvElementBuilder.h\"\n\n\nnamespace Vitelotte\n{\n\n\ntemplate < class _Mesh, typename _Scalar >\nFVElementBuilder<_Mesh, _Scalar>::FVElementBuilder(Scalar sigma)\n  : m_sigma(sigma)\n{\n}\n\n\ntemplate < class _Mesh, typename _Scalar >\nunsigned\nFVElementBuilder<_Mesh, _Scalar>::\n    nCoefficients(const Mesh& mesh, Face element,\n                  SolverError* /*error*/) const\n{\n    return mesh.nVertexGradientConstraints(element)? 61: 45;\n}\n\n\ntemplate < class _Mesh, typename _Scalar >\nunsigned\nFVElementBuilder<_Mesh, _Scalar>::\n    nExtraConstraints(const Mesh& mesh, Face element) const\n{\n    return mesh.nVertexGradientConstraints(element)? 2: 0;\n}\n\n\ntemplate < class _Mesh, typename _Scalar >\ntemplate < typename Inserter >\nvoid\nFVElementBuilder<_Mesh, _Scalar>::\n    addCoefficients(Inserter& inserter, const Mesh& mesh,\n                    Face element, SolverError* error)\n{\n    if(mesh.valence(element) != 3)\n    {\n        if(error) error->error(\"Non-triangular face\");\n        return;\n    }\n\n    typedef Eigen::Matrix<Scalar, 9, 9> Matrix9;\n    Matrix9 sm;\n\n    int nodes[9];\n\n    typename Mesh::HalfedgeAroundFaceCirculator hit = mesh.halfedges(element);\n    typename Mesh::HalfedgeAroundFaceCirculator hend = hit;\n    do ++hit;\n    while(!mesh.isGradientConstraint(mesh.toVertex(*hit)) && hit != hend);\n    bool isPgc = mesh.isGradientConstraint(mesh.toVertex(*hit));\n\n    bool orient[3];\n    // TODO: remove dynamic allocation with dynamic dims.\n    Vector p[3];\n    --hit;\n    for(int i = 0; i < 3; ++i)\n    {\n        orient[i] = mesh.halfedgeOrientation(*hit);\n        nodes[3+i] = mesh.edgeValueNode(*hit).idx();\n        nodes[6+i] = mesh.edgeGradientNode(*hit).idx();\n        ++hit;\n        nodes[i] = mesh.toVertexValueNode(*hit).idx();\n        p[i] = mesh.position(mesh.toVertex(*hit)).template cast<Scalar>();\n    }\n\n    for(int i = 0; i < 9; ++i)\n    {\n        if(nodes[i] < 0)\n        {\n            if(error) error->error(\"Invalid node\");\n            return;\n        }\n    }\n\n    typedef FVElement<Scalar> Elem;\n    Elem elem(p);\n\n    if(elem.doubleArea() <= 0)\n    {\n        if(error) error->warning(\"Degenerated or reversed triangle\");\n    }\n\n    typedef Eigen::Array<Scalar, 3, 1> Array3;\n    Array3 dx2[9];\n    Array3 dy2[9];\n    Array3 dxy[9];\n    for(int pi = 0; pi < 3; ++pi)\n    {\n        Vector3 bc((pi == 0)? 0: .5,\n                   (pi == 1)? 0: .5,\n                   (pi == 2)? 0: .5);\n        typename Elem::Hessian hessians[9];\n        elem.hessian(bc, hessians);\n\n        for(int bi = 0; bi < 9; ++bi)\n        {\n            dx2[bi](pi) = hessians[bi](0, 0);\n            dy2[bi](pi) = hessians[bi](1, 1);\n            dxy[bi](pi) = hessians[bi](0, 1);\n        }\n    }\n\n    for(size_t i = 0; i < 9; ++i)\n    {\n        for(size_t j = i; j < 9; ++j)\n        {\n            EIGEN_ASM_COMMENT(\"MYBEGIN\");\n\n            Array3 quadPointValue =\n                    (dx2[i]+dy2[i]) * (dx2[j]+dy2[j])\n                  + (1.-m_sigma) * (\n                        2. * dxy[i] * dxy[j]\n                      - dx2[i] * dy2[j]\n                      - dx2[j] * dy2[i]);\n\n            Scalar value = quadPointValue.sum() * (elem.doubleArea() / 6);\n\n            EIGEN_ASM_COMMENT(\"MYEND\");\n\n            if((i < 6 || orient[i%3]) != (j < 6 || orient[j%3]))\n            {\n                value *= -1;\n            }\n\n            sm(i, j) = value;\n            sm(j, i) = value;\n        }\n    }\n\n    for(size_t i = 0; i < 9; ++i)\n    {\n        for(size_t j = 0; j < 9; ++j)\n        {\n            if(nodes[i] < nodes[j]) continue;\n            inserter.addCoeff(nodes[i], nodes[j], sm(i, j));\n        }\n    }\n\n    if(isPgc)\n    {\n        typedef Eigen::Matrix<Scalar, 9, 1> Vector9;\n        Vector9 fde1, fde2;\n        fde1 <<\n            -1.0L/2.0L*(elem.doubleArea()*(2*elem.dldn(0, 1) + elem.dldn(1, 1)) + 7*elem.edgeLength(1))/(elem.edgeLength(1)*elem.edgeLength(2)),\n            (1.0L/2.0L)*(elem.doubleArea()*(elem.dldn(0, 0) + 2*elem.dldn(1, 0)) - elem.edgeLength(0))/(elem.edgeLength(0)*elem.edgeLength(2)),\n            -1.0L/2.0L*elem.doubleArea()*(elem.edgeLength(0)*(elem.dldn(1, 1) + 2*elem.dldn(2, 1)) - elem.edgeLength(1)*(elem.dldn(0, 0) + 2*elem.dldn(2, 0)))/(elem.edgeLength(0)*elem.edgeLength(1)*elem.edgeLength(2)),\n            -4/elem.edgeLength(2),\n            4/elem.edgeLength(2),\n            4/elem.edgeLength(2),\n            elem.doubleArea()/(elem.edgeLength(0)*elem.edgeLength(2)),\n            -elem.doubleArea()/(elem.edgeLength(1)*elem.edgeLength(2)),\n            0;\n        fde2 <<\n            -1.0L/2.0L*(elem.doubleArea()*(2*elem.dldn(0, 2) + elem.dldn(2, 2)) + 7*elem.edgeLength(2))/(elem.edgeLength(1)*elem.edgeLength(2)),\n            -1.0L/2.0L*elem.doubleArea()*(elem.edgeLength(0)*(2*elem.dldn(1, 2) + elem.dldn(2, 2)) - elem.edgeLength(2)*(elem.dldn(0, 0) + 2*elem.dldn(1, 0)))/(elem.edgeLength(0)*elem.edgeLength(1)*elem.edgeLength(2)),\n            (1.0L/2.0L)*(elem.doubleArea()*(elem.dldn(0, 0) + 2*elem.dldn(2, 0)) - elem.edgeLength(0))/(elem.edgeLength(0)*elem.edgeLength(1)),\n            -4/elem.edgeLength(1),\n            4/elem.edgeLength(1),\n            4/elem.edgeLength(1),\n            elem.doubleArea()/(elem.edgeLength(0)*elem.edgeLength(1)),\n            0,\n            -elem.doubleArea()/(elem.edgeLength(1)*elem.edgeLength(2));\n\n        for(size_t i = 0; i < 9; ++i)\n        {\n            Scalar f = (i < 6 || orient[i%3])? 1: -1;\n            if(i != 8 /*fde1(i) != Scalar(0.)*/)\n            {\n                inserter.addExtraCoeff(element, 1, nodes[i], fde1(i) * f);\n            }\n            if(i != 7 /*fde2(i) != Scalar(0.)*/)\n            {\n                inserter.addExtraCoeff(element, 0, nodes[i], fde2(i) * f);\n            }\n        }\n    }\n}\n\n\ntemplate < class _Mesh, typename _Scalar >\ntemplate < typename Inserter >\nvoid\nFVElementBuilder<_Mesh, _Scalar>::\n    addExtraConstraints(Inserter& inserter, const Mesh& mesh,\n                                Face element, SolverError* /*error*/)\n{\n    typename Mesh::HalfedgeAroundFaceCirculator hit = mesh.halfedges(element);\n    typename Mesh::HalfedgeAroundFaceCirculator hend = hit;\n    do ++hit;\n    while(!mesh.isGradientConstraint(mesh.toVertex(*hit)) && hit != hend);\n    if(!mesh.isGradientConstraint(mesh.toVertex(*hit))) {\n        return;\n    }\n\n\n    for(unsigned hi = 0; hi < 2; ++hi)\n    {\n        typename Mesh::Halfedge h = *hit;\n\n        typename Mesh::Vertex from = mesh.fromVertex(h);\n        typename Mesh::Vertex to   = mesh.  toVertex(h);\n\n        bool v0c = mesh.isGradientConstraint(from);\n        const typename Mesh::Gradient& grad = mesh.gradientConstraint(v0c? from: to);\n        typename Mesh::Vector v = mesh.position(to) - mesh.position(from);\n        if(!v0c) v = -v;\n        typename Mesh::Value cons = grad * v;\n        inserter.setExtraRhs(element, hi, cons.template cast<Scalar>());\n\n        ++hit;\n    }\n\n}\n\n\n}\n", "meta": {"hexsha": "5182e1a74305c5570d3079c769f6e11128c9d1cf", "size": 7117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/fvElementBuilder.hpp", "max_stars_repo_name": "HoEmpire/slambook2", "max_stars_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/fvElementBuilder.hpp", "max_issues_repo_name": "HoEmpire/slambook2", "max_issues_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_issues_repo_licenses": ["MIT"], "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/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/fvElementBuilder.hpp", "max_forks_repo_name": "HoEmpire/slambook2", "max_forks_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_forks_repo_licenses": ["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.4145299145, "max_line_length": 218, "alphanum_fraction": 0.5488267528, "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5902385968581247}}
{"text": "#include <iostream>\n#include <cmath>\n#include <chrono>\n#include <limits>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/video/tracking.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"pose2d.h\"\n#include \"Ransac.hh\"\n#include \"PoseRANSAC.hh\"\n\n//#define USE_QUATERNION\n#define USE_ROTATION_MATRIX\n\nnamespace pose2d\n{\n/* Matrix coefficients for the non-depth case matrix to be solved by SVD */\n   inline double tx_coeff(double xp1, double yp1, double xq1, double yq1, const Eigen::Matrix3d& R)\n//---------------------------------------------------------------------------------------------------\n   {\n      return (R(1, 2) + R(1, 0) * xp1 + R(1, 1) * yp1 - R(2, 2) * yq1 + (-(R(2, 0) * xp1) - R(2, 1) * yp1) * yq1);\n      //return (R(1,2) + R(1,0)*xq1 - R(2,2)*yp1 - R(2,0)*xq1*yp1 + R(1,1)*yq1 - R(2,1)*yp1*yq1);\n   }\n\n   inline double ty_coeff(double xp1, double yp1, double xq1, double yq1, const Eigen::Matrix3d& R)\n//----------------------------------------------------------------------------------------------------\n   {\n      return (-R(0, 2) - R(0, 0) * xp1 + R(2, 2) * xq1 + R(2, 0) * xp1 * xq1 - R(0, 1) * yp1 + R(2, 1) * xq1 * yp1);\n      //return ((-R(0,2) + R(2,2)*xp1 - R(0,0)*xq1 + R(2,0)*xp1*xq1 - R(0,1)*yq1 + R(2,1)*xp1*yq1));\n   }\n\n   inline double tz_coeff(double xp1, double yp1, double xq1, double yq1, const Eigen::Matrix3d& R)\n//---------------------------------------------------------------------------------------------------\n   {\n      return (-(R(1, 2) * xq1) - R(1, 0) * xp1 * xq1 - R(1, 1) * xq1 * yp1 +\n              (R(0, 2) + R(0, 0) * xp1 + R(0, 1) * yp1) * yq1);\n//   return (-(R(1,2)*xp1) - R(1,0)*xp1*xq1 + R(0,2)*yp1 + R(0,0)*xq1*yp1 - R(1,1)*xp1*yq1 + R(0,1)*yp1*yq1);\n   }\n\n/* RHS values for depth solution*/\n   inline double b0(const Eigen::Matrix3d& R, const double x_0, const double y_0, const double d_0, const double y_1)\n   {\n      return d_0 *\n             (-R(1, 0) * x_0 - R(1, 1) * y_0 - R(1, 2) + R(2, 0) * x_0 * y_1 + R(2, 1) * y_0 * y_1 + R(2, 2) * y_1);\n   }\n\n   inline double b1(const Eigen::Matrix3d& R, const double x_0, const double y_0, const double d_0, const double x_1)\n   {\n      return -d_0 *\n             (-R(0, 0) * x_0 - R(0, 1) * y_0 - R(0, 2) + R(2, 0) * x_0 * x_1 + R(2, 1) * x_1 * y_0 + R(2, 2) * x_1);\n   }\n\n   inline double b2(const Eigen::Matrix3d& R, const double x_0, const double y_0, const double d_0,\n                    const double x_1, const double y_1)\n   {\n      return d_0 *\n             (-R(0, 0) * x_0 * y_1 - R(0, 1) * y_0 * y_1 - R(0, 2) * y_1 + R(1, 0) * x_0 * x_1 + R(1, 1) * x_1 * y_0 +\n              R(1, 2) * x_1);\n   }\n\n   inline double b0(double Qw, double Qx, double Qy, double Qz, double x_0, double y_0, double y_1, double d)\n   {\n      double Qw2 = Qw * Qw, Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, QwQx = Qw * Qx;\n      return d * (-Qw2 * y_1 - 2 * QwQx * y_0 * y_1 - 2 * QwQx + 2 * Qw * Qy * x_0 * y_1 + Qx2 * y_1 -\n                  2 * Qx * Qz * x_0 * y_1 +\n                  Qy2 * y_1 - 2 * Qy * Qz * y_0 * y_1 + 2 * Qy * Qz - Qz2 * y_1 + 2 * x_0 * (Qw * Qz + Qx * Qy) +\n                  y_0 * (Qw2 -\n                         Qx2 + Qy2 - Qz2));\n   }\n\n   inline double b1(double Qw, double Qx, double Qy, double Qz, double x_0, double y_0, double x_1, double d)\n   {\n      double Qw2 = Qw * Qw, Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, QwQy = Qw * Qy, QxQz = Qx * Qz;\n      return -d *\n             (-Qw2 * x_1 - 2 * Qw * Qx * x_1 * y_0 + 2 * QwQy * x_0 * x_1 + 2 * QwQy - 2 * Qw * Qz * y_0 + Qx2 * x_1 +\n              2 * Qx * Qy * y_0 - 2 * QxQz * x_0 * x_1 + 2 * QxQz + Qy2 * x_1 - 2 * Qy * Qz * x_1 * y_0 - Qz2 * x_1 +\n              x_0 * (Qw2 + Qx2 - Qy2 - Qz2));\n   }\n\n   inline double b2(double Qw, double Qx, double Qy, double Qz, double x_0, double y_0, double x_1, double y_1, double d)\n   {\n      double Qw2 = Qw * Qw, Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, QwQz = Qw * Qz, QxQy = Qx * Qy;\n      return -d *\n             (-Qw2 * x_0 * y_1 - 2 * Qw * Qx * x_1 - 2 * Qw * Qy * y_1 + 2 * QwQz * x_0 * x_1 + 2 * QwQz * y_0 * y_1 -\n              Qx2 * x_0 * y_1 + 2 * QxQy * x_0 * x_1 - 2 * QxQy * y_0 * y_1 - 2 * Qx * Qz * y_1 + Qy2 * x_0 * y_1 +\n              2 * Qy * Qz * x_1 + Qz2 * x_0 * y_1 + x_1 * y_0 * (Qw2 - Qx2 + Qy2 - Qz2));\n\n   }\n\n   inline Eigen::Vector3d homogeneous(Eigen::Matrix3d A)\n   //---------------------------------------------------------------------------------------------------------------------------\n   {\n      Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::FullPivHouseholderQRPreconditioner>\n            svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      auto U = svd.matrixU();\n      auto V = svd.matrixV();\n      return V.col(V.cols() - 1);\n   }\n\n   inline Eigen::Quaterniond rotation(const Eigen::Vector3d &from, const Eigen::Vector3d &to,\n                                      const Eigen::Vector3d &fallbackAxis = Eigen::Vector3d(0, 0, 0))\n   //-----------------------------------------------------------------------------------------------\n   {\n      Eigen::Quaterniond q;\n      Eigen::Vector3d v0 = from;\n      Eigen::Vector3d v1 = to;\n      v0.normalize();\n      v1.normalize();\n\n      double d = v0.dot(v1);\n      if (d >= 1.0f)\n         return Eigen::Quaterniond(1, 0, 0, 0);\n\n      if (d < (1e-6f - 1.0f))\n      {\n         if (fallbackAxis != Eigen::Vector3d(0, 0, 0))\n            q = Eigen::AngleAxis<double>(PI, fallbackAxis);\n         else\n         {\n            // Generate an axis\n            Eigen::Vector3d axis = Eigen::Vector3d(1, 0, 0).cross(from);\n            if (axis.norm() < 0.000000001) // pick another if colinear\n               axis = Eigen::Vector3d(0, 1, 0).cross(from);\n            axis.normalize();\n            q = Eigen::AngleAxis<double>(PI, axis);\n         }\n      }\n      else\n      {\n         double s = sqrt((1 + d) * 2);\n         double invs = 1 / s;\n\n         Eigen::Vector3d c = v0.cross(v1);\n\n         q.x() = c.x() * invs;\n         q.y() = c.y() * invs;\n         q.z() = c.z() * invs;\n         q.w() = s * 0.5f;\n         q.normalize();\n      }\n      return q;\n   }\n\n   void pose(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts, const Eigen::Vector3d& train_g,\n             const Eigen::Vector3d query_g, const cv::Mat& intrinsics,\n             Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n//-----------------------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K((double*) intrinsics.data);\n      pose(pts, train_g, query_g, K, Q, translation);\n   }\n\n   void pose(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n             const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n             const Eigen::Matrix3d& K, Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n   //--------------------------------------------------------------------------------------\n   {\n      Eigen::Matrix3d KI = K.inverse();\n      //   std::cout << K << std::endl << KI << std::endl;\n      //   if (std::isnan(KI(0,0))) KI = K;\n\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n      //   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n      Eigen::Matrix3d R = Q.toRotationMatrix();\n      size_t m = pts.size();\n      Eigen::MatrixXd A(m, 3);\n      for (size_t row = 0; row < m; row++)\n      {\n         const cv::Point3d& tpt = pts[row].first;\n         const cv::Point3d& qpt = pts[row].second;\n         Eigen::Vector3d train_ray = KI*Eigen::Vector3d(tpt.x, tpt.y, 1);\n         Eigen::Vector3d query_ray = KI*Eigen::Vector3d(qpt.x, qpt.y, 1);\n         double xt1 = train_ray[0], yt1 = train_ray[1], xq1 = query_ray[0], yq1 = query_ray[1];\n         A.row(row) << tx_coeff(xt1, yt1, xq1, yq1, R),\n               ty_coeff(xt1, yt1, xq1, yq1, R),\n               tz_coeff(xt1, yt1, xq1, yq1, R);\n      }\n\n      Eigen::JacobiSVD<Eigen::MatrixXd, Eigen::FullPivHouseholderQRPreconditioner>\n            svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n      auto V = svd.matrixV();\n      translation = V.col(V.cols() - 1);\n//   assert(mut::check_essential(R, translation));\n   }\n\n   void pose(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n             const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g, const double depth,\n             const cv::Mat& intrinsics, Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n//-----------------------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K((double*) intrinsics.data);\n      pose(pts, train_g, query_g, depth, K, Q, translation);\n   }\n\n   void pose(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n             const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g, const double depth,\n             const Eigen::Matrix3d& K, Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n   //--------------------------------------------------------------------------------------\n   {\n      size_t m = pts.size();\n//   if ( (! std::isnan(depth)) && (m > 6 ) )\n//   {\n//      pose_ransac(pts, train_g, query_g, depth, K, Q, translation, 3);\n//      return;\n//   }\n      Eigen::Matrix3d KI = K.inverse();\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n//   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n\n      Eigen::Matrix3d R = Q.toRotationMatrix();\n      Eigen::MatrixXd A(3 * m, 3);\n      Eigen::VectorXd b(m * 3);\n      for (size_t row = 0, ri = 0; row < m; row++)\n      {\n         const cv::Point3d& tpt = pts[row].first;\n         const cv::Point3d& qpt = pts[row].second;\n         Eigen::Vector3d train_ray = KI*Eigen::Vector3d(tpt.x, tpt.y, 1);\n         Eigen::Vector3d query_ray = KI*Eigen::Vector3d(qpt.x, qpt.y, 1);\n         double xt1 = train_ray[0], yt1 = train_ray[1], xq1 = query_ray[0], yq1 = query_ray[1];\n#ifdef USE_ROTATION_MATRIX\n         A.row(ri) << 0, 1, -yq1;\n         b(ri++) = b0(R, xt1, yt1, depth, yq1);\n         A.row(ri) << -1, 0, xq1;\n         b(ri++) = b1(R, xt1, yt1, depth, xq1);\n         A.row(ri) << yq1, -xq1, 0;\n         b(ri++) = b2(R, xt1, yt1, depth, xq1, yq1);\n#endif\n#ifdef USE_QUATERNION\n         A.row(ri) << 0, -1, yq1;\n         b(ri++) = b0(Q.w(), Q.x(), Q.y(), Q.z(), xt1, yt1, yq1, d);\n         A.row(ri) <<  1, 0, -xq1;\n         b(ri++) = b1(Q.w(), Q.x(), Q.y(), Q.z(), xt1, yt1, xq1, d);\n         A.row(ri) << -yq1, xq1, 0;\n         b(ri++) = b2(Q.w(), Q.x(), Q.y(), Q.z(), xt1, yt1, xq1, yq1, d);\n#endif\n      }\n   std::cout << \"Rank \" << A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).rank() << std::endl;\n//      Eigen::ColPivHouseholderQR<Eigen::MatrixXd> MQR(A);\n//      translation = MQR.solve(b);\n   translation = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n   }\n\n   double pose_ransac(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                      const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n                      const cv::Mat& intrinsics, Eigen::Quaterniond& Q, Eigen::Vector3d& translation,\n                      void* RANSAC_params, int samples)\n   //------------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K((double*) intrinsics.data);\n      return pose_ransac(pts, train_g, query_g, K, Q, translation, RANSAC_params, samples);\n   }\n\n   double pose_ransac(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                      const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n                      const Eigen::Matrix3d& K, Eigen::Quaterniond& Q, Eigen::Vector3d& translation,\n                      void* RANSAC_params, int samples)\n   //-----------------------------------------------------------------------------------------------\n   {\n      if (RANSAC_params == nullptr) throw std::logic_error(\"pose2d::pose_ransac (no depth): RANSAC params are null\");\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n//   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n      double confidence = -1;\n#ifdef USE_THEIA_RANSAC\n      Grav2DRansacEstimator estimator(K, Q, -1, samples);\n      theia::RansacParameters* parameters = static_cast<theia::RansacParameters*>(RANSAC_params);\n      theia::RansacSummary summary;\n      std::unique_ptr<theia::SampleConsensusEstimator<Grav2DRansacEstimator>> ransac =\n            theia::CreateAndInitializeRansacVariant(theia::RansacType::RANSAC, *parameters, estimator);\n      if (ransac)\n      {\n         GravPoseRansacModel best_model;\n         ransac->Estimate(pts, &best_model, &summary);\n         confidence = summary.confidence;\n         if (confidence > 0)\n         {\n            Q = best_model.rotation;\n            translation = best_model.translation;\n         }\n      }\n#else\n      templransac::RANSACParams* parameters = static_cast<templransac::RANSACParams*>(RANSAC_params);\n      Grav2DRansacEstimator estimator(K, Q);\n      Grav2DRansacData data(pts);\n      std::vector<std::pair<double, GravPoseRansacModel> > results;\n      std::vector<std::vector<size_t>> inlier_indices;\n      std::stringstream errs;\n      confidence = templransac::RANSAC(*parameters, estimator, data, pts.size(), samples, 1,\n                                       results, inlier_indices, &errs);\n      if (confidence > 0)\n      {\n         GravPoseRansacModel& model = results[0].second;\n         translation = model.translation;\n      }\n#endif\n      return confidence;\n   }\n\n   double pose_ransac(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                      const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n                      const double depth, const cv::Mat& intrinsics,\n                      Eigen::Quaterniond& Q, Eigen::Vector3d& translation,\n                      void* RANSAC_params, int samples)\n   //----------------------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> K((double*) intrinsics.data);\n      return pose_ransac(pts, train_g, query_g, depth, K, Q, translation, RANSAC_params, samples);\n   }\n\n   double pose_ransac(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                      const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n                      const double depth, const Eigen::Matrix3d& K,\n                      Eigen::Quaterniond& Q, Eigen::Vector3d& translation,\n                      void *RANSAC_params, int samples)\n   //---------------------------------------------------------------------------------\n   {\n      if (RANSAC_params == nullptr) throw std::logic_error(\"pose2d::pose_ransac (with depth): RANSAC params are null\");\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n//   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n      double confidence = -1;\n#ifdef USE_THEIA_RANSAC\n      Grav2DRansacEstimator estimator(K, Q, depth, samples);\n      theia::RansacParameters* parameters = static_cast<theia::RansacParameters*>(RANSAC_params);\n      theia::RansacSummary summary;\n      std::unique_ptr<theia::SampleConsensusEstimator<Grav2DRansacEstimator>> ransac =\n            theia::CreateAndInitializeRansacVariant(theia::RansacType::RANSAC, *parameters, estimator);\n      if (ransac)\n      {\n         GravPoseRansacModel best_model;\n\n         if (ransac->Estimate(pts, &best_model, &summary))\n         {\n            confidence = summary.confidence;\n            if (confidence > 0)\n            {\n               Q = best_model.rotation;\n               translation = best_model.translation;\n            }\n         }\n      }\n#else\n      templransac::RANSACParams* parameters = static_cast<templransac::RANSACParams*>(RANSAC_params);\n      Grav2DDepthRansacEstimator estimator(K, Q, depth);\n      Grav2DRansacData data(pts);\n      std::vector<std::pair<double, GravPoseRansacModel>> results;\n      std::vector<std::vector<size_t>> inlier_indices;\n      std::stringstream errs;\n      confidence = templransac::RANSAC(*parameters, estimator, data, pts.size(), samples, 1,\n                                       results, inlier_indices, &errs);\n      if (confidence > 0)\n      {\n         GravPoseRansacModel& model = results[0].second;\n         translation = model.translation;\n\n//      for (size_t k=0; k<results.size(); k++)\n//      {\n//         std::pair<double, Grav2DRansacModel> pp = results[k];\n//         std::cout << \"RANSAC Result \" << pp.second.translation.transpose() << \" \";\n//         std::vector<size_t> inliers = inlier_indices[k];\n//         for (size_t inlier : inliers)\n//            std::cout << train_img_pts[inlier] << \" -> \" << query_image_pts[inlier] << \" | \";\n//         std::cout << std::endl;\n//      }\n      }\n#endif\n      return confidence;\n   }\n\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation)\n//----------------------------------------------------------------------------------------------------------------\n   {\n      const cv::Point3d& tpt0 = pts[0].first;\n      const cv::Point3d& qpt0 = pts[0].second;\n      const cv::Point3d& tpt1 = pts[1].first;\n      const cv::Point3d& qpt1 = pts[1].second;\n      const cv::Point3d& tpt2 = pts[2].first;\n      const cv::Point3d& qpt2 = pts[2].second;\n      Eigen::Vector3d train_ray1 = Kinv*Eigen::Vector3d(tpt0.x, tpt0.y, 1);\n      Eigen::Vector3d query_ray1 = Kinv*Eigen::Vector3d(qpt0.x, qpt0.y, 1);\n      Eigen::Vector3d train_ray2 = Kinv*Eigen::Vector3d(tpt1.x, tpt1.y, 1);\n      Eigen::Vector3d query_ray2 = Kinv*Eigen::Vector3d(qpt1.x, qpt1.y, 1);\n      Eigen::Vector3d train_ray3 = Kinv*Eigen::Vector3d(tpt2.x, tpt2.y, 1);\n      Eigen::Vector3d query_ray3 = Kinv*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double xt1 = train_ray1[0], yt1 = train_ray1[1], xq1 = query_ray1[0], yq1 = query_ray1[1];\n      double xt2 = train_ray2[0], yt2 = train_ray2[1], xq2 = query_ray2[0], yq2 = query_ray2[1];\n      double xt3 = train_ray3[0], yt3 = train_ray3[1], xq3 = query_ray3[0], yq3 = query_ray3[1];\n      Eigen::Matrix3d A;\n      A << tx_coeff(xt1, yt1, xq1, yq1, R),\n            ty_coeff(xt1, yt1, xq1, yq1, R),\n            tz_coeff(xt1, yt1, xq1, yq1, R),\n\n            tx_coeff(xt2, yt2, xq2, yq2, R),\n            ty_coeff(xt2, yt2, xq2, yq2, R),\n            tz_coeff(xt2, yt2, xq2, yq2, R),\n\n            tx_coeff(xt3, yt3, xq3, yq3, R),\n            ty_coeff(xt3, yt3, xq3, yq3, R),\n            tz_coeff(xt3, yt3, xq3, yq3, R);\n      translation = homogeneous(A);\n   }\n\n   //Called by RANSAC estimation\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<cv::Point3d>& train_img_pts,\n                         const std::vector<cv::Point3d>& query_img_pts,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation)\n//------------------------------------------------------------------------\n   {\n      const cv::Point3d& tpt0 = train_img_pts[0];\n      const cv::Point3d& tpt1 = train_img_pts[1];\n      const cv::Point3d& tpt2 = train_img_pts[2];\n      const cv::Point3d& qpt0 = query_img_pts[0];\n      const cv::Point3d& qpt1 = query_img_pts[1];\n      const cv::Point3d& qpt2 = query_img_pts[2];\n      Eigen::Vector3d train_ray1 = Kinv*Eigen::Vector3d(tpt0.x, tpt0.y, 1);\n      Eigen::Vector3d query_ray1 = Kinv*Eigen::Vector3d(qpt0.x, qpt0.y, 1);\n      Eigen::Vector3d train_ray2 = Kinv*Eigen::Vector3d(tpt1.x, tpt1.y, 1);\n      Eigen::Vector3d query_ray2 = Kinv*Eigen::Vector3d(qpt1.x, qpt1.y, 1);\n      Eigen::Vector3d train_ray3 = Kinv*Eigen::Vector3d(tpt2.x, tpt2.y, 1);\n      Eigen::Vector3d query_ray3 = Kinv*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double xt1 = train_ray1[0], yt1 = train_ray1[1], xq1 = query_ray1[0], yq1 = query_ray1[1];\n      double xt2 = train_ray2[0], yt2 = train_ray2[1], xq2 = query_ray2[0], yq2 = query_ray2[1];\n      double xt3 = train_ray3[0], yt3 = train_ray3[1], xq3 = query_ray3[0], yq3 = query_ray3[1];\n      Eigen::Matrix3d A;\n      A << tx_coeff(xt1, yt1, xq1, yq1, R),\n            ty_coeff(xt1, yt1, xq1, yq1, R),\n            tz_coeff(xt1, yt1, xq1, yq1, R),\n\n            tx_coeff(xt2, yt2, xq2, yq2, R),\n            ty_coeff(xt2, yt2, xq2, yq2, R),\n            tz_coeff(xt2, yt2, xq2, yq2, R),\n\n            tx_coeff(xt3, yt3, xq3, yq3, R),\n            ty_coeff(xt3, yt3, xq3, yq3, R),\n            tz_coeff(xt3, yt3, xq3, yq3, R);\n      translation = homogeneous(A);\n   }\n\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts, const double depth,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation)\n   //-------------------------------------------------------------------------\n   {\n      const cv::Point3d& tpt0 = pts[0].first;\n      const cv::Point3d& qpt0 = pts[0].second;\n      const cv::Point3d& tpt1 = pts[1].first;\n      const cv::Point3d& qpt1 = pts[1].second;\n      const cv::Point3d& tpt2 = pts[2].first;\n      const cv::Point3d& qpt2 = pts[2].second;\n      Eigen::Vector3d train_ray1 = Kinv*Eigen::Vector3d(tpt0.x, tpt0.y, 1);\n      Eigen::Vector3d query_ray1 = Kinv*Eigen::Vector3d(qpt0.x, qpt0.y, 1);\n      Eigen::Vector3d train_ray2 = Kinv*Eigen::Vector3d(tpt1.x, tpt1.y, 1);\n      Eigen::Vector3d query_ray2 = Kinv*Eigen::Vector3d(qpt1.x, qpt1.y, 1);\n      Eigen::Vector3d train_ray3 = Kinv*Eigen::Vector3d(tpt2.x, tpt2.y, 1);\n      Eigen::Vector3d query_ray3 = Kinv*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double xt1 = train_ray1[0], yt1 = train_ray1[1], xq1 = query_ray1[0], yq1 = query_ray1[1];\n      double xt2 = train_ray2[0], yt2 = train_ray2[1], xq2 = query_ray2[0], yq2 = query_ray2[1];\n      double xt3 = train_ray3[0], yt3 = train_ray3[1], xq3 = query_ray3[0], yq3 = query_ray3[1];\n//   Eigen::MatrixXd A(9, 3);\n//   Eigen::VectorXd b(9);\n      Eigen::Matrix<double, 9, 3> A;\n      Eigen::Matrix<double, 9, 1> b;\n      A << 0, 1, -yq1,\n            -1, 0, xq1,\n            yq1, -xq1, 0,\n\n            0, 1, -yq2,\n            -1, 0, xq2,\n            yq2, -xq2, 0,\n\n            0, 1, -yq3,\n            -1, 0, xq3,\n            yq3, -xq3, 0;\n\n      b << b0(R, xt1, yt1, depth, yq1), b1(R, xt1, yt1, depth, xq1), b2(R, xt1, yt1, depth, xq1, yq1),\n            b0(R, xt2, yt2, depth, yq2), b1(R, xt2, yt2, depth, xq2), b2(R, xt2, yt2, depth, xq2, yq2),\n            b0(R, xt3, yt3, depth, yq3), b1(R, xt3, yt3, depth, xq3), b2(R, xt3, yt3, depth, xq3, yq3);\n//      Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 9, 3>> MQR(A);\n//      translation = MQR.solve(b);\n      translation = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n//   std::cout << \"Rank \" << A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).rank() << std::endl;\n   }\n\n   //Called by RANSAC estimation\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<cv::Point3d>& train_img_pts,\n                         const std::vector<cv::Point3d>& query_img_pts, const double depth,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation)\n   //-------------------------------------------------------------------------\n   {\n      const cv::Point3d& tpt0 = train_img_pts[0];\n      const cv::Point3d& tpt1 = train_img_pts[1];\n      const cv::Point3d& tpt2 = train_img_pts[2];\n      const cv::Point3d& qpt0 = query_img_pts[0];\n      const cv::Point3d& qpt1 = query_img_pts[1];\n      const cv::Point3d& qpt2 = query_img_pts[2];\n      Eigen::Vector3d train_ray1 = Kinv*Eigen::Vector3d(tpt0.x, tpt0.y, 1);\n      Eigen::Vector3d query_ray1 = Kinv*Eigen::Vector3d(qpt0.x, qpt0.y, 1);\n      Eigen::Vector3d train_ray2 = Kinv*Eigen::Vector3d(tpt1.x, tpt1.y, 1);\n      Eigen::Vector3d query_ray2 = Kinv*Eigen::Vector3d(qpt1.x, qpt1.y, 1);\n      Eigen::Vector3d train_ray3 = Kinv*Eigen::Vector3d(tpt2.x, tpt2.y, 1);\n      Eigen::Vector3d query_ray3 = Kinv*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double xt1 = train_ray1[0], yt1 = train_ray1[1], xq1 = query_ray1[0], yq1 = query_ray1[1];\n      double xt2 = train_ray2[0], yt2 = train_ray2[1], xq2 = query_ray2[0], yq2 = query_ray2[1];\n      double xt3 = train_ray3[0], yt3 = train_ray3[1], xq3 = query_ray3[0], yq3 = query_ray3[1];\n//   Eigen::MatrixXd A(9, 3);\n//   Eigen::VectorXd b(9);\n      Eigen::Matrix<double, 9, 3> A;\n      Eigen::Matrix<double, 9, 1> b;\n      A << 0, 1, -yq1,\n            -1, 0, xq1,\n            yq1, -xq1, 0,\n\n            0, 1, -yq2,\n            -1, 0, xq2,\n            yq2, -xq2, 0,\n\n            0, 1, -yq3,\n            -1, 0, xq3,\n            yq3, -xq3, 0;\n\n      b << b0(R, xt1, yt1, depth, yq1), b1(R, xt1, yt1, depth, xq1), b2(R, xt1, yt1, depth, xq1, yq1),\n            b0(R, xt2, yt2, depth, yq2), b1(R, xt2, yt2, depth, xq2), b2(R, xt2, yt2, depth, xq2, yq2),\n            b0(R, xt3, yt3, depth, yq3), b1(R, xt3, yt3, depth, xq3), b2(R, xt3, yt3, depth, xq3, yq3);\n//      Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 9, 3>> MQR(A);\n//      translation = MQR.solve(b);\n      translation = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n//   std::cout << \"Rank \" << A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).rank() << std::endl;\n   }\n}", "meta": {"hexsha": "ecad36d5afdfb2de57bd79334fe46d4e8dd84437", "size": 26013, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose/pose2d.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/pose2d.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/pose2d.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": 47.5557586837, "max_line_length": 134, "alphanum_fraction": 0.5406143082, "num_tokens": 8689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5902385748682625}}
{"text": "#pragma once\n\n#define BOOST_MATH_PROMOTE_DOUBLE_POLICY false\n#include \"tools.hpp\"\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/math/distributions.hpp>\n#include <boost/math/special_functions/hermite.hpp>\n#include <random>\n#include <vector>\n\nnamespace kde1d {\n\n//! statistical functions\nnamespace stats {\n\n//! standard normal density\n//! @param x evaluation points.\n//! @return matrix of pdf values.\ninline Eigen::MatrixXd\ndnorm(const Eigen::MatrixXd& x)\n{\n  boost::math::normal dist;\n  return x.unaryExpr(\n    [&dist](const double& y) { return boost::math::pdf(dist, y); });\n};\n\n//! standard normal density\n//! @param x evaluation points.\n//! @param drv order of the derivative\n//! @return matrix of pdf values.\ninline Eigen::MatrixXd\ndnorm_drv(const Eigen::MatrixXd& x, unsigned drv)\n{\n  boost::math::normal dist;\n  double rt2 = std::sqrt(2);\n  return x.unaryExpr([&dist, &drv, &rt2](const double& y) {\n    double res = boost::math::pdf(dist, y);\n    // boost implementes phsyicist's hermite poly; rescale to probabilist's.\n    res *= boost::math::hermite(drv, y / rt2);\n    res *= std::pow(0.5, drv * 0.5);\n    if (drv % 2)\n      res = -res;\n    return res;\n  });\n};\n\n//! standard normal cdf\n//! @param x evaluation points.\n//! @return matrix of cdf values.\ninline Eigen::MatrixXd\npnorm(const Eigen::MatrixXd& x)\n{\n  boost::math::normal dist;\n  return x.unaryExpr(\n    [&dist](const double& y) { return boost::math::cdf(dist, y); });\n};\n\n//! standard normal quantiles\n//! @param x evaluation points.\n//! @return matrix of quantiles.\ninline Eigen::MatrixXd\nqnorm(const Eigen::MatrixXd& x)\n{\n  boost::math::normal dist;\n  return x.unaryExpr(\n    [&dist](const double& y) { return boost::math::quantile(dist, y); });\n};\n\n//! empirical quantiles\n//! @param x data.\n//! @param q evaluation points.\n//! @return vector of quantiles.\ninline Eigen::VectorXd\nquantile(const Eigen::VectorXd& x, const Eigen::VectorXd& q)\n{\n  double n = static_cast<double>(x.size() - 1);\n  size_t m = q.size();\n  Eigen::VectorXd res(m);\n\n  // map to std::vector and sort\n  std::vector<double> x2(x.data(), x.data() + x.size());\n  std::sort(x2.begin(), x2.end());\n\n  // linear interpolation (quantile of type 7 in R)\n  for (size_t i = 0; i < m; ++i) {\n    size_t k = std::floor(n * q(i));\n    double p = static_cast<double>(k) / n;\n    res(i) = x2[k];\n    if (k < n)\n      res(i) += (x2[k + 1] - x2[k]) * (q(i) - p) * n;\n  }\n  return res;\n}\n\n//! empirical quantiles\n//! @param x data.\n//! @param q evaluation points.\n//! @param w vector of weights.\n//! @return vector of quantiles.\ninline Eigen::VectorXd\nquantile(const Eigen::VectorXd& x,\n         const Eigen::VectorXd& q,\n         const Eigen::VectorXd& w)\n{\n  if (w.size() == 0)\n    return quantile(x, q);\n  if (w.size() != x.size())\n    throw std::runtime_error(\"x and w must have the same size\");\n  double n = static_cast<double>(x.size());\n  size_t m = q.size();\n  Eigen::VectorXd res(m);\n\n  // map to std::vector and sort\n  std::vector<size_t> ind(n);\n  for (size_t i = 0; i < n; ++i)\n    ind[i] = i;\n  std::sort(\n    ind.begin(), ind.end(), [&x](size_t i, size_t j) { return x(i) < x(j); });\n\n  auto x2 = x;\n  auto wcum = w;\n  double wacc = 0.0;\n  for (size_t i = 0; i < n; ++i) {\n    x2(i) = x(ind[i]);\n    wcum(i) = wacc;\n    wacc += w(ind[i]);\n  }\n\n  double wsum = w.sum() - w(ind[n - 1]);\n  ;\n  for (size_t j = 0; j < m; ++j) {\n    size_t i = 1;\n    while ((wcum(i) < q(j) * wsum) & (i < n))\n      i++;\n    res(j) = x2(i - 1);\n    if (w(ind[i - 1]) > 1e-30) {\n      res(j) +=\n        (x2(i) - x2(i - 1)) * (q(j) - wcum(i - 1) / wsum) / w(ind[i - 1]);\n    }\n  }\n\n  return res;\n}\n\n// conditionally equidistant jittering; equivalent to the R implementation:\n//   tab <- table(x)\n//   noise <- unname(unlist(lapply(tab, function(l) -0.5 + 1:l / (l + 1))))\n//   s <- sort(x, index.return = TRUE)\n//   return((s$x + noise)[rank(x, ties.method = \"first\", na.last = \"keep\")])\ninline Eigen::VectorXd\nequi_jitter(const Eigen::VectorXd& x)\n{\n  size_t n = x.size();\n\n  // first compute the corresponding permutation that sorts x (required later)\n  auto perm = tools::get_order(x);\n  // actually sort x\n  Eigen::VectorXd srt(n);\n  for (size_t i = 0; i < n; ++i)\n    srt(i) = x(perm(i));\n\n  // compute contingency table\n  Eigen::MatrixXd tab(n, 2);\n  size_t lev = 0;\n  size_t cnt = 1;\n  for (size_t k = 1; k < n; ++k) {\n    if (srt(k - 1) != srt(k)) {\n      tab(lev, 0) = srt(k - 1);\n      tab(lev++, 1) = cnt;\n      cnt = 1;\n    } else {\n      cnt++;\n      if (k == n - 1) {\n        tab(lev, 0) = srt(k);\n        tab(lev++, 1) = cnt;\n      }\n    }\n  }\n  tab.conservativeResize(lev, 2);\n\n  // add deterministic, conditionally uniorm noise\n  Eigen::VectorXd noise = Eigen::VectorXd::Zero(n);\n  size_t i = 0;\n  for (long k = 0; k < tab.rows(); ++k) {\n    for (size_t cnt = 1; cnt <= tab(k, 1); ++cnt)\n      noise(i++) = -0.5 + cnt / (tab(k, 1) + 1.0);\n    cnt = 1;\n  }\n  Eigen::VectorXd jtr = srt + noise;\n\n  // invert the permutation to return jittered x in original order\n  for (long i = 0; i < perm.size(); ++i)\n    srt(perm(i)) = jtr(i);\n\n  return srt;\n}\n\n//! @brief simulates from the standard uniform distribution.\n//!\n//! @param n number of observations.\n//! @param seeds seeds of the random number generator; if empty (default),\n//!   the random number generator is seeded randomly.\n//!\n//! @return An size n vector of independent \\f$ \\mathrm{U}[0, 1] \\f$ random\n//!   variables.\ninline Eigen::VectorXd\nsimulate_uniform(size_t n, std::vector<int> seeds)\n{\n  if (n < 1)\n    throw std::runtime_error(\"n  must be at least 1.\");\n\n  if (seeds.size() == 0) { // no seeds provided, seed randomly\n    std::random_device rd{};\n    seeds = std::vector<int>(5);\n    for (auto& s : seeds)\n      s = static_cast<int>(rd());\n  }\n\n  // initialize random engine and uniform distribution\n  std::seed_seq seq(seeds.begin(), seeds.end());\n  std::mt19937 generator(seq);\n  std::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n  Eigen::VectorXd U(n);\n  return U.unaryExpr([&](double) { return distribution(generator); });\n}\n\n} // end kde1d::stats\n\n} // end kde1d\n", "meta": {"hexsha": "4ed89b24e7d3e5713da90460da0f59d73776d3d6", "size": 6095, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kde1d/stats.hpp", "max_stars_repo_name": "vinecopulib/kde1d-cpp", "max_stars_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/kde1d/stats.hpp", "max_issues_repo_name": "vinecopulib/kde1d-cpp", "max_issues_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kde1d/stats.hpp", "max_forks_repo_name": "vinecopulib/kde1d-cpp", "max_forks_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_forks_repo_licenses": ["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.2715517241, "max_line_length": 78, "alphanum_fraction": 0.6001640689, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5902366613553575}}
{"text": "#include \"incidencematrices.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <array>\n#include <memory>\n\nnamespace IncidenceMatrices {\n\n/** @brief Create the mesh consisting of a triangle and quadrilateral\n *         from the exercise sheet.\n * @return Shared pointer to the hybrid2d mesh.\n */\nstd::shared_ptr<lf::mesh::Mesh> createDemoMesh() {\n  // builder for a hybrid mesh in a world of dimension 2\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Add points\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 0});    // (0)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 0});    // (1)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 1});    // (2)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 1});    // (3)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0.5, 1});  // (4)\n\n  // Add the triangle\n  // First set the coordinates of its nodes:\n  Eigen::MatrixXd nodesOfTria(2, 3);\n  nodesOfTria << 1, 1, 0.5, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kTria(),  // we want a triangle\n      std::array<lf::mesh::Mesh::size_type, 3>{\n          {1, 2, 4}},  // indices of the nodes\n      std::make_unique<lf::geometry::TriaO1>(nodesOfTria));  // node coords\n\n  // Add the quadrilateral\n  Eigen::MatrixXd nodesOfQuad(2, 4);\n  nodesOfQuad << 0, 1, 0.5, 0, 0, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kQuad(),\n      std::array<lf::mesh::Mesh::size_type, 4>{{0, 1, 4, 3}},\n      std::make_unique<lf::geometry::QuadO1>(nodesOfQuad));\n\n  std::shared_ptr<lf::mesh::Mesh> demoMesh_p = mesh_factory_ptr->Build();\n\n  return demoMesh_p;\n}\n\n/** @brief Compute the edge-vertex incidence matrix G for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The edge-vertex incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<int> computeEdgeVertexIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store edge-vertex incidence matrix here\n\n\n  // number of edges\n  int N = mesh.NumEntities(1);\n  // number of vertices\n  int M = mesh.NumEntities(2);\n\n  Eigen::SparseMatrix<int, Eigen::RowMajor> G(N,M);\n\n\n  G.reserve(Eigen::VectorXi::Constant(N, 2));\n\n  for(int i = 0; i < N; i++) {\n    auto vertices = mesh.Entities(1)[i]->SubEntities(1);\n    G.coeffRef(i, mesh.Index(*vertices[0])) = 1;\n    G.coeffRef(i, mesh.Index(*vertices[1])) = -1;\n  }\n\n\n  return G;\n}\n/* SAM_LISTING_END_1 */\n\n/** @brief Compute the cell-edge incidence matrix D for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The cell-edge incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<int> computeCellEdgeIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n\n  // number of cells\n  int N = mesh.NumEntities(0);\n  // number of edges\n  int M = mesh.NumEntities(1);\n\n  Eigen::SparseMatrix<int, Eigen::RowMajor> D(N,M);\n\n\n  D.reserve(Eigen::VectorXi::Constant(N, 4));\n\n  for(int i = 0; i < N; i++) {\n\n    auto edges = mesh.Entities(0)[i]->SubEntities(1);\n\n    for(int k = 0; k < edges.size(); k++) {\n      D.coeffRef(i, mesh.Index(*edges[k])) = lf::mesh::to_sign(mesh.Entities(0)[i]->RelativeOrientations()[k]);\n    }\n\n  }\n\n\n\n  return D;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief For a given mesh test if the product of cell-edge and edge-vertex\n *        incidence matrix is zero: D*G == 0?\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *             such as lf::mesh::hybrid2d::Mesh)\n * @return true, if the product is zero and false otherwise\n */\n/* SAM_LISTING_BEGIN_3 */\nbool testZeroIncidenceMatrixProduct(const lf::mesh::Mesh &mesh) {\n  return (computeCellEdgeIncidenceMatrix(mesh) * computeEdgeVertexIncidenceMatrix(mesh)).norm() == 0;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace IncidenceMatrices\n", "meta": {"hexsha": "03238ae95d0e5ceee28a3f019d207e92e4e6a2a3", "size": 4113, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/mysolution/incidencematrices.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/IncidenceMatrices/mysolution/incidencematrices.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/IncidenceMatrices/mysolution/incidencematrices.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6940298507, "max_line_length": 111, "alphanum_fraction": 0.6644784829, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.5902366433435796}}
{"text": "/*\n(c) 2019 M. Werner - Part of the GIS++ tutorial \n- https://www.martinwerner.de/teaching/spatial-cpp\n- https://github.com/mwernerds/spatial-cpp\n\nProgram: Points\nCompile: g++ -I $(BOOST_DIR) -Wall -std=c++11  -o 02_simplefeatures 02_simplefeatures.cpp\n*/\n\n#include<iostream>\n#include<fstream>\n#include <boost/geometry.hpp>\n\nnamespace bg = boost::geometry;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point;\ntypedef bg::model::box<point> box;\ntypedef bg::model::linestring<point> linestring;\ntypedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\n\n// Note: the higher order objects usually have all features of a random_access container (or actually are some)\n\nint main(int argc, char **argv)\n{\n    // let us make a nice triangle\n    point a(0,0),b(1,1),c(2,0);\n    polygon triangle;\n    bg::append(bg::exterior_ring(triangle),a);\n    bg::append(bg::exterior_ring(triangle),b);\n    bg::append(bg::exterior_ring(triangle),c);\n    std::cout << bg::wkt(a) << std::endl;\n    std::cout << bg::wkt(b) << std::endl;\n    std::cout << bg::wkt(c) << std::endl;\n    std::cout << bg::wkt(triangle) << std::endl;\n\n    // point in polygon (within relation)\n    std::cout << std::boolalpha; // we want all bools to be written as true/false\n\n    bg::correct(triangle); // make it CCW!\n    std::cout << \"Corrected Geometry: \" << bg::wkt(triangle) << std::endl;\n    std::cout << \"Within: \" << bg::within (bg::make<point>(1.0,0.5),triangle) << std::endl;\n\n    // Let us now create our first file for QGIS:\n    //\n    // Algorithm in short:\n    // 1) take two random (integer) triangles in [0,0]-[10,10].\n    // 2) compute most important relations\n    // 3) write a CSV file using WKT containing the two polygons for inspection\n\n    std::srand(std::time(0)); //use current time as seed for random generator\n\n    auto random_point = []()->point {return bg::make<point>(static_cast<int> (std::rand()%10),static_cast<int> (std::rand()%10));};\n\n    //std::cout << bg::wkt(random_point()) << std::endl;\n    polygon A,B;\n    for (size_t i=0; i<3; i++) bg::append(bg::exterior_ring(A),random_point());\n    for (size_t i=0; i<3; i++) bg::append(bg::exterior_ring(B),random_point());\n\n    // remove these lines to see catastrophic results including negative area!\n    bg::correct(A);\n    bg::correct(B);\n\n    std::cout << bg::wkt(A) << std::endl;\n    std::cout << bg::wkt(B) << std::endl;\n\n    // DE-9IM Matrix\n    bg::de9im::matrix matrix = boost::geometry::relation(A,B);\n    std::string code = matrix.str();\n    std::cout << \"relation: \" << code << std::endl;\n    // generic relate operation:\n   \n    bg::de9im::mask mask(\"T*F**F***\"); // within\n    auto p = random_point();\n    bool check = bg::relate(p, A, mask);\n    std::cout << \"A random point \" << bg::wkt(p) << \" related: \" << check << std::endl;\n\n    // some algorithms relations:\n\n    std::cout << \"area: \" << bg::area(A) << std::endl;\n    std::cout << \"covered_by: \" <<  bg::covered_by (A,B) << std::endl;\n    std::cout << \"disjoint: \" <<  bg::disjoint(A,B) << std::endl;\n    std::cout << \"equals: \" <<  bg::equals(A,B) << std::endl;\n    std::cout << \"intersects: \" <<  bg::intersects   (A,B) << std::endl;\n    std::cout << \"overlaps: \" <<  bg::overlaps (A,B) << std::endl;\n    std::cout << \"touches: \" <<  bg::touches (A,B) << std::endl;\n    std::cout << \"within: \" <<  bg::within (A,B) << std::endl;\n\n   \n    // write CSV\n    {\n    std::ofstream ofs(\"geometry.csv\");\n    ofs << \"wkt\" << std::endl;\n    ofs << bg::wkt(A)<< std::endl;\n    ofs << bg::wkt(B) << std::endl;\n    ofs.close();\n    }\n\n\n    \n    // and now let us test within with random floating points\n    {\n    std::ofstream ofs(\"points.csv\");\n    ofs << \"wkt; within\" << std::endl;\n    for (size_t i=0; i < 500; i++)\n    {\n\tauto p = bg::make<point>( static_cast<double>(std::rand())/RAND_MAX*10.0,static_cast<double>(std::rand())/RAND_MAX*10.0);\n\tauto rel1 = bg::within(p,A);\n\tauto rel2 = bg::within(p,B);\n\tint score = (rel1 << 1) + rel2;\n\tofs << bg::wkt(p) << \";\" << score << std::endl;\n    }\n    }\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "937fb679597efe172bde2bc0680110a43e8a7f2b", "size": 4058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02_geo/02_simplefeatures.cpp", "max_stars_repo_name": "mwernerds/spatial-cpp", "max_stars_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_geo/02_simplefeatures.cpp", "max_issues_repo_name": "mwernerds/spatial-cpp", "max_issues_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_geo/02_simplefeatures.cpp", "max_forks_repo_name": "mwernerds/spatial-cpp", "max_forks_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T23:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T23:57:30.000Z", "avg_line_length": 34.6837606838, "max_line_length": 131, "alphanum_fraction": 0.5963528832, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839876, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5902366427082106}}
{"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: Toby D. Young, Polish Academy of Sciences, \n *          Wolfgang Bangerth, Texas A&M University \n */ \n\n\n// @sect3{Include files}  \n\n// 正如介绍中提到的，本程序基本上只是  step-4  的一个小修改版本。因此，以下大部分的include文件都是在那里使用的，或者至少是在以前的教程程序中已经使用的。\n\n#include <deal.II/base/logstream.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/function_parser.h> \n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/base/utilities.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/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/full_matrix.h> \n\n// IndexSet用于设置每个  PETScWrappers::MPI::Vector:  的大小。\n#include <deal.II/base/index_set.h> \n\n// PETSc出现在这里是因为SLEPc依赖于这个库。\n\n#include <deal.II/lac/petsc_sparse_matrix.h> \n#include <deal.II/lac/petsc_vector.h> \n\n// 然后我们需要实际导入SLEPc提供的求解器接口。\n\n#include <deal.II/lac/slepc_solver.h> \n\n// 我们还需要一些标准的C++。\n\n#include <fstream> \n#include <iostream> \n\n// 最后，和以前的程序一样，我们将所有的deal.II类和函数名导入到本程序中所有的名字空间中。\n\nnamespace Step36 \n{ \n  using namespace dealii; \n// @sect3{The <code>EigenvalueProblem</code> class template}  \n\n// 下面是主类模板的类声明。它看起来和在  step-4  中已经展示过的差不多了。\n\n  template <int dim> \n  class EigenvalueProblem \n  { \n  public: \n    EigenvalueProblem(const std::string &prm_file); \n    void run(); \n\n  private: \n    void         make_grid_and_dofs(); \n    void         assemble_system(); \n    unsigned int solve(); \n    void         output_results() const; \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n// 有了这些例外情况。对于我们的特征值问题，我们既需要左手边的刚度矩阵，也需要右手边的质量矩阵。我们还需要的不仅仅是一个解函数，而是一整套我们想要计算的特征函数，以及相应的特征值。\n\n    PETScWrappers::SparseMatrix             stiffness_matrix, mass_matrix; \n    std::vector<PETScWrappers::MPI::Vector> eigenfunctions; \n    std::vector<double>                     eigenvalues; \n\n// 然后，我们需要一个对象来存储几个运行时参数，我们将在输入文件中指定。\n\n    ParameterHandler parameters; \n\n// 最后，我们将有一个对象，包含对我们自由度的 \"约束\"。如果我们有自适应细化的网格（目前的程序中没有），这可能包括悬挂节点约束。这里，我们将存储边界节点的约束  $U_i=0$  。\n\n    AffineConstraints<double> constraints; \n  }; \n// @sect3{Implementation of the <code>EigenvalueProblem</code> class}  \n// @sect4{EigenvalueProblem::EigenvalueProblem}  \n\n// 首先是构造函数。主要的新部分是处理运行时的输入参数。我们需要首先声明它们的存在，然后从输入文件中读取它们的值，该文件的名称被指定为该函数的参数。\n\n  template <int dim> \n  EigenvalueProblem<dim>::EigenvalueProblem(const std::string &prm_file) \n    : fe(1) \n    , dof_handler(triangulation) \n  { \n\n// TODO研究为什么获得正确的特征值退化所需的最小细化步骤数为6\n\n    parameters.declare_entry( \n      \"Global mesh refinement steps\", \n      \"5\", \n      Patterns::Integer(0, 20), \n      \"The number of times the 1-cell coarse mesh should \" \n      \"be refined globally for our computations.\"); \n    parameters.declare_entry(\"Number of eigenvalues/eigenfunctions\", \n                             \"5\", \n                             Patterns::Integer(0, 100), \n                             \"The number of eigenvalues/eigenfunctions \" \n                             \"to be computed.\"); \n    parameters.declare_entry(\"Potential\", \n                             \"0\", \n                             Patterns::Anything(), \n                             \"A functional description of the potential.\"); \n\n    parameters.parse_input(prm_file); \n  } \n// @sect4{EigenvalueProblem::make_grid_and_dofs}  \n\n// 下一个函数在域 $[-1,1]^d$ 上创建一个网格，根据输入文件的要求对其进行多次细化，然后给它附加一个DoFHandler，将矩阵和向量初始化为正确的大小。我们还建立了对应于边界值的约束  $u|_{\\partial\\Omega}=0$  。\n\n// 对于矩阵，我们使用PETSc包装器。这些包装器能够在非零条目被添加时分配必要的内存。这看起来效率很低：我们可以先计算稀疏模式，用它来初始化矩阵，然后在我们插入条目时，我们可以确定我们不需要重新分配内存和释放之前使用的内存。一种方法是使用这样的代码。用\n// @code\n//    DynamicSparsityPattern\n//       dsp (dof_handler.n_dofs(),\n//            dof_handler.n_dofs());\n//    DoFTools::make_sparsity_pattern (dof_handler, dsp);\n//    dsp.compress ();\n//    stiffness_matrix.reinit (dsp);\n//    mass_matrix.reinit (dsp);\n//  @endcode\n//  代替下面两个 <code>reinit()</code> 的刚度和质量矩阵的调用。\n\n// 不幸的是，这并不完全可行。上面的代码可能会导致在非零模式下的一些条目，我们只写零条目；最值得注意的是，对于那些属于边界节点的行和列的非对角线条目，这一点是成立的。这不应该是一个问题，但是不管什么原因，PETSc的ILU预处理程序（我们用来解决特征值求解器中的线性系统）不喜欢这些额外的条目，并以错误信息中止。\n\n// 在没有任何明显的方法来避免这种情况的情况下，我们干脆选择第二种最好的方法，即让PETSc在必要时分配内存。也就是说，由于这不是一个时间上的关键部分，这整个事件就不再重要了。\n\n  template <int dim> \n  void EigenvalueProblem<dim>::make_grid_and_dofs() \n  { \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global( \n      parameters.get_integer(\"Global mesh refinement steps\")); \n    dof_handler.distribute_dofs(fe); \n\n    DoFTools::make_zero_boundary_constraints(dof_handler, constraints); \n    constraints.close(); \n\n    stiffness_matrix.reinit(dof_handler.n_dofs(), \n                            dof_handler.n_dofs(), \n                            dof_handler.max_couplings_between_dofs()); \n    mass_matrix.reinit(dof_handler.n_dofs(), \n                       dof_handler.n_dofs(), \n                       dof_handler.max_couplings_between_dofs()); \n\n// 下一步是处理特征谱的问题。在这种情况下，输出是特征值和特征函数，所以我们将特征函数和特征值列表的大小设置为与我们在输入文件中要求的一样大。当使用 PETScWrappers::MPI::Vector, 时，Vector是使用IndexSet初始化的。IndexSet不仅用于调整 PETScWrappers::MPI::Vector 的大小，而且还将 PETScWrappers::MPI::Vector 中的一个索引与一个自由度联系起来（更详细的解释见 step-40 ）。函数complete_index_set()创建了一个IndexSet，每个有效的索引都是这个集合的一部分。请注意，这个程序只能按顺序运行，如果并行使用，将抛出一个异常。\n\n    IndexSet eigenfunction_index_set = dof_handler.locally_owned_dofs(); \n    eigenfunctions.resize( \n      parameters.get_integer(\"Number of eigenvalues/eigenfunctions\")); \n    for (unsigned int i = 0; i < eigenfunctions.size(); ++i) \n      eigenfunctions[i].reinit(eigenfunction_index_set, MPI_COMM_WORLD); \n\n    eigenvalues.resize(eigenfunctions.size()); \n  } \n// @sect4{EigenvalueProblem::assemble_system}  \n\n// 在这里，我们从局部贡献 $A^K_{ij} = \\int_K \\nabla\\varphi_i(\\mathbf x) \\cdot \\nabla\\varphi_j(\\mathbf x) + V(\\mathbf x)\\varphi_i(\\mathbf x)\\varphi_j(\\mathbf x)$ 和 $M^K_{ij} = \\int_K \\varphi_i(\\mathbf x)\\varphi_j(\\mathbf x)$ 中分别组合出全局刚度和质量矩阵。如果你看过以前的教程程序，这个函数应该会很熟悉。唯一新的东西是使用我们从输入文件中得到的表达式，设置一个描述势 $V(\\mathbf x)$ 的对象。然后我们需要在每个单元的正交点上评估这个对象。如果你见过如何评估函数对象（例如，见 step-5 中的系数），这里的代码也会显得相当熟悉。\n\n  template <int dim> \n  void EigenvalueProblem<dim>::assemble_system() \n  { \n    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.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_stiffness_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> cell_mass_matrix(dofs_per_cell, dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    FunctionParser<dim> potential; \n    potential.initialize(FunctionParser<dim>::default_variable_names(), \n                         parameters.get(\"Potential\"), \n                         typename FunctionParser<dim>::ConstMap()); \n\n    std::vector<double> potential_values(n_q_points); \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        cell_stiffness_matrix = 0; \n        cell_mass_matrix      = 0; \n\n        potential.value_list(fe_values.get_quadrature_points(), \n                             potential_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            for (unsigned int j = 0; j < dofs_per_cell; ++j) \n              { \n                cell_stiffness_matrix(i, j) +=           // \n                  (fe_values.shape_grad(i, q_point) *    // \n                     fe_values.shape_grad(j, q_point)    // \n                   +                                     // \n                   potential_values[q_point] *           // \n                     fe_values.shape_value(i, q_point) * // \n                     fe_values.shape_value(j, q_point)   // \n                   ) *                                   // \n                  fe_values.JxW(q_point);                // \n\n                cell_mass_matrix(i, j) +=              // \n                  (fe_values.shape_value(i, q_point) * // \n                   fe_values.shape_value(j, q_point)   // \n                   ) *                                 // \n                  fe_values.JxW(q_point);              // \n              } \n\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                                               stiffness_matrix); \n        constraints.distribute_local_to_global(cell_mass_matrix, \n                                               local_dof_indices, \n                                               mass_matrix); \n      } \n\n// 在函数的最后，我们告诉PETSc，矩阵现在已经完全组装好了，稀疏矩阵表示法现在可以被压缩了，因为不会再添加任何条目。\n\n    stiffness_matrix.compress(VectorOperation::add); \n    mass_matrix.compress(VectorOperation::add); \n\n// 在离开函数之前，我们计算虚假的特征值，这些特征值是由零Dirichlet约束引入到系统中的。正如介绍中所讨论的，使用Dirichlet边界条件，加上位于域的边界的自由度仍然是我们所求解的线性系统的一部分，引入了一些虚假的特征值。下面，我们输出它们所处的区间，以确保我们在计算中出现时可以忽略它们。\n\n    double min_spurious_eigenvalue = std::numeric_limits<double>::max(), \n           max_spurious_eigenvalue = -std::numeric_limits<double>::max(); \n\n    for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) \n      if (constraints.is_constrained(i)) \n        { \n          const double ev         = stiffness_matrix(i, i) / mass_matrix(i, i); \n          min_spurious_eigenvalue = std::min(min_spurious_eigenvalue, ev); \n          max_spurious_eigenvalue = std::max(max_spurious_eigenvalue, ev); \n        } \n\n    std::cout << \"   Spurious eigenvalues are all in the interval \" \n              << \"[\" << min_spurious_eigenvalue << \",\" \n              << max_spurious_eigenvalue << \"]\" << std::endl; \n  } \n// @sect4{EigenvalueProblem::solve}  \n\n// 这是该程序的关键新功能。现在系统已经设置好了，现在是实际解决问题的好时机：和其他例子一样，这是使用 \"解决 \"程序来完成的。从本质上讲，它的工作原理与其他程序一样：你设置一个SolverControl对象，描述我们要解决的线性系统的精度，然后我们选择我们想要的解算器类型。这里我们选择了SLEPc的Krylov-Schur求解器，对于这类问题来说，这是一个相当快速和强大的选择。\n\n  template <int dim> \n  unsigned int EigenvalueProblem<dim>::solve() \n  { \n\n// 我们从这里开始，就像我们通常做的那样，指定我们想要的收敛控制。\n\n    SolverControl                    solver_control(dof_handler.n_dofs(), 1e-9); \n    SLEPcWrappers::SolverKrylovSchur eigensolver(solver_control); \n\n// 在我们实际求解特征函数和-值之前，我们还必须选择哪一组特征值来求解。让我们选择那些实部最小的特征值和相应的特征函数（事实上，我们在这里解决的问题是对称的，所以特征值是纯实部的）。之后，我们就可以真正让SLEPc做它的工作了。\n\n    eigensolver.set_which_eigenpairs(EPS_SMALLEST_REAL); \n\n    eigensolver.set_problem_type(EPS_GHEP); \n\n    eigensolver.solve(stiffness_matrix, \n                      mass_matrix, \n                      eigenvalues, \n                      eigenfunctions, \n                      eigenfunctions.size()); \n\n// 上述调用的输出是一组向量和数值。在特征值问题中，特征函数只确定到一个常数，这个常数可以很随意地固定。由于对特征值问题的原点一无所知，SLEPc除了将特征向量归一到 $l_2$ （向量）准则外，没有其他选择。不幸的是，这个规范与我们从特征函数角度可能感兴趣的任何规范没有什么关系： $L_2(\\Omega)$ 规范，或者也许是 $L_\\infty(\\Omega)$ 规范。\n\n//让我们选择后者，重新划分特征函数的尺度，使其具有 $\\|\\phi_i(\\mathbf x)\\|_{L^\\infty(\\Omega)}=1$ 而不是 $\\|\\Phi\\|_{l_2}=1$ （其中 $\\phi_i$ 是 $i$ 第三个特征<i>function</i>， $\\Phi_i$ 是相应的结点值矢量）。对于这里选择的 $Q_1$ 元素，我们知道函数 $\\phi_i(\\mathbf x)$ 的最大值是在其中一个节点达到的，所以 $\\max_{\\mathbf x}\\phi_i(\\mathbf x)=\\max_j (\\Phi_i)_j$ ，使得在 $L_\\infty$ 准则下的归一化是微不足道的。请注意，如果我们选择 $Q_k$ 元素与 $k>1$ ，这就不容易了：在那里，一个函数的最大值不一定要在一个节点上达到，所以 $\\max_{\\mathbf x}\\phi_i(\\mathbf x)\\ge\\max_j (\\Phi_i)_j$ （尽管平等通常几乎是真的）。\n\n    for (unsigned int i = 0; i < eigenfunctions.size(); ++i) \n      eigenfunctions[i] /= eigenfunctions[i].linfty_norm(); \n\n// 最后返回收敛所需的迭代次数。\n\n    return solver_control.last_step(); \n  } \n// @sect4{EigenvalueProblem::output_results}  \n\n// 这是本程序的最后一个重要功能。它使用DataOut类来生成特征函数的图形输出，以便以后进行可视化。它的工作原理与其他许多教程中的程序一样。\n\n// 整个函数的集合被输出为一个单一的VTK文件。\n\n  template <int dim> \n  void EigenvalueProblem<dim>::output_results() const \n  { \n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n\n    for (unsigned int i = 0; i < eigenfunctions.size(); ++i) \n      data_out.add_data_vector(eigenfunctions[i], \n                               std::string(\"eigenfunction_\") + \n                                 Utilities::int_to_string(i)); \n\n// 唯一值得讨论的可能是，由于势在输入文件中被指定为函数表达式，因此最好能将其与特征函数一起以图形形式表示。实现这一目的的过程相对简单：我们建立一个代表 $V(\\mathbf x)$ 的对象，然后将这个连续函数插值到有限元空间。我们还将结果附加到DataOut对象上，以便进行可视化。\n\n    Vector<double> projected_potential(dof_handler.n_dofs()); \n    { \n      FunctionParser<dim> potential; \n      potential.initialize(FunctionParser<dim>::default_variable_names(), \n                           parameters.get(\"Potential\"), \n                           typename FunctionParser<dim>::ConstMap()); \n      VectorTools::interpolate(dof_handler, potential, projected_potential); \n    } \n    data_out.add_data_vector(projected_potential, \"interpolated_potential\"); \n\n    data_out.build_patches(); \n\n    std::ofstream output(\"eigenvectors.vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{EigenvalueProblem::run}  \n\n// 这是一个对一切都有顶层控制的函数。它几乎与  step-4  中的内容完全相同。\n\n  template <int dim> \n  void EigenvalueProblem<dim>::run() \n  { \n    make_grid_and_dofs(); \n\n    std::cout << \"   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\n    assemble_system(); \n\n    const unsigned int n_iterations = solve(); \n    std::cout << \"   Solver converged in \" << n_iterations << \" iterations.\" \n              << std::endl; \n\n    output_results(); \n\n    std::cout << std::endl; \n    for (unsigned int i = 0; i < eigenvalues.size(); ++i) \n      std::cout << \"      Eigenvalue \" << i << \" : \" << eigenvalues[i] \n                << std::endl; \n  } \n} // namespace Step36 \n// @sect3{The <code>main</code> function}  \nint main(int argc, char **argv) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step36; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \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-36\")); \n\n      EigenvalueProblem<2> problem(\"step-36.prm\"); \n      problem.run(); \n    } \n\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\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// 如果没有抛出异常，我们就告诉程序不要再胡闹了，乖乖地退出。\n\n  std::cout << std::endl << \"   Job done.\" << std::endl; \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "caf603386e70ee635ab0c5e7ea880213bf064115", "size": 16200, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-36/step-36.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-36/step-36.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-36/step-36.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.7622377622, "max_line_length": 436, "alphanum_fraction": 0.6154320988, "num_tokens": 5844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5902366358495374}}
{"text": "#include <sophus/se3.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cmath>\n#include <Eigen/StdVector>\n// need pangolin for plotting trajectory\n#include <pangolin/pangolin.h>\n\nusing namespace std;\n\n// path to trajectory file\nstring estimated_file = \"./estimated.txt\";\nstring groundtruth_file = \"./groundtruth.txt\";\n\n\nvoid DrawTrajectory(vector<Sophus::SE3> estimated_poses,vector<Sophus::SE3> groundtruth_poses) {\n    if (estimated_poses.empty() || groundtruth_poses.empty()) {\n        cerr << \"Trajectory 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(1.0f, 1.0f, 1.0f, 1.0f);\n\n        glLineWidth(2);\n\n\n        for (size_t i = 0; i < estimated_poses.size() - 1; i++) {\n            glColor3f(1 - (float) i / estimated_poses.size(), 0.0f, (float) i / estimated_poses.size());\n            glBegin(GL_LINES);\n            auto p1 = estimated_poses[i], p2 = estimated_poses[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n\n        for (size_t i = 0; i < groundtruth_poses.size() - 1; i++) {\n            glColor3f(1 - (float) i / groundtruth_poses.size(), 0.0f, (float) i / groundtruth_poses.size());\n            glBegin(GL_LINES);\n            auto p1 = groundtruth_poses[i], p2 = groundtruth_poses[i + 1];\n            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n            glEnd();\n        }\n\n\n\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n\n}\n\nvector<Sophus::SE3> readPose(string filename)\n{\n    vector<Sophus::SE3> poses;\n    /// implement pose reading code\n    // start your code here (5~10 lines)\n\n    ifstream fin(filename);\n    for ( int i=0; i<612; i++ )\n    {\n        double data[8] = {0};\n        for ( auto& d:data )\n            fin>>d;\n        Eigen::Quaterniond q( data[7], data[4], data[5], data[6] );\n        Eigen::Vector3d t(data[1], data[2], data[3]);\n        Sophus::SE3 SE3_qt(q,t);\n        poses.push_back(SE3_qt);\n    }\n\n    return poses;\n    // end your code here\n\n}\n\ndouble RMSE(vector<Sophus::SE3> estimated_poses,vector<Sophus::SE3> groundtruth_poses)\n{\n    double sum = 0;\n    for(int i=0;i<estimated_poses.size();i++)\n    {\n        double error = 0;\n        double e = sqrt(  (groundtruth_poses.at(i).inverse() * estimated_poses.at(i)).log().transpose() *   (groundtruth_poses.at(i).inverse() * estimated_poses.at(i)).log()   );\n\n\n        error = pow(abs(e),2);\n        sum+= error;\n    }\n    double rmse = pow(sum/estimated_poses.size(),0.5);\n    return rmse;\n}\n\n\nint main(int argc, char **argv) {\n\n    vector<Sophus::SE3> estimated_poses;\n    vector<Sophus::SE3> groundtruth_poses;\n\n    estimated_poses = readPose(estimated_file);\n    groundtruth_poses = readPose(groundtruth_file);\n\n    \n    std::cout<<RMSE(estimated_poses,groundtruth_poses)<<endl;;\n    DrawTrajectory(estimated_poses,groundtruth_poses);\n    return 0;\n}\n\n", "meta": {"hexsha": "319047efdc91a3dd6b7bb9ea0591e9e5ad7db93b", "size": 3935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3/rmse.cpp", "max_stars_repo_name": "Yvon-Shong/SLAM", "max_stars_repo_head_hexsha": "4f633e71e13e1b3482255bc5abc38446a56beebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:25:08.000Z", "max_issues_repo_path": "SLAM14Lectures-master/3/rmse.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T11:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T18:40:41.000Z", "max_forks_repo_path": "SLAM14Lectures-master/3/rmse.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T16:30:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T11:37:37.000Z", "avg_line_length": 30.0381679389, "max_line_length": 178, "alphanum_fraction": 0.6142312579, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.5902291865173503}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\ntypedef Eigen::Matrix<float, 3, 3> MyMatrix33f;\ntypedef Eigen::Matrix<float, 3, 1> MyVector3f;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MyMatrix;\n\nint main() {\n  {\n    // declaration\n    MyMatrix33f a;\n    MyVector3f v;\n    MyMatrix m(10, 15);\n\n    // initialization\n    a = MyMatrix33f::Zero();\n    std::cout << \"Zero matrix:\\n\" << a << std::endl;\n\n    a = MyMatrix33f::Identity();\n    std::cout << \"Identity matrix:\\n\" << a << std::endl;\n\n    v = MyVector3f::Random();\n    std::cout << \"Random vector:\\n\" << v << std::endl;\n\n    a << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n    std::cout << \"Comma initilized matrix:\\n\" << a << std::endl;\n\n    a(0, 0) = 3;\n    std::cout << \"Matrix with changed element[0][0]:\\n\" << a << std::endl;\n\n    int data[] = {1, 2, 3, 4};\n    Eigen::Map<Eigen::RowVectorXi> v_map(data, 4);\n    std::cout << \"Row vector mapped to array:\\n\" << v_map << std::endl;\n\n    std::vector<float> vdata = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n    Eigen::Map<MyMatrix33f> a_map(vdata.data());\n    std::cout << \"Matrix mapped to array:\\n\" << a_map << std::endl;\n  }\n  // arithmetic\n  {\n    Eigen::Matrix2d a;\n    a << 1, 2, 3, 4;\n    Eigen::Matrix2d b;\n    b << 1, 2, 3, 4;\n\n    // element wise operations\n    Eigen::Matrix2d result = a.array() * b.array();\n    std::cout << \"element wise a * b :\\n\" << result << std::endl;\n\n    result = a.array() / b.array();\n    std::cout << \"element wise a / b :\\n\" << result << std::endl;\n\n    a = b.array() * 4;\n    std::cout << \"element wise a = b * 4 :\\n\" << a << std::endl;\n\n    // matrix operations\n    result = a + b;\n    std::cout << \"matrices a + b :\\n\" << result << std::endl;\n\n    a += b;\n    std::cout << \"matrices a += b :\\n\" << result << std::endl;\n\n    result = a * b;\n    std::cout << \"matrices a * b :\\n\" << result << std::endl;\n  }\n\n  // patial access\n  {\n    Eigen::MatrixXf m = Eigen::MatrixXf::Random(4, 4);\n    std::cout << \"Random 4x4 matrix :\\n\" << m << std::endl;\n\n    Eigen::Matrix2f b =\n        m.block(1, 1, 2, 2);  // coping the middle part of matrix\n    std::cout << \"Middle of 4x4 matrix :\\n\" << b << std::endl;\n\n    m.block(1, 1, 2, 2) *= 0;  // change values in original matrix\n    std::cout << \"Modified middle of 4x4 matrix :\\n\" << m << std::endl;\n\n    m.row(1).array() += 3;\n    std::cout << \"Modified row of 4x4 matrix :\\n\" << m << std::endl;\n\n    m.col(2).array() /= 4;\n    std::cout << \"Modified col of 4x4 matrix :\\n\" << m << std::endl;\n  }\n\n  // broadcasting\n  {\n    Eigen::MatrixXf mat = Eigen::MatrixXf::Random(2, 4);\n    std::cout << \"Random 2x4 matrix :\\n\" << mat << std::endl;\n\n    Eigen::VectorXf v(2);  // column vector\n    v << 100, 100;\n    mat.colwise() += v;\n    std::cout << \"Sum broadcasted over columns :\\n\" << mat << std::endl;\n  }\n  return 0;\n};\n", "meta": {"hexsha": "3e6838bf6fabb117c3a490ddb258ae6e8c838122", "size": 2797, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter01/eigen_samples/linalg_eigen.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": "Chapter01/eigen_samples/linalg_eigen.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": "Chapter01/eigen_samples/linalg_eigen.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": 28.5408163265, "max_line_length": 74, "alphanum_fraction": 0.540579192, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5902291804232316}}
{"text": "/*\n * Instruction.cpp\n *\n *  Created on: 2015/01/18\n *      Author: kryozahiro\n */\n\n#include \"Instruction.h\"\n\n#include <cassert>\n#include <cmath>\n#include <boost/lexical_cast.hpp>\nusing namespace std;\n\nvoid Instruction::set(Opcode op, int ret, int mem1, int mem2) {\n\tthis->op = op;\n\tthis->ret = ret;\n\tthis->arg1 = mem1;\n\tthis->arg2 = mem2;\n}\n\nvoid Instruction::operator()(unsigned int& pc, unsigned int end, bool& condition, std::vector<double>& memory) const {\n\t//条件が満たされていないときに分岐以外の命令に到達したらスキップする\n\tif (!condition and op != Opcode::IF and op != Opcode::IF_GT and op != Opcode::IF_LE) {\n\t\tcondition = true;\n\t\treturn;\n\t}\n\n\tswitch (op) {\n\tcase Opcode::AND:\n\t\tmemory[ret] = static_cast<int>(memory[arg1]) & static_cast<int>(memory[arg2]);\n\t\tbreak;\n\tcase Opcode::OR:\n\t\tmemory[ret] = static_cast<int>(memory[arg1]) | static_cast<int>(memory[arg2]);\n\t\tbreak;\n\tcase Opcode::NOT:\n\t\tmemory[ret] = ~static_cast<int>(memory[arg1]);\n\t\tbreak;\n\tcase Opcode::ADD:\n\t\tmemory[ret] = memory[arg1] + memory[arg2];\n\t\tbreak;\n\tcase Opcode::SUB:\n\t\tmemory[ret] = memory[arg1] - memory[arg2];\n\t\tbreak;\n\tcase Opcode::MUL:\n\t\tmemory[ret] = memory[arg1] * memory[arg2];\n\t\tbreak;\n\tcase Opcode::DIV:\n\t\tmemory[ret] = (memory[arg2] != 0) ? memory[arg1] / memory[arg2] : 0;\n\t\tbreak;\n\tcase Opcode::IF:\n\t\tcondition &= static_cast<int>(memory[arg1]);\n\t\tbreak;\n\tcase Opcode::IF_GT:\n\t\tcondition &= (memory[arg1] > memory[arg2]);\n\t\tbreak;\n\tcase Opcode::IF_LE:\n\t\tcondition &= (memory[arg1] <= memory[arg2]);\n\t\tbreak;\n\tcase Opcode::JMP:\n\t\tpc += min(static_cast<unsigned int>(abs(memory[arg2])), end);\n\t\tbreak;\n\tcase Opcode::JG:\n\t\tif (memory[arg1] > 0) {\n\t\t\tpc += min(static_cast<unsigned int>(abs(memory[arg2])), end);\n\t\t}\n\t\tbreak;\n\tcase Opcode::JLE:\n\t\tif (memory[arg1] <= 0) {\n\t\t\tpc += min(static_cast<unsigned int>(abs(memory[arg2])), end);\n\t\t}\n\t\tbreak;\n\tcase Opcode::SIN:\n\t\tmemory[ret] = sin(memory[arg1]);\n\t\tbreak;\n\tcase Opcode::COS:\n\t\tmemory[ret] = cos(memory[arg1]);\n\t\tbreak;\n\tcase Opcode::SQRT:\n\t\tmemory[ret] = sqrt(abs(memory[arg1]));\n\t\tbreak;\n\tcase Opcode::EXP:\n\t\tmemory[ret] = exp(memory[arg1]);\n\t\tbreak;\n\tcase Opcode::LOG:\n\t\tmemory[ret] = (memory[arg1] != 0) ? log(abs(memory[arg1])) : 0;\n\t\tbreak;\n\tcase Opcode::IMM:\n\t\tmemory[ret] = arg1 * memory.size() + arg2;\n\t\tbreak;\n\tcase Opcode::NOP:\n\t\t//do nothing\n\t\tbreak;\n\tdefault:\n\t\tassert(false);\n\t}\n}\n\nstring Instruction::toString() const {\n\treturn \"[\" + to_string(ret) + \"] \" + boost::lexical_cast<string>(op) + \" [\" + to_string(arg1) + \"] [\" + to_string(arg2) + \"] \";\n}\n\nInstruction::Opcode Instruction::getOpcode() const {\n\treturn op;\n}\n\nint Instruction::getRet() const {\n\treturn ret;\n}\n\nint Instruction::getArg1() const {\n\treturn arg1;\n}\n\nint Instruction::getArg2() const {\n\treturn arg2;\n}\n", "meta": {"hexsha": "68e0e65a011e57b53df2b302f7db70d222761e63", "size": 2707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/program/InstructionSequence/Instruction.cpp", "max_stars_repo_name": "kryozahiro/gamesolver", "max_stars_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamesolver/program/InstructionSequence/Instruction.cpp", "max_issues_repo_name": "kryozahiro/gamesolver", "max_issues_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamesolver/program/InstructionSequence/Instruction.cpp", "max_forks_repo_name": "kryozahiro/gamesolver", "max_forks_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-06T16:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T16:06:10.000Z", "avg_line_length": 22.9406779661, "max_line_length": 128, "alphanum_fraction": 0.6464721093, "num_tokens": 848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5901502261500402}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp\n\n [begin_description]\n Coefficients for the Adams Moulton method.\n [end_description]\n\n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_MOULTON_COEFFICIENTS_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_MOULTON_COEFFICIENTS_HPP_INCLUDED\n\n\n#include <boost/array.hpp>\n\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\nnamespace detail {\n\ntemplate< class Value , size_t Steps >\nclass adams_moulton_coefficients ;\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 1 > : public boost::array< Value , 1 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 1 >()\n      {\n        (*this)[0] = static_cast< Value >( 1 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 2 > : public boost::array< Value , 2 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 2 >()\n      {\n        (*this)[0] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n        (*this)[1] = static_cast< Value >( 1 ) / static_cast< Value >( 2 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 3 > : public boost::array< Value , 3 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 3 >()\n      {\n        (*this)[0] = static_cast< Value >( 5 ) / static_cast< Value >( 12 );\n        (*this)[1] = static_cast< Value >( 2 ) / static_cast< Value >( 3 );\n        (*this)[2] = -static_cast< Value >( 1 ) / static_cast< Value >( 12 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 4 > : public boost::array< Value , 4 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 4 >()\n      {\n        (*this)[0] = static_cast< Value >( 3 ) / static_cast< Value >( 8 );\n        (*this)[1] = static_cast< Value >( 19 ) / static_cast< Value >( 24 );\n        (*this)[2] = -static_cast< Value >( 5 ) / static_cast< Value >( 24 );\n        (*this)[3] = static_cast< Value >( 1 ) / static_cast< Value >( 24 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 5 > : public boost::array< Value , 5 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 5 >()\n      {\n        (*this)[0] = static_cast< Value >( 251 ) / static_cast< Value >( 720 );\n        (*this)[1] = static_cast< Value >( 323 ) / static_cast< Value >( 360 );\n        (*this)[2] = -static_cast< Value >( 11 ) / static_cast< Value >( 30 );\n        (*this)[3] = static_cast< Value >( 53 ) / static_cast< Value >( 360 );\n        (*this)[4] = -static_cast< Value >( 19 ) / static_cast< Value >( 720 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 6 > : public boost::array< Value , 6 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 6 >()\n      {\n        (*this)[0] = static_cast< Value >( 95 ) / static_cast< Value >( 288 );\n        (*this)[1] = static_cast< Value >( 1427 ) / static_cast< Value >( 1440 );\n        (*this)[2] = -static_cast< Value >( 133 ) / static_cast< Value >( 240 );\n        (*this)[3] = static_cast< Value >( 241 ) / static_cast< Value >( 720 );\n        (*this)[4] = -static_cast< Value >( 173 ) / static_cast< Value >( 1440 );\n        (*this)[5] = static_cast< Value >( 3 ) / static_cast< Value >( 160 );\n      }\n};\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 7 > : public boost::array< Value , 7 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 7 >()\n      {\n        (*this)[0] = static_cast< Value >( 19087 ) / static_cast< Value >( 60480 );\n        (*this)[1] = static_cast< Value >( 2713 ) / static_cast< Value >( 2520 );\n        (*this)[2] = -static_cast< Value >( 15487 ) / static_cast< Value >( 20160 );\n        (*this)[3] = static_cast< Value >( 586 ) / static_cast< Value >( 945 );\n        (*this)[4] = -static_cast< Value >( 6737 ) / static_cast< Value >( 20160 );\n        (*this)[5] = static_cast< Value >( 263 ) / static_cast< Value >( 2520 );\n        (*this)[6] = -static_cast< Value >( 863 ) / static_cast< Value >( 60480 );\n      }\n};\n\n\ntemplate< class Value >\nclass adams_moulton_coefficients< Value , 8 > : public boost::array< Value , 8 >\n{\npublic:\n    adams_moulton_coefficients( void )\n    : boost::array< Value , 8 >()\n      {\n        (*this)[0] = static_cast< Value >( 5257 ) / static_cast< Value >( 17280 );\n        (*this)[1] = static_cast< Value >( 139849 ) / static_cast< Value >( 120960 );\n        (*this)[2] = -static_cast< Value >( 4511 ) / static_cast< Value >( 4480 );\n        (*this)[3] = static_cast< Value >( 123133 ) / static_cast< Value >( 120960 );\n        (*this)[4] = -static_cast< Value >( 88547 ) / static_cast< Value >( 120960 );\n        (*this)[5] = static_cast< Value >( 1537 ) / static_cast< Value >( 4480 );\n        (*this)[6] = -static_cast< Value >( 11351 ) / static_cast< Value >( 120960 );\n        (*this)[7] = static_cast< Value >( 275 ) / static_cast< Value >( 24192 );\n      }\n};\n\n\n\n\n\n\n\n} // detail\n} // odeint\n} // numeric\n} // boost\n\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_MOULTON_COEFFICIENTS_HPP_INCLUDED\n", "meta": {"hexsha": "0e7ed07d6b5be718942f11f7f633e1e4278e8875", "size": 5441, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp", "max_stars_repo_name": "creatologist/openFrameworks0084", "max_stars_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "libs/boost/boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp", "max_issues_repo_name": "creatologist/openFrameworks0084", "max_issues_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "libs/boost/boost/numeric/odeint/stepper/detail/adams_moulton_coefficients.hpp", "max_forks_repo_name": "creatologist/openFrameworks0084", "max_forks_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 32.1952662722, "max_line_length": 85, "alphanum_fraction": 0.6061385775, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5901502154547617}}
{"text": "#include \"CirclePatterns.h\"\n#include <Eigen/SparseQR>\n\nCirclePatterns::CirclePatterns(shared_ptr<ManifoldSurfaceMesh> mesh0, Vertex infVertex, \n    EdgeData<bool> eMask, EdgeData<bool> eBdry,FaceData<bool> fMask, int optScheme0, \n    vector<double>& solve, Eigen::VectorXd thetas):\nmesh(mesh0),\ninfVertex(infVertex),\neMask(eMask),\neBdry(eBdry),\nfMask(fMask),\nangles(mesh->nHalfedges()),\nthetas(thetas),\nradii(mesh->nFaces()),\neIntIndices(mesh->nEdges()),\nimaginaryHe(0),\nOptScheme(optScheme0)\n{\n    // I added a plus 1 here and at radii; should figure why I need to\n    solver.n = mesh->nFaces();\n    sol = solve;\n    uv = VertexData<Eigen::Vector2d> (*mesh);\n    eInd = mesh->getEdgeIndices();\n    vInd = mesh->getVertexIndices();\n    fInd = mesh->getFaceIndices();\n}\n\ninline double Cl2(double x) {\n    if (x == 0.0) return 0.0;\n    x = std::remainder(x, 2*M_PI);\n    if (x == 0.0) return 0.0;\n    \n    if (fabs(x) <= 2.0944) {\n        double xx = x * x;\n        return ((((((((((((2.3257441143020875e-22 * xx\n                           + 1.0887357368300848e-20) * xx\n                           + 5.178258806090624e-19) * xx\n                           + 2.5105444608999545e-17) * xx\n                           + 1.2462059912950672e-15) * xx\n                           + 6.372636443183181e-14) * xx\n                           + 3.387301370953521e-12) * xx\n                           + 1.8978869988971e-10) * xx\n                           + 1.1482216343327455e-8) * xx\n                           + 7.873519778281683e-7) * xx\n                           + 0.00006944444444444444) * xx\n                           + 0.013888888888888888) * xx\n                           - log(fabs(x)) + 1.0) * x;\n    }\n    \n    x += ((x > 0.0) ? - M_PI : M_PI);\n    double xx = x * x;\n    return ((((((((((((3.901950904063069e-15 * xx\n                       + 4.566487567193635e-14) * xx\n                       + 5.429792727596476e-13) * xx\n                       + 6.5812165661369675e-12) * xx\n                       + 8.167010963952222e-11) * xx\n                       + 1.0440290284867003e-9) * xx\n                       + 1.3870999114054669e-8) * xx\n                       + 1.941538399871733e-7) * xx\n                       + 2.927965167548501e-6) * xx\n                       + 0.0000496031746031746) * xx\n                       + 0.0010416666666666667) * xx\n                       + 0.041666666666666664) * xx\n                       + log(0.5)) * x;\n}\n\ndouble ImLi2Sum(double dp, double theta) {\n    double tStar = M_PI - theta;\n    double x = 2*atan(tanh(0.5*dp) * tan(0.5*tStar));\n    \n    return x*dp + Cl2(x + tStar) + Cl2(-x + tStar) - Cl2(2.0*tStar);\n}\n\ndouble fe(double dp, double theta) {\n    return atan2(sin(theta), exp(dp) - cos(theta));\n}\n\nvoid CirclePatterns::computeEnergy(double& energy, const Eigen::VectorXd& rho)\n{\n    energy = 0.0;\n\n    // sum over edges\n    for (Edge e : mesh->edges()) {\n        if (eMask[e]) {\n            int fk = e.halfedge().face().getIndex();\n\n            if (eBdry[e]) {\n                energy -= 2 * (M_PI - thetas[e.getIndex()]) * rho[fk];\n\n            } else {\n                int fl = e.halfedge().twin().face().getIndex();\n                energy += ImLi2Sum(rho[fk] - rho[fl], thetas[e.getIndex()]) -\n                          (M_PI - thetas[e.getIndex()]) * (rho[fk] + rho[fl]);\n            }\n        }\n    }\n\n    // sum over faces\n    for (Face f: mesh->faces()) {\n        if (!f.isBoundaryLoop() && fMask[f]) energy += 2*M_PI*rho[fInd[f]];\n    }\n}\n\nvoid CirclePatterns::computeGradient(Eigen::VectorXd& gradient, const Eigen::VectorXd& rho)\n{\n    // loop over faces\n    for (Face f : mesh->faces()) {\n        if (!f.isBoundaryLoop() && fMask[f]) {\n            int fk = fInd[f];\n            gradient[fk] = 2*M_PI;\n            \n            // sum of adjacent edges\n            Halfedge he = f.halfedge();\n            do {\n                Edge e = he.edge();\n                if (eBdry[e]) {\n                    gradient[fk] -= 2*(M_PI - thetas[eInd[e]]);\n                    \n                } else {\n                    Halfedge h = e.halfedge();\n                    int fl = fk == (int)fInd[h.face()] ? fInd[h.twin().face()] : fInd[h.face()];\n                    gradient[fk] -= 2*fe(rho[fk] - rho[fl], thetas[e.getIndex()]);\n                }\n                \n                he = he.next();\n            } while (he != f.halfedge());\n        }\n    }\n}\n\nvoid CirclePatterns::computeHessian(Eigen::SparseMatrix<double>& hessian, const Eigen::VectorXd& rho)\n{\n    std::vector<Eigen::Triplet<double>> HTriplets;\n    \n    for (Edge e : mesh->edges()) {\n        if (!eBdry[e] && eMask[e]) {\n            int fk = fInd[e.halfedge().face()];\n            int fl = fInd[e.halfedge().twin().face()];\n                        \n            double hessval = sin(thetas[eInd[e]]) / (cosh(rho(fk) - rho(fl)) - cos(thetas[eInd[e]]));\n            HTriplets.push_back(Eigen::Triplet<double>(fk, fk, hessval + 1e-8));\n            HTriplets.push_back(Eigen::Triplet<double>(fl, fl, hessval + 1e-8));\n            HTriplets.push_back(Eigen::Triplet<double>(fk, fl, -hessval));\n            HTriplets.push_back(Eigen::Triplet<double>(fl, fk, -hessval));\n        }\n    }\n    \n    hessian.setFromTriplets(HTriplets.begin(), HTriplets.end());\n}\n\nvoid CirclePatterns::setRadii()\n{\n    for (Face f : mesh->faces()) {\n        if (!f.isBoundaryLoop() && fMask[f]) radii[fInd[f]] = exp(solver.x[fInd[f]]);\n    }\n}\n\nbool CirclePatterns::computeRadii()\n{\n    MeshHandle handle;\n    handle.computeEnergy = std::bind(&CirclePatterns::computeEnergy, this, _1, _2);\n    handle.computeGradient = std::bind(&CirclePatterns::computeGradient, this, _1, _2);\n    handle.computeHessian = std::bind(&CirclePatterns::computeHessian, this, _1, _2);\n    \n    solver.handle = &handle;\n    if (OptScheme == GRAD_DESCENT) solver.gradientDescent();\n    else if (OptScheme == NEWTON) solver.newton();\n    else if (OptScheme == TRUST_REGION) solver.trustRegion();\n    else solver.lbfgs();\n    \n    // set radii\n    setRadii();\n    \n    return true;\n}\n\nvoid CirclePatterns::computeAnglesAndEdgeLengths(Eigen::VectorXd& lengths)\n{\n    for (Edge e : mesh->edges()) {\n        if(eMask[e]) {\n            Halfedge h1 = e.halfedge();\n        \n            if (eBdry[e]) {\n                angles[h1.getIndex()] = M_PI - thetas[eInd[e]];\n            \n            } else {\n                Halfedge h2 = h1.twin();\n                double dp = log(radii[h1.face().getIndex()]) - log(radii[h2.face().getIndex()]);\n                angles[h1.getIndex()] = fe(dp, thetas[e.getIndex()]);\n                angles[h2.getIndex()] = fe(-dp, thetas[e.getIndex()]);\n            }\n        \n            lengths[eInd[e]] = 2.0*radii[h1.face().getIndex()]*sin(angles[h1.getIndex()]);\n        }\n    }\n}\n\nvoid CirclePatterns::performFaceLayout(Halfedge he, const Eigen::Vector2d& dir,\n                                       Eigen::VectorXd& lengths, std::unordered_map<int, bool>& visited,\n                                       std::stack<Edge>& stack)\n{\n    if (he.isInterior() && fMask[he.face()]) {\n        int fIdx = he.face().getIndex();\n        if (visited.find(fIdx) == visited.end()) {\n            Halfedge next = he.next();\n            Halfedge prev = he.next().next();\n            \n            // compute new uv position\n            double angle = angles[next.getIndex()];\n            Eigen::Vector2d newDir = {cos(angle)*dir[0] - sin(angle)*dir[1],\n                                      sin(angle)*dir[0] + cos(angle)*dir[1]};\n            \n            uv[prev.vertex()] = uv[he.vertex()] + newDir*lengths[eInd[prev.edge()]];\n            \n            // mark face as visited\n            visited[fIdx] = true;\n            \n            // push edges onto stack\n            if(eMask[next.edge()]) stack.push(next.edge());\n            if(eMask[prev.edge()]) stack.push(prev.edge());\n        }\n    }\n}\n\nvoid CirclePatterns::setUVs()\n{\n    // compute edge lengths\n    Eigen::VectorXd lengths(mesh->nEdges());\n    computeAnglesAndEdgeLengths(lengths);\n    \n    // push any edge\n    std::stack<Edge> stack;\n    Edge e0;\n    for (Edge e :mesh->edges()) {\n        if(eMask[e]) {\n            e0 = e;\n            break;\n        }\n    };\n    stack.push(e0);\n\n    uv[e0.halfedge().vertex()] = Eigen::Vector2d::Zero();\n    uv[e0.halfedge().next().vertex()] = Eigen::Vector2d(lengths[eInd[e0]], 0);\n    \n    // perform layout\n    std::unordered_map<int, bool> visited;\n    while (!stack.empty()) {\n        Edge e = stack.top();\n        stack.pop();\n        \n        Halfedge h1 = e.halfedge();\n        Halfedge h2 = h1.twin();\n        \n        // compute edge vector\n\n        Eigen::Vector2d dir = uv[h2.vertex()] - uv[h1.vertex()];\n\n        dir.normalize();\n        // boundary edges\n        performFaceLayout(h1, dir, lengths, visited, stack);\n        performFaceLayout(h2, -dir, lengths, visited, stack);\n    }\n    \n    normalize();\n}\n\nVertexData<Eigen::Vector2d> CirclePatterns::parameterize() {\n    // set interior edge indices\n    int eIdx = 0;\n    for (Edge e : mesh->edges()) {\n        if (eMask[e]) {\n            if (!eBdry[e])\n                eIntIndices[eInd[e]] = eIdx++;\n            else {\n                eIntIndices[eInd[e]] = -1;\n                imaginaryHe++;\n            }\n        }\n    }\n\n    // compute radii\n    if (!computeRadii()) {\n        std::cout << \"Unable to compute radii\" << std::endl;\n        return VertexData<Eigen::Vector2d>();\n    }\n    \n    // set uvs\n    setUVs();\n    return uv;\n}\ndouble CirclePatterns::uvArea(Face f) {\n    if (f.isBoundaryLoop() || !fMask[f]) {\n        return 0;\n    }\n    \n    const Eigen::Vector2d& a(uv[f.halfedge().vertex()]);\n    const Eigen::Vector2d& b(uv[f.halfedge().next().vertex()]);\n    const Eigen::Vector2d& c(uv[f.halfedge().next().next().vertex()]);\n    \n    const Eigen::Vector2d u = b - a;\n    const Eigen::Vector2d v = c - a;\n    \n    return 0.5 * (u.x()*v.y() - v.x()*u.y());\n}\n\nEigen::Vector2d CirclePatterns::uvBarycenter(Face f) {\n    if (f.isBoundaryLoop() || !fMask[f]) {\n        return Eigen::Vector2d::Zero();\n    }\n    \n    const Eigen::Vector2d& a(uv[f.halfedge().vertex()]);\n    const Eigen::Vector2d& b(uv[f.halfedge().next().vertex()]);\n    const Eigen::Vector2d& c(uv[f.halfedge().next().next().vertex()]);\n    \n    return (a + b + c) / 3.0;\n}\nvoid CirclePatterns::normalize() {\n    // compute center\n    double totalArea = 0;\n    Eigen::Vector2d center = Eigen::Vector2d::Zero();\n    uv[infVertex.getIndex()] = Eigen::Vector2d::Zero();\n    /*\n    uv[infVertex.getIndex()].x() = -8;\n    uv[infVertex.getIndex()].y() = 5;\n    */\n    for (Face f : mesh->faces()) {\n        if (fMask[f]){\n            double area = uvArea(f);\n            center += area * uvBarycenter(f);\n            totalArea += area;\n        }\n    }\n    center /= totalArea;\n    \n    // shift\n    double r = 0.0;\n    for (Vertex v : mesh->vertices()) {\n        if (v != infVertex) {\n            uv[v] -= center;\n            r = std::max(r, uv[v].squaredNorm());\n        }\n    }\n    \n    // scale\n    r = sqrt(r);\n    for (Vertex v : mesh->vertices()) {\n        uv[v] /= r;\n    }\n}\n\ninline double shift(double c) {\n    return (c + 2.) * 500;\n}", "meta": {"hexsha": "fe90da6268827b47b7c12362ddcf29c3194660fb", "size": 11143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CirclePatterns.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": "src/CirclePatterns.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": "src/CirclePatterns.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": 31.566572238, "max_line_length": 104, "alphanum_fraction": 0.5065960693, "num_tokens": 3138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5901502074342061}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <Eigen/LU>\n\n#include \"tsef.h\"\n#include \"../parameters.h\"\n\nCHARGEFW2_METHOD(TSEF)\n\n\ndouble K(int i);\n\n\ndouble K(int i) {\n    double vals[] = {0.556, 0.778, 1.000, 1.053, 1.087, 1.091};\n    if (i > 6)\n        return vals[5];\n    else\n        return vals[i - 1];\n}\n\n\nstd::vector<double> TSEF::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.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    const double alpha = 14.4;\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = molecule.atoms()[i];\n        A(i, i) = parameters_->atom()->parameter(atom::hardness)(atom_i);\n        b(i) = - parameters_->atom()->parameter(atom::electronegativity)(atom_i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = molecule.atoms()[j];\n            int bd = molecule.bond_distance(atom_i, atom_j);\n            auto x = alpha * K(bd) / (0.84 * bd + 0.46);\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) = molecule.total_charge();\n\n    Eigen::VectorXd q = A.partialPivLu().solve(b).head(n);\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "8681f25ea23837c27cba1867bd2be11a1fdb031d", "size": 1409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/tsef.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/tsef.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/tsef.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": 25.1607142857, "max_line_length": 81, "alphanum_fraction": 0.5464868701, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.590120892414604}}
{"text": "#ifdef USE_EIGEN\n#define EIGEN_USE_MKL_ALL\n#endif\n// do this before include Eigen.\n\n#include \"optim.hpp\"\n\n#include \"alap.h\"\n#include \"matrix.h\" // \"\"\n\n#include \"timer.h\"\n\n#ifdef USE_EIGEN\n#include <Eigen/Core>\n#endif\n\n#include <iostream>\n\n#ifdef USE_LBFGSPP\n#include <LBFGS.h>\n#endif\n\n#include <iostream>\n\n#include \"helper.h\"\n#include \"mesh.h\"\n\nstatic void show_usage()\n{\n    std::cerr << \"Usage: \" \n              << \"Options:\\n\"\n              << \"\\t-h,--help\\t\\tShow this help message\\n\"\n              << \"\\t-d,--destination DESTINATION\\tSpecify the destination path\"\n              << std::endl;\n}\n\n/*\nDifferentiable Projection of Weights\n*/\n\narma::mat W2F_n(const arma::mat& W)\n{\n    using namespace arma;\n\n    arma::mat SW = sum(W, 1); // dim=1 so it sums all cols for each row. \n\n    arma::mat FW = W.each_col() / SW;\n\n    return FW;\n}\n\nconst double DEFAULT_W_EPSILON = 1e-2;\n\narma::mat W2F_m1(const arma::mat& W, const double epsilon=DEFAULT_W_EPSILON)\n{\n    // In matlab grammar: W2F_m = @(W) (W>epsilon) .* W + (W<=epsilon) .* (- W.^3 / epsilon^2  + 2 * W.^2 / epsilon );\n\n    using namespace arma;\n\n    arma::mat FW = (W > epsilon) % W + (W <= epsilon) % (- W % W % W / (epsilon*epsilon) + 2 * W % W / epsilon);\n\n    return FW;\n}\n\narma::mat dFW2dW_m1(const arma::mat& D, const arma::mat& W, const double epsilon=DEFAULT_W_EPSILON)\n{\n    // In matlab grammar: dFW2dW_m = @(D,W) ( (W>epsilon) + (W<=epsilon) .* (- 3 * W.^2 / epsilon^2  + 4 * W / epsilon ) ) .* D;\n\n    using namespace arma;\n\n    arma::mat FD = ( (W > epsilon) + (W <= epsilon) % (-3 * W % W / (epsilon*epsilon) + 4 * W / epsilon) ) % D; \n\n    return FD;\n}\n\nconst double DEFAULT_W_EPSILON1 = 0e-2;\nconst double DEFAULT_W_EPSILON2 = 1e-4;\n\narma::mat W2F_m2(const arma::mat& W, const double e1 = DEFAULT_W_EPSILON1, const double e2 = DEFAULT_W_EPSILON2)\n{\n\n    using namespace arma;\n\n    double c1 = (e1 + e2) / ((e2 - e1) * (e2 - e1) * (e2 - e1));\n    double c2 = (e1 + 2 * e2) / ((e2 - e1) * (e2 - e1));\n\n    arma::mat FW = (W <= -1000) % W -(W > e1) % (W < e2) % pow(W - e1, 3) * c1 + (W > e1) % (W < e2) % pow(W - e1, 2) * c2 + (W >= e2) % W;\n\n    return FW;\n}\n\narma::mat dFW2dW_m2(const arma::mat& D, const arma::mat& W, const double e1 = DEFAULT_W_EPSILON1, const double e2 = DEFAULT_W_EPSILON2)\n{\n\n    using namespace arma;\n\n    double c1 = (e1 + e2) / ((e2 - e1) * (e2 - e1) * (e2 - e1));\n    double c2 = (e1 + 2 * e2) / ((e2 - e1) * (e2 - e1));\n\n    arma::mat FD = ((W <= -1000) - (W > e1) % (W < e2) % pow(W - e1, 2) * 3 * c1 + (W > e1) % (W < e2) % pow(W - e1, 2) * c2 + (W >= e2) ) % D;\n\n    return FD;\n}\n\narma::mat dFW2dW_n(const arma::mat& D, const arma::mat& W)\n{\n    // In matlab grammar: dFW2dW_n = @(D,W) bsxfun(@rdivide, D, sum(W,2)) - bsxfun(@times, bsxfun(@rdivide, W, sum(W,2).^2), sum(D,2));\n\n    using namespace arma;\n\n    arma::mat FD;\n\n    arma::mat SW = sum(W, 1);\n    arma::mat SD = sum(D, 1);\n\n    arma::mat MM = W.each_col() / (SW % SW);\n\n    FD = D.each_col() / SW - MM.each_col() % SD; // % is the element-wise multiplication, NOT '*'!!!\t \n\n    return FD;\n}\n\nDense W2F_n(const Dense& W)\n{\n    // const arma::mat W_arma(W.head(), W.nrow(), W.ncol());\n    const arma::mat W_arma = dense_array_to_arma_mat(W);\n\n    arma::mat FW_arma = W2F_n(W_arma);\n\n    Dense FW = arma_mat_to_dense_array(FW_arma);\n\n    return FW;\n}\n\nDense dFW2dW_n(const Dense& D, const Dense& W)\n{\n\n    const arma::mat W_arma = dense_array_to_arma_mat(W);\n    const arma::mat D_arma = dense_array_to_arma_mat(D);\n\n    arma::mat FD = dFW2dW_n(D_arma, W_arma);\n\n    return arma_mat_to_dense_array(FD);\n}\n\nDense W2F_m(const Dense& W)\n{\n    const arma::mat W_arma = dense_array_to_arma_mat(W);\n\n    arma::mat FW_arma = W2F_m2(W_arma);\n\n    Dense FW = arma_mat_to_dense_array(FW_arma);\n\n    return FW;\n}\n\nDense dFW2dW_m(const Dense& D, const Dense& W)\n{\n\n    const arma::mat W_arma = dense_array_to_arma_mat(W);\n    const arma::mat D_arma = dense_array_to_arma_mat(D);\n\n    arma::mat FD = dFW2dW_m2(D_arma, W_arma);\n\n    return arma_mat_to_dense_array(FD);\n}\n\n\nint main(int argc, char** argv)\n{\n\n    const std::string SNAPSHOT_NONE = std::string(\"none\");\n\n    std::vector <std::string> sources;\n    std::string EXAMPLE = std::string(\"/qhw/qhw/data/tibiman-H\");\n    std::string SOLVER = std::string(\"adamd\");\n    std::string SNAPSHOT = SNAPSHOT_NONE;\n    std::string OUTPUT = std::string(\"\");\n    int NUM_ITER = 50;\n    double STEP_SIZE = 0.1;\n    bool PROJECT_SIMPLEX = false;\n    bool TIMING = false;\n    int REPEAT = 5;\n    bool LOG_HISTORY = false;\n    int LBFGS_M = 10;\n    double COND_BOUND = 0.2;\n    double DELTA = 0;\n    int verbose = 3;\n\n    for (int i = 1; i < argc; i++) {\n        std::string arg = argv[i];\n        if ((arg == \"-h\") || (arg == \"--help\")) {\n            show_usage();\n            return 0;\n        }\n        else if ((arg == \"--project\")) {\n            PROJECT_SIMPLEX = true;\n        }\n        else if ((arg == \"--timing\")) {\n            TIMING = true;\n        }\n        else if ((arg == \"-e\") || (arg == \"--example\")) {\n            if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n                EXAMPLE = std::string(argv[++i]); // Increment 'i' so we don't get the argument as the next argv[i].\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--example option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--snapshot\")) {\n            if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n                SNAPSHOT = std::string(argv[++i]); // Increment 'i' so we don't get the argument as the next argv[i].\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--snapshot option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--output\")) {\n            if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n                OUTPUT = std::string(argv[++i]); // Increment 'i' so we don't get the argument as the next argv[i].\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--output option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--solver\")) {\n            if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n                SOLVER = std::string(argv[++i]); // Increment 'i' so we don't get the argument as the next argv[i].\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--solver option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--lbfgs_m\")) {\n            if (i + 1 < argc) { // Make sure we aren't at the end of argv!\n                LBFGS_M = atoi(argv[++i]);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--lbfgs_m option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"-n\") || (arg == \"--num_iter\")) {\n            if (i + 1 < argc) { \n                NUM_ITER = atoi(argv[++i]);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--num_iter option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--repeat\")) {\n            if (i + 1 < argc) {\n                REPEAT = atoi(argv[++i]);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--repeat option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if (arg == \"--verbose\") {\n            if (i + 1 < argc) {\n                verbose = atoi(argv[++i]);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--verbose option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--log_history\")) {\n            LOG_HISTORY = true;\n        }\n        else if ( (arg == \"--step_size\")) {\n            if (i + 1 < argc) {\n                STEP_SIZE = atof(argv[++i]);\n                printf(\"step_size=%f\\n\", STEP_SIZE);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--step_size option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--cond_bound\")) {\n            if (i + 1 < argc) {\n                COND_BOUND = atof(argv[++i]);\n                printf(\"cond_bound=%f\\n\", COND_BOUND);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--cond_bound option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else if ((arg == \"--delta\")) {\n            if (i + 1 < argc) {\n                DELTA = atof(argv[++i]);\n                printf(\"delta=%f\\n\", DELTA);\n            }\n            else { // Uh-oh, there was no argument to the destination option.\n                std::cerr << \"--delta option requires one argument.\" << std::endl;\n                return 1;\n            }\n        }\n        else {\n            sources.push_back(argv[i]);\n        }\n    }\n\n    double t = 0;\n\n    std::string folder;\n    int dim = 2;\n\n    folder = EXAMPLE + std::string(\"/\");\n\n    printf(\"Loading files from %s.\\n\", folder.c_str());\n\n    if (OUTPUT.length() > 0) {\n        OUTPUT = OUTPUT;\n    }\n    \n    int length_his = NUM_ITER * (REPEAT + 1) * 2 + 1; // This *2 should not be need, just for redundancy.\n    double* energy_his = new double[length_his];\n    double* time_his = new double[length_his];\n\n    cholmod_common* cm = Begin();\n\n    Dense V;\n    DenseInt F;\n\n    Dense FA;\n\n//#ifdef USE_LARGER_G\n    Sparse Gk, Gu, G;\n//#endif\n\n    Sparse Gx, Gy, Gz;\n\n    Sparse Gxk, Gxu, Gyk, Gyu;\n    Sparse Gzk, Gzu; // for 3D\n\n    DenseInt known;\n    DenseInt unknown;\n    int nk, nu; \n\n    Sparse L; // Note L is not p.d., just p.s.d.\n    Sparse Mass;\n    Sparse invMass;\n\n    Dense mass_vertex;\n    mass_vertex.read(folder + \"mv.mtx\");\n\n    int f, mcdim;\n\n    Dense BC(0, 1);\n    BC.read(folder + \"BC.mtx\");\n    printf(\"BC size (%d,%d)\\n\", BC.nrow(), BC.ncol());\n\n    int nr;\n    known.read(folder + \"B.mtx\", true); // setting 'true' will delete 1 from the matrix for 0-index. \n\n    nk = known.nrow();\n    assert(known.ncol() == 1);\n\n    {\n\n        V.read(folder + \"V.mtx\");\n        F.read(folder + \"F.mtx\", true); // from 1-index matrix.\n\n        printf(\"Files loaded successfully!\\n\");\n\n        f = F.nrow();\n        dim = F.ncol() - 1;\n        \n        complementary_list(known, V.nrow(), unknown);\n\n        FA = (dim == 3) ? volume(V, F) : area(V, F);\n\n        sparse_grads(V, F,\n            known,\n            Gx, Gy, Gz,\n            Gxk, Gxu, Gyk, Gyu,\n            Gzk, Gzu);\n\n        Mass = Sparse::Diag(mass_vertex);\n        invMass = Sparse::Diag(Dense::div(1.0, mass_vertex));\n\n    }\n\n    mcdim = (dim == 2) ? 3 : 6; // so au is of dim (f*mcdim)\n\n\n    Sparse GxkT = Gxk.transposed();\n    Sparse GxuT = Gxu.transposed();\n    Sparse GykT = Gyk.transposed();\n    Sparse GyuT = Gyu.transposed();\n    Sparse GzkT;\n    Sparse GzuT;\n    if (dim == 3) {\n        GzkT = Gzk.transposed();\n        GzuT = Gzu.transposed();\n    }\n\n    Sparse GxuT_A00 = GxuT;\n    Sparse GxuT_A01 = GxuT;\n\n    Sparse GyuT_A01 = GyuT;\n    Sparse GyuT_A11 = GyuT;\n\n    // Used for 3D only: \n    Sparse GxuT_A02 = GxuT;\n    Sparse GzuT_A02 = GzuT;\n    Sparse GyuT_A12 = GyuT;\n    Sparse GzuT_A12 = GzuT;\n    Sparse GzuT_A22 = GzuT;\n\n    Sparse Mf = Sparse::Diag(FA);\n\n    Dense Zf = Dense::Zeros(f, 1);\n\n    Dense RFA = Dense::concatenate(FA,\n        Dense::concatenate(Zf, FA));\n\n    int stype = 0; // 0; // 0; unsymmetric // 1: symmetric and use triu\n\n    stype = 1; // 1: symmetric and use triu\n    Sparse A = GxuT_A00.mul(Gxu, stype)\n        + GyuT_A01.mul(Gxu, stype)\n        + GxuT_A01.mul(Gyu, stype)\n        + GyuT_A11.mul(Gyu, stype);\n    if (dim == 3) {\n        A = A\n            + GzuT_A22.mul(Gzu, stype)\n            + GxuT_A02.mul(Gzu, stype)\n            + GzuT_A02.mul(Gxu, stype)\n            + GyuT_A12.mul(Gzu, stype)\n            + GzuT_A12.mul(Gyu, stype);\n    }\n\n\n    L = (Mf * Gx).transposed().mul(Gx, stype)\n        + (Mf * Gy).transposed().mul(Gy, stype);\n    if (dim == 3) {\n        L = L + (Mf * Gz).transposed().mul(Gz, stype);\n    }\n\n    int* I;\n    int* J;\n    symmetric_tensor_assemble_indices(I, J, f, dim);\n\n    // Setup the objective function:\n    Sparse Q; \n    stype = 1; // 1: symmetric and use triu\n    (L * invMass).mul(L, Q, stype);\n    // So Q is a symmetric matrix such that \n    // Q==L*M^-1*L. \n\n    Sparse diagm = Sparse::Diag(\n        Dense::concatenate(FA, dim==2? FA : Dense::concatenate(FA, FA))\n    );\n\n    Sparse Quu, Quk;\n    Sparse Qku, Qkk;\n\n    Sparse Lua = (GxuT * Mf * Gx + GyuT * Mf * Gy);\n    Sparse Lka = (GxkT * Mf * Gx + GykT * Mf * Gy);\n    if (dim == 3) {\n        Lua = Lua + GzuT * Mf * Gz;\n        Lka = Lka + GzkT * Mf * Gz;\n    }\n    Sparse Lau = Lua.transposed();\n    Sparse Lak = Lka.transposed();\n    (Lua* invMass).mul(Lau, Quu, 0);\n    (Lka* invMass).mul(Lak, Qkk, 0);\n    (Lua* invMass).mul(Lak, Quk, 0);\n\n    Qku = Quk.transposed();\n\n    Sparse SA = GxuT * Mf * Gxk + GyuT * Mf * Gyk;\n    if (dim == 3)\n        SA = SA + GzuT * Mf * Gzk;\n    Dense B = (SA * BC) * (-1);\n    \n\n    Dense X(B.nrow(), B.ncol());\n    \n    if (verbose>2) \n    {\n        t = GetTime();\n        for (int i = 0; i < 1; i++) \n        {\n            X = A.mul(B); \n        }\n        printf(\"Time for linear matrix-vector mul :%f.\\n\", GetTime() - t);\n\n        Dense X3(B.nrow(), B.ncol());\n        t = GetTime();\n        for (int i = 0; i < 1000; i++) \n        {\n            Dense::saxy(X, X3, -0.4);\n        }\n        printf(\"Time for saxy x1000:%f.\\n\", GetTime() - t);\n\n        t = GetTime();\n        configure_solve(A.cm);\n        A.solve(B, X); // X = A \\ B;\n        printf(\"Time for one linear solve :%f.\\n\", GetTime() - t);\n    }\n\n    Dense Y = A.mul(X);\n\n    t = GetTime();\n    A.symbolic_factor();\n    printf(\"symbolic_factor: %f seconds.\\n\", GetTime() - t);\n\n    t = GetTime();\n    A.numerical_factor();\n    printf(\"numerical_factor: %f seconds.\\n\", GetTime() - t);\n\n\n    Dense W_u;\n    Dense GW;\n    Dense Res_u;\n    Dense BR;\n    Dense PS;\n\n    Dense st0 = Dense::Ones(f, 1);\n    // Dense st0 = FA;\n\n    Dense at0 = Dense::concatenate(st0,\n        Dense::concatenate(st0 * 1e-6, st0));\n\n    if (dim == 3) \n    {\n        at0 = Dense::concatenate(at0,\n            Dense::concatenate(Dense::concatenate(st0,st0) * 1e-6, st0));\n    }\n\n    if (SNAPSHOT != SNAPSHOT_NONE) \n    {\n        Dense at0_snapshot; \n        at0_snapshot.read(SNAPSHOT);\n        if (at0.nrow() == at0_snapshot.nrow() && at0.ncol() == at0_snapshot.ncol() ) {\n            printf(\"Snapshot file %s is loaded.\\n\", SNAPSHOT.c_str());\n            at0 = at0_snapshot;\n        }\n        else {\n            printf(\"Snapshot file is of wrong size! File ignored. \\n\");\n        }\n    }\n \n\n    Dense au = at0;\n\n    Sparse diagAU = diagm;\n\n    Dense W(L.nrow(), BC.ncol());\n    W.slice_assign_value(known, BC, 0); // W(known, :) = BC;\n\n    Dense FW(L.nrow(), BC.ncol());\n    FW.slice_assign_value(known, BC, 0);\n\n    Dense FW_u, FW_k;\n\n    Dense gau = Dense::Zeros(f * mcdim, 1);\n    Dense gau_j = Dense::Zeros(f * mcdim, 1);\n\n    t = GetTime();\n\n    std::function<Dense(const Dense&)> W2F_pn = [&](const Dense& W)\n    {\n        return W2F_n(W2F_m(W));\n        //return W2F_n(W);\n    };\n\n    std::function<Dense(const Dense&, const Dense&)> dFW2dW_pn = [&](const Dense& D, const Dense& W)\n    {\n        return dFW2dW_n(dFW2dW_m(D, W), W2F_m(W));\n        //return dFW2dW_n(D, W);\n    };\n\n    std::function<Dense(const Dense&)> W2F;\n    std::function<Dense(const Dense&, const Dense&)> dFW2dW;\n    \n    if (PROJECT_SIMPLEX) \n    {\n        W2F = W2F_pn;\n        dFW2dW = dFW2dW_pn;\n    }\n    else \n    {\n        W2F = [&](const Dense& W)\n        {\n            return W;\n        };\n        dFW2dW = [&](const Dense& D, const Dense& W)\n        {\n            return D;\n        };\n    }\n\n    Grad grad = compute_grads_pre(V, F);\n\n    // GRADtf64 grad_tf = GRADtf64(V, F, W.ncol());\n    GRADtf grad_tf = GRADtf(V, F, W.ncol());\n\n    int i = 0;\n    double start_time = GetTime();\n    // Dense gat = Dense::Zeros(mcdim * f, 1);\n    // Dense at = Dense::concatenate(Dense::Ones(f, 1),\n    //     Dense::concatenate(Dense::Ones(f, 1) * 1e-6, Dense::Ones(f, 1))); // do not use Dense::Zeros(f, 1)\n\n    const Para para; \n\n    auto fun = [&](const arma::vec& at, arma::vec& gat)\n    {\n\n        t = GetTime();\n\n        if (TIMING) \n        {\n            printf(\"Entered loop for timing.\\n\");\n        }\n\n        /* update au from at */\n\n        // arma::vec at_tmp = at;\n        // s_at2au_fast(at_tmp, au, FA, dim, para);\n        s_at2au(at, au, FA, dim, para); \n\n        if (TIMING) \n        {\n            printf(\"Check point 1: %f.\\t Apply Parameterization.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        int stype = 1; // 1: symmetric and use triu\n\n        Sparse A2 = Sparse::assemble_lap(GxuT, GyuT, GzuT, au, dim);\n        Sparse::assign_value_same_pattern(A2, A);\n        // A.symbolic_factor(); // no need since sparsity pattern remain unchanged. \n\n        B = Sparse::assemble_lap_off_diag(GxuT, GyuT, GzuT, GxkT, GykT, GzkT, au, dim) * (BC * (-1));\n\n        if (TIMING) \n        {\n            printf(\"Check point 2: %f.\\t Assemble Lap.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        configure_solve(A.cm);\n\n        A.numerical_factor();\n\n        if (TIMING) \n        {\n            printf(\"Check point 3: %f.\\t Numerical factor.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        W_u = A.solve_with_factor(B); // W_u = A\\B; but more efficiently.\n\n        if (TIMING) \n        {\n            printf(\"Check point 4: %f.\\t Back Sub 1.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        // project the weights to the probability simplex. \n        FW_u = W2F(W_u);\n        FW_k = BC;\n\n        W.slice_assign_value(unknown, W_u, 0); // W(unknown, :) = W_u;\n                \n        double e = 1 / (i + 1); \n        // many optimizers do not rely on the energy value e, only its gradient. \n        // in this case e can be an arbitary value to save time.\n\n        bool last_iter = i == (NUM_ITER * (REPEAT + 1)); // it's not (i+1) here. \n\n        if (verbose > 2 || last_iter) \n        {\n\n            Dense H_u = Quu.mul(FW_u) + Quk.mul(FW_k);\n            Dense H_k = Qku.mul(FW_u) + Qkk.mul(FW_k);\n            e = ((Dense::times(FW_u, H_u).reduce_sum(0) + Dense::times(FW_k, H_k).reduce_sum(0)).reduce_sum(1))(0, 0);\n\n            printf(\"\\nIter %04d: energy=%f \\t\", i, e);\n\n            if (verbose > 3) \n            {\n                printf(\"W_u.min()=\");\n                W_u.reduce_min().print();\n                printf(\"FW_u.min()=\");\n                FW_u.reduce_min().print();\n            }\n\n            if (i < length_his) \n            {\n                energy_his[i] = e;\n                time_his[i] = GetTime() - start_time;\n            }\n            if (LOG_HISTORY)\n            {\n                FW.slice_assign_value(unknown, FW_u, 0);\n                char fname[64];\n                sprintf(fname, \"W%04d.mtx\", i);\n                FW.write(OUTPUT + fname); // projected weights\n                sprintf(fname, \"UW%04d.mtx\", i);\n                W.write(OUTPUT + fname); // unprojected weights\n            }\n        }\n        else \n        {\n            printf(\"Iter %04d...\\t\", i);\n        }\n        \n        if (verbose>4) \n        {\n            Dense NW = W2F_n(W);\n            double pou = (W - NW).norm() / W.norm();\n            printf(\"Checking partition of unity: %f, expecting ~0.\\n\", pou);\n        }\n\n        if (TIMING) \n        {\n            printf(\"Check point 5: %f.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        // Calculate gradients. \n\n        switch (4) { // 4 is fastest\n\n        case 0:\n\n            GW = G * W; // old code\n\n            break;\n\n        case 1:\n\n            // [Gxu, Gxk]\n            // [Gyu, Gyk] [W_u] = \n            // [Gzu, Gzk] [W_k]\n            GW = Dense::concatenate(Gxu * W_u + Gxk * BC, Gyu * W_u + Gyk * BC);\n            if (dim == 3)\n                GW = Dense::concatenate(GW, Gzu * W_u + Gzk * BC);\n\n            break;\n\n        case 2:\n\n            compute_grads(V, F, grad, W, GW); // somehow slower than G * W...\n\n            break;\n\n        case 3:\n\n            tf_compute_grads(V, F, W, GW);\n\n            break;\n\n        case 4:\n\n            grad_tf.run(W, GW);\n\n            break;\n        default:\n            ;\n        }\n \n        if (TIMING) \n        {\n            printf(\"Check point 6: %f. \\t Gradient computation. \\n\", GetTime() - t); t = GetTime();\n        }\n\n        Res_u = (Quu.mul(FW_u) + Quk.mul(FW_k))* 2.0;\n\n        Dense dW = dFW2dW(Res_u, W_u); // since dFW2dW is a row-wise operation\n\n        if (TIMING) \n        {\n            printf(\"Check point 7: %f.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        BR = A.solve_with_factor(dW);\n\n        if (TIMING) \n        {\n            printf(\"Check point 8: %f. \\t Back Sub 2\\n\", GetTime() - t); t = GetTime();\n        }\n\n        // Calculate gradients for the second time\n\n        switch (2) { // 2 is fastest\n\n        case 0:\n\n            PS = Gu.mul(BR); // old code\n\n            break;\n\n        case 1:\n\n            PS = Dense::concatenate(Gxu.mul(BR), Gyu.mul(BR));\n            if (dim == 3)\n                PS = Dense::concatenate(PS, Gzu.mul(BR));\n\n            break;\n\n        case 2:\n\n            static Dense BRa;\n            if (i==0)\n                BRa = Dense::Zeros(V.nrow(), BR.ncol());\n\n            BRa.slice_assign_value(unknown, BR, 0);\n\n            grad_tf.run(BRa, PS);\n\n            break;\n\n        default:\n            ;\n        }\n        \n        if (TIMING) \n        {\n            printf(\"Check point 9: %f. \\t Mat Multiplication 2.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        gau = Dense::Zeros(f * mcdim, 1);\n\n        for (int j = 0; j < W.ncol(); j++) \n        {\n            symmetric_tensor_span_dot(&GW(0, j), &PS(0, j), gau_j.head(), f, dim);\n            // gau = gau - gau_j;\n            Dense::saxy(gau_j, gau, -1.0);\n        }\n\n        if (TIMING) \n        {\n            printf(\"Check point 10: %f.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        /* gat <- gau: back-prop grad */\n        \n        // s_pdapdt_lmul_fast(at_tmp, gau, gat, FA, dim, para);\n        s_pdapdt_lmul(at, gau, gat, FA, dim, para); \n        \n        if (TIMING) \n        {\n            printf(\"Check point 11: %f.\\n\", GetTime() - t); t = GetTime();\n        }\n\n        i++;\n        return e;\n        // e may not be the function value, depends on parameters. \n    };\n\n    Dense at_out;\n    {\n        using arma::vec;\n        using arma::mat;\n        vec at = dense_array_to_arma_vec(at0);\n\n        printf(\"Solver: %s\\n\", SOLVER.c_str());\n\n        if (SOLVER==std::string(\"adamd\")) \n        {\n            /* Adam - based optim */\n\n            optim::algo_settings_t settings;\n            settings.gd_method = 6;\n            settings.gd_settings.step_size = STEP_SIZE;\n            settings.iter_max = NUM_ITER;\n\n            std::function<double(const arma::vec&, arma::vec*, void*)> fn \n                = [&](const arma::vec& at, arma::vec* pgat, void* opt_data) {\n                double v = fun(at, *pgat);\n                return v;\n            };\n\n            for (int j = 0; j < REPEAT; j++)\n            {\n                optim::gd2(at, fn, NULL, settings); // gd2 gets rid of an extra call of fn at the end. \n\n                settings.gd_settings.step_size /= 2.0;\n                printf(\"\\nlr=%g \\n\", settings.gd_settings.step_size);\n            }\n\n            optim::gd(at, fn, NULL, settings);\n            // NUM_ITER * REPEAT + NUM_ITER: in total\n\n        } \n        else if (SOLVER == std::string(\"adam\")) \n        {\n\n            optim::algo_settings_t settings;\n            settings.gd_method = 6;\n            settings.gd_settings.step_size = STEP_SIZE;\n            settings.iter_max = NUM_ITER * (REPEAT+1);\n\n            std::function<double(const arma::vec&, arma::vec*, void*)> fn\n                = [&](const arma::vec& at, arma::vec* pgat, void* opt_data) {\n                double v = fun(at, *pgat);\n                return v;\n            };\n\n            optim::gd(at, fn, NULL, settings);\n\n        } \n        else if (SOLVER == std::string(\"lbfgs\")) \n        {\n\n            optim::algo_settings_t settings;\n            settings.iter_max = NUM_ITER * (REPEAT + 1);\n            settings.lbfgs_par_M = LBFGS_M;\n\n            std::function<double(const arma::vec&, arma::vec*, void*)> fn\n                = [&](const arma::vec& at, arma::vec* pgat, void* opt_data) {\n                double v = fun(at, *pgat);\n                return v;\n            };\n\n            optim::lbfgs(at, fn, NULL, settings);\n\n        }\n        else \n        {\n            std::cerr << \"--solver not supported.\" << std::endl;\n        }\n\n        at_out = arma_vec_to_dense_array(at);\n    }\n\n    printf(\"numerical_factor + solving: %f seconds.\\n\", GetTime() - start_time);\n\n    if (LOG_HISTORY) \n    {\n        printf(\"Timing is not meaningful due to logging cost. \\n\");\n    }\n\n    FW.slice_assign_value(unknown, FW_u, 0); // FW(unknown, :) = FW_u;\n    FW.write(OUTPUT+\"W.mtx\"); // projected weights\n    W.write(OUTPUT+\"UW.mtx\"); // unprojected weights\n    at_out.write(OUTPUT+\"at.mtx\");\n    au.write(OUTPUT + \"au.mtx\");\n\n\n    End(cm);\n\n    free(I);\n    free(J);\n\n    FILE* filename = fopen((OUTPUT+\"log.txt\").c_str(), \"wb\");\n    if (filename != NULL) \n    {\n        for (int i = 0; i < length_his; i++) \n        {\n            fprintf(filename, \"%04d\\t%g\\t%g\\n\", i, energy_his[i], time_his[i]);\n        }\n        fclose(filename);\n    }\n\n    free(energy_his);\n\n    return 0;\n}\n\n// #include \"iter_lap_timing.cpp\"", "meta": {"hexsha": "a02ce0eb8b4b55a1de608ae01abba49ee951d5d3", "size": 26250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qhw/qhw.cpp", "max_stars_repo_name": "wangyu9/qhw-code", "max_stars_repo_head_hexsha": "62e09fdcfe5c96201b9e2fe897c9314dbab81a21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T08:42:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T23:08:32.000Z", "max_issues_repo_path": "qhw/qhw.cpp", "max_issues_repo_name": "wangyu9/qhw-code", "max_issues_repo_head_hexsha": "62e09fdcfe5c96201b9e2fe897c9314dbab81a21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qhw/qhw.cpp", "max_forks_repo_name": "wangyu9/qhw-code", "max_forks_repo_head_hexsha": "62e09fdcfe5c96201b9e2fe897c9314dbab81a21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-06T14:23:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T14:23:14.000Z", "avg_line_length": 27.0618556701, "max_line_length": 143, "alphanum_fraction": 0.4952, "num_tokens": 7854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5900973921506983}}
{"text": "\t#include \"savageFunctions.h\"\n#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <string>\n#include <Eigen/Dense>\n\n// a little documentation up front:\n// an eigen vector is what you'd expect--a vector that only scales in a linear transformation\n// an \"Eigen\" vector is a vector using the Eigen api\n\n// also, it's pretty convenient that eigen objects work as regular objects for pass by value and return by value\n// so that's nice to keep in mind\n\n\n\nEigen::Matrix3d savageFunctions::skew(Eigen::Vector3d v)\n{//pass in an \"Eigen\" vector\n\n\t//initialize a \"skewwed\" matrix\n\tEigen::Matrix3d skewwed;\n\n\t//populate the \"skewwed\" matrix\n\tskewwed <<    0, -v(2),  v(1), \n\t\t\t   v(2),     0, -v(0),\n\t\t\t  -v(1),  v(0),     0;\n\n  //return the skewwed matrix\n  return skewwed;\n}\n\nEigen::VectorXd savageFunctions::stateIntegrate(Eigen::Vector3d omega, Eigen::Vector3d accel,\n\t\t\t\t\t\t\t\t\t\t\t\t  Eigen::VectorXd prevState, Eigen::Matrix3d prevDCM, double d_t)\n{\n\t//state of form,\n\t// 0 x \n\t// 1 y\n\t// 2 z\n\t// 3 v_x\n\t// 4 v_y\n\t// 5 v_z\n\t// 6 a_x\n\t// 7 a_y\n\t// 8 a_z\n\n\t//and of course the previous dcm is needed\n\n\t//EVERY PARAMETER must be of the \"Eigen\" type\n\n\t//Okay getting started here\n\t//First things first,\n\t//use the previous time step DCM and the current angular rates to \n\t//find the current derivative of the current DCM\n\t//the d_ will be used to denore a time rate of change for something that doesn't have a \n\t//standard usage (eg. theta->omega)\n\t//taken from 3-53 of savage (eq. 3.3.2-6)\n\tEigen::Matrix3d d_DCM = prevDCM * skew(omega);\n\n\t//calculate the current DCM\n\tEigen::Matrix3d DCM = d_DCM * d_t + prevDCM;\n\n\t// use the current DCM to convert acceleration to the inertial frame\n\tEigen::Vector3d accelInertial = DCM * accel;\n\n\t//okay now working down through the state vector and integrating as I go\n\n\t\t\t\t\t\t\t\n\tEigen::VectorXd state(9);  // x               v*t                 .5at^2\n\t               state << prevState[0] + prevState[3] * d_t + accelInertial[0] * pow(d_t,2) * .5, //x\n\t\t\t\t\t\t\tprevState[1] + prevState[4] * d_t + accelInertial[1] * pow(d_t,2) * .5, //y\n\t\t\t\t\t\t\tprevState[2] + prevState[5] * d_t + accelInertial[2] * pow(d_t,2) * .5, //z\n\t\t\t\t\t\t\t // v                 a*t\n\t\t\t\t\t\t\tprevState[3] + accelInertial[0] * d_t, //v_x\n\t\t\t\t\t\t\tprevState[4] + accelInertial[1] * d_t, //v_y\n\t\t\t\t\t\t\tprevState[5] + accelInertial[2] * d_t, //v_z\n\t\t\t\t\t\t\t // a\n\t\t\t\t\t\t\taccelInertial[0], //a_x\n\t\t\t\t\t\t\taccelInertial[1], //a_y\n\t\t\t\t\t\t\taccelInertial[2]; //a_z\n\n\tstd::cout << DCM << std::endl;\n\n\treturn state;\n} s\n\n\n", "meta": {"hexsha": "a9c45e21cee3f1f00fb0f5e8106fec831c1942b1", "size": 2506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "savageFunctions.cpp", "max_stars_repo_name": "LyonFoster/GNC-Homework", "max_stars_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "savageFunctions.cpp", "max_issues_repo_name": "LyonFoster/GNC-Homework", "max_issues_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "savageFunctions.cpp", "max_forks_repo_name": "LyonFoster/GNC-Homework", "max_forks_repo_head_hexsha": "445ce0369785b6731555602eac1e0f42cad342eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8045977011, "max_line_length": 112, "alphanum_fraction": 0.6364724661, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5900973813710984}}
{"text": "#include <string>\n#include <vector>\n#include <map>\n#include <set>\n#include <cmath>\n#include <utility>\n#include <algorithm>\n\n#include \"main.h\"\n#include \"option.h\"\n#include \"likelihood.h\"\n#include <boost/math/distributions/chi_squared.hpp>\n\n// needed by alglib\n#include \"stdafx.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include \"optimization.h\"\n#include \"ap.h\"\n\nstruct fn_data {\n    std::string         base;\n    std::vector<double> errRateV;\n};\n\n// composite log likelihood: l_c(theta)\n// mat theta is a column vector which has 4 elements for A, C, G, T, respectively.\n//\ndouble composite_LogLikelihood (\n        const string         &base,\n        const vector<double> &errRateV,\n        const alglib::real_1d_array  &theta )\n{\n    double l_c(0.0);\n\n    for (size_t i(0); i != base.size(); i++ ) {\n        const double &e = errRateV[i]/3;\n        switch( base[i] ) {\n            case 'A': l_c += log( (1-4*e) * theta[0] + e ); break;\n            case 'C': l_c += log( (1-4*e) * theta[1] + e ); break;\n            case 'G': l_c += log( (1-4*e) * theta[2] + e ); break;\n            case 'T': l_c += log( (1-4*e) * theta[3] + e ); break;\n            default: cerr << \"unknown base in \" << base << endl,exit(1);\n        }\n    }\n\n    return l_c;\n}\n\n// -composite score function: -U_c(theta)\n// return a column vector\n//\nalglib::real_1d_array composite_score (\n        const string         &base,\n        const vector<double> &errRateV,\n        const alglib::real_1d_array  &theta )\n{\n    alglib::real_1d_array U_c = \"[0,0,0,0]\";\n\n    for (size_t i(0); i != base.size(); i++ ) {\n        const double &e = errRateV[i]/3;\n\n        switch( base[i] ) {\n            case 'A': U_c[0] -= (1-4*e) / ( (1-4*e)*theta[0] + e );  break;\n            case 'C': U_c[1] -= (1-4*e) / ( (1-4*e)*theta[1] + e );  break;\n            case 'G': U_c[2] -= (1-4*e) / ( (1-4*e)*theta[2] + e );  break;\n            case 'T': U_c[3] -= (1-4*e) / ( (1-4*e)*theta[3] + e );  break;\n            default: cerr << \"unknown base in \" << base << endl, exit(1);\n        }\n    }\n\n    return U_c;\n}\n\n// gradient optimization\nvoid function1_grad (\n        const alglib::real_1d_array  &x,\n        double                       &func,\n        alglib::real_1d_array        &grad,\n        void                         *opt_data )\n{\n    fn_data* objfn_data = reinterpret_cast<fn_data*>(opt_data);\n    const std::string &base = objfn_data->base;\n    const std::vector<double> &errRateV = objfn_data->errRateV;\n\n    func = -composite_LogLikelihood( base, errRateV, x);\n    grad = composite_score( base, errRateV, x );\n}\n\nstring initAlleleFreq (\n        mCharUlong       &fr,\n        const double     &depth,\n        const char       &except_b )\n{\n    ostringstream s;\n    s << '[';\n\n    if ( depth == fr[except_b] ) {\n        for ( auto b : \"ACGT\" ) {\n            b == except_b ? s << 0.0 : s << 0.333333333;\n            b == 'T' ? s << ']' : s << ',';\n            if ( b == 'T' ) break;\n        }\n    }\n    else {\n        for ( auto b : \"ACGT\" ) {\n            b == except_b ? s << 0.0 : s << fr[b] / (depth - fr[except_b]);\n            b == 'T' ? s << ']' : s << ',';\n            if ( b== 'T' ) break;\n        }\n    }\n    return s.str();\n}\n\nstring initAlleleFreq (\n        mCharUlong       &fr,\n        double           depth,\n        const set<char>  &except_bs )\n{\n    ostringstream s;\n\n    for ( auto b : \"ACGT\" ) {\n        set<char>::const_iterator it = except_bs.find(b);\n        if ( it != except_bs.end() ) {\n            fr[b] = 0;\n            depth -= fr[b];\n        }\n\n        if ( b== 'T' ) break;\n    }\n\n    if ( depth == 0 ) {\n        s  << \"[0.25,0.25,0.25,0.25]\";\n        return s.str();\n    }\n\n    s << '[';\n    for ( auto b : \"ACGT\" ) {\n        set<char>::const_iterator it = except_bs.find(b);\n        it != except_bs.end() ? s << 0.0 : s << fr[b] / depth;  // depth here don't contain num of except_bs\n        b == 'T' ? s << ']' : s << ',';\n        if ( b== 'T' ) break;\n    }\n\n    return s.str();\n}\n\nstring _upBoundary(const char except_b)\n{\n    ostringstream s;\n    s << '[';\n\n    for ( auto b : \"ACGT\" ) {\n        b == except_b ? s << 0 : s << 1;\n        b == 'T' ? s << ']' : s << ',';\n        if ( b == 'T' ) break;\n    }\n    return s.str();\n}\n\nstring _upBoundary(const set<char> except_bs)\n{\n    ostringstream s;\n    s << '[';\n\n    for ( auto b : \"ACGT\" ) {\n        set<char>::const_iterator it = except_bs.find(b);\n        it != except_bs.end() ? s << 0 : s << 1;\n        b == 'T' ? s << ']' : s << ',';\n        if ( b == 'T' ) break;\n    }\n    return s.str();\n}\n\nmap<char, vector<double> > llh_genotype(const string &s, const string &q, const Option &opt)\n{\n//    mCharDouble ntP; // nt => pvalue\n    map<char, vector<double> > ntPF; // nt => pvalue, fraction\n\n    boost::math::chi_squared X2_dist(1);\n\n    mCharUlong fr;\n    for ( auto b : \"ACGTN\" ) {\n        fr[b] = 0;\n        if ( b == 'N' ) break;\n    }\n\n    string new_s(\"\"), new_q(\"\");\n    for ( size_t i(0); i != s.size(); i++ ) {\n        if ( lowQuality(q[i], opt) || s[i] == 'N' || s[i] == '*' )  continue; // fr['N'] == 0\n        fr[ s[i] ]++;\n        new_s += s[i];\n        new_q += q[i];\n    }\n\n    double depth(new_s.size());\n    vector<double> errV = quaToErrorRate(new_q, opt);\n\n    if ( depth == 0 ) return ntPF;\n\n    fn_data data;\n    data.base = new_s;\n    data.errRateV = errV;\n\n    // var for alglib\n    alglib::minbleicstate state;\n    alglib::minbleicreport rep;\n    double epsg(0.000001);\n    double epsf(0.0);\n    double epsx(0.0);\n    alglib::ae_int_t maxits(0);\n\n    // constraint: sum of frequency of 4 alleles == 1\n    alglib::real_2d_array c = \"[[1,1,1,1,1]]\";  // sum of four allele == 1\n    alglib::integer_1d_array ct = \"[0]\";    // equal\n    alglib::real_1d_array bndl = \"[0,0,0,0]\";  // lower boundary\n\n    // four allele maximize\n    double cl_4(0.0);\n    try {\n        string AFstr = initAlleleFreq(fr, depth, 'N');\n        alglib::real_1d_array alg_x = AFstr.c_str();\n        alglib::real_1d_array bndu = \"[1,1,1,1]\";\n\n        alglib::minbleiccreate(alg_x, state);\n        alglib::minbleicsetlc(state, c, ct);\n        alglib::minbleicsetbc(state, bndl, bndu);\n        alglib::minbleicsetcond(state, epsg, epsf, epsx, maxits);\n        alglib::minbleicoptimize(state, function1_grad, NULL, &data );\n        alglib::minbleicresults(state, alg_x, rep);\n\n        if ( opt.debug ) {\n            printf(\"%d\\n\", int(rep.terminationtype)); // EXPECTED: 4\n            printf(\"%s\\n\", alg_x.tostring(20).c_str());\n        }\n\n        cl_4 = composite_LogLikelihood( data.base, data.errRateV, alg_x );\n        if ( opt.debug ) cout << \"cl_4: \" << setprecision(20) << cl_4 << endl;\n    }\n    catch ( alglib::ap_error &e ) {\n        cerr << \"catch error: \" << e.msg << \" at seq[\" << new_s << \"] qua[\" << new_q << \"]\" << endl;\n    }\n\n    map<char, string> init_V;\n    map<char, string> bndu_V;\n\n    for ( auto b : \"ACGT\" ) {\n        init_V[b] = initAlleleFreq(fr, depth, b);\n        bndu_V[b] = _upBoundary(b);\n        if ( b == 'T' ) break;\n    }\n\n    for ( mCharUlong::const_iterator it = fr.begin(); it != fr.end(); it++ )\n    {\n        if ( it->second < opt.minSupOnEachStrand || it->second/depth < opt.minFractionInFam ) continue;\n\n        double cl_3(0.0);\n        try {\n            alglib::real_1d_array alg_x = init_V[ it->first ].c_str();\n            alglib::real_1d_array bndu = bndu_V[ it->first ].c_str();\n\n            alglib::minbleiccreate(alg_x, state);\n            alglib::minbleicsetlc(state, c, ct);\n            alglib::minbleicsetbc(state, bndl, bndu);\n            alglib::minbleicsetcond(state, epsg, epsf, epsx, maxits);\n            alglib::minbleicoptimize(state, function1_grad, NULL, &data );\n            alglib::minbleicresults(state, alg_x, rep);\n\n            if ( opt.debug ) {\n                printf(\"%d\\n\", int(rep.terminationtype)); // EXPECTED: 4\n                printf(\"%s\\n\", alg_x.tostring(20).c_str());\n            }\n\n            cl_3 = composite_LogLikelihood( data.base, data.errRateV, alg_x );\n            if ( opt.debug ) cout << \"cl_3: \" << cl_3 << endl;\n        }\n        catch ( alglib::ap_error &e ) {\n            cerr << \"catch error: \" << e.msg << \" at seq[\" << new_s << \"] qua[\" << new_q\n                << \"] for base[\" << it->first << \"]\" << endl;\n        }\n\n        if ( cl_4 - cl_3 > opt.lhrGapCutoff ) {\n//            ntP[ it->first ] = 1 - boost::math::cdf(X2_dist, 2*(cl_4 - cl_3) );\n            ntPF[ it->first ].push_back( 1 - boost::math::cdf(X2_dist, 2*(cl_4 - cl_3)) );\n        }\n    }\n\n    if ( ntPF.size() == 1 ) {\n        ntPF[ ntPF.begin()->first ].push_back(1.0);\n        return ntPF;\n    }\n    else if ( ntPF.size() > 1 ) {\n        set<char> except_bs;\n        for ( auto b : \"ACGT\" ) {\n            map<char, vector<double> >::const_iterator it = ntPF.find(b);\n            if ( it == ntPF.end() ) {  // not in ntPF\n                except_bs.insert(b);\n            }\n\n            if ( b == 'T' ) break;\n        }\n\n        string AFstr = initAlleleFreq(fr, depth, except_bs);\n        alglib::real_1d_array alg_x = AFstr.c_str();\n\n        try {\n            string upBnd = _upBoundary(except_bs);\n            alglib::real_1d_array bndu = upBnd.c_str();\n\n            alglib::minbleiccreate(alg_x, state);\n            alglib::minbleicsetlc(state, c, ct);\n            alglib::minbleicsetbc(state, bndl, bndu);\n            alglib::minbleicsetcond(state, epsg, epsf, epsx, maxits);\n            alglib::minbleicoptimize(state, function1_grad, NULL, &data );\n            alglib::minbleicresults(state, alg_x, rep);\n\n            if ( opt.debug ) {\n                printf(\"%d\\n\", int(rep.terminationtype)); // EXPECTED: 4\n                printf(\"%s\\n\", alg_x.tostring(20).c_str());\n            }\n\n            cl_4 = composite_LogLikelihood( data.base, data.errRateV, alg_x );\n            if ( opt.debug ) cout << \"cl_4: \" << setprecision(20) << cl_4 << endl;\n        }\n        catch ( alglib::ap_error &e ) {\n            cerr << \"catch error: \" << e.msg << \" at seq[\" << new_s << \"] qua[\" << new_q << \"]\" << endl;\n        }\n\n        string st = \"ACGT\";\n        map<char, double> mBaseFrac;\n        for ( int i(0); i != 4; i++ ) {\n            mBaseFrac[ st[i] ] = alg_x[i];\n        }\n\n        for ( auto &p : ntPF ) {\n            ntPF[ p.first ].push_back( mBaseFrac[p.first] );\n        }\n\n        return ntPF;\n    }\n    else if ( ntPF.size() > 4 ) {\n        cerr << \"ntPF contain unknown base\" << endl, exit(1);\n    }\n    else {\n        return ntPF;\n    }\n}\n\n", "meta": {"hexsha": "0f06d84d860132278eb8de2082cf4a0344306af0", "size": 10477, "ext": "cc", "lang": "C++", "max_stars_repo_path": "likelihood.cc", "max_stars_repo_name": "RainyEricYe/lhmut", "max_stars_repo_head_hexsha": "bb8a2f5826a290b9c83527238922b303ee75cb0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "likelihood.cc", "max_issues_repo_name": "RainyEricYe/lhmut", "max_issues_repo_head_hexsha": "bb8a2f5826a290b9c83527238922b303ee75cb0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "likelihood.cc", "max_forks_repo_name": "RainyEricYe/lhmut", "max_forks_repo_head_hexsha": "bb8a2f5826a290b9c83527238922b303ee75cb0b", "max_forks_repo_licenses": ["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.9342857143, "max_line_length": 108, "alphanum_fraction": 0.5023384557, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5900973811694853}}
{"text": "#ifndef FEA_MATERIAL\n#define FEA_MATERIAL\n\n#include <Eigen/Dense>\n#include \"../euclid/Geometry\"\n\nnamespace FEA {\nclass Material {\n\tdouble _young;\n\tdouble _poisson;\n\tpublic:\n\tMaterial(double E=1.,double nu=0.3) : _young(E), _poisson(nu) {};\n\tconst Eigen::Matrix<double,6,6> ConstitutiveLinearIsotropicElastic ();\n};\n\ninline const Eigen::Matrix<double,6,6>\nMaterial::ConstitutiveLinearIsotropicElastic () {\n\tdouble l = ( _young * _poisson ) / ((1. + _poisson ) * (1. - 2. * _poisson ));\n\tdouble g =   _young / (2. * (1. + _poisson ));\n\tdouble G = 2. * g;\n\tEigen::Matrix<double,6,6> C;\n\tC << \tl+G, \tl, \t\tl, \t\t0., \t0., \t0.,\n\t\t\tl, \t\tl+G, \tl, \t\t0., \t0., \t0.,\n\t\t\tl, \t\tl, \t\tl+G, \t0., \t0., \t0.,\n\t\t\t0., \t0., \t0., \tg, \t\t0., \t0.,\n\t\t\t0., \t0., \t0., \t0., \tg, \t\t0.,\n\t\t\t0., \t0., \t0., \t0., \t0., \tg;\n\treturn C;\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "f62f93dd814cc6da4da402a4de1623e2900dec6f", "size": 806, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "physics/Material.hpp", "max_stars_repo_name": "nbrummerstedt/fea", "max_stars_repo_head_hexsha": "cb591311eaa924c4dbd6edc3b64cd0b4a0515e60", "max_stars_repo_licenses": ["MIT"], "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/Material.hpp", "max_issues_repo_name": "nbrummerstedt/fea", "max_issues_repo_head_hexsha": "cb591311eaa924c4dbd6edc3b64cd0b4a0515e60", "max_issues_repo_licenses": ["MIT"], "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/Material.hpp", "max_forks_repo_name": "nbrummerstedt/fea", "max_forks_repo_head_hexsha": "cb591311eaa924c4dbd6edc3b64cd0b4a0515e60", "max_forks_repo_licenses": ["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.7058823529, "max_line_length": 79, "alphanum_fraction": 0.5558312655, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5900839973512585}}
{"text": "/* Boost libs/numeric/odeint/examples/multiprecision/cmp_precision.cpp\n\n Copyright 2009-2013 Karsten Ahnert\n Copyright 2009-2013 Mario Mulansky\n\n example comparing double to multiprecision using Boost.Multiprecision\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/numeric/odeint.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\ntypedef boost::multiprecision::cpp_dec_float_50 mp_50;\n\n/* we solve the simple ODE x' = 3/(2t^2) + x/(2t)\n * with initial condition x(1) = 0.\n * Analytic solution is x(t) = sqrt(t) - 1/t\n */\n\nvoid rhs_m( const mp_50 x , mp_50 &dxdt , const mp_50 t )\n{   // version for multiprecision\n    dxdt = mp_50(3)/(mp_50(2)*t*t) + x/(mp_50(2)*t);\n}\n\nvoid rhs_d( const double x , double &dxdt , const double t )\n{   // version for double precision\n    dxdt = 3.0/(2.0*t*t) + x/(2.0*t);\n}\n\n// state_type = mp_50 = deriv_type = time_type = mp_50\ntypedef runge_kutta4< mp_50 , mp_50 , mp_50 , mp_50 , vector_space_algebra , default_operations , never_resizer > stepper_type_m;\n\ntypedef runge_kutta4< double , double , double , double , vector_space_algebra , default_operations , never_resizer > stepper_type_d;\n\nint main()\n{\n\n    stepper_type_m stepper_m;\n    stepper_type_d stepper_d;\n\n    mp_50 dt_m( 0.5 );\n    double dt_d( 0.5 );\n\n    cout << \"dt\" << '\\t' << \"mp\" << '\\t' << \"double\" << endl;\n    \n    while( dt_m > 1E-20 )\n    {\n\n        mp_50 x_m = 0; //initial value x(1) = 0\n        stepper_m.do_step( rhs_m , x_m , mp_50( 1 ) , dt_m );\n        double x_d = 0;\n        stepper_d.do_step( rhs_d , x_d , 1.0 , dt_d );        \n\n        cout << dt_m << '\\t';\n        cout << abs((x_m - (sqrt(1+dt_m)-mp_50(1)/(1+dt_m)))/x_m) << '\\t' ;\n        cout << abs((x_d - (sqrt(1+dt_d)-mp_50(1)/(1+dt_d)))/x_d) << endl ;\n        dt_m /= 2;\n        dt_d /= 2;\n    }\n}\n", "meta": {"hexsha": "7988dc2a440aecb62c26abd002ac46e7b87ba935", "size": 1989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/multiprecision/cmp_precision.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/multiprecision/cmp_precision.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/multiprecision/cmp_precision.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 28.8260869565, "max_line_length": 133, "alphanum_fraction": 0.6425339367, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5900788253579015}}
{"text": "#include \"multi_cg/multi_cg.hpp\"\n\n#include <Eigen/Core>\n\n#include <iostream>\n\nusing namespace Eigen;\n\ntemplate<typename T>\nstruct BlockVector {\n    Matrix<T, Dynamic, Dynamic> vec;\n\n    typedef T value_type;\n\n    typedef Matrix<T, Dynamic, 1> VectorT;\n\n    BlockVector(Matrix<T, Dynamic, Dynamic> && X) : vec(std::move(X)) {}\n\n    // Make it easy to switch between f32 and f64.\n    template <typename U>\n    BlockVector(BlockVector<U> const &X) : vec(X.vec.template cast<T>()) {}\n\n    template <typename U>\n    void block_add(BlockVector<U> const &X, size_t num) {\n        vec.leftCols(num) += X.vec.leftCols(num).template cast<T>();\n    }\n\n    void block_axpy(std::vector<T> alphas, BlockVector const &X, size_t num) {\n        DiagonalMatrix<T,Dynamic,Dynamic> D = Map<VectorT>(alphas.data(), num).asDiagonal();\n        vec.leftCols(num) += X.vec.leftCols(num) * D;\n    }\n\n    void block_axpy_scatter(std::vector<T> alphas, BlockVector const &X, std::vector<size_t> ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            vec.col(ids[i]) += alphas[i] * X.vec.col(i);\n        }\n    }\n\n    // rhos[i] = dot(X[i], Y[i])\n    void block_dot(BlockVector const &Y, std::vector<T> &rhos, size_t num) {\n        VectorT result = (vec.leftCols(num).transpose() * Y.vec.leftCols(num)).diagonal();\n        VectorT::Map(rhos.data(), result.size()) = result;\n    }\n\n    // X[:, i] = Z[:, i] + alpha[i] * X[:, i] for i < num_unconverged\n    void block_xpby(BlockVector const &Z, std::vector<T> alphas, size_t num) {\n        DiagonalMatrix<T,Dynamic,Dynamic> D = Map<VectorT>(alphas.data(), num).asDiagonal();\n        vec.leftCols(num) = Z.vec.leftCols(num) + vec.leftCols(num) * D;\n    }\n\n    void copy(BlockVector const &X, size_t num) {\n        vec.leftCols(num) = X.vec.leftCols(num);\n    }\n\n    void fill(T val) {\n        vec.fill(val);\n    }\n\n    auto cols() {\n        return vec.cols();\n    }\n\n    void repack(std::vector<size_t> const &ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            auto j = ids[i];\n            if (j != i) {\n                vec.col(i) = vec.col(j);\n            }\n        }\n    }\n};\n\n// This is a linear but special operator A(X)\n// producing AX + XD where D_ii = shifts[i] is a diagonal matrix.\n// So column-wise it performs (A + shift[i])X[:, i]\n// the multiply function basically does a gemv on every column with a different shift\n// so alpha * A(X) + beta * Y.\ntemplate <typename T>\nstruct PosDefMatrixShifted {\n    DiagonalMatrix<T, Dynamic, Dynamic> A;\n    Matrix<T, Dynamic, 1> shifts;\n\n    PosDefMatrixShifted(DiagonalMatrix<T, Dynamic, Dynamic> && A, Matrix<T, Dynamic, 1> && shifts)\n        : A(std::move(A)),\n          shifts(std::move(shifts))\n    {}\n\n    // Make it easy to switch between f32 and f64.\n    template <typename U>\n    PosDefMatrixShifted(PosDefMatrixShifted<U> const &mat)\n        : A(mat.A.diagonal().template cast<T>().asDiagonal()),\n          shifts(mat.shifts.template cast<T>())\n    {}\n\n    void multiply(T alpha, BlockVector<T> const &u, T beta, BlockVector<T> &v, size_t num) {\n        v.vec.leftCols(num) = alpha * A * u.vec.leftCols(num) \n                              + alpha * u.vec.leftCols(num) * shifts.head(num).asDiagonal()\n                              + beta * v.vec.leftCols(num);\n    }\n\n    void repack(std::vector<size_t> const &ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            auto j = ids[i];\n\n            if (j != i)\n                shifts[i] = shifts[j];\n        }\n    }\n};\n\nstruct IdentityPreconditioner {\n    template<typename T>\n    void apply(BlockVector<T> &C, BlockVector<T> const &B) {\n        C = B;\n    }\n    void repack(std::vector<size_t> const &ids) {\n        // nothing to do;\n    }\n};\n\nint main(int argc, char ** argv) {\n    // The general idea is to solve Ax = b in mixed precision\n    // Define the residual r_k = b - Ax_k\n    // and the error e_k := x - x_k\n    // which satisfy Ae_k = Ax - Ax_k = b - Ax_k = r_k.\n    // So we are gonna solve Ae_k = r_k approximately for e_k, and by definition\n    // x = e_k + x_k.\n    // So we compute r_k = b - Ax_k in f64, and then solve Ae_k = r_k\n    // approximately in f32.\n    auto m = argc >= 2 ? std::stoul(argv[1]) : 1000;\n    auto n = argc >= 3 ? std::stoul(argv[2]) : 20;\n    auto outer_iter = argc >= 4 ? std::stoul(argv[3]) : 100;\n    auto inner_iter = argc >= 5 ? std::stoul(argv[4]) : 40;\n\n    if (n > m)\n        throw std::runtime_error(\"matrix order should be >= block size\");\n\n    // Let's stick to this no-op preconditioner.\n    auto P = IdentityPreconditioner{};\n\n    // Setup f64 matrices and vecs\n    auto A_hi = PosDefMatrixShifted<double>{\n        VectorXd::LinSpaced(m, 1, m).asDiagonal(),\n        VectorXd::LinSpaced(n, 1, n)\n    };\n    auto X_hi = BlockVector<double>{MatrixXd::Zero(m, n)};\n    auto B_hi = BlockVector<double>{MatrixXd::Random(m, n)};\n    auto R_hi = BlockVector<double>{MatrixXd::Zero(m, n)};\n    auto U_hi = BlockVector<double>{MatrixXd::Zero(m, n)};\n    auto C_hi = BlockVector<double>{MatrixXd::Zero(m, n)};\n\n    // Setup f32 stuff.\n    auto U_lo = BlockVector<float>{MatrixXf::Zero(m, n)};\n    auto C_lo = BlockVector<float>{MatrixXf::Zero(m, n)};\n    auto E_lo = BlockVector<float>(MatrixXf::Zero(m, n));\n    auto R_lo = BlockVector<float>(MatrixXf::Zero(m, n));\n\n    auto tol = 1e-10;\n\n    std::vector<std::vector<float>> all_resnorms(n);\n\n    for (size_t outer = 0; outer < outer_iter; ++outer) {\n        // A_lo is mutated during multi_cg, so let's just reinitialize.\n        auto A_lo = PosDefMatrixShifted<float>(A_hi);\n        R_hi = B_hi;\n        A_hi.multiply(-1.0, X_hi, 1.0, R_hi, n);\n\n        E_lo.fill(0);\n        R_lo = R_hi;\n        auto iter_resnorms = sirius::cg::multi_cg(\n            A_lo, P,\n            E_lo, R_lo, U_lo, C_lo,\n            inner_iter, tol, true\n        );\n        X_hi.block_add(E_lo, n);\n\n        // Save all the resnorms\n        bool done = true;\n        for (size_t i = 0; i < n; ++i) {\n            done &= iter_resnorms[i].back() <= tol;\n            all_resnorms[i].insert(all_resnorms[i].end(), iter_resnorms[i].begin(), iter_resnorms[i].end());\n        }\n        if (done) break;\n    }\n\n    for (auto r : all_resnorms[0])\n        std::cout << r << '\\n';\n    std::cout << '\\n';\n\n    // Compare to a f64-only run.\n    X_hi.fill(0);\n    R_hi = B_hi;\n    auto resnorms_64 = sirius::cg::multi_cg(\n        A_hi, P,\n        X_hi, R_hi, U_hi, C_hi,\n        m * n, tol, true\n    );\n\n    for (auto r : resnorms_64[0])\n        std::cout << r << '\\n';\n    std::cout << '\\n';\n}", "meta": {"hexsha": "8db645a5520834ab3fc876177d04812d9eec14fa", "size": 6526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/unit_tests/multi_cg/test_multi_cg_multiprecision.cpp", "max_stars_repo_name": "simonpp/SIRIUS", "max_stars_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T08:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T08:48:55.000Z", "max_issues_repo_path": "apps/unit_tests/multi_cg/test_multi_cg_multiprecision.cpp", "max_issues_repo_name": "simonpintarelli/SIRIUS", "max_issues_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "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": "apps/unit_tests/multi_cg/test_multi_cg_multiprecision.cpp", "max_forks_repo_name": "simonpintarelli/SIRIUS", "max_forks_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3069306931, "max_line_length": 108, "alphanum_fraction": 0.5733987128, "num_tokens": 1903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.590008745486346}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_SOLVERS_DDP_HPP_\n#define CROCODDYL_CORE_SOLVERS_DDP_HPP_\n\n#include <Eigen/Cholesky>\n#include <vector>\n\n#include \"crocoddyl/core/solver-base.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Differential Dynamic Programming (DDP) solver\n *\n * The DDP solver computes an optimal trajectory and control commands by iterates running `backwardPass()` and\n * `forwardPass()`. The backward-pass updates locally the quadratic approximation of the problem and computes descent\n * direction. If the warm-start is feasible, then it computes the gaps \\f$\\mathbf{\\bar{f}}_s\\f$ and run a modified\n * Riccati sweep:\n * \\f{eqnarray*}\n *   \\mathbf{Q}_{\\mathbf{x}_k} &=& \\mathbf{l}_{\\mathbf{x}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k} (V_{\\mathbf{x}_{k+1}} +\n * V_{\\mathbf{xx}_{k+1}}\\mathbf{\\bar{f}}_{k+1}),\\\\\n *   \\mathbf{Q}_{\\mathbf{u}_k} &=& \\mathbf{l}_{\\mathbf{u}_k} + \\mathbf{f}^\\top_{\\mathbf{u}_k} (V_{\\mathbf{x}_{k+1}} +\n * V_{\\mathbf{xx}_{k+1}}\\mathbf{\\bar{f}}_{k+1}),\\\\\n *   \\mathbf{Q}_{\\mathbf{xx}_k} &=& \\mathbf{l}_{\\mathbf{xx}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k} V_{\\mathbf{xx}_{k+1}}\n * \\mathbf{f}_{\\mathbf{x}_k},\\\\\n *   \\mathbf{Q}_{\\mathbf{xu}_k} &=& \\mathbf{l}_{\\mathbf{xu}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k} V_{\\mathbf{xx}_{k+1}}\n * \\mathbf{f}_{\\mathbf{u}_k},\\\\\n *   \\mathbf{Q}_{\\mathbf{uu}_k} &=& \\mathbf{l}_{\\mathbf{uu}_k} + \\mathbf{f}^\\top_{\\mathbf{u}_k} V_{\\mathbf{xx}_{k+1}}\n * \\mathbf{f}_{\\mathbf{u}_k}.\n * \\f}\n * Then, the forward-pass rollouts this new policy by integrating the system dynamics along a tuple of optimized\n * control commands \\f$\\mathbf{u}^*_s\\f$, i.e.\n * \\f{eqnarray}\n *   \\mathbf{\\hat{x}}_0 &=& \\mathbf{\\tilde{x}}_0,\\\\\n *   \\mathbf{\\hat{u}}_k &=& \\mathbf{u}_k + \\alpha\\mathbf{k}_k + \\mathbf{K}_k(\\mathbf{\\hat{x}}_k-\\mathbf{x}_k),\\\\\n *   \\mathbf{\\hat{x}}_{k+1} &=& \\mathbf{f}_k(\\mathbf{\\hat{x}}_k,\\mathbf{\\hat{u}}_k).\n * \\f}\n *\n * \\sa `backwardPass()` and `forwardPass()`\n */\nclass SolverDDP : public SolverAbstract {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /**\n   * @brief Initialize the DDP solver\n   *\n   * @param[in] problem  Shooting problem\n   */\n  explicit SolverDDP(boost::shared_ptr<ShootingProblem> problem);\n  virtual ~SolverDDP();\n\n  virtual bool solve(const std::vector<Eigen::VectorXd>& init_xs = DEFAULT_VECTOR,\n                     const std::vector<Eigen::VectorXd>& init_us = DEFAULT_VECTOR, const std::size_t& maxiter = 100,\n                     const bool& is_feasible = false, const double& regInit = 1e-9);\n  virtual void computeDirection(const bool& recalc = true);\n  virtual double tryStep(const double& steplength = 1);\n  virtual double stoppingCriteria();\n  virtual const Eigen::Vector2d& expectedImprovement();\n\n  /**\n   * @brief Update the Jacobian and Hessian of the optimal control problem\n   *\n   * These derivatives are computed around the guess state and control trajectory. These trajectory can be set by using\n   * `setCandidate()`.\n   *\n   * @return  The total cost around the guess trajectory\n   */\n  virtual double calcDiff();\n\n  /**\n   * @brief Run the backward pass (Riccati sweep)\n   *\n   * It assumes that the Jacobian and Hessians of the optimal control problem have been compute (i.e. `calcDiff()`).\n   * The backward pass handles infeasible guess through a modified Riccati sweep:\n   * \\f{eqnarray*}\n   *   \\mathbf{Q}_{\\mathbf{x}_k} &=& \\mathbf{l}_{\\mathbf{x}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k} (V_{\\mathbf{x}_{k+1}}\n   * +\n   * V_{\\mathbf{xx}_{k+1}}\\mathbf{\\bar{f}}_{k+1}),\\\\\n   *   \\mathbf{Q}_{\\mathbf{u}_k} &=& \\mathbf{l}_{\\mathbf{u}_k} + \\mathbf{f}^\\top_{\\mathbf{u}_k} (V_{\\mathbf{x}_{k+1}}\n   * +\n   * V_{\\mathbf{xx}_{k+1}}\\mathbf{\\bar{f}}_{k+1}),\\\\\n   *   \\mathbf{Q}_{\\mathbf{xx}_k} &=& \\mathbf{l}_{\\mathbf{xx}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k}\n   * V_{\\mathbf{xx}_{k+1}}\n   * \\mathbf{f}_{\\mathbf{x}_k},\\\\\n   *   \\mathbf{Q}_{\\mathbf{xu}_k} &=& \\mathbf{l}_{\\mathbf{xu}_k} + \\mathbf{f}^\\top_{\\mathbf{x}_k}\n   * V_{\\mathbf{xx}_{k+1}}\n   * \\mathbf{f}_{\\mathbf{u}_k},\\\\\n   *   \\mathbf{Q}_{\\mathbf{uu}_k} &=& \\mathbf{l}_{\\mathbf{uu}_k} + \\mathbf{f}^\\top_{\\mathbf{u}_k}\n   * V_{\\mathbf{xx}_{k+1}} \\mathbf{f}_{\\mathbf{u}_k}, \\f} where\n   * \\f$\\mathbf{l}_{\\mathbf{x}_k}\\f$,\\f$\\mathbf{l}_{\\mathbf{u}_k}\\f$,\\f$\\mathbf{f}_{\\mathbf{x}_k}\\f$ and\n   * \\f$\\mathbf{f}_{\\mathbf{u}_k}\\f$ are the Jacobians of the cost function and dynamics,\n   * \\f$\\mathbf{l}_{\\mathbf{xx}_k}\\f$,\\f$\\mathbf{l}_{\\mathbf{xu}_k}\\f$ and \\f$\\mathbf{l}_{\\mathbf{uu}_k}\\f$ are the\n   * Hessians of the cost function, \\f$V_{\\mathbf{x}_{k+1}}\\f$ and \\f$V_{\\mathbf{xx}_{k+1}}\\f$ defines the\n   * linear-quadratic approximation of the Value function, and \\f$\\mathbf{\\bar{f}}_{k+1}\\f$ describes the gaps of the\n   * dynamics.\n   */\n  virtual void backwardPass();\n\n  /**\n   * @brief Run the forward pass or rollout\n   *\n   * It rollouts the action model given the computed policy (feedforward terns and feedback gains) by the\n   * `backwardPass()`:\n   * \\f{eqnarray}\n   *   \\mathbf{\\hat{x}}_0 &=& \\mathbf{\\tilde{x}}_0,\\\\\n   *   \\mathbf{\\hat{u}}_k &=& \\mathbf{u}_k + \\alpha\\mathbf{k}_k + \\mathbf{K}_k(\\mathbf{\\hat{x}}_k-\\mathbf{x}_k),\\\\\n   *   \\mathbf{\\hat{x}}_{k+1} &=& \\mathbf{f}_k(\\mathbf{\\hat{x}}_k,\\mathbf{\\hat{u}}_k).\n   * \\f}\n   * We can define different step lengths \\f$\\alpha\\f$.\n   *\n   * @param  stepLength  applied step length (\\f$0\\leq\\alpha\\leq1\\f$)\n   */\n  virtual void forwardPass(const double& stepLength);\n\n  /**\n   * @brief Compute the feedforward and feedback terms using a Cholesky decomposition\n   *\n   * To compute the feedforward \\f$\\mathbf{k}_k\\f$ and feedback \\f$\\mathbf{K}_k\\f$ terms, we use a Cholesky\n   * decomposition to solve \\f$\\mathbf{Q}_{\\mathbf{uu}_k}^{-1}\\f$ term:\n   * \\f{eqnarray}\n   * \\mathbf{k}_k &=& \\mathbf{Q}_{\\mathbf{uu}_k}^{-1}\\mathbf{Q}_{\\mathbf{u}},\\\\\n   * \\mathbf{K}_k &=& \\mathbf{Q}_{\\mathbf{uu}_k}^{-1}\\mathbf{Q}_{\\mathbf{ux}}.\n   * \\f}\n   *\n   * Note that if the Cholesky decomposition fails, then we re-start the backward pass and increase the\n   * state and control regularization values.\n   */\n  virtual void computeGains(const std::size_t& t);\n\n  /**\n   * @brief Increase the state and control regularization values by a `regfactor_` factor\n   */\n  void increaseRegularization();\n\n  /**\n   * @brief Decrease the state and control regularization values by a `regfactor_` factor\n   */\n  void decreaseRegularization();\n\n  /**\n   * @brief Allocate all the internal data needed for the solver\n   */\n  virtual void allocateData();\n\n  /**\n   * @brief Return the regularization factor used to decrease / increase it\n   */\n  const double& get_regfactor() const;\n\n  /**\n   * @brief Return the minimum regularization value\n   */\n  const double& get_regmin() const;\n\n  /**\n   * @brief Return the maximum regularization value\n   */\n  const double& get_regmax() const;\n\n  /**\n   * @brief Return the set of step lengths using by the line-search procedure\n   */\n  const std::vector<double>& get_alphas() const;\n\n  /**\n   * @brief Return the step-length threshold used to decrease regularization\n   */\n  const double& get_th_stepdec() const;\n\n  /**\n   * @brief Return the step-length threshold used to increase regularization\n   */\n  const double& get_th_stepinc() const;\n\n  /**\n   * @brief Return the tolerance of the expected gradient used for testing the step\n   */\n  const double& get_th_grad() const;\n\n  /**\n   * @brief Return the threshold for accepting a gap as non-zero\n   */\n  const double& get_th_gaptol() const;\n  \n  /**\n   * @brief Return the Hessian of the Value function \\f$V_{\\mathbf{xx}_s}\\f$\n   */\n  const std::vector<Eigen::MatrixXd>& get_Vxx() const;\n\n  /**\n   * @brief Return the Hessian of the Value function \\f$V_{\\mathbf{x}_s}\\f$\n   */\n  const std::vector<Eigen::VectorXd>& get_Vx() const;\n\n  /**\n   * @brief Return the Hessian of the Hamiltonian function \\f$\\mathbf{Q}_{\\mathbf{xx}_s}\\f$\n   */\n  const std::vector<Eigen::MatrixXd>& get_Qxx() const;\n\n  /**\n   * @brief Return the Hessian of the Hamiltonian function \\f$\\mathbf{Q}_{\\mathbf{xu}_s}\\f$\n   */\n  const std::vector<Eigen::MatrixXd>& get_Qxu() const;\n\n  /**\n   * @brief Return the Hessian of the Hamiltonian function \\f$\\mathbf{Q}_{\\mathbf{uu}_s}\\f$\n   */\n  const std::vector<Eigen::MatrixXd>& get_Quu() const;\n\n  /**\n   * @brief Return the Jacobian of the Hamiltonian function \\f$\\mathbf{Q}_{\\mathbf{x}_s}\\f$\n   */\n  const std::vector<Eigen::VectorXd>& get_Qx() const;\n\n  /**\n   * @brief Return the Jacobian of the Hamiltonian function \\f$\\mathbf{Q}_{\\mathbf{u}_s}\\f$\n   */\n  const std::vector<Eigen::VectorXd>& get_Qu() const;\n\n  /**\n   * @brief Return the feedback gains \\f$\\mathbf{K}_{s}\\f$\n   */\n  const std::vector<Eigen::MatrixXd>& get_K() const;\n\n  /**\n   * @brief Return the feedforward gains \\f$\\mathbf{k}_{s}\\f$\n   */\n  const std::vector<Eigen::VectorXd>& get_k() const;\n\n  /**\n   * @brief Return the gaps \\f$\\mathbf{\\bar{f}}_{s}\\f$\n   */\n  const std::vector<Eigen::VectorXd>& get_fs() const;\n\n  /**\n   * @brief Modify the regularization factor used to decrease / increase it\n   */\n  void set_regfactor(const double& reg_factor);\n\n  /**\n   * @brief Modify the minimum regularization value\n   */\n  void set_regmin(const double& regmin);\n\n  /**\n   * @brief Modify the maximum regularization value\n   */\n  void set_regmax(const double& regmax);\n\n  /**\n   * @brief Modify the set of step lengths using by the line-search procedure\n   */\n  void set_alphas(const std::vector<double>& alphas);\n\n  /**\n   * @brief Modify the step-length threshold used to decrease regularization\n   */\n  void set_th_stepdec(const double& th_step);\n\n  /**\n   * @brief Modify the step-length threshold used to increase regularization\n   */\n  void set_th_stepinc(const double& th_step);\n\n  /**\n   * @brief Modify the tolerance of the expected gradient used for testing the step\n   */\n  void set_th_grad(const double& th_grad);\n\n  /**\n   * @brief Modify the threshold for accepting a gap as non-zero\n   */\n  void set_th_gaptol(const double& th_gaptol);\n  \n protected:\n  double regfactor_;  //!< Regularization factor used to decrease / increase it\n  double regmin_;     //!< Minimum allowed regularization value\n  double regmax_;     //!< Maximum allowed regularization value\n\n  double cost_try_;                      //!< Total cost computed by line-search procedure\n  std::vector<Eigen::VectorXd> xs_try_;  //!< State trajectory computed by line-search procedure\n  std::vector<Eigen::VectorXd> us_try_;  //!< Control trajectory computed by line-search procedure\n  std::vector<Eigen::VectorXd> dx_;\n\n  // allocate data\n  std::vector<Eigen::MatrixXd> Vxx_;  //!< Hessian of the Value function\n  std::vector<Eigen::VectorXd> Vx_;   //!< Gradient of the Value function\n  std::vector<Eigen::MatrixXd> Qxx_;  //!< Hessian of the Hamiltonian\n  std::vector<Eigen::MatrixXd> Qxu_;  //!< Hessian of the Hamiltonian\n  std::vector<Eigen::MatrixXd> Quu_;  //!< Hessian of the Hamiltonian\n  std::vector<Eigen::VectorXd> Qx_;   //!< Gradient of the Hamiltonian\n  std::vector<Eigen::VectorXd> Qu_;   //!< Gradient of the Hamiltonian\n  std::vector<Eigen::MatrixXd> K_;    //!< Feedback gains\n  std::vector<Eigen::VectorXd> k_;    //!< Feed-forward terms\n  std::vector<Eigen::VectorXd> fs_;   //!< Gaps/defects between shooting nodes\n\n  Eigen::VectorXd xnext_;                              //!< Next state\n  Eigen::MatrixXd FxTVxx_p_;                           //!< fxTVxx_p_\n  std::vector<Eigen::MatrixXd> FuTVxx_p_;              //!< fuTVxx_p_\n  Eigen::VectorXd fTVxx_p_;                            //!< fTVxx_p term\n  std::vector<Eigen::LLT<Eigen::MatrixXd> > Quu_llt_;  //!< Cholesky LLT solver\n  std::vector<Eigen::VectorXd> Quuk_;                  //!< Quuk term\n  std::vector<double> alphas_;                         //!< Set of step lengths using by the line-search procedure\n  double th_grad_;     //!< Tolerance of the expected gradient used for testing the step\n  double th_gaptol_;   //!< Threshold limit to check non-zero gaps\n  double th_stepdec_;  //!< Step-length threshold used to decrease regularization\n  double th_stepinc_;  //!< Step-length threshold used to increase regularization\n  bool was_feasible_;  //!< Label that indicates in the previous iterate was feasible\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_SOLVERS_DDP_HPP_\n", "meta": {"hexsha": "4fa17a32c7594cceedef16a8230dbf9d731e085f", "size": 12540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/solvers/ddp.hpp", "max_stars_repo_name": "nyu-locomotion/crocoddyl", "max_stars_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crocoddyl/core/solvers/ddp.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/solvers/ddp.hpp", "max_forks_repo_name": "nyu-locomotion/crocoddyl", "max_forks_repo_head_hexsha": "b0eeaa5713166d7e6955454b90aedf0fc940baa1", "max_forks_repo_licenses": ["BSD-3-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.9440993789, "max_line_length": 119, "alphanum_fraction": 0.6446570973, "num_tokens": 3885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5899430048774046}}
{"text": "//  (C) Copyright Anton Bikineev 2014\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_RECURRENCE_HPP_\n#define BOOST_MATH_TOOLS_RECURRENCE_HPP_\n\n#include <boost/math/tools/config.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/math/tools/tuple.hpp>\n#include <boost/math/tools/fraction.hpp>\n#include <boost/math/tools/cxx03_warn.hpp>\n#include <boost/math/tools/assert.hpp>\n\nnamespace boost {\n   namespace math {\n      namespace tools {\n         namespace detail{\n\n            //\n            // Function ratios directly from recurrence relations:\n            // H. Shintan, Note on Miller's recurrence algorithm, J. Sci. Hiroshima Univ. Ser. A-I\n            // Math., 29 (1965), pp. 121 - 133.\n            // and:\n            // COMPUTATIONAL ASPECTS OF THREE-TERM RECURRENCE RELATIONS\n            // WALTER GAUTSCHI\n            // SIAM REVIEW Vol. 9, No. 1, January, 1967\n            //\n            template <class Recurrence>\n            struct function_ratio_from_backwards_recurrence_fraction\n            {\n               typedef typename boost::remove_reference<decltype(boost::math::get<0>(std::declval<Recurrence&>()(0)))>::type value_type;\n               typedef std::pair<value_type, value_type> result_type;\n               function_ratio_from_backwards_recurrence_fraction(const Recurrence& r) : r(r), k(0) {}\n\n               result_type operator()()\n               {\n                  value_type a, b, c;\n                  boost::math::tie(a, b, c) = r(k);\n                  ++k;\n                  // an and bn defined as per Gauchi 1.16, not the same\n                  // as the usual continued fraction a' and b's.\n                  value_type bn = a / c;\n                  value_type an = b / c;\n                  return result_type(-bn, an);\n               }\n\n            private:\n               function_ratio_from_backwards_recurrence_fraction operator=(const function_ratio_from_backwards_recurrence_fraction&);\n\n               Recurrence r;\n               int k;\n            };\n\n            template <class R, class T>\n            struct recurrence_reverser\n            {\n               recurrence_reverser(const R& r) : r(r) {}\n               boost::math::tuple<T, T, T> operator()(int i)\n               {\n                  using std::swap;\n                  boost::math::tuple<T, T, T> t = r(-i);\n                  swap(boost::math::get<0>(t), boost::math::get<2>(t));\n                  return t;\n               }\n               R r;\n            };\n\n            template <class Recurrence>\n            struct recurrence_offsetter\n            {\n               typedef decltype(std::declval<Recurrence&>()(0)) result_type;\n               recurrence_offsetter(Recurrence const& rr, int offset) : r(rr), k(offset) {}\n               result_type operator()(int i)\n               {\n                  return r(i + k);\n               }\n            private:\n               Recurrence r;\n               int k;\n            };\n\n\n\n         }  // namespace detail\n\n         //\n         // Given a stable backwards recurrence relation:\n         // a f_n-1 + b f_n + c f_n+1 = 0\n         // returns the ratio f_n / f_n-1\n         //\n         // Recurrence: a functor that returns a tuple of the factors (a,b,c).\n         // factor:     Convergence criteria, should be no less than machine epsilon.\n         // max_iter:   Maximum iterations to use solving the continued fraction.\n         //\n         template <class Recurrence, class T>\n         T function_ratio_from_backwards_recurrence(const Recurrence& r, const T& factor, std::uintmax_t& max_iter)\n         {\n            detail::function_ratio_from_backwards_recurrence_fraction<Recurrence> f(r);\n            return boost::math::tools::continued_fraction_a(f, factor, max_iter);\n         }\n\n         //\n         // Given a stable forwards recurrence relation:\n         // a f_n-1 + b f_n + c f_n+1 = 0\n         // returns the ratio f_n / f_n+1\n         //\n         // Note that in most situations where this would be used, we're relying on\n         // pseudo-convergence, as in most cases f_n will not be minimal as N -> -INF\n         // as long as we reach convergence on the continued-fraction before f_n\n         // switches behaviour, we should be fine.\n         //\n         // Recurrence: a functor that returns a tuple of the factors (a,b,c).\n         // factor:     Convergence criteria, should be no less than machine epsilon.\n         // max_iter:   Maximum iterations to use solving the continued fraction.\n         //\n         template <class Recurrence, class T>\n         T function_ratio_from_forwards_recurrence(const Recurrence& r, const T& factor, std::uintmax_t& max_iter)\n         {\n            boost::math::tools::detail::function_ratio_from_backwards_recurrence_fraction<boost::math::tools::detail::recurrence_reverser<Recurrence, T> > f(r);\n            return boost::math::tools::continued_fraction_a(f, factor, max_iter);\n         }\n\n\n\n         // solves usual recurrence relation for homogeneous\n         // difference equation in stable forward direction\n         // a(n)w(n-1) + b(n)w(n) + c(n)w(n+1) = 0\n         //\n         // Params:\n         // get_coefs: functor returning a tuple, where\n         //            get<0>() is a(n); get<1>() is b(n); get<2>() is c(n);\n         // last_index: index N to be found;\n         // first: w(-1);\n         // second: w(0);\n         //\n         template <class NextCoefs, class T>\n         inline T apply_recurrence_relation_forward(const NextCoefs& get_coefs, unsigned number_of_steps, T first, T second, long long* log_scaling = 0, T* previous = 0)\n         {\n            BOOST_MATH_STD_USING\n            using boost::math::tuple;\n            using boost::math::get;\n\n            T third;\n            T a, b, c;\n\n            for (unsigned k = 0; k < number_of_steps; ++k)\n            {\n               tie(a, b, c) = get_coefs(k);\n\n               if ((log_scaling) &&\n                  ((fabs(tools::max_value<T>() * (c / (a * 2048))) < fabs(first))\n                     || (fabs(tools::max_value<T>() * (c / (b * 2048))) < fabs(second))\n                     || (fabs(tools::min_value<T>() * (c * 2048 / a)) > fabs(first))\n                     || (fabs(tools::min_value<T>() * (c * 2048 / b)) > fabs(second))\n                     ))\n\n               {\n                  // Rescale everything:\n                  long long log_scale = lltrunc(log(fabs(second)));\n                  T scale = exp(T(-log_scale));\n                  second *= scale;\n                  first *= scale;\n                  *log_scaling += log_scale;\n               }\n               // scale each part separately to avoid spurious overflow:\n               third = (a / -c) * first + (b / -c) * second;\n               BOOST_MATH_ASSERT((boost::math::isfinite)(third));\n\n\n               swap(first, second);\n               swap(second, third);\n            }\n\n            if (previous)\n               *previous = first;\n\n            return second;\n         }\n\n         // solves usual recurrence relation for homogeneous\n         // difference equation in stable backward direction\n         // a(n)w(n-1) + b(n)w(n) + c(n)w(n+1) = 0\n         //\n         // Params:\n         // get_coefs: functor returning a tuple, where\n         //            get<0>() is a(n); get<1>() is b(n); get<2>() is c(n);\n         // number_of_steps: index N to be found;\n         // first: w(1);\n         // second: w(0);\n         //\n         template <class T, class NextCoefs>\n         inline T apply_recurrence_relation_backward(const NextCoefs& get_coefs, unsigned number_of_steps, T first, T second, long long* log_scaling = 0, T* previous = 0)\n         {\n            BOOST_MATH_STD_USING\n            using boost::math::tuple;\n            using boost::math::get;\n\n            T next;\n            T a, b, c;\n\n            for (unsigned k = 0; k < number_of_steps; ++k)\n            {\n               tie(a, b, c) = get_coefs(-static_cast<int>(k));\n\n               if ((log_scaling) && \n                  ( (fabs(tools::max_value<T>() * (a / b) / 2048) < fabs(second))\n                     || (fabs(tools::max_value<T>() * (a / c) / 2048) < fabs(first))\n                     || (fabs(tools::min_value<T>() * (a / b) * 2048) > fabs(second))\n                     || (fabs(tools::min_value<T>() * (a / c) * 2048) > fabs(first))\n                  ))\n               {\n                  // Rescale everything:\n                  int log_scale = itrunc(log(fabs(second)));\n                  T scale = exp(T(-log_scale));\n                  second *= scale;\n                  first *= scale;\n                  *log_scaling += log_scale;\n               }\n               // scale each part separately to avoid spurious overflow:\n               next = (b / -a) * second + (c / -a) * first;\n               BOOST_MATH_ASSERT((boost::math::isfinite)(next));\n\n               swap(first, second);\n               swap(second, next);\n            }\n\n            if (previous)\n               *previous = first;\n\n            return second;\n         }\n\n         template <class Recurrence>\n         struct forward_recurrence_iterator\n         {\n            typedef typename boost::remove_reference<decltype(std::get<0>(std::declval<Recurrence&>()(0)))>::type value_type;\n\n            forward_recurrence_iterator(const Recurrence& r, value_type f_n_minus_1, value_type f_n)\n               : f_n_minus_1(f_n_minus_1), f_n(f_n), coef(r), k(0) {}\n\n            forward_recurrence_iterator(const Recurrence& r, value_type f_n)\n               : f_n(f_n), coef(r), k(0)\n            {\n               std::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<boost::math::policies::policy<> >();\n               f_n_minus_1 = f_n * boost::math::tools::function_ratio_from_forwards_recurrence(detail::recurrence_offsetter<Recurrence>(r, -1), value_type(boost::math::tools::epsilon<value_type>() * 2), max_iter);\n               boost::math::policies::check_series_iterations<value_type>(\"forward_recurrence_iterator<>::forward_recurrence_iterator\", max_iter, boost::math::policies::policy<>());\n            }\n\n            forward_recurrence_iterator& operator++()\n            {\n               using std::swap;\n               value_type a, b, c;\n               boost::math::tie(a, b, c) = coef(k);\n               value_type f_n_plus_1 = a * f_n_minus_1 / -c + b * f_n / -c;\n               swap(f_n_minus_1, f_n);\n               swap(f_n, f_n_plus_1);\n               ++k;\n               return *this;\n            }\n\n            forward_recurrence_iterator operator++(int)\n            {\n               forward_recurrence_iterator t(*this);\n               ++(*this);\n               return t;\n            }\n\n            value_type operator*() { return f_n; }\n\n            value_type f_n_minus_1, f_n;\n            Recurrence coef;\n            int k;\n         };\n\n         template <class Recurrence>\n         struct backward_recurrence_iterator\n         {\n            typedef typename boost::remove_reference<decltype(std::get<0>(std::declval<Recurrence&>()(0)))>::type value_type;\n\n            backward_recurrence_iterator(const Recurrence& r, value_type f_n_plus_1, value_type f_n)\n               : f_n_plus_1(f_n_plus_1), f_n(f_n), coef(r), k(0) {}\n\n            backward_recurrence_iterator(const Recurrence& r, value_type f_n)\n               : f_n(f_n), coef(r), k(0)\n            {\n               std::uintmax_t max_iter = boost::math::policies::get_max_series_iterations<boost::math::policies::policy<> >();\n               f_n_plus_1 = f_n * boost::math::tools::function_ratio_from_backwards_recurrence(detail::recurrence_offsetter<Recurrence>(r, 1), value_type(boost::math::tools::epsilon<value_type>() * 2), max_iter);\n               boost::math::policies::check_series_iterations<value_type>(\"backward_recurrence_iterator<>::backward_recurrence_iterator\", max_iter, boost::math::policies::policy<>());\n            }\n\n            backward_recurrence_iterator& operator++()\n            {\n               using std::swap;\n               value_type a, b, c;\n               boost::math::tie(a, b, c) = coef(k);\n               value_type f_n_minus_1 = c * f_n_plus_1 / -a + b * f_n / -a;\n               swap(f_n_plus_1, f_n);\n               swap(f_n, f_n_minus_1);\n               --k;\n               return *this;\n            }\n\n            backward_recurrence_iterator operator++(int)\n            {\n               backward_recurrence_iterator t(*this);\n               ++(*this);\n               return t;\n            }\n\n            value_type operator*() { return f_n; }\n\n            value_type f_n_plus_1, f_n;\n            Recurrence coef;\n            int k;\n         };\n\n      }\n   }\n} // namespaces\n\n#endif // BOOST_MATH_TOOLS_RECURRENCE_HPP_\n", "meta": {"hexsha": "9c6badac5d20c8a332530f412080bab599edec8e", "size": 12876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/recurrence.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/tools/recurrence.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/tools/recurrence.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 39.7407407407, "max_line_length": 213, "alphanum_fraction": 0.5290462877, "num_tokens": 3011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.589938368600882}}
{"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 StrictGaussianClassifier 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 \"strict_gaussian_classifier.h\"\n\n// Other Dependencies\n#include <cassert>\n#include <iostream>\n#include <fstream>\n\n#include \"bayes_classifier.h\"\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/**\nStrictGaussianClassifier\n\nDescription\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*/\nStrictGaussianClassifier::StrictGaussianClassifier()\n{\n  // variables\n  int ndx = 0;\n  Eigen::Matrix2d temp_matrix;\n    temp_matrix << 1, 0,\n                   0, 1;\n\n  // initialize all members\n  class_name_ = \"Give me a name!\";\n  mean_vector_ << 1, 1;\n  set_covariance( temp_matrix );\n  decision_threshold_ = 0.5;\n\n  // no return - constructor\n}\n\n\nStrictGaussianClassifier::StrictGaussianClassifier(\n    const StrictGaussianClassifier& other )\n{\n  // no return - copy constructor\n}\n\n\nStrictGaussianClassifier& StrictGaussianClassifier::operator=(\n    const StrictGaussianClassifier& other )\n{\n  // return *this\n  return *this;\n}\n\n\nStrictGaussianClassifier::~StrictGaussianClassifier()\n{\n  // currently nothing to destruct\n\n  // no return - destructor\n}\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   MUTATORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\nvoid StrictGaussianClassifier::clear()\n{\n  // no return - void\n}\n\n\nvoid StrictGaussianClassifier::set_mean( const Eigen::Vector2d& new_mean_vector )\n{\n  // set the appropriate mean vector\n  mean_vector_ = new_mean_vector;\n\n  // no return - void\n}\n\n\nvoid StrictGaussianClassifier::set_mean( const vector<DataItem>& data )\n{\n  // variables\n  int i = 0;\n  int num_data = 0;\n\n  // reset the mean vector\n  mean_vector_( 0 ) = 0;\n  mean_vector_( 1 ) = 0;\n\n  // sum the values of the features over all of the data\n  for( i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sum\n      mean_vector_( 0 ) += data[i].feature_vector( 0 );\n      mean_vector_( 1 ) += data[i].feature_vector( 1 );\n      num_data++;\n    }\n  }\n\n  // scale the data\n  mean_vector_( 0 ) /= num_data;\n  mean_vector_( 1 ) /= num_data;\n\n  // no return - void\n}\n\n\nvoid StrictGaussianClassifier::set_covariance(\n    const Eigen::Matrix2d& new_covariance_matrix )\n{\n  // set the appropriate covariance matrix\n  covariance_matrix_ = new_covariance_matrix;\n\n  // update the other covariance related members\n  inverse_covariance_matrix_ = covariance_matrix_.inverse();\n  covariance_determinant_ = covariance_matrix_.determinant();\n\n  // no return - void\n}\n\n\nvoid StrictGaussianClassifier::set_covariance( const vector<DataItem>& data,\n                                      const Eigen::Vector2d& mean )\n{\n  // variables\n  int i = 0;\n  int num_data = 0;\n\n  // reset the covariance matrix\n  covariance_matrix_ << 0, 0,\n                        0, 0;\n\n\n  // sum the values of the features over all of the data\n  for( num_data = 0, i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sums\n      covariance_matrix_( 0, 0 ) +=\n          ( data[i].feature_vector( 0 ) - mean( 0 ) ) *\n          ( data[i].feature_vector( 0 ) - mean( 0 ) );\n      covariance_matrix_( 1, 0 ) +=\n          ( data[i].feature_vector( 1 ) - mean( 1 ) ) *\n          ( data[i].feature_vector( 0 ) - mean( 0 ) );\n      covariance_matrix_( 1, 1 ) +=\n          ( data[i].feature_vector( 1 ) - mean( 1 ) ) *\n          ( data[i].feature_vector( 1 ) - mean( 1 ) );\n      num_data++;\n    }\n  }\n\n  // set the covariance above the diagonal\n  covariance_matrix_( 0, 1 ) = covariance_matrix_( 1, 0 );\n\n  // scale the result\n  covariance_matrix_ = ( 1.0 / ( (double) num_data - 1.0) ) *\n                       covariance_matrix_;\n\n  // update the other covariance related members\n  inverse_covariance_matrix_ = covariance_matrix_.inverse();\n  covariance_determinant_ = covariance_matrix_.determinant();\n\n  // no return - void\n}\n\n\nvoid StrictGaussianClassifier::set_class_name( const string& new_name )\n{\n  // set the class name member\n  class_name_ = new_name;\n}\n\n\nvoid StrictGaussianClassifier::set_decision_threshold(\n    const double new_threshold )\n{\n  // set the class decision threshold member\n  decision_threshold_ = new_threshold;\n}\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   ACCESSORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\nEigen::Vector2d StrictGaussianClassifier::mean_vector() const\n{\n  // return the prior mean feature vector of the class\n  return mean_vector_;\n}\n\n\nEigen::Matrix2d StrictGaussianClassifier::covariance_matrix() const\n{\n  // return the covariance matrix of the class\n  return covariance_matrix_;\n}\n\n\nEigen::Matrix2d StrictGaussianClassifier::inverse_covariance_matrix() const\n{\n  // return the inverse of the covariance matrix of the class\n  return inverse_covariance_matrix_;\n}\n\n\ndouble StrictGaussianClassifier::covariance_determinant() const\n{\n  // return the determinant of the covariance matrix of the class\n  return covariance_determinant_;\n}\n\n\nstring StrictGaussianClassifier::class_name() const\n{\n  // return the class name\n  return class_name_;\n}\n\ndouble StrictGaussianClassifier::decision_threshold() const\n{\n  // return the decision threshold value\n  return decision_threshold_;\n}\n\nvoid StrictGaussianClassifier::reportClassifierInfo()\n{\n  // variables\n    // none\n\n  // report the class name\n  cout << \"Classifier for class \" << class_name_ << endl;\n\n  // report the trained mean\n  printf( \"The training data mean is:\\r\\n\" );\n  cout << mean_vector_ << endl;\n\n  // report the trained covariance\n  printf( \"The training data covariance is:\\r\\n\" );\n  cout << covariance_matrix_ << endl;\n\n  // no return - void\n}\n\n\nbool StrictGaussianClassifier::objectIsInThisClass( Eigen::Vector2d& test_vector )\n{\n  // return the decision that the object is in this class\n  return ( getGaussianProbability( test_vector ) > decision_threshold_ );\n}\n\n\ndouble StrictGaussianClassifier::getGaussianProbability(\n    Eigen::Vector2d& test_vector )\n{\n  // variables\n  double gaussian_probability_density = 0;\n  double fractional_part = 1;\n  double exponent_part = 0;\n  Eigen::Vector2d test_mean_difference;\n  Eigen::Vector2d intermediate_vector;\n\n/*\n    DON'T KNOW WHY, BUT THE SCALE FACTOR IS RUINING THINGS - IS DATA ALREADY\n    NORMALIZED/SCALED SOMEHOW? \n\n  // compute the normalizing/scale factor\n  fractional_part = sqrt( 2 * PI );\n  fractional_part = pow( fractional_part, DIMENSIONALITY );\n  fractional_part *= sqrt( covariance_determinant_ );\n  fractional_part = pow( fractional_part, -1 );\n*/\n\n  // compute the expontent part\n  test_mean_difference = test_vector - mean_vector_;\n\n  intermediate_vector = test_mean_difference.transpose() *\n                        inverse_covariance_matrix_;\n  exponent_part = -0.5 * ( intermediate_vector.dot( test_mean_difference ) );\n\n  // compute the whole thing\n  gaussian_probability_density = fractional_part * exp( exponent_part );\n\n  // return the result\n  return gaussian_probability_density;\n}\n\n\n", "meta": {"hexsha": "2cfbad8c16b2d513d66bfe322b336106324706f1", "size": 8351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_2/strict_gaussian_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_2/strict_gaussian_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_2/strict_gaussian_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": 25.4603658537, "max_line_length": 82, "alphanum_fraction": 0.6055562208, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5899383581409268}}
{"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 <mpi.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\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;\nstatic void get_lcm_sub(GF2X& lcmpoly, dSFMText& dsfmt);\n\nvoid calc_minimal(GF2X& minimal, int maxdegree, w128_t outseq[], int bitpos)\n{\n    uint64_t mask;\n    vec_GF2 seq;\n    seq.SetLength(2 * maxdegree);\n    int idx;\n    if (bitpos >= 64) {\n\tidx = 1;\n\tmask = UINT64_C(1) << (bitpos - 64);\n    } else {\n\tidx = 0;\n\tmask = UINT64_C(1) << bitpos;\n    }\n    for (int i = 0; i < 2 * maxdegree; i++) {\n\tif (outseq[i].u[idx] & mask) {\n\t    seq[i] = 1;\n\t} else {\n\t    seq[i] = 0;\n\t}\n    }\n    MinPolySeq(minimal, seq, maxdegree);\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(int rank, int num_process, GF2X& lcmpoly, dSFMText& dsfmt) {\n    int maxdegree = dsfmt.get_mamaxdegree();\n    dsfmt.seeding(1234);\n    get_lcm_sub(lcmpoly, dsfmt);\n    int unit = maxdegree / num_process;\n    int start = rank * num_process;\n    for(int i = start; i < start + unit; i++) {\n\tdsfmt.init_basis(i);\n\tget_lcm_sub(lcmpoly, dsfmt);\n    }\n}\n\nstatic void get_lcm_sub(GF2X& lcmpoly, dSFMText& dsfmt) {\n    GF2X tmp;\n    int mamaxdegree = dsfmt.get_mamaxdegree();\n    w128_t out_seq[2 * mamaxdegree];\n    int i, bitpos;\n\n    for (int i = 0; i < 2 * mamaxdegree; i++) {\n\tout_seq[i] = dsfmt.next();\n    }\n\n    GF2X minimal;\n    for (bitpos = 0; bitpos < 128; bitpos++) {\n\tcalc_minimal(minimal, mamaxdegree, out_seq, bitpos);\n\tLCM(tmp, lcmpoly, minimal);\n\tlcmpoly = tmp;\n    }\n}\n\n#if defined(IRRE_CHECK)\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#endif\n\nint main(int argc, char *argv[]) {\n    int rank;\n    int num_process;\n    int MPI_Status status;\n    MPI_Init(&argc, &argv);\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    MPI_Comm_size(MPI_COMM_WORLD, &num_process);\n    if (argc < 6) {\n\tcout << argv[0] << \" mexp pos1 sl1 mask1 mask2\" << endl;\n\tMPI_Finalize();\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    stringstream ss;\n    ss << \"lcm.\" << dec << mexp << \".\" << rank << \".txt\";\n    string fname;\n    ss >> fname;\n    //ofstream fout(\"/tmp/results.txt\", ios::trunc );\n    ofstream fout(fname.c_str());\n\n    dSFMText dsfmt(mexp, pos1, sl1, mask[0], mask[1]);\n    GF2X characteristic(0,1);\n    get_lcm(rank, num_process, characteristic, dsfmt);\n    GF2X work;\n    work = characteristic;\n#if defined(IRRE_CHECK)\n    if (!has_large_irreducible(characteristic, mexp)) {\n        fout << \"error? does not have large irreducible\" << endl;\n\tMPI_Finalize();\n        return -1;\n    }\n#endif\n    string x;\n    polytostring(x, work);\n    fout << \"#\" << dec << mexp;\n    fout << \",\" << dec << pos1;\n    fout << \",\" << dec << sl1;\n    fout << \",\" << hex << mask[0];\n    fout << \",\" << hex << mask[1];\n    fout << dec << endl;\n    fout << x << endl;\n    fout << dec << flush;\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "4e2d0045561b52ae77fd219d4d721bc61862cd42", "size": 4265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jump/calc-characteristic-mpi.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-mpi.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-mpi.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.5635359116, "max_line_length": 76, "alphanum_fraction": 0.5983587339, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5898398395682396}}
{"text": "#include <adept.h>\n#include <benchmark/benchmark.h>\n#include <ceres/autodiff_cost_function.h>\n#include <game/vsr/cga_op.h>\n#include <glog/logging.h>\n#include <hep/ga.hpp>\n#include <vahlen/vahlen.h>\n\nusing namespace vsr::cga;\n\nadept::Stack g_stack;\n\ndouble g_vector[3] = {1.0, 2.0, 3.0};\ndouble g_bivector[3] = {1.0, 2.0, 3.0};\ndouble g_motor[8] = {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\ndouble g_point[5] = {1.0, 2.0, 3.0, 1.0, 7.0};\ndouble g_point_spin_motor[5];\ndouble g_vec_ip_biv[3] = {0.0, 0.0, 0.0};\n\ntemplate <typename T>\nvoid InnerProductVectorBivector(const T *vec, const T *biv, T *res) {\n  Vector<T> vector(vec);\n  Bivector<T> bivector(biv);\n  Vector<T> result = vector <= bivector;\n  for (int i = 0; i < 3; ++i)\n    res[i] = result[i];\n}\n\nstruct InnerProductVectorBivectorFunctor {\n  template <typename T>\n  bool operator()(const T *vec, const T *biv, T *res) const {\n    InnerProductVectorBivector(vec, biv, res);\n    return true;\n  }\n};\n\ntemplate <typename T>\nvoid InnerProductVectorBivector2(const T *a, const T *b, T *res) {\n  res[0] = -a[2] * b[1] - a[1] * b[0];\n  res[1] = -a[2] * b[2] + a[0] * b[0];\n  res[2] = a[1] * b[2] + a[0] * b[1];\n}\n\nstruct InnerProductVectorBivectorFunctor2 {\n  template <typename T>\n  bool operator()(const T *vec, const T *biv, T *res) const {\n    InnerProductVectorBivector2(vec, biv, res);\n    return true;\n  }\n};\n\ntemplate <typename T>\nvoid GaalopCalculateMotorSpinPoint(const T m1, const T m2, const T m3,\n                                   const T m4, const T m5, const T m6,\n                                   const T m7, const T m8, const T p1,\n                                   const T p2, const T p3, const T p4,\n                                   const T p5, T *q) {\n\n  q[0] = ((-(2.0 * m1 * m5)) - 2.0 * m2 * m6 - 2.0 * m3 * m7 - 2.0 * m4 * m8) *\n             p4 +\n         (2.0 * m1 * m3 + 2.0 * m2 * m4) * p3 +\n         (2.0 * m1 * m2 - 2.0 * m3 * m4) * p2 +\n         (m1 * m1 - m2 * m2 - m3 * m3 + m4 * m4) * p1; // e1\n  q[1] = (2.0 * m2 * m5 - 2.0 * m1 * m6 - 2.0 * m4 * m7 + 2.0 * m3 * m8) * p4 +\n         (2.0 * m1 * m4 - 2.0 * m2 * m3) * p3 +\n         ((m1 * m1 - m2 * m2 + m3 * m3) - m4 * m4) * p2 +\n         ((-(2.0 * m1 * m2)) - 2.0 * m3 * m4) * p1; // e2\n  q[2] =\n      ((2.0 * m3 * m5 + 2.0 * m4 * m6) - 2.0 * m1 * m7 - 2.0 * m2 * m8) * p4 +\n      ((m1 * m1 + m2 * m2) - m3 * m3 - m4 * m4) * p3 +\n      ((-(2.0 * m2 * m3)) - 2.0 * m1 * m4) * p2 +\n      (2.0 * m2 * m4 - 2.0 * m1 * m3) * p1;            // e3\n  q[3] = (m4 * m4 + m3 * m3 + m2 * m2 + m1 * m1) * p4; // e0\n  q[4] =\n      (m1 * m1 + m2 * m2 + m3 * m3 + m4 * m4) * p5 +\n      (2.0 * m5 * m5 + 2.0 * m6 * m6 + 2.0 * m7 * m7 + 2.0 * m8 * m8) * p4 +\n      ((-(2.0 * m3 * m5)) - 2.0 * m4 * m6 - 2.0 * m1 * m7 - 2.0 * m2 * m8) *\n          p3 +\n      ((-(2.0 * m2 * m5)) - 2.0 * m1 * m6 + 2.0 * m4 * m7 + 2.0 * m3 * m8) *\n          p2 +\n      (((-(2.0 * m1 * m5)) + 2.0 * m2 * m6 + 2.0 * m3 * m7) - 2.0 * m4 * m8) *\n          p1; // einf\n}\n\ntemplate <typename T>\nvoid GaalopMotorSpinPoint(const T *mot, const T *pnt, T *res) {\n  GaalopCalculateMotorSpinPoint(mot[0], mot[1], mot[2], mot[3], mot[4], mot[5],\n                                mot[6], mot[7], pnt[0], pnt[1], pnt[2], pnt[3],\n                                pnt[4], res);\n}\n\nstruct GaalopMotorSpinPointFunctor {\n  template <typename T>\n  bool operator()(const T *mot, const T *pnt, T *res) const {\n    GaalopMotorSpinPoint(mot, pnt, res);\n    return true;\n  }\n};\n\ntemplate <typename T>\nvoid VahlenMotorSpinPoint(const T *mot, const T *pnt, T *res) {\n  using Mat = vahlen::Matrix<T>;\n  Mat motor = vahlen::Motor<T>(mot);\n  Mat point = vahlen::Point<T>(pnt);\n  Mat result = motor * point * vahlen::Reverse(motor);\n}\n\nstruct VahlenMotorSpinPointFunctor {\n  template <typename T>\n  bool operator()(const T *mot, const T *pnt, T *res) const {\n    VahlenMotorSpinPoint(mot, pnt, res);\n    return true;\n  }\n};\n\ntemplate <typename T> void MotorSpinPoint(const T *mot, const T *pnt, T *res) {\n  Motor<T> motor(mot);\n  Point<T> point(pnt);\n  Point<T> result = point.spin(motor);\n  for (int i = 0; i < 5; ++i)\n    res[i] = result[i];\n}\n\nstruct MotorSpinPointFunctor {\n  template <typename T>\n  bool operator()(const T *mot, const T *pnt, T *res) const {\n    MotorSpinPoint(mot, pnt, res);\n    return true;\n  }\n};\n\ntemplate <typename T> void RotorSpinPoint(const T *rot, const T *pnt, T *res) {\n  Rotor<T> rotor(rot);\n  Vector<T> point(pnt);\n  Vector<T> result = point.spin(rotor);\n  for (int i = 0; i < 3; ++i)\n    res[i] = result[i];\n}\n\nstruct RotorSpinPointFunctor {\n  template <typename T>\n  bool operator()(const T *rot, const T *pnt, T *res) const {\n    RotorSpinPoint(rot, pnt, res);\n    return true;\n  }\n};\n\nstatic void BM_InnerProductVectorBivector(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    InnerProductVectorBivector(g_vector, g_bivector, g_vec_ip_biv);\n  }\n}\n\nstatic void BM_InnerProductVectorBivector2(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    InnerProductVectorBivector2(g_vector, g_bivector, g_vec_ip_biv);\n  }\n}\n\nstatic void BM_AdeptJacobianForward(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    adept::adouble vector[3];\n    adept::set_values(vector, 3, g_vector);\n    adept::adouble bivector[3];\n    adept::set_values(bivector, 3, g_bivector);\n    g_stack.new_recording();\n    adept::adouble vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    InnerProductVectorBivector(vector, bivector, vec_ip_biv);\n\n    g_stack.independent(vector, 3);\n    g_stack.dependent(vec_ip_biv, 3);\n    g_stack.jacobian_forward(jac);\n  }\n}\n\nstatic void BM_AdeptJacobianForward2(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    adept::adouble vector[3];\n    adept::set_values(vector, 3, g_vector);\n    adept::adouble bivector[3];\n    adept::set_values(bivector, 3, g_bivector);\n    g_stack.new_recording();\n    adept::adouble vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    InnerProductVectorBivector2(vector, bivector, vec_ip_biv);\n\n    g_stack.independent(vector, 3);\n    g_stack.dependent(vec_ip_biv, 3);\n    g_stack.jacobian_forward(jac);\n  }\n}\n\nstatic void BM_AdeptJacobianReverse(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    adept::adouble vector[3];\n    adept::set_values(vector, 3, g_vector);\n    adept::adouble bivector[3];\n    adept::set_values(bivector, 3, g_bivector);\n    g_stack.new_recording();\n    adept::adouble vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    InnerProductVectorBivector(vector, bivector, vec_ip_biv);\n\n    g_stack.independent(vector, 3);\n    g_stack.dependent(vec_ip_biv, 3);\n    g_stack.jacobian_reverse(jac);\n  }\n}\n\nstatic void BM_AdeptJacobianReverse2(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    adept::adouble vector[3];\n    adept::set_values(vector, 3, g_vector);\n    adept::adouble bivector[3];\n    adept::set_values(bivector, 3, g_bivector);\n    g_stack.new_recording();\n    adept::adouble vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    InnerProductVectorBivector2(vector, bivector, vec_ip_biv);\n\n    g_stack.independent(vector, 3);\n    g_stack.dependent(vec_ip_biv, 3);\n    g_stack.jacobian_reverse(jac);\n  }\n}\n\nstatic void BM_CeresJacobian(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    double vector[3] = {1.0, 2.0, 3.0};\n    double bivector[3] = {1.0, 2.0, 3.0};\n    double vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    const double *parameters[2] = {&vector[0], &bivector[0]};\n    double *jacobians[2] = {jac, nullptr};\n\n    ceres::AutoDiffCostFunction<InnerProductVectorBivectorFunctor, 3, 3, 3>(\n        new InnerProductVectorBivectorFunctor())\n        .Evaluate(parameters, &vec_ip_biv[0], jacobians);\n  }\n}\n\nstatic void BM_CeresJacobian2(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[9];\n    double vector[3] = {1.0, 2.0, 3.0};\n    double bivector[3] = {1.0, 2.0, 3.0};\n    double vec_ip_biv[3] = {0.0, 0.0, 0.0};\n    const double *parameters[2] = {&vector[0], &bivector[0]};\n    double *jacobians[2] = {jac, nullptr};\n\n    ceres::AutoDiffCostFunction<InnerProductVectorBivectorFunctor2, 3, 3, 3>(\n        new InnerProductVectorBivectorFunctor2())\n        .Evaluate(parameters, &vec_ip_biv[0], jacobians);\n  }\n}\n\nstatic void BM_MotorSpinPoint(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    MotorSpinPoint(g_motor, g_point, g_point_spin_motor);\n  }\n}\n\nstatic void BM_VahlenMotorSpinPoint(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    VahlenMotorSpinPoint(g_motor, g_point, g_point_spin_motor);\n  }\n}\n\nstatic void BM_GaalopMotorSpinPoint(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    GaalopMotorSpinPoint(g_motor, g_point, g_point_spin_motor);\n  }\n}\n\nstatic void BM_AdeptMotorSpinPointJacobianReverse(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[5 * 8];\n    adept::adouble motor[8];\n    adept::set_values(motor, 8, g_motor);\n    adept::adouble point[5];\n    adept::set_values(point, 5, g_point);\n    g_stack.new_recording();\n    adept::adouble res[5] = {0.0, 0.0, 0.0, 0.0, 0.0};\n    MotorSpinPoint(motor, point, res);\n\n    g_stack.independent(motor, 8);\n    g_stack.dependent(res, 5);\n    g_stack.jacobian_reverse(jac);\n  }\n}\n\nstatic void BM_AdeptMotorSpinPointJacobianForward(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[5 * 8];\n    adept::adouble motor[8];\n    adept::set_values(motor, 8, g_motor);\n    adept::adouble point[5];\n    adept::set_values(point, 5, g_point);\n    g_stack.new_recording();\n    adept::adouble res[5] = {0.0, 0.0, 0.0, 0.0, 0.0};\n    MotorSpinPoint(motor, point, res);\n\n    g_stack.independent(motor, 8);\n    g_stack.dependent(res, 5);\n    g_stack.jacobian_forward(jac);\n  }\n}\n\nstatic void BM_AdeptRotorSpinPointJacobianForward(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[3 * 4];\n    adept::adouble motor[4];\n    adept::set_values(motor, 4, g_motor);\n    adept::adouble point[3];\n    adept::set_values(point, 3, g_point);\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    RotorSpinPoint(motor, point, res);\n\n    g_stack.independent(motor, 4);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstatic void BM_CeresMotorSpinPointJacobian(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[5 * 8];\n    const double *parameters[2] = {&g_motor[0], &g_point[0]};\n    double *jacobians[2] = {jac, nullptr};\n\n    ceres::AutoDiffCostFunction<MotorSpinPointFunctor, 5, 8, 5>(\n        new MotorSpinPointFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nstatic void BM_CeresGaalopMotorSpinPointJacobian(benchmark::State &state) {\n  while (state.KeepRunning()) {\n    double jac[5 * 8];\n    const double *parameters[2] = {&g_motor[0], &g_point[0]};\n    double *jacobians[2] = {jac, nullptr};\n\n    ceres::AutoDiffCostFunction<GaalopMotorSpinPointFunctor, 5, 8, 5>(\n        new GaalopMotorSpinPointFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nstatic void BM_CeresRotorSpinPointJacobian(benchmark::State &state) {\n  double jac[3 * 4];\n  const double *parameters[2] = {&g_motor[0], &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<RotorSpinPointFunctor, 3, 4, 3>(\n        new RotorSpinPointFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\ntemplate <typename T> using Matrix4 = Eigen::Matrix<T, 4, 4>;\n\ntemplate <typename T> inline static Matrix4<T> s() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1), T(0),\n      T(0), T(0), T(0), T(1);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e1() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0),\n      T(1), T(0), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e2() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(1), T(0), T(0), T(0),\n      T(0), T(-1), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e3() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(0),\n      T(0), T(0), T(0), T(-1);\n  return m;\n}\n\nstruct DiffRotorMatrixFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    Matrix4<T> rotor =\n        cos(T(0.5) * th[0]) * s<T>() - sin(T(0.5) * th[0]) * e1<T>() * e2<T>();\n    Matrix4<T> rotor_inv =\n        cos(T(0.5) * th[0]) * s<T>() + sin(T(0.5) * th[0]) * e1<T>() * e2<T>();\n    Matrix4<T> vec_a = a[0] * e1<T>() + a[1] * e2<T>() + a[2] * e3<T>();\n    Matrix4<T> vec_b = rotor * vec_a * rotor_inv;\n    b[0] = vec_b(0, 3); // e1\n    b[1] = vec_b(0, 2); // e2\n    b[2] = vec_b(0, 0); // e3\n    return true;\n  }\n};\n\nstatic void BM_CeresRotorMatrixJacobian(benchmark::State &state) {\n  double theta = 0.5;\n  double jac[3];\n  const double *parameters[2] = {&theta, &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<DiffRotorMatrixFunctor, 3, 1, 3>(\n        new DiffRotorMatrixFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nstruct DiffRotorVersorFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    Rotor<T> rotor{cos(T(0.5) * th[0]), -sin(T(0.5) * th[0]), T(0.0), T(0.0)};\n    Vector<T> vec_a{a[0], a[1], a[2]};\n    Vector<T> vec_b = vec_a.spin(rotor);\n    for (int i = 0; i < 3; ++i)\n      b[i] = vec_b[i];\n    return true;\n  }\n};\n\nstatic void BM_CeresRotorVersorJacobian(benchmark::State &state) {\n  double theta = 0.5;\n  double jac[3];\n  const double *parameters[2] = {&theta, &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<DiffRotorVersorFunctor, 3, 1, 3>(\n        new DiffRotorVersorFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nstruct DiffRotorHepGAFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    using Algebra = hep::algebra<T, 3, 0>;\n    using Rotor = hep::multi_vector<Algebra, hep::list<0, 3, 5, 6>>;\n    using Vector = hep::multi_vector<Algebra, hep::list<1, 2, 4>>;\n    Rotor rotor{cos(T(0.5) * th[0]), -sin(T(0.5) * th[0]), T(0.0), T(0.0)};\n    Vector pnt_a{a[0], a[1], a[2]};\n    Vector pnt_b = hep::grade<1>(rotor * pnt_a * ~rotor);\n    for (int i = 0; i < 3; ++i)\n      b[i] = pnt_b[i];\n    return true;\n  }\n};\n\nstatic void BM_CeresRotorHepGAJacobian(benchmark::State &state) {\n  double theta = 0.5;\n  double jac[3];\n  const double *parameters[2] = {&theta, &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<DiffRotorHepGAFunctor, 3, 1, 3>(\n        new DiffRotorHepGAFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nstatic void BM_AdeptRotorHepGAJacobianForward(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorHepGAFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_forward(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorHepGAJacobianReverse(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorHepGAFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorVersorJacobianForward(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorVersorFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_forward(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorVersorJacobianReverse(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorVersorFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorMatrixJacobianForward(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorMatrixFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_forward(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorMatrixJacobianReverse(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorMatrixFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstruct DiffRotorHandFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    T st = sin(th[0] / 2.0);\n    T ct = cos(th[0] / 2.0);\n    T stst = st * st;\n    T ctct = ct * ct;\n    T ctst = ct * st;\n    b[0] = (-(a[0] * stst)) - 2.0 * a[1] * ctst + a[0] * ctct; // e1\n    b[1] = (-(a[1] * stst)) + 2.0 * a[0] * ctst + a[1] * ctct; // e2\n    b[2] = a[2] * stst + a[2] * ctct;                          // e3\n    return true;\n  }\n};\n\nstruct DiffRotorGaalopFunctor {\n  template <typename T> bool operator()(const T *th, const T *a, T *b) const {\n    b[0] = (-(a[0] * sin(th[0] / 2.0) * sin(th[0] / 2.0))) -\n           2.0 * a[1] * cos(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[0] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e1\n    b[1] = (-(a[1] * sin(th[0] / 2.0) * sin(th[0] / 2.0))) +\n           2.0 * a[0] * cos(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[1] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e2\n    b[2] = a[2] * sin(th[0] / 2.0) * sin(th[0] / 2.0) +\n           a[2] * cos(th[0] / 2.0) * cos(th[0] / 2.0); // e3\n    return true;\n  }\n};\n\nstatic void BM_AdeptRotorGaalopJacobianReverse(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorGaalopFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstatic void BM_RotorMatrix(benchmark::State &state) {\n  double theta{0.5};\n  double point[3] = {1.0, 2.0, 3.0};\n  double res[3] = {0.0, 0.0, 0.0};\n  while (state.KeepRunning()) {\n    DiffRotorHandFunctor()(&theta, &point[0], &res[0]);\n  }\n}\nstatic void BM_RotorHand(benchmark::State &state) {\n  double theta{0.5};\n  double point[3] = {1.0, 2.0, 3.0};\n  double res[3] = {0.0, 0.0, 0.0};\n  while (state.KeepRunning()) {\n    DiffRotorHandFunctor()(&theta, &point[0], &res[0]);\n  }\n}\nstatic void BM_RotorGaalop(benchmark::State &state) {\n  double theta{0.5};\n  double point[3] = {1.0, 2.0, 3.0};\n  double res[3] = {0.0, 0.0, 0.0};\n  while (state.KeepRunning()) {\n    DiffRotorGaalopFunctor()(&theta, &point[0], &res[0]);\n  }\n}\n\nstatic void BM_RotorVersor(benchmark::State &state) {\n  double theta{0.5};\n  double point[3] = {1.0, 2.0, 3.0};\n  double res[3] = {0.0, 0.0, 0.0};\n  while (state.KeepRunning()) {\n    DiffRotorVersorFunctor()(&theta, &point[0], &res[0]);\n  }\n}\n\nstatic void BM_RotorHepGA(benchmark::State &state) {\n  double theta{0.5};\n  double point[3] = {1.0, 2.0, 3.0};\n  double res[3] = {0.0, 0.0, 0.0};\n  while (state.KeepRunning()) {\n    DiffRotorHepGAFunctor()(&theta, &point[0], &res[0]);\n  }\n}\n\nstatic void BM_AdeptRotorGaalopJacobianForward(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorGaalopFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_forward(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorHandJacobianReverse(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorHandFunctor()(&theta, &point[0], &res[0]);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    g_stack.jacobian_reverse(jac, true);\n  }\n}\n\nstatic void BM_AdeptRotorHandJacobianForward(benchmark::State &state) {\n  double jac[3];\n  adept::adouble theta{0.5};\n  adept::adouble point[3];\n  adept::set_values(point, 3, g_point);\n  while (state.KeepRunning()) {\n    g_stack.new_recording();\n    adept::adouble res[3] = {0.0, 0.0, 0.0};\n    DiffRotorHandFunctor()(&theta, &point[0], &res[0]);\n    g_stack.set_max_jacobian_threads(3);\n    g_stack.independent(&theta, 1);\n    g_stack.dependent(res, 3);\n    // g_stack.jacobian_forward_openmp(jac, true);\n    g_stack.jacobian_forward(jac, true);\n  }\n}\n\nstatic void BM_CeresRotorHandJacobian(benchmark::State &state) {\n  double theta = 0.5;\n  double jac[3];\n  const double *parameters[2] = {&theta, &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<DiffRotorHandFunctor, 3, 1, 3>(\n        new DiffRotorHandFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\nstatic void BM_CeresRotorGaalopJacobian(benchmark::State &state) {\n  double theta = 0.5;\n  double jac[3];\n  const double *parameters[2] = {&theta, &g_point[0]};\n  double *jacobians[2] = {jac, nullptr};\n  while (state.KeepRunning()) {\n    ceres::AutoDiffCostFunction<DiffRotorGaalopFunctor, 3, 1, 3>(\n        new DiffRotorGaalopFunctor())\n        .Evaluate(parameters, &g_point_spin_motor[0], jacobians);\n  }\n}\n\nBENCHMARK(BM_InnerProductVectorBivector);\nBENCHMARK(BM_AdeptJacobianForward);\nBENCHMARK(BM_AdeptJacobianReverse);\nBENCHMARK(BM_CeresJacobian);\nBENCHMARK(BM_InnerProductVectorBivector2);\nBENCHMARK(BM_AdeptJacobianForward2);\nBENCHMARK(BM_AdeptJacobianReverse2);\nBENCHMARK(BM_CeresJacobian2);\nBENCHMARK(BM_MotorSpinPoint);\nBENCHMARK(BM_VahlenMotorSpinPoint);\nBENCHMARK(BM_GaalopMotorSpinPoint);\nBENCHMARK(BM_AdeptMotorSpinPointJacobianForward);\nBENCHMARK(BM_AdeptMotorSpinPointJacobianReverse);\nBENCHMARK(BM_CeresGaalopMotorSpinPointJacobian);\nBENCHMARK(BM_CeresMotorSpinPointJacobian);\nBENCHMARK(BM_CeresRotorSpinPointJacobian);\nBENCHMARK(BM_AdeptRotorSpinPointJacobianForward);\n\n// AMDO paper\nBENCHMARK(BM_CeresRotorMatrixJacobian);\nBENCHMARK(BM_CeresRotorVersorJacobian);\nBENCHMARK(BM_CeresRotorHepGAJacobian);\nBENCHMARK(BM_CeresRotorGaalopJacobian);\nBENCHMARK(BM_CeresRotorHandJacobian);\nBENCHMARK(BM_AdeptRotorMatrixJacobianForward);\nBENCHMARK(BM_AdeptRotorMatrixJacobianReverse);\nBENCHMARK(BM_AdeptRotorVersorJacobianForward);\nBENCHMARK(BM_AdeptRotorVersorJacobianReverse);\nBENCHMARK(BM_AdeptRotorHepGAJacobianForward);\nBENCHMARK(BM_AdeptRotorHepGAJacobianReverse);\nBENCHMARK(BM_AdeptRotorGaalopJacobianReverse);\nBENCHMARK(BM_AdeptRotorGaalopJacobianForward);\nBENCHMARK(BM_AdeptRotorHandJacobianReverse);\nBENCHMARK(BM_AdeptRotorHandJacobianForward);\n\nBENCHMARK(BM_RotorHand);\nBENCHMARK(BM_RotorGaalop);\nBENCHMARK(BM_RotorVersor);\nBENCHMARK(BM_RotorMatrix);\nBENCHMARK(BM_RotorHepGA);\n\nBENCHMARK_MAIN()\n", "meta": {"hexsha": "24d570be0f832e81ce4947fd60538c347afaa4b8", "size": 24329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmark.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/benchmark.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/benchmark.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": 32.1812169312, "max_line_length": 79, "alphanum_fraction": 0.6306054503, "num_tokens": 8797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5896717818327393}}
{"text": "// This file is part of the dune-xt project:\n//   https://github.com/dune-community/dune-xt\n// Copyright 2009-2018 dune-xt developers and contributors. All rights reserved.\n// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)\n//          with \"runtime exception\" (http://www.dune-project.org/license.html)\n// Authors:\n//   René Fritze    (2018 - 2019)\n//   Tobias Leibner (2018)\n\n#ifndef DUNE_XT_DATA_COORDINATES_HH\n#define DUNE_XT_DATA_COORDINATES_HH\n\n\n#include <boost/geometry.hpp>\n\n#include <dune/common/fvector.hh>\n\nnamespace Dune::XT::Data {\n\n\n/** Converts from (x, y, z) to (theta, phi) on the unit sphere s.t.\n * (x, y, z) = (sin(theta) cos(phi), sin(theta) sin(phi), cos(theta))\n * with 0 \\leq \\theta \\leq \\pi and 0 \\leq \\varphi < 2\\pi. **/\ntemplate <class DomainFieldType>\nclass CoordinateConverter\n{\n  using BoostCartesianCoordType =\n      typename boost::geometry::model::point<DomainFieldType, 3, typename boost::geometry::cs::cartesian>;\n  using BoostSphericalCoordType = typename boost::geometry::model::\n      point<DomainFieldType, 2, typename boost::geometry::cs::spherical<boost::geometry::radian>>;\n\npublic:\n  using CartesianCoordType = FieldVector<DomainFieldType, 3>;\n  using SphericalCoordType = FieldVector<DomainFieldType, 2>;\n\n  static SphericalCoordType to_spherical(const CartesianCoordType& x)\n  {\n    BoostCartesianCoordType x_boost(x[0], x[1], x[2]);\n    BoostSphericalCoordType x_spherical_boost;\n    boost::geometry::transform(x_boost, x_spherical_boost);\n    return SphericalCoordType{boost::geometry::get<1>(x_spherical_boost), boost::geometry::get<0>(x_spherical_boost)};\n  }\n\n  static CartesianCoordType to_cartesian(const SphericalCoordType& x_spherical, bool first_is_cosine = false)\n  {\n    // if first_is_cosine, the first coordinate is not theta but rather cos(theta)\n    if (first_is_cosine) {\n      const auto& mu = x_spherical[0];\n      const auto& phi = x_spherical[1];\n      return CartesianCoordType{\n          std::sqrt(1 - std::pow(mu, 2)) * std::cos(phi), std::sqrt(1 - std::pow(mu, 2)) * std::sin(phi), mu};\n    }\n    BoostSphericalCoordType x_spherical_boost(x_spherical[1], x_spherical[0]);\n    BoostCartesianCoordType x_boost;\n    boost::geometry::transform(x_spherical_boost, x_boost);\n    return CartesianCoordType{\n        boost::geometry::get<0>(x_boost), boost::geometry::get<1>(x_boost), boost::geometry::get<2>(x_boost)};\n  }\n};\n\n\n} // namespace Dune::XT::Data\n\n#endif // DUNE_XT_DATA_COORDINATES_HH\n", "meta": {"hexsha": "4b961db6f96794a3cd18b54166d71d3d2baf6f98", "size": 2570, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/xt/data/coordinates.hh", "max_stars_repo_name": "dune-community/dune-xt-data", "max_stars_repo_head_hexsha": "32593bbcd52ed69b0a11963400a9173740089a75", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:09:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:09:11.000Z", "max_issues_repo_path": "dune/xt/data/coordinates.hh", "max_issues_repo_name": "dune-community/dune-xt-data", "max_issues_repo_head_hexsha": "32593bbcd52ed69b0a11963400a9173740089a75", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2018-08-26T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T13:01:55.000Z", "max_forks_repo_path": "dune/xt/data/coordinates.hh", "max_forks_repo_name": "dune-community/dune-xt-data", "max_forks_repo_head_hexsha": "32593bbcd52ed69b0a11963400a9173740089a75", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:10:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:10:14.000Z", "avg_line_length": 38.9393939394, "max_line_length": 118, "alphanum_fraction": 0.7151750973, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5896717553687989}}
{"text": "/*\n *  Copyright (c) 2009, Rene Wagner\n *  All rights reserved.\n *\n *  Author: Rene Wagner <rw@nelianur.org>\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 Rene Wagner nor the names of any\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#ifndef __UKFOM_LAPACK_CHOLESKY_HPP__\n#define __UKFOM_LAPACK_CHOLESKY_HPP__\n\n#include \"lapack.h\"\n\n#include <Eigen/Core>\n\nnamespace ukfom {\nnamespace lapack {\nusing namespace Eigen;\n\ntemplate<size_t M>\nclass cholesky\n{\npublic:\n\tcholesky(const Matrix<double, M, M> &m)\n\t{\n\t\tL_ = m;\n\t\t\n\t\tchar UPLO = 'L';\n\t\tint N = L_.cols();\n\t\tint LDA = L_.stride();\n\t\tint INFO;\n\n\t\tdpotrf_(&UPLO, &N, L_.data(), &LDA, &INFO);\n\n\t\tspd_ = INFO == 0;\n\n\t\t// clear everything but the lower triangular matrix\n\t\tfor (int j = 1; j < L_.cols(); ++j)\n\t\t\tfor (int i = 0; i < j; ++i)\n\t\t\t\tL_(i,j) = 0;\n\t}\n\n\t\n\tconst Matrix<double, M, M> &getL() const\n\t{\n\t\tif (!spd_)\n\t\t\tthrow \"not SPD\";\n\t\treturn L_;\n\t}\n\n\tbool isSPD() const\n\t{\n\t\treturn spd_;\n\t}\n\t\nprivate:\n\tMatrix<double, M, M> L_;\n\tbool spd_;\n};\n\n} // namespace lapack\n} // namespace ukfom\n\n#endif // __UKFOM_LAPACK_CHOLESKY_HPP__\n", "meta": {"hexsha": "5647665dba4c2e7cb71766d5eb239200e24985f1", "size": 2499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/ukfom/lapack/cholesky.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/ukfom/lapack/cholesky.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/ukfom/lapack/cholesky.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": 27.4615384615, "max_line_length": 72, "alphanum_fraction": 0.7042817127, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5896717553687989}}
{"text": "/**\n * \\file      rigid-body-kinematics.hpp\n * \\author    Mehdi Benallegue\n * \\date       2013\n * \\brief      Implements integrators for the kinematics, in terms or rotations\n *             and translations.\n *\n * \\details\n *\n *\n */\n\n#ifndef StATEOBSERVATIONRIGIDBODYKINEMATICS_H\n#define StATEOBSERVATIONRIGIDBODYKINEMATICS_H\n\n#include <Eigen/SVD>\n\n#include <state-observation/api.h>\n#include <state-observation/tools/definitions.hpp>\n#include <state-observation/tools/miscellaneous-algorithms.hpp>\n#include <state-observation/tools/probability-law-simulation.hpp>\n\nnamespace stateObservation\n{\nnamespace kine\n{\ninline void integrateKinematics(Vector3 & position, const Vector3 & velocity, double dt);\n\ninline void integrateKinematics(Vector3 & position, Vector3 & velocity, const Vector3 & acceleration, double dt);\n\ninline void integrateKinematics(Matrix3 & orientation, const Vector3 & rotationVelocity, double dt);\n\ninline void integrateKinematics(Matrix3 & orientation,\n                                Vector3 & rotationVelocity,\n                                const Vector3 & rotationAcceleration,\n                                double dt);\n\ninline void integrateKinematics(Quaternion & orientation, const Vector3 & rotationVelocity, double dt);\n\ninline void integrateKinematics(Quaternion & orientation,\n                                Vector3 & rotationVelocity,\n                                const Vector3 & rotationAcceleration,\n                                double dt);\n\n/// integrates the position/orientation and their time derivatives, given the\n/// accelerations, and initial velocities and positions. The rotations are\n/// expressed by rotation matrix\ninline void integrateKinematics(Vector3 & position,\n                                Vector3 & velocity,\n                                const Vector3 & acceleration,\n                                Matrix3 & orientation,\n                                Vector3 & rotationVelocity,\n                                const Vector3 & rotationAcceleration,\n                                double dt);\n\n/// integrates the position/orientation and their time derivatives, given the\n/// accelerations, and initial velocities and positions. The orientations are\n/// expressed by quaternions\ninline void integrateKinematics(Vector3 & position,\n                                Vector3 & velocity,\n                                const Vector3 & acceleration,\n                                Quaternion & orientation,\n                                Vector3 & rotationVelocity,\n                                const Vector3 & rotationAcceleration,\n                                double dt);\n\n/// integrates the postition/orientation given the velocities\ninline void integrateKinematics(Vector3 & position,\n                                const Vector3 & velocity,\n                                Matrix3 & orientation,\n                                const Vector3 & rotationVelocity,\n                                double dt);\n\n/// integrates the postition/orientation given the velocities\ninline void integrateKinematics(Vector3 & position,\n                                const Vector3 & velocity,\n                                Quaternion & orientation,\n                                const Vector3 & rotationVelocity,\n                                double dt);\n\n/// Puts the orientation vector norm between 0 and Pi if it\n/// gets close to 2pi\ninline Vector regulateRotationVector(const Vector3 & v);\n\n/// Transform the rotation vector into angle axis\ninline AngleAxis rotationVectorToAngleAxis(const Vector3 & v);\n\n/// Tranbsform the rotation vector into rotation matrix\ninline Matrix3 rotationVectorToRotationMatrix(const Vector3 & v);\n\n/// Tranbsform the rotation vector into quaternion\ninline Quaternion rotationVectorToQuaternion(const Vector3 & v);\n\n/// Tranbsform the rotation matrix into rotation vector\ninline Vector3 rotationMatrixToRotationVector(const Matrix3 & R);\n\n/// Tranbsform a quaternion into rotation vector\ninline Vector3 quaternionToRotationVector(const Quaternion & q);\n\n/// Tranbsform a quaternion into rotation vector\ninline Vector3 quaternionToRotationVector(const Vector4 & v);\n\n/// scalar component of a quaternion\ninline double scalarComponent(const Quaternion & q);\n\n/// vector part of the quaternion\ninline Vector3 vectorComponent(const Quaternion & q);\n\n/// Transform the rotation matrix into roll pitch yaw\n///(decompose R into Ry*Rp*Rr)\ninline Vector3 rotationMatrixToRollPitchYaw(const Matrix3 & R, Vector3 & v);\n\ninline Vector3 rotationMatrixToRollPitchYaw(const Matrix3 & R);\n\n/// Transform the roll pitch yaw into rotation matrix\n///( R = Ry*Rp*Rr)\ninline Matrix3 rollPitchYawToRotationMatrix(double roll, double pitch, double yaw);\n\ninline Matrix3 rollPitchYawToRotationMatrix(const Vector3 & rpy);\n\n/// Transform the roll pitch yaw into rotation matrix\n///( R = Ry*Rp*Rr)\ninline Quaternion rollPitchYawToQuaternion(double roll, double pitch, double yaw);\n\ninline Quaternion rollPitchYawToQuaternion(const Vector3 & rpy);\n\n/// Projects the Matrix to so(3)\ninline Matrix3 orthogonalizeRotationMatrix(const Matrix3 & M);\n\n/// transform a 3d vector into a skew symmetric 3x3 matrix\ninline Matrix3 skewSymmetric(const Vector3 & v, Matrix3 & R);\n\n/// transform a 3d vector into a skew symmetric 3x3 matrix\ninline Matrix3 skewSymmetric(const Vector3 & v);\n\n/// transform a 3d vector into a squared skew symmetric 3x3 matrix\ninline Matrix3 skewSymmetric2(const Vector3 & v, Matrix3 & R);\n\n/// transform a 3d vector into a squared skew symmetric 3x3 matrix\ninline Matrix3 skewSymmetric2(const Vector3 & v);\n\n/// transforms a homogeneous matrix into 6d vector (position theta mu)\ninline Vector6 homogeneousMatrixToVector6(const Matrix4 & M);\n\n/// transforms a 6d vector (position theta mu) into a homogeneous matrix\ninline Matrix4 vector6ToHomogeneousMatrix(const Vector6 & v);\n\n/// @brief Builds the smallest angle matrix allowing to get from a NORMALIZED vector v1 to its imahe Rv1\n/// This is based on Rodrigues formula\n///\n/// @param v1 the NORMALIZED vector\n/// @param Rv1 the NORMALIZED image of this vector by the rotation matrix R\n/// @return Matrix3 the rotation matrix R\ninline Matrix3 twoVectorsToRotationMatrix(const Vector3 & v1, const Vector3 Rv1);\n\n/// @brief checks if this matrix is a pure yaw matrix or not\n///\n/// @param R the rotation matrix\n/// @return true is pure yaw\n/// @return false is not pure yaw\ninline bool isPureYaw(const Matrix3 & R);\n\n/// @brief Gets a vector that remains horizontal with this rotation. This vector is NOT normalized\n/// @details There is a general version in getInvariantOrthogonalVector(). This can be used to extract yaw angle from\n/// a rotation matrix without needing to specify an order in the tils (e.g. roll then pich).\n///\n/// @param R the input rotation\n/// @return Vector3 the output horizontal vector\ninline Vector3 getInvariantHorizontalVector(const Matrix3 & R);\n\n/// @brief Gets a vector \\f$v\\f$ that is orthogonal to \\f$e_z\\f$ and such that \\f$\\hat{R}^T e_z\\f$ is orthogonal to\n/// the tilt \\f$R^T e_z\\f$. This vector is NOT normalized.\n/// @details This is a generalization of getInvariantHorizontalVector() which corresponds to no tilt\n/// \\f$\\hat{R}^T e_z=e_z\\f$. This function is useful to merge the yaw from the rotation matrix with the tilt.\n///\n/// @param Rhat the input rotation matrix \\f$\\hat{R}^T\\f$\n/// @param Rtez the input tilt \\f$\\hat{R}^T e_z\\f$\n/// @return Vector3 the output horizontal vector\ninline Vector3 getInvariantOrthogonalVector(const Matrix3 & Rhat, const Vector3 & Rtez);\n\n/// @brief Merge the roll and pitch from the tilt (R^T e_z) with the yaw from a rotation matrix (minimizes the\n/// deviation of the v vector)\n/// @details throws exception when the orientation is singlular (likely gimbal lock)\n/// to avoid these issues, we recommend to use mergeTiltWithYawAxisAgnostic()\n/// @param Rtez the tilt \\f$R_1^T e_z\\f$ (the local image of \\f$e_z\\f$ unit vector)\n/// @param R2 is the second rotation matrix from which the \"yaw\" needs to be extracted\n/// @param v is the vector to use as reference it must be horizontal and normalized (for a traditional yaw v is by\n/// deftault \\f$e_x\\f$)\n/// @return Matrix3 the merged rotation matrix\ninline Matrix3 mergeTiltWithYaw(const Vector3 & Rtez,\n                                const Matrix3 & R2,\n                                const Vector3 & v = Vector3::UnitX()) noexcept(false);\n\n/// @brief Merge the roll and pitch with the yaw from a rotation matrix (minimizes the deviation of the v vector)\n///\n/// @param R1 is the first rotation to get the roll and pitch\n/// @param R2 is the second rotation matrix from which the \"yaw\" needs to be extracted\n/// @param v is the vector to use as reference (for a traditional yaw v is initialized to \\f$e_x\\f$)\n/// @return Matrix3 the merged rotation matrix\ninline Matrix3 mergeRoll1Pitch1WithYaw2(const Matrix3 & R1, const Matrix3 & R2, const Vector3 & v = Vector3::UnitX());\n\n/// @brief Merge the roll and pitch from the tilt (R^T e_z) with the yaw from a rotation matrix (minimizes the deviation\n/// of the v vector)\n/// @param Rtez the tilt \\f$R_1^T e_z\\f$ (the local image of \\f$e_z\\f$ unit vector)\n/// @param R2 is the second rotation matrix from which the \"yaw\" needs to be extracted\n/// @param v is the vector to use as reference (for a traditional yaw v is initialized to \\f$e_x\\f$)\n/// @return Matrix3 the merged rotation matrix\ninline Matrix3 mergeTiltWithYawAxisAgnostic(const Vector3 & Rtez, const Matrix3 & R2);\n\n/// @brief Merge the roll and pitch with the yaw from a rotation matrix with optimal reference vector\n///\n/// @param R1 is the first rotation to get the roll and pitch\n/// @param R2 is the second rotation matrix from which the \"yaw\" needs to be extracted\n/// @param v is the vector to use as reference (for a traditional yaw v is initialized to \\f$e_x\\f$)\n/// @return Matrix3 the merged rotation matrix\ninline Matrix3 mergeRoll1Pitch1WithYaw2AxisAgnostic(const Matrix3 & R1, const Matrix3 & R2);\n\n/// @brief take 3x3 matrix represeting a rotation and gives the angle that vector v turns around the axis with this\n/// rotation\n/// @param rotation The 3x3 rotation matrix\n/// @param axis the axis of rotation (must be normalized)\n/// @param v the vector that is rotated with the rotation (must be orthogonal to axis and normalized)\n/// @return double the angle\ninline double rotationMatrixToAngle(const Matrix3 & rotation, const Vector3 & axis, const Vector3 & v);\n\n/// @brief take 3x3 matrix represeting a rotation and gives the angle that vector v turns around the upward vertical\n/// axis with this rotation\n/// @details this is a generalization of yaw extraction (yaw is equivalent to v = Matrix3::UnitX(), but it is more\n/// efficiant to calll the dedicated  rotationMatrixToYaw() without vector parameter).\n/// @param rotation The 3x3 rotation matrix\n/// @param v the rotated vector (expressed in the horizontal plane, must be normalized)\n/// @return double the angle\ninline double rotationMatrixToYaw(const Matrix3 & rotation, const Vector2 & v);\n\n/// @brief take 3x3 matrix represeting a rotation and gives the yaw angle from roll pitch yaw representation\n/// @param rotation The 3x3 rotation matrix\n/// @return double the angle\ninline double rotationMatrixToYaw(const Matrix3 & rotation);\n\n/// @brief take 3x3 matrix represeting a rotation and gives a corresponding angle around upward vertical axis\n/// @details This is similar to yaw angle but here we identify a horizontal vector that stays horizontal after rotation.\n/// this can be called axis agnostic yaw extraction.\n/// and get the angle between them\n/// @param rotation The 3x3 rotation matrix\n/// @return double the angle\ninline double rotationMatrixToYawAxisAgnostic(const Matrix3 & rotation);\n\n/// @brief Get the Identity Quaternion\n///\n/// @return Quaternion\ninline Quaternion zeroRotationQuaternion();\n\n/// @brief Get a uniformly random Quaternion\n///\n/// @return Quaternion\ninline Quaternion randomRotationQuaternion();\n\n/// @brief get a randomAngle between -pi and pu\n///\n/// @return double the random angle\ninline double randomAngle();\n\n/// @brief Checks if it is a rotation matrix (right-hand orthonormal) or not\n/// @param precision the absolute precision of the test\n/// @return true when it is a rotation matrix\n/// @return false when not\ninline bool isRotationMatrix(const Matrix3 &, double precision = 2 * cst::epsilon1);\n\n/// transforms a rotation into translation given a constraint of a fixed point\ninline void fixedPointRotationToTranslation(const Matrix3 & R,\n                                            const Vector3 & rotationVelocity,\n                                            const Vector3 & rotationAcceleration,\n                                            const Vector3 & fixedPoint,\n                                            Vector3 & outputTranslation,\n                                            Vector3 & outputLinearVelocity,\n                                            Vector3 & outputLinearAcceleration);\n\n/// derivates a quaternion using finite difference to get a angular velocity vector\ninline Vector3 derivateRotationFD(const Quaternion & q1, const Quaternion & q2, double dt);\n\n/// derivates a rotation vector using finite difference to get a angular velocity vector\ninline Vector3 derivateRotationFD(const Vector3 & o1, const Vector3 & o2, double dt);\n\ninline Vector6 derivateHomogeneousMatrixFD(const Matrix4 & m1, const Matrix4 & m2, double dt);\n\ninline Vector6 derivatePoseThetaUFD(const Vector6 & v1, const Vector6 & v2, double dt);\n\n/// Computes the \"multiplicative Jacobian\" for\n/// Kalman filtering for example\n/// orientation is the current orientation\n/// dR is the rotation delta between the current orientation and the orientation\n/// at the next step.\n/// dRdR is the \"multiplicative\" Jacobian with regard to variations of orientation\n/// dRddeltaR is the \"multiplicative\" Jacobian with regard to variations of deltaR\ninline void derivateRotationMultiplicative(const Vector3 & deltaR, Matrix3 & dRdR, Matrix3 & dRddeltaR);\n\n/// Computes the \"multiplicative Jacobian\" for\n/// a function R^T.v giving a vector v expressed in a local frame\n/// with regard to Rotations of this local frame\ninline Matrix3 derivateRtvMultiplicative(const Matrix3 & R, const Vector3 & v);\n\n/// uses the derivation to reconstruct the velocities and accelerations given\n/// trajectories in positions and orientations only\ninline IndexedVectorArray reconstructStateTrajectory(const IndexedVectorArray & positionOrientation, double dt);\n\ninline Vector invertState(const Vector & state);\n\ninline Matrix4 invertHomoMatrix(const Matrix4 & m);\n\nenum rotationType\n{\n  matrix = 0,\n  rotationVector = 1,\n  quaternion = 2,\n  angleaxis = 3\n};\n\ntemplate<rotationType = rotationVector>\nstruct indexes\n{\n};\n\ntemplate<>\nstruct indexes<rotationVector>\n{\n  /// indexes of the different components of a vector of the kinematic state\n  /// when the orientation is represented using a 3D rotation vector\n  static const unsigned pos = 0;\n  static const unsigned ori = 3;\n  static const unsigned linVel = 6;\n  static const unsigned angVel = 9;\n  static const unsigned linAcc = 12;\n  static const unsigned angAcc = 15;\n  static const unsigned size = 18;\n};\n\ntemplate<>\nstruct indexes<quaternion>\n{\n  /// indexes of the different components of a vector of the kinematic state\n  /// when the orientation is represented using a quaternion\n  static const unsigned pos = 0;\n  static const unsigned ori = 3;\n  static const unsigned linVel = 7;\n  static const unsigned angVel = 10;\n  static const unsigned linAcc = 13;\n  static const unsigned angAcc = 16;\n  static const unsigned size = 19;\n};\n\n/// relative tolereance to the square of quaternion norm.\nconstexpr double quatNormTol = 1e-6;\n\nclass Orientation\n{\npublic:\n  /// The parameter initialize should be set to true except when it is\n  /// certain that the initial value will not be used\n  /// And that the first operation would be to set its value\n  explicit Orientation(bool initialize = true);\n\n  /// this is the rotation vector and NOT Euler angles\n  explicit Orientation(const Vector3 & v);\n\n  explicit Orientation(const Quaternion & q);\n\n  explicit Orientation(const Matrix3 & m);\n\n  explicit Orientation(const AngleAxis & aa);\n\n  Orientation(const Quaternion & q, const Matrix3 & m);\n\n  Orientation(const double & roll, const double & pitch, const double & yaw);\n\n  Orientation(const Orientation & multiplier1, const Orientation & multiplier2);\n\n  inline Orientation & operator=(const Vector3 & v);\n\n  inline Orientation & operator=(const Quaternion & q);\n\n  inline Orientation & operator=(const Matrix3 & m);\n\n  inline Orientation & operator=(const AngleAxis & aa);\n\n  inline Orientation & setValue(const Quaternion & q, const Matrix3 & m);\n\n  inline Orientation & fromVector4(const Vector4 & v);\n\n  inline Orientation & setRandom();\n\n  template<typename t>\n  inline Orientation & setZeroRotation();\n\n  inline Orientation & setZeroRotation();\n\n  /// get a const reference on the matrix or the quaternion\n  inline const Matrix3 & toMatrix3() const;\n  inline const Quaternion & toQuaternion() const;\n\n  inline operator const Matrix3 &() const;\n  inline operator const Quaternion &() const;\n\n  inline Vector4 toVector4() const;\n\n  inline Vector3 toRotationVector() const;\n  inline Vector3 toRollPitchYaw() const;\n  inline AngleAxis toAngleAxis() const;\n\n  /// Multiply the rotation (orientation) by another rotation R2\n  /// the non const versions allow to use more optimized methods\n\n  inline Orientation operator*(const Orientation & R2) const;\n\n  /// Noalias versions of the operator*\n  inline const Orientation & setToProductNoAlias(const Orientation & R1, const Orientation & R2);\n\n  inline Orientation inverse() const;\n\n  /// use the vector dt_x_omega as the increment of rotation expressed in the\n  /// world frame. Which gives R_{k+1}=\\exp(S(dtxomega))R_k\n  inline const Orientation & integrate(Vector3 dt_x_omega);\n\n  /// gives the log (rotation vector) of the difference of orientation\n  /// gives log of (*this).inverse()*R_k1\n  inline Vector3 differentiate(Orientation R_k1) const;\n\n  /// Rotate a vector\n  inline Vector3 operator*(const Vector3 & v) const;\n\n  inline bool isSet() const;\n  inline void reset();\n\n  inline bool isMatrixSet() const;\n  inline bool isQuaternionSet() const;\n\n  /// switch the state of the Matrix or quaternion to set or not\n  /// this can be used for forward initialization\n  inline void setMatrix(bool b = true);\n  inline void setQuaternion(bool b = true);\n\n  /// no checks are performed for these functions, use with caution\n\n  inline CheckedMatrix3 & getMatrixRefUnsafe();\n  inline CheckedQuaternion & getQuaternionRefUnsafe();\n\n  /// synchronizes the representations (quaternion and rotation matrix)\n  inline void synchronize();\n\n  /// retruns a zero rotation\n  static inline Orientation zeroRotation();\n\n  /// Returns a uniformly distributed random rotation\n  static inline Orientation randomRotation();\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  void check_() const;\n\n  inline const Matrix3 & quaternionToMatrix_() const;\n  inline const Quaternion & matrixToQuaternion_() const;\n\n  mutable CheckedQuaternion q_;\n  mutable CheckedMatrix3 m_;\n};\n\nstruct Kinematics\n{\n  struct Flags\n  {\n    typedef unsigned char Byte;\n\n    static const Byte position = BOOST_BINARY(000001);\n    static const Byte orientation = BOOST_BINARY(000010);\n    static const Byte linVel = BOOST_BINARY(000100);\n    static const Byte angVel = BOOST_BINARY(001000);\n    static const Byte linAcc = BOOST_BINARY(010000);\n    static const Byte angAcc = BOOST_BINARY(100000);\n\n    static const Byte all = position | orientation | linVel | angVel | linAcc | angAcc;\n  };\n\n  Kinematics() {}\n\n  /// Constructor from a vector\n  /// the flags show which parts of the kinematics to be loaded from the vector\n  /// the order of the vector is\n  /// position orientation (quaternion) linevel angvel linAcc angAcc\n  /// use the flags to define the structure of the vector\n  Kinematics(const Vector & v, Flags::Byte = Flags::all);\n\n  Kinematics(const Kinematics & multiplier1, const Kinematics & multiplier2);\n\n  /// Fills from vector\n  /// the flags show which parts of the kinematics to be loaded from the vector\n  /// the order of the vector is\n  /// position orientation (quaternion) linevel angvel linAcc angAcc\n  /// use the flags to define the structure of the vector\n  Kinematics & fromVector(const Vector & v, Flags::Byte = Flags::all);\n\n  /// initializes at zero all the flagged fields\n  /// the typename allows to set if the prefered type for rotation\n  /// is a Matrix3 or a Quaternion (Quaternion by default)\n  template<typename t>\n  Kinematics & setZero(Flags::Byte = Flags::all);\n\n  Kinematics & setZero(Flags::Byte = Flags::all);\n\n  inline const Kinematics & integrate(double dt);\n\n  inline const Kinematics & update(const Kinematics & newValue, double dt, Flags::Byte = Flags::all);\n\n  inline Kinematics getInverse() const;\n\n  /// converts the object to a vector\n  /// the order of the vector is\n  /// position orientation (quaternion) linevel angvel linAcc angAcc\n  /// use the flags to define the structure of the vector\n  inline Vector toVector(Flags::Byte) const;\n  inline Vector toVector() const;\n\n  /// composition of transformation\n  inline Kinematics operator*(const Kinematics &)const;\n\n  inline Kinematics setToProductNoAlias(const Kinematics & operand1, const Kinematics & operand2);\n\n  inline void reset();\n\n  CheckedVector3 position;\n  Orientation orientation;\n\n  CheckedVector3 linVel;\n  CheckedVector3 angVel;\n\n  CheckedVector3 linAcc;\n  CheckedVector3 angAcc;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprotected:\n  inline const Kinematics & update_deprecated(const Kinematics & newValue, double dt, Flags::Byte = Flags::all);\n\n  Vector3 tempVec_;\n};\n\n} // namespace kine\n} // namespace stateObservation\n\ninline std::ostream & operator<<(std::ostream & os, const stateObservation::kine::Kinematics & k);\n\n#include <state-observation/tools/rigid-body-kinematics.hxx>\n\n#endif // StATEOBSERVATIONRIGIDBODYKINEMATICS_H\n", "meta": {"hexsha": "ee69d3b6d427b6f3ba2d1df92836b32b165fd08b", "size": 22079, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/state-observation/tools/rigid-body-kinematics.hpp", "max_stars_repo_name": "jrl-umi3218/state-observation", "max_stars_repo_head_hexsha": "bd4f1b7e64a0a3b393f63f69219c061200793d35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "include/state-observation/tools/rigid-body-kinematics.hpp", "max_issues_repo_name": "mehdi-benallegue/state-observation", "max_issues_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "include/state-observation/tools/rigid-body-kinematics.hpp", "max_forks_repo_name": "mehdi-benallegue/state-observation", "max_forks_repo_head_hexsha": "cfc703a52380bd15065801f5d87baba4bbb506ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 39.8537906137, "max_line_length": 120, "alphanum_fraction": 0.7186466778, "num_tokens": 4932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.5896255696453878}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu)  2011.\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#include <boost/config.hpp>\r\n\r\n#ifdef BOOST_NO_CXX11_CONSTEXPR\r\n#include <iostream>\r\n\r\nint main()\r\n{\r\n  std::cout << \"Please use a compiler that supports constexpr\" << std::endl;\r\n}\r\n#else\r\n\r\n#define BOOST_MPL_LIMIT_STRING_SIZE 64 \r\n#define BOOST_METAPARSE_LIMIT_STRING_SIZE BOOST_MPL_LIMIT_STRING_SIZE\r\n\r\n#include <boost/metaparse/grammar.hpp>\r\n#include <boost/metaparse/entire_input.hpp>\r\n#include <boost/metaparse/build_parser.hpp>\r\n#include <boost/metaparse/token.hpp>\r\n#include <boost/metaparse/string.hpp>\r\n#include <boost/metaparse/util/digit_to_int.hpp>\r\n\r\n#include <boost/mpl/apply_wrap.hpp>\r\n#include <boost/mpl/fold.hpp>\r\n#include <boost/mpl/front.hpp>\r\n#include <boost/mpl/back.hpp>\r\n#include <boost/mpl/plus.hpp>\r\n#include <boost/mpl/minus.hpp>\r\n#include <boost/mpl/times.hpp>\r\n#include <boost/mpl/divides.hpp>\r\n#include <boost/mpl/equal_to.hpp>\r\n#include <boost/mpl/eval_if.hpp>\r\n#include <boost/mpl/lambda.hpp>\r\n#include <boost/mpl/char.hpp>\r\n#include <boost/mpl/int.hpp>\r\n\r\nusing boost::metaparse::build_parser;\r\nusing boost::metaparse::entire_input;\r\nusing boost::metaparse::token;\r\nusing boost::metaparse::grammar;\r\n\r\nusing boost::metaparse::util::digit_to_int;\r\n\r\nusing boost::mpl::apply_wrap1;\r\nusing boost::mpl::fold;\r\nusing boost::mpl::front;\r\nusing boost::mpl::back;\r\nusing boost::mpl::plus;\r\nusing boost::mpl::minus;\r\nusing boost::mpl::times;\r\nusing boost::mpl::divides;\r\nusing boost::mpl::eval_if;\r\nusing boost::mpl::equal_to;\r\nusing boost::mpl::_1;\r\nusing boost::mpl::_2;\r\nusing boost::mpl::char_;\r\nusing boost::mpl::lambda;\r\nusing boost::mpl::int_;\r\n\r\n#ifdef _STR\r\n  #error _STR already defined\r\n#endif\r\n#define _STR BOOST_METAPARSE_STRING\r\n\r\ntemplate <class A, class B>\r\nstruct lazy_plus : plus<typename A::type, typename B::type> {};\r\n\r\ntemplate <class A, class B>\r\nstruct lazy_minus : minus<typename A::type, typename B::type> {};\r\n\r\ntemplate <class A, class B>\r\nstruct lazy_times : times<typename A::type, typename B::type> {};\r\n\r\ntemplate <class A, class B>\r\nstruct lazy_divides : divides<typename A::type, typename B::type> {};\r\n\r\ntemplate <class C, class T, class F>\r\nstruct lazy_eval_if : eval_if<typename C::type, T, F> {};\r\n\r\ntemplate <class A, class B>\r\nstruct lazy_equal_to : equal_to<typename A::type, typename B::type> {};\r\n\r\ntemplate <class Sequence, class State, class ForwardOp>\r\nstruct lazy_fold :\r\n  fold<typename Sequence::type, typename State::type, typename ForwardOp::type>\r\n{};\r\n\r\ntypedef\r\n  lazy_fold<\r\n    back<_1>,\r\n    front<_1>,\r\n    lambda<\r\n      lazy_eval_if<\r\n        lazy_equal_to<front<_2>, char_<'*'>>,\r\n        lazy_times<_1, back<_2>>,\r\n        lazy_divides<_1, back<_2>>\r\n      >\r\n    >::type\r\n  >\r\n  prod_action;\r\n\r\ntypedef\r\n  lazy_fold<\r\n    back<_1>,\r\n    front<_1>,\r\n    lambda<\r\n      lazy_eval_if<\r\n        lazy_equal_to<front<_2>, char_<'+'>>,\r\n        lazy_plus<_1, back<_2>>,\r\n        lazy_minus<_1, back<_2>>\r\n      >\r\n    >::type\r\n  >\r\n  plus_action;\r\n\r\ntypedef\r\n  lambda<\r\n    lazy_fold<\r\n      _1,\r\n      int_<0>,\r\n      lambda<\r\n        lazy_plus<lazy_times<_1, int_<10>>, apply_wrap1<digit_to_int<>, _2>>\r\n      >::type\r\n    >\r\n  >::type\r\n  int_action;\r\n\r\ntypedef\r\n  grammar<_STR(\"plus_exp\")>\r\n\r\n    ::rule<_STR(\"int ::= ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')+\"), int_action>::type\r\n    ::rule<_STR(\"ws ::= (' ' | '\\n' | '\\r' | '\\t')*\")>::type\r\n    ::rule<_STR(\"int_token ::= int ws\"), front<_1>>::type\r\n    ::rule<_STR(\"plus_token ::= '+' ws\"), front<_1>>::type\r\n    ::rule<_STR(\"minus_token ::= '-' ws\"), front<_1>>::type\r\n    ::rule<_STR(\"mult_token ::= '*' ws\"), front<_1>>::type\r\n    ::rule<_STR(\"div_token ::= '/' ws\"), front<_1>>::type\r\n    ::rule<_STR(\"plus_token ::= '+' ws\")>::type\r\n    ::rule<_STR(\"plus_exp ::= prod_exp ((plus_token | minus_token) prod_exp)*\"), plus_action>::type\r\n    ::rule<_STR(\"prod_exp ::= int_token ((mult_token | div_token) int_token)*\"), prod_action>::type\r\n  expression;\r\n\r\ntypedef build_parser<entire_input<expression>> calculator_parser;\r\n\r\nint main()\r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n  \r\n  cout\r\n    << apply_wrap1<calculator_parser, _STR(\"13\")>::type::value << endl\r\n    << apply_wrap1<calculator_parser, _STR(\"1+ 2*4-6/2\")>::type::value << endl\r\n    ;\r\n}\r\n#endif\r\n\r\n", "meta": {"hexsha": "a0b41bb1a1be8fa7b5bd93eeee3804a2de50b558", "size": 4433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metaparse/example/grammar_calculator/main.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:57:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:57:24.000Z", "max_issues_repo_path": "thirdparty-cpp/boost_1_62_0/libs/metaparse/example/grammar_calculator/main.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/metaparse/example/grammar_calculator/main.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": 27.5341614907, "max_line_length": 100, "alphanum_fraction": 0.647417099, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5896255674001525}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/numeric/odeint.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/feedback/mpc.hpp>\n\n#include <chrono>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\nusing namespace std::chrono_literals;\nusing namespace boost::numeric::odeint;\n\nusing Time = std::chrono::duration<double>;\n\ntemplate<typename T>\nusing X = Eigen::Vector2<T>;\ntemplate<typename T>\nusing U = Eigen::Matrix<T, 1, 1>;\n\nusing Gd = X<double>;\nusing Ud = U<double>;\n\nint main()\n{\n  using std::sin;\n  std::srand(5);\n\n  // system variables\n  Gd g = Gd::Random();\n  Ud u;\n\n  // dynamics\n  auto f = []<typename S>(const X<S> & x, const U<S> u) -> smooth::Tangent<X<S>> {\n    return {x(1), u(0)};\n  };\n\n  // running constraints\n  auto cr = []<typename S>(const X<S> &, const U<S> & u) -> Eigen::Vector<S, 1> { return u; };\n  Eigen::Vector<double, 1> crl{-0.5}, cru{0.5};\n\n  // create MPC object and set input bounds, and desired trajectories\n  smooth::feedback::MPC<Time, Gd, Ud, decltype(f), decltype(cr)> mpc{\n    f,\n    cr,\n    crl,\n    cru,\n    {\n      .K  = 20,\n      .tf = 5,\n      .qp = {.scaling = false, .polish = false},\n    },\n  };\n\n  mpc.set_weights({\n    .Q   = Eigen::Matrix2d::Identity(),\n    .Qtf = 0.1 * Eigen::Matrix2d::Identity(),\n    .R   = 0.1 * Eigen::Matrix<double, 1, 1>::Identity(),\n  });\n  mpc.set_xdes_rel([]<typename T>(T t) -> X<T> { return X<T>{-0.5 * sin(0.3 * t), 0}; });\n  mpc.set_udes_rel([]<typename T>(T) -> U<T> { return U<T>::Zero(); });\n\n  // prepare for integrating the closed-loop system\n  runge_kutta4<Gd, double, smooth::Tangent<Gd>, double, vector_space_algebra> stepper{};\n  const auto ode = [&f, &u](const Gd & x, smooth::Tangent<Gd> & d, double) { d = f(x, u); };\n  std::vector<double> tvec, xvec, vvec, uvec;\n\n  // integrate closed-loop system\n  const auto t0 = std::chrono::high_resolution_clock::now();\n\n  for (std::chrono::milliseconds t = 0s; t < 60s; t += 50ms) {\n    // compute MPC input\n    auto [u_mpc, code] = mpc(t, g);\n    u                  = u_mpc;\n    if (code != smooth::feedback::QPSolutionStatus::Optimal) {\n      std::cerr << \"Solver failed with code \" << static_cast<int>(code) << std::endl;\n    }\n\n    // store data\n    tvec.push_back(duration_cast<Time>(t).count());\n    xvec.push_back(g.x());\n    vvec.push_back(g.y());\n    uvec.push_back(u(0));\n\n    // step dynamics\n    stepper.do_step(ode, g, 0, 0.05);\n  }\n\n  const auto tf = std::chrono::high_resolution_clock::now();\n\n  std::cout << \"MPC loop time: \"\n            << std::chrono::duration_cast<std::chrono::microseconds>(tf - t0).count() << \"us\\n\";\n\n#if ENABLE_PLOTTING\n  matplot::figure();\n  matplot::hold(matplot::on);\n\n  matplot::plot(tvec, xvec)->line_width(2);\n  matplot::plot(tvec, matplot::transform(tvec, [](auto t) { return -0.5 * sin(0.3 * t); }), \"k--\")\n    ->line_width(2);\n  matplot::plot(tvec, vvec)->line_width(2);\n  matplot::plot(tvec, uvec)->line_width(2);\n  matplot::legend({\"x\", \"x_{des}\", \"v\", \"u\"});\n\n  matplot::show();\n#else\n  std::cout << \"TRAJECTORY:\" << std::endl;\n  for (auto i = 0u; i != tvec.size(); ++i) {\n    std::cout << \"t=\" << tvec[i] << \": x=\" << xvec[i] << \", v=\" << vvec[i] << std::endl;\n  }\n#endif\n}\n", "meta": {"hexsha": "a4e1164175048e6dfd7de2e3939151287b900953", "size": 4436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpc_doubleintegrator.cpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/mpc_doubleintegrator.cpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mpc_doubleintegrator.cpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1449275362, "max_line_length": 98, "alphanum_fraction": 0.6408926961, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220786, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5895014745677667}}
{"text": "#pragma once\n\n#include \"Faddeeva/Faddeeva.hh\"\n#include \"util.hpp\"\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n#include <random>\n\n#include <fstream>\n#include <sstream>\n\nnamespace myFM {\ntemplate <typename Real> struct OprobitSampler {\n\n  using DenseVector = types::Vector<Real>;\n  using DenseMatrix = types::DenseMatrix<Real>;\n  using IntVector = Eigen::Matrix<int, Eigen::Dynamic, 1>;\n  static constexpr Real SQRT2 = 1.4142135623730951;\n  static constexpr Real SQRTPI = 1.7724538509055159;\n  static constexpr Real SQRT2PI = SQRT2 * SQRTPI;\n  static constexpr Real PI = 3.141592653589793;\n\n  OprobitSampler(DenseVector &x, const DenseVector &y, int K,\n                 const std::vector<size_t> &indices, std::mt19937 &rng,\n                 Real reg, Real nu)\n      : x_(x), y_(y), K(K), indices_(indices), reg(reg), nu(nu), rng(rng),\n        zmins(K), zmaxs(K), histogram(K), accept_count(0) {\n    this->alpha_now = DenseVector::Zero(K - 1);\n    this->gamma_now = DenseVector::Zero(K - 1);\n    this->alpha_to_gamma(gamma_now, alpha_now);\n    this->H = DenseMatrix::Zero(K - 1, K - 1);\n    for (auto i : indices_) {\n      int y_label = static_cast<int>(y_(i));\n      if (std::abs(y_label - y(i)) > 1e-3) {\n        throw std::invalid_argument(\"y has a floating-point element.\");\n      }\n      if (y_label < 0) {\n        throw std::invalid_argument(\"y has a negative element.\");\n      }\n      if (y_label >= K) {\n        std::stringstream ss;\n        ss << \"y[ \" << i << \"] is greater than \" << (K - 1) << \".\";\n        throw std::invalid_argument(ss.str());\n      }\n      histogram[y_label]++;\n    }\n  }\n\n  inline Real log_p_mvt(const DenseMatrix &SigmaInverse, const DenseVector mu,\n                        Real nu, const DenseVector &x) {\n    Real log_p = (x - mu).transpose() * SigmaInverse * (x - mu);\n    return std::log(1 + log_p / nu) * (-nu - SigmaInverse.rows()) / 2;\n  }\n\n  inline DenseVector sample_mvt(const DenseMatrix &SigmaInverse, Real nu) {\n    /*Sample From multivariate t-distribution*/\n    DenseVector result(SigmaInverse.rows());\n    std::normal_distribution<Real> base_dist(0, 1);\n    std::gamma_distribution<Real> chi_gen(nu / 2);\n    for (int i = 0; i < result.rows(); i++) {\n      result(i) = base_dist(rng);\n    }\n    Eigen::LLT<DenseMatrix, Eigen::Upper> L(SigmaInverse);\n    result = L.matrixU().solve(result);\n    result /= std::sqrt(chi_gen(rng) * 2 / nu);\n    if (fix_gamma0) {\n      result(0) = 0;\n    }\n    return result;\n  }\n\n  static inline void jacobian_dgamma_dalpha(DenseMatrix &J,\n                                            const DenseVector &alpha) {\n    /*\n    J_{ij} with i=> alpha, j=>gamma\n    */\n    J.array() = 0;\n    J(0, 0) = 1;\n    if (!fix_gamma0) {\n      for (int j = 1; j < alpha.rows(); j++) {\n        J(0, j) = 1;\n      }\n    }\n    for (int i = 1; i < alpha.rows(); i++) {\n      Real ed = std::exp(alpha(i));\n      for (int j = i; j < alpha.rows(); j++) {\n        J(i, j) = ed;\n      }\n    }\n    // d f / d alpha_0 = (df / d gamma_i) (d gamma_i / d alpha_0 )\n  }\n\n  static inline void alpha_to_gamma(DenseVector &target,\n                                    const DenseVector &alpha) {\n    target(0) = alpha(0);\n    for (int i = 1; i < alpha.rows(); i++) {\n      target(i) = target(i - 1) + std::exp(alpha(i));\n    }\n  }\n\n  static inline void gamma_to_alpha(DenseVector &target,\n                                    const DenseVector &gamma) {\n    target(0) = gamma(0);\n    for (int i = 1; i < gamma.rows(); i++) {\n      target(i) = std::log(gamma(i) - gamma(i - 1));\n    }\n  }\n\n  static inline void safe_ldiff(Real x, Real y, Real &loss, Real &dx, Real &dy,\n                                DenseMatrix *HessianTarget = nullptr,\n                                int label = 0) {\n    // assert(x >= y);\n    Real denominator;\n    Real exp_factor;\n    if (y > 0) {\n      // both positive\n      // erfcy = erfc * exp( y**2 / 2)\n      exp_factor = std::exp((y * y - x * x) / 2);\n      denominator =\n          Faddeeva::erfcx(y / SQRT2) - exp_factor * Faddeeva::erfcx(x / SQRT2);\n\n      loss -= y * y / 2;\n      loss += std::log(denominator / 2);\n      dx += (2 / SQRT2PI) * exp_factor / denominator;\n      dy -= (2 / SQRT2PI) / denominator;\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label, label) +=\n            -(SQRT2PI * x * denominator * std::exp((y * y - x * x) / 2) +\n              2 * std::exp(y * y - x * x)) /\n            denominator / denominator / PI;\n        (*HessianTarget)(label - 1, label - 1) +=\n            (SQRT2PI * y * denominator - 2) / denominator / denominator / PI;\n        Real off_diag =\n            2 * std::exp((y * y - x * x) / 2) / PI / denominator / denominator;\n        (*HessianTarget)(label, label - 1) += off_diag;\n        (*HessianTarget)(label - 1, label) += off_diag;\n      }\n    } else if (x < 0) {\n      // both negative\n      loss -= x * x / 2;\n\n      exp_factor = std::exp((x * x - y * y) / 2);\n      denominator = Faddeeva::erfcx(-x / SQRT2) -\n                    exp_factor * Faddeeva::erfcx(-y / SQRT2);\n      loss += std::log(denominator / 2);\n      dx += (2 / SQRT2PI) / denominator;\n      dy -= (2 / SQRT2PI) * exp_factor / denominator;\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label, label) +=\n            -(SQRT2PI * x * denominator + 2) / PI / denominator / denominator;\n        (*HessianTarget)(label - 1, label - 1) +=\n            (SQRT2PI * y * exp_factor * denominator -\n             2 * (exp_factor * exp_factor)) /\n            PI / denominator / denominator;\n        Real off_diag = 2 * exp_factor / PI / denominator / denominator;\n        (*HessianTarget)(label, label - 1) += off_diag;\n        (*HessianTarget)(label - 1, label) += off_diag;\n      }\n    } else {\n      // x positive, y negative. safe to use erf\n      denominator = Faddeeva::erf(x / SQRT2) - Faddeeva::erf(y / SQRT2);\n      Real expxx = std::exp(-x * x / 2);\n      Real expyy = std::exp(-y * y / 2);\n      dx += 2 * expxx / denominator / SQRT2PI;\n      dy -= 2 * expyy / denominator / SQRT2PI;\n      loss += std::log(denominator / 2);\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label, label) +=\n            -(SQRT2PI * x * denominator * expxx + 2 * expxx * expxx) / PI /\n            denominator / denominator;\n        (*HessianTarget)(label - 1, label - 1) +=\n            -(-SQRT2PI * y * denominator * expyy + 2 * expyy * expyy) / PI /\n            denominator / denominator;\n        Real off_diag = 2 * expxx * expyy / PI / denominator / denominator;\n        (*HessianTarget)(label, label - 1) += off_diag;\n        (*HessianTarget)(label - 1, label) += off_diag;\n      }\n    }\n  }\n\n  static inline void safe_lcdf(Real x, Real &loss, Real &dx,\n                               DenseMatrix *HessianTarget = nullptr,\n                               int label = 0) {\n    Real denominator;\n    Real exp_factor;\n    if (x > 1) {\n      exp_factor = std::exp(-x * x / 2);\n      denominator = 1 + Faddeeva::erf(x / SQRT2);\n      dx += (2 / SQRT2PI) * exp_factor / denominator;\n      loss += std::log(denominator / 2);\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label, label) +=\n            -(SQRT2PI * x * denominator * exp_factor +\n              2 * exp_factor * exp_factor) /\n            PI / denominator / denominator;\n      }\n    } else {\n      denominator = Faddeeva::erfcx(-x / SQRT2);\n      dx += (2 / SQRT2PI) / denominator;\n      loss -= x * x / 2;\n      loss += std::log(denominator / 2);\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label, label) +=\n            -(SQRT2PI * x * denominator + 2) / PI / denominator / denominator;\n      }\n    }\n  }\n\n  inline void safe_lccdf(Real x, Real &loss, Real &dx,\n                         DenseMatrix *HessianTarget, int label = 0) {\n    Real denominator;\n    if (x > -1) {\n      denominator = Faddeeva::erfcx(x / SQRT2);\n      dx -= (2 / SQRT2PI) / denominator;\n      loss += std::log(denominator / 2);\n      loss -= x * x / 2;\n      if (HessianTarget != nullptr) {\n        (*HessianTarget)(label - 1, label - 1) +=\n            (SQRT2PI * x * denominator - 2) / denominator / denominator / PI;\n      }\n    } else {\n      // safe to use erf\n      denominator = 1 - Faddeeva::erf(x / SQRT2);\n      dx -= (2 / SQRT2PI) * std::exp(-x * x / 2) / denominator;\n      loss += std::log(denominator / 2);\n      if (HessianTarget != nullptr) {\n        Real exp_factor = std::exp(-(x * x) / 2);\n        (*HessianTarget)(label - 1, label - 1) +=\n            -(-SQRT2PI * x * denominator * exp_factor +\n              2 * exp_factor * exp_factor) /\n            PI / denominator / denominator;\n      }\n    }\n  }\n\n  inline void sample_z_given_cutpoint() {\n    zmins.array() = std::numeric_limits<Real>::max();\n    zmaxs.array() = std::numeric_limits<Real>::lowest();\n    Real deviation = 1;\n\n    for (int train_data_index : indices_) {\n      int class_index = static_cast<int>(y_(train_data_index));\n      Real pred_score = x_(train_data_index);\n      Real z_new;\n\n      if (class_index == 0) {\n        z_new = deviation * sample_truncated_normal_right(\n                                rng, (gamma_now(class_index) - pred_score) /\n                                         deviation) +\n                pred_score;\n        zmaxs(0) = std::max(zmaxs(0), z_new);\n      } else if (class_index == (K - 1)) {\n        z_new =\n            deviation * sample_truncated_normal_left(\n                            rng, (gamma_now(K - 2) - pred_score) / deviation) +\n            pred_score;\n        zmins(K - 1) = std::min(zmins(K - 1), z_new);\n      } else {\n        z_new =\n            deviation *\n                sample_truncated_normal_twoside(\n                    rng, (gamma_now(class_index - 1) - pred_score) / deviation,\n                    (gamma_now(class_index) - pred_score) / deviation) +\n            pred_score;\n        zmins(class_index) = std::min(zmins(class_index), z_new);\n        zmaxs(class_index) = std::max(zmaxs(class_index), z_new);\n      }\n      x_(train_data_index) -= z_new;\n    }\n  }\n\n  inline void start_sample() {\n    DenseVector alpha_hat = DenseVector::Zero(K - 1);\n    find_minimum(alpha_hat);\n    alpha_now = alpha_hat;\n    alpha_to_gamma(gamma_now, alpha_now);\n  }\n\n  inline void sample_cutpoint_given_z() {\n    for (int i = 1; i <= (K - 3); i++) {\n      Real lower = zmaxs(i);\n      Real upper = zmins(i + 1);\n      gamma_now(i) = std::uniform_real_distribution<Real>(lower, upper)(rng);\n    }\n  }\n\n  inline void find_minimum(DenseVector &alpha_hat, bool verbose = false) {\n    int max_iter = 10000;\n    Real epsilon = 1e-5;\n    Real epsilon_rel = 1e-5;\n    Real delta = 1e-5;\n    int past = 3;\n    DenseVector history(past);\n    DenseVector alpha_new(alpha_hat);\n    DenseVector dalpha(alpha_hat);\n    DenseVector direction(alpha_hat);\n    Real ll_current;\n    bool first = true;\n    int i = 0;\n    while (true) {\n      if (first) {\n        ll_current = (*this)(alpha_hat, dalpha, &H);\n        if (verbose) {\n          print_to_stream(std::cout, \"ll_current = \", ll_current,\n                          \"\\ndalpha = \", dalpha);\n          std::cout << std::endl;\n        }\n      }\n      {\n\n        Real alpha2 = alpha_hat.norm();\n        Real dalpha2 = dalpha.norm();\n        if (verbose) {\n          print_to_stream(std::cout, \"ll = \", ll_current,\n                          \"\\nalpha_hat =\", alpha_hat);\n          std::cout << std::endl;\n\n          print_to_stream(std::cout, \"dalpha2 = \", dalpha2);\n          std::cout << std::endl;\n        }\n\n        if (dalpha2 < epsilon || dalpha2 < epsilon_rel * alpha2) {\n          break;\n        }\n      }\n\n      direction = -H.llt().solve(dalpha);\n      if (verbose) {\n        print_to_stream(std::cout, \"H = \", H);\n        std::cout << std::endl;\n\n        print_to_stream(std::cout, \"direction = \", direction);\n        std::cout << std::endl;\n      }\n\n      Real step_size = 1;\n      int lsc = 0;\n      while (true) {\n        alpha_new = alpha_hat + step_size * direction;\n        Real ll_new;\n        try {\n          ll_new = (*this)(alpha_new, dalpha, &H);\n        } catch (std::runtime_error) {\n          step_size /= 2;\n          continue;\n        }\n\n        if (ll_new >= (ll_current * (1 + delta))) {\n          step_size /= 2;\n        } else {\n          alpha_hat = alpha_new;\n          ll_current = ll_new;\n          break;\n        }\n        if (++lsc > 1000)\n          break;\n      }\n      first = false;\n      if (i >= past) {\n        Real past_loss = history(i % past);\n        if (std::abs(past_loss - ll_current) <=\n            delta *\n                std::max(std::max(abs(ll_current), abs(past_loss)), Real(1))) {\n          break;\n        }\n      }\n      history(i % past) = ll_current;\n      i++;\n      if (i >= max_iter)\n        break;\n    }\n    if (i == max_iter) {\n      throw std::runtime_error(\"Failed to converge. See fail-log.txt\");\n    }\n  }\n\n  inline bool step(bool verbose = false) {\n    DenseVector alpha_hat = alpha_now;\n    DenseVector gamma(alpha_hat);\n    find_minimum(alpha_hat, verbose);\n    DenseVector alpha_candidate = sample_mvt(H, nu) + alpha_hat;\n\n    Real ll_candidate, ll_old;\n    try {\n      ll_candidate = -(*this)(alpha_candidate, gamma);\n      ll_old = -(*this)(alpha_now, gamma);\n    } catch (std::runtime_error e) {\n      // should be NaN encounter\n      return false;\n    }\n    Real log_p_transition_candidate =\n        log_p_mvt(H, alpha_hat, nu, alpha_candidate);\n    Real log_p_transition_old = log_p_mvt(H, alpha_hat, nu, alpha_now);\n    Real test_ratio = std::exp(ll_candidate - log_p_transition_candidate -\n                               ll_old + log_p_transition_old);\n    Real u = std::uniform_real_distribution<Real>{0, 1}(rng);\n    if (u < test_ratio) {\n      alpha_now = alpha_candidate;\n      alpha_to_gamma(gamma_now, alpha_now);\n      accept_count++;\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  inline Real operator()(const DenseVector &alpha, DenseVector &dalpha,\n                         DenseMatrix *HessianTarget = nullptr) {\n    DenseVector gamma = DenseVector::Zero(alpha.rows());\n    dalpha.array() = 0;\n    alpha_to_gamma(gamma, alpha);\n\n    DenseMatrix dGammadAlpha = DenseMatrix(alpha.rows(), alpha.rows());\n    jacobian_dgamma_dalpha(dGammadAlpha, alpha);\n    Real ll = 0;\n    if (HessianTarget != nullptr) {\n\n      (*HessianTarget).array() = 0;\n    }\n    for (auto i : indices_) {\n      int label = y_(i);\n      if (label == 0) {\n        safe_lcdf(gamma(0) - x_(i), ll, dalpha(0), HessianTarget, label);\n      } else if (label == (K - 1)) {\n        safe_lccdf(gamma(K - 2) - x_(i), ll, dalpha(K - 2), HessianTarget,\n                   label);\n      } else {\n        safe_ldiff(gamma(label) - x_(i), gamma(label - 1) - x_(i), ll,\n                   dalpha(label), dalpha(label - 1), HessianTarget, label);\n      }\n    }\n\n    if (HessianTarget != nullptr) {\n      DenseMatrix &H = (*HessianTarget);\n      DenseVector expAlpha(alpha.array().exp().matrix());\n      H = dGammadAlpha * H * dGammadAlpha.transpose();\n      {\n        // m = 0\n        // gamma 0 = alpha_0 does not contribute\n        // since \\partial^2 gamma_0 / \\partial alpha_i \\partial alpha_j = 0 for\n        // all gamma_m = alpha_0 + \\sum _{s=1}^{m}(exp\\alpha_s)\n        for (int m = 1; m < (K - 1); m++) {\n          { // i =0, j > 0\n            for (int j = 1; j <= m; j++) {\n              H(j, j) += dalpha(m) * expAlpha(j);\n            }\n          }\n        }\n      }\n      H(0, 0) -= reg;\n      for (int m = 1; m < (K - 1); m++) {\n        H(m, m) -= reg;\n      }\n      H.array() *= -1;\n      if (H.hasNaN()) {\n        fail_dump();\n        throw std::runtime_error(print_to_string(\n            __FILE__, \":\", __LINE__, \" H has NaN, alpha = \", alpha));\n      }\n    }\n    if (fix_gamma0) {\n      dalpha(0) = 0;\n      if (HessianTarget != nullptr) {\n        (*HessianTarget).row(0).array() = 0;\n        (*HessianTarget).col(0).array() = 0;\n        (*HessianTarget)(0, 0) = 1;\n      }\n    }\n    dalpha = -dGammadAlpha * dalpha;\n    if (dalpha.hasNaN()) {\n      fail_dump();\n      throw std::runtime_error(print_to_string(\n          __FILE__, \":\", __LINE__, \" dalpha has NaN, alpha = \", alpha));\n    }\n\n    dalpha(0) += reg * alpha(0);\n    ll -= 0.5 * reg * alpha(0) * alpha(0);\n    for (int m = 1; m < (K - 1); m++) {\n      dalpha(m) += reg * alpha(m);\n      ll -= 0.5 * reg * alpha(m) * alpha(m);\n    }\n    return -ll;\n  }\n\n  template <class ostype> inline void show_info(ostype &os) {\n    os << \"{\\\"xs\\\": [\";\n    bool first = true;\n    for (auto i : indices_) {\n      if (!first)\n        os << \", \";\n      os << x_[i];\n      first = false;\n    }\n    os << \"], \\\"ys\\\":[\";\n    first = true;\n    for (auto i : indices_) {\n      if (!first)\n        os << \", \";\n      os << y_[i];\n      first = false;\n    }\n    os << \"]}\";\n  }\n\n  inline void fail_dump() {\n    std::ofstream fail_log(\"fail-log.json\");\n    show_info(fail_log);\n  }\n\n  DenseVector &x_;\n  const DenseVector &y_;\n\n  int K;\n  const std::vector<size_t> indices_;\n  Real tune = 1;\n  Real reg;\n  Real nu;\n  std::mt19937 &rng;\n  DenseVector alpha_now;\n  DenseVector gamma_now;\n  DenseMatrix H;\n  static constexpr bool fix_gamma0 = false;\n  DenseVector zmins, zmaxs;\n  std::vector<size_t> histogram;\n  size_t accept_count;\n};\n\n} // namespace myFM", "meta": {"hexsha": "25de49009c473e90ec11f6e082d425d89f63f205", "size": 17257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/myfm/OProbitSampler.hpp", "max_stars_repo_name": "devanshusomani99/myFM", "max_stars_repo_head_hexsha": "d8e3d93de7c4a3dc19551c07d5f1d71d13f6abc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2019-12-27T01:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:48:56.000Z", "max_issues_repo_path": "include/myfm/OProbitSampler.hpp", "max_issues_repo_name": "devanshusomani99/myFM", "max_issues_repo_head_hexsha": "d8e3d93de7c4a3dc19551c07d5f1d71d13f6abc6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-03-13T00:59:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T19:29:34.000Z", "max_forks_repo_path": "include/myfm/OProbitSampler.hpp", "max_forks_repo_name": "devanshusomani99/myFM", "max_forks_repo_head_hexsha": "d8e3d93de7c4a3dc19551c07d5f1d71d13f6abc6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-09-01T16:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T15:18:34.000Z", "avg_line_length": 32.5603773585, "max_line_length": 79, "alphanum_fraction": 0.533348786, "num_tokens": 4937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5895014699030999}}
{"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 \"JordanMatrix.h\"\n#include \"MatrixToString.h\"\n\nnamespace abstract{\n\ntemplate <class scalar>\nscalar  JordanMatrix<scalar>::ms_half(0.5);\n\ntemplate <class scalar>\nscalar  JordanMatrix<scalar>::ms_one(1);\n\ntemplate <class scalar>\nscalar  JordanMatrix<scalar>::ms_two(2);\n\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::complexS JordanMatrix<scalar>::ms_complexOne(1,0);\n\ntemplate <class scalar>\nMatToStr<scalar>  JordanMatrix<scalar>::ms_logger(true);\n\ntemplate <class scalar>\nMatToStr<scalar>  JordanMatrix<scalar>::ms_decoder(false);\n\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS JordanMatrix<scalar>::ms_emptyMatrix(0,0);\n\ntemplate <class scalar>\ntraceDynamics_t JordanMatrix<scalar>::ms_trace_dynamics=eTraceNoDynamics;\n\ntemplate <class scalar>\nbool JordanMatrix<scalar>::ms_trace_time=false;\n\n/// Constructs an empty matrix\ntemplate <class scalar>\nJordanMatrix<scalar>::JordanMatrix(int dimension) :\n  m_dimension(dimension),\n  m_zero(func::ms_weakZero),\n  m_largeZero(dimension*dimension*func::ms_weakZero),\n  m_dynamics(dimension,dimension),\n  m_refDynamics(dimension,dimension),\n  m_eigenSpace(dimension),\n  m_minSeparation(dimension,1),\n  m_jordanTime(0)\n{\n  m_pseudoEigenVectors=MatrixS(m_dimension,m_dimension);\n  m_invPseudoEigenVectors=MatrixS(m_dimension,m_dimension);\n}\n\n/// Changes the default dimension of the system\ntemplate <class scalar>\nvoid JordanMatrix<scalar>::changeDimensions(const int dimension)\n{\n  if (dimension!=m_dimension) {\n    m_dimension=dimension;\n    m_dynamics.conservativeResize(dimension,dimension);\n    m_minSeparation.conservativeResize(dimension,1);\n    m_refDynamics.resize(dimension,dimension);\n    m_pseudoEigenVectors.resize(dimension,dimension);\n    m_invPseudoEigenVectors.resize(dimension,dimension);\n  }\n}\n\n/// Loads a matrix from a given description\ntemplate <class scalar>\nint JordanMatrix<scalar>::load(const std::string &data,size_t pos)\n{\n  int result=ms_logger.StringToMat(m_dynamics,data,pos);\n  //changeDimensions(m_dynamics.rows());\n  if ((result>0) && !calculateJordanForm()) return -1;\n  return result;\n}\n\ntemplate <class scalar>\nbool JordanMatrix<scalar>::loadFromRef(const MatrixR &matrix)\n{\n  changeDimensions(matrix.rows());\n  for (int row=0;row<matrix.rows();row++) {\n    for (int col=0;col<matrix.cols();col++) {\n      m_dynamics.coeffRef(row,col)=matrix.coeff(row,col);\n    }\n  }\n  return calculateJordanForm();\n}\n\ntemplate <class scalar>\nbool JordanMatrix<scalar>::load(const MatrixS &dynamics)\n{\n  changeDimensions(dynamics.rows());\n  m_dynamics=dynamics;\n  return calculateJordanForm();\n}\n\ntemplate <class scalar>\nbool JordanMatrix<scalar>::loadJordan(const MatrixS &matrix)\n{\n  boost::timer timer;\n  changeDimensions(matrix.rows());\n  m_dynamics=matrix;\n  m_zero=calculateEpsilon(m_dynamics);\n  func::setZero(m_zero);\n  m_largeZero=m_zero*m_dimension*m_dimension;\n  interToRef(m_refDynamics,m_dynamics);\n  m_pseudoEigenValues=m_dynamics;\n  m_pseudoEigenVectors=MatrixS::Identity(m_dimension,m_dimension);\n  m_invPseudoEigenVectors=m_pseudoEigenVectors;\n  m_hasOnes=false;\n  m_hasMultiplicities=false;\n  m_isOne.resize(2*m_dimension);\n  m_conjugatePair.resize(2*m_dimension);\n  m_jordanIndex.resize(2*m_dimension);\n  for (int i=0;i<m_dimension;i++) {\n    m_conjugatePair[i]=-1;\n    m_conjugatePair[i+m_dimension]=-1;\n    if ((i<m_dimension-1) && !func::isZero(m_dynamics.coeff(i,i+1))) m_conjugatePair[i]=i+1;\n    else if ((i>0) && !func::isZero(m_dynamics.coeff(i-1,i)))        m_conjugatePair[i]=i-1;\n    int mult=(m_conjugatePair[i]<0) ? 1 : 2;\n    m_jordanIndex[i]=0;\n    if ((i>=mult) && !func::isZero(m_dynamics.coeff(i,i-mult))) m_jordanIndex[i-mult]+1;\n    m_jordanIndex[i+m_dimension]=0;\n    if (m_jordanIndex[i]>0) m_hasMultiplicities=true;\n    m_isOne[i]=func::isZero(ms_one-m_dynamics.coeff(i,i)) && (m_conjugatePair[i]<0);\n    m_hasOnes|=m_isOne[i];\n  }\n  m_eigenValues=pseudoToJordan(m_pseudoEigenValues,eToEigenValues);\n  m_eigenNorms.resize(m_eigenValues.rows(),1);\n  for (int i=0;i<m_eigenValues.rows();i++) m_eigenNorms.coeffRef(i,0)=func::norm2(m_eigenValues.coeff(i,i));\n  m_eigenVectors=MatrixC::Identity(m_dimension,m_dimension);\n  m_invEigenVectors=m_eigenVectors;\n  m_error=func::ms_hardZero;\n  m_jordanTime=timer.elapsed()*1000;\n  if (ms_trace_time) ms_logger.logData(m_jordanTime,\"Pole Extraction time:\",true);\n  return true;\n}\n\n/// calculates the estimated roundoff error of a matrix operation\ntemplate <class scalar>\ntemplate <class MatrixType> inline typename JordanMatrix<scalar>::refScalar JordanMatrix<scalar>::calculateEpsilon(const MatrixType &matrix)\n{\n  if (matrix.rows()>0) {\n    refScalar max=func::toUpper(func::norm2(matrix.coeff(0,0)));\n    refScalar min=func::toLower(func::norm2(matrix.coeff(0,0)));\n    for (int row=0;row<matrix.rows();row++) {\n      for (int col=0;col<matrix.cols();col++) {\n        refScalar upper=func::toUpper(func::norm2(matrix.coeff(row,col)));\n        refScalar lower=func::toLower(func::norm2(matrix.coeff(row,col)));\n        if (upper>max) max=upper;\n        if (lower<min) min=lower;\n      }\n    }\n    //scalar max=matrix.maxCoeff();\n    //scalar min=matrix.minCoeff();\n    if (-min>max) max=-min;\n    return max*func::ms_weakEpsilon;\n  }\n  return 0;\n}\n\n/// Loads the transformation matrix for the state space\ntemplate <class scalar>\nbool JordanMatrix<scalar>::calculateJordanForm(bool includeSvd)\n{\n  boost::timer timer;\n  m_zero=calculateEpsilon(m_dynamics);\n  func::setZero(m_zero);\n  m_largeZero=m_zero*m_dimension*m_dimension;\n  interToRef(m_refDynamics,m_dynamics);\n\n  m_eigenSpace.computeJordan(m_refDynamics);\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Jordan Form:\",true);\n  if (m_eigenSpace.info()!=Eigen::Success) {\n    if (ms_trace_dynamics>=eTraceDynamics) ms_logger.logData(\"Failed to find Jordan Form\");\n    return false;\n  }\n  refToInter(m_eigenValues,m_eigenSpace.getEigenValues());\n  refToInter(m_eigenVectors,m_eigenSpace.getEigenVectors());\n\n  m_jordanIndex=m_eigenSpace.getJordanIndeces();\n  m_conjugatePair=m_eigenSpace.getConjugatePairs();\n  m_isOne=m_eigenSpace.getOnes();\n  m_hasOnes=m_eigenSpace.hasOnes();\n  m_hasMultiplicities=m_eigenSpace.hasMultiplicities();\n  m_eigenNorms.resize(m_eigenValues.rows(),1);\n  for (int i=0;i<m_eigenValues.rows();i++) m_eigenNorms.coeffRef(i,0)=func::norm2(m_eigenValues.coeff(i,i));\n  try {\n    m_invEigenVectors=m_eigenVectors.inverse();\n  }\n  catch(...) {\n    refToInter(m_invEigenVectors,m_eigenSpace.getEigenVectors().inverse());\n  }\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(m_dynamics,\"Dynamics:\");\n    ms_logger.logData(m_eigenValues,\"EigenValues:\");\n    ms_logger.logData(m_eigenVectors,\"EigenVectors:\");\n    ms_logger.logData(m_invEigenVectors,\"InvEigenVectors:\");\n  }\n\n  m_pseudoEigenValues=jordanToPseudoJordan(m_eigenValues,eToEigenValues);\n  m_pseudoEigenVectors=jordanToPseudoJordan(m_eigenVectors,eToEigenVectors);\n  m_invPseudoEigenVectors=m_pseudoEigenVectors.inverse();\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    MatrixS pseudoCalculated=m_pseudoEigenVectors*m_pseudoEigenValues*m_invPseudoEigenVectors;\n    ms_logger.logData(m_pseudoEigenValues,\"PseudoEigenValues\");\n    ms_logger.logData(m_pseudoEigenVectors,\"PseudoEigenVectors\");\n    ms_logger.logData(m_invPseudoEigenVectors,\"InvPseudoEigenVectors\");\n    ms_logger.logData(pseudoCalculated,\"PseudoCalc\");\n  }\n  if (includeSvd) {\n    calculateBlockSVD();\n    m_minSigma=func::toLower(m_blockSingularValues.coeff(0,0));\n    m_maxSigma=func::toUpper(m_blockSingularValues.coeff(0,0));\n    for (int row=1;row<m_blockSingularValues.rows();row++) {\n      if (func::toUpper(m_blockSingularValues.coeff(row,0))>m_maxSigma) {\n        m_maxSigma=func::toUpper(m_blockSingularValues.coeff(row,0));\n      }\n      if (func::toLower(m_blockSingularValues.coeff(row,0))<m_minSigma) {\n        m_minSigma=func::toLower(m_blockSingularValues.coeff(row,0));\n      }\n    }\n    m_jordanTime=timer.elapsed()*1000;\n    if (ms_trace_time) ms_logger.logData(m_jordanTime,\"SVD time:\",true);\n  }\n  calculateEigenError();\n  m_jordanTime=timer.elapsed()*1000;\n  if (ms_trace_time) ms_logger.logData(m_jordanTime,\"Jordan Error time:\",true);\n  for (int row=0;row<m_invPseudoEigenVectors.rows();row++) {\n    for (int col=0;col<m_invPseudoEigenVectors.cols();col++) {\n      if (func::isNan(m_invPseudoEigenVectors.coeff(row,col))) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/// Retrieves an equivalent real Jordan from a complex representation\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS JordanMatrix<scalar>::jordanToPseudoJordan(const MatrixC &source,const pseudoType_t conversionType)\n{\n  MatrixS result=source.real();\n  if (conversionType==eToEigenValues) {\n    for (int col=0;col<source.rows();col++) {\n      if (m_conjugatePair[col]>col) {\n        result.coeffRef(col+1,col)=-source.coeff(col,col).imag();\n        result.coeffRef(col,col+1)=source.coeff(col,col).imag();\n        for (int offset=1;offset<=m_jordanIndex[col];offset++) {\n          int row=col-2*offset;\n          result.coeffRef(row+1,col)=-source.coeff(row,col).imag();\n          result.coeffRef(row,col+1)=source.coeff(row,col).imag();\n        }\n        col++;\n      }\n    }\n  }\n  else if (conversionType==eToEigenVectors) {\n    for (int col=0;col<source.cols();col++) {\n      if (m_conjugatePair[col]>col) {\n        result.col(col+1)=source.col(col).imag();\n        col++;\n      }\n    }\n  }\n  else {\n      for (int row=0;row<source.rows();row++) {\n        if (m_conjugatePair[row]>row) {\n          result.row(row+1)=source.row(row).imag();\n          row++;\n        }\n      }\n  }\n  return result;\n}\n\n/// Retrieves an equivalent complex Jordan from a real representation\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixC JordanMatrix<scalar>::pseudoToJordan(const MatrixS &source,const pseudoType_t conversionType)\n{\n  MatrixC result=MatrixC::Zero(source.rows(),source.cols());\n  if (conversionType==eToEigenValues) {\n    int mult=1;\n    for (int row=0;row<source.rows();row+=mult) {\n      mult=(m_conjugatePair[row]<0) ? 1 : 2;\n      if (m_jordanIndex[row+mult]>0) {\n        if (m_conjugatePair[row]<0) {\n          result.coeffRef(row,row)=complexS(source.coeff(row,row),func::ms_hardZero);\n        }\n        else {\n          result.coeffRef(row,row)=complexS(source.coeff(row,row),source.coeff(row,row+1));\n          result.coeffRef(row+1,row+mult+1)=ms_complexOne;\n        }\n        result.coeffRef(row,row+mult)=ms_complexOne;\n      }\n      else {\n        result.coeffRef(row,row)=complexS(source.coeff(row,row),source.coeff(row,row+1));\n      }\n    }\n  }\n  else if (conversionType==eToEigenVectors) {\n    for (int col=0;col<source.cols();col++) {\n      result.col(col).real()=source.col(col);\n      if (m_conjugatePair[col]>col) {\n        result.col(col).imag()=source.col(col+1);\n        col++;\n        result.col(col).real()=source.col(col-1);\n        result.col(col).imag()=-source.col(col);\n      }\n    }\n  }\n  else {\n    for (int row=0;row<source.rows();row++) {\n      result.row(row).real()=source.row(row);\n      if (m_conjugatePair[row]>row) {\n        result.row(row).imag()=source.row(row+1);\n        row++;\n        result.row(row).real()=source.row(row-1);\n        result.row(row).imag()=-source.row(row);\n      }\n    }\n  }\n  return result;\n}\n\n/// Retrieves a scalar matrix from a refScalar one\ntemplate <class scalar>\nvoid JordanMatrix<scalar>::interToRef(SolverMatrixType &dest,const MatrixS &source)\n{\n  dest.conservativeResize(source.rows(),source.cols());\n  for (int row=0;row<source.rows();row++) {\n    for (int col=0;col<source.cols();col++) {\n      refScalar coef=func::toCentre(source.coeff(row,col));\n      dest.coeffRef(row,col)=coef;\n    }\n  }\n}\n\n/// Retrieves a scalar matrix from a refScalar one\ntemplate <class scalar>\nvoid JordanMatrix<scalar>::refToInter(MatrixC &dest,const SolverComplexMatrixType &source)\n{\n  dest.conservativeResize(source.rows(),source.cols());\n  for (int row=0;row<source.rows();row++) {\n    for (int col=0;col<source.cols();col++) {\n      dest.coeffRef(row,col)=func::toScalar(source.coeff(row,col));\n    }\n  }\n}\n\n/// Retrieves a scalar matrix from a refScalar one\ntemplate <class scalar>\nvoid JordanMatrix<scalar>::refToInter(MatrixS &dest,const SolverMatrixType &source)\n{\n  dest.conservativeResize(source.rows(),source.cols());\n  for (int row=0;row<source.rows();row++) {\n    for (int col=0;col<source.cols();col++) {\n      dest.coeffRef(row,col)=source.coeff(row,col);\n    }\n  }\n}\n\n/// Transforms the matrix to Reduced Row Echelon Form\ntemplate <class scalar>\nint JordanMatrix<scalar>::toRREF(MatrixC &matrix)\n{\n  int rank=m_dimension;\n  int col=0;\n  for (int row=0;col<matrix.rows();row++,col++) {\n    while (func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) {\n      for (int row2=row+1;row2<matrix.rows();row2++) {\n        if (!func::isZero(func::norm2(matrix.coeff(row2,col)),m_zero)) {\n          matrix.row(row)+=matrix.row(row2);\n          break;\n        }\n      }\n      if (func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) {\n        col++;\n        if (col==matrix.rows()) break;\n      }\n    }\n    if (col==matrix.rows()) break;\n    complexR multiplier=func::toCentre(matrix.coeff(row,col));\n    if (!func::isZero(func::norm2(multiplier),m_zero)) {\n      for (int col2=0;col2<matrix.cols();col2++) matrix.coeffRef(row,col2)/=multiplier;\n      rank--;\n    }\n    for (int row2=row+1;row2<matrix.rows();row2++) {\n      complexS multiplier=matrix.coeff(row2,col);\n      matrix.row(row2)-=multiplier*matrix.row(row);\n    }\n  }\n  col=0;\n  for (int row=1;(row<matrix.rows()) && (col<matrix.cols());row++) {\n    while ((col<matrix.cols()) && func::isZero(func::norm2(matrix.coeff(row,col)),m_zero)) col++;\n    if (col<matrix.cols()) {\n      for (int row2=0;row2<row;row2++) {\n        if (!func::isZero(func::norm2(matrix.coeff(row2,col)),m_zero)) {\n          complexS multiplier=matrix.coeff(row2,col);\n          matrix.row(row2)-=multiplier*matrix.row(row);\n        }\n      }\n    }\n  }\n  return rank;\n}\n\n/// Returns the description of a complex matrix\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getMatrix(const MatrixC &matrix,bool brackets)\n{\n  if (brackets) return ms_logger.MatToString(matrix);\n  return ms_decoder.MatToString(matrix);\n}\n\n/// Returns the description of a matrix\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getMatrix(const MatrixS &matrix,bool brackets)\n{\n  if (brackets) return ms_logger.MatToString(matrix);\n  return ms_decoder.MatToString(matrix);\n}\n\n/// Returns the complex eigenvector matrix (S)\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getEigenVectorsDesc(bool pseudo)\n{\n  if (pseudo) return getMatrix(m_pseudoEigenVectors,false);\n  return getMatrix(m_eigenVectors,false);\n}\n\n/// Returns the singular values of the matrix\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getSingularValuesDesc()\n{\n  return getMatrix(m_blockSingularValues,false);\n}\n\n/// Returns the inverse complex eigenvector matrix (S^-1)\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getInvEigenVectorsDesc(bool pseudo)\n{\n  if (pseudo) return getMatrix(m_invPseudoEigenVectors,false);\n  return getMatrix(m_invEigenVectors,false);\n}\n\n/// Returns the schur decomposition of the dynamics\ntemplate <class scalar>\nstd::string JordanMatrix<scalar>::getSJinvS()\n{\n  MatrixC matrix=m_eigenVectors;\n  std::string result=getMatrix(matrix);\n  result+=getMatrix(m_eigenValues);\n  matrix=m_eigenVectors.inverse();\n  result+=getMatrix(matrix);\n  return result;\n}\n\n/// Retrieves the inverse of the dynamics\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS JordanMatrix<scalar>::getPseudoInverse(const MatrixS &matrix,bool &hasInverse)\n{\n  load(matrix);\n  MatrixC diag=m_eigenValues;\n  hasInverse=true;\n  for (int i=0;i<m_dimension;i++) {\n    char sign=func::hardSign(func::norm2(diag.coeff(i,i)));\n    if (sign!=0) {\n      diag.coeffRef(i,i)=ms_complexOne/diag.coeff(i,i);\n      for (int j=1;j<=m_jordanIndex[i];j++) {\n        diag.coeffRef(i-j,i)=-func::c_pow(-diag.coeffRef(i,i),j+1);\n      }\n    }\n    else hasInverse=false;\n  }\n  if (hasInverse) return m_dynamics.inverse();\n  diag=m_invEigenVectors*diag*m_eigenVectors;\n  return diag.real();\n}\n\n/// Calculates the pseudoinverse of a matrix\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS JordanMatrix<scalar>::getSVDpseudoInverse(const MatrixS &matrix,bool &hasInverse)\n{\n  interToRef(m_refDynamics,matrix);\n  m_svdSpace.compute(m_refDynamics, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  SolverMatrixType d=m_svdSpace.singularValues().asDiagonal();\n  SolverMatrixType u=m_svdSpace.matrixU();\n  SolverMatrixType v=m_svdSpace.matrixV();\n  MatrixS diag;\n  MatrixS matrixU;\n  MatrixS matrixV;\n  refToInter(diag,d);\n  refToInter(matrixU,u);\n  refToInter(matrixV,v);\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(matrix,\"Inverse:\");\n    ms_logger.logData(matrixU);\n    ms_logger.logData(diag);\n    ms_logger.logData(matrixV);\n  }\n  for (int i=0;i<matrix.rows();i++) {\n    if (func::isZero(diag.coeff(i,i))) hasInverse=false;\n    else diag.coeffRef(i,i)=scalar(1)/diag.coeff(i,i);\n  }\n  if (matrix.rows()!=matrix.cols()) {\n    diag.conservativeResize(matrixV.cols(),matrixU.rows());\n    if (matrixV.cols()>matrixU.rows()) {\n      diag.block(matrixU.rows(),0,matrixV.cols()-matrixU.rows(),matrixU.rows())=MatrixS::Zero(matrixV.cols()-matrixU.rows(),matrixU.rows());\n    }\n    else {\n      diag.block(0,matrixV.cols(),matrixV.cols(),matrixU.rows()-matrixV.cols())=MatrixS::Zero(matrixV.cols(),matrixU.rows()-matrixV.cols());\n    }\n    hasInverse=false;\n  }\n  if (hasInverse) return matrix.inverse();\n  return matrixV*diag*matrixU.adjoint();\n}\n\n/// Calculates a lower bound for the minimum separation between any two jordan blocks\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::refScalar JordanMatrix<scalar>::calculateMinSeparation()\n{\n  MatrixS base;\n  refToInter(base,m_eigenSpace.getSchur());\n  scalar nonDiagNorm2=0;\n  for (int row=0;row<m_dimension-1;row++) {\n    if (m_conjugatePair[row]<row) nonDiagNorm2+=func::squared(base.coeff(row,row+1));//*base.coeff(row,row+1);\n    for (int col=row+2;col<m_dimension;col++) {\n      nonDiagNorm2+=func::squared(base.coeff(row,col));//*base.coeff(row,col);\n    }\n  }\n  scalar dimension=m_dimension;\n  scalar factor=sqrt(func::pow((dimension-ms_one)/dimension,m_dimension-1));\n  factor*=sqrt(func::pow(ms_two,(m_dimension-1)*(m_dimension+1)));//The smallest col/row is ignored\n\n  for (int i=0;i<m_dimension;i++) {\n    scalar diagNorm2=0;\n    scalar det=ms_one;\n    int mult=(m_conjugatePair[i]<0) ? 1 : 2;\n    m_minSeparation.coeffRef(i,0)=func::toLower(func::norm2(m_eigenValues.coeff(i,i)));\n    for (int j=0;j<m_dimension;j++) {\n      if (i+mult*m_jordanIndex[j]==j) continue;\n      scalar sep=func::norm2(m_eigenValues.coeff(i,i)-m_eigenValues.coeff(j,j));\n      det*=sep;\n      diagNorm2+=func::squared(sep);//*sep;\n    }\n    if (func::toLower(det)==0) func::imprecise(det,func::ms_hardZero);\n    diagNorm2+=nonDiagNorm2;\n    scalar maxColOrRowProd=func::pow(sqrt(diagNorm2),m_dimension-1);\n    while (m_jordanIndex[i+mult]>0) i+=mult;\n    if (m_jordanIndex[i]>0) {\n      maxColOrRowProd*=func::pow(dimension,m_dimension);\n      m_minSeparation.coeffRef(i,0)=func::toLower(factor*func::pow(det,m_jordanIndex[i])/maxColOrRowProd);\n      for (int j=0;j<m_jordanIndex[i]*mult;j++) m_minSeparation.coeffRef(i-j,0)=m_minSeparation.coeffRef(i,0);\n    }\n    else m_minSeparation.coeffRef(i,0)=func::toLower(factor*det/maxColOrRowProd);\n    if (m_conjugatePair[i]>i) {\n      m_minSeparation.coeffRef(i+1,0)=m_minSeparation.coeffRef(i,0);\n      i++;\n    }\n  }\n  return m_minSeparation.minCoeff();\n}\n\n/// Calculates the maximum error for the numerical approximation of the eigencvalues\ntemplate <class scalar>\nscalar JordanMatrix<scalar>::calculateEigenError()\n{\n  scalar kP=m_pseudoEigenVectors.norm()*m_invPseudoEigenVectors.norm();\n  MatrixS calculated=m_pseudoEigenVectors*m_pseudoEigenValues*m_invPseudoEigenVectors;\n  if (ms_trace_dynamics>=eTraceErrors) ms_logger.logData(calculated,\"Calculated:\");\n  calculated-=m_dynamics;\n  scalar errorNorm=calculated.norm();\n  m_error=errorNorm*kP;\n  if (func::toUpper(m_error)>m_zero) func::imprecise(m_error,m_zero);\n\n  m_boundForError=0;\n  if (m_hasMultiplicities) return m_error;\n\n  if (ms_trace_dynamics>=eTraceErrors) ms_logger.logData(m_error,\"Error:\",true);\n  m_error=func::setpm(m_error);\n  complexS complexError=m_error;\n  for (int i=0;i<m_dimension;i++) {\n    m_eigenValues.coeffRef(i,i)+=complexError;\n//    m_eigenValues.coeffRef(i,i).real()+=m_error;\n//    if (m_conjugatePair[i]>=0) m_eigenValues.coeffRef(i,i).imag()+=m_error;\n  }\n  m_pseudoEigenValues=jordanToPseudoJordan(m_eigenValues,eToEigenValues);\n\n  calculateMinSeparation();\n  for (int i=0;i<m_dimension;i++) {\n    if (m_minSeparation.coeff(i,0)>0) {\n      scalar angleError=errorNorm/m_minSeparation.coeff(i,0);\n      scalar cosTheta=func::toLower(func::cosine(angleError));\n      scalar invCosTheta=ms_one/cosTheta;\n      scalar vError=func::getHull(cosTheta,invCosTheta);\n      m_eigenVectors.col(i)*=vError;\n    }\n  }\n  m_pseudoEigenVectors=jordanToPseudoJordan(m_eigenVectors,eToEigenVectors);\n  m_invPseudoEigenVectors=m_pseudoEigenVectors.inverse();//jordanToPseudoJordan(m_invEigenVectors,eToInvEigenVectors);\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    ms_logger.logData(m_pseudoEigenValues,\"PseudoEigenValues\");\n    ms_logger.logData(m_pseudoEigenVectors,\"PseudoEigenVectors\");\n    ms_logger.logData(m_invPseudoEigenVectors,\"InvPseudoEigenVectors\");\n  }\n  return m_error;\n}\n\n/// Calculates the maximum error for the numerical approximation of the matrix to the nth power\n/// @return the maximum variation of the eigenvalues\ntemplate <class scalar>\nscalar JordanMatrix<scalar>::calculateBoundedEigenError(scalar iteration)\n{\n  if (func::isNegative(iteration)) iteration=-iteration;\n  if (func::isZero(iteration-m_boundForError)) return m_error;\n  m_pseudoEigenVectors=jordanToPseudoJordan(m_eigenVectors,eToEigenVectors);\n  m_invPseudoEigenVectors=m_pseudoEigenVectors.inverse();//jordanToPseudoJordan(m_invEigenVectors,eToInvEigenVectors);\n  if (ms_trace_dynamics>=eTraceDynamics) {\n      ms_logger.logData(m_pseudoEigenVectors,\"S\");\n      ms_logger.logData(m_pseudoEigenValues,\"J\");\n      ms_logger.logData(m_invPseudoEigenVectors,\"invS\");\n  }\n  MatrixS calculated=m_pseudoEigenVectors*m_pseudoEigenValues*m_invPseudoEigenVectors;\n  if (ms_trace_dynamics>=eTraceErrors) ms_logger.logData(calculated,\"Calculated\");\n  MatrixS jordanError=m_invPseudoEigenVectors*m_dynamics*m_pseudoEigenVectors;\n  if (ms_trace_dynamics>=eTraceErrors) ms_logger.logData(jordanError,\"Calculated Jordan\");\n  jordanError-=m_pseudoEigenValues;\n  if (ms_trace_dynamics>=eTraceErrors) ms_logger.logData(jordanError,\"Jordan Error\");\n  m_error=jordanError.norm();\n  scalar theta=acos((ms_one-m_error)/(ms_one+m_error));\n  scalar nTheta=iteration*theta;\n  if (func::toUpper(nTheta)>m_zero) func::imprecise(nTheta,m_zero);\n  scalar cosn=func::toLower(func::cosine(nTheta));\n  scalar invCosN=ms_one/cosn;\n  scalar vError=func::getHull(cosn,invCosN);\n  m_pseudoEigenVectors*=vError;\n  m_invPseudoEigenVectors=m_pseudoEigenVectors.inverse();\n  return m_error;\n}\n\n/// Calculates the singular values\ntemplate <class scalar>\nbool JordanMatrix<scalar>::calculateSVD()\n{\n  boost::timer timer;\n  MatrixS dynamicsSq=m_dynamics*m_dynamics.transpose();\n  interToRef(m_refDynamics,dynamicsSq);\n  m_eigenSpace.computeJordan(m_refDynamics);\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Full Svd:\",true);\n  if (m_eigenSpace.info()!=Eigen::Success) return false;\n  MatrixS singularValues,singularVectors,inverseVectors;\n  refToInter(singularValues,m_eigenSpace.getEigenValues().real());\n  refToInter(singularVectors,m_eigenSpace.getEigenVectors().real());\n  inverseVectors=singularVectors.inverse();\n  scalar kP=singularVectors.norm()*inverseVectors.norm();\n  dynamicsSq-=singularVectors*singularValues*singularVectors.inverse();\n  scalar error=dynamicsSq.norm()*kP;\n  if (func::toUpper(m_error)>m_zero) func::imprecise(m_error,m_zero);\n  error=func::setpm(error);\n  for (int i=0;i<m_dimension;i++) {\n    singularValues.coeffRef(i,i)+=error;\n    singularValues.coeffRef(i,i)=sqrt(singularValues.coeff(i,i));\n  }\n  return true;\n}\n\n/// Calculates the singular values for each Jordan Block\ntemplate <class scalar>\nvoid JordanMatrix<scalar>::calculateBlockSVD()\n{\n  m_blockSingularValues.resize(m_dimension,2);\n  for (int row=m_dimension-1;row>=0;row--) {\n    if (m_jordanIndex[row]>0) {\n      int blockSize=(m_jordanIndex[row]+1);\n      MatrixR jordanBlock=MatrixR::Zero(m_dimension,m_dimension);\n      jordanBlock.coeffRef(0,0)=func::toUpper(m_eigenNorms.coeff(row,0));\n      for (int i=1;i<blockSize;i++) {\n        jordanBlock.coeffRef(i,i)=jordanBlock.coeff(0,0);\n        jordanBlock.coeffRef(i,i-1)=1;\n      }\n      m_svdSpace.compute(jordanBlock);\n      scalar norm=m_svdSpace.singularValues().coeff(0)*(ms_one+m_dimension*m_dimension*Eigen::NumTraits<refScalar>::epsilon());\n      if (m_conjugatePair[row]>=0) blockSize*=2;\n      for (int j=0;j<blockSize;j++) m_blockSingularValues.coeffRef(row--,0)=norm;\n      row++;\n    }\n    else {\n      m_blockSingularValues.coeffRef(row,0)=m_eigenNorms.coeff(row,0);\n    }\n  }\n  m_blockSingularValues.col(1)=MatrixS::Ones(m_dimension,1);\n  for (int row=1;row<m_dimension;row++) {\n    if (m_jordanIndex[row]>0)\n    {\n      int mult=(m_conjugatePair[row]>=0) ? 2 : 1;\n      m_blockSingularValues.coeffRef(row,1)=m_blockSingularValues.coeff(row-mult,1)/(this->ms_one-norm(m_eigenValues.coeff(row,row)));\n      m_blockSingularValues.coeffRef(row-mult*m_jordanIndex[row],1)+=m_blockSingularValues.coeff(row,1);\n    }\n  }\n}\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class JordanMatrix<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class JordanMatrix<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class JordanMatrix<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class JordanMatrix<mpinterval>;\n  #endif\n#endif\n}\n", "meta": {"hexsha": "cf799c90ba1d54f42ff1f297d9537021447f6b34", "size": 26389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/JordanMatrix.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/JordanMatrix.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/JordanMatrix.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": 36.2984869326, "max_line_length": 140, "alphanum_fraction": 0.7174959263, "num_tokens": 7269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5895014654177662}}
{"text": "#pragma once\n///@file simpleClusterization.hpp\n///@brief This is a simple library that provides basic functionality to clusterize data according to either kmeans or fuzzy cmeans algorithms\n\n#include <Eigen/Dense>\n#ifndef FCM_MAX_ITERATIONS\n///The maximum number of iterations to do if the algorithm doesn't otherwise converge\n//@note It's wrapped in an #ifndef to allow the user to override it at compile time\n#define FCM_MAX_ITERATIONS  20\n#endif\n\n#ifndef FCM_THRESHOLD\n///The threshold below which real numbers are deemed identical, used to avoid infinite weights and determine when the algorithm has converged\n//@note It's wrapped in an #ifndef to allow the user to override it at compile time\n#define FCM_THRESHOLD   1.0E-19\n#endif\n\n#include <simpleClusterization_common.hpp>\nusing namespace Eigen;\n\n///A constant used in offsetting the centroids of one-datapoint clusters in fuzzy-cmeans, to avoid infinite weights\nconst float offsetConstant                  = 0.05;\n///The number of different seeds to try for each value of clusters number when attempting a clusterization\nconst int   attemptsPerClustersNumber       = 3;\n///If empty clusters happen, the algorithm for that number of clusters fails, so we try up to this number of times if this happens.\nconst int   maxIterationPerClustersNumber   = 5;\n\n\n\n/*!\n * @brief       This function calculates the weights of a fuzzy c-means clusterization, according to the next formula:\n *              w_ij = 1 / (norm(centroids(i), entities(j)))\n * @note        The weights are not normalized, as depending on the use case the normalization will be columns-wise or row-wise\n * @param[in]   entities    The datapoints\n * @param[in]   centroids   The centroids of the clusters\n * @param[out]  weights     The resulting weights\n * @param[in]   norm        A pointer to the norm function you want to use\n*/\nvoid calculateFuzzyWeights(\n        const Ref<const MatrixXf>   &entities,\n        const Ref<const MatrixXf>   &centroids,\n        Ref<MatrixXfR>              weights,\n        squaredNorm_t               *norm\n        );\n\n/*!\n * @brief Generates a fixed number of clusters and their fuzzy weights \n * @param[in]       entities    The datapoints\n * @param[out]      centroids   The centroids of the clusters. The number of rows are the required clusters to find\n * @param[out]      weights     The weights associated with the clusterization (array of floats)\n * @param[in]       norm        A pointer to the norm function you want to use\n*/\nvoid FCMGenerator(\n        const Ref<const MatrixXf>   &entities, \n        Ref<MatrixXf>               centroids, \n        Ref<MatrixXfR>              weights, \n        squaredNorm_t               *norm\n    );\n\n/*! \n * @brief       Returns a measure of the fit of the clusterization, it's strictly positive and the smaller it is, the best the fit\n * @details     The Davies-Boulding Index defines a measure of the \"goodness\" of a clusterization of a data population based on the following quantities:\n                The scatter vector S_i= (1/T_i * sum_j (norm(C_i, X_j)))^(1/2) where T_i is the population size of the i-th cluster and the sum runs over the datapoints belonging to the i-th cluster\n                The Cluster Separation Matrix M_ij = (norm(C_i, C_j))^(1/2)\n                The Davies-Bouldin Matrix R_ij = (S_i + S_j)/M_ij\n                The Davies-Bouldin Vector R_i = max_(j!=i) R_ij\n                The Davies-Bouldin index is, in terms of the previous quantities, R = 1/N * sum_i R_i where N is the number of clusters\n * @param[in]   entities    The datapoints\n * @param[in]   centroids   The centroids of the clusters\n * @param[out]  weights     The weights associating each centroid to its cluster (it's an array of bools)\n * @param[in]   norm        A pointer to the norm function you want to use\n * @return     The Davies-Boulding index of the provided clusterization\n*/ \nfloat daviesBouldinIndex(\n        const Ref<const MatrixXf>    &entities,\n        const Ref<const MatrixXf>    &centroids,\n        const Ref<const MatrixXb>    &weights,\n        squaredNorm_t                *norm\n    );\n\n/*!\n * @brief Returns a measure of how well the clusters fit the data\n * @warning TODO <b>Not implemented</b>\n * @param[in]   entities     The datapoints\n * @param[in]   clusters     The centroids of the clusters\n * @param[out]  weights      The weights associating each centroid to its cluster (it's an array of floats)\n * @param[in]   norm         A pointer to the norm function you want to use\n * @return     the fitness of the clusterization\n*/\nfloat silhouetteTest(\n        const Ref<const MatrixXf>   &entities, \n        const Ref<const MatrixXf>   &clusters,\n        const Ref<const MatrixXfR>  &weights,\n        squaredNorm_t               *norm\n        );\n\n/*!\n * @brief       Given a dataset and centroids, returns a weights matrix that is true if the j-th centroid is the closest to the i-th datapoint, and false otherwise\n * @param[in]   entities    The datapoints\n * @param[in]   centroids   The centroids of the clusters\n * @param[out]  weights     The weights associating each centroid to its cluster (it's an array of bools)\n * @param[in]   norm        A pointer to the norm function you want to use\n*/\nvoid calculateBooleanWeights(\n        const Ref<const MatrixXf>   &entities,\n        const Ref<const MatrixXf>   &centroids,\n        Ref<MatrixXbR>              weights,\n        squaredNorm_t               *norm\n    );\n\n/*!\n * @brief       Given a dataset and a centroids matrix of k rows, it tries to identify the most probable k centroids to represent the dataset\n * @param[in]   entities    The datapoints\n * @param[out]   centroids   The centroids of the clusters\n * @param[out]  weights     The weights associating each centroid to its cluster (it's an array of bools)\n * @param[in]   norm        A pointer to the norm function you want to use\n*/\nvoid kmeansGenerator(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        Ref<MatrixXbR>              weights,\n        squaredNorm_t               *norm\n    );\n\n/*!\n * @brief Finds the best fitting number of clusters for the given datapoints, up to the number of rows of centroids through an approximated algorithm compared to full fuzzy c-means\n * @param[in]   entities    The datapoints\n * @param[out]  centroids   The centroids of the clusters\n * @param[out]  weights     The weights associating each centroid to its cluster (it's an array of floats)\n * @param[out]  boolWeights The weights associating each centroid to its cluster (it's an array of bools)\n * @param[in]   norm        A pointer to the norm function you want to use\n * @return     the number of clusters generated\n*/ \nint clusterGeneratorApproximate(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        Ref<MatrixXfR>              weights,\n        Ref<MatrixXbR>              boolWeights,\n        squaredNorm_t               *norm\n    );\n\n/*!\n * @brief Finds the best fitting number of clusters for the given datapoints, up to the number of rows of centroids using the fuzzy c-means algorithm\n * @param[in]   entities    The datapoints\n * @param[out]  centroids   The centroids of the clusters\n * @param[out]  weights     The weights associating each centroid to its cluster (it's an array of floats)\n * @param[in]   norm        A pointer to the norm function you want to use\n * @return     the number of clusters generated\n*/ \nint clusterGeneratorExact(\n        const Ref<const MatrixXf>   &entities,\n        Ref<MatrixXf>               centroids,\n        MatrixXfR                   &weights, \n        squaredNorm_t               *norm\n    );\n\n", "meta": {"hexsha": "c12da7facf2f30f5d59fb9397d7ef376a59db5db", "size": 7700, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/simpleClusterization.hpp", "max_stars_repo_name": "tesseract241/simpleClusterization", "max_stars_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/simpleClusterization.hpp", "max_issues_repo_name": "tesseract241/simpleClusterization", "max_issues_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/simpleClusterization.hpp", "max_forks_repo_name": "tesseract241/simpleClusterization", "max_forks_repo_head_hexsha": "d5125e5b99b67ac92847cccb28b8bf058ac35efd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.0445859873, "max_line_length": 198, "alphanum_fraction": 0.668961039, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.5894109703602043}}
{"text": "#include \"line_interval.hpp\"\n#include \"shape2d.hpp\"\n#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include <iostream>\n#define _USE_MATH_DEFINES\n#include <math.h>\n\nusing namespace Eigen;\nusing namespace std;\n\narray<double, 2> polarEquation(Vector2d v0, Vector2d v1){\n    array<double, 3> line={v0[1]-v1[1], v1[0]-v0[0],-(v0[0]*v1[1]-v1[0]*v0[1])};\n\n    double normalAngle=atan2(line[1], line[0]);\n    double normalDist=line[2] / sqrt(line[0] * line[0] + line[1] * line[1]);\n\n    if(normalDist<0){\n\tnormalDist = -normalDist;\n\tnormalAngle += M_PI;\n\tif(normalAngle>=M_PI){\n\t    normalAngle -= 2 * M_PI;\n\t}\n    }\n\n    array<double, 2> polar={normalDist, normalAngle};\n    return polar;\n}\n\nLineInterval::LineInterval(Vector2d _point){\n    point = _point;\n    angleStart = atan2(point[1], point[0]);\n    distLowerBound = 0.0;\n    distUpperBound = 0.0;\n    intervalMaxDists = {0.0, 0.0};\n}\n\nLineInterval::LineInterval(double _angleStart, double _angleEnd){\n    angleStart=_angleStart;\n    angleEnd=_angleEnd;\n    distLowerBound = 0.0;\n    distUpperBound = 0.0;\n    intervalMaxDists = {0.0, 0.0};\n}\n\ndouble LineInterval::DistAt(array<double, 2> edge, int side){\n    double angle=(side==0 ? angleStart : angleEnd);\n    return edge[0]/cos(angle-edge[1]);\n}\n\narray<double, 3> LineInterval::Divide(){\n    double mid=(angleStart+IntervalAngleEnd())/2;\n    if(mid>=M_PI){\n\tmid -= 2 * M_PI;\n    }\n    return {angleStart, mid, angleEnd};\n}\n\nbool LineInterval::IntersectsEdge(double v0Angle, double v1Angle){\n    double edgeAngleStart=v0Angle;\n    double edgeAngleEnd=v1Angle;\n    if(edgeAngleStart>edgeAngleEnd){\n\tif(angleStart<0){\n\t    edgeAngleStart -= M_PI * 2;\n\t} else {\n\t    edgeAngleEnd += M_PI * 2;\n\t}\n    }\n    return (edgeAngleStart<=angleStart && edgeAngleEnd>=IntervalAngleEnd());\n}\n\n\ndouble LineInterval::IntervalAngleEnd(){\n    double intervalAngleEnd= (angleStart>angleEnd ? angleEnd + (2 * M_PI) : angleEnd);\n    return intervalAngleEnd;\n}\n\nbool LineInterval::containsNormal(array<double, 2> edge){\n\n    if(angleStart>angleEnd){\n\treturn (edge[1]>=angleStart && edge[1]<=M_PI) || (edge[1]<=angleEnd && edge[1] >= -M_PI);\n    } else {\n\treturn (edge[1] >= angleStart && edge[1] <= angleEnd);\n    }\n}\n\narray<double, 3> LineInterval::FunctionsAt(array<double, 2> edge, int side){\n    double angle=(side==0 ? angleStart : angleEnd);\n    //double dist=edge[0]/cos(angle-edge[1]);\n    double dist=DistAt(edge, side);\n    double distPrime=tan(angle-edge[1])*dist;\n   \n    double angleSin=sin(angle-edge[1]);\n    double angleCos=cos(angle-edge[1]);\n\n    double distPrime2=edge[0]*(1+angleSin*angleSin)/(angleCos*angleCos*angleCos);\n    return {dist, distPrime, distPrime2};\n}\n\ndouble LineInterval::ApproxRoot(double distStart, double distEnd, double derivStart, double derivEnd){\n    //double intervalAngleEnd= (angleStart>angleEnd ? angleEnd + (2 * M_PI) : angleEnd);\n\n    double bStart=distStart - (angleStart * derivStart);\n    double bEnd=distEnd - (IntervalAngleEnd() * derivEnd);\n\n    Matrix2d A;\n    A << derivStart, -1,   derivEnd, -1;\n    Vector2d b;\n    b << -bStart, -bEnd;\n\n    return A.colPivHouseholderQr().solve(b)[1];\n}\n\nvoid LineInterval::SetAngleEnd(Vector2d _point){\n    angleEnd = atan2(_point[1], _point[0]);\n}\n\nvoid LineInterval::update(double upperBound, double lowerBound, double distStart, double distEnd, unsigned long int shapeId){\n    distUpperBound+=upperBound;\n    distLowerBound+=lowerBound;\n\n    if(distStart > max(intervalMaxDists[0], intervalMaxDists[1]) || distEnd > max(intervalMaxDists[0], intervalMaxDists[1])){\n\tintervalMaxDists={distStart, distEnd};\n    }\n    shapeIds.push_back(shapeId);\n}\n\ndouble LineInterval::MaxWidth(){\n    //double intervalAngleEnd= (angleStart>angleEnd ? angleEnd + (2 * M_PI) : angleEnd);\n    double b=intervalMaxDists[0];\n    double c=intervalMaxDists[1];\n    return sqrt( b*b + c*c - 2*b*c*cos(IntervalAngleEnd()-angleStart) );\n}\n\narray<Vector2d, 2> LineInterval::EndPoints(){\n    Vector2d v0(intervalMaxDists[0]*cos(angleStart), intervalMaxDists[0]*sin(angleStart));\n    Vector2d v1(intervalMaxDists[1]*cos(angleEnd), intervalMaxDists[1]*sin(angleEnd));\n    return {v0, v1};\n}\n\n\nvector<unsigned long int> LineInterval::ShapeIds(){\n    return shapeIds;\n}\n\ndouble LineInterval::LowerBound(){\n    return distLowerBound;\n}\n\ndouble LineInterval::UpperBound(){\n    return distUpperBound;\n}\n\nVector2d LineInterval::Point(){\n    return point;\n}\n\n", "meta": {"hexsha": "4ff33f151b8960947bb34bca7b5c2542176b225f", "size": 4406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/line_interval.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/line_interval.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/line_interval.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": 27.7106918239, "max_line_length": 125, "alphanum_fraction": 0.6852019973, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5894021526560679}}
{"text": "#include <nori/object.h>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#if defined(PLATFORM_LINUX)\n#include <malloc.h>\n#endif\n\n#if defined(PLATFORM_WINDOWS)\n#include <windows.h>\n#endif\n\n#if defined(PLATFORM_MACOS)\n#include <sys/sysctl.h>\n#endif\n\n#if !defined(L1_CACHE_LINE_SIZE)\n#define L1_CACHE_LINE_SIZE 64\n#endif\n\nNORI_NAMESPACE_BEGIN\n\nColor3f Color3f::toSRGB() const {\n\tColor3f result;\n\n\tfor (int i=0; i<3; ++i) {\n\t\tfloat value = coeff(i);\n\n\t\tif (value <= 0.0031308f)\n\t\t\tresult[i] = 12.92f * value;\n\t\telse\n\t\t\tresult[i] = (1.0f + 0.055f) \n\t\t\t\t* std::pow(value, 1.0f/2.4f) -  0.055f;\n\t}\n\n\treturn result;\n}\n\nColor3f Color3f::toLinearRGB() const {\n\tColor3f result;\n\n\tfor (int i=0; i<3; ++i) {\n\t\tfloat value = coeff(i);\n\n\t\tif (value <= 0.04045f)\n\t\t\tresult[i] = value * (1.0f / 12.92f);\n\t\telse\n\t\t\tresult[i] = std::pow((value + 0.055f)\n\t\t\t\t* (1.0f / 1.055f), 2.4f);\n\t}\n\n\treturn result;\n}\n\nbool Color3f::isValid() const {\n\tfor (int i=0; i<3; ++i) {\n\t\tfloat value = coeff(i);\n\t\tint cl = boost::math::fpclassify(value);\n\t\tif (value < 0 || cl == FP_INFINITE || cl == FP_NAN)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\n\nfloat Color3f::getLuminance() const {\n\treturn coeff(0) * 0.212671f + coeff(1) * 0.715160f + coeff(2) * 0.072169f;\n}\n\nTransform::Transform(const Eigen::Matrix4f &trafo) \n\t: m_transform(trafo), m_inverse(trafo.inverse()) { }\n\nQString Transform::toString() const {\n\tstd::ostringstream oss;\n\toss << m_transform.format(Eigen::IOFormat(4, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\"));\n\treturn QString(oss.str().c_str());\n}\nQString Transform::toLineString() const {\n\tstd::ostringstream oss;\n        for(int row = 0; row < 4; ++row){\n            if(row > 0) oss << \"; \";\n            for(int col = 0; col < 4; ++col){\n                if(col > 0) oss << \", \";\n                oss << m_transform(row, col);\n            }\n        }\n\treturn QString(oss.str().c_str());\n}\n\nVector3f squareToUniformSphere(const Point2f &sample) {\n\tfloat z = 1.0f - 2.0f * sample.y();\n\tfloat r = std::sqrt(std::max((float) 0.0f, 1.0f - z*z));\n\tfloat sinPhi, cosPhi;\n\tsincosf(2.0f * M_PI * sample.x(), &sinPhi, &cosPhi);\n\treturn Vector3f(r * cosPhi, r * sinPhi, z);\n}\n\nVector3f squareToUniformHemisphere(const Point2f &sample) {\n\tfloat cosTheta = sample.x();\n\tfloat sinTheta = std::sqrt(std::max((float) 0, 1-cosTheta*cosTheta));\n\n\tfloat sinPhi, cosPhi;\n\tsincosf(2.0f * M_PI * sample.y(), &sinPhi, &cosPhi);\n\n\treturn Vector3f(cosPhi * sinTheta, sinPhi * sinTheta, cosTheta);\n}\n\nPoint2f squareToUniformDisk(const Point2f &sample) {\n\tfloat r = std::sqrt(sample.x());\n\tfloat sinPhi, cosPhi;\n\tsincosf(2.0f * M_PI * sample.y(), &sinPhi, &cosPhi);\n\n\treturn Point2f(\n\t\tcosPhi * r,\n\t\tsinPhi * r\n\t);\n}\n\nPoint2f squareToUniformDiskConcentric(const Point2f &sample) {\n\tfloat r1 = 2.0f*sample.x() - 1.0f;\n\tfloat r2 = 2.0f*sample.y() - 1.0f;\n\n\tPoint2f coords;\n\tif (r1 == 0 && r2 == 0) {\n\t\tcoords = Point2f(0, 0);\n\t} else if (r1 > -r2) { /* Regions 1/2 */\n\t\tif (r1 > r2)\n\t\t\tcoords = Point2f(r1, (M_PI/4.0f) * r2/r1);\n\t\telse\n\t\t\tcoords = Point2f(r2, (M_PI/4.0f) * (2.0f - r1/r2));\n\t} else { /* Regions 3/4 */\n\t\tif (r1<r2)\n\t\t\tcoords = Point2f(-r1, (M_PI/4.0f) * (4.0f + r2/r1));\n\t\telse \n\t\t\tcoords = Point2f(-r2, (M_PI/4.0f) * (6.0f - r1/r2));\n\t}\n\n\tPoint2f result;\n\tsincosf(coords.y(), &result[1], &result[0]);\n\treturn result*coords.x();\n}\n\nPoint2f squareToUniformTriangle(const Point2f &sample) {\n\tfloat a = std::sqrt(1.0f - sample.x());\n\treturn Point2f(1 - a, a * sample.y());\n}\n\nfloat intervalToTent(float sample) {\n\tfloat sign;\n\n\tif (sample < 0.5f) {\n\t\tsign = 1;\n\t\tsample *= 2;\n\t} else {\n\t\tsign = -1;\n\t\tsample = 2 * (sample - 0.5f);\n\t}\n\n\treturn sign * (1 - std::sqrt(sample));\n}\n\nPoint2f squareToTent(const Point2f &sample) {\n\treturn Point2f(\n\t\tintervalToTent(sample.x()),\n\t\tintervalToTent(sample.y())\n\t);\n}\n\nPoint2f squareToTriangle(const Point2f &sample) {\n\tfloat a = std::sqrt(1.0f - sample.x());\n\treturn Point2f(1 - a, a * sample.y());\n}\n\nVector3f sphericalDirection(float theta, float phi) {\n\tfloat sinTheta, cosTheta, sinPhi, cosPhi;\n\n\tsincosf(theta, &sinTheta, &cosTheta);\n\tsincosf(phi, &sinPhi, &cosPhi);\n\n\treturn Vector3f(\n\t\tsinTheta * cosPhi,\n\t\tsinTheta * sinPhi,\n\t\tcosTheta\n\t);\n}\n\nPoint2f sphericalCoordinates(const Vector3f &v) {\n\tPoint2f result(\n\t\tstd::acos(v.z()),\n\t\tstd::atan2(v.y(), v.x())\n\t);\n\tif (result.y() < 0)\n\t\tresult.y() += 2*M_PI;\n\treturn result;\n}\n\nvoid coordinateSystem(const Vector3f &a, Vector3f &b, Vector3f &c) {\n\tif (std::abs(a.x()) > std::abs(a.y())) {\n\t\tfloat invLen = 1.0f / std::sqrt(a.x() * a.x() + a.z() * a.z());\n\t\tc = Vector3f(a.z() * invLen, 0.0f, -a.x() * invLen);\n\t} else {\n\t\tfloat invLen = 1.0f / std::sqrt(a.y() * a.y() + a.z() * a.z());\n\t\tc = Vector3f(0.0f, a.z() * invLen, -a.y() * invLen);\n\t}\n\tb = c.cross(a);\n}\n\nvoid *allocAligned(size_t size) {\n#if defined(PLATFORM_WINDOWS)\n\treturn _aligned_malloc(size, L1_CACHE_LINE_SIZE);\n#elif defined(PLATFORM_MACOS)\n\t/* OSX malloc already returns 16-byte aligned data suitable\n\t   for AltiVec and SSE computations */\n\treturn malloc(size);\n#else\n\treturn memalign(L1_CACHE_LINE_SIZE, size);\n#endif\n}\n\nvoid freeAligned(void *ptr) {\n#if defined(PLATFORM_WINDOWS)\n\t_aligned_free(ptr);\n#else\n\tfree(ptr);\n#endif\n}\n\nint getCoreCount() {\n#if defined(PLATFORM_WINDOWS)\n\tSYSTEM_INFO sys_info;\n\tGetSystemInfo(&sys_info);\n\treturn sys_info.dwNumberOfProcessors;\n#elif defined(PLATFORM_MACOS)\n\tint nprocs;\n\tsize_t nprocsSize = sizeof(int);\n\tif (sysctlbyname(\"hw.activecpu\", &nprocs, &nprocsSize, NULL, 0))\n\t\tthrow NoriException(\"Could not detect the number of processors!\");\n\treturn (int) nprocs;\n#else\n\treturn sysconf(_SC_NPROCESSORS_CONF);\n#endif\n}\n\nQString indent(const QString &string, int amount) {\n\tQString result = string;\n\tresult.replace(\"\\n\", QString(\"\\n\") + QString(\" \").repeated(amount));\n\treturn result;\n}\n\nfloat fresnel(float cosThetaI, float extIOR, float intIOR) {\n\tfloat etaI = extIOR, etaT = intIOR;\n\n\tif (extIOR == intIOR)\n\t\treturn 0.0f;\n\n\t/* Swap the indices of refraction if the interaction starts\n\t   at the inside of the object */\n\tif (cosThetaI < 0.0f) {\n\t\tstd::swap(etaI, etaT);\n\t\tcosThetaI = -cosThetaI;\n\t}\n\n\t/* Using Snell's law, calculate the squared sine of the\n\t   angle between the normal and the transmitted ray */\n\tfloat eta = etaI / etaT,\n\t\t  sinThetaTSqr = eta*eta * (1-cosThetaI*cosThetaI);\n\n\tif (sinThetaTSqr > 1.0f)\n\t\treturn 1.0f;  /* Total internal reflection! */\n\n\tfloat cosThetaT = std::sqrt(1.0f - sinThetaTSqr);\n\n\tfloat Rs = (etaI * cosThetaI - etaT * cosThetaT)\n\t         / (etaI * cosThetaI + etaT * cosThetaT);\n\tfloat Rp = (etaT * cosThetaI - etaI * cosThetaT)\n\t         / (etaT * cosThetaI + etaI * cosThetaT);\n\n\treturn (Rs * Rs + Rp * Rp) / 2.0f;\n}\n\nNORI_NAMESPACE_END\n", "meta": {"hexsha": "00cabc65f3d03929725c171ebb92dc7fc9449d2f", "size": 6694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw4/src/common.cpp", "max_stars_repo_name": "jrabasco/acg2015", "max_stars_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw4/src/common.cpp", "max_issues_repo_name": "jrabasco/acg2015", "max_issues_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw4/src/common.cpp", "max_forks_repo_name": "jrabasco/acg2015", "max_forks_repo_head_hexsha": "419fd0fdf5293dda95ea0231cf6c6f4af5331120", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6537102473, "max_line_length": 81, "alphanum_fraction": 0.6389303854, "num_tokens": 2278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5893412884808267}}
{"text": "//\n//  mex_top_eig.cpp\n//  \n//\n//  Created by Bo_Royce on 8/17/16.\n//\n//\n#include <mex.h>\n#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/SparseCore>\n#include <Eigen/Core>\n#include <SymEigsSolver.h>\n#include <MatOp/SparseSymMatProd.h>\n#include <time.h>\nusing namespace Eigen;\nusing namespace Spectra;\nvoid make_top_eigenvectors(double *val,double *ind, int KK, int NN, int NK, double *eigenvectors,double *eigenvalues){\n    clock_t begin = clock();\n    Eigen::SparseMatrix<double> mat((const int) NN,(const int) NN);         // default is column major\n    mat.reserve(Eigen::VectorXi::Constant((const int) NN, (const int) NK));\n    typedef Eigen::Triplet<double> T;\n    std::vector<T> tripletList;\n    tripletList.reserve((const int) NN*NK);\n    for(int i=0; i<NN; i++){\n        for (int j = 0; j< NK; j++){\n            tripletList.push_back(T((int) ind[i+NN*j]-1,i,val[i+j*NN]));\n        }\n    }\n    mat.setFromTriplets(tripletList.begin(), tripletList.end());\n    mat += Eigen::SparseMatrix<double>(mat.transpose());\n    clock_t end = clock();\n    //printf(\"Elapsed time in initialization is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    \n    SparseSymMatProd<double> op(mat);\n    begin = clock();\n    // Construct eigen solver object, requesting the largest KK eigenvalues\n    SymEigsSolver< double, LARGEST_ALGE, SparseSymMatProd<double> > eigs(&op, KK, 2*KK);\n    \n    // Initialize and compute\n    eigs.init();\n    int nconv = eigs.compute();\n    \n    // Retrieve results\n    \n    Eigen::VectorXd evalues;\n    Eigen::MatrixXd evectors;\n    if(eigs.info() == SUCCESSFUL){\n        evalues = eigs.eigenvalues();\n        evectors = eigs.eigenvectors();\n    }\n    //std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n    end = clock();\n    printf(\"Elapsed time in eigen-decomposition is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    ///\n    begin = clock();\n    for (int j = 0; j< KK; j++){\n        eigenvalues[j] = evalues[j];\n        for (int i = 0; i < NN; i++){\n            eigenvectors[i+NN*j] = evectors.col(j)[i];\n        }\n    }\n   end = clock();\n    printf(\"Elapsed time in copying eigenvectors is %f seconds\\n\", (double)(end - begin)/CLOCKS_PER_SEC);\n    ///\n}\n\n/// usage: eigenvectors = mex_top_eig(val, ind, KK);\n/// input: val of size NxK, the value of transition matrix \n///        ind of size NxK, the index of the values (Note ind starts with 0);\n///        KK , the number of eigenvectors    \nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){\n    double *val, *ind, *eigenvectors,*eigenvalues;\n    int KK, NN, NK;\n    val = mxGetPr(prhs[0]);\n    ind = mxGetPr(prhs[1]); //\n    KK = (int) mxGetScalar(prhs[2]); //number of eigenvalues\n    NN = mxGetM(prhs[0]);\n    NK = mxGetN(prhs[1]);\n    plhs[0] = mxCreateDoubleMatrix(NN,KK,mxREAL);\n    eigenvectors = mxGetPr(plhs[0]);\n    plhs[1] = mxCreateDoubleMatrix(KK,1,mxREAL);\n    eigenvalues = mxGetPr(plhs[1]);\n    make_top_eigenvectors(val,ind, KK,  NN, NK, eigenvectors,eigenvalues);\n}\n", "meta": {"hexsha": "af4507340831bb48c5993fe3da7914e7f78446f8", "size": 3040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "+run/thirdparty/SIMLR/src/mex_top_eig.cpp", "max_stars_repo_name": "jamesjcai/scGEAtoolbox", "max_stars_repo_head_hexsha": "9f04d79100b01939b2c58fe612a6b56b68f6eb57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T18:04:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-24T02:27:16.000Z", "max_issues_repo_path": "+run/thirdparty/SIMLR/src/mex_top_eig.cpp", "max_issues_repo_name": "jamesjcai/scGEAtoolbox", "max_issues_repo_head_hexsha": "9f04d79100b01939b2c58fe612a6b56b68f6eb57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-05-15T13:55:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T21:41:34.000Z", "max_forks_repo_path": "+run/thirdparty/SIMLR/src/mex_top_eig.cpp", "max_forks_repo_name": "jamesjcai/scGEAtoolbox", "max_forks_repo_head_hexsha": "9f04d79100b01939b2c58fe612a6b56b68f6eb57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-02-13T06:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T14:00:16.000Z", "avg_line_length": 34.9425287356, "max_line_length": 118, "alphanum_fraction": 0.6282894737, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5893284514288168}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n* \n*   Tutorial: Calculation of eigenvalues using Lanczos' method (lanczos.cpp and lanczos.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n// include necessary system headers\n#include <iostream>\n\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n#define VIENNACL_WITH_UBLAS\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n\n#include \"viennacl/linalg/lanczos.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n// Some helper functions for this tutorial:\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <string>\n#include <iomanip>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp> \n#include <boost/numeric/ublas/vector_expression.hpp>\n\n\n\ntemplate <typename MatrixType>\nstd::vector<double> initEig(MatrixType const & A)\n{\n  viennacl::linalg::lanczos_tag ltag(0.75, 10, viennacl::linalg::lanczos_tag::partial_reorthogonalization, 1700);\n  std::vector<double> lanczos_eigenvalues = viennacl::linalg::eig(A, ltag);\n  for(std::size_t i = 0; i< lanczos_eigenvalues.size(); i++){\n          std::cout << \"Eigenvalue \" << i+1 << \": \" << std::setprecision(10) << lanczos_eigenvalues[i] << std::endl; \n  }\n  \n  return lanczos_eigenvalues;\n}\n\n\nint main()\n{\n  typedef double     ScalarType;\n  \n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;\n\n  if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n  \n  std::cout << \"Running Lanczos algorithm (this might take a while)...\" << std::endl;\n  std::vector<double> eigenvalues = initEig(ublas_A);\n}\n\n", "meta": {"hexsha": "81db5b365b48a6e121cfe265cc030f05d0fe055c", "size": 2722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/lanczos.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/lanczos.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/lanczos.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": 31.6511627907, "max_line_length": 164, "alphanum_fraction": 0.6359294636, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5893085339866913}}
{"text": "// Includes\n// ========\n#include <iostream>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n  boost::no_property, boost::property<boost::edge_weight_t, long> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\n\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>>>> flow_graph;\n\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\n\n\n// Custom edge adder class\nclass edge_adder {\n weighted_graph &G;\n\n public:\n  explicit edge_adder(weighted_graph &G) : G(G) {}\n  void add_edge(int from, int to, long weight) {\n    auto w_map = boost::get(boost::edge_weight, G); // new!\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    w_map[e] = weight;   // new assign cost\n  }\n};\n\n\n// Custom edge adder class, highly recommended\nclass edge_adder_flow {\n  flow_graph &G;\n\n public:\n  explicit edge_adder_flow(flow_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\nvoid testcase() {\n    int n, m, a, s, c, d;\n    std::cin >> n >> m >> a >> s >> c >> d;\n    weighted_graph G(n);\n    edge_adder adder(G);\n\n    for(int i = 0; i < m; i++) {\n        char w; int x, y, z;\n        std::cin >> w >> x >> y >> z;\n        adder.add_edge(x, y, z);\n        if(w == 'L') {\n            adder.add_edge(y, x, z);\n        }\n    }\n\n    std::vector<int> agent(a);\n    for(int i = 0; i < a; i++) {\n        std::cin >> agent[i];\n    }\n\n    std::vector<int> shelter(s);\n    for(int i = 0; i < s; i++) {\n        std::cin >> shelter[i];\n    }\n\n\n    std::vector<std::vector<long>> distance_to(a, std::vector<long>(s));\n    long max_dist = 0;\n    for(int i = 0; i < a; i++) {\n        std::vector<int> dist_map(n);\n        boost::dijkstra_shortest_paths(G, agent[i],\n            boost::distance_map(boost::make_iterator_property_map(\n            dist_map.begin(), boost::get(boost::vertex_index, G))));\n        for(int j = 0; j < s; j++) {\n            distance_to[i][j] = dist_map[shelter[j]];\n            if(distance_to[i][j] < std::numeric_limits<int>::max()) {\n                max_dist = std::max(max_dist, distance_to[i][j]);\n            }\n        }\n    }\n\n    int l = 0, r = max_dist + c * d;\n\n    while(l < r) {\n        // compute matching for all edges dist + c * d <= mid\n        flow_graph G_f(a + c * s);\n        edge_adder_flow adder_f(G_f);\n        int mid = (l + r) / 2;\n        const int v_source = boost::add_vertex(G_f);\n        const int v_sink = boost::add_vertex(G_f);\n        for(int i = 0; i < a; i++) {\n            adder_f.add_edge(v_source, i, 1);\n            for(int j = 0; j < s; j++) {\n                if(distance_to[i][j] + d <= mid) adder_f.add_edge(i, a + j, 1);\n                if(c == 2) {\n                    if(distance_to[i][j] + 2 * d <= mid) adder_f.add_edge(i, a + s + j, 1);\n                }\n            }\n        }\n        for(int j = 0; j < s; j++) {\n            adder_f.add_edge(a + j, v_sink, 1);\n            if(c == 2) adder_f.add_edge(a + s + j, v_sink, 1);\n        }\n        long flow = boost::push_relabel_max_flow(G_f, v_source, v_sink);\n        if(flow == a) { // matching maximal -> all agents arrive at shelter\n            r = mid;\n        } else {\n            l = mid + 1;\n        }\n    }\n    std::cout << l << 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": "06aae963870c0608f02e585afe80c753bdd7e0dc", "size": 4388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week12-majestys_secret_service/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-majestys_secret_service/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-majestys_secret_service/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": 30.9014084507, "max_line_length": 93, "alphanum_fraction": 0.5715587967, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5893061047163374}}
{"text": "#include \"gcd.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <algorithm>\n#include <cmath>\nnamespace HT\n{\n    void gcd(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()<2)\n          throw std::runtime_error(\"Gcd should have at least 1 parameter\");\n        auto  secondCh = (++astnode->ch.begin() );\n        myParserHelper.parse(*secondCh);\n        if ((*secondCh)->token.tokenType != Complex) throw std::runtime_error(\"the argument of gcd must be complex\"+ (*secondCh)->token.raw);\n        auto cast = boost::get<ComplexType>((*secondCh)->token.info);\n        if (!cast.isInt())\n          throw std::runtime_error(\"the argument of gcd must be int\");\n        auto now = cast.toInt();\n\n        std::for_each(++secondCh, astnode->ch.end(), [&](PASTNode an)\n                    {\n                    myParserHelper.parse(an);\n                    if (an->token.tokenType!=Complex) throw std::runtime_error(\"the argument of gcd must be complex\" + an->token.raw);\n                    cast = boost::get<ComplexType>(an->token.info);\n                    if (!cast.isInt())\n                        throw std::runtime_error(\"the argument of gcd must be int\");\n                    if (!cast.toInt().isZero())\n                    now = gcd( now, cast.toInt());\n                    });\n\n        astnode->token.info = ComplexType(now.setSign(true));\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        astnode->remove();\n    }\n}\n\n\n", "meta": {"hexsha": "df312e8c2e7800b548e2f18ec2a77a5a50fb4627", "size": 1584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/gcd.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/gcd.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/gcd.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8372093023, "max_line_length": 141, "alphanum_fraction": 0.5669191919, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5892963246647501}}
{"text": "#include \"teca_laplacian.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;\nusing std::tan;\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 the laplacian. This  assumes fixed mesh spacing. Here we add periodic\n// bc in lon and apply unit stride vector optimization strategy to loops\ntemplate <typename num_t, typename pt_t>\nvoid laplacian(num_t *w, const pt_t *lon, const pt_t *lat,\n    const num_t *f, 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_lon_sq = static_cast<num_t*>(malloc(n_bytes));\n\n    // delta lon squared as a function of latitude\n    num_t d_lon = (lon[1] - lon[0]) * deg_to_rad<num_t>() * earth_radius<num_t>();\n    // tan(lat)\n    num_t *tan_lat = static_cast<num_t*>(malloc(n_bytes)); \n    for (unsigned long j = 0; j < n_lat; ++j)\n    {\n        delta_lon_sq[j] = pow(d_lon * cos(lat[j] * deg_to_rad<num_t>()),2);\n    \ttan_lat[j] = tan(lat[j] * deg_to_rad<num_t>());\n    }\n\n    // delta lat squared\n    num_t delta_v = (lat[1] - lat[0]) * deg_to_rad<num_t>() * earth_radius<num_t>();\n    num_t dlat = num_t(2)*delta_v;\n    num_t dlat_sq = delta_v*delta_v;\n    dlat *= earth_radius<num_t>(); // scale dlat by R for the tan term\n\n    unsigned long max_i = n_lon - 1;\n    unsigned long max_j = n_lat - 1;\n\n    // laplacian\n    for (unsigned long j = 1; j < max_j; ++j)\n    {\n\t// set the current row in the u/v/w arrays\n        unsigned long jj = j*n_lon;\n\t/* \n\t * The following f_* variables describe the field\n\t * f in a grid oriented fashion:\n\t *\n\t *\tf_ipjm\tf_ipj\tf_ipjp\n\t *\n\t *\tf_ijm\tf_ji\tf_ijp\n\t *\n\t *\tf_imjm\tf_imj\tf_imjp\n\t * \n\t * The 'j' direction represents longitude, the\n\t * 'i' direciton represents latitude. \n\t *\n\t * Note: The laplacian represented here uses the chain\n\t * rule to separate the (1/cos(lat)*d(cos(lat)*df/dlat)/dlat \n\t * term into two terms.\n\t *\n\t */\n\t// Set array pointer locations so that index 'i' refers to the\n\t// shifted location in all variables\n        const num_t *f_ij = f + jj;          // i,j\n        const num_t *f_ipj = f + jj + n_lon; // i+1, j\n        const num_t *f_imj = f + jj - n_lon; // i-1, j\n        const num_t *f_ijp = f + jj + 1;     // i,   j + 1\n        const num_t *f_ijm = f + jj - 1;     // i,   j - 1\n\t\n\t// set the pointer index for the output field w\n\t// ... this is index i,j\n        num_t *ww = w + jj;\n\t// create a dummy variable for u**2 \n        num_t dlon_sq = delta_lon_sq[j];\n\n        for (unsigned long i = 1; i < max_i; ++i)\n        {\n\t    // calculate the laplacian in spherical coordinates, assuming\n\t    // constant radius R.\n            ww[i] = (f_imj[i] - num_t(2)*f_ij[i] + f_ipj[i])/dlat_sq - \n\t\t    tan_lat[j]*(f_ipj[i]-f_imj[i])/dlat + \n                    (f_ijm[i] - num_t(2)*f_ij[i] + f_ijp[i])/dlon_sq;\n        }\n    }\n\n    if (periodic_lon)\n    {\n        // periodic in longitude; leftmost boundary\n        for (unsigned long j = 1; j < max_j; ++j)\n        {\n\t    // set the current row in the u/v/w arrays\n            unsigned long jj = j*n_lon;\n\t    // Set array pointer locations so that index 'i' refers to the\n\t    // shifted location in all variables\n            const num_t *f_ij = f + jj;          // i,j\n            const num_t *f_ipj = f + jj + n_lon; // i+1, j\n            const num_t *f_imj = f + jj - n_lon; // i-1, j\n            const num_t *f_ijp = f + jj + 1;     // i,   j + 1\n            const num_t *f_ijm = f + jj - max_i; // i,   j - 1\n\n\t    // set the pointer index for the output field w\n\t    // ... this is index i,j\n            num_t *ww = w + jj;\n\t    // create a dummy variable for u**2 \n            num_t dlon_sq = delta_lon_sq[j];\n\n\t    // calculate the laplacian in spherical coordinates, assuming\n\t    // constant radius R.\n            ww[0] = (f_imj[0] - num_t(2)*f_ij[0] + f_ipj[0])/dlat_sq - \n\t\t    tan_lat[j]*(f_ipj[0]-f_imj[0])/dlat + \n                    (f_ijm[0] - num_t(2)*f_ij[0] + f_ijp[0])/dlon_sq;\n        }\n\n        // periodic in longitude; rightmost boundary\n        for (unsigned long j = 1; j < max_j; ++j)\n        {\n\t    // set the current row in the u/v/w arrays\n            unsigned long jj = j*n_lon;\n\n\t    // Set array pointer locations so that index 'i' refers to the\n\t    // shifted location in all variables\n            const num_t *f_ij = f + jj + max_i;          // i,j\n            const num_t *f_ipj = f + jj + max_i + n_lon; // i+1, j\n            const num_t *f_imj = f + jj + max_i - n_lon; // i-1, j\n            const num_t *f_ijp = f + jj;                 // i,   j + 1\n            const num_t *f_ijm = f + jj - max_i;         // i,   j - 1\n\n\t    // set the pointer index for the output field w\n\t    // ... this is index i,j\n            num_t *ww = w + jj + max_i;\n\t    // create a dummy variable for u**2 \n            num_t dlon_sq = delta_lon_sq[j];\n\n\t    // calculate the laplacian in spherical coordinates, assuming\n\t    // constant radius R.\n            ww[0] = (f_imj[0] - num_t(2)*f_ij[0] + f_ipj[0])/dlat_sq - \n\t\t    tan_lat[j]*(f_ipj[0]-f_imj[0])/dlat + \n                    (f_ijm[0] - num_t(2)*f_ij[0] + f_ijp[0])/dlon_sq;\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_lon_sq);\n    free(tan_lat);\n\n    return;\n}\n};\n\n\n// --------------------------------------------------------------------------\nteca_laplacian::teca_laplacian() :\n    component_0_variable(), \n    laplacian_variable(\"laplacian\")\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_laplacian::~teca_laplacian()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_laplacian::get_properties_description(\n    const string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_laplacian\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, component_0_variable,\n            \"array containing the input variable\")\n        TECA_POPTS_GET(std::string, prefix, laplacian_variable,\n            \"array to store the computed laplacian in\")\n        ;\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_laplacian::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, laplacian_variable)\n}\n#endif\n\n// --------------------------------------------------------------------------\nstd::string teca_laplacian::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_laplacian::component_0_variable\"))\n            request.get(\"teca_laplacian::component_0_variable\", comp_0_var);\n\n    return comp_0_var;\n}\n\n// --------------------------------------------------------------------------\nstd::string teca_laplacian::get_laplacian_variable(\n    const teca_metadata &request)\n{\n    std::string lapl_var = this->laplacian_variable;\n\n    if (lapl_var.empty())\n    {\n        if (request.has(\"teca_laplacian::laplacian_variable\"))\n            request.get(\"teca_laplacian::laplacian_variable\", lapl_var);\n        else\n            lapl_var = \"laplacian\";\n    }\n\n    return lapl_var;\n}\n\n// --------------------------------------------------------------------------\nteca_metadata teca_laplacian::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_laplacian::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->laplacian_variable);\n\n    return out_md;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_laplacian::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    // 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\n    // capture the array we produce\n    arrays.erase(this->get_laplacian_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_laplacian::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_laplacian::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 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 lapl = comp_0->new_instance();\n    lapl->resize(comp_0->size());\n\n    // compute laplacian\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            lapl.get(), 2,\n\n            const NT2 *p_comp_0 = dynamic_cast<const TT2*>(comp_0.get())->get();\n            NT2 *p_lapl = dynamic_cast<TT2*>(lapl.get())->get();\n\n            ::laplacian(p_lapl, p_lon, p_lat,\n                p_comp_0, lon->size(), lat->size());\n            )\n        )\n\n    // create the output mesh, pass everything through, and\n    // add the laplacian 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_laplacian_variable(request), lapl);\n\n    return out_mesh;\n}\n", "meta": {"hexsha": "43c481e449ebee365834378da7b2deaf5aa18159", "size": 12430, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_laplacian.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_laplacian.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_laplacian.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": 30.4656862745, "max_line_length": 84, "alphanum_fraction": 0.5818181818, "num_tokens": 3412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.589296322519961}}
{"text": "/** $Id: polygon.cxx 137064 2015-08-31 18:24:47Z jvansanten $\n * @file\n * @author Jakob van Santen <jakob.van.santen@desy.de>\n *\n * $Revision: 137064 $\n * $Date: 2015-08-31 12:24:47 -0600 (Mon, 31 Aug 2015) $\n */\n\n#include <phys-services/surfaces/detail/polygon.h>\n#include <boost/utility.hpp>\n\nnamespace I3Surfaces { namespace polygon {\n\nnamespace {\n\n/// A counterclockwise curve is the basic building block of a convex hull\nclass ccw_curve : public std::vector<vec2> {\npublic:\n\t// Add a point to the curve\n\tvoid operator()(const vec2 &p)\n\t{\n\t\t// Remove points until the curve will be counterclockwise\n\t\twhile (size() >= 2 && !ccw((*this)[size()-2], (*this)[size()-1], p))\n\t\t\tpop_back();\n\t\tpush_back(p);\n\t}\nprivate:\n\tstatic bool\n\tccw(const vec2 &o, const vec2 &a, const vec2 &b)\n\t{\n\t\t// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n\t\t// positive, if OAB makes a counter-clockwise turn,\n\t\t// negative for clockwise turn, and zero if the points are collinear.\n\t\treturn (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) > 0;\n\t}\n};\n\n}\n\n/// Lifted from http://code.icecube.wisc.edu/svn/sandbox/ckopper/eventinjector/python/util/__init__.py\nstd::vector<vec2>\nconvex_hull(const std::vector<I3Position> &positions)\n{\n\tstd::vector<vec2> hull;\n\t\n\t// Build a set of unique points, sorted lexicographically\n\tstd::set<vec2> points;\n\tstd::transform(positions.begin(), positions.end(),\n\t    std::inserter(points, points.end()), vec2::from_I3Position);\n\t\n\t// Boring case: 1 point (perhaps repeated)\n\tif (points.size() <= 1) {\n\t\tstd::copy(points.begin(), points.end(), std::back_inserter(hull));\n\t\treturn hull;\n\t}\n\t\n\t// Build lower and upper hulls\n\tstd::vector<vec2> lower = std::for_each(points.begin(), points.end(), ccw_curve());\n\tstd::vector<vec2> upper = std::for_each(points.rbegin(), points.rend(), ccw_curve());\n\t\n\t// Concatenation of the lower and upper hulls gives the convex hull.\n\t// Last point of each list is omitted because it is repeated at the\n\t// beginning of the other list.\n\tstd::copy(lower.begin(), lower.end()-1, std::back_inserter(hull));\n\tstd::copy(upper.begin(), upper.end()-1, std::back_inserter(hull));\n\t\n\treturn hull;\n}\n\nstd::vector<vec2>\nexpand_polygon(const std::vector<vec2> &hull, double padding)\n{\n\tstd::vector<vec2> points;\n\tfor (std::vector<vec2>::const_iterator p = hull.begin(); p != hull.end(); p++) {\n\t\tstd::vector<vec2>::const_iterator next = boost::next(p);\n\t\tif (next == hull.end())\n\t\t\tnext = hull.begin();\n\t\tstd::vector<vec2>::const_iterator prev = boost::prior(\n\t\t    p == hull.begin() ? hull.end() : p);\n\t\t// normalized vector connecting this vertex to the next one\n\t\tvec2 d = vec2::normalized(next->x-p->x, next->y-p->y);\n\t\t// and the previous vertex to this one\n\t\tvec2 prev_d = vec2::normalized(p->x-prev->x, p->y-prev->y);\n\t\t// sine of the inner angle between the segments that meet here\n\t\tdouble det = prev_d.x*d.y - prev_d.y*d.x;\n\t\tif (det == 0.)\n\t\t\tlog_fatal(\"Edges can't be [anti]parallel\");\n\t\tvec2 outwards(prev_d.x-d.x, prev_d.y-d.y);\n\t\tpoints.push_back(vec2(p->x + outwards.x*padding/det, p->y + outwards.y*padding/det));\n\t}\n\t\n\treturn points;\n}\n\nvec2::vec2(double xi, double yi) : x(xi), y(yi)\n{}\n\ntemplate <typename Archive>\nvoid vec2::serialize(Archive &ar, unsigned version)\n{\n\tif (version > 0)\n\t\tlog_fatal_stream(\"Version \"<<version<<\" is from the future\");\n\t\n\tar & make_nvp(\"X\", x);\n\tar & make_nvp(\"Y\", y);\n}\n\nvec2\nvec2::from_I3Position(const I3Position &p)\n{\n\treturn vec2(p.GetX(), p.GetY());\n}\n\nvec2\nvec2::normalized(double xi, double yi)\n{\n\tdouble l = hypot(xi, yi);\n\treturn vec2(xi/l, yi/l);\n}\n\nbool\noperator<(const vec2 &a, const vec2 &b)\n{\n\tif (a.x < b.x)\n\t\treturn true;\n\telse if (a.x > b.x)\n\t\treturn false;\n\telse if (a.y < b.y)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nside::side(const vec2 &p, const vec2 &np) : origin(p),\n    vector(np.x-p.x, np.y-p.y), length(hypot(vector.x, vector.y)),\n\tnormal(vector.y/length, -vector.x/length, 0.)\n{}\n\n}}\n\nI3_SERIALIZABLE(I3Surfaces::polygon::vec2);\n", "meta": {"hexsha": "cff78b2ff9b47f7a561cb26856d7119fba4f4e56", "size": 3982, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "phys-services/private/surfaces/polygon.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": "phys-services/private/surfaces/polygon.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": "phys-services/private/surfaces/polygon.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": 28.0422535211, "max_line_length": 102, "alphanum_fraction": 0.6652435962, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.5892963017612288}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2014 Basil Fierz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// VCL configuration\n#include <vcl/config/global.h>\n\n// C++ standard library\n#include <iostream>\n#include <random>\n\n// Eigen library\n#include <Eigen/Dense>\n\n// VCL\n#include <vcl/core/simd/vectorscalar.h>\n#include <vcl/core/interleavedarray.h>\n#include <vcl/math/jacobieigen33_selfadjoint.h>\n#include <vcl/math/jacobieigen33_selfadjoint_quat.h>\n#include <vcl/util/precisetimer.h>\n\ntemplate<typename Scalar>\nVcl::Core::InterleavedArray<Scalar, 3, 3, -1> createProblems(size_t nr_problems)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution<float> d;\n\n\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1> F(nr_problems);\n\n\t// Initialize data\n\tfor (size_t i = 0; i < nr_problems; i++)\n\t{\n\t\tEigen::Matrix<Scalar, 3, 3> rnd;\n\t\trnd << d(rng), d(rng), d(rng),\n\t\t\t   d(rng), d(rng), d(rng),\n\t\t\t   d(rng), d(rng), d(rng);\n\t\tF.template at<Scalar>(i) = rnd.transpose() * rnd;\n\t}\n\n\treturn std::move(F);\n}\n\nvoid perfEigenEigen\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tVcl::Util::PreciseTimer timer;\n\ttimer.start();\n#ifdef _OPENMP\n#\tpragma omp parallel for\n#endif /* _OPENMP */\n\tfor (size_t i = 0; i < nr_problems; i++)\n\t{\n\t\t// Map data\n\t\tVcl::Matrix3f A = F.at<float>(i);\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\tresU.at<float>(i) = solver.eigenvectors();\n\t\tresS.at<float>(i) = solver.eigenvalues();\n\t}\n\ttimer.stop();\n\tstd::cout << \"Eigen Jacobi SVD: \" << timer.interval() / nr_problems * 1e9 << \"[ns]\" << std::endl;\t\n}\n\nvoid perfEigenEigenDirect\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tVcl::Util::PreciseTimer timer;\n\ttimer.start();\n#ifdef _OPENMP\n#\tpragma omp parallel for\n#endif /* _OPENMP */\n\tfor (size_t i = 0; i < nr_problems; i++)\n\t{\n\t\t// Map data\n\t\tVcl::Matrix3f A = F.at<float>(i);\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\tsolver.computeDirect(A, Eigen::ComputeEigenvectors);\n\n\t\tresU.at<float>(i) = solver.eigenvectors();\n\t\tresS.at<float>(i) = solver.eigenvalues();\n\t}\n\ttimer.stop();\n\tstd::cout << \"Eigen Jacobi SVD: \" << timer.interval() / nr_problems * 1e9 << \"[ns]\" << std::endl;\t\n}\n\ntemplate<typename WideScalar>\nvoid perfJacobiEigen\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\t\n\tVcl::Util::PreciseTimer timer;\n\ttimer.start();\n\tint avg_nr_iter = 0;\n#ifdef _OPENMP\n#\tpragma omp parallel for\n#endif /* _OPENMP */\n\tfor (size_t i = 0; i < nr_problems / width; i++)\n\t{\n\t\t// Map data\n\t\tauto U = resU.at<real_t>(i);\n\t\tauto S = resS.at<real_t>(i);\n\t\t\n\t\t// Compute SVD using 2-sided Jacobi iterations (Brent)\n\t\tmatrix3_t SV = F.at<real_t>(i);\n\t\tmatrix3_t matU = matrix3_t::Identity();\n\n\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigen(SV, matU);\n\n\t\t// Store results\n\t\tU = matU;\n\t\tS = SV.diagonal();\n\t}\n\ttimer.stop();\n\tstd::cout << \"Self-adjoint Jacobi Eigen Decomposition: \" << timer.interval() / nr_problems * 1e9 << \"[ns], Avg. iterations: \" << (double) (avg_nr_iter * width) / (double) nr_problems << std::endl;\n}\n\t\ntemplate<typename WideScalar>\nvoid perfJacobiEigenQuat\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\t\n\tVcl::Util::PreciseTimer timer;\n\ttimer.start();\n\tint avg_nr_iter = 0;\n#ifdef _OPENMP\n#\tpragma omp parallel for\n#endif /* _OPENMP */\n\tfor (size_t i = 0; i < nr_problems / width; i++)\n\t{\n\t\t// Map data\n\t\tauto U = resU.at<real_t>(i);\n\t\tauto S = resS.at<real_t>(i);\n\n\t\t// Compute SVD using Jacobi iterations and QR decomposition\n\t\tmatrix3_t SV = F.at<real_t>(i);\n\t\tmatrix3_t matU = matrix3_t::Identity();\n\n\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigenQuat(SV, matU);\n\n\t\t// Store results\n\t\tU = matU;\n\t\tS = SV.diagonal();\n\t}\n\ttimer.stop();\n\tstd::cout << \"Self-adjoint Jacobi Quaternion Eigen Decomposition: \" << timer.interval() / nr_problems * 1e9 << \"[ns], Avg. iterations: \" << (double) (avg_nr_iter * width) / (double) nr_problems << std::endl;\n}\nint main(int, char**)\n{\n\tsize_t nr_problems = 1024*1024;\n\n\tVcl::Core::InterleavedArray<float, 3, 3, -1> resU(nr_problems);\n\tVcl::Core::InterleavedArray<float, 3, 1, -1> resS(nr_problems);\n\n\t// Initialize data\n\tauto F = createProblems<float>(nr_problems);\n\t\n\t// Test Performance: Eigen Jacobi Decomposition\n\tperfEigenEigen(nr_problems, F, resU, resS);\n\tperfEigenEigenDirect(nr_problems, F, resU, resS);\n\t\n\t// Test Performance: Jacobi Eigenvalue Decomposition\n\tperfJacobiEigen<float>(nr_problems, F, resU, resS);\n\tperfJacobiEigen<Vcl::float4>(nr_problems, F, resU, resS);\n\tperfJacobiEigen<Vcl::float8>(nr_problems, F, resU, resS);\n\tperfJacobiEigen<Vcl::float16>(nr_problems, F, resU, resS);\n\t\n\t// Test Performance: Jacobi Eigenvalue Decomposition using quaternions\n\tperfJacobiEigenQuat<float>(nr_problems, F, resU, resS);\n\tperfJacobiEigenQuat<Vcl::float4>(nr_problems, F, resU, resS);\n\tperfJacobiEigenQuat<Vcl::float8>(nr_problems, F, resU, resS);\n\tperfJacobiEigenQuat<Vcl::float16>(nr_problems, F, resU, resS);\n}\n", "meta": {"hexsha": "f860678e885f141da9f5aa8dfef29f4c1af1731c", "size": 6851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmarks/eigen33performance/main.cpp", "max_stars_repo_name": "bschindler/vcl", "max_stars_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/benchmarks/eigen33performance/main.cpp", "max_issues_repo_name": "bschindler/vcl", "max_issues_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmarks/eigen33performance/main.cpp", "max_forks_repo_name": "bschindler/vcl", "max_forks_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.314159292, "max_line_length": 208, "alphanum_fraction": 0.6980002919, "num_tokens": 2158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5892899826120184}}
{"text": "#include \"solvers.hpp\"\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <Eigen/QR>\n#include <Eigen/LU>\n#include <Eigen/SparseLU>\n\n// -----------------------------------------------------------------------------\n\ntypedef Eigen::Triplet<double, int> Triplet;\n/// declares a column-major sparse matrix type of double\ntypedef Eigen::SparseMatrix<double> Sparse_mat;\n\n// -----------------------------------------------------------------------------\n\n/// Are angles obtuse between e0 and e1 (meaning a < PI/2)\nstatic bool check_obtuse(const Vec3& e0,\n                         const Vec3& e1)\n{\n    return e0.normalized().dot( e1.normalized() ) >= 0.f;\n}\n\n// -----------------------------------------------------------------------------\n\n/**\n * @brief Check if a triangle is obtuse (every angles < PI/2)\n * Here how edges must be defined :\n   @code\n      p0\n      |\\\n      | \\\n      |  \\\n      |   \\\n      |____\\\n     p1     p2\n\n    Vec3 e0 = p1 - p0;\n    Vec3 e1 = p2 - p0;\n    Vec3 e2 = p2 - p1;\n   @endcode\n */\nstatic bool check_obtuse(const Vec3& e0,\n                         const Vec3& e1,\n                         const Vec3& e2)\n{\n    return check_obtuse(e0, e1) && check_obtuse(-e0, e2) && check_obtuse(-e1, -e2);\n}\n\n// -----------------------------------------------------------------------------\n\ninline static\ndouble mixed_voronoi_area(const Vec3& pi,\n                          const Vec3& pj0,\n                          const Vec3& pj1)\n{\n    double area = 0.;\n    Vec3 e0 = pj0 - pi ;\n    Vec3 e1 = pj1 - pi;\n    Vec3 e2 = pj1 - pj0;\n\n    if( check_obtuse(e0, e1, e2) )\n    {\n        area = (1/8.) * (double)(e0.norm_squared() * (-e0).cotan( e2) +\n                                 e1.norm_squared() * (-e1).cotan(-e2));\n    }\n    else\n    {\n        const double ta = (double)e0.cross( e1 ).norm() / 2.; // Tri area\n        area = ta / (check_obtuse(e0, e1) ? 2. : 4.);\n    }\n    return area;\n}\n\n// -----------------------------------------------------------------------------\n\nstatic\ndouble get_cell_area(int vidx,\n                     const std::vector< Vec3 >& vertices,\n                     const std::vector< std::vector<int> >& edges )\n{\n    double area = 0.0;\n    const Vec3 c_pos = vertices[vidx];\n    //get triangles areas\n    for(int e = 0; e < (int)edges[vidx].size(); ++e)\n    {\n        int ne = (e + 1) % edges[vidx].size();\n\n        if(true){\n            // Supposidely more precise (but a bit more complex to compute)\n            Vec3 p0 = vertices[edges[vidx][e ] ];\n            Vec3 p1 = vertices[edges[vidx][ne]];\n            area += mixed_voronoi_area(c_pos, p0, p1 );\n        }else{\n            // This should give descent results as well:\n            Vec3 edge0 = vertices[edges[vidx][e ]] - c_pos;\n            Vec3 edge1 = vertices[edges[vidx][ne]] - c_pos;\n            area += (edge0.cross(edge1)).norm() / 2.f;\n        }\n    }\n    return area;\n}\n\n\n// -----------------------------------------------------------------------------\n\nstatic\nfloat angle_between(const Vec3& v1, const Vec3& v2)\n{\n    float cosa = v1.dot(v2);\n    if(cosa >= 1.f)\n        return 0.f;\n    else if(cosa <= -1.f)\n        return M_PI;\n    else\n        return std::acos(cosa);\n}\n\n// -----------------------------------------------------------------------------\n\n/// @return A sparse representation of the Laplacian matrix 'L'\n/// list[ith_row][list of columns] = Triplet(ith_row, jth_column, matrix value)\nstatic\nstd::vector<std::vector<Triplet>>\nget_laplacian(const std::vector< Vec3 >& vertices,\n              const std::vector< std::vector<int> >& edges )\n{\n    std::cout << \"BUILD LAPLACIAN MATRIX\" << std::endl;\n    unsigned nv = unsigned(vertices.size());\n    std::vector<std::vector<Triplet>> mat_elemts(nv);\n    for(int i = 0; i < nv; ++i)\n        mat_elemts[i].reserve(10);\n\n    for(int i = 0; i < nv; ++i)\n    {\n        const Vec3 c_pos = vertices[i];\n\n        //get laplacian\n        double sum = 0.;\n        int nb_edges = edges[i].size();\n        for(int e = 0; e < nb_edges; ++e)\n        {\n            int next_edge = (e + 1           ) % nb_edges;\n            int prev_edge = (e + nb_edges - 1) % nb_edges;\n\n\n            /*                                 next_edge\n                                    e ◀---v4---(cotan2)\n                                   ◥ ◤         /\n                                  /   \\       /\n                                 v2    v5    v3\n                                /       \\   /\n                               /         \\ ◣\n                        (cotan1)----v1---▶c_pos\n                       prev_edge\n            */\n            Vec3 v1 = c_pos - vertices[edges[i][prev_edge]];\n            Vec3 v3 = c_pos - vertices[edges[i][next_edge]];\n            double w = 0.0;\n            if(true)\n            {\n                /* Cotangent weights\n                 * (may be negative and undesirable in certain situations)\n                */\n                Vec3 v2 = vertices[edges[i][e]] - vertices[edges[i][prev_edge]];\n                Vec3 v4 = vertices[edges[i][e]] - vertices[edges[i][next_edge]];\n\n                double cotan1 = (v1.dot(v2)) / (1e-6 + (v1.cross(v2)).norm() );\n                double cotan2 = (v3.dot(v4)) / (1e-6 + (v3.cross(v4)).norm() );\n\n                // TODO: check for edge cases such as\n                // the mesh corners and boundaries and adjust cotan weights\n                // appropriatly ...\n                w = (cotan1 + cotan2) * 0.5f;\n            } else {\n                // Mean value coordinations weights:\n                // doesn't really work something must be wrong\n                Vec3 v5 = c_pos - vertices[edges[i][e]];\n                v1.normalize();\n                v3.normalize();\n                float v5_norm = v5.normalize();\n                double tan1 = std::tan(angle_between(-v1, v5)*0.5f);\n                double tan2 = std::tan(angle_between(-v3, v5)*0.5f);\n                w = (tan1 + tan2) / (1e-6 + v5_norm);\n            }\n\n\n            // Disable / Enable multiplying against the inverse of\n            // the Mass matrix 'M':\n            if(false)\n            {\n                // If we want to return M^{-1}.L instead of just L\n                // Then we can do it here since its more efficient\n                // than building M^{-1} and then do the product M^{-1}.L\n                // Since we solve for harmonic weights\n                // M^{-1}.L = 0 can be simplified to L = 0\n                // and this step safely ignored\n                double area = get_cell_area(i, vertices, edges);\n                area = 1. / ((1e-10 + area));\n                w *= area;\n            }\n\n            sum += w;\n\n            mat_elemts[i].push_back( Triplet(i, edges[i][e], w) );\n        }\n\n        mat_elemts[i].push_back( Triplet(i, i, -sum) );\n    }\n    return mat_elemts;\n}\n\n//------------------------------------------------------------------------------\n\n/*\n    Alternate implementation of the Laplacian matrix using only the\n    list of triangles instead of the first ring neighboors.\n*/\nstatic\nstd::vector<std::vector<Triplet>>\nget_laplacian(const std::vector< Vec3 >& vertices,\n              const std::vector< Tri_face >& triangles )\n{\n\n    unsigned nv = unsigned(vertices.size());\n    std::vector<std::vector<Triplet>> mat_elemts(nv);\n    for(int i = 0; i < nv; ++i)\n        mat_elemts[i].reserve(10);\n\n    for( const Tri_face& f : triangles)\n    {\n        struct Edge { int i, j, org; };\n        std::vector<Edge> edges =\n        {\n            {f.a, f.b, f.c},\n            {f.b, f.c, f.a},\n            {f.c, f.a, f.b},\n        };\n\n        for(Edge edge : edges)\n        {\n            /*\n                                    j\n                                   ◥\n                                  /  \\\n                                 v2   \\\n                                /      \\\n                               /        \\\n                        (cotan)----v1---▶ i\n                           org\n            */\n            Vec3 v1 = vertices[edge.org] - vertices[edge.i];\n            Vec3 v2 = vertices[edge.org] - vertices[edge.j];\n            double cotan = (v1.dot(v2)) / (1e-6 + (v1.cross(v2)).norm() );\n            float w = cotan * 0.5f;\n\n            int i = edge.i;\n            int j = edge.j;\n            // Note Eigen::setFromTriplets will sum up duplicate elements for us\n            mat_elemts[i].push_back( Triplet(i, j,  w) );\n            mat_elemts[j].push_back( Triplet(j, i,  w) );\n            mat_elemts[i].push_back( Triplet(i, i, -w) );\n            mat_elemts[j].push_back( Triplet(j, j, -w) );\n        }\n    }\n    return mat_elemts;\n}\n\n//------------------------------------------------------------------------------\n\n// Compute harmonic weights\nvoid solve_laplace_equation(const std::vector< Vec3 >& vertices,\n        const std::vector< std::vector<int> >& edges,\n        const std::vector<Tri_face>& triangles,\n        const std::vector<std::pair<Vert_idx, float> >& boundaries,\n        std::vector<double>& harmonic_weight_map)\n{\n    std::cout << \"COMPUTE LAPLACE EQUATION\" << std::endl;\n\n    int nv = vertices.size();\n\n    // compute laplacian matrix of the mesh\n    /*\n        We can build the laplacian 'L' either from the half edge data structure\n        (edges) or simply the list of triangles.\n        For reference both versions are implemented here.\n    */\n    assert(edges.size() > 0 || triangles.size() > 0 );\n    std::vector<std::vector<Triplet>> mat_elemts;\n    if( edges.size() > 0)\n        mat_elemts = get_laplacian(vertices, edges);\n    else if( triangles.size() > 0 )\n        mat_elemts = get_laplacian(vertices, triangles);\n\n\n    // Set boundary conditions\n    Eigen::VectorXd rhs = Eigen::VectorXd::Constant(nv, 0.);\n    // Initialize handle\n    for(const std::pair<int, float>& elt : boundaries){\n        rhs( elt.first ) = double(elt.second);\n        // Set row to 0.0f\n        mat_elemts[elt.first].clear();\n        // Set\n        mat_elemts[elt.first].push_back( Triplet(elt.first, elt.first, 1.0) );\n    }\n\n\n#if 0\n    // Solving with a dense matrix is Extremely slow\n    Eigen::MatrixXd L = Eigen::MatrixXd::Constant(nv, nv, 0.);\n    for( const std::vector<Triplet>& row : mat_elemts)\n        for( const Triplet& elt : row )\n            L(elt.row(), elt.col()) = elt.value();\n\n    //Eigen::ColPivHouseholderQR<Eigen::MatrixXd> llt;\n    Eigen::FullPivLU<Eigen::MatrixXd> solver;\n    std::cout << \"BEGIN MATRIX FACTORIZATION\" << std::endl;\n    solver.compute( L );\n    std::cout << \"END MATRIX FACTORIZATION\" << std::endl;\n\n#else\n    Sparse_mat L(nv, nv);\n    // Convert to triplets\n    std::vector<Triplet> triplets;\n    triplets.reserve(nv * 10);\n    for( const std::vector<Triplet>& row : mat_elemts)\n        for( const Triplet& elt : row )\n            triplets.push_back( elt );\n\n    L.setFromTriplets(triplets.begin(), triplets.end());\n\n    Eigen::SparseLU<Sparse_mat> solver;\n    std::cout << \"BEGIN SPARSE MATRIX FACTORIZATION\" << std::endl;\n    solver.compute( L );\n    std::cout << \"END SPARSE MATRIX FACTORIZATION\" << std::endl;\n#endif\n\n    harmonic_weight_map.resize(nv);\n    Eigen::VectorXd res = solver.solve( rhs );\n    for(int i = 0; i < nv; ++i)\n        harmonic_weight_map[i] = res(i);\n\n    return;\n}\n\n// -----------------------------------------------------------------------------\n\n", "meta": {"hexsha": "3a48c365c57f885b486d4de4c8f2af20ffe26e02", "size": 11296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solve_laplace_equation.cpp", "max_stars_repo_name": "jonntd/harmonic_weights_triangle_mesh", "max_stars_repo_head_hexsha": "c5fc2304dcd3490ee167dda5b39d4e0a623db2a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-19T23:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-20T12:14:38.000Z", "max_issues_repo_path": "src/solve_laplace_equation.cpp", "max_issues_repo_name": "brainexcerpts/harmonic_weights_triangle_mesh", "max_issues_repo_head_hexsha": "09c92dc5a793eb1b396ebef5b76ddbe54ee4f70a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solve_laplace_equation.cpp", "max_forks_repo_name": "brainexcerpts/harmonic_weights_triangle_mesh", "max_forks_repo_head_hexsha": "09c92dc5a793eb1b396ebef5b76ddbe54ee4f70a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-10-29T03:25:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-19T01:53:26.000Z", "avg_line_length": 32.2742857143, "max_line_length": 83, "alphanum_fraction": 0.4705205382, "num_tokens": 2843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5892485179644762}}
{"text": "// Author: Tucker Haydon\n\n#include \"gnuplot-iostream.h\"\n\n#include <cstdlib>\n#include <Eigen/Dense>\n\n#include \"polynomial_solver.h\"\n#include \"polynomial_sampler.h\"\n\nusing namespace p4;\n\nint main(int argc, char** argv) {\n\n  // Time in seconds\n  const std::vector<double> times = {0, 1, 2.5};\n\n  // NodeEqualityBound(dimension_idx, node_idx, derivative_idx, value)\n  const std::vector<NodeEqualityBound> node_equality_bounds = {\n    // Constraining position and velocity of first node to zero\n    NodeEqualityBound(0,0,0,0),\n    NodeEqualityBound(1,0,0,0),\n    NodeEqualityBound(2,0,0,0),\n    NodeEqualityBound(0,0,1,0),\n    NodeEqualityBound(1,0,1,0),\n    NodeEqualityBound(2,0,1,0),\n\n    // Other nodes may constrain whatever they want\n    // The second node is constraining position to (1,0,0)\n    NodeEqualityBound(0,1,0,1),\n    NodeEqualityBound(1,1,0,0),\n    NodeEqualityBound(2,1,0,0),\n\n    // The third node is contraining position to (1,1,free)\n    NodeEqualityBound(0,2,0,1),\n    NodeEqualityBound(1,2,0,1),\n  };\n\n  // NodeInequalityBound(dimension_idx, node_idx, derivative_idx, lower, upper)\n  const std::vector<NodeInequalityBound> node_inequality_bounds = {\n    // Constraining the z value of the third node above 0.5\n    NodeInequalityBound(2,2,0,0.5,NodeInequalityBound::INFTY),\n  };\n\n  // SegmentInequalityBound(segment_idx, derivative_idx, mapping, value)\n  // Segment inequality bounds constrain a derivative of a segment to \n  //   dot(a,x) < b\n  const std::vector<SegmentInequalityBound> segment_inequality_bounds = {\n    // Constraining the x-acceleration of the first segment below 4 m/s^2\n    SegmentInequalityBound(0,2,Eigen::Vector3d(1,0,0),4),\n  };\n\n  // Configure solver options\n  PolynomialSolver::Options solver_options;\n  solver_options.num_dimensions   = 3;   // 3D\n  solver_options.polynomial_order = 8;   // Fit an 8th-order polynomial\n  solver_options.continuity_order = 4;   // Require continuity through the 4th derivative\n  solver_options.derivative_order = 2;   // Minimize the 2nd derivative (acceleration)\n\n  // Configure the OSQP settings\n  // Reference: https://osqp.org/docs/interfaces/cc++#settings\n  solver_options.osqp_settings.polish = true;       // Polish the solution, getting the best answer possible\n  solver_options.osqp_settings.verbose = false;     // Suppress the printout\n\n  // Solve\n  PolynomialSolver solver(solver_options);\n  const PolynomialSolver::Solution solution\n    = solver.Run(\n        times, \n        node_equality_bounds,\n        node_inequality_bounds,\n        segment_inequality_bounds);\n\n  // Print some output info\n  // Reference: https://osqp.org/docs/interfaces/cc++#info\n  std::cout << \"Status:                    \" << solution.workspace->info->status << std::endl;\n  std::cout << \"Status Val (1 == success): \" << solution.workspace->info->status_val << std::endl;\n  std::cout << \"Optimal Cost:              \" << solution.workspace->info->obj_val << std::endl;\n\n  // Sampling and Plotting\n  { // Plot acceleration profiles\n    PolynomialSampler::Options sampler_options;\n    sampler_options.frequency = 100;\n    sampler_options.derivative_order = 2;\n\n    PolynomialSampler sampler(sampler_options);\n    Eigen::MatrixXd samples = sampler.Run(times, solution);\n\n    std::vector<double> t_hist, x_hist, y_hist, z_hist;\n    for(size_t time_idx = 0; time_idx < samples.cols(); ++time_idx) {\n      t_hist.push_back(samples(0,time_idx));\n      x_hist.push_back(samples(1,time_idx));\n      y_hist.push_back(samples(2,time_idx));\n      z_hist.push_back(samples(3,time_idx));\n    }\n\n    Gnuplot gp;\n    gp << \"plot '-' using 1:2 with lines title 'X-Acceleration'\";\n    gp << \", '-' using 1:2 with lines title 'Y-Acceleration'\";\n    gp << \", '-' using 1:2 with lines title 'Z-Acceleration'\";\n    gp << std::endl;\n    gp.send1d(boost::make_tuple(t_hist, x_hist));\n    gp.send1d(boost::make_tuple(t_hist, y_hist));\n    gp.send1d(boost::make_tuple(t_hist, z_hist));\n    gp << \"set grid\" << std::endl;\n    gp << \"replot\" << std::endl;\n  }\n\n  { // Plot velocity profiles\n    PolynomialSampler::Options sampler_options;\n    sampler_options.frequency = 100;\n    sampler_options.derivative_order = 1;\n\n    PolynomialSampler sampler(sampler_options);\n    Eigen::MatrixXd samples = sampler.Run(times, solution);\n\n    std::vector<double> t_hist, x_hist, y_hist, z_hist;\n    for(size_t time_idx = 0; time_idx < samples.cols(); ++time_idx) {\n      t_hist.push_back(samples(0,time_idx));\n      x_hist.push_back(samples(1,time_idx));\n      y_hist.push_back(samples(2,time_idx));\n      z_hist.push_back(samples(3,time_idx));\n    }\n\n    Gnuplot gp;\n    gp << \"plot '-' using 1:2 with lines title 'X-Velocity'\";\n    gp << \", '-' using 1:2 with lines title 'Y-Velocity'\";\n    gp << \", '-' using 1:2 with lines title 'Z-Velocity'\";\n    gp << std::endl;\n    gp.send1d(boost::make_tuple(t_hist, x_hist));\n    gp.send1d(boost::make_tuple(t_hist, y_hist));\n    gp.send1d(boost::make_tuple(t_hist, z_hist));\n    gp << \"set grid\" << std::endl;\n    gp << \"replot\" << std::endl;\n  }\n\n  { // Plot 3D position\n    PolynomialSampler::Options sampler_options;\n    sampler_options.frequency = 50;\n    sampler_options.derivative_order = 0;\n\n    PolynomialSampler sampler(sampler_options);\n    Eigen::MatrixXd samples = sampler.Run(times, solution);\n\n    std::vector<double> t_hist, x_hist, y_hist, z_hist;\n    for(size_t time_idx = 0; time_idx < samples.cols(); ++time_idx) {\n      t_hist.push_back(samples(0,time_idx));\n      x_hist.push_back(samples(1,time_idx));\n      y_hist.push_back(samples(2,time_idx));\n      z_hist.push_back(samples(3,time_idx));\n    }\n\n    Gnuplot gp;\n    gp << \"splot '-' using 1:2:3 with lines title 'Trajectory'\" << std::endl;\n    gp.send1d(boost::make_tuple(x_hist, y_hist, z_hist));\n    gp << \"set grid\" << std::endl;\n    gp << \"replot\" << std::endl;\n\n    // Must keep position gp in scope to rotate 3D graph\n    std::cout << \"Press enter to exit.\" << std::endl;\n    std::cin.get();\n  }\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8c830e29142ce1647ac57d61020782c783280cad", "size": 5975, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/3D.cc", "max_stars_repo_name": "TuckerHaydon/MinimumSnap", "max_stars_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T07:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T03:37:48.000Z", "max_issues_repo_path": "examples/3D.cc", "max_issues_repo_name": "TuckerHaydon/MinimumSnap", "max_issues_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T23:00:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T18:37:04.000Z", "max_forks_repo_path": "examples/3D.cc", "max_forks_repo_name": "TuckerHaydon/MinimumSnap", "max_forks_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T21:44:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T09:55:09.000Z", "avg_line_length": 35.9939759036, "max_line_length": 108, "alphanum_fraction": 0.6778242678, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5892233571760366}}
{"text": "/**\n * @file expfittedupwind_main.cc\n * @brief NPDE homework ExpFittedUpwind\n * @author Amélie Loher, Philippe Peter\n * @date 07.01.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n\n#include \"expfittedupwind.h\"\n\nint main() {\n  // Define Mesh-independent Data:\n#if SOLUTION\n  auto f = [](Eigen::Vector2d x) { return 0.0; };\n\n  Eigen::Vector2d q = Eigen::Vector2d::Ones(2);\n  auto Psi = [&q](Eigen::Vector2d x) { return q.dot(x); };\n\n  auto g = [&Psi](Eigen::Vector2d x) { return std::exp(Psi(x)); };\n\n  auto ref_sol = [&Psi](Eigen::Vector2d x) { return std::exp(Psi(x)); };\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  // Output file\n  std::ofstream L2output;\n  L2output.open(\"L2error.txt\");\n  L2output << \"No. of dofs, L2 error\" << std::endl;\n\n  // generate a mesh hierarchy:\n  unsigned int reflevels = 6;\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  auto top_mesh = builder.Build();\n\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(top_mesh,\n                                                              reflevels);\n  lf::refinement::MeshHierarchy& multi_mesh{*multi_mesh_p};\n  multi_mesh.PrintInfo(std::cout);\n\n  // get number of levels:\n  auto L = multi_mesh.NumLevels();\n\n  // perform computations on all levels:\n  for (int l = 0; l < L; ++l) {\n    // Compute finite element solution and compute L2 error on current level:\n    double L2_err = 1.0;\n\n    // get current mesh and fe space\n    auto mesh_p = multi_mesh.getMesh(l);\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n    const lf::assemble::DofHandler& dofh{fe_space->LocGlobMap()};\n    const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n#if SOLUTION\n    // wrap Psi and the reference solution into a mesh function on the current\n    // level\n    auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(Psi);\n    Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n    auto mf_ref_sol = lf::mesh::utils::MeshFunctionGlobal(ref_sol);\n\n    // compute the finite element solution and wrap it into a mesh function\n    Eigen::VectorXd sol_vec =\n        ExpFittedUpwind::SolveDriftDiffusionDirBVP(fe_space, mu, f, g);\n    auto mf_sol = lf::fe::MeshFunctionFE(fe_space, sol_vec);\n\n    // evaluate L2 error:\n    L2_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::uscalfe::squaredNorm(mf_sol - mf_ref_sol), 3));\n#else\n    //====================\n    // Your code goes here\n    //====================\n#endif\n\n    L2output << N_dofs << \", \" << L2_err << std::endl;\n    std::cout << N_dofs << \",\" << L2_err << std::endl;\n  }\n\n  L2output.close();\n\n  // Plot the computed L2 error\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_error.py \" CURRENT_BINARY_DIR\n              \"/L2error.txt \" CURRENT_BINARY_DIR \"/results.eps\");\n\n  return 0;\n}\n", "meta": {"hexsha": "d45839e826c9393a727de96b929ffd0e30eaae3d", "size": 3539, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ExpFittedUpwind/mastersolution/expfittedupwind_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/ExpFittedUpwind/mastersolution/expfittedupwind_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/ExpFittedUpwind/mastersolution/expfittedupwind_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.0438596491, "max_line_length": 80, "alphanum_fraction": 0.6476405764, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5892233571760366}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\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#include <boost/graph/dag_shortest_paths.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n\r\n#include <iostream>\r\n\r\n// Example from Introduction to Algorithms by Cormen, et all p.537.\r\n\r\n// Sample output:\r\n//  r: inifinity\r\n//  s: 0\r\n//  t: 2\r\n//  u: 6\r\n//  v: 5\r\n//  x: 3\r\n\r\nint main()\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list<vecS, vecS, directedS, \r\n    property<vertex_distance_t, int>, property<edge_weight_t, int> > graph_t;\r\n  graph_t g(6);\r\n  enum verts { r, s, t, u, v, x };\r\n  char name[] = \"rstuvx\";\r\n  add_edge(r, s, 5, g);\r\n  add_edge(r, t, 3, g);\r\n  add_edge(s, t, 2, g);\r\n  add_edge(s, u, 6, g);\r\n  add_edge(t, u, 7, g);\r\n  add_edge(t, v, 4, g);\r\n  add_edge(t, x, 2, g);\r\n  add_edge(u, v, -1, g);\r\n  add_edge(u, x, 1, g);\r\n  add_edge(v, x, -2, g);\r\n\r\n  property_map<graph_t, vertex_distance_t>::type\r\n    d_map = get(vertex_distance, g);\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ has trouble with the named-parameter mechanism, so\r\n  // we make a direct call to the underlying implementation function.\r\n  std::vector<default_color_type> color(num_vertices(g));\r\n  std::vector<std::size_t> pred(num_vertices(g));\r\n  default_dijkstra_visitor vis;\r\n  std::less<int> compare;\r\n  closed_plus<int> combine;\r\n  property_map<graph_t, edge_weight_t>::type w_map = get(edge_weight, g);\r\n  dag_shortest_paths(g, s, d_map, w_map, &color[0], &pred[0], \r\n     vis, compare, combine, (std::numeric_limits<int>::max)(), 0);\r\n#else\r\n  dag_shortest_paths(g, s, distance_map(d_map));\r\n#endif\r\n\r\n  graph_traits<graph_t>::vertex_iterator vi , vi_end;\r\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    if (d_map[*vi] == (std::numeric_limits<int>::max)())\r\n      std::cout << name[*vi] << \": inifinity\\n\";\r\n    else\r\n      std::cout << name[*vi] << \": \" << d_map[*vi] << '\\n';\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "81ba1a2e028fe55a039f9f380d823be61af0758a", "size": 2276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/dag_shortest_paths.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/dag_shortest_paths.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/dag_shortest_paths.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": 32.5142857143, "max_line_length": 78, "alphanum_fraction": 0.5931458699, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.5891873646342806}}
{"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 * Authors: Natasha Sharma, University of Texas at El Paso, \n *          Guido Kanschat, University of Heidelberg \n *          Timo Heister, Clemson University \n *          Wolfgang Bangerth, Colorado State University \n *          Zhuroan Wang, Colorado State University \n */ \n\n\n// @sect3{Include files}  \n\n// 前面的几个include文件已经在前面的例子中使用过了，所以我们在这里不再解释它们的含义。该程序的主要结构与例如 step-4 的结构非常相似，因此我们包含了许多相同的头文件。\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/full_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/sparse_matrix.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\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/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n// 最有趣的两个头文件将是这两个。\n\n#include <deal.II/fe/fe_interface_values.h> \n#include <deal.II/meshworker/mesh_loop.h> \n\n// 其中第一个文件负责提供FEInterfaceValues类，该类可用于评估单元间界面的形状函数（或其梯度）的跳跃或平均值等数量。这个类在评估C0IP公式中出现的惩罚项时将相当有用。\n\n#include <fstream> \n#include <iostream> \n#include <cmath> \n\nnamespace Step47 \n{ \n  using namespace dealii; \n\n// 在下面的命名空间中，让我们定义精确解，我们将与数值计算的解进行比较。它的形式是 $u(x,y) = \\sin(\\pi x) \\sin(\\pi y)$ （只实现了2d的情况），该命名空间还包含一个对应于产生该解的右手边的类。\n\n  namespace ExactSolution \n  { \n    using numbers::PI; \n\n    template <int dim> \n    class Solution : public Function<dim> \n    { \n    public: \n      static_assert(dim == 2, \"Only dim==2 is implemented.\"); \n\n      virtual double value(const Point<dim> &p, \n                           const unsigned int /*component*/ = 0) const override \n      { \n        return std::sin(PI * p[0]) * std::sin(PI * p[1]); \n      } \n\n      virtual Tensor<1, dim> \n      gradient(const Point<dim> &p, \n               const unsigned int /*component*/ = 0) const override \n      { \n        Tensor<1, dim> r; \n        r[0] = PI * std::cos(PI * p[0]) * std::sin(PI * p[1]); \n        r[1] = PI * std::cos(PI * p[1]) * std::sin(PI * p[0]); \n        return r; \n      } \n\n      virtual void \n      hessian_list(const std::vector<Point<dim>> &       points, \n                   std::vector<SymmetricTensor<2, dim>> &hessians, \n                   const unsigned int /*component*/ = 0) const override \n      { \n        for (unsigned i = 0; i < points.size(); ++i) \n          { \n            const double x = points[i][0]; \n            const double y = points[i][1]; \n\n            hessians[i][0][0] = -PI * PI * std::sin(PI * x) * std::sin(PI * y); \n            hessians[i][0][1] = PI * PI * std::cos(PI * x) * std::cos(PI * y); \n            hessians[i][1][1] = -PI * PI * std::sin(PI * x) * std::sin(PI * y); \n          } \n      } \n    }; \n\n    template <int dim> \n    class RightHandSide : public Function<dim> \n    { \n    public: \n      static_assert(dim == 2, \"Only dim==2 is implemented\"); \n\n      virtual double value(const Point<dim> &p, \n                           const unsigned int /*component*/ = 0) const override \n\n      { \n        return 4 * std::pow(PI, 4.0) * std::sin(PI * p[0]) * \n               std::sin(PI * p[1]); \n      } \n    }; \n  } // namespace ExactSolution \n\n//  @sect3{The main class}  \n\n// 以下是本教程程序的主类。它具有许多其他教程程序的结构，其内容和后面的构造函数应该没有什么特别令人惊讶的地方。\n\n  template <int dim> \n  class BiharmonicProblem \n  { \n  public: \n    BiharmonicProblem(const unsigned int fe_degree); \n\n    void run(); \n\n  private: \n    void make_grid(); \n    void setup_system(); \n    void assemble_system(); \n    void solve(); \n    void compute_errors(); \n    void output_results(const unsigned int iteration) const; \n\n    Triangulation<dim> triangulation; \n\n    MappingQ<dim> mapping; \n\n    FE_Q<dim>                 fe; \n    DoFHandler<dim>           dof_handler; \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\n  template <int dim> \n  BiharmonicProblem<dim>::BiharmonicProblem(const unsigned int fe_degree) \n    : mapping(1) \n    , fe(fe_degree) \n    , dof_handler(triangulation) \n  {} \n\n// 接下来是创建初始网格（一次精炼的单元格）和设置每个网格的约束、向量和矩阵的函数。同样，这两个函数与之前的许多教程程序基本没有变化。\n\n  template <int dim> \n  void BiharmonicProblem<dim>::make_grid() \n  { \n    GridGenerator::hyper_cube(triangulation, 0., 1.); \n    triangulation.refine_global(1); \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  template <int dim> \n  void BiharmonicProblem<dim>::setup_system() \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    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n\n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             ExactSolution::Solution<dim>(), \n                                             constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp, constraints, true); \n    sparsity_pattern.copy_from(dsp); \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//  @sect4{Assembling the linear system}  \n\n// 下面的几段代码更有意思。它们都与线性系统的组装有关。虽然组装单元格内部项的难度不大--这在本质上就像组装拉普拉斯方程的相应项一样，你已经在 step-4 或 step-6 中看到了这是如何工作的，例如，困难在于公式中的惩罚项。这需要在单元格的界面上对形状函数的梯度进行评估。因此，至少需要使用两个FEFaceValues对象，但如果其中一个面是自适应细化的，那么实际上需要一个FEFaceValues和一个FESubfaceValues对象；我们还需要跟踪哪些形状函数在哪里，最后我们需要确保每个面只被访问一次。所有这些对于我们真正想要实现的逻辑（即双线性形式中的惩罚项）来说都是一笔不小的开销。因此，我们将使用FEInterfaceValues类--这是deal.II中的一个辅助类，它允许我们抽象出两个FEFaceValues或FESubfaceValues对象，直接访问我们真正关心的东西：跳跃、平均等。\n\n// 但这还没有解决我们的问题，即当我们在所有单元格和它们的所有面中循环时，必须跟踪我们已经访问过哪些面。为了使这个过程更简单，我们使用了 MeshWorker::mesh_loop() 函数，它为这个任务提供了一个简单的接口：基于WorkStream命名空间文档中概述的想法， MeshWorker::mesh_loop() 需要三个函数对单元、内部面和边界面进行工作。这些函数在抓取对象上工作，以获得中间结果，然后将其计算结果复制到复制数据对象中，由一个复制器函数将其复制到全局矩阵和右侧对象中。\n\n// 然后，下面的结构提供了这种方法所需的从头开始和复制对象。你可以查阅WorkStream命名空间以及 @ref threads \"多处理器并行计算 \"模块，了解更多关于它们通常如何工作的信息。\n\n  template <int dim> \n  struct 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\n  struct CopyData \n  { \n    CopyData(const unsigned int dofs_per_cell) \n      : cell_matrix(dofs_per_cell, dofs_per_cell) \n      , cell_rhs(dofs_per_cell) \n      , local_dof_indices(dofs_per_cell) \n    {} \n\n    CopyData(const CopyData &) = default; \n\n    CopyData(CopyData &&) = default; \n\n    ~CopyData() = default; \n\n    CopyData &operator=(const CopyData &) = default; \n\n    CopyData &operator=(CopyData &&) = default; \n\n    struct FaceData \n    { \n      FullMatrix<double>                   cell_matrix; \n      std::vector<types::global_dof_index> joint_dof_indices; \n    }; \n\n    FullMatrix<double>                   cell_matrix; \n    Vector<double>                       cell_rhs; \n    std::vector<types::global_dof_index> local_dof_indices; \n    std::vector<FaceData>                face_data; \n  }; \n\n// 更有趣的部分是我们实际组装线性系统的地方。从根本上说，这个函数有五个部分。\n\n// - `cell_worker`λ函数的定义，这是一个定义在`assemble_system()`函数中的小函数，它将负责计算单个单元上的局部积分。它将在`ScratchData`类的副本上工作，并将其结果放入相应的`CopyData`对象。\n\n// - `face_worker` lambda函数的定义，它将对单元格之间的界面上的所有项进行积分。\n\n// - 定义了`boundary_worker`函数，对位于域的边界上的单元面做同样的工作。\n\n// - `copier`函数的定义，该函数负责将前面三个函数中的所有数据复制到单个单元的复制对象中，并复制到全局矩阵和右侧。\n\n// 第五部分是我们把所有这些都集中在一起。\n\n// 让我们轮流浏览一下这些组装所需的每一块。\n\n  template <int dim> \n  void BiharmonicProblem<dim>::assemble_system() \n  { \n    using Iterator = typename DoFHandler<dim>::active_cell_iterator; \n\n// 第一部分是`cell_worker'，它在细胞内部进行组装。它是一个（lambda）函数，以一个单元格（输入）、一个抓取对象和一个复制对象（输出）为参数。它看起来像许多其他教程程序的装配函数，或者至少是所有单元格的循环主体。\n\n// 我们在这里整合的条款是单元格对全局矩阵的贡献\n// @f{align*}{\n//     A^K_{ij} = \\int_K \\nabla^2\\varphi_i(x) : \\nabla^2\\varphi_j(x) dx\n//  @f} ，\n//  以及对右侧向量的贡献\n//  @f{align*}{\n//     f^K_i = \\int_K \\varphi_i(x) f(x) dx\n//  @f}\n\n// 我们使用与组装 step-22 相同的技术来加速该函数。我们不在最里面的循环中调用`fe_values.shape_hessian(i, qpoint)`，而是创建一个变量`hessian_i`，在循环中对`i`进行一次评估，在循环中对`j`重新使用如此评估的值。为了对称，我们对变量`hessian_j`也做了同样的处理，尽管它确实只用了一次，而且我们可以在计算两个项之间标量乘积的指令中留下对`fe_values.shape_hessian(j,qpoint)`的调用。\n\n    auto cell_worker = [&](const Iterator &  cell, \n                           ScratchData<dim> &scratch_data, \n                           CopyData &        copy_data) { \n      copy_data.cell_matrix = 0; \n      copy_data.cell_rhs    = 0; \n\n      FEValues<dim> &fe_values = scratch_data.fe_values; \n      fe_values.reinit(cell); \n\n      cell->get_dof_indices(copy_data.local_dof_indices); \n\n      const ExactSolution::RightHandSide<dim> right_hand_side; \n\n      const unsigned int dofs_per_cell = \n        scratch_data.fe_values.get_fe().n_dofs_per_cell(); \n\n      for (unsigned int qpoint = 0; qpoint < fe_values.n_quadrature_points; \n           ++qpoint) \n        { \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const Tensor<2, dim> &hessian_i = \n                fe_values.shape_hessian(i, qpoint); \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const Tensor<2, dim> &hessian_j = \n                    fe_values.shape_hessian(j, qpoint); \n\n                  copy_data.cell_matrix(i, j) += \n                    scalar_product(hessian_i,   // nabla^2 phi_i(x) \n                                   hessian_j) * // nabla^2 phi_j(x) \n                    fe_values.JxW(qpoint);      // dx \n                } \n\n              copy_data.cell_rhs(i) += \n                fe_values.shape_value(i, qpoint) * // phi_i(x) \n                right_hand_side.value( \n                  fe_values.quadrature_point(qpoint)) * // f(x) \n                fe_values.JxW(qpoint);                  // dx \n            } \n        } \n    }; \n\n// 下一个构建模块是在网格的每个内部面组装惩罚项。正如 MeshWorker::mesh_loop(), 文档中所描述的，这个函数接收到的参数表示一个单元和它的相邻单元，以及（对于这两个单元中的每一个）我们必须整合的面（以及潜在的子面）。同样地，我们也得到了一个从头开始的对象，以及一个用于放置结果的拷贝对象。\n\n// 这个函数本身有三个部分。在顶部，我们初始化FEInterfaceValues对象，并创建一个新的 `CopyData::FaceData` 对象来存储我们的输入。这将被推到`copy_data.face_data`变量的末尾。我们需要这样做，因为我们对一个给定单元进行积分的面（或子面）的数量因单元而异，而且这些矩阵的大小也不同，取决于面或子面相邻的自由度。正如 MeshWorker::mesh_loop(), 文档中所讨论的，每次访问一个新的单元时，复制对象都会被重置，所以我们推到`copy_data.face_data()`末尾的内容实际上就是后来的`copier`函数在复制每个单元的贡献到全局矩阵和右侧对象时所能看到的。\n\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.joint_dof_indices = \n        fe_interface_values.get_interface_dof_indices(); \n\n      const unsigned int n_interface_dofs = \n        fe_interface_values.n_current_interface_dofs(); \n      copy_data_face.cell_matrix.reinit(n_interface_dofs, n_interface_dofs); \n\n// 第二部分涉及到确定惩罚参数应该是什么。通过观察双线性形式中各种项的单位，很明显，惩罚必须具有 $\\frac{\\gamma}{h_K}$ 的形式（即，超过长度尺度的一个），但如何选择无维数 $\\gamma$ 并不是先验的。从拉普拉斯方程的不连续Galerkin理论来看，人们可能猜想正确的选择是 $\\gamma=p(p+1)$ 是正确的选择，其中 $p$ 是所用有限元的多项式程度。我们将在本程序的结果部分更详细地讨论这个选择。\n\n// 在上面的公式中， $h_K$  是单元格  $K$  的大小。但这也不是很简单的事情。如果使用高度拉伸的单元格，那么一个更复杂的理论说， $h$ 应该被单元格 $K$ 的直径取代，该直径是有关边缘方向的法线。 事实证明，在deal.II中有一个函数用于此。其次，当从一个面的两个不同侧面看时， $h_K$ 可能是不同的。\n\n// 为了安全起见，我们取这两个值的最大值。我们将注意到，如果使用自适应网格细化所产生的悬空节点，有可能需要进一步调整这一计算方法。\n\n      const unsigned int p = fe.degree; \n      const double       gamma_over_h = \n        std::max((1.0 * p * (p + 1) / \n                  cell->extent_in_direction( \n                    GeometryInfo<dim>::unit_normal_direction[f])), \n                 (1.0 * p * (p + 1) / \n                  ncell->extent_in_direction( \n                    GeometryInfo<dim>::unit_normal_direction[nf]))); \n\n// 最后，像往常一样，我们在正交点和指数`i`和`j`上循环，把这个面或子面的贡献加起来。然后将这些数据存储在上面创建的`copy_data.face_data`对象中。至于单元格工作者，如果可能的话，我们将平均数和跳跃的评估从循环中拉出来，引入局部变量来存储这些结果。然后组件只需要在最里面的循环中使用这些局部变量。关于这段代码实现的具体公式，回顾一下，双线性形式的接口项如下。\n// @f{align*}{\n//   -\\sum_{e \\in \\mathbb{F}} \\int_{e}\n//   \\jump{ \\frac{\\partial v_h}{\\partial \\mathbf n}}\n//   \\average{\\frac{\\partial^2 u_h}{\\partial \\mathbf n^2}} \\ ds\n//  -\\sum_{e \\in \\mathbb{F}} \\int_{e}\n//  \\average{\\frac{\\partial^2 v_h}{\\partial \\mathbf n^2}}\n//  \\jump{\\frac{\\partial u_h}{\\partial \\mathbf n}} \\ ds\n//  + \\sum_{e \\in \\mathbb{F}}\n//  \\frac{\\gamma}{h_e}\n//  \\int_e\n//  \\jump{\\frac{\\partial v_h}{\\partial \\mathbf n}}\n//  \\jump{\\frac{\\partial u_h}{\\partial \\mathbf n}} \\ ds.\n//  @f}\n\n      for (unsigned int qpoint = 0; \n           qpoint < fe_interface_values.n_quadrature_points; \n           ++qpoint) \n        { \n          const auto &n = fe_interface_values.normal(qpoint); \n\n          for (unsigned int i = 0; i < n_interface_dofs; ++i) \n            { \n              const double av_hessian_i_dot_n_dot_n = \n                (fe_interface_values.average_hessian(i, qpoint) * n * n); \n              const double jump_grad_i_dot_n = \n                (fe_interface_values.jump_gradient(i, qpoint) * n); \n\n              for (unsigned int j = 0; j < n_interface_dofs; ++j) \n                { \n                  const double av_hessian_j_dot_n_dot_n = \n                    (fe_interface_values.average_hessian(j, qpoint) * n * n); \n                  const double jump_grad_j_dot_n = \n                    (fe_interface_values.jump_gradient(j, qpoint) * n); \n\n                  copy_data_face.cell_matrix(i, j) += \n                    (-av_hessian_i_dot_n_dot_n       // - {grad^2 v n n } \n                       * jump_grad_j_dot_n           // [grad u n] \n                     - av_hessian_j_dot_n_dot_n      // - {grad^2 u n n } \n                         * jump_grad_i_dot_n         // [grad v n] \n                     +                               // + \n                     gamma_over_h *                  // gamma/h \n                       jump_grad_i_dot_n *           // [grad v n] \n                       jump_grad_j_dot_n) *          // [grad u n] \n                    fe_interface_values.JxW(qpoint); // dx \n                } \n            } \n        } \n    }; \n\n// 第三块是对处于边界的面做同样的装配。当然，想法和上面一样，唯一不同的是，现在有惩罚条款也进入了右手边。\n\n// 和以前一样，这个函数的第一部分只是设置了一些辅助对象。\n\n    auto boundary_worker = [&](const Iterator &    cell, \n                               const unsigned int &face_no, \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, face_no); \n      const auto &q_points = fe_interface_values.get_quadrature_points(); \n\n      copy_data.face_data.emplace_back(); \n      CopyData::FaceData &copy_data_face = copy_data.face_data.back(); \n\n      const unsigned int n_dofs = \n        fe_interface_values.n_current_interface_dofs(); \n      copy_data_face.joint_dof_indices = \n        fe_interface_values.get_interface_dof_indices(); \n\n      copy_data_face.cell_matrix.reinit(n_dofs, n_dofs); \n\n      const std::vector<double> &JxW = fe_interface_values.get_JxW_values(); \n      const std::vector<Tensor<1, dim>> &normals = \n        fe_interface_values.get_normal_vectors(); \n\n      const ExactSolution::Solution<dim> exact_solution; \n      std::vector<Tensor<1, dim>>        exact_gradients(q_points.size()); \n      exact_solution.gradient_list(q_points, exact_gradients); \n\n// 从正面看，由于我们现在只处理与面相邻的一个单元（因为我们在边界上），惩罚因子 $\\gamma$ 的计算大大简化了。\n\n      const unsigned int p = fe.degree; \n      const double       gamma_over_h = \n        (1.0 * p * (p + 1) / \n         cell->extent_in_direction( \n           GeometryInfo<dim>::unit_normal_direction[face_no])); \n\n// 第三块是术语的组合。由于这些条款包含了矩阵的条款和右手边的条款，所以现在稍微有些麻烦。前者与上面所说的内部面完全相同，如果我们只是适当地定义了跳跃和平均（这就是FEInterfaceValues类所做的）。后者需要我们评估边界条件 $j(\\mathbf x)$ ，在当前情况下（我们知道确切的解决方案），我们从 $j(\\mathbf x) = \\frac{\\partial u(\\mathbf x)}{\\partial {\\mathbf n}}$ 中计算出来。然后，要添加到右侧向量的项是  $\\frac{\\gamma}{h_e}\\int_e \\jump{\\frac{\\partial v_h}{\\partial \\mathbf n}} j \\ ds$  。\n\n      for (unsigned int qpoint = 0; qpoint < q_points.size(); ++qpoint) \n        { \n          const auto &n = normals[qpoint]; \n\n          for (unsigned int i = 0; i < n_dofs; ++i) \n            { \n              const double av_hessian_i_dot_n_dot_n = \n                (fe_interface_values.average_hessian(i, qpoint) * n * n); \n              const double jump_grad_i_dot_n = \n                (fe_interface_values.jump_gradient(i, qpoint) * n); \n\n              for (unsigned int j = 0; j < n_dofs; ++j) \n                { \n                  const double av_hessian_j_dot_n_dot_n = \n                    (fe_interface_values.average_hessian(j, qpoint) * n * n); \n                  const double jump_grad_j_dot_n = \n                    (fe_interface_values.jump_gradient(j, qpoint) * n); \n\n                  copy_data_face.cell_matrix(i, j) += \n                    (-av_hessian_i_dot_n_dot_n  // - {grad^2 v n n} \n                       * jump_grad_j_dot_n      //   [grad u n] \n\n//                                      \n\n                     - av_hessian_j_dot_n_dot_n // - {grad^2 u n n} \n                         * jump_grad_i_dot_n    //   [grad v n] \n\n//                                      \n\n                     + gamma_over_h             //  gamma/h \n                         * jump_grad_i_dot_n    // [grad v n] \n                         * jump_grad_j_dot_n    // [grad u n] \n                     ) * \n                    JxW[qpoint]; // dx \n                } \n\n              copy_data.cell_rhs(i) += \n                (-av_hessian_i_dot_n_dot_n *       // - {grad^2 v n n } \n                   (exact_gradients[qpoint] * n)   //   (grad u_exact . n) \n                 +                                 // + \n                 gamma_over_h                      //  gamma/h \n                   * jump_grad_i_dot_n             // [grad v n] \n                   * (exact_gradients[qpoint] * n) // (grad u_exact . n) \n                 ) * \n                JxW[qpoint]; // dx \n            } \n        } \n    }; \n\n// 第四部分是一个小函数，它将上面的单元格、内部和边界面装配程序产生的数据复制到全局矩阵和右手向量中。这里真的没有什么可做的。我们分配单元格矩阵和右侧贡献，就像我们在其他几乎所有的教程程序中使用约束对象那样。然后，我们还必须对面矩阵的贡献做同样的处理，这些贡献已经获得了面（内部和边界）的内容，并且`面_工作`和`边界_工作`已经添加到`copy_data.face_data`阵列中。\n\n    auto copier = [&](const CopyData &copy_data) { \n      constraints.distribute_local_to_global(copy_data.cell_matrix, \n                                             copy_data.cell_rhs, \n                                             copy_data.local_dof_indices, \n                                             system_matrix, \n                                             system_rhs); \n\n      for (auto &cdf : copy_data.face_data) \n        { \n          constraints.distribute_local_to_global(cdf.cell_matrix, \n                                                 cdf.joint_dof_indices, \n                                                 system_matrix); \n        } \n    }; \n\n// 在设置了所有这些之后，剩下的就是创建一个从头开始和复制数据的对象，并调用 MeshWorker::mesh_loop() 函数，然后遍历所有的单元格和面，调用它们各自的工作器，然后是复制器函数，将东西放入全局矩阵和右侧。作为一个额外的好处， MeshWorker::mesh_loop() 以并行方式完成所有这些工作，使用你的机器恰好有多少个处理器核心。\n\n    const unsigned int n_gauss_points = dof_handler.get_fe().degree + 1; \n    ScratchData<dim>   scratch_data(mapping, \n                                  fe, \n                                  n_gauss_points, \n                                  update_values | update_gradients | \n                                    update_hessians | update_quadrature_points | \n                                    update_JxW_values, \n                                  update_values | update_gradients | \n                                    update_hessians | update_quadrature_points | \n                                    update_JxW_values | update_normal_vectors); \n    CopyData           copy_data(dof_handler.get_fe().n_dofs_per_cell()); \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//  @sect4{Solving the linear system and postprocessing}  \n\n// 到此为止，节目基本上结束了。其余的函数并不太有趣或新颖。第一个函数只是用一个直接求解器来求解线性系统（也见 step-29  ）。\n\n  template <int dim> \n  void BiharmonicProblem<dim>::solve() \n  { \n    std::cout << \"   Solving system...\" << std::endl; \n\n    SparseDirectUMFPACK A_direct; \n    A_direct.initialize(system_matrix); \n    A_direct.vmult(solution, system_rhs); \n\n    constraints.distribute(solution); \n  } \n\n// 下一个函数评估了计算出的解和精确解之间的误差（在这里是已知的，因为我们选择了右手边和边界值的方式，所以我们知道相应的解）。在下面的前两个代码块中，我们计算了 $L_2$ 准则和 $H^1$ 半准则下的误差。\n\n  template <int dim> \n  void BiharmonicProblem<dim>::compute_errors() \n  { \n    { \n      Vector<float> norm_per_cell(triangulation.n_active_cells()); \n      VectorTools::integrate_difference(mapping, \n                                        dof_handler, \n                                        solution, \n                                        ExactSolution::Solution<dim>(), \n                                        norm_per_cell, \n                                        QGauss<dim>(fe.degree + 2), \n                                        VectorTools::L2_norm); \n      const double error_norm = \n        VectorTools::compute_global_error(triangulation, \n                                          norm_per_cell, \n                                          VectorTools::L2_norm); \n      std::cout << \"   Error in the L2 norm           :     \" << error_norm \n                << std::endl; \n    } \n\n    { \n      Vector<float> norm_per_cell(triangulation.n_active_cells()); \n      VectorTools::integrate_difference(mapping, \n                                        dof_handler, \n                                        solution, \n                                        ExactSolution::Solution<dim>(), \n                                        norm_per_cell, \n                                        QGauss<dim>(fe.degree + 2), \n                                        VectorTools::H1_seminorm); \n      const double error_norm = \n        VectorTools::compute_global_error(triangulation, \n                                          norm_per_cell, \n                                          VectorTools::H1_seminorm); \n      std::cout << \"   Error in the H1 seminorm       : \" << error_norm \n                << std::endl; \n    } \n\n// 现在也计算一下 $H^2$ 半正态误差的近似值。实际的 $H^2$ 半规范要求我们对解决方案 $u_h$ 的二阶导数进行积分，但是考虑到我们使用的拉格朗日形状函数， $u_h$ 当然在单元间的界面上有结点，因此二阶导数在界面是奇异的。因此，我们实际上只对单元的内部进行积分，而忽略了界面的贡献。这不是*等同于问题的能量准则，但是仍然可以让我们了解误差收敛的速度。\n\n// 我们注意到，我们可以通过定义一个等同于能量准则的准则来解决这个问题。这将涉及到不仅要像我们下面做的那样将细胞内部的积分相加，而且还要为 $u_h$ 的导数在界面上的跳跃添加惩罚项，并对这两种项进行适当的缩放。我们将把这个问题留给以后的工作。\n\n    { \n      const QGauss<dim>            quadrature_formula(fe.degree + 2); \n      ExactSolution::Solution<dim> exact_solution; \n      Vector<double> error_per_cell(triangulation.n_active_cells()); \n\n      FEValues<dim> fe_values(mapping, \n                              fe, \n                              quadrature_formula, \n                              update_values | update_hessians | \n                                update_quadrature_points | update_JxW_values); \n\n      FEValuesExtractors::Scalar scalar(0); \n      const unsigned int         n_q_points = quadrature_formula.size(); \n\n      std::vector<SymmetricTensor<2, dim>> exact_hessians(n_q_points); \n      std::vector<Tensor<2, dim>>          hessians(n_q_points); \n      for (auto &cell : dof_handler.active_cell_iterators()) \n        { \n          fe_values.reinit(cell); \n          fe_values[scalar].get_function_hessians(solution, hessians); \n          exact_solution.hessian_list(fe_values.get_quadrature_points(), \n                                      exact_hessians); \n\n          double local_error = 0; \n          for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n            { \n              local_error += \n                ((exact_hessians[q_point] - hessians[q_point]).norm_square() * \n                 fe_values.JxW(q_point)); \n            } \n          error_per_cell[cell->active_cell_index()] = std::sqrt(local_error); \n        } \n\n      const double error_norm = error_per_cell.l2_norm(); \n      std::cout << \"   Error in the broken H2 seminorm: \" << error_norm \n                << std::endl; \n    } \n  } \n\n// 同样无趣的是生成图形输出的函数。它看起来和  step-6  中的一模一样，比如说。\n\n  template <int dim> \n  void \n  BiharmonicProblem<dim>::output_results(const unsigned int iteration) const \n  { \n    std::cout << \"   Writing graphical output...\" << std::endl; \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    const std::string filename = \n      (\"output_\" + Utilities::int_to_string(iteration, 6) + \".vtu\"); \n    std::ofstream output_vtu(filename); \n    data_out.write_vtu(output_vtu); \n  } \n\n// `run()`函数的情况也是如此。就像在以前的程序中一样。\n\n  template <int dim> \n  void BiharmonicProblem<dim>::run() \n  { \n    make_grid(); \n\n    const unsigned int n_cycles = 4; \n    for (unsigned int cycle = 0; cycle < n_cycles; ++cycle) \n      { \n        std::cout << \"Cycle \" << cycle << \" of \" << n_cycles << std::endl; \n\n        triangulation.refine_global(1); \n        setup_system(); \n\n        assemble_system(); \n        solve(); \n\n        output_results(cycle); \n\n        compute_errors(); \n        std::cout << std::endl; \n      } \n  } \n} // namespace Step47 \n\n//  @sect3{The main() function}  \n\n// 最后是 \"main() \"函数。同样，这里没有什么可看的。它看起来和以前的教程程序中的一样。有一个变量，可以选择我们要用来解方程的元素的多项式程度。因为我们使用的C0IP公式要求元素的度数至少为2，所以我们用一个断言来检查，无论为多项式度数设置什么都是有意义的。\n\nint main() \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step47; \n\n      const unsigned int fe_degree = 2; \n      Assert(fe_degree >= 2, \n             ExcMessage(\"The C0IP formulation for the biharmonic problem \" \n                        \"only works if one uses elements of polynomial \" \n                        \"degree at least 2.\")); \n\n      BiharmonicProblem<2> biharmonic_problem(fe_degree); \n      biharmonic_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": "4072023016d4f45502612f156562a5edc1af5258", "size": 29614, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-47/step-47.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-47/step-47.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-47/step-47.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.2609819121, "max_line_length": 408, "alphanum_fraction": 0.5647328966, "num_tokens": 9801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577159, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.589187353004554}}
{"text": "// Copyright PinaPL\n//\n// weights.cpp\n// PinaPL\n//\n\n#include <Eigen/Dense>\n#include <random>\n#include \"weights.hpp\"\n\nWeights::Weights(int input_size, int output_size) {\n    this->input_size = input_size;\n    this->output_size = output_size;\n\n// We initialize random weights\n    this->weight_in_forget_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->input_size);\n\n    this->weight_in_input_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->input_size);\n\n    this->weight_in_input_block = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->input_size);\n\n    this->weight_in_output_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->input_size);\n\n    this->weight_st_forget_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->output_size);\n\n    this->weight_st_input_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->output_size);\n\n    this->weight_st_input_block = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->output_size);\n\n    this->weight_st_output_gate = 0.1 * Eigen::MatrixXd::Random(\n        this->output_size,\n        this->output_size);\n\n    this->bias_forget_gate = 0.1\n        * Eigen::MatrixXd::Random(this->output_size, 1);\n    this->bias_input_gate = 0.1\n        * Eigen::MatrixXd::Random(this->output_size, 1);\n    this->bias_input_block = 0.1\n        * Eigen::MatrixXd::Random(this->output_size, 1);\n    this->bias_output_gate = 0.1\n        * Eigen::MatrixXd::Random(this->output_size, 1);\n\n\n\n// We initialize a null gradient\n\n    this->delta_weight_in_forget_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_input_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_input_block = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_output_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_st_forget_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_input_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_input_block = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_output_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_bias_forget_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->delta_bias_input_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->delta_bias_input_block = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->delta_bias_output_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n}\n\nvoid Weights::apply_gradient(double lambda) {\n// We apply the weight variations\n    this->weight_in_forget_gate =\n        this->weight_in_forget_gate\n        - lambda * this->delta_weight_in_forget_gate;\n\n    this->weight_in_input_gate =\n        this->weight_in_input_gate\n        - lambda * this->delta_weight_in_input_gate;\n\n    this->weight_in_input_block =\n        this->weight_in_input_block\n        - lambda * this->delta_weight_in_input_block;\n\n    this->weight_in_output_gate =\n        this->weight_in_output_gate\n        - lambda * this->delta_weight_in_output_gate;\n\n    this->weight_st_forget_gate =\n        this->weight_st_forget_gate\n        - lambda * this->delta_weight_st_forget_gate;\n\n    this->weight_st_input_gate =\n        this->weight_st_input_gate\n        - lambda * this->delta_weight_st_input_gate;\n\n    this->weight_st_input_block =\n        this->weight_st_input_block\n        - lambda * this->delta_weight_st_input_block;\n\n    this->weight_st_output_gate =\n        this->weight_st_output_gate\n        - lambda * this->delta_weight_st_output_gate;\n\n    this->bias_forget_gate -= lambda * this->delta_bias_forget_gate;\n    this->bias_input_gate -= lambda * this->delta_bias_input_gate;\n    this->bias_input_block -= lambda * this->delta_bias_input_block;\n    this->bias_output_gate -= lambda * this->delta_bias_output_gate;\n\n\n// We set a null gradient\n    this->delta_weight_in_forget_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_input_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_input_block = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_in_output_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->input_size);\n\n    this->delta_weight_st_forget_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_input_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_input_block = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->delta_weight_st_output_gate = Eigen::MatrixXd::Zero(\n        this->output_size,\n        this->output_size);\n\n    this->bias_forget_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->bias_input_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->bias_input_block = Eigen::MatrixXd::Zero(this->output_size, 1);\n    this->bias_output_gate = Eigen::MatrixXd::Zero(this->output_size, 1);\n}\n", "meta": {"hexsha": "8f4f6f02ca7faf9472ed8f11f1c16a65604df209", "size": 5519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "weights.cpp", "max_stars_repo_name": "supelec-lstm/PinaPL_lstm", "max_stars_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "weights.cpp", "max_issues_repo_name": "supelec-lstm/PinaPL_lstm", "max_issues_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weights.cpp", "max_forks_repo_name": "supelec-lstm/PinaPL_lstm", "max_forks_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1807909605, "max_line_length": 79, "alphanum_fraction": 0.6716796521, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5891477846656606}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2011-2016 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// Calculating free energy density of square lattice Ising model\n\n// reference: B. Kastening, Phys. Rev. E 64, 066106 (2001), wrn:2011/02/10\n\n#ifndef ISING_SQUARE_FINITE_HPP\n#define ISING_SQUARE_FINITE_HPP\n\n#include <vector>\n#include <cmath>\n#include <boost/math/differentiation/autodiff.hpp>\n// #include <lse/exp_number.hpp>\n\n// namespace {\n  \n// inline lse::exp_double cosh_value(double x) {\n//   return (lse::exp_value(x) + lse::exp_value(-x)) / 2;\n// }\n\n// inline lse::exp_double sinh_value(double x) {\n//   return (lse::exp_value(x) - lse::exp_value(-x)) / 2;\n// }\n\n// }\n\nnamespace ising {\nnamespace square {\n\ntemplate <typename FVAR>\ninline double partition_function_impl(const FVAR& beta, double Jx, double Jy, int Lx, int Ly) {\n  auto a = beta * Jx;\n  auto b = beta * Jy;\n  std::vector<FVAR> gamma(2 * Lx);\n  for (int k = 0; k < 2 * Lx; ++k) {\n    auto cosh_g =\n      (cosh(2*a) * cosh(2*b) - cos(M_PI*k/Lx) * sinh(2*b)) / sinh(2*a);\n    gamma[k] = log(cosh_g + sqrt(cosh_g * cosh_g - 1));\n  }\n  if (sinh(2*a) * sinh(2*b) > 1) gamma[0] = -gamma[0];\n  FVAR p0(1), p1(1), p2(1), p3(1);\n  for (int k = 1; k <= Lx; ++k) {\n    p0 *= 2 * cosh(Ly * gamma[2*k-1] / 2);\n    p1 *= 2 * sinh(Ly * gamma[2*k-1] / 2);\n    p2 *= 2 * cosh(Ly * gamma[2*k-2] / 2);\n    p3 *= 2 * sinh(Ly * gamma[2*k-2] / 2);\n  }\n  auto z = 0.5 * pow(2 * sinh(2*a), Lx*Ly/2) * (p0 + p1 + p2 - p3);\n  auto f = -log(z) / beta / (Lx * Ly);\n  // auto e = \n  std::cout << f.derivative(0) << ' ' << f.derivative(1) << ' ' << f.derivative(2) << std::endl;\n  return z.derivative(0);\n}\n\ninline double partition_function(double beta_in, double Jx, double Jy, int Lx, int Ly) {\n  using namespace boost::math::differentiation;\n  constexpr unsigned Order = 2;\n  auto const beta = make_fvar<double, Order>(beta_in);\n  return partition_function_impl(beta, Jx, Jy, Lx, Ly);\n  \n}\n  \ninline double free_energy(double beta, double Jx, double Jy, int Lx, int Ly) {\n  return -log(partition_function(beta, Jx, Jy, Lx, Ly)) / beta;\n}\n\ninline double free_energy_density(double beta, double Jx, double Jy, int Lx, int Ly) {\n  return free_energy(beta, Jx, Jy, Lx, Ly) / (Lx * Ly);\n}\n\n} // end namespace square\n} // end namespace ising\n\n#endif // ISING_SQUARE_FINITE_HPP\n", "meta": {"hexsha": "fdf321c244c68a6abfe13c49471b5655a1de0c99", "size": 2604, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/square/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": "ising/square/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": "ising/square/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": 31.756097561, "max_line_length": 96, "alphanum_fraction": 0.5937019969, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5891477846656605}}
{"text": "#include <cctbx/boost_python/flex_fwd.h>\n\n#include <boost/python.hpp>\n#include <rstbx/indexing_api/indexing_api.h>\n\n\nusing namespace boost::python;\nusing namespace rstbx::indexing_api;\n\nnamespace indexing_api{\n\nstruct rayleigh_cpp { // a fast C++ version of the Rayleigh distribution class\n  /*\n  =============================================================================\n  Class models a 1-d Rayleigh distribution using one parameter, sigma.\n\n              x                x^2\n    pdf = --------- exp(- ------------)\n           sigma^2         2 sigma^2\n\n                        x^2\n    cdf = 1 - exp(- -----------)\n                     2 sigma^2\n\n  The derivative of the cdf with respect to sigma is,\n\n      d(cdf)          x^2               x^2             x\n    ---------- = - --------- exp( - -----------) = - ------- pdf\n     d(sigma)       sigma^3          2 sigma^2        sigma\n\n  Methods:\n    set_parameters\n    get_parameters\n    estimate_parameters_from_cdf\n    pdf\n    cdf\n    d_cdf_d_sigma\n    d_cdf_d_sigma_finite\n    cdf_gradients\n  -----------------------------------------------------------------------------\n  */\n  rayleigh_cpp(): sigma(1.),interface(\"C++\"){}\n  rayleigh_cpp(const double& s): sigma(s){}\n\n  void set_parameters(scitbx::af::shared<double> p) {\n    SCITBX_ASSERT(p.size() == 1);\n    sigma = p[0];\n  }\n\n  scitbx::af::shared<double> get_parameters(){\n    return scitbx::af::shared<double>(1,sigma);\n  }\n\n  void estimate_parameters_from_cdf(scitbx::af::shared<double> x_data,scitbx::af::shared<double>y_data){\n    //Function estimates the parameter values based on the data (cdf)\n    // sigma is the mode of the distribution\n    // approximate with the median (cdf = 0.5)\n    int midpoint = 0;\n    for (int i=0; i < x_data.size(); ++i){\n      if (y_data[i] > 0.5){\n        midpoint = i;\n        break;\n      }\n    }\n    if (midpoint == 0){\n      midpoint = x_data.size() - 1;\n    }\n    sigma = x_data[midpoint];\n  }\n\n  double pdf(const double& x){\n    //Function returns the probability density function at x\n      double x_sigma = x/sigma;\n      return (x_sigma/sigma)*std::exp(-0.5*x_sigma*x_sigma);\n  }\n\n  scitbx::af::shared<double> pdf(scitbx::af::shared<double> x){\n    //Function returns the probability density function at x\n    scitbx::af::shared<double> f;\n    for (int i = 0; i < x.size(); ++i){\n      double x_sigma = x[i]/sigma;\n      f.push_back( (x_sigma/sigma)*std::exp(-0.5*x_sigma*x_sigma) );\n    }\n    return f;\n  }\n\n  double cdf(const double& x){\n    //Function returns the cumulative distribution function at x\n      double x_sigma = x/sigma;\n      return 1.0 - std::exp(-0.5*x_sigma*x_sigma);\n  }\n\n  scitbx::af::shared<double> cdf(scitbx::af::shared<double> x){\n    //Function returns the cumulative distribution function at x\n    scitbx::af::shared<double> f;\n    for (int i = 0; i < x.size(); ++i){\n      double x_sigma = x[i]/sigma;\n      f.push_back( 1.0 - std::exp(-0.5*x_sigma*x_sigma) );\n    }\n    return f;\n  }\n\n  double d_cdf_d_sigma(const double& x){\n    //Function returns the derivative of the cdf at x with respect to the standard deviation\n    double p = pdf(x);\n    return -(x/sigma)*p ;\n  }\n\n  scitbx::af::shared<double> d_cdf_d_sigma(scitbx::af::shared<double> x){\n    //Function returns the derivative of the cdf at x with respect to the standard deviation\n    scitbx::af::shared<double> p = pdf(x);\n    scitbx::af::shared<double> df;\n    for (int i = 0; i < x.size(); ++i){\n      df.push_back ( -(x[i]/sigma)*p[i] );\n    }\n    return df;\n  }\n\n  scitbx::af::shared<double> cdf_gradients(const double& x){\n    //Function returns a flex.double containing all derivatives\n    scitbx::af::shared<double> result;\n    result.push_back( d_cdf_d_sigma(x) );\n    return result;\n  }\n  scitbx::af::shared<double> gradients(\n    scitbx::af::shared<double> x, const int& nparams, scitbx::af::shared<double>difference){\n    //Convenience function to return the gradients in the context of fit_distribution.py\n    scitbx::af::shared<double> gradients = scitbx::af::shared<double>(nparams);\n    for (int i = 0; i < x.size(); ++i){\n      scitbx::af::shared<double> g_i = cdf_gradients(x[i]);\n      for (int j = 0; j < nparams; ++j){\n        gradients[j] = gradients[j] + difference[i]*g_i[j];\n      }\n    }\n    for (int i = 0; i < gradients.size(); ++i){\n      gradients[i] = 2.0*gradients[i];\n    }\n    return gradients;\n  }\n  double sigma;\n  std::string interface;\n};\n\nstruct find_green_bar {\n  find_green_bar(const scitbx::af::shared<double> rayleigh_cdf_x,\n                 const scitbx::af::shared<double> rayleigh_cdf,\n                 const scitbx::af::shared<double> dr,\n                 const scitbx::af::shared<double> x,\n                 const double& sd ):\n                 is_set(false){\n    const double* ptr_rayleigh_cdf_x = rayleigh_cdf_x.begin();\n    const double* ptr_rayleigh_cdf = rayleigh_cdf.begin();\n    const double* ptr_x = x.begin();\n    const double* ptr_dr = dr.begin();\n\n    for (std::size_t i=0; i < rayleigh_cdf_x.size(); ++i){\n      double mx = ptr_rayleigh_cdf_x[i];\n      double my = ptr_rayleigh_cdf[i];\n      for (std::size_t j=1; j < dr.size(); ++j){\n        double upper_x = ptr_dr[j];\n        double upper_y = ptr_x[j];\n        double lower_x = ptr_dr[j-1];\n        double lower_y = ptr_x[j-1];\n        if ((my >= lower_y) && (my < upper_y)){\n          if ((sd <= (upper_x - mx)) && ((lower_x - mx) > 0.0)){\n            //sd_data = ((mx,my),(lower_x,lower_y))\n            sd_mx = mx;\n            sd_my = my;\n            sd_lower_x = lower_x;\n            sd_lower_y = lower_y;\n            is_set = true;\n            radius_outlier_index = j-1;\n            limit_outlier = lower_x;\n            break;\n          }\n        }\n        if (is_set){\n          break;\n        }\n      }\n    }\n  }\n\n  bool is_set;\n  double sd_mx,sd_my,limit_outlier,sd_lower_x,sd_lower_y;\n  int radius_outlier_index;\n\n};\n\n}\n\nBOOST_PYTHON_MODULE(rstbx_indexing_api_ext)\n{\n\n   def(\"cpp_absence_test\",cpp_absence_test);\n\n   class_<dps_extended, bases<rstbx::dps_core> >(\"dps_extended\",init< >())\n     .def(\"getData\",&dps_extended::getData)\n     .def(\"setData\",&dps_extended::setData)\n     .def(\"refine_direction\",&dps_extended::refine_direction,\n          (arg(\"candidate\"),arg(\"current_grid\"),\n           arg(\"target_grid\")))\n   ;\n\n   def(\"raw_spot_positions_mm_to_reciprocal_space_xyz\",\n     ( scitbx::af::shared< scitbx::vec3<double> > (*) (\n       rstbx::pointlist,dxtbx::model::Detector const&, double const&,\n       scitbx::vec3<double> const& , scitbx::vec3<double> const&, scitbx::af::shared<int>) )\n     raw_spot_positions_mm_to_reciprocal_space_xyz);\n   def(\"raw_spot_positions_mm_to_reciprocal_space_xyz\",\n     ( scitbx::af::shared< scitbx::vec3<double> > (*) (\n       rstbx::pointlist,dxtbx::model::Detector const&, double const&,\n       scitbx::vec3<double> const& , scitbx::af::shared<int>) )\n     raw_spot_positions_mm_to_reciprocal_space_xyz);\n\n  typedef return_value_policy<return_by_value> rbv;\n  class_<indexing_api::find_green_bar>(\"find_green_bar\",\n    init<const scitbx::af::shared<double>, const scitbx::af::shared<double>,\n              const scitbx::af::shared<double>, const scitbx::af::shared<double>,\n              const double& > ((\n              arg(\"rayleigh_cdf_x\"),arg(\"rayleigh_cdf\"),arg(\"dr\"),arg(\"x\"),arg(\"sd\"))))\n    .add_property(\"is_set\",make_getter(&indexing_api::find_green_bar::is_set, rbv()))\n    .add_property(\"sd_mx\",make_getter(&indexing_api::find_green_bar::sd_mx, rbv()))\n    .add_property(\"sd_my\",make_getter(&indexing_api::find_green_bar::sd_my, rbv()))\n    .add_property(\"limit_outlier\",make_getter(&indexing_api::find_green_bar::limit_outlier, rbv()))\n    .add_property(\"sd_lower_x\",make_getter(&indexing_api::find_green_bar::sd_lower_x, rbv()))\n    .add_property(\"sd_lower_y\",make_getter(&indexing_api::find_green_bar::sd_lower_y, rbv()))\n    .add_property(\"radius_outlier_index\",make_getter(&indexing_api::find_green_bar::radius_outlier_index, rbv()))\n  ;\n   class_<indexing_api::rayleigh_cpp >(\"rayleigh_cpp\",init< >())\n     .def(\"set_parameters\",&indexing_api::rayleigh_cpp::set_parameters, (arg(\"p\")))\n     .def(\"get_parameters\",&indexing_api::rayleigh_cpp::get_parameters)\n     .def(\"estimate_parameters_from_cdf\",&indexing_api::rayleigh_cpp::estimate_parameters_from_cdf,\n         (arg(\"x_data\"),arg(\"y_data\")))\n     .def(\"pdf\",(double (indexing_api::rayleigh_cpp::*)(const double&))&indexing_api::rayleigh_cpp::pdf, (arg(\"x\")))\n     .def(\"pdf\",(scitbx::af::shared<double> (indexing_api::rayleigh_cpp::*)(scitbx::af::shared<double>))&indexing_api::rayleigh_cpp::pdf, (arg(\"x\")))\n     .def(\"cdf\",(double (indexing_api::rayleigh_cpp::*)(const double&))(&indexing_api::rayleigh_cpp::cdf), (arg(\"x\")))\n     .def(\"cdf\",(scitbx::af::shared<double> (indexing_api::rayleigh_cpp::*)(scitbx::af::shared<double>))(&indexing_api::rayleigh_cpp::cdf), (arg(\"x\")))\n     .def(\"d_cdf_d_sigma\",(double (indexing_api::rayleigh_cpp::*)(const double&))&indexing_api::rayleigh_cpp::d_cdf_d_sigma)\n     .def(\"d_cdf_d_sigma\",(scitbx::af::shared<double> (indexing_api::rayleigh_cpp::*)(scitbx::af::shared<double>))&indexing_api::rayleigh_cpp::d_cdf_d_sigma)\n     .def(\"cdf_gradients\",(scitbx::af::shared<double> (indexing_api::rayleigh_cpp::*)(const double&))&indexing_api::rayleigh_cpp::cdf_gradients, (arg(\"x\")))\n     .add_property(\"interface\",make_getter(&indexing_api::rayleigh_cpp::interface, rbv()))\n     .def(\"gradients\",&indexing_api::rayleigh_cpp::gradients, (arg(\"x\"),arg(\"nparams\"),arg(\"difference\")))\n   ;\n}\n", "meta": {"hexsha": "a1755e08c6d32f99eb7d57a0d838c6bbe4af9025", "size": 9518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rstbx/indexing_api/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": "rstbx/indexing_api/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": "rstbx/indexing_api/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": 38.6910569106, "max_line_length": 157, "alphanum_fraction": 0.6196679975, "num_tokens": 2698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5891450474947088}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char *argv[])\n{\n\tofstream writing_file;\n\tconst float pi = boost::math::constants::pi<float>();\n\t\n\t/* 遊脚の時間 */\n\tconst float period = 0.30;\n\t/* 目標足上げ高さ */\n\tconst float h = 0.060;\n\t/* サンプリングタイム */\n\tconst float dt = 0.01; \n\t\n\t/* 足先軌道 */\n\tMatrix<float,2,1> p(Matrix<float,2,1>::Zero());\n\t/* 目標足先接地位置 */\n\tMatrix<float,2,1> p_goal(Matrix<float,2,1>::Zero());\n\t/* 初期足先位置 */\n\tMatrix<float,2,1> p_start(Matrix<float,2,1>::Zero());\n\n\t/* 3次補間のための係数 */\n\tMatrix<float,2,4> A(Matrix<float,2,4>::Zero());\n\n\t/* 目標足先接地地点 */\n\tp_goal << atof(argv[1]), atof(argv[2]); \n\t/* 初期の足先位置 */\n\tp_start << atof(argv[3]), atof(argv[4]);\n\n\tA << p_start(0), 0, 3*(p_goal(0)-p_start(0))/pow(period,2), -2*(p_goal(0)-p_start(0))/pow(period,3),\n\t\t p_start(1), 0, 3*(p_goal(1)-p_start(1))/pow(period,2), -2*(p_goal(1)-p_start(1))/pow(period,3),\n\t\n\twriting_file.open(\"swing_foot_trajectory.csv\");\n\tfor(float t=0.0f; t<=period;t+=dt){\n\t\t/* z方向の遊脚軌道生成(サイクロイド曲線) */\n\t\tfloat z_swing = h*0.5*(1-cos(2*pi/static_cast<int>(period/dt)*(t/dt)));\n\n\t\t/* 時刻tのx, y方向の遊脚軌道生成 */\n\t\tp = A * Vector4f(1, t, t*t, t*t*t);\n\t\t\n\t\t/* ファイル書き込み */\t\t\n\t\twriting_file << t << \" \" << p(0) << \" \" << p(1) << \" \"<<z_swing << endl;\n\t}\n\twriting_file.close();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a0080d857f5eb33da51a6d9dbe0186b5f1ef9968", "size": 1390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/swing_trajectory/test_swing_leg.cpp", "max_stars_repo_name": "takayan660/HumanoidRobotLibrary", "max_stars_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/swing_trajectory/test_swing_leg.cpp", "max_issues_repo_name": "takayan660/HumanoidRobotLibrary", "max_issues_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/swing_trajectory/test_swing_leg.cpp", "max_forks_repo_name": "takayan660/HumanoidRobotLibrary", "max_forks_repo_head_hexsha": "302c95f8660056b42d1bed836253f2169d71769f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8214285714, "max_line_length": 101, "alphanum_fraction": 0.6100719424, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5888722297783044}}
{"text": "/**\n *  @file    SparseSolver.hpp\n *  @brief   Solves a finite difference problem.\n *  @author  Francois Roy\n *  @date    12/01/2019\n */\n#ifndef SPARSESOLVER_H\n#define SPARSESOLVER_H\n\n#include <vector>\n#include <Eigen/SparseCore>\n#include \"spdlog/spdlog.h\"\n#include \"Problem.hpp\"\n\nnamespace numerical {\n\nnamespace fdm {\n\n/*\n * This class is used to solve the diffusion problem in 1D with uniform and\n * constant diffusion coefficient \\f$\\alpha\\f$ and constant Dirichlet boundary \n * conditions.\n */\ntemplate <typename T>\nclass SparseSolver {\ntypedef Eigen::SparseMatrix<T> SpMat;\ntypedef Eigen::Triplet<T> Trip;\ntypedef Eigen::VectorXd Vec;\nprivate:\n  SpMat m_A;\n  Vec m_b;\n  Vec m_u;\n  Problem<T>* m_problem;\npublic:\n  SparseSolver(Problem<T>* problem)\n    : m_problem(problem)\n     {\n      // define variables\n      T dx, dt;\n  }\n  ~SparseSolver(){\n      // delete m_A;\n      // delete m_b;\n  }\n\n  /**\n  * Assembles sparse coefficient matrix A.\n  *\n  * \\f[\n  *    A_{i,i-1}=-F\\Theta,~A{i, i}=1+2F\\Theta,~A_{i, i+1}=-F\\Theta\n  * \\f].\n  *\n  */\n  void assemble_a(){\n    /*\n    // The loops are vectorized for efficiency -- see bench/performances\n    SpMat A(nx + 1, nx + 1);\n    std::vector<Trip> trp;\n    // diagonal terms\n    // Eigen::VectorXd val = Eigen::VectorXd::Zero(nx + 1);  // initialized to zero\n    Vec diagonal = Eigen::VectorXd::Constant(nx + 1, 1.0);\n    diagonal[0] = 0.0;\n    diagonal[nx] = 0.0;\n    // segment(pos, n) the n coeffs in the range [pos : pos + n - 1]\n    diagonal.segment(1, diagonal.size()-2) += Dl * m_a.segment(2, m_a.size()-2);\n    diagonal.segment(1, diagonal.size()-2) += Dl * 2.0 * m_a.segment(1, m_a.size()-2);\n    diagonal.segment(1, diagonal.size()-2) += Dl * m_a.segment(0, m_a.size()-2);\n    // lower terms\n    Vec lower = Eigen::VectorXd::Zero(nx);\n    lower.segment(0, lower.size()-1) += -Dl * m_a.segment(1, m_a.size()-2);\n    lower.segment(0, lower.size()-1) += -Dl * m_a.segment(0, m_a.size()-2);\n    // upper terms\n    Vec upper = Eigen::VectorXd::Zero(nx);\n    upper.segment(1, upper.size()-1) += -Dl * m_a.segment(2, m_a.size()-2);\n    upper.segment(1, upper.size()-1) += -Dl * m_a.segment(1, m_a.size()-2);\n\n    // boundary conditions\n    diagonal[0] = 1.0;\n    upper[0] = 0.0;\n    diagonal[nx] = 1.0;\n    lower[nx-1] = 0.0;\n    \n    // std::cout << diagonal << \"\\n\";\n    for(int i=1; i<m_x.size() - 1; i++){\n        trp.push_back(Trip(i,i,diagonal[i]));    \n    }\n    // std::cout << lower << \"\\n\";\n    for(int i=1; i<m_x.size() - 1; i++){\n         trp.push_back(Trip(i,i-1,lower[i-1]));    \n    }\n    // std::cout << upper << \"\\n\";\n    for(int i=1; i<m_x.size() - 1; i++){\n        trp.push_back(Trip(i,i+1,upper[i]));    \n    }\n    // create sparse matrix\n    A.setFromTriplets(trp.begin(), trp.end());\n    m_A = A;\n    */\n  }\n\n  /**\n  * Assembles RHS vector b.\n  *\n  * \\f[\n  *    b_i = u_i^n + F\\left(1-\\Theta\\right)u_{i+1}^n-2u_i^n+u_{i-1}^n +\n  *        \\Delta t \\Theta f_i^{n+1} + \\Delta t \\left(1-\\Theta\\right)f_i^n\n  * \\f]\n  *\n  * using vectorization we get:\n  *\n  * \\f[\n  *    b[1:n_x-1] = u_n[1:n_x-1] + \\left(1-\\Theta\\right)F\n  *        \\left(u_n[2:n_x]-2u_n[1:n_x-1]+u_n[0:n_x-2]\\right) + \n  *        \\Theta\\Delta t f[1:n_x-1](n+1) + \n  *        \\left(1-\\Theta\\right)\\Delta t f[1:n_x-1](n)\n  * \\f]\n  *\n  */\n  void assemble_b(T t){\n\n  }\n\n  /*\n  * Solve the time dependent problem.\n  */\n  virtual Eigen::VectorXf solve(){\n      //  Set initial condition\n      //for(int i=0; i<u_n.size(); i++){\n          // u_n[i] = m_params.init(m_x[i], 0., 0.);    \n      //}\n      // std::cout << u_n << \"\\n\";\n\n      spdlog::info(\"{}\", m_problem->left(0, 1.0, 1.0, 1.0));\n      // Time loop\n\n      Eigen::VectorXf solution = Eigen::VectorXf::Unit(4,1);\n      return solution;\n  }\n\n};\n\n/*\n * For a sparse matrix, return a vector of triplets, such that we can\n * reconstruct the matrix using setFromTriplet function.\n * @param matrix A sparse matrix.\n * @return A triplet with the row, column and value of the non-zero entries.\n */\ntemplate <typename Derived>\nstd::vector<Eigen::Triplet<typename Derived::Scalar>> SparseMatrixToTriplets(\n    const Derived& matrix) {\n  using Scalar = typename Derived::Scalar;\n  std::vector<Eigen::Triplet<Scalar>> triplets;\n  triplets.reserve(matrix.nonZeros());\n  for (int i = 0; i < matrix.outerSize(); i++) {\n    for (typename Derived::InnerIterator it(matrix, i); it; ++it) {\n      triplets.push_back(\n          Eigen::Triplet<Scalar>(it.row(), it.col(), it.value()));\n    }\n  }\n  return triplets;\n}\n\n}  // namespace fdm\n\n}  // namespace numerical\n\n#endif  // SPARSESOLVER_H\n", "meta": {"hexsha": "806ce20221d844bc386334fd227d5f1abe8ddbbd", "size": 4560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fdm/SparseSolver.hpp", "max_stars_repo_name": "dbeat/numerical", "max_stars_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/fdm/SparseSolver.hpp", "max_issues_repo_name": "dbeat/numerical", "max_issues_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/fdm/SparseSolver.hpp", "max_forks_repo_name": "dbeat/numerical", "max_forks_repo_head_hexsha": "bce26eb7d537eb8e32105f2887ea11940ce4fc96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1428571429, "max_line_length": 86, "alphanum_fraction": 0.5826754386, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.5888107306458987}}
{"text": "\n/*\n * CubicPolynomialTrajectory.h\n *\n *  Created on: June 21, 2020\n *      Author: Quincy Jones\n *\n * Copyright (c) <2020> <Quincy Jones - quincy@implementedrobotics.com/>\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 Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\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 LIABILITY,\n * WHETHER 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 NOMAD_CUBICPOLYNOMIALTRAJECTORY_H_\n#define NOMAD_CUBICPOLYNOMIALTRAJECTORY_H_\n\n// C System Files\n\n// C++ System Files\n\n// Third Party Includes\n#include <Eigen/Dense>\n\n// Project Include Files\nnamespace Common\n{\n    class CubicPolynomialTrajectory\n    {\n\n    public:\n        CubicPolynomialTrajectory(double q_f, double t_f);\n        CubicPolynomialTrajectory(double q_0, double q_f, double v_0, double v_f, double t_0, double t_f);\n        CubicPolynomialTrajectory(); // Empty Trajectory\n\n        void Generate(double q_f, double t_f);\n        void Generate(double q_0, double q_f, double v_0, double v_f, double t_0, double t_f);\n\n        // TODO: Check for valid t between 0<->t_f\n        double Position(double t);\n        double Velocity(double t);\n        double Acceleration(double t);\n\n    protected:\n        void ComputeCoeffs();\n\n        Eigen::Vector4d a_; // Coefficients\n\n        double q_0_;\n        double v_0_;\n        double t_0_;\n\n        double q_f_;\n        double v_f_;\n        double t_f_;\n    };\n} // namespace Common\n\n#endif // NOMAD_CUBICPOLYNOMIALTRAJECTORY_H_", "meta": {"hexsha": "6c319a1df66071d6d884067106329dee5e25667e", "size": 2335, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Software/Common/include/Common/Math/CubicPolynomialTrajectory.hpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Common/include/Common/Math/CubicPolynomialTrajectory.hpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Common/include/Common/Math/CubicPolynomialTrajectory.hpp", "max_forks_repo_name": "implementedrobotics/Nomad", "max_forks_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T03:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:34:16.000Z", "avg_line_length": 33.8405797101, "max_line_length": 106, "alphanum_fraction": 0.7156316916, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.588740692556227}}
{"text": "/**\n * @file solver.cpp\n * @brief API for ADMM-based formation gain solver\n * @author Parker Lusk <parkerclusk@gmail.com>\n * @date 25 July 2020\n */\n\n#include <iostream>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <Eigen/SparseCholesky>\n\n#include \"admm/solver.h\"\n\nnamespace acl {\nnamespace aclswarm {\nnamespace admm {\n\nSolver::Solver(const Params& params)\n: params_(params)\n{\n\n}\n\n// ----------------------------------------------------------------------------\n\nEigen::MatrixXd Solver::solve(\n                        const Eigen::Matrix<double, 3, Eigen::Dynamic>& pts,\n                        const Eigen::MatrixXd& adj)\n{\n\n  //\n  // Solve 2D gain design subproblem\n  //\n\n  const auto A2d = solve2d(pts.topRows(2), adj);\n\n  //\n  // Solve 1D gain design subproblem\n  //\n\n  const auto A1d = solve1d(pts.bottomRows(1), adj);\n\n  //\n  // Combine for 3D gain design problem\n  //\n\n  const size_t n = pts.cols();\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3*n,3*n);\n  for (size_t i=0; i<A.rows(); ++i) {\n    for (size_t j=0; j<A.cols(); ++j) {\n\n      // which 3x3 A_ij sub-block are we in?\n      const size_t blki = i / 3;\n      const size_t blkj = j / 3;\n\n      // map index into 2d sub-block\n      const size_t i2d = i - blki;\n      const size_t j2d = j - blkj;\n\n      // map index into 1d sub-block\n      const size_t i1d = blki;\n      const size_t j1d = blkj;\n\n      // determine if we are indexing the 3rd row/col in A_ij\n      bool row3 = ((i+1) % 3) == 0;\n      bool col3 = ((j+1) % 3) == 0;\n\n      if (!row3 && !col3) {\n        A(i,j) = A2d(i2d,j2d);\n      } else if (row3 && col3) {\n        A(i,j) = A1d(i1d,j1d);\n      }\n    }\n  }\n\n  return A;\n}\n\n// ----------------------------------------------------------------------------\n// Private Methods\n// ----------------------------------------------------------------------------\n\nEigen::MatrixXd Solver::solve1d(\n                        const Eigen::Matrix<double, 1, Eigen::Dynamic>& pts,\n                        const Eigen::MatrixXd& adj)\n{\n\n  //\n  // Build orthogonal complement of gain matrix kernel\n  //\n\n  const size_t n = adj.rows();\n  const size_t d = 1; // ambient dimension of the problem\n\n  // xy stacked\n  Eigen::Map<const Eigen::VectorXd> qz(pts.data(), pts.size());\n\n  // one vector\n  Eigen::VectorXd ez = Eigen::VectorXd::Ones(n);\n\n  // determine if desired formation is actually 2D (flat planar)\n  const double stdev = std::sqrt((qz.array() - qz.mean()).array().square().sum()/(n-1));\n  bool xyflat = (stdev < params_.thrPlanar);\n\n  // kernel of gain matrix\n  size_t dimKer;\n  Eigen::MatrixXd N;\n  if (xyflat) {\n    dimKer = 1;\n    N = Eigen::MatrixXd(pts.size(), dimKer);\n    N << qz;\n  } else {\n    dimKer = 2;\n    N = Eigen::MatrixXd(pts.size(), dimKer);\n    N << qz, ez;\n  }\n  const size_t m = n - dimKer; // reduced number due to orth. compl. restriction\n\n  // find the orthogonal complement of the kernel\n  // recall: N = [U1 U2][S 0; 0 0][V1h; V2h]. We want U2.\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(N, Eigen::ComputeFullU);\n  Eigen::MatrixXd Q = svd.matrixU().rightCols(svd.matrixU().cols() - dimKer);\n\n  //\n  // Build the gain design optimization problem\n  //\n\n  SpMat C, A, b, X;\n  parse(d, m, n, adj, Q, C, A, b, X);\n\n  //\n  // Solve SDP using ADMM on sparse matrices\n  //\n\n  admm(C, A, b, X);\n\n  //\n  // Recover gain matrix\n  //\n\n  Eigen::MatrixXd Aopt = - Q * X.bottomRightCorner(d*m, d*m) * Q.transpose();\n  Aopt = (params_.thrSparseZero < Aopt.array().abs()).select(Aopt, 0.0);\n\n  return Aopt;\n}\n\n// ----------------------------------------------------------------------------\n\nEigen::MatrixXd Solver::solve2d(\n                        const Eigen::Matrix<double, 2, Eigen::Dynamic>& pts,\n                        const Eigen::MatrixXd& adj)\n{\n\n  //\n  // Build orthogonal complement of gain matrix kernel\n  //\n\n  const size_t n = adj.rows();\n  const size_t m = n - 2; // reduced number due to orth. compl. restriction\n  const size_t d = 2; // ambient dimension of the problem\n\n  // xy stacked\n  Eigen::Map<const Eigen::VectorXd> q(pts.data(), pts.size());\n\n  // 90-degree rotated (-yx stacked)\n  Eigen::VectorXd qbar = Eigen::VectorXd::Zero(pts.size());\n  Eigen::Map<const Eigen::VectorXd, 0, Eigen::InnerStride<2>> qx(q.data(), q.size()/2);\n  Eigen::Map<const Eigen::VectorXd, 0, Eigen::InnerStride<2>> qy(q.data()+1, q.size()/2);\n  Eigen::Map<Eigen::VectorXd, 0, Eigen::InnerStride<2>> qbarx(qbar.data(), qbar.size()/2);\n  Eigen::Map<Eigen::VectorXd, 0, Eigen::InnerStride<2>> qbary(qbar.data()+1, qbar.size()/2);\n  qbarx = -qy;\n  qbary =  qx;\n\n  // one vectors\n  Eigen::VectorXd ex = Eigen::Vector2d::UnitX().replicate(n, 1);\n  Eigen::VectorXd ey = Eigen::Vector2d::UnitY().replicate(n, 1);\n\n  // kernel of gain matrix\n  static constexpr size_t dimKer = 4;\n  Eigen::Matrix<double, Eigen::Dynamic, dimKer> N = Eigen::MatrixXd(pts.size(), dimKer);\n  N << q, qbar, ex, ey;\n\n  // find the orthogonal complement of the kernel\n  // recall: N = [U1 U2][S 0; 0 0][V1h; V2h]. We want U2.\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(N, Eigen::ComputeFullU);\n  Eigen::MatrixXd Q = svd.matrixU().rightCols(svd.matrixU().cols() - dimKer);\n\n  //\n  // Build the gain design optimization problem\n  //\n\n  SpMat C, A, b, X;\n  parse(d, m, n, adj, Q, C, A, b, X);\n\n  //\n  // Solve SDP using ADMM on sparse matrices\n  //\n\n  admm(C, A, b, X);\n\n  //\n  // Recover gain matrix\n  //\n\n  Eigen::MatrixXd Aopt = - Q * X.bottomRightCorner(d*m, d*m) * Q.transpose();\n  Aopt = (params_.thrSparseZero < Aopt.array().abs()).select(Aopt, 0.0);\n\n  return Aopt;\n}\n\n// ----------------------------------------------------------------------------\n\ninline size_t Solver::vecsel(size_t rows, size_t cols, size_t i, size_t j)\n{\n  return j*rows + i;\n}\n\n// ----------------------------------------------------------------------------\n\ninline size_t Solver::blksel(size_t dim, size_t blkidx, size_t subidx)\n{\n  return dim*blkidx + subidx;\n}\n\n// ----------------------------------------------------------------------------\n\ninline void Solver::vectorize(const SpMat& X, SpMat& x)\n{\n  x.resize(X.size(), 1);\n  x.reserve(X.nonZeros());\n  x.startVec(0);\n  for (size_t j=0; j<X.cols(); ++j) {\n    for (SpMat::InnerIterator it(X, j); it; ++it) {\n      x.insertBack(j*X.rows() + it.row(), 0) = it.value();\n    }\n  }\n}\n\n// ----------------------------------------------------------------------------\n\ninline void Solver::unvectorize(const SpMat& x, SpMat& X)\n{\n  X.reserve(x.nonZeros());\n  int curj = -1;\n\n  for (SpMat::InnerIterator it(x, 0); it; ++it) {\n\n    // select the correct destination row/col.\n    const size_t i = it.row() % X.rows();\n    const size_t j = it.row() / X.cols();\n    if (j != curj) {\n      X.startVec(j);\n      curj = j;\n    }\n\n    X.insertBack(i, j) = it.value();\n  }\n}\n\n// ----------------------------------------------------------------------------\n\nvoid Solver::admm(const SpMat& C, const SpMat& A, const SpMat& b, SpMat& X)\n{\n\n  // cached operations\n  const SpMat As = A.adjoint(); // dual operator\n  Eigen::SimplicialCholesky<SpMat> AAs((A * As).pruned());\n\n  // initialize intermediate variables\n  SpMat Xold;\n  SpMat S(X.rows(), X.cols());\n  SpMat y(b.rows(), 1);\n\n  //\n  // ADMM Iterations\n  //\n\n  for (size_t i=0; i<params_.maxItr; ++i) {\n\n    // update y\n    {\n      const SpMat D = C - S - params_.mu * X;\n      SpMat Dvec; vectorize(D, Dvec);\n      const SpMat e = A * Dvec + params_.mu * b;\n      y = AAs.solve(e); // AAs \\ e\n    }\n\n    // update S\n    SpMat W;\n    {\n      const SpMat d = (As * y).pruned(1, params_.thrSparseZero);\n      SpMat dmat(X.rows(), X.cols()); unvectorize(d, dmat);\n      const SpMat WW = C - dmat - params_.mu * X;\n      W = (WW + SpMat(WW.transpose())) / 2.0;\n    }\n\n    // determine index where positive evals start\n    Eigen::SelfAdjointEigenSolver<SpMat> es(W);\n    size_t k = 0;\n    for (size_t i=0; i<W.rows(); ++i) {\n      if (es.eigenvalues()(i) > params_.epsEig) {\n        k = i;\n        break;\n      }\n    }\n    const size_t idxPosStart = W.rows() - k;\n\n    // remove non-positive modes\n    const Eigen::MatrixXd V = es.eigenvectors().rightCols(idxPosStart);\n    const Eigen::MatrixXd D = es.eigenvalues().tail(idxPosStart).asDiagonal();\n    S = (V * D * V.transpose()).sparseView(1, params_.thrSparseZero);\n\n    // update X\n    Xold = X;\n    X = (S - W) / params_.mu;\n\n    // check stop criteria --- difference in X\n    const double diffX = (X - Xold).cwiseAbs().sum();\n    if (diffX < params_.thresh) break;\n\n    // check problem specific stop criteria --- trace value of \\bar{A}\n    const auto Abar = X.bottomRightCorner(X.rows()/2, X.cols()/2);\n    const double Etr = Abar.rows(); // expected trace value (d*m)\n    double tr = 0;\n    for (size_t k=0; k<Abar.rows(); ++k) tr += Abar.coeff(k,k);\n    double trPercentErr = (tr - Etr) / Etr;\n    if (trPercentErr < params_.threshTr) break;\n  }\n\n  //\n  // Project soln to ensure graph constraints are satisfied (set S=0)\n  //\n\n  const SpMat D = C - params_.mu * X;\n  SpMat Dvec; vectorize(D, Dvec);\n  const SpMat e = A * Dvec + params_.mu * b;\n  y = AAs.solve(e); // AAs \\ e\n\n  const SpMat d = (As * y).pruned(1, params_.thrSparseZero);\n  SpMat dmat(X.rows(), X.cols()); unvectorize(d, dmat);\n  const SpMat WW = C - dmat - params_.mu * X;\n  const SpMat W = (WW + SpMat(WW.transpose())) / 2.0;\n\n  X = (- W) / params_.mu;\n}\n\n// ----------------------------------------------------------------------------\n\nvoid Solver::parse(size_t d, size_t m, size_t n,\n                      const Eigen::MatrixXd& adj, const Eigen::MatrixXd& Q,\n                      SpMat& C, SpMat& A, SpMat& b, SpMat& X)\n{\n  //\n  // Preallocate number of non-zeros\n  //\n\n  // block X_11\n  const size_t nrA_X11 =\n      (d*m-1)*2               // [X_11]_11 can be whatever it wants (t)\n                              // but the other diag elements must be == [X_11]_11\n    + (d*m)*(d*m-1)/2;        // set upper-triangular elements to zero\n  const size_t nrb_X11 = 0;\n\n  // block X_12\n  const size_t nrA_X12 =\n      d*m                     // each diagonal elem must be 1\n    + (d*m)*(d*m-1);          // each off-diagonal elem must be 0\n  const size_t nrb_X12 = d*m; // each diagonal elem must be 1\n\n  // structure constraints for each gain matrix block\n  const size_t nrA_X22_struct =\n  (d == 2) ?\n      0.5*m*(m+1)*(2+2)       // structure constraints: A_ij = [a b; -b a]\n                              // 0.5*m*(m+1): each blk, including A_ii blks\n    - m                       // don't count -b elem on A_ii (below diag)\n                              // (2+2) because a-a=0 is 2 and b-b=0 is 2\n  : 0; // no structure requirement for 1D subproblem\n  const size_t nrb_X22_struct = 0;\n\n  // zero-gain constraints based on given adj mat\n  const size_t nr0 = ((adj.array()==0).count() - n)/2; // number of zeros in adj\n  const size_t nrA_X22_adjmat =\n      nr0*(d*(d*m)*(d*m));    // each 0 in adj creates d constraints on \\bar{A}\n  const size_t nrb_X22_adjmat = 0;\n\n  // TODO: see MATLAB impl (ADMMGainDesign3D.m). Do we actually need to remove\n  // trivial constraints, or was that left over from debugging / designing?\n\n  // trace constraint on \\bar{A}\n  const size_t nrA_X22_trace =\n      d*m;                    // the sum of each [X_22]_ii == d*m*destrace\n  const size_t nrb_X22_trace = 1;\n\n  // X must be symmetric: [X]_ij == [X]_ji\n  const size_t nrA_X_sym =\n      2 * d*m * (2*d*m-1);    //\n  const size_t nrb_X_sym = 0;\n\n  // total number of elements from constraints\n  const size_t nrA = nrA_X11 + nrA_X12 + nrA_X22_struct + nrA_X22_adjmat + nrA_X22_trace + nrA_X_sym;\n  const size_t nrb = nrb_X11 + nrb_X12 + nrb_X22_struct + nrb_X22_adjmat + nrb_X22_trace + nrb_X_sym;\n\n  if (params_.verbose) {\n    std::cout << std::endl;\n    std::cout << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"nrA_X11: \" << nrA_X11 << std::endl;\n    std::cout << \"nrA_X12: \" << nrA_X12 << std::endl;\n    std::cout << \"nrA_X22_struct: \" << nrA_X22_struct << std::endl;\n    std::cout << \"nr0: \" << nr0 << std::endl;\n    std::cout << \"nrA_X22_adjmat: \" << nrA_X22_adjmat << std::endl;\n    std::cout << \"nrA_X22_trace: \" << nrA_X22_trace << std::endl;\n    std::cout << \"nrA_X_sym: \" << nrA_X_sym << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"nrA: \" << nrA << std::endl;\n    std::cout << \"nrb: \" << nrb << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << std::endl;\n    std::cout << std::endl;\n  }\n\n  std::vector<Eigen::Triplet<double>> Acoeffs, bcoeffs;\n  Acoeffs.reserve(nrA);\n  bcoeffs.reserve(nrb);\n\n  size_t itrr = 0; // which row of \\mathbf{A} should nz val be in?\n\n  //\n  // Build constraints for block X_11\n  //\n\n  // diagonal entries of X_11 should be equal to the first diagonal entry\n  for (size_t i=1; i<d*m; ++i) {\n\n    // always select first diagonal entry\n    Acoeffs.emplace_back(itrr, 0, 1);\n\n    // [1 0 ... -1 ... 0] vec(X) = 0\n    //           ^\n    //           selects elem corresponding to diagonal, [X_11]_ii\n    const size_t itrc = vecsel(2*d*m, 2*d*m, i, i);\n    Acoeffs.emplace_back(itrr, itrc, -1);\n\n    // create new row in \\mathbf{A} linear constraint matrix\n    itrr++;\n  }\n\n  // off-diagonal entries should be zero\n  for (size_t i=0; i<d*m; ++i) {\n    for (size_t j=i+1; j<d*m; ++j) {\n\n      const size_t itrc = vecsel(2*d*m, 2*d*m, i, j);\n      Acoeffs.emplace_back(itrr, itrc, 1);\n\n      // create new row in \\mathbf{A} linear constraint matrix\n      itrr++;\n    }\n  }\n\n  size_t tmpA = 0;\n  size_t tmpb = 0;\n\n  if (params_.verbose) {\n    std::cout << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"Built rows in \\\\mathbf{A} for X_11 constraints\" << std::endl;\n    std::cout << \"nnzA: \" << Acoeffs.size()-tmpA << std::endl;\n    std::cout << \"nnzb: \" << bcoeffs.size()-tmpb << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << std::endl;\n\n    tmpA = Acoeffs.size();\n    tmpb = bcoeffs.size();\n  }\n\n  //\n  // Build constraints for block X_12\n  //\n\n  // off-diagonal entries should be zero\n  for (size_t i=0; i<d*m; ++i) {\n    for (size_t j=0; j<d*m; ++j) {\n\n      const size_t jj = d*m + j; // skip first dm cols to get into X_12\n      const size_t itrc = vecsel(2*d*m, 2*d*m, i, jj);\n\n      // diagonal entries should be one\n      if (i == j) {\n        Acoeffs.emplace_back(itrr, itrc, 1);\n        bcoeffs.emplace_back(itrr,    0, 1);\n      } else { // all other entries should be zero\n        Acoeffs.emplace_back(itrr, itrc, 1);\n      }\n\n      // create new row in \\mathbf{A} linear constraint matrix\n      itrr++;\n    }\n  }\n\n  if (params_.verbose) {\n    std::cout << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"Built rows in \\\\mathbf{A} for X_12 constraints\" << std::endl;\n    std::cout << \"nnzA: \" << Acoeffs.size()-tmpA << std::endl;\n    std::cout << \"nnzb: \" << bcoeffs.size()-tmpb << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << std::endl;\n\n    tmpA = Acoeffs.size();\n    tmpb = bcoeffs.size();\n  }\n\n  //\n  // Build constraints for block X_22 = \\bar{A}\n  //\n\n  if (d == 2) {\n    // structure constraints A_ij = [a b; -b a]\n    for (size_t i=0; i<m; ++i) {\n      for (size_t j=i; j<m; ++j) {\n\n        // diagonal entries should be equal\n        const size_t ii1 = d*m + blksel(d, i, 0); // skip first dm rows\n        const size_t jj1 = d*m + blksel(d, j, 0); // and cols for X_22\n        const size_t ii2 = d*m + blksel(d, i, 1);\n        const size_t jj2 = d*m + blksel(d, j, 1);\n        const size_t itrc1 = vecsel(2*d*m, 2*d*m, ii1, jj1);\n        const size_t itrc2 = vecsel(2*d*m, 2*d*m, ii2, jj2);\n        Acoeffs.emplace_back(itrr, itrc1,  1);\n        Acoeffs.emplace_back(itrr, itrc2, -1);\n\n        // create new row in \\mathbf{A} linear constraint matrix\n        itrr++;\n\n        // off-diagonal entries should have same value with opposite sign.\n        if (i == j) {\n          // If operating on a blk on the diag (A_ii), only enfore constraints\n          // for the upper triangular portion---sym const enforced later.\n          // note that these constraints enforce b = 0.\n          const size_t ii = d*m + blksel(d, i, 0); // skip first dm rows\n          const size_t jj = d*m + blksel(d, j, 1); // and cols for X_22\n          const size_t itrc = vecsel(2*d*m, 2*d*m, ii, jj);\n          Acoeffs.emplace_back(itrr, itrc, 1);\n        } else {\n          const size_t ii1 = d*m + blksel(d, i, 0); // skip first dm rows\n          const size_t jj1 = d*m + blksel(d, j, 1); // and cols for X_22\n          const size_t ii2 = d*m + blksel(d, i, 1);\n          const size_t jj2 = d*m + blksel(d, j, 0);\n          const size_t itrc1 = vecsel(2*d*m, 2*d*m, ii1, jj1);\n          const size_t itrc2 = vecsel(2*d*m, 2*d*m, ii2, jj2);\n          Acoeffs.emplace_back(itrr, itrc1, 1);\n          Acoeffs.emplace_back(itrr, itrc2, 1);\n        }\n\n        // create new row in \\mathbf{A} linear constraint matrix\n        itrr++;\n      }\n    }\n  }\n\n  // graph constraints (zero blocks for non-neighbors)\n  if (nr0 > 0) {\n    for (size_t i=0; i<n; ++i) {\n      for (size_t j=i+1; j<n; ++j) {\n        if (adj(i,j) == 1) continue;\n\n        // we leverage the structure constraint [a b; -b a] and only\n        // create explicit constraints for [A_ij]_11 and [A_ij]_12.\n\n        // two constraint rows are created in \\mathbf{A}\n        const size_t itrr1 = itrr;\n        const size_t itrr2 = itrr + 1;\n\n        // Constraint on [A_ij]_11\n        const size_t ii1 = blksel(d, i, 0); // skip first dm rows\n        const size_t jj1 = blksel(d, j, 0); // and cols for X_22\n        const Eigen::MatrixXd QQ1 = Q.transpose().col(jj1) * Q.row(ii1);\n\n        Eigen::MatrixXd QQ2;\n        if (d == 2) {\n          // Constraint on [A_ij]_12\n          const size_t ii2 = blksel(d, i, 1); // skip first dm rows\n          const size_t jj2 = blksel(d, j, 0); // and cols for X_22\n          QQ2 = Q.transpose().col(jj2) * Q.row(ii2);\n        }\n\n        // Note how the linear transformation using the orthogonal complement Q\n        // leaks signal into each element of the gain matrix \\bar{A}.\n        for (size_t ki=0; ki<d*m; ++ki) {\n          for (size_t kj=0; kj<d*m; ++kj) {\n\n            const size_t ii = d*m + ki; // skip first dm rows\n            const size_t jj = d*m + kj; // and cols for X_22\n            const size_t itrc = vecsel(2*d*m, 2*d*m, ii, jj);\n\n            Acoeffs.emplace_back(itrr1, itrc, QQ1(ki,kj));\n            if (d == 2) Acoeffs.emplace_back(itrr2, itrc, QQ2(ki,kj));\n          }\n        }\n\n        // advance by d rows in \\mathbf{A} linear constraint matrix\n        itrr += d;\n      }\n    }\n  }\n\n  // trace of \\bar{A} matrix must be the specified value\n  {\n    for (size_t i=0; i<d*m; ++i) {\n\n      const size_t ii = d*m + i; // skip first dm rows/cols for X_22\n      const size_t itrc = vecsel(2*d*m, 2*d*m, ii, ii);\n      Acoeffs.emplace_back(itrr, itrc, 1);\n    }\n\n    // expected trace value\n    bcoeffs.emplace_back(itrr, 0, d*m);\n\n    // create new row in \\mathbf{A} linear constraint matrix\n    itrr++;\n  }\n\n  if (params_.verbose) {\n    std::cout << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"Built rows in \\\\mathbf{A} for X_22 constraints\" << std::endl;\n    std::cout << \"nnzA: \" << Acoeffs.size()-tmpA << std::endl;\n    std::cout << \"nnzb: \" << bcoeffs.size()-tmpb << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << std::endl;\n\n    tmpA = Acoeffs.size();\n    tmpb = bcoeffs.size();\n  }\n\n  //\n  // Symmetry constraints for entire X matrix\n  //\n\n  // symmetric entries should be equal\n  for (size_t i=0; i<2*d*m; ++i) {\n    for (size_t j=i+1; j<2*d*m; ++j) {\n\n      const size_t itrc1 = vecsel(2*d*m, 2*d*m, i, j);\n      const size_t itrc2 = vecsel(2*d*m, 2*d*m, j, i);\n      Acoeffs.emplace_back(itrr, itrc1,  1);\n      Acoeffs.emplace_back(itrr, itrc2, -1);\n\n      // create new row in \\mathbf{A} linear constraint matrix\n      itrr++;\n    }\n  }\n\n  if (params_.verbose) {\n    std::cout << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << \"Built rows in \\\\mathbf{A} for X symmetry constraints\" << std::endl;\n    std::cout << \"nnzA: \" << Acoeffs.size()-tmpA << std::endl;\n    std::cout << \"nnzb: \" << bcoeffs.size()-tmpb << std::endl;\n    std::cout << \"**********************************************\" << std::endl;\n    std::cout << std::endl;\n\n    tmpA = Acoeffs.size();\n    tmpb = bcoeffs.size();\n  }\n\n  //\n  // Prepare sparse matrices for ADMM\n  //\n\n  C.resize(2*d*m, 2*d*m);\n  C.reserve(Eigen::VectorXi::Constant(d*m,1)); // reserve 1 nz per column of X_11\n  for (size_t i=0; i<d*m; ++i) C.insert(i,i) = 1; // make [I 0; 0 0]\n\n  // initialize decision variable to something fairly close\n  X.resize(2*d*m, 2*d*m); // [I I; I I]\n  X.reserve(Eigen::VectorXi::Constant(2*d*m,2)); // reserve 2 nz per column\n  for (size_t i=0; i<d*m; ++i) {\n    X.insert(i,i) = 1;\n    X.insert(d*m+i,i) = 1;\n  }\n  for (size_t i=d*m; i<2*d*m; ++i) {\n    X.insert(i,i) = 1;\n    X.insert(i-d*m,i) = 1;\n  }\n\n  A.resize(itrr, X.size());\n  A.setFromTriplets(Acoeffs.begin(), Acoeffs.end());\n\n  b.resize(itrr, 1);\n  b.setFromTriplets(bcoeffs.begin(), bcoeffs.end());\n}\n\n\n\n} // ns admm\n} // ns aclswarm\n} // ns acl", "meta": {"hexsha": "b2d6445c4399f18246796df44b77b7cb5b831836", "size": 21473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aclswarm/lib/admm/src/solver.cpp", "max_stars_repo_name": "mit-acl/aclswarm", "max_stars_repo_head_hexsha": "2a4d1e0962a3e3bbc2568172f33f5b466e296647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T03:25:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T07:22:44.000Z", "max_issues_repo_path": "aclswarm/lib/admm/src/solver.cpp", "max_issues_repo_name": "mit-acl/aclswarm", "max_issues_repo_head_hexsha": "2a4d1e0962a3e3bbc2568172f33f5b466e296647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-07T18:13:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-07T20:26:00.000Z", "max_forks_repo_path": "aclswarm/lib/admm/src/solver.cpp", "max_forks_repo_name": "mit-acl/aclswarm", "max_forks_repo_head_hexsha": "2a4d1e0962a3e3bbc2568172f33f5b466e296647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-04-10T02:14:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T14:00:53.000Z", "avg_line_length": 30.6757142857, "max_line_length": 101, "alphanum_fraction": 0.5381642062, "num_tokens": 6706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5887406870786166}}
{"text": "// Copyright 2004-5 The Trustees of Indiana University.\n// Copyright 2002 Brad King and Douglas Gregor\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n\n#ifndef _ALG_PAGE_RANK_HPP\n#define _ALG_PAGE_RANK_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/iteration_macros.hpp>\n#include <boost/graph/overloading.hpp>\n#include <boost/graph/page_rank.hpp>\n#include <vector>\n\nnamespace boost { namespace graph {\n\n//~ struct n_iterations\n//~ {\n  //~ explicit n_iterations(std::size_t n) : n(n) { }\n\n  //~ template<typename RankMap, typename Graph>\n  //~ bool \n  //~ operator()(const RankMap&, const Graph&)\n  //~ {\n    //~ return n-- == 0;\n  //~ }\n\n //~ private:\n  //~ std::size_t n;\n//~ };\n\nnamespace detail {\n  template<typename Graph, typename RankMap, typename RankMap2>\n  void page_rank_step(const Graph& g, RankMap from_rank, RankMap2 to_rank,\n                      typename property_traits<RankMap>::value_type damping,\n                      std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct,\n                      incidence_graph_tag)\n  {\n    typedef typename property_traits<RankMap>::value_type rank_type;\n\n    // Set new rank maps \n    BGL_FORALL_VERTICES_T(v, g, Graph) put(to_rank, v, rank_type(1 - damping));\n\n    BGL_FORALL_VERTICES_T(u, g, Graph) {\n      rank_type u_rank_out = damping * get(from_rank, u) / out_degree(u, g);\n      BGL_FORALL_ADJ_T(u, v, g, Graph){\n        rank_type ctx_factor = decision_fct(u, v);\n        put(to_rank, v, get(to_rank, v) + u_rank_out * ctx_factor);\n      }\n    }\n  }\n\n  template<typename Graph, typename RankMap, typename RankMap2>\n  void page_rank_step(const Graph& g, RankMap from_rank, RankMap2 to_rank,\n                      typename property_traits<RankMap>::value_type damping,\n                      std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct,\n                      bidirectional_graph_tag)\n  {\n    typedef typename property_traits<RankMap>::value_type damping_type;\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      typename property_traits<RankMap>::value_type rank(0);\n      BGL_FORALL_INEDGES_T(v, e, g, Graph){\n        damping_type ctx_factor = decision_fct(v, source(e, g));\n        rank += get(from_rank, source(e, g)) / out_degree(source(e, g), g) * ctx_factor;\n      }\n      put(to_rank, v, (damping_type(1) - damping) + damping * rank);\n    }\n  }\n} // end namespace detail\n\ntemplate<typename Graph, typename RankMap, typename Done, typename RankMap2>\nvoid\npage_rank(const Graph& g, RankMap rank_map,\n          std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct, \n          Done done, \n          typename property_traits<RankMap>::value_type damping,\n          typename graph_traits<Graph>::vertices_size_type n,\n          RankMap2 rank_map2\n          BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph, vertex_list_graph_tag))\n{\n  typedef typename property_traits<RankMap>::value_type rank_type;\n\n  rank_type initial_rank = rank_type(rank_type(1) / n);\n  BGL_FORALL_VERTICES_T(v, g, Graph) put(rank_map, v, initial_rank);\n\n  bool to_map_2 = true;\n  while ((to_map_2 && !done(rank_map, g)) ||\n         (!to_map_2 && !done(rank_map2, g))) {\n    typedef typename graph_traits<Graph>::traversal_category category;\n\n    if (to_map_2) {\n      detail::page_rank_step(g, rank_map, rank_map2, damping, decision_fct, category());\n    } else {\n      detail::page_rank_step(g, rank_map2, rank_map, damping, decision_fct, category());\n    }\n    to_map_2 = !to_map_2;\n  }\n\n  if (!to_map_2) {\n    BGL_FORALL_VERTICES_T(v, g, Graph) put(rank_map, v, get(rank_map2, v));\n  }\n}\n\ntemplate<typename Graph, typename RankMap, typename Done>\nvoid\npage_rank(const Graph& g, RankMap rank_map,\n          std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct, \n          Done done, \n          typename property_traits<RankMap>::value_type damping,\n          typename graph_traits<Graph>::vertices_size_type n)\n{\n  typedef typename property_traits<RankMap>::value_type rank_type;\n\n  std::vector<rank_type> ranks2(num_vertices(g));\n  page_rank(g, rank_map, decision_fct, done, damping, n,\n            make_iterator_property_map(ranks2.begin(), get(vertex_index, g)));\n}\n\ntemplate<typename Graph, typename RankMap, typename Done>\ninline void\npage_rank_ctx(const Graph& g, RankMap rank_map,\n          std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct, \n          Done done, \n          typename property_traits<RankMap>::value_type damping = 0.85)\n{\n  page_rank(g, rank_map, decision_fct, done, damping, num_vertices(g));\n}\n\ntemplate<typename Graph, typename RankMap>\ninline void\npage_rank_ctx(const Graph& g, RankMap rank_map,\n          std::function<typename property_traits<RankMap>::value_type (typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_fct)\n{\n  page_rank_ctx(g, rank_map, decision_fct, n_iterations(20));\n}\n\n\n} } // end namespace boost::graph\n\n#ifdef BOOST_GRAPH_USE_MPI\n#  include <boost/graph/distributed/page_rank.hpp>\n#endif\n\n#endif // BOOST_GRAPH_PAGE_RANK_HPP\n", "meta": {"hexsha": "dc30cb448130cb328938b5a08266f687dfdb50ca", "size": 5838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nctx/topology/page_rank_ctx.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/nctx/topology/page_rank_ctx.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/nctx/topology/page_rank_ctx.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": 38.4078947368, "max_line_length": 195, "alphanum_fraction": 0.7110311751, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5887406818154223}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <functional>\n\n#include \"../util/assert.hh\"\n#include \"../util/Maybe.hh\"\n\nnamespace bold\n{\n  template<typename T>\n  class LineSegment2;\n\n  class Math\n  {\n  public:\n    static Maybe<Eigen::Vector3d> intersectRayWithGroundPlane(Eigen::Vector3d const& position,\n                                                              Eigen::Vector3d const& direction,\n                                                              double const planeZ);\n\n    static Maybe<Eigen::Vector3d> intersectRayWithPlane(Eigen::Vector3d const& position,\n                                                        Eigen::Vector3d const& direction,\n                                                        Eigen::Vector4d const& plane);\n\n    static Eigen::Vector2d linePointClosestToPoint(LineSegment2<double> const& segment,\n                                                   Eigen::Vector2d const& point);\n\n    // TODO what if 'vector' has zero length? should this return 'Maybe<Vector2d>'?\n    static Eigen::Vector2d findPerpendicularVector(Eigen::Vector2d const& vector);\n\n    static std::function<double()> createUniformRng(double min, double max, bool randomSeed = true);\n    static std::function<double()> createNormalRng(double mean, double stddev, bool randomSeed = true);\n\n    static constexpr double degToRad(double degrees) { return (degrees * M_PI) / 180.0; }\n    static constexpr double radToDeg(double radians) { return (radians / M_PI) * 180.0; }\n\n    static double smallestAngleBetween(Eigen::Vector2d v1, Eigen::Vector2d v2);\n\n    static Eigen::Affine3d alignUp(Eigen::Affine3d const& transform);\n\n    template<typename T>\n    static constexpr T clamp(T val, T min, T max)\n    {\n      return val < min\n        ? min\n        : val > max\n          ? max\n          : val;\n    }\n\n    /**\n      * Maps @link input to a value in the range from @link lowerOutput to @link upperOutput.\n      * If @link input is outside the range from @link lower to @link upper, then @link lowerOutput or @link upperOutput are returned,\n      * otherwise the value is linearly interpolated.\n      * Note that @link lower must be less than @link upper, but that there is no restriction on values of @link lowerOutput and @link upperOutput.\n      */\n    template<typename T>\n    static T lerp(double const& input, double const& lower, double const& upper, T const& lowerOutput, T const& upperOutput)\n    {\n      if (unlikely(upper <= lower))\n        throw std::runtime_error(\"lower must be less than upper\");\n\n      double ratio = (input - lower) / (upper - lower);\n      ratio = clamp(ratio, 0.0, 1.0);\n\n      return lowerOutput + (upperOutput - lowerOutput) * ratio;\n    }\n\n    template<typename T>\n    static constexpr T lerp(double const& ratio, T const& lowerOutput, T const& upperOutput)\n    {\n      return lowerOutput + (upperOutput - lowerOutput) * ratio;\n    }\n\n    /** Constrains the angle to range [-PI,PI). */\n    static double normaliseRads(double rads)\n    {\n      rads = fmod(rads + M_PI, 2*M_PI);\n      if (rads < 0)\n          rads += 2*M_PI;\n      return rads - M_PI;\n    }\n\n    /** Angle spanned by rotation between two angles\n     *\n     * The rotation is measured by rotating from @a a1 to @a2 in\n     * positive direction (counter clockwise for right hand system).\n     */\n    static double angleDiffRads(double a1, double a2)\n    {\n      double rads = a2 - a1;\n      if (rads < 0.0)\n        rads += 2.0 * M_PI;\n      return rads;\n    }\n\n    /** Absolute distance between two angles in radians\n     *\n     * e.g.:\n     * |pi - .5 pi| = |.5 pi - pi| = .5 pi\n     * | -.1 po - .1pi | = | .1pi - -.1 pi | = .2 pi\n     * | -.9 pi - .9 pi | = | .9 pi - -.9pi | = .2 pi\n     */\n    static double shortestAngleDiffRads(double a1, double a2)\n    {\n      // The fmod() function computes the floating-point remainder of\n      // dividing x by y.  The return value is x - n * y, where n is\n      // the quotient of x / y, rounded toward zero to an integer.\n      double d = fmod(a2 - a1, 2 * M_PI);\n\n      d += (d > M_PI)\n        ? -2 * M_PI\n        : d <= -M_PI\n          ? 2 * M_PI\n          : 0;\n\n      return d;\n    }\n\n    /** Returns the angle to a point, as defined in the agent frame,\n     * where zero is straight ahead and positive is to the left\n     * (counter-clockwise). */\n    template<int N>\n    static double angleToPoint(Eigen::Matrix<double, N, 1> const& point)\n    {\n      static_assert(N > 1, \"Vector must have at least two dimensions\");\n      return ::atan2(-point.x(), point.y());\n    }\n\n    /** Returns the point at the given angle and distance, as defined\n     * in the agent frame, where zero is straight ahead and positive\n     * is to the left (counter-clockwise). */\n    static inline Eigen::Vector2d pointAtAngle(double angle, double distance)\n    {\n      return Eigen::Vector2d(cos(angle) * distance, sin(angle) * distance);\n    }\n\n    /** Returns mean of angles\n     *\n     * TODO: Algorithm at:\n     * http://www.codeproject.com/Articles/190833/Circular-Values-Math-and-Statistics-with-Cplusplus\n     * seems to give more intuitive results\n     */\n    static double angularMean(std::vector<double> const& angles)\n    {\n      double x = 0.0;\n      double y = 0.0;\n      for (auto a : angles)\n      {\n        x += sin(a);\n        y += cos(a);\n      }\n      return atan2(x / angles.size(), y / angles.size());\n    }\n\n  private:\n    Math() = delete;\n  };\n}\n", "meta": {"hexsha": "c67297dc5d2abba4ea915a5f9d146ad4eca90268", "size": 5425, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Math/math.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": "Math/math.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": "Math/math.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": 33.6956521739, "max_line_length": 147, "alphanum_fraction": 0.5948387097, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5887406710746173}}
{"text": "// -*- mode: c++; fill-column: 80; indent-tabs-mode: nil; -*-\n\n#include <cassert>\n#include <cmath>\n\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n#include \"expsum/fast_esprit.hpp\"\n#include <boost/math/special_functions/bessel.hpp>\n\nusing size_type = arma::uword;\n// using Complex   = std::complex<double>;\n\n//------------------------------------------------------------------------------\n// Test functors\n//------------------------------------------------------------------------------\n\nstruct BesselJ0\n{\n    double operator()(double x) const\n    {\n        return boost::math::cyl_bessel_j(0, x);\n    }\n};\n\nstruct rinv\n{\n    double operator()(double x) const\n    {\n        return 1.0 / x;\n    }\n};\n\ntemplate <typename F, typename Vec>\nvoid make_sample(F f, double xmin, double xmax, Vec& result)\n{\n    auto np = result.n_elem;\n    auto h  = (xmax - xmin) / (np - 1);\n    for (size_type n = 0; n < np; ++n)\n    {\n        result(n) = f(xmin + n * h);\n    }\n\n    return;\n}\n\ntemplate <typename F>\nvoid test_fast_esprit(F fn, double xmin, double xmax, size_type N, size_type L,\n                      size_type M, double eps)\n{\n    using value_type  = decltype(fn(xmin));\n    using vector_type = arma::Col<value_type>;\n    using esprit_type = expsum::fast_esprit<value_type>;\n    using real_type   = typename esprit_type::real_type;\n\n    vector_type exact(N);\n    make_sample(fn, xmin, xmax, exact);\n    auto delta = (xmax - xmin) / (N - 1);\n\n    // ESPRIT esprit(N, std::min<size_type>(100, n / 2));\n    esprit_type esprit(N, L, M);\n\n    esprit.fit(exact, xmin, delta, eps);\n\n    auto nterms = esprit.exponents().n_elem;\n    std::cout << \"# \" << nterms << \" terms found\\n\"\n              << \"# exponent, weight\\n\";\n\n    for (size_type i = 0; i < nterms; ++i)\n    {\n        std::cout << esprit.exponents()(i) << '\\t' << esprit.weights()(i)\n                  << '\\n';\n    }\n\n    std::cout << \"# x, approx, exact, abserr, relerr\\n\";\n\n    for (size_type i = 0; i < N; ++i)\n    {\n        auto x      = xmin + i * delta;\n        auto approx = esprit.eval_at(x);\n        auto abserr = std::abs(approx - exact(i));\n        auto relerr =\n            (abserr == real_type()) ? real_type() : abserr / std::abs(exact(i));\n\n        std::cout << x << '\\t' << approx << '\\t' << exact(i) << '\\t' << abserr\n                  << '\\t' << relerr << '\\n';\n    }\n}\n\nint main()\n{\n    std::cout.precision(15);\n    std::cout.setf(std::ios::scientific);\n\n    std::cout << \"# Approximation of Bessel J0(x): x in [0, 1000] by fast \"\n                 \"ESPRIT method.\"\n              << std::endl;\n    size_type N = 1024;  // # of sampling points\n    size_type L = N / 2; // window length\n    size_type M = 100;   // max # of terms\n    double xmin = 0.0;\n    double xmax = 1000.0;\n    double eps  = 1.0e-10;\n    test_fast_esprit(BesselJ0(), xmin, xmax, N, L, M, eps);\n\n    std::cout << \"\\n\\n# Approximation of 1/r: r in [1, 10^{6}] by fast\"\n                 \"ESPRIT method.\"\n              << std::endl;\n    N    = (1 << 12);\n    L    = N / 2;\n    M    = 100;\n    xmin = 1.0;\n    xmax = 1.0e+6;\n    eps  = 1.0e-8;\n    test_fast_esprit(rinv(), xmin, xmax, N, L, M, eps);\n\n    // std::cout << \"# Exponential sum recovery test\" << std::endl;\n    // const auto pi = arma::datum::pi;\n    // numeric::ExponentialSum<Complex> orig(5);\n\n    // orig.exponents(0) = Complex(0.0,     0.0);\n    // orig.exponents(1) = Complex(0.0,  pi / 4);\n    // orig.exponents(2) = Complex(0.0, -pi / 4);\n    // orig.exponents(3) = Complex(0.0,  pi / 2);\n    // orig.exponents(4) = Complex(0.0, -pi / 2);\n\n    // orig.weights(0) = Complex(34.0,  0.0);\n    // orig.weights(1) = Complex(300.0, 0.0);\n    // orig.weights(2) = Complex(300.0, 0.0);\n    // orig.weights(3) = Complex(1.0,   0.0);\n    // orig.weights(4) = Complex(1.0,   0.0);\n\n    // N = 1024;\n    // L = N / 2;\n    // M = 20;\n    // eps = 1.0e-10;\n    // test_frequency_estimation(orig, N, L, M, eps);\n\n    return 0;\n}\n", "meta": {"hexsha": "c265c24c9d651d9de40493f8f684666a4344518b", "size": 3928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fast_esprit.cpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fast_esprit.cpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fast_esprit.cpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4685314685, "max_line_length": 80, "alphanum_fraction": 0.5137474542, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5887257208429134}}
{"text": "// This example consists of a single constant velocity target which\n// moves under piecewise constant velocity in 3D. Its position is\n// measured by an idealised GPS receiver.\n\n#include <Eigen/StdVector>\n#include <iostream>\n\n#include <stdint.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/cholmod/linear_solver_cholmod.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n#include <g2o/stuff/sampler.h>\n\n#include \"targetTypes6D.hpp\"\n#include \"continuous_to_discrete.h\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace g2o;\n\nint main()\n{\n  // Set up the parameters of the simulation\n  int numberOfTimeSteps = 1000;\n  const double processNoiseSigma = 1;\n  const double accelerometerNoiseSigma = 1;\n  const double gpsNoiseSigma = 1;\n  const double dt = 1;  \n\n  // Set up the optimiser and block solver\n  SparseOptimizer optimizer;\n  optimizer.setVerbose(false);\n\n  typedef BlockSolver< BlockSolverTraits<6, 6> > BlockSolver;\n  BlockSolver::LinearSolverType * linearSolver\n      = new LinearSolverCholmod<BlockSolver::PoseMatrixType>();\n  BlockSolver* blockSolver = new BlockSolver(linearSolver);\n  OptimizationAlgorithm* optimizationAlgorithm = new OptimizationAlgorithmGaussNewton(blockSolver);\n  optimizer.setAlgorithm(optimizationAlgorithm);\n\n  // Sample the start location of the target\n  Vector6d state;\n  state.setZero();\n  for (int k = 0; k < 3; k++)\n    {\n      state[k] = 1000 * sampleGaussian();\n    }\n  \n  // Construct the first vertex; this corresponds to the initial\n  // condition and register it with the optimiser\n  VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n  stateNode->setEstimate(state);\n  stateNode->setId(0);\n  optimizer.addVertex(stateNode);\n\n  // Set up last estimate\n  VertexPositionVelocity3D* lastStateNode = stateNode;\n\n  // Iterate over the simulation steps\n  for (int k = 1; k <= numberOfTimeSteps; ++k)\n    {\n      // Simulate the next step; update the state and compute the observation\n      Vector3d processNoise(processNoiseSigma*sampleGaussian(),\n                            processNoiseSigma*sampleGaussian(),\n                            processNoiseSigma*sampleGaussian());\n\n      for (int m = 0; m < 3; m++)\n        {\n          state[m] += dt * (state[m+3] + 0.5 * dt * processNoise[m]);\n        }\n\n      for (int m = 0; m < 3; m++)\n        {\n          state[m+3] += dt * processNoise[m];\n        }\n\n      // Construct the accelerometer measurement\n      Vector3d accelerometerMeasurement;\n      for (int m = 0; m < 3; m++)\n        {\n          accelerometerMeasurement[m] = processNoise[m] + accelerometerNoiseSigma * sampleGaussian();\n        }\n\n      // Construct the GPS observation\n      Vector3d gpsMeasurement;     \n      for (int m = 0; m < 3; m++)\n        {\n          gpsMeasurement[m] = state[m] + gpsNoiseSigma * sampleGaussian();\n        }\n\n      // Construct vertex which corresponds to the current state of the target\n      VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n      \n      stateNode->setId(k);\n      stateNode->setMarginalized(false);\n      optimizer.addVertex(stateNode);\n\n      TargetOdometry3DEdge* toe = new TargetOdometry3DEdge(dt, accelerometerNoiseSigma);\n      toe->setVertex(0, lastStateNode);\n      toe->setVertex(1, stateNode);\n      VertexPositionVelocity3D* vPrev= dynamic_cast<VertexPositionVelocity3D*>(lastStateNode);\n      VertexPositionVelocity3D* vCurr= dynamic_cast<VertexPositionVelocity3D*>(stateNode);\n      toe->setMeasurement(accelerometerMeasurement);\n      optimizer.addEdge(toe);\n      \n      // compute the initial guess via the odometry\n      g2o::OptimizableGraph::VertexSet vPrevSet;\n      vPrevSet.insert(vPrev);\n      toe->initialEstimate(vPrevSet,vCurr);\n\n      lastStateNode = stateNode;\n\n      // Add the GPS observation\n      GPSObservationEdgePositionVelocity3D* goe = new GPSObservationEdgePositionVelocity3D(gpsMeasurement, gpsNoiseSigma);\n      goe->setVertex(0, stateNode);\n      optimizer.addEdge(goe);\n    }\n\n  // Configure and set things going\n  optimizer.initializeOptimization();\n  optimizer.setVerbose(true);\n  optimizer.optimize(5);\n  cerr << \"number of vertices:\" << optimizer.vertices().size() << endl;\n  cerr << \"number of edges:\" << optimizer.edges().size() << endl;\n\n  // Print the results\n\n  cout << \"state=\\n\" << state << endl;\n\n#if 0\n  for (int k = 0; k < numberOfTimeSteps; k++)\n    {\n      cout << \"computed estimate \" << k << \"\\n\"\n           << dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find(k)->second)->estimate() << endl;\n       }\n#endif\n\n  Vector6d v1 = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find((std::max)(numberOfTimeSteps-2,0))->second)->estimate();\n  Vector6d v2 = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find((std::max)(numberOfTimeSteps-1,0))->second)->estimate();\n  cout << \"v1=\\n\" << v1 << endl;\n  cout << \"v2=\\n\" << v2 << endl;\n  cout << \"delta state=\\n\" << v2-v1 << endl;\n}\n", "meta": {"hexsha": "6ea409ca5683b814e8d077bc43f463c99b9eabc4", "size": 5070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Thirdparty/g2o/g2o/examples/target/constant_velocity_target.cpp", "max_stars_repo_name": "liyi2017/StructSLAM", "max_stars_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2018-03-11T03:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:39:26.000Z", "max_issues_repo_path": "Thirdparty/g2o/g2o/examples/target/constant_velocity_target.cpp", "max_issues_repo_name": "jyakaranda/StructSLAM", "max_issues_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_issues_repo_licenses": ["MIT"], "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": "Thirdparty/g2o/g2o/examples/target/constant_velocity_target.cpp", "max_forks_repo_name": "jyakaranda/StructSLAM", "max_forks_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T11:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T05:35:53.000Z", "avg_line_length": 34.4897959184, "max_line_length": 138, "alphanum_fraction": 0.683234714, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5886503061487651}}
{"text": "#ifndef BURST_BENCHMARK_UTILITY_RANDOM_URD_ORDER_STATISTIC_DISTRIBUTION_HPP\n#define BURST_BENCHMARK_UTILITY_RANDOM_URD_ORDER_STATISTIC_DISTRIBUTION_HPP\n\n#include <boost/math/special_functions/beta.hpp>\n\n#include <cstddef>\n#include <random>\n#include <tuple>\n\nnamespace utility\n{\n    template <typename RealType>\n    class urd_order_statistic_distribution;\n\n    template <typename RealType>\n    class urd_order_statistic_distribution_param\n    {\n    public:\n        using distribution_type = urd_order_statistic_distribution<RealType>;\n\n        urd_order_statistic_distribution_param\n        (\n            std::size_t n,\n            std::size_t k,\n            RealType a,\n            RealType b\n        ):\n            m_n(n),\n            m_k(k),\n            m_a(a),\n            m_b(b)\n        {\n        }\n\n        std::size_t n () const\n        {\n            return m_n;\n        }\n\n        std::size_t k () const\n        {\n            return m_k;\n        }\n\n        RealType a () const\n        {\n            return m_a;\n        }\n\n        RealType b () const\n        {\n            return m_b;\n        }\n\n        friend bool\n            operator ==\n            (\n                const urd_order_statistic_distribution_param & left,\n                const urd_order_statistic_distribution_param & right\n            )\n        {\n            return\n                std::tie(left.m_n, left.m_k, left.m_a, left.m_b) ==\n                std::tie(right.m_n, right.m_k, right.m_a, right.m_b);\n        }\n\n        friend bool\n            operator !=\n            (\n                const urd_order_statistic_distribution_param & left,\n                const urd_order_statistic_distribution_param & right\n            )\n        {\n            return !(left == right);\n        }\n\n    private:\n        std::size_t m_n;\n        std::size_t m_k;\n        RealType m_a;\n        RealType m_b;\n    };\n\n    /*!\n        \\brief\n            Распределение порядковых статистик выборки из стандартного непрерывного равномерного\n            распределения.\n\n        \\details\n            \"urd\" означает \"uniform random distribution\".\n            https://ru.wikipedia.org/wiki/Порядковая_статистика#Пример\n    */\n    template <typename RealType = double>\n    class urd_order_statistic_distribution\n    {\n    public:\n        using result_type = RealType;\n        using param_type = urd_order_statistic_distribution_param<result_type>;\n\n        /*!\n            \\brief\n                Создание распределения с параметрами\n\n            \\param n\n                Размер выборки.\n            \\param k\n                Номер порядковой статистики.\n            \\param a\n                Минимальное значение равномерного распределения.\n            \\param b\n                Максимальное значение равномерного распределения.\n         */\n        urd_order_statistic_distribution\n        (\n            std::size_t n,\n            std::size_t k,\n            result_type a,\n            result_type b\n        ):\n            m_param(n, k, a, b)\n        {\n        }\n\n        explicit urd_order_statistic_distribution (const param_type & p):\n            m_param(p)\n        {\n        }\n\n        void reset ()\n        {\n        }\n\n        template <typename URNG>\n        result_type operator () (URNG & g)\n        {\n            return (*this)(g, m_param);\n        }\n\n        template <typename URNG>\n        result_type operator () (URNG & g, const param_type & p)\n        {\n            auto ibeta = m_uniform(g);\n            auto beta = boost::math::ibeta_inv(p.k(), p.n() - p.k() + 1, ibeta);\n            return beta * (p.b() - p.a()) + p.a();\n        }\n\n        std::size_t n () const\n        {\n            return m_param.n();\n        }\n\n        std::size_t k () const\n        {\n            return m_param.k();\n        }\n\n        result_type a () const\n        {\n            return m_param.a();\n        }\n\n        result_type b () const\n        {\n            return m_param.b();\n        }\n\n        param_type param () const\n        {\n            return m_param;\n        }\n\n        void param (const param_type & p)\n        {\n            m_param = p;\n        }\n\n        result_type min () const\n        {\n            return a();\n        }\n\n        result_type max () const\n        {\n            return b();\n        }\n\n        friend bool\n            operator ==\n            (\n                const urd_order_statistic_distribution & left,\n                const urd_order_statistic_distribution& right\n            )\n        {\n            return left.m_param == right.m_param;\n        }\n\n        friend bool\n            operator !=\n            (\n                const urd_order_statistic_distribution & left,\n                const urd_order_statistic_distribution& right\n            )\n        {\n            return !(left == right);\n        }\n\n    private:\n        using uniform_real_distribution_type = std::uniform_real_distribution<result_type>;\n\n        param_type m_param;\n        uniform_real_distribution_type m_uniform{0, 1};\n    };\n}\n\n#endif // BURST_BENCHMARK_UTILITY_RANDOM_URD_ORDER_STATISTIC_DISTRIBUTION_HPP\n", "meta": {"hexsha": "af4609d15d655272cf61f31b62873859b9dd7e9e", "size": 5059, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/include/random/urd_order_statistic_distribution.hpp", "max_stars_repo_name": "izvolov/thrust", "max_stars_repo_head_hexsha": "399e12eed54131d731c4c5ef40512b17107bca56", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-11-25T14:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T11:47:19.000Z", "max_issues_repo_path": "benchmark/include/random/urd_order_statistic_distribution.hpp", "max_issues_repo_name": "izvolov/burst", "max_issues_repo_head_hexsha": "399e12eed54131d731c4c5ef40512b17107bca56", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 147.0, "max_issues_repo_issues_event_min_datetime": "2015-01-11T08:36:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-04T09:03:36.000Z", "max_forks_repo_path": "benchmark/include/random/urd_order_statistic_distribution.hpp", "max_forks_repo_name": "izvolov/thrust", "max_forks_repo_head_hexsha": "399e12eed54131d731c4c5ef40512b17107bca56", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-06-02T17:28:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-05T11:16:16.000Z", "avg_line_length": 23.4212962963, "max_line_length": 96, "alphanum_fraction": 0.5105752125, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5886503000515584}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    /* Constructor */\n\n    arma::mat input;\n    /*\n    input << 1 << 446 << 42 << arma::endr\n          << 2 <<  16 << 63 << arma::endr\n          << 3 <<  13 << 63 << arma::endr\n          << 4 <<  21 << 21 << arma::endr\n          << 1 <<  13 << 11 << arma::endr\n          << 32 << 45 << 42 << arma::endr\n          << 22 << 16 << 63 << arma::endr\n          << 32 << 13 << 42 << arma::endr;\n    */\n    input << 1  << 19  << arma::endr\n          << 2  << 20  << arma::endr\n          << 3  << 21  << arma::endr\n          << 4  << 22  << arma::endr\n          << 5  << 23  << arma:: endr\n          << 6  << 24  << arma::endr\n          << 7  << 25  << arma::endr\n          << 8  << 26  << arma:: endr\n          << 9  << 27  << arma::endr\n          << 10 << 28  << arma::endr\n          << 11 << 29  << arma:: endr\n          << 12 << 30  << arma::endr\n          << 13 << 31  << arma::endr\n          << 14 << 32  << arma:: endr\n          << 15 << 33  << arma::endr\n          << 16 << 34  << arma::endr\n          << 17 << 35  << arma:: endr\n          << 18 << 36  << arma::endr;\n    cout << \"-----------------------------------\" << endl;\n    cout << \"Input shape : \" << input.n_rows << \" \" << input.n_cols << endl;\n    cout << \"-----------------------------------\" << endl;\n\n    const size_t size = 3; // number of channels\n    const double eps = 1e-5;\n    const double momentum = 0.1;\n    arma::mat weights, runningMean, runningVariance, gamma, beta;\n    weights.set_size(size + size, 1); // (size + size, 1)\n    runningMean.zeros(size, 1); // (size, 1)\n    runningVariance.ones(size, 1); // (size, 1)\n\n    /* Reset() */\n\n    gamma = arma::mat(weights.memptr(), size, 1, false, false);  // (size, 1)\n    beta = arma::mat(weights.memptr() + gamma.n_elem, size, 1, false, false); // (size, 1)\n    gamma.fill(1.0);\n    beta.fill(0.0);\n\n    /* Forward */\n\n    // Step-0 : Preparation of temporary cubes for input and output\n    const size_t batchSize = input.n_cols;\n    const size_t inputSize = input.n_rows / size; // (inputWidth * inputHeight)\n    arma::mat output;\n    output.set_size(arma::size(input));\n    arma::cube inputTemp(const_cast<arma::mat&>(input).memptr(),input.n_rows / size, size, batchSize, false, false);\n    arma::cube outputTemp(const_cast<arma::mat&>(output).memptr(),input.n_rows / size, size, input.n_cols, false, false);\n    outputTemp = inputTemp; // n_rows = inputSize, n_cols = size, n_slices = batchSize // (4, 2, 3)\n\n    cout << \"N     : \" << batchSize << endl;\n    cout << \"C     : \" << size << endl;\n    cout << \"H x W : \" << inputSize << endl;\n    cout << \"-----------------------------------\" << endl;\n    cout << \"Input Cube - \" << endl << \"each slice is an image of the batch of \"<< batchSize << \" images\" << endl << \"each column of a slice is one of the \" << size << \" channels of the image, HxW is flattened into this single column\" << endl;\n    cout << \"-----------------------------------\" << endl;\n    inputTemp.print();\n    cout << \"-----------------------------------\" << endl;\n\n    // PURE FORWARD FOR INSTANCE NORM\n\n    arma::cube mean(1, size, batchSize);\n    arma::cube variance(1, size, batchSize);\n    for (size_t s = 0; s < inputTemp.n_slices; s++)\n    {\n        arma::mat& currentInputSlice = inputTemp.slice(s);\n        arma::mat& currentOutputSlice = outputTemp.slice(s);\n\n        // Step -1 :  Calculate mean and variance\n        mean.slice(s) = arma::mean(currentInputSlice,0);\n        variance.slice(s) = arma::var(currentInputSlice, 1, 0);\n\n        // Step 2 : Normalisation\n        currentOutputSlice -= arma::repmat(mean.slice(s), input.n_rows / size, 1);\n        currentOutputSlice /= arma::sqrt(arma::repmat(variance.slice(s), input.n_rows / size, 1) + eps);\n\n        // Step 3 : Scaling\n        currentOutputSlice %= arma::repmat(gamma.t(), input.n_rows / size, 1);\n        currentOutputSlice += arma::repmat(beta.t(), input.n_rows / size, 1);\n    }\n    cout << \"Input Mean : \" << endl;\n    cout << mean << endl;\n    cout << \"-----------------------------------\" << endl;\n    cout << \"Input Variance : \" << endl;\n    cout << variance << endl;\n    cout << \"-----------------------------------\" << endl;\n    cout << \"Output Cube - \" << endl << \"each slice is an image of the batch of \"<< batchSize << \" images\" << endl << \"each column of a slice is one of the \" << size << \" channels of the image, HxW is flattened into this single column\" << endl;\n    cout << \"-----------------------------------\" << endl;\n    outputTemp.print();\n    cout << \"-----------------------------------\" << endl;\n\n    cout << \"Output shape : \" << output.n_rows << \" \" << output.n_cols << endl;\n    cout << \"-----------------------------------\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "d739bac3851f478e607e6a69f1afe49899e99a69", "size": 4794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "instance_norm/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": "instance_norm/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": "instance_norm/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": 41.3275862069, "max_line_length": 244, "alphanum_fraction": 0.4891531081, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5886502997778299}}
{"text": "#ifndef STAN_MATH_FWD_SCAL_FUN_INV_SQRT_HPP\n#define STAN_MATH_FWD_SCAL_FUN_INV_SQRT_HPP\n\n#include <stan/math/fwd/core.hpp>\n\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T>\n    inline\n    fvar<T>\n    inv_sqrt(const fvar<T>& x) {\n      using std::sqrt;\n      T sqrt_x(sqrt(x.val_));\n      return fvar<T>(1 / sqrt_x, -0.5 * x.d_ / (x.val_ * sqrt_x));\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "3bd9d4b9121374ecfb65708fa125cfc12763d532", "size": 425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/inv_sqrt.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/scal/fun/inv_sqrt.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/scal/fun/inv_sqrt.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": 19.3181818182, "max_line_length": 66, "alphanum_fraction": 0.6588235294, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5886502950492627}}
{"text": "// TMA_calculator.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//\r\n\r\n#include \"pch.h\"\r\n#include <iostream>\r\n#include <math.h>\r\n#include <vector>\r\n#include <thread>\r\n#include <dlib/matrix.h>\r\n#include <dlib/optimization.h>\r\n#include <dlib/global_optimization.h>\r\n#include <wchar.h>\r\n#include <locale.h>\r\n#include <io.h>\r\n#include <cstdio>\r\n#include <cwchar>\r\n#include <fcntl.h>\r\n\r\nusing namespace std;\r\n\r\nvector<double> bearing = vector<double>(20, 0.0); //target bearing\r\nvector<double> bearing_noisy = vector<double>(20, 0.0); //target bearing with random inaccuracies\r\nvector<double> recording_time = vector<double>(20, 0.0);\r\n\r\n//ownship coordinate (m,n)\r\nvector<double> m = vector<double>(20, 0.0); \r\nvector<double> n = vector<double>(20, 0.0);\r\n\r\nunsigned int _j = 2; //iteration index\r\ndouble own_ship_hdg = 0.0; //ownship heading\r\ndouble last_travel_distance = 0.0; //ownship travel straight distance from last position\r\ndouble last_travel_direction = 0.0; //ownship travel straight direction from last position\r\n\r\ntypedef dlib::matrix<double, 0, 1> column_vector;\r\n\r\n// Simple upper and lower limiter\r\ndouble limit(double input, double lower_limit, double upper_limit)\r\n{\r\n    if (input > upper_limit)\r\n    {\r\n        return upper_limit;\r\n    }\r\n    else if (input < lower_limit)\r\n    {\r\n        return lower_limit;\r\n    }\r\n    else\r\n    {\r\n        return input;\r\n    }\r\n}\r\n\r\nvector<double> calculate_last_brg(const double &L1_distance, const double &spd, const double &crs)\r\n{\r\n    vector<double> out = vector<double>(3, 0.0);\r\n    double u = spd * sin(crs * deg_to_rad); //target speed component on x axis\r\n    double v = spd * cos(crs * deg_to_rad); //target speed component on y axis\r\n\r\n    //target coordinate (a,b) at first bearing\r\n    double a = L1_distance * sin(bearing[0] * deg_to_rad); //L1_distance = target distance at first bearing\r\n    double b = L1_distance * cos(bearing[0] * deg_to_rad);\r\n\r\n    //target coordinate (x,y) at last bearing\r\n    double x = a + u * recording_time[_j];\r\n    double y = b + v * recording_time[_j];\r\n\r\n    out[0] = x;\r\n    out[1] = y;\r\n    out[2] = sqrt(pow(y - n[_j], 2) + pow(x - m[_j], 2));\r\n\r\n    return out;\r\n}\r\n\r\nvector<double> calculate_last_brg_noisy(const double &L1_distance, const double &spd, const double &crs)\r\n{\r\n    vector<double> out = vector<double>(3, 0.0);\r\n    double u = spd * sin(crs * deg_to_rad); //target speed component on x axis\r\n    double v = spd * cos(crs * deg_to_rad); //target speed component on y axis\r\n\r\n    //target coordinate (a,b) at first bearing\r\n    double a = L1_distance * sin(bearing_noisy[0] * deg_to_rad); //L1_distance = target distance at first bearing\r\n    double b = L1_distance * cos(bearing_noisy[0] * deg_to_rad);\r\n\r\n    //target coordinate (x,y) at last bearing\r\n    double x = a + u * recording_time[_j];\r\n    double y = b + v * recording_time[_j];\r\n\r\n    out[0] = x;\r\n    out[1] = y;\r\n    out[2] = sqrt(pow(y - n[_j], 2) + pow(x - m[_j], 2));\r\n\r\n    return out;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n    _setmode(_fileno(stdout), _O_U16TEXT); //support for chinese characters\r\n\r\n    double optimize_L1_distance;\r\n    double optimize_spd;\r\n    double optimize_current_distance;\r\n    double optimize_x;\r\n    double optimize_y;\r\n\r\n    //target function to minimize using BFGS algorithm\r\n    auto target_function = [](const column_vector& mStartingPoint)\r\n    {\r\n        const double L1_distance = mStartingPoint(0);\r\n        const double spd = mStartingPoint(1);\r\n        const double crs = mStartingPoint(2);\r\n\r\n        double u = spd * sin(crs * deg_to_rad);\r\n        double v = spd * cos(crs * deg_to_rad);\r\n        double a = L1_distance * sin(bearing[0] * deg_to_rad);\r\n        double b = L1_distance * cos(bearing[0] * deg_to_rad);\r\n\r\n        double total_error = 0.0;\r\n\r\n        for (unsigned int i = 0; i < _j + 1; i++)\r\n        {\r\n            double x = a + u * recording_time[i];\r\n            double y = b + v * recording_time[i];\r\n            double line_error = (y - n[i]) * sin(bearing[i] * deg_to_rad) - (x - m[i]) * cos(bearing[i] * deg_to_rad);\r\n            total_error += pow(line_error, 2);\r\n        }\r\n\r\n        //double penalty_for_spd = pow(limit(0.5 - spd, 0.0, 999999.0) * 100.0, 2) + pow(limit(spd - 6.0, 0.0, 999999.0) * 100.0, 2); //set speed limit: from 0.5 to 6.0 m/s\r\n        //double penalty_for_range = pow(limit(500 - L1_distance, 0.0, 999999.0) * 0.1, 2) + pow(limit(L1_distance - 10000.0, 0.0, 999999.0) * 0.1, 2); //set limit for target distance at t1: from 500m to 10km\r\n\r\n        return total_error;\r\n    };\r\n\r\n    auto target_function_noisy = [](const column_vector& mStartingPoint)\r\n    {\r\n        const double L1_distance = mStartingPoint(0);\r\n        const double spd = mStartingPoint(1);\r\n        const double crs = mStartingPoint(2);\r\n\r\n        double u = spd * sin(crs * deg_to_rad);\r\n        double v = spd * cos(crs * deg_to_rad);\r\n        double a = L1_distance * sin(bearing_noisy[0] * deg_to_rad);\r\n        double b = L1_distance * cos(bearing_noisy[0] * deg_to_rad);\r\n\r\n        double total_error = 0.0;\r\n\r\n        for (unsigned int i = 0; i < _j + 1; i++)\r\n        {\r\n            double x = a + u * recording_time[i];\r\n            double y = b + v * recording_time[i];\r\n            double line_error = (y - n[i]) * sin(bearing_noisy[i] * deg_to_rad) - (x - m[i]) * cos(bearing_noisy[i] * deg_to_rad);\r\n            total_error += pow(line_error, 2);\r\n        }\r\n        return total_error;\r\n    };\r\n\r\n#ifdef _CHINESE\r\n    std::wcout << L\"说明：本舰自上一次所在位置的移动方向 = 从上一个观测点指向当前位置的绝对方位，可在海图中对两个观测点连线获得。v0.3版本加入误差分布计算，对观测到的方位角施加-0.5到0.5度范围内的随机误差，并进行1000次循环计算误差分布概率。\" << endl;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"时间点time t1 = 0 (sec)\" << endl;\r\n\r\n    std::wcout << L\"本舰航向 (deg): \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"敌舰相对方位角 (deg): \";\r\n    std::cin >> bearing[0];\r\n    std::wcout << endl;\r\n    bearing[0] += own_ship_hdg;\r\n\r\n    std::wcout << L\"本舰自上一次所在位置的移动方向 = 0 (deg)\" << endl;\r\n    std::wcout << L\"本舰距上一次所在位置的直线距离 = 0 (meter)\" << endl;\r\n\r\n    std::wcout << L\"*******************************\" << endl;\r\n\r\n    std::wcout << L\"时间点time t2 (sec): \";\r\n    std::cin >> recording_time[1];\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"本舰航向 (deg): \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"敌舰相对方位角 (deg): \";\r\n    std::cin >> bearing[1];\r\n    std::wcout << endl;\r\n    bearing[1] += own_ship_hdg;\r\n\r\n    std::wcout << L\"本舰自上一次所在位置的移动方向 (deg): \";\r\n    std::cin >> last_travel_direction;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << L\"本舰距上一次所在位置的直线距离 (meter): \";\r\n    std::cin >> last_travel_distance;\r\n    std::wcout << endl;\r\n#else\r\n    std::wcout << \"time t1 = 0 (sec)\" << endl;\r\n\r\n    std::wcout << \"ownship heading at t1 (deg): \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << \"target relative bearing at t1 (deg): \";\r\n    std::cin >> bearing[0];\r\n    std::wcout << endl;\r\n    bearing[0] += own_ship_hdg;\r\n\r\n    std::wcout << \"true bearing from ownship last observation position to current position = 0 (deg)\" << endl;\r\n    std::wcout << \"straight distance from ownship last observation position to current position = 0 (meter)\" << endl;\r\n\r\n    std::wcout << \"*******************************\" << endl;\r\n\r\n    std::wcout << \"time t2 (sec): \";\r\n    std::cin >> recording_time[1];\r\n    std::wcout << endl;\r\n\r\n    std::wcout << \"ownship heading at t2: \";\r\n    std::cin >> own_ship_hdg;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << \"target relative bearing at t2 (deg): \";\r\n    std::cin >> bearing[1];\r\n    std::wcout << endl;\r\n    bearing[1] += own_ship_hdg;\r\n\r\n    std::wcout << \"true bearing from ownship last observation position to current position (deg): \";\r\n    std::cin >> last_travel_direction;\r\n    std::wcout << endl;\r\n\r\n    std::wcout << \"straight distance from ownship last observation position to current position (meter): \";\r\n    std::cin >> last_travel_distance;\r\n    std::wcout << endl;\r\n#endif\r\n\r\n    m[1] = last_travel_distance * sin(last_travel_direction * deg_to_rad);\r\n    n[1] = last_travel_distance * cos(last_travel_direction * deg_to_rad);\r\n\r\n    //start input iteration\r\n    for (unsigned int j = 2; j < 20; j++)\r\n    {\r\n        _j = j;\r\n\r\n#ifdef _CHINESE\r\n        std::wcout << L\"*******************************\" << endl;\r\n\r\n        std::wcout << L\"时间点time t\" << j + 1 << L\" (sec): \";\r\n        std::cin >> recording_time[j];\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"本舰航向 (deg): \";\r\n        std::cin >> own_ship_hdg;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"敌舰相对方位角 (deg): \";\r\n        std::cin >> bearing[j];\r\n        std::wcout << endl;\r\n        bearing[j] += own_ship_hdg;\r\n\r\n\r\n        std::wcout << L\"本舰自上一次所在位置的移动方向 (deg): \";\r\n        std::cin >> last_travel_direction;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << L\"本舰距上一次所在位置的直线距离 (meter): \";\r\n        std::cin >> last_travel_distance;\r\n        std::wcout << endl;\r\n#else\r\n        std::wcout << \"*******************************\" << endl;\r\n\r\n        std::wcout << \"time t\" << j + 1 << \" (sec): \";\r\n        std::cin >> recording_time[j];\r\n        std::wcout << endl;\r\n\r\n        std::wcout << \"ownship heading at t\" << j + 1 << \": \";\r\n        std::cin >> own_ship_hdg;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << \"target relative bearing at t\" << j + 1 << \" (deg): \";\r\n        std::cin >> bearing[j];\r\n        std::wcout << endl;\r\n        bearing[j] += own_ship_hdg;\r\n\r\n\r\n        std::wcout << \"true bearing from ownship last observation position to current position (deg): \";\r\n        std::cin >> last_travel_direction;\r\n        std::wcout << endl;\r\n\r\n        std::wcout << \"straight distance from ownship last observation position to current position (meter): \";\r\n        std::cin >> last_travel_distance;\r\n        std::wcout << endl;\r\n#endif\r\n\r\n        m[j] = m[j - 1] + last_travel_distance * sin(last_travel_direction * deg_to_rad);\r\n        n[j] = n[j - 1] + last_travel_distance * cos(last_travel_direction * deg_to_rad);\r\n\r\n        std::wcout << endl;\r\n        column_vector starting_point = { 1000.0,1.0,0.0 };\r\n        vector<double> optimal_crs;\r\n        \r\n        //multiple starting point for BFGS algorithm to find for multiple local minimal. (We need to keep all possible results for TMA)\r\n\r\n        for (double L1_distance = 1000.0; L1_distance <= 10000.0; L1_distance += 500.0)\r\n        {\r\n            for (double spd = 1.0; spd < 10.0; spd += 2.0)\r\n            {\r\n                for (double crs = 0.0; crs <= 360.0; crs += 60.0)\r\n                {\r\n                    starting_point = { L1_distance,spd,crs };\r\n\r\n                    dlib::find_min_using_approximate_derivatives(dlib::bfgs_search_strategy(), dlib::objective_delta_stop_strategy(1e-7), target_function, starting_point, -1);\r\n                    vector<double> last_brg = calculate_last_brg(starting_point(0), starting_point(1), starting_point(2));\r\n\r\n                    //adjust course result within 0-360 range\r\n                    while (starting_point(2) < 0)\r\n                    {\r\n                        starting_point(2) += 360;\r\n                    }\r\n\r\n                    while (starting_point(2) >= 360)\r\n                    {\r\n                        starting_point(2) -= 360;\r\n                    }\r\n\r\n                    starting_point(2) = round(starting_point(2) * 100.0) / 100.0;\r\n\r\n                    if (starting_point(0) > 1.0 && starting_point(1) > 0.0 && find(optimal_crs.begin(), optimal_crs.end(), starting_point(2)) == optimal_crs.end()) {\r\n                        optimal_crs.push_back(starting_point(2));\r\n                        optimize_L1_distance = starting_point(0);\r\n                        optimize_spd = starting_point(1);\r\n                        optimize_current_distance = last_brg[2];\r\n                        optimize_x = last_brg[0];\r\n                        optimize_y = last_brg[1];\r\n\r\n                        if (abs(m[j]) < 0.1 && abs(n[j]) < 0.1)\r\n                        {\r\n#ifdef _CHINESE\r\n                            std::wcout << L\"敌舰航向target true course: \" << starting_point(2) << L\"deg\" << endl;\r\n#else\r\n                            std::wcout << \"target true course: \" << starting_point(2) << \"deg\" << endl;\r\n#endif\r\n                        }\r\n                        else\r\n                        {\r\n#ifdef _CHINESE\r\n                            std::wcout << L\"敌舰航向target true course: \" << starting_point(2) << L\"deg, 速度speed: \" << optimize_spd * ms_to_kts << L\"knots, 距离distance: \" << optimize_current_distance << L\"m\" << endl;\r\n#else\r\n                            std::wcout << \"target true course: \" << starting_point(2) << \"deg, speed: \" << optimize_spd * ms_to_kts << \"knots, distance: \" << optimize_current_distance << \"m\" << endl;\r\n#endif\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        //error analysis\r\n        if (optimal_crs.size() > 0)\r\n        {\r\n            double last_opt_crs = optimal_crs[optimal_crs.size() - 1];\r\n            int total_error_count = 0;\r\n            int error_within_75m = 0;\r\n            int error_within_150m = 0;\r\n            int error_within_300m = 0;\r\n            int error_within_5deg = 0;\r\n            int error_within_10deg = 0;\r\n            int error_within_20deg = 0;\r\n            int error_within_05kts = 0;\r\n            int error_within_1kts = 0;\r\n            int error_within_2kts = 0;\r\n\r\n            for (double L1_distance = optimize_L1_distance; L1_distance <= optimize_L1_distance + 1.0; L1_distance += 0.1)\r\n            {\r\n                for (double spd = optimize_spd; spd <= optimize_spd + 0.1; spd += 0.01)\r\n                {\r\n                    for (double crs = last_opt_crs; crs <= last_opt_crs + 1.0; crs += 0.1)\r\n                    {\r\n                        starting_point = { L1_distance,spd,crs };\r\n\r\n                        for (unsigned int k = 0; k < _j + 1; k++)\r\n                        {\r\n                            bearing_noisy[k] = bearing[k] + (rand() % 11 - 5) / 10.0;\r\n                        }\r\n\r\n                        dlib::find_min_using_approximate_derivatives(dlib::bfgs_search_strategy(), dlib::objective_delta_stop_strategy(1e-7), target_function_noisy, starting_point, -1);\r\n                        vector<double> last_brg = calculate_last_brg_noisy(starting_point(0), starting_point(1), starting_point(2));\r\n\r\n                        //adjust course result within 0-360 range\r\n                        while (starting_point(2) < 0)\r\n                        {\r\n                            starting_point(2) += 360;\r\n                        }\r\n\r\n                        while (starting_point(2) >= 360)\r\n                        {\r\n                            starting_point(2) -= 360;\r\n                        }\r\n\r\n                        if (starting_point(0) > 1.0 && starting_point(1) > 0.0) {\r\n                            double last_x = last_brg[0];\r\n                            double last_y = last_brg[1];\r\n                            double distance_error = sqrt(pow(last_x - optimize_x, 2) + pow(last_y - optimize_y, 2));\r\n                            double course_error = min(abs(starting_point(2) - last_opt_crs), 360.0 - abs(starting_point(2) - last_opt_crs));\r\n                            double spd_error = abs(starting_point(1) - optimize_spd);\r\n                            if (distance_error < 75.0)\r\n                            {\r\n                                error_within_75m += 1;\r\n                            }\r\n                            \r\n                            if (distance_error < 150.0)\r\n                            {\r\n                                error_within_150m += 1;\r\n                            }\r\n                            \r\n                            if (distance_error < 300.0)\r\n                            {\r\n                                error_within_300m += 1;\r\n                            }\r\n\r\n                            if (course_error < 5.0)\r\n                            {\r\n                                error_within_5deg += 1;\r\n                            }\r\n\r\n                            if (course_error < 10.0)\r\n                            {\r\n                                error_within_10deg += 1;\r\n                            }\r\n\r\n                            if (course_error < 20.0)\r\n                            {\r\n                                error_within_20deg += 1;\r\n                            }\r\n\r\n                            if (spd_error < 0.5)\r\n                            {\r\n                                error_within_05kts += 1;\r\n                            }\r\n\r\n                            if (spd_error < 1.0)\r\n                            {\r\n                                error_within_1kts += 1;\r\n                            }\r\n\r\n                            if (spd_error < 2.0)\r\n                            {\r\n                                error_within_2kts += 1;\r\n                            }\r\n\r\n                            total_error_count += 1;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            double error_prob_75m = error_within_75m * 100.0 / total_error_count;\r\n            double error_prob_150m = error_within_150m * 100.0 / total_error_count;\r\n            double error_prob_300m = error_within_300m * 100.0 / total_error_count;\r\n            double error_prob_5deg = error_within_5deg * 100.0 / total_error_count;\r\n            double error_prob_10deg = error_within_10deg * 100.0 / total_error_count;\r\n            double error_prob_20deg = error_within_20deg * 100.0 / total_error_count;\r\n            double error_prob_05kts = error_within_05kts * 100.0 / total_error_count;\r\n            double error_prob_1kts = error_within_1kts * 100.0 / total_error_count;\r\n            double error_prob_2kts = error_within_2kts * 100.0 / total_error_count;\r\n            std::wcout << endl;\r\n\r\n#ifdef _CHINESE\r\n            std::wcout << L\"航向误差分布位于5度以内的概率probability of target course error within 5deg: \" << error_prob_5deg << \" %\" << endl;\r\n            std::wcout << L\"航向误差分布位于10度以内的概率probability of target course error within 10deg: \" << error_prob_10deg << \" %\" << endl;\r\n            std::wcout << L\"航向误差分布位于20度以内的概率probability of target course error within 20deg: \" << error_prob_20deg << \" %\" << endl;\r\n#else\r\n            std::wcout << \"probability of target course error within 5deg: \" << error_prob_5deg << \" %\" << endl;\r\n            std::wcout << \"probability of target course error within 10deg: \" << error_prob_10deg << \" %\" << endl;\r\n            std::wcout << \"probability of target course error within 20deg: \" << error_prob_20deg << \" %\" << endl;\r\n#endif\r\n            std::wcout << endl;\r\n            if (abs(m[j]) < 0.1 && abs(n[j]) < 0.1)\r\n            {\r\n                std::wcout << j + 1 << L\" bearings when stationary can only get course solution.\" << endl;\r\n            }\r\n            else\r\n            {\r\n#ifdef _CHINESE\r\n                std::wcout << L\"位置误差分布位于75米以内的概率probability of target positional error within 75m: \" << error_prob_75m << \" %\" << endl;\r\n                std::wcout << L\"位置误差分布位于150米以内的概率probability of target positional error within 150m: \" << error_prob_150m << \" %\" << endl;\r\n                std::wcout << L\"位置误差分布位于300米以内的概率probability of target positional error within 300m: \" << error_prob_300m << \" %\" << endl;\r\n                std::wcout << endl;\r\n                std::wcout << \"速度误差分布位于0.5节以内的概率probability of target speed error within 0.5kts: \" << error_prob_05kts << \" %\" << endl;\r\n                std::wcout << \"速度误差分布位于1节以内的概率probability of target speed error within 1kts: \" << error_prob_1kts << \" %\" << endl;\r\n                std::wcout << \"速度误差分布位于2节以内的概率probability of target speed error within 2kts: \" << error_prob_2kts << \" %\" << endl;\r\n#else\r\n                std::wcout << \"probability of target positional error within 75m: \" << error_prob_75m << \" %\" << endl;\r\n                std::wcout << \"probability of target positional error within 150m: \" << error_prob_150m << \" %\" << endl;\r\n                std::wcout << \"probability of target positional error within 300m: \" << error_prob_300m << \" %\" << endl;\r\n                std::wcout << endl;\r\n                std::wcout << \"probability of target speed error within 0.5kts: \" << error_prob_05kts << \" %\" << endl;\r\n                std::wcout << \"probability of target speed error within 1kts: \" << error_prob_1kts << \" %\" << endl;\r\n                std::wcout << \"probability of target speed error within 2kts: \" << error_prob_2kts << \" %\" << endl;\r\n#endif\r\n            }\r\n            std::wcout << endl;\r\n        }\r\n        else\r\n        {\r\n#ifdef _CHINESE\r\n            std::wcout << L\"无解！\" << endl;\r\n#else\r\n        std::wcout << L\"No solution found!\" << endl;\r\n#endif\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "4be21ea620f6da6be65e2a6fe31515da849e14ef", "size": 20848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TMA_calculator/TMA_calculator.cpp", "max_stars_repo_name": "LJQCN101/Auto-TMA-console", "max_stars_repo_head_hexsha": "a867a63041c970045fcc30e0967aa27ec1ab7440", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-04-02T19:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T23:44:18.000Z", "max_issues_repo_path": "TMA_calculator/TMA_calculator.cpp", "max_issues_repo_name": "LJQCN101/Auto-TMA-console", "max_issues_repo_head_hexsha": "a867a63041c970045fcc30e0967aa27ec1ab7440", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TMA_calculator/TMA_calculator.cpp", "max_forks_repo_name": "LJQCN101/Auto-TMA-console", "max_forks_repo_head_hexsha": "a867a63041c970045fcc30e0967aa27ec1ab7440", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-04-02T09:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T13:47:12.000Z", "avg_line_length": 40.7984344423, "max_line_length": 212, "alphanum_fraction": 0.521105142, "num_tokens": 5661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5886133495331444}}
{"text": "#include <iostream>\n#include <utility>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nusing boost::multiprecision::cpp_bin_float_single;\nusing boost::multiprecision::cpp_bin_float_double;\n\ntypedef boost::multiprecision::cpp_bin_float_single f32;\ntypedef boost::multiprecision::cpp_bin_float_double f64;\n\nint main(void)\n{\n#if BUGTEST_PRECISION == 32\n    //f32 pi32 = boost::math::constants::pi<f32, boost::math::policies::policy<boost::math::policies::digits2<32> > >();\n    f32 pi32 = boost::math::constants::pi<f32>();\n    std::cout << pi32 << std::endl;\n#elif BUGTEST_PRECISION == 64\n    //f64 pi64 = boost::math::constants::pi<f64, boost::math::policies::policy<boost::math::policies::digits2<64> > >();\n    f64 pi64 = boost::math::constants::pi<f64>();\n    std::cout << pi64 << std::endl;\n#else\n#error Set BUGTEST_PRECISION to 32 or 64.\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "a09875dcbea8c0e0dd4a52b60a87ad3c30c91713", "size": 915, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boost/bug.cc", "max_stars_repo_name": "jeffhammond/multiprecision", "max_stars_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T16:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:24:15.000Z", "max_issues_repo_path": "boost/bug.cc", "max_issues_repo_name": "jeffhammond/multiprecision", "max_issues_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/bug.cc", "max_forks_repo_name": "jeffhammond/multiprecision", "max_forks_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T23:27:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:27:36.000Z", "avg_line_length": 32.6785714286, "max_line_length": 120, "alphanum_fraction": 0.712568306, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.588453207089905}}
{"text": "\n/** @file spanning_trees.cc\n * @author David F. Gleich\n * @date 2008-09-29\n * @copyright Stanford University, 2006-2008\n * Implement the BGL spanning tree wrappers.\n */\n\n/** History\n *  2006-04-20: Initial version\n *  2006-11-10: Fixed bug with incorrect number of edges returned,\n *    when the input graph has multiple components.\n *    The nedges output parameter is now set correctly for all algorithms.\n *    Although, it depends on a somewhat dubious \"hack\" to detect\n *    unused portions of the output iterator.\n *  2007-07-09: Switched to simple_csr_matrix graph type\n *    Switched to kruskal mst from boost mod to fix bug with output iterator\n *  2007-11-16: Added root vertex option to prim's MST\n *  2008-10-01: Changed copy_to_ijval to use mbglIndex instead of int.\n *    Removed old commented regions.\n */\n\n#include \"include/matlab_bgl.h\"\n\n#include <yasmic/simple_csr_matrix_as_graph.hpp>\n#include <yasmic/iterator_utility.hpp>\n\n#include <yasmic/boost_mod/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\n#include <vector>\n\n/*template <class Graph, class Edge>\nclass spanning_tree_insert_iterator\n    : public boost::iterator_facade<\n        spanning_tree_insert_iterator<Edge>\n      , Edge\n      , boost::forward_traversal_tag\n    >\n{\npublic:\n    int* i; int* j; double* val;\n    Graph& g;\n\n    spanning_tree_insert_iterator(int* _i, int* _j, double* _val)\n        : i(_i), j(_j), val(_val)\n    {}\n\nprivate:\n    friend class boost::iterator_core_access;\n\n    void increment()\n    {\n        i++;\n        j++;\n        val++;\n    }\n\n    bool equal(spanning_tree_insert_iterator const& other)\n    {\n        return (i == other.i && j == other.j && val == other.val);\n    }\n\n    Edge\n\n\n};*/\n\ntemplate <class Graph, class EdgeWeightPropMap, class Iterator>\nmbglIndex copy_to_ijval(Graph& g, EdgeWeightPropMap ewpm, Iterator oi,\n                   Iterator oi_end, mbglIndex* i, mbglIndex* j, double* val)\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        val[ei] = ewpm[e];\n    }\n\n    return (ei);\n}\n\nint kruskal_mst(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex* i, mbglIndex* j, double* val /* tree output */,\n    mbglIndex* nedges)\n{\n    using namespace yasmic;\n    using namespace boost;\n\n    // create the graph g\n    typedef simple_csr_matrix<mbglIndex,double> crs_weighted_graph;\n    crs_weighted_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n    //\n    // warning, this code assumes that the default constructor for\n    // an edges has source == target, otherwise we will detect\n    // incorrect edges in the next step.\n    //\n    std::vector<graph_traits<crs_weighted_graph>::edge_descriptor>\n        oi(nverts-1);\n\n    std::vector<graph_traits<crs_weighted_graph>::edge_descriptor>::iterator\n        oi_end = kruskal_minimum_spanning_tree(g,oi.begin());\n\n\n    //*nedges = nverts-1;\n    //*nedges = (int)(oi_end - oi.begin());\n\n    // warning, this code assumes that the default constructor for\n    // an edges has source == target, otherwise we will detect\n    // incorrect edges in the next step.\n    *nedges = copy_to_ijval(g,get(edge_weight,g),\n        oi.begin(), oi_end, i, j, val);\n\n    return (0);\n}\n\nint prim_mst_rooted(mbglIndex nverts, mbglIndex *ja, mbglIndex *ia,\n    double *weight, /* connectivity params */\n    mbglIndex* i, mbglIndex* j, double* val, mbglIndex *nedges, /* tree output */\n    mbglIndex root /* tree root */)\n{\n  using namespace yasmic;\n  using namespace boost;\n\n  typedef simple_csr_matrix<mbglIndex, double> crs_weighted_graph;\n  crs_weighted_graph g(nverts, nverts, ia[nverts], ia, ja, weight);\n\n  std::vector<mbglIndex> pred(nverts);\n\n  prim_minimum_spanning_tree(g, make_iterator_property_map(pred.begin(), get(\n      vertex_index, g)), root_vertex(root));\n\n  mbglIndex edge_num = 0;\n  for (mbglIndex pi = 0; pi < nverts; pi++) {\n    if (pred[pi] == pi) {\n      // this edge isn't present\n    } else {\n      assert(edge_num<nverts-1);\n\n      i[edge_num] = pi;\n      j[edge_num] = pred[pi];\n      val[edge_num] = 0.0;\n\n      for (mbglIndex k = ia[pred[pi]]; k < ia[pred[pi] + 1]; k++) {\n        if (ja[k] == pi) {\n          val[edge_num] = weight[k];\n          break;\n        }\n      }\n\n      edge_num++;\n    }\n  }\n\n  *nedges = edge_num;\n\n  return (0);\n}\n\n/**\n * Compute a minimum spanning tree starting from vertex 0 using Prim's algorithm\n */\nint prim_mst(\n    mbglIndex nverts, mbglIndex *ja, mbglIndex *ia, double *weight, /* connectivity params */\n    mbglIndex* i, mbglIndex* j, double* val, mbglIndex *nedges /* tree output */)\n{\n    // for our graph type, calling for a rooted tree with root 0 is identical\n    // to calling for the default root.\n    return prim_mst_rooted(nverts, ja, ia, weight, i, j, val, nedges, 0);\n}\n\n", "meta": {"hexsha": "04b61d4a76aad9cdc9c75697778849b0129cf74d", "size": 4966, "ext": "cc", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/spanning_trees.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/spanning_trees.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/spanning_trees.cc", "max_forks_repo_name": "anajmedd/ENSEEIHT-Projects", "max_forks_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 28.0564971751, "max_line_length": 93, "alphanum_fraction": 0.6550543697, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5883899077311142}}
{"text": "/**\n * This file contains functions for solving stochastic optimization problems provided the user extends the\n * \"Parameters\" class to update the model underlying the parameters and provides both an objective function and a\n * Jacobian thereof that conforms to the expected format for the optimization algorithm.\n */\n\n#ifndef PROMETHEUS_OPTIMIZATION_HPP\n#define PROMETHEUS_OPTIMIZATION_HPP\n\n#include <Eigen/Dense>\n#include \"stopwatch.hpp\"\n\n// zach's-attempt-at-math\nnamespace zaamath {\n\n    /**\n     * template class responsible for maintaining the parameters used during optimization and updating the parameters\n     * (and optionally the underlying model of those parameters) once an updated set of parameters are passed in by the\n     * optimization algorithm\n     * @tparam RowIndexType the number of rows of the parameter vector (number of parameters)\n     */\n    template <int RowIndexType>\n    class Parameters {\n    protected:\n        Eigen::Matrix<double, RowIndexType, 1> eigen_params_;\n\n    public:\n        Parameters(Eigen::Matrix<double, RowIndexType, 1>& eigen_params) : eigen_params_(eigen_params) {\n\n        }\n\n        virtual ~Parameters() = default;\n\n        virtual void update(Eigen::Matrix<double, RowIndexType, 1>& eigen_params) {\n            eigen_params_ = eigen_params;\n        }\n\n        Eigen::Matrix<double, RowIndexType, 1> eigen_params() {\n            return eigen_params_;\n        }\n    };\n\n    /**\n     * This class implements the stochastic gradient descent optimization algorithm known as ADAM (short for Adaptive\n     * Moment Estimation) as well as holds meta-data for the algorithm such as termination conditions and\n     * hyper-parameters.\n     *\n     * The class performs inplace optimization, updating the Parameters object passed in by reference by the user every\n     * iteration. Additional the class stores member variables about the status of the algorithm at each iteration,\n     * which can be read by the client to discover things about the covergence of the algorthim. Therefore, if one seeks\n     * to perform more than one optimization with the same Adam instance, one must first reset those member variables\n     * with the\n     */\n    class Adam {\n    private:\n        bool show_trace_{true};\n        int show_trace_every_{15};\n        int f_x_tol_interval_{20};\n        double f_x_tol_{1e-10};\n        int x_tol_interval_{20};\n        double x_tol_{1e-12};\n        int max_iterations_{10000};\n        double alpha_{0.01}; // learning rate / step size\n        std::size_t batch_size_{1}; // not sure how to implement\n        double beta1_{0.9};\n        double beta2_{0.999};\n        double epsilon_{1e-8};\n        Eigen::Matrix<double, Eigen::Dynamic, 1> f_x_prev_; // don't initialize to any size yet\n        Eigen::Matrix<double, Eigen::Dynamic, 1> times_;\n\n        /**\n         * implements the termination conditions for the loop in the optimization algorithm, returning true if the\n         * process as converged or run out of iterations and false otherwise\n         * @tparam RealRowIndexType the number of columns in the parameter vector\n         * @param f_x_prev a running series of past error of all the previous iteration of the algorithm\n         * @param x_prev the previous \"x_tol_interval_\" parameter values\n         * @param iterations the iteration number that we are currently on\n         * @return true if we have reached any termination criterion, false otherwise\n         */\n        template <int RealRowIndexType>\n        bool reached_termination(Eigen::Matrix<double, Eigen::Dynamic, 1>& f_x_prev, Eigen::Matrix<double, Eigen::Dynamic, RealRowIndexType>& x_prev, int iterations) {\n            if (iterations >= max_iterations_) {\n                std::cout << \"Quitting b/c reached max iterations\" << std::endl;\n                return true;\n            }\n\n            if (iterations >= f_x_tol_interval_) {\n                Eigen::Matrix<double, Eigen::Dynamic, 1> last_n_items = f_x_prev(Eigen::lastN(f_x_tol_interval_));\n                if ((zaamath::range(last_n_items).cwiseAbs().array() < f_x_tol_).all()) {\n                    std::cout << \"Quitting b/c Error Converged\" << std::endl;\n                    std::cout << \" - Range: \" << zaamath::range(last_n_items).cwiseAbs().array() << \" < \" << f_x_tol_ << std::endl;\n                    return true;\n                }\n            }\n\n            if (iterations >= x_tol_interval_) {\n                if ((zaamath::range(x_prev).cwiseAbs().array() < x_tol_).all()) {\n                    std::cout << \"Quitting b/c Parameters Converged\" << std::endl;\n                    std::cout << \" - Range: \" << zaamath::range(x_prev).cwiseAbs().array() << \" < \" << x_tol_ << std::endl;\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n    public:\n\n        /**\n         * clears the member variables having to do with the performance of the optimization at each iteration so that\n         * the object may be used again for another optimization.\n         */\n        void clear() {\n//            f_x_prev_ = Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero();\n            f_x_prev_.resize(0);\n//            times_ = Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero();\n            times_.resize(0);\n        }\n\n        /**\n         * implements the vanilla Adam optimization algorithm\n         * @tparam RowIndexType the number of parameters (the number of rows of the input parameter vector)\n         * @param initial_params the initial parameter set\n         * @param obj_func the objective function\n         * @param jacobian the jacobian of the objective function w.r.t. the parameters\n         */\n        template <int RowIndexType>\n        void optimize(Parameters<RowIndexType>& initial_params, std::function<double(Parameters<RowIndexType>&)>& obj_func, std::function<Eigen::Matrix<double, RowIndexType, 1>(Parameters<RowIndexType>&, int)>& jacobian) {\n\n            // initialize to zero\n            Eigen::Matrix<double, RowIndexType, 1> mt = Eigen::Matrix<double, RowIndexType, 1>::Zero();\n            Eigen::Matrix<double, RowIndexType, 1> vt = Eigen::Matrix<double, RowIndexType, 1>::Zero();\n            Eigen::Matrix<double, RowIndexType, 1> mthat = Eigen::Matrix<double, RowIndexType, 1>::Zero();\n            Eigen::Matrix<double, RowIndexType, 1> vthat = Eigen::Matrix<double, RowIndexType, 1>::Zero();\n\n            // Grab the last 'x_tol_interval' inputs\n            Eigen::Matrix<double, Eigen::Dynamic, RowIndexType> x_prev = Eigen::Matrix<double, Eigen::Dynamic, RowIndexType>::Zero(x_tol_interval_, RowIndexType);\n            x_prev.row(0) = initial_params.eigen_params();\n\n            // track number of iterations\n            int iterations{0};\n\n            // trace table headers\n            std::size_t header_widths[4] = {\n                std::string(\" Iteration \").size()-1,\n                std::string(\"    Time    \").size()-std::string(\" [us] \").size(),\n                std::string(\"   Error   \").size()-1,\n                std::string(\" Min. Error \").size()-1\n            };\n\n            // Grab the stopwatch\n            StopWatch stop_watch;\n\n            while (!reached_termination(f_x_prev_, x_prev, iterations)) {\n                stop_watch.start();\n                Eigen::Matrix<double, RowIndexType, 1> grad = jacobian(initial_params, iterations);\n                std::size_t batch{1};\n                while (batch < batch_size_) {\n                    grad += jacobian(initial_params, iterations + batch);\n                    ++batch;\n                }\n\n                // update mt and vt\n                mt = beta1_ * mt + (1 - beta1_) * grad;\n                vt = beta2_ * vt + (1 - beta2_) * grad.array().square().matrix();\n\n                // update mthat and vthat\n                mthat = mt * 1 / (1 + std::pow(beta1_, iterations + 1));\n                vthat = vt * 1 / (1 + std::pow(beta2_, iterations + 1));\n\n                // update theta\n                Eigen::Matrix<double, RowIndexType, 1> new_engine_params = initial_params.eigen_params() - (alpha_ * mthat.array() * (vthat.array().sqrt() + epsilon_).inverse()).matrix();\n                initial_params.update(new_engine_params);\n\n                stop_watch.stop();\n                times_.conservativeResize(times_.rows()+1, Eigen::NoChange);\n                times_(times_.rows()-1) = stop_watch.duration() * 1e-3;\n\n                f_x_prev_.conservativeResize(f_x_prev_.rows()+1, Eigen::NoChange);\n                f_x_prev_(f_x_prev_.rows()-1) = obj_func(initial_params);\n\n                if (show_trace_) {\n                    if (iterations == 0) {\n                        std::cout << \"| Iteration |    Time    |   Error   | Min. Error |\" <<  std::endl;\n                        std::cout << \"+-----------+------------+-----------+------------+\" << std::endl;\n                        std::cout << \"|\";\n                        std::cout << std::setw(header_widths[0]) << (iterations+1) << \" \";\n                        std::cout << \"|\";\n                        double duration = times_(0);\n                        std::cout << std::setw(header_widths[1]) << std::setprecision(4) << duration << \" [us] \";\n                        std::cout << \"|\";\n                        double error = f_x_prev_(0);\n                        std::cout << std::setw(header_widths[2]) << std::setprecision(4) << error << \" \";\n                        std::cout << \"|\";\n                        std::cout << std::setw(header_widths[3]) << std::setprecision(4) << error << \" \";\n                        std::cout << \"|\" << std::endl;\n                    } else if ((iterations + 1) % show_trace_every_ == 0) {\n                        std::cout << \"|\";\n                        std::cout << std::setw(header_widths[0]) << (iterations+1) << \" \";\n                        std::cout << \"|\";\n                        double duration = times_.middleRows(iterations+1-show_trace_every_+1, show_trace_every_-1).sum();\n                        std::cout << std::setw(header_widths[1]) << std::setprecision(4) << duration << \" [us] \";\n                        std::cout << \"|\";\n                        double error = f_x_prev_(f_x_prev_.rows()-1);\n                        std::cout << std::setw(header_widths[2]) << std::setprecision(4) << error << \" \";\n                        std::cout << \"|\";\n                        double min_error = f_x_prev_.minCoeff();\n                        std::cout << std::setw(header_widths[3]) << std::setprecision(4) << min_error << \" \";\n                        std::cout << \"|\" << std::endl;\n                    }\n                }\n                ++iterations;\n            }\n        }\n\n        Eigen::Matrix<double, Eigen::Dynamic, 1> f_x_prev() {\n            return f_x_prev_;\n        }\n\n        Eigen::Matrix<double, Eigen::Dynamic, 1> times() {\n            return times_;\n        }\n    };\n\n};\n\n#endif //PROMETHEUS_OPTIMIZATION_HPP\n", "meta": {"hexsha": "bea0d3de86b2a49303c3d812699e048a63ab8ae8", "size": 10895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tools/math/optimization.hpp", "max_stars_repo_name": "zborffs/AsterionEngine", "max_stars_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-29T10:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-29T10:39:56.000Z", "max_issues_repo_path": "tools/math/optimization.hpp", "max_issues_repo_name": "zborffs/AsterionEngine", "max_issues_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T06:44:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T06:47:56.000Z", "max_forks_repo_path": "tools/math/optimization.hpp", "max_forks_repo_name": "zborffs/AsterionEngine", "max_forks_repo_head_hexsha": "029624cba19cd7fbc407bb24b9beb33efd089c5b", "max_forks_repo_licenses": ["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.7850877193, "max_line_length": 222, "alphanum_fraction": 0.5642955484, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403176, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5883899066609539}}
{"text": "/**\n * @file gausslobattoparabolic.cc\n * @brief NPDE exam TEMPLATE CODE FILE\n * @author Oliver Rietmann\n * @date 22.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"gausslobattoparabolic.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n#include <functional>\n#include <memory>\n#include <utility>\n\nnamespace GaussLobattoParabolic {\n\n/* SAM_LISTING_BEGIN_1 */\nlf::assemble::COOMatrix<double> initMbig(\n    std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space) {\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n#if SOLUTION\n  // Diffusion coefficient =0, reaction coefficient = 1\n  lf::mesh::utils::MeshFunctionConstant alpha(0.0), gamma(1.0);\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider entity_matrix_provider(\n      fe_space, alpha, gamma);\n  // Compute mass matrix for full finite element space\n  lf::assemble::COOMatrix<double> M =\n      lf::assemble::AssembleMatrixLocally<lf::assemble::COOMatrix<double>,\n                                          decltype(entity_matrix_provider)>(\n          0, dofh, entity_matrix_provider);\n  // Find mesh nodes on the boundary\n  const lf::mesh::utils::CodimMeshDataSet<bool> bd_flags =\n      lf::mesh::utils::flagEntitiesOnBoundary(fe_space->Mesh(), 2);\n  // Predicate for selecting matrix rows induced by test functions associated\n  // with nodes on the boundary\n  auto pred = [&bd_flags, &dofh](int i, int j) {\n    return bd_flags(dofh.Entity(i));\n  };\n  // Set the corresponding triplets to zero using LehrFEM++ helper function\n  M.setZero(pred);\n#else\n  //====================\n  // Your code goes here\n  // Replace this dummy assignment for M:\n  int N = dofh.NumDofs();\n  lf::assemble::COOMatrix<double> M(N, N);\n  //====================\n#endif\n\n  return M;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nlf::assemble::COOMatrix<double> initAbig(\n    std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space) {\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n#if SOLUTION\n  // Diffusion coefficient =1, reaction coefficient = 0\n  lf::mesh::utils::MeshFunctionConstant alpha(1.0), gamma(0.0);\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider entity_matrix_provider(\n      fe_space, alpha, gamma);\n  // Compute Galerkin matrix for -Laplacian on full FE space\n  lf::assemble::COOMatrix<double> A =\n      lf::assemble::AssembleMatrixLocally<lf::assemble::COOMatrix<double>,\n                                          decltype(entity_matrix_provider)>(\n          0, dofh, entity_matrix_provider);\n  // Find mesh nodes on the boundary\n  const lf::mesh::utils::CodimMeshDataSet<bool> bd_flags =\n      lf::mesh::utils::flagEntitiesOnBoundary(fe_space->Mesh(), 2);\n  // Predicate for selecting matrix rows induced by test functions associated\n  // with nodes on the boundary\n  auto pred = [&bd_flags, &dofh](int i, int j) {\n    return bd_flags(dofh.Entity(i));\n  };\n  // Set the corresponding triplets to zero using LehrFEM++ helper function\n  A.setZero(pred);\n  // Set \"boundary block\" to the identity matrix\n  for (int i = 0; i < dofh.NumDofs(); ++i) {\n    if (bd_flags(dofh.Entity(i))) A.AddToEntry(i, i, 1.0);\n  }\n#else\n  //====================\n  // Your code goes here\n  // Replace this dummy assignment for A:\n  int N = dofh.NumDofs();\n  lf::assemble::COOMatrix<double> A(N, N);\n  //====================\n#endif\n\n  return A;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nRHSProvider::RHSProvider(const lf::assemble::DofHandler &dofh,\n                         std::function<double(double)> g)\n    : g_(std::move(g)) {\n#if SOLUTION\n  // Finde nodes on the boundary\n  const lf::mesh::utils::CodimMeshDataSet<bool> bd_flags =\n      lf::mesh::utils::flagEntitiesOnBoundary(dofh.Mesh(), 2);\n  int N = dofh.NumDofs();\n  // Initialize the fixed vector, components for degrees of freedom associated\n  // with nodes on the boundary are set to 1, all other to 0\n  zero_one_ = Eigen::VectorXd(N);\n  for (int i = 0; i < N; ++i) {\n    zero_one_(i) = bd_flags(dofh.Entity(i)) ? 1.0 : 0.0;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n}\n\nEigen::VectorXd RHSProvider::operator()(double t) const {\n#if SOLUTION\n  // Just rescale the stored vector\n  return g_(t) * zero_one_;\n#else\n  //====================\n  // Your code goes here\n  // Replace this dummy return value:\n  return Eigen::VectorXd(0);\n  //====================\n#endif\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace GaussLobattoParabolic\n", "meta": {"hexsha": "a157ecfcdf94ea18008065aa6e8c0c351edb1da0", "size": 4575, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/GaussLobattoParabolic/mastersolution/gausslobattoparabolic.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/GaussLobattoParabolic/mastersolution/gausslobattoparabolic.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/GaussLobattoParabolic/mastersolution/gausslobattoparabolic.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 33.152173913, "max_line_length": 78, "alphanum_fraction": 0.6594535519, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5883899031220813}}
{"text": "#include <cstdlib>\n#include <iostream>\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/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/blas/level1.hpp>\n#include <boost/numeric/bindings/blas/level2.hpp>\n#include <boost/numeric/bindings/upper.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 typename vector::size_type size_type;\n\n  rand_normal<double>::reset();\n  size_type n=128;\n  matrix A(n, n);\n  for (size_type j=0; j<n; ++j) {\n    for (size_type i=0; i<=j; ++i) {\n      A(i, j)=rand_normal<double>::get();\n      A(j, i)=A(i, j);\n    }\n  }\n  {\n    vector lambda(n);\n    matrix A_bak(A);\n    int info=lapack::syev('V', lapack::upper(A), lambda);\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(A, i);\n\tvector res(v);\n\tblas::gemv(1., A_bak, v, -lambda(i), res);\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": "f8872dddea532051716b01e277afae05b7fd9fed", "size": 1649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/syev.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/syev.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/syev.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": 30.537037037, "max_line_length": 60, "alphanum_fraction": 0.662219527, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5883855696483284}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOG_SUM_EXP_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOG_SUM_EXP_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/log1p_exp.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Calculates the log sum of exponetials without overflow.\n *\n * \\f$\\log (\\exp(a) + \\exp(b)) = m + \\log(\\exp(a-m) + \\exp(b-m))\\f$,\n *\n * where \\f$m = max(a, b)\\f$.\n *\n *\n   \\f[\n   \\mbox{log\\_sum\\_exp}(x, y) =\n   \\begin{cases}\n     \\ln(\\exp(x)+\\exp(y)) & \\mbox{if } -\\infty\\leq x, y \\leq \\infty \\\\[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{log\\_sum\\_exp}(x, y)}{\\partial x} =\n   \\begin{cases}\n     \\frac{\\exp(x)}{\\exp(x)+\\exp(y)} & \\mbox{if } -\\infty\\leq x, y \\leq \\infty\n \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{log\\_sum\\_exp}(x, y)}{\\partial y} =\n   \\begin{cases}\n     \\frac{\\exp(y)}{\\exp(x)+\\exp(y)} & \\mbox{if } -\\infty\\leq x, y \\leq \\infty\n \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n *\n * @param a the first variable\n * @param b the second variable\n */\ntemplate <typename T1, typename T2>\ninline return_type_t<T1, T2> log_sum_exp(const T2& a, const T1& b) {\n  if (a == NEGATIVE_INFTY)\n    return b;\n  if (a == INFTY && b == INFTY)\n    return INFTY;\n  if (a > b)\n    return a + log1p_exp(b - a);\n  return b + log1p_exp(a - b);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "29b8335f8dfe3d22f76286794c070c4cc7593479", "size": 1623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/fun/log_sum_exp.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/scal/fun/log_sum_exp.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/scal/fun/log_sum_exp.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": 26.1774193548, "max_line_length": 78, "alphanum_fraction": 0.5939617991, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5883855641413718}}
{"text": "#ifndef TVMTL_MANIFOLD_SPHERE_HPP\n#define TVMTL_MANIFOLD_SPHERE_HPP\n\n#include <cmath>\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"enumerators.hpp\"\n\nnamespace tvmtl {\n\n// Specialization SPHERE\ntemplate < int N>\nstruct Manifold< SPHERE, N> {\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\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, 1>\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, N-1> 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, N>     deriv2_type;\n\ttypedef deriv2_type&\t\t\t     deriv2_ref_type;\n\ttypedef\tEigen::Matrix<scalar_type, N-1, N-1> restricted_deriv2_type;\n\n\n\t// Manifold distance functions (for IRLS)\n\tinline static dist_type dist_squared(cref_type x, cref_type y);\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\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\n\t// Projection\n\tinline static void projector(ref_type x);\n\t\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 SPHERE----------*/\n\n// Static constants, Outside definition to avoid linker error\n\ntemplate <int N>\nconst MANIFOLD_TYPE Manifold < SPHERE, N>::MyType = SPHERE; \n\ntemplate <int N>\nconst int Manifold < SPHERE, N>::manifold_dim = N-1; \n\ntemplate <int N>\nconst int Manifold < SPHERE, N>::value_dim = N; \n\ntemplate <int N>\nconst bool Manifold < SPHERE, N>::non_isometric_embedding = false; \n\n\n// Squared Sphere distance function\ntemplate <int N>\ninline typename Manifold < SPHERE, N>::dist_type Manifold < SPHERE, N>::dist_squared( cref_type x, cref_type y ){\n    scalar_type xdoty = x.dot(y);\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >  1.0) xdoty = 1.0;\n    dist_type d = std::acos(xdoty);\n    #ifdef TVMTL_MANIFOLD_DEBUG\n\t    if(!std::isfinite(d)){\n\t    std::cout << \"\\nDX Non-Series: \" << std::endl;\n\t    std::cout << \"x \"<< x  << std::endl;\n\t    std::cout << \"y \"<< y << std::endl;\n\t    std::cout << \"x^Ty \"<< x.dot(y) << std::endl;\n\t    std::cout << \"xdoty \"<< xdoty << std::endl;\n\t    std::cout << \"result\" << d << std::endl;\n\t    }\n\t#endif\n    return d*d;\n}\n\n\n// Derivative of Squared Sphere distance w.r.t. first argument\n// TODO: Extende implementation of series to 1.0-eps\ntemplate <int N>\ninline void Manifold < SPHERE, N>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >= 1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type acos = std::acos(xdoty);\n\tresult =  -2.0 * acos / std::sqrt(1.0 - xdoty * xdoty) * y;\n\t#ifdef TVMTL_MANIFOLD_DEBUG\n\t    if(!std::isfinite(result(0))){\n\t    std::cout << \"\\nDX Non-Series: \" << std::endl;\n\t    std::cout << \"x \"<< x  << std::endl;\n\t    std::cout << \"y \"<< y << std::endl;\n\t    std::cout << \"x^Ty \"<< x.dot(y) << std::endl;\n\t    std::cout << \"xdoty \"<< xdoty << std::endl;\n\t    std::cout << \"acos(x) \" << acos << std::endl;\n\t    std::cout << \"sqrt(1-x^2)\" << std::sqrt(1.0 - xdoty * xdoty) << std::endl;\n\t    std::cout << \"result\" << result << std::endl;\n\t    }\n\t#endif\n    }\n    else{\n\tresult = -2.0 * y;\n\t#ifdef TVMTL_MANIFOLD_DEBUG\n\t    if(!std::isfinite(result(0)))\n\t\tstd::cout << \"DX Series:\" << result << std::endl;\n\t#endif\n    }\n}\n// Derivative of Squared Sphere distance w.r.t. second argument\ntemplate <int N>\ninline void Manifold < SPHERE, N>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >=  1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type acos = std::acos(xdoty);\n\tresult =  -2.0 * acos / std::sqrt(1.0 - xdoty * xdoty) * x;\n    }\n    else\n\tresult = -2.0 * x;\n}\n\n\n\n\n// Second Derivative of Squared Sphere distance w.r.t first argument\ntemplate <int N>\ninline void Manifold < SPHERE, N>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >=  1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type onemx2 = 1.0 - xdoty * xdoty;\n\tscalar_type acos = std::acos(xdoty);\n\tscalar_type da =  -2.0 * acos / std::sqrt(onemx2);\n\tresult = (2.0 + da * xdoty) / onemx2 * y * y.transpose() - da * xdoty * deriv2_type::Identity();\n    }\n    else\n\tresult = 2.0/3.0 * y * y.transpose() + 2.0 * xdoty * deriv2_type::Identity();\n\n}\n// Second Derivative of Squared Sphere distance w.r.t first and second argument\ntemplate <int N>\ninline void Manifold < SPHERE, N>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >=  1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type onemx2 = 1.0 - xdoty * xdoty;\n\tscalar_type acos = std::acos(xdoty);\n\tscalar_type da =  -2.0 * acos / std::sqrt(onemx2);\n\tresult = (2.0 + da * xdoty) / onemx2 * y * x.transpose() + da * deriv2_type::Identity(); \n    }\n    else\n\tresult = 2.0/3.0 * y * x.transpose() - 2.0 * deriv2_type::Identity();\n}\n// Second Derivative of Squared Sphere distance w.r.t second argument\ntemplate <int N>\ninline void Manifold < SPHERE, N>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >=  1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type onemx2 = 1.0 - xdoty * xdoty;\n\tscalar_type acos = std::acos(xdoty);\n\tscalar_type da =  -2.0 * acos / std::sqrt(onemx2);\n\tresult = (2.0 + da * xdoty) / onemx2 * x * x.transpose() - da * xdoty * deriv2_type::Identity();\n\n    }\n    else\n\tresult = 2.0/3.0 * x * x.transpose() + 2.0 * xdoty * deriv2_type::Identity();\n\n}\n\n\n\n// Exponential and Logarithm Map\ntemplate <int N>\ntemplate <typename DerivedX, typename DerivedY>\ninline void Manifold <SPHERE, N>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result){\n    //result=(x+y).normalized();\n    scalar_type n = y.norm();\n    if(n!=0)\n\tresult = std::cos(n) * x + std::sin(n) * y / n;\n    else\n\tresult = x;\n}\n\ntemplate <int N>\ninline void Manifold <SPHERE, N>::log(cref_type x, cref_type y, ref_type result){\n    //result = (y-x).normalized();\n    scalar_type xdoty = x.dot(y);\n    bool useSeries = false;\n\n    if (xdoty < - 1.0) xdoty = -1.0;\n    if (xdoty >=  1.0) { xdoty = 1.0; useSeries = true; }\n    \n    if(!useSeries){\n\tscalar_type fac = std::acos(xdoty) / std::sqrt(1.0 - xdoty * xdoty);\n\tresult = fac * (y - xdoty * x);\n    }\n    else\n\tresult =  y - xdoty * x;\n}\n\n// Tangent Plane restriction\n// TODO: Implement general QR Composition here\ntemplate <int N>\ninline void Manifold <SPHERE, N>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    result = tm_base_type::Identity();\n}\n\ntemplate <> // Special Version for S^2 utilizing the cross product\ninline void Manifold <SPHERE, 3>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    //int c = static_cast<int>(std::abs(x.coeff(0)) > 0.5);\n    int c = static_cast<int>(std::abs(x.coeff(2)) > 0.5 || std::abs(x.coeff(1)) > 0.5);\n    result.col(0) = value_type(0, x.coeff(2), -x.coeff(1)) * c + value_type(x.coeff(2), 0, -x.coeff(0)) * (1-c);\n    result.col(0).normalize();\n    result.col(1) = x.cross(result.col(0)).normalized();\n\n    if(x.norm()==0)\n\tresult = tm_base_type::Zero();\n\n    #ifdef TVMTL_MANIFOLD_DEBUG\n\t    if(!std::isfinite(result(0,0))){\n\t    std::cout << \"\\n\\nx \"<< x  << std::endl;\n\t    std::cout << \"col0 V1 \"<<  value_type(0, x.coeff(2), -x.coeff(1)) << std::endl;\n\t    std::cout << \"col0 V2 \"<<  value_type(x.coeff(2), 0, -x.coeff(0)) << std::endl;\n\t    std::cout << \"col0 norm \" << result.col(0) << std::endl;\n\t    std::cout << \"cross prod\" << x.cross(result.col(0)) << std::endl;\n\t    std::cout << \"cross prod norm\" << result.col(1) << std::endl;\n\t    }\n    #endif\n}\n\n// Convex geodesic combinations\ntemplate <int N>\ninline void Manifold <SPHERE, N>::convex_combination(cref_type x, cref_type y, double t, ref_type result){\n   if(t == 0.5){\n\tresult = x + y;\n\tprojector(result);\n   }\n   else{\n\tvalue_type l;\n\tlog(x, y, l);\n\texp(x, l * t, result);\n   }\n}\n\n// Karcher mean implementations\ntemplate <int N>\ninline void Manifold<SPHERE, N>::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>\ninline void Manifold<SPHERE, N>::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>\ntemplate <typename V, class... Args>\ninline void Manifold<SPHERE, N>::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>\ntemplate <typename V>\ninline void Manifold<SPHERE, N>::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>\ntemplate <typename V, class... Args>\ninline void Manifold<SPHERE, N>::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\ntemplate <int N>\ninline void Manifold <SPHERE, N>::projector(ref_type x){\n    \n    #ifdef TVMTL_MANIFOLD_DEBUG\n\tif(!std::isfinite(x(0))) std::cout << \"Projector recieved nan\" << std::endl;\n    #endif\n\n    scalar_type norm = x.norm();\n    if(norm!=0.0) x.normalize();\n    else x.setConstant(1.0 / 256.0).normalize();\n\n    #ifdef TVMTL_MANIFOLD_DEBUG\n\tif(!std::isfinite(x(0))) std::cout << \"Projector returns nan\" << std::endl;\n    #endif\n}\n\n\n\n} // end namespace tvmtl\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "5c53f353610c18ee1277fef9dc3440bd92e84e49", "size": 13164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/manifold_sphere.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_sphere.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_sphere.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": 30.5429234339, "max_line_length": 151, "alphanum_fraction": 0.6486630204, "num_tokens": 4161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5882138293045379}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_TAN_3PIO_8_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_TAN_3PIO_8_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant \\f$\\tan3\\frac\\pi{8} = \\sqrt2 + 1\\f$.\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Tan_3pio_8<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = 1.0+sqrt(2.0);\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Tan_3pio_8();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant \\f$\\tan3\\frac\\pi{8} = \\sqrt2 + 1\\f$.\n\n      Generate the  constant tan_3pio_8.\n\n      @return The Tan_3pio_8 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::tan_3pio_8_> tan_3pio_8 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/tan_3pio_8.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "ffc1129ab67f11fb0c6a9ea9a8633f18d213d06d", "size": 1433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/tan_3pio_8.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/tan_3pio_8.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/tan_3pio_8.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0461538462, "max_line_length": 100, "alphanum_fraction": 0.5861828332, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5882138168363416}}
{"text": "#include <iostream>\n#include <fstream>\n#include<iomanip>\n\n#include <cstdlib>\n#include <stdio.h>\n#include <string>\n#include <vector>\n\n#include <time.h>\n#include <sys/time.h>\n\n#include \"mkl.h\"\n#include <omp.h>\n//#include \"mkl_service.h\"\n#include <fftw3.h>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\ndouble gettime(){\n    struct timeval tv;\n    gettimeofday(&tv,NULL);\n    return tv.tv_sec*1000+tv.tv_usec/1000.0;\n};\n\ndouble *** al(int &n1,int &n2,int &n3){\n    double ***p;\n    p=new double**[n1];\n    for (int i=0;i<n1;i++){\n        p[i] = new double *[n2];\n        for (int j=0;j<n2;j++) {\n            p[i][j] = new double[n3];\n        }\n    }\n    return p;\n}\n\n//template <typename T>\nvoid del(double *** p, int &n1,int &n2){\n    for(int i=0; i<n1; i++) {\n        for (int j = 0; j < n2; j++) {\n            delete [] p[i][j];\n        }\n        delete [] p[i];\n    }\n    delete  [] p;\n    p=NULL;\n}\n\ndouble *** loadfile(int &n1, int &n2, int &n3, char *path){\n\n    int count = 0;\n    FILE* fp;\n    char str[100];\n\n    double ***v = al(n1,n2,n3);\n\n    fp = fopen(path,\"r\");\n\n    string tmp;\n    while (fscanf(fp, \"%s\", str) != EOF)\n    {\n        int NUM=count;\n        int k=NUM%(n1*n2);\n        k=(NUM-k)/(n1*n2);\n        int j=(NUM-k*n1*n2)%n2;\n        int i=(NUM-k*n1*n2)/n2;\n        tmp=str;\n        v[i][j][k]=(double)atof(tmp.c_str());\n        count++;\n        if(count==n1*n2*n3){break;}\n    }\n\n    fclose(fp);\n\n    return v;\n}\n\nvoid display(double *** v, int &n1, int &n2, int &n3){\n\n    cout << \"Tensor: \" << endl;\n\n    for (int k = 0; k < n3; k++) {\n        for (int i = 0; i < n1; i++) {\n            for (int j = 0; j < n2; j++) {\n                cout << v[i][j][k] << \" \";\n            }\n            cout << endl;\n        }\n        cout << endl;\n    }\n}\n\nint main()\n{\n    double t0, t1, t2, t3, t4;\n    int turn=2000;\n    int n1 = turn, n2 = turn, n3 = 110;\n    int N0 = floor(n3/2.0) + 1; \n\n    char path[1000] = \"/home/jcfei/Documents/MATLAB/data/a2000.txt\";\n\n    double ***M = loadfile(n1, n2, n3, path);\n    cout << \"loadfile\" << endl;\n\n    double ***v_t = al(n1, n2, N0);\n    double ***v_t1 = al(n1, n2, N0);\n\n    t0 = gettime();\n    fftw_complex out[N0]; //fftw_alloc_real()\n    double *in = fftw_alloc_real(n3);\n\n    fftw_plan p_fft;\n    p_fft = fftw_plan_dft_r2c_1d(n3, in, out, FFTW_ESTIMATE);\n//    p=fftw_plan_dft_1d(n3,in,out,FFTW_FORWARD,FFTW_MEASURE);\n\n//#pragma omp parallel for num_threads(8)\n    for (int i = 0; i < n1; i++) {\n        for (int j = 0; j < n2; j++) {\n            in = M[i][j];   \n            fftw_execute_dft_r2c(p_fft, in, out);\n            for (int k = 0; k < N0; k++) {\n                v_t[i][j][k] = out[k][0];\n                v_t1[i][j][k] = out[k][1];\n            }             \n        }\n    }\n    del(M,n1,n2);\n//    t1=gettime();\n//    cout<<\"fft time: \"<<t1-t0<<endl;\n\n    double ***uf = al(n1, n1, N0);\n    double ***uf1 = al(n1, n1, N0);\n    double ***theta = al(n1, n2, N0);\n    double ***vf = al(n2, n2, N0);\n    double ***vf1 = al(n2, n2, N0);\n\n    cx_mat TMP = zeros<cx_mat>(n1, n2);\n    cx_mat TMPU = zeros<cx_mat>(n1, n1);\n    cx_mat TMPV = zeros<cx_mat>(n2, n2);\n    colvec TMPT;\n\n//    t2=gettime();\n//    cout<<\"alloc space: \"<<t2-t1<<endl;\n\n//#pragma omp parallel for num_threads(8) \n    for (int k = 0; k < N0; k++) {\n        for (int i = 0; i < n1; i++) {\n            for (int j = 0; j < n2; j++) {\n                TMP(i, j).real(v_t[i][j][k]);\n                TMP(i, j).imag(v_t1[i][j][k]);\n            }\n        }\n        svd(TMPU, TMPT, TMPV, TMP, \"dc\");\n//        svd(TMPU,TMPT,TMPV,TMP,\"std\");\n\n        for (int i = 0; i < n1; i++) {\n            for (int j = 0; j < n1; j++) {\n                uf[i][j][k] = TMPU(i, j).real();\n                uf1[i][j][k] = TMPU(i, j).imag();\n            }\n        }\n        for (int i = 0; i < n2; i++) {\n            for (int j = 0; j < n2; j++) {\n                vf[i][j][k] = TMPV(i, j).real();\n                vf1[i][j][k] = TMPV(i, j).imag();\n            }\n        }\n        if (n1 <= n2) {\n            for (int i = 0; i < n1; i++) {\n                theta[i][i][k] = TMPT(i);\n            }\n        } else {\n            for (int i = 0; i < n2; i++) {\n                theta[i][i][k] = TMPT(i);\n            }\n        }\n    }\n\n    del(v_t, n1, n2);\n    del(v_t1, n1, n2);\n\n    fftw_complex out1[N0]; //fftw_alloc_real()\n    double *in1 = fftw_alloc_real(n3);\n    p_fft = fftw_plan_dft_c2r_1d(n3, out1, in1, FFTW_ESTIMATE);\n\n//    #pragma omp parallel for num_threads(8)\n//    #pragma omp parallel for num_threads(2)\n\n    double ***U = al(n1, n1, n3);\n\n    for (int i = 0; i < n1; i++) {\n        for (int j = 0; j < n1; j++) {\n            for (int k = 0; k < N0; k++) {\n                out1[k][0] = uf[i][j][k];\n                out1[k][1] = uf1[i][j][k];\n            }\n            fftw_execute_dft_c2r(p_fft, out1, in1);\n\n            for (int k = 0; k < n3; k++) {\n                U[i][j][k] = 1.0 / n3 * in1[k];\n            }\n        }\n    }\n\n    del(uf, n1, n1);\n    del(uf1, n1, n1);\n\n    double ***V = al(n2, n2, n3);\n    for (int i = 0; i < n2; i++) {\n        for (int j = 0; j < n2; j++) {\n            for (int k = 0; k < N0; k++) {\n                out1[k][0] = vf[i][j][k];\n                out1[k][1] = vf1[i][j][k];\n            }\n            fftw_execute_dft_c2r(p_fft, out1, in1);\n            for (int k = 0; k < n3; k++) {\n                V[i][j][k] = 1.0 / n3 * in1[k];\n            }\n        }\n    }\n    del(vf, n2, n2);\n    del(vf1, n2, n2);\n\n    double ***Theta = al(n1, n2, n3);\n    for (int i = 0; i < n1; i++) {\n        for (int j = 0; j < n2; j++) {\n            for (int k = 0; k < N0; k++) {\n                out1[k][0] = theta[i][j][k];\n                out1[k][1] = 0;\n            }\n            fftw_execute_dft_c2r(p_fft, out1, in1);\n            for (int k = 0; k < n3; k++) {\n                Theta[i][j][k] = 1.0 / n3 * in1[k];\n            }\n        }\n    }\n    del(theta, n1, n2);\n\n    fftw_destroy_plan(p_fft);\n\n    t4 = gettime();\n//    cout<<\"ifft time: \"<<t4-t3<<endl;\n    cout << \"Total time: \" << t4 - t0 << endl;\n\n    //fft transform result write to txt\n//    ofstream a;\n//    a.open(\"/home/jcfei/Desktop/TensorC++/txtToarray/Theta-video.txt\");\n//    for (int k=0; k<n3;k++){\n//        for (int i=0; i<n1;i++){\n//            for(int j=0; j<n2;j++){\n//                a<<setiosflags(ios::right)<<setw(15)<<Theta[i][j][k]<<\"  \";\n//            }\n//            a<<endl;\n//        }\n//    }\n//    a.close();\n//\n//    ofstream b;\n//    b.open(\"/home/jcfei/Desktop/TensorC++/txtToarray/U-video.txt\");\n//    for (int k=0; k<n3;k++){\n//        for (int i=0; i<n1;i++){\n//            for(int j=0; j<n1;j++){\n//                b<<setiosflags(ios::right)<<setw(10)<<U[i][j][k]<<\"  \";\n//            }\n//            b<<endl;\n//        }\n//    }\n//    b.close();\n//\n//    ofstream c;\n//    c.open(\"/home/jcfei/Desktop/TensorC++/txtToarray/V-video.txt\");\n//    for (int k=0; k<n3;k++){\n//        for (int i=0; i<n2;i++){\n//            for(int j=0; j<n2;j++){\n//                c<<setiosflags(ios::right)<<setw(10)<<V[i][j][k]<<\"  \";\n//            }\n//            c<<endl;\n//        }\n//    }\n//    c.close();\n    return 0;\n}\n", "meta": {"hexsha": "33aa9d3190382166aafe8ada0321d21b6c6e77b8", "size": 7163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "T-SVD/tsvd.cpp", "max_stars_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_stars_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "T-SVD/tsvd.cpp", "max_issues_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_issues_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "T-SVD/tsvd.cpp", "max_forks_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_forks_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_forks_repo_licenses": ["Apache-2.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.1333333333, "max_line_length": 77, "alphanum_fraction": 0.4242635767, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861584, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5880633553768825}}
{"text": "/*!\n * @file diffusion_problem_ms.hpp\n * @brief Contains implementation of the main object for multiscale FEM.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_DIFFUSION_PROBLEM_MS_HPP_\n#define INCLUDE_DIFFUSION_PROBLEM_MS_HPP_\n\n// Deal.ii\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/base/multithread_info.h>\n#include <deal.II/base/timer.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/affine_constraints.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n// My Headers\n#include \"matrix_coeff.hpp\"\n#include \"right_hand_side.hpp\"\n#include \"neumann_bc.hpp\"\n#include \"dirichlet_bc.hpp\"\n#include \"diffusion_problem_basis.hpp\"\n\n/*!\n * @namespace DiffusionProblem\n * @brief Contains implementation of the main object\n * and all functions to solve a\n * Dirichlet-Neumann problem on a unit square.\n */\nnamespace DiffusionProblem\n{\nusing namespace dealii;\n\n/*!\n * @class DiffusionProblemMultiscale\n * @brief Main class to solve\n * Dirichlet-Neumann problem on a unit square with\n * multiscale FEM.\n */\ntemplate <int dim>\nclass DiffusionProblemMultiscale\n{\npublic:\n\tDiffusionProblemMultiscale (unsigned int n_refine, unsigned int n_refine_local);\n\tvoid run ();\n\nprivate:\n\t// *********************************************\n\t// This is for threading the basis computation\n\tstruct BasisScratchData\n\t{\n\t\tBasisScratchData () {}; // No implementation\n\t\tBasisScratchData (const BasisScratchData& /*scratch_data*/) {}; // No implementation\n\t};\n\n\tstruct BasisCopyData\n\t{\n\n\t};\n\n\tvoid compute_local_basis(const typename std::vector<DiffusionProblemBasis<dim>>::iterator &it_basis,\n\t\t\t\t\t\t\t\tBasisScratchData\t&scratch_data,\n\t\t\t\t\t\t\t\tBasisCopyData\t&copy_data);\n\tvoid output_local_solution(const typename std::vector<DiffusionProblemBasis<dim>>::iterator &it_basis,\n\t\t\t\t\t\t\t\tBasisScratchData\t&scratch_data,\n\t\t\t\t\t\t\t\tBasisCopyData\t&copy_data);\n\tvoid fake_copy (const BasisCopyData&) {}; // No implementation\n\t// *********************************************\n\n\tvoid make_grid ();\n\tvoid initialize_basis_problem ();\n\tvoid compute_basis ();\n\tvoid setup_system ();\n\tvoid assemble_system ();\n\tvoid solve_iterative ();\n\n\tvoid send_global_weights_to_cell ();\n\n\tvoid output_global_coarse () const;\n\tvoid output_global_fine ();\n\n\tTriangulation<dim>   \t\t\ttriangulation;\n\tFE_Q<dim>            \t\t\tfe;\n\tDoFHandler<dim>      \t\t\tdof_handler;\n\n\tAffineConstraints<double> \t\tconstraints;\n\n\tSparsityPattern      \t\t\tsparsity_pattern;\n\tSparseMatrix<double> \t\t\tsystem_matrix;\n\n\t/*!\n\t * Solution vector containing weights at the dofs.\n\t */\n\tVector<double>       \t\t\tsolution;\n\n\t/*!\n\t * Contains all parts of the right-hand side needed to\n\t * solve the linear system.\n\t */\n\tVector<double>       \t\t\tsystem_rhs;\n\n\t/*!\n\t * Number of global refinements.\n\t */\n\tconst unsigned int n_refine;\n\n\t/*!\n\t * Number of local refinements.\n\t */\n\tconst unsigned int n_refine_local;\n\n\t/*!\n\t * STL Vector holding basis functions for each coarse cell.\n\t */\n\tstd::vector<DiffusionProblemBasis<dim>> \tcell_basis_vector;\n};\n\n\n/*!\n * Constructor.\n */\ntemplate <int dim>\nDiffusionProblemMultiscale<dim>::DiffusionProblemMultiscale (unsigned int n_refine, unsigned int n_refine_local) :\n  fe (1),\n  dof_handler (triangulation),\n  n_refine(n_refine),\n  n_refine_local(n_refine_local),\n  cell_basis_vector(std::pow(2,dim*n_refine))\n{}\n\n\n/*!\n * Set all relevant data to local basis object and initialize the basis fully.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::initialize_basis_problem ()\n{\n\t// First set up all cell problems serially\n\ttypename Triangulation<dim>::active_cell_iterator\n\t\t\t\t\t\t\t\t\tcell = dof_handler.begin_active(),\n\t\t\t\t\t\t\t\t\tendc = dof_handler.end();\n\tunsigned int cell_number = 0;\n\tfor (; cell!=endc; ++cell)\n\t{\n\t\tcell_basis_vector[cell_number].set_n_local_refinements (n_refine_local);\n\t\tcell_basis_vector[cell_number].set_cell_data (cell, cell_number);\n\t\tcell_basis_vector[cell_number].set_basis_data ();\n\n\t\tif (cell_number==0)\n\t\t\tcell_basis_vector[cell_number].set_output_flag (true);\n\n\t\t++cell_number;\n\t}\n}\n\n/*!\n * @brief Function pre-computes basis functions.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::compute_basis ()\n{\n\t// Now run them in threads\n\ttypename std::vector<DiffusionProblemBasis<dim>>::iterator\n\t\t\t\t\t\t\t\t\t\tit_basis = cell_basis_vector.begin (),\n\t\t\t\t\t\t\t\t\t\tit_endbasis = cell_basis_vector.end ();\n\tWorkStream::run(it_basis,\n\t\t\t\t\tit_endbasis,\n\t\t\t\t\t*this,\n\t\t\t\t\t&DiffusionProblemMultiscale<dim>::compute_local_basis,\n\t\t\t\t\t&DiffusionProblemMultiscale<dim>::fake_copy,\n\t\t\t\t\tBasisScratchData(),\n\t\t\t\t\tBasisCopyData());\n}\n\n\n/*!\n * Pre-compute the local basis. This function\n * is only used for threading.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::compute_local_basis(const typename\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstd::vector<DiffusionProblemBasis<dim>>::iterator &it_basis,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tBasisScratchData&,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tBasisCopyData&)\n{\n\tit_basis->run ();\n}\n\n\n/*!\n * @brief Set up the grid with a certain number of refinements.\n *\n * Generate a triangulation of \\f$[0,1]^{\\rm{dim}}\\f$ with edges/faces\n * numbered form \\f$1,\\dots,2\\rm{dim}\\f$.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::make_grid ()\n{\n\tGridGenerator::hyper_cube (triangulation, 0, 1, /* colorize */ true);\n\n\ttriangulation.refine_global (n_refine);\n\n\tstd::cout << \"Number of active cells: \"\n\t\t\t<< triangulation.n_active_cells()\n\t\t\t<< std::endl;\n}\n\n\n/*!\n * @brief Setup sparsity pattern and system matrix.\n *\n * Compute sparsity pattern and reserve memory for the sparse system matrix\n * and a number of right-hand side vectors. Also build a constraint object\n * to take care of Dirichlet boundary conditions.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::setup_system ()\n{\n\tdof_handler.distribute_dofs (fe);\n\n\tstd::cout << std::endl\n\t\t\t<< \"Number of active global cells:   \"\n\t\t\t<< triangulation.n_active_cells()\n\t\t\t<< std::endl\n\t\t\t<< \"Number of degrees of freedom:   \" << dof_handler.n_dofs()\n\t\t\t<< std::endl\n\t\t\t<< std::endl;\n\n\n\tconstraints.clear();\n\tDoFTools::make_hanging_node_constraints(dof_handler, constraints);\n\n\t/*\n\t * Set up Dirichlet boundary conditions.\n\t */\n\tconst Coefficients::DirichletBC<dim> dirichlet_bc;\n\tfor (unsigned int i = 0; i<dim; ++i)\n\t{\n\t\tVectorTools::interpolate_boundary_values(dof_handler,\n\t\t\t\t\t\t\t\t\t\t\t\t\t/*boundary id*/ 2*i, // only even boundary id\n\t\t\t\t\t\t\t\t\t\t\t\t\tdirichlet_bc,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconstraints);\n\t}\n\n\tconstraints.close();\n\n\n\tDynamicSparsityPattern dsp(dof_handler.n_dofs());\n\tDoFTools::make_sparsity_pattern (dof_handler,\n\t\t\t\t\t\t\t\t\tdsp,\n\t\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t\t\t/*keep_constrained_dofs =*/ true); // for time stepping this is essential to be true\n\n\tsparsity_pattern.copy_from(dsp);\n\n\tsystem_matrix.reinit (sparsity_pattern);\n\n\tsolution.reinit (dof_handler.n_dofs());\n\tsystem_rhs.reinit (dof_handler.n_dofs());\n}\n\n\n/*!\n * @brief Assemble the system matrix and the static right hand side.\n *\n * Assembly routine to build the time-independent (static) part.\n * Neumann boundary conditions will be put on edges/faces\n * with odd number. Constraints are not applied here yet.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::assemble_system ()\n{\n\tQGauss<dim - 1> face_quadrature_formula(fe.degree + 1);\n\n\tFEFaceValues<dim> \tfe_face_values(fe,\n\t\t\t\t\t\t\t\t\t\tface_quadrature_formula,\n\t\t\t\t\t\t\t\t\t\tupdate_values | update_quadrature_points |\n\t\t\t\t\t\t\t\t\t\tupdate_normal_vectors |\n\t\t\t\t\t\t\t\t\t\tupdate_JxW_values);\n\n\tconst unsigned int   \tdofs_per_cell = fe.dofs_per_cell;\n\tconst unsigned int \t\tn_face_q_points = face_quadrature_formula.size();\n\n\tFullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\tVector<double>       cell_rhs (dofs_per_cell);\n\n\tstd::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n\t/*\n\t * Neumann BCs and vector to store the values.\n\t */\n\tconst Coefficients::NeumannBC<dim> \tneumann_bc;\n\tstd::vector<double>  \tneumann_values(n_face_q_points);\n\n\t// initialize basis iterator\n\ttypename std::vector<DiffusionProblemBasis<dim>>::iterator\n\t\t\t\t\t\t\t\t\tit_basis = cell_basis_vector.begin();\n\n\t/*\n\t * Integration over cells.\n\t */\n\tfor (const auto &cell: dof_handler.active_cell_iterators())\n\t{\n\t\tcell_matrix = 0;\n\t\tcell_rhs = 0;\n\n\t\tcell_matrix = it_basis->get_global_element_matrix ();\n\t\tcell_rhs = it_basis->get_global_element_rhs ();\n\n\t\t/*\n\t\t * Boundary integral for Neumann values for odd boundary_id.\n\t\t */\n\t\tfor (unsigned int face_number = 0;\n\t\t\t face_number < GeometryInfo<dim>::faces_per_cell;\n\t\t\t ++face_number)\n\t\t{\n\t\t\tif (cell->face(face_number)->at_boundary() &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 1) ||\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 3) ||\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 5)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tfe_face_values.reinit(cell, face_number);\n\n\t\t\t\t// Fill in values at this particular face.\n\t\t\t\tneumann_bc.value_list(fe_face_values.get_quadrature_points(),\n\t\t\t\t\t\t\t\t\t\t   neumann_values);\n\n\t\t\t\tfor (unsigned int q_face_point = 0; q_face_point < n_face_q_points; ++q_face_point)\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tcell_rhs(i) += neumann_values[q_face_point] // g(x_q)\n\t\t\t\t\t\t\t\t\t\t* fe_face_values.shape_value(i, q_face_point) // phi_i(x_q)\n\t\t\t\t\t\t\t\t\t\t* fe_face_values.JxW(q_face_point); // dS\n\t\t\t\t\t} // end ++i\n\t\t\t\t} // end ++q_face_point\n\t\t\t} // end if\n\t\t} // end ++face_number\n\n\n\t\t// get global indices\n\t\tcell->get_dof_indices (local_dof_indices);\n\t\t/*\n\t\t * Now add the cell matrix and rhs to the right spots\n\t\t * in the global matrix and global rhs. Constraints will\n\t\t * be taken care of later.\n\t\t */\n\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i)\n\t\t{\n\t\t\tfor (unsigned int j = 0; j < dofs_per_cell; ++j)\n\t\t\t{\n\t\t\t\tsystem_matrix.add(local_dof_indices[i],\n\t\t\t\t\t\t\tlocal_dof_indices[j],\n\t\t\t\t\t\t\tcell_matrix(i, j));\n\t\t\t}\n\t\t\tsystem_rhs(local_dof_indices[i]) += cell_rhs(i);\n\t\t}\n\t} // end ++cell\n}\n\n\n/*!\n * @brief Iterative solver.\n *\n * CG-based solver with SSOR-preconditioning.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::solve_iterative ()\n{\n\tSolverControl           solver_control (1000, 1e-12);\n\tSolverCG<>              solver (solver_control);\n\n\tPreconditionSSOR<> preconditioner;\n\tpreconditioner.initialize(system_matrix, 1.2);\n\n\tsolver.solve (system_matrix,\n\t\t\t\tsolution,\n\t\t\t\tsystem_rhs,\n\t\t\t\tpreconditioner);\n\n\tconstraints.distribute (solution);\n\n\tstd::cout << \"   \"\n\t\t\t<< \"(global problem)   \"\n\t\t\t<< solver_control.last_step()\n\t\t\t<< \" coarse CG iterations needed to obtain convergence.\"\n\t\t\t<< std::endl;\n}\n\n\n/*!\n * @brief Send coarse weights to corresponding local cell.\n *\n * After the coarse (global) weights have been computed they\n * must be set to the local basis object and stored there.\n * This is necessary to write the local multiscale solution.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::send_global_weights_to_cell ()\n{\n\t// For each cell we get dofs_per_cell values\n\tconst unsigned int   dofs_per_cell   = fe.dofs_per_cell;\n\tstd::vector<types::global_dof_index> \tlocal_dof_indices (dofs_per_cell);\n\n\t// active cell iterator\n\ttypename DoFHandler<dim>::active_cell_iterator\n\t\t\t\t\t\t\t\tcell = dof_handler.begin_active (),\n\t\t\t\t\t\t\t\tendc = dof_handler.end ();\n\t// initialize basis iterator\n\ttypename std::vector<DiffusionProblemBasis<dim>>::iterator\n\t\t\t\t\t\t\t\t\tit_basis = cell_basis_vector.begin ();\n\tfor (; cell!=endc; ++cell)\n\t{\n\t\t// Get local\n\t\tcell->get_dof_indices (local_dof_indices);\n\n\t\tstd::vector<double> extracted_weights (dofs_per_cell, 0);\n\t\tsolution.extract_subvector_to (local_dof_indices, extracted_weights);\n\t\tit_basis->set_global_weights (extracted_weights);\n\n\t\t// increase syncronously\n\t\t++it_basis;\n\t}\n}\n\n\n/*!\n * @brief Write coarse solution to disk.\n *\n * Write results for coarse solution to disk in vtu-format.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::output_global_coarse () const\n{\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\tdata_out.add_data_vector (solution, \"solution\");\n\tdata_out.build_patches ();\n\n\tstd::ofstream output (dim == 2 ?\n\t\t\t\t\t\"solution-ms_coarse-2d.vtu\" :\n\t\t\t\t\t\"solution-ms_coarse-3d.vtu\");\n\n\tdata_out.write_vtu (output);\n}\n\n\n/*!\n * Output function to write local multiscale solution. Only used for threading output.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::output_local_solution (\n\t\tconst typename std::vector<DiffusionProblemBasis<dim>>::iterator &it_basis,\n\t\tBasisScratchData&,\n\t\tBasisCopyData&)\n{\n\tit_basis->output_global_solution_in_cell ();\n}\n\n\n/*!\n * Write all local multiscale solution (threaded) and\n * a global pvtu-record.\n */\ntemplate <int dim>\nvoid\nDiffusionProblemMultiscale<dim>::output_global_fine ()\n{\n\t// List of filenames of local outputs for master file\n\tstd::vector<std::string> filenames_on_cell;\n\n\t// Now run them in threads\n\ttypename std::vector<DiffusionProblemBasis<dim>>::iterator\n\t\t\t\t\t\t\t\t\t\t\tit_basis = cell_basis_vector.begin (),\n\t\t\t\t\t\t\t\t\t\t\tit_endbasis = cell_basis_vector.end ();\n\tWorkStream::run(it_basis,\n\t\t\t\t\tit_endbasis,\n\t\t\t\t\t*this,\n\t\t\t\t\t&DiffusionProblemMultiscale<dim>::output_local_solution,\n\t\t\t\t\t&DiffusionProblemMultiscale<dim>::fake_copy,\n\t\t\t\t\tBasisScratchData(),\n\t\t\t\t\tBasisCopyData());\n\n\t// Active cell iterator\n\ttypename DoFHandler<dim>::active_cell_iterator\n\t\t\t\t\t\t\t\tcell = dof_handler.begin_active (),\n\t\t\t\t\t\t\t\tendc = dof_handler.end ();\n\t// Initialize const basis iterator again\n\tit_basis = cell_basis_vector.begin ();\n\n\tfor (; cell!=endc; ++cell)\n\t{\n\t\t// Get the global file name\n\t\tfilenames_on_cell.push_back ( it_basis->get_filename_global () );\n\n\t\t++it_basis;\n\t}\n\n\t// Build a*.pvtu file that points to all output files\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\n\t// Names of solution components\n\tdata_out.add_data_vector (solution, \"solution\");\n\n\tstd::string filename_master = (dim == 2 ?\n\t\t\t\"solution-ms_fine-2d\" :\n\t\t\t\"solution-ms_fine-3d\");\n\tfilename_master += \".pvtu\";\n\n\tstd::ofstream master_output (filename_master.c_str ());\n\n\tdata_out.write_pvtu_record (master_output, filenames_on_cell);\n}\n\n\n/*!\n * @brief Run function of the object.\n *\n * Run the computation after object is built.\n */\ntemplate <int dim>\nvoid DiffusionProblemMultiscale<dim>::run ()\n{\n\tstd::cout << std::endl\n\t\t\t<< \"===========================================\"\n\t\t\t<< std::endl;\n\n\tstd::cout << \"Solving problem in \"\n\t\t\t<< dim << \" space dimensions.\"\n\t\t\t<< std::endl;\n\n\tmake_grid ();\n\n\tsetup_system ();\n\n\tinitialize_basis_problem ();\n\tcompute_basis ();\n\n\tassemble_system ();\n\n\t// Now solve\n\tconstraints.condense(system_matrix, system_rhs);\n\tsolve_iterative ();\n\n\tsend_global_weights_to_cell ();\n\n\toutput_global_coarse ();\n\toutput_global_fine ();\n\n\tstd::cout << std::endl\n\t\t\t<< \"===========================================\"\n\t\t\t<< std::endl;\n}\n\n} // end namespace DiffusionProblem\n\n\n#endif /* INCLUDE_DIFFUSION_PROBLEM_MS_HPP_ */\n", "meta": {"hexsha": "abdd8e3381f6ef948a2d3d37402bf52785af799e", "size": 15477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/diffusion_problem_ms.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/diffusion_problem_ms.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/diffusion_problem_ms.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 25.8380634391, "max_line_length": 114, "alphanum_fraction": 0.6999418492, "num_tokens": 3956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.5880633491039432}}
{"text": "#include \"apch.h\"\n#include \"Maths.h\"\n\t//#include <Eigen/Core>\n\t//#include <Eigen/Geometry>\n\t//#include <Eigen/Dense>\n\nnamespace A {\n\n\tEigen::Affine3f CreateOrthographicProjection(float left, float right, float bottom, float top, float z_near, float z_far)\n\t{\n\t\tAP_PROFILE_FN();\n\t\tEigen::Affine3f proj = Eigen::Affine3f::Identity();\n\t\tproj(0, 0) = 2 / (right - left);\n\t\tproj(1, 1) = 2 / (top - bottom);\n\t\tproj(2, 2) = 2 / (z_near - z_far);\n\t\tproj(0, 3) = (right + left) / (left - right);\n\t\tproj(1, 3) = (top + bottom) / (bottom - top);\n\t\tproj(2, 3) = (z_far + z_near) / (z_near - z_far);\n\t\tproj(3, 3) = 1;\n\t\treturn proj;\n\t}\n\n}", "meta": {"hexsha": "9d9537ea0cc82af4d12db3e6d2225d846034fde6", "size": 625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Apsis/src/Apsis/Utility/Maths.cpp", "max_stars_repo_name": "Bodleum/Apsis", "max_stars_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-16T09:11:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T17:45:04.000Z", "max_issues_repo_path": "Apsis/src/Apsis/Utility/Maths.cpp", "max_issues_repo_name": "Bodleum/Apsis", "max_issues_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Apsis/src/Apsis/Utility/Maths.cpp", "max_forks_repo_name": "Bodleum/Apsis", "max_forks_repo_head_hexsha": "8a849340355c50bf4635287b3c94b3a6c2985f2c", "max_forks_repo_licenses": ["Apache-2.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.1739130435, "max_line_length": 122, "alphanum_fraction": 0.6112, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5880439129532063}}
{"text": "#include <Eigen/Eigenvalues>\n#include <eigen3/unsupported/Eigen/MPRealSupport>\n#include <mpfr.h>\n#include <iostream>\n\ntypedef mpfr::mpreal realt;\ntypedef std::complex<realt> complext;\ntypedef realt __plant_typet;\n#define CONTROL_TYPES_H_\n#define interval(x) x\n#include \"benchmark.h\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace mpfr;\n\n#define EXIT_INCREASE_K 2\n#define EXIT_INCREASE_SAMPLE_RATE 3\n#define PRECISION 256\n#define NUM_PROG_ARGS 2 + NSTATES\n#define K_SIZE_ARG_INDEX 1u\n#define K_ARG_OFFSET 2u\n\ntypedef Matrix<realt, NSTATES, NSTATES> matrixt;\n\n//const realt _controller_K[] = { 0.0234375,-0.1328125, 0.00390625 };\n//const realt _controller_K[] = { 0.0234375,0.1328125, 0.00390625 };\nrealt _controller_K[NSTATES];\n\nbool is_imaginary(const realt &imaginary_offset, const complext &complex) {\n  const realt imag_value = std::imag(complex);\n  cout << \"imag_value: \" << imag_value << endl;\n  cout << \"imaginary_offset: \" << imaginary_offset << endl;\n  return abs(imag_value) > imaginary_offset;\n}\n\nint main(const int argc, const char * const argv[]) {\n  const realt two = \"2.0\";\n  const realt two_pi = const_pi() * two;\n  const realt imaginary_offset = pow(two, -PRECISION/4);\n  if (argc != NUM_PROG_ARGS) return EXIT_FAILURE;\n  mpreal::set_default_prec(PRECISION);\n  const realt K_SIZE = argv[K_SIZE_ARG_INDEX];\n  for (size_t i=0; i < NSTATES; ++i)\n    _controller_K[i]=argv[i + K_ARG_OFFSET];\n\n  Matrix<realt, NSTATES, NSTATES> A;\n  for (size_t i = 0; i < NSTATES; ++i) {\n    for (size_t j = 0; j < NSTATES; ++j) {\n      A(i, j) = _controller_A[i][j];\n    }\n  }\n  Matrix<realt, NSTATES, 1> B;\n  for (size_t i = 0; i < NSTATES; ++i) {\n    B(i) = _controller_B[i];\n  }\n  Matrix<realt, 1, NSTATES> K;\n  for (size_t i = 0; i < NSTATES; ++i) {\n    K[i] = _controller_K[i];\n  }\n\n  // Check K_SIZE\n  matrixt result = A - B * K;\n  EigenSolver<matrixt> eigenSpace(result);\n  if (Success != eigenSpace.info())\n    return EXIT_FAILURE;\n  const EigenSolver<matrixt>::EigenvalueType eigenvalues = eigenSpace.eigenvalues();\n  cout << \"num_eigenvalues: \" << eigenvalues.size() << endl;\n  for (size_t i=0; i < eigenvalues.size(); ++i) {\n    cout << \"eigenvalue: \" << eigenvalues[i] << endl;\n    if (!is_imaginary(imaginary_offset, eigenvalues[i])) continue;\n    const realt angle = std::arg(eigenvalues[i]);\n    const realt expected = abs(two_pi / angle);\n    cout << \"expected_k_size=\" << expected << endl;\n    cout << \"actual_k_size=\" << K_SIZE << endl;\n    if (expected > K_SIZE)\n      return EXIT_INCREASE_K;\n  }\n\n  // Check sample rate\n  /*Matrix<realt, Dynamic, Dynamic> vertices(Matrix<realt, Dynamic, Dynamic>::Ones(NSTATES, ::pow(2, NSTATES)));\n  int step = 1;\n  for (size_t row = 0; row < vertices.rows(); ++row) {\n    for (size_t col = 1; col < vertices.cols(); ++col) {\n      vertices.coeffRef(row, col) = vertices.coeffRef(row, col - 1);\n      if (col % step == 0) vertices.coeffRef(row, col) = -vertices.coeffRef(row, col);\n    }\n    step <<= 1;\n  }\n  const Matrix<complext, NSTATES, NSTATES> eigenvectors(eigenSpace.eigenvectors());\n  cout << \"eigenvectors: \" << endl << eigenvectors << endl;\n  matrixt pseudo_eigenvectors(eigenvectors.real());\n  for (size_t i=0; i < NSTATES - 1; ++i) {\n    if (!is_imaginary(imaginary_offset, eigenvalues[i])) continue;\n    pseudo_eigenvectors.col(i + 1) = eigenvectors.col(i).imag();\n    ++i;\n  }\n  cout << \"pseudo_eigenvectors: \" << endl << pseudo_eigenvectors << endl;\n  vertices *= pseudo_eigenvectors.transpose();*/\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5769310d28f7e1a5425295ea4eb0c6937de578d9", "size": 3506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/universalrunner/discrete_step_k_completeness_check.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/universalrunner/discrete_step_k_completeness_check.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/universalrunner/discrete_step_k_completeness_check.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": 34.0388349515, "max_line_length": 112, "alphanum_fraction": 0.6739874501, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723468, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5880043902889529}}
{"text": "#include <vector> /* representing state */\n#include <algorithm> /* for numeric min/max */\n#include <cmath> /* log, exp, fmod */\n\n#include <boost/numeric/odeint.hpp>\n#include <ios>\nusing namespace boost::numeric::odeint;\n\ntypedef double icing_float;\n\n// [1] - Reference Paper: TBME-01160-2016 \n// [2] - Reference Paper: computer methods and programs in biomedicine 102 (2011) 192–205\ntemplate<typename U = icing_float>\nclass ChaseIcing {\n    // Each enum maps to an index within the state vector for accessing that\n    // function's value.\n    enum Function { fn_G = 0\n        , fn_Q\n        , fn_I\n        , fn_P1\n        , fn_P2\n        , fn_P\n        , fn_u_en\n    };\n    using _state_type = std::vector<U>;\n\n    /* a bunch of constants that should be in the namespace */\n    const U n_I = 0.0075; // 1/min, Table II, [1]\n    const U d1 = -std::log(0.5)/20.0; // 1/min, Table II, [1]\n    const U d2 = -std::log(0.5)/100.0; // 1/min, Table II, [1]\n    const U P_max = 6.11; // mmol/min, Table II, [1]\n\n    auto P_min(const _state_type &x)\n    {\n        return std::min(d2 * x[fn_P2], P_max);\n    }\n\n    auto alpha_decay(const U variable, const U decay_parameter)\n    {\n        return variable / (1.0 + decay_parameter * variable);\n    }\n\n    auto Q_frac(const _state_type &x)\n    {\n        const U a_G = 1.0 / 65.0; // Table II, [1]\n        const U Q = x[fn_Q];\n        return alpha_decay(Q, a_G);\n    }\n\n    // PN(t) -> Parenteral nutrition input, eg IV dextrose\n    auto _P(const _state_type &x)\n    {\n        const U _PN_ext = dextrose_rate; // TODO -> derive this over the network\n\n        return P_min(x) + _PN_ext;\n    }\n\n    auto _u_en(const _state_type &x)\n    {\n        const U k1 = 14.9; // mU * l / mmol/min, Table II, [1]\n        const U k2 = -49.9; // mU/min, Table II, [1]\n        const U u_min = 16.7; // mU/min, Table II, [1]\n        const U u_max = 266.7; // mU/min, Table II, [1]\n        const U G = x[fn_G];\n        return std::min(std::max(u_min, k1 * G + k2), u_max);\n    }\n\n    auto G_dot(const _state_type &x)\n    {\n        const U p_G = 0.006; // End of section 4.1, in [2]\n        const U S_I = 0.5e-3; // TODO: patient specific\n        const U G = x[fn_G];\n        const U Q = x[fn_Q];\n        const U P = _P(x);\n        const U EGP = 1.16; // mmol/min Table II, [1]\n        const U CNS = 0.3; // mmol/min Table II, [1]\n        const U V_G = 13.3; // L, Table II, [1]\n\n        U dGdt = 0.0;\n        // G' = -p_G G(t)\n        //\t - S_I G(t) (Q(t) / (1 + a_G Q(t)))\n        //\t + (P(t) + EGP -CNS)/V_G\n        dGdt += -p_G * G;\n        dGdt += -S_I*G * Q_frac(x);\n        dGdt += (P + EGP - CNS)/V_G;\n\n        return dGdt;\n    }\n\n    auto Q_dot(const _state_type &x)\n    {\n        const U I = x[fn_I];\n        const U Q = x[fn_Q];\n        const U n_C = 0.0075; // 1/min, Table II, [1]\n\n        return n_I * (I - Q) - n_C * Q_frac(x);\n    }\n\n    auto I_dot(const _state_type &x)\n    {\n        const U n_K = 0.0542; // 1/min, Table II, [1]\n        const U n_L = 0.1578; // 1/min, Table II, [1] \n        const U a_I = 1.7e-3; // 1/mU, Table II, [1]\n        const U V_I = 4.0; // L, Table II, [1]\n        const U x_L = 0.67; // unitless, Table II, [1]\n\n        const U u_ex = insulin_rate; // TODO: get this over the network\n\n        const U Q = x[fn_Q];\n        const U I = x[fn_I];\n        const U u_en = _u_en(x);\n\n        auto dIdt = U(0.0);\n        // I' = - n_K I(t)\n        //\t- n_L (I(t)/(1+a_I I(t)))\n        //\t- n_I (I(t) - Q(t))\n        //\t+ u_ex(t) / V_I\n        //\t+ (1 - x_L) u_en / V_I\n        dIdt += -n_K * I;\n        dIdt += -n_L * alpha_decay(I, a_I);\n        dIdt += -n_I * (I - Q);\n        dIdt += u_ex / V_I;\n        dIdt += (1.0 - x_L) * u_en / V_I;\n        return dIdt;\n    }\n\n    auto P1_dot(const _state_type &x)\n    {\n        const auto D = U(0.0); // enteral feed rate TODO: get from network\n        return -d1 * x[fn_P1] + D;\n    }\n\n    auto P2_dot(const _state_type &x)\n    {\n        return -P_min(x) + d1 * x[fn_P1];\n    }\n\n    void copy(const ChaseIcing &other)\n    {\n        data = other.data;\n        insulin_rate = other.insulin_rate;\n        dextrose_rate = other.dextrose_rate;\n    }\n\n    /* data is the container which contains the most up to date representation of the model's state\n     *\n     * Should only be accessed using the enum Function data type\n     */\n    _state_type data;\npublic:\n    using state_type = _state_type;\n    void operator() (const state_type &x, state_type &dxdt, const U t)\n    {\n        dxdt[fn_G] = G_dot(x);\n        dxdt[fn_Q] = Q_dot(x);\n        dxdt[fn_I] = I_dot(x);\n        dxdt[fn_P1] = P1_dot(x);\n        dxdt[fn_P2] = P2_dot(x);\n    }\n\n    auto glucose()\n    {\n        return data[fn_G];\n    }\n\n    auto q()\n    {\n        return data[fn_Q];\n    }\n\n    auto i()\n    {\n        return data[fn_I];\n    }\n\n    auto p1()\n    {\n        return data[fn_P1];\n    }\n\n    auto p2()\n    {\n        return data[fn_P2];\n    }\n\n    int run(U time_start\n            , U time_end\n            , U dt\n            , U insulin_rate_mUpermin\n            , U dextrose_rate_mmolpermin)\n    {\n\n        insulin_rate = insulin_rate_mUpermin;\n        dextrose_rate = dextrose_rate_mmolpermin;\n\n        /* model doesnt modify inplace, so we make copies of its data\n         * for integration */\n        auto x = data;\n        auto step = stepper;\n\n        integrate_const(step, *this, x, time_start, time_end, dt);\n        \n        data = x;\n        stepper = step;\n        \n        return 0;\n    }\n\n    /* run the model until time_end using default rates and time step\n     */\n    int run(U time_end)\n    {\n        return run(0.0, time_end, 0.1, insulin_rate, dextrose_rate);\n    }\n\n    /* run the model with implicitly provided rates\n     */\n    int run(U time_start, U time_end, U dt)\n    {\n        return run(time_start, time_end, dt, insulin_rate, dextrose_rate);\n    }\n\n    /* insulin_rate is the exogenous IV insulin rate, in mU/min (not mmol/min as listed in [1])\n     *\n     * Available for public modification, but use run() for most purposes.\n     */\n    U insulin_rate;\n\n    /* dextrose_rate is the exogenous IV dextrose rate, in mmol/min\n     *\n     * Available for public modification, but use run() for most purposes.\n     */\n    U dextrose_rate;\n\n    /* stepper is the Boost integration type, we use RK4 but you may use any you like\n     */\n    runge_kutta4<state_type> stepper;\n\n    /* public constructor\n     */\n    ChaseIcing(state_type _data) : data(_data) {};\n\n    /* copy constructor\n     */\n    ChaseIcing(const ChaseIcing &other)\n    {\n        copy(other);\n    }\n\n    /* assignment operator\n     */\n    ChaseIcing& operator=(const ChaseIcing &other)\n    {\n        copy(other);\n        return *this;\n    }\n};\n\n", "meta": {"hexsha": "9be2078fd57eadea0c4ef4175fe274ddbe5eb000", "size": 6699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ChaseIcing.hpp", "max_stars_repo_name": "ijustlovemath/chase-icing", "max_stars_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ChaseIcing.hpp", "max_issues_repo_name": "ijustlovemath/chase-icing", "max_issues_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ChaseIcing.hpp", "max_forks_repo_name": "ijustlovemath/chase-icing", "max_forks_repo_head_hexsha": "80408eed567478df4065c10f03d696a9226ea75e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8648648649, "max_line_length": 99, "alphanum_fraction": 0.5359008807, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5878959101638727}}
{"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/container/small_vector.hpp>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/range/size.hpp>\nMSVC_WARNING_POP()\n\n#include \"polynomial.hpp\"\n#include \"sequence.hpp\"\n#include \"traits.hpp\"\n\nnamespace poly {\ntemplate <class Poly, std::size_t N = SmallStorageSize>\nclass PolynomialSeries {\n public:\n  using Traits = typename Poly::Traits;\n  using Real = typename Traits::Real;\n  using OrderType = typename Traits::OrderType;\n\n  template <typename T>\n  using small_vector = boost::container::small_vector<T, N>;\n\n  explicit PolynomialSeries(OrderType n) { resize(n); }\n\n  template <class Range, typename = std::enable_if_t<detail::is_range<Range>::value>>\n  explicit PolynomialSeries(Range const& coefficients) {\n    auto count = boost::size(coefficients);\n    coefficients_.resize(count);\n    polynomials_.resize(count);\n    for (auto&& [index, coefficient] : coefficients | boost::adaptors::indexed()) {\n      polynomials_[index].order(narrow_cast<OrderType>(index));\n      coefficients_[index] = static_cast<Real>(coefficient);\n    }\n  }\n\n  auto coefficients() noexcept -> view<Real> {\n    return {coefficients_.data(), coefficients_.size()};\n  }\n  [[nodiscard]] auto coefficients() const noexcept -> view<Real const> {\n    return {coefficients_.data(), coefficients_.size()};\n  }\n  [[nodiscard]] auto polynomials() const noexcept -> view<Poly const> {\n    return {polynomials_.data(), polynomials_.size()};\n  }\n\n  auto operator[](std::size_t index) noexcept -> Real& { return coefficients_[index]; }\n  [[nodiscard]] auto operator[](std::size_t index) const noexcept -> Real {\n    return coefficients_[index];\n  }\n\n  auto at(std::size_t index) noexcept -> Real& { return coefficients_.at(index); }\n  [[nodiscard]] auto at(std::size_t index) const noexcept -> Real {\n    return coefficients_.at(index);\n  }\n\n  template <class F, typename = std::enable_if_t<std::is_invocable_r_v<Real, F, Real>>>\n  [[nodiscard]] static auto project(F const& function, OrderType order) -> PolynomialSeries {\n    Poly poly{order};\n    view<Real const> abscissa = poly.abscissa();\n    return project(abscissa | boost::adaptors::transformed(\n                                  [&function](Real const& x) { return function(x); }));\n  }\n\n  template <class Range, typename = std::enable_if_t<detail::is_range<Range>::value>>\n  [[nodiscard]] static auto project(Range const& y_range) -> PolynomialSeries {\n    OrderType count = narrow<OrderType>(boost::size(y_range));\n    if (count == 0) return PolynomialSeries(0);\n    OrderType max_order = count - 1;\n\n    Poly poly{max_order};\n    view<Real const> weights = poly.weights();\n    view<Real const> abscissa = poly.abscissa();\n\n    PolynomialSeries series(max_order);\n\n    for (auto&& [j, y] : y_range | boost::adaptors::indexed()) {\n      for (auto&& [i, f] :\n           polynomial_sequence<Poly>(count, abscissa[j]) | boost::adaptors::indexed()) {\n        series.coefficients_[i] += f * weights[j] * y;\n      }\n    }\n\n    return series;\n  }\n\n  [[nodiscard]] auto operator()(Real x) const -> Real {\n    if constexpr (Traits::has_next) {\n      if (size() == 0) return 0;\n      Real t0 = polynomials_[0](x);\n      Real f = coefficients_[0] * t0;\n      if (size() == 1) return f;\n      Real t1 = polynomials_[1](x);\n      for (std::size_t i = 1; i < size(); i++) {\n        f += coefficients_[i] * t1;\n        std::swap(t0, t1);\n        t1 = polynomials_[i].next(x, t0, t1);\n      }\n      return f;\n    } else {\n      Real f = 0;\n      for (auto&& [index, polynomial] : polynomials_ | boost::adaptors::indexed())\n        f += coefficients_[index] * polynomial(x);\n      return f;\n    }\n  }\n\n  [[nodiscard]] auto size() const noexcept -> std::size_t { return polynomials_.size(); }\n  void resize(OrderType new_size) {\n    OrderType old_size = narrow<OrderType>(size());\n    polynomials_.resize(new_size);\n    coefficients_.resize(new_size, 0);\n\n    for (OrderType i = old_size; i < new_size; i++) polynomials_[i].order(i);\n  }\n\n  template <bool check = false>\n  [[nodiscard]] auto weights(bounds_check<check> c = no_bounds_check) const -> view<Real const> {\n    return polynomials_[size() - 1].weights(c);\n  }\n  template <bool check = false>\n  [[nodiscard]] auto abscissa(bounds_check<check> c = no_bounds_check) const -> view<Real const> {\n    return polynomials_[size() - 1].abscissa(c);\n  }\n\n  static auto domain() noexcept -> std::pair<Real, Real> { return Poly::domain(); }\n\n private:\n  small_vector<Real> coefficients_;\n  small_vector<Poly> polynomials_;\n};\n}  // namespace poly\n", "meta": {"hexsha": "996589bc802d3574b46cb9c9196b398463467633", "size": 5763, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/polynomials/include/series.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/series.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/series.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.4746835443, "max_line_length": 98, "alphanum_fraction": 0.6793336804, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5878036337714424}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n  Eigen::MatrixXf m(2,4);\n  Eigen::VectorXf v(2);\n  \n  m << 1, 23, 6, 9,\n       3, 11, 7, 2;\n       \n  v << 2,\n       3;\n\n  MatrixXf::Index index;\n  // find nearest neighbour\n  (m.colwise() - v).colwise().squaredNorm().minCoeff(&index);\n\n  cout << \"Nearest neighbour is column \" << index << \":\" << endl;\n  cout << m.col(index) << endl;\n}\n", "meta": {"hexsha": "334b4d852b06bf22a0fcaa999fa008120dd8591d", "size": 440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_broadcast_1nn.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_broadcast_1nn.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_ReductionsVisitorsBroadcasting_broadcast_1nn.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 17.6, "max_line_length": 65, "alphanum_fraction": 0.5727272727, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5877334929187762}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include \"base/eigen2hdf.hpp\"\n#include \"base/init.hpp\"\n#include \"base/timer.hpp\"\n#include \"fft/fft2.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\nusing namespace std;\n\nconst char* fname = \"test_rt_truncate.h5\";\n\ntypedef FFT fft_t;\ntypedef RT<std::complex<double>, RidgeletFrame, fft_t> RT_t;\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\n\nvoid dump_frc(const std::vector<rt_coeff_t>& f_rc, const RidgeletFrame& rt)\n{\n  const char* fname = \"f_rc.h5\";\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (unsigned int i = 0; i < f_rc.size(); ++i) {\n    stringstream ss;\n    ss << rt.lambdas()[i];\n    string slam = ss.str();\n    eigen2hdf::save(file, slam, f_rc[i]);\n  }\n  H5Fclose(file);\n  cout << \"Written f(lambda, t) to \" << fname << \"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int J, rho_x, rho_y;\n  double keep;\n  double sigma;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"J,j\", po::value<unsigned int>(&J)->default_value(3), \"J\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"rttre\", po::value<double>(&keep)->default_value(1), \"percentage of coefficients kept\")\n      (\"sigma\", po::value<double>(&sigma)->default_value(1. / 8), \"parameter\")\n      (\"save\", \"save coefficients\")\n      (\"non-smooth\", \"non-smooth\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << setw(20) << \"J: \" << J << \"\\n\"\n       << setw(20) << \"rho_x: \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y: \" << rho_y << \"\\n\"\n       << setw(20) << \"Nx: \" << std::pow(2, J + 2) * rho_x << \"\\n\"\n       << setw(20) << \"Ny: \" << std::pow(2, J + 2) * rho_y << \"\\n\";\n  RDTSCTimer timer;\n\n  timer.start();\n  RidgeletFrame frame(J, J, rho_x, rho_y);\n  double time_frame_constructor = timer.stop();\n  timer.print(cout, time_frame_constructor, \"RidgeletFrame init\");\n\n  const unsigned int ncols = frame.Nx();  // #cols\n  const unsigned int nrows = frame.Ny();  // #rows\n\n  RT_t rt(frame);\n  typedef typename RT_t::rt_coeff_t rt_coeff_t;\n  typedef RidgeletCellArray<rt_coeff_t> rca_t;\n  array_t F(nrows / 2, ncols / 2);\n  const double sigma2 = sigma * sigma;\n  if (vm.count(\"non-smooth\")) {\n    Eigen::ArrayXd x = Eigen::ArrayXd::LinSpaced(ncols / 2, 0, 1);\n    Eigen::ArrayXd y = Eigen::ArrayXd::LinSpaced(nrows / 2, 0, 1);\n    F = x.transpose()\n            .replicate(nrows / 2, 1)\n            .binaryExpr(y.replicate(1, ncols / 2), [sigma2](double x, double y) {\n              return std::exp(-1 / sigma2 * (std::pow(x - 0.5, 2) + std::pow(y - 0.5, 2)));\n            });\n    F = ((x.transpose().replicate(nrows / 2, 1) - 0.5).cwiseAbs() < sigma)\n            .select(F, Eigen::ArrayXXd::Zero(nrows / 2, ncols / 2));\n\n  } else {  // smooth\n    Eigen::ArrayXd x = Eigen::ArrayXd::LinSpaced(ncols / 2, 0, 1);\n    Eigen::ArrayXd y = Eigen::ArrayXd::LinSpaced(nrows / 2, 0, 1);\n    F = x.transpose()\n            .replicate(nrows / 2, 1)\n            .binaryExpr(y.replicate(1, ncols / 2), [sigma2](double x, double y) {\n              return std::exp(-1 / sigma2 * (std::pow(x - 0.5, 2) + std::pow(y - 0.5, 2)));\n            });\n  }\n\n  fft_t fft;\n  // debug\n  complex_array_t Fhh(nrows / 2, ncols / 2);\n  fft.ft(Fhh, F, false);\n  hid_t file;\n  if (vm.count(\"save\")) {\n    file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    eigen2hdf::save(file, \"Fhh\", Fhh);  // debug\n  }\n  // ----------------------------------------\n  complex_array_t Fh(nrows, ncols);\n  Fh.setZero();\n  ftcut(Fh, nrows / 2, ncols / 2) = Fhh;\n  // hf_zero(Fh); // make sure RT projection is real valued\n  rca_t rca(frame);\n  timer.start();\n  cout << \"rt.rt(...)\"\n       << \"\\n\";\n  rt.rt(rca.coeffs(), Fh);\n\n  rca_t rca_copy(frame);\n  rca_copy = rca;\n  auto& rt_coeffs = rca.coeffs();\n\n  int ncoeffs = 0;\n  for (unsigned int i = 0; i < rt_coeffs.size(); ++i) {\n    ncoeffs += rt_coeffs[i].rows() * rt_coeffs[i].cols();\n  }\n  cout << \"dim(rt_coeffs): \" << ncoeffs << \"\\n\";\n  auto time_rt = timer.stop();\n  timer.print(cout, time_rt, \"rt.rt\");\n\n  RCLinearize rcl(frame);\n\n  if (keep < 1) {\n    double tre = rcl.get_threshold(rca, keep);\n    // apply threshold\n    rcl.threshold(rca, tre);\n  }\n\n  // -------------------- Inverse transform --------------------\n  complex_array_t Fh2(nrows, ncols);\n  timer.start();\n  cout << \"rt.irt(...)\"\n       << \"\\n\";\n  rt.irt(Fh2, rt_coeffs);\n  auto time_irt = timer.stop();\n  timer.print(cout, time_irt, \"rt.irt\");\n\n  array_t F2(nrows / 2, ncols / 2);\n  complex_array_t Fh2_cut(nrows / 2, ncols / 2);\n  Fh2_cut.setZero();\n  Fh2_cut = ftcut(Fh2, nrows / 2, ncols / 2);\n  // hf_zero(Fh2_cut);\n  fft.ift(F2, Fh2_cut);\n  auto diff = (F - F2).abs() / (F.rows() * F.cols());\n  cout << \"(F-F2).abs().sum(): \" << diff.sum() << \"\\n\";\n\n  if (vm.count(\"save\")) {\n    eigen2hdf::save(file, \"Fhl\", Fhh);\n    eigen2hdf::save(file, \"Fh\", Fh);\n    eigen2hdf::save(file, \"R\", F);\n    eigen2hdf::save(file, \"Fh2\", Fh2);\n    eigen2hdf::save(file, \"R2\", F2);\n    H5Fclose(file);\n    cout << \"written results to \" << fname << \"\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "58cf7378d3ab4c7f777a9d5a50f0ea6dbb2606e9", "size": 5741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_rt_truncate.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_rt_truncate.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_rt_truncate.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": 32.2528089888, "max_line_length": 94, "alphanum_fraction": 0.581605992, "num_tokens": 1850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5877334809336667}}
{"text": "#include <array>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <math.h>\n#include <Eigen/Dense>\n\nint print_vector_int(std::vector<int> A) {\n   int i;\n   for (i=0; i<A.size(); i=i+1) {\n      std::cout << A[i] <<  \" \" ;\n   }\n   std::cout << \" \" << std::endl;\n   std::cout << \" \" << std::endl;\n   return 0;\n}\n\nint print_vector_double(std::vector<double> A) {\n   int i;\n   for (i=0; i<A.size(); i=i+1) {\n      std::cout << A[i] <<  \" \" ;\n   }\n   std::cout << \" \" << std::endl;\n   std::cout << \" \" << std::endl;\n   return 0;\n}\n\nint print_vector_string(std::vector<std::string> A) {\n   int i;\n   for (i=0; i<A.size(); i=i+1) {\n      std::cout << A[i] << \" \";\n   }\n   std::cout << \" \" << std::endl;\n   std::cout << \" \" << std::endl;\n   return 0;\n}\n\nint print_matrix_int(std::vector<std::vector<int> > A) {\n   int i, j;\n   for (i=0; i<A.size(); i=i+1) {\n      for (j=0; j<A[i].size(); j=j+1) {\n         std::cout << A[i][j] << \" \";\n      }\n      std::cout << \" \" << std::endl;\n   }\n   std::cout << \" \" << std::endl;\n   return 0;\n}\n\nbool fexists(const char *filename) {\n   std::ifstream ifile(filename);\n   return ifile.good();\n}\n\nint if_file_exist_delete (std::string filename) {\n   if (fexists(filename.c_str())) {\n      if (std::remove(filename.c_str()) != 0) {\n          std::cout << \"failed to remove \" << filename << std::endl;\n          exit(1);\n       }\n       else {\n          std::cout << filename << \" found and deleted \" << std::endl;\n       }\n   }\n   return 0;\n}\n\nint x_rotation_matrix (double cosx, double sinx, Eigen::Matrix3d& Rx) {\n\n   Rx(0,0)=1;\n   Rx(0,1)=0;\n   Rx(0,2)=0;\n   Rx(1,0)=0;\n   Rx(1,1)=cosx;\n   Rx(1,2)=-sinx;\n   Rx(2,0)=0;\n   Rx(2,1)=sinx;\n   Rx(2,2)=cosx;\n\n   std::cout << \"Rx \" << Rx << std::endl;\n\n   return 0;\n}\n\nint y_rotation_matrix (double cosy, double siny, Eigen::Matrix3d& Ry) {\n\n   Ry(0,0)=cosy;\n   Ry(0,1)=0;\n   Ry(0,2)=-siny;\n   Ry(1,0)=0;\n   Ry(1,1)=1;\n   Ry(1,2)=0;\n   Ry(2,0)=siny;\n   Ry(2,1)=0;\n   Ry(2,2)=cosy;\n\n   std::cout << \"Ry \" << Ry << std::endl;\n\n   return 0;\n}\n\nint align (Eigen::Vector3d vec_in, Eigen::MatrixXd& coords) {\n\n   double cosx, sinx, cosy, siny;\n   Eigen::Matrix3d Rx, Ry;\n   Eigen::Vector3d vecz;\n   Eigen::MatrixXd coords_t(coords.cols(),coords.rows());\n   coords_t = coords.transpose();\n\n   if (vec_in(0,0) == 0) {\n      if (vec_in(1,0) != 0) { // if vec_in = [0,y,z]\n         \n         // find matrix for rotation about the x-axis:\n         cosx = vec_in(2,0)/sqrt( pow(vec_in(1,0),2) + pow(vec_in(2,0),2) );\n         sinx = vec_in(1,0)/sqrt( pow(vec_in(1,0),2) + pow(vec_in(2,0),2) );\n         x_rotation_matrix(cosx, sinx, Rx);\n\n         // rotate space about the x - axis to bring vec_in\n         // in the xz-plane:\n         coords_t = Rx*coords_t;\n         vecz = Rx*vec_in;\n      }\n      else if (vec_in(1,0) == 0) {// [0,0,z]\n         // all is good\n         vecz = vec_in;\n      }\n   }\n   if (vec_in(1,0) == 0) {\n      if (vec_in(0,0) != 0) { // [x, 0, z]\n         \n         // find matrix for rotation about the y-axis:\n         cosy = vec_in(2,0)/sqrt( pow(vec_in(0,0),2) + pow(vec_in(2,0),2) );\n         siny = vec_in(0,0)/sqrt( pow(vec_in(0,0),2) + pow(vec_in(2,0),2) );\n         y_rotation_matrix (cosy, siny, Ry);\n\n         // rotate space around the y - axis, so that the \n         // rotation axis lies along the positive z - axis:\n         coords_t = Ry*coords_t;\n         vecz = Ry*vec_in; // should have the form [0,0,z]\n      }\n   }\n   if (vec_in(0,0) != 0 ) {\n      if (vec_in(1,0) != 0) { // [x, y, z]\n\n         Eigen::Vector3d vecxz;\n\n         // find matrix for rotation about the x-axis:\n         cosx = vec_in(2,0)/sqrt( pow(vec_in(1,0),2) + pow(vec_in(2,0),2) );\n         sinx = vec_in(1,0)/sqrt( pow(vec_in(1,0),2) + pow(vec_in(2,0),2) );\n         x_rotation_matrix (cosx, sinx, Rx);\n        \n         // rotate space about the x - axis to bring vec_in\n         // in the xz-plane:\n         std::cout << Ry.rows() << Ry.cols() << coords.rows() << coords.cols()    ;\n         coords_t = Rx*coords_t;\n         vecxz = Rx*vec_in;\n        \n         //find matrix for rotation about the y-axis\n         cosy = vecxz(2,0)/sqrt( pow(vecxz(0,0),2) + pow(vecxz(2,0),2) );\n         siny = vecxz(0,0)/sqrt( pow(vecxz(0,0),2) + pow(vecxz(2,0),2) );\n         y_rotation_matrix (cosy, siny, Ry);\n\n         // rotate space around the y - axis, so that the rotation axis lies\n         // along the positive z - axis:\n         std::cout << Ry.rows() << Ry.cols() << coords.rows() << coords.cols();\n         coords_t = Ry*coords_t;\n         vecz = Ry*vecxz; //should have the form [0,0,z]\n      }\n   }\n   coords = coords_t.transpose();\n   std::cout << \"vecz: \" << vecz << std::endl;\n   return 0;\n}\n\nint periodic_table(std::string& lable, double& mass) {\n\n   int k;\n\tstd::vector<std::string> lables{\"C\", \"S\"};\n\tstd::vector<double> masses{12.0107, 32.065};\n\n   std::cout << \"lable: \" << lable << \"end\" << std::endl;\n\n\tfor (k=0; k<lables.size(); k=k+1) {\n      if (lable == lables[k]) {\n         mass = masses[k];\n      }\n   }\n\n   return(0);\n}\n\nint read_input_file(int& nmols, std::vector<std::string>& filenames, \\\n      std::vector<int>& nrings_per_molecule, \\\n      std::vector<std::vector<int>>& rings_atoms) {\n\n   std::string line, temp;\n   char test_char;\n   int nrings_total, nfile, counts, finds_nl, rr, temp_int;\n\n   // check input file:\n   // for line n\n   // if old = m new != f wrong\n   // if old = f new != r wrong\n   // if old = r new != r or m wrong\n   // if wrong cout \"there is a mistake at line n\n\n   //----------------------------------\n   // count number of molecules,\n   // and the total number of rings:\n   //----------------------------------\n\n   std::ifstream inputfile;\n   inputfile.open(\"input\");\n   nmols = 0;\n   finds_nl = 0; // finds new line\n   nrings_total = 0;\n   while (!inputfile.eof()) {\n      inputfile.get(test_char);\n      if (finds_nl == 0) { // if this is the first character in the line\n         if (test_char == 'm') { // and the first character is 'm'\n            nmols = nmols + 1;\n         }\n         if (test_char == 'r') {\n            nrings_total = nrings_total + 1;\n         }\n      }\n      finds_nl = finds_nl + 1; // because it's probably not the\n                                       // end of the line\n      if (test_char == '\\n') { // though, if it is the end of the line:\n         finds_nl = 0;\n      }\n   }\n   std::cout << \"nrings total: \" << nrings_total << std::endl;\n\n   //---------------------------------------------\n   // get the filenames of the molecules,\n   // count the total numbers of rings, and the\n   // number of rings per molecule:\n   //---------------------------------------------\n\n   filenames.resize(nmols);\n   nrings_per_molecule.resize(nmols);\n   rings_atoms.resize(nrings_total);\n   nfile = -1; // because c++ array numbering starts from 0\n   rr = 0; // the current ring being read\n   finds_nl = 0; // finds new line\n   inputfile.clear(); // To clear the EOF from previously\n   inputfile.seekg(0, std::ios::beg); // set to beggining of file\n   while (!inputfile.eof()) {\n      inputfile.get(test_char);\n      if (finds_nl == 0) { // if this is the first character in the line\n         if (test_char == 'm') { // we have a new molecule\n            nfile = nfile + 1;\n            nrings_per_molecule[nfile] = 0; // initialize to 0 rings\n         }\n         if (test_char == 'f') { // the filename of the new molecule is\n                                 // written here\n            getline(inputfile,line); // get this line\n            std::stringstream ssin(line); // break up line in string stream\n            counts = 1;\n            while (ssin.good()){\n               ssin >> temp;\n               if (counts = 2) {\n                  filenames[nfile] = temp;\n               }\n               counts = counts + 1;\n            }\n            // go back by 1 character so that get reads '\\n' from\n            // this line which was read by getline:\n            inputfile.seekg(-1, std::ios::cur);\n         }\n         if (test_char == 'r') { \n            // there is another ring for this molecule:\n            nrings_per_molecule[nfile] = nrings_per_molecule[nfile] + 1;\n            // get the atoms that make up this ring\n            getline(inputfile,line); // get this line\n            std::stringstream ssin(line); // break up line in string stream\n            counts = 1;\n            while (ssin.good()){\n               ssin >> temp;\n               std::cout << temp << \" \";\n               if (counts > 1) {\n                  temp_int = std::atoi(temp.c_str());\n                  rings_atoms[rr].push_back(temp_int);\n               }\n               counts = counts + 1;\n            }\n            std::cout << \" \" << std::endl;\n            // move on to next ring\n            rr = rr + 1;\n            // go back by 1 character so that get reads '\\n' from\n            // this line which was read by getline:\n            inputfile.seekg(-1, std::ios::cur);\n         }\n      }\n      finds_nl = finds_nl + 1; // because it's probably not the\n                                       // end of the line\n      if (test_char == '\\n') { // though, if it is the end of the line:\n         finds_nl = 0;\n      }\n   }\n\n   inputfile.close();\n   return 0;\n}\n", "meta": {"hexsha": "e17ceb076c88a6530544834dc23074f4db762f7d", "size": 9270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "using_inertia_tensor/NICS-module.cpp", "max_stars_repo_name": "ElenaKusevska/NICS_prepare_input", "max_stars_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "using_inertia_tensor/NICS-module.cpp", "max_issues_repo_name": "ElenaKusevska/NICS_prepare_input", "max_issues_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "using_inertia_tensor/NICS-module.cpp", "max_forks_repo_name": "ElenaKusevska/NICS_prepare_input", "max_forks_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0, "max_line_length": 83, "alphanum_fraction": 0.5078748652, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5875044163983255}}
{"text": "/*\n * Matrix-vector multiply\n *\n * Information on Intel vector pragmas is available in the following link:\n * https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-vector-1#58209E46-70EA-4C47-BED6-E69236C6680C\n */\n\n// https://en.cppreference.com/w/cpp/memory/c/aligned_alloc\n#include <cstdlib>  // aligned_alloc (C++11), std::aligned_alloc (C++17)\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <boost/align/aligned_allocator.hpp>\n#include <cmath>\n// #include \"papi.h\"\n#include \"simd.h\"\n#include \"environ.h\"\n#include \"utils.h\"\n#include \"vutils.h\"\n\n\n///////////////////////////////////////////////////////////////////////////////\n// USER CONFIGURATION\n///////////////////////////////////////////////////////////////////////////////\n// Square matrix dimension\nconst size_t N = 6;\n\n// Precision for floating-point operations\n// Valid values are: 4, 8\n#define REAL_TYPE 4\n\n\n///////////////////////////////////////////////////////////////////////////////\n// FP and SIMD\n///////////////////////////////////////////////////////////////////////////////\n// Precision for floating-point operations\n#if REAL_TYPE == 4\ntypedef float real;\ntypedef SIMD_FLT vreal;\n#elif REAL_TYPE == 8\ntypedef double real;\ntypedef SIMD_DBL vreal;\n#endif\n\n// Number of floating-point values that fit into a SIMD register\nconst int SIMD_STREAMS = SIMD_WIDTH_BYTES / sizeof(real);\nconst int LOG2STREAMS = std::log2(SIMD_STREAMS);\n\n\n///////////////////////////////////////////////////////////////////////////////\n// PROGRAM\n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename T>\nusing aligned_vector = std::vector<T, boost::alignment::aligned_allocator<T, SIMD_WIDTH_BYTES>>;\n\n\nvoid gemv(\n    const size_t n,\n    const size_t lda,\n    const aligned_vector<real> v1,\n    const aligned_vector<real> v2,\n    aligned_vector<real> &dp)\n{\n    for (size_t row = 0; row < n; row++) {\n        for (size_t col = 0; col < n; col++) {\n            dp[row] += v1[row * lda + col] * v2[col];\n        }\n    }\n}\n\n\nvoid gemv_simd_tree_sum(\n    const size_t n,\n    const size_t lda,\n    const real *v1,\n    const real *v2,\n    real *dp)\n{\n    // const real *_v1 = v1; __SIMD_ASSUME_ALIGNED__(v1);\n    // const real *_v2 = v2; __SIMD_ASSUME_ALIGNED__(v2);\n    const real *_v1 = (real *)__SIMD_ASSUME_ALIGNED__(v1);\n    const real *_v2 = (real *)__SIMD_ASSUME_ALIGNED__(v2);\n\n    for (size_t row = 0; row < n; row++) {\n        vreal vdp;\n        simd_set_zero(&vdp);\n        for (size_t col = 0; col < lda; col+=SIMD_STREAMS) {\n            vreal vv1 = simd_load(&_v1[row * lda + col]);\n            vreal vv2 = simd_load(&_v2[col]);\n            vdp = simd_fmadd(vv1, vv2, vdp);\n        }\n\n        // Binary tree sum reduction\n        for (size_t i = 0; i < LOG2STREAMS - 1; i++) {\n            vdp = simd_hadd(vdp, vdp);\n        }\n\n        real tdp[SIMD_STREAMS] __SIMD_ALIGN__;\n        simd_store(tdp, vdp);\n        // NOTE: 'dp' does need to be aligned because it is used to store a scalar value.\n        if (SIMD_WIDTH_BYTES == 16) {\n            // HADD from SSE3 does not interleave horizontal sums.\n            dp[row] = tdp[0] + tdp[1];\n        } else if (SIMD_WIDTH_BYTES == 32) {\n            dp[row] = tdp[0] + tdp[SIMD_STREAMS / 2];\n        }\n    }\n}\n\n\nvoid print_matrix(\n    const size_t n,\n    const size_t m,\n    const size_t lda,\n    const real *v)\n{\n    for (size_t row = 0; row < n; row++) {\n        for (size_t col = 0; col < m; col++) {\n            std::cout << v[row * lda + col] << \", \";\n        }\n        std::cout << std::endl;\n    }\n\n}\n\n\nint main(int argc, char *argv[])\n{\n    size_t num_matrices = 1;\n    if (argc > 1) {\n        num_matrices = std::atoi(argv[1]);\n    }\n\n    detectCPU();\n    detectSIMD();\n\n    std::cout << \"Alignment: \" << SIMD_WIDTH_BYTES << std::endl;\n    std::cout << \"Num. elems: \" << SIMD_STREAMS << std::endl;\n    std::cout << \"Log2 SIMD: \" << LOG2STREAMS << std::endl;\n\n    // Number of elements in padded matrix column to conform with SIMD alignment\n    const size_t lda = (((N * sizeof(real)) / SIMD_WIDTH_BYTES) * SIMD_WIDTH_BYTES + SIMD_WIDTH_BYTES) / sizeof(real);\n    // For unaligned rows, set LDA to N\n    // const size_t lda = N;\n\n    // Create a vector of given size\n    aligned_vector<real> v1(N * lda);      // matrix\n    aligned_vector<real> v2(1 * lda, 1.);  // column vector, set to 1 --> add rows of matrix\n    aligned_vector<real> dp(N, 0.);  // resulting column vector (dot products)\n\n    // Zero out extra rows used for padding, to prevent floating-point exception during vector multiplication.\n    // This memory elements are never modified, so set once.\n    std::memset(v2.data() + N, 0, (lda - N) * sizeof(real));\n\n    // real *v1 = NULL;\n    // real *v2 = NULL;\n    // real *dp = NULL;\n    // scalar_malloc(&v1, SIMD_WIDTH_BYTES, N * lda);\n    // scalar_malloc(&v2, SIMD_WIDTH_BYTES, 1 * lda);\n    // scalar_malloc(&dp, SIMD_WIDTH_BYTES, N);\n\n    for (size_t k = 0; k < num_matrices; k++) {\n\n        // Initialize vector\n        for (size_t row = 0; row < N; row++) {\n            for (size_t col = 0; col < N; col++) {\n                v1[row * lda + col] = k + 1. * (row + col);\n            }\n        }\n\n#if defined(DEBUG)\n        // Print matrix and vector\n        std::cout << \"Matrix:\" << std::endl;\n        print_matrix(N, lda, lda, v1.data());\n        std::cout << std::endl;\n\n        std::cout << \"Vector:\" << std::endl;\n        print_matrix(lda, 1, 1, v2.data());\n        std::cout << std::endl;\n#endif\n\n        // Matrix-vector multiply\n        gemv_simd_tree_sum(N, lda, v1.data(), v2.data(), dp.data());\n        gemv(N, lda, v1, v2, dp);\n\n#if defined(DEBUG)\n        // Print resulting column vector\n        std::cout << \"Result:\" << std::endl;\n        print_matrix(N, 1, 1, dp.data());\n        std::cout << std::endl;\n#endif\n    }\n\n    std::cout << \"Matrix size: \" << N << \" x \" << lda << std::endl;\n\n    // Only needed if this array was allocated using 'scalar_malloc'.\n    // scalar_free(&v1);\n    // scalar_free(&v2);\n    // scalar_free(&dp);\n}\n", "meta": {"hexsha": "b2b1f703c6fa5dbecd3944c2c44d0d702328cae8", "size": 6077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/small_gemv/gemv.cpp", "max_stars_repo_name": "edponce/libsimdcpp", "max_stars_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T04:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T10:07:25.000Z", "max_issues_repo_path": "examples/small_gemv/gemv.cpp", "max_issues_repo_name": "edponce/libsimdcpp", "max_issues_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/small_gemv/gemv.cpp", "max_forks_repo_name": "edponce/libsimdcpp", "max_forks_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_forks_repo_licenses": ["BSD-3-Clause", "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.0841584158, "max_line_length": 124, "alphanum_fraction": 0.5466513082, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303137346446, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5874968345091633}}
{"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 * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup trigo_constant\n * \\defgroup trigo_constant_radindeg Radindeg\n *\n * \\par Description\n * Constant Radindeg : Degree in radian multiplier, \\f$\\frac{180}\\pi\\f$.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/radindeg.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::_radindeg_(A0)>::type\n *     Radindeg();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Radindeg\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    BOOST_SIMD_CONSTANT_REGISTER( Radindeg, double\n                                , 57, 0x42652ee1\n                                , 0x404ca5dc1a63c1f8ll\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Radindeg, Radindeg);\n}\n\nnamespace nt2\n{\n  static const long double long_radindeg =  57.295779513082320876798154814105l;\n}\n\n#endif\n", "meta": {"hexsha": "027e391a499c9bf4c88b7ddc85efb7db97c4d8e7", "size": 1672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/radindeg.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.231884058, "max_line_length": 80, "alphanum_fraction": 0.5741626794, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.5874968336799076}}
{"text": "/*\n * Copyright 2020 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n */\n\n/*\n * File:   CartesianToGeodeticFukushima.hpp\n * Author: jordan\n */\n\n#ifndef CARTESIANTOGEODETICFUKUSHIMA_HPP\n#define CARTESIANTOGEODETICFUKUSHIMA_HPP\n\n#ifdef _WIN32\n#define _USE_MATH_DEFINES\n#include <math.h>\n#else\n#include <cmath>\n#endif\n\n#include <vector>\n#include <Eigen/Dense>\n#include \"../Position.hpp\"\n#include \"../utils/Constants.hpp\"\n\nclass CartesianToGeodeticFukushima {\n    /*\n     * This class implements the method given in Fukushima (2006):\n     *\n     * Transformation from Cartesian to geodetic coordinates\n     * accelerated by Halley's method\n     * DOI: 10.1007/s00190-006-0023-2\n     */\nprivate:\n\n    unsigned int numberOfIterations;\n\n    // Ellipsoid parameters\n    double a; // semi-major axis\n    double e2; // first eccentricity squared\n\n    // Derived parameters\n    double b; // semi-minor axis\n    double a_inverse; // 1/a\n    double ec; // sqrt(1 - e*e)\n\npublic:\n\n    CartesianToGeodeticFukushima(unsigned int numberOfIterations, double a=a_wgs84, double e2=e2_wgs84) :\n    numberOfIterations(numberOfIterations), a(a), e2(e2) {\n        ec = std::sqrt(1 - e2);\n        b = a*ec;\n        a_inverse = 1 / a;\n    }\n\n    ~CartesianToGeodeticFukushima() {};\n\n    void ecefToLongitudeLatitudeElevation(Eigen::Vector3d & ecefPosition, Position & positionGeographic) {\n        double x = ecefPosition(0);\n        double y = ecefPosition(1);\n        double z = ecefPosition(2);\n\n        // Center of the Earth\n        if (x == 0.0 && y == 0.0 && z == 0.0) {\n            positionGeographic.setLatitude(0.0);\n            positionGeographic.setLongitude(0.0);\n            positionGeographic.setEllipsoidalHeight(0.0);\n            return;\n        }\n\n        // Position at Poles\n        if (x == 0.0 && y == 0.0 && z != 0.0) {\n            if (z > 0) {\n                positionGeographic.setLatitude(M_PI_2*R2D);\n            } else {\n                positionGeographic.setLatitude(-M_PI_2*R2D);\n            }\n\n            positionGeographic.setLongitude(0.0);\n            positionGeographic.setEllipsoidalHeight(std::abs(z) - b);\n            return;\n        }\n        \n        double pp = x * x + y * y;\n        double p = std::sqrt(pp);\n\n        // Position at Equator\n        if (z == 0.0) {\n            positionGeographic.setLatitude(0.0);\n            positionGeographic.setLongitude(estimateLongitude(x, y, p)*R2D);\n            positionGeographic.setEllipsoidalHeight(std::sqrt(x * x + y * y) - a);\n            return;\n        }\n\n        double P = p*a_inverse;\n        double Z = a_inverse * ec * std::abs(z);\n\n        //double R = std::sqrt(pp + z * z);\n        std::vector<double> S(numberOfIterations + 1, 0);\n        std::vector<double> C(numberOfIterations + 1, 0);\n\n        std::vector<double> D(numberOfIterations + 1, 0);\n        std::vector<double> F(numberOfIterations + 1, 0);\n\n        std::vector<double> A(numberOfIterations + 1, 0);\n        std::vector<double> B(numberOfIterations + 1, 0);\n\n        S[0] = Z; //starter variables. See (Fukushima, 2006) p.691 equation (17)\n        C[0] = ec*P; //starter variables. See (Fukushima, 2006) p.691 equation (17)\n        A[0] = std::sqrt(S[0] * S[0] + C[0] * C[0]);\n        B[0] = 1.5 * e2 * e2 * P * S[0] * S[0] * C[0] * C[0] * (A[0] - ec); //starter variables. See (Fukushima, 2006) p.691 equation  (18)\n\n        unsigned int iterationNumber = 1;\n\n        while (iterationNumber <= numberOfIterations) {\n\n            D[iterationNumber - 1] =\n                    Z * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] +\n                    e2 * S[iterationNumber - 1] * S[iterationNumber - 1] * S[iterationNumber - 1];\n            F[iterationNumber - 1] =\n                    P * A[iterationNumber - 1] * A[iterationNumber - 1] * A[iterationNumber - 1] -\n                    e2 * C[iterationNumber - 1] * C[iterationNumber - 1] * C[iterationNumber - 1];\n\n            S[iterationNumber] =\n                    D[iterationNumber - 1] * F[iterationNumber - 1] -\n                    B[iterationNumber - 1] * S[iterationNumber - 1];\n            C[iterationNumber] =\n                    F[iterationNumber - 1] * F[iterationNumber - 1] -\n                    B[iterationNumber - 1] * C[iterationNumber - 1];\n\n            A[iterationNumber] = std::sqrt(\n                    S[iterationNumber] * S[iterationNumber] +\n                    C[iterationNumber] * C[iterationNumber]);\n\n            B[iterationNumber] =\n                    1.5 *\n                    e2 * S[iterationNumber] *\n                    C[iterationNumber] * C[iterationNumber] *\n                    ((P * S[iterationNumber] - Z * C[iterationNumber]) * A[iterationNumber] -\n                    e2 * S[iterationNumber] * C[iterationNumber]);\n\n            ++iterationNumber;\n        }\n\n        double lon = estimateLongitude(x, y, p);\n\n        double Cc = ec*C[numberOfIterations];\n        double lat = estimateLatitude(z, S[numberOfIterations], Cc);\n        double h = estimateHeight(z, p, A[numberOfIterations], S[numberOfIterations], Cc);\n\n        positionGeographic.setLatitude(lat*R2D);\n        positionGeographic.setLongitude(lon*R2D);\n        positionGeographic.setEllipsoidalHeight(h);\n    }\n\n    double estimateLongitude(double x, double y, double p) {\n        // Vermeille (2004), stable longitude calculation\n        // atan(y/x) suffers when x = 0\n\n        if (y < 0) {\n            return -M_PI_2 + 2*std::atan(x/(p - y));\n        }\n\n        return M_PI_2 - 2*std::atan(x/(p + y));\n    }\n\n    double estimateLatitude(double z, double S, double Cc) {\n        double lat = std::abs(std::atan(S / Cc));\n\n        if (z < 0) {\n            return -lat;\n        }\n\n        return lat;\n    }\n\n    double estimateHeight(double z, double p, double A, double S, double Cc) {\n        return (p * Cc + std::abs(z) * S - b * A) / std::sqrt(Cc * Cc + S * S);\n    }\n};\n\n#endif /* CARTESIANTOGEODETICFUKUSHIMA_HPP */\n", "meta": {"hexsha": "27eee5181ee98dc3d63b1216c64d059f9b5afdba", "size": 5995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/CartesianToGeodeticFukushima.hpp", "max_stars_repo_name": "JordanMcManus/MBES-lib", "max_stars_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/math/CartesianToGeodeticFukushima.hpp", "max_issues_repo_name": "JordanMcManus/MBES-lib", "max_issues_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/math/CartesianToGeodeticFukushima.hpp", "max_forks_repo_name": "JordanMcManus/MBES-lib", "max_forks_repo_head_hexsha": "618d64f4e042bf5660015819f89537cdd70e696d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 32.9395604396, "max_line_length": 139, "alphanum_fraction": 0.5684737281, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363299661721, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5874014449988688}}
{"text": "/*\n    $ sudo apt-get install libboost-math*\n\n    real   4m15.388s\n    user    4m10.272s\n    sys 0m0.588s\n*/\n\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\n\nstruct Result {\n    boost::numeric::ublas::matrix<int> A;\n    boost::numeric::ublas::matrix<int> B;\n};\n\nint getMatrixSize(string filename) {\n    string line;\n    ifstream infile;\n    infile.open (filename.c_str());\n    getline(infile, line);\n    return count(line.begin(), line.end(), '\\t') + 1;\n}\n\nvoid printMatrix(boost::numeric::ublas::matrix<int> matrix) {\n    for (unsigned int i=0; i < matrix.size1(); i++) {\n        for (unsigned int j=0; j < matrix.size2(); j++) {\n            cout << matrix(i, j);\n            if(j+1 != matrix.size2()) {\n                cout << \"\\t\";\n            }    \n        }\n        cout << endl;\n    }\n}\n\nResult read(string filename) {\n    Result ab;\n    string line;\n    ifstream infile;\n    infile.open (filename.c_str());\n\n    // get dimension\n    getline(infile, line);\n    int n = getMatrixSize(filename);\n\n    boost::numeric::ublas::matrix<int> A(n,n), B(n,n);\n\n    // process first line\n    istringstream iss(line);\n    int a, i = 0, j = 0;\n    while (iss >> a) {\n        A(i,j) = a;\n        j++;\n    }\n    i++;\n\n    while (getline(infile, line) &amp;&amp; !line.empty()) {\n        istringstream iss(line);\n        j = 0;\n        while (iss >> a) {\n            A(i,j) = a;\n            j++;\n        }\n        i++;\n    }\n\n    i = 0;\n    while (getline(infile, line)) {\n        istringstream iss(line);\n        j = 0;\n        while (iss >> a) {\n            B(i,j) = a;\n            j++;\n        }\n        i++;\n    }\n\n    infile.close();\n    ab.A = A;\n    ab.B = B;\n    return ab;\n}\n\nint main (int argc, char* argv[]) {\n    string filename;\n    if (argc < 3) {\n        filename = \"2000.in\";\n    } else {\n        filename = argv[2];\n    }\n    Result result = read (filename);\n\n    boost::numeric::ublas::matrix<int> C;\n    C = boost::numeric::ublas::prod(result.A, result.B);\n    printMatrix(C);\n\n    return 0;\n}", "meta": {"hexsha": "a1a1f66780f40f34c11f0f6e09ef33f7ac13799a", "size": 2151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "P4/c++/secuencial/libraryboost.cpp", "max_stars_repo_name": "romanarranz/AC", "max_stars_repo_head_hexsha": "509810007777b2cf261608f4492ae675105a1793", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "P4/c++/secuencial/libraryboost.cpp", "max_issues_repo_name": "romanarranz/AC", "max_issues_repo_head_hexsha": "509810007777b2cf261608f4492ae675105a1793", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "P4/c++/secuencial/libraryboost.cpp", "max_forks_repo_name": "romanarranz/AC", "max_forks_repo_head_hexsha": "509810007777b2cf261608f4492ae675105a1793", "max_forks_repo_licenses": ["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.2924528302, "max_line_length": 61, "alphanum_fraction": 0.5165039517, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5873380590371207}}
{"text": "/**\n * \\file SecondOrderSVFFilter.cpp\n */\n\n#include \"SecondOrderSVFFilter.h\"\n\n#include <cassert>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename SVFCoefficients>\n  struct SecondOrderSVFFilter<SVFCoefficients>::SVFState\n  {\n    typename SVFCoefficients::DataType iceq1;\n    typename SVFCoefficients::DataType iceq2;\n    \n    SVFState()\n    :iceq1(0), iceq2(0)\n    {\n    }\n  };\n  \n  template<typename SVFCoefficients>\n  SecondOrderSVFFilter<SVFCoefficients>::SecondOrderSVFFilter(int nb_channels)\n  :SVFCoefficients(nb_channels), state(new SVFState[nb_channels])\n  {\n  }\n\n  template<typename SVFCoefficients>\n  SecondOrderSVFFilter<SVFCoefficients>::~SecondOrderSVFFilter()\n  {\n  }\n\n  template<typename SVFCoefficients>\n  void SecondOrderSVFFilter<SVFCoefficients>::full_setup()\n  {\n    state.reset(new SVFState[nb_input_ports]);\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFFilter<DataType>::process_impl(int64_t size) const\n  {\n    assert(nb_input_ports == nb_output_ports);\n    \n    for(int j = 0; j < nb_input_ports; ++j)\n    {\n      const DataType* ATK_RESTRICT input = converted_inputs[j];\n      DataType* ATK_RESTRICT output = outputs[j];\n      \n      for(int64_t i = 0; i < size; ++i)\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  SecondOrderSVFBaseCoefficients<DataType>::SecondOrderSVFBaseCoefficients(int nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels), cut_frequency(0), Q(1)\n  {\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFBaseCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType SecondOrderSVFBaseCoefficients<DataType>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFBaseCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    this->Q = Q;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType SecondOrderSVFBaseCoefficients<DataType>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType_>\n  SecondOrderSVFLowPassCoefficients<DataType_>::SecondOrderSVFLowPassCoefficients(int nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFLowPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFBandPassCoefficients<DataType_>::SecondOrderSVFBandPassCoefficients(int nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFBandPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFHighPassCoefficients<DataType_>::SecondOrderSVFHighPassCoefficients(int nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFHighPassCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFNotchCoefficients<DataType_>::SecondOrderSVFNotchCoefficients(int nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFNotchCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFPeakCoefficients<DataType_>::SecondOrderSVFPeakCoefficients(int nb_channels)\n  :Parent(nb_channels)\n  {\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFPeakCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFBellCoefficients<DataType_>::SecondOrderSVFBellCoefficients(int nb_channels)\n  :Parent(nb_channels), gain(0)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void SecondOrderSVFBellCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType SecondOrderSVFBellCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFBellCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFLowShelfCoefficients<DataType_>::SecondOrderSVFLowShelfCoefficients(int nb_channels)\n  :Parent(nb_channels), gain(0)\n  {\n    \n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFLowShelfCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType SecondOrderSVFLowShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFLowShelfCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  SecondOrderSVFHighShelfCoefficients<DataType_>::SecondOrderSVFHighShelfCoefficients(int nb_channels)\n  :Parent(nb_channels), gain(0)\n  {\n  }\n\n  template<typename DataType_>\n  void SecondOrderSVFHighShelfCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template<typename DataType>\n  DataType SecondOrderSVFHighShelfCoefficients<DataType>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  void SecondOrderSVFHighShelfCoefficients<DataType>::setup()\n  {\n    auto g = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\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  template class SecondOrderSVFBaseCoefficients<float>;\n  template class SecondOrderSVFBaseCoefficients<double>;\n\n  template class SecondOrderSVFLowPassCoefficients<float>;\n  template class SecondOrderSVFLowPassCoefficients<double>;\n  template class SecondOrderSVFBandPassCoefficients<float>;\n  template class SecondOrderSVFBandPassCoefficients<double>;\n  template class SecondOrderSVFHighPassCoefficients<float>;\n  template class SecondOrderSVFHighPassCoefficients<double>;\n  template class SecondOrderSVFNotchCoefficients<float>;\n  template class SecondOrderSVFNotchCoefficients<double>;\n  template class SecondOrderSVFPeakCoefficients<float>;\n  template class SecondOrderSVFPeakCoefficients<double>;\n  template class SecondOrderSVFBellCoefficients<float>;\n  template class SecondOrderSVFBellCoefficients<double>;\n  template class SecondOrderSVFLowShelfCoefficients<float>;\n  template class SecondOrderSVFLowShelfCoefficients<double>;\n  template class SecondOrderSVFHighShelfCoefficients<float>;\n  template class SecondOrderSVFHighShelfCoefficients<double>;\n\n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBandPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighPassCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFNotchCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFPeakCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFBellCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFLowShelfCoefficients<double> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<float> >;\n  template class SecondOrderSVFFilter<SecondOrderSVFHighShelfCoefficients<double> >;\n}\n", "meta": {"hexsha": "b8a533e4a17a21b0edf3aacadb2329973e07b89d", "size": 9640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/SecondOrderSVFFilter.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/SecondOrderSVFFilter.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/SecondOrderSVFFilter.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": 29.4801223242, "max_line_length": 102, "alphanum_fraction": 0.7107883817, "num_tokens": 2746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5871840190385398}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <fstream>\n#include <iostream>\n#include <omp.h>\n#include <cmath>\n#include <cstdio>\n#include <chrono>\n#include <string>\n#include <armadillo>\n#include <vector>\n#include \"wigner/gaunt.hpp\"\n\nusing namespace std::chrono;\nusing namespace arma;\n\nstatic const double kB = 1.3806504e-23;         // J/K\nstatic const double NA = 6.02214179e23;         // 1/mol\nstatic const double EHARTREE = 4.35974434e-18;  // J/Hartree\nstatic const double AMU = 1.660538921e-27;      // kg/amu\nstatic const double HBAR = 1.054571726e-34;     // J.s\nstatic const double HBAR1 = HBAR / EHARTREE;    // Hartree.s\nstatic const double HBAR2 = HBAR * 1e20 / AMU;  // amu.Å^2/s\nstatic const double SCH4 = 186.25; // J/mol.K\n\nMat<double> getHamiltonian(int lmax, double Ix, double Iy, double Iz) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number for the spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*Å^2\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    std::cout << \"Lmax = \" << lmax << std::endl;\n    double size = (double(1.0/3.0)*(lmax+1)*(2*lmax+1)*(2*lmax+3));\n    std::cout << \"Dimensions of the matrix: \" << size << std::endl;\n    Mat<double> H = zeros<mat>(size+1, size+1);\n    //SpMat<double> H = sp_mat(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n\n    double kap;\n    if (A == B && A == C) {     //SPHERICAL ROTOR\n        kap = 0;\n    } else {\n        kap = (2.0*B - (A + C)) / (A - C);\n    }\n\n    std::cout << \"kappa val is \" << kap << \".\" << std::endl;\n    #pragma omp parallel\n    {\n        double g;\n        double a;\n        #pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    unsigned long long j = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    //std::cout << j << '\\t';\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                unsigned long long i = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0)\n                                    + 2*mm*ell + mm + kk;\n                                //if (j < i) {\n                                //    continue;\n                                //} else {\n                                //    H(i,j) += 1;\n                                //}\n                                if (i == j) {\n                                    try {\n                                        //H(i,j) += B*el*(el+1);\n                                        H(i,j) += 0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k;\n                                        if (k-2 >= -el) {\n                                            H(i-2,j) += 0.25*(C-A)*sqrt(el*(el+1)-k*(k-1))*sqrt(el*(el+1)-(k-1)*(k-2));\n                                            if (abs(double(j - i+2)) != 2) {\n                                                std::cout << \"(i-2, j) index spacing incorrect @ (\" << i-2 << ',' << j << \") --> (\" \n                                                    << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n\n                                        }\n                                        if (k+2 <= el) {\n                                            H(i+2,j) += 0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2));\n                                            if (abs(double(i+2 - j)) != 2) {\n                                                std::cout << \"(i+2, j) index spacing incorrect @ (\" << i+2 << ',' << j << \") --> (\" \n                                                    << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n\n                                        }\n                                    } catch (const std::exception& e) {\n                                        std::cout << \"Failure at index: \" <<\n                                            i << \"\\t(\" << el << ',' << m << ',' <<\n                                            k << ')' << std::endl;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    } // end parallel\n    std::cout << std::endl;\n    //H.print(\"H = \");\n    return H;\n}\n\nSpMat<double> getSparseHam(int lmax, double Ix, double Iy, double Iz) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number for the spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*Å^2\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    std::cout << \"Lmax = \" << lmax << std::endl;\n    double size = (double(1.0/3.0)*(lmax+1)*(2*lmax+1)*(2*lmax+3));\n    std::cout << \"Dimensions of the sparse matrix: \" << size << std::endl;\n    SpMat<double> H = sp_mat(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n\n    double kap;\n    if (A == B && A == C) {     //SPHERICAL ROTOR\n        kap = 0;\n    } else {\n        kap = (2.0*B - (A + C)) / (A - C);\n    }\n    #pragma omp parallel\n    {\n        double g;\n        double a;\n        #pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    unsigned long long j = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    //std::cout << j << '\\t';\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                unsigned long long i = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0)\n                                    + 2*mm*ell + mm + kk;\n                                //if (j < i) {\n                                //    continue;\n                                //} else {\n                                //    H(i,j) += 1;\n                                //}\n                                if (i == j) {\n                                    try {\n                                        //H(i,j) += B*el*(el+1);\n                                        H(i,j) += 0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k;\n                                        if (k-2 >= -el) {\n                                            H(i-2,j) += 0.25*(C-A)*sqrt(el*(el+1)-k*(k-1))*sqrt(el*(el+1)-(k-1)*(k-2));\n                                            if (isnan(H(i-2,j))) {\n                                                std:: cout << \"NaN @ (\" << i-2 << ',' << j << \") --> (\" << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n                                            if (abs(double(j - i+2)) != 2) {\n                                                std::cout << \"Index spacing incorrect @ (\" << i-2 << ',' << j << \") --> (\" << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n                                        }\n                                        if (k+2 <= el) {\n                                            H(i+2,j) += 0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2));\n                                            if (isnan(H(i+2,j))) {\n                                                std:: cout << \"NaN @ (\" << i+2 << ',' << j << \") --> (\" << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n                                            if (abs(double(i+2 - j)) != 2) {\n                                                std::cout << \"Index spacing incorrect @ (\" << i+2 << ',' << j << \") --> (\" << el << ',' << m << ',' << k << ')' << std::endl;\n                                            }\n                                        }\n                                    } catch (const std::exception& e) {\n                                        std::cout << \"Failure at index: \" <<\n                                            i << \"\\t(\" << el << ',' << m << ',' <<\n                                            k << ')' << std::endl;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    } // end parallel\n    return H;\n}\n\n\nstd::string getDirectory(std::string sysname) {\n    std::string dirname = \"/Users/lancebettinson/Thesis/umrr/code/hamiltonian-cpp/data\";\n    if (sysname == \"\") {\n        std::string sysname;\n        std::cout << \"Enter system name:\" << std::endl;\n        std::cin >> sysname;\n    }\n    return dirname+'/'+sysname;\n}\n\nCol<double> getCoefficients(std::string sysname) {\n    std::string dirname = getDirectory(sysname);\n    std::string filename = dirname+'/'+\"vdat.txt\";\n    std::ifstream is(filename);\n    if (is.fail())\n    {\n        std::cout << \"cannot open file \" << filename;\n    }\n    double theta, phi, v;\n    std::vector<double> my_vec;\n    while (is) {\n        if (!(is >> theta >> phi >> v)) {\n            break;\n        }\n        //std::cout << theta << '\\t' << phi << '\\t' << v << std::endl;\n        my_vec.push_back(v);\n    }\n    Col<double> cvec = conv_to<vec>::from(my_vec);\n    //cvec.print();\n    is.close();\n    return cvec;\n}\n\nstd::vector<double> getMomentOfInertia(std::string sysname=\"METH-CHA\") {\n    std::string dirname = getDirectory(sysname);\n    std::string filename = dirname+'/'+\"I.txt\";\n    std::ifstream is(filename);\n    double val;\n    std::vector<double> Ivec;\n    while (is) {\n        if (!(is >> val)) {\n            break;\n        }\n        Ivec.push_back(val);\n    }\n    return Ivec;\n}\n\ndouble getPartitionFunction(double T, Mat<double>& H, int sym=1) {\n    /* Solve the Eigenvalues\n     * Inputs:  T;  the temperature [=] K\n     *          H;  the Hamiltonian matrix [=] Hartree\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n\n    //Col<double> eigval = eig_sym(H);\n    //double Q = 0;\n    ////b = 1;\n    //int count = 0;\n    //for (double e : eigval) {\n    //    Q += exp(-b * e);\n    //}\n    //for (double e : eigval) {\n    //    if (count == 5) {\n    //        //std::cout << std::endl;\n    //    } //std::cout << exp(-b*e)/Q << '\\t';\n    //    count++;\n    //}\n    //std::cout << std::endl << \"Q predicted by eig_sym: \" << Q/sym << std::endl;\n    Mat<double> bH = -b*H;\n    Mat<double> expbH = expmat_sym(bH);\n    double tr = trace(expbH);\n    std::cout << pow(b,-1) << std::endl;\n    std::cout << std::endl << \"Q predicted by eig_sym: \" << tr/sym << std::endl;\n    return double(tr/sym);\n    //return double(Q/sym);\n}\n\ndouble getSparseQ(double T, SpMat<double>& H, int sym=1) {\n    /* Solve the Eigenvalues for Sparse Matrix\n     * Inputs:  T;  the temperature [=] K\n     *          H;  the (sparse) Hamiltonian matrix [=] Hartree\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n    //SpMat<double> bH = -b*H;\n\n    vec eigval;\n    mat eigvec;\n    \n    std::cout << \"Number of rows: \" << H.n_rows << std::endl;\n    eigs_sym(eigval, eigvec, H, H.n_rows-1);\n    double Q = 0;\n    std::cout << \"Eigenvalues: \" << std::endl;\n    for (double e : eigval) {\n        std::cout << e << '\\t';\n        Q += exp(-b * e);\n    }\n    std::cout << std::endl;\n    std::cout << \"Q predicted by eigs_sym: \" << Q/sym << std::endl;\n    return double(Q/sym);\n}\n\nint main() {\n    auto start = high_resolution_clock::now();\n\n    std::string sysname = \"ETH1-CHA\";\n    int sigma = 1;\n    std::string dirname = getDirectory(sysname);\n\n    std::vector<double> Ivec = getMomentOfInertia(sysname);\n    std::cout << \"Printing I:\" << std::endl;\n    for (double i : Ivec) {\n        std::cout << i << '\\t';\n    }\n    //std::cout << \"Rotational Constant: = \" << HBAR1*HBAR2/2.0/I << std::endl;\n    std::cout << \"kT = \" << kB*300 / EHARTREE << std::endl;\n    //std::cout << \"Ratio = \" << HBAR1*HBAR2/2.0/I *EHARTREE/(kB*300) << std::endl;\n    //std::cout << \"Qapprox = \" << kB*300/EHARTREE / (HBAR1*HBAR2/2.0/I) << std::endl;\n\n    Col<double> ahat = getCoefficients(sysname);\n    std::cout << \"Directory is: \" << dirname << std::endl;\n\n    /*\n     *  Sparse Matrix Implementation\n     */\n    //SpMat<double> spH = getSparseHam(25, Ivec[0], Ivec[1], Ivec[2]);\n    ////spH.print(\"My sparse Ham =\");\n    //if (!spH.is_hermitian()) {\n    //    std::cout << \"NOT HERMITIAN, CHECK\" << std::endl;\n    //} else {\n    //    std::cout << \"IS HERMITIAN, GOOD TO GO\" << std::endl;\n    //}\n    //double spQ = getSparseQ(300, spH, 3);\n    //std::cout << \"spQ = \" << spQ << std::endl;\n\n    \n    /*\n     *  Dense Matrix Implementation \n     */\n    Mat<double> H = getHamiltonian(31, Ivec[0], Ivec[1], Ivec[2]);\n    if (!H.is_hermitian()) {\n        std::cout << \"NOT HERMITIAN, CHECK\" << std::endl;\n    } else {\n        std::cout << \"HERMITIAN YAY\" << std::endl;\n    }\n    //H.print(\"My ham:\");\n    double Q = getPartitionFunction(298, H, sigma);\n\n    /*\n     *  Classical Partition Function\n     */\n    double B = HBAR1*HBAR2/(2.0*Ivec[2]);\n    double A = HBAR1*HBAR2/(2.0*Ivec[1]);\n    double C = HBAR1*HBAR2/(2.0*Ivec[0]);\n    std::cout << \"Rotational constants / Hartree:\\n\" << A << '\\t' << B << '\\t' << C << '\\t' << std::endl;\n    std::cout << \"kB T / Hartree:\\n\" << kB * 298 / EHARTREE << std::endl;\n    std::cout << \"Qapprox = \" << sqrt(M_PI)/sigma * sqrt(pow(kB*300/EHARTREE, 3) / (A*B*C));\n\n    std::cout << std::endl;\n    std::cout << std::endl;\n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<microseconds>(stop - start);\n    std::cout << std::endl << duration.count()/1e6 << \" secs\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "e60065c28325ab8ad10ad986980904f706d23d2b", "size": 14050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hamiltonian.cpp", "max_stars_repo_name": "lbettins/rotational-hamiltonian", "max_stars_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hamiltonian.cpp", "max_issues_repo_name": "lbettins/rotational-hamiltonian", "max_issues_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hamiltonian.cpp", "max_forks_repo_name": "lbettins/rotational-hamiltonian", "max_forks_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_forks_repo_licenses": ["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.5774647887, "max_line_length": 173, "alphanum_fraction": 0.3948042705, "num_tokens": 3927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110483133801, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5871840133587996}}
{"text": "// ----------------------------------------------------------------------------\n// FILENAME: tylortest.cpp\n//\n// DESCRIPTION:\n//    This file contians the function that used for save the running time of\n//    tylor expansion of polynomial shift with original one\n//\n// AUTHOR: Xinlong Yi\n//\n// ----------------------------------------------------------------------------\n\n#include \"poly.h\"\n#include <boost/numeric/interval/utility_fwd.hpp>\n#include <chrono>\n#include <time.h>\n\nstatic const int kTYLORDEGREE = 6;\nstatic const int digit = 2; // number of digit after point\nstatic const int digit_control = std::pow(10, digit); // controler of digit\nstatic const double max_root = 1000;\n// static const double max_root = std::pow(2, kTYLORDEGREE);\n\n/**\n * Get random double in range min to max\n */\ndouble rand_double(double min, double max) {\n  double f = (double)rand() / RAND_MAX;\n  f = min + f * (max - min);\n  f = std::ceil(f * digit_control) / digit_control;\n  return f;\n}\n\n/**\n * Replace \"x\" in polynomial with \"x+h\"\n * Applied Taylor Expansion to this.\n * p(x+h) = p(h) + p'(h)x + 1/2*p''(h)x^2 ... 1/(n!) * p^n(h)*x^n\n * ref: https://math.stackexchange.com/questions/694565/polynomial-shift\n *\n * @tparam n :Maximum degree of poly\n * @param poly :Polynomial\n * @param h :Number add to x\n * @return :Polynomial that replace x in poly to x+h\n */\ntemplate <int n> Poly<n> Tylor(const Poly<n> &poly, interval h) {\n  if (h.lower() <= 0.0 && h.upper() >= 0.0)\n    return poly;\n\n  Poly<n> ret, tmp(poly);\n  ret[0] = tmp.ValueAt(h);\n  double divisor(1.0);\n  for (int index = 1; index <= poly.get_degree(); ++index) {\n    divisor *= index;\n    tmp.Derivative_();\n    ret[index] = (tmp.ValueAt(h) / divisor);\n  }\n\n  ret.set_degree();\n  return ret;\n}\n\n/**\n * Replace \"x\" in polynomial with \"x+h\"\n * With original implementation. Start with x+h, then multiply them\n *\n * @tparam n :Maximum degree of poly\n * @param poly :Polynomial\n * @param h :Number add to x\n * @return :Polynomial that replace x in poly to x+h\n */\ntemplate <int n> Poly<n> Original(const Poly<n> &poly, interval h) {\n  double tmp[2] = {boost::numeric::median(h), 1};\n  Poly<n> tmp_poly(tmp, 2), ret, multiplier(tmp, 2);\n  ret[0] = poly[0];\n\n  /* TODO :  */\n  for (int i = 1; i <= poly.get_degree(); i++) {\n    ret += (poly[i] * multiplier);\n\n    for (int j = multiplier.get_degree(); j >= 0; j--) {\n      multiplier[j + 1] = multiplier[j] + h * multiplier[j + 1];\n    }\n    multiplier[0] *= h;\n    multiplier.set_degree(multiplier.get_degree() + 1);\n  }\n\n  ret.set_degree(poly.get_degree());\n\n  return ret;\n}\n\nint main() {\n  srand(time(NULL));\n\n  double *coeffs = new double[kTYLORDEGREE];\n  for (size_t i = 0; i < kTYLORDEGREE; i++) {\n    coeffs[i] = rand_double(-kTYLORDEGREE, kTYLORDEGREE);\n  }\n\n  interval h(rand_double(-max_root, max_root));\n\n  Poly<kTYLORDEGREE> test_poly(coeffs, kTYLORDEGREE);\n  std::cout << \"orig \" << test_poly << std::endl;\n\n  // Tylor\n  auto tylor_start = std::chrono::high_resolution_clock::now();\n  auto r1 = Tylor(test_poly, h);\n  auto tylor_end = std::chrono::high_resolution_clock::now();\n\n  //    Original\n  auto ori_start = std::chrono::high_resolution_clock::now();\n  auto r2 = Original(test_poly, h);\n  auto ori_end = std::chrono::high_resolution_clock::now();\n\n  //     Time\n  auto tylor_duration = std::chrono::duration_cast<std::chrono::nanoseconds>(\n      tylor_end - tylor_start);\n  auto ori_duration =\n      std::chrono::duration_cast<std::chrono::nanoseconds>(ori_end - ori_start);\n\n  std::cout << \"Tylor expansion method takes \" << tylor_duration.count()\n            << \" ns for \" << kTYLORDEGREE - 1 << \" degree\" << std::endl;\n\n  std::cout << \"Original method takes \" << ori_duration.count() << \" ns for \"\n            << kTYLORDEGREE - 1 << \" degree\" << std::endl;\n\n  std::cout << r1 << std::endl;\n  std::cout << r2 << std::endl;\n\n  interval a = 1.0, b = 3.0;\n  interval tmp = a - b;\n  std::cout << boost::numeric::median(tmp) << \"[\" << boost::numeric::width(tmp)\n            << \"]\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b7d1ff908bac10ed567063446665bf78b7751256", "size": 4022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tylortest.cpp", "max_stars_repo_name": "willyii/PolynomialRootFinding", "max_stars_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tylortest.cpp", "max_issues_repo_name": "willyii/PolynomialRootFinding", "max_issues_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-13T00:53:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-13T00:53:54.000Z", "max_forks_repo_path": "src/tylortest.cpp", "max_forks_repo_name": "willyii/PolynomialRootFinding", "max_forks_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T12:54:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T12:54:48.000Z", "avg_line_length": 29.5735294118, "max_line_length": 80, "alphanum_fraction": 0.605917454, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.5871032564039498}}
{"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_VectorND_HPP\n#define RW_MATH_VectorND_HPP\n\n/**\n * @file VectorND.hpp\n */\n#if !defined(SWIG)\n#include <rw/common/InputArchive.hpp>\n#include <rw/common/OutputArchive.hpp>\n#include <rw/common/Serializable.hpp>\n#include <rw/core/macros.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A N-Dimensional Vector\n     *\n     */\n    template< size_t N, class T = double > class VectorND : public rw::common::Serializable\n    {\n      public:\n        //! The type of the internal Eigen Vector\n        typedef Eigen::Matrix< T, N, 1 > EigenVectorND;\n\n        //! Value type.\n        typedef T value_type;\n\n        /**\n         * @brief Creates a N-dimensional VectorND\n         */\n        VectorND ()\n        {\n            if (N <= 0) {\n                RW_THROW (\"Vector to small, N must be larger than 0\");\n            }\n            _vec = EigenVectorND (N);\n        }\n\n        /**\n         * @brief Construct a Vector from N arguments\n         * @param args [in] a list of arguments\n         */\n        template< typename... ARGS > VectorND (T arg0, ARGS... args)\n        {\n            if (N <= 0u) {\n                RW_THROW (\"Vector to small, N must be larger than 0\");\n            }\n            size_t i = 1;\n            ParamExpansion (i, args...);\n\n            _vec[--i] = arg0;\n        }\n\n        /**\n         * @brief construct vector from std::vector\n         * @param vec [in] the vector to construct from\n         */\n        VectorND (const std::vector< T >& vec)\n        {\n            if (N <= 0u) {\n                RW_THROW (\"Vector to small, N must be larger than 0\");\n            }\n            else if (vec.size () != N) {\n                RW_THROW (\"Wrong Size vector matrix: N of size:\" << N << \" and vector of size: \"\n                                                                 << vec.size () << \"given\");\n            }\n            for (size_t i = 0; i < N; i++) {\n                _vec[i] = vec[i];\n            }\n        }\n\n        /**\n         * @brief Creates a 3D VectorND from Eigen type.\n         *\n         * @param v [in] an Eigen vector.\n         */\n        template< class R > VectorND (const Eigen::MatrixBase< R >& v)\n        {\n            if (v.cols () != 1 || v.rows () != N)\n                RW_THROW (\"Unable to initialize VectorND with \" << v.rows () << \" x \" << v.cols ()\n                                                                << \" matrix\");\n            _vec = v;\n        }\n\n        /**\n         * @brief The dimension of the VectorND (i.e. 3).\n         * This method is provided to help support generic algorithms using\n           size() and operator[].\n         */\n        size_t size () const { return N; }\n\n        // ###################################################\n        // #                 Math Operations                 #\n        // ###################################################\n\n        // ########## Eigen Operations\n\n        /**\n         * @brief element wise multiplication.\n         * @param rhs [in] the vector being multiplied with\n         * @return the resulting VectorND\n         */\n        template< class R > VectorND< N, T > elemMultiply (const Eigen::MatrixBase< R >& rhs) const\n        {\n            VectorND< N, T > ret = *this;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] *= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief element wise division.\n         * @param lhs [in] vector\n         * @param rhs [in] vector\n         * @return the resulting VectorND\n         */\n        template< class R > VectorND< N, T > elemDivide (const Eigen::MatrixBase< R >& rhs) const\n        {\n            VectorND< N, T > ret;\n            for (size_t i = 0; i < N; i++) {\n                ret[i] = (*this)[i] / rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > VectorND< N, T > operator- (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return VectorND< N, T > (_vec - rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend VectorND< N, T > operator- (const Eigen::MatrixBase< R >& lhs,\n                                           const VectorND< N, T >& rhs)\n        {\n            return VectorND< N, T > (lhs - rhs.e ());\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > VectorND< N, T > operator+ (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return VectorND< N, T > (_vec + rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend VectorND< N, T > operator+ (const Eigen::MatrixBase< R >& lhs,\n                                           const VectorND< N, T >& rhs)\n        {\n            return VectorND< N, T > (lhs + rhs.e ());\n        }\n\n        // ########## VectorND Operations\n\n        /**\n         * @brief element wise division.\n         * @param rhs [in] the vector being devided with\n         * @return the resulting Vector3D\n         */\n        VectorND< N, T > elemDivide (const VectorND< N, T >& rhs) const\n        {\n            VectorND< N, T > ret = *this;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] /= rhs._vec[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Elementweise multiplication.\n         * @param rhs [in] vector\n         * @return the element wise product\n         */\n        VectorND< N, T > elemMultiply (const VectorND< N, T >& rhs) const\n        {\n            VectorND< N, T > ret = *this;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] *= rhs._vec[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        VectorND< N, T > operator- (const VectorND< N, T >& rhs) const\n        {\n            return VectorND< N, T > (_vec - rhs._vec);\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        VectorND< N, T > operator+ (const VectorND< N, T >& rhs) const\n        {\n            return VectorND< N, T > (_vec + rhs._vec);\n        }\n\n        /**\n         * @brief Unary minus.\n         * @brief negative version\n         */\n        VectorND< N, T > operator- () const { return VectorND< N, T > (_vec * (-1)); }\n\n        // ########## Scalar Operations\n\n        /**\n         * @brief Scalar division.\n         * @param rhs [in] the scalar to devide with\n         * @return result of devision\n         */\n        VectorND< N, T > operator/ (T rhs) const { return VectorND< N, T > (_vec / rhs); }\n\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar division.\n         * @param lhs [in] the scalar to devide with\n         * @param rhs [out] the vector beind devided\n         * @return result of devision\n         */\n        friend VectorND< N, T > operator/ (T lhs, const VectorND< N, T >& rhs)\n        {\n            VectorND< N, T > ret = rhs;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] = lhs / ret._vec[i];\n            }\n            return ret;\n        }\n#endif\n\n        /**\n         * @brief Scalar multiplication.\n         * @param rhs [in] the scalar to multiply with\n         * @return the product\n         */\n        VectorND< N, T > operator* (T rhs) const { return VectorND< N, T > (_vec * rhs); }\n\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar multiplication.\n         * @param lhs [in] the scalar to multiply with\n         * @param rhs [in] the Vector to be multiplied\n         * @return the product\n         */\n        friend VectorND< N, T > operator* (T lhs, const VectorND< N, T >& rhs)\n        {\n            return VectorND< N, T > (lhs * rhs._vec);\n        }\n#endif\n\n        /**\n         * @brief Scalar subtraction.\n         */\n        VectorND< N, T > elemSubtract (const T& rhs) const\n        {\n            VectorND< N, T > ret = *this;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] = ret._vec[i] - rhs;\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Scalar addition.\n         */\n        VectorND< N, T > elemAdd (const T& rhs) const\n        {\n            VectorND< N, T > ret = *this;\n            for (size_t i = 0; i < N; i++) {\n                ret._vec[i] = ret._vec[i] + rhs;\n            }\n            return ret;\n        }\n\n        // ########### Math Functions\n\n        /**\n         * @brief Returns the Euclidean norm (2-norm) of the VectorND\n         * @return the norm\n         */\n        T norm2 () const { return _vec.norm (); }\n\n        /**\n         * @brief Returns the Manhatten norm (1-norm) of the VectorND\n         * @return the norm\n         */\n        T norm1 () const { return _vec.template lpNorm< 1 > (); }\n\n        /**\n         * @brief Returns the infinte norm (\\f$\\inf\\f$-norm) of the VectorND\n         * @return the norm\n         */\n        T normInf () const { return _vec.template lpNorm< Eigen::Infinity > (); }\n\n        /**\n         * @brief calculate the dot product\n         * @param vec [in] the vecor to be dotted\n         * @return the dot product\n         */\n        double dot (const VectorND< N, T >& vec) const { return _vec.dot (vec._vec); }\n\n        /**\n         * @brief normalize vector to get length 1\n         * @return the normalized Vector\n         */\n        VectorND< N, T > normalize ()\n        {\n            T length = norm2 ();\n            if (length != 0)\n                return (*this) / length;\n            else\n                return VectorND< N, T > ();\n        }\n\n        // ###################################################\n        // #                Acces Operators                  #\n        // ###################################################\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to VectorND element\n         * @param i [in] index in the VectorND \\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 VectorND element\n         * @param i [in] index in the VectorND \\f$i\\in \\{0,1,2\\} \\f$\n         * @return reference to element\n         */\n        T& operator() (size_t i) { return _vec[i]; }\n\n        /**\n         * @brief Returns reference to VectorND element\n         * @param i [in] index in the VectorND \\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 VectorND element\n         * @param i [in] index in the VectorND \\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         * @brief Accessor for the internal Eigen VectorND.\n         */\n        EigenVectorND& e () { return _vec; }\n\n        /**\n           @brief Accessor for the internal Eigen VectorND.\n         */\n        const EigenVectorND& e () const { return _vec; }\n#if !defined(SWIG)\n        /**\n         * @brief Streaming operator.\n         * @param out [in/out] the stream to continue\n         * @param v [in] the vector to stream\n         * @param reference to \\b out\n         */\n        friend std::ostream& operator<< (std::ostream& out, const VectorND< N, T >& v)\n        {\n            out << \"Vector\" << N << \"D(\";\n            for (size_t i = 0; i < N - 1; i++) {\n                out << v[i] << \", \";\n            }\n            out << v[N - 1] << \")\";\n            return out;\n        }\n#else\n#define VECTORND(num, type) rw::math::VectorND< num, type >\n        TOSTRING (VECTORND (N, T));\n#undef VECTORND\n#endif\n\n        /**\n         * @brief converts the vector to a std:vector\n         * @return a std::vector\n         */\n        std::vector< T > toStdVector () const\n        {\n            std::vector< T > ret;\n            for (size_t i = 0; i < N; i++) {\n                ret.push_back (_vec[i]);\n            }\n            return ret;\n        }\n\n        // ###################################################\n        // #             assignement Operators               #\n        // ###################################################\n\n        /**\n         * @brief Scalar multiplication.\n         */\n        VectorND< N, T >& operator*= (double s)\n        {\n            _vec *= s;\n            return *this;\n        }\n\n        /**\n         * @brief Scalar division.\n         */\n        VectorND< N, T >& operator/= (double s)\n        {\n            _vec /= s;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        VectorND< N, T >& operator+= (const VectorND< N, T >& v)\n        {\n            _vec += v._vec;\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        VectorND< N, T >& operator-= (const VectorND< N, T >& v)\n        {\n            _vec -= v._vec;\n            return *this;\n        }\n\n        /**\n         * @brief copy a vector from eigen type\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > VectorND< N, T >& operator= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec = r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > VectorND< N, T >& operator+= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec += r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > VectorND< N, T >& operator-= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec -= r;\n            return *this;\n        }\n\n        // ###################################################\n        // #                    Comparetors                  #\n        // ###################################################\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R > bool operator== (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return this->_vec == rhs;\n        }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R >\n        friend bool operator== (const Eigen::MatrixBase< R >& lhs, const VectorND< N, T >& rhs)\n        {\n            return lhs == rhs._vec;\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param ths [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R > bool operator!= (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return !(*this == rhs);\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param b [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R >\n        friend bool operator!= (const Eigen::MatrixBase< R >& lhs, const VectorND< N, T >& rhs)\n        {\n            return !(lhs == rhs);\n        }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const VectorND< N, T >& rhs) const { return this->_vec == rhs._vec; }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param rhs [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        bool operator!= (const VectorND< N, T >& rhs) const { return !(*this == rhs); }\n\n        // ###################################################\n        // #                      OTHER                      #\n        // ###################################################\n#if !defined(SWIG)\n        //! @copydoc rw::common::Serializable::write\n        void write (rw::common::OutputArchive& oarchive, const std::string& id) const\n        {\n            oarchive.write (this->toStdVector (), id, \"VectorND\");\n        }\n\n        //! @copydoc rw::common::Serializable::read\n        void read (rw::common::InputArchive& iarchive, const std::string& id)\n        {\n            std::vector< T > result (N, 0);\n            iarchive.read (result, id, \"VectorND\");\n            *this = VectorND< N, T > (result);\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator EigenVectorND () const { return this->e (); }\n\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator EigenVectorND& () { return this->e (); }\n#endif\n        /**\n         * @brief Get zero-initialized vector.\n         * @return vector.\n         */\n        static VectorND< N, T > zero () { return Eigen::Matrix< T, N, 1 >::Zero (); }\n\n      private:\n        void ParamExpansion (size_t& i)\n        {\n            if (i > N) {\n                RW_THROW (\"Vector to big, argc(\" << i << \") != N(\" << N << \")\");\n            }\n            else if (i < N) {\n                RW_THROW (\"Vector to small, argc(\" << i << \") != N(\" << N << \")\");\n            }\n        }\n\n        template< typename R > void ParamExpansion (size_t& i, R arg)\n        {\n            ParamExpansion (++i);\n            _vec[--i] = T (arg);\n        }\n\n        template< typename R, typename... ARGS >\n        void ParamExpansion (size_t& i, R arg, ARGS... args)\n        {\n            ParamExpansion (++i, args...);\n\n            _vec[--i] = T (arg);\n        }\n\n        EigenVectorND _vec;\n    };\n\n    /**\n     * @brief Calculates the 3D VectorND cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the 3D VectorND cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * The 3D VectorND cross product is defined as:\n     * @f$\n     * \\mathbf{v1} \\times \\mathbf{v2} = \\left[\\begin{array}{c}\n     *  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     * \\end{array}\\right]\n     * @f$\n     *\n     * @relates VectorND\n     */\n    template< size_t ND, class T >\n    const VectorND< ND, T > cross (const VectorND< ND, T >& v1, const VectorND< ND, T >& v2)\n    {\n        return v1.e ().cross (v2.e ());\n        // return cross(v1.e(),v2.e());\n    }\n\n    /**\n     * @brief Calculates the 3D VectorND cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     * @param dst [out] the 3D VectorND cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * The 3D VectorND cross product is defined as:\n     * @f$\n     * \\mathbf{v1} \\times \\mathbf{v2} = \\left[\\begin{array}{c}\n     *  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     * \\end{array}\\right]\n     * @f$\n     *\n     * @relates VectorND\n     */\n    template< size_t ND, class T >\n    void cross (const VectorND< ND, T >& v1, const VectorND< ND, T >& v2, VectorND< ND, T >& dst)\n    {\n        dst = v1.e ().cross (v2.e ());\n        // dst = cross(v1.m(),v2.m());\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     * @relates VectorND\n     */\n    template< size_t ND, class T > T dot (const VectorND< ND, T >& v1, const VectorND< ND, T >& v2)\n    {\n        return v1.e ().dot (v2.e ());\n    }\n\n    /**\n     * @brief Returns the normalized VectorND \\f$\\mathbf{n}=\\frac{\\mathbf{v}}{\\|\\mathbf{v}\\|} \\f$.\n     * In case \\f$ \\|mathbf{v}\\| = 0\\f$ the zero VectorND is returned.\n     * @param v [in] \\f$ \\mathbf{v} \\f$ which should be normalized\n     * @return the normalized VectorND \\f$ \\mathbf{n} \\f$\n     *\n     * @relates VectorND\n     */\n    template< size_t ND, class T > const VectorND< ND, T > normalize (const VectorND< ND, T >& v)\n    {\n        // Create a copy\n        VectorND< ND, T > res (v);\n        res.e ().normalize ();\n        return res;\n    }\n\n    /**\n     * @brief Calculates the angle from @f$ \\mathbf{v1}@f$ to @f$ \\mathbf{v2} @f$\n     * around the axis defined by @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$ with n\n     * determining the sign.\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     * @param n [in] @f$ \\mathbf{n} @f$\n     *\n     * @return the angle\n     *\n     * @relates VectorND\n     */\n    template< size_t ND, class T >\n    double angle (const VectorND< ND, T >& v1, const VectorND< ND, T >& v2,\n                  const VectorND< ND, T >& n)\n    {\n        const VectorND< ND, T > nv1 = normalize (v1);\n        const VectorND< ND, T > nv2 = normalize (v2);\n        const VectorND< ND, T > nn  = normalize (n);\n        return atan2 (dot (nn, cross (nv1, nv2)), dot (nv1, nv2));\n    }\n\n    /**\n     * @brief Calculates the angle from @f$ \\mathbf{v1}@f$ to @f$ \\mathbf{v2} @f$\n     * around the axis defined by @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the angle\n     *\n     * @relates VectorND\n     */\n    template< size_t ND, class T >\n    double angle (const VectorND< ND, T >& v1, const VectorND< ND, T >& v2)\n    {\n        VectorND< ND, T > n = cross (v1, v2);\n        return angle (v1, v2, n);\n    }\n\n    /**\n     * @brief Casts VectorND<N,T> to VectorND<Q>\n     * @param v [in] VectorND with type T\n     * @return VectorND with type Q\n     *\n     * @relates VectorND\n     */\n    template< class Q, size_t ND, class T >\n    const VectorND< ND, Q > cast (const VectorND< ND, T >& v)\n    {\n        VectorND< ND, Q > ret;\n\n        for (size_t i = 0; i < v.size (); i++) {\n            ret[i] = static_cast< Q > (v[i]);\n        }\n        return ret;\n    }\n\n    template< class T > using Vector6D = VectorND< 6, T >;\n\n#if !defined(SWIG)\n    extern template class rw::math::VectorND< 6, double >;\n    extern template class rw::math::VectorND< 6, float >;\n    extern template class rw::math::VectorND< 5, double >;\n    extern template class rw::math::VectorND< 5, float >;\n    extern template class rw::math::VectorND< 4, double >;\n    extern template class rw::math::VectorND< 4, float >;\n    extern template class rw::math::VectorND< 3, double >;\n    extern template class rw::math::VectorND< 3, float >;\n    extern template class rw::math::VectorND< 2, double >;\n    extern template class rw::math::VectorND< 2, float >;\n#else\n#define VECTORND(num, type) rw::math::VectorND< num, type >;\n    SWIG_DECLARE_TEMPLATE (Vector6Dd, VECTORND (6, double));\n    SWIG_DECLARE_TEMPLATE (Vector6Df, VECTORND (6, float));\n    SWIG_DECLARE_TEMPLATE (Vector5Dd, VECTORND (5, double));\n    SWIG_DECLARE_TEMPLATE (Vector5Df, VECTORND (5, float));\n    SWIG_DECLARE_TEMPLATE (Vector4Dd, VECTORND (4, double));\n    SWIG_DECLARE_TEMPLATE (Vector4Df, VECTORND (4, float));\n#undef VECTORND\n#endif\n\n    /**@}*/\n}}    // namespace rw::math\n\n#endif    // end include guard\n", "meta": {"hexsha": "aef2a2c8341c06c1c334ef18c4a059076d3b9746", "size": 24376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/VectorND.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/VectorND.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/VectorND.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2512820513, "max_line_length": 99, "alphanum_fraction": 0.4669346899, "num_tokens": 6430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.5871032520202027}}
{"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/**\n * @file Optimal control problem on SE2.\n */\n\n#ifndef OCP_SE2_HPP_\n#define OCP_SE2_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <smooth/bundle.hpp>\n#include <smooth/derivatives.hpp>\n#include <smooth/feedback/ocp.hpp>\n#include <smooth/feedback/utils/sparse.hpp>\n#include <smooth/se2.hpp>\n\ntemplate<typename T>\nusing X = smooth::Bundle<smooth::SE2<T>, Eigen::Vector2<T>>;\n\ntemplate<typename T>\nusing U = Eigen::Vector2<T>;\n\ntemplate<typename T, std::size_t N>\nusing Vec = Eigen::Vector<T, N>;\n\n/// @brief Objective function\nstruct SE2Theta\n{\n  template<typename T>\n  T operator()(T tf, const X<T> &, const X<T> &, const Vec<T, 1> & q) const\n  {\n    return tf + q.x();\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(1, 12);\n    ret.coeffRef(0, 0)  = 1;\n    ret.coeffRef(0, 11) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(12, 12);\n    return ret;\n  }\n};\n\n/// @brief Dynamics\nstruct SE2Dyn\n{\n  template<typename T>\n  smooth::Tangent<X<T>> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    smooth::Tangent<X<T>> ret;\n    ret(0) = x.template part<1>().x();\n    ret(1) = T(0);\n    ret(2) = x.template part<1>().y();\n    ret(3) = u.x();\n    ret(4) = u.y();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(5, 8);\n    ret.coeffRef(0, 4) = 1;\n    ret.coeffRef(2, 5) = 1;\n    ret.coeffRef(3, 6) = 1;\n    ret.coeffRef(4, 7) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(8, 5 * 8);\n    return ret;\n  }\n};\n\n/// @brief Target trajectory\nconst auto xdes = []<typename T>(T t) -> X<T> {\n  const Eigen::Vector3<T> vel{1., 0., 0.5};\n\n  X<T> ret;\n  ret.template part<0>()     = smooth::SE2<T>::exp(t * vel);\n  ret.template part<1>().x() = vel.x();\n  ret.template part<1>().y() = vel.z();\n  return ret;\n};\n\n/// @brief Integrals\nstruct SE2Integral\n{\n  template<typename T>\n  Vec<T, 1> operator()(T t, const X<T> & x, const U<T> & u) const\n  {\n    return 0.5 * Vec<T, 1>{(x - xdes(t)).squaredNorm() + u.squaredNorm()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double t, const X<double> & x, const U<double> & u) const\n  {\n    const auto a = x - xdes(t);\n\n    Eigen::SparseMatrix<double> ret(1, 8);\n    ret.coeffRef(0, 0) = -(a.transpose() * smooth::dl_expinv<X<double>>(a))\n                            .dot(Eigen::Vector<double, 5>{1., 0., 0.5, 0, 0});\n    smooth::feedback::block_add(ret, 0, 1, smooth::dr_rminus_squarednorm<X<double>>(a));\n    ret.coeffRef(0, 6) = u.x();\n    ret.coeffRef(0, 7) = u.y();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double t, const X<double> & x, const U<double> &) const\n  {\n    const auto H = smooth::d2r_rminus_squarednorm<X<double>>(x - xdes(t));\n\n    Eigen::SparseMatrix<double> ret(8, 8);\n    /// @todo don't have derivatives w.r.t. t\n    smooth::feedback::block_add(ret, 1, 1, H);\n    ret.coeffRef(6, 6) = 1;\n    ret.coeffRef(7, 7) = 1;\n    return ret;\n  }\n};\n\n/// @brief Running constraints\nstruct SE2Cr\n{\n  template<typename T>\n  Vec<T, 2> operator()(T, const X<T> &, const U<T> & u) const\n  {\n    return u;\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(2, 8);\n    ret.coeffRef(0, 6) = 1;\n    ret.coeffRef(1, 7) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(8, 2 * 8);\n    return ret;\n  }\n};\n\n/// @brief End constraints\nstruct SE2Ce\n{\n  template<typename T>\n  Vec<T, 6> operator()(T tf, const X<T> & x0, const X<T> &, const Vec<T, 1> &) const\n  {\n    Vec<T, 6> ret;\n    ret << tf, x0.log();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> & x0, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(6, 12);\n    ret.coeffRef(0, 0) = 1;\n    smooth::feedback::block_add(ret, 1, 1, smooth::dr_expinv<X<double>>(x0.log()));\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> & x0, const X<double> &, const Vec<double, 1> &) const\n  {\n    const auto d2_logx0 = smooth::d2r_rminus<X<double>>(x0.log());\n\n    Eigen::SparseMatrix<double> ret(12, 6 * 12);\n    for (auto i = 0u; i < 5; ++i) {\n      smooth::feedback::block_add(ret, 1, 12 * (1 + i) + 1, d2_logx0.block(0, i * 5, 5, 5));\n    }\n\n    return ret;\n  }\n};\n\nusing OcpSE2 =\n  smooth::feedback::OCP<X<double>, U<double>, SE2Theta, SE2Dyn, SE2Integral, SE2Cr, SE2Ce>;\n\ninline const OcpSE2 ocp_se2{\n  .theta = SE2Theta{},\n  .f     = SE2Dyn{},\n  .g     = SE2Integral{},\n  .cr    = SE2Cr{},\n  .crl   = Vec<double, 2>{{-1, -1}},\n  .cru   = Vec<double, 2>{{1, 1}},\n  .ce    = SE2Ce{},\n  .cel   = Vec<double, 6>{{5, 0, 0, 0, 1, 0}},\n  .ceu   = Vec<double, 6>{{5, 0, 0, 0, 1, 0}},\n};\n\n#endif  // OCP_SE2_HPP_\n", "meta": {"hexsha": "9c3a0559008e38fae6642a32862a787f3cd19fa0", "size": 6449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/ocp_se2.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ocp_se2.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ocp_se2.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2850877193, "max_line_length": 96, "alphanum_fraction": 0.6276942162, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.58707064341313}}
{"text": "#include \"q_matrix_tools.h\"\n#include \"rhab/basic_iteration.h\"\n#include <iomanip>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n// Boost Algorithm\n#include <boost/algorithm/minmax_element.hpp>\n\nextern \"C\"\n{\n#include <cblas.h>\n}\n\n#include <gsl/gsl_multifit.h>\n#include <gsl/gsl_multimin.h>\n\ntypedef boost::tuple<const std::vector<size_t>*,\n                     const std::vector<double>*,\n                     const std::vector<double>*\n                     > params_t;\n\n/**\n * Apply symmetry condition.\n *\n * We can only use pairs of T(i->j) and T(j->i) for the equation system.\n */\nvoid apply_symmetry_conditions(matrix_int_t &imat, std::vector<size_t> &coords) {\n  for (size_t i = 0; i < imat.size1(); i++) {\n    for (size_t j = 0; j < imat.size2(); ++j) {\n      if (i==j) {\n        continue;\n      }\n      if (imat(i,j) > 0 && imat(j,i) > 0) {\n        coords.push_back(i);\n        coords.push_back(j);\n        continue;\n      }\n      imat(i,j) = imat(j,i) = 0;\n    }\n  }\n}\n\ndouble variance_function(const gsl_vector * x, void * params) {\n  params_t* p = (params_t*)params;\n  const std::vector<size_t>* coords  = boost::get<0>(*p);\n  const std::vector<double>* sigma   = boost::get<1>(*p);\n  const std::vector<double>* precalc = boost::get<2>(*p);\n\n  double err = 0;\n\n  for (size_t k = 0; k < coords->size(); k+=2) {\n    const size_t &i = (*coords)[k];\n    const size_t &j = (*coords)[k+1];\n\n    double xi(1.0), xj(1.0);\n    if (i < x->size) {\n      xi = gsl_vector_get(x, i);\n    }\n    if (j < x->size) {\n      xj = gsl_vector_get(x, j);\n    }\n\n    double tmp = xi - xj + (*precalc)[k/2];\n    err += tmp*tmp / (*sigma)[k/2];\n  }\n\n  return err;\n}\n\nbool rhab::calculate_dos_minimization(matrix_int_t imat, matrix_double_t &dmat, vector_double_t &dos) {\n  // Histogram\n  vector_int_t hist(imat.size1());\n\n  // coordinates of entries in the matrix stored one after another i1,j1,i2,j2,...\n  std::vector<size_t> coords;\n  std::vector<double> sigma;\n  std::vector<double> precalc;\n\n  apply_symmetry_conditions(imat, coords);\n\n  // if we have too few entries left in the matrix abort\n  if (coords.size()/2 < dos.size()) {\n    return false;\n  }\n\n  normalize_q(imat, dmat);\n\n  for (size_t i = 0; i < imat.size1(); i++) {\n    hist[i] = sum(row(imat,i));\n  }\n\n  // we keep the state with the highest energy fixed\n  // and thus do minimization only on N-1 states\n  size_t num_states = dos.size()-1;\n\n  // Precalculate variables\n  sigma.resize(coords.size()/2);\n  precalc.resize(coords.size()/2);\n\n  for (size_t k = 0; k < coords.size(); k+=2) {\n    const size_t &i = coords[k];\n    const size_t &j = coords[k+1];\n\n    precalc[k/2] = log(dmat(i,j) / dmat(j,i));\n    sigma[k/2]   = 1./imat(i,j) + 1./hist[i] + 1./imat(j,i) + 1./hist[j];\n  }\n\n  // setup the minimization function and fminimizer\n  gsl_vector *ss, *x;\n  gsl_multimin_function minex_func;\n\n  params_t params(&coords, &sigma, &precalc);\n\n  minex_func.n = num_states;\n  minex_func.f = variance_function;\n  minex_func.params = &params;\n\n  // Starting point\n  x = gsl_vector_alloc(num_states);\n  gsl_vector_set_all(x,  1.0);\n\n  // Set initial step sizes to 1\n  ss = gsl_vector_alloc(num_states);\n  gsl_vector_set_all(ss, 1.0);\n\n  gsl_multimin_fminimizer *s = NULL;\n  s = gsl_multimin_fminimizer_alloc(gsl_multimin_fminimizer_nmsimplex2, num_states);\n  gsl_multimin_fminimizer_set(s, &minex_func, x, ss);\n  int status;\n  size_t iter = 0;\n  double size;\n\n  do {\n    iter++;\n    status = gsl_multimin_fminimizer_iterate(s);\n\n    if (status) {\n      break;\n    }\n\n    size = gsl_multimin_fminimizer_size(s);\n    status = gsl_multimin_test_size(size, 1e-6);\n    //std::cout << iter << \" \" << size << \" \" << status << std::endl;\n  } while(status == GSL_CONTINUE /* && iter < 1000000*/);\n\n  std::cout << iter << \" \" << size;\n\n  for (size_t i = 0; i < s->x->size; i++) {\n    dos[i] = gsl_vector_get(s->x, i);\n  }\n  dos[dos.size()-1] = 1;\n\n  for (size_t i = 0; i < dos.size(); i++) {\n    std::cout << \" \" << dos[i];\n  }\n  std::cout << std::endl;\n\n  gsl_multimin_fminimizer_free(s);\n  gsl_vector_free(x);\n  gsl_vector_free(ss);\n\n\n  return true;\n}\n\nbool rhab::calculate_dos_leastsquares(matrix_int_t imat, matrix_double_t &dmat, vector_double_t &dos) {\n  vector_int_t hist(imat.size1());\n\n  // coordinates of entries in the matrix stored one after another i1,j1,i2,j2,...\n  std::vector<size_t> coords;\n  std::vector<size_t> pivot(imat.size1());\n  size_t cnt_nnz = 0;\n\n  apply_symmetry_conditions(imat, coords);\n\n  if (coords.size()/2 < dos.size()) {\n    return false;\n  }\n\n  normalize_q(imat, dmat);\n\n  for (size_t i = 0; i < imat.size1(); i++) {\n    hist[cnt_nnz] = sum(row(imat,i));\n    if (hist[cnt_nnz] > 0) {\n      pivot[i] = cnt_nnz;\n      cnt_nnz ++;\n    }\n  }\n\n  int xn = coords.size()/2;\n\n  gsl_matrix *X, *cov;\n  gsl_vector *y, *c;\n  double chisq;\n\n  X = gsl_matrix_calloc(xn, cnt_nnz);\n  y = gsl_vector_calloc(xn);\n  c = gsl_vector_calloc(cnt_nnz);\n  cov = gsl_matrix_calloc(cnt_nnz, cnt_nnz);\n\n  for (int k = 0; k < 2*xn; k+=2) {\n    const size_t &i = coords[k];\n    const size_t &j = coords[k+1];\n    gsl_matrix_set(X, k/2, pivot[i],  1.0/sqrt(1./hist[pivot[i]] + 1./hist[pivot[j]] + 1./imat(j,i) + 1./imat(i,j)));\n    gsl_matrix_set(X, k/2, pivot[j], -1.0/sqrt(1./hist[pivot[i]] + 1./hist[pivot[j]] + 1./imat(j,i) + 1./imat(i,j)));\n    gsl_vector_set(y, k/2, -log( dmat(i,j) / dmat(j,i) )/sqrt(1./hist[pivot[i]] + 1./hist[pivot[j]] + 1./imat(j,i) + 1./imat(i,j)));\n  }\n\n  {\n    gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc(xn, cnt_nnz);\n    gsl_multifit_linear(X,y,c,cov,&chisq, work);\n    gsl_multifit_linear_free(work);\n  }\n\n  for (size_t i = 0; i < dos.size(); i++) {\n    dos[i] = gsl_vector_get(c, pivot[i]);\n  }\n\n  gsl_matrix_free(X);\n  gsl_vector_free(y);\n  gsl_vector_free(c);\n  gsl_matrix_free(cov);\n\n  return true;\n}\n\nvoid rhab::normalize_q(const matrix_int_t & Q, matrix_double_t & Qd) {\n  using namespace boost::numeric::ublas;\n  for (size_t i = 0; i < Q.size1(); i++) {\n    double s = sum(row(Q,i));\n    if (s == 0) {\n      row(Qd,i) *= 0;\n    } else {\n      row(Qd,i) = row(Q,i)/s;\n    }\n  }\n}\n\nvoid rhab::normalize(vector_double_t &vec) {\n  vec /= sum(vec);\n}\n\nvoid rhab::normalize_from_log(vector_double_t &vec) {\n  double sub(0), norm(0);\n  std::pair<vector_double_t::iterator, vector_double_t::iterator> mm =\n    boost::minmax_element(vec.begin(), vec.end());\n  sub = (*(mm.second) + *(mm.first))/2;\n  for (size_t i = 0; i < vec.size(); i++) {\n    norm += exp(vec[i] - sub);\n  }\n  for (size_t i = 0; i < vec.size(); i++) {\n    vec[i] = exp(vec[i] - sub) / norm;\n  }\n}\n\nbool rhab::calculate_dos_gth(matrix_double_t & inner_mat, vector_double_t &dos) {\n  namespace ublas = boost::numeric::ublas;\n  std::size_t inner_rows(inner_mat.size1());\n  std::size_t inner_cols(inner_mat.size1());\n  // we assume small matrix and try GTH method\n  // do GTH LU decomposition\n  for (std::size_t i = inner_rows-1; i > 0; --i) {\n    double s = ublas::norm_1(ublas::subrange(ublas::row(inner_mat,i), 0, i));\n    if (s != 0) {\n      inner_mat(i,i) = -s;\n      for (std::size_t j = 0; j < i; ++j) {\n        inner_mat(j,i) /= s;\n      }\n    }\n    for (std::size_t k = 0; k < i; ++k) {\n      for (std::size_t j = 0; j < i; ++j) {\n        inner_mat(k,j) += inner_mat(k,i)*inner_mat(i,j);\n      }\n    }\n  }\n  // now just do modified eqn. 33 of M. Fenwick - J. Chem. Phys. 125, 144905\n  std::fill(dos.begin(), dos.end(), 0.0);//dos.clear();\n  dos[0] = 1;\n  for (std::size_t i = 1; i < inner_rows; ++i) {\n    for (std::size_t j = 0; j < i; ++j) {\n      if (inner_mat(j,i) > 0) {\n        dos[i] += exp(dos[j] + log(inner_mat(j,i)));\n      }\n    }\n    dos[i] = log(dos[i]);\n  }\n  for (std::size_t ei = 0; ei < inner_cols; ++ei) {\n    dos(ei) = exp(dos(ei));\n  }\n\n  // eqn. 32 of M. Fenwick - J. Chem. Phys. 125, 144905\n  /*\n  for (size_t i = 1; i < inner_rows; ++i) {\n    for (size_t j = 0; j < i; ++j) {\n      dos[i] += dos[j] * inner_mat(j,i);\n    }\n  }\n  */\n\n  normalize(dos);\n  return ( std::count_if(dos.begin(), dos.end(), boost::math::isnan<double>) == 0 );\n}\n\nbool rhab::calculate_dos_power(const matrix_double_t &imat, vector_double_t &t1) {\n  namespace ublas = boost::numeric::ublas;\n  matrix_double_t mat(ublas::trans(imat));\n  //vector_double_t t1(mat.size1());\n  vector_double_t t2(mat.size1());\n  vector_double_t t3(mat.size1());\n  std::fill(t1.begin(), t1.end(), 1.0/mat.size1());\n  size_t max_iter = 10000;\n  double lambda, residual, dist;\n\n  rhab::basic_iteration<vector_double_t::iterator> iter(max_iter, 1e-8);\n  do {\n    ++iter;\n    cblas_dgemv(CblasRowMajor, CblasNoTrans, mat.size1(), mat.size2(), 1, &(mat.data()[0]), mat.size1(), &(t1.data()[0]), 1, 0.0, &(t2.data()[0]), 1);\n    //ublas::axpy_prod(mat, t1, t2, true);\n    t2 /= ublas::norm_1(t2);\n    ++iter;\n    cblas_dgemv(CblasRowMajor, CblasNoTrans, mat.size1(), mat.size2(), 1, &(mat.data()[0]), mat.size1(), &(t2.data()[0]), 1, 0.0, &(t1.data()[0]), 1);\n    //ublas::axpy_prod(mat, t2, t1, true);\n    t1 /= ublas::norm_1(t1);\n  } while(!iter.converged(t2.begin(), t2.end(), t1.begin(), dist));\n\n  size_t cnt_zero = std::count_if(t2.begin(), t2.end(), std::bind2nd(std::equal_to<double>(), 0.0));\n  bool enought_non_zero   = ( cnt_zero < 0.7 * t2.size() );\n  bool all_entries_finite = ( std::count_if(t2.begin(), t2.end(),\n        boost::math::isfinite<double>) == (long)t2.size() );\n  return ( enought_non_zero && all_entries_finite );\n}\n\n\ndouble rhab::calculate_error(const vector_double_t &exact,\n                             const vector_double_t &dos,\n                             error_mat_t* error_per_bin,\n                             const size_t& index, bool normalize) {\n  if (dos.size() == 0 || exact.size() == 0) {\n    std::cerr << \"exact or calculated density of states vector has zero length!\" << std::endl;\n    return -1;\n  }\n\n  // vector to calculate the error\n  vector_double_t err(dos.size());\n  std::fill(err.begin(), err.end(), 0.0);\n\n  double sum = 0.0;\n  size_t cnt = 0;\n  double norm = 0;\n\n  if (normalize) {\n    /*\n     * Density of states provided in dos is actually \\f$\\ln(\\Omega)\\f$.\n     * Find the largest value, then subtract it from dos[i]\n     * and sum exp(dos[i] - max) to calculate the norm.\n     * Then divide the every exp(dos[i] - max) by the norm\n     * and subtract the exact value, i.e. exact[i].\n     * Calculate the absolute value of it and divide by exact[i].\n     *\n     * exact[i] is assumed to be positive\n     *\n     * @todo: calculate both error in density of states and entropy,\n     *        i.e. additionally dos[i]-log(exact[i])/log(exact[i])\n     */\n\n    // create a copy\n    vector_double_t d(dos);\n    // and find median\n    vector_double_t::iterator middle = d.begin()+(d.end()-d.begin())/2;\n    std::nth_element(d.begin(), middle, d.end());\n    double sub  = *middle;\n\n    // calculate the norm\n    for (size_t i = 0; i < dos.size(); i++) {\n      // Be careful here! The least squares and minimization algorithms\n      // tend to calculate very large values for states that have never been\n      // visited. Having a very large max value results in the exp(foo-max)\n      // to become 0\n      if ((exact[i]) > 0) {\n        norm += exp(dos[i]-sub);\n#ifdef DEBUG\n        if (!boost::math::isfinite(norm) || !boost::math::isfinite(dos[i])\n            || !boost::math::isfinite(exp(dos[i]-sub))) {\n          std::cerr << __FILE__ << \":\" << __LINE__ << \" \"\n                    << norm << \" \" << dos[i] << \" \" << exp(dos[i]-sub) << std::endl;\n        }\n#endif\n      }\n    }\n\n    // yeah, I know that one should not compare doubles by equal\n    if (norm == 0) {\n      norm = 1;\n    }\n\n    for (size_t i = 0; i < dos.size(); i++) {\n      // Be careful here and do not devide by 0\n      if ((exact[i]) > 0) {\n        err[i] = fabs( (exp(dos[i]-sub)/norm - exact[i]) / exact[i] );\n        sum += err[i];\n        cnt ++;\n        (*error_per_bin)(index, i)(err[i]);\n#ifdef DEBUG\n        if (!boost::math::isfinite(sum) || !boost::math::isfinite(exact[i])\n            || !boost::math::isfinite(err[i])) {\n          std::cerr << __FILE__ << \":\" << __LINE__ << \" \"\n                    << sum << \" \" << norm << \" \"\n                    << dos[i] <<  \" \" << exact[i] << std::endl;\n        }\n#endif\n      }\n    }\n  } else {\n    for (size_t i = 0; i < dos.size(); i++) {\n      if (exact[i] > 0) {\n        norm += dos[i];\n      }\n    }\n    for (size_t i = 0; i < dos.size(); i++) {\n      // Be careful here and do not divide by 0\n      if (exact[i] > 0) {\n        err[i] = fabs( (dos[i]/norm - exact[i]) / exact[i] );\n        sum += err[i];\n        cnt ++;\n        (*error_per_bin)(index, i)(err[i]);\n      }\n#ifdef DEBUG\n      if (!boost::math::isfinite(sum) || !boost::math::isfinite(dos[i])\n          || !boost::math::isfinite(exact[i])\n          || !boost::math::isfinite(err[i])) {\n        std::cerr << __FILE__ << \":\" << __LINE__ << \" \"\n                  << sum << \" \" << dos[i] << \" \" << exact[i] << std::endl;\n      }\n#endif\n    }\n  }\n\n  return (sum / cnt);\n}\n\ndouble rhab::calculate_error_q_matrix(const matrix_double_t &Qex, const matrix_double_t &Q) {\n  double value(0.0);\n  size_t cnt(0);\n  for (size_t i = 0; i < Qex.data().size(); i++) {\n    if (Qex.data()[i] > 0) {\n      double tmp = fabs(Qex.data()[i] - Q.data()[i])/Qex.data()[i];\n      value += tmp;\n      cnt ++;\n    }\n  }\n  return value / cnt;\n}\n\nboost::tuple<double, double, double, bool, bool, bool, double>\nrhab::calculate_error_q(const vector_double_t &exact,\n                        const matrix_double_t &Qexact,\n                        const matrix_int_t &Q, matrix_double_t &Qd,\n                        error_mat_tuple_t error_matrices,\n                        vector_double_t &dos_lsq,\n                        vector_double_t &dos_gth,\n                        vector_double_t &dos_pow,\n                        const size_t& index) {\n  std::fill(dos_lsq.begin(), dos_lsq.end(), 0.0);\n  std::fill(dos_gth.begin(), dos_gth.end(), 0.0);\n  std::fill(dos_pow.begin(), dos_pow.end(), 0.0);\n\n  // Least Squares\n  bool lq = calculate_dos_leastsquares(Q, Qd, dos_lsq);\n  //bool lq = calculate_dos_minimization(Q, Qd, dos);\n  double error_lsq = calculate_error(exact, dos_lsq, error_matrices.get<0>(), index, true);\n  if (!boost::math::isfinite(error_lsq)) {\n    lq = false;\n  }\n\n  // Least Squares uses Qd as workspace only, so compute Qd\n  normalize_q(Q, Qd);\n\n  // calculate error in Q matrix\n  double q_error = 0;\n  if (Qexact.size1() > 0) {\n    q_error = rhab::calculate_error_q_matrix(Qexact, Qd);\n  }\n\n  // GTH method\n  bool gth = calculate_dos_gth(Qd, dos_gth);\n  double error_gth = calculate_error(exact, dos_gth, error_matrices.get<1>(), index, false);\n\n  // GTH Method modifies Qd, so recompute\n  normalize_q(Q, Qd);\n\n  // Power method\n  bool pow = calculate_dos_power(Qd, dos_pow);\n  double error_pow = calculate_error(exact, dos_pow, error_matrices.get<2>(), index, false);\n\n  return boost::make_tuple(error_lsq, error_gth, error_pow,\n                           lq,        gth,       pow,\n                           q_error);\n}\n\nboost::tuple<double, double, double, bool,  bool,   bool>\nrhab::calculate_error_q_lj(const vector_double_t &exact,\n                           const matrix_int_t &Q, matrix_double_t &Qd,\n                           error_mat_tuple_t error_matrices,\n                           vector_double_t &dos_lsq,\n                           vector_double_t &dos_gth,\n                           vector_double_t &dos_pow,\n                           const size_t& index) {\n  std::fill(dos_lsq.begin(), dos_lsq.end(), 0.0);\n  std::fill(dos_gth.begin(), dos_gth.end(), 0.0);\n  std::fill(dos_pow.begin(), dos_pow.end(), 0.0);\n\n  // Least Squares\n  bool lq = calculate_dos_leastsquares(Q, Qd, dos_lsq);\n  //bool lq = calculate_dos_minimization(Q, Qd, dos_lsq);\n  double error_lsq = calculate_error(exact, dos_lsq, error_matrices.get<0>(), index, true);\n  if (!boost::math::isfinite(error_lsq)) {\n    lq = false;\n  }\n\n  // Least Squares uses Qd as workspace only, so compute Qd\n  normalize_q(Q, Qd);\n\n  // GTH method\n  bool gth = calculate_dos_gth(Qd, dos_gth);\n  double error_gth = calculate_error(exact, dos_gth, error_matrices.get<1>(), index, false);\n\n  // GTH Method modifies Qd, so recompute\n  normalize_q(Q, Qd);\n\n  // Power method\n  bool pow = calculate_dos_power(Qd, dos_pow);\n  double error_pow = calculate_error(exact, dos_pow, error_matrices.get<2>(), index, false);\n\n  return boost::make_tuple(error_lsq, error_gth, error_pow,\n                           lq,        gth,       pow);\n}\n\n\n/* vim: set ts=2 sw=2 sts=2 tw=0 expandtab :*/\n", "meta": {"hexsha": "16e8d5aead5f9a7dcd2640848762e28171ff5990", "size": 16566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/q_matrix_tools.cpp", "max_stars_repo_name": "Reen/density_of_states", "max_stars_repo_head_hexsha": "a2d2c7f9c955749f4ee3fd6c7b37a833ef8b9b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/q_matrix_tools.cpp", "max_issues_repo_name": "Reen/density_of_states", "max_issues_repo_head_hexsha": "a2d2c7f9c955749f4ee3fd6c7b37a833ef8b9b48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/q_matrix_tools.cpp", "max_forks_repo_name": "Reen/density_of_states", "max_forks_repo_head_hexsha": "a2d2c7f9c955749f4ee3fd6c7b37a833ef8b9b48", "max_forks_repo_licenses": ["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.6210720887, "max_line_length": 150, "alphanum_fraction": 0.583001328, "num_tokens": 5157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5870706379184802}}
{"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_TRIANGULATION_HPP\n#define PIC_COMPUTER_VISION_TRIANGULATION_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../image.hpp\"\n\n#include \"../util/math.hpp\"\n\n#include \"../util/eigen_util.hpp\"\n\n#include \"../computer_vision/nelder_mead_opt_triangulation.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n#else\n    #include <Eigen/Dense>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief triangulationLonguetHiggins computes triangulation using Longuet-Higgins equations.\n * @param point_0 is the point from the first view that matches point_1\n * @param point_1 is the point from the second view that matches point_0\n * @param R is the rotation matrix between the two views.\n * @param t is the translation matrix between the two views.\n * @return\n */\nPIC_INLINE Eigen::Vector3d triangulationLonguetHiggins(Eigen::Vector3d &point_0, Eigen::Vector3d &point_1, Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n    Eigen::Vector3d ret;\n\n    Eigen::Vector3d r_0 = Eigen::Vector3d(R(0, 0), R(0, 1), R(0, 2));\n    Eigen::Vector3d r_2 = Eigen::Vector3d(R(2, 0), R(2, 1), R(2, 2));\n\n    Eigen::Vector3d tmp = r_0 - point_1[0] * r_2;\n\n    ret[2] = tmp.dot(t) / tmp.dot(point_0);\n\n    ret[0] = point_0[0] * ret[2];\n    ret[1] = point_0[1] * ret[2];\n\n    return ret;\n}\n\n/**\n * @brief triangulationHartl\n * Sturm\n * @param point_0\n * @param point_1\n * @param R\n * @param t\n * @return\n */\nPIC_INLINE Eigen::Vector4d triangulationHartleySturm(Eigen::Vector3d &point_0, Eigen::Vector3d &point_1,\n                                          Eigen::Matrix34d &M0, Eigen::Matrix34d &M1, int maxIter = 100)\n{\n    Eigen::Vector4d M0_row[3], M1_row[3];\n\n    for(int i = 0; i < 3; i++) {\n        M0_row[i] = Eigen::Vector4d(M0(i, 0), M0(i, 1), M0(i, 2), M0(i, 3));\n        M1_row[i] = Eigen::Vector4d(M1(i, 0), M1(i, 1), M1(i, 2), M1(i, 3));\n    }\n\n    Eigen::Vector4d x;\n    double weight0 = 1.0;\n    double weight0_prev = 1.0;\n\n    double weight1 = 1.0;\n    double weight1_prev = 1.0;\n\n    int j = 0;\n    while(j < maxIter) {\n        Eigen::Vector4d A0 = (M0_row[0] - point_0[0] * M0_row[2]) / weight0;\n        Eigen::Vector4d A1 = (M0_row[1] - point_0[1] * M0_row[2]) / weight0;\n\n        Eigen::Vector4d A2 = (M1_row[0] - point_1[0] * M1_row[2]) / weight1;\n        Eigen::Vector4d A3 = (M1_row[1] - point_1[1] * M1_row[2]) / weight1;\n\n        Eigen::MatrixXd A(4, 4);\n        for(int i = 0; i < 4; i++) {\n            A(0, i) = A0[i];\n            A(1, i) = A1[i];\n            A(2, i) = A2[i];\n            A(3, i) = A3[i];\n        }\n\n        Eigen::JacobiSVD< Eigen::MatrixXd > svdA(A, Eigen::ComputeFullV);\n        Eigen::MatrixXd V = svdA.matrixV();\n        int n = int(V.cols()) - 1;\n\n        x[0] = V(0, n);\n        x[1] = V(1, n);\n        x[2] = V(2, n);\n        x[3] = V(3, n);\n        x /= x[3];\n\n        weight0_prev = weight0;\n        weight1_prev = weight1;\n\n        weight0 = x.dot(M0_row[2]);\n        weight1 = x.dot(M1_row[2]);\n\n        double d0 = weight0_prev - weight0;\n        double d1 = weight1_prev - weight1;\n        double err = sqrt(d0 * d0 + d1 * d1);\n\n        if(err < 1e-12){\n            break;\n        }\n\n        j++;\n    }\n\n    #ifdef PIC_DEBUG\n        printf(\"triangulationHartleySturm's Iterations: %d\\n\",j);\n    #endif\n\n    return x;\n}\n\n/**\n * @brief triangulationPoints\n * @param M0\n * @param M1\n * @param m0f\n * @param m1f\n * @param points_3d\n * @param colors\n * @param bColor\n */\nPIC_INLINE void triangulationPoints(Eigen::Matrix34d &M0,\n                                    Eigen::Matrix34d &M1,\n                                    std::vector< Eigen::Vector2f > &m0f,\n                                    std::vector< Eigen::Vector2f > &m1f,\n                                    std::vector< Eigen::Vector3d > &points_3d,\n                                    std::vector< unsigned char > &colors,\n                                    Image *img0 = NULL,\n                                    Image *img1 = NULL,\n                                    bool bColor = false\n                                  )\n{\n    if(m0f.size() != m1f.size()) {\n        return;\n    }\n\n    NelderMeadOptTriangulation nmTri(M0, M1);\n    for(unsigned int i = 0; i < m0f.size(); i++) {\n        //normalized coordinates\n        Eigen::Vector3d p0 = Eigen::Vector3d(m0f[i][0], m0f[i][1], 1.0);\n        Eigen::Vector3d p1 = Eigen::Vector3d(m1f[i][0], m1f[i][1], 1.0);\n\n        //triangulation\n        Eigen::Vector4d point = triangulationHartleySturm(p0, p1, M0, M1);\n\n        //non-linear refinement\n        nmTri.update(m0f[i], m1f[i]);\n        double tmpp[] = {point[0], point[1], point[2]};\n        double out[3];\n        nmTri.run(tmpp, 3, 1e-9f, 10000, &out[0]);\n\n        //output\n        points_3d.push_back(Eigen::Vector3d(out[0], out[1], out[2]));\n\n        if(bColor) {\n            float *color0 = (*img0)(int(m0f[i][0]), int(m0f[i][1]));\n            float *color1 = (*img1)(int(m1f[i][0]), int(m1f[i][1]));\n\n            for(int j = 0; j < img0->channels; j++) {\n                float c_mean = (color0[j] + color1[j]) * 0.5f;\n                c_mean = CLAMPi(c_mean, 0.0f, 1.0f);\n                unsigned char c = int(c_mean * 255.0f);\n                colors.push_back(c);\n            }\n        }\n    }\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_TRIANGULATION_HPP\n", "meta": {"hexsha": "f706f5579ddb32d9fba4d7c0f6b5ca3986e70ac7", "size": 5821, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/triangulation.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/triangulation.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/triangulation.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": 27.4575471698, "max_line_length": 146, "alphanum_fraction": 0.5559182271, "num_tokens": 1877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5869523105588482}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Fabien Le Floc'h\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 analytichestonengine.hpp\n    \\brief analytic Heston expansion engine\n*/\n\n#ifndef quantlib_heston_expansion_engine_hpp\n#define quantlib_heston_expansion_engine_hpp\n\n#include <ql/pricingengines/genericmodelengine.hpp>\n#include <ql/models/equity/hestonmodel.hpp>\n#include <ql/instruments/vanillaoption.hpp>\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    //! Heston-model engine for European options based on analytic expansions\n    /*! References:\n\n        M Forde, A Jacquier, R Lee, The small-time smile and term\n        structure of implied volatility under the Heston model\n        SIAM Journal on Financial Mathematics, 2012 - SIAM\n\n        M Lorig, S Pagliarani, A Pascucci, Explicit implied vols for\n        multifactor local-stochastic vol models\n        arXiv preprint arXiv:1306.5447v3, 2014 - arxiv.org\n\n        \\ingroup vanillaengines\n    */\n    class HestonExpansionEngine\n        : public GenericModelEngine<HestonModel,\n                                    VanillaOption::arguments,\n                                    VanillaOption::results> {\n      public:\n        enum HestonExpansionFormula { LPP2, LPP3, Forde };\n\n        HestonExpansionEngine(const boost::shared_ptr<HestonModel>& model,\n                              HestonExpansionFormula formula);\n\n        void calculate() const;\n\n      private:\n        const HestonExpansionFormula formula_;\n    };\n\n    /*! Interface to represent some Heston expansion formula.\n        During calibration, it would typically be initialized once per\n        implied volatility surface slice, then calls for each surface\n        strike to impliedVolatility(strike, forward) would be\n        performed.\n    */\n    class HestonExpansion {\n      public:\n        virtual ~HestonExpansion() {}\n        virtual Real impliedVolatility(const Real strike,\n                                       const Real forward) const = 0;\n    };\n\n    /*! Lorig Pagliarani Pascucci expansion of order-2 for the Heston model.\n        During calibration, it can be initialized once per expiry, and\n        called many times with different strikes.  The formula is also\n        available in the Mathematica notebook from the authors at\n        http://explicitsolutions.wordpress.com/\n    */\n    class LPP2HestonExpansion : public HestonExpansion {\n      public:\n        LPP2HestonExpansion(const Real kappa, const Real theta,\n                            const Real sigma, const Real v0,\n                            const Real rho, const Real term);\n        virtual Real impliedVolatility(const Real strike,\n                                       const Real forward) const;\n      private:\n        Real coeffs[3];\n        Real ekt, e2kt, e3kt, e4kt;\n        Real z0(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n        Real z1(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n        Real z2(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n    };\n\n    /*! Lorig Pagliarani Pascucci expansion of order-3 for the Heston model.\n        During calibration, it can be initialized once per expiry, and\n        called many times with different strikes.  The formula is also\n        available in the Mathematica notebook from the authors at\n        http://explicitsolutions.wordpress.com/\n    */\n    class LPP3HestonExpansion : public HestonExpansion{\n      public:\n        LPP3HestonExpansion(const Real kappa, const Real theta,\n                            const Real sigma, const Real v0,\n                            const Real rho, const Real term);\n        virtual Real impliedVolatility(const Real strike,\n                                       const Real forward) const;\n      private:\n        Real coeffs[4];\n        Real ekt, e2kt, e3kt, e4kt;\n        Real z0(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n        Real z1(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n        Real z2(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n        Real z3(Real t, Real kappa, Real theta,\n                Real delta, Real y, Real rho) const;\n    };\n\n    /*! Small-time expansion from\n        \"The small-time smile and term structure of implied volatility\n        under the Heston model\" M Forde, A Jacquier, R Lee - SIAM\n        Journal on Financial Mathematics, 2012 - SIAM\n    */\n    class FordeHestonExpansion : public HestonExpansion {\n      public:\n        FordeHestonExpansion(const Real kappa, const Real theta,\n                             const Real sigma, const Real v0,\n                             const Real rho, const Real term);\n        virtual Real impliedVolatility(const Real strike,\n                                       const Real forward) const;\n      private:\n        Real coeffs[5];\n    };\n\n}\n\n\n#endif\n", "meta": {"hexsha": "dcc00aef355014d1839955e89e05fa2d97212058", "size": 5694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/vanilla/hestonexpansionengine.hpp", "max_stars_repo_name": "japari/QuantLib", "max_stars_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/pricingengines/vanilla/hestonexpansionengine.hpp", "max_issues_repo_name": "japari/QuantLib", "max_issues_repo_head_hexsha": "c2670bd433289eaf98410e911d87156595ca6d67", "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/pricingengines/vanilla/hestonexpansionengine.hpp", "max_forks_repo_name": "TheOnlyDyson/QuantLib", "max_forks_repo_head_hexsha": "78a144bbc5030c9e417e810e44ee48cffe40cf70", "max_forks_repo_licenses": ["BSD-3-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.0, "max_line_length": 79, "alphanum_fraction": 0.6348788198, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5868985960601164}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <NTL/ZZ.h>\n\n\nNTL::ZZ mortal_fib(uintmax_t n, uintmax_t m)\n{\n    std::vector<NTL::ZZ> rabbits(m);\n    rabbits.at(0) = 1;\n    for (decltype(n) i = 0; i < n - 1; ++i) {\n        auto tmp = rabbits.at(0), total = NTL::to_ZZ(0);\n        for (decltype(m) j = 1; j < m; ++j) {\n            total += rabbits.at(j);\n            std::swap(rabbits.at(j), tmp);\n        }\n        rabbits.at(0) = total;\n    }\n    return std::accumulate(std::begin(rabbits),\n            std::end(rabbits),\n            NTL::to_ZZ(0));\n}\n\n\nint main()\n{\n    std::ifstream f(\"data/rosalind_fibd.txt\");\n    uintmax_t n, m;\n    f >> n;\n    f >> m;\n    f.close();\n    std::cout << mortal_fib(n, m) << std::endl;\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3e08d6850be11895c874406f13e85152d95161f5", "size": 806, "ext": "cc", "lang": "C++", "max_stars_repo_path": "rosalind/fibd2.cc", "max_stars_repo_name": "genos/online_problems", "max_stars_repo_head_hexsha": "324597e8b64d74ad96dbece551a8220a1b61e615", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T13:15:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T13:15:21.000Z", "max_issues_repo_path": "rosalind/fibd2.cc", "max_issues_repo_name": "genos/online_problems", "max_issues_repo_head_hexsha": "324597e8b64d74ad96dbece551a8220a1b61e615", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rosalind/fibd2.cc", "max_forks_repo_name": "genos/online_problems", "max_forks_repo_head_hexsha": "324597e8b64d74ad96dbece551a8220a1b61e615", "max_forks_repo_licenses": ["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.7837837838, "max_line_length": 56, "alphanum_fraction": 0.5322580645, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096227509861, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5868926838692418}}
{"text": "#pragma once\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n#include \"GNAObject.hh\"\n\nclass GaussianPeakWithBackground: public GNAObject,\n                                  public TransformationBind<GaussianPeakWithBackground> {\npublic:\n  GaussianPeakWithBackground() {\n    variable_(&m_b, \"BackgroundRate\");\n    variable_(&m_mu, \"Mu\");\n    variable_(&m_E0, \"E0\");\n    variable_(&m_w, \"Width\");\n\n    transformation_(\"rate\")\n      .input(\"E\")\n      .output(\"rate\")\n      .types(Atypes::pass<0,0>)\n      .func(&GaussianPeakWithBackground::calcRate)\n      ;\n  }\n\n  void calcRate(Args args, Rets rets) {\n    const double pi = boost::math::constants::pi<double>();\n    const auto &E = args[0].arr;\n    rets[0].arr = m_b + m_mu*(1./std::sqrt(2*pi*m_w))*(-(E-m_E0).square()/(2*m_w*m_w)).exp();\n  }\nprotected:\n  variable<double> m_b, m_mu, m_E0, m_w;\n};\n", "meta": {"hexsha": "71b5502a5f760e5dbe3993fd23f487dab36de03f", "size": 862, "ext": "hh", "lang": "C++", "max_stars_repo_path": "doc/source/examples/GaussianPeakWithBackground.hh", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "doc/source/examples/GaussianPeakWithBackground.hh", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/source/examples/GaussianPeakWithBackground.hh", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1212121212, "max_line_length": 93, "alphanum_fraction": 0.626450116, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5868926809346279}}
{"text": "#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Eigen_solver_traits.h>\n#include <CGAL/Mean_curvature_flow_skeletonization.h>\n#include <CGAL/iterator.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n#include <CGAL/Bbox_3.h>\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <CGAL/boost/iterator/transform_iterator.hpp>\n\n#include <Eigen/SparseLU>\n#include <Eigen/Sparse>\n\n#include <fstream>\n#include <map>\n\n\ntypedef CGAL::Simple_cartesian<double>                                    Kernel;\ntypedef Kernel::Point_3                                                    Point;\ntypedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Polyhedron;\n\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor    vertex_descriptor;\n\ntypedef CGAL::Eigen_solver_traits<\n        Eigen::SparseLU<\n        CGAL::Eigen_sparse_matrix<double>::EigenType,\n        Eigen::COLAMDOrdering<int> >  >                         SparseLU_solver;\n\ntypedef CGAL::Eigen_solver_traits<\n        Eigen::SimplicialLDLT<\n        CGAL::Eigen_sparse_matrix<double>::EigenType\n         >  >                                             SimplicialLDLT_solver;\n\ntypedef CGAL::Default                                                         D;\n\n// The input of the skeletonization algorithm must be a pure triangular closed\n// mesh and has only one component.\nbool is_mesh_valid(Polyhedron& pMesh)\n{\n  if (!pMesh.is_closed())\n  {\n    std::cerr << \"The mesh is not closed.\";\n    return false;\n  }\n  if (!pMesh.is_pure_triangle())\n  {\n    std::cerr << \"The mesh is not a pure triangle mesh.\";\n    return false;\n  }\n\n  // the algorithm is only applicable on a mesh\n  // that has only one connected component\n  std::size_t num_component;\n  CGAL::Counting_output_iterator output_it(&num_component);\n  CGAL::internal::corefinement::extract_connected_components(pMesh, output_it);\n  ++output_it;\n  if (num_component != 1)\n  {\n    std::cerr << \"The mesh is not a single closed mesh. It has \"\n              << num_component << \" components.\";\n    return false;\n  }\n  return true;\n}\n\nint main()\n{\n  Polyhedron mesh;\n  std::ifstream input(CGAL::data_file_path(\"meshes/elephant.off\"));\n\n  if ( !input || !(input >> mesh) || mesh.empty() ) {\n    std::cerr << \"Cannot open data/elephant.off\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  if (!is_mesh_valid(mesh)) {\n    return EXIT_FAILURE;\n  }\n\n\n\n  int NTEST = 10;\n  double sum = 0;\n  for (int i = 0; i < NTEST; i++)\n  {\n    typedef CGAL::Mean_curvature_flow_skeletonization<Polyhedron, D, D, SparseLU_solver> MCF_skel;\n    MCF_skel::Skeleton skeleton;\n\n    CGAL::Timer timer;\n    timer.start();\n    MCF_skel mcf_skel(mesh);\n    mcf_skel(skeleton);\n    timer.stop();\n    sum += timer.time();\n  }\n  std::cout << \"Time of SparseLU: \" << sum / NTEST << \"\\n\";\n\n  sum = 0;\n  for (int i = 0; i < NTEST; i++)\n  {\n    typedef CGAL::Mean_curvature_flow_skeletonization<Polyhedron, D, D, SimplicialLDLT_solver> MCF_skel;\n    MCF_skel::Skeleton skeleton;\n\n    CGAL::Timer timer;\n    timer.start();\n    MCF_skel mcf_skel(mesh);\n    mcf_skel(skeleton);\n    timer.stop();\n    sum += timer.time();\n  }\n  std::cout << \"Time of SimplicialLDLT: \" << sum / NTEST << \"\\n\";\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "a6530898b5115be3449bebd79f8bfc3c5854f485", "size": 3409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_skeletonization/benchmark/Surface_mesh_skeletonization/solver_benchmark.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_skeletonization/benchmark/Surface_mesh_skeletonization/solver_benchmark.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_skeletonization/benchmark/Surface_mesh_skeletonization/solver_benchmark.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.4083333333, "max_line_length": 104, "alphanum_fraction": 0.6506306835, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5868926780000139}}
{"text": "#include <fstream>\n#include <assert.h> \n#include <stdlib.h>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/plod_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n\n\nvoid printUsageAndExit()\n{\n  printf(\"%s\", \"Usage:./plodg x\\n\");\n  printf(\"%s\", \"x is the size of the graph\\n\");\n  exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n  \n  /* \" The Power Law Out Degree (PLOD) algorithm generates a scale-free graph from three parameters, n, alpha, and beta.\n  [...] The value of beta controls the y-intercept of the curve, so that increasing beta increases the average degree of vertices (credit = beta*x^-alpha). \n  [...] The value of alpha controls how steeply the curve drops off, with larger values indicating a steeper curve. */\n  // From Boost documentation http://www.boost.org/doc/libs/1_47_0/libs/graph/doc/plod_generator.html\n  \n  // we use setS aka std::set for edges storage\n  // so we have at most one edges between 2 vertices\n  // the extra cost is O(log(E/V)).\n  typedef boost::adjacency_list<boost::setS> Graph;\n  typedef boost::plod_iterator<boost::minstd_rand, Graph> SFGen;\n\n  if (argc < 2) printUsageAndExit();\n  int size = atoi (argv[1]);\n  assert (size > 1 && size < INT_MAX);\n  double alpha = 2.57; // It is known that web graphs have alpha ~ 2.72.\n  double beta = size*512+1024; // This will give an average degree ~ 15\n\n  // generation\n  std::cout << \"generating ... \"<<'\\n';\n  boost::minstd_rand gen;\n  Graph g(SFGen(gen, size, alpha, beta, false), SFGen(), size);\n  boost::graph_traits<Graph>::edge_iterator edge, edge_end;\n  \n  std::cout << \"vertices : \"      << num_vertices(g) <<'\\n';\n  std::cout << \"edges : \"         << num_edges(g) <<'\\n';\n  std::cout << \"average degree : \"<< static_cast<float>(num_edges(g))/num_vertices(g)<< '\\n';\n  // Print in matrix coordinate real general format\n  std::cout << \"writing ... \"<<'\\n';\n  std::stringstream tmp;\n  tmp <<\"local_test_data/plod_graph_\" << size << \".mtx\";\n  const std::string filename = tmp.str();\n  std::ofstream fout(tmp.str().c_str()) ;\n  \n  if (argv[2]==NULL)\n  {\n    // Power law out degree with random weights\n    fout << \"%%MatrixMarket matrix coordinate real general\\n\";\n    fout << num_vertices(g) <<' '<< num_vertices(g)  <<' '<< num_edges(g) << '\\n';\n    float val;\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n    {\n      val = (rand()%10)+(rand()%100)*(1e-2f);\n      fout << boost::source(*edge, g) << ' ' << boost::target(*edge, g)<< ' ' << val << '\\n';\n    }\n  }\n  else if (argv[2][0]=='i')\n  {\n    // Power law in degree (ie the transpose will have a power law)\n    // -- Edges only --\n    // * Wraning * edges will be unsorted, use sort_edges.cpp to sort the dataset.\n    fout << num_vertices(g) <<' '<< num_edges(g) << '\\n';\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n      fout <<boost::target(*edge, g)<< ' ' << boost::source(*edge, g) << '\\n';\n  }\n  else if (argv[2][0]=='o')\n  {\n    // Power law out degree\n    // -- Edges only --\n    fout << num_vertices(g) <<' '<< num_edges(g) << '\\n';\n    for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n      fout << boost::source(*edge, g) << ' ' << boost::target(*edge, g)<< '\\n';\n  }\n  else printUsageAndExit();\n\n  fout.close();\n  std::cout << \"done!\"<<'\\n';\n  return 0;\n}\n\n", "meta": {"hexsha": "dab6528cc3ca7520dd3c6364c5724b5c90692b39", "size": 3384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nvgraph/test/generators/plod.cpp", "max_stars_repo_name": "seunghwak/cugraph", "max_stars_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-09-13T11:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:11:59.000Z", "max_issues_repo_path": "cpp/nvgraph/test/generators/plod.cpp", "max_issues_repo_name": "seunghwak/cugraph", "max_issues_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T14:55:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T17:55:12.000Z", "max_forks_repo_path": "cpp/nvgraph/test/generators/plod.cpp", "max_forks_repo_name": "seunghwak/cugraph", "max_forks_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-04-06T01:34:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T17:13:24.000Z", "avg_line_length": 37.6, "max_line_length": 156, "alphanum_fraction": 0.6190898345, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925404, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.5867953179939871}}
{"text": "/* Tags: Delaunay Triangulation, Union-Find, Connected Components, Closest Neighbor \n\n  Key idea: 1:1 correspondence between points being connected (connected components in EMST)\n                <==>\n                we can move between the disks of the points\n                (for a radius >= 2 * minimal distance betw. them) \n            Can copy code from the EMST template, and adapt:\n            * three UF structures, one for the given radius U_p,\n              U_a: minimum power needed to execute _all_ missions\n              U_b: minimum power needed to execute same set of missions as with inital p\n            * First connect components of U_p with edges <= p\n            * then see, for each mission, if 4*distance <= p and\n              components are connected, mission can be executed\n            * If can be executed: enlarge U_b until it is covered\n            * In any case: enlarge U_a until it is covered\n\n*/\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n#include <iostream>\n\n// Epic kernel is enough, no constructions needed, provided the squared distance\n// fits into a double (!)\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n// we want to store an index with each vertex\ntypedef std::size_t                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Triangulation;\n\n// As edges are not explicitly represented in the triangulation, we extract them\n// from the triangulation to be able to sort and process them. We store the\n// indices of the two endpoints, first the smaller, second the larger, and third\n// the squared length of the edge. The i-th entry, for i=0,... of a tuple t can\n// be accessed using std::get<i>(t).\ntypedef std::tuple<Index,Index,double> Edge;\ntypedef std::vector<Edge> EdgeV;\n\nvoid solve() {\n  Index n, m;\n  double p;\n  std::cin >> n >> m >> p;\n\n  // read points\n  typedef std::pair<K::Point_2,Index> IPoint;\n  std::vector<IPoint> jammers;\n  jammers.reserve(n);\n  for (Index i = 0; i < n; ++i) {\n    int x, y;\n    std::cin >> x >> y;\n    jammers.push_back({K::Point_2(x, y), i});\n  }\n  // construct triangulation\n  Triangulation t;\n  t.insert(jammers.begin(), jammers.end());\n  \n  // extract edges and sort by (squared) length\n  // This step takes O(n log n) time (for the sorting).\n  EdgeV edges;\n  edges.reserve(3*n); // there can be no more in a planar graph\n  for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n    Index i1 = e->first->vertex((e->second+1)%3)->info();\n    Index i2 = e->first->vertex((e->second+2)%3)->info();\n    // ensure smaller index comes first\n    if (i1 > i2) std::swap(i1, i2);\n    edges.emplace_back(i1, i2, t.segment(e).squared_length());\n  }\n  std::sort(edges.begin(), edges.end(),\n      [](const Edge& e1, const Edge& e2) -> bool {\n        return std::get<2>(e1) < std::get<2>(e2);\n            });\n\n  // setup and initialize union-find data structure for initial power\n  boost::disjoint_sets_with_storage<> uf_p(n);\n  for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n    // determine components of endpoints\n    Index c1 = uf_p.find_set(std::get<0>(*e));\n    Index c2 = uf_p.find_set(std::get<1>(*e));\n    double squared_dist = std::get<2>(*e);\n    if (squared_dist <= p){\n      if(c1 != c2) {\n       // this edge connects two different components => part of the emst\n        uf_p.link(c1, c2);\n      }\n    } else {\n      break;\n    }\n  }\n\n\n  K::FT a = 0, b = 0;\n  // setup and initialize union-find data structure for \n  // a: minimum power needed to execute _all_ missions\n  // b: minimum power needed to execute same set of missions as with inital p\n\n  boost::disjoint_sets_with_storage<> uf_a(n);\n  boost::disjoint_sets_with_storage<> uf_b(n);\n\n  // we continously enlarge the tree components for a and b,\n  // so we need to remember where we left off for new missions\n  EdgeV::const_iterator e_iter_a = edges.begin();\n  EdgeV::const_iterator e_iter_b = edges.begin();\n  Index n_components_a = n;\n  Index n_components_b = n;\n  for (Index j = 0; j < m; j++) {\n    int x0, y0, x1, y1; std::cin >> x0 >> y0 >> x1 >> y1;\n    auto sj = K::Point_2(x0, y0);\n    auto tj = K::Point_2(x1, y1);\n\n    auto vertex_sj = t.nearest_vertex(sj);\n    auto vertex_tj = t.nearest_vertex(tj);\n    double dist_sj = CGAL::squared_distance(sj, vertex_sj->point());\n    double dist_tj = CGAL::squared_distance(tj, vertex_tj->point());\n    K::FT max_dist_start = 4 * std::max(dist_sj, dist_tj);\n\n    Index vi0 = vertex_sj->info();\n    Index vi1 = vertex_tj->info();\n\n    // mission is possible with intial power\n    if(max_dist_start <= p && uf_p.find_set(vi0) == uf_p.find_set(vi1)) {\n      std::cout << \"y\";\n      double squared_dist_needed = 0;\n      // since covered, increase the tree of b until points are connected\n      while(uf_b.find_set(vi0) != uf_b.find_set(vi1) && e_iter_b != edges.end()\n            && n_components_b != 0) {\n        Index c1 = uf_b.find_set(std::get<0>(*e_iter_b));\n        Index c2 = uf_b.find_set(std::get<1>(*e_iter_b));\n        squared_dist_needed = std::get<2>(*e_iter_b);\n        if(c1 != c2) {\n          // this edge connects two different components\n          uf_b.link(c1, c2);\n          n_components_b--;\n        }\n        e_iter_b++;\n      }\n      b = std::max({squared_dist_needed, max_dist_start, b});\n    } else {\n      std::cout << \"n\";\n    }\n\n    // same as above but for trees a\n    double squared_dist_needed = 0;\n    // since covered, increase the tree of b until points are connected\n    while(uf_a.find_set(vi0) != uf_a.find_set(vi1) && e_iter_a != edges.end()\n           && n_components_a != 0) {\n      Index c1 = uf_a.find_set(std::get<0>(*e_iter_a));\n      Index c2 = uf_a.find_set(std::get<1>(*e_iter_a));\n      squared_dist_needed = std::get<2>(*e_iter_a);\n      if(c1 != c2) {\n        // this edge connects two different components\n        uf_a.link(c1, c2);\n        n_components_a--;\n      }\n      e_iter_a++;\n    }\n    a = std::max({squared_dist_needed, max_dist_start, a});\n  }\n\n  std::cout << \"\\n\" << a << \"\\n\" << b << \"\\n\";\n}\n\nint main() \n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(0);\n  std::size_t t;\n  for (std::cin >> t; t > 0; --t) solve();\n  return 0;\n}", "meta": {"hexsha": "6bc99e1d362c64730ad291ce379ffc471bfd6a12", "size": 6726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week10-potw-goldeneye/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/week10-potw-goldeneye/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/week10-potw-goldeneye/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": 38.2159090909, "max_line_length": 92, "alphanum_fraction": 0.6321736545, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5867839118919906}}
{"text": "/*! Little utility to generate a camflow grid.\n *  Laurence McGlashan (lrm29@cam.ac.uk)\n */\n\n#include \"boost/program_options.hpp\"\n#include <boost/math/distributions/triangular.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <fstream>\n#include <iomanip>\n#include <numeric>\n#include <iostream>\n\nusing namespace boost::program_options;\nusing namespace boost::math;\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n\n    cout << argv[0] << \" by Laurence McGlashan\\n\" << endl;\n\n    string outputFile = \"grid.inp\";\n    string distType;\n    double stMixFrac = -1;\n    int numberOfCells, numberOfCellsLower, numberOfCellsUpper = -1;\n\n    {\n        // Parse arguments.\n        options_description desc(\"Allowed options for program\");\n        desc.add_options()\n            (\"help\", \"Show this help message.\")\n            (\"stoich\", value<double>(), \"Stoichiometric mixture fraction.\")\n            (\"outputFile\", value<string>(), \"Output file for grid.\")\n            (\"cells\", value<int>(), \"Number of cells.\")\n            (\"distribution\", value<string>(), \"Type of distribution to weight points against (triangular|normal).\");\n\n        variables_map vm;\n        store(parse_command_line(argc, argv, desc), vm);\n        notify(vm);\n\n        if (vm.count(\"help\")) {\n            cout << desc << \"\\n\";\n            return 1;\n        }\n\n        if (vm.count(\"stoich\")) {\n            stMixFrac = vm[\"stoich\"].as<double>();\n            if (stMixFrac <= 0)\n                throw std::logic_error(\"Stochiometric mixture fraction must be greater than 0.\\n\");\n            cout<< \"Stochiometric mixture fraction is \" << stMixFrac << \".\\n\";\n        } else {\n            throw std::logic_error(\"Stochiometric mixture fraction was not provided.\\n\");\n        }\n\n        if (vm.count(\"cells\")) {\n            numberOfCells = vm[\"cells\"].as<int>();\n            if (numberOfCells <= 0)\n                throw std::logic_error(\"Number of cells must be greater than 2.\\n\");\n            if (numberOfCells%2 != 0)\n                throw std::logic_error(\"Number of cells must be even.\\n\");\n            cout<< \"Number of cells is \" << numberOfCells << \".\\n\";\n        } else {\n            throw std::logic_error(\"Number of cells was not provided.\\n\");\n        }\n\n        if (vm.count(\"distribution\")) {\n            distType = vm[\"distribution\"].as<string>();\n            if (distType != \"triangular\" && distType != \"normal\")\n                    throw std::logic_error(\"Distribution \" + distType + \" not available.\\n\");\n            cout<< \"Distribution used will be \" << distType << \".\\n\";\n        } else {\n            throw std::logic_error(\"Distribution was not provided.\\n\");\n        }\n\n        if (vm.count(\"outputFile\")) {\n            outputFile = vm[\"outputFile\"].as<string>();\n            cout<< \"Grid will be output to \"\n                << outputFile << \".\\n\";\n        } else {\n            cout<< \"outputFile was not provided. Use default of grid.inp.\\n\";\n        }\n    }\n\n    // Calculate the grid here. The values are the cell edges.\n    vector<double> grid;\n    grid.push_back(0.0);\n    grid.push_back(stMixFrac);\n    grid.push_back(1.0);\n\n    numberOfCellsLower = numberOfCells/2.0;\n    numberOfCellsUpper = numberOfCells/2.0;\n\n    //////////// Generate grid here ///////////\n\n    // Construct uniform grid.\n    for (size_t i=1; i<numberOfCellsLower; ++i)\n    {\n            grid.push_back(2.0*i*stMixFrac/numberOfCells);\n    }\n    for (size_t i=1; i<numberOfCellsUpper; ++i)\n    {\n            grid.push_back(stMixFrac + 2.0*i*(1.0-stMixFrac)/numberOfCells);\n    }\n\n    // Sort the values.\n    sort(grid.begin(), grid.end());\n\n    if (distType == \"triangular\")\n    {\n        triangular s(0.0,stMixFrac,1.0);\n        double max = pdf(s,stMixFrac);\n        for (size_t i=1; i<=numberOfCells; ++i)\n        {\n            grid[i] = stMixFrac + (grid[i]-stMixFrac)*(1.0-pdf(s,grid[i])/max);\n        }\n    }\n\n    if (distType == \"normal\")\n    {\n        normal s(stMixFrac,0.5);\n        vector<double> spacingFactor, pdfSaved;\n        \n        for (size_t i=0; i<=numberOfCells; ++i) \n            pdfSaved.push_back(pdf(s,grid[i]));\n            \n        for (size_t i=0; i<numberOfCells; ++i)\n            spacingFactor.push_back(abs(pdfSaved[i+1] - pdfSaved[i]));\n\n        double normalise = accumulate(spacingFactor.begin(),spacingFactor.end(),0.0);\n        for (size_t i=1; i<numberOfCells; ++i)\n            grid[i] = grid[i-1] + abs(pdfSaved[i]-pdfSaved[i-1])/normalise;\n    }\n\n    //////////// End Generate grid here ///////\n\n    // Sort the values.\n    sort(grid.begin(), grid.end());\n\n    // Output the grid.\n    ofstream out;\n    out.open(outputFile.c_str(), ios::trunc);\n    if (out.good())\n    {\n        for (size_t i=0; i<grid.size(); ++i)\n        {\n            out << setprecision(10) << grid[i] << endl;\n        }\n    }\n\n    cout << \"\\nProgram End.\" << endl;\n\n    return 0;\n\n}\n\n", "meta": {"hexsha": "ebe6b922d59571c63b65a5c96485403475447381", "size": 4874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/utilities/camflowGridGenerator/camflowGridGenerator.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "applications/utilities/camflowGridGenerator/camflowGridGenerator.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "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/utilities/camflowGridGenerator/camflowGridGenerator.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 31.2435897436, "max_line_length": 116, "alphanum_fraction": 0.5564218301, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5867839076264565}}
{"text": "#ifndef QUADRATICPROBLEM_H\n#define QUADRATICPROBLEM_H\n\n#include <CoMISo/Config/config.hh>\n#include <CoMISo/Utils/StopWatch.hh>\n#include <vector>\n#include <CoMISo/NSolver/NProblemInterface.hh>\n#include <Base/Code/Quality.hh>\nLOW_CODE_QUALITY_SECTION_BEGIN\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\nLOW_CODE_QUALITY_SECTION_END\n\n\n//== NAMESPACES ===============================================================\n\nnamespace COMISO {\n\n// this problem optimizes the quadratic functional 0.5*x^T A x -x^t b + c\nclass QuadraticProblem : public COMISO::NProblemInterface\n{\npublic:\n\n  // Sparse Matrix Type\n  //  typedef Eigen::DynamicSparseMatrix<double,Eigen::ColMajor> SMatrixNP;\n\n  QuadraticProblem()\n  : A_(0,0), b_(Eigen::VectorXd::Index(0)), c_(0.0)\n  {\n\n  }\n\n  QuadraticProblem(SMatrixNP& _A, Eigen::VectorXd& _b, const double _c)\n  : A_(_A), c_(_c)\n  {\n    if(A_.rows() != A_.cols())\n      std::cerr << \"Warning: matrix not square in QuadraticProblem\" << std::endl;\n    b_ = _b;\n    x_ = Eigen::VectorXd::Zero(A_.cols());\n  }\n\n\n  // number of unknowns\n  virtual int n_unknowns()\n  {\n     return A_.rows();\n  }\n\n  // initial value where the optimization should start from\n  virtual void initial_x(double* _x)\n  {\n        for( int i=0; i<this->n_unknowns(); ++i)\n            _x[i] = x_[i];\n  }\n\n  // function evaluation at location _x\n  virtual double eval_f( const double* _x )\n  {\n    Eigen::Map<const Eigen::VectorXd> x(_x, this->n_unknowns());\n\n    return (double)(x.transpose()*A_*x)*0.5 - (double)(x.transpose()*b_) + c_;\n  }\n\n  // gradient evaluation at location _x\n  virtual void   eval_gradient( const double* _x, double*    _g)\n  {\n    Eigen::Map<const Eigen::VectorXd> x(_x, this->n_unknowns());\n    Eigen::Map<Eigen::VectorXd> g(_g, this->n_unknowns());\n\n    g = A_*x - b_;\n   }\n\n  // hessian matrix evaluation at location _x\n  virtual void   eval_hessian ( const double* _x, SMatrixNP& _H)\n  {\n    _H = A_;\n  }\n\n  // print result\n  virtual void   store_result ( const double* _x               )\n  {\n    Eigen::Map<const Eigen::VectorXd> x(_x, this->n_unknowns());\n    x_ = x;\n  }\n\n  // get current solution\n  Eigen::VectorXd& x() { return x_;}\n\n  // advanced properties\n  virtual bool   constant_hessian() const { return true; }\n\n  void set_A(const SMatrixNP& _A)\n  {\n    A_ = _A;\n    if(A_.rows() != A_.cols())\n        std::cerr << \"Warning: matrix not square in QuadraticProblem\" << std::endl;\n    x_ = Eigen::VectorXd::Zero(A_.cols());\n  }\n\n  void set_b(const Eigen::VectorXd& _b)\n  {\n    b_ = _b;\n  }\n\n  void set_c( const double _c)\n  {\n    c_ = _c;\n  }\n\nprivate:\n\n  // quadratic problem 0.5*x^T A x -x^t b + c\n SMatrixNP       A_;\n Eigen::VectorXd b_;\n double          c_;\n // current solution, which is also used as initial value\n Eigen::VectorXd x_;\n};\n\n//=============================================================================\n} // namespace COMISO\n//=============================================================================\n\n#endif // QUADRATICPROBLEM_H\n", "meta": {"hexsha": "b3d942933488f2b9d66514b6c3e848feabb17eff", "size": 3009, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ACAP_linux/3rd/CoMISo/NSolver/QuadraticProblem.hh", "max_stars_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_stars_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "ACAP_linux/3rd/CoMISo/NSolver/QuadraticProblem.hh", "max_issues_repo_name": "gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer", "max_issues_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/3rd/CoMISo/NSolver/QuadraticProblem.hh", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 23.880952381, "max_line_length": 83, "alphanum_fraction": 0.5958790296, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5867839020754575}}
{"text": "#include \"pch.h\"\n#include \"CalculatorCore.h\"\n#include <stack>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\nauto op_dict = unordered_map<char, int>{\n    {'\\n', 0},\n    {')',  0},\n    {'&',  1},\n    {'|',  1},\n    {'+',  2},\n    {'-',  2},\n    {'*',  3},\n    {'/',  3},\n    {'!',  4},\n    {'(',  5}\n};\n\nauto __calculator(stringstream& in, bool isInitial) -> cpp_dec_float_100 {\n    auto ops = stack<char>();\n    auto nums = stack<cpp_dec_float_100>();\n    auto calculate = [&] {\n        if (nums.empty())\n            throw runtime_error(\"Invalid expression\");\n        auto op = ops.top();\n        ops.pop();\n        auto res = (cpp_dec_float_100)0;\n        if (op == '!') {\n            auto x = nums.top();\n            nums.pop();\n            res = !x;\n            nums.push(res);\n            return;\n        }\n        if (nums.size() < 2)\n            throw runtime_error(\"Invalid expression\");\n        auto y = nums.top();\n        nums.pop();\n        auto x = nums.top();\n        nums.pop();\n        if (op == '+')\n            res = x + y;\n        else if (op == '-')\n            res = x - y;\n        else if (op == '*')\n            res = x * y;\n        else if (op == '&')\n            res = x && y;\n        else if (op == '|')\n            res = x || y;\n        else {\n            if (y == 0)\n                throw runtime_error(\"Math error\");\n            res = x / y;\n        }\n        nums.push(res);\n    };\n    while (!in.eof()) {\n        if (isdigit(in.peek())) {\n            auto temp = string();\n            while (isdigit(in.peek()))\n                temp += (char)in.get();\n            nums.push(cpp_dec_float_100(temp));\n            continue;\n        }\n        auto temp = (char)in.get();\n        auto priority = op_dict[temp];\n        if (priority == 2) {\n            while (op_dict[in.peek()] == 2)\n                temp = temp == in.get() ? '+' : '-';\n            if (nums.empty())\n                nums.push(0);\n        }\n        else if (priority == 3) {\n            auto ch = '+';\n            while (op_dict[in.peek()] == 2)\n                ch = ch == in.get() ? '+' : '-';\n            if (!nums.empty() && ch == '-') {\n                auto temp_num = nums.top();\n                nums.pop();\n                nums.push(-temp_num);\n            }\n        }\n        if (temp == '(') {\n            nums.push(__calculator(in, false));\n            continue;\n        }\n        while (!ops.empty() && priority <= op_dict[ops.top()])\n            calculate();\n        if (temp == ')') {\n            if (isInitial)\n                throw runtime_error(\"Invalid expression\");\n            break;\n        }\n        if (temp == '\\n')\n            break;\n        ops.push(temp);\n    }\n    if (!ops.empty() || nums.size() != 1)\n        throw runtime_error(\"Invalid expression\");\n    return nums.top();\n}\n\nauto calculator(stringstream& in) -> cpp_dec_float_100 {\n    return __calculator(in, true);\n}\n", "meta": {"hexsha": "5153dbed8558358e3f1e385cb11f408dbbc6ac4b", "size": 3019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Calculator/CalculatorCore.cpp", "max_stars_repo_name": "ToyaVoV/UWP-Calculater", "max_stars_repo_head_hexsha": "4a7f3a8b5171b53448ba39979bc69b9d43fc31ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Calculator/CalculatorCore.cpp", "max_issues_repo_name": "ToyaVoV/UWP-Calculater", "max_issues_repo_head_hexsha": "4a7f3a8b5171b53448ba39979bc69b9d43fc31ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Calculator/CalculatorCore.cpp", "max_forks_repo_name": "ToyaVoV/UWP-Calculater", "max_forks_repo_head_hexsha": "4a7f3a8b5171b53448ba39979bc69b9d43fc31ab", "max_forks_repo_licenses": ["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.7168141593, "max_line_length": 74, "alphanum_fraction": 0.4266313349, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5867838867079245}}
{"text": "/*!\n * \\file complex.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2020 Jun Yoshida.\n * The project is released under the 2-clause BSD License.\n * \\date August, 2020: created\n */\n\n#pragma once\n\n#include <cstdint>\n#include <array>\n#include <queue>\n\n#include <Eigen/Dense>\n\n#include \"hnf.hpp\"\n\n//* Debug\n#include \"debug/debug.hpp\"\n//*/\n\nnamespace khover {\n\n//! Representation of abelian groups by direct sums of cyclic groups.\nstruct AbGroupCyc {\n    //! Rank of the free part.\n    std::size_t freerank;\n    //! A list of torsions.\n    std::vector<int> torsions;\n\n    //! Check if the group is torion-free\n    inline bool isTorFree() const noexcept {\n        return torsions.empty();\n    }\n\n    //! Check if the group is finite (<=> trivial after tensored with Q)\n    inline bool isFinite() const noexcept {\n        return freerank == 0;\n    }\n\n    //! Check if the group is trivial\n    inline bool isZero() const noexcept {\n        return isFinite() && isTorFree();\n    }\n\n    //! Pretty printer\n    std::string pretty() const noexcept {\n        std::string str_free\n            = freerank == 0 ? std::string{} : freerank == 1 ? std::string(\"Z\") : \"Z^\" + std::to_string(freerank);\n        std::string str_tor{};\n\n        for(int t : torsions) {\n            if (!str_tor.empty())\n                str_tor += \"+\";\n            str_tor += \"Z/\" + std::to_string(t);\n        }\n\n        if(str_free.empty() && str_tor.empty())\n            return std::string(\"0\");\n        else if (str_free.empty())\n            return str_tor;\n        else if (str_tor.empty())\n            return str_free;\n        else\n            return str_free + \"+\" + str_tor;\n    }\n};\n\n//! Representation of abelian groups by representation matrices.\nclass AbelianGroup {\npublic:\n    using integer_t = int64_t;\n    using matrix_t = Eigen::Matrix<integer_t,Eigen::Dynamic,Eigen::Dynamic>;\n\nprivate:\n    //! The presentation matrix, which is kept to be a column HNF.\n    matrix_t m_repMat;\n    //! The least rank of the free part of the abelian group.\n    std::size_t m_freerk;\n\npublic:\n    //! Default constructor.\n    AbelianGroup() noexcept : m_repMat(0,0), m_freerk(0) {}\n\n    //! Constructor from a presentation matrix.\n    //! Represent an abelian group by a presentation matrix.\n    //! \\tparam IsColHNF If IsColHNF::value == true, then repMat must be in the column HNF. Otherwise, its column HNF is computed.\n    template <class Derived, class IsColHNF>\n    AbelianGroup(Eigen::MatrixBase<Derived> const& repMat, IsColHNF, std::size_t freerk = 0) noexcept\n        : m_repMat(repMat), m_freerk(freerk)\n    {\n        if constexpr(!IsColHNF::value) {\n            auto rk = hnf_LLL<khover::colops>(m_repMat, {}, {});\n            if(rk) {\n                m_repMat = m_repMat.leftCols(*rk).eval();\n            }\n            else {\n                ERR_MSG(\"Something bad happended.\");\n            }\n        }\n    }\n\n    //! Nothing special to do in destructor.\n    ~AbelianGroup() = default;\n\n    //! Get the number of generators.\n    inline std::size_t ngens() const noexcept {\n        return m_repMat.rows() + m_freerk;\n    }\n\n    //! Get the number of relations.\n    inline std::size_t nrels() const noexcept { return m_repMat.cols(); }\n\n    //! Get the presentation matrix.\n    inline auto get_repmatrix() const noexcept {\n        return (matrix_t(ngens(),nrels()) << m_repMat, matrix_t::Zero(m_freerk, m_repMat.cols())).finished();\n    }\n\n    //! Reduce the number of generators and relations by computing the Hermite normal form of the representation matrix.\n    //! This will suffice in order to compute the rank of the free part.\n    //! \\param post Homomorphisms whose domains are *this*. They will be transformed so that their domains will be the reduced one.\n    //! \\param pre Homomorphisms whose codomains are *this*. They will be transformed so that their codomains will be the reduced one.\n    //! \\return If the function fails to compute HNF correctly, or if the homomorphisms are wrong, then it returns false.\n    template <class...Posts, class...Pres>\n    bool reduce(\n        std::tuple<Posts&...> const & posts,\n        std::tuple<Pres&...> const & pres\n        ) noexcept\n    {\n        static_assert(\n            std::conjunction_v<\n            std::bool_constant<Posts::ColsAtCompileTime == Eigen::Dynamic>...\n            >,\n            \"The function may change the number of columns of matrices in the posts parameter, so make sure they have dynamic numbers of columns.\");\n\n        static_assert(\n            std::conjunction_v<\n            std::bool_constant<Pres::RowsAtCompileTime == Eigen::Dynamic>...\n            >,\n            \"The function may change the number of rows of matrices in the posts parameter, so make sure they have dynamic numbers of rows.\");\n\n        /*\n         * Take columns with pivot = 1 to left\n         */\n        // The rank of the presentation matrix over Q (the field of rationals).\n        std::size_t rk = 0;\n        // The number of columns with pivot = 1.\n        std::size_t upivs = 0;\n\n        // Traverse pivots\n        using Ops = khover::colops;\n        for(std::size_t i=0; i < Ops::size(m_repMat) && rk < Ops::dual_t::size(m_repMat); ++i) {\n            // A column with pivot 1 is found.\n            if (Ops::at(m_repMat, rk).coeff(i) == 1) {\n                // If there is a column with non-unit pivot on left, swap with it.\n                if (rk > upivs) {\n                    Ops::swap(m_repMat, rk, upivs);\n                }\n                // If the pivot is below diagonal, raise it.\n                if (i > upivs) {\n                    Ops::dual_t::swap(m_repMat, i, upivs);\n                    khover::for_each_tuple(\n                        pres,\n                        [i,upivs](auto& u) {\n                            Ops::dual_t::swap(u, i, upivs);\n                        });\n                    khover::for_each_tuple(\n                        posts,\n                        [i,upivs](auto& v) {\n                            Ops::swap(v, i, upivs);\n                        });\n                }\n                ++upivs;\n                ++rk;\n            }\n            // A column with pivot != 1 is found.\n            else if (Ops::at(m_repMat, rk).coeff(i) != 0) {\n                ++rk;\n            }\n        }\n\n        // Reduce homomorphisms\n        matrix_t redPiv_mat\n            = matrix_t::Identity(\n                m_repMat.rows() + m_freerk,\n                m_repMat.rows() + m_freerk\n                ).bottomRows(m_repMat.rows() + m_freerk - upivs);\n        redPiv_mat.block(0, 0, m_repMat.rows() - upivs, upivs).noalias()\n            = - m_repMat.bottomLeftCorner(m_repMat.rows() - upivs, upivs);\n\n        khover::for_each_tuple(\n            pres,\n            [&](auto& u) {\n                u = redPiv_mat.bottomRows(m_repMat.rows() + m_freerk - upivs) * u;\n            } );\n        khover::for_each_tuple(\n            posts,\n            [upivs](auto& v) {\n                v = v.rightCols(v.cols() - upivs); //v.block(0, upivs, v.rows(), v.cols()-upivs).eval();\n            } );\n\n        // Forget thw row/columns with unital pivots.\n        m_freerk += m_repMat.rows() - rk;\n        m_repMat = m_repMat.block(upivs, upivs, m_repMat.rows() - upivs, rk - upivs).eval();\n        rk -= upivs;\n\n        // Compute the row HNF\n        if (!hnf_LLL<khover::rowops>(m_repMat,posts, pres))\n            return false;\n\n        // Reduce the presentation matrix again.\n        m_repMat = m_repMat.topRows(rk).eval();\n\n        // Keep the presentation matrix in column HNF.\n        khover::hnf_LLL<khover::colops>(m_repMat, {}, {});\n\n        // Finish successfully.\n        return true;\n    }\n\n    //! Compute the abelian group in the form of the pair of the free rank and the list of torsions.\n    //! \\remark The result is not necessarily in the normal form.\n    AbGroupCyc\n    compute() noexcept {\n        do {\n            reduce({}, {});\n        } while(!m_repMat.isDiagonal());\n\n        auto diag = m_repMat.diagonal();\n        std::vector<int> torsions{};\n        std::size_t r = 0;\n\n        for(int i = 0; i < diag.size(); ++i) {\n            if (diag.coeff(i) == 0)\n                ++r;\n            else if(std::abs(diag.coeff(i)) != 1)\n                torsions.push_back(std::abs(diag.coeff(i)));\n        }\n\n        return {r+m_freerk, std::move(torsions)};\n    }\n\n    //! Compute the image of a homomorphism whose codomain is this abelian group.\n    //! \\tparam ReturnMorphism If ReturnMorphism::value == true, then the function also returns the matrix representing the morphism from the image to this group.\n    template <class Derived, class DoesReturnMorphism = std::false_type>\n    auto\n    image(\n        Eigen::MatrixBase<Derived> const& morph,\n        DoesReturnMorphism = DoesReturnMorphism{}\n        ) const noexcept\n        -> std::conditional_t<\n            DoesReturnMorphism::value,\n            std::optional<std::pair<AbelianGroup,matrix_t>>,\n            std::optional<AbelianGroup>\n            >\n    {\n        // If the number of rows doesn't agree, return immediately.\n        if(morph.rows() != static_cast<int>(m_freerk) + m_repMat.rows()) {\n            ERR_MSG(\"Incompatible rows:\"\n                    << morph.rows() << \" != \"\n                    << static_cast<int>(m_freerk) + m_repMat.rows());\n            return std::nullopt;\n        }\n\n        // Sum of the images of the homomorphism and the representation matrix.\n        matrix_t sumspace(morph.rows(), morph.cols() + m_repMat.cols());\n        sumspace << morph, get_repmatrix();\n\n        // Compute the column HNF of the sumspace.\n        matrix_t u = matrix_t::Identity(sumspace.cols(), sumspace.cols());\n        auto rk = hnf_LLL<khover::colops>(sumspace, std::tie(u), {});\n\n        // Error occured.\n        if(!rk) {\n            ERR_MSG(\"Failed to compute HNF.\");\n            return std::nullopt;\n        }\n\n        // Return the resulting abelian group together with the homomorphism from it.\n        if constexpr (DoesReturnMorphism::value) {\n            return std::make_pair(\n                AbelianGroup(\n                    u.topRightCorner(*rk, m_repMat.cols()),\n                    std::false_type{}),\n                sumspace.leftCols(*rk)\n                );\n        }\n        else {\n            return AbelianGroup(\n                u.topRightCorner(*rk, m_repMat.cols()),\n                std::false_type{});\n        }\n    }\n};\n\n} // end namespace khover\n", "meta": {"hexsha": "34b38a227751f7c7f8337e75cb0d8982b8101d09", "size": 10395, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/abelian.hpp", "max_stars_repo_name": "Junology/khover", "max_stars_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T06:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T06:50:39.000Z", "max_issues_repo_path": "src/abelian.hpp", "max_issues_repo_name": "Junology/khover", "max_issues_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/abelian.hpp", "max_forks_repo_name": "Junology/khover", "max_forks_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8825503356, "max_line_length": 162, "alphanum_fraction": 0.5578643579, "num_tokens": 2568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5866814822234543}}
{"text": "/*\nreplay\nSoftware Library\n\nCopyright (c) 2010-2019 Marius Elvert\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#ifndef replay_math_hpp\n#define replay_math_hpp\n\n#include <boost/math/special_functions/sign.hpp>\n#include <replay/interval.hpp>\n\nnamespace replay\n{\n\n/** generic linear interpolation.\n    \\ingroup Math\n*/\ntemplate <class type, class delta_type> inline constexpr type lerp(type a, type b, delta_type x)\n{\n    return a + x * (b - a);\n}\n\n/** Math related functions.\n*/\nnamespace math\n{\n\n/** default numerical error tolerance.\n    \\ingroup Math\n*/\nfloat const default_epsilon = 0.000001f;\n\n/** multiply a only by the sign of b.\n    \\ingroup Math\n*/\ninline void mult_ref_by_sign(float& a, float b)\n{\n    a = boost::math::copysign(a, a * b);\n}\n\n/** multiply a only by the sign of b.\n    \\ingroup Math\n*/\ninline void mult_by_sign(float a, float b, float& result)\n{\n    result = boost::math::copysign(a, a * b);\n}\n\n/** copies the sign.\n    \\ingroup Math\n*/\ninline float copy_sign(float value, float sign)\n{\n    return boost::math::copysign(value, sign);\n}\n\n/** return true if the value is within a threshold of zero.\n    \\ingroup Math\n*/\ninline bool fuzzy_zero(float value, float epsilon)\n{\n    return std::abs(value) < epsilon;\n}\n\n/** return true if the value is within a threshold of zero.\n    \\ingroup Math\n*/\ninline bool fuzzy_zero(float value)\n{\n    return std::abs(value) < default_epsilon;\n}\n\n/** Return true if a is within a treshold of b.\n    This is used to compare floating point numbers.\n    \\ingroup Math\n*/\ninline bool fuzzy_equals(float a, float b, float epsilon = default_epsilon)\n{\n    return std::abs(a - b) < epsilon;\n}\n\n/** check if the value is in the range. borders count as in.\n    \\ingroup Math\n*/\ntemplate <class T> inline bool in_range(T value, interval<T> const& range)\n{\n    return (range[0] <= value) && (value <= range[1]);\n}\n\n/** check if the value is in the range. borders count as in.\n    \\ingroup Math\n*/\ntemplate <class T> inline bool in_range(T value, const T left, const T right)\n{\n    return (left <= value) && (value <= right);\n}\n\n/** check whether two intervals intersect.\n    \\ingroup Math\n*/\ntemplate <class T> inline bool intervals_intersect(interval<T> const& a, interval<T> const& b)\n{\n    return a[1] > b[0] && a[0] < b[1];\n}\n\n/** clamp a value into the range [-abs,abs]\n    \\ingroup Math\n*/\ntemplate <class T> inline constexpr T clamp_absolute(const T value, const T abs)\n{\n    if (value < -abs)\n        return -abs;\n    else if (value > abs)\n        return abs;\n    else\n        return value;\n}\n\n/** Clamp a value into a range.\n    \\ingroup Math\n*/\ntemplate <class T> inline constexpr T clamp(T value, interval<T> const& range)\n{\n    if (value < range[0])\n        return range[0];\n    else if (value > range[1])\n        return range[1];\n    else\n        return value;\n}\n\n/** Saturate the value, i.e., clamp it into the [0..1] range.\n    \\param x Value to be saturated.\n    \\ingroup Math\n*/\ninline constexpr float saturate(float x)\n{\n    if (x < 0.f)\n        return 0.f;\n    else\n        return std::min(x, 1.f);\n}\n\n/** Perform a smooth hermite blend between two edge values.\n    Returns 0 for values smaller than edge0 and 1 for values greater than edge1.\n    Values in between are interpolated by the polynomial x*x*(3-2*x).\n    \\ingroup Math\n*/\ninline float smoothstep(float edge0, float edge1, float x)\n{\n    // Early out to avoid divisions by zero if edge0==edge1.\n    if (x <= edge0)\n        return 0.f;\n    else if (x >= edge1)\n        return 1.f;\n\n    // Do actual interpolation in-between edges.\n    x = (x - edge0) / (edge1 - edge0);\n    return x * x * (3.0f - 2.f * x);\n}\n\n/** find the sign.\n    \\ingroup Math\n*/\ninline unsigned int sign(float value) // returns 1 for - and 0 for +\n{\n    return value < 0.f ? 1 : 0;\n}\n\n/** compare signs.\n    \\ingroup Math\n*/\ninline unsigned int same_sign(float a, float b)\n{\n    return a * b < 0.f ? 0 : 1;\n}\n\n/** convert radians to degrees.\n    \\ingroup Math\n*/\ninline constexpr float convert_to_degrees(float radians)\n{\n    constexpr float factor = 180.f / 3.14159265358979323846f;\n    return radians * factor;\n}\n\n/** convert degrees to radians.\n    \\ingroup Math\n*/\ninline constexpr float convert_to_radians(float degrees)\n{\n    constexpr float factor = 3.14159265358979323846f / 180.f;\n    return degrees * factor;\n}\n\n/** returns true if the given integer is a power of two.\n    \\ingroup Math\n*/\ninline bool is_pow2(unsigned int Number)\n{\n    return (Number & (Number - 1)) == 0;\n}\n\n/** returns true if the given integer is a power of two.\n    \\ingroup Math\n*/\ninline bool is_pow2(int Number)\n{\n    return Number > 0 && is_pow2(static_cast<unsigned int>(Number));\n}\n\n/** compute the square.\n    \\ingroup Math\n*/\ntemplate <class T> inline constexpr T square(T p)\n{\n    return p * p;\n}\n\n/** Solve a quadratic equation of the form: a*x^2+b*x+c=0\n    \\ingroup Math\n*/\nunsigned int solve_quadratic_eq(float a, float b, float c, interval<>& result, float epsilon);\n\n/** interpolation functions.\n    \\ingroup Math\n*/\nnamespace interpolate\n{\n\n/** linear\n*/\ntemplate <class type, class delta_type> inline type linear(const type a, const type b, const delta_type x)\n{\n    return a + x * (b - a);\n}\n\n/** cubic\n*/\ntemplate <class type, class delta_type>\ninline type cubic(const type& a, const type& b, const type& c, const type& d, const delta_type x)\n{\n    // 6 mults, 8 adds\n\n    const type P = (d - c) - (a - b);\n    const type Q = (a - b) - P;\n\n    return ((P * x + Q) * x + (c - a)) * x + b;\n}\n\n/** bicubic\n*/\ntemplate <class type, class delta_type>\ninline type bicubic(const type& v11,\n                    const type& v21,\n                    const type& v31,\n                    const type& v41,\n                    const type& v12,\n                    const type& v22,\n                    const type& v32,\n                    const type& v42,\n                    const type& v13,\n                    const type& v23,\n                    const type& v33,\n                    const type& v43,\n                    const type& v14,\n                    const type& v24,\n                    const type& v34,\n                    const type& v44,\n                    const delta_type x,\n                    const delta_type y)\n{\n    return cubic(cubic(v14, v13, v12, v11, y), cubic(v24, v23, v22, v21, y), cubic(v34, v33, v32, v31, y),\n                 cubic(v44, v43, v42, v41, y), x);\n}\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "0665ff49ed76d7fab7146126c0e9592cead6bf1d", "size": 7389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/replay/math.hpp", "max_stars_repo_name": "ltjax/replay", "max_stars_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T19:52:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-15T19:52:50.000Z", "max_issues_repo_path": "include/replay/math.hpp", "max_issues_repo_name": "ltjax/replay", "max_issues_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-03T21:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-23T02:11:50.000Z", "max_forks_repo_path": "include/replay/math.hpp", "max_forks_repo_name": "ltjax/replay", "max_forks_repo_head_hexsha": "33680beae225c9c388f33e3f7ffd7e8bae4643e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4668874172, "max_line_length": 106, "alphanum_fraction": 0.6394640682, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5865644727695237}}
{"text": "\n#include <string>\n#include <fstream>\n#include <exception>\n#include <std_msgs/String.h>\n#include <geometry_msgs/Twist.h>\n#include <geometry_msgs/Pose.h>\n#include <ensenso/pathfinder.h>\n#include <std_msgs/Float64MultiArray.h>\n#include \"nn_controller/nn_controller.h\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n#include <boost/numeric/odeint/algebra/vector_space_algebra.hpp>\n\nusing namespace amfc_control;\nusing namespace boost::numeric::odeint;\n\n//constructor\nController::Controller(ros::NodeHandle nc, const Eigen::Vector3d& ref, bool print,\n\t\t\t\t\t\tbool useSigma, bool save)\n: n_(nc), ref_(ref), updatePoseInfo(false), updateController(false), useSigma(useSigma),\n  save(save), resetController(false), updateWeights(false), print(print), counter(0), \n  multicast_address(\"235.255.0.1\")\n{\t \t\t \n\tinitMatrices();\t\n\tsigma_y = 0.01;\n\tsigma_r = 0.01;\n\t// BladderTypeEnum bladder_type_;\n\tros::param::get(\"/nn_controller/Control/with_net\", with_net_);\n\tcontrol_pub_ = n_.advertise<ensenso::ValveControl>(\"/mannequine_head/u_valves\", 100);\n}\n\n//copy constructor\nController::Controller()\n{\n\n}\n\n// Destructor.\nController::~Controller()\n{\n}\n\n\nvoid Controller::vectorToHeadPose(Eigen::VectorXd&& pose_info, geometry_msgs::Pose& eig2Pose)\n{\n    eig2Pose.orientation.x = pose_info(0); // roll\n    eig2Pose.position.z = pose_info(1);\t// z\n    eig2Pose.orientation.y = pose_info(2);\t// pitch\n}\n\nros::Time Controller::getTime() {\n\treturn ros::Time::now();\n}\n\n/*Subscribers*/\n// pose subscriber from ensenso_seg/vicon_sub\nvoid Controller::pose_subscriber(const geometry_msgs::Pose& headPose) {\n\tgetPoseInfo(headPose, pose_info);\n\n\tstd::lock_guard<std::mutex> pose_locker(pose_mutex);\n\tthis->pose_info = pose_info;\n\tupdatePoseInfo  = true;\t\t\n}\n\nvoid Controller::net_control_subscriber(const ensenso::ValveControl& net_control_law){\n\tEigen::VectorXd net_control;\n\tnet_control.resize(6);\n\n\tnet_control << net_control_law.left_bladder_pos, net_control_law.left_bladder_neg,\n\t\t\t\t   net_control_law.base_bladder_pos, net_control_law.base_bladder_neg,\n\t\t\t\t   net_control_law.right_bladder_pos, net_control_law.right_bladder_neg;\n\tupdate_net_law = true;\n\tthis->net_control.resize(6);\n\tthis->net_control = net_control;\t\t\t\t   \n}\n\n\nvoid Controller::getPoseInfo(const geometry_msgs::Pose& headPose, Eigen::VectorXd pose_info)\n{\n\tpose_info << headPose.orientation.x, // roll = [left and right]\n\t\t\t\t headPose.position.z, \t// base  = [base actuator]\t\n\t\t\t\t headPose.orientation.y; // pitch = [right actuator]\n\t\n\tthis->pose_info = pose_info;\n\t//set ref's non-controlled states to measurement\n\tControllerParams(std::move(pose_info));\n}\n\nvoid Controller::ControllerParams(Eigen::VectorXd&& pose_info)\n{\t\n\t// Am = -0.782405        -0        -0\n\t//       -0          -0.782405     -0\n    //       -0              -0    -0.782405\n\t// Bm = [1 0 0; 0 1 0; 0 0 1]\n\t// ref_ = [z, roll, pitch ] given by user\n\tif(counter == 0){\n\t\tym = pose_info;\t\t// will be 3x1; pose_info is also 3x1\n\t\tym_dot = Am * ym + Bm * ref_;\t// will be 3x1\n\t\tprev_ym.push_back(ym);\n\n\t\ttracking_error = pose_info - ym; \t// will be 3x1\n\n\n\t\tros::param::get(\"/nn_controller/Utils/filename\", filename_);\n\t\tpathfinder::getROSPackagePath(\"nn_controller\", nn_controller_path_);\n\t\tss << nn_controller_path_.c_str() << filename_;\n\t\tref_pose_file_ = ss.str();\n\t}\n\telse{\n\t\t// find ym\n\t\tym_dot = Am * prev_ym.back() + Bm * ref_;  // will be 3x1\n\t\tym = prev_ym.back() + 0.01 * ym_dot;\t\t// will be 3x1\n\t\tprev_ym.push_back(ym);    // don't leve the linked list empty\n\n\t\ttracking_error = pose_info - ym;\t\t\t// will be 3x1\n\n\t\t// // find Ky_hat \n\t\t// Ky_hat_dot = -Gamma_y * pose_info * tracking_error.transpose() * P * B  * sgnLambda;\n\t\t// Ky_hat = prev_Ky_hat_.back() + 0.01 * Ky_hat_dot;\n\t\t// prev_Ky_hat_.push_back(Ky_hat);\n\n\t\t// // find Kr_hat\n\t\t// Kr_hat_dot = -Gamma_r * ref_      * tracking_error.transpose() * P * B  * sgnLambda;\n\t\t// Kr_hat = prev_Kr_hat_.back() + 0.01 * Kr_hat_dot;\n\t\t// prev_Kr_hat_.push_back(Kr_hat);\n\t}\n\t// tracking_error = pose_info - ym;\n\n\t//use boost ode solver to compute Ky_hat and Kr_hat:: lot more stable than trapezoidal rule\n\trunge_kutta_dopri5<state,double,state,double,vector_space_algebra> stepper;\n\tKy_hat_dot = -Gamma_y * pose_info * tracking_error.transpose() * P * B  * sgnLambda;\n\tKr_hat_dot = -Gamma_r * ref_      * tracking_error.transpose() * P * B  * sgnLambda;\n\n\t//use reference for the derivative\n\tstepper.do_step([](const state& x, state & dxdt, const double t)->void{\n\t\tdxdt = x;\n\t}, Ky_hat_dot, counter, Ky_hat, 0.01);\n\t//integrate Ky_hat_dot\n\tstepper.do_step([](const state& x, state & dxdt, const double t)->void{\n\t\tdxdt = x;\n\t}, Kr_hat_dot, counter, Kr_hat, 0.01);\n\n\tEigen::VectorXd net_control;\n\tnet_control.resize(m);\n\tif(update_net_law)\t{\n\t\tstd::lock_guard<std::mutex> net_pred_locker(pred_mutex);\n\t\tupdate_net_law = false;\n\t\tnet_control = this->net_control;\n\t}\n\t/*\n\t* Calculate Control Law\n\t*/\n\tif(with_net_){\n\t\tu_control = (Ky_hat.transpose() * pose_info) + \n\t\t\t\t\t(Kr_hat.transpose() * ref_) + this->net_control; \n\t}\n\telse{\n\t\tu_control = (Ky_hat.transpose() * pose_info) + \n\t\t\t\t\t(Kr_hat.transpose() * ref_); \t\n\t}\n\t// u_control = this->net_control;\n\t/*\n\tHere are the rules that govern the bladders\n\tl_i --> Roll+\tr_i -->Roll-\n\tl_o --> Roll-   r_o -->Roll+\n\tb_i --> Pitch+, Z+   b_o -->Pitch-, Z-\n\tu_{o+} is a suitable controller magnitude; u_+ is a +ve input\n\t------------------------------------------------------------\n\tDOF     |  Control Law\n\t------------------------------------------------------------\n\tRoll+   |  if f_{li} = u_{+}:\n\t\t\t|\tf_{ri} = 0,\n\t\t\t|   f_{lo} = |u_{lo}|\n\t\t\t| \tf_{ro} = |u_{ro}|\n\t------------------------------------------------------------\n\tRoll-   | if f_{ri} = u_{+}:\n\t\t\t|  \tf_{li} = 0; \n\t\t\t|   f_{ro} = 0  or u_{o+}\n\t------------------------------------------------------------\n\tPitch+  | if f_{bi} = u_{+}\n\t\t\t|    f_{bo} = u_{o+} and f_{li} =f_{ri} = u_{head+}\n\t------------------------------------------------------------\n\tPitch-  | f_{bo} = u_{max-}\n\t\t\t| f_{bi} = 0 or < f_{bo}\n\t------------------------------------------------------------\n\tZ+      | f_{li} = f_{ri} = u_{head+}\n\t\t\t| f_{bi} = u_{+} f_{bo} = u_{o+}\n\t------------------------------------------------------------\n\tZ-      | f_{bo} = u_{-}\n\t\t\t| f_{bi} = 0 or f_{bo}\n\t*/\n\t// // saturate control signals\n\t// for(auto i = 0; i < 6; ++i){\n\t// \tif(u_control[i] < 0)\n\t// \t\tu_control[i] = 0;\n\t// \telse if (u_control[i] > 1)\n\t// \t\tu_control[i] = 1;\n\t// \telse\n\t// \t\tu_control[i] = u_control[i];\n\t// }\n\tu_valves_.left_bladder_pos  = u_control(0);\n\tu_valves_.left_bladder_neg  = u_control(1);\n\tu_valves_.base_bladder_pos  = u_control(2);\n\tu_valves_.base_bladder_neg  = u_control(3);\t\n\tu_valves_.right_bladder_pos = u_control(4);\n\tu_valves_.right_bladder_neg = u_control(5);\t\n\n\tif(save) {\n\t\tstd::ofstream file_handle;\n\t\tfile_handle.open(ref_pose_file_, std::ofstream::out | std::ofstream::app);\n\t\tfile_handle  << ref_(0) <<\"\\t\" <<ref_(1) << \"\\t\" << ref_(2) << \"\\t\" << pose_info(0) <<\"\\t\" <<pose_info(1) << \"\\t\" << pose_info(2) << \"\\n\"; \n\t\tfile_handle.close();\n\t}\n\tros::Rate sleeper(2);\n\tsleeper.sleep();\n\tcontrol_pub_.publish(u_valves_);\n\tvectorToHeadPose(std::move(pose_info), pose_);\t// convert from eigen to headpose\n\tudp::sender s(io_service, boost::asio::ip::address::from_string(multicast_address), u_valves_, ref_, pose_);\n\t// pose is  [roll, z, pitch]\n\t// udp::sender s(io_service, boost::asio::ip::address::from_string(multicast_address), pose_); // used for identification\n\n\tif(print)\t{\t\n\t\tOUT(\"\\nref_: \" \t\t\t<< ref_.transpose());\n\t\tOUT(\"y  (roll, z,  pitch): \" \t\t << pose_info.transpose());\n\t\tOUT(\"ym (roll, z,  pitch): \" \t\t << ym.transpose());\n\t\tOUT(\"e  (y-ym): \" << tracking_error.transpose());\n\t\tOUT(\"pred (z, z, pitch, pitch, roll, roll): \" << pred.transpose());\n\t\tOUT(\"net_control: \" << net_control.transpose());\n\t\tOUT(\"Control Law: \" << u_control.transpose());\n\t\tOUT(\"Kr_hat: \\n\" << Kr_hat);\n\t\tOUT(\"Ky_hat: \\n\" << Ky_hat);\n\t}\n\t++counter;\n}\n\nint main(int argc, char** argv)\n{ \n\tros::init(argc, argv, \"controller_node\", ros::init_options::AnonymousName);\n\tros::NodeHandle n;\n\tbool print, useSigma, save, useVicon(true);\n\n\tEigen::Vector3d ref;\n\tref.resize(3);\n\n\ttry{\t\t\n\t\t//supply values from the cmd line or retrieve them \n\t\t//from the ros parameter server\n\t\tn.getParam(\"/nn_controller/Reference/z\", ref(1));    \t//ref z\n\t\tn.getParam(\"/nn_controller/Reference/pitch\", ref(2));\t//ref pitch\n\t\tn.getParam(\"/nn_controller/Reference/roll\", ref(0));\t    //ref roll\n\t\tn.getParam(\"/nn_controller/Utils/print\", print);\n\t\tn.getParam(\"/nn_controller/Utils/useSigma\", useSigma);\n\t\tsave = n.getParam(\"/nn_controller/Utils/save\", save);\n\t}\n\tcatch(std::exception& e){\n\t\te.what();\n\t}\n\n\tController c(n, ref, print, useSigma, save);\n\n\tros::Subscriber sub_pose = n.subscribe(\"/mannequine_head/pose\", 100, &Controller::pose_subscriber, &c);\t\n\tros::Subscriber sub_pred = n.subscribe(\"/mannequine_pred/preds\", 100, &Controller::net_control_subscriber, &c);\n\tros::spin();\n\n\tif(!ros::ok())\n\t\tros::shutdown();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "708b777237665e023b8f40fdea459dc2efb14da1", "size": 9046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nn_controller/src/nn_controller.cpp", "max_stars_repo_name": "lakehanne/RAL2017", "max_stars_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T15:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T14:02:56.000Z", "max_issues_repo_path": "nn_controller/src/nn_controller.cpp", "max_issues_repo_name": "lakehanne/soft-neuro-adapt", "max_issues_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nn_controller/src/nn_controller.cpp", "max_forks_repo_name": "lakehanne/soft-neuro-adapt", "max_forks_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_forks_repo_licenses": ["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.2573529412, "max_line_length": 141, "alphanum_fraction": 0.6336502321, "num_tokens": 2782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5865067926919898}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__CARE_HPP_\n#define CBR_CONTROL__CARE_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include <type_traits>\n#include <numeric>\n\nnamespace cbr\n{\n\n/* -------------------------------------------------------------------------- */\n/*                               Matrix Balance                               */\n/* -------------------------------------------------------------------------- */\n\n// Numerical Recipes p.593 - Balancing Trasformation\n// D^-1 * A * D = B\n\ntemplate<std::size_t nx, class T = double>\nvoid matrix_balance(\n  const Eigen::Ref<const Eigen::Matrix<T, 2 * nx, 2 * nx>> A,\n  Eigen::Ref<Eigen::Matrix<T, 2 * nx, 2 * nx>> D,\n  Eigen::Ref<Eigen::Matrix<T, 2 * nx, 2 * nx>> B\n)\n{\n  std::size_t n = 2 * nx;\n\n  // Initialize D and B\n  D.setIdentity();\n  B = A;\n\n  double RADIX = 2.0;\n  double sqrdx = RADIX * RADIX;\n\n  std::size_t done = 0;\n\n  while (done != 1) {\n    done = 1;\n\n    for (std::size_t i = 0; i < n; i++) {\n      double r = 0.;\n      double c = 0.;\n\n      for (std::size_t j = 0; j < n; j++) {\n        if (j != i) {\n          c = c + std::abs(B(j, i));\n          r = r + std::abs(B(i, j));\n        }\n      }\n\n      if ((c != 0) && (r != 0)) {\n        double g = r / RADIX;\n        double f = 1.0;\n        double s = c + r;\n\n        while (c < g) {\n          f = f * RADIX;\n          c = c * sqrdx;\n        }\n\n        g = r * RADIX;\n\n        while (c > g) {\n          f = f / RADIX;\n          c = c / sqrdx;\n        }\n\n        if (((c + r) / f) < 0.95 * s) {\n          done = 0;\n          g = 1 / f;\n          D(i, i) = D(i, i) * f;\n\n          for (std::size_t j = 0; j < n; j++) {\n            B(i, j) = B(i, j) / f;\n          }\n\n          for (std::size_t j = 0; j < n; j++) {\n            B(j, i) = B(j, i) * f;\n          }\n        }\n      }\n    }\n  }\n}\n\n\n// Finds the solution to the ARE by finding the Eigen-decomposition of the Hamiltonean.\ntemplate<std::size_t nx, std::size_t nu, class T = double>\nbool care(\n  const Eigen::Ref<const Eigen::Matrix<T, nx, nx>> A,\n  const Eigen::Ref<const Eigen::Matrix<T, nx, nu>> B,\n  const Eigen::Ref<const Eigen::Matrix<T, nx, nx>> Q,\n  const Eigen::Ref<const Eigen::Matrix<T, nu, nu>> R,\n  Eigen::Ref<Eigen::Matrix<T, nx, nx>> P,\n  Eigen::Ref<Eigen::Matrix<T, nu, nx>> K\n)\n{\n// Ensure R positive definite (R>0)\n  const Eigen::LLT<Eigen::Matrix<T, nu, nu>> Rdecomposed(R.transpose());\n  if (Rdecomposed.info() == Eigen::NumericalIssue) {\n    return false;\n  }\n\n  using H_t = Eigen::Matrix<T, 2 * nx, 2 * nx>;\n  using Hc_t = Eigen::Matrix<std::complex<T>, 2 * nx, 2 * nx>;\n  using Ac_t = Eigen::Matrix<std::complex<T>, nx, nx>;\n\n//  1. Define Hamiltonean:\n//\n//                      [  A | -(B/R)*B' ]\n//                H =   [ ---|-----------]\n//                      [ -Q |    -A'    ]\n\n  H_t H;\n  H.template topLeftCorner<nx, nx>() = A;\n  H.template topRightCorner<nx,\n    nx>() = -Rdecomposed.solve(B.transpose()).transpose() * B.transpose();\n  H.template bottomLeftCorner<nx, nx>() = -Q;\n  H.template bottomRightCorner<nx, nx>() = -A.transpose();\n\n  //  2. Balance the Hamiltonean\n  H_t D;\n  H_t Hb;\n  matrix_balance<nx, T>(H, D, Hb);\n\n  //  3. Solve the ARE through eigen decomposition of Hb\n  // Start by obtaining eigenvalues and eigenvectors\n  const Eigen::EigenSolver<H_t> es(Hb);\n  auto V = es.eigenvectors();\n  const auto & l = es.eigenvalues();\n  V = D * V;\n\n  // Idendify which eigenvalues are positive and which are negative\n  std::array<int, 2 * nx> ord_L;\n  std::fill(ord_L.begin(), ord_L.end(), 0);\n\n  for (std::size_t k = 0; k < (2 * nx); k++) {\n    if (std::real(l[k]) < 0) {\n      ord_L[k] = -1;\n    } else if (std::real(l[k]) > 0) {\n      ord_L[k] = 1;\n    }\n  }\n\n  // Sorting indices - place positive on left side, negative on right\n  std::array<std::size_t, 2 * nx> ord_index;\n  std::iota(ord_index.begin(), ord_index.end(), 0LU);\n  std::sort(\n    ord_index.begin(), ord_index.end(),\n    [&](const std::size_t i1, const std::size_t i2) {\n      const auto & l1 = ord_L[i1];\n      const auto & l2 = ord_L[i2];\n      return l1 > l2;\n    });\n\n  // Sort Eigenvector based on ord_index array\n  Hc_t V_ord;\n  for (std::size_t i = 0; i < 2 * nx; i++) {\n    V_ord.col(i) = V.col(ord_index[i]);\n  }\n\n  // Define upper and lower right side block matrices\n  const Ac_t V12 = V_ord.template topRightCorner<nx, nx>();\n  const Ac_t V22 = V_ord.template bottomRightCorner<nx, nx>();\n\n  const Eigen::FullPivLU<Ac_t> V12decomposed(V12.transpose());\n  const Ac_t P_complex = V12decomposed.solve(V22.transpose()).transpose();  // P_complex = T22/T12\n\n  // 4. Write Results\n  P = P_complex.unaryExpr([](const std::complex<T> & v) {return std::real(v);});\n\n  K = R.inverse() * B.transpose() * P;\n\n  return true;\n}\n\n}    // namespace cbr\n\n\n#endif  // CBR_CONTROL__CARE_HPP_\n", "meta": {"hexsha": "8b9d2370722142e466c16614589eae6836c31ffa", "size": 4898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/care.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/care.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/care.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": 26.192513369, "max_line_length": 98, "alphanum_fraction": 0.5242956309, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5865067856997357}}
{"text": "#ifndef _POSE_ESTIMATION_UKF_HPP\n#define _POSE_ESTIMATION_UKF_HPP\n\n#include <iostream>\n#include <stdexcept>\n#include <ukfom/ukf.hpp>\n#include <ukfom/mtkwrap.hpp>\n#include <boost/shared_ptr.hpp>\n#include <base/Time.hpp>\n#include <boost/noncopyable.hpp>\n\nnamespace pose_estimation\n{\n\ntemplate<typename Manifold>\nclass UnscentedKalmanFilter : private boost::noncopyable\n{\npublic:\n    enum {\n        DOF = Manifold::DOF\n    };\n    typedef Manifold State;\n    typedef ukfom::mtkwrap<Manifold> WState;\n    typedef ukfom::ukf<WState> MTK_UKF;\n    typedef typename MTK_UKF::cov Covariance;\n\n    UnscentedKalmanFilter()\n    {\n        process_noise_cov = Covariance::Zero();\n        last_measurement_time.microseconds = 0;\n        min_time_delta = 1.0e-9;\n        max_time_delta = std::numeric_limits<double>::max();\n    }\n\n    virtual ~UnscentedKalmanFilter() {}\n\n    /**\n     * (Re-)initializes the UKF filter from a given state.\n     */\n    void initializeFilter(const State& initial_state, const Covariance& state_cov)\n    {\n        ukf.reset(new MTK_UKF(initial_state, state_cov));\n        last_measurement_time.microseconds = 0;\n    }\n\n    /**\n     * Provides the current state and covariance of the filter.\n     *\n     * @returns false if the filter has not been initialized.\n     */\n    bool getCurrentState(State& state, Covariance& state_cov) const\n    {\n        if(ukf.get() != NULL)\n        {\n            state = ukf->mu();\n            state_cov = ukf->sigma();\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Provides the current state of the filter.\n     *\n     * @returns false if the filter has not been initialized.\n     */\n    bool getCurrentState(State& state) const\n    {\n        if(ukf.get() != NULL)\n        {\n            state = ukf->mu();\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Computes the time delta from a given sample timestamp and\n     * calls predictionStep(delta_t)\n     *\n     * @throws runtime_error if delta_t is negative or greater then the allowed maximum.\n     */\n    void predictionStepFromSampleTime(const base::Time& sample_time)\n    {\n        // first call\n        if(last_measurement_time.isNull())\n        {\n            last_measurement_time = sample_time;\n            return;\n        }\n\n        // compute delta t\n        double delta_t = (sample_time - last_measurement_time).toSeconds();\n\n        // set new last measurement time\n        if(delta_t > min_time_delta)\n            last_measurement_time = sample_time;\n\n        predictionStep(delta_t);\n    }\n\n    /**\n     * Calls the predictionStepImpl after checking the delta_t value.\n     *\n     * @throws runtime_error if delta_t is negative or greater then the allowed maximum.\n     */\n    void predictionStep(double delta_t)\n    {\n        // check delta time\n        if(delta_t < 0.0)\n        {\n            throw std::runtime_error(\"Delta time is negative!\");\n        }\n        else if(delta_t <= min_time_delta)\n        {\n            // delta time is zero or close to zero\n            return;\n        }\n        else if(delta_t > max_time_delta)\n        {\n            throw std::runtime_error(\"Delta time is greater then the allowed maximum!\");\n        }\n\n        predictionStepImpl(delta_t);\n    }\n\n    unsigned getStateSize() const {return unsigned(WState::DOF);}\n    bool isInitialized() const {return ukf.get() != NULL;}\n    const Covariance& getProcessNoiseCovariance() const {return process_noise_cov;}\n    void setProcessNoiseCovariance(const Covariance& noise_cov) {process_noise_cov = noise_cov;}\n    const base::Time& getLastMeasurementTime() const {return last_measurement_time;}\n    void setLastMeasurementTime(const base::Time& last_measurement_time)\n                               {this->last_measurement_time = last_measurement_time;}\n    double getMaxTimeDelta() const {return max_time_delta;}\n    void setMaxTimeDelta(double max_time_delta) {this->max_time_delta = max_time_delta;}\n    double getMinTimeDelta() const {return min_time_delta;}\n    void setMinTimeDelta(double min_time_delta) {this->min_time_delta = min_time_delta;}\n\nprotected:\n    virtual void predictionStepImpl(double delta_t) = 0;\n\n    template<int DIM, typename scalar_type>\n    void checkMeasurment(const Eigen::Matrix<scalar_type, DIM, 1>& mu, const Eigen::Matrix<scalar_type, DIM, DIM>& cov) const\n    {\n        if(!mu.allFinite() || !cov.allFinite())\n            throw std::runtime_error(\"Measurement or covariance contains non-finite values!\");\n    }\n\nprotected:\n    boost::shared_ptr<MTK_UKF> ukf;\n    Covariance process_noise_cov;\n    base::Time last_measurement_time;\n    double max_time_delta;\n    double min_time_delta;\n};\n\n}\n\n#endif", "meta": {"hexsha": "6047128adeb451067b8d0b7b9c629d5baa09c1cd", "size": 4691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/UnscentedKalmanFilter.hpp", "max_stars_repo_name": "rock-slam/slam-pose_estimation", "max_stars_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-13T07:26:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T02:51:09.000Z", "max_issues_repo_path": "src/UnscentedKalmanFilter.hpp", "max_issues_repo_name": "rock-slam/slam-pose_estimation", "max_issues_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-26T16:46:41.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-27T16:10:23.000Z", "max_forks_repo_path": "src/UnscentedKalmanFilter.hpp", "max_forks_repo_name": "rock-slam/slam-pose_estimation", "max_forks_repo_head_hexsha": "66c516b2bed5f9a826811e34cf24b08b0483e508", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-20T12:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-05T14:47:10.000Z", "avg_line_length": 29.5031446541, "max_line_length": 125, "alphanum_fraction": 0.6452781923, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5865067767746399}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using namespace std;\n    typedef  mtl::dense2D<double>            Matrix;\n\n    double array[][4]= {{2, 3,   4,   5}, \n                        {4, 10, 13,  16},\n                        {6, 25, 38,  46},\n\t\t        {8, 32, 77, 100}};\n    Matrix \t\tA(array), I(4, 4);\n    I= 1.0;\n\n    Matrix LU(A);\n    dense_vector<std::size_t> v(4);\n    lu(LU, v);\n    mat::traits::permutation<>::type P(permutation(v));\n    \n    cout << \"A is:\\n\" << A << \"\\nPermuted A is \\n\" << Matrix(P * A);\n\n    Matrix L(I + strict_lower(LU)), U(upper(LU)), A2(L * U);\n    cout << \"L [permuted] is:\\n\" << L << \"U [permuted] is:\\n\" << U \n\t << \"L * U [permuted] is:\\n\" << A2\n\t << \"L * U is:\\n\" << Matrix(trans(P) * A2);\n \n    Matrix UI(inv_upper(U));\n    cout << \"inv(U) [permuted] is:\\n\" << UI << \"UI * U is:\\n\" << UI * U;\n \n    Matrix LI(inv_lower(L));\n    cout << \"inv(L) [permuted] is:\\n\" << LI << \"LI * L is:\\n\" << LI * L;\n \n    Matrix AI(UI * LI * P);\n    cout << \"inv(A) [inv(U) * inv(L) * P] is \\n\" << AI << \"Test: A * AI is\\n\" << AI * A;\n \n    mat::traits::inv<Matrix>::type A_inv(inv(A));\n    cout << \"inv(A) is \\n\" << A_inv << \"Test: A * AI is\\n\" << A_inv * A;\n\n    return 0;\n}\n", "meta": {"hexsha": "3ce01d0291cfbcbaccb5b38a67b41c23575cc88e", "size": 1262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/inv_matrix.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/inv_matrix.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/inv_matrix.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.0476190476, "max_line_length": 88, "alphanum_fraction": 0.4690966719, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5863971969795492}}
{"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_ACOTH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACOTH_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 cotangent argument \\f$\\frac12\\log\\frac{x+1}{x-1}\\f$\n\n\n    @see cosh, sinh, acosh, asinh, atanh, asech, acosh, acsch\n\n\n    @par Header <boost/simd/function/acoth.hpp>\n\n    @par Example:\n\n      @snippet acoth.cpp acoth\n\n    @par Possible output:\n\n      @snippet acoth.txt acoth\n\n  **/\n  IEEEValue acoth(IEEEValue const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acoth.hpp>\n#include <boost/simd/function/simd/acoth.hpp>\n\n#endif\n", "meta": {"hexsha": "2b278fa5041b0be175ec742f093800d72e3cf1ad", "size": 1073, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acoth.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/acoth.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/acoth.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.3260869565, "max_line_length": 100, "alphanum_fraction": 0.5824790308, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5863971857662046}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkLaplacianInfilling.cxx\n  Author: Pierre Guilbert\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n\n// LOCAL\n#include \"vtkLaplacianInfilling.h\"\n\n// STD\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n\n// VTK\n#include <vtkObjectFactory.h>\n#include <vtkImageData.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n#include <vtkXMLImageDataWriter.h>\n\n// BOOST\n#include <boost/algorithm/string.hpp>\n\n// Eigen\n#include <Eigen/Sparse>\n\n// Implementation of the New function\nvtkStandardNewMacro(vtkLaplacianInfilling)\n\n//-----------------------------------------------------------------------------\nint vtkLaplacianInfilling::RequestData(vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector, vtkInformationVector *outputVector)\n{\n  // Get the input\n  vtkImageData * inputImage = vtkImageData::GetData(inputVector[0]->GetInformationObject(0));\n\n  // Get the output\n  vtkImageData* outputImage = vtkImageData::GetData(outputVector->GetInformationObject(0));\n  outputImage->ShallowCopy(inputImage);\n\n  int xBound = outputImage->GetDimensions()[0];\n  int yBound = outputImage->GetDimensions()[1];\n  int nParams = xBound * yBound;\n\n  Eigen::SparseMatrix<double> Laplacian(nParams, nParams);\n  Eigen::VectorXd Y(nParams); // The values of the laplacian required\n\n  // Triplet of value: row, column and value\n  std::vector<Eigen::Triplet<double> > nonZeroCoefficient;\n  for (int x = 0; x < xBound; ++x)\n  {\n    for (int y = 0; y < yBound; ++y)\n    {\n      int flattenIndex = x + xBound * y;\n\n      // check if the current pixel has a value\n      double value = inputImage->GetScalarComponentAsDouble(x, y, 0, 0);\n      if ((std::abs(value) > std::numeric_limits<double>::epsilon()))\n      {\n        // we don't want this value to be modified\n        // contraint: xi = yi\n        nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex, 1.0));\n        Y(flattenIndex) = value;\n      }\n      else\n      {\n        // else fill it solving the laplace equation\n        // using finite difference scheme and Dirichlet\n        // boundary\n        int validNeigh = 0;\n\n        // Laplacian constraints matrix:\n        // Neighbors contraint\n        if (x != 0)\n        {\n          nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex - 1, 1));\n          validNeigh++;\n        }\n        if (x != xBound - 1)\n        {\n          nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex + 1, 1));\n          validNeigh++;\n        }\n        if (y != 0)\n        {\n          nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex - xBound, 1));\n          validNeigh++;\n        }\n        if (y != yBound - 1)\n        {\n          nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex + xBound, 1));\n          validNeigh++;\n        }\n        // Diagonal constraint\n        nonZeroCoefficient.push_back(Eigen::Triplet<double>(flattenIndex, flattenIndex, -1.0 * static_cast<double>(validNeigh)));\n        // We want the laplacian to be null\n        Y(flattenIndex) = 0;\n      }\n    }\n  }\n\n  // Fill Laplacian constraints matrix\n  Laplacian.setFromTriplets(nonZeroCoefficient.begin(), nonZeroCoefficient.end());\n\n  // Solving:\n  Eigen::SparseLU< Eigen::SparseMatrix<double> > solver(Laplacian);\n  Eigen::MatrixXd X = solver.solve(Y);\n\n  // X contains the Dirichlet solution function\n  // values i.e: 0-values pixel are filled with\n  // laplacian\n  for (int x = 0; x < xBound; ++x)\n  {\n    for (int y = 0; y < yBound; ++y)\n    {\n      int flattendIndex = x + xBound * y;\n      outputImage->SetScalarComponentFromDouble(x, y, 0, 0, X(flattendIndex));\n    }\n  }\n\n  return 1;\n}\n", "meta": {"hexsha": "f6a08957dfaf9b5c91c0e225d3ca42ad9f371e6b", "size": 4280, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Filter/LaplacianInfilling/vtkLaplacianInfilling.cxx", "max_stars_repo_name": "zhihua-wang/VeloView", "max_stars_repo_head_hexsha": "609d3e4c0cf722c512f4b0b2a615208557bb7757", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T07:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T07:03:50.000Z", "max_issues_repo_path": "VelodyneHDL/Filter/LaplacianInfilling/vtkLaplacianInfilling.cxx", "max_issues_repo_name": "zactodd/VeloView", "max_issues_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T13:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:26:11.000Z", "max_forks_repo_path": "VelodyneHDL/Filter/LaplacianInfilling/vtkLaplacianInfilling.cxx", "max_forks_repo_name": "zactodd/VeloView", "max_forks_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T11:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T11:28:59.000Z", "avg_line_length": 31.4705882353, "max_line_length": 129, "alphanum_fraction": 0.6299065421, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5861852989100014}}
{"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/Gaussian.h>\n#include <BayesFilters/GaussianFilter.h>\n#include <BayesFilters/sigma_point.h>\n#include <BayesFilters/SimulatedLinearSensor.h>\n#include <BayesFilters/SimulatedStateModel.h>\n#include <BayesFilters/UKFCorrection.h>\n#include <BayesFilters/UKFPrediction.h>\n#include <BayesFilters/utils.h>\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n\n#include <string>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nclass UKFSimulation : public GaussianFilter\n{\npublic:\n    UKFSimulation\n    (\n        Gaussian& initial_state,\n        std::unique_ptr<GaussianPrediction> prediction,\n        std::unique_ptr<GaussianCorrection> correction,\n        std::size_t simulation_steps\n    ) noexcept :\n        GaussianFilter(std::move(prediction), std::move(correction)),\n        predicted_state_(initial_state.dim_linear, initial_state.dim_circular),\n        corrected_state_(initial_state),\n        simulation_steps_(simulation_steps)\n    { }\n\nprotected:\n    bool run_condition() override\n    {\n        if (step_number() < simulation_steps_)\n            return true;\n        else\n            return false;\n    }\n\n\n    bool initialization_step() override\n    {\n        return true;\n    }\n\n\n    void filtering_step() override\n    {\n        prediction().predict(corrected_state_, predicted_state_);\n        correction().freeze_measurements();\n        correction().correct(predicted_state_, corrected_state_);\n\n        log();\n    }\n\n\n    std::vector<std::string> log_file_names(const std::string& folder_path, const std::string& file_name_prefix) override\n    {\n        return {folder_path + \"/\" + file_name_prefix + \"_pred_mean\",\n                folder_path + \"/\" + file_name_prefix + \"_cor_mean\"};\n    }\n\n\n    void log() override\n    {\n        logger(predicted_state_.mean().transpose(), corrected_state_.mean().transpose());\n    }\n\nprivate:\n    Gaussian predicted_state_;\n\n    Gaussian corrected_state_;\n\n    std::size_t simulation_steps_;\n};\n\n\nint main(int argc, char* argv[])\n{\n    std::cout << \"Running a UKF filter on a simulated target.\" << std::endl;\n\n    const bool write_to_file = (argc > 1 ? std::string(argv[1]) == \"ON\" : false);\n    if (write_to_file)\n        std::cout << \"Data is logged in the test folder with prefix testUKF.\" << std::endl;\n\n\n    /* A set of parameters needed to run an unscented Kalman filter in a simulated environment. */\n    Vector4d initial_simulated_state(10.0f, 0.0f, 10.0f, 0.0f);\n    std::size_t simulation_time = 100;\n    /* Initialize unscented transform parameters. */\n    double alpha = 1.0;\n    double beta = 2.0;\n    double kappa = 0.0;\n\n\n    /* Step 1 - Initialization */\n\n    std::size_t state_size = 4;\n    Gaussian initial_state(state_size);\n    Vector4d initial_mean(4.0f, 0.04f, 15.0f, 0.4f);\n    Matrix4d initial_covariance;\n    initial_covariance << pow(0.05, 2), 0,            0,            0,\n                          0,            pow(0.05, 2), 0,            0,\n                          0,            0,            pow(0.01, 2), 0,\n                          0,            0,            0,            pow(0.01, 2);\n    initial_state.mean() = initial_mean;\n    initial_state.covariance() = initial_covariance;\n\n\n    /* Step 2 - Prediction */\n\n    /* Step 2.1 - Define the state model. */\n\n    /* Initialize a white noise acceleration state model. */\n    double T = 1.0f;\n    double tilde_q = 10.0f;\n\n    std::unique_ptr<AdditiveStateModel> wna = utils::make_unique<WhiteNoiseAcceleration>(WhiteNoiseAcceleration::Dim::TwoD, T, tilde_q);\n\n    /* Step 2.2 - Define the prediction step. */\n\n    /* Initialize the unscented Kalman filter prediction step and pass the ownership of the state model */\n    std::unique_ptr<UKFPrediction> ukf_prediction = utils::make_unique<UKFPrediction>(std::move(wna), state_size, alpha, beta, kappa);\n\n\n    /* Step 3 - Correction */\n\n    /* Step 3.1 - Define where the measurement are originated from (simulated in this case). */\n\n    /* Initialize simulated target model with a white noise acceleration. */\n    std::unique_ptr<AdditiveStateModel> target_model = utils::make_unique<WhiteNoiseAcceleration>(WhiteNoiseAcceleration::Dim::TwoD, T, tilde_q);\n    std::unique_ptr<SimulatedStateModel> simulated_state_model = utils::make_unique<SimulatedStateModel>(std::move(target_model), initial_simulated_state, simulation_time);\n\n    if (write_to_file)\n        simulated_state_model->enable_log(\"./\", \"testUKF\");\n\n    /* Step 3.2 - Initialize a measurement model (a linear sensor reading x and y coordinates). */\n    double sigma_x = 10.0;\n    double sigma_y = 10.0;\n    Eigen::MatrixXd R(2, 2);\n    R << std::pow(sigma_x, 2.0),                    0.0,\n                            0.0, std::pow(sigma_y, 2.0);\n\n    std::unique_ptr<AdditiveMeasurementModel> simulated_linear_sensor = utils::make_unique<SimulatedLinearSensor>(std::move(simulated_state_model), SimulatedLinearSensor::LinearMatrixComponent{ 4, std::vector<std::size_t>{ 0, 2 } }, R);\n\n    if (write_to_file)\n        simulated_linear_sensor->enable_log(\"./\", \"testUKF\");\n\n    /* Step 3.3 - Initialize the unscented Kalman filter correction step and pass the ownership of the measurement model. */\n    std::unique_ptr<UKFCorrection> ukf_correction = utils::make_unique<UKFCorrection>(std::move(simulated_linear_sensor), state_size, alpha, beta, kappa);\n\n\n    /* Step 4 - Assemble the unscented Kalman filter. */\n    std::cout << \"Constructing unscented Kalman filter...\" << std::flush;\n\n    UKFSimulation ukf(initial_state, std::move(ukf_prediction), std::move(ukf_correction), simulation_time);\n\n    if (write_to_file)\n        ukf.enable_log(\"./\", \"testUKF\");\n\n    std::cout << \"done!\" << std::endl;\n\n\n    /* Step 5 - Boot the filter. */\n    std::cout << \"Booting unscented Kalman filter...\" << std::flush;\n\n    ukf.boot();\n\n    std::cout << \"completed!\" << std::endl;\n\n\n    /* Step 6 - Run the filter and wait until it is closed. */\n    /* Note that since this is a simulation, the filter will end upon simulation termination. */\n    std::cout << \"Running unscented Kalman filter...\" << std::flush;\n\n    ukf.run();\n\n    std::cout << \"waiting...\" << std::flush;\n\n    if (!ukf.wait())\n        return EXIT_FAILURE;\n\n    std::cout << \"completed!\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0f79e933fc66951be35a9bebea1c781a80af0ab2", "size": 6488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_UKF/main.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": "test/test_UKF/main.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": "test/test_UKF/main.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": 32.7676767677, "max_line_length": 236, "alphanum_fraction": 0.656134402, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5860916791598804}}
{"text": "/*\n libs/numeric/odeint/examples/stochastic_euler.hpp\n\n Copyright 2012 Karsten Ahnert\n Copyright 2012 Mario Mulansky\n\n Stochastic euler stepper example and Ornstein-Uhlenbeck process\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 <vector>\n#include <iostream>\n#include <boost/random.hpp>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n\n/*\n//[ stochastic_euler_class_definition\ntemplate< size_t N > class stochastic_euler\n{\npublic:\n\n    typedef boost::array< double , N > state_type;\n    typedef boost::array< double , N > deriv_type;\n    typedef double value_type;\n    typedef double time_type;\n    typedef unsigned short order_type;\n    typedef boost::numeric::odeint::stepper_tag stepper_category;\n\n    static order_type order( void ) { return 1; }\n\n    // ...\n};\n//]\n*/\n\n\n/*\n//[ stochastic_euler_do_step\ntemplate< size_t N > class stochastic_euler\n{\npublic:\n\n    // ...\n\n    template< class System >\n    void do_step( System system , state_type &x , time_type t , time_type dt ) const\n    {\n        deriv_type det , stoch ;\n        system.first( x , det );\n        system.second( x , stoch );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            x[i] += dt * det[i] + sqrt( dt ) * stoch[i];\n    }\n};\n//]\n*/\n\n\n\n\n//[ stochastic_euler_class\ntemplate< size_t N >\nclass stochastic_euler\n{\npublic:\n\n    typedef boost::array< double , N > state_type;\n    typedef boost::array< double , N > deriv_type;\n    typedef double value_type;\n    typedef double time_type;\n    typedef unsigned short order_type;\n\n    typedef boost::numeric::odeint::stepper_tag stepper_category;\n\n    static order_type order( void ) { return 1; }\n\n    template< class System >\n    void do_step( System system , state_type &x , time_type t , time_type dt ) const\n    {\n        deriv_type det , stoch ;\n        system.first( x , det );\n        system.second( x , stoch );\n        for( size_t i=0 ; i<x.size() ; ++i )\n            x[i] += dt * det[i] + sqrt( dt ) * stoch[i];\n    }\n};\n//]\n\n\n\n//[ stochastic_euler_ornstein_uhlenbeck_def\nconst static size_t N = 1;\ntypedef boost::array< double , N > state_type;\n\nstruct ornstein_det\n{\n    void operator()( const state_type &x , state_type &dxdt ) const\n    {\n        dxdt[0] = -x[0];\n    }\n};\n\nstruct ornstein_stoch\n{\n    boost::mt19937 m_rng;\n    boost::normal_distribution<> m_dist;\n\n    ornstein_stoch( double sigma ) : m_rng() , m_dist( 0.0 , sigma ) { }\n\n    void operator()( const state_type &x , state_type &dxdt )\n    {\n        dxdt[0] = m_dist( m_rng );\n    }\n};\n//]\n\nstruct streaming_observer\n{\n    template< class State >\n    void operator()( const State &x , double t ) const\n    {\n        std::cout << t << \"\\t\" << x[0] << \"\\n\";\n    }\n};\n\n\nint main( int argc , char **argv )\n{\n    using namespace std;\n    using namespace boost::numeric::odeint;\n\n    //[ ornstein_uhlenbeck_main\n    double dt = 0.1;\n    state_type x = {{ 1.0 }};\n    integrate_const( stochastic_euler< N >() , make_pair( ornstein_det() , ornstein_stoch( 1.0 ) ) ,\n            x , 0.0 , 10.0 , dt , streaming_observer() );\n    //]\n    return 0;\n}\n", "meta": {"hexsha": "23474255b6337d4c47d950c21e53e53f0d9d83e2", "size": 3178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/examples/stochastic_euler.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/examples/stochastic_euler.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": 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": "boost/boost_1_56_0/libs/numeric/odeint/examples/stochastic_euler.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": 21.619047619, "max_line_length": 100, "alphanum_fraction": 0.6299559471, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867969424067, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.5859645137493321}}
{"text": "/// @file bealab/core/prelim/math.hpp\n/// A number of math functions for real and complex numbers.\n\n#ifndef _BEALAB_PRELIM_MATH_\n#define\t_BEALAB_PRELIM_MATH_\n\n#include <cmath>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\nnamespace bealab\n{\n/// @defgroup prelim_math Math functions\n/// A number of math functions, most of them imported from STD.\n/// - Classification\n///   - isnan\n///   - isinf\n///   - isfinite\n/// - Basic functions\n///   - min\n///   - max\n///   - round\n///   - trunc\n///   - ceil\n///   - floor\n///   - mod\n/// - Complex functions\n///   - abs\n///   - arg\n///   - real\n///   - imag\n///   - conj\n///   - polar\n/// - Trigonometric functions\n///   - sin\n///   - cos\n///   - tan\n///   - asin\n///   - acos\n///   - atan\n/// - Hyperbolic functions\n///   - sinh\n///   - cosh\n///   - tanh\n///   - asinh\n///   - acosh\n///   - atanh\n/// - Exponential and power functions\n///   - exp\n///   - log\n///   - log2\n///   - log10\n///   - pow\n///   - sqrt\n/// - Special functions\n///   - sinc\n///   - factorial\n///   - erf\n///   - erfc\n///   - erf_inv\n///   - erfc_inv\n/// @{\n\n/// @name Classification\nusing std::isnan;\nusing std::isinf;\nusing std::isfinite;\n/// @}\n\n/// @name Basic functions\nusing std::min;\nusing std::max;\n#ifdef BEALAB_MACOSX\nusing ::round;\nusing ::trunc;\n#else\nusing std::round;\nusing std::trunc;\n#endif\nusing std::ceil;\nusing std::floor;\n\n/// x modulo y\ninline double mod( double x, double y ) { return x - floor( x / y ) * y; }\n/// @}\n\n/// @name Complex functions\nusing std::abs;\nusing std::arg;\nusing std::real;\nusing std::imag;\nusing std::conj;\nusing std::polar;\n//inline double abs( const complex& x )  { return std::abs(_complex(x)); }\n//inline double arg( const complex& x ) { return std::arg(_complex(x)); }\n//inline double real( const complex& x ) { return std::real(_complex(x)); }\n//inline double imag( const complex& x ) { return std::imag(_complex(x)); }\n//inline complex conj( const complex& x ) { return std::conj(_complex(x)); }\n//inline complex polar( double r, double theta=0 ) { return std::polar(r,theta); }\n/// @}\n\n/// @name Trigonometric functions\nusing std::sin;\nusing std::cos;\nusing std::tan;\nusing std::asin;\nusing std::acos;\nusing std::atan;\n//inline complex sin( const complex& x ) { return std::sin(_complex(x)); }\n//inline complex cos( const complex& x ) { return std::cos(_complex(x)); }\n//inline complex tan( const complex& x ) { return std::tan(_complex(x)); }\n//inline complex asin( const complex& x ) { return std::asin(_complex(x)); }\n//inline complex acos( const complex& x ) { return std::acos(_complex(x)); }\n//inline complex atan( const complex& x ) { return std::atan(_complex(x)); }\n/// @}\n\n/// @name Hyperbolic functions\nusing std::sinh;\nusing std::cosh;\nusing std::tanh;\nusing std::asinh;\nusing std::acosh;\nusing std::atanh;\n//inline complex sinh( const complex& x ) { return std::sinh(_complex(x)); }\n//inline complex cosh( const complex& x ) { return std::cosh(_complex(x)); }\n//inline complex tanh( const complex& x ) { return std::tanh(_complex(x)); }\n//inline complex asinh( const complex& x ) { return std::asinh(_complex(x)); }\n//inline complex acosh( const complex& x ) { return std::acosh(_complex(x)); }\n//inline complex atanh( const complex& x ) { return std::atanh(_complex(x)); }\n/// @}\n\n/// @name Exponential and power functions\nusing std::exp;\nusing std::log;\n#ifdef BEALAB_MACOSX\nusing ::log2;\n#else\nusing std::log2;\n#endif\nusing std::log10;\n//inline complex exp( const complex& x ) { return std::exp(_complex(x)); }\n//inline complex log( const complex& x ) { return std::log(_complex(x)); }\n//inline complex log2( const complex& x ) { return log(_complex(x))/log(2); }\n//inline complex log10( const complex& x ) { return std::log10(_complex(x)); }\nusing std::pow;\n//inline double pow( double x, int y ) { return std::pow( x, y ); }\n//inline complex pow( double x, double y )  { return std::pow( _complex(x), y ); }\n//inline complex pow( const complex& x, int y ) { return std::pow(_complex(x),y); }\n//inline complex pow( const complex& x, double y ) { return std::pow(_complex(x),y); }\n//inline complex pow( double x, const complex& y ) { return std::pow(x,_complex(y)); }\nusing std::sqrt;\n//inline complex sqrt( const complex& x ) { return std::sqrt(_complex(x)); }\n/// @}\n\n/// @name Special functions\n\n/// Sine cardinal function\n//inline double sinc( double x ) { return x == 0 ? 1 : sin( pi * x ) / (pi * x); }\ninline double sinc( double x ) { return boost::math::sinc_pi( pi * x ); }\n\n/// Factorial\ninline double factorial( int i ) { return boost::math::factorial<double>(i); }\n\n/// Binomial coefficients\ninline double binomial_coefficient( int n, int k )\n\t{ return boost::math::binomial_coefficient<double>(n,k); }\n\nusing boost::math::erf;\nusing boost::math::erfc;\nusing boost::math::erf_inv;\nusing boost::math::erfc_inv;\n\n/// @}\n\n/// @}\n}\n#endif\n", "meta": {"hexsha": "9fb9958ffd955e284d33a1fdc0d0ba03a3a2f7e8", "size": 4991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bealab/core/prelim/math.hpp", "max_stars_repo_name": "damianmarelli/bealab", "max_stars_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-17T13:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-17T13:45:21.000Z", "max_issues_repo_path": "include/bealab/core/prelim/math.hpp", "max_issues_repo_name": "damianmarelli/bealab", "max_issues_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bealab/core/prelim/math.hpp", "max_forks_repo_name": "damianmarelli/bealab", "max_forks_repo_head_hexsha": "3357a0b0fd836c3557f39863471680cc99721729", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7277777778, "max_line_length": 86, "alphanum_fraction": 0.6429573232, "num_tokens": 1455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.585964497414566}}
{"text": "#include <glm/models/links/power.hpp>\n\n#include <armadillo>\n\nusing namespace arma;\n\npower_link::power_link(float lambda)\n    : glm_link::glm_link( \"power\" )\n{\n    m_lambda = lambda;\n    if( lambda < 1e-6 )\n    {\n        m_lambda = 0.0;\n    }\n    else if( lambda > 2.0 )\n    {\n        m_lambda = 2.0;\n    }\n}\n\nvec\npower_link::init_beta(const mat &X, const vec &y) const\n{\n    return 0;\n}\n\nvec\npower_link::mu(const arma::vec &eta) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return log( eta );\n    }\n    else if( m_lambda == 2.0 )\n    {\n        return exp( eta );\n    }\n    else if( m_lambda < 1.0 )\n    {\n        return ( pow( eta, m_lambda ) - 1 ) / m_lambda;\n    }\n    else\n    {\n        return pow( 1 + eta*(2-m_lambda), 1/(2-m_lambda) );\n    }\n}\n\nvec\npower_link::eta(const arma::vec &mu) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return exp( mu );\n    }\n    else if( m_lambda == 2.0 )\n    {\n        return log( mu );\n    }\n    else if( m_lambda < 1.0 )\n    {\n        return pow( 1 + mu*m_lambda, 1/m_lambda);\n    }\n    else\n    {\n        return (pow( mu, 2 - m_lambda ) - 1) / (2 - m_lambda);\n    }\n}\n\nvec\npower_link::mu_eta(const arma::vec &mu) const\n{\n    if( m_lambda == 0.0 )\n    {\n        return exp( mu );\n    }\n    else if( m_lambda == 2.0 )\n    {\n        return 1 / mu;\n    }\n    else if( m_lambda < 1.0 )\n    {\n        return pow( 1 + mu * m_lambda, 1/m_lambda - 1 );\n    }\n    else\n    {\n        return pow( mu, 1 - m_lambda );\n    }\n}\n", "meta": {"hexsha": "6adc997bff807c40af441364999ac362feb381da", "size": 1459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/glm/models/links/power.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/models/links/power.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/models/links/power.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 16.393258427, "max_line_length": 62, "alphanum_fraction": 0.4893762851, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5859352527623585}}
{"text": "#ifndef PYBNESIAN_UTIL_CHISQUARESUM_HPP\n#define PYBNESIAN_UTIL_CHISQUARESUM_HPP\n\n#include <Eigen/Dense>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <util/rpoly.hpp>\n#include <util/uniroot.hpp>\n\nusing boost::math::binomial_coefficient, boost::math::gamma_distribution, boost::math::cdf, boost::math::complement;\nusing Eigen::VectorXd, Eigen::Dynamic, Eigen::Matrix;\n\nnamespace util {\n\nnamespace detail {\n\ntemplate <typename VectorType>\nVectorType chisquaresum_moments(VectorType& coeffs, int p) {\n    using Scalar = typename VectorType::Scalar;\n    VectorType cumulants(2 * p);\n\n    cumulants(0) = coeffs.sum();\n    cumulants(1) = 2 * coeffs.squaredNorm();\n\n    // Start loop in r = 3, so 2^(r-1)*(r-1)! = 8\n    Scalar fact_const = 8;\n    for (int i = 2, end = 2 * p; i < end; ++i) {\n        cumulants(i) = fact_const * coeffs.array().pow(i + 1).sum();\n        fact_const *= 2 * (i + 1);\n    }\n\n    VectorType moments = cumulants;\n    moments(1) += moments(0) * moments(0);\n    for (int i = 2, end = 2 * p; i < end; ++i) {\n        auto offset = cumulants(0) * moments(i - 1) + i * cumulants(1) * moments(i - 2);\n\n        for (int j = 2; j < i; ++j) {\n            offset += binomial_coefficient<Scalar>(i, j) * cumulants(j) * moments(i - j - 1);\n        }\n\n        moments(i) += offset;\n    }\n\n    return moments;\n}\n\ntemplate <typename VectorType>\nMatrix<typename VectorType::Scalar, Dynamic, Dynamic> delta_matrix_template(VectorType& moments, int size_matrix) {\n    using Scalar = typename VectorType::Scalar;\n    using MatrixType = Matrix<Scalar, Dynamic, Dynamic>;\n\n    MatrixType t(size_matrix, size_matrix);\n\n    t(0) = 1;\n    t(0, 1) = t(1, 0) = moments(0);\n\n    // Fill two first columns first\n    for (int i = 2; i < size_matrix; ++i) {\n        t(i, 0) = moments(i - 1);\n    }\n\n    for (int i = 1; i < size_matrix; ++i) {\n        t(i, 1) = moments(i);\n    }\n\n    // Fill remaining columns\n    for (int j = 2; j < size_matrix; ++j) {\n        for (int i = 0; i < size_matrix; ++i) {\n            t(i, j) = moments(i + j - 1);\n        }\n    }\n\n    return t;\n}\n\ntemplate <typename Scalar>\nMatrix<Scalar, Dynamic, 1> delta_mult_coefficients(Scalar alpha, int size_matrix) {\n    using VectorType = Matrix<Scalar, Dynamic, 1>;\n    auto max_r = 2 * size_matrix - 2;\n\n    VectorType mult_coefficients(max_r - 1);\n    mult_coefficients(0) = 1 + alpha;\n    for (int i = 1, end = max_r - 1; i < end; ++i) {\n        mult_coefficients(i) = mult_coefficients(i - 1) * (1 + (i + 1) * alpha);\n    }\n\n    return mult_coefficients.cwiseInverse();\n}\n\ntemplate <typename MatrixType>\nvoid delta_apply_mult_coefficients(MatrixType& delta,\n                                   Matrix<typename MatrixType::Scalar, Dynamic, 1>& mult_coefficients) {\n    auto p = delta.rows();\n    // Divide first two columns\n    for (int i = 2; i < p; ++i) {\n        delta(i, 0) *= mult_coefficients(i - 2);\n    }\n\n    for (int i = 1; i < p; ++i) {\n        delta(i, 1) *= mult_coefficients(i - 1);\n    }\n\n    // Divide remaining columns.\n    for (int j = 2; j < p; ++j) {\n        for (int i = 0; i < p; ++i) {\n            delta(i, j) *= mult_coefficients(i + j - 2);\n        }\n    }\n}\n\ntemplate <typename Scalar>\nstruct DeltaMatrixDeterminant {\n    using VectorType = Matrix<Scalar, Dynamic, 1>;\n    using MatrixType = Matrix<Scalar, Dynamic, Dynamic>;\n    Scalar operator()(Scalar alpha) {\n        MatrixType copy = matrix;\n\n        auto mult_coefficients = delta_mult_coefficients(alpha, matrix.rows());\n        delta_apply_mult_coefficients(copy, mult_coefficients);\n\n        return copy.determinant();\n    }\n\n    MatrixType matrix;\n};\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar lambda_tilde(VectorType& moments, int p) {\n    using Scalar = typename VectorType::Scalar;\n\n    // This is the closed solution for lambda_1\n    Scalar last_lambda = moments(1) / (moments(0) * moments(0)) - 1;\n    for (auto i = 2; i <= p; ++i) {\n        DeltaMatrixDeterminant<Scalar> mdet{/*.matrix = */ delta_matrix_template(moments, i + 1)};\n        last_lambda = util::uniroot(mdet, static_cast<Scalar>(0), last_lambda, static_cast<Scalar>(1e-9), 1000);\n    }\n\n    return last_lambda;\n}\n\ntemplate <typename VectorType>\nMatrix<typename VectorType::Scalar, Dynamic, 1> mu_roots(VectorType& moments,\n                                                         typename VectorType::Scalar lambda_tilde,\n                                                         int p) {\n    using Scalar = typename VectorType::Scalar;\n    using VecType = Matrix<Scalar, Dynamic, 1>;\n\n    auto M = delta_matrix_template(moments, p + 1);\n    auto mult_coefficients = delta_mult_coefficients(lambda_tilde, p + 1);\n    delta_apply_mult_coefficients(M, mult_coefficients);\n\n    VecType poly_coeffs(p + 1);\n\n    M.col(p) = VectorType::Zero(p + 1);\n\n    for (int i = p; i >= 0; --i) {\n        M(i, p) = 1;\n        poly_coeffs(p - i) = M.determinant();\n        M(i, p) = 0;\n    }\n\n    VecType real_roots = VecType::Zero(p);\n    VecType complex_roots = VecType::Zero(p);\n\n    util::RPoly<Scalar> poly_solver;\n    poly_solver.findRoots(poly_coeffs.data(), p, real_roots.data(), complex_roots.data());\n\n    return real_roots;\n}\n\ntemplate <typename VectorType>\nVectorType mixture_proportions(VectorType& mu, VectorType& moments, typename VectorType::Scalar lambda_tilde, int p) {\n    using Scalar = typename VectorType::Scalar;\n    using MatrixType = Matrix<Scalar, Dynamic, Dynamic>;\n\n    MatrixType vandermonde(p, p);\n\n    vandermonde.row(0) = VectorType::Ones(p);\n    vandermonde.row(1) = mu;\n    vandermonde.row(2) = mu.cwiseProduct(mu);\n    for (int i = 3; i < p; ++i) {\n        vandermonde.row(i) = mu.array().pow(i);\n    }\n\n    VectorType delta_vec(p);\n    delta_vec(0) = 1;\n    delta_vec(1) = moments(0);\n    delta_vec(2) = moments(1) / (1 + lambda_tilde);\n    delta_vec(3) = moments(2) / ((1 + lambda_tilde) * (1 + 2 * lambda_tilde));\n\n    auto mult_coeff = (1 + lambda_tilde) * (1 + 2 * lambda_tilde);\n    for (int i = 4; i < p; ++i) {\n        mult_coeff *= (1 + (i - 1) * lambda_tilde);\n        delta_vec(i) = moments(i - 1) * (1. / mult_coeff);\n    }\n\n    return vandermonde.colPivHouseholderQr().solve(delta_vec);\n}\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar lpb4_cdf(VectorType& prop,\n                                     VectorType& mu,\n                                     typename VectorType::Scalar lambda_tilde,\n                                     typename VectorType::Scalar quantile) {\n    using Scalar = typename VectorType::Scalar;\n    auto k = 1. / lambda_tilde;\n\n    Scalar res = 0;\n    for (int i = 0; i < prop.rows(); ++i) {\n        auto theta = mu(i) * lambda_tilde;\n\n        if (theta <= 0) {\n            throw std::runtime_error(\"Wrong theta parameter.\");\n        }\n\n        gamma_distribution<Scalar> gamma(k, theta);\n        res += prop(i) * cdf(gamma, quantile);\n    }\n\n    return res;\n}\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar lpb4_cdf_complement(VectorType& prop,\n                                                VectorType& mu,\n                                                typename VectorType::Scalar lambda_tilde,\n                                                typename VectorType::Scalar quantile) {\n    using Scalar = typename VectorType::Scalar;\n    auto k = 1. / lambda_tilde;\n    Scalar res = 0;\n    for (int i = 0; i < prop.rows(); ++i) {\n        auto theta = mu(i) * lambda_tilde;\n        gamma_distribution<Scalar> gamma(k, theta);\n        res += prop(i) * cdf(complement(gamma, quantile));\n    }\n\n    return res;\n}\n\n}  // namespace detail\n\n/**\n * A comparison of efficient approximations for a weighted sum of chi-squared random variables\n */\ntemplate <typename VectorType>\ntypename VectorType::Scalar lpb4(VectorType& coeffs, typename VectorType::Scalar quantile) {\n    if (coeffs.rows() < 4) {\n        throw std::invalid_argument(\"lbp4 requires at least 4 coefficients.\");\n    }\n\n    auto p = 4;\n    auto moments = detail::chisquaresum_moments(coeffs, p);\n    auto ld_tilde = detail::lambda_tilde(moments, p);\n    auto mu = detail::mu_roots(moments, ld_tilde, p);\n    auto prop = detail::mixture_proportions(mu, moments, ld_tilde, p);\n    return detail::lpb4_cdf(prop, mu, ld_tilde, quantile);\n}\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar lpb4_complement(VectorType& coeffs, typename VectorType::Scalar quantile) {\n    if (coeffs.rows() < 4) {\n        throw std::invalid_argument(\"lbp4 requires at least 4 coefficients.\");\n    }\n\n    auto p = 4;\n    auto moments = detail::chisquaresum_moments(coeffs, p);\n    auto ld_tilde = detail::lambda_tilde(moments, p);\n    auto mu = detail::mu_roots(moments, ld_tilde, p);\n    auto prop = detail::mixture_proportions(mu, moments, ld_tilde, p);\n    return detail::lpb4_cdf_complement(prop, mu, ld_tilde, quantile);\n}\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar hbe(VectorType& coeffs, typename VectorType::Scalar quantile) {\n    using Scalar = typename VectorType::Scalar;\n    auto k1 = coeffs.sum();\n    auto squared = coeffs.array().square().matrix();\n    auto k2 = 2 * squared.sum();\n    auto k3 = 8 * (coeffs.dot(squared));\n\n    auto nu = 8 * (k2 * k2 * k2) / (k3 * k3);\n\n    auto statistic = std::sqrt(2 * nu / k2) * (quantile - k1) + nu;\n\n    gamma_distribution<Scalar> gamma(nu / 2., 2);\n\n    return cdf(gamma, statistic);\n}\n\ntemplate <typename VectorType>\ntypename VectorType::Scalar hbe_complement(VectorType& coeffs, typename VectorType::Scalar quantile) {\n    using Scalar = typename VectorType::Scalar;\n    auto k1 = coeffs.sum();\n    auto squared = coeffs.array().square().matrix();\n    auto k2 = 2 * squared.sum();\n    auto k3 = 8 * (coeffs.dot(squared));\n\n    auto nu = 8 * (k2 * k2 * k2) / (k3 * k3);\n\n    auto statistic = std::sqrt(2 * nu / k2) * (quantile - k1) + nu;\n\n    gamma_distribution<Scalar> gamma(nu / 2., 2);\n\n    return cdf(complement(gamma, statistic));\n}\n\n}  // namespace util\n\n#endif  // PYBNESIAN_UTIL_CHISQUARESUM_HPP", "meta": {"hexsha": "52606395968b2fa6bb09f01b6a84582813516898", "size": 10003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pybnesian/util/chisquaresum.hpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/util/chisquaresum.hpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/util/chisquaresum.hpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 32.3721682848, "max_line_length": 118, "alphanum_fraction": 0.6149155253, "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5859352473952016}}
{"text": "// Copyright 2002 Rensselaer Polytechnic Institute\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: Lauren Foutz\n//           Scott Hill\n\n/*\n  This file implements the functions\n\n  template <class VertexListGraph, class DistanceMatrix, \n    class P, class T, class R>\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\n    const VertexListGraph& g, DistanceMatrix& d, \n    const bgl_named_params<P, T, R>& params)\n\n  AND\n\n  template <class VertexAndEdgeListGraph, class DistanceMatrix, \n    class P, class T, class R>\n  bool floyd_warshall_all_pairs_shortest_paths(\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d, \n    const bgl_named_params<P, T, R>& params)\n*/\n\n\n#ifndef BOOST_GRAPH_FLOYD_WARSHALL_HPP\n#define BOOST_GRAPH_FLOYD_WARSHALL_HPP\n\n#include <boost/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/relax.hpp>\n#include <algorithm> // for std::min and std::max\n\nnamespace boost\n{\n  namespace detail \n  {\n  \n    template<typename VertexListGraph, typename DistanceMatrix, typename BinaryPredicate, typename BinaryFunction, typename Infinity, typename Zero>\n\tbool floyd_warshall_dispatch(const VertexListGraph& g,  DistanceMatrix& d, const BinaryPredicate &compare, const BinaryFunction &combine, \n\t\t\t\t\t\tconst Infinity& inf, const Zero& zero)\n    {\n      BOOST_USING_STD_MIN();\n\n      typename graph_traits<VertexListGraph>::vertex_iteratorN \n        i, lasti, j, lastj, k, lastk;\n    \n      /* main Floyd Warshall algorithm */\n      for (tie(k, lastk) = vertices(g); k != lastk; k++)\n        for (tie(i, lasti) = vertices(g); i != lasti; i++)\n          for (tie(j, lastj) = vertices(g); j != lastj; j++)\n          {\n            d[*i][*j] = min BOOST_PREVENT_MACRO_SUBSTITUTION(d[*i][*j], combine(d[*i][*k], d[*k][*j]));\n          }\n      \n    \n\t\t/* checks for negative weight cycle */\n      for (tie(i, lasti) = vertices(g); i != lasti; i++)\n      \tif (compare(d[*i][*i], zero))\n          return false;\n      \n\t  return true;\n    }\n  \n\n/* with predecessor map */\n    template<typename VertexListGraph, typename DistanceMatrix, typename PredecessorMatrix, typename BinaryPredicate, typename BinaryFunction, typename Infinity, typename Zero>\n\tbool floyd_warshall_dispatch2(const VertexListGraph& g,  DistanceMatrix& d, PredecessorMatrix& p, const BinaryPredicate &compare, const BinaryFunction &combine, \n\t\t\t\t\t\tconst Infinity& inf, const Zero& zero)\n    {\n      BOOST_USING_STD_MIN();\n\n      typename graph_traits<VertexListGraph>::vertex_iteratorN i, lasti, j, lastj, k, lastk;\n    \n      // main Floyd Warshall algorithm \n      for (tie(k, lastk) = vertices(g); k != lastk; k++)\n        for (tie(i, lasti) = vertices(g); i != lasti; i++)\n          for (tie(j, lastj) = vertices(g); j != lastj; j++)\n          {\n\t\t\tif(d[*i][*j] > combine(d[*i][*k], d[*k][*j]))\n\t\t\t\tp[*i][*j] = p[*k][*j];\n\n\t\t\td[*i][*j] = min BOOST_PREVENT_MACRO_SUBSTITUTION(d[*i][*j], combine(d[*i][*k], d[*k][*j]));\n          }\n      \n    \n\t\t// checks for negative weight cycle \n      for (tie(i, lasti) = vertices(g); i != lasti; i++)\n      \tif (compare(d[*i][*i], zero))\n          return false;\n      \n\t  return true;\n    }\n  }\n\n  template <typename VertexListGraph, typename DistanceMatrix, typename BinaryPredicate, typename BinaryFunction,typename Infinity, typename Zero>\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(const VertexListGraph& g, DistanceMatrix& d, const BinaryPredicate& compare, \n\t\t\t\t    const BinaryFunction& combine, const Infinity& inf, const Zero& zero)\n  {\n    function_requires<VertexListGraphConcept<VertexListGraph> >();\n  \n    return detail::floyd_warshall_dispatch(g, d, compare, combine, inf, zero);\n  }\n  \n\n  \n  template <typename VertexAndEdgeListGraph, typename DistanceMatrix, typename WeightMap, typename BinaryPredicate, typename BinaryFunction, typename Infinity, typename Zero>\n  bool floyd_warshall_all_pairs_shortest_paths( const VertexAndEdgeListGraph& g, DistanceMatrix& d, const WeightMap& w, \n  \t\t\t\t\t const BinaryPredicate& compare, const BinaryFunction& combine, const Infinity& inf, const Zero& zero)\n  {\n    BOOST_USING_STD_MIN();\n\n    function_requires<VertexListGraphConcept<VertexAndEdgeListGraph> >();\n    function_requires<EdgeListGraphConcept<VertexAndEdgeListGraph> >();\n    function_requires<IncidenceGraphConcept<VertexAndEdgeListGraph> >();\n  \n    typename graph_traits<VertexAndEdgeListGraph>::vertex_iteratorN \tfirstv, lastv, firstv2, lastv2;\n    typename graph_traits<VertexAndEdgeListGraph>::edge_iteratorN \tfirst, last;\n  \n\n    for(tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n      for(tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2; firstv2++)\n\t    d[*firstv][*firstv2] = inf;\n\n\n    for(tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n      d[*firstv][*firstv] = 0;\n    \n\n    for(tie(first, last) = edges(g); first != last; first++)\n    {\n      if (d[source(*first, g)][target(*first, g)] != inf)\n        d[source(*first, g)][target(*first, g)] = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(w, *first), d[source(*first, g)][target(*first, g)]);\n      else \n        d[source(*first, g)][target(*first, g)] = get(w, *first);\t\n    }\n    \n    bool is_undirected = is_same<typename graph_traits<VertexAndEdgeListGraph>::directed_category, undirected_tag>::value;\n    if (is_undirected)\n    {\n      for(tie(first, last) = edges(g); first != last; first++)\n      {\n        if (d[target(*first, g)][source(*first, g)] != inf)\n          d[target(*first, g)][source(*first, g)] = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(w, *first), d[target(*first, g)][source(*first, g)]);\n        else \n          d[target(*first, g)][source(*first, g)] = get(w, *first);\n      }\n    }\n    \n  \n    return detail::floyd_warshall_dispatch(g, d, compare, combine, inf, zero);\n  }\n\n/* with predecessor map */\n  template <typename VertexAndEdgeListGraph, typename DistanceMatrix, typename PredecessorMatrix, typename WeightMap, typename BinaryPredicate, typename BinaryFunction, typename Infinity, typename Zero>\n  bool floyd_warshall_all_pairs_shortest_paths2( const VertexAndEdgeListGraph& g, DistanceMatrix& d, PredecessorMatrix& p, const WeightMap& w, \n  \t\t\t\t\t const BinaryPredicate& compare, const BinaryFunction& combine, const Infinity& inf, const Zero& zero)\n  {\n    BOOST_USING_STD_MIN();\n\n    function_requires<VertexListGraphConcept<VertexAndEdgeListGraph> >();\n    function_requires<EdgeListGraphConcept<VertexAndEdgeListGraph> >();\n    function_requires<IncidenceGraphConcept<VertexAndEdgeListGraph> >();\n  \n    typename graph_traits<VertexAndEdgeListGraph>::vertex_iteratorN \tfirstv, lastv, firstv2, lastv2;\n    typename graph_traits<VertexAndEdgeListGraph>::edge_iteratorN \tfirst, last;\n  \n    // initialize matrix: distance infinity\n    for(tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n      for(tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2; firstv2++)\n      { \n\t  \td[*firstv][*firstv2] = inf;\n\t\tp[*firstv][*firstv2] = *firstv;\n\t\t//cerr << \"[FW::Initialization]  p: \" << *firstv << \" = \" << p[*firstv][*firstv2] << endl;\n\t  }\n    \n    // initialize matrix: distance to itself i zero\n    for(tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\n      d[*firstv][*firstv] = 0;\n    \n\n    for(tie(first, last) = edges(g); first != last; first++)\n    {\n      if (d[source(*first, g)][target(*first, g)] != inf)\n\t  {\n\t  \tcerr << \"[Floyd-Warshall] ERROR Predecessor map \" << endl;\n        d[source(*first, g)][target(*first, g)] = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(w, *first), d[source(*first, g)][target(*first, g)]);\n\t  }\n      else \n\t  {\n        d[source(*first, g)][target(*first, g)] = get(w, *first);\t\n\t\tp[source(*first, g)][target(*first, g)] = source(*first, g); // enter predecessor map here\n\t    //cerr << \"[FW::Initialization] (\" << source(*first, g) << \",\" << target(*first, g) << \") Parent map: \" << p[source(*first, g)][target(*first, g)];\n\t\t//cerr << \" Weight Map: \" << d[source(*first, g)][target(*first, g)] << endl;\n\t  }\n    }\n    \n    bool is_undirected = is_same<typename graph_traits<VertexAndEdgeListGraph>::directed_category, undirected_tag>::value;\n    if (is_undirected)\n    {\n      for(tie(first, last) = edges(g); first != last; first++)\n      {\n        if (d[target(*first, g)][source(*first, g)] != inf)\n\t\t{\n\t\t  cerr << \"[Floyd-Warshall] Undirected: ERROR Predecessor map \" << endl;\n          d[target(*first, g)][source(*first, g)] = min BOOST_PREVENT_MACRO_SUBSTITUTION(get(w, *first), d[target(*first, g)][source(*first, g)]);\n\t\t}\n        else \n\t\t{\n          d[target(*first, g)][source(*first, g)] = get(w, *first);\n\t\t  p[target(*first, g)][source(*first, g)] = target(*first, g); // enter predecessor map here\n\t\t  //cerr << \"[FW::Initialization] (\" << target(*first, g) << \",\" << source(*first, g) << \") UndParent map: \" << p[target(*first, g)][source(*first, g)];\n\t\t  //cerr << \" Weight Map: \" << d[target(*first, g)][source(*first, g)] << endl;\n\t\t}\n      }\n    }\n    \n  \n    return detail::floyd_warshall_dispatch2(g, d, p, compare, combine, inf, zero);\n  }\n\n\n  namespace detail {        \n    template <class VertexListGraph, class DistanceMatrix, class WeightMap, class P, class T, class R>\n    bool floyd_warshall_init_dispatch(const VertexListGraph& g, DistanceMatrix& d, WeightMap w, const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename property_traits<WeightMap>::value_type WM;\n    \n      return floyd_warshall_initialized_all_pairs_shortest_paths(g, d,\n        choose_param(get_param(params, distance_compare_t()), \n          std::less<WM>()),\n        choose_param(get_param(params, distance_combine_t()), \n          closed_plus<WM>()),\n        choose_param(get_param(params, distance_inf_t()), \n          std::numeric_limits<WM>::max BOOST_PREVENT_MACRO_SUBSTITUTION()),\n        choose_param(get_param(params, distance_zero_t()), \n          WM()));\n    }\n    \n\n    \n    template <class VertexAndEdgeListGraph, class DistanceMatrix, class WeightMap, class P, class T, class R>\n    bool floyd_warshall_noninit_dispatch(const VertexAndEdgeListGraph& g, DistanceMatrix& d, WeightMap w, const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename property_traits<WeightMap>::value_type WM;\n    \n      return floyd_warshall_all_pairs_shortest_paths(g, d, w,\n        choose_param(get_param(params, distance_compare_t()), \n          std::less<WM>()),\n        choose_param(get_param(params, distance_combine_t()), \n          closed_plus<WM>()),\n        choose_param(get_param(params, distance_inf_t()), \n          std::numeric_limits<WM>::max BOOST_PREVENT_MACRO_SUBSTITUTION()),\n        choose_param(get_param(params, distance_zero_t()), \n          WM()));\n    }\n\n\n/* With predecessor map */\n    template <class VertexAndEdgeListGraph, class DistanceMatrix, class PredecessorMatrix, class WeightMap, class P, class T, class R>\n    bool floyd_warshall_noninit_dispatch2(const VertexAndEdgeListGraph& g, DistanceMatrix& d, PredecessorMatrix& p, WeightMap w, const bgl_named_params<P, T, R>& params)\n    {\n      typedef typename property_traits<WeightMap>::value_type WM;\n    \n      return floyd_warshall_all_pairs_shortest_paths2(g, d, p, w,\n        choose_param(get_param(params, distance_compare_t()), \n          std::less<WM>()),\n        choose_param(get_param(params, distance_combine_t()), \n          closed_plus<WM>()),\n        choose_param(get_param(params, distance_inf_t()), \n          std::numeric_limits<WM>::max BOOST_PREVENT_MACRO_SUBSTITUTION()),\n        choose_param(get_param(params, distance_zero_t()), \n          WM()));\n    }\n\n    \n\n  }   // namespace detail\n\n  \n/* VertexListGraphs:   */  \n  template <class VertexListGraph, class DistanceMatrix, class P, class T, class R>\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(const VertexListGraph& g, DistanceMatrix& d, const bgl_named_params<P, T, R>& params)\n  {\n    return detail::floyd_warshall_init_dispatch(g, d, choose_const_pmap(get_param(params, edge_weight), g, edge_weight), params);\n  }\n  \n  template <class VertexListGraph, class DistanceMatrix>\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(const VertexListGraph& g, DistanceMatrix& d)\n  {\n    bgl_named_params<int,int> params(0);\n    return detail::floyd_warshall_init_dispatch(g, d, get(edge_weight, g), params);\n  }\n  \n\n/* VertexAndEdgeListGraphs:   */\n  template <class VertexAndEdgeListGraph, class DistanceMatrix, class P, class T, class R>\n  bool floyd_warshall_all_pairs_shortest_paths(const VertexAndEdgeListGraph& g, DistanceMatrix& d, const bgl_named_params<P, T, R>& params)\n  {\n    return detail::floyd_warshall_noninit_dispatch(g, d, choose_const_pmap(get_param(params, edge_weight), g, edge_weight), params);\n  }\n  \n  template <class VertexAndEdgeListGraph, class DistanceMatrix>\n  bool floyd_warshall_all_pairs_shortest_paths(const VertexAndEdgeListGraph& g, DistanceMatrix& d)\n  {\n    bgl_named_params<int,int> params(0);\n    return detail::floyd_warshall_noninit_dispatch(g, d, get(edge_weight, g), params);\n  }\n\n/* With predecessor map */\n  template <class VertexAndEdgeListGraph, class DistanceMatrix, class PredecessorMatrix, class P, class T, class R>\n  bool floyd_warshall_all_pairs_shortest_paths2(const VertexAndEdgeListGraph& g, DistanceMatrix& d, PredecessorMatrix& p, const bgl_named_params<P, T, R>& params)\n  {\n    return detail::floyd_warshall_noninit_dispatch2(g, d, p, choose_const_pmap(get_param(params, edge_weight), g, edge_weight), params);\n    //return detail::floyd_warshall_noninit_dispatch(g, d, choose_const_pmap(get_param(params, edge_weight), g, edge_weight), params);\n  }\n  \n\n} // namespace boost\n\n#endif\n\n", "meta": {"hexsha": "c79523dcb4fcecb5d79dffb8facda16c452a888f", "size": 13866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphLib/smtalgs/floyd_warshall_khv.hpp", "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/smtalgs/floyd_warshall_khv.hpp", "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/smtalgs/floyd_warshall_khv.hpp", "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": 42.2743902439, "max_line_length": 202, "alphanum_fraction": 0.6803692485, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5859352447314541}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <sophus/se3.hpp>\n#include <sophus/so3.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\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\nPoint2d pixel2cam(const Point2d &p, const Mat &K);\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\n\n// BA by gauss-newton\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose\n);\n\nvoid pose_refinement_gauss_newton(const VecVector3d& points_3d, const VecVector2d& points_2d, const Eigen::Matrix3d& K, Sophus::SE3d& pose);\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\n\n  VecVector3d pts_3d_eigen;\n  VecVector2d pts_2d_eigen;\n  for (size_t i = 0; i < pts_3d.size(); ++i) {\n    pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n    pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n  }\n\n  cout << \"calling bundle adjustment by gauss newton\" << endl;\n  Sophus::SE3d pose_gn;\n  t1 = chrono::steady_clock::now();\n  bundleAdjustmentGaussNewton(pts_3d_eigen, pts_2d_eigen, K, pose_gn);\n  t2 = chrono::steady_clock::now();\n  time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n  Eigen::Vector3d t_gn = pose_gn.translation();\n  Eigen::Matrix3d R_gn = pose_gn.so3().unit_quaternion().toRotationMatrix();\n  cout << \"R_gn = \" << endl << R_gn << endl;\n  cout << \"t_gn = \" << endl << t_gn << endl;\n\n  // cout << \"calling bundle adjustment by g2o\" << endl;\n  // Sophus::SE3d pose_g2o;\n  // t1 = chrono::steady_clock::now();\n  // bundleAdjustmentG2O(pts_3d_eigen, pts_2d_eigen, K, pose_g2o);\n  // t2 = chrono::steady_clock::now();\n  // time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  // cout << \"solve pnp by g2o cost time: \" << time_used.count() << \" seconds.\" << endl;\n\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  cout << \"Custom Gauss-Newton\" << endl;\n  Sophus::SE3d pose_gn2(Sophus::SO3d(Eigen::Matrix3d::Identity()), Eigen::Vector3d::Zero());\n  // Sophus::SE3d pose_gn2(Sophus::SO3d(Eigen::Matrix3d::Identity()), Eigen::Vector3d(0.5, -0.1, 0.2));\n  t1 = chrono::steady_clock::now();\n  pose_refinement_gauss_newton(pts_3d_eigen, pts_2d_eigen, K_eigen, pose_gn2);\n  t2 = chrono::steady_clock::now();\n  time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve pnp with custom Gauss-Newton cost time: \" << time_used.count() << \" seconds.\" << endl;\n  \n  Eigen::Vector3d t_gn2 = pose_gn2.translation();\n  Eigen::Matrix3d R_gn2 = pose_gn2.so3().unit_quaternion().toRotationMatrix();\n  cout << \"R_gn2 = \" << endl << R_gn2 << endl;\n  cout << \"t_gn2 = \" << endl << t_gn2 << endl;\n\n  return 0;\n}\n\nvoid pose_refinement_gauss_newton(const VecVector3d& points_3d, const VecVector2d& points_2d, const Eigen::Matrix3d& K, Sophus::SE3d& pose)\n{\n  const int max_iter = 100;\n  double fx = K(0, 0);\n  double fy = K(1, 1);\n  const int n = points_2d.size();\n  double prev_cost = 0.0;\n  for (int it = 0; it < max_iter; ++it)\n  {\n    Eigen::Matrix<double, 6, 6> H = Eigen::Matrix<double, 6, 6>::Zero();\n    Eigen::Matrix<double, 6, 1> b = Eigen::Matrix<double, 6, 1>::Zero();\n    double cost = 0.0;\n    for (int i = 0; i < n; ++i)\n    {\n      Eigen::Matrix<double, 2, 6> J = Eigen::Matrix<double, 2, 6>::Zero();\n      const auto& X = points_3d[i];\n      Eigen::Vector3d x = K * (pose * X);\n      x /= x.z();\n      Eigen::Vector2d err = points_2d[i] - x.head(2);\n      cost += err.squaredNorm();\n      double Z2 = std::pow(X.z(), 2);\n      J(0, 0) = -fx / X.z();\n      J(0, 2) = fx * X.x() / Z2;\n      J(0, 3) = fx * X.x() * X.y() / Z2;\n      J(0, 4) = -fx-fx * std::pow(X.x(), 2) / Z2;\n      J(0, 5) = fx * X.y() / X.z();\n\n      J(1, 1) = -fy / X.z();\n      J(1, 2) = fy * X.y() / Z2;\n      J(1, 3) = fy + fy * std::pow(X.y(), 2) / Z2;\n      J(1, 4) = -fy * X.y() * X.x() / Z2;\n      J(1, 5) = -fy * X.x() / X.z();\n\n      H += J.transpose() * J;\n      b += -J.transpose() * err;\n    }\n\n    std::cout << \"iter \" << it << \": cost = \" << cost << \"\\n\";\n    Eigen::Matrix<double, 6, 1> delta_x = H.inverse() * b;\n    // Eigen::Matrix<double, 6, 1> delta_x = H.ldlt().solve(b);\n\n    if (it > 0 && prev_cost - cost < 1e-5 || delta_x.norm() < 1e-5)\n    {\n      break;\n    }\n\n    // update pose\n    pose = Sophus::SE3d::exp(delta_x) * pose;\n    prev_cost = cost;\n  }\n\n}\n\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\nvoid bundleAdjustmentGaussNewton(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose) {\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  const int iterations = 10;\n  double cost = 0, lastCost = 0;\n  double fx = K.at<double>(0, 0);\n  double fy = K.at<double>(1, 1);\n  double cx = K.at<double>(0, 2);\n  double cy = K.at<double>(1, 2);\n\n  for (int iter = 0; iter < iterations; iter++) {\n    Eigen::Matrix<double, 6, 6> H = Eigen::Matrix<double, 6, 6>::Zero();\n    Vector6d b = Vector6d::Zero();\n\n    cost = 0;\n    // compute cost\n    for (int i = 0; i < points_3d.size(); i++) {\n      Eigen::Vector3d pc = pose * points_3d[i];\n      double inv_z = 1.0 / pc[2];\n      double inv_z2 = inv_z * inv_z;\n      Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx, fy * pc[1] / pc[2] + cy);\n\n      Eigen::Vector2d e = points_2d[i] - proj;\n\n      cost += e.squaredNorm();\n      Eigen::Matrix<double, 2, 6> J;\n      J << -fx * inv_z,\n        0,\n        fx * pc[0] * inv_z2,\n        fx * pc[0] * pc[1] * inv_z2,\n        -fx - fx * pc[0] * pc[0] * inv_z2,\n        fx * pc[1] * inv_z,\n        0,\n        -fy * inv_z,\n        fy * pc[1] * inv_z2,\n        fy + fy * pc[1] * pc[1] * inv_z2,\n        -fy * pc[0] * pc[1] * inv_z2,\n        -fy * pc[0] * inv_z;\n\n      H += J.transpose() * J;\n      b += -J.transpose() * e;\n    }\n\n    Vector6d dx;\n    dx = H.ldlt().solve(b);\n\n    if (isnan(dx[0])) {\n      cout << \"result is nan!\" << endl;\n      break;\n    }\n\n    if (iter > 0 && cost >= lastCost) {\n      // cost increase, update is not good\n      cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n      break;\n    }\n\n    // update your estimation\n    pose = Sophus::SE3d::exp(dx) * pose;\n    lastCost = cost;\n\n    cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << endl;\n    if (dx.norm() < 1e-6) {\n      // converge\n      break;\n    }\n  }\n\n  // cout << \"pose by g-n: \\n\" << pose.matrix() << endl;\n}\n", "meta": {"hexsha": "ef03e7807d39863835505ad79d34496b5ead05ec", "size": 10517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d_gauss_newton.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7/pose_estimation_3d2d_gauss_newton.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/pose_estimation_3d2d_gauss_newton.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.072327044, "max_line_length": 140, "alphanum_fraction": 0.6035941809, "num_tokens": 3647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5859352420016029}}
{"text": "extern \"C\" {\n#include <umfpack.h>\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\n    namespace ublas = boost::numeric::ublas;\n    namespace umf = boost::numeric::bindings::umfpack;\n\n    int 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\t  return 0;\n    }\n", "meta": {"hexsha": "a414d36e13a914653383ba2dc6eaa6d77de22550", "size": 1121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/test_umfpack.cpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/deprecated/test_umfpack.cpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/deprecated/test_umfpack.cpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2972972973, "max_line_length": 80, "alphanum_fraction": 0.5575379126, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5859120779173526}}
{"text": "#include \"solv_plug.hpp\"\r\n#include <Eigen/SparseCholesky>\r\n#include <Eigen/Geometry>\r\n#include <set>\r\n#include \"mesh/meshinfo.hpp\"\r\n#include \"tetelem.hpp\"\r\n\r\n\r\nstruct Triplet      // for Eigen interface\r\n{\r\n    int Row;\r\n    int Col;\r\n    real Value;\r\n\r\n    int row() const { return Row; }\r\n    int col() const { return Col; }\r\n    real value() const { return Value; }\r\n};\r\n\r\nstatic void ApplyBc(const MeshInfo* mesh,\r\n                    const SolvParams& params,\r\n                    SpMat& mat,\r\n                    SpVec& rhs);\r\nstatic std::string SolvStatusToStr(const Eigen::ComputationInfo st);\r\n\r\nbool SolvPlugin::Solve_(std::string& log_buf)\r\n{\r\n    const auto node_lst = solv_info_->Mesh->NodeLst;\r\n    const auto elem_lst = solv_info_->Mesh->ElemLst;\r\n    const auto node_num = solv_info_->Mesh->NodeNum;\r\n    const auto elem_num = solv_info_->Mesh->ElemNum;\r\n\r\n    const auto dof_count = 3 * node_num;\r\n\r\n    TetElem tet_el(log_buf);\r\n    Mat K_loc;\r\n    Mat node_mat = Mat::Zero(4, 3);\r\n\r\n    const size_t K_lst_size = elem_num * 4 * 4 * 3 * 3;\r\n\r\n    std::vector<Triplet> K_lst;\r\n    try\r\n    {\r\n        K_lst.resize(K_lst_size);\r\n    }\r\n    catch (const std::bad_alloc&)\r\n    {\r\n        log_buf = \"Cannot allocate memory for stiffness matrix (\" +\r\n                  std::to_string(K_lst_size * sizeof(Triplet)) + \" bytes required).\";\r\n        return false;\r\n    }\r\n\r\n    for (uint i_el = 0, i_k_el = 0; i_el < elem_num; ++i_el)\r\n    {\r\n        // build local stiffness matrices\r\n\r\n        for (int i_node = 0; i_node < 4; ++i_node)\r\n            for(int i_coord = 0; i_coord < 3; ++i_coord)\r\n                node_mat(i_node, i_coord) = node_lst[3*(elem_lst[4*i_el + i_node] - 1) + i_coord];\r\n\r\n        if(!tet_el.Init(i_el, node_mat, solv_params_->Young, solv_params_->Poisn))\r\n            return false;\r\n\r\n        K_loc = tet_el.BuildStifMat();\r\n        for (int i_node = 0; i_node < 4; ++i_node)\r\n        {\r\n            const int z1 = 3 * (elem_lst[4*i_el + i_node] - 1);\r\n            for (int j_node = 0; j_node < 4; ++j_node)\r\n            {\r\n                const int z2 = 3 * (elem_lst[4*i_el + j_node] - 1);\r\n                for (int i = 0; i < 3; ++i)\r\n                    for (int j = 0; j < 3; ++j)\r\n                    {\r\n                        K_lst[i_k_el].Row = z1 + i;\r\n                        K_lst[i_k_el].Col = z2 + j;\r\n                        K_lst[i_k_el].Value = K_loc(i_node*3 + i, j_node*3 + j);\r\n                        ++i_k_el;\r\n                    }\r\n            }\r\n        }\r\n    }\r\n\r\n    SpMat K(dof_count, dof_count);\r\n    K.setFromTriplets(K_lst.cbegin(), K_lst.cend());\r\n    K_lst.clear();\r\n\r\n    stats_buf += \"Number of DOF: \" + std::to_string(dof_count) + '\\n';\r\n\r\n    SpVec F(dof_count);\r\n\r\n    ApplyBc(solv_info_->Mesh, *solv_params_, K, F);\r\n\r\n    Eigen::SimplicialLDLT<SpMat> solver;\r\n\r\n    solver.compute(K);\r\n    if(auto st = solver.info(); st != Eigen::ComputationInfo::Success)\r\n    {\r\n        log_buf += \"Could not decompose stiffness matrix: \" + SolvStatusToStr(st);\r\n        return false;\r\n    }\r\n\r\n    Vec sol = solver.solve(F);\r\n    if(auto st = solver.info(); st != Eigen::ComputationInfo::Success)\r\n    {\r\n        log_buf += \"Could not solve linear system: \" + SolvStatusToStr(st);\r\n        return false;\r\n    }\r\n\r\n    const auto siz = sol.size();\r\n    for(int i = 0; i < siz; ++i)\r\n        solv_info_->DispLst[i] = sol(i);\r\n\r\n    return true;\r\n}\r\n\r\nvoid ApplyBc(const MeshInfo* mesh,\r\n             const SolvParams& params,\r\n             SpMat& mat,\r\n             SpVec& rhs)\r\n{\r\n    const real big_num = 1.0e+28;\r\n    std::set<MeshInfo::id_t> used_node_lst;\r\n\r\n    for(auto i_face = 0u; i_face < mesh->ElemFaceNum; ++i_face)\r\n    {\r\n        for(const auto& bc: params.BcLst)\r\n        {\r\n            if(bc.first != mesh->ElemFaceMarkerLst[i_face])\r\n                continue;\r\n\r\n            if(bc.second.BcLst.size() == 1 && bc.second.BcLst.front().Tag[0] == 'p')\r\n            {\r\n                const MeshInfo::id_t nodes[] = { mesh->ElemFaceLst[3*i_face + 0] - 1,\r\n                                                 mesh->ElemFaceLst[3*i_face + 1] - 1,\r\n                                                 mesh->ElemFaceLst[3*i_face + 2] - 1 };\r\n                const Vec3 n1_vec(mesh->NodeLst[3*nodes[0]+0], mesh->NodeLst[3*nodes[0]+1], mesh->NodeLst[3*nodes[0]+2]);\r\n                const Vec3 n2_vec(mesh->NodeLst[3*nodes[1]+0], mesh->NodeLst[3*nodes[1]+1], mesh->NodeLst[3*nodes[1]+2]);\r\n                const Vec3 n3_vec(mesh->NodeLst[3*nodes[2]+0], mesh->NodeLst[3*nodes[2]+1], mesh->NodeLst[3*nodes[2]+2]);\r\n                const Vec3 surf_v = (n2_vec - n1_vec).cross(n3_vec - n1_vec);\r\n                const Vec3 pr_vec = (bc.second.BcLst.front().Value/6) * surf_v;\r\n\r\n                for(int i = 0; i < 3; ++i)\r\n                    for(int j = 0; j < 3; ++j)\r\n                    {\r\n                        rhs.coeffRef(3*nodes[i]+j) += pr_vec(j);\r\n                        //used_node_lst.insert(nodes[i]+j);  - do we have to do this???\r\n                    }\r\n            }\r\n            else\r\n            {\r\n                for(int i_n = 0; i_n < 3; ++i_n)\r\n                {\r\n                    const auto node = mesh->ElemFaceLst[3*i_face + i_n] - 1;\r\n                    for(const auto& b: bc.second.BcLst)\r\n                    {\r\n                        for(int i_ax = 0; i_ax < 3; ++i_ax)\r\n                            if(b.Tag[i_ax+1] && !used_node_lst.count(3*node+i_ax))\r\n                            {\r\n                                if(b.Tag[0] == 'u')\r\n                                    mat.coeffRef(3*node+i_ax, 3*node+i_ax) = big_num;\r\n                                rhs.coeffRef(3*node+i_ax) = (b.Tag[0] == 'u' ? big_num : 1.0) * b.Value;\r\n                                used_node_lst.insert(3*node+i_ax);\r\n                            }\r\n                    }\r\n                }\r\n            }\r\n\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nstd::string SolvStatusToStr(const Eigen::ComputationInfo st)\r\n{\r\n    switch (st)\r\n    {\r\n    case Eigen::ComputationInfo::Success:       return \"success\";\r\n    case Eigen::ComputationInfo::InvalidInput:  return \"the inputs are invalid, or the algorithm has been improperly called\";\r\n    case Eigen::ComputationInfo::NoConvergence: return \"iterative procedure did not converge\";\r\n    case Eigen::ComputationInfo::NumericalIssue:return \"the provided data did not satisfy the prerequisites\";\r\n    }\r\n\r\n    return \"\";\r\n}\r\n", "meta": {"hexsha": "dc2c8378a6a42a23111fa744c1f329f35cb04c61", "size": 6446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solv_plug/solver.cpp", "max_stars_repo_name": "master-clown/ofeata", "max_stars_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T13:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T13:51:42.000Z", "max_issues_repo_path": "src/solv_plug/solver.cpp", "max_issues_repo_name": "master-clown/ofeata", "max_issues_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solv_plug/solver.cpp", "max_forks_repo_name": "master-clown/ofeata", "max_forks_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T13:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T13:51:35.000Z", "avg_line_length": 34.8432432432, "max_line_length": 126, "alphanum_fraction": 0.4972075706, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5859120663085505}}
{"text": "#ifndef STAN_MATH_FWD_SCAL_FUN_LOG_FALLING_FACTORIAL_HPP\r\n#define STAN_MATH_FWD_SCAL_FUN_LOG_FALLING_FACTORIAL_HPP\r\n\r\n#include <stan/math/fwd/meta.hpp>\r\n#include <stan/math/fwd/core.hpp>\r\n\r\n#include <stan/math/prim/scal/fun/log_falling_factorial.hpp>\r\n#include <boost/math/special_functions/digamma.hpp>\r\n\r\nnamespace stan {\r\nnamespace math {\r\n\r\ntemplate <typename T>\r\ninline fvar<T> log_falling_factorial(const fvar<T>& x, const fvar<T>& n) {\r\n  using boost::math::digamma;\r\n\r\n  return fvar<T>(log_falling_factorial(x.val_, n.val_),\r\n                 (digamma(x.val_ + 1) - digamma(x.val_ - n.val_ + 1)) * x.d_\r\n                     + digamma(x.val_ - n.val_ + 1) * n.d_);\r\n}\r\n\r\ntemplate <typename T>\r\ninline fvar<T> log_falling_factorial(double x, const fvar<T>& n) {\r\n  using boost::math::digamma;\r\n\r\n  return fvar<T>(log_falling_factorial(x, n.val_),\r\n                 digamma(x - n.val_ + 1) * n.d_);\r\n}\r\n\r\ntemplate <typename T>\r\ninline fvar<T> log_falling_factorial(const fvar<T>& x, double n) {\r\n  using boost::math::digamma;\r\n\r\n  return fvar<T>(log_falling_factorial(x.val_, n),\r\n                 (digamma(x.val_ + 1) - digamma(x.val_ - n + 1)) * x.d_);\r\n}\r\n}  // namespace math\r\n}  // namespace stan\r\n#endif\r\n", "meta": {"hexsha": "a34b447c37cd6090b258ba9e5cfd9f30ad2c9e3b", "size": 1217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/fwd/scal/fun/log_falling_factorial.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/fwd/scal/fun/log_falling_factorial.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/fwd/scal/fun/log_falling_factorial.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": 30.425, "max_line_length": 77, "alphanum_fraction": 0.6540673788, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5859120536816192}}
{"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_MOD_N_INCLUDE\n#define MTL_MOD_N_INCLUDE\n\n#include <iostream>\n#include <boost/operators.hpp>\n#include <cassert>\n\n#include <boost/config/concept_macros.hpp> \n#ifdef __GXX_CONCEPTS__\n#  include <bits/concepts.h>\n#endif\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/is_invertible.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/concepts.hpp>\n#include <boost/numeric/meta_math/is_prime.hpp>\n\nnamespace mtl {\n\ntemplate<typename T, T N>\n//  where std::Integral<T>\nclass mod_n_t \n  : boost::totally_ordered< mod_n_t<T, N> >,\n    boost::arithmetic< mod_n_t<T, N> >\n{\n    // or BOOST_STATIC_ASSERT((IS_INTEGRAL))\n\n    T                 value;\n public:\n    typedef T         value_type;\n    typedef mod_n_t   self;\n\n    static T const modulo= N;\n\n    mod_n_t() : value(0) {}\n\n    explicit mod_n_t(T const& v)\n    {\n\tvalue= v >= 0 ? v%modulo : modulo - -v%modulo; \n    }\n\n    // modulo of negative numbers can be bizarre\n    // better use constructor for T\n    explicit mod_n_t(int v) \n    {\n\tvalue= v >= 0 ? v%modulo : modulo - -v%modulo; \n    }\n\n    // copy constructor\n    mod_n_t(const mod_n_t<T, N>& m): value(m.get()) {}\n  \n    // assignment\n    mod_n_t<T, N>& operator= (const mod_n_t<T, N>& m) \n    {\n\tvalue= m.value; \n\treturn *this; \n    }\n\n    mod_n_t<T, N>& operator= (T const& v)\n    {\n\tvalue= v >= 0 ? v%modulo : modulo - -v%modulo; \n\treturn *this; \n    }\n    \n    // conversion from other moduli must be called explicitly\n    template<T OtherN>\n    mod_n_t<T, N>& convert(const mod_n_t<T, OtherN>& m) \n    {\n\tvalue= m.value >= 0 ? m.value%modulo : modulo - -m.value%modulo; \n\treturn *this; \n    }\n\n    T get() const \n    {\n\treturn value; \n    }\n\n    bool operator==(self const& y) const\n    {\n\tcheck(*this); check(y);\n\treturn this->value == y.value;\n    }\n\n    bool operator<(self const& y) const\n    {\n\tcheck(*this); check(y);\n\treturn this->value < y.value;\n    }\n\n    self& operator+= (self const& y)\n    {\n\tcheck(*this); check(y);\n\tthis->value += y.value;\n\tthis->value %= modulo;\n\treturn *this;\n    }\n\n    self& operator-= (self const& y)\n    {\n\tcheck(*this); check(y);\n\t// add n to avoid negative numbers esp. if T is unsigned\n\tthis->value += modulo;\n\tthis->value -= y.value;\n\tthis->value %= modulo;\n\treturn *this;\n    }\n\n    self& operator*= (self const& y)\n    {\n\tcheck(*this); check(y);\n\tthis->value *= y.value;\n\tthis->value %= modulo;\n\treturn *this;\n    }\n\n    self& operator/= (self const& y);\n    \n};\n\ntemplate<typename T, T N>\ninline void check(const mod_n_t<T, N>& x)\n{\n    assert(x.get() >= 0 && x.get() < N);\n}\n\ntemplate<typename T, T N>\ninline std::ostream& operator<< (std::ostream& stream, const mod_n_t<T, N>& a) \n{\n    check(a);\n    return stream << a.get(); \n}\n\n\n// Extended Euclidian algorithm in vector notation\n    // uu = (u1, u2, u3) := (1, 0, u)\n    // vv = (v1, v2, v3) := (0, 1, v)\n    // while (u3 % v3 != 0) {\n    //   q= u3 / v3\n    //   rr= uu - q * vv\n    //   uu= vv\n    //   vv= rr }\n    // \n    // with u = N and v = y\n    // --> v2 * v mod u == gcd(u, v)\n    // --> v2 * y mod N == 1\n    // --> x * v2 == x / y\n    // v1, u1, and r1 not used\ntemplate<typename T, T N>\ninline mod_n_t<T, N>& mod_n_t<T, N>::operator/= (const mod_n_t<T, N>& y) \n{\n    check(*this); check(y);\n    if (y.get() == 0) throw \"Division by 0\";\n\n    // Goes wrong with unsigned b/c some values will be negative (even if the result isn't)\n    // Something like remove_sign<T>::type would be cute\n    int u= N, v= y.get(), /* u1= 1, */  u2= 0, /* v1= 0, */  v2= 1, q, r, /* r1, */  r2;\n\n    while (u % v != 0) {\n\tq= u / v;\n\n\tr= u % v; /* r1= u1 - q * v1; */ r2= u2 - q * v2;\n\tu= v; /* u1= v1; */ u2= v2;\n\tv= r; /* v1= r1; */ v2= r2;\n    }\n\n    return *this *= mod_n_t<T, N>(v2); \n}\n\ninline int gcd(int u, int v)\n{\n    int r;\n    while ((r= u % v) != 0) {\n\tu= v; v= r;\n    }\n    return v;\n}\n\n} // namespace mtl\n\nnamespace math {\n\n    using mtl::mod_n_t;\n\n    template<typename T, T N>\n    struct identity_t< add< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tmod_t operator() (add<mod_t> const&, mod_t const& v) const\n\t{\n\t    return mod_t(0);\n\t}\n    };\n\n\n    // Reverse definition, a little more efficient if / uses inverse\n    template<typename T, T N>\n    struct inverse_t< add< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tmod_t operator() (add<mod_t> const& op, mod_t const& v) const\n\t{\n\t    return identity(op, v) - v;\n\t}\n    };\n    \n\n    template<typename T, T N>\n    struct is_invertible_t< add< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tbool operator() (add<mod_t> const&, mod_t const& v) const\n\t{ return true; }\n    };\n    \n\n    template<typename T, T N>\n    struct identity_t< mult< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tmod_t operator() (mult<mod_t> const&, mod_t const& v) const\n\t{\n\t    return mod_t(1);\n\t}\n    };\n\n\n    // Reverse definition, a little more efficient if / uses inverse\n    template<typename T, T N>\n    struct inverse_t< mult< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tmod_t operator() (mult<mod_t> const&, mod_t const& v) const\n\t{\n\t    return mod_t(1) / v;\n\t}\n    };\n    \n\n    template<typename T, T N>\n    struct is_invertible_t< mult< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tbool operator() (mult<mod_t> const&, mod_t const& v) const\n\t{\n#           ifdef MTL_TRACE_MOD_N_INVERTIBILITY_DISPATCHING \n                std::cout << \"[slow mod n inversion test] \";\n#           endif\n\t    T value = v.get();\n\t    return value != 0 && mtl::gcd(N, value) == 1;\n\t}\n    };\n    \n\n# ifdef __GXX_CONCEPTS__\n\n    // With Concept we can provide a faster invertibility test for prime numbers:\n    //  only 0 is not invertible and gcd doesn't need to be called\n\n    template<typename T, T N>\n        where meta_math::Prime<N>\n    struct is_invertible_t< mult< mod_n_t<T, N> >, mod_n_t<T, N> >\n    {\n\ttypedef mod_n_t<T, N> mod_t;\n\tbool operator() (mult<mod_t> const&, mod_t const& v) const\n\t{\n#           ifdef MTL_TRACE_MOD_N_INVERTIBILITY_DISPATCHING \n                std::cout << \"[fast mod n inversion test] \";\n#           endif\n \t    return v.get() != 0;\n\t}\n    };\n\n\n\n\n// Concept mapping\n// All modulo sets are commutative rings with identity\n// but only if N is prime it is also a field\n// Due to some mapping nesting trouble we define normally derived maps\n\n\ntemplate <typename T, T N>\nconcept_map CommutativeRingWithIdentity< mod_n_t<T, N> > \n{\n    // Why do we need the typedefs???\n    \n    typedef mod_n_t<T, N>& plus_assign_result_type;\n    typedef mod_n_t<T, N>  addition_result_type;\n    typedef mod_n_t<T, N>  unary_result_type;\n    typedef mod_n_t<T, N>& minus_assign_result_type;\n    typedef mod_n_t<T, N>  subtraction_result_type;\n\n    typedef mod_n_t<T, N>& mult_assign_result_type;\n    typedef mod_n_t<T, N>  mult_result_type;\n    typedef mod_n_t<T, N>& divide_assign_result_type;\n    typedef mod_n_t<T, N>  division_result_type;\n\n    typedef mod_n_t<T, N>  inverse_result_type;\n    typedef mod_n_t<T, N>  identity_result_type;\n    typedef bool           is_invertible_result_type;\n}\n\ntemplate <typename T, T N>\nconcept_map MultiplicativePartiallyInvertibleMonoid< mod_n_t<T, N> >\n{\n    // Why do we need the typedefs???\n\n    typedef mod_n_t<T, N>& mult_assign_result_type;\n    typedef mod_n_t<T, N>  mult_result_type;\n    typedef mod_n_t<T, N>& divide_assign_result_type;\n    typedef mod_n_t<T, N>  division_result_type;\n\n    typedef mod_n_t<T, N>  inverse_result_type;\n    typedef mod_n_t<T, N>  identity_result_type;\n    typedef bool           is_invertible_result_type;\n}\n\n\ntemplate <typename T, T N>\n    where meta_math::Prime<N>\nconcept_map Field< mod_n_t<T, N> >\n{\n    // Why do we need the typedefs???\n\n    typedef mod_n_t<T, N>& plus_assign_result_type;\n    typedef mod_n_t<T, N>  addition_result_type;\n    typedef mod_n_t<T, N>  unary_result_type;\n    typedef mod_n_t<T, N>& minus_assign_result_type;\n    typedef mod_n_t<T, N>  subtraction_result_type;\n\n    typedef mod_n_t<T, N>& mult_assign_result_type;\n    typedef mod_n_t<T, N>  mult_result_type;\n    typedef mod_n_t<T, N>& divide_assign_result_type;\n    typedef mod_n_t<T, N>  division_result_type;\n\n    typedef mod_n_t<T, N>  inverse_result_type;\n    typedef mod_n_t<T, N>  identity_result_type;\n    typedef bool           is_invertible_result_type;\n}\n\n# endif // __GXX_CONCEPTS__\n\n} // namespace math\n\n\n#endif // MTL_MOD_N_INCLUDE\n", "meta": {"hexsha": "860377b9b343d9b0370a70db4a955c97589d0c42", "size": 9009, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/mod_n.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/mod_n.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/mod_n.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": 24.9556786704, "max_line_length": 94, "alphanum_fraction": 0.621045621, "num_tokens": 2743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5858755784785862}}
{"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#include <tbb/tbb.h>\n\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace tbb;\n\n\ndouble *J_index, *JT_index, *J_value, *JT_value, *JTJ_info, *pu, *wu, *bu, *max_iter, *step_size;\ndouble *b, *lambda, *pi, *Jx_in, *p_mod, *dummy;\n\nint J_row;\nint J_col;\nint row_spy;\nint col_spy;\nint max_it;\ndouble step;\n\nclass spmv_mul_add\n{\n\npublic:\n\tspmv_mul_add(double* A_index, double* A_value, double* input, double* addition, double* output, int spy)\n\t{\n\n\t\tthis->A_index = A_index;\t\n\t\tthis->A_value = A_value;\t\n\t\tthis->input = input;\n        this->addition = addition;\n\t\tthis->output = output;\n\t\tthis->spy = spy;\n\n\t};\n\n\t~spmv_mul_add() {};\n\n\tvoid operator() (const blocked_range<int>& r) const\n\t{\n\t\tfor (int i = r.begin(); i != r.end(); i++)\n\t\t{\n\t\t\toutput[i] = 0;\n\n\t\t\tfor (int j = 0; j < spy; j++)\n\t\t\t{\n\t\t\t\tint index = i * spy + j;\n                \n                if(A_index[index] >= 0)\n                {\n                    int idx = A_index[index];\n                    output[i] += A_value[index] * input[idx];\n                }\t\n\t\t\t} \n            \n            output[i] += addition[i];\n\t\t}\n\t};\n\n\tdouble* A_index;\n\tdouble* A_value;\n\tdouble* input;\n    double* addition;\n\tdouble* output;\n\tint spy;\n\n};\n\n\nclass jacobi_update\n{\n\npublic:\n\tjacobi_update(double* dof, double* update, double* divisor, double alpha)\n\t{\n\t\tthis->dof = dof;\t\n\t\tthis->update = update;\t\n\t\tthis->divisor = divisor;\n        this->alpha = alpha;\n\t};\n\n\t~jacobi_update() {};\n\n\tvoid operator() (const blocked_range<int>& r) const\n\t{\n\t\tfor (int i = r.begin(); i != r.end(); i++)\n\t\t{\n            dof[i] = fmax(dof[i] - alpha * update[i] / divisor[i], 0.0);\n\t\t\t//dof[i] = dof[i] - alpha * update[i] / divisor[i];\n\t\t}\n\t};\n\n\tdouble* dof;\n\tdouble* update;\n\tdouble* divisor;\n    double alpha;\n\n};\n\n\nclass set_zero\n{\n\npublic:\n\tset_zero(double* data)\n\t{\n\t\tthis->data = data;\t\n\t};\n\n\t~set_zero() {};\n\n\tvoid operator() (const blocked_range<int>& r) const\n\t{\n\t\tfor (int i = r.begin(); i != r.end(); i++)\n\t\t{\n\t\t\tdata[i] = 0;\n\t\t}\n\t};\n\n\tdouble* data;\n\n};\n\n\ndouble get_Fischer_Burmeister(double *x, double *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 damped_Jacobi()\n{\n   \n    task_scheduler_init init(8);\n    \n    parallel_for(blocked_range<int>(0, J_col), set_zero(lambda));\n    \n    parallel_for(blocked_range<int>(0, J_row), set_zero(dummy));\n    \n    parallel_for(blocked_range<int>(0, J_col), spmv_mul_add(JT_index, JT_value, pu, bu, b, col_spy));\n    \n    double pre_FB, post_FB;\n    \n    parallel_for(blocked_range<int>(0, J_row), spmv_mul_add(J_index, J_value, lambda, dummy, Jx_in, row_spy));\n    \n    parallel_for(blocked_range<int>(0, J_col), spmv_mul_add(JT_index, JT_value, Jx_in, b, pi, col_spy));\n    \n    post_FB = get_Fischer_Burmeister(lambda, pi, J_col);\n    \n    int iteration = -1;\n    \n    for(int outer = 0; outer < max_it; outer++)\n    {\n        iteration = outer;\n        pre_FB = post_FB;\n        \n        parallel_for(blocked_range<int>(0, J_col), jacobi_update(lambda, pi, wu, step));\n        \n        ///////////////////////////////////////////////////////////////////////////////\n        \n        parallel_for(blocked_range<int>(0, J_row), spmv_mul_add(J_index, J_value, lambda, dummy, Jx_in, row_spy));\n        \n        parallel_for(blocked_range<int>(0, J_col), spmv_mul_add(JT_index, JT_value, Jx_in, b, pi, col_spy));\n        \n        ///////////////////////////////////////////////////////////////////////////////\n        \n        post_FB = get_Fischer_Burmeister(lambda, pi, J_col);\n        \n        if(abs(pre_FB) < 1e-6)\n\t\t{\n\t\t\tbreak;\n\t\t}\n        \n        if((pre_FB - post_FB) / pre_FB < 1e-3)\n        {\n            break;\n        }\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    }\n    \n    //mexPrintf(\"%d\\n\", iteration);\n    \n    parallel_for(blocked_range<int>(0, J_row), spmv_mul_add(J_index, J_value, lambda, dummy, p_mod, row_spy));\n  \n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    mxArray *output_mex;\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    J_row = JTJ_info[0];\n    J_col = JTJ_info[2];\n    row_spy = JTJ_info[1];\n    col_spy = JTJ_info[3];\n    max_it = max_iter[0];\n    step = step_size[0];\n    \n    b = (double*)malloc(J_col * sizeof(double));\n    lambda = (double*)malloc(J_col * sizeof(double));\n    pi = (double*)malloc(J_col * sizeof(double));\n    Jx_in = (double*)malloc(J_row * sizeof(double));\n    dummy = (double*)malloc(J_row * sizeof(double));\n    \n    output_mex = plhs[0] = mxCreateDoubleMatrix(J_row, 1, mxREAL);   \n    p_mod = mxGetPr(output_mex);\n    \n    damped_Jacobi();\n       \n    free(b);\n    free(lambda);\n    free(pi);\n    free(Jx_in);\n    free(dummy);\n   \n    return;\n    \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "99e3fce8215e4ddbb860efafb44cffacd0694961", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/lcp_solve_tbb_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_tbb_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_tbb_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.1194029851, "max_line_length": 114, "alphanum_fraction": 0.5465504451, "num_tokens": 1602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5858755784785862}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n\n#include <Eigen/Core>\n\n#include \"../libfovis/absolute_orientation_horn.hpp\"\n\nusing namespace std;\n\nstatic int\nrand_int_range(int min, int max)\n{\n  return rand() % (max - min) + min;\n}\n\nstatic double \nrand_double_range(double min, double max)\n{\n  double v = rand() / (double)RAND_MAX;\n  return v * (max - min) + min;\n}\n\nvoid \nrpy_to_quat (const double rpy[3], double q[4])\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  q[0] = cos_r2 * cos_p2 * cos_y2 + sin_r2 * sin_p2 * sin_y2;\n  q[1] = sin_r2 * cos_p2 * cos_y2 - cos_r2 * sin_p2 * sin_y2;\n  q[2] = cos_r2 * sin_p2 * cos_y2 + sin_r2 * cos_p2 * sin_y2;\n  q[3] = cos_r2 * cos_p2 * sin_y2 - sin_r2 * sin_p2 * cos_y2;\n}\n\nint main(int argc, char** argv)\n{\n  int num_trials = 1000;\n\n  for(int trial=0; trial<num_trials; trial++) {\n\n    // generate a random set of points\n    int num_points = rand_int_range(5, 1000);\n\n    Eigen::Matrix3Xd points(3, num_points);\n\n    for(int col=0; col<num_points; col++) {\n      points(0, col) = rand_double_range(-10, 10);\n      points(1, col) = rand_double_range(-10, 10);\n      points(2, col) = rand_double_range(-10, 10);\n    }\n\n    // generate a random transformation\n    Eigen::Vector3d translation(rand_double_range(-10, 10),\n        rand_double_range(-10, 10),\n        rand_double_range(-10, 10));\n\n    double rpy[3] = {\n      rand_double_range(-M_PI, M_PI),\n      rand_double_range(-M_PI, M_PI),\n      rand_double_range(-M_PI, M_PI) };\n    double rot_quat[4];\n    rpy_to_quat(rpy, rot_quat);\n\n    Eigen::Quaterniond rotation(rot_quat[0], rot_quat[1], rot_quat[2], rot_quat[3]);\n\n    Eigen::Isometry3d trans;\n    trans.setIdentity();\n    trans.translate(translation);\n    trans.rotate(rotation);\n\n    // apply transformation to original random point set\n    Eigen::Matrix3Xd transformed = trans * points;\n\n    Eigen::Isometry3d estimated_transform;\n    absolute_orientation_horn(points, transformed, &estimated_transform);\n\n    // reproject points using estimated transformation\n    Eigen::Matrix3Xd reprojected = estimated_transform * points;\n\n    // compute reprojection error\n    Eigen::Matrix3Xd reproject_err = reprojected - transformed;\n\n    Eigen::Vector3d mean_err = reproject_err.rowwise().sum() / num_points;\n    printf(\"%4d (%4d): mean reprojection error: %6.3f, %6.3f, %6.3f\\n\", trial, num_points, mean_err(0), mean_err(1), mean_err(2));\n    if(fabs(mean_err(0)) > 1e-9 || fabs(mean_err(1)) > 1e-9 || fabs(mean_err(1)) > 1e-9) {\n      fprintf(stderr, \"FAIL!\\n\");\n      exit(1);\n    }\n  }\n\n  fprintf(stderr, \"OK\\n\");\n  return 0;\n}\n", "meta": {"hexsha": "fb06a5b11e6a88adcb3a1dd792df8d83f4ead657", "size": 2878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/testers/absolute_orientation_horn_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/absolute_orientation_horn_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/absolute_orientation_horn_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": 27.4095238095, "max_line_length": 130, "alphanum_fraction": 0.6567060459, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5858755670016301}}
{"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 triangular lattice Ising model\n\n// reference: J. Stephenson, J. of Math. Phys. 11, 420 (1970)\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, 1>(beta)) {\n    using std::exp;\n    auto beta_fvar = boost::math::differentiation::make_fvar<T, 1>(beta);\n    auto za = exp(-2 * beta_fvar * Ja_);\n    auto zb = exp(-2 * beta_fvar * Jb_);\n    auto zc = exp(-2 * 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 triangular(T Ja, T Jb, T Jc) {\n  if (Ja * Jb * Jc <= 0) throw(std::invalid_argument(\"Ja * Jb * Jc should be positive\"));\n  auto result = standards::newton_1d(func<T>(Ja, Jb, Jc), 1 / (2 * (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": "1fa3fe9b819f83168c5584b99f66d7a298c1753c", "size": 1801, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/tc/triangular.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/triangular.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/triangular.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": 30.5254237288, "max_line_length": 98, "alphanum_fraction": 0.6785119378, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.585821511767612}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <vector>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NMF\n{\n\npublic:\n  // pass iteration number; returns true if able to continue (i.e. not\n  // cancelled)\n  using ProgressCallback = std::function<bool(index)>;\n\n  static void estimate(const RealMatrixView W, const RealMatrixView H,\n                       index idx, RealMatrixView V)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n\n    MatrixXd W1 = asEigen<Matrix>(W).transpose();\n    MatrixXd H1 = asEigen<Matrix>(H).transpose();\n    MatrixXd result = (W1.col(idx) * H1.row(idx)).transpose();\n    V <<= asFluid(result);\n  }\n\n  // processFrame computes activations of a dictionary W in a given frame\n  void processFrame(const RealVectorView x, const RealMatrixView W0,\n                    RealVectorView out, index nIterations = 10,\n                    RealVectorView v = RealVectorView(nullptr, 0, 0))\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    index    rank = W0.extent(0);\n    MatrixXd W = asEigen<Matrix>(W0).transpose();\n    VectorXd h =\n        MatrixXd::Random(rank, 1) * 0.5 + MatrixXd::Constant(rank, 1, 0.5);\n    VectorXd v0 = asEigen<Matrix>(x);\n    W = W.array().max(epsilon).matrix();\n    h = h.array().max(epsilon).matrix();\n    v0 = v0.array().max(epsilon).matrix();\n\n    MatrixXd WT = W.transpose();\n    W.colwise().normalize();\n    VectorXd ones = VectorXd::Ones(x.extent(0));\n    while (nIterations--)\n    {\n      ArrayXd  v1 = (W * h).array().max(epsilon);\n      ArrayXXd hNum = (WT * (v0.array() / v1).matrix()).array();\n      ArrayXXd hDen = (WT * ones).array();\n      h = (h.array() * hNum / hDen.max(epsilon)).matrix();\n      // VectorXd r = W * h;\n      // double divergence = (v.cwiseProduct(v.cwiseQuotient(r)) - v + r).sum();\n      // std::cout<<\"Divergence \"<<divergence<<std::endl;\n    }\n    out <<= asFluid(h);\n    if (v.extent(0) > 0)\n    {\n      ArrayXd v2 = (W * h).array();\n      v <<= asFluid(v2);\n    }\n  }\n\n  void process(const RealMatrixView X, RealMatrixView W1, RealMatrixView H1,\n               RealMatrixView V1, index rank, index nIterations, bool updateW,\n               bool           updateH = false,\n               RealMatrixView W0 = RealMatrixView(nullptr, 0, 0, 0),\n               RealMatrixView H0 = RealMatrixView(nullptr, 0, 0, 0))\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    index    nFrames = X.extent(0);\n    index    nBins = X.extent(1);\n    MatrixXd W;\n    if (W0.extent(0) == 0 && W0.extent(1) == 0)\n    {\n      W = MatrixXd::Random(nBins, rank) * 0.5 +\n          MatrixXd::Constant(nBins, rank, 0.5);\n    }\n    else\n    {\n      assert(W0.extent(0) == rank);\n      assert(W0.extent(1) == nBins);\n      W = asEigen<Matrix>(W0).transpose();\n    }\n    MatrixXd H;\n    if (H0.extent(0) == 0 && H0.extent(1) == 0)\n    {\n      H = MatrixXd::Random(rank, nFrames) * 0.5 +\n          MatrixXd::Constant(rank, nFrames, 0.5);\n    }\n    else\n    {\n      assert(H0.extent(0) == nFrames);\n      assert(H0.extent(1) == rank);\n      H = asEigen<Matrix>(H0).transpose();\n    }\n    MatrixXd V = asEigen<Matrix>(X).transpose();\n    multiplicativeUpdates(V, W, H, nIterations, updateW, updateH);\n    MatrixXd VT = V.transpose();\n    MatrixXd WT = W.transpose();\n    MatrixXd HT = H.transpose();\n\n    V1 <<= asFluid(VT);\n    W1 <<= asFluid(WT);\n    H1 <<= asFluid(HT);\n  }\n\n  void addProgressCallback(ProgressCallback&& callback)\n  {\n    mCallbacks.emplace_back(std::move(callback));\n  }\n\nprivate:\n  using MatrixXd = Eigen::MatrixXd;\n\n  void multiplicativeUpdates(Eigen::Ref<MatrixXd> V, Eigen::Ref<MatrixXd> W,\n                             Eigen::Ref<MatrixXd> H, index nIterations,\n                             bool updateW, bool updateH)\n  {\n    using namespace Eigen;\n    MatrixXd ones = MatrixXd::Ones(V.rows(), V.cols());\n    H = H.array().max(epsilon).matrix();\n    W = W.array().max(epsilon).matrix();\n    W.colwise().normalize();\n    H.rowwise().normalize();\n    for (auto i = 0; i < nIterations; ++i)\n    {\n      if (updateW)\n      {\n        ArrayXXd V1 = (W * H).array().max(epsilon);\n        ArrayXXd wnum = ((V.array() / V1).matrix() * H.transpose()).array();\n        ArrayXXd wden = (ones * H.transpose()).array();\n        W = (W.array() * wnum / wden.max(epsilon)).matrix();\n        if (W.maxCoeff() > epsilon) W.colwise().normalize();\n        assert(W.allFinite());\n      }\n      ArrayXXd V2 = (W * H).array().max(epsilon);\n      if (updateH)\n      {\n        ArrayXXd hnum = (W.transpose() * (V.array() / V2).matrix()).array();\n        ArrayXXd hden = (W.transpose() * ones).array();\n        H = (H.array() * hnum / hden.max(epsilon)).matrix();\n        assert(H.allFinite());\n      }\n      MatrixXd R = W * H;\n      R = R.cwiseMax(epsilon);\n      for (auto& cb : mCallbacks)\n        if (!cb(i + 1)) return;\n      // double divergence = (V.cwiseProduct(V.cwiseQuotient(R)) - V + R).sum();\n      // divergenceCurve.push_back(divergence);\n      // divergenceCurve(mIterations);\n      // std::cout << \"Divergence \" << divergence << \"\\n\";\n    }\n    V = W * H;\n  }\n\n  std::vector<ProgressCallback> mCallbacks;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "98df683e37c3869d8b9b1ca38219d617086976fc", "size": 5719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NMF.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/NMF.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/NMF.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": 32.1292134831, "max_line_length": 80, "alphanum_fraction": 0.5936352509, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5857966244974512}}
{"text": "\n// Local private PANACEA includes\n#include \"matrix_eigen.hpp\"\n\n// Third party includes\n#include <Eigen/Dense>\n\n// Standard includes\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <memory>\n\nnamespace panacea {\n\nMatrixEigen::MatrixEigen() { matrix_ = std::make_unique<Eigen::MatrixXd>(); }\n\nconst MatrixType MatrixEigen::type() const { return MatrixType::Eigen; }\n\ndouble MatrixEigen::getDeterminant() const {\n  assert(matrix_->rows() > 0 || matrix_->cols() > 0);\n  return matrix_->determinant();\n}\n\nbool MatrixEigen::isZero(const double threshold) const noexcept {\n  assert(threshold > 0.0);\n  // Because it is symmetric only need to check one half\n  for (int i = 0; i < matrix_->rows(); ++i) {\n    for (int j = i; j < matrix_->cols(); ++j) {\n      if (std::fabs(matrix_->operator()(i, j)) > threshold)\n        return false;\n    }\n  }\n  return true;\n}\n\nvoid MatrixEigen::resize(const int rows, const int cols) {\n  assert(rows >= 0);\n  assert(cols >= 0);\n  matrix_->resize(rows, cols);\n}\n\nMatrixEigen &MatrixEigen::operator=(const MatrixEigen &mat) {\n  this->resize(mat.rows(), mat.cols());\n  for (int row = 0; row < mat.rows(); ++row) {\n    for (int col = 0; col < mat.cols(); ++col) {\n      this->operator()(row, col) = mat(row, col);\n    }\n  }\n  return *this;\n}\n\nMatrixEigen &MatrixEigen::operator=(const Matrix &mat) {\n  this->resize(mat.rows(), mat.cols());\n  for (int row = 0; row < mat.rows(); ++row) {\n    for (int col = 0; col < mat.cols(); ++col) {\n      this->operator()(row, col) = mat(row, col);\n    }\n  }\n  return *this;\n}\n\ndouble &MatrixEigen::operator()(const int row, const int col) {\n  assert(row >= 0);\n  assert(col >= 0);\n  assert(row < matrix_->rows());\n  assert(col < matrix_->cols());\n  return (*matrix_)(row, col);\n}\n\ndouble MatrixEigen::operator()(const int row, const int col) const {\n  assert(row >= 0);\n  assert(col >= 0);\n  assert(row < matrix_->rows());\n  assert(col < matrix_->cols());\n  return (*matrix_)(row, col);\n}\n\nvoid MatrixEigen::makeIdentity() {\n  for (int row = 0; row < matrix_->rows(); ++row) {\n    this->operator()(row, row) = 1.0;\n    for (int col = row + 1; col < matrix_->cols(); ++col) {\n      this->operator()(row, col) = 0.0;\n      this->operator()(col, row) = 0.0;\n    }\n  }\n}\n\nvoid MatrixEigen::setZero() { matrix_->setZero(); }\n\nint MatrixEigen::rows() const { return matrix_->rows(); }\n\nint MatrixEigen::cols() const { return matrix_->cols(); }\n\nvoid MatrixEigen::print() const { std::cout << *matrix_ << std::endl; }\n\nEigen::MatrixXd MatrixEigen::pseudoInverse() const {\n  return matrix_->completeOrthogonalDecomposition().pseudoInverse();\n}\n\nvoid pseudoInverse(Matrix &return_mat, const MatrixEigen &mat) {\n  assert(return_mat.rows() == mat.rows());\n  assert(return_mat.cols() == mat.cols());\n\n  auto temp_mat = mat.pseudoInverse();\n  for (int row = 0; row < temp_mat.rows(); ++row) {\n    for (int col = 0; col < temp_mat.cols(); ++col) {\n      return_mat(row, col) = temp_mat(row, col);\n    }\n  }\n}\n} // namespace panacea\n", "meta": {"hexsha": "21eb3349f12d50810543b54cefb877d30969062e", "size": 2996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libpanacea/matrix/matrix_eigen.cpp", "max_stars_repo_name": "lanl/PANACEA", "max_stars_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libpanacea/matrix/matrix_eigen.cpp", "max_issues_repo_name": "lanl/PANACEA", "max_issues_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libpanacea/matrix/matrix_eigen.cpp", "max_forks_repo_name": "lanl/PANACEA", "max_forks_repo_head_hexsha": "9779bdb6dcc3be41ea7b286ae55a21bb269e0339", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5132743363, "max_line_length": 77, "alphanum_fraction": 0.6261682243, "num_tokens": 845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5857410086768308}}
{"text": "// Glauber model\n// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n// MIT License\n\n#include \"nucleus.h\"\n\n#include <cmath>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <utility>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"random.h\"\n\nnamespace glauber {\n\nnamespace {\n\n// Correct Woods-Saxon surface thickness parameter (a) for finite Gaussian\n// nucleon width (w):\n//\n//    a_corrected^2 = a^2 - c^2*w*2\n//\n// where c is a universal constant independent of a and w.\n//\n// See https://gist.github.com/jbernhard/60b3ab9662a4737658d8.\ndouble correct_a(double a, double w) {\n  constexpr auto c = 0.61;  // correction coefficient\n  constexpr auto a_min = 0.01;  // min. value (prevent div. by zero, etc.)\n  return std::sqrt(std::fmax(a*a - c*c*w*w, a_min*a_min));\n}\n\n}  // unnamed namespace\n\nNucleusPtr Nucleus::create(const std::string& species, double nucleon_width) {\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       62, 4.20, correct_a(0.596, nucleon_width)\n    }};\n  else if (species == \"Cu2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n       62, 4.20, correct_a(0.596, nucleon_width), 0.162, -0.006\n    }};\n  else if (species == \"Au\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      197, 6.38, correct_a(0.535, nucleon_width)\n    }};\n  else if (species == \"Au2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      197, 6.38, correct_a(0.535, nucleon_width), -0.131, -0.031\n    }};\n  else if (species == \"Pb\")\n    return NucleusPtr{new WoodsSaxonNucleus{\n      208, 6.62, correct_a(0.546, nucleon_width)\n    }};\n  else if (species == \"U\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.81, correct_a(0.600, nucleon_width), 0.280, 0.093\n    }};\n  else if (species == \"U2\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.86, correct_a(0.420, nucleon_width), 0.265, 0.000\n    }};\n  else if (species == \"U3\")\n    return NucleusPtr{new DeformedWoodsSaxonNucleus{\n      238, 6.67, correct_a(0.440, nucleon_width), 0.280, 0.093\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(Nucleon& nucleon, double x, double y) {\n  nucleon.set_position(x + offset_, y);\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.);\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 transverse 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\n  // Place the first nucleon at the sampled coordinates (x, y).\n  set_nucleon_position(*begin(), x, y);\n  // Place the second nucleon opposite to the first, at (-x, -y).\n  set_nucleon_position(*std::next(begin()), -x, -y);\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(std::size_t A, double R, double a)\n    : Nucleus(A),\n      R_(R),\n      a_(a),\n      woods_saxon_dist_(1000, 0., R + 10.*a,\n        [R, a](double r) { return 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 uncorrelated Woods-Saxon nucleon positions.\nvoid WoodsSaxonNucleus::sample_nucleons_impl() {\n  for (auto&& nucleon : *this) {\n    // Sample spherical radius from Woods-Saxon distribution.\n    auto r = woods_saxon_dist_(random::engine);\n\n    // Sample isotropic spherical angles.\n    auto cos_theta = random::cos_theta<double>();\n    auto phi = random::phi<double>();\n\n    // Convert to transverse 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\n    set_nucleon_position(nucleon, x, y);\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)\n    : Nucleus(A),\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 uncorrelated 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  for (auto&& nucleon : *this) {\n    // Sample (r, theta) using a standard rejection method.\n    // Remember to include the phase-space factors.\n    double r, cos_theta;\n    do {\n      r = rmax_ * std::cbrt(random::canonical<double>());\n      cos_theta = random::cos_theta<double>();\n    } while (random::canonical<double>() > deformed_woods_saxon_dist(r, cos_theta));\n\n    // Sample azimuthal angle.\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    // 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\n    set_nucleon_position(nucleon, x_rot, y_rot);\n  }\n}\n\n}  // namespace glauber\n", "meta": {"hexsha": "55744416b788b0dc6cda234d05c7d2753b38979d", "size": 9670, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/nucleus.cxx", "max_stars_repo_name": "jbernhard/glauber-model", "max_stars_repo_head_hexsha": "1bb1aac16d8faec75dc0b310cae426828f1c9c80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-04T11:49:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T08:15:32.000Z", "max_issues_repo_path": "src/nucleus.cxx", "max_issues_repo_name": "jbernhard/glauber-model", "max_issues_repo_head_hexsha": "1bb1aac16d8faec75dc0b310cae426828f1c9c80", "max_issues_repo_licenses": ["MIT"], "max_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": "jbernhard/glauber-model", "max_forks_repo_head_hexsha": "1bb1aac16d8faec75dc0b310cae426828f1c9c80", "max_forks_repo_licenses": ["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.6594982079, "max_line_length": 84, "alphanum_fraction": 0.6737331954, "num_tokens": 2871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5857409955441354}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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//  History:\r\n//  XZ wrote the original of this file as part of the Google\r\n//  Summer of Code 2006.  JM modified it to fit into the\r\n//  Boost.Math conceptual framework better, and to correctly\r\n//  handle the p < 0 case.\r\n//\r\n\r\n#ifndef BOOST_MATH_ELLINT_RJ_HPP\r\n#define BOOST_MATH_ELLINT_RJ_HPP\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/ellint_rc.hpp>\r\n\r\n// Carlson's elliptic integral of the third kind\r\n// R_J(x, y, z, p) = 1.5 * \\int_{0}^{\\infty} (t+p)^{-1} [(t+x)(t+y)(t+z)]^{-1/2} dt\r\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\r\n\r\nnamespace boost { namespace math { namespace detail{\r\n\r\ntemplate <typename T, typename Policy>\r\nT ellint_rj_imp(T x, T y, T z, T p, const Policy& pol)\r\n{\r\n    T value, u, lambda, alpha, beta, sigma, factor, tolerance;\r\n    T X, Y, Z, P, EA, EB, EC, E2, E3, S1, S2, S3;\r\n    unsigned long k;\r\n\r\n    BOOST_MATH_STD_USING\r\n    using namespace boost::math::tools;\r\n\r\n    static const char* function = \"boost::math::ellint_rj<%1%>(%1%,%1%,%1%)\";\r\n\r\n    if (x < 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument x must be non-negative, but got x = %1%\", x, pol);\r\n    }\r\n    if(y < 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument y must be non-negative, but got y = %1%\", y, pol);\r\n    }\r\n    if(z < 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument z must be non-negative, but got z = %1%\", z, pol);\r\n    }\r\n    if(p == 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument p must not be zero, but got p = %1%\", p, pol);\r\n    }\r\n    if (x + y == 0 || y + z == 0 || z + x == 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"At most one argument can be zero, \"\r\n            \"only possible result is %1%.\", std::numeric_limits<T>::quiet_NaN(), pol);\r\n    }\r\n\r\n    // error scales as the 6th power of tolerance\r\n    tolerance = pow(T(1) * tools::epsilon<T>() / 3, T(1) / 6);\r\n\r\n    // for p < 0, the integral is singular, return Cauchy principal value\r\n    if (p < 0)\r\n    {\r\n       //\r\n       // We must ensure that (z - y) * (y - x) is positive.\r\n       // Since the integral is symmetrical in x, y and z\r\n       // we can just permute the values:\r\n       //\r\n       if(x > y)\r\n          std::swap(x, y);\r\n       if(y > z)\r\n          std::swap(y, z);\r\n       if(x > y)\r\n          std::swap(x, y);\r\n\r\n       T q = -p;\r\n       T pmy = (z - y) * (y - x) / (y + q);  // p - y\r\n\r\n       BOOST_ASSERT(pmy >= 0);\r\n\r\n       T p = pmy + y;\r\n       value = boost::math::ellint_rj(x, y, z, p, pol);\r\n       value *= pmy;\r\n       value -= 3 * boost::math::ellint_rf(x, y, z, pol);\r\n       value += 3 * sqrt((x * y * z) / (x * z + p * q)) * boost::math::ellint_rc(x * z + p * q, p * q, pol);\r\n       value /= (y + q);\r\n       return value;\r\n    }\r\n\r\n    // duplication\r\n    sigma = 0;\r\n    factor = 1;\r\n    k = 1;\r\n    do\r\n    {\r\n        u = (x + y + z + p + p) / 5;\r\n        X = (u - x) / u;\r\n        Y = (u - y) / u;\r\n        Z = (u - z) / u;\r\n        P = (u - p) / u;\r\n        \r\n        if ((tools::max)(abs(X), abs(Y), abs(Z), abs(P)) < tolerance) \r\n           break;\r\n\r\n        T sx = sqrt(x);\r\n        T sy = sqrt(y);\r\n        T sz = sqrt(z);\r\n        \r\n        lambda = sy * (sx + sz) + sz * sx;\r\n        alpha = p * (sx + sy + sz) + sx * sy * sz;\r\n        alpha *= alpha;\r\n        beta = p * (p + lambda) * (p + lambda);\r\n        sigma += factor * boost::math::ellint_rc(alpha, beta, pol);\r\n        factor /= 4;\r\n        x = (x + lambda) / 4;\r\n        y = (y + lambda) / 4;\r\n        z = (z + lambda) / 4;\r\n        p = (p + lambda) / 4;\r\n        ++k;\r\n    }\r\n    while(k < policies::get_max_series_iterations<Policy>());\r\n\r\n    // Check to see if we gave up too soon:\r\n    policies::check_series_iterations(function, k, pol);\r\n\r\n    // Taylor series expansion to the 5th order\r\n    EA = X * Y + Y * Z + Z * X;\r\n    EB = X * Y * Z;\r\n    EC = P * P;\r\n    E2 = EA - 3 * EC;\r\n    E3 = EB + 2 * P * (EA - EC);\r\n    S1 = 1 + E2 * (E2 * T(9) / 88 - E3 * T(9) / 52 - T(3) / 14);\r\n    S2 = EB * (T(1) / 6 + P * (T(-6) / 22 + P * T(3) / 26));\r\n    S3 = P * ((EA - EC) / 3 - P * EA * T(3) / 22);\r\n    value = 3 * sigma + factor * (S1 + S2 + S3) / (u * sqrt(u));\r\n\r\n    return value;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class T3, class T4, class Policy>\r\ninline typename tools::promote_args<T1, T2, T3, T4>::type \r\n   ellint_rj(T1 x, T2 y, T3 z, T4 p, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T1, T2, T3, T4>::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>(\r\n      detail::ellint_rj_imp(\r\n         static_cast<value_type>(x),\r\n         static_cast<value_type>(y),\r\n         static_cast<value_type>(z),\r\n         static_cast<value_type>(p),\r\n         pol), \"boost::math::ellint_rj<%1%>(%1%,%1%,%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2, class T3, class T4>\r\ninline typename tools::promote_args<T1, T2, T3, T4>::type \r\n   ellint_rj(T1 x, T2 y, T3 z, T4 p)\r\n{\r\n   return ellint_rj(x, y, z, p, policies::policy<>());\r\n}\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_ELLINT_RJ_HPP\r\n", "meta": {"hexsha": "ed0336d1a4a9413cd09444ec112af57234d9fbd6", "size": 5638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/windows/boost/include/boost/math/special_functions/ellint_rj.hpp", "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": "external/windows/boost/include/boost/math/special_functions/ellint_rj.hpp", "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": "external/windows/boost/include/boost/math/special_functions/ellint_rj.hpp", "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": 32.2171428571, "max_line_length": 109, "alphanum_fraction": 0.5257183398, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.5857409824114398}}
{"text": "#include <Eigen/Core>\n\n#include <geos/geom.h>\n#include <geos/opBuffer.h>\n#include <geos/opDistance.h>\n\n#include <Pita/Node.hpp>\n#include <Pita/Context.hpp>\n#include <Pita/Vectorizer.hpp>\n#include <Pita/Printer.hpp>\n\nnamespace cgl\n{\n\tvoid GetQuadraticBezier(Vector<Eigen::Vector2d>& output, const Eigen::Vector2d& p0, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, int n, bool includesEndPoint)\n\t{\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tconst double t = 1.0*i / n;\n\t\t\toutput.push_back(p0*(1.0 - t)*(1.0 - t) + p1 * 2.0*(1.0 - t)*t + p2 * t*t);\n\t\t}\n\n\t\tif (includesEndPoint)\n\t\t{\n\t\t\toutput.push_back(p2);\n\t\t}\n\t}\n\n\tvoid GetCubicBezier(Vector<Eigen::Vector2d>& output, const Eigen::Vector2d& p0, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const Eigen::Vector2d& p3, int n, bool includesEndPoint)\n\t{\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tconst double t = 1.0*i / n;\n\t\t\toutput.push_back(p0*(1.0 - t)*(1.0 - t)*(1.0 - t) + p1 * 3.0*(1.0 - t)*(1.0 - t)*t + p2 * 3.0*(1.0 - t)*t*t + p3 * t*t*t);\n\t\t}\n\n\t\tif (includesEndPoint)\n\t\t{\n\t\t\toutput.push_back(p3);\n\t\t}\n\t}\n\n\tbool IsClockWise(const Vector<Eigen::Vector2d>& closedPath)\n\t{\n\t\tdouble sum = 0;\n\n\t\tfor (int i = 0; i + 1 < closedPath.size(); ++i)\n\t\t{\n\t\t\tconst auto& p1 = closedPath[i];\n\t\t\t//const auto& p2 = closedPath[(i + 1) % closedPath.size()];\n\t\t\tconst auto& p2 = closedPath[i + 1];\n\n\t\t\tsum += (p2.x() - p1.x())*(p2.y() + p1.y());\n\t\t}\n\n\t\t{\n\t\t\tconst auto& p1 = closedPath[closedPath.size() - 1];\n\t\t\tconst auto& p2 = closedPath[0];\n\n\t\t\tsum += (p2.x() - p1.x())*(p2.y() + p1.y());\n\t\t}\n\n\t\treturn sum < 0.0;\n\t}\n\n\tbool IsClockWise(const gg::LineString* closedPath)\n\t{\n\t\tdouble sum = 0;\n\n\t\tfor (size_t p = 0; p + 1 < closedPath->getNumPoints(); ++p)\n\t\t{\n\t\t\tconst gg::Coordinate& p1 = closedPath->getCoordinateN(p);\n\t\t\tconst gg::Coordinate& p2 = closedPath->getCoordinateN(p + 1);\n\t\t\tsum += (p2.x - p1.x)*(p2.y + p1.y);\n\t\t}\n\t\t{\n\t\t\tconst gg::Coordinate& p1 = closedPath->getCoordinateN(closedPath->getNumPoints() - 1);\n\t\t\tconst gg::Coordinate& p2 = closedPath->getCoordinateN(0);\n\t\t\tsum += (p2.x - p1.x)*(p2.y + p1.y);\n\t\t}\n\n\t\treturn sum < 0.0;\n\t}\n\n\tstd::tuple<bool, std::unique_ptr<gg::Geometry>> IsClockWise(std::unique_ptr<gg::Geometry> pLineString)\n\t{\n\t\tdouble sum = 0;\n\n\t\tconst gg::LineString* closedPath = dynamic_cast<const gg::LineString*>(pLineString.get());\n\n\t\tfor (size_t p = 0; p + 1 < closedPath->getNumPoints(); ++p)\n\t\t{\n\t\t\tconst gg::Coordinate& p1 = closedPath->getCoordinateN(p);\n\t\t\tconst gg::Coordinate& p2 = closedPath->getCoordinateN(p + 1);\n\t\t\tsum += (p2.x - p1.x)*(p2.y + p1.y);\n\t\t}\n\t\t{\n\t\t\tconst gg::Coordinate& p1 = closedPath->getCoordinateN(closedPath->getNumPoints() - 1);\n\t\t\tconst gg::Coordinate& p2 = closedPath->getCoordinateN(0);\n\t\t\tsum += (p2.x - p1.x)*(p2.y + p1.y);\n\t\t}\n\n\t\treturn std::make_tuple(sum < 0.0, std::move(pLineString));\n\t}\n\n\tstd::string GetGeometryType(gg::Geometry* geometry)\n\t{\n\t\tswitch (geometry->getGeometryTypeId())\n\t\t{\n\t\tcase geos::geom::GEOS_POINT:              return \"Point\";\n\t\tcase geos::geom::GEOS_LINESTRING:         return \"LineString\";\n\t\tcase geos::geom::GEOS_LINEARRING:         return \"LinearRing\";\n\t\tcase geos::geom::GEOS_POLYGON:            return \"Polygon\";\n\t\tcase geos::geom::GEOS_MULTIPOINT:         return \"MultiPoint\";\n\t\tcase geos::geom::GEOS_MULTILINESTRING:    return \"MultiLineString\";\n\t\tcase geos::geom::GEOS_MULTIPOLYGON:       return \"MultiPolygon\";\n\t\tcase geos::geom::GEOS_GEOMETRYCOLLECTION: return \"GeometryCollection\";\n\t\t}\n\n\t\treturn \"Unknown\";\n\t}\n\n\tgg::Polygon* ToPolygon(const Vector<Eigen::Vector2d>& exterior)\n\t{\n\t\tgg::CoordinateArraySequence pts;\n\n\t\tfor (int i = 0; i < exterior.size(); ++i)\n\t\t{\n\t\t\tpts.add(gg::Coordinate(exterior[i].x(), exterior[i].y()));\n\t\t}\n\n\t\tif (!pts.empty())\n\t\t{\n\t\t\tpts.add(pts.front());\n\t\t}\n\n\t\tauto factory = gg::GeometryFactory::create();\n\t\treturn factory->createPolygon(factory->createLinearRing(pts), {});\n\t}\n\n\tgg::LineString* ToLineString(const Vector<Eigen::Vector2d>& exterior)\n\t{\n\t\tgg::CoordinateArraySequence pts;\n\n\t\tfor (int i = 0; i < exterior.size(); ++i)\n\t\t{\n\t\t\tpts.add(gg::Coordinate(exterior[i].x(), exterior[i].y()));\n\t\t}\n\n\t\tauto factory = gg::GeometryFactory::create();\n\t\treturn factory->createLineString(pts);\n\t}\n\n\tvoid DebugPrint(const gg::Geometry* geometry)\n\t{\n\t\tCGL_DBG;\n\t\tswitch (geometry->getGeometryTypeId())\n\t\t{\n\t\tcase geos::geom::GEOS_POINT:\n\t\t{\n\t\t\tstd::cout << \"Point\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_LINESTRING:\n\t\t{\n\t\t\tstd::cout << \"LineString\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_LINEARRING:\n\t\t{\n\t\t\tstd::cout << \"LinearRing\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_POLYGON:\n\t\t{\n\t\t\tstd::cout << \"Polygon\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_MULTIPOINT:\n\t\t{\n\t\t\tstd::cout << \"MultiPoint\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_MULTILINESTRING:\n\t\t{\n\t\t\tstd::cout << \"MultiLineString\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_MULTIPOLYGON:\n\t\t{\n\t\t\tstd::cout << \"MultiPolygon\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase geos::geom::GEOS_GEOMETRYCOLLECTION:\n\t\t{\n\t\t\tstd::cout << \"GeometryCollection\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\tstd::cout << \"Unknown\" << std::endl;\n\t\t}\n\t\t}\n\t\tCGL_DBG;\n\t}\n\n\tPath Path::clone()const\n\t{\n\t\tPath resultPath;\n\n\t\tresultPath.cs = std::make_unique<gg::CoordinateArraySequence>();\n\t\tauto& csResult = resultPath.cs;\n\t\tauto& distancesResult = resultPath.distances;\n\n\t\tfor (size_t i = 0; i < cs->size(); ++i)\n\t\t{\n\t\t\tcsResult->add(cs->getAt(i));\n\t\t}\n\t\tdistancesResult = distances;\n\n\t\treturn std::move(resultPath);\n\t}\n\n\tBaseLineOffset Path::getOffset(double offset)const\n\t{\n\t\tBaseLineOffset result;\n\n\t\tauto it = std::upper_bound(distances.begin(), distances.end(), offset);\n\t\tif (it == distances.end())\n\t\t{\n\t\t\tconst double innerDistance = offset - distances[distances.size() - 2];\n\n\t\t\tEigen::Vector2d p0(cs->getAt(cs->size() - 2).x, cs->getAt(cs->size() - 2).y);\n\t\t\tEigen::Vector2d p1(cs->getAt(cs->size() - 1).x, cs->getAt(cs->size() - 1).y);\n\n\t\t\tconst Eigen::Vector2d v = (p1 - p0);\n\t\t\tconst double currentLineLength = sqrt(v.dot(v));\n\t\t\tconst double progress = innerDistance / currentLineLength;\n\n\t\t\tconst Eigen::Vector2d targetPos = p0 + v * progress;\n\t\t\tresult.x = targetPos.x();\n\t\t\tresult.y = targetPos.y();\n\n\t\t\tconst auto n = v.normalized();\n\t\t\tresult.angle = rad2deg * atan2(n.y(), n.x());\n\t\t\tresult.nx = n.y();\n\t\t\tresult.ny = -n.x();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst int lineIndex = std::distance(distances.begin(), it) - 1;\n\t\t\tconst double innerDistance = offset - distances[lineIndex];\n\n\t\t\tEigen::Vector2d p0(cs->getAt(lineIndex).x, cs->getAt(lineIndex).y);\n\t\t\tEigen::Vector2d p1(cs->getAt(lineIndex + 1).x, cs->getAt(lineIndex + 1).y);\n\n\t\t\tconst Eigen::Vector2d v = (p1 - p0);\n\t\t\tconst double currentLineLength = sqrt(v.dot(v));\n\t\t\tconst double progress = innerDistance / currentLineLength;\n\n\t\t\tconst Eigen::Vector2d targetPos = p0 + v * progress;\n\t\t\tresult.x = targetPos.x();\n\t\t\tresult.y = targetPos.y();\n\n\t\t\tconst auto n = v.normalized();\n\t\t\tresult.angle = rad2deg * atan2(n.y(), n.x());\n\t\t\tresult.nx = n.y();\n\t\t\tresult.ny = -n.x();\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tvoid BoundingRect::add(const Eigen::Vector2d& v)\n\t{\n\t\tif (v.x() < m_min.x())\n\t\t{\n\t\t\tm_min.x() = v.x();\n\t\t}\n\t\tif (v.y() < m_min.y())\n\t\t{\n\t\t\tm_min.y() = v.y();\n\t\t}\n\t\tif (m_max.x() < v.x())\n\t\t{\n\t\t\tm_max.x() = v.x();\n\t\t}\n\t\tif (m_max.y() < v.y())\n\t\t{\n\t\t\tm_max.y() = v.y();\n\t\t}\n\t}\n\n\tvoid BoundingRect::add(const Vector<Eigen::Vector2d>& vs)\n\t{\n\t\tfor (const auto& v : vs)\n\t\t{\n\t\t\tadd(v);\n\t\t}\n\t}\n\n\tTransformPacked::TransformPacked(const PackedRecord& record)\n\t{\n\t\tdouble px = 0, py = 0;\n\t\tdouble sx = 1, sy = 1;\n\t\tdouble angle = 0;\n\n\t\tfor (const auto& member : record.values)\n\t\t{\n\t\t\tconst PackedVal& value = member.second.value;\n\t\t\tconst auto valOpt = AsOpt<PackedRecord>(value);\n\n\t\t\tif (valOpt)\n\t\t\t{\n\t\t\t\tconst PackedRecord& childRecord = valOpt.get();\n\t\t\t\tif (member.first == \"pos\")\n\t\t\t\t{\n\t\t\t\t\tReadDoublePacked(px, \"x\", childRecord);\n\t\t\t\t\tReadDoublePacked(py, \"y\", childRecord);\n\t\t\t\t}\n\t\t\t\telse if (member.first == \"scale\")\n\t\t\t\t{\n\t\t\t\t\tReadDoublePacked(sx, \"x\", childRecord);\n\t\t\t\t\tReadDoublePacked(sy, \"y\", childRecord);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (member.first == \"angle\")\n\t\t\t{\n\t\t\t\tReadDoublePacked(angle, \"angle\", record);\n\t\t\t}\n\t\t}\n\n\t\tinit(px, py, sx, sy, angle);\n\t}\n\n\tvoid TransformPacked::init(double px, double py, double sx, double sy, double angle)\n\t{\n\t\tconst double pi = 3.1415926535;\n\t\tconst double cosTheta = std::cos(pi*angle / 180.0);\n\t\tconst double sinTheta = std::sin(pi*angle / 180.0);\n\n\t\tmat <<\n\t\t\tsx * cosTheta, -sy * sinTheta, px,\n\t\t\tsx*sinTheta, sy*cosTheta, py,\n\t\t\t0, 0, 1;\n\t}\n\n\tEigen::Vector2d TransformPacked::product(const Eigen::Vector2d& v)const\n\t{\n\t\tEigen::Vector3d xs;\n\t\txs << v.x(), v.y(), 1;\n\t\tEigen::Vector3d result = mat * xs;\n\t\tEigen::Vector2d result2d;\n\t\tresult2d << result.x(), result.y();\n\t\treturn result2d;\n\t}\n\n\tvoid TransformPacked::printMat()const\n\t{\n\t\tstd::cout << \"Matrix(\\n\";\n\t\tfor (int y = 0; y < 3; ++y)\n\t\t{\n\t\t\tstd::cout << \"    \";\n\t\t\tfor (int x = 0; x < 3; ++x)\n\t\t\t{\n\t\t\t\tstd::cout << mat(y, x) << \" \";\n\t\t\t}\n\t\t\tstd::cout << \"\\n\";\n\t\t}\n\t\tstd::cout << \")\\n\";\n\t}\n\n\tGeometryPtr MakeLine(const Eigen::Vector2d& p0, const Eigen::Vector2d& p1)\n\t{\n\t\tgg::CoordinateArraySequence pts;\n\n\t\tpts.add(gg::Coordinate(p0.x(), p0.y()));\n\t\tpts.add(gg::Coordinate(p1.x(), p1.y()));\n\n\t\tauto factory = gg::GeometryFactory::create();\n\n\t\treturn ToUnique<GeometryDeleter>(factory->createLineString(pts));\n\t}\n}\n", "meta": {"hexsha": "9404cb50687206d3501d4b78313d6fd7ab4970e1", "size": 9364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Geometry.cpp", "max_stars_repo_name": "agehama/Pita", "max_stars_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T23:42:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-06T04:16:52.000Z", "max_issues_repo_path": "source/Geometry.cpp", "max_issues_repo_name": "agehama/Pita", "max_issues_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_issues_repo_licenses": ["MIT"], "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/Geometry.cpp", "max_forks_repo_name": "agehama/Pita", "max_forks_repo_head_hexsha": "26f469d5236a9babe39991bea517135d311a8ca1", "max_forks_repo_licenses": ["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.3854166667, "max_line_length": 191, "alphanum_fraction": 0.6135198633, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5857094786960579}}
{"text": "#pragma once\n\n#if USE_STAN\n#include <stan/math.hpp>\n#include <stan/math/fwd.hpp>\n#endif\n\n// clang-format off\n#ifdef USE_CPPAD\n#include <cppad/cg.hpp>\n#include \"math/cppad/eigen_mat_inv.hpp\"\n#endif //USE_CPPAD\n\n// clang-format on\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"math/conditionals.hpp\"\n#include \"math/tiny/neural_scalar.hpp\"\n\n#include \"spatial_vector.hpp\"\n#undef max\n#undef min\n\nnamespace tds {\n\ntemplate <typename ScalarT = double>\nstruct EigenAlgebraT {\n  using Index = Eigen::Index;\n  using Scalar = ScalarT;\n  using EigenAlgebra = EigenAlgebraT<Scalar>;\n  using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n  using VectorX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n  using Matrix3 = Eigen::Matrix<Scalar, 3, 3>;\n  using Matrix6 = Eigen::Matrix<Scalar, 6, 6>;\n  using Matrix3X = Eigen::Matrix<Scalar, 3, Eigen::Dynamic>;\n  using MatrixX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n  using Quaternion = Eigen::Quaternion<Scalar>;\n  using SpatialVector = tds::SpatialVector<EigenAlgebra>;\n  using MotionVector = tds::MotionVector<EigenAlgebra>;\n  using ForceVector = tds::ForceVector<EigenAlgebra>;\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto transpose(const T &matrix) {\n    return matrix.transpose();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto inverse(const T &matrix) {\n    return matrix.inverse();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto inverse_transpose(const T &matrix) {\n    return matrix.inverse().transpose();\n  }\n\n  template <typename T1, typename T2>\n  EIGEN_ALWAYS_INLINE static auto cross(const T1 &vector_a,\n                                        const T2 &vector_b) {\n    return vector_a.cross(vector_b);\n  }\n\n  /**\n   * V1 = mv(w1, v1)\n   * V2 = mv(w2, v2)\n   * V1 x V2 = mv(w1 x w2, w1 x v2 + v1 x w2)\n   */\n  static inline MotionVector cross(const MotionVector &a,\n                                   const MotionVector &b) {\n    return MotionVector(a.top.cross(b.top),\n                        a.top.cross(b.bottom) + a.bottom.cross(b.top));\n  }\n\n  /**\n   * V = mv(w, v)\n   * F = fv(n, f)\n   * V x* F = fv(w x n + v x f, w x f)\n   */\n  static inline ForceVector cross(const MotionVector &a, const ForceVector &b) {\n    return ForceVector(a.top.cross(b.top) + a.bottom.cross(b.bottom),\n                       a.top.cross(b.bottom));\n  }\n\n  EIGEN_ALWAYS_INLINE static Index size(const VectorX &v) { return v.size(); }\n\n  EIGEN_ALWAYS_INLINE static Matrix3X create_matrix_3x(int num_cols) {\n    return Matrix3X(3, num_cols);\n  }\n  EIGEN_ALWAYS_INLINE static MatrixX create_matrix_x(int num_rows,\n                                                     int num_cols) {\n    return MatrixX(num_rows, num_cols);\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static int num_rows(const T &matrix) {\n    return matrix.rows();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static int num_cols(const T &matrix) {\n    return matrix.cols();\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar determinant(const Matrix3 &m) {\n    return m.determinant();\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar determinant(const MatrixX &m) {\n    return m.determinant();\n  }\n\n  /**\n   * CppAD-friendly matrix inverse operation that assumes the input matrix is\n   * positive-definite.\n   */\n  static void plain_symmetric_inverse(const MatrixX &mat, MatrixX &mat_inv) {\n    assert(mat.rows() == mat.cols());\n    VectorX diagonal = mat.diagonal();\n    mat_inv = mat;\n    const int n = mat.rows();\n    int i, j, k;\n    Scalar sum;\n    for (i = 0; i < n; i++) {\n      mat_inv(i, i) = one() / diagonal[i];\n      for (j = i + 1; j < n; j++) {\n        sum = zero();\n        for (k = i; k < j; k++) {\n          sum -= mat_inv(j, k) * mat_inv(k, i);\n        }\n        mat_inv(j, i) = sum / diagonal[j];\n      }\n    }\n    for (i = 0; i < n; i++) {\n      for (j = i + 1; j < n; j++) {\n        mat_inv(i, j) = zero();\n      }\n    }\n    for (i = 0; i < n; i++) {\n      mat_inv(i, i) = mat_inv(i, i) * mat_inv(i, i);\n      for (k = i + 1; k < n; k++) {\n        mat_inv(i, i) += mat_inv(k, i) * mat_inv(k, i);\n      }\n      for (j = i + 1; j < n; j++) {\n        for (k = j; k < n; k++) {\n          mat_inv(i, j) += mat_inv(k, i) * mat_inv(k, j);\n        }\n      }\n    }\n    for (i = 0; i < n; i++) {\n      for (j = 0; j < i; j++) {\n        mat_inv(i, j) = mat_inv(j, i);\n      }\n    }\n  }\n\n  /**\n   * Returns true if the matrix `mat` is positive-definite, and assigns\n   * `mat_inv` to the inverse of mat.\n   * `mat` must be a symmetric matrix.\n   */\n  static bool symmetric_inverse(const MatrixX &mat, MatrixX &mat_inv) {\n    if constexpr (!is_cppad_scalar<Scalar>::value) {\n      Eigen::LLT<MatrixX> llt(mat);\n      if (llt.info() == Eigen::NumericalIssue) {\n        return false;\n      }\n      mat_inv = mat.inverse();\n    } else {\n      plain_symmetric_inverse(mat, mat_inv);\n      // // FIXME the atomic op needs to remain in memory but it will fail when\n      // the\n      // // dimensions of the input matrix are not always the same\n      // using InnerScalar = typename Scalar::value_type;\n      // static atomic_eigen_mat_inv<InnerScalar> mat_inv_op;\n      // mat_inv = mat_inv_op.op(mat);\n    }\n    return true;\n  }\n\n  /**\n   * V = mv(w, v)\n   * F = mv(n, f)\n   * V.F = w.n + v.f\n   */\n  EIGEN_ALWAYS_INLINE static Scalar dot(const MotionVector &a,\n                                        const ForceVector &b) {\n    return a.top.dot(b.top) + a.bottom.dot(b.bottom);\n  }\n  EIGEN_ALWAYS_INLINE static Scalar dot(const ForceVector &a,\n                                        const MotionVector &b) {\n    return dot(b, a);\n  }\n\n  template <typename T1, typename T2>\n  EIGEN_ALWAYS_INLINE static auto dot(const T1 &vector_a, const T2 &vector_b) {\n    return vector_a.dot(vector_b);\n  }\n\n  TINY_INLINE static Scalar norm(const MotionVector &v) {\n    using std::sqrt;\n    return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] +\n                v[4] * v[4] + v[5] * v[5]);\n  }\n  TINY_INLINE static Scalar norm(const ForceVector &v) {\n    using std::sqrt;\n    return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] +\n                v[4] * v[4] + v[5] * v[5]);\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static Scalar norm(const T &v) {\n    return v.norm();\n  }\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static Scalar sqnorm(const T &v) {\n    return v.squaredNorm();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto normalize(T &v) {\n    v.normalize();\n    return v;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 cross_matrix(const Vector3 &v) {\n    Matrix3 tmp;\n#ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS\n    tmp << zero(), v[2], -v[1], -v[2], zero(), v[0], v[1], -v[0], zero();\n#else\n    tmp << zero(), -v[2], v[1], v[2], zero(), -v[0], -v[1], v[0], zero();\n    \n#endif\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 zero33() { return Matrix3::Zero(); }\n\n  EIGEN_ALWAYS_INLINE static VectorX zerox(Index size) {\n    return VectorX::Zero(size);\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Vector3 &v) {\n    Matrix3 tmp;\n    tmp.setZero();\n    tmp(0, 0) = v[0];\n    tmp(1, 1) = v[1];\n    tmp(2, 2) = v[2];\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Scalar &v) {\n    Matrix3 tmp;\n    tmp.setZero();\n    tmp(0, 0) = v;\n    tmp(1, 1) = v;\n    tmp(2, 2) = v;\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 eye3() { return Matrix3::Identity(); }\n  EIGEN_ALWAYS_INLINE static void set_identity(Quaternion &quat) {\n    quat = Quaternion(Scalar(1.), Scalar(0.), Scalar(0.), Scalar(0.));\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar zero() { return Scalar(0); }\n  EIGEN_ALWAYS_INLINE static Scalar one() { return Scalar(1); }\n  EIGEN_ALWAYS_INLINE static Scalar two() { return Scalar(2); }\n  EIGEN_ALWAYS_INLINE static Scalar half() { return Scalar(0.5); }\n  EIGEN_ALWAYS_INLINE static Scalar pi() { return Scalar(M_PI); }\n  EIGEN_ALWAYS_INLINE static Scalar fraction(int a, int b) {\n    return (Scalar(a)) / b;\n  }\n\n  static Scalar scalar_from_string(const std::string &s) {\n    return from_double(std::stod(s));\n  }\n\n  EIGEN_ALWAYS_INLINE static Vector3 zero3() { return Vector3::Zero(); }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_x() {\n    return Vector3(one(), zero(), zero());\n  }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_y() {\n    return Vector3(zero(), one(), zero());\n  }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_z() {\n    return Vector3(zero(), zero(), one());\n  }\n\n  EIGEN_ALWAYS_INLINE static VectorX segment(const VectorX &vec,\n                                             int start_index, int length) {\n    return vec.segment(start_index, length);\n  }\n\n  EIGEN_ALWAYS_INLINE static MatrixX block(const MatrixX &mat,\n                                           int start_row_index,\n                                           int start_col_index, int rows,\n                                           int cols) {\n    return mat.block(start_row_index, start_col_index, rows, cols);\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix3X &output,\n                                               const Matrix3 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix6 &output,\n                                               const Matrix3 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix3 &output,\n                                               const Matrix6 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(MatrixX &output,\n                                               const MatrixX &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  template <int Rows1, int Cols1, int Rows2, int Cols2>\n  EIGEN_ALWAYS_INLINE static void assign_block(\n      Eigen::Matrix<Scalar, Rows1, Cols1> &output,\n      const Eigen::Matrix<Scalar, Rows2, Cols2> &input, int i, int j,\n      int m = -1, int n = -1, int input_i = 0, int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i,\n                                                const Vector3 &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i,\n                                                const Matrix6 &v) {\n    m.col(i) = v;\n  }\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3X &m, Index i,\n                                                const Vector3 &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i,\n                                                const MatrixX &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i,\n                                                const SpatialVector &v) {\n    m.block(0, i, 3, 1) = v.top;\n    m.block(3, i, 3, 1) = v.bottom;\n  }\n  template <int Rows, int Cols, typename Derived>\n  EIGEN_ALWAYS_INLINE static void assign_column(\n      Eigen::Matrix<Scalar, Rows, Cols> &m, Index i,\n      const Eigen::DenseBase<Derived> &v) {\n    assign_column(m, i, v.eval());\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i,\n                                             const MatrixX &v) {\n    m.row(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i,\n                                             const SpatialVector &v) {\n    m.block(i, 0, 1, 3) = v.top;\n    m.block(i, 3, 1, 3) = v.bottom;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_horizontal(MatrixX &mat,\n                                                    const VectorX &vec,\n                                                    int start_row_index,\n                                                    int start_col_index) {\n    mat.block(start_row_index, start_col_index, 1, vec.rows()) =\n        vec.transpose();\n  }\n\n  template <int Rows>\n  EIGEN_ALWAYS_INLINE static void assign_vertical(\n      MatrixX &mat, const Eigen::Matrix<Scalar, Rows, 1> &vec,\n      int start_row_index, int start_col_index) {\n    mat.block(start_row_index, start_col_index, vec.rows(), 1) = vec;\n  }\n\n  template <int Rows, int Cols>\n  TINY_INLINE static VectorX mul_transpose(\n      const Eigen::Matrix<Scalar, Rows, Cols> &mat,\n      const Eigen::Matrix<Scalar, Cols, 1> &vec) {\n    return mat.transpose() * vec;\n  }\n  TINY_INLINE static VectorX mul_transpose(const MatrixX &mat,\n                                           const VectorX &vec) {\n    return mat.transpose() * vec;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Quaternion &quat) {\n    // NOTE: Eigen requires quat to be normalized\n    return quat.toRotationMatrix();\n  }\n  EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Scalar &x,\n                                                    const Scalar &y,\n                                                    const Scalar &z,\n                                                    const Scalar &w) {\n    return Quaternion(w, x, y, z).toRotationMatrix();\n  }\n  EIGEN_ALWAYS_INLINE static Quaternion matrix_to_quat(const Matrix3 &m) {\n    if constexpr (is_cppad_scalar<Scalar>::value) {\n      // add epsilon to denominator to prevent division by zero\n      const Scalar eps = from_double(1e-6);\n      Scalar tr = m(0, 0) + m(1, 1) + m(2, 2);\n      Scalar q1[4], q2[4], q3[4], q4[4];\n      // if (tr > 0)\n      {\n        Scalar S = sqrt(abs(tr + 1.0)) * two() + eps;\n        q1[0] = fraction(1, 4) * S;\n        q1[1] = (m(2, 1) - m(1, 2)) / S;\n        q1[2] = (m(0, 2) - m(2, 0)) / S;\n        q1[3] = (m(1, 0) - m(0, 1)) / S;\n      }\n      // else if ((m(0,0) > m(1,1))&(m(0,0) > m(2,2)))\n      {\n        Scalar S = sqrt(abs(1.0 + m(0, 0) - m(1, 1) - m(2, 2))) * two() + eps;\n        q2[0] = (m(2, 1) - m(1, 2)) / S;\n        q2[1] = fraction(1, 4) * S;\n        q2[2] = (m(0, 1) + m(1, 0)) / S;\n        q2[3] = (m(0, 2) + m(2, 0)) / S;\n      }\n      // else if (m(1,1) > m(2,2))\n      {\n        Scalar S = sqrt(abs(1.0 + m(1, 1) - m(0, 0) - m(2, 2))) * two() + eps;\n        q3[0] = (m(0, 2) - m(2, 0)) / S;\n        q3[1] = (m(0, 1) + m(1, 0)) / S;\n        q3[2] = fraction(1, 4) * S;\n        q3[3] = (m(1, 2) + m(2, 1)) / S;\n      }\n      // else\n      {\n        Scalar S = sqrt(abs(1.0 + m(2, 2) - m(0, 0) - m(1, 1))) * two() + eps;\n        q4[0] = (m(1, 0) - m(0, 1)) / S;\n        q4[1] = (m(0, 2) + m(2, 0)) / S;\n        q4[2] = (m(1, 2) + m(2, 1)) / S;\n        q4[3] = fraction(1, 4) * S;\n      }\n      Quaternion q;\n      // (m(0,0) > m(1,1))&(m(0,0) > m(2,2))\n      Scalar m00_is_max = where_gt(\n          m(0, 0), m(1, 1), where_gt(m(0, 0), m(2, 2), one(), zero()), zero());\n      Scalar m11_is_max =\n          (one() - m00_is_max) * where_gt(m(1, 1), m(2, 2), one(), zero());\n      Scalar m22_is_max = (one() - m00_is_max) * (one() - m11_is_max);\n      q.w() = where_gt(\n          tr, zero(), q1[0],\n          m00_is_max * q2[0] + m11_is_max * q3[0] + m22_is_max * q4[0]);\n      q.x() = where_gt(\n          tr, zero(), q1[1],\n          m00_is_max * q2[1] + m11_is_max * q3[1] + m22_is_max * q4[1]);\n      q.y() = where_gt(\n          tr, zero(), q1[2],\n          m00_is_max * q2[2] + m11_is_max * q3[2] + m22_is_max * q4[2]);\n      q.z() = where_gt(\n          tr, zero(), q1[3],\n          m00_is_max * q2[3] + m11_is_max * q3[3] + m22_is_max * q4[3]);\n      return q;\n    } else {\n      return Quaternion(m);\n    }\n  }\n  EIGEN_ALWAYS_INLINE static Quaternion axis_angle_quaternion(\n      const Vector3 &axis, const Scalar &angle) {\n    return Quaternion(Eigen::AngleAxis(angle, axis));\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_x_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n#ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS\n    temp << one(), zero(), zero(), zero(), c, s, zero(), -s, c;\n#else\n    temp << one(), zero(), zero(), zero(), c, -s, zero(), s, c;\n#endif\n    //std::cout << \"rot_x\" << temp << std::endl;\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_y_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n#ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS\n    temp << c, zero(), -s, zero(), one(), zero(), s, zero(), c;\n#else\n    temp << c, zero(), s, zero(), one(), zero(), -s, zero(), c;\n#endif\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_z_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n#ifdef TDS_USE_LEFT_ASSOCIATIVE_TRANSFORMS\n    temp << c, s, zero(), -s, c, zero(), zero(), zero(), one();\n#else\n    temp << c, -s, zero(), s, c, zero(), zero(), zero(), one();\n#endif\n    return temp;\n  }\n\n  static Matrix3 rotation_zyx_matrix(const Scalar &r, const Scalar &p,\n                                     const Scalar &y) {\n    using std::cos, std::sin;\n    Scalar ci(cos(r));\n    Scalar cj(cos(p));\n    Scalar ch(cos(y));\n    Scalar si(sin(r));\n    Scalar sj(sin(p));\n    Scalar sh(sin(y));\n    Scalar cc = ci * ch;\n    Scalar cs = ci * sh;\n    Scalar sc = si * ch;\n    Scalar ss = si * sh;\n    Matrix3 temp;\n    temp << cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc,\n        sj * cs - sc, -sj, cj * si, cj * ci;\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Vector3 rotate(const Quaternion &q,\n                                            const Vector3 &v) {\n    return q * v;\n  }\n\n  /**\n   * Computes the quaternion delta given current rotation q, angular velocity w,\n   * time step dt.\n   */\n  EIGEN_ALWAYS_INLINE static Quaternion quat_velocity(const Quaternion &q,\n                                                      const Vector3 &w,\n                                                      const Scalar &dt) {\n    Quaternion delta((-q.x() * w[0] - q.y() * w[1] - q.z() * w[2]) * (0.5 * dt),\n                     (q.w() * w[0] + q.y() * w[2] - q.z() * w[1]) * (0.5 * dt),\n                     (q.w() * w[1] + q.z() * w[0] - q.x() * w[2]) * (0.5 * dt),\n                     (q.w() * w[2] + q.x() * w[1] - q.y() * w[0]) * (0.5 * dt));\n    return delta;\n  }\n\n  EIGEN_ALWAYS_INLINE static void quat_increment(Quaternion &a,\n                                                 const Quaternion &b) {\n    a.x() += b.x();\n    a.y() += b.y();\n    a.z() += b.z();\n    a.w() += b.w();\n  }\n\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_x(const Quaternion &q) {\n    return q.x();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_y(const Quaternion &q) {\n    return q.y();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_z(const Quaternion &q) {\n    return q.z();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_w(const Quaternion &q) {\n    return q.w();\n  }\n  EIGEN_ALWAYS_INLINE static const Quaternion quat_from_xyzw(const Scalar &x,\n                                                             const Scalar &y,\n                                                             const Scalar &z,\n                                                             const Scalar &w) {\n    // Eigen specific constructor coefficient order\n    return Quaternion(w, x, y, z);\n  }\n\n  EIGEN_ALWAYS_INLINE static void set_zero(Matrix3X &m) { m.setZero(); }\n  EIGEN_ALWAYS_INLINE static void set_zero(Vector3 &m) { m.setZero(); }\n  EIGEN_ALWAYS_INLINE static void set_zero(VectorX &m) { m.setZero(); }\n\n  EIGEN_ALWAYS_INLINE static void set_zero(MatrixX &m) { m.setZero(); }\n  template <int Size1, int Size2 = 1>\n  EIGEN_ALWAYS_INLINE static void set_zero(\n      Eigen::Array<Scalar, Size1, Size2> &v) {\n    v.setZero();\n  }\n  EIGEN_ALWAYS_INLINE static void set_zero(MotionVector &v) {\n    v.top.setZero();\n    v.bottom.setZero();\n  }\n  EIGEN_ALWAYS_INLINE static void set_zero(ForceVector &v) {\n    v.top.setZero();\n    v.bottom.setZero();\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  TINY_INLINE static bool is_zero(const Scalar &a) { return a == zero(); }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool less_than(const Scalar &a, const Scalar &b) {\n    return a < b;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool less_than_zero(const Scalar &a) {\n    return a < 0.;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool greater_than_zero(const Scalar &a) {\n    return a > 0.;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool greater_than(const Scalar &a,\n                                               const Scalar &b) {\n    return a > b;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool equals(const Scalar &a, const Scalar &b) {\n    return a == b;\n  }\n\n#ifdef USE_STAN\n  template <typename InnerScalar>\n  TINY_INLINE static std::enable_if_t<\n      !std::is_same_v<Scalar, stan::math::fvar<InnerScalar>>, double>\n  to_double(const stan::math::fvar<InnerScalar> &s) {\n    return stan::math::value_of(s);\n  }\n#endif\n\n  TINY_INLINE static double to_double(const Scalar &s) {\n#ifdef USE_STAN\n    if constexpr (std::is_same_v<Scalar, stan::math::var> ||\n                  std::is_same_v<Scalar, stan::math::fvar<double>>) {\n      return stan::math::value_of(s);\n    } else\n#endif\n#ifdef USE_CPPAD\n        if constexpr (std::is_same_v<std::remove_cv_t<Scalar>,\n                                     CppAD::AD<CppAD::cg::CG<double>>>) {\n      return CppAD::Value(CppAD::Var2Par(s)).getValue();\n    } else if constexpr (std::is_same_v<std::remove_cv_t<Scalar>,\n                                        CppAD::AD<double>>) {\n      return CppAD::Value(CppAD::Var2Par(s));\n    } else \n#endif //USE_CPPAD\n    {\n      return static_cast<double>(s);\n    }\n  }\n\n  TINY_INLINE static Scalar from_double(double s) {\n    return static_cast<Scalar>(s);\n  }\n\n  template <int Size1, int Size2>\n  static void print(const std::string &title,\n                    Eigen::Matrix<Scalar, Size1, Size2> &m) {\n    std::cout << title << \"\\n\" << m << std::endl;\n  }\n  template <int Size1, int Size2 = 1>\n  static void print(const std::string &title,\n                    Eigen::Array<Scalar, Size1, Size2> &v) {\n    std::cout << title << \"\\n\" << v << std::endl;\n  }\n  static void print(const std::string &title, const Scalar &v) {\n    std::cout << title << \"\\n\" << to_double(v) << std::endl;\n  }\n  template <typename T>\n  static void print(const std::string &title, const T &abi) {\n    abi.print(title.c_str());\n  }\n\n  template <typename T>\n  TINY_INLINE static auto sin(const T &s) {\n    using std::sin;\n    return sin(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto cos(const T &s) {\n    using std::cos;\n    return cos(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto tan(const T &s) {\n    using std::tan;\n    return tan(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto atan2(const T &dy, const T &dx) {\n    using std::atan2;\n    return atan2(dy, dx);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto abs(const T &s) {\n    using std::abs;\n    return abs(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto sqrt(const T &s) {\n    using std::sqrt;\n    return sqrt(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto tanh(const T &s) {\n    using std::tanh;\n    return tanh(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto pow(const T &s, const T &e) {\n    using std::pow;\n    return pow(s, e);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto exp(const T &s) {\n    using std::exp;\n    return exp(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto log(const T &s) {\n    using std::log;\n    return log(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto max(const T &x, const T &y) {\n    return tds::where_gt(x, y, x, y);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto min(const T &x, const T &y) {\n    return tds::where_lt(x, y, x, y);\n  }\n\n  EigenAlgebraT<Scalar>() = delete;\n};\n\ntypedef EigenAlgebraT<double> EigenAlgebra;\n\n// Helpers for NeuralAlgebra\n#ifdef USE_CPPAD\ntemplate <typename Scalar>\nstruct is_cppad_scalar<NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>> {\n  static constexpr bool value = true;\n};\n\ntemplate <typename Scalar>\nstatic TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_gt(\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) {\n    return CppAD::CondExpGt(x.evaluate(), y.evaluate(), if_true.evaluate(),\n        if_false.evaluate());\n}\n\ntemplate <typename Scalar>\nstatic TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_ge(\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) {\n    return CppAD::CondExpGe(x.evaluate(), y.evaluate(), if_true.evaluate(),\n        if_false.evaluate());\n}\n\ntemplate <typename Scalar>\nstatic TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_lt(\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) {\n    return CppAD::CondExpLt(x.evaluate(), y.evaluate(), if_true.evaluate(),\n        if_false.evaluate());\n}\n\ntemplate <typename Scalar>\nstatic TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_le(\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) {\n    return CppAD::CondExpLe(x.evaluate(), y.evaluate(), if_true.evaluate(),\n        if_false.evaluate());\n}\n\ntemplate <typename Scalar>\nstatic TINY_INLINE NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>> where_eq(\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& x,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& y,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_true,\n    const NeuralScalar<EigenAlgebraT<CppAD::AD<Scalar>>>& if_false) {\n    return CppAD::CondExpEq(x.evaluate(), y.evaluate(), if_true.evaluate(),\n        if_false.evaluate());\n}\n#endif //USE_CPPAD\n\n\n\n\n}  // end namespace tds\n", "meta": {"hexsha": "1d33b6a638422bfe3b1f6fb0b7d2ce8819a83af9", "size": 29041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/eigen_algebra.hpp", "max_stars_repo_name": "eric-heiden/tds-merge", "max_stars_repo_head_hexsha": "1e18447b0096efbb6df5d9ad7d69c8b0cc282747", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/eigen_algebra.hpp", "max_issues_repo_name": "eric-heiden/tds-merge", "max_issues_repo_head_hexsha": "1e18447b0096efbb6df5d9ad7d69c8b0cc282747", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/eigen_algebra.hpp", "max_forks_repo_name": "eric-heiden/tds-merge", "max_forks_repo_head_hexsha": "1e18447b0096efbb6df5d9ad7d69c8b0cc282747", "max_forks_repo_licenses": ["Apache-2.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.8518099548, "max_line_length": 80, "alphanum_fraction": 0.5601046796, "num_tokens": 8351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605411, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5856470777279217}}
{"text": "\n\n#ifndef SAXQUANTIZER_HPP\n#define SAXQUANTIZER_HPP\n\n#include \"../CAPCA.h\"\n#include <deque>\n#include <vector>\n#include <cassert>\n#include <boost/math/distributions/normal.hpp>\n\nusing std::deque;\nusing std::vector;\nusing namespace std;\nnamespace SaxQuantizer {\n\n\tinline void fill_cutpoints(const size_t& alphabet_size, vector<double> *cutpoints) {\n\t\tassert(alphabet_size > 0);\n\t\tstatic boost::math::normal dist(0.0, 1.0);\n\t\t//std::cout << \"alphabet: \" << alphabet_size << std::endl;\n\t\tcutpoints->reserve(alphabet_size);\n\t\tcutpoints->push_back(-DBL_MAX);\n\t\t//cout << \"cdf: \";\n\t\tfor (size_t i = 1; i < alphabet_size; ++i) {\n\t\t\tdouble cdf = ((double)i) / alphabet_size;\n\t\t\t//cout << quantile(dist, cdf) << \" \";\n\t\t\tcutpoints->push_back(quantile(dist, cdf));\n\t\t\t//cout << cutpoints->begin();\n\t\t}\n\t\t//cout << endl;\n\t}\n\n\t/**\n\t * Symbolic Aggregate Approximation with fractional sliding window, numerosity reduction, and scaling\n\t */\n\tclass SAX : virtual public APCA_QUAL {\n\tprivate:\n\t\tsize_t m_window_size;\n\t\tsize_t m_string_size;// the number of segments, N .\n\t\tsize_t m_alphabet_size;\n\n\t\tdouble m_baseline_mean;\n\t\tdouble m_baseline_stdev;\n\t\tvector<double> m_cutpoints;\n\n\t\tbool m_trained;\n\n\t\tsize_t segment_number;//200923 \n\n\t\t/**\n\t\t * SAX with fractional sliding window and automatic scaling.\n\t\t * @param <it>: start iterator\n\t\t * @param <end>: end iterator\n\t\t * @param <syms> (out): quantized range\n\t\t */\n\t\ttemplate<class Iter>\n\t\tvoid saxify(Iter it, const Iter end, vector<int> *syms) {\n\t\t\t// perform PAA using a fractional sliding window\n\t\t   // double paa[m_string_size];\n\t\t\tdouble* paa = new double[m_string_size];\n\t\t\tdouble paa_window = ((double)m_window_size) / m_string_size;\n\n\t\t\tdouble p = 0; // p for progress\n\t\t\tdouble w = 1; // w for weight\n\t\t\tsize_t available = 0;\n\n\t\t\tfor (size_t i = 0; i < m_string_size && it != end; ++i, ++available) {\n\t\t\t\t// normalize around baseline\n\n\t\t\t\tdouble normalized = (*it - m_baseline_mean) / m_baseline_stdev;\n\n\t\t\t\tpaa[i] = 0;\n\t\t\t\tdouble j = 0;\n\n\t\t\t\twhile (j < paa_window && it != end) {\n\n\t\t\t\t\tpaa[i] += w * normalized; // sum of (partial) elements inside the window\n\t\t\t\t\tj += w;\n\t\t\t\t\tp += w;\n\n\t\t\t\t\t// window full\n\t\t\t\t\tif (paa_window == p) {\n\n\t\t\t\t\t\tif (fabs(w - 1.0) <= 0.01) {   // if last element fully consumed,\n\t\t\t\t\t\t\t++it;                        // then just move next.\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {                       // o.w.,\n\t\t\t\t\t\t\tw = 1.0 - w;                 // set remaining portion.\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp = 0;                         // reset progress\n\n\t\t\t\t\t  // window not full, but next must be split\n\t\t\t\t\t}\n\t\t\t\t\telse if (paa_window - p < 1.0) {\n\n\t\t\t\t\t\tw = paa_window - p;            // set needed portion\n\t\t\t\t\t\t++it;                          // move to next\n\n\t\t\t\t\t  // window not full, next can be fully consumed\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t++it;                          // move to next\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpaa[i] /= j; // averaging\n\t\t\t}\n\n\t\t\t// map to symbols. 0-based.\n\t\t\t//cout << \"available\" << available << endl;\n\t\t\tfor (size_t i = 0; i < available; ++i) {\n\t\t\t\tint cnt = -1;\n\t\t\t\tfor (const auto & cp : m_cutpoints) {\n\t\t\t\t\tif (paa[i] >= cp) ++cnt;\n\t\t\t\t}\n\t\t\t\tsyms->push_back(cnt);\n\t\t\t}\n\t\t\tdelete[] paa;\n\t\t}\n\n\tpublic:\n\t\t/**\n\t\t* Constructs a SAX quantizer of a given window size, string size and alphabet size.\n\t\t* @param <window_size>: sliding window size\n\t\t* @param <string_size>: output string size for each sliding window (can be greater than window_size)\n\t\t* @param <alphabet_size>: number of codewords\n\t\t*/\n\t\tSAX(size_t window_size, size_t string_size, size_t alphabet_size)\n\t\t\t: m_window_size(window_size), m_string_size(string_size), m_alphabet_size(alphabet_size),\n\t\t\tm_baseline_mean(0), m_baseline_stdev(1), m_trained(false) {\n\n\t\t\tassert(window_size > 0);\n\t\t\tassert(string_size > 0);\n\t\t\tassert(alphabet_size > 0);\n\n\t\t\tfill_cutpoints(alphabet_size, &m_cutpoints);\n\t\t}\n\n\n\t\t/**\n\t\t* Constructs a SAX quantizer of timeseries and alphabet size.\n\t\t* @param <window_size>: sliding window size\n\t\t* @param <string_size>: output string size for each sliding window (can be greater than window_size)\n\t\t* @param <alphabet_size>: number of codewords\n\t\t\n\t\t*/\n\t\tSAX(const size_t& alphabet_size): m_window_size(1), m_string_size(1), m_alphabet_size(alphabet_size),m_baseline_mean(0), m_baseline_stdev(1), m_trained(false) {\n\n\t\t\tassert(alphabet_size > 0);\n\n\t\t\tfill_cutpoints(alphabet_size, &m_cutpoints);\n\t\t}\n\n\n\t\tvirtual ~SAX() {\n\t\t\tm_cutpoints.clear();\n\t\t}\n\n\n\n\t\t/**\n\t\t * Trains the quantizer from a given sample. This sets the baseline mean and stdevs, which are used in\n\t\t * normalizing the input.\n\t\t *\n\t\t * @param <samples>: list of training values\n\t\t */\n\t\ttemplate<typename Container>\n\t\tvoid train(const Container & samples) {\n\t\t\tdouble mean = 0;\n\t\t\tdouble stdev = DBL_MIN;\n\n\t\t\tassert(!samples.empty());\n\n\t\t\tif (samples.size() < 2) {\n\t\t\t\tmean = samples[0];\n\t\t\t\tstdev = DBL_MIN;\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsize_t n = 0;\n\t\t\t\tdouble M2 = 0;\n\t\t\t\tfor (const auto & val : samples) {\n\t\t\t\t\t++n;\n\t\t\t\t\tdouble delta = val - mean;\n\t\t\t\t\tmean += delta / n;\n\t\t\t\t\tM2 += delta * (val - mean);\n\t\t\t\t}\n\t\t\t\tstdev = sqrt(M2 / (n - 1));\n\t\t\t}\n\n\t\t\tif (stdev == 0) stdev = DBL_MIN;\n\n\t\t\tm_baseline_mean = mean;\n\t\t\tm_baseline_stdev = stdev;\n\n\t\t\tm_trained = true;\n\t\t}\n\n\t\ttemplate<typename Container>\n\t\tsize_t quantize(const Container & seq, vector<int> *qseq, bool reduce = true) {\n\t\t\tif (!m_trained) train(seq);\n\n\t\t\tvector<int> buf1, buf2;\n\t\t\tauto *syms_buf = &buf1;\n\t\t\tauto *old_syms_buf = &buf2;\n\n\t\t\tsize_t consumed = 0;\n\t\t\tfor (consumed = 0; consumed < seq.size(); ++consumed) {\n\n\t\t\t\tif (reduce) { // run-length numerosity reduction\n\t\t\t\t\tsyms_buf->clear();\n\t\t\t\t\tsaxify(seq.begin() + consumed, seq.end(), syms_buf);\n\n\t\t\t\t\t// skip window if same as previous\n\t\t\t\t\tif (*syms_buf != *old_syms_buf) {\n\t\t\t\t\t\tqseq->insert(qseq->end(), syms_buf->begin(), syms_buf->end());\n\t\t\t\t\t\tstd::swap(syms_buf, old_syms_buf);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\telse { // no reduction\n\t\t\t\t\tsaxify(seq.begin() + consumed, seq.end(), qseq);\n\t\t\t\t}\n\n\t\t\t\t// ignore excess elements, if sequence size isn't a multiple of window size\n\t\t\t\t//if (seq.size() - consumed <= m_window_size) break;\n\t\t\t}\n\n\t\t\treturn consumed;\n\t\t}\n\n\t\t/**\n\t\t* Constructs a SAX quantizer of timeseries and alphabet size.\n\t\t* @param <window_size>: sliding window size\n\t\t* @param <string_size>: output string size for each sliding window (can be greater than window_size)\n\t\t* @param <alphabet_size>: number of codewords\n\t\t* @date : 2018/3/31 15:48\n\t\t* @author :  \n\t\t*/\n\t\ttemplate<typename Container>\n\t\tsize_t getSAX(const Container& seq, vector<char>& qseq) {\n\t\t\tif (!m_trained) train(seq);\n\t\t\tdouble normalized = NULL;\n\t\t\tfor (auto& it : seq) {\n\t\t\t\t//cout << it << endl;\n\t\t\t\tnormalized = (it - m_baseline_mean) / m_baseline_stdev;\n\t\t\t\tint cnt = -1;\n\t\t\t\t//cout << \"*******************************************\" << endl;\n\t\t\t\tfor (const auto & cp : m_cutpoints) {\n\t\t\t\t\t//cout << normalized << \", \" << cp << \", \" << (normalized > cp ? true:false) << endl;\n\t\t\t\t\tif (normalized >= cp) ++cnt;\n\t\t\t\t}\n\t\t\t\tqseq.push_back(static_cast<char>(cnt + 65));\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\n\t\t/**\n\t\t * Returns the order of the quantizer (here, the window size)\n\t\t */\n\t\tinline size_t order() const {\n\t\t\treturn m_window_size;\n\t\t}\n\n\n\t\tinline double ratio() const {\n\t\t\treturn ((double)m_window_size) / m_string_size;\n\t\t}\n\n\t\ttemplate<typename T, typename Y, typename U>\n\t\tvoid get_SAX(const vector<T>& const original_time_series_vector, const Y& const segment_number, const U& const SAX_container) {\n\n\t\t\t\n\t\t\tvector<double> paa_vector;\n\t\t\tvector<int> SAX_quantizer_vector;\n\n\t\t\tAPCA_QUAL::get_PAA(original_time_series_vector, segment_number, SAX_container);\n\n\t\t\tfor (int i = 0; i < segment_number; i++) {\n\t\t\t\tpaa_vector.emplace_back(SAX_container.v[i]);\n\t\t\t}\n\t\t\n\t\t\tquantize(paa_vector, &SAX_quantizer_vector, false);\n\t\t\n\t\t\tcopy_n(SAX_quantizer_vector.begin(), SAX_quantizer_vector.size(), SAX_container.v);\n\t\t\n\t\t}\n\n\t\t/**\n\t\t* @Name: distance_cell\n\t\t* @Qualifier: cell(r,c)\n\t\t* @Date: 200923\n\t\t* @author: \n\t\t*/\n\t\ttemplate<typename T>\n\t\tinline double get_distance_cell(const T& const vaule_1, const T& const vaule_2) {\n\t\t\tif (fabs(vaule_1 - vaule_2) <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn m_cutpoints[max(vaule_1 + 1, vaule_2 + 1) - 1] - m_cutpoints[min(vaule_1 + 1, vaule_2 + 1)];\n\t\t\t}\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tdouble distance_LB_SAX(const T& const SAX_container1, const T& const SAX_container2) {\n\n\t\t\tconst auto& const QProjection = SAX_container1;\n\t\t\tconst auto& const italicC = SAX_container2;\n\n\t\t\tint i = 0, j = 0;\n\t\t\tdouble distance = 0;\n\n\t\t\tdouble sum = (italicC.r[0] + 1) * pow(get_distance_cell(QProjection.v[0], italicC.v[0]), 2);\n\n\t\t\tfor (i = 1; i < italicC.segmentNum; i++) {\n\t\t\t\tsum += (italicC.r[i] - italicC.r[i - 1]) * pow( get_distance_cell( QProjection.v[i], italicC.v[i] ), 2 );\n\t\t\t}\n\t\t\tdistance = sqrt(sum);\n\t\t\treturn distance;\n\t\t}\n\t};\n}\n\n#endif\n", "meta": {"hexsha": "07ccea0b39e6328e4a9b7b78b7df83b6aacdc6b4", "size": 8768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/saxquantizer.hpp", "max_stars_repo_name": "newusers0/210529SAPLA", "max_stars_repo_head_hexsha": "35ec5253351ea6f373f3495e081769583355fd2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T12:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:09.000Z", "max_issues_repo_path": "lib/saxquantizer.hpp", "max_issues_repo_name": "newusers0/210529SAPLA", "max_issues_repo_head_hexsha": "35ec5253351ea6f373f3495e081769583355fd2c", "max_issues_repo_licenses": ["MIT"], "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/saxquantizer.hpp", "max_forks_repo_name": "newusers0/210529SAPLA", "max_forks_repo_head_hexsha": "35ec5253351ea6f373f3495e081769583355fd2c", "max_forks_repo_licenses": ["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.8134556575, "max_line_length": 162, "alphanum_fraction": 0.6208941606, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5855895664954546}}
{"text": "#include \"../bleichenbacher.h\"\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZ.h>\n#include <vector>\n#include <tuple>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\nusing namespace NTL;\n\nvoid loadSigs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples);\nZZ MSBguessFromM(int m, int l, ZZ mod);\n\nint main(int argc, char *argv[])\n{\n\tvector<tuple<ZZ_p, ZZ_p, ZZ_p>> rsmTuples;\n\tvector<tuple<ZZ_p, ZZ_p>> hcPairs;\n\tvector<tuple<int, double>> mValues;\n\tZZ guess;\n\n\t/* Initialize NTL modulus for secp160r1.\n\t   n = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF 7FFFFFFF\n\t   Citation: http://www.secg.org/SEC2-Ver-1.0.pdf */\n\tZZ mod;\n\tmod = to_ZZ(\"1461501637330902918203684832716283019653785059327\");\n\tZZ_p::init(mod);\n\n\t/* Load the (r,s,H(m)) tupples */\n\tcout << \"[+] Loading (r,s,H(m)) tupples...\\n\";\n\tloadSigs(&rsmTuples);\n\n\t/*\n\t *\tRound 1\n\t */\n\n\t/* Make (h,c) pairs */\n\tcout << \"[+] Making (h,c) pairs for round 1...\\n\";\n\thcFromRs(&rsmTuples, &hcPairs);\n\n\t/* Sort & Diff - we must get |c_i| <= 30 bits */\n\tcout << \"[+] Starting sort & diff for round 1...\\n\";\n\tsortAndDiff(&hcPairs, 27, 20);\n\tcout << \"\\t\" << hcPairs.size() << \" pairs left.\\n\";\n\n\t/* Get max m value */\n\tcout << \"[+] Finding top ten bias:MSB guesses for round 1...\\n\";\n\tmValues = maxM(&hcPairs, 27);\n\t\n\tfor(int i = 0; i < 10; i++)\n\t{\n\t\tguess = MSBguessFromM(get<0>(mValues[i]), 27, mod);\n\t\tcout << \"\\t\" << get<1>(mValues[i]) << \" : \" << guess << \"\\n\";\n\t}\n\n\tcout << \"[+] Average bias for round 1: \" << avgBias() << \"\\n\";\n\tcout << \"[+] Standard deviation of round 1 bias: \" << stdDevBias() \n\t\t<< \"\\n\";\n\t\n\thcPairs.clear();\n\n\n\t/*\n\t *\tRound 2\n\t *\n\t *\tAll rounds after round 1 should look like this.\n\t */\n\n\t/* In your implementation get the real 20 MSBs from round 1 \n\tresults... */\n\n\tcout << \"[+] Reinjecting correct 20 MSBs for demonstration... :P\" \n\t\t<< \"\\n\";\n\n\t// >>> bin(991662256230238939367140194553270109876310963800)[:22]\n\t// '0b10101101101100111010'\n\t// >>> int('10101101101100111010', 2)\n\t// 711482\n\n\tZZ knownBits;\n\tknownBits = 711482;\n\n\t/* Make (h,c) pairs */\n\tcout << \"[+] Making (h,c) pairs for round 2...\\n\";\n\thcFromRs(&rsmTuples, &hcPairs, 20, knownBits);\n\n\t/* Sort & Diff - we must get |c_i| <= 30 bits */\n\tcout << \"[+] Starting sort & diff for round 2...\\n\";\n\tsortAndDiff(&hcPairs, 27, 20);\n\tcout << \"\\t\" << hcPairs.size() << \" pairs left.\\n\";\n\t\n\t/* Get max m value */\n\tcout << \"[+] Finding top ten bias:MSB guesses for round 2...\\n\";\n\tmValues = maxM(&hcPairs, 20, 27);\n\n\tfor(int i = 0; i < 10; i++)\n\t{\n\t\tguess = MSBguessFromM(get<0>(mValues[i]), 27, mod);\n\t\tcout << \"\\t\" << get<1>(mValues[i]) << \" : \" << guess << \"\\n\";\n\t}\n\n\tcout << \"[+] Average bias for round 2: \" << avgBias() << \"\\n\";\n\tcout << \"[+] Standard deviation of round 2 bias: \" << stdDevBias() \n\t\t<< \"\\n\";\n\t\n\thcPairs.clear();\n}\n\nZZ MSBguessFromM(int m, int l, ZZ mod)\n{\n\tZZ zz_m, guess;\n\n\tzz_m = m;\n\tmul(guess, m, mod);\n\n\tguess >>= l;\n\t\n\treturn guess;\n}\n\nvoid loadSigs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples)\n{\n\tifstream in(\"rsmTuples\");\n\tstring line;\n\n\twhile(getline(in, line))\n\t{\n\t\tstring r, s, m;\n\t\tZZ zz_r, zz_s, zz_m;\n\t\tstringstream lineStream(line);\n\n\t\tlineStream >> r;\n\t\tlineStream >> s;\n\t\tlineStream >> m;\n\n\t\tconv(zz_r, r.c_str());\n\t\tconv(zz_s, s.c_str());\n\t\tconv(zz_m, m.c_str());\n\n\t\trsmTuples->push_back(\n\t\t\tmake_tuple(\n\t\t\t\tto_ZZ_p(zz_r),\n\t\t\t\tto_ZZ_p(zz_s),\n\t\t\t\tto_ZZ_p(zz_m)\n\t\t\t)\n\t\t);\n\t}\n}\n", "meta": {"hexsha": "6ce72ca614192a2a7430ec719457dfe848b3361c", "size": 3347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example.cpp", "max_stars_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_stars_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T22:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T22:25:06.000Z", "max_issues_repo_path": "example/example.cpp", "max_issues_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_issues_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_issues_repo_licenses": ["MIT"], "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/example.cpp", "max_forks_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_forks_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T02:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:07:29.000Z", "avg_line_length": 22.3133333333, "max_line_length": 68, "alphanum_fraction": 0.6011353451, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.585589561473351}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <gauss/internal/scopedHostPtr.h>\n#include <gauss/regression.h>\n#include <gauss/statistics.h>\n\n#include <boost/math/distributions/students_t.hpp>\n\nconstexpr auto EPSILON = 1e-20;\n\nvoid gauss::regression::linear(const af::array &xss, const af::array &yss, af::array &slope, af::array &intercept,\n                               af::array &rvalue, af::array &pvalue, af::array &stderrest) {\n    auto n = xss.dims(0);\n\n    af::array meanX = af::mean(xss, 0);\n    af::array meanY = af::mean(yss, 0);\n\n    af::array sumSquares = af::array(2, 2, xss.dims(1), xss.type());\n\n    // Assuming xss and yss contain the same number of time series\n    for (int i = 0; i < xss.dims(1); i++) {\n        sumSquares(af::span, af::span, i) =\n            gauss::statistics::covariance(af::join(1, xss(af::span, i), yss(af::span, i)));\n    }\n\n    af::array ssxm = sumSquares(0, 0, af::span);\n    ssxm = af::reorder(ssxm, 0, 2, 1, 3);\n    af::array ssxym = sumSquares(0, 1, af::span);\n    ssxym = af::reorder(ssxym, 0, 2, 1, 3);\n    af::array ssyxm = sumSquares(1, 0, af::span);\n    ssyxm = af::reorder(ssyxm, 0, 2, 1, 3);\n    af::array ssym = sumSquares(1, 1, af::span);\n    ssym = af::reorder(ssym, 0, 2, 1, 3);\n\n    af::array rNum = ssxym;\n\n    af::array rDen = af::sqrt(ssxm * ssym);\n\n    af::array r = af::transpose(af::constant(0, xss.dims(1), xss.type()));\n    r = (rDen > 0.0) * rNum / rDen;\n    r = af::min(r, 1.0);\n    r = af::max(r, -1.0);\n    rvalue = r;\n\n    auto df = n - 2;\n    slope = rNum / ssxm;\n    intercept = meanY - slope * meanX;\n\n    boost::math::students_t dist(df);\n\n    af::array t = r * af::sqrt(df / ((1.0 - r + EPSILON) * (1.0 + r + EPSILON)));\n    // Using boost to compute the CDF of the T-Student distribution\n    // It would be better to move this computation to the GPU\n    // Converting to af::dtype::f32 and back to the original type later on\n    // to avoid templating this function and all the ones using it\n    auto aux = gauss::utils::makeScopedHostPtr(af::abs(t).as(af::dtype::f32).host<float>());\n    for (long i = 0; i < t.dims(1); i++) {\n        aux[i] = 2.0f * (1.0f - static_cast<float>(boost::math::cdf(dist, aux[i])));\n    }\n    pvalue = af::array(1, t.dims(1), aux.get()).as(xss.type());\n    stderrest = af::sqrt((1 - af::pow(r, 2)) * ssym / ssxm / df);\n}\n", "meta": {"hexsha": "c441d07a29622ab2f7aa7f6ab74f195abde186e5", "size": 2512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/regression.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/regression.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/regression.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9411764706, "max_line_length": 114, "alphanum_fraction": 0.5927547771, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.585589544038677}}
{"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 integrator.hpp\n * @author Boston Cleek\n * @date 28 Oct 2020\n * @brief Numerical integration methods\n */\n#ifndef INTEGRATOR_HPP\n#define INTEGRATOR_HPP\n\n#include <cmath>\n#include <functional>\n#include <armadillo>\n\n#include <ergodic_exploration/collision.hpp>\n#include <ergodic_exploration/numerics.hpp>\n\nnamespace ergodic_exploration\n{\nusing arma::linspace;\nusing arma::mat;\nusing arma::span;\nusing arma::vec;\n\n/**\n * @brief Function representing the time derivatve of the co-state variable\n * @details inputs are co-state, ergodic measure derivatve, barrier derivatve,\n * and the jacobian of the dynamics w.r.t state\n */\ntypedef std::function<vec(const vec&, const vec&, const vec&, const mat&)> CoStateFunc;\n\n/** @brief 4th order Runge-Kutta integration */\nclass RungeKutta\n{\npublic:\n  /**\n   * @brief Constructor\n   * @param dt - time step\n   */\n  RungeKutta(double dt);\n\n  /**\n   * @brief Simulate the dynamics forward in time\n   * @param model - dynamic model\n   * @param x0 - initial state\n   * @param ut - control signal (each column is applied at a single time step)\n   * @param horizon - length of trajectory in time\n   * @return trajectory\n   * @details the boundary condition is not added to the trajectory\n   */\n  template <class ModelT>\n  mat solve(const ModelT& model, const vec& x0, const mat& ut, double horizon) const;\n\n  /**\n   * @brief Solve the co-state variable backwards in time\n   * @param func - time derivatve of co-state variable\n   * @param model - dynamic model\n   * @param rhoT - co-state variable terminal condition (zero vector)\n   * @param xt - forward porpagated dynamic model trajectory\n   * @param ut - control signal\n   * @param edx - gradient of the ergodic metric for each state in xt\n   * @param bdx - derivatve of barrier function for each state in xt\n   * @param horizon - length of trajectory in time\n   * @return co-state variable solution\n   * @details co-state is sorted from [t0 tf] no need to index backwards and the\n   * boundary condition is not added to the trajectory\n   */\n  template <class ModelT>\n  mat solve(const CoStateFunc& func, const ModelT& model, const vec& rhoT, const mat& xt,\n            const mat& ut, const mat& edx, const mat& bdx, double horizon) const;\n\n  /**\n   * @brief Performs one step of RK4 forward in time\n   * @param model - dynamic model\n   * @param x - state\n   * @param u - control\n   * @return new state\n   */\n  template <class ModelT>\n  vec step(const ModelT& model, const vec& x, const vec& u) const;\n\n  /**\n   * @brief Performs one step of RK4 backwards in time\n   * @param func - time derivatve of the co-state variable\n   * @param rho - co-state variable\n   * @param gdx - gradient of the ergodic metric\n   * @param dbar - derivatve of barrier function for a state\n   * @param fdx - jacobian of the model with respect to the control\n   * @return co-state variable\n   * @details The robot model is used to compose A = D1[f(x,u)].\n   * The columns of xt, ut, and edx correspond to\n   * the state, control, or derivative at a given time.\n   */\n  vec step(const CoStateFunc& func, const vec& rho, const vec& gdx, const vec& dbar,\n           const mat& fdx) const;\n\nprivate:\n  double dt_;  // time step\n};\n\nRungeKutta::RungeKutta(double dt) : dt_(dt)\n{\n}\n\ntemplate <class ModelT>\nmat RungeKutta::solve(const ModelT& model, const vec& x0, const mat& ut,\n                      double horizon) const\n{\n  // TODO: Add terminal x0?\n  vec x = x0;\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt_));\n  mat xt(x.n_rows, steps);\n\n  for (unsigned int i = 0; i < steps; i++)\n  {\n    x = step(model, x, ut.col(i));\n    x(2) = normalize_angle_PI(x(2));\n    xt.col(i) = x;\n  }\n\n  return xt;\n}\n\ntemplate <class ModelT>\nmat RungeKutta::solve(const CoStateFunc& func, const ModelT& model, const vec& rhoT,\n                      const mat& xt, const mat& ut, const mat& edx, const mat& bdx,\n                      double horizon) const\n{\n  // TODO: Add terminal p(T)?\n  vec rho = rhoT;\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt_));\n  mat rhot(rho.n_rows, steps);\n\n  // Iterate backwards\n  // this way rhot from t0 to tf in the returned matrix\n  for (unsigned int i = steps; i-- > 0;)\n  {\n    // Index states, controls, and ergodic measures at end of array\n    rho = step(func, rho, edx.col(i), bdx.col(i), model.fdx(xt.col(i), ut.col(i)));\n    rhot.col(i) = rho;\n  }\n\n  return rhot;\n}\n\ntemplate <class ModelT>\nvec RungeKutta::step(const ModelT& model, const vec& x, const vec& u) const\n{\n  const vec k1 = model(x, u);\n  const vec k2 = model(x + dt_ * (0.5 * k1), u);\n  const vec k3 = model(x + dt_ * (0.5 * k2), u);\n  const vec k4 = model(x + dt_ * k3, u);\n  return x + (dt_ / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4);\n}\n\nvec RungeKutta::step(const CoStateFunc& func, const vec& rho, const vec& gdx,\n                     const vec& dbar, const mat& fdx) const\n{\n  const vec k1 = func(rho, gdx, dbar, fdx);\n  const vec k2 = func(rho - dt_ * (0.5 * k1), gdx, dbar, fdx);\n  const vec k3 = func(rho - dt_ * (0.5 * k2), gdx, dbar, fdx);\n  const vec k4 = func(rho - dt_ * k3, gdx, dbar, fdx);\n  return rho - dt_ / 6.0 * (k1 + 2.0 * k2 + 2.0 * k3 + k4);\n}\n\nclass RungeKutta45\n{\npublic:\n  RungeKutta45(double hmax, double hmin, double epsilon, unsigned int max_iter);\n\n  template <class ModelT>\n  bool solve(mat& xt, const ModelT& model, const vec& x0, const mat& ut, double dt,\n             double horizon) const;\n\n  template <class ModelT>\n  bool solve(mat& rhot, const CoStateFunc& func, const ModelT& model, const vec& rhoT,\n             const mat& xt, const mat& ut, const mat& edx, const mat& bdx, double dt,\n             double horizon) const;\n\n  template <class ModelT>\n  double step(vec& x_new, const ModelT& model, const vec& x, const vec& u, double h) const;\n\n  double step(vec& rho_new, const CoStateFunc& func, const vec& rho, const vec& gdx,\n              const vec& dbar, const mat& fdx, double h) const;\n\nprivate:\n  double hmin_, hmax_;\n  double epsilon_;\n  unsigned int max_iter_;\n};\n\nRungeKutta45::RungeKutta45(double hmin, double hmax, double epsilon, unsigned int max_iter)\n  : hmin_(hmin), hmax_(hmax), epsilon_(epsilon), max_iter_(max_iter)\n{\n}\n\ntemplate <class ModelT>\nbool RungeKutta45::solve(mat& xt, const ModelT& model, const vec& x0, const mat& ut,\n                         double dt, double horizon) const\n{\n  // TODO: how to initialize h?\n  auto h = (hmax_ + hmin_) / 2.0;\n  // auto h = hmin_;\n  vec x = x0;\n\n  // desired length of trajectory\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt));\n  const vec tvec = linspace(0.0, horizon, steps);\n\n  // allocate memory for trajectory based on max possible steps\n  const auto max_steps = static_cast<unsigned int>(horizon / hmin_) + 1;\n  mat xt_max(x0.n_rows, max_steps);\n  vec tvec_max(max_steps);\n\n  // add x0\n  xt_max.col(0) = x0;\n  tvec_max(0) = 0.0;\n\n  vec x_new;\n  auto t = 0.0;\n  unsigned int stored = 1;\n  unsigned int iter = 0;\n  bool flag = 0;\n  while (!flag)\n  {\n    const auto i = static_cast<unsigned int>(\n        std::floor(std::round(static_cast<double>(steps - 1) * std::abs(t / horizon))));\n    // std::cout << \"i: \" << i << std::endl;\n\n    const auto r = step(x_new, model, x, ut.col(i), h);\n    // std::cout << \"r: \" << r << std::endl;\n\n    if (r < epsilon_ || almost_equal(r, epsilon_))\n    {\n      x = x_new;\n      xt_max.col(stored) = x;\n\n      t += h;\n      tvec_max(stored) = t;\n\n      stored++;\n    }\n\n    h *= 0.84 * std::pow(epsilon_ / r, 0.25);\n    h = std::clamp(h, hmin_, hmax_);\n\n    if (t > horizon || almost_equal(t, horizon))\n    {\n      flag = 1;\n    }\n\n    // detect final time\n    else if (t + h > horizon)\n    {\n      h = horizon - t;\n    }\n\n    // std::cout << \"t: \" << t << std::endl;\n    // std::cout << \"h: \" << h << std::endl;\n\n    if (iter == max_iter_)\n    {\n      std::cout << \"WARNING: max iterations reached \" << std::endl;\n      return false;\n    }\n\n    iter++;\n  }\n\n  // xt_max.cols(0, stored-1).t().print(\"traj\");\n  // tvec_max.rows(0, stored - 1).print(\"t rk45\");\n  // tvec.print(\"t desired\");\n  //\n  // std::cout << \"tvec_max: \" << tvec_max.n_rows << std::endl;\n  // std::cout << \"tvec: \" << tvec.n_rows << std::endl;\n  //\n  // std::cout << \"steps: \" << steps << std::endl;\n  // std::cout << \"stored: \" << stored << std::endl;\n\n  // fit quartic polynomials\n  xt.resize(x0.n_rows, steps);\n  for (unsigned int i = 0; i < x0.n_rows; i++)\n  {\n    const vec p =\n        polyfit(tvec_max.rows(0, stored - 1), xt_max(span(i, i), span(0, stored - 1)), 4);\n    // p.print(\"p\");\n    xt.row(i) = polyval(p, tvec).t();\n  }\n\n  return true;\n}\n\ntemplate <class ModelT>\ndouble RungeKutta45::step(vec& x_new, const ModelT& model, const vec& x, const vec& u,\n                          double h) const\n{\n  const vec k1 = h * model(x, u);\n\n  const vec k2 = h * model(x + ((1.0 / 4.0) * k1), u);\n\n  const vec k3 = h * model(x + ((3.0 / 32.0) * k1) + ((9.0 / 32.0) * k2), u);\n\n  const vec k4 = h * model(x + ((1932.0 / 2197.0) * k1) - ((7200.0 / 2197.0) * k2) +\n                               ((7296.0 / 2197.0) * k3),\n                           u);\n  const vec k5 = h * model(x + ((439.0 / 216.0) * k1) - (8.0 * k2) +\n                               ((3680.0 / 513.0) * k3) - ((845.0 / 4104.0) * k4),\n                           u);\n  const vec k6 =\n      h * model(x - ((8.0 / 27.0) * k1) + (2.0 * k2) - ((3544.0 / 2565.0) * k3) +\n                    ((1859.0 / 4104.0) * k4) - ((11.0 / 40.0) * k5),\n                u);\n\n  x_new = x + ((25.0 / 216.0) * k1) + ((1408.0 / 2565.0) * k3) +\n          ((2197.0 / 4101.0) * k4) - ((1.0 / 5.0) * k5);\n\n  const vec z = x + ((16.0 / 135.0) * k1) + ((6656.0 / 12825.0) * k3) +\n                ((28561.0 / 56430.0) * k4) - ((9.0 / 50.0) * k5) + ((2.0 / 55.0) * k6);\n\n  // std::cout << \"max diff: \" << max(abs(z - x_new)) << std::endl;\n  // std::cout << \"error norm: \" << norm(z - x_new, 2) << std::endl;\n\n  return max(abs(z - x_new)) / h;\n  // return min(abs(z - x_new)) / h;\n}\n\ntemplate <class ModelT>\nbool RungeKutta45::solve(mat& rhot, const CoStateFunc& func, const ModelT& model,\n                         const vec& rhoT, const mat& xt, const mat& ut, const mat& edx,\n                         const mat& bdx, double dt, double horizon) const\n{\n  // TODO: how to initialize h?\n  // auto h = (hmax_ + hmin_) / 2.0;\n  auto h = hmin_;\n  vec rho = rhoT;\n\n  // desired length of trajectory\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt));\n  const vec tvec = linspace(0.0, horizon, steps);\n\n  // allocate memory for trajectory based on max possible steps\n  const auto max_steps = static_cast<unsigned int>(horizon / hmin_) + 1;\n  mat rhot_max(rhoT.n_rows, max_steps);\n  vec tvec_max(max_steps);\n\n  // add x0\n  rhot_max.col(0) = rhoT;\n  tvec_max(0) = horizon;\n\n  vec rho_new;\n  auto t = horizon;\n  unsigned int stored = 1;\n  unsigned int iter = 0;\n  bool flag = 0;\n  while (!flag)\n  {\n    const auto i = static_cast<unsigned int>(\n        std::floor(std::round(static_cast<double>(steps - 1) * std::abs(t / horizon))));\n    // std::cout << \"i: \" << i << std::endl;\n\n    const auto r = step(rho_new, func, rho, edx.col(i), bdx.col(i),\n                        model.fdx(xt.col(i), ut.col(i)), h);\n    // std::cout << \"r: \" << r << std::endl;\n\n    if (r < epsilon_ || almost_equal(r, epsilon_))\n    {\n      rho = rho_new;\n      rhot_max.col(stored) = rho;\n\n      t -= h;\n      tvec_max(stored) = t;\n\n      stored++;\n    }\n\n    h *= 0.84 * std::pow(epsilon_ / r, 0.25);\n    h = std::clamp(h, hmin_, hmax_);\n\n    if (t < 0.0 || almost_equal(t, 0.0))\n    {\n      flag = 1;\n    }\n\n    // detect final time\n    else if (t - h < 0.0)\n    {\n      h = t;\n    }\n\n    // std::cout << \"t: \" << t << std::endl;\n    // std::cout << \"h: \" << h << std::endl;\n\n    if (iter == max_iter_)\n    {\n      std::cout << \"WARNING: max iterations reached \" << std::endl;\n      return false;\n    }\n\n    iter++;\n  }\n\n  // rhot_max.cols(0, stored-1).t().print(\"rho traj\");\n  // tvec_max.rows(0, stored - 1).print(\"t rk45\");\n  // tvec.print(\"t desired\");\n  //\n  // std::cout << \"tvec_max: \" << tvec_max.n_rows << std::endl;\n  // std::cout << \"tvec: \" << tvec.n_rows << std::endl;\n  //\n  // std::cout << \"steps: \" << steps << std::endl;\n  // std::cout << \"stored: \" << stored << std::endl;\n\n  // fit quartic polynomials\n  rhot.resize(rho.n_rows, steps);\n  for (unsigned int i = 0; i < rhoT.n_rows; i++)\n  {\n    const vec p = polyfit(tvec_max.rows(0, stored - 1),\n                          rhot_max(span(i, i), span(0, stored - 1)), 4);\n    // p.print(\"p\");\n    rhot.row(i) = polyval(p, tvec).t();\n  }\n\n  return true;\n}\n\ndouble RungeKutta45::step(vec& rho_new, const CoStateFunc& func, const vec& rho,\n                          const vec& gdx, const vec& dbar, const mat& fdx, double h) const\n{\n  const vec k1 = -h * func(rho, gdx, dbar, fdx);\n\n  const vec k2 = -h * func(rho + ((1.0 / 4.0) * k1), gdx, dbar, fdx);\n\n  const vec k3 =\n      -h * func(rho + ((3.0 / 32.0) * k1) + ((9.0 / 32.0) * k2), gdx, dbar, fdx);\n\n  const vec k4 = -h * func(rho + ((1932.0 / 2197.0) * k1) - ((7200.0 / 2197.0) * k2) +\n                               ((7296.0 / 2197.0) * k3),\n                           gdx, dbar, fdx);\n\n  const vec k5 = -h * func(rho + ((439.0 / 216.0) * k1) - (8.0 * k2) +\n                               ((3680.0 / 513.0) * k3) - ((845.0 / 4104.0) * k4),\n                           gdx, dbar, fdx);\n\n  const vec k6 =\n      -h * func(rho - ((8.0 / 27.0) * k1) + (2.0 * k2) - ((3544.0 / 2565.0) * k3) +\n                    ((1859.0 / 4104.0) * k4) - ((11.0 / 40.0) * k5),\n                gdx, dbar, fdx);\n\n  rho_new = rho + ((25.0 / 216.0) * k1) + ((1408.0 / 2565.0) * k3) +\n            ((2197.0 / 4101.0) * k4) - ((1.0 / 5.0) * k5);\n\n  const vec z = rho + ((16.0 / 135.0) * k1) + ((6656.0 / 12825.0) * k3) +\n                ((28561.0 / 56430.0) * k4) - ((9.0 / 50.0) * k5) + ((2.0 / 55.0) * k6);\n\n  // std::cout << \"max diff: \" << max(abs(z - rho_new)) << std::endl;\n  // std::cout << \"error norm: \" << norm(z - rho_new, 2) << std::endl;\n\n  return max(abs(z - rho_new)) / h;\n}\n\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "c2128f3bb6b2f672312519d940381e637ce471e5", "size": 15842, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/integrator.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/integrator.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/integrator.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": 32.1991869919, "max_line_length": 91, "alphanum_fraction": 0.5835121828, "num_tokens": 5014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.5855652560272379}}
{"text": "\n#include \"EventShapes/EventShapes.h\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <math.h>\n\nusing namespace Eigen;\n\nClassImp(EventShapes)\n\nEventShapes::EventShapes()\n\t: ndims(2),\n\t  m_thrust_axis(nullptr),\n\t  m_thrust_major_axis(nullptr),\n\t  m_thrust_minor_axis(nullptr) {}\n\nEventShapes::EventShapes(const std::vector<std::vector<float>>& momenta, unsigned int ndims) \n\t: ndims(ndims),\n\t  m_thrust_axis(nullptr),\n\t  m_thrust_major_axis(nullptr),\n\t  m_thrust_minor_axis(nullptr) {\n\n\tm_three_momenta.reserve(momenta.size());\n\t// for (auto& p : momenta) {\n\t// \tVector3f tvector;\n\t// \tif (p.size() ==  2) {\n\t// \t\ttvector = Vector3f(p[0], p[1], 0.);\n\t// \t\tndims = 2;\n\t// \t} else {\n\t// \t\ttvector = Vector3f(p[0], p[1], p[2]);\n\t// \t\tndims = 3;\n\t// \t}\n\t// \tm_three_momenta.push_back(tvector);\n\t// }\n\n\t// If problem is presented in 2d\n\tif (ndims == 2) {\n\t\tfor (auto& p : momenta) {\n\t\t\tm_three_momenta.push_back(Vector3f(p[0], p[1], 0.));\n\t\t}\n\n\t// Else if problem is presented in 3d\n\t} else {\n\t\tfor (auto& p : momenta) {\n\t\t\tm_three_momenta.push_back(Vector3f(p[0], p[1], p[2]));\n\t\t}\n\t}\n\n\tm_ntracks = m_three_momenta.size();\n\tm_min_ntracks = ndims;\n\n\tm_randg = TRandom{};\n}\n\ndouble EventShapes::calcThrustValue(const std::vector<Vector3f>& pvec, const Vector3f& axis) {\n\t/* Function that calculates the thrust value of a set of input vectors \n\t * 'pvec' about the thrust axis 'axis'\n\t */\n\n\tdouble t_num = 0.;\n\tdouble t_denom = 0.;\n\tfor (const auto& p : pvec) {\n\t\tt_num += fabs(axis.dot(p));\n\t\tt_denom += p.norm();\n\t}\n\tdouble thrust = t_num > 0 ? t_num / t_denom : 0.;\n\n\treturn thrust;\n}\n\nvoid EventShapes::compare_calcT() {\n\n\t// Calculate thrust axis by each method\n\t// std::pair<Vector3f, double> axis_new_ret = calcT_new(m_three_momenta);\n\tstd::pair<Vector3f, double> axis_orig_ret = calcT_orig(m_three_momenta);\n\n\t// Vector3f axis_new = axis_new_ret.first;\n\t// Vector3f axis_orig = axis_orig_ret.first;\n\n\t//<- Commented while many differences are found\n\t// for (unsigned int i = 0; i < 3; i++) {\n\t// \tif (fabs(fabs(axis_new[i]) - fabs(axis_orig[i])) > 1e-10) {\n\t// \t\tstd::cout << \"Difference found between two methods of thrust calculation\" << std::endl;\n\t// \t\tstd::cout << \"The new and original methods yield, respectively:\" << std::endl;\n\t// \t\taxis_new.rint();\n\t// \t\taxis_orig.rint();\n\t// \t\tbreak;\n\t// \t}\n\t// }\n\n\t// Set member data variable\n\tif (axis_orig_ret.first == Vector3f()) m_thrust_axis = nullptr;\n\telse m_thrust_axis = new Vector3f(axis_orig_ret.first);\n\tm_thrust = axis_orig_ret.second;\n}\n\nconst std::pair<Vector3f, double> EventShapes::calcT_new(const std::vector<Vector3f>& pvec) {\n\t/* Function that attempts to calculate the thrust axis more rigorously\n\t * based on the intuition that all 2^(n - 1) combinations of input \n\t * vectors and their inverses do not need to be tested, and that the \n\t * combinations that do need to be tested comprise a subset of the \n\t * 2^(n - 1) combinations that can be found.\n\t *\n\t * This method partitions the set of input vectors into n hemispheres \n\t * by dot product with each of the n input vectors in turn, builds \n\t * the Longest Vector Sum in each hemisphere, and takes the axis \n\t * that corresponds to the greatest value of thrust as the thrust axis.\n\t *\n\t * This method has produced the same thrust axis as the original \n\t * algorithm, implemented here as calcT_orig().  But it is yet to be \n\t * proven that this method is perfectly accurate, therefore it is \n\t * disfavoured for now.\n\t */\n\n\t// Do not consider the case of zero tracks\n\tif (m_ntracks < m_min_ntracks) {\n\t\treturn std::pair<Vector3f, double> (Vector3f(), -1.);\n\t}\n\n\tstd::vector<Vector3f> tvecs;\n\tstd::vector<double> tvals;\n\n\tfor (unsigned int j = 0; j < pvec.size(); j++) {\n\n\t\t// Transform initial vector into thrust axis\n\t\tVector3f axis (0, 0, 0);\n\n\t\t// Define a hemisphere by dot product with each input vector\n\t\tVector3f init (pvec[j]);\n\n\t\tfor (unsigned int i = 0; i < pvec.size(); i++) {\n\t\t\tinit.dot(pvec[i]) >= 0. ? axis += pvec[i] : axis -= pvec[i];\n\t\t}\n\t\taxis /= axis.norm();\n\n\t\t// oint in the direction of greatest energy flow\n\t\tdouble eflow = 0.;\n\t\tfor (const auto& p : pvec) eflow += axis.dot(p);\n\t\tif (eflow < 0.) axis = -axis;\n\n\t\t// Get value of thrust about the calculated thrust axis\n\t\tdouble t = calcThrustValue(pvec, axis);\n\n\t\ttvecs.push_back(axis);\n\t\ttvals.push_back(t);\n\t}\n\n\t// Find the best thrust axis\n\tdouble thrust = 0.;\n\tVector3f thrust_axis;\n\tfor (unsigned int i = 0; i < tvecs.size(); i++) {\n\t\tif (tvals[i] > thrust) {\n\t\t\tthrust = tvals[i];\n\t\t\tthrust_axis = tvecs[i];\n\t\t}\n\t}\n\n\treturn std::pair<Vector3f, double> (thrust_axis, thrust);\n}\n\nconst std::pair<Vector3f, double> EventShapes::calcT_orig(const std::vector<Vector3f>& three_momenta) {\n\t/* Method based on the original, validated algorithm supplied by \n\t * Deepak Kar and Sukanya Sinha.  Based on the iterative method \n\t * described in the ythia 6.4 Manual.\n\t *\n\t * This implementation starts from n random initial axes to build \n\t * a resultant vector as a candidate thrust axis.  The normalised \n\t * resultant that has the greatest value of thrust is taken as the \n\t * thrust axis.\n\t */\n\n\t// Alias vector of input three-vectors\n\tstd::vector<Vector3f> pvec = three_momenta;\n\n\t// Do not consider the case of zero tracks\n\tif (m_ntracks < m_min_ntracks) {\n\t\treturn std::pair<Vector3f, double> (Vector3f(), -1.);\n\t}\n\n\t// Get thrust axis\n\tVector3f tvec;\n\tdouble best_thrust = 0.;\n\n\t// Start from multiple random initial axes\n\tfor (unsigned int i = 0; i < pow(pvec.size(), 2); i++) {\n\n\t\tdouble x, y, z;\n\t\tdouble r = 1.;\n\t\tm_randg.Sphere(x, y, z, r);\n\t\tVector3f init (x, y, z);\n\n\t\t// Vector3f init (m_randg.Rndm(), m_randg.Rndm(), m_randg.Rndm());\n\t\tVector3f axis (init);\n\n\t\t// Iterate the axis to local maximum\n\t\tdouble diff = 999.;\n\t\twhile (diff > 1e-5) {\n\t\t\tVector3f foo(0, 0, 0);\n\t\t\tfor (const auto& p : pvec) {\n\t\t\t\taxis.dot(p) > 0 ? foo += p : foo -= p;\n\t\t\t}\n\t\t\tfoo /= foo.norm();\n\t\t\tdiff = (axis - foo).norm();\n\t\t\taxis = foo;\n\t\t}\n\n\t\t// Keep the axis if it increases the thrust value\n\t\tdouble thrust = calcThrustValue(pvec, axis);\n\t\tif (thrust > best_thrust) {\n\t\t\ttvec = axis;\n\t\t\tbest_thrust = thrust;\n\t\t}\n\t}\n\n\t// oint in the direction of greatest energy flow\n\tdouble eflow = 0.;\n\tfor (const auto& p : pvec) eflow += tvec.dot(p);\n\tif (eflow <= 0.) tvec = -tvec;\n\n\treturn std::pair<Vector3f, double> (tvec, best_thrust);\n}\n\nvoid EventShapes::calcThrust() {\n\t/* Function that calculates the thrust proper axis and values.\n\t * The class member data are set with the calculated values.\n\t */\n\n\tstd::pair<Vector3f, double> pair = calcT_orig(m_three_momenta);\n\n\t// Check validity of results\n\tif (pair.first == Vector3f()) { // Calculation unsuccessful\n\t\tm_thrust_axis = nullptr;\n\t\tm_thrust = -1.;\n\t} else {\n\t\tm_thrust_axis = new Vector3f(pair.first);\n\t\tm_thrust = pair.second;\n\t}\n\n\tstd::cout << \"Thrust axis: \" << std::endl;\n\tif (m_thrust_axis) {\n\t\tstd::cout << *m_thrust_axis << std::endl;\n\t} else {\n\t\tstd::cout << \"0\" << std::endl;\n\t}\n\n}\n\nvoid EventShapes::calcThrustMajor() {\n\t/* Function that calculates the thrust major axis and value.\n\t * This is the axis in the plane perpendicular to the thrust axis \n\t * along which the energy flow is greatest in that plane.\n\t * hys. Rev. Lett. 43, 830 for a nice discussion.\n\t */\n\n\t// // Do not consider the case of zero tracks\n\t// if (m_ntracks < m_min_ntracks) {\n\t// \tm_thrust_major_axis = nullptr;\n\t// \tm_thrust_major = -1.;\n\t// \treturn;\n\t// }\n\n\tconst std::vector<Vector3f> pvec = m_three_momenta;\n\n\t// Function depends on the thrust axis\n\tif (!m_thrust_axis) calcThrust();\n\n\tconst Vector3f thrust_axis (*m_thrust_axis);\n\tstd::cout << \"Thrust axis used for thrust major axis: \" << std::endl;\n\tstd::cout << thrust_axis << std::endl;\n\n\t// // Check that the thrust major axis exists\n\t// // i.e. that there are vectors in the plane perp to the thrust axis\n\t// // Unnecessary except when n input vectors < 3\n\t// if (m_ntracks < 3) {\n\t// \tbool no_thrust_major (true);\n\t// \tfor (const auto& p : pvec) {\n\t// \t\tif ((p - p.dot(thrust_axis) * thrust_axis).squaredNorm() > 1e-10) {\n\t// \t\t\tno_thrust_major = false;\n\t// \t\t\tbreak;\n\t// \t\t}\n\t// \t}\n\n\t// \tif (no_thrust_major) {\n\t// \t\tm_thrust_major_axis = nullptr;\n\t// \t\tm_thrust_major = -1.;\n\t// \t\treturn;\n\t// \t}\n\t// }\n\n\t// roject input vectors into plane perpendicular to thrust axis proper\n\tstd::vector<Vector3f> pvec_perp;\n\tpvec_perp.reserve(pvec.size());\n\tfor (const auto& p : pvec) {\n\t\tpvec_perp.push_back(p - p.dot(thrust_axis) * thrust_axis);\n\t}\n\n\tstd::pair<Vector3f, double> thrust_major = calcT_orig(pvec_perp);\n\t// std::cout << \"Thrust major value, n, vector: \" << thrust_major.second << \", \" << pvec.size() << \", \";\n\t// thrust_major.first.rint();\n\n\tVector3f thrust_major_axis;\n\tif (thrust_major.first == Vector3f()) {\n\t\tm_thrust_major_axis = nullptr;\n\t\tm_thrust_major = -1.;\n\t\treturn;\n\t} else {\n\t\tthrust_major_axis = thrust_major.first;\n\t}\n\n\t// Sanity check\n\tif (fabs(thrust_axis.dot(thrust_major_axis)) > 1e-6) {\n\t\tstd::cout << \"Major axis not orthogonal to proper axis!\" << std::endl;\n\t\tstd::cout << fabs(thrust_axis.dot(thrust_major_axis)) << std::endl;\n\t}\n\n\t// Set class data members\n\tm_thrust_major_axis = new Vector3f(thrust_major.first);\n\tm_thrust_major = thrust_major.second;\n\n\tstd::cout << \"Thrust major axis: \" << std::endl;\n\tif (m_thrust_major_axis) {\n\t\tstd::cout << *m_thrust_major_axis << std::endl;\n\t} else {\n\t\tstd::cout << \"0\" << std::endl;\n\t}\n}\n\nvoid EventShapes::calcThrustMinor() {\n\t/* Function that calculates the thrust minor axis and value.\n\t * This axis is defined as being orthogonal to the thrust and \n\t * thrust major axes.\n\t * hys. Rev. Lett. 43, 830 for a nice discussion.\n\t */\n\n\t// Do not consider the case where the thrust or thrust major values were invalid\n\tif (m_thrust == -1. || m_thrust_major == -1.) {\n\t\tm_thrust_minor_axis = nullptr;\n\t\tm_thrust_minor = -1.;\n\t\treturn;\n\t}\n\n\tconst std::vector<Vector3f> pvec = m_three_momenta;\n\n\t// This function depends on the thrust and thrust major axes\n\tif (!m_thrust_major_axis) calcThrustMajor();\n\n\t// Alias the existing axes\n\tconst Vector3f thrust_axis = *m_thrust_axis;\n\tconst Vector3f thrust_major_axis = *m_thrust_major_axis;\n\n\tVector3f thrust_minor_axis = thrust_axis.cross(thrust_major_axis);\n\tdouble thrust_minor = calcThrustValue(pvec, thrust_minor_axis);\n\n\t// Sanity check\n\tif (fabs(thrust_axis.dot(thrust_minor_axis)) > 1e-10 || fabs(thrust_major_axis.dot(thrust_minor_axis)) > 1e-10) {\n\t\tstd::cout << \"Minor axis not orthogonal to major and proper!\" << std::endl;\n\t}\n\n\t// Set class data members\n\tm_thrust_minor_axis = new Vector3f(thrust_minor_axis);\n\tm_thrust_minor = thrust_minor;\n}\n\nvoid EventShapes::calcOblateness() {\n\t/* Function that calculates the oblateness about the thrust axis.\n\t */\n\n\t// This function depends on the major and minor thrust calculations\n\tif (!m_thrust_minor_axis) calcThrustMinor();\n\n\tm_oblateness = m_thrust_major - m_thrust_minor;\n}\n\nvoid EventShapes::calcBrd() {\n\t/* Function that calculates the event broadening with respect to \n\t * the thrust axis\n\t */\n\n\t// Do not consider the case of zero tracks\n\tif (m_ntracks < m_min_ntracks) {\n\t\tm_broadening = -1.;\n\t\treturn;\n\t}\n\n\t// Alias vector of input vectors\n\tconst std::vector<Vector3f> pvec = m_three_momenta;\n\n\t// Depends on the thrust axis\n\tif (!m_thrust_axis) calcT_orig(m_three_momenta);\n\n\t// Alias thrust axis\n\tconst Vector3f thrust_axis = *m_thrust_axis;\n\n\t// Calculate broadening in Up and Down hemispheres separately\n\tdouble B_U (0.), B_D (0.);\n\tdouble B_norm (0.);\n\t// std::cout << \"New event:\" << std::endl;\n\tfor (const auto& p : pvec) {\n\t\t// std::cout << \"Dot: \" << thrust_axis.Dot(p) << std::endl;\n\t\tB_norm += p.norm();\n\t\tif (thrust_axis.dot(p) > 0) {\n\t\t\tB_U += p.cross(thrust_axis).norm();\n\t\t} else {\n\t\t\tB_D += p.cross(thrust_axis).norm();\n\t\t}\n\t}\n\n\t// std::cout << \"B_D, B_D_norm = \" << B_D << \", \" << B_norm << std::endl;\n\t// std::cout << \"B_U, B_U_norm = \" << B_U << \", \" << B_norm << std::endl;\n\t// std::cout << std::endl;\n\n\tB_U = B_U > 0. ? B_U / B_norm : 0.;\n\tB_D = B_D > 0. ? B_D / B_norm : 0.;\n\n\tdouble B = B_D + B_U;\n\n\t// std::cout << \"Broadening: \" << B << std::endl;\n\n\tm_broadening = B;\n\n}\n\nvoid EventShapes::calcLinSph() {\n\t/* Function that calculates the sphericity tensor and its eigen\n\t * vectors and values.\n\t */\n\n\t// Alias vector of input vectors\n\tconst std::vector<Vector3f> pvec = m_three_momenta;\n\n\t// Set sphericities to dummy values\n\tm_lin_spher_S = -1.;\n\tm_lin_spher_A = -1.;\n\tm_lin_spher_C = -1.;\n\tm_lin_spher_D = -1.;\n\n\t// Do not consider the case of zero tracks\n\tif (m_ntracks < m_min_ntracks) return;\n\n\t// Construct the sphericity tensor\n\tdouble a11 = 0.; double a12 = 0.; double a13 = 0.;\n\tdouble a21 = 0.; double a22 = 0.; double a23 = 0.;\n\tdouble a31 = 0.; double a32 = 0.; double a33 = 0.;\n\tdouble norm = 0.;\n\n\tfor (const auto& p : pvec){\n\t\tdouble mod (p.norm());\n\t\tnorm += mod;\n\n\t\tstd::cout << \"Adding vector to sphericity tensor\" << std::endl;\n\t\tstd::cout << p << std::endl;\n\n\t\ta11 += p.x() * p.x() / mod;\n\t\ta22 += p.y() * p.y() / mod;\n\t\ta33 += p.z() * p.z() / mod;\n\n\t\ta12 += p.x() * p.y() / mod;\n\t\ta13 += p.x() * p.z() / mod;\n\t\ta23 += p.y() * p.z() / mod;\n\t}\n\n\t// Fill symmetric elements of sphericity tensor\n\ta21 = a12; a31 = a13; a32 = a23;\n\n\tdouble s11 = a11 / norm; double s12 = a12 / norm; double s13 = a13 / norm;\n\tdouble s21 = a21 / norm; double s22 = a22 / norm; double s23 = a23 / norm;\n\tdouble s31 = a31 / norm; double s32 = a32 / norm; double s33 = a33 / norm;\n\n\t// Calculate the eigenvalues\n\tMatrix3f eigen_problem;\n\teigen_problem <<\n\t\ts11, s12, s13,\n\t\ts21, s22, s23,\n\t\ts31, s32, s33;\n\tstd::cout << \"eigen problem: \" << std::endl;\n\tstd::cout << eigen_problem << std::endl;\n\n\tSelfAdjointEigenSolver<Matrix3f> eigen_solver(eigen_problem);\n\n\tstd::cout << \"Eigenvalues are: \" << std::endl;\n\tauto eigen_values = eigen_solver.eigenvalues();\n\tstd::cout << eigen_values << std::endl;\n\n\t// Compute sphericity variables and set class data members\n\tif (ndims == 3) {\n\t\tdouble S = (eigen_values[1] + eigen_values[0]) * 3./2.;\n\t\tdouble A = eigen_values[0] * 3./2.;\n\t\tdouble C = (eigen_values[2] * eigen_values[1]\n\t\t\t\t\t+ eigen_values[2] * eigen_values[0]\n\t\t\t\t\t+ eigen_values[1] * eigen_values[0]) * 3.;\n\t\tdouble D = 27. * eigen_values[2] * eigen_values[1] * eigen_values[0];\n\n\t\tm_lin_spher_S = S;\n\t\tm_lin_spher_A = A;\n\t\tm_lin_spher_C = C;\n\t\tm_lin_spher_D = D;\n\n\t} else if (ndims == 2) {\n\t\tdouble S = eigen_values[1] * 2.;\n\t\tdouble C = eigen_values[0] * eigen_values[1] * 4.;\n\n\t\tm_lin_spher_S = S;\n\t\tm_lin_spher_C = C;\n\n\t}\n\n\tstd::cout << \"New event:\" << std::endl;\n\tstd::cout << \"S = \" << m_lin_spher_S << std::endl;\n\tstd::cout << \"A = \" << m_lin_spher_A << std::endl;\n\tstd::cout << \"C = \" << m_lin_spher_C << std::endl;\n\tstd::cout << \"D = \" << m_lin_spher_D << std::endl;\n\tstd::cout << std::endl;\n\n}\n\nvoid EventShapes::calc_all() {\n\tcalcThrust();\n\tcalcThrustMajor();\n\tcalcThrustMinor();\n\tcalcOblateness();\n\tcalcBrd();\n\tcalcLinSph();\n}\n\nEventShapes::~EventShapes() {\n\tdelete m_thrust_axis;\n\tdelete m_thrust_major_axis;\n\tdelete m_thrust_minor_axis;\n}", "meta": {"hexsha": "14a36e0bca93dcf864a248a474feb6d10c503839", "size": 14942, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Root/EventShapes.cxx", "max_stars_repo_name": "ynyrharris/event-shapes", "max_stars_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Root/EventShapes.cxx", "max_issues_repo_name": "ynyrharris/event-shapes", "max_issues_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Root/EventShapes.cxx", "max_forks_repo_name": "ynyrharris/event-shapes", "max_forks_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_forks_repo_licenses": ["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.1393596987, "max_line_length": 114, "alphanum_fraction": 0.6599518137, "num_tokens": 4654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5854899847967967}}
{"text": "#include <iostream>\n\n#include <posit/posit>\n#include <boost/range/combine.hpp>\n#include <boost/multiprecision/cpp_dec_float.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\nint main() {\n\n    ofstream outfile(\"da.txt\", ios::out);\n    outfile << \"Q,da_f,da_p2,da_p3\" << endl;\n\n    for(int Q = 1; Q <= 100; Q++) {\n        cpp_dec_float_100 dec = pow(10.0, -(cpp_dec_float_100)Q/10);\n\n        float f = powl(10.0, -(long double)Q/10);\n        posit<32,2> p2 = powl(10.0, -(long double)Q/10);\n        posit<32,3> p3 = powl(10.0, -(long double)Q/10);\n\n        cpp_dec_float_100 da_f, da_p2, da_p3;\n        da_f = decimal_accuracy(dec, static_cast<cpp_dec_float_100>(f));\n        da_p2 = decimal_accuracy(dec, static_cast<cpp_dec_float_100>(p2));\n        da_p3 = decimal_accuracy(dec, static_cast<cpp_dec_float_100>(p3));\n\n        outfile << Q << \",\";\n        outfile << setprecision(100) << fixed << da_f << \",\" << da_p2 << \",\" << da_p3 << endl << flush;\n    }\n    outfile.close();\n\n}", "meta": {"hexsha": "e9df715df1b0f3990011f84a3146296a834eac5c", "size": 1978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "phred/main.cpp", "max_stars_repo_name": "lvandam/pairhmm_posit_cpp", "max_stars_repo_head_hexsha": "580c45d65913bc683aabc9abf3049291bf7c82e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-10T17:04:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-10T17:04:06.000Z", "max_issues_repo_path": "phred/main.cpp", "max_issues_repo_name": "lvandam/pairhmm_posit_cpp", "max_issues_repo_head_hexsha": "580c45d65913bc683aabc9abf3049291bf7c82e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phred/main.cpp", "max_forks_repo_name": "lvandam/pairhmm_posit_cpp", "max_forks_repo_head_hexsha": "580c45d65913bc683aabc9abf3049291bf7c82e3", "max_forks_repo_licenses": ["Apache-2.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.56, "max_line_length": 115, "alphanum_fraction": 0.6248736097, "num_tokens": 559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5854899792580384}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOGIT_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOGIT_HPP\n\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the log odds of the argument.\n *\n * The logit function is defined as for \\f$x \\in [0, 1]\\f$ by\n * returning the log odds of \\f$x\\f$ treated as a probability,\n *\n * \\f$\\mbox{logit}(x) = \\log \\left( \\frac{x}{1 - x} \\right)\\f$.\n *\n * The inverse to this function is <code>inv_logit</code>.\n *\n *\n \\f[\n \\mbox{logit}(x) =\n \\begin{cases}\n \\textrm{NaN}& \\mbox{if } x < 0 \\textrm{ or } x > 1\\\\\n \\ln\\frac{x}{1-x} & \\mbox{if } 0\\leq x \\leq 1 \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{logit}(x)}{\\partial x} =\n \\begin{cases}\n \\textrm{NaN}& \\mbox{if } x < 0 \\textrm{ or } x > 1\\\\\n \\frac{1}{x-x^2}& \\mbox{if } 0\\leq x\\leq 1 \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n \\end{cases}\n \\f]\n *\n * @param u argument\n * @return log odds of argument\n */\ninline double logit(double u) {\n  using std::log;\n  return log(u / (1 - u));\n}\n\n/**\n * Return the log odds of the argument.\n *\n * @param u argument\n * @return log odds of argument\n */\ninline double logit(int u) { return logit(static_cast<double>(u)); }\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "a12ef76229fce17c22fe6c9e0766027631f304b0", "size": 1279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/logit.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/logit.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/logit.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": 22.4385964912, "max_line_length": 68, "alphanum_fraction": 0.6184519156, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.585489973144119}}
{"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_STATISTICS_FUNCTIONS_GENERIC_EVSTAT_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_GENERIC_EVSTAT_HPP_INCLUDED\n#include <nt2/statistics/functions/evstat.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/include/constants/euler.hpp>\n#include <nt2/include/constants/oneo_6.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/functions/sqr.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT   ( evstat_, tag::cpu_\n                                    , (A0)(A1)(A2)(A3)\n                                    , (scalar_ < floating_<A0> > )\n                                      (scalar_ < floating_<A1> > )\n                                      (scalar_ < floating_<A2> > )\n                                      (scalar_ < floating_<A3> > )\n                                    )\n  {\n    typedef void result_type;\n    BOOST_FORCEINLINE result_type operator()( A0 const& mu, A1 const& sigma\n                                            , A2 & m, A3 & v) const\n    {\n      m = mu-Euler<A0>()*sigma;\n      v = sqr(Pi<A0>()*sigma)*Oneo_6<A0>();\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT   ( evstat_, tag::cpu_\n                                    , (A0)(A1)(A2)\n                                    , (scalar_ < floating_<A0> > )\n                                      (scalar_ < floating_<A1> > )\n                                      (scalar_ < floating_<A2> > )\n                                    )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()( A0 const& mu, A1 const& sigma\n                                            , A2 & v) const\n    {\n      v = sqr(Pi<result_type>()*sigma)*Oneo_6<result_type>();\n      return mu-Euler<result_type>()*sigma;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT   ( evstat_, tag::cpu_\n                                    , (A0)(A1)\n                                    , (scalar_ < floating_<A0> > )\n                                      (scalar_ < floating_<A1> > )\n                                    )\n  {\n    typedef std::pair<A0,A0> result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& mu, A1 const& sigma) const\n    {\n      return result_type(mu-Euler<A0>()*sigma\n                        , sqr(Pi<A0>()*sigma)*Oneo_6<A0>());\n    }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "fd68bf121fb1630a5a616c57eeba72b49b39b21c", "size": 2814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/generic/evstat.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/statistics/include/nt2/statistics/functions/generic/evstat.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/statistics/include/nt2/statistics/functions/generic/evstat.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 39.0833333333, "max_line_length": 81, "alphanum_fraction": 0.4641080313, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5854355693312809}}
{"text": "/*!\n * \\file khovanov.cpp\n * \\author Jun Yoshida\n * \\copyright (c) 2020 Jun Yoshida.\n * The project is released under the 2-clause BSD License.\n * \\date August, 2020: created\n */\n\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"khovanov.hpp\"\n#include \"cubes.hpp\"\n#include \"enhancements.hpp\"\n\n/* Debug\n#include \"debug/debug.hpp\"\n//*/\n\nusing namespace khover;\n\nusing matrix_t = ChainIntegral::matrix_t;\n\n\n/***********************************\n *** Implementation of functions ***\n ***********************************/\n// Compute Khovanov complex of a given link diagram.\nstd::optional<ChainIntegral>\nkhover::khChain(\n    LinkDiagram const& diagram,\n    SmoothCube const& cube,\n    std::vector<EnhancementProperty> const& enh_prop\n    //int qdeg\n    ) noexcept\n{\n    // Compute the matrices representing matrices.\n    ChainIntegral result(\n        -diagram.npositive()-1,\n        matrix_t(\n            0, binom(cube.back().ncomp, enh_prop.back().xcnt)));\n    for(int i = cube.dim(); i > 0; --i) {\n        std::size_t maxst_cod = cube.maxState(i).to_ulong();\n        std::size_t maxst_dom = cube.maxState(i-1).to_ulong();\n\n        matrix_t diffmat = matrix_t::Zero(\n            enh_prop[maxst_cod].headidx\n            + binom(cube[maxst_cod].ncomp, enh_prop[maxst_cod].xcnt),\n            enh_prop[maxst_dom].headidx\n            + binom(cube[maxst_dom].ncomp, enh_prop[maxst_dom].xcnt));\n\n        // Traverse all the state pairs\n        for(std::size_t stidx_cod = 0;\n            stidx_cod < binom(cube.dim(), i);\n            ++stidx_cod)\n        {\n            // The state associated with the index.\n            auto st_cod = bitsWithPop<max_crosses>(i, stidx_cod).to_ullong();\n\n            for(std::size_t stidx_dom = 0;\n                stidx_dom < binom(cube.dim(), i-1);\n                ++stidx_dom)\n            {\n                // The state associated with the index.\n                auto st_dom = bitsWithPop<max_crosses>(i-1, stidx_dom).to_ullong();\n\n                // The coefficient between the domain/codomain states.\n                auto coeff = diagram.stateCoeff(\n                    state_t{st_dom}, state_t{st_cod});\n\n                // Skip the case where the codomain state is not adjacent to the domain state.\n                if(coeff == 0)\n                    continue;\n\n                // Find the position where saddle operation is applied.\n                for(std::size_t arc = 0; arc < diagram.narcs(); ++arc) {\n                    // The saddle causes multiplication.\n                    if(cube[st_cod].arccomp[arc] < cube[st_dom].arccomp[arc])\n                    {\n                        for(auto [r,c] : matrix_mult(\n                                enh_prop[st_cod].xcnt,\n                                cube[st_cod].ncomp,\n                                cube[st_cod].arccomp[arc],\n                                cube[st_dom].arccomp[arc])) {\n                            diffmat.coeffRef(\n                                enh_prop[st_cod].headidx+r,\n                                enh_prop[st_dom].headidx+c\n                                ) += coeff;\n                        }\n                        break;\n                    }\n                    // The saddle causes comultiplication\n                    else if(cube[st_cod].arccomp[arc]\n                            > cube[st_dom].arccomp[arc])\n                    {\n                        for(auto [r,c] : matrix_comult(\n                                enh_prop[st_cod].xcnt,\n                                cube[st_cod].ncomp,\n                                cube[st_dom].arccomp[arc],\n                                cube[st_cod].arccomp[arc]))\n                        {\n                            diffmat.coeffRef(\n                                enh_prop[st_cod].headidx+r,\n                                enh_prop[st_dom].headidx+c\n                                ) += coeff;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n\n        // Append the matrix as a differential.\n        if (!result.prepend(std::move(diffmat))) {\n            std::cerr << \"Wrong size matrix...\" << std::endl;\n            return std::nullopt;\n        }\n    }\n\n    return std::make_optional(std::move(result));\n}\n\n// Compute crux complex of a given link diagram and a given crossing.\nstd::optional<ChainIntegral>\nkhover::cruxChain(\n    LinkDiagram const& diagram,\n    std::size_t dblpt,\n    CruxCube const& cube,\n    std::vector<EnhancementProperty> const& enh_prop\n    //int qdeg\n    ) noexcept\n{\n    // The double point is out-of-range.\n    if(dblpt >= diagram.ncrosses()) {\n        return std::nullopt;\n    }\n\n    // Compute the matrices representing matrices.\n    ChainIntegral result(\n        -diagram.npositive() - (diagram.getSign(dblpt) > 0 ? 0 : 1),\n        matrix_t(0, binom(cube.back().ncomp, enh_prop.back().xcnt))\n        );\n\n    for(int i = diagram.ncrosses()-1; i > 0; --i) {\n        std::size_t maxst_cod = cube.maxState(i).to_ulong();\n        std::size_t maxst_dom = cube.maxState(i-1).to_ulong();\n        matrix_t diffmat = matrix_t::Zero(\n            enh_prop[maxst_cod].headidx\n            + binom(cube[maxst_cod].ncomp, enh_prop[maxst_cod].xcnt),\n            enh_prop[maxst_dom].headidx\n            + binom(cube[maxst_dom].ncomp, enh_prop[maxst_dom].xcnt)\n            );\n\n        // Traverse all the state pairs\n        for(std::size_t stidx_cod = 0;\n            stidx_cod < binom(diagram.ncrosses()-1, i);\n            ++stidx_cod)\n        {\n            // The state associated with the index.\n            auto stbits_cod = bitsWithPop<max_crosses>(i, stidx_cod);\n            auto st_cod = stbits_cod.to_ulong();\n\n            // Skip states that has no enhancement in the q-degree.\n            if(enh_prop[st_cod].xcnt < 0\n               || (enh_prop[st_cod].xcnt\n                   > static_cast<int>(cube[st_cod].ncomp)))\n            {\n                continue;\n            }\n\n            for(std::size_t c = 0; c < diagram.ncrosses()-1; ++c) {\n                if(!stbits_cod.test(c))\n                    continue;\n\n                auto stbits_dom = stbits_cod;\n                stbits_dom.set(c,false);\n                auto st_dom = stbits_dom.to_ulong();\n\n                // Skip states that has no enhancement in the q-degree.\n                if(enh_prop[st_dom].xcnt < 0\n                   || (enh_prop[st_dom].xcnt\n                       > static_cast<int>(cube[st_cod].ncomp)))\n                {\n                    continue;\n                }\n\n                // The coefficient between the domain/codomain states.\n                auto coeff = diagram.stateCoeff(\n                    cube[st_dom].state, cube[st_cod].state);\n\n                // Skip the case where the codomain state is not adjacent to the domain state.\n                if(coeff == 0)\n                    continue;\n\n                // Find the position where saddle operation is applied.\n                for(std::size_t arc = 0; arc < diagram.narcs(); ++arc) {\n                    // The saddle causes multiplication.\n                    if(cube[st_cod].arccomp[arc]\n                       < cube[st_dom].arccomp[arc])\n                    {\n                        // Enabled if the operation is involved with twisted arcs.\n                        std::optional<std::size_t> action_arc;\n                        if ((cube[st_dom].twist\n                             ^ cube[st_cod].twist).any())\n                        {\n                            // In that case, action_arc is a non-twisted arc that acts on the twisted arc.\n                            if(cube[st_dom].twist.test(arc))\n                                action_arc = cube[st_cod].arccomp[arc];\n                            else\n                                action_arc = cube[st_dom].arccomp[arc];\n                        }\n\n                        for(auto [r,c] : matrix_mult(\n                                enh_prop[st_cod].xcnt,\n                                cube[st_cod].ncomp,\n                                cube[st_cod].arccomp[arc],\n                                cube[st_dom].arccomp[arc]))\n                        {\n                            // -1 if 'x' on the act circle.\n                            diffmat.coeffRef(\n                                enh_prop[st_cod].headidx+r,\n                                enh_prop[st_dom].headidx+c\n                                ) += action_arc && bitsWithPop<max_components>(\n                                    enh_prop[st_dom].xcnt, c).test(*action_arc)\n                                ? -coeff : coeff;\n                        }\n                        break;\n                    }\n                    // The saddle causes comultiplication\n                    else if (cube[st_cod].arccomp[arc]\n                             > cube[st_dom].arccomp[arc])\n                    {\n                        // Enabled if the operation is involved with twisted arcs.\n                        std::optional<std::size_t> coact_arc;\n                        if ((cube[st_dom].twist\n                             ^ cube[st_cod].twist).any())\n                        {\n                            // In that case, coact_arc is a non-twisted arc that coacts on the twisted arc.\n                            if(cube[st_cod].twist.test(arc))\n                                coact_arc = cube[st_dom].arccomp[arc];\n                            else\n                                coact_arc = cube[st_cod].arccomp[arc];\n                        }\n\n                        for(auto [r,c] : matrix_comult(\n                                enh_prop[st_cod].xcnt,\n                                cube[st_cod].ncomp,\n                                cube[st_dom].arccomp[arc],\n                                cube[st_cod].arccomp[arc]))\n                        {\n                            // -1 if '1' on the coact circle.\n                            diffmat.coeffRef(\n                                enh_prop[st_cod].headidx+r,\n                                enh_prop[st_dom].headidx+c\n                                ) += coact_arc && bitsWithPop<max_components>(\n                                    enh_prop[st_cod].xcnt, r).test(*coact_arc)\n                                ? coeff : -coeff;\n                        }\n                        break;\n                    }\n                }\n            }\n        }\n\n        // Append the matrix as a differential.\n        if (!result.prepend(std::move(diffmat))) {\n            std::cerr << \"Wrong size matrix...\" << std::endl;\n            return std::nullopt;\n        }\n    }\n\n    return std::optional<ChainIntegral>(std::move(result));\n}\n", "meta": {"hexsha": "aebc68cd956e86f05431c20fd585269632dfb878", "size": 10629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/khovanov.cpp", "max_stars_repo_name": "Junology/khover", "max_stars_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T06:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T06:50:39.000Z", "max_issues_repo_path": "src/khovanov.cpp", "max_issues_repo_name": "Junology/khover", "max_issues_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/khovanov.cpp", "max_forks_repo_name": "Junology/khover", "max_forks_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6509090909, "max_line_length": 107, "alphanum_fraction": 0.4533822561, "num_tokens": 2263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5854355653932736}}
{"text": "#ifndef REGISTRATION_COST_HPP\n#define REGISTRATION_COST_HPP\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nstruct LiTAMIN2CostFunction\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    LiTAMIN2CostFunction(Eigen::Vector3d p_mean, Eigen::Vector3d q_mean, Eigen::Matrix3d p_cov, Eigen::Matrix3d q_cov,\n                           Eigen::Matrix3d lambdaI,double sigma_ICP) :\n                        p_mean_(p_mean), q_mean_(q_mean), p_cov_(p_cov), q_cov_(q_cov),lambdaI_(lambdaI),sigma_ICP_(sigma_ICP) {}\n\n    template <typename T>\n    bool operator()(const T *const q, const T *const t, T *residuals) const\n    {\n        Eigen::Map<Eigen::Matrix<T,3,1>> residuals_map(residuals);\n        Eigen::Matrix<T, 3, 1> p_m(p_mean_.cast<T>());\n        Eigen::Matrix<T, 3, 1> q_m(q_mean_.cast<T>());\n        Eigen::Matrix<T, 3, 3> p_c = p_cov_.cast<T>();\n        Eigen::Matrix<T, 3, 3> q_c = q_cov_.cast<T>();\n        Eigen::Matrix<T, 3, 3> lambI = lambdaI_.cast<T>();       \n        Eigen::Quaternion<T> quat(q);\n        Eigen::Matrix<T, 3, 1> translation(t);\n\n        Eigen::Matrix<T, 3, 3> mahalanobis = (q_c + quat * p_c * (quat.inverse()) + lambdaI_).inverse();\n        mahalanobis.normalize();\n        Eigen::Matrix<T,3,3> LT = mahalanobis.llt().matrixL().transpose();\n        residuals_map = LT * (q_m - (quat * p_m + translation));\n        T EICP = T(residuals_map.squaredNorm());\n        T sigma_square = T(sigma_ICP_*sigma_ICP_);\n        residuals_map = (T(1.)-(EICP/(EICP+sigma_square)))*residuals_map;\n\n        return true;\n    }\n\n    static ceres::CostFunction *Create(Eigen::Vector3d p_mean_, Eigen::Vector3d q_mean_, Eigen::Matrix3d p_cov_, \n    Eigen::Matrix3d q_cov_,Eigen::Matrix3d lambdaI_, double sigma_ICP_){\n        // 残差是三维的,变量分别是思维和三维\n        return (new ceres::AutoDiffCostFunction<LiTAMIN2CostFunction,3,4,3>\n        (new LiTAMIN2CostFunction(p_mean_,q_mean_,p_cov_,q_cov_,lambdaI_,sigma_ICP_)));\n    }\n    \n    Eigen::Vector3d p_mean_, q_mean_;\n    Eigen::Matrix3d p_cov_, q_cov_;\n    Eigen::Matrix3d lambdaI_;\n    double sigma_ICP_;\n};\n#endif", "meta": {"hexsha": "7f5a85e388dee05da2093ced757e07e7fb2b7caf", "size": 2128, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/litamin2/ceres_cost/litamin2_cost.hpp", "max_stars_repo_name": "FishInWave/fast-gicp", "max_stars_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T04:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T11:06:30.000Z", "max_issues_repo_path": "include/litamin2/ceres_cost/litamin2_cost.hpp", "max_issues_repo_name": "FishInWave/fast-gicp", "max_issues_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/litamin2/ceres_cost/litamin2_cost.hpp", "max_forks_repo_name": "FishInWave/fast-gicp", "max_forks_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:12:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:17:35.000Z", "avg_line_length": 40.9230769231, "max_line_length": 129, "alphanum_fraction": 0.6494360902, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404038127071, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5853379718753182}}
{"text": "#include <NTL/ZZ.h>\n#include <cstdint>\n#include <cmath>\n\n#define NUM_BITS_REAL_MANTISSA  128\n#define IGNORE_DECODING_COST      0\n#define SKIP_BJMM 0\n#define LOG_COST_CRITERION 1\n\n#include \"proper_primes.hpp\"\n#include \"binomials.hpp\"\n#include \"bit_error_probabilities.hpp\"\n#include \"partitions_permanents.hpp\"\n#include \"isd_cost_estimate.hpp\"\n#include <cmath>\n\nuint32_t estimate_t_val(const uint32_t c_sec_level,\n                        const uint32_t q_sec_level,\n                        const uint32_t n_0, \n                        const uint32_t p){\n    double achieved_c_sec_level = c_sec_level;\n    double achieved_q_sec_level = q_sec_level;\n    uint32_t lo = 1, t, t_prec;\n    uint32_t hi;\n    hi = p < 4*c_sec_level ? p : 4*c_sec_level;\n    t = lo;\n    t_prec = lo;\n    while (hi - lo > 1){\n       t_prec = t;\n       t = (lo + hi)/2;\n       std::cerr << \"testing t \" <<  t << std::endl;\n       achieved_c_sec_level = c_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0);\n       achieved_q_sec_level = q_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0);\n       if ( (achieved_c_sec_level >= c_sec_level) && \n            (achieved_q_sec_level >= q_sec_level)    ){\n         hi = t;\n       } else {\n         lo = t;\n       }\n    }\n    if( (achieved_c_sec_level >= c_sec_level) && \n        (achieved_q_sec_level >= q_sec_level)    ){\n        return t;\n    }\n    return t_prec;\n}\n\n\nint ComputeDvMPartition(const uint64_t d_v_prime,\n                        const uint64_t n_0,\n                        uint64_t mpartition[],\n                        uint64_t &d_v){\n     d_v = floor(sqrt(d_v_prime));\n     d_v = (d_v & 0x01) ? d_v : d_v + 1;\n     uint64_t m = ceil( (double) d_v_prime / (double) d_v );\n\n     int partition_ok;\n     partition_ok = FindmPartition(m,mpartition,n_0);\n\n     while(!partition_ok  && (d_v_prime/d_v) >= n_0){\n          d_v += 2;\n          m = ceil( (double) d_v_prime / (double) d_v );\n          partition_ok = FindmPartition(m,mpartition,n_0);\n     }\n     return partition_ok;\n}\n\nuint64_t estimate_dv (const uint32_t c_sec_level, // expressed as\n                      const uint32_t q_sec_level,\n                      const uint32_t n_0, \n                      const uint32_t p,\n                      uint64_t mpartition[]){\n    double achieved_c_sec_level = 0.0;\n    double achieved_q_sec_level = 0.0;\n    double achieved_c_enum_sec_level = 0.0;\n    double achieved_q_enum_sec_level = 0.0;\n\n    NTL::ZZ keyspace;\n\n    uint32_t lo = 1, d_v_prime, hi;\n    uint64_t d_v,d_v_prec =0;\n    int found_dv_mpartition = 0;\n    // recalling that the weight of the sought codeword in a KRA is \n    // d_c_prime = n_0 * d_v_prime, d_c_prime < p \n    // d_v_prime should not be greater than p/n_0\n    hi = (p/n_0) < 4*c_sec_level ? (p/n_0) : 4*c_sec_level;\n    d_v_prime = lo;\n    d_v = (int) sqrt(lo);\n\n    while (hi - lo > 1){\n       d_v_prec = d_v;\n       d_v_prime = (lo + hi)/2;\n       found_dv_mpartition = ComputeDvMPartition(d_v_prime,n_0,mpartition,d_v);\n       if(found_dv_mpartition) {\n          keyspace = 1;\n          for(int i =0; i < (int)n_0; i++){\n              keyspace *= binomial_wrapper(p,mpartition[i]);\n          }\n          keyspace = NTL::power(keyspace,n_0);\n          keyspace += NTL::power(binomial_wrapper(p,d_v),n_0);\n          achieved_c_enum_sec_level = NTL::conv<double>(log2_RR(NTL::to_RR(keyspace)));\n          achieved_q_enum_sec_level = achieved_c_enum_sec_level/2;\n          if ((achieved_q_enum_sec_level >= q_sec_level) && \n              (achieved_c_enum_sec_level >= c_sec_level) ){\n              /* last parameter indicates a KRA, reduce margin by p due to\n              quasi cyclicity */\n              achieved_c_sec_level = c_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1);\n              achieved_q_sec_level = q_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1);\n          }\n       }\n\n       if ( (found_dv_mpartition) && \n            (achieved_q_enum_sec_level >= q_sec_level) && \n            (achieved_c_enum_sec_level >= c_sec_level) &&\n            (achieved_c_sec_level >= c_sec_level) && \n            (achieved_q_sec_level >= q_sec_level)   ){\n          hi = d_v_prime;\n       } else {\n          lo = d_v_prime;\n       }\n    }\n\n    if ( (found_dv_mpartition) && \n            (achieved_q_enum_sec_level >= q_sec_level) && \n            (achieved_c_enum_sec_level >= c_sec_level) &&\n            (achieved_c_sec_level >= c_sec_level) && \n            (achieved_q_sec_level >= q_sec_level)   ){\n        return d_v;\n    }\n    return d_v_prec;\n}\n\nint main(int argc, char* argv[]){\n\n  if(argc != 6){\n     std::cout << \"Code Parameter Computer for LEDA[kem|pkc]\" << std::endl << \" Usage \" \n               << argv[0] << \" security_level_classic security_level_pq n_0 epsilon starting_prime_lb\" << std::endl;\n    return -1;\n  }\n  uint32_t c_sec_level = atoi(argv[1]);\n  uint32_t q_sec_level = atoi(argv[2]);\n  uint32_t n_0 = atoi(argv[3]);\n  float epsilon = atof(argv[4]);\n  uint32_t starting_prime_lower_bound = atoi(argv[5]);\n\n  std::cerr << \"Computing the parameter set for security level classic:2^\" << \n  c_sec_level << \" post-q:2^\" << q_sec_level << \" n_0 \" << n_0 << \" epsilon \" \n  << epsilon << std::endl;\n\n  uint64_t p, p_th, t, d_v_prime, d_v;\n  uint64_t mpartition[n_0] = {0};\n  \n  int current_prime_pos = 0;\n  while (proper_primes[current_prime_pos] < starting_prime_lower_bound){\n          current_prime_pos++;\n  }\n  p_th = proper_primes[current_prime_pos];\n\n\n  InitBinomials();\n  NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA);\n  pi = NTL::ComputePi_RR();\n\n  /* since some values of p may yield no acceptable partitions for m, binary\n   * search on p is not feasible. Fall back to fast increase of the value of \n   * p exploiting the value of the p expected to be correcting the required t \n   * errors */\n\n  std::cout << \"finding parameters\" << std::endl;\n  do {\n      /* estimate the current prime as the closest \n       * to the previous p_th * (1+epsilon) */\n      uint32_t next_prime = ceil(p_th * (1.0+epsilon));\n      current_prime_pos = 0;\n      while (proper_primes[current_prime_pos] < next_prime){\n          current_prime_pos++;\n      }\n      p = proper_primes[current_prime_pos];\n      std::cout << \" -- testing p: \" << p << std::endl;\n\n      // Estimate number of errors to ward off ISD decoding\n      t = estimate_t_val(c_sec_level,q_sec_level,n_0,p);\n      std::cout << \" -- found t: \" << t << std::endl;\n\n      /* Estimate H*Q density to avoid key recovery via ISD and enumeration\n       * of H and Q */\n      d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition);\n      std::cout << \" -- found d_v: \" << d_v << std::endl;\n      \n      // Estimate the bit flipping thresholds and correction capability\n      d_v_prime=0;\n      for(int i=0;i< (int)n_0;i++){\n         d_v_prime += mpartition[i];\n      }\n      d_v_prime = d_v * d_v_prime;\n      p_th=Findpth(n_0, d_v_prime, t);\n      std::cout << \" -- p should be at least \" << (1.0+epsilon)* p_th << \n         \"to correct the errors\" << std::endl;\n  }  while ((p <= (1.0+epsilon)* p_th) &&\n            (current_prime_pos < PRIMES_NO) );\n\n  std::cout << \"refining parameters\" << std::endl;\n\n  uint64_t p_ok, t_ok, d_v_ok, mpartition_ok[n_0] = {0};\n  /* refinement step taking into account possible invalid m partitions */\n\n  do {\n      p = proper_primes[current_prime_pos];\n      std::cout << \" -- testing p: \" << p << std::endl;\n      \n      // Estimate number of errors to ward off ISD decoding\n      t = estimate_t_val(c_sec_level,q_sec_level,n_0,p);\n      std::cout << \" -- found t: \" << t << std::endl;\n      \n      /* Estimate H*Q density to avoid key recovery via ISD and enumeration\n       * of H and Q */\n      d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition);\n      std::cout << \" -- found d_v: \" << d_v << std::endl;\n      \n      // Estimate the bit flipping thresholds and correction capability\n      d_v_prime=0;\n      for(int i=0;i< (int)n_0;i++){\n         d_v_prime += mpartition[i];\n      }\n      d_v_prime = d_v * d_v_prime;\n      p_th=Findpth(n_0, d_v_prime, t);\n       std::cout << \" -- the threshold value for p to be correcting errors is \" << p_th << std::endl;\n   \n      if(p > (1.0+epsilon)* p_th ) { //store last valid parameter set\n       std::cout << \" -- p is at least \" << (1.0+epsilon)*p_th << \n       \"; it corrects the errors\" << std::endl;\n           p_ok = p; t_ok = t; d_v_ok = d_v;\n           for(unsigned i = 0; i < n_0 ; i++){\n               mpartition_ok[i] = mpartition[i];\n          }\n      }\n      current_prime_pos--;\n  }  while ((p > (1.0+epsilon)* p_th )  && (current_prime_pos > 0));\n\n  std::cout << \"parameter set found: p:\" << p_ok << \" t: \" << t_ok;\n  std::cout << \" d_v : \" << d_v_ok << \" mpartition: [ \";\n  for (unsigned i = 0; i < n_0 ; i++ ){\n   std::cout << mpartition_ok[i] << \" \";\n  }\n  std::cout << \" ]\" << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "122b1f5dd7e100112c1df1920bb2392b584c44bc", "size": 8793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parameter_generator.cpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parameter_generator.cpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parameter_generator.cpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:12:30.000Z", "avg_line_length": 35.4556451613, "max_line_length": 116, "alphanum_fraction": 0.5894461503, "num_tokens": 2566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5853339483990142}}
{"text": "#include <cv_bridge/cv_bridge.h>\n#include <ros/ros.h>\n#include <rr_common/CameraGeometry.h>\n#include <sensor_msgs/Image.h>\n\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <opencv2/opencv.hpp>\n\nusing namespace std;\nusing namespace cv;\nusing namespace ros;\n\ndouble px_per_meter;           // resolution of overhead view\ndouble camera_dist_max;        // distance to look ahead of the car\ndouble camera_dist_min;        // avoid the front bumper\ndouble camera_fov_horizontal;  // radians\ndouble camera_fov_vertical;\ndouble cam_mount_angle;   // angle of camera from horizontal\ndouble cam_mount_height;  // camera height from ground in meters\ndouble cam_mount_x;       // distance from camera to base_footprint\n\nSize mapSize;  // pixels = cm\nSize imageSize;\nMat transform_matrix;\n\nmap<string, Publisher> transform_pubs;\n\n/*\n * Start with a horizontal line on the groud at dmin meters horizonally in front of the\n * camera. It fills half the camera's FOV, from the center to the right edge. Then back\n * up the car so that the line is dmax meters away horizontally from the camera. The\n * apparent length of this hypothetical line (in pixels) is the output of this function.\n * See https://www.desmos.com/calculator/jsofcq1bi5\n * See https://drive.google.com/file/d/0Bw7-7Y3CUDw1Z0ZqdmdRZ3dUTE0/view?usp=sharing\n */\ndouble pxFromDist_X(double dmin, double dmax) {\n    double min_hyp = sqrt(dmin * dmin + cam_mount_height * cam_mount_height);\n    double max_hyp = sqrt(dmax * dmax + cam_mount_height * cam_mount_height);\n    double theta1 = atan((min_hyp / max_hyp) * tan(camera_fov_horizontal / 2));\n    return imageSize.width * (theta1 / camera_fov_horizontal);\n}\n\n// calculate the y coord of the input image from the specified distance\n// see https://www.desmos.com/calculator/pwjwlnnx77\ndouble pxFromDist_Y(double dist) {\n    double tmp = atan(cam_mount_height / dist) - cam_mount_angle + camera_fov_vertical / 2;\n    return imageSize.height * tmp / (camera_fov_vertical);\n}\n\nvoid setTransformFromGeometry() {\n    // set width and height of the rectangle in front of the robot\n    // the actual output image will show more than this rectangle\n    float close_corner_dist = sqrt(pow(camera_dist_min, 2) + pow(cam_mount_height, 2));\n    float rectangle_w = close_corner_dist * tan(camera_fov_horizontal / 2) * px_per_meter * 2;\n    float rectangle_h = (camera_dist_max - camera_dist_min) * px_per_meter;\n\n    // find coordinates for corners above rectangle in input image\n    float x_top_spread = pxFromDist_X(camera_dist_min, camera_dist_max);\n    float y_bottom = pxFromDist_Y(camera_dist_min);\n    float y_top = pxFromDist_Y(camera_dist_max);\n\n    // set the ouput image size to include the whole transformed image,\n    // not just the target rectangle\n    mapSize.width = static_cast<int>(rectangle_w * (imageSize.width / x_top_spread) / 2.0);\n    mapSize.height = static_cast<int>(rectangle_h);\n\n    Point2f src[4] = {\n        Point2f(imageSize.width / 2.f - x_top_spread, y_top),  // top left\n        Point2f(imageSize.width / 2.f + x_top_spread, y_top),  // top right\n        Point2f(0, y_bottom),                                  // bottom left\n        Point2f(imageSize.width, y_bottom)                     // bottom right\n    };\n\n    Point2f dst[4] = {\n        Point2f(mapSize.width / 2.f - rectangle_w / 2.f, 0),               // top left\n        Point2f(mapSize.width / 2.f + rectangle_w / 2.f, 0),               // top right\n        Point2f(mapSize.width / 2.f - rectangle_w / 2.f, mapSize.height),  // bottom left\n        Point2f(mapSize.width / 2.f + rectangle_w / 2.f, mapSize.height)   // bottom right\n    };\n\n    transform_matrix = getPerspectiveTransform(src, dst);\n}\n\nvoid TransformImage(const sensor_msgs::ImageConstPtr& msg, string& topic) {\n    // if no one is listening or the transform is undefined, give up\n    if (transform_pubs[topic].getNumSubscribers() == 0 || transform_matrix.empty()) {\n        return;\n    }\n\n    cv_bridge::CvImagePtr cv_ptr;\n    cv_ptr = cv_bridge::toCvCopy(msg, \"mono8\");\n    const Mat& inimage = cv_ptr->image;\n\n    Mat warp_img;\n    warpPerspective(inimage, warp_img, transform_matrix, mapSize);\n\n    double map_length = camera_dist_max + cam_mount_x;\n    Mat outimage(static_cast<int>(map_length * px_per_meter), warp_img.cols, CV_8UC1, Scalar(0));\n    Rect out_warp_roi(0, 0, warp_img.cols, warp_img.rows);\n\n    warp_img.copyTo(outimage(out_warp_roi));\n\n    sensor_msgs::Image outmsg;\n    cv_ptr->image = outimage;\n    cv_ptr->toImageMsg(outmsg);\n    transform_pubs[topic].publish(outmsg);\n}\n\nint main(int argc, char** argv) {\n    init(argc, argv, \"image_transform\");\n    NodeHandle nh;\n    NodeHandle pnh(\"~\");\n\n    bool all_defined = true;\n    all_defined &= pnh.getParam(\"px_per_meter\", px_per_meter);\n    all_defined &= pnh.getParam(\"map_dist_max\", camera_dist_max);\n    all_defined &= pnh.getParam(\"map_dist_min\", camera_dist_min);\n\n    std::string camera_info_topic;\n    all_defined &= pnh.getParam(\"camera_info_topic\", camera_info_topic);\n    std::string camera_link_name;\n    all_defined &= pnh.getParam(\"camera_link_name\", camera_link_name);\n\n    // the launch file can provide camera information in case camera_info is not published\n    all_defined &= pnh.getParam(\"fallback_fov_horizontal\", camera_fov_horizontal);\n    all_defined &= pnh.getParam(\"fallback_fov_vertical\", camera_fov_vertical);\n    all_defined &= pnh.getParam(\"fallback_image_width\", imageSize.width);\n    all_defined &= pnh.getParam(\"fallback_image_height\", imageSize.height);\n\n    if (!all_defined) {\n        ROS_WARN(\"[Image Transform] Not all launch params defined\");\n    }\n\n    // load camera geometry\n    rr::CameraGeometry cam_geom;\n    cam_geom.LoadInfo(nh, camera_info_topic, camera_link_name, 60.0);\n\n    // set relevant camera geometry fields for this node\n    camera_fov_horizontal = cam_geom.GetFOVHorizontal();\n    camera_fov_vertical = cam_geom.GetFOVVertical();\n    cam_mount_angle = std::get<1>(cam_geom.GetCameraOrientationRPY());\n    cam_mount_height = cam_geom.GetCameraLocation().z;\n    cam_mount_x = cam_geom.GetCameraLocation().x;\n\n    setTransformFromGeometry();\n    ROS_INFO(\"Calculated perspective transform. Used height %f and angle %f\", cam_mount_height, cam_mount_angle);\n\n    string topicsConcat;\n    pnh.getParam(\"transform_topics\", topicsConcat);\n    vector<string> topics;\n    boost::split(topics, topicsConcat, boost::is_any_of(\" ,\"));\n    vector<Subscriber> transform_subs;\n    ROS_INFO_STREAM(\"Found \" << topics.size() << \" topics in param.\");\n    for (const string& topic : topics) {\n        if (topic.size() == 0) {\n            continue;\n        }\n\n        transform_subs.push_back(nh.subscribe<sensor_msgs::Image>(topic, 1, boost::bind(TransformImage, _1, topic)));\n        ROS_INFO_STREAM(\"Image_transform subscribed to \" << topic);\n        string newTopic(topic + \"_transformed\");\n        ROS_INFO_STREAM(\"Creating new topic \" << newTopic);\n        transform_pubs[topic] = nh.advertise<sensor_msgs::Image>(newTopic, 1);\n    }\n\n    spin();\n\n    return 0;\n}\n", "meta": {"hexsha": "d52a7fde647063cc9360ff07970b52b77c3c50d7", "size": 7043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rr_common/src/image_transformation/image_transform.cpp", "max_stars_repo_name": "btdubs/roboracing-software", "max_stars_repo_head_hexsha": "7ef473edc0e95dc793af43d64f5d2fd39695ee02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rr_common/src/image_transformation/image_transform.cpp", "max_issues_repo_name": "btdubs/roboracing-software", "max_issues_repo_head_hexsha": "7ef473edc0e95dc793af43d64f5d2fd39695ee02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rr_common/src/image_transformation/image_transform.cpp", "max_forks_repo_name": "btdubs/roboracing-software", "max_forks_repo_head_hexsha": "7ef473edc0e95dc793af43d64f5d2fd39695ee02", "max_forks_repo_licenses": ["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.1871345029, "max_line_length": 117, "alphanum_fraction": 0.7050972597, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5853301395685812}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iomanip>\n#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n\nusing namespace std;\n\ntypedef float (* node_function_t)(float a) ;\n\ntypedef float (* loss_function_t)(float y, float y_hat);\n\nclass Functions\n{\nprivate:\n    static float loss_function(float y, float y_hat)\n    {\n        return (y - y_hat)*(y - y_hat);\n    }\n    static float der_loss_function(float y, float y_hat)\n    {\n        return 2*(y-y_hat);\n    }\n    static float node_function(float x)\n    {\n        return tanh(0.01*x);\n    }\n    static float der_node_function(float x)\n    {\n        float der = 1/(cosh(0.01*x)*cosh(0.01*x));\n\n        return der;\n    }\n\npublic:\n    node_function_t f = node_function;\n    node_function_t df = der_node_function;\n    loss_function_t l = loss_function;\n    loss_function_t dl = der_loss_function;\n};\n\nclass Layer {\npublic:\n    Eigen::VectorXf result;\n    Eigen::MatrixXf w;\n    Eigen::VectorXf dres;\n    Layer (int layer_nodes_count, int prev_nodes_count) {\n        w.resize(layer_nodes_count, prev_nodes_count);\n        w.setOnes();\n        // w = w*0.01;\n        // w = w*0.01;\n\n    }\n\n    float operator[](int index){\n        return this->result[index];\n    }\n\n    Eigen::VectorXf computer_out(const Eigen::VectorXf& x, node_function_t f, node_function_t df) {\n        Eigen::VectorXf res = w * x;\n        // if(res.size()==784){\n        //   std::cout << w*x << '\\n';\n        // }\n        dres.resize(res.size());\n        for (int i = 0; i < w.rows(); i++) {\n            dres[i] = df(res[i]);\n            res[i] = f(res[i]);\n        }\n        result = res;\n        return res;\n    }\n\n\n};\n\n\nclass Network\n{\nprotected:\n    Layer input;\n    Layer hl ;\n    Layer output;\n    float learning_rate = 0.3;\n    // float learning_rate = 0.002;\n    float deviation = 0.02;\n    // float deviation = 0.02;\n    Functions functions;\n\npublic:\n    Network(int input_count, int hidden_layer, int output_count, Functions functools)\n    : input(input_count, input_count), hl(hidden_layer, input_count),\n    output(output_count, hidden_layer){\n        functions = functools;\n    }\n\n\n    Eigen::VectorXf learn_sample(const Eigen::VectorXf& x, const Eigen::VectorXf& out)\n    {\n        gradient_descent(x, out);\n        return compute_result(x);\n    }\n\n    Eigen::VectorXf compute_input(const Eigen::VectorXf& x)\n    {\n        return input.computer_out(x, functions.f, functions.df);\n    }\n\n    Eigen::VectorXf compute_hidden(const Eigen::VectorXf& x)\n    {\n        return hl.computer_out(x, functions.f, functions.df);\n    }\n\n    Eigen::VectorXf compute_output(const Eigen::VectorXf& x)\n    {\n        return output.computer_out(x, functions.f, functions.df);\n    }\n\n    Eigen::VectorXf compute_result(const Eigen::VectorXf& x)\n    {\n      // std::cout << x << '\\n';\n        return compute_output(compute_hidden(compute_input(x)));\n    }\n\n    Eigen::VectorXf compute_result(const Eigen::VectorXf& x, const Eigen::VectorXf& out)\n    {\n      // std::cout << x << '\\n';\n      learn_sample(x,out);\n        return compute_output(compute_hidden(compute_input(x)));\n    }\n\n    void set_learning_rate(float rate)\n    {\n        learning_rate = rate;\n    }\n\n    void set_deviation(float max_deviation)\n    {\n        deviation = max_deviation;\n    }\n\n    void gradient_descent(const Eigen::VectorXf& x, const Eigen::VectorXf& out, int max_count = 4)\n    {\n        int count = 0;\n        float D, D1;\n        Eigen::VectorXf D_v, dDdz;\n        Eigen::MatrixXf dw, du, dv;\n        // for (size_t i = 0; i < out.size(); i++) {\n        //   if(out[i]!=0)\n        //   {\n        //     std::cout << \" Out: \"<< i << '\\n';\n        //     std::cout << compute_result(x)[i] << '\\n';\n        //   }\n        // }\n        do {\n            D_v = compute_loss_function(out);\n            dDdz = compute_der_d_z(out);\n            D = D_v.sum();\n            // std::cout << grad_output(dDdz) << '\\n';\n            descent(grad_output(dDdz), grad_hidden_2(dDdz), grad_input_2(dDdz, x));\n            compute_result(x);\n            D1 = compute_loss_function(out).sum();\n            // std::cout << \"D =\" << D <<' '<<D1 << \"Difference: \" <<D-D1<<'\\n';\n            count++;\n        }\n        while (\n          // D>1\n        // );\n          D - D1 > deviation &&\n           count<max_count);\n    }\n\n    void descent(const Eigen::MatrixXf& dw, const Eigen::MatrixXf& du, const Eigen::MatrixXf& dv )\n    {\n        input.w -= dv;\n        hl.w -= du;\n        output.w -= dw;\n    }\n\n    Eigen::VectorXf compute_loss_function(const Eigen::VectorXf& out)\n    {\n        Eigen::VectorXf D(output.result.size());\n        for (int i = 0; i < output.result.size(); i++)\n        {\n            D[i] = functions.l(output[i], out[i]);\n        }\n        return D;\n    }\n\n    Eigen::VectorXf compute_der_d_z(const Eigen::VectorXf& out)\n    {\n        Eigen::VectorXf res(output.result.size());\n\n        for (int i = 0; i < output.result.size(); ++i) {\n            res[i] = functions.dl(output.result[i], out[i]);\n        }\n        return res;\n    }\n\n\n    Eigen::MatrixXf grad_output(const Eigen::VectorXf& dDdZ)\n    {\n        Eigen::MatrixXf dw(output.w.rows(), output.w.cols());\n\n        for (int i = 0; i < output.w.rows(); i++)\n        {\n            for(int j = 0; j < output.w.cols(); j++)\n            {\n                dw(i,j) = dDdZ[i]*hl.result[j]*output.dres[i];\n            }\n        }\n\n        return dw*learning_rate;\n    }\n\n\n    Eigen::MatrixXf grad_hidden(const Eigen::VectorXf& dDdZ)\n    {\n        Eigen::MatrixXf du(hl.w.rows(), hl.w.cols());\n        du.setZero();\n        for (int i = 0; i < hl.w.rows(); i++)\n        {\n            for(int j = 0; j < hl.w.cols(); j++)\n            {\n                for (int k = 0; k < output.w.rows(); k++)\n                {\n                  // std::cout << hl.w.rows()<<' '<<j<<' '<<k << '\\n';\n                    du(i,j) += dDdZ[k]*output.w(k,i)*output.dres[k];\n                }\n                du(i,j) *= input.result[j]*hl.dres[i];\n            }\n        }\n\n        return du*learning_rate;\n    }\n\n    Eigen::MatrixXf grad_hidden_2(const Eigen::VectorXf& dDdZ)\n    {\n        Eigen::MatrixXf du(hl.w.rows(), hl.w.cols());\n        du.setZero();\n        Eigen::MatrixXf temp = output.dres.asDiagonal()*output.w;\n        temp = dDdZ.asDiagonal()*temp;\n        float temp_sum;\n        for (int i = 0; i < hl.w.rows(); i++)\n        {\n            temp_sum = temp.col(i).sum();\n            for(int j = 0; j < hl.w.cols(); j++)\n            {\n                du(i,j) =temp_sum* input.result[j]*hl.dres[i];\n            }\n        }\n\n        return du*learning_rate;\n    }\n\n    Eigen::MatrixXf grad_input(const Eigen::VectorXf& dDdZ, const Eigen::VectorXf& in)\n    {\n        int iwc = input.w.cols();\n        Eigen::MatrixXf dv(input.w.rows(), iwc);\n        dv.setZero();\n        int ors = output.result.size();\n        for(int i = 0; i < input.w.rows(); i++)\n        {\n            for(int j = 0; j < iwc; j++)\n            {\n                for(int k= 0; k < ors; k++)\n                {\n                    for(int t = 0; t < hl.w.rows(); t++)\n                    {\n                        dv(i,j) +=hl.w(t,i)*output.w(k,t)*hl.dres[t];\n                    }\n                    dv(i,j)*=dDdZ[k]*output.dres[k];\n                     // std::cout << dv(i,j) << '\\n';\n\n                }\n                dv(i,j)*=input.dres[i]*in[j];\n            }\n\n        }\n\n        return dv*learning_rate;\n    }\n\n\n        Eigen::MatrixXf grad_input_2(const Eigen::VectorXf& dDdZ, const Eigen::VectorXf& in)\n        {\n            int iwc = input.w.cols();\n            Eigen::MatrixXf dv(input.w.rows(), iwc);\n            Eigen::MatrixXf temp = hl.dres.asDiagonal()*hl.w ;\n            temp =output.w*temp;\n            //std::cout << temp << '\\n';\n            dv.setZero();\n            float temp_sum;\n            int ors = output.result.size();\n            for(int i = 0; i < input.w.rows(); i++)\n            {\n              temp_sum = temp.col(i).sum();\n                for(int j = 0; j < iwc; j++)\n                {\n                    for(int k= 0; k < ors; k++)\n                    {\n                        dv(i,j) =dDdZ[k]*output.dres[k]*temp_sum ;\n                    }\n                    dv(i,j)*=input.dres[i]*in[j];\n                }\n                //std::cout << i << dv(i,0)<< '\\n';\n            }\n\n            return dv*learning_rate;\n        }\n\n\n    void debug_output()\n    {\n      //std::cout << input.w << '\\n';\n    //  std::cout << hl.w << '\\n';\n      // std::cout << output.w << '\\n';\n    }\n\n    void write_in_file()\n    {\n      ofstream off(\"weights.in\");\n      for (size_t i = 0; i < output.w.rows(); i++) {\n        for (size_t j = 0; j < output.w.cols(); j++) {\n          off<< output.w(i,j)<<endl;\n        }\n      }\n      for (size_t i = 0; i < hl.w.rows(); i++) {\n        for (size_t j = 0; j < hl.w.cols(); j++) {\n          off<< hl.w(i,j)<<endl;\n        }\n      }\n      for (size_t i = 0; i < input.w.rows(); i++) {\n        for (size_t j = 0; j < input.w.cols(); j++) {\n          off<< input.w(i,j)<<endl;\n        }\n      }\n      off.close();\n    }\n\n    void read_from_file() {\n      ifstream off(\"weights.in\");\n      if (off.is_open())\n      {\n      for (size_t i = 0; i < output.w.rows(); i++) {\n        for (size_t j = 0; j < output.w.cols(); j++) {\n          off>> output.w(i,j);\n        }\n      }\n      for (size_t i = 0; i < hl.w.rows(); i++) {\n        for (size_t j = 0; j < hl.w.cols(); j++) {\n          off>> hl.w(i,j);\n        }\n      }\n      for (size_t i = 0; i < input.w.rows(); i++) {\n        for (size_t j = 0; j < input.w.cols(); j++) {\n          off>> input.w(i,j);\n        }\n      }\n    }\n      off.close();\n    }\n\n};\n\n\n\n  Eigen::MatrixXf read_mnist(int samples)\n  {\n    Eigen::MatrixXf x(28*28, samples);\n\n      ifstream file (\"t10k-images-idx3-ubyte\");\n      int magic_number;\n      file.read((char*)&magic_number,sizeof(int));\n      file.read((char*)&magic_number,sizeof(int));\n      file.read((char*)&magic_number,sizeof(int));\n      file.read((char*)&magic_number,sizeof(int));\n      if (file.is_open())\n      {\n          for(int i=0;i<samples;i++)\n          {\n              for(int r=0;r<784;r++)\n              {\n                unsigned char temp=0;\n                file.read((char*)&temp,sizeof(temp));\n                x(r, i)=(float)temp/255;\n                 // std::cout <<r<<\" \"<< (float)temp/255 << ' '<<x(r, i)<< '\\n';\n              }\n          }\n      }\n      return x;\n  }\n\n  Eigen::VectorXf read_mnist_labels(int samples)\n  {\n      Eigen::VectorXf out(samples);\n      ifstream file (\"t10k-labels-idx1-ubyte\");\n      int magic_number;\n      file.read((char*)&magic_number,sizeof(int));\n      file.read((char*)&magic_number,sizeof(int));\n      if (file.is_open())\n      {\n          for(int i=0;i<samples;i++)\n          {\n            unsigned char temp=0;\n            file.read((char*)&temp,sizeof(temp));\n            out[i] = (int)temp;\n\n          }\n      }\n      return out;\n  }\n\n  struct Result\n  {\n    int predict;\n    float pred_pers;\n    float error;\n    std::vector<int> image;\n  };\n\nstruct Result test(int sample)\n{\n  Eigen::MatrixXf temp = read_mnist(sample+1);\n  Eigen::VectorXf labels = read_mnist_labels(sample+1);\n  Network nt(784, 256, 10, Functions());\n  nt.read_from_file();\n  Result result;\n  Eigen::VectorXf res;\n  float error = 0;\n    Eigen::VectorXf out_v(10);\n    out_v.setZero();\n    out_v[labels[sample]] = 1;\n\n    Eigen::VectorXf in = temp.col(sample);\n\n    for (size_t i = 0; i < 784; i++) {\n      result.image.push_back(in[i]);\n    }\n    res = nt.compute_result(in, out_v);\n\n    for (size_t j = 0; j < res.size(); j++) {\n      if(res[j]>0.9)\n      {\n        result.predict = j;\n        result.pred_pers = res[j];\n      }\n      else\n      {\n        error +=res[j]\n      }\n    }\n    result.error = error;\n\n  return result;\n}\n\nvoid train(int sample)\n{\n  Eigen::MatrixXf temp = read_mnist(sample);\n  Eigen::VectorXf labels = read_mnist_labels(sample);\n  Network nt(784, 256, 10, Functions());\n\n   for (size_t i = 0; i < sample; i++)\n   {\n    Eigen::VectorXf out_v(10);\n    out_v.setZero();\n    out_v[labels[i]] = 1;\n    Eigen::VectorXf in = temp.col(i);\n    nt.learn_sample(in, out_v);\n    // std::cout << i+1 << '\\n';\n   }\n   nt.write_in_file();\n}\n", "meta": {"hexsha": "ef208f7ae6cc6f14c040d0298799ba9430d4418e", "size": 12279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Digit_Recognition/ex.cpp", "max_stars_repo_name": "noasck/mnist_recognition_qt", "max_stars_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T22:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T19:22:19.000Z", "max_issues_repo_path": "Digit_Recognition/ex.cpp", "max_issues_repo_name": "noasck/mnist_recognition_qt", "max_issues_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Digit_Recognition/ex.cpp", "max_forks_repo_name": "noasck/mnist_recognition_qt", "max_forks_repo_head_hexsha": "979337124a97b1a1dd3f788a209c42b8a3fc481d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-03T04:32:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-03T04:32:20.000Z", "avg_line_length": 25.7421383648, "max_line_length": 99, "alphanum_fraction": 0.4931183321, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5851743592076076}}
{"text": "\n#include \"triangle.hpp\"\n\n#include \"geometry/projection.hpp\"\n\n#include <Eigen/Geometry>\n\nnamespace neon\n{\ntriangle3::triangle3(triangle_quadrature::point const p)\n    : surface_interpolation(std::make_unique<triangle_quadrature>(p), 3)\n{\n    this->precompute_shape_functions();\n}\n\nvoid triangle3::precompute_shape_functions()\n{\n    // Initialize nodal coordinates array as r and s\n    m_quadrature->evaluate([&](auto const& coordinates) {\n        auto const& [l, r, s] = coordinates;\n\n        vector N(3);\n        matrix rhea(3, 2);\n\n        N(0) = r;\n        N(1) = s;\n        N(2) = 1.0 - r - s;\n\n        rhea(0, 0) = 1.0;\n        rhea(1, 0) = 0.0;\n        rhea(2, 0) = -1.0;\n\n        rhea(0, 1) = 0.0;\n        rhea(1, 1) = 1.0;\n        rhea(2, 1) = -1.0;\n\n        return std::make_tuple(N, rhea);\n    });\n\n    extrapolation = matrix::Ones(number_of_nodes(), 1);\n}\n\ndouble triangle3::compute_measure(matrix const& nodal_coordinates) const\n{\n    // Use the cross product identity 2A = | a x b | to compute face area\n    vector3 const direction0 = nodal_coordinates.col(0) - nodal_coordinates.col(2);\n    vector3 const direction1 = nodal_coordinates.col(1) - nodal_coordinates.col(2);\n\n    vector3 const normal = direction0.cross(direction1);\n\n    return normal.norm() / 2.0;\n}\n\ntriangle6::triangle6(triangle_quadrature::point const p)\n    : surface_interpolation(std::make_unique<surface_quadrature>(triangle_quadrature(p)), 6)\n{\n    this->precompute_shape_functions();\n}\n\nvoid triangle6::precompute_shape_functions()\n{\n    using NodalCoordinate = std::tuple<int, double, double>;\n\n    // Initialize nodal coordinates array as Xi, Eta, Zeta\n    std::array<NodalCoordinate, 6> constexpr local_coordinates{{\n        {0, 1.0, 0.0},\n        {1, 0.0, 1.0},\n        {2, 0.0, 0.0},\n        {3, 0.5, 0.5},\n        {4, 0.0, 0.5},\n        {5, 0.5, 0.0},\n    }};\n\n    matrix N_matrix(m_quadrature->points(), number_of_nodes());\n    matrix local_quadrature_coordinates = matrix::Ones(m_quadrature->points(), 3);\n\n    m_quadrature->evaluate([&](auto const& coordinate) {\n        auto const& [l, r, s] = coordinate;\n\n        auto const t = 1.0 - r - s;\n\n        vector N(6);\n        matrix rhea(6, 2);\n\n        N(0) = r * (2.0 * r - 1.0);\n        N(1) = s * (2.0 * s - 1.0);\n        N(2) = t * (2.0 * t - 1.0);\n        N(3) = 4.0 * r * s;\n        N(4) = 4.0 * s * t;\n        N(5) = 4.0 * r * t;\n\n        // r coordinates\n        rhea(0, 0) = 4.0 * r - 1.0;\n        rhea(1, 0) = 0.0;\n        rhea(2, 0) = -4.0 * t + 1.0;\n        rhea(3, 0) = 4.0 * s;\n        rhea(4, 0) = -4.0 * s;\n        rhea(5, 0) = 4.0 * t - 4.0 * r;\n\n        // s coordinates\n        rhea(0, 1) = 0.0;\n        rhea(1, 1) = 4.0 * s - 1.0;\n        rhea(2, 1) = -4.0 * t + 1.0;\n        rhea(3, 1) = 4.0 * r;\n        rhea(4, 1) = 4.0 * t - 4.0 * s;\n        rhea(5, 1) = -4.0 * r;\n\n        local_quadrature_coordinates(l, 0) = r;\n        local_quadrature_coordinates(l, 1) = s;\n\n        N_matrix.row(l) = N;\n\n        return std::make_tuple(N, rhea);\n    });\n\n    // Compute extrapolation algorithm matkrices\n    matrix local_nodal_coordinates = matrix::Ones(number_of_nodes(), 3);\n\n    for (auto const& [a, r, s] : local_coordinates)\n    {\n        local_nodal_coordinates(a, 0) = r;\n        local_nodal_coordinates(a, 1) = s;\n    }\n    compute_extrapolation_matrix(N_matrix, local_nodal_coordinates, local_quadrature_coordinates);\n}\n\ndouble triangle6::compute_measure(matrix const& nodal_coordinates)\n{\n    return m_quadrature->integrate(0.0, [&](auto const& femval, auto) {\n        auto const& [N, dN] = femval;\n\n        matrix2 const Jacobian = geometry::project_to_plane(nodal_coordinates) * dN;\n\n        return Jacobian.determinant();\n    });\n}\n}\n", "meta": {"hexsha": "52ddc1969c515d4a4a23478196a94a11aed5af95", "size": 3704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interpolations/triangle.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/triangle.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/triangle.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": 26.8405797101, "max_line_length": 98, "alphanum_fraction": 0.5718142549, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.585174349370567}}
{"text": "#include <vector>\n\n#include <glm/glm.hpp>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include \"Types.h\"\n#include \"Dynamic.h\"\n\nnamespace{\n    using namespace BalloonFEM;\n    const Vec3 v[4] = {Vec3(0), Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)};\n    const Mat3 m[4][3] = {\n        { Mat3(v[1], v[0], v[0]), Mat3(v[2], v[0], v[0]), Mat3(v[3], v[0], v[0])},\n        { Mat3(v[0], v[1], v[0]), Mat3(v[0], v[2], v[0]), Mat3(v[0], v[3], v[0])},\n        { Mat3(v[0], v[0], v[1]), Mat3(v[0], v[0], v[2]), Mat3(v[0], v[0], v[3])},\n        { -Mat3(v[1], v[1], v[1]), -Mat3(v[2], v[2], v[2]), -Mat3(v[3], v[3], v[3])}\n    };\n\n}\n\nnamespace BalloonFEM\n{\n    void Engine::computeElasticForces(ObjState &state, Vvec3 &f_sum)\n    {\n        Vvec3 &pos = state.world_space_pos;\n\n        for(TIter t = m_tetra->tetrahedrons.begin();\n                t != m_tetra->tetrahedrons.end(); t++)\n        {\n            iVec4 &id = t->v_id;\n            Vec3 &v0 = pos[id[0]];\n            Vec3 &v1 = pos[id[1]];\n            Vec3 &v2 = pos[id[2]];\n            Vec3 &v3 = pos[id[3]];\n            \n            /* calculate deformation in world space */\n            Mat3 Ds = Mat3(v0 - v3, v1 - v3, v2 - v3);\n\n            /* calculate deformation gradient */\n            Mat3 F = Ds * t->Bm;\n\n            /* calculate Piola for this tetra */\n            Mat3 P = m_volume_model->Piola(F);\n\n            /* calculate forces contributed from this tetra */\n            Mat3 H = - t->W * P * transpose(t->Bm);\n\n            f_sum[id[0]] += H[0];\n            f_sum[id[1]] += H[1];\n            f_sum[id[2]] += H[2];\n            f_sum[id[3]] -= H[0] + H[1] + H[2];\n        }\n    }\n\n    SpMat Engine::computeElasticDiffMat(ObjState &state)\n    {\t\n        printf(\"building elastic differential matrix \\n\");\n        /* project from constrained freedom state to world space */\n\t\tVvec3 &pos = state.world_space_pos;\n\t    \n        /* compute elastic force Differentials */\n\t\tstd::vector<T> coefficients;\n\t\tcoefficients.clear();\n\t\tcoefficients.reserve( 12 * 12 * m_tetra->num_vertex);\n\n\t\tfor(TIter t = m_tetra->tetrahedrons.begin();\n\t\t\t\tt != m_tetra->tetrahedrons.end(); t++)\n\t\t{\n\t\t\t/* assgin world space position */\n\t\t\tiVec4 &id = t->v_id;\n\t\t\tVec3 &v0 = pos[id[0]];\n\t\t\tVec3 &v1 = pos[id[1]];\n\t\t\tVec3 &v2 = pos[id[2]];\n\t\t\tVec3 &v3 = pos[id[3]];\n            \n\t\t\t/* calculate deformation in world space */\n\t\t\tMat3 Ds = Mat3(v0 - v3, v1 - v3, v2 - v3);\n\n\t\t\t/* calculate deformation gradient */\n\t\t\tMat3 F = Ds * t->Bm;\n            \n\t\t\t/* i is index of vertex, j is index of dimention */\n\t\t\tfor (size_t i = 0; i < 4; i++)\n\t\t\t\tfor(size_t j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\t/* calculate delta deformation in world space */\n\t\t\t\tMat3 dDs = m[i][j]; \n\n\t\t\t\t/* calculate delta deformation gradient */\n\t\t\t\tMat3 dF = dDs * t->Bm;\n\n\t\t\t\t/* calculate delta Piola */\n\t\t\t\tMat3 dP = m_volume_model->StressDiff(F, dF);\n \n\t\t\t\t/* calculate forces contributed from this tetra */\n\t\t\t\tMat3 dH = - t->W * dP * transpose(t->Bm);\n\n\t\t\t\tfor(size_t w = 0; w < 3; w++)\n\t\t\t\t\tfor(size_t l = 0; l < 3; l++)\n\t\t\t\t\t\tcoefficients.push_back( T(3*id[w] + l, 3*id[i] + j,  dH[w][l]));\n\n\t\t\t\tVec3 df_4 = - dH[0] - dH[1] - dH[2];\n\t\t\t\tfor(size_t l = 0; l < 3; l++)\n\t\t\t\t\tcoefficients.push_back( T(3*id[3] + l, 3*id[i] + j,  df_4[l]));\n\t\t\t}\n\t\t}\n\t\tSpMat E( 3 * pos.size(), 3 * pos.size());\n\t\tE.setFromTriplets(coefficients.begin(), coefficients.end());\n\n        return E;\n    }\n}\n\n", "meta": {"hexsha": "4fd6af662e93b14ff3115c51c530ec27454159e1", "size": 3384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Dynamic_Elastic.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_Elastic.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_Elastic.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": 29.1724137931, "max_line_length": 84, "alphanum_fraction": 0.5141843972, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5851743395335263}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2014 Basil Fierz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// VCL configuration\n#include <vcl/config/global.h>\n\n// C++ standard library\n#include <iostream>\n#include <random>\n\n// Eigen library\n#include <Eigen/Dense>\n\n// Google benchmark\n#include \"benchmark/benchmark.h\"\n\n// VCL\n#include <vcl/core/simd/vectorscalar.h>\n#include <vcl/core/interleavedarray.h>\n#include <vcl/math/jacobieigen33_selfadjoint.h>\n#include <vcl/math/jacobieigen33_selfadjoint_quat.h>\n#include <vcl/util/precisetimer.h>\n\n#include \"problems.h\"\n\n// Global data store for one time problem setup\nconst size_t nr_problems = 1024 * 1024;\n\n// Problem set\nVcl::Core::InterleavedArray<float, 3, 3, -1> F(nr_problems);\n\nvoid perfEigenIterative(benchmark::State& state)\n{\n\tVcl::Core::InterleavedArray<float, 3, 3, -1> resU(state.range(0));\n\tVcl::Core::InterleavedArray<float, 3, 1, -1> resS(state.range(0));\n\n\tfor (auto _ : state)\n\t{\n\t\tfor (int i = 0; i < state.range(0); ++i)\n\t\t{\n\t\t\tVcl::Matrix3f A = F.at<float>(i);\n\n\t\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\t\tresU.at<float>(i) = solver.eigenvectors();\n\t\t\tresS.at<float>(i) = solver.eigenvalues();\n\t\t}\n\t}\n\n\tstate.counters[\"Iterations\"] = 0;\n\tbenchmark::DoNotOptimize(resU);\n\tbenchmark::DoNotOptimize(resS);\n\n\tstate.SetItemsProcessed(state.iterations() * state.range(0));\n}\n\nvoid perfEigenDirect(benchmark::State& state)\n{\n\tVcl::Core::InterleavedArray<float, 3, 3, -1> resU(state.range(0));\n\tVcl::Core::InterleavedArray<float, 3, 1, -1> resS(state.range(0));\n\n\tfor (auto _ : state)\n\t{\n\t\tfor (int i = 0; i < state.range(0); ++i)\n\t\t{\n\t\t\tVcl::Matrix3f A = F.at<float>(i);\n\n\t\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\t\tsolver.computeDirect(A, Eigen::ComputeEigenvectors);\n\n\t\t\tresU.at<float>(i) = solver.eigenvectors();\n\t\t\tresS.at<float>(i) = solver.eigenvalues();\n\t\t}\n\t}\n\n\tstate.counters[\"Iterations\"] = 0;\n\tbenchmark::DoNotOptimize(resU);\n\tbenchmark::DoNotOptimize(resS);\n\n\tstate.SetItemsProcessed(state.iterations() * state.range(0));\n}\n\ntemplate<typename WideScalar>\nvoid perfJacobi(benchmark::State& state)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\n\tVcl::Core::InterleavedArray<float, 3, 3, -1> resU(state.range(0));\n\tVcl::Core::InterleavedArray<float, 3, 1, -1> resS(state.range(0));\n\n\tint avg_nr_iter = 0;\n\tfor (auto _ : state)\n\t{\n\t\tavg_nr_iter = 0;\n\t\tfor (int i = 0; i < state.range(0) / width; ++i)\n\t\t{\n\t\t\tmatrix3_t A = F.at<real_t>(i);\n\t\t\tmatrix3_t U = matrix3_t::Identity();\n\n\t\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigen(A, U);\n\n\t\t\tresU.at<real_t>(i) = U;\n\t\t\tresS.at<real_t>(i) = A.diagonal();\n\t\t}\n\t}\n\n\tstate.counters[\"Iterations\"] = (double)(avg_nr_iter * width) / (double)state.range(0);\n\tbenchmark::DoNotOptimize(resU);\n\tbenchmark::DoNotOptimize(resS);\n\n\tstate.SetItemsProcessed(state.iterations() * state.range(0));\n}\n\ntemplate<typename WideScalar>\nvoid perfJacobiQuat(benchmark::State& state)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\n\tVcl::Core::InterleavedArray<float, 3, 3, -1> resU(state.range(0));\n\tVcl::Core::InterleavedArray<float, 3, 1, -1> resS(state.range(0));\n\n\tint avg_nr_iter = 0;\n\tfor (auto _ : state)\n\t{\n\t\tavg_nr_iter = 0;\n\t\tfor (int i = 0; i < state.range(0) / width; ++i)\n\t\t{\n\t\t\tmatrix3_t A = F.at<real_t>(i);\n\t\t\tmatrix3_t U = matrix3_t::Identity();\n\n\t\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigenQuat(A, U);\n\n\t\t\tresU.at<real_t>(i) = U;\n\t\t\tresS.at<real_t>(i) = A.diagonal();\n\t\t}\n\t}\n\n\tstate.counters[\"Iterations\"] = (double)(avg_nr_iter * width) / (double)state.range(0);\n\tbenchmark::DoNotOptimize(resU);\n\tbenchmark::DoNotOptimize(resS);\n\n\tstate.SetItemsProcessed(state.iterations() * state.range(0));\n}\n\nusing Vcl::float16;\nusing Vcl::float4;\nusing Vcl::float8;\n\nBENCHMARK(perfEigenIterative)->Arg(128); // ->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK(perfEigenDirect)->Arg(128);    // ->Arg(512)->Arg(8192)->ThreadRange(1, 16);\n\nBENCHMARK_TEMPLATE(perfJacobi, float)->Arg(128);   //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobi, float4)->Arg(128);  //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobi, float8)->Arg(128);  //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobi, float16)->Arg(128); //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\n\nBENCHMARK_TEMPLATE(perfJacobiQuat, float)->Arg(128);   //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobiQuat, float4)->Arg(128);  //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobiQuat, float8)->Arg(128);  //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\nBENCHMARK_TEMPLATE(perfJacobiQuat, float16)->Arg(128); //->Arg(512)->Arg(8192)->ThreadRange(1, 16);\n\nint main(int argc, char** argv)\n{\n\t// Initialize data\n\tcreateSymmetricProblems(nr_problems, F);\n\n\t::benchmark::Initialize(&argc, argv);\n\t::benchmark::RunSpecifiedBenchmarks();\n}\n", "meta": {"hexsha": "ff9edc66e0c5eff11e0c1e89b6a079a6a6fce20c", "size": 6179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmarks/vcl.math/eigen33_performance.cpp", "max_stars_repo_name": "bfierz/vcl", "max_stars_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T09:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T13:00:17.000Z", "max_issues_repo_path": "src/benchmarks/vcl.math/eigen33_performance.cpp", "max_issues_repo_name": "bfierz/vcl", "max_issues_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2015-05-14T09:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:09:06.000Z", "max_forks_repo_path": "src/benchmarks/vcl.math/eigen33_performance.cpp", "max_forks_repo_name": "bfierz/vcl", "max_forks_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-04-18T06:16:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T08:00:12.000Z", "avg_line_length": 31.0502512563, "max_line_length": 99, "alphanum_fraction": 0.7031882182, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5851658137973214}}
{"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_YN_HPP\n#define BOOST_MATH_BESSEL_YN_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/special_functions/detail/bessel_y0.hpp>\n#include <boost/math/special_functions/detail/bessel_y1.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_series.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\n// Bessel function of the second kind of integer order\n// Y_n(z) is the dominant solution, forward recurrence always OK (though unstable)\n\nnamespace boost { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT bessel_yn(int n, T x, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n    T value, factor, current, prev;\n\n    using namespace boost::math::tools;\n\n    static const char* function = \"boost::math::bessel_yn<%1%>(%1%,%1%)\";\n\n    if ((x == 0) && (n == 0))\n    {\n       return -policies::raise_overflow_error<T>(function, 0, pol);\n    }\n    if (x <= 0)\n    {\n       return policies::raise_domain_error<T>(function,\n            \"Got x = %1%, but x must be > 0, complex result not supported.\", x, pol);\n    }\n\n    //\n    // Reflection comes first:\n    //\n    if (n < 0)\n    {\n        factor = (n & 0x1) ? -1 : 1;  // Y_{-n}(z) = (-1)^n Y_n(z)\n        n = -n;\n    }\n    else\n    {\n        factor = 1;\n    }\n\n    if(x < policies::get_epsilon<T, Policy>())\n    {\n       T scale = 1;\n       value = bessel_yn_small_z(n, x, &scale, pol);\n       if(tools::max_value<T>() * fabs(scale) < fabs(value))\n          return boost::math::sign(scale) * boost::math::sign(value) * policies::raise_overflow_error<T>(function, 0, pol);\n       value /= scale;\n    }\n    else if (n == 0)\n    {\n        value = bessel_y0(x, pol);\n    }\n    else if (n == 1)\n    {\n        value = factor * bessel_y1(x, pol);\n    }\n    else\n    {\n       prev = bessel_y0(x, pol);\n       current = bessel_y1(x, pol);\n       int k = 1;\n       BOOST_ASSERT(k < n);\n       do\n       {\n           T fact = 2 * k / x;\n           if((tools::max_value<T>() - fabs(prev)) / fact < fabs(current))\n           {\n              prev /= current;\n              factor /= current;\n              current = 1;\n           }\n           value = fact * current - prev;\n           prev = current;\n           current = value;\n           ++k;\n       }\n       while(k < n);\n       if(fabs(tools::max_value<T>() * factor) < fabs(value))\n          return sign(value) * sign(value) * policies::raise_overflow_error<T>(function, 0, pol);\n       value /= factor;\n    }\n    return value;\n}\n\n}}} // namespaces\n\n#endif // BOOST_MATH_BESSEL_YN_HPP\n\n", "meta": {"hexsha": "b4f9855a2f6ff9014e694823dfb924bd093806ad", "size": 2774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/special_functions/detail/bessel_yn.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/math/special_functions/detail/bessel_yn.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T10:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-06T09:10:33.000Z", "max_forks_repo_path": "boost/boost/math/special_functions/detail/bessel_yn.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 26.6730769231, "max_line_length": 123, "alphanum_fraction": 0.5753424658, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5851384044348851}}
{"text": "#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <sstream>\n\n#pragma warning( push )\n# pragma warning (disable:4800)\n#include <Eigen/Dense>\n#include <Eigen/StdVector> //NodeArray, EdgeArray\n#pragma warning( pop )\n\nnamespace cmg {\n\ttypedef double Precision;\n\ttypedef Eigen::Matrix<Precision, Eigen::Dynamic, Eigen::Dynamic> MatT;\n\ttypedef Eigen::Matrix<Precision, Eigen::Dynamic, 1> VecT;\n\ttypedef Eigen::Matrix<Precision, 2, 2> Mat2T;\n\ttypedef Eigen::Matrix<Precision, 2, 1> Vec2T;\n\ttypedef Eigen::Matrix<Precision, 3, 3> Mat3T;\n\ttypedef Eigen::Matrix<Precision, 3, 1> Vec3T;\n\ttypedef Eigen::Matrix<Precision, 4, 4> Mat4T;\n\ttypedef Eigen::Matrix<Precision, 4, 1> Vec4T;\n\ttypedef Eigen::Matrix<Precision, 6, 6> Mat6T;\n\ttypedef Eigen::Matrix<Precision, 6, 1> Vec6T;\n\ttypedef Eigen::Matrix<Precision, 2, 4> Mat2x4T;\n\ttypedef Eigen::Matrix<Precision, 4, 2> Mat4x2T;\n\ttypedef Eigen::Matrix<Precision, 3, 4> Mat3x4T;\n\ttypedef Eigen::Matrix<Precision, 4, 3> Mat4x3T;\n\n\tinline static Precision eps() {\n\t\treturn 10*std::numeric_limits<Precision>::epsilon();\n\t}\n\n\ttypedef std::vector<int> Veci;\n\tinline static void range(const int start, const int end, const int step, Veci& ret)\n\t{\n\t\tret.clear();\n\t\tret.reserve((end-start+1)/step);\n\t\tfor(int v=start; v<=end; v+=step) ret.push_back(v);\n\t\tret.resize(ret.size());\n\t}\n\n\tinline static Precision perimeter(const Mat2x4T& u)\n\t{\n\t\tPrecision ret=0;\n\t\tfor(int i=0; i<4; ++i) {\n\t\t\tret += (u.col(i) - u.col((i+1)%4)).norm();\n\t\t}\n\t\treturn ret;\n\t}\n\n\tstruct Calibration {\n\t\tVec4T k;\t\t//[fx, fy, cx, cy]\n\t\tVec2T d;\t\t//[k1, k2]\n\t\tMat4T Ck;\t\t//Cov[k]\n\t\tMat2T Cd;\t\t//Cov[d]\n\tpublic:\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tinline Mat3T K() const\n\t\t{\n\t\t\tMat3T ret;\n\t\t\tret.setIdentity();\n\t\t\tret(0,0)=k(0);\n\t\t\tret(1,1)=k(1);\n\t\t\tret(0,2)=k(2);\n\t\t\tret(1,2)=k(3);\n\t\t\treturn ret;\n\t\t}\n\n\t\tinline void print() const\n\t\t{\n\t\t\tstd::cout<<\"k=\"<<k.transpose()<<std::endl;\n\t\t\tstd::cout<<\"d=\"<<d.transpose()<<std::endl;\n\t\t\t//std::cout<<\"Ck=\\n\"<<Ck<<std::endl; //TODO: Ck, Cd not used yet\n\t\t\t//std::cout<<\"Cd=\\n\"<<Cd<<std::endl;\n\t\t}\n\n\t\ttemplate<typename T>\n\t\tvoid project(const T X[3], T U[2]) const\n\t\t{\n\t\t\tT fx(k(0)), fy(k(1)), cx(k(2)), cy(k(3));\n\t\t\tT k1(d(0)), k2(d(1));\n\n\t\t\tT xn( X[0]/X[2] ), yn( X[1]/X[2] );\n\t\t\tT r2 = xn*xn + yn*yn;\n\t\t\tT factor=T(1)+(k2*r2+k1)*r2;\n\t\t\tT xnp=xn*factor;\n\t\t\tT ynp=yn*factor;\n\t\t\tU[0] = fx*xnp+cx;\n\t\t\tU[1] = fy*ynp+cy;\n\t\t}\n\n\t\tVec2T project(const Vec3T& X) const\n\t\t{\n\t\t\tVec2T ret;\n\t\t\tproject(X.data(), ret.data());\n\t\t\treturn ret;\n\t\t}\n\t};\n\n\t//6D pose\n\tstruct Pose {\n\t\tVec6T p;\t\t//[ra*rx,ra*ry,ra*rz,tx,ty,tz]\n\t\tMat6T Cp;\t\t//Cov[p]\n\tpublic:\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tstatic int nParams() { return 6; }\n\n\t\tinline Vec3T transform(const Vec3T& X) const\n\t\t{\n\t\t\treturn (toT() * X.homogeneous()).hnormalized();\n\t\t}\n\n\t\t//return rotation matrix R\n\t\tinline Mat3T R() const\n\t\t{\n\t\t\tPrecision ang = p.head<3>().norm();\n\t\t\tVec3T axis(1,0,0);\n\t\t\tif(ang>eps())\n\t\t\t\taxis = p.head<3>().normalized();\n\t\t\telse\n\t\t\t\tang = 0;\n\t\t\tEigen::AngleAxis<Precision> aa(ang, axis);\n\t\t\treturn aa.toRotationMatrix();\n\t\t}\n\n\t\t//return translation vector t\n\t\tinline Vec3T t() const\n\t\t{\n\t\t\treturn p.tail<3>();\n\t\t}\n\n\t\t//return T=[R,t;0,1]\n\t\tinline Mat4T toT() const\n\t\t{\n\t\t\tMat4T ret;\n\t\t\tret.setIdentity();\n\t\t\tret.topLeftCorner<3,3>() = R();\n\t\t\tret.topRightCorner<3,1>() = t();\n\t\t\treturn ret;\n\t\t}\n\n\t\tinline Mat4T invT() const\n\t\t{\n\t\t\tMat3T rot = R().transpose();\n\t\t\tMat4T T;\n\t\t\tT.setIdentity();\n\t\t\tT.topLeftCorner<3,3>() = rot;\n\t\t\tT.topRightCorner<3,1>() = -rot * t();\n\t\t\treturn T;\n\t\t}\n\n\t\tinline Vec6T invp() const\n\t\t{\n\t\t\treturn T2p(invT());\n\t\t}\n\n\t\tinline void fromR(const Mat3T& R)\n\t\t{\n\t\t\tEigen::AngleAxis<Precision> aa;\n\t\t\taa.fromRotationMatrix(R);\n\t\t\tp.head<3>() = aa.axis() * aa.angle();\n\t\t}\n\n\t\tinline void fromt(const Vec3T& t)\n\t\t{\n\t\t\tp.tail<3>() = t;\n\t\t}\n\n\t\tinline void fromT(const Mat4T& T)\n\t\t{\n\t\t\tfromR(T.topLeftCorner<3,3>());\n\t\t\tfromt(T.topRightCorner<3,1>());\n\t\t}\n\n\t\tinline static Vec6T T2p(const Mat4T& T)\n\t\t{\n\t\t\treturn Pose(T).p;\n\t\t}\n\n\t\tinline static Mat4T p2T(const Vec6T& p)\n\t\t{\n\t\t\treturn Pose(p).toT();\n\t\t}\n\n\t\tPose() { p.setZero(); Cp.setZero(); }\n\t\tPose(const Vec6T& p_) : p(p_) {\n\t\t\tCp.setZero();\n\t\t}\n\t\tPose(const Mat4T& T) {\n\t\t\tfromT(T);\n\t\t\tCp.setZero();\n\t\t}\n\t\tPose(const Mat4T& T, const Mat6T& Covp) : Cp(Covp)\n\t\t{\n\t\t\tfromT(T);\n\t\t}\n\t};\n\ttypedef std::vector< Vec6T, Eigen::aligned_allocator<Vec6T> > Vec6TArray;\n\n\tstruct Node : public Pose {\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tstd::string name;\t//name of the marker\n\t\tVeci vmeids;\t\t//vmEdges' ids linked to this marker (not used now)\n\t};\n\ttypedef std::vector< Node, Eigen::aligned_allocator<Node> > NodeArray;\n\ttypedef int NID;\n\tconst NID INVALID_NID = -1;\n\n\tstruct Edge {\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tint vid;\t//id of view\n\t\tint mid;\t//id of marker\n\t\tMat2x4T u;\t//observations, 2x4, TODO: allow different observations\n\t};\n\ttypedef std::vector< Edge, Eigen::aligned_allocator<Edge> > EdgeArray;\n\ttypedef int EID;\n\tconst EID INVALID_EID = -1;\n\n\tstruct Observation {\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\t\tstd::string name;\t\t//marker's name\n\t\tPose init_marker_pose;\t//marker pose in view, i.e., Tmc\n\t\tMat2x4T u;\t\t\t\t//observed marker corners in view\n\n\t\tbool operator<(const Observation& other) const {\n\t\t\treturn perimeter(u) > perimeter(other.u);\n\t\t}\n\t};\n\ttypedef std::vector< Observation,  Eigen::aligned_allocator<Observation> > ObsArray;\n\ttypedef std::vector<ObsArray> VecObsArray;\n\n\ttypedef std::map<std::string, int> Str2Int;\n\n\tclass CMGraph {\n\tpublic: //member variables\n\t\tNodeArray markers;\n\t\tNodeArray views;\n\t\tEdgeArray edges;\n\t\t\n\t\tPose fixed_marker_pose;\n\t\tNID fixed_marker_id;\n\n\t\tCalibration calib;\n\t\tStr2Int name2mid; //name -> makrer id\n\n\t\tPrecision marker_half_size;\n\t\tbool verbose;\n\n\t\tstruct Callback {\n\t\t\tvirtual void operator()(const CMGraph& G) = 0;\n\t\t};\n\t\ttypedef Callback* CallbackPtr;\n\t\tCallbackPtr cb_addObsFromNewView;\n\t\tCallbackPtr cb_optimizeNewViewPose;\n\t\tCallbackPtr cb_optimizeOneViewPose;\n\t\tCallbackPtr cb_optimizePose;\n\n\n\tpublic: //member functions\n\t\tCMGraph() : fixed_marker_id(INVALID_NID), marker_half_size(1), verbose(true),\n\t\t\tcb_addObsFromNewView(0), cb_optimizeNewViewPose(0), cb_optimizeOneViewPose(0), cb_optimizePose(0)\n\t\t{}\n\n\t\t//print input information\n\t\tinline void print() const\n\t\t{\n\t\t\tstd::cout<<\"-------------------\"<<std::endl;\n\t\t\tstd::cout<<\"calib:\"<<std::endl;\n\t\t\tcalib.print();\n\t\t\tstd::cout<<std::endl;\n\n\t\t\tstd::cout<<\"marker_half_size=\"<<marker_half_size<<std::endl;\n\t\t\tstd::cout<<\"verbose=\"<<verbose<<std::endl;\n\t\t\tstd::cout<<\"-------------------\"<<std::endl;\n\t\t}\n\n\t\t//print CMGraph state\n\t\tvoid report(std::ofstream& out) const;\n\n\t\tinline int nParams() const\n\t\t{\n\t\t\treturn Pose::nParams()*static_cast<int>(markers.size()+views.size());\n\t\t}\n\n\t\tinline int nResiduals() const\n\t\t{\n\t\t\treturn nObsResiduals() + nCstResiduals();\n\t\t}\n\n\t\tinline int nObsResiduals() const\n\t\t{\n\t\t\treturn 8*static_cast<int>(edges.size()); //TODO: allow each marker to have more than 4 point observations\n\t\t}\n\n\t\tinline int nCstResiduals() const\n\t\t{\n\t\t\treturn Pose::nParams();\n\t\t}\n\n\t\tinline bool empty() const\n\t\t{\n\t\t\treturn nParams()<=0;\n\t\t}\n\n\t\tNID setFixedMarker(const std::string &fixed_marker_name,\n\t\t\tconst Precision p_ang=1e-4,\n\t\t\tconst Precision p_pos=1e-2);\n\n\t\t//add all observed markers in this view to the graph, and also add view and edges\n\t\t//oa will be sorted by descending order of perimeters of the observed markers in the image\n\t\tNID addObsFromNewView(\n\t\t\tObsArray& oa,\n\t\t\tconst std::string &view_name,\n\t\t\tconst bool addNewMarker=true);\n\n\t\tbool optimizeNewViewPose(\n\t\t\tObsArray& oa,\n\t\t\tNode& newView,\n\t\t\tconst Precision sigma_u,\n\t\t\tconst int max_iter,\n\t\t\tconst Precision huber_loss_bandwidth=10, // +/- 10 pixels\n\t\t\tconst Precision error_rel_tol=1e-2,\n\t\t\tconst bool computeCovariance=false);\n\n\t\tbool optimizeOneViewPose(\n\t\t\tconst NID vid,\n\t\t\tconst Precision sigma_u,\n\t\t\tconst int max_iter,\n\t\t\tconst Precision huber_loss_bandwidth=10, // +/- 10 pixels\n\t\t\tconst Precision error_rel_tol=1e-2,\n\t\t\tconst bool computeCovariance=false);\n\n\t\t//bundle adjustment to optimize all markers' and views' poses\n\t\tbool optimizePose(\n\t\t\tconst Precision sigma_u,\n\t\t\tconst int max_iter,\n\t\t\tconst Precision huber_loss_bandwidth=10, // +/- 10 pixels\n\t\t\tconst Precision error_rel_tol=1e-2,\n\t\t\tconst bool computeCovariance=false);\n\n\tpublic: //static functions\n\t\t//return 2D coordinates of a marker's 4 corners\n\t\tinline static Mat2x4T marker_x(const Precision half_size=1)\n\t\t{\n\t\t\tPrecision ret_[]={\n\t\t\t\t-1,-1,\n\t\t\t\t 1,-1,\n\t\t\t\t 1, 1,\n\t\t\t\t-1, 1\n\t\t\t};\n\n\t\t\tMat2x4T ret(ret_);\n\t\t\treturn ret * half_size;\n\t\t}\n\n\t\t//return 3D coordinates of a marker's 4 corners\n\t\tinline static Mat3x4T marker_X(const Precision half_size=1)\n\t\t{\n\t\t\tPrecision ret_[]={\n\t\t\t\t-1,-1, 0,\n\t\t\t\t 1,-1, 0,\n\t\t\t\t 1, 1, 0,\n\t\t\t\t-1, 1, 0\n\t\t\t};\n\n\t\t\tMat3x4T ret(ret_);\n\t\t\treturn ret * half_size;\n\t\t}\n\n\t\tstatic void BatchProcess(\n\t\t\tconst VecObsArray &frames, //each frame's Observations' order would be sorted\n\t\t\tconst Calibration &calib,\n\t\t\tCMGraph& G,\n\t\t\tconst std::string &fixed_marker_name=\"\",\n\t\t\tconst Precision p_ang=1e-4,\n\t\t\tconst Precision p_pos=1e-2,\n\t\t\tconst Precision sigma_u=0.2,\n\t\t\tconst int max_iter_per_opt=20,\n\t\t\tconst bool do_covariance_estimation=true);\n\n\tprotected:\n\t\tNID newMarker(const Vec6T& p, const Mat6T& Cp, const std::string& name);\n\n\t\tNID newView(const Vec6T& p, const Mat6T& Cp, const std::string& name);\n\n\t\tEID newEdge(const NID vid, const NID mid, const MatT& u);\n\t};\n}", "meta": {"hexsha": "abeff7a271dc551c747beea7488064c24d5576a8", "size": 9373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cmgraph.hpp", "max_stars_repo_name": "simbaforrest/masfm", "max_stars_repo_head_hexsha": "dd661023b694f5bcfb0ddad97c0c6559c91ee276", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T04:09:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T07:19:15.000Z", "max_issues_repo_path": "include/cmgraph.hpp", "max_issues_repo_name": "simbaforrest/masfm", "max_issues_repo_head_hexsha": "dd661023b694f5bcfb0ddad97c0c6559c91ee276", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-30T15:16:52.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-05T11:20:05.000Z", "max_forks_repo_path": "include/cmgraph.hpp", "max_forks_repo_name": "simbaforrest/masfm", "max_forks_repo_head_hexsha": "dd661023b694f5bcfb0ddad97c0c6559c91ee276", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-03-03T07:23:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T06:51:23.000Z", "avg_line_length": 23.7893401015, "max_line_length": 108, "alphanum_fraction": 0.6568868025, "num_tokens": 3108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5851383996057582}}
{"text": "#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n// this file implements the class defined in:\n#include \"calibration/Calibration.h\"\n\nusing namespace Eigen;\nusing namespace calibration;\n// constructor\nCalibration::Calibration()\n{\n\tRzOK_ = Matrix3f::Identity();\n\tRxOK_ = Matrix3f::Identity();\n\tTzOK_ = Matrix4f::Identity();\n\tTxOK_ = Matrix4f::Identity();\n}\n\n// destructor\nCalibration::~Calibration()\n{\n\t// empty destructor\n}\n\n// set functions\nvoid Calibration::setInput(const std::vector<Matrix4f> Ta, const std::vector<Matrix4f> Tb)\n{\n\n\t// set poses number from transformations size\n\t// check the transformations have the same poses number\n\n\tint na = Ta.size();\n\tint nb = Tb.size();\n\n\tif ( (na != nb) )\n\t{\n\t\tstd::cerr << \"rotation matrix dimension not compatible!! \" << std::endl;\n\t\treturn;\n\t}\n\n\t// n_poses_ is the actual number of poses recorded by camera\n\tn_poses_ = (na%2 == 0)? na : na - 1;\n\n\n\t// std::cout << \"Calibrating for \" << n_poses_ << \" poses...\" << std::endl;\n\n\t//resizeAllParametres();\n\t//std::cout << \"all matrices resized \" << std::endl;\n\n\t// push rotations and translations in respective vectors\n\n\tRa_.clear();\n\tRb_.clear();\n\tta_.clear();\n\ttb_.clear();\n\n\tfor (int i = 0 ; i < n_poses_  ;i++) \n\t{ \n\t\tRa_.push_back( Ta[i].block<3,3>(0,0) );\n\n\t\t// std::cout << \"Ra_ pose  \" << i << std::endl << Ra_[i] << std::endl;\n\n\t\tRb_.push_back( Tb[i].block<3,3>(0,0) );\n\n\t\t// std::cout << \"Rb_ pose  \" << i << std::endl << Rb_[i] << std::endl;\n\n\t\tta_.push_back( Ta[i].block<3,1>(0,3) );\n\n\t\t// std::cout << \"ta_ pose  \" << i << std::endl << ta_[i] << std::endl;\n\n\t\ttb_.push_back( Tb[i].block<3,1>(0,3) );\n\n\t\t// std::cout << \"tb_ pose  \" << i << std::endl << tb_[i] << std::endl;\n\n\t}\n\n\t//std::cout << \"rotation part extracted \" << std::endl;\n\t\t\t\t\t\t\t  \n}\n\n// resize all parametres\n\nint Calibration::resizeAllParametres()\n{\n\tQqA_.resize(n_poses_);\n\tWqB_.resize(n_poses_);\n\tCi_.resize(n_poses_);\n\tRa_.resize(n_poses_);\n\tRb_.resize(n_poses_);\n\tRx_.resize(n_poses_);\n\tRz_.resize(n_poses_);\n\tSq_a.resize(n_poses_);\n\tSq_b.resize(n_poses_);\n\tqa_.resize(n_poses_);\n\tqb_.resize(n_poses_);\n\t//qx_.resize(n_elem_);\n\t//qz_.resize(n_elem_);\n\tta_.resize(n_poses_);\n\ttb_.resize(n_poses_);\n\ttx_.resize(n_poses_/2);\n\ttz_.resize(n_poses_/2);\n\treturn 0;\n}\n\n// dual quaternions evaluation\n/* \n\tby the skewsymmetrics we can obtain the dual quaternions Q and W as\n\tcombination of the skewsymmetric and the relative quaternion so to have\n\tqAi * qX = Q(qAi) qX, where \"*\" is vect prod, and also\n\tqBi * qZ = W(qBi) qZ, that can substitute qA * qX = qZ *qB as\n\tQ(qAi) qX - W(qBi) qZ = 0\n\n\tQ(qAi) = [  qA0         -qA'\n\t\t\t\tqA      qA0*I + S(qA)]\n\n\tW(qBi) = [  qB0         -qB'\n\t\t\t\tqB      qB0*I - S(qB)]\n\n*/\t\nint Calibration::computeDualQuaternion()\n{\n\t// compute skewsymmetric\n\n\tMatrix3f Sqa, Sqb;\n\tMatrix4f QqA, WqB;\n\tQuaternionf use;\n\n\tfor (int i = 0 ; i < n_poses_  ;i++) \n\t{\n\t\tSqa << 0, -qa_[i].z(), qa_[i].y(),\n\t\t\t   qa_[i].z(), 0, -qa_[i].x(),\n\t\t\t   -qa_[i].y(), qa_[i].x(), 0;\n\n\t\tSq_a.push_back(Sqa);\n\n\t\t//std::cout << \"from quaternion qa_\" << std::endl << Quaternionf(qa_[i]) << std::endl << \"the skewsymmetric Sq_a is \" << std::endl << Matrix4f(Sq_a[i]) << std::endl;\n\n\t\tSqb <<  0, -qb_[i].z(), qb_[i].y(),\n\t\t\t\tqb_[i].z(), 0, -qb_[i].x(),\n\t\t\t  \t-qb_[i].y(), qb_[i].x(), 0;\n\t\t\n\t\t//std::cout << \"from quaternion qb_\" << std::endl << Quaternionf(qb_[i]) << std::endl << \"the skewsymmetric Sq_b is \" << std::endl << Matrix4f(Sq_b[i]) << std::endl;\n\n\t\tQqA.block<3,3>(1,1) = Sqa + (qa_[i].w() * Matrix3f::Identity ());\n\t\tuse = qa_[i].conjugate();\n\t\tQqA.block<1,4>(0,0) = Vector4f( use.w(), use.x(), use.y(), use.z() ).transpose();\n\t\tuse = qa_[i];\n\t\tQqA.block<4,1>(0,0) = Vector4f( use.w(), use.x(), use.y(), use.z() );\n\n\t\t// std::cout  << \"QqA\" << QqA << std::endl;\n\t\t\n\t\tQqA_.push_back(QqA);\n\n\n\t\tWqB.block<3,3>(1,1) = -Sqb + (qb_[i].w() * Matrix3f::Identity ());\n\t\tuse = qb_[i].conjugate();\n\t\tWqB.block<1,4>(0,0) = Vector4f( use.w(), use.x(), use.y(), use.z() ).transpose();\n\t\tuse = qb_[i];\n\t\tWqB.block<4,1>(0,0) = Vector4f( use.w(), use.x(), use.y(), use.z() );\n\n\t\t// std::cout  << \"WqB\" << WqB << std::endl;\n\n\t\tWqB_.push_back( WqB );\n\t}\n\n\treturn 0;\n}\n\n\n\nint Calibration::computeClosedForm()\n{\n\ttransformRotations2Quaternions();\n\tcomputeDualQuaternion();\n\tcomputeC();\n\tcomputeFinalQuaternions();\n\ttransformQuaterions2Rotations();\n\tcomputeTranslations();\n\tsetOutput();\n\tcomputeError();\n\tstd::cout << \"Compute closed form done!\" << std::endl;\n\treturn 0;\n}\n\nint Calibration::computeNonLinOpt()\n{\n\tcomputeClosedForm();\n\tcomputeOneShot();\n\tsetOutput();\n\tcomputeError();\n\tstd::cout << \"Compute non linear optimization done!\" << std::endl;\n\treturn 0;\n}\n\n// C evaluation\n\n/*\n\nC matrix is the compute by the sum of the several Ci (orthogonal matrix of rank equal to 4)\nobtained as Ci = -Q (qAi)'W(qBi)\n\nC importance is due to its bond with qz and qx, because of qz is an eigenvector of the symmetric\nsemipositive definite matrix C'C and by that we can obtain qx = C qz/(lambda-n_poses)\n\n*/\n\nint Calibration::computeC()\n{\n\tC_ = Matrix4f::Zero();\n\tfor ( int i=0; i < n_poses_; i++ ) \n\t\tC_ += -QqA_[i].transpose()* WqB_[i];\n\treturn 0;\n}\n\n// final quaternions qxOK and qzOK evaluation\n// alpha and lambda evaluation by eigenvalues\n\n/*\n\nalpha is a 4 float vector made of the C'C eigenvalues \nlambda is n_poses,alpha combination (lambda = n_poses +/- sqrt (alpha))\nso to have the minimum positive of lambda choosing the best alpha of the list\n\nk_ is the best alpha index so to remember it also when compute the relative eigenvector\n\n*/\n\nint Calibration::computeFinalQuaternions()\n{\n\tEigenSolver<Matrix4f> solver (C_.transpose()*C_ );\n\talpha_ = solver.eigenvalues().real();\n\tk_= 0;\n\tfloat Lt;\n\n\tlambda_ = ((n_poses_ - sqrt(alpha_(k_)))>0) ? (n_poses_ - sqrt(alpha_(k_))) : (n_poses_ + sqrt(alpha_(k_)));\n\n\tfor (int i=1; i < 4;i++)\n\t{\n\t\tLt = n_poses_ - sqrt(alpha_[i]);\n\n\t\tif (Lt < lambda_ && Lt >0) \n\t\t{\n\t\t\tlambda_ = Lt; \n\t\t\tk_ = i; \n\t\t}\n\t\telse\n\t\t{\n\t\t\tLt = n_poses_ + sqrt(alpha_[i]);\n\t\t\tif (Lt < lambda_) \n\t\t\t{ \n\t\t\t\tlambda_ = Lt; \n\t\t\t\tk_ = i; \n\t\t\t}\n\t\t}\n\t}\n\n\tVector4f qzOK, qxOK;\n\t\n\tqzOK = solver.eigenvectors().col(k_).real();\n\tqxOK = C_*qzOK/(lambda_ - n_poses_);\n\n\tqxOK.normalize();\n\n\tqzOK_ = Quaternionf( qzOK[0], qzOK[1], qzOK[2], qzOK[3] );\n\tqxOK_ = Quaternionf( qxOK[0], qxOK[1], qxOK[2], qxOK[3] ); \n\n\treturn 0;\n}\n\n\n\n// transform all rotations needed to quaternions\n\nint Calibration::transformRotations2Quaternions()\n{\n\tfor (int i = 0; i < n_poses_; i++)\n\t{\n\t\tqa_.push_back( Quaternionf (Ra_[i]) );\n\t\tqb_.push_back( Quaternionf (Rb_[i]) );\n\t}\n\treturn 0;\n}\n\n// transform all quaternions needed to rotations (qxOK and qzOK)\n\nint Calibration::transformQuaterions2Rotations()\n{\n\tRxOK_ = qxOK_.toRotationMatrix();\n\tRzOK_ = qzOK_.toRotationMatrix();\n}\n\nint Calibration::computeTranslations()\n{\n\tif (n_poses_ == 1) \n\t{\n\t\tstd::cerr << \"translations not computable by only one rotation!! \" << std::endl;\n\t\treturn 0;\n\t}\n\n\ttxOK_ = Vector3f::Zero ();\n\ttzOK_ = Vector3f::Zero ();\n\n\tEigen::MatrixXf A;\n\tA.resize(3*n_poses_,6);\n\tEigen::VectorXf c;\n\tc.resize(3*n_poses_);\n\tEigen::VectorXf x;\n\tx.resize(6);\n\n\tfor (int i = 0; i < n_poses_ ; i++ )\n\t{\n\t\tA.block<3,3>(3*i,0) = Ra_[i];\n\t\tA.block<3,3>(3*i,3) = -1*Eigen::Matrix3f::Identity();\n\n\t\tc.block<3,1>(3*i,0) = RzOK_*tb_[i] - ta_[i];\n\t}\n\n\tMatrixXf Ainv;\n\tAinv.resize(6,6);\n\tAinv = A.transpose()*A;\n\n\tx = Ainv.inverse()*A.transpose()*c;\n\n\ttxOK_ = x.block<3,1>(0,0);\n\ttzOK_ = x.block<3,1>(3,0);\n\n\t/*for (int i = 0; i < n_poses_; i += 2)\n\t{\n\t\ttxOK_ += (Matrix3f ( Ra_[i] - Ra_[i+1]).inverse() )*( RzOK_*(tb_[i] - tb_[i+1]) + ta_[i+1] - ta_[i] );\n\t}\n\n\ttxOK_ *= 2/n_poses_;\n\t\n\tfor (int i = 0; i < n_poses_; i += 2)\n\t{\n\t\ttzOK_ += Ra_[i]*txOK_ + ta_[i] - RzOK_*tb_[i];\n\t}\n\n\ttzOK_ *= 2/n_poses_;*/\n\n\n\treturn 0;\n}\n\nint Calibration::computeError()\n{\n\tEr_ = 0;\n\n\tfloat EtNum = 0, EtDen = 1;\n\n\tfor (int i = 0; i < n_poses_; i++)\n\t{\n\t\tEr_ += Matrix3f( Ra_[i]*RxOK_ - RzOK_*Rb_[i] ).squaredNorm();\n\n\t\tEtDen += Vector3f( Ra_[i]*txOK_ - ta_[i] ).squaredNorm();\n\t\t\t\t  \n\t\tEtNum += Vector3f( Ra_[i]*txOK_ + ta_[i] - RzOK_*tb_[i] - tzOK_ ).squaredNorm();\n\n\t}\n\n\t//Et_ = sqrt(EtNum/EtDen);\n\tEt_ = EtNum/n_poses_;\n\tEr_ = Er_/n_poses_;\n\n\tstd::cout << \"Rotation error is: \" << Er_ << std::endl;\n\tstd::cout << \"Translation error is: \" << Et_ << std::endl;\n\n\treturn 0;\n}\n\nint Calibration::convertFromParamVect2ValuesOk(const VectorXf &in, Matrix3f &RzOK, Matrix3f &RxOK, Vector3f &tzOK, Vector3f &txOK)\n{\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tRxOK.col(i) = in.block<3,1>(3*i,0);\n\t\tRzOK.col(i) = in.block<3,1>((3*i)+9,0);\n\t}\n\n\ttxOK = in.block<3,1>(18,0);\t\n\ttzOK = in.block<3,1>(21,0);\n\nreturn 0;\n\n}\n\nint Calibration::convertFromValuesOk2ParamVect(const Matrix3f &RzOK, const Matrix3f &RxOK, const Vector3f &tzOK, const Vector3f &txOK, VectorXf &out)\n\n{\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tout.block<3,1>(3*i,0) = RxOK.col(i);\n\t\tout.block<3,1>((3*i)+9,0) = RzOK.col(i);\n\t}\n\n\tout.block<3,1>(18,0) = txOK;\t\n\tout.block<3,1>(21,0) = tzOK;\n\n\t//std::cout << \"out: \" << out << std::endl;\n\nreturn 0;\n\t\n}\n\nvoid Calibration::setOutput()\n{\n\tTzOK_.block<3,3>(0,0) = RzOK_;\n\tTzOK_.block<3,1>(0,3) = tzOK_;\n\n\tTxOK_.block<3,3>(0,0) = RxOK_;\n\tTxOK_.block<3,1>(0,3) = txOK_;\n\n\treturn;\n}\n\nvoid Calibration::getOutput(Matrix4f &TzOK, Matrix4f &TxOK)\n{\n\tTzOK = TzOK_;\n\tTxOK = TxOK_;\n\treturn;\n}\n\nvoid Calibration::getFullOutput(Matrix4f &TzOK, Matrix4f &TxOK, float &Er, float &Et)\n{\n\tgetOutput(TzOK, TxOK);\n\tEr = Er_;\n\tEt = Et_;\n\treturn;\n}\n\nint Calibration::computeOneShot()\n{\n\tFF_.n_poses__ = n_poses_;\n\tFF_.Ra__ = Ra_;\n\tFF_.Rb__ = Rb_;\n\tFF_.ta__ = ta_;\n\tFF_.tb__ = tb_;\n\n\tEigen::NumericalDiff<my_functor> numDiff(FF_);\n\tEigen::LevenbergMarquardt<Eigen::NumericalDiff<my_functor>,float> lm_solver(numDiff);\n\n\tEigen::VectorXf x(24);\n\tEigen::VectorXf x_ini(24);\n\n\t// from initial guess to x\n\tconvertFromValuesOk2ParamVect(RzOK_, RxOK_, tzOK_, txOK_, x);\n\t\n\t//x.setRandom();\n\tx_ini = x;\n\t// std::cout << \"initial guess x : \" << std::endl << x << std::endl;\n\n\t// init solver parameters\n\tlm_solver.parameters.maxfev = 2000;\n\t//lm_solver.parameters.xtol = 1.0e-10;\n\t//lm_solver.parameters.ftol = 1.0e-10;\n\n\tEigen::LevenbergMarquardtSpace::Status status = lm_solver.minimize(x);\n\n\tstd::cout << \"Iterations in optimization before ending: \" << lm_solver.iter << std::endl;\n\tstd::cout << \"lm_solver.nfev \" << lm_solver.nfev << std::endl;\n\tstd::cout << \"lm_solver.njev \" << lm_solver.njev << std::endl;\n\tstd::cout << \"lm_solver.fnorm \" << lm_solver.fnorm << std::endl;\n\tstd::cout << \"status code: \" << status << std::endl;\n\t// std::cout << \"x that minimizes the function: \" << std::endl << x << std::endl;\n\n\tstd::cout << \"|x_ini - x_opt|: \" << std::endl << x_ini-x << std::endl;\n\n\t// from x to solution\n\tconvertFromParamVect2ValuesOk(x, RzOK_, RxOK_, tzOK_, txOK_);\n\n\tstd::cout << \"RxOK_.determinant() : \" << RxOK_.determinant() << std::endl;\n\tstd::cout << \"RzOK_.determinant() : \" << RzOK_.determinant() << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "e2fe66f9cd6fd5717bd514ec5bd0883f7e8b2258", "size": 11017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Calibration.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": "src/Calibration.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": "src/Calibration.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": 22.9043659044, "max_line_length": 167, "alphanum_fraction": 0.6235817373, "num_tokens": 3985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5851383979567044}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n  MatrixXf m(2, 2);\n  MatrixXf n(2, 2);\n  MatrixXf result(2, 2);\n\n  m << 1, 2,\n      3, 4;\n  n << 5, 6,\n      7, 8;\n\n  result = (m.array() + 4).matrix() * m;\n  cout << \"-- Combination 1: --\" << endl << result << endl << endl;\n  result = (m.array() * n.array()).matrix() * m;\n  cout << \"-- Combination 2: --\" << endl << result << endl << endl;\n}\n", "meta": {"hexsha": "2a03a32e5a6e8b3b977eae8114d86df265eb5864", "size": 447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_interop.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": 20.3181818182, "max_line_length": 67, "alphanum_fraction": 0.5279642058, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5850525956117083}}
{"text": "/**\n * ECI to ECEF conversion matrices\n *\n * Copyright 2013 Bruce Ide\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n */\n\n#include <Eigen/Core>\n#include \"gmst.hpp\"\n\n#ifndef _HPP_CONVERSION_MATRICES\n#define _HPP_CONVERSION_MATRICES\n\nnamespace fr {\n\n  namespace coordinates {\n\n    // 6x6 population is the same for both classes, so may as well\n    // only write it once.\n    class ec_conversion_matrix_interface {\n    public:\n      ec_conversion_matrix_interface()\n      {\n      }\n\n      virtual Eigen::Matrix3d get() = 0;\n      virtual Eigen::Matrix3d get_dot() = 0;\n\n      virtual Eigen::Matrix<double,6,6> get_xyz_vel()\n      {\n\tEigen::Matrix3d mat = get();\n\tEigen::Matrix3d mat_dot = get_dot();\n\tEigen::Matrix<double,6,6> retval;\n\t\n\tfor (register int i = 0; i < 3; ++i) {\n\t  for (register int j = 0; j < 3; ++j) {\n\t    retval(i,j) = mat(i,j);\n\t    retval(i,j+3) = 0;\n\t    retval(i+3,j) = mat_dot(i,j);\n\t    retval(i+3,j+3) = mat(i,j);\n\t  }\n\t}\n\treturn retval;\n      }\n    };\n\n    /**\n     * This class requires a time at which the coordinate was observed.\n     */\n\n    class eci_to_ecef : public ec_conversion_matrix_interface {\n      double at_time;\n      double gha_rad;\n      double st,ct;\n      double we;\n      \n    public:\n      eci_to_ecef(const double &at_time) : at_time(at_time)\n      {\n\tfr::time::gmst time_gmst(at_time);\n\tgha_rad = time_gmst.get_gmst() * 2.0 * fr::constants::pi / fr::constants::secs_per_ut1_day;\n\tst = sin(gha_rad);\n\tct = cos(gha_rad);\n\twe = fr::constants::ut1_sideral_day_ratio * 2.0 * fr::constants::pi / fr::constants::secs_per_ut1_day;\n      }\n\n      ~eci_to_ecef()\n      {\n      }\n\n      Eigen::Matrix3d get()\n      {\n\tEigen::Matrix3d retval;\n\tretval << ct,st,0.0,\n\t  -1.0 * st,ct,0.0,\n\t  0.0,0.0,1.0;\n\treturn retval;\n      }\n\n      Eigen::Matrix3d get_dot()\n      {\n\tEigen::Matrix3d retval;\n\tretval << (-1.0 * we) * st, we * ct, 0.0,\n\t  (-1.0 * we) * ct, -we * st, 0.0,\n\t  0.0,0.0,0.0;\n\treturn retval;\n      }\n\n    };\n\n    // We can just transpose the eci to ecef matrix to get the ecef to\n    // eci matrix\n\n    class ecef_to_eci : public ec_conversion_matrix_interface {\n      eci_to_ecef worker;\n    public:\n      ecef_to_eci(const double &at_time) : worker(at_time)\n      {\n      }\n\n      ~ecef_to_eci()\n      {\n      }\n\n      Eigen::Matrix3d get()\n      {\n\tEigen::Matrix3d interim = worker.get();\n\tEigen::Matrix3d retval = interim.transpose();\n\treturn retval;\n      }\n\n      Eigen::Matrix3d get_dot()\n      {\n\tEigen::Matrix3d retval = worker.get_dot().transpose();\n\treturn retval;\n      }\n      \n    };\n\n  }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "52a6faffab69c50838c3dbc503eb99341d21e7c6", "size": 3082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "conversion_matrices.hpp", "max_stars_repo_name": "FlyingRhenquest/coordinates", "max_stars_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conversion_matrices.hpp", "max_issues_repo_name": "FlyingRhenquest/coordinates", "max_issues_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T12:28:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T06:36:53.000Z", "max_forks_repo_path": "conversion_matrices.hpp", "max_forks_repo_name": "FlyingRhenquest/coordinates", "max_forks_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T16:17:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:48:59.000Z", "avg_line_length": 22.496350365, "max_line_length": 103, "alphanum_fraction": 0.6171317326, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5850236297422959}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n#include <math.h>\n\n#include <unsupported/Eigen/MatrixFunctions>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace Eigen;\n//using Eigen::MatrixXd;\n\nMatrixXd readMatrix(const char *filename)\n{\n    std::ifstream indata;\n\n    indata.open(filename);\n\n    std::string line;\n    getline(indata, line);\n    std::stringstream lineStream(line);\n    std::string cell;\n    int count = 0, raw, coll;\n    while (std::getline(lineStream, cell, ','))\n    {\n        if(count == 0) raw = stoi(cell);\n        else coll = stoi( cell );\n        count++;\n    }\n    MatrixXd res(raw,coll);\n    cout<<\"Matrix has been created\"<<endl;\n    raw = 0; coll = 0;\n    while (getline(indata, line))\n    {\n    \n        std::stringstream lineStream(line);\n        std::string cell;\n\n        while (std::getline(lineStream, cell, ','))\n        {\n            \n            //cout<<\"Raw: \"<<raw<<\" Coll: \"<<coll<<endl;   \n            res(raw,coll) = stof(cell);\n            coll++;\n        }\n        coll = 0;\n        raw++;\n    }\n    indata.close();\n    return res;\n};\n\n//TODO:\n//Saving type of matrix\nvoid writeMatrix(const char *filename, MatrixXd mat)\n{\n    ofstream outdata(filename,ios_base::out);\n    int raws = mat.rows();\n    int cols = mat.cols();\n    outdata<<raws<<\",\"<<cols<<endl;\n    for(int i = 0; i< raws; i++)\n    {\n        for(int j = 0; j < cols-1; j++)\n        {\n            outdata<<mat(i,j)<<\",\";\n        }\n        outdata<<mat(i,cols-1)<<endl;\n    }\n    outdata.close();\n    \n}\n\n/* void test_read_write_matrix_into_csv()\n{\n  MatrixXd m = MatrixXd::Random(3,3);\n  writeMatrix(\"test_w.csv\", m);\n  MatrixXd n = readMatrix(\"test_w.csv\");\n  if(m == n) cout<<\"True\"<<endl;\n  cout<<m<<endl;\n  cout<<\"====\"<<endl;\n  cout<<n<<endl;\n} */\n\ndouble Exp(double x) // the functor we want to apply\n{\n    return std::exp(x);\n}\n\nint main()\n{\n    MatrixXd X = readMatrix(\"X.csv\");\n    MatrixXd y = readMatrix(\"y.csv\");\n    MatrixXd z, z1, p, p1, u, w ;\n    float b0 = log(y.mean() / (1 - y.mean()) ) ;\n    cout<< b0<<endl;\n    VectorXd b = ArrayXd::Zero(20);\n    VectorXd b_old = ArrayXd::Zero(20);\n    b(0) = b0;\n    cout<<\"Transposing\"<<endl;\n    b = b.transpose();\n    for(int i = 0; i < 20; i++)\n    {\n        z = X * b;\n        z = -z;     \n        z = z.unaryExpr([](double d) {return std::exp(d);});\n        z1 = z.unaryExpr([](double d) {return d + 1.0;});\n        p = z1.unaryExpr([](double d) {return 1.0 / d;});\n        p1 = p.unaryExpr([](double d) {return 1 - d;});\n        w = p * p1;\n        w = w.unaryExpr([](double d) {return 1.0 / d;});\n        u = z + (y -  p) * w;\n        b_old = b;\n        \n    }\n    // cout<<m;\n    return 0;\n\n    \n}\n", "meta": {"hexsha": "ceed9f79d6d52095ea3000963a3986cc29c20393", "size": 2714, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_exp/main.cpp", "max_stars_repo_name": "Astromis/tinyEmbeddingsEngine", "max_stars_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_exp/main.cpp", "max_issues_repo_name": "Astromis/tinyEmbeddingsEngine", "max_issues_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_exp/main.cpp", "max_forks_repo_name": "Astromis/tinyEmbeddingsEngine", "max_forks_repo_head_hexsha": "fea1beb7b3fd32640f788209f79cc47312a20efb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T09:38:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T09:38:52.000Z", "avg_line_length": 22.4297520661, "max_line_length": 60, "alphanum_fraction": 0.5213706706, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5849935460029219}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <manifold/SO3.h>\n#include <manifold/gradientDescentSE3.h>\n#include <manifold/newtonSE3.h>\n#include <random>\n\nclass Gmm2pc : public GDSE3<double> {\n public:\n  Gmm2pc(const Eigen::Vector3d& muA, const\n      Eigen::Matrix3d& covA, const Eigen::MatrixXd& xB) \n    : piA_(1.), muA_(muA), covA_(covA), xB_(xB)\n  {\n    std::cout << \"-A-\"\n      << muA.transpose() << std::endl\n      << covA << std::endl;\n    std::cout << \"-B-\"\n      << xB_.cols() << std::endl;\n  };\n\n  virtual void ComputeJacobian(const SE3d& theta, Eigen::Matrix<double,6,1>* J, double* f) {\n    SE3d T = theta;\n    Eigen::Matrix3d R = T.matrix().topLeftCorner(3,3);\n    Eigen::Vector3d t = T.matrix().topRightCorner(3,1);\n    uint32_t N = xB_.cols();\n    if (J) J->fill(0.);\n    if (f) *f = 0.;\n    for (uint32_t i=0; i<N; ++i) {\n      double logCA = -0.5*log(2.*M_PI)*3-0.5*log(covA_.determinant());\n      double logD = log(piA_) + logCA;\n      Eigen::Vector3d a = R*xB_.col(i)+t-muA_;\n      double z = -0.5*a.dot(covA_.ldlt().solve(a));\n      if (J) {\n        J->topRows(3) -= covA_.ldlt().solve(a);\n        for (uint32_t j=0; j<3; ++j) {\n          (*J)(3+j) -= a.dot(covA_.ldlt().solve(SO3d::G(j)*R*xB_.col(i)));\n        }\n      }\n      if (f)\n        *f += logD + z;\n    }\n    if (J) *J *= -1./N;\n    if (f) *f *= -1./N;\n  };\n protected:\n  double piA_;\n  Eigen::Vector3d muA_;\n  Eigen::Matrix3d covA_;\n  Eigen::MatrixXd xB_;\n};\n\nclass Gmm2pcNewton : public NewtonSE3<double> {\n public:\n  Gmm2pcNewton(const Eigen::Vector3d& muA, const\n      Eigen::Matrix3d& covA, const Eigen::MatrixXd& xB) \n    : piA_(1.), muA_(muA), covA_(covA), xB_(xB)\n  {\n    std::cout << \"-A-\"\n      << muA.transpose() << std::endl\n      << covA << std::endl;\n    std::cout << \"-B-\"\n      << xB_.cols() << std::endl;\n  };\n\n  virtual void ComputeJacobianAndHessian(const SE3d& theta,\n      Eigen::Matrix<double,6,6>*H, Eigen::Matrix<double,6,1>* J,\n      double* f) {\n    SE3d T = theta;\n    Eigen::Matrix3d R = T.matrix().topLeftCorner(3,3);\n    Eigen::Vector3d t = T.matrix().topRightCorner(3,1);\n    uint32_t N = xB_.cols();\n    if (H) H->fill(0.);\n    if (J) J->fill(0.);\n    if (f) *f = 0.;\n    for (uint32_t i=0; i<N; ++i) {\n      Eigen::Vector3d Rx = R*xB_.col(i);\n      double logCA = -0.5*log(2.*M_PI)*3-0.5*log(covA_.determinant());\n      double logD = log(piA_) + logCA;\n      Eigen::Vector3d a = Rx+t-muA_;\n      double z = -0.5*a.dot(covA_.ldlt().solve(a));\n      if (H) {\n        H->topLeftCorner(3,3) -= covA_.inverse();\n        for (uint32_t j=0; j<3; ++j) {\n          Eigen::Vector3d Htw_j = covA_.ldlt().solve(SO3d::G(j)*Rx);\n          H->block<3,1>(0,j+3) -= Htw_j;\n          H->block<1,3>(j+3,0) -= Htw_j.transpose();\n        }\n        for (uint32_t k=0; k<3; ++k) {\n          for (uint32_t j=0; j<3; ++j) {\n            (*H)(3+j,3+k) -= 0.5*(a.dot(covA_.ldlt().solve((\n                    SO3d::G(k)*SO3d::G(j)+SO3d::G(j)*SO3d::G(k))*Rx)))\n              - Rx.dot(SO3d::G(j)*covA_.ldlt().solve(SO3d::G(k)*Rx));\n          }\n        }\n//        std::cout << *H << std::endl << std::endl;\n      }\n      if (J) {\n        J->topRows(3) -= covA_.ldlt().solve(a);\n        for (uint32_t j=0; j<3; ++j) {\n          (*J)(3+j) -= a.dot(covA_.ldlt().solve(SO3d::G(j)*R*xB_.col(i)));\n        }\n      }\n      if (f)\n        *f += logD + z;\n    }\n    if (H) *H *= -1./N;\n    if (J) *J *= -1./N;\n    if (f) *f *= -1./N;\n  };\n protected:\n  double piA_;\n  Eigen::Vector3d muA_;\n  Eigen::Matrix3d covA_;\n  Eigen::MatrixXd xB_;\n};\n\nint main (int argc, char** argv) {\n  \n  double theta = 15.*M_PI/180.;\n  Eigen::Matrix3d R;\n  R << 1, 0, 0,\n         0, cos(theta), sin(theta),\n         0, -sin(theta), cos(theta);\n  Eigen::Vector3d t = Eigen::Vector3d::Ones();\n\n  Eigen::Matrix3d covA =   Eigen::Vector3d(1.,.1,3.).asDiagonal();\n  Eigen::Vector3d muA = Eigen::Vector3d::Zero();\n\n  std::random_device rd;\n  std::mt19937 gen(rd());\n  std::normal_distribution<> d1(muA(0),sqrt(covA(0,0)));\n  std::normal_distribution<> d2(muA(1),sqrt(covA(1,1)));\n  std::normal_distribution<> d3(muA(2),sqrt(covA(2,2)));\n \n  Eigen::Matrix<double,3,Eigen::Dynamic> xB(3,1000);\n  for (uint32_t i=0; i<xB.cols(); ++i) {\n    xB(0,i) = d1(gen);\n    xB(1,i) = d2(gen);\n    xB(2,i) = d3(gen);\n    xB.col(i) = R*xB.col(i) + t;\n  }\n  SE3d T;\n\n  Gmm2pc gd(muA, covA, xB);\n  gd.Compute(T, 1e-6, 200);\n//  gd.Compute(T, 0, 200);\n  T = gd.GetMinimum();\n  Eigen::Vector3d tEst = T.matrix().topRightCorner(3,1);\n  Eigen::Matrix3d REst = T.matrix().topLeftCorner(3,3);\n  std::cout << \" - T -\" << std::endl;\n  std::cout << T << std::endl;\n  std::cout << \" - R -\" << std::endl;\n  std::cout << R << std::endl;\n  std::cout << \" - Rest -\" << std::endl;\n  std::cout << REst.transpose() << std::endl;\n  std::cout << \" - t -\" << std::endl;\n  std::cout << t.transpose() << std::endl;\n  std::cout << \" - tEst -\" << std::endl;\n  std::cout << (-REst.transpose()*tEst).transpose() << std::endl;\n  std::cout << \" - dR = \" \n    << SO3d::Log_(R.transpose()*REst.transpose()).norm()*180./M_PI << std::endl;\n  std::cout << \" - dt = \" \n    << (t-(-REst.transpose()*tEst)).norm() << std::endl;\n\n\n  T = SE3d();\n  Gmm2pcNewton newton(muA, covA, xB);\n  newton.Compute(T, 1e-6, 300);\n//  gd.Compute(T, 0, 200);\n  T = newton.GetMinimum();\n  tEst = T.matrix().topRightCorner(3,1);\n  REst = T.matrix().topLeftCorner(3,3);\n  std::cout << \" - T -\" << std::endl;\n  std::cout << T << std::endl;\n  std::cout << \" - R -\" << std::endl;\n  std::cout << R << std::endl;\n  std::cout << \" - Rest -\" << std::endl;\n  std::cout << REst.transpose() << std::endl;\n  std::cout << \" - t -\" << std::endl;\n  std::cout << t.transpose() << std::endl;\n  std::cout << \" - tEst -\" << std::endl;\n  std::cout << (-REst.transpose()*tEst).transpose() << std::endl;\n  std::cout << \" - dR = \" \n    << SO3d::Log_(R.transpose()*REst.transpose()).norm()*180./M_PI << std::endl;\n  std::cout << \" - dt = \" \n    << (t-(-REst.transpose()*tEst)).norm() << std::endl;\n}\n", "meta": {"hexsha": "fc784db4d07e0a7fd016be6a90bd329869e7ed28", "size": 5980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/g2pc.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/g2pc.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/g2pc.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 31.4736842105, "max_line_length": 92, "alphanum_fraction": 0.5280936455, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.584993535468045}}
{"text": "#ifndef HYPSYS1D_RECONSTRUCTION_HPP\n#define HYPSYS1D_RECONSTRUCTION_HPP\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <memory>\n\n#include <ancse/grid.hpp>\n#include <ancse/model.hpp>\n#include <ancse/limiters.hpp>\n#include <ancse/rate_of_change.hpp>\n#include <ancse/simulation_time.hpp>\n\n\n\n\n// Reconstructions:\nclass PWConstantReconstruction\n{\n    public:\n        void set(const Eigen::MatrixXd &u) const\n        {\n            up.resize(u.rows(),u.cols());\n            up = u;\n        }\n\n        /// Compute the left and right trace at the interface i + 1/2.\n        /** Note: This API is agnostic to the number of cell-averages required\n         *        by the method. Therefore, reconstructions with different stencil\n         *        sizes can implement this API; and this call can be used in parts\n         *        of the code that do not need to know about the details of the\n         *        reconstruction.\n         */\n        std::pair<Eigen::VectorXd, Eigen::VectorXd> operator()(int i) const\n        {\n            return (*this)(up.col(i), up.col(i+1));\n        }\n\n        /// Compute the left and right trace at the interface.\n        /** Piecewise constant reconstruction of the left and right trace only\n         *  requires the cell-average to the left and right of the interface.\n         *\n         *  Note: Compared to the other overload this reduces the assumption on\n         *        how the cell-averages are stored. This is useful when testing and\n         *        generally makes the function useful in more situations.\n         */\n        inline std::pair<Eigen::VectorXd, Eigen::VectorXd> operator()\n            (Eigen::VectorXd ua, Eigen::VectorXd ub) const\n        {\n            return {std::move(ua), std::move(ub)};\n        }\n\n        // To have method in common with PWLinearReconstruction:\n        std::pair<Eigen::VectorXd, Eigen::VectorXd> operator()\n            (const Eigen::MatrixXd& u, const int i) const\n        {\n            return (*this)(u.col(i), u.col(i + 1));\n        }\n\n    private:\n        mutable Eigen::MatrixXd up;\n};\n\n\n// Wrapping the available scalar slope limiters for use with quantity vectors u\ntemplate <class SlopeLimiter>\nclass VectorSlopeLimiter\n{\n    public:\n        explicit VectorSlopeLimiter(const SlopeLimiter& sigma) : sigma(sigma) {}\n    \n        Eigen::VectorXd operator() (const Eigen::VectorXd& sL, const Eigen::VectorXd& sR) const\n        {\n            assert ((sL.size() == sR.size()));\n            \n            const int size= sL.size();\n            Eigen::VectorXd limited_s(size);\n\n            for (int i= 0; i < size; i++)\n                limited_s(i)= sigma(sL(i), sR(i));\n\n            return limited_s;\n        }\n\n    private:\n        SlopeLimiter sigma;\n};\n\n\ntemplate <class SlopeLimiter>\nclass PWLinearReconstruction\n{\n    public:\n        explicit PWLinearReconstruction(const SlopeLimiter& slope_limiter)\n            : slope_limiter(slope_limiter) {}\n\n        std::pair<Eigen::VectorXd, Eigen::VectorXd> operator()\n            (const Eigen::MatrixXd& u, const int i) const\n        {\n            return (*this)(u.col(i - 1), u.col(i), u.col(i + 1), u.col(i + 2));\n        }\n\n        std::pair<Eigen::VectorXd, Eigen::VectorXd> operator()\n            (Eigen::VectorXd ua, Eigen::VectorXd ub, Eigen::VectorXd uc, Eigen::VectorXd ud) const\n        {\n            Eigen::VectorXd sL= ub - ua;\n            Eigen::VectorXd sM= uc - ub;\n            Eigen::VectorXd sR= ud - uc;\n\n            Eigen::VectorXd uL= ub + 0.5 * slope_limiter(sL, sM);\n            Eigen::VectorXd uR= uc - 0.5 * slope_limiter(sM, sR);\n\n            return {uL, uR};\n        }\n\n    private:\n        VectorSlopeLimiter<SlopeLimiter> slope_limiter;\n};\n\n#endif // HYPSYS1D_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "49ee770af655d0437dc4206b486c5ec215eadb65", "size": 3739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/reconstruction.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/reconstruction.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/reconstruction.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 30.9008264463, "max_line_length": 98, "alphanum_fraction": 0.5910671302, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5849124035696939}}
{"text": "#include <vector>\n#include <boost/math/distributions/normal.hpp>\n#include \"normal_dist.h\"\n\nstochastic::NormalDistribution::NormalDistribution(double mean, double std_dev)\n  : Distribution(),\n    mean_{mean},\n    std_dev_{std_dev},\n    distribution_{mean, std_dev_}\n{}\n\nstd::vector<double> stochastic::NormalDistribution::cumulative_dist_func(\n    const std::vector<double>& locations) const {\n  std::vector<double> evaluations(locations.size());\n\n  for (unsigned int i = 0; i < locations.size(); ++i) {\n    evaluations[i] = cdf(distribution_, locations[i]);\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> stochastic::NormalDistribution::inv_cumulative_dist_func(\n    const std::vector<double>& probabilities) const {\n  std::vector<double> evaluations(probabilities.size());\n\n  for (unsigned int i = 0; i < probabilities.size(); ++i) {\n    evaluations[i] = quantile(distribution_, probabilities[i]);\n  }\n\n  return evaluations;\n}\n", "meta": {"hexsha": "de5441b49de183792fcd3bf7d29815c6a3f032d0", "size": 931, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/normal_dist.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/normal_dist.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/normal_dist.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 28.2121212121, "max_line_length": 79, "alphanum_fraction": 0.7185821697, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5849123986090368}}
{"text": "//-----------Written by ZhangYu HIT-------------------\r\n#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <fstream>\r\n#include <sstream>\r\n#include <string>\r\n#include <ctime>\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Sparse>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nint get_NodeCondition(const int ii, const int ij, const int N2);\r\n\r\ninline int coordinate(const int x, const int y, const int NX)\r\n{\r\n    return (x + y * NX);\r\n}\r\n\r\ntemplate <typename T>\r\ninline T p2(const T x)\r\n{\r\n    return (x * x);\r\n}\r\n\r\nnamespace Basic\r\n{\r\n    const int N = 80 + 1;\r\n    const double MAX_ERR = 1e-6;\r\n\r\n    // ---------------------------------------\r\n    const bool uni_mesh = 1;\r\n\r\n    double S_x = 1.0 / 0.98;\r\n    double S_y = 0.98;\r\n\r\n    //--------------------Node Spaces-----------------\r\n    vector<double> X_delta(N - 1, 0);\r\n    vector<double> Y_delta(N - 1, 0);\r\n\r\n    //--------------------Node Positions--------------\r\n    vector<double> X_position(N, 0);\r\n    vector<double> Y_position(N, 0);\r\n\r\n}\r\n\r\nnamespace Solve_equ\r\n{\r\n    using Basic::N;\r\n\r\n    double L2_error;\r\n\r\n    // ----------------- FD Coeffieient Matrix\r\n    //MatrixXd A = MatrixXd::Constant(N * N, N * N, 0);\r\n\r\n    SparseMatrix<double, RowMajor> A(N *N, N *N);\r\n\r\n    SparseMatrix<double, RowMajor> A1(p2(N - 2), p2(N - 2));\r\n\r\n    // -----------------[A][X] = [B]\r\n    VectorXd B = VectorXd::Constant(N * N, 0);\r\n\r\n    VectorXd B1 = VectorXd::Constant(p2(N - 2), 0);\r\n\r\n    VectorXd X = VectorXd::Constant(N * N, 1);\r\n\r\n    VectorXd X1 = VectorXd::Constant(p2(N - 2), 1);\r\n\r\n    VectorXd phi_ana = VectorXd::Constant(N * N, 0);\r\n}\r\n\r\nnamespace MultiGrids\r\n{\r\n\r\n}\r\n\r\nvoid get_Bacis_Mesh(const bool uni_mesh, const int N, double S_x, double S_y,\r\n                    vector<double> &X_delta, vector<double> &Y_delta,\r\n                    vector<double> &X_position, vector<double> &Y_position)\r\n{\r\n    // using namespace Basic;\r\n\r\n    if (uni_mesh != 1)\r\n    {\r\n        S_x = 1.0 / S_x;\r\n        S_y = 1.0 / S_y;\r\n    }\r\n    else\r\n    {\r\n        S_x = S_y = 1.0;\r\n    }\r\n\r\n    double x0, y0;\r\n\r\n    if (uni_mesh == 1)\r\n    {\r\n        x0 = 1.0 / (N - 1);\r\n        y0 = 1.0 / (N - 1);\r\n    }\r\n    else\r\n    {\r\n        x0 = 1.0 * (1 - S_x) / (1 - pow(S_x, N - 1));\r\n        y0 = 1.0 * (1 - S_y) / (1 - pow(S_y, N - 1));\r\n    }\r\n\r\n    X_delta[0] = x0;\r\n    Y_delta[0] = y0;\r\n\r\n    cout << \"-----------N = \" << N << \"   deltax   deltay----------\" << endl;\r\n    for (int i = 1; i < N - 1; ++i)\r\n    {\r\n        X_delta[i] = X_delta[i - 1] * S_x;\r\n        Y_delta[i] = Y_delta[i - 1] * S_y;\r\n        cout << X_delta[i] << \" \" << Y_delta[i] << endl;\r\n    }\r\n\r\n    cout << \"-----------N = \" << N << \"    positionx   positiony----------\" << endl;\r\n    for (int i = 1; i < N; ++i)\r\n    {\r\n        X_position[i] = X_position[i - 1] + X_delta[i - 1];\r\n        Y_position[i] = Y_position[i - 1] + Y_delta[i - 1];\r\n        cout << X_position[i] << \" \" << Y_position[i] << endl;\r\n    }\r\n}\r\n\r\ninline double anaSolu(const double X_, const double Y_)\r\n{\r\n    //double ana = (5000000*p2(Y_) + 5000000*p2(X_ - 1) - 100000)*exp(-50*p2(Y_) - 50*p2(1 - X_));\r\n    double ana = 500 * exp(-50 * (p2(1.0 - X_) + p2(Y_))) + 100 * X_ * (1 - Y_);\r\n    return ana;\r\n}\r\n\r\nvoid get_Analytic_Solution()\r\n{\r\n\r\n    using Basic::N;\r\n    using Basic::X_position;\r\n    using Basic::Y_position;\r\n\r\n    using Solve_equ::phi_ana;\r\n\r\n    for (int j = 0; j < N; ++j)\r\n    {\r\n        for (int i = 0; i < N; ++i)\r\n        {\r\n            const int index = coordinate(i, j, N);\r\n            const double X_ = X_position[i];\r\n            const double Y_ = Y_position[j];\r\n            //phi_ana(index) = 500 * exp(-50 * (p2(1.0 - X_) + p2(Y_))) + 100 * X_ * (1 - Y_);\r\n            phi_ana(index) = anaSolu(X_, Y_);\r\n        }\r\n    }\r\n}\r\n\r\nint get_NodeCondition(const int ii, const int ij, const int N2)\r\n{\r\n\r\n    int NodeCondition;\r\n    // ------------6 2 5\r\n    // ------------3 0 1\r\n    // ------------7 4 8\r\n    if (ii != 0 && ij != 0 && ii != N2 - 1 && ij != N2 - 1)\r\n    {\r\n        NodeCondition = 0;\r\n    }\r\n    else if (ij == 0 && ii == 0)\r\n    {\r\n        //NodeCondition = \"LeftBottom\";\r\n        NodeCondition = 7;\r\n    }\r\n    else if (ij == 0 && ii != 0 && ii != N2 - 1)\r\n    {\r\n        //NodeCondition = \"Bottom\";\r\n        NodeCondition = 4;\r\n    }\r\n    else if (ij == 0 && ii == N2 - 1)\r\n    {\r\n        //NodeCondition = \"RightBottom\";\r\n        NodeCondition = 8;\r\n    }\r\n    else if (ii == 0 && ij != 0 && ij != N2 - 1)\r\n    {\r\n        //NodeCondition = \"Left\";\r\n        NodeCondition = 3;\r\n    }\r\n    else if (ii == N2 - 1 && ij != 0 && ij != N2 - 1)\r\n    {\r\n        //NodeCondition = \"Right\";\r\n        NodeCondition = 1;\r\n    }\r\n    else if (ii == N2 - 1 && ij == N2 - 1)\r\n    {\r\n        //NodeCondition = \"RightTop\";\r\n        NodeCondition = 5;\r\n    }\r\n    else if (ij == N2 - 1 && ii != 0 && ii != N2 - 1)\r\n    {\r\n        //NodeCondition = \"Top\";\r\n        NodeCondition = 2;\r\n    }\r\n    else if (ii == 0 && ij == N2 - 1)\r\n    {\r\n        //NodeCondition = \"LeftTop\";\r\n        NodeCondition = 6;\r\n    }\r\n    return NodeCondition;\r\n}\r\n\r\ninline double SRight(const double X_, const double Y_)\r\n{\r\n    double S = (5000000 * p2(Y_) + 5000000 * p2(X_ - 1) - 100000) * exp(-50 * p2(Y_) - 50 * p2(1 - X_));\r\n    return S;\r\n}\r\n\r\nvoid get_Right_term_resi(const int N, const double *X_delta, const double *Y_delta,\r\n                         VectorXd &r, VectorXd &B)\r\n{\r\n    const int N2 = N - 2;\r\n\r\n    for (int i = 0; i < p2(N2); ++i)\r\n    {\r\n\r\n        int ii = i % ((int)N2);\r\n        int ij = i / ((int)N2);\r\n\r\n        int NodeCondition = get_NodeCondition(ii, ij, N2);\r\n\r\n        double dx1 = X_delta[1 + ii - 1];\r\n        double dx2 = X_delta[1 + ii];\r\n        double dy1 = Y_delta[1 + ij - 1];\r\n        double dy2 = Y_delta[1 + ij];\r\n\r\n        double B_N, B_S, B_W, B_E;\r\n\r\n        switch (NodeCondition)\r\n        {\r\n        case 1:\r\n            B_E = 0;\r\n            B(i) = r(i) - 2.0 * B_E / (dx2 * (dx1 + dx2)); //---E\r\n            break;\r\n        case 2:\r\n            B_N = 0;\r\n            B(i) = r(i) - 2.0 * B_N / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 3:\r\n            B_W = 0;\r\n            B(i) = r(i) - 2.0 * B_W / (dx1 * (dx1 + dx2)); //---W\r\n            break;\r\n        case 4:\r\n            B_S = 0;\r\n            B(i) = r(i) - 2.0 * B_S / (dy1 * (dy1 + dy2)); //---S\r\n            break;\r\n        case 5:\r\n            B_N = 0;\r\n            B_E = 0;\r\n            B(i) = r(i) - (2.0 * B_E / (dx2 * (dx1 + dx2)) + 2.0 * B_N / (dy2 * (dy1 + dy2))); //---NE\r\n            break;\r\n        case 6:\r\n            B_N = 0;\r\n            B_W = 0;\r\n            B(i) = r(i) - (2.0 * B_W / (dx1 * (dx1 + dx2)) + 2.0 * B_N / (dy2 * (dy1 + dy2))); //---NW\r\n            break;\r\n        case 7:\r\n            B_S = 0;\r\n            B_W = 0;\r\n            B(i) = r(i) - (2.0 * B_W / (dx1 * (dx1 + dx2)) + 2.0 * B_S / (dy1 * (dy1 + dy2))); //---SW\r\n            break;\r\n        case 8:\r\n            B_S = 0;\r\n            B_E = 0;\r\n            B(i) = r(i) - (2.0 * B_E / (dx2 * (dx1 + dx2)) + 2.0 * B_S / (dy1 * (dy1 + dy2))); //---SE\r\n            break;\r\n        default:\r\n            B(i) = r(i);\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nvoid get_Right_term_interior(const int N, const double *X_delta, const double *Y_delta,\r\n                             vector<double> &X_position, vector<double> &Y_position,\r\n                             VectorXd &B1)\r\n{\r\n    const int N2 = N - 2;\r\n\r\n    for (int i = 0; i < p2(N2); ++i)\r\n    {\r\n\r\n        int ii = i % ((int)N2);\r\n        int ij = i / ((int)N2);\r\n\r\n        int NodeCondition = get_NodeCondition(ii, ij, N2);\r\n\r\n        double dx1 = X_delta[1 + ii - 1];\r\n        double dx2 = X_delta[1 + ii];\r\n        double dy1 = Y_delta[1 + ij - 1];\r\n        double dy2 = Y_delta[1 + ij];\r\n\r\n        double *X_ = &X_position[0] + ii + 1;\r\n        double *Y_ = &Y_position[0] + ij + 1;\r\n\r\n        double B_N, B_S, B_W, B_E;\r\n\r\n        B1(i) = SRight(*X_, *Y_);\r\n        switch (NodeCondition)\r\n        {\r\n        case 1:\r\n            B_E = anaSolu(*(X_ + 1), *Y_);\r\n            B1(i) -= 2.0 * B_E / (dx2 * (dx1 + dx2)); //---E\r\n            break;\r\n        case 2:\r\n            B_N = anaSolu(*X_, *(Y_ + 1));\r\n            B1(i) -= 2.0 * B_N / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 3:\r\n            B_W = anaSolu(*(X_ - 1), *Y_);\r\n            B1(i) -= 2.0 * B_W / (dx1 * (dx1 + dx2)); //---W\r\n            break;\r\n        case 4:\r\n            B_S = anaSolu(*X_, *(Y_ - 1));\r\n            B1(i) -= 2.0 * B_S / (dy1 * (dy1 + dy2)); //---S\r\n            break;\r\n        case 5:\r\n            B_N = anaSolu(*X_, *(Y_ + 1));\r\n            B_E = anaSolu(*(X_ + 1), *Y_);\r\n            B1(i) -= (2.0 * B_E / (dx2 * (dx1 + dx2)) + 2.0 * B_N / (dy2 * (dy1 + dy2))); //---NE\r\n            break;\r\n        case 6:\r\n            B_N = anaSolu(*X_, *(Y_ + 1));\r\n            B_W = anaSolu(*(X_ - 1), *Y_);\r\n            B1(i) -= (2.0 * B_W / (dx1 * (dx1 + dx2)) + 2.0 * B_N / (dy2 * (dy1 + dy2))); //---NW\r\n            break;\r\n        case 7:\r\n            B_S = anaSolu(*X_, *(Y_ - 1));\r\n            B_W = anaSolu(*(X_ - 1), *Y_);\r\n            B1(i) -= (2.0 * B_W / (dx1 * (dx1 + dx2)) + 2.0 * B_S / (dy1 * (dy1 + dy2))); //---SW\r\n            break;\r\n        case 8:\r\n            B_S = anaSolu(*X_, *(Y_ - 1));\r\n            B_E = anaSolu(*(X_ + 1), *Y_);\r\n            B1(i) -= (2.0 * B_E / (dx2 * (dx1 + dx2)) + 2.0 * B_S / (dy1 * (dy1 + dy2))); //---SE\r\n            break;\r\n        default:\r\n            //B1(i) = SRight(*X_, *Y_);\r\n            break;\r\n        }\r\n    }\r\n    //cout << B1 << endl;\r\n}\r\n\r\nvoid get_iter_coeff(VectorXd &A_c, const double *X_delta, const double *Y_delta, const int N)\r\n{\r\n    int N2 = N - 2;\r\n    int N22 = p2(N2);\r\n\r\n    for (int i = 0; i < N22; ++i)\r\n    {\r\n\r\n        int ii = i % ((int)N2);\r\n        int ij = i / ((int)N2);\r\n\r\n        int im5 = i * 5;\r\n\r\n        double dx1 = X_delta[1 + ii - 1];\r\n        double dx2 = X_delta[1 + ii];\r\n        double dy1 = Y_delta[1 + ij - 1];\r\n        double dy2 = Y_delta[1 + ij];\r\n\r\n        int NodeCondition = get_NodeCondition(ii, ij, N2);\r\n        A_c(im5) = -(2.0 / (dx1 * dx2) + 2.0 / (dy1 * dy2));\r\n\r\n        switch (NodeCondition)\r\n        {\r\n            // center - left - bottom - right - top\r\n        case 0:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 1:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 2:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            break;\r\n        case 3:\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 4:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 5:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            break;\r\n        case 6:\r\n            A_c(im5 + 2) = 2.0 / (dy1 * (dy1 + dy2)); //---S\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            break;\r\n        case 7:\r\n            A_c(im5 + 3) = 2.0 / (dx2 * (dx1 + dx2)); //---E\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n        case 8:\r\n            A_c(im5 + 1) = 2.0 / (dx1 * (dx1 + dx2)); //---W\r\n            A_c(im5 + 4) = 2.0 / (dy2 * (dy1 + dy2)); //---N\r\n            break;\r\n\r\n        default:\r\n            break;\r\n        }\r\n    }\r\n}\r\n\r\nvoid Gauss_Seidel(VectorXd &X, VectorXd &Ac, VectorXd &B, const int N)\r\n{\r\n    for (int j = 0; j < N; ++j)\r\n    {\r\n        for (int i = 0; i < N; ++i)\r\n        {\r\n            const int index = coordinate(i, j, N);\r\n\r\n            const int i_L = coordinate(i - 1, j, N);\r\n            const int i_B = coordinate(i, j - 1, N);\r\n            const int i_R = coordinate(i + 1, j, N);\r\n            const int i_T = coordinate(i, j + 1, N);\r\n\r\n            const int im5 = 5 * index;\r\n\r\n            int NodeCondition = get_NodeCondition(i, j, N);\r\n\r\n            switch (NodeCondition)\r\n            {\r\n            case 0:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 2) * X(i_B) + Ac(im5 + 3) * X(i_R) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n            case 1:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 2) * X(i_B) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n            case 2:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 2) * X(i_B) + Ac(im5 + 3) * X(i_R)));\r\n                break;\r\n            case 3:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 2) * X(i_B) + Ac(im5 + 3) * X(i_R) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n            case 4:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 3) * X(i_R) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n            case 5:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 2) * X(i_B)));\r\n                break;\r\n            case 6:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 2) * X(i_B) + Ac(im5 + 3) * X(i_R)));\r\n                break;\r\n            case 7:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 3) * X(i_R) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n            case 8:\r\n                X(index) = 1.0 / Ac(im5) * (B(index) - (Ac(im5 + 1) * X(i_L) + Ac(im5 + 4) * X(i_T)));\r\n                break;\r\n\r\n            default:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid from_X1_to_X(VectorXd &X, VectorXd &X1, int N)\r\n{\r\n    using Solve_equ::phi_ana;\r\n\r\n    for (int j = 0; j < N; ++j)\r\n    {\r\n        for (int i = 0; i < N; ++i)\r\n        {\r\n\r\n            const int index = coordinate(i, j, N);\r\n\r\n            int index_in;\r\n\r\n            int NodeCondition = get_NodeCondition(i, j, N);\r\n\r\n            switch (NodeCondition)\r\n            {\r\n            case 0:\r\n                index_in = coordinate(i - 1, j - 1, N - 2);\r\n                X(index) = X1(index_in);\r\n                break;\r\n            //case 1:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 2:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 3:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 4:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 5:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 6:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 7:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            //case 8:\r\n            //    X(index) = phi_ana(index);\r\n            //    break;\r\n            default:\r\n                X(index) = phi_ana(index);\r\n                break;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid Gauss_Seidel_Iteration(VectorXd &X, VectorXd &X1, VectorXd &B,\r\n                            vector<double> &X_delta, vector<double> &Y_delta,\r\n                            vector<double> &X_position, vector<double> &Y_position, const int N)\r\n{\r\n    // ********** The Gauss Seidel Iteration don't include Boundary nodes\r\n    const int N2 = N - 2;\r\n    // FD coefficient----------------\r\n    VectorXd A_coeff = VectorXd::Constant(p2(N2) * 5, 0);\r\n\r\n    get_iter_coeff(A_coeff, &X_delta[0], &Y_delta[0], N);\r\n\r\n    get_Right_term_interior(N, &X_delta[0], &Y_delta[0], X_position, Y_position, B);\r\n\r\n    //Gauss_Seidel(X1, A_coeff, B, N);\r\n\r\n    double err_sum = 1.0;\r\n    int iter_num = 0;\r\n\r\n    while (err_sum > 1e-8)\r\n    {\r\n        VectorXd X_old = X1;\r\n        Gauss_Seidel(X1, A_coeff, B, N2);\r\n\r\n        VectorXd error = X1 - X_old;\r\n        err_sum = error.lpNorm<2>();\r\n\r\n        ++iter_num;\r\n    }\r\n\r\n    cout << \"Iter steps is \" << iter_num << \", \"\r\n         << \"iter max err is \" << err_sum << endl;\r\n\r\n    from_X1_to_X(X, X1, N);\r\n}\r\n\r\nvoid residual(VectorXd &rh, const int N,\r\n              const MatrixXd &Ah_coeff, const VectorXd &Xh, const VectorXd &Bh)\r\n{\r\n    for (int j = 0; j < N; ++j)\r\n    {\r\n        for (int i = 0; i < N; ++i)\r\n        {\r\n            const int index = coordinate(i, j, N);\r\n\r\n            const int i_L = coordinate(i - 1, j, N);\r\n            const int i_B = coordinate(i, j - 1, N);\r\n            const int i_R = coordinate(i + 1, j, N);\r\n            const int i_T = coordinate(i, j + 1, N);\r\n\r\n            const int im5 = 5 * index;\r\n\r\n            int NodeCondition = get_NodeCondition(i, j, N);\r\n\r\n            switch (NodeCondition)\r\n            {\r\n            case 0:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 2) * Xh(i_B) + Ah_coeff(im5 + 3) * Xh(i_R) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n            case 1:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 2) * Xh(i_B) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n            case 2:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 2) * Xh(i_B) + Ah_coeff(im5 + 3) * Xh(i_R));\r\n                break;\r\n            case 3:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 2) * Xh(i_B) + Ah_coeff(im5 + 3) * Xh(i_R) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n            case 4:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 3) * Xh(i_R) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n            case 5:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 2) * Xh(i_B));\r\n                break;\r\n            case 6:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 2) * Xh(i_B) + Ah_coeff(im5 + 3) * Xh(i_R));\r\n                break;\r\n            case 7:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 3) * Xh(i_R) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n            case 8:\r\n                rh(index) = Bh(index) - (Ah_coeff(im5) * Xh(index) + Ah_coeff(im5 + 1) * Xh(i_L) + Ah_coeff(im5 + 4) * Xh(i_T));\r\n                break;\r\n\r\n            default:\r\n                break;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid Restriction(VectorXd &r1, const VectorXd &r0, const int N1, const int N0)\r\n{\r\n\r\n    // ------------------- simply injection\r\n    for (int i = 0; i < N1; ++i)\r\n    {\r\n        for (int j = 0; j < N1; ++j)\r\n        {\r\n            const int index1 = coordinate(i, j, N1);\r\n            const int index0 = coordinate(i * 2 + 1, j * 2 + 1, N0);\r\n            r1(index1) = r0(index0);\r\n        }\r\n    }\r\n}\r\n\r\nvoid Prolongation(const VectorXd &eh1, VectorXd &rh0, const int N1, const int N0,\r\n                  vector<double> &X_weight, vector<double> &Y_weight)\r\n{\r\n    // Bilinear interpolation -----------------------\r\n    for (int i = 0; i < N1 - 1; ++i)\r\n    {\r\n        for (int j = 0; j < N1 - 1; ++j)\r\n        {\r\n            const int ip1 = i + 1;\r\n            const int jp1 = j + 1;\r\n            const int im2p1 = i * 2 + 1;\r\n            const int im2p2 = i * 2 + 2;\r\n            const int jm2p1 = j * 2 + 1;\r\n            const int jm2p2 = j * 2 + 2;\r\n\r\n            const int index1 = coordinate(i, j, N1);\r\n            const int index1_i = coordinate(ip1, j, N1);\r\n            const int index1_j = coordinate(i, jp1, N1);\r\n            const int index1_ij = coordinate(ip1, jp1, N1);\r\n\r\n            const int index0 = coordinate(im2p1, jm2p1, N0);\r\n            const int index0_i = coordinate(im2p2, jm2p1, N0);\r\n            const int index0_j = coordinate(im2p1, jm2p2, N0);\r\n            const int index0_ij = coordinate(im2p2, jm2p2, N0);\r\n\r\n            rh0(index0) = eh1(index1);\r\n            rh0(index0_i) = X_weight[im2p2] * eh1(index1) + X_weight[im2p2 + 1] * eh1(index1_i);\r\n            rh0(index0_j) = Y_weight[jm2p2] * eh1(index1) + Y_weight[jm2p2 + 1] * eh1(index1_j);\r\n            rh0(index0_ij) = Y_weight[jm2p2] * (X_weight[im2p2] * eh1(index1) + X_weight[im2p2 + 1] * eh1(index1_i)) + Y_weight[jm2p2 + 1] * (X_weight[im2p2] * eh1(index1_j) + X_weight[im2p2 + 1] * eh1(index1_ij));\r\n        }\r\n    }\r\n\r\n    const int N1_1 = N1 - 1;\r\n\r\n    for (int i = 0; i < N1_1; ++i)\r\n    {\r\n        const int ip1 = i + 1;\r\n        const int im2p1 = i * 2 + 1;\r\n        const int im2p2 = i * 2 + 2;\r\n\r\n        const int index1 = coordinate(i, N1_1, N1);\r\n        const int index1_1 = coordinate(ip1, N1_1, N1);\r\n\r\n        const int index0 = coordinate(im2p1, N1_1 * 2 + 1, N0);\r\n        const int index0_1 = coordinate(im2p2, N1_1 * 2 + 1, N0);\r\n\r\n        rh0(index0) = eh1(index1);\r\n        rh0(index0_1) = X_weight[im2p2] * eh1(index1) + X_weight[im2p2 + 1] * eh1(index1_1);\r\n\r\n        const int index0_pj = coordinate(im2p1, N1_1 * 2 + 2, N0);\r\n        const int index0_1pj = coordinate(im2p2, N1_1 * 2 + 2, N0);\r\n        rh0(index0_pj) = Y_weight[N1_1 * 2 + 2] * rh0(index0) + Y_weight[N1_1 * 2 + 3] * 0;\r\n        rh0(index0_1pj) = Y_weight[N1_1 * 2 + 2] * rh0(index0_1) + Y_weight[N1_1 * 2 + 3] * 0;\r\n\r\n        const int index0_0mj = coordinate(im2p1, 1, N0);\r\n        const int index0_01mj = coordinate(im2p2, 1, N0);\r\n        rh0(coordinate(im2p1, 0, N0)) = Y_weight[1] * rh0(coordinate(im2p1, 1, N0)) + Y_weight[0] * 0;\r\n        rh0(coordinate(im2p2, 0, N0)) = Y_weight[1] * rh0(coordinate(im2p2, 1, N0)) + Y_weight[0] * 0;\r\n    }\r\n\r\n    for (int j = 0; j < N1_1; ++j)\r\n    {\r\n        const int jp1 = j + 1;\r\n        const int jm2p1 = j * 2 + 1;\r\n        const int jm2p2 = j * 2 + 2;\r\n\r\n        const int index1 = coordinate(N1_1, j, N1);\r\n        const int index1_1 = coordinate(N1_1, jp1, N1);\r\n\r\n        const int index0 = coordinate(N1_1 * 2 + 1, jm2p1, N0);\r\n        const int index0_1 = coordinate(N1_1 * 2 + 1, jm2p2, N0);\r\n\r\n        rh0(index0) = eh1(index1);\r\n        rh0(index0_1) = Y_weight[jm2p2] * eh1(index1) + Y_weight[jm2p2 + 1] * eh1(index1_1);\r\n\r\n        const int index0_pi = coordinate(N1_1 * 2 + 2, jm2p1, N0);\r\n        const int index0_1pi = coordinate(N1_1 * 2 + 2, jm2p2, N0);\r\n        rh0(index0_pi) = X_weight[N1_1 * 2 + 2] * rh0(index0) + X_weight[N1_1 * 2 + 3] * 0;\r\n        rh0(index0_1pi) = X_weight[N1_1 * 2 + 2] * rh0(index0_1) + X_weight[N1_1 * 2 + 3] * 0;\r\n\r\n        const int index0_0mi = coordinate(1, jm2p1, N0);\r\n        const int index0_01mi = coordinate(1, jm2p2, N0);\r\n        rh0(coordinate(0, jm2p1, N0)) = X_weight[1] * rh0(coordinate(1, jm2p1, N0)) + X_weight[0] * 0;\r\n        rh0(coordinate(0, jm2p2, N0)) = X_weight[1] * rh0(coordinate(1, jm2p2, N0)) + X_weight[0] * 0;\r\n    }\r\n\r\n    rh0(coordinate(2 * N1_1 + 1, 2 * N1_1 + 1, N0)) = eh1(coordinate(N1_1, N1_1, N1));\r\n\r\n    rh0(coordinate(2 * N1_1 + 1, 0, N0)) = Y_weight[1] * rh0(coordinate(2 * N1_1 + 1, 1, N0)) + Y_weight[0] * 0;\r\n    rh0(coordinate(2 * N1_1 + 1, 2 * N1_1 + 2, N0)) = Y_weight[N1_1 * 2 + 2] * rh0(coordinate(2 * N1_1 + 1, 2 * N1_1 + 1, N0)) + Y_weight[N1_1 * 2 + 3] * 0;\r\n\r\n    rh0(coordinate(0, 2 * N1_1 + 1, N0)) = X_weight[1] * rh0(coordinate(1, 2 * N1_1 + 1, N0)) + Y_weight[0] * 0;\r\n    rh0(coordinate(2 * N1_1 + 2, 2 * N1_1 + 1, N0)) = X_weight[N1_1 * 2 + 2] * rh0(coordinate(2 * N1_1 + 1, 2 * N1_1 + 1, N0)) + Y_weight[N1_1 * 2 + 3] * 0;\r\n\r\n    rh0(coordinate(0, 0, N0)) = X_weight[1] * rh0(coordinate(1, 0, N0));\r\n    rh0(coordinate(0, N0 - 1, N0)) = X_weight[1] * rh0(coordinate(1, N0 - 1, N0));\r\n    rh0(coordinate(N0 - 1, 0, N0)) = X_weight[N0 - 1] * rh0(coordinate(N0 - 2, 0, N0));\r\n    rh0(coordinate(N0 - 1, N0 - 1, N0)) = X_weight[N0 - 1] * rh0(coordinate(N0 - 2, N0 - 1, N0));\r\n}\r\n\r\nvoid get_Weight_Interpolation(vector<double> &weight, const int N_c,\r\n                              const vector<double> &X_f, const vector<double> &X_c)\r\n{\r\n    for (int i = 0; i < N_c; ++i)\r\n    {\r\n        const int i2 = 2 * i;\r\n        //const double inv_delta = 1.0 / X_c[i];\r\n        const double inv_delta = 1.0 / (X_f[i2 + 1] + X_f[i2]);\r\n\r\n        weight[i2] = X_f[i2 + 1] * inv_delta;\r\n        weight[i2 + 1] = X_f[i2 + 0] * inv_delta;\r\n    }\r\n}\r\nvoid get_resi_mesh(const int N1, vector<double> &X1_delta, vector<double> &Y1_delta,\r\n                   vector<double> &X1_position, vector<double> &Y1_position,\r\n                   vector<double> &X0_delta, vector<double> &Y0_delta,\r\n                   vector<double> &X0_position, vector<double> &Y0_position)\r\n{\r\n    for(int i = 0; i < N1 - 1; ++i){\r\n        X1_delta[i] = X0_delta[2 * i] + X0_delta[2 * i + 1];\r\n        Y1_delta[i] = Y0_delta[2 * i] + Y0_delta[2 * i + 1];\r\n    }\r\n\r\n    X1_position[0] = X0_position[0];\r\n    Y1_position[0] = Y0_position[0];\r\n    for (int i = 1; i < N1; ++i)\r\n    {\r\n        X1_position[i] = X1_position[i - 1] + X1_delta[i - 1];\r\n        Y1_position[i] = Y1_position[i - 1] + Y1_delta[i - 1];\r\n        // cout << X_position[i] << \" \" << Y_position[i] << endl;\r\n    }\r\n}\r\n\r\nvoid MultiGrid_Iter(const int N, VectorXd &X, VectorXd &Xh0, VectorXd &Bh0,\r\n                    const bool unimesh, const double S_x, const double S_y,\r\n                    vector<double> &Xh0_delta, vector<double> &Yh0_delta,\r\n                    vector<double> &Xh0_position, vector<double> &Yh0_position)\r\n{\r\n    const int N0 = N - 2;\r\n    const int N1 = (N0 - 1) / 2;\r\n    const int N2 = (N1 - 1) / 2;\r\n    const int N3 = (N2 - 1) / 2;\r\n\r\n    //--------------------Node Spaces-----------------\r\n    vector<double> Xh1_delta(N1 + 2 - 1, 0);\r\n    vector<double> Yh1_delta(N1 + 2 - 1, 0);\r\n    vector<double> Xh2_delta(N2 + 2 - 1, 0);\r\n    vector<double> Yh2_delta(N2 + 2 - 1, 0);\r\n    vector<double> Xh3_delta(N3 + 2 - 1, 0);\r\n    vector<double> Yh3_delta(N3 + 2 - 1, 0);\r\n\r\n    vector<double> X01_weight(N0 + 2 - 1, 0);\r\n    vector<double> Y01_weight(N0 + 2 - 1, 0);\r\n    vector<double> X12_weight(N1 + 2 - 1, 0);\r\n    vector<double> Y12_weight(N1 + 2 - 1, 0);\r\n    vector<double> X23_weight(N2 + 2 - 1, 0);\r\n    vector<double> Y23_weight(N2 + 2 - 1, 0);\r\n\r\n    //--------------------Node Positions--------------\r\n    vector<double> Xh1_position(N1 + 2, 0);\r\n    vector<double> Yh1_position(N1 + 2, 0);\r\n    vector<double> Xh2_position(N2 + 2, 0);\r\n    vector<double> Yh2_position(N2 + 2, 0);\r\n    vector<double> Xh3_position(N3 + 2, 0);\r\n    vector<double> Yh3_position(N3 + 2, 0);\r\n\r\n    get_resi_mesh(N1 + 2, Xh1_delta, Yh1_delta, Xh1_position, Yh1_position, Xh0_delta, Yh0_delta, Xh0_position, Yh0_position);\r\n    get_resi_mesh(N2 + 2, Xh2_delta, Yh2_delta, Xh2_position, Yh2_position, Xh1_delta, Yh1_delta, Xh1_position, Yh1_position);\r\n    get_resi_mesh(N3 + 2, Xh3_delta, Yh3_delta, Xh3_position, Yh3_position, Xh2_delta, Yh2_delta, Xh2_position, Yh2_position);\r\n    // get_Bacis_Mesh(unimesh, N1 + 2, S_x, S_y, Xh1_delta, Yh1_delta, Xh1_position, Yh1_position);\r\n    // get_Bacis_Mesh(unimesh, N2 + 2, S_x, S_y, Xh2_delta, Yh2_delta, Xh2_position, Yh2_position);\r\n    // get_Bacis_Mesh(unimesh, N3 + 2, S_x, S_y, Xh3_delta, Yh3_delta, Xh3_position, Yh3_position);\r\n\r\n    get_Weight_Interpolation(X01_weight, N1 + 1, Xh0_delta, Xh1_delta);\r\n    get_Weight_Interpolation(Y01_weight, N1 + 1, Yh0_delta, Yh1_delta);\r\n    get_Weight_Interpolation(X12_weight, N2 + 1, Xh1_delta, Xh2_delta);\r\n    get_Weight_Interpolation(Y12_weight, N2 + 1, Yh1_delta, Yh2_delta);\r\n    get_Weight_Interpolation(X23_weight, N3 + 1, Xh2_delta, Xh3_delta);\r\n    get_Weight_Interpolation(Y23_weight, N3 + 1, Yh2_delta, Yh3_delta);\r\n\r\n    VectorXd rh0 = VectorXd::Constant(p2(N0), 0);\r\n    VectorXd eh0 = VectorXd::Constant(p2(N0), 0);\r\n    VectorXd rh1 = VectorXd::Constant(p2(N1), 0);\r\n    VectorXd eh1 = VectorXd::Constant(p2(N1), 0);\r\n    VectorXd rh2 = VectorXd::Constant(p2(N2), 0);\r\n    VectorXd eh2 = VectorXd::Constant(p2(N2), 0);\r\n    VectorXd rh3 = VectorXd::Constant(p2(N3), 0);\r\n    VectorXd eh3 = VectorXd::Constant(p2(N3), 0);\r\n\r\n    VectorXd Bh1 = VectorXd::Constant(p2(N1), 1);\r\n    VectorXd Bh2 = VectorXd::Constant(p2(N2), 1);\r\n    VectorXd Bh3 = VectorXd::Constant(p2(N3), 1);\r\n\r\n    VectorXd Ah0_coeff = VectorXd::Constant(p2(N0) * 5, 0);\r\n    VectorXd Ah1_coeff = VectorXd::Constant(p2(N1) * 5, 0);\r\n    VectorXd Ah2_coeff = VectorXd::Constant(p2(N2) * 5, 0);\r\n    VectorXd Ah3_coeff = VectorXd::Constant(p2(N3) * 5, 0);\r\n\r\n    get_iter_coeff(Ah0_coeff, &Xh0_delta[0], &Yh0_delta[0], N0 + 2);\r\n    get_Right_term_interior(N0 + 2, &Xh0_delta[0], &Yh0_delta[0], Xh0_position, Yh0_position, Bh0);\r\n\r\n    get_iter_coeff(Ah1_coeff, &Xh1_delta[0], &Yh1_delta[0], N1 + 2);\r\n    get_iter_coeff(Ah2_coeff, &Xh2_delta[0], &Yh2_delta[0], N2 + 2);\r\n    get_iter_coeff(Ah3_coeff, &Xh3_delta[0], &Yh3_delta[0], N3 + 2);\r\n\r\n    double err_sum = 1.0;\r\n    int iter_num = 0;\r\n    VectorXd X_old = Xh0;\r\n    VectorXd error = Xh0;\r\n\r\n    std::ofstream err_out(\"err.txt\");\r\n    for (int step = 0; step < 20000; ++step)\r\n    //for (int step = 0; step < 1; ++step)\r\n    {\r\n        X_old = Xh0;\r\n        eh1.setZero();\r\n        eh2.setZero();\r\n        eh3.setZero();\r\n\r\n        for (int steph0 = 0; steph0 < 5; ++steph0)\r\n        {\r\n            Gauss_Seidel(Xh0, Ah0_coeff, Bh0, N0);\r\n            error = Xh0 - X_old;\r\n            err_sum = error.lpNorm<2>();\r\n        }\r\n\r\n        if (err_sum < 1e-6)\r\n        {\r\n            cout << \"Iterations of MG = \" << step << \" x 5\" << endl;\r\n            break;\r\n        }\r\n\r\n        err_out << step << \" \" << err_sum << endl;\r\n\r\n        residual(rh0, N0, Ah0_coeff, Xh0, Bh0);\r\n\r\n        Restriction(rh1, rh0, N1, N0);\r\n        get_Right_term_resi(N1 + 2, &Xh1_delta[0], &Yh1_delta[0], rh1, Bh1);\r\n\r\n        for (int steph0 = 0; steph0 < 10; ++steph0)\r\n        {\r\n            Gauss_Seidel(eh1, Ah1_coeff, rh1, N1);\r\n        }\r\n\r\n        residual(rh1, N1, Ah1_coeff, eh1, Bh1);\r\n        Restriction(rh2, rh1, N2, N1);\r\n        get_Right_term_resi(N2 + 2, &Xh2_delta[0], &Yh2_delta[0], rh2, Bh2);\r\n        for (int steph0 = 0; steph0 < 5; ++steph0)\r\n        {\r\n            Gauss_Seidel(eh2, Ah2_coeff, Bh2, N2);\r\n        }\r\n\r\n        residual(rh2, N2, Ah2_coeff, eh2, Bh2);\r\n        Restriction(rh3, rh2, N3, N2);\r\n        get_Right_term_resi(N3 + 2, &Xh3_delta[0], &Yh3_delta[0], rh3, Bh3);\r\n        for (int steph0 = 0; steph0 < 20; ++steph0)\r\n        {\r\n            Gauss_Seidel(eh3, Ah3_coeff, Bh3, N3);\r\n        }\r\n        //   cout << eh3 << endl;\r\n\r\n        //   -------------------------------------------------------\r\n        Prolongation(eh3, rh2, N3, N2, X23_weight, Y23_weight);\r\n        eh2 += rh2;\r\n        for (int steph0 = 0; steph0 < 5; ++steph0)\r\n        {\r\n            Gauss_Seidel(eh2, Ah2_coeff, Bh2, N2);\r\n        }\r\n\r\n        Prolongation(eh2, rh1, N2, N1, X12_weight, Y12_weight);\r\n        eh1 += rh1;\r\n        for (int steph0 = 0; steph0 < 5; ++steph0)\r\n        {\r\n            Gauss_Seidel(eh1, Ah1_coeff, Bh1, N1);\r\n        }\r\n\r\n        Prolongation(eh1, rh0, N1, N0, X01_weight, Y01_weight);\r\n        Xh0 += rh0;\r\n    }\r\n\r\n    err_out.close();\r\n\r\n    rh0.setZero();\r\n    VectorXd ph1 = VectorXd::Constant(p2(N1), 500);\r\n    Prolongation(ph1, rh0, N1, N0, X01_weight, Y01_weight);\r\n\r\n    cout << \"------------------------------------------------------------------ll\" << endl;\r\n    from_X1_to_X(X, Xh0, N0 + 2);\r\n}\r\n\r\nvoid out_tec()\r\n{\r\n\r\n    using Basic::N;\r\n\r\n    using Basic::X_position;\r\n    using Basic::Y_position;\r\n\r\n    using Solve_equ::phi_ana;\r\n    using Solve_equ::X;\r\n\r\n    VectorXd error_num2ana = VectorXd::Constant(p2(N), 0);\r\n    VectorXd error_num2ana_L2 = VectorXd::Constant(p2(N), 0);\r\n\r\n    std::ostringstream name;\r\n    //name << \"Phi_\" << N << \"_.dat\";\r\n    if (Basic::uni_mesh == 1)\r\n    {\r\n        name << \"UniMesh_Phi_\" << N << \"_.dat\";\r\n    }\r\n    else\r\n    {\r\n        name << \"Un_uniMesh_Phi_\" << N << \"_.dat\";\r\n    }\r\n    std::ofstream out(name.str().c_str());\r\n    out << \"Title= \\\"Poisson_\\\"\\n\"\r\n        << \"VARIABLES = \\\"X\\\", \\\"Y\\\", \\\"phi_num\\\", \\\"phi_ana\\\", \\\"error\\\", \\\"rela_error\\\" \\n\";\r\n    out << \"ZONE T= \\\"BOX\\\",I=\" << N - 2 << \",J=\" << N - 2 << \", F = POINT\" << endl;\r\n    for (int j = 1; j < N - 1; ++j)\r\n    {\r\n        for (int i = 1; i < N - 1; ++i)\r\n        {\r\n\r\n            const int index = coordinate(i, j, N);\r\n\r\n            const int NodeCondition = get_NodeCondition(i, j, N);\r\n\r\n            switch (NodeCondition)\r\n            {\r\n            case 0:\r\n                //error_num2ana(index) = sqrt(p2(X(index) - phi_ana(index)));\r\n                error_num2ana = (X - phi_ana).cwiseAbs();\r\n                error_num2ana_L2(index) = error_num2ana(index) / phi_ana(index);\r\n                break;\r\n            default:\r\n                break;\r\n            }\r\n\r\n            out << X_position[i] << \" \" << Y_position[j] << \" \"\r\n                << X(index) << \" \"\r\n                << phi_ana(index) << \" \"\r\n                << error_num2ana(index) << \" \"\r\n                << error_num2ana_L2(index) << \" \"\r\n                //<< phi_ana(index) << \" \"\r\n                << endl;\r\n        }\r\n    }\r\n    out.close();\r\n}\r\n\r\nint main()\r\n{\r\n    cout << \"Hello wo!\" << endl;\r\n\r\n    get_Bacis_Mesh(Basic::uni_mesh, Basic::N, Basic::S_x, Basic::S_y,\r\n                   Basic::X_delta, Basic::Y_delta, Basic::X_position, Basic::Y_position);\r\n    get_Analytic_Solution();\r\n\r\n    clock_t start = clock();\r\n    //// --------------- Solve AX = B directly -------------\r\n    //solve_AX_B();\r\n\r\n    // Gauss_Seidel_Iteration(Solve_equ::X, Solve_equ::X1, Solve_equ::B1,\r\n    //                        Basic::X_delta, Basic::Y_delta, Basic::X_position, Basic::Y_position, Basic::N);\r\n\r\n    MultiGrid_Iter(Basic::N, Solve_equ::X, Solve_equ::X1, Solve_equ::B1,\r\n                   Basic::uni_mesh, Basic::S_x, Basic::S_y,\r\n                   Basic::X_delta, Basic::Y_delta,\r\n                   Basic::X_position, Basic::Y_position);\r\n\r\n    clock_t end = clock();\r\n\r\n    Solve_equ::L2_error = ((Solve_equ::phi_ana - Solve_equ::X).lpNorm<1>()) / Solve_equ::phi_ana.lpNorm<1>();\r\n\r\n    cout << \"N = \" << Basic::N << \", \";\r\n    cout << \"Time : \" << double(end - start) << \" ms ,\";\r\n    cout << \"L1 error = \" << Solve_equ::L2_error << endl;\r\n\r\n    std::ofstream time_out(\"Steepest_descent.txt\", ios::app);\r\n    time_out << \"N = \" << Basic::N << \", \";\r\n    time_out << \"Time : \" << double(end - start) << \" ms ,\";\r\n    time_out << \"L1 error = \" << Solve_equ::L2_error << endl;\r\n    time_out.close();\r\n\r\n    out_tec();\r\n}\r\n", "meta": {"hexsha": "5d0cd9b261b6e4d07cb7dc8e72f69124c851ea53", "size": 35239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solution/Multigrid_ZY.cpp", "max_stars_repo_name": "zhyzhy-github-hub/The-FDM-and-The-FVM-in-CFD", "max_stars_repo_head_hexsha": "34afc320f9605435af33a58c68df6af64336e5f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2021-01-19T12:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T14:19:52.000Z", "max_issues_repo_path": "solution/Multigrid_ZY.cpp", "max_issues_repo_name": "LUOFQ5/The-FDM-and-The-FVM-in-CFD", "max_issues_repo_head_hexsha": "a25261e92f29c9ff40d0aab5f7a40b7e08fcd123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solution/Multigrid_ZY.cpp", "max_forks_repo_name": "LUOFQ5/The-FDM-and-The-FVM-in-CFD", "max_forks_repo_head_hexsha": "a25261e92f29c9ff40d0aab5f7a40b7e08fcd123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-01-19T12:38:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T07:44:46.000Z", "avg_line_length": 34.3795121951, "max_line_length": 215, "alphanum_fraction": 0.4613354522, "num_tokens": 12178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5849123986090367}}
{"text": "#ifndef CANNON_ML_BFGS_H\n#define CANNON_ML_BFGS_H \n\n/*!\n * \\file cannon/ml/bfgs.hpp\n * \\brief File containing BFGSOptimizer class definition.\n */\n\n#include <functional>\n\n#include <Eigen/Dense>\n\n#include <cannon/utils/class_forward.hpp>\n\nusing namespace Eigen;\n\nusing RealFunc = std::function<double(const VectorXd&)>;\nusing MultiFunc = std::function<VectorXd(const VectorXd&)>;\n\nnamespace cannon {\n  namespace ml {\n\n    CANNON_CLASS_FORWARD(OptimizationResult);\n\n    /*!\n     * \\brief Class representing a BFGS optimizer, which is a quasi-Newton\n     * unconstrained optimization method for nonlinear problems. See\n     * https://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm\n     */\n    class BFGSOptimizer {\n      public:\n        BFGSOptimizer() = delete;\n\n        /*!\n         * \\brief Constructor taking a function to optimize and a function\n         * providing gradients for that function.\n         */\n        BFGSOptimizer(RealFunc f, MultiFunc f_grad) : f_(f), f_grad_(f_grad) {}\n\n        /*!\n         * \\brief Minimize the function stored by this object, beginning from\n         * the input start state.\n         *\n         * \\param start Initial state for optimization\n         * \\param eps Small number used to detect convergence\n         * \\param iterations Maximum number of iterations to perform\n         *\n         * \\returns The result of the optimization.\n         */ \n        OptimizationResult optimize(const VectorXd& start, double eps=1e-4, unsigned\n            int iterations=100);\n\n      private:\n        RealFunc f_; //!< The function to minimize\n        MultiFunc f_grad_; //!< Gradient function for the function to minimize\n\n    };\n\n  } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_BFGS_H */\n", "meta": {"hexsha": "c7d8e1fe37a860b3d109ac02f2f466f9cfe4586a", "size": 1782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/bfgs.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/bfgs.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/bfgs.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.2857142857, "max_line_length": 103, "alphanum_fraction": 0.6632996633, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5849123809283961}}
{"text": "// ALGOLAB BGL Tutorial 2\n// Flow example demonstrating\n// - interior graph properties for flow algorithms\n// - custom edge adder\n\n// Compile and run with one of the following:\n// g++ -std=c++11 -O2 flows.cpp -o flows ./flows\n// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 flows.cpp -o flows; ./flows\n\n// Includes\n// ========\n// STL includes\n#include <iostream>\n#include <vector>\n#include <algorithm>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n// Namespaces\nusing namespace std;\nusing namespace boost;\n\n\n// BGL Graph definitions\n// =====================\n// Graph Type with nested interior edge properties for Flow Algorithms\ntypedef\tadjacency_list_traits<vecS, vecS, directedS> Traits;\ntypedef adjacency_list<vecS, vecS, directedS, no_property,\n\tproperty<edge_capacity_t, long,\n\t\tproperty<edge_residual_capacity_t, long,\n\t\t\tproperty<edge_reverse_t, Traits::edge_descriptor> > > >\tGraph;\n// Interior Property Maps\ntypedef\tproperty_map<Graph, edge_capacity_t>::type\t\tEdgeCapacityMap;\ntypedef\tproperty_map<Graph, edge_residual_capacity_t>::type\tResidualCapacityMap;\ntypedef\tproperty_map<Graph, edge_reverse_t>::type\t\tReverseEdgeMap;\ntypedef\tgraph_traits<Graph>::vertex_descriptor\t\t\tVertex;\ntypedef\tgraph_traits<Graph>::edge_descriptor\t\t\tEdge;\n\n\n// Custom Edge Adder Class, that holds the references\n// to the graph, capacity map and reverse edge map\n// ===================================================\nclass EdgeAdder {\n\tGraph &G;\n\tEdgeCapacityMap\t&capacitymap;\n\tReverseEdgeMap\t&revedgemap;\n\npublic:\n\t// to initialize the Object\n\tEdgeAdder(Graph & G, EdgeCapacityMap &capacitymap, ReverseEdgeMap &revedgemap):\n\t\tG(G), capacitymap(capacitymap), revedgemap(revedgemap){}\n\n\t// to use the Function (add an edge)\n\tvoid addEdge(int from, int to, long capacity) {\n\t\tEdge e, reverseE;\n\t\tbool success;\n\t\ttie(e, success) = add_edge(from, to, G);\n\t\ttie(reverseE, success) = add_edge(to, from, G);\n\t\tcapacitymap[e] = capacity;\n\t\tcapacitymap[reverseE] = 0;\n\t\trevedgemap[e] = reverseE;\n\t\trevedgemap[reverseE] = e;\n\t}\n};\n\n\n// Functions\n// =========\n// Function for an individual testcase\nvoid testcases() {\n\t// Create Graph and Maps\n\tGraph G(4);\n\tEdgeCapacityMap capacitymap = get(edge_capacity, G);\n\tReverseEdgeMap revedgemap = get(edge_reverse, G);\n\tResidualCapacityMap rescapacitymap = get(edge_residual_capacity, G);\n\tEdgeAdder eaG(G, capacitymap, revedgemap);\n\n\t// Add edges\n\teaG.addEdge(0, 1, 1); // from, to, capacity\n\teaG.addEdge(0, 3, 1);\n\teaG.addEdge(2, 1, 1);\n\teaG.addEdge(2, 3, 1);\n\n\t// Add source and sink\n\t// Careful: The names 'source' and 'target' are already used for BGL's \n\t// functions to get the two endpoints of an edge, use 'src' and 'sink'.\n\tVertex src = add_vertex(G);\n\tVertex sink = add_vertex(G);\n\teaG.addEdge(src, 0, 2);\n\teaG.addEdge(src, 2, 1);\n\teaG.addEdge(1, sink, 2);\n\teaG.addEdge(3, sink, 1);\n\n\t// Calculate flow\n\t// If not called otherwise, the flow algorithm uses the interior properties\n\t// - edge_capacity, edge_reverse (read access),\n\t// - edge_residual_capacity (read and write access).\n\tlong flow1 = push_relabel_max_flow(G, src, sink);\n\tlong flow2 = edmonds_karp_max_flow(G, src, sink);\n\tcout << flow1 << \" == \" << flow2 << endl;\n}\n\n// Main function to loop over the testcases\nint main() {\n\tios_base::sync_with_stdio(false);\n\tint T;\tT = 1;\n\tfor (; T > 0; --T)\ttestcases();\n\treturn 0;\n}\n", "meta": {"hexsha": "6f38d3fd5ba70c6bb284b77b8af5f48e1344d24d", "size": 3424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week6/examples/flows.cpp", "max_stars_repo_name": "KarlKode/algo-lab", "max_stars_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "week6/examples/flows.cpp", "max_issues_repo_name": "KarlKode/algo-lab", "max_issues_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week6/examples/flows.cpp", "max_forks_repo_name": "KarlKode/algo-lab", "max_forks_repo_head_hexsha": "69bf7e65bda465e09b72f4adaddee3f65e7a7567", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8468468468, "max_line_length": 80, "alphanum_fraction": 0.707067757, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.5847446059702581}}
{"text": "/*\r\n * Simulation of an ensemble of Roessler attractors\r\n *\r\n * Copyright 2014 Mario Mulansky\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n */\r\n\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <random>\r\n\r\n#include <boost/timer.hpp>\r\n#include <boost/array.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nnamespace odeint = boost::numeric::odeint;\r\n\r\ntypedef boost::timer timer_type;\r\n\r\ntypedef double fp_type;\r\n//typedef float fp_type;\r\n\r\ntypedef boost::array<fp_type, 3> state_type;\r\ntypedef std::vector<state_type> state_vec;\r\n\r\n//---------------------------------------------------------------------------\r\nstruct roessler_system {\r\n    const fp_type m_a, m_b, m_c;\r\n\r\n    roessler_system(const fp_type a, const fp_type b, const fp_type c)\r\n        : m_a(a), m_b(b), m_c(c)\r\n    {}\r\n\r\n    void operator()(const state_type &x, state_type &dxdt, const fp_type t) const\r\n    {\r\n        dxdt[0] = -x[1] - x[2];\r\n        dxdt[1] = x[0] + m_a * x[1];\r\n        dxdt[2] = m_b + x[2] * (x[0] - m_c);\r\n    }\r\n};\r\n\r\n//---------------------------------------------------------------------------\r\nint main(int argc, char *argv[]) {\r\nif(argc<3)\r\n{\r\n    std::cerr << \"Expected size and steps as parameter\" << std::endl;\r\n    exit(1);\r\n}\r\nconst size_t n = atoi(argv[1]);\r\nconst size_t steps = atoi(argv[2]);\r\n//const size_t steps = 50;\r\n\r\nconst fp_type dt = 0.01;\r\n\r\nconst fp_type a = 0.2;\r\nconst fp_type b = 1.0;\r\nconst fp_type c = 9.0;\r\n\r\n// random initial conditions on the device\r\nstd::vector<fp_type> x(n), y(n), z(n);\r\nstd::default_random_engine generator;\r\nstd::uniform_real_distribution<fp_type> distribution_xy(-8.0, 8.0);\r\nstd::uniform_real_distribution<fp_type> distribution_z(0.0, 20.0);\r\nauto rand_xy = std::bind(distribution_xy, std::ref(generator));\r\nauto rand_z = std::bind(distribution_z, std::ref(generator));\r\nstd::generate(x.begin(), x.end(), rand_xy);\r\nstd::generate(y.begin(), y.end(), rand_xy);\r\nstd::generate(z.begin(), z.end(), rand_z);\r\n\r\nstate_vec state(n);\r\nfor(size_t i=0; i<n; ++i)\r\n{\r\n    state[i][0] = x[i];\r\n    state[i][1] = y[i];\r\n    state[i][2] = z[i];\r\n}\r\n\r\nstd::cout.precision(16);\r\n\r\nstd::cout << \"# n: \" << n << std::endl;\r\n\r\nstd::cout << x[0] << std::endl;\r\n\r\n\r\n// Stepper type - use never_resizer for slight performance improvement\r\nodeint::runge_kutta4_classic<state_type, fp_type, state_type, fp_type,\r\n                             odeint::array_algebra,\r\n                             odeint::default_operations,\r\n                             odeint::never_resizer> stepper;\r\n\r\nroessler_system sys(a, b, c);\r\n\r\ntimer_type timer;\r\n\r\nfp_type t = 0.0;\r\n\r\nfor (int step = 0; step < steps; step++)\r\n{\r\n    for(size_t i=0; i<n; ++i)\r\n    {\r\n        stepper.do_step(sys, state[i], t, dt);\r\n    }\r\n    t += dt;\r\n}\r\n\r\nstd::cout << \"Integration finished, runtime for \" << steps << \" steps: \";\r\nstd::cout << timer.elapsed() << \" s\" << std::endl;\r\n\r\n// compute some accumulation to make sure all results have been computed\r\nfp_type s = 0.0;\r\nfor(size_t i = 0; i < n; ++i)\r\n{\r\n    s += state[i][0];\r\n}\r\n\r\nstd::cout << state[0][0] << std::endl;\r\nstd::cout << s/n << std::endl;\r\n\r\n}\r\n", "meta": {"hexsha": "054118b4cf18452756c96a7a1f2b7a1d1d20f4bf", "size": 3226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/performance/SIMD/roessler.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/performance/SIMD/roessler.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/performance/SIMD/roessler.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 25.6031746032, "max_line_length": 82, "alphanum_fraction": 0.5747055177, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.5846907886128497}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n#define CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include \"crocoddyl/core/utils/exception.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Box QP solution\n *\n * It contains the Box QP solution data which consists of\n *  - the inverse of the free space Hessian\n *  - the optimal decision vector\n *  - the indexes for the free space\n *  - the indexes for the clamped (constrained) space\n */\nstruct BoxQPSolution {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /**\n   * @brief Initialize the QP solution structure\n   */\n  BoxQPSolution() {}\n\n  /**\n   * @brief Initialize the QP solution structure\n   *\n   * @param[in] Hff_inv      Inverse of the free space Hessian\n   * @param[in] x            Decision vector\n   * @param[in] free_idx     Free space indexes\n   * @param[in] clamped_idx  Clamped space indexes\n   */\n  BoxQPSolution(const Eigen::MatrixXd& Hff_inv, const Eigen::VectorXd& x, const std::vector<size_t>& free_idx,\n                const std::vector<size_t>& clamped_idx)\n      : Hff_inv(Hff_inv), x(x), free_idx(free_idx), clamped_idx(clamped_idx) {}\n\n  Eigen::MatrixXd Hff_inv;          //!< Inverse of the free space Hessian\n  Eigen::VectorXd x;                //!< Decision vector\n  std::vector<size_t> free_idx;     //!< Free space indexes\n  std::vector<size_t> clamped_idx;  //!< Clamped space indexes\n};\n\n/**\n * @brief This class implements a Box QP solver based on a Projected Newton method.\n *\n * We consider a box QP problem of the form:\n * \\f{eqnarray*}{\n *   \\min_{\\mathbf{x}} &= \\frac{1}{2}\\mathbf{x}^T\\mathbf{H}\\mathbf{x} + \\mathbf{q}^T\\mathbf{x} \\\\\n *   \\textrm{subject to} & \\hspace{1em} \\mathbf{\\underline{b}} \\leq \\mathbf{x} \\leq \\mathbf{\\bar{b}} \\\\\n * \\f}\n * where \\f$\\mathbf{H}\\f$, \\f$\\mathbf{q}\\f$ are the Hessian and gradient of the problem,\n * respectively, \\f$\\mathbf{\\underline{b}}\\f$, \\f$\\mathbf{\\bar{b}}\\f$ are lower and upper\n * bounds of the decision variable \\f$\\mathbf{x}\\f$.\n *\n * The algorithm procees by iteratively identifying the active bounds, and then\n * performing a projected Newton step in the free sub-space.\n * The projection uses the Hessian of the free sub-space and is computed\n * efficiently using a Cholesky decomposition.\n * It uses a line search procedure with polynomial step length values in a\n * backtracking fashion.\n * The steps are checked using an Armijo condition together L2-norm gradient.\n *\n * For more details about this solver, we encourage you to read the following\n * article:\n * \\include bertsekas-siam82.bib\n */\nclass BoxQP {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /**\n   * @brief Initialize the Projected-Newton QP for bound constraints\n   *\n   * @param[in] nx             Dimension of the decision vector\n   * @param[in] maxiter        Maximum number of allowed iterations (default 100)\n   * @param[in] th_acceptstep  Acceptance step threshold (default 0.1)\n   * @param[in] th_grad        Gradient tolerance threshold (default 1e-9)\n   * @param[in] reg            Regularization value (default 1e-9)\n   */\n  BoxQP(const std::size_t nx, const std::size_t maxiter = 100, const double th_acceptstep = 0.1,\n        const double th_grad = 1e-9, const double reg = 1e-9);\n  /**\n   * @brief Destroy the Projected-Newton QP solver\n   */\n  ~BoxQP();\n\n  /**\n   * @brief Compute the solution of bound-constrained QP based on Newton projection\n   *\n   * @param[in] H      Hessian (dimension nx * nx)\n   * @param[in] q      Gradient (dimension nx)\n   * @param[in] lb     Lower bound (dimension nx)\n   * @param[in] ub     Upper bound (dimension nx)\n   * @param[in] xinit  Initial guess (dimension nx)\n   * @return The solution of the problem\n   */\n  const BoxQPSolution& solve(const Eigen::MatrixXd& H, const Eigen::VectorXd& q, const Eigen::VectorXd& lb,\n                             const Eigen::VectorXd& ub, const Eigen::VectorXd& xinit);\n\n  /**\n   * @brief Return the stored solution\n   */\n  const BoxQPSolution& get_solution() const;\n\n  /**\n   * @brief Return the decision vector dimension\n   */\n  std::size_t get_nx() const;\n\n  /**\n   * @brief Return the maximum allowed number of iterations\n   */\n  std::size_t get_maxiter() const;\n\n  /**\n   * @brief Return the acceptance step threshold\n   */\n  double get_th_acceptstep() const;\n\n  /**\n   * @brief Return the gradient tolerance threshold\n   */\n  double get_th_grad() const;\n\n  /**\n   * @brief Return the regularization value\n   */\n  double get_reg() const;\n\n  /**\n   * @brief Return the stack of step lengths using by the line-search procedure\n   */\n  const std::vector<double>& get_alphas() const;\n\n  /**\n   * @brief Modify the decision vector dimension\n   */\n  void set_nx(const std::size_t nx);\n\n  /**\n   * @brief Modify the maximum allowed number of iterations\n   */\n  void set_maxiter(const std::size_t maxiter);\n\n  /**\n   * @brief Modify the acceptance step threshold\n   */\n  void set_th_acceptstep(const double th_acceptstep);\n\n  /**\n   * @brief Modify the gradient tolerance threshold\n   */\n  void set_th_grad(const double th_grad);\n\n  /**\n   * @brief Modify the regularization value\n   */\n  void set_reg(const double reg);\n\n  /**\n   * @brief Modify the stack of step lengths using by the line-search procedure\n   */\n  void set_alphas(const std::vector<double>& alphas);\n\n private:\n  std::size_t nx_;          //!< Decision variable dimension\n  BoxQPSolution solution_;  //!< Solution of the Box QP\n  std::size_t maxiter_;     //!< Allowed maximum number of iterations\n  double th_acceptstep_;    //!< Threshold used for accepting step\n  double th_grad_;          //!< Tolerance for stopping the algorithm (gradient threshold)\n  double reg_;              //!< Current regularization value\n\n  double fold_;                 //!< Cost of previous iteration\n  double fnew_;                 //!< Cost of current iteration\n  std::size_t nf_;              //!< Free space dimension\n  std::size_t nc_;              //!< Constrained space dimension\n  std::vector<double> alphas_;  //!< Set of step lengths using by the line-search procedure\n  Eigen::VectorXd x_;           //!< Guess of the decision variable\n  Eigen::VectorXd xnew_;        //!< New decision variable guess\n  Eigen::VectorXd g_;           //!< Current gradient\n  Eigen::VectorXd dx_;          //!< Current search direction\n\n  Eigen::VectorXd qf_;                       //!< Current problem gradient in the free subspace\n  Eigen::VectorXd xf_;                       //!< Current decision variable in the free subspace\n  Eigen::VectorXd xc_;                       //!< Current decision variable in the constrained subspace\n  Eigen::VectorXd dxf_;                      //!< Search direction in the free subspace\n  Eigen::MatrixXd Hff_;                      //!< Hessian in the free subspace\n  Eigen::MatrixXd Hfc_;                      //!< Hessian in the constrained subspace\n  Eigen::LLT<Eigen::MatrixXd> Hff_inv_llt_;  //!< Cholesky solver\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n", "meta": {"hexsha": "15ca282a45427bcc9ff62f056aa498ad2e9a7749", "size": 7334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_stars_repo_name": "spykspeigel/crocoddyl", "max_stars_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 322.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T12:04:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:37:44.000Z", "max_issues_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_issues_repo_name": "spykspeigel/crocoddyl", "max_issues_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 954.0, "max_issues_repo_issues_event_min_datetime": "2019-09-02T10:07:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:14:25.000Z", "max_forks_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_forks_repo_name": "spykspeigel/crocoddyl", "max_forks_repo_head_hexsha": "0500e398861564b6986d99206a1e0ccec0d66a33", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 89.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T13:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:55:07.000Z", "avg_line_length": 35.6019417476, "max_line_length": 110, "alphanum_fraction": 0.6464412326, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5846878196499996}}
{"text": "\r\n#include <bspline_fiting.hh>\r\n#include <Geo/iterate.hh>\r\n\r\n#pragma warning( push )\r\n#pragma warning( disable : 4714 )\r\n#include <Eigen/Dense>\r\n\r\n#include <fstream>\r\n#include <vector>\r\n\r\nnamespace Geo {\r\n\r\ntemplate<size_t dimT>\r\nstruct BsplineFitting : public IBsplineFitting<dimT>\r\n{\r\n  bool init(const size_t _deg,\r\n    const std::vector<double>& _knots, const IFunction& _f)\r\n  {\r\n    if (_knots.empty())\r\n      return false;\r\n    auto extn = (_knots.back() - _knots.front()) / 2;\r\n    knots_.push_back(_knots.front() - extn);\r\n    knots_.insert(knots_.end(), _knots.begin(), _knots.end());\r\n    knots_.push_back(_knots.back() + extn);\r\n    deg_ = _deg;\r\n    f_ = &_f;\r\n    X_.clear();\r\n    A_.clear();\r\n    B_.clear();\r\n    return true;\r\n  }\r\n\r\n  void set_parameter_correction_iterations(size_t _itr_nmbr) { itr_nmbr_ = _itr_nmbr; }\r\n  void set_favour_boundaries(const bool _fvr_bndr) { fvr_bndr_ = _fvr_bndr; }\r\n  void set_samples_per_interval(const size_t _smpl_per_intrvl) \r\n  {\r\n    smpl_per_intrvl_ = _smpl_per_intrvl;\r\n  }\r\n\r\n  void compute();\r\n  const std::vector<VectorD<dimT>>& X() const { return X_; }\r\n  VectorD<dimT> eval(const double _t);\r\nprivate:\r\n  void find_equations();\r\n  double N(size_t _i, const size_t _k, const double _t);\r\n  void add_equation(const double _t, const double _wi);\r\n\r\n  std::vector<std::vector<double>> A_;\r\n  std::vector<double> knots_;\r\n  std::vector<VectorD<dimT>> B_;\r\n  std::vector<VectorD<dimT>> X_;\r\n  size_t deg_ = 0;\r\n  const IFunction* f_ = nullptr;\r\n  size_t itr_nmbr_ = 0;\r\n  bool fvr_bndr_ = true;\r\n  size_t smpl_per_intrvl_ = 4;\r\n};\r\n\r\ntemplate<size_t dimT>\r\ndouble BsplineFitting<dimT>::N(size_t _i, const size_t _p, const double _t)\r\n{\r\n  if (_p == 0)\r\n  {\r\n    if (_t < knots_[_i] || _t >= knots_[_i + 1])\r\n      return 0;\r\n    return 1;\r\n  }\r\n  double res = 0;\r\n\r\n  auto b = N(_i, _p - 1, _t);\r\n  if (b != 0)\r\n    res += b * (_t - knots_[_i]) / (knots_[_i + _p] - knots_[_i]);\r\n\r\n  b = N(_i + 1, _p - 1, _t);\r\n  if (b != 0)\r\n  {\r\n    auto end_kn = knots_[_i + _p + 1];\r\n    res += b * (end_kn - _t) / (end_kn - knots_[_i + 1]);\r\n  }\r\n  return res;\r\n}\r\n\r\ntemplate<size_t dimT>\r\nvoid BsplineFitting<dimT>::add_equation(const double _t, const double _wi)\r\n{\r\n  A_.emplace_back();\r\n  const auto wi_sqr = sqrt(_wi);\r\n  for (int j = 0; j < knots_.size() - deg_ - 1; ++j)\r\n    A_.back().push_back(N(j, deg_, _t) * wi_sqr);\r\n\r\n  VectorD<dimT> pt_crv;\r\n  if (X_.empty() || (_t == knots_[1]) || (_t == knots_[knots_.size() - 2]))\r\n    pt_crv = f_->evaluate(_t);\r\n  else\r\n    pt_crv = f_->closest_point(eval(_t), _t);\r\n  B_.emplace_back(pt_crv * wi_sqr);\r\n};\r\n\r\ntemplate<size_t dimT>\r\nvoid BsplineFitting<dimT>::find_equations()\r\n{\r\n  A_.clear();\r\n  B_.clear();\r\n  if (fvr_bndr_)\r\n  {\r\n    double w_prev = 0;\r\n    const auto last_idx = knots_.size() - 2;\r\n    for (size_t i = 2; i <= last_idx; ++i)\r\n    {\r\n      auto dw = knots_[i] - knots_[i - 1];\r\n      if (dw <= 0)\r\n        continue;\r\n      const double step = 1. / smpl_per_intrvl_;\r\n      const double w_step = dw * step;\r\n      auto wi = w_prev + w_step / 2;\r\n      for (double x = 0; x < 1; x += step)\r\n      {\r\n        auto t = knots_[i - 1] * (1 - x) + knots_[i] * x;\r\n        add_equation(t, wi);\r\n        wi = w_step;\r\n      }\r\n      w_prev = w_step / 2;\r\n    }\r\n    add_equation(knots_[last_idx], w_prev);\r\n  }\r\n  else\r\n  {\r\n    const auto last_idx = knots_.size() - 2;\r\n    for (size_t i = 2; i <= last_idx; ++i)\r\n    {\r\n      auto dw = knots_[i] - knots_[i - 1];\r\n      if (dw <= 0)\r\n        continue;\r\n      const double step = 1. / smpl_per_intrvl_;\r\n      const double wi = dw * step;\r\n      for (double x = step / 2; x < 1; x += step)\r\n        add_equation(knots_[i - 1] * (1 - x) + knots_[i] * x, wi);\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<size_t dimT>\r\nvoid BsplineFitting<dimT>::compute()\r\n{\r\n  for (size_t iter = 0; iter <= itr_nmbr_; ++iter)\r\n  {\r\n    find_equations();\r\n    const auto row_nmbr = A_.size();\r\n    const auto col_nmbr = A_.front().size();\r\n    Eigen::MatrixXd A(row_nmbr, col_nmbr);\r\n    for (int i = 0; i < row_nmbr; ++i)\r\n    {\r\n      for (int j = 0; j < col_nmbr; ++j)\r\n        A(i, j) = A_[i][j];\r\n    }\r\n    const auto& jsvd =\r\n      A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\r\n    for (int j = 0; j < B_[0].size(); ++j)\r\n    {\r\n      Eigen::VectorXd B(B_.size());\r\n      for (int i = 0; i < row_nmbr; ++i)\r\n        B(i) = B_[i][j];\r\n      Eigen::VectorXd res = jsvd.solve(B);\r\n      X_.resize(col_nmbr);\r\n      for (int i = 0; i < col_nmbr; ++i)\r\n        X_[i][j] = res(i);\r\n    }\r\n  }\r\n}\r\n\r\ntemplate<size_t dimT>\r\nVectorD<dimT> BsplineFitting<dimT>::eval(const double _t)\r\n{\r\n  VectorD<dimT> res = { 0 };\r\n  for (int i = 0; i < X_.size(); ++i)\r\n    res += N(i, deg_, _t) * X_[i];\r\n  return res;\r\n}\r\n\r\ntemplate<size_t dimT>\r\nstd::shared_ptr<IBsplineFitting<dimT>> IBsplineFitting<dimT>::make()\r\n{\r\n  return std::make_shared<BsplineFitting<dimT>>();\r\n}\r\n\r\ntemplate struct IBsplineFitting<2>;\r\ntemplate struct IBsplineFitting<3>;\r\n\r\n}//namespace Geo\r\n", "meta": {"hexsha": "5b0fdc4b833fc9a24894a0a8edbf308927d2e7e2", "size": 4997, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main/src/Geo/bspline_fiting.cc", "max_stars_repo_name": "marcomanno/ploygon_triangulation", "max_stars_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/src/Geo/bspline_fiting.cc", "max_issues_repo_name": "marcomanno/ploygon_triangulation", "max_issues_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/src/Geo/bspline_fiting.cc", "max_forks_repo_name": "marcomanno/ploygon_triangulation", "max_forks_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1623036649, "max_line_length": 88, "alphanum_fraction": 0.5711426856, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5846878106988379}}
{"text": "// --------------------------------------------------------------\r\n// SL 2019-02-25\r\n// A simple, easily hackable topopt code, directly inspired\r\n// from \"A 99 line topology optimization code written in MATLAB\"\r\n// MIT-license\r\n// (c) Sylvain Lefebvre, https://github.com/sylefeb\r\n// --------------------------------------------------------------\r\n/*\r\n\r\nThis code is directly inspired from the fantastic paper\r\n\r\nA 99 line topology optimization code written in MATLAB\r\nStructural and Multidisciplinary Optimization 21(2), 2001, pp. 120-127\r\nby Ole Sigmund.\r\n\r\nhttp://www.topopt.mek.dtu.dk/Apps-and-software/A-99-line-topology-optimization-code-written-in-MATLAB\r\n\r\nI simply re-implemented it in C/C++ using LibSL-small and Eigen.\r\nAnd yes, it takes more than 99 lines of C/C++ ;-)\r\n\r\nNotations\r\n---------\r\n\r\n- dens : optimized densities\r\n- nelx : number of elements along X axis (nelx+1 corners) \r\n- nely : number of elements along Y axis (nely+1 corners)\r\n- dc   : compliance gradient\r\n- KE   : stiffness matrix for a single element\r\n\r\n*/\r\n// --------------------------------------------------------------\r\n\r\n#include <LibSL/LibSL.h>\r\n#include <Eigen/Sparse>\r\n\r\n#include <iostream>\r\n#include <ctime>\r\n#include <cmath>\r\n#include <set>\r\n#include <limits>\r\n\r\n// --------------------------------------------------------------\r\n\r\nusing namespace std;\r\n\r\n// --------------------------------------------------------------\r\n\r\nLIBSL_WIN32_FIX;\r\n\r\n// --------------------------------------------------------------\r\n\r\n// stiffness matrix for a unit square element\r\nArray2D<double> KE;\r\n\r\n// Computes the stiffness matrix of a single, unit square element\r\n// (forward declaration, code at the end)\r\nvoid lk(Array2D<double>& _KE);\r\n\r\n// --------------------------------------------------------------\r\n\r\n// matrix vector multiply\r\ntemplate <typename T>\r\nvoid mv_mul(const Array2D<T>& A, const Array<T>& v, Array<T>& _res)\r\n{\r\n  _res.allocate(v.size());\r\n  ForIndex(l, A.ysize()) {\r\n    T al = 0;\r\n    ForIndex(c, A.xsize()) {\r\n      al = al + A.at(c, l) * v[c];\r\n    }\r\n    _res[l] = al;\r\n  }\r\n}\r\n\r\n// vector-vector multiply\r\ntemplate <typename T>\r\nT vv_mul(const Array<T>& a, const Array<T>& b)\r\n{\r\n  T res = 0;\r\n  ForIndex(i, a.size()) {\r\n    res = res + a[i] * b[i];\r\n  }\r\n  return res;\r\n}\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Applies optimality criterion (OC) to update densities (x) from compliance gradient (dc).\r\n// Maintains the volume fraction\r\nvoid OC(int nelx, int nely, Array2D<double>& _dens, double volfrac, const Array2D<double>& dc)\r\n{\r\n  double move = 0.2;\r\n  Array2D<double> dens_new(_dens.xsize(), _dens.ysize());\r\n  double vtot = 0.0;\r\n  double l1 = 0, l2 = 100000;\r\n  while (l2 - l1 > 1e-3) { // bisection search for volume preservation\r\n    double lmid = 0.5*(l2 + l1);\r\n    vtot = 0.0;\r\n    ForArray2D(dens_new, c, l) {\r\n      // OC term\r\n      double Be = (-dc.at(c, l)) / lmid;\r\n      dens_new.at(c, l) = max(0.02,\r\n        max(_dens.at(c, l) - move,\r\n          min(1.0,\r\n            min(_dens.at(c, l) + move, _dens.at(c, l) * sqrt(Be))\r\n          )\r\n        )\r\n      );\r\n      vtot += dens_new.at(c, l);\r\n    }\r\n    if (vtot - volfrac * nelx * nely > 0.0) {\r\n      l1 = lmid;\r\n    } else {\r\n      l2 = lmid;\r\n    }\r\n  }\r\n  cerr << \"Vol frac in result  \" << vtot / (nelx* nely) << endl;\r\n  _dens = dens_new;\r\n}\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Filters the result to prevent the 'checkerboard effect' due to the solver\r\n// attempting to produce infinitely small 'bubbles' (composite).\r\nvoid filter(int nelx, int nely, double rmin, const Array2D<double>& dens, Array2D<double>& _dc)\r\n{\r\n  Array2D<double> dcn(nelx, nely);\r\n  dcn.fill(0);\r\n  ForArray2D(dcn, i, j) {\r\n    double sum = 0.0;\r\n    ForRange(l, max(j - round(rmin), 0), min(j + round(rmin), nely - 1)) {\r\n      ForRange(k, max(i - round(rmin), 0), min(i + round(rmin), nelx - 1)) {\r\n        double fac = rmin - sqrt((double)(i - k)*(i - k) + (double)(j - l)*(j - l));\r\n        sum += max(0.0f, fac);\r\n        dcn.at(i, j) = dcn.at(i, j) + max(0.0f, fac) * dens.at(k, l) * _dc.at(k, l);\r\n      }\r\n    }\r\n    dcn.at(i, j) = dcn.at(i, j) / (dens.at(i, j)*sum);\r\n  }\r\n  _dc = dcn;\r\n}\r\n\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Straightforward linear finite element solver\r\n// The degrees of freedom (variables) are the corners of the elements, times two (x and y coordinates)\r\n// Each corner at (cx,cy) is associated to two ids:\r\n//   - grid id computed cx + (nelx + 1) * cy\r\n//   - variable id which identifies it in the sparse system of equations\r\n// The x/y coordinates are at respectively id*2+0 and id*2+1\r\nvoid FE(int nelx, int nely, const Array2D<double>& dens, double penal, Array2D<v2f>& _U)\r\n{\r\n  // variables to lock: there are attachement points of the structure\r\n  set<int> locked;\r\n  // -> here we attach the left third of the bottom row (x in  [0,(nelx + 1) / 3 - 1] , y = nely\r\n  ForIndex(x, (nelx + 1) / 3) {\r\n    locked.insert((x + (nelx + 1) * nely) * 2 + 0); // x\r\n    locked.insert((x + (nelx + 1) * nely) * 2 + 1); // y\r\n  }\r\n  // mapping between variable and ids\r\n  Array<int>   grid2var(2 * (nelx + 1)*(nely + 1));\r\n  Array<int>   var2grid(2 * (nelx + 1)*(nely + 1) - (int)locked.size());\r\n  grid2var.fill(-1);\r\n  var2grid.fill(-1);\r\n  int varid = 0;\r\n  ForIndex(gridid, 2 * (nelx + 1)*(nely + 1)) {\r\n    if (locked.find(gridid) == locked.end()) {\r\n      grid2var[gridid] = varid;\r\n      var2grid[varid]  = gridid;\r\n      varid++;\r\n    }\r\n  }\r\n  sl_assert(varid == 2 * (nelx + 1)*(nely + 1) - (int)locked.size());\r\n  // matrix A (FE equations)\r\n  std::vector<Eigen::Triplet<double> > coefficients;\r\n  ForIndex(x, nelx) {\r\n    ForIndex(y, nely) {\r\n      int p00 = (x + (y)* (nelx + 1));\r\n      int p01 = (x + (y + 1) * (nelx + 1));\r\n      int p11 = ((x + 1) + (y + 1) * (nelx + 1));\r\n      int p10 = ((x + 1) + (y)* (nelx + 1));\r\n      Array<int> corners(8);\r\n      corners[0] = p00 * 2 + 0;\r\n      corners[1] = p00 * 2 + 1;\r\n      corners[2] = p10 * 2 + 0;\r\n      corners[3] = p10 * 2 + 1;\r\n      corners[4] = p11 * 2 + 0;\r\n      corners[5] = p11 * 2 + 1;\r\n      corners[6] = p01 * 2 + 0;\r\n      corners[7] = p01 * 2 + 1;\r\n      double pow_x = pow(dens.at(x, y), penal);\r\n      // add coefficients only for non-locked variables\r\n      ForIndex(k, 8) {\r\n        if (grid2var[corners[k]] > -1) {\r\n          ForIndex(l, 8) {\r\n            if (grid2var[corners[l]] > -1) {\r\n              coefficients.push_back(Eigen::Triplet<double>(grid2var[corners[k]], grid2var[corners[l]],\r\n                KE.at(l, k) * pow_x\r\n                ));\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n  }\r\n  Eigen::SparseMatrix<double> A(\r\n    2 * (nelx + 1)*(nely + 1) - locked.size(),\r\n    2 * (nelx + 1)*(nely + 1) - locked.size());\r\n  A.setFromTriplets(coefficients.begin(), coefficients.end());\r\n  // vector b, contains external forces\r\n  Eigen::VectorXd b = Eigen::VectorXd(2 * (nelx + 1)*(nely + 1) - locked.size());\r\n  ForIndex(i, b.size()) {\r\n    b[i] = 0.0;\r\n  }\r\n  // -> here we apply external forces at two specific points (near the image top)\r\n  b[grid2var[(nelx / 2     + 24 * (nelx + 1)) * 2 + 1]] = -1;\r\n  b[grid2var[(nelx * 5 / 6 + 16 * (nelx + 1)) * 2 + 1]] = -1;\r\n  //                                         ^^^^^^^ force in y direction\r\n  // solver\r\n  cerr << \"solving ...\";\r\n  Eigen::SparseLU<Eigen::SparseMatrix<double> > solver(A);\r\n  Eigen::VectorXd result = solver.solve(b);\r\n  cerr << \" done.\\n\";\r\n  // store computed displacement\r\n  _U.allocate(nelx + 1, nely + 1);\r\n  ForIndex(varid, result.size()) {\r\n    int gridid = var2grid[varid];\r\n    int x = (gridid / 2) % (nelx + 1);\r\n    int y = (gridid / 2) / (nelx + 1);\r\n    int c = (gridid & 1);\r\n    _U.at(x, y)[c] = (float)result[varid];\r\n  }\r\n}\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Executes the global optimization loop until 'convergence' (change below threshold)\r\n// volfrac is the target volume fraction in [0-1]\r\n// penal   is the density penality (typically 3)\r\n// rmin    controls the filter size\r\nvoid topopt(int nelx, int nely, double volfrac, double penal, double rmin)\r\n{\r\n  ImageFloat1     img(nelx, nely);  // for image output\r\n  Array2D<double> dens(nelx, nely); // optimized density grid\r\n  Array2D<double> dens_old;         // result from previous iteration\r\n  Array2D<double> dc(nelx, nely);   // compliance gradient\r\n\r\n  // initialization with a random field of selected volume fraction (volfrac)\r\n  double tot = 0;\r\n  ForArray2D(dens, i, j) {\r\n    dens.at(i, j) = rnd();\r\n    tot += dens.at(i, j);\r\n  }\r\n  tot = tot / (nelx*nely);\r\n  ForArray2D(dens, i, j) {\r\n    dens.at(i, j) = volfrac * dens.at(i, j) / tot;\r\n  }\r\n  int loop = 0;\r\n  double change = 1;\r\n  while (change > 0.01) {\r\n\r\n    loop++;\r\n    dens_old = dens;\r\n\r\n    // solve for displacement (finite element solution)\r\n    Array2D<v2f> U;\r\n    FE(nelx, nely, dens, penal, /*out*/ U);\r\n\r\n    // option to output displacement magnitudes\r\n    if (0) {\r\n      ImageFloat1 img;\r\n      img.pixels().allocate(nelx + 1, nely + 1);\r\n      ForImage((&img), i, j) {\r\n        img.pixel(i, j) = length(U.at(i, j));\r\n      }\r\n      img.remap(0.0f, 255.0f);\r\n      saveImage(sprint(\"%03d_FE.tga\", loop), img.cast<ImageL8>());\r\n    }\r\n\r\n    // compute compliance and gradient\r\n    // -> for each element\r\n    double c_comp = 0.0;\r\n    ForIndex(ely, nely) {\r\n      ForIndex(elx, nelx) {\r\n        // get displacement for the element\r\n        Array<double> corners(8);\r\n        corners[0] = U.at(elx, ely)[0];\r\n        corners[1] = U.at(elx, ely)[1];\r\n        corners[2] = U.at(elx + 1, ely)[0];\r\n        corners[3] = U.at(elx + 1, ely)[1];\r\n        corners[4] = U.at(elx + 1, ely + 1)[0];\r\n        corners[5] = U.at(elx + 1, ely + 1)[1];\r\n        corners[6] = U.at(elx, ely + 1)[0];\r\n        corners[7] = U.at(elx, ely + 1)[1];\r\n        // compute compliance\r\n        Array<double> KE_Ue;\r\n        mv_mul(KE, corners, /*out*/KE_Ue);\r\n        v2d Ue_KE_Ue = vv_mul(KE_Ue, corners);        \r\n        double compliance = Ue_KE_Ue[0] + Ue_KE_Ue[1];\r\n        double comp       = pow(dens.at(elx, ely), penal) * compliance;\r\n        c_comp += comp;\r\n        // gradient\r\n        double dcomp    = -penal * pow(dens.at(elx, ely), penal - 1.0f) * compliance;\r\n        dc.at(elx, ely) = dcomp;\r\n      }\r\n    }\r\n\r\n    // filtering\r\n    filter(nelx, nely, rmin, dens, dc/*out*/);\r\n\r\n    // OC method\r\n    OC(nelx, nely, dens/*out*/, volfrac, dc);\r\n\r\n#if 0\r\n    // For fun: kills a circle of density (obstacle)\r\n    ForArray2D(dens, i, j) {\r\n      if ( length(v2f((float)i, (float)j) - v2f((float)nelx/2, (float)nely/2)) < nelx/6.0f) {\r\n        dens.at(i, j) = 0.01;\r\n      }\r\n    }\r\n#endif\r\n\r\n    // compute max change\r\n    change = 0.0;\r\n    ForArray2D(dens, i, j) {\r\n      change = max(change, abs(dens.at(i, j) - dens_old.at(i, j)));\r\n    }\r\n    // output iteration stats\r\n    cerr << sprint(\" Loop %d, compliance = %f, change = %f\\n\", loop, c_comp, change);\r\n    // output image\r\n    ForImage((&img), i, j) {\r\n      img.pixel(i,j) = 255.0f * (1.0f - (float)pow(dens.at(i,j),penal));\r\n    }\r\n    saveImage(sprint(\"%03d_struct.tga\", loop), img.cast<ImageL8>());\r\n\r\n  }\r\n\r\n}\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Program entry point.\r\nint main(int argc, char **argv)\r\n{\r\n  try {\r\n\r\n    // generate stiffness matrix for unit element\r\n    lk(KE);\r\n\r\n    // go ahead!\r\n    topopt(256, 96, 0.3f, 3.0f, 1.2f);\r\n\r\n  } catch (Fatal& e) {\r\n    cerr << Console::red << e.message() << Console::gray << endl;\r\n    return (-1);\r\n  }\r\n\r\n  return (0);\r\n}\r\n\r\n// --------------------------------------------------------------\r\n\r\n// Computes the stiffness matrix of a single, unit square element\r\nvoid lk(Array2D<double>& _KE)\r\n{\r\n  double E = 1.0f;\r\n  double nu = 0.3f;\r\n  double k[8];\r\n  k[0] = 1.0f / 2.0 - nu / 6.0;\r\n  k[1] = 1.0f / 8.0 + nu / 8.0;\r\n  k[2] = -1.0f / 4.0 - nu / 12.0;\r\n  k[3] = -1.0f / 8.0 + 3.0*nu / 8.0;\r\n  k[4] = -1.0f / 4.0 + nu / 12.0;\r\n  k[5] = -1.0f / 8.0 - nu / 8.0;\r\n  k[6] = nu / 6.0;\r\n  k[7] = 1.0f / 8.0 - 3.0*nu / 8.0;\r\n  _KE.allocate(8, 8);\r\n\r\n  _KE.at(0, 0) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(1, 0) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(2, 0) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(3, 0) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(4, 0) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(5, 0) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(6, 0) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(7, 0) = E / (1.0 - nu * nu) * k[7];\r\n\r\n  _KE.at(0, 1) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(1, 1) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(2, 1) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(3, 1) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(4, 1) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(5, 1) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(6, 1) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(7, 1) = E / (1.0 - nu * nu) * k[2];\r\n\r\n  _KE.at(0, 2) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(1, 2) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(2, 2) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(3, 2) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(4, 2) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(5, 2) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(6, 2) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(7, 2) = E / (1.0 - nu * nu) * k[1];\r\n\r\n  _KE.at(0, 3) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(1, 3) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(2, 3) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(3, 3) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(4, 3) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(5, 3) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(6, 3) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(7, 3) = E / (1.0 - nu * nu) * k[4];\r\n\r\n  _KE.at(0, 4) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(1, 4) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(2, 4) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(3, 4) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(4, 4) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(5, 4) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(6, 4) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(7, 4) = E / (1.0 - nu * nu) * k[3];\r\n\r\n  _KE.at(0, 5) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(1, 5) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(2, 5) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(3, 5) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(4, 5) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(5, 5) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(6, 5) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(7, 5) = E / (1.0 - nu * nu) * k[6];\r\n\r\n  _KE.at(0, 6) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(1, 6) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(2, 6) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(3, 6) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(4, 6) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(5, 6) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(6, 6) = E / (1.0 - nu * nu) * k[0];\r\n  _KE.at(7, 6) = E / (1.0 - nu * nu) * k[5];\r\n\r\n  _KE.at(0, 7) = E / (1.0 - nu * nu) * k[7];\r\n  _KE.at(1, 7) = E / (1.0 - nu * nu) * k[2];\r\n  _KE.at(2, 7) = E / (1.0 - nu * nu) * k[1];\r\n  _KE.at(3, 7) = E / (1.0 - nu * nu) * k[4];\r\n  _KE.at(4, 7) = E / (1.0 - nu * nu) * k[3];\r\n  _KE.at(5, 7) = E / (1.0 - nu * nu) * k[6];\r\n  _KE.at(6, 7) = E / (1.0 - nu * nu) * k[5];\r\n  _KE.at(7, 7) = E / (1.0 - nu * nu) * k[0];\r\n}\r\n\r\n// --------------------------------------------------------------\r\n", "meta": {"hexsha": "4896a0096103600a4c6a407b787dd5e14c89c672", "size": 15186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "topopt.cpp", "max_stars_repo_name": "sylefeb/topopt99", "max_stars_repo_head_hexsha": "4cc6b824ff693d7e138cd516e8ad1cdca3167651", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T14:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-02T06:01:18.000Z", "max_issues_repo_path": "topopt.cpp", "max_issues_repo_name": "sylefeb/topopt99", "max_issues_repo_head_hexsha": "4cc6b824ff693d7e138cd516e8ad1cdca3167651", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "topopt.cpp", "max_forks_repo_name": "sylefeb/topopt99", "max_forks_repo_head_hexsha": "4cc6b824ff693d7e138cd516e8ad1cdca3167651", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T06:02:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T06:02:24.000Z", "avg_line_length": 33.449339207, "max_line_length": 104, "alphanum_fraction": 0.4770841565, "num_tokens": 5568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5846877933066303}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2020, Jesus Tordesillas Torres, Aerospace Controls Laboratory\n * Massachusetts Institute of Technology\n * All Rights Reserved\n * Authors: Jesus Tordesillas, et al.\n * See LICENSE file for the license information\n * -------------------------------------------------------------------------- */\n\n// Continuous version, and with polytope constraints.\n\n#include \"gurobi_c++.h\"\n#include <sstream>\n#include <Eigen/Dense>\n#include <type_traits>\nusing namespace std;\n\ntemplate <typename T>\nGRBQuadExpr GetNorm2(const std::vector<T>& x)  // Return the squared norm of a vector\n{\n  GRBQuadExpr result = 0;\n  for (int i = 0; i < x.size(); i++)\n  {\n    result = result + x[i] * x[i];\n  }\n  return result;\n}\n\nstd::vector<GRBLinExpr> MatrixMultiply(const std::vector<std::vector<double>>& A, const std::vector<GRBVar>& x)\n{\n  std::vector<GRBLinExpr> result;\n\n  for (int i = 0; i < A.size(); i++)\n  {\n    GRBLinExpr lin_exp = 0;\n    for (int m = 0; m < x.size(); m++)\n    {\n      lin_exp = lin_exp + A[i][m] * x[m];\n    }\n    result.push_back(lin_exp);\n  }\n  return result;\n}\n\nstd::vector<GRBLinExpr> MatrixMultiply(const std::vector<std::vector<double>>& A, const std::vector<GRBLinExpr>& x)\n{\n  std::vector<GRBLinExpr> result;\n\n  for (int i = 0; i < A.size(); i++)\n  {\n    GRBLinExpr lin_exp = 0;\n    for (int m = 0; m < x.size(); m++)\n    {\n      lin_exp = lin_exp + A[i][m] * x[m];\n    }\n    result.push_back(lin_exp);\n  }\n  return result;\n}\n\ntemplate <typename T>  // Overload + to sum Elementwise std::vectors\nstd::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::plus<T>());\n  return result;\n}\n\ntemplate <typename T>  // Overload - to substract Elementwise std::vectors\nstd::vector<T> operator-(const std::vector<T>& a, const std::vector<T>& b)\n{\n  assert(a.size() == b.size());\n\n  std::vector<T> result;\n  result.reserve(a.size());\n\n  std::transform(a.begin(), a.end(), b.begin(), std::back_inserter(result), std::minus<T>());\n  return result;\n}\n\nstd::vector<GRBLinExpr> operator-(const std::vector<GRBVar>& x, const std::vector<double>& b)\n{\n  std::vector<GRBLinExpr> result;\n  for (int i = 0; i < x.size(); i++)\n  {\n    GRBLinExpr tmp = x[i] - b[i];\n    result.push_back(tmp);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> eigenVector2std(const Eigen::Matrix<T, -1, 1>& x)\n{\n  std::vector<T> result = 0;\n  for (int i = 0; i < x.rows(); i++)\n  {\n    result.push_back(x(i, 1));\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<std::vector<T>> eigenMatrix2std(const Eigen::Matrix<T, -1, -1>& x)\n{\n  std::vector<std::vector<T>> result;\n\n  for (int i = 0; i < x.rows(); i++)\n  {\n    std::vector<T> row;\n    for (int j = 0; j < x.cols(); j++)\n    {\n      row.push_back(x(i, j));\n    }\n    result.push_back(row);\n  }\n  return result;\n}\n\ntemplate <typename T>\nstd::vector<T> GetColumn(std::vector<std::vector<T>> x, int column)\n{\n  std::vector<T> result;\n\n  for (int i = 0; i < x.size(); i++)\n  {\n    result.push_back(x[i][column]);\n  }\n  return result;\n}\n\nGRBLinExpr getPos(int t, double tau, int ii, bool solved, std::vector<std::vector<GRBVar>> x)\n{\n  if (solved == true)\n  {\n    GRBLinExpr pos = (x[t][0 + ii].get(GRB_DoubleAttr_X)) * tau * tau * tau +\n                     (x[t][3 + ii].get(GRB_DoubleAttr_X)) * tau * tau + (x[t][6 + ii].get(GRB_DoubleAttr_X)) * tau +\n                     (x[t][9 + ii].get(GRB_DoubleAttr_X));\n    return pos;\n  }\n  else\n  {\n    GRBLinExpr pos = x[t][0 + ii] * tau * tau * tau + x[t][3 + ii] * tau * tau + x[t][6 + ii] * tau + x[t][9 + ii];\n    return pos;\n  }\n}\n\nGRBLinExpr getVel(int t, double tau, int ii, bool solved, std::vector<std::vector<GRBVar>> x)\n{  // t is the segment, tau is the time inside a specific segment (\\in[0,dt], i is the axis)\n  if (solved == true)\n  {\n    GRBLinExpr vel = (3 * x[t][0 + ii].get(GRB_DoubleAttr_X)) * tau * tau +\n                     (2 * x[t][3 + ii].get(GRB_DoubleAttr_X)) * tau + (x[t][6 + ii].get(GRB_DoubleAttr_X));\n    return vel;\n  }\n  else\n  {\n    GRBLinExpr vel = 3 * x[t][0 + ii] * tau * tau + 2 * x[t][3 + ii] * tau + x[t][6 + ii];\n    return vel;\n  }\n}\n\nGRBLinExpr getAccel(int t, double tau, int ii, bool solved, std::vector<std::vector<GRBVar>> x)\n{  // t is the segment, tau is the time inside a specific segment(\\in[0, dt], i is the axis)\n  if (solved == true)\n  {\n    GRBLinExpr accel = (6 * x[t][0 + ii].get(GRB_DoubleAttr_X)) * tau + 2 * x[t][3 + ii].get(GRB_DoubleAttr_X);\n    return accel;\n  }\n  else\n  {\n    GRBLinExpr accel = 6 * x[t][0 + ii] * tau + 2 * x[t][3 + ii];\n    return accel;\n  }\n}\n\nGRBLinExpr getJerk(int t, double tau, int ii, bool solved, std::vector<std::vector<GRBVar>> x)\n{  // t is the segment, tau is the time inside a specific segment (\\in[0,dt], i is the axis)\n  if (solved == true)\n  {\n    GRBLinExpr jerk = 6 * x[t][0 + ii].get(GRB_DoubleAttr_X);  // Note that here tau doesn't appear (makes sense)\n    return jerk;\n  }\n  else\n  {\n    GRBLinExpr jerk = 6 * x[t][0 + ii];  // Note that here tau doesn't appear (makes sense)\n    return jerk;\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  GRBEnv* env = 0;\n  GRBVar* open = 0;\n  GRBVar** transport = 0;\n  int transportCt = 0;\n  try\n  {\n    // Model\n    env = new GRBEnv();\n    GRBModel m = GRBModel(*env);\n    m.set(GRB_StringAttr_ModelName, \"planning\");\n\n    int N = 10;\n    double umax = 5;\n    double amax = 3;\n    double vmax = 5;\n    /*    double q = 20000000000;*/\n    double dt = 5.0 / N;\n    /*    double dt2 = dt * dt / 2.0;\n        double dt3 = dt * dt * dt / 6.0;\n        std::vector<std::string> states = { \"x\", \"y\", \"z\", \"vx\", \"vy\", \"vz\", \"ax\", \"ay\", \"az\" };\n        std::vector<std::string> inputs = { \"jx\", \"jy\", \"jz\" };*/\n\n    std::vector<std::string> coeff = { \"ax\", \"ay\", \"az\", \"bx\", \"by\", \"bz\", \"cx\", \"cy\", \"cz\", \"dx\", \"dy\", \"dz\" };\n\n    std::vector<double> x0 = { 5, 11.5, 0.5, 0, 0, 0, 0, 0, 0 };\n\n    std::vector<double> xf = { 14, 5, 2.5, 0, 0, 0, 0, 0, 0 };\n\n    // std::cout << \"here1\" << std::endl;\n\n    std::vector<std::vector<GRBVar>> x;\n    std::vector<std::vector<GRBVar>> u;\n\n    for (int t = 0; t < N + 1; t++)\n    {\n      std::vector<GRBVar> row_t;\n      for (int i = 0; i < 12; i++)\n      {\n        row_t.push_back(m.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_CONTINUOUS, coeff[i] + std::to_string(t)));\n      }\n      x.push_back(row_t);\n    }\n\n    // std::cout << \"here2\" << std::endl;\n\n    /*    for (int i = 0; i < 3; i++)\n        {\n          std::vector<GRBVar> row_i;\n          for (int t = 0; t < N; t++)\n          {\n            row_i.push_back(m.addVar(-umax, umax, 0, GRB_CONTINUOUS, inputs[i] + std::to_string(t)));\n          }\n          u.push_back(row_i);\n        }*/\n\n    // Constraints x_t+1=Ax_t+Bu_t\n    for (int t = 0; t < N - 1; t++)\n    {\n      for (int i = 0; i < 3; i++)\n      {\n        m.addConstr(getPos(t, dt, i, false, x) == getPos(t + 1, 0, i, false, x));      // Continuity in position\n        m.addConstr(getVel(t, dt, i, false, x) == getVel(t + 1, 0, i, false, x));      // Continuity in velocity\n        m.addConstr(getAccel(t, dt, i, false, x) == getAccel(t + 1, 0, i, false, x));  // Continuity in acceleration\n      }\n    }\n\n    // std::cout << \"here3\" << std::endl;\n    // Constraint x0==x_initial\n\n    for (int i = 0; i < 3; i++)\n    {\n      m.addConstr(getPos(0, 0, i, false, x) == x0[i]);        // Initial position\n      m.addConstr(getVel(0, 0, i, false, x) == x0[i + 3]);    // Initial velocity\n      m.addConstr(getAccel(0, 0, i, false, x) == x0[i + 6]);  // Initial acceleration}\n    }\n\n    //  std::cout << \"here4\" << std::endl;\n\n    // Constraint xT==x_final\n    for (int i = 0; i < 3; i++)\n    {\n      m.addConstr(getPos(N - 1, dt, i, false, x) - xf[i] <= 0.2);   // Final position\n      m.addConstr(getPos(N - 1, dt, i, false, x) - xf[i] >= -0.2);  // Final position\n\n      m.addConstr(getVel(N - 1, dt, i, false, x) - xf[i + 3] <= 0.2);   // Final velocity\n      m.addConstr(getVel(N - 1, dt, i, false, x) - xf[i + 3] >= -0.2);  // Final velocity\n\n      m.addConstr(getAccel(N - 1, dt, i, false, x) - xf[i + 6] <= 0.2);   // Final acceleration\n      m.addConstr(getAccel(N - 1, dt, i, false, x) - xf[i + 6] >= -0.2);  // Final acceleration\n    }\n\n    // std::cout << \"here5\" << std::endl;\n    // Constraint v<=vmax, a<=amax, u<=umax\n    for (int t = 0; t < N - 1; t++)\n    {\n      for (int i = 0; i < 3; i++)\n      {\n        m.addConstr(getVel(t, dt, i, false, x) <= vmax);\n        m.addConstr(getVel(t, dt, i, false, x) >= -vmax);\n\n        m.addConstr(getAccel(t, dt, i, false, x) <= amax);\n        m.addConstr(getAccel(t, dt, i, false, x) >= -amax);\n\n        m.addConstr(getJerk(t, dt, i, false, x) <= umax);\n        m.addConstr(getJerk(t, dt, i, false, x) >= -umax);\n      }\n    }\n\n    //  std::cout << \"here6\" << std::endl;\n\n    /*    Eigen::Matrix<double, -1, 3> A1;\n        Eigen::Matrix<double, -1, 3> A2;\n        Eigen::Matrix<double, -1, 3> A3;*/\n\n    Eigen::MatrixXd A1(12, 3);\n    Eigen::MatrixXd A2(10, 3);\n    Eigen::MatrixXd A3(10, 3);\n\n    Eigen::VectorXd b1(12);\n    Eigen::VectorXd b2(10);\n    Eigen::VectorXd b3(10);\n\n    A1 << -0.0990887, 0.994031, -0.0456529,  ////////////////////////////////////\n        -0.11874, 0.992494, 0.0292636,       ////////////////////////////////////\n        0.315838, 0.947835, -0.0430724,      ////////////////////////////////////\n        0.279625, 0.956348, 0.0849006,       ////////////////////////////////////\n        0.0379941, -0.999235, -0.00925698,   ////////////////////////////////////\n        0.031154, -0.999406, 0.0147274,      ////////////////////////////////////\n        0, -1, 0,                            ////////////////////////////////////\n        -0, 1, -0,                           ////////////////////////////////////\n        0.95448, 0, 0.298275,                ////////////////////////////////////\n        -0.95448, -0, -0.298275,             ////////////////////////////////////\n        0.298275, 0, -0.95448,               ////////////////////////////////////\n        -0.298275, -0, 0.95448;              ////////////////////////////////////\n\n    std::cout << \"here6.5\" << std::endl;\n\n    b1 << 11.2113,\n        11.1351,   ////////////////////////////////////\n        15.1733,   ////////////////////////////////////\n        15.1708,   ////////////////////////////////////\n        -9.26336,  ////////////////////////////////////\n        -9.27607,  ////////////////////////////////////\n        -9.5,      ////////////////////////////////////\n        13.5,      ////////////////////////////////////\n        14.3031,   ////////////////////////////////////\n        -3.92154,  ////////////////////////////////////\n        2.01413,   ////////////////////////////////////\n        -0.014135;\n\n    A1 << -0.0990887, 0.994031, -0.0456529,  ////////////////////////////////////\n        -0.11874, 0.992494, 0.0292636,       ////////////////////////////////////\n        0.315838, 0.947835, -0.0430724,      ////////////////////////////////////\n        0.279625, 0.956348, 0.0849006,       ////////////////////////////////////\n        0.0379941, -0.999235, -0.00925698,   ////////////////////////////////////\n        0.031154, -0.999406, 0.0147274,      ////////////////////////////////////\n        0, -1, 0,                            ////////////////////////////////////\n        -0, 1, -0,                           ////////////////////////////////////\n        0.95448, 0, 0.298275,                ////////////////////////////////////\n        -0.95448, -0, -0.298275,             ////////////////////////////////////\n        0.298275, 0, -0.95448,               ////////////////////////////////////\n        -0.298275, -0, 0.95448;              ////////////////////////////////////\n\n    A2 << -0.199658, 0.976518, 0.0809297,  ////////////////////////////////////\n        -0.166117, 0.983608, -0.0701482,   ////////////////////////////////////\n        -0.358298, -0.933434, 0.0179951,   ////////////////////////////////////\n        -0.365568, -0.928824, -0.0603848,  ////////////////////////////////////\n        -0.707107, -0.707107, 0,           ////////////////////////////////////\n        0.707107, 0.707107, -0,            ////////////////////////////////////\n        0.485071, -0.485071, -0.727607,    ////////////////////////////////////\n        -0.485071, 0.485071, 0.727607,     ////////////////////////////////////\n        -0.514496, 0.514496, -0.685994,    ////////////////////////////////////\n        0.514496, -0.514496, 0.685994;     ////////////////////////////////////\n\n    b2 << 9.06362,  ////////////////////////////////////\n        9.21024,    ////////////////////////////////////\n        -13.5612,   ////////////////////////////////////\n        -13.7295,   ////////////////////////////////////\n        -15.3241,   ////////////////////////////////////\n        19.3241,    ////////////////////////////////////\n        1.60634,    ////////////////////////////////////\n        2.45521,    ////////////////////////////////////\n        -1.82973,   ////////////////////////////////////\n        3.82973;    ////////////////////////////////////\n\n    A3 << -0.999958, 0.00342454, 0.00852636,  ////////////////////////////////////\n        -0.999832, 0.00363672, -0.0179664,    ////////////////////////////////////\n        -0.999778, -0.0204566, 0.00504416,    ////////////////////////////////////\n        -0.999564, -0.0227306, -0.0188383,    ////////////////////////////////////\n        -1, -0, 0,                            ////////////////////////////////////\n        1, 0, -0,                             ////////////////////////////////////\n        0, -0.98387, 0.178885,                ////////////////////////////////////\n        -0, 0.98387, -0.178885,               ////////////////////////////////////\n        0, -0.178885, -0.98387,               ////////////////////////////////////\n        -0, 0.178885, 0.98387;\n\n    b3 << -12.7365,  ////////////////////////////////////\n        -12.7834,    ////////////////////////////////////\n        -12.9236,    ////////////////////////////////////\n        -12.9824,    ////////////////////////////////////\n        -12,         ////////////////////////////////////\n        16,          ////////////////////////////////////\n        -3.47214,    ////////////////////////////////////\n        11.0623,     ////////////////////////////////////\n        -2.3541,     ////////////////////////////////////\n        4.3541;\n    std::cout << \"here6.7\" << std::endl;\n\n    std::vector<std::vector<double>> A1std = eigenMatrix2std(A1);\n    std::vector<std::vector<double>> A2std = eigenMatrix2std(A2);\n    std::vector<std::vector<double>> A3std = eigenMatrix2std(A3);\n\n    /*    std::vector<std::vector<double>> b1std = eigenMatrix2std(b1);\n        std::vector<std::vector<double>> b2std = eigenMatrix2std(b2);\n        std::vector<std::vector<double>> b3std = eigenMatrix2std(b3);*/\n\n    // m.update();\n\n    std::cout << \"here7\" << std::endl;\n    std::vector<std::vector<GRBVar>> b;\n    for (int t = 0; t < N + 1; t++)\n    {\n      std::vector<GRBVar> row;\n      for (int i = 0; i < 3; i++)  // For the three polytopes\n      {\n        GRBVar variable =\n            m.addVar(-GRB_INFINITY, GRB_INFINITY, 0, GRB_BINARY, \"s\" + std::to_string(i) + \"_\" + std::to_string(t));\n        row.push_back(variable);\n      }\n      b.push_back(row);\n    }\n\n    std::cout << \"here8\" << std::endl;\n\n    // If is 1 --> in that polytope\n\n    for (int t = 0; t < N; t++)\n    {\n      GRBLinExpr sum = 0;\n      for (int col = 0; col < b[0].size(); col++)\n      {\n        sum = sum + b[t][col];\n      }\n      m.addConstr(sum == 1);\n\n      std::vector<GRBLinExpr> pos = { getPos(t, 0, 0, false, x), getPos(t, 0, 1, false, x), getPos(t, 0, 2, false, x) };\n\n      for (int i = 0; i < b1.rows(); i++)\n      {\n        m.addGenConstrIndicator(b[t][0], 1, MatrixMultiply(A1std, pos)[i], '<',\n                                b1[i]);  // If b[t,0]==1, then...\n      }\n      for (int i = 0; i < b2.rows(); i++)\n      {\n        m.addGenConstrIndicator(b[t][1], 1, MatrixMultiply(A2std, pos)[i], '<',\n                                b2[i]);  // If b[t,1]==1, then...\n      }\n      for (int i = 0; i < b3.rows(); i++)\n      {\n        m.addGenConstrIndicator(b[t][2], 1, MatrixMultiply(A3std, pos)[i], '<',\n                                b3[i]);  // If b[t,2]==1, then...\n      }\n    }\n    std::cout << \"here9\" << std::endl;\n\n    GRBQuadExpr control_cost = 0;\n    for (int t = 0; t < N; t++)\n    {\n      std::vector<GRBLinExpr> ut = { getJerk(t, 0, 0, false, x), getJerk(t, 0, 1, false, x),\n                                     getJerk(t, 0, 2, false, x) };\n      control_cost = control_cost + GetNorm2(ut);\n    }\n\n    std::cout << \"here10\" << std::endl;\n\n    /*    GRBQuadExpr final_state_cost = 0;\n        std::vector<GRBVar> xFinal = GetColumn(x, N);\n        // std::vector<GRBLinExpr> prueba = xFinal - xf;\n        final_state_cost = GetNorm2(xFinal - xf);\n        final_state_cost = q * final_state_cost;*/\n\n    m.setObjective(control_cost, GRB_MINIMIZE);\n\n    // Solve*/\n    m.update();\n    std::cout << \"here11\" << std::endl;\n    m.write(\"debug.lp\");\n    m.optimize();\n    std::cout << \"here12\" << std::endl;\n\n    std::cout << \"\\nOBJECTIVE: \" << m.get(GRB_DoubleAttr_ObjVal) << std::endl;\n    std::cout << \"Positions X:\" << std::endl;\n    for (int t = 0; t < N + 1; t++)\n    {\n      std::cout << getPos(t, 0, 0, true, x) << std::endl;\n    }\n  }\n\n  catch (GRBException e)\n  {\n    cout << \"Error code = \" << e.getErrorCode() << endl;\n    cout << e.getMessage() << endl;\n  }\n  /*catch (...)\n  {\n    cout << \"Exception during optimization\" << endl;\n  }*/\n\n  delete env;\n  return 0;\n}\n", "meta": {"hexsha": "5157ae7efd1dfc81e2279c007c9665372f33f8ed", "size": 17802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "faster/other/gurobi_continuous.cpp", "max_stars_repo_name": "wyr501/faster", "max_stars_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 489.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:22:55.000Z", "max_issues_repo_path": "faster/other/gurobi_continuous.cpp", "max_issues_repo_name": "wyr501/faster", "max_issues_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-05-08T13:51:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T07:43:21.000Z", "max_forks_repo_path": "faster/other/gurobi_continuous.cpp", "max_forks_repo_name": "wyr501/faster", "max_forks_repo_head_hexsha": "df92802a72b1e5d2acf0682d0772d14a56bf56ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 116.0, "max_forks_repo_forks_event_min_datetime": "2020-03-19T20:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T03:51:21.000Z", "avg_line_length": 35.1124260355, "max_line_length": 120, "alphanum_fraction": 0.4278732727, "num_tokens": 5499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5846530100227231}}
{"text": "#include <iostream>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n\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;\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\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    //std::cout << from << \" -> \" << to << \": capacity = \" << capacity << \", cost = \" << cost << std::endl;\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\nusing namespace std;\n\nstruct elephant {\n  int x, y, cost, capacity;\n};\n\n// Compute max flow min cost given a limit for the flow\ntuple<int, int> flowAndCost(int n, int start, int end, vector<elephant> &elephants, int flowLimit, int budget) {\n  graph G(n);\n  edge_adder 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 (auto e : elephants) {\n    adder.add_edge(e.x, e.y, e.capacity, e.cost);\n  }\n  \n  int source = boost::add_vertex(G);\n  int target = boost::add_vertex(G);\n  adder.add_edge(source, start, flowLimit, 0);\n  adder.add_edge(end, target, flowLimit, 0);\n\n  boost::successive_shortest_path_nonnegative_weights(G, source, target);\n  int flow = 0;\n  out_edge_it e, eend;\n  for(boost::tie(e, eend) = boost::out_edges(boost::vertex(source,G), G); e != eend; ++e) {\n      flow += c_map[*e] - rc_map[*e];     \n  }\n  int cost = boost::find_flow_cost(G);\n  return {flow, cost};\n}\n\n// Check if it is feasible to transport numSuitcases suitcases\nbool isFeasible(int n, int start, int end, vector<elephant> &elephants, int numSuitcases, int budget) {\n  int flow, cost;\n  tie(flow, cost) = flowAndCost(n, start, end, elephants, numSuitcases, budget);\n  \n  if (flow < numSuitcases) {\n    return false;\n  }\n  return cost <= budget;\n}\n\n// Strategy:\n// - Binary search to find largest feasible number\nvoid solve() {\n  int n, m, budget, start, end;\n  cin >> n >> m >> budget >> start >> end;\n  \n  int x, y, cost, capacity;\n  vector<elephant> elephants;\n  elephants.reserve(m);\n  for (int i = 0; i < m; ++i) {\n    cin >> x >> y >> cost >> capacity;\n    elephants.push_back({x, y, cost, capacity});\n  }\n  \n  // Find an upper bound (what is the max flow?)\n  int maxFlow = get<0>(flowAndCost(n, start, end, elephants, numeric_limits<int>::max(), budget));\n  \n  // Binary search for highest feasible number of elephants\n  int a = 0;\n  int b = maxFlow;\n  while (a != b) {\n    int m = a + (b - a + 1) / 2;\n    \n    if (isFeasible(n, start, end, elephants, m, budget)) {\n      a = m;\n    }\n    else {\n      b = m - 1;\n    }\n  }\n  \n  cout << a << 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": "62fd715845f1e8ae64387e6255f885390c8f563c", "size": 4050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/india.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/india.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/india.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": 31.1538461538, "max_line_length": 112, "alphanum_fraction": 0.6483950617, "num_tokens": 1156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5846529984838509}}
{"text": "#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <utility/include_all.h>\n#include <utility/iterator.h>\n#include <utility/math.h>\n#include <utility/unit_math.h>\n#include <vector>\n  \n\nauto generateHexGrid(float h, float r, bool center = true, float scale = 1.0f) {\n\tfloat H = h * kernelSize();\n\tauto gen_position = [&](auto r, int32_t i, int32_t j, int32_t k) {\n\t\tfloat4 initial{ 2.0f * i + ((j + k) % 2), sqrt(3.f) * (j + 1.0f / 3.0f * (k % 2)), 2.0f * sqrt(6.0f) / 3.0f * k, h / r };\n\t\treturn initial * r;\n\t};\n\tint32_t requiredSlices_x = (int32_t)math::ceilf(scale * H / r);\n\tint32_t requiredSlices_y = (int32_t)math::ceilf(scale * H / (sqrt(3.0f) * r));\n\tint32_t requiredSlices_z = (int32_t)math::ceilf(scale * H / r * 3.0f / (sqrt(6.0f) * 2.0f));\n\n\tstd::vector<float4> positions;\n\tfor (int32_t x_it = -requiredSlices_x; x_it <= requiredSlices_x; x_it++)\n\t\tfor (int32_t y_it = -requiredSlices_y; y_it <= requiredSlices_y; y_it++)\n\t\t\tfor (int32_t z_it = -requiredSlices_z; z_it <= requiredSlices_z; z_it++)\n\t\t\t\tif (center || (!center && (x_it != 0 || y_it != 0 || z_it != 0)))\n\t\t\t\t\tpositions.push_back(gen_position(r, x_it, y_it, z_it));\n\treturn positions;\n}\n#define CALC_CONSTANTS\n#ifdef CALC_CONSTANTS\nconstexpr auto volume = 1.f;\nauto radius = powf(volume, 1.f / 3.f) * PI4O3_1;\nauto h = support_from_volume(volume);\nauto H = h * kernelSize();\nauto getPacking() {\n\tint32_t it = 0;\n\tauto spacing = math::brentsMethod(\n\t\t[&](auto r) {\n\t\tauto positions = generateHexGrid(h, r, true, 1.0f);\n\t\tauto positionsL = generateHexGrid(h, r, true, 2.0f);\n\t\tfloat error = 0.0f;\n\t\tfor (const auto& pos : positions) {\n\t\t\tfloat density = -1.0f;\n\t\t\tfor (const auto& posL : positionsL)\n\t\t\t\tdensity += volume * spline4_kernel(posL, pos);\n\t\t\terror += density;\n\t\t}\n\t\tstd::cout << r << \"[\" << it++ << \"] -> \" << error << std::endl;\n\t\treturn error;\n\t},\n\t\tradius * 0.75f, radius * 8.0f, 1e-5f, 100);\n\treturn spacing;\n}\nauto spacing = getPacking();\n#else\nconstexpr auto H = 0x1.2487b0p+1f;\nconstexpr auto h = 0x1.407358p+0f;\nconstexpr auto r = 0x1.e8ec8ap-3f;\nconstexpr auto V = 0x1.000000p+0f;\nconstexpr auto s = 0x1.1ece3cp-1f;\n#endif\n\nconstexpr auto lutSize = 1024;\nconstexpr auto integralSize = 16*1024;\n\ntemplate<typename C>\nauto generateLUT(C&& func) {\n\tfloat4 c{ 0.f,0.f,0.f,h };\n\tusing res_t = double;// decltype(func(c, std::declval<float4>()));\n\tstd::array<res_t, lutSize> LUT;\n\tfloat dd = 2.f * H / ((float)lutSize - 1);\n\tfor (auto di = 0; di < lutSize; ++di) {\n\t\tauto n = integralSize;\n\t\tdouble dh = H / ((double)n);\n\t\tdouble d = H - dd * (double)(di);\n\n\t\tres_t integral = vector_t<double, math::dimension_v<res_t>>::zero();\n#pragma omp parallel for reduction(+ : integral)\n\t\tfor (auto ni = 0; ni < n; ++ni) {\n\t\t\tdouble xl = dh * (double)ni;\n\t\t\tdouble xh = dh * (double)ni + dh;\n\n\t\t\tfloat4 p{ (float) xl + 0.5f * (float)dh, 0.f, 0.f, h };\n\n\t\t\tdouble hl = math::clamp(xl - d, 0.f, 2.f * xl);\n\t\t\tdouble hh = math::clamp(xh - d, 0.f, 2.f * xh);\n\n\n\t\t\tdouble Vl = CUDART_PI_F * hl * hl / 3.f * (3.f * xl - hl);\n\t\t\tdouble Vh = CUDART_PI_F * hh * hh / 3.f * (3.f * xh - hh);\n\n\t\t\tdouble dV = Vh - Vl;\n\n\t\t\tintegral += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d) / H));\n\t\t}\n\t\tLUT[di] = integral;\n\t}\n\tstd::reverse(LUT.begin(), LUT.end());\n\treturn LUT;\n}\n\nconstexpr float t = 0.0001f;\ntemplate<typename C>\nauto gradientLUT(C&& func) {\n\tfloat4 c{ 0.f,0.f,0.f,h };\n\tusing res_t = double;// decltype(func(c, std::declval<float4>()));\n\tstd::array<res_t, lutSize> LUT;\n\tdouble dd = 2.f * H / ((double)lutSize - 1);\n\tfor (auto di = 0; di < lutSize; ++di) {\n\t\tconstexpr auto n = integralSize;\n\t\tdouble dh = H / ((double)n);\n\t\tdouble d = H - dd * (double)(di);\n\n\t\tres_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();\n#pragma omp parallel for reduction(+ : integralp)\n\t\tfor (auto ni = 0; ni < n; ++ni) {\n\t\t\tdouble xl = dh * (double)ni;\n\t\t\tdouble xh = dh * (double)ni + dh;\n\n\t\t\tfloat4 p{ (float) xl + 0.5f * (float) dh, 0.f, 0.f, h };\n\n\t\t\tdouble hl = math::clamp(xl - d + t, 0., 2. * xl);\n\t\t\tdouble hh = math::clamp(xh - d + t, 0., 2. * xh);\n\n\n\t\t\tdouble Vl = CUDART_PI * hl * hl / 3. * (3. * xl - hl);\n\t\t\tdouble Vh = CUDART_PI * hh * hh / 3. * (3. * xh - hh);\n\n\t\t\tdouble dV = Vh - Vl;\n\n\t\t\tintegralp += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d - t) / H));\n\t\t}\n\t\tres_t integraln = vector_t<double, math::dimension_v<res_t>>::zero();\n#pragma omp parallel for reduction(+ : integraln)\n\t\tfor (auto ni = 0; ni < n; ++ni) {\n\t\t\tdouble xl = dh * (double)ni;\n\t\t\tdouble xh = dh * (double)ni + dh;\n\n\t\t\tfloat4 p{ (float)xl + 0.5f * (float)dh , 0.f, 0.f, h };\n\n\t\t\tdouble hl = math::clamp(xl - d - t, 0., 2. * xl);\n\t\t\tdouble hh = math::clamp(xh - d - t, 0., 2. * xh);\n\n\n\t\t\tdouble Vl = CUDART_PI_F * hl * hl / 3. * (3. * xl - hl);\n\t\t\tdouble Vh = CUDART_PI_F * hh * hh / 3. * (3. * xh - hh);\n\n\t\t\tdouble dV = Vh - Vl;\n\n\t\t\tintegraln += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (p.x - d + t) / H));\n\t\t}\n\t\tLUT[di] = (integralp - integraln) / (2.0 * t);\n\t}\n\tstd::reverse(LUT.begin(), LUT.end());\n\treturn LUT;\n}\ntemplate<typename T>\nauto lookup (const std::array<T, lutSize> LUT, float x) {\n\tauto xRel = ((x + H) / (2.f * H)) * ((float)lutSize - 1.f);\n\tauto xL = math::floorf(xRel);\n\tauto xH = math::ceilf(xRel);\n\tauto xD = xRel - xL;\n\tint32_t xLi = math::clamp(static_cast<int32_t>(xL), 0, lutSize - 1);\n\tint32_t xHi = math::clamp(static_cast<int32_t>(xH), 0, lutSize - 1);\n\tauto lL = LUT[xLi];\n\tauto lH = LUT[xHi];\n\treturn lL * xD + (1.f - xD) * lH;\n};\n\n#include <config/config.h>\n#include <fstream>\n#ifdef _WIN32\n#include <experimental/filesystem>\nnamespace fs = std::experimental::filesystem;\n#else\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n#endif\n \n\nauto writeLUT(const std::string& name, const std::string& type, const std::array<double, lutSize>& LUT) {\n\tfs::path bin_dir(sourceDirectory);\n\tauto file = bin_dir / \"cfg\" / name;\n\tfile.replace_extension(\"lut\");\n\n\tif (fs::exists(file)) {\n\t\tif (fs::exists(__FILE__)) {\n\t\t\tauto input_ts = fs::last_write_time(__FILE__);\n\t\t\tauto output_ts = fs::last_write_time(file);\n\t\t\tif (input_ts <= output_ts) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"Writing \" << file.string() << std::endl;\n\n\tstd::ofstream output(file.string());\n\t//output << \"std::vector<\" << type << \"> \" << name << \"{ \";\n\tint32_t ctr = 0;\n\tfor (auto v : LUT) {\n\t\toutput << std::scientific << std::setprecision(std::numeric_limits<float>::digits10 + 1)\n\t\t\t<< static_cast<float>(v) << \" \";\n\t}\n\t//output << \"};\" << std::endl;\n\toutput.close();\n}\n\nauto sphericalGradientIntegral(const std::function<double(float4, float4, float)>& func, int32_t phiSlices, int32_t thetaSlices, int32_t radiusSteps) {\n\tfloat4 c{ 0.f,0.f,0.f,h };\n\tusing res_t = double;\n\tstd::array<res_t, lutSize> LUT;\n\tdouble dd = 2.f * H / ((double)lutSize - 1);\n\tfor (auto di = 0; di < lutSize; ++di) {\n\t\tauto n = radiusSteps;\n\t\tdouble dh = H / ((double)n);\n\t\tdouble d = H - dd * (double)(di);\n\t\tdouble dTheta = (2.0 * CUDART_PI) / (double)thetaSlices;\n\t\tdouble dPhi = (CUDART_PI) / (double)phiSlices;\n\n\t\tres_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();\n#pragma omp parallel for\n\t\tfor (auto iR = 0; iR < radiusSteps; ++iR) {\n\t\t\tdouble xl = dh * (double)iR;\n\t\t\tdouble xh = dh * (double)iR + dh;\n\t\t\tfloat r = (float) xl + 0.5f * (float)dh;\n\t\t\tdouble Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;\n\t\t\tdouble Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;\n\n\t\t\tdouble dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;\n\t\t\tres_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\tfor (auto iTheta = 0.0; iTheta < 2.0 * CUDART_PI; iTheta += dTheta) {\n\t\t\t\tres_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\t\tfor (auto iPhi = 0.0; iPhi < CUDART_PI; iPhi += dPhi) {\n\t\t\t\t\tdouble theta = iTheta + dTheta * 0.5;\n\t\t\t\t\tdouble phi = iPhi + dPhi * 0.5;\n\t\t\t\t\tdouble x = r * cos(theta) * sin(phi);\n\t\t\t\t\tdouble y = r * sin(theta) * sin(phi);\n\t\t\t\t\tdouble z = r * cos(phi);\n\t\t\t\t\tif (x < d + t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfloat4 p{ (float)x, (float)y, (float)z, h };\n\t\t\t\t\tphiSum += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, d + t));\n\t\t\t\t}\n\t\t\t\tthetaSum += phiSum;\n\t\t\t}\n\t\t\tintegralp += thetaSum;\n\t\t}\n\t\tres_t integraln = vector_t<double, math::dimension_v<res_t>>::zero();\n#pragma omp parallel for\n\t\tfor (auto iR = 0; iR < radiusSteps; ++iR) {\n\t\t\tdouble xl = dh * (double)iR;\n\t\t\tdouble xh = dh * (double)iR + dh;\n\t\t\tfloat r = (float)xl + 0.5f * (float)dh;\n\t\t\tdouble Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;\n\t\t\tdouble Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;\n\n\t\t\tdouble dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;\n\t\t\tres_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\tfor (auto iTheta = 0.0; iTheta < 2.0 * CUDART_PI; iTheta += dTheta) {\n\t\t\t\tres_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\t\tfor (auto iPhi = 0.0; iPhi < CUDART_PI; iPhi += dPhi) {\n\t\t\t\t\tdouble theta = iTheta + dTheta * 0.5;\n\t\t\t\t\tdouble phi = iPhi + dPhi * 0.5;\n\t\t\t\t\tdouble x = r * cos(theta) * sin(phi);\n\t\t\t\t\tdouble y = r * sin(theta) * sin(phi);\n\t\t\t\t\tdouble z = r * cos(phi);\n\t\t\t\t\tif (x < d - t)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfloat4 p{ (float)x, (float)y, (float)z, h };\n\t\t\t\t\tphiSum += dV * math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, d - t));\n\t\t\t\t}\n\t\t\t\tthetaSum += phiSum;\n\t\t\t}\n\t\t\tintegraln += thetaSum;\n\t\t}\n\t\tLUT[di] = (integralp - integraln) / (2.0 * t);\n\t}\n\tstd::reverse(LUT.begin(), LUT.end());\n\treturn LUT;\n}\n\nvoid progressBar(int32_t frame, int32_t frameTarget, float progress) {\n\tstd::ios cout_state(nullptr);\n\tcout_state.copyfmt(std::cout);\n\tstatic auto startOverall = std::chrono::high_resolution_clock::now();\n\tstatic auto startFrame = startOverall;\n\tstatic auto lastTime = startOverall;\n\tstatic int32_t lastFrame = frame;\n\t//if (frame != lastFrame) {\n\t//\tlastFrame = frame;\n\tif(frame == 0)\n\t\tstartFrame = std::chrono::high_resolution_clock::now();\n\t//}\n\tauto now = std::chrono::high_resolution_clock::now();\n\tlastTime = now;\n\tint barWidth = 128;\n\tstd::cout << \"Generating \" << std::setw(4) << frame;\n\tif (frameTarget != -1)\n\t\tstd::cout << \"/\" << std::setw(4) << frameTarget;\n\tstd::cout << \" [\";\n\tint pos = barWidth * progress;\n\tfor (int i = 0; i < barWidth; ++i) {\n\t\tif (i < pos) std::cout << \"=\";\n\t\telse if (i == pos) std::cout << \">\";\n\t\telse std::cout << \" \";\n\t}\n\tstd::cout << \"] \" << std::setw(3) << int(progress * 100.0) << \" \";\n\tauto dur = std::chrono::duration_cast<std::chrono::milliseconds>(now - startFrame);\n\tif (dur.count() < 100 || progress < 1e-3f) {\n\t\tstd::cout << \" ---/---s  \";\n\t}\n\telse {\n\t\tauto totalTime = ((float)std::chrono::duration_cast<std::chrono::microseconds>(now - startFrame).count()) / 1000.f / 1000.f;\n\t\tstd::cout << std::fixed << std::setprecision(0) << \" \" << std::setw(3) << totalTime << \"/\" << std::setw(3) << (totalTime / progress) << \"s  \";\n\t}\n\tstd::cout << \"\\r\";\n\tstd::cout.flush();\n\tstd::cout.copyfmt(cout_state);\n}\n\nauto sphericalIntegral(const std::function<double(float4, float4, float)>& func, int32_t phiSlices, int32_t thetaSlices, int32_t radiusSteps) {\n\tfloat4 c{ 0.f,0.f,0.f,h };\n\tusing res_t = double;\n\tstd::array<res_t, lutSize> LUT;\n\tdouble dd = 2.f * H / ((double)lutSize - 1);\n\t//std::vector<double> thetaSum(thetaSlices);\n\t//std::vector<double> phiSum(phiSlices);\n\tfor (auto di = 0; di < lutSize; ++di) {\n\t\tprogressBar(di, lutSize, (double)di / (double)lutSize);\n\t\tauto n = radiusSteps;\n\t\tdouble dh = H / ((double)n);\n\t\tdouble d = -H + dd * (double)(di);\n\t\tdouble dTheta = (2.0 * CUDART_PI) / (double)thetaSlices;\n\t\tdouble dPhi = (CUDART_PI) / (double)phiSlices;\n\n\t\tres_t integralp = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\tdouble dVSum = 0.0;\n#pragma omp parallel for\n\t\tfor (auto iR = 0; iR < radiusSteps; ++iR) {\n\t\t\tdouble xl = dh * (double)iR;\n\t\t\tdouble xh = dh * (double)iR + dh;\n\t\t\tfloat r = (float)xl + 0.5f * (float)dh;\n\t\t\tdouble Vl = 4.0 / 3.0 * CUDART_PI * xl * xl * xl;\n\t\t\tdouble Vh = 4.0 / 3.0 * CUDART_PI * xh * xh * xh;\n\n\t\t\tdouble dV = (Vh - Vl) / (double)thetaSlices / (double)phiSlices;\n\t\t\tres_t thetaSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\tfor (auto iTheta = 0; iTheta < thetaSlices; iTheta++) {\n\t\t\t\tres_t phiSum = vector_t<double, math::dimension_v<res_t>>::zero();\n\t\t\t\tfor (auto iPhi = 0; iPhi < phiSlices; iPhi++) {\n\t\t\t\t\tdouble theta = ((double)iTheta) * dTheta;// +dTheta * 0.5;\n\t\t\t\t\tdouble phi = ((double)iPhi) * dPhi;// +dPhi * 0.5;\n\t\t\t\t\tdouble x = r * cos(theta) * sin(phi);\n\t\t\t\t\tdouble y = r * sin(theta) * sin(phi);\n\t\t\t\t\tdouble z = r * cos(phi);\n\t\t\t\t\tif (x < d)\n\t\t\t\t\t\tphiSum += 0.0;\n\t\t\t\t\telse {\n\t\t\t\t\t\tfloat4 p{ (float)x, (float)y, (float)z, h };\n\t\t\t\t\t\tphiSum += math::castTo<typename vector_t<double, math::dimension_v<res_t>>::type>(func(c, p, (x - d) / (1.0 * H)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//std::sort(phiSum.begin(), phiSum.end());\n\t\t\t\tthetaSum += phiSum;\n\t\t\t}\n\t\t\t//std::sort(thetaSum.begin(), thetaSum.end());\n\t\t\t//integralp += dV * std::reduce(thetaSum.begin(), thetaSum.end());\n\t\t\tintegralp += dV * thetaSum;\n\t\t}\n\t\tLUT[di] = integralp;\n\t\t//break;\n\t}\n\tstd::cout << std::endl;\n\t//std::reverse(LUT.begin(), LUT.end());\n\treturn LUT;\n}\n\nauto approximateGradient(const std::array<double, lutSize>& LUT, const std::array<double, lutSize>& vLUT) {\n\tstd::array<double, lutSize> gLUT;\n\tfor (auto& e : gLUT) e = 0.0;\n\tfor (int32_t i = 0; i < lutSize - 1; ++i) {\n\t\tauto vi1 = 1.f; //vLUT[i + 1];\n\t\tauto vi = 1.f; //vLUT[i];\n\t\tvi1 = vi1 < 1e-5f ? vi : vi1;\n\n\t\tgLUT[i] = (LUT[i + 1] / vi1 - LUT[i] / vi) / (2.0 * H / (double)lutSize) * vi;\n\t}\n\tgLUT[lutSize - 1] = gLUT[lutSize - 2];\n\treturn gLUT;\n}\n\nauto smoothLUT(const std::array<double, lutSize>& LUT) {\n\tstd::array<double, lutSize> gLUT;\n\tgLUT = LUT;\n\tfor (int32_t i = 1; i < lutSize - 1; ++i) {\n\t\tif(LUT[i-1] < LUT[i])\n\t\t\tgLUT[i] = (LUT[i - 1] + LUT[i + 1])*0.5;\n\t}\n\treturn gLUT;\n}\n \n#include <omp.h>\nint main(int32_t argc, char** argv) {\n\tomp_set_num_threads(12);\n#ifdef CALC_CONSTANTS\n\tstd::ios cout_state(nullptr);\n\tcout_state.copyfmt(std::cout);\n\tstd::cout << std::hexfloat << \"H = \" << H << std::endl;\n\tstd::cout << std::hexfloat << \"h = \" << h << std::endl;\n\tstd::cout << std::hexfloat << \"radius = \" << radius << std::endl;\n\tstd::cout << std::hexfloat << \"volume = \" << volume << std::endl;\n\tstd::cout << std::hexfloat << \"spacing = \" << spacing << std::endl;\n\tstd::cout.copyfmt(cout_state);\n\tstd::cout << \"H = \" << H << std::endl;\n\tstd::cout << \"h = \" << h << std::endl;\n\tstd::cout << \"radius = \" << radius << std::endl;\n\tstd::cout << \"volume = \" << volume << std::endl;\n\tstd::cout << \"spacing = \" << spacing << std::endl;\n\tstd::cout.copyfmt(cout_state);\n#endif\n\tstd::cout << \"Running LUT generation code.\" << std::endl;\n//#ifdef WIN32\n//\tHWND console = GetConsoleWindow();\n//\tRECT _r;\n//\tGetWindowRect(console, &_r);\n//\tMoveWindow(console, 0, 0, 1920, 1200, TRUE);\n//#endif\n\t//std::cout << \"H = \" << H << std::endl;\n\t//std::cout << \"h = \" << h << std::endl;\n\t//std::cout << \"radius = \" << r << std::endl;\n\t//std::cout << \"volume = \" << V << std::endl;\n\t//std::cout << \"spacing = \" << s << std::endl;\n\n\t//std::cout << \"Spherical Integral: \" <<  << std::endl;\n\t//std::cout << \"Analytical: \" << CUDART_PI * 4.0 / 3.0 * H * H * H << std::endl;\n\n\t//std::array densityLUT = sphericalIntegral([](float4 c, float4 p, float d) {return kernel(c, p); }, 128, 128, 128);\n\t//std::cout << \"Generated density LUT\" << std::endl;\n\tfloat dFactor = 0.f;// 0.f;// 1.5f; \n\tstd::array densityLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * kernel(c, p); });\n\twriteLUT(\"density\", \"float\", densityLUT);\n\n\tauto lookup = [&](auto x) {\n\t\tfloat xRel = ((x + 1.f) / 2.f)* ((float)lutSize - 1.f);\n\t\tauto xL = math::floorf(xRel);\n\t\tauto xH = math::ceilf(xRel);\n\t\tauto xD = xRel - xL;\n\t\tint32_t xLi = math::clamp(static_cast<int32_t>(xL), 0, lutSize - 1);\n\t\tint32_t xHi = math::clamp(static_cast<int32_t>(xH), 0, lutSize - 1);\n\t\tauto lL = densityLUT[xLi];\n\t\tauto lH = densityLUT[xHi];\n\t\tauto val = lL * xD + (1.f - xD) * lH;\n\t\treturn val;\n\t};\n\n\tauto findX = [&](auto x) {\n\t\tfloat f = -1.f;\n\t\tint32_t n = 8;\n\t\tfor (int32_t n = 1; n < 11; ++n) {\n\t\t\tauto fx = lookup(f);\n\t\t\t//std::cout << \"Starting at \" << f << \" : \" << fx << \" with dx = \" << powf(0.5f, (float)n) << std::endl;\n\t\t\twhile (n % 2 == 1 ? fx > x + 0.001f : fx < x - 0.001f){\n\t\t\t\tf += (n % 2 == 1 ? 1.f : -1.f) * powf(0.5f, (float)n);\n\t\t\t\tfx = lookup(f);\n\t\t\t\t//std::cout << f << \" -> \" << fx << std::endl;\n\t\t\t}\n\t\t}\n\t\t//std::cout << f << \" - \" << lookup(f) << \" <-> \" << x << std::endl;\n\t\treturn f;\n\t};\n\tstd::array<double, lutSize> offsetLUT; \n\tfor (int32_t i = 0; i < lutSize; ++i) {\n\t\tfloat f = (float) i / (float)lutSize;\n\t\toffsetLUT[i] = /*0.24509788f*/ -0.f* findX(f);\n\t}\n\t//std::reverse(offsetLUT.begin(), offsetLUT.end());\n\twriteLUT(\"offsetLUT\", \"float\", offsetLUT);\n\t//findX(0.5f);\n\n\tstd::array spline2LUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * (1.f + dFactor * d) *  math::dot3(gradient(c, p), gradient(c, p)); });\n\twriteLUT(\"spline2\", \"float\", spline2LUT);\n\tstd::array spikyLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) * PressureKernel<kernel_kind::spline4>::value(c,p); });\n\twriteLUT(\"spiky\", \"float\", spikyLUT);\n\tstd::array splineLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) *  kernel(c, p); });\n\twriteLUT(\"spline\", \"float\", splineLUT);\n\tstd::array cohesionLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) *  Kernel<kernel_kind::cohesion>::value(c, p).x; });\n\tfor (int32_t i = 1; i < cohesionLUT.size(); ++i) {\n\t\tcohesionLUT[i] = abs(cohesionLUT[i]) < 1e-12 ? cohesionLUT[i - 1] : cohesionLUT[i];\n\t}\n\twriteLUT(\"cohesion\", \"float\", cohesionLUT);\n\tstd::array adhesionLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d) *  Kernel<kernel_kind::adhesion>::value(c, p).x; });\n\tfor (int32_t i = 1; i < adhesionLUT.size(); ++i) {\n\t\tadhesionLUT[i] = abs(adhesionLUT[i]) < 1e-12 ? adhesionLUT[i - 1] : adhesionLUT[i];\n\t}\n\twriteLUT(\"adhesion\", \"float\", adhesionLUT);\n\n\tstd::array volumeLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f + dFactor * d); });\n\t//for (auto& v : volumeLUT)\n\t//\tv = 1.f;\n\twriteLUT(\"volume\", \"float\", volumeLUT);\n\n\t////std::cout << adhesion0  << std::endl;\n\t//std::array spikyGradientLUT = generateLUT([&](float4 c, float4 p, float d) { \n\t//\treturn -((1.f + dFactor * d) *  SpikyKernel<kernel_kind::spline4>::gradient(c, p).x); });\n\n\tstd::array spikyGradientLUT = approximateGradient(spikyLUT, volumeLUT);\n\tfor (int32_t i = 1; i < spikyGradientLUT.size(); ++i) {\n\t\t//spikyGradientLUT[i] = fabsf(spikyGradientLUT[i]) < 1e-12f ? spikyGradientLUT[i - 1] : spikyGradientLUT[i];\n\t}\n\t//std::array spikyGradientLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f) * SpikyKernel<kernel_kind::spline4>::gradient(c, p).x ; });\n\t//for (auto& v : spikyGradientLUT)\n\t\t//v = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);\n\twriteLUT(\"spikyGradient\", \"float\", spikyGradientLUT);\n\tstd::array splineGradientLUT = approximateGradient(splineLUT, volumeLUT);\n\tfor (int32_t i = 1; i < splineGradientLUT.size(); ++i) {\n\t\t//splineGradientLUT[i] = fabsf(splineGradientLUT[i]) < 1e-12f ? splineGradientLUT[i - 1] : splineGradientLUT[i];\n\t}\n\t//std::array splineGradientLUT = generateLUT([&](float4 c, float4 p, float d) { return (1.f ) * gradient(c, p).x;  });\n\t//for (auto& v : splineGradientLUT)\n\t//\tv = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);\n\twriteLUT(\"splineGradient\", \"float\", splineGradientLUT);\n\t\n\t//std::array densityLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return kernel(c, p); }, 127, 127, 127);\n\tauto chi = [&](auto d) {\n\t\treturn 1.f + dFactor * d;\n\t\t//return math::clamp(1.0 / lookup(densityLUT, -d * HforV1) + d,1.0,4.0);\n\t};\n\t//densityLUT = smoothLUT(densityLUT);\n\t//std::cout << \"Generated density LUT\" << std::endl;\n\t//writeLUT(\"density\", \"float\", densityLUT);\n\n\t//std::array splineLUTN = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * kernel(c, p); }, 127, 127, 127);\n\t//splineLUTN = smoothLUT(splineLUTN);\n\t//std::cout << \"Generated spline LUT\" << std::endl;\n\t//writeLUT(\"splinePolar\", \"float\", splineLUTN);\n\t//std::array splineGradientLUTN = approximateGradient(splineLUTN);\n\t//std::cout << \"Generated spline Gradient LUT\" << std::endl;\n\t//writeLUT(\"splineGradientPolar\", \"float\", splineGradientLUTN);\n\n\n\t//std::array spikyLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * SpikyKernel<kernel_kind::spline4>::value(c, p); }, 128, 128, 128);\n\t//spikyLUT = smoothLUT(spikyLUT);\n\t//std::cout << \"Generated spiky LUT\" << std::endl;\n\t//writeLUT(\"spiky\", \"float\", spikyLUT);\n\t//std::array spikyGradientLUT = approximateGradient(spikyLUT);\n\t//std::cout << \"Generated spiky Gradient LUT\" << std::endl;\n\t//writeLUT(\"spikyGradient\", \"float\", spikyGradientLUT);\n\t//std::array cohesionLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * Kernel<kernel_kind::cohesion>::value(c, p).x; }, 128, 128, 128);\n\t//std::cout << \"Generated cohesion LUT\" << std::endl;\n\t//writeLUT(\"cohesion\", \"float\", cohesionLUT);\n\t//std::array adhesionLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return chi(d) * Kernel<kernel_kind::adhesion>::value(c, p).x; }, 128, 128, 128);\n\t//auto adhesion0 = lookup(adhesionLUT, -HforV1);\n\t//for (auto& v : adhesionLUT)\n\t//\tv /= adhesion0;\n\t//std::cout << \"Generated adhesion LUT\" << std::endl;\n\t//writeLUT(\"adhesion\", \"float\", adhesionLUT);\n\t//std::array volumeLUT = sphericalIntegral([&](float4 c, float4 p, float d) {return 1.0; }, 128, 128, 128);\n\t//std::cout << \"Generated volume LUT\" << std::endl;\n\t//writeLUT(\"volume\", \"float\", volumeLUT);\n\n\n\t//float dh = 0.001f;\n\t//float4 dx{ dh,0.f,0.f,0.f };\n\t//float4 dy{ 0.f,dh,0.f,0.f };\n\t//float4 dz{ 0.f,0.f,dh,0.f };\n\n\t//std::array spikyLUT = generateLUT([&](float4 c, float4 p) { return SpikyKernel<kernel_kind::spline4>::value(c, p); });\n\t//std::array splineLUT = generateLUT([&](float4 c, float4 p) { return kernel(c, p); });\n\t//std::array cohesionLUT = generateLUT([&](float4 c, float4 p) { return Kernel<kernel_kind::cohesion>::value(c, p).x; });\n\t//std::array adhesionLUT = generateLUT([&](float4 c, float4 p) { return Kernel<kernel_kind::adhesion>::value(c, p).x; });\n\t//std::array spikyGradientLUT = gradientLUT([&](float4 c, float4 p) { return SpikyKernel<kernel_kind::spline4>::value(c, p); });\n\t//std::array splineGradientLUT = gradientLUT([&](float4 c, float4 p) { return kernel(c, p); });\n\t//std::array volumeLUT = gradientLUT([&](float4 c, float4 p) { return 1.f; });\n\n\t//for (int32_t i = 0; i < lutSize; ++i) {\n\t//\tstd::cout << i << \"\\t\" << splineLUT[i] << \" - \" << splineLUT2[i] << \" -> \" << splineLUT[i] / splineLUT2[i] << std::endl;\n\t//}\n\n\t//for (float x = -H; x <= H; x += H / 16.f) {\n\t//\tstd::cout << x << \"\\t\" << lookup(splineLUT, x) << \" @ \" << lookup(splineLUT2, x) << std::endl;\n\t//}\n\n\t//for (float x = -H; x <= H; x += H / 16.f) {\n\t//\tstd::cout << x << \"\\t\" << lookup(splineLUT, x) << \" @ \" << lookup(splineGradientLUT, x) << \" -> \" << lookup(splineLUT, x + dh) << \" : \" << lookup(splineLUT, x) + dh * lookup(splineGradientLUT, x) << std::endl;\n\t//}\n\n\t//for (auto& v : splineGradientLUT)\n\t//\tv = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);\n\t//for (auto& v : spikyGradientLUT)\n\t//\tv = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);\n\t//for (auto& v : cohesionLUT)\n\t//\tv = -v;// math::max(std::decay_t<decltype(v)>{0.f}, v);\n\t////std::cout << adhesion0  << std::endl;\n\n\n\t//auto x0 = lookup(splineLUT, 0.0f);\n\t//auto xp = lookup(splineLUT, 0.0f + t);\n\t//auto xn = lookup(splineLUT, 0.0f - t);\n\t//auto xnum = (xp - xn) / (2.f * t);\n\t//auto xint = lookup(splineGradientLUT, 0.f);\n\t//std::cout << x0 << \" -> \" << xp << std::endl;\n\t//std::cout << xnum << \" <-> \" << xint << std::endl;\n\t\n\t//float evalP = 0.f * H;\n\t//std::cout << \"Spherical integral\" << std::endl;\n\t//std::cout << \"Kernel:   \" << lookup(splineLUT, evalP) << std::endl;\n\t//std::cout << \"Gradient: \" << lookup(splineGradientLUT, evalP) << std::endl;\n\n\t//float4 c{ 0.f,0.f,0.f,h };\n\t//double sumd = 0.0;\n\t//double4 gradSumd{ 0.0,0.0,0.0,0.0 };\n\t//double volume = 0.f;\n\t//constexpr auto trapz = 512;\n\t//constexpr auto dt = 2.0 * (double) H / ((double)trapz);\n\t//constexpr auto dV = dt * dt * dt;\n\t//auto trapH = support_from_volume(dV);\n\t//for (int32_t xi = -trapz / 2; xi <= trapz / 2; ++xi) {\n\t//\tfor (int32_t yi = -trapz / 2; yi <= trapz / 2; ++yi) {\n\t//\t\tfor (int32_t zi = -trapz / 2; zi <= trapz / 2; ++zi) {\n\t//\t\t\tfloat4 p{ (float)dt * (float)xi, (float)dt * (float)yi, (float)dt * (float)zi, h };\n\t//\t\t\tif (p.x > evalP)\n\t//\t\t\t\tcontinue;\n\t//\t\t\tsumd += (double) kernel(c, p) * dV;\n\t//\t\t\tgradSumd += math::castTo<double4>(gradient(c, p)) * dV;\n\t//\t\t\tvolume += kernel(c, p) > 0.f ? dV : 0.f;\n\t//\t\t}\n\t//\t}\n\t//}\n\t//std::cout << \"Trapz\" << std::endl;\n\t//std::cout << \"Kernel:   \" << sumd << std::endl;\n\t//std::cout << \"Gradient: \" << gradSumd << std::endl;\n\n\t//getchar();\n}", "meta": {"hexsha": "7f23ee5d6d84335ad36da8fef4b5498ed843f80a", "size": 25075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metaCode/LUTCode2/Source.cpp", "max_stars_repo_name": "chenjiunfeng/openMaelstrom", "max_stars_repo_head_hexsha": "6dc6ffe3501f056eb83d1d6306d2ac5ec754c192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T13:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:51:14.000Z", "max_issues_repo_path": "metaCode/LUTCode2/Source.cpp", "max_issues_repo_name": "chenjiunfeng/openMaelstrom", "max_issues_repo_head_hexsha": "6dc6ffe3501f056eb83d1d6306d2ac5ec754c192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-06T20:25:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-07T21:45:39.000Z", "max_forks_repo_path": "metaCode/LUTCode2/Source.cpp", "max_forks_repo_name": "chenjiunfeng/openMaelstrom", "max_forks_repo_head_hexsha": "6dc6ffe3501f056eb83d1d6306d2ac5ec754c192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T09:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T07:04:55.000Z", "avg_line_length": 39.4261006289, "max_line_length": 213, "alphanum_fraction": 0.6011565304, "num_tokens": 9115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5845393291238441}}
{"text": "/*\n\tCopyright (C) 2003-2014 by David White <davewx7@gmail.com>\n\t\n\tThis software is provided 'as-is', without any express or implied\n\twarranty. In no event will the authors be held liable for any damages\n\tarising from the use of this software.\n\n\tPermission is granted to anyone to use this software for any purpose,\n\tincluding commercial applications, and to alter it and redistribute it\n\tfreely, subject to the following restrictions:\n\n\t   1. The origin of this software must not be misrepresented; you must not\n\t   claim that you wrote the original software. If you use this software\n\t   in a product, an acknowledgement in the product documentation would be\n\t   appreciated but is not required.\n\n\t   2. Altered source versions must be plainly marked as such, and must not be\n\t   misrepresented as being the original software.\n\n\t   3. This notice may not be removed or altered from any source\n\t   distribution.\n*/\n\n#pragma once\n\n#include <boost/math/special_functions/round.hpp>\n\n#include \"geometry.hpp\"\n\ntemplate<typename T>\ngeometry::Point<T> rotate_point_around_origin(T x1, T y1, float alpha, bool round)\n{\n\tgeometry::Point<T> beta;\n\n\t/*   //we actually don't need the initial theta and radius.  This is why:\n\tx2 = R * (cos(theta) * cos(alpha) + sin(theta) * sin(alpha))\n\ty2 = R * (sin(theta) * cos(alpha) + cos(theta) * sin(alpha));\n\tbut\n\tR * (cos(theta)) = x1\n\tR * (sin(theta)) = x2\n\tthis collapses the above to:  */\n\n\tfloat c1 = x1 * cos(alpha) - y1 * sin(alpha);\n\tfloat c2 = y1 * cos(alpha) + x1 * sin(alpha);\n\n\tbeta.x = static_cast<T>(round ? boost::math::round(c1) : c1);\n\tbeta.y = static_cast<T>(round ? boost::math::round(c2) : c2);\n\n\treturn beta;\n}\n\ntemplate<typename T>\ngeometry::Point<T> rotate_point_around_origin_with_offset(T x1, T y1, float alpha, T u1, T v1, bool round=true)\n{\n\tgeometry::Point<T> beta = rotate_point_around_origin(x1 - u1, y1 - v1, alpha, round);\n\n\tbeta.x += u1;\n\tbeta.y += v1;\n\n\treturn beta;\n}\n\nvoid rotate_rect(short center_x, short center_y, float rotation, short* rect_vertexes);\nvoid rotate_rect(float center_x, float center_y, float rotation, float* rect_vertexes);\nvoid rotate_rect(const rect& r, float angle, short* output);\n", "meta": {"hexsha": "82b263cacc72e39d4cb47fa98abddc01e108cb3e", "size": 2172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rectangle_rotator.hpp", "max_stars_repo_name": "gamobink/anura", "max_stars_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rectangle_rotator.hpp", "max_issues_repo_name": "gamobink/anura", "max_issues_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rectangle_rotator.hpp", "max_forks_repo_name": "gamobink/anura", "max_forks_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "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": 32.9090909091, "max_line_length": 111, "alphanum_fraction": 0.7182320442, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5845171827452371}}
{"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    Rot3M.cpp\n * @brief   Rotation (internal: 3*3 matrix representation*)\n * @author  Alireza Fathi\n * @author  Christian Potthast\n * @author  Frank Dellaert\n * @author  Richard Roberts\n */\n\n#include <gtsam/config.h> // Get GTSAM_USE_QUATERNIONS macro\n\n#ifndef GTSAM_USE_QUATERNIONS\n\n#include <gtsam/geometry/Rot3.h>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\nstatic const Matrix3 I3 = Matrix3::Identity();\n\n/* ************************************************************************* */\nRot3::Rot3() : rot_(Matrix3::Identity()) {}\n\n/* ************************************************************************* */\nRot3::Rot3(const Point3& col1, const Point3& col2, const Point3& col3) {\n  rot_.col(0) = col1.vector();\n  rot_.col(1) = col2.vector();\n  rot_.col(2) = col3.vector();\n}\n\n/* ************************************************************************* */\nRot3::Rot3(double R11, double R12, double R13,\n    double R21, double R22, double R23,\n    double R31, double R32, double R33) {\n    rot_ << R11, R12, R13,\n        R21, R22, R23,\n        R31, R32, R33;\n}\n\n/* ************************************************************************* */\nRot3::Rot3(const Matrix3& R) {\n  rot_ = R;\n}\n\n/* ************************************************************************* */\nRot3::Rot3(const Matrix& R) {\n  if (R.rows()!=3 || R.cols()!=3)\n    throw invalid_argument(\"Rot3 constructor expects 3*3 matrix\");\n  rot_ = R;\n}\n\n///* ************************************************************************* */\n//Rot3::Rot3(const Matrix3& R) : rot_(R) {}\n\n/* ************************************************************************* */\nRot3::Rot3(const Quaternion& q) : rot_(q.toRotationMatrix()) {}\n\n/* ************************************************************************* */\nRot3 Rot3::Rx(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      1,  0,  0,\n      0, ct,-st,\n      0, st, ct);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Ry(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      ct, 0, st,\n      0, 1,  0,\n      -st, 0, ct);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Rz(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      ct,-st, 0,\n      st, ct, 0,\n      0,  0, 1);\n}\n\n/* ************************************************************************* */\n// Considerably faster than composing matrices above !\nRot3 Rot3::RzRyRx(double x, double y, double z) {\n  double cx=cos(x),sx=sin(x);\n  double cy=cos(y),sy=sin(y);\n  double cz=cos(z),sz=sin(z);\n  double ss_ = sx * sy;\n  double cs_ = cx * sy;\n  double sc_ = sx * cy;\n  double cc_ = cx * cy;\n  double c_s = cx * sz;\n  double s_s = sx * sz;\n  double _cs = cy * sz;\n  double _cc = cy * cz;\n  double s_c = sx * cz;\n  double c_c = cx * cz;\n  double ssc = ss_ * cz, csc = cs_ * cz, sss = ss_ * sz, css = cs_ * sz;\n  return Rot3(\n      _cc,- c_s + ssc,  s_s + csc,\n      _cs,  c_c + sss, -s_c + css,\n      -sy,        sc_,        cc_\n  );\n}\n\n/* ************************************************************************* */\nRot3 Rot3::rodriguez(const Vector& w, double theta) {\n  // get components of axis \\omega\n  double wx = w(0), wy=w(1), wz=w(2);\n  double wwTxx = wx*wx, wwTyy = wy*wy, wwTzz = wz*wz;\n#ifndef NDEBUG\n  double l_n = wwTxx + wwTyy + wwTzz;\n  if (std::abs(l_n-1.0)>1e-9) throw domain_error(\"rodriguez: length of n should be 1\");\n#endif\n\n  double c = cos(theta), s = sin(theta), c_1 = 1 - c;\n\n  double swx = wx * s, swy = wy * s, swz = wz * s;\n  double C00 = c_1*wwTxx, C01 = c_1*wx*wy, C02 = c_1*wx*wz;\n  double                  C11 = c_1*wwTyy, C12 = c_1*wy*wz;\n  double                                   C22 = c_1*wwTzz;\n\n  return Rot3(\n        c + C00, -swz + C01,  swy + C02,\n      swz + C01,    c + C11, -swx + C12,\n     -swy + C02,  swx + C12,    c + C22);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::compose (const Rot3& R2,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  if (H1) *H1 = R2.transpose();\n  if (H2) *H2 = I3;\n  return *this * R2;\n}\n\n/* ************************************************************************* */\nRot3 Rot3::operator*(const Rot3& R2) const {\n  return Rot3(Matrix3(rot_*R2.rot_));\n}\n\n/* ************************************************************************* */\nRot3 Rot3::inverse(boost::optional<Matrix&> H1) const {\n  if (H1) *H1 = -rot_;\n  return Rot3(Matrix3(rot_.transpose()));\n}\n\n/* ************************************************************************* */\nRot3 Rot3::between (const Rot3& R2,\n    boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n  if (H1) *H1 = -(R2.transpose()*rot_);\n  if (H2) *H2 = I3;\n  return Rot3(Matrix3(rot_.transpose()*R2.rot_));\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::rotate(const Point3& p,\n    boost::optional<Matrix&> H1,  boost::optional<Matrix&> H2) const {\n  if (H1 || H2) {\n      if (H1) *H1 = rot_ * skewSymmetric(-p.x(), -p.y(), -p.z());\n      if (H2) *H2 = rot_;\n    }\n  return Point3(rot_ * p.vector());\n}\n\n/* ************************************************************************* */\n// Log map at identity - return the canonical coordinates of this rotation\nVector3 Rot3::Logmap(const Rot3& R) {\n\n  static const double PI = boost::math::constants::pi<double>();\n\n  const Matrix3& rot = R.rot_;\n  // Get trace(R)\n  double tr = rot.trace();\n\n  // when trace == -1, i.e., when theta = +-pi, +-3pi, +-5pi, etc.\n  // we do something special\n  if (std::abs(tr+1.0) < 1e-10) {\n    if(std::abs(rot(2,2)+1.0) > 1e-10)\n      return (PI / sqrt(2.0+2.0*rot(2,2) )) *\n          Vector3(rot(0,2), rot(1,2), 1.0+rot(2,2));\n    else if(std::abs(rot(1,1)+1.0) > 1e-10)\n      return (PI / sqrt(2.0+2.0*rot(1,1))) *\n          Vector3(rot(0,1), 1.0+rot(1,1), rot(2,1));\n    else // if(std::abs(R.r1_.x()+1.0) > 1e-10)  This is implicit\n      return (PI / sqrt(2.0+2.0*rot(0,0))) *\n          Vector3(1.0+rot(0,0), rot(1,0), rot(2,0));\n  } else {\n    double magnitude;\n    double tr_3 = tr-3.0; // always negative\n    if (tr_3<-1e-7) {\n      double theta = acos((tr-1.0)/2.0);\n      magnitude = theta/(2.0*sin(theta));\n    } else {\n      // when theta near 0, +-2pi, +-4pi, etc. (trace near 3.0)\n      // use Taylor expansion: magnitude \\approx 1/2-(t-3)/12 + O((t-3)^2)\n      magnitude = 0.5 - tr_3*tr_3/12.0;\n    }\n    return magnitude*Vector3(\n        rot(2,1)-rot(1,2),\n        rot(0,2)-rot(2,0),\n        rot(1,0)-rot(0,1));\n  }\n}\n\n/* ************************************************************************* */\nRot3 Rot3::retractCayley(const Vector& omega) const {\n  const double x = omega(0), y = omega(1), z = omega(2);\n  const double x2 = x * x, y2 = y * y, z2 = z * z;\n  const double xy = x * y, xz = x * z, yz = y * z;\n  const double f = 1.0 / (4.0 + x2 + y2 + z2), _2f = 2.0 * f;\n  return (*this)\n      * Rot3((4 + x2 - y2 - z2) * f, (xy - 2 * z) * _2f, (xz + 2 * y) * _2f,\n          (xy + 2 * z) * _2f, (4 - x2 + y2 - z2) * f, (yz - 2 * x) * _2f,\n          (xz - 2 * y) * _2f, (yz + 2 * x) * _2f, (4 - x2 - y2 + z2) * f);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::retract(const Vector& omega, Rot3::CoordinatesMode mode) const {\n  if(mode == Rot3::EXPMAP) {\n    return (*this)*Expmap(omega);\n  } else if(mode == Rot3::CAYLEY) {\n    return retractCayley(omega);\n  } else if(mode == Rot3::SLOW_CAYLEY) {\n    Matrix Omega = skewSymmetric(omega);\n    return (*this)*CayleyFixed<3>(-Omega/2);\n  } else {\n    assert(false);\n    exit(1);\n  }\n}\n\n/* ************************************************************************* */\nVector3 Rot3::localCoordinates(const Rot3& T, Rot3::CoordinatesMode mode) const {\n  if(mode == Rot3::EXPMAP) {\n    return Logmap(between(T));\n  } else if(mode == Rot3::CAYLEY) {\n    // Create a fixed-size matrix\n    Eigen::Matrix3d A(between(T).matrix());\n    // Mathematica closed form optimization (procrastination?) gone wild:\n    const double a=A(0,0),b=A(0,1),c=A(0,2);\n    const double d=A(1,0),e=A(1,1),f=A(1,2);\n    const double g=A(2,0),h=A(2,1),i=A(2,2);\n    const double di = d*i, ce = c*e, cd = c*d, fg=f*g;\n    const double M = 1 + e - f*h + i + e*i;\n    const double K = 2.0 / (cd*h + M + a*M -g*(c + ce) - b*(d + di - fg));\n    const double x = (a * f - cd + f) * K;\n    const double y = (b * f - ce - c) * K;\n    const double z = (fg - di - d) * K;\n    return -2 * Vector3(x, y, z);\n  } else if(mode == Rot3::SLOW_CAYLEY) {\n    // Create a fixed-size matrix\n    Eigen::Matrix3d A(between(T).matrix());\n    // using templated version of Cayley\n    Eigen::Matrix3d Omega = CayleyFixed<3>(A);\n    return -2*Vector3(Omega(2,1),Omega(0,2),Omega(1,0));\n  } else {\n    assert(false);\n    exit(1);\n  }\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::matrix() const {\n  return rot_;\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::transpose() const {\n  return rot_.transpose();\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::r1() const { return Point3(rot_.col(0)); }\n\n/* ************************************************************************* */\nPoint3 Rot3::r2() const { return Point3(rot_.col(1)); }\n\n/* ************************************************************************* */\nPoint3 Rot3::r3() const { return Point3(rot_.col(2)); }\n\n/* ************************************************************************* */\nQuaternion Rot3::toQuaternion() const {\n  return Quaternion(rot_);\n}\n\n/* ************************************************************************* */\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "118d8546ef2b6a57aa2583b84e4259f6d8f35746", "size": 10235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3M.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/Rot3M.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/Rot3M.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 33.1229773463, "max_line_length": 87, "alphanum_fraction": 0.4398632145, "num_tokens": 3053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5845171719523847}}
{"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_COTPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COTPI_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 cotangent of input in\n    \\f$\\pi\\f$ multiples: \\f$\\cos(\\pi x)/sin(\\pi x)\\f$.\n\n\n    @par Header <boost/simd/function/cotpi.hpp>\n\n    @par Note\n\n      As most other trigonometric function cotd can be called\n      with a second optional parameter  which is a tag on speed\n      and accuracy (see @ref cos for further details)\n\n    @see cos, sin, tan, cot, cotpi\n\n\n    @par Example:\n\n      @snippet cotpi.cpp cotpi\n\n    @par Possible output:\n\n      @snippet cotpi.txt cotpi\n\n  **/\n  IEEEValue cotpi(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cotpi.hpp>\n#include <boost/simd/function/simd/cotpi.hpp>\n\n#endif\n", "meta": {"hexsha": "2b096291cdebda50ed984888ad8303e46fbc0c2d", "size": 1257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cotpi.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/cotpi.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/cotpi.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 24.1730769231, "max_line_length": 100, "alphanum_fraction": 0.5910898966, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5845089334060798}}
{"text": "\n#include \"mex.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <limits>\n\n#define FIXNAN() unaryExpr(std::ptr_fun(fixNaN))\n\n\ndouble fixNaN(double x) {\n\n    return std::isnan(x) ? 0 : x;\n}\n\ndouble fixLogInf(double x) {\n\n    return std::isinf(x) ? -500 : x;\n}\n\nvoid printMatrix(char *s, Eigen::MatrixXd M) {\n\n  mexPrintf(\"Matrix: %s\\n\", s);\n\n  for (int i = 0; i < M.rows(); i++) {\n\n    for (int j = 0; j < M.cols(); j++) {\n      mexPrintf(\"\\t%f\", M(i, j));\n    }\n    mexPrintf(\"\\n\");\n  }\n  mexPrintf(\"\\n\\n\");\n}\n\nEigen::VectorXd logsumexp(Eigen::MatrixXd x) {\n\n  Eigen::VectorXd y = x.colwise().maxCoeff();\n\n  Eigen::VectorXd s = (x.rowwise() - y.transpose()).array().exp().colwise().sum().log();\n\n  return y + s;\n}\n\ndouble logdet(Eigen::MatrixXd M) {\n\n  Eigen::LLT<Eigen::MatrixXd> llt(M);\n\n  // D = 2 * sum(log(diag(chol(M))));\n\n  Eigen::VectorXd res = ((Eigen::MatrixXd) llt.matrixU()) // Calc chol())\n          .diagonal().array().log() // Log of diagonal\n          .colwise().sum(); // Calc sum of logs\n\n  return 2 * res[0];\n}\n\nstatic inline double max(double a, double b) {\n  return a < b ? b : a;\n}\n\nstatic inline double log_relative_Gauss(double z, double &e, int &exit_flag) {\n\n  double logphi, logPhi;\n\n  if (z < -6) {\n\n    e = 1;\n    logPhi = -1.0e12;\n    exit_flag = -1;\n\n  } else if (z > 6) {\n\n    e = 0;\n    logPhi = 0;\n    exit_flag = 1;\n\n  } else {\n\n    logphi = -0.5 * (z * z + log(M_PI * 2)); // Const function call gets optimized away\n    logPhi = log(0.5 * erfc(-z * M_SQRT1_2));\n    e = exp(logphi - logPhi);\n    exit_flag = 0;\n  }\n  return logPhi;\n}\n\nstatic void lt_factor(int s, int l, Eigen::VectorXd M, Eigen::MatrixXd V, double mp, double p, double gam,\n        Eigen::VectorXd &Mnew, Eigen::MatrixXd &Vnew, double &pnew, double &mpnew, double &logS, double &d) {\n\n  // rank 1 projected cavity parameters\n  Eigen::VectorXd Vc = (V.col(l) - V.col(s)) * M_SQRT1_2;\n  double cVc = (V(l, l) - 2 * V(s, l) + V(s, s)) / 2;\n  double cM = (M(l) - M(s)) * M_SQRT1_2;\n\n  double cVnic = max(0, cVc / (1 - p * cVc));\n\n  double cmni = cM + cVnic * (p * cM - mp);\n\n  // rank 1 calculation: step factor\n  double z = cmni / sqrt(cVnic);\n\n  double e;\n  int exit_flag;\n  double lP = log_relative_Gauss(z, e, exit_flag);\n\n  double alpha, beta, r, dp, dmp;\n\n  switch (exit_flag) {\n\n    case 0:\n\n      alpha = e / sqrt(cVnic);\n      beta = alpha * (alpha * cVnic + cmni);\n      r = beta / (1 - beta);\n\n      // new message\n      pnew = r / cVnic;\n      mpnew = r * (alpha + cmni / cVnic) + alpha;\n\n      // update terms\n      dp = max(-p + DBL_EPSILON, gam * (pnew - p));\n      dmp = max(-mp + DBL_EPSILON, gam * (mpnew - mp));\n      d = max(dmp, dp); // for convergence measures\n\n      pnew = p + dp;\n      mpnew = mp + dmp;\n\n      // project out to marginal\n      Vnew = V - dp / (1 + dp * cVc) * (Vc * Vc.transpose());\n      Mnew = M + (dmp - cM * dp) / (1 + dp * cVc) * Vc;\n\n      // normalization constant\n      //logS  = lP - 0.5 * (log(beta) - log(pnew)) + (alpha * alpha) / (2*beta);\n\n      // there is a problem here, when z is very large\n      logS = lP - 0.5 * (log(beta) - log(pnew) - log(cVnic)) + (alpha * alpha) / (2 * beta) * cVnic;\n\n      break;\n\n    case -1: // impossible combination\n\n      d = NAN;\n\n      //Mnew = 0;\n      //Vnew = 0;\n\n      pnew = 0;\n      mpnew = 0;\n      logS = -INFINITY;\n      break;\n\n    case 1: // uninformative message\n\n      pnew = 0;\n      mpnew = 0;\n\n      // update terms\n      dp = -p; // at worst, remove message\n      dmp = -mp;\n      d = max(dmp, dp); // for convergence measures\n\n      // project out to marginal\n      Vnew = V - dp / (1 + dp * cVc) * (Vc * Vc.transpose());\n      Mnew = M + (dmp - cM * dp) / (1 + dp * cVc) * Vc;\n\n      logS = 0;\n      break;\n  }\n}\n\ndouble min_factor(Eigen::VectorXd Mu, Eigen::MatrixXd Sigma, int k, double gam,\n        Eigen::VectorXd &dlogZdMu, Eigen::VectorXd &dlogZdSigma, Eigen::MatrixXd &dlogZdMudMu) {\n\n  int D = Mu.size();\n\n  double logZ;\n\n  // messages (in natural parameters)\n  Eigen::VectorXd logS = Eigen::VectorXd::Zero(D - 1); // normalization constant (determines zeroth moment)\n  Eigen::VectorXd MP = Eigen::VectorXd::Zero(D - 1); // mean times precision (determines first moment)\n  Eigen::VectorXd P = Eigen::VectorXd::Zero(D - 1); // precision (determines second moment)  \n\n  // TODO: check if copy is really necessary here\n  // marginal:\n  Eigen::VectorXd M(Mu);\n  Eigen::MatrixXd V(Sigma);\n\n  double mpm;\n  double s;\n  double rSr;\n  double dts;\n\n  //Eigen::VectorXd dMdMu;\n  //Eigen::VectorXd dMdSigma;\n  //Eigen::VectorXd dVdSigma;\n  Eigen::MatrixXd _dlogZdSigma;\n\n  Eigen::MatrixXd R;\n  Eigen::VectorXd r;\n\n  Eigen::MatrixXd IRSR;\n  Eigen::MatrixXd A;\n  Eigen::MatrixXd A_;\n  Eigen::VectorXd b;\n  Eigen::VectorXd Ab;\n\n  Eigen::VectorXd btA;\n\n  Eigen::MatrixXd C;\n\n  double pnew;\n  double mpnew;\n\n  double Diff = 0, diff = 0;\n\n  int l, count = 0;\n\n  // mvmin = Eigen::VectorXd(2);\n\n  while (true) {\n\n    count++;\n\n    Diff = 0;\n\n    for (int i = 0; i < D - 1; i++) {\n\n      if (i < k)\n        l = i;\n      else\n        l = i + 1;\n\n      lt_factor(k, l, M, V, MP[i], P[i], gam, // IN\n              M, V, pnew, mpnew, logS[i], diff); // OUT\n\n      // Write back vector elements\n      P[i] = pnew;\n      MP[i] = mpnew;\n\n      if (std::isnan(diff))\n        goto done; // found impossible combination\n\n      Diff = Diff + std::abs(diff);\n    }\n\n    if (count > 50) {\n      mexPrintf(\"EP iteration ran over iteration limit. Stopped.\\n\");\n      goto done;\n    }\n    if (Diff < 1.0e-3) {\n      goto done;\n    }\n  }\n\ndone:\n\n  if (std::isnan(diff)) {\n\n    logZ = -INFINITY;\n    dlogZdMu = Eigen::VectorXd::Zero(D);\n    dlogZdSigma = Eigen::VectorXd::Zero(0.5 * (D * (D + 1)));\n    dlogZdMudMu = Eigen::MatrixXd::Zero(D, D);\n    //mvmin << Mu(k), Sigma(k, k);\n    //dMdMu = Eigen::VectorXd::Zero(D);\n    //dMdSigma = Eigen::VectorXd::Zero(0.5 * (D * (D + 1)));\n    //dVdSigma = Eigen::VectorXd::Zero(0.5 * (D * (D + 1)));\n\n  } else {\n\n    // evaluate log Z:\n\n    // C = eye(D) ./ sqrt(2); C(k,:) = -1/sqrt(2); C(:,k) = [];\n    C = Eigen::MatrixXd::Zero(D, D - 1);\n    for (int i = 0; i < D - 1; i++) {\n\n      C(i + (i >= k), i) = M_SQRT1_2;\n      C(k, i) = -M_SQRT1_2;\n    }\n\n    R = C.array().rowwise() * P.transpose().array().sqrt();\n    r = (C.array().rowwise() * MP.transpose().array()).rowwise().sum();\n    mpm = (MP.array() * MP.array() / P.array()).FIXNAN().sum();\n    s = logS.sum();\n\n    IRSR = R.transpose() * Sigma * R;\n    IRSR.diagonal().array() += 1; // Add eye()\n\n    rSr = r.dot(Sigma * r);\n\n    A_ = R * IRSR.llt().solve(R.transpose());\n    A = 0.5 * (A_.transpose() + A_); // ensure symmetry.\n\n    b = (Mu + Sigma * r);\n    Ab = A * b;\n\n    dts = logdet(IRSR);\n    logZ = 0.5 * (rSr - b.dot(Ab) - dts) + Mu.dot(r) + s - 0.5 * mpm;\n\n    if (true /*TODO: needs derivative? */) {\n\n      dlogZdSigma = Eigen::VectorXd(0.5 * (D * (D + 1)));\n\n      btA = b.transpose() * A;\n\n      dlogZdMu = r - Ab;\n      dlogZdMudMu = -A;\n\n      _dlogZdSigma = -A - 2 * r * Ab.transpose() + r * r.transpose() + btA * Ab.transpose();\n\n\n      Eigen::MatrixXd diag = _dlogZdSigma.diagonal().asDiagonal();\n\n      _dlogZdSigma = 0.5 * (_dlogZdSigma + _dlogZdSigma.transpose() - diag);\n\n      // dlogZdSigma = dlogZdSigma(logical(triu(ones(D,D))));\n      for (int x = 0, i = 0; x < D; x++) {\n\n        for (int y = 0; y <= x; y++) {\n          dlogZdSigma[i++] = _dlogZdSigma(y, x);\n        }\n      }\n    }\n  }\n\n  return logZ;\n}\n\nvoid joint_min(Eigen::VectorXd Mu, Eigen::MatrixXd Sigma,\n        Eigen::VectorXd &logP, Eigen::MatrixXd &dlogPdMu, Eigen::MatrixXd &dlogPdSigma, Eigen::MatrixXd **dlogPdMudMu) {\n\n  Eigen::VectorXd dlPdM;\n  Eigen::VectorXd dlPdS;\n  Eigen::MatrixXd dlPdMdM;\n\n  double gam = 1;\n  int D = Mu.size();\n\n  Eigen::MatrixXd gg = Eigen::MatrixXd(D, D);\n\n  logP = Eigen::VectorXd(D);\n\n  dlogPdMu = Eigen::MatrixXd(D, D);\n  dlogPdSigma = Eigen::MatrixXd(D, D * (D + 1) / 2);\n  *dlogPdMudMu = new Eigen::MatrixXd[D]; // Create an array of matrizes\n\n  for (int k = 0; k < D; k++) {\n\n#ifdef DEBUG_PRINTF\n    if (k % 10 == 0)\n      DEBUG_PRINTF('#');\n#endif\n    \n    logP(k) = min_factor(Mu, Sigma, k, gam, // IN\n            dlPdM, dlPdS, dlPdMdM); // OUT\n\n    dlogPdMu.row(k) = dlPdM;\n    dlogPdSigma.row(k) = dlPdS;\n\n    (*dlogPdMudMu)[k] = dlPdMdM;\n  }\n\n  // Sanity check for INF values\n  logP = logP.unaryExpr(std::ptr_fun(fixLogInf));\n\n  // re-normalize at the end, to smooth out numerical imbalances:\n  double Z = logP.array().exp().sum();\n\n  Eigen::VectorXd Zm = (dlogPdMu.array().colwise() * logP.array().exp()).colwise().sum() /Z;\n  Eigen::VectorXd Zs = (dlogPdSigma.array().colwise() * logP.array().exp()).colwise().sum() /Z;\n\n  Eigen::MatrixXd Zij = Zm * Zm.transpose();\n\n  for (int i = 0; i < D; i++) {\n\n    for (int j = i; j < D; j++) {\n\n      Eigen::MatrixXd Mj = (*dlogPdMudMu)[j];\n\n      for (int k = 0; k < D; k++) {\n        gg(i, j) -= (dlogPdMu(k, i) * dlogPdMu(k, j) + Mj(k, i)) * exp(logP(k));\n      }\n      gg(j, i) = // Hesse Matrix is symmetric\n              gg(i, j) = gg(i, j) / Z + Zij(i, j);\n    }\n  }\n\n  for (int i = 0; i < D; i++) {\n    (*dlogPdMudMu)[i].array() *= gg.array();\n  }\n\n  dlogPdMu = dlogPdMu.array().rowwise() - Zm.transpose().array();\n  dlogPdSigma = dlogPdSigma.array().rowwise() - Zs.transpose().array();\n  \n  logP = logP.array() - logsumexp(logP)(0, 0);\n}\n\nstatic void copyMatrix(Eigen::MatrixXd from, mxArray **out) {\n\n  int r = from.rows();\n  int c = from.cols();\n\n  *out = mxCreateDoubleMatrix(r, c, mxREAL);\n  double *write = mxGetPr(*out);\n  for (int i = 0; i < r; i++) {\n\n    for (int j = 0; j < c; j++) {\n      write[j * r + i] = from(i, j);\n    }\n  }\n}\n\nstatic void copyCube(Eigen::MatrixXd *from, int elms, mxArray **out) {\n\n  // They're all of the same dimension\n  int r = from->rows();\n  int c = from->cols();\n\n  mwSize dims[3];\n  dims[0] = r;\n  dims[1] = c;\n  dims[2] = elms;\n\n  *out = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);\n  double *write = mxGetPr(*out);\n  for (int k = 0; k < elms; k++) {\n\n    for (int i = 0; i < r; i++) {\n\n      for (int j = 0; j < c; j++) {\n        write[k * r * c + i * c + j] = from[k](i, j);\n      }\n    }\n  }\n}\n\nvoid mexFunction(int nlhs, mxArray * plhs[],\n        int nrhs, const mxArray * prhs[]) {\n\n  if (nrhs != 2)\n    mexErrMsgIdAndTxt(\"MATLAB:xtimesy:invalidNumInputs\",\n          \"Two inputs required.\");\n\n  if (nlhs != 4)\n    mexErrMsgIdAndTxt(\"MATLAB:xtimesy:invalidNumOutputs\",\n          \"Four outputs required.\");\n\n  if (mxGetM(prhs[0]) != 1 && mxGetN(prhs[0]) != 1) {\n    mexErrMsgIdAndTxt(\"MATLAB:xtimesy:invalidNumOutputs\",\n            \"Vector for param 1 required\");\n  }\n\n  // Input vars\n  Eigen::Map<Eigen::VectorXd> Mu(mxGetPr(prhs[0]), mxGetM(prhs[0]) == 1 ? mxGetN(prhs[0]) : mxGetM(prhs[0]));\n  Eigen::Map<Eigen::MatrixXd> Sigma(mxGetPr(prhs[1]), mxGetM(prhs[1]), mxGetN(prhs[1]));\n\n  // Output vars\n  Eigen::VectorXd logP;\n  Eigen::MatrixXd dlogPdMu;\n  Eigen::MatrixXd dlogPdSigma;\n  Eigen::MatrixXd *dlogPdMudMu;\n\n  // Do the heavy work\n  joint_min(Mu, Sigma,\n          logP, dlogPdMu, dlogPdSigma, &dlogPdMudMu);\n\n  // Output results\n  copyMatrix(logP, &(plhs[0]));\n  copyMatrix(dlogPdMu, &(plhs[1]));\n  copyMatrix(dlogPdSigma, &(plhs[2]));\n  copyMatrix(dlogPdSigma, &(plhs[3]));\n  copyCube(dlogPdMudMu, Mu.size(), &(plhs[3]));\n\n  // Endpoint, delete array\n  delete[] dlogPdMudMu;\n}\n", "meta": {"hexsha": "7efcb741bee81e7c643b7540dd90221e36062116", "size": 11319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/joint_min.cpp", "max_stars_repo_name": "ProbabilisticNumerics/entropy-search", "max_stars_repo_head_hexsha": "3f968b190670ab23e7a99fee6ef574bbc80c1656", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-05-30T00:01:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T15:16:56.000Z", "max_issues_repo_path": "cpp/joint_min.cpp", "max_issues_repo_name": "ProbabilisticNumerics/entropy-search", "max_issues_repo_head_hexsha": "3f968b190670ab23e7a99fee6ef574bbc80c1656", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-09-20T05:22:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-30T07:09:18.000Z", "max_forks_repo_path": "cpp/joint_min.cpp", "max_forks_repo_name": "ProbabilisticNumerics/entropy-search", "max_forks_repo_head_hexsha": "3f968b190670ab23e7a99fee6ef574bbc80c1656", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T21:24:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:41:54.000Z", "avg_line_length": 23.7794117647, "max_line_length": 120, "alphanum_fraction": 0.553847513, "num_tokens": 3960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5845089199332993}}
{"text": "///\\file shooting-method.cpp\n///\\author Ethan Knox\n///\\date 8/2/2020.\n\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <iomanip>\n#include <functional>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/math/tools/roots.hpp>\n\n#include \"potentials.h\"\n#include \"determine_domain_from_potential.h\"\n\nusing namespace std::placeholders;\n\nconst double m = 1.0;\nconst double k = 1.0;\nconst double hbar = 1.0;\nconst double omega = 1.0;\n\ntypedef std::vector<double> state_t;\ntypedef boost::numeric::odeint::runge_kutta_fehlberg78<state_t> stepper_rkf78_t;\ntypedef boost::numeric::odeint::runge_kutta4<state_t> rk4;\n\nvoid TISE(state_t &psi, state_t &dpsi_dx, double x, std::function<double(double)> V, double E) {\n    dpsi_dx[0] = psi[1];\n    dpsi_dx[1] = (2.0 * m / pow(hbar, 2.0)) * (V(x) - E) * psi[0];\n}\n\nint eigenE_shooting(state_t& psi, double boundary_condition, std::string Vfunc, double L, double h_0, double eps_rel, double eps_abs, double E)\n{\n    // Potential\n    std::function<double(double)> V;\n    std::function<double(double)> dV;\n    if (Vfunc == \"QHO\") {\n        V = quantum_harmonic_oscillator;\n        dV = d_quantum_harmonic_oscillator;\n    }\n    else { // Vfunc == \"ISW\"\n        V = infinite_square_well;\n        dV = d_infinite_square_well;\n    }\n\n    // Domain\n    std::pair<double, double> domain = determine_domain_from_potential(Vfunc, L);\n    const double xi = domain.first;\n    const double xf = domain.second;\n    double x = xi;\n\n    // Initial Condition\n    state_t psi_copy(psi);\n    state_t dpsi_dx(2);\n    double h_0 = 1.0e-4;\n\n    std::function<double(double)> defect = [x, xf, h_0, psi_copy, &V](double E) {\n        boost::numeric::odeint::integrate_const(rk4(), std::bind(TISE, _1, _2, _3, V, E), psi_copy, x, xf, h_0);\n        return psi_copy[0];\n    };\n    boost::math::tools::eps_tolerance<double> tol;\n    std::pair<double, double> r = boost::math::tools::bisect(defect, 0.0, 10.0, tol);\n    return r.first + (r.second - r.first) / 2;\n}\n", "meta": {"hexsha": "00c4736ccfbbe4e5fb5c17503ea9d9bb762feb6e", "size": 1986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shooting-method.cpp", "max_stars_repo_name": "ethank5149/Quantum-Mechanics", "max_stars_repo_head_hexsha": "71e1c2a47b8a399bf0ba7e07bb0dcbaa4a2068bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shooting-method.cpp", "max_issues_repo_name": "ethank5149/Quantum-Mechanics", "max_issues_repo_head_hexsha": "71e1c2a47b8a399bf0ba7e07bb0dcbaa4a2068bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shooting-method.cpp", "max_forks_repo_name": "ethank5149/Quantum-Mechanics", "max_forks_repo_head_hexsha": "71e1c2a47b8a399bf0ba7e07bb0dcbaa4a2068bd", "max_forks_repo_licenses": ["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.0909090909, "max_line_length": 143, "alphanum_fraction": 0.663141994, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.584419845614867}}
{"text": "#ifndef SE3_OPS_HPP\n#define SE3_OPS_HPP\n\n#include <tuple>\n#include <vector>\n#include <Eigen/StdVector>\n#include <Eigen/Core>\n#include <sophus/se3.hpp>\n#include <math.h>\n#include <opencv2/core.hpp>\n#include <opencv2/hdf.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"math_utils.hpp\"\n\nnamespace orcvio\n{\n\ntemplate<typename T>\n  using vector_eigen = std::vector<T, Eigen::aligned_allocator<T>>;\n\n/**\n * @brief converts vector to skew symmetric matrix in batch\n *\n * @param a: size n x 3, input vector\n *\n * @return : size n x 3 x 3, skew symmetric matrix\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 3, 3> > skew(const vector_eigen<Eigen::Matrix<Scalar, 3, 1> > &a)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 3, 3> > S;\n\n    for (const auto& w : a)\n    {\n        Eigen::Matrix<Scalar, 3, 3> w_x = skewSymmetric(w);\n        S.push_back(w_x);\n    }\n\n    return S;\n\n}\n\n/**\n * @brief converts 6-vector to 4x4 hat form in se(3) in batch\n *\n * @param x: size n x 6, n se3 elements\n *\n * @return : size n x 4 x 4, n elements of se(3)\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 4, 4> > axangle2twist(const vector_eigen<Eigen::Matrix<Scalar, 6, 1> > &a)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 4, 4> > T;\n\n    for (auto v : a)\n    {\n        Eigen::Matrix<Scalar, 4, 4> v_x = Eigen::Matrix4d::Zero();\n        v_x(0, 1) = -v(5);\n        v_x(0, 2) = v(4);\n        v_x(0, 3) = v(0);\n        v_x(1, 0) = v(5);\n        v_x(1, 2) = -v(3);\n        v_x(1, 3) = v(1);\n        v_x(2, 0) = -v(4);\n        v_x(2, 1) = v(3);\n        v_x(2, 3) = v(2);\n\n        T.push_back(v_x);\n    }\n\n    return T;\n\n}\n\n/**\n * @brief converts se3 element to SE3 in batch\n *\n * @param x: size n x 6, n se3 elements\n *\n * @return : size n x 4 x 4, n elements of SE(3)\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 4, 4> > axangle2pose(const vector_eigen<Eigen::Matrix<Scalar, 6, 1> > &a)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 4, 4> > T;\n\n    for (auto x : a)\n    {\n\n        Sophus::SE3d T_temp = Sophus::SE3d::exp(x);\n        T.push_back(T_temp.matrix());\n\n    }\n\n    return T;\n\n}\n\n/**\n * @brief converts axis angle to SO3 in batch\n *\n * @param a = n x 3 = n axis-angle elements\n *\n * @return : R = n x 3 x 3 = n elements of SO(3)\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 3, 3> > axangle2rot(const vector_eigen<Eigen::Matrix<Scalar, 3, 1> > &a)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 3, 3> > R;\n\n    for (auto x : a)\n    {\n\n        Sophus::SO3d R_temp = Sophus::SO3d::exp(x);\n        R.push_back(R_temp.matrix());\n\n    }\n\n    return R;\n\n}\n\n\n/**\n * @brief performs batch inverse of transform matrix\n *\n * @param T: size n x 4 x 4, n elements of SE(3)\n *\n * @return : size n x 4 x 4, inverse of T\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 4, 4> > inversePose(const vector_eigen<Eigen::Matrix<Scalar, 4, 4> > &T)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 4, 4> > iT;\n\n    for (auto T_temp : T)\n    {\n        Eigen::Matrix<Scalar, 4, 4> iT_temp = Eigen::Matrix4d::Zero();\n\n        iT_temp(0, 0) = T_temp(0, 0);\n        iT_temp(0, 1) = T_temp(1, 0);\n        iT_temp(0, 2) = T_temp(2, 0);\n\n        iT_temp(1, 0) = T_temp(0, 1);\n        iT_temp(1, 1) = T_temp(1, 1);\n        iT_temp(1, 2) = T_temp(2, 1);\n\n        iT_temp(2, 0) = T_temp(0, 2);\n        iT_temp(2, 1) = T_temp(1, 2);\n        iT_temp(2, 2) = T_temp(2, 2);\n\n        iT_temp.block(0, 3, 3, 1) = -1 * iT_temp.block(0, 0, 3, 3) * T_temp.block(0, 3, 3, 1);\n\n        iT_temp.block(3, 0, 1, 4) = T_temp.block(3, 0, 1, 4);\n\n        iT.push_back(iT_temp);\n\n    }\n\n    return iT;\n\n}\n\n\n/**\n * @brief odot operator\n *\n * \\f{align*}{\n *  \\underline{x}^{\\odot} = \\begin{bmatrix} I_{3\\times 3} & -x_{\\times} \\\\ 0 & 0\\end{bmatrix}\n @f}\n *\n * @param ph = 4 = point in homogeneous coordinates\n *\n * @return : odot(ph) = 4 x 6\n */\ntemplate<typename Derived>\n Eigen::Matrix<typename Derived::Scalar, 4, 6> odotOperator(const Eigen::MatrixBase<Derived>& x) {\n     assert(x.rows() == 4);\n     assert(x.cols() == 1);\n\n   Eigen::Matrix<typename Derived::Scalar, 4, 6> temp;\n   temp.setZero();\n\n   temp.block(0, 3, 3, 3) = -1 * skewSymmetric(x.template head<3>());\n\n   temp(0, 0) = x(3);\n   temp(1, 1) = x(3);\n   temp(2, 2) = x(3);\n   return temp;\n }\n\n/**\n * @brief odot operator\n *\n * \\f{align*}{\n *  \\underline{x}^{\\odot} = \\begin{bmatrix} I_{3\\times 3} & -x_{\\times} \\\\ 0 & 0\\end{bmatrix}\n  @f}\n *\n * @param ph = n x 4 = points in homogeneous coordinates\n *\n * @return : odot(ph) = n x 4 x 6\n */\n template<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 4, 6> > odotOperator(const vector_eigen<Eigen::Matrix<Scalar, 4, 1> > &ph)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 4, 6> > zz;\n\n    for (const auto& x : ph)\n    {\n      zz.emplace_back(odotOperator(x));\n    }\n    return zz;\n}\n\n/**\n  * @brief circle dot operator\n  *\n  * @param ph = 4 = points in homogeneous coordinates\n  *\n  * @return : circledCirc(ph) = 6 x 4\n  */\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 6, 4> circledCirc(const Eigen::MatrixBase<Derived>& x) {\n    static_assert(Derived::RowsAtCompileTime == 4, \"x is not 4D vector\");\n    static_assert(Derived::ColsAtCompileTime == 1, \"x is not a vector\");\n    Eigen::Matrix<typename Derived::Scalar, 6, 4> temp;\n    temp.setZero();\n\n    temp.block(3, 0, 3, 3) = -1 * skewSymmetric(x.template block<3, 1>(0, 0));\n\n    temp.block(0, 3, 3, 1) = x.template block<3, 1>(0, 0);\n    return temp;\n}\n\n/**\n * @brief circle dot operator\n *\n * @param ph = n x 4 = points in homogeneous coordinates\n *\n * @return : circledCirc(ph) = n x 6 x 4\n */\ntemplate<typename Scalar>\nvector_eigen<Eigen::Matrix<Scalar, 6, 4> > circledCirc(const vector_eigen<Eigen::Matrix<Scalar, 4, 1> > &ph)\n{\n\n    vector_eigen<Eigen::Matrix<Scalar, 6, 4>  > zz;\n\n    for (const auto& x : ph)\n    {\n      zz.push_back(circledCirc(x));\n    }\n\n    return zz;\n\n}\n\n/**\n * @brief only keep yaw and zero z\n *\n * @param T_SE3: 4 x 4\n *\n * @return T_SE2: 4 x 4\n */\n\n// template<typename Scalar>\n// Eigen::Matrix<Scalar, 4, 4> poseSE32SE2(const Eigen::Matrix<Scalar, 4, 4> &T_SE3)\n// {\n\n//     Eigen::Matrix<Scalar, 4, 4> T_SE2 = Eigen::Matrix4d::Identity();\n\n//     // yaw: alpha=arctan(r21/r11)\n//     Scalar yaw = M_PI/atan2(T_SE3(1, 0), T_SE3(0, 0));\n\n//     // deal with the case when yaw is nan  \n//     if (!std::isfinite(yaw))\n//       yaw = 0; \n\n//     T_SE2(0, 0) = cos(yaw);\n//     T_SE2(0, 1) = -sin(yaw);\n//     T_SE2(0, 3) = T_SE3(0, 3);\n\n//     T_SE2(1, 0) = sin(yaw);\n//     T_SE2(1, 1) = cos(yaw);\n//     T_SE2(1, 3) = T_SE3(1, 3);\n\n//     return T_SE2;\n\n// }\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 2, Eigen::Dynamic>\nproject_image(const Eigen::MatrixBase<Derived>& uv_hom) {\n  auto den = uv_hom.template bottomRows<1>().array().template replicate<2, 1>();\n  auto num = uv_hom.template topRows<2>().array();\n  return ( num / den ).matrix();\n}\n\ntemplate<typename Scalar>\nusing Matrix23 = Eigen::Matrix<Scalar, 2, 3>;\n\n/**\n * @brief Differentiate \\f$ \\pi([x, y, z]^\\top) = [x/z, y/z] \\f$\n *\n * \\f{align*}{\n * \\frac{\\partial \\pi([x, y, z]^\\top)}{\\partial \\mathbf{x}}\n * = [1/z, 0,   -x/z^2]\n *   [0,   1/z, -y/z^2]\n * @f}\n\n * @param x\n * @return Jacobian\n */\ntemplate <typename Derived>\nMatrix23<typename Derived::Scalar>\n  project_image_df(const Eigen::MatrixBase<Derived>& x)\n{\n    static_assert(Derived::RowsAtCompileTime == 3, \" need 3 x 1 vector\");\n    static_assert(Derived::ColsAtCompileTime == 1, \" need 3 x 1 vector\");\n    typedef typename Derived::Scalar Scalar;\n   Scalar z = x(2, 0);\n  Scalar zsq = z * z;\n  Matrix23<typename Derived::Scalar> df;\n  df <<\n    1/z,   0, -x(0, 0)/zsq,\n    0  , 1/z, -x(1, 0)/zsq;\n  return df;\n}\n\n/**\n * @brief project_object_points\n *\n * @param P   : Camera projection matrix (3 x 4)\n * @param wTo : Object to world transform (4 x 4)\n * @param points_w : Points (n x 4), note this is points in object frame with homo coord \n * @return Points (n x 2)\n */\ntemplate <typename D1, typename D2, typename D3>\nEigen::Matrix<typename D3::Scalar, Eigen::Dynamic, 2>\nproject_object_points(const Eigen::MatrixBase<D1>& P,\n                   const Eigen::MatrixBase<D2>& wTo, const Eigen::MatrixBase<D3>& points_w) {\n  auto uv_hom = P * (wTo * points_w.transpose());\n  return project_image(uv_hom).transpose();\n}\n\n\n/**\n * @brief Computes the derivative of projection operation wrt object pose\n *\n * \\f[\n * \\frac{\\partial \\pi(K ^CT_w(\\chi) x_w)}{\\partial \\xi} = \\frac{\\partial \\pi(K T x_w)}{\\partial T} @ \\frac{^cT_w(\\chi)}{\\partial \\xi}\n * \\f]\n *\n * @param [in] P   : Camera projection matrix (3 x 4)\n * @param [in] wTo : World transform (4 x 4)\n * @param [in] points_o : Points in object frame (n x 4)\n *\n * @return Jacobians (n x 2 x 6)\n */\ntemplate<typename D1, typename D2, typename D3>\nEigen::Matrix<typename D3::Scalar, Eigen::Dynamic, 6>\n  project_object_points_df_object(const Eigen::MatrixBase<D1>& P, const Eigen::MatrixBase<D2>& wTo,\n                           const Eigen::MatrixBase<D3>& points_o,\n                           const bool use_left_perturbation_flag) {\n  auto X_o = points_o.transpose();\n  Eigen::Matrix<typename D3::Scalar, Eigen::Dynamic, 6> jacobians(2*points_o.rows(), 6);\n  for (int i = 0; i < points_o.rows(); ++i) {\n\n    auto dpibydx = project_image_df(P * wTo * X_o.col(i).template topLeftCorner<4, 1>());\n    \n    Eigen::MatrixXd jac;\n    if (use_left_perturbation_flag)\n    {\n      // using left perturbation \n      jac = dpibydx * P * odotOperator(wTo * X_o.col(i));\n    }\n    else \n    {\n      // using right perturbation \n      jac = dpibydx * P * wTo * odotOperator(X_o.col(i));\n    }\n\n    assert(jac.rows() == 2 && jac.cols() == 6);\n    jacobians.template block<2, 6>(2*i, 0) = jac.template block<2, 6>(0,0);\n    \n  }\n\n  return jacobians;\n}\n\n/**\n * @brief Computes the derivative of projection operation wrt camera pose\n * @param [in] P   : Camera projection matrix (3 x 4)\n * @param [in] wTo : Object frame to World frame transformation (4 x 4)\n * @param [in] cTw : world frame to camera frame transformation (4 x 4)\n * @param [in] points_o : Points in object frame (n x 4)\n *\n * @return Jacobians ((nk x 2) x 6)\n */\ntemplate<typename D1, typename D2, typename D3>\nEigen::Matrix<typename D3::Scalar, Eigen::Dynamic, 6>\n  project_object_points_df_camera(const Eigen::MatrixBase<D1>& P, \n                           const Eigen::MatrixBase<D2>& wTo,\n                           const Eigen::MatrixBase<D2>& cTw,\n                           const Eigen::MatrixBase<D3>& points_o,\n                           const bool use_left_perturbation_flag) {\n  \n  auto X_o = points_o.transpose();\n  Eigen::Matrix<typename D3::Scalar, Eigen::Dynamic, 6> jacobians(2*points_o.rows(), 6);\n\n  Eigen::MatrixXd ps_puline_s = Eigen::Matrix<double, 3, 4>::Zero();\n  ps_puline_s.block<3,3>(0,0) = Eigen::Matrix3d::Identity();\n\n  for (int i = 0; i < points_o.rows(); ++i) {\n\n    auto dpibydx = project_image_df(P * wTo * X_o.col(i).template topLeftCorner<4, 1>());\n\n    Eigen::MatrixXd jac;\n    if (use_left_perturbation_flag)\n    {\n      // using left perturbation \n      jac = -1 * dpibydx * ps_puline_s * cTw * odotOperator(wTo * X_o.col(i));\n      // or equivalently \n      // jac = -1 * dpibydx * P * odotOperator(wTo * X_o.col(i));\n      // std::cerr << \"jac equivalent \" << odotOperator(wTo * X_o.col(i)) << \"\\n\";\n    }\n    else \n    {\n      // using right perturbation \n      jac = -1 * dpibydx * ps_puline_s * odotOperator(cTw * wTo * X_o.col(i));\n    }\n\n    assert(jac.rows() == 2 && jac.cols() == 6);\n    jacobians.template block<2, 6>(2*i, 0) = jac.template block<2, 6>(0,0);\n\n    // for debugging \n    // std::cerr << \"jac \" << jac << \"\\n\";\n\n  }\n\n  return jacobians;\n}\n\n/**\n * @brief Read eigen matrices from hdfio object\n *\n * @param h5io\n * @param name\n * @return\n */\ntemplate<typename T = cv::Ptr<cv::hdf::HDF5>>\nEigen::MatrixXd\ndsread(const T& h5io, const std::string& name) {\n  cv::Mat m;\n  if (! h5io->hlexists(name))\n    throw std::runtime_error(\"Unable to find dataset \" + name);\n  h5io->dsread( m, name );\n  if (m.dims > 2)\n    throw std::runtime_error(\"Cannot handle more than 2 dims, found \" + std::to_string(m.dims));\n  Eigen::MatrixXd m_e;\n  cv::cv2eigen(m, m_e);\n  return m_e;\n}\n\n\n/**\n * @brief Computes the distance between two SE3 transforms\n *\n * @param T1: size 4 x 4, input transform\n * @param T2: size 4 x 4, input transform\n *\n * @return : (3-tr(R))/2, |t₁ - t₂|₂\n */\ntemplate <typename D1, typename D2>\nstd::tuple<typename D1::Scalar, typename D1::Scalar>\ndisplacement(const Eigen::MatrixBase<D1>& T1, const Eigen::MatrixBase<D2>& T2)\n{\n  using Scalar = typename D1::Scalar;\n  // tr(R) = 1 + 2 cos θ\n  // 1 - cos θ = 3/2 - tr(R)/2 ∈ [0, 2]\n  auto R1 = T1.template block<3,3>(0,0);\n  auto R2 = T2.template block<3,3>(0,0);\n  Scalar dispR = (3 - (R1.transpose() * R2).trace()) / 2;\n  Scalar dispt = (T1.template topRightCorner<3,1>() - T2.template topRightCorner<3,1>()).norm();\n  return std::make_tuple(dispR, dispt);\n}\n\n/**\n * @brief odot operator\n *\n * \\f{align*}{\n *  \\underline{x}^{\\odot} = \\begin{bmatrix} I_{3\\times 3} & -x_{\\times} \\\\ 0 & 0\\end{bmatrix}\n @f}\n *\n * @param ph = 4 = point in homogeneous coordinates\n *\n * @return : odot(ph) = 4 x 6\n */\ninline Eigen::Matrix<double, 4, 6> odotOperator(const Eigen::Vector4d& x) {\n  Eigen::Matrix<double, 4, 6> temp;\n  temp.setZero();\n  temp.block(0, 3, 3, 3) = -1 * skewSymmetric(x.head(3));\n\n  temp(0, 0) = x(3);\n  temp(1, 1) = x(3);\n  temp(2, 2) = x(3);\n  return temp;\n}\n\n/**\n * @brief Computes the derivative of camera se3 wrt IMU se3 \n * @param [in] R_b2c : rotation of body frame to camera frame \n * @param [in] t_c_b : position of camera frame in body frame \n * @param [in] R_w2c : rotation of world frame to camera frame \n * @param [in] t_b_w : position of body frame in world frame \n * @param [in] use_left_perturbation_flag : which perturbation to use \n *\n * @return Jacobians (6 x 6)\n */\ninline Eigen::Matrix<double, 6, 6> get_cam_wrt_imu_se3_jacobian(const Eigen::Matrix3d& R_b2c, const Eigen::Vector3d& t_c_b, const Eigen::Matrix3d& R_w2c, const Eigen::Vector3d& t_b_w, const bool use_left_perturbation_flag)\n{\n  Eigen::Matrix<double, 6, 6> p_cxi_p_ixi = Eigen::Matrix<double, 6, 6>::Zero();\n  if (use_left_perturbation_flag)\n  {\n\n    p_cxi_p_ixi.block<3, 3>(0, 0) = skewSymmetric(t_b_w);\n    p_cxi_p_ixi.block<3, 3>(3, 0) = Eigen::Matrix<double, 3, 3>::Identity();\n    p_cxi_p_ixi.block<3, 3>(0, 3) = Eigen::Matrix<double, 3, 3>::Identity();\n\n  }\n  else \n  {\n\n    p_cxi_p_ixi.block<3, 3>(0, 0) = -1 * R_b2c * skewSymmetric(t_c_b);\n    p_cxi_p_ixi.block<3, 3>(3, 0) = R_b2c;\n    p_cxi_p_ixi.block<3, 3>(0, 3) = R_w2c;\n\n  }\n\n  return p_cxi_p_ixi;\n}\n\n} // namespace orcvio\n#endif // SE3_OPS_HPP\n", "meta": {"hexsha": "7f37bc71d3b6bcddaa2630e3fb4704f07c478db6", "size": 14685, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orcvio/utils/se3_ops.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/utils/se3_ops.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/utils/se3_ops.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": 26.6515426497, "max_line_length": 222, "alphanum_fraction": 0.6059244127, "num_tokens": 5068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.584419845614867}}
{"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_POSV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_POSV_HPP\n\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/lapack/lapack.h>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/numeric/bindings/traits/detail/symm_herm_traits.hpp>\n#  include <boost/static_assert.hpp>\n#  include <boost/type_traits/is_same.hpp>\n#endif \n\n#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 symmetric or Hermitian positive definite matrix\n    //\n    /////////////////////////////////////////////////////////////////////\n\n    /*\n     * posv() computes the solution to a system of linear equations \n     * A * X = B, where A is an N-by-N symmetric or Hermitian positive \n     * definite matrix and X and B are N-by-NRHS matrices.\n     *\n     * The Cholesky decomposition is used to factor A as\n     *   A = U^T * U or A = U^H * U,  if UPLO = 'U', \n     *   A = L * L^T or A = L * L^H,  if UPLO = 'L',\n     * where U is an upper triangular matrix and L is a lower triangular\n     * matrix. The factored form of A is then used to solve the system of\n     * equations A * X = B.\n     * \n     * If UPLO = 'U', the leading N-by-N upper triangular part of A \n     * contains the upper triangular part of the matrix A, and the \n     * strictly lower triangular part of A is not referenced. \n     * If UPLO = 'L', the leading N-by-N lower triangular part of A \n     * contains the lower triangular part of the matrix A, and the \n     * strictly upper triangular part of A is not referenced.\n     */\n\n    namespace detail {\n\n      inline \n      void posv (char const uplo, int const n, int const nrhs,\n                 float* a, int const lda, \n                 float* b, int const ldb, int* info) \n      {\n        LAPACK_SPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);\n      }\n\n      inline \n      void posv (char const uplo, int const n, int const nrhs,\n                 double* a, int const lda, \n                 double* b, int const ldb, int* info) \n      {\n        LAPACK_DPOSV (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);\n      }\n\n      inline \n      void posv (char const uplo, int const n, int const nrhs,\n                 traits::complex_f* a, int const lda, \n                 traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CPOSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (a), &lda, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void posv (char const uplo, int const n, int const nrhs,\n                 traits::complex_d* a, int const lda, \n                 traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZPOSV (&uplo, &n, &nrhs, \n                      traits::complex_ptr (a), &lda, \n                      traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename SymmMatrA, typename MatrB>\n      inline\n      int posv (char const uplo, SymmMatrA& a, MatrB& b) {\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        int info; \n        posv (uplo, n, traits::matrix_size2 (b),\n              traits::matrix_storage (a), \n              traits::leading_dimension (a),\n              traits::matrix_storage (b), \n              traits::leading_dimension (b), \n              &info);\n        return info; \n      }\n\n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int posv (char const uplo, SymmMatrA& a, MatrB& b) {\n\n      assert (uplo == 'U' || uplo == 'L'); \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure, \n        traits::general_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      return detail::posv (uplo, a, b); \n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int posv (SymmMatrA& a, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      typedef traits::matrix_traits<SymmMatrA> matraits;\n      typedef typename matraits::value_type val_t;\n      BOOST_STATIC_ASSERT( (traits::detail::symm_herm_compatible< val_t, typename matraits::matrix_structure >::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      char uplo = traits::matrix_uplo_tag (a);\n      return detail::posv (uplo, a, b); \n    }\n\n\n    /*\n     * potrf() computes the Cholesky factorization of a symmetric\n     * or Hermitian positive definite matrix A. The factorization has \n     * the form\n     *   A = U^T * U or A = U^H * U,  if UPLO = 'U', \n     *   A = L * L^T or A = L * L^H,  if UPLO = 'L',\n     * where U is an upper triangular matrix and L is lower triangular.\n     */\n\n    namespace detail {\n\n      inline \n      void potrf (char const uplo, int const n, \n                  float* a, int const lda, int* info) \n      {\n        LAPACK_SPOTRF (&uplo, &n, a, &lda, info);\n      }\n\n      inline \n      void potrf (char const uplo, int const n, \n                  double* a, int const lda, int* info) \n      {\n        LAPACK_DPOTRF (&uplo, &n, a, &lda, info);\n      }\n\n      inline \n      void potrf (char const uplo, int const n, \n                  traits::complex_f* a, int const lda, int* info) \n      {\n        LAPACK_CPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info);\n      }\n\n      inline \n      void potrf (char const uplo, int const n, \n                  traits::complex_d* a, int const lda, int* info) \n      {\n        LAPACK_ZPOTRF (&uplo, &n, traits::complex_ptr (a), &lda, info);\n      }\n\n      template <typename SymmMatrA> \n      inline\n      int potrf (char const uplo, SymmMatrA& a) {\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        int info; \n        potrf (uplo, n, traits::matrix_storage (a), \n               traits::leading_dimension (a), &info);\n        return info; \n      }\n\n    }\n\n    template <typename SymmMatrA> \n    inline\n    int potrf (char const uplo, SymmMatrA& a) {\n\n      assert (uplo == 'U' || uplo == 'L'); \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure, \n        traits::general_t\n      >::value));\n#endif\n\n      return detail::potrf (uplo, a); \n    }\n\n    template <typename SymmMatrA>\n    inline\n    int potrf (SymmMatrA& a) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      typedef traits::matrix_traits<SymmMatrA> matraits;\n      typedef typename matraits::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename matraits::matrix_structure,\n        typename traits::detail::symm_herm_t<val_t>::type\n      >::value));\n#endif\n      \n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::potrf (uplo, a); \n    }\n\n\n    /*\n     * potrs() solves a system of linear equations A*X = B with \n     * a symmetric or Hermitian positive definite matrix A using \n     * the Cholesky factorization computed by potrf().\n     */\n\n    namespace detail {\n\n      inline \n      void potrs (char const uplo, int const n, int const nrhs,\n                  float const* a, int const lda, \n                  float* b, int const ldb, int* info) \n      {\n        LAPACK_SPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);\n      }\n\n      inline \n      void potrs (char const uplo, int const n, int const nrhs,\n                  double const* a, int const lda, \n                  double* b, int const ldb, int* info) \n      {\n        LAPACK_DPOTRS (&uplo, &n, &nrhs, a, &lda, b, &ldb, info);\n      }\n\n      inline \n      void potrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_f const* a, int const lda, \n                  traits::complex_f* b, int const ldb, int* info) \n      {\n        LAPACK_CPOTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (a), &lda, \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      inline \n      void potrs (char const uplo, int const n, int const nrhs,\n                  traits::complex_d const* a, int const lda, \n                  traits::complex_d* b, int const ldb, int* info) \n      {\n        LAPACK_ZPOTRS (&uplo, &n, &nrhs, \n                       traits::complex_ptr (a), &lda, \n                       traits::complex_ptr (b), &ldb, info);\n      }\n\n      template <typename SymmMatrA, typename MatrB>\n      inline\n      int potrs (char const uplo, SymmMatrA const& a, MatrB& b) {\n        int const n = traits::matrix_size1 (a);\n        assert (n == traits::matrix_size2 (a));\n        assert (n == traits::matrix_size1 (b));\n        int info; \n        potrs (uplo, n, traits::matrix_size2 (b),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (a), \n#else\n               traits::matrix_storage_const (a), \n#endif \n               traits::leading_dimension (a),\n               traits::matrix_storage (b), \n               traits::leading_dimension (b), \n               &info);\n        return info; \n      }\n\n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int potrs (char const uplo, SymmMatrA const& a, MatrB& b) {\n\n      assert (uplo == 'U' || uplo == 'L'); \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmMatrA>::matrix_structure, \n        traits::general_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      return detail::potrs (uplo, a, b); \n    }\n\n    template <typename SymmMatrA, typename MatrB>\n    inline\n    int potrs (SymmMatrA const& a, MatrB& b) {\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      typedef traits::matrix_traits<SymmMatrA> matraits;\n      typedef traits::matrix_traits<MatrB> mbtraits;\n      typedef typename matraits::value_type val_t;\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename matraits::matrix_structure,\n        typename traits::detail::symm_herm_t<val_t>::type\n      >::value));\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename mbtraits::matrix_structure, traits::general_t\n      >::value));\n#endif\n\n      char uplo = traits::matrix_uplo_tag (a);\n      return detail::potrs (uplo, a, b); \n    }\n\n    // TO DO: potri() \n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "3e773704d0b7d12bf16ba18cbd740bb6229b7ffa", "size": 11219, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/posv.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/posv.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/posv.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": 31.6028169014, "max_line_length": 123, "alphanum_fraction": 0.5824939834, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5844198375279879}}
{"text": "/*=================================================================\n*\n* compute various kinds of Laplacian weight\n*\n* usage: \n\t\tL = perform_mesh_weight(verts, faces, type, options);\n* inputs:\n\t\tverts: 3*nverts\n\t\tfaces: 3*faces\n\t\ttype: type is either \n\t\t\t%       0: 'combinatorial' or 'graph': W(i,j)=1 is vertex i is conntected to vertex j.\n\t\t\t%       1: 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex\n\t\t\t%           i and j.\n\t\t\t%       2: 'spring': W(i,j) = 1/d_ij where d_ij is distance between vertex\n\t\t\t%           i and j.\n\t\t\t%       3: 'conformal' or 'dcp': W(i,j) = (cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n\t\t\t%           beta_ij are the adjacent angle to edge (i,j). (do not offer W(i,j) = cot(alpha_ij)+cot(beta_ij) anymore)\n\t\t\t%           Refer to Computing discrete minimal surfaces and their conjugates_93, \n\t\t\t%           Lemma 2 of On the convergence of metric and geometric properties of polyhedral surfaces_06 and \n\t\t\t%           Characterizing Shape Using Conformal Factors_08.\n\t\t\t%           Refer to Skeleton Extraction by Mesh Extraction_08, and Intrinsic Parameterizations of Surface Meshes_02.\n\t\t\t%       4: 'Mean_curvature' or 'Laplace-Beltrami': W(i,j) = (1/area_i)*(cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n\t\t\t%           beta_ij are the adjacent angle to edge (i,j), area_i is the area of vertex i's Voroni vicinity. \n\t\t\t%           Refer to Discrete Differential-Geometry Operators_for triangulated 2-manifolds_02\n\t\t\t%       5: 'Manifold-harmonic': W(i,j) = (1/sqrt(area_i*area_j))*(cot(alpha_ij)+cot(beta_ij))/2 where alpha_ij and\n\t\t\t%           beta_ij are the adjacent angle to edge (i,j). \n\t\t\t%           Refer to Spectral Geometry Processing with Manifold Harmonics_08\n\t\t\t%       6: 'mvc': W(i,j) = [tan(/_kij/2)+tan(/_jil/2)]/d_ij where /_kij and /_jil are angles at i\n\t\toptions.?:\n*\n*           4 or 5 can be built on 3 in matlab.          \n*           just 0 & 3 are handled here. 1, 2 and 6 are left as todo.\n*\n* JJCAO, 2013\n*\n*=================================================================*/\n\n#include <mex.h>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <vector>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Triplet<double> T;\ntypedef SparseMatrix<double>::Index Index;\ntypedef SparseMatrix<double>::Scalar Scalar;\n\n\n/// Return cotangent of (P,Q,R) corner (ie cotan of QP,QR angle).\ndouble cotangent(const Vector3d& P,\n                    const Vector3d& Q,\n                    const Vector3d& R)\n{\n\n    Vector3d u = P - Q;\n    Vector3d v = R - Q;\n    // (u . v)/((u x v).len)\n    double dot = u.dot(v);\n    Vector3d cross_vector = u.cross(v);\n    double cross_norm = std::sqrt(cross_vector.dot(cross_vector));\n    if(cross_norm != 0.0)\n        return (dot/cross_norm);\n    else\n        return 0.0; // undefined\n}\n\n////                                                  -> ->\n///// Return tangent of (P,Q,R) corner (ie tangent of QP,QR angle).\n//double tangent(const Point_3& P,\n//                const Point_3& Q,\n//                const Point_3& R)\n//{\n//    Vector_3 u = P - Q;\n//    Vector_3 v = R - Q;\n//    // (u . v)/((u x v).len)\n//    double dot = (u*v);\n//    CGAL_surface_mesh_parameterization_assertion(dot != 0.0);\n//    Vector_3 cross_vector = CGAL::cross_product(u,v);\n//    double cross_norm = std::sqrt(cross_vector*cross_vector);\n//    if(dot != 0.0)\n//        return (cross_norm/dot);\n//    else\n//        return 0.0; // undefined\n//}\n\nvoid compute_dcp_weight(double* verts, int* faces, int nverts, int nfaces, SparseMatrix<double>& sm)\n{\n\tint i,j,m;\n\tdouble dtmp;\n\tstd::vector<T> coef(nverts*6);\t\n\tfor (int k = 0; k < nfaces; ++k)\n\t{\n\t\tint tmp = 3*k;\n\t\tint face[3] = {faces[tmp],faces[tmp+1],faces[tmp+2]};\t\t\t\n\t\tfor (int l = 0; l < 3; ++l)\n\t\t{\n\t\t\ti = face[l]; j = face[(l+1)%3]; m = face[(l+2)%3];\n\t\t\tVector3d p(verts[3*i],verts[3*i+1],verts[3*i+2]);\n\t\t\tVector3d q(verts[3*m],verts[3*m+1],verts[3*m+2]);\n\t\t\tVector3d r(verts[3*j],verts[3*j+1],verts[3*j+2]);\n\t\t\tdtmp = 0.5*cotangent(p, q, r);\n\t\t\tcoef.push_back(T(i,j,dtmp));\n\t\t}\t\t\t\n\t}\n\t{\n\t\tSparseMatrix<double> smtmp(nverts, nverts);\n\t\tsmtmp.setFromTriplets(coef.begin(), coef.end());\n\t\tsm = SparseMatrix<double>(smtmp.transpose()) + smtmp;\n\t}\n}\n\nvoid perform_mesh_weight(double* verts, int nverts, int *faces, int nfaces, int type, double *vert_areas, SparseMatrix<double>& sm)\n{\t\n\tswitch(type)\n\t{\n\tcase 0: //'combinatorial' or 'graph'\n\t\t// ���ܴ�������\n\t\t{\n\t\tint i,j;\t\n\t\tstd::vector<T> coef(nverts*6);\t\n\t\tfor (int k = 0; k < nfaces; ++k)\n\t\t{\n\t\t\tint tmp = 3*k;\n\t\t\tint face[3] = {faces[tmp],faces[tmp+1],faces[tmp+2]};\t\t\t\n\t\t\tfor (int l = 0; l < 3; ++l)\n\t\t\t{\n\t\t\t\ti = face[l]; j = face[(l+1)%3];\n\t\t\t\tcoef.push_back(T(i,j,1));\n\t\t\t}\t\t\t\n\t\t}\n\t\tsm.setFromTriplets(coef.begin(), coef.end());\n\t\t//sm.coeffRef(1,1) = 2;sm.coeffRef(2,2) = 3;//sm.coeffRef(0,0) = 1;\n\t\t}\n\t\tbreak;\n\tcase 3: //'conformal' or 'dcp'\t\t\n\t\tcompute_dcp_weight(verts, faces, nverts, nfaces, sm);\n\t\tbreak;\n\t//case 4: // 'Mean_curvature' or 'Laplace-Beltrami'\t\n\t//\t//if (vert_areas == 0)\n\t//\t//{\n\t//\t//\tstringstream ss(\"options.vert_areas is not offered! \");\t \n\t//\t//\tmexErrMsgTxt(ss.str().c_str());\n\t//\t//}\n\t//\tcompute_dcp_weight(verts, faces, nverts, nfaces, sm);\n\t//\t//{\n\t//\t//\tfor ( int i = 0; i < sm.rows(); ++i)\n\t//\t//\t{\n\t//\t//\t\tsm.row(i) = sm.row(i) * (1.0/vert_areas[i]);\n\t//\t//\t}\n\t//\t//}\n\t//\tbreak;\n\tdefault:\n\t\tstringstream ss(\"type: \");\t \n\t\tss << type << \" is not supported!\";\n\t\tmexErrMsgTxt(ss.str().c_str());\n\t}\n\n\tsm.makeCompressed();\n}\n\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])\n{\n\t///////////// Error Check\n\tif ( nrhs < 3) \n\t\tmexErrMsgTxt(\"Number of input should be > 2\");\n\tif (1 != nlhs) \n\t\tmexErrMsgTxt(\"Number of output should be 1\");\n\n\t///////////// input & output arguments\t\n\t// input 0: verts: 3*nverts\n\tint row = mxGetM(prhs[0]);\n\tint nverts = mxGetN(prhs[0]);\n\tif(row != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be 3*n\");\n\n\tdouble *verts = mxGetPr(prhs[0]);\n\n\t// input 1: faces: 3*nfaces\n\trow = mxGetM(prhs[1]);\n\tint nfaces = mxGetN(prhs[1]);\n\tif(row != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be 3*n\");\n\n\tdouble* dfaces = mxGetPr(prhs[1]);\n    int* faces = new int[nfaces*3];\n    for(int i = 0; i < nfaces*3; ++i)\n    {\n        faces[i] = int(dfaces[i]);\n\t\t--faces[i];\n    }\n    \n\t// input 3: type\n\tdouble* type = mxGetPr(prhs[2]);\n\t\n\t// input 4: options\n\tdouble* vert_areas(0);\n\tif ( nrhs > 3) \n\t{\n\t\tmxArray* tmp;\n\t\tconst mxArray *options = prhs[3];\n\t\tif ( mxSTRUCT_CLASS != mxGetClassID(options))\n\t\t\tmexErrMsgTxt(\"4th arguments is not a structure!\");\n\t\telse\n\t\t{\n\t\t\t// options.vert_areas: 1*nverts\n\t\t\ttmp = mxGetField(options,0,\"vert_areas\");\n\t\t\tif (tmp)\n\t\t\t\tvert_areas = mxGetPr(tmp);// not used!\n\t\t\t//mexPrintf(\"%f, %f, %f\\n\", vert_areas[0],vert_areas[1],vert_areas[2]);\t\n\t\t}\n\t}\n\n\t///////////////////////////////////////////////\t\t\n\tSparseMatrix<double> sm(nverts, nverts);\n\tperform_mesh_weight(verts, nverts, faces, nfaces, *type, vert_areas, sm);\n\n\tSparseMatrix<double>::StorageIndex* innerInd = sm.innerIndexPtr();\n\tSparseMatrix<double>::StorageIndex* outerInd = sm.outerIndexPtr();\n\tScalar* valuePtr = sm.valuePtr();\n\n\t///////////////////////////////////////////////\n\t// output 0\n\t//plhs[0] = mxCreateDoubleMatrix( nverts, nverts, mxREAL);\n    mwSize nzmax= sm.nonZeros();\n\tplhs[0] = mxCreateSparse( nverts, nverts, nzmax, mxREAL);\n\tdouble *L = mxGetPr(plhs[0]);\n\tmwIndex *irs = mxGetIr(plhs[0]);//row index\n    mwIndex *jcs = mxGetJc(plhs[0]);//column index\t\n\t\n\n\tfor (int k = 0; k<nzmax; ++k)\n\t{\n\t\t//double dtmp = valuePtr[k];\n\t\t//long ltmp = innerInd[k];\n\t\tL[k] = valuePtr[k];\n\t\tirs[k] = innerInd[k];\n\t\t//mexPrintf(\"%f %f\\n\", L[k], irs[k]);\n\t}\n\n\tfor (int k = 0; k<nverts; ++k)\n\t{\n\t\t//long ltmp = outerInd[k];\n\t\tjcs[k] = outerInd[k];\n\t}\n\t//long ltmp = outerInd[nverts];\n\tjcs[nverts]=outerInd[nverts];\n    \n    delete[] faces;\n}", "meta": {"hexsha": "4f7475075feda5103943dcbcba56ebcd38787eca", "size": 7873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/perform_mesh_weight.cpp", "max_stars_repo_name": "joycewangsy/normals_pointnet", "max_stars_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/perform_mesh_weight.cpp", "max_issues_repo_name": "joycewangsy/normals_pointnet", "max_issues_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/perform_mesh_weight.cpp", "max_forks_repo_name": "joycewangsy/normals_pointnet", "max_forks_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3665338645, "max_line_length": 131, "alphanum_fraction": 0.5810999619, "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5843965441067301}}
{"text": "// Copyright (c) 2020, Viktor Larsson\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#include \"univariate.h\"\n\n#include <Eigen/Eigen>\n#include <complex>\n\nnamespace poselib {\nnamespace univariate {\n/* Solves the quadratic equation a*x^2 + b*x + c = 0 */\nvoid solve_quadratic(double a, double b, double c, std::complex<double> roots[2]) {\n\n    std::complex<double> b2m4ac = b * b - 4 * a * c;\n    std::complex<double> sq = std::sqrt(b2m4ac);\n\n    // Choose sign to avoid cancellations\n    roots[0] = (b > 0) ? (2 * c) / (-b - sq) : (2 * c) / (-b + sq);\n    roots[1] = c / (a * roots[0]);\n}\n\n/* Solves the quadratic equation a*x^2 + b*x + c = 0 */\nint solve_quadratic_real(double a, double b, double c, double roots[2]) {\n\n    double b2m4ac = b * b - 4 * a * c;\n    if (b2m4ac < 0)\n        return 0;\n\n    double sq = std::sqrt(b2m4ac);\n\n    // Choose sign to avoid cancellations\n    roots[0] = (b > 0) ? (2 * c) / (-b - sq) : (2 * c) / (-b + sq);\n    roots[1] = c / (a * roots[0]);\n\n    return 2;\n}\n\n/* Sign of component with largest magnitude */\ninline double sign2(const std::complex<double> z) {\n    if (std::abs(z.real()) > std::abs(z.imag()))\n        return z.real() < 0 ? -1.0 : 1.0;\n    else\n        return z.imag() < 0 ? -1.0 : 1.0;\n}\n\n/* Sign of component with largest magnitude */\ninline double sign(const double z) { return z < 0 ? -1.0 : 1.0; }\n\nvoid solve_cubic_single_real(double c2, double c1, double c0, double &root) {\n    double a = c1 - c2 * c2 / 3.0;\n    double b = (2.0 * c2 * c2 * c2 - 9.0 * c2 * c1) / 27.0 + c0;\n    double c = b * b / 4.0 + a * a * a / 27.0;\n    if (c > 0) {\n        c = std::sqrt(c);\n        b *= -0.5;\n        root = std::cbrt(b + c) + std::cbrt(b - c) - c2 / 3.0;\n    } else {\n        c = 3.0 * b / (2.0 * a) * std::sqrt(-3.0 / a);\n        root = 2.0 * std::sqrt(-a / 3.0) * std::cos(std::acos(c) / 3.0) - c2 / 3.0;\n    }\n}\n\nint solve_cubic_real(double c2, double c1, double c0, double roots[3]) {\n    double a = c1 - c2 * c2 / 3.0;\n    double b = (2.0 * c2 * c2 * c2 - 9.0 * c2 * c1) / 27.0 + c0;\n    double c = b * b / 4.0 + a * a * a / 27.0;\n    int n_roots;\n    if (c > 0) {\n        c = std::sqrt(c);\n        b *= -0.5;\n        roots[0] = std::cbrt(b + c) + std::cbrt(b - c) - c2 / 3.0;\n        n_roots = 1;\n    } else {\n        c = 3.0 * b / (2.0 * a) * std::sqrt(-3.0 / a);\n        double d = 2.0 * std::sqrt(-a / 3.0);\n        roots[0] = d * std::cos(std::acos(c) / 3.0) - c2 / 3.0;\n        roots[1] = d * std::cos(std::acos(c) / 3.0 - 2.09439510239319526263557236234192) - c2 / 3.0; // 2*pi/3\n        roots[2] = d * std::cos(std::acos(c) / 3.0 - 4.18879020478639052527114472468384) - c2 / 3.0; // 4*pi/3\n        n_roots = 3;\n    }\n\n    // single newton iteration\n    for (int i = 0; i < n_roots; ++i) {\n        double x = roots[i];\n        double x2 = x * x;\n        double x3 = x * x2;\n        double dx = -(x3 + c2 * x2 + c1 * x + c0) / (3 * x2 + 2 * c2 * x + c1);\n        roots[i] += dx;\n    }\n    return n_roots;\n}\n\n/* Solves the quartic equation x^4 + b*x^3 + c*x^2 + d*x + e = 0 */\nvoid solve_quartic(double b, double c, double d, double e, std::complex<double> roots[4]) {\n\n    // Find depressed quartic\n    std::complex<double> p = c - 3.0 * b * b / 8.0;\n    std::complex<double> q = b * b * b / 8.0 - 0.5 * b * c + d;\n    std::complex<double> r = (-3.0 * b * b * b * b + 256.0 * e - 64.0 * b * d + 16.0 * b * b * c) / 256.0;\n\n    // Resolvent cubic is now\n    // U^3 + 2*p U^2 + (p^2 - 4*r) * U - q^2\n    std::complex<double> bb = 2.0 * p;\n    std::complex<double> cc = p * p - 4.0 * r;\n    std::complex<double> dd = -q * q;\n\n    // Solve resolvent cubic\n    std::complex<double> d0 = bb * bb - 3.0 * cc;\n    std::complex<double> d1 = 2.0 * bb * bb * bb - 9.0 * bb * cc + 27.0 * dd;\n\n    std::complex<double> C3 = (d1.real() < 0) ? (d1 - sqrt(d1 * d1 - 4.0 * d0 * d0 * d0)) / 2.0\n                                              : (d1 + sqrt(d1 * d1 - 4.0 * d0 * d0 * d0)) / 2.0;\n\n    std::complex<double> C;\n    if (C3.real() < 0)\n        C = -std::pow(-C3, 1.0 / 3);\n    else\n        C = std::pow(C3, 1.0 / 3);\n\n    std::complex<double> u2 = (bb + C + d0 / C) / -3.0;\n\n    // std::complex<double> db = u2 * u2 * u2 + bb * u2 * u2 + cc * u2 + dd;\n\n    std::complex<double> u = sqrt(u2);\n\n    std::complex<double> s = -u;\n    std::complex<double> t = (p + u * u + q / u) / 2.0;\n    std::complex<double> v = (p + u * u - q / u) / 2.0;\n\n    roots[0] = (-u - sign2(u) * sqrt(u * u - 4.0 * v)) / 2.0;\n    roots[1] = v / roots[0];\n    roots[2] = (-s - sign2(s) * sqrt(s * s - 4.0 * t)) / 2.0;\n    roots[3] = t / roots[2];\n\n    for (int i = 0; i < 4; i++) {\n        roots[i] = roots[i] - b / 4.0;\n\n        // do one step of newton refinement\n        std::complex<double> x = roots[i];\n        std::complex<double> x2 = x * x;\n        std::complex<double> x3 = x * x2;\n        std::complex<double> dx =\n            -(x2 * x2 + b * x3 + c * x2 + d * x + e) / (4.0 * x3 + 3.0 * b * x2 + 2.0 * c * x + d);\n        roots[i] = x + dx;\n    }\n}\n\n/* Solves the quartic equation x^4 + b*x^3 + c*x^2 + d*x + e = 0 */\nint solve_quartic_real(double b, double c, double d, double e, double roots[4]) {\n\n    // Find depressed quartic\n    double p = c - 3.0 * b * b / 8.0;\n    double q = b * b * b / 8.0 - 0.5 * b * c + d;\n    double r = (-3.0 * b * b * b * b + 256.0 * e - 64.0 * b * d + 16.0 * b * b * c) / 256.0;\n\n    // Resolvent cubic is now\n    // U^3 + 2*p U^2 + (p^2 - 4*r) * U - q^2\n    double bb = 2.0 * p;\n    double cc = p * p - 4.0 * r;\n    double dd = -q * q;\n\n    // Solve resolvent cubic\n    double u2;\n    solve_cubic_single_real(bb, cc, dd, u2);\n\n    if (u2 < 0)\n        return 0;\n\n    double u = sqrt(u2);\n\n    double s = -u;\n    double t = (p + u * u + q / u) / 2.0;\n    double v = (p + u * u - q / u) / 2.0;\n\n    int sols = 0;\n    double disc = u * u - 4.0 * v;\n    if (disc > 0) {\n        roots[0] = (-u - sign(u) * std::sqrt(disc)) / 2.0;\n        roots[1] = v / roots[0];\n        sols += 2;\n    }\n    disc = s * s - 4.0 * t;\n    if (disc > 0) {\n        roots[sols] = (-s - sign(s) * std::sqrt(disc)) / 2.0;\n        roots[sols + 1] = t / roots[sols];\n        sols += 2;\n    }\n\n    for (int i = 0; i < sols; i++) {\n        roots[i] = roots[i] - b / 4.0;\n\n        // do one step of newton refinement\n        double x = roots[i];\n        double x2 = x * x;\n        double x3 = x * x2;\n        double dx = -(x2 * x2 + b * x3 + c * x2 + d * x + e) / (4.0 * x3 + 3.0 * b * x2 + 2.0 * c * x + d);\n        roots[i] = x + dx;\n    }\n    return sols;\n}\n\n}; // namespace univariate\n}; // namespace poselib\n", "meta": {"hexsha": "0b9a629db6ed6b405eb8d8809815dd23e8febc30", "size": 8046, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PoseLib/misc/univariate.cc", "max_stars_repo_name": "MikhailTerekhov/PoseLib", "max_stars_repo_head_hexsha": "8f1a2d92c3955bc1e2ce455d4009f9df98ceb697", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T12:12:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:12:59.000Z", "max_issues_repo_path": "PoseLib/misc/univariate.cc", "max_issues_repo_name": "wuyuanmm/PoseLib", "max_issues_repo_head_hexsha": "35cf8989ddbe721209e8d314eaa94447ab2bd504", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PoseLib/misc/univariate.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": 35.135371179, "max_line_length": 110, "alphanum_fraction": 0.5254784986, "num_tokens": 2934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.584282704069643}}
{"text": "#pragma once\n\n#include <polyfem/Types.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace polyfem {\n\n\t// Show some stats about the matrix M: det, singular values, condition number, etc\n\tvoid show_matrix_stats(const Eigen::MatrixXd &M);\n\n\n\ttemplate<typename T>\n\tT determinant(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3> &mat)\n\t{\n\t\tassert(mat.rows() == mat.cols());\n\n\t\tif(mat.rows() == 1)\n\t\t\treturn mat(0);\n\t\telse if(mat.rows() == 2)\n\t\t\treturn mat(0, 0) * mat(1, 1) - mat(0, 1) * mat(1, 0);\n\t\telse if(mat.rows() == 3)\n\t\t\treturn mat(0,0)*(mat(1,1)*mat(2,2)-mat(1,2)*mat(2,1))-mat(0,1)*(mat(1,0)*mat(2,2)-mat(1,2)*mat(2,0))+mat(0,2)*(mat(1,0)*mat(2,1)-mat(1,1)*mat(2,0));\n\n\t\tassert(false);\n\t\treturn T(0);\n\t}\n\n    template<typename T>\n\tvoid read_matrix(const std::string &path, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &mat);\n\n\tEigen::Vector4d compute_specturm(const StiffnessMatrix &mat);\n\n} // namespace polyfem\n", "meta": {"hexsha": "036ebd67b368d514d2aac3e11560f7f49294cd4b", "size": 949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/MatrixUtils.hpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/MatrixUtils.hpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/MatrixUtils.hpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3611111111, "max_line_length": 151, "alphanum_fraction": 0.645943098, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5842626035744083}}
{"text": "#include \"geometrycentral/stripes.h\"\n#include <Eigen/SparseCholesky>\n\n// ONLY WORKS FOR MESHES WITHOUT BOUNDARY\nStripes::Stripes(HalfedgeMesh* m, Geometry<Euclidean>* g) : mesh(m), geom(g), phi(m), r(m), field(m), \n                                                                singularities(m), branchCover(m), omega(m) {\n    assert(mesh->nBoundaryLoops() == 0);\n}\n\nvoid Stripes::setup() {\n    VertexData<double> s(mesh);\n    // Compute s_i at each vertex\n    for (VertexPtr v : mesh->vertices()) {\n        if (v.isBoundary()) {\n            s[v] = 1.0;\n        } else {\n            double sum = 0;\n            for (HalfedgePtr he : v.outgoingHalfedges()) {\n                sum += geom->angle(he.next());\n            }\n            s[v] = 2*M_PI / sum;\n        }\n    }\n    \n    // Compute transport at edges r_ij <- e^ip_ij\n    for (VertexPtr v : mesh->vertices()) {\n        HalfedgePtr he = v.halfedge();\n        double angle = 0;\n        double s_i = s[v];\n        do {\n            phi[he] = angle;\n            angle += s_i * geom->angle(he.next());\n            he = he.next().next().twin();\n        } while (he != v.halfedge());\n    }\n\n    // Compute r_ij\n    std::complex<double> i(0, 1);\n    for (VertexPtr v : mesh->vertices()) {\n        for (HalfedgePtr he : v.outgoingHalfedges()) {\n            double theta_ij = phi[he];\n            double theta_ji = phi[he.twin()] + M_PI;\n            double rho_ij = theta_ij - theta_ji;\n            r[he] = std::exp(i * n * rho_ij);\n        }\n    }   \n}\n\nEigen::SparseMatrix<std::complex<double>> Stripes::assembleM() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> M(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he_ij = f.halfedge();\n        size_t i = vertexIndices[he_ij.vertex()];\n        size_t j = vertexIndices[he_ij.next().vertex()];\n        size_t k = vertexIndices[he_ij.prev().vertex()];\n\n        double area = geom->area(f);\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, area/3.));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j, j, area/3.));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k, k, area/3.));\n    }\n    M.setFromTriplets(triplets.begin(),triplets.end());\n    return M;\n}\n\nEigen::SparseMatrix<std::complex<double>> Stripes::assembleA() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> A(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he_ij = f.halfedge();\n        HalfedgePtr he_jk = f.halfedge().next();\n        HalfedgePtr he_ki = f.halfedge().prev();\n\n        size_t i = vertexIndices[he_ij.vertex()];\n        size_t j = vertexIndices[he_jk.vertex()];\n        size_t k = vertexIndices[he_ki.vertex()];\n\n        double a = geom->cotan(he_jk);\n        double b = geom->cotan(he_ki);\n        double c = geom->cotan(he_ij);\n\n        std::complex<double> r_ij = r[he_ij];\n        std::complex<double> r_ji = r[he_ij.twin()];\n        std::complex<double> r_jk = r[he_jk];\n        std::complex<double> r_kj = r[he_jk.twin()];\n        std::complex<double> r_ki = r[he_ki];\n        std::complex<double> r_ik = r[he_ki.twin()];\n\n        // row i\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i,b + c));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,j,-c * r_ij));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,k,-b * r_ik));\n\n        // row j\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,i,-c * r_ji));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,j,c + a));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,k,-a * r_jk));\n\n        // row k\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,i,-b * r_ki));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,j,-a * r_kj));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,k,a + b));\n    }\n    A.setFromTriplets(triplets.begin(),triplets.end());\n    return A;\n}\n\nEigen::MatrixXcd Stripes::principalEigenvector(Eigen::SparseMatrix<std::complex<double>> A, Eigen::SparseMatrix<std::complex<double>> B) {\n    // LL^T <- Cholesky(A)\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<std::complex<double>>> solver;\n    solver.compute(A);\n\n    // u <- UniformRand(-1,1)\n    Eigen::MatrixXcd x = Eigen::MatrixXcd::Random(mesh->nVertices(),1);\n\n    // inverse power iteration to find eigenvector belonging to the smallest eigenvalue\n    for (int i = 0; i < nPowerIterations; i++) {\n        x = solver.solve(B * x);\n        std::complex<double> norm2 = (x.transpose() * B * x)(0,0);\n        x = x / sqrt(norm2);\n    }\n    return x;\n} \n\nEigen::MatrixXcd Stripes::principalEigenvector(Eigen::SparseMatrix<double> A, Eigen::SparseMatrix<double> B) {\n    // LL^T <- Cholesky(A)\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n    solver.compute(A);\n\n    // u <- UniformRand(-1,1)\n    Eigen::MatrixXcd x = Eigen::MatrixXcd::Random(2*mesh->nVertices(),1);\n\n    // inverse power iteration to find eigenvector belonging to the smallest eigenvalue\n    for (int i = 0; i < nPowerIterations; i++) {\n        x = solver.solve(B * x);\n        std::complex<double> norm2 = (x.transpose() * B * x)(0,0);\n        x = x / sqrt(norm2);\n    }\n    return x;\n}\n\nVertexData<std::complex<double>> Stripes::computeField() {\n    std::cout << \"Computing Cross Field... \";\n    // Algorithm 1 : Setup\n    setup();\n\n    // Algorithm 2 : Smoothest Field\n    Eigen::SparseMatrix<std::complex<double>> A = assembleA();\n    Eigen::SparseMatrix<std::complex<double>> M = assembleM();\n    A = A + eps * M;\n    Eigen::MatrixXcd x = principalEigenvector(A,M);\n\n    // map resulting vector to VertexData\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (VertexPtr v : mesh->vertices()) {\n        std::complex<double> c = x(vertexIndices[v],0);\n        if (std::abs(c) == 0) {\n            field[v] = 0;\n        } else {\n            field[v] = c / std::abs(c);   \n        }\n    }\n    std::cout << \"Done!\" << std::endl;\n    return field;\n}\n\nFaceData<int> Stripes::computeSingularities() {\n    std::cout << \"Computing Singularities... \";\n    // first, compute Omega_ijk <- arg(r_ij r_jk r_ki)\n    FaceData<double> Omega(mesh);\n    for (FacePtr f : mesh->faces()) {\n        std::complex<double> r_ij = r[f.halfedge()];\n        std::complex<double> r_jk = r[f.halfedge().next()];\n        std::complex<double> r_ki = r[f.halfedge().prev()];\n        Omega[f] = std::arg(r_ij * r_jk * r_ki);\n    }\n\n    // next, compute w_ij for each e_ij, such that u_j = e^iw_ij * r_ij * u_i \n    // w_ij = arg(u_j / (r_ij * u_i))\n    HalfedgeData<double> w(mesh);\n    for (HalfedgePtr he : mesh->allHalfedges()) {\n        std::complex<double> u_i = field[he.vertex()];\n        std::complex<double> u_j = field[he.twin().vertex()];        \n        std::complex<double> r_ij = r[he];\n        w[he] = std::arg(u_j * r_ij / u_i);\n    }\n\n    // finally, compute index for each triangle t\n    // (1/2pi) * (w_ij + w_jk + w_ki + Omega_ijk)\n    int total = 0;\n    for (FacePtr f : mesh->faces()) {\n        double w_ij = w[f.halfedge()];\n        double w_jk = w[f.halfedge().next()];\n        double w_ki = w[f.halfedge().prev()];\n        double Omega_ijk = Omega[f];\n        double phi = (w_ij + w_jk + w_ki - Omega_ijk) / (2.0 * M_PI);\n        singularities[f] = std::round(phi);\n        total += singularities[f];\n    }\n    std::cout << \"Sum: \" << total << std::endl;\n    return singularities;\n}\n\nvoid Stripes::edgeData() {\n    std::cout<< \"Computing EdgeData... \";\n    std::complex<double> i(0, 1);\n    for (EdgePtr e : mesh->edges()) {\n        HalfedgePtr he_ij = e.halfedge();\n        HalfedgePtr he_ji = he_ij.twin();\n\n        // disambiguate the big vectors\n        std::complex<double> f_ij = std::pow(field[he_ij.vertex()], 1.0 / n);\n        std::complex<double> f_ji = std::pow(field[he_ji.vertex()], 1.0 / n);\n        \n        // we need to recompute r_ij here without raising to the nth power, \n        // as raising to the nth power and then taking the nth root is not always an identity operation\n        double theta_ij = phi[he_ij];\n        double theta_ji = phi[he_ij.twin()] + M_PI;\n        double rho_ij = theta_ji - theta_ij;\n        std::complex<double> r_ij = std::exp(i * rho_ij);\n        std::complex<double> s_ij = f_ji / (f_ij * r_ij); \n        double ang = std::arg(s_ij);\n        \n        double sign;\n        if ( ang >= -M_PI_2 && ang < M_PI_2 ) {\n            sign = 1;\n            branchCover[e] = 0;\n        } else {\n            sign = -1;\n            branchCover[e] = 1;\n        }\n    \n        double phi_i = std::arg(f_ij);\n        double phi_j = std::arg(sign * f_ji);\n        double l_ij = geom->length(e);\n        omega[e] = lambda * (l_ij / 2.0) * (cos(phi_i - theta_ij) + cos(phi_j - theta_ji));\n    }\n    std::cout << \"Done!\" << std::endl;\n}\n\nEigen::SparseMatrix<double> Stripes::EnergyMatrix() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<double> A(2*n,2*n);\n    std::vector<Eigen::Triplet<double>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (EdgePtr e : mesh->edges()) {\n        HalfedgePtr he_ij = e.halfedge();\n        \n        // cotan weights\n        double cotA = geom->cotan(he_ij);\n        double cotB = geom->cotan(he_ij.twin());\n        if (singularities[he_ij.face()] != 0) cotA = 0;\n        if (singularities[he_ij.twin().face()] != 0) cotB = 0;\n        double w = (cotA + cotB) / 2.0;\n\n        // indices\n        size_t i = 2 * vertexIndices[he_ij.vertex()];\n        size_t j = 2 * vertexIndices[he_ij.twin().vertex()];\n\n        // add diagonal terms\n        triplets.push_back( Eigen::Triplet<double>(i,i,w) );\n        triplets.push_back( Eigen::Triplet<double>(i+1,i+1,w) );\n        triplets.push_back( Eigen::Triplet<double>(j,j,w) );\n        triplets.push_back( Eigen::Triplet<double>(j+1,j+1,w) );\n\n        // transport coefficient components\n        double x = w * cos(omega[e]);\n        double y = w * sin(omega[e]);\n\n        // stays on same sheet\n        if (branchCover[e] == 0) {\n            // A_ij\n            triplets.push_back( Eigen::Triplet<double>(i,j,-x) ); triplets.push_back( Eigen::Triplet<double>(i,j+1,-y) );\n            triplets.push_back( Eigen::Triplet<double>(i+1,j,y) ); triplets.push_back( Eigen::Triplet<double>(i+1,j+1,-x) );\n            // A_ji\n            triplets.push_back( Eigen::Triplet<double>(j,i,-x) ); triplets.push_back( Eigen::Triplet<double>(j,i+1,y) );\n            triplets.push_back( Eigen::Triplet<double>(j+1,i,-y) ); triplets.push_back( Eigen::Triplet<double>(j+1,i+1,-x) );\n        } else {\n            // A_ij\n            triplets.push_back( Eigen::Triplet<double>(i,j,-x) ); triplets.push_back( Eigen::Triplet<double>(i,j+1,y) );\n            triplets.push_back( Eigen::Triplet<double>(i+1,j,y) ); triplets.push_back( Eigen::Triplet<double>(i+1,j+1,x) );\n            // A_ji\n            triplets.push_back( Eigen::Triplet<double>(j,i,-x) ); triplets.push_back( Eigen::Triplet<double>(j,i+1,y) );\n            triplets.push_back( Eigen::Triplet<double>(j+1,i,y) ); triplets.push_back( Eigen::Triplet<double>(j+1,i+1,x) );\n        }\n    }\n\n    A.setFromTriplets(triplets.begin(),triplets.end());\n    return A;\n}\n\nEigen::SparseMatrix<double> Stripes::MassMatrix() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<double> M(2*n,2*n);\n    std::vector<Eigen::Triplet<double>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he_ij = f.halfedge();\n        size_t i = vertexIndices[he_ij.vertex()];\n        size_t j = vertexIndices[he_ij.next().vertex()];\n        size_t k = vertexIndices[he_ij.prev().vertex()];\n\n        double area = geom->area(f);\n        triplets.push_back(Eigen::Triplet<double>(2*i, 2*i, area/3.));\n        triplets.push_back(Eigen::Triplet<double>(2*i+1, 2*i+1, area/3.));\n        triplets.push_back(Eigen::Triplet<double>(2*j, 2*j, area/3.));\n        triplets.push_back(Eigen::Triplet<double>(2*j+1, 2*j+1, area/3.));\n        triplets.push_back(Eigen::Triplet<double>(2*k, 2*k, area/3.));\n        triplets.push_back(Eigen::Triplet<double>(2*k+1, 2*k+1, area/3.));\n    }\n    M.setFromTriplets(triplets.begin(),triplets.end());\n    return M;\n}\n\nvoid Stripes::computeStripes() {\n    std::cout << \"Computing Stripes... \";\n    Eigen::SparseMatrix<double> A = EnergyMatrix();\n    Eigen::SparseMatrix<double> B = MassMatrix();\n    Eigen::MatrixXcd x = principalEigenvector(A,B);\n    std::cout << \"Done!\" << std::endl;\n    std::cout << x.rows() << \",\" << x.cols() << std::endl;\n}", "meta": {"hexsha": "f04240ee36740d2163e8883aa2b74c3b3c8348e2", "size": 12902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stripes.cpp", "max_stars_repo_name": "connorzl/geometry-central", "max_stars_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stripes.cpp", "max_issues_repo_name": "connorzl/geometry-central", "max_issues_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stripes.cpp", "max_forks_repo_name": "connorzl/geometry-central", "max_forks_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9788519637, "max_line_length": 138, "alphanum_fraction": 0.5809176872, "num_tokens": 3749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5842625981402425}}
{"text": "#pragma once\n// Add a backcheck on the correspondence\n\n\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include \"nanoflannWrapper.hpp\"\n#include \"utils/visualization/progressbar.h\"\n\nEigen::MatrixXd sub_space(const Eigen::MatrixXd &cloud, std::vector<int> indices) {\n    Eigen::MatrixXd out(3, indices.size());\n    for (int i=0; i<indices.size(); i++)\n        out.col(i) = cloud.col(indices.at(i));\n    return out;\n}\n\ntemplate <typename T>\nT median_filter(std::vector<T> vector)\n{\n    std::sort(vector.begin(), vector.end());\n    return vector[ std::round( vector.size()/2 ) ];\n}\n\n\nEigen::Vector3d get_median_point( std::vector<int> pointIdxNKNSearch, Eigen::MatrixXd & cloud )\n{\n    int x=0, y=1, z=2;\n    Eigen::Vector3d median_point;\n    std::vector< double > x_vector, y_vector, z_vector;\n    for (int i=0; i<pointIdxNKNSearch.size(); ++i)\n    {\n        x_vector.push_back( cloud(pointIdxNKNSearch[i], x) );\n        y_vector.push_back( cloud(pointIdxNKNSearch[i], y) );\n        z_vector.push_back( cloud(pointIdxNKNSearch[i], z) );\n    }\n    median_point(x) = median_filter(x_vector);\n    median_point(y) = median_filter(y_vector);\n    median_point(z) = median_filter(z_vector);\n    return median_point;\n}\n\n\nEigen::Vector3d point_association(std::string method, \n                                Eigen::Vector3d p_i, \n                                Eigen::Vector3d n_i, \n\t                            Eigen::MatrixXd & P,\n\t                            Eigen::MatrixXd & N)\n{\n    // used for readability\n    int x=0, y=1, z=2;\n\tEigen::VectorXd points_dist(P.cols());\n\tEigen::VectorXd normals_dist(P.cols());\n\tfor (int i = 0; i < P.cols(); ++i)\n\t{\n\t\tpoints_dist(i) = sqrt( (p_i(x) - P.col(i)(x)) * (p_i(x) - P.col(i)(x))\n\t\t\t                  +(p_i(y) - P.col(i)(y)) * (p_i(y) - P.col(i)(y))\n\t\t\t                  +(p_i(z) - P.col(i)(z)) * (p_i(z) - P.col(i)(z)));\n\t\tnormals_dist(i) = n_i(x)*N.col(i)(x) \n\t\t                + n_i(y)*N.col(i)(y) \n\t\t                + n_i(z)*N.col(i)(z);\n\t}\n\tEigen::MatrixXd::Index pointIndex;\n\tif (method == \"closest_point\")\n\t{\n\t\tpoints_dist.minCoeff(&pointIndex);\n\t}\n\tif (method == \"normals_distances\")\n\t{\n\t\tnormals_dist.maxCoeff(&pointIndex);\n\t}\n\tif (method == \"weighted\")\n\t{\n\t\t( points_dist/0.1 - normals_dist ).minCoeff(&pointIndex);\n\t}\n\tif (method == \"hybrid\")\n\t{\n\t\t//pointIndex = ( points_dist.array().pow(31)/normals_dist ).maxCoeff(&pointIndex);\n\t\tpointIndex = 1;\n\t\t//pointIndex = ( pow(points_dist, 31)/normals_dist ).maxCoeff(&pointIndex);\n\t}\n\n    return P.row(pointIndex);\n}\n\n\nint find_correspondence(std::string method, \n                        Eigen::Vector3d v, \n                        Eigen::Vector3d n, \n\t                    const Eigen::MatrixXd & cloud,\n\t                    const Eigen::MatrixXd & normals,\n                        nanoflann_wrapper kd_tree,\n                        int K)\n{\n    // downsampling of the cloud and normals with K closest points\n    std::vector<int> closest_point_indices(K);\n    closest_point_indices = kd_tree.return_k_closest_points(v, K);\n    Eigen::MatrixXd sample_cloud = sub_space(cloud, closest_point_indices);\n    Eigen::MatrixXd sample_normals = sub_space(normals, closest_point_indices);\n\n    // build the distance between points and normals\n    int x=0, y=1, z=2;\n    Eigen::VectorXd points_distance(cloud.cols());\n\tEigen::VectorXd normals_distance(cloud.cols());\n    for (int i = 0; i < cloud.cols(); ++i)\n\t{\n\t\tpoints_distance(i) = sqrt( (v(x) - cloud.col(i)(x)) * (v(x) - cloud.col(i)(x))\n\t\t\t                      +(v(y) - cloud.col(i)(y)) * (v(y) - cloud.col(i)(y))\n\t\t\t                      +(v(z) - cloud.col(i)(z)) * (v(z) - cloud.col(i)(z)));\n\t\tnormals_distance(i) = n(x)*normals.col(i)(x) \n\t\t                    + n(y)*normals.col(i)(y) \n\t\t                    + n(z)*normals.col(i)(z);\n\t}\n\n    // return the min distance according to the selected method\n\tEigen::MatrixXd::Index pointIndex;\n\tif (method == \"closest_point\")\n\t{\n\t\tpoints_distance.minCoeff(&pointIndex);\n\t}\n\tif (method == \"normals_distances\")\n\t{\n\t\tnormals_distance.maxCoeff(&pointIndex);\n\t}\n\tif (method == \"weighted\")\n\t{\n\t\t( points_distance/0.1 - normals_distance ).minCoeff(&pointIndex);\n\t}\n\n    return pointIndex;\n}\n\n\n\nvoid get_surface_association(Eigen::MatrixXd V_source, Eigen::MatrixXd N_source,\n                             Eigen::MatrixXd V_target, Eigen::MatrixXd N_target,\n                             Eigen::MatrixXd &source_position,\n                             Eigen::MatrixXd &target_position)\n{\n    // this need to be moved out of hardcoded parameters into config file\n    int x=0, y=1, z=2;                                  // used to access the points\n    double distance_threshold = 0.05;                   // used to check that the correspondence of the correspondence is not too far\n    int skip_points = 5;                               // pseudo downsampling\n    int K = 50;                                         // limit the search space\n    \n    std::vector<Eigen::Vector3d> correspondences_on_source;\n    std::vector<Eigen::Vector3d> correspondences_on_target;\n    \n    nanoflann_wrapper tree_target(V_target.transpose());\n    nanoflann_wrapper tree_source(V_source.transpose());\n    std::vector<int> closest_point_indices(K);\n\n    // for loop\n    progressbar bar(V_source.cols()/skip_points);\n    for (int i = 0; i < V_source.cols(); i = i+skip_points) {\n        int point_index_original = i*skip_points;\n\n        // find the correspondence of the source on the target\n        int correspondence_on_target = find_correspondence(\"weighted\", \n                                                           V_source.col(point_index_original),\n                                                           N_source.col(point_index_original), \n\t                                                       V_target,\n\t                                                       N_target,\n                                                           tree_target,\n                                                           K);\n\n        // find the correspondence of the source on the target\n        int correspondence_on_source = find_correspondence(\"weighted\", \n                                                           V_target.col(correspondence_on_target),\n                                                           N_target.col(correspondence_on_target), \n\t                                                       V_source,\n\t                                                       N_source,\n                                                           tree_source,\n                                                           K);\n\n        // check the distance between the points\n        if ( (V_source.col(point_index_original)-V_source.col(correspondence_on_source)).norm() < distance_threshold ) {\n            correspondences_on_source.push_back(V_source.col(point_index_original));\n            correspondences_on_target.push_back(V_target.col(correspondence_on_target));\n        }\n\n        bar.update();\n    }\n\n    // push back into an Eigen Matrices\n    source_position.resize(3, correspondences_on_source.size());\n    for (int i=0; i<correspondences_on_source.size(); i++)\n        source_position.col(i) = correspondences_on_source.at(i);\n    \n    target_position.resize(3, correspondences_on_target.size());\n    for (int i=0; i<correspondences_on_target.size(); i++)\n        target_position.col(i) = correspondences_on_target.at(i);\n    \n    /*\n    int x=0, y=1, z=2;\n    //for (int i = 0; i < template_cloud->size(); i = i+10)\n    //{\n    //    template_cloud_downsampled->points.push_back(template_cloud->points[i]);\n    //    template_normals_downsampled->points.push_back(template_normals->points[i]);\n    //}\n    double distance_threshold = 0.05;                   // used to check that the correspondence of the correspondence is not too far\n    int skip_points = 10;                               // pseudo downsampling\n    int K = 50;                                         // limit the search space\n    int number_of_correspondences = int(round(V_source.cols()/skip_points));\n\n    // generate downsampled cloud\n    Eigen::MatrixXd V_source_downsampled, N_source_downsampled;\n    V_source_downsampled.resize(3, number_of_correspondences);\n    N_source_downsampled.resize(3, number_of_correspondences);\n    for (int i = 0; i < number_of_correspondences; i++) {\n        V_source_downsampled.col(i) = V_source.col(i*skip_points);\n        N_source_downsampled.col(i) = N_source.col(i*skip_points);\n    }\n\n    // create kd-tree\n    nanoflann_wrapper tree(V_target.transpose());\n    std::vector<int> pointIdxNKNSearch(K);\n    std::vector<float> pointNKNSquaredDistance(K);\n\n    pointIdxNKNSearch.clear();\n\n    Eigen::Vector3d median_point;\n\n    source_position.resize(3, number_of_correspondences);\n    target_position.resize(3, number_of_correspondences);\n\n\n    for (int i = 0; i < number_of_correspondences; i++)\n    {\n        // WTF this is not used ????? LOOOOL\n\t\tpointIdxNKNSearch = tree.return_k_closest_points(V_source.col(i*skip_points).transpose(), K);\n\n        //median_point = point_association(\"closest_point\",\n        //                                    V_source.col(i*skip_points),\n        //                                    N_source.col(i*skip_points),\n        //                                    V_target,\n        //                                    N_target);\n        \n        median_point = V_target.col(pointIdxNKNSearch[0]);\n        \n        target_position.col(i) <<  median_point(x), median_point(y), median_point(z);\n        source_position.col(i) << V_source.col(i*skip_points)(x),\n                                  V_source.col(i*skip_points)(y),\n                                  V_source.col(i*skip_points)(z);\n    }\n    */\n}\n\n", "meta": {"hexsha": "e06724f896b91e0b31ba27a49366c134860cc13b", "size": 9742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "embedded_deformation/include/embedded_deformation/surface_association.hpp", "max_stars_repo_name": "jessemorris/embedded_deformation", "max_stars_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T23:42:04.000Z", "max_issues_repo_path": "embedded_deformation/include/embedded_deformation/surface_association.hpp", "max_issues_repo_name": "jessemorris/embedded_deformation", "max_issues_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-24T11:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T02:11:05.000Z", "max_forks_repo_path": "embedded_deformation/include/embedded_deformation/surface_association.hpp", "max_forks_repo_name": "jessemorris/embedded_deformation", "max_forks_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T10:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:38:35.000Z", "avg_line_length": 39.124497992, "max_line_length": 133, "alphanum_fraction": 0.5665161158, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5842155680064486}}
{"text": "#pragma once\n\n#include <fftw3.h>\n#include <complex>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <type_traits>\n\n#include \"shift.hpp\"\n\n\ntemplate <typename D1, typename D2>\nstruct enable_if_cc\n    : public std::enable_if<std::is_same<typename D1::Scalar, std::complex<double>>::value &&\n                            std::is_same<typename D2::Scalar, std::complex<double>>::value>\n{\n};\n\ntemplate <typename D1, typename D2>\nstruct enable_if_cr\n    : public std::enable_if<std::is_same<typename D1::Scalar, std::complex<double>>::value &&\n                            std::is_same<typename D2::Scalar, double>::value>\n{\n};\n\ntemplate <typename D1, typename D2>\nstruct enable_if_rc\n    : public std::enable_if<std::is_same<typename D1::Scalar, double>::value &&\n                            std::is_same<typename D2::Scalar, std::complex<double>>::value>\n{\n};\n\nstruct FFT\n{\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n  typedef Eigen::Array<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      complex_array_t;\n\n  typedef std::complex<double> cdouble;\n\n  /**\n   * @brief forward transform\n   *\n   * @param[out] dst\n   * @param[in] src\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cr<DERIVED1, DERIVED2>::type fft2(Eigen::DenseBase<DERIVED1> &dst,\n                                                       const Eigen::DenseBase<DERIVED2> &src,\n                                                       bool scale = true) const;\n\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cc<DERIVED1, DERIVED2>::type fft2(Eigen::DenseBase<DERIVED1> &dst,\n                                                       const Eigen::DenseBase<DERIVED2> &src,\n                                                       bool scale = true) const;\n\n  /**\n   * @brief inverse transform (does not preserve input)\n   *\n   * @param[out] dst\n   * @param[in] src   full spectrum\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_rc<DERIVED1, DERIVED2>::type ifft2(Eigen::DenseBase<DERIVED1> &dst,\n                                                        Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n  * @brief ifft2 (c -> r)\n  *\n  * @param[out] dst  dest\n  * @param[in] src  will be overwritten by FFTW!\n  */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cr<DERIVED1, DERIVED2>::type ifft2(Eigen::DenseBase<DERIVED1> &dst,\n                                                        Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n   * @brief ifft2 (c -> c)\n   *\n   * @param[out] dst  destination\n   * @param[in] src  will be overwritten by FFTW!\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cc<DERIVED1, DERIVED2>::type ifft2(Eigen::DenseBase<DERIVED1> &dst,\n                                                        Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n   * @brief 2-dim fft (including fftshift)\n   *\n   * @param[out] dst  complex array (centered zero-frequency convention)\n   * @param[in] src   real array\n   * @param[in] scale if true: scales output by 1/numel(src)\n   *\n   * This is the inverse of ift for \\var scale set to false.\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cr<DERIVED1, DERIVED2>::type ft(Eigen::DenseBase<DERIVED1> &dst,\n                                                     const Eigen::DenseBase<DERIVED2> &src,\n                                                     bool scale = true) const;\n\n  /**\n   * complex, complex\n   * @brief fft2 (including fftshift)\n   *\n   * @param[out] dst (in centered zero-frequency convention)\n   * @param[int] src\n   * @param bool  if true: scales output by 1/numel(src)\n   *\n   * This is the inverse of ift for \\var scale set to false.\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cc<DERIVED1, DERIVED2>::type ft(Eigen::DenseBase<DERIVED1> &dst,\n                                                     const Eigen::DenseBase<DERIVED2> &src,\n                                                     bool scale = true) const;\n\n  /**\n   * real, complex\n   *\n   * @brief ifft2 (including ifftshift)\n   *\n   * @param[out] dst   real array\n   * @param[in] src   complex array\n   *\n   * Scales the output by 1/numel(src). Inverse of ft(dst, src, scale=false).\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_rc<DERIVED1, DERIVED2>::type ift(Eigen::DenseBase<DERIVED1> &dst,\n                                                      const Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n   * complex, complex\n   * @brief complex ifft2 (including ifftshift)\n   *\n   * @param[out] dst\n   * @param[in] src\n   *\n   * Scales the output by 1/numel(src). Inverse of ft(dst, src, scale=false).\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename enable_if_cc<DERIVED1, DERIVED2>::type ift(Eigen::DenseBase<DERIVED1> &dst,\n                                                      const Eigen::DenseBase<DERIVED2> &src) const;\n};\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cr<DERIVED1, DERIVED2>::type\nFFT::fft2(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, bool scale) const\n{\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n  // typedef double fftw_cdouble[2];\n  typedef fftw_complex fftw_cdouble;\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n  int embed[2] = {n0, n1};\n  dst.derived().resize(n0, n1);\n  int flags = FFTW_PRESERVE_INPUT | FFTW_ESTIMATE;\n  fftw_cdouble *out = reinterpret_cast<fftw_cdouble *>(dst.derived().data());\n  double *in = const_cast<double *>(src.derived().data());\n  fftw_plan fwd_plan = fftw_plan_many_dft_r2c(2 /* rank */,\n                                              n /* dims */,\n                                              1 /* num dfts */,\n                                              in,\n                                              embed,\n                                              1 /* stride */,\n                                              embed[0] * embed[1],\n                                              out,\n                                              embed,\n                                              1 /*stride */,\n                                              embed[0] * embed[1],\n                                              flags);\n  assert(fwd_plan != NULL);\n  fftw_execute(fwd_plan);\n\n  // mirror coefficients\n  for (int i = 0; i < n0; ++i) {\n    int idest = (n0 - i) % n0;\n    for (int j = 1; j < n1 / 2 + n1 % 2; ++j) {\n      dst(idest, n1 - j) = std::conj(dst(i, j));\n    }\n  }\n  if (scale) {\n    double f = 1. / (n0 * n1);\n    dst *= f;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cc<DERIVED1, DERIVED2>::type\nFFT::fft2(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, bool scale) const\n{\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  dst.derived().resize(n0, n1);\n  fftw_complex *in =\n      const_cast<fftw_complex *>(reinterpret_cast<const fftw_complex *>(src.derived().data()));\n  fftw_complex *out = reinterpret_cast<fftw_complex *>(dst.derived().data());\n  unsigned int flags = FFTW_ESTIMATE | FFTW_PRESERVE_INPUT;\n  fftw_plan inv_plan = fftw_plan_dft_2d(n0, n1, in, out, FFTW_FORWARD, flags);\n\n  assert(inv_plan != NULL);\n  fftw_execute(inv_plan);\n  if (scale) {\n    double f = 1. / (n0 * n1);\n    dst *= f;\n  }\n}\n\n// ----------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_rc<DERIVED1, DERIVED2>::type\nFFT::ifft2(Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const\n{\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n  // typedef double fftw_cdouble[2];\n  typedef fftw_complex fftw_cdouble;\n\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n  dst.derived().resize(n0, n1);\n  fftw_cdouble *in = reinterpret_cast<fftw_cdouble *>(src.derived().data());\n  double *out = dst.derived().data();\n  int embed[2] = {n0, n1};\n  unsigned int flags = FFTW_ESTIMATE;\n  fftw_plan inv_plan = fftw_plan_many_dft_c2r(\n      2, n, 1, in, embed, 1, embed[0] * embed[1], out, embed, 1, embed[0] * embed[1], flags);\n  assert(inv_plan != NULL);\n  fftw_execute(inv_plan);\n\n  double f = 1. / (n0 * n1);\n  dst *= f;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cc<DERIVED1, DERIVED2>::type\nFFT::ifft2(Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const\n{\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n\n  dst.derived().resize(n0, n1);\n\n  fftw_complex *in = reinterpret_cast<fftw_complex *>(src.derived().data());\n  fftw_complex *out = reinterpret_cast<fftw_complex *>(dst.derived().data());\n  unsigned int flags = FFTW_ESTIMATE;\n  // fftw_plan fftw_plan_dft_2d(int n0, int n1,\n  //                          fftw_complex *in, fftw_complex *out,\n  //                          int sign, unsigned flags);\n  fftw_plan inv_plan = fftw_plan_dft_2d(n0, n1, in, out, FFTW_BACKWARD, flags);\n\n  assert(inv_plan != NULL);\n  fftw_execute(inv_plan);\n  double f = 1. / (n0 * n1);\n  dst *= f;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cr<DERIVED1, DERIVED2>::type\nFFT::ifft2(Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const\n{\n  // not implemented\n  throw 1;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cr<DERIVED1, DERIVED2>::type\nFFT::ft(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, bool scale) const\n{\n  complex_array_t tmp(src.rows(), src.cols());\n  this->fft2(tmp, src, scale);\n  dst.derived().resize(tmp.rows(), tmp.cols());\n  fftshift(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cc<DERIVED1, DERIVED2>::type\nFFT::ft(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src, bool scale) const\n{\n  complex_array_t tmp(src.rows(), src.cols());\n  this->fft2(tmp, src, scale);\n  dst.derived().resize(tmp.rows(), tmp.cols());\n  fftshift(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_rc<DERIVED1, DERIVED2>::type\nFFT::ift(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const\n{\n  complex_array_t tmp(src.rows(), src.cols());\n  ifftshift(tmp, src);\n  this->ifft2(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename enable_if_cc<DERIVED1, DERIVED2>::type\nFFT::ift(Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const\n{\n  complex_array_t tmp(src.rows(), src.cols());\n  ifftshift(tmp, src);\n  this->ifft2(dst, tmp);\n}\n", "meta": {"hexsha": "e4a9c237ad27cd5fe46c8a13ef0b89ce2816700d", "size": 11478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/fft2.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": "fft/fft2.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": "fft/fft2.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": 36.2082018927, "max_line_length": 99, "alphanum_fraction": 0.5615960969, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5842155560563658}}
{"text": "#include \"constants.h\"\n#include \"inset_state.h\"\n#include \"interpolate_bilinearly.h\"\n#include <boost/multi_array.hpp>\n#include <omp.h>\n\n// Function to calculate the velocity at the grid points (x, y) with x =\n// 0.5, 1.5, ..., lx-0.5 and y = 0.5, 1.5, ..., ly-0.5 at time t\nvoid calculate_velocity(\n    double t,\n    FTReal2d &grid_fluxx_init,\n    FTReal2d &grid_fluxy_init,\n    FTReal2d &rho_ft,\n    FTReal2d &rho_init,\n    boost::multi_array<double, 2> *grid_vx,\n    boost::multi_array<double, 2> *grid_vy,\n    const unsigned int lx,\n    const unsigned int ly\n) {\n  double rho;\n\n#pragma omp parallel for private(rho)\n  for (unsigned int i = 0; i < lx; ++i) {\n    for (unsigned int j = 0; j < ly; ++j) {\n      rho = rho_ft(0, 0) + (1.0 - t) * (rho_init(i, j) - rho_ft(0,0));\n      (*grid_vx)[i][j] = -grid_fluxx_init(i, j) / rho;\n      (*grid_vy)[i][j] = -grid_fluxy_init(i, j) / rho;\n    }\n  }\n  return;\n}\n\nbool all_points_are_in_domain(\n    double delta_t,\n    boost::multi_array<XYPoint, 2> *proj,\n    boost::multi_array<XYPoint, 2> *v_intp,\n    const unsigned int lx,\n    const unsigned int ly\n) {\n  // Return false if and only if there exists a point that would be outside\n  // [0, lx] x [0, ly]\n  for (unsigned int i = 0; i < lx; ++i) {\n    for (unsigned int j = 0; j < ly; ++j) {\n      double x = (*proj)[i][j].x + 0.5 * delta_t * (*v_intp)[i][j].x;\n      double y = (*proj)[i][j].y + 0.5 * delta_t * (*v_intp)[i][j].y;\n      if (x < 0.0 || x > lx || y < 0.0 || y > ly) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n// Function to integrate the equations of motion with the fast flow-based\n// method\nvoid InsetState::flatten_density()\n{\n  std::cerr << \"In flatten_density()\" << std::endl;\n\n  // Constants for the numerical integrator\n  const double inc_after_acc = 1.1;\n  const double dec_after_not_acc = 0.75;\n  const double abs_tol = (std::min(lx_, ly_) * 1e-6);\n\n  // Resize proj_ multi-array if running for the first time\n  if (proj_.shape()[0] != lx_ || proj_.shape()[1] != ly_) {\n    proj_.resize(boost::extents[lx_][ly_]);\n  }\n  for (unsigned int i = 0; i < lx_; ++i) {\n    for (unsigned int j = 0; j < ly_; ++j) {\n      proj_[i][j].x = i + 0.5;\n      proj_[i][j].y = j + 0.5;\n    }\n  }\n\n  // Allocate memory for the velocity grid\n  boost::multi_array<double, 2> grid_vx(boost::extents[lx_][ly_]);\n  boost::multi_array<double, 2> grid_vy(boost::extents[lx_][ly_]);\n\n  // Prepare Fourier transforms for the flux\n  FTReal2d grid_fluxx_init;\n  FTReal2d grid_fluxy_init;\n  grid_fluxx_init.allocate(lx_, ly_);\n  grid_fluxy_init.allocate(lx_, ly_);\n  grid_fluxx_init.make_fftw_plan(FFTW_RODFT01, FFTW_REDFT01);\n  grid_fluxy_init.make_fftw_plan(FFTW_REDFT01, FFTW_RODFT01);\n\n  // eul[i][j] will be the new position of proj_[i][j] proposed by a simple\n  // Euler step: move a full time interval delta_t with the velocity at time t\n  // and position (proj_[i][j].x, proj_[i][j].y)\n  boost::multi_array<XYPoint, 2> eul(boost::extents[lx_][ly_]);\n\n  // mid[i][j] will be the new displacement proposed by the midpoint\n  // method (see comment below for the formula)\n  boost::multi_array<XYPoint, 2> mid(boost::extents[lx_][ly_]);\n\n  // (vx_intp, vy_intp) will be the velocity at position (proj_.x, proj_.y) at\n  // time t\n  boost::multi_array<XYPoint, 2> v_intp(boost::extents[lx_][ly_]);\n\n  // (vx_intp_half, vy_intp_half) will be the velocity at the midpoint\n  // (proj_.x + 0.5*delta_t*vx_intp, proj_.y + 0.5*delta_t*vy_intp) at time\n  // t + 0.5*delta_t\n  boost::multi_array<XYPoint, 2> v_intp_half(boost::extents[lx_][ly_]);\n\n  // Initialize the Fourier transforms of gridvx[] and gridvy[] at\n  // every point on the lx_-times-ly_ grid at t = 0. We must typecast lx_ and ly_\n  // as double-precision numbers. Otherwise the ratios in the denominator\n  // will evaluate as zero.\n  double dlx = lx_;\n  double dly = ly_;\n\n  // We temporarily insert the Fourier coefficients for the x-components and\n  // y-components of the flux vector into grid_fluxx_init and grid_fluxy_init.\n  // The reason for `+1` in `di+1` stems from the RODFT10 formula at:\n  // https://www.fftw.org/fftw3_doc/1d-Real_002dodd-DFTs-_0028DSTs_0029.html\n  for (unsigned int i = 0; i < lx_-1; ++i) {\n    double di = i;\n    for (unsigned int j = 0; j < ly_; ++j) {\n      double denom = pi * ((di+1)/dlx + (j/(di+1)) * (j/dly) * (dlx/dly));\n      grid_fluxx_init(i, j) =\n        -rho_ft_(i+1, j) / denom;\n    }\n  }\n  for (unsigned int j = 0; j < ly_; ++j) {\n    grid_fluxx_init(lx_-1, j) = 0.0;\n  }\n  for (unsigned int i=0; i<lx_; ++i) {\n    double di = i;\n    for (unsigned int j = 0; j < ly_-1; ++j) {\n      double denom = pi * ((di/(j+1)) * (di/dlx) * (dly/dlx) + (j+1)/dly);\n      grid_fluxy_init(i, j) =\n        -rho_ft_(i, j+1) / denom;\n    }\n  }\n  for (unsigned int i=0; i<lx_; ++i) {\n    grid_fluxy_init(i, ly_-1) = 0.0;\n  }\n\n  // Compute the flux vector and store the result in grid_fluxx_init and\n  // grid_fluxy_init\n  grid_fluxx_init.execute_fftw_plan();\n  grid_fluxy_init.execute_fftw_plan();\n  double t = 0.0;\n  double delta_t = 1e-2;  // Initial time step.\n  unsigned int iter = 0;\n\n  // Integrate\n  while (t < 1.0) {\n    calculate_velocity(\n      t,\n      grid_fluxx_init,\n      grid_fluxy_init,\n      rho_ft_,\n      rho_init_,\n      &grid_vx,\n      &grid_vy,\n      lx_,\n      ly_\n    );\n#pragma omp parallel for\n    for (unsigned int i = 0; i < lx_; ++i) {\n      for (unsigned int j = 0; j < ly_; ++j) {\n\n        // We know, either because of the initialization or because of the\n        // check at the end of the last iteration, that (proj_.x, proj_.y)\n        // is inside the rectangle [0, lx_] x [0, ly_]. This fact guarantees\n        // that interpolate_bilinearly() is given a point that cannot cause it\n        // to fail.\n        v_intp[i][j].x = interpolate_bilinearly(\n          proj_[i][j].x,\n          proj_[i][j].y,\n          &grid_vx,\n          'x',\n          lx_,\n          ly_\n        );\n        v_intp[i][j].y = interpolate_bilinearly(\n          proj_[i][j].x,\n          proj_[i][j].y,\n          &grid_vy,\n          'y',\n          lx_,\n          ly_\n        );\n      }\n    }\n    bool accept = false;\n    while (!accept) {\n\n      // Simple Euler step.\n\n#pragma omp parallel for\n      for (unsigned int i = 0; i < lx_; ++i) {\n        for (unsigned int j = 0; j < ly_; ++j) {\n          eul[i][j].x = proj_[i][j].x + v_intp[i][j].x * delta_t;\n          eul[i][j].y = proj_[i][j].y + v_intp[i][j].y * delta_t;\n        }\n      }\n\n      // Use \"explicit midpoint method\"\n      // x <- x + delta_t * v_x(x + 0.5*delta_t*v_x(x,y,t),\n      //                        y + 0.5*delta_t*v_y(x,y,t),\n      //                        t + 0.5*delta_t)\n      // and similarly for y.\n      calculate_velocity(\n        t + 0.5*delta_t,\n        grid_fluxx_init,\n        grid_fluxy_init,\n        rho_ft_,\n        rho_init_,\n        &grid_vx,\n        &grid_vy,\n        lx_,\n        ly_\n      );\n\n      // Make sure we do not pass a point outside [0, lx_] x [0, ly_] to\n      // interpolate_bilinearly(). Otherwise decrease the time step below and\n      // try again.\n      accept = all_points_are_in_domain(delta_t, &proj_, &v_intp, lx_, ly_);\n      if (accept) {\n\n        // Okay, we can run interpolate_bilinearly()\n\n#pragma omp parallel for\n        for (unsigned int i = 0; i < lx_; ++i) {\n          for (unsigned int j = 0; j < ly_; ++j) {\n            v_intp_half[i][j].x = interpolate_bilinearly(\n              proj_[i][j].x + 0.5*delta_t*v_intp[i][j].x,\n              proj_[i][j].y + 0.5*delta_t*v_intp[i][j].y,\n              &grid_vx,\n              'x',\n              lx_,\n              ly_\n            );\n            v_intp_half[i][j].y = interpolate_bilinearly(\n              proj_[i][j].x + 0.5*delta_t*v_intp[i][j].x,\n              proj_[i][j].y + 0.5*delta_t*v_intp[i][j].y,\n              &grid_vy,\n              'y',\n              lx_,\n              ly_\n            );\n            mid[i][j].x = proj_[i][j].x + v_intp_half[i][j].x * delta_t;\n            mid[i][j].y = proj_[i][j].y + v_intp_half[i][j].y * delta_t;\n\n            // Do not accept the integration step if the maximum squared\n            // difference between the Euler and midpoint proposals exceeds\n            // abs_tol. Neither should we accept the integration step if one\n            // of the positions wandered out of the domain. If one of these\n            // problems occurred, decrease the time step.\n            const double sq_dist =\n              (mid[i][j].x-eul[i][j].x) * (mid[i][j].x-eul[i][j].x)\n              + (mid[i][j].y-eul[i][j].y) * (mid[i][j].y-eul[i][j].y);\n            if (sq_dist > abs_tol ||\n                mid[i][j].x < 0.0 || mid[i][j].x > lx_ ||\n                mid[i][j].y < 0.0 || mid[i][j].y > ly_) {\n              accept = false;\n            }\n          }\n        }\n      }\n      if (!accept) {\n        delta_t *= dec_after_not_acc;\n      }\n    }\n\n    // Control ouput\n    if (iter % 10 == 0) {\n      std::cerr << \"iter = \"\n                << iter\n                << \", t = \"\n                << t\n                << \", delta_t = \"\n                << delta_t\n                << \"\\n\";\n    }\n\n    // When we get here, the integration step was accepted\n    t += delta_t;\n    ++iter;\n    proj_ = mid;\n    delta_t *= inc_after_acc;  // Try a larger step next time\n  }\n  grid_fluxx_init.destroy_fftw_plan();\n  grid_fluxy_init.destroy_fftw_plan();\n  grid_fluxx_init.free();\n  grid_fluxy_init.free();\n  return;\n}\n", "meta": {"hexsha": "f83be4bac2c4d723b698e74ceefe6d8f6862d707", "size": 9414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inset_state/flatten_density.cpp", "max_stars_repo_name": "mgastner/cartogram-cpp", "max_stars_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inset_state/flatten_density.cpp", "max_issues_repo_name": "mgastner/cartogram-cpp", "max_issues_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-03-13T02:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T09:53:52.000Z", "max_forks_repo_path": "src/inset_state/flatten_density.cpp", "max_forks_repo_name": "mgastner/cartogram-cpp", "max_forks_repo_head_hexsha": "007e4cf87c9590abef280feb43052280c454a0c5", "max_forks_repo_licenses": ["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.2397260274, "max_line_length": 81, "alphanum_fraction": 0.5591671978, "num_tokens": 3022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5842155518051121}}
{"text": "/** \\file  TSBinomialExample.cpp\r\n    \\brief Test and demonstration program.\r\n           Copyright 2006, 2015 by Erik Schloegl \r\n     */\r\n\r\n#include <iostream>\r\n#include <cstdlib>\r\n#include <boost/bind.hpp>\r\n#include \"GaussianHJM.hpp\"\r\n#include \"TSBinomial.hpp\"\r\n#include \"QFArrayUtil.hpp\"\r\n#include \"TSPayoff.hpp\"\r\n#include \"TSInstruments.hpp\"\r\n#include \"ExponentialVol.hpp\"\r\n\r\nusing namespace quantfin; \r\n \r\ninline double positivePart(double x)\r\n{\r\n  return (x>0.0) ? x : 0.0;      \r\n}\r\n\r\n/** Test and demonstration for HJM implementation.\r\n\r\n    Command-line arguments:\r\n      -# interest rate. \r\n      -# volatility.\r\n      -# number of time steps.\r\n      -# maturity.\r\n      -# moneyness.\r\n  */\r\nint main(int argc,char* argv[]) \r\n{\r\n  using std::cout;\r\n  using std::endl;\r\n  using std::flush;\r\n\r\n  int i,j;\r\n  try {\r\n    double r = 0.05;\r\n    if (argc>1) r = atof(argv[1]);\r\n    double sgm = 0.3;\r\n    if (argc>2) sgm = atof(argv[2]);\r\n    int N = 10;\r\n    if (argc>3) N = atoi(argv[3]);\r\n    double mat = 1.5;\r\n    if (argc>4) mat = atof(argv[4]);\r\n    double K = 1.0;\r\n    if (argc>5) K = atof(argv[5]);\r\n    FlatTermStructure flat_ts(r,0.0,mat+10.0);\r\n    Array<double,1> T(9);\r\n    double T1 = mat;\r\n    double T2 = T1 + 5.0;\r\n    firstIndex idx;\r\n    Array<double,1> SaSoT(N+1);\r\n    double dtSaSo = T2/N;\r\n    SaSoT = idx * dtSaSo;\r\n    int iseg = find_segment(T1,SaSoT);\r\n    if (std::abs(T1-SaSoT(iseg))>std::abs(T1-SaSoT(iseg+1))) iseg++;\r\n    T1 = SaSoT(iseg);\r\n    double strike = K * flat_ts(T2)/flat_ts(T1);\r\n    double ZCBstrike = strike;\r\n    /// Test SaSo binomial method\r\n    cout << \"Creating SaSo lattice... \" << SaSoT << endl;\r\n    TSBinomialMethod SaSo(flat_ts,sgm,SaSoT); \r\n    cout << \"Rolling back term structures... \" << endl;\r\n    SaSo.rollbackTermstructures();\r\n    cout << \"SaSo verified: \" << SaSo.verify() << endl;\r\n    ZCBoption zcbpayoff(ZCBstrike,T2);\r\n    boost::function<double (const TermStructure& ts)> f;\r\n    f = boost::bind(std::mem_fun(&ZCBoption::operator()),&zcbpayoff,_1);\r\n    SaSo.apply_payoff(iseg,f);\r\n    SaSo.rollback(iseg,0);\r\n    cout << \"SaSo lattice ZCB call: \" << SaSo.result() << endl;\r\n    SaSo.apply_payoff(iseg,f);\r\n    SaSo.rollback(iseg);\r\n    cout << \"SaSo lattice ZCB call using state prices: \" << SaSo.result() << endl;\r\n    cout << \"Attempting to reproduce Figure 8.4 of Clewlow/Strickland...\" << endl;\r\n    Array<double,1> CST(5);\r\n    CST = idx;\r\n    cout << \"Time line: \" << CST << endl;\r\n    Array<double,1> PDB(5);\r\n    PDB(0) = 1.0;\r\n    for (i=1;i<5;i++) PDB(i) = PDB(i-1)/1.05;\r\n    cout << \"Initial bonds: \" << PDB << endl;\r\n    TSLogLinear CSts(CST,PDB);\r\n    TSBinomialMethod CSmodel(CSts,0.1,CST);\r\n\tcout << \"Short rates:\" << endl;\r\n\tfor (i=0;i<4;i++) {\r\n\t  for (j=0;j<=i;j++) {\r\n\t\tcout << CSmodel.short_rate(i,j) << ','; }\r\n\t  cout << endl; }\r\n\tcout << \"State prices:\" << endl;\r\n\tfor (i=0;i<4;i++) {\r\n\t  for (j=0;j<=i;j++) {\r\n\t\tcout << CSmodel.state_price(i,j) << ','; }\r\n\t  cout << endl; }\r\n    cout << \"Testing calibration to caplets...\" << endl;\r\n    double mr = 0.1;\r\n    ExponentialVol evol(sgm/10.0,mr);\r\n    GaussianHJM emodel(&evol,&CSts);\r\n    std::vector<TSEuropeanInstrument*> caplets,floorlets;    \r\n    double delta    = CST(2)-CST(1);\r\n    double lvl      = CSts.simple_rate(CST(1),delta);\r\n\tdouble floorlvl = lvl;\r\n    Caplet caplet1(emodel.caplet(CST(1),delta,lvl),CST(0),CST(1),lvl,delta);\r\n    cout << caplet1.price() << ' ' << flush;\r\n    caplets.push_back(&caplet1);\r\n    Floorlet floorlet1(-1.0,CST(0),CST(1),floorlvl,delta);\r\n    floorlets.push_back(&floorlet1);\r\n    delta = CST(3)-CST(2);\r\n    lvl   = CSts.simple_rate(CST(2),delta);\r\n    Caplet caplet2(emodel.caplet(CST(2),delta,lvl),CST(0),CST(2),lvl,delta);\r\n    cout << caplet2.price() << ' ' << flush;\r\n    caplets.push_back(&caplet2);\r\n    Floorlet floorlet2(-1.0,CST(0),CST(2),floorlvl,delta);\r\n    floorlets.push_back(&floorlet2);\r\n    delta = CST(4)-CST(3);\r\n    lvl   = CSts.simple_rate(CST(3),delta);\r\n    Caplet caplet3(emodel.caplet(CST(3),delta,lvl),CST(0),CST(3),lvl,delta);\r\n    cout << caplet3.price() << ' ' << flush;\r\n    caplets.push_back(&caplet3);\r\n    Floorlet floorlet3(-1.0,CST(0),CST(3),floorlvl,delta);\r\n    floorlets.push_back(&floorlet3);\r\n    cout << endl;\r\n    CSmodel.calibrate(caplets);\r\n\tcout << \"Compare model price with input price\" << endl;\r\n    std::vector<TSEuropeanInstrument*>::iterator iter;\r\n    for (iter=caplets.begin();iter!=caplets.end();iter++) {\r\n      cout << CSmodel.price(**iter) << ' ' << (*iter)->price() << endl; }\r\n\t// Price an interest rate floor\r\n\tdouble floor = 0.0;\r\n    for (iter=floorlets.begin();iter!=floorlets.end();iter++) {\r\n      floor += CSmodel.price(**iter); }\r\n\tcout << \"Price of interest rate floor with floor level \" << floorlvl << \": \" << floor << endl;\r\n\t// Instantiate larger lattice\r\n\tint N2 = 130;\r\n    Array<double,1> SaSoT2(N2+1);\r\n    double dtSaSo2 = T2/N2;\r\n    SaSoT2 = idx * dtSaSo2;\r\n    cout << \"Creating SaSo lattice... \" << SaSoT2 << endl;\r\n    TSBinomialMethod SaSo2(flat_ts,sgm,SaSoT2); \r\n    cout << \"Rolling back term structures... \" << endl;\r\n    SaSo2.rollbackTermstructures();\r\n    cout << \"SaSo verified: \" << SaSo2.verify() << endl;\r\n\t// Price a European swaption\r\n\tSwaption swaption(-1.0,0.0,SaSoT2(25),r,0.5,4);\r\n\tcout << \"Maturity: \" << SaSoT2(25) << endl;\r\n\tcout << \"Swaption price: \" << SaSo2.price(swaption) << endl;\r\n\t// Price a Bermudan swaption\r\n    BermudanSwaption bermudan(-1.0,0.0,SaSoT2(25),r,0.5,4); \r\n\tif (!subset(bermudan.maturity(),SaSoT2)) throw std::logic_error(\"Timeline mismatch\");\r\n\tcout << \"Maturity: \" << SaSoT2(25) << endl;\r\n\tcout << \"Bermudan Swaption price: \" << SaSo2.price(bermudan) << endl;\r\n\t// Price a barrier caplet\r\n\tCaplet capletB(-1.0,0.0,SaSoT2(50),lvl,delta);\r\n\tBarrierInstrument barrier_caplet(-1.0,0.0,capletB,SaSoT2(Range(0,50)),0.8*lvl,delta,-1);\r\n\tcout << \"Caplet price: \" << SaSo2.price(capletB) << endl;\r\n\tcout << \"Barrier caplet price: \" << SaSo2.price(barrier_caplet) << endl;\r\n\r\n\t} // end of try block\r\n\r\n  catch (std::logic_error xcpt) {\r\n    std::cerr << xcpt.what() << endl; }\r\n  catch (std::runtime_error xcpt) {\r\n    std::cerr << xcpt.what() << endl; }\r\n  catch (...) {\r\n    std::cerr << \"Other exception caught\" << endl; }\r\n  \r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "5fd8abe99a3e2d347b4c2be3aaef799179341537", "size": 6256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter 3/TSBinomialExample.cpp", "max_stars_repo_name": "RoelofBerg/QuantFinCode", "max_stars_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Chapter 3/TSBinomialExample.cpp", "max_issues_repo_name": "RoelofBerg/QuantFinCode", "max_issues_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chapter 3/TSBinomialExample.cpp", "max_forks_repo_name": "RoelofBerg/QuantFinCode", "max_forks_repo_head_hexsha": "a0d32b51fb46cf591242cf9981bdd86ea7b37898", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3720930233, "max_line_length": 96, "alphanum_fraction": 0.5981457801, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5842155513126015}}
{"text": "#define _CRT_SECURE_NO_WARNINGS\n#pragma warning(disable:4819)\n\n#include <iostream>\n#include <string>\n#include <random>\n#include <sstream>\n#include <iomanip>\n#include <numeric>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\n#include <opencv2/opencv.hpp>\n\ncv::Mat capture(const cv::Mat& prj_im)\n{\n\t//\n\t// Write your code for projection a projector image in \"prj_im\" and capture a camera image to \"cam_im\"\n\t//\n\n\t// This is dummy\n\tcv::Mat cam_im = prj_im.clone();\n\n\treturn cam_im;\n}\n\nstruct fitting_functor\n{\n\tfitting_functor(const int inputs, const int values, const Eigen::VectorXd& input_x, const Eigen::VectorXd& input_y, const int im_num_)\n\t\t: inputs_(inputs), values_(values), im_num(im_num_), N(values / im_num_), x(input_x), y(input_y) {}\n\n\tEigen::VectorXd x;\n\tEigen::VectorXd y;\n\n\tint operator()(const Eigen::VectorXd& p, Eigen::VectorXd& fvec) const\n\t{\n\t\t// f = min(1, c_i * ((a * x + b)^g) + d_i);\n\t\t// p[0] --- p[N-1] : c_i\n\t\t// p[N] --- p[2*N-1] : d_i\n\t\t// p[2*N+0] : a\n\t\t// p[2*N+1] : b\n\t\t// p[2*N+2] : g\n\n\t\tfor (int pix_idx = 0; pix_idx < N; ++pix_idx)\n\t\t{\n\t\t\tfor (int im_idx = 0; im_idx < im_num; ++im_idx)\n\t\t\t{\n\t\t\t\tconst int elem_idx = im_num * pix_idx + im_idx;\n\n\t\t\t\tconst auto& c_i = p[pix_idx];\n\t\t\t\tconst auto& d_i = p[N + pix_idx];\n\t\t\t\tconst auto& a = p[2 * N + 0];\n\t\t\t\tconst auto& b = p[2 * N + 1];\n\t\t\t\tconst auto& g = p[2 * N + 2];\n\n\t\t\t\tconst auto& x_ = x[im_idx];\n\t\t\t\tconst auto& y_ = y[elem_idx];\n\n\t\t\t\tfvec[elem_idx] = std::pow(std::min(1.0, c_i * std::pow(std::max(0.0, a * x_ + b), g) + d_i) - y_, 2);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\tint df(const Eigen::VectorXd& p, Eigen::MatrixXd& fjac)\n\t{\n\t\tfjac.setZero();\n\n\t\tfor (int pix_idx = 0; pix_idx < N; ++pix_idx)\n\t\t{\n\t\t\tfor (int im_idx = 0; im_idx < im_num; ++im_idx)\n\t\t\t{\n\t\t\t\tconst int elem_idx = im_num * pix_idx + im_idx;\n\n\t\t\t\tconst auto& c_i = p[pix_idx];\n\t\t\t\tconst auto& d_i = p[N + pix_idx];\n\t\t\t\tconst auto& a = p[2 * N + 0];\n\t\t\t\tconst auto& b = p[2 * N + 1];\n\t\t\t\tconst auto& g = p[2 * N + 2];\n\n\t\t\t\tconst auto& x_ = x[im_idx];\n\t\t\t\tconst auto& y_ = y[elem_idx];\n\n\t\t\t\tconst double E = std::max(0.0, a * x_ + b);\n\t\t\t\tconst double D = std::pow(E, g);\n\t\t\t\tconst double C = c_i * D + d_i;\n\t\t\t\tconst double B = std::min(1.0, C);\n\t\t\t\tconst double A = B - y_;\n\n\t\t\t\tconst double uC = C > 1.0 ? 1.0 : 0.0;\n\n\t\t\t\tconst double df_dd = 2.0 * A * (1.0 - uC);\n\t\t\t\tconst double df_dc = df_dd * D;\n\t\t\t\tconst double df_dg = E > 0.0 ? df_dc * c_i * std::log(E) : 0.0;\n\t\t\t\tconst double df_db = df_dd * c_i * g * std::pow(E, g - 1);\n\t\t\t\tconst double df_da = df_db * x_;\n\t\t\t\t\n\t\t\t\tfjac(elem_idx, pix_idx) = df_dc;\n\t\t\t\tfjac(elem_idx, N + pix_idx) = df_dd;\n\t\t\t\tfjac(elem_idx, 2 * N + 0) = df_da;\n\t\t\t\tfjac(elem_idx, 2 * N + 1) = df_db;\n\t\t\t\tfjac(elem_idx, 2 * N + 2) = df_dg;\n\t\t\t}\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tconst int inputs_;\n\tconst int values_;\n\tconst int N;\n\tconst int im_num;\n\tint inputs() const { return inputs_; }\n\tint values() const { return values_; }\n};\n\ndouble opt_func(const int N, const int im_num, const Eigen::VectorXd& x, const Eigen::VectorXd& y, const Eigen::VectorXd& p)\n{\n\tdouble error = 0.0;\n\n\tfor (int pix_idx = 0; pix_idx < N; ++pix_idx)\n\t{\n\t\tfor (int im_idx = 0; im_idx < im_num; ++im_idx)\n\t\t{\n\t\t\tconst int elem_idx = im_num * pix_idx + im_idx;\n\n\t\t\tconst auto& c_i = p[pix_idx];\n\t\t\tconst auto& d_i = p[N + pix_idx];\n\t\t\tconst auto& a = p[2 * N + 0];\n\t\t\tconst auto& b = p[2 * N + 1];\n\t\t\tconst auto& g = p[2 * N + 2];\n\n\t\t\tconst auto& x_ = x[im_idx];\n\t\t\tconst auto& y_ = y[elem_idx];\n\n\t\t\terror += std::pow(std::min(1.0, c_i * std::pow(a * x_ + b, g) + d_i) - y_, 2);\n\t\t}\n\t}\n\n\treturn error;\n}\n\nEigen::VectorXd opt_func_df(const int N, const int im_num, const Eigen::VectorXd& x, const Eigen::VectorXd& y, const Eigen::VectorXd& p)\n{\n\tEigen::VectorXd df = Eigen::VectorXd::Zero(2 * N + 3);\n\n\tfor (int pix_idx = 0; pix_idx < N; ++pix_idx)\n\t{\n\t\tfor (int im_idx = 0; im_idx < im_num; ++im_idx)\n\t\t{\n\t\t\tconst int elem_idx = im_num * pix_idx + im_idx;\n\n\t\t\tconst auto& c_i = p[pix_idx];\n\t\t\tconst auto& d_i = p[N + pix_idx];\n\t\t\tconst auto& a = p[2 * N + 0];\n\t\t\tconst auto& b = p[2 * N + 1];\n\t\t\tconst auto& g = p[2 * N + 2];\n\n\t\t\tconst auto& x_ = x[im_idx];\n\t\t\tconst auto& y_ = y[elem_idx];\n\n\t\t\tconst double E = std::max(0.0, a * x_ + b);\n\t\t\tconst double D = std::pow(E, g);\n\t\t\tconst double C = c_i * D + d_i;\n\t\t\tconst double B = std::min(1.0, C);\n\t\t\tconst double A = B - y_;\n\n\t\t\tconst double uC = C > 1.0 ? 1.0 : 0.0;\n\n\t\t\tconst double df_dd = 2.0 * A * (1.0 - uC);\n\t\t\tconst double df_dc = df_dd * D;\n\t\t\tconst double df_dg = E > 0.0 ? df_dc * c_i * std::log(E) : 0.0;\n\t\t\tconst double df_db = df_dd * c_i * g * std::pow(E, g - 1);\n\t\t\tconst double df_da = df_db * x_;\n\n\t\t\tdf[pix_idx] += df_dc;\n\t\t\tdf[N + pix_idx] += df_dd;\n\t\t\tdf[2 * N + 0] += df_da;\n\t\t\tdf[2 * N + 1] += df_db;\n\t\t\tdf[2 * N + 2] += df_dg;\n\t\t}\n\t}\n\n\treturn df;\n}\n\nint main()\n{\n\t//\n\t// modify these arguments for your usage\n\t//\n\tconst int im_num = 25;\n\tconst cv::Size cam_resized_size(8, 4);\n\tconst cv::Size prj_size(640, 480);\n\tconst std::string data_path = \"./\";\n\n\n\tEigen::VectorXd prj_intensities = Eigen::VectorXd::Zero(im_num);\n\tfor (int i = 0; i < im_num; ++i)\n\t{\n\t\tprj_intensities[i] = static_cast<double>(i) / (im_num - 1);\n\t}\n\n\tstd::vector<cv::Mat> cam_im_vec;\n\n\n\tfor (int i = 0; i < im_num; ++i)\n\t{\n\t\tstd::cout << prj_intensities[i] * 255.0 << std::endl;\n\n\t\tconst cv::Mat prj_im = cv::Mat::ones(prj_size, CV_8U) * static_cast<int>(prj_intensities[i] * 255.0);\n\t\t//const cv::Mat prj_im = cv::Mat::ones(setting.prj.size, CV_8U) * static_cast<int>(prj_intensities[i]);\n\t\tconst cv::Mat cam_im = capture(prj_im);\n\t\tcv::imwrite(data_path + std::to_string(i) + \"_org.bmp\", cam_im);\n\n\t\tcv::Mat cam_im_resized;\n\t\tcv::resize(cam_im, cam_im_resized, cam_resized_size);\n\n\t\tcam_im_vec.push_back(cam_im_resized);\n\n\t\tcv::imshow(\"cam_im_resized\", cam_im_resized);\n\t\tcv::waitKey(1);\n\n\t\tcv::imwrite(data_path + std::to_string(i) + \".bmp\", cam_im_resized);\n\t}\n\n\tconst int N = cam_resized_size.area();\n\t//const int N = 1;\n\n\t// y[0*im_num] --- p[1*im_num-1] : for cam_idx=0\n\t// y[1*im_num] --- p[2*im_num-1] : for cam_idx=1\n\t// ---\n\t// y[(N-1)*im_num] --- p[N*im_num-1] : for cam_idx=N\n\tEigen::VectorXd cam_intensities_vec = Eigen::VectorXd::Zero(N * im_num);\n\n\tfor (int cam_y = 0; cam_y < cam_resized_size.height; ++cam_y)\n\t{\n\t\tstd::vector<uchar*> cam_ptrs(im_num);\n\t\tfor (int i = 0; i < im_num; ++i)\n\t\t{\n\t\t\tcam_ptrs[i] = cam_im_vec[i].ptr<uchar>(cam_y);\n\t\t}\n\n\t\tfor (int cam_x = 0; cam_x < cam_resized_size.width; ++cam_x)\n\t\t{\n\t\t\tconst int cam_idx = cam_y * cam_resized_size.width + cam_x;\n\n\t\t\tfor (int i = 0; i < im_num; ++i)\n\t\t\t{\n\t\t\t\tconst auto val = cam_ptrs[i][cam_x];\n\t\t\t\tcam_intensities_vec[cam_idx * im_num + i] = static_cast<double>(val) / 255.0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// f = min(1, c_i * ((a * x + b)^g) + d_i);\n\t// p[0] --- p[N-1] : c_i\n\t// p[N] --- p[2*N-1] : d_i\n\t// p[2*N+0] : a\n\t// p[2*N+1] : b\n\t// p[2*N+2] : g\n\n\tEigen::VectorXd p(2 * N + 3);\n\t\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tp[i] = 1.0;\n\t\tp[N+i] = 0.0;\n\t}\n\tp[2 * N + 0] = 1.0;\n\tp[2 * N + 1] = 0.0;\n\tp[2 * N + 2] = 1.0;\n\n\tfitting_functor functor(2 * N + 3, N * im_num, prj_intensities, cam_intensities_vec, im_num);\n\tEigen::LevenbergMarquardt<fitting_functor> lm(functor);\n\n\tEigen::LevenbergMarquardtSpace::Status info = lm.minimize(p);\n\n\tstd::cout << \"lm.fnorm:\" << std::endl;\n\tstd::cout << lm.fnorm << std::endl;\n\n\tconst Eigen::VectorXd c_vec = p.block(0, 0, N, 1);\n\tconst Eigen::VectorXd d_vec = p.block(N, 0, N, 1);\n\n\tdouble min_val = std::numeric_limits<double>::max();\n\tint min_idx = 0;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tconst double c = c_vec[i];\n\t\tconst double d = d_vec[i];\n\t\tconst double a = p[2 * N + 0];\n\t\tconst double b = p[2 * N + 1];\n\t\tconst double g = p[2 * N + 2];\n\n\t\tdouble x = (std::pow((1.0 - d) / c, 1.0 / g) - b) / a;\n\t\tx = std::isnan(x) ? std::numeric_limits<double>::max() : x;\n\n\t\tif (x < min_val)\n\t\t{\n\t\t\tmin_idx = i;\n\t\t\tmin_val = x;\n\t\t}\n\t}\n\n\t//std::cout << c_vec.mean() << std::endl;\n\t//std::cout << d_vec.mean() << std::endl;\n\t//std::cout << c_vec[min_idx] << std::endl;\n\t//std::cout << d_vec[min_idx] << std::endl;\n\t//std::cout << min_val << std::endl;\n\t//std::cout << p.tail(3) << std::endl;\n\t//std::cout << info << std::endl;\n\n\tstd::cout << \"c_thr: \" << c_vec[min_idx] << std::endl;\n\tstd::cout << \"d_thr: \" << d_vec[min_idx] << std::endl;\n\tstd::cout << \"prj_thr: \" << min_val << std::endl;\n\tstd::cout << \"a: \" << p[2 * N + 0] << std::endl;\n\tstd::cout << \"b: \" << p[2 * N + 1] << std::endl;\n\tstd::cout << \"g: \" << p[2 * N + 2] << std::endl;\n\tstd::cout << \"k: \" << (1.0 - d_vec[min_idx]) / c_vec[min_idx] << std::endl;\n\n\t/*\n\tcv::FileStorage fs(setting.optical_calibration_path, cv::FileStorage::WRITE);\n\n\tif (!fs.isOpened())\n\t{\n\t\tstd::cout << \"Error: Failed to open calibration file.\" << std::endl;\n\t\tthrow std::runtime_error(\"optical_calib_open\");\n\t}\n\n\tcv::write(fs, \"a\", p[2 * N + 0]);\n\tcv::write(fs, \"b\", p[2 * N + 1]);\n\tcv::write(fs, \"gamma\", p[2 * N + 2]);\n\tcv::write(fs, \"k\", (1.0 - d_vec[min_idx]) / c_vec[min_idx]);\n\n\tfs.release();\n\t*/\n\n\tcv::waitKey(-1);\n\n\treturn 0;\n}", "meta": {"hexsha": "756d4077340c74d53e1e7df2b3f0148b1d600327", "size": 9050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optical_calibration.cpp", "max_stars_repo_name": "naoya-chiba/OpticalCalibrationTool", "max_stars_repo_head_hexsha": "ca0f70e73cb404877a634ba479382a1c7dce47c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T05:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T05:53:44.000Z", "max_issues_repo_path": "optical_calibration.cpp", "max_issues_repo_name": "naoya-chiba/OpticalCalibrationTool", "max_issues_repo_head_hexsha": "ca0f70e73cb404877a634ba479382a1c7dce47c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optical_calibration.cpp", "max_forks_repo_name": "naoya-chiba/OpticalCalibrationTool", "max_forks_repo_head_hexsha": "ca0f70e73cb404877a634ba479382a1c7dce47c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T22:44:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T22:44:23.000Z", "avg_line_length": 26.3081395349, "max_line_length": 136, "alphanum_fraction": 0.5812154696, "num_tokens": 3383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5841510331013667}}
{"text": "// The template and inlines for the -*- C++ -*- rational number classes.\n// Initially implemented by Wai-Shing Luk <luk036@gmail.com>\n//\n\n/** @file include/rational.hpp\n *  This is a C++ Library header.\n */\n\n#ifndef FUN_RATIONAL_HPP\n#define FUN_RATIONAL_HPP 1\n\n#include <cassert>\n#include <type_traits> // is_integral<T>\n#include <boost/operators.hpp>\n\nnamespace fun \n{\n  /**\n   * @defgroup rational (extended) Rational Number\n   * @ingroup arithmetic\n   *\n   * Classes and functions for (extended) rational number.\n   * Reference: MF103-\n   * @{\n   */\n\n  // Forward declarations.\n  //template<typename _Z> struct rational;\n\n  /// greatest common divider\n  template<typename _Z, class = typename\n\t    std::enable_if<std::is_integral<_Z>::value>::type> \n  //xxx requires is_integral<_Z>::value\n  inline constexpr _Z gcd(const _Z& a, const _Z& b) noexcept\n  { return b == _Z(0) ? abs(a) : gcd(b, a%b); }\n  \n  /** \n   *  Rational number. \n   *\n   *  @param  Z  Type of rational number elements\n   *  @todo unit testing\n   */\n  template <typename _Z, class = typename\n\t    std::enable_if<std::is_integral<_Z>::value>::type>\n  //xxx requires is_integral<_Z>::value\n  struct rational : boost::ordered_field_operators<rational<_Z>,\n\t\t    boost::ordered_field_operators2<rational<_Z>, _Z> >\n  {\n    /// Value typedef.\n    typedef _Z value_type;\n    \n    /// Default constructor.\n    ///  Unspecified parameters default to 0.\n    explicit \n    rational(const _Z& p = _Z(), const _Z& q = _Z(1)) \n      : _num{p}, _denom{q} \n    {\n      assert(!(_num == _Z(0) && _denom == _Z(0)));\n      normalize(); \n    }\n\n    // Lets the compiler synthesize the copy constructor\n    //rational (const rational<_Z>&) = default;\n\n    /// Copy constructor\n    template<typename _Up>\n    explicit constexpr \n    rational(const rational<_Up>& s) noexcept \n      : _num{s.num()}, _denom{s.denom()} \n    { }\n    \n    /// Return first element of rational number.\n    constexpr _Z num() const noexcept { return _num; }\n    \n    /// Return second element of rational number.\n    constexpr _Z denom() const noexcept { return _denom; }\n    \n    // Lets the compiler synthesize the assignment operator\n    // rational<_Z>& operator= (const rational<_Z>&);\n    /// Assign this rational number to rational number @a s.\n    template<typename _Up>\n    rational<_Z>& operator=(const rational<_Up>& s)\n    { _num = s.num(); _denom = s.denom(); return *this; }\n\n    /// Increase this rational number (prefix operator)\n    rational<_Z>& operator++()\n    { _num += _denom; return *this; }\n\n    /// Decrease this rational number (prefix operator)\n    rational<_Z>& operator--()\n    { _num -= _denom; return *this; }\n\n    /// Increase this rational number (postfix operator)\n    rational<_Z> operator++(int)\n    { rational<_Z> res(*this); ++(*this); return res; }\n\n    /// Decrease this rational number (postfix operator)\n    rational<_Z> operator--(int)\n    { rational<_Z> res(*this); --(*this); return res; }\n        \n    /// Add @a s to this rational number.\n    rational<_Z>& operator+=(const _Z& a)\n    { _num += _denom * a; return *this; }\n\n    /// Subtract @a s from this rational number.\n    rational<_Z>& operator-=(const _Z& a)\n    { _num -= _denom * a; return *this; }\n    \n    /// Multiply this rational number by @a a.\n    rational<_Z>& operator*=(const _Z& a) \n    { _num *= a; normalize(); return *this; }\n    \n    /// Divide this rational number by @a a.\n    rational<_Z>& operator/=(const _Z& a) \n    { _denom *= a; normalize(); return *this; }\n\n    /// Add @a s to this rational number.\n    template<typename _Up>\n    rational<_Z>& operator+=(const rational<_Up>& s)\n    { \n      _num = _num * s.denom() + _denom * s.num(); \n      _denom *= s.denom();\n      normalize(); \n      return *this;\n    }\n\n    /// Subtract @a s from this rational number.\n    template<typename _Up>\n    rational<_Z>& operator-=(const rational<_Up>& s)\n    { \n      _num = _num * s.denom() - _denom * s.num(); \n      _denom *= s.denom();\n      normalize();\n      return *this;\n    }\n\n    /// Multiply @a s to this rational number.\n    template<typename _Up>\n    rational<_Z>& operator*=(const rational<_Up>& s)\n    { \n      _num *= s.num(); \n      _denom *= s.denom();\n      normalize();\n      return *this;\n    }\n\n    /// Divide @a s to this rational number.\n    template<typename _Up>\n    rational<_Z>& operator/=(const rational<_Up>& s)\n    {\n      *this *= rational<_Z>(s.denom(), s.num());\n      return *this;\n    }\n\n    /// Cast to double\n    operator double () const { return double(num()) / denom(); }\n\n  private:\n    /// Normalize rational number.\n    void normalize() { \n      if (_denom < _Z()) { \n\t      _num = -_num; \n\t      _denom = -_denom; \n      } \n      _Z g = gcd(_num, _denom);\n      _num /= g;\n      _denom /= g;\n    }\n    \n  private:\n    _Z _num;\n    _Z _denom;\n    \n  };\n  \n  // Operators:\n  ///  Return new rational number @a r plus @a s.\n  template<typename _Z, typename _Up>\n  inline auto\n  operator+(const rational<_Z>& r, const rational<_Up>& s) \n    -> rational<decltype(r.num()*s.denom())>\n  {\n    auto num = r.num() * s.denom() + r.denom() * s.num(); \n    decltype(num) denom =  r.denom() * s.denom();\n    return rational<decltype(num)> {num, denom}; \n  }\n\n  ///  Return new rational number @a r plus @a s.\n  template<typename _Z, typename _Up>\n  inline auto\n  operator-(const rational<_Z>& r, const rational<_Up>& s) \n    -> rational<decltype(r.denom()*s.denom())>\n  {\n    //auto num = r.num() * s.denom() - r.denom() * s.num(); \n    //decltype(num) denom =  r.denom() * s.denom();\n    return rational<decltype(r.denom()*s.denom())> \n      { r.num() * s.denom() - r.denom() * s.num(),\n\tr.denom() * s.denom() }; \n  }\n\n  ///  Return new rational number @a r times @a s.\n  template<typename _Z, typename _Up>\n  inline auto\n  operator*(const rational<_Z>& r, const rational<_Up>& s)\n    -> rational<decltype(r.num()*s.num())>\n  {\n    return rational<decltype(r.num()*s.num())> \n      { r.num()*s.num(), r.denom()*s.denom() };\n  }\n  \n  ///  Return new rational number @a r times @a s.\n  template<typename _Z, typename _Up>\n  inline auto \n  operator/(const rational<_Z>& r, const rational<_Up>& s)\n    -> decltype(r * s) \n  {\n    return r * rational<_Up>(s.denom(), s.num());\n  }\n  \n  //xxx ///  Return new rational number @a r minus @a s.\n  //xxx template<typename _Z>\n  //xxx inline rational<_Z>\n  //xxx operator-(rational<_Z> r, const rational<_Z>& s) { return r -= s; }\n  //xxx \n  //xxx //@{\n  //xxx ///  Return new rational number @a r times @a a.\n  //xxx template<typename _Z>\n  //xxx inline rational<_Z>\n  //xxx operator*(rational<_Z> r, const rational<_Z>& s) { return r *= s; }\n  //xxx \n  //xxx template<typename _Z>\n  //xxx inline rational<_Z>\n  //xxx operator*(rational<_Z> r, const _Z& a) { return r *= a; }\n  //xxx \n  //xxx template<typename _Z>\n  //xxx inline rational<_Z>\n  //xxx operator*(const _Z& a, rational<_Z> r) { return r *= a; }\n  //xxx //@}\n  //xxx \n  //xxx ///  Return new rational number @a r divided by @a a.\n  //xxx template<typename _Z>\n  //xxx inline rational<_Z>\n  //xxx operator/(rational<_Z> r, const _Z& a) { return r /= a; }\n  \n  /// Return @a r.\n  template<typename _Z>\n  inline constexpr rational<_Z>\n  operator+(const rational<_Z>& r) noexcept { return r; }\n\n  /// Return negation of @a r\n  template<typename _Z>\n  inline constexpr rational<_Z>\n  operator-(const rational<_Z>& r) noexcept\n  { return rational<_Z>(-r.num(), r.denom()); }\n  \n  /// Return true if @a r is equal to @a s.\n  template<typename _Z, typename _Up>\n  inline bool\n  operator==(const rational<_Z>& r, const rational<_Up>& s)\n  { \n    assert(!(r.num() == 0 && r.denom() == 0)); // NaN\n    assert(!(s.num() == 0 && s.denom() == 0)); // NaN\n    return r.num() == s.num() && s.denom() == r.denom();\n  }\n\n  /// Return false if @a r is equal to @a s.\n  template<typename _Z, typename _Up>\n  inline constexpr bool\n  operator!=(const rational<_Z>& r, const rational<_Up>& s) noexcept\n  { return !(r == s); }\n\n  /// Return true if @a r is less than @a s.\n  template<typename _Z, typename _Up>\n  inline constexpr bool\n  operator<(const rational<_Z>& r, const rational<_Up>& s) noexcept\n  { return r.num()*s.denom() < r.denom()*s.num(); }\n\n  ///  Insertion operator for rational number values.\n  template<typename _Z, class _Stream>\n  _Stream& operator<<(_Stream& os, const rational<_Z>& r)\n  {\n    const auto& a = r.num();\n    const auto& b = r.denom();\n    _Z zero(0), one(1);\n    if (b == one)  { os << a; return os; }\n    if (b != zero) { os << '(' << a << '/' << b << ')'; return os; }\n    if (a < zero)  { os << \"-Inf\"; return os; }\n    if (a > zero)  { os << \"Inf\"; return os; }\n    os << \"NaN\"; return os;\n  }\n\n}\n\n#endif\n", "meta": {"hexsha": "55642e2519886ad0fd5489ec8e67271b5414f54c", "size": 8699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/fun/rational.hpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/fun/rational.hpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/fun/rational.hpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4881355932, "max_line_length": 75, "alphanum_fraction": 0.5931716289, "num_tokens": 2539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5841219128149983}}
{"text": "/**\n * \\file dcs/math/stats/distribution/exponential.hpp\n *\n * \\brief The (Negative) Exponential probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_EXPONENTIAL_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_EXPONENTIAL_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/random/exponential_distribution.hpp>\n//#include <boost/random/variate_generator.hpp>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n//TODO\n//#include <dcs/math/random/any_generator.hpp>\n//#include <dcs/math/random/base_generator.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\n/**\n * \\brief The (Negative) Exponential distribution with rate parameter\n * \\f$\\lambda\\f$.\n *\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * The probability density function (pdf):\n * \\f[\n *   \\Pr(x|\\lambda) = \\lambda e^{-\\lambda x}\n * \\f]\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass exponential_distribution//TODO>>: public base_distribution<RealT>\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit exponential_distribution(support_type lambda=1)\n\t\t: dist_(lambda)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this\n\t * exponential distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this exponential\n\t * distribution.\n\t *\n\t * A \\c exponential random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\lambda) = \\lambda e^{-\\lambda x}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\ttypedef ::boost::exponential_distribution<support_type> rdist_type;\n//\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n//\n//\t\treturn variate_type(rng, rdist_type(dist_.lambda()))();\n\t\treturn rdist_type(dist_.lambda())(rng);\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * exponential distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * exponential distribution.\n\t *\n\t * A \\c exponential random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\lambda) = \\lambda e^{-\\lambda x}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n)\n\t{\n\t\ttypedef ::boost::exponential_distribution<support_type> rdist_type;\n//\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n\n\t\t::std::vector<support_type> rnds(n);\n\t\trdist_type rvg(dist_.lambda());\n\n\t\tfor (; n > 0; --n)\n\t\t{\n//\t\t\trnds.push_back(variate_type(rng, rdist_type(dist_.lambda()))());\n\t\t\trnds.push_back(rvg(rng));\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type lambda() const\n\t{\n\t\treturn dist_.lambda();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn support_type(1)/dist_.lambda();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn support_type(0);\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n//TODO\n//\tprivate: support_type do_rand(::dcs::math::random::base_generator<value_type>& rng) const\n//\t{\n//\t\ttypedef ::boost::exponential_distribution<support_type> rdist_type;\n//\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n//\n//\t\treturn variate_type(rng, rdist_type(dist_.lambda()))();\n//\t}\n\n\n//TODO\n//\tprivate: support_type do_rand(::dcs::math::random::any_generator<value_type>& rng) const\n//\t{\n//\t\ttypedef ::boost::exponential_distribution<support_type> rdist_type;\n//\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n//\n//\t\treturn variate_type(rng, rdist_type(dist_.lambda()))();\n//\t}\n\n\n\tprivate: ::boost::math::exponential_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n    typename CharT,\n    typename CharTraitsT,\n    typename RealT,\n    typename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, exponential_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"Exp(\"\n\t\t\t  << \"lambda=\" <<  dist.lambda()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_EXPONENTIAL_HPP\n", "meta": {"hexsha": "2ece69a03d208065bf1fd5e6cd1fd5844ba92fe4", "size": 5686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/exponential.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/exponential.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/exponential.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": 27.8725490196, "max_line_length": 149, "alphanum_fraction": 0.7251143159, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.5841219014009542}}
{"text": "// \n// Implements traditional LQR for linear dynamics and cost.\n//\n\n#pragma once\n\n#include <vector>\n\n#include <Eigen/Dense>\n\nnamespace lqr\n{\nvoid compute_backup(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n        const Eigen::MatrixXd &Q, const Eigen::MatrixXd &R,\n        const Eigen::MatrixXd &Vt1,\n        Eigen::MatrixXd &Kt, Eigen::MatrixXd &Vt);\n\nclass LQR\n{\npublic:\n\n    LQR(const std::vector<Eigen::MatrixXd> &As, \n        const std::vector<Eigen::MatrixXd> &Bs,\n        const std::vector<Eigen::MatrixXd> &Qs,\n        const std::vector<Eigen::MatrixXd> &Rs);\n\n    LQR(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B,\n        const Eigen::MatrixXd &Q, const Eigen::MatrixXd &R, \n        const int T);\n\n    void solve();\n\n    void forward_pass(const Eigen::VectorXd &x0, \n        std::vector<double> &costs,\n        std::vector<Eigen::VectorXd> &states, \n        std::vector<Eigen::VectorXd> &controls) const;\n\n//private:\n    int state_dim_ = -1;\n    int control_dim_  = -1;\n\n    std::vector<Eigen::MatrixXd> As_; \n    std::vector<Eigen::MatrixXd> Bs_;\n    std::vector<Eigen::MatrixXd> Qs_; \n    std::vector<Eigen::MatrixXd> Rs_;\n\n    int T_ = -1;\n\n    std::vector<Eigen::MatrixXd> Ks_;\n};\n\n} // namespace lqr\n\n", "meta": {"hexsha": "7f228b7af9effa8c6550b78c00697a31e52d675b", "size": 1229, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lqr/LQR.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/lqr/LQR.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lqr/LQR.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 22.7592592593, "max_line_length": 71, "alphanum_fraction": 0.6297803092, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5841218965021922}}
{"text": "/**\n * @file calc-jump.cpp\n *\n * @brief calc jump function.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n *\n * Compile:\n * g++ calc-jump.cpp -o calc-jump -lntl\n *\n * Run with 2^128 steps:\n * ./calc-jump 340282366920938463463374607431768211456 characteristic.19937.txt > sfmt-poly-128.txt\n *\n */\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <inttypes.h>\n#include <stdint.h>\n#include <time.h>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/ZZ.h>\n#include \"SFMT-calc-jump.hpp\"\n\nusing namespace NTL;\nusing namespace std;\nusing namespace sfmt;\n\nstatic void read_file(GF2X& characteristic, long line_no, const string& file);\n\nint main(int argc, char * argv[]) {\n    if (argc <= 2) {\n\tcout << argv[0] << \" jump-step characteristic-file [no.]\" << endl;\n\tcout << \"    jump-step: a number between zero and 2^{SFMT_MEXP}-1.\\n\"\n\t     << \"               large decimal number is allowed.\" << endl;\n\tcout << \"    characteristic-file: one of characteristic.{MEXP}.txt \"\n\t     << \"file\" << endl;\n\tcout << \"    [no.]: shows which characteristic polynomial in \\n\"\n\t     << \"           the file should be used. 0 is used if omitted.\\n\"\n\t     << \"           this is used for files in params directory.\"\n\t     << endl;\n\treturn -1;\n    }\n    string step_string = argv[1];\n    string filename = argv[2];\n    long no = 0;\n    if (argc > 3) {\n\tno = strtol(argv[3], NULL, 10);\n    }\n    GF2X characteristic;\n    read_file(characteristic, no, filename);\n    ZZ step;\n    stringstream ss(step_string);\n    ss >> step;\n    string jump_str;\n    calc_jump(jump_str, step, characteristic);\n    cout << \"jump polynomial:\" << endl;\n    cout << jump_str << endl;\n    return 0;\n}\n\n\nstatic void read_file(GF2X& characteristic, 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(characteristic, line);\n}\n", "meta": {"hexsha": "a7f2396325adc9f7a6df038de39d96f36fecd3a7", "size": 2296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "randomgen/src/sfmt/calc-jump.cpp", "max_stars_repo_name": "amrali-eg/randomgen", "max_stars_repo_head_hexsha": "ea45e16d4e8ff701a705f5f5ec3592f656170f39", "max_stars_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T19:40:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:30:17.000Z", "max_issues_repo_path": "randomgen/src/sfmt/calc-jump.cpp", "max_issues_repo_name": "amrali-eg/randomgen", "max_issues_repo_head_hexsha": "ea45e16d4e8ff701a705f5f5ec3592f656170f39", "max_issues_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2018-03-22T05:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T02:07:58.000Z", "max_forks_repo_path": "randomgen/src/sfmt/calc-jump.cpp", "max_forks_repo_name": "amrali-eg/randomgen", "max_forks_repo_head_hexsha": "ea45e16d4e8ff701a705f5f5ec3592f656170f39", "max_forks_repo_licenses": ["NCSA", "BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2018-05-22T11:21:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:27:48.000Z", "avg_line_length": 25.797752809, "max_line_length": 99, "alphanum_fraction": 0.6332752613, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5841218916034301}}
{"text": "#include <iostream>\n#include <boost/math/common_factor_rt.hpp>\n#include \"audio.hpp\"\n#include \"fm.hpp\"\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nusing namespace std;\nusing namespace boost;\n\nMainWindow::MainWindow(FMSynth &fm, QWidget *parent) :\n    QMainWindow(parent),\n    fmsynth {fm},\n    ui(new Ui::MainWindow)\n{\n    ui->setupUi(this);\n\n    vizwindow.show();\n\n    audioEngine.init();\n}\n\nMainWindow::~MainWindow()\n{\n    audioEngine.close();\n    delete ui;\n}\n\nvoid MainWindow::on_button_trigger_clicked()\n{\n    // set synth params\n    fmsynth.carrier_frequency = ui->carrier_textbox->text().toFloat();\n    fmsynth.modulating_frequency = ui->modulating_textbox->text().toFloat();\n    fmsynth.modulation_index.set(ui->modulation_index_textbox->text().toFloat());\n\n    // find ratio\n    int carrier_frequency = ui->carrier_textbox->text().toInt();\n    int modulating_frequency = ui->modulating_textbox->text().toInt();\n    int gcd = math::gcd(carrier_frequency, modulating_frequency);\n    int numerator = carrier_frequency / gcd;\n    int denominator = modulating_frequency / gcd;\n    ui->ratio->setText(QString(\"%1 / %2\").arg(numerator).arg(denominator));\n\n    // find peak deviation\n    ui->peak_deviation->setText(QString(\"%1 Hz\").arg(fmsynth.peak_deviation()));\n}\n\nvoid MainWindow::on_volume_sliderMoved(int position)\n{\n    const float a = pow(10, position / 20.0);\n    audioEngine.volume.set(a);\n    QString str {QString(\"%1 dB\").arg(position)};\n    ui->label_volume_db->setText(str);\n}\n\nvoid MainWindow::on_carrier_slider_sliderMoved(int position)\n{\n    const float frequency {440.0f * powf(2, position/100.0f)};\n    ui->carrier_textbox->setText(QString(\"%1\").arg(frequency));\n    audioEngine.fmsynth.carrier_frequency = frequency;\n}\n\nvoid MainWindow::on_modulating_slider_sliderMoved(int position)\n{\n    const float frequency {static_cast<float>(position)};\n    ui->modulating_textbox->setText(QString(\"%1\").arg(frequency));\n    audioEngine.fmsynth.modulating_frequency = frequency;\n}\n\nvoid MainWindow::on_modulation_index_slider_sliderMoved(int position)\n{\n    const float index {static_cast<float>(position) / 10.0f};\n    ui->modulation_index_textbox->setText(QString(\"%1\").arg(index));\n    audioEngine.fmsynth.modulation_index.set(index);\n}\n\nvoid MainWindow::on_carrier_textbox_editingFinished()\n{\n    fmsynth.carrier_frequency = ui->carrier_textbox->text().toFloat();\n}\n\nvoid MainWindow::on_modulating_textbox_editingFinished()\n{\n    fmsynth.modulating_frequency = ui->modulating_textbox->text().toFloat();\n}\n\nvoid MainWindow::on_modulation_index_textbox_editingFinished()\n{\n    fmsynth.modulation_index.set(ui->modulation_index_textbox->text().toFloat());\n}\n\nvoid MainWindow::on_scale_sliderMoved(int position)\n{\n    vizwindow.scale = position/1000.0 * (2.0/7040.0 - 1.0/100.0) + 1.0/100.0;\n}\n\n", "meta": {"hexsha": "f1780fbd04940cda841659a948dcf75f57904147", "size": 2813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mainwindow.cpp", "max_stars_repo_name": "analoq/fmLab", "max_stars_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mainwindow.cpp", "max_issues_repo_name": "analoq/fmLab", "max_issues_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mainwindow.cpp", "max_forks_repo_name": "analoq/fmLab", "max_forks_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0, "max_line_length": 81, "alphanum_fraction": 0.7266263775, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.584121888370389}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <string>\n#include <boost/graph/edmunds_karp_max_flow.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n// Use a DIMACS network flow file as stdin.\n// edmunds-karp-eg < max_flow.dat\n//\n// Sample output:\n//  c  The total flow:\n//  s 13\n//\n//  c flow values:\n//  f 0 6 3\n//  f 0 1 6\n//  f 0 2 4\n//  f 1 5 1\n//  f 1 0 0\n//  f 1 3 5\n//  f 2 4 4\n//  f 2 3 0\n//  f 2 0 0\n//  f 3 7 5\n//  f 3 2 0\n//  f 3 1 0\n//  f 4 5 4\n//  f 4 6 0\n//  f 5 4 0\n//  f 5 7 5\n//  f 6 7 3\n//  f 6 4 0\n//  f 7 6 0\n//  f 7 5 0\n\nint\nmain()\n{\n  using namespace boost;\n\n  typedef adjacency_list_traits < vecS, vecS, directedS > Traits;\n  typedef adjacency_list < listS, vecS, directedS,\n    property < vertex_name_t, std::string >,\n    property < edge_capacity_t, long,\n    property < edge_residual_capacity_t, long,\n    property < edge_reverse_t, Traits::edge_descriptor > > > > Graph;\n\n  Graph g;\n\n  property_map < Graph, edge_capacity_t >::type\n    capacity = get(edge_capacity, g);\n  property_map < Graph, edge_reverse_t >::type rev = get(edge_reverse, g);\n  property_map < Graph, edge_residual_capacity_t >::type\n    residual_capacity = get(edge_residual_capacity, g);\n\n  Traits::vertex_descriptor s, t;\n  read_dimacs_max_flow(g, capacity, rev, s, t);\n\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\n  std::vector<default_color_type> color(num_vertices(g));\n  std::vector<Traits::edge_descriptor> pred(num_vertices(g));\n  long flow = edmunds_karp_max_flow\n    (g, s, t, capacity, residual_capacity, rev, &color[0], &pred[0]);\n#else\n  long flow = edmunds_karp_max_flow(g, s, t);\n#endif\n\n  std::cout << \"c  The total flow:\" << std::endl;\n  std::cout << \"s \" << flow << std::endl << std::endl;\n\n  std::cout << \"c flow values:\" << std::endl;\n  graph_traits < Graph >::vertex_iterator u_iter, u_end;\n  graph_traits < Graph >::out_edge_iterator ei, e_end;\n  for (tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n    for (tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n      if (capacity[*ei] > 0)\n        std::cout << \"f \" << *u_iter << \" \" << target(*ei, g) << \" \"\n          << (capacity[*ei] - residual_capacity[*ei]) << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f6cd199558f58b548fad35e1bcedb76a88afbeb1", "size": 2657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/boost_1_33_1/libs/graph/example/edmunds-karp-eg.cpp", "max_stars_repo_name": "spxuw/RFIM", "max_stars_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T13:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T02:55:10.000Z", "max_issues_repo_path": "Source/boost_1_33_1/libs/graph/example/edmunds-karp-eg.cpp", "max_issues_repo_name": "spxuw/RFIM", "max_issues_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/boost_1_33_1/libs/graph/example/edmunds-karp-eg.cpp", "max_forks_repo_name": "spxuw/RFIM", "max_forks_repo_head_hexsha": "32b78fbb90c7008b1106b0cff4f8023ae83c9b6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T14:34:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:25:58.000Z", "avg_line_length": 29.1978021978, "max_line_length": 74, "alphanum_fraction": 0.6115920211, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.5841081501351607}}
{"text": "#include <iostream>\n#include <float.h>\n#include <cmath>\n#include \"get_floor_f1Hf2.h\"\n#include \"normalize2dpts.h\"\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\nstd::vector<PoseDataVarFocal> get_floor_f1Hf2(MatrixXd &p1, MatrixXd &p2, Matrix3d &R1, Matrix3d &R2)\n{\n    int nbr_coeffs = 9 * 5;\n    int nbr_unknowns = 4;\n\n    // Save copies of the inverse rotation\n    Matrix3d R1T = R1.transpose();\n    Matrix3d R2T = R2.transpose();\n\n    // Compute normalization matrices\n    double scale1 = normalize2dpts(p1);\n    double scale2 = normalize2dpts(p2);\n    Vector3d s1, s2;\n    s1 << scale1, scale1, 1.0;\n    s2 << scale2, scale2, 1.0;\n    DiagonalMatrix<double, 3> S1 = s1.asDiagonal();\n    DiagonalMatrix<double, 3> S2 = s2.asDiagonal();\n\n    // Normalize data\n    MatrixXd x1(3, 3);\n    MatrixXd x2(3, 3);\n    x1 = S1 * p1;\n    x2 = S2 * p2;\n\n    // Setup DLT equations\n    MatrixXd A(6,9);\n    A << 0, 0, 0, -x2(2,0)*x1.col(0).transpose(), x2(1,0)*x1.col(0).transpose(),\n         x2(2,0)*x1.col(0).transpose(), 0, 0, 0, -x2(0,0)*x1.col(0).transpose(),\n         0, 0, 0, -x2(2,1)*x1.col(1).transpose(), x2(1,1)*x1.col(1).transpose(),\n         x2(2,1)*x1.col(1).transpose(), 0, 0, 0, -x2(0,1)*x1.col(1).transpose(),\n         0, 0, 0, -x2(2,2)*x1.col(2).transpose(), x2(1,2)*x1.col(2).transpose(),\n         x2(2,2)*x1.col(2).transpose(), 0, 0, 0, -x2(0,2)*x1.col(2).transpose();\n\n    JacobiSVD<MatrixXd> svd(A, ComputeFullV);\n    ArrayXXd V = svd.matrixV();\n\n    // Wrap input data to expected format\n    VectorXd input(nbr_coeffs);\n    input << V.col(6),\n             V.col(7),\n             V.col(8),\n             Map<VectorXd>(R1T.data(), 9),\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_f1Hf2(input_data);\n\n    // Pre-processing: Remove complex-valued solutions\n    double thresh = 1e-5;\n    ArrayXd real_sols(5);\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\n    // Since this is a 4 pt solver, we only return the solutions.\n    std::vector<PoseDataVarFocal> posedata(nbr_real_sols);\n    ArrayXd xx(nbr_unknowns);\n    Matrix3d Htmp;\n    double f1, f2;\n    int cnt = 0;\n\n    for (int i = 0; i < real_sols.size(); i++) {\n        if (real_sols(i) <= thresh) {\n            xx = sols.col(i).real();\n\n            // Extract focal lengths\n            f1 = 1 / xx[2] / scale1;\n            f2 = xx[3] / scale2;\n\n            // Construct putative homography\n            VectorXd tmp(9);\n            tmp << V.col(6) + xx[0] * V.col(7) + xx[1] * V.col(8);\n            Htmp = Map<Matrix3d>(tmp.data(), 3 ,3);\n            Htmp.transposeInPlace();\n            Htmp = S2.inverse() * Htmp * S1;\n\n            // Append\n            posedata[cnt].focal_length1 = f1;\n            posedata[cnt].focal_length2 = f2;\n            posedata[cnt].homography = Htmp;\n            cnt++;\n        }\n    }\n\n    return posedata;\n}\n\n// ---------------- //\n// MATLAB interface //\n// ---------------- //\n\n#ifdef MATLAB_MEX_FILE /* This macro is defined automatically when using MATLAB */\n#define NUMBER_OF_FIELDS (sizeof(field_names)/sizeof(*field_names))\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\tif (nrhs != 4) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_f1Hf2:nrhs\", \"Four input arguments are required.\");\n\t}\n\tif (nlhs != 1) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_f1Hf2:nlhs\", \"One output arguments is required.\");\n\t}\n\tif (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_f1Hf2:notDouble\", \"Input data must be type double.\");\n\t}\n\tif(mxGetNumberOfElements(prhs[0]) != 9 && mxGetNumberOfElements(prhs[1]) != 9 && mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9) {\n\t\tmexErrMsgIdAndTxt(\"get_floor_f1Hf2:incorrectSize\", \"Input dimensions incorrect.\");\n\t}\n    // Convert to expected input\n    VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), 9);\n    VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), 9);\n    MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 3, 3);\n    MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 3, 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    // Compute output\n\tstd::vector<PoseDataVarFocal> posedata = get_floor_f1Hf2(x1, x2, R1, R2);\n\n    // Wrap it all up\n    std::size_t NUMBER_OF_STRUCTS = posedata.size();\n    const char *field_names[] = {\"H\", \"f1\", \"f2\"};\n    mwSize dims[2] = {1, NUMBER_OF_STRUCTS };\n    int H_field, f1_field, f2_field;\n    mwIndex i;\n\n    plhs[0] = mxCreateStructArray(2, dims, NUMBER_OF_FIELDS, field_names);\n\n    H_field = mxGetFieldNumber(plhs[0], \"H\");\n    f1_field = mxGetFieldNumber(plhs[0], \"f1\");\n    f2_field = mxGetFieldNumber(plhs[0], \"f2\");\n\n\tdouble* zr;\n    for (i = 0; i < NUMBER_OF_STRUCTS; i++) {\n        mxArray *field_value;\n\n        // Create H\n        field_value = mxCreateDoubleMatrix(3, 3, mxREAL);\n        zr = mxGetPr(field_value);\n        for (Index j = 0; j < posedata[i].homography.size(); j++) {\n            zr[j] = posedata[i].homography(j);\n        }\n        mxSetFieldByNumber(plhs[0],i,H_field,field_value);\n\n        // Create f1\n        field_value = mxCreateDoubleMatrix(1, 1, mxCOMPLEX);\n        zr = mxGetPr(field_value);\n        zr[0] = posedata[i].focal_length1;\n        mxSetFieldByNumber(plhs[0],i,f1_field,field_value);\n\n        // Create f2\n        field_value = mxCreateDoubleMatrix(1, 1, mxCOMPLEX);\n        zr = mxGetPr(field_value);\n        zr[0] = posedata[i].focal_length2;\n        mxSetFieldByNumber(plhs[0],i,f2_field,field_value);\n    }\n}\n#endif\n", "meta": {"hexsha": "142a9e3741eadd9faea8fba90a121534c8a4fe8e", "size": 5871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/floor_f1Hf2/get_floor_f1Hf2.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_f1Hf2/get_floor_f1Hf2.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_f1Hf2/get_floor_f1Hf2.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.5485714286, "max_line_length": 159, "alphanum_fraction": 0.6048373361, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.584042356725084}}
{"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/eight_point_fundamental_matrix.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\n\nusing Eigen::JacobiSVD;\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\n\nbool NormalizedEightPointFundamentalMatrix(\n    const std::vector<Vector2d>& image_1_points,\n    const std::vector<Vector2d>& image_2_points,\n    Matrix3d* fundamental_matrix) {\n  CHECK_EQ(image_1_points.size(), image_2_points.size());\n  CHECK_GE(image_1_points.size(), 8);\n\n  std::vector<Vector2d> norm_img1_points(image_1_points.size());\n  std::vector<Vector2d> norm_img2_points(image_2_points.size());\n\n  // Normalize the image points.\n  Matrix3d img1_norm_mat, img2_norm_mat;\n  NormalizeImagePoints(image_1_points, &norm_img1_points, &img1_norm_mat);\n  NormalizeImagePoints(image_2_points, &norm_img2_points, &img2_norm_mat);\n\n  // Build the constraint matrix based on x2' * F * x1 = 0.\n  Matrix<double, Eigen::Dynamic, 9> constraint_matrix(image_1_points.size(), 9);\n  for (int i = 0; i < image_1_points.size(); i++) {\n    constraint_matrix.block<1, 3>(i, 0) = norm_img1_points[i].homogeneous();\n    constraint_matrix.block<1, 3>(i, 0) *= norm_img2_points[i].x();\n    constraint_matrix.block<1, 3>(i, 3) = norm_img1_points[i].homogeneous();\n    constraint_matrix.block<1, 3>(i, 3) *= norm_img2_points[i].y();\n    constraint_matrix.block<1, 3>(i, 6) = norm_img1_points[i].homogeneous();\n  }\n\n  // Solve the constraint equation for F from nullspace extraction.\n  // An LU decomposition is efficient for the minimally constrained case.\n  // Otherwise, use an SVD.\n  Matrix<double, 9, 1> normalized_fvector;\n  if (image_1_points.size() == 8) {\n    const auto lu_decomposition = constraint_matrix.fullPivLu();\n    if (lu_decomposition.dimensionOfKernel() != 1) {\n      return false;\n    }\n    normalized_fvector = lu_decomposition.kernel();\n  } else {\n    JacobiSVD<Matrix<double, Eigen::Dynamic, 9> > cmatrix_svd(\n        constraint_matrix, Eigen::ComputeFullV);\n    normalized_fvector = cmatrix_svd.matrixV().col(8);\n  }\n\n  // NOTE: This is the transpose of a valid fundamental matrix! We implement a\n  // \"lazy\" transpose and defer it to the SVD a few lines below.\n  Eigen::Map<const Matrix3d> normalized_fmatrix(normalized_fvector.data());\n\n  // Find the closest singular matrix to F under frobenius norm. We can compute\n  // this matrix with SVD.\n  JacobiSVD<Matrix3d> fmatrix_svd(normalized_fmatrix.transpose(),\n                                  Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Vector3d singular_values = fmatrix_svd.singularValues();\n  singular_values[2] = 0.0;\n  *fundamental_matrix = fmatrix_svd.matrixU() * singular_values.asDiagonal() *\n                        fmatrix_svd.matrixV().transpose();\n\n  // Correct for the point normalization.\n  *fundamental_matrix =\n      img2_norm_mat.transpose() * (*fundamental_matrix) * img1_norm_mat;\n\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "071755981d189738698c14205556928cf9825bef", "size": 4863, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/eight_point_fundamental_matrix.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/pose/eight_point_fundamental_matrix.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/pose/eight_point_fundamental_matrix.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 41.9224137931, "max_line_length": 80, "alphanum_fraction": 0.7300020563, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5839788340893081}}
{"text": "/**\n * @file MPCExample.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the BSD 3-Clause License\n * @date 2018\n */\n\n\n// osqp-eigen\n#include \"OsqpEigen/OsqpEigen.h\"\n\n// eigen\n#include <Eigen/Dense>\n\n#include <iostream>\n\nvoid setDynamicsMatrices(Eigen::Matrix<double, 2, 2> &a, Eigen::Matrix<double, 2, 1> &b)\n{\n    a << 1.,      0.020,\n        0.,      0.9661;\n\n    b << 0.,\n        0.0315;\n}\n\n\nvoid setInequalityConstraints(Eigen::Matrix<double, 2, 1> &xMax, Eigen::Matrix<double, 2, 1> &xMin,\n                              Eigen::Matrix<double, 1, 1> &uMax, Eigen::Matrix<double, 1, 1> &uMin)\n{\n    double u0 = 0.0;\n\n    // input inequality constraints\n    uMin << -6.0 - u0;\n\n    uMax << 10.0 - u0;\n\n    // state inequality constraints\n    // TODO : change to present pos +/- ranges\n    xMin << -100, -6.0;\n\n    xMax << 100, 10.0;\n}\n\nvoid setWeightMatrices(Eigen::DiagonalMatrix<double, 2> &Q, Eigen::DiagonalMatrix<double, 1> &R)\n{\n    Q.diagonal() << 2, 0;\n    R.diagonal() << 0.2;\n}\n\nvoid castMPCToQPHessian(const Eigen::DiagonalMatrix<double, 2> &Q, const Eigen::DiagonalMatrix<double, 1> &R, int mpcWindow,\n                        Eigen::SparseMatrix<double> &hessianMatrix)\n{\n\n    hessianMatrix.resize(2*(mpcWindow+1) + 1 * mpcWindow, 2*(mpcWindow+1) + 1 * mpcWindow);\n\n    //populate hessian matrix\n    for(int i = 0; i<2*(mpcWindow+1) + 1 * mpcWindow; i++){\n        if(i < 2*(mpcWindow+1)){\n            int posQ=i%2;\n            float value = Q.diagonal()[posQ];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n        else{\n            int posR=i%1;\n            float value = R.diagonal()[posR];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n    }\n}\n\nvoid castMPCToQPGradient(const Eigen::DiagonalMatrix<double, 2> &Q, const Eigen::Matrix<double, 2, 1> &xRef, int mpcWindow,\n                         Eigen::VectorXd &gradient)\n{\n\n    Eigen::Matrix<double,2,1> Qx_ref;\n    Qx_ref = Q * (-xRef);\n\n    // populate the gradient vector\n    gradient = Eigen::VectorXd::Zero(2*(mpcWindow+1) +  1*mpcWindow, 1);\n    for(int i = 0; i<2*(mpcWindow+1); i++){\n        int posQ=i%2;\n        float value = Qx_ref(posQ,0);\n        gradient(i,0) = value;\n    }\n}\n\nvoid castMPCToQPConstraintMatrix(const Eigen::Matrix<double, 2, 2> &dynamicMatrix, const Eigen::Matrix<double, 2, 1> &controlMatrix,\n                                 int mpcWindow, Eigen::SparseMatrix<double> &constraintMatrix)\n{\n    constraintMatrix.resize(2*(mpcWindow+1)  + 2*(mpcWindow+1) + 1 * mpcWindow, 2*(mpcWindow+1) + 1 * mpcWindow);\n\n    // populate linear constraint matrix\n    for(int i = 0; i<2*(mpcWindow+1); i++){\n        constraintMatrix.insert(i,i) = -1;\n    }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j<2; j++)\n            for(int k = 0; k<2; k++){\n                float value = dynamicMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(2 * (i+1) + j, 2 * i + k) = value;\n                }\n            }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j < 2; j++)\n            for(int k = 0; k < 1; k++){\n                float value = controlMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(2*(i+1)+j, 1*i+k+2*(mpcWindow + 1)) = value;\n                }\n            }\n\n    for(int i = 0; i<2*(mpcWindow+1) + 1*mpcWindow; i++){\n        constraintMatrix.insert(i+(mpcWindow+1)*2,i) = 1;\n    }\n}\n\nvoid castMPCToQPConstraintVectors(const Eigen::Matrix<double, 2, 1> &xMax, const Eigen::Matrix<double, 2, 1> &xMin,\n                                   const Eigen::Matrix<double, 1, 1> &uMax, const Eigen::Matrix<double, 1, 1> &uMin,\n                                   const Eigen::Matrix<double, 2, 1> &x0,\n                                   int mpcWindow, Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    // evaluate the lower and the upper inequality vectors\n    Eigen::VectorXd lowerInequality = Eigen::MatrixXd::Zero(2*(mpcWindow+1) +  1 * mpcWindow, 1);\n    Eigen::VectorXd upperInequality = Eigen::MatrixXd::Zero(2*(mpcWindow+1) +  1 * mpcWindow, 1);\n    for(int i=0; i<mpcWindow+1; i++){\n        lowerInequality.block(2*i,0,2,1) = xMin;\n        upperInequality.block(2*i,0,2,1) = xMax;\n    }\n    for(int i=0; i<mpcWindow; i++){\n        lowerInequality.block(1 * i + 2 * (mpcWindow + 1), 0, 1, 1) = uMin;\n        upperInequality.block(1 * i + 2 * (mpcWindow + 1), 0, 1, 1) = uMax;\n    }\n\n    // evaluate the lower and the upper equality vectors\n    Eigen::VectorXd lowerEquality = Eigen::MatrixXd::Zero(2*(mpcWindow+1),1 );\n    Eigen::VectorXd upperEquality;\n    lowerEquality.block(0,0,2,1) = -x0;\n    upperEquality = lowerEquality;\n    lowerEquality = lowerEquality;\n\n    // merge inequality and equality vectors\n    lowerBound = Eigen::MatrixXd::Zero(2*2*(mpcWindow+1) +  1*mpcWindow,1 );\n    lowerBound << lowerEquality,\n        lowerInequality;\n\n    upperBound = Eigen::MatrixXd::Zero(2*2*(mpcWindow+1) +  1*mpcWindow,1 );\n    upperBound << upperEquality,\n        upperInequality;\n}\n\n\nvoid updateConstraintVectors(const Eigen::Matrix<double, 2, 1> &x0,\n                             Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    lowerBound.block(0,0,2,1) = -x0;\n    upperBound.block(0,0,2,1) = -x0;\n}\n\n\ndouble getErrorNorm(const Eigen::Matrix<double, 2, 1> &x,\n                    const Eigen::Matrix<double, 2, 1> &xRef)\n{\n    // evaluate the error\n    Eigen::Matrix<double, 2, 1> error = x - xRef;\n\n    // return the norm\n    return error.norm();\n}\n\n\nint main()\n{\n    // set the preview window\n    int mpcWindow = 200;\n\n    // allocate the dynamics matrices\n    Eigen::Matrix<double, 2, 2> a;\n    Eigen::Matrix<double, 2, 1> b;\n\n    // allocate the constraints vector\n    Eigen::Matrix<double, 2, 1> xMax;\n    Eigen::Matrix<double, 2, 1> xMin;\n    Eigen::Matrix<double, 1, 1> uMax;\n    Eigen::Matrix<double, 1, 1> uMin;\n\n    // allocate the weight matrices\n    Eigen::DiagonalMatrix<double, 2> Q;\n    Eigen::DiagonalMatrix<double, 1> R;\n\n    // allocate the initial and the reference state space\n    Eigen::Matrix<double, 2, 1> x0;\n    Eigen::Matrix<double, 2, 1> xRef;\n\n    // allocate QP problem matrices and vectores\n    Eigen::SparseMatrix<double> hessian;\n    Eigen::VectorXd gradient;\n    Eigen::SparseMatrix<double> linearMatrix;\n    Eigen::VectorXd lowerBound;\n    Eigen::VectorXd upperBound;\n\n    // set the initial and the desired states\n    x0 << 0, 0 ;\n    xRef <<  1, 0;\n\n    // set MPC problem quantities\n    setDynamicsMatrices(a, b);\n    setInequalityConstraints(xMax, xMin, uMax, uMin);\n    setWeightMatrices(Q, R);\n\n    // cast the MPC problem as QP problem\n    castMPCToQPHessian(Q, R, mpcWindow, hessian);\n    castMPCToQPGradient(Q, xRef, mpcWindow, gradient);\n    castMPCToQPConstraintMatrix(a, b, mpcWindow, linearMatrix);\n    castMPCToQPConstraintVectors(xMax, xMin, uMax, uMin, x0, mpcWindow, lowerBound, upperBound);\n\n    // instantiate the solver\n    OsqpEigen::Solver solver;\n\n    // settings\n    //solver.settings()->setVerbosity(false);\n    solver.settings()->setWarmStart(true);\n\n    // set the initial data of the QP solver\n    solver.data()->setNumberOfVariables(2 * (mpcWindow + 1) + 1 * mpcWindow);\n    solver.data()->setNumberOfConstraints(2 * 2 * (mpcWindow + 1) + 1 * mpcWindow);\n    if(!solver.data()->setHessianMatrix(hessian)) return 1;\n    if(!solver.data()->setGradient(gradient)) return 1;\n    if(!solver.data()->setLinearConstraintsMatrix(linearMatrix)) return 1;\n    if(!solver.data()->setLowerBound(lowerBound)) return 1;\n    if(!solver.data()->setUpperBound(upperBound)) return 1;\n\n    // instantiate the solver\n    if(!solver.initSolver()) return 1;\n\n    // controller input and QPSolution vector\n    Eigen::VectorXd ctr;\n    Eigen::VectorXd QPSolution;\n\n    // number of iteration steps\n    int numberOfSteps = 200;\n\n    for (int i = 0; i < numberOfSteps; i++){\n\n        // solve the QP problem\n        if(solver.solveProblem() != OsqpEigen::ErrorExitFlag::NoError) return 1;\n\n        // get the controller input\n        QPSolution = solver.getSolution();\n        ctr = QPSolution.block(2 * (mpcWindow + 1), 0, 1, 1);\n\n        // save data into file\n        auto x0Data = x0.data();\n\n        // propagate the model\n        x0 = a * x0 + b * ctr;\n\n        // update the constraint bound\n        updateConstraintVectors(x0, lowerBound, upperBound);\n        if(!solver.updateBounds(lowerBound, upperBound)) return 1;\n      }\n    return 0;\n}\n", "meta": {"hexsha": "7ecedca4c4b7b718457deba08c528cb01f9eedd4", "size": 8525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/src/MPCExampleFlaptter.cpp", "max_stars_repo_name": "marunmurali/osqp-eigen", "max_stars_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/src/MPCExampleFlaptter.cpp", "max_issues_repo_name": "marunmurali/osqp-eigen", "max_issues_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/src/MPCExampleFlaptter.cpp", "max_forks_repo_name": "marunmurali/osqp-eigen", "max_forks_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_forks_repo_licenses": ["BSD-3-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.8097014925, "max_line_length": 132, "alphanum_fraction": 0.595542522, "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5839788205582566}}
{"text": "// blas.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include <iostream>\n\n/*\n#ifdef _WIN32\n#undef __STRICT_ANSI__\n#endif\n*/\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nconst boost::numeric::ublas::matrix<double> CreateMatrix(\n    const std::size_t n_rows,\n    const std::size_t n_cols,\n    const std::vector<double>& v)\n{\n    assert(n_rows * n_cols == v.size());\n    boost::numeric::ublas::matrix<double> m(n_rows, n_cols);\n    for (std::size_t row = 0; row != n_rows; ++row)\n    {\n        for (std::size_t col = 0; col != n_cols; ++col)\n        {\n            m(row, col) = v[(col * n_rows) + row];\n        }\n    }\n    return m;\n}\n\n//Chop returns a std::vector of sub-matrices\n//[ A at [0]   B at [1] ]\n//[ C at [2]   D at [4] ]\nconst std::vector<boost::numeric::ublas::matrix<double> > Chop(\n    const boost::numeric::ublas::matrix<double>& m)\n{\n    //using boost::numeric::ublas::range;\n    //using boost::numeric::ublas::matrix;\n    //using boost::numeric::ublas::matrix_range;\n    std::vector<boost::numeric::ublas::matrix<double> > v;\n    v.reserve(4);\n    const int midy = m.size1() / 2;\n    const int midx = m.size2() / 2;\n    const boost::numeric::ublas::matrix_range<const boost::numeric::ublas::matrix<double> > top_left(m, boost::numeric::ublas::range(0, midy), boost::numeric::ublas::range(0, midx));\n    const boost::numeric::ublas::matrix_range<const boost::numeric::ublas::matrix<double> > bottom_left(m, boost::numeric::ublas::range(midy, m.size1()), boost::numeric::ublas::range(0, midx));\n    const boost::numeric::ublas::matrix_range<const boost::numeric::ublas::matrix<double> > top_right(m, boost::numeric::ublas::range(0, midy), boost::numeric::ublas::range(midx, m.size2()));\n    const boost::numeric::ublas::matrix_range<const boost::numeric::ublas::matrix<double> > bottom_right(m, boost::numeric::ublas::range(midy, m.size1()), boost::numeric::ublas::range(midx, m.size2()));\n    v.push_back(boost::numeric::ublas::matrix<double>(top_left));\n    v.push_back(boost::numeric::ublas::matrix<double>(top_right));\n    v.push_back(boost::numeric::ublas::matrix<double>(bottom_left));\n    v.push_back(boost::numeric::ublas::matrix<double>(bottom_right));\n    return v;\n}\n\nbool IsAboutEqual(const double x, const double y) { return std::abs(x - y) < 0.00001; }\n\nint main()\n{\n    //using boost::numeric::ublas::matrix;\n    //using boost::numeric::ublas::prod;\n    //using boost::numeric::ublas::vector;\n    {\n        //                     [ 1.0 ] | [ 2.0   3.0 ]\n        // [ 1.0 2.0 3.0 ]     --------+--------------\n        // [ 4.0 5.0 6.0 ]     [ 4.0 ] | [ 5.0   6.0 ]\n        // [ 7.0 8.0 9.0 ] ->  [ 7.0 ] | [ 8.0   9.0 ]\n        const boost::numeric::ublas::matrix<double> m = CreateMatrix(3, 3, { 1.0,4.0,7.0,2.0,5.0,8.0,3.0,6.0,9.0 });\n        assert(m(0, 0) == 1.0); assert(m(0, 1) == 2.0); assert(m(0, 2) == 3.0);\n        assert(m(1, 0) == 4.0); assert(m(1, 1) == 5.0); assert(m(1, 2) == 6.0);\n        assert(m(2, 0) == 7.0); assert(m(2, 1) == 8.0); assert(m(2, 2) == 9.0);\n        const std::vector<boost::numeric::ublas::matrix<double> > n = Chop(m);\n        assert(n.size() == 4);\n        std::wclog\n            << L\"m   : \" << m << L'\\n'\n            << L\"n[0]: \" << n[0] << L'\\n'\n            << L\"n[1]: \" << n[1] << L'\\n'\n            << L\"n[2]: \" << n[2] << L'\\n'\n            << L\"n[3]: \" << n[3] << L'\\n';\n        assert(n[0].size1() == 1);\n        assert(n[0].size2() == 1);\n        assert(n[1].size1() == 1);\n        assert(n[1].size2() == 2);\n        assert(n[2].size1() == 2);\n        assert(n[2].size2() == 1);\n        assert(n[3].size1() == 2);\n        assert(n[3].size2() == 2);\n        assert(n[0].size1() + n[2].size1() == m.size1());\n        assert(n[1].size1() + n[3].size1() == m.size1());\n        assert(n[0].size2() + n[1].size2() == m.size2());\n        assert(n[2].size2() + n[3].size2() == m.size2());\n    }\n    {\n        const boost::numeric::ublas::matrix<double> m = CreateMatrix(5, 5,\n            {\n              1.0, 6.0,11.0,16.0,21.0,\n              2.0, 7.0,12.0,17.0,22.0,\n              3.0, 8.0,13.0,18.0,23.0,\n              4.0, 9.0,14.0,19.0,24.0,\n              5.0,10.0,15.0,20.0,25.0\n            }\n        );\n        assert(m(0, 0) == 1.0); assert(m(0, 1) == 2.0); assert(m(0, 2) == 3.0); assert(m(0, 3) == 4.0); assert(m(0, 4) == 5.0);\n        assert(m(1, 0) == 6.0); assert(m(1, 1) == 7.0); assert(m(1, 2) == 8.0); assert(m(1, 3) == 9.0); assert(m(1, 4) == 10.0);\n        assert(m(2, 0) == 11.0); assert(m(2, 1) == 12.0); assert(m(2, 2) == 13.0); assert(m(2, 3) == 14.0); assert(m(2, 4) == 15.0);\n        assert(m(3, 0) == 16.0); assert(m(3, 1) == 17.0); assert(m(3, 2) == 18.0); assert(m(3, 3) == 19.0); assert(m(3, 4) == 20.0);\n        assert(m(4, 0) == 21.0); assert(m(4, 1) == 22.0); assert(m(4, 2) == 23.0); assert(m(4, 3) == 24.0); assert(m(4, 4) == 25.0);\n        const std::vector<boost::numeric::ublas::matrix<double> > n = Chop(m);\n        assert(n.size() == 4);\n        std::wclog\n            << L\"m   : \" << m << L'\\n'\n            << L\"n[0]: \" << n[0] << L'\\n'\n            << L\"n[1]: \" << n[1] << L'\\n'\n            << L\"n[2]: \" << n[2] << L'\\n'\n            << L\"n[3]: \" << n[3] << L'\\n';\n        assert(n[0].size1() == 2);\n        assert(n[0].size2() == 2);\n        assert(n[1].size1() == 2);\n        assert(n[1].size2() == 3);\n        assert(n[2].size1() == 3);\n        assert(n[2].size2() == 2);\n        assert(n[3].size1() == 3);\n        assert(n[3].size2() == 3);\n        assert(n[0].size1() + n[2].size1() == m.size1());\n        assert(n[1].size1() + n[3].size1() == m.size1());\n        assert(n[0].size2() + n[1].size2() == m.size2());\n        assert(n[2].size2() + n[3].size2() == m.size2());\n    }\n}\n", "meta": {"hexsha": "2453ad65f62fcc4e899da9cb260d84ad781ad8be", "size": 5817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/blas/blas.cpp", "max_stars_repo_name": "ssyang/test.cpp", "max_stars_repo_head_hexsha": "21c460d08d62f972b1bc137a64f41498f2138c35", "max_stars_repo_licenses": ["MIT"], "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/blas/blas.cpp", "max_issues_repo_name": "ssyang/test.cpp", "max_issues_repo_head_hexsha": "21c460d08d62f972b1bc137a64f41498f2138c35", "max_issues_repo_licenses": ["MIT"], "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/blas/blas.cpp", "max_forks_repo_name": "ssyang/test.cpp", "max_forks_repo_head_hexsha": "21c460d08d62f972b1bc137a64f41498f2138c35", "max_forks_repo_licenses": ["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.4045801527, "max_line_length": 202, "alphanum_fraction": 0.5043837029, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5839749939288963}}
{"text": "/*  \n*  Copyright August 2015\n*  Author: Olalekan P. Ogunmolu\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* \n* See the License for the specific language governing permissions and\n* limitations under the License.\n* \n*/\n\n// Include Files\n#include \"savgol.h\"\n\n#include <Eigen/Core>\n\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid help()\n{\n  std::cout << \"================================================== \\n\" \n            << \"USAGE:                                             \\n\"\n            << \"\\n\"\n            << \"./savgol [<frame_size> [<polynomial_order> [<x_low> <x_high>] ] ] \\n\" \n            << \"\\n\"\n            << \"       <frame_size>: odd int and ideally greater than\\n\" \n            << \"       <polynomial_order>:  an integer             \\n\" \n            << \"\\n\"\n            << \"       <x_low>, <x_high>: min and max limits of    \\n\"\n            << \"       linspaced vector to be filtered.            \\n\"\n            << \"===================================================\\n\" \n            << \"       Example: ./savgol 9 5   \\n\\n\";;\n}\n\n\nint main (int argc, char** argv)\n{\n  int F;      //Frame Size\n  int k;      //Example Polynomial Order\n  double Fd ;\n  float x_min, x_max;\n\n  if(argc>1)\n  { \n    if(argv[1] == \"-h\" || \"-help\")\n    {\n      help();\n      return EXIT_SUCCESS;\n    }\n    else\n    {\n      for(auto i = 1; i < argc; ++i )\n      {\n        F = atoi(argv[1]);\n        k = atoi(argv[2]);\n        x_min = atoi(argv[3]);\n        x_max = atoi(argv[4]);\n      }\n    }\n  }\n  else  //use default values\n  {\n    F = 5; k = 3;\n    x_min = 900.0; x_max = 980.0;\n  }\n\n  auto s = vander(F);        //Compute vandermonde matrix\n\n  cout << \"Frame size: \" << F << \"; \\tPolynomial order: \" << k << endl;\n  cout << \"\\n Vandermonde Matrix: \\n\" << s  << endl;\n\n  k = atoi(argv[2]) or 3;\n\n  auto B = sgdiff(k, F, Fd);\n\n  //To express as a real filtering operation, we shift x around the nth time instant\n  auto x = VectorXf::LinSpaced(F, x_min, x_max);\n\n  auto Filter = savgolfilt(x, k, F);\n\n  cout <<\"\\n\\nFiltered values in the range \\n\" << x.transpose().eval() <<\"\\n are: \\n\" << Filter << endl;\n\n  return 0;\n}\n\n/* Compile:\ncd ../; rm build -rf; mkdir build; cd build; cmake ../; make; ./savgol\n*/\n", "meta": {"hexsha": "11e48d9e8f5a50b826b1804059ca634e84fd96bc", "size": 2623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "lakehanne/Vandermonde", "max_stars_repo_head_hexsha": "6b9855003bb55d400d9e9ac5208832682f0a4b6b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2016-01-21T03:40:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T20:03:17.000Z", "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "lakehanne/Vandermonde", "max_issues_repo_head_hexsha": "6b9855003bb55d400d9e9ac5208832682f0a4b6b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-06-23T21:10:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T22:33:20.000Z", "max_forks_repo_path": "example.cpp", "max_forks_repo_name": "lakehanne/Vandermonde", "max_forks_repo_head_hexsha": "6b9855003bb55d400d9e9ac5208832682f0a4b6b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T22:32:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-19T08:27:46.000Z", "avg_line_length": 26.23, "max_line_length": 104, "alphanum_fraction": 0.5177277926, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.5839749819457449}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// tutorial1.cc\n//                     \t\t  Pressio\n//                             Copyright 2019\n//    National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#include <array>\n#include <Eigen/Core>\n\n#include \"pressio/type_traits.hpp\"\n#include \"pressio/ops.hpp\"\n\nstruct MyCustomVector\n{\n  MyCustomVector(std::size_t ext) : d_(ext){}\n\n  double & operator()(int i){ return d_[i]; }\n  const double & operator()(int i)const { return d_[i]; }\n\n  std::size_t extent(int k)const { return (k==0) ? d_.size() : 0; }\n\n  void fill(double value){\n    std::for_each(d_.begin(), d_.end(), [](double & v){ v= 0.; });\n  }\n\nprivate:\n  std::vector<double> d_ = {};\n};\n\nstruct MyCustomMatrix\n{\n  MyCustomMatrix(std::size_t nr, std::size_t nc)\n    : num_rows_(nr), num_cols_(nc), d_(nr*nc){}\n\n  std::size_t extent(int k)const { return (k==0) ? num_rows_ : num_cols_; }\n\n  double & operator()(int i, int j){ return d_[num_cols_*i+j]; }\n  const double & operator()(int i, int j) const { return d_[num_cols_*i+j]; }\n\n  void fill(double value){\n    std::for_each(d_.begin(), d_.end(), [=](double & v){ v=value; });\n  }\n\nprivate:\n  std::size_t num_rows_ = {};\n  std::size_t num_cols_ = {};\n  std::vector<double> d_ = {};\n};\n\nstruct MyRosenbrockSystem\n{\n  using scalar_type   = double;\n  using state_type    = Eigen::VectorXd;\n  using residual_type = MyCustomVector;\n  using jacobian_type = MyCustomMatrix;\n\n  residual_type createResidual() const{ return residual_type(6);   }\n  jacobian_type createJacobian() const{ return jacobian_type(6, 4);}\n\n  void residual(const state_type& x, residual_type & res) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    const auto & x4 = x(3);\n    res(0) = 10.*(x4 - x3*x3);\n    res(1) = 10.*(x3 - x2*x2);\n    res(2) = 10.*(x2 - x1*x1);\n    res(3) = (1.-x1);\n    res(4) = (1.-x2);\n    res(5) = (1.-x3);\n  }\n\n  void jacobian(const state_type & x, jacobian_type & JJ) const\n  {\n    const auto & x1 = x(0);\n    const auto & x2 = x(1);\n    const auto & x3 = x(2);\n    JJ.fill(0.);\n\n    JJ(0,2) = -20.*x3;\n    JJ(0,3) = 10.;\n    JJ(1,1) = -20.*x2;\n    JJ(1,2) = 10.;\n    JJ(2,0) = -20.*x1;\n    JJ(2,1) = 10.;\n    JJ(3,0) = -1.;\n    JJ(4,1) = -1.;\n    JJ(5,2) = -1.;\n  }\n};\n\nnamespace pressio{\ntemplate<> struct Traits<MyCustomVector>{\n  using scalar_type = double;\n};\n\ntemplate<> struct Traits<MyCustomMatrix>{\n  using scalar_type = double;\n};\n\nnamespace ops{\nMyCustomVector clone(const MyCustomVector & src){ return src; }\nMyCustomMatrix clone(const MyCustomMatrix & src){ return src; }\n\nvoid set_zero(MyCustomVector & o){ o.fill(0); }\nvoid set_zero(MyCustomMatrix & o){ o.fill(0); }\n\ndouble norm2(const MyCustomVector & v){\n  double norm{0};\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    norm += v(i)*v(i);\n  }\n  return std::sqrt(norm);\n}\n\ntemplate<class HessianType>\nvoid product(pressio::transpose, pressio::nontranspose,\n\t     const double alpha,\n\t     const MyCustomMatrix & A,\n\t     const double beta,\n\t     HessianType & H)\n{\n  for (std::size_t i=0; i<A.extent(1); ++i){\n    for (std::size_t j=0; j<A.extent(1); ++j)\n    {\n      H(i,j) *= beta;\n      for (std::size_t k=0; k<A.extent(0); ++k){\n\tH(i,j) += alpha * A(k,i) * A(k,j);\n      }\n    }\n  }\n}\n\ntemplate<class GradientType>\nvoid product(pressio::transpose,\n\t     const double alpha,\n\t     const MyCustomMatrix & A,\n\t     const MyCustomVector & b,\n\t     const double beta,\n\t     GradientType & g)\n{\n  for (int i=0; i<g.rows(); ++i){\n    g(i) *= beta;\n    for (std::size_t k=0; k<A.extent(0); ++k){\n      g(i) += alpha * A(k,i) * b(k);\n    }\n  }\n}\n\ntemplate<class HessianType>\nHessianType product(pressio::transpose, pressio::nontranspose,\n\t     double alpha,\n\t     const MyCustomMatrix & A)\n{\n  HessianType H(A.extent(1), A.extent(1));\n  product(pressio::transpose(), pressio::nontranspose(), alpha, A, 0, H);\n  return H;\n}\n\nvoid update(MyCustomVector & v, double a, const MyCustomVector & v1, double b)\n{\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    v(i) = v(i)*a + b*v1(i);\n  }\n}\n\nvoid scale(MyCustomVector & v, double factor){\n  for (std::size_t i=0; i<v.extent(0); ++i){\n    v(i) = v(i)*factor;\n  }\n}\n}}//end namespace pressio::ops\n\n\n#include \"pressio/solvers_linear.hpp\"\n#include \"pressio/solvers_nonlinear.hpp\"\n\nint main()\n{\n  namespace plog   = pressio::log;\n  namespace pls    = pressio::linearsolvers;\n  namespace pnonls = pressio::nonlinearsolvers;\n  plog::initialize(pressio::logto::terminal);\n  plog::setVerbosity({plog::level::info});\n\n  using problem_t = MyRosenbrockSystem;\n  problem_t problem;\n\n  using state_t   = Eigen::VectorXd;\n  state_t x(4);\n  x[0] = -0.05; x[1] = 1.1; x[2] = 1.2; x[3] = 1.5;\n\n  using hessian_t    = Eigen::MatrixXd;\n  using lin_tag      = pls::direct::HouseholderQR;\n  using lin_solver_t = pls::Solver<lin_tag, hessian_t>;\n  lin_solver_t linSolver;\n\n  auto gnSolver = pnonls::create_gauss_newton(problem, x, linSolver);\n  gnSolver.setTolerance(1e-5);\n  gnSolver.solve(problem, x);\n  std::cout << std::setprecision(14) << x << std::endl;\n  // check solution\n  std::cout << \"Computed solution: \\n \"\n            << \"[\" << x(0) << \" \" << x(1) << \" \" << x(2) << \" \" << x(3) << \" \" << \"] \\n\"\n            << \"Expected solution: \\n \"\n            << \"[1.0000000156741, 0.99999999912477, 0.99999999651993, 0.99999998889888]\"\n            << std::endl;\n\n\n  std::vector<double> gold = {\n    1.00000001567414e+00,\n    9.99999999124769e-01,\n    9.99999996519930e-01,\n    9.99999988898883e-01};\n\n  std::string sentinel = \"PASSED\";\n  const auto e1 = std::abs(x(0) - gold[0]);\n  const auto e2 = std::abs(x(1) - gold[1]);\n  const auto e3 = std::abs(x(2) - gold[2]);\n  const auto e4 = std::abs(x(3) - gold[3]);\n  if (e1>1e-6 or e2>1e-6  or e3>1e-6 or e4>1e-6){\n    sentinel = \"FAILED\";\n  }\n  std::cout << sentinel << std::endl;\n\n  plog::finalize();\n  return 0;\n}\n", "meta": {"hexsha": "f91d13caafe31c79d594f0e4775cd3950a56711b", "size": 7753, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/functional_small/solvers_nonlinear/standard_gauss_newton_normal_equations/gn_normal_eq_res_jac_api_rosenbrock4_custom_types.cc", "max_stars_repo_name": "Pressio/pressio", "max_stars_repo_head_hexsha": "e07eb1ed71266490217f2f7a3aad5e1acfecfd4a", "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": "tests/functional_small/solvers_nonlinear/standard_gauss_newton_normal_equations/gn_normal_eq_res_jac_api_rosenbrock4_custom_types.cc", "max_issues_repo_name": "Pressio/pressio", "max_issues_repo_head_hexsha": "e07eb1ed71266490217f2f7a3aad5e1acfecfd4a", "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": "tests/functional_small/solvers_nonlinear/standard_gauss_newton_normal_equations/gn_normal_eq_res_jac_api_rosenbrock4_custom_types.cc", "max_forks_repo_name": "nittaya1990/pressio", "max_forks_repo_head_hexsha": "22fad15ffc00f3e4d880476a5e60b227ac714ef4", "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": 28.5036764706, "max_line_length": 88, "alphanum_fraction": 0.6245324391, "num_tokens": 2331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5839544214806544}}
{"text": "#pragma once\n#ifndef ENHANCED_MADGWICK_HPP\n#define ENHANCED_MADGWICK_HPP\n\n#include <Eigen/Geometry>\n\n/** This enhanced version of the Madgwick filter is a combination of ideas taken from Madgwick et al [2] \n *\tand Admiraal et al [1]. Admiraal improves upon the original Madgwick filter by deriving a steepest \n *\t(as apposed to gradient) descent formulation for calculating the quaternion estimate update \n *\tdirection. This eliminates some of the numerical errors in Madgwick's version while also improving speed\n *\tand precision. \n *\n *\tThe notation used for documentation is as follows: [x](y)\n *\tWhere 'x' is the source and 'y' is the equation number\n *\t\n *\t[1] \tM. Admiraal, S. Wilson and R. Vaidyanathan, \"Improved Formulation of the IMU and MARG \n *\t\t\tOrientation Gradient Descent Algorithm for Motion Tracking in Human-Machine Interfaces,\" in \n *\t\t\tInternational Conference on Multisensor Fusion and Integration for Intelligent Systems, Daegu, \n *\t\t\t2017.\n *\n *\t[2] \tS. O. Madgwick, A. J. Harrison and R. Vaidyanathan, \"Estimation of IMU and MARG Orientation\n *\t\t\tUsing A Gradient Descent Algorithm,\" in International Conference on Rehabilitation Robotics, \n *\t\t\tZurich, 2011.\n *\t\n **/\ntemplate<typename T>\nclass EnhancedMadgwick\n{\npublic:\n\n\tEnhancedMadgwick()\n\t{\n\t\tqAccel.normalize();\n\t\tqMag.normalize();\n\t}\n\t~EnhancedMadgwick() = default;\n\nprivate:\n\tEigen::Quaternion<T> qAccel;\n\tEigen::Quaternion<T> qMag;\n\n\n\t/** Calculates the gradient of the error function when referenced to gravity [1](35). This is then\n\t *\tused in the gradient descent algorithm to take a single step. This calculation assumes the \n\t *\tacceleration reference vector is [0, 0, -1] because, ya know, gravity.\n\t * \n\t *\t@param[in]\testAccelQuaternion\tThe current quaternion estimate of orientation from accelerometer data\n\t *\t@param[in]\tmeasuredAccelVector\tA column matrix [x,y,z]' with measured accelerometer data\n\t *\t@return A quaternion representing the estimated orientation gradient\n\t **/\n\tEigen::Quaternion<T> accelGradient(Eigen::Quaternion<T>& estAccelQuaternion, Eigen::Matrix<T, 3, 1> measuredAccelVector)\n\t{\n\t\tEigen::Matrix<T, 4, 1> result;\n\t\tEigen::Matrix<T, 4, 3> leftProduct;\n\t\tEigen::Matrix<T, 3, 1> rightProduct;\n\n\t\tT qw = estAccelQuaternion.w();\n\t\tT qx = estAccelQuaternion.x();\n\t\tT qy = estAccelQuaternion.y();\n\t\tT qz = estAccelQuaternion.z();\n\t\tT vmx = measuredAccelVector[0];\n\t\tT vmy = measuredAccelVector[1];\n\t\tT vmz = measuredAccelVector[2]; \n\n\n\t\tleftProduct << 2 * (\n\t\t\t qy, -qx, -qw,\n\t\t    -qz, -qw,  qx,\n\t\t\t qw, -qz,  qy,\n\t\t\t-qx, -qy, -qz\n\t\t\t);\n\n\t\trightProduct <<\n\t\t\t 2 * qw*qy, -2 * qx*qz, -vmx,\n\t\t\t-2 * qw*qx - 2 * qy*qz - vmy,\n\t\t\t-qw * qw + qx * qx + qy * qy - qz * qz - vmx;\n\t\t\t\n\t\tresult = leftProduct * rightProduct;\n\t\treturn Eigen::Quaternion<T>(result[0], result[1], result[2], result[3]);\n\t}\n\n\t/** Calculates the gradient of the error function when referenced to the earth's magnetic field. This \n\t *\tis under the assumption that the field is perfectly planar in local space and can be represented\n\t *\tby the vector [Vrx, 0, Vrz]. [1](36)\n\t *\n\t **/\n\tEigen::Quaternion<T> magGradient(Eigen::Quaternion<T>& estMagQuaternion, Eigen::Matrix<T, 3, 1> measuredMagVector, Eigen::Matrix<T, 3, 1> refMagVector)\n\t{\n\t\tEigen::Matrix<T, 4, 1> result;\n\t\tEigen::Matrix<T, 4, 3> leftProduct;\n\t\tEigen::Matrix<T, 3, 1> rightProduct;\n\n\t\tT qw = estMagQuaternion.w();\n\t\tT qx = estMagQuaternion.x();\n\t\tT qy = estMagQuaternion.y();\n\t\tT qz = estMagQuaternion.z();\n\t\tT vmx = measuredMagVector[0];\n\t\tT vmy = measuredMagVector[1];\n\t\tT vmz = measuredMagVector[2];\n\t\tT vrx = refMagVector[0];\n\t\tT vry = 0;\n\t\tT vrz = refMagVector[2];\n\t\t\n\t\tleftProduct << 2 * (\n\t\t\t( vrx*qw - vrz*qy), (-vrx*qz + vrz*qx), (vrx*qy + vrz*qw),\n\t\t\t( vrx*qx + vrz*qz), ( vrx*qy + vrz*qw), (vrx*qz - vrz*qx),\n\t\t\t(-vrx*qy - vrz*qw), ( vrx*qx + vrz*qz), (vrx*qw - vrz*qy),\n\t\t\t(-vrx*qz + vrz*qx), (-vrx*qw + vrz*qy), (vrx*qx + vrz*qz)\n\t\t\t);\n\n\t\trightProduct <<\n\t\t\tvrx * (qw*qw + qx*qx - qy*qy - qz*qz) + vrz * (-2*qw*qy + 2*qx*qz)            - vmx,\n\t\t\tvrx * (-2*qw*qz + 2*qx*qy)\t\t\t  + vrz * (2*qw*qx + 2*qy*qz)\t\t\t  - vmy,\n\t\t\tvrx * (2*qw*qy + 2*qx*qz)\t\t\t  + vrz * (qw*qw - qx*qx - qy*qy + qz*qz) - vmz;\n\n\t\tresult = leftProduct * rightProduct;\n\t\treturn Eigen::Quaternion<T>(result[0], result[1], result[2], result[3]);\n\t}\n\n};\n\n#endif /* !ENHANCED_MADGWICK_HPP */", "meta": {"hexsha": "a62cc289e58baec30bda4f03343b7fcf89520547", "size": 4311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "enhancedMadgwick.hpp", "max_stars_repo_name": "brandonbraun653/EnhancedMadgwick", "max_stars_repo_head_hexsha": "ce753e843b2a9e6480cc9c8617b875af5306f91c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "enhancedMadgwick.hpp", "max_issues_repo_name": "brandonbraun653/EnhancedMadgwick", "max_issues_repo_head_hexsha": "ce753e843b2a9e6480cc9c8617b875af5306f91c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enhancedMadgwick.hpp", "max_forks_repo_name": "brandonbraun653/EnhancedMadgwick", "max_forks_repo_head_hexsha": "ce753e843b2a9e6480cc9c8617b875af5306f91c", "max_forks_repo_licenses": ["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.3360655738, "max_line_length": 152, "alphanum_fraction": 0.6675945256, "num_tokens": 1435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5839029871071773}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved：CC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      版权部分所有，遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用\n *\n * Filename                : \n * Description             : \n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET国家重点实验室FOCUS团队\n * Modification History\t   : ver1.0, 2019.01.08, William Yu\n                             ver1.1, 2019.01.13, William Yu, add notes\n=================================================================================*/\n\n\n/*-----------------------------[Note]---------------------------\n * \n--------------------------------------------------------------*/\n\n\n/// Include Files\n#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n\n/// Global Variables\n\n\n\n\n\n/// Function Declaration\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\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nvoid pose_estimation_3d3d (\n    const vector<Point3f>& pts1,\n    const vector<Point3f>& pts2,\n    Mat& R, Mat& t\n);\n\n\n\n\n\n\n/// Function definitions\n\n/**\n * @function main\n * @brief \n */\nint main ( int argc, char** argv )\n{\n    if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d3d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    //-- 内参矩阵 \n    //--调参：相机内参--\n    //        | fx,  0, cx, | cx主点偏移\n    //   K =  |  0, fy, cy, | \n    //        |  0,  0,  1  |\n    Mat K = ( Mat_<double> ( 3,3 ) << 518.0,     0, 325.5,\n                                          0, 519.0, 253.5, \n                                          0,     0,     1 );\n    double depthScale = 1000.0;\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 depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\n    Mat depth2 = imread ( argv[4], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数，单通道图像\n    \n    vector<Point3f> pts1, pts2;\n    for ( DMatch m:matches )\n    {\n        ushort d1 = depth1.ptr<unsigned short> ( int ( keypoints_1[m.queryIdx].pt.y ) ) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n        ushort d2 = depth2.ptr<unsigned short> ( int ( keypoints_2[m.trainIdx].pt.y ) ) [ int ( keypoints_2[m.trainIdx].pt.x ) ];\n        if ( d1==0 || d2==0 )   // bad depth //深度值为0，无法使用\n            continue;\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );//是测试图像的特征点描述子（descriptor）的下标，同时也是描述符对应特征点（keypoint)的下标。\n        Point2d p2 = pixel2cam ( keypoints_2[m.trainIdx].pt, K );//是样本图像的特征点描述子的下标，同样也是相应的特征点的下标。\n        float dd1 = float ( d1 ) /depthScale;\n        float dd2 = float ( d2 ) /depthScale;\n        pts1.push_back ( Point3f ( p1.x*dd1, p1.y*dd1, dd1 ) );\n        pts2.push_back ( Point3f ( p2.x*dd2, p2.y*dd2, dd2 ) );\n    }\n\n    cout<<\"3d-3d 点对: \"<<pts1.size() <<endl;\n    Mat R, t;\n    pose_estimation_3d3d ( pts1, pts2, R, t );\n    cout<<\"---------------------------------------------\"<<endl;\n    cout<<\"ICP via SVD results: \"<<endl;\n    cout<<\"R_12 = \"<<R<<endl;\n    cout<<\"t_12 = \"<<t<<endl;\n    /*-----------------------------[Note]---------------------------\n    * pts1 = R*pts2 + t\n    * 则有pts2 = R_inv*pts1 - R_inv*t\n    * 对应pts2 = R`*pts1 + t`\n    * 即逆运动R` = R_inv\n    *        t` = - R_inv*t\n    * Notice:旋转矩阵R为正交矩阵，\n    * 所有又有 R^(-1) = R^T，逆等于转置\n    --------------------------------------------------------------*/\n    cout<<\"逆运动R：R` = R_inv = \"<<R.t() <<endl;   //Mat.t()为矩阵求转置\n    //cout<<\"逆运动R：R` = R_inv = \"<<R.inv() <<endl;  //Mat.inv()为矩阵求逆 \n    cout<<\"逆运动t：t` = - R_inv*t = \"<<-R.t() *t <<endl;\n\n    cout<<\"---------------------------------------------\"<<endl;\n    //--校验5组 p1 = R*p2 + t  和  p2 = R_inv*p1 - R_inv*t\n    for ( int i=0; i<5; i++ )\n    {\n        cout<<\"p1 = \"<<pts1[i]<<endl;\n        cout<<\"p2 = \"<<pts2[i]<<endl;\n        cout<<\"(R*p2+t) = \"<<\n            R * (Mat_<double>(3,1)<<pts2[i].x, pts2[i].y, pts2[i].z) + t << endl;\n        cout<<\"(R`*p1+t`) = \"<<\n            R.inv() * (Mat_<double>(3,1)<<pts1[i].x, pts1[i].y, pts1[i].z) -R.inv() *t << endl<< endl;\n    }\n}\n\n\n\n\n\n/**\n * @function find_feature_matches\n * @brief 特征点匹配与筛选\n * @param  const Mat& img_1, const Mat& img_2,\n                            std::vector<KeyPoint>& keypoints_1,\n                            std::vector<KeyPoint>& keypoints_2,\n                            std::vector< DMatch >& good_matches\n * @retval None\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 >& good_matches )\n{\n    //-- 初始化\n    Mat descriptors_1, descriptors_2;\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    Ptr<DescriptorMatcher> matcher  = DescriptorMatcher::create(\"BruteForce-Hamming\");\n\n\n    //--[1]:检测 Oriented FAST 角点位置\n    detector->detect ( img_1,keypoints_1 );\n    detector->detect ( img_2,keypoints_2 );\n\n    //--[2]:根据角点位置计算 BRIEF 描述子\n    descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n    descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n    \n    //绘制特征点\n    Mat outimg1, outimg2;\n    drawKeypoints( img_1, keypoints_1, outimg1, Scalar::all(-1), DrawMatchesFlags::DEFAULT );\n    namedWindow(\"ORB_img1\", WINDOW_NORMAL);\n    imshow(\"ORB_img1\",outimg1);\n    drawKeypoints( img_2, keypoints_2, outimg2, Scalar::all(-1), DrawMatchesFlags::DEFAULT );\n    namedWindow(\"ORB_img2\", WINDOW_NORMAL);\n    imshow(\"ORB_img2\",outimg2);\n    cout<<\"Img1特征点数\"<<keypoints_1.size() <<endl;//500个特征点\n    cout<<\"Img2特征点数\"<<keypoints_2.size() <<endl;\n    \n    //--[3]:对两幅图像中的BRIEF描述子进行匹配，使用 Hamming 距离\n    vector<DMatch> matches;\n    //BFMatcher matcher ( NORM_HAMMING );\n    matcher->match ( descriptors_1, descriptors_2, matches );\n    cout<<\"初步匹配\"<<matches.size() <<\"对匹配点\"<<endl; //500对匹配\n\n    //--[4]:匹配点对筛选\n    //--筛选要求：1.确保都是正确匹配，删去错误匹配\n    //          2.确保正确匹配的前提下，保证点对数足够多\n\n    //--调参：筛选阈值--\n    double min_dist=10000, max_dist=0;\n    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        double dist = matches[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\n    //--调参：筛选阈值--\n    //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.\n    //但有时候最小距离会非常小,设置一个经验值30作为下限.\n    for ( int i = 0; i < descriptors_1.rows; i++ )\n    {\n        if ( matches[i].distance <= max ( 2*min_dist, 30.0 ) )\n        {\n            good_matches.push_back ( matches[i] );\n        }\n    }\n\n    //--TODO：调参：逐点检查--\n\n\n    //--[5]:绘制匹配结果\n    Mat img_match;\n    Mat img_goodmatch;\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    namedWindow(\"img_match\", WINDOW_NORMAL);\n    namedWindow(\"img_goodmatch\", WINDOW_NORMAL);\n    imshow ( \"img_match\", img_match );\n    imshow ( \"img_goodmatch\", img_goodmatch );\n    waitKey(0);\n}\n\n\n\n\n/**\n * @function pixel2cam\n * @brief 像素坐标转相机归一化坐标\n * @param  const Point2d& p, const Mat& K\n * @retval Point2d\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\n\n\n\n/**\n * @function pose_estimation_3d3d\n * @brief   求解R、t\n * @param   const vector<Point3f>& pts1,\n            const vector<Point3f>& pts2,\n            Mat& R, Mat& t\n * @retval None\n */\nvoid pose_estimation_3d3d (\n    const vector<Point3f>& pts1,\n    const vector<Point3f>& pts2,\n    Mat& R, Mat& t\n)\n{\n    Point3f p1, p2;     // center of mass\n    int N = pts1.size();\n    for ( int i=0; i<N; i++ )\n    {\n        p1 += pts1[i];\n        p2 += pts2[i];\n    }\n    p1 = Point3f( Vec3f(p1) /  N);\n    p2 = Point3f( Vec3f(p2) / N);\n    vector<Point3f>     q1 ( N ), q2 ( N ); // remove the center\n    for ( int i=0; i<N; i++ )\n    {\n        q1[i] = pts1[i] - p1;\n        q2[i] = pts2[i] - p2;\n    }\n\n    // compute q1*q2^T\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    for ( int i=0; i<N; i++ )\n    {\n        W += Eigen::Vector3d ( q1[i].x, q1[i].y, q1[i].z ) * Eigen::Vector3d ( q2[i].x, q2[i].y, q2[i].z ).transpose();\n    }\n    cout<<\"W=\"<<W<<endl;\n\n    // SVD on W\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd ( W, Eigen::ComputeFullU|Eigen::ComputeFullV );\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n    \n    if (U.determinant() * V.determinant() < 0)\n\t{\n        for (int x = 0; x < 3; ++x)\n        {\n            U(x, 2) *= -1;\n        }\n\t}\n    \n    cout<<\"U=\"<<U<<endl;\n    cout<<\"V=\"<<V<<endl;\n\n    Eigen::Matrix3d R_ = U* ( V.transpose() );\n    Eigen::Vector3d t_ = Eigen::Vector3d ( p1.x, p1.y, p1.z ) - R_ * Eigen::Vector3d ( p2.x, p2.y, p2.z );\n\n    // convert to cv::Mat\n    R = ( Mat_<double> ( 3,3 ) <<\n          R_ ( 0,0 ), R_ ( 0,1 ), R_ ( 0,2 ),\n          R_ ( 1,0 ), R_ ( 1,1 ), R_ ( 1,2 ),\n          R_ ( 2,0 ), R_ ( 2,1 ), R_ ( 2,2 )\n        );\n    t = ( Mat_<double> ( 3,1 ) << t_ ( 0,0 ), t_ ( 1,0 ), t_ ( 2,0 ) );\n}", "meta": {"hexsha": "29907c80875b1abb2aaf00683206f6c57849f1b5", "size": 10350, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "19.yuSLAM/src/yu_pose_estimation_3d3d.cpp", "max_stars_repo_name": "HustRobot/VSLAM", "max_stars_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "19.yuSLAM/src/yu_pose_estimation_3d3d.cpp", "max_issues_repo_name": "HustRobot/VSLAM", "max_issues_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "19.yuSLAM/src/yu_pose_estimation_3d3d.cpp", "max_forks_repo_name": "HustRobot/VSLAM", "max_forks_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 30.8955223881, "max_line_length": 129, "alphanum_fraction": 0.5282125604, "num_tokens": 3681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5838823252678583}}
{"text": "#include \"sbs/physics/collision/intersections.h\"\n\n#include <Eigen/Geometry>\n\nnamespace sbs {\nnamespace physics {\nnamespace collision {\n\nline_segment_t::line_segment_t(point_t const& p, point_t const& q) : p(p), q(q) {}\n\ntriangle_t::triangle_t(point_t const& a, point_t const& b, point_t const& c) : a(a), b(b), c(c) {}\n\nnormal_t triangle_t::normal() const\n{\n    Eigen::Vector3d const ab = b - a;\n    Eigen::Vector3d const ac = c - a;\n    return ab.cross(ac).normalized();\n}\n\nray_t::ray_t(point_t const& p, direction_t const& v, double t) : p(p), v(v), t(t) {}\n\nstd::optional<point_t> intersect(line_segment_t const& segment, triangle_t const& triangle)\n{\n    Eigen::Vector3d const ab = triangle.b - triangle.a;\n    Eigen::Vector3d const ac = triangle.c - triangle.a;\n    Eigen::Vector3d const qp = segment.p - segment.q;\n\n    Eigen::Vector3d const n = ab.cross(ac);\n\n    double const d = qp.dot(n);\n    if (d <= 0.)\n        return {};\n\n    Eigen::Vector3d const ap = segment.p - triangle.a;\n    double const t           = ap.dot(n);\n    if (t < 0.)\n        return {};\n    if (t > d)\n        return {};\n\n    Eigen::Vector3d const e = qp.cross(ap);\n    double v                = ac.dot(e);\n    if (v < 0. || v > d)\n        return {};\n\n    double w = -ab.dot(e);\n    if (w < 0. || (v + w) > d)\n        return {};\n\n    double const ood = 1. / d;\n    v *= ood;\n    w *= ood;\n    double const u             = 1. - v - w;\n    point_t const intersection = u * triangle.a + v * triangle.b + w * triangle.c;\n    return intersection;\n}\n\nstd::optional<point_t> intersect_twoway(line_segment_t const& segment, triangle_t const& triangle)\n{\n    auto const intersection = intersect(segment, triangle);\n    if (intersection.has_value())\n        return intersection;\n\n    line_segment_t const flipped_segment{segment.q, segment.p};\n    return intersect(flipped_segment, triangle);\n}\n\n} // namespace collision\n} // namespace physics\n} // namespace sbs", "meta": {"hexsha": "9445aa9fd2bedc387d9cef8ea1679c1d53aca6d7", "size": 1933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/physics/collision/intersections.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/collision/intersections.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/collision/intersections.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": 27.6142857143, "max_line_length": 98, "alphanum_fraction": 0.6166580445, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5838823078012363}}
{"text": "#include <Eigen/Core>\n#include <Eigen/LU>\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <random>\n#include \"ProbDistributions.h\"\n#include \"DataSet.h\"\n#include \"Cluster.h\"\nusing namespace std;\n\nint dim = 0;\n\nint pickCandidateCluster(vector<int> *bincount,double d = 0.0)\n{\n\tvector<double> prob_list;\n\tconst double alpha = 0.8;\n\tint n = accumulate(bincount->begin(),bincount->end(),0.0);\n\tint n_k = 0;\n\tint i = 0;\n\tfor(auto bin : *bincount){\n\t\tn_k += bin;\n\t\tprob_list.push_back(((double)n_k - d*(i+1))/(n + alpha));\n\t}\n\n\tdouble r = pd.uniformRand(0.0,1.0);\n\tint candidate_cluster = 0;\n\tfor(auto p : prob_list){\n\t\tif(r < p)\n\t\t\tbreak;\n\t\tcandidate_cluster++;\n\t}\n\n\treturn candidate_cluster;\n}\n\ndouble densityMultiNormal(Data &d, Cluster &c)\n{\n\tEigen::MatrixXd info = c.cov.inverse();\n\tEigen::VectorXd mu = c.mean;//[0],c.mean[1]); \n\tEigen::VectorXd diff = d.normalized_data - mu;\n\n\tdouble det = c.cov.determinant();\n\tdouble a = 1.0/ (pow(2 * 3.151592,c.dimension*0.5) *  sqrt(det));\n\tdouble exp_part = -0.5 * diff.transpose() * info * diff;\n\n\treturn a*exp(exp_part);\n}\n\nbool resampling(DataSet *ds, Clusters *cs, Data *d, vector<int> &bin)\n{\n\tint org_c_num = (int)cs->c.size();\n\tbin[d->cluster_id]--;\n\tint candidate_cluster = pickCandidateCluster(&bin);\n\tbin[d->cluster_id]++;\n\n\tif(candidate_cluster == d->cluster_id){\n\t\treturn false;\n\t}\n\t\n\tCluster *old_cluster = &(cs->c[d->cluster_id]);\n\tdouble eval_new = 0.0;\n\tdouble eval_old = densityMultiNormal(*d,*old_cluster);\n\tCluster c(dim);\n\tif(candidate_cluster == org_c_num){//新しいクラスタ\n\t\teval_new = densityMultiNormal(*d,c);\n\t}else{//既存のクラスタ\n\t\teval_new = densityMultiNormal(*d,cs->c[candidate_cluster]);\n\t}\n\n\tdouble acceptance = eval_new/eval_old;\n\tif(pd.uniformRand(0.0,1.0) >= acceptance)\n\t\treturn false;\n\n\tbin[d->cluster_id]--;\n\td->cluster_id = candidate_cluster;\n\tif(candidate_cluster == org_c_num){\n\t\tcs->c.push_back(c);\n\t\tbin.push_back(1);\n\t}else\n\t\tbin[candidate_cluster]++;\n\treturn true;\n}\n\nvoid sweep(DataSet *ds,Clusters *cs)\n{\n\tvector<int> bincount(cs->c.size(),0);\n\tfor(auto x : ds->x){\n\t\tbincount[x.cluster_id]++;\n\t}\n\n\tint chance = 3;\n\tfor(auto &target : ds->x){\n\t\tfor(int i=0;i<chance;i++){\n\t\t\tresampling(ds,cs,&target,bincount);\n\t\t}\n\t}\n\t//どのクラスタに標本が幾つかる数える\n\tfor(auto &c : cs->c){\n\t\tc.clear();\n\t}\n\tfor(auto &d : ds->x){\n\t\tcs->c[d.cluster_id].regData(&d);\n\t}\n\tcs->calcParams();\n\tcerr << \"----\" << endl;\n}\n\nint main(int argc, char const* argv[])\n{\n\tClusters cs;\n\tDataSet ds;\n\tdim = ds.read();\n\tif(dim <= 0)\n\t\texit(1);\n\n\tint sweep_num = 50;\n\n\t//最初のクラスタを作る。平均値は1軸ごとにガウス分布からサンプリング\n\tcs.c.push_back(Cluster(dim));\n\tfor(auto &d : ds.x){\n\t\tcs.c[d.cluster_id].regData(&d);\n\t}\n\tcs.calcParams();\n\tcerr << \"----\" << endl;\n\n\tfor(int k=0;k<sweep_num;k++){\n\t\tcerr << \"sweep \" << k << endl;\n\t\tsweep(&ds,&cs);\n\t}\n\tds.print();\n\t\n\texit(0);\n}\n", "meta": {"hexsha": "64074b7b03390730918a3a1d942fce62cfb15eb7", "size": 2848, "ext": "cc", "lang": "C++", "max_stars_repo_path": "clustering_nonparametric_bayes/clustering_nonparametric_bayes.cc", "max_stars_repo_name": "ryuichiueda/clustering_commands", "max_stars_repo_head_hexsha": "e4051cf4320b8534635a2008eba6061778eda1d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-12T11:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-12T11:25:47.000Z", "max_issues_repo_path": "clustering_nonparametric_bayes/clustering_nonparametric_bayes.cc", "max_issues_repo_name": "ryuichiueda/clustering_commands", "max_issues_repo_head_hexsha": "e4051cf4320b8534635a2008eba6061778eda1d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clustering_nonparametric_bayes/clustering_nonparametric_bayes.cc", "max_forks_repo_name": "ryuichiueda/clustering_commands", "max_forks_repo_head_hexsha": "e4051cf4320b8534635a2008eba6061778eda1d4", "max_forks_repo_licenses": ["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.6376811594, "max_line_length": 69, "alphanum_fraction": 0.6495786517, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5838653029157111}}
{"text": "#include <math.h>\n#include <vector>\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\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned,K> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds> Delaunay;\ntypedef Delaunay::Face_circulator Face_circulator;\ntypedef Delaunay::Face_handle Face_handle;\ntypedef Delaunay::Point Point;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> MapM3Xd;\ntypedef Eigen::Ref<Matrix3Xd> RefM3Xd;\n\n// Pass the number of points in point cloud and address of the 0th point coords\nstatic double_t pointCloudVolume( std::size_t N, double_t* p ){\n\n    // We will extract 3*N doubles representing particle positions\n    MapM3Xd Xt( p, 3, N );\n    Matrix3Xd X0(3,N);\n\n    // Project the points to a unit sphere\n    X0 = Xt.colwise().normalized();\n\n    // Rotate all points of the shell so that the 0th point is along z-axis\n    Vector3d c = X0.col(0);\n    double_t cos_t = c(2);\n    double_t sin_t = std::sin( std::acos( cos_t ) );\n    Vector3d axis;\n    axis << c(1), -c(0), 0.;\n    axis.normalize();\n    Matrix3d rotMat, axis_cross, outer;\n    axis_cross << 0. , -axis(2), axis(1),\n               axis(2), 0., -axis(0),\n               -axis(1), axis(0), 0.;\n    outer.noalias() = axis*axis.transpose();\n    rotMat = cos_t*Matrix3d::Identity() + sin_t*axis_cross + (1 - cos_t)*outer;\n    Matrix3Xd rPts(3,N);\n    rPts = rotMat*X0;\n\n    // Calculate the stereographic projections\n    Vector3d p0;\n    p0 << 0,0,-1.0; // Point on the plane of projection\n    c = rPts.col(0); // The point from which we are projecting\n\n    MapM3Xd l0( &(rPts(0,1)), 3, N-1 );\n    Matrix3Xd l(3,N-1), proj(3,N-1);\n    l = (l0.colwise() - c).colwise().normalized(); // dirns of projections\n    for( std::size_t j=0; j < N-1; ++j ){\n        proj.col(j) = ((p0(2) - l0(2,j))/l(2,j))*l.col(j) + l0.col(j);\n    }\n\n    // Insert the projected points in a CGAL vertex_with_info vector\n    std::vector< std::pair< Point, unsigned> > verts;\n    for( std::size_t j=0; j < N-1; ++j ){\n        verts.push_back(std::make_pair(Point(proj(0,j),proj(1,j)),j+1));\n    }\n\n    // Triangulate\n    Delaunay dt( verts.begin(), verts.end() );\n\n    // Iterate over the triangles to calculate volume\n    double_t volume = 0.0;\n    for( auto ffi = dt.finite_faces_begin(); ffi != dt.finite_faces_end();\n            ++ffi){\n        auto i = ffi->vertex(0)->info();\n        auto j = ffi->vertex(2)->info();\n        auto k = ffi->vertex(1)->info();\n        volume += 0.166666667*(Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n    }\n\n    // Iterate over infinite faces\n    Face_circulator fc = dt.incident_faces(dt.infinite_vertex()), done(fc);\n    if (fc != 0) {\n        do{\n            auto i = dt.is_infinite(fc->vertex(0))?0:fc->vertex(0)->info();\n            auto j = dt.is_infinite(fc->vertex(2))?0:fc->vertex(2)->info();\n            auto k = dt.is_infinite(fc->vertex(1))?0:fc->vertex(1)->info();\n            volume += 0.166666667*\n                (Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n        }while(++fc != done);\n    }\n\n    return volume;\n}\n", "meta": {"hexsha": "f0d8a9d76e8f5ca40b6b2a0c9002708dc0d92920", "size": 3407, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "PointCloudVolume.cxx", "max_stars_repo_name": "amit112amit/learn_cython", "max_stars_repo_head_hexsha": "394a0a2698766dad4b4442659d762c19315fbcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PointCloudVolume.cxx", "max_issues_repo_name": "amit112amit/learn_cython", "max_issues_repo_head_hexsha": "394a0a2698766dad4b4442659d762c19315fbcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudVolume.cxx", "max_forks_repo_name": "amit112amit/learn_cython", "max_forks_repo_head_hexsha": "394a0a2698766dad4b4442659d762c19315fbcaf", "max_forks_repo_licenses": ["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.6344086022, "max_line_length": 79, "alphanum_fraction": 0.63604344, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5837343878006694}}
{"text": "\n#include <cmath>\n#include <string>\n#include <stdexcept>\n#include <boost/math/special_functions/bessel.hpp>\n#include \"spida/grid/besselR.h\"\n#include <iostream>\n\nnamespace spida{\n\n\nBesselRootGridR::BesselRootGridR(int nr,double maxr) : GridR(nr,maxr),\n    m_r(nr), m_sr(nr)\n{\n    //OutputIterator cyl_bessel_j_zero(\n    //                 T v,                       // Floating-point value for Jv.\n    //                 int start_index,           // 1-based index of first zero.\n    //                 unsigned number_of_roots,  // How many roots to generate.\n    //                 OutputIterator out_it);\n\n    // Want J0 -> v = 0, starting with first root -> start_index=1\n    boost::math::cyl_bessel_j_zero<double>(0.0,1,nr,std::back_inserter(m_roots));\n    // 1-based index of zero (use nr+1 for m_jN rather than nr)\n    m_jN = boost::math::cyl_bessel_j_zero<double>(0.0,nr+1);\n    // Set physical grid\n    for(auto i = 0; i < nr; i++)\n        m_r[i] = m_roots[i]*GridR::getMaxR()/m_jN;\n    // Set spectral grid\n    for(auto i = 0; i < nr; i++)\n        m_sr[i] = m_roots[i]*getMaxSR()/m_jN;\n}\n\n\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "58a55a5cbd2b8cd416d93e717adcf437ca96a49d", "size": 1107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grid/besselR.cpp", "max_stars_repo_name": "whalenpt/spida", "max_stars_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T10:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T10:22:31.000Z", "max_issues_repo_path": "src/grid/besselR.cpp", "max_issues_repo_name": "whalenpt/spida", "max_issues_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/grid/besselR.cpp", "max_forks_repo_name": "whalenpt/spida", "max_forks_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 81, "alphanum_fraction": 0.5898825655, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5837343799327358}}
{"text": "#pragma once\n#include \"kissfft.hh\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/optional.hpp>\n#include <cstddef>\n\nnamespace vv\n{\n\n\ttemplate <class T, class U>\n\tauto lerp(T x0, T x1, U ratio)\n\t{\n\t\treturn x0 + (x1 - x0) * ratio;\n\t}\n\n\ttemplate <class T>\n\tauto invlerp(T x0, T x1, T x)\n\t{\n\t\treturn (x - x0) / (x1 - x0);\n\t}\n\n\ttemplate <class T>\n\tauto squared(T x)\n\t{\n\t\treturn x * x;\n\t}\n\n\tclass processor\n\t{\n\tpublic:\n\n\t\tstatic const std::size_t buffer_size = 4096;\n\t\tstatic const std::size_t nsdf_size = buffer_size / 2;\n\n\t\texplicit processor(double sampleRate)\n\t\t\t: sampleRate_(sampleRate)\n\t\t\t, v1_(buffer_size)\n\t\t\t, v2_(buffer_size + nsdf_size)\n\t\t\t, v3_(buffer_size + nsdf_size)\n\t\t\t, v4_(buffer_size + nsdf_size)\n\t\t\t, v5_(buffer_size + nsdf_size)\n\t\t\t, v6_(buffer_size)\n\t\t\t, v7_(buffer_size / 2)\n\t\t{\n\t\t}\n\n\t\tvoid operator ()(const float* input, float* output, double pitch_shift, double formant_shift)\n\t\t{\n\t\t\tfor (std::size_t i = 0; i < buffer_size; ++i)\n\t\t\t\tv1_[i] = std::complex<float>(input[i], 0.0f);\n\n\t\t\tfor (std::size_t i = 0; i < buffer_size; ++i)\n\t\t\t{\n\t\t\t\tauto r = static_cast<double>(i) / static_cast<double>(buffer_size);\n\t\t\t\tauto w = 0.5 - 0.5 * std::cos(boost::math::constants::two_pi<double>() * r);\n\t\t\t\tv2_[i] = v1_[i] * static_cast<float>(w);\n\t\t\t}\n\n\t\t\tfft_.transform(v2_.data(), v3_.data());\n\n\t\t\tauto cutoff_hz = 800.0;\n\t\t\tauto cutoff_index = static_cast<std::size_t>(std::round(cutoff_hz * static_cast<double>(buffer_size) / sampleRate_));\n\n\t\t\tfor (std::size_t i = 0; i < cutoff_index; ++i)\n\t\t\t{\n\t\t\t\tv4_[i + 1] = std::norm(v3_[i + 1]);\n\t\t\t\tv4_[buffer_size - i - 1] = std::norm(v3_[buffer_size - i - 1]);\n\t\t\t}\n\n\t\t\tifft_.transform(v4_.data(), v5_.data());\n\n\t\t\tfor (std::size_t i = 0; i < buffer_size + nsdf_size; ++i)\n\t\t\t\tv5_[i] /= static_cast<float>(buffer_size + nsdf_size);\n\n\t\t\tfor (std::size_t i = 1; i < buffer_size; ++i)\n\t\t\t{\n\t\t\t\tauto j = buffer_size - i - 1;\n\t\t\t\tv6_[j] = v6_[j + 1] + squared(v2_[i].real()) + squared(v2_[j].real());\n\t\t\t}\n\n\t\t\tfor (std::size_t i = 0; i < buffer_size / 2; ++i)\n\t\t\t{\n\t\t\t\tif (v6_[i] < std::numeric_limits<double>::min())\n\t\t\t\t\tv7_[i] = 0.0f;\n\t\t\t\telse\n\t\t\t\t\tv7_[i] = 2.0f * v5_[i].real() / v6_[i];\n\t\t\t}\n\n\t\t\tauto minimum_hz = 50.0;\n\t\t\tauto maximum_hz = 300.0;\n\n\t\t\tauto minimum_index = static_cast<std::size_t>(std::round(sampleRate_ / maximum_hz));\n\t\t\tauto maximum_index = static_cast<std::size_t>(std::round(sampleRate_ / minimum_hz));\n\n\t\t\tminimum_index = std::max<std::size_t>(minimum_index, 1);\n\t\t\tminimum_index = std::min<std::size_t>(minimum_index, buffer_size / 2 - 2);\n\n\t\t\tmaximum_index = std::max<std::size_t>(maximum_index, 1);\n\t\t\tmaximum_index = std::min<std::size_t>(maximum_index, buffer_size / 2 - 2);\n\n\t\t\tdouble maximum_value = 0.0;\n\n\t\t\tfor (std::size_t i = minimum_index; i < maximum_index; ++i)\n\t\t\t{\n\t\t\t\tauto p1 = v7_[i - 1];\n\t\t\t\tauto p2 = v7_[i];\n\t\t\t\tauto p3 = v7_[i + 1];\n\n\t\t\t\tif (p1 < p2 && p2 > p3 && p2 > maximum_value)\n\t\t\t\t\tmaximum_value = p2;\n\t\t\t}\n\n\t\t\tboost::optional<std::size_t> peak_index;\n\t\t\tdouble peak_value = 0.0;\n\n\t\t\tfor (std::size_t i = minimum_index; i < maximum_index; ++i)\n\t\t\t{\n\t\t\t\tauto p1 = v7_[i - 1];\n\t\t\t\tauto p2 = v7_[i];\n\t\t\t\tauto p3 = v7_[i + 1];\n\n\t\t\t\tif (p1 < p2 && p2 > p3 && p2 > maximum_value * 0.9)\n\t\t\t\t{\n\t\t\t\t\tpeak_index = i;\n\t\t\t\t\tpeak_value = p2;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!peak_index && last_peak_index_)\n\t\t\t\tpeak_index = last_peak_index_;\n\n\t\t\tlast_peak_index_ = peak_index;\n\n\t\t\tbool enable = false;\n\n\t\t\tif (peak_index)\n\t\t\t{\n\t\t\t\tstd::size_t last_dst = 0;\n\t\t\t\tstd::size_t last_src1 = 0;\n\t\t\t\tstd::size_t last_src2 = 0;\n\t\t\t\tdouble last_src_ratio = 0.0;\n\n\t\t\t\tauto easing = [&](double x)\n\t\t\t\t{\n\t\t\t\t\treturn (1.0 - std::cos(boost::math::constants::pi<double>() * x)) / 2.0;\n\t\t\t\t};\n\n\t\t\t\tauto interpolate = [&](double x1, double x2, double ratio)\n\t\t\t\t{\n\t\t\t\t\treturn lerp(x1, x2, easing(ratio));\n\t\t\t\t};\n\n\t\t\t\tauto get_value = [&](double indexf) -> double\n\t\t\t\t{\n\t\t\t\t\tif (indexf < 0.0)\n\t\t\t\t\t\treturn input[0];\n\n\t\t\t\t\tauto index = static_cast<std::size_t>(std::floor(indexf));\n\t\t\t\t\tif (index >= buffer_size - 1)\n\t\t\t\t\t\treturn input[buffer_size - 1];\n\n\t\t\t\t\tauto ratio = indexf - std::floor(indexf);\n\n\t\t\t\t\treturn interpolate(input[index], input[index + 1], ratio);\n\t\t\t\t};\n\n\t\t\t\tauto overlap = [&](std::size_t dst, std::size_t src1, std::size_t src2, double src_ratio)\n\t\t\t\t{\n\t\t\t\t\tfor (std::size_t i = last_dst; i < dst; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto ratio = static_cast<double>(i - last_dst) / static_cast<double>(dst - last_dst);\n\n\t\t\t\t\t\tauto p1_1 = get_value(static_cast<double>(last_src1) + static_cast<double>(i - last_dst) * formant_shift);\n\t\t\t\t\t\tauto p1_2 = get_value(static_cast<double>(last_src2) + static_cast<double>(i - last_dst) * formant_shift);\n\t\t\t\t\t\tauto p1 = interpolate(p1_1, p1_2, last_src_ratio);\n\n\t\t\t\t\t\tauto p2_1 = get_value(static_cast<double>(src1) - static_cast<double>(dst - i) * formant_shift);\n\t\t\t\t\t\tauto p2_2 = get_value(static_cast<double>(src2) - static_cast<double>(dst - i) * formant_shift);\n\t\t\t\t\t\tauto p2 = interpolate(p2_1, p2_2, src_ratio);\n\n\t\t\t\t\t\toutput[i] = static_cast<float>(interpolate(p1, p2, ratio));\n\t\t\t\t\t}\n\n\t\t\t\t\tlast_dst = dst;\n\t\t\t\t\tlast_src1 = src1;\n\t\t\t\t\tlast_src2 = src2;\n\t\t\t\t\tlast_src_ratio = src_ratio;\n\t\t\t\t};\n\n\t\t\t\tauto q = buffer_size / *peak_index;\n\t\t\t\tauto r = buffer_size % *peak_index;\n\n\t\t\t\tauto nf = (static_cast<double>(buffer_size) * pitch_shift - static_cast<double>(r)) / static_cast<double>(*peak_index);\n\t\t\t\tauto n = static_cast<std::size_t>(std::max(0.0, std::round(nf)));\n\n\t\t\t\tif (q != 0 && n != 0)\n\t\t\t\t{\n\t\t\t\t\tauto actual_pitch_shift = static_cast<double>(n * *peak_index + r) / static_cast<double>(buffer_size);\n\n\t\t\t\t\tfor (std::size_t i = 1; i <= n; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble frame_indexf = 1.0;\n\n\t\t\t\t\t\tif (n != 1)\n\t\t\t\t\t\t\tframe_indexf = static_cast<double>((i - 1) * (q - 1)) / static_cast<double>(n - 1) + 1;\n\n\t\t\t\t\t\tauto frame_index = static_cast<std::size_t>(std::floor(frame_indexf));\n\n\t\t\t\t\t\tauto dst = static_cast<std::size_t>(std::floor(static_cast<double>(i * *peak_index) / actual_pitch_shift));\n\t\t\t\t\t\tauto src = frame_index * *peak_index;\n\n\t\t\t\t\t\tif (frame_index == q)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toverlap(dst, src, src, 0.0);\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\tauto src_ratio = frame_indexf - std::floor(frame_indexf);\n\t\t\t\t\t\t\toverlap(dst, src, src + *peak_index, src_ratio);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\toverlap(buffer_size, buffer_size, buffer_size, 0.0);\n\n\t\t\t\t\tenable = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!enable)\n\t\t\t\tstd::copy(input, input + buffer_size, output);\n\t\t}\n\n\tprivate:\n\n\t\tdouble sampleRate_;\n\n\t\tkissfft<float> fft_{ buffer_size + nsdf_size, false };\n\t\tkissfft<float> ifft_{ buffer_size + nsdf_size, true };\n\n\t\tstd::vector<std::complex<float>> v1_;\n\t\tstd::vector<std::complex<float>> v2_;\n\t\tstd::vector<std::complex<float>> v3_;\n\t\tstd::vector<std::complex<float>> v4_;\n\t\tstd::vector<std::complex<float>> v5_;\n\t\tstd::vector<float> v6_;\n\t\tstd::vector<float> v7_;\n\n\t\tboost::optional<std::size_t> last_peak_index_;\n\n\t};\n\n}\n", "meta": {"hexsha": "c3db6cc05ad1805b7094c9412c731bfde37ff443", "size": 6847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vv/src/processor.hpp", "max_stars_repo_name": "planaria/vv", "max_stars_repo_head_hexsha": "08aebfbe37338fe1735fd3431f1178237941dde1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-10-16T17:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:40:28.000Z", "max_issues_repo_path": "vv/src/processor.hpp", "max_issues_repo_name": "planaria/vv", "max_issues_repo_head_hexsha": "08aebfbe37338fe1735fd3431f1178237941dde1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-17T02:57:04.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-19T05:50:57.000Z", "max_forks_repo_path": "vv/src/processor.hpp", "max_forks_repo_name": "planaria/vv", "max_forks_repo_head_hexsha": "08aebfbe37338fe1735fd3431f1178237941dde1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-19T18:08:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T09:37:45.000Z", "avg_line_length": 26.9566929134, "max_line_length": 123, "alphanum_fraction": 0.6120928874, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5836614057948786}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <random>\n\ntemplate <int NumArguments, typename StepRNG = std::uniform_real_distribution<>,\n          class Generator = std::mt19937>\nclass MetropolisAlgorithm {\n public:\n  using Argument = Eigen::Array<double, NumArguments, 1>;\n  using FunctionType = std::function<double(const Argument&)>;\n  using GeneratorResType = Generator::result_type;\n\n private:\n  FunctionType pdf;\n  StepRNG step;\n  std::uniform_real_distribution<> uniform =\n      std::uniform_real_distribution<>(0, 1);\n  std::mt19937 gen;\n\n  // saving the old probability minimizes the function calls\n  double p_old;\n  std::size_t argument_index = 0;\n\n public:\n  Argument argument;\n\n  MetropolisAlgorithm(FunctionType pdf, Argument& argstart, StepRNG step,\n                      GeneratorResType seed,\n                      std::size_t warm_up = 100 * NumArguments)\n      : pdf(pdf), argument(argstart), step(step) {\n    gen = Generator(seed);  // Standard mersenne_twister_engine seeded with seed\n\n    p_old = pdf(argument);\n\n    for (std::size_t i = 0; i < warm_up; i++) do_step();\n  };\n\n  MetropolisAlgorithm(FunctionType pdf, Argument& argstart, StepRNG step,\n                      std::size_t warm_up = 100 * NumArguments)\n      : pdf(pdf), step(step), argument(argstart) {\n    std::random_device rd;\n    gen = Generator(rd());  // Standard mersenne_twister_engine seeded with seed\n\n    p_old = pdf(argument);\n\n    for (std::size_t i = 0; i < warm_up; i++) do_step();\n  };\n\n  void do_step() {\n    double x_old = argument[argument_index];\n    double x_new = x_old + step(gen);\n\n    argument[argument_index] = x_new;\n    double p_new = pdf(argument);\n    double p = p_new / p_old;\n\n    if (p < 1) {\n      double s = uniform(gen);\n\n      // reject new values\n      if (s > p) {\n        x_new = x_old;\n        p_new = p_old;\n      }\n    }\n\n    argument[argument_index] = x_new;\n    p_old = p_new;\n\n    argument_index++;\n    if (argument_index >= NumArguments) {\n      argument_index = 0;\n    }\n  }\n\n  Argument& next() {\n    do_step();\n    return argument;\n  }\n\n  /**\n   * @brief Calculates the expectation value and the standard deviation of the\n   * given funtion (under the pdf)\n   *\n   * Using the Welfords online algorithm to calculate the mean and standard\n   * deviation.\n   *\n   * @param function function to average\n   * @param samples number of samples to collect\n   * @return std::tuple<double, double, double> Mean, std of mean, variance\n   */\n  std::tuple<double, double, double> average(\n      std::function<double(const Argument&)> function, std::size_t samples) {\n    std::size_t n;\n    double mean = 0;\n    // double mean2 = 0;\n    double S = 0;\n\n    for (n = 1; n <= samples; n++) {\n      do_step();\n      double x = function(argument);\n      double old_mean = mean;\n      mean += (x - mean) / double(n);\n      // mean2 += (x * x - mean2) / double(n);\n      S += (x - mean) * (x - old_mean);\n    }\n\n    // return {mean, std::sqrt(mean2 - mean * mean)};\n    return {mean, std::sqrt(S / (samples - 1) / samples), S / (samples - 1)};\n  }\n\n  Eigen::Array<double, Eigen::Dynamic, NumArguments> get_sample(\n      Eigen::Index N) {\n    using namespace Eigen;\n    typedef Array<double, Eigen::Dynamic, NumArguments> ReturnType;\n\n    ReturnType returner(N, NumArguments);\n\n    for (Index i = 0; i < N; i++) {\n      do_step();\n      returner.row(i) = argument;\n    }\n\n    return returner;\n  }\n};", "meta": {"hexsha": "7bd76ab71586d082b1c781ab00b36d0aae809929", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Project03-QuantumMC/Metropolis.hpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project03-QuantumMC/Metropolis.hpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project03-QuantumMC/Metropolis.hpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8503937008, "max_line_length": 80, "alphanum_fraction": 0.62228739, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5835212982347717}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_SIGNEDSVD_HPP\n#define MCL_SIGNEDSVD_HPP 1\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nnamespace mcl\n{\n\ntemplate <typename T, int DIM>\nstatic inline void signed_svd(\n\tconst Eigen::Matrix<T,DIM,DIM> &F,\n\tEigen::Matrix<T,DIM,1> &S,\n\tEigen::Matrix<T,DIM,DIM> &U,\n\tEigen::Matrix<T,DIM,DIM> &V)\n{\n\tusing namespace Eigen;\n\tint dim = DIM == Eigen::Dynamic ? F.rows() : DIM;\n\ttypedef Matrix<T,DIM,DIM> MatX;\n\n\tJacobiSVD<MatX> svd(F, ComputeFullU | ComputeFullV);\n\tS = svd.singularValues();\n\tU = svd.matrixU();\n\tV = svd.matrixV();\n\n\tMatX J = MatX::Identity(dim,dim);\n\tJ(dim-1,dim-1) = -1.0;\n\n\tif (U.determinant() < 0.0)\n\t{\n\t\tU = U * J;\n\t\tS[dim-1] *= -1.0;\n\t}\n\n\tif (V.determinant() < 0.0)\n\t{\n\t\tV = (J * V.transpose()).transpose();\n\t\tS[dim-1] *= -1.0;\n\t}\n\n\t// Degenerate case\n\tif (!S.allFinite())\n\t{\n\t\tS.setZero();\n\t\tU.setIdentity();\n\t\tV.setIdentity();\n\t}\n\n} // end signed svd\n\n} // end mcl\n\n#endif\n", "meta": {"hexsha": "f49ad93637ab453f7dd1b481633d18c04e39e920", "size": 971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/SignedSVD.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/SignedSVD.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/SignedSVD.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": 17.0350877193, "max_line_length": 53, "alphanum_fraction": 0.6271884655, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5834959275926903}}
{"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: Liang Zhao and Timo Heister, Clemson University, 2016 \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#include <deal.II/base/tensor.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/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.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\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_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/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// 为了在网格之间传输解决方案，包括这个文件。\n\n#include <deal.II/numerics/solution_transfer.h> \n\n// 这个文件包括UMFPACK：直接求解器。\n\n#include <deal.II/lac/sparse_direct.h> \n\n// 还有一个ILU预处理程序。\n\n#include <deal.II/lac/sparse_ilu.h> \n\n#include <fstream> \n#include <iostream> \n\nnamespace Step57 \n{ \n  using namespace dealii; \n// @sect3{The <code>NavierStokesProblem</code> class template}  \n\n// 该类管理介绍中描述的矩阵和向量：特别是，我们为当前的解决方案、当前的牛顿更新和直线搜索更新存储了一个BlockVector。 我们还存储了两个AffineConstraints对象：一个是强制执行Dirichlet边界条件的对象，另一个是将所有边界值设为0的对象。第一个约束解向量，第二个约束更新（也就是说，我们从不更新边界值，所以我们强制相关的更新向量值为零）。\n\n  template <int dim> \n  class StationaryNavierStokes \n  { \n  public: \n    StationaryNavierStokes(const unsigned int degree); \n    void run(const unsigned int refinement); \n\n  private: \n    void setup_dofs(); \n\n    void initialize_system(); \n\n    void assemble(const bool initial_step, const bool assemble_matrix); \n\n    void assemble_system(const bool initial_step); \n\n    void assemble_rhs(const bool initial_step); \n\n    void solve(const bool initial_step); \n\n    void refine_mesh(); \n\n    void process_solution(unsigned int refinement); \n\n    void output_results(const unsigned int refinement_cycle) const; \n\n    void newton_iteration(const double       tolerance, \n                          const unsigned int max_n_line_searches, \n                          const unsigned int max_n_refinements, \n                          const bool         is_initial_step, \n                          const bool         output_result); \n\n    void compute_initial_guess(double step_size); \n\n    double                               viscosity; \n    double                               gamma; \n    const unsigned int                   degree; \n    std::vector<types::global_dof_index> dofs_per_block; \n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> zero_constraints; \n    AffineConstraints<double> nonzero_constraints; \n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n    SparseMatrix<double>      pressure_mass_matrix; \n\n    BlockVector<double> present_solution; \n    BlockVector<double> newton_update; \n    BlockVector<double> system_rhs; \n    BlockVector<double> evaluation_point; \n  }; \n// @sect3{Boundary values and right hand side}  \n\n// 在这个问题中，我们设定沿空腔上表面的速度为1，其他三面墙的速度为0。右边的函数为零，所以我们在本教程中不需要设置右边的函数。边界函数的分量数为  <code>dim+1</code>  。我们最终将使用 VectorTools::interpolate_boundary_values 来设置边界值，这就要求边界值函数的分量数与解相同，即使没有全部使用。换个说法：为了让这个函数高兴，我们为压力定义了边界值，尽管我们实际上永远不会用到它们。\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() \n      : Function<dim>(dim + 1) \n    {} \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component) 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    Assert(component < this->n_components, \n           ExcIndexRange(component, 0, this->n_components)); \n    if (component == 0 && std::abs(p[dim - 1] - 1.0) < 1e-10) \n      return 1.0; \n\n    return 0; \n  } \n// @sect3{BlockSchurPreconditioner for Navier Stokes equations}  \n\n// 正如介绍中所讨论的，Krylov迭代方法中的预处理器是作为一个矩阵-向量乘积算子实现的。在实践中，舒尔补码预处理器被分解为三个矩阵的乘积（如第一节所述）。第一个因素中的 $\\tilde{A}^{-1}$ 涉及到对线性系统 $\\tilde{A}x=b$ 的求解。在这里，为了简单起见，我们通过一个直接求解器来解决这个系统。第二个因素中涉及的计算是一个简单的矩阵-向量乘法。舒尔补码 $\\tilde{S}$ 可以被压力质量矩阵很好地近似，其逆值可以通过不精确求解器得到。因为压力质量矩阵是对称和正定的，我们可以用CG来解决相应的线性系统。\n\n  template <class PreconditionerMp> \n  class BlockSchurPreconditioner : public Subscriptor \n  { \n  public: \n    BlockSchurPreconditioner(double                           gamma, \n                             double                           viscosity, \n                             const BlockSparseMatrix<double> &S, \n                             const SparseMatrix<double> &     P, \n                             const PreconditionerMp &         Mppreconditioner); \n\n    void vmult(BlockVector<double> &dst, const BlockVector<double> &src) const; \n\n  private: \n    const double                     gamma; \n    const double                     viscosity; \n    const BlockSparseMatrix<double> &stokes_matrix; \n    const SparseMatrix<double> &     pressure_mass_matrix; \n    const PreconditionerMp &         mp_preconditioner; \n    SparseDirectUMFPACK              A_inverse; \n  }; \n\n// 我们可以注意到，左上角的矩阵逆的初始化是在构造函数中完成的。如果是这样，那么预处理程序的每一次应用就不再需要计算矩阵因子了。\n\n  template <class PreconditionerMp> \n  BlockSchurPreconditioner<PreconditionerMp>::BlockSchurPreconditioner( \n    double                           gamma, \n    double                           viscosity, \n    const BlockSparseMatrix<double> &S, \n    const SparseMatrix<double> &     P, \n    const PreconditionerMp &         Mppreconditioner) \n    : gamma(gamma) \n    , viscosity(viscosity) \n    , stokes_matrix(S) \n    , pressure_mass_matrix(P) \n    , mp_preconditioner(Mppreconditioner) \n  { \n    A_inverse.initialize(stokes_matrix.block(0, 0)); \n  } \n\n  template <class PreconditionerMp> \n  void BlockSchurPreconditioner<PreconditionerMp>::vmult( \n    BlockVector<double> &      dst, \n    const BlockVector<double> &src) const \n  { \n    Vector<double> utmp(src.block(0)); \n\n    { \n      SolverControl solver_control(1000, 1e-6 * src.block(1).l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n\n      dst.block(1) = 0.0; \n      cg.solve(pressure_mass_matrix, \n               dst.block(1), \n               src.block(1), \n               mp_preconditioner); \n      dst.block(1) *= -(viscosity + gamma); \n    } \n\n    { \n      stokes_matrix.block(0, 1).vmult(utmp, dst.block(1)); \n      utmp *= -1.0; \n      utmp += src.block(0); \n    } \n\n    A_inverse.vmult(dst.block(0), utmp); \n  } \n// @sect3{StationaryNavierStokes class implementation}  \n// @sect4{StationaryNavierStokes::StationaryNavierStokes}  \n\n// 该类的构造函数看起来与  step-22  中的构造函数非常相似。唯一的区别是粘度和增强的拉格朗日系数  <code>gamma</code>  。\n\n  template <int dim> \n  StationaryNavierStokes<dim>::StationaryNavierStokes(const unsigned int degree) \n    : viscosity(1.0 / 7500.0) \n    , gamma(1.0) \n    , degree(degree) \n    , triangulation(Triangulation<dim>::maximum_smoothing) \n    , fe(FE_Q<dim>(degree + 1), dim, FE_Q<dim>(degree), 1) \n    , dof_handler(triangulation) \n  {} \n// @sect4{StationaryNavierStokes::setup_dofs}  \n\n// 这个函数初始化DoFHandler，列举当前网格上的自由度和约束。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::setup_dofs() \n  { \n    system_matrix.clear(); \n    pressure_mass_matrix.clear(); \n\n// 第一步是将DoFs与给定的网格联系起来。\n\n    dof_handler.distribute_dofs(fe); \n\n// 我们对组件重新编号，使所有的速度DoF在压力DoF之前，以便能够将解向量分成两个块，在块预处理程序中分别访问。\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    dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, block_component); \n    unsigned int dof_u = dofs_per_block[0]; \n    unsigned int dof_p = dofs_per_block[1]; \n\n// 在牛顿方案中，我们首先将边界条件应用于从初始步骤得到的解。为了确保边界条件在牛顿迭代过程中保持满足，在更新时使用零边界条件  $\\delta u^k$  。因此我们设置了两个不同的约束对象。\n\n    FEValuesExtractors::Vector velocities(0); \n    { \n      nonzero_constraints.clear(); \n\n      DoFTools::make_hanging_node_constraints(dof_handler, nonzero_constraints); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               BoundaryValues<dim>(), \n                                               nonzero_constraints, \n                                               fe.component_mask(velocities)); \n    } \n    nonzero_constraints.close(); \n\n    { \n      zero_constraints.clear(); \n\n      DoFTools::make_hanging_node_constraints(dof_handler, zero_constraints); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               Functions::ZeroFunction<dim>( \n                                                 dim + 1), \n                                               zero_constraints, \n                                               fe.component_mask(velocities)); \n    } \n    zero_constraints.close(); \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              << \" (\" << dof_u << \" + \" << dof_p << ')' << std::endl; \n  } \n// @sect4{StationaryNavierStokes::initialize_system}  \n\n// 在每个网格上，SparsityPattern和线性系统的大小是不同的。这个函数在网格细化后初始化它们。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::initialize_system() \n  { \n    { \n      BlockDynamicSparsityPattern dsp(dofs_per_block, dofs_per_block); \n      DoFTools::make_sparsity_pattern(dof_handler, dsp, nonzero_constraints); \n      sparsity_pattern.copy_from(dsp); \n    } \n\n    system_matrix.reinit(sparsity_pattern); \n\n    present_solution.reinit(dofs_per_block); \n    newton_update.reinit(dofs_per_block); \n    system_rhs.reinit(dofs_per_block); \n  } \n// @sect4{StationaryNavierStokes::assemble}  \n\n// 这个函数建立了我们目前工作的系统矩阵和右手边。 @p initial_step 参数用于确定我们应用哪一组约束（初始步骤为非零，其他为零）。 @p assemble_matrix 参数分别决定了是组装整个系统还是只组装右手边的向量。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::assemble(const bool initial_step, \n                                             const bool assemble_matrix) \n  { \n    if (assemble_matrix) \n      system_matrix = 0; \n\n    system_rhs = 0; \n\n    QGauss<dim> quadrature_formula(degree + 2); \n\n    FEValues<dim> fe_values(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    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \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    std::vector<Tensor<1, dim>> present_velocity_values(n_q_points); \n    std::vector<Tensor<2, dim>> present_velocity_gradients(n_q_points); \n    std::vector<double>         present_pressure_values(n_q_points); \n\n    std::vector<double>         div_phi_u(dofs_per_cell); \n    std::vector<Tensor<1, dim>> phi_u(dofs_per_cell); \n    std::vector<Tensor<2, dim>> grad_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      { \n        fe_values.reinit(cell); \n\n        local_matrix = 0; \n        local_rhs    = 0; \n\n        fe_values[velocities].get_function_values(evaluation_point, \n                                                  present_velocity_values); \n\n        fe_values[velocities].get_function_gradients( \n          evaluation_point, present_velocity_gradients); \n\n        fe_values[pressure].get_function_values(evaluation_point, \n                                                present_pressure_values); \n\n//装配类似于  step-22  。一个以gamma为系数的附加项是增强拉格朗日（AL），它是通过grad-div稳定化组装的。 正如我们在介绍中所讨论的，系统矩阵的右下块应该为零。由于压力质量矩阵是在创建预处理程序时使用的，所以我们在这里组装它，然后在最后把它移到一个单独的SparseMatrix中（与 step-22 相同）。\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                div_phi_u[k]  = fe_values[velocities].divergence(k, q); \n                grad_phi_u[k] = fe_values[velocities].gradient(k, q); \n                phi_u[k]      = fe_values[velocities].value(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                if (assemble_matrix) \n                  { \n                    for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                      { \n                        local_matrix(i, j) += \n                          (viscosity * \n                             scalar_product(grad_phi_u[j], grad_phi_u[i]) + \n                           present_velocity_gradients[q] * phi_u[j] * phi_u[i] + \n                           grad_phi_u[j] * present_velocity_values[q] * \n                             phi_u[i] - \n                           div_phi_u[i] * phi_p[j] - phi_p[i] * div_phi_u[j] + \n                           gamma * div_phi_u[j] * div_phi_u[i] + \n                           phi_p[i] * phi_p[j]) * \n                          fe_values.JxW(q); \n                      } \n                  } \n\n                double present_velocity_divergence = \n                  trace(present_velocity_gradients[q]); \n                local_rhs(i) += \n                  (-viscosity * scalar_product(present_velocity_gradients[q], \n                                               grad_phi_u[i]) - \n                   present_velocity_gradients[q] * present_velocity_values[q] * \n                     phi_u[i] + \n                   present_pressure_values[q] * div_phi_u[i] + \n                   present_velocity_divergence * phi_p[i] - \n                   gamma * present_velocity_divergence * div_phi_u[i]) * \n                  fe_values.JxW(q); \n              } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n\n        const AffineConstraints<double> &constraints_used = \n          initial_step ? nonzero_constraints : zero_constraints; \n\n        if (assemble_matrix) \n          { \n            constraints_used.distribute_local_to_global(local_matrix, \n                                                        local_rhs, \n                                                        local_dof_indices, \n                                                        system_matrix, \n                                                        system_rhs); \n          } \n        else \n          { \n            constraints_used.distribute_local_to_global(local_rhs, \n                                                        local_dof_indices, \n                                                        system_rhs); \n          } \n      } \n\n    if (assemble_matrix) \n      { \n\n// 最后我们把压力质量矩阵移到一个单独的矩阵中。\n\n        pressure_mass_matrix.reinit(sparsity_pattern.block(1, 1)); \n        pressure_mass_matrix.copy_from(system_matrix.block(1, 1)); \n\n// 注意，将这个压力块设置为零并不等同于不在这个块中装配任何东西，因为这里的操作将（错误地）删除从压力作用力的悬挂节点约束中进来的对角线条目。这意味着，我们的整个系统矩阵将有完全为零的行。幸运的是，FGMRES处理这些行没有任何问题。\n\n        system_matrix.block(1, 1) = 0; \n      } \n  } \n\n  template <int dim> \n  void StationaryNavierStokes<dim>::assemble_system(const bool initial_step) \n  { \n    assemble(initial_step, true); \n  } \n\n  template <int dim> \n  void StationaryNavierStokes<dim>::assemble_rhs(const bool initial_step) \n  { \n    assemble(initial_step, false); \n  } \n// @sect4{StationaryNavierStokes::solve}  \n\n// 在这个函数中，我们使用FGMRES和程序开始时定义的块状预处理程序来解决线性系统。我们在这一步得到的是解向量。如果这是初始步骤，解向量为我们提供了纳维尔-斯托克斯方程的初始猜测。对于初始步骤，非零约束被应用，以确保边界条件得到满足。在下面的步骤中，我们将求解牛顿更新，所以使用零约束。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::solve(const bool initial_step) \n  { \n    const AffineConstraints<double> &constraints_used = \n      initial_step ? nonzero_constraints : zero_constraints; \n\n    SolverControl solver_control(system_matrix.m(), \n                                 1e-4 * system_rhs.l2_norm(), \n                                 true); \n\n    SolverFGMRES<BlockVector<double>> gmres(solver_control); \n    SparseILU<double>                 pmass_preconditioner; \n    pmass_preconditioner.initialize(pressure_mass_matrix, \n                                    SparseILU<double>::AdditionalData()); \n\n    const BlockSchurPreconditioner<SparseILU<double>> preconditioner( \n      gamma, \n      viscosity, \n      system_matrix, \n      pressure_mass_matrix, \n      pmass_preconditioner); \n\n    gmres.solve(system_matrix, newton_update, system_rhs, preconditioner); \n    std::cout << \"FGMRES steps: \" << solver_control.last_step() << std::endl; \n\n    constraints_used.distribute(newton_update); \n  } \n// @sect4{StationaryNavierStokes::refine_mesh}  \n\n// 在粗略的网格上找到一个好的初始猜测后，我们希望通过细化网格来减少误差。这里我们做了类似于 step-15 的自适应细化，只是我们只使用了速度上的Kelly估计器。我们还需要使用SolutionTransfer类将当前的解转移到下一个网格。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n    FEValuesExtractors::Vector velocity(0); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      present_solution, \n      estimated_error_per_cell, \n      fe.component_mask(velocity)); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.0); \n\n    triangulation.prepare_coarsening_and_refinement(); \n    SolutionTransfer<dim, BlockVector<double>> solution_transfer(dof_handler); \n    solution_transfer.prepare_for_coarsening_and_refinement(present_solution); \n    triangulation.execute_coarsening_and_refinement(); \n\n// 首先，DoFHandler被设置，约束被生成。然后我们创建一个临时的BlockVector  <code>tmp</code>  ，其大小与新网格上的解决方案一致。\n\n    setup_dofs(); \n\n    BlockVector<double> tmp(dofs_per_block); \n\n// 将解决方案从粗网格转移到细网格，并对新转移的解决方案应用边界值约束。注意，present_solution仍然是对应于旧网格的一个向量。\n\n    solution_transfer.interpolate(present_solution, tmp); \n    nonzero_constraints.distribute(tmp); \n\n// 最后设置矩阵和向量，并将present_solution设置为插值后的数据。\n\n    initialize_system(); \n    present_solution = tmp; \n  } \n// @sect4{StationaryNavierStokes<dim>::newton_iteration}  \n\n// 这个函数实现了牛顿迭代，给定了公差、最大迭代次数和要做的网格细化次数。\n\n// 参数 <code>is_initial_step</code> 告诉我们是否需要 <code>setup_system</code> ，以及应该装配哪一部分，系统矩阵或右手边的矢量。如果我们做直线搜索，在最后一次迭代中检查残差准则时，右手边已经被组装起来了。因此，我们只需要在当前迭代中装配系统矩阵。最后一个参数 <code>output_result</code> 决定了是否应该产生图形输出。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::newton_iteration( \n    const double       tolerance, \n    const unsigned int max_n_line_searches, \n    const unsigned int max_n_refinements, \n    const bool         is_initial_step, \n    const bool         output_result) \n  { \n    bool first_step = is_initial_step; \n\n    for (unsigned int refinement_n = 0; refinement_n < max_n_refinements + 1; \n         ++refinement_n) \n      { \n        unsigned int line_search_n = 0; \n        double       last_res      = 1.0; \n        double       current_res   = 1.0; \n        std::cout << \"grid refinements: \" << refinement_n << std::endl \n                  << \"viscosity: \" << viscosity << std::endl; \n\n        while ((first_step || (current_res > tolerance)) && \n               line_search_n < max_n_line_searches) \n          { \n            if (first_step) \n              { \n                setup_dofs(); \n                initialize_system(); \n                evaluation_point = present_solution; \n                assemble_system(first_step); \n                solve(first_step); \n                present_solution = newton_update; \n                nonzero_constraints.distribute(present_solution); \n                first_step       = false; \n                evaluation_point = present_solution; \n                assemble_rhs(first_step); \n                current_res = system_rhs.l2_norm(); \n \n \n \n \n \n \n                evaluation_point = present_solution; \n                assemble_system(first_step); \n                solve(first_step); \n\n// 为了确保我们的解决方案越来越接近精确的解决方案，我们让解决方案用权重 <code>alpha</code> 更新，使新的残差小于上一步的残差，这是在下面的循环中完成。这与  step-15  中使用的线搜索算法相同。\n\n                for (double alpha = 1.0; alpha > 1e-5; alpha *= 0.5) \n                  { \n                    evaluation_point = present_solution; \n                    evaluation_point.add(alpha, newton_update); \n                    nonzero_constraints.distribute(evaluation_point); \n                    assemble_rhs(first_step); \n                    current_res = system_rhs.l2_norm(); \n                    std::cout << \"  alpha: \" << std::setw(10) << alpha \n                              << std::setw(0) << \"  residual: \" << current_res \n                              << std::endl; \n                    if (current_res < last_res) \n                      break; \n                  } \n                { \n                  present_solution = evaluation_point; \n                  std::cout << \"  number of line searches: \" << line_search_n \n                            << \"  residual: \" << current_res << std::endl; \n                  last_res = current_res; \n                } \n                ++line_search_n; \n              } \n\n            if (output_result) \n              { \n                output_results(max_n_line_searches * refinement_n + \n                               line_search_n); \n\n                if (current_res <= tolerance) \n                  process_solution(refinement_n); \n              } \n          } \n\n        if (refinement_n < max_n_refinements) \n          { \n            refine_mesh(); \n          } \n      } \n  } \n// @sect4{StationaryNavierStokes::compute_initial_guess}  \n\n// 这个函数将通过使用延续法为我们提供一个初始猜测，正如我们在介绍中讨论的那样。雷诺数被逐级增加 step- ，直到我们达到目标值。通过实验，斯托克斯的解足以成为雷诺数为1000的NSE的初始猜测，所以我们从这里开始。 为了确保前一个问题的解决方案与下一个问题足够接近，步长必须足够小。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::compute_initial_guess(double step_size) \n  { \n    const double target_Re = 1.0 / viscosity; \n\n    bool is_initial_step = true; \n\n    for (double Re = 1000.0; Re < target_Re; \n         Re        = std::min(Re + step_size, target_Re)) \n      { \n        viscosity = 1.0 / Re; \n        std::cout << \"Searching for initial guess with Re = \" << Re \n                  << std::endl; \n        newton_iteration(1e-12, 50, 0, is_initial_step, false); \n        is_initial_step = false; \n      } \n  } \n// @sect4{StationaryNavierStokes::output_results}  \n\n// 这个函数与 step-22 中的函数相同，只是我们为输出文件选择了一个同时包含雷诺数（即当前环境下的粘度的倒数）的名称。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::output_results( \n    const unsigned int output_index) 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    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(present_solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.build_patches(); \n\n    std::ofstream output(std::to_string(1.0 / viscosity) + \"-solution-\" + \n                         Utilities::int_to_string(output_index, 4) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{StationaryNavierStokes::process_solution}  \n\n// 在我们的测试案例中，我们不知道分析解。该函数输出沿 $x=0.5$ 和 $0 \\leq y \\leq 1$ 的速度分量，以便与文献中的数据进行比较。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::process_solution(unsigned int refinement) \n  { \n    std::ofstream f(std::to_string(1.0 / viscosity) + \"-line-\" + \n                    std::to_string(refinement) + \".txt\"); \n    f << \"# y u_x u_y\" << std::endl; \n\n    Point<dim> p; \n    p(0) = 0.5; \n    p(1) = 0.5; \n\n    f << std::scientific; \n\n    for (unsigned int i = 0; i <= 100; ++i) \n      { \n        p(dim - 1) = i / 100.0; \n\n        Vector<double> tmp_vector(dim + 1); \n        VectorTools::point_value(dof_handler, present_solution, p, tmp_vector); \n        f << p(dim - 1); \n\n        for (int j = 0; j < dim; j++) \n          f << \" \" << tmp_vector(j); \n        f << std::endl; \n      } \n  } \n// @sect4{StationaryNavierStokes::run}  \n\n// 这是本程序的最后一步。在这一部分，我们分别生成网格和运行其他函数。最大细化度可以通过参数来设置。\n\n  template <int dim> \n  void StationaryNavierStokes<dim>::run(const unsigned int refinement) \n  { \n    GridGenerator::hyper_cube(triangulation); \n    triangulation.refine_global(5); \n\n    const double Re = 1.0 / viscosity; \n\n// 如果粘度小于 $1/1000$ ，我们必须首先通过延续法搜索初始猜测。我们应该注意的是，搜索总是在初始网格上进行的，也就是这个程序中的 $8 \\times 8$ 网格。之后，我们只需做与粘度大于 $1/1000$ 时相同的工作：运行牛顿迭代，细化网格，转移解决方案，并重复。\n\n    if (Re > 1000.0) \n      { \n        std::cout << \"Searching for initial guess ...\" << std::endl; \n        const double step_size = 2000.0; \n        compute_initial_guess(step_size); \n        std::cout << \"Found initial guess.\" << std::endl; \n        std::cout << \"Computing solution with target Re = \" << Re << std::endl; \n        viscosity = 1.0 / Re; \n        newton_iteration(1e-12, 50, refinement, false, true); \n      } \n    else \n      { \n\n// 当粘度大于1/1000时，斯托克斯方程的解作为初始猜测已经足够好。如果是这样，我们就不需要用延续法来搜索初始猜测了。牛顿迭代可以直接开始。\n\n        newton_iteration(1e-12, 50, refinement, true, true); \n      } \n  } \n} // namespace Step57 \n\nint main() \n{ \n  try \n    { \n      using namespace Step57; \n\n      StationaryNavierStokes<2> flow(/* degree = */ \n\n1); \n      flow.run(4); \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 \n \n \n \n \n \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": "4f47d091b45dd567f911a206d8f13a16275de3c1", "size": 27751, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-57/step-57.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-57/step-57.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-57/step-57.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.1723700887, "max_line_length": 270, "alphanum_fraction": 0.591762459, "num_tokens": 8516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5834807996541916}}
{"text": "/**\n * @file    sfm.hpp\n * @brief   This provides the implementation of structure-from-motion algorithm\n * @author  Shubham Shrivastava\n */\n\n#ifndef SFM_H_\n#define SFM_H_\n\n#include <Eigen/Dense>\n#include \"tapl/common/common.hpp\"\n#include \"tapl/optim/gaussNewton.hpp\"\n#include \"tapl/viz/visualization.hpp\"\n\nnamespace tapl {\n    namespace cve {\n\n        /**< Structure-from-Motion Pipeline */\n        class StructureFromMotion {\n        private:\n            // vector of images\n            std::vector<cv::Mat> images;\n            // camera intrinsic matrix\n            cv::Mat K = cv::Mat::eye(3, 3, CV_32FC1);\n            // camera distortion matrix\n            cv::Mat dist_coeff = cv::Mat::zeros(4, 1, CV_32FC1);\n            // min and max XYZ\n            std::vector<float> minXYZ;\n            std::vector<float> maxXYZ;\n            // verbose\n            bool verbose;\n            // triangulated 3D points in each image local coordinate systems\n            std::vector<std::vector<tapl::Point3d>> points3d_local;\n            // triangulated 3D points in the origin's (first image) coordinate systems\n            std::vector<tapl::Point3d> points3d_global;\n            // bundle size\n            uint16_t bundle_size=2;\n            // Gauss-Newton Optimizer\n            tapl::optim::GaussNewtonOptimizer gnOptim;\n\n            /**\n             * @brief Linear estimate of the 3d point\n             * \n             * @param[in] point2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMatrices projection matrices of 'n' cameras\n             *\n             * @return estimated 3d point\n             */\n            tapl::Point3d linearEstimate3dPt( const std::vector<tapl::Point2d> &point2d,                                         \n                                              const std::vector<Eigen::MatrixXd> &projectionMatrices );\n\n            /**\n             * @brief Non-linear estimate of the 3d point\n             *\n             * @param[in] point2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMatrices projection matrices of 'n' cameras\n             * @param[out] reprojectionErrors pair of pre-optimization and post-optimization \n             *                                  reprojection errors\n             * @param[in] nIterations maximum number of iterations for non-linear optimization\n             * @param[in] reprErrorThresh reprojection error threshold for non-linear optimization\n             *\n             * @return estimated 3d point\n             */\n            tapl::Point3d nonLinearEstimate3dPt( const std::vector<tapl::Point2d> &point2d,                                         \n                                                 const std::vector<Eigen::MatrixXd> &projectionMatrices,\n                                                 std::pair<std::vector<float>,std::vector<float>> &reprojectionErrors,\n                                                 const uint16_t nIterations=1000,\n                                                 const float reprErrorThresh=2.0 );\n\n            /**\n             * @brief Estimate R, T, and triengulated points\n             *\n             * @param[in] E essential matrix relating the first and the second camera\n             * @param[in] points2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMat1 projection matrices of the first camera\n             * @param[in] maxXYZ maximum values of x, y, and z to be considered\n             * @param[in] maxReprojectionErr maximum absolute reprojection error in pixel\n             *\n             * @return pair of RT and triangulated points\n             */\n             std::pair<Eigen::MatrixXd, std::vector<tapl::Point3d>> computeSFM( \n                                        const Eigen::MatrixXd &E, \n                                        const std::vector<std::vector<tapl::Point2d>> &points2d, \n                                        const Eigen::MatrixXd &projectionMat1,\n                                        const float &maxReprojectionErr=50.0 ) ;\n\n        public:\n            /** \n            * @brief This function initializes the structure-from-motion module\n            *\n            * @param[in] imgs images from which structure-from-motion is to be computed\n            * @param[in] K camera intrinsic matrix\n            */\n            StructureFromMotion( const std::vector<cv::Mat> &images, \n                                 const cv::Mat &K,\n                                 const std::vector<float> &minXYZ={0.0, 0.0, 0.0},\n                                 const std::vector<float> &maxXYZ={30.0, 30.0, 30.0},\n                                 const bool verbose=true );\n\n            /** \n            * @brief This function performs structure-from-motion given a set of camera frames\n            *\n            * @param[out] points point-cloud corresponding to keypoints in the first camera's coordinate frame\n            * @param[out] poses poses of each camera frame\n            * @param[out] framePairs camera pairs with associated info such as triangulated points\n            * \n            * @return tapl::SUCCESS if success\n            * @return tapl::FAILURE if failure \n            */\n            tapl::ResultCode process( std::vector<tapl::Point3dColor> &points,\n                                      std::vector<tapl::Pose6dof> &poses,\n                                      std::vector<tapl::CameraPairs> &framePairs);\n        \n        };\n    } \n} \n\n#endif /* SFM_H_ */", "meta": {"hexsha": "a358cff1eb6fd8ac440b1b53f38e17e88cd4a1ea", "size": 5521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tapl/cve/sfm.hpp", "max_stars_repo_name": "towardsautonomy/TAPL", "max_stars_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T12:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T12:53:17.000Z", "max_issues_repo_path": "tapl/cve/sfm.hpp", "max_issues_repo_name": "towardsautonomy/TAPL", "max_issues_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tapl/cve/sfm.hpp", "max_forks_repo_name": "towardsautonomy/TAPL", "max_forks_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7881355932, "max_line_length": 132, "alphanum_fraction": 0.5232747691, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5834494755614175}}
{"text": "#include <Eigen/Dense>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkDelaunay2D.h>\n#include <vtkDoubleArray.h>\n#include <vtkSmartPointer.h>\n#include <vtkIdFilter.h>\n#include <vtkPointData.h>\n\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> Map3Xd;\n\nint main(){\n    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 10000; ++i){\n        vtkNew<vtkPolyDataReader> reader;\n        reader->SetFileName(\"T7.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            proj(j,2) = 0.0;\n        }\n        // Calculate the 2d delaunay triangulations\n        vtkNew<vtkDoubleArray> pts2dArr;\n        pts2dArr->SetVoidArray((void*)proj.data(), 3*(N-1), 1);\n        pts2dArr->SetNumberOfComponents(3);\n        vtkNew<vtkPoints> pts2d;\n        pts2d->SetData(pts2dArr);\n        vtkNew<vtkPolyData> poly2d;\n        poly2d->SetPoints(pts2d);\n        vtkNew<vtkIdFilter> idf;\n        idf->PointIdsOn();\n        idf->SetIdsArrayName(\"OrigIds\");\n        idf->SetInputData(poly2d);\n        vtkNew<vtkDelaunay2D> d2d;\n        d2d->SetInputConnection(idf->GetOutputPort());\n        d2d->Update();\n\n        // Write the triangulation to file\n        vtkNew<vtkCellArray> final;\n        auto stereoTris = d2d->GetOutput()->GetPolys();\n        auto idArr = d2d->GetOutput()->GetPointData()->GetArray(\"OrigIds\");\n        vtkNew<vtkIdList> idL;\n        stereoTris->InitTraversal();\n        while( stereoTris->GetNextCell(idL) ){\n            final->InsertNextCell(3);\n            for(auto j=0; j < idL->GetNumberOfIds(); ++j)\n                final->InsertCellPoint( int(\n                                        idArr->GetTuple1(idL->GetId(j))) );\n        }\n\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": "fe679138e382bf0f7520d261130a0be554b1e07d", "size": 3437, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/vtkStereo.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/vtkStereo.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/vtkStereo.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": 34.7171717172, "max_line_length": 81, "alphanum_fraction": 0.5708466686, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5833616098237648}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string> // for string class\n#include <math.h>\n#include <iostream>\n#include <cmath>\n#include <array>\n#include <complex>\n#include<time.h>\n#include \"mex.h\"\n\n//#define EIGEN_USE_MKL_ALL\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <Eigen/LU>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include<unsupported/Eigen/SparseExtra>\n\nusing namespace Eigen;\nusing complex_sparse_matrix = Eigen::SparseMatrix<std::complex<double>>;\nusing complex_vector = Eigen::VectorXcd;\nusing complex_matrix = Eigen::MatrixXcd;\n\n#define PI acos(-1.0)\n\n//*******************Changing***************************\n//Without damping matrix\n//full geometry, no symmetric boundarycondition\n//********************************************************\n\n//#include \"mkl_lapacke.h\"\n//#include \"lapack.h\"\n\n//typedef size_t INT;\n//#define MKL_INT INT\n//#ifndef lapack_int\n//#define lapack_int MKL_INT\n//#endif\n//written by Chau Nguyen Khanh\n#define MIN(a, b) ((a) < (b) ? (a) : (b))\n//#ifdef __cplusplus\n//extern \"C\" bool utIsInterruptPending();\n//#else\n//extern bool utIsInterruptPending();\n//#endif\n\n#if defined(NAN_EQUALS_ZERO)\n#define IsNonZero(d) ((d)!=0.0 || mxIsNaN(d))\n#else\n#define IsNonZero(d) ((d)!=0.0)\n#endif\n\n//Dynamic force\n// double force(double x)\n// {\n// \tdouble i;\n// \tif ((1 - x) >= 0)\n// \t{\n// \t\ti = 1.0;\n// \t}\n// \telse\n// \t{\n// \t\ti = 0.0;\n// \t}\n// \treturn -4 * (1.0 - pow((2.0 * x - 1.0), 2.0)) * i;\n// }\ndouble force(double x)\n{\n\treturn 1e9*sin(460 * x);\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\t//*********************************************\n\t/* get the values from the struct 1x1 */\n\t// int NoTimeStep = (int) mxGetScalar(mxGetField(prhs[0], 0, \"NoTimeStep\"));\n\t// int N_DoF = (int) mxGetScalar(mxGetField(prhs[0], 0, \"N_DoF\")); // number of dof per element\n\t// double dt = (double) mxGetScalar(mxGetField(prhs[0], 0, \"dt\")); // number of dof per element\n\t//*********************************************\n\n\t/* get the values from the struct Matrix m x 1 *//*only use the pointer*/\n\t// double *TIME_vec = (double *) mxGetPr(mxGetField(prhs[0], 0, \"TIME_vec\"));\n\t// int *TIMEPLOT = (int*) mxGetPr(mxGetField(prhs[0], 0, \"TIMEPLOT\"));\n\t// int LengthTIMEPLOT = (int) mxGetScalar(mxGetField(prhs[0], 0, \"LengthTIMEPLOT\")); // number of dof per element\n\n\t// \tdouble *val_v0 = (double *) mxGetPr(mxGetField(prhs[0], 0, \"v0\")); //\n\t// \tEigen::VectorXd v0 = Map < VectorXd > (val_v0, N_DoF);\n\t//*********************************************\n\tdouble *val_rhs_matrix = (double *) mxGetPr(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n\tint m_rhs_matrix = mxGetM(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n\tint n_rhs_matrix = mxGetN(mxGetField(prhs[0], 0, \"rhs_matrix\"));\n\tEigen::MatrixXd rhs_matrix = Eigen::Map < MatrixXd > (val_rhs_matrix, m_rhs_matrix, n_rhs_matrix);\n\n\tdouble *nnzval_K = (double *) mxGetPr(mxGetField(prhs[0], 0, \"nnzval_K\"));\n\tint m_K = (int) mxGetScalar(mxGetField(prhs[0], 0, \"m_K\"));\n\tint nnz_K = (int) mxGetScalar(mxGetField(prhs[0], 0, \"nnz_K\"));\n\tint *Ir_K = (int *) mxGetPr(mxGetField(prhs[0], 0, \"Ir_K\"));\n\tint *Jc_K = (int *) mxGetPr(mxGetField(prhs[0], 0, \"Jc_K\"));\n\tstd::vector < Eigen::Triplet<double> > trip_K(3 * nnz_K);\n\tfor (int i = 0; i < nnz_K; ++i)\n\t{\n\t\ttrip_K.push_back(Eigen::Triplet<double>(Ir_K[i] - 1, Jc_K[i] - 1, nnzval_K[i]));\n\t}\n\tEigen::SparseMatrix<double> K(m_K, m_K);\n\tK.setFromTriplets(trip_K.begin(), trip_K.end());\n\n\n        std::cout << \"finishing read matrix from matlab\" << std::endl;\n\n        \n\t//\t* Out put *//* Out put *//* Out put *//* Out put *//* Out put *//* Out put */\n\tplhs[0] = mxCreateDoubleMatrix((mwSize) m_rhs_matrix, (mwSize) n_rhs_matrix, mxREAL);\n\tdouble *u0_out = mxGetPr(plhs[0]); // pointer pr_out will manage data in COLUMN Major.\n\t// plhs[1] = mxCreateDoubleMatrix((mwSize) N_DoF, (mwSize) LengthTIMEPLOT, mxREAL);\n\t// double *v0_out = mxGetPr(plhs[1]); // pointer pr_out will manage data in COLUMN Major.\n\t// plhs[2] = mxCreateDoubleMatrix((mwSize) N_DoF, (mwSize) LengthTIMEPLOT, mxREAL);\n\t// double *a0_out = mxGetPr(plhs[2]); // pointer pr_out will manage data in COLUMN Major.\n\n\n\tEigen::SparseLU < Eigen::SparseMatrix<double> > solver_LHS;\n\tsolver_LHS.analyzePattern(K); // for this step the numerical values of A are not used\n\tsolver_LHS.factorize(K);\n\tif (solver_LHS.info() != Success)\n\t{\n\t\t// decomposition failed\n\t\tstd::cout << \"decomposition failed\" << std::endl;\n\t\treturn;\n\t} else {\n\t\tstd::cout << \"decomposition successful\" << std::endl;\n\t}\n\n\tEigen::MatrixXd u_n1(m_rhs_matrix,n_rhs_matrix);\n\tu_n1 = solver_LHS.solve(rhs_matrix);\n\n\n\t//Update solution to Final matrix\n\n\tEigen::Map < MatrixXd > (u0_out + (m_rhs_matrix * 0), m_rhs_matrix,n_rhs_matrix) = u_n1;\n\n}\n", "meta": {"hexsha": "be1049046c504dfe5a0eec5ba650cdfdd6a33dd8", "size": 4821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/tests/solver_eigen_mex.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab/matlab_mex/src_mex/tests/solver_eigen_mex.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab/matlab_mex/src_mex/tests/solver_eigen_mex.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2482758621, "max_line_length": 114, "alphanum_fraction": 0.6376270483, "num_tokens": 1507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5833615732255093}}
{"text": "#define __USE_MATH_DEFINES\r\n\r\n#define BOOST_UBLAS_TYPE_CHECK (0)\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <vector>\r\n\r\n#include \"JGTL_Ray2.h\"\r\n#include \"JGTL_Vector2.h\"\r\n#include \"JGTL_Quadratic.h\"\r\n#include \"JGTL_StringConverter.h\"\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/vector_proxy.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\nusing namespace std;\r\nusing namespace JGTL;\r\nusing namespace boost;\r\nusing namespace boost::numeric;\r\n\r\n    typedef float (*regressionEquation2)(float,float,float);\r\n    typedef void (*regressionEquationDerivative2)(float,float,float,float&,float&);\r\n\r\n    typedef float (*regressionEquation3)(float,float,float,float);\r\n    typedef void (*regressionEquationDerivative3)(float,float,float,float,float&,float&,float&);\r\n\r\n\ttemplate<class T>\r\nbool InvertMatrix(const ublas::matrix<T>& input, ublas::matrix<T>& inverse) \r\n{\r\n\tusing namespace boost::numeric::ublas;\r\n\ttypedef permutation_matrix<std::size_t> pmatrix;\r\n\t// create a working copy of the input\r\n\tmatrix<T> A(input);\r\n\t// create a permutation matrix for the LU-factorization\r\n\tpmatrix pm(A.size1());\r\n\r\n\r\n\t// perform LU-factorization\r\n\tint res = lu_factorize(A,pm);\r\n\tif( res != 0 ) return false;\r\n\r\n\r\n\t// create identity matrix of \"inverse\"\r\n\tinverse.assign(ublas::identity_matrix<T>(A.size1()));\r\n\r\n\r\n\t// backsubstitute to get the inverse\r\n\tlu_substitute(A, pm, inverse);\r\n\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid LoadPoints(string ptsString,vector< JGTL::Vector2<float> > &points)\r\n{\r\n\tvector<string> splits;\r\n\tsplit( splits, ptsString, is_any_of(\",\") );\r\n\r\n\tfor(size_t a=0;a<splits.size();a+=2)\r\n\t{\r\n\t\tif(splits[a].size()==0)\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tpoints.push_back(\r\n\t\t\t\tJGTL::Vector2<float>(stringTo<float>(splits[a]),stringTo<float>(splits[a+1]))\r\n\t\t\t\t);\r\n\r\n\t\t//cout << \"Adding point: \" << points.back() << endl;\r\n\t}\r\n}\r\n\r\nfloat linear(float a,float b,float x)\r\n{\r\n\treturn a + b*x;\r\n}\r\nvoid linearDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = x;\r\n}\r\n\r\nfloat power(float a,float b,float x)\r\n{\r\n\treturn a*pow(x,b);\r\n}\r\nvoid powerDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = pow(x,b);\r\n\tderiv_a = tmp;\r\n\tderiv_b = a*tmp*log(x);\r\n}\r\n\r\nfloat exponential(float a,float b,float x)\r\n{\r\n\treturn a*exp(b*x);\r\n}\r\nvoid exponentialDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = exp(b*x);\r\n\tderiv_a = tmp;\r\n\tderiv_b = a*x*tmp;\r\n}\r\n\r\nfloat logarithmic(float a,float b,float x)\r\n{\r\n\treturn a + b*log(x);\r\n}\r\nvoid logarithmicDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = log(x);\r\n}\r\n\r\nfloat hyperbolic(float a,float b,float x)\r\n{\r\n\treturn a + b/x;\r\n}\r\nvoid hyperbolicDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = 1.0f/x;\r\n}\r\n\r\nfloat squared(float a,float b,float x)\r\n{\r\n\treturn a + b*x*x;\r\n}\r\nvoid squaredDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = x*x;\r\n}\r\n\r\nfloat taylor(float a,float b,float x)\r\n{\r\n\treturn exp(a + b*x*x);\r\n}\r\nvoid taylorDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = exp(a + b*x*x);\r\n\tderiv_a = tmp;\r\n\tderiv_b = x*x*tmp;\r\n}\r\n\r\nfloat expE(float a,float b,float x)\r\n{\r\n\treturn a + b*pow(x,float(M_E));\r\n}\r\nvoid expEDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = pow(x,float(M_E));\r\n}\r\n\r\nfloat taylor2(float a,float b,float x)\r\n{\r\n\treturn exp(a + b*sqrt(x));\r\n}\r\nvoid taylor2Derivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = exp(a + b*sqrt(x));\r\n\tderiv_a = tmp;\r\n\tderiv_b = sqrt(x)*tmp;\r\n}\r\n\r\nfloat hyperb2(float a,float b,float x)\r\n{\r\n\treturn a + (b / (x*x) );\r\n}\r\nvoid hyperb2Derivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = 1/(x*x);\r\n}\r\n\r\nfloat loglog(float a,float b,float x)\r\n{\r\n\treturn a + b*log(x)*log(x);\r\n}\r\nvoid loglogDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = log(x)*log(x);\r\n}\r\n\r\nfloat ehyperb(float a,float b,float x)\r\n{\r\n\treturn a*exp(b/x);\r\n}\r\nvoid ehyperbDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = exp(b/x);\r\n\tderiv_a = tmp;\r\n\tderiv_b = (a*tmp)/x;\r\n}\r\n\r\nfloat hyperbSqrt(float a,float b,float x)\r\n{\r\n\treturn a + b/sqrt(x);\r\n}\r\nvoid hyperbSqrtDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = 1/sqrt(x);\r\n}\r\n\r\nfloat hyperbLn(float a,float b,float x)\r\n{\r\n\treturn a + b/log(x);\r\n}\r\nvoid hyperbLnDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = 1/log(x);\r\n}\r\n\r\nfloat logPower(float a,float b,float x)\r\n{\r\n\treturn a * pow(log(x),b);\r\n}\r\nvoid logPowerDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = pow(log(x),b);\r\n\tderiv_a = tmp;\r\n\tderiv_b = a*tmp*log(log(x));\r\n}\r\n\r\nfloat sqrt(float a,float b,float x)\r\n{\r\n\treturn a + b*sqrt(x);\r\n}\r\nvoid sqrtDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = sqrt(x);\r\n}\r\n\r\nfloat xlogx(float a,float b,float x)\r\n{\r\n\treturn a + b*pow(x,log(x));\r\n}\r\nvoid xlogxDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = exp(log(x)*log(x));\r\n}\r\n\r\nfloat hblog(float a,float b,float x)\r\n{\r\n\treturn a + b/pow(x,log(x));\r\n}\r\nvoid hblogDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = exp(-1*log(x)*log(x));\r\n}\r\n\r\nfloat hbe(float a,float b,float x)\r\n{\r\n\treturn a + b/pow(x,float(M_E));\r\n}\r\nvoid hbeDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tderiv_a = 1;\r\n\tderiv_b = 1/pow(x,float(M_E));\r\n}\r\n\r\nfloat ehyperbsqrt(float a,float b,float x)\r\n{\r\n\treturn a*exp( b / sqrt(x) );\r\n}\r\nvoid ehyperbsqrtDerivatives(float a,float b,float x,float &deriv_a,float &deriv_b)\r\n{\r\n\tfloat tmp = exp( b / sqrt(x) );\r\n\tderiv_a = tmp;\r\n\tderiv_b = a*tmp/sqrt(x);\r\n}\r\n\r\nfloat quadratic(float a,float b,float c,float x)\r\n{\r\n\treturn a*x*x + b*x + c;\r\n}\r\nvoid quadraticDerivatives(float a,float b,float c,float x,float &deriv_a,float &deriv_b,float &deriv_c)\r\n{\r\n\tderiv_a = x*x;\r\n\tderiv_b = x;\r\n\tderiv_c = 1;\r\n}\r\n\r\nclass Result2\r\n{\r\npublic:\r\n\tfloat A,B;\r\n\tfloat r2;\r\n\r\n\tResult2(float Aset,float Bset,float r2set)\r\n\t\t:\r\n\t\t\tA(Aset),\r\n\t\t\tB(Bset),\r\n\t\t\tr2(r2set)\r\n\t{\r\n\t}\r\n\r\n\tResult2()\r\n\t{\r\n\t}\r\n};\r\n\r\nclass Result3\r\n{\r\npublic:\r\n\tfloat A,B,C;\r\n\tfloat r2;\r\n\r\n\tResult3(float Aset,float Bset,float Cset,float r2set)\r\n\t\t:\r\n\t\t\tA(Aset),\r\n\t\t\tB(Bset),\r\n\t\t\tC(Cset),\r\n\t\t\tr2(r2set)\r\n\t{\r\n\t}\r\n\r\n\tResult3()\r\n\t{\r\n\t}\r\n};\r\n\r\nResult2 tryRegression2(\r\n\t\tconst vector< JGTL::Vector2<float> > &points,\r\n\t\tregressionEquation2 equation2,\r\n\t\tregressionEquationDerivative2 derivative2\r\n\t\t);\r\n\r\nResult3 tryRegression3(\r\n\t\tconst vector< JGTL::Vector2<float> > &points,\r\n\t\tregressionEquation3 equation3,\r\n\t\tregressionEquationDerivative3 derivative3\r\n\t\t);\r\n\r\nint main()\r\n{\r\n\tvector< JGTL::Vector2<float> > points;\r\n\r\n\tLoadPoints(\"2,59.49,3,40.81,4,32.64,5,26.10,6,24.18,7,22.01,8,17.13,9,16.77,10,18.26,11,13.38,12,13.93,13,10.99,14,11.21,15,10.61,16,13.16,17,12.14,18,11.53,19,8.54,20,8.16,21,7.21,22,7.28,23,10.15,24,7.21,25,8.31,26,8.44,27,6.19,28,6.29,29,4.34,30,7.13,31,5.51,32,7.54,33,5.16,34,6.98,35,4.76,36,5.67,37,7.85,38,2.94,39,6.54,40,3.22,41,5.59,42,6.51,43,2.52,44,7.07,45,4.32,46,6.88,47,6.97,48,3.53,49,2.51,50,4.38,51,2.56,\",points);\r\n\r\n\t vector<regressionEquation2> equations2;\r\n\t vector<regressionEquationDerivative2> derivatives2;\r\n\r\n    /* the ampersand is actually optional */\r\n    equations2.push_back(&linear);\r\n    derivatives2.push_back(&linearDerivatives);\r\n    equations2.push_back(&power);\r\n    derivatives2.push_back(&powerDerivatives);\r\n    equations2.push_back(&exponential);\r\n    derivatives2.push_back(&exponentialDerivatives);\r\n    equations2.push_back(&logarithmic);\r\n    derivatives2.push_back(&logarithmicDerivatives);\r\n    equations2.push_back(&hyperbolic);\r\n    derivatives2.push_back(&hyperbolicDerivatives);\r\n    equations2.push_back(&squared);\r\n    derivatives2.push_back(&squaredDerivatives);\r\n    equations2.push_back(&taylor);\r\n    derivatives2.push_back(&taylorDerivatives);\r\n    equations2.push_back(&expE);\r\n    derivatives2.push_back(&expEDerivatives);\r\n    equations2.push_back(&taylor2);\r\n    derivatives2.push_back(&taylor2Derivatives);\r\n    equations2.push_back(&hyperb2);\r\n    derivatives2.push_back(&hyperb2Derivatives);\r\n    equations2.push_back(&loglog);\r\n    derivatives2.push_back(&loglogDerivatives);\r\n    equations2.push_back(&ehyperb);\r\n    derivatives2.push_back(&ehyperbDerivatives);\r\n    equations2.push_back(&hyperbSqrt);\r\n    derivatives2.push_back(&hyperbSqrtDerivatives);\r\n    equations2.push_back(&hyperbLn);\r\n    derivatives2.push_back(&hyperbLnDerivatives);\r\n    equations2.push_back(&logPower);\r\n    derivatives2.push_back(&logPowerDerivatives);\r\n    equations2.push_back(&sqrt);\r\n    derivatives2.push_back(&sqrtDerivatives);\r\n    equations2.push_back(&xlogx);\r\n    derivatives2.push_back(&xlogxDerivatives);\r\n    equations2.push_back(&hblog);\r\n    derivatives2.push_back(&hblogDerivatives);\r\n    equations2.push_back(&hbe);\r\n    derivatives2.push_back(&hbeDerivatives);\r\n    equations2.push_back(&ehyperbsqrt);\r\n    derivatives2.push_back(&ehyperbsqrtDerivatives);\r\n\r\n\t vector<regressionEquation3> equations3;\r\n\t vector<regressionEquationDerivative3> derivatives3;\r\n\t \r\n    equations3.push_back(&quadratic);\r\n    derivatives3.push_back(&quadraticDerivatives);\r\n\r\n\t Result3 bestResult;\r\n\t int resultIndex;\r\n\t int resultDim;\r\n\r\n \t for(size_t regressionTypes2=0;regressionTypes2<equations2.size();regressionTypes2++)\r\n\t{\r\n\t\tcout << \"ON CASE: \" << regressionTypes2 << endl;\r\n\t\tResult2 result = tryRegression2(\r\n\t\t\t\tpoints,\r\n\t\t\t\tequations2[regressionTypes2],\r\n\t\t\t\tderivatives2[regressionTypes2]\r\n\t\t\t\t);\r\n\r\n\t\tcout << \"A: \" << result.A << \", B: \" << result.B\r\n\t\t\t<< \", r2: \" << result.r2 << endl;\r\n\r\n\t\tif(!regressionTypes2 || result.r2>bestResult.r2)\r\n\t\t{\r\n\t\t\tbestResult.A = result.A;\r\n\t\t\tbestResult.B = result.B;\r\n\t\t\tbestResult.C = 0;\r\n\t\t\tresultIndex = regressionTypes2;\r\n\t\t\tresultDim=2;\r\n\t\t}\r\n\t}\r\n\r\n \t for(size_t regressionTypes3=0;regressionTypes3<equations3.size();regressionTypes3++)\r\n\t{\r\n\t\tcout << \"ON CASE: \" << regressionTypes3 << endl;\r\n\t\tResult3 result = tryRegression3(\r\n\t\t\t\tpoints,\r\n\t\t\t\tequations3[regressionTypes3],\r\n\t\t\t\tderivatives3[regressionTypes3]\r\n\t\t\t\t);\r\n\r\n\t\tcout << \"A: \" << result.A << \", B: \" << result.B\r\n\t\t\t<< \", C: \" << result.C \r\n\t\t\t<< \", r2: \" << result.r2 << endl;\r\n\r\n\t\tif(!regressionTypes3 || result.r2>bestResult.r2)\r\n\t\t{\r\n\t\t\tbestResult = result;\r\n\t\t\tresultIndex = regressionTypes3;\r\n\t\t\tresultDim=3;\r\n\t\t}\r\n\t}\r\n\r\n\t if(resultDim==2)\r\n\t {\r\n\t }\r\n\t else //resultDim==3\r\n\t {\r\n\t }\r\n\r\n\treturn 0;\r\n}\r\n\r\nResult2 tryRegression2(\r\n\t\tconst vector< JGTL::Vector2<float> > &points,\r\n\t\tregressionEquation2 equation2,\r\n\t\tregressionEquationDerivative2 derivative2\r\n\t\t)\r\n{\r\n\tResult2 result;\r\n\r\n\t/*\r\n\tpoints.push_back(JGTL::Vector2<float>(0,0));\r\n\tpoints.push_back(JGTL::Vector2<float>(1,1));\r\n\tpoints.push_back(JGTL::Vector2<float>(2,2));\r\n\tpoints.push_back(JGTL::Vector2<float>(3,3));\r\n\tpoints.push_back(JGTL::Vector2<float>(4,4));\r\n\t*/\r\n\r\n\t//Formula: f(x,A,B) = A + Bx\r\n\t//Derivative with respect to A: f(x,A,B) = 1\r\n\t//Derivative with respect to B: f(x,A,B) = x\r\n\r\n\t//First, pick an initial guess\r\n\tresult.A = 1;\r\n\tresult.B = 1;\r\n\r\n\tfloat prev_s_yx;\r\n\r\n\tfor(int trials=0;trials<100;trials++)\r\n\t{\r\n\t\t//cout << \"On trial: \" << trials << endl;\r\n\t\tublas::matrix<float> delta(int(points.size()),1);\r\n\r\n\t\tfloat s_yx = 0;\r\n\t\tfloat s_y = 0;\r\n\t\t//cout << \"Deltas: \";\r\n\t\tfloat avg_y=0;\r\n\t\tfor(int a=0;a<int(points.size());a++)\r\n\t\t{\r\n\t\t\tavg_y += points[a].y;\r\n\t\t}\r\n\t\tavg_y /= float(points.size());\r\n\t\t//cout << \"Difference: \";\r\n\t\tfor(int a=0;a<int(points.size());a++)\r\n\t\t{\r\n\t\t\tdelta(a,0) = points[a].y - (equation2)(result.A,result.B,points[a].x);\r\n\t\t\t//if(a)\r\n\t\t\t\t//cout << \", \";\r\n\t\t\t//cout << delta(a,0);\r\n\r\n\t\t\t//Compute s_yx and s_y to see if we need to keep going\r\n\t\t\ts_yx += (delta(a,0)*delta(a,0));\r\n\t\t\ts_y += (points[a].y - avg_y)*(points[a].y - avg_y);\r\n\t\t}\r\n\r\n\t\tresult.r2 = max(0.0f,1.0f - (s_yx / s_y));\r\n\t\t//cout << endl;\r\n\r\n\t\t//cout << \"s_yx: \" << s_yx << \" s_y: \" << s_y << endl;\r\n\t\t//cout << \"R2: \" << r2 << endl;\r\n\r\n\t\tif(trials)\r\n\t\t{\r\n\t\t\tif(fabs((prev_s_yx - s_yx)/(prev_s_yx)) < 0.0001)\r\n\t\t\t{\r\n\t\t\t\t//cout << \"Found premature stopping condition!\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tprev_s_yx = s_yx;\r\n\r\n\t\tublas::matrix<float> deriv(int(points.size()),2);\r\n\r\n\t\t//Compute estimate\r\n\t\t//cout << \"Derivative: \";\r\n\t\tfor(int testPoint=0;testPoint<int(points.size());testPoint++)\r\n\t\t{\r\n\t\t\tconst JGTL::Vector2<float> &curPoint = points[testPoint];\r\n\r\n\t\t\t(derivative2)(result.A,result.B,curPoint.x,deriv(testPoint,0),deriv(testPoint,1));\r\n\r\n\t\t\t//cout << deriv(testPoint,0) << \", \" << deriv(testPoint,1) << \", \";\r\n\t\t}\r\n\t\t//cout << endl;\r\n\r\n\t\tublas::matrix<float> derivTranspose = trans(deriv);\r\n\r\n\t\t//mat_a = derivTranspose * deriv\r\n\t\tublas::matrix<float> mat_a = prod(derivTranspose,deriv);\r\n\r\n\t\t//mat_b = derivTranspose * db\r\n\t\tublas::matrix<float> mat_b = prod(derivTranspose,delta);\r\n\r\n\t\t//a*(delta_vector) = b, so solve for delta_vector\r\n\t\tublas::matrix<float> mat_a_inverse(2,2);\r\n\t\tbool retval=false;\r\n\t\ttry\r\n\t\t{\r\n\t\t    retval = InvertMatrix(mat_a,mat_a_inverse);\r\n\t\t}\r\n\t\tcatch(...)\r\n\t\t{\r\n\t\t\tcout << \"Error computing matrix inverse!\\n\";\r\n\t\t}\r\n\r\n\t\tif(retval)\r\n\t\t{\r\n\t\t\tublas::matrix<float> delta_vector = prod(mat_a_inverse,mat_b);\r\n\r\n\t\t\t//cout << \"Delta A: \" << delta_vector(0,0) << endl;\r\n\t\t\t//cout << \"Delta B: \" << delta_vector(1,0) << endl;\r\n\r\n\t\t\tresult.A += delta_vector(0,0);\r\n\t\t\tresult.B += delta_vector(1,0);\r\n\r\n\t\t\t//cout << \"New A: \" << result.A << endl;\r\n\t\t\t//cout << \"New B: \" << result.B << endl;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcout << \"INVERSE FAILED!\\n\";\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t//cout << \"R2: \" << result.r2 << endl;\r\n\r\n\treturn result;\r\n}\r\n\r\nResult3 tryRegression3(\r\n\t\tconst vector< JGTL::Vector2<float> > &points,\r\n\t\tregressionEquation3 equation3,\r\n\t\tregressionEquationDerivative3 derivative3\r\n\t\t)\r\n{\r\n\tResult3 result;\r\n\r\n\t/*\r\n\tpoints.push_back(JGTL::Vector2<float>(0,0));\r\n\tpoints.push_back(JGTL::Vector2<float>(1,1));\r\n\tpoints.push_back(JGTL::Vector2<float>(2,2));\r\n\tpoints.push_back(JGTL::Vector2<float>(3,3));\r\n\tpoints.push_back(JGTL::Vector2<float>(4,4));\r\n\t*/\r\n\r\n\t//Formula: f(x,A,B) = A + Bx\r\n\t//Derivative with respect to A: f(x,A,B) = 1\r\n\t//Derivative with respect to B: f(x,A,B) = x\r\n\r\n\t//First, pick an initial guess\r\n\tresult.A = 1;\r\n\tresult.B = 1;\r\n\tresult.C = 1;\r\n\r\n\tfloat prev_s_yx;\r\n\r\n\tfor(int trials=0;trials<100;trials++)\r\n\t{\r\n\t\t//cout << \"On trial: \" << trials << endl;\r\n\t\tublas::matrix<float> delta(int(points.size()),1);\r\n\r\n\t\tfloat s_yx = 0;\r\n\t\tfloat s_y = 0;\r\n\t\t//cout << \"Deltas: \";\r\n\t\tfloat avg_y=0;\r\n\t\tfor(int a=0;a<int(points.size());a++)\r\n\t\t{\r\n\t\t\tavg_y += points[a].y;\r\n\t\t}\r\n\t\tavg_y /= float(points.size());\r\n\t\tfor(int a=0;a<int(points.size());a++)\r\n\t\t{\r\n\t\t\tdelta(a,0) = points[a].y - (equation3)(result.A,result.B,result.C,points[a].x);\r\n\t\t\t//if(a)\r\n\t\t\t\t//cout << \", \";\r\n\t\t\t//cout << delta(a,0);\r\n\r\n\t\t\t//Compute s_yx and s_y to see if we need to keep going\r\n\t\t\ts_yx += (delta(a,0)*delta(a,0));\r\n\t\t\ts_y += (points[a].y - avg_y)*(points[a].y - avg_y);\r\n\t\t}\r\n\r\n\t\tresult.r2 = max(0.0f,1.0f - (s_yx / s_y));\r\n\t\t//cout << endl;\r\n\r\n\t\t//cout << \"s_yx: \" << s_yx << \" s_y: \" << s_y << endl;\r\n\t\t//cout << \"R2: \" << r2 << endl;\r\n\r\n\t\tif(trials)\r\n\t\t{\r\n\t\t\tif(fabs((prev_s_yx - s_yx)/(prev_s_yx)) < 0.0001)\r\n\t\t\t{\r\n\t\t\t\t//cout << \"Found premature stopping condition!\\n\";\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tprev_s_yx = s_yx;\r\n\r\n\t\tublas::matrix<float> deriv(int(points.size()),3);\r\n\r\n\t\t//Compute estimate\r\n\t\tfor(int testPoint=0;testPoint<int(points.size());testPoint++)\r\n\t\t{\r\n\t\t\tconst JGTL::Vector2<float> &curPoint = points[testPoint];\r\n\r\n\t\t\t(derivative3)(result.A,result.B,result.C,curPoint.x,deriv(testPoint,0),deriv(testPoint,1),deriv(testPoint,2));\r\n\t\t}\r\n\r\n\t\tublas::matrix<float> derivTranspose = trans(deriv);\r\n\r\n\t\t//mat_a = derivTranspose * deriv\r\n\t\tublas::matrix<float> mat_a = prod(derivTranspose,deriv);\r\n\r\n\t\t//mat_b = derivTranspose * db\r\n\t\tublas::matrix<float> mat_b = prod(derivTranspose,delta);\r\n\r\n\t\t//a*(delta_vector) = b, so solve for delta_vector\r\n\t\tublas::matrix<float> mat_a_inverse(3,3);\r\n\t\tbool retval = InvertMatrix(mat_a,mat_a_inverse);\r\n\r\n\t\tif(retval)\r\n\t\t{\r\n\t\t\tublas::matrix<float> delta_vector = prod(mat_a_inverse,mat_b);\r\n\r\n\t\t\t//cout << \"Delta A: \" << delta_vector(0,0) << endl;\r\n\t\t\t//cout << \"Delta B: \" << delta_vector(1,0) << endl;\r\n\t\t\t//cout << \"Delta C: \" << delta_vector(2,0) << endl;\r\n\r\n\t\t\tresult.A += delta_vector(0,0);\r\n\t\t\tresult.B += delta_vector(1,0);\r\n\t\t\tresult.C += delta_vector(2,0);\r\n\r\n\t\t\t//cout << \"New A: \" << result.A << endl;\r\n\t\t\t//cout << \"New B: \" << result.B << endl;\r\n\t\t\t//cout << \"New C: \" << result.C << endl;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//cout << \"INVERSE FAILED!\\n\";\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t//cout << \"R2: \" << result.r2 << endl;\r\n\r\n\treturn result;\r\n}\r\n\r\n", "meta": {"hexsha": "00b4ee9ec35842a9f8102dc9225c852a86f3679e", "size": 17220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JGTL/tests/LeastSquares.cpp", "max_stars_repo_name": "LMBernardo/HyperNEAT", "max_stars_repo_head_hexsha": "8ebee6fda17dcf20dd0c6c081dc8681557c1faad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "JGTL/tests/LeastSquares.cpp", "max_issues_repo_name": "LMBernardo/HyperNEAT", "max_issues_repo_head_hexsha": "8ebee6fda17dcf20dd0c6c081dc8681557c1faad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "JGTL/tests/LeastSquares.cpp", "max_forks_repo_name": "LMBernardo/HyperNEAT", "max_forks_repo_head_hexsha": "8ebee6fda17dcf20dd0c6c081dc8681557c1faad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 24.2194092827, "max_line_length": 434, "alphanum_fraction": 0.6350174216, "num_tokens": 5414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5832368786015266}}
{"text": "/**\n * @file vortex.cc\n * @brief Solve the lid driven cavity experiment on a nonuniform mesh\n */\n\n#include <build_system_matrix.h>\n#include <lf/assemble/dofhandler.h>\n#include <lf/io/gmsh_reader.h>\n#include <lf/io/vtk_writer.h>\n#include <lf/mesh/entity.h>\n#include <lf/mesh/hybrid2d/mesh_factory.h>\n#include <lf/mesh/utils/tp_triag_mesh_builder.h>\n#include <lf/quad/quad.h>\n#include <lf/refinement/refinement.h>\n#include <piecewise_const_element_matrix_provider.h>\n#include <piecewise_const_element_vector_provider.h>\n#include <solution_to_mesh_data_set.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cassert>\n#include <filesystem>\n\n/**\n * @brief Solves the lid driven cavity problem on a domain [0,100]x[0,100]\n * @param mesh A shared pointer to the mesh on which to solve the PDE\n * @param dofh The dofhandler to use for the simulation\n * @param modified If true, use the modified penalty term\n * otherwise use the original one\n * @returns A vector containing the basis function coefficients of the solution\n */\nEigen::VectorXd solveLidDrivenCavity(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh,\n    const lf::assemble::DofHandler &dofh, bool modified = false) {\n  // No volume forces are present in this experiment\n  auto f = [](const Eigen::Vector2d & /*unused*/) -> Eigen::Vector2d {\n    return Eigen::Vector2d::Zero();\n  };\n  // The top lid is driven with velocity 1\n  auto dirichlet_funct = [](const lf::mesh::Entity &edge) -> Eigen::Vector2d {\n    static constexpr double eps = 1e-10;\n    const auto *const geom = edge.Geometry();\n    const auto vertices = geom->Global(edge.RefEl().NodeCoords());\n    Eigen::Vector2d v;\n    v << 1. / 100, 0;\n    if (vertices(1, 0) <= 100 + eps && vertices(1, 0) >= 100 - eps &&\n        vertices(1, 1) <= 100 + eps && vertices(1, 1) >= 100 - eps) {\n      return v;\n    }\n    return Eigen::Vector2d::Zero();\n  };\n\n  // Solve the LSE using sparse cholesky\n  const auto [A, rhs] =\n      projects::ipdg_stokes::assemble::buildSystemMatrixNoFlow(\n          mesh, dofh, f, dirichlet_funct, 1,\n          lf::quad::make_TriaQR_MidpointRule(), modified);\n  Eigen::SparseMatrix<double> As = A.makeSparse();\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(As);\n  return solver.solve(rhs);\n}\n\n/**\n * @brief stores the solution of the lid driven cavity experiment to a vtk file\n */\nint main() {\n  const double mu = 1;\n  const double sigma = 1;\n  const double rho = 1;\n\n  // Load the mesh\n  std::filesystem::path meshpath = __FILE__;\n  meshpath = meshpath.parent_path() / \"mesh.msh\";\n  std::unique_ptr<lf::mesh::MeshFactory> factory =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(factory), meshpath.string());\n  auto mesh = reader.mesh();\n\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh);\n\n  lf::assemble::UniformFEDofHandler dofh(\n      mesh, {{lf::base::RefEl::kPoint(), 1}, {lf::base::RefEl::kSegment(), 1}});\n  std::cout << \"solving original\" << std::endl;\n  const Eigen::VectorXd solution_original =\n      solveLidDrivenCavity(mesh, dofh, false);\n  std::cout << \"extracting original\" << std::endl;\n  const auto c_original =\n      projects::ipdg_stokes::post_processing::extractBasisFunctionCoefficients(\n          mesh, dofh, solution_original);\n  const auto v_original =\n      projects::ipdg_stokes::post_processing::extractVelocity(\n          mesh, dofh, solution_original);\n  std::cout << \"solving modified\" << std::endl;\n  const Eigen::VectorXd solution_modified =\n      solveLidDrivenCavity(mesh, dofh, true);\n  std::cout << \"extracting modified\" << std::endl;\n  const auto c_modified =\n      projects::ipdg_stokes::post_processing::extractBasisFunctionCoefficients(\n          mesh, dofh, solution_modified);\n  const auto v_modified =\n      projects::ipdg_stokes::post_processing::extractVelocity(\n          mesh, dofh, solution_modified);\n\n  std::cout << \"writing\" << std::endl;\n  lf::io::VtkWriter writer(mesh, \"vortex.vtk\");\n  writer.WritePointData(\"coefficients_original\", c_original);\n  writer.WritePointData(\"coefficients_modified\", c_modified);\n  writer.WriteCellData(\"velocity_original\", v_original);\n  writer.WriteCellData(\"velocity_modified\", v_modified);\n\n  return 0;\n}\n", "meta": {"hexsha": "8fc882fad511ab14560a6fe371b6efc977298ee3", "size": 4241, "ext": "cc", "lang": "C++", "max_stars_repo_path": "projects/ipdg_stokes/examples/lid_driven_cavity/vortex.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "projects/ipdg_stokes/examples/lid_driven_cavity/vortex.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "projects/ipdg_stokes/examples/lid_driven_cavity/vortex.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 37.201754386, "max_line_length": 80, "alphanum_fraction": 0.6981843905, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5832368751318213}}
{"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#include <cstdlib>\n#include <limits>\n\n\nnamespace dcs { namespace math { namespace detail {\n\n// See also:\n// - https://adtmag.com/Articles/2000/03/16/Comparing-Floats-How-To-Determine-if-Floating-Quantities-Are-Close-Enough-Once-a-Tolerance-Has-Been.aspx\n// - https://adtmag.com/articles/2000/03/16/comparing-floatshow-to-determine-if-floating-quantities-are-close-enough-once-a-tolerance-has-been-r.aspx\n// - https://bitbashing.io/comparing-floats.html\n// - http://code.google.com/p/googletest/source/browse/trunk/include/gtest/internal/gtest-internal.h\n// - https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues\n// - http://floating-point-gui.de/errors/comparison/\n// - http://fcmp.sourceforge.net/\n// - http://grouper.ieee.org/groups/754/\n// - https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#Floating-Point_Comparison\n// - http://learningcppisfun.blogspot.com/2010/04/comparing-floating-point-numbers.html\n// - https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\n// - https://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c\n// - https://twistedape.me.uk/2016/02/02/comparing-floating-point-numbers/\n// . http://www.boost.org/doc/libs/release/libs/math/doc/html/math_toolkit/float_comparison.html\n// - http://www.boost.org/doc/libs/release/libs/test/doc/html/boost_test/testing_tools/extended_comparison/floating_point.html\n// - https://www.codeproject.com/Articles/383871/Demystify-Csharp-floating-point-equality-and-relat\n// - https://www.gnu.org/software/libc/manual/html_node/Floating-Point-Parameters.html\n// - https://www.gnu.org/software/gsl/doc/html/math.html\n// - http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16\n// - http://www.petebecker.com/js/js200012.html\n// .\n//\n\n\n/**\n * \\brief Perform approximate floating-point comparison.\n *\n * This function determines whether \\a x and \\a y are approximately equal to a\n * relative accuracy \\a epsilon.\n *\n * To perform the approximate floating-point comparison, this function\n * implements the algorithm proposed by D.E. Knuth in Section 4.2.2 of (Knuth,1997) (see REFERENCES).\n *\n * The relative accuracy is measured using an interval of size \\f$2 \\delta\\f$,\n * where \\f$\\delta = 2^k \\epsilon\\f$ and \\f$k\\f$ is the maximum base-2 exponent\n * of \\a x and \\a y as computed by the function `std::frexp`.\n *\n * If \\a x and \\a y lie within this interval, they are considered approximately\n * equal and the function returns `0`.\n * Otherwise if \\a x < \\a y, the function returns `-1`, or if \\a x > \\a y, the\n * function returns `+1`.\n *\n * \\note \\a x and \\a y are compared to relative accuracy, so this function is\n *       not suitable for testing whether a value is approximately zero.\n *       Also, this function may not work correctly with degenerate cases.\n *       For instance, when both \\a x and \\a y are NaN, this function return 0,\n *       which is incorrect because, according to the IEEE 754 standard, NaN is\n *       always different from any floating-point number including itself\n *       (indeed, NaN is \"unordered\").\n *\n * The implementation is based on the one provided by the GNU Scientific Library\n * (GSL) which in turns is based on the package fcmp by T.C. Belding.\n *\n * \\copyright GNU Scientific Library (GSL) 2.4 Copyright (c) 2002 Gert Van den Eynde (https://www.gnu.org/software/gsl)\n * \\copyright fcmp 1.2.2 Copyright (c) 1998-2000 Theodore C. Belding, University of Michigan Center for the Study of Complex Systems (Ted.Belding@umich.edu)\n *\n * REFERENCES\n * - D.E. Knuth \"The Art of Computer Programming, Volume 2: Seminumerical Algorithms, 3rd Edition,\" Addison-Wesley, 1997.\n * .\n */\ntemplate <typename T>\ninline\ntypename ::boost::enable_if<\n\t::boost::is_floating_point<T>,\n\tint\n>::type fcmp(const T x, const T y, const T epsilon)\n{\n\t// Find exponent of largest absolute value\n\n\tconst T max = (std::fabs(x) > std::fabs(y)) ? x : y;\n\n\tint exponent;\n\n\tstd::frexp(max, &exponent);\n\n\t// Form a neighborhood of size  2 * delta\n\n\tconst T delta = std::ldexp(epsilon, exponent);\n\n\tconst T difference = x - y;\n\n\tif (difference > delta) // x > y\n\t{\n\t\treturn 1;\n\t}\n\tif (difference < -delta) // x < y\n\t{\n\t\treturn -1;\n\t}\n\t// -delta <= difference <= delta => x ~=~ y\n\treturn 0;\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(e_x,e_y)\n * \\f]\n * where \\f$e_x\\f$ and \\f$e_y\\f$ are the exponent of \\f$x\\f$ and \\f$y\\f$,\n * respectively.\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 or have other special values like inf or NaN)\n\tif (x == y)\n\t{\n\t\t// Tolerance is useless when both numbers are exactly the same\n\t\treturn true;\n\t}\n\n\t// Handle degenerate cases\n\t//if (::std::isnan(x) || ::std::isinf(x) || ::std::isnan(y) || ::std::isinf(y))\n\tif (!::std::isfinite(x) || !::std::isfinite(y))\n\t{\n\t\t// Tolerance is useless when at least one number is not finite\n\t\treturn x == y;\n\t}\n\n\treturn fcmp(x, y, tol) == 0;\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(e_x,e_y)\n * \\f]\n * where \\f$e_x\\f$ and \\f$e_y\\f$ are the exponent of \\f$x\\f$ and \\f$y\\f$,\n * respectively.\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 or have other special values like inf or NaN)\n\tif (x == y)\n\t{\n\t\t// Tolerance is useless when both numbers are exactly the same\n\t\treturn true;\n\t}\n\n\t// Handle degenerate cases\n\t//if (::std::isnan(x) || ::std::isinf(x) || ::std::isnan(y) || ::std::isinf(y))\n\tif (!::std::isfinite(x) || !::std::isfinite(y))\n\t{\n\t\t// Tolerance is useless when at least one number is not finite\n\t\treturn x == y;\n\t}\n\n\t// Check for numbers tha are very close to zero\n\tconst T zero = 0;\n\tconst T min_val = std::numeric_limits<T>::min();\n\tconst T diff = ::std::fabs(x-y);\n\tif (x == zero || y == zero || diff < min_val)\n\t{\n\t\t// x or y is zero or both are extremely close to it\n\t\t// relative error is less meaningful here\n\t\treturn diff < (tol*min_val);\n\t}\n\n\t// Otherwise, use the Knuth's method\n\n\t// - Find the min(x,y) and gets its exponent\n\tconst T min = (std::fabs(x) < std::fabs(y)) ? x : y;\n\tint exponent = 0;\n\tstd::frexp(min, &exponent);\n\n\t// - Form a neighborhood of size  2 * delta\n\tconst T delta = std::ldexp(tol, exponent);\n\tconst T difference = x - y;\n\n\t// - Now check if the number are very close to each other\n\tif (difference > delta      // x > y\n\t\t|| difference < -delta) // x < y\n\t{\n\t\treturn false;\n\t}\n\treturn true; // -delta <= difference <= delta => x ~=~ y\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(e_x,e_y)\n * \\f]\n * where \\f$e_x\\f$ and \\f$e_y\\f$ are the exponent of \\f$x\\f$ and \\f$y\\f$,\n * respectively.\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// Handle degenerate cases\n\t//if (::std::isnan(x) || ::std::isinf(x) || ::std::isnan(y) || ::std::isinf(y))\n\tif (!::std::isfinite(x) || !::std::isfinite(y))\n\t{\n\t\t// Tolerance is useless when at least one number is not finite\n\t\treturn x > y;\n\t}\n\n\treturn fcmp(x, y, tol) > 0;\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(e_x,e_y)\n * \\f]\n * where \\f$e_x\\f$ and \\f$e_y\\f$ are the exponent of \\f$x\\f$ and \\f$y\\f$,\n * respectively.\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// NOTE: don't use standard comparison operators because they do not take into account the given tolerance.\n\t//       For instance:\n\t//         x = 0.1233\n\t//         y = 0.1234\n\t//         -> x <  y if tol >= 1e-4\n\t//            but\n\t//            x == y if tol <  1e-3\n\n\t// Handle degenerate cases\n\t//if (::std::isnan(x) || ::std::isinf(x) || ::std::isnan(y) || ::std::isinf(y))\n\tif (!::std::isfinite(x) || !::std::isfinite(y))\n\t{\n\t\t// Tolerance is useless when at least one number is not finite\n\t\treturn x < y;\n\t}\n\n\treturn fcmp(x, y, tol) < 0;\n}\n\n}}} // Namespace dcs::math::detail\n\n\n#endif // DCS_MATH_DETAIL_FLOAT_HPP\n", "meta": {"hexsha": "38cfe918e084be1b16cdb9dddf55e0a955d8ddac", "size": 9992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/detail/float.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/detail/float.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/detail/float.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": 31.225, "max_line_length": 156, "alphanum_fraction": 0.6670336269, "num_tokens": 2959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.5832368687086324}}
{"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/series.hpp>\n#include <iostream>\n#include <complex>\n#include <cassert>\n\n//[series_log1p\ntemplate <class T>\nstruct log1p_series\n{\n   // we must define a result_type typedef:\n   typedef T result_type;\n\n   log1p_series(T x)\n      : k(0), m_mult(-x), m_prod(-1) {}\n\n   T operator()()\n   {\n      // This is the function operator invoked by the summation\n      // algorithm, the first call to this operator should return\n      // the first term of the series, the second call the second \n      // term and so on.\n      m_prod *= m_mult;\n      return m_prod / ++k;\n   }\n\nprivate:\n   int k;\n   const T m_mult;\n   T m_prod;\n};\n//]\n\n//[series_log1p_func\ntemplate <class T>\nT log1p(T x)\n{\n   // We really should add some error checking on x here!\n   assert(std::fabs(x) < 1);\n\n   // Construct the series functor:\n   log1p_series<T> s(x);\n   // Set a limit on how many iterations we permit:\n   boost::uintmax_t max_iter = 1000;\n   // Add it up, with enough precision for full machine precision:\n   return boost::math::tools::sum_series(s, std::numeric_limits<T>::epsilon(), max_iter);\n}\n//]\n\n//[series_clog1p_func\ntemplate <class T>\nstruct log1p_series<std::complex<T> >\n{\n   // we must define a result_type typedef:\n   typedef std::complex<T> result_type;\n\n   log1p_series(std::complex<T> x)\n      : k(0), m_mult(-x), m_prod(-1) {}\n\n   std::complex<T> operator()()\n   {\n      // This is the function operator invoked by the summation\n      // algorithm, the first call to this operator should return\n      // the first term of the series, the second call the second \n      // term and so on.\n      m_prod *= m_mult;\n      return m_prod / T(++k);\n   }\n\nprivate:\n   int k;\n   const std::complex<T> m_mult;\n   std::complex<T> m_prod;\n};\n\n\ntemplate <class T>\nstd::complex<T> log1p(std::complex<T> x)\n{\n   // We really should add some error checking on x here!\n   assert(abs(x) < 1);\n\n   // Construct the series functor:\n   log1p_series<std::complex<T> > s(x);\n   // Set a limit on how many iterations we permit:\n   boost::uintmax_t max_iter = 1000;\n   // Add it up, with enough precision for full machine precision:\n   return boost::math::tools::sum_series(s, std::complex<T>(std::numeric_limits<T>::epsilon()), max_iter);\n}\n//]\n\nint main()\n{\n   using namespace boost::math::tools;\n\n   std::cout << log1p(0.25) << std::endl;\n\n   std::cout << log1p(std::complex<double>(0.25, 0.25)) << std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "ee758f947d04242b693d10c1edc35de98ac045fb", "size": 2652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/series.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/series.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/series.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": 25.0188679245, "max_line_length": 106, "alphanum_fraction": 0.6519607843, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.583206470065619}}
{"text": "//| Copyright Inria May 2015\n//| This project has received funding from the European Research Council (ERC) under\n//| the European Union's Horizon 2020 research and innovation programme (grant\n//| agreement No 637972) - see http://www.resibots.eu\n//|\n//| Contributor(s):\n//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)\n//|   - Antoine Cully (antoinecully@gmail.com)\n//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)\n//|   - Federico Allocati (fede.allocati@gmail.com)\n//|   - Vaios Papaspyros (b.papaspyros@gmail.com)\n//|   - Roberto Rama (bertoski@gmail.com)\n//|\n//| This software is a computer library whose purpose is to optimize continuous,\n//| black-box functions. It mainly implements Gaussian processes and Bayesian\n//| optimization.\n//| Main repository: http://github.com/resibots/limbo\n//| Documentation: http://www.resibots.eu/limbo\n//|\n//| This software is governed by the CeCILL-C license under French law and\n//| abiding by the rules of distribution of free software.  You can  use,\n//| modify and/ or redistribute the software under the terms of the CeCILL-C\n//| license as circulated by CEA, CNRS and INRIA at the following URL\n//| \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and  rights to copy,\n//| modify and redistribute granted by the license, users are provided only\n//| with a limited warranty  and the software's author,  the holder of the\n//| economic rights,  and the successive licensors  have only  limited\n//| liability.\n//|\n//| In this respect, the user's attention is drawn to the risks associated\n//| with loading,  using,  modifying and/or developing or reproducing the\n//| software by the user in light of its specific status of free software,\n//| that may mean  that it is complicated to manipulate,  and  that  also\n//| therefore means  that it is reserved for developers  and  experienced\n//| professionals having in-depth computer knowledge. Users are therefore\n//| encouraged to load and test the software's suitability as regards their\n//| requirements in conditions enabling the security of their systems and/or\n//| data to be ensured and,  more generally, to use and operate it in the\n//| same conditions as regards security.\n//|\n//| The fact that you are presently reading this means that you have had\n//| knowledge of the CeCILL-C license and that you accept its terms.\n//|\n#define _USE_MATH_DEFINES\n#include <Eigen/Core>\n\n#ifdef BAYES_OPT\n#include <bayesopt/bayesopt.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <limbo/tools/macros.hpp>\n\nusing namespace bayesopt;\n\nusing vec_t = vectord;\nusing mat_t = matrixd;\n#define ASSIGNMENT_OP <<=\n#else\nusing vec_t = Eigen::VectorXd;\nusing mat_t = Eigen::MatrixXd;\n#define ASSIGNMENT_OP <<\n#endif\n\n// support functions\ninline double sign(double x)\n{\n    if (x < 0)\n        return -1;\n    if (x > 0)\n        return 1;\n    return 0;\n}\n\ninline double sqr(double x)\n{\n    return x * x;\n};\n\ninline double hat(double x)\n{\n    if (x != 0)\n        return std::log(std::abs(x));\n    return 0;\n}\n\ninline double c1(double x)\n{\n    if (x > 0)\n        return 10;\n    return 5.5;\n}\n\ninline double c2(double x)\n{\n    if (x > 0)\n        return 7.9;\n    return 3.1;\n}\n\ninline vec_t t_osz(const vec_t& x)\n{\n    vec_t r = x;\n    for (size_t i = 0; i < static_cast<size_t>(x.size()); i++)\n        r(i) = sign(x(i)) * std::exp(hat(x(i)) + 0.049 * std::sin(c1(x(i)) * hat(x(i))) + std::sin(c2(x(i)) * hat(x(i))));\n    return r;\n}\n\nstruct Sphere {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        vec_t opt(2);\n        opt ASSIGNMENT_OP 0.5, 0.5;\n\n#ifndef BAYES_OPT\n        return (x - opt).squaredNorm();\n#else\n        return sqr(norm_2(x - opt));\n#endif\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(1, 2);\n        sols ASSIGNMENT_OP 0.5, 0.5;\n        return sols;\n    }\n};\n\nstruct Ellipsoid {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        vec_t opt(2);\n        opt ASSIGNMENT_OP 0.5, 0.5;\n        vec_t z = t_osz(x - opt);\n        double r = 0;\n        for (size_t i = 0; i < dim_in(); ++i)\n            r += std::pow(10., ((double)i) / (dim_in() - 1.0)) * z(i) * z(i) + 1;\n        return r;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(1, 2);\n        sols ASSIGNMENT_OP 0.5, 0.5;\n        return sols;\n    }\n};\n\nstruct Rastrigin {\n    BO_PARAM(size_t, dim_in, 4);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& xx) const\n    {\n        vec_t x = xx;\n        for (size_t i = 0; i < static_cast<size_t>(x.size()); i++)\n            x(i) = 2. * xx(i) - 1.;\n        double f = 10. * dim_in();\n        for (size_t i = 0; i < dim_in(); ++i)\n            f += x(i) * x(i) - 10. * std::cos(2 * M_PI * x(i));\n        return f;\n    }\n\n    mat_t solutions() const\n    {\n#ifndef BAYES_OPT\n        mat_t sols = Eigen::MatrixXd::Zero(1, 4);\n#else\n        mat_t sols = boost::numeric::ublas::zero_matrix<double>(1, 4);\n#endif\n        for (size_t i = 0; i < 4; i++)\n            sols(0, i) = (sols(0, i) + 1.) / 2.;\n        return sols;\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/hart3.html\nstruct Hartmann3 {\n    BO_PARAM(size_t, dim_in, 3);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        mat_t a(4, 3);\n        mat_t p(4, 3);\n        a ASSIGNMENT_OP 3.0, 10., 30.,\n            0.1, 10., 35.,\n            3.0, 10., 30.,\n            0.1, 10., 35.;\n        p ASSIGNMENT_OP 0.3689, 0.1170, 0.2673,\n            0.4699, 0.4387, 0.7470,\n            0.1091, 0.8732, 0.5547,\n            0.0381, 0.5743, 0.8828;\n        vec_t alpha(4);\n        alpha ASSIGNMENT_OP 1.0, 1.2, 3.0, 3.2;\n\n        double res = 0.;\n        for (size_t i = 0; i < 4; i++) {\n            double s = 0.;\n            for (size_t j = 0; j < 3; j++) {\n                s += a(i, j) * sqr(x(j) - p(i, j));\n            }\n            res += alpha(i) * std::exp(-s);\n        }\n        return -res;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(1, 3);\n        sols ASSIGNMENT_OP 0.114614, 0.555649, 0.852547;\n        return sols;\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/hart6.html\nstruct Hartmann6 {\n    BO_PARAM(size_t, dim_in, 6);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        mat_t a(4, 6);\n        mat_t p(4, 6);\n        a ASSIGNMENT_OP 10., 3., 17., 3.5, 1.7, 8.,\n            0.05, 10., 17., 0.1, 8., 14.,\n            3., 3.5, 1.7, 10., 17., 8.,\n            17., 8., 0.05, 10., 0.1, 14.;\n        p ASSIGNMENT_OP 0.1312, 0.1696, 0.5569, 0.0124, 0.8283, 0.5886,\n            0.2329, 0.4135, 0.8307, 0.3736, 0.1004, 0.9991,\n            0.2348, 0.1451, 0.3522, 0.2883, 0.3047, 0.6650,\n            0.4047, 0.8828, 0.8732, 0.5743, 0.1091, 0.0381;\n\n        vec_t alpha(4);\n        alpha ASSIGNMENT_OP 1.0, 1.2, 3.0, 3.2;\n\n        double res = 0.;\n        for (size_t i = 0; i < 4; i++) {\n            double s = 0.;\n            for (size_t j = 0; j < 6; j++) {\n                s += a(i, j) * sqr(x(j) - p(i, j));\n            }\n            res += alpha(i) * std::exp(-s);\n        }\n        return -res;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(1, 6);\n        sols ASSIGNMENT_OP 0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573;\n        return sols;\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/goldpr.html\n// (with ln, as suggested in Jones et al.)\nstruct GoldsteinPrice {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& xx) const\n    {\n        vec_t x = xx;\n        for (size_t i = 0; i < static_cast<size_t>(x.size()); i++)\n            x(i) = 4. * xx(i) - 2.;\n\n        double fact1a = sqr(x(0) + x(1) + 1.);\n        double fact1b = 19. - 14. * x(0) + 3. * sqr(x(0)) - 14. * x(1) + 6. * x(0) * x(1) + 3. * sqr(x(1));\n        double fact1 = 1. + fact1a * fact1b;\n\n        double fact2a = sqr(2. * x(0) - 3. * x(1));\n        double fact2b = 18. - 32. * x(0) + 12. * sqr(x(0)) + 48. * x(1) - 36. * x(0) * x(1) + 27. * sqr(x(1));\n        double fact2 = 30. + fact2a * fact2b;\n\n        double r = fact1 * fact2;\n\n        return (std::log(r) - 8.693) / 2.427;\n        // return std::log(r) - 5.;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(1, 2);\n        sols ASSIGNMENT_OP 0.5, 0.25;\n        return sols;\n    }\n};\n\nstruct BraninNormalized {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        double x1 = x(0) * 15 - 5;\n        double x2 = x(1) * 15;\n\n        double term1 = sqr(x2 - (5.1 * sqr(x1) / (4. * sqr(M_PI))) + 5. * x1 / M_PI - 6);\n        double term2 = (10. - 10. / (8. * M_PI)) * std::cos(x1);\n\n        return (term1 + term2 - 44.81) / 51.95;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(3, 2);\n        sols ASSIGNMENT_OP - M_PI, 12.275,\n            M_PI, 2.275,\n            9.42478, 2.475;\n\n        sols(0, 0) = (sols(0, 0) + 5.) / 15.;\n        sols(1, 0) = (sols(1, 0) + 5.) / 15.;\n        sols(2, 0) = (sols(2, 0) + 5.) / 15.;\n        sols(0, 1) = sols(0, 1) / 15.;\n        sols(1, 1) = sols(1, 1) / 15.;\n        sols(2, 1) = sols(2, 1) / 15.;\n        return sols;\n    }\n};\n\nstruct SixHumpCamel {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    double operator()(const vec_t& x) const\n    {\n        double x1 = -3 + 6 * x(0);\n        double x2 = -2 + 4 * x(1);\n        double x1_2 = sqr(x1);\n        double x2_2 = sqr(x2);\n\n        double tmp1 = (4 - 2.1 * x1_2 + sqr(x1_2) / 3.) * x1_2;\n        double tmp2 = x1 * x2;\n        double tmp3 = (-4 + 4 * x2_2) * x2_2;\n        return tmp1 + tmp2 + tmp3;\n    }\n\n    mat_t solutions() const\n    {\n        mat_t sols(2, 2);\n        sols ASSIGNMENT_OP 0.0898, -0.7126,\n            -0.0898, 0.7126;\n        sols(0, 0) = (sols(0, 0) + 3.) / 6.;\n        sols(1, 0) = (sols(1, 0) + 3.) / 6.;\n        sols(0, 1) = (sols(0, 1) + 2.) / 4.;\n        sols(1, 1) = (sols(1, 1) + 2.) / 4.;\n        return sols;\n    }\n};\n\n#ifndef BAYES_OPT\ntemplate <typename Function>\nclass Benchmark {\npublic:\n    BO_PARAM(size_t, dim_in, Function::dim_in());\n    BO_PARAM(size_t, dim_out, Function::dim_out());\n\n    vec_t operator()(const vec_t& x) const\n    {\n        vec_t res(1);\n        res(0) = -f(x);\n        return res;\n    }\n#else\ntemplate <typename Function>\nclass Benchmark : public bayesopt::ContinuousModel {\npublic:\n    Benchmark(bopt_params par) : ContinuousModel(Function::dim_in(), par) {}\n\n    double evaluateSample(const vec_t& xin)\n    {\n        return f(xin);\n    }\n\n    bool checkReachability(const vec_t& query)\n    {\n        return true;\n    };\n#endif\n\n    double accuracy(double x)\n    {\n        mat_t sols = f.solutions();\n#ifndef BAYES_OPT\n        double diff = std::abs(x + f(sols.row(0)));\n#else\n        double diff = std::abs(x - f(row(sols, 0)));\n#endif\n        double min_diff = diff;\n\n#ifndef BAYES_OPT\n        for (int i = 1; i < sols.rows(); i++) {\n            diff = std::abs(x + f(sols.row(i)));\n#else\n        for (size_t i = 1; i < sols.size1(); i++) {\n            diff = std::abs(x - f(row(sols, i)));\n#endif\n            if (diff < min_diff)\n                min_diff = diff;\n        }\n\n        return min_diff;\n    }\n\n    Function f;\n};\n", "meta": {"hexsha": "c1b3f5703fd542283cfe24bccff8a8eb2efa8854", "size": 11381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/benchmarks/limbo/testfunctions.hpp", "max_stars_repo_name": "yjjuan/automl_cplusplus", "max_stars_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T17:52:18.000Z", "max_issues_repo_path": "limbo/src/benchmarks/limbo/testfunctions.hpp", "max_issues_repo_name": "yjjuan/automl_cplusplus", "max_issues_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "limbo/src/benchmarks/limbo/testfunctions.hpp", "max_forks_repo_name": "yjjuan/automl_cplusplus", "max_forks_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_forks_repo_licenses": ["Apache-2.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.3581730769, "max_line_length": 122, "alphanum_fraction": 0.5476671646, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931190663057, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.58320645734766}}
{"text": "#include \"utils/math_utils.h\"\n#include \"math_helper_func.hpp\"\n#include \"utils/missing_values.hpp\"\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/special_functions/beta.hpp>\n//#include <opencv2/opencv.hpp>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#if 0\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#endif\n\nnamespace utils\n{\n\nnamespace\n{\n\ndouble calctinv(double p, double v);\ndouble tinv(double p, double v);\ndouble zcritical(double alpha, double n);\nstd::size_t calcualte_max(std::vector<double> range, double meanval);\ndouble find_outlier(std::vector<double>& input, double alpha);\n\ndouble calctinv(double p, double v)\n{\n    //For large d.f., use Abramowitz & Stegun formula 26.7.5\n    double xn=boost::math::detail::find_inverse_s(p, (1 - p));\n    double df = v;\n    double xn3 = std::pow(xn, 3);\n    double xn5 = std::pow(xn, 5);\n    double xn7 = std::pow(xn, 7);\n    double xn9 = std::pow(xn, 9);\n\n\n    double x = xn + (xn3+xn)/(4*df) + \n        (5*xn5 + 16*xn3 + 3*xn)/(96*df*df) +\n        (3*xn7 + 19*xn5 + 17*xn3 - 15*xn)/(384*df*df*df) +\n        (79*xn9 + 776*xn7 + 1482*xn5 - 1920*xn3 - 945*xn)/(92160*df*df*df*df);\n    return x;\n}\n\ndouble tinv(double p, double v)\n{\n    using boost::math::beta_distribution;\n    using boost::math::sign;\n    //   TINV   Inverse of Student's T cumulative distribution function (cdf).\n    //   X=TINV(P,V) returns the inverse of Student's T cdf with V degrees\n    //   of freedom, at the values in P.\n    //   References:\n    //      [1]  M. Abramowitz and I. A. Stegun, \"Handbook of Mathematical\n    //      Functions\", Government Printing Office, 1964, 26.6.2\n\n    //   Copyright 1993-2014 The MathWorks, Inc.\n    double x = 0;\n    bool k0 = (0 < p && p < 1) && (v > 0);\n\n    // Invert the Cauchy distribution explicitly\n    int k = (k0 && (v == 1));\n    if (k) {\n        x = tan(M_PI * (p - 0.5));\n    }\n\n    // For small d.f., call betaincinv which uses Newton's method\n    k = (k0 && (v < 1000) && (v != 1));\n    if (k) {\n        double q = p - .5;\n        double df = v;\n        int t = (std::abs(q) < .25);\n        double z = 0;\n        double oneminusz=0;\n\n        if (t) {\n            // for z close to 1, compute 1-z directly to avoid roundoff\n            beta_distribution<> m1(0.5, df/2);\n            oneminusz = quantile(m1, 2.0 * std::abs(q));\n            z = 1 - oneminusz;\n\n        } else {\n            beta_distribution<> m(df/2, 0.5);\n            z = quantile(m, 1 - 2.0 * std::abs(q));\n            oneminusz = 1 - z;\n        }\n        if (z == 0.0) {\n            return z;   // an error\n        }\n        x = sign(q) * sqrt(df * (oneminusz/z));\n    }\n\n    // For large d.f., use Abramowitz & Stegun formula 26.7.5\n    k = (k0 && (v >= 1000));\n    if (k) {\n        x= calctinv( p, v );\n    }\n    return x;\n}\n\n\ndouble zcritical(double alpha, double n)\n{\n    //Computes the critical z value for rejecting outliers (GRUBBS TEST)\n    double tcrit = tinv(alpha/(2*n), n-2);\n    if (tcrit == 0.0) {\n        return 0.0;     // we have an issue with the value - make it an outlier\n    }\n    double zcrit = (n - 1)/sqrt(n) * (sqrt(tcrit * tcrit/(n-2 + tcrit * tcrit)));\n    return zcrit;\n}\n\nstd::size_t calcualte_max(std::vector<double> range, double meanval)\n{\n    std::transform(std::begin(range), std::end(range), std::begin(range),\n            [meanval](double val) {\n                val -= meanval;\n                return std::abs(val);\n            }\n        );\n    auto i =  std::max_element(std::begin(range), std::end(range));\n    return std::distance(std::begin(range), i);\n}\n\ndouble find_outlier(std::vector<double>& input, double alpha)\n{\n    if (input.empty()) {\n        return missing_value<double>();\n    }\n    auto mean_std = mean_standard_dev<double>(std::begin(input), std::end(input), input.size());\n    if (mean_std.standard_dev == 0.0) { // all values are the same, there are no outliers for sure..\n        return missing_value<double>();\n    }\n    auto max_index = calcualte_max(input, mean_std.mean);\n    auto maxval = input[max_index];\n    auto tn = std::abs((maxval - mean_std.mean)/mean_std.standard_dev);\n    auto critical = zcritical(alpha, input.size());\n    if (tn > critical) {\n        input.erase(std::begin(input) + max_index);\n        return maxval;\n    }\n    return missing_value<double>();\n}\n\n}   // end of local namespace\n\ndouble round_by(double from, unsigned int presition)\n{\n    static const double factors[] = {\n        std::pow(10, 0),\n        std::pow(10, 1),\n        std::pow(10, 2),\n        std::pow(10, 3),\n        std::pow(10, 4),\n        std::pow(10, 5),\n        std::pow(10, 6),\n        std::pow(10, 7),\n        std::pow(10, 8),\n        std::pow(10, 9),\n        std::pow(10, 10),\n        std::pow(10, 11),\n        std::pow(10, 12),\n        std::pow(10, 13),\n        std::pow(10, 14),\n        std::pow(10, 15),\n        std::pow(10, 16),\n        std::pow(10, 17),\n        std::pow(10, 18),\n        std::pow(10, 19),\n        std::pow(10, 20),\n        std::pow(10, 21),\n        std::pow(10, 22),\n        std::pow(10, 23)\n    };\n    static const std::size_t SIZE = sizeof (factors)/sizeof(factors[0]);\n\n    if (presition == SIZE) {\n        return from;\n    }\n\n    from *= factors[presition];\n    from = std::floor(from + 0.5);\n    from /= factors[presition];\n    return from;\n}\n//typical alpha =0.05;0.025\nstd::vector<double>\ngrubbstest(std::vector<double> input, double alpha)\n{\n    using value_type = double;\n    using result_type = std::vector<value_type>;\n\n    auto i = std::remove_if(std::begin(input),\n            std::end(input), [](auto d) { return std::isinf(d); }\n        );\n    input.erase(i, std::end(input));\n    result_type result; \n    auto outlier = find_outlier(input, alpha);\n    while (!missing_value(outlier)) {\n        result.push_back(outlier);\n        outlier = find_outlier(input, alpha);\n    }\n                \n    return result;\n    \n}\n}   // end of namespace utils\n\n", "meta": {"hexsha": "d39a08b9100cb41ae7013d1a9d2560d0c1bf701b", "size": 5988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/utils/src/math_utils.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/utils/src/math_utils.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/utils/src/math_utils.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5142857143, "max_line_length": 100, "alphanum_fraction": 0.5651302605, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5831152733087693}}
{"text": "/*\n * \n */\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <sophus/se3.h>\n#include <sophus/so3.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\t// opencv自带的与eigen类型转换api\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/imgcodecs.hpp>\n// #include <opencv2/highgui/highgui.hpp>\n// #include <opencv2/viz.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <g2o/core/block_solver.h>\n// #include <g2o/core/robust_kernel.h>\n// #include <g2o/core/robust_kernel_impl.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n\n#include \"pinhole_camera.h\"\n#include \"frame.h\"\n#include \"detect_features.h\"\n#include \"align_image.h\"\n#include \"param_reader.h\"\n#include \"g2o_types_costom.h\"\n#include \"map_point.h\"\n#include \"map.h\"\n\nusing namespace std;\n\nAlignImage::AlignImage(PinHoleCamera::Ptr cam, ParameterReader:: Ptr param_reader)\n{\n\tcam_ = cam;\n\tmatcher_name_ = param_reader->getParam<string>(\"matcher_name\");\n\tgood_match_threshold_ = param_reader->getParam<double>(\"good_match_threshold\");\n\tis_show_ = param_reader->getParam<bool>(\"is_show_feature_match\");\n\tmin_good_matches_ = param_reader->getParam<int>(\"min_good_matches\");\n\tmin_inliers_ = param_reader->getParam<int>(\"min_inliers\");\n\tmax_norm_ = param_reader->getParam<double>(\"max_norm\");\n\t\n// \tT_ = Eigen::Isometry3d::Identity();\n\t\n\t// 根据名字动态构建相应的匹配器\n\tif (matcher_name_ == \"FLANN\"){\n\t\tmatcher_ = cv::makePtr<cv::FlannBasedMatcher>(new cv::flann::LshIndexParams ( 5,10,2 ));\n\t}\n\telse if(matcher_name_ == \"BF\") {\n\t\tmatcher_ = cv::BFMatcher::create();\n\t}\n\telse {\n\t\tcout << \"invalid matcher name\" << endl;\n\t}\n}\n\nAlignImage::~AlignImage()\n{\n}\n\n\n// 求解PnP,求解出两帧图像之间的位姿变换关系\nvoid AlignImage:: alignTwoFrames(Frame::Ptr ref_frame, Frame::Ptr curr_frame)\n{\n\tis_good_align_ = true;\n\t\n\t// 清空之前的匹配数据,防止不同帧对之间的数据累积\n\tmatches_.clear();\n\tgood_matches_.clear();\n\t\n\t// 匹配两帧的描述子\n\tmatcher_->match(ref_frame->descrip_, curr_frame->descrip_, matches_);\n\tcout << \"find total \" << matches_.size() << \" matches\" << endl;\n\t\n\t// 根据距离,筛选好的匹配\n\t// 寻找最小距离\n\tdouble min_dist = 9999;\n\tfor (cv::DMatch  m : matches_) {\n\t\tif (m.distance < min_dist)\n\t\t\tmin_dist = m.distance;\n\t}\n\tcout << \"min_dist: \" << min_dist << endl;\n\t\n\t// 筛选\n\tif (min_dist < 10 ) min_dist = 10;\t\t// 防止因为min_dist等于0而找不到good_match的情况\n\tfor (cv::DMatch  m : matches_) {\n\t\tif (m.distance < good_match_threshold_ * min_dist)\n\t\t\tgood_matches_.push_back(m);\n\t}\n\tcout << \"good matches: \" << good_matches_.size() << endl;\n\tif (good_matches_.size() < min_good_matches_) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\tif (is_show_) {\n\t\tcv::Mat imgMatches;\n\t\tcv::drawMatches(ref_frame->rgb_img_, ref_frame->keypoints_, curr_frame->rgb_img_ , curr_frame->keypoints_, good_matches_, imgMatches);\n\t\tcv::imshow(\"good matches\", imgMatches);\n\t\tcv::waitKey(0);\n\t}\n\t\n\t// 第一帧中的三维点\n\tvector<cv::Point3f> points_obj;\n\t// 第二帧中的图像点\n\tvector<cv::Point2f> points_img;\n\t\n\t// 获得对应的三维点和像素点坐标\n\tfor (cv::DMatch m : good_matches_) {\n\t\t// 获取第一帧图像中点的像素坐标和深度\n\t\tcv::Point2f p = ref_frame->keypoints_[m.queryIdx].pt;\n\t\tushort d = ref_frame->depth_img_.ptr<ushort>(int(p.y))[int(p.x)];\n\t\tif (d == 0) continue;\n\t\t\n\t\t// 得到第一帧图像中空间点坐标\n\t\tEigen::Vector3d pt_temp = cam_->pixel2camera(Eigen::Vector2d(p.x, p.y), (double)d);\n\t\tcv::Point3f pt_obj( pt_temp(0,0), pt_temp(1,0), pt_temp(2,0) );\n\t\tpoints_obj.push_back(pt_obj);\n\t\t\n\t\t// 得到与之对应的第二帧图像中像素点坐标\n\t\tcv::Point2f pt_img = curr_frame->keypoints_[m.trainIdx].pt;\n\t\tpoints_img.push_back(pt_img);\n\t}\n\t\n\t// 检查有效的目标点的数量,小于4则会引发opencv异常,需要放弃该帧\n\tif (points_obj.size() < 4) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\t// 求解PnP问题,同时使用RANSAC去除outlier\n\tcv::Mat intrisic_matrix = cv::Mat_<double>::ones(3, 3);\n\tcv::Mat rvec, tvec, inliers;\n\tcv::eigen2cv(cam_->K(), intrisic_matrix);\n\t// solvePnPRansac函数输出的是三维点坐标系(模型坐标系)到二维点坐标系(相机坐标系)的变换关系\n\t// 在这里,就是fram1坐标系中的点左乘得到的变换关系,可以变换到curr_frame坐标系中\n\tcv::solvePnPRansac(points_obj, points_img, intrisic_matrix, cv::Mat(), rvec, tvec, false, 100, 1.0, 0.99, inliers);\n\tcout<<\"inliers: \"<<inliers.rows<<endl;\n\tcout<<\"rvec=\"<<rvec<<endl;\n\tcout<<\"tvec=\"<<tvec<<endl;\n\tif (inliers.rows < min_inliers_ || normOfTransform(rvec, tvec) > max_norm_){\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\tif (is_show_) {\n\t\t// 画出inliers匹配 \n\t\tvector< cv::DMatch > matchesShow;\n\t\tcv::Mat imgMatches;\n\t\tfor (size_t i=0; i<inliers.rows; i++) {\n\t\t\tmatchesShow.push_back( good_matches_[inliers.ptr<int>(i)[0]] );    \n\t\t}\n\t\tcv::drawMatches(ref_frame->rgb_img_, ref_frame->keypoints_, curr_frame->rgb_img_, curr_frame->keypoints_, matchesShow, imgMatches);\n\t\tcv::imshow( \"inlier matches\", imgMatches );\n\t\tcv::waitKey( 0 );\n\t}\n\t\n\toptimizePoseOfPnp(points_obj, points_img, inliers, rvec, tvec);\n\t\n\t// 计算当前帧到世界坐标的变换\n\t/******************************************************************\n\t * 注意,这个地方之所以是右乘 T_r2c_ 的逆,是因为从当前帧坐标系变到世界坐标系的\n\t * 过程等价于先变到前一帧的坐标系,再变到前前帧的坐标系,以此类推,用公式表示\n\t * 就是Pw=Tw1^-1 * T12^-1 * T23^-1 * ...* Tn-1n^-1 * Pn,因此相应的变换矩阵就是\n\t * 从第一帧到世界坐标系的变换开始不断的右乘参考帧到当前帧变换的逆\n\t ******************************************************************/\n\tcurr_frame->T_c2w_ = ref_frame->T_c2w_ * T_r2c_.inverse();\n\t\n\treturn;\n}\n\n\n/**\n * @brief ...\n * \n * @param local_map ...\n * @param curr_frame ...\n * @param ref_frame 只用于显示,调试时看图\n * @return void\n */\nvoid AlignImage::alignMapFrame(Map::Ptr local_map, Frame::Ptr curr_frame, Frame::Ptr ref_frame)\n{\n\tis_good_align_ = true;\n\t\n\t// 清空之前的匹配数据,防止数据累积\n\tmatches_.clear();\n\tgood_matches_.clear();\n\tmatch_2dkp_index_.clear();\n\t\n\t// 根据假设的当前帧位姿,对地图点进行投影,筛选可能会出现在当前帧中的地图点作为匹配候选点\n\tvector<MapPoint::Ptr> candidate_map_points;\n\tcv::Mat map_descriptor;\n\tfor ( auto point_pair : local_map->map_points_ ) {\n\t\tMapPoint::Ptr& point = point_pair.second;\n\t\tif (curr_frame->isInFrame(point->pose_)) {\n\t\t\t// 如果地图点可能出现在当前帧中,则将其作为候选\n\t\t\tcandidate_map_points.push_back(point);\n\t\t\tmap_descriptor.push_back(point->descriptor_);\n\t\t}\n\t}\n\tcout << \"candidate_map_points: \" << candidate_map_points.size() << endl;\n\t\n\t// 匹配候选的地图点和当前帧的特征点\n\tmatcher_->match(map_descriptor, curr_frame->descrip_, matches_);\n\tcout << \"find total \" << matches_.size() << \" matches\" << endl;\n\t\n\t// 根据距离,筛选好的匹配\n\t// 寻找最小距离\n\tdouble min_dist = 9999;\n\tfor (cv::DMatch  m : matches_) {\n\t\tif (m.distance < min_dist)\n\t\t\tmin_dist = m.distance;\n\t}\n\tcout << \"min_dist: \" << min_dist << endl;\n\t\n\t// 筛选\n\tif (min_dist < 10.0 ) min_dist = 10.0;\t\t// 防止因为min_dist等于0而找不到good_match的情况\n\tfor (cv::DMatch  m : matches_) {\n\t\tif (m.distance < good_match_threshold_ * min_dist) {\n\t\t\tgood_matches_.push_back(m);\n\t\t\tmatch_2dkp_index_.push_back( m.trainIdx );\n\t\t}\n\t}\n\tcout << \"good matches: \" << good_matches_.size() << endl;\n\tif (good_matches_.size() < min_good_matches_) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\tif (is_show_) {\n\t\tcv::Mat img_show = ref_frame->rgb_img_.clone();\n\t\tfor ( auto& pt : candidate_map_points ) {\n\t\t\tEigen::Vector2d pixel = ref_frame->cam_->world2pixel ( pt->pose_, ref_frame->T_c2w_.inverse() );\n\t\t\tcv::circle ( img_show, cv::Point2f ( pixel ( 0,0 ),pixel ( 1,0 ) ), 5, cv::Scalar ( 0,255,0 ), 2 );\n\t\t}\n\t\tcv::imshow(\"candidate\", img_show);\n\t\tcv::waitKey(0);\n\t}\n\t\n\tvector<cv::Point3f> points_world;\n\tvector<cv::Point2f> points_img;\n\t\n\t// 获得对应的三维点和像素点坐标\n\tfor (cv::DMatch m : good_matches_) {\n\t\t// 3D点\n\t\tcv::Point3f pt_world = (candidate_map_points[m.queryIdx])->getPositionCV();\n\t\tpoints_world.push_back(pt_world);\n\t\t// 得到与之对应的第二帧图像中像素点坐标\n\t\tcv::Point2f pt_img = curr_frame->keypoints_[m.trainIdx].pt;\n\t\tpoints_img.push_back(pt_img);\n\t}\n\t\n\t// 检查有效的目标点的数量,小于4则会引发opencv异常,需要放弃该帧\n\tif (points_world.size() < 4) {\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\t// 求解PnP问题,同时使用RANSAC去除outlier\n\tcv::Mat intrisic_matrix = cv::Mat_<double>::ones(3, 3);\n\tcv::Mat rvec, tvec, inliers;\n\tcv::eigen2cv(cam_->K(), intrisic_matrix);\n\t// solvePnPRansac函数输出的是三维点坐标系(模型坐标系)到二维点坐标系(相机坐标系)的变换关系\n\t// 在这里,就是世界坐标系中的点左乘得到的变换关系,可以变换到curr_frame坐标系中\n\tcv::solvePnPRansac(points_world, points_img, intrisic_matrix, cv::Mat(), rvec, tvec, false, 100, 1.0, 0.99, inliers);\n\tcout<<\"inliers: \"<<inliers.rows<<endl;\n\t// cout<<\"rvec=\"<<rvec<<endl;\n\t// cout<<\"tvec=\"<<tvec<<endl;\n\tinliers_num_ = inliers.rows;\n\tif (inliers.rows < min_inliers_){\n\t\tis_good_align_ = false;\n\t\treturn;\n\t}\n\t\n\tif (is_show_) {\n\t\t// TODO\n\t}\n\t\n\toptimizePoseOfPnp(points_world, points_img, inliers, rvec, tvec);\n\t\n\t// 计算当前帧到世界坐标的变换\n\t/*\n\t * 因为此时T_r2c_表示的是世界到帧的变换\n\t */\n\tcurr_frame->T_c2w_ = T_r2c_.inverse();\n\t\n\t// 根据求得的当前帧的准确位姿,对地图点的相关变量进行更新\n\tfor ( auto point_pair : local_map->map_points_ ) {\n\t\tMapPoint::Ptr& point = point_pair.second;\n\t\tif (curr_frame->isInFrame(point->pose_)) {\n\t\t\tpoint->observed_times_++;\n\t\t}\n\t}\n\tfor (int i = 0; i < inliers.rows; i++) {\n\t\tint index = inliers.at<int>(i,0);\t\n\t\t// 符合几何关系的地图点,其被匹配的次数加1\n\t\tcandidate_map_points[index]->matched_times_++;\n\t}\n\t\n\treturn;\n}\n\ndouble AlignImage::normOfTransform(cv::Mat rvec, cv::Mat tvec)\n{\n\treturn fabs(min(cv::norm(rvec), 2*M_PI-cv::norm(rvec)))+ fabs(cv::norm(tvec));\n}\n\nvoid AlignImage::optimizePoseOfPnp(vector<cv::Point3f>& points_obj,  vector<cv::Point2f>& points_img, cv::Mat inliers,  cv::Mat& rvec,  cv::Mat& tvec)\n{\n\t// 使用g2o对求解出来的变换关系进行优化\n\ttypedef g2o::BlockSolver<g2o::BlockSolverTraits< Eigen::Dynamic, Eigen::Dynamic >> MyBlockSolver;\n\ttypedef g2o::LinearSolverDense<MyBlockSolver::PoseMatrixType> MyLinerSolver;\n\tg2o::OptimizationAlgorithmLevenberg *opt_alg = new g2o::OptimizationAlgorithmLevenberg(\n\t\t\t\t\t\t\t\t\t\t\t\t\tg2o::make_unique<MyBlockSolver>(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tg2o::make_unique<MyLinerSolver>() ) );\n\tg2o::SparseOptimizer optimizer;\n\toptimizer.setAlgorithm(opt_alg);\n\t\n\t// 使用PnP输出构建待优化的SE3变量\n\tSophus::SE3 T_r2c_no_opt(\n\t\tSophus::SO3(rvec.at<double>(0,0), rvec.at<double>(1,0), rvec.at<double>(2,0)),\n\t\tEigen::Vector3d(tvec.at<double>(0,0), tvec.at<double>(1,0), tvec.at<double>(2,0)) );\n\t// cout << \"优化前的T_r2c_:\" << endl <<  T_r2c_no_opt.matrix() << endl;\n\t\n\t// 添加待优化节点\n\tg2o::VertexSE3Expmap *pose = new g2o::VertexSE3Expmap;\n\tpose->setId(0);\n\tpose->setEstimate( g2o::SE3Quat( T_r2c_no_opt.rotation_matrix(), T_r2c_no_opt.translation() ) );\n\toptimizer.addVertex( pose );\n\t// 添加边,每一条边表示一次三维点到图像点的投影测量,能计算到一个误差\n\tfor (int i = 0; i < inliers.rows; i++) {\n\t\tint index = inliers.at<int>(i,0);\t// 第i个内点在原来的点列表中的索引\n\t\tEdgeProjectXYZ2UVUPoseOnly *edge = new EdgeProjectXYZ2UVUPoseOnly;\n\t\tedge->setId(i);\n\t\tedge->setVertex(0, pose);\n\t\tedge->cam_ = cam_;\n\t\tedge->point_ = Eigen::Vector3d(points_obj[index].x, points_obj[index].y, points_obj[index].z);\n\t\tedge->setMeasurement(Eigen::Vector2d(points_img[index].x, points_img[index].y));\n\t\tedge->setInformation(Eigen::Matrix2d::Identity());\t// 信息矩阵是协方差矩阵的逆,表示的是对误差向量中不同分量的重视程度(权重),最简单的即设置为单位阵\n\t\toptimizer.addEdge( edge );\n\t}\n\t// 启动优化\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(10);\n\t\n\t// 转存优化后的变量\n\tT_r2c_ = Sophus::SE3( pose->estimate().rotation(),  pose->estimate().translation() );\n// \tR_ = T_r2c_.rotation_matrix();\n// \tt_ = T_r2c_.translation();\n// \tT_.rotate ( Eigen::AngleAxisd(R_) ); \t\t// 构造Eigen变换关系\n// \tT_.pretranslate (t_ );\n\tcout << \"优化后的T_r2c_:\" << endl <<  T_r2c_.matrix() << endl;\n\t\n\treturn;\n}\n\n\n\n", "meta": {"hexsha": "99e49042d7792739960196224993b2bdfca56738", "size": 11150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/align_image.cpp", "max_stars_repo_name": "YangQun1/Slamkit", "max_stars_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-18T08:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-18T16:32:06.000Z", "max_issues_repo_path": "src/align_image.cpp", "max_issues_repo_name": "YangQun1/Slamkit", "max_issues_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/align_image.cpp", "max_forks_repo_name": "YangQun1/Slamkit", "max_forks_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3814713896, "max_line_length": 150, "alphanum_fraction": 0.6917488789, "num_tokens": 4347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5831128789132127}}
{"text": "\n\n#ifndef INCLUDES_HPP_\n#define INCLUDES_HPP_\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <map>\n#include <list>\n#include <vector>\n#include <stdlib.h>\n#include <algorithm>\n#include <inttypes.h>\n#include <parallel/algorithm>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <cmath>\n#include <math.h>\n#include <cstdlib>\n#include <stdio.h>\n#include <list>\n#include <ctime>\n#include <time.h>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <inttypes.h>\n#include <iomanip>\n#include <locale>\n\n\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <chrono>\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/mat.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/highgui/highgui_c.h>\n#include <opencv2/ximgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <sys/stat.h>\n#include <sys/time.h>\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n#include <chrono>\n\n#include <Eigen/Dense>\n\n\n#include <opencv2/core.hpp>\n#include <opencv2/imgproc.hpp>\n#include \"opencv2/imgcodecs.hpp\"\n#include <opencv2/highgui.hpp>\n\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\ntypedef uint64_t int_type_t;\ntypedef uint16_t uint_dist_type;\ntypedef uint16_t offset_int_type_t;\n\ntemplate<class T>\nT FromString(const std::string& s)\n{\n\tstd::istringstream stream (s);\n\tT t;\n\tstream >> t;\n\treturn t;\n}\n\ntemplate<class T>\nstring ToString(T arg)\n{\n\tstd::ostringstream s;\n\n\ts << arg;\n\n\treturn s.str();\n\n}\n\nenum DISTANCE {L1, L2, L2_approx, L_g, L2_induction };\n\n\ninline void MultiplyMatrixVector(const vector< vector<double> >& M, int rows, int cols, const vector<double>& v, vector<double>& X){\n\n\tint c;\n\t// don't test to save time\n\tfor (int r = 0; r < rows; r++){\n\t\tX[r] = 0;\n\n\t\tfor (c = 0; c < cols; c++){\n\t\t\tX[r] += M[r][c]*v[c];\n\n\t\t}\n\t}\n\n\n}\n\ninline void MultiplySquareMatrixMatrix(const vector< vector<double> >& M0, const vector< vector<double> >& M1,\n\t\tint rows, vector< vector<double> >& R){\n\n\tint c;\n\t//double r;\n\t// don't test to save time\n\tfor (int r = 0; r < rows; r++){\n\n\n\t\tfor (c = 0; c < rows; c++){\n\t\t\t// row r in M0 * col c in M1.\n\t\t\tR[r][c] = 0;\n\n\t\t\tfor (int inc = 0; inc < rows; inc++){\n\t\t\t\tR[r][c] += M0[r][inc]*M1[inc][c];\n\t\t\t}\n\n\n\t\t}\n\t}\n\n\n}\n\ninline void MultiplyMatricesWithSizes(const vector< vector<double> >& M0, const vector< vector<double> >& M1,\n\t\tint rowsA, int colsA, int colsB, vector< vector<double> >& R){\n\n\tint c;\n\t//double r;\n\t// don't test to save time\n\tfor (int r = 0; r < rowsA; r++){\n\n\n\t\tfor (c = 0; c < colsB; c++){\n\t\t\t// row r in M0 * col c in M1.\n\t\t\tR[r][c] = 0;\n\n\t\t\tfor (int inc = 0; inc < colsA; inc++){\n\t\t\t\tR[r][c] += M0[r][inc]*M1[inc][c];\n\t\t\t}\n\n\n\t\t}\n\t}\n}\n\n\ninline void SubtractVectorFromVector(const vector<double>& A, const vector<double>& B, vector<double>& C, int rows){\n\tfor (int r = 0; r < rows; r++){\n\t\tC[r] = A[r] - B[r];\n\t}\n}\n\ninline void AddVectorToVector(const vector<double>& A, const vector<double>& B, vector<double>& C, int rows){\n\tfor (int r = 0; r < rows; r++){\n\t\tC[r] = A[r] + B[r];\n\t}\n}\n\ninline void AddMatrixToMatrix(const vector<vector< double> >& A, const vector<vector<double> >& B, vector<vector<double> >& C, int rows, int cols){\n\tfor (int r = 0; r < rows; r++){\n\t\tfor (int c = 0; c < cols; c++){\n\t\t\tC[r][c] = A[r][c] + B[r][c];\n\t\t}\n\t}\n}\n\ninline void MultiplyVectorByScalar(const vector<double>& A, const double scalar, vector<double>& B, int rows){\n\tfor (int r = 0; r < rows; r++){\n\t\tB[r] = scalar*A[r];\n\t}\n\n}\n\ninline double SquaredDistance(const vector<double>& A, const vector<double>& B, int rows){\n\tdouble d = 0;\n\tfor (int r = 0; r < rows; r++){\n\t\td += (A[r] - B[r])*(A[r] - B[r]);\n\t}\n\treturn d;\n}\n\nvoid PrintMatrix(vector< vector<double> >& p);\n\n\n\ninline bool ProjectPointAndReturnIndex(const vector< vector<double> >& P,\n\t\tvector<double>& X, vector<double>& x, int rows, int cols, int_type_t& pixel_index){\n\n\tbool in = false;\n\tint r, c;\n\tMultiplyMatrixVector(P, 3, 4, X, x);\n\n\n\tx[0] /= x[2];  /// c\n\tx[1] /= x[2];  /// r\n\tx[2] = 1;\n\n\n\tc = round(x[0]);\n\tr = round(x[1]);\n\n\tif (c >= 0 && c < cols && r >= 0 && r < rows){\n\t\tin = true;\n\t\tpixel_index = round(x[1])*cols + round(x[0]);\n\t}\telse {\n\t\tpixel_index = 0;\n\t}\n\n\treturn in;\n}\n\ninline void NormalizePlane(vector<double>& p){\n\n\tdouble mag = sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);\n\n\tfor (int i = 0; i < 4; i++){\n\t\tp[i] /= mag;\n\t}\n}\n\ninline void NormalizeVector(vector<double>& p){\n\n\tdouble mag = sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);\n\n\tif (fabs(mag) > 0.00000001){\n\tfor (int i = 0; i < 3; i++){\n\t\tp[i] /= mag;\n\t}\n\t}\n}\n\ninline double MagnitudeVector(vector<double>& p){\n\tdouble mag = sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);\n\treturn mag;\n}\n\ninline double DotProduct(const vector<double>& a, const vector<double>& b, int size){\n\n\tdouble r = 0;\n\n\tfor (int i = 0; i < size; i++){\n\t\tr += a[i]*b[i];\n\t}\n\treturn r;\n}\n\ninline void CrossProduct(const vector<double>& a, const vector<double>& b, vector<double>& c){\n\n\tc[0] = a[1]*b[2] - b[1]*a[2];\n\tc[1] = -a[0]*b[2] + b[0]*a[2];\n\tc[2] = a[0]*b[1] - b[0]*a[1];\n\n}\n\ninline void RayPlaneIntersection(const vector<double>& C, const vector<double>& V, const vector<double>& P, vector<double>& X ){\n\n\tdouble dp0 = DotProduct(C, P, 4);\n\tdouble dp1 = DotProduct(V, P, 4);\n\n\tif (dp1 != 0){\n\t\tdouble lambda = -dp0/dp1;\n\n\t\tX[0] = C[0] + lambda*V[0];\n\t\tX[1] = C[1] + lambda*V[1];\n\t\tX[2] = C[2] + lambda*V[2];\n\n\t}\telse {\n\n\t\tX[0] = C[0];\n\t\tX[1] = C[1];\n\t\tX[2] = C[2];\n\t\tcout << \"Slight error -- cannot find appropriate lambda b/c dot product is zero: \" << endl;\n\t\tcout << \"top \" << dp0 << \"   bottom \" << dp1 << endl;\n\t}\n}\n\ninline bool RayPlaneIntersectionBool(const vector<double>& C, const vector<double>& V, const vector<double>& P, vector<double>& X ){\n\n\tdouble dp0 = DotProduct(C, P, 4);\n\tdouble dp1 = DotProduct(V, P, 4);\n\n\tif (dp1 != 0){\n\t\tdouble lambda = -dp0/dp1;\n\n\t\tX[0] = C[0] + lambda*V[0];\n\t\tX[1] = C[1] + lambda*V[1];\n\t\tX[2] = C[2] + lambda*V[2];\n\n\t\tif (lambda < 0){\n\t\t\treturn false;\n\t\t}\telse {\n\t\t\treturn true;\n\t\t}\n\t}\telse {\n\n\t\tX[0] = C[0];\n\t\tX[1] = C[1];\n\t\tX[2] = C[2];\n\t\tcout << \"Slight error -- cannot find appropriate lambda b/c dot product is zero: \" << endl;\n\t\tcout << \"top \" << dp0 << \"   bottom \" << dp1 << endl;\n\n\t\treturn false;\n\t}\n}\n\n\n\n\n#endif /* INCLUDES_HPP_ */\n", "meta": {"hexsha": "1a62d81e04df530517cbc88ca00ca81e11625d8a", "size": 6342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "level-set-segmentation/src/Includes.hpp", "max_stars_repo_name": "oooohhhright/tabb-level-set-segmentation", "max_stars_repo_head_hexsha": "273a897a1c3443869380a5ce27a2014341b5ee58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-07-26T19:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T23:21:07.000Z", "max_issues_repo_path": "level-set-segmentation/src/Includes.hpp", "max_issues_repo_name": "oooohhhright/tabb-level-set-segmentation", "max_issues_repo_head_hexsha": "273a897a1c3443869380a5ce27a2014341b5ee58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "level-set-segmentation/src/Includes.hpp", "max_forks_repo_name": "oooohhhright/tabb-level-set-segmentation", "max_forks_repo_head_hexsha": "273a897a1c3443869380a5ce27a2014341b5ee58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T14:25:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T06:32:02.000Z", "avg_line_length": 19.6346749226, "max_line_length": 147, "alphanum_fraction": 0.6040681173, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5831128735139292}}
{"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.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 _Lf, _dt, _ref_cte, _ref_epsi, _ref_vel; \n        double  _w_cte, _w_epsi, _w_vel, _w_delta, _w_accel, _w_delta_d, _w_accel_d;\n        int _mpc_steps, _x_start, _y_start, _psi_start, _v_start, _cte_start, _epsi_start, _delta_start, _a_start;\n\n        // Constructor\n        FG_eval(Eigen::VectorXd coeffs) \n        { \n            this->coeffs = coeffs; \n\n            // Set default value    \n            _Lf = 0.25; // distance between the front of the vehicle and its center of gravity\n            _dt = 0.1;  // in sec\n            _ref_cte   = 0;\n            _ref_epsi  = 0;\n            _ref_vel   = 1.0; // m/s\n            _w_cte     = 100;\n            _w_epsi    = 100;\n            _w_vel     = 100;\n            _w_delta   = 100;\n            _w_accel   = 50;\n            _w_delta_d = 0;\n            _w_accel_d = 0;\n\n            _mpc_steps   = 40;\n            _x_start     = 0;\n            _y_start     = _x_start + _mpc_steps;\n            _psi_start   = _y_start + _mpc_steps;\n            _v_start     = _psi_start + _mpc_steps;\n            _cte_start   = _v_start + _mpc_steps;\n            _epsi_start  = _cte_start + _mpc_steps;\n            _delta_start = _epsi_start + _mpc_steps;\n            _a_start     = _delta_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            _Lf = params.find(\"LF\") != params.end() ? params.at(\"LF\") : _Lf;\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_epsi  = params.find(\"REF_EPSI\") != params.end() ? params.at(\"REF_EPSI\") : _ref_epsi;\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_epsi  = params.find(\"W_EPSI\") != params.end()  ? params.at(\"W_EPSI\") : _w_epsi;\n            _w_vel   = params.find(\"W_V\") != params.end()     ? params.at(\"W_V\") : _w_vel;\n            _w_delta = params.find(\"W_DELTA\") != params.end() ? params.at(\"W_DELTA\") : _w_delta;\n            _w_accel = params.find(\"W_A\") != params.end()     ? params.at(\"W_A\") : _w_accel;\n            _w_delta_d = params.find(\"W_DDELTA\") != params.end() ? params.at(\"W_DDELTA\") : _w_delta_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            _psi_start   = _y_start + _mpc_steps;\n            _v_start     = _psi_start + _mpc_steps;\n            _cte_start   = _v_start + _mpc_steps;\n            _epsi_start  = _cte_start + _mpc_steps;\n            _delta_start = _epsi_start + _mpc_steps;\n            _a_start     = _delta_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            \n            // fg[0] for cost function\n            fg[0] = 0;\n            for (int i = 0; i < _mpc_steps; i++) {\n              fg[0] += _w_cte * CppAD::pow(vars[_cte_start + i] - _ref_cte, 2); // cross deviation error\n              fg[0] += _w_epsi * CppAD::pow(vars[_epsi_start + i] - _ref_epsi, 2); // heading error\n              fg[0] += _w_vel * CppAD::pow(vars[_v_start + i] - _ref_vel, 2); // speed error\n            }\n\n            // Minimize the use of actuators.\n            for (int i = 0; i < _mpc_steps - 1; i++) {\n              fg[0] += _w_delta * CppAD::pow(vars[_delta_start + i], 2);\n              fg[0] += _w_accel * CppAD::pow(vars[_a_start + i], 2);\n            }\n\n            // Minimize the value gap between sequential actuations.\n            for (int i = 0; i < _mpc_steps - 2; i++) {\n              fg[0] += _w_delta_d * CppAD::pow(vars[_delta_start + i + 1] - vars[_delta_start + i], 2);\n              fg[0] += _w_accel_d * CppAD::pow(vars[_a_start + i + 1] - vars[_a_start + i], 2);\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 + _psi_start] = vars[_psi_start];\n            fg[1 + _v_start] = vars[_v_start];\n            fg[1 + _cte_start] = vars[_cte_start];\n            fg[1 + _epsi_start] = vars[_epsi_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> psi1 = vars[_psi_start + i + 1];\n                AD<double> v1 = vars[_v_start + i + 1];\n                AD<double> cte1 = vars[_cte_start + i + 1];\n                AD<double> epsi1 = vars[_epsi_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> psi0 = vars[_psi_start + i];\n                AD<double> v0 = vars[_v_start + i];\n                AD<double> cte0 = vars[_cte_start + i];\n                AD<double> epsi0 = vars[_epsi_start + i];\n\n                // Only consider the actuation at time t.\n                AD<double> delta0 = vars[_delta_start + i];\n                AD<double> a0 = vars[_a_start + i];\n\n                AD<double> f0 = 0.0;\n                for (int i = 0; i < coeffs.size(); i++) \n                {\n                    f0 += coeffs[i] * CppAD::pow(x0, i);\n                }\n                AD<double> psides0 = 0.0;\n                for (int i = 1; i < coeffs.size(); i++) \n                {\n                    psides0 += i*coeffs[i] * CppAD::pow(x0, i-1); // f'(x0)\n                }\n                psides0 = CppAD::atan(psides0);\n\n                fg[2 + _x_start + i] = x1 - (x0 + v0 * CppAD::cos(psi0) * _dt);\n                fg[2 + _y_start + i] = y1 - (y0 + v0 * CppAD::sin(psi0) * _dt);\n                fg[2 + _psi_start + i] = psi1 - (psi0 + v0 * delta0 / _Lf * _dt);\n                fg[2 + _v_start + i] = v1 - (v0 + a0 * _dt);\n                fg[2 + _cte_start + i] = cte1 - ((f0 - y0) + (v0 * CppAD::sin(epsi0) * _dt));\n                fg[2 + _epsi_start + i] = epsi1 - ((psi0 - psides0) + v0 * delta0 / _Lf * _dt);\n            }\n        }\n};\n\n// ====================================\n// MPC class definition implementation.\n// ====================================\nMPC::MPC() \n{\n    // Set default value    \n    _mpc_steps = 40;\n    _max_steering = 0.523; // Maximal steering 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    _psi_start   = _y_start + _mpc_steps;\n    _v_start     = _psi_start + _mpc_steps;\n    _cte_start   = _v_start + _mpc_steps;\n    _epsi_start  = _cte_start + _mpc_steps;\n    _delta_start = _epsi_start + _mpc_steps;\n    _a_start     = _delta_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_steering = _params.find(\"MAXSTR\") != _params.end() ? _params.at(\"MAXSTR\") : _max_steering;\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    _psi_start   = _y_start + _mpc_steps;\n    _v_start     = _psi_start + _mpc_steps;\n    _cte_start   = _v_start + _mpc_steps;\n    _epsi_start  = _cte_start + _mpc_steps;\n    _delta_start = _epsi_start + _mpc_steps;\n    _a_start     = _delta_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 psi = state[2];\n    const double v = state[3];\n    const double cte = state[4];\n    const double epsi = state[5];\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    size_t n_vars = _mpc_steps * 6 + (_mpc_steps - 1) * 2;\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    Dvector vars_lowerbound(n_vars);\n    Dvector vars_upperbound(n_vars);\n    // Set lower and upper limits for variables.\n    for (int i = 0; i < _delta_start; i++) \n    {\n        vars_lowerbound[i] = -_bound_value;\n        vars_upperbound[i] = _bound_value;\n    }\n    // The upper and lower limits of delta are set to -25 and 25\n    // degrees (values in radians).\n    for (int i = _delta_start; i < _a_start; i++) \n    {\n        vars_lowerbound[i] = -_max_steering;\n        vars_upperbound[i] = _max_steering;\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[_psi_start] = psi;\n    constraints_lowerbound[_v_start] = v;\n    constraints_lowerbound[_cte_start] = cte;\n    constraints_lowerbound[_epsi_start] = epsi;\n    constraints_upperbound[_x_start] = x;\n    constraints_upperbound[_y_start] = y;\n    constraints_upperbound[_psi_start] = psi;\n    constraints_upperbound[_v_start] = v;\n    constraints_upperbound[_cte_start] = cte;\n    constraints_upperbound[_epsi_start] = epsi;\n\n    // object that computes objective and constraints\n    FG_eval fg_eval(coeffs);\n    fg_eval.LoadParams(_params);\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 << \"Cost \" << cost << std::endl;\n    this->mpc_x = {};\n    this->mpc_y = {};\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    }\n    vector<double> result;\n    result.push_back(solution.x[_delta_start]);\n    result.push_back(solution.x[_a_start]);\n    return result;\n}\n", "meta": {"hexsha": "a029188c0a5516f039d0aeba0bb91d83a73cec20", "size": 13736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MPC.cpp", "max_stars_repo_name": "KeremZaman/hypharos_minicar", "max_stars_repo_head_hexsha": "7ba300ecf964d10147ce19be58e0c33cedeb560d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2018-07-11T18:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:14:55.000Z", "max_issues_repo_path": "src/MPC.cpp", "max_issues_repo_name": "KeremZaman/hypharos_minicar", "max_issues_repo_head_hexsha": "7ba300ecf964d10147ce19be58e0c33cedeb560d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-12T16:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-24T18:07:56.000Z", "max_forks_repo_path": "src/MPC.cpp", "max_forks_repo_name": "KeremZaman/hypharos_minicar", "max_forks_repo_head_hexsha": "7ba300ecf964d10147ce19be58e0c33cedeb560d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2018-07-11T15:08:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:57:24.000Z", "avg_line_length": 40.4, "max_line_length": 114, "alphanum_fraction": 0.5701077461, "num_tokens": 3947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5830837857660092}}
{"text": "#include <iostream>\n#include <vector>\n#include <math.h>\n#include <Eigen/Dense>\n#include <functional>\n\n#define PI 3.14159265\n\nusing V2 = Eigen::Vector2d;\nusing V3 = Eigen::Vector3d;\nusing V4 = Eigen::Vector4d;\nusing Q = Eigen::Quaternion<double>;\n\ninline V4 sane_conv(const Q & q) {\n  return V4(\n    q.w(),\n    q.x(),\n    q.y(),\n    q.z()\n  );\n}\ninline Q sane_conv(const V4 & v) {\n  return Q(\n    v[0],\n    v[1],\n    v[2],\n    v[3]\n  );\n}\ninline void q_add(Q & a, const Q & b, double s) {\n  a.w() += s * b.w();\n  a.x() += s * b.x();\n  a.y() += s * b.y();\n  a.z() += s * b.z();\n}\n\nstruct Barycentric {\n\n  Barycentric(\n    V3 a = V3(1,1,1),\n    V3 b = V3(-1,-1,1),\n    V3 c = V3(-1,1,-1),\n    V3 d = V3(1,-1,-1)\n  ) : a(a), b(b), c(c), d(d) {\n\n    Eigen::Matrix4d tmp;\n    tmp <<\n      a[0], b[0], c[0], d[0],\n      a[1], b[1], c[1], d[1],\n      a[2], b[2], c[2], d[2],\n      1.0 , 1.0 , 1.0 , 1.0;\n\n    inv = tmp.inverse();\n\n  }\n\n  inline V3 get_point(const Q & q) {\n    return q.w() * a + q.x() * b + q.y() * c + q.z() * d;\n  }\n\n  inline V4 get_coords(const V3 & p) {\n    return inv * V4(p[0],p[1],p[2],1.0);\n  }\n\n  inline Q get_quaternion(const V3 & p) {\n    return sane_conv(get_coords(p));\n  }\n\n  V3 a,b,c,d;\n\n  Eigen::Matrix4d inv;\n\n};\n\nstruct QuaternionFourier {\n\n  QuaternionFourier(size_t max_spin = 5) {\n\n    num_terms = (max_spin*2 + 1) * (max_spin*2 + 1);\n\n    u.reserve(num_terms);\n    u.push_back(V2::Zero());\n    int bound = max_spin;\n    for (int spin_u = -bound; spin_u < bound + 1; spin_u ++) {\n      for (int spin_v = -bound; spin_v < bound + 1; spin_v ++) {\n        u.push_back(V2(spin_u, spin_v));\n      }\n    }\n\n    f_hat.resize(num_terms, Q(0.0,0.0,0.0,0.0));\n\n    interpolate([](const V2 & x) {\n      V2 phase = 2.0*PI*x;\n      return V3(\n        (1.0 + 0.5*cos(phase[0])) * cos(phase[1]),\n        (1.0 + 0.5*cos(phase[0])) * sin(phase[1]),\n        0.5*sin(phase[0])\n      );\n    });\n\n  }\n\n  void interpolate(std::function<V3(const V2 &)> f, size_t interpolation_res = 100) {\n\n    double du = 1.0 / static_cast<double>(interpolation_res * interpolation_res);\n\n    V2 x;\n    for (size_t n = 0; n < interpolation_res; n++) {\n      x[0] = static_cast<double>(n) / static_cast<double>(interpolation_res);\n\n      for (size_t m = 0; m < interpolation_res; m++) {\n        x[1] = static_cast<double>(m) / static_cast<double>(interpolation_res);\n\n        V3 tmp = f(x);\n        Q q = barycentric.get_quaternion(tmp);\n\n        for (size_t t = 0; t < num_terms; t ++) {\n\n          V2 phase = - 2.0 * PI * x.cwiseProduct(u[t]);\n\n          Q left(cos(phase[0]), sin(phase[0]), 0.0, 0.0);\n          Q right(cos(phase[1]), 0.0, sin(phase[1]), 0.0);\n\n          q_add(f_hat[t], left * q * right, du);\n        }\n      }\n    }\n  }\n\n  inline Q get_term(size_t n, V2 x) {\n\n    V2 phase = 2.0 * PI * x.cwiseProduct(u[n]);\n\n    Q left(cos(phase[0]), sin(phase[0]), 0.0, 0.0);\n    Q right(cos(phase[1]), 0.0, sin(phase[1]), 0.0);\n\n    return left * f_hat[n] * right;\n\n  }\n\n  inline V3 get_term_as_point(size_t n, V2 x) {\n\n    Q tmp = get_term(n, x);\n\n    return barycentric.get_point(tmp);\n\n  }\n\n  size_t num_terms;\n\n  std::vector<V2> u;\n  std::vector<Q> f_hat;\n\n  Barycentric barycentric;\n\n};\n\nstruct BlenderData {\n\n  BlenderData(size_t num_objects, size_t num_frames, double v) : num_objects(num_objects), num_frames(num_frames) {\n\n    scales_s.resize(num_objects);\n    locations_s.resize(num_objects);\n    rotations_s.resize(num_objects);\n\n    QuaternionFourier qf(sqrt(num_objects)/2 + 1);\n\n    for (size_t o = 0; o < num_objects; o++) {\n      scales_s[o].resize(num_frames);\n      locations_s[o].resize(num_frames);\n      rotations_s[o].resize(num_frames);\n    }\n\n    for (size_t f = 0; f < num_frames; f++) {\n\n      V3 offset = V3::Zero();\n      double fd = static_cast<double>(f) / static_cast<double>(num_frames);\n\n\n      V2 x(v,fd);\n\n\n      for (size_t o = 0; o < num_objects; o++) {\n\n        locations_s[o][f] = offset;\n\n        V3 add_offset = qf.get_term_as_point(o, x);\n\n        scales_s[o][f][0] = add_offset.norm();\n        scales_s[o][f][1] = 1.0 + add_offset.norm()/10.0;\n        scales_s[o][f][2] = 1.0 + add_offset.norm()/10.0;\n\n        Q to_offset = Q::FromTwoVectors(V3::UnitX(), add_offset);\n\n        rotations_s[o][f] = sane_conv(to_offset);\n\n        offset += add_offset;\n\n      }\n    }\n  }\n\n  size_t num_objects;\n  size_t num_frames;\n\n  std::vector<std::vector<V3>> scales_s;\n  std::vector<std::vector<V3>> locations_s;\n  std::vector<std::vector<V4>> rotations_s;\n\n};\n\n\nextern \"C\" {\n  BlenderData* construct(size_t resolution, size_t num_frames, double v) {\n    return new BlenderData(resolution, num_frames, v);\n  }\n  double * get_scales(BlenderData* data, size_t i) { return data->scales_s[i][0].data(); }\n  double * get_locations(BlenderData* data, size_t i) { return data->locations_s[i][0].data(); }\n  double * get_rotations(BlenderData* data, size_t i) { return data->rotations_s[i][0].data(); }\n}\n", "meta": {"hexsha": "5522030850025b96a5c456a69c954a4bed82daad", "size": 4926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core.cpp", "max_stars_repo_name": "Vollkornaffe/Fourier_Blender", "max_stars_repo_head_hexsha": "24f2b1afaac4decfef63465d796a03f993b02b67", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "Vollkornaffe/Fourier_Blender", "max_issues_repo_head_hexsha": "24f2b1afaac4decfef63465d796a03f993b02b67", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "Vollkornaffe/Fourier_Blender", "max_forks_repo_head_hexsha": "24f2b1afaac4decfef63465d796a03f993b02b67", "max_forks_repo_licenses": ["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.2895927602, "max_line_length": 115, "alphanum_fraction": 0.5655704425, "num_tokens": 1649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.583049015602287}}
{"text": "#include <string>\n#include <ros/ros.h>\n#include <iostream>\n#include <time.h>\n#include \"vector\"\n#include \"std_msgs/Float32.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n#include \"controller_manager_msgs/SwitchController.h\"\n#include \"controller_manager_msgs/ListControllers.h\"\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nEigen::Matrix<double, 6, 6> calJacobi(geometry_msgs::Point pos[], Eigen::Vector3d Z_4, Eigen::Vector3d Z_6){\n    Eigen::Matrix<double, 3, 6> jacobiV ;\n    Eigen::Matrix<double, 3, 6> jacobiW ;\n    Eigen::Matrix<double, 6, 6> jacobi ;\n    Eigen::Vector3d Z_1, Z_2, Z_3, Z_5;\n    Z_1<< 0,0,1;\n    Z_2<< 0,-1,0;\n    Z_3<< 0,-1,0;\n    Z_5<< 0,-1,0;\n    Eigen::Vector3d P[6];\n    for(int i = 0; i<6; i++){\n        P[i] << pos[i].x, pos[i].y, pos[i].z;\n    }\n    Eigen::Vector3d temp;\n    temp<< 0,0,0;\n    jacobiV<< Z_1.cross(P[5]-P[0]), Z_2.cross(P[5]-P[1]),\n            Z_3.cross(P[5]-P[2]), Z_4.cross(P[5]-P[3]), Z_5.cross(P[5]-P[4]), temp;\n    jacobiW << Z_1, Z_2, Z_3, Z_4, Z_5, Z_6;\n    jacobi.block<3,6>(0,0) = jacobiV;\n    jacobi.block<3,6>(3,0) = jacobiW;\n    // std::cout<< jacobiV <<std::endl<<std::endl;\n    return jacobi;\n}\n\nEigen::Matrix<double, 6, 6> myCalJacob(std::vector<double> link)\n{\n    Eigen::Matrix<double, 3, 6> jacobV;\n    Eigen::Matrix<double, 3, 6> jacobW;\n    Eigen::Matrix<double, 6, 6> jacob;\n    \n\n    Eigen::Matrix<double, 6, 1> theta;\n    theta << link[0], link[1], link[2], link[3], link[4], link[5];\n    Eigen::Matrix<double, 6, 1> init_theta;\n    init_theta << 0, M_PI / 2, 0, 0, -M_PI / 2, 0;\n    Eigen::Matrix<double, 6, 1> a, alpha, d;\n    alpha << 0, M_PI/2, 0, M_PI/2, -M_PI/2, M_PI/2;\n    a<< 0, 0, 0.225, 0 ,0 ,0;\n    d << 0.284, 0, 0, 0.2289, 0, 0.055;\n    theta = theta + init_theta;\n\n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity(4, 4);\n    for(int i = 0; i<6 ;i++){\n        Eigen::Matrix4d temp ;\n        temp << cos(theta[i]), -sin(theta[i]), 0, a[i],\n            sin(theta[i])*cos(alpha[i]), cos(theta[i])*cos(alpha[i]), -sin(alpha[i]), -sin(alpha[i])*d[i],\n            sin(theta[i])*sin(alpha[i]), cos(theta[i])*sin(alpha[i]), cos(alpha[i]), cos(alpha[i])*d[i],\n            0, 0, 0, 1;\n        T = T * temp;\n        jacobV.col(i) = T.block<3, 1>(0,3);\n        jacobW.col(i) = T.block<3,3>(0,0).col(2);\n    }\n    for(int i=0; i<6; i++){\n        jacobV.col(i) = jacobW.col(i).cross((jacobV.col(5)-jacobV.col(i)));\n    }\n    jacob.block<3,6>(0,0) = jacobV;\n    jacob.block<3,6>(3,0) = jacobW;\n    return jacob;\n}", "meta": {"hexsha": "0afb4788351b64498ed131135ab830a4e211373a", "size": 2533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "probot_grasping/src/jacobi.hpp", "max_stars_repo_name": "CrescentVelvet/anno_arm", "max_stars_repo_head_hexsha": "73a94c0be2ce011081860df539daf80a235fc003", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-05T09:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T16:08:15.000Z", "max_issues_repo_path": "probot_grasping/src/jacobi.hpp", "max_issues_repo_name": "CrescentVelvet/anno_arm", "max_issues_repo_head_hexsha": "73a94c0be2ce011081860df539daf80a235fc003", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "probot_grasping/src/jacobi.hpp", "max_forks_repo_name": "CrescentVelvet/anno_arm", "max_forks_repo_head_hexsha": "73a94c0be2ce011081860df539daf80a235fc003", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T09:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T09:39:44.000Z", "avg_line_length": 34.698630137, "max_line_length": 108, "alphanum_fraction": 0.5700750099, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5830197290211857}}
{"text": "//\n// $Id$\n// \n// Original author: Robert Burke <robert.burke@cshs.org>\n//\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\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 _QR_HPP\n#define _QR_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace pwiz {\nnamespace math {\n\n\n// Constructs a matrix to reflect a vector x onto ||x|| * e1.\n//\n// \\param x vector to reflect\n// \\param F matrix object to construct reflector with\ntemplate<class matrix_type, class vector_type>\nvoid Reflector(const vector_type& x, matrix_type& F)\n{\n    using namespace boost::numeric::ublas;\n\n    typedef typename matrix_type::value_type value_type;\n\n    unit_vector<value_type> e1(x.size(), 0);\n\n    //v_k = -sgn( x(1) ) * inner_prod(x) * e1 + x;\n    double x_2 = norm_2(x);\n    boost::numeric::ublas::vector<value_type>\n        v_k((x(0) >= 0 ? x_2 : -1 * x_2) * e1 + x);\n\n    //v_k = v_k / norm_2(v_k);\n    double norm_vk = norm_2(v_k);\n    if (norm_vk != 0)\n        v_k /= norm_2(v_k);\n    \n    // F = A(k:m,k:n) - 2 * outer_prod(v_k, v_k) * A(k:m,k:n)\n    identity_matrix<value_type> eye(v_k.size());\n    F = matrix_type(v_k.size(), v_k.size());\n    \n    F = eye - 2. * outer_prod(v_k, v_k);\n}\n\n// Returns a matrix to reflect x onto ||x|| * e1.\n//\n// \\param x vector to reflect\n// \\return Householder reflector for x\ntemplate<class matrix_type, class vector_type>\nmatrix_type Reflector(const vector_type& x)\n{\n    using namespace boost::numeric::ublas;\n\n    matrix_type F(x.size(), x.size());\n\n    Reflector<matrix_type, vector_type>(x, F);\n\n    return F;\n}\n\ntemplate<class matrix_type>\nvoid qr(const matrix_type& A, matrix_type& Q, matrix_type& R)\n{\n    using namespace boost::numeric::ublas;\n\n    typedef typename matrix_type::size_type size_type;\n    typedef typename matrix_type::value_type value_type;\n\n    // TODO resize Q and R to match the needed size.\n    int m=A.size1();\n    int n=A.size2();\n\n    identity_matrix<value_type> ident(m);\n    if (Q.size1() != ident.size1() || Q.size2() != ident.size2())\n        Q = matrix_type(m, m);\n    Q.assign(ident);\n\n    R.clear();\n    R = A;\n\n    for (size_type k=0; k< R.size1() && k<R.size2(); k++)\n    {\n        slice s1(k, 1, m - k);\n        slice s2(k, 0, m - k);\n        unit_vector<value_type> e1(m - k, 0);\n\n        // x = A(k:m, k);\n        matrix_vector_slice<matrix_type> x(R, s1, s2);\n        matrix_type F(x.size(), x.size());\n        \n        Reflector(x, F);\n\n        matrix_type temp = subrange(R, k, m, k, n);\n        //F = prod(F, temp);\n        subrange(R, k, m, k, n) = prod(F, temp);\n\n        // <<---------------------------------------------->>\n        // forming Q\n        identity_matrix<value_type> iqk(A.size1());\n        matrix_type Q_k(iqk);\n        \n        subrange(Q_k, Q_k.size1() - F.size1(), Q_k.size1(),\n                 Q_k.size2() - F.size2(), Q_k.size2()) = F;\n\n        Q = prod(Q, Q_k);\n    }\n}\n\n}\n}\n\n#endif // _QR_HPP\n", "meta": {"hexsha": "10849bc0af13f7b7e313dfdb9c6ea2a82ee0e83d", "size": 3616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/qr.hpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T23:48:38.000Z", "max_issues_repo_path": "pwiz/utility/math/qr.hpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-08-31T08:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:58:06.000Z", "max_forks_repo_path": "pwiz/utility/math/qr.hpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T19:25:07.000Z", "avg_line_length": 27.3939393939, "max_line_length": 76, "alphanum_fraction": 0.6180862832, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.582948587055963}}
{"text": "// Demonstration of representing/analyzing circuits as MNA matrices\n// to accompany \"Analyzing On-Chip Interconnect with Modern C++\"\n// Author: Jeff Trull <edaskel@att.net>\n\n/*\nCopyright (c) 2014 Jeffrey E. Trull\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n#include <iostream>\n#include <boost/numeric/odeint.hpp>\n\n#include \"ckt_matrix.h\"\n\n// Create my standard 2-signal coupling testcase\nstruct coupling_circuit_t {\n    coupling_circuit_t() {\n        // MNA\n        // MNA - we will have 10 state variables:\n        // 8 for node voltages (vagg, n1, n2, n3, vvic, n5, n6, n7)\n        // 2 for input currents (iagg, ivic)\n        using namespace Eigen;\n        typedef Matrix<double, 10, 10> state_matrix_t;\n        state_matrix_t G, C;   // conductance and time derivative matrices\n        G = state_matrix_t::Zero();\n        C = state_matrix_t::Zero();\n\n        double const kohm = 1000;\n        double const ff   = 1e-15;\n        double rdrv       = 0.1*kohm;\n        double pi_r       = 1.0*kohm;\n        double pi_c       = 100*ff;\n        double coupl_c    = 100*ff;\n        double rcvr_c     = 20*ff;\n\n        stamp_i(G, 0, 8);                // aggressor driver current\n        stamp(G, 0, 1, 1.0 / rdrv);      // aggressor driver impedance\n        stamp(C, 1,    pi_c / 2);        // begin first \"pi\"\n        stamp(G, 1, 2, 1.0 / pi_r);\n        stamp(C, 2,    pi_c / 2);        // central node\n        stamp(C, 2,    pi_c / 2);        // second \"pi\"\n        stamp(G, 2, 3, 1.0 / pi_r);\n        stamp(C, 3,    pi_c / 2);\n        stamp(C, 3,    rcvr_c);          // aggressor receiver\n\n        stamp_i(G, 4, 9);                // victim driver current\n        stamp(G, 4, 5, 1.0 / rdrv);      // victim driver impedance\n        stamp(C, 5,    pi_c / 2);        // begin first \"pi\"\n        stamp(G, 5, 6, 1.0 / pi_r);\n        stamp(C, 6,    pi_c / 2);        // central node\n        stamp(C, 6,    pi_c / 2);        // second \"pi\"\n        stamp(G, 6, 7, 1.0 / pi_r);\n        stamp(C, 7,    pi_c / 2);\n        stamp(C, 7,    rcvr_c);          // victim receiver\n\n        stamp(C, 2, 6, coupl_c);         // coupling cap\n\n        // We also have 2 inputs, two outputs\n        typedef Matrix<double, 10, 2> io_matrix_t;\n        io_matrix_t B = io_matrix_t::Zero();\n        B(8, 0) = -1;                    // connect input 0 to vagg\n        B(9, 1) = -1;                    // connect input 1 to vvic\n        io_matrix_t L = io_matrix_t::Zero();\n        L(3, 0) = 1;                     // connect agg rcvr to output 0\n        L(7, 1) = 1;                     // connect vic rcvr to output 1\n\n        // cross-check: compute moments\n        Matrix<double, 2, 2> E = Matrix<double, 2, 2>::Zero();   // feedthrough term we don't have\n        auto block_moments = moments(G, C, B, L, E, 2);\n        std::cerr << \"moment 0=\\n\" << block_moments[0] << std::endl;\n        std::cerr << \"moment 1=\\n\" << block_moments[1] << std::endl;\n\n        // Now regularize.  Results are of dynamic (not initially known) size\n        MatrixXd Greg, Creg;             // regularized versions of C and G\n        Matrix<double, Dynamic, 2> Breg, Lreg;\n        std::tie(Greg, Creg, Breg, Lreg) = regularize(G, C, B, L);\n\n        // Finally, put in a form suitable for simulation, by transforming\n        // C*dX/dt = -G*X + B*u\n        // into\n        // dX/dt   = -C.inv()*G*X + C.inv()*B*u\n        // Wikipedia says Cholesky decomposition \"roughly twice as efficient\" as LU:\n        assert(canLDLTDecompose(Creg));            // make sure we can use it\n        drift_  = Creg.ldlt().solve(-1.0 * Greg);  // -Creg.inv()*Greg\n        input_  = Creg.ldlt().solve(Breg);         // Creg.inv()*Breg\n        output_ = Lreg.transpose();\n\n    }\n\n    // perform dX/dt calculation for ODEInt\n    typedef std::vector<double> state_t;\n    void operator()(state_t const& x, state_t& dxdt, double) const {\n        using namespace Eigen;\n        // need to wrap std::vector state types for Eigen to use\n        Map<const Matrix<double, Dynamic, 1>> xvec(x.data(), x.size());\n        Map<Matrix<double, Dynamic, 1>>       result(dxdt.data(), x.size());\n\n        // simulating step function at time 0 for simplicity\n        Matrix<double, 2, 1> u; u << 1.0, 0.0;   // aggressor voltage 1V, victim quiescent\n        result = drift_ * xvec + input_ * u;\n    }\n        \n    // turns internal state into output by applying transformed L matrix\n    std::vector<double> state2output(state_t const& x) const {\n        using namespace Eigen;\n        std::vector<double> result(2);\n        Map<const Matrix<double, Dynamic, 1> > xvec(x.data(), x.size());\n        Map<Matrix<double, 2, 1> >             ovec(result.data());\n        ovec = output_ * xvec;\n        return result;\n    }\n\n    size_t statecnt() const {\n        return drift_.rows();\n    }\n\nprivate:\n    Eigen::Matrix<double, Eigen::Dynamic, 2>              input_;\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> drift_;\n    Eigen::Matrix<double, 2, Eigen::Dynamic>             output_;\n};\n\nint main() {\n    using namespace std;\n\n    // instantiate circuit\n    coupling_circuit_t coupling_test;\n\n    // simulate\n    typedef coupling_circuit_t::state_t state_t;\n    state_t         x(coupling_test.statecnt(), 0.0);   // initial conditions = all zero\n\n    using boost::numeric::odeint::integrate;\n\n    integrate( coupling_test, x, 0.0, 1e-9, 1e-12,\n               [&](state_t const& x, double t) {\n                   auto outputs = coupling_test.state2output(x);\n                   cout << t << \" \" << outputs[0] << \" \" << outputs[1] << endl;\n               });\n}\n", "meta": {"hexsha": "c91e310b81c9c94fe1fc0e0ef7dd0f8f21b788f6", "size": 6571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matrix.cpp", "max_stars_repo_name": "jefftrull/OnChipInterconnect", "max_stars_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T11:05:20.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-04T11:05:20.000Z", "max_issues_repo_path": "matrix.cpp", "max_issues_repo_name": "jefftrull/OnChipInterconnect", "max_issues_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix.cpp", "max_forks_repo_name": "jefftrull/OnChipInterconnect", "max_forks_repo_head_hexsha": "11d1b2483b5a4486ea0d2b3eb6a3f0104488d1c4", "max_forks_repo_licenses": ["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.5886075949, "max_line_length": 98, "alphanum_fraction": 0.5849946736, "num_tokens": 1843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5829485754117599}}
{"text": "/*\n * Copyright 2015 Christoph Jud (christoph.jud@unibas.ch)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <iostream>\n#include <memory>\n#include <ctime>\n#include <chrono>\n\n#include <boost/random.hpp>\n#include <Eigen/SVD>\n\n#include \"LAPACKUtils.h\"\n#include \"GaussianProcess.h\"\n\nusing namespace gpr;\n\ntemplate<class T>\nvoid Test1(unsigned N, bool cout=false){\n    /*\n     * Test 1: invert general matrix\n     * - compare Eigen inversion and LAPACK inversion\n     */\n    std::cout << \"Test 1: Eigen vs. LAPACK... (general matrix) \" << std::endl;\n    std::chrono::time_point<std::chrono::system_clock> start;\n\n\n    typedef GaussianProcess<T> GaussianProcessType;\n    typedef typename GaussianProcessType::MatrixType MatrixType;\n\n    // generate random matrix\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, 1);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    // generate double precision random matrix\n    MatrixType m(N, N);\n    for (unsigned i =0; i < N ; i++) {\n        for (unsigned j = 0; j < N; j++) {\n            m(i,j) = r();\n        }\n    }\n\n    if(cout){\n        std::cout << \"matrix: \" << std::endl;\n        std::cout << m << std::endl;\n    }\n\n    // Eigen inversion (LU)\n    std::cout << \" - eigen... \" << std::flush;\n    start = std::chrono::system_clock::now();\n    MatrixType m_inv = m.inverse();\n    std::chrono::duration<double> elapsed_seconds = std::chrono::system_clock::now()-start;\n    std::cout << \"elapsed time: (sec) \" << elapsed_seconds.count() << std::endl;\n    if(cout) std::cout << m_inv << std::endl;\n\n    // LAPACK inversion (LU)\n    std::cout << \" - lapack... \" << std::flush;\n    start = std::chrono::system_clock::now();\n    MatrixType lu_inv = lapack::lu_invert<T>(m);\n    elapsed_seconds = std::chrono::system_clock::now()-start;\n    std::cout << \"elapsed time: (sec) \" << elapsed_seconds.count() << std::endl;\n    if(cout) std::cout << lu_inv << std::endl;\n\n    MatrixType lapack_identity = (m * lu_inv);\n    MatrixType lu_identity = (m * m_inv);\n    MatrixType identity = MatrixType::Identity(m.cols(), m.cols());\n\n    T lapack_error = 0;\n    T lu_error = 0;\n    // generate double precision random matrix\n    for (unsigned i =0; i < N ; i++) {\n        for (unsigned j = 0; j < N; j++) {\n            lu_error += std::fabs(identity(i,j)-lu_identity(i,j));\n            lapack_error += std::fabs(identity(i,j)-lapack_identity(i,j));\n        }\n    }\n\n    std::cout << \" - [passed] error: eigen \" << lu_error << \", lapack \" << lapack_error << std::endl;\n}\n\ntemplate<class T>\nvoid Test2(unsigned N, bool cout=false){\n    /*\n     * Test 2: invert general matrix\n     * - compare Eigen inversion and LAPACK inversion\n     */\n    std::cout << \"Test 2: Eigen vs. LAPACK... (symmetric matrix) \" << std::endl;\n    std::chrono::time_point<std::chrono::system_clock> start;\n\n\n    typedef GaussianProcess<T> GaussianProcessType;\n    typedef typename GaussianProcessType::MatrixType MatrixType;\n    typedef typename GaussianProcessType::VectorType VectorType;\n\n    // generate random matrix\n    static boost::minstd_rand randgen(static_cast<unsigned>(time(0)));\n    static boost::normal_distribution<> dist(0, 1);\n    static boost::variate_generator<boost::minstd_rand, boost::normal_distribution<> > r(randgen, dist);\n\n    // generate double precision random matrix\n    MatrixType m(N, N);\n    for (unsigned i =0; i < N ; i++) {\n        for (unsigned j = 0; j < N; j++) {\n            m(i,j) = r();\n        }\n    }\n\n    m = m.transpose()*m; // make it inverse and positive definite\n    for(unsigned i=0; i<N; i++){\n        m(i,i) += 0.01;\n    }\n\n    if(cout){\n        std::cout << \"matrix: \" << std::endl;\n        std::cout << m << std::endl;\n    }\n\n    // Eigen inversion for symmetric positive definite matrices\n    std::cout << \" - eigen... \" << std::flush;\n    start = std::chrono::system_clock::now();\n\n    Eigen::SelfAdjointEigenSolver<MatrixType> es;\n    es.compute(m);\n    VectorType eigenValues = es.eigenvalues().reverse();\n    MatrixType eigenVectors = es.eigenvectors().rowwise().reverse();\n    if((eigenValues.real().array() < 0).any()){\n        throw std::string(\"there are negative eigenvalues.\");\n        std::cout.flush();\n    }\n    MatrixType m_inv = eigenVectors * VectorType(1/eigenValues.array()).asDiagonal() * eigenVectors.transpose();\n    std::chrono::duration<double> elapsed_seconds = std::chrono::system_clock::now()-start;\n    std::cout << \"elapsed time: (sec) \" << elapsed_seconds.count() << std::endl;\n    if(cout) std::cout << m_inv << std::endl;\n\n    // LAPACK inversion (cholesky)\n    std::cout << \" - lapack... \" << std::flush;\n    start = std::chrono::system_clock::now();\n    MatrixType chol_inv = lapack::chol_invert<T>(m);\n    elapsed_seconds = std::chrono::system_clock::now()-start;\n    std::cout << \"elapsed time: (sec) \" << elapsed_seconds.count() << std::endl;\n    if(cout) std::cout << chol_inv << std::endl;\n\n    MatrixType chol_identity = (m * chol_inv);\n    MatrixType lu_identity = (m * m_inv);\n    MatrixType identity = MatrixType::Identity(m.cols(), m.cols());\n\n    T chol_error = 0;\n    T lu_error = 0;\n    // generate double precision random matrix\n    for (unsigned i =0; i < N ; i++) {\n        for (unsigned j = 0; j < N; j++) {\n            //error += std::fabs(m_inv(i,j)-chol_inv(i,j));\n            chol_error += std::fabs(chol_identity(i,j)-identity(i,j));\n            lu_error += std::fabs(lu_identity(i,j)-identity(i,j));\n        }\n    }\n    std::cout << \" - [passed] error: eigen \" << lu_error << \", lapack \" << chol_error << std::endl;\n}\n\nint main (int argc, char *argv[]){\n\n    unsigned n = 1000;\n    bool cout = false;\n    try{\n        std::cout << \"LAPACK inversion test: (float)\" << std::endl;\n        Test1<float>(n/4, cout);\n        Test2<float>(n/4, cout);\n\n        std::cout << \"LAPACK inversion test: (double)\" << std::endl;\n        Test1<double>(n, cout);\n        Test2<double>(n, cout);\n    }\n    catch(std::string& s){\n        std::cout << \" [failed] - \" << s << std::endl;\n        return -1;\n    }\n\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "e80bce4a12d3fd5636cadf68b083e2fa8eb70918", "size": 6672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/LAPACKTest.cpp", "max_stars_repo_name": "ChristophJud/GPR", "max_stars_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T14:30:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T21:44:06.000Z", "max_issues_repo_path": "tests/LAPACKTest.cpp", "max_issues_repo_name": "ChristophJud/GPR", "max_issues_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/LAPACKTest.cpp", "max_forks_repo_name": "ChristophJud/GPR", "max_forks_repo_head_hexsha": "62c60aca697ae7614356b1f6db06568f0c4085d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-11-16T00:50:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T02:00:18.000Z", "avg_line_length": 33.8680203046, "max_line_length": 112, "alphanum_fraction": 0.6146582734, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199471193039, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5829485754117598}}
{"text": "///1\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#include <boost/graph/strong_components.hpp>\n\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\n// Main\nvoid testcase() {\n  // build graph\n  int n, m;\n  std::cin >> n >> m;\n  graph G(n);\n  edge_adder adder(G);\n  // auto c_map = boost::get(boost::edge_capacity, 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  \n  std::vector<int> b(n);\n  long sum_b = 0;\n  for(int i = 0; i < n; i++) {\n    std::cin >> b[i];\n    if(b[i] > 0) {\n      sum_b += b[i];  \n      adder.add_edge(v_source, i, b[i]);\n    }\n    else {\n      adder.add_edge(i, v_sink, -b[i]);\n    }\n  }\n  \n  for(int k = 0; k < m; k++) {\n    int i, j, c;\n    std::cin >> i >> j >> c;\n    adder.add_edge(i, j, c);\n  }\n  \n  long flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  // if(sum_dfs > 0) {\n  if(flow < sum_b) {\n    std::cout << \"yes\" << std::endl;\n    return;\n  }\n  std::cout << \"no\" << std::endl; \n  // std::cout << flow << \" \" << sum_b << \" \" << sum_abs_b << \"\\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  //             << \" cmap \" << c_map[edge] << \" rcmap \" << rc_map[edge] << \" and \" << 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": "d7a6af726b1953a07cca25959f3c65ab44a2f507", "size": 3927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week10-asterix_in_switzerland/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/week10-asterix_in_switzerland/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/week10-asterix_in_switzerland/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.4545454545, "max_line_length": 106, "alphanum_fraction": 0.6299974535, "num_tokens": 1139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5829478475973034}}
{"text": "// License: The Unlicense (https://unlicense.org)\n#pragma once\n\n// TODO(tybl): Replace Eigen with liblynel\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <limits>\n\nnamespace tybl::stats {\n\ntemplate <typename Type>\nclass distribution {\n  std::size_t m_count     { 0UL };\n  double m_mean           { 0.0 };\n  double m_sum_of_squares { 0.0 };\n  Type m_maximum          { std::numeric_limits<Type>::lowest() };\n  Type m_minimum          { std::numeric_limits<Type>::max() };\npublic:\n\n  // TODO(tybl): Unintuitive use of operator+=, replace with regular function\n  constexpr auto operator+=(Type x) -> distribution& {\n    m_count += 1;\n    double delta = static_cast<double>(x) - m_mean;\n    m_mean += delta / static_cast<double>(m_count);\n    m_sum_of_squares += delta * (static_cast<double>(x) - m_mean);\n    m_maximum = std::max(x, m_maximum);\n    m_minimum = std::min(x, m_minimum);\n    return *this;\n  }\n\n  [[nodiscard]] constexpr auto count() const -> std::size_t {\n    return m_count;\n  }\n\n  [[nodiscard]] constexpr auto maximum() const -> Type {\n    return m_maximum;\n  }\n\n  [[nodiscard]] constexpr auto minimum() const -> Type {\n    return m_minimum;\n  }\n\n  [[nodiscard]] constexpr auto mean() const -> double {\n    return m_mean;\n  }\n\n  [[nodiscard]] auto pop_stddev() const -> double {\n    return std::sqrt(pop_var());\n  }\n\n  [[nodiscard]] auto samp_stddev() const -> double {\n    return std::sqrt(samp_var());\n  }\n\n  [[nodiscard]] auto pop_var() const -> double {\n    return (0 < m_count) ? (m_sum_of_squares / static_cast<double>(m_count))\n                         : std::numeric_limits<double>::quiet_NaN();\n  }\n\n  [[nodiscard]] auto samp_var() const -> double {\n    return (1 < m_count) ? (m_sum_of_squares / static_cast<double>(m_count - 1))\n                         : std::numeric_limits<double>::quiet_NaN();\n  }\n\n}; // class distribution\n\n// TODO(tybl): Class name is not descriptive\ntemplate <size_t N>\nclass dist {\n  static_assert(0 < N, \"\");\n\n  // types:\n  using value_type = double;\n  using vector_type = Eigen::Matrix<value_type, N, 1>;\n  using matrix_type = Eigen::Matrix<value_type, N, N>;\n  using size_type = std::size_t;\n\n  // member variables:\n  size_type m_count { 0UL };\n  vector_type m_means { vector_type::Zero() };\n  matrix_type m_covars { matrix_type::Zero() };\n\npublic:\n\n  constexpr auto insert(Eigen::Matrix<double, N, 1> const& xs) -> void {\n    m_count += 1;\n    vector_type deltas = xs - m_means;\n    m_means += deltas / m_count;\n    matrix_type covar_deltas = (xs - m_means) * deltas.transpose() - m_covars;\n    m_covars += covar_deltas / m_count;\n  }\n\n  constexpr auto means() const -> vector_type const& {\n    return m_means;\n  }\n\n  constexpr auto covariance() const -> matrix_type const& {\n    return m_covars;\n  }\n\n}; // class dist\n\n} // namespace tybl::stats\n", "meta": {"hexsha": "a314a3ec1b80830e0699721956df5f2fc31b3f53", "size": 2803, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/libstats/include/stats/distribution.hpp", "max_stars_repo_name": "tybl/tybl", "max_stars_repo_head_hexsha": "cc74416d3d982177d46b89c0ca44f3a8e1cf00d6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-11T21:25:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T21:25:53.000Z", "max_issues_repo_path": "libs/libstats/include/stats/distribution.hpp", "max_issues_repo_name": "tybl/tybl", "max_issues_repo_head_hexsha": "cc74416d3d982177d46b89c0ca44f3a8e1cf00d6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-08-21T13:41:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T14:13:43.000Z", "max_forks_repo_path": "libs/libstats/include/stats/distribution.hpp", "max_forks_repo_name": "tybl/tybl", "max_forks_repo_head_hexsha": "cc74416d3d982177d46b89c0ca44f3a8e1cf00d6", "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.6952380952, "max_line_length": 80, "alphanum_fraction": 0.6400285408, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5829478324314976}}
{"text": "#define ARMA_DONT_USE_WRAPPER\n\n#include <armadillo>\n#include <cstdio>\n#include <mpi.h>\n#include <string>\n\n#define ALLREDUCE(X) MPI_Allreduce(MPI_IN_PLACE, X.memptr(), X.n_elem, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD)\n\nclass Shaq\n{\n  public:\n    Shaq()\n    {\n      MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    };\n    \n    void ranshaq(int seed, arma::uword m_local, arma::uword n)\n    {\n      int size;\n      \n      MPI_Comm_size(MPI_COMM_WORLD, &size);\n      \n      Data.resize(m_local, n);\n      arma::arma_rng::set_seed(seed + rank);\n      Data.randn();\n      \n      nrows = m_local*size;\n      ncols = n;\n    };\n    \n    void center()\n    {\n      arma::rowvec colmeans = sum(Data, 0);\n      ALLREDUCE(colmeans);\n      colmeans /= (double) nrows;\n      Data.each_row() -= colmeans;\n    };\n    \n    arma::mat Data;\n    arma::uword nrows;\n    arma::uword ncols;\n    int rank;\n};\n\n// shows the first and last singular values, computed via covariance matrix\nstatic arma::vec princomp(Shaq &X)\n{\n  X.center();\n  arma::mat Cov = X.Data.t() * X.Data;\n  Cov /= X.nrows - 1;\n  ALLREDUCE(Cov);\n  \n  arma::vec d;\n  eig_sym(d, Cov); \n  \n  return sqrt(d);\n}\n\nstatic void get_dims(int argc, char **argv, arma::uword *m_local, arma::uword *n)\n{\n  \n  if (argc != 3)\n  {\n    int rank;\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n    if (rank == 0)\n      fprintf(stderr, \"ERROR incorrect number of arguments: usage is 'mpirun -np n princomp num_local_rows num_global_cols\\n\");\n    \n    exit(-1);\n  }\n  \n  *m_local = (arma::uword) std::stoi(argv[1]);\n  *n = (arma::uword) std::stoi(argv[2]);\n}\n\n\n\nint main(int argc, char **argv)\n{\n  arma::uword m_local, n;\n  MPI_Init(NULL, NULL);\n  \n  get_dims(argc, argv, &m_local, &n);\n  \n  Shaq X;\n  X.ranshaq(1234, m_local, n);\n  \n  arma::vec d = princomp(X);\n  \n  if (X.rank == 0)\n    printf(\"%f %f\\n\", d[n-1], d[0]);\n    \n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "133aa04b1f093de1358e9fe5e042ee83e61a4cc5", "size": 1869, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/cxx/src/princomp.cpp", "max_stars_repo_name": "RBigData/coral2", "max_stars_repo_head_hexsha": "1d20dde80319277cf59f84e9d1e47aeb9a1038f5", "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/cxx/src/princomp.cpp", "max_issues_repo_name": "RBigData/coral2", "max_issues_repo_head_hexsha": "1d20dde80319277cf59f84e9d1e47aeb9a1038f5", "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/cxx/src/princomp.cpp", "max_forks_repo_name": "RBigData/coral2", "max_forks_repo_head_hexsha": "1d20dde80319277cf59f84e9d1e47aeb9a1038f5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2680412371, "max_line_length": 127, "alphanum_fraction": 0.5917602996, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5829478077183488}}
{"text": "//\n//  minhash.cpp\n//  \n//\n//  Created by Roberto Perdisci on 1/7/17.\n//  Copyright © 2017 Roberto Perdisci. All rights reserved.\n//\n\n#include \"minhash.hpp\"\n\n#include <iostream>\n#include <cstdint>\n#include <cassert>\n#include <boost/functional/hash.hpp>\n#include \"xxHash/xxhash.h\"\n\n\nnamespace rp {\n\nusing std::string;\nusing std::vector;\nusing std::set;\n    \n\nMinHash::MinHash(const unsigned sig_len, const unsigned seed) {\n    this->sig_len = sig_len;\n    this->seed = seed;\n    rand_eng.seed(seed);\n}\n    \n    \nvector<uint32_t> MinHash::random_uint32_universal_hash(const uint64_t x) {\n    \n    assert(x > 0 && x < UINT64_MAX);\n    \n    static const unsigned w = sizeof(uint64_t)*8;\n    static const unsigned M = sizeof(uint32_t)*8;\n    \n    vector<uint32_t> hv;\n    hv.push_back(static_cast<uint32_t>(x));\n    \n    for(int i=0; i<sig_len; i++) {\n        if(a.size()<sig_len) {\n            a.push_back(urandom_64(rand_eng));\n            b.push_back(urandom_32(rand_eng));\n        }\n        \n        uint32_t h = static_cast<uint32_t>((a[i]*x+b[i]) >> (w-M));\n        hv.push_back(h);\n    }\n    \n    return hv;\n}\n    \n\n\nvector<uint32_t> MinHash::minhash_universal(const std::map<string, bool>& s_set) {\n\n    vector<uint32_t> mh_sig(sig_len,UINT32_MAX);\n    for(auto s : s_set) {\n        uint64_t xxh = static_cast<uint64_t>(XXH64(s.first.data(), s.first.size(),seed));\n        vector<uint32_t> rh = random_uint32_universal_hash(xxh);\n        for(int i=0; i<sig_len; i++) {\n            if(rh[i] < mh_sig[i])\n                mh_sig[i] = rh[i];\n        }\n    }\n    \n    return std::move(mh_sig);\n}\n    \n    \nuint32_t MinHash::shash32(const string s, const unsigned seed) {\n    return static_cast<uint32_t>(XXH32(s.data(),s.size(),seed));\n}\n    \n    \nvector<uint32_t> MinHash::minhash_xor(const set<string>& s_set) {\n    \n    static boost::hash<std::string> boost_hash_fn;\n    \n    static std::default_random_engine rand_eng(seed);\n    static std::uniform_int_distribution<uint32_t> srandom;\n        \n    static vector<uint32_t> rn;\n        \n    vector<uint32_t> mh_sig(sig_len,std::numeric_limits<uint32_t>::max());\n    for(string s : s_set) {\n        std::size_t boosth = boost_hash_fn(s);\n        for(int i=0; i<sig_len; i++) {\n            if(rn.size()<sig_len)\n                rn.push_back(srandom(rand_eng));\n            uint32_t h = boosth^rn[i];\n            if(h < mh_sig[i]) {\n                mh_sig[i] = h;\n            }\n        }\n    }\n        \n    return mh_sig;\n}\n\n\n} // namespace rp\n\n\n", "meta": {"hexsha": "119983f37a6ff8fc5e6890b980face6c2a02b83b", "size": 2493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "minhash.cpp", "max_stars_repo_name": "jaratM/LSH", "max_stars_repo_head_hexsha": "e7759150898b27ecc6820058a8f25c87d75cc48b", "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": "minhash.cpp", "max_issues_repo_name": "jaratM/LSH", "max_issues_repo_head_hexsha": "e7759150898b27ecc6820058a8f25c87d75cc48b", "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": "minhash.cpp", "max_forks_repo_name": "jaratM/LSH", "max_forks_repo_head_hexsha": "e7759150898b27ecc6820058a8f25c87d75cc48b", "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.2990654206, "max_line_length": 89, "alphanum_fraction": 0.590052146, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.5828841313111266}}
{"text": "#pragma once\n#include <iostream>\n#include <vector>\n#include <armadillo>\n#include <thread>\n\nnamespace arm_simu{\n\t\n\ttemplate<typename T>\n\tstruct KahanSumParam{\n\t\tT sum=0;\n\t\tT c=0;\n\t\tT y=0;\n\t\tT t=0;\n\t};\n\t\n\ttemplate<typename T>\n\tstd::ostream& operator<<(std::ostream& cout,KahanSumParam<T> param){\n\t\tcout<<\"KahanSumParam[sum:\"<<param.sum<<\", c:\"<<param.c<<\", y:\"<<param.y<<\", t:\"<<param.t<<\"]\";\n\t\treturn cout;\n\t}\n\t\n\tclass KahanSum{\n\t\t\n\t\tprivate:\n\t\t\tstatic void ThreadWorkerSummation(double* input,const int size,arma::vec* out,const int index,bool use_kahansum=true){\n\t\t\t\tif (use_kahansum){\n\t\t\t\t\tdouble sum=0;\n\t\t\t\t\tdouble c=0;\n\t\t\t\t\tfor (unsigned long long i=0;i<size;i++){\n\t\t\t\t\t\tdouble y=input[i]-c;\n\t\t\t\t\t\tdouble t=sum+y;\n\t\t\t\t\t\tc=(t-sum)-y;\n\t\t\t\t\t\tsum=t;\n\t\t\t\t\t}\n\t\t\t\t\t(*out)[index]=sum;\n\t\t\t\t}else{\n\t\t\t\t\tdouble sum=0;\n\t\t\t\t\tfor (int i=0;i<size;i++){\n\t\t\t\t\t\tsum+=input[i];\n\t\t\t\t\t}\n\t\t\t\t\t(*out)[index]=sum;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tpublic:\n\t\t\t//full Summation use_kahansum=true(for kahansummation) and false for normal summation @param arma::vec\n\t\t\ttemplate<typename T>\n\t\t\tstatic T Summation(arma::vec input,bool use_kahansum=true){\n\t\t\t\tif (use_kahansum){\n\t\t\t\t\tT sum=0;\n\t\t\t\t\tT c=0;\n\t\t\t\t\tfor (unsigned long long i=0;i<input.size();i++){\n\t\t\t\t\t\tT y=input[i]-c;\n\t\t\t\t\t\tT t=sum+y;\n\t\t\t\t\t\tc=(t-sum)-y;\n\t\t\t\t\t\tsum=t;\n\t\t\t\t\t}\n\t\t\t\t\treturn sum;\n\t\t\t\t}else{\n\t\t\t\t\tT sum=0;\n\t\t\t\t\tfor (int i=0;i<input.size();i++){\n\t\t\t\t\t\tsum+=input[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn sum;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\n\t\t\tstatic void Summation(arma::mat input,arma::vec* result,bool use_kahansum=true){\n\t\t\t\tarma::uword ncols=input.n_cols;\n\t\t\t\tarma::uword nrows=input.n_rows;\n\t\t\t\t\n\t\t\t\tif (ncols<=2000){\n\t\t\t\t\n\t\t\t\t\tstd::thread* thread_list=new std::thread[ncols];\n\t\t\t\t\tfor (int i=0;i<ncols;i++){\n\t\t\t\t\t\tdouble* ptr=input.colptr(i);\n\t\t\t\t\t\tthread_list[i]=std::thread(ThreadWorkerSummation,input.colptr(i),nrows,result,i,use_kahansum);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor (int i=0;i<ncols;i++){\n\t\t\t\t\t\tthread_list[i].join();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdelete[] thread_list;\n\t\t\t\t}else{\n\t\t\t\t\tthrow std::runtime_error(\"columns must be in range of [0,2000]\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//full Summation use_kahansum=true(for kahansummation) and false for normal summation @param std::vec\n\t\t\ttemplate<typename T>\n\t\t\tstatic T Summation(std::vector<T> input,bool use_kahansum=true){\n\t\t\t\tif (use_kahansum){\n\t\t\t\t\tT sum=0;\n\t\t\t\t\tT c=0;\n\t\t\t\t\tfor (unsigned long long i=0;i<input.size();i++){\n\t\t\t\t\t\tT y=input[i]-c;\n\t\t\t\t\t\tT t=sum+y;\n\t\t\t\t\t\tc=(t-sum)-y;\n\t\t\t\t\t\tsum=t;\n\t\t\t\t\t}\n\t\t\t\t\treturn sum;\n\t\t\t\t}else{\n\t\t\t\t\tT sum=0;\n\t\t\t\t\tfor (int i=0;i<input.size();i++){\n\t\t\t\t\t\tsum+=input[i];\n\t\t\t\t\t}\n\t\t\t\t\treturn sum;\n\t\t\t\t}\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t//Step kahansummation\n\t\t\ttemplate<typename T>\n\t\t\tstatic T StepSummation(T i_input,KahanSumParam<T>& param){\n\t\t\t\tparam.y=i_input-param.c;\n\t\t\t\tparam.t=param.sum+param.y;\n\t\t\t\tparam.c=(param.t-param.sum)-param.y;\n\t\t\t\tparam.sum=param.t;\n\t\t\t\treturn param.sum;\n\t\t\t}\n\n\t\t\t\n\t\t\t//Reseting to recompute stepsummation\n\t\t\ttemplate<typename T>\n\t\t\tstatic void ResetStepSummation(KahanSumParam<T>& param){\n\t\t\t\tparam.sum=0;\n\t\t\t\tparam.y=0;\n\t\t\t\tparam.c=0;\n\t\t\t\tparam.t=0;\n\t\t\t}\n\t\t\t\n\t};\n}", "meta": {"hexsha": "a30f6e1b58ca5829abf63f63040dcf3a4020722e", "size": 3065, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kahansum.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/kahansum.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/kahansum.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.7037037037, "max_line_length": 121, "alphanum_fraction": 0.5859706362, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5828841287847638}}
{"text": "/*******************************************************************************\n * Abstract domain described in Section 4 from the paper \"An Abstract\n * Domain of Uninterpreted Functions\" by Gange, Navas, Schachte,\n * Sondergaard, and Stuckey published in VMCAI'16.\n *\n * Each program variable is mapped to a syntactic term (aka\n * uninterpreted function). The join is antiunification and the meet\n * is a pseudo-meet based on the classical congruence closure\n * algorithm. The domain is suitable to infer equalities between\n * variables.\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/term/term_expr.hpp>\n#include <crab/domains/term/term_operators.hpp>\n#include <crab/support/debug.hpp>\n#include <crab/support/stats.hpp>\n\n#include <algorithm>\n#include <map>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <boost/container/flat_map.hpp>\n#include <boost/container/flat_set.hpp>\n#include <boost/optional.hpp>\n\nnamespace crab {\nnamespace domains {\n\n// TODO: factorize code. uf_domain and term_domain share a lot of\n// code.\ntemplate <typename Number, typename VariableName>\nclass uf_domain final\n    : public abstract_domain_api<uf_domain<Number, VariableName>> {\n\n  using uf_domain_t = uf_domain<Number, VariableName>;\n  using abstract_domain_t = abstract_domain_api<uf_domain_t>;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using number_t = Number;\n  using varname_t = VariableName;\n\nprivate:\n  using ttbl_t = term::term_table<number_t, term::term_operator_t>;\n  using term_id_t = typename ttbl_t::term_id_t;\n  using term_t = typename ttbl_t::term_t;\n  using const_term_t = typename ttbl_t::const_term_t;\n  using var_term_t = typename ttbl_t::var_term_t;\n  using ftor_term_t = typename ttbl_t::ftor_term_t;\n\n  using var_map_t = boost::container::flat_map<variable_t, term_id_t>;\n  using var_set_t = std::set<variable_t>;\n  using rev_var_map_t = boost::container::flat_map<term_id_t, var_set_t>;\n  using linterm_t = typename linear_expression_t::component_t;\n\n  bool m_is_bottom;\n  ttbl_t m_ttbl;\n  var_map_t m_var_map;\n  rev_var_map_t m_rev_var_map;\n\n  uf_domain(bool is_top) : m_is_bottom(!is_top) {}\n\n  uf_domain(ttbl_t &&tbl, var_map_t &&vm, rev_var_map_t &&rvm)\n      : m_is_bottom(false), m_ttbl(std::move(tbl)), m_var_map(std::move(vm)),\n        m_rev_var_map(std::move(rvm)) {\n    check_terms(__LINE__);\n  }\n\n  void check_terms(int line) const {\n    CRAB_LOG(\n        \"uf-check-terms\",\n        for (auto const &p\n             : m_var_map) {\n          if (!(p.second < m_ttbl.size())) {\n            CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \",\n                       \"term id is not the table term\");\n          }\n        }\n\n        for (auto kv\n             : m_rev_var_map) {\n          for (auto v : kv.second) {\n            auto it = m_var_map.find(v);\n            if (it->second != kv.first) {\n              CRAB_ERROR(\"term_equiv.hpp at line=\", line, \": \", v,\n                         \" is mapped to t\", it->second,\n                         \" but the reverse map says that should be t\",\n                         kv.first);\n            }\n          }\n        });\n  }\n\n  void deref(term_id_t t) {\n    std::vector<term_id_t> forgotten /*unused*/;\n    m_ttbl.deref(t, forgotten);\n  }\n\n  /* Begin manipulate the reverse variable map */\n  void add_rev_var_map(rev_var_map_t &rvmap, term_id_t t, variable_t v) const {\n    auto it = rvmap.find(t);\n    if (it != rvmap.end()) {\n      it->second.insert(v);\n    } else {\n      var_set_t varset;\n      varset.insert(v);\n      rvmap.insert(std::make_pair(t, varset));\n    }\n  }\n\n  void remove_rev_var_map(term_id_t t, const variable_t &v) {\n    auto it = m_rev_var_map.find(t);\n    if (it != m_rev_var_map.end()) {\n      it->second.erase(v);\n      if (it->second.empty()) {\n        m_rev_var_map.erase(it);\n      }\n    }\n  }\n  /* End manipulate the reverse variable map */\n\n  const term_t &get_term(term_id_t t) const {\n    const term_t *ptr_t = m_ttbl.get_term_ptr(t);\n    assert(ptr_t);\n    return *ptr_t;\n  }\n\n  void rebind_var(const variable_t &x, term_id_t tx) {\n    m_ttbl.add_ref(tx);\n\n    auto it(m_var_map.find(x));\n    if (it != m_var_map.end()) {\n      remove_rev_var_map((*it).second, x);\n      deref((*it).second);\n      m_var_map.erase(it);\n    }\n    m_var_map.insert(std::make_pair(x, tx));\n    add_rev_var_map(m_rev_var_map, tx, x);\n  }\n\n  term_id_t term_of_const(const number_t &n) {\n    boost::optional<term_id_t> opt_tn(m_ttbl.find_const(n));\n    if (opt_tn) {\n      return *opt_tn;\n    } else {\n      return m_ttbl.make_const(n);\n    }\n  }\n\n  term_id_t term_of_var(variable_t v, var_map_t &var_map,\n                        rev_var_map_t &rvar_map, ttbl_t &ttbl) {\n    auto it(var_map.find(v));\n    if (it != var_map.end()) {\n      // assert((*it).first == v);\n      assert(ttbl.size() > (*it).second);\n      return (*it).second;\n    } else {\n      // Allocate a fresh term\n      term_id_t id(ttbl.fresh_var());\n      var_map[v] = id;\n      add_rev_var_map(rvar_map, id, v);\n      ttbl.add_ref(id);\n      return id;\n    }\n  }\n\n  term_id_t term_of_var(variable_t v) {\n    return term_of_var(v, m_var_map, m_rev_var_map, m_ttbl);\n  }\n\n  term_id_t term_of_linterm(linterm_t term) {\n    if (term.first == 1) {\n      return term_of_var(term.second);\n    } else {\n      return build_term(term::conv2termop(OP_MULTIPLICATION),\n                        term_of_const(term.first), term_of_var(term.second));\n    }\n  }\n\n  term_id_t build_term(term::term_operator_t op, term_id_t tx) {\n    std::vector<term_id_t> ids = {tx};\n    return build_term(op, ids);\n  }\n  \n  term_id_t build_term(term::term_operator_t op, term_id_t tx, term_id_t ty) {\n    std::vector<term_id_t> ids = {tx,ty};\n    return build_term(op, ids);\n  }\n      \n  term_id_t build_term(term::term_operator_t op, const std::vector<term_id_t> &ids) {\n    boost::optional<term_id_t> eopt(m_ttbl.find_ftor(op, ids));\n    if (eopt) {\n      return *eopt;\n    } else {\n      term_id_t tx = m_ttbl.apply_ftor(op, ids);\n      return tx;\n    }\n  }\n\n  term_id_t build_linexpr(const linear_expression_t &e) {\n    number_t cst = e.constant();\n    typename linear_expression_t::const_iterator it(e.begin());\n    if (it == e.end()) {\n      return term_of_const(cst);\n    }\n\n    term_id_t t;\n    if (cst == 0) {\n      t = term_of_linterm(*it);\n      ++it;\n    } else {\n      t = term_of_const(cst);\n    }\n    for (; it != e.end(); ++it) {\n      t = build_term(term::conv2termop(OP_ADDITION), t, term_of_linterm(*it));\n    }\n\n    return t;\n  }\n\n  boost::optional<std::pair<variable_t, variable_t>>\n  get_eq_or_diseq(linear_constraint_t cst) {\n    if (cst.is_equality() || cst.is_disequation()) {\n      if (cst.size() == 2 && cst.constant() == 0) {\n        auto it = cst.begin();\n        auto nx = it->first;\n        auto vx = it->second;\n        ++it;\n        assert(it != cst.end());\n        auto ny = it->first;\n        auto vy = it->second;\n        if (nx == (ny * -1)) {\n          return std::make_pair(vx, vy);\n        }\n      }\n    }\n    return boost::optional<std::pair<variable_t, variable_t>>();\n  }\n\n  // helper for pseudo-meet: choose one non-var term from the\n  // equivalence class associated with t.\n  template <typename Range>\n  boost::optional<term_id_t> choose_non_var(ttbl_t &ttbl,\n                                            const Range &terms) const {\n    std::vector<term_id_t> non_var_terms(terms.size());\n    auto it = std::copy_if(terms.begin(), terms.end(), non_var_terms.begin(),\n                           [&ttbl](term_id_t t) {\n                             term_t *t_ptr = ttbl.get_term_ptr(t);\n                             return (t_ptr && t_ptr->kind() == term::TERM_APP);\n                           });\n    non_var_terms.resize(std::distance(non_var_terms.begin(), it));\n    if (non_var_terms.empty()) {\n      return boost::optional<term_id_t>();\n    } else {\n      // TODO: the heuristics as described in the VMCAI'16 paper\n      // that chooses the one that has more references each class.\n      return *(non_var_terms.begin());\n    }\n  }\n\n  // helper for pseudo-meet\n  term_id_t build_dag_term(ttbl_t &ttbl, int t,\n                           term::congruence_closure_solver<ttbl_t> &solver,\n                           ttbl_t &out_ttbl, std::vector<int> &stack,\n                           std::map<int, term_id_t> &cache) const {\n\n    // already processed\n    auto it = cache.find(t);\n    if (it != cache.end()) {\n      CRAB_LOG(\"uf-meet\", crab::outs() << \"build_dag_term. Found in cache: \";\n               crab::outs() << \"t\" << t << \" --> \"\n                            << \"t\" << it->second << \"\\n\";);\n      return it->second;\n    }\n\n    // break the cycle with a fresh variable\n    if (std::find(stack.begin(), stack.end(), t) != stack.end()) {\n      term_id_t v = out_ttbl.fresh_var();\n      CRAB_LOG(\"uf-meet\", crab::outs() << \"build_dag_term. Detected cycle: \";\n               crab::outs() << \"t\" << t << \" --> \"\n                            << \"t\" << v << \"\\n\";);\n      return v;\n    }\n\n    stack.push_back(t);\n    auto membs = solver.get_members(t);\n    boost::optional<term_id_t> f = choose_non_var(ttbl, membs);\n\n    if (!f) {\n      // no concrete definition exists return a fresh variable\n      term_id_t v = out_ttbl.fresh_var();\n      auto res = cache.insert(std::make_pair(t, v));\n      stack.pop_back();\n      CRAB_LOG(\"uf-meet\", crab::outs()\n                              << \"build_dag_term. No concrete definition: \";\n               crab::outs() << \"t\" << t << \" --> \"\n                            << \"t\" << (res.first)->second << \"\\n\";);\n      return (res.first)->second;\n    } else {\n      // traverse recursively the term\n      term_t *f_ptr = ttbl.get_term_ptr(*f);\n      CRAB_LOG(\"uf-meet\",\n               crab::outs()\n                   << \"build_dag_term. Traversing recursively the term \"\n                   << \"t\" << *f << \":\";\n               crab::outs() << *f_ptr << \"\\n\";);\n      const std::vector<term_id_t> &args(term::term_args(f_ptr));\n      std::vector<term_id_t> res_args;\n      res_args.reserve(args.size());\n      for (term_id_t c : args) {\n        res_args.push_back(build_dag_term(ttbl, solver.get_class(c), solver,\n                                          out_ttbl, stack, cache));\n      }\n      auto res = cache.insert(std::make_pair(\n          t, out_ttbl.apply_ftor(term::term_ftor(f_ptr), res_args)));\n      stack.pop_back();\n      CRAB_LOG(\"uf-meet\", crab::outs()\n                              << \"build_dag_term. Finished recursive case: \";\n               crab::outs() << \"t\" << t << \" --> \"\n                            << \"t\" << (res.first)->second << \"\\n\";);\n      return (res.first)->second;\n    }\n  }\n\n  void print_term(const term_t &t, crab_os &o) const {\n    if (t.kind() == term::TERM_CONST) {\n      const const_term_t *ct = static_cast<const const_term_t *>(&t);\n      o << ct->val;\n    } else if (t.kind() == term::TERM_VAR) {\n      const var_term_t *vt = static_cast<const var_term_t *>(&t);\n      o << \"$VAR_\" << vt->var;\n    } else {\n      assert(t.kind() == term::TERM_APP && \"term should be a function\");\n      const ftor_term_t *ft = static_cast<const ftor_term_t *>(&t);\n      o << ft->ftor << \"(\";\n      for (unsigned i = 0, sz = ft->args.size(); i < sz;) {\n        print_term(get_term(ft->args[i]), o);\n        ++i;\n        if (i < sz) {\n          o << \",\";\n        }\n      }\n      o << \")\";\n    }\n  }\n\npublic:\n  uf_domain_t make_top() const override { return uf_domain_t(true); }\n\n  uf_domain_t make_bottom() const override { return uf_domain_t(false); }\n\n  void set_to_top() override {\n    uf_domain abs(true);\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    uf_domain abs(false);\n    std::swap(*this, abs);\n  }\n\n  uf_domain() : m_is_bottom(false) {}\n\n  uf_domain(const uf_domain_t &o)\n      : m_is_bottom(o.m_is_bottom), m_ttbl(o.m_ttbl), m_var_map(o.m_var_map),\n        m_rev_var_map(o.m_rev_var_map) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    check_terms(__LINE__);\n  }\n\n  uf_domain_t &operator=(const uf_domain_t &o) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n\n    o.check_terms(__LINE__);\n    if (this != &o) {\n      m_is_bottom = o.m_is_bottom;\n      m_ttbl = o.m_ttbl;\n      m_var_map = o.m_var_map;\n      m_rev_var_map = o.m_rev_var_map;\n    }\n    check_terms(__LINE__);\n    return *this;\n  }\n\n  bool is_bottom() const override { return m_is_bottom; }\n\n  bool is_top() const override { return !m_var_map.size() && !is_bottom(); }\n\n  // Lattice operations\n  bool operator<=(const uf_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n\n    if (is_bottom()) {\n      return true;\n    } else if (o.is_bottom()) {\n      return false;\n    } else {\n      // FIXME: avoid this copy\n      uf_domain_t left(*this);\n      uf_domain_t right(o);\n      typename ttbl_t::term_map_t gen_map /*unused*/;\n\n      // Build up the mapping of right onto left, variable by variable.\n      // Assumption: the set of variables in left & right are common.\n      for (auto p : left.m_var_map) {\n        if (!left.m_ttbl.map_leq(right.m_ttbl, left.term_of_var(p.first),\n                                 right.term_of_var(p.first), gen_map))\n          return false;\n      }\n      return true;\n    }\n  }\n\n  void operator|=(const uf_domain_t &o) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n\n    if (is_bottom() || o.is_top()) {\n      *this = o;\n    } else if (o.is_bottom() || is_top()) {\n      return;\n    } else {\n      uf_domain_t right(o);\n      ttbl_t out_tbl;\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n      typename ttbl_t::gener_map_t gener_map /*unused*/;\n\n      for (auto p : m_var_map) {\n        const variable_t &v = p.first;\n        term_id_t tx = p.second;\n        term_id_t ty(right.term_of_var(v));\n        term_id_t tz =\n            m_ttbl.generalize(right.m_ttbl, tx, ty, out_tbl, gener_map);\n        assert(tz < out_tbl.size());\n        out_vmap[v] = tz;\n        add_rev_var_map(out_rvmap, tz, v);\n      }\n\n      for (auto p : out_vmap) {\n        out_tbl.add_ref(p.second);\n      }\n\n      m_is_bottom = false;\n      std::swap(m_ttbl, out_tbl);\n      std::swap(m_var_map, out_vmap);\n      std::swap(m_rev_var_map, out_rvmap);\n    }\n  }\n\n  uf_domain_t operator|(const uf_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n\n    if (is_bottom() || o.is_top()) {\n      return o;\n    } else if (o.is_bottom() || is_top()) {\n      return *this;\n    } else {\n      // FIXME: avoid this copy\n      uf_domain_t left(*this);\n      uf_domain_t right(o);\n      ttbl_t out_tbl;\n      typename ttbl_t::gener_map_t gener_map /*unused*/;\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n\n      // For each program variable in state, compute a generalization.\n      for (auto p : left.m_var_map) {\n        const variable_t &v = p.first;\n        term_id_t tx = p.second;\n        term_id_t ty = right.term_of_var(v);\n        term_id_t tz =\n            left.m_ttbl.generalize(right.m_ttbl, tx, ty, out_tbl, gener_map);\n        assert(tz < out_tbl.size());\n        out_vmap[v] = tz;\n        add_rev_var_map(out_rvmap, tz, v);\n      }\n\n      for (auto p : out_vmap) {\n        out_tbl.add_ref(p.second);\n      }\n\n      uf_domain_t res(std::move(out_tbl), std::move(out_vmap),\n                      std::move(out_rvmap));\n\n      CRAB_LOG(\"uf\", crab::outs() << \"============ JOIN ==================\";\n               crab::outs() << *this << \"\\n----------------\";\n               crab::outs() << o << \"\\n----------------\";\n               crab::outs() << res << \"\\n================\"\n                            << \"\\n\");\n\n      return res;\n    }\n  }\n\n  uf_domain_t operator||(const uf_domain_t &other) const override {\n    return *this | other;\n  }\n\n  uf_domain_t widening_thresholds(\n      const uf_domain_t &other,\n      const iterators::thresholds<number_t> &ts) const override {\n    return *this | other;\n  }\n\n  // Meet\n  uf_domain_t operator&(const uf_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n\n    if (is_bottom() || o.is_top()) {\n      return *this;\n    } else if (is_top() || o.is_bottom()) {\n      return o;\n    } else {\n      ttbl_t out_ttbl(m_ttbl);\n      std::map<term_id_t, term_id_t> copy_map;\n      std::vector<int> stack;\n      std::map<int, term_id_t> cache;\n      var_map_t out_vmap;\n      rev_var_map_t out_rvmap;\n\n      // bring all terms to one ttbl\n      for (auto p : o.m_var_map) {\n        term_id_t tx = p.second;\n        out_ttbl.copy_term(o.m_ttbl, tx, copy_map);\n      }\n\n      // build unifications between terms from this and o\n      std::vector<std::pair<term_id_t, term_id_t>> eqs;\n      for (auto p : m_var_map) {\n        variable_t v(p.first);\n        auto it = o.m_var_map.find(v);\n        if (it != o.m_var_map.end()) {\n          term_id_t tx = p.second;\n          eqs.push_back(std::make_pair(tx, copy_map[it->second]));\n        }\n      }\n\n      // compute equivalence classes\n      term::congruence_closure_solver<ttbl_t> solver(&out_ttbl);\n      solver.run(eqs);\n\n      // new map from variable to an acyclic term\n      for (auto p : m_var_map) {\n        const variable_t &v = p.first;\n        term_id_t t_old = p.second;\n        term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old),\n                                         solver, out_ttbl, stack, cache);\n        out_vmap[v] = t_new;\n        add_rev_var_map(out_rvmap, t_new, v);\n      }\n      for (auto p : o.m_var_map) {\n        variable_t v(p.first);\n        if (out_vmap.find(v) != out_vmap.end())\n          continue;\n        term_id_t t_old(copy_map[p.second]);\n        term_id_t t_new = build_dag_term(out_ttbl, solver.get_class(t_old),\n                                         solver, out_ttbl, stack, cache);\n        out_vmap[v] = t_new;\n        add_rev_var_map(out_rvmap, t_new, v);\n      }\n\n      for (auto p : out_vmap) {\n        out_ttbl.add_ref(p.second);\n      }\n\n      uf_domain_t res(std::move(out_ttbl), std::move(out_vmap),\n                      std::move(out_rvmap));\n\n      CRAB_LOG(\"uf\", crab::outs() << \"============ MEET ==================\";\n               crab::outs() << *this << \"\\n----------------\";\n               crab::outs() << o << \"\\n----------------\";\n               crab::outs() << res << \"\\n================\"\n                            << \"\\n\");\n      return res;\n    }\n  }\n\n  uf_domain_t operator&&(const uf_domain_t &o) const override {\n    return *this & o;\n  }\n\n  // Remove a variable from the scope\n  void operator-=(const variable_t &v) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n\n    auto it(m_var_map.find(v));\n    if (it != m_var_map.end()) {\n      term_id_t t = (*it).second;\n      m_var_map.erase(it);\n      remove_rev_var_map(t, v);\n      deref(t);\n    }\n    CRAB_LOG(\"uf\", crab::outs()\n                       << \"After removing \" << v << \": \" << *this << \"\\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    if (!is_bottom()) {\n      term_id_t tx(build_linexpr(e));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** Assign \" << x << \":=\" << e << \":\"\n                                  << *this << \"\\n\");\n    }\n  }\n\n  // Apply operations to variables.\n\n  // x = y op z\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n    check_terms(__LINE__);\n\n    if (!is_bottom()) {\n      term_id_t tx(\n          build_term(term::conv2termop(op), term_of_var(y), term_of_var(z)));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << z << \":\" << *this << \"\\n\");\n    }\n  }\n\n  // x = y op k\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      term_id_t tx(\n          build_term(term::conv2termop(op), term_of_var(y), term_of_const(k)));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << k << \":\" << *this << \"\\n\");\n    }\n  }\n\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const uf_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_assign\");\n    if (!is_bottom()) {\n      CRAB_WARN(\"backward_assign not implemented by \", domain_name());\n    }\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const uf_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    if (!is_bottom()) {\n      CRAB_WARN(\"backward_apply not implemented by \", domain_name());\n    }\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const uf_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    if (!is_bottom()) {\n      CRAB_WARN(\"backward_apply not implemented by \", domain_name());\n    }\n  }\n\n  void operator+=(const linear_constraint_t &cst) {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n\n    CRAB_LOG(\"uf\", crab::outs()\n                       << \"*** Before assume \" << cst << \":\" << *this << \"\\n\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    using pair_var_t = std::pair<variable_t, variable_t>;\n\n    if (boost::optional<pair_var_t> eq = get_eq_or_diseq(cst)) {\n      term_id_t tx(term_of_var((*eq).first));\n      term_id_t ty(term_of_var((*eq).second));\n      if (cst.is_disequation()) {\n        if (tx == ty) {\n          set_to_bottom();\n          CRAB_LOG(\"uf\", crab::outs() << \"*** After assume \" << cst << \":\"\n                                      << *this << \"\\n\");\n          return;\n        }\n      } else {\n        // not bother if they are already equal\n        if (tx == ty) {\n          return;\n        }\n\n        std::vector<int> stack;\n        std::map<int, term_id_t> cache;\n        // congruence closure to compute equivalence classes\n        term::congruence_closure_solver<ttbl_t> solver(&m_ttbl);\n        std::vector<std::pair<term_id_t, term_id_t>> eqs = {{tx, ty}};\n        solver.run(eqs);\n\n        // new map from variable to an acyclic term\n        for (auto p : m_var_map) {\n          const variable_t &v = p.first;\n          term_id_t t_old(term_of_var(v));\n          term_id_t t_new = build_dag_term(m_ttbl, solver.get_class(t_old),\n                                           solver, m_ttbl, stack, cache);\n          rebind_var(v, t_new);\n        }\n      }\n    }\n\n    CRAB_LOG(\"uf\", crab::outs()\n                       << \"*** After assume \" << cst << \":\" << *this << \"\\n\");\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    for (auto cst : csts) {\n      this->operator+=(cst);\n    }\n  }\n\n  interval_t operator[](const variable_t &x) override {\n    crab::CrabStats::count(domain_name() + \".count.to_intervals\");\n    crab::ScopedCrabStats __st__(domain_name() + \".to_intervals\");\n    if (is_bottom()) {\n      return interval_t::bottom();\n    } else {\n      return interval_t::top();\n    }\n  }\n\n  void apply(int_conv_operation_t /*op*/, const variable_t &dst,\n             const variable_t &src) override {\n    // since reasoning about infinite precision we simply assign and\n    // ignore the widths.\n    assign(dst, src);\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      term_id_t tx(\n          build_term(term::conv2termop(op), term_of_var(y), term_of_var(z)));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << z << \":\" << *this << \"\\n\");\n    }\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      term_id_t tx(\n          build_term(term::conv2termop(op), term_of_var(y), term_of_const(k)));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << k << \":\" << *this << \"\\n\");\n    }\n  }\n\n  /* Array operations */\n\n  virtual void array_init(const variable_t & /*a*/,\n                          const linear_expression_t & /*elem_size*/,\n                          const linear_expression_t & /*lb_idx*/,\n                          const linear_expression_t & /*ub_idx*/,\n                          const linear_expression_t & /*val*/) override {\n    // do nothing\n  }\n\n  virtual void array_load(const variable_t &lhs, const variable_t &a,\n                          const linear_expression_t & /*elem_size*/,\n                          const linear_expression_t &i) override {\n    crab::CrabStats::count(domain_name() + \".count.array_read\");\n    crab::ScopedCrabStats __st__(domain_name() + \".array_read\");\n\n    if (!is_bottom()) {\n      /**\n       *  We treat the array load as an uninterpreted function\n       *  lhs := array_load(a, i) -->  lhs := f(a,i)\n       */\n      term_id_t t_uf(\n          build_term(term::TERM_OP_FUNCTION, term_of_var(a), build_linexpr(i)));\n      rebind_var(lhs, t_uf);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << lhs << \":=\" << a << \"[\" << i << \"]  -- \"\n                                  << *this << \"\\n\";);\n    }\n  }\n\n  virtual void array_store(const variable_t &a,\n                           const linear_expression_t & /*elem_size*/,\n                           const linear_expression_t &i,\n                           const linear_expression_t &val,\n                           bool /*is_strong_update*/) override {\n    // do nothing\n  }\n\n  virtual void array_store_range(const variable_t &a,\n                                 const linear_expression_t &elem_size,\n                                 const linear_expression_t &i,\n                                 const linear_expression_t &j,\n                                 const linear_expression_t &v) override {\n    // do nothing\n  }\n\n  virtual void array_assign(const variable_t &lhs,\n                            const variable_t &rhs) override {\n    // do nothing\n  }\n\n  // backward array operations\n  void backward_array_init(const variable_t &a,\n                           const linear_expression_t &elem_size,\n                           const linear_expression_t &lb_idx,\n                           const linear_expression_t &ub_idx,\n                           const linear_expression_t &val,\n                           const uf_domain_t &invariant) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n  void backward_array_load(const variable_t &lhs, const variable_t &a,\n                           const linear_expression_t &elem_size,\n                           const linear_expression_t &i,\n                           const uf_domain_t &invariant) override {\n    *this -= lhs;\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n  void backward_array_store(const variable_t &a,\n                            const linear_expression_t &elem_size,\n                            const linear_expression_t &i,\n                            const linear_expression_t &v, bool is_strong_update,\n                            const uf_domain_t &invariant) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n  void backward_array_store_range(const variable_t &a,\n                                  const linear_expression_t &elem_size,\n                                  const linear_expression_t &i,\n                                  const linear_expression_t &j,\n                                  const linear_expression_t &v,\n                                  const uf_domain_t &invariant) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n  void backward_array_assign(const variable_t &lhs, const variable_t &rhs,\n                             const uf_domain_t &invariant) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n\n  DEFAULT_SELECT(uf_domain_t)\n\n  // boolean operators\n  virtual void assign_bool_cst(const variable_t &lhs,\n                               const linear_constraint_t &rhs) override {\n    // TODO\n    operator-=(lhs);\n  }\n\n  virtual void assign_bool_ref_cst(const variable_t &lhs,\n                                   const reference_constraint_t &rhs) override {\n    // TODO\n    operator-=(lhs);\n  }\n\n  virtual void assign_bool_var(const variable_t &lhs, const variable_t &rhs,\n                               bool is_not_rhs) override {\n    crab::CrabStats::count(domain_name() + \".count.assign_bool_var\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign_bool_var\");\n\n    if (!is_bottom()) {\n      check_terms(__LINE__);\n      if (is_not_rhs) {\n        term_id_t tx(build_term(term::TERM_OP_NOT, term_of_var(rhs)));\n        rebind_var(lhs, tx);\n      } else {\n        term_id_t tx(term_of_var(rhs));\n        rebind_var(lhs, tx);\n      }\n      check_terms(__LINE__);\n\n      CRAB_LOG(\n          \"uf\", crab::outs() << \"*** \" << lhs << \":=\"; if (is_not_rhs) {\n            crab::outs() << \"not(\" << rhs << \")\";\n          } else { crab::outs() << rhs; } crab::outs() << \":\"\n                                                       << *this << \"\\n\");\n    }\n  }\n\n  virtual void apply_binary_bool(bool_operation_t op, const variable_t &x,\n                                 const variable_t &y,\n                                 const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply_binary_bool\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply_binary_bool\");\n\n    if (!is_bottom()) {\n      check_terms(__LINE__);\n      term_id_t tx(\n          build_term(term::conv2termop(op), term_of_var(y), term_of_var(z)));\n      rebind_var(x, tx);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << \"*** \" << x << \":=\" << y << \" \" << op\n                                  << \" \" << z << \":\" << *this << \"\\n\");\n    }\n  }\n\n  virtual void assume_bool(const variable_t &v, bool is_negated) override {\n    // do nothing\n  }\n\n  void select_bool(const variable_t &lhs, const variable_t &cond,\n                   const variable_t &b1, const variable_t &b2) override {\n    operator-=(lhs);\n  }\n\n  // backward boolean operators\n  virtual void backward_assign_bool_cst(const variable_t &lhs,\n                                        const linear_constraint_t &rhs,\n                                        const uf_domain_t &inv) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n\n  virtual void backward_assign_bool_ref_cst(const variable_t &lhs,\n                                            const reference_constraint_t &rhs,\n                                            const uf_domain_t &inv) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n\n  virtual void backward_assign_bool_var(const variable_t &lhs,\n                                        const variable_t &rhs, bool is_not_rhs,\n                                        const uf_domain_t &inv) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n\n  virtual void backward_apply_binary_bool(bool_operation_t op,\n                                          const variable_t &x,\n                                          const variable_t &y,\n                                          const variable_t &z,\n                                          const uf_domain_t &inv) override {\n    CRAB_WARN(domain_name(), \" does not implement backward operations\");\n  }\n\n  // Region operations\n  virtual void region_init(const variable_t &reg) override {\n    // do nothing\n  }\n\n  virtual void region_copy(const variable_t &lhs_reg,\n                           const variable_t &rhs_reg) override {\n    // do nothing\n  }\n\n  virtual void region_cast(const variable_t &src_reg,\n                           const variable_t &dst_reg) override {\n    // do nothing\n  }\n\n  virtual void ref_make(const variable_t &ref, const variable_t &reg,\n                        const variable_or_constant_t &size,\n                        const allocation_site &as) override {\n    // do nothing\n  }\n\n  virtual void ref_free(const variable_t &reg, const variable_t &ref) override {\n    // do nothing\n  }\n\n  virtual void ref_load(const variable_t &ref, const variable_t &reg,\n                        const variable_t &res) override {\n    crab::CrabStats::count(domain_name() + \".count.ref_load\");\n    crab::ScopedCrabStats __st__(domain_name() + \".ref_load\");\n\n    if (!is_bottom()) {\n      /**\n       *  We treat the load as an uninterpreted function:\n       *  res := ref_load(reg, ref) -->  res := f(reg,ref)\n       */\n      term_id_t t_uf(build_term(term::TERM_OP_FUNCTION, term_of_var(reg),\n                                build_linexpr(ref)));\n      rebind_var(res, t_uf);\n      check_terms(__LINE__);\n      CRAB_LOG(\"uf\", crab::outs() << res << \":=ref_load(\" << reg << \",\" << ref\n                                  << \")  -- \" << *this << \"\\n\";);\n    }\n  }\n\n  virtual void ref_store(const variable_t &ref, const variable_t &reg,\n                         const variable_or_constant_t &val) override {\n    // do nothing\n  }\n\n  virtual void ref_gep(const variable_t &ref1, const variable_t &reg1,\n                       const variable_t &ref2, const variable_t &reg2,\n                       const linear_expression_t &offset) override {\n    // do nothing\n  }\n\n  virtual void\n  ref_load_from_array(const variable_t &lhs, const variable_t &ref,\n                      const variable_t &region,\n                      const linear_expression_t &index,\n                      const linear_expression_t &elem_size) override {\n    // TODO\n    // do nothing\n  }\n\n  virtual void ref_store_to_array(const variable_t &ref,\n                                  const variable_t &region,\n                                  const linear_expression_t &index,\n                                  const linear_expression_t &elem_size,\n                                  const linear_expression_t &val) override {\n    // do nothing\n  }\n\n  virtual void ref_assume(const reference_constraint_t &cst) override {\n    // do nothing\n  }\n\n  void ref_to_int(const variable_t &reg, const variable_t &ref_var,\n                  const variable_t &int_var) override {\n    // do nothing\n  }\n\n  void int_to_ref(const variable_t &int_var, const variable_t &reg,\n                  const variable_t &ref_var) override {\n    // do nothing\n  }\n\n  void select_ref(const variable_t &lhs_ref, const variable_t &lhs_rgn,\n                  const variable_t &cond, const variable_or_constant_t &ref1,\n                  const boost::optional<variable_t> &rgn1,\n                  const variable_or_constant_t &ref2,\n                  const boost::optional<variable_t> &rgn2) override {\n    // do nothing\n  }\n\n  boolean_value is_null_ref(const variable_t &ref) override {\n    // do nothing\n    return boolean_value();\n  }\n  bool\n  get_allocation_sites(const variable_t &ref,\n                       std::vector<allocation_site> &alloc_sites) override {\n    // do nothing\n    return false;\n  }\n\n  bool get_tags(const variable_t &rgn, const variable_t &ref,\n                std::vector<uint64_t> &tags) override {\n    // do nothing\n    return false;\n  }\n\n  // Miscellaneous\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    if (is_top() || is_bottom()) {\n      return;\n    }\n\n    CRAB_LOG(\n        \"uf\", crab::outs() << \"Renaming {\"; for (auto v\n                                                 : from) {\n          crab::outs() << v << \";\";\n        } crab::outs() << \"} with \";\n        for (auto v\n             : to) { crab::outs() << v << \";\"; } crab::outs()\n        << \"}:\\n\";\n        crab::outs() << *this << \"\\n\";);\n\n    auto error_if_found = [this](const variable_t &v) {\n      auto it = m_var_map.find(v);\n      if (it != m_var_map.end()) {\n        CRAB_ERROR(domain_name() + \"::rename assumes that \", v,\n                   \" does not exist\");\n      }\n    };\n\n    for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n      const variable_t &v = from[i];\n      const variable_t &new_v = to[i];\n      if (v == new_v) { // nothing to rename\n        continue;\n      }\n\n      error_if_found(new_v);\n\n      auto it = m_var_map.find(v);\n      if (it != m_var_map.end()) {\n        term_id_t id = it->second;\n        m_var_map.erase(it);\n        m_var_map.insert(std::make_pair(new_v, id));\n        remove_rev_var_map(id, v);\n        add_rev_var_map(m_rev_var_map, id, new_v);\n      }\n    }\n    CRAB_LOG(\"uf\", crab::outs() << \"RESULT=\" << *this << \"\\n\");\n  }\n\n  void forget(const variable_vector_t &variables) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    for (auto v : variables) {\n      *this -= v;\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    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    if (variables.empty()) {\n      set_to_top();\n      return;\n    }\n\n    std::set<variable_t> s1, s2;\n    variable_vector_t s3;\n    for (auto p : m_var_map) {\n      s1.insert(p.first);\n    }\n    s2.insert(variables.begin(), variables.end());\n    std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n                        std::back_inserter(s3));\n    forget(s3);\n  }\n\n  void expand(const variable_t &x, const variable_t &y) 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    linear_expression_t e(x);\n    term_id_t tx(build_linexpr(e));\n    rebind_var(y, tx);\n    check_terms(__LINE__);\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name, 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                          const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const uf_domain_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n  /* end intrinsics operations */\n\n  void normalize() override {}\n  void minimize() override {}\n\n  // Output function\n  void write(crab_os &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.write\");\n    crab::ScopedCrabStats __st__(domain_name() + \".write\");\n\n    if (is_bottom()) {\n      o << \"_|_\";\n      return;\n    }\n    if (m_var_map.empty()) {\n      o << \"{}\";\n      return;\n    }\n\n    bool first = true;\n    o << \"{\";\n    for (auto p : m_var_map) {\n      if (first) {\n        first = false;\n      } else {\n        o << \", \";\n      }\n      o << p.first << \" -> \";\n      print_term(get_term(p.second), o);\n    }\n    o << \"}\";\n\n    CRAB_LOG(\"ufo-print-ttbl\",\n             /// For debugging purposes\n             o << \" ttbl={\" << m_ttbl << \"}\\n\";);\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 out_csts;\n    if (is_bottom()) {\n      out_csts += linear_constraint_t::get_false();\n    } else if (!is_top()) {\n      // Extract equalities\n\n      // Seen equalities to avoid adding twice the same.\n      std::set<std::pair<variable_t, variable_t>> seen;\n      for (auto &kv : m_var_map) {\n        const variable_t &x = kv.first;\n        term_id_t tx = kv.second;\n        auto it = m_rev_var_map.find(tx);\n        if (it == m_rev_var_map.end()) {\n          // this shouldn't happen\n          continue;\n        }\n        for (auto var : it->second) {\n          if (var.index() != x.index()) {\n            if (seen.count(std::make_pair(var, x)) <= 0) {\n              seen.insert(std::make_pair(x, var));\n              out_csts += linear_constraint_t(linear_expression_t(x) ==\n                                              linear_expression_t(var));\n            }\n          }\n        }\n      }\n    }\n    return out_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 \"UFDomain\"; }\n}; // class uf_domain\n\ntemplate <typename Number, typename VariableName>\nstruct abstract_domain_traits<uf_domain<Number, VariableName>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n}; // end uf_domain\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "0462dad7e8d31e5dc390a90feb46beb091f6c624", "size": 43747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/uf_domain.hpp", "max_stars_repo_name": "seahorn/crab", "max_stars_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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/uf_domain.hpp", "max_issues_repo_name": "seahorn/crab", "max_issues_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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/uf_domain.hpp", "max_forks_repo_name": "seahorn/crab", "max_forks_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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": 33.7554012346, "max_line_length": 85, "alphanum_fraction": 0.5665759938, "num_tokens": 10781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.58288411746217}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2001-2003 Daniel Nuffer\r\n    http://spirit.sourceforge.net/\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///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Demonstrates parse trees. This is discussed in the\r\n//  \"Trees\" chapter in the Spirit User's Guide.\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n#define BOOST_SPIRIT_DUMP_PARSETREE_AS_XML\r\n\r\n#include <boost/spirit/include/classic_core.hpp>\r\n#include <boost/spirit/include/classic_parse_tree.hpp>\r\n#include <boost/assert.hpp>\r\n\r\n#include <iostream>\r\n#include <stack>\r\n#include <functional>\r\n#include <string>\r\n\r\n#ifdef BOOST_SPIRIT_DUMP_PARSETREE_AS_XML\r\n#include <boost/spirit/include/classic_tree_to_xml.hpp>\r\n#include <map>\r\n#endif\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n// This example shows how to use a parse tree\r\nusing namespace std;\r\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\r\n\r\n// Here's some typedefs to simplify things\r\ntypedef char const*         iterator_t;\r\ntypedef tree_match<iterator_t> parse_tree_match_t;\r\ntypedef parse_tree_match_t::const_tree_iterator iter_t;\r\n\r\ntypedef pt_match_policy<iterator_t> match_policy_t;\r\ntypedef scanner_policies<iteration_policy, match_policy_t, action_policy> scanner_policy_t;\r\ntypedef scanner<iterator_t, scanner_policy_t> scanner_t;\r\ntypedef rule<scanner_t> rule_t;\r\n\r\n//  grammar rules\r\nrule_t expression, term, factor, integer;\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n// Here's the function prototypes that we'll use.  One function for each\r\n// grammar rule.\r\nlong evaluate(const tree_parse_info<>& info);\r\nlong eval_expression(iter_t const& i);\r\nlong eval_term(iter_t const& i);\r\nlong eval_factor(iter_t const& i);\r\nlong eval_integer(iter_t const& i);\r\n\r\nlong evaluate(const tree_parse_info<>& info)\r\n{\r\n    return eval_expression(info.trees.begin());\r\n}\r\n\r\n// i should be pointing to a node created by the expression rule\r\nlong eval_expression(iter_t const& i)\r\n{\r\n    parser_id id = i->value.id();\r\n    BOOST_ASSERT(id == expression.id()); // check the id\r\n\r\n    // first child points to a term, so call eval_term on it\r\n    iter_t chi = i->children.begin();\r\n    long lhs = eval_term(chi);\r\n    for (++chi; chi != i->children.end(); ++chi)\r\n    {\r\n        // next node points to the operator.  The text of the operator is\r\n        // stored in value (a vector<char>)\r\n        char op = *(chi->value.begin());\r\n        ++chi;\r\n        long rhs = eval_term(chi);\r\n        if (op == '+')\r\n            lhs += rhs;\r\n        else if (op == '-')\r\n            lhs -= rhs;\r\n        else\r\n            BOOST_ASSERT(0);\r\n    }\r\n    return lhs;\r\n}\r\n\r\nlong eval_term(iter_t const& i)\r\n{\r\n    parser_id id = i->value.id();\r\n    BOOST_ASSERT(id == term.id());\r\n\r\n    iter_t chi = i->children.begin();\r\n    long lhs = eval_factor(chi);\r\n    for (++chi; chi != i->children.end(); ++chi)\r\n    {\r\n        char op = *(chi->value.begin());\r\n        ++chi;\r\n        long rhs = eval_factor(chi);\r\n        if (op == '*')\r\n            lhs *= rhs;\r\n        else if (op == '/')\r\n            lhs /= rhs;\r\n        else\r\n            BOOST_ASSERT(0);\r\n    }\r\n    return lhs;\r\n}\r\n\r\nlong eval_factor(iter_t const& i)\r\n{\r\n    parser_id id = i->value.id();\r\n    BOOST_ASSERT(id == factor.id());\r\n\r\n    iter_t chi = i->children.begin();\r\n    id = chi->value.id();\r\n    if (id == integer.id())\r\n        return eval_integer(chi->children.begin());\r\n    else if (*(chi->value.begin()) == '(')\r\n    {\r\n        ++chi;\r\n        return eval_expression(chi);\r\n    }\r\n    else if (*(chi->value.begin()) == '-')\r\n    {\r\n        ++chi;\r\n        return -eval_factor(chi);\r\n    }\r\n    else\r\n    {\r\n        BOOST_ASSERT(0);\r\n        return 0;\r\n    }\r\n}\r\n\r\nlong eval_integer(iter_t const& i)\r\n{\r\n    // extract integer (not always delimited by '\\0')\r\n    string integer(i->value.begin(), i->value.end());\r\n\r\n    return strtol(integer.c_str(), 0, 10);\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n\r\n    //  Start grammar definition\r\n    integer     =   lexeme_d[ token_node_d[ (!ch_p('-') >> +digit_p) ] ];\r\n    factor      =   integer\r\n                |   '(' >> expression >> ')'\r\n                |   ('-' >> factor);\r\n    term        =   factor >>\r\n                    *(  ('*' >> factor)\r\n                      | ('/' >> factor)\r\n                    );\r\n    expression  =   term >>\r\n                    *(  ('+' >> term)\r\n                      | ('-' >> term)\r\n                    );\r\n    //  End grammar definition\r\n\r\n\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tThe simplest working calculator...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        const char* first = str.c_str();\r\n\r\n        tree_parse_info<> info = pt_parse(first, expression);\r\n\r\n        if (info.full)\r\n        {\r\n#if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML)\r\n            // dump parse tree as XML\r\n            std::map<parser_id, std::string> rule_names;\r\n            rule_names[integer.id()] = \"integer\";\r\n            rule_names[factor.id()] = \"factor\";\r\n            rule_names[term.id()] = \"term\";\r\n            rule_names[expression.id()] = \"expression\";\r\n            tree_to_xml(cout, info.trees, first, rule_names);\r\n#endif\r\n\r\n            // print the result\r\n            cout << \"parsing succeeded\\n\";\r\n            cout << \"result = \" << evaluate(info) << \"\\n\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"parsing failed\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "a7bf1a55ac4851ef80a7f7fdf20e1343958c1b96", "size": 6204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/classic/example/fundamental/parse_tree_calc1.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/spirit/classic/example/fundamental/parse_tree_calc1.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/spirit/classic/example/fundamental/parse_tree_calc1.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": 29.8269230769, "max_line_length": 92, "alphanum_fraction": 0.4956479691, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.5828817516362583}}
{"text": "﻿#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype>\n#include <sstream>\n#include <memory>\n\nusing namespace std;\n\n#include <boost/lexical_cast.hpp>\n\nstruct Token {\n    enum Type {\n        integer, plus, minus, lparen, rparen\n    } type;\n    string text;\n\n    explicit Token(Type type, const string &text) :\n            type{type}, text{text} {}\n\n    friend ostream &operator<<(ostream &os, const Token &obj) {\n        return os << \"`\" << obj.text << \"`\";\n    }\n};\n\nvector<Token> lex(const string &input) {\n    vector<Token> result;\n\n    for (int i = 0; i < input.size(); ++i) {\n        switch (input[i]) {\n            case '+':\n                result.push_back(Token{Token::plus, \"+\"});\n                break;\n            case '-':\n                result.push_back(Token{Token::minus, \"-\"});\n                break;\n            case '(':\n                result.push_back(Token{Token::lparen, \"(\"});\n                break;\n            case ')':\n                result.push_back(Token{Token::rparen, \")\"});\n                break;\n            default:\n                // number\n                ostringstream buffer;\n                buffer << input[i];\n                for (int j = i + 1; j < input.size(); ++j) {\n                    if (isdigit(input[j])) {\n                        buffer << input[j];\n                        ++i;\n                    } else {\n                        result.push_back(Token{Token::integer, buffer.str()});\n                        break;\n                    }\n                }\n        }\n    }\n\n    return result;\n}\n\n// parsing =====================================================\n\nstruct Element {\n    virtual ~Element() = default;\n\n    virtual int eval() const = 0;\n};\n\nstruct Integer : Element {\n    int value;\n\n    explicit Integer(const int value)\n            : value(value) {\n    }\n\n    int eval() const override { return value; }\n};\n\nstruct BinaryOperation : Element {\n    enum Type {\n        addition, subtraction\n    } type;\n    shared_ptr<Element> lhs, rhs;\n\n    int eval() const override {\n        if (type == addition)\n            return lhs->eval() + rhs->eval();\n        return lhs->eval() - rhs->eval();\n    }\n};\n\nshared_ptr<Element> parse(const vector<Token> &tokens) {\n    auto result = make_unique<BinaryOperation>();\n    bool have_lhs = false;\n    for (size_t i = 0; i < tokens.size(); i++) {\n        auto token = tokens[i];\n        switch (token.type) {\n            case Token::integer: {\n                int value = boost::lexical_cast<int>(token.text);\n                auto integer = make_shared<Integer>(value);\n                if (!have_lhs) {\n                    result->lhs = integer;\n                    have_lhs = true;\n                } else result->rhs = integer;\n            }\n                break;\n            case Token::plus:\n                result->type = BinaryOperation::addition;\n                break;\n            case Token::minus:\n                result->type = BinaryOperation::subtraction;\n                break;\n            case Token::lparen: {\n                int j = i;\n                for (; j < tokens.size(); ++j)\n                    if (tokens[j].type == Token::rparen)\n                        break; // found it!\n\n                vector<Token> subexpression(&tokens[i + 1], &tokens[j]);\n                auto element = parse(subexpression);\n                if (!have_lhs) {\n                    result->lhs = element;\n                    have_lhs = true;\n                } else result->rhs = element;\n                i = j; // advance\n            }\n                break;\n        }\n    }\n    return result;\n}\n\n\nint main() {\n    string input{\"(13-4)-(12+1)\"}; // see if you can make nested braces work\n    auto tokens = lex(input);\n\n    // let's see the tokens\n    for (auto &t : tokens)\n        cout << t << \"   \";\n    cout << endl;\n\n    try {\n        auto parsed = parse(tokens);\n        cout << input << \" = \" << parsed->eval() << endl;\n    }\n    catch (const exception &e) {\n        cout << e.what() << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "ebfad7885cfe193681380c90db59724973fd6b37", "size": 4036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "module06-operation.patterns/interpreter/handmade.cpp", "max_stars_repo_name": "deepcloudlabs/dcl120-2021-aug-19", "max_stars_repo_head_hexsha": "0e322695e78a5668525b9f98da8d4234914d5fb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-13T13:40:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-13T13:40:33.000Z", "max_issues_repo_path": "module06-operation.patterns/interpreter/handmade.cpp", "max_issues_repo_name": "deepcloudlabs/dcl120-2021-aug-19", "max_issues_repo_head_hexsha": "0e322695e78a5668525b9f98da8d4234914d5fb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module06-operation.patterns/interpreter/handmade.cpp", "max_forks_repo_name": "deepcloudlabs/dcl120-2021-aug-19", "max_forks_repo_head_hexsha": "0e322695e78a5668525b9f98da8d4234914d5fb3", "max_forks_repo_licenses": ["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.2077922078, "max_line_length": 78, "alphanum_fraction": 0.4539147671, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5828817474784658}}
{"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 <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"NAOS/constants.hpp\"\n#include \"NAOS/basicMath.hpp\"\n#include \"NAOS/basicAstro.hpp\"\n#include \"NAOS/misc.hpp\"\n#include \"NAOS/ellipsoidGravitationalAcceleration.hpp\"\n\nnamespace naos\n{\n\n//! equations of motion (for a particle around the asteroid modelled as an Ellipsoid)\n/*!\n * first order differential equations describing the motion of a particle or spacecraft around a\n * central body modeled as an ellipsoid using ellipsoid gravitational model.\n */\nclass equationsOfMotionParticleAroundEllipsoid\n{\n    // declare parameters, gravitational parameter and the semi major axes of the ellipsoid\n    const double gravParameter;\n    const double alpha;\n    const double beta;\n    const double gamma;\n    const double zRotation;\n\npublic:\n    // Default constructor with member initializer list\n    equationsOfMotionParticleAroundEllipsoid(\n               const double aGravParameter,\n               const double aAlpha,\n               const double aBeta,\n               const double aGamma,\n               const double aZRotation )\n            : gravParameter( aGravParameter ),\n              alpha( aAlpha ),\n              beta( aBeta ),\n              gamma( aGamma ),\n              zRotation( aZRotation )\n    { }\n    void operator() ( const std::vector< double > &stateVector,\n                      std::vector< double > &dXdt,\n                      const double currentTime )\n    {\n        // calculate the gravitational accelerations first\n        std::vector< double > gravAcceleration( 3, 0.0 );\n\n        computeEllipsoidGravitationalAcceleration( alpha,\n                                                   beta,\n                                                   gamma,\n                                                   gravParameter,\n                                                   stateVector[ xPositionIndex ],\n                                                   stateVector[ yPositionIndex ],\n                                                   stateVector[ zPositionIndex ],\n                                                   gravAcceleration );\n\n        // now calculate the derivatives\n        dXdt[ xPositionIndex ] = stateVector[ xVelocityIndex ];\n        dXdt[ yPositionIndex ] = stateVector[ yVelocityIndex ];\n        dXdt[ zPositionIndex ] = stateVector[ zVelocityIndex ];\n\n        dXdt[ xVelocityIndex ] = gravAcceleration[ xPositionIndex ]\n                                + 2.0 * zRotation * stateVector[ yVelocityIndex ]\n                                + zRotation * zRotation * stateVector[ xPositionIndex ];\n\n        dXdt[ yVelocityIndex ] = gravAcceleration[ yPositionIndex ]\n                                - 2.0 * zRotation * stateVector[ xVelocityIndex ]\n                                + zRotation * zRotation * stateVector[ yPositionIndex ];\n\n        dXdt[ zVelocityIndex ] = gravAcceleration[ zPositionIndex ];\n    }\n};\n\n//! Store intermediate state values and time( if needed )\n/*!\n * This structure contains members that will save all intermediate state values and times when\n * an object of this structure is passed as an argument to the integrator function.\n */\nstruct pushBackStateAndTime\n{\n    // declare containers to store state and time\n    std::vector< std::vector< double > > &stateContainer;\n    std::vector< double > &timeContainer;\n\n    //member initializer list\n    pushBackStateAndTime( std::vector< std::vector< double > > &aState,\n                          std::vector< double > &aTime )\n                : stateContainer( aState ),\n                  timeContainer( aTime )\n    { }\n\n    void operator() ( const std::vector< double > &singleStateVector, const double singleTime )\n    {\n        // store the intermediate state and time values in the containers\n        stateContainer.push_back( singleStateVector );\n        timeContainer.push_back( singleTime );\n    }\n};\n\n//! particle around ellipsoid integration\n/*!\n * integrate the equations of motion for a particle around an ellipsoid. The gravitational accelerations\n * calculated using the ellipsoid gravitational potential model.\n */\nvoid executeParticleAroundEllipsoid( const double alpha,\n                                     const double beta,\n                                     const double gamma,\n                                     const double gravParameter,\n                                     std::vector< double > asteroidRotationVector,\n                                     std::vector< double > &initialOrbitalElements,\n                                     const double initialStepSize,\n                                     const double startTime,\n                                     const double endTime,\n                                     std::ostringstream &outputFilePath,\n                                     const int dataSaveIntervals )\n{\n    //! open the output csv file to save data. Declare file headers.\n    std::ofstream outputFile;\n    outputFile.open( outputFilePath.str( ) );\n    outputFile << \"x\" << \",\";\n    outputFile << \"y\" << \",\";\n    outputFile << \"z\" << \",\";\n    outputFile << \"vx\" << \",\";\n    outputFile << \"vy\" << \",\";\n    outputFile << \"vz\" << \",\";\n    outputFile << \"t\" << std::endl;\n    outputFile.precision( 16 );\n\n    //! convert the initial orbital elements to cartesian state\n    std::vector< double > initialStateInertial( 6, 0.0 );\n    initialStateInertial = convertKeplerianElementsToCartesianCoordinates( initialOrbitalElements,\n                                                                           gravParameter );\n\n    //! account for non-zero start time value and calculate the initial state in body frame\n    double phi = asteroidRotationVector[ zPositionIndex ] * startTime;\n\n    std::vector< double > initialState( 6, 0.0 );\n\n    // get the initial body frame position\n    initialState[ xPositionIndex ]\n            = initialStateInertial[ xPositionIndex ] * std::cos( phi )\n            + initialStateInertial[ yPositionIndex ] * std::sin( phi );\n\n    initialState[ yPositionIndex ]\n            = -1.0 * initialStateInertial[ xPositionIndex ] * std::sin( phi )\n            + initialStateInertial[ yPositionIndex ] * std::cos( phi );\n\n    initialState[ zPositionIndex ] = initialStateInertial[ zPositionIndex ];\n\n    // get the initial body frame velocity\n    std::vector< double > inertialPositionVector = { initialStateInertial[ xPositionIndex ],\n                                                     initialStateInertial[ yPositionIndex ],\n                                                     initialStateInertial[ zPositionIndex ] };\n\n    std::vector< double > omegaCrossPosition( 3, 0.0 );\n    omegaCrossPosition = crossProduct( asteroidRotationVector, inertialPositionVector );\n\n    double xbodyFrameVelocityInertialCoordinates\n                = initialStateInertial[ xVelocityIndex ] - omegaCrossPosition[ 0 ];\n\n    double ybodyFrameVelocityInertialCoordinates\n                = initialStateInertial[ yVelocityIndex ] - omegaCrossPosition[ 1 ];\n\n    double zbodyFrameVelocityInertialCoordinates\n                = initialStateInertial[ zVelocityIndex ] - omegaCrossPosition[ 2 ];\n\n    initialState[ xVelocityIndex ]\n            = xbodyFrameVelocityInertialCoordinates * std::cos( phi )\n            + ybodyFrameVelocityInertialCoordinates * std::sin( phi );\n\n    initialState[ yVelocityIndex ]\n            = -1.0 * xbodyFrameVelocityInertialCoordinates * std::sin( phi )\n            + ybodyFrameVelocityInertialCoordinates * std::cos( phi );\n\n    initialState[ zVelocityIndex] = zbodyFrameVelocityInertialCoordinates;\n\n    // set up boost odeint\n    const double absoluteTolerance = 1.0e-15;\n    const double relativeTolerance = 1.0e-15;\n    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;\n\n    // state step size guess (at each step this initial guess will be used)\n    double stepSizeGuess = initialStepSize;\n\n    // initialize the ode system\n    const double zRotation = asteroidRotationVector[ zPositionIndex ];\n    equationsOfMotionParticleAroundEllipsoid particleAroundEllipsoidProblem( gravParameter,\n                                                                             alpha,\n                                                                             beta,\n                                                                             gamma,\n                                                                             zRotation );\n\n    // initialize current state vector and time\n    std::vector< double > currentStateVector = initialState;\n    double currentTime = startTime;\n    double intermediateEndTime = currentTime + dataSaveIntervals;\n\n    // save the initial state vector\n    outputFile << currentStateVector[ xPositionIndex ] << \",\";\n    outputFile << currentStateVector[ yPositionIndex ] << \",\";\n    outputFile << currentStateVector[ zPositionIndex ] << \",\";\n    outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n    outputFile << currentTime << std::endl;\n\n    // start the integration outer loop\n    while( intermediateEndTime <= endTime )\n    {\n        // perform integration, integrated result stored in currentStateVector\n        size_t steps = boost::numeric::odeint::integrate_adaptive(\n                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),\n                            particleAroundEllipsoidProblem,\n                            currentStateVector,\n                            currentTime,\n                            intermediateEndTime,\n                            stepSizeGuess );\n\n        // update the time variables\n        currentTime = intermediateEndTime;\n        intermediateEndTime = currentTime + dataSaveIntervals;\n\n        // save data\n        outputFile << currentStateVector[ xPositionIndex ] << \",\";\n        outputFile << currentStateVector[ yPositionIndex ] << \",\";\n        outputFile << currentStateVector[ zPositionIndex ] << \",\";\n        outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n        outputFile << currentTime << std::endl;\n\n    } // end of outer while loop for integration\n\n    outputFile.close( );\n}\n\n//! Trajectory calculation for regolith around an asteroid (modelled as ellipsoid here)\n/*!\n * Same as the previous function, except that the initial conditions are now given as a cartesian\n * state. The initial cartesian state should be given in body fixed frame of the asteroid.\n */\nvoid singleRegolithTrajectoryCalculator( const double alpha,\n                                         const double beta,\n                                         const double gamma,\n                                         const double gravParameter,\n                                         std::vector< double > asteroidRotationVector,\n                                         std::vector< double > &initialCartesianStateVector,\n                                         const double initialStepSize,\n                                         const double startTime,\n                                         const double endTime,\n                                         std::ostringstream &outputFilePath,\n                                         const int dataSaveIntervals )\n{\n    //! open the output csv file to save data. Declare file headers.\n    std::ofstream outputFile;\n    outputFile.open( outputFilePath.str( ) );\n    outputFile << \"x\" << \",\";\n    outputFile << \"y\" << \",\";\n    outputFile << \"z\" << \",\";\n    outputFile << \"vx\" << \",\";\n    outputFile << \"vy\" << \",\";\n    outputFile << \"vz\" << \",\";\n    outputFile << \"t\" << std::endl;\n    outputFile.precision( 16 );\n\n    //! get the initial cartesian state vector in a seperate container\n    std::vector< double > initialState = initialCartesianStateVector;\n\n    // set up boost odeint\n    const double absoluteTolerance = 1.0e-15;\n    const double relativeTolerance = 1.0e-15;\n    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;\n\n    // state step size guess (at each step this initial guess will be used)\n    double stepSizeGuess = initialStepSize;\n\n    // initialize the ode system\n    const double zRotation = asteroidRotationVector[ zPositionIndex ];\n    equationsOfMotionParticleAroundEllipsoid particleAroundEllipsoidProblem( gravParameter,\n                                                                             alpha,\n                                                                             beta,\n                                                                             gamma,\n                                                                             zRotation );\n\n    // initialize current state vector and time\n    std::vector< double > currentStateVector = initialState;\n    double currentTime = startTime;\n    double intermediateEndTime = currentTime + dataSaveIntervals;\n\n    // save the initial state vector\n    outputFile << currentStateVector[ xPositionIndex ] << \",\";\n    outputFile << currentStateVector[ yPositionIndex ] << \",\";\n    outputFile << currentStateVector[ zPositionIndex ] << \",\";\n    outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n    outputFile << currentTime << std::endl;\n\n    // start the integration outer loop\n    while( intermediateEndTime <= endTime )\n    {\n        // save the last know state vector for when the particle is outside the asteroid\n        std::vector< double > lastStateVector = currentStateVector;\n\n        // perform integration, integrated result stored in currentStateVector\n        size_t steps = boost::numeric::odeint::integrate_adaptive(\n                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),\n                            particleAroundEllipsoidProblem,\n                            currentStateVector,\n                            currentTime,\n                            intermediateEndTime,\n                            stepSizeGuess );\n\n        //! check if the particle is inside the surface of the asteroid\n        double xSquare = currentStateVector[ xPositionIndex ] * currentStateVector[ xPositionIndex ];\n        double ySquare = currentStateVector[ yPositionIndex ] * currentStateVector[ yPositionIndex ];\n        double zSquare = currentStateVector[ zPositionIndex ] * currentStateVector[ zPositionIndex ];\n\n        double crashCheck = xSquare / ( alpha * alpha )\n                            + ySquare / ( beta * beta )\n                            + zSquare / ( gamma * gamma )\n                            - 1.0;\n\n        if( crashCheck == 0.0 )\n        {\n            // particle is on the surface of the asteroid, save data and stop integration\n            // update the time variables\n            currentTime = intermediateEndTime;\n\n            // save data\n            outputFile << currentStateVector[ xPositionIndex ] << \",\";\n            outputFile << currentStateVector[ yPositionIndex ] << \",\";\n            outputFile << currentStateVector[ zPositionIndex ] << \",\";\n            outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n            outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n            outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n            outputFile << currentTime << std::endl;\n\n            break;\n        }\n\n        if( crashCheck < 0.0 )\n        {\n            double stepSize = 1.0;\n            const double machinePrecision = std::numeric_limits< double >::epsilon( );\n            // if the particle is on the surface of the asteroid, then the while condition\n            // will be false, for all other cases it will be true. Within the while loop, the\n            // inside or outside differnetiation takes place.\n            while( std::fabs( crashCheck ) > machinePrecision )\n            {\n                // std::cout << \"crash check value = \" << crashCheck << std::endl;\n                if( crashCheck < 0.0 ) // particle is still inside the surface\n                {\n                    // std::cout << \"particle inside the surface\" << std::endl << std::endl;\n                    // particle is inside the surface of the asteroid. restart the integration from last\n                    // known state external to the asteroid\n                    currentStateVector = lastStateVector;\n                    stepSize = 0.5 * stepSize;\n                }\n                else // particle is outside the asteroid at the end of last integration step\n                {\n                    // std::cout << \"particle outside the surface\" << std::endl << std::endl;\n                    lastStateVector = currentStateVector;\n                    currentTime = intermediateEndTime;\n                }\n\n                typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > errorStepperType;\n                intermediateEndTime =  boost::numeric::odeint::integrate_n_steps(\n                                                errorStepperType( ),\n                                                particleAroundEllipsoidProblem,\n                                                currentStateVector,\n                                                currentTime,\n                                                stepSize,\n                                                1 );\n\n                xSquare = currentStateVector[ xPositionIndex ] * currentStateVector[ xPositionIndex ];\n                ySquare = currentStateVector[ yPositionIndex ] * currentStateVector[ yPositionIndex ];\n                zSquare = currentStateVector[ zPositionIndex ] * currentStateVector[ zPositionIndex ];\n\n                crashCheck = xSquare / ( alpha * alpha )\n                            + ySquare / ( beta * beta )\n                            + zSquare / ( gamma * gamma )\n                            - 1.0;\n            }\n\n            // particle is on the surface of the asteroid, save data and stop integration\n            // update the time variables\n            currentTime = intermediateEndTime;\n\n            // save data\n            outputFile << currentStateVector[ xPositionIndex ] << \",\";\n            outputFile << currentStateVector[ yPositionIndex ] << \",\";\n            outputFile << currentStateVector[ zPositionIndex ] << \",\";\n            outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n            outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n            outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n            outputFile << currentTime << std::endl;\n\n            break;\n        }\n\n        // update the time variables\n        currentTime = intermediateEndTime;\n        intermediateEndTime = currentTime + dataSaveIntervals;\n\n        // save data\n        outputFile << currentStateVector[ xPositionIndex ] << \",\";\n        outputFile << currentStateVector[ yPositionIndex ] << \",\";\n        outputFile << currentStateVector[ zPositionIndex ] << \",\";\n        outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n        outputFile << currentTime << std::endl;\n\n    } // end of outer while loop for integration\n\n    outputFile.close( );\n}\n\n} // namespace naos\n", "meta": {"hexsha": "d0a98dfb257867c8bde153885aa550aa94c1203f", "size": 19866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particleAroundUniformlyRotatingEllipsoid.cpp", "max_stars_repo_name": "agrawalabhishek/NAOS", "max_stars_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/particleAroundUniformlyRotatingEllipsoid.cpp", "max_issues_repo_name": "agrawalabhishek/NAOS", "max_issues_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particleAroundUniformlyRotatingEllipsoid.cpp", "max_forks_repo_name": "agrawalabhishek/NAOS", "max_forks_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_forks_repo_licenses": ["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.6689655172, "max_line_length": 113, "alphanum_fraction": 0.5731903755, "num_tokens": 3660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.5827458726479833}}
{"text": "// SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: Copyright 2019-2022 Heal Research\n\n#include <numeric>\n#include \"operon/operators/non_dominated_sorter.hpp\"\n#include \"operon/core/individual.hpp\"\n#include <Eigen/Core>\n\nnamespace Operon {\n    using Vec = Eigen::Matrix<int64_t, -1, 1, Eigen::ColMajor>;\n    using Mat = Eigen::Matrix<int64_t, -1, -1, Eigen::ColMajor>;\n\n    inline auto ComputeComparisonMatrix(Operon::Span<Operon::Individual const> pop, Mat const& idx, Eigen::Index colIdx) noexcept\n    {\n        auto const n = static_cast<Eigen::Index>(pop.size());\n        Mat c = Mat::Zero(n, n);\n        Mat::ConstColXpr b = idx.col(colIdx);\n        c.row(b(0)).fill(1); // NOLINT\n        for (auto i = 1; i < n; ++i) {\n            if (pop[b(i)][colIdx] == pop[b(i-1)][colIdx]) {\n                c.row(b(i)) = c.row(b(i-1));\n            } else {\n                for (auto j = i; j < n; ++j) {\n                    c(b(i), b(j)) = 1;\n                }\n            }\n        }\n        return c;\n    }\n\n    inline auto ComparisonMatrixSum(Operon::Span<Operon::Individual const> pop, Mat const& idx) noexcept {\n        Mat d = ComputeComparisonMatrix(pop, idx, 0);\n        for (int i = 1; i < idx.cols(); ++i) {\n            d.noalias() += ComputeComparisonMatrix(pop, idx, i);\n        }\n        return d;\n    }\n\n    inline auto ComputeDegreeMatrix(Operon::Span<Operon::Individual const> pop, Mat const& idx) noexcept\n    {\n        auto const n = static_cast<Eigen::Index>(pop.size());\n        auto const m = static_cast<Eigen::Index>(pop.front().Fitness.size());\n        Mat d = ComparisonMatrixSum(pop, idx);\n        for (auto i = 0; i < n; ++i) {\n            for (auto j = i; j < n; ++j) {\n                if (d(i, j) == m && d(j, i) == m) {\n                    d(i, j) = d(j, i) = 0;\n                }\n            }\n        }\n        return d;\n    }\n\n\n    auto DominanceDegreeSorter::Sort(Operon::Span<Operon::Individual const> pop, Operon::Scalar eps) const -> NondominatedSorterBase::Result\n    {\n        auto const n = static_cast<Eigen::Index>(pop.size());\n        auto const m = static_cast<Eigen::Index>(pop.front().Fitness.size());\n\n        Operon::Less cmp;\n        Mat idx = Vec::LinSpaced(n, 0, n-1).replicate(1, m);\n        for (auto i = 0; i < m; ++i) {\n            auto *data = idx.col(i).data();\n            std::sort(data, data + n, [&](auto a, auto b) { return cmp(pop[a][i], pop[b][i], eps); });\n        }\n        Mat d = ComputeDegreeMatrix(pop, idx);\n        auto count = 0L; // number of assigned solutions\n        std::vector<std::vector<size_t>> fronts;\n        std::vector<size_t> tmp(n);\n        std::iota(tmp.begin(), tmp.end(), 0UL);\n\n        std::vector<size_t> remaining;\n        while (count < n) {\n            std::vector<size_t> front;\n            for (auto i : tmp) {\n                if (std::all_of(tmp.begin(), tmp.end(), [&](auto j) { return d(j, i) < m; })) {\n                    front.push_back(i);\n                } else {\n                    remaining.push_back(i);\n                }\n            }\n            tmp.swap(remaining);\n            remaining.clear();\n            count += static_cast<int64_t>(front.size());\n            fronts.push_back(front);\n        }\n        return fronts;\n    }\n} // namespace Operon\n", "meta": {"hexsha": "5f2bb4a2fff97b69b8bdc2afb49293a9e2ea0eab", "size": 3265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/operators/non_dominated_sorter/dominance_degree_sort.cpp", "max_stars_repo_name": "ivor-dd/operon", "max_stars_repo_head_hexsha": "57775816304b5df7a2f64e1505693a1fdf17a2fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T09:36:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T08:31:37.000Z", "max_issues_repo_path": "source/operators/non_dominated_sorter/dominance_degree_sort.cpp", "max_issues_repo_name": "ivor-dd/operon", "max_issues_repo_head_hexsha": "57775816304b5df7a2f64e1505693a1fdf17a2fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-24T20:02:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-14T10:07:18.000Z", "max_forks_repo_path": "source/operators/non_dominated_sorter/dominance_degree_sort.cpp", "max_forks_repo_name": "ivor-dd/operon", "max_forks_repo_head_hexsha": "57775816304b5df7a2f64e1505693a1fdf17a2fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-29T05:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-31T06:48:52.000Z", "avg_line_length": 36.2777777778, "max_line_length": 140, "alphanum_fraction": 0.5182235835, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5827059184606441}}
{"text": "#include <Eigen/Core>\n#include <opencv2/opencv.hpp>\n#include <pangolin/pangolin.h>\n#include <string>\n#include <unistd.h>\n#include <vector>\n\nusing namespace std;\nusing namespace Eigen;\n\n// Load the images\nstring left_file = \"./left.png\";\nstring right_file = \"./right.png\";\n\n// Method in pangolin to plot the grayscale pointcloud\nvoid showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);\n\nint main(int argc, char **argv) {\n\n  // 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 as grayscales and get the disparity map\n  cv::Mat left = cv::imread(left_file, 0);\n  cv::Mat right = cv::imread(right_file, 0);\n  // Semi global block matching to get the disparity maps\n  // Very parameter dependent, read the paper to understand\n  cv::Ptr<cv::StereoSGBM> sgbm =\n      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);\n\n  // Vector to store the pointcloud\n  vector<Vector4d, Eigen::aligned_allocator<Vector4d>> pointcloud;\n\n  // Cycle through th pixels\n  for (int v = 0; v < left.rows; v++)\n    for (int u = 0; u < left.cols; u++) {\n      // Check if the disparity (which is in pixels) is valid\n      if (disparity.at<float>(v, u) <= 0.0 || disparity.at<float>(v, u) >= 96.0) continue;\n\n      // Initialize the position an the grayscale value\n      Vector4d point(0, 0, 0, left.at<uchar>(v, u) / 255.0);\n\n      // Steps to get pointcloud:\n      // - Get the depth using the fx (in pixels), the disparity (in pixels) and\n      // the baseline (in meters)\n      // Get the normalized coordinates which are basically projections on plane z=1\n      // Multiply the x,y coordinates with the depth and th z coordinate is the depth\n      double depth = fx * b / (disparity.at<float>(v, u));\n      double x = (u - cx) / fx;\n      double y = (v - cy) / fy;\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  // Show the pointcloud in pangolin\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  pangolin::View &d_cam =\n      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}\n", "meta": {"hexsha": "b21dc42c51a4953b243e6cc1a1c637eabedbe7c7", "size": 3453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch5/stereo/stereoVision.cpp", "max_stars_repo_name": "RachitB11/slambook2", "max_stars_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch5/stereo/stereoVision.cpp", "max_issues_repo_name": "RachitB11/slambook2", "max_issues_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch5/stereo/stereoVision.cpp", "max_forks_repo_name": "RachitB11/slambook2", "max_forks_repo_head_hexsha": "71364203ecd0bd0f2dd6e9d9bd4bd80f049bbfc4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6788990826, "max_line_length": 93, "alphanum_fraction": 0.6458152331, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5827058906482551}}
{"text": "#include \"libs/experiments/ROC.h\"\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/algorithm/copy.hpp>\n#include <math.h>\n#include <utility>\n#include <tuple>\n#include <iostream>\n#include <iterator>\n#include  <stdexcept>\n\nnamespace exprs\n{\n\nvalue_type accuracy(value_type threshold, const std::vector<int>& true_val, \n        const data_array& pred)\n{\n    static const value_type eps = 1.0e-10;\n    int a  = 0,b = 0,c = 0, d = 0;\n    for (int item = 0; item < (int)true_val.size(); item++) {\n        if (true_val[item] == 1) {\n            if (pred[item] >= threshold) {\n                a++;\n            } else {\n                b++;\n            }\n        } else {\n            if (pred[item] >= threshold) {\n                c++;\n            } else {\n                d++;\n            }\n        }\n    }\n    return( ((value_type)(a+d)) / (((value_type)(a+b+c+d)) + eps) );\n}\n\nint partition(int p, int r, std::vector<int>& true_val, data_array& pred)\n{\n    \n    value_type x = pred[p];\n    if (p >= (int)pred.size() || p < 0) {\n        throw std::runtime_error{\"cannot partition lower limit - out of range between \" + std::to_string(pred.size()) + \n            \" and \" + std::to_string(p)};\n    }\n    if (r <= 0 || r >= (int)pred.size()) {\n       throw std::runtime_error{\"cannot partition upper limit - out of range between \" + std::to_string(r) +\n                \" and \" + std::to_string(pred.size())};\n    } \n    int i = p - 1;\n    int j = r + 1;\n    while (true) {\n        do j--; while (j > -1 && pred[j] > x);\n        if (j < 0) {\n            throw std::runtime_error{\"invalid value given no value less than \" + std::to_string(x) + \" found\"};\n        }\n        do i++; while (i < (int)pred.size() && pred[i] < x );\n        if (i == (int)pred.size()) {\n            throw std::runtime_error{\"invalid value given no value greater than \" + std::to_string(x) + \" found\"};\n        }\n        if (i < j) {\n            std::swap(pred[i], pred[j]);\n            std::swap(true_val[i], true_val[j]);\n        } else {\n            return j;\n        }\n    }\n}\n\nvoid quicksort(int p, int r, std::vector<int>& true_val, data_array& pred)\n{\n    if (p < r) {\n        int q = partition(p, r, true_val, pred);\n        quicksort(p, q, true_val, pred);\n        quicksort(q+1, r, true_val, pred);\n    }\n}\n\ntemplate<typename T>\nvalue_type calculateRmse(const std::vector<T>& true_val, const data_array& pred,\n        value_type& mean_true)\n{\n    value_type sse = 0.0;\n    for(int no_item = 0; no_item < (int)true_val.size(); ++no_item) {\n        value_type p1 = pred[no_item];\n        sse+= (true_val[no_item]-p1)*(true_val[no_item]-p1);\n        mean_true += true_val[no_item];\n    }\n    mean_true /= (value_type) true_val.size();\n    return  sqrt(sse / ((value_type)true_val.size()));\n    \n}\nstd::tuple<value_type, value_type, \n    data_array, data_array>\ndo_calculation(ROC::algo_params&& calc_params)\n{\n    // now let's do the ROC cruve and area \n    quicksort(0, (int)(calc_params.partitions.size() - 1u), calc_params.partitions, calc_params.predictions);\n    auto total_0 = calc_params.predictions.size() - calc_params.condition_pos;\n    auto tt = 0;\n    auto tf = calc_params.condition_pos;\n    auto ft = 0;\n    auto ff = total_0;\n    \n    auto sens = ((value_type) tt) / ((value_type) (tt+tf));\n    auto spec = ((value_type) ff) / ((value_type) (ft+ff));\n    auto tpf = sens;\n    auto fpf = 1.f - spec;\n    data_array true_pf, false_pf;\n    \n    true_pf.push_back(tpf);\n    false_pf.push_back(fpf);\n    auto roc_area = 0.f;\n    auto tpf_prev = tpf;\n    auto fpf_prev = fpf;\n    \n    auto no_item = calc_params.predictions.size();\n    for (int item=no_item-1; item>-1; item--) {\n        tt+= calc_params.partitions[item];\n        tf-= calc_params.partitions[item];\n        ft+= 1 - calc_params.partitions[item];\n        ff-= 1 - calc_params.partitions[item];\n        sens = ((value_type) tt) / ((value_type) (tt+tf));\n        spec = ((value_type) ff) / ((value_type) (ft+ff));\n        tpf  = sens;\n        fpf  = 1.f - spec;\n        if (item > 0) {\n            if (calc_params.predictions[item] != calc_params.predictions[item - 1]) {\n                true_pf.push_back(tpf);\n                false_pf.push_back(fpf);\n                roc_area += 0.5f * (tpf + tpf_prev) * (fpf-fpf_prev);\n                tpf_prev = tpf;\n                fpf_prev = fpf;\n            }\n        }\n        if (item == 0) {\n            true_pf.push_back(tpf);\n            false_pf.push_back(fpf);\n            roc_area += 0.5f * (tpf+tpf_prev) * (fpf-fpf_prev);\n        }\n    } \n    auto acc = accuracy(0.5, calc_params.partitions, calc_params.predictions);\n    return std::make_tuple(roc_area, acc, std::move(true_pf), std::move(false_pf));\n}\n\ntemplate<typename T>\nstd::size_t ROC::algo_params::init(const std::vector<T>& ex,\n        std::vector<int>& target,\n        value_type threshold)\n{\n    auto pos = 0u;\n    boost::transform(ex, std::back_inserter(target), [&pos, threshold](auto val) {\n                if (val < threshold) {\n                    return 0;\n                } else {\n                    ++pos;\n                    return 1;\n                }\n            }\n    );\n    return pos;\n}\n\nROC::algo_params::algo_params(const data_array& ex, const data_array& predic,\n        value_type threshold) :\n        predictions(predic)/*, partitions(ex.size(), 0)*/\n{\n    condition_pos = init(ex, partitions, threshold);\n}\n\nROC::algo_params::algo_params(const std::vector<int>& ex, \n        const data_array& p, value_type threshold) :\n        predictions(p)/*, partitions(ex.size(), 0)*/\n{\n    condition_pos = init(ex, partitions, threshold);\n}\n\ntemplate<typename T>\nbool ROC::calc(const std::vector<T>& expected,\n            const data_array& predict)\n{\n    if (!expected.empty() && expected.size() == predict.size()) {\n        value_type mean = 0.f;\n        results.rmse = calculateRmse(expected, predict, mean);\n        algo_params data4calc{expected, predict, mean};\n        if (data4calc.condition_pos != 0) {\n            std::tie(results.area, results.accuracy, results.sensitivity, results.fall_out) = \n                do_calculation(std::move(data4calc));\n            return !results.sensitivity.empty();\n        }\n    }\n    return false;\n}\n\nbool ROC::calculate(const data_array& expected,\n                    const data_array& predict)\n{\n    return calc(expected, predict);\n}\n\nbool ROC::classes_calculate(const std::vector<int>& expected,\n                const data_array& predict)\n{\n    return calc(expected, predict);\n}\n\nbool ROC::classes_calculate(const data_array& expected,\n                const data_array& predict)\n{\n    return calc(expected, predict);\n}\n\nstd::ostream& operator << (std::ostream& os, const ROC& roc)\n{\n    os<<\"area: \"<<std::fixed<<roc.results.area<<\" RMS error: \"<<roc.results.rmse<<\n        \" accuracy: \"<<roc.results.accuracy;\n    os<<\"sensitivity   fall_out\\n\";\n    boost::transform(roc.results.sensitivity, roc.results.fall_out, \n                    std::ostream_iterator<std::string>(os, \"\\n\"), [](auto s, auto f) {\n                        return std::to_string(s) + \"      \" + std::to_string(f);\n                    }\n            );\n    return os;\n}\n\n}   // end of namespace exprs\n\n", "meta": {"hexsha": "a1e1e71197863dac75570f19d76901cb0f650703", "size": 7203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/experiments/src/ROC.cpp", "max_stars_repo_name": "boazsade/machine_learinig_models", "max_stars_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/experiments/src/ROC.cpp", "max_issues_repo_name": "boazsade/machine_learinig_models", "max_issues_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/experiments/src/ROC.cpp", "max_forks_repo_name": "boazsade/machine_learinig_models", "max_forks_repo_head_hexsha": "eb1f9eda0e4e25a6d028b25682dfb20628a20624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.731277533, "max_line_length": 120, "alphanum_fraction": 0.5612939053, "num_tokens": 1900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338729, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5825778411892936}}
{"text": "// Copyright (c) 2020 [Yihong Jian]. All rights reserved.\n\n#include <mylibrary/matrixsolver.h>\n#include \"mylibrary/util.h\"\n#include <Eigenvalues>\n\n// Taken from numcpp reference\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> EigenIntMatrix;\ntypedef Eigen::Map<EigenIntMatrix> EigenMatrixMap;\n\nnamespace matrixsolver {\n\n    string Rref(const string& input) {\n        // Convert to 2d array and solve\n        vector<vector<double>> mat;\n        try {\n            mat = util::StringTo2dVec(input);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n        size_t rank = MatReducer(mat);\n\n        // Strech out 2dvec to a string\n        string out;\n        for (const auto& r:mat) {\n            out += \"[\";\n            for (const auto& c:r) {\n                out += to_string(c);\n                out += \", \";\n            }\n            out += \"]\\n\";\n        }\n        return \"Rank is \" + to_string(rank)\n               + \"\\nReduced Row Echelon Form is\\n\" + out;\n    }\n\n    // Took this from https://github.com/yicheng-w/acm-icpc-notebook/blob/master/general-algorithm/rref.cpp\n    int MatReducer(vector<vector<double>>& mat) {\n        int num_row = mat.size();\n        int num_col = mat[0].size();\n        int row = 0;\n        for (int col = 0; col < num_col && row < num_row; col++) {\n            // Find pivot rows, checking if next n-rows are greater than current\n            // row on leading index\n            int j = row;\n            for (int i = row + 1; i < num_row; i++) {\n                if (fabs(mat[i][col]) > fabs(mat[j][col]))\n                    j = i;\n            }\n            if (fabs(mat[j][col]) < 1e-10)\n                continue;\n            swap(mat[j], mat[row]);\n\n            // Normalize each row based with 1\n            // subtract previous row.\n            double s = 1.0 / mat[row][col];\n            for (int j1 = 0; j1 < num_col; j1++) mat[row][j1] *= s;\n            for (int i = 0; i < num_row; i++)\n                if (i != row) {\n                    double t = mat[i][col];\n                    for (int j2 = 0; j2 < num_col; j2++) {\n                        mat[i][j2] -= t * mat[row][j2];\n                    }\n                }\n            row++;\n        }\n        return row;\n    }\n\n    string LUDecomp(const string& input) {\n        NdArray<double> mat;\n        try {\n            mat = util::StringToMat(input);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n\n        try {\n            // LUDecomp may encounter error such as rectangular matrix\n            // So we just catch whatever and print it out.\n            auto lu_res = linalg::lu_decomposition(mat);\n            string l = util::MatToString(get<0>(lu_res));\n            string u = util::MatToString(get<1>(lu_res));\n            return \"L is:\\n\" + l + \"U is\\n\" + u;\n        } catch (exception e) {\n            return e.what();\n        }\n    }\n\n    string Det(const string& input) {\n        vector<vector<double>> mat;\n        try {\n            mat = util::StringTo2dVec(input);\n        } catch (exception e) {\n            return e.what();\n        }\n\n        size_t n = mat.size();\n        if (n != mat[0].size())\n            return \"Determinant Requires Square Matrix\";\n\n        double det = 1.0;\n\n        for (int i = 0; i < n; ++i) {\n            double pivotElement = mat[i][i];\n            int pivotRow = i;\n            for (int row = i + 1; row < n; ++row) {\n                if (std::abs(mat[row][i]) > std::abs(pivotElement)) {\n                    pivotElement = mat[row][i];\n                    pivotRow = row;\n                }\n            }\n            if (pivotElement == 0.0) {\n                det = 0.0;\n                break;\n            }\n            if (pivotRow != i) {\n                mat[i].swap(mat[pivotRow]);\n                det *= -1.0;\n            }\n            det *= pivotElement;\n\n            for (int row = i + 1; row < n; ++row) {\n                for (int col = i + 1; col < n; ++col) {\n                    mat[row][col] -= mat[row][i] * mat[i][col] / pivotElement;\n                }\n            }\n        }\n\n        return \"Determinant is \" + to_string(det);\n    }\n\n    string Eig(const string& input) {\n        NdArray<double> mat;\n        try {\n            mat = util::StringToMat(input);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n\n        if (mat.numCols() != mat.numRows())\n            return \"Can't perform eigen calculation with non-square matrix\";\n        // Map numcpp array to Eigen Matrix\n        auto eigen_mat = EigenMatrixMap(mat.data(), mat.numRows(), mat.numCols());\n        // Retrieve Eigen values\n        Eigen::EigenSolver<Eigen::MatrixXd> es(eigen_mat);\n        Eigen::VectorXd eigen_values = es.eigenvalues().real();\n        Eigen::MatrixXd eigen_vectors = es.eigenvectors().real();\n\n        // Map eigen matrix to string\n        ostringstream val;\n        val << eigen_values;\n        ostringstream vec;\n        vec << eigen_vectors;\n\n        return \"CAUTION, complex eigenvalue caused UNDEFINED behavior\\n\"\n               \"Eigenvalues are\\n\" + val.str() +\n               \"\\nEigenvectors(in columns) are\\n\" + vec.str();\n    }\n\n    string SVD(const string& input) {\n        NdArray<double> mat;\n        try {\n            mat = util::StringToMat(input);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n\n        nc::NdArray<double> u;\n        nc::NdArray<double> s;\n        nc::NdArray<double> vt;\n        try {\n            linalg::svd(mat, u, s, vt);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n\n        return \"U is:\\n\" + util::MatToString(u)\n               + \"S is\\n\" + util::MatToString(s)\n               + \"V-Transpose is\\n\" + util::MatToString(vt);\n    }\n\n    string Inv(const string& input) {\n        NdArray<double> mat;\n        try {\n            mat = util::StringToMat(input);\n        } catch (exception e) {\n            // I can't catch \"int e\" for some reason.\n            return e.what();\n        }\n\n        try {\n            return \"Inverse is\\n\" + util::MatToString(linalg::inv(mat));\n        } catch (exception e) {\n            return e.what();\n        }\n    }\n\n    pair<string, string> PowerIter(const string& input, const string& init_guess) {\n        NdArray<double> mat;\n        NdArray<double> vec;\n        try {\n            mat = util::StringToMat(input).astype<double>();\n            vec = util::StringToMat(init_guess, true).astype<double>();\n        } catch (exception e) {\n            return make_pair(e.what(), init_guess);\n        }\n\n        try {\n            // Normalize input to prevent overflow\n            // Broadcasting doesn't work too well between arrays, so\n            // I extracted the double contained in array for broadcasting\n            NdArray<double> vec_normed = vec / vec.norm()(0, 0);\n            NdArray<double> y = mat.dot(vec_normed);\n            NdArray<double> res = y / y.norm()(0, 0);\n            return make_pair(\"Initial guess after 1 iteration is\\n\" + util::MatToString(res),\n                             util::VecToLine(res));\n        } catch (exception e) {\n            return make_pair(e.what(), init_guess);\n        }\n    }\n\n    string LstSq(const string& input, const string& init_guess) {\n        NdArray<double> A;\n        // Assume b is only one column\n        NdArray<double> b;\n\n        try {\n            A = util::StringToMat(input);\n            b = util::StringToMat(init_guess, true);\n        } catch (exception e) {\n            return e.what();\n        }\n\n        if (A.numRows() != b.numRows())\n            return \"For Ax = b, rows of A and b does not match\";\n\n        try {\n            return util::MatToString(nc::linalg::lstsq(A, b));\n        } catch (exception e) {\n            return e.what();\n        }\n    }\n\n}  // namespace matrixsolver\n", "meta": {"hexsha": "fdbbe4bf15dd585e99efdfc54efbdf648345c380", "size": 8084, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/matrixsolver.cc", "max_stars_repo_name": "CS126SP20/final-project-yihjian", "max_stars_repo_head_hexsha": "3e3fc0e9ae26091ed08bba06e2bf863b4667b71e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrixsolver.cc", "max_issues_repo_name": "CS126SP20/final-project-yihjian", "max_issues_repo_head_hexsha": "3e3fc0e9ae26091ed08bba06e2bf863b4667b71e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrixsolver.cc", "max_forks_repo_name": "CS126SP20/final-project-yihjian", "max_forks_repo_head_hexsha": "3e3fc0e9ae26091ed08bba06e2bf863b4667b71e", "max_forks_repo_licenses": ["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.2071713147, "max_line_length": 107, "alphanum_fraction": 0.4877535873, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5825778152322565}}
{"text": "#include <iostream>\n#include <limits>\n\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#include <opencv2/calib3d/calib3d.hpp>\n#include <sys/stat.h>\n\n#include \"Optimization.h\"\n#include \"math.hh\"\n\nbool translation_gauss_newton(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& image_pts,\n                              const Eigen::Matrix3d &K, const Eigen::Quaterniond& Q, Eigen::Vector3d &T,\n                              double& residual, int& iter)\n//----------------------------------------------------------------------------------------------------------------------\n{\n   double tx = T[0], ty = T[1], tz = T[2];\n   const Eigen::Matrix3d KI = K.inverse();\n   size_t m = std::min(world_pts.size(), image_pts.size());\n   std::vector<Eigen::Quaterniond> world_quaternions;\n   std::vector<Eigen::Vector3d> image_rays;\n   const Eigen::Quaterniond QI = Q.inverse();\n   for (size_t row = 0; row < m; row++)\n   {\n      cv::Point2d &pt = const_cast<cv::Point2d &>(image_pts[row]);\n      Eigen::Vector3d pt2d = KI * Eigen::Vector3d(pt.x, pt.y, 1);\n      pt2d /= pt2d[2];\n      image_rays.push_back(pt2d);\n      const cv::Point3d pt3d = world_pts[row];\n      const Eigen::Quaterniond QR = Q * Eigen::Quaterniond(0, pt3d.x, pt3d.y, pt3d.z) * QI;\n      world_quaternions.push_back(QR);\n   }\n   iter = 0;\n   double prev_min_residual = std::numeric_limits<double>::max();\n   double eps = 0.0000001;\n   do\n   {\n      Eigen::MatrixXd J(m, 3);\n//      Eigen::MatrixXd r(m, 3);\n      Eigen::MatrixXd r(m, 1);\n      double min_residual = std::numeric_limits<double>::max();\n      for (size_t row = 0; row < m; row++)\n      {\n         Eigen::Vector3d pt2d = image_rays[row];\n         double u = pt2d[0], v = pt2d[1];\n         const Eigen::Vector3d Rv = world_quaternions[row].vec();\n         //  Eigen::Vector3d Rr = R*Eigen::Vector3d(pt3d.x, pt3d.y, pt3d.z);\n         Eigen::Vector3d pt3d = Rv + Eigen::Vector3d(tx, ty, tz);\n         pt3d /= pt3d[2];\n         Eigen::Vector3d diff = pt3d - pt2d;\n         residual = diff.dot(diff);\n         if (residual < min_residual)\n            min_residual = residual;\n//         std::cout << \"refine: \" << pt3d.transpose() << \" \" << pt2d.transpose() << \" \" << diff.transpose() << \" \" << residual << std::endl;\n         Eigen::Vector3d d;\n         J.row(row) << 2 * (Rv[0] + tx - u), 2 * (Rv[1] + ty - v), 2 * (Rv[2] + tz - 1);\n         r.row(row) << residual;\n      }\n//      std::cout << \"minmax \" << min_residual << \" \" << (min_residual - prev_min_residual) <<  std::endl;\n      if (min_residual > prev_min_residual) break;\n      prev_min_residual = min_residual;\n      auto Jt = J.transpose();\n//      std::cout << \"JTr: \" << std::endl << (Jt * r) << std::endl << \"==================== \" << std::endl;\n\n      //auto llt = (Jt * J).ldlt();\n      auto llt = (Jt * J).llt();\n      double dx, dy, dz;\n      if (llt.info() == Eigen::Success)\n      {\n         auto delta =  llt.solve(Jt * r * (-1.0));\n         dx = delta(0, 0), dy = delta(1, 0), dz = delta(2, 0);\n//         std::cout << delta << std::endl;\n      }\n      else\n      {\n         auto JtJI = (Jt*J).inverse();\n         auto dd = -(JtJI*Jt);\n         auto delta = dd*r;\n         dx = delta(0, 0), dy = delta(1, 0), dz = delta(2, 0);\n      }\n      if ( (mut::near_zero(dx, eps)) && (mut::near_zero(dy, eps)) && (mut::near_zero(dz, eps)) ) break;\n      tx += dx;\n      ty += dy;\n      tz += dz;\n   } while (iter++ < 200);\n   if ( (iter > 1) && (iter < 100) )\n   {\n      T[0] = tx; T[1] = ty; T[2] = tz;\n      return true;\n   }\n   return false;\n}\n\nbool translation_levenberg_marquardt3d(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& image_pts,\n                                     const Eigen::Matrix3d &K, const Eigen::Quaterniond& Q, Eigen::Vector3d &T,\n                                     int& iterations)\n//-----------------------------------------------------------------------------------------------------------------------\n{\n   TranslationLevenbergMarquardt3D functor(world_pts, image_pts, K, Q);\n   Eigen::LevenbergMarquardt<TranslationLevenbergMarquardt3D, double> lm(functor);\n   Eigen::VectorXd x(3);\n   x << T[0], T[1], T[2];\n   iterations = 0;\n   Eigen::LevenbergMarquardtSpace::Status status = lm.minimizeInit(x);\n   if (status == Eigen::LevenbergMarquardtSpace::ImproperInputParameters)\n      return false;\n   do\n   {\n      status = lm.minimizeOneStep(x);\n      if (status == Eigen::LevenbergMarquardtSpace::Running)\n         iterations++;\n   } while (status == Eigen::LevenbergMarquardtSpace::Running);\n   if (iterations > 1)\n   {\n      T = x;\n      return true;\n   }\n   return false;\n}\n\nbool translation_levenberg_marquardt2d_depth(const std::vector<cv::Point3d>& world_pts,\n                                             const std::vector<cv::Point3d>& image_pts, const Eigen::Matrix3d &K,\n                                             const Eigen::Quaterniond& Q, Eigen::Vector3d &T, const double depth,\n                                             int& iterations)\n//--------------------------------------------------------------------------------------------------------------\n{\n   TranslationLevenbergMarquardt2DDepth functor(world_pts, image_pts, K, Q, depth);\n   Eigen::LevenbergMarquardt<TranslationLevenbergMarquardt2DDepth, double> lm(functor);\n   Eigen::VectorXd x(3);\n   x << T[0], T[1], T[2];\n   iterations = 0;\n   Eigen::LevenbergMarquardtSpace::Status status = lm.minimizeInit(x);\n   if (status == Eigen::LevenbergMarquardtSpace::ImproperInputParameters)\n      return false;\n   do\n   {\n      status = lm.minimizeOneStep(x);\n      if (status == Eigen::LevenbergMarquardtSpace::Running)\n         iterations++;\n   } while (status == Eigen::LevenbergMarquardtSpace::Running);\n   if (iterations > 1)\n   {\n      T = x;\n      return true;\n   }\n   return false;\n}", "meta": {"hexsha": "284366c780bf7b2c213a26b1d68f2bf6b1c05e13", "size": 5896, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose/Optimization.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/Optimization.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/Optimization.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": 39.3066666667, "max_line_length": 141, "alphanum_fraction": 0.5362957938, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5824492189137745}}
{"text": "// TinyVector<T,N> DAXPY benchmark\n\n//#define BZ_DISABLE_KCC_COPY_PROPAGATION_KLUDGE\n\n#include <blitz/array.h>\n#include <blitz/timer.h>\n#include <random/uniform.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nranlib::Uniform<double> rnd;\n\ntemplate<class T>\nvoid optimizationSink(T&);\n\ntemplate<int N_rank>\nvoid tinyDAXPYBenchmark(TinyVector<double,N_rank>, int iters, double a)\n{\n    Timer timer;\n   \n    TinyVector<double,N_rank> ta, tb, tc, td, te, tf, tg, th, ti, tj;\n    for (int i=0; i < N_rank; ++i)\n    {\n        ta[i] = rnd.random()+1;\n        tb[i] = rnd.random()+1;\n        tc[i] = rnd.random()+1;\n        td[i] = rnd.random()+1;\n        te[i] = rnd.random()+1;\n        tf[i] = rnd.random()+1;\n        tg[i] = rnd.random()+1;\n        th[i] = rnd.random()+1;\n        ti[i] = rnd.random()+1;\n        tj[i] = rnd.random()+1;\n    }\n\n    double b = -a;\n\n    double numFlops = 0;\n\n    if (N_rank < 20)\n    {\n      timer.start();\n      for (int i=0; i < iters; ++i)\n      {\n        ta += a * tb;\n        tc += a * td;\n        te += a * tf;\n        tg += a * th;\n        ti += a * tj;\n        tb += b * ta;\n        td += b * tc;\n        tf += b * te;\n        th += b * tg;\n        tj += b * ti;\n        ta += a * tb;\n        tc += a * td;\n        te += a * tf;\n        tg += a * th;\n        ti += a * tj;\n        tb += b * ta;\n        td += b * tc;\n        tf += b * te;\n        th += b * tg;\n        tj += b * ti;\n      }\n      timer.stop();\n      numFlops = 40.0 * N_rank * double(iters);\n    }\n    else {\n      timer.start();\n      for (int i=0; i < iters; ++i)\n      {\n        ta += a * tb;\n        tb += b * ta;\n      }\n      timer.stop();\n      numFlops = 4.0 * N_rank * double(iters);\n    }\n\n    optimizationSink(ta);\n    optimizationSink(tb);\n    optimizationSink(tc);\n    optimizationSink(td);\n    optimizationSink(te);\n    optimizationSink(tf);\n    optimizationSink(tg);\n    optimizationSink(th);\n    optimizationSink(ti);\n    optimizationSink(tj);\n\n    timer.stop();\n    float Gflops = numFlops / (1e9*timer.elapsed());\n\n    if (iters > 1)  \n    {\n    cout << setw(5) << N_rank << '\\t' << Gflops << endl;\n    }\n}\n\ndouble a = 0.3429843;\n\ntemplate<class T>\nvoid optimizationSink(T&)\n{\n}\n\nint main()\n{\n    cout << \"TinyVector<double,N> DAXPY benchmark\" << endl\n         << setw(5) << \"N\" << '\\t' << \"Gflops/\" << Timer::indep_var() << endl;\n    tinyDAXPYBenchmark(TinyVector<double,1>(), 800000, a);\n    tinyDAXPYBenchmark(TinyVector<double,2>(), 800000, a);\n    tinyDAXPYBenchmark(TinyVector<double,3>(), 800000, a);\n    tinyDAXPYBenchmark(TinyVector<double,4>(), 700000, a);\n    tinyDAXPYBenchmark(TinyVector<double,5>(), 600000, a);\n    tinyDAXPYBenchmark(TinyVector<double,6>(), 500000, a);\n    tinyDAXPYBenchmark(TinyVector<double,7>(), 500000, a);\n    tinyDAXPYBenchmark(TinyVector<double,8>(), 500000, a);\n    tinyDAXPYBenchmark(TinyVector<double,9>(), 500000, a);\n    tinyDAXPYBenchmark(TinyVector<double,10>(), 500000, a);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "1f78e2a77e517716eab960a0fadd693391610429", "size": 2942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/tinydaxpy.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/tinydaxpy.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/tinydaxpy.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.536, "max_line_length": 78, "alphanum_fraction": 0.5312712441, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5824056007621224}}
{"text": "#ifndef HOPS_NORMALIZEPOLYTOPE_HPP\n#define HOPS_NORMALIZEPOLYTOPE_HPP\n\n#include <Eigen/Core>\n\nnamespace hops {\n\n    /**\n     * @brief Normalizes polytope defined by Ax < b\n     * @tparam Derived1\n     * @tparam Derived2\n     * @param A Dense representation of A\n     * @param b\n     */\n    template<typename Derived1, typename Derived2>\n    void normalizePolytope(Eigen::MatrixBase<Derived1> &A, Eigen::MatrixBase<Derived2> &b) {\n        for (int i = 0; i < A.rows(); ++i) {\n            const double norm = A.row(i).template lpNorm<2>();\n            A.row(i) /= norm;\n            b(i) /= norm;\n        }\n    }\n}\n\n\n#endif //HOPS_NORMALIZEPOLYTOPE_HPP\n", "meta": {"hexsha": "a73ed3deda7d3f0f939325c4659a6602be4f4748", "size": 650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Polytope/NormalizePolytope.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/Polytope/NormalizePolytope.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/Polytope/NormalizePolytope.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": 24.0740740741, "max_line_length": 92, "alphanum_fraction": 0.6076923077, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5823544278121908}}
{"text": "#include \"CubicInterpolation/InterpolantBuilder.h\"\n\n#include <boost/math/differentiation/finite_difference.hpp>\n#include <Eigen/Dense>\n\nnamespace cubic_splines {\n\n/* template <> */\n/* BicubicSplines */\n/* InterpolantBuilder<BicubicSplines>::build(BicubicSplines::Definition const &def, */\n/*                                           std::string save_path, */\n/*                                           std::string filename) { */\n/*   using boost::math::differentiation::finite_difference_derivative; */\n/*   try { */\n/*     return load(save_path, filename); */\n/*   } catch (std::system_error const &ex) { */\n/*     if (ex.code().value() != ENOENT) */\n/*       throw ex; */\n/*   } */\n/*   auto x1nodes = def.axis[0]->required_nodes(); */\n/*   auto x2nodes = def.axis[1]->required_nodes(); */\n/*   auto data = BicubicSplines::RuntimeData(); */\n/*   auto y = Eigen::MatrixXf(x1nodes, x2nodes); */\n/*   auto dydx1 = Eigen::MatrixXf(x1nodes, x2nodes); */\n/*   auto dydx2 = Eigen::MatrixXf(x1nodes, x2nodes); */\n/*   auto d2ydx1dx2 = Eigen::MatrixXf(x1nodes, x2nodes); */\n/*   auto func = [this, &def](double x1, double x2) { */\n/*     return transform(def, x1, x2); */\n/*   }; */\n/*   for (size_t n1 = 0; n1 < x1nodes; ++n1) { */\n/*     for (size_t n2 = 0; n2 < x2nodes; ++n2) { */\n/*       auto x1 = def.axis[0]->back_transform(n1); */\n/*       auto x2 = def.axis[1]->back_transform(n2); */\n\n/*       auto dfdx1 = def.axis[0]->derive(x1); */\n/*       auto dfdx2 = def.axis[1]->derive(x2); */\n\n/*       y(n1, n2) = func(x1, x2); */\n/*       dydx1(n1, n2) = */\n/*           finite_difference_derivative( */\n/*               [this, &func, x2](double x) { return func(x, x2); }, x1) * */\n/*           dfdx1; */\n/*       dydx2(n1, n2) = */\n/*           finite_difference_derivative( */\n/*               [this, &func, x1](double x) { return func(x1, x); }, x2) * */\n/*           dfdx2; */\n/*       d2ydx1dx2(n1, n2) = */\n/*           finite_difference_derivative( */\n/*               [this, &func, x1, x2, dfdx1, dfdx2](double x_1) { */\n/*                 return finite_difference_derivative( */\n/*                            [this, &func, x_1, dfdx2](double x_2) { */\n/*                              return func(x_1, x_2); */\n/*                            }, */\n/*                            x2) * */\n/*                        dfdx2; */\n/*               }, */\n/*               x1) * */\n/*           dfdx1; */\n/*     } */\n/*   } */\n/*   bool sucess = save(save_path, filename, y, dydx1, dydx2, d2ydx1dx2); */\n/*   if (not sucess) */\n/*     std::cout << \"storage of tables have failed\" << std::endl; */\n/*   return BicubicSplines(y, dydx1, dydx2, d2ydx1dx2); */\n/* } */\n\n/* template <> */\n/* CubicSplines */\n/* InterpolantBuilder<CubicSplines>::build(CubicSplines::Definition const &def, */\n/*                                         std::string path, */\n/*                                         std::string filename) { */\n/*   using boost::math::differentiation::finite_difference_derivative; */\n/*   try { */\n/*     return load(path, filename); */\n/*   } catch (std::system_error const &ex) { */\n/*     if (ex.code().value() != ENOENT) */\n/*       throw ex; */\n/*   } */\n/*   auto y = std::vector<double>(def.axis->required_nodes()); */\n/*   auto func = [this, &def](double x) { return transform(def, x); }; */\n/*   /1* auto func = [&def](double x) { *1/ */\n/*   /1*   auto fx = def.f(x); *1/ */\n/*   /1*   if (def.f_trafo) *1/ */\n/*   /1*     fx = def.f_trafo->transform(fx); *1/ */\n/*   /1*   return fx; *1/ */\n/*   /1* }; *1/ */\n/*   for (size_t n = 0; n < y.size(); ++n) */\n/*     y[n] = func(def.axis->back_transform(n)); */\n/*   auto low = def.axis->back_transform(0); */\n/*   auto low_lim_derivate = */\n/*       finite_difference_derivative(func, low) * def.axis->derive(low); */\n/*   auto up = def.axis->back_transform(y.size() - 1); */\n/*   auto up_lim_derivate = finite_difference_derivative( */\n/*                              func, def.axis->back_transform(y.size() - 1)) * */\n/*                          def.axis->derive(up); */\n/*   bool sucess = save(path, filename, y, low_lim_derivate, up_lim_derivate); */\n/*   if (not sucess) */\n/*     std::cout << \"storage of tables have failed\" << std::endl; */\n/*   return CubicSplines(y, low_lim_derivate, up_lim_derivate); */\n/* } */\n\n} // namespace cubic_splines\n", "meta": {"hexsha": "9b1f7eb94e1b17c086406870d34a6a93f131c6b9", "size": 4319, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/detail/InterpolantBuilder.cxx", "max_stars_repo_name": "maxnoe/cubic_interpolation", "max_stars_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T15:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T06:59:47.000Z", "max_issues_repo_path": "src/detail/InterpolantBuilder.cxx", "max_issues_repo_name": "maxnoe/cubic_interpolation", "max_issues_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T11:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T09:03:01.000Z", "max_forks_repo_path": "src/detail/InterpolantBuilder.cxx", "max_forks_repo_name": "maxnoe/cubic_interpolation", "max_forks_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-12T14:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T13:33:52.000Z", "avg_line_length": 41.932038835, "max_line_length": 86, "alphanum_fraction": 0.5054410743, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.5823544218744805}}
{"text": "\n#include <armadillo>\n#include <iostream>\n#include <ostream>\n#include <target/odesolver.hpp>\n#include <target/utils.hpp>\n\nusing arma::vec;\nusing arma::mat;\nusing std::cout;\nusing std::endl;\n\nvec dy(const vec &input,  // time (first element) and input variables\n       const vec &x,      // state variables\n       const vec &par) {\n  return par(0) + par(1)*x;\n}\n\n\nint main(int argc, char **argv) {\n    cout << target::BLUE << \"RK4 test\\n\\n\";\n\n    target::RK4 MyODE(dy);\n    vec t = arma::linspace(0, 2, 20);\n    vec y0 = arma::zeros(1);\n    vec par = { 1.0, 1.0 };\n    vec y = MyODE.solve(t, y0, par);\n    cout << y << endl;\n    std::cout << target::COL_RESET;\n\n    mat ty = arma::join_horiz(t, y);\n    ty.save(\"y.csv\", arma::csv_ascii);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "ba018fca2bf8af8d546699ffb318acbb86c2b1a1", "size": 755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/ode_run.cpp", "max_stars_repo_name": "kkholst/target", "max_stars_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T19:01:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T19:01:21.000Z", "max_issues_repo_path": "misc/ode_run.cpp", "max_issues_repo_name": "kkholst/target", "max_issues_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_issues_repo_licenses": ["Apache-2.0"], "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/ode_run.cpp", "max_forks_repo_name": "kkholst/target", "max_forks_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_forks_repo_licenses": ["Apache-2.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.4054054054, "max_line_length": 69, "alphanum_fraction": 0.5920529801, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5823253333177395}}
{"text": "#include <iostream>\n#include <stdio.h>\n\n#include <Eigen/Dense>\n//using namespace Eigen;\n\n//#include <boost/array.hpp>\n//#include <boost/numeric/odeint.hpp>\n\n//using namespace boost::numeric;\n//\n//#include \"filters.h\"\n//\n//namespace syllo {\n//\n//     Kalman::Kalman()\n//     {\n//     }\n//\n//     Kalman::Kalman(const Eigen::MatrixXf &A, const Eigen::MatrixXf &B, const Eigen::VectorXf &C, const Eigen::MatrixXf &R, const Eigen::MatrixXf &Q)\n//     {\n//\t  setModel(A, B, C, R, Q);\n//     }\n//\n//     int Kalman::setModel(const Eigen::MatrixXf &A, const Eigen::MatrixXf &B, const Eigen::VectorXf &C, const Eigen::MatrixXf &R, const Eigen::MatrixXf &Q)\n//     {\n//\t  this->A = A;\n//\t  this->B = B;\n//\t  this->C = C;\n//\t  this->R = R;\n//\t  this->Q = Q;\n//\t  eye = Eigen::MatrixXf::Identity(A.rows(), A.cols());\n//\n//\t  return 0;\n//     }\n//\n//     int Kalman::init(const Eigen::VectorXf &mu0, const Eigen::MatrixXf &covar0)\n//     {\n//\t  this->mu = mu0;\n//\t  this->covar = covar0;\n//\t  return 0;\n//     }\n//\n//     int Kalman::step(Eigen::VectorXf &mu_prev, Eigen::MatrixXf &covar_prev, const Eigen::VectorXf &u)\n//     {\n//\t  Eigen::VectorXf mu_dx;\n//\n//\t  mu_dx = A*mu_prev + B*u;\n//\n//\t  mu_prev += mu_dx;\n//\n//\t  covar = A*covar_prev*A.transpose() + R;\n//\t  //K = covar*C.transpose() * (C*covar*C.transpose() + Q).inverse();\n//\t  ////mu = mu + K*(z-C*mu);\n//\t  //covar = (eye - K*C) * covar;\n//\t  \n//\t  \n//\n//\t  return 0;\n//     }\n//\n//     int Kalman::step(Eigen::VectorXf &mu_prev, Eigen::MatrixXf &covar_prev, const Eigen::VectorXf &u, const Eigen::VectorXf &z)\n//     {\n//\t  mu = A*mu_prev + B*u;\n//\t  covar = A*covar_prev*A.transpose() + R;\n//\n//\t  std::cout << \"covar: \\n\" << covar << std::endl;\n//\t  std::cout << \"C: \\n\" << C << std::endl;\n//\t  std::cout << \"C': \\n\" << C.transpose() << std::endl;\n//\t  std::cout << \"Q: \\n\" << Q << std::endl;\n//\n//\t  //K = covar*C.transpose() * (C*covar*C.transpose() + Q).inverse();\n//\t  \n//          K = covar*C * (C.transpose()*covar*C + Q).inverse();\n//\t  \n//\t  std::cout << \"mu: \\n\" <<  mu << std::endl;\n//\t  std::cout << \"K: \\n\" <<  K << std::endl;\n//\t  std::cout << \"z: \\n\" <<  z << std::endl;\n//\t  std::cout << \"C: \\n\" <<  C << std::endl;\n//\n//\t  //mu = mu + K*(z-C*mu);\n//\t  //mu = mu + K*(z-C*mu);\n//\t  z-C.transpose()*mu;\n//\t  \n//          //covar = (eye - K*C) * covar;\n//\t  \n//\t  return 0;\n//     }\n//\n//     Eigen::VectorXf Kalman::getMu()\n//     {\n//\t  return mu;\n//     }\n//     \n//     Eigen::MatrixXf Kalman::getCovar()\n//     {\n//\t  return covar;\n//     }\n//}\n", "meta": {"hexsha": "cad6a8a3a38c9047ad9f9603d331c7d4d3f71395", "size": 2519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/track/filters.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": "src/track/filters.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": "src/track/filters.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": 25.19, "max_line_length": 157, "alphanum_fraction": 0.5045653037, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5823253288262619}}
{"text": "/*\n * Copyright (c) 2020. Mohit Deshpande.\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 * 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 \"ekf/ekf.h\"\n#include \"ekf/utils.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace ekf {\n\nvoid Predict(Ekf& ekf, double dt) {\n    auto new_state = ekf.state;\n    new_state(0) = ekf.state(3) * dt * std::cos(ekf.state(2)) + ekf.state(0);\n    new_state(1) = ekf.state(3) * dt * std::sin(ekf.state(2)) + ekf.state(1);\n    new_state(2) = wrapAngle(ekf.state(4) * dt + ekf.state(2));\n\n    Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(5, 5);\n    // x\n    jacobian(0,0) = 1;\n    jacobian(0,2) = -ekf.state(3) * dt * std::sin(ekf.state(2));\n    jacobian(0,3) = dt * std::cos(ekf.state(2));\n\n    // y\n    jacobian(1,1) = 1;\n    jacobian(1,2) = ekf.state(3) * dt * std::cos(ekf.state(2));\n    jacobian(1,3) = dt * std::sin(ekf.state(2));\n\n    // theta\n    jacobian(2,2) = 1;\n    jacobian(2,4) = dt;\n\n    // v\n    jacobian(3,3) = 1;\n\n    // w\n    jacobian(4,4) = 1;\n\n    Eigen::MatrixXd process_noise = Eigen::MatrixXd::Identity(5, 5);\n    process_noise = process_noise * 0.1;\n\n    ekf.state = new_state;\n    ekf.covariance = jacobian * ekf.covariance * jacobian.transpose() + process_noise;\n}\n\nbool Update(Ekf& ekf,\n        const Eigen::VectorXd& z,\n        const Eigen::MatrixXd& H,\n        const Eigen::MatrixXd& R) {\n    Eigen::VectorXd y = z - H * ekf.state;\n    Eigen::MatrixXd S = H * ekf.covariance * H.transpose() + R;\n\n    Eigen::FullPivLU<Eigen::MatrixXd> lu(S);\n    if (!lu.isInvertible()) {\n        return false;\n    }\n\n    Eigen::MatrixXd K = ekf.covariance * H.transpose() * S.inverse();\n    ekf.state = ekf.state + K * y;\n    Eigen::MatrixXd KH = K * H;\n    ekf.covariance = (Eigen::MatrixXd::Identity(KH.rows(), KH.cols()) - KH) * ekf.covariance;\n    return true;\n}\n}\n\n", "meta": {"hexsha": "ff933c0ed795ebe3fc8db7ae03d5f85c2dcd54c5", "size": 2813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ekf/src/ekf.cpp", "max_stars_repo_name": "mohitd/hcr", "max_stars_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ekf/src/ekf.cpp", "max_issues_repo_name": "mohitd/hcr", "max_issues_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ekf/src/ekf.cpp", "max_forks_repo_name": "mohitd/hcr", "max_forks_repo_head_hexsha": "ca63462aa3bf7b3a4ddaa52720bc4147b17c3aab", "max_forks_repo_licenses": ["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.4880952381, "max_line_length": 93, "alphanum_fraction": 0.6558833985, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5823253160783406}}
{"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"tools.hpp\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\n// For converting back and forth between radians and degrees.\ndouble pi() { return M_PI; }\n\ndouble deg2rad(double x) { return x * pi() / 180.; }\ndouble rad2deg(double x) { return x * 180. / pi(); }\n\n\ndouble distance(double x1, double y1, double x2, double y2) {\n\treturn sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));\n}\n\ndouble norm(double x, double y) {\n\treturn sqrt(x*x + y*y);\n}\n\ndouble norm(double x, double y, double z) {\n\treturn sqrt(x*x + y*y + z*z);\n}\n\ndouble mph2mps(double mph) {\n\treturn mph / 2.2369362920544; \n}\n\ndouble mps2mph(double mps) {\n\treturn mps * 2.2369362920544; \n}\n\n\n// Evaluate a polynomial.\nvector<double> polyeval(vector<double> &coeffs, vector<double> &x)\n{\n    vector<double> result(x.size());\n    for (int j = 0; j < x.size(); j++)\n    {\n        result[j] = 0;\n        for (int i = 0; i < coeffs.size(); i++) {\n            result[j] += coeffs[i] * pow(x[j], i);\n        }\n    }\n    return result;\n}\n\n\ndouble polyeval(vector<double> &coeffs, double x)\n{\n    double result = 0;\n    for (int i = 0; i < coeffs.size(); i++) {\n        result += coeffs[i] * pow(x, i);\n    }\n    return result;\n}\n\n\ndouble polyeval(Eigen::VectorXd &coeffs, double x)\n{\n    double result = 0.0;\n    for (int i = 0; i < coeffs.size(); i++) {\n        result += coeffs[i] * pow(x, i);\n    }\n    return result;\n}\n\n\nvector<double> polyfit(vector<double> &xvals, vector<double> &yvals, int order) {\n    assert(xvals.size() == yvals.size());\n    assert(order >= 1 && order <= xvals.size() - 1);\n    Eigen::VectorXd xvals_eig = Eigen::VectorXd::Map(xvals.data(), xvals.size());\n    Eigen::VectorXd yvals_eig = Eigen::VectorXd::Map(yvals.data(), yvals.size());\n\tEigen::VectorXd result_eig = polyfit(xvals_eig, yvals_eig, order);\n\tvector<double> result(result_eig.data(), result_eig.data() + result_eig.size());\n    return result;\n}\n\n\n// Fit a polynomial.\n// Adapted from\n// https://github.com/JuliaMath/Polynomials.jl/blob/master/src/Polynomials.jl#L676-L716\nEigen::VectorXd polyfit(Eigen::VectorXd &xvals, Eigen::VectorXd &yvals, int order) {\n    assert(xvals.size() == yvals.size());\n    assert(order >= 1 && order <= xvals.size() - 1);\n    Eigen::MatrixXd A(xvals.size(), order + 1);\n\n    for (int i = 0; i < xvals.size(); i++) {\n        A(i, 0) = 1.0;\n    }\n\n    for (int j = 0; j < xvals.size(); j++) {\n        for (int i = 0; i < order; i++) {\n            A(j, i + 1) = A(j, i) * xvals(j);\n        }\n    }\n\n    auto Q = A.householderQr();\n    auto result = Q.solve(yvals);\n    return result;\n}\n\n\nvector<double> polyfit_wp(int wp_start, int wp_stop, int order,\n                          vector<double> &map_x, vector<double> &map_y)\n{\n    assert(map_x.size() == map_y.size());\n    int wp_count = wp_stop - wp_start;\n    Eigen::VectorXd xvals_eig(wp_count);\n    Eigen::VectorXd yvals_eig(wp_count);\n    Eigen::MatrixXd A(wp_count, order+1);\n    // make sure indicies for map_x and map_y wrap around map size!\n    wp_start = wp_start % map_x.size();\n    wp_stop  = wp_stop  % map_x.size();\n\n    for (int idx = 0; idx < wp_count; idx++) {\n        xvals_eig(idx) = map_x[wp_start+idx];\n        yvals_eig(idx) = map_y[wp_start+idx];\n    }\n\n    for (int i = 0; i < wp_count; i++) {\n        A(i, 0) = 1.0;\n    }\n\n    for (int j = 0; j < wp_count; j++) {\n        for (int i = 0; i < order; i++) {\n            A(j, i + 1) = A(j, i) * xvals_eig(j);\n        }\n    }\n    /*\n    IOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\n    cout << \"A: \" << endl << A.format(CleanFmt) << endl;\n    */\n    auto Q = A.householderQr();\n    VectorXd result_eig = Q.solve(yvals_eig);\n    vector<double> result(result_eig.data(), result_eig.data() + result_eig.size());\n    return result;\n}\n\nint getLane(const double d, const double laneWidth) {\n    for (int lane = 0; lane <= 2; lane++) {\n        if (d > laneWidth*lane && d <= laneWidth*(lane+1)) {\n            return lane;\n        }\n    }\n    cout << \"couldn't find lane for d=\" << d << endl;\n    return 0;\n}\n\ndouble getLaneOffsetD(const int lane_number, const double laneWidth) {\n    return (laneWidth*lane_number) + 2.0;\n}\n\n\n\nvector<double> JMT(vector< double> start, vector <double> end, double T)\n{\n    /*\n    Calculate the Jerk Minimizing Trajectory that connects the initial state\n    to the final state in time T.\n\n    INPUTS\n\n    start - the vehicles start location given as a length three array\n            corresponding to initial values of [s, s_dot, s_double_dot]\n\n    end   - the desired end state for vehicle. Like \"start\" this is a\n            length three array.\n\n    T     - The duration, in seconds, over which this maneuver should occur.\n\n    OUTPUT \n    an array of length 6, each value corresponding to a coefficent in the polynomial \n    s(t) = a_0 + a_1 * t + a_2 * t**2 + a_3 * t**3 + a_4 * t**4 + a_5 * t**5\n\n    */\n\n    double T2, T3, T4, T5;\n    T2 = T*T;\n    T3 = T2*T;\n    T4 = T3*T;\n    T5 = T4*T;\n\n    MatrixXd c(3,1);\n    c << end[0] - (start[0] + start[1]*T + 0.5*start[2]*T2),\n         end[1] - (start[1] + start[2]*T),\n         end[2] -  start[2];\n\n    MatrixXd A(3,3);\n    A <<   T3,    T4,    T5,\n         3*T2,  4*T3,  5*T4,\n         6*T,  12*T2, 20*T3;\n\n    MatrixXd b = A.inverse() * c;\n    \n    return {start[0], start[1], 0.5*start[2],\n            b(0),     b(1),     b(2)};\n}\n", "meta": {"hexsha": "9adc699673f708770fbe6495c39eff0ee17444fc", "size": 5403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools.cpp", "max_stars_repo_name": "da-phil/SDC-Path-Planning", "max_stars_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:27:54.000Z", "max_issues_repo_path": "src/tools.cpp", "max_issues_repo_name": "da-phil/SDC-Path-Planning", "max_issues_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools.cpp", "max_forks_repo_name": "da-phil/SDC-Path-Planning", "max_forks_repo_head_hexsha": "ae08d9cd881d35c18cd8dac3a44f2a7abfe02f0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1014492754, "max_line_length": 87, "alphanum_fraction": 0.5746807329, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5823028549574116}}
{"text": "#include <iostream>\n#include <cstdlib>\n\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n\n//#define TVMTL_MANIFOLD_DEBUG\n//#define TVMTL_MANIFOLD_DEBUG_GRASSMANN\n#include <mtvmtl/core/manifold.hpp>\n\nusing namespace tvmtl;\n\nconst int N=3;\nconst int P=2;\n\ntypedef Manifold<GRASSMANN, N, P> mf_t;\n\ntypedef typename mf_t::value_type mat;\n\n\ntemplate <class T>\nvoid test(T& vec1, T& vec2){\n\n\tstd::cout << mf_t::MyType << std::endl;\n\t\n\tstd::cout << \"Vector 1:\\n\" << vec1 << std::endl;\n\tstd::cout << \"\\nVector 2:\\n\" << vec2 << std::endl;\n\n\tstd::cout<< \"\\n\\n==========DISTANCES TEST==========\" << std::endl;\n\tstd::cout << \"Geodesic distance: \" << mf_t::distGeod_squared(vec1, vec2) << std::endl;\n\tstd::cout << \"Projection F distance: \" << mf_t::distPF_squared(vec1, vec2) << std::endl;\n\n\tstd::cout<< \"\\n\\n==========PERMUTATION MATRIX TEST==========\" << std::endl;\n\n\tauto vec1t = vec1.transpose();\n\tEigen::VectorXd vecvec1 = Eigen::Map<Eigen::VectorXd>(vec1.data(), vec1.size());\n\tEigen::VectorXd vecvec1t = Eigen::Map<Eigen::VectorXd>(vec1t.data(), vec1t.size());\n\n\tstd::cout << \"\\n\\nTest of the Permutation Matrix Knp:\" <<std::endl;\n\tstd::cout << \"s1:\\n\" << vec1 << std::endl;\n\tstd::cout << \"s1^t:\\n\" << vec1t << std::endl;\n\tstd::cout << \"\\nVectorized s1:\\n\" << vecvec1 << std::endl;\n\tstd::cout << \"\\nVectorized s1^t:\\n\" << vecvec1t << std::endl;\n\tstd::cout << \"\\nPermutation Matrix:\\n\" << mf_t::permutation_matrix.toDenseMatrix() << std::endl;\n\tstd::cout << \"\\nPermutation Matrix Indices:\\n\" << mf_t::permutation_matrix.indices() << std::endl;\n\tstd::cout << \"\\nP * Vectorized s1:\\n\" << mf_t::permutation_matrix * vecvec1 << std::endl;\n\n\tstd::cout<< \"\\n\\n==========DERIVATIVE COMPUTATION TEST==========\" << std::endl;\n\ttypedef typename mf_t::deriv2_type mat9x9;\n\n\tmat d1x,d1y;\n\tmf_t::deriv1x_dist_squared(vec1, vec2, d1x);\n\tmf_t::deriv1y_dist_squared(vec1, vec2, d1y);\n\tmat9x9 d2xx, d2xy, d2yy; \n\tmf_t::deriv2xx_dist_squared(vec1, vec2, d2xx);\n\tmf_t::deriv2xy_dist_squared(vec1, vec2, d2xy);\n\tmf_t::deriv2yy_dist_squared(vec1, vec2, d2yy);\n\t\n\tstd::cout << \"\\nFirst Derivative:\" << std::endl;\n\tstd::cout << d1x << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << d1y << std::endl;\n\n\tstd::cout << \"\\nSecond Derivative:\" << std::endl;\n\tstd::cout << d2xx << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << d2xy << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << d2yy << std::endl;\n\n\tstd::cout<< \"\\n\\n==========TANGENT SPACE BASIS TEST==========\" << std::endl;\n\tmf_t::tm_base_type t, t2;\n\tmf_t::tangent_plane_base(vec1, t);\n\tstd::cout << \"\\nTangent Base Restriction:\" << std::endl;\n\tstd::cout << t << std::endl;\n\tstd::cout << \"\\nTangent Base Restriction alternative calculatiopn: \" << std::endl;\n\tEigen::HouseholderQR<mf_t::value_type> qr(vec1);\n\tEigen::Matrix<mf_t::scalar_type, N, N> Q = qr.householderQ();\n\tEigen::Matrix<mf_t::scalar_type, N, N - P> vec1orth = Q.rightCols(N-P);\n\tt2 = Eigen::kroneckerProduct(Eigen::Matrix<mf_t::scalar_type, P, P>::Identity(), vec1orth.transpose());\n\tstd::cout << t2 << std::endl;\n\n\tstd::cout<< \"\\n\\n==========RESTRICTED DERIVIATIVES COMPUTATION TEST==========\" << std::endl;\n\tmf_t::restricted_deriv2_type rd2xx, rd2xy, rd2yy;\n\trd2xx = t.transpose() * d2xx * t;\n\trd2xy = t.transpose() * d2xy * t;\n\trd2yy = t.transpose() * d2yy * t;\n\tstd::cout << \"\\nRestricted second Derivatives:\" << std::endl;\n\tstd::cout << rd2xx << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << rd2xy << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << rd2yy << std::endl;\n\n\tstd::cout<< \"\\n\\n==========EXPONENTIAL LOGARITHM CONSISTENCY CHECK==========\" << std::endl;\n\tmf_t::value_type u, z, v;\n\tstd::cout << \"\\n\\nExponential map test:\" << std::endl;\n\tmf_t::exp(vec1, vec2, z);\n\tstd::cout << \"Exp(s1,s2) = \\n\" << z << std::endl;\n\n\n\tmf_t::log(vec1, vec2, u);\n\tmf_t::exp(vec1, u, z);\n\tmf_t::log(vec1, z, v);\n\tstd::cout << \"\\nLogarithm map test:\" << std::endl;\n\tstd::cout << \"U = Log(s1, s2) = \\n\" << u << std::endl;\n\tstd::cout << \"\\nThe next two expression should be the same:\" << std::endl;\n\tstd::cout << \"distGeod_squared(s1, s2) = \" << mf_t::distGeod_squared(vec1,vec2) << std::endl;\n\tstd::cout << \"tr U^TU = \" << (u.transpose()*u).trace() << std::endl;\n    \n\n\tstd::cout << \"\\nZ = Exp(s1, U) = \\n\"  << z << \"\\n and s2  =\\n\" << vec2 << \"\\nshould have distance close to zero for geodesic and projection F-norm :\\n\";\n\tstd::cout << \"\\ndistGeod_squared(Z, s2) = \" << mf_t::distGeod_squared(z,vec2) << std::endl;\n\tstd::cout << \"distPF_squared(Z, s2) = \" << mf_t::distPF_squared(z,vec2) << std::endl;\n//\tstd::cout << \"\\nV = Log(s1, Z) = \\n\" << v << std::endl;\n\n\n\tstd::cout<< \"\\n\\n==========KARCHER MEAN CONSISTENCY TEST==========\" << std::endl;\n\tmf_t::value_type kmean, d1, d2, sum; \n\tmf_t::karcher_mean(kmean, vec1, vec2);\n\t\n\tstd::cout << \"\\nK = K(s1, s2) =\\n \" << kmean << std::endl;\n\tmf_t::log(kmean, vec1, d1);\n\tmf_t::log(kmean, vec2, d2);\n\tsum = d1 + d2;\n\tstd::cout << \"\\n||Sum_i Log(K, si)|| should be close to zero:\" << (sum.transpose()*sum).trace() << std::endl;\n\tstd::cout << \"\\nThe following four distances should all be approximately equal, the upper pair and the lower pair should be exactly equal:\\n\";\n\tstd::cout << \"Geodesic squared distance between s1 and K: \" << mf_t::distGeod_squared(vec1, kmean) << std::endl;\n\tstd::cout << \"Geodesic squared distance between s2 and K: \" << mf_t::distGeod_squared(vec2, kmean) << std::endl;\n\tstd::cout << \"Projection F squared distance between s1 and K: \" << mf_t::distPF_squared(vec1, kmean) << std::endl;\n\tstd::cout << \"Projection F squared distance between s2 and K: \" << mf_t::distPF_squared(vec2, kmean) << std::endl;\n\n\tstd::cout<< \"\\n\\n==========KARCHER MEAN NEWTON TEST==========\" << std::endl;\n\tmf_t::value_type grad, X, Y, s;\n\tmat9x9 H;\n\tEigen::VectorXd G, S;\n\t\n\ttypedef Eigen::Matrix<mf_t::scalar_type, N, N> matn;\n\ttypedef Eigen::Matrix<mf_t::scalar_type, P, P> matp;\n\ttypedef Eigen::Matrix<mf_t::scalar_type, P, N> matpn;\n\n\tmatn I = Eigen::Matrix<mf_t::scalar_type, N, N>::Identity();\n\tmatp Ip = Eigen::Matrix<mf_t::scalar_type, P, P>::Identity();\n\n\tmatn XorthP, H1;\n\tmatp H2;\n\n\t\n\tX=vec1;\n\n\tfor (int i=0; i<8; ++i){\n\t    XorthP = I - X * X.transpose();\n\t    grad = -XorthP * vec1 * vec1.transpose() * X - XorthP * vec2 * vec2.transpose() * X;\n\t    H1 = XorthP * vec1 * vec1.transpose() + XorthP * vec2 * vec2.transpose();\n\t    H2 = X.transpose() * vec1 * vec1.transpose() * X +  X.transpose() * vec2 * vec2.transpose() * X;\n\t    H = kroneckerProduct(Ip, H1) - kroneckerProduct(H2.transpose(), I);\n\t    G = Eigen::Map<Eigen::VectorXd>(grad.data(), grad.size());\n\t    S = H.fullPivLu().solve(G);\n\t    s = Eigen::Map<mf_t::value_type>(S.data());\n\t    mf_t::exp(X,s,X);\n\t}\n\tstd::cout << \"\\nK = K(s1, s2) =\\n \" << X << std::endl;\n\t\n\tstd::cout << \"\\n||grad|| should be close to zero:\" << (grad.transpose()*grad).trace() << std::endl;\n\tstd::cout << \"\\nThe following four distances should all be approximately equal, the upper pair and the lower pair should be exactly equal:\\n\";\n\tstd::cout << \"Geodesic squared distance between s1 and K: \" << mf_t::distGeod_squared(vec1, X) << std::endl;\n\tstd::cout << \"Geodesic squared distance between s2 and K: \" << mf_t::distGeod_squared(vec2, X) << std::endl;\n\tstd::cout << \"Projection F squared distance between s1 and K: \" << mf_t::distPF_squared(vec1, X) << std::endl;\n\tstd::cout << \"Projection F squared distance between s2 and K: \" << mf_t::distPF_squared(vec2, X) << std::endl;\n\n\tstd::cout << \"\\n\\n------WITH TANGENT SPACE RESTRICTION-----\"    << std::endl;\n\tX=vec1;\n\n\tmf_t::restricted_deriv2_type HR;\n\tEigen::VectorXd GR, SR;\n\tmf_t::tm_base_type tb;\n\n\tfor (int i=0; i<8; ++i){\n\t    XorthP = I - X * X.transpose();\n\t    grad = -XorthP * vec1 * vec1.transpose() * X - XorthP * vec2 * vec2.transpose() * X;\n\t    H1 = XorthP * vec1 * vec1.transpose() + XorthP * vec2 * vec2.transpose();\n\t    H2 = X.transpose() * vec1 * vec1.transpose() * X +  X.transpose() * vec2 * vec2.transpose() * X;\n\t    H = kroneckerProduct(Ip, H1) - kroneckerProduct(H2.transpose(), I);\n\t    G = Eigen::Map<Eigen::VectorXd>(grad.data(), grad.size());\n\t    mf_t::tangent_plane_base(X, tb);\n\t    HR = tb.transpose() * H * tb;\n\t    GR = tb.transpose() * G;\n\t    SR = HR.fullPivLu().solve(GR);\n\t    S = tb * SR;\n\t    s = Eigen::Map<mf_t::value_type>(S.data());\n\t    mf_t::exp(X,s,X);\n\t}\n\n\tstd::cout << \"\\nK = K(s1, s2) =\\n \" << X << std::endl;\n\t\n\tstd::cout << \"\\n||grad|| should be close to zero:\" << (grad.transpose()*grad).trace() << std::endl;\n\tstd::cout << \"\\nThe following four distances should all be approximately equal, the upper pair and the lower pair should be exactly equal:\\n\";\n\tstd::cout << \"Geodesic squared distance between s1 and K: \" << mf_t::distGeod_squared(vec1, X) << std::endl;\n\tstd::cout << \"Geodesic squared distance between s2 and K: \" << mf_t::distGeod_squared(vec2, X) << std::endl;\n\tstd::cout << \"Projection F squared distance between s1 and K: \" << mf_t::distPF_squared(vec1, X) << std::endl;\n\tstd::cout << \"Projection F squared distance between s2 and K: \" << mf_t::distPF_squared(vec2, X) << std::endl;\n\n\n\n\n\tstd::cout<< \"\\n\\n==========2ND ORDER TAYLOR DERIVATIVE CONSISTENCY CHECK==========\" << std::endl;\n\tdouble h = 1e-4;\n\tstd::cout << \"\\n\\nTaylor expansion Derivative Tests with perturbation O(h) = O(\" << h << \")\" <<std::endl;\n\tmf_t::value_type dx, dy;\n\n\tmatn HXproj = I - vec1 * vec1.transpose();\n\tmatn HYproj = I - vec2 * vec2.transpose();\n\t\n\tstd::cout << \"\\n------Tangent vector tests-----\"    << std::endl;\n\tmat Xpdx, Ypdy;\n\tdx = mat::Random(); mf_t::projector(dx); dx = h * HXproj * dx;\n\tmf_t::exp(vec1, dx, Xpdx);\n\tEigen::VectorXd vecdx = Eigen::Map<Eigen::VectorXd>(dx.data(), dx.size());\n\tstd::cout << \"\\ndx should be in the horizontal space at X, i.e. X^Tdx=0:\\n \"<< (vec1.transpose()*dx).norm() << std::endl;\n\t\n\tdy = mat::Random(); mf_t::projector(dy); dy = h * HYproj * dy;\n\tmf_t::exp(vec2, dy, Ypdy);\n\tEigen::VectorXd vecdy = Eigen::Map<Eigen::VectorXd>(dy.data(), dy.size());\n\tstd::cout << \"\\ndy should be in the horizontal space at Y, i.e. Y^Tdy=0:\\n \"<< (vec2.transpose()*dy).norm() << std::endl;\n\t\n\tdouble exact = mf_t::dist_squared(vec1 + dx, vec2 + dy);\n\tdouble exact2 = mf_t::dist_squared(Xpdx, Ypdy);\n\tdouble taylor_order1 = mf_t::dist_squared(vec1, vec2) + d1x.cwiseProduct(dx).sum() + d1y.cwiseProduct(dy).sum();\n\tdouble taylor_order2 = taylor_order1 + 0.5 * d2xx.cwiseProduct(vecdx * vecdx.transpose()).sum() + 0.5 * d2yy.cwiseProduct(vecdy * vecdy.transpose()).sum() + d2xy.cwiseProduct(vecdx * vecdy.transpose()).sum();\n\n\tstd::cout << \"\\n\\nError of first order Taylor \" << std::abs(taylor_order1 - exact) << \" = O(h^\"<< std::log10(std::abs(taylor_order1 - exact))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"Error of first order Taylor \" << std::abs(taylor_order1 - exact2) << \" = O(h^\"<< std::log10(std::abs(taylor_order1 - exact2))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"\\nError of second order Taylor \" << std::abs(taylor_order2 - exact) << \" = O(h^\"<< std::log10(std::abs(taylor_order2 - exact))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"Error of second order Taylor \" << std::abs(taylor_order2 - exact2) << \" = O(h^\"<< std::log10(std::abs(taylor_order2 - exact2))/std::log10(h)  << \") \" <<std::endl; \n\n\n\tstd::cout<< \"\\n\\n==========2ND ORDER TAYLOR DERIVATIVE ALTERNATIVE CHECK==========\" << std::endl;\n\th = 1e-4;\n\tstd::cout << \"\\n\\nTaylor expansion Derivative Tests with perturbation O(h) = O(\" << h << \")\" <<std::endl;\n\tstd::cout << \"\\n------Single variable, fixed Y-----\"    << std::endl;\n\n\tX=vec1;\n\tY=vec2;\n\n\tXorthP = I - X * X.transpose();\n\tgrad = -XorthP * Y * Y.transpose() * X;\n\n\tH1 = XorthP * Y * Y.transpose();\n\tH2 = X.transpose() * Y * Y.transpose() * X;\n\tH = kroneckerProduct(Ip, H1) - kroneckerProduct(H2.transpose(), I);\n\n\tdouble exact1, exact3, exact4;\n\tdouble taylor_firstorder = mf_t::dist_squared(X, Y) + grad.cwiseProduct(dx).sum();\n\n\texact1 = mf_t::distGeod_squared(Xpdx,Y);\n\texact2 = mf_t::distGeod_squared(X+dx,Y);\n\texact3 = mf_t::dist_squared(Xpdx,Y);\n\texact4 = mf_t::dist_squared(X+dx,Y);\n\n\t\n\n\tstd::cout << \"\\nGeodesic distances at (X,Y): \" << mf_t::distGeod_squared(X,Y) << std::endl;\n\tstd::cout << \"1)Geodesic distances at (exp_X(dx),Y): \" << mf_t::distGeod_squared(Xpdx,Y) << std::endl;\n\tstd::cout << \"2)Geodesic distances at (X+dx,Y): \" << mf_t::distGeod_squared(X+dx,Y) << std::endl;\n\tstd::cout << \"\\nProjection F distance at (X,Y): \" << mf_t::dist_squared(X,Y) << std::endl;\n\tstd::cout << \"3)Projection F distance at (exp_X(dx),Y): \" << mf_t::dist_squared(Xpdx,Y) << std::endl;\n\tstd::cout << \"4)Projection F distance at (X+dx,Y): \" << mf_t::dist_squared(X+dx,Y) << std::endl;\n\n\n\tstd::cout << \"\\n1)Error of first order Taylor \" << std::abs(taylor_firstorder - exact1) << \" = O(h^\"<< std::log10(std::abs(taylor_firstorder - exact1))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"2)Error of first order Taylor \" << std::abs(taylor_firstorder - exact2) << \" = O(h^\"<< std::log10(std::abs(taylor_firstorder - exact2))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"\\n3)Error of first order Taylor \" << std::abs(taylor_firstorder - exact3) << \" = O(h^\"<< std::log10(std::abs(taylor_firstorder - exact3))/std::log10(h)  << \") \" <<std::endl; \n\tstd::cout << \"4)Error of first order Taylor \" << std::abs(taylor_firstorder - exact4) << \" = O(h^\"<< std::log10(std::abs(taylor_firstorder - exact4))/std::log10(h)  << \") \" <<std::endl; \n\n}\n\nint main(int argc, const char *argv[])\n{\n\tsrand(42);\n\n\tmat s1, s2;\n\ts1 = mat::Random();\n\tmf_t::projector(s1);\n\n\ts2 = mat::Random();\n\tmf_t::projector(s2);\n\n\tstd::cout << \"s1=\\n\" << s1 << std::endl;\n\n\tstd::cout << \"\\n\\nRANDOM Matrices\" << std::endl;\n\ttest(s1,s2);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "767ecd8df2c77eccd3ae4978df9dc455955fd0a0", "size": 13622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/manifold_grassmann_test.cpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "test/manifold_grassmann_test.cpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/manifold_grassmann_test.cpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1762711864, "max_line_length": 209, "alphanum_fraction": 0.621274409, "num_tokens": 4528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5821970347894317}}
{"text": "// An interval object.\n#pragma once\n\n#include <array>\n\n#include <Eigen/Core>\n\n#include <tight_inclusion/types.hpp>\n\nnamespace ticcd {\n    // calculate a*(2^b)\n    uint64_t power(const uint64_t a, const uint8_t b);\n\n    // calculate 2^exponent\n    inline uint64_t pow2(const uint8_t exponent) { return power(1l, exponent); }\n\n    // return power t. n=result*2^t\n    uint8_t reduction(const uint64_t n, uint64_t &result);\n\n    //<k,n> pair present a number k/pow(2,n)\n    struct NumCCD {\n        uint64_t numerator;\n        uint8_t denom_power;\n\n        NumCCD() {}\n\n        NumCCD(uint64_t p_numerator, uint8_t p_denom_power)\n            : numerator(p_numerator), denom_power(p_denom_power)\n        {\n        }\n\n        NumCCD(Scalar x);\n\n        ~NumCCD() {}\n\n        uint64_t denominator() const { return pow2(denom_power); }\n\n        // convert NumCCD to double number\n        Scalar value() const { return Scalar(numerator) / denominator(); }\n\n        operator double() const { return value(); }\n\n        NumCCD operator+(const NumCCD &other) const;\n\n        bool operator==(const NumCCD &other) const\n        {\n            return numerator == other.numerator\n                   && denom_power == other.denom_power;\n        }\n        bool operator!=(const NumCCD &other) const { return !(*this == other); }\n        bool operator<(const NumCCD &other) const;\n        bool operator<=(const NumCCD &other) const\n        {\n            return (*this == other) || (*this < other);\n        }\n        bool operator>=(const NumCCD &other) const { return !(*this < other); }\n        bool operator>(const NumCCD &other) const { return !(*this <= other); }\n\n        bool operator<(const Scalar other) const { return value() < other; }\n        bool operator>(const Scalar other) const { return value() > other; }\n        bool operator==(const Scalar other) const { return value() == other; }\n\n        static bool is_sum_leq_1(const NumCCD &num1, const NumCCD &num2);\n    };\n\n    // an interval represented by two double numbers\n    struct Interval {\n        NumCCD lower;\n        NumCCD upper;\n\n        Interval() {}\n\n        Interval(const NumCCD &p_lower, const NumCCD &p_upper)\n            : lower(p_lower), upper(p_upper)\n        {\n        }\n\n        ~Interval() {}\n\n        std::pair<Interval, Interval> bisect() const;\n\n        bool overlaps(const Scalar r1, const Scalar r2) const;\n    };\n\n    typedef std::array<Interval, 3> Interval3;\n    Array3 width(const Interval3 &x);\n\n} // namespace ticcd\n", "meta": {"hexsha": "31499250d1f8f76a65020ed9c5c7a1532ca76014", "size": 2494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tight_inclusion/interval.hpp", "max_stars_repo_name": "Continous-Collision-Detection/Tight-Inclusion", "max_stars_repo_head_hexsha": "d9b82d9bb173abb6d4ea3598a8a057353b18745f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tight_inclusion/interval.hpp", "max_issues_repo_name": "Continous-Collision-Detection/Tight-Inclusion", "max_issues_repo_head_hexsha": "d9b82d9bb173abb6d4ea3598a8a057353b18745f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tight_inclusion/interval.hpp", "max_forks_repo_name": "Continous-Collision-Detection/Tight-Inclusion", "max_forks_repo_head_hexsha": "d9b82d9bb173abb6d4ea3598a8a057353b18745f", "max_forks_repo_licenses": ["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.0224719101, "max_line_length": 80, "alphanum_fraction": 0.5994386528, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021788, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5821968252435974}}
{"text": "/*\n * Common.hpp\n *\n *  Created on: Feb 9, 2014\n *      Author: Bloeschm\n */\n\n#ifndef LWF_COMMON_HPP_\n#define LWF_COMMON_HPP_\n\n#include <map>\n#include <type_traits>\n#include <tuple>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"lightweight_filtering/PropertyHandler.hpp\"\n\ntypedef Eigen::Quaterniond QPD;\ntypedef Eigen::Matrix3d MPD;\ntypedef Eigen::Vector3d V3D;\ntypedef Eigen::Matrix3d M3D;\ntypedef Eigen::VectorXd VXD;\ntypedef Eigen::MatrixXd MXD;\n\ninline M3D gSM(const V3D& vec){\n  M3D mat;\n  mat << 0, -vec(2), vec(1), vec(2), 0, -vec(0), -vec(1), vec(0), 0;\n  return mat;\n}\n\nstatic void enforceSymmetry(MXD& mat){\n  mat = 0.5*(mat+mat.transpose()).eval();\n}\n\ninline M3D Lmat (const V3D& a) {\n  const double norm = a.norm();\n  const M3D skewMatrix = gSM(a);\n  if (norm < 1.0e-4) {\n    return M3D::Identity() + 0.5*skewMatrix;\n  }\n  return M3D::Identity() + (double(1.0) - cos(norm))/(norm*norm)*skewMatrix + (norm - sin(norm))/(norm*norm*norm)*(skewMatrix*skewMatrix);\n}\n\ninline V3D log_map(const QPD& q) {\n    using std::acos;\n    using std::sqrt;\n\n    // define these compile time constants to avoid std::abs:\n    static const double twoPi = 2.0 * M_PI, NearlyOne = 1.0 - 1e-10,\n    NearlyNegativeOne = -1.0 + 1e-10;\n\n    V3D omega;\n\n    const double qw = q.w();\n    // See Quaternion-Logmap.nb in doc for Taylor expansions\n    if (qw > NearlyOne) {\n      // Taylor expansion of (angle / s) at 1\n      // (2 + 2 * (1-qw) / 3) * q.vec();\n      omega = ( 8. / 3. - 2. / 3. * qw) * q.vec();\n    } else if (qw < NearlyNegativeOne) {\n      // Taylor expansion of (angle / s) at -1\n      // (-2 - 2 * (1 + qw) / 3) * q.vec();\n      omega = (-8. / 3. - 2. / 3. * qw) * q.vec();\n    } else {\n      // Normal, away from zero case\n      double angle = 2 * acos(qw), s = sqrt(1 - qw * qw);\n      // Important:  convert to [-pi,pi] to keep error continuous\n      if (angle > M_PI)\n      angle -= twoPi;\n      else if (angle < -M_PI)\n      angle += twoPi;\n      omega = (angle / s) * q.vec();\n    }\n\n    return omega;\n}\n\ninline QPD exp_map(const V3D& omega) {\n    using std::cos;\n    using std::sin;\n\n    double theta2 = omega.dot(omega);\n    if (theta2 > std::numeric_limits<double>::epsilon()) {\n      double theta = std::sqrt(theta2);\n      double ha = 0.5 * theta;\n      V3D vec = (sin(ha) / theta) * omega;\n      return QPD(cos(ha), vec.x(), vec.y(), vec.z());\n    } else {\n      // first order approximation sin(theta/2)/theta = 0.5\n      V3D vec = 0.5 * omega;\n      return QPD(1.0, vec.x(), vec.y(), vec.z());\n    }\n}\n\ninline QPD box_plus(const QPD& q, const V3D& v) {\n  return exp_map(v) * q;\n}\n\ninline V3D box_minus(const QPD& q1, const QPD& q2) {\n  return log_map(q1 * q2.inverse());\n}\n\nnamespace LWF{\n  enum FilteringMode{\n    ModeEKF,\n    ModeUKF,\n    ModeIEKF\n  };\n}\n\n#endif /* LWF_COMMON_HPP_ */\n", "meta": {"hexsha": "33f58ad0192df05763a0b893e2ee48148e8b4953", "size": 2810, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lightweight_filtering/include/lightweight_filtering/common.hpp", "max_stars_repo_name": "nicolov/rovio_fork", "max_stars_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T01:00:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-05T01:00:08.000Z", "max_issues_repo_path": "lightweight_filtering/include/lightweight_filtering/common.hpp", "max_issues_repo_name": "nicolov/rovio_fork", "max_issues_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lightweight_filtering/include/lightweight_filtering/common.hpp", "max_forks_repo_name": "nicolov/rovio_fork", "max_forks_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_forks_repo_licenses": ["BSD-3-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.0892857143, "max_line_length": 138, "alphanum_fraction": 0.5900355872, "num_tokens": 942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5821968163569415}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <complex>\n#include <tuple>\n\n#include <chrono>\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/complex_field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n#include \"vlasovpp/splitting.h\"\n#include \"vlasovpp/lagrange5.h\"\n#include \"vlasovpp/config.h\"\n#include \"vlasovpp/signal_handler.h\"\n\nstruct iter_s {\n  std::size_t iter;\n  double dt;\n  double current_time;\n  double Lhfh;\n  double LE;\n};\n/*\nstruct time_stages {\n  std::chrono::duration<double> step;\n  std::chrono::duration<double> stage_1;\n  std::chrono::duration<double> stage_2;\n  std::chrono::duration<double> stage_3;\n  std::chrono::duration<double> stage_4;\n  std::chrono::duration<double> stage_5;\n};\n*/\n#define save(data,dir,suffix,x_y) {\\\n  std::stringstream filename; filename << #data << \"_\" << suffix << \".dat\"; \\\n  std::ofstream of( dir / filename.str() );\\\n  std::transform( data.begin() , data.end() , std::ostream_iterator<std::string>(of,\"\\n\") , x_y );\\\n  of.close();\\\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*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\n\n#define ping(X) std::cerr << __LINE__ << \" \" << #X << \":\" << X << std::endl\nint debug = 0;\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  //std::cout << rho << \" \" << u << \" \" << T << std::endl;\n  //std::cout << rho/(std::sqrt(2.*math::pi<double>()*T)) << std::endl;\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\n  std::string p(\"config.init\");\n  if ( argc > 1 ) {\n    p = argv[1];\n  }\n  auto c = config(p);\n  c.name = \"vhls\";\n\n  c.create_output_directory();\n  std::cout << c << std::endl;\n  std::ofstream oconfig( c.output_dir / \"config.init\" );\n  oconfig << c << std::endl;\n  oconfig.close();\n\n/* --------------------------------------------------------------- */\n  std::size_t Nx = c.Nx, Nv = c.Nv;\n\n  // $(u_c,E,\\hat{f}_h)$ and $f_h$\n  ublas::vector<double> uc(Nx,0.);\n  ublas::vector<double> E (Nx,0.);\n  field<double,1> fh(boost::extents[Nv][Nx]);\n  complex_field<double,1> hfh(boost::extents[Nv][Nx]);\n  ublas::vector<double> uc1(Nx) , uc2(Nx) , uc3(Nx) , uc4(Nx) , ucn(Nx),\n                        E1 (Nx) , E2 (Nx) , E3 (Nx) , E4 (Nx) , En (Nx);\n  complex_field<double,1> hfh1(boost::extents[Nv][Nx]) , hfh2(boost::extents[Nv][Nx]) ,\n                          hfh3(boost::extents[Nv][Nx]) , hfh4(boost::extents[Nv][Nx]) ,\n                          hfhn(boost::extents[Nv][Nx]) ;\n\n  const double Kx = 0.5;\n  // phase-space domain\n  fh.range.v_min = -12.; fh.range.v_max = 12.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n\n  // compute dx, dv\n  fh.step.dv = (fh.range.v_max-fh.range.v_min)/Nv;\n  fh.step.dx = (fh.range.x_max-fh.range.x_min)/Nx;\n\n  double dt = 0.04; //0.5*fh.step.dv;\n  \n  // velocity and frequency\n  ublas::vector<double> v (Nv,0.); for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  const double l = fh.range.x_max-fh.range.x_min;\n  ublas::vector<double> kx(Nx);\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\n  // initial condition\n  auto tb_M1 = maxwellian(0.5*c.alpha,c.ui,1.) , tb_M2 = maxwellian(0.5*c.alpha,-c.ui,1.);\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      //fh[k][i] = ( 0.5*c.alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-c.ui)) + 0.5*c.alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)+c.ui)) )*(1.+0.04*std::cos(0.3*Xi(i)));\n      //fh[k][i] = ( 0.5*c.alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-c.ui)) + 0.5*c.alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)+c.ui)) )*(1.+0.04*std::cos(Kx*Xi(i)));\n\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n    fft::fft(&(fh[k][0]),&(fh[k][Nx-1])+1,&(hfh[k][0]));\n  }\n  fh.write( c.output_dir / \"init_vhls.dat\" );\n/*\n  std::cout << \"Nx: \" << Nx << \"\\n\";\n  std::cout << \"Nv: \" << Nv << \"\\n\";\n  std::cout << \"v_min: \" << fh.range.v_min << \"\\n\";\n  std::cout << \"v_max: \" << fh.range.v_max << \"\\n\";\n  std::cout << \"x_min: \" << fh.range.x_min << \"\\n\";\n  std::cout << \"x_max: \" << fh.range.x_max << \"\\n\";\n  std::cout << \"dt: \" << dt << \"\\n\";\n  std::cout << \"dx: \" << fh.step.dx << \"\\n\";\n  std::cout << \"dv: \" << fh.step.dv << \"\\n\";\n  std::cout << \"Tf: \" << c.Tf << \"\\n\";\n  std::cout << \"f_0: \" << \"\\\"tb\\\"\" << \"\\n\";\n  std::cout << std::endl;\n*/\n  const double rho_c = 1.-c.alpha;\n  // init E (electric field) with Poisson\n  {\n    poisson<double> poisson_solver(Nx,l);\n    ublas::vector<double> rho(Nx,0.);\n    rho = fh.density(); // compute density from init data\n    for ( auto i=0 ; i<Nx ; ++i ) { rho[i] += rho_c; } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n  }\n\n  // monitoring data\n  std::vector<iter_s> iterations; iterations.reserve(int(std::ceil(c.Tf/dt))+1);\n  std::vector<iter_s> success_iterations; success_iterations.reserve(int(std::ceil(c.Tf/dt))+1);\n  std::vector<double> ee;\n  std::vector<double> Emax;\n  std::vector<double> H;\n  std::vector<double> times;\n\n  //std::vector<time_stages> durations_s; durations_s.reserve(int(std::ceil(c.Tf/dt))+1);\n\n\n\n  auto save_data = [&] ( std::string suffix ) {\n    save(iterations,c.output_dir,suffix,[](auto const& it) { std::stringstream ss; ss << it.iter << \" \" << it.dt << \" \" << it.current_time << \" \" << it.Lhfh << \" \" << it.LE; return ss.str(); })\n    save(success_iterations,c.output_dir,suffix,[](auto const& it) { std::stringstream ss; ss << it.iter << \" \" << it.dt << \" \" << it.current_time << \" \" << it.Lhfh << \" \" << it.LE; return ss.str(); })\n\n    auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<times[count++]<<\" \"<<y; return ss.str(); };\n    save(ee,c.output_dir,suffix,dt_y);\n    save(Emax,c.output_dir,suffix,dt_y);\n    save(H,c.output_dir,suffix,dt_y);\n\n    /*\n    auto writer_times = [&,count=0] (auto const & t ) mutable {\n      std::stringstream ss;\n      ss<<times[count++]<<\" \"<<t.step.count()<<\" \"<<t.stage_1.count()<<\" \"<<t.stage_2.count()<<\" \"<<t.stage_3.count()<<\" \"<<t.stage_4.count()<<\" \"<<t.stage_5.count();\n      return ss.str();\n    };\n    c << monitoring::data( \"times_\"+suffix+\".dat\" , durations_s , writer_times );\n    */\n  };\n\n\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[36msave data...\\033[0m\\n\";\n\n    save_data(\"vhls_SIGINT\");\n    for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n    fh.write( c.output_dir / \"vp_vhls_SIGINT.dat\" );\n  });\n\n  /*\n  signal_handler::signal_handler<SIGINT>::function_handler = [&](int signal) {\n    std::cerr << \"\\n\\033[41;97m ** End of execution after signal \" << signal << \" ** \\033[0m\\n\";\n    std::cerr << \"\\033[36msave data...\\033[0m\\n\" ;\n\n    save_data(\"vhls_SIGINT\");\n    for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(&(hfh[k][0]),&(hfh[k][0])+c.Nx,&(fh[k][0])); }\n    fh.write( c.output_dir / \"vp_vhls_SIGINT.dat\" );\n  };\n  signal_handler::signal_handler<SIGINT>::signal();\n  */\n\n  times.push_back(0);\n  {\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n  }\n  Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n\n  //U_type<double,1> U({uc,E,hfh};\n  splitting<double,1> Lie( fh , l , rho_c );\n\n  std::size_t i_t = 0;\n  double current_time = 0.;\n  const double alpha1=1./(4.-std::cbrt(4.)), alpha2=alpha1, alpha3=1./(1.-SQ(std::cbrt(4.)));\n\n  const double g1 = alpha1, g2 = alpha1+alpha2;\n  const double w1 = (g2*(1.-g2))/(g1*(g1-1.)-g2*(g2-1.)) , w2 = 1.-w1 , w3 = w2 , w4 = w1;\n\n  while ( current_time < c.Tf ) {\n    std::cout<<\"\\r [\"<<std::setw(6)<<i_t<<\"] \"<< std::setw(8) << current_time << \" (\" << std::setw(9) << dt << \")\"<<std::flush;\n    /**\n    // Strang classique\n    Lie.phi_a(0.5*dt,uc,E,hfh);\n    Lie.phi_b(0.5*dt,uc,E,hfh);\n    Lie.phi_c(dt,uc,E,hfh);\n    Lie.phi_b(0.5*dt,uc,E,hfh);\n    Lie.phi_a(0.5*dt,uc,E,hfh);\n    /**/\n\n    std::copy( hfh.origin() , hfh.origin()+hfh.num_elements() , hfhn.origin() );\n    std::copy(  E.begin() ,  E.end() ,  En.begin() );\n    std::copy( uc.begin() , uc.end() , ucn.begin() );\n\n    //auto start = std::chrono::high_resolution_clock::now();\n    // Strang alpha1\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha1*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    //auto end_s1 = std::chrono::high_resolution_clock::now();\n\n    std::copy( hfh.origin() , hfh.origin()+hfh.num_elements() , hfh1.origin() );\n    std::copy(  E.begin() ,  E.end() ,  E1.begin() );\n    std::copy( uc.begin() , uc.end() , uc1.begin() );\n\n    //auto start_s2 = std::chrono::high_resolution_clock::now();\n    // Strang alpha2\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha2*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    //auto end_s2 = std::chrono::high_resolution_clock::now();\n\n    std::copy( hfh.origin() , hfh.origin()+hfh.num_elements() , hfh2.origin() );\n    std::copy(  E.begin() ,  E.end() ,  E2.begin() );\n    std::copy( uc.begin() , uc.end() , uc2.begin() );\n\n    //auto start_s3 = std::chrono::high_resolution_clock::now();\n    // Strang alpha3\n    Lie.phi_a(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha3*dt,uc,E,hfh);\n    Lie.phi_c(alpha3*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha3*0.5*dt,uc,E,hfh);\n    //auto end_s3 = std::chrono::high_resolution_clock::now();\n\n    std::copy( hfh.origin() , hfh.origin()+hfh.num_elements() , hfh3.origin() );\n    std::copy(  E.begin() ,  E.end() ,  E3.begin() );\n    std::copy( uc.begin() , uc.end() , uc3.begin() );\n\n    //auto start_s4 = std::chrono::high_resolution_clock::now();\n    // Strang alpha2\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha2*dt,uc,E,hfh);\n    Lie.phi_c(alpha2*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha2*0.5*dt,uc,E,hfh);\n    //auto end_s4 = std::chrono::high_resolution_clock::now();\n\n    std::copy( hfh.origin() , hfh.origin()+hfh.num_elements() , hfh4.origin() );\n    std::copy(  E.begin() ,  E.end() ,  E4.begin() );\n    std::copy( uc.begin() , uc.end() , uc4.begin() );\n\n   //auto start_s5 = std::chrono::high_resolution_clock::now();\n    // Strang alpha1\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_b(alpha1*dt,uc,E,hfh);\n    Lie.phi_c(alpha1*0.5*dt,uc,E,hfh);\n    Lie.phi_a(alpha1*0.5*dt,uc,E,hfh);\n    //auto end_s5 = std::chrono::high_resolution_clock::now();\n\n    //durations_s.push_back({ end_s5-start , end_s1-start , end_s2-start_s2 , end_s3-start_s3 , end_s4-start_s4 , end_s5-start_s5 });\n\n    /**/\n\n    double L_hfh = 0.;\n    for ( auto k=0 ; k<Nv ; ++k ) {\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        auto hfhtile_ik = -hfhn[k][i] + w1*(hfh1[k][i]+hfh4[k][i]) + w2*(hfh2[k][i]+hfh3[k][i]);\n        L_hfh += SQ( std::abs( hfh[k][i]-hfhtile_ik ) )*fh.step.dx*fh.step.dv;\n      }\n    }\n    L_hfh = std::sqrt(L_hfh);\n\n    double L_E = 0.;\n    for ( auto i=0 ; i<Nx ; ++i ) {\n      double Etile_ik = -En[i] + w1*(E1[i]+E4[i]) + w2*(E2[i]+E3[i]);\n      L_E += SQ( std::abs( E[i]-Etile_ik ) )*fh.step.dx;\n    }\n    L_E = std::sqrt(L_E);\n\n    std::cout << \" -- \" << std::setw(10) << L_hfh << \"        \" << std::flush;\n\n    //if ( std::abs(L_hfh - c.tol) <= c.tol ) // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n    {\n      // SAVE TIME STEP\n\n      Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      double electric_energy = 0.;\n      for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n      ee.push_back( std::sqrt(electric_energy) );\n      double total_energy = energy(fh,E);\n      {\n        auto rhoh = fh.density();\n        fft::spectrum_ hrhoh(c.Nx); hrhoh.fft(&rhoh[0]);\n        fft::spectrum_ hE(c.Nx); hE.fft(&E[0]);\n        fft::spectrum_ hrhoc(c.Nx);\n        hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n        for ( auto i=1 ; i<c.Nx ; ++i ) {\n          hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n        }\n        ublas::vector<double> rhoc (c.Nx,0.); hrhoc.ifft(&rhoc[0]);\n\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          total_energy += rhoc[i]*uc[i]*uc[i];\n        }\n      }\n      H.push_back( total_energy );\n\n      current_time += dt;\n      times.push_back( current_time );\n      success_iterations.push_back( { i_t , dt , current_time , L_hfh } );\n    }\n    /*else {\n      // REMAKE THE STEP\n      std::copy( hfhn.origin() , hfhn.origin()+hfhn.num_elements() , hfh.origin() );\n      std::copy( En.begin()  , En.end()  , E.begin() );\n      std::copy( ucn.begin() , ucn.end() , uc.begin() );\n    }*/\n\n    iterations.push_back( { i_t , dt , current_time , L_hfh } );\n    ++i_t;\n\n    //dt = std::pow( c.tol/L_hfh , 0.25 )*dt;\n    if ( current_time+dt > c.Tf ) { dt = c.Tf - current_time; }\n  } // while current_time < c.Tf\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt<<std::endl;\n\n  std::ofstream of;\n  std::size_t count = 0;\n\n  /*\n  auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<times[count++]<<\" \"<<y; return ss.str(); };\n\n  of.open( c.output_dir / \"ee_vhls.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_vhls.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_vhls.dat\" );\n  std::transform( H.begin() , H.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n  */\n  save_data(\"vhls_suzuki\");\n\n  for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(&(hfh[k][0]),&(hfh[k][Nx-1])+1,&(fh[k][0])); }\n  fh.write( c.output_dir / \"vp_vhls_suzuki.dat\" );\n\n  auto dx_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<< fh.step.dx*(count++) <<\" \"<<y; return ss.str(); };\n  save(E,c.output_dir,\"vhls\",dx_y);\n  save(uc,c.output_dir,\"vhls\",dx_y);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "91497f1b3f51ca1a4c245328c1ee632c29dc86a4", "size": 15010, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/cmp_vhls.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/cmp_vhls.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/cmp_vhls.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": 37.525, "max_line_length": 205, "alphanum_fraction": 0.5654896736, "num_tokens": 5236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.582196812941846}}
{"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/level3.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/upper.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 vector::size_type size_type;\n    rand_normal<complex>::reset();\n    {\n      size_type m=6, n=8;\n      matrix A(m, m);\n      matrix B(m, n);\n      matrix C(m, n);\n      for (size_type j=0; j<m; ++j)\n\tfor (size_type i=0; i<=j; ++i) {\n\t  A(i, j)=rand_normal<complex>::get();\n\t  A(j, i)=A(i, j);\n\t}\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i) \n\t  B(i, j)=rand_normal<complex>::get();\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i)\n\t  C(i, j)=rand_normal<complex>::get();\n      complex alpha(rand_normal<complex>::get());\n      complex beta(rand_normal<complex>::get());\n      matrix C1(alpha*ublas::prod(A, B)+beta*C);\n      matrix C2(C);\n      blas::symm(blas::left(), alpha, blas::upper(A), B, beta, C2);\n      std::cout << \"testing boost::ublas containers\\n\"\n\t\t<< \"using ublas (left multiply):\\n\" << print_mat(C1) << '\\n'\n\t\t<< \"using blas (left multiply):\\n\" << print_mat(C2) << '\\n'\n\t\t<< '\\n';\n    }\n    {\n      size_type m=6, n=8;\n      matrix A(n, n);\n      matrix B(m, n);\n      matrix C(m, n);\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<=j; ++i) {\n\t  A(i, j)=rand_normal<complex>::get();\n\t  A(j, i)=A(i, j);\n\t}\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i) \n\t  B(i, j)=rand_normal<complex>::get();\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i)\n\t  C(i, j)=rand_normal<complex>::get();\n      complex alpha(rand_normal<complex>::get());\n      complex beta(rand_normal<complex>::get());\n      matrix C1(alpha*ublas::prod(B, A)+beta*C);\n      matrix C2(C);\n      blas::symm(blas::right(), alpha, blas::upper(A), B, beta, C2);\n      std::cout << \"testing boost::ublas containers\\n\"\n\t\t<< \"using ublas (right multiply):\\n\" << print_mat(C1) << '\\n'\n\t\t<< \"using blas (right multiply):\\n\" << print_mat(C2) << '\\n'\n\t\t<< '\\n';\n    }\n  }\n  {\n    typedef std::complex<double> complex;\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    {\n      size_type m=6, n=8;\n      matrix A(m, m);\n      matrix B(m, n);\n      matrix C(m, n);\n      for (size_type j=0; j<m; ++j)\n\tfor (size_type i=0; i<=j; ++i) {\n\t  A(i, j)=rand_normal<complex>::get();\n\t  A(j, i)=A(i, j);\n\t}\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i) \n\t  B(i, j)=rand_normal<complex>::get();\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i)\n\t  C(i, j)=rand_normal<complex>::get();\n      complex alpha(rand_normal<complex>::get());\n      complex beta(rand_normal<complex>::get());\n      matrix C1(alpha*A*B+beta*C);\n      matrix C2(C);\n      blas::symm(blas::left(), alpha, blas::upper(A), B, beta, C2);\n      std::cout << \"testing Eigen containers\\n\"\n\t\t<< \"using Eigen (left multiply):\\n\" << print_mat(C1) << '\\n'\n\t\t<< \"using blas (left multiply):\\n\" << print_mat(C2) << '\\n'\n\t\t<< '\\n';\n    }\n    {\n      size_type m=6, n=8;\n      matrix A(n, n);\n      matrix B(m, n);\n      matrix C(m, n);\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<=j; ++i) {\n\t  A(i, j)=rand_normal<complex>::get();\n\t  A(j, i)=A(i, j);\n\t}\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i) \n\t  B(i, j)=rand_normal<complex>::get();\n      for (size_type j=0; j<n; ++j)\n\tfor (size_type i=0; i<m; ++i)\n\t  C(i, j)=rand_normal<complex>::get();\n      complex alpha(rand_normal<complex>::get());\n      complex beta(rand_normal<complex>::get());\n      matrix C1(alpha*B*A+beta*C);\n      matrix C2(C);\n      blas::symm(blas::right(), alpha, blas::upper(A), B, beta, C2);\n      std::cout << \"testing Eigen containers\\n\"\n\t\t<< \"using Eigen (right multiply):\\n\" << print_mat(C1) << '\\n'\n\t\t<< \"using blas (right multiply):\\n\" << print_mat(C2) << '\\n'\n\t\t<< '\\n';\n    }\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "f8b8db99d12a85848cd20c0b4938aab986536ed2", "size": 4746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/symm.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/symm.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/symm.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1888111888, "max_line_length": 74, "alphanum_fraction": 0.5863885377, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631689, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5820400675187092}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <array>\r\n#include <math.h>\r\n#include \"heatEquation.hpp\"\r\n#include \"TriDiagMatrix.hpp\"\r\n#include \"MassMatrix.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <fstream>\r\n#include <string>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\nvoid printQuadrature();\r\ndouble f( double x);\r\ndouble g (double x);\r\ndouble h (double x);\r\nconst double M_PI = 2*acos(0);\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\r\nSpaceMesh smesh;\r\n//smesh.GenerateDefaultSpaceMesh();\r\n//smesh.GloballyBisectSpaceMesh();\r\nsmesh.GenerateSpaceMesh({0, 0.15, 0.25, 0.5, 1});\r\n\r\n//smesh.GloballyBisectSpaceMesh();\r\n//smesh.GloballyBisectSpaceMesh();\r\n\r\nTimeMesh tmesh;\r\ntmesh.GenerateUniformTimeMesh(pow(smesh.meshsize(), 2), 1.0);\r\n\r\nHeatEquation heat;\r\nheat.SetSpaceTimeMesh( smesh, tmesh, \"soultion1.txt\");\r\nheat.Solve();\r\n\r\nsmesh.PrintSpaceNodes();\r\nheat.PrintSolution();\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "f40bf52730a73bb0318db8d8d418c8a224f06c4b", "size": 979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Simple Heat Equation solver class/Driver for simple heat equation classes.cpp", "max_stars_repo_name": "thabomiles/FEMHeatEquation", "max_stars_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Simple Heat Equation solver class/Driver for simple heat equation classes.cpp", "max_issues_repo_name": "thabomiles/FEMHeatEquation", "max_issues_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Simple Heat Equation solver class/Driver for simple heat equation classes.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": 20.829787234, "max_line_length": 62, "alphanum_fraction": 0.7068437181, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5819273641786689}}
{"text": "#include <iostream>\n\n#include \"LinearStateSpaceModel.h\"\n\n#include <Eigen/Core>\n\nint main()\n{\n\t// Define the initial state of the system\n\tconst int n = 2;\n\tconst int q = 1;\n\tconst int p = 1;\n\tfloat states[n] = { 1, 2 };\n\tfloat input[p] = { 0.6f };\n\tfloat state_mtx[n * n] = { 0, 2, -1, -3 };\n\tfloat input_mtx[n * p] = { 5, 0 };\n\tfloat output_mtx[q * n] = { 1, 0 };\n\tfloat feedforward_gain[q * p] = { 0 };\n\n\t// Convert input to eigen datatypes\n\tEigen::Matrix<float, n, 1> x(states);\n\tEigen::Matrix<float, p, 1> u(input);\n\tEigen::Matrix<float, n, n, Eigen::RowMajor> A(state_mtx);\n\tEigen::Matrix<float, n, p> B(input_mtx);\n\tEigen::Matrix<float, q, n> C(output_mtx);\n\tEigen::Matrix<float, q, p> D(feedforward_gain);\n\n\t// Create state space model\n\tauto ss = LinearStateSpaceModel<float, n, q, p>(A, B, C, D);\n\tss.set_state(x);\n\tss.set_input(u);\n\n\t// Iterate for 10 loops\n\tfor (int i = 0; i < 10; i++)\n\t{\n\t\t// Calculate\n\t\tss.propogate();\n\n\t\t// Output\n\t\tstd::cout << \"State Estimate @ t = \" << (i + 1) << \": \\n\" << ss.x << std::endl;\n\t\tstd::cout << \"Output Estimate @ t = \" << (i + 1) << \": \" << ss.y << std::endl;\n\t}\n}", "meta": {"hexsha": "84b6b0cd32984146870cbdf0bf1833c71e346598", "size": 1112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "State-Estimation/src/main.cpp", "max_stars_repo_name": "roberttully95/State-Estimation", "max_stars_repo_head_hexsha": "ef028ce51fc11a675f5762121df956d8c5a57c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "State-Estimation/src/main.cpp", "max_issues_repo_name": "roberttully95/State-Estimation", "max_issues_repo_head_hexsha": "ef028ce51fc11a675f5762121df956d8c5a57c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-06T20:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T00:22:46.000Z", "max_forks_repo_path": "State-Estimation/src/main.cpp", "max_forks_repo_name": "roberttully95/State-Estimation", "max_forks_repo_head_hexsha": "ef028ce51fc11a675f5762121df956d8c5a57c87", "max_forks_repo_licenses": ["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.8604651163, "max_line_length": 81, "alphanum_fraction": 0.589028777, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5819248188425289}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#include <string>\n#include <fstream>\n#include <sstream>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/opencv.hpp>\n//#include <opencv2/legacy/compat.hpp>\n\n#include \"dlib/opencv.h\"\n#include \"dlib/image_processing/frontal_face_detector.h\"\n#include \"dlib/image_processing/render_face_detections.h\"\n#include \"dlib/gui_widgets.h\"\n#include <dlib/image_processing.h>\n\n#include \"util.h\"\n#include \"gestureDetection.h\"\n\n#define DTW_INFINITY 1e30\n\ndouble maximum(double a, double b, double c) {\n\tif(a>b && a>c) {\n\t\treturn a;\n\t}\n\telse if(b>a && b>c) {\n\t\treturn b;\n\t}\n\telse return c;\n}\n\ndouble measure_deviation(std::vector<double> arr1, std::vector<double> arr2) {\n\n\t/*\n\t\tFunction to find deviation/difference between two measured vectors having size = 3.\n\n\t\t@params:\n\t\tarr1\tInput array 1\n\t\tarr2\tInput array 2\n\t*/\n\n\treturn maximum(std::fabs(arr1[0] - arr2[0]), std::fabs(arr1[1] - arr2[1]), std::fabs(arr1[2] - arr2[2]));\n}\n\ndouble minimum(double a, double b, double c) {\n\tif(a<b && a<c) {\n\t\treturn a;\n\t}\n\telse if(b<a && b<c) {\n\t\treturn b;\n\t}\n\telse return c;\n}\n\ndouble DTWScore(std::vector<std::vector<double> > arr1, std::vector<std::vector<double> > arr2) {\n\n\t/*\n\t\tFunction to estimate how close two measurements are. The closeness is denoted by the score, which is computed\n\t\tusing the DTW(Dynamic Time Warping) Algorithm. Lower the score, more close they are.\n\n\t\t@params:\n\t\tarr1\tInput array 1\n\t\tarr2\tInput array 2\n\t*/\n\n\tint m = arr1.size() - 1;\n\tint n = arr2.size() - 1;\n\n\tdouble DTW[m+1][n+1], dev;\n\n\tfor(int i=1; i<=m; i++) {\n\t\tDTW[i][0] = DTW_INFINITY;\n\t}\n\tfor(int j=1; j<=n; j++) {\n\t\tDTW[0][j] = DTW_INFINITY;\n\t}\n\tDTW[0][0] = 0;\n\n\tfor(int i=1; i<=m; i++) {\n\t\tfor(int j=1; j<=n; j++) {\n\t\t\tdev = measure_deviation(arr1[i], arr2[j]);\n\t\t\tDTW[i][j] = dev + minimum(DTW[i-1][j], DTW[i][j-1], DTW[i-1][j-1]);\n\t\t}\n\t}\n\n\t//DTW[m][n] is the score.\n\treturn DTW[m][n];\n}\n\nvoid FixedBin::assign(int _size) {\n\tfilled = 0;\n\tsize = _size;\n\tbin.resize(_size);\n}\n\nvoid FixedBin::push(std::vector<double> vec) {\n\tif(filled == size) {\n\t\tfor(int i=0;i<filled-1;i++) {\n\t\t\tbin[i] = bin[i+1];\n\t\t}\n\t\tbin[filled - 1] = vec;\n\t}\n\telse {\n\t\tbin.at(filled) = vec;\n\t\t++filled;\n\t}\n}\n\nint FixedBin::get_size() {\n\treturn size;\n}\n\nint FixedBin::get_filled() {\n\treturn filled;\n}\n\nvoid FixedBin::get(int pos, std::vector<double>& vec) {\n\tvec.resize(3);\n\tvec = bin.at(pos);\n}\n\nstd::vector<std::vector<double> > FixedBin::clone() {\n\tstd::vector<std::vector<double> > vec(filled);\n\n\t//vec.empty();\n\t//vec.resize(filled);\n\tfor(int i=0;i<filled;i++) {\n\t\tvec.at(i) = bin.at(i);\n\t}\n\treturn vec;\n}\n\nvoid FaceGesture::assign(int normal_size) {\n\tnormal = new FixedBin();\n\tnormal->assign(normal_size);\n}\n", "meta": {"hexsha": "d50aa5934f9aaf0c5f12af1d0c26443ce9665647", "size": 2699, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gestureDetection.cpp", "max_stars_repo_name": "vmthanh/Eye-Tracking", "max_stars_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gestureDetection.cpp", "max_issues_repo_name": "vmthanh/Eye-Tracking", "max_issues_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gestureDetection.cpp", "max_forks_repo_name": "vmthanh/Eye-Tracking", "max_forks_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.700729927, "max_line_length": 111, "alphanum_fraction": 0.6398666173, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.581924816026709}}
{"text": "#pragma once\n#pragma ide diagnostic ignored \"modernize-use-nodiscard\"\n#pragma ide diagnostic ignored \"NotImplementedFunctions\"\n#pragma ide diagnostic ignored \"OCUnusedGlobalDeclarationInspection\"\n#pragma ide diagnostic ignored \"OCUnusedStructInspection\"\n#pragma ide diagnostic ignored \"OCUnusedTypeAliasInspection\"\n\n#include <Eigen/Geometry>\n\nnamespace fvlam\n{\n// ==============================================================================\n// Translate2 class\n// ==============================================================================\n\n  class Translate2\n  {\n  public:\n    using MuVector = Eigen::Vector2d;\n    using TangentVector = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, 1>;\n    using CovarianceMatrix = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, MuVector::MaxSizeAtCompileTime>;\n\n  private:\n    MuVector t_;\n\n  public:\n    Translate2() :\n      t_{MuVector::Zero()}\n    {}\n\n    explicit Translate2(MuVector t) :\n      t_(std::move(t))\n    {}\n\n    Translate2(double x, double y) :\n      t_(x, y)\n    {}\n\n    const auto &x() const\n    { return t_.x(); } //\n    const auto &y() const\n    { return t_.y(); } //\n\n    const auto &t() const\n    { return t_; }\n\n    MuVector mu() const\n    { return t_; }\n\n    template<class T>\n    static Translate2 from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    template<class T>\n    static CovarianceMatrix cov_from(T &other); //\n    template<class T>\n    static T cov_to(const CovarianceMatrix &cov); //\n    template<class T>\n    static void cov_to(const CovarianceMatrix &cov, T &other); //\n\n    std::string to_string() const; //\n    static std::string cov_to_string(const CovarianceMatrix &cov); //\n\n    bool equals(const Translate2 &other, double tol = 1.0e-9, bool check_relative_also = true) const; //\n    static bool cov_equals(const CovarianceMatrix &own, const CovarianceMatrix &other,\n                           double tol = 1.0e-9, bool check_relative_also = true);\n\n    Translate2 operator+(const Translate2 &other) const\n    {\n      return Translate2(t_ + other.t_);\n    }\n\n    Translate2 operator*(double factor) const\n    {\n      return Translate2(t_ * factor);\n    }\n  };\n\n// ==============================================================================\n// Translate3 class\n// ==============================================================================\n\n  class Translate3\n  {\n  public:\n    using MuVector = Eigen::Vector3d;\n    using TangentVector = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, 1>;\n    using CovarianceMatrix = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, MuVector::MaxSizeAtCompileTime>;\n\n  private:\n    MuVector t_;\n\n  public:\n    Translate3() :\n      t_{MuVector::Zero()}\n    {}\n\n    explicit Translate3(MuVector t) :\n      t_(std::move(t))\n    {}\n\n    Translate3(double x, double y, double z) :\n      t_(x, y, z)\n    {}\n\n    const auto &x() const\n    { return t_.x(); } //\n    const auto &y() const\n    { return t_.y(); } //\n    const auto &z() const\n    { return t_.z(); } //\n\n    const auto &t() const\n    { return t_; }\n\n    MuVector mu() const\n    { return t_; }\n\n    template<class T>\n    static Translate3 from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    template<class T>\n    static CovarianceMatrix cov_from(T &other); //\n    template<class T>\n    static T cov_to(const CovarianceMatrix &cov); //\n    template<class T>\n    static void cov_to(const CovarianceMatrix &cov, T &other); //\n\n    std::string to_string() const; //\n    static std::string cov_to_string(const CovarianceMatrix &cov); //\n\n    bool equals(const Translate3 &other, double tol = 1.0e-9, bool check_relative_also = true) const; //\n    static bool cov_equals(const CovarianceMatrix &own, const CovarianceMatrix &other,\n                           double tol = 1.0e-9, bool check_relative_also = true);\n\n    /// Exponential map at identity - create a translation from canonical coordinates \\f$ [T_x,T_y,T_z] \\f$\n    static Translate3 Expmap(const TangentVector &x)\n    { return Translate3(x); }\n\n    /// Log map at identity - return the canonical coordinates \\f$ [T_x,T_y,T_z] \\f$ of this translation\n    static TangentVector Logmap(const Translate3 &translate3)\n    { return translate3.t_; }\n\n    Translate3 cross(const Translate3 &v) const\n    {\n      return Translate3{t_.cross(v.t_)};\n    }\n\n    Translate3 operator+(const Translate3 &other) const\n    {\n      return Translate3(t_ + other.t_);\n    }\n\n    Translate3 operator*(double factor) const\n    {\n      return Translate3(t_ * factor);\n    }\n  };\n\n// ==============================================================================\n// Translate3WithCovariance class\n// ==============================================================================\n\n  class Translate3WithCovariance\n  {\n  public:\n    using MuVector = Eigen::Matrix<double, Translate3::MuVector::MaxSizeAtCompileTime +\n                                           Translate3::CovarianceMatrix::MaxSizeAtCompileTime, 1>;\n\n  private:\n    bool is_valid_;\n    bool is_cov_valid_;\n    Translate3 t_;\n    Translate3::CovarianceMatrix cov_;\n\n  public:\n    Translate3WithCovariance() :\n      is_valid_{false}, is_cov_valid_{false}, t_{}, cov_{Translate3::CovarianceMatrix::Zero()}\n    {}\n\n    explicit Translate3WithCovariance(Translate3 t) :\n      is_valid_{true}, is_cov_valid_{false}, t_{std::move(t)}, cov_{Translate3::CovarianceMatrix::Zero()}\n    {}\n\n    Translate3WithCovariance(Translate3 t, Translate3::CovarianceMatrix cov) :\n      is_valid_{true}, is_cov_valid_{true}, t_{std::move(t)}, cov_{std::move(cov)}\n    {}\n\n    auto is_valid() const\n    { return is_valid_; }\n\n    auto is_cov_valid() const\n    { return is_cov_valid_; }\n\n    const auto &t() const\n    { return t_; }\n\n    const auto &cov() const\n    { return cov_; }\n\n    template<class T>\n    static Translate3WithCovariance from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    std::string to_string() const;\n\n    bool equals(const Translate3WithCovariance &other, double tol = 1.0e-9, bool check_relative_also = true) const\n    {\n      return t_.equals(other.t_, tol, check_relative_also) &&\n             Translate3::cov_equals(cov_, other.cov_, tol, check_relative_also);\n    }\n  };\n\n// ==============================================================================\n// Rotate3 class\n// ==============================================================================\n\n  class Rotate3\n  {\n  public:\n    using MuVector = Eigen::Matrix<double, 3, 1>;\n    using TangentVector = Eigen::Matrix<double, 3, 1>;\n    using RotationMatrix = Eigen::Matrix<double, 3, 3>;\n    using CovarianceMatrix = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, MuVector::MaxSizeAtCompileTime>;\n    using Derived = Eigen::Quaterniond;\n\n  private:\n    Derived q_{Derived::Identity()};\n    RotationMatrix debug_r_{RotationMatrix::Zero()};\n    MuVector debug_xyz_{MuVector::Zero()};\n\n    static MuVector xyz(const Derived &q);\n\n  public:\n    Rotate3() = default;\n\n    explicit Rotate3(const Derived &q) :\n      q_(q), debug_r_{q_.toRotationMatrix()}, debug_xyz_{xyz(q_)}\n    {}\n\n    explicit Rotate3(const RotationMatrix &rotation_matrix) :\n      q_(rotation_matrix), debug_r_{q_.toRotationMatrix()}, debug_xyz_{xyz(q_)}\n    {}\n\n    static Rotate3 Rx(double x)\n    { return Rotate3{Derived{Eigen::AngleAxisd{x, Eigen::Vector3d::UnitX()}}}; }\n\n    static Rotate3 Ry(double y)\n    { return Rotate3{Derived{Eigen::AngleAxisd{y, Eigen::Vector3d::UnitY()}}}; }\n\n    static Rotate3 Rz(double z)\n    { return Rotate3{Derived{Eigen::AngleAxisd{z, Eigen::Vector3d::UnitZ()}}}; }\n\n    static Rotate3 RzRyRx(double x, double y, double z)\n    {\n      return Rotate3{Derived{Eigen::AngleAxisd{z, Eigen::Vector3d::UnitZ()}} *\n                     Derived{Eigen::AngleAxisd{y, Eigen::Vector3d::UnitY()}} *\n                     Derived{Eigen::AngleAxisd{x, Eigen::Vector3d::UnitX()}}};\n    }\n\n    static Rotate3 Ypr(double y, double p, double r)\n    { return RzRyRx(r, p, y); }\n\n    const auto &q() const\n    { return q_; }\n\n    RotationMatrix rotation_matrix() const\n    { return q_.toRotationMatrix(); }\n\n    MuVector xyz() const\n    { return xyz(q_); }\n\n    MuVector mu() const\n    { return xyz(q_); }\n\n    template<class T>\n    static Rotate3 from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    template<class T>\n    static CovarianceMatrix cov_from(T &other); //\n    template<class T>\n    static T cov_to(const CovarianceMatrix &cov); //\n    template<class T>\n    static void cov_to(const CovarianceMatrix &cov, T &other); //\n\n    std::string to_string() const; //\n    static std::string cov_to_string(const CovarianceMatrix &cov); //\n\n    bool equals(const Rotate3 &other, double tol = 1.0e-9, bool check_relative_also = true) const; //\n    static bool cov_equals(const CovarianceMatrix &own, const CovarianceMatrix &other,\n                           double tol = 1.0e-9, bool check_relative_also = true);\n\n    Rotate3 inverse() const\n    {\n      return Rotate3(q_.inverse());\n    }\n\n    /// Exponential map at identity - create a rotation from canonical coordinates \\f$ [R_x,R_y,R_z] \\f$\n    static Rotate3 Expmap(const TangentVector &x);\n\n    /// Log map at identity - return the canonical coordinates \\f$ [R_x,R_y,R_z] \\f$ of this rotation\n    static TangentVector Logmap(const Rotate3 &rotate3);\n\n    struct ChartAtOrigin\n    {\n      static Rotate3 retract(const TangentVector &v)\n      { return Expmap(v); } //\n      static TangentVector local(const Rotate3 &r)\n      { return Logmap(r); } //\n    };\n\n    Rotate3 compose(const Rotate3 &other) const\n    { return *this * other; } //\n    Rotate3 between(const Rotate3 &other) const\n    { return (*this).inverse() * other; } //\n    Rotate3 slerp(const Rotate3 &other, double t) const\n    { return compose(Expmap(t * Logmap(between(other)))); } //\n\n    Rotate3 retract(const TangentVector &v) const\n    { return compose(ChartAtOrigin::retract(v)); } //\n    TangentVector local_coordinates(const Rotate3 &other) const\n    { return ChartAtOrigin::local(between(other)); } //\n\n    Rotate3 operator*(const Rotate3 &other) const\n    {\n      return Rotate3(q_ * other.q_);\n    }\n\n    Translate3 operator*(const Translate3 &other) const\n    {\n      return Translate3(q_ * other.t());\n    }\n  };\n\n// ==============================================================================\n// Transform3 class\n// ==============================================================================\n\n  class Transform3\n  {\n  public:\n    using MuVector = Eigen::Matrix<double,\n      Rotate3::MuVector::MaxSizeAtCompileTime +\n      Translate3::MuVector::MaxSizeAtCompileTime, 1>;\n    using TangentVector = Eigen::Matrix<double,\n      Rotate3::MuVector::MaxSizeAtCompileTime +\n      Translate3::MuVector::MaxSizeAtCompileTime, 1>;\n    using CovarianceMatrix = Eigen::Matrix<double, MuVector::MaxSizeAtCompileTime, MuVector::MaxSizeAtCompileTime>;\n\n  private:\n    bool is_valid_;\n    Rotate3 r_;\n    Translate3 t_;\n\n  public:\n    Transform3() :\n      is_valid_{false}, r_{}, t_{}\n    {}\n\n    Transform3(Rotate3 r, Translate3 t) :\n      is_valid_{true}, r_(std::move(r)), t_(std::move(t))\n    {}\n\n    Transform3(double rx, double ry, double rz, double tx, double ty, double tz) :\n      is_valid_{true}, r_{Rotate3::RzRyRx(rx, ry, rz)}, t_(Translate3{tx, ty, tz})\n    {}\n\n    explicit Transform3(const MuVector &mu) :\n      is_valid_{true},\n      r_(Rotate3::RzRyRx(mu(0), mu(1), mu(2))),\n      t_(Translate3(mu(3), mu(4), mu(5)))\n    {}\n\n    const auto &r() const\n    { return r_; }\n\n    const auto &t() const\n    { return t_; }\n\n    auto is_valid() const\n    { return is_valid_; }\n\n    MuVector mu() const\n    { return (MuVector() << r_.mu(), t_.mu()).finished(); }\n\n    template<class T>\n    static Transform3 from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    template<class T>\n    static CovarianceMatrix cov_from(T &other); //\n    template<class T>\n    static T cov_to(const CovarianceMatrix &cov); //\n    template<class T>\n    static void cov_to(const CovarianceMatrix &cov, T &other); //\n\n    std::string to_string() const; //\n    static std::string cov_to_string(const CovarianceMatrix &cov); //\n\n    bool equals(const Transform3 &other, double tol = 1.0e-9, bool check_relative_also = true) const; //\n    static bool cov_equals(const CovarianceMatrix &own, const CovarianceMatrix &other,\n                           double tol = 1.0e-9, bool check_relative_also = true);\n\n    Transform3 inverse() const\n    {\n      auto qi = r_.q().inverse();\n      return Transform3(Rotate3(qi), Translate3(qi * -t_.t()));\n    }\n\n    /// Exponential map at identity - create a transform from canonical coordinates \\f$ [R_x,R_y,R_z,T_x,T_y,T_z] \\f$\n    static Transform3 Expmap(const TangentVector &x);\n\n    /// Log map at identity - return the canonical coordinates \\f$ [R_x,R_y,R_z,T_x,T_y,T_z] \\f$ of this transform\n    static TangentVector Logmap(const Transform3 &transform3);\n\n    struct ChartAtOrigin\n    {\n      static Transform3 retract(const TangentVector &v); //\n      static TangentVector local(const Transform3 &pose); //\n    };\n\n    Transform3 compose(const Transform3 &other) const\n    { return *this * other; } //\n    Transform3 between(const Transform3 &other) const\n    { return (*this).inverse() * other; } //\n\n    Transform3 retract(const TangentVector &v) const\n    { return compose(ChartAtOrigin::retract(v)); } //\n    TangentVector local_coordinates(const Transform3 &other) const\n    { return ChartAtOrigin::local(between(other)); } //\n\n    Translate3 operator*(const Translate3 &other) const\n    {\n      return Translate3(r_ * other + t_);\n    }\n\n    Transform3 operator*(const Transform3 &other) const\n    {\n      return Transform3{r_ * other.r_, t_ + r_ * other.t_};\n    }\n  };\n\n// ==============================================================================\n// Transform3WithCovariance class\n// ==============================================================================\n\n  class Transform3WithCovariance\n  {\n  public:\n    using MuVector = Eigen::Matrix<double, Transform3::MuVector::MaxSizeAtCompileTime +\n                                           Transform3::CovarianceMatrix::MaxSizeAtCompileTime, 1>;\n\n  private:\n    bool is_cov_valid_;\n    Transform3 tf_;\n    Transform3::CovarianceMatrix cov_;\n\n  public:\n    Transform3WithCovariance() :\n      is_cov_valid_{false}, tf_{}, cov_{Transform3::CovarianceMatrix::Zero()}\n    {}\n\n    explicit Transform3WithCovariance(Transform3 tf) :\n      is_cov_valid_{false}, tf_(std::move(tf)), cov_(Transform3::CovarianceMatrix::Zero())\n    {}\n\n    Transform3WithCovariance(Transform3 tf, Transform3::CovarianceMatrix cov) :\n      is_cov_valid_{true}, tf_(std::move(tf)), cov_(std::move(cov))\n    {}\n\n    auto is_valid() const\n    { return tf_.is_valid(); }\n\n    auto is_cov_valid() const\n    { return is_cov_valid_; }\n\n    const auto &tf() const\n    { return tf_; }\n\n    const auto &cov() const\n    { return cov_; }\n\n    template<class T>\n    static Transform3WithCovariance from(T &other);\n\n    template<class T>\n    T to() const;\n\n    template<class T>\n    void to(T &other) const;\n\n    std::string to_string() const;\n\n    bool equals(const Transform3WithCovariance &other, double tol = 1.0e-9, bool check_relative_also = true) const;\n  };\n}\n\n", "meta": {"hexsha": "dc1ec9a46445c09edba33d5cfd1875cdd2411912", "size": 15496, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fvlam/transform3_with_covariance.hpp", "max_stars_repo_name": "ptrmu/camsim", "max_stars_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T16:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-12T16:51:58.000Z", "max_issues_repo_path": "include/fvlam/transform3_with_covariance.hpp", "max_issues_repo_name": "ptrmu/camsim", "max_issues_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fvlam/transform3_with_covariance.hpp", "max_forks_repo_name": "ptrmu/camsim", "max_forks_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_forks_repo_licenses": ["BSD-3-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.5161904762, "max_line_length": 117, "alphanum_fraction": 0.6110609189, "num_tokens": 3909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5818928897465218}}
{"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 GEOMETRY_CIRCLE_2_INTEGRATED_FLUX_HPP\n#define GEOMETRY_CIRCLE_2_INTEGRATED_FLUX_HPP\n\n#include \"rjmcmc/geometry/Circle_2.hpp\"\n#include <boost/gil/image.hpp>\n#include <boost/gil/extension/matis/float_images.hpp>\n\ntemplate<typename View>\nvoid Add1CirclePoints(const View& view, double cx, double cy, double dx, double dy, double d, double & res, double & w)\n{\n//    typedef View::pixel_t pixel_t;\n    typedef boost::gil::dev2n32F_pixel_t pixel_t;\n\tint i = (int) (cx + dx);\n\tint j = (int) (cy + dy);\n\tif(i<0 || j<0 || i>=view.width() || j>=view.height()) return;\n\tconst pixel_t& grad = view(i,j);\n\tres += boost::gil::at_c<0>(grad) * dx + boost::gil::at_c<1>(grad) * dy;\n\tw   += d;\n}\n\ntemplate<typename View>\nvoid Add4CirclePoints(const View& view, double cx, double cy, double d, double & res, double & w)\n{\n\tAdd1CirclePoints(view, cx, cy, 0, d, d, res, w);\n\tAdd1CirclePoints(view, cx, cy, 0,-d, d, res, w);\n\tAdd1CirclePoints(view, cx, cy, d, 0, d, res, w);\n\tAdd1CirclePoints(view, cx, cy,-d, 0, d, res, w);\n}\n\ntemplate<typename View>\nvoid Add8CirclePoints(const View& view, double cx, double cy, double dx, double dy, double & res, double & w)\n{\n\tdouble d = sqrt(dx*dx+dy*dy);\n\tAdd1CirclePoints(view, cx, cy, dx, dy, d, res, w);\n\tAdd1CirclePoints(view, cx, cy,-dx, dy, d, res, w);\n\tAdd1CirclePoints(view, cx, cy,-dx,-dy, d, res, w);\n\tAdd1CirclePoints(view, cx, cy, dx,-dy, d, res, w);\n\tAdd1CirclePoints(view, cx, cy, dy, dx, d, res, w);\n\tAdd1CirclePoints(view, cx, cy,-dy, dx, d, res, w);\n\tAdd1CirclePoints(view, cx, cy,-dy,-dx, d, res, w);\n\tAdd1CirclePoints(view, cx, cy, dy,-dx, d, res, w);\n}\n\ntemplate<typename OrientedImage, typename K>\ndouble integrated_flux(const OrientedImage& v, const geometry::Circle_2<K> &c)\n{\n        typedef typename OrientedImage::view_t view_t;\n    view_t view(v.view());\n\tint x0 = v.x0();\n\tint y0 = v.y0();\n\n\tdouble cx = c.center().x() - x0;\n\tdouble cy = c.center().y() - y0;\n\tdouble r  = geometry::radius(c);\n\tdouble res = 0., w = 0.;\n\tdouble dx = 0;\n\tdouble dy = r;\n\tdouble p = 3 - 2*r;\n\tAdd4CirclePoints(view, cx, cy, dy, res, w);\n\twhile (dx < dy) {\n\t\tif (p < 0) {\n\t\t\tp += 4*dx+6;\n\t\t} else {\n\t\t\t--dy;\n\t\t\tAdd8CirclePoints(view, cx, cy, dx, dy, res, w);\n\t\t\tp += 4*(dx-dy)+10;\n\t\t}\n\t\t++dx;\n\t\tAdd8CirclePoints(view, cx, cy, dx, dy, res, w);\n\t}\n\tif(w==0) return 0.;\n\treturn (res * geometry::perimeter(c)) / w;\n}\n\n#endif // GEOMETRY_CIRCLE_2_INTEGRATED_FLUX_HPP\n", "meta": {"hexsha": "dec253d0c054f13568d273e8fd57f26c44afcf45", "size": 4199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/geometry/integrated_flux/Circle_2_integrated_flux.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/geometry/integrated_flux/Circle_2_integrated_flux.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/geometry/integrated_flux/Circle_2_integrated_flux.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": 37.4910714286, "max_line_length": 119, "alphanum_fraction": 0.6899261729, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5818614291355462}}
{"text": "//\n// Created by haohanwang on 3/25/16.\n//\n\n#include \"LinearRegression.h\"\n\n#include <Eigen/Sparse>\n\n//#include \"ModelOptions.hpp\"\n\nusing namespace Eigen;\n\n\nLinearRegression::LinearRegression() {\n    L1_reg = 0;\n    L2_reg = 0;\n};\n\n\nLinearRegression::LinearRegression(const ModelOptions_t& options) {\n    L1_reg = 0;\n    L2_reg = 0;\n}\n\n\nvoid LinearRegression::setL1_reg(float l1) { L1_reg = l1; };\n\nvoid LinearRegression::setL2_reg(float l2) { L2_reg = l2; };\n\nfloat LinearRegression::cost() {\n    return 0.5 * (y - X * beta).squaredNorm()/X.rows() + L1_reg * beta.cwiseAbs().sum() + L2_reg * beta.squaredNorm();\n};\n\nSparseMatrix<float> LinearRegression::derivative() {\n    return ((-1.0 * X.transpose() * (y - X * beta)).array() + L1_reg * (beta.array() / beta.cwiseAbs().array()).sum() +\n            L2_reg * beta.sum()).matrix();\n};\n\nSparseMatrix<float> LinearRegression::proximal_derivative() {\n    return -1.0 * X.transpose() * (y - X * beta);\n};\n\nSparseMatrix<float> LinearRegression::proximal_operator(SparseMatrix<float> in, float lr) {\n    if (L1_reg == 0 && L2_reg == 0){\n        return in;\n    }\n    if (L1_reg != 0 && L2_reg == 0){\n        VectorXf sign = ((in.array()>0).matrix()).cast<float>();//sign\n        sign += -1.0*((in.array()<0).matrix()).cast<float>();\n        in = ((in.array().abs()-lr*L1_reg).max(0)).matrix();//proximal\n        return (in.array()*sign.array()).matrix();//proximal multipled back with sign\n    }\n    else if (L2_reg != 0){\n        return in/(1+2*lr*L2_reg);\n    }\n    else{\n        VectorXf sign = ((in.array()>0).matrix()).cast<float>();\n        sign += -1.0*((in.array()<0).matrix()).cast<float>();\n        in = ((in.array().abs()-lr*L1_reg).max(0)).matrix();\n        in = in.array()*sign.array()/(1+2*lr*L2_reg);\n        return in.matrix();\n    }\n}", "meta": {"hexsha": "e835158b1088dd67581aed6a403a398af0f2982f", "size": 1794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparseModel/LinearRegression.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/sparseModel/LinearRegression.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/sparseModel/LinearRegression.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": 28.4761904762, "max_line_length": 119, "alphanum_fraction": 0.5930880713, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5817175729367674}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ndt_generic/eigen_utils.h>\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main()\n{\n    // Simple check of the normalization\n    {\n        Eigen::VectorXd x(6);\n        x << 1, 2, 3, 0.1, 0.2, 2.7;\n        \n        std::cout << \"x: \" << x << std::endl;\n        \n        Eigen::Affine3d T = ndt_generic::vectorToAffine3d(x);\n        \n        std::cout << \"T : \" << ndt_generic::affine3dToStringRPY(T) << std::endl;\n        std::cout << \"T.rotation() : \" << T.rotation() << std::endl;\n        \n        x = ndt_generic::affine3dToVector(T);\n        \n        std::cout << \"x: \" << x << std::endl;\n        \n        std::cout << \"------------------------- The two T matrices should be the same below ------------------\" << std::endl;\n        \n        x(3) += M_PI;\n        \n        std::cout << \"x : \" << x << std::endl;\n        T = ndt_generic::vectorToAffine3d(x);\n        std::cout << \"T : \" << ndt_generic::affine3dToStringRPY(T) << std::endl;\n        std::cout << \"T.rotation() : \" << T.rotation() << std::endl;\n        \n        \n        ndt_generic::normalizeEulerAngles6dVec(x);\n        \n        std::cout << \"x : \" << x << std::endl;\n        T = ndt_generic::vectorToAffine3d(x);\n        std::cout << \"T : \" << ndt_generic::affine3dToStringRPY(T) << std::endl;\n        std::cout << \"T.rotation() : \" << T.rotation() << std::endl;\n    }\n    \n    // Test the fusion\n    {\n        std::cout << \"---------------------------------------------\" << std::endl;\n        Eigen::Matrix3d covA;\n        covA.setIdentity();\n\n        Eigen::Matrix3d covB;\n        covB.setIdentity();\n\n        Eigen::Vector3d a(1,2,3);\n        Eigen::Vector3d b(0,1,0);\n\n        Eigen::Vector3d weighted = ndt_generic::getWeightedPoint(a,covA,b,covB);\n\n        std::cout << \"weighted : \" << ndt_generic::getWeightedPoint(a,covA,b,covB);\n        std::cout << \"should be : 0.5, 1.5, 1.5\" << std::endl;\n        covB *= 10.;\n        std::cout << \"weighted : \" << ndt_generic::getWeightedPoint(a,covA,b,covB);\n        std::cout << \"should be : 0.9091, 1.9091, 2.7273\" << std::endl;\n    }\n    \n    {\n        std::cout << \"---------------------------------------------\" << std::endl;\n        Eigen::Affine3d a = Eigen::Translation<double,3>(1,2,3)*\n        Eigen::AngleAxis<double>(0.1,Eigen::Vector3d::UnitX()) *\n        Eigen::AngleAxis<double>(0.2,Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxis<double>(0.3,Eigen::Vector3d::UnitZ()) ;\n\n        Eigen::Affine3d b = Eigen::Translation<double,3>(0,1,0)*\n        Eigen::AngleAxis<double>(0.0,Eigen::Vector3d::UnitX()) *\n        Eigen::AngleAxis<double>(0.1,Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxis<double>(0.0,Eigen::Vector3d::UnitZ()) ;\n        \n        Eigen::MatrixXd covA(6,6);\n        covA.setIdentity();\n        \n        Eigen::MatrixXd covB(6,6);\n        covB.setIdentity();\n        \n        std::cout << \"weighted : \" << ndt_generic::affine3dToStringRPY(ndt_generic::getWeightedPose(a, covA, b, covB)) << std::endl;        \n    }\n\n\n}\n", "meta": {"hexsha": "14f9e2e1357931729c3d7fd7d4ca1f10d76389e0", "size": 3051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_generic/test/eigen_test.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_generic/test/eigen_test.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_generic/test/eigen_test.cpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 33.5274725275, "max_line_length": 140, "alphanum_fraction": 0.5047525402, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.6723316860482762, "lm_q1q2_score": 0.5817175592389542}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// accumulator::statistics::percentage_effective_sample_size.hpp             //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_STATISTICS_PERCENTAGE_EFFECTIVE_SAMPLE_SIZE_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_STATISTICS_PERCENTAGE_EFFECTIVE_SAMPLE_SIZE_HPP_ER_2009\n#include <boost/parameter/binding.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/apply.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/parameters/accumulator.hpp>\n#include <boost/statistics/detail/importance_sampling/statistics/variance_of_mean_normalized.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace accumulator{\nnamespace impl\n{\n\n    // Var(w/c) = Var(w) / c^2, where c = mean(w)\n    template<typename T>\n    class percentage_effective_sample_size \n            : public boost::accumulators::accumulator_base\n        {\n        typedef boost::accumulators::dont_care dont_care_;\n    \n        typedef tag::variance_of_mean_normalized tag_vmn_;\n        typedef boost::accumulators::tag::accumulator tag_acc_;\n    \n        public:\n        typedef T result_type;\n        percentage_effective_sample_size(){}\n        percentage_effective_sample_size(dont_care_){}\n        void operator()(dont_care_)const{}\n\n        template<typename Args>\n        result_type result(const Args& args) const\n        {\n\n            typedef \n                typename boost::parameter::binding<Args,tag_acc_>::type cref_;\n            cref_ acc = args[boost::accumulators::accumulator];\n\n            T vmn = accumulators::extract_result<tag_vmn_>(acc);\n            return one / (one+vmn);\n        }\n        \n        static const T one;\n    };\n\n    template<typename T>\n    const T percentage_effective_sample_size<T>::one = static_cast<T>(1);\n\n}//impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::percentage_effective_sample_size\nnamespace tag\n{\n    struct percentage_effective_sample_size\n      : boost::accumulators::depends_on<tag::variance_of_mean_normalized>\n    {\n      typedef statistics::detail::accumulator::impl\n        ::percentage_effective_sample_size<boost::mpl::_1> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::percentage_effective_sample_size\nnamespace extract\n{\n\n  template<typename AccSet>\n  typename\n    boost::mpl::apply<\n        AccSet,\n        tag::percentage_effective_sample_size\n    >::type::result_type\n  percentage_effective_sample_size(AccSet const& acc){\n    typedef tag::percentage_effective_sample_size the_tag;\n    return boost::accumulators::extract_result<the_tag>(acc);\n  }\n\n}\n\nusing extract::percentage_effective_sample_size;\n\n}// accumulator\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "e3b2009ba813eded6262dd6bebfef6ce5ef1d4f5", "size": 3453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/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": "importance_sampling/boost/statistics/detail/importance_sampling/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": "importance_sampling/boost/statistics/detail/importance_sampling/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": 34.53, "max_line_length": 107, "alphanum_fraction": 0.6342311034, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.58170162878236}}
{"text": "/*\nThe MATLAB gateway function to BBFMM2D developed by Sivaram.\nThe code provides a O(N) solution to a kernel matrix-vector product.\nWritten by Judith Yue Li 10/02/2013\n*/\n\n#include <iostream>\n#include \"math.h\"\n#include \"mex.h\"\n#include \"matrix.h\"\n#include \"environment.hpp\"\n#include \"BBFMM2D.hpp\"\n#include <Eigen/Core>\n#include \"kernelfun.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\ndouble pi \t=\t4.0*atan(1.0);\nextern void _main();\n\n#define IS_REAL_2D_FULL_DOUBLE(P) (!mxIsComplex(P) && mxGetNumberOfDimensions(P) == 2 && !mxIsSparse(P) && mxIsDouble(P))\n#define IS_REAL_SCALAR(P) (IS_REAL_2D_FULL_DOUBLE(P) && mxGetNumberOfElements(P) == 1)\n\n// Pass location from matlab to C\nvoid read_location(const mxArray* x, const mxArray* y, vector<Point>& location){\n    unsigned long N;\n    double *xp, *yp;\n    N = mxGetM(x);\n    xp = mxGetPr(x);\n    yp = mxGetPr(y);\n    for (unsigned long i = 0; i < N; i++){\n        Point new_Point;\n        new_Point.x = xp[i];\n        new_Point.y = yp[i];\n        location.push_back(new_Point);\n    }\n}\n\nvoid mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[]) \n{\n    // Macros for the output and input arguments\n    #define QH_OUT          plhs[0]\n    #define QHexact_OUT     plhs[1]\n    #define x_IN            prhs[0]\n    #define y_IN            prhs[1]\n    #define H_IN            prhs[2]\n    #define nCheb_IN        prhs[3]\n    #define print_IN        prhs[4]\n\n    unsigned long N;\n    unsigned m;\n    // Instruction\n    char errmsg[1023 + 1];\n    sprintf(errmsg,\"Calling sequence is\\n\\tQH = %s(xloc,yloc,H,nCheb,PrintFlag); or\\n\\t[QH QHexact] = %s(xloc,yloc,H,nCheb,PrintFlag);\\n\", mexFunctionName(), mexFunctionName());\n    \n    // Argument Checking:\n    // Check number of argument\n    if(nrhs != 5) {\n        mexPrintf(errmsg);\n        mexErrMsgTxt(\"Wrong number of input arguments\");\n    }else if(nlhs > 2){\n        mexErrMsgTxt(\"Too many output arguments\");\n    }\n\n    if( !IS_REAL_2D_FULL_DOUBLE(x_IN)) {\n        mexErrMsgTxt(\"Third input argument is not a real 2D full double array.\");\n    }\n    if( !IS_REAL_2D_FULL_DOUBLE(y_IN)) {\n        mexErrMsgTxt(\"Third input argument is not a real 2D full double array.\");\n    }\n    if( !IS_REAL_2D_FULL_DOUBLE(H_IN)) {\n        mexErrMsgTxt(\"Third input argument is not a real 2D full double array.\");\n    }\n    if( !IS_REAL_SCALAR(nCheb_IN)){\n        mexErrMsgTxt(\"nChebnotes must be a real double scalar\");\n    }\n    if( mxGetM(x_IN)!= mxGetM(y_IN) || mxGetM(x_IN) != mxGetM(H_IN)){\n        mexErrMsgTxt(\"The dimension of the input matrices is wrong\");\n    }\n    \n    //processing on input arguments\n    N = mxGetM(H_IN); // get the first dimension of H\n    m = mxGetN(H_IN); // get the second dimension of H\n    unsigned short nChebNodes = *mxGetPr(nCheb_IN);\n    bool print = *mxGetPr(print_IN);\n    vector<Point> location;\n    read_location(x_IN,y_IN,location);\n    double *charges;\n    charges = mxGetPr(H_IN);\n    // Load data to local array using Eigen <Map>\n    MatrixXd H = Map<MatrixXd>(charges, N, m); // Map<MatrixXd> H(charges,N,m);\n    \n    // Compute Fast matrix vector product\n    // 1. Build Tree\n    clock_t startBuild  = clock();\n    H2_2D_Tree Atree(nChebNodes, charges, location, N, m, print); //Build the fmm tree\n    clock_t endBuild = clock();\n\n    double FMMTotalTimeBuild = double(endBuild-startBuild)/double(CLOCKS_PER_SEC);\n    if(print)\n        mexPrintf(\"\\nTime taken for FMM(build tree) is: %.4g\\n\",FMMTotalTimeBuild);    \n    \n    // 2.Calculateing potential\n    clock_t startA = clock();\n    // Create the output matrix\n    QH_OUT = mxCreateDoubleMatrix(N, m, mxREAL);     \n    // Get a pointer to the real data in the output matrix\n    double *QHp;\n    QHp = mxGetPr(QH_OUT);\n    myKernel A;\n    A.calculate_Potential(Atree, QHp);\n    clock_t endA = clock();\n    double FMMTotalTimeA = double(endA-startA)/double(CLOCKS_PER_SEC);\n    if(print){\n        mexPrintf(\"\\nTime taken for FMM(calculating potential) is: %.4g\\n\",FMMTotalTimeA);\n        mexPrintf(\"\\nTotal time taken for FMM is: %.4g\\n\",FMMTotalTimeA+FMMTotalTimeBuild);\n    }\n\n    /*///////////////////////////////\n    // Compute exact covariance Q //\n    ///////////////////////////////*/\n\n    if(nlhs == 2){\n    if(print){    \n        mexPrintf(\"\\nStarting exact computation...\\n\");\n    }\n    clock_t start = clock();\n    MatrixXd Q;\n    A.kernel_2D(N, location, N, location, Q);// Q is initialized inside function A.kernel_2D\n    clock_t end = clock();\n    double exactAssemblyTime = double(end-start)/double(CLOCKS_PER_SEC);\n    \n    // Compute exact Matrix vector product\n    start = clock();\n    QHexact_OUT = mxCreateDoubleMatrix(N, m, mxREAL);\n    double *QHexactp;\n    QHexactp = mxGetPr(QHexact_OUT);\n    Map<MatrixXd> QHT(QHexactp,N,m);\n    QHT = Q*H;\n    end = clock();\n    double exactComputingTime = double(end-start)/double(CLOCKS_PER_SEC);\n    if(print){    \n        mexPrintf(\"\\nThe total exact computation time is: %.4g\\n\",exactAssemblyTime + exactComputingTime);\n    }\n        \n    // Compute the difference\n    MatrixXd QHfast = Map<MatrixXd>(QHp, N, m);\n    MatrixXd error = QHfast - QHT;\n    double absoluteError = error.norm();\n    double relativeError = absoluteError/QHT.norm();\n    if(print){    \n        mexPrintf(\"The relative difference is: %13.6E \\n\", relativeError);\n    }\n\n    } \n\n    return;\n}\n", "meta": {"hexsha": "d565412376eeed534c9c551d35249908136e854e", "size": 5332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mexFMM2D.cpp", "max_stars_repo_name": "judithyueli/mexBBFMM2D", "max_stars_repo_head_hexsha": "2c73d867f48db3c2e395f9e1c2bebe9784c333e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-13T21:11:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T00:42:41.000Z", "max_issues_repo_path": "mexFMM2D.cpp", "max_issues_repo_name": "judithyueli/mexBBFMM2D", "max_issues_repo_head_hexsha": "2c73d867f48db3c2e395f9e1c2bebe9784c333e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mexFMM2D.cpp", "max_forks_repo_name": "judithyueli/mexBBFMM2D", "max_forks_repo_head_hexsha": "2c73d867f48db3c2e395f9e1c2bebe9784c333e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-09T00:06:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-14T06:42:51.000Z", "avg_line_length": 33.534591195, "max_line_length": 177, "alphanum_fraction": 0.6348462116, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5817016287560887}}
{"text": "#include \"interface.h\"\n\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseCholesky>\n#include <Eigen/IterativeLinearSolvers>\n\nconstexpr bool DEBUG = false;\n\nusing namespace Eigen;\n\nconstexpr int N = WIDTH * HEIGHT;\n\nvoid print_total_velocities(int line, Grid *grid) {\n    double total_sum_x = 0.0;\n    double total_sum_y = 0.0;\n    for (int y = 0; y < HEIGHT + 1; y++) for (int x = 0; x < WIDTH + 1; x++) {\n        total_sum_x += std::abs(grid->velocity_x[y][x]);\n        total_sum_y += std::abs(grid->velocity_y[y][x]);\n    }\n    if (DEBUG) std::cout << \"total at line \" << line << \": \" << total_sum_x << \", \" << total_sum_y << std::endl;\n}\n\n#define PV do { if (DEBUG) print_total_velocities(__LINE__, grid); } while (false)\n\nstatic SimParams params;\nstatic SparseMatrix<double> laplacian;\nstatic ConjugateGradient<SparseMatrix<double>, Lower|Upper, IncompleteCholesky<double>> solver;\n// static SimplicialLDLT<SparseMatrix<double>> solver;\n\nstatic void step(Grid *grid, const Grid *prev);\n\nvoid sim_init_grid(Grid *grid) {\n    std::memset(grid, 0, sizeof *grid);\n    for (int y = 0; y < HEIGHT + 1; y++) for (int x = 0; x < WIDTH + 1; x++) {\n        grid->velocity_x[y][x] = 0.0;\n        grid->velocity_y[y][x] = 0.0;\n    }\n    for (int y = 0; y < 20; y++) for (int x = 0; x < 20; x++) {\n        grid->density[y + HEIGHT - 40][WIDTH / 2 - 10 + x] = 1.0;\n        grid->temperature[y + HEIGHT - 40][WIDTH / 2 - 10 + x] = 20;\n    }\n}\n\ninline int INDEX(int x, int y) { return x + y * WIDTH; }\n\nbool is_valid(int x, int y) {\n    if (x < 0 || x >= WIDTH) return false;\n    if (y < 0 || y >= HEIGHT) return false;\n    if (params.obstacle_enabled\n     && x >= params.obstacle_xmin && x < params.obstacle_xmax\n     && y >= params.obstacle_ymin && y < params.obstacle_ymax) {\n        return false;\n    }\n    return true;\n}\n\nvoid sim_init() {\n    solver.setMaxIterations(40);\n    solver.setTolerance(1e-10);\n    std::vector<Eigen::Triplet<double>> rows;\n    rows.reserve(5 * N);\n    // fill in Laplacian matrix\n    int NEIGHBOR_OFFSETS[][2] = {\n        {-1, 0},\n        { 1, 0},\n        { 0,-1},\n        { 0, 1},\n    };\n    for (int y = 0; y < HEIGHT; y++) for (int x = 0; x < WIDTH; x++) {\n        if (!is_valid(x, y)) {\n            rows.emplace_back(INDEX(x, y), INDEX(x, y), 1.0);\n            continue;\n        }\n        int neighbor_count = 0;\n        for (const int (&d)[2] : NEIGHBOR_OFFSETS) {\n            int dx = x + d[0], dy = y + d[1];\n            if (is_valid(dx, dy)) {\n                rows.emplace_back(INDEX(x, y), INDEX(dx, dy), -1.0);\n                neighbor_count += 1;\n            }\n        }\n        // rows.emplace_back(INDEX(x, y), INDEX(x, y), neighbor_count);\n        rows.emplace_back(INDEX(x, y), INDEX(x, y), neighbor_count);\n    }\n    laplacian.resize(N, N);\n    laplacian.setFromTriplets(rows.begin(), rows.end());\n    rows.clear();\n    solver.compute(laplacian);\n}\n\nextern \"C\" {\n    double glfwGetTime();\n}\n\nstd::atomic<TimeNode *> timer_root(nullptr);\n\nvoid sim_main() {\n    TimeNode *prev_root = timer_root.exchange(nullptr);\n    while (prev_root) {\n        TimeNode *next = prev_root->next;\n        delete prev_root;\n        prev_root = next;\n    }\n    Grid *prev = grids.get_current(WRITER);\n    while (running.load(std::memory_order_relaxed)) {\n        // update FPS counter\n        TimeNode *root = timer_root.load();\n        TimeNode *node = new TimeNode();\n        node->time = glfwGetTime();\n        node->next = root;\n        timer_root.store(node);\n        Grid *next = grids.swap(WRITER);\n        auto new_params = param_buf.swap(READER);\n        if (new_params->updated) {\n            params = *new_params;\n            new_params->updated = false;\n        }\n        step(next, prev);\n        next->updated = true;\n        /*\n        for (int y = 0; y < HEIGHT; y++) {\n            for (int x = 0; x < WIDTH; x++) {\n                std::cout << (next->temperature[y][x] > 10.0f ? 'A' : ' ');\n            }\n            std::cout << \"\\n\";\n        }\n        std::cout << std::endl;\n        */\n        prev = next;\n    }\n}\n\ntemplate<int W, int H>\ndouble querySafe(const double (&values)[H][W], int x, int y) {\n    if (x < 0 || y < 0 || x >= W || y >= H) return 0.0;\n    return values[y][x];\n}\n\ntemplate<int W, int H>\ndouble interpolate(const double (&values)[H][W], Vector2d position) {\n    int ix = (int) std::floor(position(0)),\n        iy = (int) std::floor(position(1));\n    double fx = position(0) - ix, fy = position(1) - iy;\n    double vx0 = querySafe(values, ix, iy  ) * (1.0 - fx) + querySafe(values, ix+1, iy  ) * fx;\n    double vx1 = querySafe(values, ix, iy+1) * (1.0 - fx) + querySafe(values, ix+1, iy+1) * fx;\n    return vx0 * (1.0 - fy) + vx1 * fy;\n}\n\n// estimate velocity at position by interpolating nearest neighbors\nVector2d interpolateVelocity(const Grid &grid, Vector2d position) {\n    double vx = interpolate(grid.velocity_x, position + Vector2d(0.5, 0.0));\n    double vy = interpolate(grid.velocity_y, position + Vector2d(0.0, 0.5));\n    return Vector2d(vx, vy);\n}\n\nvoid process_forces(Grid *grid) {\n    memset(grid->force_x, 0, sizeof grid->force_x);\n    memset(grid->force_y, 0, sizeof grid->force_y);\n    for (int y = 0; y < HEIGHT; y++) for (int x = 0; x < WIDTH; x++) {\n        grid->force_y[y][x] += -params.alpha * grid->density[y][x] + params.beta * grid->temperature[y][x];\n    }\n    for (int y = 0; y < HEIGHT; y++) for (int x = 0; x < WIDTH; x++)\n    {\n      Vector2d vel_u = interpolateVelocity(*grid, Vector2d(x,y+1));\n      Vector2d vel_d = interpolateVelocity(*grid, Vector2d(x,y-1));\n      Vector2d vel_l = interpolateVelocity(*grid, Vector2d(x+1,y));\n      Vector2d vel_r = interpolateVelocity(*grid, Vector2d(x-1,y));\n\n      //Since 2-D we only need z direction of omega\n      grid->vorticity[y][x] = 0.5 * (vel_r(1) - vel_l(1) - vel_u(0) + vel_d(0));\n    }\n    for (int y = 1; y < HEIGHT - 1; y++) for (int x = 1; x < WIDTH - 1; x++)\n    {\n      Vector2d N;\n      //Used for normalization\n      using std::abs;\n      N(0) = 0.5 * (abs(grid->vorticity[y][x+1]) - abs(grid->vorticity[y][x-1]));\n      N(1) = 0.5 * (abs(grid->vorticity[y+1][x]) - abs(grid->vorticity[y-1][x]));\n      N /= N.norm() + 1e-5;\n      grid->force_x[y][x] += N(1) * grid->vorticity[y][x] * params.epsilon;\n      grid->force_y[y][x] -= N(0) * grid->vorticity[y][x] * params.epsilon;\n    }\n}\n\nvoid apply_force(Grid *grid) {\n    for (int y = 0; y < HEIGHT + 1; y++) for (int x = 0; x < WIDTH + 1; x++) {\n        grid->velocity_x[y][x] += params.timestep * interpolate(grid->force_x, Vector2d(x - 0.5, y));\n        grid->velocity_y[y][x] += params.timestep * interpolate(grid->force_y, Vector2d(x, y - 0.5));\n    }\n}\n\nvoid calculate_pressure(Grid *grid) {\n    VectorXd b(N);\n    double sum_b = 0.0;\n    double dot_b = 0.0;\n    for (int y = 0; y < HEIGHT; y++) for (int x = 0; x < WIDTH; x++) {\n        int n = INDEX(x, y);\n        b(n) = -grid->velocity_x[y][x] + grid->velocity_x[y][x + 1]\n             + -grid->velocity_y[y][x] + grid->velocity_y[y + 1][x];\n        b(n) *= -1.0;\n        sum_b += std::abs(b(n));\n        dot_b += b(n);\n    }\n    if (DEBUG) std::cout << \"sum of b's: \" << sum_b << std::endl;\n    if (DEBUG) std::cout << \"dot b with 1: \" << dot_b << std::endl;\n    Map<VectorXd> pressureMap((double *) grid->pressure, N);\n    VectorXd temp = solver.solve(b);\n    if (DEBUG) std::cout << \"solver error: \" << ((laplacian * temp) - b).norm() << std::endl;\n    // if (b.norm() < 1e-10) {\n    //     temp.setZero();\n    // }\n    double sum_p = 0.0;\n    for (int i = 0; i < N; i++) {\n        sum_p += std::abs(temp(i));\n    }\n    if (DEBUG) std::cout << \"sum of P: \" << sum_p << std::endl;\n    pressureMap = temp;\n}\n\nbool have_exported = false;\n\nvoid step(Grid *grid, const Grid *prev) {\n    *grid = *prev;\n    PV;\n    process_forces(grid);\n    PV;\n    for (int y = 0; y < HEIGHT + 1; y++) for (int x = 0; x < WIDTH + 1; x++) {\n        // update velocity to obtain u*\n        grid->velocity_x[y][x] = interpolate(\n            prev->velocity_x,\n            Vector2d(x, y) - params.timestep *\n                interpolateVelocity(*prev, Vector2d(x - 0.5, y))\n        );\n        grid->velocity_y[y][x] = interpolate(\n            prev->velocity_y,\n            Vector2d(x, y) - params.timestep *\n                interpolateVelocity(*prev, Vector2d(x, y - 0.5))\n        );\n    }\n    apply_force(grid);\n    PV;\n    calculate_pressure(grid);\n    {\n        double sum_div = 0.0;\n        for (int y = 1; y < HEIGHT - 1; y++) for (int x = 1; x < WIDTH - 1; x++) {\n            double div = -grid->velocity_x[y][x] + grid->velocity_x[y][x+1]\n                         -grid->velocity_y[y][x] + grid->velocity_y[y+1][x];\n            sum_div += std::abs(div);\n            // if (std::fabs(div) > 1e-2) std::cout << \"+++\" << div << std::endl;\n        }\n        if (DEBUG) std::cout << \"sum of div before: \" << sum_div << std::endl;\n    }\n    for (int y = 1; y < HEIGHT; y++) for (int x = 1; x < WIDTH; x++) {\n        // update velocity based on pressure\n        grid->velocity_x[y][x] -= (grid->pressure[y][x] - grid->pressure[y][x - 1]);\n        grid->velocity_y[y][x] -= (grid->pressure[y][x] - grid->pressure[y - 1][x]);\n    }\n    PV;\n    {\n        double sum_div = 0.0;\n        for (int y = 1; y < HEIGHT - 1; y++) for (int x = 1; x < WIDTH - 1; x++) {\n            double div = -grid->velocity_x[y][x] + grid->velocity_x[y][x+1]\n                         -grid->velocity_y[y][x] + grid->velocity_y[y+1][x];\n            sum_div += std::abs(div);\n            // if (std::fabs(div) > 1e-2) std::cout << \"+++\" << div << std::endl;\n        }\n        if (DEBUG) std::cout << \"sum of div after: \" << sum_div << std::endl;\n    }\n    for (int i = 0; i <= WIDTH; i++) {\n        grid->velocity_y[0][i] = 0;\n        grid->velocity_y[HEIGHT][i] = 0;\n    }\n    for (int i = 0; i <= HEIGHT; i++) {\n        grid->velocity_y[i][0] = 0;\n        grid->velocity_y[i][WIDTH] = 0;\n    }\n    if (params.obstacle_enabled) {\n        for (int y = params.obstacle_ymin; y <= params.obstacle_ymax; y++) {\n            for (int x = params.obstacle_xmin; x <= params.obstacle_xmax; x++) {\n                if (!(x == params.obstacle_xmin || x == params.obstacle_xmax - 1)) {\n                    grid->velocity_y[y][x] = 0;\n                }\n                if (!(y == params.obstacle_ymin || y == params.obstacle_ymax - 1)) {\n                    grid->velocity_x[y][x] = 0;\n                }\n            }\n        }\n    }\n    // advect temperature and density\n    for (int y = 0; y < HEIGHT; y++) for (int x = 0; x < WIDTH; x++) {\n        Vector2d pt = Vector2d(x, y) - params.timestep *\n            interpolateVelocity(*grid, Vector2d(x, y));\n        grid->density[y][x] = interpolate(prev->density, pt);\n        if (grid->density[y][x] < 0.0) {\n            std::cout << \"NEGATIVE DENSITY!\" << std::endl;\n        }\n        grid->temperature[y][x] = interpolate(prev->temperature, pt);\n        // heat transfer\n        double old = grid->temperature[y][x];\n        grid->temperature[y][x] -= params.kappa * grid->temperature[y][x] * params.timestep;\n        if (old * grid->temperature[y][x] < 0.0) {\n            grid->temperature[y][x] = 0.0;\n        }\n    }\n    PV;\n    if (params.emitter_density > 1e-6) {\n        for (int z = 0; z < 10; z++) {\n            int y = 2;\n            int x = (WIDTH - 10) / 2 + z;\n            double d = grid->density[y][x];\n            double dens = params.emitter_density;\n            grid->density[y][x] += dens;\n            grid->temperature[y][x] = (grid->temperature[y][x] * d + dens * params.emitter_temp) / grid->density[y][x];\n            // grid->velocity_y[y][x] = 1.0;\n        }\n    }\n    if (params.obstacle_enabled) {\n        for (int y = params.obstacle_ymin; y < params.obstacle_ymax; y++) {\n            for (int x = params.obstacle_xmin; x < params.obstacle_xmax; x++) {\n                grid->pressure[y][x] = 0;\n                grid->temperature[y][x] = 0;\n                grid->density[y][x] = 0;\n            }\n        }\n    }\n    PV;\n    if (params.want_to_export && !have_exported) {\n        have_exported = true;\n        std::ofstream f(\"out.csv\");\n        for (int y = 0; y <= HEIGHT; y++) for (int x = 0; x <= WIDTH; x++) {\n            f << x << \",\" << y << \",\" << grid->velocity_x[y][x] << \",\" << grid->velocity_y[y][x] << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "d2023d5e5f574e20d3fa93011dd2ac2a21a75a87", "size": 12467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sim.cpp", "max_stars_repo_name": "j-dong/ps-final", "max_stars_repo_head_hexsha": "818e04602e4e51cee1c86c2f8e927785fe5626a8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sim.cpp", "max_issues_repo_name": "j-dong/ps-final", "max_issues_repo_head_hexsha": "818e04602e4e51cee1c86c2f8e927785fe5626a8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim.cpp", "max_forks_repo_name": "j-dong/ps-final", "max_forks_repo_head_hexsha": "818e04602e4e51cee1c86c2f8e927785fe5626a8", "max_forks_repo_licenses": ["Apache-2.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.1362318841, "max_line_length": 119, "alphanum_fraction": 0.5274725275, "num_tokens": 3872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.5817016179836557}}
{"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#ifndef UTILITIES_DATA_MATRIX_HPP\r\n#define UTILITIES_DATA_MATRIX_HPP\r\n\r\n#include \"Vector.hpp\"\r\n#include \"../UtilitiesAPI.hpp\"\r\n#include \"../core/Logger.hpp\"\r\n\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n\r\nnamespace openstudio{\r\n\r\n  /// Matrix \r\n  typedef boost::numeric::ublas::matrix<double> Matrix;\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n// Begin SWIG'able, copy and paste into Matrix.i\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n  /// new operators\r\n\r\n  UTILITIES_API bool operator==(const Matrix& lhs, const Matrix& rhs);\r\n  UTILITIES_API bool operator!=(const Matrix& lhs, const Matrix& rhs);\r\n\r\n  /// common methods\r\n\r\n  /// linear interpolation of the function v = f(x, y) at point xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  UTILITIES_API double interp(const Vector& x, const Vector& y, const Matrix& v, double xi, double yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  UTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, double yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  UTILITIES_API Vector interp(const Vector& x, const Vector& y, const Matrix& v, double xi, const Vector& yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n  /// linear interpolation of the function v = f(x, y) at points xi, yi\r\n  /// assumes that x and y are strictly increasing\r\n  UTILITIES_API Matrix interp(const Vector& x, const Vector& y, const Matrix& v, const Vector& xi, const Vector& yi, InterpMethod interpMethod = LinearInterp, ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n  /// matrix product\r\n  UTILITIES_API Matrix prod(const Matrix& lop, const Matrix& rop);\r\n\r\n  /// vector product\r\n  UTILITIES_API Vector prod(const Matrix& m, const Vector& v);\r\n\r\n  /// outer product\r\n  UTILITIES_API Matrix outerProd(const Vector& lhs, const Vector& rhs);\r\n\r\n  /// take the natural logarithm of Matrix elements, componentwise\r\n  UTILITIES_API Matrix log(const Matrix& v);\r\n\r\n  /// take the logarithm of Matrix elements with respect to base, componentwise\r\n  UTILITIES_API Matrix log(const Matrix& v, double base);\r\n\r\n  /// generates a M x N Matrix whose elements come from the uniform distribution on [a,b].\r\n  UTILITIES_API Matrix randMatrix(double a, double b, unsigned M, unsigned N);\r\n\r\n  /// sum of all elements\r\n  UTILITIES_API double sum(const Matrix& matrix);\r\n\r\n  /// maximum of all elements\r\n  UTILITIES_API double maximum(const Matrix& matrix);\r\n\r\n  /// minimum of all elements\r\n  UTILITIES_API double minimum(const Matrix& matrix);\r\n\r\n  /// mean of all elements\r\n  UTILITIES_API double mean(const Matrix& matrix);\r\n\r\n  /// get the connected components from an NxN adjacency matrix (1.0 for i-j connected, 0.0 for i-j not connected)\r\n  UTILITIES_API std::vector<std::vector<unsigned> > findConnectedComponents(const Matrix& matrix);\r\n\r\n  // from the boost vault:\r\n  // The following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipes in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\r\n  /// Matrix inversion routine, using lu_factorize and lu_substitute in uBLAS to invert a matrix */\r\n template<class T>\r\n bool invert(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) {\r\n\r\n   // create a working copy of the input\r\n   boost::numeric::ublas::matrix<T> A(input);\r\n\r\n   // create a permutation matrix for the LU-factorization\r\n   boost::numeric::ublas::permutation_matrix<std::size_t> pm(A.size1());\r\n\r\n   // perform LU-factorization\r\n   typename boost::numeric::ublas::matrix<T>::size_type res = boost::numeric::ublas::lu_factorize(A, pm);\r\n   if( res != 0 ){\r\n     LOG_FREE(Info, \"boost.ublas\", \"boost::numeric::ublas::lu_factorize returned res = \" << res <<\r\n                    \", A = \" << A << \", pm = \" << pm << \" for input = \" << input);\r\n     return false;\r\n   }\r\n\r\n   // create identity matrix of \"inverse\"\r\n   inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));\r\n\r\n   // backsubstitute to get the inverse\r\n   try {\r\n     boost::numeric::ublas::lu_substitute(A, pm, inverse);\r\n   }catch (std::exception& e){\r\n     LOG_FREE(Info, \"boost.ublas\", \"boost::numeric::ublas::lu_substitute threw exception '\" << e.what() <<\r\n                    \"' for A = \" << A << \", pm = \" << pm);\r\n     return false;\r\n   }\r\n\r\n   return true;\r\n }\r\n\r\n\r\n} // openstudio\r\n\r\n#endif //UTILITIES_DATA_MATRIX_HPP\r\n", "meta": {"hexsha": "00a82eef4b4bfba326786467dd249adf4d52e145", "size": 5917, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/data/Matrix.hpp", "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/data/Matrix.hpp", "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/data/Matrix.hpp", "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": 43.8296296296, "max_line_length": 200, "alphanum_fraction": 0.6650329559, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.581672691454386}}
{"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#include <complex>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/dense2D.hpp> \n#include <boost/numeric/mtl/matrix/laplacian_setup.hpp> \n#include <boost/numeric/mtl/vector/dense_vector.hpp> \n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename MatrixA>\nvoid test(MatrixA& A, unsigned dim1, unsigned dim2, const char* name)\n{\n    const unsigned max_print_size= 25;\n    cout << \"\\n\" << name << \"\\n\";\n    laplacian_setup(A, dim1, dim2);\n\n    unsigned size= dim1 * dim2;\n    mtl::dense_vector<double> v(size);\n    for (unsigned i= 0; i < num_cols(A); i++)\n\tv[i]= A[12][i];\n\n    // Resulting vector has same value type as matrix\n    typedef typename mtl::Collection<MatrixA>::value_type rvalue_type;\n    mtl::dense_vector<rvalue_type> w(size), w2;\n\n    w= A * v;\n    //mult(A, v, w);\n\n    if (size <= max_print_size)\n\tcout << \"A= \\n\" << A << \"\\n\\nv= \" << v << \"\\n\\nA*v= \" << w << \"\\n\";\n\n    // Same test as in matrix product: resulting vector corresponds to column 12\n    // Check for stencil below in the middle of the matrix\n    //        1\n    //     2 -8  2\n    //  1 -8 20 -8  1\n    //     2 -8  2\n    //        1    \n    if (dim1 == 5 && dim2 == 5) {\n\trvalue_type twenty(20.0), two(2.0), one(1.0), zero(0.0), minus_eight(-8.0);\n\tMTL_THROW_IF(w[12] != twenty, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(w[13] != minus_eight, mtl::runtime_error(\"wrong east neighbor\"));\n\tMTL_THROW_IF(w[14] != one, mtl::runtime_error(\"wrong east east neighbor\"));\n\tMTL_THROW_IF(w[15] != zero, mtl::runtime_error(\"wrong zero-element\"));\n\tMTL_THROW_IF(w[17] != minus_eight, mtl::runtime_error(\"wrong south neighbor\"));\n\tMTL_THROW_IF(w[18] != two, mtl::runtime_error(\"wrong south east neighbor\"));\n\tMTL_THROW_IF(w[22] != one, mtl::runtime_error(\"wrong south south neighbor\"));\n    }\n\n    w+= A * v;\n\n    if (size <= max_print_size)\n\tcout << \"w+= A*v= \\n\\n\" << w << \"\\n\";\n\n    // Check for stencil, must be doubled now\n    if (dim1 == 5 && dim2 == 5) {\n\trvalue_type forty(40.0), four(4.0);\n\tMTL_THROW_IF(w[12] != forty, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(w[18] != four, mtl::runtime_error(\"wrong south east neighbor\"));\n    }\n\n    w-= A * v;\n\n    if (size <= max_print_size)\n\tcout << \"w-= A*v= \\n\\n\" << w << \"\\n\";\n\n    // Check for stencil, must be A*v now\n    if (dim1 == 5 && dim2 == 5) {\n\trvalue_type twenty(20.0), two(2.0);\n\tMTL_THROW_IF(w[12] != twenty, mtl::runtime_error(\"wrong diagonal\"));\n\tMTL_THROW_IF(w[18] != two, mtl::runtime_error(\"wrong south east neighbor\"));\n    }\n\n#if 0\n    rvalue_type dotexp= dot(w, v), dotres;\n    mtl::with_dot(w2, dotres)= A * v;\n\n    w2-= w;\n    if (two_norm(w2) > 0.001)\n\tthrow \"Vector result wrong in with_dot computation.\";\n    if (std::abs(dotres - dotexp) > 0.001)\n\tthrow \"Dot result wrong in with_dot computation.\";\n#endif\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n\n    unsigned dim1= 5, dim2= 5;\n\n    if (argc > 2) {dim1= atoi(argv[1]); dim2= atoi(argv[2]);}\n    unsigned size= dim1 * dim2; \n\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n\n    test(cr, dim1, dim2, \"Row-major sparse\");\n#if 1\n    test(cc, dim1, dim2, \"Column-major sparse\");\n\n    test(dr, dim1, dim2, \"Row-major dense\");\n    test(dc, dim1, dim2, \"Column-major dense\");\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "225a6161ba6f3c6ac60fce18b4aceea4ec007fb4", "size": 4145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_vector_product_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_vector_product_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_vector_product_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.1317829457, "max_line_length": 94, "alphanum_fraction": 0.6275030157, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.5816726832499267}}
{"text": "#ifndef DG_BASIS_HPP\n#define DG_BASIS_HPP\n\n#include <tuple>\n#include <map>\n#include <boost/math/special_functions/legendre.hpp>\n\nnamespace DGHydro {\n\n  template<int nDim, int nDeg>\n  class BasisFunctions {\n  public:\n    BasisFunctions() {\n      total_number = 0;\n\n      for (int i = 0; i <= nDeg; i++) {\n        for (int j = 0; j <= nDeg*(nDim > 1); j++) {\n          for (int k = 0; k <= nDeg*(nDim > 2); k++) {\n            if (i + j + k <= nDeg) {\n              basisMap.insert({total_number, std::make_tuple(i, j, k)});\n\n              //std::cout << \"Added \" << i << \" \" << j << \" \" << k << std::endl;\n              total_number++;\n            }\n          }\n        }\n      }\n    };\n\n    ~BasisFunctions(void) {};\n\n    double operator()(int i, double x, double y, double z) {\n      int a = std::get<0>(basisMap[i]);\n      int b = std::get<1>(basisMap[i]);\n      int c = std::get<2>(basisMap[i]);\n\n      return boost::math::legendre_p(a, x)*boost::math::legendre_p(b, y)*boost::math::legendre_p(c, z);\n    }\n\n    double x_derivative(int i, double x, double y, double z) {\n      int a = std::get<0>(basisMap[i]);\n      int b = std::get<1>(basisMap[i]);\n      int c = std::get<2>(basisMap[i]);\n\n      double p_prime = a*(x*boost::math::legendre_p(a, x) -\n                          boost::math::legendre_p(a - 1, x))/(x*x - 1.0);\n\n      return p_prime*boost::math::legendre_p(b, y)*boost::math::legendre_p(c, z);\n    }\n\n    double y_derivative(int i, double x, double y, double z) {\n      int a = std::get<0>(basisMap[i]);\n      int b = std::get<1>(basisMap[i]);\n      int c = std::get<2>(basisMap[i]);\n\n      double p_prime = b*(y*boost::math::legendre_p(b, y) -\n                          boost::math::legendre_p(b - 1, y))/(y*y - 1.0);\n\n      return boost::math::legendre_p(a, x)*p_prime*boost::math::legendre_p(c, z);\n    }\n\n    double z_derivative(int i, double x, double y, double z) {\n      int a = std::get<0>(basisMap[i]);\n      int b = std::get<1>(basisMap[i]);\n      int c = std::get<2>(basisMap[i]);\n\n      double p_prime = c*(z*boost::math::legendre_p(c, z) -\n                          boost::math::legendre_p(c - 1, z))/(z*z - 1.0);\n\n      return boost::math::legendre_p(a, x)*boost::math::legendre_p(b, y)*p_prime;\n    }\n\n\n    int total_number;\n  private:\n    std::map<int, std::tuple<int, int, int>> basisMap;\n\n\n  };\n\n} // namespace DGHydro\n\n#endif  // DG_BASIS_HPP\n", "meta": {"hexsha": "396bce87d60d54705c2ab728ab8af787eb03246a", "size": 2379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/state/basis.hpp", "max_stars_repo_name": "SijmeJan/DGHydro", "max_stars_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/state/basis.hpp", "max_issues_repo_name": "SijmeJan/DGHydro", "max_issues_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/state/basis.hpp", "max_forks_repo_name": "SijmeJan/DGHydro", "max_forks_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3214285714, "max_line_length": 103, "alphanum_fraction": 0.5313156789, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.581672667960853}}
{"text": "// Compile command: g++ -Wall -Wextra -std=c++17 -O2 -pthread -I/usr/include/eigen3 -I/usr/include/python3.8 -o triangular_cone_sigmax triangular_cone_sigmax.cpp -lpython3.8\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <Eigen/Dense>\n#include <vector>\n#include <utility>\n#include <functional>\n#include <thread>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <ctime>\n#include <iomanip>\n#include <fstream>\n#include <filesystem>\n#include \"matplotlibcpp.h\"\n\n\nnamespace plt = matplotlibcpp;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix2cd;\nusing Eigen::Vector2cd;\nusing std::vector;\nusing std::sqrt;\nusing std::cos;\nusing std::acos;\nusing std::sin;\nusing std::atan2;\nusing namespace std::complex_literals;\n\ntypedef std::complex<double> cd;\ntypedef vector<vector<vector<cd>>> grid_t;\ntypedef std::function<Matrix2cd(int, double, double)> gen_coin_t;\n\n// Settings here\nint num_steps = 10000;\nint initialState = 0; // See main function for details\ndouble eps = 0.01;\ndouble dy = sqrt(3);\nbool bugLambda = true; // Set to true to set Lambda = I_2\nbool plotCone = false; // Set to true to plot the results in the cone coordinates\nbool showVectField = true; // Set to true to show the vector field in original coordinates\nint ymin = -50, ymax = 50;\nint xmin = 2*ymin-2, xmax = 2*ymax+2;\nint ntriangles_x = xmax-xmin+1;\nint ntriangles_y = ymax-ymin+1;\nint center[2] = {-xmin, -ymin};\nstd::string prefix;\nbool sigmax_pattern[11];\nvector<std::string> initialStateName = {\"square\", \"shiftright\", \"shiftdl\", \"center\", \"bothsides\", \"almostcenter\"};\n\nstd::time_t now = time(0);\nstd::tm *ltm = localtime(&now);\n\ngrid_t zerogrid() {\n    return vector<vector<vector<cd>>>(ntriangles_x, vector<vector<cd>> (ntriangles_y, vector<cd> (3, 0. + 0i)));\n}\ngrid_t nangrid() {\n    return vector<vector<vector<cd>>>(ntriangles_x, vector<vector<cd>> (ntriangles_y, vector<cd> (3, std::nan(\"\") + 0i)));\n}\n\ngrid_t grid = zerogrid();\n\nMatrix2cd H, Q;\n\ndouble sumAmplitudes() {\n    double ret = 0.0;\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++) {\n                cd val = grid[x+center[0]][y+center[1]][side];\n                ret += std::real(val*std::conj(val));\n            }\n    return ret;\n}\n\nvoid normalizeGrid() {\n    double target = sumAmplitudes();\n    double mul = 1/sqrt(target);\n    if(target == 0)\n        return;\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++)\n                grid[x+center[0]][y+center[1]][side] *= mul;\n}\n\ninline int modulo(int a, int b) {\n    return (a%b+b)%b;\n}\n\nvoid init_HQ() {\n    H << 1, 1, 1, -1;\n    H /= sqrt(2);\n    Q << 1, -1i, 1, 1i;\n    Q /= sqrt(2);\n}\n\nMatrix2cd gen_Ui(double thetai) {\n    Matrix2cd ret;\n    ret << \n        cos(thetai/2), sin(thetai/2),\n        -sin(thetai/2), cos(thetai/2);\n    return ret;\n}\n\ninline int sign(double d) {\n    if(d>=0)\n        return 1;\n    else\n        return -1;\n}\n\ninline double sq(double d) {\n    return d*d;\n}\n\ninline double correct_fmod(const double a, const double b) {\n    return std::fmod(std::fmod(a,b)+b, b);\n}\n\ninline double principal_measure(const double theta) {\n    double ret = correct_fmod(theta, 2*M_PI);\n    if(ret > M_PI)\n        ret -= 2*M_PI;\n    return ret;\n}\n\nMatrix2cd lamb(double rx, double ry) {\n    Matrix2cd ret;\n    if(bugLambda)\n        ret = Matrix2cd::Identity();\n    else if(rx == 0 && ry == 0) {\n        ret <<\n            6./5.*cos(-5.*M_PI/6.), -6./5.*sin(-5.*M_PI/6.),\n            6./5.*sin(-5.*M_PI/6.), 5./5.*cos(-5.*M_PI/6.);\n    }\n    else {\n        double r = 5./6.*sqrt(rx*rx+ry*ry);\n        double thetap = atan2(ry, rx);\n        double theta2 = principal_measure(thetap + 5*M_PI/6);\n        double theta = 6./5.*theta2;\n        double x = r*cos(theta), y = r*sin(theta);\n        ret <<\n            6./5.*(x/r*cos(thetap) + y/r*sin(thetap)),\n            6./5.*(y/r*cos(thetap) - x/r*sin(thetap)),\n            6./5.*(x/r*sin(thetap) - y/r*cos(thetap)),\n            6./5.*(y/r*sin(thetap) + x/r*cos(thetap));\n    }\n    return ret;\n}\n\nvector<cd> l(double rx, double ry) {\n    Matrix2cd lam = lamb(rx, ry);\n    double sqrt3 = sqrt(3.0);\n    return {lam(0,0), lam(1,0)/sqrt3, -lam(1,0)/sqrt3, lam(0,1), lam(1,1)/sqrt3, -lam(1,1)/sqrt3};\n}\n\ndouble gen_theta(int i, double rx, double ry) {\n    return std::real(M_PI/2 + sqrt(eps)*l(rx, ry)[i]);\n}\n\nMatrix2cd gen_U(int i, double rx, double ry) {\n    return gen_Ui(gen_theta(i, rx, ry));\n}\n\nMatrix2cd gen_Ubis(int i, double rx, double ry) {\n    return gen_U(i+3, rx, ry);\n}\n\nMatrix2cd gen_Ustar(int i, double rx, double ry) {\n    return gen_U(i, rx, ry).adjoint();\n}\n\nMatrix2cd gen_Ubisstar(int i, double rx, double ry) {\n    return gen_Ustar(i+3, rx, ry);\n}\n\ngrid_t shift(grid_t grid) {\n    grid_t ngrid = zerogrid();\n    for(int x = xmin; x <= xmax; x++) {\n        for(int y = ymin; y <= ymax; y++) {\n            for(int i = 0; i < 3; i++) {\n                int iprec = ((i-1)%3+3)%3;\n                ngrid[x+center[0]][y+center[1]][i] = grid[x+center[0]][y+center[1]][iprec];\n            }\n        }\n    }\n    return ngrid;\n}\n\nstd::pair<double, double> real_coords(int iside, int x, int y, bool show = false) {\n    double dec;\n    if(show)\n        dec = .4;\n    else\n        dec = .5;\n    double xcoord, ycoord;\n    if((x+y)%2==0) {\n        if(iside == 0) {\n            xcoord = x-dec;\n            ycoord = (y+.5)*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x+dec;\n            ycoord = (y+.5)*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y+.5+dec)*dy;\n        }\n    }\n    else {\n        if(iside == 0) {\n            xcoord = x+dec;\n            ycoord = (y+.5)*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x-dec;\n            ycoord = (y+.5)*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y+.5-dec)*dy;\n        }\n    }\n    return std::make_pair(sqrt(eps)*xcoord, sqrt(eps)*ycoord);\n}\n\nstd::pair<double, double> cone_coords(int iside, int x, int y, bool show = false) {\n    double rx, ry;\n    std::tie(rx, ry) = real_coords(iside, x, y, show);\n    double r = 5./6.*sqrt(rx*rx+ry*ry);\n    double theta_before = atan2(ry, rx);\n    double theta_rotate = principal_measure(theta_before+5*M_PI/6.);\n    double theta = 6./5.*theta_rotate;\n    //std::cerr << \"theta \" << theta_before*180/M_PI << \" -> \" << theta_rotate*180/M_PI << \" -> \" << theta*180/M_PI << std::endl;\n    return std::make_pair(r*cos(theta), r*sin(theta));\n}\n\nconst int DELTAS[][2] = {{-1,0}, {1,0}, {0,1}};\nconst int NUM_THREADS = 8;\n\nvoid applyCoinsPartial(grid_t &ngrid, grid_t &grid, gen_coin_t &gen_coin, int loc_xmin, int loc_xmax, bool is_sigmax) {\n    for(int x = loc_xmin; x < loc_xmax; x++) {\n        for(int y = ymin; y <= ymax; y++) {\n            if((x+y)%2 || (x>y && y>=0))\n                continue;\n            for(int iside = 0; iside < 3; iside++) {\n                cd thisval = grid[x+center[0]][y+center[1]][iside];\n                int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                //if(xo > xmax || xo < xmin || yo > ymax || yo < ymin || (xo > yo && yo >= 0)) { // pas de propagation aux bords\n                if(xo > xmax || xo < xmin || yo > ymax || yo < ymin || (!is_sigmax && xo > yo && yo >= 0)) { // pas de propagation aux bords\n                    ngrid[x+center[0]][y+center[1]][iside] = thisval;\n                    continue;\n                }\n                else if(y == -1 && x >= 1 && iside == 2) {\n                    int xo = x/2, yo = x/2;\n                    ngrid[x+center[0]][y+center[1]][iside] = std::exp(1.0i * M_PI/3.) * grid[xo+center[0]][yo+center[1]][1];\n                }\n                else if(x == y && x >= 0 && iside == 1) {\n                    int xo = 2*x+1, yo = -1;\n                    ngrid[x+center[0]][y+center[1]][iside] = std::exp(-1.0i * M_PI/3.) * grid[xo+center[0]][yo+center[1]][2];\n                }\n                else {\n                    cd otherval = grid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside];\n                    Vector2cd vect;\n                    vect << thisval, otherval;\n                    double rx, ry;\n                    std::tie(rx, ry) = real_coords(iside, x, y);\n                    Matrix2cd coin = gen_coin(iside, rx, ry);\n                    Vector2cd newvect = coin*vect;\n                    ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                    ngrid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside] = newvect(1);\n                }\n            }\n        }\n    }\n}\n\ngrid_t applyCoins(grid_t grid, gen_coin_t gen_coin, bool is_sigmax, bool multithread = true) {\n    grid_t ngrid = nangrid();\n    if(!multithread) {\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                if((x+y)%2 || (x>y && y>=0)) // pentagone : on enlève un bout de 60°\n                    continue;\n                for(int iside = 0; iside < 3; iside++) {\n                    cd thisval = grid[x+center[0]][y+center[1]][iside];\n                    int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                    if(xo > xmax || xo < xmin || yo > ymax || yo < ymin || (!is_sigmax && xo > yo && yo >= 0)) { // pas de propagation aux bords\n                        ngrid[x+center[0]][y+center[1]][iside] = thisval;\n                        continue;\n                    }\n                    else if(y == -1 && x >= 1 && iside == 2) {\n                        int xo = x/2, yo = x/2;\n                        ngrid[x+center[0]][y+center[1]][iside] = std::exp(1.0i * M_PI/3.) * grid[xo+center[0]][yo+center[1]][1];\n                    }\n                    else if(x == y && x >= 0 && iside == 1) {\n                        int xo = 2*x+1, yo = -1;\n                        ngrid[x+center[0]][y+center[1]][iside] = std::exp(-1.0i * M_PI/3.) * grid[xo+center[0]][yo+center[1]][2];\n                    }\n                    else {\n                        cd otherval = grid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside];\n                        Vector2cd vect;\n                        vect << thisval, otherval;\n                        double rx, ry;\n                        std::tie(rx, ry) = real_coords(iside, x, y);\n                        Matrix2cd coin = gen_coin(iside, rx, ry);\n                        Vector2cd newvect = coin*vect;\n                        ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                        ngrid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside] = newvect(1);\n                    }\n                }\n            }\n        }\n    }\n    else {\n        std::thread threads[NUM_THREADS];\n        int delta_x = ntriangles_x/NUM_THREADS;\n        for(int iThread = 0; iThread < NUM_THREADS-1; iThread++) {\n            threads[iThread] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(gen_coin), xmin+iThread*delta_x, xmin+(iThread+1)*delta_x, is_sigmax);\n        }\n        threads[NUM_THREADS-1] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(gen_coin), xmin+(NUM_THREADS-1)*delta_x, xmax+1, is_sigmax);\n        for(int iThread = 0; iThread < NUM_THREADS; iThread++)\n            threads[iThread].join();\n    }\n    // We may miss some sides of 1 (tip up) triangles which are not adjacent to a valid 0 triangle\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++) {\n                cd &newval = ngrid[x+center[0]][y+center[1]][side];\n                if(std::isnan(std::real(newval)))\n                    newval = grid[x+center[0]][y+center[1]][side];\n            }\n    return ngrid;\n}\n\nvoid plotVectorField(double minx, double maxx, double miny, double maxy, int gridstep = 20) {\n    vector<double> xloc, yloc;\n    vector<double> vectx, vecty;\n    double dx = (maxx-minx)/gridstep, dy = (maxy-miny)/gridstep;\n    for(double x = minx; x <= maxx; x += dx)\n        for(double y = miny; y <= maxy; y += dy) {\n            for(int i = 0; i < 2; i++) {\n                xloc.push_back(x);\n                yloc.push_back(y);\n                Matrix2cd deform = lamb(x,y);\n                vectx.push_back(std::real(deform(0,i)));\n                vecty.push_back(std::real(deform(1,i)));\n            }\n        }\n    plt::quiver(xloc, yloc, vectx, vecty, {{\"pivot\",\"tail\"}, {\"color\", \"grey\"}});\n}\n\nvoid plot(int iGrid = -1) {\n    std::cerr << \"Plotting \" << iGrid << std::endl;\n    PyObject *fig;\n    if(plotCone) {\n        fig = plt::figure_size(1000,1000);\n        plt::xlim(xmin*sqrt(eps), xmax*sqrt(eps));\n        plt::ylim(ymin*sqrt(eps)*dy, ymax*sqrt(eps)*dy);\n        plt::set_aspect_equal();\n        vector<double> xlist, ylist, colorlist;\n        vector<double> listvals;\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    listvals.push_back(col);\n                }\n            }\n        }\n        std::sort(listvals.rbegin(), listvals.rend());\n        double maxi = (listvals[0]+listvals[1])/2;\n        double threshold = maxi/10;\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    if(col > threshold) {\n                        double rx, ry;\n                        std::tie(rx, ry) = cone_coords(iside, x, y, true);\n                        xlist.push_back(rx);\n                        ylist.push_back(ry);\n                        colorlist.push_back(col);\n                    }\n                }\n            }\n        }\n        if(maxi == 0.0)\n            maxi = 1.0;\n        maxi *= 0.6;\n        plt::scatter_colored(xlist, ylist, colorlist, 5, {{\"cmap\",\"gist_heat_r\"}, {\"vmin\", \"0\"}, {\"vmax\", std::to_string(maxi)}});\n    }\n    else {\n        fig = plt::figure_size(1000,1000);\n        plt::set_aspect_equal();\n        vector<vector<double>> imgrid(ymax-ymin+1, vector<double>(xmax-xmin+1, 0.0));\n        vector<double> listvals;\n        for(int y = ymin; y <= ymax; y++) {\n            for(int x = xmin; x <= xmax; x++) {\n                double sum = 0.0;\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    sum += col;\n                }\n                listvals.push_back(sum);\n                imgrid[y+center[1]][x+center[0]] = sum;\n            }\n        }\n        std::sort(listvals.rbegin(), listvals.rend());\n        double maxi = (listvals[0]+listvals[1])/2;\n        if(maxi == 0.0)\n            maxi = 1.0;\n        maxi *= .6;\n            \n        double minx = sqrt(eps)*(xmin-.5);\n        double maxx = sqrt(eps)*(xmax+.5);\n        double miny = sqrt(eps)*dy*(ymin-.5);\n        double maxy = sqrt(eps)*dy*(ymax+.5);\n        plt::imshow(imgrid, {minx, maxx, miny, maxy}, {{\"origin\", \"lower\"}, {\"cmap\", \"gist_heat_r\"}, {\"vmin\", \"0.0\"}, {\"vmax\", std::to_string(maxi)}});\n        plt::plot({0.0, maxy/tan(M_PI/3)}, {0.0, maxy}, {{\"color\",\"red\"}});\n        plt::plot({0.0, xmax*sqrt(eps)}, {0.0, 0.0}, {{\"color\",\"red\"}});\n        if(showVectField)\n            plotVectorField(xmin*sqrt(eps), xmax*sqrt(eps), ymin*sqrt(eps)*dy, ymax*sqrt(eps)*dy, 20);\n    }\n    std::ostringstream filename;\n    filename << prefix << \"_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename.str());\n    plt::clf();\n    plt::close(fig);\n    Py_DECREF(fig);\n\n    // Plot around dislocation line\n    vector<double> xlist2, ylist2;\n    for(int x = 0; x <= xmax; x++) {\n        vector<int> klist;\n        if((x+1)%2)\n            klist = {1, 2, 0};\n        else\n            klist = {0, 2, 1};\n        for(int k : klist) {\n            double rx, ry;\n            std::tie(rx, ry) = real_coords(k, x, -1);\n            xlist2.push_back(rx);\n            cd val = grid[x+center[0]][center[1]-1][k];\n            double col = std::real(val*std::conj(val));\n            ylist2.push_back(col);\n        }\n    }\n    plt::plot(xlist2, ylist2);\n    std::ostringstream filename_disloc;\n    filename_disloc << prefix << \"_dislocation_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename_disloc.str());\n    plt::cla();\n    plt::clf();\n    plt::close();\n    std::cerr << \"Done plotting \" << iGrid << std::endl;\n}\n\nvoid step_walk(int step = -1) {\n    std::cerr << \"Begin step \" << step << std::endl;\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = H;\n        return ret;\n    }, sigmax_pattern[0]);\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ustar, sigmax_pattern[1]);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_U(((i-1)%3+3)%3, rx, ry);\n            return ret;\n        }, sigmax_pattern[2]);\n    }\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_U, sigmax_pattern[3]);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ustar(((i-1)%3+3)%3, rx, ry);\n            return ret;\n        }, sigmax_pattern[4]);\n    }\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = Q*H;\n        return ret;\n    }, sigmax_pattern[5]);\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ubisstar, sigmax_pattern[6]);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ubis(((i-1)%3+3)%3, rx, ry);\n            return ret;\n        }, sigmax_pattern[7]);\n    }\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ubis, sigmax_pattern[8]);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ubisstar(((i-1)%3+3)%3, rx, ry);\n            return ret;\n        }, sigmax_pattern[9]);\n    }\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = Q.adjoint();\n        return ret;\n    }, sigmax_pattern[10]);\n    std::cerr << \"Total amplitude: \" << sumAmplitudes() << \"\\n\";\n    //normalizeGrid();\n    //std::cerr << \"After normalization: \" << sumAmplitudes() << \"\\n\";\n    std::cerr << \"End step \" << step << std::endl;\n}\n\nvoid print_params() {\n    std::ofstream ostream(prefix + \"/settings.txt\");\n    ostream << \"num_steps = \" << num_steps << \"\\n\";\n    ostream << \"eps = \" << eps << \"\\n\";\n    ostream << \"xmin = \" << xmin << \"\\n\";\n    ostream << \"xmax = \" << xmax << \"\\n\";\n    ostream << \"ymin = \" << ymin << \"\\n\";\n    ostream << \"ymax = \" << ymax << \"\\n\";\n    ostream << \"sigma_x pattern: \";\n    for(int i = 0; i < 11; i++)\n        ostream << (int)sigmax_pattern[i];\n    ostream.close();\n}\n\nvoid listInitialStates() {\n    for(size_t i = 0; i < initialStateName.size(); i++)\n        std::cerr << \"- \" << i << \": \" << initialStateName[i] << \"\\n\";\n}\n\nint main(int argc, char **argv)\n{\n    if(argc <= 3) {\n        std::cerr << \"Usage: \" << std::string(argv[0]) << \" <initial state> <plot cone> <sigmax pattern>\\n\";\n        std::cerr << \"Initial states:\\n\";\n        listInitialStates();\n        std::cerr << \"<plot cone> should be 1 if the figure should be plotted in cone coordinates, 0 otherwise.\\n\";\n        std::cerr << \"<sigmax pattern> should be a sequence of 11 ones and zeroes, a 1 at position i meaning that sigma_x should be applied on the dislocation line at coin i and 0 meaning that the identity should be applied instead.\\n\";\n        return 1;\n    }\n    initialState = std::atoi(argv[1]);\n    if(initialState < 0 || initialState >= (int)initialStateName.size()) {\n        std::cerr << \"Invalid initial state \" << initialState << \". List of possible states:\\n\";\n        listInitialStates();\n        return 2;\n    }\n    plotCone = (bool) std::atoi(argv[2]);\n    if(std::strlen(argv[3]) != 11) {\n        std::cerr << \"Invalid sigma_x pattern: mismatching length, should be 11 characters\\n\";\n        return 3;\n    }\n    for(int i = 0; i < 11; i++) {\n        if(argv[3][i] == '0')\n            sigmax_pattern[i] = false;\n        else if(argv[3][i] == '1')\n            sigmax_pattern[i] = true;\n        else {\n            std::cerr << \"Invalid sigma_x pattern: expected 0 or 1, got \" << argv[3][i] << \"\\n\";\n            return 3;\n        }\n    }\n    std::ostringstream str;\n    str <<\n        \"simul_conesigmax_\" << initialStateName[initialState];\n    if(plotCone)\n        str << \"_conecoord_\";\n    else\n        str << \"_altcoord_\";\n    str <<\n        std::setw(4) << std::setfill('0') << ltm->tm_year+1900 << \"-\" << \n        std::setw(2) << ltm->tm_mon+1 << \"-\" << \n        std::setw(2) << ltm->tm_mday << \"_\" << \n        std::setw(2) << ltm->tm_hour << \"-\" << \n        std::setw(2) << ltm->tm_min << \"-\" << \n        std::setw(2) << ltm->tm_sec;\n    prefix = str.str();\n    std::filesystem::create_directory(prefix);\n    init_HQ();\n    print_params();\n    // Initial state\n    if(initialState == 0) {\n        for(int x = xmin/5; x <= xmax/5; x++)\n            for(int y = ymin/5; y <= ymax/5; y++)\n                for(int k = 0; k < 3; k++)\n                    if(x <= y || y < 0)\n                        grid[center[0]+x][center[1]+y][k] = 1;\n        normalizeGrid();\n    }\n    // Shifted\n    else if(initialState == 1) {\n        for(int k = 0; k < 3; k++)\n            grid[center[0]+xmax/2-1][center[1]-1][k]=1/sqrt(3);\n    }\n    // Shifted (in another way)\n    else if(initialState == 2) {\n        for(int k = 0; k < 3; k++)\n            grid[center[0]+xmin/4+1][center[1]+ymin/4+1][k]=1/sqrt(3);\n    }\n    // Centered\n    else if(initialState == 3) {\n        vector<vector<int>> centercoord = {{-1,0},{0,0},{-1,-1},{0,-1},{1,-1}};\n        for(vector<int> &coord : centercoord)\n            for(int k = 0; k < 3; k++)\n                grid[center[0]+coord[0]][center[1]+coord[1]][k]=1/sqrt(3*centercoord.size());\n    }\n    // Shifted, both sides of the line\n    else if(initialState == 4) {\n        for(int k=0; k<3; k++) {\n            grid[center[0]+10][center[1]+10][k] = 1/sqrt(6);\n            grid[center[0]+21][center[1]-1][k] = 1/sqrt(6);\n        }\n    }\n    // Almost centered\n    else if(initialState == 5) {\n        for(int k = 0; k < 3; k++)\n            grid[center[0]-1][center[1]-1][k] = 1/sqrt(3);\n    }\n    plot(0);\n    for(int i = 0; i < num_steps; i++) {\n        step_walk(i);\n        if(((i+1)%10) == 0)\n            plot(i+1);\n    }\n}\n", "meta": {"hexsha": "6ad2b197ccf9c9ce30fa2148da3f818541675e86", "size": 22894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "triangular_cone_sigmax.cpp", "max_stars_repo_name": "vdng9338/qw_simul", "max_stars_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "triangular_cone_sigmax.cpp", "max_issues_repo_name": "vdng9338/qw_simul", "max_issues_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "triangular_cone_sigmax.cpp", "max_forks_repo_name": "vdng9338/qw_simul", "max_forks_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_forks_repo_licenses": ["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.2820919176, "max_line_length": 236, "alphanum_fraction": 0.5048921115, "num_tokens": 6931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5816630322656481}}
{"text": "#include <stdio.h>\n#include <iostream>\n\n#include <Eigen/Geometry>\n\n#include \"../libfovis/refine_motion_estimate.hpp\"\n\n#define dump(v) std::cerr << #v << \" : \" << (v) << \"\\n\"\n#define dumpT(v) std::cerr << #v << \" : \" << (v).transpose() << \"\\n\"\n\nusing namespace fovis;\n\nstatic inline Eigen::Isometry3d\nisometryFromXYZRollPitchYaw(const Eigen::Matrix<double, 6, 1>& params)\n{\n  Eigen::Isometry3d result;\n\n  double roll = params(3), pitch = params(4), yaw = params(5);\n  double halfroll = roll / 2;\n  double halfpitch = pitch / 2;\n  double halfyaw = yaw / 2;\n  double sin_r2 = sin(halfroll);\n  double sin_p2 = sin(halfpitch);\n  double sin_y2 = sin(halfyaw);\n  double cos_r2 = cos(halfroll);\n  double cos_p2 = cos(halfpitch);\n  double cos_y2 = cos(halfyaw);\n\n  Eigen::Quaterniond quat(\n    cos_r2 * cos_p2 * cos_y2 + sin_r2 * sin_p2 * sin_y2,\n    sin_r2 * cos_p2 * cos_y2 - cos_r2 * sin_p2 * sin_y2,\n    cos_r2 * sin_p2 * cos_y2 + sin_r2 * cos_p2 * sin_y2,\n    cos_r2 * cos_p2 * sin_y2 - sin_r2 * sin_p2 * cos_y2);\n\n  result.setIdentity();\n  result.translate(params.head<3>());\n  result.rotate(quat);\n\n  return result;\n}\n\nstatic inline Eigen::Vector3d\nisometryGetRollPitchYaw(const Eigen::Isometry3d& M)\n{\n  Eigen::Quaterniond q(M.rotation());\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 pitch_sin = 2 * (q.w()*q.y() - q.z()*q.x());\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\n  return Eigen::Vector3d(atan2(roll_a, roll_b),\n      asin(pitch_sin),\n      atan2(yaw_a, yaw_b));\n}\n\nint main(int argc, char** argv)\n{\n\n  int num_points = 9;\n\n  Eigen::Matrix<double, 4, Eigen::Dynamic> points_xyz(4, num_points);\n  Eigen::Matrix<double, 4, Eigen::Dynamic> transformed_xyz(4, num_points);\n  Eigen::Matrix<double, 2, Eigen::Dynamic> ref_projections(2, num_points);\n\n  double tx    = 1.0;\n  double ty    = 1.5;\n  double tz    = 0.5;\n  double roll  = 10 * (M_PI / 180);\n  double pitch =  1 * (M_PI / 180);\n  double yaw   =  5 * (M_PI / 180);\n  //\ttx = 0;\n  //\tty = 0;\n  //\ttz = 0;\n  //\troll = 0;\n  //\tpitch = 0;\n  //\tyaw = 1 * (M_PI / 180);\n\n  Eigen::Matrix<double, 6, 1> params;\n  params << tx, ty, tz, roll, pitch, yaw;\n  Eigen::Isometry3d true_motion = isometryFromXYZRollPitchYaw(params);\n  double fx = 528;\n  double cx = 320;\n  double cy = 240;\n\n  Eigen::Matrix<double, Eigen::Dynamic, 2> tmp(num_points, 2);\n  tmp << \n    0, 0,\n    320, 0,\n    640, 0,\n    0, 240,\n    320, 240,\n    640, 240,\n    0, 480,\n    320, 480,\n    640, 480;\n  ref_projections = tmp.transpose();\n  double depths[] = {\n    1, 0.5, 0.75,\n    100, 1, 0.75,\n    0.75, 0.5, 1,\n  };\n\n  Eigen::Matrix<double, 3, 4> K;\n  K << fx, 0, cx, 0,\n    0, fx, cy, 0,\n    0, 0, 1, 0;\n\n  for(int i=0; i<num_points; i++) {\n    points_xyz(0, i) = depths[i] * (ref_projections(0, i) - cx) / fx;\n    points_xyz(1, i) = depths[i] * (ref_projections(1, i) - cy) / fx;\n    points_xyz(2, i) = depths[i];\n    points_xyz(3, i) = 1;\n\n    Eigen::Vector3d uvw = K * points_xyz.col(i);\n    uvw(0) /= uvw(2);\n    uvw(1) /= uvw(2);\n    uvw(2) = 1;\n\n    transformed_xyz.col(i) = true_motion.inverse().matrix() * points_xyz.col(i);\n\n    Eigen::Vector4d t = transformed_xyz.col(i);\n    Eigen::Vector4d p = points_xyz.col(i);\n\n    printf(\"%3d : %6.2f %6.2f  ->  %6.2f %6.2f %6.2f  -> %7.3f %7.3f %7.3f\\n\",\n        i,\n        uvw(0), uvw(1),\n        p(0), p(1), p(2),\n        t(0), t(1), t(2));\n  }\n  printf(\"=======\\n\");\n\n\n  Eigen::Isometry3d initial_estimate;\n  initial_estimate.setIdentity();\n  Eigen::Vector3d initial_rpy = isometryGetRollPitchYaw(initial_estimate);\n  Eigen::Vector3d initial_trans = initial_estimate.translation();\n\n  Eigen::Isometry3d estimate = refineMotionEstimate(transformed_xyz,\n      ref_projections,\n      fx, cx, cy,\n      initial_estimate, 6);\n\n  Eigen::Matrix<double, 3, 4> P = K * estimate.matrix();\n\n  Eigen::Vector3d estimated_rpy = isometryGetRollPitchYaw(estimate);\n  Eigen::Vector3d estimated_trans = estimate.translation();\n  printf(\"       Estimate   True    Initial\\n\"\n      \"tx:    %6.2f %6.2f %6.2f\\n\"\n      \"ty:    %6.2f %6.2f %6.2f\\n\"\n      \"tz:    %6.2f %6.2f %6.2f\\n\"\n      \"roll:  %6.2f %6.2f %6.2f\\n\"\n      \"pitch: %6.2f %6.2f %6.2f\\n\"\n      \"yaw:   %6.2f %6.2f %6.2f\\n\",\n      estimated_trans(0), tx, initial_trans(0), \n      estimated_trans(1), ty, initial_trans(1), \n      estimated_trans(2), tz, initial_trans(2), \n      estimated_rpy(0) * 180 / M_PI, roll * 180 / M_PI,  initial_rpy(0) * 180 / M_PI,\n      estimated_rpy(1) * 180 / M_PI, pitch * 180 / M_PI, initial_rpy(1) * 180 / M_PI,\n      estimated_rpy(2) * 180 / M_PI, yaw * 180 / M_PI,   initial_rpy(2) * 180 / M_PI);\n\n  // compute reprojection error\n  for(int i=0; i<num_points; i++) {\n    Eigen::Vector3d uvw = P * transformed_xyz.col(i);\n    double u = uvw(0) / uvw(2);\n    double v = uvw(1) / uvw(2);\n    double ref_u = ref_projections(0, i);\n    double ref_v = ref_projections(1, i);\n    double err_u = u - ref_u;\n    double err_v = v - ref_v;\n\n    printf(\"%3d  %6.1f %6.1f -> %6.1f %6.1f (%6.2f %6.2f)\\n\", i, ref_u, ref_v, u, v, err_u, err_v);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "580a57aed217723a4ae879d62e0f8cf1ab426f5f", "size": 5135, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/testers/refine_motion_estimate_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/refine_motion_estimate_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/refine_motion_estimate_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": 29.011299435, "max_line_length": 99, "alphanum_fraction": 0.588510224, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5816630057378901}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <orient/detail/so3_generator.hpp>\n\n#include <Eigen/Dense>\n\nnamespace orient::detail {\n\ntemplate <typename Derived, typename Scalar = typename Eigen::DenseBase<Derived>::Scalar>\nEigen::Matrix<Scalar,3,3> skewSymmetric(Eigen::DenseBase<Derived> const& w) {\n  return (Eigen::Matrix<Scalar,3,3>() << 0.0, -w(2), w(1), w(2), 0.0, -w(0), -w(1), w(0), 0.0).finished();\n}\n\ntemplate <typename Derived, typename Scalar = typename Eigen::DenseBase<Derived>::Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,3>, Eigen::Matrix<Scalar, 9, 3>> skewSymmetricWPD(Eigen::MatrixBase<Derived> const& w) {\n  Eigen::Matrix<Scalar, 9, 3> J{};\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,0).data(), 3,3) = generator<Axis::x>;\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,1).data(), 3,3) = generator<Axis::y>;\n  Eigen::Map<Eigen::Matrix<Scalar,3,3>>(J.template block<9,1>(0,2).data(), 3,3) = generator<Axis::z>;\n  return std::make_pair(skewSymmetric(w), J);\n}\n\ntemplate <typename Derived, typename Scalar = typename Eigen::DenseBase<Derived>::Scalar>\nEigen::Matrix<Scalar,3,1> unskewSymmetric(Eigen::MatrixBase<Derived> const& M)\n{\n  return (Eigen::Matrix<Scalar,3,1>() << - M(1,2), M(0,2), - M(0,1)).finished();\n}\n\ntemplate <typename Derived, typename Scalar = typename Eigen::DenseBase<Derived>::Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,1>, Eigen::Matrix<Scalar, 3, 9>> unskewSymmetricWPD(Eigen::MatrixBase<Derived> const& M)\n{\n  Eigen::Matrix<Scalar, 3, 9> J = Eigen::Matrix<Scalar, 3, 9>::Zero();\n  J(0, 2*3 + 1) = -1.;\n  J(1, 2*3) = 1.;\n  J(2, 1*3) = -1.;\n  return std::make_pair(unskewSymmetric(M), J);\n}\n\n}\n", "meta": {"hexsha": "c1e0d417155e9e4a5c03fad266149d2e2b39fbe7", "size": 1862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/detail/skew_symmetric.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/detail/skew_symmetric.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/detail/skew_symmetric.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 41.3777777778, "max_line_length": 121, "alphanum_fraction": 0.6734693878, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5816630002938525}}
{"text": "#include \"../cnum.h\"\n\n#ifndef _WINDOWS\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#endif\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/special_functions/airy.hpp>\n\n#ifndef _WINDOWS\n#pragma GCC diagnostic pop\n#endif\n\nusing namespace boost::math::policies;\n\ntypedef policy<\ndomain_error    <ignore_error>,\noverflow_error  <ignore_error>,\nunderflow_error <ignore_error>,\ndenorm_error    <ignore_error>,\npole_error      <ignore_error>,\nevaluation_error<ignore_error>,\ndigits10<8>\n> PREC;\n\n//----------------------------------------------------------------------------------------------------------------------\n// Bessel functions\n//----------------------------------------------------------------------------------------------------------------------\n\n#define BESSEL(NAME, FUNC) \\\nvoid NAME(const cnum &n, const cnum &z, cnum &r){ try{\\\n\t\tr = (!is_real(z) || !is_real(n)) ? UNDEFINED\\\n\t\t: is_natural(n) ? boost::math::FUNC(to_int(n), z.real(), PREC())\\\n\t\t: boost::math::FUNC(n.real(), z.real(), PREC());\\\n\t}catch(...){ r = UNDEFINED; }}\\\n\\\ndouble NAME(const cnum &n, const cnum &z){ try{\\\n\t\treturn (!is_real(z) || !is_real(n)) ? UNDEFINED\\\n\t\t: is_natural(n) ? boost::math::FUNC(to_int(n), z.real(), PREC())\\\n\t\t: boost::math::FUNC(n.real(), z.real(), PREC());\\\n\t}catch(...){ return UNDEFINED; }}\\\n\\\ndouble NAME(double n, double z){ try{\\\n\t\treturn is_natural(n) ? boost::math::FUNC(to_int(n), z, PREC())\\\n\t\t: boost::math::FUNC(n, z, PREC());\\\n\t}catch(...){ return UNDEFINED; }}\n\nBESSEL(bessel_J, cyl_bessel_j)\nBESSEL(bessel_Y, cyl_neumann)\nBESSEL(bessel_I, cyl_bessel_i)\nBESSEL(bessel_K, cyl_bessel_k)\n\n#undef BESSEL\n\n//----------------------------------------------------------------------------------------------------------------------\n// Elliptic integral Ei\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid expint_i(const cnum &z, cnum &r)\n{\n\ttry\n\t{\n\t\tr = is_real(z) ? boost::math::expint(z.real(), PREC()) : UNDEFINED;\n\t}\n\tcatch(...)\n\t{\n\t\tr = UNDEFINED;\n\t}\n}\ndouble expint_i(const cnum &z)\n{\n\ttry\n\t{\n\t\treturn is_real(z) ? boost::math::expint(z.real(), PREC()) : UNDEFINED;\n\t}\n\tcatch(...)\n\t{\n\t\treturn UNDEFINED;\n\t}\n}\ndouble expint_i(double z)\n{\n\ttry\n\t{\n\t\treturn boost::math::expint(z, PREC());\n\t}\n\tcatch(...)\n\t{\n\t\treturn UNDEFINED;\n\t}\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n// Elliptic integral En\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid expint_n(const cnum &n, const cnum &z, cnum &r)\n{\n\ttry\n\t{\n\t\tr = (is_real(z) && is_natural(n)) ? boost::math::expint(to_natural(n), z.real(), PREC()) : UNDEFINED;\n\t}\n\tcatch(...)\n\t{\n\t\tr = UNDEFINED;\n\t}\n}\ndouble expint_n(const cnum &n, const cnum &z)\n{\n\ttry\n\t{\n\t\treturn (is_real(z) && is_natural(n)) ? boost::math::expint(to_natural(n), z.real(), PREC()) : UNDEFINED;\n\t}\n\tcatch(...)\n\t{\n\t\treturn UNDEFINED;\n\t}\n}\ndouble expint_n(double n, double z)\n{\n\ttry\n\t{\n\t\treturn (is_natural(n)) ? boost::math::expint(to_natural(n), z, PREC()) : UNDEFINED;\n\t}\n\tcatch(...)\n\t{\n\t\treturn UNDEFINED;\n\t}\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n// Airy Ai and Bi, Ai' and Bi'\n//----------------------------------------------------------------------------------------------------------------------\n\n#define AIRY(NAME, FUNC) \\\nvoid NAME(const cnum &z, cnum &r){ try{\\\n\tr = is_real(z) ? boost::math::FUNC(z.real(), PREC()) : UNDEFINED;\\\n\t}catch(...){ r = UNDEFINED; }}\\\n\\\ndouble NAME(const cnum &z){ try{\\\n\treturn is_real(z) ? boost::math::FUNC(z.real(), PREC()) : UNDEFINED;\\\n\t}catch(...){ return UNDEFINED; }}\\\n\\\ndouble NAME(double z){ try{\\\n\treturn boost::math::FUNC(z, PREC());\\\n\t}catch(...){ return UNDEFINED; }}\n\nAIRY(airy_ai, airy_ai)\nAIRY(airy_bi, airy_bi)\nAIRY(airy_ai_prime, airy_ai_prime)\nAIRY(airy_bi_prime, airy_bi_prime)\n\n#undef AIRY\n", "meta": {"hexsha": "8e33446e91232656ef7d678a8a9c949dccc86b93", "size": 4143, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Engine/Functions/boost_wrappers.cc", "max_stars_repo_name": "TrevorShelton/cplot", "max_stars_repo_head_hexsha": "8bf40e94519cc4fd69b2e0677d3a3dcf8695245a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T03:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T17:03:40.000Z", "max_issues_repo_path": "Engine/Functions/boost_wrappers.cc", "max_issues_repo_name": "TrevorShelton/cplot", "max_issues_repo_head_hexsha": "8bf40e94519cc4fd69b2e0677d3a3dcf8695245a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-11-10T09:47:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-21T22:36:47.000Z", "max_forks_repo_path": "Engine/Functions/boost_wrappers.cc", "max_forks_repo_name": "TrevorShelton/cplot", "max_forks_repo_head_hexsha": "8bf40e94519cc4fd69b2e0677d3a3dcf8695245a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-01-05T17:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T14:11:01.000Z", "avg_line_length": 26.3885350318, "max_line_length": 120, "alphanum_fraction": 0.4979483466, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5816350057735066}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vpp/algorithms/symbols.hh>\n\nnamespace vpp\n{\n\n  namespace lk_internals\n  {\n    template <typename F, typename GD>\n    auto match(vfloat2 p, vfloat2 tr_prediction,\n\t       F A, F B, GD Ag,\n\t       const int winsize,\n\t       const float min_ev_th,\n\t       const int max_interations,\n\t       const float convergence_delta)\n    {\n      typedef typename F::value_type V;\n      int WS = winsize;\n      int ws = winsize;\n      int hws = ws/2;\n\n      // Gradient matrix\n      Eigen::Matrix2f G = Eigen::Matrix2f::Zero();\n      int cpt = 0;\n      for(int r = -hws; r <= hws; r++)\n\tfor(int c = -hws; c <= hws; c++)\n\t  {\n\t    vfloat2 n = p + vfloat2(r, c);\n\t    if (A.has(n.cast<int>()))\n\t      {\n\t\tEigen::Matrix2f m;\n\t\tauto g = Ag.linear_interpolate(n);\n\t\tfloat gx = g[0];\n\t\tfloat gy = g[1];\n\t\tm <<\n\t\t  gx * gx, gx * gy,\n\t\t  gx * gy, gy * gy;\n\t\tG += m;\n\t\tcpt++;\n\t      }\n\t  }\n\n      // Check minimum eigenvalue.\n      float min_ev = 99999.f;\n      auto ev = (G / cpt).eigenvalues();\n      for (int i = 0; i < ev.size(); i++)\n\tif (fabs(ev[i].real()) < min_ev) min_ev = fabs(ev[i].real());\n\n      if (min_ev < min_ev_th)\n\treturn std::pair<vfloat2, float>(vfloat2(-1,-1), FLT_MAX);\n\n      Eigen::Matrix2f G1 = G.inverse();\n\n      // Precompute gs and as.\n      vfloat2 prediction_ = p + tr_prediction;\n      vfloat2 v = prediction_;\n      Eigen::Vector2f nk = Eigen::Vector2f::Ones();\n\n      char gs_buffer[WS * WS * sizeof(vfloat2)];\n      vfloat2* gs = (vfloat2*) gs_buffer;\n      // was: vfloat2 gs[WS * WS];\n\n      typedef plus_promotion<V> S;\n      char as_buffer[WS * WS * sizeof(S)];\n      S* as = (S*) as_buffer;\n      // was: S as[WS * WS];\n      {\n\tfor(int i = 0, r = -hws; r <= hws; r++)\n\t  {\n\t    for(int c = -hws; c <= hws; c++)\n\t      {\n\t\tvfloat2 n = p + vfloat2(r, c);\n\t\tif (Ag.has(n.cast<int>()))\n\t\t  {\n\t\t    gs[i] = Ag.linear_interpolate(n).template cast<float>();\n\t\t    as[i] = cast<S>(A.linear_interpolate(n));\n\t\t  }\n\t\ti++;\n\t      }\n\t  }\n      }\n      auto domain = B.domain();// - border(hws + 1);\n\n      // Gradient descent\n      for (int k = 0; k <= max_interations && nk.norm() >= convergence_delta; k++)\n\t{\n\t  Eigen::Vector2f bk = Eigen::Vector2f::Zero();\n\t  // Temporal difference.\n\t  int i = 0;\n\t  for(int r = -hws; r <= hws; r++)\n\t    {\n\t      for(int c = -hws; c <= hws; c++)          \n\t\t{\n\t\t  vfloat2 n = p + vfloat2(r, c);\n\t\t  if (Ag.has(n.cast<int>()))\n\t\t    {\n\t\t      vfloat2 n2 = v + vfloat2(r, c);\n\t\t      auto g = gs[i];\n\t\t      float dt = (cast<float>(as[i]) - cast<float>(B.linear_interpolate(n2)));\n\t\t      bk += Eigen::Vector2f{g[0] * dt, g[1] * dt};\n\t\t    }\n\t\t  i++;\n\t\t}\n\t    }\n\n\t  nk = G1 * bk;\n\t  v += vfloat2{nk[0], nk[1]};\n\n\t  if (!domain.has(v.cast<int>()))\n\t    return std::pair<vfloat2, float>(vfloat2(0, 0), FLT_MAX);\n\t}\n\n      // Compute the SSD.\n      float err = 0;\n      for(int r = -hws; r <= hws; r++)\n\tfor(int c = -hws; c <= hws; c++)\n\t  {\n\t    vfloat2 n2 = v + vfloat2(r, c);\n\t    int i = (r+hws) * ws + (c+hws);\n\t    {\n\t      err += fabs(cast<float>(as[i] - cast<S>(B.linear_interpolate(n2))));\n\t      cpt++;\n\t    }\n\t  }\n\n      return std::pair<vfloat2, float>(v - p, err / (cpt));\n\n\n    }\n  }\n  \n  template <typename V, typename... OPTS>\n  void lucas_kanade(const image2d<V>& i1,\n\t\t    const image2d<V>& i2,\n\t\t    OPTS... opts)\n  {\n    auto options = iod::D(opts...);\n    int niterations = options.get(_niterations, 21);\n    int winsize = options.get(_winsize, 11);\n    int nscales = options.get(_nscales, 3);\n    int min_ev = options.get(_min_ev, 0.0001);\n    int delta = options.get(_delta, 0.1);\n    auto prediction = options.get(_prediction,\n\t\t\t\t  [] (auto p) { return vfloat2(0.f, 0.f); });\n    auto flow = options.flow;\n\n    auto keypoints = options.keypoints;\n\n    typedef std::decay_t<decltype(V() - V())> Gr;\n    pyramid2d<V> pyramid_prev(i1, nscales, 2, _border = winsize / 2);\n    pyramid2d<vector<Gr, 2>> pyramid_prev_grad(i1.domain(), nscales, 2, _border = winsize / 2);\n    pyramid2d<V> pyramid_next(i2, nscales, 2, _border = winsize / 2);\n\n    scharr(pyramid_prev[0], pyramid_prev_grad[0]);\n    pyramid_prev_grad.propagate_level0();\n\n    for (int i = 0; i < keypoints.size(); i++)\n    {\n      auto kp = keypoints[i];\n\n      vfloat2 tr = (prediction(kp)).template cast<float>() / float(std::pow(2, nscales));\n      float dist = 0.f;\n      for(int S = pyramid_prev.size() - 1; S >= 0; S--)\n\t{\n\t  tr *= pyramid_prev.factor();\n\t  auto match = lk_internals::match(kp.template cast<float>() / int(std::pow(2, S)),\n\t\t\t\t\t   tr,\n\t\t\t\t\t   pyramid_prev[S],\n\t\t\t\t\t   pyramid_next[S],\n\t\t\t\t\t   pyramid_prev_grad[S],\n\t\t\t\t\t   winsize,\n\t\t\t\t\t   min_ev,\n\t\t\t\t\t   niterations, delta);\n\n\t  tr = match.first;\n\t  dist = match.second;\n\t}\n\n      flow(kp, tr, dist);\n\n    }\n  }\n\n}\n", "meta": {"hexsha": "c008431171d4babe6f079ac8958ac966bbf66259", "size": 4758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/lucas_kanade/lucas_kanade.hpp", "max_stars_repo_name": "jjzhang166/videopp", "max_stars_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/lucas_kanade/lucas_kanade.hpp", "max_issues_repo_name": "jjzhang166/videopp", "max_issues_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/lucas_kanade/lucas_kanade.hpp", "max_forks_repo_name": "jjzhang166/videopp", "max_forks_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 25.4438502674, "max_line_length": 95, "alphanum_fraction": 0.5393022278, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5816202206904783}}
{"text": "#include <math.h>\n#include <EigenUnsupported/Eigen/KroneckerProduct>\n#include \"Core/Utilities/QProgInfo/QCircuitInfo.h\"\n#include \"Core/Utilities/Tools/MatrixDecomposition.h\"\n#include <chrono>\n#include \"Core/Utilities/QProgInfo/Visualization/QVisualization.h\"\n#include \"QAlg/Base_QCircuit/AmplitudeEncode.h\"\n\n\nUSING_QPANDA\nusing namespace std;\nusing namespace chrono;\n\n#define PRINT_TRACE 0\n#if PRINT_TRACE\n#define PTrace printf\n#define PTraceMat(mat) (std::cout << (mat) << endl)\n#define PTraceCircuit(cir) (std::cout << cir << endl)\n#else\n#define PTrace\n#define PTraceMat(mat)\n#define PTraceCircuit(cir)\n#endif\n\n#define MAX_MATRIX_PRECISION 1e-10\n\nusing MatrixSequence = std::vector<MatrixUnit>;\nusing DecomposeEntry = std::pair<int, MatrixSequence>;\n\nusing ColumnOperator = std::vector<DecomposeEntry>;\nusing MatrixOperator = std::vector<ColumnOperator>;\n\nusing SingleGateUnit = std::pair<MatrixSequence, QStat>;\n\nstatic void upper_partition(int order, MatrixOperator& entries)\n{\n\tauto index = (int)std::log2(entries.size() + 1) - (int)std::log2(order) - 1;\n\n\tfor (auto cdx = 0; cdx < order - 1; ++cdx)\n\t{\n\t\tfor (auto rdx = 0; rdx < order - cdx - 1; ++rdx)\n\t\t{\n\t\t\tauto entry = entries[cdx][rdx];\n\n\t\t\tentry.first += order;\n\t\t\tentry.second[index] = MatrixUnit::SINGLE_P1;\n\n\t\t\tentries[cdx + order].emplace_back(entry);\n\t\t}\n\t}\n\n\treturn;\n}\n\n\nstatic bool entry_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint lj = ((cdx - 1) >> (udx - 1)) & 1;\n\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if 1 ≤ j ≤ m and cj = lj' = 1 , return true\n\tauto mat = units[units.size() - udx];\n\treturn udx >= 1\n\t\t&& udx <= M\n\t\t&& lj\n\t\t&& mat == MatrixUnit::SINGLE_P1;\n}\n\nstatic bool steps_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if j = n and none of cn...cm+1 is 1 , return true\n\tif (units.size() != udx)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto iter = std::find(units.begin(), units.end() - M, MatrixUnit::SINGLE_P1);\n\t\treturn (units.end() - M) == iter;\n\t}\n}\n\nstatic void under_partition(int order, MatrixOperator& entries)\n{\n\tauto qubits = (int)std::log2(entries.size() + 1);\n\n\tfor (auto cdx = 1; cdx < order; ++cdx)\n\t{\n\t\tif (cdx & 1)\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto value = entries[0][rdx + order - 1].first ^ cdx;\n\t\t\t\tauto entry = make_pair(value, entries[cdx - 1][rdx + order - cdx].second);\n\n\t\t\t\tentries[cdx].emplace_back(entry);\n\t\t\t}\n\n\t\t\tauto& units = entries[cdx].back().second;\n\t\t\tfor (auto idx = 0; idx < (int)std::log2(order); ++idx)\n\t\t\t{\n\t\t\t\tunits[qubits - idx - 1] = ((cdx >> idx) & 1) ?\n\t\t\t\t\tMatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto range = (int)std::log2(order) + 1;\n\t\t\t\tauto refer = entries[0][rdx + order - 1].second;\n\t\t\t\tauto entry = entries[0][rdx + order - 1].first ^ cdx;\n\n\t\t\t\tMatrixSequence units(refer.begin() + qubits - range, refer.end());\n\n\t\t\t\tfor (auto udx = 1; udx <= range; ++udx)  /*udx = j , cdx = L*/\n\t\t\t\t{\n\t\t\t\t\tbool steps_accord = steps_requirement(units, udx, cdx + 1);\n\t\t\t\t\tbool entry_accord = entry_requirement(units, udx, cdx + 1);\n\n\t\t\t\t\tunits[range - udx] = steps_accord ? MatrixUnit::SINGLE_P1 :\n\t\t\t\t\t\tentry_accord ? MatrixUnit::SINGLE_P0 : units[range - udx];\n\t\t\t\t}\n\n\t\t\t\tfor (auto idx = 0; idx < qubits - range; ++idx)\n\t\t\t\t{\n\t\t\t\t\tunits.insert(units.begin(), MatrixUnit::SINGLE_I2);\n\t\t\t\t}\n\n\t\t\t\tentries[cdx].emplace_back(make_pair(entry, units));\n\t\t\t}\n\n\t\t\tauto refer_opt = entries[0][2 * order - 2].second;\n\t\t\tfor (auto idx = 0; idx < qubits; ++idx)\n\t\t\t{\n\t\t\t\tif ((cdx >> idx) & 1)\n\t\t\t\t{\n\t\t\t\t\trefer_opt[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentries[cdx].back().second = refer_opt;\n\t\t}\n\t}\n\n\treturn;\n}\n\nstatic void controller(MatrixSequence& sequence, const EigenMatrix2c U2, EigenMatrixXc& matrix)\n{\n\tEigenMatrix2c P0;\n\tEigenMatrix2c P1;\n\tEigenMatrix2c I2;\n\n\tP0 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\tEigen::dcomplex(0, 0), Eigen::dcomplex(0, 0);\n\tP1 << Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0),\n\t\tEigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\tI2 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\tEigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\n\tstd::map<MatrixUnit, std::function<EigenMatrix2c()>> mapping =\n\t{\n\t\t{ MatrixUnit::SINGLE_P0, [&]() {return P0; } },\n\t\t{ MatrixUnit::SINGLE_P1, [&]() {return P1; } },\n\t\t{ MatrixUnit::SINGLE_I2, [&]() {return I2; } },\n\t\t{ MatrixUnit::SINGLE_V2, [&]() {return U2 - I2; } }\n\t};\n\n\tauto order = sequence.size();\n\tEigenMatrixXc Un = EigenMatrixXc::Identity(1, 1);\n\tEigenMatrixXc In = EigenMatrixXc::Identity(1ull << order, 1ull << order);\n\n\tfor (const auto& val : sequence)\n\t{\n\t\tEigenMatrix2c M2 = mapping.find(val)->second();\n\t\tUn = Eigen::kroneckerProduct(Un, M2).eval();\n\t}\n\n\tmatrix = In + Un;\n\treturn;\n}\n\nstatic void recursive_partition(const EigenMatrixXc& sub_matrix, MatrixOperator& entries)\n{\n\tEigen::Index order = sub_matrix.rows();\n\tif (1 == order)\n\t{\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tEigenMatrixXc corner = sub_matrix.topLeftCorner(order / 2, order / 2);\n\n\t\trecursive_partition(corner, entries);\n\n\t\tupper_partition(order / 2, entries);\n\t\tunder_partition(order / 2, entries);\n\t}\n\n\treturn;\n}\n\nstatic void decomposition(EigenMatrixXc& matrix, MatrixOperator& entries, std::vector<SingleGateUnit>& cir_units)\n{\n\tfor (auto cdx = 0; cdx < entries.size(); ++cdx)\n\t{\n\t\tauto opts = entries[cdx].size();\n\t\tfor (auto idx = 0; idx < opts; ++idx)\n\t\t{\n\t\t\tauto rdx = entries[cdx][idx].first;\n\t\t\tauto opt = entries[cdx][idx].second;\n\n\t\t\tif ((EigenComplexT(0, 0) == matrix(rdx, cdx) && (idx != opts - 1)) ||\n\t\t\t\t(EigenComplexT(1, 0) == matrix(cdx, cdx) && (idx == opts - 1)))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEigenMatrix2c C2; /*placeholder*/\n\t\t\t\tC2 << EigenComplexT(0, 1), EigenComplexT(0, 1),\n\t\t\t\t\tEigenComplexT(0, 1), EigenComplexT(0, 1);\n\n\t\t\t\tEigenMatrixXc Cn;\n\t\t\t\tcontroller(opt, C2, Cn);\n\n\t\t\t\tQnum indices(2);\n\t\t\t\tfor (Eigen::Index index = 0; index < (1ull << opt.size()); ++index)\n\t\t\t\t{\n\t\t\t\t\tif (Cn(rdx, index) != EigenComplexT(0, 0))\n\t\t\t\t\t{\n\t\t\t\t\t\tindices[index == rdx] = index;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tEigenComplexT C0 = matrix(indices[0], cdx);  /*The entry to be eliminated */\n\t\t\t\tEigenComplexT C1 = matrix(indices[1], cdx);  /*The corresponding entry */\n\n\t\t\t\tEigenComplexT V11, V12, V21, V22;\n\n\t\t\t\tif (indices[0] < indices[1])\n\t\t\t\t{\n\t\t\t\t\tV11 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tV11 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\n\t\t\t\tEigenMatrix2c V2;\n\t\t\t\tV2 << V11, V12, V21, V22;\n\n\t\t\t\tEigenMatrixXc Un;\n\t\t\t\tcontroller(opt, V2, Un);\n\n\t\t\t\tmatrix = Un * matrix;\n\n\t\t\t\tQStat M2 = { (qcomplex_t)V11 ,(qcomplex_t)V12 ,(qcomplex_t)V21 ,(qcomplex_t)V22 };\n\t\t\t\tcir_units.insert(cir_units.begin(), std::make_pair(opt, M2));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigenMatrix2c V2 = matrix.bottomRightCorner(2, 2);\n\tif (EigenMatrixXc::Identity(2, 2) != V2)\n\t{\n\t\tQPANDA_ASSERT((V2(0, 0) * V2(1, 1)) == (V2(0, 1) * V2(1, 0)), \"decomposition error on matrix.bottomRightCorner(2, 2)\");\n\n\t\tqcomplex_t E0 = V2(1, 1) / ((V2(0, 0) * V2(1, 1)) - (V2(0, 1) * V2(1, 0)));\n\t\tqcomplex_t E1 = V2(0, 1) / ((V2(0, 1) * V2(1, 0)) - (V2(0, 0) * V2(1, 1)));\n\t\tqcomplex_t E2 = V2(1, 0) / ((V2(0, 1) * V2(1, 0)) - (V2(0, 0) * V2(1, 1)));\n\t\tqcomplex_t E3 = V2(0, 0) / ((V2(0, 0) * V2(1, 1)) - (V2(0, 1) * V2(1, 0)));\n\n\t\tQStat M2 = { E0 ,E1 ,E2 ,E3 };\n\n\t\tauto entry = entries.back().back().second;\n\t\tcir_units.insert(cir_units.begin(), std::make_pair(entry, M2));\n\t}\n}\n\nstatic void initialize(EigenMatrixXc& matrix, MatrixOperator& entries)\n{\n\tauto qubits = (int)std::log2(matrix.rows());\n\n\tMatrixSequence Cns(qubits, MatrixUnit::SINGLE_I2);\n\tCns.back() = MatrixUnit::SINGLE_V2;\n\tentries.front().emplace_back(make_pair(1, Cns));\n\n\tColumnOperator& column = entries.front();\n\tfor (auto idx = 1; idx < qubits; ++idx)\n\t{\n\t\tsize_t path = 1ull << idx;\n\t\tfor (auto opt = 0; opt < (1 << idx) - 1; ++opt)\n\t\t{\n\t\t\tauto entry = column[opt].first;\n\t\t\tauto units = column[opt].second;\n\n\t\t\t// 1 : none of cn−1, . . . , c1 equals 1\n\t\t\t// * : otherwise\n\t\t\tauto iter = std::find(units.end() - idx, units.end(), MatrixUnit::SINGLE_P1);\n\n\t\t\tunits[units.size() - 1 - idx] = (units.end() == iter) ?\n\t\t\t\tMatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\n\t\t\tcolumn.emplace_back(make_pair(entry + path, units));\n\t\t}\n\n\t\tMatrixSequence Lns(qubits, MatrixUnit::SINGLE_I2);\n\t\tLns[qubits - idx - 1] = MatrixUnit::SINGLE_V2;\n\n\t\tcolumn.emplace_back(make_pair((1ull << idx), Lns));\n\t}\n\n\treturn;\n}\n\nstatic void general_scheme(EigenMatrixXc& matrix, std::vector<SingleGateUnit>& cir_units)\n{\n\tMatrixOperator entries;\n\tfor (auto idx = 1; idx < matrix.cols(); ++idx)\n\t{\n\t\tColumnOperator Co;\n\t\tentries.emplace_back(Co);\n\t}\n\n\tinitialize(matrix, entries);\n\trecursive_partition(matrix, entries);\n\tdecomposition(matrix, entries, cir_units);\n\n\treturn;\n}\n\nstatic void circuit_insert(QVec& qubits, std::vector<SingleGateUnit>& cir_units, QCircuit& circuit, bool b_positive_seq)\n{\n\tif (b_positive_seq)\n\t{\n\t\tstd::sort(qubits.begin(), qubits.end(), [&](Qubit* a, Qubit* b) {\n\t\t\treturn a->getPhysicalQubitPtr()->getQubitAddr()\n\t\t\t\t< b->getPhysicalQubitPtr()->getQubitAddr();\n\t\t\t});\n\t}\n\telse\n\t{\n\t\tstd::sort(qubits.begin(), qubits.end(), [&](Qubit* a, Qubit* b) {\n\t\t\treturn a->getPhysicalQubitPtr()->getQubitAddr()\n\t\t\t\t> b->getPhysicalQubitPtr()->getQubitAddr();\n\t\t\t});\n\t}\n\n\tauto rank = qubits.size();\n\tfor (auto& val : cir_units)\n\t{\n\t\tQVec control;\n\t\tQCircuit cir;\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_P0 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcir << X(qubits[qdx]);\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse if (MatrixUnit::SINGLE_P1 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t}\n\t\t}\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_V2 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcircuit << cir\n\t\t\t\t\t<< U4(val.second, qubits[qdx]).control(control).dagger()\n\t\t\t\t\t<< cir;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*******************************************************************\n*                      class DiagonalMatrixDecompose\n********************************************************************/\nclass DiagonalMatrixDecompose\n{\npublic:\n\tDiagonalMatrixDecompose() {}\n\t~DiagonalMatrixDecompose() {}\n\n\n\tQCircuit decompose(const QVec& qubits, const QStat& src_mat)\n\t{\n\t\t//check param\n\t\tif (!is_unitary_matrix(src_mat))\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, the input matrix is not a unitary-matrix.\");\n\t\t}\n\n\t\tconst auto mat_dimension = sqrt(src_mat.size());\n\t\tconst auto need_qubits_num = ceil(log2(mat_dimension));\n\t\tif (need_qubits_num > qubits.size())\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, no enough qubits.\");\n\t\t}\n\n\t\tQCircuit decompose_result_cir;\n\t\tm_qubits = qubits;\n\n\t\tQVec controlqvec = qubits;\n\t\tcontrolqvec.pop_back();\n\t\tQStat tmp_mat22; //2*2 unitary matrix\n\t\tconst size_t tmp_base_unitary_cnt = mat_dimension / 2;\n\t\tlong pre_index = -1;\n\t\tfor (size_t i = 0; i < tmp_base_unitary_cnt; ++i)\n\t\t{\n\t\t\tif (0 == i)\n\t\t\t{\n\t\t\t\tQCircuit index_cir_zero = index_to_circuit(0, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir_zero;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQCircuit index_cir = index_to_merge_circuit(i, pre_index, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir;\n\t\t\t}\n\n\t\t\ttmp_mat22.clear();\n\t\t\tconst size_t tmp_row = (2 * i * mat_dimension) + (2 * i);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + 1]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension + 1]);\n\t\t\tQGate tmp_u4 = U4(tmp_mat22, qubits.back()).control(controlqvec);\n\t\t\tQGATE_SPACE::U4* p_gate = dynamic_cast<QGATE_SPACE::U4*>(tmp_u4.getQGate());\n\t\t\tif ((abs(p_gate->getAlpha()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getBeta()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getGamma()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getDelta()) > MAX_MATRIX_PRECISION))\n\t\t\t{\n\t\t\t\tdecompose_result_cir << tmp_u4;\n\t\t\t}\n\n\t\t\tpre_index = i;\n\t\t}\n\n\t\treturn decompose_result_cir;\n\t}\n\nprotected:\n\tQCircuit index_to_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif (0 == index % 2)\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t pre_index = index - 1;\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t\tpre_index /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, long pre_index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t tmp_pre_index = pre_index;\n\t\tif (pre_index < 0)\n\t\t{\n\t\t\ttmp_pre_index = 1;\n\t\t}\n\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (tmp_pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\n\t\t\tif (pre_index > 0)\n\t\t\t{\n\t\t\t\ttmp_pre_index /= 2;\n\t\t\t}\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\nprivate:\n\tQVec m_qubits;\n};\n\n\n/*******************************************************************\n*                      public interface\n********************************************************************/\nQCircuit QPanda::matrix_decompose_qr(QVec qubits, const QStat& src_mat, const bool b_positive_seq)\n{\n\tauto order = std::sqrt(src_mat.size());\n\tEigenMatrixXc tmp_mat = EigenMatrixXc::Map(&src_mat[0], order, order);\n\n\treturn matrix_decompose_qr(qubits, tmp_mat, b_positive_seq);\n}\n\nQCircuit QPanda::matrix_decompose_qr(QVec qubits, EigenMatrixXc& src_mat, const bool b_positive_seq)\n{\n\tif (!src_mat.isUnitary(MAX_MATRIX_PRECISION))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"Non-unitary matrix.\");\n\t}\n\n\tif (qubits.size() != log2(src_mat.cols()))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"The qubits number is error or the input matrix is not a 2^n-dimensional matrix.\");\n\t}\n\n\tQCircuit output_circuit;\n\t//QR decompose\n\tstd::vector<SingleGateUnit> cir_units;\n\tgeneral_scheme(src_mat, cir_units);\n\tcircuit_insert(qubits, cir_units, output_circuit, b_positive_seq);\n\n\treturn output_circuit;\n}\n\nQCircuit QPanda::diagonal_matrix_decompose(const QVec& qubits, const QStat& src_mat)\n{\n\treturn DiagonalMatrixDecompose().decompose(qubits, src_mat);\n}\n\n\n/*******************************************************************\n*                    puali-XYZ  decomposition\n********************************************************************/\n\nMatrixToPauli::MatrixToPauli(QuantumMachine* qvm)\n{\n\tm_qvm = qvm;\n}\n\nMatrixToPauli::~MatrixToPauli()\n{\n\t//destroyQuantumMachine(m_qvm);\n}\n\n\nvoid MatrixToPauli::matrixDecompositionNew(QMatrix<double>& qmat)\n{\n\tint size = qmat.size;\n\tint numbits = ceil(log2(size));\n\tauto a = qAllocMany(numbits);\n\tunsigned short index;\n\tfor (int i = 0; i < size - 1; i++) {\n\t\tfor (int j = i + 1; j < size; j++) {\n\t\t\tif (qmat(i, j) != 0 && qmat(j, i) != 0) {\n\t\t\t\tindex = 1;\n\t\t\t}\n\t\t\telse if (qmat(i, j) != 0 && qmat(j, i) == 0) {\n\t\t\t\tindex = 2;\n\t\t\t}\n\t\t\telse if (qmat(i, j) == 0 && qmat(j, i) != 0) {\n\t\t\t\tindex = 3;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tindex = 10;\n\t\t\t}\n\t\t\tmatrixDecompositionSub(qmat.data, i, j, index, numbits, a);\n\t\t}\n\t}\n\tadd2CirAndCoeII(qmat.data, a);\n}\n\n\nstd::vector<int> MatrixToPauli::ASCII2BIN(int a)\n{\n\tint d = a;\n\tvector<int> binary;\n\tif (d == 0)\n\t{\n\t\tbinary.push_back(0);\n\t}\n\telse\n\t{\n\t\twhile (d != 0)\n\t\t{\n\t\t\tbinary.push_back(d % 2);\n\t\t\td /= 2;\n\t\t}\n\t}\n\treturn binary;\n}\n\nvoid MatrixToPauli::add2CirAndCoeIJ(std::vector<double>& mat, int i, int j, const QVec& a)\n{\n\tauto BinIndex = convert2FullBinaryIndex(a.size(), i, j);\n\tauto pauliCircuitIJ = convert2PauliOperator(BinIndex.first, BinIndex.second, a);\n\tauto pauliCircuitJI = convert2PauliOperator(BinIndex.second, BinIndex.first, a);\n\tauto signIJ = pauliCircuitIJ.second;\n\tauto signJI = pauliCircuitJI.second;\n\tint num = signIJ.size();\n\tvector<double> Mcoe(num);\n\tint size = 1 << a.size();\n\tfor (int K = 0; K < num; K++)\n\t{\n\t\tMcoe[K] = mat[i * size + j] * signIJ[K] + mat[j * size + i] * signJI[K];\n\t}\n\taddCoeAndCirAtMij(1, pauliCircuitIJ.first, Mcoe);\n}\n\n\nvoid MatrixToPauli::matrixDecompositionSub(std::vector<double>& mat,\n\tint i,\n\tint j,\n\tunsigned short index,\n\tint numbits,\n\tconst QVec& a)\n{\n\tswitch (index)\n\t{\n\tcase 1:\n\t\tadd2CirAndCoeIJ(mat, i, j, a);\n\t\tbreak;\n\tcase 2:\n\t\tadd2CirAndCoeIorJ(mat, i, j, a);\n\t\tbreak;\n\tcase 3:\n\t\tadd2CirAndCoeIorJ(mat, j, i, a);\n\t\tbreak;\n\tcase 10:\n\t\tbreak;\n\t}\n}\n\n\nvoid MatrixToPauli::add2CirAndCoeIorJ(std::vector<double>& mat, int i, int j, const QVec& a)\n{\n\tauto BinIndex = convert2FullBinaryIndex(a.size(), i, j);\n\tauto pauliCircuitIJ = convert2PauliOperator(BinIndex.first, BinIndex.second, a);\n\tint size = 1 << a.size();\n\taddCoeAndCirAtMij(mat[i * size + j], pauliCircuitIJ.first, pauliCircuitIJ.second);\n}\n\n\nvoid MatrixToPauli::add2CirAndCoeII(std::vector<double>& mat, const QVec& a)\n{\n\tvector<vector<int>> signs;\n\tvector<QCircuit> PauliCirDiag;\n\tint size = 1 << a.size();\n\tauto BinIndex = convert2FullBinaryIndex(a.size(), 0, 0);\n\tauto pauliCircuitII = convert2PauliOperator(BinIndex.first, BinIndex.second, a);\n\tPauliCirDiag = pauliCircuitII.first;\n\tsigns.push_back(pauliCircuitII.second);\n\tfor (int i = 1; i < size; i++)\n\t{\n\t\tauto BinIndex = convert2FullBinaryIndex(a.size(), i, i);\n\t\tauto pauliCoefficient = convert2Coefficient(BinIndex.first, BinIndex.second);\n\t\tsigns.push_back(pauliCoefficient);\n\t}\n\tvector<double> Mcoe(signs.size());\n\tfor (int j = 0; j < signs.size(); j++)\n\t{\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < size; i++)\n\t\t{\n\t\t\tsum = mat[i * size + i] * signs[i][j] + sum;\n\t\t}\n\t\tMcoe[j] = sum;\n\t}\n\taddCoeAndCirAtMij(1, pauliCircuitII.first, Mcoe);\n}\n\n\nstd::pair<std::vector<QCircuit>, std::vector<int>> MatrixToPauli::convert2PauliOperator\n                                        (const std::vector<int>& i_s,\n\t                                     const std::vector<int>& j_s,\n\t                                     const QVec& a)\n{\n\tint num = i_s.size();\n\tstd::vector<QCircuit> Pauli_i(num);\n\tstd::vector<QCircuit> Pauli_j(num);\n\tstd::vector<QCircuit> Pauli((1 << num));\n\tstd::vector<int> sign;\n\tstd::vector<int> signFull((1 << num));\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tif (i_s[i] == 0 && j_s[i] == 0)\n\t\t{\n\t\t\tPauli_i[i] << I(a[num - i - 1]);\n\t\t\tPauli_j[i] << Z(a[num - i - 1]);\n\t\t\tsign.push_back(1);\n\t\t}\n\t\tif (i_s[i] == 1 && j_s[i] == 1)\n\t\t{\n\t\t\tPauli_i[i] << I(a[num - i - 1]);\n\t\t\tPauli_j[i] << Z(a[num - i - 1]);\n\t\t\tsign.push_back(-1);\n\t\t}\n\t\tif (i_s[i] == 0 && j_s[i] == 1)\n\t\t{\n\t\t\tPauli_i[i] << X(a[num - i - 1]);\n\t\t\tPauli_j[i] << Z(a[num - i - 1]);\n\t\t\tPauli_j[i] << X(a[num - i - 1]);\n\t\t\tsign.push_back(1);\n\t\t}\n\t\tif (i_s[i] == 1 && j_s[i] == 0) {\n\t\t\tPauli_i[i] << X(a[num - i - 1]);\n\t\t\tPauli_j[i] << Z(a[num - i - 1]);\n\t\t\tPauli_j[i] << X(a[num - i - 1]);\n\t\t\tsign.push_back(-1);\n\t\t}\n\t}\n\tfor (int i = 1; i < ((1 << num) + 1); i++)\n\t{\n\t\tint k = i;\n\t\tint count = 0;\n\t\tsignFull[i - 1] = 1;\n\t\twhile (count < num) {\n\t\t\tif (k <= (1 << (num - count - 1)))\n\t\t\t{\n\t\t\t\tPauli[i - 1] << Pauli_i[count];\n\t\t\t\tsignFull[i - 1] = signFull[i - 1] * 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPauli[i - 1] << Pauli_j[count];\n\t\t\t\tk = k - (1 << (num - count - 1));\n\t\t\t\tsignFull[i - 1] = signFull[i - 1] * sign[count];\n\t\t\t}\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn make_pair(Pauli, signFull);\n}\n\n\nstd::vector<int> MatrixToPauli::convert2Coefficient(const std::vector<int>& i_s,\n\t                                                const std::vector<int>& j_s)\n{\n\tint num = i_s.size();\n\tvector<int> sign;\n\tvector<int> signFull((1 << num));\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tif (i_s[i] == 0 && j_s[i] == 0)\n\t\t{\n\t\t\tsign.push_back(1);\n\t\t}\n\t\tif (i_s[i] == 1 && j_s[i] == 1)\n\t\t{\n\t\t\tsign.push_back(-1);\n\t\t}\n\t\tif (i_s[i] == 0 && j_s[i] == 1)\n\t\t{\n\t\t\tsign.push_back(1);\n\t\t}\n\t\tif (i_s[i] == 1 && j_s[i] == 0)\n\t\t{\n\t\t\tsign.push_back(-1);\n\t\t}\n\t}\n\tfor (int i = 1; i < ((1 << num) + 1); i++)\n\t{\n\t\tint k = i;\n\t\tint count = 0;\n\t\tsignFull[i - 1] = 1;\n\t\twhile (count < num) {\n\t\t\tif (k <= (1 << num - count - 1))\n\t\t\t{\n\t\t\t\tsignFull[i - 1] = signFull[i - 1] * 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tk = k - (1 << num - count - 1);\n\t\t\t\tsignFull[i - 1] = signFull[i - 1] * sign[count];\n\t\t\t}\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn signFull;\n}\n\n\ntemplate <typename V>\nvoid MatrixToPauli::addCoeAndCirAtMij(double ma, const std::vector<QCircuit>& cir, V& sign)\n{\n\tint num = sign.size();\n\tfor (int i = 0; i < num; i++)\n\t{\n\t\tif (ma * sign[i] != 0)\n\t\t{\n\t\t\tm_QMcoe.push_back(ma * sign[i] / num);\n\t\t\tm_QMcir.push_back(cir[i]);\n\t\t}\n\t}\n}\n\n\nstd::pair<std::vector<int>, std::vector<int>> MatrixToPauli::convert2FullBinaryIndex(int numbits,\n\tunsigned long i,\n\tunsigned long j)\n{\n\tauto rowi = ASCII2BIN(i);\n\tauto colj = ASCII2BIN(j);\n\tif (rowi.size() < numbits)\n\t{\n\t\tfor (int k = rowi.size(); k < numbits; ++k)\n\t\t\trowi.push_back(0);\n\t}\n\tif (colj.size() < numbits)\n\t{\n\t\tfor (int k = colj.size(); k < numbits; ++k)\n\t\t\tcolj.push_back(0);\n\t}\n\treverse(rowi.begin(), rowi.end());\n\treverse(colj.begin(), colj.end());\n\treturn make_pair(rowi, colj);\n}\n\nvoid MatrixToPauli::combine_same_circuit()\n{\n\tint size = m_QMcir.size();\n\tint num = ceil(log2(size));\n\tstd::vector<int> repeatedindex;\n\tfor (int i = 0; i < size; i++)\n\t{\n\t\tif (!matchIndex(i, repeatedindex))\n\t\t{\n\t\t\tstd::vector<int> index;\n\t\t\tfor (int j = i + 1; j < size; j++)\n\t\t\t{\n\t\t\t\tif (matchTwoCircuit(m_QMcir[i], m_QMcir[j]))\n\t\t\t\t{\n\t\t\t\t\tindex.push_back(j);\n\t\t\t\t\trepeatedindex.push_back(j);\n\t\t\t\t}\n\t\t\t}\n\t\t\taddtoSimplyCircuit(i, index, num);\n\t\t\tindex.clear();\n\t\t}\n\t}\n}\n\nbool MatrixToPauli::matchIndex(int k, const std::vector<int>& repeatedindex)\n{\n\tint size = repeatedindex.size();\n\tbool matched = false;\n\tif (size == 0)\n\t{\n\t\tmatched = false;\n\t}\n\telse\n\t{\n\t\tfor (int i = 0; i < size; i++)\n\t\t{\n\t\t\tif (k == repeatedindex[i])\n\t\t\t{\n\t\t\t\tmatched = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn matched;\n}\n\nbool MatrixToPauli::matchTwoCircuit(const QCircuit& a, const QCircuit& b, bool criteria_matrix_circuit)\n{\n\tbool matched = false;\n\tif (!criteria_matrix_circuit)\n\t{\n\t\tQuantumMachine* mach = initQuantumMachine(CPU);\n\t\tauto prog_a = createEmptyQProg();\n\t\tauto prog_b = createEmptyQProg();\n\t\tprog_a << a;\n\t\tprog_b << b;\n\t\tauto instrcution_a = transformQProgToOriginIR(prog_a, mach);\n\t\tauto instrcution_b = transformQProgToOriginIR(prog_b, mach);\n\t\tif (instrcution_a == instrcution_b)\n\t\t{\n\t\t\tmatched = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmatched = false;\n\t\t}\n\t}\n\tif (criteria_matrix_circuit)\n\t{\n\t\tQuantumMachine* mach = initQuantumMachine(CPU);\n\t\tauto prog_a = createEmptyQProg();\n\t\tauto prog_b = createEmptyQProg();\n\t\tprog_a << a;\n\t\tprog_b << b;\n\t\tQStat cir_a = getCircuitMatrix(prog_a);\n\t\tQStat cir_b = getCircuitMatrix(prog_b);\n\t\tif (QStat_to_Eigen(cir_a).isApprox(QStat_to_Eigen(cir_b)))\n\t\t{\n\t\t\tmatched = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmatched = false;\n\t\t}\n\t}\n\treturn matched;\n}\n\nvoid MatrixToPauli::addtoSimplyCircuit(int i, const std::vector<int>& index, int num)\n{\n\tbool is_zero = false;\n\tif (index.size() > 0)\n\t{\n\t\tdouble sum = 0;\n\t\tfor (int k = 0; k < index.size(); k++)\n\t\t{\n\t\t\tsum += m_QMcoe[index[k]];\n\t\t}\n\t\tif (sum + m_QMcoe[i] == 0)\n\t\t{\n\t\t\tis_zero = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_QMcoeMerged.push_back(sum + m_QMcoe[i]);\n\t\t}\n\t}\n\telse\n\t{\n\t\tm_QMcoeMerged.push_back(m_QMcoe[i]);\n\t}\n\tif (!is_zero)\n\t{\n\t\tm_QMcirMerged.push_back(m_QMcir[i]);\n\t}\n}\n\n\nvoid QPanda::matrix_decompose_pualis(QuantumMachine* qvm, const EigenMatrixX& mat, PualiOperatorLinearCombination& linearcom)\n{\n\tif (mat.size() == 0 ||\n\t\t(mat.rows() != mat.cols()) ||\n\t\t(mat.rows() & (mat.rows() - 1)) != 0\n\t\t)\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"The input matrix is not a 2^n-dimensional square matrix!\");\n\t}\n\tvector<double> val(mat.data(), mat.data() + mat.size());\n\tQMatrix<double> ass(mat.rows(), val);\n\tass.initialQMatrix();\n\tMatrixToPauli Vqe_alg(qvm);\n\tVqe_alg.matrixDecompositionNew(ass);\n\tVqe_alg.combine_same_circuit();\n\tstd::vector<double> coe = Vqe_alg.getQMcoe();\n\tstd::vector<QCircuit> cir = Vqe_alg.getQMcir();\n\tfor (int i = 0; i < coe.size(); i++)\n\t{\n\t\tlinearcom.push_back(make_pair(coe[i], cir[i]));\n\t}\n}\n\n", "meta": {"hexsha": "03667e594b79a4cd58177c14fe61f6ac0991e2f0", "size": 24740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_stars_repo_name": "QianJianhua1/QPanda-2", "max_stars_repo_head_hexsha": "a13c7b733031b1d0007dceaf1dae6ad447bb969c", "max_stars_repo_licenses": ["Apache-2.0"], "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/Utilities/Tools/MatrixDecomposition.cpp", "max_issues_repo_name": "QianJianhua1/QPanda-2", "max_issues_repo_head_hexsha": "a13c7b733031b1d0007dceaf1dae6ad447bb969c", "max_issues_repo_licenses": ["Apache-2.0"], "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/Utilities/Tools/MatrixDecomposition.cpp", "max_forks_repo_name": "QianJianhua1/QPanda-2", "max_forks_repo_head_hexsha": "a13c7b733031b1d0007dceaf1dae6ad447bb969c", "max_forks_repo_licenses": ["Apache-2.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.2549019608, "max_line_length": 126, "alphanum_fraction": 0.6113581245, "num_tokens": 8475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846387, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5816202134565752}}
{"text": "/*\n * L2H1.cpp\n *\n *  Created on: 28.05.2019\n *      Author: thies\n */\n\n#include <deal.II/numerics/vector_tools.h>\n#include <norms/L2H1.h>\n\nusing namespace dealii;\n\nnamespace wavepi {\nnamespace norms {\n\ntemplate <int dim>\ndouble L2H1<dim>::absolute_error(const DiscretizedFunction<dim>& u, Function<dim>& v) {\n  auto mesh     = u.get_mesh();\n  double result = 0;\n\n  // trapezoidal rule in time:\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Vector<double> cellwise_error;\n\n    v.set_time(mesh->get_time(i));\n    VectorTools::integrate_difference(*mesh->get_dof_handler(i), u[i], v, cellwise_error, QGauss<dim>(5),\n                                      VectorTools::NormType::H1_norm);\n\n    double nrm =\n        VectorTools::compute_global_error(*mesh->get_triangulation(i), cellwise_error, VectorTools::NormType::H1_norm);\n\n    if (i > 0) result += nrm * nrm / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += nrm * nrm / 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 L2H1<dim>::norm(const DiscretizedFunction<dim>& u) const {\n  auto mesh     = u.get_mesh();\n  double result = 0;\n\n  // trapezoidal rule in time:\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double nrm2 =\n        mesh->get_mass_matrix(i)->matrix_norm_square(u[i]) + mesh->get_laplace_matrix(i)->matrix_norm_square(u[i]);\n\n    if (i > 0) result += nrm2 / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += nrm2 / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  // assume that function is linear in time (consistent with crank-nicolson!)\n  // and integrate that exactly (Simpson rule)\n  // problem when mesh changes in time!\n  //   for (size_t i = 0; i < mesh->length(); i++) {\n  //      double nrm2 = mesh->get_mass_matrix(i)->matrix_norm_square(function_coefficients[i]);\n  //\n  //      if (i > 0)\n  //         result += nrm2 / 3 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n  //\n  //      if (i < mesh->length() - 1)\n  //         result += nrm2 / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n  //\n  //   for (size_t i = 0; i < mesh->length() - 1; i++) {\n  //      double tmp = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            function_coefficients[i + 1]);\n  //\n  //      result += tmp / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n\n  return std::sqrt(result);\n}\n\ntemplate <int dim>\ndouble L2H1<dim>::dot(const DiscretizedFunction<dim>& u, const DiscretizedFunction<dim>& v) const {\n  auto mesh     = u.get_mesh();\n  double result = 0.0;\n\n  // trapezoidal rule in time:\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                  mesh->get_laplace_matrix(i)->matrix_scalar_product(u[i], v[i]);\n\n    if (i > 0) result += doti / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += doti / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  // assume that both functions are linear in time (consistent with crank-nicolson!)\n  // and integrate that exactly (Simpson rule)\n  // problem when mesh changes in time!\n  //   for (size_t i = 0; i < mesh->length(); i++) {\n  //      Assert(function_coefficients[i].size() == V.function_coefficients[i].size(),\n  //            ExcDimensionMismatch (function_coefficients[i].size() , V.function_coefficients[i].size()));\n  //\n  //      double doti = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            V.function_coefficients[i]);\n  //\n  //      if (i > 0)\n  //         result += doti / 3 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n  //\n  //      if (i < mesh->length() - 1)\n  //         result += doti / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n  //\n  //   for (size_t i = 0; i < mesh->length() - 1; i++) {\n  //      Assert(function_coefficients[i].size() == V.function_coefficients[i+1].size(),\n  //            ExcDimensionMismatch (function_coefficients[i].size() , V.function_coefficients[i+1].size()));\n  //      Assert(function_coefficients[i+1].size() == V.function_coefficients[i].size(),\n  //             ExcDimensionMismatch (function_coefficients[i+1].size() , V.function_coefficients[i].size()));\n  //\n  //      double dot1 = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            V.function_coefficients[i + 1]);\n  //      double dot2 = mesh->get_mass_matrix(i + 1)->matrix_scalar_product(function_coefficients[i + 1],\n  //            V.function_coefficients[i]);\n  //\n  //      result += (dot1 + dot2) / 6 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n\n  return result;\n}\n\ntemplate <int dim>\nvoid L2H1<dim>::dot_transform(DiscretizedFunction<dim>& u) {\n  u.mult_mass();\n  dot_solve_mass_and_transform(u);\n}\n\ntemplate <int dim>\nvoid L2H1<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u) {\n  u.solve_mass();\n  dot_mult_mass_and_transform_inverse(u);\n}\n\ntemplate <int dim>\nvoid L2H1<dim>::dot_solve_mass_and_transform(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\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    u[i] *= factor;\n  }\n}\n\ntemplate <int dim>\nvoid L2H1<dim>::dot_mult_mass_and_transform_inverse(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\n  // trapezoidal rule in time:\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    u[i] /= factor;\n  }\n}\n\ntemplate <int dim>\nstd::string L2H1<dim>::name() const {\n  return \"L²([0,T], H¹(Ω))\";\n}\n\ntemplate <int dim>\nstd::string L2H1<dim>::unique_id() const {\n  return \"L²([0,T], H¹(Ω))\";\n}\n\ntemplate class L2H1<1>;\ntemplate class L2H1<2>;\ntemplate class L2H1<3>;\n\n} /* namespace norms */\n} /* namespace wavepi */\n", "meta": {"hexsha": "12340fcd029dd559ac50b965d1c197c29cc35a99", "size": 6324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/norms/L2H1.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/L2H1.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/L2H1.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": 34.9392265193, "max_line_length": 119, "alphanum_fraction": 0.6054712207, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5815254122641618}}
{"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_HBEVX_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HBEVX_HPP\n\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\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 banded Hermitian matrix.\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /*\n     * hbevx() computes the eigenvalues and optionally the associated\n     * eigenvectors of a banded Hermitian matrix A. A matrix is Hermitian\n     * when herm( A ) == A. When A is real, a Hermitian matrix is also\n     * called symmetric.\n     *\n     * The eigen decomposition is A = U S * herm(U)  where  U  is a\n     * unitary matrix and S is a diagonal matrix. The eigenvalues of A\n     * are on the main diagonal of S. The eigenvalues are real.\n     */\n\n    /*\n     * If uplo=='L' only the lower triangular part is stored.\n     * If uplo=='U' only the upper triangular part is stored.\n     *\n     * The matrix is assumed to be stored in LAPACK band format, i.e.\n     * matrices are stored columnwise, in a compressed format so that when e.g. uplo=='U'\n     * the (i,j) element with j>=i is in position  (i-j) + j * (KD+1) + KD  where KD is the\n     * half bandwidth of the matrix. For a triadiagonal matrix, KD=1, for a diagonal matrix\n     * KD=0.\n     * When uplo=='L', the (i,j) element with j>=i is in position  (i-j) + j * (KD+1).\n     *\n     * The matrix A is thus a rectangular matrix with KD+1 rows and N columns.\n     */\n\n    namespace detail {\n      inline\n      void hbevx (\n        char const jobz, char const range, char const uplo, integer_t const n, integer_t const kd,\n        float* ab, integer_t const ldab, float* q, integer_t const ldq,\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,\n        float* work, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_SSBEVX (\n          &jobz, &range, &uplo, &n, &kd, ab, &ldab, q, &ldq,\n          &vl, &vu, &il, &iu, &abstol, &m,\n          w, z, &ldz,\n          work, iwork, ifail, &info);\n      }\n\n      inline\n      void hbevx (\n        char const jobz, char const range, char const uplo, integer_t const n, integer_t const kd,\n        double* ab, integer_t const ldab, double* q, integer_t const ldq,\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,\n        double* work, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_DSBEVX (\n          &jobz, &range, &uplo, &n, &kd, ab, &ldab, q, &ldq,\n          &vl, &vu, &il, &iu, &abstol, &m,\n          w, z, &ldz,\n          work, iwork, ifail, &info);\n      }\n\n      inline\n      void hbevx (\n        char const jobz, char const range, char const uplo, integer_t const n, integer_t const kd,\n        traits::complex_f* ab, integer_t const ldab, traits::complex_f* q, integer_t const ldq,\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,\n        traits::complex_f* work, float* rwork, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_CHBEVX (\n          &jobz, &range, &uplo, &n, &kd, traits::complex_ptr(ab), &ldab,\n          traits::complex_ptr(q), &ldq,\n          &vl, &vu, &il, &iu, &abstol, &m,\n          w, traits::complex_ptr(z), &ldz,\n          traits::complex_ptr(work), rwork, iwork, ifail, &info);\n      }\n\n      inline\n      void hbevx (\n        char const jobz, char const range, char const uplo, integer_t const n, integer_t const kd,\n        traits::complex_d* ab, integer_t const ldab, traits::complex_d* q, integer_t const ldq,\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,\n        traits::complex_d* work, double* rwork, integer_t* iwork, integer_t* ifail, integer_t& info)\n      {\n        LAPACK_ZHBEVX (\n          &jobz, &range, &uplo, &n, &kd, traits::complex_ptr(ab), &ldab,\n          traits::complex_ptr(q), &ldq,\n          &vl, &vu, &il, &iu, &abstol, &m,\n          w, traits::complex_ptr(z), &ldz,\n          traits::complex_ptr(work), rwork, iwork, ifail, &info);\n      }\n    }\n\n\n    namespace detail {\n      template <int N>\n      struct Hbevx{};\n\n\n      /// Handling of workspace in the case of one workarray.\n      template <>\n      struct Hbevx< 1 > {\n        template <typename T, typename R>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          minimal_workspace, integer_t* ifail, integer_t& info ) const {\n\n          traits::detail::array<T> work( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work ),\n            traits::vector_storage (iwork),\n            ifail, info );\n        }\n\n        template <typename T, typename R>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          optimal_workspace, integer_t* ifail, integer_t& info ) const {\n\n          traits::detail::array<T> work( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work ),\n            traits::vector_storage (iwork),\n            ifail, info );\n        }\n\n        template <typename T, typename R, typename W, typename WI>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          detail::workspace2<W, WI> work,\n          integer_t* ifail, integer_t& info ) const {\n\n          assert( traits::vector_size( work.select(T()) )         >= 7*n );\n          assert( traits::vector_size( work.select(integer_t()) ) >= 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work.select(T()) ),\n            traits::vector_storage( work.select(integer_t()) ),\n            ifail, info );\n        }\n      }; // Hbevx< 1 >\n\n\n      /// Handling of workspace in the case of two workarrays.\n      template <>\n      struct Hbevx< 2 > {\n        template <typename T, typename R>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          minimal_workspace, integer_t* ifail, integer_t& info ) const {\n\n          traits::detail::array<T> work( n );\n          traits::detail::array<R> rwork( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work ),\n            traits::vector_storage( rwork ),\n            traits::vector_storage (iwork),\n            ifail, info );\n        }\n\n        template <typename T, typename R>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          optimal_workspace, integer_t* ifail, integer_t& info ) const {\n\n          traits::detail::array<T> work( n );\n          traits::detail::array<R> rwork( 7*n );\n          traits::detail::array<integer_t> iwork( 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work ),\n            traits::vector_storage( rwork ),\n            traits::vector_storage (iwork),\n            ifail, info );\n        }\n\n        template <typename T, typename R, typename W, typename RW, typename WI>\n        void operator() (char const jobz, char const range, char const uplo, integer_t const n,\n          integer_t const kd, T* ab, integer_t const ldab, T* q, integer_t const ldq,\n          R vl, R vu, integer_t const il, integer_t const iu, R abstol, integer_t& m,\n          R* w, T* z, integer_t const ldz,\n          detail::workspace3<W, RW, WI> work,\n          integer_t* ifail, integer_t& info ) const {\n\n          assert( traits::vector_size( work.select(T()) ) >= n );\n          assert( traits::vector_size( work.select(R()) ) >= 7*n );\n          assert( traits::vector_size( work.select(integer_t()) ) >= 5*n );\n          hbevx( jobz, range, uplo, n, kd, ab, ldab, q, ldq,\n            vl, vu, il, iu, abstol, m,\n            w, z, ldz,\n            traits::vector_storage( work.select(T()) ),\n            traits::vector_storage( work.select(R()) ),\n            traits::vector_storage( work.select(integer_t()) ),\n            ifail, info );\n        }\n      }; // Hbevx< 2 >\n    } // namespace detail\n\n    template <typename AB, typename Q, typename R, typename Z, typename W, typename IFail, typename Work>\n    int hbevx( char const jobz, char const range, AB& ab, Q& q, R vl, R vu, integer_t il, integer_t iu, R abstol, integer_t& m,\n      W& w, Z& z, IFail& ifail, Work work ) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<AB>::matrix_structure,\n        traits::hermitian_t\n      >::value));\n#endif\n\n      typedef typename AB::value_type                            value_type ;\n\n      integer_t const n = traits::matrix_size2 (ab);\n      assert (n == traits::matrix_size1 (z));\n      assert (n == traits::vector_size (w));\n      assert (n == traits::vector_size (ifail));\n      assert ( jobz=='N' || jobz=='V' );\n\n      integer_t info ;\n      detail::Hbevx< n_workspace_args<value_type>::value >() (jobz, range,\n        traits::matrix_uplo_tag( ab ), n,\n        traits::matrix_upper_bandwidth(ab),\n        traits::matrix_storage (ab),\n        traits::leading_dimension (ab),\n        traits::matrix_storage (q),\n        traits::leading_dimension (q),\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    } // hbevx()\n  }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "db46c42bad310e57e79d0886b27b3508e3e2f7a1", "size": 12317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/lapack/hbevx.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/hbevx.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/hbevx.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.1939799331, "max_line_length": 127, "alphanum_fraction": 0.5897539985, "num_tokens": 3440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5815206191507255}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nint dijkstra_dist(const weighted_graph &G, int s, int t) {\n  int n = boost::num_vertices(G);\n  std::vector<int> dist_map(n);\n\n  boost::dijkstra_shortest_paths(G, s,\n    boost::distance_map(boost::make_iterator_property_map(\n      dist_map.begin(), boost::get(boost::vertex_index, G))));\n\n  return dist_map[t];\n}\n\nint index(int v, int k, int n) {\n  return k * n + v;\n}\n\nvoid solve()\n{\n  int n; std::cin >> n;\n  int m; std::cin >> m;\n  int k; std::cin >> k;\n  int x; std::cin >> x;\n  int y; std::cin >> y;\n\n\n  weighted_graph G;\n\n  int a, b, c, d;\n  for (int i = 0; i < m; ++i) {\n    std::cin >> a;\n    std::cin >> b;\n    std::cin >> c;\n    std::cin >> d;\n\n    for (int j = 1; j <= k; ++j) {\n      boost::add_edge(a + j * n, b + (j - d) * n, c, G); \n      boost::add_edge(b + j * n, a + (j - d) * n, c, G); \n    }\n    boost::add_edge(a, b, c, G); \n    boost::add_edge(b, a, c, G);  \n  }\n\n  std::cout << dijkstra_dist(G, x + k * n, y) << std::endl;\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false);\n  int t; std::cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n}", "meta": {"hexsha": "d814327710ad3b6706691c0632c033aba12c53a0", "size": 1656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tracking.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/tracking.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/tracking.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": 25.4769230769, "max_line_length": 87, "alphanum_fraction": 0.6074879227, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5815205898183191}}
{"text": "#include \"geometry.hpp\"\n#include <opencv2/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <boost/functional/hash.hpp>\n#include <cmath>\n#include <algorithm>\n\nnamespace r = ranges;\nnamespace rv = ranges::views;\n\nch::matrix ch::rotation_matrix(double theta)\n{\n\treturn rotation_matrix(std::cos(theta), std::sin(theta));\n}\n\nch::matrix ch::rotation_matrix(double cos_theta, double sin_theta) {\n\tch::matrix rotation;\n\trotation <<\n\t\tcos_theta, -sin_theta, 0,\n\t\tsin_theta, cos_theta, 0,\n\t\t0, 0, 1;\n\treturn rotation;\n}\n\nch::matrix ch::translation_matrix(double x, double y) {\n\tch::matrix translation;\n\ttranslation <<\n\t\t1, 0, x,\n\t\t0, 1, y,\n\t\t0, 0, 1;\n\treturn translation;\n}\n\nch::matrix ch::translation_matrix(const cv::Point2d& pt)\n{\n\treturn translation_matrix(pt.x, pt.y);\n}\n\nch::matrix ch::scale_matrix(double x_scale, double y_scale) {\n\tch::matrix scale;\n\tscale <<\n\t\tx_scale, 0, 0,\n\t\t0, y_scale, 0,\n\t\t0, 0, 1;\n\treturn scale;\n}\n\nranges::any_view<ch::polyline> ch::transform(ranges::any_view<polyline> polys, const matrix& mat)\n{\n\treturn polys | rv::transform([=](const auto& poly) { return ch::transform(poly, mat); });\n}\n\nstd::vector<ch::polyline> ch::transform(const std::vector<polyline>& polys, const matrix& mat)\n{\n\tstd::vector<ch::polyline> output(polys.size());\n\tstd::transform(polys.begin(), polys.end(), output.begin(),\n\t\t[&mat](const auto& poly) {\n\t\t\treturn ch::transform(poly, mat);\n\t\t}\n\t);\n\treturn output;\n}\n\nch::point ch::mean_point(const polyline& poly)\n{\n\tauto x = 0.0;\n\tauto y = 0.0;\n\tfor (const auto& pt : poly) {\n\t\tx += pt.x;\n\t\ty += pt.y;\n\t}\n\treturn {\n\t\tx / poly.size(),\n\t\ty / poly.size()\n\t};\n}\n\nch::polyline ch::transform(const polyline& poly, const matrix& mat)\n{\n\tch::polyline output(poly.size());\n\tstd::transform(poly.begin(), poly.end(), output.begin(),\n\t\t[&mat](const auto& p) {return transform(p, mat); }\n\t);\n\treturn output;\n}\n\nch::point ch::transform(const point& pt, const matrix& mat)\n{\n\tvec v;\n\tv << pt.x, pt.y, 1.0;\n\tv = mat * v;\n\treturn { v[0], v[1] }; \n}\n\nvoid ch::paint_polyline(cv::Mat& mat, const polyline& poly, double thickness, int color, point offset)\n{\n\tstd::vector<cv::Point> int_pts(poly.size());\n\tstd::transform(poly.begin(), poly.end(), int_pts.begin(),\n\t\t[offset](const auto& p) {\n\t\t\treturn cv::Point(\n\t\t\t\tstatic_cast<int>(std::round(p.x + offset.x)),\n\t\t\t\tstatic_cast<int>(std::round(p.y + offset.y))\n\t\t\t); \n\t\t}\n\t);\n\tauto npts = int_pts.size();\n\tcv::polylines(mat, int_pts, false, color, thickness, 8, 0);\n}\n\ndouble ch::euclidean_distance(const point& pt1, const point& pt2)\n{\n\tauto x_diff = pt2.x - pt1.x;\n\tauto y_diff = pt2.y - pt1.y;\n\treturn std::sqrt(x_diff * x_diff + y_diff * y_diff);\n}\n\nstd::size_t ch::point_hasher::operator()(const cv::Point& p) const\n{\n\tstd::size_t seed = 0;\n\tboost::hash_combine(seed, p.x);\n\tboost::hash_combine(seed, p.y);\n\n\treturn seed;\n}\n\n", "meta": {"hexsha": "c528d68df9fa922eda77d68715f1ad34b69c38cd", "size": 2841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crosshatching/geometry.cpp", "max_stars_repo_name": "jwezorek/crosshatching", "max_stars_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crosshatching/geometry.cpp", "max_issues_repo_name": "jwezorek/crosshatching", "max_issues_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crosshatching/geometry.cpp", "max_forks_repo_name": "jwezorek/crosshatching", "max_forks_repo_head_hexsha": "0811e239998cc68d5d6e900510974d6196638577", "max_forks_repo_licenses": ["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.3700787402, "max_line_length": 102, "alphanum_fraction": 0.6606828581, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.5814617239416738}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson_ext::detail::math.hpp                                    //\n//                                                                          //\n//                                                                          //\n//  (C) Copyright 2010 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_RANDOM_POISSON_EXT_DETAIL_MATH_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DETAIL_MATH_HPP_ER_2010\n#include <cmath>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\n#include <boost/numeric/conversion/converter.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/limits.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{\nnamespace detail{\n\n\t// Math functions or constants are gathered here, so that any implementation\n    // change to one of them need not be replicated throughout the code.\n \ttemplate<typename Int,typename T,typename P>\n\tstruct math{\n    \ttypedef Int int_type;\n    \ttypedef T float_type;\n    \n\t\tstatic const float_type pi(){ \n        \tstatic const float_type val \n            \t= boost::math::constants::pi<float_type>();\n            return val;\n        }\n        static const float_type eps(){\n        \treturn boost::numeric::bounds<float_type>::smallest();\n        }\n        static bool is_strictly_negative(const float_type& x){\n        \treturn ( !( x >= (-eps()) ) );\n        }\n        template<typename E>\n        static float_type pow(const float_type& x,const E& k){\n        \treturn std::pow(x,k);\n        }\n        static float_type exp(const float_type& x){\n        \treturn std::exp(x);\n        }\n        static float_type sqrt(const float_type& x){\n        \treturn std::sqrt(x);\n        }\n\t\tstatic float_type floor(const float_type& x){\n        \tfloat_type val = std::floor(x);\n        \treturn val;\n        }\n\t\tstatic float_type ceil(const float_type& x){\n        \tfloat_type val = std::ceil(x);\n        \treturn val;\n        }\n        static float_type log1p(const float_type& x){\n        \treturn boost::math::log1p(x);\n        }\n        static float_type log1p(const float_type& x,const P& p){\n        \treturn boost::math::log1p(x,p);\n        }\n        static float_type log(const float_type& x){\n        \treturn std::log(x);\n        }\n        static float_type factorial(const int_type& i,const P& p){\n        \treturn boost::math::factorial<float_type>(i,p);\n        }\n\n\t\ttemplate<typename To,typename From>\n        static To convert(const From& t){\n            typedef boost::numeric::converter<To,From> to_; \n            return to_::convert(t);        \n        \n        }\n\t\tstatic float_type to_float(const int_type& i){\n            return convert<float_type>(i);        \n        }\n\t\tstatic int_type to_int(const float_type& x){\n            return convert<int_type>(x);        \n        }\n\t};\n\n}// math\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif     \n    ", "meta": {"hexsha": "e1095ef8b9562eaacbce8d265854fd0308241f2c", "size": 3367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/detail/math.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/detail/math.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/detail/math.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.7113402062, "max_line_length": 78, "alphanum_fraction": 0.5488565489, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5814617169406787}}
{"text": "// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com>\n// SPDX-License-Identifier: MIT\n\n#ifndef ADS_SIMULATION_BASIC_SIMULATION_2D_HPP\n#define ADS_SIMULATION_BASIC_SIMULATION_2D_HPP\n\n#include <array>\n#include <cstddef>\n\n#include <boost/range/counting_range.hpp>\n\n#include \"ads/lin/tensor.hpp\"\n#include \"ads/simulation/boundary.hpp\"\n#include \"ads/simulation/dimension.hpp\"\n#include \"ads/util/function_value.hpp\"\n#include \"ads/util/iter/product.hpp\"\n\nnamespace ads {\n\nclass basic_simulation_2d {\npublic:\n    virtual ~basic_simulation_2d() = default;\n\n    basic_simulation_2d() = default;\n    basic_simulation_2d(const basic_simulation_2d&) = delete;\n    basic_simulation_2d& operator=(const basic_simulation_2d&) = delete;\n    basic_simulation_2d(basic_simulation_2d&&) = delete;\n    basic_simulation_2d& operator=(basic_simulation_2d&&) = delete;\n\nprotected:\n    using vector_type = lin::tensor<double, 2>;\n    using vector_view = lin::tensor_view<double, 2>;\n    using value_type = function_value_2d;\n\n    using index_type = std::array<int, 2>;\n    using index_1d_iter_type = boost::counting_iterator<int>;\n    using index_iter_type = util::iter_product2<index_1d_iter_type, index_type>;\n    using index_range = boost::iterator_range<index_iter_type>;\n\n    using point_type = std::array<double, 2>;\n\n    struct L2 {\n        double operator()(value_type a) const { return a.val * a.val; }\n    };\n\n    struct H10 {\n        double operator()(value_type a) const { return a.dx * a.dx + a.dy * a.dy; }\n    };\n\n    struct H1 {\n        double operator()(value_type a) const { return a.val * a.val + a.dx * a.dx + a.dy * a.dy; }\n    };\n\n    value_type eval_basis(index_type e, index_type q, index_type a, const dimension& x,\n                          const dimension& y) const {\n        auto loc = dof_global_to_local(e, a, x, y);\n\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n\n        double B1 = bx.b[e[0]][q[0]][0][loc[0]];\n        double B2 = by.b[e[1]][q[1]][0][loc[1]];\n        double dB1 = bx.b[e[0]][q[0]][1][loc[0]];\n        double dB2 = by.b[e[1]][q[1]][1][loc[1]];\n\n        double v = B1 * B2;\n        double dxv = dB1 * B2;\n        double dyv = B1 * dB2;\n\n        return {v, dxv, dyv};\n    }\n\n    double laplacian(index_type e, index_type q, index_type a, const dimension& x,\n                     const dimension& y) const {\n        auto loc = dof_global_to_local(e, a, x, y);\n\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n\n        double B1 = bx.b[e[0]][q[0]][0][loc[0]];\n        double B2 = by.b[e[1]][q[1]][0][loc[1]];\n        double ddB1 = bx.b[e[0]][q[0]][2][loc[0]];\n        double ddB2 = by.b[e[1]][q[1]][2][loc[1]];\n\n        return B1 * ddB2 + ddB1 * B2;\n    }\n\n    template <typename Sol>\n    value_type eval(const Sol& v, index_type e, index_type q, const dimension& x,\n                    const dimension& y) const {\n        value_type u{};\n        for (auto b : dofs_on_element(e, x, y)) {\n            double c = v(b[0], b[1]);\n            value_type B = eval_basis(e, q, b, x, y);\n            u += c * B;\n        }\n        return u;\n    }\n\n    index_range elements(const dimension& x, const dimension& y) const {\n        return util::product_range<index_type>(x.element_indices(), y.element_indices());\n    }\n\n    index_range quad_points(const dimension& x, const dimension& y) const {\n        auto rx = boost::counting_range(0, x.basis.quad_order);\n        auto ry = boost::counting_range(0, y.basis.quad_order);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    index_range dofs_on_element(index_type e, const dimension& x, const dimension& y) const {\n        auto rx = x.basis.dof_range(e[0]);\n        auto ry = y.basis.dof_range(e[1]);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    index_range elements_supporting_dof(index_type dof, const dimension& x,\n                                        const dimension& y) const {\n        auto rx = x.basis.element_range(dof[0]);\n        auto ry = y.basis.element_range(dof[1]);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    bool supported_in(index_type dof, index_type e, const dimension& x, const dimension& y) const {\n        auto xrange = x.basis.element_ranges[dof[0]];\n        auto yrange = y.basis.element_ranges[dof[1]];\n        return e[0] >= xrange.first && e[0] <= xrange.second && e[1] >= yrange.first\n            && e[1] <= yrange.second;\n    }\n\n    index_type dof_global_to_local(index_type e, index_type a, const dimension& x,\n                                   const dimension& y) const {\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        return {{a[0] - bx.first_dof(e[0]), a[1] - by.first_dof(e[1])}};\n    }\n\n    template <typename RHS>\n    void update_global_rhs(RHS& global, const vector_type& local, index_type e, const dimension& x,\n                           const dimension& y) const {\n        for (auto a : dofs_on_element(e, x, y)) {\n            auto loc = dof_global_to_local(e, a, x, y);\n            global(a[0], a[1]) += local(loc[0], loc[1]);\n        }\n    }\n\n    index_range dofs(const dimension& x, const dimension& y) const {\n        auto rx = boost::counting_range(0, x.dofs());\n        auto ry = boost::counting_range(0, y.dofs());\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    index_range internal_dofs(const dimension& x, const dimension& y) const {\n        auto rx = boost::counting_range(1, x.dofs() - 1);\n        auto ry = boost::counting_range(1, y.dofs() - 1);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    double jacobian(index_type e, const dimension& x, const dimension& y) const {\n        return x.basis.J[e[0]] * y.basis.J[e[1]];\n    }\n\n    double weight(index_type q, const dimension& x, const dimension& y) const {\n        return x.basis.w[q[0]] * y.basis.w[q[1]];\n    }\n\n    point_type point(index_type e, index_type q, const dimension& x, const dimension& y) const {\n        double px = x.basis.x[e[0]][q[0]];\n        double py = y.basis.x[e[1]][q[1]];\n        return {px, py};\n    }\n\n    auto overlapping_dofs(int dof, int begin, int end, const dimension& x) const {\n        using std::max;\n        using std::min;\n\n        auto minx = max(begin, dof - x.B.degree);\n        auto maxx = min(end, dof + x.B.degree + 1);\n\n        return boost::counting_range(minx, maxx);\n    }\n\n    index_range overlapping_dofs(index_type dof, const dimension& x, const dimension& y) const {\n        auto rx = overlapping_dofs(dof[0], 0, x.dofs(), x);\n        auto ry = overlapping_dofs(dof[1], 0, y.dofs(), y);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    index_range overlapping_dofs(index_type dof, const dimension& Ux, const dimension& Uy,\n                                 const dimension& Vx, const dimension& Vy) const {\n        auto xrange = Ux.basis.element_ranges[dof[0]];\n        auto yrange = Uy.basis.element_ranges[dof[1]];\n\n        auto x0 = Vx.basis.first_dof(xrange.first);\n        auto x1 = Vx.basis.last_dof(xrange.second) + 1;\n\n        auto y0 = Vy.basis.first_dof(yrange.first);\n        auto y1 = Vy.basis.last_dof(yrange.second) + 1;\n\n        auto rx = boost::counting_range(x0, x1);\n        auto ry = boost::counting_range(y0, y1);\n\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    index_range overlapping_internal_dofs(index_type dof, const dimension& x,\n                                          const dimension& y) const {\n        auto rx = overlapping_dofs(dof[0], 1, x.dofs() - 1, x);\n        auto ry = overlapping_dofs(dof[1], 1, y.dofs() - 1, y);\n        return util::product_range<index_type>(rx, ry);\n    }\n\n    int linear_index(index_type dof, const dimension& x, const dimension& y) const {\n        auto order = reverse_ordering<2>({x.dofs(), y.dofs()});\n        return order.linear_index(dof[0], dof[1]);\n    }\n\n    template <typename Fun>\n    void for_boundary_dofs(const dimension& x, const dimension& y, Fun&& fun) const {\n        for (auto jx = 0; jx < x.dofs(); ++jx) {\n            fun({jx, 0});\n            fun({jx, y.dofs() - 1});\n        }\n        for (auto jy = 1; jy < y.dofs() - 1; ++jy) {\n            fun({0, jy});\n            fun({x.dofs() - 1, jy});\n        }\n    }\n\n    bool is_boundary(int dof, const dimension& x) const { return dof == 0 || dof == x.dofs() - 1; }\n\n    bool is_boundary(index_type dof, const dimension& x, const dimension& y) const {\n        return is_boundary(dof[0], x) || is_boundary(dof[1], y);\n    }\n\n    template <typename MT1, typename MT2>\n    double kron(const MT1& A, const MT2& B, index_type i, index_type j) const {\n        return A(i[0], j[0]) * B(i[1], j[1]);\n    }\n\n    template <typename RHS, typename Fun,\n              typename = std::enable_if<std::is_arithmetic<std::result_of_t<Fun(double)>>{}>>\n    void dirichlet_bc(RHS& u, boundary side, dimension& x, dimension& y, Fun&& fun) const {\n        bool horizontal = side == boundary::top || side == boundary::bottom;\n        auto& basis = horizontal ? x : y;\n        const auto& other = horizontal ? y : x;\n\n        lin::vector buf{{basis.dofs()}};\n        compute_projection(buf, basis.basis, std::forward<Fun>(fun));\n        lin::solve_with_factorized(basis.M, buf, basis.ctx);\n\n        int idx = side == boundary::left || side == boundary::bottom ? 0 : other.dofs() - 1;\n        for (int i = 0; i < basis.dofs(); ++i) {\n            if (horizontal) {\n                u(i, idx) = buf(i);\n            } else {\n                u(idx, i) = buf(i);\n            }\n        }\n    }\n\n    template <typename RHS>\n    void dirichlet_bc(RHS& u, boundary side, dimension& x, dimension& y, double value) const {\n        dirichlet_bc(u, side, x, y, [value](double) { return value; });\n    }\n\n    template <typename Norm, typename Fun>\n    double norm(const dimension& Ux, const dimension& Uy, Norm&& norm, Fun&& fun) const {\n        double val = 0;\n\n        for (auto e : elements(Ux, Uy)) {\n            double J = jacobian(e, Ux, Uy);\n            for (auto q : quad_points(Ux, Uy)) {\n                double w = weight(q, Ux, Uy);\n                auto x = point(e, q, Ux, Uy);\n                auto d = fun(x);\n                val += norm(d) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Fun>\n    double normL2(const dimension& Ux, const dimension& Uy, Fun&& fun) const {\n        return norm(Ux, Uy, L2{}, fun);\n    }\n\n    template <typename Fun>\n    double normH1(const dimension& Ux, const dimension& Uy, Fun&& fun) const {\n        return norm(Ux, Uy, H1{}, fun);\n    }\n\n    template <typename Sol, typename Norm>\n    double norm(const Sol& u, const dimension& Ux, const dimension& Uy, Norm&& norm) const {\n        double val = 0;\n\n        for (auto e : elements(Ux, Uy)) {\n            double J = jacobian(e, Ux, Uy);\n            for (auto q : quad_points(Ux, Uy)) {\n                double w = weight(q, Ux, Uy);\n                value_type uu = eval(u, e, q, Ux, Uy);\n                val += norm(uu) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Sol>\n    double normL2(const Sol& u, const dimension& Ux, const dimension& Uy) const {\n        return norm(u, Ux, Uy, L2{});\n    }\n\n    template <typename Sol>\n    double normH1(const Sol& u, const dimension& Ux, const dimension& Uy) const {\n        return norm(u, Ux, Uy, H1{});\n    }\n\n    template <typename Sol, typename Fun, typename Norm>\n    double error(const Sol& u, const dimension& Ux, const dimension& Uy, Norm&& norm,\n                 Fun&& fun) const {\n        double error = 0;\n\n        for (auto e : elements(Ux, Uy)) {\n            double J = jacobian(e, Ux, Uy);\n            for (auto q : quad_points(Ux, Uy)) {\n                double w = weight(q, Ux, Uy);\n                auto x = point(e, q, Ux, Uy);\n                value_type uu = eval(u, e, q, Ux, Uy);\n\n                auto d = uu - fun(x);\n                error += norm(d) * w * J;\n            }\n        }\n        return std::sqrt(error);\n    }\n\n    template <typename Sol, typename Fun>\n    double errorL2(const Sol& u, const dimension& Ux, const dimension& Uy, Fun&& fun) const {\n        return error(u, Ux, Uy, L2{}, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double error_relative_L2(const Sol& u, const dimension& Ux, const dimension& Uy,\n                             Fun&& fun) const {\n        return error_relative(u, Ux, Uy, L2{}, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double errorH1(const Sol& u, const dimension& Ux, const dimension& Uy, Fun&& fun) const {\n        return error(u, Ux, Uy, H1{}, fun);\n    }\n\n    template <typename Sol, typename Fun, typename Norm>\n    double error_relative(const Sol& u, const dimension& Ux, const dimension& Uy, Norm&& norm,\n                          Fun&& fun) const {\n        return error(u, Ux, Uy, norm, fun) / this->norm(Ux, Uy, norm, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double error_relative_H1(const Sol& u, const dimension& Ux, const dimension& Uy,\n                             Fun&& fun) const {\n        return error_relative(u, Ux, Uy, H1{}, fun);\n    }\n};\n\n}  // namespace ads\n\n#endif  // ADS_SIMULATION_BASIC_SIMULATION_2D_HPP\n", "meta": {"hexsha": "eca3eeca76bfdfd8efa7f05720bd1afb7c94f00f", "size": 13213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ads/simulation/basic_simulation_2d.hpp", "max_stars_repo_name": "Pan-Maciek/iga-ads", "max_stars_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T00:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T00:53:00.000Z", "max_issues_repo_path": "include/ads/simulation/basic_simulation_2d.hpp", "max_issues_repo_name": "Pan-Maciek/iga-ads", "max_issues_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T22:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T15:18:00.000Z", "max_forks_repo_path": "include/ads/simulation/basic_simulation_2d.hpp", "max_forks_repo_name": "Pan-Maciek/iga-ads", "max_forks_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-04-13T19:42:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T18:46:24.000Z", "avg_line_length": 35.9048913043, "max_line_length": 99, "alphanum_fraction": 0.5754181488, "num_tokens": 3694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5814595707300918}}
{"text": "#include \"nnig_hierarchy.h\"\n\n#include <google/protobuf/stubs/casts.h>\n\n#include <Eigen/Dense>\n#include <stan/math/prim/prob.hpp>\n#include <vector>\n\n#include \"algorithm_state.pb.h\"\n#include \"hierarchy_prior.pb.h\"\n#include \"ls_state.pb.h\"\n#include \"src/utils/rng.h\"\n\ndouble NNIGHierarchy::like_lpdf(\n    const Eigen::RowVectorXd &datum,\n    const Eigen::RowVectorXd &covariate /*= Eigen::RowVectorXd(0)*/) const {\n  return stan::math::normal_lpdf(datum(0), state.mean, sqrt(state.var));\n}\n\ndouble NNIGHierarchy::marg_lpdf(\n    const NNIG::Hyperparams &params, const Eigen::RowVectorXd &datum,\n    const Eigen::RowVectorXd &covariate /*= Eigen::RowVectorXd(0)*/) const {\n  double sig_n = sqrt(params.scale * (params.var_scaling + 1) /\n                      (params.shape * params.var_scaling));\n  return stan::math::student_t_lpdf(datum(0), 2 * params.shape, params.mean,\n                                    sig_n);\n}\n\nNNIG::State NNIGHierarchy::draw(const NNIG::Hyperparams &params) {\n  // Update state values from their prior centering distribution\n  auto &rng = bayesmix::Rng::Instance().get();\n  NNIG::State out;\n  out.var = stan::math::inv_gamma_rng(params.shape, params.scale, rng);\n  out.mean = stan::math::normal_rng(params.mean,\n                                    sqrt(state.var / params.var_scaling), rng);\n  return out;\n}\n\nvoid NNIGHierarchy::update_summary_statistics(\n    const Eigen::RowVectorXd &datum, const Eigen::RowVectorXd &covariate,\n    bool add) {\n  if (add) {\n    data_sum += datum(0);\n    data_sum_squares += datum(0) * datum(0);\n  } else {\n    data_sum -= datum(0);\n    data_sum_squares -= datum(0) * datum(0);\n  }\n}\n\nNNIG::Hyperparams NNIGHierarchy::get_posterior_parameters() {\n  // Initialize relevant variables\n  if (card == 0) {  // no update possible\n    return *hypers;\n  }\n  // Compute posterior hyperparameters\n  NNIG::Hyperparams post_params;\n  double y_bar = data_sum / (1.0 * card);  // sample mean\n  double ss = data_sum_squares - card * y_bar * y_bar;\n  post_params.mean = (hypers->var_scaling * hypers->mean + data_sum) /\n                     (hypers->var_scaling + card);\n  post_params.var_scaling = hypers->var_scaling + card;\n  post_params.shape = hypers->shape + 0.5 * card;\n  post_params.scale = hypers->scale + 0.5 * ss +\n                      0.5 * hypers->var_scaling * card *\n                          (y_bar - hypers->mean) * (y_bar - hypers->mean) /\n                          (card + hypers->var_scaling);\n  return post_params;\n}\n\nvoid NNIGHierarchy::clear_data() {\n  data_sum = 0;\n  data_sum_squares = 0;\n  card = 0;\n  cluster_data_idx = std::set<int>();\n}\n\nvoid NNIGHierarchy::initialize_state() {\n  state.mean = hypers->mean;\n  state.var = hypers->scale / (hypers->shape + 1);\n}\n\nvoid NNIGHierarchy::initialize_hypers() {\n  if (prior->has_fixed_values()) {\n    // Set values\n    hypers->mean = prior->fixed_values().mean();\n    hypers->var_scaling = prior->fixed_values().var_scaling();\n    hypers->shape = prior->fixed_values().shape();\n    hypers->scale = prior->fixed_values().scale();\n    // Check validity\n    if (hypers->var_scaling <= 0) {\n      throw std::invalid_argument(\"Variance-scaling parameter must be > 0\");\n    }\n    if (hypers->shape <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (hypers->scale <= 0) {\n      throw std::invalid_argument(\"Scale parameter must be > 0\");\n    }\n  }\n\n  else if (prior->has_normal_mean_prior()) {\n    // Set initial values\n    hypers->mean = prior->normal_mean_prior().mean_prior().mean();\n    hypers->var_scaling = prior->normal_mean_prior().var_scaling();\n    hypers->shape = prior->normal_mean_prior().shape();\n    hypers->scale = prior->normal_mean_prior().scale();\n    // Check validity\n    if (hypers->var_scaling <= 0) {\n      throw std::invalid_argument(\"Variance-scaling parameter must be > 0\");\n    }\n    if (hypers->shape <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (hypers->scale <= 0) {\n      throw std::invalid_argument(\"Scale parameter must be > 0\");\n    }\n  }\n\n  else if (prior->has_ngg_prior()) {\n    // Get hyperparameters:\n    // for mu0\n    double mu00 = prior->ngg_prior().mean_prior().mean();\n    double sigma00 = prior->ngg_prior().mean_prior().var();\n    // for lambda0\n    double alpha00 = prior->ngg_prior().var_scaling_prior().shape();\n    double beta00 = prior->ngg_prior().var_scaling_prior().rate();\n    // for beta0\n    double a00 = prior->ngg_prior().scale_prior().shape();\n    double b00 = prior->ngg_prior().scale_prior().rate();\n    // for alpha0\n    double alpha0 = prior->ngg_prior().shape();\n    // Check validity\n    if (sigma00 <= 0) {\n      throw std::invalid_argument(\"Variance parameter must be > 0\");\n    }\n    if (alpha00 <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (beta00 <= 0) {\n      throw std::invalid_argument(\"Rate parameter must be > 0\");\n    }\n    if (a00 <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    if (b00 <= 0) {\n      throw std::invalid_argument(\"Rate parameter must be > 0\");\n    }\n    if (alpha0 <= 0) {\n      throw std::invalid_argument(\"Shape parameter must be > 0\");\n    }\n    // Set initial values\n    hypers->mean = mu00;\n    hypers->var_scaling = alpha00 / beta00;\n    hypers->shape = alpha0;\n    hypers->scale = a00 / b00;\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid NNIGHierarchy::update_hypers(\n    const std::vector<bayesmix::AlgorithmState::ClusterState> &states) {\n  auto &rng = bayesmix::Rng::Instance().get();\n\n  if (prior->has_fixed_values()) {\n    return;\n  }\n\n  else if (prior->has_normal_mean_prior()) {\n    // Get hyperparameters\n    double mu00 = prior->normal_mean_prior().mean_prior().mean();\n    double sig200 = prior->normal_mean_prior().mean_prior().var();\n    double lambda0 = prior->normal_mean_prior().var_scaling();\n    // Compute posterior hyperparameters\n    double prec = 0.0;\n    double num = 0.0;\n    for (auto &st : states) {\n      double mean = st.uni_ls_state().mean();\n      double var = st.uni_ls_state().var();\n      prec += 1 / var;\n      num += mean / var;\n    }\n    prec = 1 / sig200 + lambda0 * prec;\n    num = mu00 / sig200 + lambda0 * num;\n    double mu_n = num / prec;\n    double sig2_n = 1 / prec;\n    // Update hyperparameters with posterior random sampling\n    hypers->mean = stan::math::normal_rng(mu_n, sqrt(sig2_n), rng);\n  }\n\n  else if (prior->has_ngg_prior()) {\n    // Get hyperparameters:\n    // for mu0\n    double mu00 = prior->ngg_prior().mean_prior().mean();\n    double sig200 = prior->ngg_prior().mean_prior().var();\n    // for lambda0\n    double alpha00 = prior->ngg_prior().var_scaling_prior().shape();\n    double beta00 = prior->ngg_prior().var_scaling_prior().rate();\n    // for tau0\n    double a00 = prior->ngg_prior().scale_prior().shape();\n    double b00 = prior->ngg_prior().scale_prior().rate();\n    // Compute posterior hyperparameters\n    double b_n = 0.0;\n    double num = 0.0;\n    double beta_n = 0.0;\n    for (auto &st : states) {\n      double mean = st.uni_ls_state().mean();\n      double var = st.uni_ls_state().var();\n      b_n += 1 / var;\n      num += mean / var;\n      beta_n += (hypers->mean - mean) * (hypers->mean - mean) / var;\n    }\n    double var = hypers->var_scaling * b_n + 1 / sig200;\n    b_n += b00;\n    num = hypers->var_scaling * num + mu00 / sig200;\n    beta_n = beta00 + 0.5 * beta_n;\n    double sig_n = 1 / var;\n    double mu_n = num / var;\n    double alpha_n = alpha00 + 0.5 * states.size();\n    double a_n = a00 + states.size() * hypers->shape;\n    // Update hyperparameters with posterior random Gibbs sampling\n    hypers->mean = stan::math::normal_rng(mu_n, sig_n, rng);\n    hypers->var_scaling = stan::math::gamma_rng(alpha_n, beta_n, rng);\n    hypers->scale = stan::math::gamma_rng(a_n, b_n, rng);\n  }\n\n  else {\n    throw std::invalid_argument(\"Unrecognized hierarchy prior\");\n  }\n}\n\nvoid NNIGHierarchy::set_state_from_proto(\n    const google::protobuf::Message &state_) {\n  auto &statecast = google::protobuf::internal::down_cast<\n      const bayesmix::AlgorithmState::ClusterState &>(state_);\n  state.mean = statecast.uni_ls_state().mean();\n  state.var = statecast.uni_ls_state().var();\n  set_card(statecast.cardinality());\n}\n\nvoid NNIGHierarchy::write_state_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::UniLSState state_;\n  state_.set_mean(state.mean);\n  state_.set_var(state.var);\n\n  auto *out_cast = google::protobuf::internal::down_cast<\n      bayesmix::AlgorithmState::ClusterState *>(out);\n  out_cast->mutable_uni_ls_state()->CopyFrom(state_);\n  out_cast->set_cardinality(card);\n}\n\nvoid NNIGHierarchy::write_hypers_to_proto(\n    google::protobuf::Message *out) const {\n  bayesmix::NNIGPrior hypers_;\n  hypers_.mutable_fixed_values()->set_mean(hypers->mean);\n  hypers_.mutable_fixed_values()->set_var_scaling(hypers->var_scaling);\n  hypers_.mutable_fixed_values()->set_shape(hypers->shape);\n  hypers_.mutable_fixed_values()->set_scale(hypers->scale);\n\n  google::protobuf::internal::down_cast<bayesmix::NNIGPrior *>(out)\n      ->mutable_fixed_values()\n      ->CopyFrom(hypers_.fixed_values());\n}\n", "meta": {"hexsha": "28490eac47e64931fab6cfa4adac395e458446e7", "size": 9197, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hierarchies/nnig_hierarchy.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/hierarchies/nnig_hierarchy.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/hierarchies/nnig_hierarchy.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": 34.3171641791, "max_line_length": 79, "alphanum_fraction": 0.6464064369, "num_tokens": 2492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5813200628255858}}
{"text": "#include <iostream>\r\n#include <limits>\r\n#include <string>\r\n#include <Eigen/Dense> \r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nvoid test(VectorXd &vec)\r\n{\r\n\tcout << vec << '\\n';\r\n\tfor (int i = 0; i < vec.rows(); i++)\r\n\t{\r\n\t\tvec[i] = i / 10.;\r\n\t}\r\n\tcout << vec << '\\n';\r\n}\r\n\r\nvoid test(MatrixXd &mat)\r\n{\r\n\tcout << mat << '\\n';\r\n\tfor (int i = 0; i < mat.rows(); i++)\r\n\t\tfor (int j = 0; j < mat.cols(); j++)\r\n\t\t\tmat(i, j) = (i + j) / 10.;\r\n\tcout << mat << '\\n';\r\n\tmat << 0.7, 0.8, 0.9,1.,2.,3.;\r\n\tcout << mat << '\\n';\r\n}\r\n\r\nvoid test(double t[])\r\n{\r\n\tt[0] = 0.;\r\n\tt[1] = 0.;\r\n}\r\n\r\nint main()\r\n{\r\n\tArrayXXd t1(2, 3);\r\n\tt1 << 1.1, 2.2, 3.3, 4.4, 5.5, 6.6;\r\n\tArray<unsigned int, Dynamic, 3> t2 = (t1 / 0.1).cast<unsigned int>();\r\n\tcout << t2 << endl;\r\n\tArrayXXd t3(2, 3);\r\n\tt3 << 1.2, 2.1, 3.4, 4.5, 5.6, 6.7;\r\n\tArrayXXd t4 = (t3 > t1).cast<double>();\r\n\tcout << t4 << endl;\r\n\tArrayXXd t5 = (t3 > 4).cast<double>();\r\n\tcout << t5 << endl;\r\n\t\r\n\tdouble max = std::numeric_limits<double>::max();\r\n\tdouble inf = std::numeric_limits<double>::infinity();\r\n\r\n\tif (inf > max)\r\n\t\tcout << inf << \" is greater than \" << max << '\\n';\r\n\tcout << inf + inf << endl;\r\n\tcout << 0.*inf << endl;\r\n\tchar* inf_char = \"inf\";\r\n\tcout << strtod(inf_char, nullptr) << endl;\r\n\tcout << isinf(inf) << endl;\r\n\t\r\n\t/*\r\n\tArrayXXd t1(3, 2);\r\n\tt1 << 1, 2, 3, 4, 5, 6;\r\n\tcout << t1 << endl;\r\n\tArrayXXd t2(3, 2);\r\n\tt2 << 7, 8, 9, 0, 1, 2;\r\n\tcout << t2 << endl;\r\n\tcout << t1.block(0, 0, 1, 2).transpose() + t2.block(0, 0, 2, 1) << endl;\r\n\r\n\tdouble *q = t1.data();\r\n\tcout << *q << endl;\r\n\tq[0] = 90., q[2] = 80; // matrix and array elements are in colum stored in memory\r\n\tcout << *q << endl;\r\n\tcout << t1 << endl;\r\n\t*/\r\n\r\n\t/*\r\n\tVectorXd vec(4);\r\n\tvec << 1 , 2 , 3 , 4;\r\n\ttest(vec);\r\n\r\n\tMatrixXd mat(2, 3);\r\n\tmat << 1, 2, 3, 4, 5, 6;\r\n\ttest(mat);\r\n\t//\r\n\tVectorXd v2 = VectorXd::LinSpaced(10, 0., 12.);\r\n\ttest(v2);\r\n\tv2 *= 2.;\r\n\tcout << v2 << '\\n';\r\n\t\r\n\tMatrix3f A;\r\n\tVector3f b;\r\n\tA << 1, 2, 3, 4, 5, 6, 7, 8, 10;\r\n\tb << 3, 3, 4;\r\n\tcout << \"Here is the matrix A:\\n\" << A << endl;\r\n\tcout << \"Here is the vector b:\\n\" << b << endl;\r\n\tVector3f x = A.colPivHouseholderQr().solve(b);\r\n\tcout << \"The solution is:\\n\" << x << endl;\r\n\tcout << b.array().cos() << endl;\r\n\t*/\r\n\r\n\t//\r\n\treturn 0;\r\n}", "meta": {"hexsha": "ff4f5dde96e11ec5152a874f6abea3601ed71eb8", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_eigen3/main.cpp", "max_stars_repo_name": "bourbakilee/CppMPL", "max_stars_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-19T14:13:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-14T01:52:20.000Z", "max_issues_repo_path": "test_eigen3/main.cpp", "max_issues_repo_name": "bourbakilee/CppMPL", "max_issues_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_eigen3/main.cpp", "max_forks_repo_name": "bourbakilee/CppMPL", "max_forks_repo_head_hexsha": "67f6355bcd2db5016841484d16bf9299e3293457", "max_forks_repo_licenses": ["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.9901960784, "max_line_length": 83, "alphanum_fraction": 0.494872938, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.5812652868643092}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::search_reflection.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_SEARCH_REFLECTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_SEARCH_REFLECTION_HPP_ER_2009\n#include <string>\n#include <boost/format.hpp>\n#include <boost/function.hpp>\n#include <boost/ars/constant.hpp>\n#include <boost/ars/point.hpp>\n#include <boost/ars/error.hpp>\n#include <boost/ars/function/signature.hpp>\n#include <boost/ars/function/adaptor.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\n\n// This function searches by reflection for initial starting points \n// (x_0,x_1) such that if x_min = -inf, dy_0>0 and if x_min = inf, dy_0<0\n\n//TODO even if x_min or x_max finite, |dy|>eps might be desirable\ntemplate<typename T>\nunsigned\nsearch_reflection(\n    const T& x_min,\n    const T& x_max,\n    boost::function<typename ars::function::signature<T>::type> delegate,\n    point<T>& p_0,\n    point<T>& p_1,\n    unsigned n_max\n){\n    static const char* function\n    = \"search_reflection(%1%, %2%, ...)\";\n\n    typedef point<T> point_t;\n    typedef constant<T> const_;\n\n    struct local{\n        static bool ok_0(const point_t& p){ \n            return ( p.dy() >=  const_::eps_ ); }\n        static bool ok_1(const point_t& p){ \n            return ( p.dy() <= (-const_::eps_) ); }\n    };\n\n    unsigned n = 0;\n    T new_x_0 = p_0.x();\n    T new_x_1 = p_1.x();\n    bool ok_0, ok_1 = true;\n    if(math::isinf(x_min)){ ok_0 = local::ok_0(p_0); }\n    if(math::isinf(x_max)){ ok_1 = local::ok_1(p_1); }\n\n    while(\n        (!(ok_0 && ok_1))\n    ){\n        if(n>n_max){\n            boost::format f(function);\n            f % x_min % x_max;\n            throw ars::exception(f.str(),\"n>n_max\",p_0,p_1);\n        }\n\n        if(!ok_0){\n            T delta = (new_x_1-new_x_0);\n            if(delta < const_::eps_ ){\n                boost::format f(function);\n                f % x_min % x_max;\n                throw ars::exception(\n                    f.str(),\n                    \"new_x_0-new_x_1< (- const_::eps_)\",\n                    p_0,p_1\n                );\n            }\n            //TODO max(new_x_0,-highest) ?\n            new_x_0 -=  delta;\n            p_0 = create_point<T>(new_x_0,delegate);\n            ok_0 = local::ok_0(p_0);\n        }\n        if(!ok_1){\n            T delta = (new_x_1-new_x_0);\n            if( delta < const_::eps_){\n                boost::format f(function);\n                f % x_min % x_max;\n                throw ars::exception(\n                    f.str(),\n                    \"new_x_1-new_x_0 > const_::eps_\",\n                    p_0,p_1\n                );\n            }\n            new_x_1 += delta;\n            p_1 = create_point<T>(new_x_1,delegate);\n            ok_1 = local::ok_1(p_1);\n        }\n        ++n;\n    }\n    return n;\n}\n\ntemplate<typename T>\nunsigned search_reflection(\n    const T& x_min,\n    const T& x_max,\n    boost::function<typename ars::function::signature<T>::type> delegate,\n    const T& x_0,\n    const T& x_1,\n    point<T>& p_0,\n    point<T>& p_1,\n    unsigned n_max\n){\n    {\n        p_0 = create_point<T>(x_0,delegate);\n        p_1 = create_point<T>(x_1,delegate);\n    }\n    return search_reflection(\n        x_min,\n        x_max,\n        delegate,\n        p_0,\n        p_1,\n        n_max\n    );\n}\n\n// TODO theck that\n// T = remove_const< remove_reference< D> ::type >::type ::value_type\ntemplate<typename D,typename T> // D = const E& or E\nunsigned search_reflection_dist(\n    const T& x_min,\n    const T& x_max,\n    const D& dist,\n    const T& x_0,\n    const T& x_1,\n    ars::point<T>& p_0,\n    ars::point<T>& p_1,\n    unsigned n_max\n){\n    typedef ars::function::adaptor<const D&> fnal_t;\n    typedef typename ars::function::signature<T>::type   signature;\n    typedef boost::function<signature>                  delegate_t;\n    fnal_t fnal(dist);\n\n    return search_reflection<T>(\n        x_min,\n        x_max,\n        fnal, //automatic conversion\n        x_0,\n        x_1,\n        p_0,\n        p_1,\n        n_max\n    );\n}\n\n\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "b174c3b968800d50243f75ed5f9fb9d4b123ae51", "size": 4561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/search_reflection.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/search_reflection.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/search_reflection.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": 27.6424242424, "max_line_length": 79, "alphanum_fraction": 0.5178688884, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5812652778623615}}
{"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_PSB_INCLUDE\n#define ITL_PSB_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/itl/utility/exception.hpp>\n\nnamespace itl {\n\n/// Update of Hessian matrix for e.g. Quasi-Newton by Powell's symmetric Broyden formula\nstruct psb\n{\n    /// \\f$ H_{k+1}=B_{k+1}^{-1}=H_k+\\frac{(y_k-H_k\\cdot s_k)s_k^T+s_k(y_k-H_k\\cdot s_k)^T}{s_k^T\\cdot s_k}-\\frac{(y_k-H_k\\cdot s_k)^T\\cdot s_k}{(s_k^ts_k)^2}s_k\\cdot s_k^T \\f$\n    template <typename Matrix, typename Vector>\n    void operator() (Matrix& H, const Vector& y, const Vector& s)\n    {\n\ttypedef typename mtl::Collection<Vector>::value_type value_type;\n\tassert(num_rows(H) == num_cols(H));\n\tVector     a(s - H * y);\n\tvalue_type gamma= 1 / dot (y, y);\n        MTL_THROW_IF(gamma == 0.0, unexpected_orthogonality());\n    \n        H+= gamma * a * trans(y) + gamma * y * trans(a) - dot(a, y) * gamma * gamma * y * trans(y);\n   }\n};\n\n\n\n} // namespace itl\n\n#endif // ITL_PSB_INCLUDE\n\n", "meta": {"hexsha": "304da7790cf69582617efd2847b984246e3b76ec", "size": 1452, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/updater/psb.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/itl/updater/psb.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/itl/updater/psb.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": 32.2666666667, "max_line_length": 176, "alphanum_fraction": 0.6783746556, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5812567405380502}}
{"text": "#include <iostream>\n#include <vector>\n#include <mtl/utility/tag.hpp>\n#include <mtl/matrix/dense2D.hpp>\n#include <mtl/fractalu.hpp>\n#include <mtl/utility/property_map.hpp>\n#include <mtl/mat_vec_mult.hpp>\n#include <boost/timer.hpp>\n\n#include <boost/mpl/if.hpp>\n\nint main (int argc, char** argv) {\n  using namespace std;\n  using namespace mtl;\n\n  if (argc < 2) {\n    cout << \"syntax: mat_vec_mult_timing size\\n\"; exit(1); }\n\n  typedef double                                val_t;\n  typedef dense2D<val_t, row_major, c_index>    matrix_type; \n  typedef fractalu<val_t, 64>                   umatrix_type; \n  std::size_t     size(atoi(argv[1]));\n  matrix_type     matrix(dim_type(size, size), 1);\n  std::vector<val_t>  vin(size, 1), vout(size, 7);\n  umatrix_type    umatrix(dim_type(size, size), 1);\n  \n  cout << \"vin is mtl type: \" << is_mtl_type<std::vector<int> >::value\n       << \" is fortran indexed: \" <<  is_fortran_indexed<std::vector<int> >::value << endl;\n  cout << \"matrix is mtl type: \" << is_mtl_type<matrix_type>::value\n       << \" is fortran indexed: \" <<  is_fortran_indexed<matrix_type>::value << endl;\n\n  // cout << \"matrix is boost::is_same<typename indexing<T>::type, c_index>::value\n\n  boost::timer ti;\n//   mat_vec_mult(matrix, vin, vout);\n//   cout << ti.elapsed() << \" s\\n\";\n//   for (size_t i= 0; i < size; i++) \n//     if (vout[i] != (int) size) cout << \"vout[\" << i << \"] is \" << vout[i] << endl;\n\n//   ti.restart();\n  dense_mat_vec_mult(matrix, vin, vout);\n  cout << ti.elapsed() << \" s with dense matrix vector product\\n\";\n  for (size_t i= 0; i < size; i++) \n    if (vout[i] != (int) size) cout << \"vout[\" << i << \"] is \" << vout[i] << endl;\n\n  ti.restart();\n  mat_vec_mult(umatrix, vin, vout);\n  cout << ti.elapsed() << \" s\\n\";\n  for (size_t i= 0; i < size; i++) \n    if (vout[i] != (int) size) cout << \"vout[\" << i << \"] is \" << vout[i] << endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "f056f5d871c92d4f88fa3688fff51d2f2761e964", "size": 1889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/mat_vec_mult_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/experimental/mat_vec_mult_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/experimental/mat_vec_mult_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": 34.9814814815, "max_line_length": 91, "alphanum_fraction": 0.592376919, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5811804572368725}}
{"text": "/* Copyright (c) 2018-2019 the `graphkernels` developers\n * All rights reserved.\n */\n\n#include \"rest.h\"\n\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include <algorithm>\n#include <utility>\n\nusing std::vector;\nusing std::pair;\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing Eigen::SparseMatrix;\nusing Eigen::VectorXd;\n\nauto order_by_labels(const vector<int>& labels) {\n    vector<pair<int, int>> map;\n    map.reserve(labels.size());\n\n    auto idx = 0;\n    for (const auto label : labels) {\n        map.emplace_back(label, idx++);\n    }\n\n    sort(map.begin(), map.end());\n    return map;\n}\n\nauto compute_valid_vertex_pairs(\n        const vector<pair<int, int>>& map1,\n        const vector<pair<int, int>>& map2) {\n    vector<pair<int, int>> pairs;\n    pairs.reserve(map1.size() * map2.size());\n\n    const auto comp = [](const auto& p_a, const auto& p_b){\n        return p_a.first < p_b.first;\n    };\n\n    auto p = map2.cbegin();  // Memoize low limit (see below).\n    for (auto i1 = map1.cbegin(); i1 != map1.cend(); ) {\n        // Find range of map2 that contains vertices labelled \"label1\".\n        auto [eq_cbegin, eq_cend] = std::equal_range(p, map2.cend(), *i1, comp);\n\n        // Iterate over all equal values in map1.\n        const auto label1 = i1->first;\n        do {\n            const auto num1 = i1->second;\n\n            // Create all pairs between vertex of map1 and range of map2.\n            for (auto p = eq_cbegin; p != eq_cend; ++p) {\n                pairs.emplace_back(num1, p->second);\n            }\n\n            ++i1;\n        } while (i1 != map1.cend() && i1->first == label1);\n\n        // All vertices with that label have been exhausted in both maps.\n        p = eq_cend;\n    }\n\n    sort(pairs.begin(), pairs.end());\n    return pairs;\n}\n\nauto productAdjacency(\n        const MatrixXi& e1,\n        const MatrixXi& e2,\n        const vector<int>& v1_label,\n        const vector<int>& v2_label) {\n    // Step 1: Order vertices by labels; compute all valid vertex pairs\n    const auto pairs = compute_valid_vertex_pairs(\n            order_by_labels(v1_label),\n            order_by_labels(v2_label));\n\n    // Step 2: Compute new labels for vertices of the product graph.\n    Eigen::Matrix<int, -1, -1, Eigen::RowMajor> H(v1_label.size(), v2_label.size());\n\n    auto next_label = 0;\n    for (const auto& [v1, v2] : pairs) {\n        H(v1, v2) = next_label++;\n    }\n\n    // Step 3: Compute the adjacency matrix of the direct product graph.\n    vector<Eigen::Triplet<double>> v;\n    for (auto i = 0; i < e1.rows(); ++i) {\n        const auto e1_s = e1(i, 0);\n        const auto e1_t = e1(i, 1);\n        const auto e1_label = e1(i, 2);\n\n        for (auto j = 0; j < e2.rows(); ++j) {\n            if (e1_label == e2(j, 2)) {\n                const auto e2_s = e2(j, 0);\n                const auto e2_t = e2(j, 1);\n\n                if (v1_label[e1_s] == v2_label[e2_s]\n                &&  v1_label[e1_t] == v2_label[e2_t]\n                   ) {\n                    v.emplace_back(H(e1_s, e2_s), H(e1_t, e2_t), 1.0);\n                    v.emplace_back(H(e1_t, e2_t), H(e1_s, e2_s), 1.0);\n                }\n\n                if (v1_label[e1_s] == v2_label[e2_t]\n                &&  v1_label[e1_t] == v2_label[e2_s]\n                   ) {\n                    v.emplace_back(H(e1_s, e2_t), H(e1_t, e2_s), 1.0);\n                    v.emplace_back(H(e1_t, e2_s), H(e1_s, e2_t), 1.0);\n                }\n            }\n        }\n    }\n\n    SparseMatrix<double> Ax(next_label, next_label);\n    Ax.setFromTriplets(v.cbegin(), v.cend());\n\n    return Ax;\n}\n\ndouble geometricRandomWalkKernel(\n        const MatrixXi& e1,\n        const MatrixXi& e2,\n        const vector<int>& v1_label,\n        const vector<int>& v2_label,\n        double lambda,\n        int max_iterations,\n        double eps) {\n    // compute the adjacency matrix Ax of the direct product graph\n    const SparseMatrix<double> Lx = lambda * productAdjacency(\n            e1, e2, v1_label, v2_label);\n\n    // inverse of I - lambda * Ax by fixed-poInt iterations\n    const auto n_rows = Lx.rows();\n    const VectorXd ones = VectorXd::Ones(n_rows);\n    auto x = ones;\n    VectorXd x_pre = VectorXd::Zero(n_rows);\n\n    auto count = 0;\n    do {\n        x_pre = x;\n        x = ones + Lx * x_pre;\n        ++count;\n    } while (count <= max_iterations && (x - x_pre).squaredNorm() > eps);\n    return x.sum();\n}\n\nMatrixXd CalculateGeometricRandomWalkKernelPy(\n        const vector<MatrixXi>& E,\n        const vector<vector<int>>& V_label,\n        double lambda,\n        int max_iterations,\n        double eps) {\n    MatrixXd K(V_label.size(), V_label.size());\n\n    for (auto j = 0; j < V_label.size(); ++j) {\n        for (auto i = 0; i <= j; ++i) {\n            K(i, j) = geometricRandomWalkKernel(\n                    E[i], E[j], V_label[i], V_label[j], lambda,\n                    max_iterations, eps);\n        }\n    }\n\n    return K.selfadjointView<Eigen::Upper>();\n}\n\ndouble exponentialRandomWalkKernel(\n        const MatrixXi& e1,\n        const MatrixXi& e2,\n        const vector<int>& v1_label,\n        const vector<int>& v2_label,\n        double beta) {\n    // compute the adjacency matrix Ax of the direct product graph\n    const MatrixXd Ax = productAdjacency(e1, e2, v1_label, v2_label);\n\n    return Ax.exp().sum();\n}\n\nMatrixXd CalculateExponentialRandomWalkKernelPy(\n        const vector<MatrixXi>& E,\n        const vector<vector<int>>& V_label,\n        double beta) {\n    MatrixXd K(V_label.size(), V_label.size());\n\n    for (auto j = 0; j < V_label.size(); ++j) {\n        for (auto i = 0; i <= j; ++i) {\n            K(i, j) = exponentialRandomWalkKernel(\n                    E[i], E[j], V_label[i], V_label[j], beta);\n        }\n    }\n\n    return K.selfadjointView<Eigen::Upper>();\n}\n\ndouble kstepRandomWalkKernel(\n        const MatrixXi& e1,\n        const MatrixXi& e2,\n        const vector<int>& v1_label,\n        const vector<int>& v2_label,\n        const vector<double>& lambda_list) {\n    // compute the adjacency matrix Ax of the direct product graph\n    const SparseMatrix<double> Ax = productAdjacency(e1, e2, v1_label, v2_label);\n\n    // prepare identity matrix\n    const auto n_rows = Ax.rows();\n    SparseMatrix<double> I{n_rows, n_rows};\n    I.setIdentity();\n\n    auto Sum = SparseMatrix<double>{n_rows, n_rows};\n    Sum.setZero();\n\n    // Compute products until k using:\n    // https://en.wikipedia.org/wiki/Horner%27s_method\n    auto k = lambda_list.size();\n    while (k-- > 0) {\n        Sum = (Sum * Ax) + lambda_list[k] * I;\n    }\n\n    return Sum.sum();\n}\n\nMatrixXd CalculateKStepRandomWalkKernelPy(\n        const vector<MatrixXi>& E,\n        const vector<vector<int>>& V_label,\n        const vector<double>& par) {\n    MatrixXd K(V_label.size(), V_label.size());\n\n    for (auto j = 0; j < V_label.size(); ++j) {\n        for (auto i = 0; i <= j; ++i) {\n            K(i, j) = kstepRandomWalkKernel(\n                    E[i], E[j], V_label[i], V_label[j], par);\n        }\n    }\n\n    return K.selfadjointView<Eigen::Upper>();\n}\n", "meta": {"hexsha": "16544e08e344a50f33e35d04d08464a2f4e98b75", "size": 7031, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphkernels/cppkernels/rest.cpp", "max_stars_repo_name": "Renelvon/GraphKernels", "max_stars_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graphkernels/cppkernels/rest.cpp", "max_issues_repo_name": "Renelvon/GraphKernels", "max_issues_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphkernels/cppkernels/rest.cpp", "max_forks_repo_name": "Renelvon/GraphKernels", "max_forks_repo_head_hexsha": "68d2006ff29363ee1f5435e7b2bb158f6770433a", "max_forks_repo_licenses": ["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.4184100418, "max_line_length": 84, "alphanum_fraction": 0.5684824349, "num_tokens": 1912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5811804507471794}}
{"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 \"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, 0.25);\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        {1, -0.9},\n    };\n    ARSeq seq(coeff, 100);\n    std::vector<my_float> v;\n    for (auto i = 0; i < 1; i++) {\n        v.push_back(u(gen));\n    }\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    std::cout << \"After 100 iterations\\n\";\n    seq.print_past_vals();\n    \n    for (auto i = 0; i < 900; i++) {\n        seq.next();\n    }\n    std::cout << \"After 1000 iterations\\n\";\n    seq.print_past_vals();\n\n    for (auto i = 0; i < 9000; i++) {\n        seq.next();\n    }\n    std::cout << \"After 10000 iterations\\n\";\n    seq.print_past_vals();\n    \n    return 0;\n}\n", "meta": {"hexsha": "8cd9d18562a142f02556c80d123f29831ec33656", "size": 1417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gen-data/test/test-gen.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/test-gen.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/test-gen.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": 23.6166666667, "max_line_length": 82, "alphanum_fraction": 0.6146788991, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5811804501068684}}
{"text": "#include <string>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nstring scan_match_file = \"./scan_match.txt\";\nstring odom_file = \"./odom.txt\";\n\nint main(int argc, char **argv)\n{\n    // 放置激光雷达的时间和匹配值 t_s s_x s_y s_th\n    vector<vector<double>> s_data;\n    // 放置轮速计的时间和左右轮角速度 t_r w_L w_R\n    vector<vector<double>> r_data;\n\n    ifstream fin_s(scan_match_file);\n    ifstream fin_r(odom_file);\n    if (!fin_s || !fin_r)\n    {\n        cerr << \"请在有scan_match.txt和odom.txt的目录下运行此程序\" << endl;\n        return 1;\n    }\n\n    // 读取激光雷达的匹配值\n    while (!fin_s.eof())\n    {\n        double s_t, s_x, s_y, s_th;\n        fin_s >> s_t >> s_x >> s_y >> s_th;\n        s_data.push_back(vector<double>({s_t, s_x, s_y, s_th}));\n    }\n    fin_s.close();\n\n    // 读取两个轮子的角速度\n    while (!fin_r.eof())\n    {\n        double t_r, w_L, w_R;\n        fin_r >> t_r >> w_L >> w_R;\n        r_data.push_back(vector<double>({t_r, w_L, w_R}));\n    }\n    fin_r.close();\n\n    // 第一步：计算中间变量J_21和J_22\n    Eigen::MatrixXd A;\n    Eigen::VectorXd b;\n    // 设置数据长度\n    A.conservativeResize(5000, 2);\n    b.conservativeResize(5000);\n    A.setZero();\n    b.setZero();\n\n    size_t id_r = 0;\n    size_t id_s = 0;\n    double last_rt = r_data[0][0];\n    double w_Lt = 0;\n    double w_Rt = 0;\n    while (id_s < 5000)\n    {\n        // 激光的匹配信息\n        const double &s_t = s_data[id_s][0];\n        const double &s_th = s_data[id_s][3];\n        // 里程计信息\n        const double &r_t = r_data[id_r][0];\n        const double &w_L = r_data[id_r][1];\n        const double &w_R = r_data[id_r][2];\n        ++id_r;\n        // 在2帧激光匹配时间内进行里程计角度积分\n        if (r_t < s_t)\n        {\n            double dt = r_t - last_rt;\n            w_Lt += w_L * dt;\n            w_Rt += w_R * dt;\n            last_rt = r_t;\n        }\n        else\n        {\n            double dt = s_t - last_rt;\n            w_Lt += w_L * dt;\n            w_Rt += w_R * dt;\n            last_rt = s_t;\n            // 填充A, b矩阵\n            //TODO: (3~5 lines)\n            A(id_s, 0) = w_Lt;\n            A(id_s, 1) = w_Rt;\n            b(id_s) = s_th;\n\n            //end of TODO\n            w_Lt = 0;\n            w_Rt = 0;\n            ++id_s;\n        }\n    }\n    // 进行最小二乘求解\n    Eigen::Vector2d J21J22;\n    //TODO: (1~2 lines)\n    J21J22 = A.householderQr().solve(b);\n\n    //end of TODO\n    const double &J21 = J21J22(0);\n    const double &J22 = J21J22(1);\n    cout << \"J21: \" << J21 << endl;\n    cout << \"J22: \" << J22 << endl;\n\n    // 第二步，求解轮间距b\n    Eigen::VectorXd C;\n    Eigen::VectorXd S;\n    // 设置数据长度\n    C.conservativeResize(10000);\n    S.conservativeResize(10000);\n    C.setZero();\n    S.setZero();\n\n    id_r = 0;\n    id_s = 0;\n    last_rt = r_data[0][0];\n    double th = 0;\n    double cx = 0;\n    double cy = 0;\n    while (id_s < 5000)\n    {\n        // 激光的匹配信息\n        const double &s_t = s_data[id_s][0];\n        const double &s_x = s_data[id_s][1];\n        const double &s_y = s_data[id_s][2];\n        // 里程计信息\n        const double &r_t = r_data[id_r][0];\n        const double &w_L = r_data[id_r][1];\n        const double &w_R = r_data[id_r][2];\n        ++id_r;\n        // 在2帧激光匹配时间内进行里程计位置积分\n        if (r_t < s_t)\n        {\n            double dt = r_t - last_rt;\n            cx += 0.5 * (-J21 * w_L * dt + J22 * w_R * dt) * cos(th);\n            cy += 0.5 * (-J21 * w_L * dt + J22 * w_R * dt) * sin(th);\n            th += (J21 * w_L + J22 * w_R) * dt;\n            last_rt = r_t;\n        }\n        else\n        {\n            double dt = s_t - last_rt;\n            cx += 0.5 * (-J21 * w_L * dt + J22 * w_R * dt) * cos(th);\n            cy += 0.5 * (-J21 * w_L * dt + J22 * w_R * dt) * sin(th);\n            th += (J21 * w_L + J22 * w_R) * dt;\n            last_rt = s_t;\n            // 填充C, S矩阵\n            //TODO: (4~5 lines)\n            C(2 * id_s) = cx;\n            C(2 * id_s + 1) = cy;\n            S(2 * id_s) = s_x;\n            S(2 * id_s + 1) = s_y;\n\n            //end of TODO\n            cx = 0;\n            cy = 0;\n            th = 0;\n            ++id_s;\n        }\n    }\n    // 进行最小二乘求解，计算b, r_L, r_R\n    double b_wheel;\n    double r_L;\n    double r_R;\n    //TODO: (3~5 lines)\n    b_wheel = C.householderQr().solve(S)(0);\n    r_L = -b_wheel * J21J22(0);\n    r_R = b_wheel * J21J22(1);\n\n    //end of TODO\n    cout << \"b: \" << b_wheel << endl;\n    cout << \"r_L: \" << r_L << endl;\n    cout << \"r_R: \" << r_R << endl;\n\n    cout << \"参考答案：轮间距b为0.6m左右，两轮半径为0.1m左右\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "f1466822ee5ba6564671a1145bebebcf95548ef4", "size": 4513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/HW2/odom_calib/odom_calib.cpp", "max_stars_repo_name": "SS47816/Lidar-SLAM", "max_stars_repo_head_hexsha": "91e2f6deec7b941b51cedde61d53ca9effcbb973", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-22T12:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T12:23:45.000Z", "max_issues_repo_path": "Homeworks/HW2/odom_calib/odom_calib.cpp", "max_issues_repo_name": "SS47816/Lidar-SLAM", "max_issues_repo_head_hexsha": "91e2f6deec7b941b51cedde61d53ca9effcbb973", "max_issues_repo_licenses": ["MIT"], "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/HW2/odom_calib/odom_calib.cpp", "max_forks_repo_name": "SS47816/Lidar-SLAM", "max_forks_repo_head_hexsha": "91e2f6deec7b941b51cedde61d53ca9effcbb973", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-04T15:42:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T15:42:38.000Z", "avg_line_length": 24.527173913, "max_line_length": 69, "alphanum_fraction": 0.4755151784, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5810399421811265}}
{"text": "// Cpush+ version 0.10\n// defines a class for particle tracks\n// in a uniform magnetic field, with\n// a simple leapfrog pushing method.\n\n#include <iostream>\n#include <fstream>\n#include <time.h>\n\n#include <string>\n#include <cmath>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Vector3d eigvec;\ntypedef Matrix3d eigmat;\n\nconst double pi = 3.1415926;\nconst eigmat I  = eigmat::Identity();\n\n// particle track class\nclass track{\npublic:\n  // initialise track properties\n  double mass, charge;\n\n  // object constructor\n  track(string);\n\n  // field interpolation method\n  eigmat interpolate(eigvec x, double step){\n    // retrieve vector field\n    eigvec B_ = eigvec(0,0,1);\n\n    // compute magnetic rotation map\n    eigmat hatmap;\n    hatmap << +0,     -B_[2], +B_[1],\n              +B_[2], +0,     -B_[0],\n              -B_[1], +B_[0], +0;\n    hatmap *= (charge * step) / (2 * mass);\n    return hatmap;\n  }\n\n  // leapfrog pushing method\n  int leapfrog(double step, int nsteps){\n    // set transverse velocity\n    double eV = 1E-03;\n    double vx = sqrt((2 * eV * abs(charge))/mass);\n\n    // initialise dynamic variables\n    eigvec x_ = eigvec(0,  0, 0);\n    eigvec v_ = eigvec(vx, 0, 0);\n\n    // backwards half-step the velocity\n    eigmat hatmap = -(1./2.) * interpolate(x_, step);\n    v_  = (I + hatmap).inverse() * (I - hatmap) * v_;\n\n    // open a stream to write to file\n    fstream track_io (\"my_track.bin\", ios::out | ios::binary);\n    if (track_io.is_open()){\n\n      // particle pushing loop\n      for (int n = 0; n <= nsteps; n++){\n\n        // write the position & velocity to file\n        track_io << n << ' ' << ' ' << x_[0] << ' ' << x_[1] << ' ' << x_[2];\n        track_io      << ' ' << ' ' << v_[0] << ' ' << v_[1] << ' ' << v_[2] << endl;\n\n        // update the velocity and position\n        hatmap = interpolate(x_, step);\n        v_  = (I + hatmap).inverse() * (I - hatmap) * v_;\n        x_ += v_ * step;\n      }\n    }\n    return 0;\n  }\n};\n\n// track object constructor\ntrack::track(string ptype){\n  if ((ptype == \"antiproton\") || (ptype == \"pbar\")){\n    mass   = +1.67E-27;\n    charge = -1.60E-19;\n  }\n\n  if ((ptype == \"positron\") || (ptype == \"e+\")){\n    mass   = +9.11E-31;\n    charge = +1.60-19;\n  }\n}\n\nint main(){\n  // example of the class\n  track my_track (\"pbar\");\n  double step = 6.56E-09;\n  my_track.leapfrog(step, 10000);\n}\n", "meta": {"hexsha": "d65927ae581e2ffe6f44bded465370525a431c3a", "size": 2377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "track.cpp", "max_stars_repo_name": "markojn/Cpush", "max_stars_repo_head_hexsha": "685323e644adcb5330f911ed8d0765e415681441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "track.cpp", "max_issues_repo_name": "markojn/Cpush", "max_issues_repo_head_hexsha": "685323e644adcb5330f911ed8d0765e415681441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "track.cpp", "max_forks_repo_name": "markojn/Cpush", "max_forks_repo_head_hexsha": "685323e644adcb5330f911ed8d0765e415681441", "max_forks_repo_licenses": ["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.77, "max_line_length": 85, "alphanum_fraction": 0.5687841817, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5810399404827516}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nusing namespace std;\n\nint dijkstra_dist(const weighted_graph &G, int s, int t) {\n  int n = boost::num_vertices(G);\n  std::vector<int> dist_map(n);\n\n  boost::dijkstra_shortest_paths(G, s,\n    boost::distance_map(boost::make_iterator_property_map(\n      dist_map.begin(), boost::get(boost::vertex_index, G))));\n\n  return dist_map[t];\n}\n\nvoid solve()\n{\n  int n; cin >> n;\n  int m; cin >> m;\n  int s; cin >> s;\n  int a; cin >> a;\n  int b; cin >> b;\n\n  \n  vector<weighted_graph> graphs(s, weighted_graph(n));\n  vector<weight_map> weights(s);\n  for (int i = 0; i < s; ++i) {\n    weights[i] = boost::get(boost::edge_weight, graphs[i]);\n  }\n  \n  int u, v, w;\n  for (int i = 0; i < m; ++i) {\n    cin >> u;\n    cin >> v;\n    for (int j = 0; j < s; ++j) {\n      cin >> w;\n      boost::add_edge(u, v, w, graphs[j]);\n    }\n  }\n\n  int h;\n  for (int i = 0; i < s; ++i) {\n    cin >> h;\n  }\n\n  weighted_graph G(n);\n\n  for (int i = 0; i < s; ++i) {\n    vector<edge_desc> mst;\n    boost::kruskal_minimum_spanning_tree(graphs[i], back_inserter(mst));\n    for (auto e : mst) {\n      int u = boost::source(e, graphs[i]);\n      int v = boost::target(e, graphs[i]);\n      boost::add_edge(u, v, weights[i][e], G);\n    }\n  }\n  \n  cout << dijkstra_dist(G, a, b) << endl;\n\n}\n\nint main() {\n  int t; cin >> t;\n  for (int i = 0; i < t; ++i) {\n    solve();\n  }\n}", "meta": {"hexsha": "d8138fb6e2924aa1bacbb1a8cafa4773e47b98ad", "size": 1965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ant_challenge.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/ant_challenge.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/ant_challenge.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 24.5625, "max_line_length": 87, "alphanum_fraction": 0.6188295165, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5810256039619806}}
{"text": "//\n//  quadratic_polynomial.cpp\n//  BGV-Adder\n//\n//  Created by Andris on 27/10/2020.\n//  Copyright © 2020 RUG. All rights reserved.\n//\n\n#include \"quadratic_polynomial.hpp\"\n#include <helib/FHE.h>\n#include <NTL/ZZX.h>\n#include <NTL/tools.h>\n\nusing helib::Ctxt;\n\nlong quadratic_polynomial(int16_t aVal, int16_t bVal, int16_t cVal, int16_t xVal) {\n    long k = 128; // Security parameter\n    long L = 128; // Number of levels in the modulus default is 16\n    long c = 3; // Nr of columns in key switch matrix.\n    long w = 64; // secret key hamming weight\n    \n    // Change to 65537 for noise warning. (Always fun times)\n    // Compensate for that by setting L = 128. (Increase modchain basically)\n    // Set P to 65537 and L to 32 to showcase decryption failures.\n    \n    long p = 65537; // plaintext base default = 1021\n    long d = 0; // Degree of field extension\n    long r = 1; // hensel lifting\n    \n    // Determine a value for m\n    auto m = helib::FindM(k, L, c, p, d, 0, 0);\n    // Setup context\n    auto context = helib::Context(m, p, r);\n    // Build mod chain\n    helib::buildModChain(context, L, c);\n    \n    \n    // Generating secret key and public key\n    NTL::ZZX encryption_polynomial = context.alMod.getFactorsOverZZ()[0];\n    auto secretKey = helib::SecKey(context);\n    secretKey.GenSecKey();\n    const helib::PubKey& publicKey = secretKey;\n       \n    // Initialize ciphertexts\n    Ctxt aVal_ciphertext = Ctxt(publicKey);\n    Ctxt bVal_ciphertext = Ctxt(publicKey);\n    Ctxt cVal_ciphertext = Ctxt(publicKey);\n    Ctxt xVal_ciphertext = Ctxt(publicKey);\n\n    \n    // Plaintext must be encrypted as a polynomial using zzx api.\n    publicKey.Encrypt(aVal_ciphertext, NTL::ZZX(aVal));\n    publicKey.Encrypt(bVal_ciphertext, NTL::ZZX(bVal));\n    publicKey.Encrypt(cVal_ciphertext, NTL::ZZX(cVal));\n    publicKey.Encrypt(xVal_ciphertext, NTL::ZZX(xVal));\n\n    \n    // Apply operations on the ciphertexts.\n    \n    aVal_ciphertext *= xVal_ciphertext;\n    aVal_ciphertext *= xVal_ciphertext;\n    bVal_ciphertext *= xVal_ciphertext;\n    \n    aVal_ciphertext += bVal_ciphertext;\n    aVal_ciphertext += cVal_ciphertext;\n    \n    Ctxt cipherResult = aVal_ciphertext;\n\n    // Decrypt the results using secret key and convert back from\n    // polynomial representation to numeric.\n    long return_value = 0;\n    NTL::ZZX plaintext_result;\n    NTL::ZZX zzx;\n    secretKey.Decrypt(zzx, cipherResult);\n    conv(return_value, zzx[0]);\n    if (return_value > p / 2) {\n        return_value += (-1 * p);\n    }\n\n    return return_value;\n}\n", "meta": {"hexsha": "d388cfc2bc3804ccffbc5afdd2f3157d923f5de9", "size": 2539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGV-Adder/Algorithms/QuadraticPolynomials/quadratic_polynomial.cpp", "max_stars_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_stars_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BGV-Adder/Algorithms/QuadraticPolynomials/quadratic_polynomial.cpp", "max_issues_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_issues_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BGV-Adder/Algorithms/QuadraticPolynomials/quadratic_polynomial.cpp", "max_forks_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_forks_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9634146341, "max_line_length": 83, "alphanum_fraction": 0.6679795195, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5810059524855313}}
{"text": "#include <iostream>\n#include <math.h>\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#include \"../include/Filter.h\"\n\n#include \"../include/Robot.h\"\n#include \"../include/Odom.h\"\n#include \"../include/Imu.h\"\n#include \"../include/Gps.h\"\n\nWeightingFilter weightingFilter;\nWeightingFilter* pweightingFilter;\n\n\nKalmanFilter kalmanFilter;\nKalmanFilter *pkalmanFilter;\n\n// Constructor\nKalmanFilter::KalmanFilter()\n{\n    is_initialized_ = false;\n    lastTimeStamp_ = 0;\n    nowTimeStamp_ = 0;\n    deltaTime_ = 0;\n}\n\n//Destructor\nKalmanFilter::~KalmanFilter()\n{\n    delete pkalmanFilter;\n}\n\nvoid KalmanFilter::Initialization()\n{\n    lastTimeStamp_ = nowTimeStamp_ = getSysTime();\n    \n    Eigen::VectorXf x_in(5,1);\n    x_in << 0, \n            0,\n            0, \n            0, \n            0;\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\n    //process covariance matrix\n    Eigen::MatrixXf Q_in(5,5);\n    Q_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    SetQ(Q_in);\n\n    //Observation\n    Eigen::VectorXf z_in(3,1);\n    z_in << 0.0,\n            0.0, \n            0.0;\n\n\n    //measurement matrix\n    Eigen::MatrixXf H_in(3,5);\n    H_in << 0.0, 0.0, 0.0, 1.0, 0.0,\n            0.0, 0.0, 0.0, 0.0, 1.0,\n            0.0, 0.0, 0.0, 0.0, 1.0;\n    SetH(H_in);\n    \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\n    is_initialized_ = true;\n\n}\n\nvoid KalmanFilter::SetX(Eigen::VectorXf x_in)\n{\n    x_ = x_in;\n}\n\nbool KalmanFilter::GetIsInitialized()\n{\n    return is_initialized_;\n}\n\nvoid KalmanFilter::SetF(Eigen::MatrixXf F_in)\n{\n    F_ = F_in;\n}\n\nvoid KalmanFilter::SetP(Eigen::MatrixXf P_in)\n{\n    P_ = P_in;\n}\n\nvoid KalmanFilter::SetQ(Eigen::MatrixXf Q_in)\n{\n    Q_ = Q_in;\n}\n\nvoid KalmanFilter::SetH(Eigen::MatrixXf H_in)\n{\n    H_ = H_in;\n}\n\nvoid KalmanFilter::SetR(Eigen::MatrixXf R_in)\n{\n    R_ = R_in;\n}\n\nvoid KalmanFilter::Prediction(float d_t) //预测\n{\n    float x_k, y_k, theta_k, v_k, w_k;\n    x_k = x_[0];\n    y_k = x_[1];\n    theta_k = x_[2];\n    v_k = x_[3];\n    w_k = x_[4];\n\n    x_ << x_k + v_k*d_t*cos(theta_k),y_k + v_k*d_t*sin(theta_k), theta_k + w_k*d_t, v_k,  w_k;\n    Eigen::MatrixXf F_in(5,5);\n    F_in << 1, 0, 0, d_t*cos(x_[2]), 0,\n            0, 1, 0, d_t*sin(x_[2]), 0,\n            0, 0, 1, 0, d_t,\n            0, 0, 0, 1, 0,\n            0, 0, 0, 0, 1;\n\n    kalmanFilter.SetF(F_in);\n    Eigen::MatrixXf Ft = F_.transpose();\n    P_ = F_ * P_ * Ft + Q_;\n}\n/*\nvoid KalmanFilter::CalculateJacobianMatrix()\n{\n    Eigen::MatrixXf Hj(4,4);\n\n    //get state paraeters\n    float px = x_(0);\n    float py = x_(1);\n    float vx = x_(2);\n    float vy = x_(3);\n\n    //pre-compute a set of terms to avoid repeated calculation\n    Hj << 1.0, 0.0, 0.0, 0.0,   //GPS 与 ODOM与IMU加权平均 后的结果进行再次融合\n          0.0, 1.0, 0.0, 0.0,\n          0.0, 0.0, 0.0, 0.0,\n          0.0, 0.0, 0.0, 0.0;\n\n    SetH(Hj);\n}\n*/\nvoid KalmanFilter::KFUpdate(const Eigen::VectorXf &z)\n{\n    int size = x_.size();\n    std::cout << size << std::endl;\n    Eigen::VectorXf y = z - H_ * x_;\n    Eigen::MatrixXf S = H_ * P_ * H_.transpose() + R_;\n    Eigen::MatrixXf K = P_ * H_.transpose() * S.inverse();\n    x_ = x_ + (K * y);\n    Eigen::MatrixXf I = Eigen::MatrixXf::Identity(size, size);\n    P_ = (I - K * H_) * P_;\n    //std::cout << \"x_:\" << std::endl << x_ << std::endl;\n\n}\n/*\nvoid KalmanFilter::EKFUpdate(const Eigen::VectorXf &z)\n{   \n   \n    // Eigen::VectorXf h = Eigen::VectorXf(4);\n    CalculateJacobianMatrix(); \n\n    Eigen::VectorXf y = z - H_ * x_;\n    Eigen::MatrixXf Ht = H_.transpose();\n    Eigen::MatrixXf S = H_ * P_ * Ht + R_;\n    Eigen::MatrixXf Si = S.inverse();\n    Eigen::MatrixXf K = P_ * Ht * Si;\n\n    x_ = x_ + (K * y);\n\n    int x_size = x_.size();\n    Eigen::MatrixXf I = Eigen::MatrixXf::Identity(x_size, x_size);\n    P_ = (I - K * H_) * P_;\n\tstd::cout << \"x_:\" << std::endl << x_ <<std::endl;\n\n}\n*/\nEigen::VectorXf KalmanFilter::GetX()\n{\n    return x_;\n}\n\nvoid KalmanFilter::setLastTimeStamp(const long int lastTimeStamp)\n{\n    this->lastTimeStamp_ = lastTimeStamp;\n}\n\nvoid KalmanFilter::setNowTimeStamp(const long int nowTimeStamp )\n{\n    this->nowTimeStamp_ = nowTimeStamp;\n}\nvoid KalmanFilter::setDeltaTime(const long int deltaTime)\n{\n    this->deltaTime_ = deltaTime;\n}\n\nvoid KalmanFilter::getLastTimeStamp(long int& lastTimeStamp)\n{\n    lastTimeStamp = this->lastTimeStamp_;\n}\nvoid KalmanFilter::getNowTimeStamp(long int& nowTimeStamp)\n{\n    nowTimeStamp = this->nowTimeStamp_;\n}\nvoid KalmanFilter::getDeltaTime(long int& deltaTime)\n{\n    deltaTime = this->deltaTime_;\n}\n\n\nWeightingFilter::WeightingFilter()\n{\n\n}\n\nWeightingFilter::~WeightingFilter()\n{\n    delete pweightingFilter;\n}\n\nvoid WeightingFilter::WeightingFilterUpdate()  //只是进行位置融合\n{\n    float odom_x, odom_y, odom_theta;\n    float imu_x, imu_y, imu_z, imu_theta;\n    float Roll; //翻滚角\n    float Pitch; //俯仰角\n    float Yaw; //偏航角\n\n    odom.GetPos(odom_x, odom_y, odom_theta);\n    imu.GetPosition( imu_x, imu_y, imu_theta);\n\n    float robot_x, robot_y, robot_theta;\n\n    robot_x = WEIGHT * odom_x + (1- WEIGHT) * imu_x;\n    robot_y = WEIGHT * odom_y + (1- WEIGHT) * imu_y;\n    imu.GetPostureYPR(Roll, Pitch, Yaw);\n    robot_theta = Yaw/57.3;\n    \n    robot.SetRobotPosition(robot_x, robot_y, 0); \n    robot.SetRobotRotation(Roll, Pitch, Yaw);\n    odom.SetPos(robot_x,robot_y,robot_theta);\n    imu.SetPosition(robot_x,robot_y,robot_theta);\n}\n\n\n\n\n\n", "meta": {"hexsha": "3ce18b62f6f4fea2d1afbd1b3a3cd8bbd1f3096e", "size": 5877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Localization_merged/src/Filter.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": "Localization_merged/src/Filter.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": "Localization_merged/src/Filter.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": 21.2166064982, "max_line_length": 94, "alphanum_fraction": 0.5843117237, "num_tokens": 2186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5810059343561196}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n#ifndef KINDR_LINEARALGEBRA_LINEARALGEBRA_HPP_\n#define KINDR_LINEARALGEBRA_LINEARALGEBRA_HPP_\n\n#include <Eigen/SVD>\n\nnamespace kindr {\n//! Linear algebra methods\nnamespace linear_algebra {\n\n/*!\n * \\brief Gets a skew-symmetric matrix from a (column) vector\n * \\param   vec 3x1-matrix (column vector)\n * \\return skew   3x3-matrix\n */\ntemplate<typename PrimType_>\ninline static Eigen::Matrix<PrimType_, 3, 3> getSkewMatrixFromVector(const Eigen::Matrix<PrimType_, 3, 1>& vec) {\n  Eigen::Matrix<PrimType_, 3, 3> mat;\n  mat << 0, -vec(2), vec(1), vec(2), 0, -vec(0), -vec(1), vec(0), 0;\n  return mat;\n}\n\n/*!\n * \\brief Gets a 3x1 vector from a skew-symmetric matrix\n * \\param   matrix 3x3-matrix\n * \\return  column vector (3x1-matrix)\n */\ntemplate<typename PrimType_>\ninline static Eigen::Matrix<PrimType_, 3, 1> getVectorFromSkewMatrix(const Eigen::Matrix<PrimType_, 3, 3>& matrix) {\n  return Eigen::Matrix<PrimType_, 3, 1> (matrix(2,1), matrix(0,2), matrix(1,0));\n}\n\n\n\n/*!\n * \\brief Computes the Moore–Penrose pseudoinverse\n * info: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257\n * \\param a: Matrix to invert\n * \\param result: Result is written here\n * \\param epsilon: Numerical precision (for example 1e-6)\n * \\return true if successful\n */\ntemplate<typename _Matrix_Type_>\nbool static pseudoInverse(const _Matrix_Type_ &a, _Matrix_Type_ &result, double epsilon = std::numeric_limits<typename _Matrix_Type_::Scalar>::epsilon())\n{\n  Eigen::JacobiSVD< _Matrix_Type_ > svd = a.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  typename _Matrix_Type_::Scalar tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs().maxCoeff();\n\n  result = svd.matrixV() * _Matrix_Type_( (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0) ).asDiagonal() * svd.matrixU().adjoint();\n\n  return true;\n}\n\n} // end namespace linear_algebra\n} // end namespace kindr\n\n#endif /* KINDR_LINEARALGEBRA_LINEARALGEBRA_HPP_ */\n", "meta": {"hexsha": "20e67edb6556c4cc6178db669807c6a1d2b10974", "size": 3668, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/linear_algebra/LinearAlgebra.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/linear_algebra/LinearAlgebra.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/linear_algebra/LinearAlgebra.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 43.1529411765, "max_line_length": 182, "alphanum_fraction": 0.7388222465, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.5807898909865932}}
{"text": "/**\n * @file pfasst/quadrature.hpp\n * @since v0.1.0\n */\n#ifndef _PFASST__QUADRATURE_HPP_\n#define _PFASST__QUADRATURE_HPP_\n\n#include <cmath>\n#include <exception>\n#include <vector>\nusing namespace std;\n\n#include <Eigen/Dense>\ntemplate<typename scalar>\nusing Matrix = Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n\n\n#include \"pfasst/config.hpp\"\n#include \"pfasst/interfaces.hpp\"\n#include \"pfasst/quadrature/polynomial.hpp\"\n#include \"pfasst/quadrature/interface.hpp\"\n#include \"pfasst/quadrature/gauss_lobatto.hpp\"\n#include \"pfasst/quadrature/gauss_legendre.hpp\"\n#include \"pfasst/quadrature/gauss_radau.hpp\"\n#include \"pfasst/quadrature/clenshaw_curtis.hpp\"\n#include \"pfasst/quadrature/uniform.hpp\"\n\ntemplate<typename scalar>\nusing Matrix = Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n\nnamespace pfasst\n{\n  /**\n   * Functionality related to computing quadrature nodes and weights.\n   *\n   * @note Please note, that all quadrature nodes are in the range \\\\( [0, 1] \\\\).\n   */\n  namespace quadrature\n  {\n    /**\n     * Instantiates quadrature handler for given number of nodes and type descriptor.\n     *\n     * @tparam precision numerical type of the nodes (e.g. `double`)\n     * @param[in] nnodes number of quadrature nodes\n     * @param[in] qtype type descriptor of the quadrature\n     * @returns instance of pfasst::quadrature::IQuadrature of specified type with desired number\n     *   of nodes\n     * @throws pfasst::ValueError if @p qtype is not a valid quadrature type descriptor\n     */\n    template<typename precision = pfasst::time_precision>\n    shared_ptr<IQuadrature<precision>> quadrature_factory(const size_t nnodes,\n                                                          const QuadratureType qtype)\n    {\n      if (qtype == QuadratureType::GaussLegendre) {\n        return make_shared<GaussLegendre<precision>>(nnodes);\n      } else if (qtype == QuadratureType::GaussLobatto) {\n        return make_shared<GaussLobatto<precision>>(nnodes);\n      } else if (qtype == QuadratureType::GaussRadau) {\n        return make_shared<GaussRadau<precision>>(nnodes);\n      } else if (qtype == QuadratureType::ClenshawCurtis) {\n        return make_shared<ClenshawCurtis<precision>>(nnodes);\n      } else if (qtype == QuadratureType::Uniform) {\n        return make_shared<Uniform<precision>>(nnodes);\n      } else {\n        throw ValueError(\"invalid node type passed to compute_nodes.\");\n        return nullptr;\n      }\n    }\n\n    /**\n     * Compute quadrature nodes for given quadrature type descriptor.\n     *\n     * @tparam precision numerical type of the nodes (e.g. `double`)\n     * @param[in] nnodes number of quadrature nodes to compute\n     * @param[in] qtype type descriptor of the quadrature nodes\n     * @returns std::vector of quadrature nodes of given type\n     *\n     * @see pfasst::quadrature::QuadratureType for valid types\n     * @see pfasst::quadrature::quadrature_factory for further details\n     */\n    template<typename precision = pfasst::time_precision>\n    vector<precision> compute_nodes(size_t nnodes, QuadratureType qtype)\n    {\n      return quadrature_factory<precision>(nnodes, qtype)->get_nodes();\n    }\n\n    /**\n     * Compute weights to interpolate from @p src nodes to @p dst nodes.\n     *\n     * @tparam precision numerical type of the interpolation (e.g. `double`)\n     */\n    template<typename precision = time_precision>\n    Matrix<precision> compute_interp(vector<precision> dst, vector<precision> src)\n    {\n      const size_t ndst = dst.size();\n      const size_t nsrc = src.size();\n\n      Matrix<precision> mat(ndst, nsrc);\n\n      for (size_t i = 0; i < ndst; i++) {\n        for (size_t j = 0; j < nsrc; j++) {\n          precision den = 1.0;\n          precision num = 1.0;\n\n          for (size_t k = 0; k < nsrc; k++) {\n            if (k == j) { continue; }\n            den *= src[j] - src[k];\n            num *= dst[i] - src[k];\n          }\n\n          if (abs(num) > 1e-32) {\n            mat(i, j) = num / den;\n          } else {\n            mat(i, j) = 0.0;\n          }\n        }\n      }\n\n      return mat;\n    }\n  }  // ::pfasst::quadrature\n}  // ::pfasst\n\n#endif  // _PFASST__QUADRATURE_HPP_\n", "meta": {"hexsha": "6c22e5cac54829cb442b86416cfb6300f48efa2c", "size": 4188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pfasst/quadrature.hpp", "max_stars_repo_name": "memmett/PFASST", "max_stars_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T11:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T01:09:52.000Z", "max_issues_repo_path": "include/pfasst/quadrature.hpp", "max_issues_repo_name": "memmett/PFASST", "max_issues_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-13T11:03:04.000Z", "max_forks_repo_path": "include/pfasst/quadrature.hpp", "max_forks_repo_name": "memmett/PFASST", "max_forks_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T07:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T20:26:08.000Z", "avg_line_length": 32.9763779528, "max_line_length": 97, "alphanum_fraction": 0.6451766953, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7025300449389325, "lm_q1q2_score": 0.5807898798388675}}
{"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 distributed alternating least squares.\n * We first create factors and then a data matrix\n * from these factors. THis process ensures that we know the best factorization of the input.\n * We then try to reconstruct the factors.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n\tboost::mpi::communicator& world = mfInit(argc, argv);\n\n\t// parameters for the factorization\n\tmf_size_type size1 =10;// 480189;//10000;\n\tmf_size_type size2 =10;// 17770;//10000;\n\tmf_size_type nnz = 10;//1408395;//1000000;\n\tdouble sigma = 1; // standard deviation\n\tdouble lambda =0;// 1/sigma/sigma;\n\tmf_size_type r = 5;\n\n\t// parameters for ALS\n\tunsigned epochs = 2;\n\tAlsRegularizer regularizer = ALS_L2;\n\ttypedef SumLoss<NzslLoss, L2Loss> Loss;\n\ttypedef NzslLoss TestLoss;\n\tLoss loss((NzslLoss()), L2Loss(lambda));\n\tTestLoss testLoss;\n\tmf_size_type testNnz = 100;//nnz/100;\n\tBalanceType type = BALANCE_NONE;// BALANCE_L2;;\n\tBalanceMethod method = BALANCE_SIMPLE;\n\n\t// parameters for distribution\n\tint tasksPerRank = 2;\n\tmf_size_type blocks = world.size() * tasksPerRank;\n\n\tmfStart();\n\n\tif (world.rank() == 0) {\n\t#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n\t#endif\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\tv.sort();\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\t\tSparseMatrixCM vc;\n\t\tcopyCm(v, vc);\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// 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\n\t\tDistributedSparseMatrix dv = distributeMatrix(\"V\", blocks, 1, true, v);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix: \"\n\t\t\t\t<< dv.blocks1() << \" x \" << dv.blocks2() << \" blocks\");\n\t\tDistributedSparseMatrixCM dvc = distributeMatrix(\"VC\", 1, blocks, false, vc);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix (CM): \"\n\t\t\t\t<< dvc.blocks1() << \" x \" << dvc.blocks2() << \" blocks\");\n\t\tDistributedSparseMatrix dvTest = distributeMatrix(\"Vtest\", blocks, blocks, true, vTest);\n\t\tLOG4CXX_INFO(logger, \"Distributed test matrix: \"\n\t\t\t\t<< dvTest.blocks1() << \" x \" << dvTest.blocks2() << \" blocks\");\n\t\tDistributedDenseMatrix dw = distributeMatrix(\"W\", blocks, 1, true, w);\n\t\tDistributedDenseMatrixCM dh = distributeMatrix(\"H\", 1, blocks, false, h);\n\t\tLOG4CXX_INFO(logger, \"Distributed factor matrices\");\n\n\t\t// initialize\n\t\tDapFactorizationData<> data(dv, dw, dh, tasksPerRank, &dvc);\n\t\tDsgdFactorizationData<> testJob(dvTest, dw, dh, tasksPerRank);\n\t\tTrace trace;\n\t\t// here add fields to Trace\n//\t\ttrace.addField(\"balancing-type\", type);\n//\t\ttrace.addField(\"balancing-method\", method);\n\t\tTimer t;\n\n\t\t// run ALS to try to reconstruct the original factors\n\t\tt.start();\n\t\tdalsNzsl(data, epochs, trace, lambda, regularizer, type, method, &testJob);\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// write trace to an R file\n\t\tstring typeString, methodString;\n\t\tswitch (type) {\n\t\tcase BALANCE_NONE:\n\t\t\ttypeString = \"None\";\n\t\t\tbreak;\n\t\tcase BALANCE_L2:\n\t\t\ttypeString = \"L2\";\n\t\t\tbreak;\n\t\tcase BALANCE_NZL2:\n\t\t\ttypeString = \"Nzl2\";\n\t\t\tbreak;\n\t\t}\n\t\tswitch (method) {\n\t\tcase BALANCE_SIMPLE:\n\t\t\tmethodString = \"Simple\";\n\t\t\tbreak;\n\t\tcase BALANCE_OPTIMAL:\n\t\t\tmethodString = \"Optimal\";\n\t\t\tbreak;\n\t\t}\n\t\tstring filename = \"/tmp/dals-trace.R\";\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << filename);\n\t\ttrace.toRfile(filename, \"dals\");\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "4cbfc1919c2997123f3807f0c250315f34700b66", "size": 5533, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/dals.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/dals.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/dals.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 33.9447852761, "max_line_length": 99, "alphanum_fraction": 0.6954635821, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.5806930010908572}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2015 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 \"quad_planarity.h\"\n#include <Eigen/Geometry>\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedP>\nIGL_INLINE void igl::quad_planarity(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedP> & P)\n{\n  int nf = F.rows();\n  P.setZero(nf,1);\n  for (int i =0; i<nf; ++i)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v1 = V.row(F(i,0));\n    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v2 = V.row(F(i,1));\n    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v3 = V.row(F(i,2));\n    const Eigen::Matrix<typename DerivedV::Scalar,1,3> &v4 = V.row(F(i,3));\n    Eigen::Matrix<typename DerivedV::Scalar,1,3> diagCross=(v3-v1).cross(v4-v2);\n    typename Eigen::PlainObjectBase<DerivedV>::Scalar denom = diagCross.norm()*(((v3-v1).norm()+(v4-v2).norm())/2);\n    if (fabs(denom)<1e-8)\n      //degenerate quad is still planar\n      P[i] = 0;\n    else\n      P[i] = (diagCross.dot(v2-v1)/denom);\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate void igl::quad_planarity<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": "d4edd473551ed85175bd9477aecba8dafbfaaa26", "size": 1788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/quad_planarity.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/quad_planarity.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "Code/include/igl/quad_planarity.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": 45.8461538462, "max_line_length": 367, "alphanum_fraction": 0.6649888143, "num_tokens": 597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5806725848619841}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <limits>\n\n#include <solvers/qp.hpp>\n\nnamespace sqp {\n\ntemplate <typename T>\nclass SQP;\n\ntemplate <typename Scalar>\nstruct sqp_settings_t {\n    Scalar tau = 0.5;       /**< line search iteration decrease, 0 < tau < 1 */\n    Scalar eta = 0.25;      /**< line search parameter, 0 < eta < 1 */\n    Scalar rho = 0.5;       /**< line search parameter, 0 < rho < 1 */\n    Scalar eps_prim = 1e-4; /**< primal step termination threshold, eps_prim > 0 */\n    Scalar eps_dual = 1e-4; /**< dual step termination threshold, eps_dual > 0 */\n    int max_iter = 100;\n    int line_search_max_iter = 20;\n    bool second_order_correction = false;\n    std::function<void(SQP<Scalar>&)> iteration_callback;\n\n    bool validate() {\n        bool valid;\n        valid = 0.0 < tau && tau < 1.0 && 0.0 < eta && eta < 1.0 && 0.0 < rho && rho < 1.0 &&\n                eps_prim < 0.0 && eps_dual < 0.0 && max_iter > 0 && line_search_max_iter > 0;\n        return valid;\n    }\n};\n\ntypedef enum { SOLVED, MAX_ITER_EXCEEDED, INVALID_SETTINGS } Status;\n\nstruct Info {\n    int iter;\n    int qp_solver_iter;\n    Status status;\n\n    void print() {\n        printf(\"SQP info:\\n\");\n        printf(\"  iter: %d\\n\", iter);\n        printf(\"  qp_solver_iter: %d\\n\", qp_solver_iter);\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 INVALID_SETTINGS:\n                printf(\"INVALID_SETTINGS\\n\");\n                break;\n            default:\n                printf(\"UNKNOWN\\n\");\n                break;\n        }\n    }\n};\n\ntemplate <typename Scalar_ = double>\nstruct NonLinearProblem {\n    using Scalar = Scalar_;\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n    int num_var;\n    int num_constr;\n\n    virtual void objective(const Vector& x, Scalar& obj) = 0;\n    virtual void objective_linearized(const Vector& x, Vector& grad, Scalar& obj) = 0;\n    virtual void constraint(const Vector& x, Vector& c, Vector& l, Vector& u) = 0;\n    virtual void constraint_linearized(const Vector& x, Matrix& Jc, Vector& c, Vector& l,\n                                       Vector& u) = 0;\n};\n\n/*\n * minimize     f(x)\n * subject to   l <= c(x) <= u\n */\ntemplate <typename Scalar_>\nclass SQP {\n   public:\n    using Scalar = Scalar_;\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using Problem = NonLinearProblem<Scalar>;\n    using Settings = sqp_settings_t<Scalar>;\n\n    // Constants\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    SQP();\n    ~SQP() = default;\n\n    void solve(Problem& prob, const Vector& x0, const Vector& lambda0);\n    void solve(Problem& prob);\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 lambda_; }\n    inline Vector& dual_solution() { return lambda_; }\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    // private:\n    void run_solve(Problem& prob);\n\n    bool termination_criteria(const Vector& x, Problem& prob);\n    void solve_qp(Problem& prob, Vector& p, Vector& lambda);\n    bool run_solve_qp(const Matrix& P, const Vector& q, const Matrix& A, const Vector& l,\n                      const Vector& u, Vector& prim, Vector& dual);\n\n    /** Second order correction by solving the same QP with corrected constraints. */\n    void second_order_correction(Problem& prob, Vector& p, Vector& lambda);\n\n    /** Line search in direction p using l1 merit function. */\n    Scalar line_search(Problem& prob, const Vector& p);\n\n    /** L1 norm of constraint violation */\n    Scalar constraint_norm(const Vector& x, Problem& prob);\n\n    /** L1 norm of constraint violation, for given constraint evaluation */\n    Scalar constraint_norm(const Vector &constr, const Vector &l, const Vector &u) const;\n\n    /** L_inf norm of constraint violation */\n    Scalar max_constraint_violation(const Vector& x, Problem& prob);\n\n    // Solver state variables\n    Vector x_;\n    Vector lambda_;\n    Vector step_prev_;\n    Vector grad_L_;\n    Vector delta_grad_L_;\n\n    Matrix Hess_;\n    Vector grad_obj_;\n    Scalar obj_;\n    Matrix Jac_constr_;\n    Vector constr_;\n    Vector l_, u_;\n\n    // info\n    Scalar dual_step_norm_;\n    Scalar primal_step_norm_;\n\n    Settings settings_;\n    Info info_;\n\n    qp_solver::QPSolver<Scalar> qp_solver_;\n};\n\nextern template class SQP<double>;\n\n}  // namespace sqp\n", "meta": {"hexsha": "fe357dfa5570daff94611409058a5c7ce41d5b6d", "size": 5075, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solvers/sqp.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/sqp.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/sqp.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.5722891566, "max_line_length": 93, "alphanum_fraction": 0.6299507389, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5806348151388072}}
{"text": "/**********************************************************************\n*  Copyright (c) 2008-2016, Alliance for Sustainable Energy.  \n*  All rights reserved.\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 Street, Fifth Floor, Boston, MA  02110-1301  USA\n**********************************************************************/\n\n#ifndef UTILITIES_GEOMETRY_GEOMETRY_HPP\n#define UTILITIES_GEOMETRY_GEOMETRY_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace openstudio{\n\n  class Point3d;\n  class PointLatLon;\n  class Vector3d;\n\n  /// convert degrees to radians\n  UTILITIES_API double degToRad(double degrees);\n\n  /// convert radians to degrees\n  UTILITIES_API double radToDeg(double radians);\n\n  /// compute area from surface as Point3dVector\n  UTILITIES_API boost::optional<double> getArea(const std::vector<Point3d>& points);\n\n  /// compute Newall vector from surface as Point3dVector, direction is same as outward normal\n  /// magnitude is twice the area\n  UTILITIES_API boost::optional<Vector3d> getNewallVector(const std::vector<Point3d>& points);\n\n  /// compute outward normal from surface as Point3dVector\n  UTILITIES_API boost::optional<Vector3d> getOutwardNormal(const std::vector<Point3d>& points);\n\n  /// compute centroid from surface as Point3dVector\n  UTILITIES_API boost::optional<Point3d> getCentroid(const std::vector<Point3d>& points);\n\n  /// reorder points to upper-left-corner convention\n  UTILITIES_API std::vector<Point3d> reorderULC(const std::vector<Point3d>& points);\n\n  /// removes collinear points, tolerance is for length of cross product after normalizing each line segment\n  UTILITIES_API std::vector<Point3d> removeCollinear(const std::vector<Point3d>& points, double tol = 0.001);\n\n  /// return distance between two points\n  UTILITIES_API double getDistance(const Point3d& point1, const Point3d& point2);\n\n  /// return distance between a point and a line segment\n  /// returns 0 if lineSegment does not have length 2\n  UTILITIES_API double getDistancePointToLineSegment(const Point3d& point, const std::vector<Point3d>& lineSegment);\n\n  /// return distance between a point and a triangle\n  /// returns 0 if triangle does not have length 3\n  UTILITIES_API double getDistancePointToTriangle(const Point3d& point, const std::vector<Point3d>& triangle);\n\n  /// return angle (in radians) between two vectors\n  UTILITIES_API double getAngle(const Vector3d& vector1, const Vector3d& vector2);\n  \n  /// compute distance in meters between two points on the Earth's surface\n  /// lat and lon are specified in degrees\n  UTILITIES_API double getDistanceLatLon(double lat1, double lon1, double lat2, double lon2);\n\n  /// check if two vectors of points are equal (within tolerance) irregardless of initial ordering.\n  UTILITIES_API bool circularEqual(const std::vector<Point3d>& points1, const std::vector<Point3d>& points2, double tol = 0.001);\n\n  /// if point3d is within tol of any existing points then returns existing point\n  /// otherwise adds point3d to allPoints and returns point3d\n  UTILITIES_API Point3d getCombinedPoint(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol = 0.001);\n\n  /// compute triangulation of vertices, holes are removed in the triangulation\n  /// requires that vertices and holes are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed) \n  UTILITIES_API std::vector<std::vector<Point3d> > computeTriangulation(const std::vector<Point3d>& vertices, const std::vector<std::vector<Point3d> >& holes, double tol = 0.001);\n\n  /// move all vertices towards point by distance, pass negative distance to move away from point\n  /// no guarantee that resulting polygon will be valid\n  UTILITIES_API std::vector<Point3d> moveVerticesTowardsPoint(const std::vector<Point3d>& vertices, const Point3d& point, double distance);\n\n  /// reverse order of vertices\n  UTILITIES_API std::vector<Point3d> reverse(const std::vector<Point3d>& vertices);\n\n\n} // openstudio\n\n#endif //UTILITIES_GEOMETRY_GEOMETRY_HPP\n", "meta": {"hexsha": "ede5a6955d608f9b4a14f83523fa3220fec54469", "size": 4675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_stars_repo_name": "jasondegraw/OpenStudio", "max_stars_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-29T08:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-29T08:45:03.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_issues_repo_name": "jasondegraw/OpenStudio", "max_issues_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Geometry.hpp", "max_forks_repo_name": "jasondegraw/OpenStudio", "max_forks_repo_head_hexsha": "2ab13f6e5e48940929041444e40ad9d36f80f552", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.2222222222, "max_line_length": 179, "alphanum_fraction": 0.7422459893, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5806348115741181}}
{"text": "\n#include <NTL/FFT.h>\n#include <NTL/FFT_impl.h>\n\n#ifdef NTL_ENABLE_AVX_FFT\n#include <NTL/SmartPtr.h>\n#include <NTL/pd_FFT.h>\n#endif\n\n\n/********************************************************************\n\nThis is an implementation of a \"small prime\" FFT, which lies at the heart of\nZZ_pX and zz_pX arithmetic, and impacts many other applications as well\n(such as arithmetic in ZZ_pEX, zz_pEX, and ZZX).\n\nThe algorithm is a Truncated FFT based on code originally developed by David\nHarvey.  David's code built on the single-precision modular multiplication\ntechnique introduced in NTL many years ago, but also uses a \"lazy\nmultiplication\" technique, which reduces the number of \"correction\" steps that\nneed to be performed in each butterfly (see below for more details).  It also\nimplements a version of the Truncated FFT algorithm introduced by Joris van der\nHoeven at ISSAC 2004.  Also see \"A cache-friendly truncated FFT\", David Harvey,\nTheoretical Computer Science Volume 410, Issues 27-29, 28 June 2009, Pages\n2649-2658.\n\nI have almost completely re-written David's original code to make it fit into\nNTL's software framework; however, all all of the key logic is still based on\nDavid's code.  David's original code also implemented a 2D transformation which\nis more cache friendly for *very* large transforms.  However, my experimens\nindicated this was only beneficial for transforms of size at least 2^20, and so\nI did not incorporate this variant.\n\nHere is the Copyright notice from David's original code:\n\n\n==============================================================================\n\nfft62: a library for number-theoretic transforms\n\nCopyright (C) 2013, David Harvey\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n==============================================================================\n\n\nSINGLE-PRECISION MODULAR ARITHMETIC\n\nThe implementation of arithmetic modulo n, where n is a \"word sized\" integer is\ncritical to the performance of the FFT.  Such word-sized modular arithmetic is\nused throughout many other parts of NTL, and is a part of the external,\ndocumented interface.\n\nAs NTL was initially built on top of Arjen Lenstra's LIP software, I stole a\nlot of ideas from LIP.  One very nice ideas was LIP's way of handling\nsingle-precision modular arithmetic.  Back in those days (the early 1990's), I\nwas targeting 32-machines, mainly SPARC stations.  LIP's stratgey was to\nrestrict n to 30 bits, and to compute a*b % n, where 0 <= a, b < n, the\nfollwong was computed:\n\n   long q = long(double(a) * double(b) / double(n));\n   long r = a*b - q*n;\n   if (r >= n) \n      r -= n;\n   else if (r < 0)\n      r += n;\n\nWith quite reasonable assumptions about floating point (certainly, anything\neven remotely close to IEEE 64-bit doubles), the computation of q always gives\nthe true quotient floor(a*b / n), plus or minus 1.  The computation of r is\ndone modulo the 2^{word size}, and the following if/then/else adjusts r as\nnecessary.  To be more portable, some of these computations should really be\ndone using unsigned arithmetic, but that is not so important here.  Also, the\nadjustment steps can be replaced by simple non-branching instrictions sequences\ninvolving SHIFT, AND, and ADD/SUB instructions.  On some modern machines, this\nis usually faster and NTL uses this non-branching strategy.  However, on other\nmachines (modern x86's are  an example of this), conditional move instructions\ncan be used in place of branching, and this code can be faster than the\nnon-branching code.  NTL's performance-tuning script will figure out the best\nway to do this.\n\n\nOther simple optimizations can be done, such as precomputing 1/double(n) when n\nremains fixed for many computations, as is often the case.  \n\nNote also that this strategy works perfectly well even when a or b are larger\nthan n, but the quotient itself is bounded by 2^30.\n\nThis strategy worked well for many years.  I had considered employing\n\"Montgomery multiplication\", but did not do so for a couple of reasons:\n  1) it would require non-portable code, because Montgomery multiplication\n     requires the computation of two-word products,\n  2) I did not like the idea of working with \"alternative representations\"\n     for integers mod n, as this would make the interfaces more awkward.\n\nAt some point in the early 2000's, this strategy was starting to slow things\ndown, as floating point arithmetic, especially the integer/floating point\nconversions, was starting to slow down relative to integer arithmetic.  This\nwas especially true on x86 machines, which by this time was starting to become\nthe most important target.  As it happens, later in the 2000's, as the x86\nplatforms started to use SSE instructions in lieu of the old x87 FPU\ninstructions, this speed differential again became less of a problem.\nNevertheless, I introduced some new techniques that speed things up across a\nvariety of platforms.  I introduced this new technique in NTL 5.4 back in 2005.\nI never claimed it was particularly new, and I never really documented many\ndetails about it, but since then, it has come to be known as \"Shoup\nmultiplcation\" in a few papers, so I'll accept that. :-)  The paper \"Faster\narithmetic for number-theoretic transforms\" [David Harvey, J. Symb. Comp. 60\n(2014)] seems to be the first place where it is discussed in detail,\nand Harvey's paper also contains some improvements which I discuss below.\n\nThe basic idea is that in many computations, not only n, but one of the\narguments, say b, remains fixed for many computatations of a*b % n, and so we\ncan afford to do a little precomputation, based on b and n, to speed things up.\nThis approach does require the ability to compute double-word products\n(actually, just the high word of the product), but it still presents the same\nbasic interface as before (i.e., no awkward, alternative representations);\nmoreover, on platforms where we can't get double-word products, the\nimplementation falls back to the old floating point strategy, and client code\nneed not be aware of this.\n\nThe basic idea is this: suppose 0 <= n < 2^w, and 0 <= a < 2^w, and 0 <= b < n.\nWe precompute bninv = floor(2^w*b/n).  Then if we compute q =\nfloor(a*bninv/2^w), it can be argued that q is either floor(a*b/n), or is 1 too\nsmall.  The computation of bninv can be done using the floating point\ntechniques described above.  The computation of q can be done by computing the\nhigh word of a double-word product (it helps if bninv is left-shifted an\nappropriate amount first).  Once we have q, we can compute a*b - q*n as before,\nand adjust (but now only one adjustment is needed).  So after the\nprecomputation.  the whole operation takes 3 multiplies (one doube-word and two\nsingle-word), and a small handful of simple instructions (adds, shifts, etc).\nMoreover, two of the three multiplies can start in parallel, on platforms where\nthis is possible.\n\nDavid Harvey noticed that because on modern machines, multiplies are really not\nthat slow compared to additions, the cost of all of the adjustments (in the\nMulMod, as well as in the AddMod and SubMod's in the basic FFT butterfly steps)\nstarts to dominate the cost of the FFT. Indeed, with a straightforward\nimplementation of the above ideas, there are three multiplies and three\nadjustment steps in each butterfly step.  David's idea was to work with\nredundant representations mod n, in the range [0..4*n), and thus reduce the\nnumber of adjustments per butterfly from three to one.  I've implemented this\nidea here, and it does indeed make a significant difference, which is even more\npronounced when all of the FFT multipliers b and corresponding bninv values are\nprecomputed.  My initial implementation of David's ideas (v6.0 in 2013) only\nimplemented his approach with these precomputated tables: it seemed that\nwithout these tables, it was not a significant improvement.  However, I later\nfigured out how to reduce the cost of computing all the necessary data \"on the\nfly\", in a way that seems only slightly (10-15%) slower overall.  I introduced\nthis in v9.1 in 2015, and set things up so that now the pre-computed tables are\nstill used, but not exclusively, in such a way as to reduce the memory used by\nthese tables for very large polynomials (either very high degree or lots of FFT\nprimes).   The idea here is simple, but I haven't seen it discussed elsewhere,\nso I'll document the basic idea here.\n\nSuppose we have the preconditioners for a and b, and want a*b % n along with\nthe preconditioner for a*b % n.\n\nFor a, let us suppose that we have both q1 and r1, where:\n   2^w*a = n*q1 + r1\nWe can obtain both q1 and r1 using floating point techniques.\n\nStep 1. Compute a*b % n, using the integer-only MulMod, using\neither the preconditioner for either a or b.\n\nStep 2. Compute q2 and r2 such that\n   r1*b = n*q2 + r2\nWe can obtain these using the integer-only MulMod, preconditioned on b.\nActually, we only need q2, not r2.\n\nStep 3. Compute\n   q3 = q1*b + q2 mod 2^w\nwhich we can compute with just a single-word multiply and an addition.\n\nOne can easily show that the value q3 computed above is indeed the\npreconditioner for a*b % n.  \n\nNote that, in theory, if the computation in Step 2 is done using the\npreconditioner for a (i.e., q1), then the multiplication q1*b in Step 3 should\nnot really be necessary (assuming that computing both high and low words of a\ndoube-wprd product is no more expensive than just computing the low word).\nHowever, none of the compilers I've used have been able to perform that\noptimization (in NTL v11.1, I added code that hand-codes this optimization).\n\n\n64-BIT MACHINES\n\nCurrent versions of NTL use (by default) 60-bit moduli based\non all-integer arithemtic.\n\n\nPrior to v9.0 of NTL, on 64 bits, the modulus n was restricted to 50 bits, in\norder to allow the use of double-precision techniques, as double's have 53 bits\nof precision.  However, NTL now supports 60-bit moduli.  Actually, 62 bits can\nbe supported by setting the NTL_MAXIMIZE_SP_NBITS configuraton flag, but other\nthings (namely, the TBL_REM implementation in lip.cpp) start to slow down if 62\nbits are used, so 60 seems like a good compromise.  Currently,  60-bit moduli\nare available only when compiling NTL with GMP, and when some kind of extended\ninteger of floating point arithmetic is available. \n\n\nFUTURE TRENDS\n\n\n* The following papers\n\n   https://eprint.iacr.org/2017/727\n   https://eprint.iacr.org/2016/504\n   https://eprint.iacr.org/2015/382\n\npresent FFTs that access the pre-computed tables in a somewhat more efficent\nfashion, so that we only need to read from the tables O(n) times, rather than\nO(n log n) times.  \n\nI've partially implemented this, and have gotten mixed results.\nFor smallish FFT's (below k=10 or 11), this code is somewhat slower.\nFor larger FFT's (say, k=17), I see a speedup of 3-10%.\n\n\n********************************************************************/\n\n\n\n#define NTL_FFT_BIGTAB_LIMIT (180)\n#define NTL_FFT_BIGTAB_MAXROOT (17)\n#define NTL_FFT_BIGTAB_MINROOT (7)\n\n// table sizes are bounded by 2^bound, where \n// bound = NTL_FFT_BIGTAB_MAXROOT-index/NTL_FFT_BIGTAB_LIMIT.\n// Here, index is the index of an FFT prime, or 0 for a user FFT prime.\n// If bound <= NTL_FFT_BIGTAB_MINROOT, then big tables are not used,\n// so only the first \n//    (NTL_FFT_BIGTAB_MAXROOT-NTL_FFT_BIGTAB_MINROOT)*NTL_FFT_BIGTAB_LIMIT\n// FFT primes will have big tables.\n\n// NOTE: in newer versions of NTL (v9.1 and later), the BIGTAB\n// code is only about 5-15% faster than the non-BIGTAB code, so\n// this is not a great time/space trade-off.\n// However, some futher optimizations may only be implemented \n// if big tables are used.\n\n// NOTE: NTL_FFT_BIGTAB_MAXROOT is set independently of the parameter\n// NTL_FFTMaxRoot defined in FFT.h (and which is typically 25).\n// The space for the LazyTable FFTMultipliers could be reduced a bit\n// by using min(NTL_FFT_BIGTAB_MAXROOT, NTL_FFTMaxRoot) + 1 for the\n// size of these tables.\n\n\n\nNTL_START_IMPL\n\n\n\nclass FFTVectorPair {\npublic:\n   Vec<long> wtab_precomp;\n   Vec<mulmod_precon_t> wqinvtab_precomp;\n};\n\ntypedef LazyTable<FFTVectorPair, NTL_FFTMaxRoot+1> FFTMultipliers;\n\n\n#ifdef NTL_ENABLE_AVX_FFT\nclass pd_FFTVectorPair {\npublic:\n   AlignedArray<double> wtab_precomp;\n   AlignedArray<double> wqinvtab_precomp;\n};\n\ntypedef LazyTable<pd_FFTVectorPair, NTL_FFTMaxRoot+1> pd_FFTMultipliers;\n#endif\n\n\n\nclass FFTMulTabs {\npublic:\n\n#ifndef NTL_ENABLE_AVX_FFT\n   long bound;\n   FFTMultipliers MulTab;\n#else\n   pd_FFTMultipliers pd_MulTab[2];\n#endif\n\n};\n\nvoid FFTMulTabsDeleterPolicy::deleter(FFTMulTabs *p) { delete p; }\n\n\n\nFFTTablesType FFTTables;\n// a truly GLOBAL variable, shared among all threads\n\n\n\nlong IsFFTPrime(long n, long& w)\n{\n   long  m, x, y, z;\n   long j, k;\n\n\n   if (n <= 1 || n >= NTL_SP_BOUND) return 0;\n\n   if (n % 2 == 0) return 0;\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\n   for (j = NTL_FFTMaxRoot; j < k; j++) {\n      x = MulMod(x, x, n);\n   }\n\n   w = x;\n\n   return 1;\n}\n\n\nstatic\nvoid NextFFTPrime(long& q, long& w, long index)\n{\n   static long m = NTL_FFTMaxRootBnd + 1;\n   static long k = 0;\n   // m and k are truly GLOBAL variables, shared among\n   // all threads.  Access is protected by a critical section\n   // guarding FFTTables\n\n   static long last_index = -1;\n   static long last_m = 0;\n   static long last_k = 0;\n\n   if (index == last_index) {\n      // roll back m and k...part of a simple error recovery\n      // strategy if an exception was thrown in the last \n      // invocation of UseFFTPrime...probably of academic \n      // interest only\n\n      m = last_m;\n      k = last_k;\n   }\n   else {\n      last_index = index;\n      last_m = m;\n      last_k = k;\n   }\n\n   long t, cand;\n\n   for (;;) {\n      if (k == 0) {\n         m--;\n         if (m < 5) ResourceError(\"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\n\n#ifndef NTL_WIZARD_HACK\nSmartPtr<zz_pInfoT> Build_zz_pInfo(FFTPrimeInfo *info);\n#else\nSmartPtr<zz_pInfoT> Build_zz_pInfo(FFTPrimeInfo *info) { return 0; }\n#endif\n\nvoid UseFFTPrime(long index)\n{\n   if (index < 0) LogicError(\"invalud FFT prime index\");\n   if (index >= NTL_MAX_FFTPRIMES) ResourceError(\"FFT prime index too large\");\n\n   if (index+1 >= NTL_NSP_BOUND) ResourceError(\"FFT prime index too large\");\n   // largely acacedemic, but it is a convenient assumption\n\n   do {  // NOTE: thread safe lazy init\n      FFTTablesType::Builder bld(FFTTables, index+1);\n      long amt = bld.amt();\n      if (!amt) break;\n\n      long first = index+1-amt;\n      // initialize entries first..index\n\n      long i;\n      for (i = first; i <= index; i++) {\n         UniquePtr<FFTPrimeInfo> info;\n         info.make();\n\n         long q, w;\n         NextFFTPrime(q, w, i);\n\n         long bigtab_index = -1;\n\n#ifdef NTL_FFT_BIGTAB\n         bigtab_index = i;\n#endif\n\n         InitFFTPrimeInfo(*info, q, w, bigtab_index);\n         info->zz_p_context = Build_zz_pInfo(info.get());\n         bld.move(info);\n      }\n\n   } while (0);\n}\n\n\n#ifdef NTL_FFT_LAZYMUL \n// we only honor the FFT_LAZYMUL flag if either the SPMM_ULL_VIABLE or LONGLONG_SP_MULMOD \n// flags are set\n\n#if (!defined(NTL_SPMM_ULL_VIABLE) && !defined(NTL_LONGLONG_SP_MULMOD))\n#undef NTL_FFT_LAZYMUL\n\n// raise an error if running the wizard\n#if (defined(NTL_WIZARD_HACK))\n#error \"cannot honor NTL_FFT_LAZYMUL\"\n#endif\n\n#endif\n\n#endif\n\n\n\n\n#ifdef NTL_FFT_LAZYMUL\n// FFT with  lazy multiplication\n\n#ifdef NTL_CLEAN_INT\n#define NTL_FFT_USEBUF\n#endif\n// DIRT: with the lazy multiplication strategy, we have to work\n// with unisgned long's rather than long's.  To avoid unnecessary\n// copying, we simply cast long* to unsigned long*.\n// Is this standards compliant? Does it evoke Undefined Behavior?\n// The C++ standard before C++14 were actually somewhat inconsistent \n// on this point.\n\n// In all versions of the C++ and C standards, the \"strict aliasing\"\n// rules [basic.lval] have always said that signed/unsigned can\n// always alias each other.  So this does not break the strict\n// aliasing rules.  However, prior to C++14, the section\n// on Lvalue-to-rvalue conversion [conv.lval] said that\n// this was actually UB.  This has been cleared up in C++14,\n// where now it is no longer UB.  Actally, it seems that the change\n// to C++14 was cleaning up an inconsistency in the standard\n// itself, and not really a change in the language definition.\n\n// In practice, it does make a significant difference in performance\n// to avoid all these copies, so the default is avoid them.\n\n// See: https://stackoverflow.com/questions/30048135/efficient-way-to-bit-copy-a-signed-integer-to-an-unsigned-integer\n\n// See: https://stackoverflow.com/questions/27109701/aliasing-of-otherwise-equivalent-signed-and-unsigned-types \n// Especially comments by Columbo regarding N3797 and [conv.lval] \n\n\n\n\n\n\n#if (defined(NTL_LONGLONG_SP_MULMOD))\n\n\n#if (NTL_BITS_PER_LONG >= NTL_SP_NBITS+4) \n\nstatic inline unsigned long \nsp_NormalizedLazyPrepMulModPreconWithRem(unsigned long& rres, long b, long n, unsigned long ninv)\n{\n   unsigned long H = cast_unsigned(b);\n   unsigned long Q = ll_mul_hi(H << 4, ninv);\n   unsigned long L = cast_unsigned(b) << (NTL_SP_NBITS+2);\n   long r = L - Q*cast_unsigned(n);  // r in [0..2*n)\n\n   r = sp_CorrectExcessQuo(Q, r, n);\n   rres = r;\n   return Q; // NOTE: not shifted\n}\n\nstatic inline unsigned long \nsp_NormalizedLazyPrepMulModPrecon(long b, long n, unsigned long ninv)\n{\n   unsigned long H = cast_unsigned(b);\n   unsigned long Q = ll_mul_hi(H << 4, ninv);\n   unsigned long L = cast_unsigned(b) << (NTL_SP_NBITS+2);\n   long r = L - Q*cast_unsigned(n);  // r in [0..2*n)\n\n   Q += 1L + sp_SignMask(r-n);\n   return Q; // NOTE: not shifted\n}\n\n\n#else\n\n// NTL_BITS_PER_LONG == NTL_SP_NBITS+2\nstatic inline unsigned long \nsp_NormalizedLazyPrepMulModPreconWithRem(unsigned long& rres, long b, long n, unsigned long ninv)\n{\n   unsigned long H = cast_unsigned(b) << 2;\n   unsigned long Q = ll_mul_hi(H, (ninv << 1)) + H;\n   unsigned long rr = -Q*cast_unsigned(n);  // r in [0..3*n)\n\n   long r = sp_CorrectExcessQuo(Q, rr, n);\n   r = sp_CorrectExcessQuo(Q, r, n);\n   rres = r;\n   return Q;  // NOTE: not shifted\n}\n\nstatic inline unsigned long \nsp_NormalizedLazyPrepMulModPrecon(long b, long n, unsigned long ninv)\n{\n   unsigned long H = cast_unsigned(b) << 2;\n   unsigned long Q = ll_mul_hi(H, (ninv << 1)) + H;\n   unsigned long rr = -Q*cast_unsigned(n);  // r in [0..3*n)\n   Q += 2L + sp_SignMask(rr-n) + sp_SignMask(rr-2*n);\n   return Q; // NOTE: not shifted\n}\n\n\n#endif\n\n\nstatic inline unsigned long\nLazyPrepMulModPrecon(long b, long n, sp_inverse ninv)\n{\n   return sp_NormalizedLazyPrepMulModPrecon(b << ninv.shamt, n << ninv.shamt, ninv.inv) << (NTL_BITS_PER_LONG-NTL_SP_NBITS-2);\n}\n\n\nstatic inline unsigned long\nLazyPrepMulModPreconWithRem(unsigned long& rres, long b, long n, sp_inverse ninv)\n{\n   unsigned long qq, rr;\n   qq = sp_NormalizedLazyPrepMulModPreconWithRem(rr, b << ninv.shamt, n << ninv.shamt, ninv.inv); \n   rres = rr >> ninv.shamt;\n   return qq << (NTL_BITS_PER_LONG-NTL_SP_NBITS-2);\n}\n\n\n\n\n\n\n\n\n#elif (NTL_BITS_PER_LONG - NTL_SP_NBITS >= 4 && NTL_WIDE_DOUBLE_PRECISION - NTL_SP_NBITS >= 4)\n\n\n// slightly faster functions, which should kick in on x86-64, where \n//    NTL_BITS_PER_LONG == 64\n//    NTL_SP_NBITS == 60 (another reason for holding this back to 60 bits)\n//    NTL_WIDE_DOUBLE_PRECISION == 64\n\n// DIRT: if the relative error in floating point calcuations (muls and reciprocals)\n//   is <= epsilon, the relative error in the calculations is <= 3*epsilon +\n//   O(epsilon^2), and we require that this relative error is at most\n//   2^{-(NTL_SP_NBITS+2)}, so it should be pretty safe as long as\n//   epsilon is at most, or not much geater than, 2^{-NTL_WIDE_DOUBLE_PRECISION}.\n\nstatic inline \nunsigned long LazyPrepMulModPrecon(long b, long n, wide_double ninv)\n{\n   long q = (long) ( (((wide_double) b) * wide_double(4*NTL_SP_BOUND)) * ninv ); \n\n   unsigned long rr = (cast_unsigned(b) << (NTL_SP_NBITS+2)) \n                       - cast_unsigned(q)*cast_unsigned(n);\n\n   q += sp_SignMask(rr) + sp_SignMask(rr-n) + 1L;\n\n   return cast_unsigned(q) << (NTL_BITS_PER_LONG - NTL_SP_NBITS - 2);\n}\n\nstatic inline \nunsigned long LazyPrepMulModPreconWithRem(unsigned long& rres, long b, long n, wide_double ninv)\n{\n   long q = (long) ( (((wide_double) b) * wide_double(4*NTL_SP_BOUND)) * ninv ); \n\n   unsigned long rr = (cast_unsigned(b) << (NTL_SP_NBITS+2)) \n                       - cast_unsigned(q)*cast_unsigned(n);\n\n   long r = sp_CorrectDeficitQuo(q, rr, n);\n   r = sp_CorrectExcessQuo(q, r, n);\n\n   unsigned long qres = cast_unsigned(q) << (NTL_BITS_PER_LONG - NTL_SP_NBITS - 2);\n   rres = r;\n   return qres;\n}\n\n#else\n\n\nstatic inline \nunsigned long LazyPrepMulModPrecon(long b, long n, wide_double ninv)\n{\n   long q = (long) ( (((wide_double) b) * wide_double(NTL_SP_BOUND)) * ninv ); \n\n   unsigned long rr = (cast_unsigned(b) << (NTL_SP_NBITS)) \n                       - cast_unsigned(q)*cast_unsigned(n);\n\n   long r = sp_CorrectDeficitQuo(q, rr, n);\n   r = sp_CorrectExcessQuo(q, r, n);\n\n   unsigned long qq = q;\n\n   qq = 2*qq;\n   r = 2*r;\n   r = sp_CorrectExcessQuo(qq, r, n);\n\n   qq = 2*qq;\n   r = 2*r;\n   qq += sp_SignMask(r-n) + 1L;\n\n   return qq << (NTL_BITS_PER_LONG - NTL_SP_NBITS - 2);\n}\n\n\n\n\n\nstatic inline \nunsigned long LazyPrepMulModPreconWithRem(unsigned long& rres, long b, long n, wide_double ninv)\n{\n   long q = (long) ( (((wide_double) b) * wide_double(NTL_SP_BOUND)) * ninv ); \n\n   unsigned long rr = (cast_unsigned(b) << (NTL_SP_NBITS)) \n                       - cast_unsigned(q)*cast_unsigned(n);\n\n   long r = sp_CorrectDeficitQuo(q, rr, n);\n   r = sp_CorrectExcessQuo(q, r, n);\n\n   unsigned long qq = q;\n\n   qq = 2*qq;\n   r = 2*r;\n   r = sp_CorrectExcessQuo(qq, r, n);\n\n   qq = 2*qq;\n   r = 2*r;\n   r = sp_CorrectExcessQuo(qq, r, n);\n\n   rres = r;\n   return qq << (NTL_BITS_PER_LONG - NTL_SP_NBITS - 2);\n}\n\n#endif\n\n\n\nstatic inline\nunsigned long LazyMulModPreconQuo(unsigned long a, unsigned long b, \n                                  unsigned long n, unsigned long bninv)\n{\n   unsigned long q = ll_mul_hi(a, bninv);\n   unsigned long r = a*b - q*n;\n   q += sp_SignMask(r-n) + 1L;\n   return q << (NTL_BITS_PER_LONG - NTL_SP_NBITS - 2);\n}\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 = ll_mul_hi(a, bninv);\n   unsigned long res = a*b - q*n;\n   return res;\n}\n\n\ntypedef long mint_t;\ntypedef unsigned long umint_t;\n// For readability and to make it easier to adapt this\n// code to other settings\n\nstatic inline \numint_t LazyReduce1(umint_t a, mint_t q)\n{\n  return sp_CorrectExcess(mint_t(a), q);\n}\n\nstatic inline \numint_t LazyReduce2(umint_t a, mint_t q)\n{\n  return sp_CorrectExcess(a, 2*q);\n}\n\n\n// inputs in [0, 2*n), output in [0, 4*n)\nstatic inline \numint_t LazyAddMod(umint_t a, umint_t b, mint_t n)\n{\n   return a+b;\n}\n\n// inputs in [0, 2*n), output in [0, 4*n)\nstatic inline \numint_t LazySubMod(umint_t a, umint_t b, mint_t n)\n{\n   return a-b+2*n;\n}\n\n// inputs in [0, 2*n), output in [0, 2*n)\nstatic inline \numint_t LazyAddMod2(umint_t a, umint_t b, mint_t n)\n{\n   umint_t r = a+b;\n   return sp_CorrectExcess(r, 2*n);\n}\n\n// inputs in [0, 2*n), output in [0, 2*n)\nstatic inline \numint_t LazySubMod2(umint_t a, umint_t b, mint_t n)\n{\n   umint_t r = a-b;\n   return sp_CorrectDeficit(r, 2*n);\n}\n\n#ifdef NTL_AVOID_BRANCHING\n\n// x, y in [0, 4*m)\n// returns x + y mod 4*m, in [0, 4*m)\ninline static umint_t \nLazyAddMod4(umint_t x, umint_t y, mint_t m)\n{\n   x = LazyReduce2(x, m);\n   y = LazyReduce2(y, m);\n   return x+y;\n}\n\n// x, y in [0, 4*m)\n// returns x - y mod 4*m, in [0, 4*m)\ninline static umint_t \nLazySubMod4(umint_t x, umint_t y, mint_t m)\n{\n   x = LazyReduce2(x, m);\n   y = LazyReduce2(y, m);\n   return x-y+2*m;\n}\n\n#else\n\nstatic inline umint_t \nLazyAddMod4(umint_t x, umint_t y, umint_t m)\n{\n  y = 4*m - y;\n  umint_t z = x - y;\n  z += (x < y) ? 4*m : 0;\n  return z;\n}\n\n\nstatic inline umint_t \nLazySubMod4(umint_t x, umint_t y, umint_t m)\n{\n  umint_t z = x - y;\n  z += (x < y) ? 4*m : 0;\n  return z;\n}\n\n#endif\n\n// Input and output in [0, 4*n)\nstatic inline umint_t\nLazyDoubleMod4(umint_t a, mint_t n)\n{\n   return 2 * LazyReduce2(a, n);\n}\n\n// Input and output in [0, 2*n)\nstatic inline umint_t\nLazyDoubleMod2(umint_t a, mint_t n)\n{\n   return 2 * LazyReduce1(a, n);\n}\n\nvoid ComputeMultipliers(Vec<FFTVectorPair>& v, long k, mint_t q, mulmod_t qinv, const mint_t* root)\n{\n\n   long old_len = v.length();\n   v.SetLength(k+1);\n\n   for (long s = max(old_len, 1); s <= k; s++) {\n      v[s].wtab_precomp.SetLength(1L << (s-1));\n      v[s].wqinvtab_precomp.SetLength(1L << (s-1));\n   }\n\n   if (k >= 1) {\n      v[1].wtab_precomp[0] = 1;\n      v[1].wqinvtab_precomp[0] = LazyPrepMulModPrecon(1, q, qinv);\n   }\n\n   if (k >= 2) {\n      v[2].wtab_precomp[0] = v[1].wtab_precomp[0];\n      v[2].wtab_precomp[1] = root[2];\n      v[2].wqinvtab_precomp[0] = v[1].wqinvtab_precomp[0];\n      v[2].wqinvtab_precomp[1] = LazyPrepMulModPrecon(root[2], q, qinv);\n   }\n\n   for (long s = 3; s <= k; s++) {\n      long m = 1L << s;\n      long m_half = 1L << (s-1);\n      long m_fourth = 1L << (s-2);\n      mint_t* NTL_RESTRICT wtab = v[s].wtab_precomp.elts();\n      mint_t* NTL_RESTRICT wtab1 = v[s-1].wtab_precomp.elts();\n      mulmod_precon_t* NTL_RESTRICT wqinvtab = v[s].wqinvtab_precomp.elts();\n      mulmod_precon_t* NTL_RESTRICT wqinvtab1 = v[s-1].wqinvtab_precomp.elts();\n\n      mint_t w = root[s];\n      umint_t wqinv_rem;\n      mulmod_precon_t wqinv = LazyPrepMulModPreconWithRem(wqinv_rem, w, q, qinv);\n\n\n      for (long i = m_half-1, j = m_fourth-1; i >= 0; i -= 2, j--) {\n         mint_t w_j = wtab1[j];\n         mulmod_precon_t wqi_j = wqinvtab1[j];\n\n#if 0\n         mint_t w_i = LazyReduce1(LazyMulModPrecon(w_j, w, q, wqinv), q);\n         mulmod_precon_t wqi_i = LazyMulModPreconQuo(wqinv_rem, w_j, q, wqi_j) \n                                   + cast_unsigned(w_j)*wqinv;\n#else\n         // This code sequence makes sure the compiler sees\n         // that the product w_j*wqinv needs to be computed just once\n         ll_type x;\n         ll_mul(x, w_j, wqinv);\n         umint_t hi = ll_get_hi(x);\n         umint_t lo = ll_get_lo(x);\n         umint_t r = cast_unsigned(w_j)*cast_unsigned(w) - hi*cast_unsigned(q);\n\n         mint_t w_i = LazyReduce1(r, q);\n         mulmod_precon_t wqi_i = lo+LazyMulModPreconQuo(wqinv_rem, w_j, q, wqi_j); \n#endif\n\n         wtab[i-1] = w_j;\n         wqinvtab[i-1] = wqi_j;\n         wtab[i] = w_i;\n         wqinvtab[i] = wqi_i;\n      }\n   }\n\n#if 0\n   // verify result\n   for (long s = 1; s <= k; s++) {\n      mint_t *wtab = v[s].wtab_precomp.elts();\n      mulmod_precon_t *wqinvtab = v[s].wqinvtab_precomp.elts();\n      long m_half = 1L << (s-1);\n\n      mint_t w = root[s];\n      mint_t w_i = 1;\n      for (long i = 0; i < m_half; i++) {\n         if (wtab[i] != w_i || wqinvtab[i] != LazyPrepMulModPrecon(w_i, q, qinv))\n            Error(\"bad table entry\");\n         w_i = MulMod(w_i, w, q, qinv);\n      }\n   }\n#endif\n}\n\n\n#else\n\n\n// Hacks to make the LAZY code work with ordinary modular arithmetic\n\ntypedef long mint_t;\ntypedef long umint_t;\n\nstatic inline mint_t IdentityMod(mint_t a, mint_t q) { return a; }\nstatic inline mint_t DoubleMod(mint_t a, mint_t q) { return AddMod(a, a, q); }\n\n#define LazyPrepMulModPrecon PrepMulModPrecon\n#define LazyMulModPrecon MulModPrecon\n\n#define LazyReduce1 IdentityMod\n#define LazyReduce2 IdentityMod\n#define LazyAddMod AddMod\n#define LazySubMod SubMod\n#define LazyAddMod2 AddMod\n#define LazySubMod2 SubMod\n#define LazyAddMod4 AddMod\n#define LazySubMod4 SubMod\n#define LazyDoubleMod2 DoubleMod\n#define LazyDoubleMod4 DoubleMod\n\n\nvoid ComputeMultipliers(Vec<FFTVectorPair>& v, long k, mint_t q, mulmod_t qinv, const mint_t* root)\n{\n\n   long old_len = v.length();\n   v.SetLength(k+1);\n\n   for (long s = max(old_len, 1); s <= k; s++) {\n      v[s].wtab_precomp.SetLength(1L << (s-1));\n      v[s].wqinvtab_precomp.SetLength(1L << (s-1));\n   }\n\n   if (k >= 1) {\n      v[1].wtab_precomp[0] = 1;\n      v[1].wqinvtab_precomp[0] = PrepMulModPrecon(1, q, qinv);\n   }\n\n   if (k >= 2) {\n      v[2].wtab_precomp[0] = v[1].wtab_precomp[0];\n      v[2].wtab_precomp[1] = root[2];\n      v[2].wqinvtab_precomp[0] = v[1].wqinvtab_precomp[0];\n      v[2].wqinvtab_precomp[1] = PrepMulModPrecon(root[2], q, qinv);\n   }\n\n   for (long s = 3; s <= k; s++) {\n      long m = 1L << s;\n      long m_half = 1L << (s-1);\n      long m_fourth = 1L << (s-2);\n      mint_t* NTL_RESTRICT wtab = v[s].wtab_precomp.elts();\n      mint_t* NTL_RESTRICT wtab1 = v[s-1].wtab_precomp.elts();\n      mulmod_precon_t* NTL_RESTRICT wqinvtab = v[s].wqinvtab_precomp.elts();\n      mulmod_precon_t* NTL_RESTRICT wqinvtab1 = v[s-1].wqinvtab_precomp.elts();\n\n      mint_t w = root[s];\n      mulmod_precon_t wqinv = PrepMulModPrecon(w, q, qinv);\n\n\n      for (long i = m_half-1, j = m_fourth-1; i >= 0; i -= 2, j--) {\n         mint_t w_j = wtab1[j];\n         mulmod_precon_t wqi_j = wqinvtab1[j];\n\n         mint_t w_i = MulModPrecon(w_j, w, q, wqinv);\n         mulmod_precon_t wqi_i = PrepMulModPrecon(w_i, q, qinv); \n\n         wtab[i-1] = w_j;\n         wqinvtab[i-1] = wqi_j;\n         wtab[i] = w_i;\n         wqinvtab[i] = wqi_i;\n      }\n   }\n\n#if 0\n   // verify result\n   for (long s = 1; s <= k; s++) {\n      mint_t *wtab = v[s].wtab_precomp.elts();\n      mulmod_precon_t *wqinvtab = v[s].wqinvtab_precomp.elts();\n      long m_half = 1L << (s-1);\n\n      mint_t w = root[s];\n      mint_t w_i = 1;\n      for (long i = 0; i < m_half; i++) {\n         if (wtab[i] != w_i || wqinvtab[i] != PrepMulModPrecon(w_i, q, qinv))\n            Error(\"bad table entry\");\n         w_i = MulMod(w_i, w, q, qinv);\n      }\n   }\n#endif\n}\n\n#endif\n\n\n\nstatic\nvoid LazyPrecompFFTMultipliers(long k, mint_t q, mulmod_t qinv, const mint_t *root, const FFTMultipliers& tab)\n{\n   if (k < 1) LogicError(\"LazyPrecompFFTMultipliers: bad input\");\n\n   do { // NOTE: thread safe lazy init\n      FFTMultipliers::Builder bld(tab, k+1);\n      long amt = bld.amt();\n      if (!amt) break;\n\n      long first = k+1-amt;\n      // initialize entries first..k\n\n\n      for (long s = first; s <= k; s++) {\n         UniquePtr<FFTVectorPair> item;\n\n         if (s == 0) {\n            bld.move(item); // position 0 not used\n            continue;\n         }\n\n         if (s == 1) {\n            item.make();\n            item->wtab_precomp.SetLength(1);\n            item->wqinvtab_precomp.SetLength(1);\n            item->wtab_precomp[0] = 1;\n            item->wqinvtab_precomp[0] = LazyPrepMulModPrecon(1, q, qinv);\n            bld.move(item);\n            continue;\n         }\n\n         item.make();\n         item->wtab_precomp.SetLength(1L << (s-1));\n         item->wqinvtab_precomp.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         const mint_t *wtab_last = tab[s-1]->wtab_precomp.elts();\n         const mulmod_precon_t *wqinvtab_last = tab[s-1]->wqinvtab_precomp.elts();\n\n         mint_t *wtab = item->wtab_precomp.elts();\n         mulmod_precon_t *wqinvtab = item->wqinvtab_precomp.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         mint_t w = root[s];\n         mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, qinv);\n\n         // prepare wtab...\n\n         if (s == 2) {\n            wtab[1] = LazyReduce1(LazyMulModPrecon(wtab[0], w, q, wqinv), q);\n            wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\n         }\n         else {\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] = LazyReduce1(LazyMulModPrecon(wtab[i-1], w, q, wqinv), q);\n\n            i -= 2; j --;\n\n            for (; i >= 0; i -= 2, j --) {\n               mint_t wp2 = wtab[i+2];\n               mint_t 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] = LazyReduce1(LazyMulModPrecon(wm1, w, q, wqinv), q);\n            }\n\n            wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\n         }\n\n         bld.move(item);\n      }\n   } while (0);\n}\n\n\n//===================================================================\n\n// TRUNCATED FFT\n\n// This code is derived from code originally developed\n// by David Harvey.  I include his original documentation,\n// annotated appropriately to highlight differences in\n// the implemebtation (see NOTEs).\n\n/*\n  The DFT is defined as follows.\n\n  Let the input sequence be a_0, ..., a_{N-1}.\n\n  Let w = standard primitive N-th root of 1, i.e. w = g^(2^FFT62_MAX_LGN / N),\n  where g = some fixed element of Z/pZ of order 2^FFT62_MAX_LGN.\n\n  Let Z = an element of (Z/pZ)^* (twisting parameter).\n\n  Then the output sequence is\n    b_j = \\sum_{0 <= i < N} Z^i a_i w^(ij'), for 0 <= j < N,\n  where j' is the length-lgN bit-reversal of j.\n\n  Some of the FFT routines can operate on truncated sequences of certain\n  \"admissible\" sizes. A size parameter n is admissible if 1 <= n <= N, and n is\n  divisible by a certain power of 2. The precise power depends on the recursive\n  array decomposition of the FFT. The smallest admissible n' >= n can be\n  obtained via fft62_next_size().\n*/\n\n// NOTE: the twising parameter is not implemented.\n// NOTE: the next admissible size function is called FFTRoundUp,\n//   and is defined in FFT.h.  \n\n\n/*\n  Truncated FFT interface is as follows:\n\n  xn and yn must be admissible sizes for N.\n\n  Input in xp[] is a_0, a_1, ..., a_{xn-1}. Assumes a_i = 0 for xn <= i < N.\n\n  Output in yp[] is b_0, ..., b_{yn-1}, i.e. only first yn outputs are computed.\n\n  Twisting parameter Z is described by z and lgH. If z == 0, then Z = basic\n  2^lgH-th root of 1, and must have lgH >= lgN + 1. If z != 0, then Z = z\n  (and lgH is ignored).\n\n  The buffers {xp,xn} and {yp,yn} may overlap, but only if xp == yp.\n\n  Inputs are in [0, 2p), outputs are in [0, 2p).\n\n  threads = number of OpenMP threads to use.\n*/\n\n\n\n/*\n  Inverse truncated FFT interface is as follows.\n\n  xn and yn must be admissible sizes for N, with yn <= xn.\n\n  Input in xp[] is b_0, b_1, ..., b_{yn-1}, N*a_{yn}, ..., N*a_{xn-1}.\n\n  Assumes a_i = 0 for xn <= i < N.\n\n  Output in yp[] is N*a_0, ..., N*a_{yn-1}.\n\n  Twisting parameter Z is described by z and lgH. If z == 0, then Z = basic\n  2^lgH-th root of 1, and must have lgH >= lgN + 1. If z != 0, then Z = z^(-1)\n  (and lgH is ignored).\n\n  The buffers {xp,xn} and {yp,yn} may overlap, but only if xp == yp.\n\n  Inputs are in [0, 4p), outputs are in [0, 4p).\n\n  threads = number of OpenMP threads to use.\n\n  (note: no function actually implements this interface in full generality!\n  This is because it is tricky (and not that useful) to implement the twisting\n  parameter when xn != yn.)\n*/\n\n// NOTE: threads and twisting parameter are not used here. \n// NOTE: the code has been re-written and simplified so that\n//   everything is done in place, so xp == yp.\n\n\n\n\n//===================================================================\n\n\n\n\n\n\n// NOTE: these could be inlined, but I found the code generation\n// to be extremely sensitive to seemingly trivial changes,\n// so it seems safest to use macros instead.\n// w and wqinv are read only once.\n// q is read several times.\n// xx0, xx1 are read once and written once\n\n#define fwd_butterfly(xx0, xx1, w, q, wqinv)  \\\ndo \\\n{ \\\n   umint_t x0_ = xx0; \\\n   umint_t x1_ = xx1; \\\n   umint_t t_  = LazySubMod(x0_, x1_, q); \\\n   xx0 = LazyAddMod2(x0_, x1_, q); \\\n   xx1 = LazyMulModPrecon(t_, w, q, wqinv); \\\n}  \\\nwhile (0)\n\n#define fwd_butterfly_neg(xx0, xx1, w, q, wqinv)  \\\ndo \\\n{ \\\n   umint_t x0_ = xx0; \\\n   umint_t x1_ = xx1; \\\n   umint_t t_  = LazySubMod(x1_, x0_, q); /* NEG */ \\\n   xx0 = LazyAddMod2(x0_, x1_, q); \\\n   xx1 = LazyMulModPrecon(t_, w, q, wqinv); \\\n}  \\\nwhile (0)\n\n#define fwd_butterfly1(xx0, xx1, w, q, wqinv, w1, w1qinv)  \\\ndo \\\n{ \\\n   umint_t x0_ = xx0; \\\n   umint_t x1_ = xx1; \\\n   umint_t t_  = LazySubMod(x0_, x1_, q); \\\n   xx0 = LazyAddMod2(x0_, x1_, q); \\\n   xx1 = LazyMulModPrecon(LazyMulModPrecon(t_, w1, q, w1qinv), w, q, wqinv); \\\n}  \\\nwhile (0)\n\n\n#define fwd_butterfly0(xx0, xx1, q) \\\ndo   \\\n{  \\\n   umint_t x0_ = xx0;  \\\n   umint_t x1_ = xx1;  \\\n   xx0 = LazyAddMod2(x0_, x1_, q);  \\\n   xx1 = LazySubMod2(x0_, x1_, q);  \\\n}  \\\nwhile (0)\n\n\n#define NTL_NEW_FFT_THRESH (11)\n\nstruct new_mod_t {\n   mint_t q;\n   const mint_t **wtab;\n   const mulmod_precon_t **wqinvtab;\n};\n\n\n\n\n\n// requires size divisible by 8\nstatic void\nnew_fft_layer(umint_t* xp, long blocks, long size,\n              const mint_t* NTL_RESTRICT wtab, \n              const mulmod_precon_t* NTL_RESTRICT wqinvtab, \n              mint_t q)\n{\n  size /= 2;\n\n  do\n    {\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + size;\n\n      // first 4 butterflies\n      fwd_butterfly0(xp0[0+0], xp1[0+0], q);\n      fwd_butterfly(xp0[0+1], xp1[0+1], wtab[0+1], q, wqinvtab[0+1]);\n      fwd_butterfly(xp0[0+2], xp1[0+2], wtab[0+2], q, wqinvtab[0+2]);\n      fwd_butterfly(xp0[0+3], xp1[0+3], wtab[0+3], q, wqinvtab[0+3]);\n\n      // 4-way unroll\n      for (long j = 4; j < size; j += 4) {\n        fwd_butterfly(xp0[j+0], xp1[j+0], wtab[j+0], q, wqinvtab[j+0]);\n        fwd_butterfly(xp0[j+1], xp1[j+1], wtab[j+1], q, wqinvtab[j+1]);\n        fwd_butterfly(xp0[j+2], xp1[j+2], wtab[j+2], q, wqinvtab[j+2]);\n        fwd_butterfly(xp0[j+3], xp1[j+3], wtab[j+3], q, wqinvtab[j+3]);\n      }\n\n      xp += 2 * size;\n    }\n  while (--blocks != 0);\n}\n\n\nstatic void\nnew_fft_last_two_layers(umint_t* xp, long blocks,\n\t\t\t  const mint_t* wtab, const mulmod_precon_t* wqinvtab, \n                          mint_t q)\n{\n  // 4th root of unity\n  mint_t w = wtab[1];\n  mulmod_precon_t wqinv = wqinvtab[1];\n\n  do\n    {\n      umint_t u0 = xp[0];\n      umint_t u1 = xp[1];\n      umint_t u2 = xp[2];\n      umint_t u3 = xp[3];\n\n      umint_t v0 = LazyAddMod2(u0, u2, q);\n      umint_t v2 = LazySubMod2(u0, u2, q);\n      umint_t v1 = LazyAddMod2(u1, u3, q);\n      umint_t t  = LazySubMod(u1, u3, q);\n      umint_t v3 = LazyMulModPrecon(t, w, q, wqinv);\n\n      xp[0] = LazyAddMod2(v0, v1, q);\n      xp[1] = LazySubMod2(v0, v1, q);\n      xp[2] = LazyAddMod2(v2, v3, q);\n      xp[3] = LazySubMod2(v2, v3, q);\n\n      xp += 4;\n    }\n  while (--blocks != 0);\n}\n\n\n\nvoid new_fft_base(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  if (lgN == 0) return;\n\n  mint_t q = mod.q;\n\n  if (lgN == 1)\n    {\n      umint_t x0 = xp[0];\n      umint_t x1 = xp[1];\n      xp[0] = LazyAddMod2(x0, x1, q);\n      xp[1] = LazySubMod2(x0, x1, q);\n      return;\n    }\n\n  const mint_t** wtab = mod.wtab;\n  const mulmod_precon_t** wqinvtab = mod.wqinvtab;\n\n  long N = 1L << lgN;\n\n  for (long j = lgN, size = N, blocks = 1; \n       j > 2; j--, blocks <<= 1, size >>= 1)\n    new_fft_layer(xp, blocks, size, wtab[j], wqinvtab[j], q);\n\n  new_fft_last_two_layers(xp, N/4, wtab[2], wqinvtab[2], q);\n}\n\n\n// Implements the truncated FFT interface, described above.\n// All computations done in place, and xp should point to \n// an array of size N, all of which may be overwitten\n// during the computation.\nstatic\nvoid new_fft_short(umint_t* xp, long yn, long xn, long lgN, \n                   const new_mod_t& mod)\n{\n  long N = 1L << lgN;\n\n  if (yn == N)\n    {\n      if (xn == N && lgN <= NTL_NEW_FFT_THRESH)\n\t{\n\t  // no truncation\n\t  new_fft_base(xp, lgN, mod);\n\t  return;\n\t}\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  if (yn <= half)\n    {\n      if (xn <= half)\n\t{\n\t  new_fft_short(xp, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> X + Y\n\t  for (long j = 0; j < xn; j++)\n\t    xp[j] = LazyAddMod2(xp[j], xp[j + half], q);\n\n\t  new_fft_short(xp, yn, half, lgN - 1, mod);\n\t}\n    }\n  else\n    {\n      yn -= half;\n      \n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + half;\n      const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN];\n      const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN];\n\n      if (xn <= half)\n\t{\n\t  // X -> (X, w*X)\n\t  for (long j = 0; j < xn; j++)\n\t    xp1[j] = LazyMulModPrecon(xp0[j], wtab[j], q, wqinvtab[j]);\n\n\t  new_fft_short(xp0, half, xn, lgN - 1, mod);\n\t  new_fft_short(xp1, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> (X + Y, w*(X - Y))\n          // DIRT: assumes xn is a multiple of 4\n          fwd_butterfly0(xp0[0], xp1[0], q);\n          fwd_butterfly(xp0[1], xp1[1], wtab[1], q, wqinvtab[1]);\n          fwd_butterfly(xp0[2], xp1[2], wtab[2], q, wqinvtab[2]);\n          fwd_butterfly(xp0[3], xp1[3], wtab[3], q, wqinvtab[3]);\n\t  for (long j = 4; j < xn; j+=4) {\n            fwd_butterfly(xp0[j+0], xp1[j+0], wtab[j+0], q, wqinvtab[j+0]);\n            fwd_butterfly(xp0[j+1], xp1[j+1], wtab[j+1], q, wqinvtab[j+1]);\n            fwd_butterfly(xp0[j+2], xp1[j+2], wtab[j+2], q, wqinvtab[j+2]);\n            fwd_butterfly(xp0[j+3], xp1[j+3], wtab[j+3], q, wqinvtab[j+3]);\n          }\n\n\t  // X -> (X, w*X)\n\t  for (long j = xn; j < half; j++)\n\t    xp1[j] = LazyMulModPrecon(xp0[j], wtab[j], q, wqinvtab[j]);\n\n\t  new_fft_short(xp0, half, half, lgN - 1, mod);\n\t  new_fft_short(xp1, yn, half, lgN - 1, mod);\n\t}\n    }\n}\n\nstatic\nvoid new_fft_short_notab(umint_t* xp, long yn, long xn, long lgN, \n                   const new_mod_t& mod, mint_t w, mulmod_precon_t wqinv)\n// This version assumes that we only have tables up to level lgN-1,\n// and w generates the values at level lgN.\n// DIRT: requires xn even\n{\n  long N = 1L << lgN;\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  if (yn <= half)\n    {\n      if (xn <= half)\n\t{\n\t  new_fft_short(xp, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> X + Y\n\t  for (long j = 0; j < xn; j++)\n\t    xp[j] = LazyAddMod2(xp[j], xp[j + half], q);\n\n\t  new_fft_short(xp, yn, half, lgN - 1, mod);\n\t}\n    }\n  else\n    {\n      yn -= half;\n      \n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + half;\n      const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN-1];\n      const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN-1];\n\n      if (xn <= half)\n\t{\n\t  // X -> (X, w*X)\n\t  for (long j = 0, j_half = 0; j < xn; j+=2, j_half++) {\n\t    xp1[j] = LazyMulModPrecon(xp0[j], wtab[j_half], q, wqinvtab[j_half]);\n\t    xp1[j+1] = LazyMulModPrecon(LazyMulModPrecon(xp0[j+1], w, q, wqinv), \n                                        wtab[j_half], q, wqinvtab[j_half]);\n          }\n\n\t  new_fft_short(xp0, half, xn, lgN - 1, mod);\n\t  new_fft_short(xp1, yn, xn, lgN - 1, mod);\n\t}\n      else\n\t{\n\t  xn -= half;\n\n\t  // (X, Y) -> (X + Y, w*(X - Y))\n          fwd_butterfly0(xp0[0], xp1[0], q);\n          fwd_butterfly(xp0[1], xp1[1], w, q, wqinv);\n          long j = 2;\n          long j_half = 1;\n\t  for (; j < xn; j+=2, j_half++) {\n            fwd_butterfly(xp0[j], xp1[j], wtab[j_half], q, wqinvtab[j_half]);\n            fwd_butterfly1(xp0[j+1], xp1[j+1], wtab[j_half], q, wqinvtab[j_half], w, wqinv);\n          }\n\n\t  // X -> (X, w*X)\n\t  for (; j < half; j+=2, j_half++) {\n\t    xp1[j] = LazyMulModPrecon(xp0[j], wtab[j_half], q, wqinvtab[j_half]);\n\t    xp1[j+1] = LazyMulModPrecon(LazyMulModPrecon(xp0[j+1], w, q, wqinv), \n                                        wtab[j_half], q, wqinvtab[j_half]);\n          }\n\n\t  new_fft_short(xp0, half, half, lgN - 1, mod);\n\t  new_fft_short(xp1, yn, half, lgN - 1, mod);\n\t}\n    }\n}\n\n\n//=====\n\n\n// NOTE: these \"flipped\" routines perform the same\n// functions as their normal, \"unflipped\" counter-parts,\n// except that they work with inverted roots.\n// They also perform no truncation, just to keep things simple.\n// All of this is necessary only to implement the UpdateMap\n// routines for ZZ_pX and zz_pX.\n\n// requires size divisible by 8\nstatic void\nnew_fft_layer_flipped(umint_t* xp, long blocks, long size,\n              const mint_t* wtab, \n              const mulmod_precon_t* wqinvtab, \n              mint_t q)\n{\n  size /= 2;\n\n  const mint_t* NTL_RESTRICT wtab1 = wtab + size;\n  const mulmod_precon_t* NTL_RESTRICT wqinvtab1 = wqinvtab + size;\n\n  do\n    {\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + size;\n\n      // first 4 butterflies\n      fwd_butterfly0(xp0[0+0], xp1[0+0], q);\n      fwd_butterfly_neg(xp0[0+1], xp1[0+1], wtab1[-(0+1)], q, wqinvtab1[-(0+1)]);\n      fwd_butterfly_neg(xp0[0+2], xp1[0+2], wtab1[-(0+2)], q, wqinvtab1[-(0+2)]);\n      fwd_butterfly_neg(xp0[0+3], xp1[0+3], wtab1[-(0+3)], q, wqinvtab1[-(0+3)]);\n\n      // 4-way unroll\n      for (long j = 4; j < size; j += 4) {\n        fwd_butterfly_neg(xp0[j+0], xp1[j+0], wtab1[-(j+0)], q, wqinvtab1[-(j+0)]);\n        fwd_butterfly_neg(xp0[j+1], xp1[j+1], wtab1[-(j+1)], q, wqinvtab1[-(j+1)]);\n        fwd_butterfly_neg(xp0[j+2], xp1[j+2], wtab1[-(j+2)], q, wqinvtab1[-(j+2)]);\n        fwd_butterfly_neg(xp0[j+3], xp1[j+3], wtab1[-(j+3)], q, wqinvtab1[-(j+3)]);\n      }\n\n      xp += 2 * size;\n    }\n  while (--blocks != 0);\n}\n\n\n\nstatic void\nnew_fft_last_two_layers_flipped(umint_t* xp, long blocks,\n\t\t\t  const mint_t* wtab, const mulmod_precon_t* wqinvtab, \n                          mint_t q)\n{\n  // 4th root of unity\n  mint_t w = wtab[1];\n  mulmod_precon_t wqinv = wqinvtab[1];\n\n  do\n    {\n      umint_t u0 = xp[0];\n      umint_t u1 = xp[1];\n      umint_t u2 = xp[2];\n      umint_t u3 = xp[3];\n\n      umint_t v0 = LazyAddMod2(u0, u2, q);\n      umint_t v2 = LazySubMod2(u0, u2, q);\n      umint_t v1 = LazyAddMod2(u1, u3, q);\n      umint_t t  = LazySubMod(u3, u1, q); // NEG\n      umint_t v3 = LazyMulModPrecon(t, w, q, wqinv);\n\n      xp[0] = LazyAddMod2(v0, v1, q);\n      xp[1] = LazySubMod2(v0, v1, q);\n      xp[2] = LazyAddMod2(v2, v3, q); \n      xp[3] = LazySubMod2(v2, v3, q); \n\n      xp += 4;\n    }\n  while (--blocks != 0);\n}\n\n\n\nvoid new_fft_base_flipped(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  if (lgN == 0) return;\n\n  mint_t q = mod.q;\n\n  if (lgN == 1)\n    {\n      umint_t x0 = xp[0];\n      umint_t x1 = xp[1];\n      xp[0] = LazyAddMod2(x0, x1, q);\n      xp[1] = LazySubMod2(x0, x1, q);\n      return;\n    }\n\n  const mint_t** wtab = mod.wtab;\n  const mulmod_precon_t** wqinvtab = mod.wqinvtab;\n\n  long N = 1L << lgN;\n\n  for (long j = lgN, size = N, blocks = 1; \n       j > 2; j--, blocks <<= 1, size >>= 1)\n    new_fft_layer_flipped(xp, blocks, size, wtab[j], wqinvtab[j], q);\n\n  new_fft_last_two_layers_flipped(xp, N/4, wtab[2], wqinvtab[2], q);\n}\n\n\nstatic\nvoid new_fft_short_flipped(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  long N = 1L << lgN;\n\n  if (lgN <= NTL_NEW_FFT_THRESH)\n    {\n      new_fft_base_flipped(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  umint_t* NTL_RESTRICT xp0 = xp;\n  umint_t* NTL_RESTRICT xp1 = xp + half;\n  const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN] + half;\n  const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN] + half;\n\n  // (X, Y) -> (X + Y, w*(X - Y))\n\n  fwd_butterfly0(xp0[0], xp1[0], q);\n  fwd_butterfly_neg(xp0[1], xp1[1], wtab[-1], q, wqinvtab[-1]);\n  fwd_butterfly_neg(xp0[2], xp1[2], wtab[-2], q, wqinvtab[-2]);\n  fwd_butterfly_neg(xp0[3], xp1[3], wtab[-3], q, wqinvtab[-3]);\n  for (long j = 4; j < half; j+=4) {\n    fwd_butterfly_neg(xp0[j+0], xp1[j+0], wtab[-(j+0)], q, wqinvtab[-(j+0)]);\n    fwd_butterfly_neg(xp0[j+1], xp1[j+1], wtab[-(j+1)], q, wqinvtab[-(j+1)]);\n    fwd_butterfly_neg(xp0[j+2], xp1[j+2], wtab[-(j+2)], q, wqinvtab[-(j+2)]);\n    fwd_butterfly_neg(xp0[j+3], xp1[j+3], wtab[-(j+3)], q, wqinvtab[-(j+3)]);\n  }\n\n  new_fft_short_flipped(xp0, lgN - 1, mod);\n  new_fft_short_flipped(xp1, lgN - 1, mod);\n}\n\n\n\n// IFFT (inverse truncated FFT)\n\n\n#define inv_butterfly0(xx0, xx1, q)  \\\ndo   \\\n{  \\\n   umint_t x0_ = LazyReduce2(xx0, q);  \\\n   umint_t x1_ = LazyReduce2(xx1, q);  \\\n   xx0 = LazyAddMod(x0_, x1_, q);  \\\n   xx1 = LazySubMod(x0_, x1_, q);  \\\n} while (0)  \n\n\n#define inv_butterfly_neg(xx0, xx1, w, q, wqinv)  \\\ndo  \\\n{  \\\n   umint_t x0_ = LazyReduce2(xx0, q);  \\\n   umint_t x1_ = xx1;  \\\n   umint_t t_ = LazyMulModPrecon(x1_, w, q, wqinv);   \\\n   xx0 = LazySubMod(x0_, t_, q);  /* NEG */   \\\n   xx1 = LazyAddMod(x0_, t_, q);  /* NEG */   \\\n} while (0)\n   \n#define inv_butterfly(xx0, xx1, w, q, wqinv)  \\\ndo  \\\n{  \\\n   umint_t x0_ = LazyReduce2(xx0, q);  \\\n   umint_t x1_ = xx1;  \\\n   umint_t t_ = LazyMulModPrecon(x1_, w, q, wqinv);   \\\n   xx0 = LazyAddMod(x0_, t_, q);    \\\n   xx1 = LazySubMod(x0_, t_, q);    \\\n} while (0)\n   \n#define inv_butterfly1_neg(xx0, xx1, w, q, wqinv, w1, w1qinv)  \\\ndo  \\\n{  \\\n   umint_t x0_ = LazyReduce2(xx0, q);  \\\n   umint_t x1_ = xx1;  \\\n   umint_t t_ = LazyMulModPrecon(LazyMulModPrecon(x1_, w1, q, w1qinv), w, q, wqinv);   \\\n   xx0 = LazySubMod(x0_, t_, q);  /* NEG */   \\\n   xx1 = LazyAddMod(x0_, t_, q);  /* NEG */   \\\n} while (0)\n\n\nstatic\nvoid new_ifft_short2(umint_t* yp, long yn, long lgN, const new_mod_t& mod);\n\n\n\n// requires size divisible by 8\nstatic void\nnew_ifft_layer(umint_t* xp, long blocks, long size,\n\t\t const mint_t* wtab, \n                 const mulmod_precon_t* wqinvtab, mint_t q)\n{\n\n  size /= 2;\n  const mint_t* NTL_RESTRICT wtab1 = wtab + size;\n  const mulmod_precon_t* NTL_RESTRICT wqinvtab1 = wqinvtab + size;\n\n  do\n    {\n\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + size;\n\n\n      // first 4 butterflies\n      inv_butterfly0(xp0[0], xp1[0], q);\n      inv_butterfly_neg(xp0[1], xp1[1], wtab1[-1], q, wqinvtab1[-1]); \n      inv_butterfly_neg(xp0[2], xp1[2], wtab1[-2], q, wqinvtab1[-2]); \n      inv_butterfly_neg(xp0[3], xp1[3], wtab1[-3], q, wqinvtab1[-3]); \n\n      // 4-way unroll\n      for (long j = 4; j < size; j+= 4) {\n\t inv_butterfly_neg(xp0[j+0], xp1[j+0], wtab1[-(j+0)], q, wqinvtab1[-(j+0)]); \n\t inv_butterfly_neg(xp0[j+1], xp1[j+1], wtab1[-(j+1)], q, wqinvtab1[-(j+1)]); \n\t inv_butterfly_neg(xp0[j+2], xp1[j+2], wtab1[-(j+2)], q, wqinvtab1[-(j+2)]); \n\t inv_butterfly_neg(xp0[j+3], xp1[j+3], wtab1[-(j+3)], q, wqinvtab1[-(j+3)]); \n      }\n\n      xp += 2 * size;\n    }\n  while (--blocks != 0);\n}\n\n\nstatic void\nnew_ifft_first_two_layers(umint_t* xp, long blocks, const mint_t* wtab, \n                          const mulmod_precon_t* wqinvtab, mint_t q)\n{\n  // 4th root of unity\n  mint_t w = wtab[1];\n  mulmod_precon_t wqinv = wqinvtab[1];\n\n  do\n    {\n      umint_t u0 = LazyReduce2(xp[0], q);\n      umint_t u1 = LazyReduce2(xp[1], q);\n      umint_t u2 = LazyReduce2(xp[2], q);\n      umint_t u3 = LazyReduce2(xp[3], q);\n\n      umint_t v0 = LazyAddMod2(u0, u1, q);\n      umint_t v1 = LazySubMod2(u0, u1, q);\n      umint_t v2 = LazyAddMod2(u2, u3, q);\n      umint_t t  = LazySubMod(u2, u3, q);\n      umint_t v3 = LazyMulModPrecon(t, w, q, wqinv);\n\n      xp[0] = LazyAddMod(v0, v2, q);\n      xp[2] = LazySubMod(v0, v2, q);\n      xp[1] = LazySubMod(v1, v3, q);  // NEG\n      xp[3] = LazyAddMod(v1, v3, q);  // NEG\n\n      xp += 4;\n    }\n  while (--blocks != 0);\n}\n\n\n\nstatic\nvoid new_ifft_base(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  if (lgN == 0) return;\n\n  mint_t q = mod.q;\n\n  if (lgN == 1)\n    {\n      umint_t x0 = LazyReduce2(xp[0], q);\n      umint_t x1 = LazyReduce2(xp[1], q);\n      xp[0] = LazyAddMod(x0, x1, q);\n      xp[1] = LazySubMod(x0, x1, q);\n      return;\n    }\n\n  const mint_t** wtab = mod.wtab;\n  const mulmod_precon_t** wqinvtab = mod.wqinvtab;\n\n  long blocks = 1L << (lgN - 2);\n  new_ifft_first_two_layers(xp, blocks, wtab[2], wqinvtab[2], q);\n  blocks >>= 1;\n\n  long size = 8;\n  for (long j = 3; j <= lgN; j++, blocks >>= 1, size <<= 1)\n    new_ifft_layer(xp, blocks, size, wtab[j], wqinvtab[j], q);\n}\n\n\nstatic\nvoid new_ifft_short1(umint_t* xp, long yn, long lgN, const new_mod_t& mod)\n\n// Implements truncated inverse FFT interface, but with xn==yn.\n// All computations are done in place.\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N && lgN <= NTL_NEW_FFT_THRESH)\n    {\n      // no truncation\n      new_ifft_base(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j++)\n      \txp[j] = LazyDoubleMod4(xp[j], q);\n\n      new_ifft_short1(xp, yn, lgN - 1, mod);\n    }\n  else\n    {\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + half;\n      const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN];\n      const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN];\n\n      new_ifft_short1(xp0, half, lgN - 1, mod);\n\n      yn -= half;\n\n      // X -> (2X, w*X)\n      for (long j = yn; j < half; j++)\n\t{\n\t  umint_t x0 = xp0[j];\n\t  xp0[j] = LazyDoubleMod4(x0, q);\n\t  xp1[j] = LazyMulModPrecon(x0, wtab[j], q, wqinvtab[j]);\n\t}\n\n      new_ifft_short2(xp1, yn, lgN - 1, mod);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      {\n\tconst mint_t* NTL_RESTRICT wtab1 = wtab + half;\n\tconst mulmod_precon_t* NTL_RESTRICT wqinvtab1 =  wqinvtab + half;\n\n\t// DIRT: assumes yn is a multiple of 4\n\tinv_butterfly0(xp0[0], xp1[0], q);\n\tinv_butterfly_neg(xp0[1], xp1[1], wtab1[-1], q, wqinvtab1[-1]);\n\tinv_butterfly_neg(xp0[2], xp1[2], wtab1[-2], q, wqinvtab1[-2]);\n\tinv_butterfly_neg(xp0[3], xp1[3], wtab1[-3], q, wqinvtab1[-3]);\n\tfor (long j = 4; j < yn; j+=4) {\n\t  inv_butterfly_neg(xp0[j+0], xp1[j+0], wtab1[-(j+0)], q, wqinvtab1[-(j+0)]);\n\t  inv_butterfly_neg(xp0[j+1], xp1[j+1], wtab1[-(j+1)], q, wqinvtab1[-(j+1)]);\n\t  inv_butterfly_neg(xp0[j+2], xp1[j+2], wtab1[-(j+2)], q, wqinvtab1[-(j+2)]);\n\t  inv_butterfly_neg(xp0[j+3], xp1[j+3], wtab1[-(j+3)], q, wqinvtab1[-(j+3)]);\n\t}\n      }\n    }\n}\n\n\nstatic\nvoid new_ifft_short1_notab(umint_t* xp, long yn, long lgN, const new_mod_t& mod,\n                           mint_t w, mulmod_precon_t wqinv,\n                           mint_t iw, mulmod_precon_t iwqinv)\n// This version assumes that we only have tables up to level lgN-1,\n// and w generates the values at level lgN.\n// DIRT: requires yn even\n{\n  long N = 1L << lgN;\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j++)\n      \txp[j] = LazyDoubleMod4(xp[j], q);\n\n      new_ifft_short1(xp, yn, lgN - 1, mod);\n    }\n  else\n    {\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + half;\n      const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN-1];\n      const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN-1];\n\n      new_ifft_short1(xp0, half, lgN - 1, mod);\n\n      yn -= half;\n\n      // X -> (2X, w*X)\n      for (long j = yn, j_half = yn/2; j < half; j+=2, j_half++) {\n\t{\n\t  umint_t x0 = xp0[j+0];\n\t  xp0[j+0] = LazyDoubleMod4(x0, q);\n\t  xp1[j+0] = LazyMulModPrecon(x0, wtab[j_half], q, wqinvtab[j_half]);\n\t}\n\t{\n\t  umint_t x0 = xp0[j+1];\n\t  xp0[j+1] = LazyDoubleMod4(x0, q);\n\t  xp1[j+1] = LazyMulModPrecon(LazyMulModPrecon(x0, w, q, wqinv), \n                                      wtab[j_half], q, wqinvtab[j_half]);\n\t}\n      }\n\n      new_ifft_short2(xp1, yn, lgN - 1, mod);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      {\n\tconst mint_t* NTL_RESTRICT wtab1 = wtab + half/2;\n\tconst mulmod_precon_t* NTL_RESTRICT wqinvtab1 =  wqinvtab + half/2;\n\n\tinv_butterfly0(xp0[0], xp1[0], q);\n\tinv_butterfly(xp0[1], xp1[1], iw, q, iwqinv);\n\tfor (long j = 2, j_half = 1; j < yn; j+=2, j_half++) {\n\t  inv_butterfly_neg(xp0[j+0], xp1[j+0], wtab1[-j_half], q, wqinvtab1[-j_half]);\n\t  inv_butterfly1_neg(xp0[j+1], xp1[j+1], wtab1[-j_half], q, wqinvtab1[-j_half], iw, iwqinv);\n\t}\n      }\n    }\n}\n\n\n\n//=========\n\n\n// requires size divisible by 8\nstatic void\nnew_ifft_layer_flipped(umint_t* xp, long blocks, long size,\n\t\t const mint_t* NTL_RESTRICT wtab, \n                 const mulmod_precon_t* NTL_RESTRICT wqinvtab, mint_t q)\n{\n\n  size /= 2;\n\n  do\n    {\n\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + size;\n\n\n      // first 4 butterflies\n      inv_butterfly0(xp0[0], xp1[0], q);\n      inv_butterfly(xp0[1], xp1[1], wtab[1], q, wqinvtab[1]); \n      inv_butterfly(xp0[2], xp1[2], wtab[2], q, wqinvtab[2]); \n      inv_butterfly(xp0[3], xp1[3], wtab[3], q, wqinvtab[3]); \n\n      // 4-way unroll\n      for (long j = 4; j < size; j+= 4) {\n\t inv_butterfly(xp0[j+0], xp1[j+0], wtab[j+0], q, wqinvtab[j+0]); \n\t inv_butterfly(xp0[j+1], xp1[j+1], wtab[j+1], q, wqinvtab[j+1]); \n\t inv_butterfly(xp0[j+2], xp1[j+2], wtab[j+2], q, wqinvtab[j+2]); \n\t inv_butterfly(xp0[j+3], xp1[j+3], wtab[j+3], q, wqinvtab[j+3]); \n      }\n\n      xp += 2 * size;\n    }\n  while (--blocks != 0);\n}\n\n\nstatic void\nnew_ifft_first_two_layers_flipped(umint_t* xp, long blocks, const mint_t* wtab, \n                          const mulmod_precon_t* wqinvtab, mint_t q)\n{\n  // 4th root of unity\n  mint_t w = wtab[1];\n  mulmod_precon_t wqinv = wqinvtab[1];\n\n  do\n    {\n      umint_t u0 = LazyReduce2(xp[0], q);\n      umint_t u1 = LazyReduce2(xp[1], q);\n      umint_t u2 = LazyReduce2(xp[2], q);\n      umint_t u3 = LazyReduce2(xp[3], q);\n\n      umint_t v0 = LazyAddMod2(u0, u1, q);\n      umint_t v1 = LazySubMod2(u0, u1, q);\n      umint_t v2 = LazyAddMod2(u2, u3, q);\n      umint_t t  = LazySubMod(u2, u3, q);\n      umint_t v3 = LazyMulModPrecon(t, w, q, wqinv);\n\n      xp[0] = LazyAddMod(v0, v2, q);\n      xp[2] = LazySubMod(v0, v2, q);\n      xp[1] = LazyAddMod(v1, v3, q);  \n      xp[3] = LazySubMod(v1, v3, q); \n\n      xp += 4;\n    }\n  while (--blocks != 0);\n}\n\n\n\nstatic\nvoid new_ifft_base_flipped(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  if (lgN == 0) return;\n\n  mint_t q = mod.q;\n\n  if (lgN == 1)\n    {\n      umint_t x0 = LazyReduce2(xp[0], q);\n      umint_t x1 = LazyReduce2(xp[1], q);\n      xp[0] = LazyAddMod(x0, x1, q);\n      xp[1] = LazySubMod(x0, x1, q);\n      return;\n    }\n\n  const mint_t** wtab = mod.wtab;\n  const mulmod_precon_t** wqinvtab = mod.wqinvtab;\n\n  long blocks = 1L << (lgN - 2);\n  new_ifft_first_two_layers_flipped(xp, blocks, wtab[2], wqinvtab[2], q);\n  blocks >>= 1;\n\n  long size = 8;\n  for (long j = 3; j <= lgN; j++, blocks >>= 1, size <<= 1)\n    new_ifft_layer_flipped(xp, blocks, size, wtab[j], wqinvtab[j], q);\n}\n\n\nstatic\nvoid new_ifft_short1_flipped(umint_t* xp, long lgN, const new_mod_t& mod)\n{\n  long N = 1L << lgN;\n\n  if (lgN <= NTL_NEW_FFT_THRESH)\n    {\n      new_ifft_base_flipped(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  umint_t* NTL_RESTRICT xp0 = xp;\n  umint_t* NTL_RESTRICT xp1 = xp + half;\n  const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN];\n  const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN];\n\n  new_ifft_short1_flipped(xp0, lgN - 1, mod);\n  new_ifft_short1_flipped(xp1, lgN - 1, mod);\n\n  // (X, Y) -> (X + Y*w, X - Y*w)\n\n  inv_butterfly0(xp0[0], xp1[0], q);\n  inv_butterfly(xp0[1], xp1[1], wtab[1], q, wqinvtab[1]);\n  inv_butterfly(xp0[2], xp1[2], wtab[2], q, wqinvtab[2]);\n  inv_butterfly(xp0[3], xp1[3], wtab[3], q, wqinvtab[3]);\n  for (long j = 4; j < half; j+=4) {\n    inv_butterfly(xp0[j+0], xp1[j+0], wtab[j+0], q, wqinvtab[j+0]);\n    inv_butterfly(xp0[j+1], xp1[j+1], wtab[j+1], q, wqinvtab[j+1]);\n    inv_butterfly(xp0[j+2], xp1[j+2], wtab[j+2], q, wqinvtab[j+2]);\n    inv_butterfly(xp0[j+3], xp1[j+3], wtab[j+3], q, wqinvtab[j+3]);\n  }\n}\n\n//=========\n\n\n\nstatic\nvoid new_ifft_short2(umint_t* xp, long yn, long lgN, const new_mod_t& mod)\n\n// Implements truncated inverse FFT interface, but with xn==N.\n// All computations are done in place.\n\n{\n  long N = 1L << lgN;\n\n  if (yn == N && lgN <= NTL_NEW_FFT_THRESH)\n    {\n      // no truncation\n      new_ifft_base(xp, lgN, mod);\n      return;\n    }\n\n  // divide-and-conquer algorithm\n\n  long half = N >> 1;\n  mint_t q = mod.q;\n\n  if (yn <= half)\n    {\n      // X -> 2X\n      for (long j = 0; j < yn; j++)\n     \txp[j] = LazyDoubleMod4(xp[j], q);\n      // (X, Y) -> X + Y\n      for (long j = yn; j < half; j++)\n\txp[j] = LazyAddMod4(xp[j], xp[j + half], q);\n\n      new_ifft_short2(xp, yn, lgN - 1, mod);\n\n      // (X, Y) -> X - Y\n      for (long j = 0; j < yn; j++)\n\txp[j] = LazySubMod4(xp[j], xp[j + half], q);\n    }\n  else\n    {\n      umint_t* NTL_RESTRICT xp0 = xp;\n      umint_t* NTL_RESTRICT xp1 = xp + half;\n      const mint_t* NTL_RESTRICT wtab = mod.wtab[lgN];\n      const mulmod_precon_t* NTL_RESTRICT wqinvtab = mod.wqinvtab[lgN];\n\n      new_ifft_short1(xp0, half, lgN - 1, mod);\n\n      yn -= half;\n\n\n      // (X, Y) -> (2X - Y, w*(X - Y))\n      for (long j = yn; j < half; j++)\n\t{\n\t  umint_t x0 = xp0[j];\n\t  umint_t x1 = xp1[j];\n\t  umint_t u = LazySubMod4(x0, x1, q);\n\t  xp0[j] = LazyAddMod4(x0, u, q);\n\t  xp1[j] = LazyMulModPrecon(u, wtab[j], q, wqinvtab[j]);\n\t}\n\n      new_ifft_short2(xp1, yn, lgN - 1, mod);\n\n      // (X, Y) -> (X + Y/w, X - Y/w)\n      {\n\tconst mint_t* NTL_RESTRICT wtab1 = wtab + half;\n\tconst mulmod_precon_t* NTL_RESTRICT wqinvtab1 =  wqinvtab + half;\n\n\t// DIRT: assumes yn is a multiple of 4\n\tinv_butterfly0(xp0[0], xp1[0], q);\n\tinv_butterfly_neg(xp0[1], xp1[1], wtab1[-1], q, wqinvtab1[-1]);\n\tinv_butterfly_neg(xp0[2], xp1[2], wtab1[-2], q, wqinvtab1[-2]);\n\tinv_butterfly_neg(xp0[3], xp1[3], wtab1[-3], q, wqinvtab1[-3]);\n\tfor (long j = 4; j < yn; j+=4) {\n\t  inv_butterfly_neg(xp0[j+0], xp1[j+0], wtab1[-(j+0)], q, wqinvtab1[-(j+0)]);\n\t  inv_butterfly_neg(xp0[j+1], xp1[j+1], wtab1[-(j+1)], q, wqinvtab1[-(j+1)]);\n\t  inv_butterfly_neg(xp0[j+2], xp1[j+2], wtab1[-(j+2)], q, wqinvtab1[-(j+2)]);\n\t  inv_butterfly_neg(xp0[j+3], xp1[j+3], wtab1[-(j+3)], q, wqinvtab1[-(j+3)]);\n\t}\n      }\n    }\n}\n\n\n//=============================================\n\n// HIGH LEVEL ROUTINES\n\n//=========== FFT without tables ===========\n\n\nNTL_TLS_GLOBAL_DECL(Vec<umint_t>, AA_store)\n\nNTL_TLS_GLOBAL_DECL(Vec<FFTVectorPair>, mul_vec)\n\nvoid new_fft_notab(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info,\n             long yn, long xn)\n\n// Performs a high-level FFT.  Inputs and outputs are in the range [0,q). \n// xn and yn are as described above in the truncated FFT interface.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// This version does not use precomputed tables.\n\n{\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t 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   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n\n   NTL_TLS_GLOBAL_ACCESS(mul_vec);\n   ComputeMultipliers(mul_vec, k-1, q, qinv, root);\n\n   long n = 1L << k;\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wtab[s] = mul_vec[s].wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wqinvtab[s] = mul_vec[s].wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   mint_t w = info.RootTable[0][k];\n   mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, info.qinv);\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < xn; i++) AA[i] = a[i];\n\n   new_fft_short_notab(AA, yn, xn, k, mod, w, wqinv);\n\n   for (long i = 0; i < yn; i++) {\n      A[i] = LazyReduce1(AA[i], q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < xn; i++) AA[i] = a[i];\n\n   new_fft_short_notab(AA, yn, xn, k, mod, w, wqinv);\n\n   for (long i = 0; i < yn; i++) {\n      AA[i] = LazyReduce1(AA[i], q);\n   }\n#endif\n}\n\n\nvoid new_fft_flipped_notab(mint_t* A, const mint_t* a, long k, \n             const FFTPrimeInfo& info)\n\n// Performs a high-level FFT.  Inputs and outputs are in the range [0,q). \n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// This version is \"flipped\" -- it uses inverted roots, \n// multiplies by 2^{-k}, and performs no truncations.\n// This version does not use precomputed tables.\n\n{\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t two_inv = info.TwoInvTable[1];\n         mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[1];\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t A1 = SubMod(a[0], a[1], q);\n         A[0] = LazyReduce1(LazyMulModPrecon(A0, two_inv, q, two_inv_aux), q);\n         A[1] = LazyReduce1(LazyMulModPrecon(A1, two_inv, q, two_inv_aux), q);\n\t return;\n      }\n   }\n\n   // assume k > 1\n   const mint_t *root = info.RootTable[1].elts();\n   mulmod_t qinv = info.qinv;\n\n   NTL_TLS_GLOBAL_ACCESS(mul_vec);\n   ComputeMultipliers(mul_vec, k-1, q, qinv, root);\n\n   long n = 1L << k;\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wtab[s] = mul_vec[s].wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wqinvtab[s] = mul_vec[s].wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   mint_t w = info.RootTable[1][k];\n   mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, info.qinv);\n\n   mint_t two_inv = info.TwoInvTable[k];\n   mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[k];\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_fft_short_notab(AA, n, n, k, mod, w, wqinv);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_fft_short_notab(AA, n, n, k, mod, w, wqinv);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      AA[i] = LazyReduce1(tmp, q);\n   }\n\n#endif\n}\n\n\n//=========== Inverse FFT without tables  ===========\n\nvoid new_ifft_notab(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info,\n              long yn)\n\n// Performs a high-level IFFT.  Inputs and outputs are in the range [0,q). \n// yn==xn are as described above in the truncated FFT interface.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// Multiplies by 2^{-k}.\n// This version does not use precomputed tables.\n\n{\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t two_inv = info.TwoInvTable[1];\n         mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[1];\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t A1 = SubMod(a[0], a[1], q);\n         A[0] = LazyReduce1(LazyMulModPrecon(A0, two_inv, q, two_inv_aux), q);\n         A[1] = LazyReduce1(LazyMulModPrecon(A1, two_inv, q, two_inv_aux), q);\n\t return;\n      }\n   }\n\n   // assume k > 1\n   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n\n   NTL_TLS_GLOBAL_ACCESS(mul_vec);\n   ComputeMultipliers(mul_vec, k-1, q, qinv, root);\n\n   long n = 1L << k;\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wtab[s] = mul_vec[s].wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wqinvtab[s] = mul_vec[s].wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n\n   mint_t w = info.RootTable[0][k];\n   mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, info.qinv);\n\n   mint_t iw = info.RootTable[1][k];\n   mulmod_precon_t iwqinv = LazyPrepMulModPrecon(iw, q, info.qinv);\n\n   mint_t two_inv = info.TwoInvTable[k];\n   mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[k];\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < yn; i++) AA[i] = a[i];\n\n   new_ifft_short1_notab(AA, yn, k, mod, w, wqinv, iw, iwqinv);\n\n   for (long i = 0; i < yn; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < yn; i++) AA[i] = a[i];\n\n   new_ifft_short1_notab(AA, yn, k, mod, w, wqinv, iw, iwqinv);\n\n   for (long i = 0; i < yn; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      AA[i] = LazyReduce1(tmp, q);\n   }\n\n#endif\n}\n\n\nvoid new_ifft_flipped_notab(mint_t* A, const mint_t* a, long k, \n              const FFTPrimeInfo& info)\n\n// Performs a high-level IFFT.  Inputs and outputs are in the range [0,q). \n// Flipped means inverse roots are used an no truncation and\n// no multiplication by 2^{-k}.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// This version does not use precomputed tables.\n\n{\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t 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   const mint_t *root = info.RootTable[1].elts();\n   mulmod_t qinv = info.qinv;\n\n   NTL_TLS_GLOBAL_ACCESS(mul_vec);\n   ComputeMultipliers(mul_vec, k-1, q, qinv, root);\n\n   long n = 1L << k;\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wtab[s] = mul_vec[s].wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k-1; s++) wqinvtab[s] = mul_vec[s].wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   mint_t w = info.RootTable[1][k];\n   mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, info.qinv);\n\n   mint_t iw = info.RootTable[0][k];\n   mulmod_precon_t iwqinv = LazyPrepMulModPrecon(iw, q, info.qinv);\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < n; i++) AA[i] = a[i];\n\n\n   new_ifft_short1_notab(AA, n, k, mod, w, wqinv, iw, iwqinv);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyReduce2(AA[i], q);\n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_ifft_short1_notab(AA, n, k, mod, w, wqinv, iw, iwqinv);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyReduce2(AA[i], q);\n      AA[i] = LazyReduce1(tmp, q);\n   }\n#endif\n}\n\n\n#ifndef NTL_ENABLE_AVX_FFT\n\n//================ FFT with tables ==============\n\n\nvoid new_fft(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info, \n             long yn, long xn)\n\n// Performs a high-level FFT.  Inputs and outputs are in the range [0,q). \n// xn and yn are as described above in the truncated FFT interface.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n\n{\n   if (!info.bigtab || k > info.bigtab->bound) {\n      new_fft_notab(A, a, k, info, yn, xn);\n      return;\n   }\n\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t 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   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n   const FFTMultipliers& tab = info.bigtab->MulTab;\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n\n   long n = 1L << k;\n\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < xn; i++) AA[i] = a[i];\n\n   new_fft_short(AA, yn, xn, k, mod);\n\n   for (long i = 0; i < yn; i++) {\n      A[i] = LazyReduce1(AA[i], q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < xn; i++) AA[i] = a[i];\n\n   new_fft_short(AA, yn, xn, k, mod);\n\n   for (long i = 0; i < yn; i++) {\n      AA[i] = LazyReduce1(AA[i], q);\n   }\n#endif\n\n}\n\nvoid new_fft_flipped(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info)\n\n// Performs a high-level FFT.  Inputs and outputs are in the range [0,q). \n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// This version is \"flipped\" -- it uses inverted roots, \n// multiplies by 2^{-k}, and performs no truncations.\n\n{\n   if (!info.bigtab || k > info.bigtab->bound) {\n      new_fft_flipped_notab(A, a, k, info);\n      return;\n   }\n\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t two_inv = info.TwoInvTable[1];\n         mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[1];\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t A1 = SubMod(a[0], a[1], q);\n         A[0] = LazyReduce1(LazyMulModPrecon(A0, two_inv, q, two_inv_aux), q);\n         A[1] = LazyReduce1(LazyMulModPrecon(A1, two_inv, q, two_inv_aux), q);\n\t return;\n      }\n   }\n\n   // assume k > 1\n   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n   const FFTMultipliers& tab = info.bigtab->MulTab;\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n\n   long n = 1L << k;\n\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   mint_t two_inv = info.TwoInvTable[k];\n   mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[k];\n\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_fft_short_flipped(AA, k, mod);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_fft_short_flipped(AA, k, mod);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      AA[i] = LazyReduce1(tmp, q);\n   }\n#endif\n}\n\n//=======  Inverse FFT with tables ==============\n\n\nvoid new_ifft(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info, \n              long yn)\n\n// Performs a high-level IFFT.  Inputs and outputs are in the range [0,q). \n// yn==xn are as described above in the truncated FFT interface.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n// Multiples by 2^{-k}.\n\n{\n   if (!info.bigtab || k > info.bigtab->bound) {\n      new_ifft_notab(A, a, k, info, yn);\n      return;\n   }\n\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t two_inv = info.TwoInvTable[1];\n         mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[1];\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t A1 = SubMod(a[0], a[1], q);\n         A[0] = LazyReduce1(LazyMulModPrecon(A0, two_inv, q, two_inv_aux), q);\n         A[1] = LazyReduce1(LazyMulModPrecon(A1, two_inv, q, two_inv_aux), q);\n\t return;\n      }\n   }\n\n   // assume k > 1\n   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n   const FFTMultipliers& tab = info.bigtab->MulTab;\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n\n   long n = 1L << k;\n\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   mint_t two_inv = info.TwoInvTable[k];\n   mulmod_precon_t two_inv_aux = info.TwoInvPreconTable[k];\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < yn; i++) AA[i] = a[i];\n\n   new_ifft_short1(AA, yn, k, mod);\n\n   for (long i = 0; i < yn; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < yn; i++) AA[i] = a[i];\n\n   new_ifft_short1(AA, yn, k, mod);\n\n   for (long i = 0; i < yn; i++) {\n      umint_t tmp = LazyMulModPrecon(AA[i], two_inv, q, two_inv_aux); \n      AA[i] = LazyReduce1(tmp, q);\n   }\n#endif\n}\n\n\nvoid new_ifft_flipped(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info)\n\n\n// Performs a high-level IFFT.  Inputs and outputs are in the range [0,q). \n// Flipped means inverse roots are used an no truncation and\n// no multiplication by 2^{-k}.\n// Both A and a should point to arrays of size 2^k,\n// and should either be the same or not overlap at all.\n\n\n{\n   if (!info.bigtab || k > info.bigtab->bound) {\n      new_ifft_flipped_notab(A, a, k, info);\n      return;\n   }\n\n   mint_t q = info.q;\n\n   if (k <= 1) {\n      if (k == 0) {\n\t A[0] = a[0];\n\t return;\n      }\n      if (k == 1) {\n         mint_t A0 = AddMod(a[0], a[1], q);\n         mint_t 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   const mint_t *root = info.RootTable[0].elts();\n   mulmod_t qinv = info.qinv;\n   const FFTMultipliers& tab = info.bigtab->MulTab;\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n\n   long n = 1L << k;\n\n\n   const mint_t *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const mulmod_precon_t *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   new_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n\n#ifdef NTL_FFT_USEBUF\n   NTL_TLS_GLOBAL_ACCESS(AA_store);\n   AA_store.SetLength(1L << k);\n   umint_t *AA = AA_store.elts();\n\n   for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_ifft_short1_flipped(AA, k, mod);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyReduce2(AA[i], q);\n      A[i] = LazyReduce1(tmp, q);\n   }\n#else\n   umint_t *AA = (umint_t *) A;\n   if (a != A) for (long i = 0; i < n; i++) AA[i] = a[i];\n\n   new_ifft_short1_flipped(AA, k, mod);\n\n   for (long i = 0; i < n; i++) {\n      umint_t tmp = LazyReduce2(AA[i], q);\n      AA[i] = LazyReduce1(tmp, q);\n   }\n#endif\n}\n\n#endif\n\n//===============================================\n\nvoid InitFFTPrimeInfo(FFTPrimeInfo& info, long q, long w, long bigtab_index)\n{\n   mulmod_t qinv = PrepMulMod(q);\n\n   long mr = CalcMaxRoot(q);\n\n   info.q = q;\n   info.qinv = qinv;\n   info.qrecip = 1/double(q);\n   info.zz_p_context = 0;\n\n\n   info.RootTable[0].SetLength(mr+1);\n   info.RootTable[1].SetLength(mr+1);\n   info.TwoInvTable.SetLength(mr+1);\n   info.TwoInvPreconTable.SetLength(mr+1);\n\n   long *rt = &info.RootTable[0][0];\n   long *rit = &info.RootTable[1][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] = LazyPrepMulModPrecon(tit[j], q, qinv);\n\n#ifndef NTL_ENABLE_AVX_FFT\n   if (bigtab_index != -1) {\n      long bound = NTL_FFT_BIGTAB_MAXROOT-bigtab_index/NTL_FFT_BIGTAB_LIMIT;\n      if (bound > NTL_FFT_BIGTAB_MINROOT) {\n         info.bigtab.make();\n         info.bigtab->bound = bound;\n      }\n   }\n#else\n   // with the AVX implementation, we unconditionally use tables\n   info.bigtab.make();\n#endif\n}\n\n\n//===================================================================\n\n#ifdef NTL_ENABLE_AVX_FFT\n\nstatic void\npd_LazyPrepMulModPrecon(double *bninv, const double *b, double n, long len)\n{\n   CSRPush push;\n   pd_LazyPrepMulModPrecon_impl(bninv, b, n, len);\n}\n\nstatic\nvoid LazyPrecompFFTMultipliers(long k, mint_t q, mulmod_t qinv, const mint_t *root, const pd_FFTMultipliers& tab)\n{\n   if (k < 1) LogicError(\"LazyPrecompFFTMultipliers: bad input\");\n\n   do { // NOTE: thread safe lazy init\n      pd_FFTMultipliers::Builder bld(tab, k+1);\n      long amt = bld.amt();\n      if (!amt) break;\n\n      long first = k+1-amt;\n      // initialize entries first..k\n\n\n      for (long s = first; s <= k; s++) {\n         UniquePtr<pd_FFTVectorPair> item;\n\n         if (s == 0) {\n            bld.move(item); // position 0 not used\n            continue;\n         }\n\n         long m = 1L << s;\n         long m_half = 1L << (s-1);\n\n         item.make();\n         item->wtab_precomp.SetLength(m_half);\n         item->wqinvtab_precomp.SetLength(m_half);\n\n         double *wtab = item->wtab_precomp.elts();\n         double *wqinvtab = item->wqinvtab_precomp.elts();\n\n         mint_t w = root[s];\n         mulmod_precon_t wqinv = PrepMulModPrecon(w, q, qinv);\n\n         mint_t wi = 1;\n         wtab[0] = wi;\n         for (long i = 1; i < m_half; i++) {\n            wi = MulModPrecon(wi, w, q, wqinv);\n            wtab[i] = wi;\n         }\n         pd_LazyPrepMulModPrecon(wqinvtab, wtab, q, m_half);\n\n         bld.move(item);\n      }\n   } while (0);\n}\n\nNTL_TLS_GLOBAL_DECL(AlignedArray<double>, pd_AA_store)\nstatic NTL_CHEAP_THREAD_LOCAL long pd_AA_store_len = 0;\n\n\n#define PD_MIN_K (NTL_LG2_PDSZ+3)\n// k must be at least PD_MIN_K\n\nvoid new_fft(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info,\n            long yn, long xn)\n{\n   if (k < PD_MIN_K) {\n      new_fft_notab(A, a, k, info, yn, xn);\n      return;\n   }\n\n   long dir = 0;\n\n   mint_t q = info.q;\n   const mint_t *root = info.RootTable[dir].elts();\n   mulmod_t qinv = info.qinv;\n   const pd_FFTMultipliers& tab = info.bigtab->pd_MulTab[dir];\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n   const double *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const double *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   pd_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   long n = 1L << k;\n\n   NTL_TLS_GLOBAL_ACCESS(pd_AA_store);\n   if (pd_AA_store_len < n) pd_AA_store.SetLength(n);\n   double *AA = pd_AA_store.elts();\n\n   CSRPush push;\n   pd_fft_trunc_impl(A, a, AA, k, mod, yn, xn);\n}\n\n\n\nvoid new_fft_flipped(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info)\n{\n   if (k < PD_MIN_K) {\n      new_fft_flipped_notab(A, a, k, info);\n      return;\n   }\n\n   long dir = 1;\n\n   mint_t q = info.q;\n   const mint_t *root = info.RootTable[dir].elts();\n   mulmod_t qinv = info.qinv;\n   const pd_FFTMultipliers& tab = info.bigtab->pd_MulTab[dir];\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n\n   const double *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const double *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   pd_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n\n   long n = 1L << k;\n\n   NTL_TLS_GLOBAL_ACCESS(pd_AA_store);\n   if (pd_AA_store_len < n) pd_AA_store.SetLength(n);\n   double *AA = pd_AA_store.elts();\n\n   CSRPush push;\n   pd_fft_trunc_impl(A, a, AA, k, mod, n, n, info.TwoInvTable[k]);\n}\n\n\nvoid new_ifft(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info,\n            long yn)\n{\n   if (k < PD_MIN_K) {\n      new_ifft_notab(A, a, k, info, yn);\n      return;\n   }\n\n   long dir = 0;\n\n   mint_t q = info.q;\n   const mint_t *root = info.RootTable[1-dir].elts();\n   const mint_t *root1 = info.RootTable[dir].elts();\n   mulmod_t qinv = info.qinv;\n   const pd_FFTMultipliers& tab = info.bigtab->pd_MulTab[1-dir];\n   const pd_FFTMultipliers& tab1 = info.bigtab->pd_MulTab[dir];\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n   if (k >= tab1.length()) LazyPrecompFFTMultipliers(k, q, qinv, root1, tab1);\n\n   const double *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const double *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   const double *wtab1[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab1[s] = tab1[s]->wtab_precomp.elts();\n\n   const double *wqinvtab1[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab1[s] = tab1[s]->wqinvtab_precomp.elts();\n\n   pd_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n   mod.wtab1 = &wtab1[0];\n   mod.wqinvtab1 = &wqinvtab1[0];\n\n   long n = 1L << k;\n\n   NTL_TLS_GLOBAL_ACCESS(pd_AA_store);\n   if (pd_AA_store_len < n) pd_AA_store.SetLength(n);\n   double *AA = pd_AA_store.elts();\n\n   CSRPush push;\n   pd_ifft_trunc_impl(A, a, AA, k, mod, yn, info.TwoInvTable[k]);\n}\n\n\nvoid new_ifft_flipped(mint_t* A, const mint_t* a, long k, const FFTPrimeInfo& info)\n{\n   if (k < PD_MIN_K) {\n      new_ifft_flipped_notab(A, a, k, info);\n      return;\n   }\n\n   long dir = 1;\n\n   mint_t q = info.q;\n   const mint_t *root = info.RootTable[1-dir].elts();\n   const mint_t *root1 = info.RootTable[dir].elts();\n   mulmod_t qinv = info.qinv;\n   const pd_FFTMultipliers& tab = info.bigtab->pd_MulTab[1-dir];\n   const pd_FFTMultipliers& tab1 = info.bigtab->pd_MulTab[dir];\n\n   if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, qinv, root, tab);\n   if (k >= tab1.length()) LazyPrecompFFTMultipliers(k, q, qinv, root1, tab1);\n\n   const double *wtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab[s] = tab[s]->wtab_precomp.elts();\n\n   const double *wqinvtab[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab[s] = tab[s]->wqinvtab_precomp.elts();\n\n   const double *wtab1[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wtab1[s] = tab1[s]->wtab_precomp.elts();\n\n   const double *wqinvtab1[NTL_FFTMaxRoot+1];\n   for (long s = 1; s <= k; s++) wqinvtab1[s] = tab1[s]->wqinvtab_precomp.elts();\n\n   pd_mod_t mod;\n   mod.q = q;\n   mod.wtab = &wtab[0];\n   mod.wqinvtab = &wqinvtab[0];\n   mod.wtab1 = &wtab1[0];\n   mod.wqinvtab1 = &wqinvtab1[0];\n\n   long n = 1L << k;\n\n   NTL_TLS_GLOBAL_ACCESS(pd_AA_store);\n   if (pd_AA_store_len < n) pd_AA_store.SetLength(n);\n   double *AA = pd_AA_store.elts();\n\n   CSRPush push;\n   pd_ifft_trunc_impl(A, a, AA, k, mod, n);\n}\n\n#endif\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "f6c4ac19e1832e913b08957d6964336d032455f5", "size": 89657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/ntl-11.4.3/src/FFT.cpp", "max_stars_repo_name": "fedlearnJDT/libfedlearn", "max_stars_repo_head_hexsha": "581dfeca7ba6c49c480b883a883001dce7922f76", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-07-20T01:54:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:56:04.000Z", "max_issues_repo_path": "thirdparty/ntl-11.4.3/src/FFT.cpp", "max_issues_repo_name": "fedlearnJDT/libfedlearn", "max_issues_repo_head_hexsha": "581dfeca7ba6c49c480b883a883001dce7922f76", "max_issues_repo_licenses": ["Apache-2.0"], "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/ntl-11.4.3/src/FFT.cpp", "max_forks_repo_name": "fedlearnJDT/libfedlearn", "max_forks_repo_head_hexsha": "581dfeca7ba6c49c480b883a883001dce7922f76", "max_forks_repo_licenses": ["Apache-2.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.9044506692, "max_line_length": 126, "alphanum_fraction": 0.6133374974, "num_tokens": 31114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098192, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5806029730646379}}
{"text": "/**\n * Image Warping\n * 2020/03/14\n * zyw\n * */\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <algorithm>\n#include <cmath>\n#include <Eigen/Eigen>\n#include <Eigen/QR>\nusing namespace cv;\nusing std::cout, std::endl;\nusing std::vector;\n//#define DEBUG\n\nVec3b interpolate(const Mat& src, double x, int xf, int xc, double y, int yf, int yc) {\n    Vec3f res;\n    if (xf == xc && yf == yc)\n        res = src.at<Vec3b>(xf, yf);\n    else if (xf == xc)\n        res = src.at<Vec3b>(xf, yf) * (yc-y) + src.at<Vec3b>(xf, yc) * (y-yf);\n    else if (yf == yc)\n        res = src.at<Vec3b>(xf, yf) * (xc-x) + src.at<Vec3b>(xc, yf) * (x-xf);\n    else {\n        Vec3f inter1 = src.at<Vec3b>(xf, yf) * (yc-y) + src.at<Vec3b>(xf, yc) * (y-yf);\n        Vec3f inter2 = src.at<Vec3b>(xc, yf) * (yc-y) + src.at<Vec3b>(xc, yc) * (y-yf);\n        res = inter1 * (xc-x) + inter2 * (x-xf);\n    }\n    Vec3b res2 = res;\n    return res2;\n}\n\nvoid affine(const Mat& source, const Mat& target, Mat& result, const int Sx[], const int Sy[], const int Tx[], const int Ty[]) {\n    Eigen::Matrix3f srcA;\n    srcA << Sx[0], Sy[0], 1, Sx[1], Sy[1], 1, Sx[2], Sy[2], 1;\n    Eigen::Vector3f b1;\n    b1 << Tx[0], Tx[1], Tx[2];\n    Eigen::Vector3f x1 = srcA.colPivHouseholderQr().solve(b1);\n    Eigen::Vector3f b2;\n    b2 << Ty[0], Ty[1], Ty[2];\n    Eigen::Vector3f x2 = srcA.colPivHouseholderQr().solve(b2);\n    Eigen::Matrix3f A;\n    A << x1(0), x1(1), x1(2), x2(0), x2(1), x2(2), 0, 0, 1;\n    int width = result.cols;\n    int height = result.rows;\n    for (int i = 0; i < height; ++i)\n        for (int j = 0; j < width; ++j) {\n            Eigen::Vector3f vecB;\n            vecB << i, j, 1;\n            Eigen::Vector3f vecX = A.colPivHouseholderQr().solve(vecB);\n\n            double x = vecX(0);\n            double y = vecX(1);\n            if (0 <= x && x < source.rows && 0 <= y && y < source.cols)\n                result.at<Vec3b>(i,j) = interpolate(source, x, floor(x), ceil(x), y, floor(y), ceil(y));\n            else\n                result.at<Vec3b>(i,j) = target.at<Vec3b>(i,j);\n\n#ifdef DEBUG\n            int x = vecX(0);\n            int y = vecX(1);\n            float X = vecX(0);\n            float Y = vecX(1);\n            if (0 <= x && x < source.rows && 0 <= y && y < source.cols) {\n                result.at<Vec3b>(i,j) = (source.at<Vec3b>(x,y) * ((float)x+1-X)*((float)y+1-Y)\n                                         + source.at<Vec3b>(x,y+1) * ((float)x+1-X)*(Y-(float)y)\n                                         + source.at<Vec3b>(x+1,y) * (X-(float)x)*((float)y+1-Y)\n                                         + source.at<Vec3b>(x+1,y+1) * (X-(float)x)*(Y-(float)y));\n                // result.at<Vec3b>(i,j) = source.at<Vec3b>(round(vecX(0)), round(vecX(1)));\n            }\n            else {\n                result.at<Vec3b>(i,j) = target.at<Vec3b>(i,j);\n            }\n#endif\n        }\n}\n\nvoid projective(const Mat &in, Mat& out) {\n    double rhoMax = (double)min(out.rows, out.cols) / 2;\n    double dMax = (double)max(in.rows, in.cols) / 2;\n    for (int i = -out.rows/2; i < out.rows/2; ++i)\n        for (int j = -out.cols/2; j < out.cols/2; ++j) {\n            double rho = sqrt(i*i+j*j);\n            double theta = atan2(i,j);\n            if (rho/rhoMax > 1)\n                continue;\n            double phi = asin(rho/rhoMax);\n\n            double d = 2.0 / M_PI * dMax * phi;\n            double x = d * sin(theta);\n            double y = d * cos(theta);\n\n            if (-in.rows/2.0 <= x && x <= in.rows/2.0 && -in.cols/2.0 <= y && y <= in.cols/2.0)\n                out.at<Vec3b>(i+out.rows/2, j+out.cols/2) = in.at<Vec3b>((int)round(x+in.rows/2.0), (int)round(y+in.cols/2.0));\n            else\n                out.at<Vec3b>(i+out.rows/2, j+out.cols/2) = Vec3b(127, 127, 127);\n        }\n}\n\nvoid cart2pol(const Mat &in, Mat& out, int size) {\n    int width = in.cols;\n    int height = in.rows;\n\n    double R = (size - 1) / 2.0;\n    double deltaR = (2.0 * height) / (size - 1);\n    double deltaT = 2.0 * M_PI / width;\n\n    for (int i = 0; i < size; ++i)\n        for (int j = 0; j < size; ++j) {\n            double x = j - R;\n            double y = R - i;\n            double r = sqrt(x*x + y*y);\n            if (r > R)\n                continue;\n\n            double theta = atan2(y, x);\n            theta = theta > 0 ? theta : (theta + 2.0*M_PI);\n            double cx = r * deltaR;\n            double cy = theta / deltaT;\n            int xf = floor(cx) > 0 ? (int)floor(cx) : 0;\n            int xc = ceil(cx) < height ? (int)ceil(cx) : (height-1);\n            int yf = floor(cy) > 0 ? (int)floor(cy) : 0;\n            int yc = ceil(cy) < width ? (int)ceil(cy) : (width-1);\n\n            out.at<Vec3b>(i, j) = interpolate(in, cx, xf, xc, cy, yf, yc);\n        }\n}\n\nint main() {\n    // 1\n    Mat source = imread(\"../image/source.jpg\");\n    Mat target = imread(\"../image/target.jpg\");\n    Mat result(source.size(), CV_8UC3);\n    int Sx[4] = {0, 524, 0, 524};\n    int Sy[4] = {0, 0, 699, 699};\n    int Tx[4] = {193, 315, 265, 387};\n    int Ty[4] = {192, 168, 535, 511};\n    affine(source, target, result, Sx, Sy, Tx, Ty);\n    imwrite(\"../image/result.jpg\", result);\n\n    // 2\n    int rOut = 300, cOut = 300;\n    Mat warping = imread(\"../image/warping.png\");\n    Mat warping_result(warping.size(), CV_8UC3);\n    projective(warping, warping_result);\n    imwrite(\"../image/warping_result.png\", warping_result);\n\n    // 3\n    Mat input = imread(\"../image/cart4.jpg\");\n    Mat output = Mat::zeros(500, 500, CV_8UC3);\n    cart2pol(input, output, output.rows);\n    imwrite(\"../image/polar4.jpg\", output);\n    return 0;\n}\n\n", "meta": {"hexsha": "104b5d6e2f44dac0086ae09cf10af0b13c2429a2", "size": 5591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hw2/code/main.cpp", "max_stars_repo_name": "zondie17/DIP", "max_stars_repo_head_hexsha": "538f5a9f2bed80f8b69065daad63abc9fce16408", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hw2/code/main.cpp", "max_issues_repo_name": "zondie17/DIP", "max_issues_repo_head_hexsha": "538f5a9f2bed80f8b69065daad63abc9fce16408", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hw2/code/main.cpp", "max_forks_repo_name": "zondie17/DIP", "max_forks_repo_head_hexsha": "538f5a9f2bed80f8b69065daad63abc9fce16408", "max_forks_repo_licenses": ["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.6114649682, "max_line_length": 128, "alphanum_fraction": 0.4920407798, "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.580469165582289}}
{"text": "/* Newton nonlinear solver class header/implementation file.\n\n   D.R. Reynolds\n   Math 6321 @ SMU\n   Fall 2020  */\n\n#ifndef NEWTON_DEFINED__\n#define NEWTON_DEFINED__\n\n// Inclusions\n#include <cmath>\n#include <armadillo>\n#include <iomanip>\n\n\n// Declare abstract base classes for residual and Jacobian to\n// define what the Newton solver expects from each.\n\n//   Residual function abstract base class; derived classes\n//   must at least implement the Evaluate() routine\nclass ResidualFunction {\n public:\n  virtual int Evaluate(arma::vec& y, arma::vec& r) = 0;\n};\n\n//   Residual Jacobian function abstract base class; derived classes\n//   must at least implement the Evaluate() routine\nclass ResidualJacobian {\n public:\n  virtual int Evaluate(arma::vec& y, arma::mat& J) = 0;\n};\n\n\n\n// Newton solver class\nclass NewtonSolver {\n\n private:\n\n  // private reusable data\n  arma::vec f;      // stores nonlinear residual vector\n  arma::vec s;      // stores Newton update vector\n  arma::mat J;      // stores nonlinear residual Jacobian matrix\n\n  // private pointers to problem-defining function objects\n  ResidualFunction *fres;   // nonlinear residual function pointer\n  ResidualJacobian *Jres;   // nonlinear residual Jacobian function pointer\n\n  // private solver parameters\n  const arma::vec *w;       // pointer to desired error weight vector\n\n  // private statistics\n  int iters;                // iteration counter (reset in each solve)\n  double error_norm;        // most recent error estimate (in error-weight max norm)\n\n public:\n\n  // public solver parameters\n  double tol;               // desired tolerance (in error-weight max norm)\n  int maxit;                // maximum desired Newton iterations\n  bool show_iterates;       // flag to output iteration information\n\n  // Constructor\n  //\n  // Inputs:  fres_  -- the ResidualFunction to use\n  //          Jres_  -- the JacobianFunction to use\n  //          tol_   -- the desired solution tolerance\n  //          w_     -- the error weight vector to use\n  //          maxit_ -- the maximum allowed number of iterations\n  //          y      -- template solution vector (only used to clone)\n  //          show_iterates_ -- enable/disable printing iterate info\n  NewtonSolver(ResidualFunction& fres_, ResidualJacobian& Jres_,\n               const double tol_, const arma::vec& w_, const int maxit_,\n               const arma::vec& y, const bool show_iterates_) {\n\n    // set pointers to problem-defining function objects\n    fres = &fres_;\n    Jres = &Jres_;\n\n    // set error weight vector pointer, tolerance\n    tol = tol_;\n    w = &w_;\n\n    // set remaining solver parameters\n    show_iterates = show_iterates_;\n    maxit = maxit_;\n\n    // create reusable solver objects (clone off of y)\n    f = arma::vec(y);\n    s = arma::vec(y);\n    J = arma::mat(y.size(), y.size());\n\n    // initialize statistics\n    iters = 0;\n    error_norm = 0.0;\n  }\n\n  // Utility routine to ensure that the Newton solver object has the current\n  // fres, Jres and w pointers\n  void UpdatePointers(ResidualFunction& fres_,\n                      ResidualJacobian& Jres_,\n                      const arma::vec& w_) {\n    fres = &fres_;\n    Jres = &Jres_;\n    w = &w_;\n  };\n\n  // Error-weight max norm utility routine for convergence tests\n  //   max_i | w_i*e_i |\n  // where w is the error-weight vector stored in the NewtonSolver\n  // object, and e is the input vector.\n  double EWTNorm(const arma::vec& e) {\n    double nrm = 0.0;\n    for (size_t i=0; i<e.size(); i++) {\n      double we = (*w)(i) * e(i);\n      nrm = std::max(nrm, std::abs(we));\n    }\n    return nrm;\n  }\n\n  // Newton solver routine\n  //\n  // Input:   y  -- the initial guess\n  // Outputs: y  -- the computed solution\n  //\n  // The return value is one of:\n  //          0 => successful solve\n  //         -1 => bad function call or input\n  //          1 => non-convergent iteration\n  int Solve(arma::vec& y) {\n\n    // set initial residual value\n    if (fres->Evaluate(y, f) != 0) {\n      std::cerr << \"NewtonSolver::Solve error: residual function failure\\n\";\n      return -1;\n    }\n\n    // perform iterations\n    for (iters=1; iters<=maxit; iters++) {\n\n      // evaluate Jacobian\n      if (Jres->Evaluate(y, J) != 0) {\n        std::cerr << \"NewtonSolver::Solve error: Jacobian function failure\\n\";\n        return -1;\n      }\n\n      // compute Newton update, norm\n      if (arma::solve(s, J, f) == false) {\n        std::cerr << \"NewtonSolver::Solve error: linear solver failure\\n\";\n        return -1;\n      }\n      error_norm = EWTNorm(s);\n\n      // perform update\n      y -= s;\n\n      // update residual\n      if (fres->Evaluate(y, f) != 0) {\n        std::cerr << \"NewtonSolver::Solve error: residual function failure\\n\";\n        return -1;\n      }\n\n      // output convergence information\n      if (show_iterates)\n        printf(\"   iter %3i, ||s*w||_inf = %7.2e, ||f(x)*w||_inf = %7.2e\\n\",\n               iters, error_norm, EWTNorm(f));\n\n      // check for convergence, return if successful\n      if (error_norm < tol)  return 0;\n\n    }\n\n    // if we've made it here, Newton did not converge, output warning and return\n    std::cerr << \"\\nNewtonSolver::Solve WARNING: nonconvergence after \" << maxit\n              << \" iterations (||s|| = \" << error_norm << \")\\n\";\n    return 1;\n  }\n\n  // Parameter update & statistics accessor routines\n  void ResetIters() { iters = 0; };\n  const int GetIters() { return iters; };\n  const double GetErrorNorm() { return error_norm; };\n\n};\n\n#endif\n", "meta": {"hexsha": "0ae58a6a7f875a7b02164aa10e4e0b5df4b43d0d", "size": 5476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shared/newton.hpp", "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": "shared/newton.hpp", "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": "shared/newton.hpp", "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": 29.2834224599, "max_line_length": 84, "alphanum_fraction": 0.6181519357, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.5804360117460399}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <manifold/SO3.h>\n#include <manifold/S.h>\n\nint main (int argc, char** argv) {\n\n  uint32_t N = 10;\n  uint32_t K = 2;\n  \n  double theta = 0.*M_PI/180.;\n  Eigen::Matrix3d Rmu_;\n  Rmu_ << 1, 0, 0,\n         0, cos(theta), sin(theta),\n         0, -sin(theta), cos(theta);\n  SO3d Rmu(Rmu_);\n  SO3d R = Rmu;\n  double tau_R = 10.;\n\n  std::vector<S3d> mus; \n  mus.push_back(S3d(Eigen::Vector3d(0.,cos(theta),-sin(theta))));\n  mus.push_back(S3d(Eigen::Vector3d(0.,sin(theta),cos(theta))));\n  std::vector<double> taus;\n  taus.push_back(10.);\n  taus.push_back(10.);\n\n  theta = 15.*M_PI/180.;\n  std::vector<S3d> ns; \n  std::vector<uint32_t> zs;\n  for (uint32_t i=0; i<N/2; ++i) {\n    ns.push_back(S3d(Eigen::Vector3d(0.,cos(theta),-sin(theta))));\n    ns.push_back(S3d(Eigen::Vector3d(0.,sin(theta),cos(theta))));\n    zs.push_back(0);\n    zs.push_back(1);\n  }\n\n  std::cout << \"Using SO(3) formulation derived from the Stiefel manifold formulation by Absil\" << std::endl;\n  \n  double delta = 0.01;\n  double f_prev = 1e99;\n  double f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n  for (uint32_t i=0; i<N; ++i)\n    f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100; ++it) {\n    Eigen::Matrix3d J = -0.5*tau_R*(Rmu.matrix() - (R+Rmu.Inverse()+R).matrix()); \n    for (uint32_t i=0; i<N; ++i) {\n      J -= 0.5*(taus[zs[i]]*(mus[zs[i]].vector()*ns[i].vector().transpose()\n         - R.matrix()*(ns[i].vector()*mus[zs[i]].vector().transpose()*R.matrix())));\n    }\n    Eigen::Vector3d Jw = SO3d::vee(R.Inverse().matrix()*J);\n    R += -delta*Jw;\n    f_prev = f;\n    f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n    for (uint32_t i=0; i<N; ++i)\n      f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n    std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f)\n      << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) \n      break;\n  }\n//  std::cout << std::endl << Rmu << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n\n  std::cout << \"Using SO(3) formulation first order\" << std::endl;\n\n  R = Rmu;\n  delta = 0.01;\n  f_prev = 1e99;\n  f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n  for (uint32_t i=0; i<N; ++i)\n    f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<200; ++it) {\n    Eigen::Vector3d J;\n    for (uint32_t l=0; l<3; ++l) {\n      J(l) = -tau_R*(Rmu.Inverse().matrix()*SO3d::G(l)*R.matrix()).trace(); \n//      std::cout << -tau_R*(Rmu.Inverse().matrix()*R.matrix()*SO3d::G(l)).trace() \n//        << \" \" << -tau_R*(Rmu.Inverse().matrix()*SO3d::G(l)*R.matrix()).trace() \n//        << std::endl;\n//      J(l) = -tau_R*(Rmu.Inverse().matrix()*R.matrix()*SO3d::G(l)).trace(); \n    }\n    for (uint32_t i=0; i<N; ++i) {\n      J -= -taus[zs[i]]*mus[zs[i]].vector().transpose()*SO3d::invVee(R.matrix()*ns[i].vector());\n    }\n    R += -delta*J;\n    f_prev = f;\n    f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n    for (uint32_t i=0; i<N; ++i)\n      f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n    std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) \n      break;\n  }\n//  std::cout << std::endl << Rmu << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n\n  std::cout << \"Using SO(3) formulation second order\" << std::endl;\n\n  R = Rmu;\n  delta = 0.9;\n  f_prev = 1e99;\n  f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n  for (uint32_t i=0; i<N; ++i)\n    f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n  std::cout << \"f=\" << f << std::endl;\n  for (uint32_t it=0; it<100; ++it) {\n    Eigen::Vector3d J;\n    for (uint32_t l=0; l<3; ++l)\n      J(l) = -tau_R*(Rmu.Inverse().matrix()*SO3d::G(l)*R.matrix()).trace(); \n    for (uint32_t i=0; i<N; ++i) {\n      J -= -taus[zs[i]]*mus[zs[i]].vector().transpose()*SO3d::invVee(R.matrix()*ns[i].vector());\n    }\n    Eigen::Matrix3d H;\n    for (uint32_t l=0; l<3; ++l)\n      for (uint32_t m=0; m<3; ++m) {\n        Eigen::Matrix3d Glmml = 0.5*(SO3d::G(l)*SO3d::G(m)+SO3d::G(m)*SO3d::G(l));\n        H(l,m) = -tau_R*(Rmu.Inverse().matrix()*R.matrix()*Glmml).trace(); \n      }\n    for (uint32_t i=0; i<N; ++i) {\n      for (uint32_t l=0; l<3; ++l)\n        for (uint32_t m=0; m<3; ++m) {\n          Eigen::Matrix3d Glmml = 0.5*(SO3d::G(l)*SO3d::G(m)+SO3d::G(m)*SO3d::G(l));\n          H(l,m) += -taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*Glmml*ns[i].vector();\n        }\n    }\n    Eigen::Vector3d xi = - H.lu().solve(J);\n    R += delta*xi;\n    f_prev = f;\n    f = -tau_R*(Rmu.Inverse() + R).matrix().trace();\n    for (uint32_t i=0; i<N; ++i)\n      f -= taus[zs[i]]*mus[zs[i]].vector().transpose()*R.matrix()*ns[i].vector();\n    std::cout << \"@\" << it << \": f=\" << f << \" df/f=\" << (f_prev - f)/fabs(f) << std::endl;\n    if ((f_prev - f)/fabs(f) < 1e-9) \n      break;\n  }\n//  std::cout << std::endl << Rmu << std::endl;\n  std::cout << std::endl << R << std::endl;\n  std::cout << acos(R.matrix()(1,1))*180/M_PI << std::endl;\n\n}\n", "meta": {"hexsha": "a1a380cb7bf78065aa1ec3e083b4181ee5de3fd4", "size": 5321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SO3_incSurfNormAlign.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SO3_incSurfNormAlign.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SO3_incSurfNormAlign.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": 36.4452054795, "max_line_length": 109, "alphanum_fraction": 0.5271565495, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5804095787421155}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"mgc.h\"\n#include \"../structures/molecule.h\"\n\nCHARGEFW2_METHOD(MGC)\n\n\nstd::vector<double> MGC::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.atoms().size();\n\n    Eigen::MatrixXd S = Eigen::MatrixXd::Zero(n, n);\n    Eigen::VectorXd X0 = Eigen::VectorXd::Zero(n);\n\n    double log_sum = 0;\n\n    for (const auto &atom: molecule.atoms()) {\n        auto i = atom.index();\n        S(i, i) = 1;\n        X0(i) = atom.element().electronegativity();\n        log_sum += log(X0(i));\n    }\n\n    for (const auto &bond: molecule.bonds()) {\n        auto i1 = bond.first().index();\n        auto i2 = bond.second().index();\n        auto order = bond.order();\n        S(i1, i1) += order;\n        S(i2, i2) += order;\n        S(i1, i2) -= order;\n        S(i2, i1) -= order;\n    }\n\n    Eigen::VectorXd chi = S.partialPivLu().solve(X0);\n    for (size_t i = 0; i < n; i++) {\n        chi(i) -= molecule.atoms()[i].element().electronegativity();\n    }\n    chi /= exp(log_sum / n);\n\n    return std::vector<double>(chi.data(), chi.data() + chi.size());\n}\n", "meta": {"hexsha": "284b742f04298cde587d977fc958c0459bca32b9", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/mgc.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/mgc.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/mgc.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": 23.7142857143, "max_line_length": 76, "alphanum_fraction": 0.5593803787, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5804095522514882}}
{"text": "/*\n Copyright 2010-2012 Karsten Ahnert\n Copyright 2011-2013 Mario Mulansky\n Copyright 2013 Pascal Germroth\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 <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n\n\n//[ rhs_function\n/* The type of container used to hold the state vector */\ntypedef std::vector< double > state_type;\n\nconst double gam = 0.15;\n\n/* The rhs of x' = f(x) */\nvoid harmonic_oscillator( const state_type &x , state_type &dxdt , const double /* t */ )\n{\n    dxdt[0] = x[1];\n    dxdt[1] = -x[0] - gam*x[1];\n}\n//]\n\n\n\n\n\n//[ rhs_class\n/* The rhs of x' = f(x) defined as a class */\nclass harm_osc {\n\n    double m_gam;\n\npublic:\n    harm_osc( double gam ) : m_gam(gam) { }\n\n    void operator() ( const state_type &x , state_type &dxdt , const double /* t */ )\n    {\n        dxdt[0] = x[1];\n        dxdt[1] = -x[0] - m_gam*x[1];\n    }\n};\n//]\n\n\n\n\n\n//[ integrate_observer\nstruct push_back_state_and_time\n{\n    std::vector< state_type >& m_states;\n    std::vector< double >& m_times;\n\n    push_back_state_and_time( std::vector< state_type > &states , std::vector< double > &times )\n    : m_states( states ) , m_times( times ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        m_states.push_back( x );\n        m_times.push_back( t );\n    }\n};\n//]\n\nstruct write_state\n{\n    void operator()( const state_type &x ) const\n    {\n        std::cout << x[0] << \"\\t\" << x[1] << \"\\n\";\n    }\n};\n\n\nint main(int /* argc */ , char** /* argv */ )\n{\n    using namespace std;\n    using namespace boost::numeric::odeint;\n\n\n    //[ state_initialization\n    state_type x(2);\n    x[0] = 1.0; // start at x=1.0, p=0.0\n    x[1] = 0.0;\n    //]\n\n\n\n    //[ integration\n    size_t steps = integrate( harmonic_oscillator ,\n            x , 0.0 , 10.0 , 0.1 );\n    //]\n\n\n\n    //[ integration_class\n    harm_osc ho(0.15);\n    steps = integrate( ho ,\n            x , 0.0 , 10.0 , 0.1 );\n    //]\n\n\n\n\n\n    //[ integrate_observ\n    vector<state_type> x_vec;\n    vector<double> times;\n\n    steps = integrate( harmonic_oscillator ,\n            x , 0.0 , 10.0 , 0.1 ,\n            push_back_state_and_time( x_vec , times ) );\n\n    /* output */\n    for( size_t i=0; i<=steps; i++ )\n    {\n        cout << times[i] << '\\t' << x_vec[i][0] << '\\t' << x_vec[i][1] << '\\n';\n    }\n    //]\n\n\n\n\n\n\n\n    //[ define_const_stepper\n    runge_kutta4< state_type > stepper;\n    integrate_const( stepper , harmonic_oscillator , x , 0.0 , 10.0 , 0.01 );\n    //]\n\n\n\n\n    //[ integrate_const_loop\n    const double dt = 0.01;\n    for( double t=0.0 ; t<10.0 ; t+= dt )\n        stepper.do_step( harmonic_oscillator , x , t , dt );\n    //]\n\n\n\n\n    //[ define_adapt_stepper\n    typedef runge_kutta_cash_karp54< state_type > error_stepper_type;\n    //]\n\n\n\n    //[ integrate_adapt\n    typedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\n    controlled_stepper_type controlled_stepper;\n    integrate_adaptive( controlled_stepper , harmonic_oscillator , x , 0.0 , 10.0 , 0.01 );\n    //]\n\n    {\n    //[integrate_adapt_full\n    double abs_err = 1.0e-10 , rel_err = 1.0e-6 , a_x = 1.0 , a_dxdt = 1.0;\n    controlled_stepper_type controlled_stepper( \n        default_error_checker< double , range_algebra , default_operations >( abs_err , rel_err , a_x , a_dxdt ) );\n    integrate_adaptive( controlled_stepper , harmonic_oscillator , x , 0.0 , 10.0 , 0.01 );\n    //]\n    }\n\n\n    //[integrate_adapt_make_controlled\n    integrate_adaptive( make_controlled< error_stepper_type >( 1.0e-10 , 1.0e-6 ) , \n                        harmonic_oscillator , x , 0.0 , 10.0 , 0.01 );\n    //]\n\n\n\n\n    //[integrate_adapt_make_controlled_alternative\n    integrate_adaptive( make_controlled( 1.0e-10 , 1.0e-6 , error_stepper_type() ) , \n                        harmonic_oscillator , x , 0.0 , 10.0 , 0.01 );\n    //]\n\n    #ifdef BOOST_NUMERIC_ODEINT_CXX11\n    //[ define_const_stepper_cpp11\n    {\n    runge_kutta4< state_type > stepper;\n    integrate_const( stepper , []( const state_type &x , state_type &dxdt , double t ) {\n            dxdt[0] = x[1]; dxdt[1] = -x[0] - gam*x[1]; }\n        , x , 0.0 , 10.0 , 0.01 );\n    }\n    //]\n    \n    \n    \n    //[ harm_iterator_const_step]\n    std::for_each( make_const_step_time_iterator_begin( stepper , harmonic_oscillator, x , 0.0 , 0.1 , 10.0 ) ,\n                   make_const_step_time_iterator_end( stepper , harmonic_oscillator, x ) ,\n                   []( std::pair< const state_type & , const double & > x ) {\n                       cout << x.second << \" \" << x.first[0] << \" \" << x.first[1] << \"\\n\"; } );\n    //]\n    #endif\n    \n    \n\n\n}\n", "meta": {"hexsha": "a1f53c4ffa2ac979a5666e378052141224ef0b4f", "size": 4688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/harmonic_oscillator.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/harmonic_oscillator.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/harmonic_oscillator.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": 22.1132075472, "max_line_length": 115, "alphanum_fraction": 0.5810580205, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7341195385342972, "lm_q1q2_score": 0.5803437527391525}}
{"text": "#ifndef HOPS_EXPECTEDSQUAREDJUMPDISTANCE_HPP\n#define HOPS_EXPECTEDSQUAREDJUMPDISTANCE_HPP\n\n#include <hops/Statistics/Covariance.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n\n#include <string>\n#include <stdexcept>\n#include <vector>\n#include <cmath>\n#include <cassert>\n#include <memory>\n\nnamespace hops {\n    /*\n     * Compute Expected Squared Jump Distance incrementally on a single vector of draws. \n     * The Expected Squared Jump Distance is defined as\n     * \\[ ESJD = \\frac{1}{N-1} \\sum_{n=1}^(N-1) \\| \\theta_{n+1} - \\theta_n \\|^2_{\\Sigma} \\]\n     */\n    template<typename StateType, typename MatrixType>\n    double computeExpectedSquaredJumpDistance(const std::vector<StateType>& draws, \n                                              unsigned long numUnseen, \n                                              double esjdSeen, \n                                              unsigned long numSeen,\n                                              const MatrixType& sqrtCovariance) {\n        size_t numDraws = draws.size(),\n               correction = 0;\n        // account for missing jump between two batches of samples\n        if (numSeen > 0 && draws.size() > numUnseen) {\n            correction = 1;\n        }\n\n        // in order to guarantee eta to be 1, we have to set it to 1.\n        if (numSeen == 0) {\n            ++numSeen;\n        }\n\n        double esjd = 0, \n               eta = 1.0 * (numSeen - 1) / (numSeen + numUnseen - 1),\n               squaredDistance;\n        for (unsigned long i = numDraws - numUnseen - correction; i < numDraws - 1; ++i) {\n            StateType distance = sqrtCovariance.template triangularView<Eigen::Lower>().solve(draws[i] - draws[i+1]);\n            distance = sqrtCovariance.template triangularView<Eigen::Lower>().transpose().solve(distance);\n            squaredDistance = (draws[i] - draws[i+1]).transpose() * distance;\n            esjd += squaredDistance;\n        }\n        esjd /=  numUnseen - 1 + correction;\n        return eta * esjdSeen + (1 - eta) * esjd;\n    }\n\n    /* \n     * Compute Expected Squared Jump Distance non-incrementally on all draws passed.\n     */\n    template<typename StateType, typename MatrixType>\n    double computeExpectedSquaredJumpDistance(const std::vector<StateType>& draws, const MatrixType& sqrtCovariance) {\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(draws, draws.size(), 0, 0, sqrtCovariance);\n    }\n\n    /* \n     * Compute Expected Squared Jump Distance non-incrementally on all draws passed.\n     */\n    template<typename StateType, typename MatrixType>\n    double computeExpectedSquaredJumpDistance(const std::vector<StateType>& draws) {\n        MatrixType covariance = computeCovariance<StateType, MatrixType>(draws);\n        MatrixType sqrtCovariance = covariance.llt().matrixL();\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(draws, sqrtCovariance);\n    }\n\n    /*\n     * Compute Expected Squared Jump Distance for every chain in \\c chains incrementally.\n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<std::vector<StateType>>& chains, \n                                                           unsigned long numUnseen, \n                                                           std::vector<double> esjdSeen, \n                                                           unsigned long numSeen,\n                                                           const MatrixType& sqrtCovariance) {\n        std::vector<double> esjds(chains.size());\n        for (size_t i = 0; i < chains.size(); ++i) {\n            esjds[i] = computeExpectedSquaredJumpDistance<StateType, MatrixType>(chains[i], numUnseen, esjdSeen[i], numSeen, sqrtCovariance);\n        }\n        return esjds;\n    }\n\n    /*\n     * Compute Expected Squared Jump Distance non-incrementally for every chain in \\c chains. \n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<std::vector<StateType>>& chains, const MatrixType& sqrtCovariance) {\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(chains, chains[0].size(), std::vector<double>(chains.size()), 0, sqrtCovariance); \n    }\n\n    /*\n     * Compute Expected Squared Jump Distance non-incrementally for every chain in \\c chains. \n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<std::vector<StateType>>& chains) {\n        MatrixType covariance = computeCovariance<StateType, MatrixType>(chains);\n        MatrixType sqrtCovariance = covariance.llt().matrixL();\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(chains, sqrtCovariance); \n    }\n\n    /*\n     * Compute Expected Squared Jump Distance for every chain in \\c chains incrementally. \n     * \\c chains is supposed to be a vector of pointers to the actual chains.\n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<const std::vector<StateType>*>& chains, \n                                                           unsigned long numUnseen, \n                                                           std::vector<double> esjdSeen, \n                                                           unsigned long numSeen,\n                                                           const MatrixType& sqrtCovariance) {\n        std::vector<double> esjds(chains.size());\n        for (size_t i = 0; i < chains.size(); ++i) {\n            esjds[i] = computeExpectedSquaredJumpDistance<StateType, MatrixType>(*chains[i], numUnseen, esjdSeen[i], numSeen, sqrtCovariance);\n        }\n        return esjds;\n    }\n\n    /*\n     * Compute Expected Squared Jump Distance non-incrementally for every chain in \\c chains. \n     * \\c chains is supposed to be a vector of pointers to the actual chains.\n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<const std::vector<StateType>*>& chains, \n                                                           const MatrixType& sqrtCovariance) {\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(chains, chains[0]->size(), std::vector<double>(chains.size()), 0, sqrtCovariance); \n    }\n\n    /*\n     * Compute Expected Squared Jump Distance non-incrementally for every chain in \\c chains. \n     * \\c chains is supposed to be a vector of pointers to the actual chains.\n     */\n    template<typename StateType, typename MatrixType>\n    std::vector<double> computeExpectedSquaredJumpDistance(const std::vector<const std::vector<StateType>*>& chains) {\n        MatrixType covariance = computeCovariance<StateType, MatrixType>(chains);\n        MatrixType sqrtCovariance = covariance.llt().matrixL();\n        return computeExpectedSquaredJumpDistance<StateType, MatrixType>(chains, sqrtCovariance); \n    }\n}\n\n\n#endif //HOPS_EXPECTEDSQUAREDJUMPDISTANCE_HPP\n\n", "meta": {"hexsha": "f55d746a6063e60f13772f18197f8c746d28e09a", "size": 7094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Statistics/ExpectedSquaredJumpDistance.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/Statistics/ExpectedSquaredJumpDistance.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/Statistics/ExpectedSquaredJumpDistance.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": 48.2585034014, "max_line_length": 156, "alphanum_fraction": 0.6224978855, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5802887957610738}}
{"text": "//  Copyright (c) 2017 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#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\ntemplate <class T>\nvoid print_gauss_constants(const char* suffix, int prec, int tag)\n{\n   auto ab = T::abscissa();\n   auto w = T::weights();\n   std::cout << std::setprecision(prec) << std::scientific;\n   std::size_t order = (ab[0] == 0) ? (ab.size() * 2) - 1 : ab.size() * 2;\n   std::cout <<\n      \"template <class T>\\n\"\n      \"class gauss_detail<T, \" << order << \", \" << tag << \">\\n\"\n      \"   {\\n\"\n      \"   public:\\n\"\n      \"      static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << ab.size() << \"> const & abscissa()\\n\"\n      \"      {\\n\"\n      \"         static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << ab.size() << \"> data = {\\n\";\n   for (unsigned i = 0; i < ab.size(); ++i)\n      std::cout << \"            \" << (prec > 40 ? \"BOOST_MATH_HUGE_CONSTANT(T, 0, \" : \"\") << ab[i] << (prec > 40 ? \")\" : suffix) << \",\\n\";\n   std::cout <<\n      \"};\\n\"\n      \"         return data;\\n\"\n      \"      }\\n\"\n      \"      static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << w.size() << \"> const & weights()\\n\"\n      \"      {\\n\"\n      \"         static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << w.size() << \"> data = {\\n\";\n   for (unsigned i = 0; i < w.size(); ++i)\n      std::cout << \"            \" << (prec > 40 ? \"BOOST_MATH_HUGE_CONSTANT(T, 0, \" : \"\") << w[i] << (prec > 40 ? \")\" : suffix) << \",\\n\";\n\n   std::cout << \"         };\\n\"\n      \"         return data;\\n\"\n      \"      }\\n\"\n      \"   };\\n\\n\";\n}\n\ntemplate <class T>\nvoid print_gauss_kronrod_constants(const char* suffix, int prec, int tag)\n{\n   auto ab = T::abscissa();\n   auto w = T::weights();\n   std::cout << std::setprecision(prec) << std::scientific;\n   std::size_t order = (ab.size() * 2) - 1;\n   std::cout <<\n      \"   template <class T>\\n\"\n      \"   class gauss_kronrod_detail<T, \" << order << \", \" << tag << \">\\n\"\n      \"   {\\n\"\n      \"   public:\\n\"\n      \"      static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << ab.size() << \"> const & abscissa()\\n\"\n      \"      {\\n\"\n      \"         static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << ab.size() << \"> data = {\\n\";\n\n   for (unsigned i = 0; i < ab.size(); ++i)\n      std::cout << \"            \" << (prec > 40 ? \"BOOST_MATH_HUGE_CONSTANT(T, 0, \" : \"\") << ab[i] << (prec > 40 ? \")\" : suffix) << \",\\n\";\n\n   std::cout << \"         };\\n\"\n      \"         return data;\\n\"\n      \"      }\\n\"\n      \"      static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << w.size() << \"> const & weights()\\n\"\n      \"      {\\n\"\n      \"         static \" << (prec > 40 ? \" \" : \"constexpr \") << \"std::array<T, \" << w.size() << \"> data = {\\n\";\n\n   for (unsigned i = 0; i < w.size(); ++i)\n      std::cout << \"            \" << (prec > 40 ? \"BOOST_MATH_HUGE_CONSTANT(T, 0, \" : \"\") << w[i] << (prec > 40 ? \")\" : suffix) << \",\\n\";\n\n   std::cout << \"         };\\n\"\n      \"         return data;\\n\"\n      \"      }\\n\"\n      \"   };\\n\\n\";\n}\n\n\n\nint main()\n{\n   typedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<250> > mp_type;\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 7> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 7> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 7> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 7> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 7> >(\"\", 115, 4);\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 10> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 10> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 10> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 10> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 10> >(\"\", 115, 4);\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 15> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 15> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 15> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 15> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 15> >(\"\", 115, 4);\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 20> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 20> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 20> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 20> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 20> >(\"\", 115, 4);\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 25> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 25> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 25> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 25> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 25> >(\"\", 115, 4);\n\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 30> >(\"f\", 9, 0);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 30> >(\"\", 17, 1);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 30> >(\"L\", 35, 2);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 30> >(\"Q\", 35, 3);\n   print_gauss_constants<boost::math::quadrature::gauss<mp_type, 30> >(\"\", 115, 4);\n\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 15> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 15> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 15> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 15> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 15> >(\"\", 115, 4);\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 21> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 21> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 21> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 21> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 21> >(\"\", 115, 4);\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 31> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 31> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 31> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 31> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 31> >(\"\", 115, 4);\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 41> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 41> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 41> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 41> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 41> >(\"\", 115, 4);\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 51> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 51> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 51> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 51> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 51> >(\"\", 115, 4);\n\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 61> >(\"f\", 9, 0);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 61> >(\"\", 17, 1);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 61> >(\"L\", 35, 2);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 61> >(\"Q\", 35, 3);\n   print_gauss_kronrod_constants<boost::math::quadrature::gauss_kronrod<mp_type, 61> >(\"\", 115, 4);\n\n   return 0;\n}\n\n", "meta": {"hexsha": "73fee4c139f3b1333f9863b3d02aee6c04ddfd92", "size": 8889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/gauss_kronrod_constants.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/math/tools/gauss_kronrod_constants.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/math/tools/gauss_kronrod_constants.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": 55.9056603774, "max_line_length": 138, "alphanum_fraction": 0.6154798065, "num_tokens": 3156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5802887845228284}}
{"text": "/*\nUtilize the result of eye-in-hand calibration to transform (picking) point\ncoordinates from the camera frame to the robot base frame.\n*/\n\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n\n#include <cmath>\n#include <iostream>\n\nEigen::MatrixXd cvToEigen(const cv::Mat &);\ncv::Mat readTransform(const std::string &);\n\nint main()\n{\n    try\n    {\n        // define (picking) point in camera frame\n        const Eigen::Vector4d pointInCameraFrame(81.2, 18.0, 594.6, 1);\n        std::cout << \"Point coordinates in camera frame: \" << pointInCameraFrame.segment(0, 3).transpose() << std::endl;\n\n        // Read camera pose in end-effector frame (result of eye-in-hand calibration)\n        const auto eyeInHandTransformation = readTransform(\"handEyeTransform.yaml\");\n\n        // Read end-effector pose in robot base frame\n        const auto endEffectorPose = readTransform(\"robotTransform.yaml\");\n\n        // convert to Eigen matrices for easier computation\n        const auto transformEndEffectorToCamera = cvToEigen(eyeInHandTransformation);\n        const auto transformBaseToEndEffector = cvToEigen(endEffectorPose);\n\n        // Compute camera pose in robot base frame\n        const auto transform_base_to_camera = transformBaseToEndEffector * transformEndEffectorToCamera;\n\n        // compute (picking) point in robot base frame\n        const auto pointInBaseFrame = transform_base_to_camera * pointInCameraFrame;\n        std::cout << \"Point coordinates in robot base frame: \" << pointInBaseFrame.segment(0, 3).transpose()\n                  << std::endl;\n    }\n\n    catch(const std::exception &e)\n    {\n        std::cerr << \"Error: \" << e.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n\nEigen::MatrixXd cvToEigen(const cv::Mat &cvMat)\n{\n    if(cvMat.dims > 2)\n    {\n        throw std::invalid_argument(\"Invalid matrix dimensions. Expected 2D.\");\n    }\n\n    Eigen::MatrixXd eigenMat(cvMat.rows, cvMat.cols);\n\n    for(int i = 0; i < cvMat.rows; i++)\n    {\n        for(int j = 0; j < cvMat.cols; j++)\n        {\n            eigenMat(i, j) = cvMat.at<double>(i, j);\n        }\n    }\n\n    return eigenMat;\n}\n\ncv::Mat readTransform(const std::string &file_name)\n{\n    auto fileStorage = cv::FileStorage();\n\n    if(!fileStorage.open(file_name, cv::FileStorage::Mode::READ))\n    {\n        throw std::invalid_argument(\"Could not open \" + file_name);\n    }\n    try\n    {\n        const auto poseStateNode = fileStorage[\"PoseState\"];\n\n        if(poseStateNode.empty())\n        {\n            throw std::invalid_argument(\"PoseState not found in file \" + file_name);\n        }\n\n        const auto rows = poseStateNode.mat().rows;\n        const auto cols = poseStateNode.mat().cols;\n        if(rows != 4 || cols != 4)\n        {\n            throw std::invalid_argument(\"Expected 4x4 matrix in \" + file_name + \", but got \" + std::to_string(cols)\n                                        + \"x\" + std::to_string(rows));\n        }\n\n        const auto poseState = poseStateNode.mat();\n        fileStorage.release();\n        return poseState;\n    }\n    catch(...)\n    {\n        fileStorage.release();\n        throw;\n    }\n}", "meta": {"hexsha": "81545acd31c1b4d2c92503bfdc654bc3f1e33de3", "size": 3111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Applications/Advanced/HandEyeCalibration/UtilizeEyeInHandCalibration/UtilizeEyeInHandCalibration.cpp", "max_stars_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_stars_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/HandEyeCalibration/UtilizeEyeInHandCalibration/UtilizeEyeInHandCalibration.cpp", "max_issues_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_issues_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/HandEyeCalibration/UtilizeEyeInHandCalibration/UtilizeEyeInHandCalibration.cpp", "max_forks_repo_name": "ZachZheng0316/Cpp_Sample_For_Zivid_Camera", "max_forks_repo_head_hexsha": "f448e5a206bc755813727b319eae43dfe1504e6d", "max_forks_repo_licenses": ["BSD-3-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.2038834951, "max_line_length": 120, "alphanum_fraction": 0.6197364192, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5802751470045495}}
{"text": "#include \"aux/eigen2hdf.hpp\"\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"post_processing/momentum.hpp\"\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/basis/spectral_basis.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/spectral_elem.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/spectral_function/hermite_polynomial.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n\n#include \"spectral/polar_to_hermite.hpp\"\n#include \"spectral/shift_hermite_2d.hpp\"\n\n#include <Eigen/Sparse>\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n\n#define PI 3.141592653589793238462643383279502884197\n\nusing namespace std;\nusing namespace boltzmann;\n\nnamespace po = boost::program_options;\n\n#ifdef EXTENDED_PRECISION\ntypedef long double numeric_t;\n#else\ntypedef double numeric_t;\n#endif\nconst int nrep = 1000;\n\nint main(int argc, char *argv[])\n{\n  Timer<> timer;\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"show help message\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  // read polar basis from file\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, \"spectral_basis.desc\");\n  //  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  int max_deg = spectral::get_max_k(polar_basis);\n  const unsigned int K = max_deg + 1;\n  // create corresponding Hermite basis\n  typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, max_deg + 1, 2);\n  SpectralBasisFactoryHN::write_basis_descriptor(hermite_basis, \"hermite_basis.desc\");\n\n  if (hermite_basis.n_dofs() != polar_basis.n_dofs()) {\n    throw runtime_error(\"Hermite basis does not match!\");\n    return 1;\n  }\n\n  cout << \"size(polar basis) = \" << polar_basis.n_dofs() << endl\n       << \"size(hermite basis) = \" << hermite_basis.n_dofs();\n\n  cout << \"\\n--------------------\\n\";\n  cout << \"Test 2: (P->H) -> (H->P) show coefficients\\n\";\n  timer.start();\n  Polar2Hermite<polar_basis_t, hermite_basis_t> P2H(polar_basis, hermite_basis);\n  print_timer(timer.stop(), \"init P2H\");\n\n  /*\n   * load coefficients (polar basis) from HDF5\n   */\n  const unsigned int N = polar_basis.n_dofs();\n  Eigen::VectorXd coeffs(N);\n  hid_t h5_init = H5Fopen(\"init.h5\", H5F_ACC_RDONLY, H5P_DEFAULT);\n  eigen2hdf::load(h5_init, \"coeffs\", coeffs);\n  H5Fclose(h5_init);\n\n  // compute bulk velocity\n  Mass mass;\n  mass.init(polar_basis);\n  Momentum momentum;\n  momentum.init(polar_basis);\n\n  const double m = mass.compute(coeffs.data());\n  auto u = momentum.compute(coeffs.data()) / m;\n  cout << scientific << setprecision(8) << \"mass: \" << m << endl\n       << \"momentum: \" << u(0) << \", \" << u(1) << endl;\n\n  // compute hermite coefficients\n  Eigen::VectorXd buf(N);\n\n  // --------------------------------------------------\n  // Transform to Hermite basis\n  // --------------------------------------------------\n  {\n    timer.start();\n    int nrep = 100000;\n    for (int i = 0; i < nrep; ++i) {\n      P2H.to_hermite(buf, coeffs);\n    }\n    double t = timer.stop();\n\n    print_timer(t / nrep, \"P2H.to_hermite\");\n  }\n\n  if (sizeof(numeric_t) == 16) {\n    cout << \"Using *extended precision*  in ShiftHermite\\n\";\n  } else if (sizeof(numeric_t) == 8) {\n    cout << \"Using double precision in ShiftHermite\\n\";\n  }\n\n  // use (extended/double) precision for shifting ...\n  std::vector<numeric_t> cH(buf.data(), buf.data() + N);\n  ShiftHermite2D<hermite_basis_t, numeric_t> shift_hermite(hermite_basis);\n  shift_hermite.init();\n\n  // --------------------------------------------------\n  // Shift hermite coefficients\n  // --------------------------------------------------\n  timer.start();\n  for (int i = 0; i < nrep; ++i) {\n    shift_hermite.shift(cH.data(), u(0), u(1));\n  }\n  double t_shift_hermite = timer.stop();\n  print_timer(t_shift_hermite / nrep, \"shift Hermite coefficients\");\n  cout << \"t_shift_hermite: \" << scientific << setprecision(10) << t_shift_hermite << endl;\n\n  // // transform coefficients back to double\n  // std::transform(cH.begin(), cH.end(), buf.begin(), [](numeric_t x) { return double(x); });\n\n  // // -> Polar coordinates\n  // std::vector<double> Cc(N, 0.0);\n  // P2H.to_polar(Cc, buf);\n\n  // const double mc = mass.compute(Cc.data());\n  // auto uc = momentum.compute(Cc.data())/mc;\n  // cout << \"centered:\\n\";\n  // cout << \"mass: \" << scientific  << setprecision(8) << mc << \"\\t(diff = \" << std::abs(m-mc) <<\n  // \")\"\n  //      << endl\n  //      << \"momentum: \" << uc(0) << \", \" << uc(1) << endl;\n\n  // // write new coefficients to disk\n  // hid_t h5_shifted = H5Fcreate(\"shifted.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  // Eigen::Map< Eigen::VectorXd> Cc_eigen(Cc.data(), Cc.size());\n  // eigen2hdf::save(h5_shifted, \"coeffs\", Cc_eigen);\n  // // export hermite coefficients\n  // Eigen::Map< Eigen::VectorXd> cH_eigen(buf.data(), buf.size());\n  // eigen2hdf::save(h5_shifted, \"coeffs_hermite\", cH_eigen);\n  // H5Fclose(h5_shifted);\n\n  // // do some cheap scattering\n  // // ...\n\n  // // Move back to original position\n  // timer.start();\n  // shift_hermite.shift(cH.data(), -u(0), -u(1));\n  // print_timer(timer.stop(), \"shift Hermite coefficients (back)\");\n\n  // // go back to polar coordinates\n  // std::transform(cH.begin(), cH.end(), buf.begin(), [](numeric_t x) { return double(x); });\n  // std::vector<double> Cc2(N, 0.0);\n  // P2H.to_polar(Cc2, buf);\n\n  // const double m1 = mass.compute(Cc2.data());\n  // auto u1 = momentum.compute(Cc2.data())/m1;\n\n  // cout << \"move back:\\n\";\n  // cout << \"mass: \" << scientific  << setprecision(8) << m1 << \"\\t(diff = \" << std::abs(m-m1) <<\n  // \")\"\n  //      << endl\n  //      << \"momentum: \" << scientific  << setprecision(8) << u1(0) << \", \" << u1(1) << \"\\t(diff =\n  //      \" << (u-u1).squaredNorm() << \")\" << endl;\n  return 0;}\n", "meta": {"hexsha": "b93d926ecb45584f63f09750292cf80a10fb47a4", "size": 6254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/p2h_shift_h2p/main_timings.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/p2h_shift_h2p/main_timings.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/p2h_shift_h2p/main_timings.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4438502674, "max_line_length": 99, "alphanum_fraction": 0.635753118, "num_tokens": 1807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.5802751468089824}}
{"text": "#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nextern \"C\" {\n  void AmulB(double*, double*, double*, long, long, long);\n  void AmulBt(double*, double*, double*, long, long, long);\n  void AtmulB(double*, double*, double*, long, long, long);\n  void AtmulBt(double*, double*, double*, long, long, long);\n  void Amulvb(double*, double*, double*, long, long);\n  void Atmulvb(double*, double*, double*, long, long);\n  double dot(double*, double*, long);\n  double selfdot(double*, long);\n  double dot3(double*, double*, double*, long, long);\n  void aplusBc(double*, double*, double*, double*, long, long);\n  double OLSlp(double*, double*, double*, long, long);\n  void AplusAt(double*, double*, long);\n  double logdettriangle(double*, long);\n}\n\ntypedef Map<MatrixXd> mMatrix;\ntypedef Map<VectorXd> mVector;\n\nvoid AmulB(double* pC, double* pA, double* pB, long M, long K, long N){\n  mMatrix A(pA, M, K);\n  mMatrix B(pB, K, N);\n  mMatrix C(pC, M, N);\n  C.noalias() = A * B;\n  return;\n}\nvoid AmulBt(double* pC, double* pA, double* pBt, long M, long K, long N){\n  mMatrix A(pA, M, K);\n  mMatrix Bt(pBt, N, K);\n  mMatrix C(pC, M, N);\n  C.noalias() = A * Bt.transpose();\n  return;\n}\nvoid AtmulB(double* pC, double* pAt, double* pB, long M, long K, long N){\n  mMatrix At(pAt, K, M);\n  mMatrix B(pB, K, N);\n  mMatrix C(pC, M, N);\n  C.noalias() = At.transpose() * B;\n  return;\n}\nvoid AtmulBt(double* pC, double* pAt, double* pBt, long M, long K, long N){\n  mMatrix At(pAt, K, M);\n  mMatrix Bt(pBt, N, K);\n  mMatrix C(pC, M, N);\n  C.noalias() = At.transpose() * Bt.transpose();\n  return;\n}\n\nvoid Amulvb(double* px, double* pA, double* py, long M, long N){\n  mVector x(px, M);\n  mMatrix A(pA, M, N);\n  mVector y(py, N);\n  x.noalias() = A * y;\n  return;\n}\n\nvoid Atmulvb(double* px, double* pAt, double* py, long M, long N){\n  mVector x(px, M);\n  mMatrix At(pAt, M, N);\n  mVector y(py, N);\n  x.noalias() = At.transpose() * y;\n  return;\n}\n\ndouble dot(double* pa, double* pb, long N){\n  mVector a(pa, N);\n  mVector b(pb, N);\n  return a.dot(b);\n}\n \ndouble selfdot(double* pa, long N){\n  mVector a(pa, N);\n  return a.dot(a);\n}\n\ndouble dot3(double* px, double* pA, double* py, long M, long N){\n  mVector x(px, M);\n  mMatrix A(pA, M, N);\n  mVector y(py, N);\n  return x.dot(A * y);\n}\n\nvoid aplusBc(double* pD, double* pa, double* pB, double* pc, long M, long N){\n  mMatrix D(pD, M, N);\n  mVector a(pa, M);\n  mMatrix B(pB, M, N);\n  mVector c(pc, N);\n  // D = (a + (B * c.asDiagonal()).colwise());\n  D.colwise() = a;\n  D.noalias() += B * c.asDiagonal();\n  return;\n}\n\ndouble OLSlp(double* py, double* pA, double* px, long M, long N){\n  mVector y(py, M);\n  mMatrix A(pA, M, N);\n  mVector x(px, N);\n  return (y - A * x).squaredNorm();\n}\n\nvoid AplusAt(double* pB, double* pA, long N){\n  mMatrix B(pB, N, N);\n  mMatrix A(pA, N, N);\n  B = A + A.transpose();\n  return;\n}\n\n// double logdettriangle(double* pA, long N){\n//   mMatrix A(pA, N, N);\n//   return log(A.diagonal()).sum();\n// }\n\n", "meta": {"hexsha": "64d54e90d112a6d808d618f372eff3ea8e552c6c", "size": 2950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/looptestseigen.cpp", "max_stars_repo_name": "danielwe/LoopVectorization.jl", "max_stars_repo_head_hexsha": "ed466fb1ca7e92b70b98d6ee50eb5544b64678e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 329.0, "max_stars_repo_stars_event_min_datetime": "2019-04-07T04:42:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T17:24:39.000Z", "max_issues_repo_path": "benchmark/looptestseigen.cpp", "max_issues_repo_name": "danielwe/LoopVectorization.jl", "max_issues_repo_head_hexsha": "ed466fb1ca7e92b70b98d6ee50eb5544b64678e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 198.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T03:34:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-11T20:49:20.000Z", "max_forks_repo_path": "benchmark/looptestseigen.cpp", "max_forks_repo_name": "danielwe/LoopVectorization.jl", "max_forks_repo_head_hexsha": "ed466fb1ca7e92b70b98d6ee50eb5544b64678e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2021-03-16T21:53:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T06:46:19.000Z", "avg_line_length": 25.2136752137, "max_line_length": 77, "alphanum_fraction": 0.6101694915, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5802737564016284}}
{"text": "//Refer: https://github.com/gaoxiang12/g2o_ba_example\n#include \"common.h\"\n\n// for std\n#include <iostream>\n// for opencv\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <boost/concept_check.hpp>\n// for g2o\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n#include <g2o/types/slam3d/se3quat.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\nusing namespace std;\n\n// 寻找两个图像中的对应点，像素坐标系\n// 输入：img1, img2 两张图像\n// 输出：points1, points2, 两组对应的2D点\nint findCorrespondingPoints(const cv::Mat &img1, const cv::Mat &img2, vector<cv::Point2f> &points1, vector<cv::Point2f> &points2);\n\n// 相机内参\ndouble cx = 325.5;\ndouble cy = 253.5;\ndouble fx = 518.0;\ndouble fy = 519.0;\n\nint main(int argc, char **argv)\n{\n    // 调用格式：命令 [第一个图] [第二个图]\n    if (argc != 3)\n    {\n        cout << \"Usage: ba_example img1, img2\" << endl;\n        exit(1);\n    }\n\n    // 读取图像\n    cv::Mat img1 = cv::imread(argv[1]);\n    cv::Mat img2 = cv::imread(argv[2]);\n\n    // 找到对应点\n    vector<cv::Point2f> pts1, pts2;\n    if (findCorrespondingPoints(img1, img2, pts1, pts2) == false)\n    {\n        cout << \"匹配点不够！\" << endl;\n        return 0;\n    }\n    cout << \"找到了\" << pts1.size() << \"组对应特征点。\" << endl;\n    // 构造g2o中的图\n    // 先构造求解器\n    g2o::SparseOptimizer optimizer;\n    // 使用Cholmod中的线性方程求解器\n    std::unique_ptr<g2o::BlockSolver_6_3::LinearSolverType> linearSolver = g2o::make_unique<g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType>>();\n\n    // 6*3 的参数\n    std::unique_ptr<g2o::BlockSolver_6_3> block_solver = g2o::make_unique<g2o::BlockSolver_6_3>(std::move(linearSolver));\n    // L-M 下降\n    g2o::OptimizationAlgorithmLevenberg *algorithm = new g2o::OptimizationAlgorithmLevenberg(std::move(block_solver));\n\n    optimizer.setAlgorithm(algorithm);\n    optimizer.setVerbose(false);\n\n    // 添加节点\n    // 两个位姿节点\n    for (int i = 0; i < 2; i++)\n    {\n        g2o::VertexSE3Expmap *v = new g2o::VertexSE3Expmap();\n        v->setId(i);\n        if (i == 0)\n            v->setFixed(true); // 第一个点固定为零\n        // 预设值为单位Pose，因为我们不知道任何信息\n        v->setEstimate(g2o::SE3Quat());\n        optimizer.addVertex(v);\n    }\n    // 很多个特征点的节点\n    // 以第一帧为准\n    for (size_t i = 0; i < pts1.size(); i++)\n    {\n        g2o::VertexSBAPointXYZ *v = new g2o::VertexSBAPointXYZ();\n        v->setId(2 + i);\n        // 由于深度不知道，只能把深度设置为1了\n        double z = 1;\n        double x = (pts1[i].x - cx) * z / fx;\n        double y = (pts1[i].y - cy) * z / fy;\n        v->setMarginalized(true);\n        v->setEstimate(Eigen::Vector3d(x, y, z));\n        optimizer.addVertex(v);\n    }\n\n    // 准备相机参数\n    g2o::CameraParameters *camera = new g2o::CameraParameters(fx, Eigen::Vector2d(cx, cy), 0);\n    camera->setId(0);\n    optimizer.addParameter(camera);\n\n    // 准备边\n    // 第一帧\n    vector<g2o::EdgeProjectXYZ2UV *> edges;\n    for (size_t i = 0; i < pts1.size(); i++)\n    {\n        g2o::EdgeProjectXYZ2UV *edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ *>(optimizer.vertex(i + 2)));\n        edge->setVertex(1, dynamic_cast<g2o::VertexSE3Expmap *>(optimizer.vertex(0)));\n        edge->setMeasurement(Eigen::Vector2d(pts1[i].x, pts1[i].y));\n        edge->setInformation(Eigen::Matrix2d::Identity());\n        edge->setParameterId(0, 0);\n        // 核函数\n        edge->setRobustKernel(new g2o::RobustKernelHuber());\n        optimizer.addEdge(edge);\n        edges.push_back(edge);\n    }\n    // 第二帧\n    for (size_t i = 0; i < pts2.size(); i++)\n    {\n        g2o::EdgeProjectXYZ2UV *edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ *>(optimizer.vertex(i + 2)));\n        edge->setVertex(1, dynamic_cast<g2o::VertexSE3Expmap *>(optimizer.vertex(1)));\n        edge->setMeasurement(Eigen::Vector2d(pts2[i].x, pts2[i].y));\n        edge->setInformation(Eigen::Matrix2d::Identity());\n        edge->setParameterId(0, 0);\n        // 核函数\n        edge->setRobustKernel(new g2o::RobustKernelHuber());\n        optimizer.addEdge(edge);\n        edges.push_back(edge);\n    }\n\n    cout << \"开始优化\" << endl;\n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    cout << \"优化完毕\" << endl;\n\n    //我们比较关心两帧之间的变换矩阵\n    g2o::VertexSE3Expmap *v = dynamic_cast<g2o::VertexSE3Expmap *>(optimizer.vertex(1));\n    Eigen::Isometry3d pose = v->estimate();\n    cout << \"Pose=\" << endl\n         << pose.matrix() << endl;\n\n    // 以及所有特征点的位置\n    for (size_t i = 0; i < pts1.size(); i++)\n    {\n        g2o::VertexSBAPointXYZ *v = dynamic_cast<g2o::VertexSBAPointXYZ *>(optimizer.vertex(i + 2));\n        cout << \"vertex id \" << i + 2 << \", pos = \";\n        Eigen::Vector3d pos = v->estimate();\n        cout << pos(0) << \",\" << pos(1) << \",\" << pos(2) << endl;\n    }\n\n    // 估计inlier的个数\n    int inliers = 0;\n    for (auto e : edges)\n    {\n        e->computeError();\n        // chi2 就是 error*\\Omega*error, 如果这个数很大，说明此边的值与其他边很不相符\n        if (e->chi2() > 1)\n        {\n            cout << \"error = \" << e->chi2() << endl;\n        }\n        else\n        {\n            inliers++;\n        }\n    }\n\n    cout << \"inliers in total points: \" << inliers << \"/\" << pts1.size() + pts2.size() << endl;\n    optimizer.save(\"ba.g2o\");\n    return 0;\n}\n\nint findCorrespondingPoints(const cv::Mat &img1, const cv::Mat &img2, vector<cv::Point2f> &points1, vector<cv::Point2f> &points2)\n{\n\n    cv::Ptr<cv::Feature2D> orb = cv::ORB::create(1000, 1.2, 8, 31, 0, 2, 0, 31, 20);\n    vector<cv::KeyPoint> kp1, kp2;\n    cv::Mat desp1, desp2;\n    orb->detectAndCompute(img1, cv::Mat(), kp1, desp1);\n    orb->detectAndCompute(img2, cv::Mat(), kp2, desp2);\n    cout << \"分别找到了\" << kp1.size() << \"和\" << kp2.size() << \"个特征点\" << endl;\n\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n\n    double knn_match_ratio = 0.8;\n    vector<vector<cv::DMatch>> matches_knn;\n    matcher->knnMatch(desp1, desp2, matches_knn, 2);\n    vector<cv::DMatch> matches;\n    for (size_t i = 0; i < matches_knn.size(); i++)\n    {\n        if (matches_knn[i][0].distance < knn_match_ratio * matches_knn[i][1].distance)\n            matches.push_back(matches_knn[i][0]);\n    }\n\n    if (matches.size() <= 20) //匹配点太少\n        return false;\n\n    for (auto m : matches)\n    {\n        points1.push_back(kp1[m.queryIdx].pt);\n        points2.push_back(kp2[m.trainIdx].pt);\n    }\n\n    return true;\n}\n", "meta": {"hexsha": "a66c4f8b949d1fbea3564c7c176c1afab73503a6", "size": 6592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/g2o_ba.cpp", "max_stars_repo_name": "yubaoliu/Practice", "max_stars_repo_head_hexsha": "8f0a9a7fbfb4b1d6e7745822fd81e66b2cf40b61", "max_stars_repo_licenses": ["MIT"], "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/g2o_ba.cpp", "max_issues_repo_name": "yubaoliu/Practice", "max_issues_repo_head_hexsha": "8f0a9a7fbfb4b1d6e7745822fd81e66b2cf40b61", "max_issues_repo_licenses": ["MIT"], "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/g2o_ba.cpp", "max_forks_repo_name": "yubaoliu/Practice", "max_forks_repo_head_hexsha": "8f0a9a7fbfb4b1d6e7745822fd81e66b2cf40b61", "max_forks_repo_licenses": ["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.845410628, "max_line_length": 158, "alphanum_fraction": 0.6030036408, "num_tokens": 2304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5802737429780078}}
{"text": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ntypedef long long ll;\ntypedef vector <int> vi;\n\nint der[14];\nint fac[14];\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    freopen(\"in.txt\", \"r\", stdin);\n    freopen(\"out.txt\", \"w\", stdout);\n    der[0] = 1; der[1] = 0;\n    int res = 1;\n    fac[0] = fac[1] = 1;\n    for(int i=2; i<13; i++){\n        der[i] = (i-1) * (der[i-1] + der[i-2]);\n        fac[i] = res = res * i;\n    }\n    int tc; cin >> tc;\n    for(int cas = 1; cas <= tc; cas++){\n        int n; cin >> n;\n        cout << der[n] << \"/\" << fac[n] << \"\\n\";\n    }\n    return 0;\n}", "meta": {"hexsha": "3abb5869db4de1adbc31afa592aa9db2cac88eda", "size": 691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Hats.cpp", "max_stars_repo_name": "satvik007/uva", "max_stars_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T06:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-16T02:31:27.000Z", "max_issues_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Hats.cpp", "max_issues_repo_name": "satvik007/uva", "max_issues_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Hats.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": 23.8275862069, "max_line_length": 48, "alphanum_fraction": 0.520984081, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.580273248932983}}
{"text": "// Copyright 2013 Velodyne Acoustics, 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\n  Program:   Visualization Toolkit\n  Module:    vtkVelodyneHDLReader.cxx\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n\n#include \"vtkPlaneFitter.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointSet.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkThreshold.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkNew.h\"\n\n#include <Eigen/Dense>\n\n//-----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkPlaneFitter);\n\n//-----------------------------------------------------------------------------\nvtkPlaneFitter::vtkPlaneFitter()\n{\n}\n\n//-----------------------------------------------------------------------------\nvtkPlaneFitter::~vtkPlaneFitter()\n{\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkPlaneFitter::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkPlaneFitter::PlaneFit(vtkPointSet* pts, double origin[3], double normal[3],\n                              double &minDist, double &maxDist, double &stdDev,\n                              double channelMean[32], double channelStdDev[32],\n                              vtkIdType channelNpts[32])\n{\n  using namespace Eigen;\n\n  vtkSmartPointer<vtkDoubleArray> ptdata = vtkSmartPointer<vtkDoubleArray>::New();\n  ptdata->DeepCopy(pts->GetPoints()->GetData());\n\n  const vtkIdType n = ptdata->GetNumberOfTuples();\n  if(n < 1)\n    {\n    return;\n    }\n\n  assert(ptdata->GetNumberOfComponents() == 3);\n  Map<MatrixXd> eigpointsraw(static_cast<double*>(ptdata->GetVoidPointer(0)),\n                             ptdata->GetNumberOfComponents(),\n                             ptdata->GetNumberOfTuples());\n\n  MatrixXd eigpoints = eigpointsraw.transpose();\n\n  VectorXd mean(3);\n\n  mean = eigpoints.colwise().sum() / n;\n  assert(mean.size() == 3);\n\n  for(int i = 0; i < 3; ++i)\n    {\n    origin[i] = mean[i];\n    }\n\n  eigpoints.rowwise() -= mean.transpose();\n\n  JacobiSVD<MatrixXd> svd(eigpoints, ComputeThinU | ComputeThinV);\n\n  VectorXd enormal = svd.matrixV().col(2);\n  assert(enormal.size() == 3);\n  assert(std::fabs(enormal.norm() - 1.0) < 1.0e-8);\n\n  for(int i = 0; i < 3; ++i)\n    {\n    normal[i] = enormal[i];\n    }\n\n  VectorXd distances = eigpoints * enormal;\n  assert(distances.size() == n);\n\n  minDist = distances.minCoeff();\n  maxDist = distances.maxCoeff();\n\n  stdDev = std::sqrt(distances.squaredNorm() / (n-1));\n\n  for(int i = 0; i < 32; ++i)\n    {\n    vtkNew<vtkThreshold> threshold;\n    threshold->ThresholdBetween(i,i);\n    threshold->SetInputData(pts);\n    threshold->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"laser_id\");\n    threshold->SetOutputPointsPrecision(vtkAlgorithm::DEFAULT_PRECISION);\n    threshold->Update();\n\n    channelNpts[i] = threshold->GetOutput()->GetNumberOfPoints();\n\n\n    vtkSmartPointer<vtkDoubleArray> threshdata = vtkSmartPointer<vtkDoubleArray>::New();\n    threshdata->DeepCopy(threshold->GetOutput()->GetPoints()->GetData());\n\n    const vtkIdType n = threshdata->GetNumberOfTuples();\n    if(n < 2)\n      {\n      channelMean[i] = 0.0;\n      channelStdDev[i] = 0.0;\n      continue;\n      }\n\n    assert(threshdata->GetNumberOfComponents() == 3);\n    assert(threshdata->GetNumberOfTuples() >= 2);\n    Map<MatrixXd> channelraw(static_cast<double*>(threshdata->GetVoidPointer(0)),\n                             threshdata->GetNumberOfComponents(),\n                             threshdata->GetNumberOfTuples());\n\n    MatrixXd channelpts = channelraw.transpose();\n    channelpts.rowwise() -= mean.transpose();\n\n    VectorXd channelds = channelpts * enormal;\n\n    double cmean = channelds.sum() / channelds.size();\n    double cstddev = std::sqrt((channelds.array() - cmean).matrix().squaredNorm() / (channelds.size()-1));\n\n    channelMean[i] = cmean;\n    channelStdDev[i] = cstddev;\n    }\n\n}\n", "meta": {"hexsha": "101c19a9391ccbefb3f96f2a959bf6bcd6d4ac12", "size": 5005, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/vtkPlaneFitter.cxx", "max_stars_repo_name": "yajin1126/C-Users-yajin-Documents-veloview", "max_stars_repo_head_hexsha": "aa1286abf5232827a3fac625146f69cbdb72a97a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "VelodyneHDL/vtkPlaneFitter.cxx", "max_issues_repo_name": "yajin1126/C-Users-yajin-Documents-veloview", "max_issues_repo_head_hexsha": "aa1286abf5232827a3fac625146f69cbdb72a97a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VelodyneHDL/vtkPlaneFitter.cxx", "max_forks_repo_name": "yajin1126/C-Users-yajin-Documents-veloview", "max_forks_repo_head_hexsha": "aa1286abf5232827a3fac625146f69cbdb72a97a", "max_forks_repo_licenses": ["Apache-2.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.8789808917, "max_line_length": 106, "alphanum_fraction": 0.5982017982, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5801438816139033}}
{"text": "//Authors: Dario Cattaruzza, Alessandro Abate, Peter Schrammel, Daniel Kroening\n//University of Oxford 2016\n//This code is based on Komei Fukuda's ccd implementation and as such supplied under the GPL license agreement (see license.txt)\n\n/* dplex.c:  dual simplex method c-code\n   written by Komei Fukuda, fukuda@ifor.math.ethz.ch\n   Version 0.61, December 1, 1997\n*/\n\n/* dplex.c : C-Implementation of the dual simplex method for\n   solving an LP: max/min  c^T x subject to  x in P, where\n   P= {x :  b - A x >= 0}.  \n   Please read COPYING (GNU General Public Licence) and\n   the manual cddman.tex for detail.\n*/\n\n#include \"DualSimplex.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n#include <string.h>\n\n#include <boost/timer.hpp>\n\nnamespace abstract {\ntemplate <class scalar>  DualSimplex<scalar>::DualSimplex(const int size,const int dimension)  :\n    Tableau<scalar>(size,dimension),\n    m_auxiliaryRow(1,m_dimension),\n    m_orBlockSize(1)\n{}\n\ntemplate <class scalar>\nbool DualSimplex<scalar>::load(const MatrixS &faces,const MatrixS &supports,const bool transpose)\n{\n  this->Conversion=LPMax;\n  if (!Tableau<scalar>::load (faces,supports,transpose)) return false;\n  m_auxiliaryRow.resize(1,m_dimension);\n  m_tableau.coeffRef(m_objectiveRow,0)=0;\n  return true;\n}\n\ntemplate <class scalar>\nbool DualSimplex<scalar>::SelectDualSimplexPivot(const bool Phase1,pivot_t &pivot)\n{ /* selects a dual simplex pivot (pivot.row, pivot.col) if the current\n     basis is dual feasible and not optimal. If not dual feasible,\n     the procedure returns false and m_status=LPSundecided.\n     If Phase1=true, the RHS column will be considered as the negative\n     of the column of the largest variable (==m_size).  For this case, it is assumed\n     that the caller used the auxiliary row (with variable m_size) to make the current\n     dictionary dual feasible before calling this routine so that the nonbasic\n     column for m_size corresponds to the auxiliary variable.\n  */\n  refScalar maxrat=0,rat=0;\n  scalar val=0;\n  scalar rcost[m_dimension];\n\n  pivot.col=0;\n  m_status=eUndecided;\n  for (int j=1; j<m_dimension; j++){//ignore RHSCol\n    rcost[j]=entry(m_objectiveRow,j);\n    if (func::isPositive(rcost[j])) {\n      //The zero case may cause an overapproximation of an empty set to an m_zero^n size hypercube.\n      return false;\n    }\n  }\n  //Dual Feasible.\n  pivot.row=Phase1 ? findMaxRow(m_basicVars[m_size]) : findMinRow(RHSCol);\n  if (pivot.row<0) {\n    m_status=eOptimal;\n  }\n  else {\n    for (int j=1; j<m_dimension; j++){// ignore RHSCol\n      val=entry(pivot.row,j);\n      if (func::isPositive(val)) {\n        //The zero case would result in a pivot move by a value inside the interval of the hyperplane\n        rat=func::toUpper(rcost[j]/val);\n        if ((pivot.col==0) || (rat > maxrat)){\n          maxrat=rat;\n          pivot.col=j;\n        }\n      }\n    }\n    if (pivot.col>0) return true;\n    m_status=eInconsistent;\n  }\n  return false;\n}\n\ntemplate <class scalar>\nbool DualSimplex<scalar>::SelectOredPivot(const long rowmax, const Set &noPivotRow, const Set &noPivotCol, pivot_t &pivot)\n/* Select a position (pivot) in the matrix X.T such that (X.T)[pivot.row][pivot.col] is nonzero\n   The choice is feasible, i.e., not on NopivotRow and NopivotCol, and\n   best with respect to the specified roworder\n */\n{\n  long rtemp;\n  Set rowexcluded(noPivotRow);\n  scalar Xtemp,Xtemp2;\n  scalar Ftemp,Ftemp2;\n  for (rtemp=rowmax;rtemp<m_size;rtemp++) {\n    rowexcluded.add(rtemp);   /* cannot pivot on any row > rmax */\n  }\n  while(true) {\n    rtemp=-1;\n    for (int i=1;i<=m_size;i++) {\n      if (!rowexcluded.member(m_tableau.zeroOrder(i))){\n        rtemp=m_tableau.zeroOrder(i);\n        break;\n      }\n    }\n    if (rtemp>=0) {\n      rtemp-=(rtemp%m_orBlockSize);\n      pivot.row=rtemp;\n      for (pivot.col=0;pivot.col < m_dimension;pivot.col++) {\n        if (!noPivotCol.member(pivot.col)) {\n          Xtemp=entry(pivot.row,pivot.col);\n          Ftemp=Xtemp/entry(pivot.row,0);\n          int offset=0;\n          for (int j=1;j<m_orBlockSize;j++) {\n            Xtemp2=entry(pivot.row+j,pivot.col);\n            Ftemp2=Xtemp2/entry(pivot.row+j,0);\n            if (func::isPositive(Ftemp2-Ftemp)) {\n              offset=j;\n              Xtemp=Xtemp2;\n              Ftemp=Ftemp2;\n            }\n          }\n          pivot.row+=offset;\n          char sign=func::softSign(Xtemp);//hardSign(Xtemp);//Zero is ensured by check in entry\n          if (sign<0) return true;\n        }\n      }\n      for (int i=0;i<m_orBlockSize;i++) rowexcluded.add(rtemp+i);\n    }\n    else {\n      pivot.row = -1;\n      pivot.col = -1;\n      return false;\n    }\n  }\n  return true;\n}\n\ntemplate <class scalar>\nvoid DualSimplex<scalar>::AuxiliaryPivotAndUpdate(long col)\n{\n  MatrixS Rtemp=m_auxiliaryRow*m_basisInverse;\n  char sign=func::hardSign(Rtemp.coeff(0,col));\n  if (sign==0) return;\n  scalar Xtemp;\n  refScalar Xtemp0 = func::toCentre(Rtemp.coeff(0,col));\n  for (int j = 0; j < m_dimension; j++) {\n    if (j != col) {\n      Xtemp = Rtemp.coeff(0,j) / Xtemp0;\n      for (int j1 = 0; j1 < m_dimension; j1++)\n        func::msub(m_basisInverse.coeffRef(j1,j),m_basisInverse.coeff(j1,col),Xtemp); //m_basisInverse.coeffRef(j1,j) -= m_basisInverse.coeff(j1,col) * Xtemp;\n    }\n  }\n  m_basisInverse.col(col) /= Xtemp0;\n  if (ms_trace_tableau>eTraceTableau) this->logBasis(m_size,col);\n  long entering=m_nonBasicRow[col];\n  m_basicVars[m_size]=col;              // the nonbasic variable r corresponds to column s\n  m_nonBasicRow[col]=m_size;            // the nonbasic variable on s column is r\n  if (entering>=0) m_basicVars[entering]=-1; // original variables have negative index and should not affect the row index\n}\n\n// Find the corresponding row with the minimum entry value for a given column\ntemplate <class scalar>\nint DualSimplex<scalar>::findMinRow(const int col)\n{\n  int row=-1;\n  refScalar minval=0;\n  refScalar val;\n  for (int i=0; i<m_objectiveRow; i++) {\n    if (m_basicVars[i]<0) {  /* i is a basic variable */\n      val=func::toUpper(entry(i,col)); // for dual Phase I (auxiliary row is non-basic)\n      if (val < minval) {\n        row=i;\n        minval=val;\n      }\n    }\n  }\n  return row;\n}\n\n// Find the corresponding row with the minimum entry value for a given column\ntemplate <class scalar>\nint DualSimplex<scalar>::findMaxRow(const int col)\n{\n  int row=-1;\n  refScalar maxval=0;\n  refScalar val;\n  for (int i=0; i<m_objectiveRow; i++) {\n    if (m_basicVars[i]<0) {  /* i is a basic variable */\n      // for dual Phase I (auxiliary row is non-basic)\n      val=func::toLower(entry(i,col));\n      if (val > maxval) {\n        row=i;\n        maxval=val;\n      }\n    }\n  }\n  return row;\n}\n\ntemplate <class scalar>\nint DualSimplex<scalar>::FindDualFeasibleBasis()\n{ /* Find a dual feasible basis using Phase I of Dual Simplex method.\n     If the problem is dual feasible,\n     the procedure returns m_status=LPSundecided and a dual feasible\n     basis.   If the problem is dual infeasible, this returns\n     m_status=DualInconsistent and the evidence column.\n  */\n\n  long rank=0;\n  pivot_t pivot;\n\n  m_status=eUndecided; this->m_evidenceCol=-1;\n  if (ms_trace_tableau>eTraceTableau) this->logBasis(m_objectiveRow,-1);\n  scalar maxcost=-1;\n  int maxReducedCostCol=0;  /* ms will be the index of column which has the largest reduced cost */\n  for (int col=1; col<m_tableau.cols(); col++){//ignore RHSCol\n    scalar cost=entry(m_objectiveRow,col);\n    if (func::toLower(cost) > func::toUpper(maxcost)) {maxcost=cost; maxReducedCostCol = col;}//TODO:might want to check for imprecision\n  }\n  if (ms_trace_tableau>=eTracePivots) {\n    std::stringstream buffer;\n    buffer << \"Dual feasible Basis. cost=\" << ms_logger.MakeNumber(maxcost) << \",c=\" << maxReducedCostCol;\n    ms_logger.logData(buffer.str());\n  }\n  if (!func::isPositive(maxcost)) return rank;//Dual feasible\n  //The zero case above indicates we are somewhere on the hyperplane which is feasible (or an m_zero overapprox)\n  m_auxiliaryRow=MatrixS::Zero(1,m_dimension);\n  for (int k=1; k<m_dimension; k++) {\n    if (m_nonBasicRow[k]>=0) {\n      m_auxiliaryRow-=m_tableau.row(m_nonBasicRow[k]);/* To make the auxiliary row (0,-1,-1,...,-1).  */\n    }\n  }\n  if (ms_trace_tableau>eTracePivots) {\n    ms_logger.logData(m_auxiliaryRow,\"Auxiliary Row:\");\n    if (ms_trace_tableau>=eTraceEntries) {\n      this->logNonBasic();\n      this->logBasic();\n      MatrixS matrix=m_auxiliaryRow*m_basisInverse;\n      ms_logger.logData(matrix,\"Entries\");\n    }\n  }\n\n  /* Pivot on (m_auxiliaryRow, maxReducedCostCol) so that the dual basic solution becomes feasible */\n  AuxiliaryPivotAndUpdate(maxReducedCostCol);\n  rank++;\n\n  m_status=eUndecided;/* Dual Simplex Phase I */\n  while (SelectDualSimplexPivot(true, pivot))  {\n    this->ColumnPivotAndUpdate(pivot);\n    rank++;\n    if (m_basicVars[m_size]<0) return rank;\n  }\n  /* The current dictionary is terminal.  There are two cases:\n     TableauEntry(m_objectiveRow,maxReducedCostCol) is negative or zero.\n     The first case implies dual infeasible,\n     and the latter implies dual feasible but m_size is still in nonbasis.\n     We must pivot in the auxiliary variable m_size. */\n\n  pivot.row=findMinRow(maxReducedCostCol);\n  pivot.col=maxReducedCostCol;\n  if (pivot.row>=0) {\n    this->ColumnPivotAndUpdate(pivot);\n    rank++;\n  }\n  if (func::isNegative(entry(m_objectiveRow, pivot.col))) {\n    m_status=eDualInconsistent;\n    this->m_evidenceCol=maxReducedCostCol;\n  }\n  return rank;\n}\n\ntemplate <class scalar>\nscalar DualSimplex<scalar>::maximise(const std::vector<scalar> &vector,const ResetType_t resetType)\n{\n  if (vector.size()<this->getDimension()) return func::ms_nan;\n  for (int col=1;col<m_tableau.cols();col++) {\n    m_tableau.coeffRef(m_objectiveRow,col)=vector.at(col-1);//TODO: check the sign\n  }\n  return processMaximize(resetType);\n}\n\ntemplate <class scalar>\nscalar DualSimplex<scalar>::maximise(const MatrixS &vector,const ResetType_t resetType)\n{\n  m_tableau.block(m_objectiveRow,1,1,vector.cols())=vector;//TODO: check the sign\n  return processMaximize(resetType);\n}\n\ntemplate <class scalar>\nbool DualSimplex<scalar>::maximiseAll(const MatrixS &vectors, MatrixS &supports,AproxType_t aprox)\n{\n  boost::timer timer;\n  try {\n    if (aprox==eOverAprox)       this->toOuter();\n    else if (aprox==eUnderAprox) this->toInner();\n    if ((supports.rows()!=vectors.cols()) || (supports.cols()!=1)) supports.resize(vectors.cols(),1);\n    FindFeasBasis(eResetBasis);\n    for (int i=0;i<vectors.cols();i++) {\n      m_tableau.block(m_objectiveRow,1,1,vectors.rows())=vectors.block(0,i,vectors.rows(),1).transpose();//TODO: check sign\n      supports.coeffRef(i,0)=processMaximize(eUseDefaultBasis);\n    }\n  }\n  catch(std::string error) {\n    ms_logger.logData(error);\n    return false;\n  }\n  if (this->ms_trace_time) {\n    int elapsed=timer.elapsed()*1000;\n    if (elapsed>0) {\n      ms_logger.logData(this->getName(),false);\n      ms_logger.logData(elapsed,\" Maximise time\",true);\n    }\n  }\n  return true;\n}\n\ntemplate <class scalar>\nscalar DualSimplex<scalar>::processMaximize(const ResetType_t resetType)\n/* \nWhen LP is inconsistent then *re returns the evidence row.\nWhen LP is dual-inconsistent then *se returns the evidence column.\n*/\n{\n  boost::timer timer;\n  long rank=0;\n  long maxpivfactor=70;\n  pivot_t pivot;\n  this->Error=this->None;\n  func::setZero(this->m_zero);\n  long maxpivots=maxpivfactor*m_dimension;  // maximum pivots to be performed before cc pivot is applied.\n  long rebasepivots=((func::getDefaultPrec()>>6)+1)*m_dimension;\n  /* Initializing control variables. */\n\n  this->m_evidenceRow=-1;\n  this->m_evidenceCol=-1;\n\n  if (resetType!=eRebaseBasis) m_iterations=0;\n\n  if (ms_trace_tableau>=eTracePivots) {\n    ms_logger.logData(m_tableau,\"Maximise\");\n  }\n\n  m_iterations+=this->FindFeasBasis(resetType);\n  if (this->ms_trace_time && (ms_trace_tableau>=eTracePivots) && (resetType!=eUseDefaultBasis)) {\n    logPivotCount(timer.elapsed()*1000,\"Find Feasible:\");\n  }\n  m_status=eUndecided;\n  if (this->m_evidenceCol<0) m_iterations+=FindDualFeasibleBasis();\n  if ((this->ms_trace_time) && (ms_trace_tableau>=eTracePivots)) {\n    logPivotCount(timer.elapsed()*1000,\"Find DualFeasible:\");\n  }\n\n  if (this->m_evidenceCol>=0){\n    if (m_status==eUndecided) m_status=eStrucDualInconsistent;// No LP basis is found, and thus Inconsistent.\n    // else No dual feasible basis is found, and thus DualInconsistent.\n    return entry( m_objectiveRow,RHSCol);\n  }\n  \n  if (ms_trace_tableau>=eTracePivots) ms_logger.logData(\"LP max\");\n\n  /* Dual Simplex Method */\n  while(true) {\n    m_status=eUndecided;\n    if (rank>rebasepivots) {// && (func::toWidth(entry(m_objectiveRow,RHSCol))*m_dimension*m_dimension>m_zero)) {\n      return processMaximize(eRebaseBasis);\n    }\n    if ((rank<maxpivots) && SelectDualSimplexPivot(false, pivot)) {\n      this->ColumnPivotAndUpdate(pivot);\n      rank++;\n    }\n    else if ((m_status==eUndecided) && SelectCrissCrossPivot(pivot)) {\n      /* In principle this should not be executed because we already have dual feasibility\n         attained and dual simplex pivot should have been chosen.  This might occur\n         under floating point computation, or the case of cycling.\n      */\n      this->ColumnPivotAndUpdate(pivot);\n      maxpivots+=maxpivfactor*m_dimension;\n      rank++;\n    }\n    else {\n      switch (m_status) {\n        case eInconsistent: this->m_evidenceRow=pivot.row;\n        case eDualInconsistent: this->m_evidenceCol=pivot.col;\n        default: break;\n      }\n      break;\n    }\n  }\n  m_iterations+=rank;\n  if ((this->ms_trace_time) && (ms_trace_tableau>=eTracePivots)) logPivotCount(timer.elapsed()*1000,\"Find Support:\");\n  scalar result=entry( m_objectiveRow,RHSCol);\n  if (func::isNan(result))\n    return result;\n  return result;\n}\n\ntemplate <class scalar>\nint DualSimplex<scalar>::FindFeasBasis(const ResetType_t resetType)\n{\n  m_tableau.coeffRef(m_objectiveRow,RHSCol)=0;\n  if (resetType==eUseDefaultBasis) {\n    m_basisInverse=m_feasBasisInverse;\n    m_basicVars=m_feasBasicVars;\n    m_nonBasicRow=m_feasNonBasicRow;\n    if (ms_trace_tableau>=eTraceTableau) this->logBasis(-1,-1);\n    return 0;\n  }\n  else if (resetType==eRebaseBasis) {\n    return this->Rebase();\n  }\n  this->ComputeRowOrderVector(MinIndex);\n  int result=this->FindLPBasis();//TODO: go to feasLP?\n  m_feasBasisInverse=m_basisInverse;\n  m_feasBasicVars=m_basicVars;\n  m_feasNonBasicRow=m_nonBasicRow;\n  return result;\n}\n\ntemplate <class scalar>\nint DualSimplex<scalar>::FindFeasOrBasis(int orBlockSize,const ResetType_t resetType)\n{\n  normalise(true);\n  m_orBlockSize=orBlockSize;\n  m_tableau.coeffRef(m_objectiveRow,RHSCol)=0;\n  if (resetType==eUseDefaultBasis) {\n    m_basisInverse=m_feasBasisInverse;\n    m_basicVars=m_feasBasicVars;\n    m_nonBasicRow=m_feasNonBasicRow;\n    if (ms_trace_tableau>=eTraceTableau) this->logBasis(-1,-1);\n    return 0;\n  }\n  else if (resetType==eRebaseBasis) {\n    return this->Rebase();\n  }\n  this->ComputeRowOrderVector(MinIndex);\n  int result=this->FindOrLPBasis();\n  m_feasBasisInverse=m_basisInverse;\n  m_feasBasicVars=m_basicVars;\n  m_feasNonBasicRow=m_nonBasicRow;\n  return result;\n}\n\ntemplate <class scalar>\nint DualSimplex<scalar>::FindOrLPBasis()\n{ /* Find a LP basis using Gaussian pivots.\n     If the problem has an LP basis,\n     the procedure returns m_evidenceCol=-1 if LPSundecided and an LP basis.\n     If the constraint matrix A (excluding the rhs and objective) is not\n     column indepent, there are two cases.  If the dependency gives a dual\n     inconsistency, this returns the evidence column m_evidenceCol.  Otherwise, this returns an LP basis of size less than n_size.  Columns j\n     that do not belong to the basis (i.e. cannot be chosen as pivot because\n     they are all zero) will be indicated in nbindex vector: nbindex[j] will\n     be negative and set to -j.\n  */\n  if (ms_trace_tableau>=eTracePivots) ms_logger.logData(\"Ored Feasibility Basis\");\n  ResetTableau();\n  Set RowSelected(m_size);\n  Set ColSelected(m_dimension);\n  RowSelected.add(m_objectiveRow);\n  ColSelected.add(RHSCol);\n  pivot_t pivot;\n  int rank=m_dimension;\n  m_evidenceCol=-1;\n  for (int i=0;i<m_dimension;i++) {   /* Find a set of rows for a basis */\n    if (!SelectOredPivot(m_size, RowSelected, ColSelected, pivot))\n    {\n      rank=i;\n      for (int j=1;j<m_dimension; j++) {//Skip RHSCol\n        if (m_nonBasicRow[j]<0){\n          if (!func::isZero(entry(m_objectiveRow,j),m_zero)) {  /* dual inconsistent */\n            m_evidenceCol=j;\n            break;\n          }\n        }\n      }\n      /* dependent columns but not dual inconsistent. */\n      break;\n    }\n    if (ms_trace_tableau>=eTraceEntries) {\n      RowSelected.logSet(\"Available Rows:\",true);\n      ColSelected.logSet(\"Available Cols:\",true);\n    }\n    RowSelected.add(pivot.row);\n    ColSelected.add(pivot.col);\n    ColumnPivotAndUpdate(pivot);\n  }\n  return rank;\n}\n\n\ntemplate <class scalar>\nbool DualSimplex<scalar>::SelectCrissCrossPivot(pivot_t &pivot)\n{\n  m_status=eUndecided;\n  for (int i=0; i<m_size; i++) {\n    if (i!=m_objectiveRow && m_basicVars[i]==-1) {  /* i is a basic variable */\n      if (func::isNegative(entry(i,RHSCol))) {\n        //The zero case above indicates we are somewhere on the hyperplane which is feasible (or an m_zero overapprox)\n        pivot.row=i;\n        for (int j=0; j<m_size; j++) {\n          if (m_basicVars[j] >0) { /* i is nonbasic variable */\n             if (func::isPositive(entry(pivot.row,m_basicVars[j]))) {\n               pivot.col=m_basicVars[j];\n               return true;\n             }\n          }\n        }\n        m_status=eInconsistent;\n        return false;\n      }\n\n    }\n    else if (m_basicVars[i] >0) { /* i is nonbasic variable */\n      if (func::isPositive(entry(m_objectiveRow,m_basicVars[i]))) {\n        //The zero case above indicates we are somewhere on the hyperplane which is feasible (or an m_zero overapprox)\n        pivot.col=m_basicVars[i];\n        for (int j=0; j<m_size; j++) {\n          if (j!=m_objectiveRow && m_basicVars[j]==-1) {  /* i is a basic variable */\n            if (func::isNegative(entry(j,pivot.col))) {\n              pivot.row=j;\n              return true;\n            }\n          }\n        }\n        m_status=eDualInconsistent;\n        return false;\n      }\n    }\n  }\n  m_status=eOptimal;\n  return false;\n}\n\n/// Normalises the directions of the faces\ntemplate <class scalar>\nvoid DualSimplex<scalar>::normalise(bool reload)\n{\n  if (this->m_isNormalised || m_faces.rows()<=0) return;\n  MatrixS norms=m_faces.rowwise().norm();\n  for (int i=0;i<m_faces.rows();i++) {\n    char sign=func::hardSign(norms.coeff(i));\n    if (sign!=0) {\n      for (int j=0;j<m_faces.cols();j++) m_faces.coeffRef(i,j)/=norms.coeff(i);\n      m_supports.coeffRef(i,0)=m_supports.coeff(i,0)/norms.coeff(i);\n    }\n  }\n  this->m_isNormalised=true;\n  if (reload) load(m_faces,m_supports);\n}\n\n/// Clears redundant faces in the polyhedra (caused by intersections and reductions)\ntemplate <class scalar>\nbool DualSimplex<scalar>::removeRedundancies()\n{\n  int rows=m_faces.rows();\n  if (rows<=0) return false;\n  bool isRedundant[rows];\n  for (int i=0;i<m_faces.rows();i++) isRedundant[i] =true;\n  int redundant=m_faces.rows();\n  this->m_isNormalised=false;\n  for (int row=0;row<m_faces.rows();row++) {\n    for (int col=0;col<m_faces.cols();col++) {\n      char sign=func::hardSign(m_faces.coeff(row,col));\n      if (sign!=0) {\n        isRedundant[row]=false;\n        redundant--;\n        break;\n      }\n    }\n  }\n  normalise(false);\n  SortedMatrix<scalar> faces(m_faces.rows(),m_faces.cols());\n  faces.block(0,0,m_faces.rows(),m_faces.cols())=m_faces;\n  faces.ComputeRowOrderVector(LexMin);\n  for (int i=1;i<=m_faces.rows();i++)\n  {\n    int row=faces.zeroOrder(i);\n    if (isRedundant[row]) continue;\n    int count=m_faces.rows();\n    for (int j=i+1;j<=count;j++) {\n      int row2=faces.zeroOrder(j);\n      if (isRedundant[row2]) continue;\n      MatrixS check=m_faces.row(row)-m_faces.row(row2);\n      char sign=func::hardSign(check.norm());\n      if (sign==0) {\n        isRedundant[row2]=true;//TODO: should aggregate width(error) on non-redundant vector\n        if (func::isNegative(m_supports.coeff(row2,0)-m_supports.coeff(row,0))) {\n          isRedundant[row2]=false;\n          isRedundant[row]=true;\n          i=j;\n          row=row2;\n        }\n        redundant++;\n      }\n      else break;\n    }\n  }\n\n/*  for (int i=0;i<m_faces.rows();i++)\n  {\n    if (isRedundant[i]) continue;\n    int count=m_faces.rows();\n    for (int j=i+1;j<count;j++) {\n      if (isRedundant[j]) continue;\n      MatrixS check=m_faces.row(i)-m_faces.row(j);\n      char sign=func::hardSign(check.norm());\n      if (sign==0) isRedundant[j]=true;\n      if (isRedundant[j]) {\n        if (m_supports.coeff(j,0)<m_supports.coeff(i,0)) {\n          isRedundant[j]=false;\n          isRedundant[i++]=true;\n          while ((i<count) && isRedundant[i]) i++;\n          j=i+1;\n        }\n        redundant++;\n      }\n    }\n  }*/\n  if (redundant>0) {\n    int pos=0;\n    for (int i=0;i<m_faces.rows();i++) {\n      if (isRedundant[i]) continue;\n      m_faces.row(pos)=m_faces.row(i);\n      m_supports.coeffRef(pos,0)=m_supports.coeff(i,0);\n      pos++;\n    }\n    m_faces.conservativeResize(pos,m_faces.cols());\n    m_supports.conservativeResize(pos,1);\n    load(m_faces,m_supports);\n    return true;\n  }\n  load(m_faces,m_supports);\n  return false;\n}\n\n/// Saves the time and iteration count data for the given process\ntemplate <class scalar>\nvoid DualSimplex<scalar>::logPivotCount(int time,std::string process)\n{\n  ms_logger.logData(time,process,true);\n  ms_logger.logData(m_iterations,\"Iterations:\",true);\n}\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class DualSimplex<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class DualSimplex<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class DualSimplex<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class DualSimplex<mpinterval>;\n  #endif\n#endif\n\n}\n", "meta": {"hexsha": "098805d83f7fb2e42652aa963f72cc07895deb26", "size": 22040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/DualSimplex.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/DualSimplex.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/DualSimplex.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": 32.8955223881, "max_line_length": 158, "alphanum_fraction": 0.6691016334, "num_tokens": 6225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162774, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5799593421639149}}
{"text": "#include <iostream>\n#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Constrained_triangulation_plus_2.h>\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/IO/WKT.h>\n\nnamespace PS = CGAL::Polyline_simplification_2;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Polygon_2<K>    Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<K>    Polygon_with_holes_2;\ntypedef PS::Vertex_base_2<K>  Vb;\ntypedef CGAL::Constrained_triangulation_face_base_2<K> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb> TDS;\ntypedef CGAL::Exact_predicates_tag                          Itag;\ntypedef CGAL::Constrained_Delaunay_triangulation_2<K,TDS, Itag> CDT;\ntypedef CGAL::Constrained_triangulation_plus_2<CDT>     CT;\ntypedef CT::Point                           Point;\ntypedef CT::Constraint_id                   Constraint_id;\ntypedef CT::Constraint_iterator             Constraint_iterator;\ntypedef CT::Vertices_in_constraint_iterator Vertices_in_constraint_iterator;\ntypedef CT::Points_in_constraint_iterator   Points_in_constraint_iterator;\ntypedef PS::Stop_below_count_ratio_threshold Stop;\ntypedef PS::Squared_distance_cost Cost;\n\nvoid print(const CT& ct, Constraint_id cid)\n{\n  std::cout << \"simplified polyline\" <<std::endl;\n  for(Vertices_in_constraint_iterator vit =\n        ct.vertices_in_constraint_begin(cid);\n      vit != ct.vertices_in_constraint_end(cid);\n      ++vit){\n    std::cout << (*vit)->point() << std::endl ;\n  }\n\n  std::cout << \"original points\" <<std::endl;\n  for(Points_in_constraint_iterator pit =\n        ct.points_in_constraint_begin(cid);\n      pit != ct.points_in_constraint_end(cid);\n      ++pit){\n    std::cout << *pit << std::endl ;\n  }\n\n}\n\n\nint main(int argc, char* argv[])\n{\n  std::ifstream ifs( (argc==1)?\"data/polygon.wkt\":argv[1]);\n  const bool remove_points = false;\n  CT ct;\n  Polygon_with_holes_2 P;\n  Constraint_id cid;\n  std::size_t largest = 0;\n  while(CGAL::IO::read_polygon_WKT(ifs, P)){\n    const Polygon_2& poly = P.outer_boundary();\n    Constraint_id cid2 = ct.insert_constraint(poly);\n    if(poly.size() > largest){\n      cid = cid2;\n    }\n  }\n\n  PS::simplify(ct, cid, Cost(), Stop(0.5), remove_points);\n  print(ct, cid);\n  PS::simplify(ct, cid, Cost(), Stop(0.5), remove_points);\n  ct.remove_points_without_corresponding_vertex(cid);\n  print(ct, cid);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "0faecfc1c97031b3dfc4a0515350b02055e5bcbc", "size": 2579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polyline_simplification_2/examples/Polyline_simplification_2/points_and_vertices.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": "Polyline_simplification_2/examples/Polyline_simplification_2/points_and_vertices.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": "Polyline_simplification_2/examples/Polyline_simplification_2/points_and_vertices.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": 32.6455696203, "max_line_length": 76, "alphanum_fraction": 0.7219852656, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5799592005793104}}
{"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_COLORS_MATRIX_FORM_PRIMARIES_HPP\n#define PIC_COLORS_MATRIX_FORM_PRIMARIES_HPP\n\n#include \"../base.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n    #ifndef PIC_EIGEN_NOT_BUNDLED\n        #include \"../externals/Eigen/Dense\"\n        #include \"../externals/Eigen/QR\"\n    #else\n        #include <Eigen/Dense>\n        #include <Eigen/QR>\n    #endif\n#endif\n\nnamespace pic {\n\n/**\n * @brief createMatrixFromPrimaries computes a matrix for converting XYZ values into the\n * defined color space (i.e., by defining the three primaries: red, green, and blue).\n * @param red_XYZ is the XYZ values of the red primary\n * @param green_XYZ is the XYZ values of the green primary\n * @param blue_XYZ is the XYZ values of the blue primary\n * @param white_point_XYZ is the XYZ values of the white point primary\n * @return It returns a 3x3 matrix for converting XYZ values into the defined color space\n */\nfloat *createMatrixFromPrimaries(float *red_XYZ,\n                                 float *green_XYZ,\n                                 float *blue_XYZ,\n                                 float *white_point_XYZ,\n                                 float *ret = NULL\n                                 )\n{\n    if(red_XYZ == NULL || green_XYZ == NULL || blue_XYZ == NULL) {\n        return ret;\n    }\n\n    if(ret == NULL) {\n        ret = new float[9];\n    }\n\n#ifndef PIC_DISABLE_EIGEN\n\n    int w = 0;\n    if(white_point_XYZ != NULL) {\n        w = 3;\n    }\n\n    //set up a liner system A x = b\n    int nRow = 9 + w;\n    Eigen::MatrixXf A(nRow, 9);\n    Eigen::VectorXf b(nRow);\n\n    //A matrix\n    A.setZero();\n\n    //red\n    for(int j = 0; j < 3; j++) {\n        for(int i = 0 ; i < 3; i++) {\n            A(j, j * 3 + i) = red_XYZ[i];\n        }\n    }\n\n    //green`\n    for(int j = 0; j < 3; j++) {\n        for(int i = 0 ; i < 3; i++) {\n            A(j + 3, j * 3 + i) = green_XYZ[i];\n        }\n    }\n\n    //blue`\n    for(int j = 0; j < 3; j++) {\n        for(int i = 0 ; i < 3; i++) {\n            A(j + 6, j * 3 + i) = blue_XYZ[i];\n        }\n    }\n\n    //white\n    if(w == 3) {\n        for(int j = 0; j < 3; j++) {\n            for(int i = 0 ; i < 3; i++) {\n                A(j + 9, j * 3 + i) = white_point_XYZ[i];\n            }\n        }\n    }\n\n    //b vector\n    b(0) = 1.0f;\n    b(1) = 0.0f;\n    b(2) = 0.0f;\n\n    b(3) = 0.0f;\n    b(4) = 1.0f;\n    b(5) = 0.0f;\n\n    b(6) = 0.0f;\n    b(7) = 0.0f;\n    b(8) = 1.0f;\n\n    if(w == 3) {\n        b(9) = 1.0f;\n        b(10) = 1.0f;\n        b(11) = 1.0f;\n    }\n\n    //solve Ax=b\n    Eigen::VectorXf x = A.colPivHouseholderQr().solve(b);\n\n    for(int i = 0; i < 9; i++) {\n        ret[i] = x(i);\n    }\n#endif\n    return ret;\n}\n\n} // end namespace pic\n\n#endif /* PIC_COLORS_MATRIX_FORM_PRIMARIES_HPP */\n\n", "meta": {"hexsha": "9ca9154f9aed96cee9ce2fcd0fb29b17fb361b59", "size": 3101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/colors/matrix_from_primaries.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/colors/matrix_from_primaries.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/colors/matrix_from_primaries.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": 22.6350364964, "max_line_length": 89, "alphanum_fraction": 0.523379555, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5799591890559523}}
{"text": "#include <iostream>\n#include <stdlib.h>\n\n#include <gmpxx.h>\n#include <NTL/ZZ.h>\n\nusing namespace std;\n\nvoid usage(char *progname) {\n\tcout << \"This program finds m given m^e and e, as long as \"\n\t\t\"m^e < n.\" << endl;\n\tcout << \"Usage: \" << progname << \" c e\" << endl;\n}\n\n\nint main(int argc, char *argv[]) {\n\tif (argc != 3) { usage(argv[0]); return 3; }\n\n\t// NTL doesn't provide an integer root function, so we\n\t// have to use GMP integers\n\tmpz_class c, root;\n\tmpz_t r;\n\tmpz_init(r);\n\tif(c.set_str(argv[1],0)) {\n\t\tcerr << \"Invalid message: \" << argv[1] << endl;\n\t\treturn 2;\n\t}\n\n\tunsigned long e;\n\tif(!(e = strtoul(argv[2], NULL, 0))) {\n\t\tcerr << \"Invalid public exponent: \" << argv[2] << endl;\n\t\treturn 2;\n\t}\n\n\t\n\t// Find c^(1/e)\n\tif(!mpz_root(r, c.get_mpz_t(), e)) {\n\t\tcerr << \"Error: m^e is greater than n!\" << endl;\n\t\treturn 1;\n\t} else {\n\t\tcout << mpz_class(r) << endl;\n\t}\n}\n", "meta": {"hexsha": "4b412ddfeded998669a5d4e50137aa1da7ba5121", "size": 873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integer_root.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "integer_root.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "integer_root.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8409090909, "max_line_length": 60, "alphanum_fraction": 0.5841924399, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5799591785457604}}
{"text": "// Copyright (C) 2016 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef STAT_NORMAL_DISTRIBUTION_HPP\n#define STAT_NORMAL_DISTRIBUTION_HPP\n\n#include <stdexcept>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include <boost/throw_exception.hpp>\n#include \"power.hpp\"\n#include \"moment.hpp\"\n\nnamespace stat {\n\nusing math::p2;\nusing math::p3;\nusing math::p4;\n  \nclass normal_distribution : public moment<normal_distribution> {\nprivate:\n  typedef moment<normal_distribution> super_type;\npublic:\n  normal_distribution(double mu = 0, double sigma = 1) : super_type(*this), mu_(mu), sigma_(sigma) {\n    if (sigma_ <= 0)\n      boost::throw_exception(std::invalid_argument(\"stat::normal_distribution\"));\n  }\n  std::string name() const {\n    return \"Normal Distribution: N(\" + boost::lexical_cast<std::string>(mu_) + \",\"\n      + boost::lexical_cast<std::string>(sigma_) + \")\";\n  }\n  double moment1() const { return mu_; }\n  double moment2() const { return p2(mu_) + p2(sigma_); }\n  double moment3() const { return p3(mu_) + 3 * mu_ * p2(sigma_); }\n  double moment4() const { return p4(mu_) + 6 * p2(mu_) * p2(sigma_) + 3 * p4(sigma_); }\nprivate:\n  double mu_, sigma_;\n};\n\n} // end namespace stat\n\n#endif // STAT_NORMAL_DISTRIBUTION_HPP\n", "meta": {"hexsha": "06e6f5083b502673db5f88ce7c0702d0627709c5", "size": 1390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/tools/normal_distribution.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/tools/normal_distribution.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/tools/normal_distribution.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": 30.8888888889, "max_line_length": 100, "alphanum_fraction": 0.7050359712, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5799430979177497}}
{"text": "\n#include <NTL/mat_ZZ_pE.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\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      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_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      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 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  \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      Error(\"matrix mul: dimension mismatch\");  \n  \n   X.SetDims(n, m);  \n  \n   long i, j, k;  \n   ZZ_pX 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, rep(A(i,k)), rep(B(k,j)));  \n            add(acc, acc, tmp);  \n         }  \n         conv(X(i,j), acc);  \n      }  \n   }  \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  \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      Error(\"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.position1(x) != -1) {\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      Error(\"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\nvoid determinant(ZZ_pE& d, const mat_ZZ_pE& M_in)\n{\n   long k, n;\n   long i, j;\n   long pos;\n   ZZ_pX t1, t2;\n   ZZ_pX *x, *y;\n\n   const ZZ_pXModulus& p = ZZ_pE::modulus();\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   vec_ZZ_pX *M = NTL_NEW_OP vec_ZZ_pX[n];\n\n   for (i = 0; i < n; i++) {\n      M[i].SetLength(n);\n      for (j = 0; j < n; j++) {\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   ZZ_pX det;\n   set(det);\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      for (i = k; 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         if (k != pos) {\n            swap(M[pos], M[k]);\n            negate(det, det);\n         }\n\n         MulMod(det, det, M[k][k], p);\n\n         // make M[k, k] == -1 mod p, and make row k reduced\n\n         InvMod(t1, M[k][k], p);\n         negate(t1, t1);\n         for (j = k+1; j < n; j++) {\n            rem(t2, M[k][j], p);\n            MulMod(M[k][j], t2, t1, p);\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];   // this is already reduced\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         goto done;\n      }\n   }\n\n   conv(d, det);\n\ndone:\n   delete[] M;\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\nvoid solve(ZZ_pE& d, vec_ZZ_pE& X, \n           const mat_ZZ_pE& A, const vec_ZZ_pE& 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   ZZ_pX t1, t2;\n   ZZ_pX *x, *y;\n\n   const ZZ_pXModulus& p = ZZ_pE::modulus();\n\n   vec_ZZ_pX *M = NTL_NEW_OP vec_ZZ_pX[n];\n\n   for (i = 0; i < n; i++) {\n      M[i].SetLength(n+1);\n      for (j = 0; j < n; j++) {\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\n         M[i][j] = rep(A[j][i]);\n      }\n      M[i][n].rep.SetMaxLength(2*deg(p)-1);\n      M[i][n] = rep(b[i]);\n   }\n\n   ZZ_pX det;\n   set(det);\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      for (i = k; 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\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], p);\n\n         // make M[k, k] == -1 mod p, and make row k reduced\n\n         InvMod(t1, M[k][k], p);\n         negate(t1, t1);\n         for (j = k+1; j <= n; j++) {\n            rem(t2, M[k][j], p);\n            MulMod(M[k][j], t2, t1, p);\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];   // this is already reduced\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         goto done;\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, 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\ndone:\n   delete[] M;\n}\n\nvoid inv(ZZ_pE& d, mat_ZZ_pE& X, const mat_ZZ_pE& 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   ZZ_pX t1, t2;\n   ZZ_pX *x, *y;\n\n   const ZZ_pXModulus& p = ZZ_pE::modulus();\n\n\n   vec_ZZ_pX *M = NTL_NEW_OP vec_ZZ_pX[n];\n\n   for (i = 0; i < n; i++) {\n      M[i].SetLength(2*n);\n      for (j = 0; j < n; j++) {\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\n         M[i][j] = rep(A[i][j]);\n         M[i][n+j].rep.SetMaxLength(2*deg(p)-1);\n         clear(M[i][n+j]);\n      }\n      set(M[i][n+i]);\n   }\n\n   ZZ_pX det;\n   set(det);\n\n   for (k = 0; k < n; k++) {\n      pos = -1;\n      for (i = k; 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\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], p);\n\n         // make M[k, k] == -1 mod p, and make row k reduced\n\n         InvMod(t1, M[k][k], p);\n         negate(t1, t1);\n         for (j = k+1; j < 2*n; j++) {\n            rem(t2, M[k][j], p);\n            MulMod(M[k][j], t2, t1, p);\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];   // this is already reduced\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         goto done;\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, rep(X[j][k]), M[i][j]);\n            add(t1, t1, t2);\n         }\n         sub(t1, t1, M[i][n+k]);\n         conv(X[i][k], t1);\n      }\n   }\n\n   conv(d, det);\n\ndone:\n   delete[] M;\n}\n\n\n\nlong gauss(mat_ZZ_pE& M_in, long w)\n{\n   long k, l;\n   long i, j;\n   long pos;\n   ZZ_pX t1, t2, t3;\n   ZZ_pX *x, *y;\n\n   long n = M_in.NumRows();\n   long m = M_in.NumCols();\n\n   if (w < 0 || w > m)\n      Error(\"gauss: bad args\");\n\n   const ZZ_pXModulus& p = ZZ_pE::modulus();\n\n\n   vec_ZZ_pX *M = NTL_NEW_OP vec_ZZ_pX[n];\n\n   for (i = 0; i < n; i++) {\n      M[i].SetLength(m);\n      for (j = 0; j < m; j++) {\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\n         M[i][j] = rep(M_in[i][j]);\n      }\n   }\n\n   l = 0;\n   for (k = 0; k < w && l < n; k++) {\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\n      if (pos != -1) {\n         swap(M[pos], M[l]);\n\n         InvMod(t3, M[l][k], p);\n         negate(t3, t3);\n\n         for (j = k+1; j < m; j++) {\n            rem(M[l][j], M[l][j], p);\n         }\n\n         for (i = l+1; i < n; i++) {\n            // M[i] = M[i] + M[l]*M[i,k]*t3\n\n            MulMod(t1, M[i][k], t3, p);\n\n            clear(M[i][k]);\n\n            x = M[i].elts() + (k+1);\n            y = M[l].elts() + (k+1);\n\n            for (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         l++;\n      }\n   }\n   \n   for (i = 0; i < n; i++)\n      for (j = 0; j < m; j++)\n         conv(M_in[i][j], M[i][j]);\n\n   delete [] M;\n\n   return l;\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\nvoid kernel(mat_ZZ_pE& X, const mat_ZZ_pE& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   mat_ZZ_pE M;\n   long r;\n\n   transpose(M, A);\n   r = gauss(M);\n\n   X.SetDims(m-r, m);\n\n   long i, j, k, s;\n   ZZ_pX t1, t2;\n\n   ZZ_pE T3;\n\n   vec_long D;\n   D.SetLength(m);\n   for (j = 0; j < m; j++) D[j] = -1;\n\n   vec_ZZ_pE inverses;\n   inverses.SetLength(m);\n\n   j = -1;\n   for (i = 0; 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   for (k = 0; k < m-r; k++) {\n      vec_ZZ_pE& v = X[k];\n      long pos = 0;\n      for (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            i = D[j];\n\n            clear(t1);\n\n            for (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   \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) Error(\"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()) Error(\"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\nNTL_END_IMPL\n", "meta": {"hexsha": "17519cddb9d280408dce8b8833bbc5c8e0f8bd79", "size": 16364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/mat_ZZ_pE.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_ZZ_pE.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_ZZ_pE.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": 18.8525345622, "max_line_length": 69, "alphanum_fraction": 0.3976411635, "num_tokens": 6063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5798360462391028}}
{"text": "#include <nav_msgs/Odometry.h>\n#include <ros/ros.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <Eigen/Core>\n#include <cmath>\n#include <iostream>\n\nusing namespace Eigen;\n\ndouble deg2rad(const double degree) { return degree * M_PI / 180.0; }\n\ndouble rad2deg(const double radian) { return radian * 180.0 / M_PI; }\n\ndouble angle_limit_pi(double angle)\n{\n  while (angle >= M_PI) { angle -= 2 * M_PI; }\n  while (angle <= -M_PI) { angle += 2 * M_PI; }\n  return angle;\n}\n\ndouble sdlab_uniform()\n{\n  double ret = ((double)rand() + 1.0) / ((double)RAND_MAX + 2.0);\n  return ret;\n}\n\n// gauss noise\ndouble gauss(double mu, double sigma)\n{\n  double z = std::sqrt(-2.0 * std::log(sdlab_uniform())) * std::sin(2.0 * M_PI * sdlab_uniform());\n  return mu + sigma * z;\n}\n\nclass FakeSensorPublisher\n{\npublic:\n  FakeSensorPublisher()\n  : grund_truth(Matrix<double, 3, 1>::Zero()),\n    odom(Matrix<double, 3, 1>::Zero()),\n    gps(Matrix<double, 3, 1>::Zero())\n  {\n    Q << 0.1, 0, 0, deg2rad(30);\n    Q = Q * Q;\n    R << 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, deg2rad(5);\n    R = R * R;\n\n    ground_truth_pub_ = pnh_.advertise<nav_msgs::Odometry>(\"grund_truth\", 10);\n    odom_pub_ = pnh_.advertise<nav_msgs::Odometry>(\"odom\", 10);\n    gps_pub_ = pnh_.advertise<nav_msgs::Odometry>(\"gps\", 10);\n\n    previous_stamp_ = ros::Time::now();\n\n    timer_ = nh_.createTimer(ros::Duration(0.01), &FakeSensorPublisher::timerCallback, this);\n  }\n  ~FakeSensorPublisher() {}\n  nav_msgs::Odometry inputToNavMsgs(Matrix<double, 3, 1> pose_2d, Matrix<double, 2, 1> input)\n  {\n    nav_msgs::Odometry msg;\n    msg.header.frame_id = \"world\";\n    msg.child_frame_id = \"odom\";\n    msg.pose.pose.position.x = pose_2d[0];\n    msg.pose.pose.position.y = pose_2d[1];\n\n    tf2::Quaternion quat;\n    quat.setRPY(0.0, 0.0, angle_limit_pi(pose_2d[2]));\n    msg.pose.pose.orientation.w = quat.w();\n    msg.pose.pose.orientation.x = quat.x();\n    msg.pose.pose.orientation.y = quat.y();\n    msg.pose.pose.orientation.z = quat.z();\n    msg.twist.twist.linear.x = input[0];\n    msg.twist.twist.angular.z = input[1];\n\n    return msg;\n  }\n  void timerCallback(const ros::TimerEvent & e)\n  {\n    ros::Time current_stamp = ros::Time::now();\n\n    nav_msgs::Odometry grund_truth_msg;\n    nav_msgs::Odometry odom_msg;\n    nav_msgs::Odometry gps_msgs;\n\n    Matrix<double, 2, 1> u(1.0, deg2rad(5));\n\n    const double dt = current_stamp.toSec() - previous_stamp_.toSec();\n\n    // ground truth\n    ROS_INFO(\"delta time: %f\", dt);\n    grund_truth = motionModel(grund_truth, u, dt);\n    grund_truth_msg = inputToNavMsgs(grund_truth, u);\n\n    // dead recogning\n    Matrix<double, 2, 1> ud = motionNoise(u, Q);\n    odom = motionModel(odom, ud, dt);\n    odom_msg = inputToNavMsgs(odom, ud);\n\n    // observation\n    Matrix<double, 3, 1> gps = observationNoise(grund_truth, R);\n    gps_msgs = inputToNavMsgs(gps, Matrix<double, 2, 1>::Zero());\n\n    ground_truth_pub_.publish(grund_truth_msg);\n    odom_pub_.publish(odom_msg);\n    gps_pub_.publish(gps_msgs);\n\n    previous_stamp_ = current_stamp;\n  }\n  Matrix<double, 3, 1> motionModel(Matrix<double, 3, 1> x, Matrix<double, 2, 1> u, double dt)\n  {\n    Matrix<double, 3, 3> F = Matrix<double, 3, 3>::Identity();\n    Matrix<double, 3, 2> B;\n    B << dt * std::cos(x[2]), 0, dt * std::sin(x[2]), 0, 0, dt;\n\n    x = F * x + B * u;\n    x[2] = angle_limit_pi(x[2]);\n    return x;\n  }\n  Matrix<double, 2, 1> motionNoise(Matrix<double, 2, 1> u, Matrix<double, 2, 2> Q)\n  {\n    Matrix<double, 2, 1> uw(gauss(0.0, Q(0, 0)), gauss(0.0, Q(1, 1)));\n    return u + uw;\n  }\n  Matrix<double, 3, 1> observationNoise(Matrix<double, 3, 1> x, Matrix<double, 3, 3> R)\n  {\n    Matrix<double, 3, 1> xw(gauss(0.0, R(0, 0)), gauss(0.0, R(1, 1)), gauss(0.0, R(2, 2)));\n    return x + xw;\n  }\n\nprivate:\n  ros::NodeHandle nh_{};\n  ros::NodeHandle pnh_{\"~\"};\n  ros::Timer timer_;\n  ros::Time previous_stamp_;\n\n  ros::Publisher ground_truth_pub_;\n  ros::Publisher odom_pub_;\n  ros::Publisher gps_pub_;\n\n  Matrix<double, 2, 2> Q;\n  Matrix<double, 3, 3> R;\n  Matrix<double, 3, 1> grund_truth;\n  Matrix<double, 3, 1> odom;\n  Matrix<double, 3, 1> gps;\n};\n\nint main(int argc, char ** argv)\n{\n  ros::init(argc, argv, \"fake_sensor_publisher_node\");\n  FakeSensorPublisher fake_sensor_publisher;\n  ros::spin();\n  return 0;\n}\n", "meta": {"hexsha": "960f7dcce24cf6259b73ea43efef22bafe6fbc47", "size": 4319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fake_sensor_publisher_node.cpp", "max_stars_repo_name": "RyuYamamoto/fake_sensor_publisher", "max_stars_repo_head_hexsha": "aab437e98ee3ecd8a8f73b5a5a08d8aa24972b11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/fake_sensor_publisher_node.cpp", "max_issues_repo_name": "RyuYamamoto/fake_sensor_publisher", "max_issues_repo_head_hexsha": "aab437e98ee3ecd8a8f73b5a5a08d8aa24972b11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fake_sensor_publisher_node.cpp", "max_forks_repo_name": "RyuYamamoto/fake_sensor_publisher", "max_forks_repo_head_hexsha": "aab437e98ee3ecd8a8f73b5a5a08d8aa24972b11", "max_forks_repo_licenses": ["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.2287581699, "max_line_length": 98, "alphanum_fraction": 0.6383422088, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5797034585682844}}
{"text": "#include \"sampler.h\"\n#include \"params.h\"\n#include <NTL/ZZ_pX.h>\n#include <NTL/mat_ZZ_p.h>\n#include <cassert>\n\nvoid Sampler::get_ternary_vector(vector<int>& vec)\n{\n\n    for(int i=0; i<vec.size(); i++)\n        vec[i] = ternary_sampler(rand_engine);\n}\n\nvoid Sampler::get_ternary_matrix(vector<vector<int>>& mat)\n{\n\n    for(int i=0; i<mat.size(); i++)\n    {\n        vector<int>& row = mat[i];\n        get_ternary_vector(row);\n    }\n}\n\nvoid Sampler::get_binary_vector(vector<int>& vec)\n{\n    for(int i=0; i<vec.size(); i++)\n        vec[i] = binary_sampler(rand_engine);\n}\n\nvoid Sampler::get_uniform_vector(vector<int>& vec)\n{\n    for(int i=0; i<vec.size(); i++)\n        vec[i] = mod_q_base_sampler(rand_engine);\n}\n\nvoid Sampler::get_uniform_matrix(vector<vector<int>>& mat)\n{\n    for(int i=0; i<mat.size(); i++)\n    {\n        vector<int>& row = mat[i];\n        get_uniform_vector(row);\n    }\n}\n\nvoid Sampler::get_gaussian_vector(vector<int>& vec, double st_dev)\n{\n    normal_distribution<double> gaussian_sampler(0.0, st_dev);\n    for(size_t i=0; i<vec.size(); i++)\n        vec[i] = static_cast<int>(round(gaussian_sampler(rand_engine)));\n}\n\nvoid Sampler::get_gaussian_matrix(vector<vector<int>>& mat, double st_dev)\n{\n    for(size_t i=0; i<mat.size(); i++)\n    {\n        vector<int>& row = mat[i];\n        get_gaussian_vector(row, st_dev);\n    }\n}\n\nvoid Sampler::get_invertible_vector(vector<int>& vec, vector<int>& vec_inv, int scale, int shift)\n{\n    //polynomial with the coefficient vector vec (will be generated later)\n    ZZ_pX poly;\n    //element of Z_(q_boot)\n    ZZ_p coef;\n    coef.init(ZZ(q_boot));\n    //the inverse of poly modulo poly_mod (will be generated later)\n    ZZ_pX inv_poly;\n    //random sampling\n    while (true)\n    {\n        //create the polynomial with the coefficient vector of the desired form\n        SetCoeff(poly, 0, ternary_sampler(rand_engine)*scale + shift);\n        for (size_t i = 1; i < vec.size(); i++)\n        {\n            coef = ternary_sampler(rand_engine)*scale;\n            SetCoeff(poly, i, coef);\n        }\n        //test invertibility\n        try\n        {\n            InvMod(inv_poly, poly, Param::get_def_poly());\n            break;\n        }\n        catch(...)\n        {\n            cout << \"Polynomial \" << poly << \" isn't a unit\" << endl;\n            continue;\n        }\n    }\n    //cout << \"Poly: \" << poly << endl;\n    //cout << \"Poly inverse: \" << inv_poly << endl;\n    //extract the coefficient vector of poly\n    int tmp_coef;\n    for (int i = 0; i <= deg(poly); i++)\n    {\n        tmp_coef = conv<long>(poly[i]);\n        if (tmp_coef > half_q_boot)\n            tmp_coef -= q_boot;\n        vec[i] = tmp_coef;\n    }\n\n    for (int i = 0; i <= deg(inv_poly); i++)\n    {\n        tmp_coef = conv<long>(inv_poly[i]);\n        if (tmp_coef > half_q_boot)\n            tmp_coef -= q_boot;\n        vec_inv[i] = tmp_coef;\n    }\n\n    //cout << \"Vector:\" << vec << endl;\n    //cout << \"Inverse vector:\" << vec_inv << endl;\n}\n\nvoid Sampler::get_invertible_matrix(vector<vector<int>>& mat, vector<vector<int>>& mat_inv, int scale, int shift)\n{\n    //check that the input matrices are squares\n    assert(mat[0].size() == mat.size());\n    assert(mat_inv[0].size() == mat_inv.size());\n    //check that both input matrices have the same dimension\n    assert(mat.size() == mat_inv.size());\n\n    //number of rows of the input matrix\n    int dim = mat.size();\n\n    //element of Z_(q_boot)\n    ZZ_p coef;\n    coef.init(ZZ(param.q_base));\n\n    //candidate matrix\n    mat_ZZ_p tmp_mat(INIT_SIZE, dim, dim);\n\n    //candidate inverse matrix\n    mat_ZZ_p tmp_mat_inv(INIT_SIZE, dim, dim);\n    \n    //sampling and testing\n    while (true)\n    {\n        //sampling\n        for (int i = 0; i < dim; i++)\n        {\n            Vec<ZZ_p>& row = tmp_mat[i];\n            for (int j = 0; j < dim; j++)\n            {\n                coef = ternary_sampler(rand_engine)*scale;\n                if (i==j)\n                    coef += ZZ_p(shift);\n                row[j] = coef;\n            }\n        }\n        //test invertibility\n        try\n        {\n            inv(tmp_mat_inv, tmp_mat);\n            break;\n        }\n        catch(...)\n        {\n            cout << \"Matrix \" << tmp_mat << \" is singular\" << endl;\n            continue;\n        }\n    }\n    //lift mod q representation to integers\n    int tmp_coef;\n    for (int i = 0; i < dim; i++)\n    {\n        Vec<ZZ_p>& tmp_row = tmp_mat[i];\n        Vec<ZZ_p>& tmp_row_inv = tmp_mat_inv[i];\n        vector<int>& row = mat[i];\n        vector<int>& row_inv = mat_inv[i];\n        for (int j = 0; j < dim; j++)\n        {\n            tmp_coef = conv<long>(tmp_row[j]);\n            if (tmp_coef > param.half_q_base)\n                tmp_coef -= param.q_base;\n            row[j] = tmp_coef;\n\n            tmp_coef = conv<long>(tmp_row_inv[j]);\n            if (tmp_coef > param.half_q_base)\n                tmp_coef -= param.q_base;\n            row_inv[j] = tmp_coef;\n        }\n    }\n}", "meta": {"hexsha": "f3dcb8132ab7414f69295cae713b3ba967670d18", "size": 4944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sampler.cpp", "max_stars_repo_name": "KULeuven-COSIC/FINAL", "max_stars_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2022-01-21T13:15:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:46:19.000Z", "max_issues_repo_path": "src/sampler.cpp", "max_issues_repo_name": "KULeuven-COSIC/FINAL", "max_issues_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-24T21:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T21:09:18.000Z", "max_forks_repo_path": "src/sampler.cpp", "max_forks_repo_name": "KULeuven-COSIC/FINAL", "max_forks_repo_head_hexsha": "c6296ae5457ae6e61a9466a1497c6b0130460343", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-24T07:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T07:27:50.000Z", "avg_line_length": 26.7243243243, "max_line_length": 113, "alphanum_fraction": 0.5461165049, "num_tokens": 1292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6619228891883799, "lm_q1q2_score": 0.5797034558252084}}
{"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// edited: Simon Pintarelli\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n#include <cmath>\n\n#include \"mpfr/import_std_math.hpp\"\n\nnamespace boost {\nnamespace math {\n\n// Recurrance relation for Hermite polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\nhermiten_next(unsigned n, T1 x, T2 Hn, T3 Hnm1)\n{\n  typedef T1 numeric_t;\n\n  const numeric_t fn = 2 / numeric_t(n + 1);\n  const numeric_t fnm = numeric_t(n) / (n + 1);\n  return ::math::sqrt(fn) * x * Hn - ::math::sqrt(fnm) * Hnm1;\n}\n\nnamespace detail {\n\n// Implement Hermite polynomials via recurrance:\ntemplate <class T>\nT\nhermiten_imp(unsigned n, T x)\n{\n  static const T pi = boost::math::constants::pi<T>();\n  static const T pif = ::math::pow(pi, (T)-0.25);\n  T p0 = pif;\n\n  if (n == 0) return p0;\n\n  T p1 = sqrt(T(2)) * x * pif;\n\n  unsigned c = 1;\n\n  while (c < n) {\n    std::swap(p0, p1);\n    p1 = hermiten_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\nhermiten(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>(\n      detail::hermiten_imp(n, static_cast<value_type>(x)),\n      \"boost::math::hermiten<%1%>(unsigned, %1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\nhermiten(unsigned n, T x)\n{\n  return boost::math::hermiten(n, x, policies::policy<>());\n}\n\n}  // namespace math\n}  // namespace boost\n", "meta": {"hexsha": "529e33e00188eab5a58b4ab61062811b4333bdf2", "size": 2014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/hermiten_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/hermiten_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/hermiten_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": 25.4936708861, "max_line_length": 78, "alphanum_fraction": 0.6911618669, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5796852377975695}}
{"text": "#pragma once\r\n\r\n#include <boost/math/special_functions/sign.hpp>\r\n\r\nDFG_ROOT_NS_BEGIN { DFG_SUB_NS(math) {\r\n\r\n// Returns sign of a value: 1 if value is positive, 0 if value is 0, -1 if value is < 0.\r\n// Note: Behaviour for NaN's is unspecified.\r\n// See also: std::signbit, std::copysign (C++11)\r\ntemplate <class T>\r\nint sign(const T& val)\r\n{\r\n\treturn boost::math::sign(val);\r\n\t/*\r\n\tif (val > 0)\r\n\t\treturn 1;\r\n\telse if (val == 0)\r\n\t\treturn 0;\r\n\telse\r\n\t\treturn -1;\r\n\t\t*/\r\n}\r\n\r\ntemplate <class T>\r\nauto signBit(const T& val) -> decltype(boost::math::signbit(val))\r\n{\r\n\treturn boost::math::signbit(val);\r\n}\r\n\r\n// Returns value whose absolute value is from val0 and sign from val1.\r\ntemplate <class T0, class T1>\r\nauto signCopied(const T0& val0, const T1& val1) -> decltype(boost::math::copysign(val0, val1))\r\n{\r\n\treturn boost::math::copysign(val0, val1);\r\n}\r\n\r\n// Returns val with sign changed.\r\ntemplate <class T>\r\nauto signChanged(const T& val) -> decltype(boost::math::changesign(val))\r\n{\r\n\treturn boost::math::changesign(val);\r\n}\r\n\r\n}} // module namespace\r\n", "meta": {"hexsha": "f99df962cc69f6aa1884b5884a7a00378bf5d497", "size": 1057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dfg/math/sign.hpp", "max_stars_repo_name": "tc3t/dfglib", "max_stars_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_stars_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-01T04:42:29.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-01T04:42:29.000Z", "max_issues_repo_path": "dfg/math/sign.hpp", "max_issues_repo_name": "tc3t/dfglib", "max_issues_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_issues_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": 128.0, "max_issues_repo_issues_event_min_datetime": "2018-04-06T23:01:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:19:38.000Z", "max_forks_repo_path": "dfg/math/sign.hpp", "max_forks_repo_name": "tc3t/dfglib", "max_forks_repo_head_hexsha": "7157973e952234a010da8e9fbd551a912c146368", "max_forks_repo_licenses": ["MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T01:11:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T19:20:31.000Z", "avg_line_length": 23.4888888889, "max_line_length": 95, "alphanum_fraction": 0.6584673605, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5796852261896891}}
{"text": "/*\n * position3.hpp\n *\n *  Created on: Dec 9, 2013\n *      Author: joost\n */\n\n#ifndef POSITION3_HPP_\n#define POSITION3_HPP_\n\n#include <math.h>\n#include <boost/serialization/serialization.hpp>\n#include <boost/serialization/utility.hpp>\n#include <sferes/dbg/dbg.hpp>\n\nnamespace sferes\n{\n  namespace gen\n  {\n    namespace spatial\n    {\n      class Pos\n      {\n        public:\n          Pos() {\n          }\n          Pos(float x, float y, float z) : _x(x), _y(y), _z(z) {\n          }\n          float dist(const Pos& p) const\n          {\n            float x = _x - p._x;\n            float y = _y - p._y;\n            float z = _z - p._z;\n            return sqrt(x * x + y * y + z * z);\n          }\n          float x() const { return _x; }\n          float y() const { return _y; }\n          float z() const { return _z; }\n\n          void setX(const float& x){_x = x;};\n          void setY(const float& y){_y = y;};\n          void setZ(const float& z){_z = z;};\n\n          void moveX(const float& dx){_x += dx;};\n          void moveY(const float& dy){_y += dy;};\n          void moveZ(const float& dz){_z += dz;};\n\n          void translate(const float& dx, const float& dy, const float& dz){\n        \t  moveX(dx);\n        \t  moveY(dy);\n        \t  moveZ(dz);\n          }\n\n          float& operator [] (const size_t& index){\n        \t  switch(index){\n        \t  case 0:\n        \t\t  return _x;\n        \t  case 1:\n        \t\t  return _y;\n        \t  case 2:\n        \t\t  return _z;\n        \t  default: dbg::sentinel(DBG_HERE);\n        \t  }\n        \t  dbg::sentinel(DBG_HERE);\n        \t  throw 0;\n          }\n\n          Pos& operator *= (const float& scalar){\n        \t  _x*=scalar;\n        \t  _y*=scalar;\n        \t  _z*=scalar;\n        \t  return *this;\n          }\n\n          Pos& operator += (const float& scalar){\n        \t  _x+=scalar;\n        \t  _y+=scalar;\n        \t  _z+=scalar;\n        \t  return *this;\n          }\n\n          Pos& operator += (const Pos& other){\n        \t  _x+=other.x();\n        \t  _y+=other.y();\n        \t  _z+=other.z();\n        \t  return *this;\n          }\n\n          template<class Archive>\n          void serialize(Archive& ar, const unsigned int version)\n          {\n            ar& BOOST_SERIALIZATION_NVP(_x);\n            ar& BOOST_SERIALIZATION_NVP(_y);\n            ar& BOOST_SERIALIZATION_NVP(_z);\n          }\n          bool operator == (const Pos &p)\n          { return _x == p._x && _y == p._y && _z == p._z; }\n        protected:\n          float _x, _y, _z;\n      };\n\n      Pos operator+(const Pos& lhs, const Pos& rhs){\n    \tPos result (lhs);\n      \tresult+=rhs;\n      \treturn result;\n      }\n\n      Pos operator*(const Pos& lhs, const float& rhs){\n    \tPos result (lhs);\n      \tresult*=rhs;\n      \treturn result;\n      }\n\n      Pos operator*(const float& rhs, const Pos& lhs){\n      \treturn lhs*rhs;\n      }\n\n      std::ostream& operator<<(std::ostream& is, const Pos& obj){\n          is << obj.x() << \" \" << obj.y() << \" \" << obj.z();\n          return is;\n      }\n    }\n  }\n}\n\n#endif /* POSITION3_HPP_ */\n", "meta": {"hexsha": "3db1e7d7626c4908365cf76eccbb6a352e5113b1", "size": 3029, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "position3.hpp", "max_stars_repo_name": "JoostHuizinga/datatools", "max_stars_repo_head_hexsha": "05e47f8a74b13c59fdcd3882db6d9ed284607ba1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "position3.hpp", "max_issues_repo_name": "JoostHuizinga/datatools", "max_issues_repo_head_hexsha": "05e47f8a74b13c59fdcd3882db6d9ed284607ba1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "position3.hpp", "max_forks_repo_name": "JoostHuizinga/datatools", "max_forks_repo_head_hexsha": "05e47f8a74b13c59fdcd3882db6d9ed284607ba1", "max_forks_repo_licenses": ["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.8503937008, "max_line_length": 76, "alphanum_fraction": 0.4625288874, "num_tokens": 809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5796759406125651}}
{"text": "// Filename: matrix_free_3.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), s(m * n) {}\n\n    template <typename VectorIn, typename VectorOut, typename Assign>\n    void mult(const VectorIn& v, VectorOut& w, Assign) const\n    {\n\tassert(int(size(v)) == m * n);\n\tassert(size(v) == size(w));\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\tAssign::apply(w[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    Assign::apply(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    Assign::apply(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    Assign::apply(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    Assign::apply(w[k], 4 * v[k] - v[k-n] - v[k+n] - v[k-1]); \n\n\t// Corners\n\tAssign::apply(w[0], 4 * v[0] - v[1] - v[n]);\n\tAssign::apply(w[n-1], 4 * v[n-1] - v[n-2] - v[2*n - 1]);\n\tAssign::apply(w[(m-1)*n], 4 * v[(m-1)*n] - v[(m-2)*n] - v[(m-1)*n+1]);\n\tAssign::apply(w[m*n-1], 4 * v[m*n-1] - v[m*n-2] - v[m*n-n-1]);\n    }\n\n    template <typename VectorIn>\n    mtl::vec::mat_cvec_multiplier<poisson2D_dirichlet, VectorIn> operator*(const VectorIn& v) const\n    {\treturn mtl::vec::mat_cvec_multiplier<poisson2D_dirichlet, VectorIn>(*this, v);    }\n\n    int m, n, s;\n};\n\ninline std::size_t size(const poisson2D_dirichlet& A) { return A.s * A.s; }\ninline std::size_t num_rows(const poisson2D_dirichlet& A) { return A.s; }\ninline std::size_t num_cols(const poisson2D_dirichlet& A) { return A.s; }\n\nnamespace mtl { \n\n    template <>\n    struct Collection<poisson2D_dirichlet>\n    {\n\ttypedef double value_type;\n\ttypedef int    size_type;\n    };\n\n    namespace ashape {\n\ttemplate <> struct ashape_aux<poisson2D_dirichlet> \n\t{\ttypedef nonscal type;    };\n    }\n}\n\nint main(int, char**)\n{\n    using namespace std;\n    typedef mtl::dense_vector<double> vt;\n    \n    vt v(20);\n    iota(v);\n    cout << \"v is \" << v << endl;\n\n    poisson2D_dirichlet A(4, 5);\n    vt                  w2(20);\n\n    w2= A * v;\n    cout << \"A * v is \" << w2 << endl;\n\n    w2+= A * v;\n    cout << \"w2+= A * v is \" << w2 << endl;\n\n    w2-= A * v;\n    cout << \"w2-= A * v is \" << w2 << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0e7a5fca38b1c98a32c224a4441ec6d66cd67fe9", "size": 2504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_free_3.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_3.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_3.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.6382978723, "max_line_length": 99, "alphanum_fraction": 0.5399361022, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.579675940612565}}
{"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 * Author: Martin Kronbichler, 2020 \n */ \n\n\n\n// 包含文件与之前的无矩阵教程程序 step-37 、 step-48 和 step-59 相似。\n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/time_stepping.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/vectorization.h> \n\n#include <deal.II/distributed/tria.h> \n\n#include <deal.II/dofs/dof_handler.h> \n\n#include <deal.II/fe/fe_dgq.h> \n#include <deal.II/fe/fe_system.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/tria.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/la_parallel_vector.h> \n\n#include <deal.II/matrix_free/fe_evaluation.h> \n#include <deal.II/matrix_free/matrix_free.h> \n\n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <iomanip> \n#include <iostream> \n\n// 下面的文件包括CellwiseInverseMassMatrix数据结构，我们将在质量矩阵反演中使用它，这是本教程程序中唯一的新包含文件。\n\n#include <deal.II/matrix_free/operators.h> \n\nnamespace Euler_DG \n{ \n  using namespace dealii; \n\n// 与其他无矩阵教程程序类似，我们在文件的顶部收集所有控制程序执行的参数。除了我们想要运行的维度和多项式程度，我们还指定了我们想要用于欧拉方程中非线性项的高斯正交公式的点数。此外，我们指定了随时间变化的问题的时间间隔，并实现了两个不同的测试案例。第一个是二维的分析解，而第二个是介绍中描述的围绕圆柱体的通道流。根据测试案例，我们还改变了运行模拟的最终时间，以及一个变量`output_tick`，它指定了我们要在哪个时间间隔内写入输出（假设tick大于时间步长）。\n\n  constexpr unsigned int testcase             = 0; \n  constexpr unsigned int dimension            = 2; \n  constexpr unsigned int n_global_refinements = 3; \n  constexpr unsigned int fe_degree            = 5; \n  constexpr unsigned int n_q_points_1d        = fe_degree + 2; \n\n  using Number = double; \n\n  constexpr double gamma       = 1.4; \n  constexpr double final_time  = testcase == 0 ? 10 : 2.0; \n  constexpr double output_tick = testcase == 0 ? 1 : 0.05; \n\n// 接下来是时间积分器的一些细节，即用公式 $\\Delta t =\n//  \\text{Cr} n_\\text{stages} \\frac{h}{(p+1)^{1.5} (\\|\\mathbf{u} +\n//  c)_\\text{max}}$ 来衡量时间步长的库朗数，以及选择一些低存储量的Runge--Kutta方法。我们指定Runge--Kutta方案每级的Courant数，因为这对不同级数的方案给出了一个更实际的数值成本表达。\n\n  const double courant_number = 0.15 / std::pow(fe_degree, 1.5); \n  enum LowStorageRungeKuttaScheme \n  { \n    stage_3_order_3, /* Kennedy, Carpenter, Lewis, 2000 */ \n\n\n    stage_5_order_4, /* Kennedy, Carpenter, Lewis, 2000 */ \n\n\n    stage_7_order_4, /* Tselios, Simos, 2007 */ \n\n\n    stage_9_order_5, /* Kennedy, Carpenter, Lewis, 2000 */ \n\n\n  }; \n  constexpr LowStorageRungeKuttaScheme lsrk_scheme = stage_5_order_4; \n\n// 最终，我们选择了空间离散化的一个细节，即单元间面的数值通量（黎曼求解器）。在这个程序中，我们实现了Lax--Friedrichs通量和Harten--Lax--van Leer(HLL)通量的一个改进版本。\n\n  enum EulerNumericalFlux \n  { \n    lax_friedrichs_modified, \n    harten_lax_vanleer, \n  }; \n  constexpr EulerNumericalFlux numerical_flux_type = lax_friedrichs_modified; \n\n//  @sect3{Equation data}  \n\n// 我们现在定义了一个带有测试情况0的精确解的类和一个带有测试情况1的通道背景流场的类。鉴于欧拉方程是一个在 $d$ 维度上有 $d+2$ 个方程的问题，我们需要告诉函数基类正确的分量数量。\n\n  template <int dim> \n  class ExactSolution : public Function<dim> \n  { \n  public: \n    ExactSolution(const double time) \n      : Function<dim>(dim + 2, time) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n// 就实际实现的函数而言，分析性测试案例是一个等熵涡旋案例（例如参见Hesthaven和Warburton的书，第209页第6.6节中的例6.1），它满足欧拉方程，右侧的力项为零。考虑到这个定义，我们返回密度、动量或能量，这取决于所要求的成分。请注意，密度的原始定义涉及一些表达式的 $\\frac{1}{\\gamma -1}$ -次方。由于 `std::pow()` 在某些系统上的实现相当慢，我们用对数和指数（以2为底）来代替它，这在数学上是等价的，但通常优化得更好。与 `std::pow()`, 相比，对于非常小的数字，这个公式可能会在最后一位数字上失去准确性，但我们还是很高兴，因为小数字映射为接近1的数据。\n\n// 对于通道测试案例，我们简单地选择密度为1， $x$ 方向的速度为0.4，其他方向的速度为0，以及对应于背景速度场测量的1.3声速的能量，根据关系 $E = \\frac{c^2}{\\gamma (\\gamma -1)} + \\frac 12 \\rho \\|u\\|^2$ 计算得出。\n\n  template <int dim> \n  double ExactSolution<dim>::value(const Point<dim> & x, \n                                   const unsigned int component) const \n  { \n    const double t = this->get_time(); \n\n    switch (testcase) \n      { \n        case 0: \n          { \n            Assert(dim == 2, ExcNotImplemented()); \n            const double beta = 5; \n\n            Point<dim> x0; \n            x0[0] = 5.; \n            const double radius_sqr = \n              (x - x0).norm_square() - 2. * (x[0] - x0[0]) * t + t * t; \n            const double factor = \n              beta / (numbers::PI * 2) * std::exp(1. - radius_sqr); \n            const double density_log = std::log2( \n              std::abs(1. - (gamma - 1.) / gamma * 0.25 * factor * factor)); \n            const double density = std::exp2(density_log * (1. / (gamma - 1.))); \n            const double u       = 1. - factor * (x[1] - x0[1]); \n            const double v       = factor * (x[0] - t - x0[0]); \n\n            if (component == 0) \n              return density; \n            else if (component == 1) \n              return density * u; \n            else if (component == 2) \n              return density * v; \n            else \n              { \n                const double pressure = \n                  std::exp2(density_log * (gamma / (gamma - 1.))); \n                return pressure / (gamma - 1.) + \n                       0.5 * (density * u * u + density * v * v); \n              } \n          } \n\n        case 1: \n          { \n            if (component == 0) \n              return 1.; \n            else if (component == 1) \n              return 0.4; \n            else if (component == dim + 1) \n              return 3.097857142857143; \n            else \n              return 0.; \n          } \n\n        default: \n          Assert(false, ExcNotImplemented()); \n          return 0.; \n      } \n  } \n\n//  @sect3{Low-storage explicit Runge--Kutta time integrators}  \n\n// 接下来的几行实现了一些低存储量的Runge--Kutta方法的变体。这些方法有特定的布彻表，系数为 $b_i$ 和 $a_i$ ，如介绍中所示。如同Runge--Kutta方法的惯例，我们可以从这些系数中推导出时间步骤 $c_i = \\sum_{j=1}^{i-2} b_i + a_{i-1}$ 。这种方案的主要优点是每个阶段只需要两个向量，即解的累积部分 $\\mathbf{w}$ （在最后一个阶段后的新时间 $t^{n+1}$ 保持解 $\\mathbf{w}^{n+1}$ ），在各阶段被评估的更新向量 $\\mathbf{r}_i$ ，加上一个向量 $\\mathbf{k}_i$ 来保持算子评估。这样的Runge--Kutta设置减少了内存存储和内存访问。由于内存带宽通常是现代硬件上的性能限制因素，当微分算子的评估得到很好的优化时，性能可以比标准的时间积分器得到改善。考虑到传统的Runge--Kutta方案可能允许稍大的时间步长，因为更多的自由参数可以获得更好的稳定性，这一点也是真实的。\n\n// 在本教程中，我们集中讨论Kennedy, Carpenter和Lewis(2000)文章中定义的低存储方案的几个变体，以及Tselios和Simos(2007)描述的一个变体。还有一大系列的其他方案，可以通过额外的系数集或稍微不同的更新公式来解决。\n\n// 我们为这四种积分器定义了一个单一的类，用上述的枚举来区分。对每个方案，我们再将 $b_i$ 和 $a_i$ 的向量填充到类中的给定变量。\n\n  class LowStorageRungeKuttaIntegrator \n  { \n  public: \n    LowStorageRungeKuttaIntegrator(const LowStorageRungeKuttaScheme scheme) \n    { \n      TimeStepping::runge_kutta_method lsrk; \n\n// 首先是Kennedy等人（2000）提出的三阶方案。虽然它的稳定区域比其他方案小得多，但它只涉及三个阶段，所以在每个阶段的工作方面很有竞争力。\n\n      switch (scheme) \n        { \n          case stage_3_order_3: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE3_ORDER3; \n              break; \n            } \n\n// 下一个方案是四阶的五级方案，同样在Kennedy等人（2000）的论文中定义。\n\n          case stage_5_order_4: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE5_ORDER4; \n              break; \n            } \n\n// 下面这个七级和四阶的方案已经明确地推导出用于声学问题。它在四阶方案中兼顾了虚特征值的精度，并结合了一个大的稳定区域。由于DG方案在最高频率之间是耗散的，这不一定转化为每级可能的最高时间步长。在本教程方案的背景下，数值通量在耗散中起着至关重要的作用，因此也是最大的稳定时间步长。对于修改后的Lax--Friedrichs通量，如果只考虑稳定性，该方案在每级步长方面与`stage_5_order_4`方案相似，但对于HLL通量来说，效率稍低。\n\n          case stage_7_order_4: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE7_ORDER4; \n              break; \n            } \n\n// 这里包括的最后一个方案是Kennedy等人（2000）的五阶九级方案。它是这里使用的方案中最精确的，但是较高的精度牺牲了一些稳定性，所以每级的归一化步长比四阶方案要小。\n\n          case stage_9_order_5: \n            { \n              lsrk = TimeStepping::LOW_STORAGE_RK_STAGE9_ORDER5; \n              break; \n            } \n\n          default: \n            AssertThrow(false, ExcNotImplemented()); \n        } \n      TimeStepping::LowStorageRungeKutta< \n        LinearAlgebra::distributed::Vector<Number>> \n        rk_integrator(lsrk); \n      rk_integrator.get_coefficients(ai, bi, ci); \n    } \n\n    unsigned int n_stages() const \n    { \n      return bi.size(); \n    } \n\n// 时间积分器的主要功能是通过阶段，评估算子，为下一次评估准备  $\\mathbf{r}_i$  矢量，并更新解决方案矢量  $\\mathbf{w}$  。我们把工作交给所涉及的`pde_operator`，以便能够把Runge--Kutta设置的矢量操作与微分算子的评估合并起来，以获得更好的性能，所以我们在这里所做的就是委托矢量和系数。\n\n// 我们单独调用第一阶段的算子，因为我们需要稍微修改一下那里的参数。我们从旧的解决方案 $\\mathbf{w}^n$ 而不是 $\\mathbf r_i$ 向量中评估解决方案，所以第一个参数是`solution`。我们在这里让阶段向量 $\\mathbf{r}_i$ 也持有评估的临时结果，因为它在其他情况下不会被使用。对于所有后续阶段，我们使用向量`vec_ki`作为第二个向量参数来存储运算符的求值结果。最后，当我们到了最后一个阶段，我们必须跳过对向量 $\\mathbf{r}_{s+1}$ 的计算，因为没有系数 $a_s$ 可用（也不会用到）。\n\n    template <typename VectorType, typename Operator> \n    void perform_time_step(const Operator &pde_operator, \n                           const double    current_time, \n                           const double    time_step, \n                           VectorType &    solution, \n                           VectorType &    vec_ri, \n                           VectorType &    vec_ki) const \n    { \n      AssertDimension(ai.size() + 1, bi.size()); \n\n      pde_operator.perform_stage(current_time, \n                                 bi[0] * time_step, \n                                 ai[0] * time_step, \n                                 solution, \n                                 vec_ri, \n                                 solution, \n                                 vec_ri); \n\n      for (unsigned int stage = 1; stage < bi.size(); ++stage) \n        { \n          const double c_i = ci[stage]; \n          pde_operator.perform_stage(current_time + c_i * time_step, \n                                     bi[stage] * time_step, \n                                     (stage == bi.size() - 1 ? \n                                        0 : \n                                        ai[stage] * time_step), \n                                     vec_ri, \n                                     vec_ki, \n                                     solution, \n                                     vec_ri); \n        } \n    } \n\n  private: \n    std::vector<double> bi; \n    std::vector<double> ai; \n    std::vector<double> ci; \n  }; \n\n//  @sect3{Implementation of point-wise operations of the Euler equations}  \n\n// 在下面的函数中，我们实现了与欧拉方程有关的各种特定问题的运算。每个函数都作用于我们在解向量中持有的守恒变量向量 $[\\rho, \\rho\\mathbf{u}, E]$ ，并计算各种派生量。\n\n// 首先是速度的计算，我们从动量变量 $\\rho \\mathbf{u}$ 除以 $\\rho$ 得出。这里需要注意的是，我们用关键字`DEAL_II_ALWAYS_INLINE`来装饰所有这些函数。这是一个特殊的宏，映射到一个编译器专用的关键字，告诉编译器永远不要为这些函数创建一个函数调用，而是将实现<a href=\"https:en.wikipedia.org/wiki/Inline_function\">inline</a>移到它们被调用的地方。这对性能至关重要，因为我们对其中一些函数的调用达到了几百万甚至几十亿次。例如，我们既使用速度来计算通量，也使用速度来计算压力，而这两个地方都要在每个单元的每个正交点进行评估。确保这些函数是内联的，不仅可以确保处理器不必执行跳转指令进入函数（以及相应的返回跳转），而且编译器可以在调用函数的地方之后的代码中重新使用一个函数的上下文的中间信息。(我们注意到，编译器通常很善于自己找出哪些函数要内联。这里有一个地方，编译器可能是自己想出来的，也可能不是，但我们可以肯定的是，内联是一种胜利。)\n\n// 我们应用的另一个技巧是为反密度设置一个单独的变量  $\\frac{1}{\\rho}$  。这使得编译器只对通量进行一次除法，尽管除法在多个地方使用。由于除法的费用大约是乘法或加法的10到20倍，避免多余的除法对性能至关重要。我们注意到，由于四舍五入的影响，在浮点运算中，先取反数，后与之相乘并不等同于除法，所以编译器不允许用标准的优化标志来交换一种方式。然而，以正确的方式编写代码也不是特别困难。\n\n// 总而言之，所选择的总是内联和仔细定义昂贵的算术运算的策略使我们能够写出紧凑的代码，而不需要将所有的中间结果传递出去，尽管要确保代码映射到优秀的机器码。\n\n  template <int dim, typename Number> \n  inline DEAL_II_ALWAYS_INLINE // \n    Tensor<1, dim, Number> \n    euler_velocity(const Tensor<1, dim + 2, Number> &conserved_variables) \n  { \n    const Number inverse_density = Number(1.) / conserved_variables[0]; \n\n    Tensor<1, dim, Number> velocity; \n    for (unsigned int d = 0; d < dim; ++d) \n      velocity[d] = conserved_variables[1 + d] * inverse_density; \n\n    return velocity; \n  } \n\n// 下一个函数从保守变量的矢量中计算压力，使用公式  $p = (\\gamma - 1) \\left(E - \\frac 12 \\rho \\mathbf{u}\\cdot \\mathbf{u}\\right)$  。如上所述，我们使用来自`euler_velocity()`函数的速度。注意，我们需要在这里指定第一个模板参数`dim`，因为编译器无法从张量的参数中推导出它，而第二个参数（数字类型）可以自动推导出来。\n\n  template <int dim, typename Number> \n  inline DEAL_II_ALWAYS_INLINE // \n    Number \n    euler_pressure(const Tensor<1, dim + 2, Number> &conserved_variables) \n  { \n    const Tensor<1, dim, Number> velocity = \n      euler_velocity<dim>(conserved_variables); \n\n    Number rho_u_dot_u = conserved_variables[1] * velocity[0]; \n    for (unsigned int d = 1; d < dim; ++d) \n      rho_u_dot_u += conserved_variables[1 + d] * velocity[d]; \n\n    return (gamma - 1.) * (conserved_variables[dim + 1] - 0.5 * rho_u_dot_u); \n  } \n\n// 这里是欧拉通量函数的定义，也就是实际方程的定义。考虑到速度和压力（编译器的优化将确保只做一次），考虑到介绍中所说的方程，这是直截了当的。\n\n  template <int dim, typename Number> \n  inline DEAL_II_ALWAYS_INLINE // \n    Tensor<1, dim + 2, Tensor<1, dim, Number>> \n    euler_flux(const Tensor<1, dim + 2, Number> &conserved_variables) \n  { \n    const Tensor<1, dim, Number> velocity = \n      euler_velocity<dim>(conserved_variables); \n    const Number pressure = euler_pressure<dim>(conserved_variables); \n\n    Tensor<1, dim + 2, Tensor<1, dim, Number>> flux; \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        flux[0][d] = conserved_variables[1 + d]; \n        for (unsigned int e = 0; e < dim; ++e) \n          flux[e + 1][d] = conserved_variables[e + 1] * velocity[d]; \n        flux[d + 1][d] += pressure; \n        flux[dim + 1][d] = \n          velocity[d] * (conserved_variables[dim + 1] + pressure); \n      } \n\n    return flux; \n  } \n\n// 接下来的这个函数是一个简化数值通量实现的助手，它实现了一个张量的张量（具有大小为`dim + 2`的非标准外维，所以deal.II的张量类提供的标准重载在此不适用）与另一个相同内维的张量的作用，即一个矩阵-向量积。\n\n  template <int n_components, int dim, typename Number> \n  inline DEAL_II_ALWAYS_INLINE // \n    Tensor<1, n_components, Number> \n    operator*(const Tensor<1, n_components, Tensor<1, dim, Number>> &matrix, \n              const Tensor<1, dim, Number> &                         vector) \n  { \n    Tensor<1, n_components, Number> result; \n    for (unsigned int d = 0; d < n_components; ++d) \n      result[d] = matrix[d] * vector; \n    return result; \n  } \n\n// 这个函数实现了数值通量（黎曼求解器）。它从一个界面的两边获得状态，并获得法向量，从解的一边  $\\mathbf{w}^-$  向解  $\\mathbf{w}^+$  的方向。在依赖片断恒定数据的有限体积方法中，数值通量是核心成分，因为它是唯一输入物理信息的地方。在DG方法中，由于元素内部的多项式和那里使用的物理通量，数值通量就不那么核心了。由于在连续解的极限中，两边的数值一致的高阶插值，数值通量可以被看作是对两边解的跳跃的控制，以弱化连续性。必须认识到，在存在冲击的情况下，仅靠数值通量是无法稳定高阶DG方法的，因此任何DG方法都必须与进一步的冲击捕捉技术相结合，以处理这些情况。在本教程中，我们将重点讨论欧拉方程在没有强不连续的亚声速体系中的波状解，我们的基本方案已经足够了。\n\n// 尽管如此，数值通量对整个方案的数值耗散起着决定性作用，并影响到显式Runge-Kutta方法的可接受的时间步长。我们考虑两种选择，一种是改良的Lax-Friedrichs方案，另一种是广泛使用的Harten-Lax-van Leer（HLL）通量。对于这两种方案，我们首先需要得到界面两边的速度和压力，并评估物理欧拉通量。\n\n// 对于局部Lax--Friedrichs通量，其定义是 $\\hat{\\mathbf{F}}\n//  =\\frac{\\mathbf{F}(\\mathbf{w}^-)+\\mathbf{F}(\\mathbf{w}^+)}{2} +\n//  \\frac{\\lambda}{2}\\left[\\mathbf{w}^--\\mathbf{w}^+\\right]\\otimes\n//  \\mathbf{n^-}$  ，其中因子 $\\lambda =\n//  \\max\\left(\\|\\mathbf{u}^-\\|+c^-, \\|\\mathbf{u}^+\\|+c^+\\right)$ 给出了最大波速， $c = \\sqrt{\\gamma p / \\rho}$ 是音速。在这里，考虑到通量对解的影响很小，为了计算效率的原因，我们选择了该表达式的两个修改。对于上述因子 $\\lambda$ 的定义，我们需要取四个平方根，两个用于两个速度规范，两个用于两侧的声速。因此，第一个修改是宁可使用 $\\sqrt{\\|\\mathbf{u}\\|^2+c^2}$ 作为最大速度的估计（如介绍中所示，它与实际最大速度最多相差2倍）。这使我们能够从最大速度中提取平方根，并且只需进行一次平方根计算就可以了。第二个修改是进一步放宽参数 $\\lambda$ --它越小，耗散系数就越小（与 $\\mathbf{w}$ 的跳跃相乘，最终可能导致耗散变小或变大）。这使得我们可以用更大的时间步长将频谱纳入显式Runge--Kutta积分器的稳定区域。然而，我们不能使耗散太小，因为否则假想的特征值会越来越大。最后，目前的保守公式在 $\\lambda\\to 0$ 的极限中不是能量稳定的，因为它不是偏斜对称的，在这种情况下需要额外的措施，如分裂形式的DG方案。\n\n// 对于HLL通量，我们遵循文献中的公式，通过一个参数 $s$ 引入Lax--Friedrichs的两个状态的额外加权。它是由欧拉方程的物理传输方向得出的，以当前的速度方向和声速为准。对于速度，我们在此选择一个简单的算术平均数，这对危险情况和材料参数的适度跳跃是足够的。\n\n// 由于数值通量在弱形式下是与法向量相乘的，因此我们对方程中的所有项都用法向量来乘以结果。在这些乘法中，上面定义的 \"操作符*\"可以实现类似于数学定义的紧凑符号。\n\n// 在这个函数和下面的函数中，我们使用变量后缀`_m`和`_p`来表示从 $\\mathbf{w}^-$ 和 $\\mathbf{w}^+$ 得出的量，即在观察相邻单元时相对于当前单元的 \"这里 \"和 \"那里 \"的数值。\n\n  template <int dim, typename Number> \n  inline DEAL_II_ALWAYS_INLINE // \n    Tensor<1, dim + 2, Number> \n    euler_numerical_flux(const Tensor<1, dim + 2, Number> &u_m, \n                         const Tensor<1, dim + 2, Number> &u_p, \n                         const Tensor<1, dim, Number> &    normal) \n  { \n    const auto velocity_m = euler_velocity<dim>(u_m); \n    const auto velocity_p = euler_velocity<dim>(u_p); \n\n    const auto pressure_m = euler_pressure<dim>(u_m); \n    const auto pressure_p = euler_pressure<dim>(u_p); \n\n    const auto flux_m = euler_flux<dim>(u_m); \n    const auto flux_p = euler_flux<dim>(u_p); \n\n    switch (numerical_flux_type) \n      { \n        case lax_friedrichs_modified: \n          { \n            const auto lambda = \n              0.5 * std::sqrt(std::max(velocity_p.norm_square() + \n                                         gamma * pressure_p * (1. / u_p[0]), \n                                       velocity_m.norm_square() + \n                                         gamma * pressure_m * (1. / u_m[0]))); \n\n            return 0.5 * (flux_m * normal + flux_p * normal) + \n                   0.5 * lambda * (u_m - u_p); \n          } \n\n        case harten_lax_vanleer: \n          { \n            const auto avg_velocity_normal = \n              0.5 * ((velocity_m + velocity_p) * normal); \n            const auto   avg_c = std::sqrt(std::abs( \n              0.5 * gamma * \n              (pressure_p * (1. / u_p[0]) + pressure_m * (1. / u_m[0])))); \n            const Number s_pos = \n              std::max(Number(), avg_velocity_normal + avg_c); \n            const Number s_neg = \n              std::min(Number(), avg_velocity_normal - avg_c); \n            const Number inverse_s = Number(1.) / (s_pos - s_neg); \n\n            return inverse_s * \n                   ((s_pos * (flux_m * normal) - s_neg * (flux_p * normal)) - \n                    s_pos * s_neg * (u_m - u_p)); \n          } \n\n        default: \n          { \n            Assert(false, ExcNotImplemented()); \n            return {}; \n          } \n      } \n  } \n\n// 这个函数和下一个函数是辅助函数，提供紧凑的评估调用，因为多个点通过VectorizedArray参数被分批放在一起（详见 step-37 教程）。这个函数用于亚音速外流边界条件，我们需要将能量分量设置为一个规定值。下一个函数请求所有分量上的解，用于流入边界，其中解的所有分量都被设置。\n\n  template <int dim, typename Number> \n  VectorizedArray<Number> \n  evaluate_function(const Function<dim> &                      function, \n                    const Point<dim, VectorizedArray<Number>> &p_vectorized, \n                    const unsigned int                         component) \n  { \n    VectorizedArray<Number> result; \n    for (unsigned int v = 0; v < VectorizedArray<Number>::size(); ++v) \n      { \n        Point<dim> p; \n        for (unsigned int d = 0; d < dim; ++d) \n          p[d] = p_vectorized[d][v]; \n        result[v] = function.value(p, component); \n      } \n    return result; \n  } \n\n  template <int dim, typename Number, int n_components = dim + 2> \n  Tensor<1, n_components, VectorizedArray<Number>> \n  evaluate_function(const Function<dim> &                      function, \n                    const Point<dim, VectorizedArray<Number>> &p_vectorized) \n  { \n    AssertDimension(function.n_components, n_components); \n    Tensor<1, n_components, VectorizedArray<Number>> result; \n    for (unsigned int v = 0; v < VectorizedArray<Number>::size(); ++v) \n      { \n        Point<dim> p; \n        for (unsigned int d = 0; d < dim; ++d) \n          p[d] = p_vectorized[d][v]; \n        for (unsigned int d = 0; d < n_components; ++d) \n          result[d][v] = function.value(p, d); \n      } \n    return result; \n  } \n\n//  @sect3{The EulerOperation class}  \n\n// 这个类实现了欧拉问题的评估器，类似于  step-37  或  step-59  的 `LaplaceOperator` 类。由于本算子是非线性的，不需要矩阵接口（交给预处理程序），我们跳过了无矩阵算子中的各种`vmult`函数，只实现了`apply`函数以及`apply`与上述低存储Runge-Kutta时间积分器所需的矢量更新的组合（称为`perform_stage`）。此外，我们还增加了三个涉及无矩阵例程的额外函数，即一个是根据元素中的速度和声速计算时间步长的估计值（与实际时间步长的Courant数相结合），一个是解的投影（专门针对DG情况的 VectorTools::project() ），还有一个是计算与可能的分析解或与某些背景状态的规范的误差。\n\n// 该课的其余部分与其他无矩阵教程相似。正如介绍中所讨论的，我们提供了几个函数，允许用户在由 types::boundary_id 变量标记的领域边界的不同部分传递各种形式的边界条件，以及可能的体力。\n\n  template <int dim, int degree, int n_points_1d> \n  class EulerOperator \n  { \n  public: \n    static constexpr unsigned int n_quadrature_points_1d = n_points_1d; \n\n    EulerOperator(TimerOutput &timer_output); \n\n    void reinit(const Mapping<dim> &   mapping, \n                const DoFHandler<dim> &dof_handler); \n\n    void set_inflow_boundary(const types::boundary_id       boundary_id, \n                             std::unique_ptr<Function<dim>> inflow_function); \n\n    void set_subsonic_outflow_boundary( \n      const types::boundary_id       boundary_id, \n      std::unique_ptr<Function<dim>> outflow_energy); \n\n    void set_wall_boundary(const types::boundary_id boundary_id); \n\n    void set_body_force(std::unique_ptr<Function<dim>> body_force); \n\n    void apply(const double                                      current_time, \n               const LinearAlgebra::distributed::Vector<Number> &src, \n               LinearAlgebra::distributed::Vector<Number> &      dst) const; \n\n    void \n    perform_stage(const Number cur_time, \n                  const Number factor_solution, \n                  const Number factor_ai, \n                  const LinearAlgebra::distributed::Vector<Number> &current_ri, \n                  LinearAlgebra::distributed::Vector<Number> &      vec_ki, \n                  LinearAlgebra::distributed::Vector<Number> &      solution, \n                  LinearAlgebra::distributed::Vector<Number> &next_ri) const; \n\n    void project(const Function<dim> &                       function, \n                 LinearAlgebra::distributed::Vector<Number> &solution) const; \n\n    std::array<double, 3> compute_errors( \n      const Function<dim> &                             function, \n      const LinearAlgebra::distributed::Vector<Number> &solution) const; \n\n    double compute_cell_transport_speed( \n      const LinearAlgebra::distributed::Vector<Number> &solution) const; \n\n    void \n    initialize_vector(LinearAlgebra::distributed::Vector<Number> &vector) const; \n\n  private: \n    MatrixFree<dim, Number> data; \n\n    TimerOutput &timer; \n\n    std::map<types::boundary_id, std::unique_ptr<Function<dim>>> \n      inflow_boundaries; \n    std::map<types::boundary_id, std::unique_ptr<Function<dim>>> \n                                   subsonic_outflow_boundaries; \n    std::set<types::boundary_id>   wall_boundaries; \n    std::unique_ptr<Function<dim>> body_force; \n\n    void local_apply_inverse_mass_matrix( \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    void local_apply_cell( \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    void local_apply_face( \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> &     face_range) const; \n\n    void local_apply_boundary_face( \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> &     face_range) const; \n  }; \n\n  template <int dim, int degree, int n_points_1d> \n  EulerOperator<dim, degree, n_points_1d>::EulerOperator(TimerOutput &timer) \n    : timer(timer) \n  {} \n\n// 对于欧拉算子的初始化，我们设置了类中包含的MatrixFree变量。这可以通过给定一个描述可能的弯曲边界的映射以及一个描述自由度的DoFHandler对象来完成。由于我们在这个教程程序中使用的是不连续的Galerkin离散化，没有对解场施加强烈的约束，所以我们不需要传入AffineConstraints对象，而是使用一个假的来构造。关于正交，我们要选择两种不同的方式来计算基础积分。第一种是灵活的，基于模板参数`n_points_1d`（将被分配到本文件顶部指定的`n_q_points_1d`值）。更精确的积分是必要的，以避免由于欧拉算子中的可变系数而产生的混叠问题。第二个不太精确的正交公式是一个基于`fe_degree+1`的严密公式，需要用于反质量矩阵。虽然该公式只在仿生元素形状上提供了精确的反，而在变形元素上则没有，但它可以通过张量积技术快速反转质量矩阵，这对于确保整体的最佳计算效率是必要的。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::reinit( \n    const Mapping<dim> &   mapping, \n    const DoFHandler<dim> &dof_handler) \n  { \n    const std::vector<const DoFHandler<dim> *> dof_handlers = {&dof_handler}; \n    const AffineConstraints<double>            dummy; \n    const std::vector<const AffineConstraints<double> *> constraints = {&dummy}; \n    const std::vector<Quadrature<1>> quadratures = {QGauss<1>(n_q_points_1d), \n                                                    QGauss<1>(fe_degree + 1)}; \n\n    typename MatrixFree<dim, Number>::AdditionalData additional_data; \n    additional_data.mapping_update_flags = \n      (update_gradients | update_JxW_values | update_quadrature_points | \n       update_values); \n    additional_data.mapping_update_flags_inner_faces = \n      (update_JxW_values | update_quadrature_points | update_normal_vectors | \n       update_values); \n    additional_data.mapping_update_flags_boundary_faces = \n      (update_JxW_values | update_quadrature_points | update_normal_vectors | \n       update_values); \n    additional_data.tasks_parallel_scheme = \n      MatrixFree<dim, Number>::AdditionalData::none; \n\n    data.reinit( \n      mapping, dof_handlers, constraints, quadratures, additional_data); \n  } \n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::initialize_vector( \n    LinearAlgebra::distributed::Vector<Number> &vector) const \n  { \n    data.initialize_dof_vector(vector); \n  } \n\n// 随后的四个成员函数是必须从外部调用的，以指定各种类型的边界。对于一个流入的边界，我们必须以密度  $\\rho$  、动量  $\\rho \\mathbf{u}$  和能量  $E$  来指定所有成分。考虑到这些信息，我们将函数与各自的边界ID一起存储在这个类的地图成员变量中。同样，我们对亚音速外流边界（我们也要求一个函数，用来检索能量）和壁面（无穿透）边界进行处理，在壁面上我们施加零法线速度（不需要函数，所以我们只要求边界ID）。对于目前的DG代码来说，边界条件只作为弱形式的一部分被应用（在时间积分期间），设置边界条件的调用可以出现在对这个类的`reinit()`调用之前或之后。这与连续有限元代码不同，在连续有限元代码中，边界条件决定了被送入MatrixFree初始化的AffineConstraints对象的内容，因此需要在无矩阵数据结构的初始化之前设置。\n\n// 在四个函数中的每一个中添加的检查是用来确保边界条件在边界的各个部分是相互排斥的，也就是说，用户不会意外地将一个边界既指定为流入边界，又指定为亚声速流出边界。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::set_inflow_boundary( \n    const types::boundary_id       boundary_id, \n    std::unique_ptr<Function<dim>> inflow_function) \n  { \n    AssertThrow(subsonic_outflow_boundaries.find(boundary_id) == \n                    subsonic_outflow_boundaries.end() && \n                  wall_boundaries.find(boundary_id) == wall_boundaries.end(), \n \n \n \n \n \n                ExcMessage(\"Expected function with dim+2 components\")); \n\n    inflow_boundaries[boundary_id] = std::move(inflow_function); \n  } \n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::set_subsonic_outflow_boundary( \n    const types::boundary_id       boundary_id, \n    std::unique_ptr<Function<dim>> outflow_function) \n  { \n    AssertThrow(inflow_boundaries.find(boundary_id) == \n                    inflow_boundaries.end() && \n                  wall_boundaries.find(boundary_id) == wall_boundaries.end(), \n                ExcMessage(\"You already set the boundary with id \" + \n                           std::to_string(static_cast<int>(boundary_id)) + \n                           \" to another type of boundary before now setting \" + \n                           \"it as subsonic outflow\")); \n    AssertThrow(outflow_function->n_components == dim + 2, \n                ExcMessage(\"Expected function with dim+2 components\")); \n\n    subsonic_outflow_boundaries[boundary_id] = std::move(outflow_function); \n  } \n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::set_wall_boundary( \n    const types::boundary_id boundary_id) \n  { \n    AssertThrow(inflow_boundaries.find(boundary_id) == \n                    inflow_boundaries.end() && \n                  subsonic_outflow_boundaries.find(boundary_id) == \n                    subsonic_outflow_boundaries.end(), \n                ExcMessage(\"You already set the boundary with id \" + \n                           std::to_string(static_cast<int>(boundary_id)) + \n                           \" to another type of boundary before now setting \" + \n                           \"it as wall boundary\")); \n\n    wall_boundaries.insert(boundary_id); \n  } \n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::set_body_force( \n    std::unique_ptr<Function<dim>> body_force) \n  { \n    AssertDimension(body_force->n_components, dim); \n\n    this->body_force = std::move(body_force); \n  } \n\n//  @sect4{Local evaluators}  \n\n// 现在我们开始研究欧拉问题的局部评估器。评估器相对简单，遵循  step-37  、  step-48  或  step-59  中提出的内容。第一个显著的区别是，我们使用的是具有非标准正交点数量的FEE评估。以前我们总是将正交点的数量设置为等于多项式度数加1（确保在仿生元素形状上的精确积分），现在我们将正交点的数量设置为一个单独的变量（例如多项式度数加多项式度数的二分之一或三分之一），以更准确地处理非线性项。由于评估器通过模板参数输入了适当的循环长度，并在变量 FEEvaluation::n_q_points, 中保留了整个单元格的正交点数量，所以我们现在自动操作更精确的公式，而无需进一步修改。\n\n// 第二个区别是由于我们现在评估的是一个多分量系统，而不是之前考虑的标量系统。无矩阵框架提供了几种方法来处理多成分的情况。这里显示的变体是利用一个嵌入了多个分量的FEEvaluation对象，由第四个模板参数`dim + 2`指定欧拉系统中的分量。因此， FEEvaluation::get_value() 的返回类型不再是一个标量（这将返回一个VectorizedArray类型，收集几个元素的数据），而是一个`dim+2`组件的张量。该功能与标量的情况类似；它由一个基类的模板专业化处理，称为FEEvaluationAccess。另一个变体是使用几个FEEvaluation对象，一个标量对象用于密度，一个带`dim`分量的矢量值对象用于动量，另一个标量评价器用于能量。为了确保这些分量指向解决方案的正确部分，FEEvaluation的构造函数在所需的MatrixFree字段之后需要三个可选的整数参数，即多DoFHandler系统的DoFHandler编号（默认取第一个），如果有多个Quadrature对象，则取正交点的编号（见下文），以及作为第三个参数的矢量系统中的分量。由于我们有一个单一的矢量来表示所有的分量，我们将使用第三个参数，并将其设置为`0`表示密度，`1`表示矢量值的动量，`dim+1`表示能量槽。然后FEEvaluation在 FEEvaluationBase::read_dof_values() 和 FEEvaluation::distributed_local_to_global() 或更紧凑的 FEEvaluation::gather_evaluate() 和 FEEvaluation::integrate_scatter() 调用中挑选适当的解矢量子范围。\n\n// 当涉及到身体力向量的评估时，为了效率，我们区分了两种情况。如果我们有一个常数函数（源自 Functions::ConstantFunction), ），我们可以在正交点的循环外预先计算出数值，并简单地在所有地方使用该数值。对于一个更通用的函数，我们反而需要调用我们上面提供的`evaluate_function()`方法；这个路径更昂贵，因为我们需要访问与正交点数据有关的内存。\n\n// 其余部分沿用其他教程的程序。由于我们已经在单独的`euler_flux()`函数中实现了欧拉方程的所有物理学，我们在这里所要做的就是给定在正交点评估的当前解，由`phi.get_value(q)`返回，并告诉FEEvaluation对象，通过形状函数的梯度（这是一个外部`dim+2`分量的张量，每个张量持有一个`dim`分量的 $x,y,z$  ] 欧拉通量的分量）。) 最后值得一提的是，在我们得到一个外部函数的情况下，我们通过测试函数`phi.submit_value()`的值来排队测试数据的顺序。我们必须在调用`phi.get_value(q)'之后进行，因为`get_value()'（读取解决方案）和`submit_value()'（排队等待测试函数的乘法和正交点的求和）访问同一个底层数据域。这里很容易实现没有临时变量`w_q`，因为值和梯度之间没有混合。对于更复杂的设置，必须首先复制出例如正交点的值和梯度，然后通过 FEEvaluationBase::submit_value() 和 FEEvaluationBase::submit_gradient(). 再次排列结果。\n\n// 作为最后的说明，我们提到我们没有使用这个函数的第一个MatrixFree参数，这是一个来自 MatrixFree::loop(). 的回调，接口规定了现在的参数列表，但是由于我们在一个成员函数中，MatrixFree对象已经可以作为`data`变量，我们坚持使用，以避免混淆。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::local_apply_cell( \n    const MatrixFree<dim, Number> &, \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, degree, n_points_1d, dim + 2, Number> phi(data); \n\n    Tensor<1, dim, VectorizedArray<Number>> constant_body_force; \n    const Functions::ConstantFunction<dim> *constant_function = \n      dynamic_cast<Functions::ConstantFunction<dim> *>(body_force.get()); \n\n    if (constant_function) \n      constant_body_force = evaluate_function<dim, Number, dim>( \n        *constant_function, Point<dim, VectorizedArray<Number>>()); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        phi.reinit(cell); \n        phi.gather_evaluate(src, EvaluationFlags::values); \n\n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            const auto w_q = phi.get_value(q); \n            phi.submit_gradient(euler_flux<dim>(w_q), q); \n            if (body_force.get() != nullptr) \n              { \n                const Tensor<1, dim, VectorizedArray<Number>> force = \n                  constant_function ? constant_body_force : \n                                      evaluate_function<dim, Number, dim>( \n                                        *body_force, phi.quadrature_point(q)); \n\n                Tensor<1, dim + 2, VectorizedArray<Number>> forcing; \n                for (unsigned int d = 0; d < dim; ++d) \n                  forcing[d + 1] = w_q[0] * force[d]; \n                for (unsigned int d = 0; d < dim; ++d) \n                  forcing[dim + 1] += force[d] * w_q[d + 1]; \n\n                phi.submit_value(forcing, q); \n              } \n          } \n\n        phi.integrate_scatter(((body_force.get() != nullptr) ? \n                                 EvaluationFlags::values : \n                                 EvaluationFlags::nothing) | \n                                EvaluationFlags::gradients, \n                              dst); \n      } \n  } \n\n// 下一个函数涉及到内部面的积分计算，在这里我们需要与面相邻的两个单元的评估器。我们将变量`phi_m`与解分量 $\\mathbf{w}^-$ 相关联，将变量`phi_p`与解分量 $\\mathbf{w}^+$ 相关联。我们在FEFaceEvaluation的构造函数中通过第二个参数来区分两边，`true`表示内侧，`false`表示外侧，内侧和外侧表示相对于法向量的方向。\n\n// 注意调用 FEFaceEvaluation::gather_evaluate() 和 FEFaceEvaluation::integrate_scatter() 结合了对向量的访问和因式分解部分。这种合并操作不仅节省了一行代码，而且还包含了一个重要的优化。鉴于我们在Gauss-Lobatto正交公式的点上使用拉格朗日多项式的节点基础，在每个面上只有 $(p+1)^{d-1}$ 的基础函数评估为非零。因此，评估器只访问了向量中的必要数据，而跳过了乘以零的部分。如果我们首先读取向量，我们就需要从向量中加载所有的数据，因为孤立的调用不知道后续操作中需要哪些数据。如果随后的 FEFaceEvaluation::evaluate() 调用要求数值和导数，确实需要每个分量的所有 $(p+1)^d$ 向量条目，因为所有基函数的法向导数都是非零的。\n\n// 评价器的参数以及程序与单元评价相似。由于非线性项的存在，我们再次使用更精确的（过度）积分方案，指定为列表中第三个模板参数。在正交点上，我们再去找我们的自由函数来计算数值通量。它从两边（即 $\\mathbf{w}^-$ 和 $\\mathbf{w}^+$ ）接收在正交点评估的解决方案，以及到减去一边的法向量。正如上面所解释的，数值通量已经乘以来自减法侧的法向量了。我们需要转换符号，因为在引言中得出的弱形式中，边界项带有一个减号。然后，通量被排队在减号和加号上进行测试，由于加号上的法向量与减号上的法向量正好相反，所以要调换符号。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::local_apply_face( \n    const MatrixFree<dim, Number> &, \n    LinearAlgebra::distributed::Vector<Number> &      dst, \n    const LinearAlgebra::distributed::Vector<Number> &src, \n    const std::pair<unsigned int, unsigned int> &     face_range) const \n  { \n    FEFaceEvaluation<dim, degree, n_points_1d, dim + 2, Number> phi_m(data, \n                                                                      true); \n    FEFaceEvaluation<dim, degree, n_points_1d, dim + 2, Number> phi_p(data, \n                                                                      false); \n\n    for (unsigned int face = face_range.first; face < face_range.second; ++face) \n      { \n        phi_p.reinit(face); \n        phi_p.gather_evaluate(src, EvaluationFlags::values); \n\n        phi_m.reinit(face); \n        phi_m.gather_evaluate(src, EvaluationFlags::values); \n\n        for (unsigned int q = 0; q < phi_m.n_q_points; ++q) \n          { \n            const auto numerical_flux = \n              euler_numerical_flux<dim>(phi_m.get_value(q), \n                                        phi_p.get_value(q), \n                                        phi_m.get_normal_vector(q)); \n            phi_m.submit_value(-numerical_flux, q); \n            phi_p.submit_value(numerical_flux, q); \n          } \n\n        phi_p.integrate_scatter(EvaluationFlags::values, dst); \n        phi_m.integrate_scatter(EvaluationFlags::values, dst); \n      } \n  } \n\n// 对于位于边界的面，我们需要施加适当的边界条件。在这个教程程序中，我们实现了上述的四种情况。第五种情况，即超音速流出条件，将在下面的 \"结果 \"部分讨论）。不连续的Galerkin方法对边界条件的施加不是作为约束条件，而只是弱化。因此，各种条件是通过找到一个适当的<i>exterior</i>量 $\\mathbf{w}^+$ 来施加的，然后将其交给也用于内部面的数值通量函数。实质上，我们在域外 \"假装 \"一个状态，如果那是现实，PDE的解将满足我们想要的边界条件。\n\n// 对于墙的边界，我们需要对动量变量施加一个无正态通量的条件，而对于密度和能量，我们使用的是诺伊曼条件  $\\rho^+ = \\rho^-$  和  $E^+ = E^-$  。为了实现无正态通量条件，我们将外部数值设定为内部数值，并减去墙面法线方向，即法线矢量方向上的速度的2倍。\n\n// 对于流入边界，我们简单地将给定的Dirichlet数据 $\\mathbf{w}_\\mathrm{D}$ 作为边界值。另一种方法是使用 $\\mathbf{w}^+ = -\\mathbf{w}^- + 2 \\mathbf{w}_\\mathrm{D}$  ，即所谓的镜像原理。\n\n// 强加外流本质上是一个诺伊曼条件，即设定  $\\mathbf{w}^+ = \\mathbf{w}^-$  。对于亚声速流出的情况，我们仍然需要强加一个能量值，我们从各自的函数中得出这个值。对于<i>backflow</i>的情况，即在Neumann部分有动量通入域的情况，需要一个特殊的步骤。根据文献（这一事实可以通过适当的能量论证得出），我们必须切换到流入部分的通量的另一个变体，见Gravemeier, Comerford, Yoshihara, Ismail, Wall, \"A novel formulation for Neumann inflow conditions in biomechanics\", Int. J. Numer. Meth. 生物医学。Eng., vol. 28 (2012). 这里，动量项需要再次添加，这相当于去除动量变量上的通量贡献。我们在后处理步骤中这样做，而且只适用于我们都处于外流边界且法向量与动量（或等同于速度）之间的点积为负的情况。由于我们在SIMD矢量化中一次处理多个正交点的数据，这里需要明确地在SIMD数组的条目上循环。\n\n// 在下面的实现中，我们在正交点的层面上检查各种类型的边界。当然，我们也可以将决定权移出正交点循环，将整个面孔视为同类，这就避免了在正交点的内循环中进行一些地图/集合的查找。然而，效率的损失并不明显，所以我们在这里选择了更简单的代码。还要注意的是，最后的 \"else \"子句会捕捉到这样的情况，即边界的某些部分没有通过 `EulerOperator::set_..._boundary(...)`. 分配任何边界条件。\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::local_apply_boundary_face( \n    const MatrixFree<dim, Number> &, \n    LinearAlgebra::distributed::Vector<Number> &      dst, \n    const LinearAlgebra::distributed::Vector<Number> &src, \n    const std::pair<unsigned int, unsigned int> &     face_range) const \n  { \n    FEFaceEvaluation<dim, degree, n_points_1d, dim + 2, Number> phi(data, true); \n\n    for (unsigned int face = face_range.first; face < face_range.second; ++face) \n      { \n        phi.reinit(face); \n        phi.gather_evaluate(src, EvaluationFlags::values); \n\n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            const auto w_m    = phi.get_value(q); \n            const auto normal = phi.get_normal_vector(q); \n\n            auto rho_u_dot_n = w_m[1] * normal[0]; \n            for (unsigned int d = 1; d < dim; ++d) \n              rho_u_dot_n += w_m[1 + d] * normal[d]; \n\n            bool at_outflow = false; \n\n            Tensor<1, dim + 2, VectorizedArray<Number>> w_p; \n            const auto boundary_id = data.get_boundary_id(face); \n            if (wall_boundaries.find(boundary_id) != wall_boundaries.end()) \n              { \n                w_p[0] = w_m[0]; \n                for (unsigned int d = 0; d < dim; ++d) \n                  w_p[d + 1] = w_m[d + 1] - 2. * rho_u_dot_n * normal[d]; \n                w_p[dim + 1] = w_m[dim + 1]; \n              } \n            else if (inflow_boundaries.find(boundary_id) != \n                     inflow_boundaries.end()) \n              w_p = \n                evaluate_function(*inflow_boundaries.find(boundary_id)->second, \n                                  phi.quadrature_point(q)); \n            else if (subsonic_outflow_boundaries.find(boundary_id) != \n                     subsonic_outflow_boundaries.end()) \n              { \n                w_p          = w_m; \n                w_p[dim + 1] = evaluate_function( \n                  *subsonic_outflow_boundaries.find(boundary_id)->second, \n                  phi.quadrature_point(q), \n                  dim + 1); \n                at_outflow = true; \n              } \n            else \n              AssertThrow(false, \n                          ExcMessage(\"Unknown boundary id, did \" \n                                     \"you set a boundary condition for \" \n                                     \"this part of the domain boundary?\")); \n\n            auto flux = euler_numerical_flux<dim>(w_m, w_p, normal); \n\n            if (at_outflow) \n              for (unsigned int v = 0; v < VectorizedArray<Number>::size(); ++v) \n                { \n                  if (rho_u_dot_n[v] < -1e-12) \n                    for (unsigned int d = 0; d < dim; ++d) \n                      flux[d + 1][v] = 0.; \n                } \n\n            phi.submit_value(-flux, q); \n          } \n\n        phi.integrate_scatter(EvaluationFlags::values, dst); \n      } \n  } \n\n// 下一个函数实现了质量矩阵的逆运算。在介绍中已经广泛讨论了算法和原理，所以我们在这里只讨论 MatrixFreeOperators::CellwiseInverseMassMatrix 类的技术问题。它所做的操作与质量矩阵的正向评估类似，只是使用了不同的插值矩阵，代表逆 $S^{-1}$ 因子。这些代表了从指定的基础（在这种情况下，高斯--洛巴托正交公式点中的拉格朗日基础）到高斯正交公式点中的拉格朗日基础的改变。在后者的基础上，我们可以应用点的逆向`JxW`因子，即正交权重乘以从参考坐标到实坐标的映射的雅各布系数。一旦完成了这一操作，基数将再次变回节点高斯-洛巴托基数。所有这些操作都由下面的 \"apply() \"函数完成。我们需要提供的是要操作的局部场（我们通过一个FEEvaluation对象从全局向量中提取），并将结果写回质量矩阵操作的目标向量。\n\n// 需要注意的一点是，我们在FEEvaluation的构造函数中添加了两个整数参数（可选），第一个是0（在多DoFHandler系统中选择DoFHandler；在这里，我们只有一个），第二个是1，用于进行正交公式选择。由于我们将正交公式0用于非线性项的过度积分，我们使用公式1与默认的 $p+1$ （或变量名称中的`fe_degree+1`）点用于质量矩阵。这导致了对质量矩阵的平方贡献，并确保了精确的积分，正如介绍中所解释的。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::local_apply_inverse_mass_matrix( \n    const MatrixFree<dim, Number> &, \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, degree, degree + 1, dim + 2, Number> phi(data, 0, 1); \n    MatrixFreeOperators::CellwiseInverseMassMatrix<dim, degree, dim + 2, Number> \n      inverse(phi); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        phi.reinit(cell); \n        phi.read_dof_values(src); \n\n        inverse.apply(phi.begin_dof_values(), phi.begin_dof_values()); \n\n        phi.set_dof_values(dst); \n      } \n  } \n\n//  @sect4{The apply() and related functions}  \n\n// 我们现在来到实现欧拉算子整体评估的函数，即 $\\mathcal M^{-1} \\mathcal L(t, \\mathbf{w})$  ，调用上面介绍的局部评估器。这些步骤在前面的代码中应该是清楚的。需要注意的一点是，我们需要调整与边界各部分相关的函数中的时间，以便在边界数据与时间相关的情况下与方程一致。然后，我们调用 MatrixFree::loop() 来执行单元和面的积分，包括在`src`向量中进行必要的ghost数据交换。该函数的第七个参数，\"true\"，指定我们要在开始向其累积积分之前，将 \"dst \"向量作为循环的一部分归零。这个变体比在循环之前明确调用`dst = 0.;`要好，因为归零操作是在矢量的子范围内完成的，其部分是由附近的积分写入的。这加强了数据的定位，并允许缓存，节省了向量数据到主内存的一次往返，提高了性能。循环的最后两个参数决定了哪些数据被交换：由于我们只访问一个面的形状函数的值，这是典型的一阶双曲问题，并且由于我们有一个节点基础，节点位于参考元素表面，我们只需要交换这些部分。这又节省了宝贵的内存带宽。\n\n// 一旦应用了空间算子 $\\mathcal L$ ，我们需要进行第二轮操作，应用反质量矩阵。这里，我们调用 MatrixFree::cell_loop() ，因为只有单元格积分出现。单元循环比全循环更便宜，因为只访问与本地拥有的单元相关的自由度，这只是DG离散化的本地拥有的自由度。因此，这里不需要鬼魂交换。\n\n// 在所有这些函数的周围，我们设置了定时器范围来记录计算时间，以统计各部分的贡献。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::apply( \n    const double                                      current_time, \n    const LinearAlgebra::distributed::Vector<Number> &src, \n    LinearAlgebra::distributed::Vector<Number> &      dst) const \n  { \n    { \n      TimerOutput::Scope t(timer, \"apply - integrals\"); \n\n      for (auto &i : inflow_boundaries) \n        i.second->set_time(current_time); \n      for (auto &i : subsonic_outflow_boundaries) \n        i.second->set_time(current_time); \n\n      data.loop(&EulerOperator::local_apply_cell, \n                &EulerOperator::local_apply_face, \n                &EulerOperator::local_apply_boundary_face, \n                this, \n                dst, \n                src, \n                true, \n                MatrixFree<dim, Number>::DataAccessOnFaces::values, \n                MatrixFree<dim, Number>::DataAccessOnFaces::values); \n    } \n\n    { \n      TimerOutput::Scope t(timer, \"apply - inverse mass\"); \n\n      data.cell_loop(&EulerOperator::local_apply_inverse_mass_matrix, \n                     this, \n                     dst, \n                     dst); \n    } \n  } \n\n// 让我们转到做Runge--Kutta更新的整个阶段的函数。它调用 EulerOperator::apply() ，然后对向量进行一些更新，即`next_ri = solution + factor_ai * k_i`和`solution += factor_solution * k_i`。与其通过向量接口执行这些步骤，我们在这里提出了一个替代策略，在基于缓存的架构上速度更快。由于向量所消耗的内存往往比缓存所能容纳的要大得多，因此数据必须有效地来自缓慢的RAM内存。这种情况可以通过循环融合来改善，即在一次扫描中对`next_ki`和`solution`进行更新。在这种情况下，我们将读取两个向量`rhs`和`solution`并写入`next_ki`和`solution`，而在基线情况下，至少有4次读取和两次写入。在这里，我们更进一步，当质量矩阵反转在向量的某一部分完成后，立即执行循环。  MatrixFree::cell_loop() 提供了一种机制，在单元格的循环第一次接触到一个向量条目之前，附加一个 `std::function` （我们在这里没有使用，但用于例如向量的归零），以及在循环最后接触到一个条目之后，调用第二个 `std::function` 。回调的形式是给定向量上的一个范围（就MPI宇宙中的本地索引编号而言），可以由`local_element()`函数来处理。\n\n// 对于这个第二个回调，我们创建一个lambda，在一个范围内工作，并在这个范围内写入相应的更新。理想情况下，我们会在本地循环之前添加`DEAL_II_OPENMP_SIMD_PRAGMA`，以建议编译器对这个循环进行SIMD并行化（这意味着在实践中我们要确保在循环内部使用的指针的索引范围之间没有重叠，也称为别名）。事实证明，在写这篇文章的时候，GCC 7.2无法编译lambda函数中的OpenMP pragma，所以我们在下面注释了这个pragma。如果你的编译器比较新，你应该可以再次取消注释这些行。\n\n// 注意，当我们不需要更新`next_ri`向量时，我们为最后的Runge--Kutta阶段选择不同的代码路径。这个策略带来了相当大的速度提升。在40核机器上，默认矢量更新时，逆质量矩阵和矢量更新需要60%以上的计算时间，而在更优化的变体中，这一比例约为35%。换句话说，这是一个大约三分之一的速度提升。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::perform_stage( \n    const Number                                      current_time, \n    const Number                                      factor_solution, \n    const Number                                      factor_ai, \n    const LinearAlgebra::distributed::Vector<Number> &current_ri, \n    LinearAlgebra::distributed::Vector<Number> &      vec_ki, \n    LinearAlgebra::distributed::Vector<Number> &      solution, \n    LinearAlgebra::distributed::Vector<Number> &      next_ri) const \n  { \n    { \n      TimerOutput::Scope t(timer, \"rk_stage - integrals L_h\"); \n\n      for (auto &i : inflow_boundaries) \n        i.second->set_time(current_time); \n      for (auto &i : subsonic_outflow_boundaries) \n        i.second->set_time(current_time); \n\n      data.loop(&EulerOperator::local_apply_cell, \n                &EulerOperator::local_apply_face, \n                &EulerOperator::local_apply_boundary_face, \n                this, \n                vec_ki, \n                current_ri, \n                true, \n                MatrixFree<dim, Number>::DataAccessOnFaces::values, \n                MatrixFree<dim, Number>::DataAccessOnFaces::values); \n    } \n\n    { \n      TimerOutput::Scope t(timer, \"rk_stage - inv mass + vec upd\"); \n      data.cell_loop( \n        &EulerOperator::local_apply_inverse_mass_matrix, \n        this, \n        next_ri, \n        vec_ki, \n        std::function<void(const unsigned int, const unsigned int)>(), \n        [&](const unsigned int start_range, const unsigned int end_range) { \n          const Number ai = factor_ai; \n          const Number bi = factor_solution; \n          if (ai == Number()) \n            { \n\n          /* DEAL_II_OPENMP_SIMD_PRAGMA  */ \n              for (unsigned int i = start_range; i < end_range; ++i) \n                { \n                  const Number k_i          = next_ri.local_element(i); \n                  const Number sol_i        = solution.local_element(i); \n                  solution.local_element(i) = sol_i + bi * k_i; \n                } \n            } \n          else \n            { \n\n              /* DEAL_II_OPENMP_SIMD_PRAGMA  */ \n              for (unsigned int i = start_range; i < end_range; ++i) \n                { \n                  const Number k_i          = next_ri.local_element(i); \n                  const Number sol_i        = solution.local_element(i); \n                  solution.local_element(i) = sol_i + bi * k_i; \n                  next_ri.local_element(i)  = sol_i + ai * k_i; \n                } \n            } \n        }); \n    } \n  } \n\n// 在讨论了将解提前一个时间步长的函数的实现后，现在让我们来看看实现其他辅助性操作的函数。具体来说，这些是计算投影、评估误差和计算单元上信息传输速度的函数。\n\n// 这些函数中的第一个基本上等同于 VectorTools::project(), ，只是速度快得多，因为它是专门针对DG元素的，不需要设置和解决线性系统，因为每个元素都有独立的基函数。我们在这里展示代码的原因，除了这个非关键操作的小幅提速之外，还因为它显示了 MatrixFreeOperators::CellwiseInverseMassMatrix. 提供的额外功能。\n\n// 投影操作的工作原理如下。如果我们用 $S$ 表示在正交点评估的形状函数矩阵，那么在单元格 $K$ 上的投影是一个形式为 $\\underbrace{S J^K S^\\mathrm T}_{\\mathcal M^K} \\mathbf{w}^K = S J^K \\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$ 的操作，其中 $J^K$ 是包含雅各布系数乘以正交权重（JxW）的对角矩阵， $\\mathcal M^K$ 是单元格的质量矩阵， $\\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$ 是要投影到正交点的领域评估。实际上，矩阵 $S$ 通过张量积有额外的结构，如介绍中所解释的）。这个系统现在可以等效地写成 $\\mathbf{w}^K = \\left(S J^K S^\\mathrm T\\right)^{-1} S J^K \\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q} = S^{-\\mathrm T} \\left(J^K\\right)^{-1} S^{-1} S J^K \\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$  。现在，项 $S^{-1} S$ 和 $\\left(J^K\\right)^{-1} J^K$ 相抵消，导致最后的表达式 $\\mathbf{w}^K = S^{-\\mathrm T} \\tilde{\\mathbf{w}}(\\mathbf{x}_q)_{q=1:n_q}$  。这个操作由 MatrixFreeOperators::CellwiseInverseMassMatrix::transform_from_q_points_to_basis(). 实现。这个名字来自于这个投影只是乘以 $S^{-\\mathrm T}$ ，一个从高斯正交点的节点基到给定的有限元基的基数变化。请注意，我们调用 FEEvaluation::set_dof_values() 将结果写入矢量，覆盖之前的内容，而不是像典型的积分任务那样累积结果--我们可以这样做，因为对于不连续的Galerkin离散，每个矢量条目都只有一个单元的贡献。\n\n  template <int dim, int degree, int n_points_1d> \n  void EulerOperator<dim, degree, n_points_1d>::project( \n    const Function<dim> &                       function, \n    LinearAlgebra::distributed::Vector<Number> &solution) const \n  { \n    FEEvaluation<dim, degree, degree + 1, dim + 2, Number> phi(data, 0, 1); \n    MatrixFreeOperators::CellwiseInverseMassMatrix<dim, degree, dim + 2, Number> \n      inverse(phi); \n    solution.zero_out_ghost_values(); \n    for (unsigned int cell = 0; cell < data.n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          phi.submit_dof_value(evaluate_function(function, \n                                                 phi.quadrature_point(q)), \n                               q); \n        inverse.transform_from_q_points_to_basis(dim + 2, \n                                                 phi.begin_dof_values(), \n                                                 phi.begin_dof_values()); \n        phi.set_dof_values(solution); \n      } \n  } \n\n// 下一个函数再次重复了同样由deal.II库提供的功能，即 VectorTools::integrate_difference(). 我们在这里展示了明确的代码，以强调跨几个单元的矢量化是如何工作的，以及如何通过该接口累积结果。回顾一下，每个<i>lane</i>的矢量化数组持有来自不同单元的数据。通过对当前MPI进程所拥有的所有单元批的循环，我们就可以填充一个结果的VectorizedArray；为了得到一个全局的总和，我们需要进一步去对SIMD阵列中的条目进行求和。然而，这样的程序并不稳定，因为SIMD数组事实上可能并不持有其所有通道的有效数据。当本地拥有的单元的数量不是SIMD宽度的倍数时，就会发生这种情况。为了避免无效数据，我们必须在访问数据时明确地跳过那些无效的通道。虽然人们可以想象，我们可以通过简单地将空车道设置为零（从而不对总和做出贡献）来使其工作，但情况比这更复杂。如果我们要从动量中计算出一个速度呢？那么，我们就需要除以密度，而密度是零--结果就会是NaN，并污染结果。当我们在单元格批次中循环时，使用函数 MatrixFree::n_active_entries_per_cell_batch() 给我们提供有效数据的通道数，累积有效SIMD范围内的结果，就可以避免这种陷阱。它在大多数单元上等于 VectorizedArray::size() ，但如果单元数与SIMD宽度相比有余数，则在最后一个单元批上可能会更少。\n\n  template <int dim, int degree, int n_points_1d> \n  std::array<double, 3> EulerOperator<dim, degree, n_points_1d>::compute_errors( \n    const Function<dim> &                             function, \n    const LinearAlgebra::distributed::Vector<Number> &solution) const \n  { \n    TimerOutput::Scope t(timer, \"compute errors\"); \n    double             errors_squared[3] = {}; \n    FEEvaluation<dim, degree, n_points_1d, dim + 2, Number> phi(data, 0, 0); \n\n    for (unsigned int cell = 0; cell < data.n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n        phi.gather_evaluate(solution, EvaluationFlags::values); \n        VectorizedArray<Number> local_errors_squared[3] = {}; \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            const auto error = \n              evaluate_function(function, phi.quadrature_point(q)) - \n              phi.get_value(q); \n            const auto JxW = phi.JxW(q); \n\n            local_errors_squared[0] += error[0] * error[0] * JxW; \n            for (unsigned int d = 0; d < dim; ++d) \n              local_errors_squared[1] += (error[d + 1] * error[d + 1]) * JxW; \n            local_errors_squared[2] += (error[dim + 1] * error[dim + 1]) * JxW; \n          } \n        for (unsigned int v = 0; v < data.n_active_entries_per_cell_batch(cell); \n             ++v) \n          for (unsigned int d = 0; d < 3; ++d) \n            errors_squared[d] += local_errors_squared[d][v]; \n      } \n\n    Utilities::MPI::sum(errors_squared, MPI_COMM_WORLD, errors_squared); \n\n    std::array<double, 3> errors; \n    for (unsigned int d = 0; d < 3; ++d) \n      errors[d] = std::sqrt(errors_squared[d]); \n\n    return errors; \n  } \n\n// EulerOperator类的最后一个函数是用来估计传输速度的，由网格大小缩放，这与设置显式时间积分器的时间步长有关。在欧拉方程中，有两种传输速度，即对流速度 $\\mathbf{u}$ 和相对于以速度 $\\mathbf u$ 运动的介质而言，声波的传播速度 $c = \\sqrt{\\gamma p/\\rho}$  。\n\n// 在时间步长的公式中，我们感兴趣的不是这些绝对速度，而是信息穿过一个单元所需的时间量。对于与介质一起传输的信息， $\\mathbf u$ 是由网格大小缩放的，所以最大速度的估计可以通过计算 $\\|J^{-\\mathrm T} \\mathbf{u}\\|_\\infty$  得到，其中 $J$ 是实域到参考域的转换的雅各布。请注意， FEEvaluationBase::inverse_jacobian() 返回的是反转和转置的雅各布，代表从实数到参考坐标的度量项，所以我们不需要再次转置。我们在下面的代码中把这个极限存储在变量`convective_limit`中。\n\n// 声音的传播是各向同性的，所以我们需要考虑到任何方向的网格尺寸。然后，适当的网格大小比例由 $J$ 的最小奇异值给出，或者，等同于 $J^{-1}$ 的最大奇异值。请注意，当忽略弯曲的单元时，可以用单元顶点之间的最小距离来近似这个量。为了得到Jacobian的最大奇异值，一般的策略是使用一些LAPACK函数。由于我们在这里需要的只是一个估计值，所以我们可以避免将一个向量数组的张量分解成几个矩阵的麻烦，并在没有向量的情况下进入一个（昂贵的）特征值函数，而是使用应用于 $J^{-1}J^{-\\mathrm T}$ 的幂方法进行几次迭代（在下面的代码中为五次）。这种方法的收敛速度取决于最大特征值与次大特征值的比率以及初始猜测，即所有1的矢量。这可能表明，我们在接近立方体形状的单元上得到缓慢的收敛，在这种情况下，所有的长度几乎都是一样的。然而，这种缓慢的收敛意味着结果将位于两个最大的奇异值之间，而这两个奇异值无论如何都是接近最大值的。在所有其他情况下，收敛将是快速的。因此，我们可以只在这里硬编码5次迭代，并确信结果是好的。\n\n  template <int dim, int degree, int n_points_1d> \n  double EulerOperator<dim, degree, n_points_1d>::compute_cell_transport_speed( \n    const LinearAlgebra::distributed::Vector<Number> &solution) const \n  { \n    TimerOutput::Scope t(timer, \"compute transport speed\"); \n    Number             max_transport = 0; \n    FEEvaluation<dim, degree, degree + 1, dim + 2, Number> phi(data, 0, 1); \n\n    for (unsigned int cell = 0; cell < data.n_cell_batches(); ++cell) \n      { \n        phi.reinit(cell); \n        phi.gather_evaluate(solution, EvaluationFlags::values); \n        VectorizedArray<Number> local_max = 0.; \n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            const auto solution = phi.get_value(q); \n            const auto velocity = euler_velocity<dim>(solution); \n            const auto pressure = euler_pressure<dim>(solution); \n\n            const auto inverse_jacobian = phi.inverse_jacobian(q); \n            const auto convective_speed = inverse_jacobian * velocity; \n            VectorizedArray<Number> convective_limit = 0.; \n            for (unsigned int d = 0; d < dim; ++d) \n              convective_limit = \n                std::max(convective_limit, std::abs(convective_speed[d])); \n\n            const auto speed_of_sound = \n              std::sqrt(gamma * pressure * (1. / solution[0])); \n\n            Tensor<1, dim, VectorizedArray<Number>> eigenvector; \n            for (unsigned int d = 0; d < dim; ++d) \n              eigenvector[d] = 1.; \n            for (unsigned int i = 0; i < 5; ++i) \n              { \n                eigenvector = transpose(inverse_jacobian) * \n                              (inverse_jacobian * eigenvector); \n                VectorizedArray<Number> eigenvector_norm = 0.; \n                for (unsigned int d = 0; d < dim; ++d) \n                  eigenvector_norm = \n                    std::max(eigenvector_norm, std::abs(eigenvector[d])); \n                eigenvector /= eigenvector_norm; \n              } \n            const auto jac_times_ev   = inverse_jacobian * eigenvector; \n            const auto max_eigenvalue = std::sqrt( \n              (jac_times_ev * jac_times_ev) / (eigenvector * eigenvector)); \n            local_max = \n              std::max(local_max, \n                       max_eigenvalue * speed_of_sound + convective_limit); \n          } \n\n// 与前面的函数类似，我们必须确保只在一个单元格批次的有效单元格上积累速度。\n\n     for (unsigned int v = 0; v < data.n_active_entries_per_cell_batch(cell);\n             ++v) \n          for (unsigned int d = 0; d < 3; ++d) \n            max_transport = std::max(max_transport, local_max[v]); \n      } \n\n    max_transport = Utilities::MPI::max(max_transport, MPI_COMM_WORLD); \n\n    return max_transport; \n  } \n\n//  @sect3{The EulerProblem class}  \n\n// 该类将EulerOperator类与时间积分器和通常的全局数据结构（如FiniteElement和DoFHandler）相结合，以实际运行Euler问题的模拟。\n\n// 成员变量是一个三角形、一个有限元、一个映射（用于创建高阶曲面，见 step-10 ），以及一个描述自由度的DoFHandler。此外，我们还保留了上面描述的EulerOperator的实例，它将完成所有积分方面的繁重工作，以及一些时间积分的参数，如当前时间或时间步长。\n\n// 此外，我们使用一个PostProcessor实例来向输出文件写入一些额外的信息，这与  step-33  中的做法类似。DataPostprocessor类的接口很直观，要求我们提供关于需要评估的信息（通常只有解决方案的值，除了Schlieren图，我们只在二维中启用它是有意义的），以及被评估的东西的名称。请注意，也可以通过可视化程序（如ParaView）中的计算器工具来提取大部分信息，但在写输出时就已经做了，这要方便得多。\n\n  template <int dim> \n  class EulerProblem \n  { \n  public: \n    EulerProblem(); \n\n    void run(); \n\n  private: \n    void make_grid_and_dofs(); \n\n    void output_results(const unsigned int result_number); \n\n    LinearAlgebra::distributed::Vector<Number> solution; \n\n    ConditionalOStream pcout; \n\n#ifdef DEAL_II_WITH_P4EST \n    parallel::distributed::Triangulation<dim> triangulation; \n#else \n    Triangulation<dim> triangulation; \n#endif \n\n    FESystem<dim>        fe; \n    MappingQGeneric<dim> mapping; \n    DoFHandler<dim>      dof_handler; \n\n    TimerOutput timer; \n\n    EulerOperator<dim, fe_degree, n_q_points_1d> euler_operator; \n\n    double time, time_step; \n\n    class Postprocessor : public DataPostprocessor<dim> \n    { \n    public: \n      Postprocessor(); \n\n      virtual void evaluate_vector_field( \n        const DataPostprocessorInputs::Vector<dim> &inputs, \n        std::vector<Vector<double>> &computed_quantities) const override; \n\n      virtual std::vector<std::string> get_names() const override; \n\n      virtual std::vector< \n        DataComponentInterpretation::DataComponentInterpretation> \n      get_data_component_interpretation() const override; \n\n      virtual UpdateFlags get_needed_update_flags() const override; \n\n    private: \n      const bool do_schlieren_plot; \n    }; \n  }; \n\n  template <int dim> \n  EulerProblem<dim>::Postprocessor::Postprocessor() \n    : do_schlieren_plot(dim == 2) \n  {} \n\n// 对于字段变量的主要评估，我们首先检查数组的长度是否等于预期值（长度`2*dim+4`或`2*dim+5`来自我们在下面get_names()函数中指定的名字的大小）。然后我们在所有的评估点上循环，填充相应的信息。首先，我们填写密度 $\\rho$ 、动量 $\\rho \\mathbf{u}$ 和能量 $E$ 的原始解变量，然后我们计算得出速度 $\\mathbf u$ 、压力 $p$ 、声速 $c=\\sqrt{\\gamma p / \\rho}$ ，以及显示 $s = |\\nabla \\rho|^2$ 的Schlieren图，如果它被启用。参见 step-69 中另一个创建Schlieren图的例子）。\n\n  template <int dim> \n  void EulerProblem<dim>::Postprocessor::evaluate_vector_field( \n    const DataPostprocessorInputs::Vector<dim> &inputs, \n    std::vector<Vector<double>> &               computed_quantities) const \n  { \n    const unsigned int n_evaluation_points = inputs.solution_values.size(); \n\n    if (do_schlieren_plot == true) \n      Assert(inputs.solution_gradients.size() == n_evaluation_points, \n             ExcInternalError()); \n\n    Assert(computed_quantities.size() == n_evaluation_points, \n           ExcInternalError()); \n    Assert(inputs.solution_values[0].size() == dim + 2, ExcInternalError()); \n    Assert(computed_quantities[0].size() == \n             dim + 2 + (do_schlieren_plot == true ? 1 : 0), \n           ExcInternalError()); \n\n    for (unsigned int q = 0; q < n_evaluation_points; ++q) \n      { \n        Tensor<1, dim + 2> solution; \n        for (unsigned int d = 0; d < dim + 2; ++d) \n          solution[d] = inputs.solution_values[q](d); \n\n        const double         density  = solution[0]; \n        const Tensor<1, dim> velocity = euler_velocity<dim>(solution); \n        const double         pressure = euler_pressure<dim>(solution); \n\n        for (unsigned int d = 0; d < dim; ++d) \n          computed_quantities[q](d) = velocity[d]; \n        computed_quantities[q](dim)     = pressure; \n        computed_quantities[q](dim + 1) = std::sqrt(gamma * pressure / density); \n\n        if (do_schlieren_plot == true) \n          computed_quantities[q](dim + 2) = \n            inputs.solution_gradients[q][0] * inputs.solution_gradients[q][0]; \n      } \n  } \n\n  template <int dim> \n  std::vector<std::string> EulerProblem<dim>::Postprocessor::get_names() const \n  { \n    std::vector<std::string> names; \n    for (unsigned int d = 0; d < dim; ++d) \n      names.emplace_back(\"velocity\"); \n    names.emplace_back(\"pressure\"); \n    names.emplace_back(\"speed_of_sound\"); \n\n    if (do_schlieren_plot == true) \n      names.emplace_back(\"schlieren_plot\"); \n\n    return names; \n  } \n\n// 对于量的解释，我们有标量密度、能量、压力、声速和Schlieren图，以及动量和速度的向量。\n\n  template <int dim> \n  std::vector<DataComponentInterpretation::DataComponentInterpretation> \n  EulerProblem<dim>::Postprocessor::get_data_component_interpretation() const \n  { \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      interpretation; \n    for (unsigned int d = 0; d < dim; ++d) \n      interpretation.push_back( \n        DataComponentInterpretation::component_is_part_of_vector); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n\n    if (do_schlieren_plot == true) \n      interpretation.push_back( \n        DataComponentInterpretation::component_is_scalar); \n\n    return interpretation; \n  } \n\n// 关于必要的更新标志，我们只需要所有数量的值，但Schlieren图除外，它是基于密度梯度的。\n\n  template <int dim> \n  UpdateFlags EulerProblem<dim>::Postprocessor::get_needed_update_flags() const \n  { \n    if (do_schlieren_plot == true) \n      return update_values | update_gradients; \n    else \n      return update_values; \n  } \n\n// 这个类的构造函数并不令人惊讶。我们设置了一个基于 \"MPI_COMM_WORLD \"通信器的平行三角形，一个具有 \"dim+2 \"分量的密度、动量和能量的矢量有限元，一个与底层有限元相同程度的高阶映射，并将时间和时间步长初始化为零。\n\n  template <int dim> \n  EulerProblem<dim>::EulerProblem() \n    : pcout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n#ifdef DEAL_II_WITH_P4EST \n    , triangulation(MPI_COMM_WORLD) \n#endif \n    , fe(FE_DGQ<dim>(fe_degree), dim + 2) \n    , mapping(fe_degree) \n    , dof_handler(triangulation) \n    , timer(pcout, TimerOutput::never, TimerOutput::wall_times) \n    , euler_operator(timer) \n    , time(0) \n    , time_step(0) \n  {} \n\n// 作为一个网格，本教程程序实现了两种选择，取决于全局变量`testcase`。对于分析型变量（`testcase==0`），域是 $(0, 10) \\times (-5, 5)$ ，域的四周都有迪里希特边界条件（流入）。对于 \"testcase==1\"，我们将域设置为矩形箱中的圆柱体，源自Sch&auml;fer和Turek（1996）对不可压缩的粘性流动的圆柱体的流动测试案例。在这里，我们有更多种类的边界。通道左侧的流入部分是给定的流入类型，为此我们选择了一个恒定的流入轮廓，而我们在右侧设置了一个亚声速的流出。对于圆柱体周围的边界（边界id等于2）以及通道壁（边界id等于3），我们使用壁的边界类型，即无正态流。此外，对于三维圆柱体，我们还在垂直方向上增加了一个重力。有了基础网格（包括由 GridGenerator::channel_with_cylinder()), 设置的流形），我们就可以执行指定数量的全局细化，从DoFHandler创建未知的编号，并将DoFHandler和Mapping对象交给EulerOperator的初始化。\n\n  template <int dim> \n  void EulerProblem<dim>::make_grid_and_dofs() \n  { \n    switch (testcase) \n      { \n        case 0: \n          { \n            Point<dim> lower_left; \n            for (unsigned int d = 1; d < dim; ++d) \n              lower_left[d] = -5; \n\n            Point<dim> upper_right; \n            upper_right[0] = 10; \n            for (unsigned int d = 1; d < dim; ++d) \n              upper_right[d] = 5; \n\n            GridGenerator::hyper_rectangle(triangulation, \n                                           lower_left, \n                                           upper_right); \n            triangulation.refine_global(2); \n\n            euler_operator.set_inflow_boundary( \n              0, std::make_unique<ExactSolution<dim>>(0)); \n\n            break; \n          } \n\n        case 1: \n          { \n            GridGenerator::channel_with_cylinder( \n              triangulation, 0.03, 1, 0, true); \n\n            euler_operator.set_inflow_boundary( \n              0, std::make_unique<ExactSolution<dim>>(0)); \n            euler_operator.set_subsonic_outflow_boundary( \n              1, std::make_unique<ExactSolution<dim>>(0)); \n\n            euler_operator.set_wall_boundary(2); \n            euler_operator.set_wall_boundary(3); \n\n            if (dim == 3) \n              euler_operator.set_body_force( \n                std::make_unique<Functions::ConstantFunction<dim>>( \n                  std::vector<double>({0., 0., -0.2}))); \n\n            break; \n          } \n\n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n    triangulation.refine_global(n_global_refinements); \n\n    dof_handler.distribute_dofs(fe); \n\n    euler_operator.reinit(mapping, dof_handler); \n    euler_operator.initialize_vector(solution); \n\n// 在下文中，我们输出一些关于问题的统计数据。因为我们经常会出现相当多的单元格或自由度，所以我们希望用逗号来分隔每一组的三位数来打印它们。这可以通过 \"locales \"来实现，尽管这种工作方式不是特别直观。  step-32 对此有稍微详细的解释。\n\n    std::locale s = pcout.get_stream().getloc(); \n    pcout.get_stream().imbue(std::locale(\"\")); \n    pcout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n          << \" ( = \" << (dim + 2) << \" [vars] x \" \n          << triangulation.n_global_active_cells() << \" [cells] x \" \n          << Utilities::pow(fe_degree + 1, dim) << \" [dofs/cell/var] )\" \n          << std::endl; \n    pcout.get_stream().imbue(s); \n  } \n\n// 对于输出，我们首先让欧拉算子计算出数值结果的误差。更确切地说，对于分析解的情况，我们计算与分析结果的误差，而对于第二个测试情况，我们计算与密度和能量恒定的背景场以及 $x$ 方向的恒定速度的偏差。\n\n// 下一步是创建输出。这与 step-33 中的做法类似：我们让上面定义的后处理器控制大部分的输出，除了我们直接写的原始场。对于分析解的测试案例，我们还对分析解进行了另一次投影，并打印出该场和数值解之间的差异。一旦我们定义了所有要写的量，我们就建立输出的补丁。与 step-65 类似，我们通过设置适当的标志来创建一个高阶VTK输出，这使我们能够可视化高多项式度的场。最后，我们调用 `DataOutInterface::write_vtu_in_parallel()` 函数，将结果写入给定的文件名。这个函数使用了特殊的MPI并行写设施，与其他大多数教程程序中使用的标准库的 `std::ofstream` 变体相比，它通常对并行文件系统更加优化。`write_vtu_in_parallel()`函数的一个特别好的特点是，它可以将所有MPI行列的输出合并到一个文件中，使得没有必要有一个所有此类文件的中央记录（即 \"pvtu \"文件）。\n\n// 对于并行程序来说，看一下单元在处理器之间的划分往往是有启发的。为此，我们可以向 DataOut::add_data_vector() 传递一个数字向量，其中包含与当前处理器拥有的活动单元一样多的条目；然后这些数字应该是拥有这些单元的处理器的等级。例如，这样一个向量可以从 GridTools::get_subdomain_association(). 中获得。另一方面，在每个MPI进程中，DataOut将只读取那些对应于本地拥有的单元的条目，这些条目当然都有相同的值：即当前进程的等级。矢量的其余条目中的内容实际上并不重要，因此我们可以用一个廉价的技巧逃脱。我们只是把我们给 DataOut::add_data_vector() 的向量的所有*值都填上当前MPI进程的等级。关键是在每个进程中，只有对应于本地拥有的单元格的条目会被读取，而忽略其他条目中的（错误）值。事实上，每个进程提交的向量中的条目子集是正确的，这就足够了。\n\n  template <int dim> \n  void EulerProblem<dim>::output_results(const unsigned int result_number) \n  { \n    const std::array<double, 3> errors = \n      euler_operator.compute_errors(ExactSolution<dim>(time), solution); \n    const std::string quantity_name = testcase == 0 ? \"error\" : \"norm\"; \n\n    pcout << \"Time:\" << std::setw(8) << std::setprecision(3) << time \n          << \", dt: \" << std::setw(8) << std::setprecision(2) << time_step \n          << \", \" << quantity_name << \" rho: \" << std::setprecision(4) \n          << std::setw(10) << errors[0] << \", rho * u: \" << std::setprecision(4) \n          << std::setw(10) << errors[1] << \", energy:\" << std::setprecision(4) \n          << std::setw(10) << errors[2] << std::endl; \n\n    { \n      TimerOutput::Scope t(timer, \"output\"); \n\n      Postprocessor postprocessor; \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      { \n        std::vector<std::string> names; \n        names.emplace_back(\"density\"); \n        for (unsigned int d = 0; d < dim; ++d) \n          names.emplace_back(\"momentum\"); \n        names.emplace_back(\"energy\"); \n\n        std::vector<DataComponentInterpretation::DataComponentInterpretation> \n          interpretation; \n        interpretation.push_back( \n          DataComponentInterpretation::component_is_scalar); \n        for (unsigned int d = 0; d < dim; ++d) \n          interpretation.push_back( \n            DataComponentInterpretation::component_is_part_of_vector); \n        interpretation.push_back( \n          DataComponentInterpretation::component_is_scalar); \n\n        data_out.add_data_vector(dof_handler, solution, names, interpretation); \n      } \n      data_out.add_data_vector(solution, postprocessor); \n\n      LinearAlgebra::distributed::Vector<Number> reference; \n      if (testcase == 0 && dim == 2) \n        { \n          reference.reinit(solution); \n          euler_operator.project(ExactSolution<dim>(time), reference); \n          reference.sadd(-1., 1, solution); \n          std::vector<std::string> names; \n          names.emplace_back(\"error_density\"); \n          for (unsigned int d = 0; d < dim; ++d) \n            names.emplace_back(\"error_momentum\"); \n          names.emplace_back(\"error_energy\"); \n\n          std::vector<DataComponentInterpretation::DataComponentInterpretation> \n            interpretation; \n          interpretation.push_back( \n            DataComponentInterpretation::component_is_scalar); \n          for (unsigned int d = 0; d < dim; ++d) \n            interpretation.push_back( \n              DataComponentInterpretation::component_is_part_of_vector); \n          interpretation.push_back( \n            DataComponentInterpretation::component_is_scalar); \n\n          data_out.add_data_vector(dof_handler, \n                                   reference, \n                                   names, \n                                   interpretation); \n        } \n\n      Vector<double> mpi_owner(triangulation.n_active_cells()); \n      mpi_owner = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD); \n      data_out.add_data_vector(mpi_owner, \"owner\"); \n\n      data_out.build_patches(mapping, \n                             fe.degree, \n                             DataOut<dim>::curved_inner_cells); \n\n      const std::string filename = \n        \"solution_\" + Utilities::int_to_string(result_number, 3) + \".vtu\"; \n      data_out.write_vtu_in_parallel(filename, MPI_COMM_WORLD); \n    } \n  } \n\n//  EulerProblem::run() 函数将所有的部分组合起来。它首先调用创建网格和设置数据结构的函数，然后初始化时间积分器和低存储积分器的两个临时向量。我们称这些向量为`rk_register_1`和`rk_register_2`，并使用第一个向量表示 $\\mathbf{r}_i$ ，第二个向量表示 $\\mathbf{k}_i$ ，在介绍中概述的Runge--Kutta方案的公式。在我们开始时间循环之前，我们通过 `EulerOperator::compute_cell_transport_speed()` 函数计算时间步长。为了便于比较，我们将那里得到的结果与最小网格尺寸进行比较，并将它们打印到屏幕上。对于像本教程程序中接近于统一的声速和速度，预测的有效网格尺寸将是接近的，但如果缩放比例不同，它们可能会有变化。\n\n  template <int dim> \n  void EulerProblem<dim>::run() \n  { \n    { \n      const unsigned int n_vect_number = VectorizedArray<Number>::size(); \n      const unsigned int n_vect_bits   = 8 * sizeof(Number) * n_vect_number; \n\n      pcout << \"Running with \" \n            << Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) \n            << \" MPI processes\" << std::endl; \n      pcout << \"Vectorization over \" << n_vect_number << \" \" \n            << (std::is_same<Number, double>::value ? \"doubles\" : \"floats\") \n            << \" = \" << n_vect_bits << \" bits (\" \n            << Utilities::System::get_current_vectorization_level() << \")\" \n            << std::endl; \n    } \n\n    make_grid_and_dofs(); \n\n    const LowStorageRungeKuttaIntegrator integrator(lsrk_scheme); \n\n    LinearAlgebra::distributed::Vector<Number> rk_register_1; \n    LinearAlgebra::distributed::Vector<Number> rk_register_2; \n    rk_register_1.reinit(solution); \n    rk_register_2.reinit(solution); \n\n    euler_operator.project(ExactSolution<dim>(time), solution); \n\n    double min_vertex_distance = std::numeric_limits<double>::max(); \n    for (const auto &cell : triangulation.active_cell_iterators()) \n      if (cell->is_locally_owned()) \n        min_vertex_distance = \n          std::min(min_vertex_distance, cell->minimum_vertex_distance()); \n    min_vertex_distance = \n      Utilities::MPI::min(min_vertex_distance, MPI_COMM_WORLD); \n\n    time_step = courant_number * integrator.n_stages() / \n                euler_operator.compute_cell_transport_speed(solution); \n    pcout << \"Time step size: \" << time_step \n          << \", minimal h: \" << min_vertex_distance \n          << \", initial transport scaling: \" \n          << 1. / euler_operator.compute_cell_transport_speed(solution) \n          << std::endl \n          << std::endl; \n\n    output_results(0); \n\n// 现在我们准备开始时间循环，我们一直运行到时间达到预期的结束时间。每隔5个时间步长，我们就计算一个新的时间步长估计值--由于解决方案是非线性的，在模拟过程中调整这个值是最有效的。如果Courant数选择得过于激进，模拟通常会在时间步数为NaN时爆炸，所以在这里很容易发现。有一点需要注意的是，由于不同的时间步长选择的相互作用，四舍五入的误差可能会传播到前几位数，从而导致略有不同的解决方案。为了降低这种敏感性，通常的做法是将时间步长四舍五入或截断到几位数，例如在这种情况下是3。如果当前时间接近规定的输出 \"刻度 \"值（如0.02），我们也会写出输出。在时间循环结束后，我们通过打印一些统计数据来总结计算，这主要由 TimerOutput::print_wall_time_statistics() 函数完成。\n\n    unsigned int timestep_number = 0; \n\n    while (time < final_time - 1e-12) \n      { \n        ++timestep_number; \n        if (timestep_number % 5 == 0) \n          time_step = \n            courant_number * integrator.n_stages() / \n            Utilities::truncate_to_n_digits( \n              euler_operator.compute_cell_transport_speed(solution), 3); \n\n        { \n          TimerOutput::Scope t(timer, \"rk time stepping total\"); \n          integrator.perform_time_step(euler_operator, \n                                       time, \n                                       time_step, \n                                       solution, \n                                       rk_register_1, \n                                       rk_register_2); \n        } \n\n        time += time_step; \n\n        if (static_cast<int>(time / output_tick) != \n              static_cast<int>((time - time_step) / output_tick) || \n            time >= final_time - 1e-12) \n          output_results( \n            static_cast<unsigned int>(std::round(time / output_tick))); \n      } \n\n    timer.print_wall_time_statistics(MPI_COMM_WORLD); \n    pcout << std::endl; \n  } \n\n} // namespace Euler_DG \n\n// main()函数并不令人惊讶，它遵循了以前所有MPI程序中的做法。当我们运行一个MPI程序时，我们需要调用`MPI_Init()`和`MPI_Finalize()`，我们通过 Utilities::MPI::MPI_InitFinalize 数据结构来完成。请注意，我们只用MPI来运行程序，并将线程数设置为1。\n\nint main(int argc, char **argv) \n{ \n  using namespace Euler_DG; \n  using namespace dealii; \n\n  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n  try \n    { \n      deallog.depth_console(0); \n\n      EulerProblem<dimension> euler_problem; \n      euler_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": "f1ddcc49d02732f25cef357b741a5ca518d9c025", "size": 72266, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-67/step-67.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-67/step-67.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-67/step-67.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": 44.6086419753, "max_line_length": 953, "alphanum_fraction": 0.6349735699, "num_tokens": 28914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928951399098, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.5796657754867541}}
{"text": "/**\n    This file is part of Deformable Shape Tracking (DEST).\n\n    Copyright(C) 2015/2016 Christoph Heindl\n    All rights reserved.\n\n    This software may be modified and distributed under the terms\n    of the BSD license.See the LICENSE file for details.\n*/\n\n#include <dest/core/shape.h>\n#include <Eigen/Dense>\n\nnamespace dest {\n    namespace core {\n        \n        Eigen::AffineCompact2f estimateSimilarityTransform(const Eigen::Ref<const Shape> &from, const Eigen::Ref<const Shape> &to)\n        {            \n            Eigen::Vector2f meanFrom = from.rowwise().mean();\n            Eigen::Vector2f meanTo = to.rowwise().mean();\n            \n            Shape centeredFrom = from.colwise() - meanFrom;\n            Shape centeredTo = to.colwise() - meanTo;\n            \n            Eigen::Matrix2f cov = (centeredFrom) * (centeredTo).transpose();\n            cov /= static_cast<float>(from.cols());\n            const float sFrom = centeredFrom.squaredNorm() / from.cols();\n            \n            auto svd = cov.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n            Eigen::Matrix2f d = Eigen::Matrix2f::Zero(2, 2);\n            d(0, 0) = svd.singularValues()(0);\n            d(1, 1) = svd.singularValues()(1);\n            \n            // Correct reflection if any.\n            float detCov = cov.determinant();\n            float detUV = svd.matrixU().determinant() * svd.matrixV().determinant();\n            Eigen::Matrix2f s = Eigen::Matrix2f::Identity(2, 2);\n            if (detCov < 0.f || (detCov == 0.f && detUV < 0.f)) {\n                if (svd.singularValues()(1) < svd.singularValues()(0)) {\n                    s(1, 1) = -1;\n                } else {\n                    s(0, 0) = -1;\n                }\n            }\n            \n            Eigen::Matrix2f rot = svd.matrixU().transpose() * s * svd.matrixV();\n            float c = 1.f;\n            if (sFrom > 0) {\n                c = 1.f / sFrom * (d * s).trace();\n            }\n            \n            Eigen::Vector2f t = meanTo - c * rot * meanFrom;\n            \n            Eigen::Matrix<float, 2, 3> ret = Eigen::Matrix<float, 2, 3>::Identity(2, 3);\n            ret.block<2,2>(0,0) = c * rot;\n            ret.block<2,1>(0,2) = t;\n            \n            return Eigen::AffineCompact2f(ret);\n        }\n        \n        int findClosestLandmarkIndex(const Shape &s, const Eigen::Ref<const Eigen::Vector2f> &x)\n        {\n            const int numLandmarks = static_cast<int>(s.cols());\n            \n            int bestLandmark = -1;\n            float bestD2 = std::numeric_limits<float>::max();\n            \n            for (int i = 0; i < numLandmarks; ++i) {\n                float d2 = (s.col(i) - x).squaredNorm();\n                if (d2 < bestD2) {\n                    bestD2 = d2;\n                    bestLandmark = i;\n                }\n            }\n            \n            return bestLandmark;\n        }\n        \n        \n        void shapeRelativePixelCoordinates(const Shape &s, const PixelCoordinates &abscoords, PixelCoordinates &relcoords, Eigen::VectorXi &closestLandmarks)\n        {\n            \n            relcoords.resize(abscoords.rows(), abscoords.cols());\n            closestLandmarks.resize(abscoords.cols());\n            \n            const int numLocs = static_cast<int>(abscoords.cols());\n            for (int i  = 0; i < numLocs; ++i) {\n                int idx = findClosestLandmarkIndex(s, abscoords.col(i));\n                relcoords.col(i) = abscoords.col(i) - s.col(idx);\n                closestLandmarks(i) = idx;\n            }\n            \n        }\n\n        inline Rect getUnitRectangle() {\n            Rect r(2, 4);\n\n            // Top-left\n            r(0, 0) = -0.5f;\n            r(1, 0) = -0.5f;\n\n            // Top-right\n            r(0, 1) = 0.5f;\n            r(1, 1) = -0.5f;\n\n            // Bottom-left\n            r(0, 2) = -0.5f;\n            r(1, 2) = 0.5f;\n\n            // Bottom-right\n            r(0, 3) = 0.5f;\n            r(1, 3) = 0.5f;\n\n            return r;\n        }\n\n        const Rect &unitRectangle() {\n            const static Rect _instance = getUnitRectangle();\n            return _instance;\n        }\n\n        Rect shapeBounds(const Eigen::Ref<const Shape> &s)\n        {\n            const Eigen::Vector2f minC = s.rowwise().minCoeff();\n            const Eigen::Vector2f maxC = s.rowwise().maxCoeff();\n\n            return createRectangle(minC, maxC);\n        }\n\n        Rect createRectangle(const Eigen::Vector2f &minC, const Eigen::Vector2f &maxC)\n        {\n            Rect rect(2, 4);\n            rect.col(0) = minC;\n            rect.col(1) = Eigen::Vector2f(maxC(0), minC(1));\n            rect.col(2) = Eigen::Vector2f(minC(0), maxC(1));\n            rect.col(3) = maxC;\n            return rect;\n        }\n    }\n}", "meta": {"hexsha": "16d4135033d544d86f5370f24d8b71245d877211", "size": 4752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/shape.cpp", "max_stars_repo_name": "cluert/dest", "max_stars_repo_head_hexsha": "82c25f44ebe00b64e098d7e554fbc4ae1ae1c788", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 309.0, "max_stars_repo_stars_event_min_datetime": "2016-01-19T23:49:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:16:32.000Z", "max_issues_repo_path": "src/core/shape.cpp", "max_issues_repo_name": "jnulzl/dest", "max_issues_repo_head_hexsha": "82c25f44ebe00b64e098d7e554fbc4ae1ae1c788", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-02-16T16:36:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-25T05:56:02.000Z", "max_forks_repo_path": "src/core/shape.cpp", "max_forks_repo_name": "jnulzl/dest", "max_forks_repo_head_hexsha": "82c25f44ebe00b64e098d7e554fbc4ae1ae1c788", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2016-02-27T13:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T09:00:06.000Z", "avg_line_length": 33.9428571429, "max_line_length": 157, "alphanum_fraction": 0.4816919192, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5796493187784607}}
{"text": "/*\n supercell.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 <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include \"supercell.hxx\"\n#include \"utils.hxx\"\n\nnamespace ublas = boost::numeric::ublas;\n\nSupercell::Supercell(ublas::vector<long> sext,\n                     long primitive_number_of_atoms,\n                     ublas::matrix<double> primitive_lattice_vectors,\n                     ublas::matrix<double> primitive_basis_vectors,\n\t\t     double concentration) {\n\n  supercell_extension = sext;\n  primitive_number_of_atoms_ = primitive_number_of_atoms;\n  primitive_lattice_vectors_ = primitive_lattice_vectors;\n  primitive_basis_vectors_ = primitive_basis_vectors;\n  concentration_ = concentration;\n\n  number_of_atoms = product(supercell_extension)*primitive_number_of_atoms_;\n\n  lattice_vectors = primitive_lattice_vectors_;\n  for (auto i = 0; i < 3; i++) {\n    long s = supercell_extension(i);\n    for (auto j = 0; j < 3; j++) {\n      double pij = primitive_lattice_vectors_(i,j);\n      lattice_vectors(i,j) = s*pij;\n    }\n  }\n\n  ublas::matrix<double> basis(number_of_atoms,3);\n  auto iat = 0;\n  for (auto i = 0; i < primitive_number_of_atoms_; i++) {\n    for (auto j = 0; j < supercell_extension(0); j++) {\n      for (auto k = 0; k < supercell_extension(1); k++) {\n        for (auto l = 0; l < supercell_extension(2); l++) {\n          for (auto a = 0; a < 3; a++) {\n\t    basis(iat,a) = primitive_basis_vectors_(i,a)\n\t                 + j*primitive_lattice_vectors_(0,a)\n                         + k*primitive_lattice_vectors_(1,a)\n\t                 + l*primitive_lattice_vectors_(2,a);\n          }\n          ublas::matrix_row<ublas::matrix<double>> b(basis_vectors,iat);\n          iat++;\n        }\n      }\n    }\n  }\n  \n  auto solute = concentration_*number_of_atoms;\n  ublas::vector<long> tmp(number_of_atoms);\n  for (auto i = 0; i < number_of_atoms; i++) {\n    if (i < solute) {\n      tmp(i) = -1;\n    } else {\n      tmp(i) = 1;\n    }\n  }\n\n  basis_vectors = basis;\n  pointers = tmp;\n  \n}\n", "meta": {"hexsha": "1c6e17440020ea8e870a56fef3925f050cd3aacc", "size": 2321, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/supercell.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/supercell.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/supercell.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": 29.7564102564, "max_line_length": 76, "alphanum_fraction": 0.6419646704, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5796493100332362}}
{"text": "#ifndef ALEPH_MATH_PRINCIPAL_COMPONENT_ANALYSIS_HH__\n#define ALEPH_MATH_PRINCIPAL_COMPONENT_ANALYSIS_HH__\n\n#include <aleph/config/Eigen.hh>\n\n#ifdef ALEPH_WITH_EIGEN\n  #include <Eigen/Core>\n  #include <Eigen/SVD>\n#endif\n\n#include <vector>\n\n#include <cmath>\n\n// These warnings can become a bit overzealous; the initialization done\n// in the class is completely fine and will default to a struct that is\n// properly initialized.\n_Pragma( \"GCC diagnostic push\" )\n_Pragma( \"GCC diagnostic ignored \\\"-Wmissing-field-initializers\\\"\" )\n\nnamespace aleph\n{\n\nnamespace math\n{\n\nclass PrincipalComponentAnalysis\n{\npublic:\n\n  template <class T > struct Result\n  {\n    std::vector< std::vector<T> > components;\n    std::vector<T> singularValues;\n  };\n\n  // Main functor ------------------------------------------------------\n\n  template <class T> Result<T> operator()( const std::vector< std::vector<T> >& data )\n  {\n#ifdef ALEPH_WITH_EIGEN\n    if( data.empty() )\n      return {};\n\n    auto n = data.size();\n    auto m = data.front().size();\n\n    using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n    using Vector = Eigen::Matrix<T, 1, Eigen::Dynamic>;\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    Matrix M(n,m);\n\n    for( std::size_t row = 0; row < n; row++ )\n      M.row( Index(row) ) = Vector::Map( &data[row][0], Index(m) );\n\n    M  = M.rowwise() - M.colwise().mean();\n    M /= std::sqrt( static_cast<T>( m ) );\n\n    Eigen::JacobiSVD<Matrix> svd( M, Eigen::ComputeThinV );\n\n    Result<T> result;\n\n    {\n      auto&& singularValues = svd.singularValues();\n      result.singularValues.reserve( static_cast<std::size_t>( singularValues.size() ) );\n\n      for( decltype( singularValues.size() ) i = 0; i < singularValues.size(); i++ )\n        result.singularValues.push_back( singularValues( Index(i) ) );\n    }\n\n    {\n      auto numSingularVectors = std::min( n, m );\n      auto dimension          = m;\n\n      result.components.resize( numSingularVectors,\n                                std::vector<T>() );\n\n      auto&& V = svd.matrixV();\n\n      for( decltype(numSingularVectors) i = 0; i < numSingularVectors; i++ )\n      {\n        auto&& column = V.col( Index(i) );\n        result.components[i].assign( column.data(), column.data() + dimension );\n      }\n    }\n\n    return result;\n\n#else\n  // to quiet compiler warnings\n  (void) data;\n  return {};\n#endif\n  }\n};\n\n} // namespace math\n\n} // namespace aleph\n\n_Pragma( \"GCC diagnostic pop\" )\n\n#endif\n", "meta": {"hexsha": "ef7892f6134f97560313018fe549d8570250d6fd", "size": 2535, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/math/PrincipalComponentAnalysis.hh", "max_stars_repo_name": "eudoxos/Aleph", "max_stars_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2019-04-24T22:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:37:47.000Z", "max_issues_repo_path": "include/aleph/math/PrincipalComponentAnalysis.hh", "max_issues_repo_name": "eudoxos/Aleph", "max_issues_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2016-11-30T09:37:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-30T21:43:39.000Z", "max_forks_repo_path": "include/aleph/math/PrincipalComponentAnalysis.hh", "max_forks_repo_name": "eudoxos/Aleph", "max_forks_repo_head_hexsha": "874882c33a0e8429c74e567eb01525613fee0616", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-02T11:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T14:05:40.000Z", "avg_line_length": 23.0454545455, "max_line_length": 89, "alphanum_fraction": 0.6197238659, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5796430075976999}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2016 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 \"shortest_edge_and_midpoint.h\"\n#include \"circulation.h\"\n#include <iostream>\n#include <Eigen/LU>\n\nEigen::MatrixXd face_normals_dec;\nbool doPrint;\n\nIGL_INLINE void igl::shortest_edge_and_midpoint(\n  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{\n  cost = (V.row(E(e,0))-V.row(E(e,1))).norm();\n  p = 0.5*(V.row(E(e,0))+V.row(E(e,1)));\n}\n\nIGL_INLINE void igl::edgeErrorAndOptimalPlacement(\n\tconst int e,\n\tconst Eigen::MatrixXd & V,\n\tconst Eigen::MatrixXi & F,\n\tconst Eigen::MatrixXi & E,\n\tconst Eigen::VectorXi & EMAP,\n\tconst Eigen::MatrixXi & EF,\n\tconst Eigen::MatrixXi & EI,\n\tdouble & cost,\n\tEigen::RowVectorXd & p)\n{\n\tint v1 = E(e, 0);\n\tint v2 = E(e, 1);\n\tEigen::Matrix4d Q = Eigen::Matrix4d::Zero();\n\n\tstd::vector<int> N = circulation(e, true, EMAP, EF, EI);\n\tstd::vector<int> Nd = circulation(e, false, EMAP, EF, EI);\n\tN.insert(N.begin(), Nd.begin(), Nd.end());\n\n\tfor (auto i : N)\n\t{\n\t\tEigen::Vector3d normal = face_normals_dec.row(i).normalized();\n\t\t//std::cout << \"face \" << i << \" normal: \" << normal << std::endl;\n\t\tdouble d = -V.row(F.row(i)[0]) * normal;\n\t\tEigen::Vector4d p = Eigen::Vector4d(normal[0], normal[1], normal[2], d).transpose();\n\t\tEigen::Matrix4d Kp = p * (p.transpose());\n\t\tQ += Kp;\n\t}\n\tEigen::Matrix4d Qtag = Q;\n\tQtag(3, 0) = 0;\n\tQtag(3, 1) = 0;\n\tQtag(3, 2) = 0;\n\tQtag(3, 3) = 1;\n\n\tEigen::Vector4d vtag = Qtag.inverse() * Eigen::Vector4d(0, 0, 0, 1); \n\tp = Eigen::Vector3d(vtag[0], vtag[1], vtag[2]);\n\t//std::cout << \"p: \" << p << std::endl;\n\t//p = 0.5*(V.row(v1) + V.row(v2)); \n\n\tcost = vtag.transpose() *  Q * vtag;\n\tif(doPrint)\n\t\tstd::cout << \"edge \" << e << \", cost = \" << cost << \", new v position (\" << p << \")\" << std::endl;\n}\n", "meta": {"hexsha": "751e03b77cf255526b35cbcb06ff58f69c2f718d", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/shortest_edge_and_midpoint.cpp", "max_stars_repo_name": "epdaniel/vgp201-ass1", "max_stars_repo_head_hexsha": "d92074bb2d348a419843eafaa1049913392990ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "igl/shortest_edge_and_midpoint.cpp", "max_issues_repo_name": "epdaniel/vgp201-ass1", "max_issues_repo_head_hexsha": "d92074bb2d348a419843eafaa1049913392990ba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "igl/shortest_edge_and_midpoint.cpp", "max_forks_repo_name": "epdaniel/vgp201-ass1", "max_forks_repo_head_hexsha": "d92074bb2d348a419843eafaa1049913392990ba", "max_forks_repo_licenses": ["Apache-2.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.9594594595, "max_line_length": 100, "alphanum_fraction": 0.6197564276, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.579639136896443}}
{"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\nvoid linalg_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::vector<double> *residual)\n{\n    // check matrix for zero column\n    int nonzero_found = 0;\n    for(size_t j=0; j<A.size2(); j++) {\n        nonzero_found = 0;\n        for(size_t i=0; i<A.size1(); i++) {\n            if(fabs(A(i,j))>0) {\n                nonzero_found = 1;\n            }\n        }\n        if(nonzero_found==0) {\n            throw \"qrsolve_zero_column_in_matrix\";\n        }\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    gsl_vector *tau = gsl_vector_alloc (x.size());\n    gsl_vector *gsl_residual = gsl_vector_alloc (b.size());\n\n    gsl_linalg_QR_decomp (&m.matrix, tau);\n\n    gsl_linalg_QR_lssolve (&m.matrix, tau, &gb.vector, gsl_x, gsl_residual);\n\n    for (size_t i =0 ; i < x.size(); i++)\n        x(i) = gsl_vector_get(gsl_x, i);\n\n    if(residual)\n        for (size_t i =0 ; i < residual->size(); i++)\n            (*residual)(i) = gsl_vector_get(gsl_residual, i);\n\n    gsl_vector_free (gsl_x);\n    gsl_vector_free (tau);\n    gsl_vector_free (gsl_residual);\n}\n\nvoid linalg_constrained_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::matrix<double> &constr)\n{\n    // check matrix for zero column\n    int nonzero_found = 0;\n    for(size_t j=0; j<A.size2(); j++) {\n        nonzero_found = 0;\n        for(size_t i=0; i<A.size1(); i++) {\n            if(fabs(A(i,j))>0) {\n                nonzero_found = 1;\n            }\n        }\n        if(nonzero_found==0) {\n            throw std::runtime_error(\"constrained_qrsolve_zero_column_in_matrix\");\n        }\n    }\n\n    // Transpose constr:\n    constr = trans(constr);\n\n    const int N = b.size();\n    const int ngrid = x.size()/2;\n\n    // temporary variables\n    ub::matrix<double> Q(2*ngrid, 2*ngrid);       // Q matrix: QR decomposition of trans(B)\n    ub::matrix<double> Q_k(2*ngrid, 2*ngrid);\n    ub::identity_matrix<double> I (2*ngrid);\n    ub::vector<double> v(2*ngrid);\n\n    Q = ub::zero_matrix<double>(2*ngrid, 2*ngrid);\n    Q_k = ub::zero_matrix<double>(2*ngrid, 2*ngrid);\n    v = ub::zero_vector<double>(2*ngrid);\n\n    double *tmp = & constr(0,0);\n    gsl_matrix_view gsl_constr\n      = gsl_matrix_view_array (tmp, constr.size1(), constr.size2());\n\n    tmp = &b(0);\n    gsl_vector_view gsl_b\n         = gsl_vector_view_array (tmp, b.size());\n\n\n    gsl_vector *tau_qr = gsl_vector_alloc (ngrid);\n\n    gsl_linalg_QR_decomp (&gsl_constr.matrix, tau_qr);\n\n    Q = I;\n\n    for (int k = ngrid; k > 0 ; k--) {\n\n        for (int icout = 0; icout < k - 1; icout++) {\n             v(icout) = 0;\n        }\n        v(k - 1) = 1.0;\n\n        for (int icout = k; icout < 2*ngrid; icout++) {\n             v(icout) = gsl_matrix_get(&gsl_constr.matrix, icout, k - 1 );\n        }\n\n        Q_k = I - gsl_vector_get(tau_qr, k - 1 ) * outer_prod ( v, v );\n        Q = prec_prod(Q, Q_k);\n\n    }\n\n    Q = trans(Q);\n    gsl_vector_free (tau_qr);\n\n    // Calculate A * Q and store the result in A\n    A = prec_prod(A, Q);\n\n\n    // A = [A1 A2], so A2 is just a block of A\n    ub::matrix<double> A2 = ub::matrix_range<ub::matrix<double> >(A,\n            ub::range (0, N), ub::range (ngrid, 2*ngrid)\n         );\n\n    tmp = &A2(0,0);\n    gsl_matrix_view gsl_A2\n         = gsl_matrix_view_array (tmp, A2.size1(), A2.size2());\n   \n        \n    gsl_vector *z = gsl_vector_alloc (ngrid);\n    gsl_vector *tau_solve = gsl_vector_alloc (ngrid);  // already done!\n    gsl_vector *residual = gsl_vector_alloc (N);\n\n    gsl_linalg_QR_decomp (&gsl_A2.matrix, tau_solve);\n    gsl_linalg_QR_lssolve (&gsl_A2.matrix, tau_solve, &gsl_b.vector, z, residual);\n\n    // Next two cycles assemble vector from y (which is zero-vector) and z\n    // (which we just got by gsl_linalg_QR_lssolve)\n\n    for (int i = 0; i < ngrid; i++ ) {\n           x[i] = 0.0;\n    }\n\n    for (int i = ngrid; i < 2 * ngrid; i++ ) {\n           x[i] = gsl_vector_get(z, i - ngrid);\n    }\n\n    // To get the final answer this vector should be multiplied by matrix Q\n    // TODO: here i changed the sign, check again! (victor)\n    x = -prec_prod( Q, x );\n\n    gsl_vector_free (z);\n    gsl_vector_free (tau_solve);\n    gsl_vector_free (residual);\n}\n\n}}\n", "meta": {"hexsha": "d0b681cf314c08c2ac43e9d6f044b27cd94516a8", "size": 5214, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/gsl/qrsolve.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/qrsolve.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/qrsolve.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": 28.8066298343, "max_line_length": 128, "alphanum_fraction": 0.6020329881, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5796391317011858}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n//! \\file tylorintegrator.hpp Solution for Problem 3c, implementing TaylorIntegrator class\n\n//! \\brief Implements an autonomous ODE integrator based on Taylor expansion\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate <class State>\nclass TaylorIntegrator {\npublic:\n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a Taylor expansion method\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function (and its derivatives).\n    //! \\param[in] odefun function handle for rhs f and its derivatives\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function>\n    std::vector<State> solve(const Function &odefun, double T, const State & y0, unsigned int N) const {\n        // TODO: solve the autonomous ODE using a Taylor expansion method and suitable call to step\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the Taylor expansion for the solution of the autonomous ODE\n    //! Compute a single explicit step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs and its derivatives.\n    //! \\param[in] odefun function handle for rhs f and the derivatives\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial state \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function>\n    void step(const Function &odefun, double h,\n              const State & y0, State & y1 /* TODO: optional: modify step signature */ ) const {\n        // TODO: implement a single step of the Taylor expansion method using provided odefunction\n    }\n    \n};\n", "meta": {"hexsha": "130e4f994908bf138274ace185badfc749269930", "size": 2174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS12/solutions_ps12/taylorintegrator_template.hpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS12/templates_ps12/taylorintegrator_template.hpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS12/templates_ps12/taylorintegrator_template.hpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2916666667, "max_line_length": 122, "alphanum_fraction": 0.6853725851, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.5796391235509163}}
{"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_BROYDEN_INCLUDE\n#define ITL_BROYDEN_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/itl/utility/exception.hpp>\n\nnamespace itl {\n\n/// Update of Hessian matrix for e.g. Quasi-Newton by Broyden formula\nstruct broyden\n{\n    /// \\f$ H_{k+1}=B_{k+1}^{-1}=H_k+\\frac{(s_k-H_k\\cdot y_k)\\cdot y_k^T\\cdot H_k}{y_k^T\\cdot H_k\\cdot s_k} \\f$\n    template <typename Matrix, typename Vector>\n    void operator() (Matrix& H, const Vector& y, const Vector& s)\n    {\n\ttypedef typename mtl::Collection<Vector>::value_type value_type;\n\tassert(num_rows(H) == num_cols(H));\n\n\tVector     h(H * y), d(s - h);\n\tvalue_type gamma= 1 / dot(y, h);\n\tMTL_THROW_IF(gamma == 0.0, unexpected_orthogonality());\n\tMatrix     A(gamma * d * trans(y)),\n\t           H2(H + A * H);\n\tswap(H2, H); // faster than H= H2\n   }\n}; \n\n\n\n} // namespace itl\n\n#endif // ITL_BROYDEN_INCLUDE\n", "meta": {"hexsha": "40b34703927ea71f215f303f80c655d26796c286", "size": 1382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/updater/broyden.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/itl/updater/broyden.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/itl/updater/broyden.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": 30.0434782609, "max_line_length": 111, "alphanum_fraction": 0.6808972504, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5795076595503645}}
{"text": "\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <ceres/loss_function.h>\n#include <ceres/autodiff_cost_function.h>\n\n#include <Eigen/Jacobi>\n#include <Eigen/SVD>\n#include <Eigen/LU>\n\n#include <iostream>\n\n#include <opencv2/core/utility.hpp>\n\n#include <sphericalsfm/sfm.h>\n#include <sphericalsfm/so3.h>\n\nnamespace sphericalsfm {\n\n    class ParallelTriangulator : public cv::ParallelLoopBody\n    {\n    public:\n        ParallelTriangulator( SfM &_sfm ) :sfm(_sfm) { }\n        virtual void operator()(const cv::Range &range) const CV_OVERRIDE\n        {\n            for ( int j = range.start; j < range.end; j++ )\n            {\n                if ( !sfm.points.exists(j) ) continue;\n                \n                int firstcam = -1;\n                int lastcam = -1;\n                \n                int nobs = 0;\n                for ( int i = 0; i < sfm.numCameras; i++ )\n                {\n                    if ( !sfm.cameras.exists(i) ) continue;\n                    if ( !( sfm.observations.exists(i,j) ) ) continue;\n                    if ( firstcam == -1 ) firstcam = i;\n                    lastcam = i;\n                    nobs++;\n                }\n\n                sfm.SetPoint( j, Eigen::Vector3d::Zero() );\n                if ( nobs < 3 ) continue;\n\n                Eigen::MatrixXd A( nobs*2, 4 );\n                 \n                int n = 0;\n                for ( int i = 0; i < sfm.numCameras; i++ )\n                {\n                    if ( !sfm.cameras.exists(i) ) continue;\n                    if ( !( sfm.observations.exists(i,j) ) ) continue;\n\n                    Observation vec = sfm.observations(i,j);\n\n                    Eigen::Vector2d point(vec(0)/sfm.intrinsics.focal,vec(1)/sfm.intrinsics.focal);\n                    Eigen::Matrix4d P = sfm.GetPose(i).P;\n                    \n                    A.row(2*n+0) = P.row(2) * point[0] - P.row(0);\n                    A.row(2*n+1) = P.row(2) * point[1] - P.row(1);\n                    n++;\n                }\n\n                Eigen::JacobiSVD<Eigen::MatrixXd> svdA(A,Eigen::ComputeFullV);\n                Eigen::Vector4d Xh = svdA.matrixV().col(3);\n                Eigen::Vector3d X = Xh.head(3)/Xh(3);\n\n                sfm.SetPoint( j, X );\n            }\n        }\n        ParallelTriangulator& operator=(const ParallelTriangulator &) {\n            return *this;\n        }\n    private:\n        SfM &sfm;\n    };\n    \n    struct ReprojectionError\n    {\n        ReprojectionError( double _focal, double _x, double _y )\n        : focal(_focal), x(_x), y(_y)\n        {\n            \n        }\n        \n        template <typename T>\n        bool operator()(const T* const camera_t,\n                        const T* const camera_r,\n                        const T* const point,\n                        T* residuals) const\n        {\n            // transform from world to camera\n            T p[3];\n            ceres::AngleAxisRotatePoint(camera_r, point, p);\n            p[0] += camera_t[0]; p[1] += camera_t[1]; p[2] += camera_t[2];\n            \n            // projection\n            T xp = p[0] / p[2];\n            T yp = p[1] / p[2];\n            \n            // intrinsics\n            T fxp = T(focal) * xp;\n            T fyp = T(focal) * yp;\n            \n            // residuals\n            residuals[0] = fxp - T(x);\n            residuals[1] = fyp - T(y);\n            \n            return true;\n        }\n        \n        double focal, x, y;\n    };\n    \n    SfM::SfM( const Intrinsics &_intrinsics )\n    : intrinsics( _intrinsics ),\n    numCameras( 0 ),\n    numPoints( 0 ),\n    nextCamera( -1 ),\n    nextPoint( 0 )\n    {\n    }\n\n    double * SfM::GetCameraPtr( int camera )\n    {\n        return (double*)&cameras(camera);\n    }\n\n    double * SfM::GetPointPtr( int point )\n    {\n        return (double*)&points(point);\n    }\n\n    int SfM::AddCamera( const Pose &initial_pose, const std::string &path )\n    {\n        nextCamera++;\n        numCameras++;\n        \n        cameras( nextCamera ).head(3) = initial_pose.t;\n        cameras( nextCamera ).tail(3) = initial_pose.r;\n        paths( nextCamera ) = path;\n        rotationFixed( nextCamera ) = false;\n        translationFixed( nextCamera ) = false;\n        \n        return nextCamera;\n    }\n\n    int SfM::AddPoint( const Point &initial_position, const cv::Mat &descriptor )\n    {\n        numPoints++;\n        \n        points( nextPoint ) = initial_position;\n        pointFixed( nextPoint ) = false;\n        \n        cv::Mat descriptor_copy;\n        descriptor.copyTo( descriptor_copy );\n        descriptors( nextPoint ) = descriptor_copy;\n\n        return nextPoint++;\n    }\n\n    void SfM::MergePoint( int point1, int point2 )\n    {\n        for ( int i = 0; i < numCameras; i++ )\n        {\n            if ( !cameras.exists(i) ) continue;\n            if ( !( observations.exists(i,point2) ) ) continue;\n            \n            observations(i,point1) = observations(i,point2);\n        }\n        \n        RemovePoint( point2 );\n    }\n\n    void SfM::AddObservation( int camera, int point, const Observation &observation )\n    {\n        observations(camera,point) = observation;\n    }\n\n    void SfM::AddMeasurement( int i, int j, const Pose &measurement )\n    {\n        measurements(i,j) = measurement;\n    }\n\n    bool SfM::GetMeasurement( int i, int j, Pose &measurement )\n    {\n        if ( !measurements.exists(i,j) ) return false;\n\n        measurement = measurements(i,j);\n        \n        return true;\n    }\n\n    bool SfM::GetObservation( int camera, int point, Observation &observation )\n    {\n        if ( !observations.exists(camera,point) ) return false;\n\n        observation = observations(camera,point);\n        \n        return true;\n    }\n\n    void SfM::Retriangulate()\n    {\n        cv::parallel_for_(cv::Range(0,numPoints), [&](const cv::Range &range){\n        //for ( int j = 0; j < numPoints; j++ )\n        for ( int j = range.start; j < range.end; j++ )\n        {\n            if ( !points.exists(j) ) continue;\n            \n            int firstcam = -1;\n            int lastcam = -1;\n            \n            int nobs = 0;\n            for ( int i = 0; i < numCameras; i++ )\n            {\n                if ( !cameras.exists(i) ) continue;\n                if ( !( observations.exists(i,j) ) ) continue;\n                if ( firstcam == -1 ) firstcam = i;\n                lastcam = i;\n                nobs++;\n            }\n\n            SetPoint( j, Eigen::Vector3d::Zero() );\n            if ( nobs < 3 ) continue;\n\n            Eigen::MatrixXd A( nobs*2, 4 );\n             \n            int n = 0;\n            for ( int i = 0; i < numCameras; i++ )\n            {\n                if ( !cameras.exists(i) ) continue;\n                if ( !( observations.exists(i,j) ) ) continue;\n\n                Observation vec = observations(i,j);\n\n                Eigen::Vector2d point(vec(0)/intrinsics.focal,vec(1)/intrinsics.focal);\n                Eigen::Matrix4d P = GetPose(i).P;\n                \n                A.row(2*n+0) = P.row(2) * point[0] - P.row(0);\n                A.row(2*n+1) = P.row(2) * point[1] - P.row(1);\n                n++;\n            }\n\n            Eigen::JacobiSVD<Eigen::MatrixXd> svdA(A,Eigen::ComputeFullV);\n            Eigen::Vector4d Xh = svdA.matrixV().col(3);\n            Eigen::Vector3d X = Xh.head(3)/Xh(3);\n\n            SetPoint( j, X );\n        }\n        });\n    }\n\n    void SfM::PreOptimize()\n    {\n        loss_function = new ceres::CauchyLoss( 2.0 );\n    }\n\n    void SfM::ConfigureSolverOptions( ceres::Solver::Options &options )\n    {\n        options.minimizer_type = ceres::TRUST_REGION;\n        options.linear_solver_type = ceres::SPARSE_SCHUR;\n        options.max_num_iterations = 1000;\n        options.max_num_consecutive_invalid_steps = 100;\n        options.minimizer_progress_to_stdout = true;\n        options.num_threads = 16;\n    }\n\n    void SfM::AddResidual( ceres::Problem &problem, int camera, int point )\n    {\n        Observation vec = observations(camera,point);\n        \n        ReprojectionError *reproj_error = new ReprojectionError(intrinsics.focal,vec(0),vec(1));\n        ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<ReprojectionError, 2, 3, 3, 3>(reproj_error);\n        problem.AddResidualBlock(cost_function, loss_function, GetCameraPtr(camera), GetCameraPtr(camera)+3, GetPointPtr(point) );\n\n        if ( translationFixed( camera ) ) problem.SetParameterBlockConstant( GetCameraPtr(camera) );\n        if ( rotationFixed( camera ) ) problem.SetParameterBlockConstant( GetCameraPtr(camera)+3 );\n        if ( pointFixed( point ) ) problem.SetParameterBlockConstant( GetPointPtr(point) );\n    }\n\n    bool SfM::Optimize()\n    {\n        if ( numCameras == 0 || numPoints == 0 ) return false;\n        \n        ceres::Problem problem;\n        \n        PreOptimize();\n        \n        bool added_one_camera = false;\n        \n        std::cout << \"\\tBuilding BA problem...\\n\";\n\n        for ( int j = 0; j < numPoints; j++ )\n        {\n            if ( !points.exists(j) ) continue;\n            if ( points(j).norm() == 0 ) continue;\n            \n            int nobs = 0;\n            for ( int i = 0; i < numCameras; i++ )\n            {\n                if ( !cameras.exists(i) ) continue;\n                if ( !( observations.exists(i,j) ) ) continue;\n                \n                nobs++;\n            }\n            \n            if ( nobs < 3 ) continue;\n            for ( int i = 0; i < numCameras; i++ )\n            {\n                if ( !cameras.exists(i) ) continue;\n                if ( !( observations.exists(i,j) ) ) continue;\n\n                AddResidual( problem, i, j );\n                added_one_camera = true;\n            }\n        }\n            \n        if ( !added_one_camera ) {\n            std::cout << \"didn't add any cameras\\n\";\n            return false;\n        }\n        \n        std::cout << \"Running optimizer...\\n\";\n        std::cout << \"\\t\" << problem.NumResiduals() << \" residuals\\n\";\n\n        ceres::Solver::Options options;\n        ConfigureSolverOptions( options );\n        ceres::Solver::Summary summary;\n        ceres::Solve(options, &problem, &summary);\n        std::cout << summary.FullReport() << \"\\n\";\n        if ( summary.termination_type == ceres::FAILURE )\n        {\n            std::cout << \"error: ceres failed.\\n\";\n            exit(1);\n        }\n        \n        PostOptimize();\n        \n        return ( summary.termination_type == ceres::CONVERGENCE );\n    }\n\n    void SfM::PostOptimize()\n    {\n        \n    }\n    \n    void SfM::Apply( const Pose &pose )\n    {\n        // x = PX\n        // X -> pose*X\n        // x = P' * (pose*X)\n        // x = (P*poseinv) * (pose*X)\n        Pose poseinv = pose.inverse();\n        for ( int i = 0; i < numCameras; i++ )\n        {\n            Pose campose = GetPose(i);\n            campose.postMultiply( poseinv );\n            SetPose( i, campose );\n        }\n        for ( int j = 0; j < numPoints; j++ )\n        {\n            Point X = GetPoint(j);\n            X = pose.apply(X);\n            SetPoint( j, X );\n        }\n    }\n\n    void SfM::Apply( double scale )\n    {\n        for ( int i = 0; i < numCameras; i++ )\n        {\n            Pose campose = GetPose(i);\n            campose.t *= scale;\n            campose.P.block<3,1>(0,3) = campose.t;\n            SetPose( i, campose );\n        }\n        for ( int j = 0; j < numPoints; j++ )\n        {\n            Point X = GetPoint(j);\n            X *= scale;\n            SetPoint( j, X );\n        }\n    }\n\n    void SfM::Unapply( const Pose &pose )\n    {\n        // x = PX\n        // X -> poseinv*X\n        // x = P' * (poseinv*X)\n        // x = (P*pose) * (poseinv*X)\n        for ( int i = 0; i < numCameras; i++ )\n        {\n            Pose campose = GetPose(i);\n            campose.postMultiply( pose );\n            SetPose( i, campose );\n        }\n        Pose poseinv = pose.inverse();\n        for ( int j = 0; j < numPoints; j++ )\n        {\n            Point X = GetPoint(j);\n            X = poseinv.apply(X);\n            SetPoint( j, X );\n        }\n    }\n\n    Pose SfM::GetPose( int camera )\n    {\n        if ( !cameras.exists(camera) ) return Pose();\n        \n        return Pose( cameras( camera ).head(3), cameras( camera ).tail(3) );\n    }\n\n    void SfM::SetPose( int camera, const Pose &pose )\n    {\n        cameras( camera ).head(3) = pose.t;\n        cameras( camera ).tail(3) = pose.r;\n    }\n\n    Point SfM::GetPoint( int point )\n    {\n        if ( !points.exists( point ) ) return Point(0,0,0);\n        return points( point );\n    }\n\n    void SfM::SetPoint( int point, const Point &position )\n    {\n        points( point ) = position;\n    }\n\n    void SfM::RemovePoint( int point )\n    {\n        for ( int i = 0; i < numCameras; i++ )\n        {\n            observations.erase(i,point);\n        }\n        points.erase( point );\n        descriptors.erase( point );\n    }\n\n    void SfM::RemoveCamera( int camera )\n    {\n        cameras.erase(camera);\n        observations.erase(camera);\n        \n        for ( int j = 0; j < numPoints; j++ )\n        {\n            int i = 0;\n            for ( ; i < numCameras; i++ )\n            {\n                if ( observations.exists(i,j) ) break;\n            }\n            if ( i == numCameras ) points.erase(j);\n        }\n    }\n\n    void SfM::WritePoses( const std::string &path, const std::vector<int> &indices )\n    {\n        assert(indices.size() == numCameras);\n        FILE *f = fopen( path.c_str(), \"w\" );\n        \n        for ( int i = 0; i < numCameras; i++ )\n        {\n            fprintf(f,\"%d \",indices[i]);\n            Camera camera = cameras(i);\n            for ( int j = 0; j < 6; j++ )\n            {\n                fprintf(f,\"%.15lf \",camera(j));\n            }\n            fprintf(f,\"\\n\");\n        }\n\n        fclose(f);\n    }\n    \n    void SfM::WritePointsOBJ( const std::string &path )\n    {\n        FILE *f = fopen( path.c_str(), \"w\" );\n\n        std::vector<int> nobs(numPoints);\n        std::vector<double> distances(numPoints);\n        for ( int j = 0; j < numPoints; j++ )\n        {\n            nobs[j] = 0;\n        }\n        \n        for ( int i = 0; i < numCameras; i++ )\n        {\n            Pose pose = GetPose(i);\n            Eigen::Vector3d center = pose.getCenter();\n            \n            for ( int j = 0; j < numPoints; j++ )\n            {\n                if ( !points.exists(j) ) continue;\n                if ( !observations.exists(i,j) ) continue;\n                \n                nobs[j]++;\n                distances[j] = (GetPoint(j)-center).norm();\n            }\n        }\n        \n        for ( int i = 0; i < numPoints; i++ )\n        {\n            if ( !points.exists(i) ) continue;\n            \n            if ( distances[i] > 2000. ) continue;\n            Point X = GetPoint(i);\n            if ( X.norm() == 0 ) continue;\n            fprintf(f,\"v %0.15lf %0.15lf %0.15lf\\n\", X(0), X(1), X(2) );\n        }\n        \n        fclose( f );\n    }\n\n    void SfM::WriteCameraCentersOBJ( const std::string &path )\n    {\n        FILE *f = fopen( path.c_str(), \"w\" );\n        \n        for ( int i = 0; i < numCameras; i++ )\n        {\n            Pose pose = GetPose(i);\n            Eigen::Vector3d center = pose.getCenter();\n            fprintf(f,\"v %0.15lf %0.15lf %0.15lf\\n\", center(0), center(1), center(2) );\n        }\n        \n        fclose( f );\n    }\n}\n", "meta": {"hexsha": "a98e05e46ac6f535859048b887f506c141c56cff", "size": 15277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sfm.cpp", "max_stars_repo_name": "jonathanventura/spherical-sfm", "max_stars_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T15:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T06:27:32.000Z", "max_issues_repo_path": "src/sfm.cpp", "max_issues_repo_name": "jonathanventura/spherical-sfm", "max_issues_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-09T06:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T07:26:47.000Z", "max_forks_repo_path": "src/sfm.cpp", "max_forks_repo_name": "jonathanventura/spherical-sfm", "max_forks_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:30:46.000Z", "avg_line_length": 28.8790170132, "max_line_length": 130, "alphanum_fraction": 0.4692020685, "num_tokens": 3972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5795076439484251}}
{"text": "/**\n * @file fixed_point.hpp\n * @author Salvatore Cardamone\n * @brief Largely a replica of the Fixed Point Math Library developed by\n *        Peter Schregle. Pared down superfluous functionality and added some\n *        bits and pieces to make the code a little more useful for the types\n *        of calculation we do in tyche++.\n */\n#ifndef __TYCHEPLUSPLUS_FIXED_POINT_HPP\n#define __TYCHEPLUSPLUS_FIXED_POINT_HPP\n\n#include <cstddef>\n#include <boost/operators.hpp>\n#include <boost/type_index.hpp>\n#include \"utilities/type_promotion.hpp\"\n\nnamespace tycheplusplus {\n  \n/**\n * @class FixedPoint\n * @brief Generic fixed point functionality, allowing us to use this class as\n *        we would any other data type, like float or double. All integer\n *        arithmetic, so if there's no dedicated FPU, using FixedPoint as the\n *        real numerical type is probably advantageous. Furthermore, any\n *        high-level synthesis tools will hopefully pick up on the use of\n *        integer arithmetic and generate efficient implementations.\n *\n *        boost/operators.hpp provides a fairly remarkable set of\n *        functionalities, whereby operators can be automatically generated from\n *        a smaller set of operators. Deriving from the appropriate boost\n *        classes within boost/operators.hpp then gives us access to the full\n *        complement of operators.\n *\n *        For instance, deriving from boost::ordered_field_operators allows us\n *        to explicitly define the += operator, and obtain the + operator for\n *        free, without the need for additional boilerplate.\n *\n * @tparam B Data type used to store the fixed point number. It the type is\n *           signed, then the fixed point representation will be signed too.\n * @tparam I Number of integer bits.\n * @tparam F Number of fractional bits. Automatically determined from number of\n *           integer bits and number of available storage bits.\n */\ntemplate<typename B,\n         unsigned char I,\n         unsigned char F = std::numeric_limits<B>::digits - I>\nclass FixedPoint\n    : boost::ordered_field_operators<FixedPoint<B,I,F>,\n      boost::unit_steppable<FixedPoint<B,I,F>,\n      boost::shiftable<FixedPoint<B,I,F> > > >\n{\n\npublic:\n  /**\n   * @brief Class constructor.\n   * @param value Single precision value to initialise with.\n   */\n  FixedPoint(float value)\n      : value_(value * two_power_f_ + (value >= 0 ? 0.5 : -0.5)) {}\n\n  /**\n   * @brief Class constructor.\n   * @param value Double precision value to initialise with.\n   */\n  FixedPoint(double value)\n      : value_(value * two_power_f_ + (value >= 0 ? 0.5 : -0.5)) {\n  }\n\n  /**\n   * @brief Class constructor.\n   * @param value Single precision value to initialise with.\n   */\n  FixedPoint<B,I,F>& operator +=(FixedPoint<B,I,F> const& rhs) {\n    value_ += rhs.value_;\n    return *this;\n  }\n\n  /**\n   * @brief Subtraction assignment operator.\n   * @param rhs Value to subtract from lhs.\n   * @retval lhs - rhs.\n   */\n  FixedPoint<B,I,F>& operator -=(FixedPoint<B,I,F> const& rhs) {\n    value_ -= rhs.value_;\n    return *this;\n  }\n\n  /**\n   * @brief Multiplication assignment operator.\n   * @param rhs Value to multiply lhs by.\n   * @retval lhs * rhs.\n   */\n  FixedPoint<B,I,F>& operator *=(FixedPoint<B,I,F> const& rhs) {\n    value_ = (static_cast<typename TypePromotion<B>::type>\n\t      (value_) * rhs.value_) >> number_fractional_bits_;\n    return *this;\n  }\n\n  /**\n   * @brief Division assignment operator.\n   * @param rhs Value to divide lhs by.\n   * @retval lhs / rhs.\n   */\n  FixedPoint<B,I,F>& operator /=(FixedPoint<B,I,F> const& rhs) {\n    value_ = (static_cast<typename TypePromotion<B>::type>\n\t      (value_) << number_fractional_bits_) / rhs.value_;\n    return *this;\n  }\n  \n  /**\n   * @brief Convert the internal value of the fixed point object to a float.\n   * @retval Fixed point number cast to float.\n   */\n  float AsFloat() const {\n    return (float)value_ / two_power_f_;\n  }\n\n  /**\n   * @brief Convert the internal value of the fixed point object to a double.\n   * @retval Fixed point number cast to double.\n   */\n  double AsDouble() const {\n    return (double)value_ / two_power_f_;\n  }\n\n  /**\n   * @brief Print some information about the object.\n   */\n  void Print(std::ostream& stream) const {\n    stream << \" *** FixedPoint object\" << std::endl\n\t   << \"     \"\n\t   << (int)number_fractional_bits_ << \" fractional bits and \"\n\t   << (int)number_integer_bits_ << \" integer bits.\" << std::endl\n\t   << \"     Storage type: \"\n\t   << boost::typeindex::type_id<B>().pretty_name() << std::endl\n\t   << \"     Has Sign Bit: \"\n\t   << std::numeric_limits<B>::is_signed << std::endl\n\t   << \"     Stored Value: \" << std::hex << value_ << std::dec << std::endl\n\t   << \"     Floating Point: \" << AsDouble() << std::endl;\n  }\n\n  /**\n   * @brief Compute the exponential of a fixed point number.\n   *\n   *        This is fairly inefficient, utilising (I+F) integer multiplications.\n   *        The exponential is split into its integer and fractional parts:\n   *\n   *                         exp(i.f) = exp(i) * exp(f)\n   *\n   *        For the fractional part, we move down the fractional bits of the\n   *        argument, lookup the associated value for the exponential of the\n   *        fractional bit and multiply-accumulate if the bit is high, otherwise\n   *        it makes no contribution. So, for instance, e^{0.625} is equal to:\n   *\n   *                    1*exp(0.5) * 0*exp(0.25) * 1*exp(0.125)\n   *\n   *        the values of the exponential for which are already tabulated.\n   *        We compute the integer part in a similar fashion using the\n   *        integer part lookup table. If the argument is negative, we\n   *        divide-accumulate rather than multiply-accumulate.\n   *\n   *        We should implement a specialised Gaussian function, since the \n   *        integer part is only relevant over a much smaller dynamic range.\n   * @param arg The argument of the exponential function.\n   * @retval exp(arg).\n   */\n  friend FixedPoint<B,I,F> exp(FixedPoint<B,I,F> const& arg) {\n\n    FixedPoint<B,I,F> result(1.0);\n\n    // We start from the MSB in the fractional part and work our way down the\n    // number of fractional bits\n    for (int i_frac = F-1; i_frac >= 0; --i_frac) {\n      if (arg.value_ & 1ULL<<i_frac) {\n\tresult.value_ =\n\t  (static_cast<typename TypePromotion<B>::type>(result.value_) *\n\t   (exp_frac_lut[F-i_frac-1] >> (32-F))) >> F;\n      }\n    }\n\n    // Need to find out whether we're dividing or multiplying for the\n    // integer part\n    bool is_negative =\n      std::numeric_limits<B>::is_signed && ((1ULL << (I+F-1)) & arg.value_);\n\n    // If the number is negative, we need to do some two's complement to get the\n    // integer part then work our way up from the LSB\n    if (is_negative) {\n      B integer_part = ~(arg.value_ >> F) + 1;\n      for (int i_int = 0; i_int<I; ++i_int) {\n\tif (integer_part & 1ULL<<i_int) {\n\t  result.value_ =\n\t    (static_cast<typename TypePromotion<B>::type>(result.value_) << F) /\n\t    (exp_int_lut[i_int] >> (32-F));\n\t}\n      }\n    // If the number is positive, we start from the MSB in the integer part and\n    // work our way up the number of integer bits\n    } else {\n      for (int i_int = F; i_int<(I+F); ++i_int) {\n\tif (arg.value_ & 1ULL<<i_int) {\n\t  result.value_ =\n\t    (static_cast<typename TypePromotion<B>::type>(result.value_) *\n\t     (exp_int_lut[i_int-F]) >> (32-F)) >> F;\n\t}\n      }\n    }\n    \n    return result;\n    \n  }\n  \nprivate:\n  // Alias for the sake of simplifying functions\n  B value_;\n  static constexpr unsigned char number_integer_bits_ = (unsigned char)I;\n  static constexpr unsigned char number_fractional_bits_ = (unsigned char)F;\n  static constexpr B two_power_f_ = (1ULL << F);\n\n  // exp[0.5], exp[0.25], exp[0.125], etc... in Q32.32\n  static constexpr unsigned long exp_frac_lut[32] = {\n    0x00000001a61298e2, 0x0000000148b5e3c4, 0x000000012216045b,\n    0x000000011082b578, 0x0000000108205601, 0x0000000104080ab5,\n    0x0000000102020156, 0x000000010100802b, 0x0000000100802005,\n    0x0000000100400801, 0x0000000100200200, 0x0000000100100080,\n    0x0000000100080020, 0x0000000100040008, 0x0000000100020002,\n    0x0000000100010001, 0x0000000100008000, 0x0000000100004000,\n    0x0000000100002000, 0x0000000100001000, 0x0000000100000800,\n    0x0000000100000400, 0x0000000100000200, 0x0000000100000100,\n    0x0000000100000080, 0x0000000100000040, 0x0000000100000020,\n    0x0000000100000010, 0x0000000100000008, 0x0000000100000004,\n    0x0000000100000002, 0x0000000100000001\n  };\n  // exp[1], exp[2], exp[4], etc... in Q32.32\n  static constexpr unsigned long exp_int_lut[32] = {\n    0x00000002b7e15163, 0x0000000763992e35, 0x0000003699205c4e,\n    0x00000ba4f53ea386, 0x0087975e85400100, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff,\n    0xffffffffffffffff, 0xffffffffffffffff\n  };\n\n};\n  \n}\n\n#endif /* #ifndef __TYCHEPLUSPLUS_FIXED_POINT_HPP */\n\n\n", "meta": {"hexsha": "6484fbd2038edd68be4aa81f7f0a896b588d48c5", "size": 9390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/fixed_point.hpp", "max_stars_repo_name": "savcardamone/tyche-", "max_stars_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utilities/fixed_point.hpp", "max_issues_repo_name": "savcardamone/tyche-", "max_issues_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-28T13:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-29T10:30:33.000Z", "max_forks_repo_path": "src/utilities/fixed_point.hpp", "max_forks_repo_name": "savcardamone/tyche", "max_forks_repo_head_hexsha": "ea89edea89a607291e4fe0ba738d75522f54dc1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6796875, "max_line_length": 80, "alphanum_fraction": 0.6711395101, "num_tokens": 2613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.5793066965650577}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <limits>\n#include <cassert>\n#include <map>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> Graph;\n\nvoid testcase()\n{\n  int n, e, s, source_node, target_node;\n  std::cin >> n >> e >> s >> source_node >> target_node;\n  assert(n >= 1 && n <= 500 && e >= 1 && s >= 1 && s <= 10);\n  assert(source_node >= 0 && source_node < n);\n  assert(target_node >= 0 && target_node < n);\n\n  Graph G(n);\n  auto shared_weights = boost::get(boost::edge_weight, G);\n  int infinite_weight = std::numeric_limits<int>::max();\n  std::vector<std::map<Graph::edge_descriptor, int>> weights_by_species(s);\n  for (int i = 0; i < e; i++)\n  {\n    int a, b;\n    std::cin >> a >> b;\n    Graph::edge_descriptor edge = boost::add_edge(a, b, infinite_weight, G).first;\n\n    for (int j = 0; j < s; j++)\n    {\n      int w;\n      std::cin >> w;\n      weights_by_species.at(j).insert(std::make_pair(edge, w));\n    }\n  }\n\n  for (int i = 0; i < s; i++)\n  {\n    int hive_location;\n    std::cin >> hive_location;\n    auto species_weight_map = boost::make_assoc_property_map(weights_by_species.at(i));\n    std::vector<Graph::vertex_descriptor> predecessors(n);\n    boost::prim_minimum_spanning_tree(G, boost::make_iterator_property_map(predecessors.begin(), boost::get(boost::vertex_index, G)), boost::weight_map(species_weight_map).root_vertex(hive_location));\n\n    for (Graph::vertex_descriptor a = 0; a < Graph::vertex_descriptor(n); a++)\n    {\n      Graph::vertex_descriptor b = predecessors.at(a);\n      if (a == b)\n      {\n        continue;\n      }\n      assert(boost::edge(a, b, G).second);\n      Graph::edge_descriptor edge = boost::edge(a, b, G).first;\n      int &min_weight = shared_weights[edge];\n      min_weight = std::min({min_weight, species_weight_map[edge]});\n    }\n  }\n\n  Graph G_finite(n);\n  for (auto edge_iterators = boost::edges(G); edge_iterators.first != edge_iterators.second; edge_iterators.first++)\n  {\n    auto edge = *edge_iterators.first;\n    int w = shared_weights[edge];\n    assert(w >= 0);\n    if (w != infinite_weight)\n    {\n      boost::add_edge(edge.m_source, edge.m_target, w, G_finite);\n    }\n  }\n\n  std::vector<int> distances(n);\n  boost::dijkstra_shortest_paths(G_finite, boost::vertex(source_node, G_finite), boost::distance_map(boost::make_iterator_property_map(distances.begin(), boost::get(boost::vertex_index, G_finite))));\n\n  std::cout << distances.at(target_node) << \"\\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": "b42edb6834d42ab0d4d4fb9b28d3c01038a42a50", "size": 2795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-04/ant-challenge/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-04/ant-challenge/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-04/ant-challenge/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.404494382, "max_line_length": 200, "alphanum_fraction": 0.6515205725, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5793046179748539}}
{"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\n#include <random>\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n\n#define LOG_2 0.69314718055994529\n#define LOG_PI 1.1447298858494002\n#define LOG_2PI 1.8378770664093453\n#define LOG_4PI 2.5310242469692907\n\ntemplate<typename T> \ninline T logBesselI(T nu, T x)\n{\n  //TODO link against boost\n  // for large values of x besselI \\approx exp(x)/sqrt(2 PI x)\n//  if(x>100.)  return x - 0.5*log(2.*M_PI*x);\n//  return log(std::cyl_bessel_i(nu,x));\n  return x - 0.5*LOG_2PI -0.5*log(x);\n};\n\ntemplate<typename T> \ninline T logxOverSinhX(T x) {\n  if (fabs(x) < 1e-9) \n    return 0.;\n  else\n    return log(x)-log(sinh(x));\n}\ntemplate<typename T> \ninline T xOverSinhX(T x) {\n  if (fabs(x) < 1e-9) \n    return 1.;\n  else\n    return x/sinh(x);\n}\ntemplate<typename T> \ninline T xOverTanPiHalfX(T x) {\n  if (fabs(x) < 1e-9) \n    return 2./M_PI;\n  else\n    return x/tan(x*M_PI*0.5);\n}\n\ntemplate<typename T> \ninline T logSumExp(const Eigen::Matrix<T,Eigen::Dynamic,1>& logX) {\n  T logMax = logX.maxCoeff();\n  return log((logX.array()-logMax).exp().sum()) + logMax;\n}\n\ntemplate <typename T, uint32_t D>\ninline T MLEstimateTau(const Eigen::Matrix<T,3,1>& xSum, const\n    Eigen::Matrix<T,3,1>& mu, T count) {\n  // Need double precision to achive convergence; single is not enough.\n  double tau = 1.0;\n  double prevTau = 0.;\n  double eps = 1e-8;\n  double R = xSum.norm()/count;\n  while (fabs(tau - prevTau) > eps) {\n//    std::cout << \"tau \" << tau << \" R \" << R << std::endl;\n    double inv_tanh_tau = 1./tanh(tau);\n    double inv_tau = 1./tau;\n    double f = -inv_tau + inv_tanh_tau - R;\n    double df = inv_tau*inv_tau - inv_tanh_tau*inv_tanh_tau + 1.;\n    prevTau = tau;\n    tau -= f/df;\n  }\n  return tau;\n};\n\ntemplate<typename T, int D>\nclass vMF \n{\npublic:\n  vMF()\n    : mu_(0,0,1), tau_(0.), unif_(0.,1.), gauss_(0.,1.)\n  {}\n  vMF(const Eigen::Matrix<T,D,1>& mu, T tau)\n    : mu_(mu), tau_(tau), unif_(0.,1.), gauss_(0.,1.)\n  {}\n  vMF(const Eigen::Matrix<T,D,1>& tauMu)\n    : mu_(tauMu.normalized()), tau_(tauMu.norm()), unif_(0.,1.), gauss_(0.,1.)\n  {}\n  vMF(const vMF<T,D>& vmf)\n    : mu_(vmf.mu_), tau_(vmf.tau_), unif_(0.,1.), gauss_(0.,1.)\n  {}\n\n  T logPdf(const Eigen::Matrix<T,D,1>& x) const {\n    const T d = static_cast<T>(D);\n    if (tau_ < 1e-9) {\n      // TODO insert general formula here\n      return -LOG_4PI;\n    } else {\n      return (d/2. -1.)*log(tau_) - (d/2.)*LOG_2PI \n        - logBesselI<T>(d/2. -1.,tau_) + tau_*mu_.dot(x);\n    }\n  }\n\n  /// Use uniform distribution on the sphere as a proposal distribution\n  Eigen::Matrix<T,D,1> sample(std::mt19937& rnd) {\n//    std::cout << \"stating n sampling ------------ \" << std::endl;\n    // implemented using rejection sampling and proposals from a gaussian\n    Eigen::Matrix<T,D,1> x;\n    T pdf_g = -LOG_4PI;\n    // bound via maximum over vMF at mu\n    // TODO: dont know why I need to multiply by 2 here to get the\n    // correct samples (as seen in concentration estimates)\n    T M = 2.*tau_; \n    while(42) {\n      // sample from zero mean Gaussian \n      for (uint32_t d=0; d<D; d++) x[d] = gauss_(rnd);\n      x.normalize();\n      // rejection sampling (in log domain)\n      T u = log(unif_(rnd));\n      T pdf_f = 2.*tau_*x.dot(mu_); //this->logPdf(x);\n//      std::cout << pdf_f << \" \" << pdf_g << \" \" << M << \" \" << tau_ << std::endl;\n      if(u < pdf_f-(M+pdf_g)) break;\n    };\n    return x;\n  }\n\n\n  Eigen::Matrix<T,D,1> mu_;\n  T tau_;\nprivate:\n  std::uniform_real_distribution<T> unif_;\n  std::normal_distribution<T> gauss_;\n};\n\n\ntemplate<>\nfloat vMF<float,3>::logPdf(const Eigen::Matrix<float,3,1>& x) const {\n  if (tau_ < 1e-9) {\n    return -LOG_4PI;\n  } else {\n    return -LOG_2PI + log(tau_) + tau_*(mu_.dot(x)-1.) - log(1.-exp(-2.*tau_));\n//    return 0.5*LOG_PI - 0.5*LOG_2 + tau_*mu_.dot(x) + logxOverSinhX(tau_);\n  }\n}\n\ntemplate<>\nEigen::Matrix<float,3,1> vMF<float,3>::sample(std::mt19937& rnd) {\n  if (tau_ < 1e-10) {\n    return Eigen::Vector3f(gauss_(rnd), gauss_(rnd), gauss_(rnd)).normalized();\n  }\n  // https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf\n  // sample around (0,0,1)\n  Eigen::Vector2f v(gauss_(rnd), gauss_(rnd));\n  v.normalize();\n  const float u = unif_(rnd);\n  const float w = 1. + log(u+(1.-u)*exp(-2.*tau_))/tau_;\n  const float a = sqrtf(1.-w*w);\n  Eigen::Vector3f x(a*v(0), a*v(1), w);\n\n  // rotate to mu\n  Eigen::Vector3f axis = Eigen::Vector3f(0,0,1).cross(mu_);\n  float angle = acos(mu_[2]);\n\n  if (fabs(angle) <1e-9) \n    return x;\n\n  Eigen::Quaternion<float> q(cos(angle*0.5), \n      sin(angle*0.5)*axis(0)/axis.norm(),\n      sin(angle*0.5)*axis(1)/axis.norm(),\n      sin(angle*0.5)*axis(2)/axis.norm());\n  return q._transformVector(x);\n}\n\n", "meta": {"hexsha": "5bd08a31f2ed6eda7c0d9a6237d8e95752a7d0e5", "size": 4796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "experiments/dpvmf/vmf.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": "experiments/dpvmf/vmf.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": "experiments/dpvmf/vmf.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": 27.8837209302, "max_line_length": 83, "alphanum_fraction": 0.6077981651, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5792394563013028}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nint main(int, char *[]) {\n  // AngleAxisf aa = Quaternionf(..);\n  Eigen::VectorXd vq(4);\n  vq[0] = 1.0;\n  vq[1] = 0.0;\n  vq(2) = 0.0;\n  vq(3) = 0.0;\n  Eigen::Matrix<float, 4, 1> coe;\n  Eigen::Matrix<float, 3, 3> R;\n  Eigen::Quaternionf q(2.0, 0.1, 0.3, 4.0);  // wxyz\n  coe = q.coeffs();\n  std::cout << coe << std::endl;  // xyzw\n\n  Eigen::Vector3f vec = q.vec();  // xyz\n  std::cout << vec << std::endl;\n\n  Eigen::AngleAxisf aa;\n  Eigen::Matrix3f mat;\n  Eigen::Quaternionf qm(mat);\n  Eigen::Quaternionf qa(aa);\n\n  Eigen::Quaternionf qw;\n  qw.setIdentity();  // important\n  R = qw.toRotationMatrix();\n  qw = qw * q;\n  qw = qw.normalized();  //规范化\n  std::cout << R << std::endl;\n  qw = qw.Identity();  // 1 0 0 0 or qw.setIdentity();\n  std::cout << qw.w() << \"  \" << qw.x() << \"  \" << qw.y() << \"  \" << qw.z()\n            << std::endl;\n  qw = qw.inverse();\n  std::cout << qw.w() << \"  \" << qw.x() << \"  \" << qw.y() << \"  \" << qw.z()\n            << std::endl;\n\n  Eigen::Vector3f w1;\n  w1 << 1, 2, 3;\n  Eigen::Vector3f w2;\n  w2 << 2, 3, 4;\n  qw = qw.Identity();\n  qw = qw.setFromTwoVectors(w1, w2);  //出来的norm=1--姿态四元数\n  std::cout << qw.squaredNorm() << std::endl;  // norm^2  .norm()\n  q.setIdentity();\n  qw = qw.normalized();\n  q = q.normalized();\n  q = q.inverse();\n  std::cout << q.angularDistance(qw) << std::endl;  //必须先规范化\n  std::cout << qw.dot(q) << std::endl;              // dot product 内积\n  std::cout << qw.w() << \"  \" << qw.x() << \"  \" << qw.y() << \"  \" << qw.z()\n            << std::endl;\n  std::cout << q.w() << \"  \" << q.x() << \"  \" << q.y() << \"  \" << q.z()\n            << std::endl;\n\n  // std::cout<<q;\n  std::cout << std::endl;\n  for (int size = 1; size <= 4; ++size) {\n    Eigen::MatrixXi m(size, size + 1);    // a (size)x(size+1)-matrix of int's\n    for (int j = 0; j < m.cols(); ++j)    // loop over columns\n      for (int i = 0; i < m.rows(); ++i)  // loop over rows\n        m(i, j) = i + j * m.rows();       // to access matrix coefficients,\n    // use operator()(int,int)\n    std::cout << m << \"\\n\\n\";\n  }\n  Eigen::VectorXf v(4);  // a vector of 4 float's\n  // to access vector coefficients, use either operator () or operator []\n  v[0] = 1;\n  v[1] = 2;\n  v(2) = 3;\n  v(3) = 4;\n  std::cout << \"\\nv:\\n\" << v << std::endl;\n}\n", "meta": {"hexsha": "b0e9649506ec5656cc95ded48e24e73aecbbeca4", "size": 2289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Quaternion/first.cpp", "max_stars_repo_name": "jasonleecode/algorithm_exercise", "max_stars_repo_head_hexsha": "4edfd4b3668d138613694a492b061f3cbbf05b11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Quaternion/first.cpp", "max_issues_repo_name": "jasonleecode/algorithm_exercise", "max_issues_repo_head_hexsha": "4edfd4b3668d138613694a492b061f3cbbf05b11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Quaternion/first.cpp", "max_forks_repo_name": "jasonleecode/algorithm_exercise", "max_forks_repo_head_hexsha": "4edfd4b3668d138613694a492b061f3cbbf05b11", "max_forks_repo_licenses": ["Apache-2.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.9324324324, "max_line_length": 78, "alphanum_fraction": 0.4901703801, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5792394521591008}}
{"text": "#include <complex>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <vector>\nusing namespace std;\nusing namespace std::complex_literals;\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <ieompp/algebra/monomial.hpp>\n#include <ieompp/algebra/operator.hpp>\n#include <ieompp/constants.hpp>\n#include <ieompp/lattices/periodic_chain.hpp>\n#include <ieompp/models/hubbard_real_space/basis.hpp>\n#include <ieompp/models/hubbard_real_space/expectation_value.hpp>\n#include <ieompp/openmp.hpp>\nnamespace hubbard = ieompp::models::hubbard_real_space;\n\ncomplex<double> minus_i_power(uint64_t power)\n{\n    switch(power % 4) {\n        case 0:\n            return 1.;\n        case 1:\n            return -1.i;\n        case 2:\n            return -1.;\n        default:\n            return 1.i;\n    }\n}\n\nint main()\n{\n    const uint64_t N = 128;\n    ieompp::lattices::PeriodicChain<double> lattice(N, 1.);\n    hubbard::Basis1Operator<ieompp::algebra::Monomial<ieompp::algebra::Operator<uint64_t, bool>>>\n        basis(lattice);\n\n    const double dt      = 0.01;\n    const uint64_t steps = 10000;\n\n    // precompute time dependent prefactors and their complex conjugates\n    vector<vector<complex<double>>> h_vals(N), h_vals_conj(N);\n#pragma omp parallel for\n    for(uint64_t i = 0; i < N; ++i) {\n        h_vals[i].resize(steps);\n        h_vals_conj[i].resize(steps);\n        const auto j                   = lattice.lattice_distance(0, i);\n        std::complex<double> prefactor = minus_i_power(j);\n        for(uint64_t step = 0; step < steps; ++step) {\n            double bess          = boost::math::cyl_bessel_j(j, 2 * step * dt);\n            h_vals[i][step]      = bess * prefactor;\n            h_vals_conj[i][step] = bess * std::conj(prefactor);\n        }\n    }\n\n    const hubbard::ExpectationValue1DHalfFilled<double, decltype(lattice)> expectation_value(\n        lattice, 1., 0.5);\n\n    vector<vector<complex<double>>> results;\n#pragma omp parallel\n    {\n#pragma omp critical\n        {\n            results.emplace_back(steps, complex<double>(0.));\n        }\n    }\n\n#pragma omp parallel for\n    for(uint64_t i = 0; i < N; ++i) {\n        for(uint64_t j = 0; j < N; ++j) {\n            const auto ev = expectation_value(basis[i].front().index1, basis[j].front().index1);\n            for(uint64_t step = 0; step < steps; ++step) {\n                results[omp_get_thread_num()][step] +=\n                    ev * (h_vals[i][step] * h_vals_conj[j][step]);\n            }\n        }\n    }\n\n    ofstream file(\"theory.txt\", ofstream::trunc);\n    for(uint64_t step = 0; step < steps; ++step) {\n        complex<double> val = 0.;\n        for(auto &result : results) {\n            val += result[step];\n        }\n        file << step * dt << '\\t' << val.real() << '\\t' << val.imag() << '\\n';\n    }\n    file.close();\n}\n", "meta": {"hexsha": "f8e670fc99a36c8033d480aea1bee48bac393ed3", "size": 2890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hubbard/hubbard_real_1d_kinetic_theory.cpp", "max_stars_repo_name": "qftphys/Simulate-the-non-equilibrium-dynamics-of-Fermionic-systems", "max_stars_repo_head_hexsha": "48d36fecbe4bc12af90f104cdf1f9f68352c508c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-18T14:35:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T15:12:49.000Z", "max_issues_repo_path": "src/hubbard/hubbard_real_1d_kinetic_theory.cpp", "max_issues_repo_name": "f-koehler/ieompp", "max_issues_repo_head_hexsha": "48d36fecbe4bc12af90f104cdf1f9f68352c508c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hubbard/hubbard_real_1d_kinetic_theory.cpp", "max_forks_repo_name": "f-koehler/ieompp", "max_forks_repo_head_hexsha": "48d36fecbe4bc12af90f104cdf1f9f68352c508c", "max_forks_repo_licenses": ["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.7446808511, "max_line_length": 97, "alphanum_fraction": 0.6006920415, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.579236561533047}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <stdio.h>\n\n#include <Eigen/Dense>\n\n#include \"configuration.hpp\"\n#include \"utils/util.hpp\"\n\nnamespace util {\ndouble SmoothPos(double ini, double end, double moving_duration,\n                 double curr_time);\ndouble SmoothVel(double ini, double end, double moving_duration,\n                 double curr_time);\ndouble SmoothAcc(double ini, double end, double moving_duration,\n                 double curr_time);\nvoid SinusoidTrajectory(double initTime_, const Eigen::VectorXd &midPoint_,\n                        const Eigen::VectorXd &amp_,\n                        const Eigen::VectorXd &freq_, double evalTime_,\n                        Eigen::VectorXd &p_, Eigen::VectorXd &v_,\n                        Eigen::VectorXd &a_, double smoothing_dur = 1.0);\ndouble Smooth(double ini, double fin, double rat);\n} // namespace util\n\nclass HermiteCurve {\npublic:\n  HermiteCurve();\n  HermiteCurve(const double &start_pos, const double &start_vel,\n               const double &end_pos, const double &end_vel);\n  ~HermiteCurve();\n  void Initialize(const double &start_pos, const double &start_vel,\n                  const double &end_pos, const double &end_vel);\n  double Evaluate(const double &s_in);\n  double EvaluateFirstDerivative(const double &s_in);\n  double EvaluateSecondDerivative(const double &s_in);\n\nprivate:\n  double p1_;\n  double v1_;\n  double p2_;\n  double v2_;\n\n  double s_;\n};\n\nclass HermiteCurveVec {\npublic:\n  HermiteCurveVec();\n  HermiteCurveVec(const Eigen::VectorXd &start_pos,\n                  const Eigen::VectorXd &start_vel,\n                  const Eigen::VectorXd &end_pos,\n                  const Eigen::VectorXd &end_vel);\n\n  void Initialize(const Eigen::VectorXd &start_pos,\n                  const Eigen::VectorXd &start_vel,\n                  const Eigen::VectorXd &end_pos,\n                  const Eigen::VectorXd &end_vel);\n\n  ~HermiteCurveVec();\n  Eigen::VectorXd Evaluate(const double &s_in);\n  Eigen::VectorXd EvaluateFirstDerivative(const double &s_in);\n  Eigen::VectorXd EvaluateSecondDerivative(const double &s_in);\n\nprivate:\n  Eigen::VectorXd p1_;\n  Eigen::VectorXd v1_;\n  Eigen::VectorXd p2_;\n  Eigen::VectorXd v2_;\n\n  std::vector<HermiteCurve> curves_;\n  Eigen::VectorXd output_;\n};\n\nclass HermiteQuaternionCurve {\npublic:\n  HermiteQuaternionCurve();\n  HermiteQuaternionCurve(const Eigen::Quaterniond &quat_start,\n                         const Eigen::Vector3d &angular_velocity_start,\n                         const Eigen::Quaterniond &quat_end,\n                         const Eigen::Vector3d &angular_velocity_end);\n  ~HermiteQuaternionCurve();\n\n  void Initialize(const Eigen::Quaterniond &quat_start,\n                  const Eigen::Vector3d &angular_velocity_start,\n                  const Eigen::Quaterniond &quat_end,\n                  const Eigen::Vector3d &angular_velocity_end);\n\n  // All values are expressed in \"world frame\"\n  void Evaluate(const double &s_in, Eigen::Quaterniond &quat_out);\n  void GetAngularVelocity(const double &s_in, Eigen::Vector3d &ang_vel_out);\n  void GetAngularAcceleration(const double &s_in, Eigen::Vector3d &ang_acc_out);\n\nprivate:\n  Eigen::Quaterniond qa;   // Starting quaternion\n  Eigen::Vector3d omega_a; // Starting Angular Velocity\n  Eigen::Quaterniond qb;   // Ending quaternion\n  Eigen::Vector3d omega_b; // Ending Angular velocity\n\n  Eigen::AngleAxisd omega_a_aa; // axis angle representation of omega_a\n  Eigen::AngleAxisd omega_b_aa; // axis angle representation of omega_b\n\n  void initialize_data_structures();\n\n  void computeBasis(const double &s_in); // computes the basis functions\n  void computeOmegas();\n\n  Eigen::Quaterniond q0; // quat0\n  Eigen::Quaterniond q1; // quat1\n  Eigen::Quaterniond q2; // quat1\n  Eigen::Quaterniond q3; // quat1\n\n  double b1; // basis 1\n  double b2; // basis 2\n  double b3; // basis 3\n\n  double bdot1; // 1st derivative of basis 1\n  double bdot2; // 1st derivative of basis 2\n  double bdot3; // 1st derivative of basis 3\n\n  double bddot1; // 2nd derivative of basis 1\n  double bddot2; // 2nd derivative of basis 2\n  double bddot3; // 2nd derivative of basis 3\n\n  Eigen::Vector3d omega_1;\n  Eigen::Vector3d omega_2;\n  Eigen::Vector3d omega_3;\n\n  Eigen::AngleAxisd omega_1aa;\n  Eigen::AngleAxisd omega_2aa;\n  Eigen::AngleAxisd omega_3aa;\n\n  // Allocate memory for quaternion operations\n  Eigen::Quaterniond qtmp1;\n  Eigen::Quaterniond qtmp2;\n  Eigen::Quaterniond qtmp3;\n\n  // progression variable\n  double s_;\n};\n\nclass MinJerkCurve {\npublic:\n  // Constructors\n  MinJerkCurve();\n  MinJerkCurve(const Eigen::Vector3d &init, const Eigen::Vector3d &end,\n               const double &time_start, const double &time_end);\n\n  void SetParams(const Eigen::Vector3d &init, const Eigen::Vector3d &end,\n                 const double &time_start, const double &time_end);\n\n  void GetPos(const double &time, double &pos);\n  void GetVel(const double &time, double &vel);\n  void GetAcc(const double &time, double &acc);\n\n  // Destructor\n  ~MinJerkCurve();\n\nprivate:\n  Eigen::MatrixXd C_mat;     // Matrix of Coefficients\n  Eigen::MatrixXd C_mat_inv; // Inverse of Matrix of Coefficients\n  Eigen::VectorXd\n      a_coeffs; // mininum jerk coeffs. a = [a0, a1, a2, a3, a4, a5, a6];\n  Eigen::VectorXd bound_cond; // boundary conditions x_b = [ x(to), xdot(to),\n                              // xddot(to), x(tf), xdot(tf), xddot(tf)]\n\n  Eigen::Vector3d init_cond; // initial pos, vel, acceleration\n  Eigen::Vector3d end_cond;  // final pos, vel, acceleration\n  double to;                 // Starting time\n  double tf;                 // Ending time\n\n  void Initialization();\n\n  // Compute the coefficients\n  void compute_coeffs();\n};\n\nclass MinJerkCurveVec {\npublic:\n  MinJerkCurveVec();\n  MinJerkCurveVec(const Eigen::VectorXd &start_pos,\n                  const Eigen::VectorXd &start_vel,\n                  const Eigen::VectorXd &start_acc,\n                  const Eigen::VectorXd &end_pos,\n                  const Eigen::VectorXd &end_vel,\n                  const Eigen::VectorXd &end_acc, double duration);\n  ~MinJerkCurveVec();\n  Eigen::VectorXd Evaluate(const double &t_in);\n  Eigen::VectorXd EvaluateFirstDerivative(const double &t_in);\n  Eigen::VectorXd EvaluateSecondDerivative(const double &t_in);\n\nprivate:\n  double Ts_;\n\n  Eigen::VectorXd p1_;\n  Eigen::VectorXd v1_;\n  Eigen::VectorXd a1_;\n\n  Eigen::VectorXd p2_;\n  Eigen::VectorXd v2_;\n  Eigen::VectorXd a2_;\n\n  std::vector<MinJerkCurve> curves_;\n  Eigen::VectorXd output_;\n};\n", "meta": {"hexsha": "8ae29c5bd4c94bfe2be449f924b1fc5cc1caedac", "size": 6533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/interpolation.hpp", "max_stars_repo_name": "junhyeokahn/PnC", "max_stars_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T13:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T13:19:01.000Z", "max_issues_repo_path": "utils/interpolation.hpp", "max_issues_repo_name": "junhyeokahn/PnC", "max_issues_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T20:48:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T11:42:02.000Z", "max_forks_repo_path": "utils/interpolation.hpp", "max_forks_repo_name": "junhyeokahn/PnC", "max_forks_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T22:37:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T17:17:27.000Z", "avg_line_length": 31.2583732057, "max_line_length": 80, "alphanum_fraction": 0.677177407, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5792195696238874}}
{"text": "#include \"inf_pers2cyc.h\"\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <tuple>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include \"utils.h\"\n#include \"mesh_writer.h\"\n#include \"tests.h\"\n#include \"flow_graph.hpp\"\n\nconst size_t MAX_N_INTERVALS = 1000;\n\nstruct CompPersPairsByFiltIndex {\n    CompPersPairsByFiltIndex(Bitmap_cubical_complex* _complex) : complex(_complex) {}\n\n    bool operator()(const std::pair<int,int>& p1, const std::pair<int,int>& p2) {\n        return complex->key(p1.second) - complex->key(p1.first) >\n               complex->key(p2.second) - complex->key(p2.first);\n    }\n\n    Bitmap_cubical_complex* complex;\n};\n\nstruct CompPersPairsByFuncVal {\n    CompPersPairsByFuncVal(Bitmap_cubical_complex* _complex) : complex(_complex) {}\n\n    bool operator()(const std::pair<int,int>& p1, const std::pair<int,int>& p2) {\n        return complex->filtration(p1.second) - complex->filtration(p1.first) >\n               complex->filtration(p2.second) - complex->filtration(p2.first);\n    }\n\n    Bitmap_cubical_complex* complex;\n};\n\nvoid computePersistenceCube(\n    const std::string& perseus_fname, \n    const IntervSortType interv_sort_type, \n    const ExecOptions& ops,\n    std::string* filt_fname) {\n\n    Bitmap_cubical_complex bm_cube_cmplx(perseus_fname.c_str());\n    cout << endl << \"bitmap complex load done\" << endl;\n\n    Persistent_cohomology pcoh(bm_cube_cmplx);\n    pcoh.init_coefficients(2);\n    pcoh.compute_persistent_cohomology(0.0);\n    auto pers_pairs = pcoh.get_persistent_pairs();\n    \n    vector<std::pair<int,int>> pers_pairs_dim2;\n    for (auto p : pers_pairs) {\n        if (bm_cube_cmplx.dimension(get<0>(p)) == 2) {\n            pers_pairs_dim2.emplace_back(get<0>(p), get<1>(p));\n        }\n    }\n\n    if (interv_sort_type == BY_FILT_INDEX) {\n        CompPersPairsByFiltIndex comp(&bm_cube_cmplx);\n        std::sort(pers_pairs_dim2.begin(), pers_pairs_dim2.end(), comp);\n    } else {\n        CompPersPairsByFuncVal comp(&bm_cube_cmplx);\n        std::sort(pers_pairs_dim2.begin(), pers_pairs_dim2.end(), comp);\n    }\n\n    cout << endl << \"computing persistence done, total intervals: \" \n        << pers_pairs_dim2.size() << endl;\n\n    int dim, x_res, y_res, z_res;\n\n    std::ifstream fin(perseus_fname.c_str());\n    fin >> dim;\n    if (dim != 3) {\n        cout << \"FATAL: perseus file dim not 3\" << endl;\n        exit(-1);\n    }\n\n    fin >> x_res >> y_res >> z_res;\n\n    std::string purename;\n    getFilePurename(perseus_fname, &purename);\n\n    *filt_fname = purename\n        + (interv_sort_type == BY_FILT_INDEX ? \"_IX\" : \"_FV\")\n        + \".filt\";\n\n    cout << endl << \"writing filt file '\" \n        << *filt_fname << \"'\" << endl;\n\n    writeFiltCube(\n        &bm_cube_cmplx, x_res, y_res, z_res, \n        pers_pairs_dim2, *filt_fname);\n}\n\nvoid writeFiltCube(Bitmap_cubical_complex* bm_cube_cmplx, \n    const int x_res, const int y_res, const int z_res, \n    vector<std::pair<int,int>> pers_pairs_dim2,\n    const std::string& filename) {\n\n    int num_intv = std::min(pers_pairs_dim2.size(), MAX_N_INTERVALS);\n\n    // cell count of every dimension for each pair.\n    // indexed the same as 'pers_pairs_dim2'.\n    vector<array<int,4>> dim_cell_count_all(num_intv, {-1, -1, -1, -1});\n    vector<array<int,2>> pairs_key_index(num_intv);\n\n    for (auto i = 0; i < num_intv; i ++) {\n        // i-th pair in 'pers_pairs_dim2'\n        auto p = pers_pairs_dim2[i];\n        pairs_key_index[i][0] = bm_cube_cmplx->key(p.first);\n        pairs_key_index[i][1] = i;\n    }\n\n    struct  {\n        bool operator()(const array<int,2>& ki1, const array<int,2>& ki2) {\n            return ki1[0] < ki2[0];\n        }\n    } comp;\n\n    std::sort(pairs_key_index.begin(), pairs_key_index.end(), comp);\n    // for (auto ki : pairs_key_index) {\n    //     cout << ki[0] << \" \" << ki[1] << endl;\n    // }\n\n    // calculate the cell count of every dimension for all pairs\n    array<int,4> dim_cell_count {0, 0, 0, 0};\n    int cur_ind = 0;\n\n    for (auto key = 0; \n        key < bm_cube_cmplx->num_simplices() &&\n        cur_ind < num_intv; \n        key ++) {\n\n        auto cell_id = bm_cube_cmplx->simplex(key);\n        dim_cell_count[bm_cube_cmplx->dimension(cell_id)] ++;\n\n        if (key == pairs_key_index.at(cur_ind).at(0)) {\n            auto intv_ind = pairs_key_index.at(cur_ind).at(1);\n            dim_cell_count_all.at(intv_ind) = dim_cell_count;\n            cur_ind ++;\n        }\n    }\n\n    if (cur_ind != num_intv) {\n        cout << \"FATAL: cur_ind != num_intv in writeFiltCube\" << endl;\n        exit(-1);\n    }\n \n    std::ofstream fout(filename);\n\n    fout << num_intv << endl;\n\n    for (auto i = 0; i < num_intv; i ++) {\n        auto p = pers_pairs_dim2[i];\n\n        fout << i << \" \"                              // 0: seq of interval\n            << dim_cell_count_all.at(i).at(2)         // 1: count of 2 and 3-cells\n            + dim_cell_count_all.at(i).at(3) << \" \"   \n            << bm_cube_cmplx->key(p.first) << \" \"     // 2: start key\n            << bm_cube_cmplx->key(p.second) << \" \"    // 3: end key\n            << p.first << \" \"                         // 4: start bm id \n            << bm_cube_cmplx->key(p.second)           // 5: index length\n            - bm_cube_cmplx->key(p.first) << \" \"\n            << bm_cube_cmplx->filtration(p.second)    // 6: function value length\n            - bm_cube_cmplx->filtration(p.first) << \" \"\n            << dim_cell_count_all.at(i).at(1) << \" \"  // 7: 1-cell tount\n            << dim_cell_count_all.at(i).at(2) << \" \"  // 8: 2-cell tount\n            << dim_cell_count_all.at(i).at(3) << endl;// 9: 3-cell tount\n    }\n    \n    fout << endl;\n\n    // the given resolution is in terms of 3-d cells (cubes), while\n    // the resolution for the filt file as well as for CubeComplex \n    // is in terms of 0-d cells (vertices).\n    fout << x_res+1 << \" \" << y_res+1 << \" \" << z_res+1 << endl << endl;\n\n    vector<int> verts;\n    for (auto key = 0; key <= bm_cube_cmplx->num_simplices(); key ++) {\n        auto cell_id = bm_cube_cmplx->simplex(key);\n        auto dim = bm_cube_cmplx->dimension(cell_id);\n\n        if (dim == 2 || dim == 3) {\n            getBitmapComplexCellVerts(cell_id, dim, \n                x_res, y_res, z_res, &verts);\n\n            fout << verts[0];\n            for (auto i = 1; i < verts.size(); i ++) {\n                fout << ' ' << verts[i];\n            }\n            fout << endl;\n        }\n    }\n}\n\nvoid infPers2CycsFromFile(\n    const std::string& filt_fname, \n    const ComplexType cmplx_type, \n    const int start_interval, \n    const int num_intervals, \n    const ExecOptions& ops) {\n\n    int num_all_intervals;\n\n    {\n        std::ifstream fin(filt_fname);\n        fin >> num_all_intervals;\n    }\n\n    cout << endl << \"filt file num of intervals: \" << num_all_intervals << endl;\n\n    for (int i = start_interval; \n        i < num_all_intervals && i < start_interval + num_intervals; \n        i ++) {\n\n        cout << endl << endl << \"---- \" << i << \"-th interval ----\" << endl;\n\n        // this complex will be deleted in infPers2Cyc\n        CellComplex* complex;\n        if (cmplx_type == CUBE_CMPLX) {\n            complex = new CubeComplex();\n        }\n        complex->init(1,3);\n\n        vector<int> pos_cell_2d_verts;\n        int start_key = -1, start_id = -1;\n\n        // loadToyCubeComplex((CubeComplex*)complex, &pos_cell_2d_verts);\n        // std::string purename = \"hardcode_toy\";\n\n        loadComplex(filt_fname, cmplx_type, complex, \n            i, &start_key, &start_id, &pos_cell_2d_verts);\n\n        char buf[50];\n        snprintf(buf, 50, \"%03d_\", i);\n\n        std::string purename;\n        getFilePurename(filt_fname, &purename);\n        purename = purename + buf + std::to_string(start_key) \n            + \"_\" + std::to_string(start_id);\n        \n        if (ops.verbose) {\n            cout << endl << \"positive cell: \" << pos_cell_2d_verts << endl;\n        }\n        cout << endl << \"load complex done\" << endl;\n\n        if (ops.write_intem) {\n            complex->writeMesh(purename + \"_orig.off\");\n            // ((CubeComplex*)complex)->writeEdges(purename + \"_orig_edges.ply\");\n        }\n\n        infPers2Cyc(cmplx_type, complex, pos_cell_2d_verts, ops, purename);\n    }\n}\n\nvoid loadComplex(\n    const std::string& filt_fname, \n    const ComplexType cmplx_type, \n    CellComplex* complex, \n    const int interval_id,\n    int* interv_start_key,\n    int* interv_start_id,\n    vector<int>* pos_cell_2d_verts) {\n\n    std::ifstream fin(filt_fname);\n\n    int num_all_intervals, interv_cell_count;\n    array<int,4> interv_dim_cell_count;\n\n    fin >> num_all_intervals;\n\n    for (int i = 0; i < num_all_intervals; i ++) {\n        int interv_seq, cell_count, start_key, end_key, len_idx, start_id;\n        double len_fv;\n        array<int,4> dim_cell_count;\n\n        fin >> interv_seq >> cell_count >> start_key >> end_key >> start_id \n            >> len_idx >> len_fv\n            >> dim_cell_count[1] >> dim_cell_count[2] >> dim_cell_count[3];\n\n        if (i == interval_id) {\n            interv_cell_count = cell_count;\n            interv_dim_cell_count = dim_cell_count;\n            *interv_start_key = start_key;\n            *interv_start_id = start_id;\n        }\n    }\n\n    if (cmplx_type == CUBE_CMPLX) {\n        int x_res, y_res, z_res;\n        fin >> x_res >> y_res >> z_res;\n        ((CubeComplex*)complex)->setResolution(x_res, y_res, z_res);\n    }\n\n    complex->reserveCellSize(1, interv_dim_cell_count[1]);\n    complex->reserveCellSize(2, interv_dim_cell_count[2]);\n    complex->reserveCellSize(3, interv_dim_cell_count[3]);\n\n    std::string line, s;\n    vector<int> verts;\n\n    for (int k = 0; k < interv_cell_count;) {\n        if (!std::getline(fin, line)) {\n            cout << \"FATAL: reach end of file but not finish reading in loadComplex\" << endl;\n            exit(-1);\n        }\n\n        if (line.compare(\"\") == 0) {\n            continue;\n        }\n\n        std::istringstream iss(line);\n        verts.clear();\n        while (getline(iss, s, ' ')) {\n            verts.push_back(std::stoi(s));\n        }\n\n        // cout << verts << endl;\n\n        if (verts.size() == complex->getVertCnt(2)) {\n            complex->toCanonVerts(2, &verts);\n            complex->addCellNoConvCanon(2, verts);\n        } else if (verts.size() == complex->getVertCnt(3)) {\n            complex->toCanonVerts(3, &verts);\n            complex->addCellNoConvCanon(3, verts);\n        } else {\n            cout << \"FATAL: filt file has cells other than 2d or 3d\" << endl;\n        }\n\n        k ++;\n    }\n\n    if (verts.size() != complex->getVertCnt(2)) {\n        cout << \"FATAL: positive cell vert count not right in loadComplex\" << endl;\n        exit(-1);\n    }\n\n    *pos_cell_2d_verts = verts;\n}\n\nvoid infPers2Cyc(\n    const ComplexType cmplx_type, CellComplex* orig_complex, \n    const vector<int>& pos_cell_2d_verts, const ExecOptions& ops, \n    const std::string& file_prefix) {\n\n    /* pruning */\n\n    pruneComplex(orig_complex);\n\n    // orig_complex->print();\n    cout << endl << \"prune done\" << endl;\n\n    if (ops.verbose) {\n        cout << endl << \"orig_complex map load:\" << endl;\n        orig_complex->printLoadStat();\n    }\n\n    if (ops.write_intem) {\n        orig_complex->writeMesh(file_prefix + \"_pruned.off\");\n    }\n\n\n    /* get 2-connected component */\n\n    auto start_cell_2d_id = orig_complex->getCellIdNoConvCanon(2, pos_cell_2d_verts);\n    if (start_cell_2d_id < 0) {\n        cout << \"FATAL: start_cell_2d_id < 0 in infPers2Cyc\" << endl;\n        exit(-1);\n    }\n\n    auto orig_complex_cell_1d_cnt = orig_complex->getCellCount(1);\n    auto orig_complex_cell_2d_cnt = orig_complex->getCellCount(2);\n    auto orig_complex_cell_3d_cnt = orig_complex->getCellCount(3);\n\n    orig_complex->deleteDimCofaces(2);\n    orig_complex->deleteDimVertQueryMap(2);\n\n    CellComplex* conn_complex;\n\n    if (cmplx_type == CUBE_CMPLX) {\n        conn_complex = new CubeComplex();\n        ((CubeComplex*)conn_complex)->setResolution(\n            ((CubeComplex*)orig_complex)->getXRes(),\n            ((CubeComplex*)orig_complex)->getYRes(),\n            ((CubeComplex*)orig_complex)->getZRes());\n    }\n\n    conn_complex->init(1,3);\n    conn_complex->setCofaceCountHint(2, 2);\n\n    // just some hints\n    conn_complex->reserveCellSize(1, orig_complex_cell_1d_cnt/4+1);\n    conn_complex->reserveCellSize(2, orig_complex_cell_2d_cnt/4+1);\n    conn_complex->reserveCellSize(3, orig_complex_cell_3d_cnt/4+1);\n \n    cellConnectedComponent(orig_complex, start_cell_2d_id, conn_complex);\n\n    int conn_compnt_cell_2d_cnt = conn_complex->getCellCount(2);\n    \n    if (ops.write_intem) {\n        conn_complex->writeMesh(file_prefix + \"_conn.off\");\n    }\n\n\n    /* add necessary 3-cells */\n\n    vector<int> cell_3d_verts;\n    vector<int> f_2d_verts;\n\n    for (auto cell_3d_id = 0; \n        cell_3d_id < orig_complex->getCellSize(3); \n        cell_3d_id ++) {\n\n        if (orig_complex->isCellValid(3, cell_3d_id)) {\n            orig_complex->getCellVerts(3, cell_3d_id, &cell_3d_verts);\n            orig_complex->getFaceVerts(3, cell_3d_verts, 0, &f_2d_verts);\n\n            if (conn_complex->getCellId(2, f_2d_verts) >= 0) {\n                conn_complex->addCellNoConvCanon(3, cell_3d_verts);\n            }\n        }\n    }\n\n    if (conn_compnt_cell_2d_cnt != conn_complex->getCellCount(2)) {\n        cout << \"FATAL: 2-cell count not equal after 3-cells adding\" << endl;\n        exit(-1);\n    }\n\n    cout << endl << \"2-conn component done\" << endl;\n\n    if (ops.verbose) {\n        cout << endl <<  \"conn_complex map load:\" << endl;\n        conn_complex->printLoadStat();\n    }\n\n    delete orig_complex;\n    orig_complex = NULL;\n\n\n    /* reconstruct void boundaries */\n\n    vector<array<int,2>>* cell_2d_void_map = \n        new vector<array<int,2>>(conn_complex->getCellSize(2), {-1, -1});\n    int void_cnt;\n\n    reconVoidBound(cmplx_type, conn_complex, cell_2d_void_map, ops, file_prefix, &void_cnt);\n\n    cout << endl << \"void boundary reconstruction done\" << endl;\n\n    // free some memory space\n\n    int src, sink;\n    {\n        auto pos_cell_2d_id = conn_complex->\n            getCellIdNoConvCanon(2, pos_cell_2d_verts);\n\n        vector<int> void_ids;\n        getCell2dVoidIds(pos_cell_2d_id, conn_complex, cell_2d_void_map, &void_ids);\n        src = void_ids.at(0);\n        sink = void_ids.at(1);\n\n        // auto cofaces = conn_complex->getCellCofaces(2, pos_cell_2d_id);\n        // src = cofaces->at(0);\n        // sink = cofaces->at(1);\n    }\n\n    if (src == sink) {\n        cout << \"FATAL: src sink the same in infPers2Cyc\" << endl;\n        exit(-1);\n    }\n\n    conn_complex->deleteDimCellData(1);\n    conn_complex->deleteDimCellData(3);\n    conn_complex->deleteDimVertQueryMap(2);\n\n\n    /* record the corresponding set of 2-cells for each graph edge */\n\n    GEdgeCellMap* gedge_cell_map = new GEdgeCellMap(conn_complex->getCellCount(2)/4+1);\n\n    std::pair<int,int> gedge;\n    const vector<int> empty_vector;\n    for (auto cell_2d_id = 0;\n        cell_2d_id < conn_complex->getCellSize(2);\n        cell_2d_id ++) {\n\n        if (conn_complex->isCellValid(2, cell_2d_id)) {\n            vector<int> void_ids;\n            getCell2dVoidIds(cell_2d_id, conn_complex, cell_2d_void_map, &void_ids);\n\n            if (void_ids.at(0) != void_ids.at(1)) {\n                gedge.first = void_ids.at(0);\n                gedge.second = void_ids.at(1);\n                toCanonEdge(&gedge);\n\n                auto iter = gedge_cell_map->find(gedge);\n                if (iter == gedge_cell_map->end()) {\n                    std::tie(iter, std::ignore) = \n                        gedge_cell_map->insert({gedge, empty_vector});\n                    iter->second.reserve(1);\n                    iter->second.push_back(cell_2d_id);\n                } else {\n                    iter->second.push_back(cell_2d_id);\n                }\n            }\n        }\n    }\n\n    if (ops.verbose) {\n        cout << endl << \"gedge_cell_map: \";\n        printHashMapLoad(*gedge_cell_map);\n    }\n    // cout << endl;\n    // printGEdgeCellMap(gedge_cell_map, conn_complex);\n\n\n    /* compute the min cyc by flow network */\n\n    delete cell_2d_void_map;\n    conn_complex->deleteDimCofaces(2);\n\n    if (cmplx_type == CUBE_CMPLX) {\n        long max_w = 0;\n\n        for (auto iter = gedge_cell_map->begin(); \n            iter != gedge_cell_map->end(); iter ++) {\n\n            if (iter->second.size() > max_w) {\n                max_w = iter->second.size();\n            }\n        }\n\n        if (ops.verbose) {\n            cout << endl << \"max_w: \" << max_w << endl;\n        }\n\n        // TODO: use cpp limits instead\n        if (max_w <= 127/2) {\n            if (ops.verbose) {\n                cout << \"use 'char' as weight type\" << endl;\n            }\n\n            computeMinCyc<char>(\n                conn_complex, gedge_cell_map, void_cnt,\n                src, sink, ops, file_prefix);\n        } else if (max_w <= 32767/2) {\n            if (ops.verbose) {\n                cout << \"use 'short' as weight type\" << endl;\n            }\n\n            computeMinCyc<short>(\n                conn_complex, gedge_cell_map, void_cnt,\n                src, sink, ops, file_prefix);\n        } else {\n            if (ops.verbose) {\n                cout << \"use 'int' as weight type\" << endl;\n            }\n            \n            computeMinCyc<int>(\n                conn_complex, gedge_cell_map, void_cnt,\n                src, sink, ops, file_prefix);\n        }\n    }\n\n    cout << endl << \"compute min cycle done\" << endl;\n\n    delete gedge_cell_map;\n    delete conn_complex;\n}\n\nvoid cellConnectedComponent(\n    CellComplex* in_complex, const int start_cell_2d_id, CellComplex* out_complex) {\n\n    vector<bool> cell_2d_visited(in_complex->getCellSize(2), false);\n\n    cell_2d_visited[start_cell_2d_id] = true;\n    vector<int> cell_stack { start_cell_2d_id };\n\n    // vertices container for the 2-cell being deleted\n    vector<int> cell_2d_verts;\n    // vertices container for 1-faces of the 2-cell being deleted\n    vector<int> f_verts;\n\n    while (!cell_stack.empty()) {\n        auto cell_2d_id = cell_stack[cell_stack.size() - 1];\n        cell_stack.pop_back();\n        in_complex->getCellVerts(2, cell_2d_id, &cell_2d_verts);\n\n#ifdef DEBUG_OPT\n        if (out_complex->getCellIdNoConvCanon(2, cell_2d_verts) >= 0) {\n            cout << \"FATAL: cell in out_complex\" << endl;\n            exit(-1);\n        }\n#endif\n\n        out_complex->addCellNoConvCanon(2, cell_2d_verts);\n\n        for (auto i = 0; i < in_complex->getFaceCnt(2); i ++) {\n            in_complex->getFaceVerts(2, cell_2d_verts, i, &f_verts);\n            auto face_id = in_complex->getCellId(1, f_verts);\n            const vector<int>* cofaces = in_complex->getCellCofaces(1, face_id);\n\n            for (auto j = 0; j < cofaces->size(); j ++) {\n#ifdef DEBUG_OPT\n                if ( !in_complex->isCellValid( 2, cofaces->at(j) ) ) {\n                    cout << \"FATAL: coface invalid in cellConnectedComponent\" << endl;\n                    exit(-1);\n                }\n#endif\n\n                if (!cell_2d_visited[ cofaces->at(j) ]) {\n                    cell_stack.push_back( cofaces->at(j) );\n                    cell_2d_visited[ cofaces->at(j) ] = true;\n                }\n            }\n        }\n    }\n}\n\nvoid pruneComplex(CellComplex* complex) {\n\n    std::unordered_set<int> one_cells_w1cof;\n    for (auto cell_1d_id = 0; cell_1d_id < complex->getCellSize(1); cell_1d_id ++) {\n        if (complex->isCellValid(1, cell_1d_id)) {\n            if (complex->getCellCofaces(1, cell_1d_id)->size() == 1) {\n                one_cells_w1cof.insert(cell_1d_id);\n            }\n        }\n    }\n\n    // vertices container for the 2-cell being deleted\n    vector<int> cell_2d_verts;\n    // vertices container for 1-faces of the 2-cell being deleted\n    vector<int> f_verts;\n\n    while (!one_cells_w1cof.empty()) {\n        auto cell_1d_id = *(one_cells_w1cof.begin());\n        // the 2-cell being deleted\n        auto cell_2d_id = complex->getCellCofaces(1, cell_1d_id)->at(0);\n\n#ifdef DEBUG_OPT\n        if (complex->getCellCofaces(1, cell_1d_id)->size() != 1) {\n            cout << \"FATAL: 1d cell has cofaces not 1\" << endl;\n            exit(-1);\n        }\n        if (complex->getCellCofaces(2, cell_2d_id)->size() != 0) {\n            cout << \"FATAL: 2d cell has coface in prune\" << endl;\n            exit(-1);\n        }\n#endif\n \n        complex->getCellVerts(2, cell_2d_id, &cell_2d_verts);\n        complex->deleteCell(2, cell_2d_id);\n\n        // enumerate all faces of the 2-cell being deleted\n        for (auto i = 0; i < complex->getFaceCnt(2); i ++) {\n            complex->getFaceVerts(2, cell_2d_verts, i, &f_verts);\n            auto face_id = complex->getCellId(1, f_verts);\n\n            complex->deleteCoface(1, face_id, cell_2d_id);\n\n            if (complex->getCellCofaces(1, face_id)->size() == 0) {\n                one_cells_w1cof.erase(face_id);\n            } else if (complex->getCellCofaces(1, face_id)->size() == 1) {                 \n                one_cells_w1cof.insert(face_id);\n            }\n        }\n    }\n}\n\nvoid get2DCellPtCubic(\n    CellComplex* complex, const int cell_2d_id, \n    const vector<int>& cell_1d_verts, Vector3d* pt) {\n\n    vector<int> cell_2d_verts;\n    complex->getCellVerts(2, cell_2d_id, &cell_2d_verts);\n\n    int verts[2];\n    int j = 0;\n    for (auto v : cell_2d_verts) {\n        if (v != cell_1d_verts[0] && v != cell_1d_verts[1]) {\n            verts[j] = v;\n            j ++;\n        }\n    }\n\n#ifdef DEBUG_OPT\n    if (j != 2) {\n        cout << \"FATAL: j!=2 in get2DCellPtCubic\" << endl;\n        exit(-1);\n    }\n#endif\n\n    Vector3d pt1, pt2;\n    complex->getVertPos(verts[0], &pt1);\n    complex->getVertPos(verts[1], &pt2);\n    *pt = (pt1+pt2) / 2;\n}\n\n// get the canonical oriented 2d cell vertex sequence where the orientation is\n// from the from_vert to the to_vert. the canonical vertex sequence then starts\n// from the smallest vertex following the orientation.\n// the input 'verts' is assumed to be in canon order.\nvoid getCanonOrien2DCellVertsCubic(const vector<int>& verts, \n    const int& from_vert, const int& to_vert, vector<int>* canon_verts) {\n\n    canon_verts->clear();\n\n    int inc;\n    for (auto i = 0; i < verts.size(); i ++) {\n        if (verts[i] == from_vert) {\n            if (verts[ mod(i+1, verts.size()) ] == to_vert) {\n                inc = 1;\n            } else {\n                inc = -1;\n            }\n            \n            break;\n        }\n    }\n\n    // int min_ind = 0;\n    // int min_vert = verts[0];\n\n    // for (auto i = 1; i < verts.size(); i ++) {\n    //     if (verts[i] < min_vert) {\n    //         min_ind = i;\n    //         min_vert = verts[i];\n    //     }\n    // }\n\n    for (auto i = 0; i < verts.size(); i ++) {\n        // canon_verts->push_back( verts[ mod(min_ind+i*inc, verts.size()) ] );\n        canon_verts->push_back( verts[ mod(i*inc, verts.size()) ] );\n    }\n}\n\nvoid addOrien2DCellPairs(\n    const ComplexType cmplx_type, \n    CellComplex* complex, \n    const int cell_1d_id,\n    const vector<int>& cell_1d_verts, \n    VertArrIdMap* orien_cell_2d_id_map, \n    Graph<int>* orien_cell_2d_graph) {\n\n    // if (cell_1d->cofaces.size() == 2) {\n    //     int dosomething = 0;\n    // }\n\n    const vector<int>* cell_1d_cofaces = complex->getCellCofaces(1, cell_1d_id);\n\n    Vector3d cell_1d_pt0, cell_1d_pt1;\n    complex->getVertPos(cell_1d_verts[0], &cell_1d_pt0);\n    complex->getVertPos(cell_1d_verts[1], &cell_1d_pt1);\n\n    // cout << endl << cell_1d_verts << endl;\n    // cout << cell_1d_pt0 << endl;\n    // cout << cell_1d_pt1 << endl;\n\n    Vector3d cell_1d_mid_pt = (cell_1d_pt0+cell_1d_pt1) / 2;\n    // cout << cell_1d_mid_pt << endl;\n\n\n    /* get the plane equation of the first coface */\n\n    auto first_cell_2d_id = cell_1d_cofaces->at(0);\n    vector<int> first_cell_2d_verts;\n    complex->getCellVerts(2, first_cell_2d_id, &first_cell_2d_verts);\n\n    Vector3d first_cell_2d_pt0, first_cell_2d_pt1, first_cell_2d_pt2;\n    complex->getVertPos(first_cell_2d_verts[0], &first_cell_2d_pt0);\n    complex->getVertPos(first_cell_2d_verts[1], &first_cell_2d_pt1);\n    complex->getVertPos(first_cell_2d_verts[2], &first_cell_2d_pt2);\n\n    Vector4d first_cell_plane_eq;\n    getPlaneEquation(first_cell_2d_pt0, first_cell_2d_pt1, first_cell_2d_pt2, &first_cell_plane_eq);\n    // first_cell_plane_eq = -first_cell_plane_eq;\n    // cout << first_cell_plane_eq << endl;\n    // cout << evalPlaneEquation(first_cell_plane_eq, first_cell_2d_pt0) << endl;\n    // cout << evalPlaneEquation(first_cell_plane_eq, first_cell_2d_pt1) << endl;\n    // cout << evalPlaneEquation(first_cell_plane_eq, first_cell_2d_pt2) << endl;\n\n\n    /* get the angles of other cofaces w.r.t the first coface */\n\n    // TODO: this vector seems useless\n    vector<Vector3d> cell_2d_pts(cell_1d_cofaces->size());\n    vector<std::pair<Decimal,int>> cell_2d_order(cell_1d_cofaces->size());\n\n    Vector3d first_cell_2d_vec;\n    for (auto i = 0; i < cell_1d_cofaces->size(); i ++) {\n        if (cmplx_type == CUBE_CMPLX) {\n            get2DCellPtCubic(complex, cell_1d_cofaces->at(i), cell_1d_verts, &cell_2d_pts[i]);\n        } else if (cmplx_type == SIMP_CMPLX) {\n            int dosomething = 0;\n        }\n\n        if (i == 0) {\n            cell_2d_order[i].first = 0;\n            first_cell_2d_vec = cell_2d_pts[i] - cell_1d_mid_pt;\n            first_cell_2d_vec.normalize();\n        } else {\n            Vector3d cell_2d_vec = cell_2d_pts[i] - cell_1d_mid_pt;\n            cell_2d_vec.normalize();\n\n            cell_2d_order[i].first = acos(first_cell_2d_vec.dot(cell_2d_vec));\n            if (evalPlaneEquation(first_cell_plane_eq, cell_2d_pts[i]) < 0) {\n                cell_2d_order[i].first = 2*M_PI - cell_2d_order[i].first;\n            }\n        }\n\n        cell_2d_order[i].second = i;\n    }\n\n    struct {\n        bool operator()(const std::pair<Decimal,int> &a, \n            const std::pair<Decimal,int> &b) const {   \n            return a.first < b.first;\n        }\n    } comp;\n\n    std::sort(cell_2d_order.begin(), cell_2d_order.end(), comp);\n\n#ifdef DEBUG_OPT\n    if (cell_2d_order[0].second != 0) {\n        cout << \"FATAL: cell_2d_order[0].second != 0 in addOrien2DCellPairs\" << endl;\n        exit(-1);\n    }\n#endif\n\n    // for (auto pair : cell_2d_order) {\n    //     cout << radian2Degree(pair.first) << ' ';\n    // }\n    // cout << endl;\n\n    Vector3d cell_1d_vec = cell_1d_pt1 - cell_1d_pt0;\n    cell_1d_vec.normalize();\n    Vector3d cell_1d_ortho_pt = cell_1d_mid_pt + cell_1d_vec.cross(first_cell_2d_vec);\n\n    bool cell_1d_0_to_1 = true;\n    if (evalPlaneEquation(first_cell_plane_eq, cell_1d_ortho_pt) < 0) {\n        cell_1d_0_to_1 = false;\n    }\n\n    // cout << \"cell_1d_0_to_1: \" << cell_1d_0_to_1 << endl;\n    \n    vector<int> cell_2d_verts1, cell_2d_verts2, canon_verts1, canon_verts2;\n    canon_verts1.reserve(complex->getVertCnt(2));\n    canon_verts2.reserve(complex->getVertCnt(2));\n\n    for (auto i = 0; i < cell_2d_order.size(); i ++) {\n        if (cmplx_type == CUBE_CMPLX) {\n            auto cell_2d_order1 = cell_2d_order[i].second;\n            auto cell_2d_order2 = cell_2d_order[ mod(i+1, cell_2d_order.size()) ].second;\n\n            auto cell_2d_id1 = cell_1d_cofaces->at(cell_2d_order1);\n            auto cell_2d_id2 = cell_1d_cofaces->at(cell_2d_order2);\n\n            auto cell_2d_cofaces1 = complex->getCellCofaces(2, cell_2d_id1);\n            auto cell_2d_cofaces2 = complex->getCellCofaces(2, cell_2d_id2);\n\n            // check whether the two oriented 2-cells enclose a 3-cell\n            if (vecIntersect(*cell_2d_cofaces1, *cell_2d_cofaces2)) {\n                if (cell_1d_cofaces->size() == 2) {\n                    auto degree1 = cell_2d_order[i].first;\n                    auto degree2 = cell_2d_order[ mod(i+1, cell_2d_order.size()) ].first;\n\n                    // cout << \"deg:\" << radian2Degree(degree1) << \" \" << radian2Degree(degree2) \n                        // << \" \" << radian2Degree(radianSub(degree2, degree1)) << endl;\n\n                    if (radianSub(degree2, degree1) <= M_PI) {\n                        continue;\n                    }\n                } else {\n                    continue;\n                }\n            }\n\n            complex->getCellVerts(2, cell_2d_id1, &cell_2d_verts1);\n            complex->getCellVerts(2, cell_2d_id2, &cell_2d_verts2);\n\n            if (cell_1d_0_to_1) {\n                // CAUTION: should guarantee the input vertices in canon order\n                getCanonOrien2DCellVertsCubic(\n                    cell_2d_verts1, cell_1d_verts[0], cell_1d_verts[1], &canon_verts1);\n                getCanonOrien2DCellVertsCubic(\n                    cell_2d_verts2, cell_1d_verts[1], cell_1d_verts[0], &canon_verts2);\n            } else {\n                getCanonOrien2DCellVertsCubic(\n                    cell_2d_verts1, cell_1d_verts[1], cell_1d_verts[0], &canon_verts1);\n                getCanonOrien2DCellVertsCubic(\n                    cell_2d_verts2, cell_1d_verts[0], cell_1d_verts[1], &canon_verts2);\n            }\n\n            // cout << cell_2d_verts1 << endl;\n            // cout << \"paired 2-cells: \" << canon_verts1 << ' ' << canon_verts2 << endl;\n\n            auto id1 = orien_cell_2d_id_map->getId(canon_verts1);\n            if (id1 < 0) {\n                id1 = orien_cell_2d_id_map->addArrayLabel(canon_verts1);\n            }\n            \n            auto id2 = orien_cell_2d_id_map->getId(canon_verts2);\n            if (id2 < 0) {\n                id2 = orien_cell_2d_id_map->addArrayLabel(canon_verts2);\n            }\n            \n            orien_cell_2d_graph->addEdge(id1, id2);\n        }\n    }\n}\n\nvoid reconVoidBound(\n    const ComplexType cmplx_type, \n    CellComplex* complex, \n    vector<array<int,2>>* cell_2d_void_map,\n    const ExecOptions& ops, \n    const std::string& file_prefix,\n    int* void_cnt) {\n\n    VertArrIdMap orien_cell_2d_id_map;\n    orien_cell_2d_id_map.init(complex->getVertCnt(2));\n    // cout << \"complex->getVertCnt(2): \" << complex->getVertCnt(2) << endl;\n\n    Graph<int> orien_cell_2d_graph;\n\n\n    /* get the number of boundary oriented 2-cells \n       and reserve the size for the graph and the id map */\n\n    int orien_cell_2d_cnt = 0;\n    for (auto cell_2d_id = 0; cell_2d_id < complex->getCellSize(2); cell_2d_id ++) {\n        if (complex->isCellValid(2, cell_2d_id)) {\n            orien_cell_2d_cnt += 2 - complex->getCellCofaces(2, cell_2d_id)->size();\n        }\n    }\n\n    orien_cell_2d_id_map.reserve(orien_cell_2d_cnt);\n    orien_cell_2d_graph.reserve(orien_cell_2d_cnt);\n\n\n    /* traverse all boundary 2-cells and their 1-faces \n       to add all pairs of orented 2-cells */\n    // TODO: traverse all 1-cells instead\n\n    std::unordered_set<int>* visited_cells_1d = new std::unordered_set<int>;\n    vector<int> cell_1d_verts, cell_2d_verts;\n\n    for (auto cell_2d_id = 0; cell_2d_id < complex->getCellSize(2); cell_2d_id ++) {\n        if (complex->isCellValid(2, cell_2d_id)) {\n            if (complex->getCellCofaces(2, cell_2d_id)->size() < 2) {\n                complex->getCellVerts(2, cell_2d_id, &cell_2d_verts);\n\n                for (auto i = 0; i < complex->getFaceCnt(2); i ++) {\n                    complex->getFaceVerts(2, cell_2d_verts, i, &cell_1d_verts);\n                    complex->toCanonVerts(1, &cell_1d_verts);\n                    // cout << \"  \" << cell_1d_verts << endl;\n                    auto cell_1d_id = complex->getCellIdNoConvCanon(1, cell_1d_verts);\n\n                    if (visited_cells_1d->find(cell_1d_id) == visited_cells_1d->end()) {\n                        visited_cells_1d->insert(cell_1d_id);\n                        addOrien2DCellPairs(cmplx_type, complex, cell_1d_id, cell_1d_verts,\n                            &orien_cell_2d_id_map, &orien_cell_2d_graph);\n                    }\n                }\n            }\n        }\n    }\n\n    delete visited_cells_1d;\n    visited_cells_1d = NULL;\n\n    if (ops.verbose) {\n        cout << endl << \"orien_cell_2d_id_map size stat:\" << endl;\n        orien_cell_2d_id_map.printLoadStat();\n        cout << endl << \"orien_cell_2d_graph: capacity=\" \n            << orien_cell_2d_graph.adj_nodes_.capacity() \n            << \",size=\" << orien_cell_2d_graph.adj_nodes_.size() << endl;\n    }\n\n    // TODO: maybe can add a degree check for the graph: 4 for cubical complex?\n    // orien_cell_2d_graph.print();\n    // cout << endl;\n\n\n    /* get connected components of the graph of oriented 2-cells by DFS */\n\n    int void_id = 0;\n    vector<bool> orien_cell_2d_visited;\n    orien_cell_2d_visited.resize(orien_cell_2d_graph.size(), false);\n    vector<int> node_stack;\n    vector<int> orien_cell_2d;\n    \n    for (auto i = 0; i < orien_cell_2d_graph.size(); i ++) {\n        if (orien_cell_2d_visited[i] == false) {\n            node_stack = { i };\n            orien_cell_2d_visited[i] = true;\n\n            MeshWriter* mesh_writer;\n            if (ops.write_intem) {\n                mesh_writer = new MeshWriter(complex, complex->getVertCnt(2));\n            }\n            \n            // cout << endl << \"node_stack.capacity(): \" << node_stack.capacity() << endl << endl;\n            // cout << \"void \" << void_id << \": (\";\n            // cout << \"void \" << void_id << \":\" << endl;\n\n            while (!node_stack.empty()) {\n                auto node = node_stack[node_stack.size() - 1];\n                node_stack.pop_back();\n\n                // cout << node << \",\";\n                orien_cell_2d_id_map.getArrayLabel(node, &orien_cell_2d);\n                // cout << orien_cell_2d << endl;\n\n                if (ops.write_intem) {\n                    mesh_writer->addFace(orien_cell_2d);\n                }\n\n                complex->toCanonVerts(2, &orien_cell_2d);\n                auto cell_2d_id = complex->getCellIdNoConvCanon(2, orien_cell_2d);\n\n                if (cell_2d_void_map->at(cell_2d_id).at(0) < 0) {\n                    cell_2d_void_map->at(cell_2d_id).at(0) = void_id + complex->getCellSize(3);\n                } else if (cell_2d_void_map->at(cell_2d_id).at(1) < 0) {\n                    cell_2d_void_map->at(cell_2d_id).at(1) = void_id + complex->getCellSize(3);\n                } else {\n                    cout << \"FATAL cell_2d_void_map[cell_2d_id] both >= 0 in reconVoidBound\" << endl;\n                    exit(-1);\n                }\n\n                // auto cofaces = const_cast<vector<int>*>(complex->getCellCofaces(2, cell_2d_id));\n                // cofaces->push_back(void_id + complex->getCellSize(3));\n\n                for (auto j = 0; j < orien_cell_2d_graph.adj_nodes_[node].size(); j ++) {\n                    auto adj_node = orien_cell_2d_graph.adj_nodes_[node][j];\n\n                    if (orien_cell_2d_visited[adj_node] == false) {\n                        node_stack.push_back(adj_node);\n                        orien_cell_2d_visited[adj_node] = true;\n                    }\n                }\n            }\n\n            if (ops.write_intem) {\n                mesh_writer->write(file_prefix + \"_void\" + std::to_string(void_id) + \".off\");\n                delete mesh_writer;\n            }\n\n            void_id ++;\n            // cout << \")\" << endl;\n            // cout << endl;\n        }\n    }\n\n    *void_cnt = complex->getCellSize(3) + void_id;\n\n    if (ops.verbose) {\n        cout << endl << \"void count: \" << void_id << endl;\n    }\n}\n\ntemplate<typename WeightType>\nvoid computeMinCyc(\n    CellComplex* complex, \n    const GEdgeCellMap* gedge_cell_map, \n    const int void_cnt,\n    const int src,\n    const int sink, \n    const ExecOptions& ops, \n    const std::string& file_prefix) {\n\n    // if (ops.verbose) {\n    //     cout << \"vertex size:\" << void_cnt + gedge_cell_map->size() << endl;\n    // }\n\n    // FlowGraph<int,WeightType> _graph(void_cnt + gedge_cell_map->size());\n\n    // int edge_id = 0;\n    // for (auto iter = gedge_cell_map->begin(); \n    //     iter != gedge_cell_map->end(); iter ++) {\n\n    //     const std::pair<int,int>& edge = iter->first;\n\n    //     WeightType w = 0;\n    //     for (auto cell_2d_id : iter->second) {\n    //         w += (WeightType)(complex->getWeight(2, cell_2d_id));\n    //     }\n\n    //     _graph.addEdge(edge.first, edge.second, w);\n    //     _graph.addEdge(edge.second, void_cnt + edge_id, w);\n    //     _graph.addEdge(void_cnt + edge_id, edge.first, w);\n\n    //     edge_id ++;\n    // }\n\n    // return;\n\n\n    /* compute the maximal flow */\n\n    typedef boost::adjacency_list_traits < boost::vecS, boost::vecS, boost::directedS > Traits;\n\n    typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::directedS,\n    // boost::property < boost::vertex_name_t, std::string,\n    boost::property < boost::vertex_index_t, int, // originally it's 'long'\n    boost::property < boost::vertex_color_t, boost::default_color_type,\n    boost::property < boost::vertex_distance_t, int, // originally it's 'long'\n    boost::property < boost::vertex_predecessor_t, Traits::edge_descriptor > > > >,\n\n    boost::property < boost::edge_capacity_t, WeightType,\n    boost::property < boost::edge_residual_capacity_t, WeightType,\n    boost::property < boost::edge_reverse_t, Traits::edge_descriptor > > > > FlowGraphBoost;\n\n    if (ops.verbose) {\n        cout << endl << \"graph elem sizes: \" \n            << sizeof(Traits::vertex_descriptor) << \" \" \n            << sizeof(Traits::edge_descriptor) << endl;\n    }\n\n    FlowGraphBoost* graph = new FlowGraphBoost;\n    typename boost::property_map<FlowGraphBoost, boost::edge_capacity_t>::type\n        capacity = get(boost::edge_capacity, *graph);\n    typename boost::property_map<FlowGraphBoost, boost::edge_residual_capacity_t>::type\n        residual_capacity = get(boost::edge_residual_capacity, *graph);\n    typename boost::property_map<FlowGraphBoost, boost::edge_reverse_t>::type \n        reverse_edge = get(boost::edge_reverse, *graph);\n\n    for (auto iter = gedge_cell_map->begin(); \n        iter != gedge_cell_map->end(); iter ++) {\n\n        const std::pair<int,int>& edge = iter->first;\n        Traits::edge_descriptor e1, e2;\n\n        boost::tie(e1, boost::tuples::ignore) \n            = add_edge(edge.first, edge.second, *graph);\n        boost::tie(e2, boost::tuples::ignore) \n            = add_edge(edge.second, edge.first, *graph);\n\n        WeightType w = 0;\n        for (auto cell_2d_id : iter->second) {\n            w += (WeightType)(complex->getWeight(2, cell_2d_id));\n        }\n\n        // cout << edge << \" w=\" << w << endl;\n\n        capacity[e1] = w;\n        capacity[e2] = w;\n        reverse_edge[e1] = e2;\n        reverse_edge[e2] = e1;\n    }\n    \n    cout << endl << \"build flow network done\" << endl;\n \n    auto max_flow = boykov_kolmogorov_max_flow(*graph ,src, sink);\n    if (ops.verbose) {\n        cout << endl << \"max_flow: \" << (double)max_flow << endl;\n    }\n\n\n    /* do a DFS to get the min-cut */\n\n    if (ops.verbose) {\n        cout << \"graph num_vertices: \" << num_vertices(*graph) << endl;\n    }\n\n    vector<bool> visited;\n\n    {\n        visited.resize(num_vertices(*graph), false);\n        visited[src] = true;\n        vector<int> vert_stack = { src };\n\n        while (!vert_stack.empty()) {\n            auto v = vert_stack.back();\n            vert_stack.pop_back();\n\n            typename boost::graph_traits<FlowGraphBoost>::out_edge_iterator e_iter, e_end;\n            boost::tie(e_iter, e_end) = out_edges(v, *graph);\n            for (; e_iter != e_end; e_iter ++) {\n                if (residual_capacity[*e_iter] > 0) {\n                    int adj_v = target(*e_iter, *graph);\n                    if (!visited[adj_v]) {\n                        vert_stack.push_back(adj_v);\n                        visited[adj_v] = true;\n                    }\n                }\n            }\n        }\n    }\n\n    delete graph;\n\n    \n    /* collect edges across the min-cut */\n\n    MeshWriter mesh_writer(complex, complex->getVertCnt(2));\n    vector<int> cell_2d_verts;\n\n    for (auto iter = gedge_cell_map->begin(); \n        iter != gedge_cell_map->end(); iter ++) {\n\n        const std::pair<int,int>& edge = iter->first;\n        if (visited[edge.first] != visited[edge.second]) {\n            for (auto cell_2d_id : iter->second) {\n                complex->getCellVerts(2, cell_2d_id, &cell_2d_verts);\n                mesh_writer.addFace(cell_2d_verts);\n            }\n        }\n    }\n\n    mesh_writer.write(file_prefix + \"_mincyc.off\");\n}\n\nvoid getBitmapComplexCellVerts(const int cell_handle, const int cell_dim, \n    const int x_res, const int y_res, const int z_res, vector<int>* verts) {\n\n    const int x_cnt = 2*x_res + 1;\n    const int y_cnt = 2*y_res + 1;\n\n    const int z_coord = cell_handle / (x_cnt*y_cnt);\n    const int left = cell_handle % (x_cnt*y_cnt);\n    const int y_coord = left / x_cnt;\n    const int x_coord = left % x_cnt;\n\n    int vari_cnt = 0;\n\n    int x_vari = 1;\n    if (x_coord % 2 == 1) {\n        x_vari = 2;\n        vari_cnt ++;\n    }\n\n    int y_vari = 1;\n    if (y_coord % 2 == 1) {\n        y_vari = 2;\n        vari_cnt ++;\n    }\n\n    int z_vari = 1;\n    if (z_coord % 2 == 1) {\n        z_vari = 2;\n        vari_cnt ++;\n    }\n\n#ifdef DEBUG_OPT\n    if (vari_cnt != cell_dim) {\n        cout << \"FATAL: getBitmapCC2dCellVerts dim not equal\" << endl;\n        exit(-1);\n    }\n#endif\n\n    vector<int> temp_verts;\n    for (auto x = x_coord/2; x < x_coord/2 + x_vari; x ++) {\n        for (auto y = y_coord/2; y < y_coord/2 + y_vari; y ++) {\n            for (auto z = z_coord/2; z < z_coord/2 + z_vari; z ++) {\n                temp_verts.push_back(x + y*(x_res+1) + z*(x_res+1)*(y_res+1));\n            }\n        }\n    }\n\n    if (cell_dim == 2) {\n        *verts = {temp_verts[0], temp_verts[1], temp_verts[3], temp_verts[2]};\n    } else if (cell_dim == 3) {\n        *verts = {temp_verts[0], temp_verts[1], temp_verts[3], temp_verts[2],\n            temp_verts[4], temp_verts[5], temp_verts[7], temp_verts[6]};\n    }\n}\n\nvoid printGEdgeCellMap(const GEdgeCellMap* gedge_cell_map, CellComplex* complex) {\n    cout << \"3-cells [\" << complex->getCellCount(3) << \"]:\" << endl;\n    for (int cell_3d_id = 0; cell_3d_id < complex->getCellSize(3); cell_3d_id ++) {\n        if (complex->isCellValid(3, cell_3d_id)) {\n            vector<int> verts;\n            complex->getCellVerts(3, cell_3d_id, &verts);\n            cout << cell_3d_id << \": \" << verts << endl;\n        }\n    }\n    cout << endl;\n\n    for (auto iter = gedge_cell_map->begin(); \n        iter != gedge_cell_map->end(); iter ++) {\n\n        cout << iter->first << \":\" << endl;\n        for (auto cell_2d_id : iter->second) {\n            vector<int> verts;\n            complex->getCellVerts(2, cell_2d_id, &verts);\n            cout << \"  \" << verts << endl;\n        }\n    }\n}\n\nvoid getCell2dVoidIds(\n    const int cell_2d_id, CellComplex* complex, \n    vector<array<int,2>>* cell_2d_void_map, vector<int>* void_ids) {\n\n    void_ids->clear();\n\n    auto cofaces = complex->getCellCofaces(2, cell_2d_id);\n    for (auto cell_3d_id : *cofaces) {\n        void_ids->push_back(cell_3d_id);\n    }\n\n    for (auto void_id : cell_2d_void_map->at(cell_2d_id)) {\n        if (void_id >= 0) {\n            void_ids->push_back(void_id);\n        }\n    }\n\n    if (void_ids->size() != 2) {\n        cout << \"FATAL: void_ids.size() != 2 in getCell2dVoidIds\" << endl;\n        exit(-1);\n    }\n}\n  \n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9c979c3c0d56a8a850162d247b8e2a335ba26d89", "size": 43241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pers2cyc_inf/src/inf_pers2cyc.cpp", "max_stars_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_stars_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "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": "pers2cyc_inf/src/inf_pers2cyc.cpp", "max_issues_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_issues_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T14:35:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T14:18:00.000Z", "max_forks_repo_path": "pers2cyc_inf/src/inf_pers2cyc.cpp", "max_forks_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_forks_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6101055807, "max_line_length": 101, "alphanum_fraction": 0.577946856, "num_tokens": 12258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.5792195625691517}}
{"text": "#ifndef _LDAPLUSPLUS_OPTIMIZATION_SECOND_ORDER_LOGISTIC_REGRESSION_APPROXIMATION_HPP_\n#define _LDAPLUSPLUS_OPTIMIZATION_SECOND_ORDER_LOGISTIC_REGRESSION_APPROXIMATION_HPP_\n\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Core>\n\nnamespace ldaplusplus {\nnamespace optimization {\n\n\n/**\n * SecondOrderLogisticRegressionApproximation is a second order taylor\n * approximation to the expectation of the logistic loss function of a random\n * variable.\n *\n * We use this class to approximate the following equation in the lower bound\n * of the likelihood of an LDA model. \\f$q\\f$ is the variational distribution\n * used and \\f$\\bar{z}\\f$ is a random variable (the mean of the topic\n * assignments). The equation below is for a single document.\n *\n * \\f[\n *     \\mathbb{E}_q\\left[\n *         \\eta_{y_n}^T \\bar{z} -\n *         \\log\\left( \\sum_{\\hat{y}=1}^Y \\exp(\\eta_{\\hat{y}}^T \\bar{z}) \\right)\n *         \\right] \\approx\n *         \\eta_{y_n}^T \\mathbb{E}_q[\\bar{z}] -\n *         \\log \\sum_{\\hat{y}=1}^Y \\exp(\\eta_{\\hat{y}}^T \\mathbb{E}_q[\\bar{z})\\left(\n *         1 + \\frac{1}{2} \\eta_{\\hat{y}}^T \\mathbb{V}_q[\\bar{z}] \\eta_{\\hat{y}}\n *         \\right)\n * \\f]\n */\ntemplate <typename Scalar>\nclass SecondOrderLogisticRegressionApproximation\n{\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX;\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> VectorX;\n\n    public:\n        /**\n         * @param X     The documents defining the minimization problem (\\f$X\n         *              \\in \\mathbb{R}^{D \\times N}\\f$)\n         * @param X_var A vector containing the variance matrix for each\n         *              document (\\f$X_{\\text{var}} \\in \\mathbb{R}^{N \\times D\n         *              \\times D}\\f$)\n         * @param y     The class indexes for each document (\\f$y \\in\n         *              \\mathbb{N}^N\\f$)\n         * @param Cy    A different weight for each class in the optimization\n         *              problem\n         * @param L     The L2 regularization penalty for the weights\n         */\n        SecondOrderLogisticRegressionApproximation(\n            const MatrixX &X,\n            const std::vector<MatrixX> &X_var,\n            const Eigen::VectorXi &y,\n            VectorX Cy,\n            Scalar L\n        );\n\n        /**\n         * @param X     The documents defining the minimization problem (\\f$X\n         *              \\in \\mathbb{R}^{D \\times N}\\f$)\n         * @param X_var A vector containing the variance matrix for each\n         *              document (\\f$X_{\\text{var}} \\in \\mathbb{R}^{N \\times D\n         *              \\times D}\\f$)\n         * @param y     The class indexes for each document (\\f$y \\in\n         *              \\mathbb{N}^N\\f$)\n         * @param L     The L2 regularization penalty for the weights\n         */\n        SecondOrderLogisticRegressionApproximation(\n            const MatrixX &X,\n            const std::vector<MatrixX> &X_var,\n            const Eigen::VectorXi &y,\n            Scalar L\n        );\n\n        /**\n         * The value of the objective function to be minimized.\n         *\n         * \\f$N\\f$ is the number of documents (different vectors), \\f$X_n \\in\n         * \\mathbb{R}^D\\f$ is the nth document, \\f$\\eta_y \\in \\mathbb{R}^D\\f$\n         * is the weights vector for the class \\f$y\\f$ defining the hyperplane\n         * that separates class \\f$y\\f$ from all the other, \\f$y_n\\f$\n         * is the class of the nth document and finally \\f$X_n^{\\text{var}} \\in\n         * \\mathbb{R}^{D \\times D}\\f$ is the variance of the nth document (see\n         * the class description).\n         *\n         * \\f[\n         *     J = - \\sum_{n=1}^N C_{y_n} \\left(\n         *         \\eta_{y_n}^T X_n -\n         *         \\log \\sum_{\\hat{y}=1}^Y \\exp(\\eta_{\\hat{y}}^T X_n) \\left(\n         *         1 +\n         *         \\frac{1}{2} \\eta_{\\hat{y}}^T X_n^{\\text{var}} \\eta_{\\hat{y}}\n         *         \\right)\n         *         \\right) +\n         *         \\frac{L}{2} \\left\\| \\eta \\right\\|_F^2\n         * \\f]\n         *\n         * @param eta The weights of the linear model (\\f$\\eta \\in\n         *            \\mathbb{R}^{D \\times Y}\\f$)\n         */\n        Scalar value(const MatrixX &eta) const;\n        \n        /**\n         * The gradient of the objective function implemented in value().\n         *\n         * We use \\f$I(y) \\in \\mathbb{R}^Y\\f$ as the indicator vector of\n         * \\f$y\\f$ (a vector with all the values 0 except at the yth position).\n         *\n         * \\f[\n         *     \\nabla_{\\eta} J = - \\sum_{n=1}^N C_{y_n} \\left(\n         *         X_n I(y_n)^T -\n         *         \\frac{\n         *              \\sum_{\\hat{y}=1}^Y \\left(\\left(\n         *              X_n \\exp(\\eta_{\\hat{y}}^T X_n) \\left(\n         *              1 +\n         *              \\frac{1}{2} \\eta_{\\hat{y}}^T X_n^{\\text{var}} \\eta_{\\hat{y}}\n         *              \\right)\\right) + \\left(\n         *              \\frac{1}{2}\n         *              \\exp(\\eta_{\\hat{y}}^T X_n) \\eta_{\\hat{y}}^T \\left(\n         *              X_n^{\\text{var}} + \\left(X_n^{\\text{var}}\\right)^T\n         *              \\right)\\right)\n         *              \\right) I(\\hat{y})^T\n         *              }\n         *              {\n         *              \\sum_{\\hat{y}=1}^Y \\exp(\\eta_{\\hat{y}}^T X_n) \\left(\n         *              1 +\n         *              \\frac{1}{2} \\eta_{\\hat{y}}^T X_n^{\\text{var}} \\eta_{\\hat{y}}\n         *              \\right)\n         *              }\n         *         \\right) +\n         *         L \\eta\n         * \\f]\n         *\n         * @param eta  The weights of the linear model (\\f$\\eta \\in\n         *             \\mathbb{R}^{D \\times Y}\\f$)\n         * @param grad A matrix of dimensions equal to \\f$\\eta\\f$ that will\n         *             hold the result\n         */\n        void gradient(const MatrixX &eta, Eigen::Ref<MatrixX> grad) const;\n\n    private:\n        const MatrixX &X_;\n        const std::vector<MatrixX> &X_var_;\n        const Eigen::VectorXi &y_;\n        Scalar L_;\n        VectorX Cy_;\n};\n\n\n}  // namespace optimization\n}  // namespace ldaplusplus\n\n#endif // _LDAPLUSPLUS_OPTIMIZATION_SECOND_ORDER_LOGISTIC_REGRESSION_APPROXIMATION_HPP_\n", "meta": {"hexsha": "d2a225c1f8a440d7fa0f1f64cc7272f1d0ae2d3d", "size": 6146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ldaplusplus/optimization/SecondOrderLogisticRegressionApproximation.hpp", "max_stars_repo_name": "angeloskath/supervised-lda", "max_stars_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-25T11:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T08:51:41.000Z", "max_issues_repo_path": "include/ldaplusplus/optimization/SecondOrderLogisticRegressionApproximation.hpp", "max_issues_repo_name": "angeloskath/supervised-lda", "max_issues_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T15:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:43:16.000Z", "max_forks_repo_path": "include/ldaplusplus/optimization/SecondOrderLogisticRegressionApproximation.hpp", "max_forks_repo_name": "angeloskath/supervised-lda", "max_forks_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-09-28T14:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T14:22:38.000Z", "avg_line_length": 39.3974358974, "max_line_length": 87, "alphanum_fraction": 0.5042303938, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5792092905176934}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <cassert>\n#include <vector>\n#include \"Option.h\"\n#include <cmath>\n#include \"Regression.h\"\n#include \"FileManagement.h\"\n#include <chrono>\n#include \"nonuniform_grid.h\"\n#include <random>\n#include \"Simulation.h\"\n#include <tuple>\n#include \"HestonOption.h\"\n#include \"OptimalExecution.h\"\n\n\n\n\nint main() {\n\n  // Generation of option prices\n  // auto o = Option(\"Call\");\n  // o.set_tn(1);\n  // o.set_s_max(100);\n  // o.set_numdiff_t(10);\n  // o.set_numdiff_s(10);\n  // o.set_volatility(.1);\n  // o.set_interest_rate(.15);\n  // o.set_strike(50);\n  // o.set_stock_boundary_condition(\"Dirichlet\");\n  // o.fixed_difference_step();\n  //\n  // o.compute_solution_grid(\"Crank-Nicholson\");\n  // o.print_solution_grid();\n\n\n  // Heston option Monte-Carlo Simulation\n  // auto h = HestonOption(\"Call\", 1, 10, 100, 50);\n  // h.set_params_stock_process(45, .1);\n  // h.set_prams_variance_process(.2, 1, 1, .25, .5);\n  // auto pr = h.compute_price();\n  //\n  // std::cout << pr << \"\\n\";\n\n\n  // Generation of optimal execution paths\n   // double a_coeff_, double b_coeff_, double sigma_coeff_, double k_coeff_, double phi_coeff_\n   // auto o = OptimalExecution(.6,.1, 0.1,.1,.6);\n   // // num_diff_t_, int num_diff_q_\n   // o.set_num_steps(100,100);\n   // // true_impact, trading_speed, impact_nonlinearity\n   // o.compute_liquidation(\"Linear\", 1);\n   // Eigen::VectorXd h = o.get_value_process();\n   // std::cout << \"Value Process\\n\" << h << \"\\n\";\n   // Eigen::VectorXd j = o.get_optimal_speed_process();\n   // std::cout << \"Speed Process\\n\" << j << \"\\n\";\n   // Eigen::VectorXd s = o.get_stock_process();\n   // std::cout << \"Stock Process\\n\" << s << \"\\n\";\n   // Eigen::VectorXd c = o.get_cash_process();\n   // std::cout << \"Cash Process\\n\" << c << \"\\n\";\n   // Eigen::VectorXd i = o.get_inventory_process();\n   // std::cout << \"Inventory Process\\n\" << i << \"\\n\";\n   //\n   // std::cout << o.get_value_matrix();\n\n    // Generate 500 optimal execution scenarios and save it in the csv files\n    // Eigen::MatrixXd nonlinear_speed_csv_value,nonlinear_speed_csv_optimal_speed, nonlinear_speed_csv_stock, nonlinear_speed_csv_cash, nonlinear_speed_csv_inventory;\n    // nonlinear_speed_csv_value.resize(101,100); nonlinear_speed_csv_optimal_speed.resize(101,100); nonlinear_speed_csv_stock.resize(101,100); nonlinear_speed_csv_cash.resize(101,100); nonlinear_speed_csv_inventory.resize(101,100);\n    // Eigen::MatrixXd linear_speed_csv_value,linear_speed_csv_optimal_speed, linear_speed_csv_stock, linear_speed_csv_cash, linear_speed_csv_inventory;\n    // linear_speed_csv_value.resize(101,100); linear_speed_csv_optimal_speed.resize(101,100); linear_speed_csv_stock.resize(101,100); linear_speed_csv_cash.resize(101,100); linear_speed_csv_inventory.resize(101,100);\n    // for (int sim = 0; sim < 100; ++sim) {\n        // Trading speed: Nonlinear, true impact: Nonlinear\n        // auto o = OptimalExecution(.08,.06, .1,.08,.06);\n        // o.set_num_steps(100,100);\n        // o.compute_liquidation(\"Nonlinear\", \"Nonlinear\", .6);\n        // Eigen::VectorXd value_process = o.get_value_process();\n        // nonlinear_speed_csv_value.col(sim) = value_process;\n        // Eigen::VectorXd optimal_speed_process = o.get_optimal_speed_process();\n        // nonlinear_speed_csv_optimal_speed.col(sim) = optimal_speed_process;\n        // Eigen::VectorXd stock_process = o.get_stock_process();\n        // nonlinear_speed_csv_stock.col(sim) = stock_process;\n        // Eigen::VectorXd cash_process = o.get_cash_process();\n        // nonlinear_speed_csv_cash.col(sim) = cash_process;\n        // Eigen::VectorXd inventory_process = o.get_inventory_process();\n        // nonlinear_speed_csv_inventory.col(sim) = inventory_process;\n\n        // Trading speed: Linear, true impact: Nonlinear\n        // auto ol = OptimalExecution(.6,.1, 0.1,.1,.6);\n        // ol.set_num_steps(100,100);\n        // ol.compute_liquidation(\"Linear\", 1);\n        // Eigen::VectorXd value_process_lin = ol.get_value_process();\n        // linear_speed_csv_value.col(sim) = value_process_lin;\n        // Eigen::VectorXd optimal_speed_process_lin = ol.get_optimal_speed_process();\n        // linear_speed_csv_optimal_speed.col(sim) = optimal_speed_process_lin;\n        // Eigen::VectorXd stock_process_lin = ol.get_stock_process();\n        // linear_speed_csv_stock.col(sim) = stock_process_lin;\n        // Eigen::VectorXd cash_process_lin = ol.get_cash_process();\n        // linear_speed_csv_cash.col(sim) = cash_process_lin;\n        // Eigen::VectorXd inventory_process_lin = ol.get_inventory_process();\n        // linear_speed_csv_inventory.col(sim) = inventory_process_lin;\n    // }\n    // saveData(\"data/nonlinear_speed_csv_value.csv\", nonlinear_speed_csv_value);\n    // saveData(\"data/nonlinear_speed_csv_optimal_speed.csv\", nonlinear_speed_csv_optimal_speed);\n    // saveData(\"data/nonlinear_speed_csv_stock.csv\", nonlinear_speed_csv_stock);\n    // saveData(\"data/nonlinear_speed_csv_cash.csv\", nonlinear_speed_csv_cash);\n    // saveData(\"data/nonlinear_speed_csv_inventory.csv\", nonlinear_speed_csv_inventory);\n\n    // saveData(\"data/linear_speed_csv_value.csv\", linear_speed_csv_value);\n    // saveData(\"data/linear_speed_csv_optimal_speed.csv\", linear_speed_csv_optimal_speed);\n    // saveData(\"data/linear_speed_csv_stock.csv\", linear_speed_csv_stock);\n    // saveData(\"data/linear_speed_csv_cash.csv\", linear_speed_csv_cash);\n    // saveData(\"data/linear_speed_csv_inventory.csv\", linear_speed_csv_inventory);\n\n\n\n\n\n    return 0;\n}\n", "meta": {"hexsha": "e86d9d784f66156e1ad9f6c7a0c6b2412f3d72e6", "size": 5523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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": 45.6446280992, "max_line_length": 232, "alphanum_fraction": 0.70106826, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5792092853828321}}
{"text": "#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\nusing namespace Rcpp;\nusing namespace Eigen;\n\n// [[Rcpp::depends(RcppEigen)]]\n//\n\ntypedef Eigen::MappedSparseMatrix<double> MSpMat;\ntypedef Eigen::SparseMatrix<double> SpMat;\nEigen::SimplicialLLT <Eigen::SparseMatrix<double>, Eigen::Lower, Eigen::NaturalOrdering<int>> cholesky;\n\n// [[Rcpp::export]]\ndouble bym_scale(const SEXP &Q_) {\n    \n    //Map SparseMatrix\n    const SpMat Q(Rcpp::as<MSpMat>(Q_));\n    \n    MatrixXd L = cholesky.compute(Q).matrixL();\n    MatrixXd Sigma;\n    Sigma.setZero(Q.rows(),Q.cols());\n    Sigma.diagonal() = 1 / pow(L.diagonal().array(), 2);\n    int n = Sigma.rows();\n    for(int i = (n-2); i >= 0; --i){ \n        for(int j = (n-1); j >= i; --j){\n            Sigma(i,j) -= 1.0 / L(i,i) * Sigma.col(j).tail(n-i-1).dot(L.col(i).tail(n-i-1));\n            Sigma(j,i) = Sigma(i,j);\n        }\n    }\n    \n    MatrixXd A = Eigen::MatrixXd::Constant(1,n,1);\n    MatrixXd W = Sigma * A.transpose();\n    Sigma = Sigma - W * (A*W).inverse() * W.transpose(); \n    \n    \n    return(exp(Sigma.diagonal().array().log().mean()));\n}", "meta": {"hexsha": "7a568e6c2583ddf63045f8601fd6500a4947b3a6", "size": 1141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bym_scale.cpp", "max_stars_repo_name": "apeterson91/BYMScale", "max_stars_repo_head_hexsha": "9a439beac177e5dc26102f2975e98e88e5fd8170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bym_scale.cpp", "max_issues_repo_name": "apeterson91/BYMScale", "max_issues_repo_head_hexsha": "9a439beac177e5dc26102f2975e98e88e5fd8170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bym_scale.cpp", "max_forks_repo_name": "apeterson91/BYMScale", "max_forks_repo_head_hexsha": "9a439beac177e5dc26102f2975e98e88e5fd8170", "max_forks_repo_licenses": ["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.2564102564, "max_line_length": 103, "alphanum_fraction": 0.5950920245, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541643004809, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5792000405573565}}
{"text": "/**\n * @file GaussianHyperparameters.cpp\n * @author Jan Nguyen\n * @date 11.05.20\n */\n\n#include \"GaussianHyperparameters.h\"\n\n#include <Eigen/Cholesky>\n\n#include \"GaussianProcess.h\"\n\nvoid autopas::GaussianHyperparameters::precalculate(double sigma, const std::vector<Eigen::VectorXd> &inputs,\n                                                    const Eigen::VectorXd &outputs) {\n  size_t size = outputs.size();\n  // mean of output shifted to zero\n  Eigen::VectorXd outputCentered = outputs - mean * Eigen::VectorXd::Ones(size);\n\n  Eigen::MatrixXd covMat(size, size);\n  // calculate covariance matrix\n  for (size_t i = 0; i < size; ++i) {\n    covMat(i, i) = GaussianProcess::kernel(inputs[i], inputs[i], theta, dimScales) + sigma;\n    for (size_t j = i + 1; j < size; ++j) {\n      covMat(i, j) = covMat(j, i) = GaussianProcess::kernel(inputs[i], inputs[j], theta, dimScales);\n    }\n  }\n\n  // cholesky decomposition\n  Eigen::LLT<Eigen::MatrixXd> llt = covMat.llt();\n  Eigen::MatrixXd l = llt.matrixL();\n\n  // precalculate inverse of covMat and weights for predictions\n  covMatInv = llt.solve(Eigen::MatrixXd::Identity(size, size));\n  weights = covMatInv * outputCentered;\n\n  // likelihood of evidence given parameters\n  score = std::exp(-0.5 * outputCentered.dot(weights)) / l.diagonal().prod();\n\n  if (std::isnan(score)) {\n    // error score calculation failed\n    utils::ExceptionHandler::exception(\"GaussianProcess: invalid score \", score);\n  }\n}\n", "meta": {"hexsha": "69a4ea89c776cc5d2716960339b9faf81a1f7b0a", "size": 1446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/autopas/selectors/tuningStrategy/GaussianModel/GaussianHyperparameters.cpp", "max_stars_repo_name": "TheH0bbit/autopas_dem", "max_stars_repo_head_hexsha": "d7761e6ba0f6353fb97ecf78fb60873a00e41e17", "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/autopas/selectors/tuningStrategy/GaussianModel/GaussianHyperparameters.cpp", "max_issues_repo_name": "TheH0bbit/autopas_dem", "max_issues_repo_head_hexsha": "d7761e6ba0f6353fb97ecf78fb60873a00e41e17", "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/autopas/selectors/tuningStrategy/GaussianModel/GaussianHyperparameters.cpp", "max_forks_repo_name": "TheH0bbit/autopas_dem", "max_forks_repo_head_hexsha": "d7761e6ba0f6353fb97ecf78fb60873a00e41e17", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8636363636, "max_line_length": 109, "alphanum_fraction": 0.6618257261, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.579167502086554}}
{"text": "/*\n * KolmogorovComputer.cpp\n *\n *  Created on: Jan 28, 2014\n *      Author: jan\n *\n *      This class handles everything that deals with the Kolmogorov distance or Kolmogorov function. In particular this class provides the number of needed\n *      simulations S for each provided tolerance epsilon, and the other way around. It also computes the distance between a computed trajectory and the original data.\n *      The parameters beta  comes from: d(Y_S, X_M) < epsilon ==> P(d(Y, X) > epsilon) <= beta for further details see Lillacci & Khammash 2013\n *      The parameter kappa is the computed tolerance corresponding to the number of samples in the original dataset\n */\n\n#include \"KolmogorovComputer.h\"\n\n#include <cmath>\n#include <iostream>\n#include <cstdlib>\n\n#include <Eigen/Dense>\n#include <boost/math/tools/roots.hpp>\n\n#include \"IllegalArgumentException.h\"\n\nnamespace INSIGHTv3 {\n\n// Constructor for approximated kappa\nKolmogorovComputer::KolmogorovComputer(\n\t\tconst std::vector<EiVector>& original_data, double beta,\n\t\tdouble tolerance) {\n\n\t_kappa = getKappaForMApprox(original_data[0].size(), beta);\n\t_beta = beta;\n\t_tolerance = tolerance;\n\t_init(original_data);\n}\n\n// Constructor for exact kappa\nKolmogorovComputer::KolmogorovComputer(double kappa_tolerance,\n\t\tconst std::vector<EiVector>& original_data, double beta,\n\t\tdouble tolerance) {\n\n\tstd::cout\n\t\t\t<< \"Exact kappa for the KolmovorovComputer is being computed. M is \"\n\t\t\t<< original_data[0].size()\n\t\t\t<< \". The tolerance for the kolmogorov function root solver is \"\n\t\t\t<< kappa_tolerance\n\t\t\t<< \". This may take a long time. Consider using one of the other constructors that use a precomputed kappa, or compute kappa only approximately\"\n\t\t\t<< std::endl;\n\t_kappa = getKappaForM(original_data[0].size(), beta, kappa_tolerance);\n\t_beta = beta;\n\t_tolerance = tolerance;\n\t_init(original_data);\n}\n\n// Constructor for precomputed kappa\nKolmogorovComputer::KolmogorovComputer(\n\t\tconst std::vector<EiVector>& original_data, double beta,\n\t\tdouble tolerance, double kappa) {\n\n\t_kappa = kappa;\n\t_beta = beta;\n\t_tolerance = tolerance;\n\t_init(original_data);\n}\n\nKolmogorovComputer::~KolmogorovComputer() {\n}\n\nvoid KolmogorovComputer::_init(const std::vector<EiVector>& original_data) {\n\tfor (size_t column = 0; column < original_data.size(); column++) {\n\t\tEiVector single_column = original_data[column];\n\t\tstd::sort(single_column.data(),\n\t\t\t\tsingle_column.data() + single_column.size());\n\t\t_sorted_Data.push_back(single_column);\n\t}\n\n}\n\ndouble KolmogorovComputer::distTwoSample(const EiVector& first_sample,\n\t\tconst size_t column_of_second_sample) {\n\n\tsize_t j1 = 0, j2 = 0;\n\tdouble distance = 0.0, d1, d2, dt, fn1 = 0.0, n1 =\n\t\t\t(double) first_sample.size(), fn2 = 0.0, n2 =\n\t\t\t(_sorted_Data[column_of_second_sample]).size();\n\n\tEiVector first_sample_sorted = EiVector(first_sample);\n\tstd::sort(first_sample_sorted.data(),\n\t\t\tfirst_sample_sorted.data() + first_sample_sorted.size());\n\n\tEiVector* second_sample_sorted = (&_sorted_Data[column_of_second_sample]);\n\n\twhile (j1 < n1 && j2 < n2) {\n\t\tif ((d1 = first_sample_sorted(j1))\n\t\t\t\t<= (d2 = (*second_sample_sorted)(j2))) {\n\n\t\t\tEiVectorRef first_sample_tail = first_sample_sorted.tail(\n\t\t\t\t\tfirst_sample_sorted.size() - j1);\n\n\t\t\tif (d1 == d2) {\n\t\t\t\tj1 = j1 + _findLargestIndex(d2, first_sample_tail) + 1;\n\t\t\t} else {\n\t\t\t\tj1 = j1 + _findSmallestPredecesorIndex(d2, first_sample_tail)\n\t\t\t\t\t\t+ 1;\n\t\t\t}\n\t\t}\n\t\tif (d2 <= d1) {\n\t\t\tEiVectorRef second_sample_tail = second_sample_sorted->tail(\n\t\t\t\t\tsecond_sample_sorted->size() - j2);\n\t\t\tif (d1 == d2) {\n\t\t\t\tj2 = j2 + _findLargestIndex(d1, second_sample_tail) + 1;\n\t\t\t} else {\n\t\t\t\tj2 = j2 + _findSmallestPredecesorIndex(d1, second_sample_tail)\n\t\t\t\t\t\t+ 1;\n\t\t\t}\n\t\t}\n\t\tfn2 = (j2) / n2;\n\t\tfn1 = (j1) / n1;\n\t\tif ((dt = fabs((double) fn2 - fn1)) > distance)\n\t\t\tdistance = dt;\n\t}\n\n\treturn distance;\n}\n\nsize_t KolmogorovComputer::_findSmallestPredecesorIndex(const double value,\n\t\tEiVectorRef& _vector) {\n\tif (_vector.size() == 1) {\n\t\treturn 0;\n\t} else {\n\t\tsize_t median_index = floor(_vector.size() / 2.0);\n\t\tdouble median = _vector(median_index);\n\t\tif (value > median) {\n\n\t\t\tEiVectorRef upper_sub_vector = _vector.tail(\n\t\t\t\t\t_vector.size() - median_index);\n\n\t\t\treturn median_index\n\t\t\t\t\t+ _findSmallestPredecesorIndex(value, upper_sub_vector);\n\t\t} else {\n\t\t\tEiVectorRef lower_sub_vector = _vector.head(median_index);\n\t\t\treturn _findSmallestPredecesorIndex(value, lower_sub_vector);\n\t\t}\n\t}\n\n}\n\nsize_t KolmogorovComputer::_findLargestIndex(const double value,\n\t\tEiVectorRef& _vector) {\n\tif (_vector.size() == 1) {\n\t\treturn 0;\n\t} else {\n\t\tsize_t median_index = floor(_vector.size() / 2.0);\n\t\tdouble median = _vector(median_index);\n\t\tif (value >= median) {\n\t\t\tEiVectorRef upper_sub_vector = _vector.tail(\n\t\t\t\t\t_vector.size() - median_index);\n\n\t\t\treturn median_index + _findLargestIndex(value, upper_sub_vector);\n\t\t} else {\n\t\t\tEiVectorRef lower_sub_vector = _vector.head(median_index);\n\t\t\treturn _findLargestIndex(value, lower_sub_vector);\n\t\t}\n\t}\n}\n\ndouble KolmogorovComputer::getKappaForMApprox(int M, double beta) {\n\tdouble alpha = 1 - sqrt(1.0 - beta);\n\treturn sqrt(-(1 / (2.0 * M)) * log(alpha / 2.0));\n}\n\ndouble KolmogorovComputer::getKappaForM(int M, double beta, double tolerance) {\n\treturn kolmogorovCdfInverse(M, 1 - (1 - sqrt(1 - beta)), tolerance);\n}\n\ndouble KolmogorovComputer::getThresholdForSApprox(int s, double beta, int M) {\n\tdouble kappa = getKappaForMApprox(M, beta);\n\treturn getThresholdForSApprox(s, beta, kappa);\n}\n\ndouble KolmogorovComputer::getThresholdForSApprox(int s, double beta,\n\t\tdouble kappa) {\n\tdouble alpha = 1 - sqrt(1.0 - beta);\n\treturn sqrt(-(1 / (2.0 * s)) * log(alpha / 2.0)) + kappa;\n}\n\ndouble KolmogorovComputer::getThresholdForS(int s, double beta, double kappa,\n\t\tdouble tolerance) {\n\treturn kolmogorovCdfInverse(s, 1 - (1 - sqrt(beta)), tolerance) + kappa;\n}\n\nint KolmogorovComputer::getSForThresholdApprox(double threshold, double beta,\n\t\tint M) {\n\tdouble kappa = getKappaForMApprox(M, beta);\n\treturn getSForThresholdApprox(threshold, beta, kappa);\n}\n\nint KolmogorovComputer::getSForThresholdApprox(double threshold, double beta,\n\t\tdouble kappa) {\n\tdouble alpha = 1 - sqrt(1.0 - beta);\n\tint s = ceil(-log(alpha / 2.0) / (2.0 * pow(threshold - kappa, 2.0)));\n\treturn s;\n}\n\nint KolmogorovComputer::getSForThreshold(double threshold, double beta,\n\t\tdouble kappa, double tolerance) {\n\tint s = 1;\n\tdouble tol = kolmogorovCdfInverse(s, 1 - (1 - sqrt(beta)), tolerance);\n\twhile (tol < threshold - kappa) {\n\t\ts++;\n\t\ttol = kolmogorovCdfInverse(s, 1 - (1 - sqrt(beta)), tolerance);\n\t}\n\treturn s;\n}\n\ndouble KolmogorovComputer::getThresholdForSApprox(int s) {\n\tdouble alpha = 1 - sqrt(1.0 - _beta);\n\treturn sqrt(-(1 / (2.0 * s)) * log(alpha / 2.0)) + _kappa;\n}\n\ndouble KolmogorovComputer::getThresholdForS(int s) {\n\treturn kolmogorovCdfInverse(s) + _kappa;\n}\n\nint KolmogorovComputer::getSForThresholdApprox(double threshold) {\n\n\tdouble alpha = 1 - sqrt(1.0 - _beta);\n\tint s = ceil(-log(alpha / 2.0) / (2.0 * pow(threshold - _kappa, 2.0)));\n\treturn s;\n}\n\nint KolmogorovComputer::getSForThreshold(double threshold) {\n\tint s = 1;\n\tdouble tol = kolmogorovCdfInverse(s);\n\twhile (tol < threshold - _kappa) {\n\t\ts++;\n\t\ttol = kolmogorovCdfInverse(s);\n\t}\n\treturn s;\n}\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/**\n Supporting function for kolmogorov_cdf_marsaglia, not to be used directly.\n */\nvoid mMultiply(double *A, double *B, double *C, int m) {\n\tint i, j, k;\n\tdouble s;\n\tfor (i = 0; i < m; i++)\n\t\tfor (j = 0; j < m; j++) {\n\t\t\ts = 0.;\n\t\t\tfor (k = 0; k < m; k++)\n\t\t\t\ts += A[i * m + k] * B[k * m + j];\n\t\t\tC[i * m + j] = s;\n\t\t}\n}\n\n/**\n Supporting function for kolmogorov_cdf_marsaglia, not to be used directly.\n */\nvoid mPower(double *A, int eA, double *V, int *eV, int m, int n) {\n\tdouble *B;\n\tint eB, i;\n\tif (n == 1) {\n\t\tfor (i = 0; i < m * m; i++)\n\t\t\tV[i] = A[i];\n\t\t*eV = eA;\n\t\treturn;\n\t}\n\tmPower(A, eA, V, eV, m, n / 2);\n\tB = (double*) malloc((m * m) * sizeof(double));\n\tmMultiply(V, V, B, m);\n\teB = 2 * (*eV);\n\tif (n % 2 == 0) {\n\t\tfor (i = 0; i < m * m; i++)\n\t\t\tV[i] = B[i];\n\t\t*eV = eB;\n\t} else {\n\t\tmMultiply(A, B, V, m);\n\t\t*eV = eA + eB;\n\t}\n\tif (V[(m / 2) * m + (m / 2)] > 1e140) {\n\t\tfor (i = 0; i < m * m; i++)\n\t\t\tV[i] = V[i] * 1e-140;\n\t\t*eV += 140;\n\t}\n\tfree(B);\n}\n\ndouble kolmogorov_cdf_marsaglia(int n, double d) {\n\tint k, m, i, j, g, eH, eQ;\n\tdouble h, s, *H, *Q;\n\n\t//OMIT NEXT LINE IF YOU REQUIRE >7 DIGIT ACCURACY IN THE RIGHT TAIL\n\ts = d * d * n;\n\tif (s > 7.24 || (s > 3.76 && n > 99))\n\t\treturn 1 - 2 * exp(-(2.000071 + .331 / sqrt(n) + 1.409 / n) * s);\n\n\tk = (int) (n * d) + 1;\n\tm = 2 * k - 1;\n\th = k - n * d;\n\tH = (double*) malloc((m * m) * sizeof(double));\n\tQ = (double*) malloc((m * m) * sizeof(double));\n\tfor (i = 0; i < m; i++)\n\t\tfor (j = 0; j < m; j++)\n\t\t\tif (i - j + 1 < 0)\n\t\t\t\tH[i * m + j] = 0;\n\t\t\telse\n\t\t\t\tH[i * m + j] = 1;\n\tfor (i = 0; i < m; i++) {\n\t\tH[i * m] -= pow(h, i + 1);\n\t\tH[(m - 1) * m + i] -= pow(h, (m - i));\n\t}\n\tH[(m - 1) * m] += (2 * h - 1 > 0 ? pow(2 * h - 1, m) : 0);\n\tfor (i = 0; i < m; i++)\n\t\tfor (j = 0; j < m; j++)\n\t\t\tif (i - j + 1 > 0)\n\t\t\t\tfor (g = 1; g <= i - j + 1; g++)\n\t\t\t\t\tH[i * m + j] /= g;\n\teH = 0;\n\tmPower(H, eH, Q, &eQ, m, n);\n\ts = Q[(k - 1) * m + k - 1];\n\tfor (i = 1; i <= n; i++) {\n\t\ts = s * i / n;\n\t\tif (s < 1e-140) {\n\t\t\ts *= 1e140;\n\t\t\teQ -= 140;\n\t\t}\n\t}\n\ts *= pow(10., eQ);\n\tfree(H);\n\tfree(Q);\n\treturn s;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n// q = 1- alpha or, in terms of beta: q = 1 - (1 - sqrt(beta))\ndouble KolmogorovComputer::kolmogorovCdfInverse(int S, double q,\n\t\tdouble tolerance) {\n\tdouble x_lo = 0.0;\n\n\t// Set initial guesses using the DKW bounds\n\tdouble x_hi = sqrt(-1 / (2 * (double) S) * log((1 - q) / 2));\n\n\tKolmogorovCdfRoots kolmogorov_roots(S, q);\n\tKolmogorovTol kolmogorov_tol(tolerance);\n\n\tstd::pair<double, double> result = boost::math::tools::bisect<\n\t\t\tKolmogorovCdfRoots, double, KolmogorovTol>(kolmogorov_roots, x_lo,\n\t\t\tx_hi, kolmogorov_tol);\n\n\treturn (result.first + result.second) / 2.0;\n}\n\ndouble KolmogorovComputer::kolmogorovCdfInverse(int S) {\n\tdouble q = 1 - (1 - sqrt(1 - _beta));\n\n\treturn kolmogorovCdfInverse(S, q, _tolerance);\n}\n\n} /* namespace INSIGHTv3 */\n", "meta": {"hexsha": "c1b7515e3834fe44feb02d2b75e43cb9dbb062f0", "size": 10099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "container/INSIGHT/src/KolmogorovComputer.cpp", "max_stars_repo_name": "mcapuccini/cloud-insight", "max_stars_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T12:43:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-21T12:43:48.000Z", "max_issues_repo_path": "container/INSIGHT/src/KolmogorovComputer.cpp", "max_issues_repo_name": "mcapuccini/cloud-insight", "max_issues_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T14:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-10T14:14:13.000Z", "max_forks_repo_path": "container/INSIGHT/src/KolmogorovComputer.cpp", "max_forks_repo_name": "mcapuccini/cloud-insight", "max_forks_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-17T20:05:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T08:29:07.000Z", "avg_line_length": 27.5177111717, "max_line_length": 167, "alphanum_fraction": 0.6509555402, "num_tokens": 3403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5789227783316737}}
{"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\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_source.h>\n#include <adept.h>\nusing adept::adouble;\n\n#define SINCOSN 10000000\nstatic \ndouble sincos_real(double x) {\n  double sum = 0;\n  for(int i=1; i<=SINCOSN; i++) {\n    sum += pow(x, i) / i;\n  }\n  return sum;\n}\n\nstatic void sincos_real_tapenade(double x, double *xb, double sincos_realb) {\n    double sum = 0;\n    double sumb = 0.0;\n    double sincos_real;\n    sumb = sincos_realb;\n    for (int i = SINCOSN; i > 0; --i)\n        if (!(x<=0.0&&(i==0.0||i!=(int)i)))\n            *xb = *xb + pow(x, (i-1))*sumb;\n}\n\nstatic\nadouble sincos(adouble x) {\n  adouble sum = 0;\n  for(int i=1; i<=SINCOSN; i++) {\n    sum += pow(x, i) / i;\n  }\n  return sum;\n}\n\nstatic\ndouble sincos_and_gradient(double xin, double& xgrad) {\n    adept::Stack stack;\n    adouble x = xin;\n    stack.new_recording();\n    adouble y = sincos(x);\n    y.set_gradient(1.0);\n    stack.compute_adjoint();\n    xgrad = x.get_gradient();\n    return y.value();\n}\n\nstatic void adept_sincos(double inp) {\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = sincos_real(inp);\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  gettimeofday(&start, NULL);\n\n  adept::Stack stack;\n // stack.new_recording();\n  adouble resa = sincos(inp);\n  double res = resa.value();\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  gettimeofday(&start, NULL);\n\n  double res2 = 0;\n  sincos_and_gradient(inp, res2);\n\n  gettimeofday(&end, NULL);\n  printf(\"%0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\nstatic void tapenade_sincos(double inp) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = sincos_real(inp);\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  gettimeofday(&start, NULL);\n\n  double res = sincos_real(inp);\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  gettimeofday(&start, NULL);\n  double res2 = 0;\n\n  sincos_real_tapenade(inp, &res2, 1.0);\n\n  gettimeofday(&end, NULL);\n  printf(\"tapendade %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\nstatic void enzyme_sincos(double inp) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = sincos_real(inp);\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  gettimeofday(&start, NULL);\n\n  double res = sincos_real(inp);\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  gettimeofday(&start, NULL);\n  double res2;\n\n  res2 = __enzyme_autodiff<double>(sincos_real, inp);\n\n  gettimeofday(&end, NULL);\n  printf(\"%0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\nint main(int argc, char** argv) {\n\n  double inp = atof(argv[1]) ;\n  printf(\"adept\\n\");\n  adept_sincos(inp);\n  printf(\"tapenade\\n\");\n  tapenade_sincos(inp);\n  printf(\"enzyme\\n\");\n  enzyme_sincos(inp);\n}\n", "meta": {"hexsha": "f8589fe488b471e8cda997f8d9bef688a2f42b5c", "size": 3494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/taylorlog/taylorlog.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/taylorlog/taylorlog.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/taylorlog/taylorlog.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": 19.8522727273, "max_line_length": 77, "alphanum_fraction": 0.6305094448, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5788693884061944}}
{"text": "/**\n * @file Projector.hpp\n * @author Takashi Michikawa <michikawa@acm.org>\n */\n\n#ifndef MI_PROJECTOR_HPP\n#define MI_PROJECTOR_HPP 1\n#include <array>\n#include <memory>\n\n#include <Eigen/Dense>\n\nnamespace mi4\n{\n        class Projector\n        {\n        private:\n                using map_mat = Eigen::Map< Eigen::Matrix4d >;\n                Projector (const Projector& that) = delete;\n                Projector (Projector&& that) = delete;\n                void operator = (const Projector& that) = delete;\n                void operator = (Projector&& that) = delete;\n        public:\n                explicit Projector (double modelview[16], double projection[16], int vp[4]) : _matrix(map_mat(projection) * map_mat(modelview)), _inv_matrix((map_mat(projection) * map_mat(modelview)).inverse()), _viewport({vp[0], vp[1], vp[2], vp[3]}) {}\n                explicit Projector (const Eigen::Matrix4d& modelview, const Eigen::Matrix4d& projection, const std::array< int, 4 >& vp) : _matrix(projection * modelview), _inv_matrix((projection * modelview).inverse()), _viewport(vp) {}\n                ~Projector ( void ) = default;\n\n                Eigen::Vector2d project ( const Eigen::Vector3d& p, double* depth )\n                {\n                        const auto& vp = this->_viewport;\n                        const auto p0 = this->_matrix * p.homogeneous();\n\n                        if ( p0.w() == 0 ) {\n                                return Eigen::Vector2d(0, 0);\n                        }\n\n                        *depth = (1.0 + p0.z() / p0.w()) * 0.5;\n                        return Eigen::Vector2d(vp[0] + (1 + p0.x() / p0.w()) * vp[2] * 0.5, vp[1] + (1 + p0.y() / p0.w()) * vp[3] * 0.5);\n                }\n\n                Eigen::Vector3d unproject (const Eigen::Vector2d& wp, double depth) const\n                {\n                        const auto& inv_matrix = this->_inv_matrix;\n                        const auto& vp = this->_viewport;\n                        const Eigen::Vector4d p0((wp.x() - vp[0]) * 2 / vp[2] - 1.0, (wp.y() - vp[1]) * 2 / vp[3] - 1.0, 2.0 * depth - 1.0, 1.0);\n                        const Eigen::Vector4d p1 = inv_matrix * p0;\n                        return (p1.w() != 0.0) ? p1.hnormalized() : Eigen::Vector3d(0, 0, 0);\n                }\n        private:\n                const Eigen::Matrix4d _matrix;\n                const Eigen::Matrix4d _inv_matrix;\n                const std::array< int, 4 > _viewport;\n        };\n}\n\n#endif// MI_PROJECTOR_HPP\n", "meta": {"hexsha": "124f8c209f26f68729b978f687cecca220d911c4", "size": 2480, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mi4/Projector.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/Projector.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/Projector.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": 43.5087719298, "max_line_length": 254, "alphanum_fraction": 0.502016129, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.57886936407332}}
{"text": "// Filename: matrix_free_cg.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_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\t\n\tfor (int i= 0; i < m; i++)\n\t    for (int j= 0; j < n; j++) {\n\t\tint k= i * n + j; // offset\n\t\tw[k]= 4 * v[k];\n\t\tif (i > 0) w[k]-= v[k-n];   // upper neighbor\n\t\tif (i < m-1) w[k]-= v[k+n]; // lower neighbor\n\t\tif (j > 0) w[k]-= v[k-1];   // left neighbor\n\t\tif (j < n-1) w[k]-= v[k+1]; // right neighbor\n\t    }\n\treturn w;\n    }\n    int m, n;\n};\n\nnamespace mtl { namespace ashape {\n    template <> struct ashape_aux<poisson2D_dirichlet> \n    {\ttypedef nonscal type;    };\n}}\n\n\nint main(int, char**)\n{\n    // For a more realistic example set size to 1000 or larger\n    const int size = 1000, N = size * size;\n\n    typedef ::poisson2D_dirichlet             matrix_type;\n    matrix_type                               A(size, size);\n    itl::pc::identity<matrix_type>            P(A);\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, 10, 1.e-11, 0.0, 5);\n    cg(A, x, b, P, iter);\n\n    return 0;\n}\n", "meta": {"hexsha": "99efb078c2e762a7f9ab71cb4edcee7353cccf7e", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/matrix_free_cg_slow_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_cg_slow_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_cg_slow_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.6071428571, "max_line_length": 74, "alphanum_fraction": 0.5435413643, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5788456332454127}}
{"text": "// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"functiontablefactory.h\"\n#include <vespa/vespalib/locale/c.h>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <cmath>\n#include <vespa/log/log.h>\nLOG_SETUP(\".fef.functiontablefactory\");\n\nnamespace {\n\nvoid logArgumentWarning(const vespalib::string & name, size_t exp, size_t act)\n{\n    LOG(warning, \"Cannot create table for function '%s'. Wrong number of arguments: expected %zu to %zu, but got %zu\",\n        name.c_str(), exp, exp + 1, act);\n}\n\n}\n\nnamespace search::fef {\n\nbool\nFunctionTableFactory::checkArgs(const std::vector<vespalib::string> & args, size_t exp, size_t & tableSize) const\n{\n    if (exp <= args.size() && args.size() <= (exp + 1)) {\n        if (args.size() == (exp + 1)) {\n            tableSize = atoi(args.back().c_str());\n        } else {\n            tableSize = _defaultTableSize;\n        }\n        return true;\n    }\n    return false;\n}\n\nbool\nFunctionTableFactory::isSupported(const vespalib::string & type) const\n{\n    return (isExpDecay(type) || isLogGrowth(type) || isLinear(type));\n}\n\nTable::SP\nFunctionTableFactory::createExpDecay(double w, double t, size_t len) const\n{\n    Table::SP table(new Table());\n    for (size_t x = 0; x < len; ++x) {\n        table->add(w * std::exp(-(x / t)));\n    }\n    return table;\n}\n\nTable::SP\nFunctionTableFactory::createLogGrowth(double w, double t, double s, size_t len) const\n{\n    Table::SP table(new Table());\n    for (size_t x = 0; x < len; ++x) {\n        table->add(w * (std::log(1 + (x / s))) + t);\n    }\n    return table;\n}\n\nTable::SP\nFunctionTableFactory::createLinear(double w, double t, size_t len) const\n{\n    Table::SP table(new Table());\n    for (size_t x = 0; x < len; ++x) {\n        table->add(w * x + t);\n    }\n    return table;\n}\n\nFunctionTableFactory::FunctionTableFactory(size_t defaultTableSize) :\n    _defaultTableSize(defaultTableSize)\n{\n}\n\nTable::SP\nFunctionTableFactory::createTable(const vespalib::string & name) const\n{\n    ParsedName p;\n    if (parseFunctionName(name, p)) {\n        if (isSupported(p.type)) {\n            size_t tableSize = _defaultTableSize;\n            if (isExpDecay(p.type)) {\n                if (checkArgs(p.args, 2, tableSize)) {\n                    return createExpDecay(vespalib::locale::c::atof(p.args[0].c_str()), vespalib::locale::c::atof(p.args[1].c_str()), tableSize);\n                }\n                logArgumentWarning(name, 2, p.args.size());\n            } else if (isLogGrowth(p.type)) {\n                if (checkArgs(p.args, 3, tableSize)) {\n                    return createLogGrowth(vespalib::locale::c::atof(p.args[0].c_str()), vespalib::locale::c::atof(p.args[1].c_str()), vespalib::locale::c::atof(p.args[2].c_str()), tableSize);\n                }\n                logArgumentWarning(name, 3, p.args.size());\n            } else if (isLinear(p.type)) {\n                if (checkArgs(p.args, 2, tableSize)) {\n                    return createLinear(vespalib::locale::c::atof(p.args[0].c_str()), vespalib::locale::c::atof(p.args[1].c_str()), tableSize);\n                }\n                logArgumentWarning(name, 2, p.args.size());\n            }\n        } else {\n            LOG(warning, \"Cannot create table for function '%s'. Function type '%s' is not supported\",\n                name.c_str(), p.type.c_str());\n        }\n    } else {\n        LOG(warning, \"Cannot create table for function '%s'. Could not be parsed.\", name.c_str());\n    }\n    return Table::SP(NULL);\n}\n\nbool\nFunctionTableFactory::parseFunctionName(const vespalib::string & name, ParsedName & parsed)\n{\n    size_t ps = name.find('(');\n    size_t pe = name.find(')');\n    if (ps == vespalib::string::npos || pe == vespalib::string::npos) {\n        LOG(warning, \"Parse error: Did not find '(' and ')' in function name '%s'\", name.c_str());\n        return false;\n    }\n    if (ps >= pe) {\n        LOG(warning, \"Parse error: Found ')' before '(' in function name '%s'\", name.c_str());\n        return false;\n    }\n    parsed.type = name.substr(0, ps);\n    vespalib::string args = name.substr(ps + 1, pe - ps - 1);\n    if (!args.empty()) {\n        boost::split(parsed.args, args, boost::is_any_of(\",\"));\n    }\n    return true;\n}\n\n}\n", "meta": {"hexsha": "3c816870a6d5e485e91b4464b561e2e77e565874", "size": 4292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "searchlib/src/vespa/searchlib/fef/functiontablefactory.cpp", "max_stars_repo_name": "Anlon-Burke/vespa", "max_stars_repo_head_hexsha": "5ecd989b36cc61716bf68f032a3482bf01fab726", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4054.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T07:58:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:32:15.000Z", "max_issues_repo_path": "searchlib/src/vespa/searchlib/fef/functiontablefactory.cpp", "max_issues_repo_name": "Anlon-Burke/vespa", "max_issues_repo_head_hexsha": "5ecd989b36cc61716bf68f032a3482bf01fab726", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4854.0, "max_issues_repo_issues_event_min_datetime": "2017-08-10T20:19:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:04:23.000Z", "max_forks_repo_path": "searchlib/src/vespa/searchlib/fef/functiontablefactory.cpp", "max_forks_repo_name": "Anlon-Burke/vespa", "max_forks_repo_head_hexsha": "5ecd989b36cc61716bf68f032a3482bf01fab726", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 541.0, "max_forks_repo_forks_event_min_datetime": "2017-08-10T18:51:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:18:56.000Z", "avg_line_length": 32.2706766917, "max_line_length": 192, "alphanum_fraction": 0.5945945946, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.57884562526796}}
{"text": "/*Deep Euler implementation of a sonochemical bubble model*/\r\n\r\n//#define EIGEN_NO_DEBUG\r\n#include <iostream>\r\n#include <fstream>\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n#include <vector>\r\n#include <string>\r\n#include <chrono>\r\n\r\n#include <torch/script.h>\r\n#include <Eigen/Core>\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nconst double rho_L = 9.970639504998557e+02;\r\nconst double p_inf = 1.0e+5;\r\nconst double sigma = 0.071977583160056;\r\nconst double gamma = 1.33;\r\nconst double c_L = 1.497251785455527e+03; // water 25 Celsius\r\nconst double mu_L = 8.902125058209557e-04; //25 Celsius\r\nconst double lambda = 0.6084; //water 25 Celsius\r\nconst double T_inf = 298.15; // 25 Celsius\r\n\r\nconst double R_E = 10e-6; //1...10u\r\nconst double p_A = 0.5e5; //0.5..2 bar\r\nconst double f = 100e3; //20 kHz... 2 MHz\r\n\r\nusing namespace std;\r\n\r\nconst int N = 16;\r\nconst int N_z = N / 2 - 1;\r\n\r\nconst int nn_inputs = 2 + 3 + N_z;\r\nconst int nn_outputs = N_z;\r\nconst int system_order = 4+N_z;\r\nc10::TensorOptions global_tensor_op;\r\n\r\n//Modify these to load the correct model\r\nstring file_name = \"../simulations/bub_hybrid_test.txt\";\r\nstring model_file = \"../../../training/traced_model_bub0.5_hybrid_e51_2112021549.pt\";\r\nstring scaler_file = \"../../../training/scaler_bub0.5_hybrid_2112021549.psca\";\r\n\r\ntypedef double value_type;\r\ntypedef vector<value_type> state_type;\r\ntypedef Eigen::Matrix<value_type, N / 2, N / 2> matrix_type;\r\n\r\nstruct std_scaler {\r\n\ttorch::Tensor mean;\r\n\ttorch::Tensor scale;\r\n\r\n\ttorch::Tensor operator()(torch::Tensor tensor) {\r\n\t\treturn (tensor - mean) / scale;\r\n\t}\r\n\ttorch::Tensor inverse_transform(torch::Tensor tensor) {\r\n\t\treturn tensor * scale + mean;\r\n\t}\r\n\tvoid parse(istream& is, int numel) {\r\n\t\tmean = torch::ones({ 1, numel });\r\n\t\tis.get();\r\n\t\tdouble temp = 0.0;\r\n\t\tfor (int i = 0; i < numel; i++) {\r\n\t\t\tis >> temp;\r\n\t\t\tmean[0][i] = temp;\r\n\t\t}\r\n\t\tis.get();\r\n\t\tis.get();\r\n\t\tscale = torch::ones({ 1, numel });\r\n\t\tis.get();\r\n\t\tfor (int i = 0; i < numel; i++) {\r\n\t\t\tis >> temp;\r\n\t\t\tscale[0][i] = temp;\r\n\t\t}\r\n\t\tis.get();\r\n\t\tis.get();\r\n\t}\r\n};\r\n\r\nstruct norm_scaler {\r\n\ttorch::Tensor data_min;\r\n\ttorch::Tensor data_max;\r\n\tdouble min = 0;\r\n\tdouble max = 0;\r\n\r\n\ttorch::Tensor operator()(torch::Tensor tensor) {\r\n\t\ttorch::Tensor X_std = (tensor - data_min) / (data_max - data_min);\r\n\t\treturn X_std * (max - min) + min;\r\n\t}\r\n\ttorch::Tensor inverse_transform(torch::Tensor tensor) {\r\n\t\ttorch::Tensor Y_std = (tensor - min) / (max - min);\r\n\t\treturn Y_std * (data_max - data_min) + data_min;\r\n\t}\r\n\tvoid parse(istream& is) {\r\n\t\tdata_min = torch::ones({ 1,nn_outputs });\r\n\t\tis.get();\r\n\t\tdouble temp = 0.0;\r\n\t\tfor (int i = 0; i < nn_outputs; i++) {\r\n\t\t\tis >> temp;\r\n\t\t\tdata_min[0][i] = temp;\r\n\t\t}\r\n\t\tis.get();\r\n\t\tis.get();\r\n\t\tdata_max = torch::ones({ 1, nn_outputs });\r\n\t\tis.get();\r\n\t\tfor (int i = 0; i < nn_outputs; i++) {\r\n\t\t\tis >> temp;\r\n\t\t\tdata_max[0][i] = temp;\r\n\t\t}\r\n\t\tis.get(); //']'\r\n\t\tis.get(); //'\\n'\r\n\t\tis >> min;\r\n\t\tis >> max;\r\n\t}\r\n};\r\n\r\n//ode function of Van der Pol equation\r\nclass BubDyn {\r\n\tdouble mu = 1.5;\r\n\tstd::vector<torch::jit::IValue> inps; //reused neural network input vector\r\n\ttorch::Tensor inputs; //reused tensor of inputs\r\npublic:\r\n\ttorch::jit::script::Module model; //the neural network\r\n\tstd_scaler in_transf;\r\n\tstd_scaler out_transf;\r\n\r\n\tstd::array<double, 5> stage_times;\r\n\tstd::vector<value_type> C; //constants of the right hand side\r\n\tEigen::Matrix<value_type, N / 2, 1> y; //collocation points (half)\r\n\tEigen::Matrix<value_type, N / 2, 1> y_sq; //same, every entry squared\r\n\tmatrix_type D_E; //Derivative matrix for even functions\r\n\tmatrix_type D_O; //Derivative matrix for odd functions\r\n\r\n\tBubDyn() {\r\n\t\tinps = std::vector<torch::jit::IValue>(1);\r\n\t\tinputs = torch::ones({ 5, nn_inputs }, global_tensor_op);\r\n\r\n\t\t//----------------------------------------------------------\r\n\t\t//bubblemodel initializations\r\n\t\t//----------------------------------------------------------\r\n\t\tconst double omega = 2 * M_PI * f;\r\n\t\tvalue_type pi2wRE = 2 * M_PI / (omega * R_E);\r\n\r\n\t\t//constants\r\n\t\tC = std::vector<value_type>(13);\r\n\t\tC[0] = omega * R_E / (2 * M_PI * c_L);\r\n\t\tC[1] = 4 * mu_L / (c_L * rho_L * R_E);\r\n\t\tC[2] = 4 * mu_L / (rho_L * R_E) * pi2wRE;\r\n\t\tC[3] = 2 * sigma * pi2wRE * pi2wRE / (rho_L * R_E);\r\n\t\tC[4] = p_inf / rho_L * pi2wRE * pi2wRE;\r\n\t\tC[5] = p_A / rho_L * pi2wRE * pi2wRE;\r\n\t\tC[6] = pi2wRE * p_inf / (c_L * rho_L);\r\n\t\tC[7] = pi2wRE * p_A / (c_L * rho_L);\r\n\t\tC[8] = 2 * M_PI * pi2wRE * p_A / (c_L * rho_L);\r\n\t\tC[9] = lambda * (gamma - 1) / gamma * pi2wRE / R_E * T_inf / p_inf;\r\n\t\tC[10] = lambda * (gamma - 1) * pi2wRE / R_E * T_inf / p_inf;\r\n\t\tC[11] = (gamma - 1) / gamma;\r\n\t\tC[12] = 1.0 / (3 * gamma);\r\n\r\n\t\t//Derivative matrices\r\n\t\tEigen::Matrix<value_type, N, 1> y_full(N);\r\n\t\tvalue_type rec_cpn = 1.0 / (N - 1);\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\ty_full[i] = cos(M_PI * i * rec_cpn);\r\n\t\t\t//std::cout << y_full[i] << std::endl;\r\n\t\t}\r\n\t\tEigen::Matrix<value_type, N, N> D(N, N);\r\n\t\tfor (int i = 0; i < N; i++) {\r\n\t\t\tfor (int j = 0; j < N; j++) {\r\n\t\t\t\tif (i == j) {\r\n\t\t\t\t\tif (i == N - 1) {\r\n\t\t\t\t\t\tD(N - 1, N - 1) = -(1 + 2 * (N - 1) * (N - 1)) / 6.0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (i == 0) {\r\n\t\t\t\t\t\tD(0, 0) = (1 + 2 * (N - 1) * (N - 1)) / 6.0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tD(i, i) = -y_full[i] / (2.0 * (1.0 - y_full[i] * y_full[i]));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tD(i, j) = std::pow(-1, i + j) * (i == 0 || i == N - 1 ? 2.0 : 1.0)\r\n\t\t\t\t\t\t/ ((j == 0 || j == N - 1 ? 2.0 : 1.0) * (y_full[i] - y_full[j]));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tD_E = matrix_type(N / 2, N / 2);\r\n\t\tD_O = matrix_type(N / 2, N / 2);\r\n\t\tfor (int i = 0; i < N / 2; i++) {\r\n\t\t\tfor (int j = 0; j < N / 2; j++) {\r\n\t\t\t\tD_E(i, j) = D(i, j) + D(i, N - 1 - j);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (int i = 0; i < N / 2; i++) {\r\n\t\t\tfor (int j = 0; j < N / 2; j++) {\r\n\t\t\t\tD_O(i, j) = D(i, j) - D(i, N - 1 - j);\r\n\t\t\t}\r\n\t\t}\r\n\t\ty = y_full.head<N / 2>();\r\n\t\ty_sq = y.cwiseProduct(y);\r\n\r\n\t\t//---------------------------------------------------------\r\n\t\t//neural network initializations\r\n\t\t//---------------------------------------------------------\r\n\t\ttorch::Tensor inputs = torch::ones({ 1, nn_inputs }, global_tensor_op);\r\n\r\n\t\ttry {\r\n\t\t\tmodel = torch::jit::load(model_file);\r\n\t\t\tstd::vector<torch::jit::IValue> inp;\r\n\t\t\tinp.push_back(torch::ones({ 1, nn_inputs }, global_tensor_op));\r\n\t\t\tstd::cout << inp << endl;\r\n\t\t\t// Execute the model and turn its output into a tensor.\r\n\t\t\tat::Tensor output = model.forward(inp).toTensor().detach();\r\n\t\t\tstd::cout << output << endl;\r\n\t\t}\r\n\t\tcatch (const c10::Error& e) {\r\n\t\t\tstd::cerr << \"Error loading the model: \" << e.what() << endl;\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t\tifstream in(scaler_file);\r\n\t\tif (!in) {\r\n\t\t\tstd::cerr << \"Error loading the scalers.\" << endl;\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t\tout_transf.parse(in, nn_outputs);\r\n\t\tin_transf.parse(in, nn_inputs);\r\n\t\tin.close();\r\n\t}\r\n\r\n\t//Rewrites the errors array with the predicted local truncation errors\r\n\ttorch::Tensor local_error(double t, double dt, const double * x, const double* z) {\r\n\t\tdouble sinpi = sin(2 * M_PI * t);\r\n\r\n\t\tfor (int jj = 0; jj < 5; jj++) {\r\n\t\t\tinputs[jj][1] = x[0];\r\n\t\t\tinputs[jj][2] = x[1];\r\n\t\t\tinputs[jj][3] = x[2];\r\n\t\t\tinputs[jj][nn_inputs - 1] = sinpi;\r\n\t\t\t//timestep\r\n\t\t\tinputs[jj][0] = stage_times[jj] * dt;\r\n\t\t\t//temperature\r\n\t\t\tfor (int i = 0; i < N_z; i++) {\r\n\t\t\t\tinputs[jj][i + 4] = z[i+1];\r\n\t\t\t}\r\n\t\t\t//scaling\r\n\t\t\tinputs.index_put_({jj, torch::indexing::Slice()}, in_transf(inputs.index({ jj, torch::indexing::Slice() })));\r\n\t\t}\r\n\t\tinps[0] = inputs;\r\n\t\t//evaluating\r\n\t\ttorch::Tensor loc_trun_err = model.forward(inps).toTensor().detach();\r\n\t\tfor (int i = 0; i < 5; i++) {\r\n\t\t\tloc_trun_err.index_put_({ i, torch::indexing::Slice() }, out_transf.inverse_transform(loc_trun_err.index({ i, torch::indexing::Slice() })));\r\n\t\t}\r\n\t\treturn loc_trun_err;\r\n\t}\r\n\t//ODE function of discretized temperature (z)\r\n\tvoid temperature(double t, const double * x, const double* z, double* dzdt) {\r\n\t\tEigen::Map<const Eigen::Matrix<value_type, N / 2, 1>> z_vector(z);\r\n\t\tEigen::Map<Eigen::Matrix<value_type, N / 2, 1>> dzdt_vector(dzdt);\r\n\r\n\t\tEigen::Matrix<value_type, N / 2, 1> De_x = D_E * z_vector; //derivative of z (dimless temperature)\r\n\t\t\r\n\t\tvalue_type rec_xR = 1.0 / x[0];\r\n\t\tvalue_type rec_xp = 1.0 / x[2];\r\n\t\tvalue_type dxdt2 = 3 * rec_xR * (C[10] * rec_xR * De_x[0] - gamma * x[1] * x[2]);\r\n\r\n\t\t//discretized PDE of bubble temperature\r\n\t\tdzdt_vector = De_x.cwiseProduct(x[1] * rec_xR * y - C[9] * rec_xR * rec_xR * rec_xp * De_x //this might show error, but it will not fail at compile time, valid syntax\r\n\t\t\t+ C[12] * rec_xp * dxdt2 * y)\r\n\t\t\t+ C[11] * rec_xp * dxdt2 * z_vector + C[9] * rec_xp * rec_xR * rec_xR * z_vector\r\n\t\t\t.cwiseProduct(y_sq.cwiseInverse()).cwiseProduct(D_O * (y_sq.cwiseProduct(De_x)));\r\n\t\tdzdt_vector[0] = 0.0; //Boundary condition\r\n\r\n\t\treturn;\r\n\t}\r\n\r\n\t//ODE function of bubbledynamics (x). In the pointer x the values are rewritten with the computed slopes\r\n\tvoid operator()(double t, const double* x, const double * z, double* dxdt) {\r\n\t\tEigen::Map<const Eigen::Matrix<value_type, N / 2, 1>> z_vector(z);\r\n\t\tvalue_type rec_xR = 1.0 / x[0];\r\n\t\tvalue_type rec_xp = 1.0 / x[2];\r\n\r\n\t\t//bubble pressure evolution\r\n\t\tdxdt[2] = 3 * rec_xR * (C[10] * rec_xR * (D_E * z_vector)[0] - gamma * x[1] * x[2]);\r\n\r\n\t\t//Keller-Miksis equation\r\n\t\tdxdt[0] = x[1];\r\n\t\tvalue_type sin2pit = sin(2 * M_PI * t);\r\n\t\tvalue_type den = x[0] - C[0] * x[0] * x[1] + C[1];\r\n\t\tvalue_type num = 0.5 * C[0] * x[1] * x[1] * x[1] - 1.5 * x[1] * x[1] - C[2] * x[1] * rec_xR - C[3] * rec_xR\r\n\t\t\t+ C[4] * x[2] - C[4] - C[5] * sin2pit + C[6] * x[1] * x[2] - C[6] * x[1] - C[7] * x[1] * sin2pit\r\n\t\t\t- C[8] * x[0] * cos(2 * M_PI * t) + C[6] * x[0] * dxdt[2];\r\n\t\tdxdt[1] = num / den;\r\n\t}\r\n};\r\n\r\nclass BubbleSolver\r\n{\r\npublic:\r\n\r\n\tBubbleSolver(int temperature_size) :z_size(temperature_size) {};\r\n\r\n\tbool setInitialConditions(const double* conds_x, const double * conds_z, const double at) {\r\n\t\tbegin_t = at;\r\n\t\tx_init = (double*)malloc(sizeof(double) * x_size);\r\n\t\tfor (int u = 0; u < x_size; u++) {\r\n\t\t\tx_init[u] = conds_x[u];\r\n\t\t}\r\n\t\tz_init = (double*)malloc(sizeof(double) * z_size);\r\n\t\tfor (int u = 0; u < z_size; u++) {\r\n\t\t\tz_init[u] = conds_z[u];\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\tvoid setMaxTime(double max_t) {\r\n\t\tt_max = max_t;\r\n\t}\r\n\tvoid setTolerances(double rel, double abs) {\r\n\t\tabs_tol = abs;\r\n\t\trel_tol = rel;\r\n\t}\r\n\r\n\tvoid solve(BubDyn& sys, ostream& os) {\r\n\r\n\t\tdouble* x = (double*)malloc(sizeof(double) * x_size);\r\n\t\tfor (int u = 0; u < x_size; u++) {\r\n\t\t\tx[u] = x_init[u];\r\n\t\t}\r\n\t\tdouble* z = (double*)malloc(sizeof(double) * z_size);\r\n\t\tfor (int u = 0; u < z_size; u++) {\r\n\t\t\tz[u] = z_init[u];\r\n\t\t}\r\n\r\n\t\t//preparations\r\n\t\tdouble* z_stage = (double*)malloc(sizeof(double) * z_size);\r\n\t\tdouble* z_next = (double*)malloc(sizeof(double) * z_size);\r\n\t\tdouble* dzdt = (double*)malloc(sizeof(double) * z_size);\r\n\t\tdouble* x_stage = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* x_tmp = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* k1 = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* k2 = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* k3 = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* k4 = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble* k5 = (double*)malloc(sizeof(double) * x_size);\r\n\t\tdouble t = begin_t;\r\n\t\tint l = 0;\r\n\t\ttorch::Tensor errors;\r\n\t\tbool accept = true;\r\n\t\tbool nan_detect = false;\r\n\t\tvalue_type rel_err = 0.0;\r\n\t\tvalue_type coeff = 1.0;\r\n\t\tsys.stage_times = { 0.2, 0.3, 0.6, 1.0, 7.0 / 8.0 };\r\n\t\tz_stage[0] = 1.0; //fixed, boundary condition\r\n\t\tz_next[0] = 1.0; //same\r\n\r\n\t\tos << t;\r\n\t\tfor (int i = 0; i < x_size; i++) {\r\n\t\t\tos << \" \" << x[i];\r\n\t\t}\r\n\t\tfor (int i = 0; i < z_size; i++) {\r\n\t\t\tos << \" \" << z[i];\r\n\t\t}\r\n\t\tos << endl;\r\n\r\n\t\tif (t_max - t < delta_t) delta_t = t_max - t;\r\n\r\n\t\twhile (t < t_max) {\r\n\r\n\t\t\t//DEM for temperature----------------------------------------------\r\n\t\t\terrors = sys.local_error(t, delta_t, x, z); //neural network\r\n\t\t\tsys.temperature(t, x, z, dzdt);\r\n\t\t\t//DOPRI for bubbleradius-------------------------------------------\r\n\t\t\tsys(t, x, z, k1);\r\n\r\n\t\t\t//k2\r\n\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\tz_stage[j] = z[j] + 0.2 * delta_t * dzdt[j] +0.04 * delta_t * delta_t * errors[0][j - 1].item<double>();\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + 0.2 * delta_t * k1[j];\r\n\t\t\t}\r\n\t\t\tsys(t + 0.2 * delta_t, x_stage, z_stage,  k2);\r\n\r\n\t\t\t//k3\r\n\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\tz_stage[j] = z[j] + 0.3 * delta_t * dzdt[j] + 0.09 * delta_t * delta_t * errors[1][j-1].item<double>();\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + 3.0 / 40.0 * delta_t * k1[j] + 9.0 / 40.0 * delta_t * k2[j];\r\n\t\t\t}\r\n\t\t\tsys(t + 0.3 * delta_t, x_stage, z_stage, k3); //k3\r\n\r\n\t\t\t//k4\r\n\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\tz_stage[j] = z[j] + 0.6 * delta_t * dzdt[j] + 0.36 * delta_t * delta_t * errors[2][j-1].item<double>();\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + delta_t * (0.3 * k1[j] - 0.9 * k2[j] + 6.0 / 5.0 * k3[j]);\r\n\t\t\t}\r\n\t\t\tsys(t + 0.6 * delta_t, x_stage, z_stage, k4);\r\n\r\n\t\t\t//k5\r\n\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\tz_next[j] = z[j] + delta_t * dzdt[j] + delta_t * delta_t * errors[3][j-1].item<double>();\r\n\t\t\t\t//this is the DEM solution\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + delta_t * (-11.0 / 54.0 * k1[j] + 5.0 / 2.0 * k2[j] - 70.0 / 27.0 * k3[j] + 35.0 / 27.0 * k4[j]);\r\n\t\t\t}\r\n\t\t\tsys(t + delta_t, x_stage, z_next, k5);\r\n\r\n\t\t\t//k6\r\n\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\tz_stage[j] = z[j] + 7.0/8.0 * delta_t * dzdt[j] + 49.0/64.0 * delta_t * delta_t * errors[4][j-1].item<double>();\r\n\t\t\t}\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + delta_t * (1631.0 / 55296.0 * k1[j] + 175.0 / 512.0 * k2[j] + 575.0 / 13824.0 * k3[j] + 44275.0 / 110592.0 * k4[j] + 253.0 / 4096.0 * k5[j]);\r\n\t\t\t}\r\n\t\t\tsys(t + 7.0 / 8.0 * delta_t, x_stage, z_stage, k2); //k6\r\n\r\n\t\t\t//solution--------------------------------------------\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\t//Main solution:\r\n\t\t\t\tx_tmp[j] = x[j] + delta_t * (37.0 / 378.0 * k1[j] + 250.0 / 621.0 * k3[j] + 125.0 / 594.0 * k4[j] + 512.0 / 1771.0 * k2[j]); //k2=k6\r\n\t\t\t\t//main solution end\r\n\t\t\t}\r\n\t\t\t//secondary solution\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tx_stage[j] = x[j] + delta_t * (2825.0 / 27648.0 * k1[j] + 18575.0 / 48384.0 * k3[j] + 13525.0 / 55296.0 * k4[j] + 277.0 / 14336.0 * k5[j] + 0.25 * k2[j]); //k2=k6\r\n\t\t\t}\r\n\r\n\t\t\t//error control---------------------------------------\r\n\t\t\taccept = true;\r\n\t\t\tnan_detect = false;\r\n\t\t\trel_err = 0;\r\n\t\t\tfor (int j = 0; j < x_size; j++) {\r\n\t\t\t\tif (!std::isfinite(x_tmp[j]) || !isfinite(x_stage[j])) {\r\n\t\t\t\t\taccept = false;\r\n\t\t\t\t\tstd::cout << \"NaN detected!\" << std::endl;\r\n\t\t\t\t\tnan_detect = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tk2[j] = distance(x_tmp[j], x_stage[j]); // local error\r\n\t\t\t\tk4[j] = abs_tol + std::fmax(std::fabs(x_tmp[j]), std::fabs(x[j])) * rel_tol; //tolerance\r\n\t\t\t\tif (k2[j] > k4[j]) {\r\n\t\t\t\t\taccept = false;\r\n\t\t\t\t}\r\n\t\t\t\trel_err = std::fmax(rel_err, k2[j] / k4[j]);\r\n\t\t\t}\r\n\t\t\t/*if (std::isfinite(rel_err))\r\n\t\t\t\tfor (int j = 1; j < z_size; j++) {\r\n\t\t\t\t\tif ( !std::isfinite(z_next[j]) ) {\r\n\t\t\t\t\t\taccept = false;\r\n\t\t\t\t\t\tstd::cout << \"NaN detected!\" << std::endl;\r\n\t\t\t\t\t\tnan_detect = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}*/\r\n\r\n\t\t\tif (!accept) {\r\n\t\t\t\t//1/(q+1) = 1/5 = 0.2;\r\n\t\t\t\tcoeff = safety_factor * std::pow(1.0 / rel_err, 0.2);\r\n\t\t\t\tif (!std::isfinite(coeff) || nan_detect) coeff = 0.1;\r\n\t\t\t\tdelta_t = coeff * delta_t;\r\n\t\t\t\t//std::cout << \"Not good\\n\";\r\n\t\t\t\tcontinue;\r\n\t\t\t\t//redo this step\r\n\t\t\t}\r\n\r\n\t\t\t//save------------------------------------------------\r\n\t\t\tt += delta_t;\r\n\t\t\tl++;\r\n\t\t\tcoeff = safety_factor * std::pow(1.0 / rel_err, 0.2);\r\n\t\t\tif (!std::isfinite(coeff)) coeff = 0.1;\r\n\t\t\telse if (coeff < 0.1) coeff = 0.1;\r\n\t\t\telse if (coeff > 5.0) coeff = 5.0;\r\n\r\n\t\t\tif (t + coeff * delta_t > t_max)delta_t = t_max - t;\r\n\t\t\telse delta_t = coeff * delta_t;\r\n\r\n\t\t\tos << t;\r\n\t\t\tfor (int i = 0; i < x_size; i++) {\r\n\t\t\t\tx[i] = x_tmp[i];\r\n\t\t\t\tos << \" \" << x[i];\r\n\t\t\t}\r\n\t\t\tfor (int i = 0; i < z_size; i++) {\r\n\t\t\t\tz[i] = z_next[i];\r\n\t\t\t\tos << \" \" << z[i];\r\n\t\t\t}\r\n\t\t\tos << endl;\r\n\t\t}\r\n\t\tfree(x); free(z);\r\n\t\tfree(x_stage); free(x_tmp);\r\n\t\tfree(dzdt); \r\n\t\tfree(z_stage); free(z_next);\r\n\t\tfree(k1); free(k2); free(k3); free(k4); free(k5);\r\n\t}\r\n\r\n\t~BubbleSolver() {\r\n\t\tfree(x_init);\r\n\t\tfree(z_init);\r\n\t}\r\nprivate:\r\n\tconst int x_size = 3;\r\n\tint z_size = 8;\r\n\tdouble* x_init = 0;\r\n\tdouble* z_init = 0;\r\n\tdouble begin_t = 0;\r\n\tdouble delta_t = 1e-4;\r\n\tdouble abs_tol = 1e-6;\r\n\tdouble rel_tol = 1e-6;\r\n\tconst double safety_factor = 0.8;\r\n\tint t_max = 10;\r\n\tdouble distance(double a, double b) {\r\n\t\tif (a < b)return b - a;\r\n\t\telse return a - b;\r\n\t}\r\n};\r\n\r\n\r\n\r\n\r\nint main() {\r\n\tglobal_tensor_op = torch::TensorOptions().dtype(torch::kFloat64);\r\n\tstd::cout << \"BubbleDynamics with DEM started\\n\" << setprecision(17) << endl;\r\n\r\n\tofstream ofs(file_name);\r\n\tif (!ofs.is_open()) {\r\n\t\tstd::cout << \"File could not be opened: \" << file_name << endl;\r\n\t\texit(-1);\r\n\t}\r\n\tofs.precision(17);\r\n\tofs.flags(ios::scientific);\r\n\tstd::cout << \"Writing file: \" << file_name << endl;\r\n\r\n\t//initial conditions\r\n\tdouble* x = new double[3] {1.0, 0.0, 1.0 + 2.0 * sigma / (R_E * p_inf)};\r\n\tdouble* z = new double[N/2] {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};\r\n\tdouble t_start = 0.0;\r\n\tstd::cout << \"Rarrrr\" << endl;\r\n\tBubDyn bubi;\r\n\r\n\tBubbleSolver solver(N/2);\r\n\tsolver.setInitialConditions(x, z, 0.0);\r\n\tsolver.setTolerances(1e-8, 1e-8);\r\n\tsolver.setMaxTime(5.0);\r\n\r\n\tcout << \"Solving...\" << endl;\r\n\tauto t1 = chrono::high_resolution_clock::now();\r\n\tsolver.solve(bubi, ofs);\r\n\tauto t2 = chrono::high_resolution_clock::now();\r\n\t//Not valid measurement of DEM computational time. Just a slight indicator\r\n\tcout << \"Time (ms):\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;\r\n\r\n\tofs.flush();\r\n\tofs.close();\r\n\r\n\tcout << \"Ready\" << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "38143dcc6b1e6d49375570ea0bdd53ab7f92c427", "size": 17841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DEM/run/hybrid/bub_hybrid.cpp", "max_stars_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_stars_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DEM/run/hybrid/bub_hybrid.cpp", "max_issues_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_issues_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DEM/run/hybrid/bub_hybrid.cpp", "max_forks_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_forks_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_forks_repo_licenses": ["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.915921288, "max_line_length": 169, "alphanum_fraction": 0.5438035985, "num_tokens": 6461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5788456197372157}}
{"text": "#ifndef STOCHASTICCOLLOCATIONS_HPP_\n#define STOCHASTICCOLLOCATIONS_HPP_\n\n#include <mpi.h>\n#include <boost/random.hpp>\n#include <iostream>\n#include <numeric>\n#include <cmath>\n#include <cstring>\n#include <fstream>\n\n\n class StochasticCollocations\n {\n private:\n    /* the Raynolds number will be of the form mean + stddev*sigma, where\n    sigma is ~N(0,1) or ~U(0,1) */\n    double u_gauss, s_gauss; // u_gauss = 0, s_gauss = 1;\n    int u_uniform , s_uniform; // u_uniform = 0; s_uniform = 1;\n\n    /* mersenne twister random number generator */\n    boost::mt19937 rng;\n    /* normal(Gaussian) distribution */\n    boost::normal_distribution<> normal_distr;\n    /* uniform distribution */\n    boost::uniform_int<> uniform_distr;\n\n    boost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<> >* var_normal;\n\n    boost::variate_generator<boost::mt19937&,\n    boost::uniform_int<> >* var_uniform;\n\npublic:\n    StochasticCollocations(double u_gauss, double s_gauss);\n    StochasticCollocations(int u_uniform, int s_uniform);\n\n    /** Uncertainty (i.e. Random variables) related methods **/\n\n    /* generate nsamples samples of normal distributed random variables */\n    std::vector<double> generate_nd_samples(double mean_nd, double sttdev_nd, int nsamples);\n    /* generate nsamples samples of uniformly distributed random variables */\n    std::vector<double> generate_ud_samples(double mean_ud, double sttdev_ud, int nsamples);\n\n    /* compute the first two statistical moments */\n    double compute_mean(const std::vector<double> &v) const;\n    double compute_variance(const std::vector<double> &v, double mean) const;\n\n    /* get a normal and uniform distributed RV */\n    double get_normal() const;\n    double get_uniform() const;\n\n    double hermite_poly(int degree, double &var);\n    void gauss_hermite_quad(int quad_degree, std::vector<double> &nodes, std::vector<double> &weights);\n    std::vector<double> get_coefficiants(int quad_degree, int no_coeff, double mean, double stddev, std::vector<double> &nodes, std::vector<double> &weights);\n\n    /***********************************************************/\n\n    /** Parallelization related methods **/\n\n    /* data decomposition among processes*/\n    void data_decomposition(int* ncoeff, int* nprocs, int* coeff_per_proc);\n\n    /* call the NS solver for each generated sample */\n    void get_NS_solution(int* coeff_per_proc, const std::vector<double> &nodes, int rv_flag, int imax, int jmax);\n\n    /* get the QoI (Quantities of interest - the desired output parameters, from a UQ point of view) */\n    void get_QoI(int* coeff_per_proc, std::vector<double> &coeff);\n\n    /***********************************************************/\n\n    /* destructor */\n    ~StochasticCollocations();\n};\n\n#endif /* MONTECARLO_HPP_ */\n", "meta": {"hexsha": "fd84165388b7fc0e7dad5a764c228a71ac17306d", "size": 2785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "project/monte_carlo/Stochastic_Collocations.hpp", "max_stars_repo_name": "grantathon/computational_fluid_dynamics", "max_stars_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-14T11:02:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-22T21:18:37.000Z", "max_issues_repo_path": "project/monte_carlo/Stochastic_Collocations.hpp", "max_issues_repo_name": "grantathon/computational_fluid_dynamics", "max_issues_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project/monte_carlo/Stochastic_Collocations.hpp", "max_forks_repo_name": "grantathon/computational_fluid_dynamics", "max_forks_repo_head_hexsha": "ecb9c180952d4791e4368087f4b26d29e7daefe9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1688311688, "max_line_length": 158, "alphanum_fraction": 0.6822262118, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5788333569403866}}
{"text": "/* Copyright Institute of Sound and Vibration Research - All rights reserved */\n\n#include \"parametric_iir_coefficient_calculator.hpp\"\n\n#include \"biquad_coefficient.hpp\"\n#include \"parametric_iir_coefficient.hpp\"\n\n#include <libefl/db_linear_conversion.hpp>\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\nnamespace visr\n{\nnamespace rbbl\n{\n\ntemplate< typename CoefficientType > \nBiquadCoefficient<CoefficientType> \nParametricIirCoefficientCalculator::\ncalculateIirCoefficients( ParametricIirCoefficient< CoefficientType> const & param,\n                                                    CoefficientType samplingFrequency )\n{\n  BiquadCoefficient<CoefficientType> res;\n  calculateIirCoefficients( param, res, samplingFrequency );\n  // Return value optimization avoids copy operation (normally)\n  return res;\n}\n\n// Explicit instantiations\n// Note: This code needs to be excluded from Doxygen documentation generation to avoid\n// warnings about non-matching class members.\n/// @cond NEVER\ntemplate VISR_RBBL_LIBRARY_SYMBOL\nBiquadCoefficient<float> ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<float>(ParametricIirCoefficient<float> const &, float);\ntemplate VISR_RBBL_LIBRARY_SYMBOL\nBiquadCoefficient<double> ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<double>(ParametricIirCoefficient<double> const &, double);\n/// @endcond NEVER\n\ntemplate< typename T >\nvoid ParametricIirCoefficientCalculator::\ncalculateIirCoefficients( ParametricIirCoefficient<T> const & param,\n                          BiquadCoefficient<T> & coeffs,\n                          T samplingFrequency )\n{\n  T const w0 = static_cast<T>(2.0) * boost::math::constants::pi<T>()*param.frequency() / samplingFrequency;\n  T const alpha = std::sin( w0 ) / (static_cast<T>(2.0) * param.quality() );\n  T const cw0 = std::cos( w0 );\n\n  switch( param.type() )\n  {\n    case ParametricIirCoefficientBase::Type::lowpass:\n    {\n      // b0 = (1 - cos( w0 )) / 2\n      // b1 = 1 - cos( w0 )\n      // b2 = (1 - cos( w0 )) / 2\n      // a0 = 1 + alpha\n      // a1 = -2 * cos( w0 )\n      // a2 = 1 - alpha\n      T const a0 = static_cast<T>(1.0) + alpha;\n      coeffs.b0() = (static_cast<T>(1.0) - cw0) / (static_cast<T>(2.0)*a0);\n      coeffs.b1() = (static_cast<T>(1.0) - cw0) / a0;\n      coeffs.b2() = coeffs.b0();\n      coeffs.a1() = (static_cast<T>(-2.0)*cw0) / a0;\n      coeffs.a2() = (static_cast<T>(1.0) - alpha) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::highpass:\n    {\n      //b0 = (1 + cos( w0 )) / 2\n      //b1 = -(1 + cos( w0 ))\n      //b2 = (1 + cos( w0 )) / 2\n      //a0 = 1 + alpha\n      //a1 = -2 * cos( w0 )\n      //a2 = 1 - alpha\n      T const a0 = static_cast<T>(1.0) + alpha;\n      coeffs.b0() = (static_cast<T>(1.0) + cw0) / (static_cast<T>(2.0)*a0);\n      coeffs.b1() = -(static_cast<T>(1.0) + cw0) / a0;\n      coeffs.b2() = coeffs.b0();\n      coeffs.a1() = (static_cast<T>(-2.0)*cw0) / a0;\n      coeffs.a2() = (static_cast<T>(1.0) - alpha) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::bandpass:\n    {\n      // \"Constant 0 dB gain\" variant.\n      // b0 = alpha\n      //  b1 = 0\n      //  b2 = -alpha\n      //  a0 = 1 + alpha\n      //  a1 = -2 * cos( w0 )\n      //  a2 = 1 - alpha\n      T const a0 = static_cast<T>(1.0) + alpha;\n      coeffs.b0() = alpha / a0;\n      coeffs.b1() = static_cast<T>(0.0);\n      coeffs.b2() = -coeffs.b0();\n      coeffs.a1() = (static_cast<T>(-2.0)*cw0) / a0;\n      coeffs.a2() = (static_cast<T>(1.0) - alpha) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::bandstop:\n    {\n      // b0 = 1\n      //  b1 = -2 * cos( w0 )\n      //  b2 = 1\n      //  a0 = 1 + alpha\n      //  a1 = -2 * cos( w0 )\n      //  a2 = 1 - alpha\n      T const a0 = static_cast<T>(1.0) + alpha;\n      coeffs.b0() = static_cast<T>(1.0) / a0;\n      coeffs.b1() = (static_cast<T>(-2.0) * cw0) / a0;\n      coeffs.b2() = coeffs.b0();\n      coeffs.a1() = (static_cast<T>(-2.0)*cw0) / a0;\n      coeffs.a2() = (static_cast<T>(1.0) - alpha) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::allpass:\n    {\n      // b0 = 1 - alpha\n      // b1 = -2 * cos( w0 )\n      // b2 = 1 + alpha\n      // a0 = 1 + alpha\n      // a1 = -2 * cos( w0 )\n      // a2 = 1 - alpha\n      T const a0 = static_cast<T>(1.0) + alpha;\n      coeffs.b0() = (static_cast<T>(1.0) -alpha) / a0;\n      coeffs.b1() = (static_cast<T>(-2.0) * cw0) / a0;\n      coeffs.b2() = static_cast<T>(1.0); // the unnormalised b0 is the same as a0\n      coeffs.a1() = coeffs.b1();\n      coeffs.a2() = coeffs.b0();\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::peak:\n    {\n      // b0 = 1 + alpha*A\n      // b1 = -2 * cos( w0 )\n      // b2 = 1 - alpha*A\n      // a0 = 1 + alpha / A\n      // a1 = -2 * cos( w0 )\n      // a2 = 1 - alpha / A\n      T const A = std::sqrt( efl::dB2linear( param.gain() ) );\n      T const a0 = static_cast<T>(1.0) + alpha/A;\n      coeffs.b0() = (static_cast<T>(1.0) + A *alpha) / a0;\n      coeffs.b1() = (static_cast<T>(-2.0)*cw0)/a0;\n      coeffs.b2() = (static_cast<T>(1.0) - A *alpha) / a0;\n      coeffs.a1() = coeffs.b1();\n      coeffs.a2() = (static_cast<T>(1.0) - alpha/A) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::lowshelf:\n    {\n      // b0 = A*((A + 1) - (A - 1)*cos( w0 ) + 2 * sqrt( A )*alpha)\n      //  b1 = 2 * A*((A - 1) - (A + 1)*cos( w0 ))\n      //  b2 = A*((A + 1) - (A - 1)*cos( w0 ) - 2 * sqrt( A )*alpha)\n      //  a0 = (A + 1) + (A - 1)*cos( w0 ) + 2 * sqrt( A )*alpha\n      //  a1 = -2 * ((A - 1) + (A + 1)*cos( w0 ))\n      //  a2 = (A + 1) + (A - 1)*cos( w0 ) - 2 * sqrt( A )*alpha\n      T const A = std::sqrt( efl::dB2linear( param.gain() ) );\n      T const Asqrt = sqrt( A );\n      T const a0 = (A + static_cast<T>(1.0)) + (A - static_cast<T>(1.0))*cw0 + static_cast<T>(2.0) * Asqrt*alpha;\n      coeffs.b0() = A*((A + static_cast<T>(1.0)) - (A - static_cast<T>(1.0))*cw0 + static_cast<T>(2.0) * Asqrt*alpha)/a0 ;\n      coeffs.b1() = (static_cast<T>(2.0) * A * ((A - static_cast<T>(1.0)) - (A + static_cast<T>(1.0)) * cw0)) / a0;\n      coeffs.b2() = A*((A + static_cast<T>(1.0)) - (A - static_cast<T>(1.0))*cw0 - static_cast<T>(2.0) * Asqrt*alpha) / a0;\n      coeffs.a1() = (static_cast<T>(-2.0) * ((A - static_cast<T>(1.0)) + (A + static_cast<T>(1.0)) * cw0)) / a0;\n      coeffs.a2() = ((A + static_cast<T>(1.0)) + (A - static_cast<T>(1.0))*cw0 - static_cast<T>(2.0) * Asqrt*alpha) / a0;\n      break;\n    }\n    case ParametricIirCoefficientBase::Type::highshelf:\n    {\n      //  b0 = A*((A + 1) + (A - 1)*cos( w0 ) + 2 * sqrt( A )*alpha)\n      //  b1 = -2 * A*((A - 1) + (A + 1)*cos( w0 ))\n      //  b2 = A*((A + 1) + (A - 1)*cos( w0 ) - 2 * sqrt( A )*alpha)\n      //  a0 = (A + 1) - (A - 1)*cos( w0 ) + 2 * sqrt( A )*alpha\n      //  a1 = 2 * ((A - 1) - (A + 1)*cos( w0 ))\n      //  a2 = (A + 1) - (A - 1)*cos( w0 ) - 2 * sqrt( A )*alpha\n      T const A = std::sqrt( efl::dB2linear( param.gain() ) );\n      T const Asqrt = sqrt( A );\n      T const a0 = (A + static_cast<T>(1.0)) - (A - static_cast<T>(1.0))*cw0 + static_cast<T>(2.0) * Asqrt*alpha;\n      coeffs.b0() = A*((A + static_cast<T>(1.0)) + (A - static_cast<T>(1.0))*cw0 + static_cast<T>(2.0) * Asqrt*alpha) / a0;\n      coeffs.b1() = (static_cast<T>(-2.0) * A * ((A - static_cast<T>(1.0)) + (A + static_cast<T>(1.0)) * cw0)) / a0;\n      coeffs.b2() = A*((A + static_cast<T>(1.0)) + (A - static_cast<T>(1.0))*cw0 - static_cast<T>(2.0) * Asqrt*alpha) / a0;\n      coeffs.a1() = (static_cast<T>(2.0) * ((A - static_cast<T>(1.0)) - (A + static_cast<T>(1.0)) * cw0)) / a0;\n      coeffs.a2() = ((A + static_cast<T>(1.0)) - (A - static_cast<T>(1.0))*cw0 - static_cast<T>(2.0) * Asqrt*alpha) / a0;\n      break;\n    }\n  }\n}\n\n// Explicit instantiations\n// Note: This code needs to be excluded from Doxygen documentation generation to avoid\n// warnings about non-matching class members.\n/// @cond NEVER\ntemplate  VISR_RBBL_LIBRARY_SYMBOL\nvoid ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<float>( ParametricIirCoefficient<float> const &,\n                                 BiquadCoefficient<float> &, float );\ntemplate  VISR_RBBL_LIBRARY_SYMBOL\nvoid ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<double>( ParametricIirCoefficient<double> const &,\n                                  BiquadCoefficient<double> &, double );\n/// @endcond NEVER\n\ntemplate< typename CoefficientType >\nvoid ParametricIirCoefficientCalculator::calculateIirCoefficients( ParametricIirCoefficientList<CoefficientType> const & params,\n                                                                   BiquadCoefficientList<CoefficientType> & coeffs,\n                                                                   CoefficientType samplingFrequency )\n{\n  if( params.size() > coeffs.size() )\n  {\n    throw std::invalid_argument( \"calculateIirCoefficients(): The output argument list \\\"coeffs\\\" holds less elements than the input list \\\"params\\\".\" );\n  }\n  typename BiquadCoefficientList<CoefficientType>::iterator it = std::transform( params.begin(), params.end(), coeffs.begin(),\n     [samplingFrequency]( ParametricIirCoefficient<CoefficientType> const & params ) { return calculateIirCoefficients<CoefficientType>( params, samplingFrequency ); } );\n  // Fill the remaining entries in coeffs with default (flat) biquad parameters.\n  std::fill( it, coeffs.end(), BiquadCoefficient<CoefficientType>() );\n}\n\n// Note: This code needs to be excluded from Doxygen documentation generation to avoid\n// warnings about non-matching class members.\n/// @cond NEVER\ntemplate VISR_RBBL_LIBRARY_SYMBOL \nvoid ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<float>( ParametricIirCoefficientList<float> const &, BiquadCoefficientList<float> &, float );\ntemplate VISR_RBBL_LIBRARY_SYMBOL \nvoid ParametricIirCoefficientCalculator::\ncalculateIirCoefficients<double>( ParametricIirCoefficientList<double> const &, BiquadCoefficientList<double> &, double );\n/// @endcond NEVER\n\n} // namespace rbbl\n} // namespace visr\n", "meta": {"hexsha": "e5e5560450052256354d2e3b71f055ad0c7ea855", "size": 10011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/librbbl/parametric_iir_coefficient_calculator.cpp", "max_stars_repo_name": "s3a-spatialaudio/VISR", "max_stars_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_stars_repo_licenses": ["ISC"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T14:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T01:16:23.000Z", "max_issues_repo_path": "src/librbbl/parametric_iir_coefficient_calculator.cpp", "max_issues_repo_name": "s3a-spatialaudio/VISR", "max_issues_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/librbbl/parametric_iir_coefficient_calculator.cpp", "max_forks_repo_name": "s3a-spatialaudio/VISR", "max_forks_repo_head_hexsha": "55f6289bc5058d4898106f3520e1a60644ffb3ab", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T12:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T10:08:08.000Z", "avg_line_length": 42.6, "max_line_length": 170, "alphanum_fraction": 0.5830586355, "num_tokens": 3262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5788333458816604}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nusing namespace std;\nusing namespace boost;\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\ntypedef boost::adjacency_list<listS, vecS, undirectedS, no_property, EdgeWeightProperty> Graph;\ntypedef Graph::vertex_descriptor Vertex;\ntypedef Graph::edge_descriptor Edge;\n\nint main() {\n  Graph g;\n  Vertex u = add_vertex(g);\n  Vertex v = add_vertex(g);\n  Vertex w = add_vertex(g);\n  Vertex x = add_vertex(g);\n  add_edge(u, v, 10, g);\n  add_edge(u, w,  5, g);\n  add_edge(u, x,  3, g);\n  add_edge(v, w,  1, g);\n  add_edge(v, x,  3, g);\n  add_edge(w, x,  7, g);\n  cout << \"Number of edges: \" << num_edges(g) << \"\\n\";\n  cout << \"Number of vertices: \" << num_vertices(g) << \"\\n\";\n  list<Edge> spanning_tree;\n  kruskal_minimum_spanning_tree(g, back_inserter(spanning_tree));\n  for (list<Edge>::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) {\n    cout << *ei << \" \";\n  }\n  cout << \"\\n\";\n  return 0;\n}\n", "meta": {"hexsha": "1a1276e178e7fcf9424be420093b6435801461b7", "size": 1037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/graph3.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/graph3.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/graph3.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": 30.5, "max_line_length": 95, "alphanum_fraction": 0.6740597878, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.5788333403522968}}
{"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_REGULARIZER_H_\n#define TURI_REGULARIZER_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/optimization_interface.hpp>\n#include <ml/optimization/regularizer_interface.hpp>\n\n// TODO: List of todo's for this file\n//------------------------------------------------------------------------------\n//\n\nnamespace turi {\n\nnamespace optimization {\n\n\n/**\n * \\ingroup group_optimization\n * \\addtogroup regularizers Regularizers\n * \\{\n */\n\n\n/**\n * Interface for the regularizer (Scaled L2-norm)\n *\n *      f(x) = \\sum_{i} lambda_i * x_i^2\n *\n */\nclass l2_norm : public smooth_regularizer_interface {\n\n  protected:\n\n    DenseVector lambda;                     /**< Penalty on the regularizer */\n    size_t variables;                       /**< # Variables in the problem */\n\n  public:\n\n\n  /**\n   * Default constructor.\n   */\n  l2_norm(const DenseVector& _lambda){\n    lambda= _lambda;\n    variables = _lambda.size();\n  }\n\n  /**\n   * Default desctuctor. Do nothing.\n   */\n  ~l2_norm(){\n  }\n\n  /**\n   * Compute the hessian of the regularizer at a given point.\n   * \\param[in]      point   Point at which we are computing the gradient.\n   * \\param[in,out]  hessian Diagonal matrix as the hessian gradient.\n   *\n   */\n  inline void compute_hessian(const DenseVector &point, DiagonalMatrix\n      &hessian) const {\n    hessian = 2 * lambda.asDiagonal();\n  }\n\n  /**\n   * Compute the function value of the regularizer at a given point.\n   * \\param[in]  point   Point at which we are computing the gradient.\n   *\n   */\n  inline double compute_function_value(const DenseVector &point) const{\n    DASSERT_EQ(variables, point.size());\n    return lambda.dot(point.cwiseAbs2());\n  }\n\n\n  /**\n   * Compute the gradient (or subgradient) at the given point.\n   *\n   * \\param[in]  point    Point at which we are computing the gradient.\n   * \\param[out] gradient Dense gradient\n   *\n   */\n  inline void compute_gradient(const DenseVector &point, DenseVector& gradient)\n    const{\n    DASSERT_EQ(variables, point.size());\n    gradient = 2 * lambda.cwiseProduct(point);\n  }\n\n  /**\n   * Compute the proximal operator for the l2-regularizer\n   *\n   * \\param[in,out]  point      Point at which we are computing the gradient.\n   * \\param[in]      penalty    Penalty\n   *\n   * \\note The proximal operator for lambda * ||x||^2 at the point v is\n   * given by\n   *                  v/(1 + 2*lambda*penalty)\n   *\n   */\n  inline void apply_proximal_operator(DenseVector &point, const double&\n      _penalty=0)const{\n    DASSERT_EQ(variables, point.size());\n    for(size_t i = 0; i < variables; i++)\n      point[i] = point[i] / (1 + 2*_penalty*lambda[i]);\n  }\n\n\n};\n\n\n/**\n * Interface for the regularizer (Scaled L1-norm)\n *\n *      f(x) = \\sum_{i} lambda_i * |x_i|\n *\n */\nclass l1_norm : public regularizer_interface {\n\n  protected:\n\n    DenseVector lambda;                     /**< Penalty on the regularizer */\n    size_t variables;                       /**< # Variables in the problem */\n\n  public:\n\n  /**\n   * Default constructor.\n   */\n  l1_norm(const DenseVector& _lambda){\n    lambda= _lambda;\n    variables = _lambda.size();\n  }\n\n  /**\n   * Default desctuctor. Do nothing.\n   */\n  ~l1_norm(){\n  }\n\n  /**\n   * Compute the function value of the regularizer at a given point.\n   * \\param[in]  point   Point at which we are computing the gradient.\n   *\n   */\n  inline double compute_function_value(const DenseVector &point) const{\n    DASSERT_EQ(variables, point.size());\n    return lambda.dot(point.cwiseAbs());\n  }\n\n\n  /**\n   * Compute the subgradient at the given point.\n   *\n   * \\param[in]  point    Point at which we are computing the gradient.\n   * \\param[out] gradient Dense sub-gradient\n   *\n   */\n  inline void compute_gradient(const DenseVector &point, DenseVector& gradient) const{\n    DASSERT_EQ(variables, point.size());\n    gradient.setZero();\n    for(size_t i = 0; i < variables; i++)\n      if (gradient[i] > OPTIMIZATION_ZERO)\n        gradient[i] = lambda[i];\n      else if (gradient[i] < - OPTIMIZATION_ZERO)\n        gradient[i] = - lambda[i];\n  }\n\n  /**\n   * Compute the proximal operator for the l2-regularizer\n   *\n   * \\param[in,out]  point      Point at which we are computing the gradient.\n   * \\param[in]      penalty    Penalty\n   *\n   * \\note The proximal operator for lambda * ||x||_1 at the point v is\n   * given by\n   *        soft(x, lambda) = (x - lambda)_+ - (-x - lambda)_+\n   *\n   */\n  inline void apply_proximal_operator(DenseVector &point, const double&\n      _penalty=0)const{\n    DASSERT_EQ(variables, point.size());\n    for(size_t i = 0; i < variables; i++)\n      point[i] = std::max(point[i] - _penalty*lambda[i], 0.0) -\n                            std::max(-point[i] - _penalty*lambda[i], 0.0);\n  }\n\n\n};\n\n\n/**\n * Interface for the elastic net regularizer (Scaled L1-norm)\n *\n *      f(x) = \\sum_{i} alpha_i * |x_i| + \\sum_{i} beta_i * x_i^2\n *\n */\nclass elastic_net : public regularizer_interface {\n\n  protected:\n\n    DenseVector alpha;                     /**< Penalty on the l1-regularizer */\n    DenseVector beta;                      /**< Penalty on the l2-regularizer */\n    size_t variables;                      /**< # Variables in the problem */\n\n  public:\n\n\n  /**\n   * Default constructor.\n   */\n  elastic_net(const DenseVector& _alpha, const DenseVector& _beta){\n    DASSERT_EQ(_alpha.size(), _beta.size());\n    alpha = _alpha;\n    beta = _beta;\n    variables = _alpha.size();\n  }\n\n  /**\n   * Default desctuctor. Do nothing.\n   */\n  ~elastic_net(){\n  }\n\n  /**\n   * Compute the function value of the regularizer at a given point.\n   * \\param[in]  point   Point at which we are computing the gradient.\n   *\n   */\n  inline double compute_function_value(const DenseVector &point) const{\n    DASSERT_EQ(variables, point.size());\n    return alpha.dot(point.cwiseAbs()) + beta.dot(point.cwiseAbs2());\n  }\n\n\n  /**\n   * Compute the subgradient at the given point.\n   *\n   * \\param[in]  point    Point at which we are computing the gradient.\n   * \\param[out] gradient Dense sub-gradient\n   *\n   */\n  inline void compute_gradient(const DenseVector &point, DenseVector& gradient) const{\n    DASSERT_EQ(variables, point.size());\n    gradient = 2 * beta.cwiseProduct(point);\n    for(size_t i = 0; i < variables; i++)\n      if (gradient[i] > OPTIMIZATION_ZERO)\n        gradient[i] += alpha[i];\n      else if (gradient[i] < - OPTIMIZATION_ZERO)\n        gradient[i] += -alpha[i];\n  }\n\n  /**\n   * Compute the proximal operator for the elastic-regularizer\n   *\n   * \\param[in,out]  point      Point at which we are computing the gradient.\n   * \\param[in]      penalty    Penalty\n   *\n   * \\note The proximal operator for alpha||x||_1 + beta||x||_2^2 at\n   *        y = soft(x, alpha) = (x - alpha)_+ - (-x - alpha)_+\n   *        x = y / (1 + 2 beta)\n   *\n   * \\note Do not swap the order.\n   *\n   */\n  inline void apply_proximal_operator(DenseVector &point, const double&\n      _penalty=0)const{\n    DASSERT_EQ(variables, point.size());\n    for(size_t i = 0; i < variables; i++){\n      point[i] = std::max(point[i] - _penalty*alpha[i], 0.0) -\n                            std::max(-point[i] - _penalty*alpha[i], 0.0);\n      point[i] = point[i] / (1 + 2*_penalty*beta[i]);\n    }\n  }\n\n\n};\n\n/// \\}\n\n} // optimization\n} // turicreate\n\n#endif\n", "meta": {"hexsha": "0b8a1388933014d8168d1a9fe361865fcd8779de", "size": 7590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ml/optimization/regularizers-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/regularizers-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/regularizers-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": 25.6418918919, "max_line_length": 86, "alphanum_fraction": 0.6105401845, "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5788005249726759}}
{"text": "#include <iostream>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nconst double sigma = 10.0;\nconst double R = 28.0;\nconst double b = 8.0 / 3.0;\n\ntypedef boost::array< double , 3 > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , double t )\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\nvoid write_lorenz( const state_type &x , const double t )\n{\n    cout << t << '\\t' << x[0] << '\\t' << x[1] << '\\t' << x[2] << endl;\n}\n\nint main(int argc, char **argv)\n{\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}\n", "meta": {"hexsha": "37155aaedca0b845c61f4df2d9b12f891399a4b2", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/lorenz.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/lorenz.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/lorenz.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": 23.90625, "max_line_length": 70, "alphanum_fraction": 0.5712418301, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5788005035317423}}
{"text": "/**\n * @date Fri Jan 27 14:10:23 2012 +0100\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <algorithm>\n#include <boost/shared_array.hpp>\n\n#include <bob.math/lu.h>\n\n#include <bob.core/assert.h>\n#include <bob.core/array_copy.h>\n\n// Declaration of the external LAPACK functions\n// LU decomposition of a general matrix (dgetrf)\nextern \"C\" void dgetrf_( const int *M, const int *N, double *A,\n  const int *lda, int *ipiv, int *info);\n// Cholesky decomposition of a real symmetric definite-positive matrix (dpotrf)\nextern \"C\" void dpotrf_( const char *uplo, const int *N, double *A,\n  const int *lda, int *info);\n\n\nvoid bob::math::lu(const blitz::Array<double,2>& A, blitz::Array<double,2>& L,\n  blitz::Array<double,2>& U, blitz::Array<double,2>& P)\n{\n  // Size variable\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int minMN = std::min(M,N);\n\n  // Check\n  const blitz::TinyVector<int,2> shapeL(M,minMN);\n  const blitz::TinyVector<int,2> shapeU(minMN,N);\n  const blitz::TinyVector<int,2> shapeP(minMN,minMN);\n\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(L);\n  bob::core::array::assertZeroBase(U);\n  bob::core::array::assertZeroBase(P);\n\n  bob::core::array::assertSameShape(L,shapeL);\n  bob::core::array::assertSameShape(U,shapeU);\n  bob::core::array::assertSameShape(P,shapeP);\n\n  bob::math::lu_(A, L, U, P);\n}\n\nvoid bob::math::lu_(const blitz::Array<double,2>& A, blitz::Array<double,2>& L,\n  blitz::Array<double,2>& U, blitz::Array<double,2>& P)\n{\n  // Size variable\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n  const int minMN = std::min(M,N);\n\n  // Prepares to call LAPACK function\n\n  // Initialises LAPACK variables\n  int info = 0;\n  const int lda = M;\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double *A_lapack = A_blitz_lapack.data();\n  boost::shared_array<int> ipiv(new int[minMN]);\n\n  // Calls the LAPACK function\n  dgetrf_( &M, &N, A_lapack, &lda, ipiv.get(), &info);\n\n  // Checks info variable\n  // If U is greater than zero, this means that the U matrix is equal to zero.\n  if (info < 0)\n    throw std::runtime_error(\"The LAPACK dgetrf function returned a negative value.\");\n\n  // Copy result back to L and U\n  blitz::firstIndex bi;\n  blitz::secondIndex bj;\n  blitz::Array<double,2> A_blitz_lapack_t = A_blitz_lapack.transpose(1,0);\n  blitz::Range rall = blitz::Range::all();\n  L = blitz::where(bi>bj, A_blitz_lapack_t(rall,blitz::Range(0,minMN-1)), 0.);\n  L = blitz::where(bi==bj, 1., L);\n  U = blitz::where(bi<=bj, A_blitz_lapack_t(blitz::Range(0,minMN-1),rall), 0.);\n\n  // Converts weird permutation format returned by LAPACK into a permutation\n  // function\n  blitz::Array<int,1> Pp(minMN);\n  Pp = bi;\n  int temp;\n  for (int i=0; i<minMN-1; ++i)\n  {\n    temp = Pp(ipiv[i]-1);\n    Pp(ipiv[i]-1) = Pp(i);\n    Pp(i) = temp;\n  }\n  // Updates P\n  P = 0.;\n  for (int j = 0; j<minMN; ++j)\n    P(j,Pp(j)) = 1.;\n}\n\n\nvoid bob::math::chol(const blitz::Array<double,2>& A,\n  blitz::Array<double,2>& L)\n{\n  // Size variable\n  const int M = A.extent(0);\n  const int N = A.extent(1);\n\n  // Check\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(L);\n  bob::core::array::assertSameDimensionLength(M,N);\n  bob::core::array::assertSameShape(A,L);\n\n  bob::math::chol_(A, L);\n}\n\nvoid bob::math::chol_(const blitz::Array<double,2>& A,\n  blitz::Array<double,2>& L)\n{\n  // Size variable\n  const int N = A.extent(0);\n\n  // Prepares to call LAPACK function\n  // Initialises LAPACK variables\n  int info = 0;\n  const int lda = N;\n  const char uplo = 'L';\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack;\n  // Tries to use V directly\n  blitz::Array<double,2> Lt = L.transpose(1,0);\n  const bool Lt_direct_use = bob::core::array::isCZeroBaseContiguous(Lt);\n  if (Lt_direct_use)\n  {\n    A_blitz_lapack.reference(Lt);\n    A_blitz_lapack = A;\n  }\n  else\n    A_blitz_lapack.reference(bob::core::array::ccopy(A));\n  double *A_lapack = A_blitz_lapack.data();\n\n  // Calls the LAPACK function\n  dpotrf_( &uplo, &N, A_lapack, &lda, &info);\n\n  // Checks info variable\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK dpotrf function returned a non-zero value.\");\n\n  // Copy result back to L if required\n  if (!Lt_direct_use)\n    Lt = A_blitz_lapack;\n\n  // Sets strictly upper triangular part to 0\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n  L = blitz::where(i < j, 0, L);\n}\n\n", "meta": {"hexsha": "25cad4f6c8b4827471327adb538304b62031e103", "size": 4606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/lu.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/lu.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/lu.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": 27.9151515152, "max_line_length": 86, "alphanum_fraction": 0.6632653061, "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5786909708046293}}
{"text": "#include <iostream>\n#include <cmath>\n#include <complex>\n#include <type_traits>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\nnamespace tst {\n\n    template <typename T>\n    struct is_matrix\n      : std::false_type\n    {};\n    \n    template <typename Value, typename Para>\n    struct is_matrix<mtl::dense2D<Value, Para> >\n      : std::true_type\n    {};\n\n    template <typename T>\n    struct is_vector\n      : std::false_type\n    {};\n    \n    template <typename Value, typename Para>\n    struct is_vector<mtl::dense_vector<Value, Para> >\n      : std::true_type\n    {};\n\n    template <typename T>\n    struct Magnitude\n    {\n\tusing type= T;\n    };\n\n    template <typename T>\n    struct Magnitude<std::complex<T> >\n    {\n\tusing type= T;\n    };\n\n    template <typename T, typename Para>\n    struct Magnitude<mtl::dense_vector<T, Para> >\n    {\n\tusing type= typename Magnitude<T>::type;  \n    };\n\n    template <typename T, typename Para>\n    struct Magnitude<mtl::dense2D<T, Para> >\n    {\n\tusing type= typename Magnitude<T>::type;  \n    };\n\n    template <typename T>\n    using Magnitude_t= typename Magnitude<T>::type;\n\n    template <bool Cond, typename T= void>\n    using enable_if_t= typename std::enable_if<Cond, T>::type;\n\n\n    template <typename T>\n    enable_if_t<is_matrix<T>::value, Magnitude_t<T>>\n    inline one_norm(const T& A)\n    {\n\tusing std::abs;\n\tMagnitude_t<T> max{0};\n\tfor (unsigned c= 0; c < num_cols(A); c++) {\n\t    Magnitude_t<T> sum{0};\n\t    for (unsigned r= 0; r < num_cols(A); r++)\n\t\tsum+= abs(A[r][c]);\n\t    max= max < sum ? sum : max;\n\t}\n\treturn max;\n    }\n\n    template <typename T>\n    enable_if_t<is_vector<T>::value, Magnitude_t<T>>\n    inline one_norm(const T& v)\n    {\n\tusing std::abs;\n\tMagnitude_t<T> sum{0};\n\tfor (unsigned r= 0; r < size(v); r++)\n\t    sum+= abs(v[r]);\n\treturn sum;\n    }\n\n\n}\n\nint main (int argc, char* argv[]) \n{\n    mtl::dense2D<float> A= {{2, 3, 4},\n\t\t\t    {5, 6, 7},\n\t\t\t    {8, 9, 10}};\n    mtl::dense_vector<float> v{3, 4, 5};\n\n    std::cout << \"one_norm(A) is \" << tst::one_norm(A) << \"\\n\";\n    std::cout << \"one_norm(v) is \" << tst::one_norm(v) << \"\\n\";\n\n    // std::cout << \"one_norm(3.5) is \" << tst::one_norm(3.5) << \"\\n\";\n\n    return 0 ;\n\n}\n", "meta": {"hexsha": "a7197499335865fd6eed30477a728c733c4ba5f1", "size": 2186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++11/enable_if_example.cpp", "max_stars_repo_name": "tzaffi/cpp", "max_stars_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T14:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:28:17.000Z", "max_issues_repo_path": "DMCpp/GottschlingRepo/c++11/enable_if_example.cpp", "max_issues_repo_name": "tzaffi/cpp", "max_issues_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T14:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T02:14:07.000Z", "max_forks_repo_path": "DMCpp/GottschlingRepo/c++11/enable_if_example.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-29T02:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T08:52:22.000Z", "avg_line_length": 20.819047619, "max_line_length": 70, "alphanum_fraction": 0.5832570906, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.5786909687149492}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include \"timer.h\"\n\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/GenEigsSolver.h>\n\nusing namespace Spectra;\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXcd;\nusing Eigen::VectorXcd;\n\nvoid eigs_sym_Cpp(MatrixXd &M, VectorXd &init_resid, int k, int m,\n                  double &time_used, double &prec_err, int &nops)\n{\n    double start, end;\n    start = get_wall_time();\n\n    DenseSymMatProd<double> op(M);\n    SymEigsSolver<double, LARGEST_MAGN, DenseSymMatProd<double> > eigs(&op, k, m);\n    eigs.init(init_resid.data());\n\n    int nconv = eigs.compute();\n    int niter = eigs.num_iterations();\n    nops = eigs.num_operations();\n\n    VectorXd evals = eigs.eigenvalues();\n    MatrixXd evecs = eigs.eigenvectors();\n\n    /* std::cout << \"computed eigenvalues D = \\n\" << evals.transpose() << std::endl;\n    std::cout << \"first 5 rows of computed eigenvectors U = \\n\" << evecs.topRows<5>() << std::endl;\n    std::cout << \"nconv = \" << nconv << std::endl;\n    std::cout << \"niter = \" << niter << std::endl;\n    std::cout << \"nops = \" << nops << std::endl; */\n\n    end = get_wall_time();\n    time_used = (end - start) * 1000;\n\n    MatrixXd err = M * evecs - evecs * evals.asDiagonal();\n    prec_err = err.cwiseAbs().maxCoeff();\n}\n\nvoid eigs_gen_Cpp(MatrixXd &M, VectorXd &init_resid, int k, int m,\n                  double &time_used, double &prec_err, int &nops)\n{\n    double start, end;\n    start = get_wall_time();\n\n    DenseGenMatProd<double> op(M);\n    GenEigsSolver<double, LARGEST_MAGN, DenseGenMatProd<double> > eigs(&op, k, m);\n    eigs.init(init_resid.data());\n\n    int nconv = eigs.compute();\n    int niter = eigs.num_iterations();\n    nops = eigs.num_operations();\n\n    VectorXcd evals = eigs.eigenvalues();\n    MatrixXcd evecs = eigs.eigenvectors();\n\n    /* std::cout << \"computed eigenvalues D = \\n\" << evals.transpose() << std::endl;\n    std::cout << \"first 5 rows of computed eigenvectors U = \\n\" << evecs.topRows<5>() << std::endl;\n    std::cout << \"nconv = \" << nconv << std::endl;\n    std::cout << \"niter = \" << niter << std::endl;\n    std::cout << \"nops = \" << nops << std::endl;\n\n    MatrixXcd err = M * evecs - evecs * evals.asDiagonal();\n    std::cout << \"||AU - UD||_inf = \" << err.array().abs().maxCoeff() << std::endl; */\n\n    end = get_wall_time();\n    time_used = (end - start) * 1000;\n\n    MatrixXcd err = M * evecs - evecs * evals.asDiagonal();\n    prec_err = err.cwiseAbs().maxCoeff();\n}\n", "meta": {"hexsha": "c0ec8084056e0db5733c120a70531b50fb993d70", "size": 2483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/Cpp.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/Cpp.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/benchmark/Cpp.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 32.2467532468, "max_line_length": 99, "alphanum_fraction": 0.619009263, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.578690967967323}}
{"text": "/*\n * main.cpp\n *\n *  Created on: Dec 10, 2021\n *      Author: tiba\n */\n\n//\n\n#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n#include <vector>\n#include <Eigen/StdVector>\n#include <fstream>\n#include <iterator>\n#include \"STRUC.h\"\n#include \"Mesh.h\"\n#include \"Fluid.h\"\n#include \"FSI.h\"\n#include \"config.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\nproperties load_ppts()\n{\n\tproperties ppts;\n\tfloat a, b, c, interm;\n\n\tppts.Coeff = coeff; // Fraction of natural structural period, giving the total period of simulation\n\n\tppts.L_0 = 1; // Initial Gas Chamber Length (not including the initial displacement)\n\tppts.A = 1;\t  // Section\n\n\tppts.U_0 = .2; // Initial displacement\n\tppts.L_t = ppts.L_0 + ppts.U_0;\n\n\tppts.gam = 1.4; // the specific heat ratio of the gas\n\tppts.gamm1 = ppts.gam - 1.;\n\tppts.R = 287;\t\t\t\t\t// the individual gas constant\n\tppts.C_v = ppts.R / ppts.gamm1; // the specific heat capacity of the gas\n\n\tppts.pres_init0 = 1E5;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// initial pressure for chamber length = L0\n\tppts.temp_init0 = 300;\t\t\t\t\t\t\t\t\t\t\t\t\t\t// initial temperature\n\tppts.rho_init0 = ppts.pres_init0 / ppts.gamm1 / ppts.C_v / ppts.temp_init0; // initial volumic mass\n\n\tppts.pres_init = ppts.pres_init0 * pow((ppts.L_0 / ppts.L_t), ppts.gam);\n\n\tppts.rho_init = ppts.rho_init0 * pow((ppts.pres_init / ppts.pres_init0), (1. / ppts.gam));\n\tppts.temp_init = ppts.pres_init / ppts.rho_init / ppts.gamm1 / ppts.C_v;\n\tppts.p_ext = 0 * ppts.pres_init0; // pressure on the right of the piston\n\n\t// we set the initial fluid velocity and the initial total fluid energy\n\tppts.u_init = 0.;\n\tppts.e_init = ppts.pres_init / ppts.gamm1 / ppts.rho_init + 0.5 * pow(ppts.u_init, 2.);\n\n\tppts.vprel.push_back(1e7);\t// Spring rigidity\n\tppts.vprel.push_back(mass); // Spring mass\n\tppts.spring_model = \"linear\";\n\tppts.nln_order = 3;\n\n\tppts.Lsp0 = 1.2; // Unstretched spring length\n\tif (ppts.spring_model == \"nonlinear\")\n\t{\n\t\tppts.umax = 0.2; // Maximum spring displacements for linear spring model ('C' Model)\n\t\tppts.mu = mu_coeff * ppts.vprel[0] / ppts.umax;\n\t\tif (ppts.nln_order == 2)\n\t\t{\n\t\t\tppts.u0 = (-ppts.vprel[0] + sqrt(pow(ppts.vprel[0], 2) + 4 * ppts.mu * ppts.A * ppts.pres_init0)) / (-2 * ppts.mu);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ta = ppts.vprel[0];\n\t\t\tb = ppts.mu;\n\t\t\tc = ppts.A * ppts.pres_init0;\n\t\t\tinterm = pow((((std::sqrt((27 * b * pow(c, 2) + 4 * pow(a, 3)) / b)) / (b * 2 * pow(3, (3. / 2.)))) - c / (2 * b)), (1. / 3.));\n\t\t\tppts.u0 = interm - a / (3 * b * interm);\n\t\t}\n\t\tppts.Lspe = ppts.Lsp0 + ppts.u0;\n\t}\n\telse\n\t{\n\t\tppts.Lspe = ppts.Lsp0 - (ppts.pres_init0 - ppts.p_ext) * ppts.A / ppts.vprel[0]; // initial spring length\n\t}\n\n\treturn ppts;\n}\n\nint main()\n{\n\n\t// Geometrical and physical properties\n\tproperties ppts;\n\tppts = load_ppts();\n\n\t// Create the mesh\n\tint nnt = nmesh;\n\tMesh mesh_n;\n\tmesh_n.load(nnt, ppts.L_t);\n\n\t// Create the fluid FEM model\n\tFluid fluid_model(ppts);\n\tfluid_model.initialize(mesh_n);\n\n\t// Create the structure FEM model\n\tSTRUC structure_model(ppts);\n\tstructure_model.initialize(fluid_model.get_vpres()(nnt - 1));\n\n\t// Create the fluid-strucure interaction coupling\n\tFSI fsi_piston(structure_model.T0);\n\n\t// Solve the problem\n\tfsi_piston.solve(structure_model, fluid_model);\n\n\t// Export the results into .txt files\n\tfsi_piston.export_results();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d920a29495945fba3fb9b337627e940db1992fca", "size": 3295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "azzeddinetiba/fsi_piston", "max_stars_repo_head_hexsha": "9f706e1d2f04f7a338782959c4a89a9d2c9f2956", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T14:36:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T14:36:37.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "azzeddinetiba/fsi_piston", "max_issues_repo_head_hexsha": "9f706e1d2f04f7a338782959c4a89a9d2c9f2956", "max_issues_repo_licenses": ["MIT"], "max_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": "azzeddinetiba/fsi_piston", "max_forks_repo_head_hexsha": "9f706e1d2f04f7a338782959c4a89a9d2c9f2956", "max_forks_repo_licenses": ["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.7886178862, "max_line_length": 130, "alphanum_fraction": 0.6655538695, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5786842534701037}}
{"text": "//\n//  main.cpp\n//  using_eigen\n//\n//  Created by on 2018/11/6.\n//  Copyright @2018 kouui. All rights reserved.\n//\n\n#include <Eigen/Dense>\n#include <iostream>\n\nint main()\n{\n    // Dynamic\n    // X : unknown size, resizable\n    // d : double\n    Eigen::MatrixXd m;\n\n    // fixed Sized Matrix\n    Eigen::Matrix3d f;\n\n    f << 1, 2, 3,\n        4, 5, 6,\n        7, 8, 9;\n\n    f = Eigen::Matrix3d::Constant(1.0);\n\n    m = Eigen::MatrixXd::Constant(5, 5, 1.0);\n\n    std::cout << m << \"\\n\";\n}\n", "meta": {"hexsha": "6776d8dc6b3b4176f9a88be89dbceea9ca27744b", "size": 486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "using_eigen/main.cpp", "max_stars_repo_name": "kouui/cpp_testground", "max_stars_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "using_eigen/main.cpp", "max_issues_repo_name": "kouui/cpp_testground", "max_issues_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "using_eigen/main.cpp", "max_forks_repo_name": "kouui/cpp_testground", "max_forks_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.1875, "max_line_length": 47, "alphanum_fraction": 0.5308641975, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5786282068644508}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <complex>\n#include <tuple>\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/complex_field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n#include \"vlasovpp/splitting.h\"\n#include \"vlasovpp/lagrange5.h\"\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*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\n\n#define ping(X) std::cerr << __LINE__ << \" \" << #X << \":\" << X << std::endl\nint debug = 0;\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  //std::cout << rho << \" \" << u << \" \" << T << std::endl;\n  //std::cout << rho/(std::sqrt(2.*math::pi<double>()*T)) << std::endl;\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 main(int,char**)\n{\n  std::size_t Nx = 135, Nv = 256;\n\n  // $(u_c,E,\\hat{f}_h)$ and $f_h$\n  ublas::vector<double> uc(Nx,0.);\n  ublas::vector<double> E (Nx,-1.76);\n  field<double,1> fh(boost::extents[Nv][Nx]);\n  complex_field<double,1> hfh(boost::extents[Nv][Nx]);\n\n  const double Kx = 0.5;\n  // phase-space domain\n  fh.range.v_min = -8.; fh.range.v_max = 8.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n\n  // compute dx, dv\n  fh.step.dv = (fh.range.v_max-fh.range.v_min)/Nv;\n  fh.step.dx = (fh.range.x_max-fh.range.x_min)/Nx;\n\n  const double dt = 0.1;//1.*fh.step.dv;\n  double Tf = 60.*dt;\n  \n  // velocity and frequency\n  ublas::vector<double> v (Nv,0.); for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  const double l = fh.range.x_max-fh.range.x_min;\n  ublas::vector<double> kx(Nx);\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\n  // initial condition\n  double ui=2., alpha=0.2;\n  auto tb_M1 = maxwellian(0.5*alpha,ui,1.) , tb_M2 = maxwellian(0.5*alpha,-ui,1.);\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      fh[k][i] = std::cos(2.*math::pi<double>()/16.*(Vk(k)-0.5));\n    }\n    fft::fft(&(fh[k][0]),&(fh[k][Nx-1])+1,&(hfh[k][0]));\n  }\n  fh.write(\"vphl/split/init.dat\");\n\n  splitting<double,1> Lie( fh , l , 1. );\n\n  std::vector<double> times;\n\n  std::size_t i_t = 0;\n  double current_time = 0.;\n  while ( i_t < 60 ) {\n    std::cout << \" [\" << std::setw(5) << i_t << \"] \" << i_t*dt << \"\\r\" << std::flush;\n\n    Lie.phi_b(dt,uc,E,hfh);\n\n    current_time += dt;\n    ++i_t;\n    times.push_back( current_time );\n  } // while current_time < Tf\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt<< \"    \"<<std::endl;\n\n  for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(&(hfh[k][0]),&(hfh[k][Nx-1])+1,&(fh[k][0])); }\n  fh.write(\"vphl/split/vp.dat\");\n\n  for ( auto k=0 ; k<fh.size(0) ; ++k ) {\n    for ( auto i=0 ; i<fh.size(1) ; ++i ) {\n      fh[k][i] -= std::cos(2.*math::pi<double>()/16.*( Vk(k)-0.5-E(i)*Tf ));\n    }\n  }\n\n  fh.write(\"vphl/split/diff.dat\");\n\n  for ( auto ei : E ) {\n    std::cout << ei << \" , \";\n  }\n  std::cout << std::endl;\n  return 0;\n}\n\n", "meta": {"hexsha": "aa52dbad2add4f9230bd9e499bf1a48dc15a45d0", "size": 3442, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/phib.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/phib.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/phib.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": 29.6724137931, "max_line_length": 111, "alphanum_fraction": 0.5729227193, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5786281851612877}}
{"text": "\r\n#include <NTL/vec_RR.h>\r\n\r\n\r\nNTL_START_IMPL\r\n\r\n\r\nvoid InnerProduct(RR& xx, const vec_RR& a, const vec_RR& b)\r\n{\r\n   RR t1, x;\r\n\r\n   long n = min(a.length(), b.length());\r\n   long i;\r\n\r\n   clear(x);\r\n   for (i = 1; i <= n; i++) {\r\n      mul(t1, a(i), b(i));\r\n      add(x, x, t1);\r\n   }\r\n\r\n   xx = x;\r\n}\r\n\r\nvoid mul(vec_RR& x, const vec_RR& a, const RR& b_in)\r\n{\r\n   RR b = b_in;\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      mul(x[i], a[i], b);\r\n}\r\n\r\nvoid mul(vec_RR& x, const vec_RR& a, double b_in)\r\n{\r\n   NTL_THREAD_LOCAL static RR b;\r\n   conv(b, b_in);\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      mul(x[i], a[i], b);\r\n}\r\n\r\nvoid add(vec_RR& x, const vec_RR& a, const vec_RR& b)\r\n{\r\n   long n = a.length();\r\n   if (b.length() != n) LogicError(\"vector add: dimension mismatch\");\r\n\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      add(x[i], a[i], b[i]);\r\n}\r\n\r\nvoid sub(vec_RR& x, const vec_RR& a, const vec_RR& b)\r\n{\r\n   long n = a.length();\r\n   if (b.length() != n) LogicError(\"vector sub: dimension mismatch\");\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      sub(x[i], a[i], b[i]);\r\n}\r\n\r\nvoid clear(vec_RR& x)\r\n{\r\n   long n = x.length();\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\nvoid negate(vec_RR& x, const vec_RR& a)\r\n{\r\n   long n = a.length();\r\n   x.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      negate(x[i], a[i]);\r\n}\r\n\r\n\r\nlong IsZero(const vec_RR& a)\r\n{\r\n   long n = a.length();\r\n   long i;\r\n\r\n   for (i = 0; i < n; i++)\r\n      if (!IsZero(a[i]))\r\n         return 0;\r\n\r\n   return 1;\r\n}\r\n\r\nvec_RR operator+(const vec_RR& a, const vec_RR& b)\r\n{\r\n   vec_RR res;\r\n   add(res, a, b);\r\n   NTL_OPT_RETURN(vec_RR, res);\r\n}\r\n\r\nvec_RR operator-(const vec_RR& a, const vec_RR& b)\r\n{\r\n   vec_RR res;\r\n   sub(res, a, b);\r\n   NTL_OPT_RETURN(vec_RR, res);\r\n}\r\n\r\n\r\nvec_RR operator-(const vec_RR& a)\r\n{\r\n   vec_RR res;\r\n   negate(res, a);\r\n   NTL_OPT_RETURN(vec_RR, res);\r\n}\r\n\r\nRR operator*(const vec_RR& a, const vec_RR& b)\r\n{\r\n   RR res;\r\n   InnerProduct(res, a, b);\r\n   return res;\r\n}\r\n\r\nvoid VectorCopy(vec_RR& x, const vec_RR& a, long n)\r\n{\r\n   if (n < 0) LogicError(\"VectorCopy: negative length\");\r\n   if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in VectorCopy\");\r\n\r\n   long m = min(n, a.length());\r\n\r\n   x.SetLength(n);\r\n\r\n   long i;\r\n\r\n   for (i = 0; i < m; i++)\r\n      x[i] = a[i];\r\n\r\n   for (i = m; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "a7ac205411e0baa649eef1d55d0ff96cd943ce2f", "size": 2529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/vec_RR.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/vec_RR.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/vec_RR.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5625, "max_line_length": 71, "alphanum_fraction": 0.5061289047, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.5785894112912101}}
{"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\nint max(int a, int b){\n    if (a<b) return b;\n    else return a;\n}\n\nint min(int a, int b){\n    if (a>b) return b;\n    else return a;\n}\n\n// auto max(auto a, auto b){\n//     if (a<b) return b;\n//     else return a;\n// }\n\n// auto min(auto a, auto b){\n//     if (a>b) return b;\n//     else return a;\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\ndouble eigenProjsDistance(vector<double> proj1, vector<double> proj2){\n\n    double res =0.0;\n    for (int i=0; i<min(proj1.size(),proj2.size());i++){\n        res+=(proj1[i]-proj2[i])*(proj1[i]-proj2[i]);\n    }\n    return res;\n}\n\n\n\nint main(int argc, char* argv[]){\n\n    //DB file : \n    ofstream outFile;\n    outFile.open (\"DBEigen.txt\");\n    \n\n\n    //recup eigenfaces\n\n    if (argc<3){\n        cout<<\"usage : eigenfaces dir0 ... dirn\\n\"<<endl;\n    }\n    vector<string> directories;\n    for (int i=0; i<argc-2;i++){\n        string s = string(argv[i+2]);\n        int found = s.find_last_of('/');\n\n        directories.push_back(s.substr(found+1));\n    }\n    \n    vector<TempImgLine> eigenfaces;\n    int K =42; int nH;int nW;\n\n    for (int i=0; i<K;i++){\n        OCTET* im;\n        char name[100];\n        \n        sprintf(name,\"/im%d.pgm\",i);\n        string eigenFolder = string(string(argv[1])+string(name));\n        \n        lire_nb_lignes_colonnes_image_pgm(eigenFolder.c_str(),&nH,&nW);\n        allocation_tableau(im,OCTET,nH*nW);\n        lire_image_pgm(eigenFolder.c_str(),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++){\n            eigenFace(j)=eigenFace(j)/sqrt(sum);\n            }\n        eigenfaces.push_back(eigenFace);\n        free(im);\n    }\n\n    \n    \n\n    //vector<vector<vector<double>>> registre = vector<vector<vector<double>>>();\n\n    int countDirs =0;\n    for (int i=0; i<argc-2;i++){\n        int countFile=0;\n\n        outFile<<\"!\"<<directories[i]<<endl;\n        for (auto& file : std::filesystem::directory_iterator(argv[i+2])){\n            //registre.push_back(vector<vector<double>>());\n            OCTET* img;\n            lire_nb_lignes_colonnes_image_pgm(file.path().c_str(),&nH,&nW);\n            TempImgLine imgLine(nH*nW);            \n            allocation_tableau(img,OCTET, nH*nW);\n            lire_image_pgm(file.path().c_str(),img,nH*nW);\n            double sumIm=0.0;\n            for (int ip=0;ip<nH*nW;ip++){sumIm+=(double)(img[ip]-127)*(double)(img[ip]-127);}\n            for (int ip=0; ip<nH*nW;ip++){imgLine(ip)=(double)(img[ip]-127)/sumIm;}\n\n            //registre[countDirs].push_back(projectOnEigenSpace(eigenfaces,imgLine,K));\n            vector<double> testPrint = projectOnEigenSpace(eigenfaces,imgLine,K);\n            for (int d=0; d<testPrint.size();d++){outFile<<testPrint[d]<<\" \";}\n            outFile<<endl;\n\n            countFile++;\n        }\n        outFile<<endl;\n        countDirs++;\n    }\n\n    outFile.close();\n} ", "meta": {"hexsha": "8f0b67992177f0a7b52af98ded45098d3312d2b8", "size": 4192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/dbMakingEigen.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/dbMakingEigen.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/dbMakingEigen.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": 24.2312138728, "max_line_length": 95, "alphanum_fraction": 0.5794370229, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5785818795089785}}
{"text": "#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\ntemplate <typename qp_t>\nvoid print_qp(qp_t qp)\n{\n    Eigen::IOFormat fmt(Eigen::StreamPrecision, 0, \", \", \",\", \"[\", \"]\", \"[\", \"]\");\n    std::cout << \"P = \" << qp.P.format(fmt) << '\\n';\n    std::cout << \"q = \" << qp.q.transpose().format(fmt) << '\\n';\n    std::cout << \"A = \" << qp.A.format(fmt) << '\\n';\n    std::cout << \"l = \" << qp.l.transpose().format(fmt) << '\\n';\n    std::cout << \"u = \" << qp.u.transpose().format(fmt) << '\\n';\n}\n\ntemplate <typename Mat>\nbool is_psd(Mat &h)\n{\n    Eigen::EigenSolver<Mat> eigensolver(h);\n    for (int i = 0; i < eigensolver.eigenvalues().RowsAtCompileTime; i++) {\n        double v = eigensolver.eigenvalues()(i).real();\n        if (v <= 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\n#endif /* UTILS_HPP */", "meta": {"hexsha": "caaf15642c0fa04aec78489444bce12a96fbe577", "size": 875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solvers/utils.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/utils.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/utils.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": 27.34375, "max_line_length": 82, "alphanum_fraction": 0.5462857143, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5785818630610444}}
{"text": "/**\n * \\file dcs/math/stats/distribution/weibull.hpp\n *\n * \\brief The Weibull probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_WEIBULL_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_WEIBULL_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/weibull.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/random/uniform_01_adaptor.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\n/**\n * \\brief The Weibull distribution with shape parameter \\f$k\\f$ and scale\n *  parameter \\f$\\lambda\\f$.\n *\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * The probability density function (pdf):\n * \\f[\n *   \\Pr(x|k,\\lambda)=\\begin{cases} \\frac{k}{\\lambda}\\left(\\frac{x}{\\lambda}\\right)^{k-1}e^{-(x/\\lambda)^{k}} & x\\geq0\\\\ 0 & x<0\\end{cases}\n * \\f]\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass weibull_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit weibull_distribution(support_type shape, support_type scale=1)\n\t\t: dist_(shape, scale)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this\n\t * weibull distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this weibull\n\t * distribution.\n\t *\n\t * A \\c weibull random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|k,\\lambda)=\\begin{cases} \\frac{k}{\\lambda}\\left(\\frac{x}{\\lambda}\\right)^{k-1}e^{-(x/\\lambda)^{k}} & x\\geq0\\\\ 0 & x<0\\end{cases}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\t::dcs::math::random::uniform_01_adaptor<UniformRandomGeneratorT&, support_type> eng(rng);\n\n\t\treturn dist_.scale()*(::std::pow(-::std::log(eng()),value_type(1)/dist_.shape()));\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * weibull distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * weibull distribution.\n\t *\n\t * A \\c weibull random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\lambda) = \\lambda e^{-\\lambda x}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n)\n\t{\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(rand(rng));\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type shape() const\n\t{\n\t\treturn dist_.shape();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn dist_.scale();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn support_type(0);\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\tprivate: ::boost::math::weibull_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, weibull_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"Weibull(\"\n\t\t\t  << \"shape=\" <<  dist.shape()\n\t\t\t  << \", scale=\" <<  dist.scale()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_WEIBULL_HPP\n", "meta": {"hexsha": "a26aa716a83419542664a44b33ddc0bfe33134bc", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/weibull.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/weibull.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/weibull.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.5714285714, "max_line_length": 145, "alphanum_fraction": 0.7032258065, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5785717157284682}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n\n#include \"sys.h\"\n#include <time.h>\n#include \"grid.h\"\n#include <armadillo>\n\nusing namespace std;\n\ndouble compute_convolution_normal(System *sys, double *pNoise, Node *C) {\n    double sum = 0;\n\n    for (int i = 1; i < 2 * sys->len; i++) {\n        int samp_y = (C[i].x + C[i - 1].x) * 0.5;\n        int samp_x = (C[i].y + C[i - 1].y) * 0.5;\n\n        if (samp_x < 0)\n            samp_x = 0;\n        if (samp_y < 0)\n            samp_y = 0;\n\n        if (samp_x > sys->NGrid)\n            samp_x = sys->NGrid - 1;\n        if (samp_y > sys->NGrid)\n            samp_y = sys->NGrid - 1;\n\n        int pic_loc = samp_y * sys->NGrid + samp_x;\n\n        sum = sum + pNoise[pic_loc];\n    }\n\n    sum = sum / (2 * sys->len + 1);\n\n    return sum;\n}\n\ndouble compute_convolution_high(System *sys, double *pNoise, Node *C) {\n    double sum = 0;\n\n    double filter[3][3] = {\n        0, 1 / 2, 0,\n        1 / 2, 1.5, 1 / 2,\n        0, 1 / 2, 0\n    };\n\n    for (int i = 1; i < 2 * sys->len; i++) {\n        int samp_x = (C[i].x + C[i - 1].x) * 0.5;\n        int samp_y = (C[i].y + C[i - 1].y) * 0.5;\n\n        if (samp_x < 0)\n            samp_x = 0;\n        if (samp_y < 0)\n            samp_y = 0;\n\n        if (samp_x > sys->NGrid)\n            samp_x = sys->NGrid - 1;\n        if (samp_y > sys->NGrid)\n            samp_y = sys->NGrid - 1;\n\n        for (int r = 0; r < 3; r++) {\n            for (int s = 0; s < 3; s++) {\n                int n = (samp_x - 3 / 2 + r + sys->NGrid) % sys->NGrid;\n                int m = (samp_y - 3 / 2 + s + sys->NGrid) % sys->NGrid;\n                int pic_loc = n * sys->NGrid + m;\n                sum = sum + (pNoise[pic_loc] * filter[r][s]);\n            }\n        }\n    }\n\n    sum = sum / (2 * sys->len + 1);\n\n    return sum;\n}\n\nvoid synthesize_vectors(System *sys, Grid *grid, double **vect_x, double **vect_y) {\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            vect_x[j][i] = grid->Hy(j,i);\n            vect_y[j][i] = grid->Hz(j,i);\n        }\n    }\n}\n\nvoid normalize_vectors(System *sys, double **vect_x, double **vect_y) {\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            double mag = sqrtf(vect_x[j][i] * vect_x[j][i] + vect_y[j][i] * vect_y[j][i]);\n\n            if (mag > 0.0) {\n                vect_x[j][i] = vect_x[j][i] / mag;\n                vect_y[j][i] = vect_y[j][i] / mag;\n            }\n            else {\n                vect_x[j][i] = 0;\n                vect_y[j][i] = 0;\n            }\n        }\n    }\n}\n\nvoid white_noise(System *sys, double *pNoise) {\n    int pic_loc;\n\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            int r = rand();\n            pic_loc = j * sys->NGrid + i;\n\n            r = ((r & 255) + ((r & 255) >> 8)) & 255;\n            pNoise[pic_loc] = (unsigned char) r;\n        }\n    }\n}\n\nvoid compute_integral_curve(System *sys, Node *p, Node *C, double **vect_x, double **vect_y) {\n    double x = p->x + 0.5;\n    double y = p->y + 0.5;\n\n    int s;\n    int index = 0;\n\n    C[index].x = x;\n    C[index].y = y;\n\n    double segLen = 0;\n    double vctr_x = 0;\n    double vctr_y = 0;\n\n    // positive calculations\n    for (s = 0; s < sys->len; s++) {\n        if (x < 0)\n            x = 0;\n        if (y < 0)\n            y = 0;\n\n        if (x > sys->NGrid)\n            x = sys->NGrid - 1;\n        if (y > sys->NGrid)\n            y = sys->NGrid - 1;\n\n        vctr_x = vect_x[(int) x][(int) y];\n        vctr_y = vect_y[(int) x][(int) y];\n\n        segLen += 0.1;\n\n        x = x + segLen * vctr_x;\n        y = y + segLen * vctr_y;\n\n        C[index].x = x;\n        C[index].y = y;\n\n        index++;\n    }\n\n    x = p->x + 0.5;\n    y = p->y + 0.5;\n\n    segLen = 0;\n\n    // negative calculations\n    for (s = 0; s < sys->len; s++) {\n        if (x < 0)\n            x = 0;\n        if (y < 0)\n            y = 0;\n\n        if (x > sys->NGrid)\n            x = sys->NGrid - 1;\n        if (y > sys->NGrid)\n            y = sys->NGrid - 1;\n\n        vctr_x = vect_x[(int) x][(int) y];\n        vctr_y = vect_y[(int) x][(int) y];\n\n        segLen += 0.1;\n\n        x = x - segLen * vctr_x;\n        y = y - segLen * vctr_y;\n\n        C[index].x = x;\n        C[index].y = y;\n\n        index++;\n    }\n}\n\nvoid lic(System *sys, Grid *grid) {\n    grid->ix.reshape(sys->NGrid, sys->NGrid);\n    grid->iy.reshape(sys->NGrid, sys->NGrid);\n    grid->iz.reshape(sys->NGrid, sys->NGrid);\n\n    sys->len = 20;\n\n    std::cout << \"\\n--- LIC algorithm started ---\" << std::endl;\n\n    clock_t begin, end;\n    double time_spent;\n\n    begin = clock();\n\n    Node *p = (Node *) calloc(1, sizeof(Node));\n    Node *C = (Node *) calloc(2 * sys->len, sizeof(Node));\n\n    double *pNoise = (double *) malloc(sizeof(double) * sys->NGrid * sys->NGrid);\n    double *pNoise_double = (double *) malloc(sizeof(double) * sys->NGrid * sys->NGrid);\n\n    double **vect_x = (double **) calloc(sys->NGrid, sizeof(double *));\n    double **vect_y = (double **) calloc(sys->NGrid, sizeof(double *));\n\n    for (int i = 0; i < sys->NGrid; i++)\n        vect_x[i] = (double *) calloc(sys->NGrid, sizeof(double));\n    for (int i = 0; i < sys->NGrid; i++)\n        vect_y[i] = (double *) calloc(sys->NGrid, sizeof(double));\n\n    synthesize_vectors(sys, grid, vect_x, vect_y);\n    normalize_vectors(sys, vect_x, vect_y);\n    white_noise(sys, pNoise);\n\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            p->x = j;\n            p->y = i;\n\n            compute_integral_curve(sys, p, C, vect_x, vect_y);\n            double sum = compute_convolution_normal(sys, pNoise, C);\n\n            if (sum < 100)\n                sum = 0;\n            if (sum > 150)\n                sum = 255;\n\n            pNoise_double[j * sys->NGrid + i] = sum;\n        }\n    }\n\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            p->x = j;\n            p->y = i;\n\n            compute_integral_curve(sys, p, C, vect_x, vect_y);\n            double sum = compute_convolution_high(sys, pNoise_double, C);\n\n            if (sum < 0)\n                sum = 0;\n            if (sum > 255)\n                sum = 255;\n\n            grid->ix(j,i) = sum;\n        }\n    }\n\n    arma::mat magVect(sys->NGrid, sys->NGrid);\n\n    for (int j = 0; j < sys->NGrid; j++) {\n        for (int i = 0; i < sys->NGrid; i++) {\n            double mag_x = grid->Hx(j,i) * grid->Hx(j,i);\n            double mag_y = grid->Hy(j,i) * grid->Hy(j,i);\n            double mag_z = grid->Hz(j,i) * grid->Hz(j,i);\n            \n            double mag = sqrtf(mag_x + mag_y + mag_z);\n\n            if (mag > 0)\n                magVect(j,i) = mag;\n        }\n    }\n\n    for (int j = 0; j < sys->NGrid; j++)\n        for (int i = 0; i < sys->NGrid; i++)\n            grid->iy(j,i) = magVect(j,i);\n\n    end = clock();\n    time_spent = (double) (end - begin) / CLOCKS_PER_SEC;\n\n    printf(\"LIC End\\n\");\n    printf(\"Time Spend: %lf\\n\", time_spent);\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "58f555ed05a6cb6a088a791bcbcd5b13fd13c733", "size": 7056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lic.cpp", "max_stars_repo_name": "rubenvanstaden/Magix", "max_stars_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lic.cpp", "max_issues_repo_name": "rubenvanstaden/Magix", "max_issues_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lic.cpp", "max_forks_repo_name": "rubenvanstaden/Magix", "max_forks_repo_head_hexsha": "0b45955d98a57b15b021e3d2e99698972f874a2d", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5, "max_line_length": 94, "alphanum_fraction": 0.4472789116, "num_tokens": 2347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5785716968715265}}
{"text": "/*\nThe MIT License\n\nCopyright (c) 2015-2017 Albert Murienne\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n#include \"edge_detect.h\"\n\n#include <boost/type_traits/is_same.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\n#include <iostream>\n\nusing namespace cimg_library;\n\nextern \"C\" {\n\t#include \"ccv.h\"\n}\n\n////////////////////////////////////// SOBEL CCV /////////////////////////////////////////////////\n\ntemplate<> void sobel_ccv::process<unsigned char>( const CImg<unsigned char>& image_in, CImg<unsigned char>& image_out )\n{\n\tccv_dense_matrix_t* ccv_image_in =\n\t\tccv_dense_matrix_new( image_in.height(), image_in.width(), CCV_8U | CCV_C1 | CCV_NO_DATA_ALLOC, (void*)image_in.data(), 0);\n\tccv_image_in->step = image_in.width() * sizeof(unsigned char);\n\n\tccv_dense_matrix_t* ccv_image_out =\n\t\tccv_dense_matrix_new( image_out.height(), image_out.width(), CCV_8U | CCV_C1 | CCV_NO_DATA_ALLOC, (void*)image_out.data(), 0);\n\tccv_image_out->step = image_out.width() * sizeof(unsigned char);\n\n\tccv_sobel( ccv_image_in, &ccv_image_out, CCV_8U, 0, 1 );\n\n\t//CImg<float> test( ccv_image_out->data.f32, 50, 50, 1, 1 );\n\t//test.display();\n}\n\n////////////////////////////////////// CANNY CCV /////////////////////////////////////////////////\n\ntemplate<> void canny_ccv::process<unsigned char>( const CImg<unsigned char>& image_in, CImg<unsigned char>& image_out )\n{\n\t// http://www.kerrywong.com/2009/05/07/canny-edge-detection-auto-thresholding/\n\tunsigned char mean = image_in.mean();\n\tunsigned char low_thresh = 0.66 * mean;\n\tunsigned char high_thresh = 1.33 * mean;\n\n\tccv_dense_matrix_t* ccv_image_in =\n\t\tccv_dense_matrix_new( image_in.height(), image_in.width(), CCV_8U | CCV_C1 | CCV_NO_DATA_ALLOC, (void*)image_in.data(), 0);\n\tccv_image_in->step = image_in.width() * sizeof(unsigned char);\n\n\tccv_dense_matrix_t* ccv_image_out =\n\t\tccv_dense_matrix_new( image_out.height(), image_out.width(), CCV_8U | CCV_C1 | CCV_NO_DATA_ALLOC, (void*)image_out.data(), 0);\n\tccv_image_out->step = image_out.width() * sizeof(unsigned char);\n\n\tccv_canny( ccv_image_in, &ccv_image_out, CCV_8U, 1, low_thresh, high_thresh );\n}\n\n////////////////////////////////////// SOBEL /////////////////////////////////////////////////\n\n// use with normalized [0,1] floating point images\ntemplate<typename T>\nvoid sobel::process( const CImg<T>& image_in, CImg<T>& image_out )\n{\n\t//static_assert( boost::is_same<T,float>::value || boost::is_same<T,double>::value,\n\t//\t\"Template type should be floating point type!\" );\n\n\tT upper_bound = 1;\n\tT lower_bound = 0;\n\tT sum;\n\tT sumX, sumY;\n\n\tT GX[3][3];\n\tT GY[3][3];\n\n\t//Sobel Matrices Horizontal\n\tGX[0][0] = 1; GX[0][1] = 0; GX[0][2] = -1;\n\tGX[1][0] = 2; GX[1][1] = 0; GX[1][2] = -2;\n\tGX[2][0] = 1; GX[2][1] = 0; GX[2][2] = -1;\n\n\t//Sobel Matrices Vertical\n\tGY[0][0] =  1; GY[0][1] =\t 2; GY[0][2] =   1;\n\tGY[1][0] =  0; GY[1][1] =\t 0; GY[1][2] =   0;\n\tGY[2][0] = -1; GY[2][1] =\t-2;\tGY[2][2] =  -1;\n\n\t/*Edge detection using Sobel Algorithm*/\n\n\tfor( int y = 0; y < image_in.height() ; y++)\n\t{\n\t\tfor( int x = 0; x < image_in.width() ; x++)\n\t\t{\n\t\t\tsumX\t= 0;\n\t\t\tsumY\t= 0;\n\n\t\t\t/*Image Boundaries*/\n\t\t\tif( y == 0 || y == image_in.height() - 1 )\n\t\t\t\tsum = 0;\n\t\t\telse if( x == 0 || x == image_in.width() - 1 )\n\t\t\t\tsum = 0;\n\t\t\telse\n\t\t\t{\n\t\t\t\t/*Convolution for X*/\n\t\t\t\tfor( int i = -1; i < 2; i++ )\n\t\t\t\t{\n\t\t\t\t\tfor( int j = -1; j < 2; j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tsumX = sumX + GX[j+1][i+1] * image_in(x+j,y+i);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*Convolution for Y*/\n\t\t\t\tfor( int i = -1; i < 2; i++ )\n\t\t\t\t{\n\t\t\t\t\tfor( int j = -1; j < 2; j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tsumY = sumY + GY[j+1][i+1] * image_in(x+j,y+i);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/*Edge strength*/\n\t\t\t\tsum = std::sqrt( boost::math::pow<2>( sumX ) + boost::math::pow<2>( sumY ) );\n\t\t\t}\n\n\t\t\tif(sum > upper_bound) sum = upper_bound;\n\t\t\tif(sum < lower_bound) sum = lower_bound;\n\n\t\t\timage_out(x,y) = sum;//( upper_bound - sum );\n\n\t\t\t//std::cout << \"x \" << x << \" y \" << y << \" SUM \" << image_out(x,y) << std::endl;\n\t\t}\n\t}\n}\n\ntemplate void sobel::process<float>( const CImg<float>& image_in, CImg<float>& image_out );\n\n////////////////////////////////////// CANNY /////////////////////////////////////////////////\n\n#define MAX_SIZE 5\n\n//***************************\n// helper function that returns true if a>b and c\n//***************************\nbool is_first_max( int a, int b, int c )\n{\n\treturn ( a>b && a>c );\n}\n\n//***************************\n// convolve is a general helper funciton that applies a convolution\n// to the image and then returns the weighted sum so that\n// it can replace whatever pixel we were just analyzing\n//**************************\ntemplate<typename T,const int dim>\nT convolve( const CImg<T>& image_in, T con[][MAX_SIZE], T divisor, int i, int j )\n{\n    int midx = dim/2;\n    int midy = dim/2;\n\n\tT weighted_sum = 0;\n\tfor( int x = i-midx; x < i + dim-midx; x++ )\n\t{\n\t\tfor( int y = j-midy; y < j + dim-midy; y++ )\n\t\t{\n\t\t\tweighted_sum += divisor * con[x-i+midx][y-j+midy] * image_in(x,y);\n\t\t}\n\t}\n\treturn weighted_sum;\n}\n\n//*****************************\n//helper function that says whether arg is between a-b or c-d\n//*****************************\nbool is_between( float arg, float a, float b, float c, float d )\n{\n\treturn ( ( arg >= a && arg <= b ) || ( arg >= c && arg <= d ) );\n}\n\n//****************************\n// buckets the thetas into 0, 45, 90, 135\n//****************************\nint get_orientation( float angle )\n{\n\tif( is_between( angle, -22.5, 22.5, -180, -157.5 ) || is_between( angle, 157.5, 180, -22.5, 0 ) )\n\t\treturn 0;\n\tif( is_between( angle, 22.5, 67.5, -157.5, -112.5 ) )\n\t\treturn 45;\n\tif( is_between( angle, 67.5, 112.5, -112.5, -67.5) )\n\t\treturn 90;\n\tif( is_between( angle, 112.5, 157.5, -67.5, -22.5  ) )\n\t\treturn 135;\n\n\treturn -1;\n}\n\ntemplate<typename T>\ncanny<T>::canny( const int& columns, const int& rows )\n\t: m_rows( rows ), m_columns( columns ),\n\tm_low_thresh( 0 ), m_high_thresh( 0 ),\n\tm_thetas( boost::extents[columns][rows] ), m_mag_array( boost::extents[columns][rows] )\n{\n\tstatic_assert( boost::is_same<T,float>::value || boost::is_same<T,double>::value,\n\t\t\"Template type should be floating point type!\" );\n}\n\ntemplate canny<float>::canny( const int& rows, const int& columns );\n\ntemplate<typename T>\ncanny<T>::~canny()\n{\n}\n\ntemplate canny<float>::~canny();\n\n//*****************************\n// gaussian blur\n// applies a gaussian blur via a convolution of a gaussian\n// matrix with sigma = 1.4. hard-coded in.\n// future development could generate the gauss matrix on the fly\n//*****************************\ntemplate<typename T>\nvoid canny<T>::_gaussian_blur( const CImg<T>& image_in, CImg<T>& image_out )\n{\n\t// define gauss matrix\n\tT gauss_array[5][5] = {\t{2, 4, 5, 4, 2},\n\t\t\t\t\t\t\t{4, 9, 12,9, 4},\n\t\t\t\t\t\t\t{5, 12, 15, 12, 5},\n\t\t\t\t\t\t\t{4, 9, 12,9, 4},\n\t\t\t\t\t\t\t{2, 4, 5, 4, 2} };\n\n\tT gauss_divisor = 1.0/159.0;\n\tT sum = 0.0;\n\n\tfor( auto j=2U; j < m_rows-2; j++ )\n\t{\n\t\tfor( auto i=2U; i < m_columns-2; i++ )\n\t\t{\n\t\t\tsum = convolve<T,5>( image_in, gauss_array, gauss_divisor, i, j );\n\t\t\timage_out(i,j) = sum;\n\t\t}\n\t}\n}\n\n//****************************\n// Applies a sobel filter to find the gradient direction\n// and magnitude. those values are then stored in thetas and magArray\n// so that info can be used later for further analysis\n//****************************\ntemplate<typename T>\nvoid canny<T>::_sobel( CImg<T>& image )\n{\n\tT G_x, G_y, G;\n\tT sobel_y[5][5] = {\t{-1, 0, 1,0,0},\n\t\t\t\t\t\t{-2, 0, 2,0,0},\n\t\t\t\t\t\t{-1, 0, 1,0,0},\n\t\t\t\t\t\t{0, 0, 0, 0, 0},\n\t\t\t\t\t\t{0, 0, 0, 0, 0} };\n\n\tT sobel_x[5][5] = {\t{1, 2, 1, 0, 0},\n\t\t\t\t\t\t{0, 0, 0, 0, 0},\n\t\t\t\t\t\t{-1, -2, -1, 0, 0},\n\t\t\t\t\t\t{0, 0, 0, 0, 0},\n\t\t\t\t\t\t{0, 0, 0, 0, 0} };\n\n\tfor ( auto j = 1U; j < m_rows-1; j++ )\n\t{\n\t\tfor ( auto i = 1U; i < m_columns-1; i++ )\n\t\t{\n\t\t\tG_x = convolve<T,3>( image, sobel_x, 1, i, j );\n\t\t\tG_y = convolve<T,3>( image, sobel_y, 1, i, j );\n\t\t\tG = std::sqrt( G_x*G_x + G_y*G_y );\n\n\t\t\tm_thetas[i][j] = get_orientation( 180.0 * std::atan2( G_y, G_x ) / cimg::PI );\n\n\t\t\tm_mag_array[i][j] = G;\n\t\t}\n\t}\n}\n\n//*****************************\n//non-maximum suppression\n//depending on the orientation, pixels are either thrown away or accepted\n//by checking it's neighbors\n//*****************************\ntemplate<typename T>\nvoid canny<T>::_no_max( CImg<T>& image )\n{\n\tfor( auto j=1U ; j < m_rows-1 ; j++ )\n\t{\n\t    for( auto i=1U ; i < m_columns-1 ; i++ )\n\t\t{\n\t\t\t \t//std::cout << m_thetas[i][j] << std::endl;\n\n\t\t\t\tswitch( m_thetas[i][j] )\n\t\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t\tif( is_first_max( m_mag_array[i][j], m_mag_array[i+1][j], m_mag_array[i-1][j] ) )\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 1; // white\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 0; // black\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 45:\n\t\t\t\t\tif( is_first_max( m_mag_array[i][j], m_mag_array[i+1][j+1], m_mag_array[i-1][j-1] ) )\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 1; // white\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 0; // black\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 90:\n\t\t\t\t\tif( is_first_max( m_mag_array[i][j], m_mag_array[i][j+1], m_mag_array[i][j-1] ) )\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 1; // white\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 0; // black\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tcase 135:\n\t\t\t\t\tif( is_first_max( m_mag_array[i][j], m_mag_array[i+1][j-1], m_mag_array[i-1][j+1] ) )\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 1; // white\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\timage(i,j) = 0; // black\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n//*******************************\n//hysteresis noise filter makes lines continuous and filters out the noise\n// see the pdf that we used to understand this step in english (Step 5)\n//*******************************\ntemplate<typename T>\nvoid canny<T>::_hysteresis( CImg<T>& image )\n{\n\tbool greater_found;\n\tbool between_found;\n\n\tfor( auto j=2U ; j < m_rows-2 ; j++ )\n\t{\n\t\tfor( auto i=2U ; i < m_columns-2 ; i++ )\n\t\t{\n\t\t\tif( m_mag_array[i][j] < m_low_thresh )\n\t\t\t{\n\t\t\t\timage(i,j) = 0; // black\n\t\t\t}\n\n\t\t\tif( m_mag_array[i][j] > m_high_thresh )\n\t\t\t{\n\t\t\t\timage(i,j) = 1; // white\n\t\t\t}\n\n\t\t\t/*If pixel (x, y) has gradient magnitude between tlow and thigh and\n\t\t\tany of its neighbors in a 3 × 3 region around\n\t\t\tit have gradient magnitudes greater than thigh, keep the edge*/\n\n\t\t\tif( m_mag_array[i][j] >= m_low_thresh && m_mag_array[i][j] <= m_high_thresh)\n\t\t\t{\n\t\t\t\tgreater_found = false;\n\t\t\t\tbetween_found = false;\n\t\t\t\tfor( int m = -1; m < 2; m++ )\n\t\t\t\t{\n\t\t\t\t\tfor( int n = -1; n < 2; n++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tif( m_mag_array[i+m][j+n] > m_high_thresh )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\timage(i,j) = 0;\n\t\t\t\t\t\t\tgreater_found = true;\n\t\t\t\t \t\t}\n\t\t\t\t \t\tif( m_mag_array[i][j] > m_low_thresh && m_mag_array[i][j] < m_high_thresh )\n\t\t\t\t\t\t\tbetween_found = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif( !greater_found && between_found )\n\t\t\t\t{\n\t\t\t\t\tfor( int m = -2; m < 3; m++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tfor( int n = -2; n < 3; n++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif( m_mag_array[i+m][j+n] > m_high_thresh )\n\t\t\t\t\t\t\t\tgreater_found = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif( greater_found )\n\t\t\t\t\timage(i,j) = 0;\n\t\t\t\telse\n\t\t\t\t\timage(i,j) = 1;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*If pixel (x, y) has gradient magnitude between tlow and thigh and any of its neighbors in a 3 × 3 region around\nit have gradient magnitudes greater than thigh, keep the edge (write out white).\nIf none of pixel (x, y)s neighbors have high gradient magnitudes but at least one falls between tlow and thigh,\nsearch the 5 × 5 region to see if any of these pixels have a magnitude greater than thigh. If so, keep the edge\n(write out white).\n*/\n\ntemplate<typename T>\nvoid canny<T>::process( const CImg<T>& image_in, CImg<T>& image_out )\n{\n\t// http://www.kerrywong.com/2009/05/07/canny-edge-detection-auto-thresholding/\n\tT mean = image_in.mean();\n\tm_low_thresh = 0.66 * mean;\n\tm_high_thresh = 1.33 * mean;\n\n\t_gaussian_blur( image_in, image_out );\n\t_sobel( image_out );\n\t_no_max( image_out );\n\t_hysteresis( image_out );\n\n\t// 2px border not managed for now\n\tcimg_for_borderXY( image_out, x, y, 3 ) { image_out( x, y ) = 0; }\n}\n\ntemplate void canny<float>::process( const CImg<float>& image_in, CImg<float>& image_out );\n", "meta": {"hexsha": "a430e90606fcd153404522bcb8f77ee6a975926c", "size": 12793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/imagetools/edge_detect.cpp", "max_stars_repo_name": "blackccpie/neurocl", "max_stars_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-01T22:19:04.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T19:06:24.000Z", "max_issues_repo_path": "utils/imagetools/edge_detect.cpp", "max_issues_repo_name": "blackccpie/neurocl", "max_issues_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/imagetools/edge_detect.cpp", "max_forks_repo_name": "blackccpie/neurocl", "max_forks_repo_head_hexsha": "cfbb1978ba92d5085796330846d997944f604c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-19T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T08:17:54.000Z", "avg_line_length": 28.1164835165, "max_line_length": 128, "alphanum_fraction": 0.5752364574, "num_tokens": 4182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.57848655992848}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2014 Erik Erlandson\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/units/systems/information.hpp>\n\n/** \n\\file\n\n\\brief information.cpp\n\n\\details\nDemonstrate information unit system.\n\nOutput:\n@verbatim\nbytes= 1.25e+08 B\nbits= 8e+06 b\nnats= 4605.17 nat\n1024 bytes in a kibi-byte\n8.38861e+06 bits in a mebi-byte\n0.000434294 hartleys in a milli-nat\nentropy in bits= 1 b\nentropy in nats= 0.693147 nat\nentropy in hartleys= 0.30103 Hart\nentropy in shannons= 1 Sh\nentropy in bytes= 0.125 B\n@endverbatim\n**/\n\n#include <cmath>\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <boost/units/quantity.hpp>\n#include <boost/units/io.hpp>\n#include <boost/units/conversion.hpp>\nnamespace bu = boost::units;\nusing bu::quantity;\nusing bu::conversion_factor;\n\n// SI prefixes\n#include <boost/units/systems/si/prefixes.hpp>\nnamespace si = boost::units::si;\n\n// information unit system\n#include <boost/units/systems/information.hpp>\nusing namespace bu::information;\n\n// Define a function for the entropy of a bernoulli trial.\n// The formula is computed using natural log, so the units are in nats.\n// The user provides the desired return unit, the only restriction being that it\n// must be a unit of information.  Conversion to the requested return unit is \n// accomplished automatically by the boost::units library.\ntemplate <typename Sys>\nquantity<bu::unit<bu::information_dimension, Sys> > \nbernoulli_entropy(double p, const bu::unit<bu::information_dimension, Sys>&) {\n    typedef bu::unit<bu::information_dimension, Sys> requested_unit;\n    return quantity<requested_unit>((-(p*log(p) + (1-p)*log(1-p)))*nats);\n}\n\nint main(int argc, char** argv) {\n    // a quantity of information (default in units of bytes) \n    quantity<info> nbytes(1 * si::giga * bit);\n    cout << \"bytes= \" << nbytes << endl;\n\n    // a quantity of information, stored as bits\n    quantity<hu::bit::info> nbits(1 * si::mega * byte);\n    cout << \"bits= \" << nbits << endl;\n\n    // a quantity of information, stored as nats\n    quantity<hu::nat::info> nnats(2 * si::kilo * hartleys);\n    cout << \"nats= \" << nnats << endl;\n\n    // how many bytes are in a kibi-byte?\n    cout << conversion_factor(kibi * byte, byte) << \" bytes in a kibi-byte\" << endl;\n\n    // how many bits are in a mebi-byte?\n    cout << conversion_factor(mebi * byte, bit) << \" bits in a mebi-byte\" << endl;\n\n    // how many hartleys are in a milli-nat?\n    cout << conversion_factor(si::milli * nat, hartley) << \" hartleys in a milli-nat\" << endl;\n\n    // compute the entropy of a fair coin flip, in various units of information:\n    cout << \"entropy in bits= \" << bernoulli_entropy(0.5, bits) << endl;\n    cout << \"entropy in nats= \" << bernoulli_entropy(0.5, nats) << endl;\n    cout << \"entropy in hartleys= \" << bernoulli_entropy(0.5, hartleys) << endl;\n    cout << \"entropy in shannons= \" << bernoulli_entropy(0.5, shannons) << endl;\n    cout << \"entropy in bytes= \" << bernoulli_entropy(0.5, bytes) << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0efc01a1747b09c4ce0461fc1f54cd59e2962a79", "size": 3235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/units/example/information.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "libs/units/example/information.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "libs/units/example/information.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 32.6767676768, "max_line_length": 94, "alphanum_fraction": 0.6927357032, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.5784865597323096}}
{"text": "// example_policy_handling.cpp\n\n// Copyright Paul A. Bristow 2007, 2010.\n// Copyright John Maddock 2007.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// See error_handling_example.cpp for use of\n// macro definition to change policy for\n// domain_error - negative degrees of freedom argument\n// for student's t distribution CDF,\n// and catching the exception.\n\n// See error_handling_policies.cpp for more examples.\n\n// Boost\n#include <boost/math/distributions/students_t.hpp>\nusing boost::math::students_t_distribution;  // Probability of students_t(df, t).\nusing boost::math::students_t;  // Probability of students_t(df, t) convenience typedef for double.\n\nusing boost::math::policies::policy;\nusing boost::math::policies::domain_error;\nusing boost::math::policies::ignore_error;\n\n// std\n#include <iostream>\n   using std::cout;\n   using std::endl;\n\n#include <stdexcept>\n\n\n// Define a (bad?) policy to ignore domain errors ('bad' arguments):\ntypedef policy<\n      domain_error<ignore_error>\n      > my_policy;\n\n// Define my_students_t distribution with this different domain error policy:\ntypedef students_t_distribution<double, my_policy> my_students_t;\n\nint main()\n{  // Example of error handling of bad argument(s) to a distribution.\n  cout << \"Example error handling using Student's t function. \" << endl;\n\n  double degrees_of_freedom = -1; double t = -1.; // Two 'bad' arguments!\n\n  try\n  {\n    cout << \"Probability of ignore_error Student's t is \"\n      << cdf(my_students_t(degrees_of_freedom), t) << endl;\n    cout << \"Probability of default error policy Student's t is \" << endl;\n    // By contrast the students_t distribution default domain error policy is to throw,\n    cout << cdf(students_t(-1), -1) << endl;  // so this will throw.\n/*`\n    Message from thrown exception was:\n   Error in function boost::math::students_t_distribution<double>::students_t_distribution:\n   Degrees of freedom argument is -1, but must be > 0 !\n*/\n\n    // We could also define a 'custom' distribution\n    // with an \"ignore overflow error policy\" in a single statement:\n    using boost::math::policies::overflow_error;\n    students_t_distribution<double, policy<overflow_error<ignore_error> > > students_t_no_throw(-1);\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\n  return 0;\n} // int main()\n\n/*\n\nOutput:\n\n   error_policy_example.cpp\n  Generating code\n  Finished generating code\n  error_policy_example.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\error_policy_example.exe\n  Example error handling using Student's t function.\n  Probability of ignore_error Student's t is 1.#QNAN\n  Probability of default error policy Student's t is\n\n  Message from thrown exception was:\n     Error in function boost::math::students_t_distribution<double>::students_t_distribution: Degrees of freedom argument is -1, but must be > 0 !\n\n*/\n", "meta": {"hexsha": "051d01cb3f75c923e5c25a9dcf5662e98bc92354", "size": 3066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/error_policy_example.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/error_policy_example.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/error_policy_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": 32.6170212766, "max_line_length": 146, "alphanum_fraction": 0.7270058708, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.5784865555069844}}
{"text": "#include <iostream>\n#include <cmath>\n#include <chrono>\n#include <cassert>\n#include <vector>\n#include <NTL/ZZ.h>\n#include <NTL/vector.h>\n#include \"Element.hpp\"\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace NTL;\n\nvoid test_wilson(int bound);\nvoid test_wolstenholme(int bound);\nvoid test_kurepa(int bound);\n\ntemplate<typename T, typename M>\nvoid remainder_tree(vector<Elt<T>> &C, vector<Elt<T>> &A, vector<Elt<T>> &m, Elt<T> &AProd, Elt<M> &mProd, Elt<T> const &root_value = Elt<T>(1), int start = 0, int end = -1);\n// void remainder_tree_v1(vector<Elt<T>> &C, vector<Elt<T>> &A, vector<Elt<M>> &m, Elt<T> const &root_value = Elt<T>(1), const int k = 2);\ntemplate<typename T, typename M>\nElt<T> get_node(int index, vector<Elt<T>> &base, Elt<M> const &mod = Elt<M>(0));\ntemplate<typename T, typename M>\nvoid remainder_tree_v2(vector<Elt<T>> &C, vector<Elt<T>> &A, vector<Elt<M>> &m, Elt<T> const &root_value = Elt<T>(1), const int k = 2);\ntemplate<typename T>\nvoid print_tree(vector<Elt<T>> tree);\nvoid complexity_graph(int N, int d);\n\n/* Tags:\n *\n * //DEBUG// for debug statements\n * Optimization idea for optimizations that havent been impemented yet\n * TODO: add typename specifications to functions when they are called\n * TODO: add .t whenever need to access a value of Elt\n */\n\nint main(){\n\t\n\tcomplexity_graph(1<<24, 10);\n}\n\ntemplate<typename T>\nvoid elt_to_base(vector<T> &b, vector<Elt<T>> &e){\n\tassert(b.size() == e.size());\n\tfor(int i = 0; i < b.size(); i++){\n\t\tb[i] = e[i].t;\n\t}\n}\n\ntemplate<typename T>\nvoid base_to_elt(vector<Elt<T>> &e, vector<T> &b){\n\tassert(e.size() == b.size());\n\tfor(int i = 0; i < e.size(); i++){\n\t\te[i] = b[i];\n\t}\n}\n\n// Test for Wilson Primes\nvoid test_wilson(int bound){\n\n\tvector<ZZ> A;\n\tA.resize(bound);\n\tvector<ZZ> m;\n\tm.resize(bound);\n\n\tvector<Elt<ZZ>> A_elt;\n\tA_elt.resize(bound);\n\tvector<Elt<ZZ>> m_elt;\n\tm_elt.resize(bound);\n\n\tbase_to_elt(A_elt, A);\n\tbase_to_elt(m_elt, m);\n\t\n\n\t// make sure implicit ints don't overflow\t\n\tfor(int i = 1; i <= bound; i++){\n\t\tA[i-1] = ZZ(i);\n\t\tm[i-1] = ProbPrime(ZZ(i)) ? ZZ(i)*ZZ(i) : ZZ(1);\n\t}\n\t\n\t/*\t\n\tfor(int i = 0; i < A.size(); i++){\n\t\tcout << A[i] << \" \";\n\t}\n\tcout << endl;\n\n\tfor(int i = 0; i < m.size(); i++){\n\t\tcout << m[i] << \" \";\n\t}\n\tcout << endl;\n\t*/\n\n\tvector<ZZ> C;\n\tC.resize(bound);\n\tvector<Elt<ZZ>> C_elt;\n\tC_elt.resize(bound);\n\n\tbase_to_elt(C_elt, C);\n\n\tremainder_tree_v2<ZZ, ZZ>(C_elt, A_elt, m_elt, ZZ(1), 4);\n\t\n\telt_to_base(C, C_elt);\n\n\t/*\t\n\tfor(int i = 0; i < C.size(); i++){\n\t\tcout << (i+1) << \": \" << C[i] << endl;\n\t}\n\tcout << endl;\n\t*/\n}\n\n// Test for Wolstenholme Primes\nvoid test_wolstenholme(int bound){\n\t\n\tvector<ZZ> Anum; \n\tAnum.resize(bound);\n\tvector<ZZ> m;\n\tm.resize(bound);\n\n\tvector<Elt<ZZ>> Anum_elt; \n\tAnum_elt.resize(bound);\n\tvector<Elt<ZZ>> m_elt;\n\tm_elt.resize(bound);\n\n\t\n\tfor(int i = 1; i <= bound; i++){\n\t\tAnum[i-1] = 4*i+2;\n\t\tm[i-1] = ProbPrime(ZZ(i)) ? ZZ(i)*ZZ(i)*ZZ(i)*ZZ(i)*ZZ(i) : ZZ(1);\n\n\t}\t\t\n\n\tbase_to_elt(Anum_elt, Anum);\n\tbase_to_elt(m_elt, m);\n\n\tvector<ZZ> Cnum;\n\tCnum.resize(bound);\n\tvector<Elt<ZZ>> Cnum_elt;\n\tCnum_elt.resize(bound);\n\n\tremainder_tree_v2<ZZ, ZZ>(Cnum_elt, Anum_elt, m_elt, ZZ(1), 4);\n\n\telt_to_base(Cnum, Cnum_elt);\n\n\tfor(int i = 1; i <= bound; i++){\n\t\tCnum[i-1] /= i; // i = prime at this index\n\t}\n\n\t\n\tvector<ZZ> Adem;\n\tAdem.resize(bound);\n\tvector<Elt<ZZ>> Adem_elt;\n\tAdem_elt.resize(bound);\n\n\tfor(int i = 1; i <= bound; i++){\n\t\tAdem[i-1] = i+1;\n\t}\n\n\tbase_to_elt(Adem_elt, Adem);\n\n\tvector<ZZ> Cdem;\n\tCdem.resize(bound);\n\tvector<Elt<ZZ>> Cdem_elt;\n\tCdem_elt.resize(bound);\n\n\tremainder_tree_v2<ZZ, ZZ>(Cdem_elt, Adem_elt, m_elt, ZZ(1), 4);\n\n\telt_to_base(Cdem, Cdem_elt);\n\n\tfor(int i = 1; i <= bound; i++){\n\t\tCdem[i-1] /= i;\n\t\tZZ d;\n\t\tZZ k;\n\t\tXGCD(d, Cdem[i-1], k, Cdem[i-1], ZZ(i)*ZZ(i)*ZZ(i)*ZZ(i)); // changes Cdem[i-1] to its inverse mod p^4\n\t\tif (Cdem[i-1] < 0) Cdem[i-1] += ZZ(i)*ZZ(i)*ZZ(i)*ZZ(i); // make residue positive\n\n\t\tCnum[i-1] = (Cnum[i-1] * Cdem[i-1]) % (ZZ(i)*ZZ(i)*ZZ(i)*ZZ(i));\n\t}\n\n\tfor(int i = 1; i <= bound; i++){\n\t\tif (Cnum[i-1] == 1){\n\t\t\tcout << i << \": \" << Cnum[i-1] << endl;\n\t\t}\n\t}\n\n}\n\nvoid test_kurepa(int bound){\n\t// need to first implement remainder tree for matrices\n}\n\n/*\n * Original Remainder Tree implementation\n */\n\ntemplate<typename T, typename M>\nvoid remainder_tree(vector<Elt<T>> &C, vector<Elt<T>> &A, vector<Elt<M>> &m, Elt<T> &AProd, Elt<M> &mProd, Elt<T> const &root_value, int start, int end){\n\t\n\t//DEBUG// cout << \"AProd: \" << AProd << endl;\n\t//DEBUG// cout << \"mProd: \" << mProd << endl;\n\t//DEBUG// cout << \"root_value: \" << root_value << endl;\n\t// set default value for end\n\tif (end == -1) end = C.size();\n\n\t// Assert that interval [start, end] exists in C, A and m\n\tassert(end <= C.size());\n\tassert(end <= A.size());\n\tassert(end <= m.size());\n\n\t// Set N = length of interval\n\tint N = end - start;\n\n\t// Change nothing if N = 0\n\tif (N == 0) {\n\t\treturn;\n\t}\n\n\t// Index of leaf at the bottom left\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\n\t// Declare trees (always of length 2N for any N)\n\tvector<Elt<T>> ATree;\n\tATree.resize(2 * N);\n\tvector<Elt<M>> mTree;\n\tmTree.resize(2 * N);\n\tvector<Elt<T>> CTree;\n\tCTree.resize(2 * N);\n\n\t/* \n\t * For example when N=11 the leaves are in this order:\n\t *     / \\       /\\   /\\    /\\\n\t *    /   \\     /  7 8  9 10  11\n\t *   /\\   /\\   /\\\n\t *  1  2 3  4 5  6\n\t *\n\t */\n\n\t// Initialize the leaves in ATree and mTree\n\tfor (int i = leftmost; i < 2 * N; i++) { // leaves on lowest layer\n\t\tATree[i] = A[i - leftmost + start];\n\t\tmTree[i] = m[i - leftmost + start];\n\t}\n\tfor (int i = N; i < leftmost; i++) { // leaves on second lowest layer\n\t\tATree[i] = A[i + N - leftmost + start];\n\t\tmTree[i] = m[i + N - leftmost + start];\n\t}\n\n\t// Calculate the rest of the product tree mTree\n\tfor (int i = N - 1; i > 0; i--) {\n\t\tmTree[i] = mTree[2 * i] * mTree[2 * i + 1]; // parent is product of leaves\n\t}\n\n\n\t// Calculate the rest of the product tree aTree, taking mod mTree[1] = m[0]*...*m[N-1]\n\tfor(int i = N - 1; i > 0; i--) {\n\t\tATree[i] = (ATree[2 * i] * ATree[2 * i + 1]) % mProd; // parent is product of leaves mod mTree[1]\n\t\tATree[2 * i] %= mTree[1];\n\t\tdelete ATree[2 * i + 1];\n\t}\n\n\tmProd /= mTree[1]; // Get rid of this tree's moduli from mProd\n\tAProd = ATree[1]; // Set AProd as the product of A's mod new mProd\n\n\t// Calculate accumulating remainder tree\n\tCTree[1] = root_value % mTree[1];\n\t//DEBUG// cout << \"CTree root: \" << CTree[1] << endl;\n\tfor (int i = 1; i < N; i++) {\n\t\tCTree[2 * i] = CTree[i] % mTree[2 * i]; // Left branch\n\t\tCTree[2 * i + 1] = (CTree[i] * ATree[2 * i]) % mTree[2 * i + 1]; // Right branch\n\t\tdelete CTree[i];\n\t}\n\n\t//DEBUG// print_tree<ZZ>(ATree);\n\t//DEBUG// print_tree<ZZ>(mTree);\n\t//DEBUG// print_tree<ZZ>(CTree);\n\t\n\tfor (int i = leftmost; i < 2 * N; i++) {\n\t\tC[i - leftmost + start] = CTree[i];\n\t}\n\tfor (int i = N; i < leftmost; i++) {\n\t\tC[i + N - leftmost + start] = CTree[i];\n\t}\n\n\treturn;\n}\n\n/*\n * Implements Sutherland's optimization\n * Doesn't do intervals yet\n * k = layer where we divide into subtrees\n */\ntemplate<typename T, typename M>\nvoid remainder_tree_v2(vector<Elt<T>> &C, vector<Elt<T>> &A, vector<Elt<M>> &m, Elt<T> const &root_value, const int k){\n\n\t// Assert that lengths of A and m match\n\tassert(C.size() == A.size());\n\tassert(C.size() == m.size());\n\n\t// Set N = length of input arrays\n\tint N = C.size();\n\n\t// Change nothing if N = 0\n\tif (N == 0) {\n\t\treturn;\n\t}\n\n\t// Ensure that there are at least k layers\n\tassert(N >= (1<<k));\n\n\n\t// Index of leaf at the bottom left\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\n\t// Declare Ctree (always of length 2N for any N)\n\tvector<Elt<T>> CTree;\n\tCTree.resize(2 * N);\n\n\t/* \n\t * For example when N=11 the leaves are in this order:\n\t *     / \\       /\\   /\\    /\\\n\t *    /   \\     /  7 8  9 10  11\n\t *   /\\   /\\   /\\\n\t *  1  2 3  4 5  6\n\t *\n\t */\n\n\t// Calculate the product of all the mods to keep A's small\n\t// Elt<M> mProd = get_node<ZZ, ZZ>(1, m, Elt<M>(0));\n\n\tuint64_t start2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\n\t// Step 2: Calculate the subproduct trees\n\t// Roots are CTree[2^k + i]: {CTree[2^k], ..., CTree[2^(k+1)-1]}\n\n\t// First find index of root in subtree with leaves in both layers\n\tint notfirstk = ((int)log2(2*N-1) - k); // (#bits in 2*N-1) minus k\n\tint special = (2*N-1 - leftmost) >> notfirstk; // firstk digits excluding the most significant digit\n\n\tElt<T> AProd = Elt<T>(1);\n\tElt<M> mProd = get_node<ZZ, ZZ>(1, m, Elt<M>(0));\t\n\tCTree[1<<k] = root_value % mProd;\n\t// Subtrees with leaves in first layer\n\tfor(int i = 0; i < special; i++) {\n\t\t// Number of leaves: 2^notfirstk = leftmost/2^k\n\t\t//DEBUG// cout << \"Calculating interval: [\" << (i<<notfirstk) << \", \" << ((i+1)<<notfirstk) << \"]\" << endl; \n\t\tremainder_tree<ZZ, ZZ>(C, A, m, AProd, mProd, CTree[(1<<k) + i], i<<notfirstk, (i+1)<<notfirstk);\n\t\tCTree[(1<<k) + i+1] = (CTree[(1<<k) + i] * AProd) % mProd;\n\t}\n\n\t// Subtree with leaves in both layers\n\t// First, calculate number of leaves in this subtree, stored in specialleaves\n\tint notfirstkdigits = (2*N-1) % (1<<notfirstk);\n\tint onenotfirstkdigits = (1<<notfirstk) + notfirstkdigits;\n\tint specialleaves = (onenotfirstkdigits+1)/2; \n\t//DEBUG// cout << \"Calculating interval: [\" << (special<<notfirstk) << \", \" << ((special<<notfirstk) + specialleaves) << \"]\" << endl;\n\tremainder_tree<ZZ, ZZ>(C, A, m, AProd, mProd, CTree[(1<<k) + special], special<<notfirstk, (special<<notfirstk) + specialleaves);\n\tCTree[(1<<k) + special+1] = (CTree[(1<<k) + special] * AProd) % mProd;\n\n\t// Subtrees with leaves in second layer\n\tfor(int i = special+1; i < 1<<k; i++){\n\t\t//DEBUG// cout << \"Calculating interval: [\" << ((special<<notfirstk) + specialleaves + ((i - special-1)<<(notfirstk-1))) << \", \" << ((special<<notfirstk) + specialleaves + ((i - special)<<(notfirstk-1))) << \"]\" << endl; \n\t\tremainder_tree<ZZ, ZZ>(C, A, m, AProd, mProd, CTree[(1<<k) + i], (special<<notfirstk) + specialleaves + ((i - special-1)<<(notfirstk-1)), (special<<notfirstk) + specialleaves + ((i - special)<<(notfirstk-1)));\n\t\tif (i == (1<<k) - 1) continue; // Prevent index out of range for next operation\n\t\tCTree[(1<<k) + i+1] = (CTree[(1<<k) + i] * AProd) % mProd;\n\t}\n\n\tuint64_t end2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t//DEBUG// cout << \"Time taken for subtree step: \" << (end2-start2) << endl;\n\n\treturn;\n\n}\n\n/*\n * Returns the value of the node on the tree at index k with leaves having value base\n */\ntemplate<typename T, typename M>\nElt<T> get_node(int i, vector<Elt<T>> &base, Elt<M> const &mod) { // Optimization idea: pass in what you're taking a mod of as well so if the modulus ever gets bigger than the value, just return the value\n\tint N = base.size();\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\tif (mod == 0){\n\t\tif (i >= leftmost) return base[i - leftmost];\n\t\telse if (i >= N) return base[i + N - leftmost];\n\t\t\n\t\treturn get_node<ZZ, ZZ>(2*i, base, Elt<M>(0))*get_node<ZZ, ZZ>(2*i+1, base, Elt<M>(0));\n\t}\n\t\n\telse {\n\t\tif (i >= leftmost) return base[i - leftmost] % mod;\n\t\telse if (i >= N) return base[i + N - leftmost] % mod;\n\t\t\n\t\treturn (get_node<ZZ, ZZ>(2*i, base, mod)*get_node<ZZ, ZZ>(2*i+1, base, mod)) % mod;\n\t}\n}\n\n/*\n * Prints a tree given in vector<ZZ> form\n */\ntemplate<typename T>\nvoid print_tree(vector<Elt<T>> tree){\n\tint top = 1;\n\tint counter = 0;\n\tfor(int i = 1; i < tree.size(); i++){\n\t\tcout << tree[i] << \" \";\n\t\tcounter++;\n\t\tif (counter == top){\n\t\t\tcout << endl;\n\t\t\tcounter = 0;\n\t\t\ttop *= 2;\n\t\t}\n\t}\n\tcout << endl;\n}\n\n/*\n * Gives data points on size of input vs. computation time.\n * N = max size of data, d = number of data points\n */\n\nvoid complexity_graph(int N, int d){\n\tvector<int> x;\n\tvector<int> y;\n\tvector<int> z;\n\n\tint interval = N/d;\n\tint B = 0;\n\twhile(B <= N){\n\t\tcout << \"Testing: \" << B << endl;\n\t\t/*\n\t\tint testSize = B;\n\t\tint numSize = B;\n\t\t\n\t\tvector<ZZ> test_A;\n\t\ttest_A.resize(testSize);\n\t\tvector<ZZ> test_m;\n\t\ttest_m.resize(testSize);\n\t\tfor (int i = 0; i < testSize; i++) {\n\t\t\ttest_A[i] = rand() % numSize + 1;\n\t\t\ttest_m[i] = rand() % numSize + 1;\n\t\t}\n\n\t\tvector<ZZ> test_C;\n\t\ttest_C.resize(testSize);\n\t\t*/\n\n\t\tx.push_back(B);\n\t\t\n\t\t\n\t\tuint64_t start;\n\t\tuint64_t end;\n\t\t\n\t\tstart = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\t//remainder_tree<ZZ, ZZ>(test_C, test_A, test_m);\n\t\tend = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\n\t\ty.push_back(end-start);\n\n\n\t\tstart = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\ttest_wilson(B);\n\t\tend = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\t\n\t\tz.push_back(end-start);\n\n\t\tB += interval;\n\t}\n\n\tfor(int i = 0; i < x.size(); i++){\n\t\tcout << x[i] << \", \";\n\t}\n\tcout << endl;\n\tfor(int i = 0; i < y.size(); i++){\n\t\tcout << y[i] << \", \";\n\t}\n\tcout << endl;\n\tfor(int i = 0; i < z.size(); i++){\n\t\tcout << z[i] << \", \";\n\t}\n\tcout << endl;\n\n}\n", "meta": {"hexsha": "104b6758ea44bbfe1fae8562817382365e492478", "size": 12818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/to_incorporate/rem_tree_int_sutherland.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/to_incorporate/rem_tree_int_sutherland.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/to_incorporate/rem_tree_int_sutherland.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": 26.6486486486, "max_line_length": 222, "alphanum_fraction": 0.5987673584, "num_tokens": 4458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279739, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5784409222897289}}
{"text": "// File:  main.cpp\n// Date:  11/17/2019\n// Auth:  K. Loux\n// Desc:  Entry point for SplinePatchToFlatPattern application.\n\n// optimization headers\n#include \"optimization/nelderMead.h\"\n\n// Eigen headers\n#include <Eigen/Eigen>\n#include <Eigen/StdVector>\n\n// Standard C++ headers\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n\ntypedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> Vector2DVectors;\ntypedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> Vector3DVectors;\n\nbool ParseToken(const std::string& token, double& value)\n{\n\tstd::istringstream ss(token);\n\treturn !(ss >> value).fail();\n}\n\nbool ParseLine(const std::string& line, Vector3DVectors& curve1, Vector3DVectors& curve2)\n{\n\tstd::istringstream ss(line);\n\tEigen::Vector3d p1, p2;\n\tstd::string token;\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p1(0)))\n\t\treturn false;\n\t\t\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p1(1)))\n\t\treturn false;\n\tp1(1) = fabs(p1(1));\n\t\t\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p1(2)))\n\t\treturn false;\n\t\t\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p2(0)))\n\t\treturn false;\n\t\t\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p2(1)))\n\t\treturn false;\n\tp2(1) = fabs(p2(1));\n\t\t\n\tif (!std::getline(ss, token, ','))\n\t\treturn false;\n\t\n\tif (!ParseToken(token, p2(2)))\n\t\treturn false;\n\n\tcurve1.push_back(p1);\n\tcurve2.push_back(p2);\n\t\t\n\treturn true;\n}\n\nbool ReadInputFile(const std::string& fileName, Vector3DVectors& curve1, Vector3DVectors& curve2)\n{\n\tstd::ifstream file(fileName);\n\tif (!file.is_open() || !file.good())\n\t{\n\t\tstd::cerr << \"Failed to open '\" << fileName << \"' for input\\n\";\n\t\treturn false;\n\t}\n\t\n\tstd::string line;\n\tunsigned int lineCount(0);\n\twhile (std::getline(file, line))\n\t{\n\t\t++lineCount;\n\t\tif (!ParseLine(line, curve1, curve2))\n\t\t{\n\t\t\tstd::cerr << \"Failed to parse line \" << line << '\\n';\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tauto sortPredicate([](const Eigen::Vector3d&a, const Eigen::Vector3d& b)\n\t{\n\t\treturn a(0) < b(0);\n\t});\n\n\tstd::sort(curve1.begin(), curve1.end(), sortPredicate);\n\tstd::sort(curve2.begin(), curve2.end(), sortPredicate);\n\n\treturn true;\n}\n\nclass Spline\n{\npublic:\n\tvoid AddPoint(const Eigen::Vector3d& p, const Eigen::Vector3d& c)\n\t{\n\t\tintersectionPoints.push_back(p);\n\t\tcontrolVectors.push_back(c);\n\t}\n\n\tvoid SetControlVector(const unsigned int& i, const Eigen::Vector3d& v) { controlVectors[i] = v; }\n\n\tunsigned int GetSegmentCount() const { return intersectionPoints.size() - 1; }\n\tEigen::Vector3d GetIntersectionPoint(const unsigned int& i) const { return intersectionPoints[i]; }\n\tEigen::Vector3d GetControlVector(const unsigned int& i) const { return controlVectors[i]; }\n\n\tconst Vector3DVectors& GetIntersectionPoints() const { return intersectionPoints; }\n\tconst Vector3DVectors& GetControlVectors() const { return controlVectors; }\n\t\nprivate:\n\tVector3DVectors intersectionPoints;\n\tVector3DVectors controlVectors;\n};\n\nVector3DVectors ComputeSpline(const Spline& s, const unsigned int& segmentResolution)\n{\n\tconst auto segments(s.GetSegmentCount());\n\tVector3DVectors points(segments * segmentResolution);\n\tfor (unsigned int i = 0; i < segments; ++i)\n\t{\n\t\tdouble t(0.0);\n\t\tconst double tStep(1.0 / segmentResolution);\n\t\tfor (unsigned int j = 0; j < segmentResolution; ++j)\n\t\t{\n\t\t\tconst Eigen::Vector3d p0(s.GetIntersectionPoint(i));\n\t\t\tconst Eigen::Vector3d p1(s.GetIntersectionPoint(i) - s.GetControlVector(i));\n\t\t\tconst Eigen::Vector3d p2(s.GetIntersectionPoint(i + 1) + s.GetControlVector(i + 1));\n\t\t\tconst Eigen::Vector3d p3(s.GetIntersectionPoint(i + 1));\n\n\t\t\tpoints[i * segmentResolution + j] = pow(1.0 - t, 3) * p0 + 3.0 * pow(1.0 - t, 2) * t * p1 + 3.0 * (1. - t) * t * t * p2 + pow(t, 3) * p3;\n\t\t\tt += tStep;\n\t\t}\n\t}\n\n\treturn points;\n}\n\ndouble ComputeError(const Spline& s, const Vector3DVectors& goalPoints)\n{\n\tconst unsigned int resolution(1000);\n\tconst auto sPoints(ComputeSpline(s, resolution));\n\tdouble e(0.0);\n\tfor (const auto& p : sPoints)\n\t{\n\t\tdouble minDistance(std::numeric_limits<double>::max());\n\t\tfor (const auto& v : goalPoints)\n\t\t{\n\t\t\tconst auto distance((p - v).norm());\n\t\t\tif (distance < minDistance)\n\t\t\t\tminDistance = distance;\n\t\t}\n\t\te += minDistance;\n\t}\n\n\treturn e;\n}\n\nVector3DVectors BuildControlVectors(Eigen::VectorXd x, const Eigen::VectorXd* initialGuess = nullptr)\n{\n\tVector3DVectors controlVectors;\n\tcontrolVectors.push_back(Eigen::Vector3d(0.0, -fabs(x(0)), 0.0));\n\n\tif (initialGuess)\n\t{\n\t\tfor (int i = 1; i < x.size() - 1; ++i)\n\t\t{\n\t\t\tif (x(i) * (*initialGuess)(i) < 0.0)\n\t\t\t\tx(i) *= -1.0;\n\t\t}\n\t}\n\n\tfor (int i = 1; i < x.size() - 1; i += 3)\n\t\tcontrolVectors.push_back(Eigen::Vector3d(x(i), x(i + 1), x(i + 2)));\n\n\tcontrolVectors.push_back(Eigen::Vector3d(0.0, fabs(x(x.size() - 1)), 0.0));\n\n\treturn controlVectors;\n}\n\nstruct SplineFitArgs : public Optimizer::AdditionalArgs\n{\n\tSplineFitArgs(const Vector3DVectors& goalPoints,\n\t\tconst Vector3DVectors& intersectionPoints, const Eigen::VectorXd& initialGuess)\n\t\t: goalPoints(goalPoints), intersectionPoints(intersectionPoints), initialGuess(initialGuess) {}\n\n\tconst Vector3DVectors& goalPoints;\n\tconst Vector3DVectors& intersectionPoints;\n\tconst Eigen::VectorXd initialGuess;\n};\n\nEigen::VectorXd DoIteration(const Eigen::VectorXd& guess, const Optimizer::AdditionalArgs* args)\n{\n\tconst auto& arguments(*dynamic_cast<const SplineFitArgs*>(args));\n\tconst auto controlVectors(BuildControlVectors(guess, &arguments.initialGuess));\n\tSpline s;\n\tfor (unsigned int i = 0; i < controlVectors.size(); ++i)\n\t\ts.AddPoint(arguments.intersectionPoints[i], controlVectors[i]);\n\n\treturn Eigen::VectorXd(guess.size()).setOnes() * ComputeError(s, arguments.goalPoints);// TODO:  Is this correct?  Can we return 1x1?\n}\n\nvoid FitSplineToPoints(const Vector3DVectors& points, Spline& spline)\n{\n\tconstexpr unsigned int splineSegmentCount(3);// Assume that we'll get a good fit if we choose three segments.\n\tassert(points.size() > splineSegmentCount);\n\tEigen::VectorXd initialGuess((splineSegmentCount - 1) * 3 + 2, 1);\n\tinitialGuess.setOnes();\n\t\n\tspline.AddPoint(points.front(), Eigen::Vector3d(0.0, -1.0, 0.0));\n\n\tconst unsigned int i1(points.size() / splineSegmentCount);\n\tfor (unsigned int a = 1; a < splineSegmentCount; ++a)\n\t{\n\t\tconst double signAdjust(1.0);\n\t\tspline.AddPoint(points[i1 * a], (points[i1 * a - 1] - points[i1 * a + 1]) * signAdjust);\n\t\tinitialGuess((a - 1) * 3 + 1) = spline.GetControlVector(a)(0);\n\t\tinitialGuess((a - 1) * 3 + 2) = spline.GetControlVector(a)(1);\n\t\tinitialGuess((a - 1) * 3 + 3) = spline.GetControlVector(a)(2);\n\t}\n\n\tspline.AddPoint(points.back(), Eigen::Vector3d(0.0, 1.0, 0.0));\n\n\t/*std::cout << \"\\nIntersection Points:\\n\";\n\tfor (const auto& ip : spline.GetIntersectionPoints())\n\t\tstd::cout << ip.transpose() << '\\n';\n\n\tstd::cout << \"\\nInitial Control Vectors:\\n\";\n\tfor (const auto& cp : spline.GetControlVectors())\n\t\tstd::cout << cp.transpose() << '\\n';*/\n\t\n\tSplineFitArgs arguments(points, spline.GetIntersectionPoints(), initialGuess);\n\tconst unsigned int iterationLimit(10000);\n\tNelderMead<(splineSegmentCount - 1) * 3 + 2> optimizer(DoIteration, iterationLimit, &arguments);\n\toptimizer.SetInitialGuess(initialGuess);\n\tconst auto x(optimizer.Optimize());\n\tconst auto newControlVectors(BuildControlVectors(x));\n\n\tfor (unsigned int i = 0; i < newControlVectors.size(); ++i)\n\t\tspline.SetControlVector(i, newControlVectors[i]);\n\n\t/*std::cout << \"\\nFinal Control Vectors:\\n\";\n\tfor (const auto& cp : spline.GetControlVectors())\n\t\tstd::cout << cp.transpose() << '\\n';*/\n}\n\ndouble ComputeLength(const Vector3DVectors& p)\n{\n\tdouble length(0.0);\n\tfor (unsigned int i = 1; i < p.size(); ++i)\n\t\tlength += (p[i] - p[i - 1]).norm();\n\treturn length;\n}\n\nbool FindIntersectionOfTwoCircles(const Eigen::Vector2d& c1, const double& r1,\n\tconst Eigen::Vector2d& c2, const double& r2, Eigen::Vector2d& isect1, Eigen::Vector2d& isect2)\n{\n\tconst double distance((c1 - c2).norm());\n\tif (distance > r1 + r2 /*|| distance < fabs(r1 - r2)*/ || (distance == 0.0 && r1 == r2))// If there are no solutions, or infinite solutions, we cannot proceed\n\t\treturn false;\n\n\tconst double a((r1 * r1 - r2 * r2 + distance * distance) / (2.0 * distance));\n\tconst double h(sqrt(r1 * r1 - a * a));\n\tconst Eigen::Vector2d p(c1 + a * (c2 - c1) / distance);\n\n\tisect1(0) = p(0) + h * (c2(1) - c1(1)) / distance;\n\tisect1(1) = p(1) - h * (c2(0) - c1(0)) / distance;\n\n\tisect2(0) = p(0) - h * (c2(1) - c1(1)) / distance;\n\tisect2(1) = p(1) + h * (c2(0) - c1(0)) / distance;\n\n\treturn true;\n}\n\nEigen::Vector2d ChooseBestIntersection(const Eigen::Vector2d& isect1, const Eigen::Vector2d& isect2, const Vector2DVectors& c)\n{\n\t// TODO:  Improve this.  Should also consider distance between intersection results as criteria?  And/or distance from previous point?\n\t/*if (c.size() < 2)\n\t\treturn isect1;\n\n\tif ((c.back() - isect1).norm() > (c.back() - isect2).norm())\n\t\treturn isect1;*/\n\treturn isect2;\n}\n\nbool GenerateFlatPattern(const Spline& s1, const Spline& s2, const double& stepTarget, Vector2DVectors& flatPatternPoints, const unsigned int& targetOutputPointCount)\n{\n\tconst unsigned int resolution(1000);\n\tauto c1(ComputeSpline(s1, resolution));\n\tauto c2(ComputeSpline(s2, resolution));\n\n\tdouble s1Length(ComputeLength(c1));\n\tdouble s2Length(ComputeLength(c2));\n\n\t// Recalculate with resolution fine enough to give good distance resolution\n\tconst double factor(100.0);\n\tc1 = ComputeSpline(s1, static_cast<unsigned int>(s1Length / stepTarget * factor));\n\tc2 = ComputeSpline(s2, static_cast<unsigned int>(s2Length / stepTarget * factor));\n\n\ts1Length = ComputeLength(c1);\n\ts2Length = ComputeLength(c2);\n\n\tconst double step1(s1Length > s2Length ? stepTarget : stepTarget * s1Length / s2Length);\n\tconst double step2(s2Length > s1Length ? stepTarget : stepTarget * s2Length / s1Length);\n\n\tVector2DVectors curve1, curve2;\n\tdouble d((c1.front() - c2.front()).norm());\n\tcurve1.push_back((Eigen::Vector2d() << 0.0, 0.0).finished());\n\tcurve2.push_back((Eigen::Vector2d() << d, 0.0).finished());\n\n\tunsigned int i1(1), i2(1);\n\tunsigned int i1Last(0), i2Last(0);\n\twhile (i1 < c1.size() - 1 && i2 < c2.size() - 1)\n\t{\n\t\tfor (; i1 < c1.size() - 1; ++i1)\n\t\t{\n\t\t\tif ((c1[i1] - c1[i1Last]).norm() > step1)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tfor (; i2 < c2.size() - 1; ++i2)\n\t\t{\n\t\t\tif ((c2[i2] - c2[i2Last]).norm() > step2)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst double d1From1((c1[i1] - c1[i1Last]).norm());\n\t\tconst double d1From2((c1[i1] - c2[i2Last]).norm());\n\t\tconst double d2From1((c2[i2] - c1[i1Last]).norm());\n\t\tconst double d2From2((c2[i2] - c2[i2Last]).norm());\n\t\ti1Last = i1;\n\t\ti2Last = i2;\n\n\t\tEigen::Vector2d isect11, isect12, isect21, isect22;\n\t\tif (!FindIntersectionOfTwoCircles(curve1.back(), d1From1, curve2.back(), d1From2, isect11, isect12))\n\t\t\treturn false;\n\t\tif (!FindIntersectionOfTwoCircles(curve1.back(), d2From1, curve2.back(), d2From2, isect21, isect22))\n\t\t\treturn false;\n\n\t\tcurve1.push_back(ChooseBestIntersection(isect11, isect12, curve1));\n\t\tcurve2.push_back(ChooseBestIntersection(isect21, isect22, curve2));\n\t}\n\n\tauto decimate([](Vector2DVectors& curve, const unsigned int& increment)\n\t{\n\t\tunsigned int swapCount(0);\n\t\tfor (unsigned int i = 0; i < curve.size(); ++i)\n\t\t{\n\t\t\tif (i % increment == 0 || i == curve.size() - 1)\n\t\t\t\tcontinue;\n\t\t\tauto it(curve.begin() + i - swapCount);\n\t\t\tstd::rotate(it, it + 1, curve.end());\n\t\t\t++swapCount;\n\t\t}\n\t\tcurve.erase(curve.begin() + curve.size() - swapCount, curve.end());\n\t});\n\n\tconst unsigned int increment(std::max(static_cast<unsigned int>(curve1.size() / targetOutputPointCount), 1U));\n\tdecimate(curve1, increment);\n\tdecimate(curve2, increment);\n\n\tflatPatternPoints = curve1;\n\tflatPatternPoints.insert(flatPatternPoints.end(), curve2.rbegin(), curve2.rend());\n\n\treturn true;\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\tstd::cout << \"Usage:  \" << argv[0] << \" <input file>\\n\"\n\t\t\t<< \"  Input file must be comma-delimited and must contain four columns.\\n\"\n\t\t\t<< \"  The first three columns are (x,y,z) for a series of points\\n\"\n\t\t\t<< \"  describing one spline, and columns 4-5 are (x,y,z) for a series of\\n\"\n\t\t\t<< \"  points describing the second spline.  Points should only be included\\n\"\n\t\t\t<< \"  for half of each curve (i.e. positive y-ordinates only).  It is\\n\"\n\t\t\t<< \"  assumed that x-z plane symmetry is desired, and curves are\\n\"\n\t\t\t<< \"  constrained to have slopes parallel to the y-axis where the curves\\n\"\n\t\t\t<< \"  meet the x-z plane.\\n\" << std::endl;\n\t}\n\n\tVector3DVectors curve1, curve2;\n\tif (!ReadInputFile(argv[1], curve1, curve2))\n\t\treturn 1;\n\n\tSpline spline1, spline2;\n\tFitSplineToPoints(curve1, spline1);\n\tFitSplineToPoints(curve2, spline2);\n\n\tconst unsigned int res(30);\n\tconst auto c1(ComputeSpline(spline1, res));\n\tconst auto c2(ComputeSpline(spline2, res));\n\tstd::ofstream splinesOut(\"splinesOut.csv\");\n\tfor (unsigned int i = 0; i < c1.size(); ++i)\n\t\tsplinesOut << c1[i](0) << ',' << c1[i](1) << ',' << c1[i](2) << ',' << c2[i](0) << ',' << c2[i](1) << ',' << c2[i](2) << '\\n';//*/\n\n\tconst double distanceResolution(0.01);\n\tconst unsigned int targetOutputPointCount(100);\n\tVector2DVectors flatPatternPoints;\n\tif (!GenerateFlatPattern(spline1, spline2, distanceResolution, flatPatternPoints, targetOutputPointCount))\n\t\treturn 1;\n\n\tstd::ofstream flatPatternOut(\"flatPattern.csv\");\n\tflatPatternOut.precision(10);\n\tfor (unsigned int i = 0; i < flatPatternPoints.size(); ++i)\n\t\tflatPatternOut << std::fixed << flatPatternPoints[i](0) << ',' << flatPatternPoints[i](1) << '\\n';\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "a557d21b47746fef3d4c4bf155fb117777c9bb2e", "size": 13607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "KerryL/SplinePatchToFlatPattern", "max_stars_repo_head_hexsha": "b9f005a955d66cbfbe1b568b6abfd7979f7587c3", "max_stars_repo_licenses": ["MIT"], "max_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": "KerryL/SplinePatchToFlatPattern", "max_issues_repo_head_hexsha": "b9f005a955d66cbfbe1b568b6abfd7979f7587c3", "max_issues_repo_licenses": ["MIT"], "max_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": "KerryL/SplinePatchToFlatPattern", "max_forks_repo_head_hexsha": "b9f005a955d66cbfbe1b568b6abfd7979f7587c3", "max_forks_repo_licenses": ["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.6441860465, "max_line_length": 166, "alphanum_fraction": 0.6795766885, "num_tokens": 4151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583167, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.578440918209334}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\ntemplate <typename T>\nvoid deg2rad(T &deg)\n{\n    deg *= M_PI / 180.;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 1> eulerToQuaternion(const Eigen::Matrix<T, 3, 1> &rpy)\n{\n    Eigen::Quaternion<T> q = Eigen::AngleAxis<T>(rpy.x(), Eigen::Matrix<T, 3, 1>::UnitX()) *\n                             Eigen::AngleAxis<T>(rpy.y(), Eigen::Matrix<T, 3, 1>::UnitY()) *\n                             Eigen::AngleAxis<T>(rpy.z(), Eigen::Matrix<T, 3, 1>::UnitZ());\n    Eigen::Matrix<T, 4, 1> quat;\n    quat << q.w(), q.vec();\n\n    return quat;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> omegaMatrix(const Eigen::Matrix<T, 3, 1> &w)\n{\n    Eigen::Matrix<T, 4, 4> omegaMatrix;\n    omegaMatrix << T(0.), -w(0), -w(1), -w(2),\n        w(0), T(0.), w(2), -w(1),\n        w(1), -w(2), T(0.), w(0),\n        w(2), w(1), -w(0), T(0.);\n\n    return omegaMatrix;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> omegaMatrixReduced(const Eigen::Matrix<T, 3, 1> &q)\n{\n    Eigen::Matrix<T, 3, 3> omegaMatrix;\n    const T qw = sqrt(1. - q.squaredNorm());\n    omegaMatrix << qw, -q(2), q(1),\n        q(2), qw, -q(0),\n        -q(1), q(0), qw;\n\n    return omegaMatrix;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> EulerRotationMatrix(const Eigen::Matrix<T, 3, 1> &eta)\n{\n    const T phi = eta(0);\n    const T theta = eta(1);\n    const T psi = eta(2);\n\n    Eigen::Matrix<T, 3, 3> R;\n    R.row(0) << cos(theta) * cos(psi), -cos(theta) * sin(psi), sin(theta);\n    R.row(1) << sin(phi) * sin(theta) * cos(psi) + cos(phi) * sin(psi),\n        cos(phi) * cos(psi) - sin(phi) * sin(theta) * sin(psi), -sin(phi) * cos(theta);\n    R.row(2) << -cos(phi) * sin(theta) * cos(psi) + sin(phi) * sin(psi),\n        sin(phi) * cos(psi) + cos(phi) * sin(theta) * sin(psi), cos(phi) * cos(theta);\n\n    return R;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 3, 3> EulerRotationJacobian(const Eigen::Matrix<T, 3, 1> &eta)\n{\n    const T phi = eta(0);\n    const T theta = eta(1);\n    const T psi = eta(2);\n\n    Eigen::Matrix<T, 3, 3> J;\n    J.row(0) << cos(psi), -sin(psi), 0.;\n    J.row(1) << cos(theta) * sin(psi), cos(theta) * cos(psi), 0;\n    J.row(2) << -sin(theta) * cos(psi), sin(theta) * sin(psi), cos(theta);\n\n    return 1. / cos(theta) * J;\n}", "meta": {"hexsha": "03a52d511f5f7311c0d1a6b2670d0310eead1e4d", "size": 2233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "socp_mpc/models/include/common.hpp", "max_stars_repo_name": "boyali/SCpp", "max_stars_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "socp_mpc/models/include/common.hpp", "max_issues_repo_name": "boyali/SCpp", "max_issues_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "socp_mpc/models/include/common.hpp", "max_forks_repo_name": "boyali/SCpp", "max_forks_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-18T12:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-18T12:58:00.000Z", "avg_line_length": 29.0, "max_line_length": 92, "alphanum_fraction": 0.5378414689, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5784409118070516}}
{"text": "// Eigen::Ref can be used to refer to a matrix *or* a block without copying.\n// The referred matrix must have its memory fully allocated: cannot be resized.\n\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n\nusing namespace std;\n\nEigen::MatrixXd A = Eigen::MatrixXd::Random(1, 2);\nEigen::Ref<Eigen::MatrixXd> ref_from_address(Eigen::MatrixXd *address) {\n  return *address;\n}\n\nint main() {\n  std::cout << \"A: \" << std::endl << A << std::endl << std::endl;\n\n  Eigen::MatrixXd *A_address = &A;\n  std::cout << \"A_address: \" << A_address << std::endl;\n\n  std::cout << \"A = Eigen::MatrixXd::Random(2, 4);\" << std::endl;\n  A = Eigen::MatrixXd::Random(2, 4);\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"ref_from_address(A_address) =  Eigen::MatrixXd::Random(2, 4);\"\n            << \" // Okay, since shape matches\" << std::endl;\n  ref_from_address(A_address) =  Eigen::MatrixXd::Random(2, 4);\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"ref_from_address(A_address).col(2) = \"\n            << \"Eigen::MatrixXd::Zero(2, 1); // Also okay\" << std::endl;\n  ref_from_address(A_address).col(2) =  Eigen::MatrixXd::Zero(2, 1);\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"// ref_from_address(A_address) =  \"\n            << \"Eigen::MatrixXd::Ones(2, 10); // ERROR! \"\n            << \"\\\"DenseBase::resize() does not actually allow to resize.\\\"\"\n            << std::endl << std::endl;\n  // ref_from_address(A_address) =  Eigen::MatrixXd::Ones(2, 10);\n\n  std::cout << \"// First need to directly resize NOT USING REF. This destroys \"\n            << \"coeffs if the number of coeffs is different.\" << std::endl;\n  std::cout << \"A_address->resize(2, 10);  \" << std::endl;\n  A_address->resize(2, 10);\n  // ref_from_address(A_address).resize(2, 4);  // This gives error.\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"ref_from_address(A_address) =  \"\n            << \"Eigen::MatrixXd::Ones(2, 10); // Now okay\" << std::endl;\n  ref_from_address(A_address) =  Eigen::MatrixXd::Ones(2, 10);\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"ref_from_address(A_address) << 1, 3, 5, 7, 9, 11, 13, 15, 17, \"\n            << \"19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20; // Also okay\"\n            << std::endl;\n  ref_from_address(A_address) <<\n      1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20;\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"// Aside: resizing is conservative when the number of coeffs \"\n            << \"remains the same.\" << std::endl;\n  std::cout << \"A_address->resize(2, 10);  \" << std::endl;\n  A_address->resize(4, 5);\n  std::cout << A << std::endl << std::endl;\n\n  std::cout << \"// Coefficient access\" << std::endl;\n  std::cout << \"ref_from_address(A_address)(1, 2) = \"\n            << ref_from_address(A_address)(1, 2) << std::endl;\n  std::cout << \"ref_from_address(A_address).data()[9] = \"\n            << ref_from_address(A_address).data()[9] << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "9273a1473adbbbe73807635cf2c2dbc4240f2939", "size": 3017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "notes/eigen_ref/main.cc", "max_stars_repo_name": "karlstratos/mesosphere", "max_stars_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T22:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T22:18:39.000Z", "max_issues_repo_path": "notes/eigen_ref/main.cc", "max_issues_repo_name": "karlstratos/stratosphere_nn", "max_issues_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notes/eigen_ref/main.cc", "max_forks_repo_name": "karlstratos/stratosphere_nn", "max_forks_repo_head_hexsha": "efb6774e94aa4ed60aaba5bf5ad4c0a3e79506b0", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 79, "alphanum_fraction": 0.58501823, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5784356811586983}}
{"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_EXPM1_INCLUDED\r\n#define BOOST_MATH_EXPM1_INCLUDED\r\n\r\n#include <cmath>\r\n#include <math.h> // platform's ::expm1\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 ::exp; using ::fabs; }\r\n#endif\r\n\r\n\r\nnamespace boost{ namespace math{\r\n\r\nnamespace detail{\r\n//\r\n// Functor expm1_series returns the next term in the Taylor series\r\n// x^k / k!\r\n// each time that operator() is invoked.\r\n//\r\ntemplate <class T>\r\nstruct expm1_series\r\n{\r\n   typedef T result_type;\r\n\r\n   expm1_series(T x)\r\n      : k(0), m_x(x), m_term(1) {}\r\n\r\n   T operator()()\r\n   {\r\n      ++k;\r\n      m_term *= m_x;\r\n      m_term /= k;\r\n      return m_term; \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_x;\r\n   T m_term;\r\n   expm1_series(const expm1_series&);\r\n   expm1_series& operator=(const expm1_series&);\r\n};\r\n\r\n} // namespace\r\n\r\n//\r\n// Algorithm expm1 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.\r\n//\r\ntemplate <class T>\r\nT expm1(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\r\n   T a = std::fabs(x);\r\n   if(a > T(0.5L))\r\n      return std::exp(x) - T(1);\r\n   if(a < std::numeric_limits<T>::epsilon())\r\n      return x;\r\n   detail::expm1_series<T> s(x);\r\n   T result = detail::kahan_sum_series(s, std::numeric_limits<T>::digits + 2);\r\n   return result;\r\n}\r\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))\r\ninline float expm1(float z)\r\n{\r\n   return expm1<float>(z);\r\n}\r\ninline double expm1(double z)\r\n{\r\n   return expm1<double>(z);\r\n}\r\ninline long double expm1(long double z)\r\n{\r\n   return expm1<long double>(z);\r\n}\r\n#endif\r\n\r\n#ifdef expm1\r\n#  ifndef BOOST_HAS_expm1\r\n#     define BOOST_HAS_expm1\r\n#  endif\r\n#  undef expm1\r\n#endif\r\n\r\n#ifdef BOOST_HAS_EXPM1\r\n#  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)\r\ninline float expm1(float x){ return ::expm1f(x); }\r\ninline long double expm1(long double x){ return ::expm1l(x); }\r\n#else\r\ninline float expm1(float x){ return ::expm1(x); }\r\n#endif\r\ninline double expm1(double x){ return ::expm1(x); }\r\n#endif\r\n\r\n} } // namespaces\r\n\r\n#endif // BOOST_MATH_HYPOT_INCLUDED\r\n", "meta": {"hexsha": "8af573db1e0c51699ecccd3cdc6de3ce8efba3e5", "size": 2771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/expm1.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/expm1.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/expm1.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": 22.7131147541, "max_line_length": 79, "alphanum_fraction": 0.6622158066, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.578435669263665}}
{"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#include <string>\n\nusing namespace std::string_literals;\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/complex_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#include \"miMaS/iteration.h\"\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*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\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  auto c = config(p);\n  c.name = \"vhll\";\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> fh(boost::extents[c.Nv][c.Nx]);\n  complex_field<double,1> hfh(boost::extents[c.Nv][c.Nx]);\n\n  const double Kx = 0.5;\n  fh.range.v_min = -8.; fh.range.v_max = 8.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n  fh.compute_steps();\n\n  ublas::vector<double> v(c.Nv,0.);\n  std::generate( v.begin() , v.end() , [&,k=0]() mutable {return (k++)*fh.step.dv+fh.range.v_min;} );\n\n  ublas::vector<double> kx(c.Nx); // beware, Nx need to be odd\n  {\n    double l = fh.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  auto tb_M1 = maxwellian( 0.5*c.alpha , c.ui , 1. ) , tb_M2 = maxwellian( 0.5*c.alpha , -c.ui , 1. );\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n    fft::fft(fh[k].begin(),fh[k].end(),hfh[k].begin());\n  }\n  fh.write( c.output_dir / (\"init_\"+c.name+\".dat\") );\n\n  iteration::iteration<double> iter;\n  iter.iter = 0;\n  iter.current_time = 0.;\n  iter.dt = 0.5*fh.step.dv;\n\n  ublas::vector<double> uc(c.Nx,0.);\n  ublas::vector<double> E (c.Nx,0.);\n\n  std::vector<double> ee;   ee.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<double> Emax; Emax.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<double> H;    H.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<iteration::iteration<double>> iterations; iterations.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n  std::vector<iteration::iteration<double>> success_iterations; success_iterations.reserve(int(std::ceil(c.Tf/iter.dt))+1);\n\n  std::vector<double> times; times.reserve(int(std::ceil(c.Tf/iter.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 iterations informations\n    auto writer_iter = [] ( auto const & it ) {\n      std::stringstream ss; ss << it;\n      return ss.str();\n    };\n    c << monitoring::data( \"iterations_\"+suffix+\".dat\"         , iterations         , writer_iter );\n    c << monitoring::data( \"success_iterations_\"+suffix+\".dat\" , success_iterations , writer_iter );\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    for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n    fh.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  const double rho_c = 1.-c.alpha;\n  const double sqrt_rho_c = std::sqrt(rho_c);\n\n  // init E with Poisson solver, init also ee, Emax, H and times\n  {\n    poisson<double> poisson_solver(c.Nx,fh.range.len_x());\n    ublas::vector<double> rho(c.Nx,0.);\n    rho = fh.density(); // compute density from init data\n    for ( auto i=0 ; i<c.Nx ; ++i ) { rho[i] += (1.-c.alpha); } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n\n    Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n    double electric_energy = std::sqrt(std::accumulate(\n      E.begin() , E.end() , 0. ,\n      [&] ( double partial_sum , double ei ) {\n        return partial_sum + ei*ei*fh.step.dx;\n      }\n    ));\n    ee.push_back( electric_energy );\n\n    double total_energy = energy(fh,E);\n    total_energy += 0.; // sum(rho_c*u_c*u_c) = 0 because u_c = 0 at time 0\n    H.push_back( total_energy );\n    times.push_back(0.);\n  }\n\n  // initialize memory for all temporary variables\n  ublas::vector<double> J(c.Nx,0.);\n  fft::spectrum_ d(c.Nx);\n  field<double,1> Edvf(tools::array_view<const std::size_t>(fh.shape(),2));\n  ublas::vector<double> uc1(c.Nx) , uc2(c.Nx) , uc3(c.Nx) , uc4(c.Nx) , uc5(c.Nx) , uc6(c.Nx) , uc7(c.Nx),\n                        E1 (c.Nx) , E2(c.Nx)  , E3 (c.Nx) , E4 (c.Nx) , E5 (c.Nx) , E6 (c.Nx) , E7 (c.Nx);\n  complex_field<double,1> hfh1(boost::extents[c.Nv][c.Nx]) , hfh2(boost::extents[c.Nv][c.Nx]) ,\n                          hfh3(boost::extents[c.Nv][c.Nx]) , hfh4(boost::extents[c.Nv][c.Nx]) ,\n                          hfh5(boost::extents[c.Nv][c.Nx]) , hfh6(boost::extents[c.Nv][c.Nx]) ,\n                          hfh7(boost::extents[c.Nv][c.Nx]) ;\n\n  while (  iter.current_time < c.Tf ) {\n    std::cout << \"\\r\" << iteration::time(iter) << std::flush;\n\n///////////////////////////////////////////////////////////////////////////////\n// DP4(3) /////////////////////////////////////////////////////////////////////\n\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c05 = std::cos(0.5*iter.dt*sqrt_rho_c), s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc1[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c - 0.5*iter.dt*J[i]*s05/sqrt_rho_c;\n        E1[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*iter.dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) - 0.5*iter.dt*d[i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c05 = std::cos(0.5*iter.dt*sqrt_rho_c), s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc2[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c;\n        E2[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh2[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) - 0.5*iter.dt*d[i];\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc3[i] =  uc[i]*c1 + E[i]*s1/sqrt_rho_c - iter.dt*J[i]*s05/sqrt_rho_c;\n        E3[i]  = -uc[i]*s1*sqrt_rho_c + E[i]*c1 - iter.dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh3[k][i] = hfh[k][i]*std::exp(-I*kx[i]*v[k]*iter.dt) - iter.dt*d[i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt);\n        }\n      }\n    } // end stage 3\n\n    // STAGE 4\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh3[k].begin(),hfh3[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E3);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc4[i] = -(1./3.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./3.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./3.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/3.;\n        E4[i]  = -(1./3.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./3.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./3.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/3. - (1./6.)*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh4[k][i] = -(1./3.)*hfh[k][i]*std::exp(-I*kx[i]*v[k]*iter.dt) + (1./3.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) + (2./3.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) + hfh3[k][i]/3. - (1./6.)*iter.dt*d[i];\n        }\n      }\n    } // end stage 4\n\n    // STAGE 5\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh4[k].begin(),hfh4[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E4);\n\n      double c1  = std::cos(iter.dt*sqrt_rho_c)     , s1  = std::sin(iter.dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*iter.dt*sqrt_rho_c) , s05 = std::sin(0.5*iter.dt*sqrt_rho_c);\n      for ( auto i=0 ; i<c.Nx ; ++i ) {\n        uc5[i] = -(1./5.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./5.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./5.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/5. + (2./5.)*uc4[i];\n        E5[i]  = -(1./5.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./5.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./5.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/5. + (2./5.)*E4[i] - (1./10.)*iter.dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          hfh5[k][i] = -(1./5.)*hfh[k][i]*std::exp(-I*kx[i]*v[k]*iter.dt) + (1./5.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) + (2./5.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*v[k]*iter.dt) + hfh3[k][i]/5. + (2./5.)*hfh4[k][i] - 0.1*iter.dt*d[i];\n        }\n      }\n    } // end stage 5\n\n///////////////////////////////////////////////////////////////////////////////\n// MONITORING /////////////////////////////////////////////////////////////////\n\n    // CHECH local error for compute next time step\n    iter.E_error(E5,E4,fh.step.dx);\n    iter.hfh_error(hfh5,hfh4,fh.step.dx*fh.step.dv);\n    iter.success = std::abs(iter.error() - c.tol) <= c.tol;\n\n    std::cout << \" -- \" << iteration::error(iter) << std::flush;\n    if ( iter.success )\n    {\n      // SAVE TIME STEP\n      std::copy( uc4.begin()  , uc4.end()  , uc.begin()  );\n      std::copy( E4.begin()   , E4.end()   , E.begin()   );\n      std::copy( hfh4.begin() , hfh4.end() , hfh.begin() );\n\n      Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n      double electric_energy = std::sqrt(std::accumulate(\n        E.begin() , E.end() , 0. ,\n        [&] ( double partial_sum , double ei ) {\n          return partial_sum + ei*ei*fh.step.dx;\n        }\n      ));\n      ee.push_back( electric_energy );\n\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      double total_energy = energy(fh,E);\n      {\n        auto rhoh = fh.density();\n        fft::spectrum_ hrhoh(c.Nx); hrhoh.fft(rhoh.begin());\n        fft::spectrum_ hE(c.Nx); hE.fft(E.begin());\n        fft::spectrum_ hrhoc(c.Nx);\n        hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n        for ( auto i=1 ; i<c.Nx ; ++i ) {\n          hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n        }\n        ublas::vector<double> rhoc (c.Nx,0.); hrhoc.ifft(rhoc.begin());\n\n        for ( auto i=0 ; i<c.Nx ; ++i ) {\n          total_energy += rhoc[i]*uc[i]*uc[i];\n        }\n      }\n      H.push_back( total_energy );\n\n      // increment time\n      iter.current_time += iter.dt;\n      times.push_back( iter.current_time );\n      success_iterations.push_back( iter );\n    }\n    iterations.push_back( iter );\n\n\n    ++iter.iter;\n    iter.dt = std::pow( c.tol/iter.Lhfh , 0.25 )*iter.dt;\n    if ( iter.current_time+iter.dt > c.Tf ) { iter.dt = c.Tf - iter.current_time; }\n  } // while (  iter.current_time < c.Tf ) // end of time loop\n  std::cout << \"\\r\" << time(iter) << std::endl;\n\n  save_data(\"dp4\");\n\n  auto dx_y = [&,count=0](auto const& y) mutable {\n    std::stringstream ss; ss<< fh.step.dx*(count++) <<\" \"<<y;\n    return ss.str();\n  };\n  c << monitoring::data( \"E_\"+c.name+\".dat\" , E , dx_y );\n\n  ublas::vector<double> rho (c.Nx,0.);\n  ublas::vector<double> rhoc(c.Nx,0.);\n  {\n    ublas::vector<double> rhoh = fh.density();\n    fft::spectrum_ hrhoh(c.Nx); hrhoh.fft(rhoh.begin());\n    fft::spectrum_ hE(c.Nx);    hE.fft(E.begin());\n\n    fft::spectrum_ hrho(c.Nx), hrhoc(c.Nx);\n\n    hrho[0] = I*kx[0]*hE[0] + 1.;\n    hrho[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n    for ( auto i=1 ; i<c.Nx ; ++i ) {\n      hrho[i]  = I*kx[i]*hE[i];\n      hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i];\n    }\n    hrho.ifft(rho.begin());\n  }\n\n  c << monitoring::data( \"rho_\"+c.name+\".dat\"  , rho  , dx_y );\n  c << monitoring::data( \"uc_\"+c.name+\".dat\"   , uc   , dx_y );\n  c << monitoring::data( \"rhoc_\"+c.name+\".dat\" , rhoc , dx_y );\n\n  J = fh.courant();\n  for ( auto i=0 ; i<c.Nx ; ++i ) {\n    J[i] += rhoc[i]*uc[i];\n  }\n  c << monitoring::data( \"J_\"+c.name+\".dat\" , J , dx_y );\n\n  return 0;\n}\n", "meta": {"hexsha": "0bfafe9df982282f05c98614fcd9c81053cc8449", "size": 14652, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/tb_dp4.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/tb_dp4.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/tb_dp4.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": 39.8152173913, "max_line_length": 244, "alphanum_fraction": 0.5200655201, "num_tokens": 5275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5783539088620243}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Copyright (c) 2015 Kenjiro Sugimoto\n// Released under the MIT license\n// http://opensource.org/licenses/mit-license.php\n////////////////////////////////////////////////////////////////////////////////\n\n// This code implements the algorithm of the following paper. Please cite it in \n// your paper if your research uses this code.\n//   + K. Sugimoto and S. Kamata: \"Compressive bilateral filtering\", IEEE Trans.\n//     Image Process., vol. 24, no. 11, pp. 3357-3369 (Nov. 2015).\n\n#pragma once\n#define _USE_MATH_DEFINES\n#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <cassert>\n#ifdef USE_OPENCV2\n#include <opencv2/opencv.hpp>\n#endif\n#ifdef USE_BOOST\n#include <boost/math/special_functions/erf.hpp> // for erfc_inv() only\n#endif\n#include \"o1_spatial_gaussian_filter.hpp\"\n\n//==============================================================================\n\nclass compressive_bilateral_filter\n{\nprivate:\n\tint tone;\n\n\t// this parameter will provide sufficient accuracy.\n\to1_spatial_gaussian_filter<2> gaussian;\n\tint K; // number of basis range kernels\n\tdouble T; // period length of periodic range kernel\n\tstd::vector<double> sqrta;\n\npublic:\n\tcompressive_bilateral_filter(double sigmaS,double sigmaR,double tol=0.10,int tone=256):tone(tone),gaussian(sigmaS)\n\t{\n#ifdef USE_BOOST\n\t\tdouble xi=boost::math::erfc_inv(tol*tol);\n#else\n\t\t// hard-coding for boost-less running\n\t\tdouble xi;\n\t\t     if(tol==0.05) xi=2.1378252338818511;\n\t\telse if(tol==0.10) xi=1.8213863677184496;\n\t\telse if(tol==0.20) xi=1.4522197815622468;\n\t\telse\n\t\t\tthrow std::invalid_argument(\"Unsupported tolerance! ({0.05,0.10,0.20} only or use boost)\");\n#endif\n\t\t// estimating an optimal K\n\t\tdouble s=sigmaR/(tone-1.0); // normalized to dynamic range [0,1]\n\t\tK=static_cast<int>(std::ceil(xi*xi/(2.0*M_PI)+xi/(2.0*M_PI*s)-0.5));\n\t\t\n\t\t// estimating an optimal T\n\t\tderivative_estimated_gaussian_range_kernel_error df(s,K);\n\t\tdouble t1=s*xi+1.0;\n\t\tdouble t2=M_PI*(2*K+1)*s/xi;\n\t\t// It is better to slightly extend the original search domain D\n\t\t// because it might uncover the minimum of E(T) due to approximate error.\n\t\tconst double MAGICNUM=0.03;\n\t\tT=(tone-1.0)*solve_by_bs(df,t1,t2+MAGICNUM);\n\n\t\t// precomputing the square root of spectrum\n\t\tdouble omega=2.0*M_PI/T;\n\t\tsqrta=std::vector<double>(K);\n\t\tfor(int k=1;k<=K;++k)\n\t\t\tsqrta[k-1]=M_SQRT2*exp(-0.25*omega*omega*sigmaR*sigmaR*k*k);\n\t}\n\nprivate:\n\t/// a scale-adjusted derivative of the estimated Gaussian range kernel error\n\tclass derivative_estimated_gaussian_range_kernel_error\n\t{\n\tprivate:\n\t\tdouble sigma,kappa;\n\tpublic:\n\t\tderivative_estimated_gaussian_range_kernel_error(double sigma,int K)\n\t\t\t:sigma(sigma),kappa(M_PI*(2*K+1)){}\n\tpublic:\n\t\tdouble operator()(double T)\n\t\t{\n\t\t\tdouble phi=(T-1.0)/sigma;\n\t\t\tdouble psi=kappa*sigma/T;\n\t\t\treturn kappa*exp(-phi*phi)-psi*psi*exp(-psi*psi);\n\t\t}\n\t};\n\t/// solve df(x)==0 by binary search\n\ttemplate<class Functor>\n\tinline double solve_by_bs(Functor df,double x1,double x2,int loop=10)\n\t{\n\t\tfor(int i=0;i<loop;++i)\n\t\t{\n\t\t\tdouble x=(x1+x2)/2.0;\n\t\t\t((0.0<=df(x))?x2:x1)=x;\n\t\t}\n\t\treturn (x1+x2)/2.0;\n\t}\n\npublic:\n#ifdef USE_OPENCV2\n\t/// O(1) cross/joint bilateral filtering\n\t/// \"guide\" has to have dynamic range [0,tone).\n\tvoid operator()(const cv::Mat_<double>& src,const cv::Mat_<double>& guide,cv::Mat_<double>& dst)\n\t{\n\t\tassert(src.size()==guide.size());\n\t\tassert(src.size()==dst.size());\n\t\t\n\t\t// lookup tables (discretized for fast computation)\n\t\tstd::vector<double> tblC(tone);\n\t\tstd::vector<double> tblS(tone);\n\t\t// component images\n\t\tcv::Mat_<cv::Vec4d> compsI(src.size());\n\t\tcv::Mat_<cv::Vec4d> compsO(src.size());\n\t\t\n\t\t// DC component\n\t\tconst int winsz=gaussian.window_size();\n\t\tcv::Mat_<double> denom(src.size(),winsz*winsz);\n\t\tcv::Mat_<double> numer(src.size());\n\t\tgaussian.filter_xy(src,numer);\n\n\t\t// AC components\n\t\tdouble omega=2.0*M_PI/T;\n\t\tfor(int k=1;k<=K;++k)\n\t\t{\n\t\t\t// preparing look-up tables\n\t\t\tdouble omegak=omega*k;\n\t\t\tfor(int t=0;t<tone;++t)\n\t\t\t{\n\t\t\t\tdouble theta=omegak*t;\n\t\t\t\ttblC[t]=sqrta[k-1]*cos(theta);\n\t\t\t\ttblS[t]=sqrta[k-1]*sin(theta);\n\t\t\t}\n\n\t\t\t// generating k-th component images\n\t\t\tfor(int y=0;y<src.rows;++y)\n\t\t\tfor(int x=0;x<src.cols;++x)\n\t\t\t{\n\t\t\t\tint t=int(guide(y,x)); // from guide image\n\t\t\t\tdouble c=tblC[t];\n\t\t\t\tdouble s=tblS[t];\n\t\t\t\tdouble p=src(y,x);\n\t\t\t\tcompsI(y,x)=cv::Vec4d(c*p,s*p,c,s);\n\t\t\t}\n\t\t\tgaussian.filter_xy(compsI,compsO);\n\t\t\n\t\t\t// decompressing k-th components\n\t\t\tfor(int y=0;y<src.rows;++y)\n\t\t\tfor(int x=0;x<src.cols;++x)\n\t\t\t{\n\t\t\t\tint t=int(guide(y,x)); // from guide image\n\t\t\t\tdouble c=tblC[t];\n\t\t\t\tdouble s=tblS[t];\n\t\t\t\tconst cv::Vec4d& values=compsO(y,x);\n\t\t\t\tnumer(y,x)+=c*values[0]+s*values[1];\n\t\t\t\tdenom(y,x)+=c*values[2]+s*values[3];\n\t\t\t}\n\t\t}\n\t\tdst=numer/denom;\n\t}\n\t/// O(1) bilateral filtering\n\t/// \"src\" has to have dynamic range [0,tone).\n\tvoid operator()(const cv::Mat_<double>& src,cv::Mat_<double>& dst)\n\t{\n\t\tassert(src.size()==dst.size());\n\t\t\n\t\t// lookup tables (discretized for fast computation)\n\t\tstd::vector<double> tblC(tone);\n\t\tstd::vector<double> tblS(tone);\n\t\t// component images\n\t\tcv::Mat_<cv::Vec4d> compsI(src.size());\n\t\tcv::Mat_<cv::Vec4d> compsO(src.size());\n\t\t\n\t\t// DC component\n\t\tconst int winsz=gaussian.window_size();\n\t\tcv::Mat_<double> denom(src.size(),winsz*winsz);\n\t\tcv::Mat_<double> numer(src.size());\n\t\tgaussian.filter_xy(src,numer);\n\n\t\t// AC components\n\t\tdouble omega=2.0*M_PI/T;\n\t\tfor(int k=1;k<=K;++k)\n\t\t{\n\t\t\t// preparing look-up tables\n\t\t\tdouble omegak=omega*k;\n\t\t\tfor(int t=0;t<tone;++t)\n\t\t\t{\n\t\t\t\tdouble theta=omegak*t;\n\t\t\t\ttblC[t]=sqrta[k-1]*cos(theta);\n\t\t\t\ttblS[t]=sqrta[k-1]*sin(theta);\n\t\t\t}\n\n\t\t\t// generating k-th component images\n\t\t\tfor(int y=0;y<src.rows;++y)\n\t\t\tfor(int x=0;x<src.cols;++x)\n\t\t\t{\n\t\t\t\tint t=int(src(y,x));\n\t\t\t\tdouble c=tblC[t];\n\t\t\t\tdouble s=tblS[t];\n\t\t\t\tdouble p=src(y,x);\n\t\t\t\tcompsI(y,x)=cv::Vec4d(c*p,s*p,c,s);\n\t\t\t}\n\t\t\tgaussian.filter_xy(compsI,compsO);\n\t\t\n\t\t\t// decompressing k-th components\n\t\t\tfor(int y=0;y<src.rows;++y)\n\t\t\tfor(int x=0;x<src.cols;++x)\n\t\t\t{\n\t\t\t\tint t=int(src(y,x));\n\t\t\t\tdouble c=tblC[t];\n\t\t\t\tdouble s=tblS[t];\n\t\t\t\tconst cv::Vec4d& values=compsO(y,x);\n\t\t\t\tnumer(y,x)+=c*values[0]+s*values[1];\n\t\t\t\tdenom(y,x)+=c*values[2]+s*values[3];\n\t\t\t}\n\t\t}\n\t\tdst=numer/denom;\n\t}\n#endif\n};\n\n//==============================================================================\n", "meta": {"hexsha": "8622c1e8780302be0ce21734fd946b02e10a3aa3", "size": 6402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CompressiveBilateralFilter/include/compressive_bilateral_filter.hpp", "max_stars_repo_name": "Rintarooo/compressive-bilateral-filter", "max_stars_repo_head_hexsha": "cbaa4bd3b167aaea5f2b5fff0d72fdc7063ebf1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-08-26T03:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T06:25:12.000Z", "max_issues_repo_path": "CompressiveBilateralFilter/include/compressive_bilateral_filter.hpp", "max_issues_repo_name": "Rintarooo/compressive-bilateral-filter", "max_issues_repo_head_hexsha": "cbaa4bd3b167aaea5f2b5fff0d72fdc7063ebf1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T11:29:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-25T11:29:05.000Z", "max_forks_repo_path": "CompressiveBilateralFilter/include/compressive_bilateral_filter.hpp", "max_forks_repo_name": "Rintarooo/compressive-bilateral-filter", "max_forks_repo_head_hexsha": "cbaa4bd3b167aaea5f2b5fff0d72fdc7063ebf1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-03-09T14:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T04:51:25.000Z", "avg_line_length": 28.0789473684, "max_line_length": 115, "alphanum_fraction": 0.6269915651, "num_tokens": 2020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5781265151509448}}
{"text": "#include <CGAL/config.h>\n#define CGAL_EIGEN3_ENABLED\n#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4)\n#include <iostream>\nint main()\n{\n  std::cerr << \"NOTICE: This test requires G++ >= 4.4, and will not be compiled.\" << std::endl;\n}\n#else\n#include <CGAL/Epick_d.h>\n#include <eigen3/Eigen/Core>\n#include <CGAL/Delaunay_triangulation.h>\n#include <CGAL/IO/Triangulation_off_ostream.h>\n#include <CGAL/point_generators_d.h>\n#include <CGAL/Timer.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/Origin.h>\n\n#include <vector>\n#include <random>\n#include <string>\n#include <fstream>\n#include <cstdlib>\n#include <algorithm>\n#include <cmath>\n#include <boost/algorithm/string.hpp>\n#include <chrono>\n\n// uncomment this if want generate random points\n// #define RANDOM_PTS \n\nconst double lower_bound = 0.0;\nconst double upper_bound = 1.0;\nconst double step_size = 0.01;\nconst double small_step_size = 0.001;\n//TODO: Change the path_prefix before running the function!\nconst std::string path_prefix = \"/Users/angelynaye/Desktop/Research/result/space-partition-adv\";\n\n/** Helper Functions Section  **/\n\n//function to read in data from csv file \nstd::vector<std::vector<double> > read_data(std::string file_name, int dim,\nstd::string delimeter = \" \")\n{\n\tstd::ifstream file(file_name);\n \n\tstd::vector<std::vector<double> > data_list;\n \n\tstd::string line = \"\";\n\t// Iterate through each line split the content using delimeter\n  // convert it to double\n\twhile (getline(file, line))\n\t{\n\t\tstd::vector<std::string> vec;\n\t\tboost::algorithm::split(vec, line, boost::is_any_of(delimeter));\n        std::vector<double> dd;\n        dd.reserve(dim);\n        for(std::vector<std::string>::iterator it = vec.begin(); \n        it != vec.end(); ++it) {\n          dd.push_back(std::stod(*it));\n        }\n\n\t\tdata_list.push_back(dd);\n\n\t}\n\t// Close the File\n\tfile.close();\n \n\treturn data_list;\n}\n\n// return true if within [0,1]\ntemplate<int D>\nbool check_boundary(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a) {\n    for(int i = 0; i < D; i++) {\n      if(a[i] < lower_bound || a[i] > upper_bound) {\n        return false;\n      }\n    }\n    return true;\n}\n\n// compute Euclidean distance of dimension D points \ntemplate<int D>\ndouble distance(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d b) {\n    double distance = 0;\n    for(int i = 0; i < D; i++) {\n      distance += pow(a[i] - b[i], 2);\n    }\n    return distance;\n  }\n\n// compute distance of all points in vector to another point v\ntemplate<int D>\nstd::vector<double> neighbors_distance(\n  std::set<typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Vertex_handle> neighs, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d st_proj,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d cur_n) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n    typedef typename DT::Vertex_handle Vertex_handle;\n    typedef std::set<Vertex_handle> Vertex_set;\n    std::vector<double> nei_dists;\n    for(typename Vertex_set::iterator neighs_it = neighs.begin(); \n    neighs_it != neighs.end(); neighs_it++) {\n      Point n = (*neighs_it)->point();\n      // remove the n on the voronoi edge from the neighbors list \n      if(n == cur_n) continue;\n      nei_dists.push_back(distance<D>(n, st_proj));\n    }\n    return nei_dists;\n  }\n\n// return dot product of two points\ntemplate<int D>\ndouble compute_dot_product(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d b) {\n    double product = 0;\n    for(int i = 0; i < D; i++) {\n      product += a[i] * b[i];\n    }\n    return product;\n  }\n\n// assign the bounding value for edge\ntemplate<int D>\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d assign_vals(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n    double new_a[D];\n\n    for(int i = 0; i < D; i++) {\n      if(a[i] < lower_bound ) {\n        new_a[i] = lower_bound;\n      } else if (a[i] > upper_bound) {\n        new_a[i] = upper_bound;\n      }\n    }\n    Point result(&new_a[0], &new_a[D]);\n    return result;\n}\n\n// return addition of point\ntemplate<int D>\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d point_addition(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d b) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n\n    // std::vector<double> sum;\n    double sum[D];\n    // sum.reserve(D);\n    for(int i = 0; i < D; i++) {\n      sum[i] = a[i] + b[i];\n      // sum.push_back(a[i] + b[i]);\n    }\n    Point result(&sum[0], &sum[D]);\n    // Point result(&sum.at(0), &sum.at(sum.size() - 1));\n    return result;\n  }\n\n// return multiplication of a point and a constant double\ntemplate<int D>\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d point_mul(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d a, \n  double b) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n\n    // std::vector<double> mul;\n    // mul.reserve(D);\n    double mul[D];\n    for(int i = 0; i < D; i++) {\n      mul[i] = a[i]*b;\n      // mul.push_back(a[i]*b);\n    }\n    Point result(&mul[0], &mul[D]);\n    // Point result(&mul.at(0), &mul.at(mul.size() - 1));\n    return result;\n  }\n\n// return whether right point is larger than left point in a given direction\ntemplate<int D>\nbool is_larger(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d right, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d left,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d direction) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n\n    Point diff = point_addition<D>(right, point_mul<D>(left,  -1.0));\n    // since right = left + direction * constant\n    // constant is the same for all direction, we only need to check first poistion's c\n    double diff_0 = diff[0];\n    double direction_0 = direction[0];\n    double c = diff_0 / direction_0;\n    return c > 0;\n  }\n\n\n// return the projection of a point on half space\ntemplate<int D>\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d projection(\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d v, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d w,\n  double c) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n\n    // v - v*unit_w*w + c*unit_w \n    double w_norm = sqrt(compute_dot_product<D>(w,w));\n    Point unit_w = point_mul<D>(w, 1/w_norm);\n    double proj_normal_length = compute_dot_product<D>(v, unit_w);\n    Point proj_normal = point_mul<D>(w, proj_normal_length);\n    Point proj_v = point_addition<D>(v, proj_normal);\n    Point offset = point_mul<D>(unit_w, c);\n    return point_addition<D>(proj_v, offset);\n  }\n\n// binary search get start and end of the voronoi edge\ntemplate<int D>\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d binary_search(\n  std::set<typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Vertex_handle> neighs,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d cur_n,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d start, \n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d direction,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d v,\n  typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d w,\n  double c,  double cur_dist, double min_nei_dist, bool reverse) {\n    typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point_d Point;\n\n    Point original_dir = direction;\n    Point left = start;\n    Point right = start;\n    Point right_proj;\n    double mul = 2.0;\n    std::vector<double> nei_dists;\n    \n    // reverse = true if we want find end point in case 1/ start/end point in case 2: \n    // first point closer to other neighs than v: distance(v, proj_pt) >= min_nei_dist\n    if(reverse) {\n      cur_dist *= -1.0;\n      min_nei_dist *= -1.0;\n    }\n\n    // find the range of the point\n\n    // find start in case 1: first point closer to v than to other neighs \n    // i.e. distance(v, proj_pt) <= min_nei_dist if reverse -> \">=\"\n    while(check_boundary<D>(right) && cur_dist > min_nei_dist) {\n      left = right;\n      direction = point_mul<D>(direction, mul);\n      right = point_addition<D>(right, direction);\n      right_proj = projection<D>(right, w, c);\n      cur_dist = reverse? -1.0 * distance<D>(right_proj, v) : distance<D>(right_proj, v);\n      nei_dists = neighbors_distance<D>(neighs, right_proj, cur_n);\n      min_nei_dist = *std::min_element(nei_dists.begin(), nei_dists.end());\n      min_nei_dist = reverse? -1.0 * min_nei_dist : min_nei_dist;\n    }\n\n    // get `right` inside the boundary if it's out \n    // may because the step size is too large that we skip the voronoi edge\n    if(!check_boundary<D>(right)) {\n      if(cur_dist > min_nei_dist) {\n        // case 1: cur_dist > min_nei_dist: redo it with small step size, \n        right = start;\n        direction = original_dir;\n        while(check_boundary<D>(right) && cur_dist > min_nei_dist) {\n          left = right;\n          right = point_addition<D>(right, direction);\n          right_proj = projection<D>(right, w, c);\n          cur_dist = reverse? -1.0 * distance<D>(right_proj, v) : distance<D>(right_proj, v);\n          nei_dists = neighbors_distance<D>(neighs, right_proj, cur_n);\n          min_nei_dist = *std::min_element(nei_dists.begin(), nei_dists.end());\n          min_nei_dist = reverse? -1.0 * min_nei_dist : min_nei_dist;\n        }\n      } else {\n        // case 2: cur_dist <= min_nei_dist: get all the points within bound\n        right = assign_vals<D>(right);\n      }\n    }\n    \n    Point mid;\n    Point mid_proj;\n    // (right - left)/ direction > 0\n    while(is_larger<D>(right, left, original_dir)) {\n      Point diff = point_mul<D>(point_addition<D>(right, point_mul<D>(left, -1.0)), 1/2.0);\n      // get mid point\n      mid = point_addition<D>(left, diff);\n      mid_proj = projection<D>(mid, w, c);\n      cur_dist = reverse? -1.0 * distance<D>(mid_proj, v) : distance<D>(mid_proj, v);\n      nei_dists = neighbors_distance<D>(neighs, mid_proj, cur_n);\n      min_nei_dist = *std::min_element(nei_dists.begin(), nei_dists.end());\n      min_nei_dist = reverse? -1.0 * min_nei_dist : min_nei_dist;\n\n      // if midpoint out of bound or midpoint is closer to v than all the other neighbors\n      if(!check_boundary<D>(mid) || cur_dist <= min_nei_dist) {\n        right = mid;\n      } else {\n        left = point_addition<D>(mid, original_dir);\n      }\n    }\n\n    return right;\n  }\n\ntemplate<int D>\nstd::vector<typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d>\nfind_voronoi_edge(\nstd::set<typename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Vertex_handle> neighs,\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d cur_n,\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d lp,\ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d v, \ntypename CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<D>>>::Point_d w, double c) {\n  \n  typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n  typedef CGAL::Delaunay_triangulation<K> DT;\n  typedef typename DT::Point_d Point;\n  typedef typename DT::Vertex_handle Vertex_handle;\n  typedef std::set<Vertex_handle> Vertex_set;\n\n  std::vector<double> dummy = std::vector<double>(D + 1, 0.5);\n  int end = dummy.size() - 1;\n\n  Point start(&dummy.at(0), &dummy.at(end));\n\n  double sum = 0;\n  // projection of point onto plane\n  Point st_proj = projection<D>(start, w, c);\n  // calculate v's neighbors' distance \n  std::vector<double> nei_dists = neighbors_distance<D>(neighs, st_proj, cur_n);\n\n  double cur_dist = distance<D>(st_proj, v);\n  double min_nei_dist = *std::min_element(nei_dists.begin(), nei_dists.end());\n  \n  Point start_vor;\n  Point end_vor;\n\n  // generate random direction to walk [current random seed based on time]\n  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  std::default_random_engine generator (seed);\n  std::uniform_int_distribution<int> dist(-1 , 1);\n  double direct = dist(generator); // -1 or 1 \n  direct *= step_size;\n\n  // case 1: st_proj isn’t included in the voronoi edge \n  if(cur_dist > min_nei_dist) {\n    Point point_direct = point_mul<D>(lp, direct);\n    Point st2 = point_addition<D>(start, point_direct);\n    Point st2_proj = projection<D>(st2, w, c);\n    double temp_dist = distance<D>(st2_proj, v);\n    //oof, we are moving the wrong direction:\n    if(temp_dist > cur_dist) {\n      point_direct = point_mul<D>(point_direct, -1.0); // flip the direction\n    }\n    \n    start_vor = \n    binary_search<D>(neighs, cur_n, start, point_direct, v, w, c, cur_dist, min_nei_dist, false);\n\n    Point start_vor_proj = projection<D>(start, w, c);\n    double dist = distance<D>(start_vor_proj, v);\n    nei_dists = neighbors_distance<D>(neighs, start_vor_proj, cur_n);\n    double temp_min_nei_dist = *std::min_element(nei_dists.begin(), nei_dists.end());\n    end_vor = \n    binary_search<D>(neighs, cur_n, start_vor, point_direct, v, w, c, dist, temp_min_nei_dist, true);\n\n  } else {\n    Point point_direct = point_mul<D>(w, direct);\n    Point another_point_direct = point_mul<D>(point_direct, -1.0); // flip the direction\n    start_vor = \n    binary_search<D>(neighs, cur_n, start, point_direct, v, w, c, cur_dist, min_nei_dist, true);\n    end_vor =  \n    binary_search<D>(neighs, cur_n, start, another_point_direct, v, w, c, cur_dist, min_nei_dist, true);\n  }\n\n  std::vector<Point> result;\n  result.reserve(2);\n  result.push_back(start_vor);\n  result.push_back(end_vor);\n\n  return result;\n}\n\n// build LSH\ntemplate<int D>\nstd::vector<std::vector<std::vector<double>>> compute_LSH(std::string file_name, \nstd::size_t N, std::size_t num_proj, double bucket_size)\n{\n  typedef CGAL::Epick_d<CGAL::Dimension_tag<D>> K;\n  typedef CGAL::Delaunay_triangulation<K> DT;\n\n  typedef typename DT::Vertex Vertex;\n  typedef typename DT::Vertex_handle Vertex_handle;\n  typedef typename DT::Full_cell Full_cell;\n  typedef typename DT::Full_cell_handle Full_cell_handle;\n  typedef typename DT::Facet Facet;\n  typedef typename DT::Point_d Point;\n  typedef typename DT::Geom_traits::RT RT;\n  typedef typename DT::Finite_full_cell_const_iterator Finite_full_cell_const_iterator;\n  typedef typename DT::Finite_vertex_iterator Finite_vertex_iterator;\n  typedef typename DT::Vertex_iterator Vertex_iterator;\n  typedef typename DT::Face Face;\n  typedef std::set<Vertex_handle> Vertex_set;\n  typedef std::vector<Face> Faces;\n  typedef CGAL::Random_points_in_cube_d<Point> Random_points_iterator;\n\n  CGAL::Timer cost;  // timer\n  std::vector<Point> points;\n\n  // Generate points\n  #ifdef RANDOM_PTS\n  CGAL::Random rng;\n  Random_points_iterator rand_it(D, 1.0, rng); // generate point within the cube with length 1\n  std::copy_n(rand_it, N, std::back_inserter(points));\n  #endif\n\n  std::string full_file_name = path_prefix + file_name;\n\n  // CSVReader reader(full_file_name);\n  std::cout <<\"          Reading file: \" << file_name << std::endl;\n\n  // Get the data from CSV File\n  std::vector<std::vector<double> > data_vec = read_data(full_file_name, D);\n\n  // construct points\n  for(int i = 0; i < data_vec.size(); i++) {\n    std::vector<double> cur = data_vec.at(i);\n    double temp[cur.size()];\n    std::copy(cur.begin(), cur.end(), temp);\n    Point p(&temp[0], &temp[cur.size()]);\n    points.push_back(p);\n  }\n\n  #ifdef READ_PTS\n  for(int i = 0; i < D; i++) {\n    std::cout << \"Points 0[ \" << i << \"]\"<< points.at(0)[i] << std::endl;\n  }\n  #endif\n\n  cost.reset();\n  cost.start();\n\n  N = data_vec.size();\n  std::cout << \"Delaunay triangulation of \" << N <<\n    \" points in dim \" << D << \":\" << std::endl;\n\n  // create delaunay triangulation with dimension D\n  DT dt(D);\n  \n  dt.insert(points.begin(), points.end());\n\n  // assert the delaunay triangle is valid\n  CGAL_assertion(dt.is_valid());\n\n  // generate random line passing through (0,0), stored it in vector<Point> w\n  std::default_random_engine generator;\n  double cur[D] = {};\n  // randomly generate pts from standard normal distribution\n  std::normal_distribution<double> distribution(0.0, 1.0);\n  std::vector<Point> proj_lines;\n\n  double sum_sqr;\n  for(int i= 0; i< num_proj; ++i) {\n    sum_sqr = 0.0;\n    for(int j = 0; j < D; j++) {\n        cur[j]= distribution(generator);\n        sum_sqr += pow(cur[j], 2);\n    }\n\n    // check not divide by zero, add a really small constant \n    // divide by norm + e^-10\n    double norm = sqrt(sum_sqr);\n    if(norm == 0) norm += 1e-9;\n    for(int j = 0; j < D; j++) {\n        cur[j] /= norm;\n    }\n\n    Point p(&cur[0], &cur[D]);\n    proj_lines.push_back(p);\n    std::cout << \"\\n\" << std::endl;\n  }\n\n  int max_bucket = 2 * std::ceil(sqrt(D) / bucket_size); \n  int bound = max_bucket / 2;\n  int num_edges = 0;\n\n  // generate all the neighs for each vertices \n  // calculate the #edges for all \n  Vertex_iterator fvit = dt.vertices_begin();\n  for (;fvit != dt.vertices_end(); fvit++) {\n    if(dt.is_infinite(fvit)) continue;\n    Vertex_handle curr = fvit;\n    // circulate through incident full cells to get all neighbors of current vertex\n    std::vector<Full_cell_handle> neigh_full_cellss;\n    dt.tds().incident_full_cells(curr, back_inserter(neigh_full_cellss));\n    Vertex_handle vhh;\n    for(typename std::vector<Full_cell_handle>::iterator it = neigh_full_cellss.begin(); \n    it != neigh_full_cellss.end(); ++it ) {\n        for( int i = 0; i <= dt.current_dimension(); ++i )\n        {\n            vhh = (*it)->vertex(i);\n            if( dt.is_infinite(vhh) || vhh ==  curr)\n                continue;\n            num_edges++;\n        }\n    }\n  }\n\n\n  std::vector<std::vector<std::vector<double>>> buks(num_proj, \n  std::vector<std::vector<double>>(max_bucket, std::vector<double>(num_edges)));\n\n  // double buks[num_proj][max_bucket][num_edges];\n\n  // iterate through all vertices\n  fvit = dt.vertices_begin();\n  for (;fvit != dt.vertices_end(); fvit++) {\n    if(dt.is_infinite(fvit)) continue;\n    Vertex_handle cur = fvit;\n    Point v = cur->point();\n    // circulate through incident full cells to get all neighbors of current vertex\n    std::vector<Full_cell_handle> neigh_full_cells;\n    dt.tds().incident_full_cells(cur, back_inserter(neigh_full_cells));\n    Vertex_set neighs;\n    Vertex_handle vh;\n    for(typename std::vector<Full_cell_handle>::iterator it = neigh_full_cells.begin(); \n    it != neigh_full_cells.end(); ++it ) {\n        for( int i = 0; i <= dt.current_dimension(); ++i )\n        {\n            vh = (*it)->vertex(i);\n            if( dt.is_infinite(vh) || vh ==  cur)\n                continue;\n            neighs.insert(vh);\n        }\n    }\n    \n    int idx = 0;\n    Point n;\n    // iterate through neighbors\n    for(typename Vertex_set::iterator neighs_it = neighs.begin(); \n    neighs_it != neighs.end(); neighs_it++) {\n      n = (*neighs_it)->point();\n\n      // find the half space\n      Point w = point_addition<D>(v, point_mul<D>(n, -1.0)); // v - n\n\n      Point half_point = point_mul<D>(point_addition<D>(n, v), 1 /2.0); // (n + v) / 2\n      \n      double product = compute_dot_product<D>(w, half_point);\n\n      // iterate through project line\n      for(std::size_t i = 0; i != proj_lines.size(); i++) {\n        Point lp = proj_lines[i];\n        std::vector<Point> edge = find_voronoi_edge<D>(neighs, n, lp, v, w, product);\n\n        Point start = edge.at(0);\n        Point end = edge.at(1);\n        // project the start and end point to the line\n        double a = compute_dot_product<D>(w, start);\n        double b = compute_dot_product<D>(w, end);\n        int s_idx = std::max(ceil(std::min(a,b)), lower_bound);\n        int e_idx = std::min(upper_bound, ceil(std::max(a,b)));\n\n        std::cout<< \"s_idx \" << \"line: \"<<i<< \" neigh: \"<<idx << \" is \" << s_idx << std::endl;\n        std::cout<< \"e_idx \" << \"line: \"<<i<< \" neigh: \"<<idx << \" is \" << e_idx << std::endl;\n\n        for(int s = s_idx; s != e_idx + 1; s++) {\n          // buks[i][s][idx] += 1;\n          buks.at(i).at(s).at(idx) += 1;\n        }\n      }\n      // std::cout << \"I am here ------------\" << std::endl;\n      idx++;\n    }\n  }\n\n  double timing = cost.time();\n\n  std::cout<< \"Total computation time is: \" << timing << std::endl;\n  return buks;\n\n}\n\n\nint main(int argc, char **argv)\n{\n    srand(static_cast<unsigned int>(time(NULL)));\n\n    std::vector<std::vector<std::vector<double>>> lsh_buk = \n    compute_LSH<2>(\"data.csv\", 10, 5, 0.1);\n\n    return 0;\n}\n#endif\n\n// FIXME: low dimension, 3 , put 5 - 10 points, know exactly the edges \n// fix the projection line [eliminate all randomness]\n// get the neighbors, check correct\n// get the voronoi edges, check\n// test the projection\n// ", "meta": {"hexsha": "1e0fe64e16fa3914cd4bd98697ea675f2124d73c", "size": 22174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archived/cpp/LSH.cpp", "max_stars_repo_name": "wagner-group/geoadex", "max_stars_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-01T18:18:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T05:58:57.000Z", "max_issues_repo_path": "archived/cpp/LSH.cpp", "max_issues_repo_name": "wagner-group/geoadex", "max_issues_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archived/cpp/LSH.cpp", "max_forks_repo_name": "wagner-group/geoadex", "max_forks_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_forks_repo_licenses": ["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.0552845528, "max_line_length": 112, "alphanum_fraction": 0.6622621088, "num_tokens": 6454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5781106747815351}}
{"text": "/*\n * Copyright (c) 2013-2019 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_MAFFINE2_HPP\n#define ODE_MAFFINE2_HPP\n\n// ODE using Affine and Mean Value Form (fast)\n\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/psa.hpp>\n#include <kv/affine.hpp>\n#include <kv/ode.hpp>\n#include <kv/ode-autodif.hpp>\n#include <kv/ode-param.hpp>\n#include <kv/ode-callback.hpp>\n\n\n#ifndef ODE_FAST\n#define ODE_FAST 1\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nvoid\node_onlytype1(F f, ub::vector< interval<T> >& init, const interval<T>& start, const interval<T>& end, int order) {\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< psa< interval<T> > > x, y;\n\tpsa< interval<T> > torg;\n\tpsa< interval<T> > t;\n\n\tub::vector< interval<T> > result;\n\n\tinterval<T> deltat;\n\n\tbool save_mode, save_uh, save_rh;\n\n\n\tx = init;\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa< interval<T> >::mode();\n\tsave_uh = psa< interval<T> >::use_history();\n\tsave_rh = psa< interval<T> >::record_history();\n\tpsa< interval<T> >::mode() = 1;\n\tpsa< interval<T> >::use_history() = false;\n\tpsa< interval<T> >::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa< interval<T> >::record_history() = true;\n\tpsa< interval<T> >::history().clear();\n\t#endif\n\tfor (j=0; j<order; j++) {\n\t\t#if ODE_FAST == 1\n\t\tif (j == 1) psa< interval<T> >::use_history() = true;\n\t\tif (j == order - 1) psa< interval<T> >::record_history() = false;\n\t\t#endif\n\t\tt = setorder(torg, j);\n\t\ty = f(x, t);\n\t\tfor (i=0; i<n; i++) y(i) = integrate(y(i));\n\t\tx = init + y;\n\t}\n\n\tdeltat = end - start;\n\n\tresult.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tresult(i) = eval(x(i), deltat);\n\t}\n\n\tinit = result;\n\n\tpsa< interval<T> >::mode() = save_mode;\n\tpsa< interval<T> >::use_history() = save_uh;\n\tpsa< interval<T> >::record_history() = save_rh;\n}\n\n\ntemplate <class T, class F>\nvoid\node_onlytype1(F f, ub::vector< autodif< interval<T> > >& init, const interval<T>& start, const interval<T>& end, int order) {\n\tint n = init.size();\n\tint i, j, k;\n\n\tub::vector< psa< autodif< interval<T> > > > x, y;\n\tpsa< autodif< interval<T> > > torg;\n\tpsa< autodif< interval<T> > > t;\n\n\tub::vector< autodif< interval<T> > > result;\n\n\tinterval<T> deltat;\n\n\tbool save_mode, save_uh, save_rh;\n\n\n\tx = init;\n\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa< autodif< interval<T> > >::mode();\n\tsave_uh = psa< autodif< interval<T> > >::use_history();\n\tsave_rh = psa< autodif< interval<T> > >::record_history();\n\tpsa< autodif< interval<T> > >::mode() = 1;\n\tpsa< autodif< interval<T> > >::use_history() = false;\n\tpsa< autodif< interval<T> > >::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa< autodif< interval<T> > >::record_history() = true;\n\tpsa< autodif< interval<T> > >::history().clear();\n\t#endif\n\tfor (j=0; j<order; j++) {\n\t\t#if ODE_FAST == 1\n\t\tif (j == 1) psa< autodif< interval<T> > >::use_history() = true;\n\t\tif (j == order - 1) psa< autodif< interval<T> > >::record_history() = false;\n\t\t#endif\n\t\tt = setorder(torg, j);\n\t\ty = f(x, t);\n\t\tfor (i=0; i<n; i++) y(i) = integrate(y(i));\n\t\tx = init + y;\n\t}\n\n\tdeltat = end - start;\n\n\tresult.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tresult(i) = eval(x(i), (autodif< interval<T> >)deltat);\n\t}\n\n\tinit = result;\n\n\tpsa< autodif< interval<T> > >::mode() = save_mode;\n\tpsa< autodif< interval<T> > >::use_history() = save_uh;\n\tpsa< autodif< interval<T> > >::record_history() = save_rh;\n}\n\n\ntemplate <class T, class F>\nint\node_maffine2(F f, ub::vector< affine<T> >& init, const interval<T>& start, interval<T>& end, ode_param<T> p = ode_param<T>(), ub::vector< psa< interval<T> > >* result_psa = NULL)\n{\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< interval<T> > c;\n\tub::vector< interval<T> > fc;\n\tub::vector< interval<T> > I, Idummy, I2;\n\tub::vector< autodif< interval<T> > > Iad;\n\n\tub::vector< interval<T> > result_i;\n\tub::matrix< interval<T> > result_d;\n\n\tub::vector< affine<T> > result;\n\n\tint maxnum_save;\n\n\tinterval<T> deltat_n;\n\tub::vector< psa< interval<T> > > psa_result;\n\n\tint r;\n\n\tinterval<T> end2 = end;\n\n\n\tI.resize(n);\n\tc.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tI(i) = to_interval(init(i));\n\t\tc(i) = mid(I(i));\n\t}\n\n\tIdummy = I;\n\tr = ode(f, Idummy, start, end2, p, &psa_result);\n\tif (r == 0) return 0;\n\n\tif (result_psa != NULL) {\n\t\t*result_psa = psa_result;\n\t}\n\n\tdeltat_n = pow(end2 - start, p.order);\n\n\tI2.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tI2(i) = psa_result(i).v(p.order) * deltat_n;\n\t}\n\n\tIad = autodif< interval<T> >::init(I);\n\t// NOTICE: below must be autodif version\n\tode_onlytype1(f, Iad, start, end2, p.order-1);\n\n\tfc = c;\n\tode_onlytype1(f, fc, start, end2, p.order-1);\n\n\tautodif< interval<T> >::split(Iad, result_i, result_d);\n\n\tif (p.ep_reduce == 0) {\n\t\tmaxnum_save = affine<T>::maxnum();\n\t}\n\n\tresult = I2 + fc + prod(result_d, init - c);\n\n\tif (p.ep_reduce == 0) {\n\t\tepsilon_reduce2(result, maxnum_save);\n\t} else {\n\t\tepsilon_reduce(result, p.ep_reduce, p.ep_reduce_limit);\n\t}\n\n\tinit = result;\n\tif (r == 1) end = end2;\n\n\treturn r;\n}\n\ntemplate <class T, class F>\nint\nodelong_maffine2(\n\tF f,\n\tub::vector< affine<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tub::vector< affine<T> > x, x1;\n\tinterval<T> t, t1;\n\tint ret_ode;\n\tint ret_val = 0;\n\tbool ret_callback;\n\n\tub::vector< psa< interval<T> > > result_tmp;\n\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\n\twhile (1) {\n\t\tx1 = x;\n\t\tt1 = end;\n\n\t\tret_ode = ode_maffine2(f, x1, t, t1, p, &result_tmp);\n\t\tif (ret_ode == 0) {\n\t\t\tif (ret_val == 1) {\n\t\t\t\tinit = x1;\n\t\t\t\tend = t;\n\t\t\t}\n\t\t\treturn ret_val;\n\t\t}\n\t\tret_val = 1;\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << to_interval(x1) << \"\\n\";\n\t\t}\n\n\t\tret_callback = callback(t, t1, to_interval(x), to_interval(x1), result_tmp);\n\n\t\tif (ret_callback == false) {\n\t\t\tinit = x1;\n\t\t\tend = t1;\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (ret_ode == 2) {\n\t\t\tinit = x1;\n\t\t\treturn 2;\n\t\t}\n\n\t\tt = t1;\n\t\tx = x1;\n\t}\n}\n\ntemplate <class T, class F>\nint\nodelong_maffine2(\n\tF f,\n\tub::vector< interval<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tint i;\n\tub::vector< affine<T> > x;\n\tint maxnum_save;\n\tint r;\n\n\tmaxnum_save = affine<T>::maxnum();\n\taffine<T>::maxnum() = 0;\n\tx = init;\n\n\tr = odelong_maffine2(f, x, start, end, p, callback);\n\n\taffine<T>::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tfor (i=0; i<s; i++) init(i) = to_interval(x(i));\n\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // ODE_MAFFINE2_HPP\n", "meta": {"hexsha": "d0a6b982fd7c1cd179a97f902335f3f4a7bc41b6", "size": 6768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-maffine2.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/ode-maffine2.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/ode-maffine2.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.15, "max_line_length": 178, "alphanum_fraction": 0.6100768322, "num_tokens": 2369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5781106730708708}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2015  IBM Corporation and others\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 GaussianProcess_hpp\n#define GaussianProcess_hpp\n\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <complex>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n\n#include \"KernelFunction.hpp\"\n#include \"MathUtils.hpp\"\n\nnamespace loc{\n    \n    class GaussianProcessParameterSet{\n    public:\n        std::vector<double> sigmaFs{1,2,3,5};\n        std::vector<double> lengthes{1,2,3,4,5,7,9};\n        std::vector<double> lengthFloors{0.01};\n        std::vector<double> sigmaNs{1};\n    };\n    \n    class GaussianProcessParameters{\n    public:\n        GaussianKernel::Parameters gaussianKernelParameters;\n        double sigmaN;\n    };\n    \n    class GaussianProcess{\n        \n    private:\n        // variables to be serialized\n        ////std::shared_ptr<KernelFunction> mKernel;\n        GaussianKernel mGaussianKernel;\n        Eigen::MatrixXd X_;\n        Eigen::MatrixXd Weights_;\n        double sigmaN_ = 1.0;\n        \n        // variables not to be serialized\n        Eigen::MatrixXd Y_;\n        Eigen::MatrixXd K_;\n        Eigen::MatrixXd Ky_;\n        Eigen::MatrixXd invKy_;\n        Eigen::MatrixXd Actives_;\n        GaussianProcessParameterSet mParameterSet;\n        \n    public:\n        // A function for serealization\n        template<class Archive>\n        void serialize(Archive& ar);\n        \n        virtual GaussianProcess& sigmaN(double sigmaN);\n        virtual double sigmaN() const;\n        /*\n        GaussianProcess& kernel(std::shared_ptr<KernelFunction> kernel){\n            mKernel = kernel;\n            return *this;\n        }\n        */\n        virtual GaussianProcess& gaussianProcessParameterSet(const GaussianProcessParameterSet&);\n        virtual GaussianProcess& gaussianKernel(GaussianKernel gaussianKernel);\n        virtual GaussianKernel gaussianKernel() const;\n        \n        virtual Eigen::MatrixXd X() const;\n        virtual Eigen::MatrixXd Y() const;\n        virtual GaussianProcess& fit(const Eigen::MatrixXd & X, const Eigen::MatrixXd& Y);\n        virtual GaussianProcess& fit(const Eigen::MatrixXd & X, const Eigen::MatrixXd& Y, const Eigen::MatrixXd& Actives);\n        virtual GaussianProcess& actives(const Eigen::MatrixXd& Actives);\n        \n        virtual Eigen::MatrixXd computeKernelMatrix(const Eigen::MatrixXd& X);\n        virtual Eigen::VectorXd computeKstar(double x[]) const;\n        \n        virtual Eigen::VectorXd predict(double x[]) const;\n        virtual Eigen::VectorXd predict(const Eigen::VectorXd& kstar) const;\n        \n        virtual double predict(double x[], int index);\n        virtual std::vector<double> predict(double x[], const std::vector<int>& indices) const;\n        virtual std::vector<double> predict(const Eigen::VectorXd& kstar, const std::vector<int>& indices) const;\n        virtual Eigen::VectorXd predictVarianceF(double x[]) const;\n        virtual Eigen::VectorXd predictVarianceF(const Eigen::VectorXd& kstar) const;\n        \n        virtual double computeLogLikelihood(double x[], const Eigen::VectorXd& y) const;\n        virtual double marginalLogLikelihood();\n        virtual double predictiveLogLikelihood();\n        virtual double leaveOneOutMSE();\n        \n        virtual std::vector<GaussianProcessParameters> createParameterMatrix(const GaussianProcessParameterSet&) const;\n        virtual void fitCV(const Eigen::MatrixXd & X, const Eigen::MatrixXd& Y, const Eigen::MatrixXd& Actives);\n    };\n}\n\n#endif /* GaussianProcess_hpp */\n", "meta": {"hexsha": "26d63d1ac8023f2c5738d8d38c8f14af7c007a4e", "size": 4790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/model/GaussianProcess.hpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ble-cpp/src/model/GaussianProcess.hpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ble-cpp/src/model/GaussianProcess.hpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["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.9166666667, "max_line_length": 122, "alphanum_fraction": 0.6622129436, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5780818829162179}}
{"text": "/*************************************************************************\n\t> File Name: main.cpp\n\t> Author: TAI Lei\n\t> Mail: ltai@ust.hk\n\t> Created Time: Thu Mar  7 19:39:14 2019\n ************************************************************************/\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Eigen>\n#include \"csv_reader.h\"\n#include \"motion_model.h\"\n#include \"trajectory_optimizer.h\"\n\n#define L 1.0\n#define DS 0.1\n#define CONST_V 3.0  // use a const linear velocity here\ntypedef std::vector<std::vector<float>> Table;\n\nusing namespace cpprobotics;\n\nStateList sample_states(std::vector<float> angle_samples,\n                        float a_min, float a_max,\n                        int d, float p_max, float p_min, int nh){\n  StateList states;\n  for(float item:angle_samples){\n    float a = a_min + ( a_max - a_min ) * item;\n    for(int j=0; j<nh; j++){\n      float xf = d * std::cos(a);\n      float yf = d * std::sin(a);\n      float yawf;\n      if(nh == 1) yawf = (p_max - p_min)/2.0 + a;\n      else yawf = p_min + (p_max - p_min) * j /(nh-1) + a;\n      states.push_back(TrajState(xf, yf, yawf));\n    }\n  }\n  return states;\n};\n\nStateList calc_uniform_polar_states(int nxy, int nh, int d,\n                                    float a_min, float a_max,\n                                    float p_min, float p_max){\n  std::vector<float> angle_samples;\n  for(int i=0; i<nxy; i++){\n    angle_samples.push_back(i*1.0/(nxy-1));\n  }\n  StateList states = sample_states(angle_samples, a_min, a_max, d, p_max, p_min, nh);\n  return states;\n};\n\nStateList calc_biased_polar_states(float goal_angle, int ns, int nxy,\n                                   int nh, int d,\n                                   float a_min, float a_max,\n                                   float p_min, float p_max){\n  std::vector<float> asi;\n  std::vector<float> cnav;\n  float cnav_max = std::numeric_limits<float>::min();\n  float cnav_sum = 0;\n  for(int i=0; i<ns-1; i++){\n    float asi_sample = a_min + (a_max - a_min)*i/(ns-1);\n    asi.push_back(asi_sample);\n    float cnav_sample = M_PI - std::abs(asi_sample - goal_angle);\n    cnav.push_back(cnav_sample);\n    cnav_sum += cnav_sample;\n    if (cnav_max < cnav_sample){\n      cnav_max = cnav_sample;\n    }\n  }\n\n  std::vector<float> csumnav;\n  float cum_temp = 0;\n  for(int i=0; i<ns-1; i++){\n    cnav[i] = (cnav_max - cnav[i]) / (cnav_max * ns - cnav_sum);\n    cum_temp += cnav[i];\n    csumnav.push_back(cum_temp);\n  }\n\n  int li = 0;\n  std::vector<float> angle_samples;\n  for(int i=0; i<nxy; i++){\n    for(int j=li; j<ns-1; j++){\n      if (j*1.0/ns >= i*1.0/(nxy -1)){\n        angle_samples.push_back(csumnav[j]);\n        li = j - 1;\n        break;\n      }\n    }\n  }\n\n  StateList states = sample_states(angle_samples, a_min, a_max, d, p_max, p_min, nh);\n  return states;\n};\n\nStateList calc_lane_states(float l_center, float l_heading, float l_width, float v_width, float d, int nxy){\n  float xc = std::cos(l_heading) * d + std::sin(l_heading) * l_center;\n  float yc = std::sin(l_heading) * d + std::cos(l_heading) * l_center;\n\n  StateList states;\n  for(int i=0; i<nxy; i++){\n    float delta = -0.5 * (l_width - v_width) + (l_width - v_width) * i / (nxy -1);\n    float xf = xc - delta * std::sin(l_heading);\n    float yf = yc + delta * std::cos(l_heading);\n    states.push_back(TrajState(xf, yf, l_heading));\n  }\n  return states;\n}\n\nParameter search_nearest_one_from_lookuptable(TrajState target, Table csv_file){\n\n    float min_d = std::numeric_limits<float>::max();\n    int min_id = -1;\n\n    for(unsigned int i=0; i<csv_file.size(); i++)\n    {\n      float dx = target.x - csv_file[i][0];\n      float dy = target.y - csv_file[i][1];\n      float dyaw = target.yaw - csv_file[i][2];\n      float d = std::sqrt(dx * dx + dy * dy + dyaw * dyaw);\n\n      if ( d<min_d ){\n        min_id = i;\n        min_d = d;\n      }\n    }\n    Parameter best_p(std::sqrt(target.x * target.x + target.y * target.y),\n        {{0, csv_file[min_id][4], csv_file[min_id][5]}});\n    return best_p;\n}\n\nstd::vector<Traj> generate_path(StateList states, Table csv_file, float k0=0.0){\n  std::vector<Traj> traj_list;\n  for(TrajState state:states){\n    Parameter   p = search_nearest_one_from_lookuptable(state, csv_file);\n    p.steering_sequence[0] = k0;\n\n    // default settings for this scenario\n    State init_state(0, 0, 0, CONST_V);\n    MotionModel m_model(L, DS, init_state);\n    float cost_th_ = 0.1;\n    std::vector<float> h_step_{0.5, 0.02, 0.02};\n    int max_iter = 100;\n\n    TrajectoryOptimizer traj_opti_obj(m_model, p, state);\n    Traj traj = traj_opti_obj.optimizer_traj(max_iter, cost_th_, h_step_, true, true);\n    traj_list.push_back(traj);\n  }\n  return traj_list;\n};\n\nstd::vector<Traj> uniform_terminal_state_sample_test(Table csv_file){\n  float k0 = 0.0;\n  int nxy = 5;  // number of position sampling\n  int nh = 3;  // number of heading sampling\n  int d = 20; // distance to target\n  float a_min = -45.0/180 * M_PI; // position sampling min angle\n  float a_max = +45.0/180 * M_PI; // position sampling max angle\n  float p_min = -45.0/180 * M_PI; // heading sampling min angle\n  float p_max = +45.0/180 * M_PI; // heading sampling max angle\n\n  StateList states = calc_uniform_polar_states(nxy, nh, d,\n                                               a_min, a_max,\n                                               p_min, p_max);\n\n  std::vector<Traj> traj_list = generate_path(states, csv_file, k0);\n  return traj_list;\n};\n\nstd::vector<Traj> biased_terminal_state_sample_test(Table csv_file){\n  float k0 = 0.0;\n  int nxy = 30;  // number of position sampling\n  int nh = 2;  // number of heading sampling\n  int d = 20; // distance to target\n  float a_min = -45.0/180 * M_PI; // position sampling min angle\n  float a_max = +45.0/180 * M_PI; // position sampling max angle\n  float p_min = -20.0/180 * M_PI; // heading sampling min angle\n  float p_max = +20.0/180 * M_PI; // heading sampling max angle\n\n  int ns = 100;\n  float goal_angle = 0.0;\n  StateList states = calc_biased_polar_states(goal_angle, ns,\n                                              nxy, nh, d,\n                                              a_min, a_max,\n                                              p_min, p_max);\n\n  std::vector<Traj> traj_list = generate_path(states, csv_file, k0);\n  return traj_list;\n};\n\nstd::vector<Traj> lane_state_sample_test(Table csv_file){\n  float k0 = 0.0;\n  float l_center = 10.0;\n  float l_heading = 90.0/180.0 * M_PI;\n  float l_width = 3.0;\n  float v_width = 1.0;\n  int d = 10;\n  int nxy = 5;\n\n  StateList states = calc_lane_states(l_center, l_heading, l_width,\n                                      v_width, d, nxy);\n\n  std::vector<Traj> traj_list = generate_path(states, csv_file, k0);\n  return traj_list;\n};\n\nint main(){\n  //uniform_terminal_state_sample_test1();\n    std::vector<std::vector<float>> lookup_table;\n\n    std::ifstream file(\"../../lookuptable.csv\");\n    CSVIterator loop(file);\n    loop++;\n    for(; loop != CSVIterator(); ++loop)\n    {\n      std::vector<float> temp;\n      for(int i=0; i<6; i++){\n        temp.push_back(std::stod((*loop)[i]));\n      }\n      lookup_table.push_back(temp);\n    }\n    std::vector<Traj> traj_list1 = uniform_terminal_state_sample_test(lookup_table);\n    std::vector<Traj> traj_list2 = biased_terminal_state_sample_test(lookup_table);\n    std::vector<Traj> traj_list3 = lane_state_sample_test(lookup_table);\n\n};\n", "meta": {"hexsha": "61b4a5ba498bf5fc2e8f2679b1d349ab5df95fd9", "size": 7538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/state_lattice_planner.cpp", "max_stars_repo_name": "Singh-sid930/CppRobotics", "max_stars_repo_head_hexsha": "0e4ced2cf1c927156cd3745dee2b2e7250ce95d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-27T07:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T07:54:34.000Z", "max_issues_repo_path": "src/state_lattice_planner.cpp", "max_issues_repo_name": "sweetquiet/CppRobotics", "max_issues_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/state_lattice_planner.cpp", "max_forks_repo_name": "sweetquiet/CppRobotics", "max_forks_repo_head_hexsha": "c5a8cc9a958ee64ab80b9726dc70a3c11f499bd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-11T13:53:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T13:53:59.000Z", "avg_line_length": 32.4913793103, "max_line_length": 108, "alphanum_fraction": 0.6002918546, "num_tokens": 2160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5780818709744545}}
{"text": "//  To use the simple FFT implementation\n//  g++ -o demofft -I.. -Wall -O3 FFT.cpp\n\n//  To use the FFTW implementation\n//  g++ -o demofft -I.. -DUSE_FFTW -Wall -O3 FFT.cpp -lfftw3 -lfftw3f -lfftw3l\n\n#ifdef USE_FFTW\n#include <fftw3.h>\n#endif\n\n#include <vector>\n#include <complex>\n#include <algorithm>\n#include <iterator>\n#include <iostream>\n#include <Eigen/Core>\n#include <unsupported/Eigen/FFT>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename T> T mag2(T a) { return a * a; }\ntemplate <typename T> T mag2(std::complex<T> a) { return norm(a); }\n\ntemplate <typename T> T mag2(const std::vector<T> &vec) {\n    T out = 0;\n    for (size_t k = 0; k < vec.size(); ++k)\n        out += mag2(vec[k]);\n    return out;\n}\n\ntemplate <typename T> T mag2(const std::vector<std::complex<T>> &vec) {\n    T out = 0;\n    for (size_t k = 0; k < vec.size(); ++k)\n        out += mag2(vec[k]);\n    return out;\n}\n\ntemplate <typename T>\nvector<T> operator-(const vector<T> &a, const vector<T> &b) {\n    vector<T> c(a);\n    for (size_t k = 0; k < b.size(); ++k)\n        c[k] -= b[k];\n    return c;\n}\n\ntemplate <typename T> void RandomFill(std::vector<T> &vec) {\n    for (size_t k = 0; k < vec.size(); ++k)\n        vec[k] = T(rand()) / T(RAND_MAX) - .5;\n}\n\ntemplate <typename T> void RandomFill(std::vector<std::complex<T>> &vec) {\n    for (size_t k = 0; k < vec.size(); ++k)\n        vec[k] = std::complex<T>(T(rand()) / T(RAND_MAX) - .5,\n                                 T(rand()) / T(RAND_MAX) - .5);\n}\n\ntemplate <typename T_time, typename T_freq> void fwd_inv(size_t nfft) {\n    typedef typename NumTraits<T_freq>::Real Scalar;\n    vector<T_time> timebuf(nfft);\n    RandomFill(timebuf);\n\n    vector<T_freq> freqbuf;\n    static FFT<Scalar> fft;\n    fft.fwd(freqbuf, timebuf);\n\n    vector<T_time> timebuf2;\n    fft.inv(timebuf2, freqbuf);\n\n    long double rmse = mag2(timebuf - timebuf2) / mag2(timebuf);\n    cout << \"roundtrip rmse: \" << rmse << endl;\n}\n\ntemplate <typename T_scalar> void two_demos(int nfft) {\n    cout << \"     scalar \";\n    fwd_inv<T_scalar, std::complex<T_scalar>>(nfft);\n    cout << \"    complex \";\n    fwd_inv<std::complex<T_scalar>, std::complex<T_scalar>>(nfft);\n}\n\nvoid demo_all_types(int nfft) {\n    cout << \"nfft=\" << nfft << endl;\n    cout << \"   float\" << endl;\n    two_demos<float>(nfft);\n    cout << \"   double\" << endl;\n    two_demos<double>(nfft);\n    cout << \"   long double\" << endl;\n    two_demos<long double>(nfft);\n}\n\nint main() {\n    demo_all_types(2 * 3 * 4 * 5 * 7);\n    demo_all_types(2 * 9 * 16 * 25);\n    demo_all_types(1024);\n    return 0;\n}\n", "meta": {"hexsha": "0225585358e041cb7c6b7639fe2f69e219681e59", "size": 2578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gpu/kinfu_large_scale/src/unsupported/doc/examples/FFT.cpp", "max_stars_repo_name": "yxlao/StanfordPCL", "max_stars_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gpu/kinfu_large_scale/src/unsupported/doc/examples/FFT.cpp", "max_issues_repo_name": "yxlao/StanfordPCL", "max_issues_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gpu/kinfu_large_scale/src/unsupported/doc/examples/FFT.cpp", "max_forks_repo_name": "yxlao/StanfordPCL", "max_forks_repo_head_hexsha": "98a8663f896c1ba880d14efa2338b7cfbd01b6ef", "max_forks_repo_licenses": ["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.5773195876, "max_line_length": 78, "alphanum_fraction": 0.5961986036, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.5780154384463155}}
{"text": "// Copyright 2019 Xanadu Quantum Technologies Inc.\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @file\n * Contains functions for computing the Torontonian using the algorithm described in\n * *A faster hafnian formula for complex matrices and its benchmarking\n * on the Titan supercomputer*, [arxiv:1805.12498](https://arxiv.org/abs/1805.12498)\n */\n#pragma once\n#include <stdafx.h>\n#include <numeric>\n\n#ifdef LAPACKE\n#define EIGEN_SUPERLU_SUPPORT\n#define EIGEN_USE_BLAS\n#define EIGEN_USE_LAPACKE\n\n#define LAPACK_COMPLEX_CUSTOM\n#define lapack_complex_float std::complex<float>\n#define lapack_complex_double std::complex<double>\n#endif\n\n#include <Eigen/Eigenvalues>\n#include \"fsum.hpp\"\n\nnamespace libwalrus {\n/**\n * Given a string of length `len`, finds the positions in which it has a 1\n * and stores its position i, as 2*i and 2*i+1 in consecutive slots\n * of the array pos.\n *\n * It also returns (twice) the number of ones in array dst\n *\n * @param dst character array representing binary digits.\n * @param len length of the array `dst`.\n * @param pos resulting character array of length `2*len` storing\n * the indices at which `dst` contains the values 1.\n * @return returns twice the number of ones in array `dst`.\n */\nvoid find2T (char *dst, Byte len, Byte *pos, char offset)\n{\n    Byte j = offset - 1;\n\n    for (Byte i = 0; i < len; i++) {\n        if (1 == dst[i]) {\n            pos[j] = len - i - 1;\n            pos[j + offset] = 2 * len - i - 1;\n            j--;\n        }\n    }\n}\n\n\n/**\n * Partial sum of a character array\n *\n * @param dst character array\n * @param m sum the first m characters\n *\n * @return the partial sum\n */\nchar sum(char *dst, Byte m) {\n    char sum_tot = 0;\n    for (int i = 0; i < m; i++) {\n        sum_tot += (Byte)dst[i];\n    }\n    return sum_tot;\n}\n\n/**\n * Computes the Torontonian of an input matrix.\n *\n * If the output is NaN, that means that the input matrix does not have\n * a Torontonian with physical meaning.\n *\n * This function uses OpenMP (if available) to parallelize the reduction.\n *\n * @param mat flattened vector of size \\f$n^2\\f$, representing an \\f$n\\times n\\f$\n *       row-ordered symmetric matrix.\n * @return Torontonian of the input matrix\n */\ntemplate <typename T>\ninline T torontonian(std::vector<T> &mat) {\n    int n = std::sqrt(static_cast<double>(mat.size()));\n    Byte m = n / 2;\n    unsigned long long int x = static_cast<unsigned long long int>(pow(2, m));\n\n    namespace eg = Eigen;\n    eg::Matrix<T, eg::Dynamic, eg::Dynamic> A = eg::Map<eg::Matrix<T, eg::Dynamic, eg::Dynamic>, eg::Unaligned>(mat.data(), n, n);\n\n#ifdef _OPENMP\n    int nthreads = omp_get_max_threads();\n    omp_set_num_threads(nthreads);\n#else\n    int nthreads = 1;\n#endif\n\n    std::vector<unsigned long long int> threadbound_low(nthreads);\n    std::vector<unsigned long long int> threadbound_hi(nthreads);\n\n    for (int i = 0; i < nthreads; i++) {\n\n        threadbound_low[i] = i * x / nthreads;\n        threadbound_hi[i] = (i + 1) * x / nthreads;\n    }\n\n\n    std::vector<T> localsum(nthreads);\n\n    #pragma omp parallel for shared(localsum)\n\n    for (int ii = 0; ii < nthreads; ii++) {\n\n        T netsum = static_cast<T>(0.0);\n        for (unsigned long long int k = threadbound_low[ii]; k < threadbound_hi[ii]; k++) {\n\n\n            unsigned long long int xx = k;\n            char* dst = new char[m];\n\n            dec2bin(dst, xx, m);\n            char len = sum(dst, m);\n\n            Byte* short_st = new Byte[2 * len];\n            find2T(dst, m, short_st, len);\n            delete [] dst;\n\n            eg::Matrix<T, eg::Dynamic, eg::Dynamic> B;\n            B.resize(2 * len, 2 * len);\n\n            for (int i = 0; i < 2 * len; i++) {\n                for (int j = 0; j < 2 * len; j++) {\n                    B(i, j) = -A(short_st[i], short_st[j]);\n                }\n            }\n\n            delete [] short_st;\n\n            for (int i = 0; i < 2 * len; i++) {\n                B(i, i) += static_cast<T>(1);\n            }\n\n            T det = std::real(B.determinant());\n\n            if (len % 2 == 0) {\n                netsum += static_cast<T>(1.0) / std::sqrt(det);\n            }\n            else {\n                netsum -= static_cast<T>(1.0) / std::sqrt(det);\n            }\n\n        }\n\n        localsum[ii] = netsum;\n\n    }\n\n    int n_local = localsum.size();\n    T final = 0.0;\n    T sign = 1.0;\n\n    if (m % 2 != 0)\n        sign = -1.0;\n\n    for (int i = 0; i < n_local; i++) {\n        final += localsum[i]    ;\n    }\n\n    return sign * final;\n}\n\n\n/**\n * Computes the Torontonian of an input matrix using the\n * [Shewchuck algorithm](https://github.com/achan001/fsum),\n * a significantly more [accurate summation algorithm](https://link.springer.com/article/10.1007%2FPL00009321).\n *\n * Note that the fsum implementation currently only allows for\n * double precision, and precludes use of OpenMP parallelization.\n *\n * Note: if the output is NaN, that means that the input matrix does not have\n * a Torontonian with physical meaning.\n *\n * @param mat flattened vector of size \\f$n^2\\f$, representing an \\f$n\\times n\\f$\n *       row-ordered symmetric matrix.\n * @return Torontonian of the input matrix\n */\ntemplate <typename T>\ninline double torontonian_fsum(std::vector<T> &mat) {\n    // Here weinput the matrix from python. The variable n is the size of the matrix\n    int n = std::sqrt(static_cast<double>(mat.size()));\n    Byte m = n / 2;\n    unsigned long long int x = static_cast<unsigned long long int>(pow(2, m));\n\n    fsum::sc_partials netsum;\n\n    namespace eg = Eigen;\n    eg::Matrix<T, eg::Dynamic, eg::Dynamic> A = eg::Map<eg::Matrix<T, eg::Dynamic, eg::Dynamic>, eg::Unaligned>(mat.data(), n, n);\n\n    for (int k = 0; k < x; k++) {\n        unsigned long long int xx = k;\n        char* dst = new char[m];\n\n        dec2bin(dst, xx, m);\n        char len = sum(dst, m);\n\n        Byte* short_st = new Byte[2 * len];\n        find2T(dst, m, short_st, len);\n        delete [] dst;\n\n        // eg::Matrix<double,eg::Dynamic,eg::Dynamic> B(2*len, 2*len, 0.);\n        eg::Matrix<T, eg::Dynamic, eg::Dynamic> B;\n        B.resize(2 * len, 2 * len);\n\n        for (int i = 0; i < 2 * len; i++) {\n            for (int j = 0; j < 2 * len; j++) {\n                B(i, j) = -A(short_st[i], short_st[j]);\n            }\n        }\n\n        delete [] short_st;\n\n        for (int i = 0; i < 2 * len; i++) {\n            B(i, i) += 1;\n        }\n\n        long double det = std::real(B.determinant());\n\n        if (len % 2 == 0) {\n            netsum += 1.0 / std::sqrt(det);\n        }\n        else {\n            netsum += -1.0 / std::sqrt(det);\n        }\n    }\n\n    double sign = 1.0;\n\n    if (m % 2 != 0)\n        sign = -1.0;\n\n    return static_cast<double>(netsum) * static_cast<double>(sign);\n}\n\n\n/**\n * Computes the Torontonian of an input matrix.\n *\n * If the output is NaN, that means that the input matrix does not have\n * a Torontonian with physical meaning.\n *\n * This is a wrapper around the templated function `libwalrus::torontonian` for Python\n * integration. It accepts and returns complex double numeric types, and\n * returns sensible values for empty and non-even matrices.\n *\n * In addition, this wrapper function automatically casts all matrices\n * to type `complex<long double>`, allowing for greater precision than supported\n * by Python and NumPy.\n *\n * @param mat flattened vector of size \\f$n^2\\f$, representing an \\f$n\\times n\\f$\n *       row-ordered symmetric matrix.\n * @return Torontonian of the input matrix\n */\nstd::complex<double> torontonian_quad(std::vector<std::complex<double>> &mat) {\n    std::vector<std::complex<long double>> matq(mat.begin(), mat.end());\n    std::complex<long double> tor = torontonian(matq);\n    return static_cast<std::complex<double>>(tor);\n}\n\n\n/**\n * Computes the Torontonian of an input matrix.\n *\n * If the output is NaN, that means that the input matrix does not have\n * a Torontonian with physical meaning.\n *\n * This is a wrapper around the templated function `libwalrus::torontonian` for Python\n * integration. It accepts and returns double numeric types, and\n * returns sensible values for empty and non-even matrices.\n *\n * In addition, this wrapper function automatically casts all matrices\n * to type `long double`, allowing for greater precision than supported\n * by Python and NumPy.\n *\n * @param mat flattened vector of size \\f$n^2\\f$, representing an \\f$n\\times n\\f$\n *       row-ordered symmetric matrix.\n * @return Torontonian of the input matrix\n */\ndouble torontonian_quad(std::vector<double> &mat) {\n    std::vector<long double> matq(mat.begin(), mat.end());\n    long double tor = torontonian(matq);\n    return static_cast<double>(tor);\n}\n\n}\n", "meta": {"hexsha": "bbf799f186341033f335a98edd51f04716989fa2", "size": 9158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/torontonian.hpp", "max_stars_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_stars_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/torontonian.hpp", "max_issues_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_issues_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/torontonian.hpp", "max_forks_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_forks_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_forks_repo_licenses": ["Apache-2.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.8306188925, "max_line_length": 130, "alphanum_fraction": 0.6161825726, "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5780154366166628}}
{"text": "#ifndef _LDAPLUSPLUS_OPTIMIZATION_MULTINOMIAL_LOGISTIC_REGRESSION\n#define _LDAPLUSPLUS_OPTIMIZATION_MULTINOMIAL_LOGISTIC_REGRESSION\n\n#include <cmath>\n\n#include <Eigen/Core>\n\nnamespace ldaplusplus {\nnamespace optimization {\n\n\n/**\n * MultinomialLogisticRegression is an implementation of the multinomial\n * logistic loss function (without bias unit).\n *\n * It follows the protocol used by GradientDescent. For the specific function\n * implementations see value() and gradient().\n */\ntemplate <typename Scalar>\nclass MultinomialLogisticRegression\n{\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixX;\n    typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> VectorX;\n\n    public:\n        /**\n         * @param X  The documents defining the minimization problem (\\f$X \\in\n         *           \\mathbb{R}^{D \\times N}\\f$)\n         * @param y  The class indexes for each document (\\f$y \\in\n         *           \\mathbb{N}^N\\f$)\n         * @param Cy A different weight for each class in the optimization\n         *           problem\n         * @param L  The L2 regularization penalty for the weights\n         */\n        MultinomialLogisticRegression(const MatrixX &X, const Eigen::VectorXi &y, VectorX Cy, Scalar L);\n        /**\n         * @param X  The documents defining the minimization problem (\\f$X \\in\n         *           \\mathbb{R}^{D \\times N}\\f$)\n         * @param y  The class indexes for each document (\\f$y \\in\n         *           \\mathbb{N}^N\\f$)\n         * @param L  The L2 regularization penalty for the weights\n         */\n        MultinomialLogisticRegression(const MatrixX &X, const Eigen::VectorXi &y, Scalar L);\n\n        /**\n         * The value of the objective function to be minimized.\n         *\n         * \\f$N\\f$ is the number of documents (different vectors), \\f$X_n \\in\n         * \\mathbb{R}^D\\f$ is the nth document, \\f$\\eta_y \\in \\mathbb{R}^D\\f$\n         * is the weights vector for the class \\f$y\\f$ defining the hyperplane\n         * that separates class \\f$y\\f$ from all the other, finally \\f$y_n\\f$\n         * is the class of the nth document.\n         *\n         * \\f[\n         *     J = -\\sum_{n=1}^N C_{y_n}\\left(\\eta_{y_n}^T X_n - \\log\\left(\n         *         \\sum_{\\hat{y}=1}^Y \\exp\\left( \\eta_{\\hat{y}}^T X_n \\right)\n         *         \\right)\\right) +\n         *         \\frac{L}{2} \\left\\| \\eta \\right\\|_F^2\n         * \\f]\n         *\n         * @param eta The weights of the linear model (\\f$\\eta \\in\n         *            \\mathbb{R}^{D \\times Y}\\f$)\n         */\n        Scalar value(const MatrixX &eta) const;\n\n        /**\n         * The gradient of the objective function implemented in value().\n         *\n         * We use \\f$I(y) \\in \\mathbb{R}^Y\\f$ as the indicator vector of\n         * \\f$y\\f$ (a vector with all the values 0 except at the yth position).\n         *\n         * \\f[\n         *     \\nabla_{\\eta} J = -\\sum_{n=1}^N C_{y_n} \\left(\n         *         X_n I(y_n)^T -\n         *         \\frac{\\sum_{\\hat{y}=1}^Y X_n I(\\hat{y})^T \\exp(\\eta_{\\hat{y}}^T X_n)}\n         *              {\\sum_{\\hat{y}=1}^Y \\exp(\\eta_{\\hat{y}}^T X_n)}\n         *         \\right) +\n         *         L \\eta\n         * \\f]\n         * \n         * @param eta  The weights of the linear model (\\f$\\eta \\in\n         *             \\mathbb{R}^{D \\times Y}\\f$)\n         * @param grad A matrix of dimensions equal to \\f$\\eta\\f$ that will\n         *             hold the result\n         */\n        void gradient(const MatrixX &eta, Eigen::Ref<MatrixX> grad) const;\n\n    private:\n        const MatrixX &X_;\n        const Eigen::VectorXi &y_;\n        Scalar L_;\n        VectorX Cy_;\n};\n\n\n}  // namespace optimization\n}  // namespace ldaplusplus\n#endif // _LDAPLUSPLUS_OPTIMIZATION_MULTINOMIAL_LOGISTIC_REGRESSION\n", "meta": {"hexsha": "7c91fe112b83f48bdaba1ee83ac19dc326d7c41d", "size": 3751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ldaplusplus/optimization/MultinomialLogisticRegression.hpp", "max_stars_repo_name": "angeloskath/supervised-lda", "max_stars_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-05-25T11:59:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T08:51:41.000Z", "max_issues_repo_path": "include/ldaplusplus/optimization/MultinomialLogisticRegression.hpp", "max_issues_repo_name": "angeloskath/supervised-lda", "max_issues_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2016-06-30T15:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:43:16.000Z", "max_forks_repo_path": "include/ldaplusplus/optimization/MultinomialLogisticRegression.hpp", "max_forks_repo_name": "angeloskath/supervised-lda", "max_forks_repo_head_hexsha": "fe3a39bb0d6c7d0c2a33f069440869ad70774da8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-09-28T14:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T14:22:38.000Z", "avg_line_length": 37.8888888889, "max_line_length": 104, "alphanum_fraction": 0.5603838976, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007393, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5779791949377882}}
{"text": "#ifndef CANNON_PHYSICS_SYSTEMS_KINEMATIC_CAR_H\n#define CANNON_PHYSICS_SYSTEMS_KINEMATIC_CAR_H \n\n#include <random>\n\n#include <ompl/control/ODESolver.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/base/spaces/SO2StateSpace.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n\n#include <Eigen/Dense>\n\n#include <cannon/physics/rk4_integrator.hpp>\n#include <cannon/physics/systems/system.hpp>\n#include <cannon/graphics/geometry/plane.hpp>\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nnamespace oc = ompl::control;\nnamespace ob = ompl::base;\n\nnamespace cannon {\n  namespace physics {\n    namespace systems {\n\n      struct KinCarSystem : System {\n        KinCarSystem(double l = 1.0) : l_(l) {}\n\n        virtual void operator()(const VectorXd& s, VectorXd& dsdt, const double /*t*/) override {\n          double th = s[2];\n          double uv = s[3];\n          double uth = s[4];\n\n          dsdt.resize(5);\n          dsdt[0] = uv * std::cos(th);\n          dsdt[1] = uv * std::sin(th);\n          dsdt[2] = (uv / l_) * std::tan(uth);\n          dsdt[3] = 0.0;\n          dsdt[4] = 0.0;\n        }\n\n        virtual void ompl_ode_adaptor(const oc::ODESolver::StateType& q, \n            const oc::Control* control, oc::ODESolver::StateType& qdot) override {\n\n          const double uv = control->as<oc::RealVectorControlSpace::ControlType>()->values[0];\n          const double uth = control->as<oc::RealVectorControlSpace::ControlType>()->values[1];\n\n          VectorXd s(5);\n          s[0] = q[0];\n          s[1] = q[1];\n          s[2] = q[2];\n          s[3] = uv;\n          s[4] = uth;\n          VectorXd dsdt(5);\n\n          (*this)(s, dsdt, 0.0);\n\n          qdot.resize(q.size(), 0);\n          for (unsigned int i = 0; i < q.size(); i++) {\n            qdot[i] = dsdt[i];\n          }\n        }\n\n        virtual std::tuple<MatrixXd, MatrixXd, VectorXd> get_linearization(const VectorXd& x) override {\n          MatrixXd A = MatrixXd::Identity(3, 3);\n          VectorXd c = x; \n\n          // TODO Don't hardcode timestep at some point\n          double theta = x[2];\n          MatrixXd B(3, 2);\n          B << std::cos(theta) * 0.01, 0,\n               std::sin(theta) * 0.01, 0,\n               0, 0;\n          \n          return std::make_tuple(A, B, c);\n        }\n\n        virtual void\n        get_continuous_time_linearization(const oc::ODESolver::StateType &q,\n                                          Ref<MatrixXd> A,\n                                          Ref<MatrixXd> B) override {\n          // TODO\n          throw std::runtime_error(\"Not implemented yet\");\n        }\n\n        static void ompl_post_integration(const ob::State* /*state*/, const\n            oc::Control* /*control*/, const double /*duration*/, ob::State *result) {\n\n          ob::SO2StateSpace SO2;\n          SO2.enforceBounds(result->as<ob::SE2StateSpace::StateType>()->as<ob::SO2StateSpace::StateType>(1));\n        }\n\n        // Parameters\n        double l_;\n      };\n\n      class KinematicCar {\n        public:\n          KinematicCar() = delete;\n\n          KinematicCar(Vector3d s, Vector3d g) : e_(s_, 4, time_step), start_(s), goal_(g) {\n            std::random_device rd;\n            gen_ = std::mt19937(rd());  \n\n            xy_dis_ = std::uniform_real_distribution<double>(-1.0, 1.0);\n            th_dis_ = std::uniform_real_distribution<double>(-M_PI, M_PI);\n\n            state_ = VectorXd::Zero(5);\n            reset();\n          }\n\n          std::pair<VectorXd, double> step(double uv, double uth) {\n            double clipped_uv = std::max(-1.0, std::min(uv, 1.0));\n            //double clipped_uth = std::max(-M_PI, std::min(uth, M_PI));\n            \n            state_[3] = clipped_uv;\n            state_[4] = uth;\n\n            double goal_r = -std::pow((state_.head(2) - goal_.head(2)).norm(), 2.0);\n            double control_r = -std::pow((std::abs(clipped_uv) + std::abs(uth)), 2.0);\n            double reward = goal_r + 0.001*control_r;\n\n            e_.set_state(state_);\n            state_ = e_.step();\n\n            return std::make_pair(state_.head(3), reward);\n          }\n          \n          VectorXd reset() {\n            //state_.head(3) = start_ + Vector3d::Random() * 0.1;\n            state_[0] = xy_dis_(gen_);\n            state_[1] = xy_dis_(gen_);\n            state_[2] = th_dis_(gen_);\n            \n            state_[3] = 0.0;\n            state_[4] = 0.0;\n\n            return state_.head(3);\n          }\n\n          VectorXd reset(const VectorXd& s) {\n            state_[0] = s[0];\n            state_[1] = s[1];\n            state_[2] = s[2];\n            \n            state_[3] = 0.0;\n            state_[4] = 0.0;\n\n            return state_.head(3);\n\n          }\n\n          // In seconds\n          const double time_step = 0.01;\n\n          KinCarSystem s_;\n          \n        private:\n          RK4Integrator e_;\n\n          VectorXd state_;\n\n          Vector3d start_;\n          Vector3d goal_;\n\n          std::mt19937 gen_;\n          std::uniform_real_distribution<double> xy_dis_;\n          std::uniform_real_distribution<double> th_dis_;\n      };\n\n\n    } // namespace physics\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_SYSTEMS_KINEMATIC_CAR_H */\n", "meta": {"hexsha": "2dc61971b7411c4d7de6adf99d2fad6860aa4ace", "size": 5244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/systems/kinematic_car.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/physics/systems/kinematic_car.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/physics/systems/kinematic_car.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": 29.1333333333, "max_line_length": 109, "alphanum_fraction": 0.5295575896, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5779791941282794}}
{"text": "/** @file\n*****************************************************************************\n\nImplementation of a secret-key lattice-based additively homomorphic\nvector encryption scheme.\n\nSee lwe.hpp\n\n*****************************************************************************\n* @author     Samir Menon, Brennan Shacklett, and David J. Wu\n* @copyright  MIT license (see LICENSE file)\n*****************************************************************************/\n\n#include <cstdlib>\n#include <iostream>\n#include <cassert>\n#include <random>\n#include <cstdint>\n#include <fstream>\n#include <NTL/ZZ.h>\n\n#include \"lwe.hpp\"\n#include <libsnark/common/libsnark_serialization.hpp>\n\nusing namespace std;\nnamespace LWE {\n\nstatic NTL::ZZ_p random(const NTL::ZZ &mod) {\n    // Choose a random value from a space that is 128-bits\n    // longer than the target space, and then round down.\n\n    long num_bytes = NTL::NumBytes(mod) + 16;\n    unsigned char bytes[num_bytes];\n    static ifstream urandom(\"/dev/urandom\", ios::binary);\n    urandom.read(reinterpret_cast<char *>(bytes), num_bytes);\n\n    NTL::ZZ randZZ = NTL::ZZFromBytes(bytes, num_bytes);\n\n    return NTL::to_ZZ_p(randZZ % mod);\n}\n\n// Sample a discrete Gaussian variable using the Box-Muller\n// transform.\nstatic int32_t sample_discrete_gaussian(double stddev) {\n    static const double PI = 4.0*atan(1.0);\n\n    double r1 = ((double) rand()) / RAND_MAX;\n    double r2 = ((double) rand()) / RAND_MAX;\n    double theta = 2*PI*r1;\n\n    return (int32_t) floor(stddev * sqrt(-2.0*log(r2)) * cos(theta) + 0.5);\n}\n\nciphertext& ciphertext::operator=(const ciphertext& other) {\n    NTL::ZZ_p::init(LWE::q);\n\n    this->ctxt = other.ctxt;\n\n    return *this;\n}\n\nciphertext ciphertext::operator+(const ciphertext &other) const {\n    ciphertext sum = *this;\n    sum += other;\n\n    return sum;\n}\n\nciphertext& ciphertext::operator+=(const ciphertext &other) {\n    NTL::ZZ_p::init(LWE::q);\n\n    this->ctxt += other.ctxt;\n    return *this;\n}\n\nciphertext ciphertext::operator*(uint64_t val) const {\n    return operator*(NTL::ZZ_p(val));\n}\n\nciphertext ciphertext::operator*(const NTL::ZZ_p &val) const {\n    ciphertext prod = *this;\n    prod *= val;\n\n    return prod;\n}\n\nciphertext& ciphertext::operator*=(uint64_t val) {\n    return operator*=(NTL::ZZ_p(val));\n}\n\nciphertext& ciphertext::operator*=(const NTL::ZZ_p &val) {\n    NTL::ZZ_p::init(LWE::q);\n\n    this->ctxt *= val;\n    return *this;\n}\n\nciphertext operator*(uint64_t val, const ciphertext& ct) {\n    return operator*(NTL::ZZ_p(val), ct);\n}\n\nciphertext operator*(const NTL::ZZ_p &val, const ciphertext& ct) {\n    ciphertext prod = ct;\n    prod *= val;\n\n    return prod;\n}\n\nsecret_key keygen() {\n    NTL::ZZ_p::init(LWE::q);\n    secret_key sk;\n\n    // Sampled uniformly random matrix A\n    matrix A_hat(NTL::INIT_SIZE, n, n);\n    for (size_t i = 1; i <= n; i++) {\n        for (size_t j = 1; j <= n; j++) {\n            A_hat(i, j) = random(q);\n        }\n    }\n\n    // Sample secret keys from error distribution\n    matrix S_hat(NTL::INIT_SIZE, n, pt_dim);\n    for (size_t i = 1; i <= n; i++) {\n        for (size_t j = 1; j <= pt_dim; j++) {\n            S_hat(i, j) = sample_discrete_gaussian(stddev);\n        }\n    }\n\n    // Sample errors from error distribution\n    matrix E_hat(NTL::INIT_SIZE, pt_dim, n);\n    for (size_t i = 1; i <= pt_dim; i++) {\n        for (size_t j = 1; j <= n; j++) {\n            E_hat(i, j) = sample_discrete_gaussian(stddev);\n        }\n    }\n\n    // Construct A = [ A_hat ; S_hat^T * A_hat + p * E_hat ]\n    matrix A_bottom = NTL::transpose(S_hat)*A_hat + p_int*E_hat;\n\n    for (size_t i = 1; i <= n; i++) {\n        for (size_t j = 1; j <= n; j++) {\n            sk.A(i, j) = A_hat(i, j);\n        }\n    }\n\n    for (size_t i = 1; i <= pt_dim; i++) {\n        for (size_t j = 1; j <= n; j++) {\n            sk.A(i + n, j) = A_bottom(i, j);\n        }\n    }\n\n    // Construct S = [ -S_hat ; I ]\n    for (size_t i = 1; i <= n; i++) {\n        for (size_t j = 1; j <= pt_dim; j++) {\n            sk.S(i, j) = -S_hat(i, j);\n        }\n    }\n\n    matrix ident = NTL::ident_mat_ZZ_p(pt_dim);\n    for (size_t i = 1; i <= pt_dim; i++) {\n        for (size_t j = 1; j <= pt_dim; j++) {\n            sk.S(i + n, j) = ident(i, j);\n        }\n    }\n\n    return sk;\n}\n\nciphertext encrypt(const secret_key &sk, const plaintext &pt) {\n    NTL::ZZ_p::init(LWE::q);\n\n    // Sample an LWE error vector for the randomness (n x 1)\n    vector r(NTL::INIT_SIZE, n);\n    for (size_t i = 1; i <= n; i++) {\n        r(i) = sample_discrete_gaussian(stddev);  \n    }\n\n    vector v_padded(NTL::INIT_SIZE, n + pt_dim);\n    for (size_t i = 1; i <= n; i++) {\n        v_padded(i) = 0;\n    }\n\n    for (size_t i = 1; i <= pt_dim; i++) {\n        v_padded(i + n) = pt(i);\n    }\n\n    ciphertext ctxt;\n    ctxt.ctxt = sk.A*r + v_padded;\n\n    // Add error to each component of ciphertext\n    for (size_t i = 1; i <= n + pt_dim; i++) {\n        ctxt.ctxt(i) += sample_discrete_gaussian(stddev) * LWE::p_int;\n    }\n\n    return ctxt;\n}\n\nplaintext decrypt(const secret_key &sk, const ciphertext& ct) {\n    NTL::ZZ_p::init(LWE::q);\n    vector modqvec = NTL::transpose(sk.S)*ct.ctxt;\n\n    NTL::ZZ_p::init(LWE::p);\n    plaintext pt(NTL::INIT_SIZE, pt_dim);\n    for (size_t i = 1; i <= pt_dim; i++) {\n        NTL::ZZ modq = NTL::rep(modqvec(i));\n        if (modq > q/2) {\n            modq -= q;\n        } else if (modq < -q/2) {\n            modq += q;\n        }\n        pt(i) = ((modq % p_int) + p_int) % p_int;\n    }\n\n    return pt;\n}\n\n}\n", "meta": {"hexsha": "5e46226422eb6180c9b6c8b8c28403b95487d1ce", "size": 5486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lattice_snarg/algebra/lattice/lwe.cpp", "max_stars_repo_name": "dwu4/lattice-snarg", "max_stars_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T03:16:15.000Z", "max_issues_repo_path": "lattice_snarg/algebra/lattice/lwe.cpp", "max_issues_repo_name": "dwu4/lattice-snarg", "max_issues_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lattice_snarg/algebra/lattice/lwe.cpp", "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": 25.1651376147, "max_line_length": 78, "alphanum_fraction": 0.549580751, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5779464305051077}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <utility>\n\n#include \"utils/profiling.h\"\n\n#include <armadillo>\n\nusing namespace util;\nusing namespace arma;\n\nbool checkMat(int row, int col, mat const &mat) {\n    if(mat.n_rows == row && mat.n_cols == col) return true;\n    return false;\n}\nbool checkVec(int dim, vec const &vec) {\n    if(vec.size() == dim) return true;\n    return false;\n}\n\nvoid exit_with_error(std::string error_message) {\n    std::cout << error_message << std::endl;\n    exit(1);\n}\n\nint main() {\n\n    auto timer = Timer{};\n    //timer.here_then_reset(\"\");\n    \n    int r_dim = 3; // Reduced rank r\n\n    // TF matrix for the test.\n    // n_dim by m_dim .\n    int n_dim = 50;\n    int m_dim = 50;\n    \n    sp_mat inM(n_dim,m_dim);\n    for(int i = 0; i < n_dim; i++) {\n        for(int j = 0; j < m_dim; j++) {\n            inM(i,j) = n_dim*i + j + 1;\n        }\n    }\n\n    mat inU;\n    vec ins;\n    mat inV;\n\n    svds(inU,ins,inV,inM,r_dim);\n\n    timer.here_then_reset(\"Truncated SVD is done for original data matrix.\\n\");\n    \n    if(checkMat(n_dim,r_dim,inU) == false) exit_with_error(\"U matrix is incorrect.\");\n    if(checkVec(r_dim,ins) == false) exit_with_error(\"s diagonal matrix is incorrect.\");\n    if(checkMat(m_dim,r_dim,inV) == false) exit_with_error(\"V matrix is incorrect.\");\n    \n    // incremental n_dim by c_dim matrix\n    int c_dim = 1;\n    mat inC(n_dim,c_dim);\n    for(int i = 0; i < n_dim; i++) {\n        for(int j = 0; j < c_dim; j++) {\n            inC(i,j) = i*i+j*(j+1)+1;\n        }\n    }\n\n    if(checkMat(n_dim,c_dim,inC) == false) exit_with_error(\"C matrix is incorrect.\");\n    \n    mat inL = trans(inU)*inC;\n    if(checkMat(r_dim,c_dim,inL) == false) exit_with_error(\"L matrix is incorrect.\");\n    \n    mat inH;\n    inH = inC - inU*inL;\n    if(checkMat(n_dim,c_dim,inH) == false) exit_with_error(\"H matrix is incorrect.\");\n\n    mat inJ;\n    mat inK;\n\n    qr(inJ,inK,inH);\n\n    timer.here_then_reset(\"QR decomposition for H matrix.\\n\");\n    \n    if(checkMat(n_dim,n_dim,inJ) == false) exit_with_error(\"J matrix is incorrect.\");\n    if(checkMat(n_dim,c_dim,inK) == false) exit_with_error(\"K matrix is incorrect.\");\n    \n    mat inQ(r_dim+n_dim,r_dim+c_dim,fill::zeros);\n    \n    for(int r=0;r<r_dim;r++)\n        inQ(r,r) = ins(r);\n\n    for(int i=0;i<r_dim;i++) {\n        for(int j=0;j<c_dim;j++) {\n            inQ(i,r_dim+j) = inL(i,j);\n        }\n    }\n\n    for(int i=0;i<n_dim;i++) {\n        for(int j=0;j<c_dim;j++) {\n            inQ(r_dim+i,r_dim+j)=inK(i,j);\n        }\n    }\n\n    if(checkMat(r_dim+n_dim,r_dim+c_dim,inQ) == false) exit_with_error(\"Q matrix is incorrect.\");\n    \n    mat inUp;\n    vec insp;\n    mat inVp;\n    \n    svd(inUp,insp,inVp,inQ);\n    timer.here_then_reset(\"SVD is done for extended Q matrix.\\n\");\n    \n    if(checkMat(r_dim+n_dim,r_dim+n_dim,inUp) == false) exit_with_error(\"Up matrix is incorrect.\");\n    if(checkVec(r_dim+c_dim,insp) == false) exit_with_error(\"sp diagonal matrix is incorrect.\");\n    // Assuming r_dim+c_dim <= r_dim+n_dim\n    if(checkMat(r_dim+c_dim,r_dim+c_dim,inVp) == false) exit_with_error(\"Vp matrix is incorrect.\");\n\n    \n    mat inUpp;\n    vec inspp;\n    mat inVpp;\n\n    mat mapU;\n    mapU = join_rows(inU,inJ);\n    if(checkMat(n_dim,r_dim+n_dim,mapU) == false) exit_with_error(\"mapU matrix is incorrect.\");\n    \n    mat mapV(m_dim+c_dim,r_dim+c_dim,fill::zeros);\n    for(int i=0;i<m_dim;i++) {\n        for(int j=0;j<r_dim;j++) {\n            mapV(i,j) = inV(i,j);\n        }\n    }\n\n    for(int i=0;i<c_dim;i++) {\n        mapV(m_dim+i,r_dim+i) = 1; \n    }\n    if(checkMat(m_dim+c_dim,r_dim+c_dim,mapV) == false) exit_with_error(\"mapV matrix is incorrect.\");    \n    \n    inUpp = mapU * inUp;\n    inspp = insp;\n    inVpp = mapV * inVp;\n\n    mat inspp_diag(r_dim+n_dim,r_dim+c_dim,fill::zeros);\n\n    for(int i=0;i<r_dim+c_dim;i++) {\n        inspp_diag(i,i) = insp(i);\n    }\n\n    if(checkMat(n_dim,n_dim+r_dim,inUpp) == false) exit_with_error(\"Upp matrix is incorrect.\");\n    if(checkMat(n_dim+r_dim,r_dim+c_dim,inspp_diag) == false) exit_with_error(\"inspp_diag matrix is incorrect.\");\n    if(checkMat(m_dim+c_dim,r_dim+c_dim,inVpp) == false) exit_with_error(\"Vpp matrix is incorrect.\");\n    \n    mat resMat = inUpp*inspp_diag*trans(inVpp);\n    timer.here_then_reset(\"Updated SVD is done.\\n\");\n\n    //resMat.print(\"resMat = \");\n    //End of updating SVD (slow way)\n\n\n    //Begin of brute SVD\n\n\n    timer.here_then_reset(\"Test for brute SVD begins. First I make the matrix.\\n\");\n    \n    mat inMb;\n\n    mat inMd(inM.n_rows, inM.n_cols);\n    for(int i=0;i<inMd.n_rows;i++) {\n        for(int j=0;j<inMd.n_cols;j++) {\n            inMd(i,j) = inM(i,j);\n        }\n    }\n    \n    inMb = join_rows(inMd,inC);\n\n    sp_mat inMbb(inMb.n_rows,inMb.n_cols);\n    for(int i=0;i< inMbb.n_rows;i++) {\n        for(int j=0;j<inMbb.n_cols;j++) {\n            inMbb(i,j) = inMb(i,j);\n        }\n    }\n    \n    timer.here_then_reset(\"Now begins brute SVD calculation.\\n\");\n    \n    mat inUb;\n    vec insb;\n    mat inVb;\n\n    svds(inUb,insb,inVb,inMbb,r_dim+1); // For the fair comparison, I added 1 to r_dim.\n\n    timer.here_then_reset(\"Brute SVD is done.\\n\");\n    \n    \n    //End of brute SVD\n    return 0;\n}\n", "meta": {"hexsha": "a9413e0e7160952a7b77ba497f0bfefdd6c74dd9", "size": 5258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tf-kld/tests/IncSVD.cpp", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tf-kld/tests/IncSVD.cpp", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tf-kld/tests/IncSVD.cpp", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.29, "max_line_length": 113, "alphanum_fraction": 0.5950931913, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5779239783461694}}
{"text": "#include <iostream>\n#include <vector>\n#include <random>\n#include <boost/concept_check.hpp>\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#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n\n\nusing namespace std;\nusing namespace g2o;\n\nclass g2o_vertex: public BaseVertex<3, Eigen::Matrix<double, 1, 3>> {\n\tvoid oplusImpl(const double* v) {\n\t\t_estimate += Eigen::Matrix<double, 1, 3>(v);\n\t}\n\tvoid setToOriginImpl() {\n\t\t_estimate.setZero();\n\t}\n\t\n\tbool read(istream& is) {}\n\tbool write(ostream& os) const {}\n};\n\nclass g2o_edge: public BaseUnaryEdge<1, double, g2o_vertex> {\npublic:\n\texplicit g2o_edge(double x): _x(x) {}\n\tvoid computeError() {\n\t\tg2o_vertex* v = static_cast<g2o_vertex*>(_vertices[0]);\n\t\tconst Eigen::Matrix<double, 1, 3> est = v->estimate();\n\t\t_error(0, 0) = _measurement - exp(est(0,0)*_x*_x + est(0,1)*_x + est(0,2));\n\t\t//cout << \"_error = \" << _error(0,0) << endl;\n\t}\n\t\n\tbool read(istream& is) {}\n\tbool write(ostream& os) const {}\nprivate:\n\tdouble _x;\n};\n\n//y = exp(3*x^2 + 2*x + 1)\nint main(int argc, char **argv) \n{\n\ttypedef BlockSolver<BlockSolverTraits<3, 1>> block_solver;\n\tblock_solver::LinearSolverType* linear_solver = new LinearSolverDense<block_solver::PoseMatrixType>;\n\tblock_solver* blk_slv = new block_solver(linear_solver);\n\t\n\tOptimizationAlgorithmLevenberg* algorithm = new OptimizationAlgorithmLevenberg(blk_slv);\n\tSparseOptimizer optimizer;\n\toptimizer.setAlgorithm(algorithm);\n\toptimizer.setVerbose(true);\n\t\n\t//加顶点\n\tg2o_vertex* vertex = new g2o_vertex;\n\tvertex->setEstimate(Eigen::Matrix<double, 1, 3>(0,0,0));\n\tvertex->setId(0);\n\toptimizer.addVertex(vertex);\n\t\n\t//生成观测值\n\tvector<double> _x,_y;\n\tdouble x_temp;\n\tdefault_random_engine generator;\n\tnormal_distribution<double> distribution(0.0,0.5);\n\tfor(int i=0;i<100;i++) {\n\t\t//100 * 0.005 = 0.5,此值不能太大,过大时exp(3*x^2 + 2*x + 1)就溢出了\n\t\tx_temp = i*0.005;\n\t\t_x.push_back(x_temp);\n\t\t_y.push_back(exp(3*x_temp*x_temp + 2*x_temp + 1) + distribution(generator));\n\t}\n\t//加边\n\tfor(int i=0;i<100;i++) {\n\t\tg2o_edge* edge = new g2o_edge(_x[i]);\n\t\tedge->setId(i);\n\t\tedge->setVertex(0, vertex);\n\t\tedge->setInformation(Eigen::Matrix<double,1,1>(1/0.25));\n\t\tedge->setMeasurement(_y[i]);\n\t\toptimizer.addEdge(edge);\n\t}\n\t//开始进行优化估计\n\toptimizer.initializeOptimization();\n\toptimizer.optimize(100);\n\t\n\tcout << \"optimized variable: \" << vertex->estimate().transpose() << endl;\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "bda7d438f816c77c8e964a5b3c81e709b6dadac3", "size": 2460, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/g2o_curvefitting/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_curvefitting/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_curvefitting/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": 27.6404494382, "max_line_length": 101, "alphanum_fraction": 0.7024390244, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5779239757626834}}
{"text": "// Copyright © 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#include <vinecopulib/misc/tools_stats.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace vinecopulib {\ninline StudentBicop::StudentBicop()\n{\n    family_ = BicopFamily::student;\n    parameters_ = Eigen::VectorXd(2);\n    parameters_lower_bounds_ = Eigen::VectorXd(2);\n    parameters_upper_bounds_ = Eigen::VectorXd(2);\n    parameters_ << 0, 50;\n    parameters_lower_bounds_ << -1, 2;\n    parameters_upper_bounds_ << 1, 50;\n}\n\ninline Eigen::VectorXd StudentBicop::pdf_raw(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    double rho = double(this->parameters_(0));\n    double nu = double(this->parameters_(1));\n    Eigen::VectorXd f = Eigen::VectorXd::Ones(u.rows());\n    Eigen::Matrix<double, Eigen::Dynamic, 2> tmp = tools_stats::qt(u, nu);\n\n    f = tmp.col(0).cwiseAbs2() + tmp.col(1).cwiseAbs2() -\n        (2 * rho) * tmp.rowwise().prod();\n    f /= nu * (1.0 - pow(rho, 2.0));\n    f = f + Eigen::VectorXd::Ones(u.rows());\n    f = f.array().pow(-(nu + 2.0) / 2.0);\n    f = f.cwiseQuotient(tools_stats::dt(tmp, nu).rowwise().prod());\n    f *= boost::math::tgamma_ratio((nu + 2.0) / 2.0, nu / 2.0);\n    f /= (nu * constant::pi * sqrt(1.0 - pow(rho, 2.0)));\n\n    return f;\n}\n\ninline Eigen::VectorXd StudentBicop::cdf(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    using namespace tools_stats;\n\n    double rho = double(this->parameters_(0));\n    double nu = double(this->parameters_(1));\n\n    // for integer nu, just use pbvt\n    // otherwise, interpolate linearly between floor(nu) and ceil(nu)\n    if (nu == round(nu)) {\n        int inu = static_cast<int>(nu);\n        return pbvt(qt(u, inu), inu, rho);\n    } else {\n        int nu1 = static_cast<int>(std::floor(nu));\n        int nu2 = static_cast<int>(std::ceil(nu));\n        double weight = (nu - static_cast<double>(nu1)) /\n            (static_cast<double>(nu2) - static_cast<double>(nu1));\n        return pbvt(qt(u, nu1), nu1, rho) * (1 - weight) +\n            pbvt(qt(u, nu2), nu2, rho) * weight;\n    }\n}\n\ninline Eigen::VectorXd StudentBicop::hfunc1(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    double rho = double(this->parameters_(0));\n    double nu = double(this->parameters_(1));\n    Eigen::VectorXd h = Eigen::VectorXd::Ones(u.rows());\n    Eigen::Matrix<double, Eigen::Dynamic, 2> tmp = tools_stats::qt(u, nu);\n    h = nu * h + tmp.col(0).cwiseAbs2();\n    h *= (1.0 - pow(rho, 2)) / (nu + 1.0);\n    h = h.cwiseSqrt().cwiseInverse().cwiseProduct(\n        tmp.col(1) - rho * tmp.col(0));\n    h = tools_stats::pt(h, nu + 1.0);\n\n    return h;\n}\n\ninline Eigen::VectorXd StudentBicop::hinv1(\n    const Eigen::Matrix<double, Eigen::Dynamic, 2> &u\n)\n{\n    double rho = double(this->parameters_(0));\n    double nu = double(this->parameters_(1));\n    Eigen::VectorXd hinv = Eigen::VectorXd::Ones(u.rows());\n    Eigen::VectorXd tmp = u.col(1);\n    Eigen::VectorXd tmp2 = u.col(0);\n    tmp = tools_stats::qt(tmp, nu + 1.0);\n    tmp2 = tools_stats::qt(tmp2, nu);\n\n    hinv = nu * hinv + tmp2.cwiseAbs2();\n    hinv *= (1.0 - pow(rho, 2)) / (nu + 1.0);\n    hinv = hinv.cwiseSqrt().cwiseProduct(tmp) + rho * tmp2;\n    hinv = tools_stats::pt(hinv, nu);\n\n    return hinv;\n}\n\ninline Eigen::VectorXd StudentBicop::get_start_parameters(const double tau)\n{\n    Eigen::VectorXd parameters = get_parameters();\n    parameters(0) = std::sin(tau * constant::pi / 2);;\n    parameters(1) = 5;\n    return parameters;\n}\n\ninline Eigen::MatrixXd StudentBicop::tau_to_parameters(const double &tau)\n{\n    return no_tau_to_parameters(tau);\n}\n}\n", "meta": {"hexsha": "1754ed0f3b0305f721287f5109d76d1d1d2b0383", "size": 3809, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/student.ipp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/student.ipp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/bicop/implementation/student.ipp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 32.5555555556, "max_line_length": 79, "alphanum_fraction": 0.6285114203, "num_tokens": 1172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5778973585009367}}
{"text": "#include <iostream>\n#include <time.h>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random.hpp>\n#include <LEDA/graph/graph.h>\n#include <LEDA/graph/shortest_path.h>\n\nusing namespace std;\nusing namespace boost;\nusing namespace leda;\n\n// Define the boost edge weight property\ntypedef property<edge_weight_t, int> EdgeWeightProperty;\n\n// Define the boost directed graph: std::vector, std::vector, directed, no vertex property, int edge property, no graph property, std::list\ntypedef adjacency_list<vecS, vecS, directedS, no_property, EdgeWeightProperty, no_property, listS> DirectedGraph;\n\n// Define the vertex class as vertex_desciptor\ntypedef graph_traits<DirectedGraph>::vertex_descriptor Vertex;\n\n// Define the edge class as edge_desciptor\ntypedef graph_traits<DirectedGraph>::edge_descriptor Edge;\n\n// Define the edge iterator as edge_iterator\ntypedef graph_traits<DirectedGraph>::edge_iterator EdgeIterator;\n\n// Define the edge iterator as edge_iterator\ntypedef graph_traits<DirectedGraph>::vertex_iterator VertexIterator;\n\n// Define the edge weight map as a property map\ntypedef property_map<DirectedGraph, edge_weight_t>::type EdgeWeightMap;\n\n/**\n * Copies @param LedaGraph to @param BoostDirectedGraph, using the @param LedaEdgeWeightMap\n * @param BoostDirectedGraph The boost directed graph\n * @param LedaGraph The leda directed graph\n * @param LedaEdgeWeightMap The edge array that contain the leda directed graph edges weights\n*/\nvoid CopyLedaGraphToBoostGraph(DirectedGraph& BoostDirectedGraph, leda::graph& LedaGraph, edge_array<int>& LedaEdgeWeightMap)\n{\n\t// Create a new boost directed graph containing the smae number of nodes as the leda directed graph\n\tDirectedGraph boostGraph(LedaGraph.number_of_nodes());\n\n\t// Leda edge that will be used for iteration\n\tleda::edge tempEdge;\n\n\t// For all edges in the leda directed graph\n\tforall_edges(tempEdge, LedaGraph)\n\t{\n\t\t// Get the source node of the edge\n\t\tnode source = LedaGraph.source(tempEdge);\n\n\t\t// Get the target node of the edge\n\t\tnode target = LedaGraph.target(tempEdge);\n\n\t\t// Get the weight of the edge\n\t\tint edgeWeight = LedaEdgeWeightMap[tempEdge];\n\n\t\t// Add the edge in the boost directed graph\n\t\tadd_edge(LedaGraph.index(source), LedaGraph.index(target), edgeWeight, boostGraph);\n\t}\n\n\t// Update the boost directed graph\n\tBoostDirectedGraph = boostGraph;\n}\n\n/**\n * Applies the Bellman Ford algorithm to the @param directedGraph, using @param startingnode\n * @param directedGraph The inserted boost directed graph\n * @param startingNode The node that will be used as the minimum path's starting node\n * @return False if the graph contains a negative weight circle or true otherwise\n */\nbool BellmanFord(DirectedGraph& directedGraph, Vertex startingVertex)\n{\n\t// Initialize a node map containg the node minimum path cost\n\tstd::map<Vertex, int> nodeCostMap;\n\n\t// Initialize the property map that contain the edges's weights\n\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, directedGraph);\n\n\t// Initialise the boost vertex iterators\n\tVertexIterator vertexIteratorBegin, vertexIteratorEnd;\n\n\t// For every vertex in the boost directed graph...\n\tfor(tie(vertexIteratorBegin, vertexIteratorEnd) = vertices(directedGraph); vertexIteratorBegin != vertexIteratorEnd; vertexIteratorBegin++)\n\t{\n\t\t// Set the vertex initial cost to INT_MAX\n\t\tnodeCostMap.insert(pair<Vertex,int>(*vertexIteratorBegin, INT_MAX));\n\t}\n\n\t// Set the starting node cost to 0\n\tnodeCostMap[startingVertex] = 0;\n\n\t// Initialise the boost edge iterators\n\tEdgeIterator edgeIteratorBegin, edgeIteratorEnd;\n\n\t// For every vertex in the boost directed graph...\n\tfor(tie(vertexIteratorBegin, vertexIteratorEnd) = vertices(directedGraph); vertexIteratorBegin != vertexIteratorEnd; vertexIteratorBegin++)\n\t{\n\t\t// For every out edge of the current vertex... \n\t\tfor(tie(edgeIteratorBegin, edgeIteratorEnd) = edges(directedGraph); edgeIteratorBegin != edgeIteratorEnd; edgeIteratorBegin++)\n\t\t{\n\t\t\t// Get the current edge's source node\n\t\t\tint sourceNodeCost = nodeCostMap[source(*edgeIteratorBegin, directedGraph)];\n\n\t\t\t// Get the current edge's target node\n\t\t\tint targetNodeCost = nodeCostMap[target(*edgeIteratorBegin, directedGraph)];\n\n\t\t\t// Get the current edge's weight\n\t\t\tint edgeWeight = boostEdgeWeightMap[*edgeIteratorBegin];\n\t\t\t\n\t\t\t// If the current edge verifies the triangular inequality and has already been accessed...\n\t\t\tif(sourceNodeCost != INT_MAX && (sourceNodeCost + edgeWeight < targetNodeCost))\n\t\t\t{\n\t\t\t\tnodeCostMap[target(*edgeIteratorBegin, directedGraph)] = sourceNodeCost + edgeWeight;\n\t\t\t}\n\t \t}\n\t}\n\n\t// For all edges in the boost directed graph...\n\tfor(tie(edgeIteratorBegin, edgeIteratorEnd) = edges(directedGraph); edgeIteratorBegin != edgeIteratorEnd; edgeIteratorBegin++)\n\t{\n\t\t// Get the current edge's source node\n\t\tint sourceNodeCost = nodeCostMap[source(*edgeIteratorBegin, directedGraph)];\n\n\t\t// Get the current edge's target node\n\t\tint targetNodeCost = nodeCostMap[target(*edgeIteratorBegin, directedGraph)];\n\n\t\t// Get the current edge's weight\n\t\tint edgeWeight = boostEdgeWeightMap[*edgeIteratorBegin];\n\n\t\t// If negative cycle is detected...\n\t\tif(sourceNodeCost != INT_MAX && (sourceNodeCost + edgeWeight < targetNodeCost))\n\t\t{\n\t\t\t// Return false if a negative weight cycle is present in the directed graph\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// Return true since the directed graph doesn't contain a negative weight cycle\n\treturn true;\n}\n\n// Main function\nint main()\n{\n\t#pragma region Initialization\n\n\t// Create an empty boost directed graph\n\tDirectedGraph boostDirectedGraph;\n\n\t// Create an empty leda directed graph\n\tleda::graph ledaDirectedGraph;\n\n\t//Create an empty edge array\n\tedge_array<int> ledaEdgeWeightArray;\n\t\n\t// User graph option\n\tstd::string graphOption;\n\n\t// Number of nodes\n\tint numberOfNodes;\n\n\tcout << \"Choose the testing graph between grid or random.\" << endl; \n\n\t// Read the graph type\n\tcin >> graphOption;\n\n\tcout << \"Enter the number of nodes.\" << endl;\n\n\t// Read the number of nodes\n\tcin >> numberOfNodes;\n\n\t// If the grid graph is selected...\n\tif(graphOption == \"grid\")\n\t{\n\t\t// Create a grid graph\n\t\tgrid_graph(ledaDirectedGraph, numberOfNodes);\n\n\t\t// Intialise an edge array that will contain the leda graph edges weights\n\t\tedge_array<int> edgeWeightArray(ledaDirectedGraph);\n\n\t\t// Copy the edge array\n\t\tledaEdgeWeightArray = edgeWeightArray;\n\n\t\t// Initialise a random seed\n\t\tsrand(time(NULL));\n\n\t\t// Edge that will be used for the iteration\n\t\tleda::edge tempEdge;\n\n\t\t// For every edge in the undirected graph...\n\t\tforall_edges(tempEdge, ledaDirectedGraph)\n\t\t{\n\t\t\t// Get the current edge source node index\n\t\t\tint tempEdgeSourceNodeIndex = ledaDirectedGraph.index(ledaDirectedGraph.source(tempEdge));\n\n\t\t\t// Get the current edge target node index\n\t\t\tint tempEdgeTargetNodeIndex = ledaDirectedGraph.index(ledaDirectedGraph.target(tempEdge));\n\n\t\t\t// Get the point representation of the edge's source node index\n\t\t\tdiv_t tempEdgeSourceNodeIndexDivResult = div(tempEdgeSourceNodeIndex, numberOfNodes);\n\n\t\t\t// Get the point representation of the edge's target node index\n\t\t\tdiv_t tempEdgeTargetNodeIndexDivResult = div(tempEdgeTargetNodeIndex, numberOfNodes);\n\n\t\t\t// Check if the edge is a vertical edge that belong in the third quarter\n\t\t\tbool verticalEdgeThirdQuarterPresence = (tempEdgeSourceNodeIndexDivResult.quot >= (numberOfNodes/2)) && (tempEdgeSourceNodeIndexDivResult.rem <= (numberOfNodes/2)) && (tempEdgeTargetNodeIndexDivResult.quot > (numberOfNodes/2)) && (tempEdgeTargetNodeIndexDivResult.rem < (numberOfNodes/2));\n\n\t\t\t// Check if the edge is a horizontal edge that belong in the third quarter\n\t\t\tbool horizontalEdgeThirdQuarterPresence = (tempEdgeSourceNodeIndexDivResult.quot > (numberOfNodes/2)) && (tempEdgeSourceNodeIndexDivResult.rem < (numberOfNodes/2)) && (tempEdgeTargetNodeIndexDivResult.quot >= (numberOfNodes/2)) && (tempEdgeTargetNodeIndexDivResult.rem <= (numberOfNodes/2));\n\n\t\t\t// If the edge belongs into the third quarter...\n\t\t\tif(verticalEdgeThirdQuarterPresence || horizontalEdgeThirdQuarterPresence)\n\t\t\t{\n\t\t\t\t// If the current edge, was randomly chosen to reversed...\n\t\t\t\tif((rand() % 2) == 0)\n\t\t\t\t{\n\t\t\t\t\t// Reverse the current edge\n\t\t\t\t\tledaDirectedGraph.rev_edge(tempEdge);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Check if the edge is the special horizontal edge\n\t\t\t\tbool specialThirdQuarterHorizontalEdge = (tempEdgeSourceNodeIndexDivResult.quot == (numberOfNodes/2 + 1)) && (tempEdgeSourceNodeIndexDivResult.rem == (numberOfNodes/2 - 1)) && (tempEdgeTargetNodeIndexDivResult.quot == (numberOfNodes/2 + 1)) && (tempEdgeTargetNodeIndexDivResult.rem == (numberOfNodes/2));\n\n\t\t\t\t// Check if the edge is the special vertical edge\n\t\t\t\tbool specialThirdQuarterVerticalEdge = (tempEdgeSourceNodeIndexDivResult.quot == (numberOfNodes/2)) && (tempEdgeSourceNodeIndexDivResult.rem == (numberOfNodes/2 - 1)) && (tempEdgeTargetNodeIndexDivResult.quot == (numberOfNodes/2 + 1)) && (tempEdgeTargetNodeIndexDivResult.rem == (numberOfNodes/2 - 1));\n\n\t\t\t\t// If the edge is either the special negative weight vertical edge or the special negative weight horizontal edge...\n\t\t\t\tif(specialThirdQuarterVerticalEdge || specialThirdQuarterHorizontalEdge)\n\t\t\t\t{\n\t\t\t\t\t// Assign -100000 as weight to the current special edge\n\t\t\t\t\tledaEdgeWeightArray[tempEdge] = -100000;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Assign random integer values as costs between 0 and 10000\n\t\t\t\tledaEdgeWeightArray[tempEdge] = (rand() % 10000);\n\t\t\t}\n\t\t}\n\t\t// Get the grid graph number of nodes\n\t\tnumberOfNodes = ledaDirectedGraph.number_of_nodes();\n\n\t\t// Copy the leda directed graph to the boost directed graph\n\t\tCopyLedaGraphToBoostGraph(boostDirectedGraph, ledaDirectedGraph, ledaEdgeWeightArray);\n\n\t\t// Initialise a property map that contain the boost graph edges weights\n\t\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, boostDirectedGraph);\n\t}\n\telse\n\t{\n\t\t// If the random graph is selected...\n\t\tif(graphOption == \"random\")\n\t\t{\n\t\t\t// Calculate the number of edges\n\t\t\tint numberOfEdges = ceil(20 * numberOfNodes * log2(numberOfNodes));\n\n\t\t\t// Generate a random directed graph\n\t\t\trandom_graph(ledaDirectedGraph, numberOfNodes, numberOfEdges, false, true, true);\n\n\t\t\t// Make the graph cohesive\n\t\t\tMake_Connected(ledaDirectedGraph);\n\n\t\t\t// Intialise an edge array that will contain the leda graph edges weights\n\t\t\tedge_array<int> edgeWeightArray(ledaDirectedGraph);\n\n\t\t\t// Copy the edge array\n\t\t\tledaEdgeWeightArray = edgeWeightArray;\n\n\t\t\t// Initialise a random seed\n\t\t\tsrand(time(NULL));\n\n\t\t\t// Edge that will be used for the iteration\n\t\t\tleda::edge tempEdge;\n\n\t\t\t// For every edge in the undirected graph...\n\t\t\tforall_edges(tempEdge, ledaDirectedGraph)\n\t\t\t{\n\t\t\t\t// Assign random integer values as costs between 10 and 10000\n\t\t\t\tledaEdgeWeightArray[tempEdge] = (rand() % 10100) - 100;\n\t\t\t}\n\n\t\t\t// Copy the leda directed graph to the boost directed graph\n\t\t\tCopyLedaGraphToBoostGraph(boostDirectedGraph, ledaDirectedGraph, ledaEdgeWeightArray);\n\n\t\t\t// Initialise a property map that contain the boost graph edges weights\n\t\t\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, boostDirectedGraph);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Choose between grid or random.\" << endl;\n\n\t\t\t// Exit if another option is selected\n\t\t\texit(0);\n\t\t}\n\t}\n\n\t// Choose a random node from the Leda directed graph\n\tnode randomLedaNode = ledaDirectedGraph.choose_node();\n\n\t// Get the index of the Boost directed graph vertex that correspond to the appropriate Leda random chosen node\n\tVertex randomBoostVertex = vertex(ledaDirectedGraph.index(randomLedaNode), boostDirectedGraph);\n\t\n\t// Initialise a node array the will contain the last edge on a shortest path from the starting node to a node\n\tnode_array<leda::edge> ledaPredecessorNodeArray(ledaDirectedGraph);\n\n\t// Initialise a node array the will contain the shortest path langth from the starting node to a node\n\tnode_array<int> ledaDistanceNodeArray(ledaDirectedGraph);\n\n\t// Initialize a property map that contain the edges's weights\n\tEdgeWeightMap boostEdgeWeightMap = get(edge_weight, boostDirectedGraph);\n\n\t// Initialize a vector that will contain the distance to each node and set the initial distance to INT_MAX\n\tstd::vector<int> boostDistanceVector(numberOfNodes,INT_MAX);\n\n\t// Set the distance of the chosen vertex to 0\n\tboostDistanceVector[randomBoostVertex] = 0;\n\n\t// Initialize a vector that will contain the predeccesor of each node\n\tstd::vector<std::size_t> boostPredeccesorVector(numberOfNodes);\n\n\t// For every vertex in the boost directed graph...\n\tfor(int index = 0; index < numberOfNodes; index++)\n\t{\n\t\t// Set the current vertex predeccesor to itself\n\t\tboostPredeccesorVector[index] = index;\n\t}\n\t\n\t#pragma endregion Initialization\n\n\t#pragma region Simulation\n\n\t// Initialise the starting CPU time\n\tfloat CPUTime = used_time();\n\n\t// Execute the user defined Bellman Ford algorithm for the boost directed graph using the random vertex\n\tbool negativeWeightCircleNotFound = BellmanFord(boostDirectedGraph, randomBoostVertex);\n\n\t// Print the user defined Bellman Ford function execution time\n\tcout << \"User defined Bellman Ford function execution time: \" << used_time(CPUTime) << \" seconds.\"<< endl;\n\n\t// Execute the Leda Bellman Ford algorithm for the Leda directed graph using the random node and the defined arrays\n\tnegativeWeightCircleNotFound = BELLMAN_FORD(ledaDirectedGraph, randomLedaNode, ledaEdgeWeightArray, ledaDistanceNodeArray, ledaPredecessorNodeArray);\n\n\t// Print the Leda Bellman Ford function execution time\n\tcout << \"Leda Bellman Ford function execution time: \" << used_time(CPUTime) << \" seconds.\"<< endl;\n\n\t// If the directed graph doesn't contain a negative weight circle...\n\tif(negativeWeightCircleNotFound)\n\t{\n\t\t// Execute the Boost Bellman Ford algorithm for the boost directed graph using the defined maps\n\t\tbellman_ford_shortest_paths(boostDirectedGraph, numberOfNodes, weight_map(boostEdgeWeightMap).distance_map(&boostDistanceVector[0]).distance_map(&boostPredeccesorVector[0]));\n\n\t\t// Print the Boost Bellman Ford function execution time\n\t\tcout << \"Boost Bellman Ford function execution time: \" << used_time(CPUTime) << \" seconds.\"<< endl;\n\n\t\tcout << \"The directed graph doesn't contain a negative weight cycle.\" << endl; \n\t}\n\telse\n\t{\n\t\tcout << \"The directed graph contains a negative weight cycle.\" << endl;\n\t}\n\n\t#pragma endregion Simulation\n\n\t// Return 0\n\treturn 0;\n}\n", "meta": {"hexsha": "13e705f357dcbcb4586cad1e5d7a39d7b6026e8f", "size": 14338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project Τεχνολογίες Υλοποίησης Αλγορίθμων/2η Άσκηση/Ergasia_2.cpp", "max_stars_repo_name": "DimosthenisMich/UndergraduateCeidProjects", "max_stars_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T18:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T17:49:30.000Z", "max_issues_repo_path": "Project Τεχνολογίες Υλοποίησης Αλγορίθμων/2η Άσκηση/Ergasia_2.cpp", "max_issues_repo_name": "DimosthenisMich/UndergraduateCeidProjects", "max_issues_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-30T19:16:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-30T19:16:39.000Z", "max_forks_repo_path": "Project Τεχνολογίες Υλοποίησης Αλγορίθμων/2η Άσκηση/Ergasia_2.cpp", "max_forks_repo_name": "DimitrisKostorrizos/UndergraduateCeidProjects", "max_forks_repo_head_hexsha": "9f99f2c44e41d06020f3a5e9aacc0cd4357ee833", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T21:34:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T22:37:35.000Z", "avg_line_length": 38.6469002695, "max_line_length": 308, "alphanum_fraction": 0.7611242851, "num_tokens": 3519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5778940245070753}}
{"text": "/*****************************************************************************\n * fixed.cpp        Blitz++ array using a custom type\n * $Id$\n * This example illustrates how simple it is to create Blitz++ arrays\n * using a custom type.  \n *****************************************************************************/\n\n#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n// A simple fixed point arithmetic class which represents a point\n// in the interval [0,1].\nclass FixedPoint {\n\npublic:\n    typedef unsigned int T_mantissa;\n\n    FixedPoint() { }\n\n    explicit FixedPoint(T_mantissa mantissa)\n    {  \n        mantissa_ = mantissa;\n    }\n\n    FixedPoint(double value)\n    {\n        assert((value >= 0.0) && (value <= 1.0));\n        mantissa_ = T_mantissa(value * huge(T_mantissa()));\n    }\n   \n    FixedPoint operator+(FixedPoint x)\n    { return FixedPoint(mantissa_ + x.mantissa_); }\n\n    double value() const\n    { return mantissa_ / double(huge(T_mantissa())); }\n\nprivate:\n    T_mantissa mantissa_;\n};\n\nostream& operator<<(ostream& os, const FixedPoint& a)\n{\n    os << a.value();\n    return os;\n}\n\nint main()\n{\n    // Now create an array using the FixedPoint class:\n\n    Array<FixedPoint, 2> A(4,4), B(4,4);\n\n    A = 0.5, 0.3, 0.8, 0.2,\n        0.1, 0.3, 0.2, 0.9,\n        0.0, 1.0, 0.7, 0.4,\n        0.2, 0.3, 0.8, 0.4;\n\n    B = A + 0.05;\n\n    cout << \"B = \" << B << endl;\n\n    return 0;\n}\n\n\n// Program output:\n// B = 4 x 4\n//      0.55      0.35      0.85      0.25\n//      0.15      0.35      0.25      0.95\n//      0.05      0.05      0.75      0.45\n//      0.25      0.35      0.85      0.45\n\n/*\n * Note: Just because Array<T,N> supports all possible operators doesn't\n * mean that a user-defined class has to.  You only need to define the \n * operators you actually use on the array.  This works because the ISO/ANSI\n * draft standard forbids instantiation of unused member functions:\n *\n * [temp.inst, paragraph 7]\n * An implementation shall not implicitly instantiate  a  function,  non-\n * virtual  member  function,  class  or  member  template  that does not\n * require instantiation.  It is unspecified whether or not an  implemen-\n * tation implicitly instantiates a virtual member function that does not\n * require specialization.\n */\n", "meta": {"hexsha": "babdd489a46f616489fbba844e82dd3fba78e493", "size": 2254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/fixed.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/examples/fixed.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/examples/fixed.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.908045977, "max_line_length": 79, "alphanum_fraction": 0.5683229814, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.8006920068519378, "lm_q1q2_score": 0.5778940162821758}}
{"text": "// GMTL is (C) Copyright 2001-2010 by Allen Bierbaum\n// Distributed under the GNU Lesser General Public License 2.1 with an\n// addendum covering inlined code. (See accompanying files LICENSE and\n// LICENSE.addendum or http://www.gnu.org/copyleft/lesser.txt)\n\n// This file was originally part of PyJuggler.\n\n// PyJuggler is (C) Copyright 2002, 2003 by Patrick Hartling\n// Distributed under the GNU Lesser General Public License 2.1.  (See\n// accompanying file COPYING.txt or http://www.gnu.org/copyleft/lesser.txt)\n\n// Includes ====================================================================\n#include <boost/python.hpp>\n#include <gmtl/Math.h>\n\n// Using =======================================================================\nusing namespace boost::python;\n\n// Declarations ================================================================\n\n\nnamespace gmtlWrappers\n{\n   template<typename T, typename U>\n   T lerp(const U& lerp, const T& a, const T& b)\n   {\n      T result;\n      gmtl::Math::lerp(result, lerp, a, b);\n      return result;\n   }\n\n   template<typename T>\n   tuple quadraticFormula(const T& a, const T& b, const T& c)\n   {\n      T r1, r2;\n      bool result = gmtl::Math::quadraticFormula(r1, r2, a, b, c);\n      return make_tuple(result, r1, r2);\n   }\n}\n\nnamespace\n{\n\nclass Fake : public boost::noncopyable\n{\n};\n\n}\n\n\n// Module ======================================================================\nvoid _Export_gmtl_Math_h()\n{\n    // Retained (temporarily) for backwards compatibility.\n    def(\"deg2Rad\", (double (*)(double))&gmtl::Math::deg2Rad);\n    def(\"deg2Rad\", (float (*)(float))&gmtl::Math::deg2Rad);\n    def(\"rad2Deg\", (float (*)(float))&gmtl::Math::rad2Deg);\n    def(\"rad2Deg\", (double (*)(double))&gmtl::Math::rad2Deg);\n\n    scope* gmtl_Math_scope = new scope(\n    class_< Fake, boost::noncopyable >(\"Math\", no_init)\n        .def(\"sign\", (int (*)(int)) &gmtl::Math::sign)\n        .def(\"sign\", (int (*)(float)) &gmtl::Math::sign)\n        .def(\"sign\", (int (*)(double)) &gmtl::Math::sign)\n        .def(\"fastInvSqrt\", &gmtl::Math::fastInvSqrt)\n        .def(\"fastInvSqrt2\", &gmtl::Math::fastInvSqrt2)\n        .def(\"fastInvSqrt3\", &gmtl::Math::fastInvSqrt3)\n        .def(\"deg2Rad\", (double (*)(double))&gmtl::Math::deg2Rad)\n        .def(\"deg2Rad\", (float (*)(float))&gmtl::Math::deg2Rad)\n        .def(\"rad2Deg\", (float (*)(float))&gmtl::Math::rad2Deg)\n        .def(\"rad2Deg\", (double (*)(double))&gmtl::Math::rad2Deg)\n        .def(\"factorial\", (double (*)(double)) &gmtl::Math::factorial)\n        .def(\"factorial\", (float (*)(float)) &gmtl::Math::factorial)\n        .def(\"factorial\", (int (*)(int)) &gmtl::Math::factorial)\n        .def(\"lerp\",\n            (double (*)(const double&, const double&, const double&)) &gmtlWrappers::lerp)\n        .def(\"lerp\",\n            (float (*)(const float&, const float&, const float&)) &gmtlWrappers::lerp)\n        .def(\"quadraticFormula\",\n            (tuple (*)(const double&, const double&, const double&)) &gmtlWrappers::quadraticFormula)\n        .def(\"quadraticFormula\",\n            (tuple (*)(const float&, const float&, const float&)) &gmtlWrappers::quadraticFormula)\n        .staticmethod(\"sign\")\n        .staticmethod(\"fastInvSqrt\")\n        .staticmethod(\"fastInvSqrt2\")\n        .staticmethod(\"fastInvSqrt3\")\n        .staticmethod(\"deg2Rad\")\n        .staticmethod(\"rad2Deg\")\n        .staticmethod(\"factorial\")\n        .staticmethod(\"lerp\")\n        .staticmethod(\"quadraticFormula\")\n    );\n\n    delete gmtl_Math_scope;\n}\n", "meta": {"hexsha": "9deb82bbdeed12ce5cded4d4b81fcd8d09f6a14a", "size": 3483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_Math_h.cpp", "max_stars_repo_name": "Glitch0011/QuadTree-Example", "max_stars_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_Math_h.cpp", "max_issues_repo_name": "Glitch0011/QuadTree-Example", "max_issues_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_Math_h.cpp", "max_forks_repo_name": "Glitch0011/QuadTree-Example", "max_forks_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_forks_repo_licenses": ["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.28125, "max_line_length": 101, "alphanum_fraction": 0.5716336492, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.5778940011920788}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2007, 2010.\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#ifdef _MSC_VER\n# pragma warning (disable : 4305) // 'initializing' : truncation from 'long double' to 'const eval_type'\n# pragma warning (disable : 4244) //  conversion from 'long double' to 'const eval_type'\n#endif\n\n#include <iostream>\nusing std::cout; using std::endl;\n\n//[policy_eg_3\n\n#include <boost/math/distributions/binomial.hpp>\nusing boost::math::binomial_distribution;\n\n// Begin by defining a policy type, that gives the behaviour we want:\n\n//using namespace boost::math::policies; or explicitly\nusing boost::math::policies::policy;\n\nusing boost::math::policies::promote_float;\nusing boost::math::policies::discrete_quantile;\nusing boost::math::policies::integer_round_nearest;\n\ntypedef policy<\n   promote_float<false>, // Do not promote to double.\n   discrete_quantile<integer_round_nearest> // Round result to nearest integer.\n> mypolicy;\n//\n// Then define a new distribution that uses it:\ntypedef boost::math::binomial_distribution<float, mypolicy> mybinom;\n\n//  And now use it to get the quantile:\n\nint main()\n{\n   cout << \"quantile(mybinom(200, 0.25), 0.05) is: \" <<\n      quantile(mybinom(200, 0.25), 0.05) << endl;\n}\n\n//]\n\n/*\n\nOutput:\n\n  quantile(mybinom(200, 0.25), 0.05) is: 40\n\n*/\n", "meta": {"hexsha": "e77d28f0b13e0cf9c7c955da666c687e9eb5d0d3", "size": 1470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_eg_3.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_eg_3.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/policy_eg_3.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.7272727273, "max_line_length": 104, "alphanum_fraction": 0.7238095238, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5778850282483898}}
{"text": "#include <math.h>\n#include <EigenUnsupported/Eigen/KroneckerProduct>\n#include \"Core/Utilities/QProgInfo/QCircuitInfo.h\"\n#include \"Core/Utilities/Tools/MatrixDecomposition.h\"\n#include <chrono>\n#include \"Core/Utilities/QProgInfo/Visualization/QVisualization.h\"\n#include \"QAlg/Base_QCircuit/AmplitudeEncode.h\"\n\nUSING_QPANDA\nusing namespace std;\nusing namespace chrono;\n\n#define PRINT_TRACE 0\n#if PRINT_TRACE\n#define PTrace printf\n#define PTraceMat(mat) (std::cout << (mat) << endl)\n#define PTraceCircuit(cir) (std::cout << cir << endl)\n#else\n#define PTrace\n#define PTraceMat(mat)\n#define PTraceCircuit(cir)\n#endif\n\n#define MAX_MATRIX_PRECISION 1e-10\n\nusing MatrixSequence = std::vector<MatrixUnit>;\nusing DecomposeEntry = std::pair<int, MatrixSequence>;\n\nusing ColumnOperator = std::vector<DecomposeEntry>;\nusing MatrixOperator = std::vector<ColumnOperator>;\n\nusing SingleGateUnit = std::pair<MatrixSequence, QStat>;\n\nstatic void upper_partition(int order, MatrixOperator &entries)\n{\n\tauto index = (int)std::log2(entries.size() + 1) - (int)std::log2(order) - 1;\n\n\tfor (auto cdx = 0; cdx < order - 1; ++cdx)\n\t{\n\t\tfor (auto rdx = 0; rdx < order - cdx - 1; ++rdx)\n\t\t{\n\t\t\tauto entry = entries[cdx][rdx];\n\n\t\t\tentry.first += order;\n\t\t\tentry.second[index] = MatrixUnit::SINGLE_P1;\n\n\t\t\tentries[cdx + order].emplace_back(entry);\n\t\t}\n\t}\n\n    return;\n}\n\n\nstatic bool entry_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint lj = ((cdx - 1) >> (udx - 1)) & 1;\n\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if 1 ≤ j ≤ m and cj = lj' = 1 , return true\n\tauto mat = units[units.size() - udx];\n\treturn udx >= 1\n\t\t&& udx <= M\n\t\t&& lj\n\t\t&& mat == MatrixUnit::SINGLE_P1;\n}\n\nstatic bool steps_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if j = n and none of cn...cm+1 is 1 , return true\n\tif (units.size() != udx)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto iter = std::find(units.begin(), units.end() - M, MatrixUnit::SINGLE_P1);\n\t\treturn (units.end() - M) == iter;\n\t}\n}\n\nstatic void under_partition(int order, MatrixOperator& entries)\n{\n\tauto qubits = (int)std::log2(entries.size() + 1);\n\n\tfor (auto cdx = 1; cdx < order; ++cdx)\n\t{\n\t\tif (cdx & 1)\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto value = entries[0][rdx + order - 1].first ^ cdx;\n\t\t\t\tauto entry = make_pair(value, entries[cdx - 1][rdx + order - cdx].second);\n\n\t\t\t\tentries[cdx].emplace_back(entry);\n\t\t\t}\n\n\t\t\tauto &units = entries[cdx].back().second;\n\t\t\tfor (auto idx = 0; idx < (int)std::log2(order); ++idx)\n\t\t\t{\n\t\t\t\tunits[qubits - idx - 1] = ((cdx >> idx) & 1) ?\n\t\t\t\t\tMatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto range = (int)std::log2(order) + 1;\n\t\t\t\tauto refer = entries[0][rdx + order - 1].second;\n\t\t\t\tauto entry = entries[0][rdx + order - 1].first ^ cdx;\n\n\t\t\t\tMatrixSequence units(refer.begin() + qubits - range, refer.end());\n\n\t\t\t\tfor (auto udx = 1; udx <= range; ++udx)  /*udx = j , cdx = L*/\n\t\t\t\t{\n\t\t\t\t\tbool steps_accord = steps_requirement(units, udx, cdx + 1);\n\t\t\t\t\tbool entry_accord = entry_requirement(units, udx, cdx + 1);\n\n\t\t\t\t\tunits[range - udx] = steps_accord ? MatrixUnit::SINGLE_P1 :\n\t\t\t\t\t\tentry_accord ? MatrixUnit::SINGLE_P0 : units[range - udx];\n\t\t\t\t}\n\n\t\t\t\tfor (auto idx = 0; idx < qubits - range; ++idx)\n\t\t\t\t{\n\t\t\t\t\tunits.insert(units.begin(), MatrixUnit::SINGLE_I2);\n\t\t\t\t}\n\n\t\t\t\tentries[cdx].emplace_back(make_pair(entry, units));\n\t\t\t}\n\n\t\t\tauto refer_opt = entries[0][2 * order - 2].second;\n\t\t\tfor (auto idx = 0; idx < qubits; ++idx)\n\t\t\t{\n\t\t\t\tif ((cdx >> idx) & 1)\n\t\t\t\t{\n\t\t\t\t\trefer_opt[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentries[cdx].back().second = refer_opt;\n\t\t}\n\t}\n\n    return;\n}\n\nstatic void controller(MatrixSequence &sequence, const EigenMatrix2c U2, EigenMatrixXc &matrix)\n{\n\tEigenMatrix2c P0;\n\tEigenMatrix2c P1;\n\tEigenMatrix2c I2;\n\n\tP0 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0);\n\tP1 << Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\tI2 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\n\tstd::map<MatrixUnit, std::function<EigenMatrix2c()>> mapping =\n\t{\n\t\t{ MatrixUnit::SINGLE_P0, [&]() {return P0; } },\n\t\t{ MatrixUnit::SINGLE_P1, [&]() {return P1; } },\n\t\t{ MatrixUnit::SINGLE_I2, [&]() {return I2; } },\n\t\t{ MatrixUnit::SINGLE_V2, [&]() {return U2 - I2; } }\n\t};\n\n\tauto order = sequence.size();\n\tEigenMatrixXc Un = EigenMatrixXc::Identity(1, 1);\n\tEigenMatrixXc In = EigenMatrixXc::Identity(1ull << order, 1ull << order);\n\n\tfor (const auto &val : sequence)\n\t{\n\t\tEigenMatrix2c M2 = mapping.find(val)->second();\n\t\tUn = Eigen::kroneckerProduct(Un, M2).eval();\n\t}\n\n\tmatrix = In + Un;\n    return;\n}\n\nstatic void recursive_partition(const EigenMatrixXc& sub_matrix, MatrixOperator &entries)\n{\n    Eigen::Index order = sub_matrix.rows();\n    if (1 == order)\n    {\n        return;\n    }\n    else\n    {\n        EigenMatrixXc corner = sub_matrix.topLeftCorner(order / 2, order / 2);\n\n        recursive_partition(corner, entries);\n\n        upper_partition(order / 2, entries);\n        under_partition(order / 2, entries);\n    }\n\n    return;\n}\n\nstatic void decomposition(EigenMatrixXc& matrix, MatrixOperator& entries, std::vector<SingleGateUnit>& cir_units)\n{\n\tfor (auto cdx = 0; cdx < entries.size(); ++cdx)\n\t{\n\t\tauto opts = entries[cdx].size();\n\t\tfor (auto idx = 0; idx < opts; ++idx)\n\t\t{\n\t\t\tauto rdx = entries[cdx][idx].first;\n\t\t\tauto opt = entries[cdx][idx].second;\n\n\t\t\tif ((((abs(matrix(rdx, cdx).real()) < MAX_MATRIX_PRECISION) && (abs(matrix(rdx, cdx).imag()) < MAX_MATRIX_PRECISION)) && (idx != opts - 1)) ||\n\t\t\t\t(((abs(matrix(cdx + 1, cdx).real() - 1.0) < MAX_MATRIX_PRECISION) && (abs(matrix(cdx + 1, cdx).imag()) < MAX_MATRIX_PRECISION)) && (idx == opts - 1)))\n\t\t\t/*if ((EigenComplexT(0, 0) == matrix(rdx, cdx) && (idx != opts - 1)) ||\n\t\t\t\t(EigenComplexT(1, 0) == matrix(cdx + 1, cdx) && (idx == opts - 1)))*/\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEigenMatrix2c C2; /*placeholder*/\n\t\t\t\tC2 << EigenComplexT(0, 1), EigenComplexT(0, 1),\n\t\t\t\t\tEigenComplexT(0, 1), EigenComplexT(0, 1);\n\n\t\t\t\tEigenMatrixXc Cn;\n\t\t\t\tcontroller(opt, C2, Cn);\n\n\t\t\t\tQnum indices(2);\n\t\t\t\tfor (Eigen::Index index = 0; index < (1ull << opt.size()); ++index)\n\t\t\t\t{\n\t\t\t\t\tif (Cn(rdx, index) != EigenComplexT(0, 0))\n\t\t\t\t\t{\n\t\t\t\t\t\tindices[index == rdx] = index;\n\t\t\t\t\t}  \n\t\t\t\t}\n\n\t\t\t\tEigenComplexT C0 = matrix(indices[0], cdx);  /*The entry to be eliminated */\n\t\t\t\tEigenComplexT C1 = matrix(indices[1], cdx);  /*The corresponding entry */\n\n\t\t\t\tEigenComplexT V11, V12, V21, V22;\n\n\t\t\t\tif (indices[0] < indices[1])\n\t\t\t\t{\n\t\t\t\t\tV11 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tV11 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\n\t\t\t\tEigenMatrix2c V2;\n\t\t\t\tV2 << V11, V12, V21, V22;\n\n\t\t\t\tEigenMatrixXc Un;\n\t\t\t\tcontroller(opt, V2, Un);\n\n\t\t\t\tmatrix = Un * matrix;\n\n\t\t\t\tQStat M2 = { (qcomplex_t)V11 ,(qcomplex_t)V12 ,(qcomplex_t)V21 ,(qcomplex_t)V22 };\n\t\t\t\tcir_units.insert(cir_units.begin(), std::make_pair(opt, M2));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigenMatrix2c V2 = matrix.bottomRightCorner(2, 2);\n\tif(!V2.isApprox(EigenMatrixXc::Identity(2, 2), MAX_MATRIX_PRECISION))\n\t//if (EigenMatrixXc::Identity(2, 2) != V2)\n\t{\n\t\tQStat M2 = { (qcomplex_t)((EigenComplexT)1.0 / V2(0,0)), (qcomplex_t)(V2(0,1)),\n\t\t\t\t\t (qcomplex_t)(V2(1,0)) , (qcomplex_t)((EigenComplexT)1.0 / V2(1,1))};\n\n\t\tauto entry = entries.back().back().second;\n\t\tcir_units.insert(cir_units.begin(), std::make_pair(entry, M2));\n\t}\n}\n\nstatic void initialize(EigenMatrixXc& matrix, MatrixOperator& entries)\n{\n    auto qubits = (int)std::log2(matrix.rows());\n\n    MatrixSequence Cns(qubits, MatrixUnit::SINGLE_I2);\n    Cns.back() = MatrixUnit::SINGLE_V2;\n    entries.front().emplace_back(make_pair(1, Cns));\n\n    ColumnOperator& column = entries.front();\n    for (auto idx = 1; idx < qubits; ++idx)\n    {\n        size_t path = 1ull << idx;\n        for (auto opt = 0; opt < (1 << idx) - 1; ++opt)\n        {\n            auto entry = column[opt].first;\n            auto units = column[opt].second;\n\n            // 1 : none of cn−1, . . . , c1 equals 1\n            // * : otherwise\n            auto iter = std::find(units.end() - idx, units.end(), MatrixUnit::SINGLE_P1);\n\n            units[units.size() - 1 - idx] = (units.end() == iter) ?\n                MatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\n            column.emplace_back(make_pair(entry + path, units));\n        }\n\n        MatrixSequence Lns(qubits, MatrixUnit::SINGLE_I2);\n        Lns[qubits - idx - 1] = MatrixUnit::SINGLE_V2;\n\n        column.emplace_back(make_pair((1ull << idx), Lns));\n    }\n\n    return;\n}\n\nstatic void general_scheme(EigenMatrixXc& matrix, std::vector<SingleGateUnit>& cir_units)\n{\n\tMatrixOperator entries;\n\tfor (auto idx = 1; idx < matrix.cols(); ++idx)\n\t{\n\t\tColumnOperator Co;\n\t\tentries.emplace_back(Co);\n\t}\n\n\tinitialize(matrix, entries);\n \trecursive_partition(matrix, entries);\n\tdecomposition(matrix, entries, cir_units);\n\n    return;\n}\n\nstatic void circuit_insert(QVec& qubits, std::vector<SingleGateUnit>& cir_units, QCircuit &circuit)\n{\n\tstd::sort(qubits.begin(), qubits.end(), [&](Qubit *a, Qubit *b)\n\t{\n\t\treturn a->getPhysicalQubitPtr()->getQubitAddr()\n\t\t\t < b->getPhysicalQubitPtr()->getQubitAddr();\n\t});\n\n\tauto rank = qubits.size();\n\tfor (auto &val : cir_units)\n\t{\n\t\tQVec control;\n\t\tQCircuit cir;\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_P0 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcir << X(qubits[qdx]);\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse if (MatrixUnit::SINGLE_P1 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse\n\t\t\t{}\n\t\t}\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_V2 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcircuit << cir\n\t\t\t\t\t    << U4(val.second, qubits[qdx]).control(control).dagger()\n\t\t\t\t\t\t<< cir;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*******************************************************************\n*                      class DiagonalMatrixDecompose\n********************************************************************/\nclass DiagonalMatrixDecompose\n{\npublic:\n\tDiagonalMatrixDecompose() {}\n\t~DiagonalMatrixDecompose() {}\n\n\n\tQCircuit decompose(const QVec& qubits, const QStat& src_mat)\n\t{\n\t\t//check param\n\t\tif (!is_unitary_matrix(src_mat))\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, the input matrix is not a unitary-matrix.\");\n\t\t}\n\n\t\tconst auto mat_dimension = sqrt(src_mat.size());\n\t\tconst auto need_qubits_num = ceil(log2(mat_dimension));\n\t\tif (need_qubits_num > qubits.size())\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, no enough qubits.\");\n\t\t}\n\n\t\tQCircuit decompose_result_cir;\n\t\tm_qubits = qubits;\n\t\tQVec controlqvec = qubits;\n\t\tcontrolqvec.pop_back();\n\t\tQStat tmp_mat22; //2*2 unitary matrix\n\t\tconst size_t tmp_base_unitary_cnt = mat_dimension / 2;\n\t\tlong pre_index = -1;\n\t\tfor (size_t i = 0; i < tmp_base_unitary_cnt; ++i)\n\t\t{\n\t\t\ttmp_mat22.clear();\n\t\t\tconst size_t tmp_row = (2 * i * mat_dimension) + (2 * i);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + 1]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension + 1]);\n\t\t\tQGate tmp_u4 = U4(tmp_mat22, qubits.back()).control(controlqvec);\n\t\t\tQGATE_SPACE::U4* p_gate = dynamic_cast<QGATE_SPACE::U4*>(tmp_u4.getQGate());\n\t\t\tif ((abs(p_gate->getAlpha()) < MAX_MATRIX_PRECISION)\n\t\t\t\t&& (abs(p_gate->getBeta()) < MAX_MATRIX_PRECISION)\n\t\t\t\t&& (abs(p_gate->getGamma()) < MAX_MATRIX_PRECISION)\n\t\t\t\t&& (abs(p_gate->getDelta()) < MAX_MATRIX_PRECISION))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (0 == i)\n\t\t\t{\n\t\t\t\tQCircuit index_cir_zero = index_to_circuit(0, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir_zero;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQCircuit index_cir = index_to_merge_circuit(i, pre_index, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir;\n\t\t\t}\n\n\t\t\tdecompose_result_cir << tmp_u4;\n\t\t\tpre_index = i;\n\t\t}\n\n\t\treturn decompose_result_cir;\n\t}\n\nprotected:\n\tQCircuit index_to_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif (0 == index % 2)\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t pre_index = index - 1;\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t\tpre_index /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, long pre_index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t tmp_pre_index = pre_index;\n\t\tif (pre_index < 0)\n\t\t{\n\t\t\ttmp_pre_index = 1;\n\t\t}\n\t\t\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (tmp_pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\n\t\t\tif (pre_index > 0)\n\t\t\t{\n\t\t\t\ttmp_pre_index /= 2;\n\t\t\t}\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\nprivate:\n\tQVec m_qubits;\n};\n\n/*******************************************************************\n*                      class HQRDecompose\n* Householder QR-decompose\n* refer to <Quantum circuits synthesis using Householder transformations>(https://arxiv.org/abs/2004.07710v1)\n********************************************************************/\nclass HQRDecompose\n{\npublic:\n\tHQRDecompose() \n\t\t:m_dimension(0)\n\t{}\n\t~HQRDecompose() {}\n\n\tQCircuit decompose(QVec qubits, const EigenMatrixXc& src_mat)\n\t{\n\t\t//check param\n\t\tif (!src_mat.isUnitary(MAX_MATRIX_PRECISION))\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, the input matrix is not a unitary-matrix.\");\n\t\t}\n\n\t\t\n\t\tconst auto mat_dimension = src_mat.rows();\n\t\tconst auto need_qubits_num = ceil(log2(mat_dimension));\n\t\tif (need_qubits_num > qubits.size())\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, no enough qubits.\");\n\t\t}\n\n\t\t// do Householder QR_decompose\n\t\tm_dimension = mat_dimension;\n\t\tm_qubits = qubits;\n\t\tauto start = system_clock::now();\n\t\tHouseholder_QR_decompose(src_mat);\n\n#if PRINT_TRACE\n\t\tauto end = system_clock::now();\n\t\tauto duration = duration_cast<microseconds>(end - start);\n\t\tPTrace(\"Total used: %f s\",\n\t\t\tdouble(duration.count()) * microseconds::period::num / microseconds::period::den);\n#endif\n\n\t\treturn m_result_cir;\n\t}\n\nprotected:\n\tvoid print_vec(const QStat& vec)\n\t{\n\t\tfor (auto i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tprintf(\"(%-g, %-g), \", vec[i].real(), vec[i].imag());\n\t\t}\n\n\t\tprintf(\"\\n\");\n\t}\n\n\tvoid Householder_QR_decompose(EigenMatrixXc src_mat)\n\t{\n\t\tconst auto& lines = m_dimension;\n\t\tQStat tmp_mat_R(m_dimension * m_dimension);\n\t\tQCircuit cir_Q;\n\t\tfor (size_t cur_col = 0; cur_col < lines; ++cur_col)\n\t\t{\n\t\t\t//printf(\"On column %ld\\n\", cur_col);\n\t\t\tconst auto cur_col_size = lines - cur_col;\n\t\t\tQStat cur_col_vec(cur_col_size);\n\t\t\tQStat cur_col_vec_dagger(cur_col_size);\n\t\t\tqstate_type norm = 0;\n\t\t\tfor (size_t cur_row = cur_col; cur_row < lines; ++cur_row)\n\t\t\t{\n\t\t\t\tcur_col_vec[cur_row - cur_col] = -src_mat(cur_row, cur_col);\n\t\t\t\tnorm += (cur_col_vec[cur_row - cur_col].real() * cur_col_vec[cur_row - cur_col].real() +\n\t\t\t\t\tcur_col_vec[cur_row - cur_col].imag() * cur_col_vec[cur_row - cur_col].imag());\n\t\t\t}\n\n\t\t\tnorm = sqrt(norm);\n\t\t\tconst double angle = arg(cur_col_vec[0]);\n\t\t\tcur_col_vec[0] -= exp(qcomplex_t(0, angle)); // ?\n\t\t\t//vec[0] = exp(complex_t(0, 1.0 * angle)) * (sqrt(vec[0].real() * vec[0].real() + vec[0].imag() * vec[0].imag()) - tmp_x);\n\n\t\t\tnorm = 0.0;\n\t\t\tfor (size_t i = 0; i < cur_col_size; ++i)\n\t\t\t{\n\t\t\t\tnorm += (cur_col_vec[i].real() * cur_col_vec[i].real() + cur_col_vec[i].imag() * cur_col_vec[i].imag());\n\t\t\t}\n\n\t\t\tif (norm > 1e-7)\n\t\t\t{\n\t\t\t\t// vec Dagger  \n\t\t\t\tfor (size_t i = 0; i < cur_col_size; ++i)\n\t\t\t\t{\n\t\t\t\t\tqstate_type real_v = cur_col_vec[i].real();\n\t\t\t\t\tqstate_type imag_v = cur_col_vec[i].imag();\n\t\t\t\t\t//cur_col_vec[i] = qcomplex_t(real_v, imag_v);\n\t\t\t\t\tcur_col_vec_dagger[i] = qcomplex_t(real_v, -imag_v);\n\t\t\t\t}\n#if PRINT_TRACE\n\t\t\t\tprintf(\"The vec:\\n\");\n\t\t\t\tprint_vec(cur_col_vec);\n\t\t\t\tprintf(\"The vec_dagger:\\n\");\n\t\t\t\tprint_vec(cur_col_vec_dagger);\n\t\t\t\tprintf(\":::::::::::::::::::::::::::::\\n\");\n#endif\n\t\t\t\t//sestavit matici P\n\t\t\t\tEigenMatrixXc matrix_p(cur_col_size, cur_col_size);\n\t\t\t\tfor (size_t k = 0; k < cur_col_size; ++k)\n\t\t\t\t{\n\t\t\t\t\tfor (size_t h = 0; h < cur_col_size; ++h)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (k == h)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmatrix_p(k, k) = qcomplex_t(1, 0) - qcomplex_t(2, 0) * cur_col_vec[k] * cur_col_vec_dagger[h] / norm;\n\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\tmatrix_p(k, h) = -qcomplex_t(2, 0) * cur_col_vec[k] * cur_col_vec_dagger[h] / norm;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tPTrace(\"-----tmp matrixP:\\n\");\n\t\t\t\tPTraceMat(matrix_p);\n\t\t\t\tPTrace(\"tmp matrixP end -----------:\\n\");\n\n\t\t\t\tauto norm_sqr = sqrt(norm);\n\t\t\t\tfor (size_t i = 0; i < cur_col_size; ++i)\n\t\t\t\t{\n\t\t\t\t\tcur_col_vec[i] /= norm_sqr;\n\t\t\t\t}\n\t\t\t\tcir_Q << build_cir_Pi(cur_col_vec);\n\t\t\t\t/*using testMat = Eigen::Matrix<qcomplex_t, -1, -1, Eigen::RowMajor>;\n\t\t\t\ttestMat mat_test_1 = testMat::Map(&matrix_p[0], cur_col_size, cur_col_size);*/\n\t\t\t\t/*testMat mat_test_2 = testMat::Map(&src_mat[0], m_dimension, m_dimension);*/\n\t\t\t\tEigenMatrixXc mat_test_3 = src_mat.bottomRightCorner(m_dimension - cur_col, m_dimension - cur_col);\n\t\t\t\tmatrix_p *= mat_test_3;\n\t\t\t\t//src_mat.block(cur_col, cur_col, m_dimension - cur_col, m_dimension - cur_col) *= matrix_p;\n\t\t\t\t//src_mat.bottomRightCorner(m_dimension - cur_col, m_dimension - cur_col) = matrix_p;\n\t\t\t\tsrc_mat.block(cur_col, cur_col, m_dimension - cur_col, m_dimension - cur_col) = matrix_p;\n\t\t\t\tPTrace(\"-----tmp matrixA:\\n\");\n\t\t\t\tPTraceMat(src_mat);\n\t\t\t\tPTrace(\"tmp matrixA end -----------:\\n\");\n\t\t\t}\n\t\t}\n\n\t\t//QCircuit last_cir_D = matrix_decompose(m_qubits, src_mat);\n\t\tQStat mat_r(src_mat.data(), src_mat.data() + src_mat.size());\n\t\tQCircuit last_cir_D = diagonal_matrix_decompose(m_qubits, mat_r);\n\t\tm_result_cir << last_cir_D << cir_Q.dagger();\n\t}\n\n\tQCircuit build_cir_Pi(const QStat& cur_col_vec)\n\t{\n\t\tQStat full_cur_vec(m_dimension - cur_col_vec.size(), qcomplex_t(0, 0));\n\t\tfull_cur_vec.insert(full_cur_vec.end(), cur_col_vec.begin(), cur_col_vec.end());\n\t\tif (full_cur_vec.size() != m_dimension)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: current vector size error on HQRDecompose.\");\n\t\t}\n\n\t\tQCircuit cir_swap_qubits;\n\t\tfor (size_t i = 0; (i * 2) < (m_qubits.size() - 1); ++i)\n\t\t{\n\t\t\tcir_swap_qubits << SWAP(m_qubits[i], m_qubits[m_qubits.size() - 1 - i]);\n\t\t}\n\n\t\tstd::vector<double> ui_mod(m_dimension);\n\t\tstd::vector<double> ui_angle(m_dimension);\n\t\tdouble tatal = 0.0;\n\t\tfor (size_t i = 0; i < m_dimension; ++i)\n\t\t{\n\t\t\tauto tmp_m = full_cur_vec[i].real() * full_cur_vec[i].real() + full_cur_vec[i].imag() * full_cur_vec[i].imag();\n\t\t\ttatal += tmp_m;\n\t\t\tui_mod[i] = sqrt(tmp_m);\n\t\t\tui_angle[i] = arg(full_cur_vec[i]);\n\t\t}\n\n\t\tQStat mat_d(m_dimension * m_dimension, qcomplex_t(0, 0));\n\t\tfor (size_t i = 0; i < m_dimension; ++i)\n\t\t{\n\t\t\tmat_d[i + i * m_dimension] = exp(qcomplex_t(0, ui_angle[i]));\n\t\t}\n\n\t\tQCircuit cir_d = diagonal_matrix_decompose(m_qubits, mat_d);\n\t\t\n\t\tPTrace(\"cir_d:\\n\");\n\t\tPTraceCircuit(cir_d);\n\n#if PRINT_TRACE\n\t\tconst auto mat_test_d = getCircuitMatrix(cir_d);\n\t\tPTrace(\"mat_test_d:\\n\");\n\t\tPTraceCircuit(mat_test_d);\n\t\tif (mat_test_d == mat_d)\n\t\t{\n\t\t\tcout << \"matrix decompose okkkkkkkkkkkkkkk\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"ffffffffffffffffffffailed on matrix decompose.\" << endl;\n\t\t}\n#endif\n\n\t\tQCircuit cir_y = build_cir_b(m_qubits, ui_mod);\n\t\tQCircuit cir_P;\n\t\tcir_P << cir_y << cir_swap_qubits  << cir_d << cir_swap_qubits;\n\n\t\tQCircuit cir_DG = zero_phase_shift_cir();\n\t\tQCircuit cir_pi;\n\t\tcir_pi << cir_swap_qubits  << cir_P.dagger() << cir_DG << cir_P << cir_swap_qubits;\n\n\t\treturn cir_pi;\n\t}\n\n\tQCircuit zero_phase_shift_cir()\n\t{\n\t\tQCircuit cir_DG;\n\t\tQVec tmp_qubits = m_qubits;\n\t\ttmp_qubits.pop_back();\n\t\tcir_DG << applyQGate(m_qubits, X) << Z(m_qubits.back()).control(tmp_qubits) << applyQGate(m_qubits, X);\n\n\t\treturn cir_DG;\n\t}\n\n\tQCircuit build_cir_b(QVec qubits, const std::vector<double>& b)\n\t{\n\t\treturn amplitude_encode(qubits, b);\n\t}\n\nprivate:\n\tQVec m_qubits;\n\tsize_t m_dimension;\n\tQCircuit m_result_cir;\n};\n\nstatic QCircuit Householder_qr_matrix_decompose(QVec qubits, const EigenMatrixXc& src_mat)\n{\n\treturn HQRDecompose().decompose(qubits, src_mat);\n}\n\n/*******************************************************************\n*                      public interface\n********************************************************************/\nQCircuit QPanda::matrix_decompose(QVec qubits, const QStat& src_mat, DecompositionMode de_mode/* = HOUSEHOLDER_QR*/)\n{\n\tauto order = std::sqrt(src_mat.size());\n\tEigenMatrixXc tmp_mat = EigenMatrixXc::Map(&src_mat[0], order, order);\n\n\treturn matrix_decompose(qubits, tmp_mat, de_mode);\n}\n\nQCircuit QPanda::matrix_decompose(QVec qubits, EigenMatrixXc& src_mat, DecompositionMode de_mode/* = HOUSEHOLDER_QR*/)\n{\n\tif (!src_mat.isUnitary(MAX_MATRIX_PRECISION))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"Non-unitary matrix.\");\n\t}\n\n\tif (qubits.size() != log2(src_mat.cols()))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"The qubits number is error.\");\n\t}\n\n\tQCircuit output_circuit;\n\tswitch (de_mode)\n\t{\n\tcase HOUSEHOLDER_QR:\n\t\toutput_circuit = Householder_qr_matrix_decompose(qubits, src_mat);\n\t\tbreak;\n\n\tdefault:\n\t{\n\t\t//QR decompose\n\t\tstd::vector<SingleGateUnit> cir_units;\n\t\tgeneral_scheme(src_mat, cir_units);\n\t\tcircuit_insert(qubits, cir_units, output_circuit);\n\t}\n\t\tbreak;\n\t}\n\t\n\treturn output_circuit;\n}\n\nQCircuit QPanda::diagonal_matrix_decompose(const QVec& qubits, const QStat& src_mat)\n{\n\treturn DiagonalMatrixDecompose().decompose(qubits, src_mat);\n}\n", "meta": {"hexsha": "424fa629592a7e81ce9c7f1bf2a511df1bd34e76", "size": 22590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_stars_repo_name": "YeweiYuan/QPanda-2", "max_stars_repo_head_hexsha": "7087f1a002e8248bc46e6c16968fae5071243efd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-04T06:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T06:52:53.000Z", "max_issues_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_issues_repo_name": "YeweiYuan/QPanda-2", "max_issues_repo_head_hexsha": "7087f1a002e8248bc46e6c16968fae5071243efd", "max_issues_repo_licenses": ["Apache-2.0"], "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/Utilities/Tools/MatrixDecomposition.cpp", "max_forks_repo_name": "YeweiYuan/QPanda-2", "max_forks_repo_head_hexsha": "7087f1a002e8248bc46e6c16968fae5071243efd", "max_forks_repo_licenses": ["Apache-2.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.4150485437, "max_line_length": 154, "alphanum_fraction": 0.6305887561, "num_tokens": 7287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476784277755, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5777460652236354}}
{"text": "#include \"Angle.hpp\"\n#include <boost/format.hpp>\n#include <base/Eigen.hpp>\n\nnamespace base {\n\nAngle Angle::vectorToVector(const Vector3d& a, const Vector3d& b)\n{\n    double dot = a.dot(b);\n    double norm = a.norm() * b.norm();\n    return fromRad(acos(dot / norm));\n}\n\nAngle Angle::vectorToVector(const Vector3d& a, const Vector3d& b, const Vector3d& positive)\n{\n    double cos = a.dot(b) / (a.norm() * b.norm());\n\n    bool is_positive = (a.cross(b).dot(positive) > 0);\n    if (is_positive)\n        return fromRad(acos(cos));\n    else\n        return fromRad(-acos(cos));\n}\n\nstd::ostream& operator << (std::ostream& os, Angle angle)\n{\n    os << angle.getRad() << boost::format(\"[%3.1fdeg]\") % angle.getDeg();\n    return os;\n}\n\nAngleSegment::AngleSegment(): width(0), startRad(0), endRad(0)\n{\n}\n\nAngleSegment::AngleSegment(const Angle &start, double _width): width(_width), startRad(start.getRad()), endRad(startRad + width)\n{\n    if(width < 0)\n        throw std::runtime_error(\"Error got segment with negative width\");\n}\n\nbool AngleSegment::isInside(const Angle& angle) const\n{\n    double angleRad = angle.getRad();\n    if(angleRad < startRad)\n        angleRad += 2*M_PI;\n    \n    if(angleRad <= endRad) //startRad <= angleRad && \n        return true;\n    \n    return false;\n}\n\nbool AngleSegment::isInside(const AngleSegment& segment) const\n{\n    double otherStart = segment.startRad;\n    if(otherStart < startRad)\n        otherStart += 2*M_PI;\n\n    double otherEnd = otherStart + segment.width;\n    \n    if(otherEnd <= endRad)\n        return true;\n    \n    return false;\n}\n\nstd::vector< AngleSegment > AngleSegment::getIntersections(const AngleSegment& b) const\n{\n    std::vector<AngleSegment> ret;\n    //special case, this segment is a whole circle\n    if(width >= 2*M_PI)\n    {\n        ret.push_back(b);\n        return ret;\n    }\n    \n    //special case, other segment is a whole circle\n    if(b.width >= 2*M_PI)\n    {\n        ret.push_back(*this);\n        return ret;\n    }\n\n    double startA = startRad;\n    double startB = b.startRad;\n    double widthA = width;\n    double widthB = b.width;\n    \n    //make A the smaller angle\n    if(startA > startB)\n    {\n        std::swap(startA, startB);\n        std::swap(widthA, widthB);\n    }\n    double endA = startA + widthA;\n    double endB = startB + widthB;\n\n    //test if segemnts do not intersect at all\n    if(endA < startB)\n    {\n        //wrap case\n        if(endB > M_PI)\n        {\n            //check if segments intersect after wrap correction\n            if(startA < endB - 2*M_PI)\n            {\n                //this means the start of A is inside of B\n                //drop first part of B and realign it to -M_PI\n                //also switch A and B as B is now the 'lower' one\n                double newWidthA = widthB - (M_PI - startB);\n                startB = startA;\n                widthB = widthA;\n                startA = - M_PI;\n                widthA = newWidthA;\n                endA = startA + widthA;\n                endB = startB + widthB;\n                //no return, still need \n                //to check for intersection\n            }\n            else\n                //no intersection\n                return ret;\n        } else\n                //no intersection\n            return ret;\n    }\n\n    //normal case, no wrap around\n    double newStart = startB;        \n    double newEnd = 0;\n    \n    if(endA < endB)\n    {\n        newEnd = endA;\n    }\n    else\n    {\n        newEnd = endB;\n    }\n    \n    double newWidth = newEnd - newStart;\n\n    //filter invalid segments\n    if(newWidth > 1e-10)\n        ret.push_back(AngleSegment(Angle::fromRad(newStart), newWidth));\n    \n    newStart = endB - 2*M_PI;\n    if(newStart > startA)\n    {\n        newWidth = newStart - startA;\n        //filter invalid segments\n        if(newWidth > 1e-10)\n            ret.push_back(AngleSegment(Angle::fromRad(startA), newWidth));\n    }\n    \n    return ret;\n}\n\nAngle AngleSegment::getStart() const\n{\n    return Angle::fromRad(startRad);\n}\n\nAngle AngleSegment::getEnd() const\n{\n    return Angle::fromRad(endRad);\n}\n\nstd::ostream& operator << (std::ostream& os, AngleSegment seg)\n{\n    os << \" Segmend start \" << seg.startRad/M_PI *180.0 << \" end  \" << seg.endRad/M_PI * 180.0 << \" width \" << seg.width /M_PI * 180.0;\n    return os;\n}\n\n} //end namespace base\n", "meta": {"hexsha": "6f0a4f4df2cfc35456db8c9edad90cb359d063b3", "size": 4320, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gr740_stream_aligner/Angle.cc", "max_stars_repo_name": "ESROCOS/gr740-stream_aligner", "max_stars_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gr740_stream_aligner/Angle.cc", "max_issues_repo_name": "ESROCOS/gr740-stream_aligner", "max_issues_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gr740_stream_aligner/Angle.cc", "max_forks_repo_name": "ESROCOS/gr740-stream_aligner", "max_forks_repo_head_hexsha": "fbcd23ab655b5cf2c1fcb8a0a5b6d2be66a5ebef", "max_forks_repo_licenses": ["BSD-3-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.5454545455, "max_line_length": 135, "alphanum_fraction": 0.5719907407, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5777460593422082}}
{"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_QUATERNION_HPP\n#define RW_MATH_QUATERNION_HPP\n\n/**\n * @file Quaternion.hpp\n */\n\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n#include <rw/math/Rotation3D.hpp>\n#include <rw/math/Rotation3DVector.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ostream>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A Quaternion @f$ \\mathbf{q}\\in \\mathbb{R}^4 @f$ a complex\n     * number used to describe rotations in 3-dimensional space.\n     * @f$ q_w+{\\bf i}\\ q_x+ {\\bf j} q_y+ {\\bf k}\\ q_z @f$\n     *\n     * Quaternions can be added and multiplied in a similar way as usual\n     * algebraic numbers. Though there are differences. Quaternion\n     * multiplication is not commutative which means\n     * \\f$ Q\\cdot P \\neq P\\cdot Q \\f$\n     */\n    template< class T = double > class Quaternion : public rw::math::Rotation3DVector< T >\n    {\n      private:\n        typedef Eigen::Quaternion< T > EigenQuaternion;\n\n\n      public:\n\n        //! Value type.\n        typedef T value_type;\n\n        /**\n         * @brief constuct Quaterinion of {0,0,0,1}\n         */\n        Quaternion () : _q (0, 0, 0, 1) {}\n\n        /**\n         * @brief Creates a Quaternion\n         * @param qx [in] @f$ q_x @f$\n         * @param qy [in] @f$ q_y @f$\n         * @param qz [in] @f$ q_z @f$\n         * @param qw  [in] @f$ q_w @f$\n         */\n        Quaternion (T qx, T qy, T qz, T qw) : _q (qw, qx, qy, qz) {}\n\n        /**\n         * @brief Creates a Quaternion from another Quaternion\n         * @param quat [in] Quaternion\n         */\n        Quaternion (const Quaternion< T >& quat) : _q (quat._q) {}\n\n        /**\n         * @brief Creates a Quaternion from another Rotation3DVector type\n         * @param rot [in] The Rotation3DVector type\n         */\n        Quaternion (const rw::math::Rotation3DVector< T >& rot)\n        {\n            setRotation (rot.toRotation3D ());\n        }\n\n        /**\n         * @brief Extracts a Quaternion from Rotation matrix using\n         * setRotation(const Rotation3D<R>& rot)\n         * @param rot [in] A 3x3 rotation matrix @f$ \\mathbf{rot} @f$\n         */\n        Quaternion (const rw::math::Rotation3D< T >& rot) { setRotation (rot); }\n\n        /**\n         * @brief Creates a Quaternion from a Eigen quaternion\n         * @param r [in] a boost quaternion\n         */\n        Quaternion (const Eigen::Quaternion< T >& r) : _q (r) {}\n\n        /**\n         * @brief Creates a Quaternion from vector_expression\n         *\n         * @param r [in] an Eigen Vector\n         */\n        template< class R >\n        explicit Quaternion (const Eigen::MatrixBase< R >& r) :\n            _q (r.row (3) (0), r.row (0) (0), r.row (1) (0), r.row (2) (0))\n        {}\n\n        // ###################################################\n        // #                Acces Operators                  #\n        // ###################################################\n\n        /**\n         * @brief get method for the x component\n         * @return the x component of the quaternion\n         */\n        inline T getQx () const { return _q.x (); }\n\n        /**\n         * @brief get method for the y component\n         * @return the y component of the quaternion\n         */\n        inline T getQy () const { return _q.y (); }\n\n        /**\n         * @brief get method for the z component\n         * @return the z component of the quaternion\n         */\n        inline T getQz () const { return _q.z (); }\n\n        /**\n         * @brief get method for the w component\n         * @return the w component of the quaternion\n         */\n        inline T getQw () const { return _q.w (); }\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to Quaternion element\n         * @param i [in] index in the quaternion \\f$i\\in \\{0,1,2,3\\} \\f$\n         * @return const reference to element\n         */\n        inline T operator() (size_t i) const\n        {\n            switch (i) {\n                case 0: return _q.x ();\n                case 1: return _q.y ();\n                case 2: return _q.z ();\n                case 3: return _q.w ();\n                default: assert (0); return _q.x ();\n            }\n        }\n\n        /**\n         * @brief Returns reference to Quaternion element\n         * @param i [in] index in the quaternion \\f$i\\in \\{0,1,2,3\\} \\f$\n         * @return reference to element\n         */\n        inline T& operator() (size_t i)\n        {\n            switch (i) {\n                case 0: return _q.x ();\n                case 1: return _q.y ();\n                case 2: return _q.z ();\n                case 3: return _q.w ();\n                default: assert (0); return _q.x ();\n            }\n        }\n\n        /**\n         * @brief Returns reference to Quaternion element\n         * @param i [in] index in the quaternion \\f$i\\in \\{0,1,2,3\\} \\f$\n         * @return reference to element\n         */\n        inline T& operator[] (size_t i)\n        {\n            switch (i) {\n                case 0: return _q.x ();\n                case 1: return _q.y ();\n                case 2: return _q.z ();\n                case 3: return _q.w ();\n                default: assert (0); return _q.x ();\n            }\n        }\n\n        /**\n         * @brief Returns reference to Quaternion element\n         * @param i [in] index in the quaternion \\f$i\\in \\{0,1,2,3\\} \\f$\n         * @return reference to element\n         */\n        inline T operator[] (size_t i) const\n        {\n            switch (i) {\n                case 0: return _q.x ();\n                case 1: return _q.y ();\n                case 2: return _q.z ();\n                case 3: return _q.w ();\n                default: assert (0); return _q.x ();\n            }\n        }\n#else\n        ARRAYOPERATOR (T);\n#endif\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Calculates the @f$ 3\\times 3 @f$ Rotation matrix\n         *\n         * @return A 3x3 rotation matrix @f$ \\mathbf{rot} @f$\n         * @f$\n         * \\mathbf{rot} =\n         *  \\left[\n         *   \\begin{array}{ccc}\n         *      1-2(q_y^2-q_z^2) & 2(q_x\\ q_y+q_z\\ q_w)& 2(q_x\\ q_z-q_y\\ q_w) \\\\\n         *      2(q_x\\ q_y-q_z\\ q_w) & 1-2(q_x^2-q_z^2) & 2(q_y\\ q_z+q_x\\ q_w)\\\\\n         *      2(q_x\\ q_z+q_y\\ q_w) & 2(q_y\\ q_z-q_x\\ q_z) & 1-2(q_x^2-q_y^2)\n         *    \\end{array}\n         *  \\right]\n         * @f$\n         *\n         */\n#endif\n        inline const rw::math::Rotation3D< T > toRotation3D () const\n        {\n            const T qx = _q.x ();\n            const T qy = _q.y ();\n            const T qz = _q.z ();\n            const T qw = _q.w ();\n\n            return rw::math::Rotation3D< T > (1 - 2 * qy * qy - 2 * qz * qz,\n                                              2 * (qx * qy - qz * qw),\n                                              2 * (qx * qz + qy * qw),\n                                              2 * (qx * qy + qz * qw),\n                                              1 - 2 * qx * qx - 2 * qz * qz,\n                                              2 * (qy * qz - qx * qw),\n                                              2 * (qx * qz - qy * qw),\n                                              2 * (qy * qz + qx * qw),\n                                              1 - 2 * qx * qx - 2 * qy * qy);\n        }\n\n        /** @brief Converts a Rotation3D to a Quaternion and saves the Quaternion\n         * in this.\n         *\n         * @param rot [in] A 3x3 rotation matrix @f$ \\mathbf{R} @f$\n         *\n         * @f$\n         * \\begin{array}{c}\n         * q_x\\\\ q_y\\\\ q_z\\\\ q_w\n         * \\end{array}\n         * =\n         *  \\left[\n         *   \\begin{array}{c}\n         *      \\\\\n         *      \\\\\n         *\n         *    \\end{array}\n         *  \\right]\n         * @f$\n         *\n         * The conversion method is proposed by Henrik Gordon Petersen. The switching between\n         * different cases occur well before numerical instabilities, hence the solution should be\n         * more robust, than many of the methods proposed elsewhere.\n         *\n         */\n        template< class R > void setRotation (const rw::math::Rotation3D< R >& rot)\n        {\n            // The method\n            const T min  = (T) (-0.9);\n            const T min1 = (T) (min / 3.0);\n\n            const T tr = rot (0, 0) + rot (1, 1) + rot (2, 2);\n\n            if (tr > min) {\n                const T s = static_cast< T > (0.5) / static_cast< T > (sqrt (tr + 1.0));\n                _q.w ()   = static_cast< T > (0.25) / s;\n                _q.x ()   = static_cast< T > (rot (2, 1) - rot (1, 2)) * s;\n                _q.y ()   = static_cast< T > (rot (0, 2) - rot (2, 0)) * s;\n                _q.z ()   = static_cast< T > (rot (1, 0) - rot (0, 1)) * s;\n            }\n            else {\n                if (rot (0, 0) > min1) {\n                    const T sa =\n                        static_cast< T > (sqrt (rot (0, 0) - rot (1, 1) - rot (2, 2) + 1.0));\n                    _q.x ()   = static_cast< T > (0.5) * sa;\n                    const T s = static_cast< T > (0.25) / _q.x ();\n                    _q.y ()   = static_cast< T > (rot (0, 1) + rot (1, 0)) * s;\n                    _q.z ()   = static_cast< T > (rot (0, 2) + rot (2, 0)) * s;\n                    _q.w ()   = static_cast< T > (rot (2, 1) - rot (1, 2)) * s;\n                }\n                else if (rot (1, 1) > min1) {\n                    const T sb = static_cast< T > (sqrt (rot (1, 1) - rot (2, 2) - rot (0, 0) + 1));\n                    _q.y ()    = static_cast< T > (0.5) * sb;\n\n                    const T s = static_cast< T > (0.25) / _q.y ();\n                    _q.x ()   = static_cast< T > (rot (0, 1) + rot (1, 0)) * s;\n                    _q.z ()   = static_cast< T > (rot (1, 2) + rot (2, 1)) * s;\n                    _q.w ()   = static_cast< T > (rot (0, 2) - rot (2, 0)) * s;\n                }\n                else {\n                    const T sc = static_cast< T > (sqrt (rot (2, 2) - rot (0, 0) - rot (1, 1) + 1));\n                    _q.z ()    = static_cast< T > (0.5) * sc;\n\n                    const T s = static_cast< T > (0.25) / _q.z ();\n                    _q.x ()   = static_cast< T > (rot (0, 2) + rot (2, 0)) * s;\n                    _q.y ()   = static_cast< T > (rot (1, 2) + rot (2, 1)) * s;\n                    _q.w ()   = static_cast< T > (rot (1, 0) - rot (0, 1)) * s;\n                }\n            }\n        }\n\n        /**\n         * @brief The dimension of the quaternion (i.e. 4).\n         * This method is provided to help support generic algorithms using\n         * size() and operator[].\n         */\n        size_t size () const { return 4; }\n\n        /**\n         * @brief Convert to an Eigen Quaternion.\n         * @return Eigen Quaternion representation.\n         */\n        Eigen::Quaternion< T >& e () { return _q; }\n\n        //! @copydoc e()\n        const Eigen::Quaternion< T >& e () const { return _q; }\n\n        /**\n         * @brief convert to Eigen Vector\n         * @return eigen Vector of quaternion\n         */\n        Eigen::Matrix< T, 4, 1 > toEigenVector () const\n        {\n            return Eigen::Matrix< T, 4, 1 > (_q.x (), _q.y (), _q.z (), _q.w ());\n        }\n\n        // ###################################################\n        // #                 Math Operators                  #\n        // ###################################################\n\n        // ############ Quaternion Operations\n\n        /**\n         * @brief Unary minus.\n         */\n        Quaternion< T > operator- () const\n        {\n            return Quaternion (-_q.x (), -_q.y (), -_q.z (), -_q.w ());\n        }\n\n        /**\n         * @brief Unary plus.\n         */\n        Quaternion< T > operator+ () const { return Quaternion (*this); }\n\n        /**\n         * @brief Subtraction.\n         */\n        inline const Quaternion< T > operator- (const Quaternion< T >& v)\n        {\n            return Quaternion< T > (\n                (*this) (0) - v (0), (*this) (1) - v (1), (*this) (2) - v (2), (*this) (3) - v (3));\n        }\n\n        /**\n         * @brief Multiply-from operator\n         */\n        inline Quaternion< T > operator* (const Quaternion< T >& r) const\n        {\n            Quaternion q = Quaternion (_q * r.e ());\n            return q;\n        }\n\n        /**\n           @brief Addition of two quaternions\n         */\n        inline const Quaternion< T > operator+ (const Quaternion< T >& v) const\n        {\n            return Quaternion< T > (\n                (*this) (0) + v (0), (*this) (1) + v (1), (*this) (2) + v (2), (*this) (3) + v (3));\n        }\n\n        // ############ Scalar Operations\n\n        /**\n         * @brief Scalar multiplication.\n         */\n        inline const Quaternion< T > operator* (T s) const\n        {\n            return Quaternion< T > (_q.x () * s, _q.y () * s, _q.z () * s, _q.w () * s);\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar multiplication.\n         */\n        inline friend const Quaternion< T > operator* (T s, const Quaternion< T >& v)\n        {\n            return v * s;\n        }\n#endif\n        /**\n         * @brief element whise division\n         * @param lhs [in] the scalar to devide with\n         * @return the result of elementwise devision\n         */\n        Quaternion< T > elemDivide (const T& lhs) const;\n\n        // ############ Math Operations\n\n        /**\n         * @brief get length of quaternion\n         * @f$ \\sqrt{q_x^2+q_y^2+q_z^2+q_w^2} @f$\n         * @return the length og this quaternion\n         */\n        inline T getLength () const { return _q.norm (); }\n\n        /**\n         * @brief get squared length of quaternion\n         * @f$ q_x^2+q_y^2+q_z^2+q_w^2 @f$\n         * @return the length og this quaternion\n         */\n        inline T getLengthSquared () const { return _q.squaredNorm (); }\n\n        /**\n         * @brief normalizes this quaternion so that\n         * @f$ normalze(Q)=\\frac{Q}{\\sqrt{q_x^2+q_y^2+q_z^2+q_w^2}} @f$\n         */\n        inline void normalize () { _q.normalize (); };\n\n        /**\n         * @brief Calculates a slerp interpolation between \\b this and \\b v.\n         *\n         * The slerp interpolation ensures a constant velocity across the interpolation.\n         * For \\f$ t=0\\f$ the result is \\b this and for \\f$ t=1\\f$ it is \\b v.\n         *\n         * @note Algorithm and implementation is thanks to euclideanspace.com\n         */\n        inline const Quaternion< T > slerp (const Quaternion< T >& v, const T t) const\n        {\n            return Quaternion (_q.slerp (t, v.e ()));\n        }\n\n        /*\n         * @brief this will return the exponential of this quaternion \\f$ e^Quaternion \\f$\n         * @return the exponential of this quaternion\n         */\n        Quaternion< T > exp () const;\n\n        /**\n         * @brief Calculate the inverse Quaternion\n         * @return the inverse quaternion\n         */\n        Quaternion< T > inverse () const;\n\n        /**\n         * @brief calculates the natural logerithm of this quaternion\n         * @return natural logetihm\n         */\n        Quaternion< T > ln () const;\n\n        /**\n         * @brief calculates the quaternion lifted to the power of \\b power\n         * @param power [in] the power the quaternion is lifted to\n         * @return \\f$ Quaternion^power \\f$\n         */\n        Quaternion< T > pow (double power) const;\n\n        // ###################################################\n        // #             assignement Operators               #\n        // ###################################################\n\n        /**\n         * @brief copy a boost quaternion to this Quaternion\n         * @param r [in] - boost quaternion\n         */\n        inline void operator= (const Eigen::Quaternion< T >& r) { _q = r; }\n\n        /**\n           @brief Scalar multiplication.\n         */\n        inline const Quaternion< T > operator*= (T s)\n        {\n            _q.x () *= s;\n            _q.y () *= s;\n            _q.z () *= s;\n            _q.w () *= s;\n            return *this;\n        }\n\n        /**\n         * @brief Multiply with operator\n         */\n        inline const Quaternion< T > operator*= (const Quaternion< T >& r)\n        {\n            *this = (*this) * r;\n            return *this;\n        }\n\n        /**\n         *@brief Add-to operator\n         */\n        inline const Quaternion< T > operator+= (const Quaternion< T >& r)\n        {\n            _q.x () += r (0);\n            _q.y () += r (1);\n            _q.z () += r (2);\n            _q.w () += r (3);\n            return *this;\n        }\n\n        /**\n         * @brief Subtract-from operator\n         */\n        inline const Quaternion< T > operator-= (const Quaternion< T >& r)\n        {\n            _q.x () -= r (0);\n            _q.y () -= r (1);\n            _q.z () -= r (2);\n            _q.w () -= r (3);\n            return *this;\n        }\n\n        /**\n         * @brief copyfrom rotaion matrix, same as setRotation.\n         * @param rhs [in] the rotation that will be copyed\n         */\n        Quaternion< T >& operator= (const rw::math::Rotation3D<>& rhs)\n        {\n            this->setRotation (rhs);\n            return (*this);\n        }\n\n        // ###################################################\n        // #              Comparison Operators               #\n        // ###################################################\n\n        /**\n         * @brief Comparison (equals) operator\n         */\n        inline bool operator== (const Quaternion< T >& r) const\n        {\n            return (*this) (0) == r (0) && (*this) (1) == r (1) && (*this) (2) == r (2) &&\n                   (*this) (3) == r (3);\n        }\n\n        /**\n         * @brief Comparison (not equals) operator\n         */\n        inline bool operator!= (const Quaternion< T >& r) const { return !((*this) == r); }\n\n#if defined(SWIG)\n        TOSTRING ();\n#endif\n      private:\n        Eigen::Quaternion< T > _q;\n    };\n\n    /**\n       @brief Streaming operator.\n\n       @relates Quaternion\n    */\n    template< class T > std::ostream& operator<< (std::ostream& out, const Quaternion< T >& v)\n    {\n        return out << \"Quaternion {\" << v (0) << \", \" << v (1) << \", \" << v (2) << \", \" << v (3)\n                   << \"}\";\n    }\n\n    /**\n     * @brief calculates the natural logerithm of this quaternion\n     * @param q [in] the quaternion being operated on\n     * @return natural logetihm\n     */\n    template< class T > Quaternion< T > ln (const Quaternion< T >& q) { return q.ln (); }\n\n    /**\n     * @brief this will return the exponential of this quaternion \\f$ e^Quaternion \\f$\n     * @param q [in] the quaternion being operated on\n     * @return the exponential of this quaternion\n     */\n    template< class T > Quaternion< T > exp (const Quaternion< T >& q) { return q.exp (); }\n\n    /**\n     * @brief Calculate the inverse Quaternion\n     * @param q [in] the quaternion being operated on\n     * @return the inverse quaternion\n     */\n    template< class T > Quaternion< T > inverse (const Quaternion< T >& q) { return q.inverse (); }\n\n    /**\n     * @brief calculates the quaternion lifted to the power of \\b power\n     * @param q [in] the quaternion being operated on\n     * @param power [in] the power the quaternion is lifted to\n     * @return \\f$ Quaternion^power \\f$\n     */\n    template< class T > Quaternion< T > pow (const Quaternion< T >& q, double power)\n    {\n        return q.pow (power);\n    }\n\n    /**\n     * @brief Casts Quaternion<T> to Quaternion<Q>\n     * @param quaternion [in] Quarternion with type T\n     * @return Quaternion with type Q\n     */\n    template< class Q, class T >\n    inline const Quaternion< Q > cast (const Quaternion< T >& quaternion)\n    {\n        return Quaternion< Q > (static_cast< Q > (quaternion (0)),\n                                static_cast< Q > (quaternion (1)),\n                                static_cast< Q > (quaternion (2)),\n                                static_cast< Q > (quaternion (3)));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::Quaternion< double >;\n    extern template class rw::math::Quaternion< float >;\n#else\n\n#if SWIG_VERSION < 0x040000\n    SWIG_DECLARE_TEMPLATE (Quaternion_d, rw::math::Quaternion< double >);\n    ADD_DEFINITION (Quaternion_d, Quaternion)\n#else\n    SWIG_DECLARE_TEMPLATE (Quaternion, rw::math::Quaternion< double >);\n#endif\n    SWIG_DECLARE_TEMPLATE (Quaternion_f, rw::math::Quaternion< float >);\n#endif\n    using Quaterniond = Quaternion< double >;\n    using Quaternionf = Quaternion< 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::Quaternion\n         */\n        template<>\n        void write (const rw::math::Quaternion< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Quaternion\n         */\n        template<>\n        void write (const rw::math::Quaternion< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Quaternion\n         */\n        template<>\n        void read (rw::math::Quaternion< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Quaternion\n         */\n        template<>\n        void read (rw::math::Quaternion< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "6298be0e710d680274db8f4d57dfa7bfae6ebe5e", "size": 22671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Quaternion.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/Quaternion.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/Quaternion.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5866666667, "max_line_length": 100, "alphanum_fraction": 0.458338847, "num_tokens": 5836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5776643975918486}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2014 - 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: Damien Lebrun-Grandie, Bruno Turcksin, 2014 \n */ \n\n\n// @sect3{Include files}  \n\n// 像往常一样，第一个任务是包括这些著名的deal.II库文件和一些C++头文件的功能。\n\n#include <deal.II/base/discrete_time.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/quadrature_lib.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_out.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/lac/affine_constraints.h> \n#include <deal.II/lac/sparse_direct.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <iostream> \n#include <cmath> \n#include <map> \n\n// 这是唯一一个新的包含文件：它包括所有的Runge-Kutta方法。\n\n#include <deal.II/base/time_stepping.h> \n\n// 接下来的步骤与之前所有的教程程序一样。我们把所有的东西放到一个自己的命名空间中，然后把deal.II的类和函数导入其中。\n\nnamespace Step52 \n{ \n  using namespace dealii; \n// @sect3{The <code>Diffusion</code> class}  \n\n// 下一块是主类的声明。这个类中的大部分函数并不新鲜，在以前的教程中已经解释过了。唯一有趣的函数是  <code>evaluate_diffusion()</code>  和  <code>id_minus_tau_J_inverse()</code>. <code>evaluate_diffusion()</code>  评估扩散方程，  $M^{-1}(f(t,y))$  ，在一个给定的时间和一个给定的  $y$  。  <code>id_minus_tau_J_inverse()</code>  在给定的时间和给定的 $\\tau$ 和 $y$ 下，评估 $\\left(I-\\tau M^{-1} \\frac{\\partial f(t,y)}{\\partial y}\\right)^{-1}$ 或类似的 $\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} M$ 。当使用隐式方法时，就需要这个函数。\n\n  class Diffusion \n  { \n  public: \n    Diffusion(); \n\n    void run(); \n\n  private: \n    void setup_system(); \n\n    void assemble_system(); \n\n    double get_source(const double time, const Point<2> &point) const; \n\n    Vector<double> evaluate_diffusion(const double          time, \n                                      const Vector<double> &y) const; \n\n    Vector<double> id_minus_tau_J_inverse(const double          time, \n                                          const double          tau, \n                                          const Vector<double> &y); \n\n    void output_results(const double                     time, \n                        const unsigned int               time_step, \n                        TimeStepping::runge_kutta_method method) const; \n\n// 接下来的三个函数分别是显式方法、隐式方法和嵌入式显式方法的驱动。嵌入显式方法的驱动函数返回执行的步数，鉴于它只接受作为参数传递的时间步数作为提示，但内部计算了最佳时间步数本身。\n\n    void explicit_method(const TimeStepping::runge_kutta_method method, \n                         const unsigned int                     n_time_steps, \n                         const double                           initial_time, \n                         const double                           final_time); \n\n    void implicit_method(const TimeStepping::runge_kutta_method method, \n                         const unsigned int                     n_time_steps, \n                         const double                           initial_time, \n                         const double                           final_time); \n\n    unsigned int \n    embedded_explicit_method(const TimeStepping::runge_kutta_method method, \n                             const unsigned int n_time_steps, \n                             const double       initial_time, \n                             const double       final_time); \n\n    const unsigned int fe_degree; \n\n    const double diffusion_coefficient; \n    const double absorption_cross_section; \n\n    Triangulation<2> triangulation; \n\n    const FE_Q<2> fe; \n\n    DoFHandler<2> dof_handler; \n\n    AffineConstraints<double> constraint_matrix; \n\n    SparsityPattern sparsity_pattern; \n\n    SparseMatrix<double> system_matrix; \n    SparseMatrix<double> mass_matrix; \n    SparseMatrix<double> mass_minus_tau_Jacobian; \n\n    SparseDirectUMFPACK inverse_mass_matrix; \n\n    Vector<double> solution; \n  }; \n\n// 我们选择二次方有限元，并初始化参数。\n\n  Diffusion::Diffusion() \n    : fe_degree(2) \n    , diffusion_coefficient(1. / 30.) \n    , absorption_cross_section(1.) \n    , fe(fe_degree) \n    , dof_handler(triangulation) \n  {} \n\n// 现在，我们创建约束矩阵和稀疏模式。然后，我们初始化这些矩阵和求解向量。\n\n  void Diffusion::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n\n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             1, \n                                             Functions::ZeroFunction<2>(), \n                                             constraint_matrix); \n    constraint_matrix.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraint_matrix); \n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n    mass_matrix.reinit(sparsity_pattern); \n    mass_minus_tau_Jacobian.reinit(sparsity_pattern); \n    solution.reinit(dof_handler.n_dofs()); \n  } \n\n//  @sect4{<code>Diffusion::assemble_system</code>}  在这个函数中，我们计算  $-\\int D \\nabla b_i \\cdot \\nabla b_j d\\boldsymbol{r} - \\int \\Sigma_a b_i b_j d\\boldsymbol{r}$  和质量矩阵  $\\int b_i b_j d\\boldsymbol{r}$  。然后使用直接求解器对质量矩阵进行反演；然后 <code>inverse_mass_matrix</code> 变量将存储质量矩阵的反值，这样 $M^{-1}$ 就可以使用该对象的 <code>vmult()</code> 函数应用于一个矢量。在内部，UMFPACK并没有真正存储矩阵的逆，而是存储它的LU因子；应用矩阵的逆相当于用这两个因子做一次正解和一次逆解，这与应用矩阵的显式逆具有相同的复杂性）。\n\n  void Diffusion::assemble_system() \n  { \n    system_matrix = 0.; \n    mass_matrix   = 0.; \n\n    const 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); \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    FullMatrix<double> cell_mass_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      { \n        cell_matrix      = 0.; \n        cell_mass_matrix = 0.; \n\n        fe_values.reinit(cell); \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              { \n                cell_matrix(i, j) += \n                  ((-diffusion_coefficient *                // (-D \n                      fe_values.shape_grad(i, q_point) *    //  * grad phi_i \n                      fe_values.shape_grad(j, q_point)      //  * grad phi_j \n                    - absorption_cross_section *            //  -Sigma \n                        fe_values.shape_value(i, q_point) * //  * phi_i \n                        fe_values.shape_value(j, q_point))  //  * phi_j) \n                   * fe_values.JxW(q_point));               // * dx \n                cell_mass_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\n        cell->get_dof_indices(local_dof_indices); \n\n        constraint_matrix.distribute_local_to_global(cell_matrix, \n                                                     local_dof_indices, \n                                                     system_matrix); \n        constraint_matrix.distribute_local_to_global(cell_mass_matrix, \n                                                     local_dof_indices, \n                                                     mass_matrix); \n      } \n\n    inverse_mass_matrix.initialize(mass_matrix); \n  } \n\n//  @sect4{<code>Diffusion::get_source</code>}  \n\n// 在这个函数中，计算出特定时间和特定点的方程的源项。\n\n  double Diffusion::get_source(const double time, const Point<2> &point) const \n  { \n    const double intensity = 10.; \n    const double frequency = numbers::PI / 10.; \n    const double b         = 5.; \n    const double x         = point(0); \n\n    return intensity * \n           (frequency * std::cos(frequency * time) * (b * x - x * x) + \n            std::sin(frequency * time) * \n              (absorption_cross_section * (b * x - x * x) + \n               2. * diffusion_coefficient)); \n  } \n\n//  @sect4{<code>Diffusion::evaluate_diffusion</code>}  \n\n// 接下来，我们在给定的时间  $t$  和给定的矢量  $y$  评价扩散方程的弱形式。换句话说，正如介绍中所述，我们评估  $M^{-1}(-{\\cal D}y - {\\cal A}y + {\\cal S})$  。为此，我们必须将矩阵 $-{\\cal D} - {\\cal A}$ （之前计算并存储在变量 <code>system_matrix</code> 中）应用于 $y$ ，然后添加源项，我们像通常那样进行积分。(如果你想节省几行代码，或者想利用并行积分的优势，可以用 VectorTools::create_right_hand_side() 来进行积分。) 然后将结果乘以 $M^{-1}$  。\n\n  Vector<double> Diffusion::evaluate_diffusion(const double          time, \n                                               const Vector<double> &y) const \n  { \n    Vector<double> tmp(dof_handler.n_dofs()); \n    tmp = 0.; \n    system_matrix.vmult(tmp, y); \n\n    const QGauss<2> quadrature_formula(fe_degree + 1); \n\n    FEValues<2> fe_values(fe, \n                          quadrature_formula, \n                          update_values | 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_source(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_source = 0.; \n\n        fe_values.reinit(cell); \n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n          { \n            const double source = \n              get_source(time, fe_values.quadrature_point(q_point)); \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              cell_source(i) += fe_values.shape_value(i, q_point) * // phi_i(x) \n                                source *                            // * S(x) \n                                fe_values.JxW(q_point);             // * dx \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n\n        constraint_matrix.distribute_local_to_global(cell_source, \n                                                     local_dof_indices, \n                                                     tmp); \n      } \n\n    Vector<double> value(dof_handler.n_dofs()); \n    inverse_mass_matrix.vmult(value, tmp); \n\n    return value; \n  } \n// @sect4{<code>Diffusion::id_minus_tau_J_inverse</code>}  \n\n// 我们计算  $\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} M$  。这要分几个步骤进行。 \n\n// - 计算  $M-\\tau \\frac{\\partial f}{\\partial y}$  。  \n\n// - 反转矩阵，得到  $\\left(M-\\tau \\frac{\\partial f} {\\partial y}\\right)^{-1}$  。  \n\n// --计算 $tmp=My$ 。  \n\n// --计算 $z=\\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} tmp =  \\left(M-\\tau \\frac{\\partial f}{\\partial y}\\right)^{-1} My$ 。  \n\n// - 返回z。\n\n  Vector<double> Diffusion::id_minus_tau_J_inverse(const double /*time*/, \n                                                   const double          tau, \n                                                   const Vector<double> &y) \n  { \n    SparseDirectUMFPACK inverse_mass_minus_tau_Jacobian; \n\n    mass_minus_tau_Jacobian.copy_from(mass_matrix); \n    mass_minus_tau_Jacobian.add(-tau, system_matrix); \n\n    inverse_mass_minus_tau_Jacobian.initialize(mass_minus_tau_Jacobian); \n\n    Vector<double> tmp(dof_handler.n_dofs()); \n    mass_matrix.vmult(tmp, y); \n\n    Vector<double> result(y); \n    inverse_mass_minus_tau_Jacobian.vmult(result, tmp); \n\n    return result; \n  } \n\n//  @sect4{<code>Diffusion::output_results</code>}  \n\n// 下面的函数将解决方案以vtu文件的形式输出，并以时间步长和时间步长方法的名称为索引。当然，所有时间步长方法的（精确）结果应该是一样的，但这里的输出至少可以让我们对它们进行比较。\n\n  void Diffusion::output_results(const double                     time, \n                                 const unsigned int               time_step, \n                                 TimeStepping::runge_kutta_method method) const \n  { \n    std::string method_name; \n\n    switch (method) \n      { \n        case TimeStepping::FORWARD_EULER: \n          { \n            method_name = \"forward_euler\"; \n            break; \n          } \n        case TimeStepping::RK_THIRD_ORDER: \n          { \n            method_name = \"rk3\"; \n            break; \n          } \n        case TimeStepping::RK_CLASSIC_FOURTH_ORDER: \n          { \n            method_name = \"rk4\"; \n            break; \n          } \n        case TimeStepping::BACKWARD_EULER: \n          { \n            method_name = \"backward_euler\"; \n            break; \n          } \n        case TimeStepping::IMPLICIT_MIDPOINT: \n          { \n            method_name = \"implicit_midpoint\"; \n            break; \n          } \n        case TimeStepping::SDIRK_TWO_STAGES: \n          { \n            method_name = \"sdirk\"; \n            break; \n          } \n        case TimeStepping::HEUN_EULER: \n          { \n            method_name = \"heun_euler\"; \n            break; \n          } \n        case TimeStepping::BOGACKI_SHAMPINE: \n          { \n            method_name = \"bocacki_shampine\"; \n            break; \n          } \n        case TimeStepping::DOPRI: \n          { \n            method_name = \"dopri\"; \n            break; \n          } \n        case TimeStepping::FEHLBERG: \n          { \n            method_name = \"fehlberg\"; \n            break; \n          } \n        case TimeStepping::CASH_KARP: \n          { \n            method_name = \"cash_karp\"; \n            break; \n          } \n        default: \n          { \n            break; \n          } \n      } \n\n    DataOut<2> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n\n    data_out.build_patches(); \n\n    data_out.set_flags(DataOutBase::VtkFlags(time, time_step)); \n\n    const std::string filename = \"solution_\" + method_name + \"-\" + \n                                 Utilities::int_to_string(time_step, 3) + \n                                 \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n\n    static std::vector<std::pair<double, std::string>> times_and_names; \n\n    static std::string method_name_prev = \"\"; \n    static std::string pvd_filename; \n    if (method_name_prev != method_name) \n      { \n        times_and_names.clear(); \n        method_name_prev = method_name; \n        pvd_filename     = \"solution_\" + method_name + \".pvd\"; \n      } \n    times_and_names.emplace_back(time, filename); \n    std::ofstream pvd_output(pvd_filename); \n    DataOutBase::write_pvd_record(pvd_output, times_and_names); \n  } \n// @sect4{<code>Diffusion::explicit_method</code>}  \n\n// 这个函数是所有显式方法的驱动。在顶部，它初始化了时间步长和解决方案（通过将其设置为零，然后确保边界值和悬挂节点约束得到尊重；当然，对于我们在这里使用的网格，悬挂节点约束实际上不是一个问题）。然后调用 <code>evolve_one_time_step</code> ，执行一个时间步骤。时间是通过DiscreteTime对象来存储和增加的。\n\n// 对于显式方法， <code>evolve_one_time_step</code> 需要评估 $M^{-1}(f(t,y))$ ，也就是说，它需要 <code>evaluate_diffusion</code>  。因为 <code>evaluate_diffusion</code> 是一个成员函数，它需要被绑定到 <code>this</code> 。在每个进化步骤之后，我们再次应用正确的边界值和悬挂节点约束。\n\n// 最后，每隔10个时间步骤就会输出解决方案。\n\n  void Diffusion::explicit_method(const TimeStepping::runge_kutta_method method, \n                                  const unsigned int n_time_steps, \n                                  const double       initial_time, \n                                  const double       final_time) \n  { \n    const double time_step = \n      (final_time - initial_time) / static_cast<double>(n_time_steps); \n\n    solution = 0.; \n    constraint_matrix.distribute(solution); \n\n    TimeStepping::ExplicitRungeKutta<Vector<double>> explicit_runge_kutta( \n      method); \n    output_results(initial_time, 0, method); \n    DiscreteTime time(initial_time, final_time, time_step); \n    while (time.is_at_end() == false) \n      { \n        explicit_runge_kutta.evolve_one_time_step( \n          [this](const double time, const Vector<double> &y) { \n            return this->evaluate_diffusion(time, y); \n          }, \n          time.get_current_time(), \n          time.get_next_step_size(), \n          solution); \n        time.advance_time(); \n\n        constraint_matrix.distribute(solution); \n\n        if (time.get_step_number() % 10 == 0) \n          output_results(time.get_current_time(), \n                         time.get_step_number(), \n                         method); \n      } \n  } \n\n//  @sect4{<code>Diffusion::implicit_method</code>}  这个函数等同于 <code>explicit_method</code> ，但用于隐式方法。当使用隐式方法时，我们需要评估 $M^{-1}(f(t,y))$ 和 $\\left(I-\\tau M^{-1} \\frac{\\partial f(t,y)}{\\partial y}\\right)^{-1}$ ，为此我们使用之前介绍的两个成员函数。\n\n  void Diffusion::implicit_method(const TimeStepping::runge_kutta_method method, \n                                  const unsigned int n_time_steps, \n                                  const double       initial_time, \n                                  const double       final_time) \n  { \n    const double time_step = \n      (final_time - initial_time) / static_cast<double>(n_time_steps); \n\n    solution = 0.; \n    constraint_matrix.distribute(solution); \n\n    TimeStepping::ImplicitRungeKutta<Vector<double>> implicit_runge_kutta( \n      method); \n    output_results(initial_time, 0, method); \n    DiscreteTime time(initial_time, final_time, time_step); \n    while (time.is_at_end() == false) \n      { \n        implicit_runge_kutta.evolve_one_time_step( \n          [this](const double time, const Vector<double> &y) { \n            return this->evaluate_diffusion(time, y); \n          }, \n          [this](const double time, const double tau, const Vector<double> &y) { \n            return this->id_minus_tau_J_inverse(time, tau, y); \n          }, \n          time.get_current_time(), \n          time.get_next_step_size(), \n          solution); \n        time.advance_time(); \n\n        constraint_matrix.distribute(solution); \n\n        if (time.get_step_number() % 10 == 0) \n          output_results(time.get_current_time(), \n                         time.get_step_number(), \n                         method); \n      } \n  } \n\n//  @sect4{<code>Diffusion::embedded_explicit_method</code>}  这个函数是嵌入式显式方法的驱动。它需要更多的参数。 \n\n// - coarsen_param：当误差低于阈值时，乘以当前时间步长的系数。 \n\n// - refine_param: 当误差高于阈值时，乘以当前时间步长的系数。 \n\n// - min_delta: 可接受的最小时间步长。 \n\n// - max_delta: 可接受的最大时间步长。 \n\n// - refine_tol：时间步长超过的阈值。 \n\n// - coarsen_tol：阈值，低于该阈值的时间步长将被粗化。\n\n// 嵌入方法使用一个猜测的时间步长。如果使用这个时间步长的误差太大，时间步长将被缩小。如果误差低于阈值，则在下一个时间步长时将尝试更大的时间步长。  <code>delta_t_guess</code> 是由嵌入式方法产生的猜测的时间步长。总之，时间步长有可能以三种方式修改。 \n\n// - 在 TimeStepping::EmbeddedExplicitRungeKutta::evolve_one_time_step(). 内减少或增加时间步长。  \n\n// - 使用计算出的  <code>delta_t_guess</code>  。 \n\n// - 自动调整最后一个时间步长，以确保模拟在  <code>final_time</code>  处精确结束。这种调整是在DiscreteTime实例中处理的。\n\n  unsigned int Diffusion::embedded_explicit_method( \n    const TimeStepping::runge_kutta_method method, \n    const unsigned int                     n_time_steps, \n    const double                           initial_time, \n    const double                           final_time) \n  { \n    const double time_step = \n      (final_time - initial_time) / static_cast<double>(n_time_steps); \n    const double coarsen_param = 1.2; \n    const double refine_param  = 0.8; \n    const double min_delta     = 1e-8; \n    const double max_delta     = 10 * time_step; \n    const double refine_tol    = 1e-1; \n    const double coarsen_tol   = 1e-5; \n\n    solution = 0.; \n    constraint_matrix.distribute(solution); \n\n    TimeStepping::EmbeddedExplicitRungeKutta<Vector<double>> \n      embedded_explicit_runge_kutta(method, \n                                    coarsen_param, \n                                    refine_param, \n                                    min_delta, \n                                    max_delta, \n                                    refine_tol, \n                                    coarsen_tol); \n    output_results(initial_time, 0, method); \n    DiscreteTime time(initial_time, final_time, time_step); \n    while (time.is_at_end() == false) \n      { \n        const double new_time = \n          embedded_explicit_runge_kutta.evolve_one_time_step( \n            [this](const double time, const Vector<double> &y) { \n              return this->evaluate_diffusion(time, y); \n            }, \n            time.get_current_time(), \n            time.get_next_step_size(), \n            solution); \n        time.set_next_step_size(new_time - time.get_current_time()); \n        time.advance_time(); \n\n        constraint_matrix.distribute(solution); \n\n        if (time.get_step_number() % 10 == 0) \n          output_results(time.get_current_time(), \n                         time.get_step_number(), \n                         method); \n\n        time.set_desired_next_step_size( \n          embedded_explicit_runge_kutta.get_status().delta_t_guess); \n      } \n\n    return time.get_step_number(); \n  } \n\n//  @sect4{<code>Diffusion::run</code>}  \n\n// 下面是该程序的主要功能。在顶部，我们创建网格（一个[0,5]x[0,5]的正方形）并对其进行四次细化，得到一个有16乘16单元的网格，共256个。 然后我们将边界指示器设置为1，用于边界中 $x=0$ 和 $x=5$ 的部分。\n\n  void Diffusion::run() \n  { \n    GridGenerator::hyper_cube(triangulation, 0., 5.); \n    triangulation.refine_global(4); \n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->at_boundary()) \n          { \n            if ((face->center()[0] == 0.) || (face->center()[0] == 5.)) \n              face->set_boundary_id(1); \n            else \n              face->set_boundary_id(0); \n          } \n\n// 接下来，我们设置线性系统并为其填充内容，以便在整个时间步进过程中使用它们。\n\n    setup_system(); \n\n    assemble_system(); \n\n// 最后，我们使用命名空间TimeStepping中实现的几种Runge-Kutta方法来解决扩散问题，每次都会在结束时输出误差。(正如介绍中所解释的，由于精确解在最后时间为零，所以误差等于数值解，只需取解向量的 $l_2$ 准则即可计算出来。)\n\n    unsigned int       n_steps      = 0; \n    const unsigned int n_time_steps = 200; \n    const double       initial_time = 0.; \n    const double       final_time   = 10.; \n\n    std::cout << \"Explicit methods:\" << std::endl; \n    explicit_method(TimeStepping::FORWARD_EULER, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Forward Euler:            error=\" << solution.l2_norm() \n              << std::endl; \n\n    explicit_method(TimeStepping::RK_THIRD_ORDER, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Third order Runge-Kutta:  error=\" << solution.l2_norm() \n              << std::endl; \n\n    explicit_method(TimeStepping::RK_CLASSIC_FOURTH_ORDER, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Fourth order Runge-Kutta: error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << std::endl; \n\n    std::cout << \"Implicit methods:\" << std::endl; \n    implicit_method(TimeStepping::BACKWARD_EULER, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Backward Euler:           error=\" << solution.l2_norm() \n              << std::endl; \n\n    implicit_method(TimeStepping::IMPLICIT_MIDPOINT, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Implicit Midpoint:        error=\" << solution.l2_norm() \n              << std::endl; \n\n    implicit_method(TimeStepping::CRANK_NICOLSON, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   Crank-Nicolson:           error=\" << solution.l2_norm() \n              << std::endl; \n\n    implicit_method(TimeStepping::SDIRK_TWO_STAGES, \n                    n_time_steps, \n                    initial_time, \n                    final_time); \n    std::cout << \"   SDIRK:                    error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << std::endl; \n\n    std::cout << \"Embedded explicit methods:\" << std::endl; \n    n_steps = embedded_explicit_method(TimeStepping::HEUN_EULER, \n                                       n_time_steps, \n                                       initial_time, \n                                       final_time); \n    std::cout << \"   Heun-Euler:               error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << \"                   steps performed=\" << n_steps << std::endl; \n\n    n_steps = embedded_explicit_method(TimeStepping::BOGACKI_SHAMPINE, \n                                       n_time_steps, \n                                       initial_time, \n                                       final_time); \n    std::cout << \"   Bogacki-Shampine:         error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << \"                   steps performed=\" << n_steps << std::endl; \n\n    n_steps = embedded_explicit_method(TimeStepping::DOPRI, \n                                       n_time_steps, \n                                       initial_time, \n                                       final_time); \n    std::cout << \"   Dopri:                    error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << \"                   steps performed=\" << n_steps << std::endl; \n\n    n_steps = embedded_explicit_method(TimeStepping::FEHLBERG, \n                                       n_time_steps, \n                                       initial_time, \n                                       final_time); \n    std::cout << \"   Fehlberg:                 error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << \"                   steps performed=\" << n_steps << std::endl; \n\n    n_steps = embedded_explicit_method(TimeStepping::CASH_KARP, \n                                       n_time_steps, \n                                       initial_time, \n                                       final_time); \n    std::cout << \"   Cash-Karp:                error=\" << solution.l2_norm() \n              << std::endl; \n    std::cout << \"                   steps performed=\" << n_steps << std::endl; \n  } \n} // namespace Step52 \n\n//  @sect3{The <code>main()</code> function}  \n\n// 下面的 <code>main</code> 函数与前面的例子类似，不需要注释。\n\nint main() \n{ \n  try \n    { \n      Step52::Diffusion diffusion; \n      diffusion.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": "30bc495329fcbf9898f32a5bb7b0acd133d3f1b1", "size": 27406, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-52/step-52.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-52/step-52.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-52/step-52.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.2034346103, "max_line_length": 435, "alphanum_fraction": 0.5437860323, "num_tokens": 7754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5776643943455061}}
{"text": "#include <iostream>\n#include \"BenchTimer.h\"\n#include <Eigen/Dense>\n#include <map>\n#include <vector>\n#include <string>\n#include <sstream>\nusing namespace Eigen;\n\nstd::map<std::string,Array<float,1,8,DontAlign|RowMajor> > results;\nstd::vector<std::string> labels;\nstd::vector<Array2i> sizes;\n\ntemplate<typename Solver,typename MatrixType>\nEIGEN_DONT_INLINE\nvoid compute_norm_equation(Solver &solver, const MatrixType &A) {\n  if(A.rows()!=A.cols())\n    solver.compute(A.transpose()*A);\n  else\n    solver.compute(A);\n}\n\ntemplate<typename Solver,typename MatrixType>\nEIGEN_DONT_INLINE\nvoid compute(Solver &solver, const MatrixType &A) {\n  solver.compute(A);\n}\n\ntemplate<typename Scalar,int Size>\nvoid bench(int id, int rows, int size = Size)\n{\n  typedef Matrix<Scalar,Dynamic,Size> Mat;\n  typedef Matrix<Scalar,Dynamic,Dynamic> MatDyn;\n  typedef Matrix<Scalar,Size,Size> MatSquare;\n  Mat A(rows,size);\n  A.setRandom();\n  if(rows==size)\n    A = A*A.adjoint();\n  BenchTimer t_llt, t_ldlt, t_lu, t_fplu, t_qr, t_cpqr, t_cod, t_fpqr, t_jsvd, t_bdcsvd;\n\n  int svd_opt = ComputeThinU|ComputeThinV;\n  \n  int tries = 5;\n  int rep = 1000/size;\n  if(rep==0) rep = 1;\n//   rep = rep*rep;\n  \n  LLT<MatSquare> llt(size);\n  LDLT<MatSquare> ldlt(size);\n  PartialPivLU<MatSquare> lu(size);\n  FullPivLU<MatSquare> fplu(size,size);\n  HouseholderQR<Mat> qr(A.rows(),A.cols());\n  ColPivHouseholderQR<Mat> cpqr(A.rows(),A.cols());\n  CompleteOrthogonalDecomposition<Mat> cod(A.rows(),A.cols());\n  FullPivHouseholderQR<Mat> fpqr(A.rows(),A.cols());\n  JacobiSVD<MatDyn> jsvd(A.rows(),A.cols());\n  BDCSVD<MatDyn> bdcsvd(A.rows(),A.cols());\n  \n  BENCH(t_llt, tries, rep, compute_norm_equation(llt,A));\n  BENCH(t_ldlt, tries, rep, compute_norm_equation(ldlt,A));\n  BENCH(t_lu, tries, rep, compute_norm_equation(lu,A));\n  if(size<=1000)\n    BENCH(t_fplu, tries, rep, compute_norm_equation(fplu,A));\n  BENCH(t_qr, tries, rep, compute(qr,A));\n  BENCH(t_cpqr, tries, rep, compute(cpqr,A));\n  BENCH(t_cod, tries, rep, compute(cod,A));\n  if(size*rows<=10000000)\n    BENCH(t_fpqr, tries, rep, compute(fpqr,A));\n  if(size<500) // JacobiSVD is really too slow for too large matrices\n    BENCH(t_jsvd, tries, rep, jsvd.compute(A,svd_opt));\n//   if(size*rows<=20000000)\n    BENCH(t_bdcsvd, tries, rep, bdcsvd.compute(A,svd_opt));\n  \n  results[\"LLT\"][id] = t_llt.best();\n  results[\"LDLT\"][id] = t_ldlt.best();\n  results[\"PartialPivLU\"][id] = t_lu.best();\n  results[\"FullPivLU\"][id] = t_fplu.best();\n  results[\"HouseholderQR\"][id] = t_qr.best();\n  results[\"ColPivHouseholderQR\"][id] = t_cpqr.best();\n  results[\"CompleteOrthogonalDecomposition\"][id] = t_cod.best();\n  results[\"FullPivHouseholderQR\"][id] = t_fpqr.best();\n  results[\"JacobiSVD\"][id] = t_jsvd.best();\n  results[\"BDCSVD\"][id] = t_bdcsvd.best();\n}\n\n\nint main()\n{\n  labels.push_back(\"LLT\");\n  labels.push_back(\"LDLT\");\n  labels.push_back(\"PartialPivLU\");\n  labels.push_back(\"FullPivLU\");\n  labels.push_back(\"HouseholderQR\");\n  labels.push_back(\"ColPivHouseholderQR\");\n  labels.push_back(\"CompleteOrthogonalDecomposition\");\n  labels.push_back(\"FullPivHouseholderQR\");\n  labels.push_back(\"JacobiSVD\");\n  labels.push_back(\"BDCSVD\");\n\n  for(int i=0; i<labels.size(); ++i)\n    results[labels[i]].fill(-1);\n\n  const int small = 8;\n  sizes.push_back(Array2i(small,small));\n  sizes.push_back(Array2i(100,100));\n  sizes.push_back(Array2i(1000,1000));\n  sizes.push_back(Array2i(4000,4000));\n  sizes.push_back(Array2i(10000,small));\n  sizes.push_back(Array2i(10000,100));\n  sizes.push_back(Array2i(10000,1000));\n  sizes.push_back(Array2i(10000,4000));\n\n  using namespace std;\n\n  for(int k=0; k<sizes.size(); ++k)\n  {\n    cout << sizes[k](0) << \"x\" << sizes[k](1) << \"...\\n\";\n    bench<float,Dynamic>(k,sizes[k](0),sizes[k](1));\n  }\n\n  cout.width(32);\n  cout << \"solver/size\";\n  cout << \"  \";\n  for(int k=0; k<sizes.size(); ++k)\n  {\n    std::stringstream ss;\n    ss << sizes[k](0) << \"x\" << sizes[k](1);\n    cout.width(10); cout << ss.str(); cout << \" \";\n  }\n  cout << endl;\n\n\n  for(int i=0; i<labels.size(); ++i)\n  {\n    cout.width(32); cout << labels[i]; cout << \"  \";\n    ArrayXf r = (results[labels[i]]*100000.f).floor()/100.f;\n    for(int k=0; k<sizes.size(); ++k)\n    {\n      cout.width(10);\n      if(r(k)>=1e6)  cout << \"-\";\n      else           cout << r(k);\n      cout << \" \";\n    }\n    cout << endl;\n  }\n\n  // HTML output\n  cout << \"<table class=\\\"manual\\\">\" << endl;\n  cout << \"<tr><th>solver/size</th>\" << endl;\n  for(int k=0; k<sizes.size(); ++k)\n    cout << \"  <th>\" << sizes[k](0) << \"x\" << sizes[k](1) << \"</th>\";\n  cout << \"</tr>\" << endl;\n  for(int i=0; i<labels.size(); ++i)\n  {\n    cout << \"<tr\";\n    if(i%2==1) cout << \" class=\\\"alt\\\"\";\n    cout << \"><td>\" << labels[i] << \"</td>\";\n    ArrayXf r = (results[labels[i]]*100000.f).floor()/100.f;\n    for(int k=0; k<sizes.size(); ++k)\n    {\n      if(r(k)>=1e6) cout << \"<td>-</td>\";\n      else\n      {\n        cout << \"<td>\" << r(k);\n        if(i>0)\n          cout << \" (x\" << numext::round(10.f*results[labels[i]](k)/results[\"LLT\"](k))/10.f << \")\";\n        if(i<4 && sizes[k](0)!=sizes[k](1))\n          cout << \" <sup><a href=\\\"#note_ls\\\">*</a></sup>\";\n        cout << \"</td>\";\n      }\n    }\n    cout << \"</tr>\" << endl;\n  }\n  cout << \"</table>\" << endl;\n\n//   cout << \"LLT                             (ms)  \" << (results[\"LLT\"]*1000.).format(fmt) << \"\\n\";\n//   cout << \"LDLT                             (%)  \" << (results[\"LDLT\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"PartialPivLU                     (%)  \" << (results[\"PartialPivLU\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"FullPivLU                        (%)  \" << (results[\"FullPivLU\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"HouseholderQR                    (%)  \" << (results[\"HouseholderQR\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"ColPivHouseholderQR              (%)  \" << (results[\"ColPivHouseholderQR\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"CompleteOrthogonalDecomposition  (%)  \" << (results[\"CompleteOrthogonalDecomposition\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"FullPivHouseholderQR             (%)  \" << (results[\"FullPivHouseholderQR\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"JacobiSVD                        (%)  \" << (results[\"JacobiSVD\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n//   cout << \"BDCSVD                           (%)  \" << (results[\"BDCSVD\"]/results[\"LLT\"]).format(fmt) << \"\\n\";\n}\n", "meta": {"hexsha": "24343dcd88e4d101862e4b07021d2d647b1ac398", "size": 6416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/bench/dense_solvers.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/bench/dense_solvers.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/bench/dense_solvers.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 34.3101604278, "max_line_length": 137, "alphanum_fraction": 0.5889962594, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.5776643855024003}}
{"text": "#include \"KDE.hpp\"\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/range/irange.hpp>\n#include <boost/range/numeric.hpp>\n#include <random>\n#include <math.h>\n\nusing namespace std;\nusing namespace delphi::utils;\nusing boost::irange, boost::adaptors::transformed, boost::lambda::_1;\n\ndouble sample_from_normal(\n    std::mt19937 gen,\n    double mu = 0.0, /**< The mean of the distribution.*/\n    double sd = 1.0  /**< The standard deviation of the distribution.*/\n) {\n  normal_distribution<> d{mu, sd};\n  return d(gen);\n}\n\nKDE::KDE(std::vector<double> v) : dataset(v) {\n\n  // Compute the bandwidth using Silverman's rule\n  mu = mean(v);\n  auto X = v | transformed(_1 - mu);\n\n  // Compute standard deviation of the sample.\n  size_t N = v.size();\n  double stdev = sqrt(inner_product(X, X, 0.0) / (N - 1));\n  bw = pow(4 * pow(stdev, 5) / (3 * N), 1 / 5);\n}\n\nKDE::KDE(vector<double> thetas, int n_bins)  : n_bins(n_bins) {\n  this->dataset = thetas;\n  this->mu = mean(thetas);\n  double small_count = 0.00001; // To avoid log(0)\n  this->log_prior_hist = vector<double>(n_bins, small_count);\n  this->delta_theta = M_PI / n_bins;\n\n  int highest_freq = 0;\n  int highest_freq_bin = 0;\n\n//  int bin_lo = n_bins - 1;\n//  int bin_hi = 0;\n\n  for (double theta : thetas) {\n    theta = theta < 0 ? M_PI + theta : theta;\n\n    int bin = this->theta_to_bin(theta);\n//    bin_lo = bin < bin_lo ? bin : bin_lo;\n//    bin_hi = bin > bin_hi ? bin : bin_hi;\n\n    this->log_prior_hist[bin] += 1;\n\n    if (highest_freq < this->log_prior_hist[bin]) {\n      highest_freq = this->log_prior_hist[bin];\n      highest_freq_bin = bin;\n    }\n  }\n\n//  if (bin_lo != bin_hi && bin_lo != (bin_hi + 1) % n_bins)\n\n  this->most_probable_theta = highest_freq_bin * this->delta_theta +\n                              this->delta_theta / 2;\n  double n_points = thetas.size() + small_count * n_bins;\n\n  for (double & count : this->log_prior_hist) {\n    count /= n_points;\n    count = log(count);\n  }\n}\n\nvoid KDE::set_num_bins(int n_bins) {\n  this->n_bins = n_bins;\n  this->delta_theta = M_PI / n_bins;\n}\n\nint KDE::theta_to_bin(double theta) {\n    return floor(theta / this->delta_theta);\n}\n\n\nvector<double> KDE::resample(int n_samples,\n                             std::mt19937& gen,\n                             uniform_real_distribution<double>& uni_dist,\n                             normal_distribution<double>& norm_dist) {\n  vector<double> samples(n_samples);\n\n  for (int i : irange(0, n_samples)) {\n    double element = select_random_element(dataset, gen, uni_dist);\n\n    // Transform the sampled values using a Gaussian distribution\n    // ~ ( sampled value, bw)\n    // We sample from a standard Gaussian and transform that sample\n    // to the desired Gaussian distribution by\n    // μ + σ * standard Gaussian sample\n    samples[i] = element + bw * norm_dist(gen);\n  }\n\n  return samples;\n}\n\n// This Should not be called!\ndouble KDE::pdf(double x) {\n  double p = 0.0;\n  size_t N = this->dataset.size();\n  for (double elem : this->dataset) {\n    double x1 = exp(-sqr(x - elem) / (2 * sqr(bw)));\n    x1 /= N * bw * sqrt(2 * M_PI);\n    p += x1;\n  }\n  return p;\n}\n\nvector<double> KDE::pdf(vector<double> v) {\n  vector<double> values;\n  for (double elem : v) {\n    values.push_back(pdf(elem));\n  }\n  return values;\n}\n\ndouble KDE::logpdf(double x) { return log(pdf(x)); }\n", "meta": {"hexsha": "b4b2ca6e9f728dbc500ea55bc01bc9228caf252c", "size": 3442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/KDE.cpp", "max_stars_repo_name": "ml4ai/delphi", "max_stars_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2018-03-03T11:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T21:19:54.000Z", "max_issues_repo_path": "lib/KDE.cpp", "max_issues_repo_name": "ml4ai/delphi", "max_issues_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 385.0, "max_issues_repo_issues_event_min_datetime": "2018-02-21T16:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T07:44:56.000Z", "max_forks_repo_path": "lib/KDE.cpp", "max_forks_repo_name": "ml4ai/delphi", "max_forks_repo_head_hexsha": "9294d2d491f10c297c84f1cd5fdc9b55b6f866d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-03-20T01:08:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T01:04:49.000Z", "avg_line_length": 27.1023622047, "max_line_length": 73, "alphanum_fraction": 0.6313190006, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5776125606921453}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\nEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> loge(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> in)\n{\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> out = in;\n\n  out = out.array() + 1e-7f;\n\n  for(int i=0; i<in.cols(); i++)\n    {\n      out(0, i) = logf(out(0,i));\n    }\n\n  return out;\n}\n\n\nstruct NNLayer {\n  struct NNLayer *next;\n  struct NNLayer *back;\n\n  NNLayer() : next(NULL), back(NULL)\n    {\n    };\n\n  ~NNLayer() {};\n\n  virtual Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m) = 0;\n\n  virtual void back_propagation() = 0;\n\n  void setNext(struct NNLayer *n)\n    {\n      next = n;\n      n->back = this;\n    };\n\n  struct NNLayer * getNext()\n    {\n      return next;\n    };\n\n};\n\n\nclass Activation : public NNLayer {\n  public:\n    virtual Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m)\n      {\n      };\n};\n\n\nstruct AffineLayer : public NNLayer {\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> w;\n  Eigen::Matrix<float, 1, Eigen::Dynamic> bias;\n  Eigen::Matrix<float, 1, Eigen::Dynamic> output;\n  bool needActivation;\n\n  AffineLayer() : NNLayer(), needActivation(true)\n    {\n    }\n\n  AffineLayer(int raws, int cols) : NNLayer(), needActivation(true)\n    {\n      resize(raws, cols);\n    }\n\n  ~AffineLayer() {};\n\n  void resize(int raws, int cols)\n    {\n      w.resize(raws, cols);\n      bias.resize(1, cols);\n      output.resize(1, cols);\n\n      w      = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Random(raws, cols);\n      bias   = Eigen::Matrix<float, 1, Eigen::Dynamic>::Random(1, cols);\n      output = Eigen::Matrix<float, 1, Eigen::Dynamic>::Random(1, cols);\n    }\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m)\n    {\n      output = (m * w) - bias;\n      if (needActivation) activate();\n\n      if (next != NULL)\n        {\n          return next->forward(output);\n        }\n      else\n        {\n          return output;\n        }\n    }\n\n  void back_propagation()\n    {\n    };\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> activate()\n    {\n      for(int i=0; i<output.cols(); i++)\n        {\n          output(0, i) = 1.0/(1.0 + exp(output(0, i)));\n        }\n      return output;\n    }\n\n  void setActivation(bool isneed)\n    {\n      needActivation = isneed;\n    }\n};\n\n\nclass NeuralNetwork {\n  NNLayer *top_layer;\n  NNLayer *last_layer;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> output;\n\n  public:\n    NeuralNetwork()\n      {\n        AffineLayer * tmplayers = new AffineLayer[3];\n        tmplayers[0].resize(2,3);\n        tmplayers[1].resize(3,5);\n        tmplayers[2].resize(5,2);\n        // tmplayers[2].setActivation(false);\n\n        tmplayers[0].setNext(&tmplayers[1]);\n        tmplayers[1].setNext(&tmplayers[2]);\n\n        top_layer  = &tmplayers[0];\n        last_layer = &tmplayers[2];\n      };\n    ~NeuralNetwork()\n      {\n        delete [] top_layer;\n      };\n\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> forward(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> input)\n      {\n        output = top_layer->forward(input);\n        return output;\n      };\n\n    void back_propagation()\n      {\n      };\n\n    float cross_entropy(Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> in)\n      {\n        Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> tmp;\n        float out = 0.f;\n        tmp = in.array() * loge(output).array();\n        for(int i=0; i<tmp.cols(); i++)\n          {\n            out -= tmp(0, i);\n          }\n        return out;\n      };\n};\n\n\nint main(void)\n{\n  NeuralNetwork nn;\n\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> out;\n  Eigen::Matrix<float, 1, 2> input;\n  Eigen::Matrix<float, 1, 2> expect;\n  input << 3, 3;\n\n  expect << 2, 5;\n\n  std::cout << \"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\n  std::cout << \"out = \" << out << std::endl;\n\n  std::cout << \"CrossEnt = \" << nn.cross_entropy(expect) << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "8005f0b3d5349613d00902950350fff00d9d7bb9", "size": 4421, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/old/nn2.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/old/nn2.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/old/nn2.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": 22.3282828283, "max_line_length": 131, "alphanum_fraction": 0.5706853653, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5775887175351555}}
{"text": "/* $Id: step-3.cc 24232 2011-09-02 09:47:37Z kronbichler $ */\n/* Author: Wolfgang Bangerth, 1999, Guido Kanschat, 2011 */\n\n/*    $Id: step-3.cc 24232 2011-09-02 09:47:37Z kronbichler $       */\n/*                                                                */\n/*    Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2008, 2010, 2011 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/* Modified for Exercise 2.5 of the finite element lecture \n   in Hamburg in Summer 2014 by W. Wollner\n*/\n\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#include <deal.II/numerics/data_out.h>\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\n\nclass Solution : public Function<2>\n{\npublic:\n  Solution () : Function<2>() {}\n  \n  double value (const Point<2>   &p,\n\t\tconst unsigned int  component = 0) const;\n  \n  Tensor<1,2> gradient (const Point<2>   &p,\n\t\t\tconst unsigned int  component = 0) const;\n};\n\ndouble Solution::value(const Point<2>   &p, const unsigned int) const\n{\n  return sin(M_PI * p(0))*sin(2.*M_PI * p(1));\n}\n\nTensor<1,2> Solution::gradient (const Point<2>   &p,\n\t\t\t\tconst unsigned int) const\n{\n  //EXERCISE: This is used to evaluate the gradient of the \n  //known reference solution and needs to be implemented. \n  //If you don't know how to do this have a look into the \n  //deal.II steps 1-3 and the function evaluation \n  //the value of this function above.\n  Tensor<1,2> return_value;\n  return_value[0] = M_PI * cos(M_PI * p(0)) * sin(2.*M_PI * p(1));\n  return_value[1] = 2 * M_PI * sin(M_PI * p(0)) * cos(2.*M_PI * p(1));\n  return return_value;\n}\n\nclass Problem\n{\n  public:\n    Problem (unsigned int deg);\n    void run ();\n    void summarize_results () const;\n\n  private:\n    void refine_grid(); \n    void setup_system ();\n    void assemble_system ();\n    void solve ();\n    void output_results ();\n    virtual void make_grid (unsigned int ref);\n\n    Triangulation<2>     triangulation;\n   \n    FE_Q<2>              fe;\n    DoFHandler<2>        dof_handler;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n    std::vector<double> dofs;\n    std::vector<double> l2_value;\n    std::vector<double> h1_value;\n    unsigned int n_iter;\n    unsigned int iter;\n};\n\nProblem::Problem (unsigned int deg)\n\t\t:\n                fe (deg),\n\t\tdof_handler (triangulation)\n{\n  n_iter = 5;\n  dofs.resize(n_iter);\n  l2_value.resize(n_iter);\n  h1_value.resize(n_iter);\n  iter = 0;\n}\n\nvoid Problem::make_grid (unsigned int ref)\n{\n  GridGenerator::hyper_cube (triangulation);\n  triangulation.refine_global (ref);\n  std::cout << \"Number of active cells: \"\n\t    << triangulation.n_active_cells()\n\t    << std::endl;\n  std::cout << \"Total number of cells: \"\n\t    << triangulation.n_cells()\n\t    << std::endl;\n}\nvoid Problem::refine_grid ()\n{\n  triangulation.refine_global (1);\n  std::cout << std::endl;\n  std::cout << \"Refining the triangulation ...\"<<std::endl;\n  std::cout << \"Number of active cells: \"\n\t    << triangulation.n_active_cells()\n\t    << std::endl;\n  std::cout << \"Total number of cells: \"\n\t    << triangulation.n_cells()\n\t    << std::endl;\n}\nvoid Problem::setup_system ()\n{\n  dof_handler.distribute_dofs (fe);\n  std::cout << \"Number of degrees of freedom: \"\n\t    << dof_handler.n_dofs()\n\t    << std::endl;\n  dofs[iter] = dof_handler.n_dofs();\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  solution.reinit (dof_handler.n_dofs());\n  system_rhs.reinit (dof_handler.n_dofs());\n}\n\nvoid Problem::assemble_system ()\n{\n  QGauss<2>  quadrature_formula(2);\n  FEValues<2> fe_values (fe, quadrature_formula,\n\t\t\t update_quadrature_points | update_values | update_gradients | update_JxW_values);\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  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      cell_matrix = 0;\n      cell_rhs = 0;\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n\tfor (unsigned int j=0; j<dofs_per_cell; ++j)\n\t  for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n\t    cell_matrix(i,j) += (fe_values.shape_grad (i, q_point) *\n\t\t\t\t fe_values.shape_grad (j, q_point) *\n\t\t\t\t fe_values.JxW (q_point));\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n\tfor (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n\t{\n\n \t  //EXERCISE\n \t  /* This should implement the required right hand side\n \t   *  so you need to implement the integrand of \n \t   *  \\int_\\Omega f \\phi \\, dx \n \t   *  Since you use a quadrature formula, you only need to write \n \t   *  The value in the quadrature point (q_point)\n \t   *  which you can access using \n \t   *  fe_values.quadrature_point(q_point)\n \t   *  Currently the righthand side f = 1 is implemented.\n \t   *  The value of the test function is accessible using \n \t   *  fe_values.shape_value (i, q_point)\n \t   *\n \t   *  Note: do not remove the term fe_values.JxW (q_point)\n \t   *  it contains the quadrature weights!\n \t   */\n\t  Point<2> c_point = fe_values.quadrature_point(q_point);\n\t  cell_rhs(i) += (fe_values.shape_value (i, q_point) *\n\t\t\t  5 * M_PI * M_PI * sin(M_PI * c_point(0)) * sin(2 * M_PI * c_point(1)) *\n\t\t\t  fe_values.JxW (q_point));\n\t}\n      cell->get_dof_indices (local_dof_indices);\n\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n\tfor (unsigned int j=0; j<dofs_per_cell; ++j)\n\t  system_matrix.add (local_dof_indices[i],\n\t\t\t     local_dof_indices[j],\n\t\t\t     cell_matrix(i,j));\n\n      for (unsigned int i=0; i<dofs_per_cell; ++i)\n\tsystem_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n\n  std::map<unsigned int,double> boundary_values;\n  VectorTools::interpolate_boundary_values (dof_handler,\n\t\t\t\t\t    0,\n\t\t\t\t\t    ZeroFunction<2>(),\n\t\t\t\t\t    boundary_values);\n  MatrixTools::apply_boundary_values (boundary_values,\n\t\t\t\t      system_matrix,\n\t\t\t\t      solution,\n\t\t\t\t      system_rhs);\n}\n\nvoid Problem::solve ()\n{\n  SolverControl           solver_control (10000, 1e-12);\n  SolverCG<>              solver (solver_control);\n\n  solver.solve (system_matrix, solution, system_rhs,\n\t\tPreconditionIdentity());\n}\n\nvoid Problem::output_results () \n{\n  DataOut<2> data_out;\n  data_out.attach_dof_handler (dof_handler);\n  data_out.add_data_vector (solution, \"solution\");\n  data_out.build_patches ();\n  std::ofstream output (\"solution.gpl\");\n  data_out.write_gnuplot (output);  \n\n  Vector<float> difference_per_cell (triangulation.n_active_cells());\n\n  VectorTools::integrate_difference (dof_handler,\n\t\t\t\t     solution,\n\t\t\t\t     Solution(),\n\t\t\t\t     difference_per_cell,\n\t\t\t\t     QGauss<2>(3),\n\t\t\t\t     VectorTools::L2_norm);\n  l2_value[iter] = difference_per_cell.l2_norm();\n\n\n  std::cout << \"L2 Error \"\n\t    << l2_value[iter]\n  << std::endl;\n  //EXERCISE: Here you should take care to evaluate the \n  // H1 seminorm.\n  VectorTools::integrate_difference (dof_handler,\n\t\t\t\t     solution,\n\t\t\t\t     Solution(),\n\t\t\t\t     difference_per_cell,\n\t\t\t\t     QGauss<2>(3),\n\t\t\t\t     VectorTools::H1_seminorm);\n  h1_value[iter] = difference_per_cell.l2_norm();\n  std::cout << \"H1 Error: \"\n\t    << h1_value[iter]\n\t    << std::endl;\n\n}\n\nvoid Problem::summarize_results () const\n{\n  std::cout<<\"DOFS\\tL2 Norm\\t\\tEOC\\tH1 Norm\\t\\tEOC\"<<std::endl;\n  std::cout<<\"--------------------------------------------------\"<<std::endl;\n  for(unsigned int i = 0; i < n_iter; i++)\n  {\n    double order_p = 0.;\n    double order_m = 0.;\n    if(i > 1)\n    {\n      //EXERCISE: \n      /* The following lines need to calculate the estimated order of \n       * convergence for the L^2- and H^1 Norm.\n       * To do so we have stored the values of the L^2 error on the different \n       * triangulations h_1, h_2, h_3 in the array named \" l2_value \"\n       * and those for the H1 seminorm in h1_value.\n       */\n      order_p = log(l2_value[i-1] / l2_value[i]) / log(2);\n      order_m = log(h1_value[i-1] / h1_value[i]) / log(2);\n      std::cout<<dofs[i]<<\"\\t\"<<l2_value[i]<<\"\\t\"<<order_p<<\"\\t\"<<h1_value[i]<<\"\\t\"<<order_m<<std::endl;\n    }\n    else\n    {\n      std::cout<<dofs[i]<<\"\\t\"<<l2_value[i]<<\"\\t---\\t\"<<h1_value[i]<<\"\\t---\"<<std::endl;\n    }\n    \n\n  }\n}\n\nvoid Problem::run ()\n{\n  make_grid (3);\n  for(;iter < n_iter; iter++)\n  {\n    setup_system();\n    assemble_system ();\n    solve ();\n    output_results (); \n    refine_grid();\n  }\n}\n\nint main ()\n{\n  Problem problem(1);\n  problem.run ();\n  Problem problem_2(2);\n  problem_2.run ();\n\n  std::cout<<\"With Bilinear elements:\"<<std::endl;\n  problem.summarize_results();\n\n  std::cout<<std::endl;\n  std::cout<<\"With Biquadratic elements::\"<<std::endl;\n  problem_2.summarize_results();\n\n  return 0;\n}\n", "meta": {"hexsha": "4193906f5ba272fa71cf2870b8ec8ad448a7fe69", "size": 10046, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MathMods/FiniteElement/Ex-2-5/exercise-2-5.cc", "max_stars_repo_name": "homdx/edu", "max_stars_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathMods/FiniteElement/Ex-2-5/exercise-2-5.cc", "max_issues_repo_name": "homdx/edu", "max_issues_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathMods/FiniteElement/Ex-2-5/exercise-2-5.cc", "max_forks_repo_name": "homdx/edu", "max_forks_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-15T21:30:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T21:30:43.000Z", "avg_line_length": 29.7218934911, "max_line_length": 110, "alphanum_fraction": 0.6405534541, "num_tokens": 2865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5775056152826474}}
{"text": "#include \"utils.h\"\n\n#include <NTL/GF2EX.h>\n#include <NTL/GF2X.h>\n#include <stdexcept>\n\nusing namespace NTL;\n\nnamespace utils {\n\nstatic GF2X modulus;\n\nvoid init_ntl_extension_field(NTL_INSTANCE instance) {\n  switch (instance) {\n  case GF2_128: {\n    // modulus = x^128 + x^7 + x^2 + x^1 + 1\n    clear(modulus);\n    SetCoeff(modulus, 128);\n    SetCoeff(modulus, 7);\n    SetCoeff(modulus, 2);\n    SetCoeff(modulus, 1);\n    SetCoeff(modulus, 0);\n    GF2E::init(modulus);\n  } break;\n  case GF2_192: {\n    // modulus = x^192 + x^7 + x^2 + x^1 + 1\n    clear(modulus);\n    SetCoeff(modulus, 192);\n    SetCoeff(modulus, 7);\n    SetCoeff(modulus, 2);\n    SetCoeff(modulus, 1);\n    SetCoeff(modulus, 0);\n    GF2E::init(modulus);\n  } break;\n  case GF2_256: {\n    // modulus = x^256 + x^10 + x^5 + x^2 + 1\n    clear(modulus);\n    SetCoeff(modulus, 256);\n    SetCoeff(modulus, 10);\n    SetCoeff(modulus, 5);\n    SetCoeff(modulus, 2);\n    SetCoeff(modulus, 0);\n    GF2E::init(modulus);\n  } break;\n  default:\n    throw std::runtime_error(\"instance not implemented.\");\n  }\n}\n\nGF2E GF2E_from_bytes(const std::vector<uint8_t> &value) {\n  // assumes value is already smaller than current modulus\n  GF2X inner = GF2XFromBytes(value.data(), value.size());\n  return conv<GF2E>(inner);\n}\n\nvec_GF2E get_first_n_field_elements(size_t n) {\n  vec_GF2E result;\n  result.SetLength(n);\n  GF2X gen;\n  SetX(gen);\n  for (size_t i = 0; i < n; i++) {\n    result[i] = conv<GF2E>(gen);\n    gen = MulByX(gen);\n  }\n  return result;\n}\nstd::vector<GF2EX> precompute_lagrange_polynomials(const vec_GF2E &x_values) {\n  size_t m = x_values.length();\n  std::vector<GF2EX> precomputed_lagrange_polynomials;\n  precomputed_lagrange_polynomials.reserve(m);\n\n  GF2EX full_poly = BuildFromRoots(x_values);\n  GF2EX lagrange_poly;\n  GF2EX missing_term;\n  SetX(missing_term);\n  for (size_t k = 0; k < m; k++) {\n    SetCoeff(missing_term, 0, -x_values[k]);\n    lagrange_poly = full_poly / missing_term;\n    lagrange_poly = lagrange_poly / eval(lagrange_poly, x_values[k]);\n    precomputed_lagrange_polynomials.push_back(lagrange_poly);\n  }\n\n  return precomputed_lagrange_polynomials;\n}\n\nGF2EX interpolate_with_precomputation(\n    const std::vector<GF2EX> &precomputed_lagrange_polynomials,\n    const vec_GF2E &y_values) {\n  if (precomputed_lagrange_polynomials.size() != (size_t)y_values.length())\n    throw std::runtime_error(\"invalid sizes for interpolation\");\n\n  GF2EX res;\n  size_t m = y_values.length();\n  for (size_t k = 0; k < m; k++) {\n    res += precomputed_lagrange_polynomials[k] * y_values[k];\n  }\n  return res;\n}\n} // namespace utils\n", "meta": {"hexsha": "2818438a1f6935cb29c546300ae066ab1017566d", "size": 2591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "field/tests/utils.cpp", "max_stars_repo_name": "shibammukherjee/rainier-signatures", "max_stars_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "field/tests/utils.cpp", "max_issues_repo_name": "shibammukherjee/rainier-signatures", "max_issues_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "field/tests/utils.cpp", "max_forks_repo_name": "shibammukherjee/rainier-signatures", "max_forks_repo_head_hexsha": "cd7c89e418d52c1288c1d802b30043d09bb89cd8", "max_forks_repo_licenses": ["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.91, "max_line_length": 78, "alphanum_fraction": 0.6754148977, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5775055991825021}}
{"text": "#pragma once\n\n#include <boost/math/special_functions/hermite.hpp>\n\n#include \"hermiten_impl.hpp\"\n#include \"poly_base.hpp\"\n\n\nnamespace boltzmann {\n\n/**\n * @brief Physicists' Hermite functions normalized\n *        This class evaluates\n *        \\f$ h_j(x) exp(-x^2/2)\\f$, where\n *         \\f$ h_j(x)\\f$ is the normalized physicists' Hermite polynomial, orthogonal wrt.\n *         weight \\f$ exp(-x^21)\\f$.\n *\n */\ntemplate <typename T>\nclass HermiteNW : public PolyBase<T>\n{\n public:\n  using typename PolyBase<T>::numeric_t;\n\n public:\n  HermiteNW(unsigned int n);\n  void compute(const std::vector<numeric_t>& x);\n\n private:\n  using PolyBase<T>::Y_;\n  using PolyBase<T>::n_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename T>\nHermiteNW<T>::HermiteNW(unsigned int n)\n    : PolyBase<T>(n)\n{ /* empty */\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename T>\nvoid\nHermiteNW<T>::compute(const std::vector<numeric_t>& x)\n{\n  Y_.resize(boost::extents[n_ + 1][x.size()]);\n  unsigned int N = x.size();\n\n  std::vector<numeric_t> expw(x.size());\n  for (unsigned int i = 0; i < N; ++i) {\n    expw[i] = ::math::exp(-x[i] * x[i] * 1 / numeric_t(2));\n  }\n\n  // initalize l = 0\n  for (unsigned int i = 0; i < N; ++i) {\n    Y_[0][i] = boost::math::hermiten(0, x[i]) * expw[i];\n    Y_[1][i] = boost::math::hermiten(1, x[i]) * expw[i];\n  }\n\n  for (unsigned int l = 1; l < n_; ++l) {\n    //#pragma omp parallel for\n    for (unsigned int i = 0; i < N; ++i) {\n      Y_[l + 1][i] = boost::math::hermiten_next(l, x[i], Y_[l][i], Y_[l - 1][i]);\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "81951fbb2766922bc524cf9b7efede54a309cccd", "size": 1652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/hermitenw.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/hermitenw.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/hermitenw.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": 23.9420289855, "max_line_length": 90, "alphanum_fraction": 0.5435835351, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.5774498276512182}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#define _USE_MATH_DEFINES\n#include \"transforms.h\"\n\n#include <Eigen/Geometry>\n#include <cmath>\n#include <exception>\n#include <iostream>\n\nnamespace scenepic\n{\n  namespace Transforms\n  {\n    Transform scale(float scale)\n    {\n      Transform matrix = Transform::Identity();\n      matrix(0, 0) = matrix(1, 1) = matrix(2, 2) = scale;\n      return matrix;\n    }\n\n    Transform scale(const Vector& scale)\n    {\n      Transform matrix = Transform::Identity();\n      matrix(0, 0) = scale(0);\n      matrix(1, 1) = scale(1);\n      matrix(2, 2) = scale(2);\n      return matrix;\n    }\n\n    Transform translate(const Vector& vec)\n    {\n      Transform matrix = Transform::Identity();\n      matrix.topRightCorner(3, 1) = vec.transpose();\n      return matrix;\n    }\n\n    Transform rotation_matrix_from_axis_angle(const Vector& axis, float angle)\n    {\n      if (std::abs(angle) < 0.0001)\n      {\n        return Transform::Identity();\n      }\n\n      float x = axis(0);\n      float y = axis(1);\n      float z = axis(2);\n      float cos = std::cos(angle);\n      float sin = std::sin(angle);\n      Transform matrix;\n      matrix << x * x + (1 - x * x) * cos, x * y * (1 - cos) - z * sin,\n        x * z * (1 - cos) + y * sin, 0, x * y * (1 - cos) + z * sin,\n        y * y + (1 - y * y) * cos, y * z * (1 - cos) - x * sin, 0,\n        x * z * (1 - cos) - y * sin, z * y * (1 - cos) + x * sin,\n        z * z + (1 - z * z) * cos, 0, 0, 0, 0, 1;\n      return matrix;\n    }\n\n    Quaternion quaternion_from_axis_angle(const Vector& axis, float angle)\n    {\n      Vector norm_axis = axis.normalized();\n      float half_sin = std::sin(angle * 0.5f);\n      float half_cos = std::cos(angle * 0.5f);\n      Quaternion quat(\n        norm_axis(0) * half_sin,\n        norm_axis(1) * half_sin,\n        norm_axis(2) * half_sin,\n        half_cos);\n      return quat;\n    }\n\n    std::pair<Vector, float> axis_angle_to_align_x_to_axis(const Vector& axis)\n    {\n      std::pair<Vector, float> axis_angle;\n      Vector norm_axis = axis.normalized();\n      if (norm_axis(1) == 0 && norm_axis(2) == 0)\n      {\n        if (norm_axis(0) == -1)\n        {\n          axis_angle.first << 0, 1, 0;\n          axis_angle.second = static_cast<float>(M_PI);\n        }\n        else\n        {\n          axis_angle.first << 1, 0, 0;\n          axis_angle.second = 0;\n        }\n      }\n      else\n      {\n        float rot_angle = std::acos(norm_axis(0));\n        if (rot_angle == 0)\n        {\n          axis_angle.first << 1, 0, 0;\n          axis_angle.second = 0;\n        }\n        else\n        {\n          axis_angle.first << 0, -norm_axis(2), norm_axis(1);\n          axis_angle.first /= std::sqrt(\n            norm_axis(2) * norm_axis(2) + norm_axis(1) * norm_axis(1));\n          axis_angle.second = rot_angle;\n        }\n      }\n\n      return axis_angle;\n    }\n\n    Quaternion quaternion_to_align_x_to_axis(const Vector& axis)\n    {\n      auto axis_angle = axis_angle_to_align_x_to_axis(axis);\n      return quaternion_from_axis_angle(axis_angle.first, axis_angle.second);\n    }\n\n    Transform rotation_to_align_x_to_axis(const Vector& axis)\n    {\n      auto axis_angle = axis_angle_to_align_x_to_axis(axis);\n      return rotation_matrix_from_axis_angle(\n        axis_angle.first, axis_angle.second);\n    }\n\n    Transform rotation_about_x(float angle)\n    {\n      float cos = std::cos(angle);\n      float sin = std::sin(angle);\n      Transform matrix;\n      matrix << 1, 0, 0, 0, 0, cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1;\n      return matrix;\n    }\n\n    Transform rotation_about_y(float angle)\n    {\n      float cos = std::cos(angle);\n      float sin = std::sin(angle);\n      Transform matrix;\n      matrix << cos, 0, sin, 0, 0, 1, 0, 0, -sin, 0, cos, 0, 0, 0, 0, 1;\n      return matrix;\n    }\n\n    Transform rotation_about_z(float angle)\n    {\n      float cos = std::cos(angle);\n      float sin = std::sin(angle);\n      Transform matrix;\n      matrix << cos, -sin, 0, 0, sin, cos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n      return matrix;\n    }\n\n    Transform look_at_rotation(\n      const Vector& center, const Vector& look_at, const Vector& up_dir)\n    {\n      Transform matrix = Transform::Identity();\n      auto z_axis = (center - look_at).normalized();\n      auto x_axis = (up_dir.cross(z_axis)).normalized();\n      auto y_axis = (z_axis.cross(x_axis)).normalized();\n      matrix.row(0).leftCols(3) = x_axis;\n      matrix.row(1).leftCols(3) = y_axis;\n      matrix.row(2).leftCols(3) = z_axis;\n      return matrix;\n    }\n\n    Transform euler_angles_to_matrix(\n      const Vector& euler_angles, const std::string& convention)\n    {\n      Transform matrix = Transform::Identity();\n      for (auto i = 2; i >= 0; --i)\n      {\n        auto axis = convention[i];\n        float angle = euler_angles(i);\n        switch (axis)\n        {\n          case 'X':\n          case 'x':\n            matrix = rotation_about_x(angle) * matrix;\n            break;\n\n          case 'Y':\n          case 'y':\n            matrix = rotation_about_y(angle) * matrix;\n            break;\n\n          case 'Z':\n          case 'z':\n            matrix = rotation_about_z(angle) * matrix;\n            break;\n\n          default:\n            throw std::invalid_argument(\"Invalid convention: \" + convention);\n        }\n      }\n\n      return matrix;\n    }\n\n    Transform quaternion_to_matrix(const Quaternion& quaternion)\n    {\n      float qw = quaternion.w();\n      float qx = quaternion.x();\n      float qy = quaternion.y();\n      float qz = quaternion.z();\n      float qx2 = qx * qx;\n      float qy2 = qy * qy;\n      float qz2 = qz * qz;\n      Transform matrix;\n      matrix << 1 - 2 * qy2 - 2 * qz2, 2 * qx * qy - 2 * qz * qw,\n        2 * qx * qz + 2 * qy * qw, 0, 2 * qx * qy + 2 * qz * qw,\n        1 - 2 * qx2 - 2 * qz2, 2 * qy * qz - 2 * qx * qw, 0,\n        2 * qx * qz - 2 * qy * qw, 2 * qy * qz + 2 * qx * qw,\n        1 - 2 * qx2 - 2 * qy2, 0, 0, 0, 0, 1;\n      return matrix;\n    }\n\n    Quaternion quaternion_multiply(const Quaternion& a, const Quaternion& b)\n    {\n      float x = a.w() * b.x() + a.x() * b.w() + a.y() * b.z() - a.z() * b.y();\n      float y = a.w() * b.y() + a.y() * b.w() + a.z() * b.x() - a.x() * b.z();\n      float z = a.w() * b.z() + a.z() * b.w() + a.x() * b.y() - a.y() * b.x();\n      float w = a.w() * b.w() - a.x() * b.x() - a.y() * b.y() - a.z() * b.z();\n      return Quaternion(x, y, z, w);\n    }\n\n    Transform gl_projection(\n      double fov_y_degrees, double aspect_ratio, double znear, double zfar)\n    {\n      double fov_y = (M_PI * fov_y_degrees / 180.0);\n      double f = 1.0 / std::tan(fov_y / 2);\n      float fx = static_cast<float>(f / aspect_ratio);\n      float fy = static_cast<float>(f);\n      double nf = 1.0 / (znear - zfar);\n      float A = static_cast<float>((zfar + znear) * nf);\n      float B = static_cast<float>(2 * zfar * znear * nf);\n\n      Transform matrix;\n      matrix << fx, 0, 0, 0, 0, fy, 0, 0, 0, 0, A, B, 0, 0, -1, 0;\n      return matrix;\n    }\n\n    Transform gl_projection(\n      const Intrinsic& camera_matrix,\n      int width,\n      int height,\n      double znear,\n      double zfar)\n    {\n      float K00 = camera_matrix(0, 0);\n      float K01 = camera_matrix(0, 1);\n      float K02 = camera_matrix(0, 2);\n      float K11 = camera_matrix(1, 1);\n      float K12 = camera_matrix(1, 2);\n      float A = static_cast<float>((zfar + znear) / (znear - zfar));\n      float B = static_cast<float>(2 * zfar * znear / (znear - zfar));\n      Transform matrix;\n      matrix << 2 * K00 / width, -2 * K01 / width, (width - 2 * K02) / width, 0,\n        0, 2 * K11 / height, (2 * K12 - height) / height, 0, 0, 0, A, B, 0, 0,\n        -1, 0;\n      return matrix;\n    }\n\n    Transform gl_world_to_camera(const Extrinsic& extrinsic)\n    {\n      Transform camera_to_world =\n        extrinsic * rotation_about_x(static_cast<float>(M_PI));\n      return camera_to_world.inverse();\n    }\n\n  } // namespace Transforms\n} // namespace scenepic", "meta": {"hexsha": "d9368c900cdb1e83ba12d6d46993deba76b57ce5", "size": 7966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scenepic/transforms.cpp", "max_stars_repo_name": "microsoft/scenepic", "max_stars_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:19:23.000Z", "max_issues_repo_path": "src/scenepic/transforms.cpp", "max_issues_repo_name": "microsoft/scenepic", "max_issues_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-05T11:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T13:33:43.000Z", "max_forks_repo_path": "src/scenepic/transforms.cpp", "max_forks_repo_name": "microsoft/scenepic", "max_forks_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:50:14.000Z", "avg_line_length": 29.723880597, "max_line_length": 80, "alphanum_fraction": 0.5386643234, "num_tokens": 2386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5774266815627997}}
{"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    Rot3M.cpp\n * @brief   Rotation (internal: 3*3 matrix representation*)\n * @author  Alireza Fathi\n * @author  Christian Potthast\n * @author  Frank Dellaert\n * @author  Richard Roberts\n */\n\n#include <gtsam/config.h> // Get GTSAM_USE_QUATERNIONS macro\n\n#ifndef GTSAM_USE_QUATERNIONS\n\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/geometry/SO3.h>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nRot3::Rot3() : rot_(I_3x3) {}\n\n/* ************************************************************************* */\nRot3::Rot3(const Point3& col1, const Point3& col2, const Point3& col3) {\n  Matrix3 R;\n  R << col1, col2, col3;\n  rot_ = SO3(R);\n}\n\n/* ************************************************************************* */\nRot3::Rot3(double R11, double R12, double R13, double R21, double R22,\n           double R23, double R31, double R32, double R33) {\n  Matrix3 R;\n  R << R11, R12, R13, R21, R22, R23, R31, R32, R33;\n  rot_ = SO3(R);\n}\n\n/* ************************************************************************* */\nRot3::Rot3(const gtsam::Quaternion& q) : rot_(q.toRotationMatrix()) {\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Rx(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      1,  0,  0,\n      0, ct,-st,\n      0, st, ct);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Ry(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      ct, 0, st,\n      0, 1,  0,\n      -st, 0, ct);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Rz(double t) {\n  double st = sin(t), ct = cos(t);\n  return Rot3(\n      ct,-st, 0,\n      st, ct, 0,\n      0,  0, 1);\n}\n\n/* ************************************************************************* */\n// Considerably faster than composing matrices above !\nRot3 Rot3::RzRyRx(double x, double y, double z, OptionalJacobian<3, 1> Hx,\n                  OptionalJacobian<3, 1> Hy, OptionalJacobian<3, 1> Hz) {\n  double cx=cos(x),sx=sin(x);\n  double cy=cos(y),sy=sin(y);\n  double cz=cos(z),sz=sin(z);\n  double ss_ = sx * sy;\n  double cs_ = cx * sy;\n  double sc_ = sx * cy;\n  double cc_ = cx * cy;\n  double c_s = cx * sz;\n  double s_s = sx * sz;\n  double _cs = cy * sz;\n  double _cc = cy * cz;\n  double s_c = sx * cz;\n  double c_c = cx * cz;\n  double ssc = ss_ * cz, csc = cs_ * cz, sss = ss_ * sz, css = cs_ * sz;\n  if (Hx) (*Hx) << 1, 0, 0;\n  if (Hy) (*Hy) << 0, cx, -sx;\n  if (Hz) (*Hz) << -sy, sc_, cc_;\n  return Rot3(\n      _cc,- c_s + ssc,  s_s + csc,\n      _cs,  c_c + sss, -s_c + css,\n      -sy,        sc_,        cc_\n  );\n}\n\n/* ************************************************************************* */\nRot3 Rot3::normalized() const {\n  /// Implementation from here: https://stackoverflow.com/a/23082112/1236990\n\n  /// Essentially, this computes the orthogonalization error, distributes the\n  /// error to the x and y rows, and then performs a Taylor expansion to\n  /// orthogonalize.\n\n  Matrix3 rot = rot_.matrix(), rot_orth;\n\n  // Check if determinant is already 1.\n  // If yes, then return the current Rot3.\n  if (std::fabs(rot.determinant()-1) < 1e-12) return Rot3(rot_);\n\n  Vector3 x = rot.block<1, 3>(0, 0), y = rot.block<1, 3>(1, 0);\n  double error = x.dot(y);\n\n  Vector3 x_ort = x - (error / 2) * y, y_ort = y - (error / 2) * x;\n  Vector3 z_ort = x_ort.cross(y_ort);\n\n  rot_orth.block<1, 3>(0, 0) = 0.5 * (3 - x_ort.dot(x_ort)) * x_ort;\n  rot_orth.block<1, 3>(1, 0) = 0.5 * (3 - y_ort.dot(y_ort)) * y_ort;\n  rot_orth.block<1, 3>(2, 0) = 0.5 * (3 - z_ort.dot(z_ort)) * z_ort;\n\n  return Rot3(rot_orth);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::operator*(const Rot3& R2) const {\n  return Rot3(rot_*R2.rot_);\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::transpose() const {\n  return rot_.matrix().transpose();\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::rotate(const Point3& p,\n    OptionalJacobian<3,3> H1,  OptionalJacobian<3,3> H2) const {\n  if (H1) *H1 = rot_.matrix() * skewSymmetric(-p.x(), -p.y(), -p.z());\n  if (H2) *H2 = rot_.matrix();\n  return rot_.matrix() * p;\n}\n\n/* ************************************************************************* */\n// Log map at identity - return the canonical coordinates of this rotation\nVector3 Rot3::Logmap(const Rot3& R, OptionalJacobian<3,3> H) {\n  return SO3::Logmap(R.rot_,H);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::CayleyChart::Retract(const Vector3& omega, OptionalJacobian<3,3> H) {\n  if (H) throw std::runtime_error(\"Rot3::CayleyChart::Retract Derivative\");\n  const double x = omega(0), y = omega(1), z = omega(2);\n  const double x2 = x * x, y2 = y * y, z2 = z * z;\n  const double xy = x * y, xz = x * z, yz = y * z;\n  const double f = 1.0 / (4.0 + x2 + y2 + z2), _2f = 2.0 * f;\n  return Rot3((4 + x2 - y2 - z2) * f, (xy - 2 * z) * _2f, (xz + 2 * y) * _2f,\n          (xy + 2 * z) * _2f, (4 - x2 + y2 - z2) * f, (yz - 2 * x) * _2f,\n          (xz - 2 * y) * _2f, (yz + 2 * x) * _2f, (4 - x2 - y2 + z2) * f);\n}\n\n/* ************************************************************************* */\nVector3 Rot3::CayleyChart::Local(const Rot3& R, OptionalJacobian<3,3> H) {\n  if (H) throw std::runtime_error(\"Rot3::CayleyChart::Local Derivative\");\n  // Create a fixed-size matrix\n  Matrix3 A = R.matrix();\n  // Mathematica closed form optimization (procrastination?) gone wild:\n  const double a = A(0, 0), b = A(0, 1), c = A(0, 2);\n  const double d = A(1, 0), e = A(1, 1), f = A(1, 2);\n  const double g = A(2, 0), h = A(2, 1), i = A(2, 2);\n  const double di = d * i, ce = c * e, cd = c * d, fg = f * g;\n  const double M = 1 + e - f * h + i + e * i;\n  const double K = -4.0 / (cd * h + M + a * M - g * (c + ce) - b * (d + di - fg));\n  const double x = a * f - cd + f;\n  const double y = b * f - ce - c;\n  const double z = fg - di - d;\n  return K * Vector3(x, y, z);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::ChartAtOrigin::Retract(const Vector3& omega, ChartJacobian H) {\n  static const CoordinatesMode mode = ROT3_DEFAULT_COORDINATES_MODE;\n  if (mode == Rot3::EXPMAP) return Expmap(omega, H);\n  if (mode == Rot3::CAYLEY) return CayleyChart::Retract(omega, H);\n  else throw std::runtime_error(\"Rot3::Retract: unknown mode\");\n}\n\n/* ************************************************************************* */\nVector3 Rot3::ChartAtOrigin::Local(const Rot3& R, ChartJacobian H) {\n  static const CoordinatesMode mode = ROT3_DEFAULT_COORDINATES_MODE;\n  if (mode == Rot3::EXPMAP) return Logmap(R, H);\n  if (mode == Rot3::CAYLEY) return CayleyChart::Local(R, H);\n  else throw std::runtime_error(\"Rot3::Local: unknown mode\");\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::matrix() const {\n  return rot_.matrix();\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::r1() const { return Point3(rot_.matrix().col(0)); }\n\n/* ************************************************************************* */\nPoint3 Rot3::r2() const { return Point3(rot_.matrix().col(1)); }\n\n/* ************************************************************************* */\nPoint3 Rot3::r3() const { return Point3(rot_.matrix().col(2)); }\n\n/* ************************************************************************* */\ngtsam::Quaternion Rot3::toQuaternion() const {\n  return gtsam::Quaternion(rot_.matrix());\n}\n\n/* ************************************************************************* */\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "02e5b771fce45fb8bcc4103a1933c68dd3579bdf", "size": 8239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3M.cpp", "max_stars_repo_name": "martinvl/gtsam", "max_stars_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/geometry/Rot3M.cpp", "max_issues_repo_name": "martinvl/gtsam", "max_issues_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T17:43:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T20:21:19.000Z", "max_forks_repo_path": "gtsam/geometry/Rot3M.cpp", "max_forks_repo_name": "martinvl/gtsam", "max_forks_repo_head_hexsha": "2315df694aff7e648d2e22a478685946e7de4f24", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T08:39:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-02T08:39:51.000Z", "avg_line_length": 35.5129310345, "max_line_length": 82, "alphanum_fraction": 0.461221022, "num_tokens": 2406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6825737214979746, "lm_q1q2_score": 0.577418082908908}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2013 - 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, Texas A&M University, 2013 \n */ \n\n\n\n// 程序以通常的包含文件开始，所有这些文件你现在应该都见过了。\n\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/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/grid/grid_out.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/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\n#include <fstream> \n#include <iostream> \n\n// 然后照例将这个程序的所有内容放入一个命名空间，并将deal.II命名空间导入到我们将要工作的命名空间中。\n\nnamespace Step26 \n{ \n  using namespace dealii; \n// @sect3{The <code>HeatEquation</code> class}  \n\n// 下一个部分是这个程序的主类的声明。它沿用了以前的例子中公认的路径。如果你看过 step-6 ，例如，这里唯一值得注意的是，我们需要建立两个矩阵（质量和拉普拉斯矩阵），并保存当前和前一个时间步骤的解。然后，我们还需要存储当前时间、时间步长和当前时间步长的编号。最后一个成员变量表示介绍中讨论的theta参数，它允许我们在一个程序中处理显式和隐式欧拉方法，以及Crank-Nicolson方法和其他通用方法。\n\n// 就成员函数而言，唯一可能的惊喜是 <code>refine_mesh</code> 函数需要最小和最大的网格细化级别的参数。这样做的目的在介绍中已经讨论过了。\n\n  template <int dim> \n  class HeatEquation \n  { \n  public: \n    HeatEquation(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void solve_time_step(); \n    void output_results() const; \n    void refine_mesh(const unsigned int min_grid_level, \n                     const unsigned int max_grid_level); \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> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> old_solution; \n    Vector<double> system_rhs; \n\n    double       time; \n    double       time_step; \n    unsigned int timestep_number; \n\n    const double theta; \n  }; \n\n//  @sect3{Equation data}  \n\n// 在下面的类和函数中，我们实现了定义这个问题的各种数据（右手边和边界值），这些数据在这个程序中使用，我们需要函数对象。右手边的选择是在介绍的最后讨论的。对于边界值，我们选择零值，但这很容易在下面改变。\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    RightHandSide() \n      : Function<dim>() \n      , period(0.2) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n  private: \n    const double period; \n  }; \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    AssertIndexRange(component, 1); \n    Assert(dim == 2, ExcNotImplemented()); \n\n    const double time = this->get_time(); \n    const double point_within_period = \n      (time / period - std::floor(time / period)); \n\n    if ((point_within_period >= 0.0) && (point_within_period <= 0.2)) \n      { \n        if ((p[0] > 0.5) && (p[1] > -0.5)) \n          return 1; \n        else \n          return 0; \n      } \n    else if ((point_within_period >= 0.5) && (point_within_period <= 0.7)) \n      { \n        if ((p[0] > -0.5) && (p[1] > 0.5)) \n          return 1; \n        else \n          return 0; \n      } \n    else \n      return 0; \n  } \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    return 0; \n  } \n\n//  @sect3{The <code>HeatEquation</code> implementation}  \n\n// 现在是实现主类的时候了。让我们从构造函数开始，它选择了一个线性元素，一个时间步长为1/500的常数（记得上面把右边的源的一个周期设置为0.2，所以我们用100个时间步长来解决每个周期），并通过设置  $\\theta=1/2$  选择了Crank Nicolson方法.\n\n  template <int dim> \n  HeatEquation<dim>::HeatEquation() \n    : fe(1) \n    , dof_handler(triangulation) \n    , time_step(1. / 500) \n    , theta(0.5) \n  {} \n\n//  @sect4{<code>HeatEquation::setup_system</code>}  \n\n// 下一个函数是设置DoFHandler对象，计算约束，并将线性代数对象设置为正确的大小。我们还在这里通过简单地调用库中的两个函数来计算质量和拉普拉斯矩阵。\n\n// 注意我们在组装矩阵时不考虑悬挂节点的约束（两个函数都有一个AffineConstraints参数，默认为一个空对象）。这是因为我们要在结合当前时间步长的矩阵后，在run()中浓缩约束。\n\n  template <int dim> \n  void HeatEquation<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n\n    std::cout << std::endl \n              << \"===========================================\" << std::endl \n              << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl \n              << std::endl; \n\n    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, 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 =  */ true);\n\n    sparsity_pattern.copy_from(dsp); \n\n    mass_matrix.reinit(sparsity_pattern); \n    laplace_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    MatrixCreator::create_laplace_matrix(dof_handler, \n                                         QGauss<dim>(fe.degree + 1), \n                                         laplace_matrix); \n\n    solution.reinit(dof_handler.n_dofs()); \n    old_solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{<code>HeatEquation::solve_time_step</code>}  \n\n// 下一个函数是解决单个时间步骤的实际线性系统的函数。这里没有什么值得惊讶的。\n\n  template <int dim> \n  void HeatEquation<dim>::solve_time_step() \n  { \n    SolverControl            solver_control(1000, 1e-8 * system_rhs.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.0); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    constraints.distribute(solution); \n\n    std::cout << \"     \" << solver_control.last_step() << \" CG iterations.\" \n              << std::endl; \n  } \n\n//  @sect4{<code>HeatEquation::output_results</code>}  \n\n// 在生成图形输出方面也没有什么新东西，只是我们告诉DataOut对象当前的时间和时间步长是多少，以便将其写入输出文件中。\n\n  template <int dim> \n  void HeatEquation<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\"); \n\n    data_out.build_patches(); \n\n    data_out.set_flags(DataOutBase::VtkFlags(time, timestep_number)); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtk\"; \n    std::ofstream output(filename); \n    data_out.write_vtk(output); \n  } \n// @sect4{<code>HeatEquation::refine_mesh</code>}  \n\n// 这个函数是程序中最有趣的部分。它负责自适应网格细化的工作。这个函数执行的三个任务是：首先找出需要细化/粗化的单元，然后实际进行细化，最后在两个不同的网格之间传输解向量。第一个任务是通过使用成熟的凯利误差估计器来实现的。第二项任务是实际进行再细化。这也只涉及到基本的函数，例如 <code>refine_and_coarsen_fixed_fraction</code> ，它可以细化那些具有最大估计误差的单元，这些误差加起来占60%，并粗化那些具有最小误差的单元，这些单元加起来占40%的误差。请注意，对于像当前这样的问题，即有事发生的区域正在四处移动，我们希望积极地进行粗化，以便我们能够将单元格移动到有必要的地方。\n\n// 正如在介绍中已经讨论过的，太小的网格会导致太小的时间步长，而太大的网格会导致太小的分辨率。因此，在前两个步骤之后，我们有两个循环，将细化和粗化限制在一个允许的单元范围内。\n\n  template <int dim> \n  void HeatEquation<dim>::refine_mesh(const unsigned int min_grid_level, \n                                      const unsigned int max_grid_level) \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\n    GridRefinement::refine_and_coarsen_fixed_fraction(triangulation, \n                                                      estimated_error_per_cell, \n                                                      0.6, \n                                                      0.4); \n\n    if (triangulation.n_levels() > max_grid_level) \n      for (const auto &cell : \n           triangulation.active_cell_iterators_on_level(max_grid_level)) \n        cell->clear_refine_flag(); \n    for (const auto &cell : \n         triangulation.active_cell_iterators_on_level(min_grid_level)) \n      cell->clear_coarsen_flag(); \n\n// 上面这两个循环略有不同，但这很容易解释。在第一个循环中，我们没有调用  <code>triangulation.end()</code>  ，而是调用  <code>triangulation.end_active(max_grid_level)</code>  。这两个调用应该产生相同的迭代器，因为迭代器是按级别排序的，不应该有任何级别高于 <code>max_grid_level</code> 的单元格。事实上，这段代码确保了这种情况的发生。\n\n// 作为网格细化的一部分，我们需要将旧的网格中的解向量转移到新的网格中。为此，我们使用了SolutionTransfer类，我们必须准备好需要转移到新网格的解向量（一旦完成细化，我们将失去旧的网格，所以转移必须与细化同时发生）。在我们调用这个函数的时候，我们将刚刚计算出解决方案，所以我们不再需要old_solution变量（它将在网格被细化后被解决方案覆盖，也就是在时间步长结束时；见下文）。换句话说，我们只需要一个求解向量，并将其复制到一个临时对象中，当我们进一步向下调用 <code>setup_system()</code> 时，它就不会被重置。\n\n// 因此，我们将一个SolutionTransfer对象附加到旧的DoF处理程序中，以初始化它。然后，我们准备好三角形和数据向量，以便进行细化（按照这个顺序）。\n\n    SolutionTransfer<dim> solution_trans(dof_handler); \n\n    Vector<double> previous_solution; \n    previous_solution = solution; \n    triangulation.prepare_coarsening_and_refinement(); \n    solution_trans.prepare_for_coarsening_and_refinement(previous_solution); \n\n// 现在一切都准备好了，所以进行细化并在新网格上重新创建DoF结构，最后在 <code>setup_system</code> 函数中初始化矩阵结构和新的向量。接下来，我们实际执行从旧网格到新网格的插值解。最后一步是对解向量应用悬空节点约束，即确保位于悬空节点上的自由度值，使解是连续的。这是必要的，因为SolutionTransfer只对单元格进行局部操作，不考虑邻域。\n\n    triangulation.execute_coarsening_and_refinement(); \n    setup_system(); \n\n    solution_trans.interpolate(previous_solution, solution); \n    constraints.distribute(solution); \n  } \n\n//  @sect4{<code>HeatEquation::run</code>}  \n\n// 这是程序的主要驱动，我们在这里循环所有的时间步骤。在函数的顶部，我们通过重复第一个时间步长，设置初始全局网格细化的数量和自适应网格细化的初始周期数量。然后，我们创建一个网格，初始化我们要处理的各种对象，设置一个标签，说明我们在重新运行第一个时间步长时应该从哪里开始，并将初始解插值到网格上（我们在这里选择了零函数，当然，我们可以用更简单的方法，直接将解向量设置为零）。我们还输出一次初始时间步长。\n\n//  @note  如果你是一个有经验的程序员，你可能会对我们在这段代码中使用 <code>goto</code> 语句感到吃惊   <code>goto</code> 语句现在已经不是特别受人欢迎了，因为计算机科学界的大师之一Edsgar Dijkstra在1968年写了一封信，叫做 \"Go To Statement considered harmful\"（见<a href=\"http:en.wikipedia.org/wiki/Considered_harmful\">here</a>）。这段代码的作者全心全意地赞同这一观念。  <code>goto</code> 是难以理解的。事实上，deal.II几乎不包含任何出现的情况：不包括基本上是从书本上转录的代码，也不计算重复的代码片断，在写这篇笔记时，大约60万行代码中有3个位置；我们还在4个教程程序中使用它，其背景与这里完全相同。与其在这里试图证明这种情况的出现，不如先看看代码，我们在函数的最后再来讨论这个问题。\n\n  template <int dim> \n  void HeatEquation<dim>::run() \n  { \n    const unsigned int initial_global_refinement       = 2; \n    const unsigned int n_adaptive_pre_refinement_steps = 4; \n\n    GridGenerator::hyper_L(triangulation); \n    triangulation.refine_global(initial_global_refinement); \n\n    setup_system(); \n\n    unsigned int pre_refinement_step = 0; \n\n    Vector<double> tmp; \n    Vector<double> forcing_terms; \n\n  start_time_iteration: \n\n    time            = 0.0; \n    timestep_number = 0; \n\n    tmp.reinit(solution.size()); \n    forcing_terms.reinit(solution.size()); \n\n    VectorTools::interpolate(dof_handler, \n                             Functions::ZeroFunction<dim>(), \n                             old_solution); \n    solution = old_solution; \n\n    output_results(); \n\n// 然后我们开始主循环，直到计算的时间超过我们的结束时间0.5。第一个任务是建立我们需要在每个时间步骤中解决的线性系统的右手边。回顾一下，它包含项 $MU^{n-1}-(1-\\theta)k_n AU^{n-1}$  。我们把这些项放到变量system_rhs中，借助于一个临时矢量。\n\n    while (time <= 0.5) \n      { \n        time += time_step; \n        ++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); \n\n        laplace_matrix.vmult(tmp, old_solution); \n        system_rhs.add(-(1 - theta) * time_step, tmp); \n\n// 第二块是计算源项的贡献。这与术语  $k_n \\left[ (1-\\theta)F^{n-1} + \\theta F^n \\right]$  相对应。下面的代码调用  VectorTools::create_right_hand_side  来计算向量  $F$  ，在这里我们在评估之前设置了右侧（源）函数的时间。这一切的结果最终都在forcing_terms变量中。\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 *= time_step * theta; \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(time_step * (1 - theta), tmp); \n\n// 接下来，我们将强迫项加入到来自时间步长的强迫项中，同时建立矩阵 $M+k_n\\theta A$ ，我们必须在每个时间步长中进行反转。这些操作的最后一块是消除线性系统中悬挂的节点约束自由度。\n\n        system_rhs += forcing_terms; \n\n        system_matrix.copy_from(mass_matrix); \n        system_matrix.add(theta * time_step, laplace_matrix); \n\n        constraints.condense(system_matrix, system_rhs); \n\n// 在解决这个问题之前，我们还需要做一个操作：边界值。为此，我们创建一个边界值对象，将适当的时间设置为当前时间步长的时间，并像以前多次那样对其进行评估。其结果也被用来在线性系统中设置正确的边界值。\n\n        { \n          BoundaryValues<dim> boundary_values_function; \n          boundary_values_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_function, \n                                                   boundary_values); \n\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        output_results(); \n\n// ...负责网格的细化。在这里，我们要做的是：(i)在求解过程的最开始，细化所要求的次数，之后我们跳到顶部重新开始时间迭代，(ii)之后每隔五步细化一次。\n\n// 时间循环和程序的主要部分以开始进入下一个时间步骤结束，将old_solution设置为我们刚刚计算出的解决方案。\n\n        if ((timestep_number == 1) && \n            (pre_refinement_step < n_adaptive_pre_refinement_steps)) \n          { \n            refine_mesh(initial_global_refinement, \n                        initial_global_refinement + \n                          n_adaptive_pre_refinement_steps); \n            ++pre_refinement_step; \n\n            tmp.reinit(solution.size()); \n            forcing_terms.reinit(solution.size()); \n\n            std::cout << std::endl; \n\n            goto start_time_iteration; \n          } \n        else if ((timestep_number > 0) && (timestep_number % 5 == 0)) \n          { \n            refine_mesh(initial_global_refinement, \n                        initial_global_refinement + \n                          n_adaptive_pre_refinement_steps); \n            tmp.reinit(solution.size()); \n            forcing_terms.reinit(solution.size()); \n          } \n\n        old_solution = solution; \n      } \n  } \n} // namespace Step26 \n\n// 现在你已经看到了这个函数的作用，让我们再来看看  <code>goto</code>  的问题。从本质上讲，代码所做的事情是这样的。\n// @code\n//    void run ()\n//    {\n//      initialize;\n//    start_time_iteration:\n//      for (timestep=1...)\n//      {\n//         solve timestep;\n//         if (timestep==1 && not happy with the result)\n//         {\n//           adjust some data structures;\n//           goto start_time_iteration; simply try again\n//         }\n//         postprocess;\n//      }\n//    }\n//  @endcode \n//  这里，\"对结果满意 \"的条件是我们想保留当前的网格，还是宁愿细化网格并在新网格上重新开始。我们当然可以用下面的方法来取代  <code>goto</code>  的使用。\n//  @code\n//    void run ()\n//    {\n//      initialize;\n//      while (true)\n//      {\n//         solve timestep;\n//         if (not happy with the result)\n//            adjust some data structures;\n//         else\n//            break;\n//      }\n//      postprocess;\n\n\n//      for (timestep=2...)\n//      {\n//         solve timestep;\n//         postprocess;\n//      }\n//    }\n//  @endcode \n//  这样做的好处是摆脱了 <code>goto</code> ，但缺点是必须在两个不同的地方重复实现 \"解算时间步长 \"和 \"后处理 \"操作的代码。这可以通过将这些部分的代码（在上面的实际实现中是相当大的块）放到自己的函数中来解决，但是一个带有 <code>break</code> 语句的 <code>while(true)</code> 循环并不真的比 <code>goto</code> 容易阅读或理解。\n\n// 最后，人们可能会简单地同意，<i>in general</i> 。\n// <code>goto</code>  语句是个坏主意，但要务实地指出，在某些情况下，它们可以帮助避免代码重复和尴尬的控制流。这可能就是其中之一，它与Steve McConnell在他关于良好编程实践的优秀书籍 \"Code Complete\"  @cite CodeComplete 中采取的立场一致（见 step-1 的介绍中提到的这本书），该书花了惊人的10页来讨论一般的 <code>goto</code> 问题。\n\n//  @sect3{The <code>main</code> function}  \n\n// 走到这一步，这个程序的主函数又没有什么好讨论的了：它看起来就像自 step-6 以来的所有此类函数一样。\n\nint main() \n{ \n  try \n    { \n      using namespace Step26; \n\n      HeatEquation<2> heat_equation_solver; \n      heat_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", "meta": {"hexsha": "2f49e24392da7f48d3dc992e0586a7843d6639a6", "size": 18714, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-26/step-26.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-26/step-26.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-26/step-26.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.2120658135, "max_line_length": 439, "alphanum_fraction": 0.6101848883, "num_tokens": 6745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.5773616561626064}}
{"text": "//!\n//! @file       matrix.cpp\n//! @brief      implementing functions for matrix operations in plaintext\n//!\n//! @author     Miran Kim\n//! @date       Dec. 1, 2017\n//!\n\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n\n#include <cmath>\n#include <map>\n#include <math.h>  // pow\n#include <sys/time.h>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include \"math.h\"\n#include <cassert>\n#include <random>\n#include <string>\n#include <iomanip>\n\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include \"NTL/RR.h\"\n#include <NTL/ZZX.h>\n#include \"NTL/mat_RR.h\"\n#include \"NTL/vec_RR.h\"\n\n#include \"matrix.h\"\n\n//!@ Input: vec_RR\n//!@ Function: print the vector\n//!@ If print_size = 0, then print out all the components of an input vector\n\nvoid printRvector(vec_RR& vec, long print_size){\n    long len;\n    \n    if(print_size == 0){\n        len = vec.length();\n    }\n    else{\n        len = print_size;\n    }\n    \n    cout << \"   [\" ;\n    for(int i = 0; i < len; ++i){\n        cout << \" \" << vec[i] << ((i != len - 1) ? \"\\t\" : \"]\\n\");\n    }\n}\n\n\n//!@ Input: RR-matrix\n//!@ Function: print the matrix\nvoid printRmatrix(Mat<RR>& mat, const long print_size){\n    long rlen, clen;\n    \n    if(print_size == 0){\n        rlen = mat.NumRows();\n        clen = mat.NumCols();\n    }\n    else{\n        rlen = print_size;\n        clen = print_size;\n    }\n    \n    for(int i = 0; i< rlen; ++i){\n        cout << \"   [\";\n        for(int j = 0; j < clen; ++j){\n            cout << mat[i][j] << ((j != clen - 1) ? \"\\t\" : \"]\\n\");\n        }\n    }\n}\n\n//!@ Input: A and B\n//!@ Function: return the maximum norm of the difference of two input matrices A and B\nRR getError(mat_RR Amat, mat_RR Bmat, long nrows, long ncols){\n    RR ret = to_RR(\"0\");\n    \n    for(long i = 0; i < nrows; ++i){\n        for(long j = 0; j < ncols; ++j){\n            RR temp = abs(Amat[i][j]-Bmat[i][j]);\n            if (ret < temp){\n                ret = temp;\n            }\n            if(temp > 1e-2){\n                cout << \"(\" << i << \",\" << j  << \") = \" << Amat[i][j] << \", \" << Bmat[i][j]<< endl;\n            }\n        }\n    }\n    return ret;\n}\n\n", "meta": {"hexsha": "48bb993b6af25e14edeaa9a7a60743d2100562ad", "size": 2226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HEMat/matrix.cpp", "max_stars_repo_name": "zhanghan177/HEMat", "max_stars_repo_head_hexsha": "fdb45399ccfdcdd32e177f7180e5249d9c59e613", "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": "HEMat/matrix.cpp", "max_issues_repo_name": "zhanghan177/HEMat", "max_issues_repo_head_hexsha": "fdb45399ccfdcdd32e177f7180e5249d9c59e613", "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": "HEMat/matrix.cpp", "max_forks_repo_name": "zhanghan177/HEMat", "max_forks_repo_head_hexsha": "fdb45399ccfdcdd32e177f7180e5249d9c59e613", "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": 21.6116504854, "max_line_length": 99, "alphanum_fraction": 0.516621743, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.5773307518110528}}
{"text": "/*\n ___ ___ __     __ ____________\n|   |   |  |   |__|__|__   ___/  Ubiquitous Internet @ IIT-CNR\n|   |   |  |  /__/  /  /  /      Stateful FaaS Model Latency Simulator\n|   |   |  |/__/  /   /  /       https://github.com/ccicconetti/markovsim/\n|_______|__|__/__/   /__/\n\nLicensed under the MIT License <http://opensource.org/licenses/MIT>.\nCopyright (c) 2021 Claudio Cicconetti <https://ccicconetti.github.io/>\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/*\nCompute the average latency of a pool of FaaS clients, where:\n- one group is assigned one stateful container each;\n- another group of clients share a pool of stateless containers.\n*/\n\n#include \"Support/chrono.h\"\n#include \"Support/glograii.h\"\n\n#include <boost/program_options.hpp>\n\n#include <glog/logging.h>\n\n#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\nnamespace po = boost::program_options;\n\ndouble erlang_c(size_t aWorkers, double aLoad) {\n  assert(aWorkers > 0);\n  assert(aLoad > 0);\n\n  //            A\n  // return ---------\n  //          A + B\n\n  // compute A\n  double myFact = 1.0; // (aWorkers-1) * (aWorkers-2) * ... * 2 * 1\n  for (size_t i = 2; i < aWorkers; i++) {\n    myFact *= i;\n  }\n  double A = std::pow(aLoad, aWorkers) / (myFact * (aWorkers - aLoad));\n\n  // compute B\n  double B = 0;\n  double myCurFact = 1.0;\n  for (size_t i = 0; i < aWorkers; i++) {\n    if (i > 0) {\n      myCurFact *= i;\n    }\n    B += std::pow(aLoad, i) / myCurFact;\n  }\n\n  return A / (A + B);\n}\n\nint main(int argc, char *argv[]) {\n  uiiit::support::GlogRaii myGlogRaii(argv[0]);\n\n  size_t N_k; // number of clients\n  size_t C_k; // number of containers\n  double inv_mu_F;\n  double inv_mu_L;\n  double lambda_k;\n\n  std::string myOutput;\n\n#ifndef NDEBUG\n  assert(std::abs(erlang_c(40, 36) - 0.41156) < 0.0001);\n  assert(std::abs(erlang_c(40, 27) - 0.01272) < 0.0001);\n  assert(std::abs(erlang_c(40, 18) - 0.0000055155) < 0.0000000001);\n#endif\n\n  po::options_description myDesc(\"Allowed options\");\n  // clang-format off\n  myDesc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"arrival-rate\",\n     po::value<double>(&lambda_k)->default_value(0.075),\n     \"Arrival rate, in Hz.\")\n    (\"containers\",\n     po::value<size_t>(&C_k)->default_value(40),\n     \"Number of containers\")\n    (\"clients\",\n     po::value<size_t>(&N_k)->default_value(70),\n     \"Number of clients\")\n    (\"service-time-full\",\n     po::value<double>(&inv_mu_F)->default_value(1.0),\n     \"Service time for clients assigned a dedicated container, in s.\")\n    (\"service-time-less\",\n     po::value<double>(&inv_mu_L)->default_value(3.0),\n     \"Service time for clients sharing a pool of non-dedicated containers, in s.\")\n    (\"output\",\n     po::value<std::string>(&myOutput)->default_value(\"out.dat\"),\n     \"Output file.\")\n    ;\n  // clang-format on\n\n  try {\n    po::variables_map myVarMap;\n    po::store(po::parse_command_line(argc, argv, myDesc), myVarMap);\n    po::notify(myVarMap);\n\n    if (myVarMap.count(\"help\")) {\n      std::cout << myDesc << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    if (inv_mu_F <= 0) {\n      throw std::runtime_error(\"Invalid service time (full): \" +\n                               std::to_string(inv_mu_F));\n    }\n    double mu_F = 1.0 / inv_mu_F;\n    if (inv_mu_L <= 0) {\n      throw std::runtime_error(\"Invalid service time (less): \" +\n                               std::to_string(inv_mu_L));\n    }\n    double mu_L = 1.0 / inv_mu_L;\n\n    std::ofstream myOutfile(myOutput);\n    if (not myOutfile) {\n      throw std::runtime_error(\"Could not open file: \" + myOutput);\n    }\n\n    // n_F is the number of clients with dedicated containers\n    // it ranges from 0 (all containers are shared)\n    // to C_k-1 (only one container is shared)\n    for (size_t n_F = 0; n_F < C_k; n_F++) {\n      // number of clients associated to a pool of shared stateless containers\n      auto n_L = N_k - n_F;\n\n      // total load of clients associated to a pool of shared containers\n      auto lambda_L = lambda_k * n_L;\n\n      // number of shared stateless containers\n      assert(C_k > n_F);\n      auto C_L = C_k - n_F;\n\n      // average latency of clients with a dedicated container\n      double L_F = 1.0 / (mu_F - lambda_k);\n\n      // utilisation of dedicated containers\n      auto rho_F = lambda_k / mu_F;\n\n      // utilisation of the shared pool of containers\n      auto rho_L = lambda_L / (mu_L * C_L);\n\n      VLOG(1) << \"n_F = \" << n_F << \", n_L = \" << n_L << \", C_L \" << C_L\n              << \", mu_F = \" << mu_F << \", mu_L = \" << mu_L;\n\n      // check stability\n      if (rho_F >= 1.0 or rho_L >= 1.0) {\n        VLOG(1) << \"rho_F = \" << rho_F << \", rho_L = \" << rho_L\n                << \": system unstable\";\n        continue;\n      }\n\n      // average latency of clients associated to a pool of shared containers\n      auto L_L =\n          n_L > 0 ? (erlang_c(C_L, lambda_L / mu_L) / (mu_L * C_L - lambda_L) +\n                     inv_mu_L)\n                  : 0.0;\n\n      // average system latency\n      double L = (n_F * L_F + n_L * L_L) / N_k;\n\n      myOutfile << n_F << ' ' << L << '\\n';\n    }\n\n    return EXIT_SUCCESS;\n\n  } catch (const std::exception &aErr) {\n    LOG(ERROR) << \"Exception caught: \" << aErr.what();\n\n  } catch (...) {\n    LOG(ERROR) << \"Unknown exception caught\";\n  }\n\n  return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "df73cbd85049e9aa30d5fc33d627a96c1c583163", "size": 6330, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Executables/sfm-latency.cpp", "max_stars_repo_name": "ccicconetti/markovsim", "max_stars_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Executables/sfm-latency.cpp", "max_issues_repo_name": "ccicconetti/markovsim", "max_issues_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Executables/sfm-latency.cpp", "max_forks_repo_name": "ccicconetti/markovsim", "max_forks_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_forks_repo_licenses": ["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.1822660099, "max_line_length": 82, "alphanum_fraction": 0.6195892575, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5773307473405456}}
{"text": "#include <iostream>\nusing std::cout; using std::endl;\nusing std::left; using std::fixed; using std::right; using std::scientific;\n#include <iomanip>\nusing std::setw;\nusing std::setprecision;\n#include <limits>\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\nusing boost::multiprecision::cpp_dec_float_50;\n\n#include <boost/random.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/geometric.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nint main(int argc, const char* argv[])\n{\n    std::string fun(argv[1]);\n\n    int N = 200;\n    if (argc >= 4)\n    {\n        N = boost::lexical_cast<unsigned long>(argv[2]);\n    }\n\n    unsigned long S = 17;\n    if (argc >= 5)\n    {\n        S = boost::lexical_cast<unsigned long>(argv[3]);\n        std::cerr << S << endl;\n    }\n    boost::random::mt19937 rng(S);\n    boost::random::uniform_real_distribution<> runif;\n\n    std::cout.precision(std::numeric_limits<cpp_dec_float_50>::digits10);\n\n    if (fun == \"beta\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.01);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            unsigned long a = 1 + static_cast<unsigned long>(rexp(rng));\n            unsigned long b = 1 + static_cast<unsigned long>(rexp(rng));\n            cpp_dec_float_50 x = runif(rng);\n            boost::math::beta_distribution<cpp_dec_float_50> dst(a, b);\n            cout << \"- [\" << a << \", \" << b << \", \" << x\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, x)\n                               << \", \" << cdf(dst, x)\n                               << \", \" << cdf(complement(dst, x))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"binom\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.005);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 p = runif(rng);\n            unsigned long n = 1 + static_cast<unsigned long>(rexp(rng));\n            unsigned long k = static_cast<unsigned long>((n+1)*runif(rng));\n            boost::math::binomial_distribution<cpp_dec_float_50> dst(n, p);\n            cout << \"- [\" << n << \", \" << p << \", \" << k\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, k)\n                               << \", \" << cdf(dst, k)\n                               << \", \" << cdf(complement(dst, k))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"chisq\")\n    {\n        boost::random::exponential_distribution<double> rexp1(0.05);\n        boost::random::exponential_distribution<double> rexp2(0.01);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            unsigned long n = 1 + static_cast<unsigned long>(rexp1(rng));\n            cpp_dec_float_50 x = rexp2(rng);\n            boost::math::chi_squared_distribution<cpp_dec_float_50> dst(n);\n            cout << \"- [\" << n << \", \" << x\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, x)\n                               << \", \" << cdf(dst, x)\n                               << \", \" << cdf(complement(dst, x))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"gamma\")\n    {\n        boost::random::exponential_distribution<double> rexp1(0.05);\n        boost::random::exponential_distribution<double> rexp2(0.01);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 a = 1 + static_cast<unsigned long>(rexp1(rng));\n            cpp_dec_float_50 x = rexp2(rng);\n            boost::math::gamma_distribution<cpp_dec_float_50> dst(a);\n            cout << \"- [\" << a << \", \" << x\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, x)\n                               << \", \" << cdf(dst, x)\n                               << \", \" << cdf(complement(dst, x))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"geom\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.02);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 p = runif(rng);\n            unsigned long k = static_cast<unsigned long>(rexp(rng));\n            boost::math::geometric_distribution<cpp_dec_float_50> dst(p);\n            cout << \"- [\" << p << \", \" << k\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, k)\n                               << \", \" << cdf(dst, k)\n                               << \", \" << cdf(complement(dst, k))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"hyper\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.02);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            unsigned long M = 1 + static_cast<unsigned long>(rexp(rng));\n            unsigned long K = 1 + static_cast<unsigned long>(rexp(rng));\n            unsigned long N = M + K;\n            unsigned long n = static_cast<unsigned long>((N+1)*runif(rng));\n            unsigned long k = static_cast<unsigned long>((n+1)*runif(rng));\n            while (k > K || n - k > M) {\n                k = static_cast<unsigned long>((n+1)*runif(rng));\n            }\n            boost::math::hypergeometric_distribution<cpp_dec_float_50> dst(K, n, N);\n            cout << \"- [\" << N << \", \" << K << \", \" << n << \", \" << k\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, k)\n                               << \", \" << cdf(dst, k)\n                               << \", \" << cdf(complement(dst, k))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"norm\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.02);\n        boost::random::exponential_distribution<double> rexp2(0.005);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 mu = rexp(rng);\n            if (runif(rng) < 0.5) {\n                mu = -mu;\n            }\n            cpp_dec_float_50 sig = rexp(rng);\n            cpp_dec_float_50 x = rexp2(rng);\n            if (runif(rng) < 0.5) {\n                x = -x;\n            }\n            boost::math::normal_distribution<cpp_dec_float_50> dst(mu, sig);\n            cout << \"- [\" << mu << \", \" << sig << \", \" << x\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, x)\n                               << \", \" << cdf(dst, x)\n                               << \", \" << cdf(complement(dst, x))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"pois\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.02);\n        boost::random::exponential_distribution<double> rexp2(0.005);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 lam = rexp(rng);\n            unsigned long k = static_cast<unsigned int>(rexp(rng));\n            if (runif(rng) < 0.5)\n            {\n                k = static_cast<unsigned int>(rexp2(rng));\n            }\n            boost::math::poisson_distribution<cpp_dec_float_50> dst(lam);\n            cout << \"- [\" << lam << \", \" << k\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, k)\n                               << \", \" << cdf(dst, k)\n                               << \", \" << cdf(complement(dst, k))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n    if (fun == \"stud\")\n    {\n        boost::random::exponential_distribution<double> rexp(0.075);\n        boost::random::exponential_distribution<double> rexp2(0.005);\n\n        cout << \"seed: \" << S << endl;\n        cout << \"data:\" << endl;\n        for (int i = 0; i < N; ++i)\n        {\n            cpp_dec_float_50 nu = 2 + rexp(rng);\n            cpp_dec_float_50 x = static_cast<unsigned int>(rexp2(rng));\n            if (runif(rng) < 0.5)\n            {\n                x = -x;\n            }\n            boost::math::students_t_distribution<cpp_dec_float_50> dst(nu);\n            cout << \"- [\" << nu << \", \" << x\n                               << \", \" << mean(dst)\n                               << \", \" << variance(dst)\n                               << \", \" << pdf(dst, x)\n                               << \", \" << cdf(dst, x)\n                               << \", \" << cdf(complement(dst, x))\n                               << \"]\" << endl;\n        }\n        return 0;\n    }\n\n   return 1;\n}\n", "meta": {"hexsha": "af3b2d90ad9b75b61e7694fc20118738d31af1d4", "size": 10131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/gen_dist_test.cpp", "max_stars_repo_name": "drtconway/iid", "max_stars_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc/gen_dist_test.cpp", "max_issues_repo_name": "drtconway/iid", "max_issues_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/gen_dist_test.cpp", "max_forks_repo_name": "drtconway/iid", "max_forks_repo_head_hexsha": "c92a7c2c573a586d25d9eb5e940638de5eb03825", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1821428571, "max_line_length": 84, "alphanum_fraction": 0.4157536275, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5772459380389913}}
{"text": "/************************************************************\n *\n * Copyright (c) 2021, University of California, Los Angeles\n *\n * Authors: Kenny J. Chen, Brett T. Lopez\n * Contact: kennyjchen@ucla.edu, btlopez@ucla.edu\n *\n ***********************************************************/\n\n/***********************************************************************\n * BSD 3-Clause License\n * \n * Copyright (c) 2020, SMRT-AIST\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n * \n * 3. Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *************************************************************************/\n\n#ifndef NANO_GICP_SO3_HPP\n#define NANO_GICP_SO3_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace nano_gicp {\n\ninline Eigen::Matrix3f skew(const Eigen::Vector3f& x) {\n  Eigen::Matrix3f skew = Eigen::Matrix3f::Zero();\n  skew(0, 1) = -x[2];\n  skew(0, 2) = x[1];\n  skew(1, 0) = x[2];\n  skew(1, 2) = -x[0];\n  skew(2, 0) = -x[1];\n  skew(2, 1) = x[0];\n\n  return skew;\n}\n\ninline Eigen::Matrix3d skewd(const Eigen::Vector3d& x) {\n  Eigen::Matrix3d skew = Eigen::Matrix3d::Zero();\n  skew(0, 1) = -x[2];\n  skew(0, 2) = x[1];\n  skew(1, 0) = x[2];\n  skew(1, 2) = -x[0];\n  skew(2, 0) = -x[1];\n  skew(2, 1) = x[0];\n\n  return skew;\n}\n\n/*\n * SO3 expmap code taken from Sophus\n * https://github.com/strasdat/Sophus/blob/593db47500ea1a2de5f0e6579c86147991509c59/sophus/so3.hpp#L585\n *\n * Copyright 2011-2017 Hauke Strasdat\n *           2012-2017 Steven Lovegrove\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 */\ninline Eigen::Quaterniond so3_exp(const Eigen::Vector3d& omega) {\n  double theta_sq = omega.dot(omega);\n\n  double theta;\n  double imag_factor;\n  double real_factor;\n  if(theta_sq < 1e-10) {\n    theta = 0;\n    double theta_quad = theta_sq * theta_sq;\n    imag_factor = 0.5 - 1.0 / 48.0 * theta_sq + 1.0 / 3840.0 * theta_quad;\n    real_factor = 1.0 - 1.0 / 8.0 * theta_sq + 1.0 / 384.0 * theta_quad;\n  } else {\n    theta = std::sqrt(theta_sq);\n    double half_theta = 0.5 * theta;\n    imag_factor = std::sin(half_theta) / theta;\n    real_factor = std::cos(half_theta);\n  }\n\n  return Eigen::Quaterniond(real_factor, imag_factor * omega.x(), imag_factor * omega.y(), imag_factor * omega.z());\n}\n\n}  // namespace nano_gicp\n\n#endif", "meta": {"hexsha": "815ac07bd648b9e3e20de16c27ad7850ded286b5", "size": 4705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nano_gicp/gicp/so3.hpp", "max_stars_repo_name": "XiaoJake/direct_lidar_odometry", "max_stars_repo_head_hexsha": "14324cf875e238d35742166d8e1944597d4790f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 202.0, "max_stars_repo_stars_event_min_datetime": "2021-12-01T20:29:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:51:07.000Z", "max_issues_repo_path": "include/nano_gicp/gicp/so3.hpp", "max_issues_repo_name": "XiaoJake/direct_lidar_odometry", "max_issues_repo_head_hexsha": "14324cf875e238d35742166d8e1944597d4790f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-12-02T09:53:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T23:18:06.000Z", "max_forks_repo_path": "include/nano_gicp/gicp/so3.hpp", "max_forks_repo_name": "XiaoJake/direct_lidar_odometry", "max_forks_repo_head_hexsha": "14324cf875e238d35742166d8e1944597d4790f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T09:07:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T07:31:13.000Z", "avg_line_length": 38.5655737705, "max_line_length": 116, "alphanum_fraction": 0.6748140276, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5771956060260949}}
{"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\tboost::numeric::interval<int> range2(30, 120);\r\n\r\n\tboost::numeric::interval<int> new_range1 = range1 + range2;\r\n\r\n\tstd::cout << new_range1.lower() << \" ~ \"\r\n\t\t<< new_range1.upper() << std::endl;\r\n\r\n\r\n\tboost::numeric::interval<int> range3(10, 400);\r\n\trange3 += range2;\r\n\r\n\tstd::cout << range3.lower() << \" ~ \"\r\n\t\t<< range3.upper() << std::endl;\r\n\r\n\r\n\tboost::numeric::interval<int> range4(0, 100);\r\n\trange4 += 1;\r\n\r\n\tstd::cout << range4.lower() << \" ~ \"\r\n\t\t<< range4.upper() << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "071b3cb35857d97c26c2a37c6bc1a6dd048f1117", "size": 643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/interval_02/interval_02.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_02/interval_02.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_02/interval_02.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": 17.8611111111, "max_line_length": 61, "alphanum_fraction": 0.5800933126, "num_tokens": 187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5771561698701729}}
{"text": "#include <limits>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n\n// Epic kernel is enough, no constructions needed, provided the squared distance\n// fits into a double (!)\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n// we want to store an index with each vertex\ntypedef std::size_t                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Delaunay;\n\ntypedef std::tuple<Index,Index,K::FT> Edge;\ntypedef std::vector<Edge> EdgeV;\n\nint max_num_fam(std::vector<int> &comp_of_size, int k) {\n    // vector is size == k+1\n    int num = comp_of_size[k];\n    if(k == 4) {\n        // match 3 with ones, then take pairs of 2, match rest\n        int match_three_one = std::min(comp_of_size[3], comp_of_size[1]);\n        int remaining3 = comp_of_size[3] - match_three_one;\n        int remaining1 = comp_of_size[1] - match_three_one;\n        // add remaining size 3 to 2\n        int remaining2 = comp_of_size[2] + remaining3;\n        // if num2 is not divisible by two, we can possibly combine\n        // the one leftover with the single\n        if(remaining2 % 2 == 1) remaining1 += 2;\n        num += match_three_one + remaining2 / 2 + remaining1 / 4;\n        \n    } else if(k == 3) {\n        // match 2 with ones, add rest\n        int match_two_one = std::min(comp_of_size[2], comp_of_size[1]);\n        int remaining2 = comp_of_size[2] - match_two_one;\n        int remaining1 = comp_of_size[1] - match_two_one;\n        // the remaining 2size comp have to be div by 2 (two together is one family)\n        num += match_two_one + remaining2 / 2 + remaining1 / 3;\n    } else if(k == 2) {\n        // just take the single comp and divide by 2\n        num += comp_of_size[1] / 2;\n    }\n    return num;\n}\n\n\nvoid testcase() {\n    Index n, k, f0;\n    double s0;\n    std::cin >> n >> k >> f0 >> s0;\n\n    typedef std::pair<K::Point_2,Index> IPoint;\n    std::vector<IPoint> points;\n    points.reserve(n);\n    for (Index i = 0; i < n; ++i) {\n        int x, y;\n        std::cin >> x >> y;\n        points.emplace_back(K::Point_2(x, y), i);\n    }\n    Delaunay t;\n    t.insert(points.begin(), points.end());\n    EdgeV edges;\n    edges.reserve(3*n); // there can be no more in a planar graph\n    for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n        Index i1 = e->first->vertex((e->second+1)%3)->info();\n        Index i2 = e->first->vertex((e->second+2)%3)->info();\n        // ensure smaller index comes first\n        if (i1 > i2) std::swap(i1, i2);\n        edges.emplace_back(i1, i2, t.segment(e).squared_length());\n    }\n    std::sort(edges.begin(), edges.end(),\n            [](const Edge& e1, const Edge& e2) -> bool {\n            return std::get<2>(e1) < std::get<2>(e2);\n                });\n\n\n    // for testcases 1-2: just look at smallest distance, bc otherwise not enough tents\n    // std::cout << long(std::get<2>(edges[0])) << \" \";\n\n\n    boost::disjoint_sets_with_storage<> uf(n);\n    std::vector<Index> num_tents(n, 1);\n    Index n_components = n;\n    std::vector<int> comp_of_size(k + 1, 0);\n    comp_of_size[1] = n;\n    double last_dist = 0;\n    for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n        // determine components of endpoints\n        Index c1 = uf.find_set(std::get<0>(*e));\n        Index c2 = uf.find_set(std::get<1>(*e));\n        last_dist = std::get<2>(*e);\n        if (c1 != c2) {\n            Index n1 = num_tents[c1];\n            Index n2 = num_tents[c2];\n            uf.link(c1, c2);\n            Index c3 = uf.find_set(std::get<1>(*e));\n            // set unused indices to zero\n            num_tents[c1] = num_tents[c2] = 0;\n            // cap it at k\n            num_tents[c3] = std::min(n1 + n2, k);\n            comp_of_size[n1]--; comp_of_size[n2]--;\n            comp_of_size[num_tents[c3]]++;\n            if (max_num_fam(comp_of_size, k) < f0) break;\n        }\n    }\n    \n    std::cout << long(last_dist) << \" \";\n\n\n    // repeat process with adding edges < s0, then find max num families\n    boost::disjoint_sets_with_storage<> uf_s0(n);\n    num_tents = std::vector<Index>(n, 1);\n    comp_of_size = std::vector<int>(k + 1, 0);\n    comp_of_size[1] = n;\n\n    n_components = n;\n    for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n        // determine components of endpoints\n        Index c1 = uf_s0.find_set(std::get<0>(*e));\n        Index c2 = uf_s0.find_set(std::get<1>(*e));\n        double dist = std::get<2>(*e);\n        if(dist >= s0) {\n            break;\n        }\n        if (c1 != c2) {\n            Index n1 = num_tents[c1];\n            Index n2 = num_tents[c2];\n            uf_s0.link(c1, c2);\n            Index c3 = uf_s0.find_set(std::get<1>(*e));\n            // set unused indices to zero\n            num_tents[c1] = num_tents[c2] = 0;\n            // cap component size at k\n            num_tents[c3] = std::min(n1 + n2, k);\n            comp_of_size[n1]--; comp_of_size[n2]--;\n            comp_of_size[num_tents[c3]]++;\n            if (--n_components == 1) break;\n        }\n    }\n    std::cout << max_num_fam(comp_of_size, k) << 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": "1d9ff10a677a2d45f902a04bafc0e7c4d06de1ce", "size": 5778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week13-hand/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week13-hand/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week13-hand/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.6666666667, "max_line_length": 87, "alphanum_fraction": 0.5773624091, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5770440163794427}}
{"text": "// Compile with:\n// clang++ -o demoPriorDrawing3D demoPriorDrawing3D.cpp -L../build/ -I ../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register\n//\n\n#include <ctime>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n#include <unordered_set>\n#include <Eigen/Core>\n#include \"File.h\"\n#include \"EuclideanMetric.h\"\n#include \"KmeansClusterer.h\"\n#include \"Ellipsoid.h\"\n#include \"UniformPrior.h\"\n#include \"NormalPrior.h\"\n#include \"SuperGaussianPrior.h\"\n#include \"GridUniformPrior.h\"\n#include \"PrincipalComponentProjector.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint main()\n{\n    // ------ IDENTIFY CLUSTERS FROM INPUT SAMPLE ------\n    // Open the input file and read the data (synthetic sampling of a 2D parameter space)\n    \n    ifstream inputFile;\n    File::openInputFile(inputFile, \"onecluster3D.txt\");\n    unsigned long Nrows;\n    int Ncols;\n\n    File::sniffFile(inputFile, Nrows, Ncols);\n    ArrayXXd data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\n    ArrayXXd sample = data.transpose();\n    inputFile.close();\n\n\n    // Set up the K-means clusterer using a Euclidean metric\n\n    EuclideanMetric myMetric;\n    int minNclusters = 1;\n    int maxNclusters = 1;\n    int Ntrials = 10;\n    double relTolerance = 0.01;\n\n    bool printNdimensions = false;\n    PrincipalComponentProjector projector(printNdimensions);\n    bool featureProjectionActivated = true;\n\n    KmeansClusterer kmeans(myMetric, projector, featureProjectionActivated, \n                           minNclusters, maxNclusters, Ntrials, relTolerance); \n\n \n    // Do the clustering, and get for each point the index of the cluster it belongs to\n\n    int optimalNclusters;\n    vector<int> clusterIndices(Nrows);\n    vector<int> clusterSizes;\n\n    optimalNclusters = kmeans.cluster(sample, clusterIndices, clusterSizes);\n    int Nclusters = optimalNclusters; \n   \n\n    // Output the results \n    \n    cerr << \"Input number of clusters: 1\" << endl; \n    cerr << \"Optimal number of clusters: \" << optimalNclusters << endl;\n    \n\n    // ------ Compute Ellipsoids ------\n    \n    int Ndimensions = Ncols;\n    assert(sample.cols() == clusterIndices.size());\n    assert(sample.cols() >= Ndimensions + 1);            // At least Ndimensions + 1 points are required.\n\n\n    // The enlargement fraction (it is the fraction by which each axis of an ellipsoid is enlarged)\n\n    double enlargementFraction = 3.00;  \n    \n    \n    // Compute \"sorted indices\" such that clusterIndices[sortedindices[k]] <= clusterIndices[sortedIndices[k+1]]\n\n    vector<int> sortedIndices = Functions::argsort(clusterIndices);\n\n\n    // beginIndex will take values such that the indices for one particular cluster (# n) will be in \n    // sortedIndex[beginIndex, ..., beginIndex + clusterSize[n] - 1]      \n\n    int beginIndex = 0;\n\n\n    // Clear whatever was in the ellipsoids collection\n\n    vector<Ellipsoid> ellipsoids;\n    ellipsoids.clear();\n\n\n    // Create an Ellipsoid for each cluster (provided it's large enough)\n\n    for (int i = 0; i < Nclusters; i++)\n    {   \n        // Skip cluster if number of points is not large enough\n\n        if (clusterSizes[i] < Ndimensions + 1) \n        {\n            // Move the beginIndex up to the next cluster\n\n            beginIndex += clusterSizes[i];\n\n\n            // Continue with the next cluster\n\n            continue;\n        }\n        else\n        {\n            // The cluster is indeed large enough to compute an Ellipsoid.\n\n            // Copy those points that belong to the current cluster in a separate Array\n            // This is because Ellipsoid needs a contiguous array of points.\n\n            ArrayXXd sampleOfOneCluster(Ndimensions, clusterSizes[i]);\n\n            for (int n = 0; n < clusterSizes[i]; ++n)\n            {\n                sampleOfOneCluster.col(n) = sample.col(sortedIndices[beginIndex+n]);\n            }\n\n\n            // Move the beginIndex up to the next cluster\n\n            beginIndex += clusterSizes[i];\n\n\n            // Add ellipsoid at the end of our vector\n\n            ellipsoids.push_back(Ellipsoid(sampleOfOneCluster, enlargementFraction));\n        }\n    }\n\n    int Nellipsoids = ellipsoids.size();\n    cerr << \"Nellispids: \" << Nellipsoids << endl;\n   \n    \n    // Find which ellipsoids are overlapping and which are not\n    \n    vector<unordered_set<int>> overlappingEllipsoidsIndices;\n\n\n    // Remove whatever was in the container before\n\n    overlappingEllipsoidsIndices.clear();\n   \n\n    // Make sure that the indices container has the right size\n\n    overlappingEllipsoidsIndices.resize(ellipsoids.size());\n\n\n    // If Ellipsoid i overlaps with ellipsoid j, than of course ellipsoid j also overlaps with i.\n    // The indices are kept in an unordered_set<> which automatically takes care\n    // that there are no duplicates.  \n\n    bool ellipsoidMatrixDecompositionIsSuccessful;\n\n    for (int i = 0; i < Nellipsoids-1; ++i)\n    {\n        for (int j = i+1; j < Nellipsoids; ++j)\n        {\n            if (ellipsoids[i].overlapsWith(ellipsoids[j], ellipsoidMatrixDecompositionIsSuccessful))\n            {\n                overlappingEllipsoidsIndices[i].insert(j);\n                overlappingEllipsoidsIndices[j].insert(i);\n            }\n        }\n    }\n\n    mt19937 engine;\n    clock_t clockticks = clock();\n    engine.seed(clockticks);\n    uniform_real_distribution<> uniform(0.0, 1.0);  \n    \n\n    // Get the hyper-volume for each of the ellipsoids and normalize it \n    // to the sum of the hyper-volumes over all the ellipsoids\n\n    vector<double> normalizedHyperVolumes(Nellipsoids);\n    \n    for (int n=0; n < Nellipsoids; ++n)\n    {\n        normalizedHyperVolumes[n] = ellipsoids[n].getHyperVolume();\n    }\n\n    double sumOfHyperVolumes = accumulate(normalizedHyperVolumes.begin(), normalizedHyperVolumes.end(), 0.0, plus<double>());\n\n    cerr << \"Normalized Hyper-Volumes\" << endl;\n    ArrayXd centerCoordinate(2);\n    ArrayXXd covarianceMatrix(2,2);\n    \n    for (int n = 0; n < Nellipsoids; ++n)\n    {\n        normalizedHyperVolumes[n] /= sumOfHyperVolumes;\n        centerCoordinate = ellipsoids[n].getCenterCoordinates();\n        covarianceMatrix = ellipsoids[n].getCovarianceMatrix();\n        cerr << \"Ellipsoid #\" << n << \"   \" << normalizedHyperVolumes[n] << endl;\n        cerr << \"Center Coordinates: \" << centerCoordinate.transpose() << endl;\n        cerr << \"Covariance Matrix: \" << endl;\n        cerr << covarianceMatrix << endl;\n   \n        MatrixXd T1 = MatrixXd::Identity(Ndimensions+1,Ndimensions+1);\n        T1.bottomLeftCorner(1,Ndimensions) = (-1.0) * centerCoordinate.transpose();\n        MatrixXd A = MatrixXd::Zero(Ndimensions+1,Ndimensions+1);\n        A(Ndimensions,Ndimensions) = -1;\n        A.topLeftCorner(Ndimensions,Ndimensions) = covarianceMatrix.matrix().inverse();\n        MatrixXd AT = T1*A*T1.transpose();        // Translating to ellipsoid center\n     \n        //cerr << \"Ellipsoidal Matrix: \" << endl;\n        //cerr << AT << endl;\n        //cerr << endl;\n    }\n\n\n\n\n    // Pick an ellipsoid with a probability according to its normalized hyper-volume\n    // First generate a uniform random number between 0 and 1\n\n    double uniformNumber = uniform(engine);\n\n\n    // Select the ellipsoid that makes the cumulative hyper-volume greater than this random\n    // number. Those ellipsoids with a larger hyper-volume will have a greater probability to \n    // be chosen.\n\n    double cumulativeHyperVolume = normalizedHyperVolumes[0];\n    int indexOfSelectedEllipsoid = 0;\n    \n    while (cumulativeHyperVolume < uniformNumber)\n    {\n        indexOfSelectedEllipsoid++;\n        cumulativeHyperVolume += normalizedHyperVolumes[indexOfSelectedEllipsoid];\n    }\n\n    \n    cerr << \"Selected ellipsoid #: \" << indexOfSelectedEllipsoid << endl;\n    cerr << endl;\n\n\n\n    // ------ Set up prior distributions on each coordinate ------\n    \n    int Npoints = 10000;    \n    ArrayXXd sampleOfDrawnPoints(Npoints,Ndimensions);\n    ArrayXd drawnPoint(Ndimensions);\n   \n    /*      MIX PRIOR       UNIFORM-GRID UNIFORM-UNIFORM\n    vector<Prior*> ptrPriors(3);\n    ArrayXd parametersMinima(1);\n    ArrayXd parametersMaxima(1);\n    parametersMinima <<  0.0;\n    parametersMaxima << 4.0;\n    UniformPrior uniformPrior1(parametersMinima, parametersMaxima);\n    ptrPriors[0] = &uniformPrior1;  \n\n    ArrayXd parametersStartingCoordinate(1);\n    ArrayXd parametersNgridPoints(1);\n    ArrayXd parametersSeparation(1);\n    ArrayXd parametersTolerance(1);\n    parametersStartingCoordinate << 0.0;\n    parametersNgridPoints << 6;\n    parametersSeparation << 0.5;\n    parametersTolerance << 0.1;\n    GridUniformPrior gridUniformPrior(parametersStartingCoordinate, parametersNgridPoints, parametersSeparation, parametersTolerance);\n    ptrPriors[0] = &gridUniformPrior;  \n\n    parametersMinima <<  0.0;\n    parametersMaxima << 4.0;\n    UniformPrior uniformPrior2(parametersMinima, parametersMaxima);\n    ptrPriors[2] = &uniformPrior2;  \n    */\n\n    /*      MIX PRIOR       NORMAL-UNIFORM-NORMAL\n    vector<Prior*> ptrPriors(3);\n    ArrayXd parametersMean(1);\n    ArrayXd parametersSDV(1);\n    parametersMean <<  2.0;\n    parametersSDV << 0.4;\n    NormalPrior normalPrior1(parametersMean, parametersSDV);\n    ptrPriors[0] = &normalPrior1;  \n    \n    ArrayXd parametersMinima(1);\n    ArrayXd parametersMaxima(1);\n    parametersMinima <<  0.0;\n    parametersMaxima << 4.0;\n    UniformPrior uniformPrior(parametersMinima, parametersMaxima);\n    ptrPriors[1] = &uniformPrior;  \n\n    parametersMean <<  2.0;\n    parametersSDV << 0.4;\n    NormalPrior normalPrior2(parametersMean, parametersSDV);\n    ptrPriors[2] = &normalPrior2;  \n    */\n    \n    /*      UNIFORM PRIOR       */\n    vector<Prior*> ptrPriors(1);\n    ArrayXd parametersMinima(Ndimensions);\n    ArrayXd parametersMaxima(Ndimensions);\n    parametersMinima <<  0.0, 0.0, 0.0;\n    parametersMaxima << 4.0, 4.0, 4.0;\n    UniformPrior uniformPrior(parametersMinima, parametersMaxima);\n    ptrPriors[0] = &uniformPrior;  \n\n\n    /*      GAUSSIAN PRIOR\n    vector<Prior*> ptrPriors(1);\n    ArrayXd parametersMean(Ndimensions);\n    ArrayXd parametersSDV(Ndimensions);\n    parametersMean <<  2.0, 2.0, 2.0;\n    parametersSDV << 0.2, 0.4, 0.2;\n    NormalPrior normalPrior(parametersMean, parametersSDV);\n    ptrPriors[0] = &normalPrior;\n    */  \n    \n    /*      SUPER GAUSSIAN PRIOR\n    vector<Prior*> ptrPriors(1);\n    ArrayXd parametersMean(Ndimensions);\n    ArrayXd parametersSDV(Ndimensions);\n    ArrayXd parametersWOP(Ndimensions);\n    parametersMean <<  2.0, 2.0, 2.0;\n    parametersSDV << 0.1, 0.2, 0.3;\n    parametersWOP << 0.4, 0.4, 0.4;\n    SuperGaussianPrior superGaussianPrior(parametersMean, parametersSDV, parametersWOP);\n    ptrPriors[0] = &superGaussianPrior;  \n    */\n\n\n    // ------ Draw points from the Ellipsoid ------\n\n    for (int i=0; i < Npoints; ++i)\n    {\n        bool newPointIsFound = false;\n        \n        while (newPointIsFound == false)\n        {\n            // Draw a new point inside the ellipsoid\n            \n            ellipsoids[indexOfSelectedEllipsoid].drawPoint(drawnPoint);\n            \n            \n            // Check if the new point is also in other ellipsoids. If the point happens to be \n            // in N overlapping ellipsoids, then accept it only with a probability 1/N. If we\n            // wouldn't do this, the overlapping regions in the ellipsoids would be oversampled.\n\n            if (!overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].empty())\n            {\n                // There are overlaps, so count the number of ellipsoids to which the new\n                // point belongs\n            \n                int NenclosingEllipsoids = 1;\n\n                for (auto index = overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].begin();\n                          index != overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].end();\n                        ++index)\n                {\n                    if (ellipsoids[*index].containsPoint(drawnPoint))  \n                    {\n                        //NenclosingEllipsoids = static_cast<int>(DBL_MAX);       // No drawing from overlapping regions!\n                        //NenclosingEllipsoids++;\n                    }\n                }\n\n\n                // Only accept the new point with a probability = 1/NenclosingEllipsoids. \n                // If it's not accepted, go immediately back to the beginning of the while loop, \n                // and draw a new point inside the ellipsoid.\n\n                uniformNumber = uniform(engine);\n                newPointIsFound = (uniformNumber < 1./NenclosingEllipsoids);\n            }\n            else\n            {\n                // There are no ellipsoids overlapping with the selected one, so the point\n                // is automatically accepted\n\n                newPointIsFound = true;\n            }\n\n\n            // The point should not only be drawn inside the ellipsoid, it should also be drawn\n            // from the prior. Therefore, accept the point only with the probability given by the\n            // prior, so that the regions inside the ellipsoid with a higher prior density will \n            // be sampled more than the regions with a lower prior density. \n\n            \n            // Since different coordinates of our new point may have different priors, \n            // we need to check this for all the priors.\n        \n            int beginIndex = 0;\n\n            for (int priorIndex = 0; priorIndex < ptrPriors.size(); ++priorIndex)\n            {\n                // Figure out the number of parameters (=coordinates) that the current prior covers.\n\n                const int NdimensionsOfPrior = ptrPriors[priorIndex]->getNdimensions();\n\n\n                // Define a subset of the new point, consisting of those coordinates covered by the \n                // same (current) prior distribution.\n\n                ArrayXd subsetOfNewPoint = drawnPoint.segment(beginIndex, NdimensionsOfPrior);\n\n\n                // Check if the new point is accepted according to the corresponding prior distribution.\n             \n                newPointIsFound = ptrPriors[priorIndex]->drawnPointIsAccepted(subsetOfNewPoint);\n                \n                if (!newPointIsFound)\n                break;\n\n\n                // Move the beginIndex on to the next set of coordinates covered by the prior.\n\n                beginIndex += NdimensionsOfPrior;\n            }\n\n        }\n\n        sampleOfDrawnPoints.row(i) = drawnPoint.transpose();\n    }\n\n    ofstream outputFile;\n    File::openOutputFile(outputFile,\"priorDrawing3D.txt\");\n    File::arrayXXdToFile(outputFile, sampleOfDrawnPoints);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8acee3bb9ec479416761185f17b0725ba3c8f16d", "size": 14645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demoPriorDrawing3D.cpp", "max_stars_repo_name": "vishalbelsare/DIAMONDS", "max_stars_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/demoPriorDrawing3D.cpp", "max_issues_repo_name": "vishalbelsare/DIAMONDS", "max_issues_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/demoPriorDrawing3D.cpp", "max_forks_repo_name": "vishalbelsare/DIAMONDS", "max_forks_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0586907449, "max_line_length": 145, "alphanum_fraction": 0.6369409355, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.57703184710693}}
{"text": "/**\n * @file sophus_operators.hpp\n * @brief File with operators copied from sophus for SO(3).\n * @author Jianzhu Huai\n */\n\n#ifndef INCLUDE_OKVIS_KINEMATICS_SOPHUS_OPERATORS_HPP_\n#define INCLUDE_OKVIS_KINEMATICS_SOPHUS_OPERATORS_HPP_\n\n#include <stdint.h>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <okvis/kinematics/Transformation.hpp>\n#include <glog/logging.h>\n\n/// \\brief okvis Main namespace of this package.\nnamespace okvis {\n/// \\brief kinematics Namespace for kinematics functionality, i.e. transformations and stuff.\nnamespace kinematics {\n\ntemplate <typename Scalar>\nstruct SophusConstants {\n  EIGEN_ALWAYS_INLINE static Scalar epsilon() {\n    return static_cast<Scalar>(1e-10);\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar pi() { return static_cast<Scalar>(M_PI); }\n};\n\n// from sophus/so3.hpp\ntemplate <typename Scalar>\nEIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static Eigen::Matrix<Scalar, 3, 1> vee(\n    const Eigen::Matrix<Scalar, 3, 3>& Omega) {\n  return static_cast<Scalar>(0.5) *\n         Eigen::Matrix<Scalar, 3, 1>(Omega(2, 1) - Omega(1, 2),\n                                     Omega(0, 2) - Omega(2, 0),\n                                     Omega(1, 0) - Omega(0, 1));\n}\n\n/// Warn: Do not use sinc or its templated version for autodiff involving quaternions\n///  as its real part may be calculated without considering the infinisimal input.\n/// Use expAndTheta borrowed from Sophus instead for this purpose\ntemplate <typename Scalar>\nEigen::Quaternion<Scalar> expAndTheta(const Eigen::Matrix<Scalar, 3, 1> & omega) {\n    Scalar theta_sq = omega.squaredNorm();\n    Scalar theta = sqrt(theta_sq);\n    Scalar half_theta = static_cast<Scalar>(0.5)*(theta);\n\n    Scalar imag_factor;\n    Scalar real_factor;\n    if(theta<SophusConstants<Scalar>::epsilon()) {\n      Scalar theta_po4 = theta_sq*theta_sq;\n      imag_factor = static_cast<Scalar>(0.5)\n                    - static_cast<Scalar>(1.0/48.0)*theta_sq\n                    + static_cast<Scalar>(1.0/3840.0)*theta_po4;\n      real_factor = static_cast<Scalar>(1)\n                    - static_cast<Scalar>(0.5)*theta_sq +\n                    static_cast<Scalar>(1.0/384.0)*theta_po4;\n    } else {\n      Scalar sin_half_theta = sin(half_theta);\n      imag_factor = sin_half_theta/theta;\n      real_factor = cos(half_theta);\n    }\n\n    return Eigen::Quaternion<Scalar>(real_factor,\n                                               imag_factor*omega.x(),\n                                               imag_factor*omega.y(),\n                                               imag_factor*omega.z());\n}\n\n// From sophus so3.hpp\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, 3, 1> logAndTheta(const Eigen::Quaternion<Scalar> & other,\n                          Scalar * theta) {\n  Scalar squared_n\n      = other.vec().squaredNorm();\n  Scalar n = sqrt(squared_n);\n  Scalar w = other.w();\n\n  Scalar two_atan_nbyw_by_n;\n\n  // Atan-based log thanks to\n  //\n  // C. Hertzberg et al.:\n  // \"Integrating Generic Sensor Fusion Algorithms with Sound State\n  // Representation through Encapsulation of Manifolds\"\n  // Information Fusion, 2011\n\n  if (n < SophusConstants<Scalar>::epsilon()) {\n    // If quaternion is normalized and n=0, then w should be 1;\n    // w=0 should never happen here!\n    CHECK_GT(abs(w), SophusConstants<Scalar>::epsilon()) <<\n                  \"Quaternion should be normalized!\";\n    Scalar squared_w = w*w;\n    two_atan_nbyw_by_n = static_cast<Scalar>(2) / w\n                         - static_cast<Scalar>(2)*(squared_n)/(w*squared_w);\n  } else {\n    if (abs(w)<SophusConstants<Scalar>::epsilon()) {\n      if (w > static_cast<Scalar>(0)) {\n        two_atan_nbyw_by_n = M_PI/n;\n      } else {\n        two_atan_nbyw_by_n = -M_PI/n;\n      }\n    }else{\n      two_atan_nbyw_by_n = static_cast<Scalar>(2) * atan(n/w) / n;\n    }\n  }\n\n  *theta = two_atan_nbyw_by_n*n;\n\n  return two_atan_nbyw_by_n * other.vec();\n}\n/**\n * @brief ominus The inverse of Tbar = T.oplus(delta).\n * @param Tbar\n * @param T\n * @return delta\n */\ninline Eigen::Matrix<double, 6, 1> ominus(\n    const okvis::kinematics::Transformation& Tbar,\n    const okvis::kinematics::Transformation& T) {\n  Eigen::Matrix<double, 3, 3> dR = Tbar.C() * T.C().transpose();\n  Eigen::Matrix<double, 6, 1> delta;\n  delta.head<3>() = Tbar.r() - T.r();\n  delta.tail<3>() = vee(dR);\n  return delta;\n}\n\ninline bool motionLessThan(const okvis::kinematics::Transformation& Tab,\n                           double distanceThreshold, double angleThreshold) {\n  return Tab.r().norm() < distanceThreshold &&\n      std::fabs(Eigen::AngleAxisd(Tab.q()).angle()) < angleThreshold;\n}\n\n} // namespace kinematics\n} // namespace okvis\n\n#endif /* INCLUDE_OKVIS_KINEMATICS_SOPHUS_OPERATORS_HPP_ */\n", "meta": {"hexsha": "d8289afb9533efd029e5543173e3739528dcf190", "size": 4721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_kinematics/include/okvis/kinematics/sophus_operators.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_kinematics/include/okvis/kinematics/sophus_operators.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_kinematics/include/okvis/kinematics/sophus_operators.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 33.7214285714, "max_line_length": 93, "alphanum_fraction": 0.6396949799, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5770318193795786}}
{"text": "#include <algorithm>\n#include <cassert>\n#include <limits>\n#include <memory>\n#include <ostream>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"bsgs.hpp\"\n#include \"orbit.hpp\"\n#include \"perm.hpp\"\n#include \"perm_group.hpp\"\n#include \"perm_set.hpp\"\n#include \"util.hpp\"\n\nnamespace mpsym\n{\n\nnamespace internal\n{\n\nPermGroup::PermGroup(unsigned degree, PermSet const &generators)\n{\n  _bsgs = BSGS(degree, generators);\n  _order = _bsgs.order();\n}\n\nbool PermGroup::operator==(PermGroup const &rhs) const\n{\n  assert(rhs.degree() == degree()\n         && \"comparing permutation groups of equal degree\");\n\n  if (_order != rhs.order())\n    return false;\n\n  for (Perm const &gen : rhs.generators()) {\n    if (!contains_element(gen))\n      return false;\n  }\n\n  return true;\n}\n\nbool PermGroup::operator!=(PermGroup const &rhs) const\n{\n  return !(*this == rhs);\n}\n\nPermGroup PermGroup::symmetric(unsigned degree)\n{\n  // TODO: explicit BSGS\n\n  assert(degree > 0u);\n\n  if (degree == 1u)\n    return PermGroup(1u, {Perm(1u)});\n\n  std::vector<unsigned> gen;\n  for (unsigned i = 0u; i < degree; ++i)\n    gen.push_back(i);\n\n  return PermGroup(degree, {Perm(degree, {{0, 1}}), Perm(degree, {gen})});\n}\n\nPermGroup PermGroup::cyclic(unsigned degree)\n{\n  // TODO: explicit BSGS\n\n  assert(degree > 0u);\n\n  std::vector<unsigned> gen;\n  for (unsigned i = 0u; i < degree; ++i)\n    gen.push_back(i);\n\n  return PermGroup(degree, {Perm(degree, {gen})});\n}\n\nPermGroup PermGroup::dihedral(unsigned degree)\n{\n  // TODO: explicit BSGS\n\n  assert(degree > 0u && degree % 2 == 0);\n\n  if (degree == 2u)\n    return PermGroup(2, {Perm({1, 0})});\n\n  if (degree == 4u)\n    return PermGroup(4, {Perm({1, 0, 2, 3}), Perm({0, 1, 3, 2})});\n\n  std::vector<unsigned> rotation(degree / 2u);\n\n  // rotation\n  for (unsigned i = 0u; i < degree / 2u - 1u; ++i)\n    rotation[i] = i + 1u;\n\n  rotation[degree / 2u - 1u] = 0u;\n\n  // reflection\n  std::vector<unsigned> reflection(degree / 2u);\n\n  reflection[0] = 0u;\n\n  for (unsigned i = 1u; i < (degree / 2u + 1u) / 2u; ++i) {\n    reflection[i] = degree / 2u - i;\n    reflection[degree / 2u - i] = i;\n  }\n\n  if ((degree / 2u) % 2 == 0)\n    reflection[degree / 4u] = degree / 4u;\n\n  return PermGroup(degree / 2u, {Perm(rotation), Perm(reflection)});\n}\n\nPermSet PermGroup::wreath_product_generators(PermGroup const &lhs,\n                                             PermGroup const &rhs)\n{\n  unsigned wp_degree = lhs.degree() * rhs.degree();\n\n  auto lhs_gens(lhs.generators());\n  auto rhs_gens(rhs.generators());\n\n  PermSet wp_generators;\n\n  if (lhs.is_trivial() && rhs.is_trivial()) {\n    return {};\n\n  } else if (rhs.is_trivial()) {\n    wp_generators.resize(lhs_gens.size(), Perm(wp_degree));\n\n    for (unsigned i = 0u; i < rhs.degree(); ++i) {\n      for (auto j = 0u; j < lhs_gens.size(); ++j)\n        wp_generators[j] *= lhs_gens[j].shifted(lhs.degree() * i).extended(wp_degree);\n    }\n\n  } else {\n    for (unsigned i = 0u; i < rhs.degree(); ++i) {\n      for (Perm const &perm : lhs_gens)\n        wp_generators.insert(perm.shifted(lhs.degree() * i).extended(wp_degree));\n    }\n\n    for (Perm const &gen : rhs_gens) {\n      std::vector<std::vector<unsigned>> cycles {gen.cycles()};\n      for (auto &cycle : cycles) {\n        for (unsigned &x : cycle)\n          x = x * lhs.degree();\n      }\n\n      std::vector<std::vector<unsigned>> shifted_cycles {cycles};\n\n      for (unsigned i = 1u; i < lhs.degree(); ++i) {\n        for (auto const &cycle : cycles) {\n          std::vector<unsigned> shifted_cycle(cycle);\n\n          for (unsigned &x : shifted_cycle)\n            x += i;\n\n          shifted_cycles.push_back(shifted_cycle);\n        }\n      }\n\n      wp_generators.emplace(wp_degree, shifted_cycles);\n    }\n  }\n\n  return wp_generators;\n}\n\nPermGroup PermGroup::wreath_product(PermGroup const &lhs,\n                                    PermGroup const &rhs,\n                                    BSGSOptions const *bsgs_options_,\n                                    timeout::flag aborted)\n{\n  // degree of wreath product\n  unsigned wp_degree = lhs.degree() * rhs.degree();\n\n  // generators of wreath product\n  auto wp_generators(wreath_product_generators(lhs, rhs));\n\n  if (wp_generators.empty())\n    return PermGroup(wp_degree);\n\n  // order of wreath product\n  auto wp_order(wreath_product_order(lhs, rhs));\n\n  // construct wreath product\n  auto bsgs_options(BSGSOptions::fill_defaults(bsgs_options_));\n  bsgs_options.schreier_sims_random_known_order = wp_order;\n\n  return PermGroup(BSGS(wp_degree, wp_generators, &bsgs_options, aborted));\n}\n\nBSGS::order_type PermGroup::wreath_product_order(PermGroup const &lhs,\n                                                 PermGroup const &rhs)\n{\n  using boost::multiprecision::pow;\n\n  auto lhs_order(lhs.order());\n  auto rhs_order(rhs.order());\n\n  if (lhs.is_trivial())\n    return rhs_order;\n\n  if (rhs.is_trivial())\n    return lhs_order;\n\n  return pow(lhs_order, rhs.degree()) * rhs_order;\n}\n\nbool PermGroup::is_symmetric() const\n{\n  if (_bsgs.is_symmetric() || degree() == 1u)\n    return true;\n\n  return _order == symmetric_order(degree());\n}\n\nbool PermGroup::is_shifted_symmetric() const\n{\n  unsigned degree_ = largest_moved_point() - smallest_moved_point() + 1u;\n\n  return _order == symmetric_order(degree_);\n}\n\nbool PermGroup::is_transitive() const\n{\n  auto orbit(Orbit::generate(0u, generators().with_inverses()));\n\n  return orbit.size() == degree();\n}\n\nbool PermGroup::contains_element(Perm const &perm) const\n{\n  assert(perm.degree() == degree() && \"element has same degree as group\");\n\n  return _bsgs.strips_completely(perm);\n}\n\nPerm PermGroup::random_element() const\n{\n  static auto re(util::random_engine());\n\n  Perm result(degree());\n  for (unsigned i = 0u; i < _bsgs.base_size(); ++i) {\n    auto orbit(_bsgs.orbit(i));\n\n    std::uniform_int_distribution<> d(0u, orbit.size() - 1u);\n\n    result *= _bsgs.transversal(i, *(orbit.begin() + d(re)));\n  }\n\n  return result;\n}\n\nPermGroup::const_iterator::const_iterator(PermGroup const &pg)\n  : _trivial(pg.bsgs().base_empty()),\n    _end(false)\n{\n  if (_trivial) {\n    _current = Perm(pg.degree());\n\n    _current_valid = true;\n\n  } else {\n    for (unsigned i = 0u; i < pg.bsgs().base_size(); ++i) {\n      _state.push_back(0u);\n\n      auto transv = pg.bsgs().transversals(i);\n\n      _transversals.push_back(transv);\n      _current_factors.insert(transv[0]);\n    }\n\n    _current_valid = false;\n  }\n}\n\nbool PermGroup::const_iterator::operator==(PermGroup::const_iterator const &rhs) const\n{\n  if (_end != rhs._end)\n    return false;\n\n  if (_end && rhs._end)\n    return true;\n\n  for (unsigned i = 0u; i < _state.size(); ++i) {\n    if (_state[i] != rhs._state[i])\n      return false;\n  }\n\n  return true;\n}\n\nPermGroup::const_iterator::reference PermGroup::const_iterator::current()\n{\n  if (_current_valid)\n    return _current;\n\n  _current = _current_factors[0];\n  for (unsigned j = 1u; j < _current_factors.size(); ++j)\n    _current = _current_factors[j] * _current;\n\n  _current_valid = true;\n\n  return _current;\n}\n\nvoid PermGroup::const_iterator::next()\n{\n  if (_trivial) {\n    _end = true;\n    return;\n  }\n\n  for (unsigned i = 0u; i < _state.size(); ++i) {\n    _state[i]++;\n    if (_state[i] == _transversals[i].size())\n      _state[i] = 0u;\n\n    _current_factors[i] = _transversals[i][_state[i]];\n\n    if (i == _state.size() - 1u && _state[i] == 0u) {\n      _end = true;\n      break;\n    }\n\n    if (_state[i] != 0u)\n      break;\n  }\n\n  _current_valid = false;\n}\n\nstd::ostream &operator<<(std::ostream &os, PermGroup const &pg)\n{\n  os << pg.bsgs() << \"\\n\"\n     << \"ORDER: \" << pg._order;\n\n  return os;\n}\n\n} // namespace internal\n\n} // namespace mpsym\n", "meta": {"hexsha": "b87a9255da54b71db22dbf9b7135b4fcd29e66e8", "size": 7690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/perm_group.cpp", "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": "source/perm_group.cpp", "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": "source/perm_group.cpp", "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": 22.1613832853, "max_line_length": 86, "alphanum_fraction": 0.62236671, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.5769460394627477}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef KRAW_APPROX_HPP\n#define KRAW_APPROX_HPP\n\n// Krawczyk method using approximate solution\n// Newton iteration can be applied in advance.\n\n#include <limits>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/autodif.hpp>\n#include <kv/matrix-inversion.hpp>\n#include <kv/make-candidate.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T, class F>\nbool\nkrawczyk_approx(F f, const ub::vector<T>& c, ub::vector< interval<T> >& result, int newton_max = 2, int verbose = 1)\n{\n\tint s = c.size();\n\n\tub::vector< interval<T> > I, fc, fi, Rfc, C, K;\n\tub::matrix< interval<T> > fdc, fdi, M;\n\tub::vector<T> c2, minus;\n\tub::matrix<T> R;\n\tint i, j;\n\tbool r;\n\tub::vector<T> newton_step;\n\tT tmp, tmp2;\n\n\tc2 = c;\n\n\t// Newton iteration\n\t// use interval<T> for argument of f\n\t// preparing for the case that f can not accept T.\n\n\tfor (i=0; i<newton_max; i++) {\n\t\tC = c2;\n\t\ttry {\n\t\t\tautodif< interval<T> >::split(f(autodif< interval<T> >::init(C)), fc, fdc);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\treturn false;\n\t\t}\n\t\tr = invert(mid(fdc), R);\n\t\tif (!r) return false;\n\n\t\tminus = prod(R, mid(fc));\n\n\t\ttmp = 1.;\n\t\ttmp2 = 0.;\n\t\tfor (j=0; j<s; j++) {\n\t\t\tusing std::abs;\n\t\t\ttmp = std::max(tmp, abs(c2(j)));\n\t\t\ttmp2 = std::max(tmp2, abs(minus(j)));\n\t\t}\n\n\t\tc2 = c2 - minus;\n\t\tif (verbose >= 1) {\n\t\t\tstd::cout << \"newton\" << i << \": \" << c2 << \"\\n\";\n\t\t}\n\t\tif (tmp2 <= tmp * std::numeric_limits<T>::epsilon()) break;\n\t}\n\n\tC = c2;\n\ttry {\n\t\tautodif< interval<T> >::split(f(autodif< interval<T> >::init(C)), fc, fdc);\n\t}\n\tcatch (std::domain_error& e) {\n\t\treturn false;\n\t}\n\tr = invert(mid(fdc), R);\n\tif (!r) return false;\n\tRfc = prod(R, fc);\n\n\tnewton_step.resize(s);\n\tfor (i=0; i<s; i++) {\n\t\tnewton_step(i) = norm(Rfc(i));\n\t}\n\n\tmake_candidate(newton_step);\n\n\tI = C;\n\tfor (i=0; i<s; i++) {\n\t\ttmp = std::numeric_limits<T>::epsilon() * norm(I(i)) * (s+1) * 2;\n\t\ttmp2 = std::numeric_limits<T>::min() * (s+1) * 2;\n\t\tif (newton_step(i) < tmp) newton_step(i) = tmp;\n\t\tif (newton_step(i) < tmp2) newton_step(i) = tmp2;\n\t\tI(i) += newton_step(i) * interval<T>(-1., 1.);\n\t}\n\n\tif (verbose >= 1) {\n\t\tstd::cout << \"I: \" << I << \"\\n\";\n\t}\n\n\ttry {\n\t\tautodif< interval<T> >::split(f(autodif< interval<T> >::init(I)), fi, fdi);\n\t}\n\tcatch (std::domain_error& e) {\n\t\treturn false;\n\t}\n\n\t// M = ub::identity_matrix< interval<T> >(s) - prod(R, fdi);\n\tM = ub::identity_matrix< interval<T> >(s);\n\tM -= prod(R, fdi);\n\n\tK = C - Rfc +  prod(M, I - C);\n\n\tif (verbose >= 1) {\n\t\tstd::cout << \"K: \" << K << \"\\n\";\n\t}\n\n\tif (proper_subset(K, I)) {\n\t\tresult = K;\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\nnamespace krawczyk_approx_sub {\n\n// generate 1-d vector function from scalar function\ntemplate <class F>\nstruct MakeVec {\n\tF f;\n\tMakeVec(F f): f(f) {}\n\n\ttemplate <class T> ub::vector<T> operator()(const ub::vector<T>& x) {\n\t\tub::vector<T> r(1);\n\t\tr(0) = f(x(0));\n\t\treturn r;\n\t}\n};\n\n} // namespace krawczyk_approx_sub;\n\n\n// 1 dimensional version\n\ntemplate <class T, class F>\nbool\nkrawczyk_approx(F f, const T& c, interval<T>& result, int newton_max = 2, int verbose = 1)\n{\n\tub::vector<T> in(1);\n\tub::vector< interval<T> > out;\n\tkrawczyk_approx_sub::MakeVec<F> g(f);\n\tbool r;\n\n\tin(0) = c;\n\tr = krawczyk_approx(g, in, out, newton_max, verbose);\n\tif (!r) return r;\n\tresult = out(0);\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // KRAW_APPROX_HPP\n", "meta": {"hexsha": "6b67f08e2f05c02a89b2e611ee3c0e00dca05844", "size": 3552, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/kraw-approx.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/kraw-approx.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/kraw-approx.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": 20.6511627907, "max_line_length": 116, "alphanum_fraction": 0.6038851351, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.5769460229500213}}
{"text": "#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Polyhedron_3.h>\n\n#include <CGAL/Surface_mesh_parameterization/IO/File_off.h>\n#include <CGAL/Surface_mesh_parameterization/Square_border_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Discrete_conformal_map_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/parameterize.h>\n\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/Unique_hash_map.h>\n\n#include <boost/array.hpp>\n\n#include <unordered_set>\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::Polyhedron_3<Kernel>                               PolyMesh;\n\ntypedef boost::graph_traits<PolyMesh>::halfedge_descriptor       halfedge_descriptor;\ntypedef boost::graph_traits<PolyMesh>::vertex_descriptor         vertex_descriptor;\ntypedef boost::graph_traits<PolyMesh>::face_descriptor           face_descriptor;\n\ntypedef boost::graph_traits<PolyMesh>::vertex_iterator           vertex_iterator;\n\ntypedef boost::array<vertex_descriptor, 4>                       Vd_array;\n\ntypedef CGAL::Unique_hash_map<vertex_descriptor, Point_2>        UV_uhm;\ntypedef boost::associative_property_map<UV_uhm>                  UV_pmap;\n\nnamespace SMP = CGAL::Surface_mesh_parameterization;\n\nbool read_vertices(const PolyMesh& mesh,\n                   const char* filename,\n                   Vd_array& fixed_vertices)\n{\n  std::string str = filename;\n  if( (str.length()) < 14 || (str.substr(str.length() - 14) != \".selection.txt\") ) {\n    std::cerr << \"Error: vertices must be given by a *.selection.txt file\" << std::endl;\n    return false;\n  }\n\n  std::ifstream in(filename);\n  std::string line;\n  if(!std::getline(in, line)) {\n    std::cerr << \"Error: could not read input file: \" << filename << std::endl;\n    return false;\n  }\n\n  // The selection file is a list of integers, so we must build a correspondence\n  // between vertices and the integers.\n  std::vector<vertex_descriptor> vds;\n  vds.reserve(num_vertices(mesh));\n  vertex_iterator vi = vertices(mesh).begin(), vi_end = vertices(mesh).end();\n  CGAL_For_all(vi, vi_end) {\n    vds.push_back(*vi);\n  }\n\n  // Get the first line and read the fixed vertex indices\n  std::size_t counter = 0;\n  std::istringstream point_line(line);\n  std::size_t s;\n  std::unordered_set<std::size_t> indices;\n  while(point_line >> s) {\n    if(s >= vds.size())\n    {\n      std::cerr << \"Error: Vertex index too large\" << std::endl;\n      return false;\n    }\n\n    vertex_descriptor vd = vds[s];\n    if(!is_border(vd, mesh)) { // must be on the border\n      std::cerr << \"Error: vertex is not on the border of the mesh\" << std::endl;\n      return false;\n    }\n\n    if(counter >= 4) { // too many border vertices\n      std::cerr << \"Error: Too many vertices are fixed\" << std::endl;\n      return false;\n    }\n\n    fixed_vertices[counter++] = vd;\n    indices.insert(s);\n  }\n\n  if(indices.size() < 4) {\n    std::cerr << \"Error: at least four unique vertices must be provided\" << std::endl;\n    return false;\n  }\n\n  return true;\n}\n\nint main(int argc, char** argv)\n{\n  std::ifstream in((argc>1) ? argv[1] : CGAL::data_file_path(\"meshes/nefertiti.off\"));\n  if(!in){\n    std::cerr << \"Error: problem loading the input data\" << std::endl;\n    return 1;\n  }\n\n  PolyMesh sm;\n  in >> sm;\n\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  UV_uhm uv_uhm;\n  UV_pmap uv_map(uv_uhm);\n\n  const char* filename = (argc > 2) ? argv[2] : \"data/square_corners.selection.txt\";\n  Vd_array vda;\n  if(!read_vertices(sm, filename, vda)) {\n    std::cerr << \"Error: problem loading the square corners\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  typedef SMP::Square_border_uniform_parameterizer_3<PolyMesh> Border_parameterizer;\n  typedef SMP::Discrete_conformal_map_parameterizer_3<PolyMesh, Border_parameterizer> Parameterizer;\n\n  // Border parameterizers (pick one)\n  Border_parameterizer border_param(vda[0], vda[1], vda[2], vda[3]);\n//  Border_parameterizer border_param; // the border parameterizer will compute the corner vertices\n\n  SMP::Error_code err = SMP::parameterize(sm, Parameterizer(border_param), 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 EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5784d3a1fdb902e4efef035713d86e41d29977a4", "size": 4651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_parameterization/examples/Surface_mesh_parameterization/square_border_parameterizer.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": "Surface_mesh_parameterization/examples/Surface_mesh_parameterization/square_border_parameterizer.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": "Surface_mesh_parameterization/examples/Surface_mesh_parameterization/square_border_parameterizer.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": 32.7535211268, "max_line_length": 100, "alphanum_fraction": 0.672543539, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094303, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5769347619949197}}
{"text": "#include <iostream>\n\n#pragma GCC diagnostic ignored \"-Wparentheses\"\n#pragma GCC optimize (\"rtti\")\n\n#include <boost/units/systems/si.hpp>\n#include <boost/units/systems/cgs/length.hpp>\n#include <boost/units/io.hpp>\n\nconst auto meter = 1.0 * boost::units::si::meter;\nconst auto s     = 1.0 * boost::units::si::second;\n\nvoid print( decltype( meter / s ) v ){\n    std::cout << \"velocity = \" << v << \"\\n\";\n}\n\nint main(){\n\n   auto gravity = 10.0 * meter / ( s * s );\n   auto duration = 2.0 * s;\n   \n   print( gravity * duration );\n\n}\n", "meta": {"hexsha": "d5af8ec1f9f8319653023cb8edcb5f1c71a77195", "size": 527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hwlib/demo/native/native-#0040-units/main.cpp", "max_stars_repo_name": "TheBlindMick/MPU6050", "max_stars_repo_head_hexsha": "66880369fa7a73755846e60568137dfc07da1b5c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T14:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T14:25:57.000Z", "max_issues_repo_path": "hwlib/demo/native/native-#0040-units/main.cpp", "max_issues_repo_name": "TheBlindMick/MPU6050", "max_issues_repo_head_hexsha": "66880369fa7a73755846e60568137dfc07da1b5c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2017-02-15T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-28T15:29:01.000Z", "max_forks_repo_path": "hwlib/demo/native/native-#0040-units/main.cpp", "max_forks_repo_name": "TheBlindMick/MPU6050", "max_forks_repo_head_hexsha": "66880369fa7a73755846e60568137dfc07da1b5c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2017-05-18T11:51:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:07:01.000Z", "avg_line_length": 21.08, "max_line_length": 50, "alphanum_fraction": 0.6223908918, "num_tokens": 153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5769347527752471}}
{"text": "/*\nCopyright (C) 2012 Mathias Eitz and Ronald Richter.\nAll rights reserved.\n\nThis file is part of the imdb library and is made available under\nthe terms of the BSD license (see the LICENSE file).\n*/\n\n#ifndef DESCRIPTORS__GIST_HELPER_HPP\n#define DESCRIPTORS__GIST_HELPER_HPP\n\n#include <complex>\n#include <cstddef>\n#include <cmath>\n#include <algorithm>\n\n#include <boost/static_assert.hpp>\n#include <opencv2/core/core.hpp>\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n\n\ntemplate <class T>\nvoid fftshift_even(const cv::Mat_<T>& src, cv::Mat_<T>& dst)\n{\n    assert(src.isContinuous() && dst.isContinuous());\n\n    //assert that size is even!!!\n\n    dst.create(src.size());\n\n    const int w = src.size().width;\n    const int h = src.size().height;\n    const int hw = w / 2;\n    const int hh = h / 2;\n\n    for (int y = 0; y < hh; y++)\n    {\n        // src[i] gives the ith row with the T datatype\n        std::copy(src[y], src[y] + hw, dst[y + hh] + hw); // copy tl quadrant to br quadrant\n        std::copy(src[y] + hw, src[y] + w, dst[y + hh]);      // copy tr quadrant to bl quadrant\n    }\n\n    for (int y = hh; y < h; y++)\n    {\n        std::copy(src[y], src[y] + hw, dst[y - hh] + hw); // copy bl quadrant to tr quadrant\n        std::copy(src[y] + hw, src[y] + w, dst[y - hh]);      // copy br quadrant to tl quadrant\n    }\n}\n\n\n\n\n\ntemplate <class T>\nvoid generate_gaussian_filter(cv::Mat_<T>& image, double sigma)\n{\n    const int w = image.size().width;\n    const int h = image.size().height;\n    const int wh = w / 2;\n    const int hh = h / 2;\n\n    const double s = 1.0 / (sigma*sigma);\n\n    for (int y = -hh; y < hh; y++)\n    {\n        size_t yy = (y + h) % h;\n        for (int x = -wh; x < wh; x++)\n        {\n            size_t xx = (x + w) % w;\n            double fx = x;\n            double fy = y;\n            image(yy, xx) = std::exp(-(fx*fx + fy*fy) * s);\n        }\n    }\n}\n\nclass torralba_prefilter\n{\n    typedef std::complex<float> complex_t;\n\n    double      _sigma;\n    cv::Size    _size;\n    cv::Mat_<complex_t> _filter;\n\n    public:\n\n    torralba_prefilter(std::size_t width, std::size_t height, double cycles = 4.0)\n     : _sigma(cycles / std::sqrt(std::log(2.0)))\n     , _size(width, height)\n     , _filter(_size)\n    {\n        generate_gaussian_filter(_filter, _sigma);\n    }\n\n    void operator() (cv::Mat& img)\n    {\n        assert(img.type() == CV_8UC1 && img.size().width == _size.width && img.size().height == _size.height);\n\n        // \"whitening\"\n        cv::Mat_<float> logimg;\n        img.convertTo(logimg, CV_32FC1);\n        cv::log(1.0 + logimg, logimg);\n\n        cv::Mat_<complex_t> spbuf(_size);\n        std::copy(logimg.begin(), logimg.end(), spbuf.begin());\n\n        cv::Mat_<complex_t> frbuf;\n        cv::dft(spbuf, frbuf);\n\n        cv::mulSpectrums(frbuf, 1.0 - _filter, frbuf, 0);\n\n        cv::Mat_<complex_t> white;\n        cv::idft(frbuf, white, cv::DFT_SCALE);\n\n        // \"local contrast normalization\"\n        cv::MatIterator_<complex_t> dit = spbuf.begin();\n        for (cv::MatConstIterator_<complex_t> it = white.begin(); it != white.end(); ++it, ++dit)\n        {\n            const complex_t& v = *it;\n            *dit = v.real() * v.real();\n        }\n\n        cv::dft(spbuf, frbuf);\n        cv::mulSpectrums(frbuf, _filter, frbuf, 0);\n        cv::idft(frbuf, spbuf, cv::DFT_SCALE);\n\n        cv::MatIterator_<unsigned char> dst = img.begin<unsigned char>();\n        cv::MatConstIterator_<complex_t> wit = white.begin();\n        for (cv::MatConstIterator_<complex_t> it = spbuf.begin(); it != spbuf.end(); ++it, ++wit, ++dst)\n        {\n            float d = std::sqrt(std::abs((*it).real())) + 0.2;\n            float v = std::min(255 * std::max((*wit).real(), 0.0f) / d, 255.0f);\n            *dst = v;\n        }\n    }\n};\n\ntemplate <class T>\nvoid generate_gabor_filter(cv::Mat_<T>& image, double peakFreq, double deltaFreq, double orientAngle, double deltaAngle)\n{\n    const double C = std::sqrt(log(2.0) / M_PI);\n\n    const double Ka = (deltaFreq - 1.0) / (deltaFreq + 1.0);\n    const double Kb = std::tan(0.5 * deltaAngle);\n    //const double lambda = Ka / Kb;\n\n    // scaling factors of the gaussian envelope\n    const double a = peakFreq * (Ka / C);\n    //const double b = a / lambda;\n    const double b = Kb * peakFreq/C * std::sqrt(1.0 - Ka*Ka);\n\n    // spatial frequency in cartesian coordinates\n    const double u0 = peakFreq * std::cos(orientAngle);\n    const double v0 = peakFreq * std::sin(orientAngle);\n\n    // default: set orientation of gaussian envelope (theta) equal to orientation of filter\n    const double theta = orientAngle;\n\n    // generate filter\n    const size_t w = image.size().width;\n    const size_t h = image.size().height;\n    const double stepx = 1.0 / static_cast<double>(w);\n    const double stepy = 1.0 / static_cast<double>(h);\n    const double cos_theta = std::cos(theta);\n    const double sin_theta = std::sin(theta);\n    double v = 0.5 - v0;\n\n    for (size_t yy = 0; yy < h; yy++)\n    {\n        size_t y = (yy + (h / 2)) % h;\n        double u = -0.5 - u0;\n        for (size_t xx = 0; xx < w; xx++)\n        {\n            size_t x = (xx + (w / 2)) % w;\n\n            double ur = u * cos_theta + v * sin_theta;\n            double vr = -u * sin_theta + v * cos_theta;\n\n            double U = ur / a;\n            double V = vr / b;\n\n            double value = std::exp(-M_PI * (U*U + V*V));\n\n            image(y, x) = value;\n\n            u += stepx;\n        }\n\n        v -= stepy;\n    }\n}\n\ntemplate <class T>\nvoid generate_polargabor_filter(cv::Mat_<T>& image, double peakFreq, double deltaFreq, double orientAngle, double deltaAngle)\n{\n    // sigma_omega = 1 / (kappa * omega)\n    double kappa = (deltaFreq - 1) / ((deltaFreq + 1) * std::sqrt(2*std::log(2.0)));\n\n//    double sigma_theta = std::sqrt(2*PI)*4.0*numorients/32.0; // torralba\n    double sigma_theta = std::sqrt(std::log(2.0)) * 2.0 / deltaAngle;\n\n    // generate filter\n    const size_t w = image.size().width;\n    const size_t h = image.size().height;\n    const double stepx = 1.0 / static_cast<double>(w);\n    const double stepy = 1.0 / static_cast<double>(h);\n\n    double v = -0.5;\n    for (size_t yy = 0; yy < h; yy++)\n    {\n        size_t y = (yy + (h / 2)) % h;\n\n        double u = -0.5;\n        for (size_t xx = 0; xx < w; xx++)\n        {\n            size_t x = (xx + (w / 2)) % w;\n\n            double omega = std::sqrt(u*u + v*v);\n            double theta = std::atan2(v, u);\n\n            double Omega = omega/peakFreq - 1;\n            double Theta = theta + orientAngle;\n\n            if (Theta < -M_PI) Theta += 2*M_PI;\n            if (Theta >  M_PI) Theta -= 2*M_PI;\n\n            double value = std::exp(-1/(2*kappa*kappa) * Omega*Omega - sigma_theta*sigma_theta * Theta*Theta);\n\n            image(y, x) = value;\n\n            u += stepx;\n        }\n\n        v += stepy;\n    }\n}\n\ntemplate <class T>\nvoid symmetric_pad(const cv::Mat_<T>& src, cv::Mat_<T>& dst)\n{\n    cv::Mat_<T> tmp;\n\n    if (src.cols < dst.cols)\n    {\n        int width = dst.cols;\n        int height = std::min(src.rows, dst.rows);\n\n        int pad = dst.cols - src.cols;\n        int border = src.cols + pad/2;\n\n        tmp.create(height, width);\n\n        cv::Mat_<T> flipped;\n        cv::flip(src, flipped, 1);\n\n        for (int p = 0, k = 0; p < border; p += src.cols, k++)\n        {\n            int w = std::min(src.cols, border - p);\n            int h = height;\n\n            cv::Mat_<T> r = tmp(cv::Rect(p, 0, w, h));\n\n            if (k % 2)\n            {\n                flipped(cv::Rect(0, 0, w, h)).copyTo(r);\n            }\n            else\n            {\n                src(cv::Rect(0, 0, w, h)).copyTo(r);\n            }\n        }\n\n        for (int p = width, k = 1; p >= border; p -= src.cols, k++)\n        {\n            int w = std::min(src.cols, p - border);\n            int h = height;\n\n            cv::Mat_<T> r = tmp(cv::Rect(p - w, 0, w, h));\n\n            if (k % 2)\n            {\n                flipped(cv::Rect(src.cols - w, 0, w, h)).copyTo(r);\n            }\n            else\n            {\n                src(cv::Rect(src.cols - w, 0, w, h)).copyTo(r);\n            }\n        }\n    }\n    else\n    {\n        tmp = src;\n    }\n\n    if (src.rows < dst.rows)\n    {\n        int width = dst.cols;\n        int height = dst.rows;\n\n        int pad = dst.rows - src.rows;\n        int border = src.rows + pad/2;\n\n        cv::Mat_<T> flipped;\n        cv::flip(tmp, flipped, 0);\n\n        for (int p = 0, k = 0; p < border; p += src.rows, k++)\n        {\n            int w = width;\n            int h = std::min(src.rows, border - p);\n\n            cv::Mat_<T> r = dst(cv::Rect(0, p, w, h));\n\n            if (k % 2)\n            {\n                flipped(cv::Rect(0, 0, w, h)).copyTo(r);\n            }\n            else\n            {\n                tmp(cv::Rect(0, 0, w, h)).copyTo(r);\n            }\n        }\n\n        for (int p = height, k = 1; p >= border; p -= src.rows, k++)\n        {\n            int w = width;\n            int h = std::min(src.rows, p - border);\n\n            cv::Mat_<T> r = dst(cv::Rect(0, p - h, w, h));\n\n            if (k % 2)\n            {\n                flipped(cv::Rect(0, src.rows - h, w, h)).copyTo(r);\n            }\n            else\n            {\n                tmp(cv::Rect(0, src.rows - h, w, h)).copyTo(r);\n            }\n        }\n    }\n    else\n    {\n        tmp.copyTo(dst);\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n\n\n#endif // DESCRIPTORS__GIST_HELPER_HPP\n", "meta": {"hexsha": "85e4d4d53b041bd251e559faa3b81b0d4de48263", "size": 9522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "descriptors/gist_helper.hpp", "max_stars_repo_name": "mathiaseitz/imdb_framework", "max_stars_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T04:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T20:11:12.000Z", "max_issues_repo_path": "imdb/compute_descriptors/gist_helper.hpp", "max_issues_repo_name": "jjkislele/imdb_framework_msvs", "max_issues_repo_head_hexsha": "e283499ec6b7095d471671e963815aced45c38fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imdb/compute_descriptors/gist_helper.hpp", "max_forks_repo_name": "jjkislele/imdb_framework_msvs", "max_forks_repo_head_hexsha": "e283499ec6b7095d471671e963815aced45c38fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-12-21T13:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T01:29:11.000Z", "avg_line_length": 27.1282051282, "max_line_length": 125, "alphanum_fraction": 0.495484142, "num_tokens": 2765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5769347355913856}}
{"text": "#include \"incidencematrices.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <array>\n#include <memory>\n\nnamespace IncidenceMatrices {\n\n/** @brief Create the mesh consisting of a triangle and quadrilateral\n *         from the exercise sheet.\n * @return Shared pointer to the hybrid2d mesh.\n */\nstd::shared_ptr<lf::mesh::Mesh> createDemoMesh() {\n  // builder for a hybrid mesh in a world of dimension 2\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Add points\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 0});    // (0)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 0});    // (1)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 1});    // (2)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 1});    // (3)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0.5, 1});  // (4)\n\n  // Add the triangle\n  // First set the coordinates of its nodes:\n  Eigen::MatrixXd nodesOfTria(2, 3);\n  nodesOfTria << 1, 1, 0.5, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kTria(),  // we want a triangle\n      std::array<lf::mesh::Mesh::size_type, 3>{\n          {1, 2, 4}},  // indices of the nodes\n      std::make_unique<lf::geometry::TriaO1>(nodesOfTria));  // node coords\n\n  // Add the quadrilateral\n  Eigen::MatrixXd nodesOfQuad(2, 4);\n  nodesOfQuad << 0, 1, 0.5, 0, 0, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kQuad(),\n      std::array<lf::mesh::Mesh::size_type, 4>{{0, 1, 4, 3}},\n      std::make_unique<lf::geometry::QuadO1>(nodesOfQuad));\n\n  std::shared_ptr<lf::mesh::Mesh> demoMesh_p = mesh_factory_ptr->Build();\n\n  return demoMesh_p;\n}\n\n/** @brief Compute the edge-vertex incidence matrix G for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The edge-vertex incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<int> computeEdgeVertexIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store edge-vertex incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> G;\n  using size_type = lf::mesh::Mesh::size_type; \n\n  //====================\n  // Your code goes here\n  // index() method of lf:mesh:Mesh provides the numbering of entities which underlies \n  // indexing of the entries of the incidence matrixes. \n  // lf::mesh::Mesh::Index() provides a consecutive numbering of all mesh entities of a specific co-dimension \n  // lf::mesh::Entity::SubEntities() returns an array of subentities and fix their ordering. \n  const std::size_t nnz_row=2; \n  const size_type num_edge = mesh.Numentities(1); \n  const size_type num_node = mesh.Numentities(2); \n  \n  Eigen::SparseMatrix<int, Eigen::RowMajor> G(num_edge, num_node); \n  G.reserve(Eigen::VectorXi::Constant(num_edge,nnz_row)); \n\n  // to compute G efficiently, we iterate over all edges and \n  // check the index of the nodes at its end. \n  // this is the efficient way to do the assembly, introduced as distribute scheme\n  // in class\n  for(lf::mesh::Entity *edge: mesh.Entities(1)){\n    nonstd::span<const lf::mesh::Entity *const> node{edge.SubEntities(1)}; // the relative codimension is 1\n    size_type edge_index = mesh.Index(*edge); \n\n    size_type node_start_index = mesh.Index(*node[0]); \n    size_type node_end_index = mesh.Index(*node[1]); //\n    // subentities returned from SubEntities() can be accessed through [] operator using their local index \n    G.coeffRef(edge_index, node_start_index) +=1; \n    G.coeffRef(edge_index, node_end_index) -=1; \n  }\n  \n  //====================\n\n  return G;\n}\n/* SAM_LISTING_END_1 */\n\n/** @brief Compute the cell-edge incidence matrix D for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The cell-edge incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<int> computeCellEdgeIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store cell-edge incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> D;\n\n  //====================\n  // Your code goes here\n  using size_type = lf::mesh::Mesh::size_type; \n  const std::size_t nnz = 4; \n  const size_type num_cell = mesh.NumEntities(0); \n  const size_type num_edge = mesh.NumEntities(1); \n  Eigen::SparseMatrix<int, Eigen::RowMajor> D(num_cell,num_edge); \n  D.reserve(Eigen::VectorXi::Constant(num_cell,nnz)); \n  for(lf::mesh::Entity *cell: mesh.Entities(0)){\n    // get edges and their orientations of a cell \n    nonstd::span<const Entity* const> edges = cell->SubEntities(1); \n    nonstd::span<const Entity* const> orientations = cell->RelativeOrientations(); \n    size_type cell_index = mesh.Index(*cell); \n    auto edge_start = edges.begin(); \n    auto orientation_start = orientation.begin(); \n    // get the index of each edge and add their orientations to D\n    for(; edge_start !=edges.end() && orientation_start != orientation.end(); edge_start++, orientation++){\n      size_type edge_index=mesh.Index(*edge[edge_start]);\n      D.coeffRef(cell_index,edge_index) += lf::mesh::to_sign(orientation_start);  \n    }\n  }\n\n\n  //====================\n\n  return D;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief For a given mesh test if the product of cell-edge and edge-vertex\n *        incidence matrix is zero: D*G == 0?\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *             such as lf::mesh::hybrid2d::Mesh)\n * @return true, if the product is zero and false otherwise\n */\n/* SAM_LISTING_BEGIN_3 */\nbool testZeroIncidenceMatrixProduct(const lf::mesh::Mesh &mesh) {\n  bool isZero = false;\n\n  //====================\n  // Your code goes here\n  // returns true whenever the two incidence matrices of the 2D hybrid mesh satisfy \n  // the relationship asserted in 2.6.6 \n  Eigen::SparseMatrix<int> G = computeEdgeVertexIncidenceMatrix(*mesh); \n  Eigen::SparseMatrix<int> D = computeCellEdgeIncidenceMatrix(*mesh); \n  auto O = G*D; \n  \n  isZero = O.norm()==0; \n  }\n  //====================\n  return isZero;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace IncidenceMatrices\n", "meta": {"hexsha": "36a5f2c32b4a5f268d50463531376f588b4d911c", "size": 6288, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/mysolution/incidencematrices.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/IncidenceMatrices/mysolution/incidencematrices.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/IncidenceMatrices/mysolution/incidencematrices.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": 37.8795180723, "max_line_length": 110, "alphanum_fraction": 0.675413486, "num_tokens": 1774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210895, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.576906855610263}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_2_algorithms.h>\n#include <CGAL/Straight_skeleton_builder_2.h>\n#include <CGAL/Polygon_offset_builder_2.h>\n#include <CGAL/compute_outer_frame_margin.h>\n#include \"print.h\"\n\n#include <boost/shared_ptr.hpp>\n\n#include <vector>\n#include <cassert>\n\n//\n// This example illustrates how to use the CGAL Straight Skeleton package\n// to construct an offset contour on the outside of a polygon\n//\n\n// This is the recommended kernel\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\ntypedef Kernel::Point_2 Point_2;\ntypedef CGAL::Polygon_2<Kernel>    Contour;\ntypedef boost::shared_ptr<Contour> ContourPtr;\ntypedef std::vector<ContourPtr>    ContourSequence ;\n\ntypedef CGAL::Straight_skeleton_2<Kernel> Ss;\n\ntypedef Ss::Halfedge_iterator Halfedge_iterator;\ntypedef Ss::Halfedge_handle   Halfedge_handle;\ntypedef Ss::Vertex_handle     Vertex_handle;\n\ntypedef CGAL::Straight_skeleton_builder_traits_2<Kernel>      SsBuilderTraits;\ntypedef CGAL::Straight_skeleton_builder_2<SsBuilderTraits,Ss> SsBuilder;\n\ntypedef CGAL::Polygon_offset_builder_traits_2<Kernel>                  OffsetBuilderTraits;\ntypedef CGAL::Polygon_offset_builder_2<Ss,OffsetBuilderTraits,Contour> OffsetBuilder;\n\nint main()\n{\n  // A start-shaped polygon, oriented counter-clockwise as required for outer contours.\n  Point_2 pts[] = { Point_2(-1,-1)\n                  , Point_2(0,-12)\n                  , Point_2(1,-1)\n                  , Point_2(12,0)\n                  , Point_2(1,1)\n                  , Point_2(0,12)\n                  , Point_2(-1,1)\n                  , Point_2(-12,0)\n                  } ;\n\n  std::vector<Point_2> star(pts,pts+8);\n\n  assert(CGAL::orientation_2(pts,pts+8,Kernel()) == CGAL::COUNTERCLOCKWISE);\n\n  // We want an offset contour in the outside.\n  // Since the package doesn't support that operation directly, we use the following trick:\n  // (1) Place the polygon as a hole of a big outer frame.\n  // (2) Construct the skeleton on the interior of that frame (with the polygon as a hole)\n  // (3) Construc the offset contours\n  // (4) Identify the offset contour that corresponds to the frame and remove it from the result\n\n\n  double offset = 3 ; // The offset distance\n\n  // First we need to determine the proper separation between the polygon and the frame.\n  // We use this helper function provided in the package.\n  boost::optional<double> margin = CGAL::compute_outer_frame_margin(star.begin(),star.end(),offset);\n\n  // Proceed only if the margin was computed (an extremely sharp corner might cause overflow)\n  if ( margin )\n  {\n    // Get the bbox of the polygon\n    CGAL::Bbox_2 bbox = CGAL::bbox_2(star.begin(),star.end());\n\n    // Compute the boundaries of the frame\n    double fxmin = bbox.xmin() - *margin ;\n    double fxmax = bbox.xmax() + *margin ;\n    double fymin = bbox.ymin() - *margin ;\n    double fymax = bbox.ymax() + *margin ;\n\n    // Create the rectangular frame\n    Point_2 frame[4]= { Point_2(fxmin,fymin)\n                      , Point_2(fxmax,fymin)\n                      , Point_2(fxmax,fymax)\n                      , Point_2(fxmin,fymax)\n                      } ;\n\n    // Instantiate the skeleton builder\n    SsBuilder ssb ;\n\n    // Enter the frame\n    ssb.enter_contour(frame,frame+4);\n\n    // Enter the polygon as a hole of the frame (NOTE: as it is a hole we insert it in the opposite orientation)\n    ssb.enter_contour(star.rbegin(),star.rend());\n\n    // Construct the skeleton\n    boost::shared_ptr<Ss> ss = ssb.construct_skeleton();\n\n    // Proceed only if the skeleton was correctly constructed.\n    if ( ss )\n    {\n      print_straight_skeleton(*ss);\n\n      // Instantiate the container of offset contours\n      ContourSequence offset_contours ;\n\n      // Instantiate the offset builder with the skeleton\n      OffsetBuilder ob(*ss);\n\n      // Obtain the offset contours\n      ob.construct_offset_contours(offset, std::back_inserter(offset_contours));\n\n      // Locate the offset contour that corresponds to the frame\n      // That must be the outmost offset contour, which in turn must be the one\n      // with the largetst unsigned area.\n      ContourSequence::iterator f = offset_contours.end();\n      double lLargestArea = 0.0 ;\n      for (ContourSequence::iterator i = offset_contours.begin(); i != offset_contours.end(); ++ i  )\n      {\n        double lArea = CGAL_NTS abs( (*i)->area() ) ; //Take abs() as  Polygon_2::area() is signed.\n        if ( lArea > lLargestArea )\n        {\n          f = i ;\n          lLargestArea = lArea ;\n        }\n      }\n\n      // Remove the offset contour that corresponds to the frame.\n      offset_contours.erase(f);\n\n      print_polygons(offset_contours);\n    }\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "8ed3cf49c1b4979256c82d1d582da509f91719f6", "size": 4777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Straight_skeleton_2/examples/Straight_skeleton_2/Low_level_API.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": "Straight_skeleton_2/examples/Straight_skeleton_2/Low_level_API.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": "Straight_skeleton_2/examples/Straight_skeleton_2/Low_level_API.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 34.1214285714, "max_line_length": 112, "alphanum_fraction": 0.6717605192, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5767489232178608}}
{"text": "/*\n * gr_checker.cpp\n *\n *  Created on: 04.01.2015\n *      Author: schlund\n */\n\n#include <cstdlib>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost/program_options.hpp>\n\n#include \"datastructs/matrix.h\"\n#include \"datastructs/equations.h\"\n\n#include \"polynomials/commutative_polynomial.h\"\n#include \"polynomials/non_commutative_polynomial.h\"\n#include \"polynomials/lossy_non_commutative_polynomial.h\"\n\n\n#include \"semirings/pseudo_linear_set.h\"\n#include \"semirings/semilinear_set.h\"\n\n#include \"semirings/semilinSetNdd.h\"\n#include \"semirings/semilinSetNdd.h\"\n\n\n#include \"parser.h\"\n\n\n#include \"solvers/newton_generic.h\"\n#include \"solvers/solver_utils.h\"\n\n#include \"utils/string_util.h\"\n#include \"utils/timer.h\"\n\n\n\n// check whether a set of grammars generates the same language up to commuativity\n// (and modulo additional overapproximations given by the semiring)\ntemplate <typename SR>\nvoid check_all_equal_commutative(const std::string& startsymbol, const std::vector<std::string>& inputs) {\n\n  Parser p;\n  int num_grammars = inputs.size();\n\n  auto nc_equations = p.free_parser(inputs[0]);\n\n  std::cout << \"Eq (non-comm) : \" << std::endl;\n  PrintEquations(nc_equations);\n\n  // Use appropriate semiring (has to be commutative!)\n  auto equations_fst = MakeCommEquationsAndMap(nc_equations, [](const FreeSemiring &c) -> SR {\n    auto srconv = SRConverter<SR>();\n    return c.Eval(srconv);\n  });\n\n  std::cout << \"Eq (comm) : \"  << std::endl;\n  PrintEquations(equations_fst);\n\n  Timer timer;\n  timer.Start();\n\n  ValuationMap<SR> sol_fst = apply_solver<NewtonCL, CommutativePolynomial>(equations_fst, true, false, 0, false);\n\n  bool all_equal = true;\n  for(int i=1; i<num_grammars; i++) {\n    auto equations = MakeCommEquationsAndMap(p.free_parser(inputs[i]), [](const FreeSemiring &c) -> SR {\n      auto srconv = SRConverter<SR>();\n      return c.Eval(srconv);\n    });\n\n    ValuationMap<SR> sol = apply_solver<NewtonCL, CommutativePolynomial>(equations, true, false, 0, false);\n\n\n    if(startsymbol.compare(\"\") == 0) {\n      if(sol[equations[0].first] != sol_fst[equations_fst[0].first]) {\n        std::cout << \"[DIFF] Difference found for startsymbols (\" << equations_fst[0].first << \",\" << equations[0].first << \")\" << std::endl;\n        std::cout << \"0:\" << result_string(sol_fst) << std::endl << i << \":\" << result_string(sol) << std::endl;\n        all_equal = false;\n        break;\n      }\n    }\n    else {\n\n      if(sol.find(Var::GetVarId(startsymbol)) == sol.end() || sol_fst.find(Var::GetVarId(startsymbol)) == sol_fst.end()) {\n        std::cout << \"[ERROR] startsymbol (\" << startsymbol << \") does not occur!\"<< std::endl;\n        return;\n      }\n      else if(sol[Var::GetVarId(startsymbol)] != sol_fst[Var::GetVarId(startsymbol)]) {\n        std::cout << \"[DIFF] Difference found for startsymbol (\" << startsymbol << \")\" << std::endl << \"0:\" << result_string(sol_fst)\n                                               << std::endl << i << \":\" << result_string(sol) << std::endl;\n        all_equal = false;\n        break;\n      }\n    }\n\n  }\n\n  if(all_equal) {\n    std::cout << \"[EQUIV] All grammars equivalent modulo commutativity\" << std::endl;\n  }\n\n  timer.Stop();\n  std::cout\n  << \"Total checking time:\\t\" << timer.GetMilliseconds().count()\n  << \" ms\" << \" (\"\n  << timer.GetMicroseconds().count()\n  << \"us)\" << std::endl;\n\n}\n\nvoid check_all_equal_lossy(const std::string& startsymbol, const std::vector<std::string>& inputs, int refinementDepth) {\n  int num_grammars = inputs.size();\n  Parser p;\n  auto eq_tmp = MapEquations(p.free_parser(inputs[0]), [](const FreeSemiring &c) -> LossyFiniteAutomaton {\n    auto srconv = SRConverter<LossyFiniteAutomaton>();\n    return c.Eval(srconv);\n  });\n\n  auto equations_fst = NCEquationsBase<LossyFiniteAutomaton>(eq_tmp.begin(), eq_tmp.end());\n\n  VarId S_1;\n  if(startsymbol.compare(\"\") == 0) {\n    S_1 = equations_fst[0].first;\n  } else {\n    S_1 = Var::GetVarId(startsymbol);\n  }\n\n  Timer timer;\n  timer.Start();\n\n  bool all_equal = true;\n  for(int i=1; i<num_grammars; i++) {\n\n    auto eq_tmp2 = MapEquations(p.free_parser(inputs[i]), [](const FreeSemiring &c) -> LossyFiniteAutomaton {\n      auto srconv = SRConverter<LossyFiniteAutomaton>();\n      return c.Eval(srconv);\n    });\n    auto equations = NCEquationsBase<LossyFiniteAutomaton>(eq_tmp2.begin(), eq_tmp2.end());\n\n\n    VarId S_2;\n    if(startsymbol.compare(\"\") == 0) {\n      S_2 = equations[0].first;\n    } else {\n      S_2 = Var::GetVarId(startsymbol);\n    }\n\n    auto witness = NonCommutativePolynomial<LossyFiniteAutomaton>::refineCourcelle(equations_fst, S_1, equations, S_1, refinementDepth);\n\n    if(witness != LossyFiniteAutomaton::null()) {\n      if(startsymbol.compare(\"\") == 0) {\n        std::cout << \"[DIFF] Difference found for startsymbols (\" << equations_fst[0].first << \",\" << equations[0].first << \")\" << std::endl;\n      }\n      else {\n        std::cout << \"[DIFF] Difference found for startsymbols (\" << S_1 << \",\" << S_2 << \")\" << std::endl;\n      }\n        std::cout << \"Witness: \" << witness.string() << std::endl;\n        all_equal = false;\n        break;\n    }\n  }\n\n  if(all_equal) {\n    std::cout << \"[EQUIV] All grammars equivalent modulo subword-closure\" << std::endl;\n  }\n\n  timer.Stop();\n  std::cout\n  << \"Total checking time:\\t\" << timer.GetMilliseconds().count()\n  << \" ms\" << \" (\"\n  << timer.GetMicroseconds().count()\n  << \"us)\" << std::endl;\n\n}\n\n/*\n * Tests whether two grammars generate the same language modulo commutativity.\n * We use semilinear sets in constant-period representation to represent Parikh images\n * and check their equivalence via NDDs.\n */\nint main(int argc, char* argv[]) {\n  namespace po = boost::program_options;\n\n  po::options_description generic(\"Generic options\");\n  generic.add_options()\n        ( \"help,h\", \"print this help message\" )\n        ( \"startsymbol,s\", po::value<std::string>(), \"start symbol of the grammars\")\n        ( \"input\", po::value<std::vector<std::string> >(), \"input grammars (at least two): g1 g2 [g3] [...]\" )\n        ( \"slset\", \"commutative abstraction via semilinear sets\" )\n        ( \"lossy\", \"abstraction via subword closure\" )\n        (\"refD\", po::value<int>(), \"refinement Depth for Lossy Approximation\")\n        ;\n\n  po::positional_options_description pos;\n  pos.add(\"input\", -1);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(generic).positional(pos).run(), vm);\n  po::notify(vm);\n\n  SemilinSetNdd::genepi_init();\n\n  if(vm.count(\"help\")) {\n    std::cout << generic << std::endl;\n    return EXIT_SUCCESS;\n  }\n\n  std::vector<std::string> input_files = vm[\"input\"].as< std::vector<std::string> >();\n  int num_grammars = input_files.size();\n  std::vector<std::string> inputs;\n\n  std::string startsymbol = \"\";\n\n  if(vm.count(\"startsymbol\")) {\n    startsymbol = vm[\"startsymbol\"].as<std::string>();\n    std::cout << \"Comparing startsymbols (\" << startsymbol << \")\" << std::endl;\n  }\n  else {\n    std::cout << \"No startsymbol specified, using defaults.\" << std::endl;\n  }\n\n  if (vm.count(\"input\") && num_grammars > 1) {\n    // we are reading the input from the given files\n    std::ifstream file;\n\n    for(auto& filename : input_files) {\n      file.open(filename, std::ifstream::in);\n      if (file.fail()) {\n        std::cerr << \"Could not open input file: \" << filename << std::endl;\n      }\n      std::string line;\n      std::vector<std::string> input;\n      while (std::getline(file, line)) {\n        input.push_back(line);\n      }\n      // join the input into one string\n      inputs.push_back( std::accumulate(input.begin(), input.end(), std::string(\"\")) );\n      file.close();\n    }\n  } else {\n    std::cout << \"Please provide at least two input files!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if(!vm.count(\"slset\") && !vm.count(\"lossy\")) {\n    std::cout << \"Please specify the abstraction used for checking equivalence!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if(vm.count(\"slset\")) {\n    std::cout << \"Plain Semilinear Sets\" << std::endl;\n    // no overapproximation -- just plain semilinear sets with simplification\n    // (the approximations are not sound for inequivalence-testing!)\n    check_all_equal_commutative<SemilinearSetL>(startsymbol, inputs);\n  }\n\n  if(vm.count(\"lossy\")) {\n    std::cout << \"Lossy Approximation\" << std::endl;\n\n    int refinementDepth = 0;\n    if(vm.count(\"refD\")) {\n        refinementDepth = vm[\"refine\"].as<int>();\n    }\n\n    check_all_equal_lossy(startsymbol, inputs, refinementDepth);\n  }\n\n\n  SemilinSetNdd::genepi_dealloc();\n\n  return EXIT_SUCCESS;\n}\n\n\n\n\n", "meta": {"hexsha": "0dd80481cf016cea9356ac2c8f024667ea1e2bdf", "size": 8553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c/src/gr_checker.cpp", "max_stars_repo_name": "mschlund/FPsolve", "max_stars_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T23:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-13T20:42:54.000Z", "max_issues_repo_path": "c/src/gr_checker.cpp", "max_issues_repo_name": "mschlund/FPsolve", "max_issues_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "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": "c/src/gr_checker.cpp", "max_forks_repo_name": "mschlund/FPsolve", "max_forks_repo_head_hexsha": "4b8fbe87ed4eeac8a53e191aa34c5aa80b6e0490", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-21T11:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-11T03:50:09.000Z", "avg_line_length": 30.4377224199, "max_line_length": 141, "alphanum_fraction": 0.6372033205, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5767046875297926}}
{"text": "#ifndef OPTIMIZERS_HPP\n#define OPTIMIZERS_HPP\n\n// Eigen includes --------------------\n#include <Eigen/Dense>\n\n// Own includes --------------------\n#include \"optimizers/base-optimizer.hpp\"\n\nnamespace NNet { // begin NNet\n\n\t/**\n\t *SGDOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass SGDOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tSGDOptimizer( ) = delete;\n\t\texplicit SGDOptimizer( NetworkType& network, NumericType learningRate = 0.001 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ) {\n\t\t}\n\t\tSGDOptimizer( SGDOptimizer const& other ) = delete;\n\t\t~SGDOptimizer( ) = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) { return mLearningRate; }\n\n\t\t// interface\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tauto coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\t// std::cout << \"LearningRate, coeff: \" << mLearningRate << \", \" << coeff << std::endl;\n\t\t\t\t// std::cout << \"WeightMat Before: \" << weightMat.rows( ) << \", \" << weightMat.cols( ) << std::endl\n\t\t\t\t// \t\t  << weightMat << std::endl;\n\t\t\t\t// std::cout << \"WeightGradMat Before: \" << std::endl\n\t\t\t\t// \t\t  << weightGradMat << std::endl;\n\t\t\t\tweightMat = weightMat - mLearningRate * coeff * weightGradMat;\n\t\t\t}\n\t\t}\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate;\n\n\t}; // end of class SGDOptimizer\n\n    /**\n\t *MomentumOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass MomentumOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tMomentumOptimizer( ) = delete;\n\t\texplicit MomentumOptimizer( NetworkType& network, NumericType learningRate = 0.001, NumericType momentum = 0.9 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ), mMomentum( momentum ) {\n\t\t\tfor ( auto const& layer : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType const& weightGradMat = layer -> getWeightGradMat( );\n\t\t\t\tauto numRows = weightGradMat.rows( );\n\t\t\t\tauto numCols = weightGradMat.cols( );\n\t\t\t\tMatrixXType mat( numRows, numCols );\n\t\t\t\tmat.setZero( );\n\t\t\t\tmWeightGradMatSaves.emplace_back( mat );\n\t\t\t}\n\t\t}\n\t\tMomentumOptimizer( MomentumOptimizer const& other ) = delete;\n\t\t~MomentumOptimizer( ) = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) const { return mLearningRate; }\n\t\tvoid setLearningRate( NumericType learningRate ) { mLearningRate = learningRate; }\n\t\tNumericType getMomentum( ) const { return mMomentum; }\n\t\tvoid setMomentum( NumericType momentum ) { mMomentum = momentum; }\n\n\t\t// interface\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tauto v_iter = mWeightGradMatSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tNumericType coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\t// compute the velocity v_{t+1} at time t+1\n\t\t\t\t// note that v_iter at t = 0 is zero\n\t\t\t\tMatrixXType v = mMomentum * (*v_iter) - mLearningRate * coeff * weightGradMat;\n\t\t\t\t*v_iter = v;\n\t\t\t\tweightMat = weightMat + v;\n\t\t\t\t++v_iter;\n\t\t\t}\n\t\t}\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate, mMomentum;\n\t\tstd::vector< MatrixXType > mWeightGradMatSaves = { };\n\t}; // end of class MomentumOptimizer\n\n\t/**\n\t *NesterovMomentumOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass NesterovMomentumOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tNesterovMomentumOptimizer( ) = delete;\n\t\texplicit NesterovMomentumOptimizer( NetworkType& network, NumericType learningRate = 0.001, NumericType momentum = 0.9 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ), mMomentum( momentum ) {\n\t\t\tfor ( auto const& layer : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType const& weightGradMat = layer -> getWeightGradMat( );\n\t\t\t\tauto numRows = weightGradMat.rows( );\n\t\t\t\tauto numCols = weightGradMat.cols( );\n\t\t\t\tMatrixXType mat( numRows, numCols );\n\t\t\t\tmat.setZero( );\n\t\t\t\tmWeightGradMatSaves.emplace_back( mat );\n\t\t\t}\n\t\t}\n\t\tNesterovMomentumOptimizer( NesterovMomentumOptimizer const& other ) = delete;\n\t\t~NesterovMomentumOptimizer( ) = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) { return mLearningRate; }\n\t\tvoid setLearningRate( NumericType learningRate ) { mLearningRate = learningRate; }\n\t\tNumericType getMomentum( ) const { return mMomentum; }\n\t\tvoid setMomentum( NumericType momentum ) { mMomentum = momentum; }\n\n\t\t// interface\n\t\tvoid applyInterimUpdate( ) override {\n\t\t\tauto v_iter = mWeightGradMatSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tweightMat = weightMat + mMomentum * ( *v_iter );\n\t\t\t\t++v_iter;\n\t\t\t}\n\t\t}\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tauto v_iter = mWeightGradMatSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tNumericType coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\tMatrixXType v = mMomentum * (*v_iter) - mLearningRate * coeff * weightGradMat;\n\t\t\t\t*v_iter = v;\n\t\t\t\tweightMat = weightMat - mLearningRate * coeff * weightGradMat;\n\t\t\t\t++v_iter;\n\t\t\t}\n\t\t}\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate, mMomentum;\n\t\tstd::vector< MatrixXType > mWeightGradMatSaves = { };\n\t}; // end of class NesterovMomentumOptimizer\n\n\t/**\n\t *AdaGradOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass AdaGradOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tAdaGradOptimizer() = delete;\n\t\texplicit AdaGradOptimizer( NetworkType& network, NumericType learningRate = 0.01 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ) {\n\t\t\tfor ( auto const& layer : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType const& weightGradMat = layer -> getWeightGradMat( );\n\t\t\t\tauto numRows = weightGradMat.rows( );\n\t\t\t\tauto numCols = weightGradMat.cols( );\n\t\t\t\tMatrixXType mat( numRows, numCols );\n\t\t\t\tmat.setZero( );\n\t\t\t\tmGradMatAccumSaves.emplace_back( mat );\n\t\t\t}\n\t\t}\n\t\tAdaGradOptimizer(const AdaGradOptimizer &c) = delete;\n\t\t~AdaGradOptimizer() = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) const { return mLearningRate; }\n\t\tvoid setLearningRate( NumericType learningRate ) { mLearningRate = learningRate; }\n\n\t\t// interface\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tauto r_iter = mGradMatAccumSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tNumericType coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\t// accumulate squared gradient\n\t\t\t\tMatrixXType grad_sq = coeff * coeff * weightGradMat.cwiseProduct( weightGradMat );\n\t\t\t\t*r_iter = (*r_iter) + grad_sq;\n\t\t\t\tMatrixXType r = *r_iter;\n\t\t\t\tr = r.unaryExpr( [this]( auto const& ele ) {\n\t\t\t\t\treturn ( mLearningRate / ( 1.0e-7 + std::sqrt( ele ) ) );\n\t\t\t\t} );\n\t\t\t\tweightMat = weightMat - r.cwiseProduct( coeff * weightGradMat );\n\t\t\t\t++r_iter;\n\t\t\t}\n\t\t}\n\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate;\n\t\tstd::vector< MatrixXType > mGradMatAccumSaves = { };\n\t}; // end of class AdaGradOptimizer\n\n\t/**\n\t *RMSPropOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass RMSPropOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tRMSPropOptimizer() = delete;\n\t\texplicit RMSPropOptimizer( NetworkType& network, NumericType learningRate = 0.001, NumericType decayRate = 0.9 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ), mDecayRate( decayRate ) {\n\t\t\tfor ( auto const& layer : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType const& weightGradMat = layer -> getWeightGradMat( );\n\t\t\t\tauto numRows = weightGradMat.rows( );\n\t\t\t\tauto numCols = weightGradMat.cols( );\n\t\t\t\tMatrixXType mat( numRows, numCols );\n\t\t\t\tmat.setZero( );\n\t\t\t\tmGradMatAccumSaves.emplace_back( mat );\n\t\t\t}\n\t\t}\n\t\tRMSPropOptimizer( RMSPropOptimizer const& other ) = delete;\n\t\t~RMSPropOptimizer() = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) const { return mLearningRate; }\n\t\tvoid setLearningRate( NumericType learningRate ) { mLearningRate = learningRate; }\n\t\tNumericType getDecayRate( ) const { return mDecayRate; }\n\t\tvoid setDecayRate( NumericType decayRate ) { mDecayRate = decayRate; }\n\n\t\t// interface\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tauto r_iter = mGradMatAccumSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tNumericType coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\t// accumulate squared gradient\n\t\t\t\tMatrixXType grad_sq = coeff * coeff * weightGradMat.cwiseProduct( weightGradMat );\n\t\t\t\t*r_iter = mDecayRate * (*r_iter) + (1.0 - mDecayRate ) * grad_sq;\n\t\t\t\tMatrixXType r = *r_iter;\n\t\t\t\tr = r.unaryExpr( [this]( auto const& ele ) {\n\t\t\t\t\treturn ( mLearningRate / ( 1.0e-6 + std::sqrt( ele ) ) );\n\t\t\t\t} );\n\t\t\t\tweightMat = weightMat - r.cwiseProduct( coeff * weightGradMat );\n\t\t\t\t++r_iter;\n\t\t\t}\n\t\t}\n\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate, mDecayRate;\n\t\tstd::vector< MatrixXType > mGradMatAccumSaves = { };\n\t}; // end of class RMSPropOptimizer\n\n\t/**\n\t *RMSPropNestMomOptimizer.\n\t */\n\ttemplate< typename NetworkType >\n\tclass RMSPropNestMomOptimizer\n\t\t: public BaseOptimizer< NetworkType > {\n\tpublic: \t// public typedefs\n\t\tusing NumericType = typename NetworkType::NumericType;\n\t\tusing VectorXType = typename NetworkType::VectorXType;\n\t\tusing MatrixXType = typename NetworkType::MatrixXType;\n\n\tprivate: \t// private typedefs\n\n\tpublic: \t//public member functions\n\t\tRMSPropNestMomOptimizer() = delete;\n\t\texplicit RMSPropNestMomOptimizer( NetworkType& network, NumericType learningRate = 0.001, NumericType momentum = 0.9, NumericType decayRate = 0.9 )\n\t\t\t: BaseOptimizer< NetworkType >( network ), mLearningRate( learningRate ), mMomentum( momentum ), mDecayRate( decayRate ) {\n\t\t\tfor ( auto const& layer : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType const& weightGradMat = layer -> getWeightGradMat( );\n\t\t\t\tauto numRows = weightGradMat.rows( );\n\t\t\t\tauto numCols = weightGradMat.cols( );\n\t\t\t\tMatrixXType mat( numRows, numCols );\n\t\t\t\tmat.setZero( );\n\t\t\t\tmWeightGradMatSaves.emplace_back( mat );\n\t\t\t\tmGradMatAccumSaves.emplace_back( mat );\n\t\t\t}\n\t\t}\n\t\tRMSPropNestMomOptimizer( RMSPropNestMomOptimizer const& other ) = delete;\n\t\t~RMSPropNestMomOptimizer() = default;\n\n\t\t//get/set member functions\n\t\tNumericType getLearningRate( ) const { return mLearningRate; }\n\t\tvoid setLearningRate( NumericType learningRate ) { mLearningRate = learningRate; }\n\t\tNumericType getMomentum( ) const { return mMomentum; }\n\t\tvoid setMomentum( NumericType momentum ) { mMomentum = momentum; }\n\t\tNumericType getDecayRate( ) const { return mDecayRate; }\n\t\tvoid setDecayRate( NumericType decayRate ) { mDecayRate = decayRate; }\n\n\t\t// interface\n\t\tvoid applyInterimUpdate( ) override {\n\t\t\tauto v_iter = mWeightGradMatSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tweightMat = weightMat + mMomentum * ( *v_iter );\n\t\t\t\t++v_iter;\n\t\t\t}\n\t\t}\n\t\tvoid applyWeightUpdate( std::size_t batchSize ) override {\n\t\t\tauto v_iter = mWeightGradMatSaves.begin( );\n\t\t\tauto r_iter = mGradMatAccumSaves.begin( );\n\t\t\tfor ( auto& layerPtr : this -> getTrainableLayers( ) ) {\n\t\t\t\tMatrixXType& weightMat = layerPtr -> getWeightMat( );\n\t\t\t\tMatrixXType const& weightGradMat = layerPtr -> getWeightGradMat( );\n\t\t\t\tNumericType coeff = 1.0 / static_cast< NumericType >( batchSize );\n\t\t\t\t// accumulate squared gradient\n\t\t\t\tMatrixXType grad_sq = coeff * coeff * weightGradMat.cwiseProduct( weightGradMat );\n\t\t\t\t*r_iter = mDecayRate * (*r_iter) + (1.0 - mDecayRate ) * grad_sq;\n\t\t\t\tMatrixXType r = *r_iter;\n\t\t\t\tr = r.unaryExpr( [this]( auto const& ele ) {\n\t\t\t\t\treturn ( mLearningRate / ( 1.0e-7 + std::sqrt( ele ) ) );\n\t\t\t\t} );\n\t\t\t\tMatrixXType v = mMomentum * ( *v_iter ) - r.cwiseProduct( coeff * weightGradMat );\n\t\t\t\t*v_iter = v;\n\t\t\t\tweightMat = weightMat - r.cwiseProduct( coeff * weightGradMat );\n\t\t\t\t++v_iter;\n\t\t\t\t++r_iter;\n\t\t\t}\n\t\t}\n\n\tprivate: \t//private member functions\n\n\tpublic: \t//public data members\n\n\tprivate: \t//private data members\n\t\tNumericType mLearningRate, mMomentum, mDecayRate;\n\t\tstd::vector< MatrixXType > mWeightGradMatSaves = { }, mGradMatAccumSaves = { };\n\t}; // end of class RMSPropNestMomOptimizer\n\n} // end NNet\n\n#endif // OPTIMIZERS_HPP\n", "meta": {"hexsha": "52daee57647a3551fd57afb6d1cd68391d60cab9", "size": 14587, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/nnet/optimizers/optimizers.hpp", "max_stars_repo_name": "kjmarshall/NNet", "max_stars_repo_head_hexsha": "7b51a1c688666a626011b5b730dae3f6a9e97ec2", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/nnet/optimizers/optimizers.hpp", "max_issues_repo_name": "kjmarshall/NNet", "max_issues_repo_head_hexsha": "7b51a1c688666a626011b5b730dae3f6a9e97ec2", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/nnet/optimizers/optimizers.hpp", "max_forks_repo_name": "kjmarshall/NNet", "max_forks_repo_head_hexsha": "7b51a1c688666a626011b5b730dae3f6a9e97ec2", "max_forks_repo_licenses": ["BSD-3-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.5953608247, "max_line_length": 149, "alphanum_fraction": 0.7012408309, "num_tokens": 4075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5765086582125799}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templateauxilliaries_regression_hpp\n#define quantlib_templateauxilliaries_regression_hpp\n\n//#include <ql/types.hpp>\n//#include <boost/function.hpp>\n\n//#include <ql/experimental/template/auxilliaries/templatesvd.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/qrfactorisationT.hpp>\n\n\nnamespace TemplateAuxilliaries {\n\n    template <class Type>\n    class Regression {\n\n    protected:\n\n        size_t                               maxDegree_;  // max polynomial degree\n        std::vector< std::vector<size_t> >   multIdx_;    // list of all multi-indeces with degree <= maxDegree_\n        std::vector<Type>                    beta_;       // linear coefficients\n\n        inline void divide( std::vector<size_t> x, size_t idx, size_t degree) {\n            if (idx==x.size()-1) {\n                x[idx] = degree;\n                multIdx_.push_back(x);\n            } else {\n                for (size_t k=0; k<=degree; ++k) {\n                    x[idx] = k;\n                    divide(x, idx+1, degree-k);\n                }\n            }\n        }\n\n        // initialise multi-index matrix via recursive call of divide()\n        inline void setUpMultiIndex(const size_t dim, const size_t maxDegree) {\n            multIdx_.clear();\n            std::vector<size_t> x(dim,0);\n            for (size_t k=0; k<=maxDegree; ++k) divide(x,0,k);\n        }\n\n        // perform actual regression calculation\n        inline void calculateRegression( const std::vector< std::vector<Type> >& controls,\n                                         const std::vector< Type >&              observations ) {\n            std::vector<Type> b(observations);\n            std::vector< std::vector<Type> >  M(controls.size());\n            for (size_t i=0; i<M.size(); ++i) M[i] = monomials(controls[i]);\n            qrsolveles(M,b);\n            for (size_t i=0; i<beta_.size(); ++i) beta_[i] = b[i];\n\n        }\n\n    public:\n\n        Regression ( const std::vector< std::vector<Type> >& controls,\n                     const std::vector< Type >&              observations,\n                     const size_t                            maxDegree ) : maxDegree_(maxDegree) {\n            // check dimensions\n            size_t nRows = 0;\n            if (controls.size()==observations.size()) nRows = controls.size();\n\n            if (nRows>0) setUpMultiIndex(controls[0].size(),maxDegree_);\n            size_t nCols = multIdx_.size();\n\n            // initialise beta\n            beta_.resize(nCols,0.0);\n            if ((nRows>0)&&(nRows>=nCols))\n                calculateRegression(controls,observations);  // if nRows < nCols regression does not really make sense\n\n        }\n\n        const std::vector<Type> monomials( const std::vector<Type>& x ) const {\n            std::vector<Type> y(multIdx_.size(),0.0);\n            if ((multIdx_.size()==0)||(multIdx_[0].size()!=x.size())) return y;  // dimension mismatch\n            for (size_t i=0; i<y.size(); ++i) {\n                y[i] = 1.0;\n                for (size_t j=0; j<x.size(); ++j) {  // don't want to use pow coz not clear how it's implemented\n                    for (size_t k=0; k<multIdx_[i][j]; ++k) y[i] *= x[j];\n                }\n            }\n            return y;\n        }\n\n        const Type value( const std::vector<Type>& x ) const {\n            std::vector<Type> y = monomials(x);\n            if (y.size()!=beta_.size()) return 0.0;  // dimension mismatch\n            Type res = 0.0;\n            for (size_t i=0; i<y.size(); ++i) res += beta_[i] * y[i];\n            return res;\n        }\n\n        // inspectors\n\n        const size_t                              maxDegree() const { return maxDegree_; }\n        const std::vector< std::vector<size_t> >& multIdx()   const { return multIdx_;   }\n        const std::vector<Type>&                  beta()      const { return beta_;      }\n\n        const std::vector< std::vector<Type> >    multiIndex() const {  // workaround for Excel interface debugging\n            std::vector< std::vector<Type> > M(multIdx_.size());\n            for (size_t i=0; i<multIdx_.size(); ++i) {\n                M[i].resize(multIdx_[i].size());\n                for (size_t j=0; j<multIdx_[i].size(); ++j) M[i][j] = multIdx_[i][j];\n            }\n            return M;\n        }\n\n    };\n    \n}\n\n#endif  /* ifndef quantlib_templateauxilliaries_regression_hpp */\n", "meta": {"hexsha": "4c7b34cedab75b4b2c9d7128a201ed8191ac5d7b", "size": 4478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/regressionT.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/auxilliaries/regressionT.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/auxilliaries/regressionT.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": 37.3166666667, "max_line_length": 118, "alphanum_fraction": 0.52188477, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5765086401167492}}
{"text": "#ifndef CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H\n#define CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H \n\n#include <cmath>\n#include <utility>\n#include <random>\n\n#include <Eigen/Dense>\n\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n\n#include <cannon/physics/systems/system.hpp>\n#include <cannon/physics/euler_integrator.hpp>\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nnamespace oc = ompl::control;\nnamespace ob = ompl::base;\n\nnamespace cannon {\n  namespace physics {\n    namespace systems {\n\n      struct PendSystem : System {\n        PendSystem(double g = 10.0, double m = 1.0, double l = 1.0, double dt =\n            0.05, double max_speed = 8.0) : g_(g), m_(m), l_(l), dt_(dt),\n        max_speed_(max_speed) {}\n\n        virtual void operator()(const VectorXd& x, VectorXd& dxdt, const double /*t*/) override {\n          double th = x[0];\n          double thdot = x[1];\n          double u = x[2];\n\n          double new_thdot = (-3 * g_ / (2 * l_)) * std::sin(th + M_PI) + \n            (3.0 * u / (m_ * std::pow(l_, 2.0)));\n          double new_th = thdot + (new_thdot * dt_);\n\n          dxdt.resize(3);\n          dxdt[0] = new_th;\n          dxdt[1] = new_thdot;\n          dxdt[2] = 0.0;\n        }\n\n        virtual void ompl_ode_adaptor(const oc::ODESolver::StateType& q, \n            const oc::Control* control, oc::ODESolver::StateType& qdot) override {\n\n          const double u = control->as<oc::RealVectorControlSpace::ControlType>()->values[0];\n\n          VectorXd s(3);\n          s[0] = q[0];\n          s[1] = q[1];\n          s[2] = u;\n          VectorXd dsdt(3);\n\n          (*this)(s, dsdt, 0.0);\n\n          qdot.resize(q.size(), 0);\n          for (unsigned int i = 0; i < q.size(); i++) {\n            qdot[i] = dsdt[i];\n          }\n        }\n\n        virtual std::tuple<MatrixXd, MatrixXd, VectorXd> get_linearization(const VectorXd& x) override {\n          MatrixXd A = MatrixXd::Zero(2, 2);\n          MatrixXd B = MatrixXd::Zero(2, 1);\n          VectorXd c = VectorXd::Zero(2);\n\n          // TODO \n          \n          return std::make_tuple(A, B, c);\n        }\n\n        virtual void\n        get_continuous_time_linearization(const oc::ODESolver::StateType &q,\n                                          Ref<MatrixXd> A,\n                                          Ref<MatrixXd> B) override {\n          throw std::runtime_error(\"Not implemented yet\");\n        }\n\n        static void ompl_post_integration(const ob::State* /*state*/, const\n            oc::Control* /*control*/, const double /*duration*/, ob::State *result) {\n          // Nothing needed\n        }\n\n        // Parameters\n        double g_;\n        double m_;\n        double l_;\n        double dt_;\n        double max_speed_;\n      };\n\n\n      class InvertedPendulum {\n        public:\n          InvertedPendulum(double max_torque = 2.0) : max_torque_(max_torque),\n          e_(s_, 3, 0.05) {\n            std::random_device rd;\n            gen_ = std::mt19937(rd());  \n\n            th_dis_ = std::uniform_real_distribution<double>(-M_PI, M_PI);\n            thdot_dis_ = std::uniform_real_distribution<double>(-1.0, 1.0);\n\n            state_ = Vector3d::Zero(3);\n            reset(); \n          }\n\n          std::pair<VectorXd, double> step(double u) {\n            double th = state_[0];\n            double thdot = state_[1];\n\n            double reward = -(std::pow(normalize_(th), 2.0) + (0.1 * std::pow(thdot,\n                    2.0)) + (0.001 * std::pow(u, 2.0)));\n\n            double clipped_u = std::max(-max_torque_, std::min(max_torque_, u));\n            state_[2] = clipped_u;\n\n            e_.set_state(state_);\n            state_ = e_.step();\n\n            state_[0] = std::atan2(std::sin(state_[0]),std::cos(state_[0]));\n            state_[1] = std::max(-8.0, std::min(state_[1], 8.0)); \n            \n            return std::make_pair(state_.head(2), reward);\n          }\n\n          VectorXd reset() {\n            double th = th_dis_(gen_);\n            double thdot = thdot_dis_(gen_);\n\n            state_[0] = th;\n            state_[1] = thdot;\n            state_[2] = 0.0;\n\n            return state_.head(2);\n          }\n\n          PendSystem s_;\n\n        private:\n          inline double normalize_(double th) {\n            return (std::fmod((th + M_PI), (2.0 * M_PI)) - M_PI); \n          }\n\n          double max_torque_;\n\n          EulerIntegrator<PendSystem> e_;\n\n          Vector3d state_;\n\n          std::mt19937 gen_;\n          std::uniform_real_distribution<double> th_dis_;\n          std::uniform_real_distribution<double> thdot_dis_;\n      };\n\n    } // namespace systems\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_SYSTEMS_INVERTED_PENDULUM_H */\n", "meta": {"hexsha": "649c863ab3e86373cacf2c794c6cd317ddd5675b", "size": 4727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/systems/inverted_pendulum.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/physics/systems/inverted_pendulum.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/physics/systems/inverted_pendulum.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.8231707317, "max_line_length": 104, "alphanum_fraction": 0.534588534, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5764458433873436}}
{"text": "//\n// Created by liyubo on 12/15/17.\n//\n\n#include <iostream>\nusing namespace std;\n#include <ctime>\n// Eigen 部分\n#include <Eigen/Core>\n// 稠密矩阵的代数运算（逆，特征值等）\n#include <Eigen/Dense>\n#include\"hw.h\"\n#define MATRIX_SIZE 50\n\nvoid homework()\n{\n\n\n//作业\n    Eigen::MatrixXd matrix_A;\n    matrix_A = Eigen::MatrixXd::Random( 100, 100 );\n    Eigen::MatrixXd matrix_b;\n    matrix_b = Eigen::MatrixXd::Random( 100, 1 );\n    Eigen::MatrixXd x;\n// cout << matrix_A << endl;\n// cout << matrix_b << endl;\n    x = matrix_A.llt().solve(matrix_b);   //llt Cholesky来解方程\n\n\n    /*******************时间比较*********************/\n\n    clock_t time_stt = clock();\n    x = matrix_A.colPivHouseholderQr().solve(matrix_b);  //利用QR分解求解方程\n    cout <<\"time use in Qr decomposition is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n\n    time_stt = clock();\n    x = matrix_A.fullPivLu().solve(matrix_b);   //LU\n    cout <<\"time use  in fullPivLu  is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n\n    time_stt = clock();\n    x = matrix_A.inverse()*matrix_b;;  //利用求逆来解方程\n    cout <<\"time use  in normal inverse  is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n\n    time_stt = clock();\n    x = matrix_A.llt().solve(matrix_b);   //llt Cholesky来解方程\n    cout <<\"time use  in llt(Cholesky)  is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    time_stt = clock();\n    x = matrix_A.ldlt().solve(matrix_b);   //ldlt\n    cout <<\"time use  in ldlt is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\"<< endl;\n}\n", "meta": {"hexsha": "425cb4ef757c75bd9497830c265e4ba465955905", "size": 1577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useEigen/hw.cpp", "max_stars_repo_name": "MrCocoaCat/slambook", "max_stars_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-13T05:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T17:35:25.000Z", "max_issues_repo_path": "ch3/useEigen/hw.cpp", "max_issues_repo_name": "MrCocoaCat/slambook", "max_issues_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useEigen/hw.cpp", "max_forks_repo_name": "MrCocoaCat/slambook", "max_forks_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T13:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T13:59:20.000Z", "avg_line_length": 28.6727272727, "max_line_length": 114, "alphanum_fraction": 0.6087507926, "num_tokens": 524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.576445842697705}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_CENTERED_CONTINUED_FRACTION_HPP\n#define BOOST_MATH_TOOLS_CENTERED_CONTINUED_FRACTION_HPP\n\n#include <cmath>\n#include <cstdint>\n#include <vector>\n#include <ostream>\n#include <iomanip>\n#include <limits>\n#include <stdexcept>\n#include <sstream>\n#include <array>\n#include <type_traits>\n#include <boost/math/tools/is_standalone.hpp>\n\n#ifndef BOOST_MATH_STANDALONE\n#include <boost/core/demangle.hpp>\n#endif\n\nnamespace boost::math::tools {\n\ntemplate<typename Real, typename Z = int64_t>\nclass centered_continued_fraction {\npublic:\n    centered_continued_fraction(Real x) : x_{x} {\n        static_assert(std::is_integral_v<Z> && std::is_signed_v<Z>,\n                      \"Centered continued fractions require signed integer types.\");\n        using std::round;\n        using std::abs;\n        using std::sqrt;\n        using std::isfinite;\n        if (!isfinite(x))\n        {\n            throw std::domain_error(\"Cannot convert non-finites into continued fractions.\");  \n        }\n        b_.reserve(50);\n        Real bj = round(x);\n        b_.push_back(static_cast<Z>(bj));\n        if (bj == x)\n        {\n            b_.shrink_to_fit();\n            return;\n        }\n        x = 1/(x-bj);\n        Real f = bj;\n        if (bj == 0)\n        {\n            f = 16*(std::numeric_limits<Real>::min)();\n        }\n        Real C = f;\n        Real D = 0;\n        int i = 0;\n        while (abs(f - x_) >= (1 + i++)*std::numeric_limits<Real>::epsilon()*abs(x_))\n        {\n            bj = round(x);\n            b_.push_back(static_cast<Z>(bj));\n            x = 1/(x-bj);\n            D += bj;\n            if (D == 0) {\n                D = 16*(std::numeric_limits<Real>::min)();\n            }\n            C = bj + 1/C;\n            if (C==0)\n            {\n                C = 16*(std::numeric_limits<Real>::min)();\n            }\n            D = 1/D;\n            f *= (C*D);\n        }\n        // Deal with non-uniqueness of continued fractions: [a0; a1, ..., an, 1] = a0; a1, ..., an + 1].\n        if (b_.size() > 2 && b_.back() == 1)\n        {\n            b_[b_.size() - 2] += 1;\n            b_.resize(b_.size() - 1);\n        }\n        b_.shrink_to_fit();\n\n        for (size_t i = 1; i < b_.size(); ++i)\n        {\n            if (b_[i] == 0) {\n                std::ostringstream oss;\n                oss << \"Found a zero partial denominator: b[\" << i << \"] = \" << b_[i] << \".\"\n                    #ifndef BOOST_MATH_STANDALONE\n                    << \" This means the integer type '\" << boost::core::demangle(typeid(Z).name())\n                    #else\n                    << \" This means the integer type '\" << typeid(Z).name()\n                    #endif\n                    << \"' has overflowed and you need to use a wider type,\"\n                    << \" or there is a bug.\";\n                throw std::overflow_error(oss.str());\n            }\n        }\n    }\n\n    Real khinchin_geometric_mean() const {\n        if (b_.size() == 1)\n        { \n            return std::numeric_limits<Real>::quiet_NaN();\n        }\n        using std::log;\n        using std::exp;\n        using std::abs;\n        const std::array<Real, 7> logs{std::numeric_limits<Real>::quiet_NaN(), Real(0), log(static_cast<Real>(2)), log(static_cast<Real>(3)), log(static_cast<Real>(4)), log(static_cast<Real>(5)), log(static_cast<Real>(6))};\n        Real log_prod = 0;\n        for (size_t i = 1; i < b_.size(); ++i)\n        {\n            if (abs(b_[i]) < static_cast<Z>(logs.size()))\n            {\n                log_prod += logs[abs(b_[i])];\n            }\n            else\n            {\n                log_prod += log(static_cast<Real>(abs(b_[i])));\n            }\n        }\n        log_prod /= (b_.size()-1);\n        return exp(log_prod);\n    }\n\n    const std::vector<Z>& partial_denominators() const {\n        return b_;\n    }\n    \n    template<typename T, typename Z2>\n    friend std::ostream& operator<<(std::ostream& out, centered_continued_fraction<T, Z2>& ccf);\n\nprivate:\n    const Real x_;\n    std::vector<Z> b_;\n};\n\n\ntemplate<typename Real, typename Z2>\nstd::ostream& operator<<(std::ostream& out, centered_continued_fraction<Real, Z2>& scf) {\n    constexpr const int p = std::numeric_limits<Real>::max_digits10;\n    if constexpr (p == 2147483647)\n    {\n        out << std::setprecision(scf.x_.backend().precision());\n    }\n    else\n    {\n        out << std::setprecision(p);\n    }\n   \n    out << \"[\" << scf.b_.front();\n    if (scf.b_.size() > 1)\n    {\n        out << \"; \";\n        for (size_t i = 1; i < scf.b_.size() -1; ++i)\n        {\n            out << scf.b_[i] << \", \";\n        }\n        out << scf.b_.back();\n    }\n    out << \"]\";\n    return out;\n}\n\n\n}\n#endif\n", "meta": {"hexsha": "0493142de5284e58dbb7f2b3c366e856f4573b26", "size": 4876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/centered_continued_fraction.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/tools/centered_continued_fraction.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/tools/centered_continued_fraction.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.1976047904, "max_line_length": 223, "alphanum_fraction": 0.504511895, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5763384815754085}}
{"text": "#include \"eigen_ext.hpp\"\n#include \"function.hpp\"\n#include \"parameters.hpp\"\n#include <cassert>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace pear {\nvoid fun_diff(Vec &Cu, Vec &Cv, Vec &Ru, Vec &Rv, Mat &RudCu, Mat &RudCv,\n              Mat &RvdCu, Mat &RvdCv) {\n\n  int np = Cu.rows();\n\n  // FUNCTIONS\n  Ru = pear::Vmu * Cu.array() /\n       ((pear::Kmu + Cu.array()) * (1 + Cv.array() / pear::Kmv));\n\n  Rv = pear::rq * Ru.array() + pear::Vmfv / (1 + Cu.array() / pear::Kmfu);\n\n  // DERIVATIVES\n  Vec RudCu_diag(np);\n  Vec RudCVdiag(np);\n  Vec RvdCu_diag(np);\n  Vec RvdCVdiag(np);\n\n  RudCu_diag = (pear::Kmu * pear::Kmv * pear::Vmu) /\n               ((Cu.array() + pear::Kmu).pow(2) * (Cv.array() + pear::Kmv));\n\n  RudCVdiag = -(Cu.array() * pear::Kmv * pear::Vmu) /\n              ((Cu.array() + pear::Kmu) * (Cv.array() + pear::Kmv).pow(2));\n\n  RvdCu_diag = (pear::Kmv * pear::Vmu * pear::rq) /\n                   ((Cu.array() + pear::Kmu) * (Cv.array() + pear::Kmv)) -\n               (pear::Kmfu * pear::Vmfv) / (Cu.array() + pear::Kmfu).pow(2) -\n               (Cu.array() * pear::Kmv * pear::Vmu * pear::rq) /\n                   ((Cu.array() + pear::Kmu).pow(2) * (Cv.array() + pear::Kmv));\n\n  RvdCVdiag = -(Cu.array() * pear::Kmv * pear::Vmu * pear::rq) /\n              ((Cu.array() + pear::Kmu) * (Cv.array() + pear::Kmv).pow(2));\n\n  RudCu = RudCu_diag.asDiagonal();\n  RvdCu = RudCu_diag.asDiagonal();\n  RudCv = RudCu_diag.asDiagonal();\n  RvdCv = RudCu_diag.asDiagonal();\n}\n\n} // namespace pear\n", "meta": {"hexsha": "9cc837fac63d84f5d9042815cf62d303383f6703", "size": 1534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/function.cpp", "max_stars_repo_name": "hdeplaen/the_winning_pear", "max_stars_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/function.cpp", "max_issues_repo_name": "hdeplaen/the_winning_pear", "max_issues_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/function.cpp", "max_forks_repo_name": "hdeplaen/the_winning_pear", "max_forks_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.68, "max_line_length": 80, "alphanum_fraction": 0.5423728814, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5762682503348548}}
{"text": "#ifndef __IRLS_H__\n#define __IRLS_H__\n\n#include <armadillo>\n\n#include <glm/glm_info.hpp>\n#include <glm/models/glm_model.hpp>\n\n/**\n * Maximum number of iterations in the IRLS algorithm.\n */\nstatic const int IRLS_MAX_ITERS = 25;\n\n/**\n * Smallest change in likelihood before terminating the IRLS algorithm.\n */\nstatic double IRLS_TOLERANCE = 10e-8;\n\n/**\n* Sets the weights of missing observations to zero, so that\n* the will not influence the regression.\n*\n* @param missing Missing individuals are indicated by 1.\n* @param w Vector of weights, missing entries will be replaced by 0.\n*/\nvoid set_missing_to_zero(const arma::uvec &missing, arma::vec &w);\n\n/**\n * Compute the chisquare cdf for a vector of chi square variables.\n *\n * @param x Vector of chi square values.\n * @param df Degrees of freedom.\n *\n * @return Vector of corresponding p-values.\n */\narma::vec chi_square_cdf(const arma::vec &x, unsigned int df);\n\n/**\n * Solves the weighted least square problem:\n *   \n *   W*X*W*b = X*W*y\n *\n * The algorithm uses the singular value decomposition, to\n * compute the solution b:\n *   \n *   b = V * S^-1 * U^t sqrt( w ) * y\n *\n * where wX = U S V^t\n *\n * @param X The design matrix.\n * @param y The right hand side.\n * @param w The weight for each observation.\n * @param fast_inversion If true use less robust but faster inversion.\n *\n * @return The vector b that minimizes the weighted least squares problem.\n */\narma::vec weighted_least_squares(const arma::mat &X, const arma::vec &y, const arma::vec &w, bool fast_inversion = false);\n\n/**\n * Compute the adjusted dependent variates in the Iteratively reweighted\n * least squares algorithm.\n *\n * @param eta The linearized parameter.\n * @param mu The mean value parameter.\n * @param mu_eta The derivative of mu with respect to eta.\n * @param y The observations.\n *\n * @return The adjusted dependent variates.\n */\narma::vec compute_z(const arma::vec &eta, const arma::vec &mu, const arma::vec &mu_eta, const arma::vec &y);\n\n/**\n * Compute the weight vector that is used in one iteration\n * in the Iteratively reweighted least squares algorithm.\n *\n * @param var Variance of each observation.\n * @param mu_eta The derivative of mu with respect to eta.\n *\n * @return A weight vector.\n */\narma::vec compute_w(const arma::vec &var, const arma::vec& mu_eta);\n\n/**\n * This function performs the iteratively reweighted\n * least squares algorithm to estimate beta coefficients\n * of a genearlized linear model.\n *\n * @param X The design matrix (caller is responsible for\n *          adding an intercept).\n * @param y The observations.\n * @param model The GLM model to estimate.\n * @param output Output statistics of the estimated betas.\n * @param fast_inversion If true use less robust but faster inversion.\n *\n * @return Estimated beta coefficients.\n */\narma::vec irls(const arma::mat &X, const arma::vec &y, const glm_model &model, glm_info &output, bool fast_inversion = false);\n\n/**\n * This function performs the iteratively reweighted\n * least squares algorithm to estimate beta coefficients\n * of a genearlized linear model.\n *\n * @param X The design matrix (caller is responsible for\n *          adding an intercept).\n * @param y The observations.\n * @param missing Identifies missing sampels by 1 and non-missing by 0.\n * @param model The GLM model to estimate.\n * @param output Output statistics of the estimated betas.\n * @param fast_inversion If true use less robust but faster inversion.\n *\n * @return Estimated beta coefficients.\n */\narma::vec irls(const arma::mat &X, const arma::vec &y, const arma::uvec &missing, const glm_model &model, glm_info &output, bool fast_inversion = false);\n\n#endif /* End of __IRLS_H__ */\n", "meta": {"hexsha": "0e995539fa41ad1d87df7ba4bd8d801346f96251", "size": 3676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/glm/irls.hpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/glm/irls.hpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/glm/irls.hpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 31.4188034188, "max_line_length": 153, "alphanum_fraction": 0.718171926, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.5762659099084259}}
{"text": "#ifndef MLT_MODELS_IMPLEMENTATIONS_AUTOENCODER_HPP\n#define MLT_MODELS_IMPLEMENTATIONS_AUTOENCODER_HPP\n\n#include <limits>\n#include <tuple>\n\n#include <Eigen/Core>\n\n#include \"../../defs.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace implementations {\nnamespace autoencoder {\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\tauto loss(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, MatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\n\t\treturn (((reconstruction_activation.compute(reconstruction_z)) - target).array().pow(2).sum() / (2 * input.cols())) +\n\t\t\tregularization * hidden_weights.array().pow(2).sum() +\n\t\t\tregularization * reconstruction_weights.array().pow(2).sum();\n\t}\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\ttuple<MatrixXd, VectorXd, MatrixXd, VectorXd> \n\tgradient(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, MatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\t\tauto recontstruction_error = ((reconstruction_activation.compute(reconstruction_z) - target)).eval();\n\t\tauto reconstruction_delta = (recontstruction_error.cwiseProduct(reconstruction_activation.gradient(reconstruction_z))).eval();\n\n\t\tauto hidden_delta = ((reconstruction_weights.transpose() * reconstruction_delta).cwiseProduct(hidden_activation.gradient(hidden_z))).eval();\n\n\t\treturn{ (hidden_delta * input.transpose() / input.cols()) + regularization * 2 * hidden_weights,\n\t\t\thidden_delta.rowwise().sum() / input.cols(),\n\t\t\t(reconstruction_delta * hidden_a.transpose() / input.cols()) + regularization * 2 * reconstruction_weights,\n\t\t\treconstruction_delta.rowwise().sum() / input.cols() };\n\t}\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\ttuple<double, MatrixXd, VectorXd, MatrixXd, VectorXd>\n\tloss_and_gradient(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, MatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\t\tauto recontstruction_error = ((reconstruction_activation.compute(reconstruction_z) - target)).eval();\n\t\tauto reconstruction_delta = (recontstruction_error.cwiseProduct(reconstruction_activation.gradient(reconstruction_z))).eval();\n\n\t\tauto loss = (recontstruction_error.array().pow(2).sum() / (2 * input.cols())) +\n\t\t\tregularization * hidden_weights.array().pow(2).sum() +\n\t\t\tregularization * reconstruction_weights.array().pow(2).sum();\n\n\t\tauto hidden_delta = ((reconstruction_weights.transpose() * reconstruction_delta).cwiseProduct(hidden_activation.gradient(hidden_z))).eval();\n\n\t\treturn{ loss,\n\t\t\t(hidden_delta * input.transpose() / input.cols()) + regularization * 2 * hidden_weights,\n\t\t\thidden_delta.rowwise().sum() / input.cols(),\n\t\t\t(reconstruction_delta * hidden_a.transpose() / input.cols()) + regularization * 2 * reconstruction_weights,\n\t\t\treconstruction_delta.rowwise().sum() / input.cols() };\n\t}\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\tauto sparse_loss(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, double sparsity, double sparsity_weight,\n\tMatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\n\t\tauto rho_hat = ((hidden_a.rowwise().sum() / input.cols()).unaryExpr([](double x) { return abs(x - 1.0) < numeric_limits<double>::epsilon() ? (x + numeric_limits<double>::epsilon()) : x; })).eval();\n\t\tauto sparsity_penalty = ((sparsity * (sparsity / rho_hat.array()).log()) + ((1 - sparsity) * ((1 - sparsity) / (1 - rho_hat.array())).log())).sum();\n\n\t\treturn (((reconstruction_activation.compute(reconstruction_z)) - target).array().pow(2).sum() / (2 * input.cols())) +\n\t\t\tregularization * hidden_weights.array().pow(2).sum() +\n\t\t\tregularization * reconstruction_weights.array().pow(2).sum() +\n\t\t\tsparsity_weight * sparsity_penalty;\n\t}\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\ttuple<MatrixXd, VectorXd, MatrixXd, VectorXd>\n\tsparse_gradient(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, double sparsity, double sparsity_weight,\n\tMatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\t\tauto recontstruction_error = ((reconstruction_activation.compute(reconstruction_z) - target)).eval();\n\t\tauto reconstruction_delta = (recontstruction_error.cwiseProduct(reconstruction_activation.gradient(reconstruction_z))).eval();\n\n\t\tauto rho_hat = ((hidden_a.rowwise().sum() / input.cols()).unaryExpr([](double x) { return abs(x - 1.0) < numeric_limits<double>::epsilon() ? (x + numeric_limits<double>::epsilon()) : x; })).eval();\n\t\tauto sparsity_delta = ((-sparsity / rho_hat.array()) + ((1 - sparsity) / (1 - rho_hat.array()))).matrix().eval();\n\t\tauto hidden_delta = (((reconstruction_weights.transpose() * reconstruction_delta).colwise() +\n\t\t\t(sparsity_weight * sparsity_delta)).cwiseProduct(hidden_activation.gradient(hidden_z))).eval();\n\n\t\treturn{ (hidden_delta * input.transpose() / input.cols()) + regularization * 2 * hidden_weights,\n\t\t\thidden_delta.rowwise().sum() / input.cols(),\n\t\t\t(reconstruction_delta * hidden_a.transpose() / input.cols()) + regularization * 2 * reconstruction_weights,\n\t\t\treconstruction_delta.rowwise().sum() / input.cols() };\n\t}\n\n\ttemplate <class HiddenActivation, class ReconstructionActivation>\n\ttuple<double, MatrixXd, VectorXd, MatrixXd, VectorXd>\n\tsparse_loss_and_gradient(const HiddenActivation& hidden_activation, const ReconstructionActivation& reconstruction_activation,\n\tMatrixXdRef hidden_weights, VectorXdRef hidden_intercepts,\n\tMatrixXdRef reconstruction_weights, VectorXdRef reconstruction_intercepts,\n\tdouble regularization, double sparsity, double sparsity_weight,\n\tMatrixXdRef input, MatrixXdRef target) {\n\t\tauto hidden_z = ((hidden_weights * input).colwise() + hidden_intercepts).eval();\n\t\tauto hidden_a = (hidden_activation.compute(hidden_z)).eval();\n\t\tauto reconstruction_z = ((reconstruction_weights * hidden_a).colwise() + reconstruction_intercepts).eval();\n\t\tauto recontstruction_error = ((reconstruction_activation.compute(reconstruction_z) - target)).eval();\n\t\tauto reconstruction_delta = (recontstruction_error.cwiseProduct(reconstruction_activation.gradient(reconstruction_z))).eval();\n\n\t\tauto rho_hat = ((hidden_a.rowwise().sum() / input.cols()).unaryExpr([](double x) { return abs(x - 1.0) < numeric_limits<double>::epsilon() ? (x + numeric_limits<double>::epsilon()) : x; })).eval();\n\t\tauto sparsity_delta = ((-sparsity / rho_hat.array()) + ((1 - sparsity) / (1 - rho_hat.array()))).eval().matrix();\n\t\tauto hidden_delta = (((reconstruction_weights.transpose() * reconstruction_delta).colwise() +\n\t\t\t(sparsity_weight * sparsity_delta)).cwiseProduct(hidden_activation.gradient(hidden_z))).eval();\n\n\t\tauto loss = (recontstruction_error.array().pow(2).sum() / (2 * input.cols())) +\n\t\t\tregularization * hidden_weights.array().pow(2).sum() +\n\t\t\tregularization * reconstruction_weights.array().pow(2).sum() +\n\t\t\tsparsity_weight * ((sparsity * (sparsity / rho_hat.array()).log()) + ((1 - sparsity) * ((1 - sparsity) / (1 - rho_hat.array())).log())).sum();\n\n\t\treturn{ loss,\n\t\t\t(hidden_delta * input.transpose() / input.cols()) + regularization * 2 * hidden_weights,\n\t\t\thidden_delta.rowwise().sum() / input.cols(),\n\t\t\t(reconstruction_delta * hidden_a.transpose() / input.cols()) + regularization * 2 * reconstruction_weights,\n\t\t\treconstruction_delta.rowwise().sum() / input.cols() };\n\t}\n}\n}\n}\n}\n#endif", "meta": {"hexsha": "15d4ee77097dca2992624f5c9655cb0a93f70975", "size": 9476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/implementations/autoencoder.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/implementations/autoencoder.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/implementations/autoencoder.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": 63.1733333333, "max_line_length": 199, "alphanum_fraction": 0.7632967497, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5762659027745716}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n// The computeRoots function included in this is based on materials\n// covered by the following copyright and license:\n// \n// Geometric Tools, LLC\n// Copyright (c) 1998-2010\n// Distributed under the Boost Software License, Version 1.0.\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#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <bench/BenchTimer.h>\n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate<typename Matrix, typename Roots>\ninline void computeRoots(const Matrix& m, Roots& roots)\n{\n  typedef typename Matrix::Scalar Scalar;\n  const Scalar s_inv3 = 1.0/3.0;\n  const Scalar s_sqrt3 = internal::sqrt(Scalar(3.0));\n\n  // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0.  The\n  // eigenvalues are the roots to this equation, all guaranteed to be\n  // real-valued, because the matrix is symmetric.\n  Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1);\n  Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2);\n  Scalar c2 = m(0,0) + m(1,1) + m(2,2);\n\n  // Construct the parameters used in classifying the roots of the equation\n  // and in solving the equation for the roots in closed form.\n  Scalar c2_over_3 = c2*s_inv3;\n  Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3;\n  if (a_over_3 > Scalar(0))\n    a_over_3 = Scalar(0);\n\n  Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1));\n\n  Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3;\n  if (q > Scalar(0))\n    q = Scalar(0);\n\n  // Compute the eigenvalues by solving for the roots of the polynomial.\n  Scalar rho = internal::sqrt(-a_over_3);\n  Scalar theta = std::atan2(internal::sqrt(-q),half_b)*s_inv3;\n  Scalar cos_theta = internal::cos(theta);\n  Scalar sin_theta = internal::sin(theta);\n  roots(0) = c2_over_3 + Scalar(2)*rho*cos_theta;\n  roots(1) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta);\n  roots(2) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta);\n\n  // Sort in increasing order.\n  if (roots(0) >= roots(1))\n    std::swap(roots(0),roots(1));\n  if (roots(1) >= roots(2))\n  {\n    std::swap(roots(1),roots(2));\n    if (roots(0) >= roots(1))\n      std::swap(roots(0),roots(1));\n  }\n}\n\ntemplate<typename Matrix, typename Vector>\nvoid eigen33(const Matrix& mat, Matrix& evecs, Vector& evals)\n{\n  typedef typename Matrix::Scalar Scalar;\n  // Scale the matrix so its entries are in [-1,1].  The scaling is applied\n  // only when at least one matrix entry has magnitude larger than 1.\n\n  Scalar scale = mat.cwiseAbs()/*.template triangularView<Lower>()*/.maxCoeff();\n  scale = std::max(scale,Scalar(1));\n  Matrix scaledMat = mat / scale;\n\n  // Compute the eigenvalues\n//   scaledMat.setZero();\n  computeRoots(scaledMat,evals);\n\n  // compute the eigen vectors\n  // **here we assume 3 differents eigenvalues**\n\n  // \"optimized version\" which appears to be slower with gcc!\n//     Vector base;\n//     Scalar alpha, beta;\n//     base <<   scaledMat(1,0) * scaledMat(2,1),\n//               scaledMat(1,0) * scaledMat(2,0),\n//              -scaledMat(1,0) * scaledMat(1,0);\n//     for(int k=0; k<2; ++k)\n//     {\n//       alpha = scaledMat(0,0) - evals(k);\n//       beta  = scaledMat(1,1) - evals(k);\n//       evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized();\n//     }\n//     evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized();\n\n//   // naive version\n//   Matrix tmp;\n//   tmp = scaledMat;\n//   tmp.diagonal().array() -= evals(0);\n//   evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized();\n// \n//   tmp = scaledMat;\n//   tmp.diagonal().array() -= evals(1);\n//   evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized();\n// \n//   tmp = scaledMat;\n//   tmp.diagonal().array() -= evals(2);\n//   evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized();\n  \n  // a more stable version:\n  if((evals(2)-evals(0))<=Eigen::NumTraits<Scalar>::epsilon())\n  {\n    evecs.setIdentity();\n  }\n  else\n  {\n    Matrix tmp;\n    tmp = scaledMat;\n    tmp.diagonal ().array () -= evals (2);\n    evecs.col (2) = tmp.row (0).cross (tmp.row (1)).normalized ();\n    \n    tmp = scaledMat;\n    tmp.diagonal ().array () -= evals (1);\n    evecs.col(1) = tmp.row (0).cross(tmp.row (1));\n    Scalar n1 = evecs.col(1).norm();\n    if(n1<=Eigen::NumTraits<Scalar>::epsilon())\n      evecs.col(1) = evecs.col(2).unitOrthogonal();\n    else\n      evecs.col(1) /= n1;\n    \n    // make sure that evecs[1] is orthogonal to evecs[2]\n    evecs.col(1) = evecs.col(2).cross(evecs.col(1).cross(evecs.col(2))).normalized();\n    evecs.col(0) = evecs.col(2).cross(evecs.col(1));\n  }\n  \n  // Rescale back to the original size.\n  evals *= scale;\n}\n\nint main()\n{\n  BenchTimer t;\n  int tries = 10;\n  int rep = 400000;\n  typedef Matrix3f Mat;\n  typedef Vector3f Vec;\n  Mat A = Mat::Random(3,3);\n  A = A.adjoint() * A;\n\n  SelfAdjointEigenSolver<Mat> eig(A);\n  BENCH(t, tries, rep, eig.compute(A));\n  std::cout << \"Eigen:  \" << t.best() << \"s\\n\";\n\n  Mat evecs;\n  Vec evals;\n  BENCH(t, tries, rep, eigen33(A,evecs,evals));\n  std::cout << \"Direct: \" << t.best() << \"s\\n\\n\";\n\n  std::cerr << \"Eigenvalue/eigenvector diffs:\\n\";\n  std::cerr << (evals - eig.eigenvalues()).transpose() << \"\\n\";\n  for(int k=0;k<3;++k)\n    if(evecs.col(k).dot(eig.eigenvectors().col(k))<0)\n      evecs.col(k) = -evecs.col(k);\n  std::cerr << evecs - eig.eigenvectors() << \"\\n\\n\";\n}\n", "meta": {"hexsha": "1608b999d0b7699ce2cab6f6f7046c8a602e553a", "size": 7125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/Eigen/bench/eig33.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "SCA/eigen_332/bench/eig33.cpp", "max_issues_repo_name": "JooseRajamaeki/TVCG18", "max_issues_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "SCA/eigen_332/bench/eig33.cpp", "max_forks_repo_name": "JooseRajamaeki/TVCG18", "max_forks_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 36.1675126904, "max_line_length": 137, "alphanum_fraction": 0.6526315789, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5762658866453265}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// Polygon Example\n\n#include <algorithm> // for reverse, unique\n#include <iostream>\n#include <string>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\n\nstd::string boolstr(bool v)\n{\n    return v ? \"true\" : \"false\";\n}\n\nint main(void)\n{\n    using namespace boost::geometry;\n\n    typedef model::d2::point_xy<double> point_2d;\n    typedef model::polygon<point_2d> polygon_2d;\n    typedef model::box<point_2d> box_2d;\n\n    // Define a polygon and fill the outer ring.\n    // In most cases you will read it from a file or database\n    polygon_2d poly;\n    {\n        const double coor[][2] = {\n            {2.0, 1.3}, {2.4, 1.7}, {2.8, 1.8}, {3.4, 1.2}, {3.7, 1.6},\n            {3.4, 2.0}, {4.1, 3.0}, {5.3, 2.6}, {5.4, 1.2}, {4.9, 0.8}, {2.9, 0.7},\n            {2.0, 1.3} // closing point is opening point\n            };\n        assign_points(poly, coor);\n    }\n\n    // Polygons should be closed, and directed clockwise. If you're not sure if that is the case,\n    // call the correct algorithm\n    correct(poly);\n\n    // Polygons can be streamed as text\n    // (or more precisely: as DSV (delimiter separated values))\n    std::cout << dsv(poly) << std::endl;\n\n    // As with lines, bounding box of polygons can be calculated\n    box_2d b;\n    envelope(poly, b);\n    std::cout << dsv(b) << std::endl;\n\n    // The area of the polygon can be calulated\n    std::cout << \"area: \" << area(poly) << std::endl;\n\n    // And the centroid, which is the center of gravity\n    point_2d cent;\n    centroid(poly, cent);\n    std::cout << \"centroid: \" << dsv(cent) << std::endl;\n\n\n    // The number of points can be requested per ring (using .size())\n    // or per polygon (using num_points)\n    std::cout << \"number of points in outer ring: \" << poly.outer().size() << std::endl;\n\n    // Polygons can have one or more inner rings, also called holes, islands, interior rings.\n    // Let's add one\n    {\n        poly.inners().resize(1);\n        model::ring<point_2d>& inner = poly.inners().back();\n\n        const double coor[][2] = { {4.0, 2.0}, {4.2, 1.4}, {4.8, 1.9}, {4.4, 2.2}, {4.0, 2.0} };\n        assign_points(inner, coor);\n    }\n\n    correct(poly);\n\n    std::cout << \"with inner ring:\" << dsv(poly) << std::endl;\n    // The area of the polygon is changed of course\n    std::cout << \"new area of polygon: \" << area(poly) << std::endl;\n    centroid(poly, cent);\n    std::cout << \"new centroid: \" << dsv(cent) << std::endl;\n\n    // You can test whether points are within a polygon\n    std::cout << \"point in polygon:\"\n        << \" p1: \"  << boolstr(within(make<point_2d>(3.0, 2.0), poly))\n        << \" p2: \"  << boolstr(within(make<point_2d>(3.7, 2.0), poly))\n        << \" p3: \"  << boolstr(within(make<point_2d>(4.4, 2.0), poly))\n        << std::endl;\n\n    // As with linestrings and points, you can derive from polygon to add, for example,\n    // fill color and stroke color. Or SRID (spatial reference ID). Or Z-value. Or a property map.\n    // We don't show this here.\n\n    // Clip the polygon using a box\n    box_2d cb(make<point_2d>(1.5, 1.5), make<point_2d>(4.5, 2.5));\n    typedef std::vector<polygon_2d> polygon_list;\n    polygon_list v;\n\n    intersection(cb, poly, v);\n    std::cout << \"Clipped output polygons\" << std::endl;\n    for (polygon_list::const_iterator it = v.begin(); it != v.end(); ++it)\n    {\n        std::cout << dsv(*it) << std::endl;\n    }\n\n    typedef model::multi_polygon<polygon_2d> polygon_set;\n    polygon_set ps;\n    union_(cb, poly, ps);\n\n    polygon_2d hull;\n    convex_hull(poly, hull);\n    std::cout << \"Convex hull:\" << dsv(hull) << std::endl;\n\n    // If you really want:\n    //   You don't have to use a vector, you can define a polygon with a deque\n    //   You can specify the container for the points and for the inner rings independantly\n\n    typedef model::polygon<point_2d, true, true, std::deque, std::deque> deque_polygon;\n    deque_polygon poly2;\n    ring_type<deque_polygon>::type& ring = exterior_ring(poly2);\n    append(ring, make<point_2d>(2.8, 1.9));\n    append(ring, make<point_2d>(2.9, 2.4));\n    append(ring, make<point_2d>(3.3, 2.2));\n    append(ring, make<point_2d>(3.2, 1.8));\n    append(ring, make<point_2d>(2.8, 1.9));\n    std::cout << dsv(poly2) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "3b962ce01c3c98c3281c2c4273545f7f62aeb963", "size": 4911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/geometry/example/03_polygon_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/geometry/example/03_polygon_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/geometry/example/03_polygon_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 34.5845070423, "max_line_length": 98, "alphanum_fraction": 0.6239055182, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.5761081635194357}}
{"text": "/*\n * AttitudeESKF.cpp\n *\n *  Copyright (c) 2013 Gareth Cross. Apache 2 License.\n *\n *  This file is part of kr_attitude_eskf.\n *\n *\tCreated on: 12/24/2013\n *\t\t  Author: gareth\n */\n\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n#include \"AttitudeESKF.hpp\"\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <iostream>\n#include <cmath>\n\nusing namespace Eigen;\n\nnamespace kr {\n\n//\tskew symmetric matrix\ntemplate <typename T>\nstatic inline Matrix<T, 3, 3> crossSkew(const Matrix<T, 3, 1> &w) {\n  Matrix<T, 3, 3> W;\n\n  W(0, 0) = 0;\n  W(0, 1) = -w(2);\n  W(0, 2) = w(1);\n\n  W(1, 0) = w(2);\n  W(1, 1) = 0;\n  W(1, 2) = -w(0);\n\n  W(2, 0) = -w(1);\n  W(2, 1) = w(0);\n  W(2, 2) = 0;\n\n  return W;\n}\n\n//\thardcoded 3x3 invert (unchecked)\ntemplate <typename T>\nstatic inline Matrix<T, 3, 3> invert(const Matrix<T, 3, 3> &A, T det) {\n  Matrix<T, 3, 3> C;\n  det = 1 / det;\n\n  C(0, 0) = (-A(2, 1) * A(1, 2) + A(1, 1) * A(2, 2)) * det;\n  C(0, 1) = (-A(0, 1) * A(2, 2) + A(0, 2) * A(2, 1)) * det;\n  C(0, 2) = (A(0, 1) * A(1, 2) - A(0, 2) * A(1, 1)) * det;\n\n  C(1, 0) = (A(2, 0) * A(1, 2) - A(1, 0) * A(2, 2)) * det;\n  C(1, 1) = (-A(2, 0) * A(0, 2) + A(0, 0) * A(2, 2)) * det;\n  C(1, 2) = (A(1, 0) * A(0, 2) - A(0, 0) * A(1, 2)) * det;\n\n  C(2, 0) = (-A(2, 0) * A(1, 1) + A(1, 0) * A(2, 1)) * det;\n  C(2, 1) = (A(2, 0) * A(0, 1) - A(0, 0) * A(2, 1)) * det;\n  C(2, 2) = (-A(1, 0) * A(0, 1) + A(0, 0) * A(1, 1)) * det;\n\n  return C;\n}\n\n//\thardcoded determinant\ntemplate <typename T> static inline T determinant(const Matrix<T, 3, 3> &A) {\n  return A(0, 0) * (A(1, 1) * A(2, 2) - A(1, 2) * A(2, 1)) -\n         A(0, 1) * (A(1, 0) * A(2, 2) - A(1, 2) * A(2, 0)) +\n         A(0, 2) * (A(1, 0) * A(2, 1) - A(1, 1) * A(2, 0));\n}\n\n//  Eigen does not define these operators, which we use for integration\ntemplate <typename Scalar>\nstatic inline Eigen::Quaternion<Scalar> operator + (const Eigen::Quaternion<Scalar>& a,\n                                      const Eigen::Quaternion<Scalar>& b) {\n  return Eigen::Quaternion<Scalar>(a.w()+b.w(),\n                                   a.x()+b.x(),\n                                   a.y()+b.y(),\n                                   a.z()+b.z());\n}\n\ntemplate <typename Scalar>\nstatic inline Eigen::Quaternion<Scalar> operator * (const Eigen::Quaternion<Scalar>& q,\n                                      Scalar s) {\n  return Eigen::Quaternion<Scalar>(q.w() * s,\n                                   q.x() * s,\n                                   q.y() * s,\n                                   q.z() * s);\n}\n\n/**\n *  @brief Integrate a rotation quaterion using Euler integration\n *  @param q Quaternion to integrate\n *  @param w Angular velocity (body frame), stored in 3 complex terms\n *  @param dt Time interval in seconds\n *  @param normalize If True, quaternion is normalized after integration\n */\ntemplate <typename Scalar>\nstatic inline void integrateEuler(Eigen::Quaternion<Scalar> &q, Eigen::Quaternion<Scalar> &w, Scalar dt,\n                    bool normalize = true) {\n  q = q + (q * w * static_cast<Scalar>(0.5)) * dt;\n\n  if (normalize) {\n    q.normalize();\n  }\n}\n\n/**\n *  @brief Integrate a rotation quaternion using 4th order Runge Kutta\n *  @param q Quaternion to integrate\n *  @param w Angular velocity (body frame), stored in 3 complex terms\n *  @param dt Time interval in seconds\n *  @param normalize If true, quaternion is normalized after integration\n */\ntemplate <typename Scalar>\nstatic inline void integrateRungeKutta4(Eigen::Quaternion<Scalar> &q, const Eigen::Quaternion<Scalar> &w, Scalar dt,\n                          bool normalize = true) {\n  const static Scalar half = static_cast<Scalar>(0.5);\n  const static Scalar two = static_cast<Scalar>(2);\n\n  Eigen::Quaternion<Scalar> qw = q * w * half;\n  Eigen::Quaternion<Scalar> k2 = (q + qw * dt * half) * w * half;\n  Eigen::Quaternion<Scalar> k3 = (q + k2 * dt * half) * w * half;\n  Eigen::Quaternion<Scalar> k4 = (q + k3 * dt) * w * half;\n\n  q = q + (qw + k2 * two + k3 * two + k4) * (dt / 6);\n\n  if (normalize) {\n    q.normalize();\n  }\n}\n\ntemplate <typename Scalar>\nstatic inline Eigen::Matrix<Scalar,3,3> \nrodrigues(const Eigen::Matrix<Scalar,3,1>& w) {\n  const auto norm = w.norm();\n  if (norm < std::numeric_limits<Scalar>::epsilon()*10) {\n    return Eigen::Matrix<Scalar,3,3>::Identity() + crossSkew(w);\n  }\n  return Eigen::AngleAxis<Scalar>(norm, w / norm).matrix();\n}\n\nAttitudeESKF::AttitudeESKF()\n    : q_(1,0,0,0), steadyCount_(0), biasThresh_(0), isStable_(true) {\n  P_.setZero();\n  b_.setZero();\n  w_.setZero();\n  dx_.setZero();\n\n  magRef_.setZero();\n  predMag_.setZero();\n\n  estBias_ = false;\n  ignoreZ_ = false;\n  useMag_ = false;\n}\n\nvoid AttitudeESKF::predict(const AttitudeESKF::vec3 &wb,\n                           AttitudeESKF::scalar_t dt, \n                           const AttitudeESKF::mat3 &cov,\n                           bool useRK4) {\n  static const Matrix<scalar_t, 3, 3> I3 =\n      Matrix<scalar_t, 3, 3>::Identity(); //  identity R3\n\n  scalar_t wb2 = wb[0] * wb[0] + wb[1] * wb[1] + wb[2] * wb[2];\n  if (wb2 < biasThresh_ * biasThresh_) {\n    steadyCount_++; //  not rotating, update moving average\n\n    if (estBias_ && steadyCount_ > 20) {\n      b_ = (b_ * (steadyCount_ - 1) + wb) / steadyCount_;\n    }\n  } else {\n    steadyCount_ = 0;\n  }\n\n  w_ = (wb - b_); //\ttrue gyro reading\n\n  //\terror-state jacobian\n  const Matrix<scalar_t, 3, 3> F = I3 - crossSkew<scalar_t>(w_ * dt);\n\n  //  integrate state and covariance\n  Eigen::Quaternion<scalar_t> wQuat(0, w_[0], w_[1], w_[2]);\n  if (!useRK4) {\n    integrateEuler(q_, wQuat, dt, true);\n  } else {\n    integrateRungeKutta4(q_, wQuat, dt, true);\n  }\n\n  //  noise jacobian\n  const Matrix <scalar_t,3,3> G = -I3 * dt;\n  P_ = F*P_*F.transpose() + G*cov*G.transpose();\n}\n\nvoid AttitudeESKF::update(const AttitudeESKF::vec3 &ab, \n                          const mat3 &aCov, \n                          const AttitudeESKF::vec3 &mb, \n                          const mat3 &mCov) {\n  Matrix<scalar_t, 3, 3> A;\n\n  //  rotation matrix: world -> body\n  const Matrix<scalar_t, 3, 3> bRw = q_.conjugate().matrix();\n\n  vec3 gravity;\n  gravity[0] = 0.0;\n  gravity[1] = 0.0;\n  gravity[2] = kOneG;\n\n  //  predicted gravity vector\n  const vec3 aPred = bRw * gravity;\n\n  if (!useMag_) {\n    //  calculate jacobian\n    Matrix<scalar_t, 3, 3> H = crossSkew(aPred);\n    Matrix<scalar_t, 3, 1> r = ab - aPred;\n\n    //  solve for the kalman gain\n    const Matrix<scalar_t, 3, 3> S = H * P_ * H.transpose() + aCov;\n    Matrix<scalar_t, 3, 3> Sinv;\n\n    const scalar_t det = determinant(S);\n    if (std::abs(det) < static_cast<scalar_t>(1e-5)) {\n      isStable_ = false;\n      return;\n    } else {\n      isStable_ = true;\n    }\n    Sinv = invert(S, det);\n\n    const Matrix<scalar_t, 3, 3> K = P_ * H.transpose() * Sinv;\n\n    A = K * H;\n    dx_ = K * r;\n  }\n  else {\n#ifdef ATTITUDE_ESKF_BUILD_MAG  //  stop compilation of FullPivLU\n    //  m-field prediction\n    vec3 field = bRw * magRef_;\n    predMag_ = field;\n    \n    Matrix<scalar_t, 6, 1> r;\n    r.block<3, 1>(0, 0) = ab - aPred;\n    r.block<3, 1>(3, 0) = mb - field;\n\n    Matrix<scalar_t, 6, 3> H;\n    H.setZero();\n\n    //  jacobians for gravity and magnetic field\n    H.block<3, 3>(0, 0) = crossSkew(aPred);\n    H.block<3, 3>(3, 0) = crossSkew(field);\n\n    //  covariance for both sensors\n    Matrix<scalar_t, 6, 6> covR;\n    covR.setZero();\n    covR.block<3,3>(0,0) = aCov;\n    covR.block<3,3>(3,3) = mCov;\n\n    const Matrix<scalar_t, 6, 6> S = H * P_ * H.transpose() + covR;\n    Matrix<scalar_t, 6, 6> Sinv;\n\n    Eigen::FullPivLU<Matrix<scalar_t,6,6>> LU(S);\n    isStable_ = LU.isInvertible();\n\n    if (!isStable_) {\n      return;\n    }\n    Sinv = LU.inverse();\n\n    //  generate update\n    const Matrix<scalar_t, 3, 6> K = P_ * H.transpose() * Sinv;\n    dx_ = K * r;\n    A = K * H;\n#else\n    dx_.setZero();\n    A.setZero();\n#endif\n  }\n  \n  if (ignoreZ_) {\n    //  cancel body-frame z update\n    dx_[2] = 0;\n  }\n\n  //  perform state update\n  P_ = (Matrix<scalar_t, 3, 3>::Identity() - A) * P_;\n\n  q_ = q_ * quat(1, dx_[0]/2, dx_[1]/2, dx_[2]/2);\n  q_.normalize();\n}\n  \nvoid AttitudeESKF::externalYawUpdate(scalar_t yaw, scalar_t alpha) {\n  //  check if we are near the hover state\n  const Matrix<scalar_t,3,3> wRb = q_.matrix();\n  Matrix<scalar_t,3,1> g;\n  g[0] = 0;\n  g[1] = 0;\n  g[2] = 1;\n  \n  g = wRb.transpose() * g;\n  if (g[2] > 0.85) {\n    //  break into roll pitch yaw\n    Matrix<scalar_t,3,1> rpy = getRPY(wRb);\n    //  interpolate between prediction and estimate\n    rpy[2] = rpy[2]*(1-alpha) + yaw*alpha;\n    q_ = Eigen::AngleAxis<scalar_t>(rpy[2],vec3(0,0,1)) *\n    Eigen::AngleAxis<scalar_t>(rpy[1],vec3(0,1,0)) *\n    Eigen::AngleAxis<scalar_t>(rpy[0],vec3(1,0,0));\n  }\n}\n\nbool AttitudeESKF::initialize(const vec3 &ab,\n                              const vec3 &aCov,\n                              const vec3 &mb,\n                              const vec3 &mCov) {\n  if (!useMag_) {\n    //  determine attitude angles\n    scalar_t ay = ab[1];\n    if (ay > kOneG) { ay = kOneG; }\n    else if (ay < -kOneG) { ay = -kOneG; }\n    const scalar_t& ax = ab[0];\n    const scalar_t& az = ab[2]; \n    \n    const scalar_t phi = std::asin(-ay / kOneG);  //  roll\n    const scalar_t theta = std::atan2(ax, az);    //  pitch\n  \n    q_ = Eigen::AngleAxis<scalar_t>(theta, vec3(0,1,0)) * \n         Eigen::AngleAxis<scalar_t>(phi, vec3(1,0,0));\n  }\n  else {\n    ///  @todo: This is kind of ugly, find some simpler mechanism to do this.\n    \n#ifdef ATTITUDE_ESKF_BUILD_MAG\n    const static scalar_t eps(1e-6);\n    for (int i=0; i < 3; i++) {\n      if (aCov[i] < eps || mCov[i] < eps) {\n        return false;\n      }\n    }\n    //  jacobian\n    Eigen::Matrix <scalar_t,6,3> J;\n    J.block<3,3>(0,0) = crossSkew(ab);\n    J.block<3,3>(3,0) = crossSkew(mb);\n    \n    //  weight matrix\n    Eigen::Matrix <scalar_t,6,6> S;\n    S.setZero();\n    for (int i=0; i < 3; i++) {\n      S(i,i) = 1 / aCov[i];\n      S(i+3,i+3) = 1 / mCov[i];\n    }\n    \n    //  hessian\n    const mat3 H = J.transpose() * S * J;\n    const Eigen::LDLT<mat3> ldlt(H);\n    \n    //  optimize\n    vec3 w(0,0,0);\n    Matrix<scalar_t,6,1> r;\n    for (unsigned int iter=0; iter < 5; iter++) {\n      const mat3 W = rodrigues(w);\n      //  residuals\n      r.block<3,1>(0,0) = (W * vec3(0,0,kOneG)) - ab;\n      r.block<3,1>(3,0) = (W * magRef_) - mb;\n      //  step\n      w.noalias() += ldlt.solve(J.transpose() * S * r);\n    }\n    q_ = quat(rodrigues(w).transpose());\n#endif\n  }\n  //  start w/ a large uncertainty\n  P_.setIdentity();\n  P_ *= M_PI*M_PI;\n  \n  return true;\n}\n  \nAttitudeESKF::vec3 AttitudeESKF::getRPY(const mat3& R) {\n  vec3 rpy;\n  scalar_t sth = -R(2, 0);\n  if (sth > 1) {\n    sth = 1;\n  } else if (sth < -1) {\n    sth = -1;\n  }\n  \n  const scalar_t theta = std::asin(sth);\n  const scalar_t cth = std::sqrt(1 - sth*sth);\n  \n  scalar_t phi, psi;\n  if (cth < static_cast<scalar_t>(1.0e-6)) {\n    phi = std::atan2(R(0, 1), R(1, 1));\n    psi = 0;\n  } else {\n    phi = std::atan2(R(2, 1), R(2, 2));\n    psi = std::atan2(R(1, 0), R(0, 0));\n  }\n  \n  rpy[0] = phi;    //  x, [-pi,pi]\n  rpy[1] = theta;  //  y, [-pi/2,pi/2]\n  rpy[2] = psi;    //  z, [-pi,pi]\n  return rpy;\n}\n\n} //  namespace kr\n\n", "meta": {"hexsha": "4a9eb142c176fe53af6051bd6ecf2a069df46174", "size": 11129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/AttitudeESKF.cpp", "max_stars_repo_name": "CTSHEN/kr_attitude_eskf", "max_stars_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T00:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T02:06:01.000Z", "max_issues_repo_path": "src/AttitudeESKF.cpp", "max_issues_repo_name": "jackiecx/kr_attitude_eskf", "max_issues_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-13T08:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-13T08:37:35.000Z", "max_forks_repo_path": "src/AttitudeESKF.cpp", "max_forks_repo_name": "jackiecx/kr_attitude_eskf", "max_forks_repo_head_hexsha": "f64d6bf5f4b5b91d7ac14093dbe88471c27976a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-01-25T09:53:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T21:20:31.000Z", "avg_line_length": 27.343980344, "max_line_length": 116, "alphanum_fraction": 0.5449725941, "num_tokens": 4076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5760858841901424}}
{"text": "#include <iostream>\n#include <functional>   \n#include <numeric> \n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <map>\n#include <Eigen\\dense>\n\n#include \"markov.h\"\n#include \"TransitionMatrix.h\"\n\n\n// Hint: Set N - number of simulations low until you have it working\n//       Then set it much much higher, and run in release mode so its faster\n\nint main() {\n\n\tSetTransitionMatrix();\n\tsetGameMatrix();\n\t// Print Results to File\n\tstd::ofstream myfile;\n\tmyfile.open(\"dtmc_results.txt\");\n\n\tint start = 0;\n\n\t//simulate discrete time Markov Chain\n\tunsigned int N = 100;\n\tstd::map<int, int> hist;\n\t\n\tstd::vector<int> discreteMC;\n\t//std::vector< std::vector<double> > matrix(3, std::vector<double>(3)); //initializes a 3x3 matrix with zeros\n\tfor (unsigned int i = 0; i < N; ++i) {\n\t\t\n\t\t//TODO (add DTMC, and histogram lines.)\n\t\tdiscreteMC = DTMC(TransitionMatrix,ROLLS,start);\n\t\t++hist[std::round(discreteMC.back())];\n\t\tint counter = 0;\n\t\t// Code if you wanted to print out results at each step\n\t\tfor (auto elem : discreteMC) {\n\t\t\tif (elem < 100) counter++;\n\t\t\tstd::cout << elem << std::endl;\n\t\t\tstd::cout << counter << std::endl;\n\t\t\tmyfile << elem << std::endl;\n\t\t\tmyfile << counter << std::endl;\n\t\t\t\n\t\t}\n\t\tstd::cout << \"****New Game*****\" << i << std::endl;\n\t\tmyfile << \"******New Game*******\" << std::endl;\n\t}\n\t//Returns an array discreteMC with the states at each step of the discrete-time Markov Chain\n\t//The number of transitions is given by steps. The initial state is given by start \n\t//(the states are indexed from 0 to n-1 where n is the number of arrays in transMatrix).\n\t//hist is the histogram \n\n\n\t// (double)p.second / N    - (decimal) percentage.\n\tfor (auto p : hist) {\n\t\tstd::cout << p.first << \"\\t\" << (double)p.second / N << std::endl;\n\t}\n\n\tmyfile.close();\n\n\treturn 1;\n}", "meta": {"hexsha": "015cd4124b0e6af552d309efca8b6095d6e6d9a6", "size": 1796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SnakesAndLadders/test_dtmc.cpp", "max_stars_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_stars_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SnakesAndLadders/test_dtmc.cpp", "max_issues_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_issues_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SnakesAndLadders/test_dtmc.cpp", "max_forks_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_forks_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_forks_repo_licenses": ["Apache-2.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.6307692308, "max_line_length": 110, "alphanum_fraction": 0.6503340757, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.576085874635529}}
{"text": "/***************************************************************************\n *   Copyright (C) 2016 by Саша Миленковић                                 *\n *   sasa.milenkovic.xyz@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 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; 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 *   ( http://www.gnu.org/licenses/gpl-3.0.en.html )                       *\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 <Eigen/Dense>\n#include <cmath>\n#include \"quartic.hpp\"\nconst double PI = 3.141592653589793238463L;\nconst double M_2PI = 2*PI;\nconst double eps=1e-12;\n\n//---------------------------------------------------------------------------\n// solve cubic equation x^3 + a*x^2 + b*x + c\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\ninline unsigned int solveP3(double *x,double a,double b,double c) {\n\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+M_2PI)/3)-a;\n            x[2]=q*cos((t-M_2PI)/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 = (0==A ? 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])<eps) { x[2]=x[1]; return 2; }\n\n        return 1;\n        }\n}\n\n//---------------------------------------------------------------------------\n// solve quartic equation x^4 + a*x^3 + b*x^2 + c*x + d\nEigen::Vector4cd solve_quartic(double a, double b, double c, double d)\n{\n    double a3 = -b;\n    double b3 =  a*c -4.*d;\n    double c3 = -a*a*d - c*c + 4.*b*d;\n\n    // cubic resolvent\n    // y^3 − b*y^2 + (ac−4d)*y − a^2*d−c^2+4*b*d = 0\n\n    double x3[3];\n    unsigned int iZeroes = solveP3(x3, a3, b3, c3);\n\n    double q1, q2, p1, p2, D, sqD, y;\n\n    y = x3[0];\n    // THE ESSENCE - choosing Y with maximal absolute value !\n    if(iZeroes != 1)\n    {\n        if(fabs(x3[1]) > fabs(y)) y = x3[1];\n        if(fabs(x3[2]) > fabs(y)) y = x3[2];\n    }\n\n    // h1+h2 = y && h1*h2 = d  <=>  h^2 -y*h + d = 0    (h === q)\n\n    D = y*y - 4*d;\n    if(fabs(D) < eps) //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*(b-y);\n        if(fabs(D) < eps) //in other words - D==0\n            p1 = p2 = a * 0.5;\n\n        else\n        {\n            sqD = sqrt(D);\n            p1 = (a + sqD) * 0.5;\n            p2 = (a - sqD) * 0.5;\n        }\n    }\n    else\n    {\n        sqD = sqrt(D);\n        q1 = (y + sqD) * 0.5;\n        q2 = (y - sqD) * 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    Eigen::Vector4cd retval;\n    std::complex<double> tmp;\n    // solving quadratic eq. - x^2 + p1*x + q1 = 0\n    D = p1*p1 - 4*q1;\n    if(D < 0.0)\n    {\n        tmp.real( -p1 * 0.5 );\n        tmp.imag( sqrt(-D) * 0.5 );\n        retval[0] = tmp;\n        tmp = std::conj(tmp);\n        retval[1] = tmp;\n    }\n    else\n    {\n        tmp.imag(0);\n        sqD = sqrt(D);\n        tmp.real( (-p1 + sqD) * 0.5 );\n        retval[0] = tmp;\n        tmp.real( (-p1 - sqD) * 0.5 );\n        retval[1] = tmp;\n    }\n\n    // solving quadratic eq. - x^2 + p2*x + q2 = 0\n    D = p2*p2 - 4*q2;\n    if(D < 0.0)\n    {\n        tmp.real( -p2 * 0.5 );\n        tmp.imag( sqrt(-D) * 0.5 );\n        retval[2] = tmp;\n        tmp = std::conj(tmp);\n        retval[3] = tmp;\n    }\n    else\n    {\n        tmp.imag(0);\n        sqD = sqrt(D);\n        tmp.real( (-p2 + sqD) * 0.5 );\n        retval[2] = tmp;\n        tmp.real( (-p2 - sqD) * 0.5 );\n        retval[3] = tmp;\n    }\n\n    return retval;\n}\n", "meta": {"hexsha": "544e30d39b5350e2c6bd84cf7261f0a56db9d54a", "size": 5140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helpers/quartic.cpp", "max_stars_repo_name": "marcusvaltonen/DronePoseLib", "max_stars_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T09:35:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T13:41:20.000Z", "max_issues_repo_path": "src/helpers/quartic.cpp", "max_issues_repo_name": "marcusvaltonen/DronePoseLib", "max_issues_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-23T17:25:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T11:21:44.000Z", "max_forks_repo_path": "src/helpers/quartic.cpp", "max_forks_repo_name": "marcusvaltonen/DronePoseLib", "max_forks_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-23T17:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T19:04:59.000Z", "avg_line_length": 30.9638554217, "max_line_length": 77, "alphanum_fraction": 0.4003891051, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5760238718429177}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n//! [remquo]\n#include <boost/simd/arithmetic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/constant/valmax.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 4>;\nusing pack_it =  bs::pack <std::int32_t, 4>;\n\nint main()\n{\n  pack_ft xf = { 3.0f, -2.0f, -3.0f, 1.0f };\n  pack_ft yf = { 4.0f, -1.0f, -3.0f, 2.0f };\n  pack_ft rf;\n  pack_it qi;\n  std::tie(rf, qi) = bs::remquo(xf, yf);\n\n  std::cout\n    <<  \"---- simd:  std::tie(xf, yf) = bs::remquo(xf, yf)\\n\"\n    << \" <- xf = \" << xf << '\\n'\n    << \" <- yf = \" << yf << '\\n'\n    << \" -> rf = \" << rf << '\\n'\n    << \" -> qi = \" << qi << '\\n';\n\n  float sxf = 3.0f, syf = 4.0f;\n  float srf;\n  std::int32_t sqi;\n  std::tie(srf, sqi) = bs::remquo(sxf, syf);\n\n  std::cout\n    << \"---- scalar: std::tie(srf, sqi) = bs::remquo(sxf, syf)\\n\"\n    << \" <- sxf =  \" << sxf << '\\n'\n    << \" <- syf =  \" << syf << '\\n'\n    << \" -> srf = \" << srf << '\\n'\n    << \" -> sqi = \" << sqi << '\\n';\n  return 0;\n}\n//! [remquo]\n", "meta": {"hexsha": "6bd56c92babd249848396900fd9ecfaf779b6188", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/arithmetic/remquo.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/doc/arithmetic/remquo.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/doc/arithmetic/remquo.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 28.7083333333, "max_line_length": 100, "alphanum_fraction": 0.4361393324, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.5760238579922873}}
{"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\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#define PI (3.141592653589793)\n\n////////////////////////////////////////////////////////////////////////////\n// Auxiliar functions\n\nvoid pi2pi(double &angle)\n{\n\tdouble ang;\n    /* Process angle*/     \n    if( (angle < -2*PI) ||  (angle > 2* PI) ) \n\t\tang = fmod(angle, 2*PI); \n    else \n        ang = angle;\n    if (ang > PI) ang = ang - 2*PI;\n    if (ang < -PI) ang = ang + 2*PI;    \n    angle = ang;    \n}\n\n////////////////////////////////////////////////////////////////////////////\n\nCHOMP_SE2::CHOMP_SE2(double dt_input, double eta_input, double lambda_input, size_t nq_input, size_t numIt_input, double gain) : \nCHOMP(dt_input, eta_input, lambda_input, nq_input, 3, numIt_input, gain) \n{\t\n\tcout << \"-----------------------------------------------------:\"<< endl;  \t\t  \t\n\tcout << \"CHOMP SE2 started \"<< endl;  \n\tcout << \"-----------------------------------------------------:\"<< endl;  \t  \t\n}\n\n\nvoid CHOMP_SE2::boundTrajectoryAngles (void)\n{\n\tfor (size_t iq (0); iq < nq_; ++iq) \n\t{\t  \t   \n\t\t//Makes the angles to be between Pi to -Pi\t   \n\t\tVector q (xi_.block  (iq * cdim_, 0, cdim_, 1) ); \n\t\tpi2pi ( q(2) );\n\t\txi_.block  (iq * cdim_, 0, cdim_, 1) = q;\n\t}\n}\n\nvoid CHOMP_SE2::boundVectorAngles (Vector& VV)\n{\t \n    static size_t const VVsize = \t(VV.size()/cdim_) - 1;\t\n\tfor (size_t iq (0); iq < VVsize; ++iq) \n\t{\n\t\t//Makes the angles to be between Pi to -Pi\t   \n\t\tVector q (VV.block  (iq * cdim_, 0, cdim_, 1) ); \n\t\tpi2pi ( q(2));\n\t\tVV.block  (iq * cdim_, 0, cdim_, 1) = q;\n\t}\n}\n\ndouble CHOMP_SE2::chompIteration(Vector  &xi)\n{  \t\n\t\n\t// Before performing the iteration check if a path has been given\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\n\t//////////////////////////////////////////////////\n\t// beginning of \"the\" constrained CHOMP iteration\n\t \n\tVector nabla_smooth (AA_ * xi_ + bb_);   \n\tVector const & xidd (nabla_smooth); // indeed, it is the same in this formulation...\n  \n\t// Constrained CHOMP. \n\t// Impose nonholonmic (NH) restrictions with the rolling constraint. \n\t// Next we evaluate the constraint functional \n\t// and its Jacobian b and C, respectively, \n\t// as it appears in CHOMP's IJRR paper.\n\t//\n\tMatrix CC ( Matrix::Zero (xidim_, 1) );  \n\tdouble b = 0;  \n\tVector c1 (Vector::Zero (3)); \n\tVector c2 (Vector::Zero (3));\t \n\tVector cf1 (Vector::Zero (3)); \n\tVector cf2 (Vector::Zero (3));\t   \n\n\tfor (size_t iq (0); iq < (nq_-1); ++iq) \n\t{\n\t\t   \t\t    \n\t\t//Evaluate the constraint functional. It is defined by a sum of auxiliar functions\n\t\t//that depend on only two consecutive robot poses.\n\t\tVector const q1 (xi_.block  (iq * cdim_, 0, cdim_, 1) ); \n\t\tVector const q2 (xi_.block  ((iq+1) * cdim_, 0, cdim_, 1) ); \n\n\t\tdouble nhc =  ( q2(0)  -  q1(0) )* sin(q1(2)) - ( q2(1)  -  q1(1) )* cos(q1(2)); //nonholonomic constraint\n\t\tdouble fmc =   cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)) + sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); //forward motion constraint\n\t  \n\t\tb +=  nhc * nhc + fmc; //square of the rolling constraint + forward motion constrain\n\t  \n\t\t//Computation of the Jacobian of the NH constraint. \n\t\t//  Jacobian of the auxiliar functions  \n\t\tc1(0) = -2*sin(q1(2))*(cos(q1(2))*( q1(1)  -  q2(1) ) - sin(q1(2))*( q1(0)  -  q2(0) )); \n\t\tc1(1) =  2*cos(q1(2))*(cos(q1(2))*( q1(1)  -  q2(1) ) - sin(q1(2))*( q1(0)  -  q2(0) )); \n\t\tc1(2) =  -2*(cos(q1(2))*( q1(0)  -  q2(0) ) + sin(q1(2))*( q1(1)  -  q2(1) ))*(cos(q1(2))*( q1(1)  -  q2(1) ) - sin(q1(2))*( q1(0)  -  q2(0) ));  \n\t\tc2(0) =  2*sin(q1(2))*(cos(q1(2))*( q1(1)  -  q2(1) ) - sin(q1(2))*( q1(0)  -  q2(0) ));\n\t\tc2(1) = -2*cos(q1(2))*(cos(q1(2))*( q1(1)  -  q2(1) ) - sin(q1(2))*( q1(0)  -  q2(0) ));\n\t\tc2(2) =  0;\n\t\t//end of NHC Jacobian\n\t  \n\t\t//Computation of the Jacobian of the NH constraint. \n\t\t//  Jacobian of the auxiliar functions \n\t\tcf1(0)=     cos(q1(2)) + (cos(q1(2))*(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1))))/sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); \n\t\tcf1(1)=     sin(q1(2)) + (sin(q1(2))*(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1))))/sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); \n\t\tcf1(2)=     cos(q1(2))*(q1(1) - q2(1)) - sin(q1(2))*(q1(0) - q2(0)) + ((cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)))*(cos(q1(2))*(q1(1) - q2(1)) - sin(q1(2))*(q1(0) - q2(0))))/sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); \n\t\tcf2(0)=     -cos(q1(2)) - (cos(q1(2))*(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1))))/sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); \n\t\tcf2(1) =    - sin(q1(2)) - (sin(q1(2))*(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1))))/sqrt(pow(cos(q1(2))*(q1(0) - q2(0)) + sin(q1(2))*(q1(1) - q2(1)),2)); \n\t\tcf2(2)=     0;             \n\t\t//end of FMC Jacobian\n\t  \n\t\tif (iq == 0 ) \n\t\t{\n\t\t\t  c2(0) +=  2*sin(qs_(2))*(cos(qs_(2))*( qs_(1)  -  q1(1) ) - sin(qs_(2))*( qs_(0)  -  q1(0) ));\n\t\t\t  c2(1) += -2*cos(qs_(2))*(cos(qs_(2))*( qs_(1)  -  q1(1) ) - sin(qs_(2))*( qs_(0)  -  q1(0) ));\n\t\t\t  c2(2) +=  0;\n\t\t\t  \n\t\t\t  cf2(0) +=     -cos(qs_(2)) - (cos(qs_(2))*(cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1))))/sqrt(pow(cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1)),2)); \n\t\t\t  cf2(1) +=    - sin(qs_(2)) - (sin(qs_(2))*(cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1))))/sqrt(pow(cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1)),2)); \n\t\t\t  cf2(2) +=     0;      \n\t\t\t\t   \n\t\t\t  double nhstart  =  ( q1(0)  -  qs_(0) )* sin(qs_(2)) - ( q1(1)  -  qs_(0) )* cos(qs_(2)); \n\t\t\t  double fmstart =   cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1)) + sqrt(pow(cos(qs_(2))*(qs_(0) - q1(0)) + sin(qs_(2))*(qs_(1) - q1(1)),2)); //forward motion constraint  \n\t\t\t  b +=  nhstart * nhstart + fmstart; //square of the rolling constraint\t          \t          \n\t\t} \n\t \n\t\t//Update Jacobian with the contributions from the Jacobian of the auxiliar functions\n\t\tCC.block  (iq * cdim_, 0, cdim_, 1) = CC.block  (iq * cdim_, 0, cdim_, 1) + c1 + cf1;\n\t\tCC.block  ((iq+1) * cdim_, 0, cdim_, 1) = CC.block  ((iq+1) * cdim_, 0, cdim_, 1) + c2 + cf2;\n\t}\n\t \n\t  \n\tCC /=  dt_ * dt_ * (nq_ + 1) ; \n\tb /=  dt_ * dt_ * (nq_ + 1);\n\t\n\tMatrix CCtrans = CC.transpose(); \n    // end of the computation of C and b \n  \n  \n\tVector nabla_obs (Vector::Zero (xidim_));\n  \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\tVector qd;\n\t\tif (0 == iq) \n\t\t{\n\t\t\tqd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - qs_);\n\t\t}\n\t\telse if (iq == nq_ - 1) \n\t\t{\n\t\t\tqd = 0.5 * (qe_ - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));\n\t\t}\n\t\telse \n\t\t{\n\t\t\tqd = 0.5 * (xi_.block ((iq+1) * cdim_, 0, cdim_, 1) - xi_.block ((iq-1) * cdim_, 0, cdim_, 1));;\n\t\t}\n\n\t\tVector const & xx (qq.block (0,0,2,1));\n\t\tVector const & xd (qd.block (0,0,2,1));\n\n\t\t// In this case, C and W are NOT the same\n\t\tMatrix JJ(Matrix::Zero (2, 3));\n\t\tJJ(0,0)=1; \n\t\tJJ(1,1)=1; \n\t      \t\n\t\tdouble const vel (xd.norm());\n\t\tif (vel < 1.0e-3) \n\t\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\n\t\tVector const xdd (JJ * xidd.block (iq * cdim_, 0, cdim_ , 1));\n\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//Add obstacles\t\t\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} \n\t\t \n\t}\n    double residual;\n  \n  \n\tVector dxi (Ainv_ * (nabla_obs + lambda_ * nabla_smooth)); //unconstrained step\n\n\tif (b < 1.0e-10) \n\t{ \n\t\t//unconstrained update to initialize trajectory (it starts with b aprox to zero)\n\t\t//cout << \" One unconstrained update to initialize trajectory  \" << endl;\n\t\txi_ -= dxi / eta_; \n\t\t\n\t\tVector dxi (Ainv_ * (nabla_obs + lambda_ * nabla_smooth));\n\t\tresidual =  dxi.norm() / eta_;\n\t}\n\telse\n\t{\n\t\t// Constrained optimization update\t\n\t\tVector CAC (CCtrans * Ainv_ * CC);\n\t \n\t\tMatrix CACinv (CAC.inverse());\n\t \n\t\tVector Proj (Ainv_ * CC * CACinv); //auxiliar matrix for the update equation\n \n\t\t//cout << \"b =\" << b << \"\\n\";\n\t\tVector cdxi ( - dxi/eta_  +  Proj*CCtrans*dxi / eta_ -  Proj * b  );\n\n\t\txi_ += cdxi; //constrained update\n\t\t\n\t\tresidual = cdxi.norm() / eta_;\n\t}\n\t// end of \"the\" constrainedCHOMP iteration\n\t//////////////////////////////////////////////////\n\tboundTrajectoryAngles();\n\t\n\tres_ = residual;\n\txi = xi_; //updated path\n\t\n\treturn res_;\n \n}\n", "meta": {"hexsha": "c8d3667085763e5c745b33013e17b7cab53bdf8d", "size": 9795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "path_adaptor_se2.cpp", "max_stars_repo_name": "NEU-ZJX/path-adaptor", "max_stars_repo_head_hexsha": "6e0ae261fdc482b96c5179dd972862573c484b61", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-08-17T11:52:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T02:44:00.000Z", "max_issues_repo_path": "path_adaptor_se2.cpp", "max_issues_repo_name": "rafaelvalencia/path-adaptor", "max_issues_repo_head_hexsha": "6e0ae261fdc482b96c5179dd972862573c484b61", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_se2.cpp", "max_forks_repo_name": "rafaelvalencia/path-adaptor", "max_forks_repo_head_hexsha": "6e0ae261fdc482b96c5179dd972862573c484b61", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T21:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T22:23:51.000Z", "avg_line_length": 36.4126394052, "max_line_length": 260, "alphanum_fraction": 0.5325165901, "num_tokens": 3841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5760206478609099}}
{"text": "#include \"Cady/Cady.h\"\n#include \"Cady/Frontend.h\"\n#include \"Cady/CodeGen.h\"\n\n#include <map>\n#include <iomanip>\n\nusing namespace Cady;\nusing namespace Cady::CodeGen;\n\nvoid example_0(){\n\n\n        Function f(\"f\");\n        f.AddArgument(\"x\");\n        f.AddArgument(\"y\");\n\n        //auto expr_0 = BinaryOperator::Mul(Log::Make(BinaryOperator::Mul(ExogenousSymbol::Make(\"x\"),ExogenousSymbol::Make(\"x\"))),  Exp::Make(ExogenousSymbol::Make(\"y\")));\n        //auto expr_0 = BinaryOperator::Pow(ExogenousSymbol::Make(\"x\"), Constant::Make(2));\n        auto expr_0 = Phi::Make(BinaryOperator::Pow(ExogenousSymbol::Make(\"x\"), Constant::Make(3)));\n\n        auto stmt_0 = std::make_shared<EndgenousSymbol>(\"stmt0\", expr_0);\n\n        f.AddStatement(stmt_0);\n\n        std::ofstream fstr(\"prog.cxx\");\n        fstr << R\"(\n#include <cstdio>\n#include <cmath>\n)\";\n\n        StringCodeGenerator cg;\n        cg.Emit(fstr, f);\n        fstr << R\"(\n\nint main(){\n        double x_min = 0.1;\n        double x_max = +2.0;\n        double y_min = -2.0;\n        double y_max = +2.0;\n\n        double epsilon = 1e-10;\n        double increment = 0.05;\n\n        \n\n        for(double x =x_min; x <= x_max + increment /2; x += increment ){\n                for(double y =y_min; y <= y_max + increment /2; y += increment ){\n                        double d_x = 0.0;\n                        double d_y = 0.0;\n\n                        double value = f(x, &d_x, y, &d_y);\n\n                        double dummy;\n                        double x_lower = f(x - epsilon /2 , &dummy, y, &dummy);\n                        double x_upper = f(x + epsilon /2 , &dummy, y, &dummy);\n                        double x_finite_diff = ( x_upper - x_lower ) / epsilon;\n                        double x_residue = d_x - x_finite_diff;\n                        \n                        double y_lower = f(x, &dummy, y - epsilon /2 , &dummy);\n                        double y_upper = f(x, &dummy, y + epsilon /2 , &dummy);\n                        double y_finite_diff = ( y_upper - y_lower ) / epsilon;\n                        double y_residue = d_y - y_finite_diff;\n                        \n                        //printf(\"%f,%f,%f,%f,%f,%f\\n\", x, y, d_x, d_y, x_finite_diff, x_residue);\n                        printf(\"%f,%f,%f => %f,%f,%f => %f,%f,%f\\n\", x, y,value, d_x, x_finite_diff,x_residue, d_y, y_finite_diff,y_residue);\n                }\n\n\n        }\n\n}\n)\";\n}\n\nvoid example_1(){\n\n\n        Function f(\"f\");\n        f.AddArgument(\"a\");\n        f.AddArgument(\"b\");\n        f.AddArgument(\"x\");\n\n\n        auto expr_0 = BinaryOperator::Mul( ExogenousSymbol::Make(\"a\"), BinaryOperator::Mul(ExogenousSymbol::Make(\"x\"),  ExogenousSymbol::Make(\"x\")));\n\n\n        auto stmt_0 = std::make_shared<EndgenousSymbol>(\"stmt0\", expr_0);\n\n        auto expr_1 = BinaryOperator::Add( ExogenousSymbol::Make(stmt_0->Name()), ExogenousSymbol::Make(\"b\"));\n\n        auto stmt_1 = std::make_shared<EndgenousSymbol>(\"stmt1\", expr_1);\n        f.AddStatement(stmt_0);\n        f.AddStatement(stmt_1);\n\n        std::ofstream fstr(\"prog.c\");\n        StringCodeGenerator cg;\n        cg.Emit(fstr, f);\n        fstr << R\"(\n#include <stdio.h>\nint main(){\n        double a = 2.0;\n        double b = 3.0;\n\n        double epsilon = 1e-10;\n        double increment = 0.05;\n\n        \n\n        for(double x =0.0; x <= 2.0 + increment /2; x += increment ){\n                double d_a = 0.0;\n                double d_b = 0.0;\n                double d_x = 0.0;\n\n                double y = f(a, &d_a, b, &d_b, x, &d_x);\n\n                double dummy;\n                double lower = f(a, &dummy, b, &dummy, x - epsilon/2, &dummy);\n                double upper = f(a, &dummy, b, &dummy, x + epsilon/2, &dummy);\n                double finite_diff = ( upper - lower ) / epsilon;\n                double residue = d_x - finite_diff;\n                \n                printf(\"%f,%f,%f,%f,%f,%f,%f\\n\", x, y, d_a, d_b, d_x, finite_diff, residue);\n\n\n        }\n\n}\n)\";\n}\n\nvoid black_scholes(){\n\n\n        Function f(\"black\");\n        f.AddArgument(\"t\");\n        f.AddArgument(\"T\");\n        f.AddArgument(\"r\");\n        f.AddArgument(\"S\");\n        f.AddArgument(\"K\");\n        f.AddArgument(\"vol\");\n\n        auto time_to_expiry = BinaryOperator::Sub(\n                ExogenousSymbol::Make(\"T\"),\n                ExogenousSymbol::Make(\"t\")\n        );\n\n        auto deno = BinaryOperator::Div( \n                Constant::Make(1.0),\n                BinaryOperator::Mul(\n                        ExogenousSymbol::Make(\"vol\"),\n                        BinaryOperator::Pow(\n                                time_to_expiry,\n                                Constant::Make(0.5)\n                        )\n                )\n        );\n\n        auto d1 = BinaryOperator::Mul(\n                deno,\n                BinaryOperator::Add(\n                        Log::Make(\n                                BinaryOperator::Div(\n                                        ExogenousSymbol::Make(\"S\"),\n                                        ExogenousSymbol::Make(\"K\")\n                                )\n                        ),\n                        BinaryOperator::Mul(\n                                BinaryOperator::Add(\n                                        ExogenousSymbol::Make(\"r\"),\n                                        BinaryOperator::Div(\n                                                BinaryOperator::Pow(\n                                                        ExogenousSymbol::Make(\"vol\"),\n                                                        Constant::Make(2.0)\n                                                ),\n                                                Constant::Make(2.0)\n                                        )\n                                ),\n                                time_to_expiry\n                        )\n                )\n        );\n\n        auto stmt_0 = std::make_shared<EndgenousSymbol>(\"stmt0\", d1);\n\n        \n        auto d2 = BinaryOperator::Sub(\n                ExogenousSymbol::Make(stmt_0->Name()),\n                BinaryOperator::Mul(\n                        ExogenousSymbol::Make(\"vol\"),\n                        time_to_expiry\n                )\n        );\n\n\n        auto stmt_1 = std::make_shared<EndgenousSymbol>(\"stmt1\", d2);\n        \n        auto pv = BinaryOperator::Mul(\n                ExogenousSymbol::Make(\"K\"),\n                Exp::Make(\n                        BinaryOperator::Mul(\n                                BinaryOperator::Sub(\n                                        Constant::Make(0.0),\n                                        ExogenousSymbol::Make(\"r\")\n                                ),\n                                time_to_expiry\n                        )\n                )\n        );\n        \n        auto stmt_2 = std::make_shared<EndgenousSymbol>(\"stmt2\", pv);\n\n        auto black = BinaryOperator::Sub(\n                BinaryOperator::Mul(\n                        Phi::Make(stmt_0),\n                        ExogenousSymbol::Make(\"S\")\n                ),\n                BinaryOperator::Mul(\n                        Phi::Make(stmt_1),\n                        stmt_2\n                )\n        );\n\n        auto stmt_3 = std::make_shared<EndgenousSymbol>(\"stmt3\", black);\n\n\n        f.AddStatement(stmt_0);\n        f.AddStatement(stmt_1);\n        f.AddStatement(stmt_2);\n        f.AddStatement(stmt_3);\n\n        std::ofstream fstr(\"prog.cxx\");\n        fstr << R\"(\n#include <cstdio>\n#include <cmath>\n)\";\n\n        StringCodeGenerator cg;\n        cg.Emit(fstr, f);\n        fstr << R\"(\n\ndouble black_fd(double epsilon, double t, double d_t, double T, double d_T, double r, double d_r, double S, double d_S, double K, double d_K, double vol, double d_vol){\n        double dummy;\n        double lower = black( t - d_t*epsilon/2 , &dummy, T - d_T*epsilon/2  , &dummy, r - d_r*epsilon/2  , &dummy, S - d_S*epsilon/2  , &dummy, K - d_K*epsilon/2  , &dummy, vol - d_vol*epsilon/2, &dummy);\n        double upper = black( t + d_t*epsilon/2 , &dummy, T + d_T*epsilon/2  , &dummy, r + d_r*epsilon/2  , &dummy, S + d_S*epsilon/2  , &dummy, K + d_K*epsilon/2  , &dummy, vol + d_vol*epsilon/2, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        return finite_diff;\n}\nint main(){\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        double epsilon = 1e-10;\n\n        double d_t = 0.0;\n        double d_T = 0.0;\n        double d_r = 0.0;\n        double d_S = 0.0;\n        double d_K = 0.0;\n        double d_vol = 0.0;\n        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n\n        double d1 = 1/ ( vol * std::sqrt(T - t)) *  ( std::log(S/K) + ( r + vol*vol/2)*(T-t));\n\n        double dummy;\n        double lower = black( t - epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double upper = black( t + epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        double residue = d_t - finite_diff;\n\n        printf(\"%f,%f,%f,%f,%f,%f => %f,%f => %f,%f,%f\\n\", t, T, r, S, K, vol, value, d1, d_t, finite_diff, residue);\n\n        printf(\"d[t]  ,%f,%f\\n\", d_t  ,  black_fd(epsilon, t, 1, T  , 0, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[T]  ,%f,%f\\n\", d_T  ,  black_fd(epsilon, t, 0, T  , 1, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[r]  ,%f,%f\\n\", d_r  ,  black_fd(epsilon, t, 0, T  , 0, r  , 1, S  , 0, K  , 0, vol, 0));\n        printf(\"d[S]  ,%f,%f\\n\", d_S  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 1, K  , 0, vol, 0));\n        printf(\"d[K]  ,%f,%f\\n\", d_K  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 1, vol, 0));\n        printf(\"d[vol],%f,%f\\n\", d_vol,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 0, vol, 1));\n        \n\n}\n)\";\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid black_scholes_frontend(){\n\n        using namespace Frontend;\n        using Frontend::Log;\n        using Frontend::Exp;\n        using Frontend::Phi;\n\n\n        Function f(\"black\");\n        f.AddArgument(\"t\");\n        f.AddArgument(\"T\");\n        f.AddArgument(\"r\");\n        f.AddArgument(\"S\");\n        f.AddArgument(\"K\");\n        f.AddArgument(\"vol\");\n\n        auto d1    = f.AddStatement(Stmt(\"d1\"   , (1.0 / ( Var(\"vol\") * ((Var(\"T\") - Var(\"t\")) ^ 0.5) )) * ( Log(Var(\"S\") / \"K\") +   (\"r\" + ( Var(\"vol\") ^ 2.0 ) / 2 ) * (Var(\"T\") - Var(\"t\")) )));\n        auto d2    = f.AddStatement(Stmt(\"d2\"   , d1 - \"vol\" * (Var(\"T\") - Var(\"t\"))));\n        auto pv    = f.AddStatement(Stmt(\"pv\"   , \"K\" * Exp( -Var(\"r\") * ( Var(\"T\") - Var(\"t\") ) )));\n        auto black = f.AddStatement(Stmt(\"black\", Phi(d1) * \"S\" - Phi(d2) * pv));\n\n        std::ofstream fstr(\"prog.cxx\");\n        fstr << R\"(\n#include <cstdio>\n#include <cmath>\n)\";\n\n        StringCodeGenerator cg;\n        cg.Emit(fstr, f);\n        fstr << R\"(\n\ndouble black_fd(double epsilon, double t, double d_t, double T, double d_T, double r, double d_r, double S, double d_S, double K, double d_K, double vol, double d_vol){\n        double dummy;\n        double lower = black( t - d_t*epsilon/2 , &dummy, T - d_T*epsilon/2  , &dummy, r - d_r*epsilon/2  , &dummy, S - d_S*epsilon/2  , &dummy, K - d_K*epsilon/2  , &dummy, vol - d_vol*epsilon/2, &dummy);\n        double upper = black( t + d_t*epsilon/2 , &dummy, T + d_T*epsilon/2  , &dummy, r + d_r*epsilon/2  , &dummy, S + d_S*epsilon/2  , &dummy, K + d_K*epsilon/2  , &dummy, vol + d_vol*epsilon/2, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        return finite_diff;\n}\nint main(){\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        double epsilon = 1e-10;\n\n        double d_t = 0.0;\n        double d_T = 0.0;\n        double d_r = 0.0;\n        double d_S = 0.0;\n        double d_K = 0.0;\n        double d_vol = 0.0;\n        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n\n        double d1 = 1/ ( vol * std::sqrt(T - t)) *  ( std::log(S/K) + ( r + vol*vol/2)*(T-t));\n\n        double dummy;\n        double lower = black( t - epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double upper = black( t + epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        double residue = d_t - finite_diff;\n\n        printf(\"%f,%f,%f,%f,%f,%f => %f,%f => %f,%f,%f\\n\", t, T, r, S, K, vol, value, d1, d_t, finite_diff, residue);\n\n        printf(\"d[t]  ,%f,%f\\n\", d_t  ,  black_fd(epsilon, t, 1, T  , 0, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[T]  ,%f,%f\\n\", d_T  ,  black_fd(epsilon, t, 0, T  , 1, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[r]  ,%f,%f\\n\", d_r  ,  black_fd(epsilon, t, 0, T  , 0, r  , 1, S  , 0, K  , 0, vol, 0));\n        printf(\"d[S]  ,%f,%f\\n\", d_S  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 1, K  , 0, vol, 0));\n        printf(\"d[K]  ,%f,%f\\n\", d_K  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 1, vol, 0));\n        printf(\"d[vol],%f,%f\\n\", d_vol,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 0, vol, 1));\n        \n\n}\n)\";\n}\n\n\n\n\n\nvoid black_scholes_template(){\n        auto black_eval = BlackScholesCallOption::Build<double>{};\n\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        std::cout << \"black_eval(t,T,r,S,K,vol) => \" << black_eval.Evaluate(t,T,r,S,K,vol) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,black_eval(t,T,r,S,K,vol))\n\n\n        \n        auto ad_kernel = BlackScholesCallOption::Build<DoubleKernel>{};\n\n        auto as_black = ad_kernel.Evaluate( \n                DoubleKernel::BuildFromExo(\"t\"),\n                DoubleKernel::BuildFromExo(\"T\"),\n                DoubleKernel::BuildFromExo(\"r\"),\n                DoubleKernel::BuildFromExo(\"S\"),\n                DoubleKernel::BuildFromExo(\"K\"),\n                DoubleKernel::BuildFromExo(\"vol\")\n        );\n\n\n        Function f(\"black\");\n        f.AddArgument(\"t\");\n        f.AddArgument(\"T\");\n        f.AddArgument(\"r\");\n        f.AddArgument(\"S\");\n        f.AddArgument(\"K\");\n        f.AddArgument(\"vol\");\n\n        using namespace Frontend;\n\n        std::unordered_set< std::shared_ptr<Operator > > seen;\n        struct StackFrame{\n                explicit StackFrame(std::shared_ptr<EndgenousSymbol > op)\n                        : Op{op}\n                {\n                        auto deps_set = Op->EndgenousDependencies();\n                        Deps.assign(deps_set.begin(), deps_set.end());\n                }\n                std::shared_ptr<EndgenousSymbol > Op;\n                std::vector<std::shared_ptr<EndgenousSymbol > > Deps;\n        };\n        std::vector<StackFrame> stack{StackFrame{std::reinterpret_pointer_cast<EndgenousSymbol>(as_black.as_operator_())}};\n        for(size_t ttl=1000;stack.size() && ttl;--ttl){\n                auto& frame = stack.back();\n                if( frame.Deps.size() == 0 ){\n                        if( seen.count(frame.Op) == 0 ){\n                                seen.insert(frame.Op);\n                                auto black = f.AddStatement(frame.Op);\n                                #if 0\n                                std::cout << \"----------TERMINAL--------------\\n\";\n                                frame.Op->Display();\n                                #endif\n                        }\n                        stack.pop_back();\n                        continue;\n                }\n                auto dep = frame.Deps.back();\n                frame.Deps.pop_back();\n\n                stack.push_back(StackFrame{dep});\n\n        }\n\n\n        std::ofstream fstr(\"prog.cxx\");\n        fstr << R\"(\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <boost/timer/timer.hpp>\n)\";\n\n        StringCodeGenerator cg;\n        cg.Emit(fstr, f);\n        fstr << R\"(\n\ndouble black_fd(double epsilon, double t, double d_t, double T, double d_T, double r, double d_r, double S, double d_S, double K, double d_K, double vol, double d_vol){\n        double dummy;\n        double lower = black( t - d_t*epsilon/2 , &dummy, T - d_T*epsilon/2  , &dummy, r - d_r*epsilon/2  , &dummy, S - d_S*epsilon/2  , &dummy, K - d_K*epsilon/2  , &dummy, vol - d_vol*epsilon/2, &dummy);\n        double upper = black( t + d_t*epsilon/2 , &dummy, T + d_T*epsilon/2  , &dummy, r + d_r*epsilon/2  , &dummy, S + d_S*epsilon/2  , &dummy, K + d_K*epsilon/2  , &dummy, vol + d_vol*epsilon/2, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        return finite_diff;\n}\nint main(){\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        double epsilon = 1e-10;\n\n        double d_t = 0.0;\n        double d_T = 0.0;\n        double d_r = 0.0;\n        double d_S = 0.0;\n        double d_K = 0.0;\n        double d_vol = 0.0;\n        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n\n        double d1 = 1/ ( vol * std::sqrt(T - t)) *  ( std::log(S/K) + ( r + vol*vol/2)*(T-t));\n\n        double dummy;\n        double lower = black( t - epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double upper = black( t + epsilon/2 , &dummy, T  , &dummy, r  , &dummy, S  , &dummy, K  , &dummy, vol, &dummy);\n        double finite_diff = ( upper - lower ) / epsilon;\n        double residue = d_t - finite_diff;\n\n        printf(\"%f,%f,%f,%f,%f,%f => %f,%f => %f,%f,%f\\n\", t, T, r, S, K, vol, value, d1, d_t, finite_diff, residue);\n\n        printf(\"d[t]  ,%f,%f\\n\", d_t  ,  black_fd(epsilon, t, 1, T  , 0, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[T]  ,%f,%f\\n\", d_T  ,  black_fd(epsilon, t, 0, T  , 1, r  , 0, S  , 0, K  , 0, vol, 0));\n        printf(\"d[r]  ,%f,%f\\n\", d_r  ,  black_fd(epsilon, t, 0, T  , 0, r  , 1, S  , 0, K  , 0, vol, 0));\n        printf(\"d[S]  ,%f,%f\\n\", d_S  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 1, K  , 0, vol, 0));\n        printf(\"d[K]  ,%f,%f\\n\", d_K  ,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 1, vol, 0));\n        printf(\"d[vol],%f,%f\\n\", d_vol,  black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 0, vol, 1));\n        \n        // time profile\n        for(volatile size_t N = 100;;N*=2){\n                boost::timer::cpu_timer timer;\n                for(volatile size_t idx=0;idx!=N;++idx){\n                        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n                }\n                std::string ad_time = timer.format(4, \"%w\");\n                timer.start();\n                for(volatile size_t idx=0;idx!=N;++idx){\n                        black_fd(epsilon, t, 1, T  , 0, r  , 0, S  , 0, K  , 0, vol, 0);\n                        black_fd(epsilon, t, 0, T  , 1, r  , 0, S  , 0, K  , 0, vol, 0);\n                        black_fd(epsilon, t, 0, T  , 0, r  , 1, S  , 0, K  , 0, vol, 0);\n                        black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 1, K  , 0, vol, 0);\n                        black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 1, vol, 0);\n                        black_fd(epsilon, t, 0, T  , 0, r  , 0, S  , 0, K  , 0, vol, 1);\n                }\n                std::string fd_time = timer.format(4, \"%w\");\n                std::cout << N << \",\" << fd_time << \",\" << ad_time << \"\\n\";\n        }\n\n}\n)\";\n}\n\n\nstruct RemoveEndgenousFolder{\n        std::shared_ptr<Operator> Fold(std::shared_ptr<Operator> root){\n                if( root->Kind() == OPKind_EndgenousSymbol ){\n                        auto as_endgenous = std::reinterpret_pointer_cast<EndgenousSymbol>(root);\n                        return this->Fold(as_endgenous->Expr());\n                }\n                \n                if( root->IsNonTerminal() ){\n                        for(size_t idx=0;idx!=root->Arity();++idx){\n                                auto folded = this->Fold(root->At(idx));\n                                root->Rebind(idx, folded);\n                        }\n                }\n\n                return root;\n        }\n};\n\nstruct RemoveEndo : OperatorTransform{\n        virtual std::shared_ptr<Operator> Apply(std::shared_ptr<Operator> const& ptr){\n                auto candidate = ptr->Clone(shared_from_this());\n                if( candidate->Kind() == OPKind_EndgenousSymbol ){\n                        if( auto typed = std::dynamic_pointer_cast<EndgenousSymbol>(candidate)){\n                                return typed->Expr();\n                        }\n                }\n                return candidate;\n        }\n};\nstruct RemapUnique : OperatorTransform{\n        explicit RemapUnique(std::string const& prefix = \"__symbol_\")\n                : prefix_{prefix}\n        {\n                std::cerr << \" RemapUnique()\\n\";\n        }\n        ~RemapUnique(){\n                std::cerr << \"~RemapUnique()\\n\";\n        }\n        void mutate_prefix(std::string const& prefix){\n                prefix_ = prefix;\n        }\n        virtual std::shared_ptr<Operator> Apply(std::shared_ptr<Operator> const& ptr){\n\n                auto candidate = ptr->Clone(shared_from_this());\n\n                auto key = std::make_tuple(\n                        candidate->NameInvariantOfChildren(),\n                        candidate->Children()\n                        );\n\n                auto iter = ops_.find(key);\n                if( iter != ops_.end() )\n                        return iter->second;\n\n                if( \n                    candidate->Kind() != OPKind_EndgenousSymbol &&\n                    #if 0\n                    candidate->Kind() != OPKind_ExogenousSymbol &&\n                    #endif\n                    candidate->Kind() != OPKind_Constant )\n                {\n\n                        std::stringstream ss;\n                        ss << prefix_ << (ops_.size()+1);\n                        auto endogous_sym = EndgenousSymbol::Make(ss.str(), candidate); \n                        \n                        ops_[key] = endogous_sym;\n                        return endogous_sym;\n                } else {\n                        ops_[key] = candidate;\n                        return candidate;\n                }\n        }\nprivate:\n        std::string prefix_;\n        std::map<\n                std::tuple<\n                        std::string,\n                        std::vector<std::shared_ptr<Operator> > \n                >,\n                std::shared_ptr<Operator>\n        > ops_;\n};\n\n\n\n\nvoid black_scholes_template_opt(){\n\n        \n        auto ad_kernel = BlackScholesCallOption::Build<DoubleKernel>{};\n\n        auto as_black = ad_kernel.Evaluate( \n                DoubleKernel::BuildFromExo(\"t\"),\n                DoubleKernel::BuildFromExo(\"T\"),\n                DoubleKernel::BuildFromExo(\"r\"),\n                DoubleKernel::BuildFromExo(\"S\"),\n                DoubleKernel::BuildFromExo(\"K\"),\n                DoubleKernel::BuildFromExo(\"vol\")\n        );\n\n        SymbolTable ST;\n        ST(\"t\"  , 0.0);\n        ST(\"T\"  , 10.0);\n        ST(\"r\"  , 0.04);\n        ST(\"S\"  , 50);\n        ST(\"K\"  , 60);\n        ST(\"vol\", 0.2);\n\n        RemoveEndgenousFolder remove_endogous;\n        Transform::FoldZero constant_fold;\n\n        auto black_expr = as_black.as_operator_();\n\n        std::cout << \"--------- black_expr -----------\\n\";\n        //black_expr->Display();\n        std::cout << \"black_expr->Eval(ST) => \" << black_expr->Eval(ST) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,black_expr->Eval(ST))\n\n        auto removed_endo = remove_endogous.Fold(black_expr);\n\n        auto params = std::vector<std::string>{ \"t\", \"T\", \"r\", \"S\", \"K\", \"vol\" };\n\n        std::vector<std::shared_ptr<Operator> > ticker;\n        for(auto const& s : params){\n                auto raw_diff = removed_endo->Diff(s);\n                ticker.push_back(raw_diff);\n        }\n\n        auto unique_mapper = std::make_shared<RemapUnique>();\n\n        std::ofstream out(\"black_better.h\");\n\n        out << \"double black(\";\n        for(size_t idx=0;idx!=params.size();++idx){\n                if( idx != 0 ){\n                        out << \", \";\n                }\n                out << \"double \" << params[idx] << \", double* d_\" << params[idx];\n        }\n        out << \"){\\n\";\n\n        std::unordered_set<std::shared_ptr<Operator> > seen;\n        std::shared_ptr<EndgenousSymbol> return_;\n        for(size_t idx=0;idx!=ticker.size();++idx){\n                auto constant_folded = constant_fold.Fold(ticker[idx]);\n                \n                auto unique          = constant_folded->Clone(unique_mapper);\n\n                auto dependents = unique->DepthFirstAnySymbolicDependency();\n\n                for(auto const& dep : dependents.DepthFirst){\n                        // first emit all the expressions we need\n                        if( seen.count(dep) > 0 )\n                                continue;\n                        seen.insert(dep);\n\n                        out << \"    double \" << std::left << std::setw(15) << dep->Name() << \" = \";\n                        dep->Expr()->EmitCode(out);\n                        out << \";\\n\";\n                }\n\n                out << \"    *d_\" << params[idx] << \" = \";\n                unique->EmitCode(out);\n                out << \";\\n\";\n\n\n\n                //unique->Display();\n        }\n\n        auto constant_folded = constant_fold.Fold(removed_endo);\n        \n        auto unique          = constant_folded->Clone(unique_mapper);\n\n        auto dependents = unique->DepthFirstAnySymbolicDependency();\n\n        for(auto const& dep : dependents.DepthFirst){\n                // first emit all the expressions we need\n                if( seen.count(dep) > 0 )\n                        continue;\n                seen.insert(dep);\n\n                out << \"    double \" << std::left << std::setw(15) << dep->Name() << \" = \";\n                dep->Expr()->EmitCode(out);\n                out << \";\\n\";\n        }\n        out << \"    return \";\n        unique->EmitCode(out);\n        out << \";\\n\";\n        out << \"}\\n\";\n\n\n}\n\n\n\n\n\n\n\nstruct DataFlow;\n\nstruct DotCompiler{\n        DotCompiler(){\n                order.emplace_back();\n        }\n        std::stringstream nodes;\n        std::stringstream edges;\n        std::vector<std::vector<std::string> > order;\n};\n\nstruct DataFlowGraph{\n        void Add(std::shared_ptr<DataFlow> const& flow);\n        void EmitDot(std::ostream& out)const;\n        void EmitCppCode(std::ostream& out)const;\n        void CollectADFlow(std::vector<std::shared_ptr<EndgenousSymbol> > & computation);\n        void Display(std::ostream& out = std::cout)const;\n        void EmitInstructions(InstructionBlock& B)const;\n        void EmitADInstructions(Operator::DependentsProfile& information,\n                                std::shared_ptr<RemapUnique> RU,\n                                InstructionBlock& B)const;\nprivate:\n        std::vector<std::shared_ptr<DataFlow> > rank_;\n        std::unordered_map<std::string,std::shared_ptr<DataFlow> > index_; \n};\n\nstruct DataFlow{\n        DataFlow(std::shared_ptr<EndgenousSymbol> sym)\n                :sym_(sym)\n        {}\n        auto Expr()const{ return sym_; }\n        auto Name()const{ return sym_->Name(); }\n        void AddParent(DataFlow* ptr){\n                parents_.push_back(ptr);\n        }\n        void AddChild(DataFlow* ptr){\n                children_.push_back(ptr);\n        }\n        #if 0\n        void EmitADInstructionsImpl(Operator::DependentsProfile& information, std::shared_ptr<RemapUnique> RU, InstructionBlock& B)const\n        {\n                auto remapped = sym_->Expr()->Clone(RU);\n\n                auto dependents = remapped->DepthFirstAnySymbolicDependency();\n                for(auto const& dep : dependents.DepthFirst ){\n                        if( information.Set.count(dep) == 1 )\n                                continue;\n                        information.Set.insert(dep);\n                        B.Add(std::make_shared<InstructionDeclareVariable>(\n                                        dep->Name(),\n                                        dep->Expr()));\n                }\n\n                auto exo = std::reinterpret_pointer_cast<EndgenousSymbol>(remapped);\n\n                B.Add(std::make_shared<InstructionDeclareVariable>(\n                                exo->Name(),\n                                exo->Expr()));\n                if( children_.empty() ){\n                        std::vector<std::string> deps;\n                        auto dependents = sym_->DepthFirstAnySymbolicDependencyAndThis();\n                        for(auto const& ptr : dependents.DepthFirst ){\n                                deps.push_back(ptr->Name());\n                        }\n                        B.Add(std::make_shared<InstructionComment>(deps));\n                        B.Add(std::make_shared<InstructionReturn>(sym_->Name()));\n                }\n        }\n        #endif\n        void EmitInstructionsImpl(InstructionBlock& B)const{\n                B.Add(std::make_shared<InstructionDeclareVariable>(\n                                sym_->Name(),\n                                sym_->Expr()));\n                if( children_.empty() ){\n                        std::vector<std::string> deps;\n                        auto dependents = sym_->DepthFirstAnySymbolicDependencyAndThis();\n                        for(auto const& ptr : dependents.DepthFirst ){\n                                deps.push_back(ptr->Name());\n                        }\n                        B.Add(std::make_shared<InstructionComment>(deps));\n                        B.Add(std::make_shared<InstructionReturn>(sym_->Name()));\n                }\n        }\n        void EmitADInstructionsImpl(Operator::DependentsProfile& information, std::shared_ptr<RemapUnique> RU, InstructionBlock& B)const\n        {\n                auto make_ad_sym = [](auto const& name){\n                        return \"__rev_ad_\" + name;\n                };\n\n                if( children_.size() == 0 ){\n                        B.Add(std::make_shared<InstructionDeclareVariable>(\n                                make_ad_sym(sym_->Name()),\n                                Constant::Make(1.0)\n                        ));\n                } else {\n                        static auto removed_end = std::make_shared<RemoveEndo>();\n                        static Transform::FoldZero constant_fold;\n                        // forward\n                        auto make_node_back = [&](auto child){\n                                return constant_fold.Fold(\n                                        BinaryOperator::Mul(\n                                                child->Expr()->Expr()->Diff(sym_->Name()),\n                                                ExogenousSymbol::Make(make_ad_sym(child->Name()))\n                                        )\n                                );\n                        };\n                        std::shared_ptr<Operator> head = make_node_back(children_[0]);\n                        for(size_t idx=1;idx<children_.size();++idx){\n                                head = BinaryOperator::Add(\n                                        head,\n                                        make_node_back(children_[idx])\n                                );\n                        }\n                \n                        #if 0\n                        auto remapped = head;\n                        #else\n                        std::stringstream cpp_expr;\n                        head = head->Clone(removed_end);\n                        head->EmitCode(cpp_expr);\n                        //head = remove_endogous.Fold(head);\n                        //auto folded = constant_fold.Fold(head);\n                        auto remapped = head->Clone(RU);\n\n                        B.Add(std::make_shared<InstructionComment>(std::vector<std::string>{\"BEGIN \" + cpp_expr.str()}));\n                        auto dependents = remapped->DepthFirstAnySymbolicDependency();\n                        for(auto const& dep : dependents.DepthFirst ){\n                                if( information.Set.count(dep) == 1 )\n                                        continue;\n                                information.Set.insert(dep);\n                                B.Add(std::make_shared<InstructionDeclareVariable>(\n                                                dep->Name(),\n                                                dep->Expr()));\n                                \n                        }\n                        B.Add(std::make_shared<InstructionComment>(std::vector<std::string>{\"END \" + cpp_expr.str()}));\n                        #endif\n\n                                \n                        B.Add(std::make_shared<InstructionDeclareVariable>(\n                                make_ad_sym(sym_->Name()),\n                                remapped));\n                }\n\n                if( parents_.size() == 0 ){\n                        auto make_ptr_sym = [](auto const& name){\n                                return \"d_\" + name;\n                        };\n                        auto param_name = std::dynamic_pointer_cast<ExogenousSymbol>(sym_->Expr());\n                        B.Add(std::make_shared<InstructionPointerAssignment>(\n                                        make_ptr_sym(param_name->Name()),\n                                        make_ad_sym(sym_->Name())));\n                }\n\n\n#if 0\n\n                auto make_ptr_sym = [](auto const& name){\n                        return \"d_\" + name;\n                };\n                if( parents_.empty() ){\n                        auto param_name = std::dynamic_pointer_cast<ExogenousSymbol>(sym_->Expr());\n                        out << \"*\" << make_ptr_sym(param_name->Name()) << \" = \" << make_ad_sym(sym_->Name()) << \";\\n\";\n                }\n#endif\n        }\n        void EmitEvalCodeImpl(std::ostream& out)const{\n                out << \"double \" << sym_->Name() << \" = \";\n                sym_->Expr()->EmitCode(out);\n                out << \";\\n\";\n                if( children_.size() == 0 ){\n                        auto make_ad_sym = [](auto const& name){\n                                return \"__rev_ad_\" + name;\n                        };\n                        auto make_ptr_sym = [](auto const& name){\n                                return \"d_\" + name;\n                        };\n                        std::cout << sym_->Name() << \"\\n\";\n                        //sym_->Display();\n                        if( auto param_name = std::dynamic_pointer_cast<ExogenousSymbol>(sym_->Expr()) ){\n                                out << \"*\" << make_ptr_sym(param_name->Name()) << \" = \" << make_ad_sym(sym_->Name()) << \";\\n\";\n                        } else {\n                                out << \"// unexpcted\\n\";\n                        }\n                }\n                \n                auto make_ad_sym = [](auto const& name){\n                        return \"__rev_ad_\" + name;\n                };\n                auto make_ptr_sym = [](auto const& name){\n                        return \"d_\" + name;\n                };\n                if( parents_.empty() ){\n                        auto param_name = std::dynamic_pointer_cast<ExogenousSymbol>(sym_->Expr());\n                        out << \"*\" << make_ptr_sym(param_name->Name()) << \" = \" << make_ad_sym(sym_->Name()) << \";\\n\";\n                }\n        }\n        void EmitADFlowImpl(std::vector<std::shared_ptr<EndgenousSymbol> > & computation){\n                auto make_ad_sym = [](auto const& name){\n                        return \"__rev_ad_\" + name;\n                };\n                if( children_.size() > 0 ){\n                        static Transform::FoldZero constant_fold;\n                        // forward\n                        auto make_node_back = [&](auto child){\n                                return constant_fold.Fold(\n                                        BinaryOperator::Mul(\n                                                child->Expr()->Expr()->Diff(sym_->Name()),\n                                                ExogenousSymbol::Make(make_ad_sym(child->Name()))\n                                        )\n                                );\n                        };\n                        std::shared_ptr<Operator> head = make_node_back(children_[0]);\n                        for(size_t idx=1;idx<children_.size();++idx){\n                                head = BinaryOperator::Add(\n                                        head,\n                                        make_node_back(children_[idx])\n                                );\n                        }\n\n\n                        computation.push_back(EndgenousSymbol::Make( make_ad_sym(sym_->Name()), head));\n                                \n                }\n        }\n        void EmitReverseADCodeImpl(std::ostream& out)const{\n                auto make_ad_sym = [](auto const& name){\n                        return \"__rev_ad_\" + name;\n                };\n                out << \"double \" << make_ad_sym(sym_->Name()) << \" = \";\n                if( children_.size() > 0 ){\n                        static Transform::FoldZero constant_fold;\n                        // forward\n                        auto make_node_back = [&](auto child){\n                                return constant_fold.Fold(\n                                        BinaryOperator::Mul(\n                                                child->Expr()->Expr()->Diff(sym_->Name()),\n                                                ExogenousSymbol::Make(make_ad_sym(child->Name()))\n                                        )\n                                );\n                        };\n                        std::shared_ptr<Operator> head = make_node_back(children_[0]);\n                        for(size_t idx=1;idx<children_.size();++idx){\n                                head = BinaryOperator::Add(\n                                        head,\n                                        make_node_back(children_[idx])\n                                );\n                        }\n                                \n                        head->EmitCode(out);\n                } else {\n                        out << \"1.0\";\n                }\n                out << \";\\n\";\n\n                auto make_ptr_sym = [](auto const& name){\n                        return \"d_\" + name;\n                };\n                if( parents_.empty() ){\n                        auto param_name = std::dynamic_pointer_cast<ExogenousSymbol>(sym_->Expr());\n                        out << \"*\" << make_ptr_sym(param_name->Name()) << \" = \" << make_ad_sym(sym_->Name()) << \";\\n\";\n                }\n\n        }\n\n        void EmitDot(DotCompiler& compiler)const{\n                if( parents_.size() ){\n                        compiler.order.emplace_back(std::vector<std::string>{sym_->Name()});\n                } else {\n                        compiler.order[0].push_back(sym_->Name());\n                }\n                compiler.nodes << sym_->Name() << \"[shape=record, label=\\\"<expr>\";\n                compiler.nodes << sym_->Name() << \" = \";\n                sym_->Expr()->EmitCode(compiler.nodes);\n\n                #if 0\n                for(auto const& ptr : parents_){\n                        auto name = ptr->Name();\n                        auto diff = sym_->Expr()->Diff(name);\n                        Transform::FoldZero constant_fold;\n                        auto folded = constant_fold.Fold(diff);\n                        compiler.nodes << \"|D[\" << name << \"] = \";\n                        folded->EmitCode(compiler.nodes);\n                }\n                #endif\n                Transform::FoldZero constant_fold;\n                compiler.nodes << \"|<diff>D[\" << sym_->Name() << \"]\";\n                if( parents_.size() > 0 ){\n\n                        // forward\n                        auto make_node_fwd = [&](auto name){\n                                return constant_fold.Fold(\n                                        BinaryOperator::Mul(\n                                                sym_->Expr()->Diff(name),\n                                                ExogenousSymbol::Make(\"D[\" + name + \"]\")\n                                        )\n                                );\n                        };\n                        std::shared_ptr<Operator> head = make_node_fwd(parents_[0]->Name());\n                        for(size_t idx=1;idx<parents_.size();++idx){\n                                head = BinaryOperator::Add(\n                                        head,\n                                        make_node_fwd(parents_[idx]->Name())\n                                );\n                        }\n                                \n                        compiler.nodes << \" = \";\n                        head->EmitCode(compiler.nodes);\n\n\n                }\n                \n                compiler.nodes << \"|<bdiff>B[\" << sym_->Name() << \"]\";\n                if( children_.size() > 0 ){\n                        // forward\n                        auto make_node_back = [&](auto child){\n                                return constant_fold.Fold(\n                                        BinaryOperator::Mul(\n                                                child->Expr()->Expr()->Diff(sym_->Name()),\n                                                ExogenousSymbol::Make(\"B[\" + child->Name() + \"]\")\n                                        )\n                                );\n                        };\n                        std::shared_ptr<Operator> head = make_node_back(children_[0]);\n                        for(size_t idx=1;idx<children_.size();++idx){\n                                head = BinaryOperator::Add(\n                                        head,\n                                        make_node_back(children_[idx])\n                                );\n                        }\n                                \n                        compiler.nodes << \" = \";\n                        head->EmitCode(compiler.nodes);\n                }\n                compiler.nodes << \"\\\"];\\n\";\n                #if 1\n                for(auto const& ptr : parents_){\n\n                        auto name = ptr->Name();\n\n                        auto diff = sym_->Expr()->Diff(name);\n                        auto folded = constant_fold.Fold(diff);\n\n                        compiler.edges << name << \":diff -> \" << sym_->Name() << \":diff [color=blue,label=\\\"\";\n                        folded->EmitCode(compiler.edges);\n                        compiler.edges << \"\\\"];\\n\";\n                }\n                #endif\n                for(auto const& ptr : children_ ){\n\n                        auto diff = ptr->Expr()->Expr()->Diff(sym_->Name());\n                        auto folded = constant_fold.Fold(diff);\n\n                        compiler.edges << ptr->Name() << \":bdiff -> \" << sym_->Name() << \":bdiff [color=red,label=\\\"\";\n                        folded->EmitCode(compiler.edges);\n                        compiler.edges << \"\\\"];\\n\";\n                }\n\n        }\nprivate:\n        std::shared_ptr<EndgenousSymbol> sym_;\n        std::vector<DataFlow*> parents_;\n        std::vector<DataFlow*> children_;\n};\nvoid DataFlowGraph::CollectADFlow(std::vector<std::shared_ptr<EndgenousSymbol> > & computation){\n        for(auto const& flow : rank_){\n                flow->EmitADFlowImpl(computation);\n        }\n}\n        \nvoid DataFlowGraph::EmitDot(std::ostream& out)const{\n        DotCompiler dc;\n        for(auto const& flow : rank_){\n                flow->EmitDot(dc);\n        }\n        out << \"digraph{\\n\";\n        out << dc.nodes.str();\n        out << dc.edges.str();\n\n        out << \"node [shape = none];\\n\";\n        for(size_t idx=0;idx!=dc.order.size();++idx){\n                if( idx != 0 )\n                        out << \"->\";\n                out << idx;\n        }\n        out << \"[arrowhead=none,shape=none]\\n\";\n        for(size_t idx=0;idx!=dc.order.size();++idx){\n                out << \"{rank=same;\" << idx;\n                for(auto const& name : dc.order[idx] ){\n                        out << \",\" << name;\n                }\n                out << \"}\\n\";\n        }\n        out << \"}\\n\";\n}\nvoid DataFlowGraph::Display(std::ostream& out)const{\n        for(auto const& flow : rank_){\n                std::cout << \"--: \" << flow->Name() << \"\\n\";\n        }\n}\nvoid DataFlowGraph::EmitInstructions(InstructionBlock& B)const{\n        for(auto const& flow : rank_){\n                flow->EmitInstructionsImpl(B);\n        }\n}\nvoid DataFlowGraph::EmitADInstructions(Operator::DependentsProfile& information,\n                                       std::shared_ptr<RemapUnique> RU,\n                                       InstructionBlock& B)const\n{\n        for(size_t idx=rank_.size();idx;){\n                --idx;\n                rank_[idx]->EmitADInstructionsImpl(information, RU, B);\n        }\n}\nvoid DataFlowGraph::EmitCppCode(std::ostream& out)const{\n        out << R\"(\n\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n\ndouble black(double t, double* d_t, double T, double* d_T, double r, double* d_r, double S, double* d_S, double K, double* d_K, double vol, double* d_vol){\n)\";\n        for(auto const& flow : rank_){\n                flow->EmitEvalCodeImpl(out);\n        }\n#if 0\nfor(size_t idx=rank_.size();idx;){\n        --idx;\n        rank_[idx]->EmitReverseADCodeImpl(out);\n}\n#endif\n        out << \"return \" << rank_.back()->Name() << \";\\n\";\n        out << \"}\";\n        out <<\nR\"(\n\nint main(){\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        double d_t = 0.0;\n        double d_T = 0.0;\n        double d_r = 0.0;\n        double d_S = 0.0;\n        double d_K = 0.0;\n        double d_vol = 0.0;\n        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n\n        std::cout << \"black = \" << value << \"\\n\";\n        std::cout << \"d_t   = \" << d_t << \"\\n\";\n        std::cout << \"d_T   = \" << d_T << \"\\n\";\n        std::cout << \"d_r   = \" << d_r << \"\\n\";\n        std::cout << \"d_S   = \" << d_S << \"\\n\";\n        std::cout << \"d_K   = \" << d_K << \"\\n\";\n        std::cout << \"d_vol = \" << d_vol << \"\\n\";\n}\n)\";\n}\n\nvoid DataFlowGraph::Add(std::shared_ptr<DataFlow> const& flow){\n        rank_.push_back(flow);\n        index_[flow->Name()] = flow;\n        auto dependents = flow->Expr()->DepthFirstAnySymbolicDependencyNoRecurse();\n\n        auto link_dependency = [&](auto& child, auto& parent){\n                child->AddParent(parent.get());\n                parent->AddChild(child.get());\n        };\n\n        for(auto const& ptr : dependents.DepthFirst ){\n                auto iter = index_.find(ptr->Name());\n                if( iter == index_.end() )\n                        throw std::domain_error(\"cant find node\");\n                link_dependency(flow, iter->second);\n        }\n}\n\nvoid reverse_test(){\n        using namespace Frontend;\n        using Frontend::Sin;\n        #if 0\n        auto x1 = Var(\"x1\");\n        auto x2 = Var(\"x2\");\n        auto expr_ = Break(\"z\", Break(\"y\", x1 * x2 + Sin(x1)));\n        auto expr = expr_.as_operator_();\n        #else\n        auto ad_kernel = BlackScholesCallOption::Build<DoubleKernel>{};\n\n        auto as_black = ad_kernel.Evaluate( \n                DoubleKernel::BuildFromExo(\"t\"),\n                DoubleKernel::BuildFromExo(\"T\"),\n                DoubleKernel::BuildFromExo(\"r\"),\n                DoubleKernel::BuildFromExo(\"S\"),\n                DoubleKernel::BuildFromExo(\"K\"),\n                DoubleKernel::BuildFromExo(\"vol\")\n        );\n        auto expr_ = as_black.as_operator_();\n        RemoveEndgenousFolder remove_endogous;\n        auto expr = remove_endogous.Fold(expr_);\n        #endif\n\n        auto unique_mapper = std::make_shared<RemapUnique>(\"w\");\n        auto unique        = Break(\"value\", expr->Clone(unique_mapper)).as_operator_();\n        //unique->Display();\n                \n        auto dependents = unique->DepthFirstAnySymbolicDependencyAndThis();\n        std::vector<std::shared_ptr<DataFlow> > flow;\n        DataFlowGraph graph;\n        for(auto const& dep : dependents.DepthFirst){\n                auto ptr = std::make_shared<DataFlow>(dep);\n                flow.push_back(ptr);\n                graph.Add(ptr);\n        }\n        #if 0\n        for(auto const& step : flow){\n                step->Expr()->Display();\n        }\n        #endif\n\n        std::ofstream out(\"graph.dot\");\n        graph.EmitDot(out);\n        out.close();\n        std::system(\"dot -Tpng graph.dot -o graph.png\");\n\n\n        InstructionBlock B;\n        graph.EmitInstructions(B);\n\n        std::cout << \"dependents.Set.size() => \" << dependents.Set.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,dependents.Set.size())\n        graph.EmitADInstructions(dependents, unique_mapper, B);\n\n\n\n        std::ofstream code(\"black.cpp\");\n        code << R\"(\n\n#include <cstdio>\n#include <cmath>\n#include <iostream>\n\ndouble black(double t, double* d_t, double T, double* d_T, double r, double* d_r, double S, double* d_S, double K, double* d_K, double vol, double* d_vol){\n)\";\n\n        B.EmitCode(code);\n        code <<\nR\"(\n}\n\nint main(){\n        double t   = 0.0;\n        double T   = 10.0;\n        double r   = 0.04;\n        double S   = 50;\n        double K   = 60;\n        double vol = 0.2;\n\n        double d_t = 0.0;\n        double d_T = 0.0;\n        double d_r = 0.0;\n        double d_S = 0.0;\n        double d_K = 0.0;\n        double d_vol = 0.0;\n        double value = black( t  , &d_t, T  , &d_T, r  , &d_r, S  , &d_S, K  , &d_K, vol, &d_vol);\n\n        std::cout << \"black = \" << value << \"\\n\";\n        std::cout << \"d_t   = \" << d_t << \"\\n\";\n        std::cout << \"d_T   = \" << d_T << \"\\n\";\n        std::cout << \"d_r   = \" << d_r << \"\\n\";\n        std::cout << \"d_S   = \" << d_S << \"\\n\";\n        std::cout << \"d_K   = \" << d_K << \"\\n\";\n        std::cout << \"d_vol = \" << d_vol << \"\\n\";\n}\n)\";\n\n\n        #if 0\n        std::vector<std::shared_ptr<EndgenousSymbol> > ad_computation;\n        graph.Display();\n        graph.CollectADFlow(ad_computation);\n        std::vector<std::shared_ptr<Operator> > computation;\n        computation.push_back(unique);\n\n        unique_mapper->mutate_prefix(\"__rev_ad_\");\n\n        for(auto& ptr : ad_computation ){\n                computation.push_back(ptr->Clone(unique_mapper));\n                //computation.push_back(ptr);\n                //ptr->Display();\n        }\n\n        std::cout << \"ad_computation.size() => \" << ad_computation.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,computation.size())\n        std::cout << \"computation.size() => \" << computation.size() << \"\\n\"; // __CandyPrint__(cxx-print-scalar,computation.size())\n\n\n        do{\n\n                DataFlowGraph ad_graph;\n                Operator::DependentsProfile dependents;\n                for(auto const& ptr : computation ){\n                        ptr->CollectDepthFirstAnySymbolicDependency(dependents, true);\n                }\n                for(auto const& dep : dependents.DepthFirst){\n                        auto ptr = std::make_shared<DataFlow>(dep);\n                        flow.push_back(ptr);\n                        ad_graph.Add(ptr);\n                }\n                ad_graph.Display();\n                std::cerr << __FILE__ << \":\" << __LINE__ << \":A\\n\"; // __CandyTag__A\n                std::ofstream code(\"black.cpp\");\n                ad_graph.EmitCppCode(code);\n                code.close();\n        }while(0);\n        #endif\n\n}\n\nint main(){\n        //black_scholes();\n        //black_scholes_frontend();\n        //black_scholes_template();\n        //black_scholes_template_opt();\n\n        try{\n                reverse_test();\n        } catch ( std::exception const& e ){\n                std::cerr << \"Exception: \" << e.what() << \"\\n\";\n        }\n}\n", "meta": {"hexsha": "c608fb85c8f26e9904daab7be5a697cb1a51d5e6", "size": 52003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "driver.cpp", "max_stars_repo_name": "sweeterthancandy/sweeterthancady", "max_stars_repo_head_hexsha": "6b2a77e745349e1db0f85e71b346c4f1208f01b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-12T11:02:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T11:02:33.000Z", "max_issues_repo_path": "driver.cpp", "max_issues_repo_name": "sweeterthancandy/CandyAlgoAdjointDiff", "max_issues_repo_head_hexsha": "6b2a77e745349e1db0f85e71b346c4f1208f01b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "driver.cpp", "max_forks_repo_name": "sweeterthancandy/CandyAlgoAdjointDiff", "max_forks_repo_head_hexsha": "6b2a77e745349e1db0f85e71b346c4f1208f01b7", "max_forks_repo_licenses": ["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.0138888889, "max_line_length": 205, "alphanum_fraction": 0.4412822337, "num_tokens": 12440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5760206477713599}}
{"text": "/*\n * This file is part of bogus, a C++ sparse block matrix library.\n *\n * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n*/\n\n\n#ifndef BOGUS_POLYNOMIAL_IMPL_HPP\n#define BOGUS_POLYNOMIAL_IMPL_HPP\n\n#ifndef BOGUS_WITHOUT_EIGEN\n#include <Eigen/Eigenvalues>\n#endif\n\n#include \"Polynomial.hpp\"\n#include \"NumTraits.hpp\"\n\n\nnamespace bogus\n{\n\nnamespace polynomial {\n\n\n#ifndef BOGUS_WITHOUT_EIGEN\n\n#ifdef _MSC_VER\n#define BOGUS_TLS_SPEC __declspec( thread )\n#else\n// gcc on MacOS X does not support thread local storage\n#if !defined( __GNUC__ ) or !defined( __APPLE__ )\n#define BOGUS_TLS_SPEC __thread\n#endif\n#endif\n\ntemplate< unsigned Dimension, typename Scalar >\nstruct CompanionMatrix\n{\n\ttypedef Eigen::Matrix< Scalar, Dimension, Dimension > BaseType ;\n\n#ifdef BOGUS_TLS_SPEC\n\ttypedef typename BaseType::MapType ReturnType ;\n\n\tstatic ReturnType get()\n\t{\n\t\tstatic BOGUS_TLS_SPEC double s_matrix_data[ Dimension*Dimension ] ;\n\t\tstatic BOGUS_TLS_SPEC bool s_matrix_initialized = false ;\n\n\t\tReturnType matrix( s_matrix_data ) ;\n\n\t\tif( !s_matrix_initialized )\n\t\t{\n\t\t\tmatrix.template block< 1, Dimension-1> ( 0, 0 ).setZero() ;\n\t\t\tmatrix.template block< Dimension - 1, Dimension -1 >( 1, 0 ).setIdentity() ;\n\t\t\ts_matrix_initialized = true ;\n\t\t}\n\n\t\treturn matrix ;\n\t}\n#else\n\ttypedef BaseType ReturnType ;\n\n\tstatic ReturnType get()\n\t{\n\t\tstatic BaseType s_matrix ;\n\t\tstatic bool s_matrix_initialized = false ;\n\n\t\tif( !s_matrix_initialized )\n\t\t{\n\t\t\ts_matrix.template block< 1, Dimension-1> ( 0, 0 ).setZero() ;\n\t\t\ts_matrix.template block< Dimension - 1, Dimension -1 >( 1, 0 ).setIdentity() ;\n\t\t\ts_matrix_initialized = true ;\n\t\t}\n\n\t\treturn s_matrix ;\n\t}\n#endif\n} ;\n\ntemplate< unsigned Dimension, typename Scalar >\nunsigned RootsFinder< Dimension, Scalar>::getRealRoots(const Scalar *coeffs, Scalar *realRoots,\n\t\tRealRootsFilter filter )\n{\n\ttypedef CompanionMatrix< Dimension, Scalar > CM ;\n\ttypename CM::ReturnType matrix = CM::get() ;\n\n\tmatrix.template block< Dimension, 1 >( 0, Dimension - 1 ) = -Eigen::Matrix< Scalar, Dimension, 1 >::Map( coeffs ) ;\n\tconst typename Eigen::EigenSolver< typename CM::BaseType >::EigenvalueType& ev = matrix.eigenvalues() ;\n\n\tunsigned count = 0 ;\n\tfor( unsigned i = 0 ; i < Dimension ; ++i )\n\t{\n\t\tif( NumTraits< Scalar >::isZero( std::imag( ev[i] ) ) )\n\t\t{\n\t\t\tconst bool discard =\n\t\t\t\t\t( filter == StrictlyPositiveRoots && std::real( ev[i] ) <= 0 ) ||\n\t\t\t\t\t( filter == StrictlyNegativeRoots && std::real( ev[i] ) >= 0 ) ;\n\t\t\tif( !discard ) realRoots[ count++ ] = std::real( ev[i] ) ;\n\t\t}\n\t}\n\treturn count ;\n}\n\n#else\ntemplate< unsigned Dimension, typename Scalar >\nunsigned RootsFinder< Dimension, Scalar>::getRealRoots(const Scalar *coeffs, Scalar *realRoots,\n\t\tRealRootsFilter filter )\n{\n\tassert( 0 && \"bogus::Polynomial::RootsFinder::getRealRoots requires Eigen\" ) ;\n\treturn 0 ;\n}\n#endif\n\ntemplate< typename Scalar >\nstruct PossiblyDegenerateRootsFinder< 0, Scalar >\n{\n\tstatic unsigned getRealRoots( const Scalar* coeffs,\n\t\t\t\t\t\t\t\t  Scalar* realRoots,\n\t\t\t\t\t\t\t\t  RealRootsFilter filter = AllRoots )\n\t{\n\t\trealRoots[0] = 0. ;\n\t\treturn filter == AllRoots && NumTraits< Scalar >::isZero( coeffs[0] ) ;\n\t}\n} ;\n\ntemplate< unsigned Dimension, typename Scalar >\nunsigned PossiblyDegenerateRootsFinder< Dimension, Scalar>::getRealRoots( Scalar *coeffs, Scalar *realRoots,\n\t\tRealRootsFilter filter )\n{\n\tif( NumTraits< Scalar >::isZero( coeffs[ Dimension ] ) )\n\t{\n\t\treturn PossiblyDegenerateRootsFinder< Dimension - 1, Scalar >::getRealRoots( coeffs, realRoots, filter ) ;\n\t}\n\tconst Scalar inv = 1./coeffs[Dimension] ;\n\tfor( unsigned k = 0 ; k < Dimension ; ++k )\n\t{\n\t\tcoeffs[k] *= inv ;\n\t}\n\treturn RootsFinder< Dimension, Scalar >::getRealRoots( coeffs, realRoots, filter ) ;\n}\n\n} //namespace polynomial\n\n} //namespace bogus\n\n#endif\n", "meta": {"hexsha": "66c75e3f6fae5f00bd77613b3844d719cf5e0b49", "size": 3947, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/src/Core/Utils/Polynomial.impl.hpp", "max_stars_repo_name": "sjokic/WallDestruction", "max_stars_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "include/src/Core/Utils/Polynomial.impl.hpp", "max_issues_repo_name": "sjokic/WallDestruction", "max_issues_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/src/Core/Utils/Polynomial.impl.hpp", "max_forks_repo_name": "sjokic/WallDestruction", "max_forks_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_forks_repo_licenses": ["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.1390728477, "max_line_length": 116, "alphanum_fraction": 0.7050924753, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5760206316924751}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n*\n*   Tutorial:  Use of the iterative solvers in ViennaCL with Eigen (http://eigen.tuxfamily.org/)\n*   \n*/\n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n\n//\n// Include Eigen headers\n//\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Eigen objects\n#define VIENNACL_WITH_EIGEN 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\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n#include \"../benchmarks/benchmark-utils.hpp\"\n\n\nint main(int, char *[])\n{\n  typedef float ScalarType;\n  \n  Eigen::SparseMatrix<ScalarType, Eigen::RowMajor> eigen_matrix(65025, 65025);\n  Eigen::VectorXf eigen_rhs;\n  Eigen::VectorXf eigen_result;\n  Eigen::VectorXf ref_result;\n  Eigen::VectorXf residual;\n  \n  //\n  // Read system from file\n  //\n  std::cout << \"Reading matrix...\" << std::endl;\n  eigen_matrix.reserve(65025 * 7);\n  if (!viennacl::io::read_matrix_market_file(eigen_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return 0;\n  }\n  //eigen_matrix.endFill();\n  std::cout << \"Done: reading matrix\" << std::endl;\n\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", eigen_rhs))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return 0;\n  }\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  \n  //CG solver:\n  std::cout << \"----- Running CG -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::cg_tag());\n  \n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\n\n  //BiCGStab solver:\n  std::cout << \"----- Running BiCGStab -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::bicgstab_tag());\n  \n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\n\n  //GMRES solver:\n  std::cout << \"----- Running GMRES -----\" << std::endl;\n  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::gmres_tag());\n  \n  residual = eigen_matrix * eigen_result - eigen_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;\n  \n}\n\n", "meta": {"hexsha": "936af115a41ef1c3a34039a95c5d1f3aa6cbe69f", "size": 3595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative-eigen.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/iterative-eigen.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/iterative-eigen.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": 30.7264957265, "max_line_length": 126, "alphanum_fraction": 0.6197496523, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5760206316924751}}
{"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 target.hpp\n * @author Boston Cleek\n * @date 17 Nov 2020\n * @brief Target distribution\n */\n#ifndef TARGET_HPP\n#define TARGET_HPP\n\n#include <armadillo>\n\n#include <visualization_msgs/MarkerArray.h>\n\n#include <ergodic_exploration/grid.hpp>\n#include <ergodic_exploration/numerics.hpp>\n\nnamespace ergodic_exploration\n{\nusing arma::mat;\nusing arma::vec;\nstruct Gaussian;\ntypedef std::vector<Gaussian> GaussianList;\n\n/** @brief 2D gaussian */\nstruct Gaussian\n{\n  /** @brief Constructor */\n  Gaussian()\n  {\n  }\n\n  /**\n   * @brief Constructor\n   * @param mu - mean [mean x, mean y]\n   * @param sigmas - standard deviations [sigma x, sigma y]\n   */\n  Gaussian(const vec& mu, const vec& sigmas)\n    : mu(mu), cov(arma::diagmat(square(sigmas))), cov_inv(inv(cov))\n  {\n  }\n\n  /**\n   * @brief Evaluate gaussian\n   * @param pt - point [x y]\n   * @return evaluated gaussian at pt\n   */\n  double operator()(const vec& pt) const\n  {\n    const vec diff = pt - mu;\n    return std::exp(-0.5 * dot(diff.t() * cov_inv, diff));\n  }\n\n  /**\n   * @brief Evaluate gaussian\n   * @param pt - point [x y]\n   * @param trans - translation from map frame to fourier domain\n   * @return evaluated gaussian at pt translated by trans\n   * @details the translation is used to translate the mean into the fourier domain\n   */\n  double operator()(const vec& pt, const vec& trans) const\n  {\n    // DEBUG\n    // if (any(mu - trans) < 0.0)\n    // {\n    //   std::cout << \"WARNING: Targert mean not within fourier domain\" << std::endl;\n    // }\n\n    // translate mu into frame of fourier domain\n    const vec diff = pt - (mu - trans);\n    return std::exp(-0.5 * dot(diff.t() * cov_inv, diff));\n  }\n\n  vec mu;       // mean\n  mat cov;      // covariance\n  mat cov_inv;  // inverse of covariance\n};\n\n/** @brief Target distribution */\nclass Target\n{\npublic:\n  /** @brief Constructor */\n  Target();\n\n  /**\n   * @brief Constructor\n   * @param gaussians - list of target gaussians\n   */\n  Target(const GaussianList& gaussians);\n\n  /**\n   * @brief Adds gaussian to list\n   * @param g - gaussians\n   */\n  void addGaussian(const Gaussian& g);\n\n  /**\n   * @brief Remove gaussian from list\n   * @param idx - index of gaussian to remove\n   */\n  void deleteGaussian(unsigned int idx);\n\n  /**\n   * @brief Evaluate the list of gaussians\n   * @param pt - point [x y]\n   * @param trans - translation from map frame to fourier domain\n   * @return value of the list of gaussians evaluated at pt translated by trans\n   * @details the translation is used to translate the mean into the fourier domain\n   */\n  double evaluate(const vec& pt, const vec& trans) const;\n\n  /**\n   * @brief Evaluate the target distribution\n   * @param trans - translation from map frame to fourier domain\n   * @param phi_grid - discretization of fourier domain\n   * @return target evaluated at each grid cell in phi_grid\n   * @details the translation is used to translate the mean into the fourier domain\n   */\n  vec fill(const vec& trans, const mat& phi_grid) const;\n\n  /**\n   * @brief Visualize target distribution\n   * @param frame - target frame\n   * @return target is visualized as an ellipse\n   */\n  visualization_msgs::MarkerArray markers(const std::string& frame) const;\n\nprivate:\n  GaussianList gaussians_;  // list of target gaussians\n};\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "8fde2d6465b7738bd0bb2b07e3eb5079b3cdecae", "size": 5069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/target.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/target.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/target.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": 30.9085365854, "max_line_length": 85, "alphanum_fraction": 0.6756756757, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5760206261537473}}
{"text": "// A numerically integrated implementation of the circuit described in\n// \"Rolling Your Own Circuit Simulator with Eigen and Boost.ODEInt\"\n// Author: Jeff Trull <edaskel@att.net>\n\n/*\nCopyright (c) 2014 Jeffrey E. Trull\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n#include <iostream>\n#include <array>\n#include <boost/numeric/odeint.hpp>\n\ntypedef std::array<double, 2> state_t;   // 0 = V_out, 1 = I_L\n\nstruct circuit {\n    circuit(double r, double l, double c) : r_(r), l_(l), c_(c) {}\n\n    void operator()(state_t const& x, state_t& dxdt, double t) {\n        // calculate state derivatives from current state\n        dxdt[0] = ((1 - x[0]) / r_ - x[1]) / c_;  // KCL at V_out node\n        dxdt[1] = x[0] / l_;                      // from V_out = L * dI_L/dt\n    }\nprivate:\n    double r_, l_, c_;\n};\n\nint main() {\n    using namespace boost::numeric::odeint;\n    circuit ckt(100.0, 20e-6, 20e-9);\n    state_t x{0.0, 0.0};                    // initial conditions\n    integrate( ckt, x, 0.0, 10e-6, 0.1e-6,  // time range and increment\n               [](state_t const& x, double t) {\n                   std::cout << t << \" \" << x[0] << std::endl;\n               });\n}\n", "meta": {"hexsha": "92e746efc02300722e6b179ac648a17da3194ef3", "size": 2149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "odeint.cpp", "max_stars_repo_name": "jefftrull/CktSimLightningTalk", "max_stars_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T10:52:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-03T00:49:12.000Z", "max_issues_repo_path": "odeint.cpp", "max_issues_repo_name": "jefftrull/CktSimLightningTalk", "max_issues_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "odeint.cpp", "max_forks_repo_name": "jefftrull/CktSimLightningTalk", "max_forks_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_forks_repo_licenses": ["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.7962962963, "max_line_length": 77, "alphanum_fraction": 0.6812470917, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5760206208836683}}
{"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_SQRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the square root of its parameter.\n    For integers it is the truncation of the real square root.\n\n    @par Header <boost/simd/function/sqrt.hpp>\n\n    @par Decorators\n\n    - std_ calls std::sqrt\n\n    - raw_ for floating entries can gain some speed with less accuracy\n    on some architectures.\n\n    @see rsqrt, sqr_abs, sqr\n\n    @par Example:\n\n      @snippet sqrt.cpp sqrt\n\n    @par Possible output:\n\n      @snippet sqrt.txt sqrt\n\n  **/\n  Value sqrt(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/simd/function/simd/sqrt.hpp>\n\n#endif\n", "meta": {"hexsha": "c8a9349787d49d7d9469f154f6005c1f0d31bc5a", "size": 1198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sqrt.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/sqrt.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/sqrt.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.0384615385, "max_line_length": 100, "alphanum_fraction": 0.5943238731, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5760150628678155}}
{"text": "#pragma once\r\n#ifndef CELL_HPP\r\n#define CELL_HPP\r\n\r\n// c++ libraries\r\n#include <iosfwd>\r\n// eigen libraries\r\n#include <Eigen/Dense>\r\n// ann - serialization\r\n#include \"src/mem/serialize.hpp\"\r\n\r\n//****************************************************************\r\n//Cell class\r\n//****************************************************************\r\n\r\nclass Cell{\r\nprivate:\r\n\t//==== members ====\r\n\tdouble vol_;//the volume of the simulation cell\r\n\tEigen::Matrix3d R_;//the lattice vector matrix (lattice vectors are columns of the matrix)\r\n\tEigen::Matrix3d RInv_;//the inverse of the lattice vector matrix\r\n\tEigen::Matrix3d K_;//the repiprocal lattice vector matrix (lattice vectors are columns of the matrix\r\n\tEigen::Matrix3d KInv_;//the inverse of the reciprocal lattice vector matrix\r\npublic:\t\r\n\t//==== constructors/destructors ====\r\n\tCell(){defaults();}\r\n\tCell(const Eigen::Matrix3d& R){init(R);}\r\n\t~Cell(){}\r\n\t\r\n\t//==== operators ====\r\n\tfriend std::ostream& operator<<(std::ostream& out, const Cell& cell);\r\n\t\r\n\t//==== access ====\r\n\tdouble& vol(){return vol_;}\r\n\tconst double& vol()const{return vol_;}\r\n\tconst Eigen::Matrix3d& R()const{return R_;}\r\n\tconst Eigen::Matrix3d& RInv()const{return RInv_;}\r\n\tconst Eigen::Matrix3d& K()const{return K_;}\r\n\tconst Eigen::Matrix3d& KInv()const{return KInv_;}\r\n\t\r\n\t//==== static functions - vector operations ====\r\n\tstatic Eigen::Vector3d& sum(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& sum, const Eigen::Matrix3d& R, const Eigen::Matrix3d& RInv);\r\n\tstatic Eigen::Vector3d& diff(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& diff, const Eigen::Matrix3d& R, const Eigen::Matrix3d& RInv);\r\n\tstatic double dist(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& tmp, const Eigen::Matrix3d& R, const Eigen::Matrix3d& RInv);\r\n\tstatic double dist(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, const Eigen::Matrix3d& R, const Eigen::Matrix3d& RInv);\r\n\tstatic Eigen::Vector3d& fracToCart(const Eigen::Vector3d& vFrac, Eigen::Vector3d& vCart, const Eigen::Matrix3d& R);\r\n\tstatic Eigen::Vector3d& cartToFrac(const Eigen::Vector3d& vCart, Eigen::Vector3d& vFrac, const Eigen::Matrix3d& RInv);\r\n\tstatic Eigen::Vector3d& returnToCell(const Eigen::Vector3d& v1, Eigen::Vector3d& v2, const Eigen::Matrix3d& R, const Eigen::Matrix3d& RInv);\r\n\t\r\n\t//==== vector operations ====\r\n\tEigen::Vector3d& sum(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& sum)const;\r\n\tEigen::Vector3d& diff(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& diff)const;\r\n\tdouble dist(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)const;\r\n\tdouble dist(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& tmp)const;\r\n\tdouble dist2(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2, Eigen::Vector3d& tmp)const;\r\n\tEigen::Vector3d& modv(const Eigen::Vector3d& v1, Eigen::Vector3d& v2);\r\n\t\r\n\t//==== static functions - modification ====\r\n\tstatic Cell& make_super(const Eigen::Vector3i& s, const Cell& cell1, Cell& cell2);\r\n\t\r\n\t//==== member functions ====\r\n\tvoid defaults();\r\n\tvoid clear(){defaults();}\r\n\tvoid init(const Eigen::Matrix3d& R);\r\n};\r\n\r\nbool operator==(const Cell& c1, const Cell& c2);\t\r\nbool operator!=(const Cell& c1, const Cell& c2);\r\n\r\nnamespace serialize{\r\n\t\r\n\t//**********************************************\r\n\t// byte measures\r\n\t//**********************************************\r\n\r\n\ttemplate <> int nbytes(const Cell& obj);\r\n\t\r\n\t//**********************************************\r\n\t// packing\r\n\t//**********************************************\r\n\r\n\ttemplate <> int pack(const Cell& obj, char* arr);\r\n\t\r\n\t//**********************************************\r\n\t// unpacking\r\n\t//**********************************************\r\n\r\n\ttemplate <> int unpack(Cell& obj, const char* arr);\r\n\t\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "aba4573df616ca7dc8e18fc4c5e20e63e23c9691", "size": 3848, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/struc/cell.hpp", "max_stars_repo_name": "markdellostritto/AtomNN", "max_stars_repo_head_hexsha": "763aa2ca12916638fcca14d5bddafe1112d603cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/struc/cell.hpp", "max_issues_repo_name": "markdellostritto/AtomNN", "max_issues_repo_head_hexsha": "763aa2ca12916638fcca14d5bddafe1112d603cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/struc/cell.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": 41.376344086, "max_line_length": 163, "alphanum_fraction": 0.6148648649, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.575921644584239}}
{"text": "/* Copyright 2020 Oinam Romesh Meitei\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n \n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <vector>\n#include \"pulsec.h\"\n\n\n/* Piecewise square pulse */\n\nstd::complex<double> pcoef(double &t, std::vector< double > &amp,\n\t\t\t   std::vector< double > &tseq,\n\t\t\t   double &freq,\n\t\t\t   double &tfinal){\n\n  double  etmp;\n  int i, tlen;\n  std::complex <double>  coef;\n\n  \n  std::complex<double> etmp1(0.0, -1.0*freq*t);\n  etmp1 = std::exp(etmp1);\n  \n  tlen = tseq.size();\n  for (i=0;i<tlen;i++){\n    if (i==0){\n      if (0.0 < t && t <= tseq[i]){\n\tcoef = amp[i] * etmp1;\n      }\n    }\n    else {\n      if (tseq[i-1] < t && t <= tseq[i]){\n\tcoef = amp[i] * etmp1;\n      }\n    }\n  }\n  if (tseq[tlen-1] < t && t <= tfinal){\n    coef = amp[tlen] * etmp1;\n  \n  }\n  return coef;\n}\n\n\nEigen::SparseMatrix<std::complex<double> >\ngetham(double &t, pulsec &pobj,\n       std::vector< std::vector< Eigen::SparseMatrix<double,0,ptrdiff_t> > > &hdrive,\n       std::vector< std::complex<double> > &dsham, int &dsham_len,\n       Eigen::SparseMatrix<std::complex<double> > &matexp_){\n\n  // dsham is different from python version, here it's the diagonal of\n  // -1j*hobj.dsham in the python version.\n \n  Eigen::SparseMatrix<std::complex<double> > hamdr;\n  std::complex<double> hcoef, hcoefc;\n \n  int i;\n  for (i=0;i<pobj.nqubit;i++) {\n    hcoef = pcoef( t, pobj.amp[i], pobj.tseq[i], pobj.freq[i],\n\t\t   pobj.duration);\n    \n    hcoefc = std::conj(hcoef);\n\n    if (i==0){\n      hamdr = hcoef * hdrive[i][0];\n    } else {\n      hamdr += hcoef * hdrive[i][0];\n    }\n\n    hamdr += hcoefc * hdrive[i][1];\n  }\n      \n  for (i=0;i<dsham_len; i++){\n    matexp_.coeffRef(i,i) = std::exp(dsham[i] * t);\n  }\n\n  Eigen::SparseMatrix<std::complex<double> >\n  hamr_ = (matexp_.conjugate().transpose() * hamdr);\n  hamr_ = (hamr_ * matexp_).pruned();\n  \n  return hamr_;\n}\n", "meta": {"hexsha": "f3e74cb05cc1d2ac43c04d0494f98c51bb80e95b", "size": 2426, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ctrlq/lib/getham.cc", "max_stars_repo_name": "nkcxliu2/ctrlq", "max_stars_repo_head_hexsha": "d412641c6cef62ba0f1cb069c5580b834fa03142", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T16:16:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T17:57:50.000Z", "max_issues_repo_path": "ctrlq/lib/getham.cc", "max_issues_repo_name": "nkcxliu2/ctrlq", "max_issues_repo_head_hexsha": "d412641c6cef62ba0f1cb069c5580b834fa03142", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctrlq/lib/getham.cc", "max_forks_repo_name": "nkcxliu2/ctrlq", "max_forks_repo_head_hexsha": "d412641c6cef62ba0f1cb069c5580b834fa03142", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-07T05:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T01:48:31.000Z", "avg_line_length": 24.7551020408, "max_line_length": 85, "alphanum_fraction": 0.6166529266, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5759216393653362}}
{"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2009\n//\n//============================================================================\n\n#include \"StdLinearSolver.hpp\"\n#include \"../IDenseMatrix.hpp\"\n#include \"../ICompressedSparseMatrix.hpp\"\n#include \"NNLS/nnls.h\"\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/QR>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n#include <Eigen/SVD>\n#include <type_traits>\n\nnamespace Thea {\nnamespace Algorithms {\n\nnamespace StdLinearSolverInternal {\n\n// Implementation of StdLinearSolver functions.\nclass THEA_DLL_LOCAL StdLinearSolverImpl\n{\n  public:\n    // Constructor.\n    StdLinearSolverImpl(StdLinearSolver::Method method_, StdLinearSolver::Constraint constraint_)\n    : method(method_), constraint(constraint_), tolerance(-1), max_iters(-1), ndims(0), has_solution(false)\n    {}\n\n    // Solve the linear system Ax = b for a dense double-precision matrix A.\n    template < typename MatrixT, typename ScalarT,\n               typename std::enable_if< std::is_same<typename MatrixT::value_type, ScalarT>::value, int >::type = 0 >\n    bool solve(Eigen::MatrixBase<MatrixT> const & a, ScalarT const * b, IOptions const * options = nullptr)\n    {\n      if (a.rows() < a.cols())\n        THEA_WARNING << \"StdLinearSolver: Fewer objectives than dimensions -- the solution will not be unique\";\n\n      has_solution = false;\n      try\n      {\n        if (a.rows() <= 0 || a.cols() <= 0)\n          throw Error(\"Empty coefficient matrix\");\n\n        intx num_objectives = a.rows();\n        ndims = a.cols();\n\n        switch (constraint)\n        {\n          case StdLinearSolver::Constraint::NON_NEGATIVE:\n          {\n            if (method != StdLinearSolver::Method::DEFAULT && method != StdLinearSolver::Method::NNLS)\n              throw Error(\"Unsupported method for non-negative least squares problems\");\n\n            // Values will be overwritten anyway, so make copies\n            MatrixX<double, MatrixLayout::COLUMN_MAJOR> nnls_a = a.template cast<double>();  // NNLS needs Fortran COLUMN-MAJOR\n            VectorX<double> nnls_b = Eigen::Map< VectorX<ScalarT> const >(b, num_objectives).template cast<double>();\n\n            solution.resize(ndims);\n\n            double         rnorm;\n            Array<double>  w((size_t)ndims);\n            Array<double>  zz((size_t)num_objectives);\n            Array<int>     index((size_t)ndims);\n            int            mode;\n\n            int mda = (int)num_objectives, im = (int)num_objectives, in = (int)ndims;\n\n            // NOTE: Assume float64 == double, for passing solution vector to NNLS\n            nnls_c(nnls_a.data(), &mda, &im, &in, nnls_b.data(), solution.data(), &rnorm, &w[0], &zz[0], &index[0], &mode);\n\n            if (mode == 1)\n              has_solution = true;\n            else\n            {\n              switch (mode)\n              {\n                // Should never be 2 since we've checked for this above, but recheck all the same\n                case 2:  THEA_DEBUG << \"StdLinearSolver: NNLS error (bad problem dimensions)\"; break;\n                case 3:  THEA_DEBUG << \"StdLinearSolver: NNLS error (iteration count exceeded)\"; break;\n                default: THEA_DEBUG << \"StdLinearSolver: Unknown NNLS error\";\n              }\n            }\n\n            break;\n          }\n\n          case StdLinearSolver::Constraint::UNCONSTRAINED:\n          {\n            switch (method)\n            {\n              case StdLinearSolver::Method::HOUSEHOLDER_QR:\n              {\n                Eigen::HouseholderQR<typename MatrixT::PlainObject> solver(a);\n                solution = solver.solve(Eigen::Map< VectorX<ScalarT> const >(b, num_objectives));\n                has_solution = true;\n                break;\n              }\n\n              case StdLinearSolver::Method::DEFAULT:  // slower than plain Householder, but more accurate\n              case StdLinearSolver::Method::COL_PIV_HOUSEHOLDER_QR:\n              {\n                Eigen::ColPivHouseholderQR<typename MatrixT::PlainObject> solver(a);\n                if (tolerance >= 0) solver.setThreshold(tolerance);\n                solution = solver.solve(Eigen::Map< VectorX<ScalarT> const >(b, num_objectives));\n                has_solution = true;\n                break;\n              }\n\n              case StdLinearSolver::Method::FULL_PIV_HOUSEHOLDER_QR:\n              {\n                Eigen::FullPivHouseholderQR<typename MatrixT::PlainObject> solver(a);\n                if (tolerance >= 0) solver.setThreshold(tolerance);\n                solution = solver.solve(Eigen::Map< VectorX<ScalarT> const >(b, num_objectives));\n                has_solution = true;\n                break;\n              }\n\n              case StdLinearSolver::Method::COMPLETE_ORTHOGONAL_DECOMPOSITION:\n              {\n                Eigen::CompleteOrthogonalDecomposition<typename MatrixT::PlainObject> solver(a);\n                if (tolerance >= 0) solver.setThreshold(tolerance);\n                solution = solver.solve(Eigen::Map< VectorX<ScalarT> const >(b, num_objectives));\n                has_solution = true;\n                break;\n              }\n\n              case StdLinearSolver::Method::BDCSVD:\n              {\n                Eigen::BDCSVD<typename MatrixT::PlainObject> solver(a);\n                if (tolerance >= 0) solver.setThreshold(tolerance);\n                solution = solver.solve(Eigen::Map< VectorX<ScalarT> const >(b, num_objectives));\n                has_solution = true;\n                break;\n              }\n\n              default:\n                throw Error(\"Unsupported method for unconstrained dense least squares problems\");\n            }\n\n            break;\n          }\n\n          default:\n            throw Error(\"Unsupported constraint\");\n        }\n      }\n      THEA_STANDARD_CATCH_BLOCKS(return false;, ERROR, \"%s\",\n                                 \"StdLinearSolver: Error solving dense linear least-squares system\")\n\n      return has_solution;\n    }\n\n    // Solve the linear system Ax = b for a sparse ScalarT-precision matrix A.\n    template < typename MatrixT, typename ScalarT,\n               typename std::enable_if< std::is_same<typename MatrixT::value_type, ScalarT>::value, int >::type = 0 >\n    bool solve(Eigen::SparseMatrixBase<MatrixT> const & a, ScalarT const * b, IOptions const * options = nullptr)\n    {\n      if (a.rows() < a.cols())\n        THEA_WARNING << \"StdLinearSolver: Fewer objectives than dimensions -- the solution will not be unique\";\n\n      has_solution = false;\n      try\n      {\n        if (a.rows() <= 0 || a.cols() <= 0)\n          throw Error(\"Empty coefficient matrix\");\n\n        ndims = a.cols();\n\n        switch (constraint)\n        {\n          case StdLinearSolver::Constraint::UNCONSTRAINED:\n          {\n            // Return true if a matching solver was found\n            if (solveSparseFactorize(a, b)) break;\n            if (solveIterative(a, b)) break;\n\n            throw Error(\"Unsupported method for unconstrained sparse least squares problems\");\n          }\n\n          default:\n            throw Error(\"Unsupported constraint\");\n        }\n      }\n      THEA_STANDARD_CATCH_BLOCKS(return false;, ERROR, \"%s\",\n                                 \"StdLinearSolver: Error solving sparse linear least-squares system\")\n\n      return has_solution;\n    }\n\n  private:\n    // Use one of the iterative solvers to solve the dense or sparse problem. Returns true if a suitable solver was found, NOT\n    // if the problem was successfully solved.\n    template <typename MatrixT, typename ScalarT> bool solveIterative(MatrixT const & a, ScalarT const * b)\n    {\n      switch (method)\n      {\n        case StdLinearSolver::Method::CONJUGATE_GRADIENT:\n        {\n          Eigen::ConjugateGradient<typename MatrixT::PlainObject> solver;\n          if (tolerance >= 0) solver.setTolerance((ScalarT)tolerance);\n          if (max_iters > 0) solver.setMaxIterations(max_iters);\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        case StdLinearSolver::Method::DEFAULT:\n        case StdLinearSolver::Method::LEAST_SQUARES_CONJUGATE_GRADIENT:\n        {\n          Eigen::LeastSquaresConjugateGradient<typename MatrixT::PlainObject> solver;\n          if (tolerance >= 0) solver.setTolerance((ScalarT)tolerance);\n          if (max_iters > 0) solver.setMaxIterations(max_iters);\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        case StdLinearSolver::Method::BICGSTAB:\n        {\n          Eigen::BiCGSTAB<typename MatrixT::PlainObject> solver;\n          if (tolerance >= 0) solver.setTolerance((ScalarT)tolerance);\n          if (max_iters > 0) solver.setMaxIterations(max_iters);\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        default: return false;\n      }\n\n      return true;\n    }\n\n    // Use a solver based on sparse factorization, for column-major matrices. Returns true if a suitable solver was found, NOT\n    // if the problem was successfully solved.\n    template < typename MatrixT, typename ScalarT,\n               typename std::enable_if< !(MatrixT::Flags & Eigen::RowMajorBit), int >::type = 0 >\n    bool solveSparseFactorize(MatrixT const & a, ScalarT const * b)\n    {\n      switch (method)\n      {\n        case StdLinearSolver::Method::SIMPLICIALT_LLT:\n        {\n          Eigen::SimplicialLLT<typename MatrixT::PlainObject> solver;\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        case StdLinearSolver::Method::SIMPLICIALT_LDLT:\n        {\n          Eigen::SimplicialLDLT<typename MatrixT::PlainObject> solver;\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        case StdLinearSolver::Method::SPARSE_LU:\n        {\n          Eigen::SparseLU<typename MatrixT::PlainObject> solver;\n          if (tolerance >= 0) solver.setPivotThreshold((ScalarT)tolerance);\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        case StdLinearSolver::Method::DEFAULT:\n        case StdLinearSolver::Method::SPARSE_QR:\n        {\n          Eigen::SparseQR<typename MatrixT::PlainObject, Eigen::AMDOrdering<typename MatrixT::StorageIndex> > solver;\n          if (tolerance >= 0) solver.setPivotThreshold((ScalarT)tolerance);\n          solver.compute(a);\n          if (solver.info() == Eigen::Success)\n          {\n            solution = solver.solve(Eigen::Map< VectorX<ScalarT> >(const_cast<ScalarT *>(b), a.rows()));\n            has_solution = (solver.info() == Eigen::Success);\n          }\n          break;\n        }\n\n        default: return false;\n      }\n\n      return true;\n    }\n\n    // Use a solver based on sparse factorization, for row-major matrices. Eigen does not provide any such solvers, so this\n    // method is empty. Returns false to indicate no solver was found.\n    template < typename MatrixT, typename ScalarT,\n               typename std::enable_if< (MatrixT::Flags & Eigen::RowMajorBit), int >::type = 0 >\n    bool solveSparseFactorize(MatrixT const & a, ScalarT const * b)\n    {\n      return false;\n    }\n\n  public:  // no need for accessor fns for this internal class, and friend declarations are complicated by namespaces\n    StdLinearSolver::Method method;          // Solution method.\n    StdLinearSolver::Constraint constraint;  // Solution constraint.\n    double tolerance;                        // Solution tolerance/threshold.\n    intx max_iters;                          // Maximum number of solver iterations, if solver is iterative.\n    intx ndims;                              // Solution dimensions.\n    bool has_solution;                       // Was a solution computed by the last call to solve()? */\n    VectorX<float64> solution;               // The solution vector <b>x</b>.\n};\n\n// Shorthand\ntemplate <MatrixLayout::Value L, typename StorageIndex> using SM = Eigen::Map< SparseMatrix<double, L, StorageIndex> >;\n\n// Given a storage index type, dispatch a call to StdLinearSolverImpl::solve() with the correct pointer conversions\ntemplate <MatrixLayout::Value L, typename ScalarT>\nbool\nimplSolve(StdLinearSolverImpl * impl, int storage_type, intx nr, intx nc, intx nnz, void const * in, void const * out,\n          ScalarT const * val, void const * nzc, ScalarT const * b, IOptions const * opt)\n{\n  void    * in2  = const_cast<void *>(in);\n  void    * out2 = const_cast<void *>(out);\n  ScalarT * val2 = const_cast<ScalarT *>(val);\n  void    * nzc2 = const_cast<void *>(nzc);\n\n  switch (storage_type)\n  {\n// A casting bug in the current Eigen prevents us using StorageIndex shorter than an int.\n// Specifically, OrderingMethods/Amd.h, L104: dense = (std::min)(n-2, dense);\n// Here n and dense are of type StorageIndex, but n - 2 is of type int for StorageIndex shorter than an int, so std::min fails\n// because the arguments are not of the same type.\n//\n//     case NumericType::INT8:\n//       return impl->solve(SM<L, int8  >(nr, nc, nnz, (int8   *)in2, (int8   *)out2, val2, (int8   *)nzc2), b, opt);\n//     case NumericType::INT16:\n//       return impl->solve(SM<L, int16 >(nr, nc, nnz, (int16  *)in2, (int16  *)out2, val2, (int16  *)nzc2), b, opt);\n    case NumericType::INT32:\n      return impl->solve(SM<L, int32 >(nr, nc, nnz, (int32  *)in2, (int32  *)out2, val2, (int32  *)nzc2), b, opt);\n    case NumericType::INT64:\n      return impl->solve(SM<L, int64 >(nr, nc, nnz, (int64  *)in2, (int64  *)out2, val2, (int64  *)nzc2), b, opt);\n    default: THEA_ERROR << \"StdLinearSolver: Unsupported index type\";\n  }\n\n  return false;\n}\n\n} // namespace StdLinearSolverInternal\n\nStdLinearSolver::StdLinearSolver(Method method_, Constraint constraint_)\n: NamedObject(\"StdLinearSolver\"), impl(new StdLinearSolverInternal::StdLinearSolverImpl(method_, constraint_))\n{\n}\n\nStdLinearSolver::~StdLinearSolver()\n{\n  delete impl;\n}\n\nStdLinearSolver::Method\nStdLinearSolver::getMethod() const\n{\n  return impl->method;\n}\n\nStdLinearSolver::Constraint\nStdLinearSolver::getConstraint() const\n{\n  return impl->constraint;\n}\n\ndouble\nStdLinearSolver::getTolerance() const\n{\n  return impl->tolerance;\n}\n\nintx\nStdLinearSolver::maxIterations() const\n{\n  return impl->max_iters;\n}\n\nvoid\nStdLinearSolver::setMethod(StdLinearSolver::Method method_)\n{\n  impl->method = method_;\n}\n\nvoid\nStdLinearSolver::setConstraint(StdLinearSolver::Constraint constraint_)\n{\n  impl->constraint = constraint_;\n}\n\nvoid\nStdLinearSolver::setTolerance(double tol)\n{\n  impl->tolerance = tol;\n}\n\nvoid\nStdLinearSolver::setMaxIterations(intx max_iters_)\n{\n  impl->max_iters = max_iters_;\n}\n\nbool\nStdLinearSolver::solve(Eigen::Ref< MatrixXd > const & a, float64 const * b, IOptions const * options)\n{\n  return impl->solve(a, b, options);\n}\n\nbool\nStdLinearSolver::solve(Eigen::Ref< SparseMatrix<double> > const & a, float64 const * b, IOptions const * options)\n{\n  return impl->solve(a, b, options);\n}\n\nint8\nStdLinearSolver::solve(IMatrix<float64> const * a, float64 const * b, IOptions const * options)\n{\n  alwaysAssertM(a, \"StdLinearSolver: Coefficient matrix is null\");\n  alwaysAssertM(b, \"StdLinearSolver: Constant matrix is null\");\n\n  if (a->asAddressable() && a->asAddressable()->asDense())\n  {\n    IDenseMatrix<float64> const & dm = *a->asAddressable()->asDense();\n    if (dm.isRowMajor())\n    {\n      Eigen::Map< MatrixX<float64, MatrixLayout::ROW_MAJOR> const > wrapped(dm.data(), dm.rows(), dm.cols());\n      return impl->solve(wrapped, b, options);\n    }\n    else  // col-major\n    {\n      Eigen::Map< MatrixX<float64, MatrixLayout::COLUMN_MAJOR> const > wrapped(dm.data(), dm.rows(), dm.cols());\n      return impl->solve(wrapped, b, options);\n    }\n  }\n  else if (a->asSparse() && a->asSparse()->asCompressed())\n  {\n    ICompressedSparseMatrix<float64> const & sm = *a->asSparse()->asCompressed();\n    int storage_type = sm.getInnerIndexType();\n    if (storage_type != sm.getOuterIndexType() || storage_type != sm.getNonZeroCountType())\n    {\n      // TODO: Convert to integer arrays of consistent type to work around this problem\n\n      THEA_ERROR << \"StdLinearSolver: Different indices have different storage types -- cannot convert to SparseMatrix\";\n      return false;\n    }\n\n    if (sm.isRowMajor())\n      return StdLinearSolverInternal::implSolve<MatrixLayout::ROW_MAJOR>(impl, storage_type, sm.rows(), sm.cols(),\n                                                                         sm.numStoredElements(), sm.getOuterIndices(),\n                                                                         sm.getInnerIndices(), sm.getValues(),\n                                                                         sm.getNonZeroCounts(), b, options);\n    else\n      return StdLinearSolverInternal::implSolve<MatrixLayout::COLUMN_MAJOR>(impl, storage_type, sm.rows(), sm.cols(),\n                                                                            sm.numStoredElements(), sm.getOuterIndices(),\n                                                                            sm.getInnerIndices(), sm.getValues(),\n                                                                            sm.getNonZeroCounts(), b, options);\n  }\n  else\n  {\n    THEA_ERROR << \"StdLinearSolver: Unsupported matrix type\";\n    return false;\n  }\n}\n\nint64\nStdLinearSolver::dims() const\n{\n  return (int64)impl->ndims;\n}\n\nint8\nStdLinearSolver::hasSolution() const\n{\n  return impl->has_solution;\n}\n\nfloat64 const *\nStdLinearSolver::getSolution() const\n{\n  return impl->solution.data();\n}\n\nint8\nStdLinearSolver::getSquaredError(float64 * err) const\n{\n  return false;\n}\n\n} // namespace Algorithms\n} // namespace Thea\n", "meta": {"hexsha": "334356070257cbdddb0e6f20fb85ce8e809e1bb4", "size": 19237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/StdLinearSolver.cpp", "max_stars_repo_name": "christinazavou/Thea", "max_stars_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Source/Algorithms/StdLinearSolver.cpp", "max_issues_repo_name": "christinazavou/Thea", "max_issues_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Source/Algorithms/StdLinearSolver.cpp", "max_forks_repo_name": "christinazavou/Thea", "max_forks_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7118320611, "max_line_length": 127, "alphanum_fraction": 0.6014971149, "num_tokens": 4473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5759216335712122}}
{"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 cart.hpp\n * @author Boston Cleek\n * @date 28 Oct 2020\n * @brief Kinematic cart models control wheel velocities or body twist\n */\n#ifndef CART_HPP\n#define CART_HPP\n\n#include <cmath>\n#include <stdexcept>\n\n#include <armadillo>\n\n#include <ergodic_exploration/numerics.hpp>\n\nnamespace ergodic_exploration\n{\nnamespace models\n{\nusing arma::mat;\nusing arma::vec;\n\n/**\n * @brief Kinematic model of 2 wheel differential drive robot\n * @details The state is [x, y, theta] and controls are the velocities of each wheel [u0,\n * u1] corresponding to the left and right wheels\n */\nstruct Cart\n{\n  /**\n   * @brief Constructor\n   * @param wheel_radius - radius of wheel\n   * @param wheel_base - distance from point at the center in between both wheels to the\n   * center of a wheel\n   */\n  Cart(double wheel_radius, double wheel_base)\n    : wheel_radius(wheel_radius), wheel_base(wheel_base), state_space(3)\n  {\n  }\n\n  /**\n   * @brief Convert wheel velocities to a body frame twist\n   * @param u - control [u0, u1]\n   * @return twist in body frame Vb = [vx, vy, w]\n   */\n  vec wheels2Twist(const vec u) const\n  {\n    const double vx = wheel_radius / 2.0 * (u(0) + u(1));\n    const double w = wheel_radius / (2.0 * wheel_base) * (u(1) - u(0));\n\n    return { vx, 0.0, w };\n  }\n\n  /**\n   * @brief Kinematic model of a 2 wheel differential drive robot\n   * @param x - state [x, y, theta]\n   * @param u - control [uL, uR]\n   * @return [xdot, ydot, thetadot] = f(x,u)\n   */\n  vec operator()(const vec x, const vec u) const\n  {\n    vec xdot(3);\n    xdot(0) = (u(0) + u(1)) * std::cos(x(2));\n    xdot(1) = (u(0) + u(1)) * std::sin(x(2));\n    xdot(2) = (u(1) - u(0)) / wheel_base;\n\n    return (wheel_radius / 2.0) * xdot;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the state\n   * @param x - state [x, y, theta]\n   * @param u - control [uL, uR]\n   * @return A = D1(f(x,u)) of shape (3x3)\n   */\n  mat fdx(const vec x, const vec u) const\n  {\n    mat A(3, 3, arma::fill::zeros);\n\n    const auto df0dth = -(wheel_radius / 2.0) * (u(0) + u(1)) * std::sin(x(2));\n    const auto df1dth = (wheel_radius / 2.0) * (u(0) + u(1)) * std::cos(x(2));\n\n    A(0, 2) = df0dth;\n    A(1, 2) = df1dth;\n\n    return A;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the control\n   * @param x - state [x, y, theta]\n   * @return B = D2(f(x,u)) of shape (3x2)\n   */\n  mat fdu(const vec x) const\n  {\n    mat B(3, 2);\n\n    B(0, 0) = std::cos(x(2));\n    B(0, 1) = std::cos(x(2));\n\n    B(1, 0) = std::sin(x(2));\n    B(1, 1) = std::sin(x(2));\n\n    B(2, 0) = -1.0 / wheel_base;\n    B(2, 1) = 1.0 / wheel_base;\n\n    return (wheel_radius / 2.0) * B;\n  }\n\n  double wheel_radius;       // radius of wheel\n  double wheel_base;         // distance from robot center to wheel center\n  unsigned int state_space;  // states space dimension\n};\n\n/**\n * @brief Kinematic model of a wheeled differential drive robot\n * @details The state is [x, y, theta] and controls are the linear and\n * angular velocities [vx, vy, w] (body twist)\n */\nstruct SimpleCart\n{\n  /** @brief Constructor */\n  SimpleCart() : state_space(3)\n  {\n  }\n\n  /**\n   * @brief Kinematic model of a 2 wheel differential drive robot\n   * @param x - state [x, y, theta]\n   * @param u - body twist control [vx, vy, w]\n   * @return xdot = f(x,u)\n   */\n  vec operator()(const vec x, const vec u) const\n  {\n    if (!almost_equal(u(1), 0.0))\n    {\n      throw std::invalid_argument(\"Invalid twist y-velocity must be 0.\");\n    }\n\n    return { u(0) * std::cos(x(2)), u(0) * std::sin(x(2)), u(2) };\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the state\n   * @param x - state [x, y, theta]\n   * @param u - body twist control [vx, vy, w]\n   * @return A = D1(f(x,u)) of shape (3x3)\n   */\n  mat fdx(const vec x, const vec u) const\n  {\n    mat A(3, 3, arma::fill::zeros);\n    A(0, 2) = -u(0) * std::sin(x(2));\n    A(1, 2) = u(0) * std::cos(x(2));\n    return A;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the control\n   * @param x - state [x, y, theta]\n   * @return B = D2(f(x,u)) of shape (3x3)\n   */\n  mat fdu(const vec x) const\n  {\n    mat B(3, 3, arma::fill::zeros);\n\n    B(0, 0) = std::cos(x(2));\n    B(1, 0) = std::sin(x(2));\n    B(2, 2) = 1.0;\n\n    return B;\n  }\n\n  unsigned int state_space;  // states space dimension\n};\n}  // namespace models\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "65b5db78dee167cfbdb276f9e4529c9cbbe2b3d4", "size": 6108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/models/cart.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/models/cart.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/models/cart.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": 29.0857142857, "max_line_length": 89, "alphanum_fraction": 0.6185330714, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.57590253025498}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include <NTL/lzz_pXFactoring.h>\n\n#include <cassert>\n#include <cstdio>\n#include <iostream>\nusing namespace std;\n\nCtxt FHE_Add(Ctxt Ea, Ctxt Eb)\n{\n\tCtxt ctSum = Ea;\n\tctSum += Eb;\n\treturn ctSum;\n}\n\nCtxt FHE_Mul(Ctxt Ea, Ctxt Eb)\n{\n\tCtxt ctMul = Ea;\n\tctMul *= Eb;\n\treturn ctMul;\n}\n\nCtxt FHE_Sub(Ctxt Ea, Ctxt Eb, const FHEPubKey& publicKey)\n{\n\tCtxt minus1(publicKey);\n\tpublicKey.Encrypt(minus1, to_ZZX(-1));\n\tCtxt ctSub = Eb;\n\tctSub *= minus1;\n\tctSub += Ea;\n\treturn ctSub;\n}\n\nCtxt FHE_Div(Ctxt Ea, Ctxt Eb, long p,\n\t\t\t const FHEPubKey& publicKey, const FHESecKey& secretKey)\n{\n\tint quotient = 0;\n\tbool flag = true;\n\twhile (flag)\n\t{\n\t\tCtxt ctSub = FHE_Sub(Ea, Eb, publicKey);\n\t\tZZX ptSub;\n\t\tsecretKey.Decrypt(ptSub, ctSub);\n\t\tlong sub;\n\t\tconv(sub, ptSub[0]);\n\t\tif (sub <= p/2)\n\t\t{\n\t\t\tEa = ctSub;\n\t\t\tquotient ++;\n\t\t}\n\t\tif (sub >= p/2)\n\t\t\tflag = false;\n\t}\n\tCtxt ctDiv(publicKey);\n\tpublicKey.Encrypt(ctDiv, to_ZZX(quotient));\n\treturn ctDiv;\n}\n\nint main()\n{\n\tlong m = 0;    // 确定系数\n\tlong p = 1021; // 2^64\n\tlong r = 1;\n\tlong L = 16;\n\tlong c = 3;\n\tlong w = 64;\n\tlong d = 0;\n\tlong k = 128;\n\tlong s = 0;\n\n\tm = FindM(k, L, c, p, d, s, 0);\n\n\tFHEcontext context(m, p, r);\n\tbuildModChain(context, L, c);\n\n\tZZX G = context.alMod.getFactorsOverZZ()[0];\n\n\tFHESecKey secretKey(context);\n\tconst FHEPubKey& publicKey = secretKey;\n\tsecretKey.GenSecKey(w);\n\n\tCtxt Ea(publicKey);\n\tCtxt Eb(publicKey);\n\n\tVec<ZZ> h;\n\th.SetLength(4);\n\th[0]=2;\n\th[1]=2;\n\th[2]=0;\n\th[3]=0;\n\n\n\tpublicKey.Encrypt(Ea, to_ZZX(h));\n\t//publicKey.Encrypt(Eb, to_ZZX(2));\n\n\tZZX ptEa;\n\tsecretKey.Decrypt(ptEa, Ea);\n\tcout << \"ptEa : \" << ptEa <<endl;\n\n/*\n\tZZX ptSum;\n\tCtxt ctSum = FHE_Add(Ea, Eb);\n\tsecretKey.Decrypt(ptSum, ctSum);\n\tcout << \"ptSum : \" << ptSum <<endl;\n\t\n\tZZX ptMul;\n\tCtxt ctMul = FHE_Mul(Ea, Eb);\n\tsecretKey.Decrypt(ptMul, ctMul);\n\tcout << \"ptMul : \" << ptMul <<endl;\n\n\tZZX ptSub;\n\tsecretKey.Decrypt(ptSub, FHE_Sub(Ea, Eb, publicKey));\n\tcout << \"ptSub : \" << ptSub <<endl;\n\n\tZZX ptDiv;\n\tsecretKey.Decrypt(ptDiv, FHE_Div(Ea, Eb, p, publicKey, secretKey));\n\tcout << \"ptDiv : \" << ptDiv <<endl;\n*/\n\treturn 0;\n}", "meta": {"hexsha": "65e16ade802e4370b7b52d9b9e6e7911a5f35b07", "size": 2185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test1.cpp", "max_stars_repo_name": "edwincai/my-first-lab", "max_stars_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-12T15:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T15:33:57.000Z", "max_issues_repo_path": "test1.cpp", "max_issues_repo_name": "edwincai/my-first-lab", "max_issues_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test1.cpp", "max_forks_repo_name": "edwincai/my-first-lab", "max_forks_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7642276423, "max_line_length": 68, "alphanum_fraction": 0.6356979405, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090321, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5757493593354984}}
{"text": "//\n// Created by bobin on 17-11-9.\n//\n\n#include \"PoseEstimate.h\"\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 <chrono>\n#include \"opencv2/calib3d/calib3d.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nPoseEstimate::PoseEstimate(float _max_trans, float _max_rot) {\n    last_r = cv::Mat::zeros(1, 3, CV_64F);\n    last_t = cv::Mat::zeros(1, 3, CV_64F);\n    max_trans = _max_trans;\n    max_rot = _max_rot;\n}\n\n\nfloat PoseEstimate::pose_distance(const cv::Mat &r, const cv::Mat &t, float &delta_rot, float &delta_trans) {\n    delta_trans = cv::norm(t - last_t);\n    delta_rot = cv::norm(r - last_r);\n\n}\n\nvoid PoseEstimate::object_points(int numGridX, int numGridY,\n                   float GridWidth, float GridHeight,\n                   float GridX, float GridY,\n                   int num_ids) {\n    int cnt = 0;;\n    GridPointXY.resize(num_ids);\n    for (int i = 0; i < numGridY; ++i) {\n        vector<Point3f> rowGridXY;\n        rowGridXY.resize(4);\n        for (int j = 0; j < numGridX; ++j) {\n            rowGridXY[0] = Point3f(j * GridX, i * GridY, 0);\n            rowGridXY[1] = Point3f(j * GridX + GridWidth, i * GridY, 0);\n            rowGridXY[2] = Point3f(j * GridX, i * GridY + GridHeight, 0);\n            rowGridXY[3] = Point3f(j * GridX + GridWidth, i * GridY + GridHeight, 0);\n            GridPointXY[cnt] = rowGridXY;\n            cnt++;\n            if(cnt >= num_ids)\n                break;\n        }\n\n    }\n}\n\n\nvoid PoseEstimate::set_pose(const cv::Mat &r, const cv::Mat &t) {\n    unique_lock<mutex> lock(rotMutex);\n    last_r = r;\n    last_t = t;\n}\n\nvoid PoseEstimate::get_pose(cv::Mat &pose) {\n    unique_lock<mutex> lock(rotMutex);\n    cv::Mat R, t;\n    cv::Rodrigues(last_r, R);\n    t = last_t;\n\n    R.copyTo(pose.rowRange(0, 3).colRange(0, 3));\n    t.copyTo(pose.rowRange(0, 3).col(3));\n}\n\nvoid PoseEstimate::estimate(vector<Point3f> pts_3d,\n                            vector<Point2f> pts_2d,\n                            bool check_last\n                            ) {\n    cv::Mat r, t, R;\n    solvePnP(pts_3d, pts_2d, K, Mat(), r, t, false); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n\n//    unique_lock<mutex> lock(rotMutex);\n    float delta_r, delta_t;\n    if (check_last){\n        pose_distance(r, t, delta_r, delta_t);\n        if ((delta_r > max_rot) || (delta_t > max_trans)) {\n            r = last_r;\n            t = last_t;\n        }\n    }\n    cv::Rodrigues(r, R); // r为旋转向量形式，用Rodrigues公式转换为矩阵\n//    cout << \"R=\" << endl << r << endl;\n//    cout << \"t=\" << endl << t << endl;\n    PoseEstimate::bundleAdjustment(pts_3d, pts_2d, K, R, t);\n    cv::Rodrigues(R, r); // r为旋转向量形式，用Rodrigues公式转换为矩阵\n    set_pose(r, t);\n\n}\n\n\nvoid PoseEstimate::bundleAdjustment(\n        const vector<Point3f> points_3d,\n        const vector<Point2f> points_2d,\n        const Mat &K,\n        Mat &R, Mat &t) {\n    // 初始化g2o\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3> > Block;  // pose维度为 6, landmark 维度为 3\n    Block::LinearSolverType *linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 线性方程求解器\n    Block *solver_ptr = new Block(linearSolver);     // 矩阵块求解器\n    g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(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);\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        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}", "meta": {"hexsha": "bdfbddd3e226c39778893c57e256ad6a746ef8bc", "size": 5733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose/PoseEstimate.cpp", "max_stars_repo_name": "x007dwd/apriltag", "max_stars_repo_head_hexsha": "acf21e16e2dc9a77382366abc7c6fb2154d9593b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pose/PoseEstimate.cpp", "max_issues_repo_name": "x007dwd/apriltag", "max_issues_repo_head_hexsha": "acf21e16e2dc9a77382366abc7c6fb2154d9593b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose/PoseEstimate.cpp", "max_forks_repo_name": "x007dwd/apriltag", "max_forks_repo_head_hexsha": "acf21e16e2dc9a77382366abc7c6fb2154d9593b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.125, "max_line_length": 109, "alphanum_fraction": 0.6045700331, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5757486021605261}}
{"text": "#include <iostream>\r\n#include <iomanip>\r\n#include <fstream>\r\n#include <string>\r\n#include <ctime>\r\n#include <opencv2/opencv.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <imgproc/derivative_gradient.hpp>\r\n#define DISABLE_DC_ZERO_FIX\r\n#include <imgproc/quadratureG2.hpp>\r\n#include <imgproc/quadratureS.hpp>\r\n#include <imgproc/laplace.hpp>\r\n#include <dlib/optimization.h>\r\n\r\nusing namespace std;\r\nusing namespace lsfm;\r\nusing namespace cv;\r\n\r\nvoid showGradient(const std::string &name,const cv::Mat &mag, double mul = 1) {\r\n    double vmin,vmax;\r\n    cv::minMaxIdx(mag,&vmin,&vmax);\r\n    mag -= vmin;\r\n    mag /= vmax - vmin;\r\n    mag *= mul;\r\n    imshow(\"gradient \" + name,mag);\r\n}\r\n\r\ndouble d_lower = 0.1, d_upper = 10, start = 1;\r\ncv::Mat white(18, 18, CV_64F, 1);\r\n\r\ntemplate <\r\n    class GRAD,\r\n    class search_strategy_type = dlib::bfgs_search_strategy,\r\n    class stop_strategy_type = dlib::objective_delta_stop_strategy\r\n>\r\ndouble optimizeGradKernel(GRAD& grad,\r\n    double derivative_prec = 1e-7, search_strategy_type search = dlib::bfgs_search_strategy(),\r\n    stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n\r\n    typedef dlib::matrix<double, 0, 1> column_vector;\r\n        \r\n    auto eval = [&](const column_vector& v) -> double {\r\n        grad.kernelSpacing(v(0));\r\n        return std::abs(cv::sum(grad.kernel())[0]);\r\n    };\r\n\r\n    grad.kernelSpacing(start);\r\n    column_vector starting_point(1), lower(1), upper(1);\r\n    starting_point = start;\r\n    lower = d_lower;\r\n    upper = d_upper;\r\n    return dlib::find_min_box_constrained(search, stop,\r\n        eval, dlib::derivative(eval, derivative_prec), starting_point, lower, upper);\r\n\r\n}\r\n\r\ntemplate <\r\n    class GRAD,\r\n    class search_strategy_type = dlib::bfgs_search_strategy,\r\n    class stop_strategy_type = dlib::objective_delta_stop_strategy\r\n>\r\ndouble optimizeGradKernel2( GRAD& grad,\r\n    double derivative_prec = 1e-7, search_strategy_type search = dlib::bfgs_search_strategy(),\r\n    stop_strategy_type stop = dlib::objective_delta_stop_strategy(1e-7)) {\r\n\r\n    typedef dlib::matrix<double, 0, 1> column_vector;\r\n\r\n    auto eval = [&](const column_vector& v) -> double {\r\n        grad.kernelSpacing(v(0));\r\n        grad.process(white);\r\n        cv::Mat mag = grad.even();\r\n        return std::abs(mag.at<double>(0, 0));\r\n    };\r\n\r\n    grad.kernelSpacing(start);\r\n    column_vector starting_point(1), lower(1), upper(1);\r\n    starting_point = start;\r\n    lower = d_lower;\r\n    upper = d_upper;\r\n    return dlib::find_min_box_constrained(search, stop,\r\n        eval, dlib::derivative(eval, derivative_prec), starting_point, lower, upper);\r\n\r\n}\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n    const char* filename = argc >= 2 ? argv[1] : \"../../images/circle2.png\";\r\n    //const char* filename = argc >= 2 ? argv[1] : \"../../images/bike.png\";\r\n    //const char* filename = argc >= 2 ? argv[1] : \"../../images/office1_low.JPG\";\r\n\r\n    cv::Mat src = cv::imread(filename, IMREAD_GRAYSCALE);\r\n    if (src.empty())\r\n    {\r\n        cout << \"Can not open \" << filename << endl;\r\n        return -1;\r\n    }\r\n\r\n    GaussianBlur(src, src, cv::Size(3, 3),0.6);\r\n    typedef double FT;\r\n\r\n    QuadratureG2<uchar, FT> quad3(3, 1.240080);\r\n\tQuadratureG2<uchar, FT> quad5(5, 1.008000);\r\n    QuadratureG2<uchar, FT> quad7(7, 0.873226);\r\n    QuadratureG2<uchar, FT> quad9(9, 0.781854);\r\n\r\n    quad3.process(src);\r\n    showGradient(\"Quad3 -\", Mat(abs(quad3.even())));\r\n\r\n    quad5.process(src);\r\n    showGradient(\"Quad5 -\", Mat(abs(quad5.even())));\r\n\r\n    quad7.process(src);\r\n    showGradient(\"Quad7 -\", Mat(abs(quad7.even())));\r\n\r\n    quad9.process(src);\r\n    showGradient(\"Quad9 -\", Mat(abs(quad9.even())));\r\n\r\n    cv::waitKey();\r\n\r\n    QuadratureS<uchar, FT, FT> quadS3(1, 2, 3, 1);\r\n    QuadratureS<uchar, FT, FT> quadS5(1, 2, 5, 1);\r\n    QuadratureS<uchar, FT, FT> quadS7(1, 2, 7, 1);\r\n    QuadratureS<uchar, FT, FT> quadS9(1, 2, 9, 1);\r\n    \r\n    LoG<uchar, FT> log3(3, 1);\r\n    LoG<uchar, FT> log5(5, 1);\r\n    LoG<uchar, FT> log7(7, 1);\r\n    LoG<uchar, FT> log9(9, 1);\r\n    LoG<uchar, FT> log11(11, 1);\r\n    LoG<uchar, FT> log15(15, 1);\r\n    LoG<uchar, FT> log25(25, 1);\r\n    LoG<uchar, FT> log75(75, 1);\r\n    LoG<uchar, FT> log125(125, 1);\r\n    \r\n    double e;\r\n    e = optimizeGradKernel(log3);\r\n    std::cout << \"LoG3 - error: \" << e << \", spacing: \" << log3.kernelSpacing() << std::endl;\r\n    //std::cout << log3.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel(log5);\r\n    std::cout << \"LoG5 - error: \" << e << \", spacing: \" << log5.kernelSpacing() << std::endl;\r\n    //std::cout << log5.kernel() << std::endl;\r\n    \r\n    e = optimizeGradKernel(log7);\r\n    std::cout << \"LoG7 - error: \" << e << \", spacing: \" << log7.kernelSpacing() << std::endl;\r\n    //std::cout << log7.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel(log9);\r\n    std::cout << \"LoG9 - error: \" << e << \", spacing: \" << log9.kernelSpacing() << std::endl;\r\n    //std::cout << log9.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log3);\r\n    std::cout << \"LoG3 - error2: \" << e << \", spacing: \" << log3.kernelSpacing() << std::endl;\r\n    //std::cout << log3.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log5);\r\n    std::cout << \"LoG5 - error2: \" << e << \", spacing: \" << log5.kernelSpacing() << std::endl;\r\n    //std::cout << log5.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log7);\r\n    std::cout << \"LoG7 - error2: \" << e << \", spacing: \" << log7.kernelSpacing() << std::endl;\r\n    //std::cout << log7.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log9);\r\n    std::cout << \"LoG9 - error2: \" << e << \", spacing: \" << log9.kernelSpacing() << std::endl;\r\n    //std::cout << log9.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log11);\r\n    std::cout << \"LoG11 - error2: \" << e << \", spacing: \" << log11.kernelSpacing() << std::endl;\r\n    //std::cout << log11.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log15);\r\n    std::cout << \"LoG15 - error2: \" << e << \", spacing: \" << log15.kernelSpacing() << std::endl;\r\n    //std::cout << log15.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log25);\r\n    std::cout << \"LoG25 - error2: \" << e << \", spacing: \" << log25.kernelSpacing() << std::endl;\r\n    //std::cout << log25.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log75);\r\n    std::cout << \"LoG75 - error2: \" << e << \", spacing: \" << log75.kernelSpacing() << std::endl;\r\n    //std::cout << log75.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(log125);\r\n    std::cout << \"LoG125 - error2: \" << e << \", spacing: \" << log125.kernelSpacing() << std::endl;\r\n    //std::cout << log25.kernel() << std::endl;\r\n    \r\n    \r\n    /*log3.process(src);\r\n    showGradient(\"LoG3 -\", log3.laplace());\r\n\r\n    log5.process(src);\r\n    showGradient(\"LoG5 -\", log5.laplace());\r\n\r\n    log7.process(src);\r\n    showGradient(\"LoG7 -\", log7.laplace());\r\n\r\n    log9.process(src);\r\n    showGradient(\"LoG9 -\", log9.laplace());\r\n\r\n    cv::waitKey();*/\r\n\r\n    e = optimizeGradKernel2(quad3);\r\n    std::cout << \"Quad3 - error: \" << e << \", spacing: \" << quad3.kernelSpacing() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quad5);\r\n    std::cout << \"Quad5 - error: \" << e << \", spacing: \" << quad5.kernelSpacing() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quad7);\r\n    std::cout << \"Quad7 - error: \" << e << \", spacing: \" << quad7.kernelSpacing() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quad9);\r\n    std::cout << \"Quad9 - error: \" << e << \", spacing: \" << quad9.kernelSpacing() << std::endl;\r\n\r\n\r\n    quad3.process(src);\r\n    showGradient(\"Quad3 -\", Mat(abs(quad3.even())));\r\n\r\n    quad5.process(src);\r\n    showGradient(\"Quad5 -\", Mat(abs(quad5.even())));\r\n\r\n    quad7.process(src);\r\n    showGradient(\"Quad7 -\", Mat(abs(quad7.even())));\r\n\r\n    quad9.process(src);\r\n    showGradient(\"Quad9 -\", Mat(abs(quad9.even())));\r\n\r\n    cv::waitKey();\r\n\r\n    e = optimizeGradKernel(quadS3);\r\n    std::cout << \"QuadS3 - error: \" << e << \", spacing: \" << quadS3.kernelSpacing() << \", scale: \" << quadS3.scale() << \", muls: \" << quadS3.muls() << std::endl;\r\n    //std::cout << quadS3.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel(quadS5);\r\n    std::cout << \"QuadS5 - error: \" << e << \", spacing: \" << quadS5.kernelSpacing() << \", scale: \" << quadS5.scale() << \", muls: \" << quadS5.muls() << std::endl;\r\n    //std::cout << quadS5.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel(quadS7);\r\n    std::cout << \"QuadS7 - error: \" << e << \", spacing: \" << quadS7.kernelSpacing() << \", scale: \" << quadS7.scale() << \", muls: \" << quadS7.muls() << std::endl;\r\n    //std::cout << quadS7.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel(quadS9);\r\n    std::cout << \"QuadS9 - error: \" << e << \", spacing: \" << quadS9.kernelSpacing() << \", scale: \" << quadS9.scale() << \", muls: \" << quadS9.muls() << std::endl;\r\n    //std::cout << quadS9.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quadS3);\r\n    std::cout << \"QuadS3 - error2: \" << e << \", spacing: \" << quadS3.kernelSpacing() << \", scale: \" << quadS3.scale() << \", muls: \" << quadS3.muls() << std::endl;\r\n    //std::cout << quadS3.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quadS5);\r\n    std::cout << \"QuadS5 - error2: \" << e << \", spacing: \" << quadS5.kernelSpacing() << \", scale: \" << quadS5.scale() << \", muls: \" << quadS5.muls() << std::endl;\r\n    //std::cout << quadS5.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quadS7);\r\n    std::cout << \"QuadS7 - error2: \" << e << \", spacing: \" << quadS7.kernelSpacing() << \", scale: \" << quadS7.scale() << \", muls: \" << quadS7.muls() << std::endl;\r\n    //std::cout << quadS7.kernel() << std::endl;\r\n\r\n    e = optimizeGradKernel2(quadS9);\r\n    std::cout << \"QuadS9 - error2: \" << e << \", spacing: \" << quadS9.kernelSpacing() << \", scale: \" << quadS9.scale() << \", muls: \" << quadS9.muls() << std::endl;\r\n    //std::cout << quadS9.kernel() << std::endl;\r\n\r\n\r\n    /*quadS3.process(src);\r\n    showGradient(\"QuadS3 -\", quadS3.even());\r\n\r\n    quadS5.process(src);\r\n    showGradient(\"QuadS5 -\", quadS5.even());\r\n\r\n    quadS7.process(src);\r\n    showGradient(\"QuadS7 -\", quadS7.even());\r\n\r\n    quadS9.process(src);\r\n    showGradient(\"QuadS9 -\", quadS9.even());\r\n\r\n    cv::waitKey();*/\r\n\r\n    \r\n\r\n    /*QuadratureS<uchar, FT, FT> quadS5(1.0, 2.0, 5, 1);\r\n    QuadratureS<uchar, FT, FT> quadS7(1.0, 2.0, 7, 1);\r\n    QuadratureS<uchar, FT, FT> quadS9(1.0, 2.0, 9, 0.1);\r\n\r\n    quadS5.process(src);\r\n    quadS7.process(src);\r\n    quadS9.process(src);\r\n\r\n    //showGradient(\"QuadS5 -\", quadS5.laplace(),5);\r\n    //showGradient(\"QuadS7 -\", quadS7.laplace(),5);\r\n    showGradient(\"QuadS9 -\", quadS9.laplace(),5);\r\n\r\n    //showGradient(\"QuadS5 m-\", quadS5.magnitude());\r\n    //showGradient(\"QuadS7 m-\", quadS7.magnitude());\r\n    showGradient(\"QuadS9 m-\", quadS9.magnitude());\r\n\r\n    //showGradient(\"QuadS5 lm-\", quadS5.localMagnitude());\r\n    //showGradient(\"QuadS7 lm-\", quadS7.localMagnitude());\r\n    showGradient(\"QuadS9 lm-\", quadS9.localMagnitude());\r\n\r\n    //showGradient(\"QuadS5 e-\", quadS5.even());\r\n    //showGradient(\"QuadS7 e-\", quadS7.even());\r\n    showGradient(\"QuadS9 e-\", quadS9.even());\r\n    cv::waitKey();*/\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "1b93ad0ffa272354e152001851dd668b7f8161a9", "size": 11146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/old/even_parameter_test.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/even_parameter_test.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/even_parameter_test.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3061889251, "max_line_length": 163, "alphanum_fraction": 0.577875471, "num_tokens": 3448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5757485740275213}}
{"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 Density {\npublic:\n\tvirtual double densityr(double R) = 0;  \n};\n\nclass Profile : public Density {\npublic:\n\tvirtual double densityr(double r) = 0;\n\tvirtual double densityR(double R) = 0;  \n\tvirtual double I(double r, double I0=1.0) = 0;  \n\tvirtual double dphidr(double r) = 0;\n\tvirtual double potentialr(double r) = 0;\n\tdouble dphidx2(double x, double y) {\n\t\tdouble r = sqrt(x*x+y*y);\n\t\treturn dphidr(r) * x / r;\n\t}\n\tdouble dphidy2(double x, double y) {\n\t\tdouble r = sqrt(x*x+y*y);\n\t\treturn dphidr(r) * y / r;\n\t}\n\tstd::tuple<double,double> dphidxy(double x, double y) {\n\t\tdouble r = sqrt(x*x+y*y);\n\t\tdouble F = dphidr(r);\n\t\treturn std::make_tuple(F*x/r, F*y/r);\n\t};\n\t\n\tdouble 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 ProfileModel {\npublic:\n\tvirtual double densityr(double r) = 0;\n\tvirtual double densityR(double r) = 0;\n\tvirtual double dphidr(double r) = 0;\n\tvirtual double potentialr(double r) = 0;\n\tboost::python::tuple get_apo_peri(double E, double L, double rmin, double rcirc, double rmax);\n\tboost::python::tuple Lmax_and_rcirc_at_E_(double E);\n\tvoid Lmax_and_rcirc_at_E(double E, double& Lmax, double& rcirc);\n\tdouble Lmax_at_E(double E);\n\tdouble rcirc_at_E(double E);\n\tdouble rmax_at_E(double E, double rcirc);\n};\n\nclass ProfileModel1C : public ProfileModel {\npublic:\n\tProfileModel1C(Profile* p) : p(p) {} \n\tvirtual double densityr(double r) { return p->densityr(r); } \n\tvirtual double densityR(double r)  { return p->densityR(r); }\n\tvirtual double dphidr(double r) { return p->dphidr(r); }\n\tvirtual double potentialr(double r) { return p->potentialr(r); }\n\tProfile* p;\n};\n\nclass ProfileModel2C : public ProfileModel {\npublic:\n\tProfileModel2C(Profile* p1, Profile* p2) : p1(p1), p2(p2) {} \n\tvirtual double densityr(double r) { return p1->densityr(r) + p2->densityr(r); } \n\tvirtual double densityR(double r)  { return p1->densityR(r); }\n\tvirtual double dphidr(double r) { return p1->dphidr(r) + p2->dphidr(r); }\n\tvirtual double potentialr(double r) { return p1->potentialr(r) + p2->potentialr(r); }\n\tProfile *p1, *p2;\n};\n\n\n\nclass Plummer : public Profile {\npublic:\n\tPlummer(double mass, double scale, double G) : mass(mass), scale(scale), G(G) {\n\t}\n\tdouble densityr(double r) {\n\t\treturn 3 * mass * scale * scale / (4*M_PI) / pow((r*r + scale*scale), (5./2));\n\t}\n\tdouble densityR(double R) {\n\t\tdouble a = (scale*scale+R*R);\n\t\treturn mass * scale*scale / (M_PI * a*a);\n\t}  \n\tdouble I(double R, double I0=1.0) {\n\t\tdouble a = (scale*scale+R*R);\n\t\treturn I0 * scale*scale / (M_PI * a*a);\n\t}\n\tdouble dphidr(double r) {\n\t\treturn G * mass * r / pow((r*r + scale*scale), (3./2));\n\t}\n\tdouble potentialr(double r) {\n\t\treturn - G * mass / sqrt(r*r + scale*scale);\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\treturn r * 2;\n\t}*/\n\tdouble mass, scale, G;\n};\n/* \nclass ProjectedExponential(Potential):\n\tdef __init__(self, M, scale, G=G):\n\t\tself.M = M\n\t\tself.scale = scale\n\t\tself.rho0 = 1.\n\t\tprint self.scale\n\t\tMcurrent = self.enclosed_mass(inf)\n\t\tself.rho0 = M/Mcurrent\n\t\tself._fast = mab.gdfast.ProjectedExponential(M, scale, G)\n\n\t\t#2 \\[Pi] Rs (Rs - E^(-(r/Rs)) (r + Rs))\n\n\tdef densityR(self, r):\n\t\treturn exp(-r/self.scale) * self.rho0\n\n\tdef densityr(self, r):\n\t\t# kn is the (modified) bessel of second kind (integer order = 0)\n\t\treturn self.rho0 * scipy.special.kn(0., r) / (self.scale * pi)\n\n\tdef potentialr(self, r):\n\t\treturn 0\n\n\tdef dphidr(self, r):\n\t\treturn 0\n*/\nclass ProjectedExponential : public Profile {\npublic:\n\tProjectedExponential(double mass, double scale, double G) : mass(mass), scale(scale), G(G) {\n\t\trho0 = 1;\n\t\tdouble current_mass = this->total_mass();\n\t\trho0 *= mass/current_mass;\n\t}\n\tdouble densityr(double r) {\n\t\treturn rho0 * boost::math::cyl_bessel_k(0, r/scale)  / (scale * M_PI);\n\t}\n\tdouble densityR(double R) {\n\t\treturn rho0 * exp(-R/scale);\n\t}  \n\tdouble I(double R, double I0=1.0) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double r) {\n\t\treturn 0;\n\t}\n\tdouble potentialr(double r) {\n\t\treturn 0;\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\treturn r * 2;\n\t}*/\n\tdouble mass, scale, G, rho0;\n};\n\nclass TestCase : public Profile {\npublic:\n\tTestCase(double mass, double scale, double G) : mass(mass), scale(scale), G(G) {\n\t}\n\tdouble densityr(double r) {\n\t\t//return 3 * mass * scale * scale / (4*M_PI) / pow((r*r + scale*scale), (5./2));\n\t\treturn 3 * pow(1+pow(r/20,2), -5./2);\n\t}\n\tdouble densityR(double R) {\n\t\tdouble a = (scale*scale+R*R);\n\t\treturn mass * scale*scale / (M_PI * a*a);\n\t}  \n\tdouble I(double R, double I0=1.0) {\n\t\tdouble a = (scale*scale+R*R);\n\t\treturn I0 * scale*scale / (M_PI * a*a);\n\t}\n\tdouble dphidr(double r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\treturn 1/(4*M_PI*2)*(8000*pow(400+r*r, -3./2)*2*r);\n\t}\n\tdouble potentialr(double r) {\n\t\treturn -1/(4*M_PI)*(8000/sqrt(400+r*r)-178.88);\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\treturn r * 2;\n\t}*/\n\tdouble mass, scale, G;\n};\n\n\nclass Isochrone : public Profile {\npublic:\n\tIsochrone(double mass, double scale, double G) : mass(mass), scale(scale), G(G) {\n\t}\n\tdouble densityr(double) {\n\t\treturn 0;\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t} \n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double) {\n\t\treturn 0;\n\t}\n\tdouble potentialr(double) {\n\t\treturn 0;\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\treturn r * 2;\n\t}*/\n\tdouble mass, scale, G;\n};\n\n\nclass LogarithmicProfile : public Profile {\npublic:\n\tLogarithmicProfile(double vcirc, double G) : vcirc(vcirc), G(G) {\n\t}\n\tdouble densityr(double) {\n\t\treturn 0;\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t} \n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double) {\n\t\treturn 0;\n\t}\n\tdouble potentialr(double) {\n\t\treturn 0;\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\treturn r * 2;\n\t}*/\n\tdouble vcirc, G;\n};\n\n\n\nclass NullProfile : public Profile {\npublic:\n\tNullProfile() {\n\t}\n\tdouble densityr(double) {\n\t\treturn 0;\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t}  \n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double) {\n\t\treturn 0;\n\t}\n\tdouble potentialr(double) {\n\t\treturn 0;\n\t}\n\t/*double_vector dphidr2(double_vector r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\treturn r*0;\n\t}*/\n};\n\nclass Hernquist : public Profile {\npublic:\n\tHernquist(double mass, double scale, double G) : mass(mass), scale(scale), G(G) {\n\t\trho0 = mass / (2*M_PI*scale*scale*scale);\n\t}\n\tdouble potentialr(double r) {\n\t\treturn - 4 * M_PI * G * rho0 * scale*scale /(2*(1+r/scale));\n\t}\n\tdouble densityr(double r) {\n\t\tdouble m = r/scale;\n\t\tdouble a = (1+m);\n\t\treturn rho0 / (m * a*a*a);\n\t}\n\tdouble _ddensityR(double r, double R) {\n\t\treturn 2 * r * densityr(r) / sqrt(r*r-R*R);\n\t}\n\tdouble densityR(double R) {\n\t\t/*return -pow(scale,4) * rho0 * (3 * scale * (scale-R)*(scale+R)+sqrt(R*R-scale*scale)*(2*scale*scale+R*R)*acos(scale/R)) / pow(scale*scale-R*R,3);-*/\n\t\t//std::tr1::function<double(double)> f(bind(&Hernquist::_ddensityR, this, _1, R));\n\t\tauto ddensity = [&R,this](double r){ return 2 * r * this->densityr(r) / sqrt(r*r-R*R); };\n\t\tIntegratorGSL<> integratorGSL(ddensity); // the integrator\n\t\tdouble integral = integratorGSL.integrate_to_inf(R);\n\t\treturn integral;\n\t}\n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double r) {\n\t\t//return G * mass * r / pow((r*r + scale*scale), (3./2));\n\t\tdouble a = (1+r/scale);\n\t\treturn 4 * M_PI * G * rho0 * scale / (2*a*a);\n\t}\n\tdouble mass, rho0, scale, G;\n};\n\nclass NFW : public Profile {\npublic:\n\tNFW(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\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 densityR(double) {\n\t\treturn 0;\n\t}\n\tdouble I(double, double) {\n\t\treturn 0;\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\nclass Jaffe : public Profile {\npublic:\n\tJaffe(double rho0, double rs, double G) : rho0(rho0), rs(rs), G(G) {\n\t}\n\tdouble potentialr(double r) {\n\t\treturn - 4 * M_PI * G * rho0 * rs*rs * log(1+rs/r);\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (pow(x, 2) * pow(1+x, 2));\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t}\n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double r) {\n\t\t/*double 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\treturn - 4 * M_PI * G * rho0 * rs*rs * 1./(1.+rs/r) * -rs/(r*r);\n\t}\n\tdouble rho0, rs, G;\n};\n\n\nclass NFWCut : public Density {\npublic:\n\tNFWCut(double rho0, double rs, double rte) : rho0(rho0), rs(rs), rte(rte) {\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (x * pow(1+x,2)) / (1+pow(r/rte, 3));\n\t}\n\tdouble rho0, rs, rte;\n};\n\nclass TwoSlopeDensity : public Density {\npublic:\n\tTwoSlopeDensity(double rho0, double alpha, double beta, double rs, double gamma=1.) : rho0(rho0), alpha(alpha), beta(beta), rs(rs), gamma(gamma) {\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (pow(x, -alpha) * pow(1+pow(x, gamma), (-beta+alpha)/gamma));\n\t}\n\tdouble rho0, alpha, beta, rs, gamma;\n};\n\nclass TwoSlopeDensityCut : public Density {\npublic:\n\tTwoSlopeDensityCut(double rho0, double alpha, double beta, double rs, double gamma, double rte) : rho0(rho0), alpha(alpha), beta(beta), rs(rs), gamma(gamma), rte(rte) {\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho0 / (pow(x, -alpha) * pow(1+pow(x, gamma), (-beta+alpha)/gamma)) / (1+pow(r/rte, 3));\n\t}\n\tdouble rho0, alpha, beta, rs, gamma, rte;\n};\n\n\nclass BrokenPowerLawDensitySoft3 : public Density {\npublic:\n\tBrokenPowerLawDensitySoft3(double rho0, double s1, double s2, double s3, double gamma1, double gamma2, double rs1, double rs2) : rho0(rho0), s1(s1), s2(s2), s3(s3), gamma1(gamma1), gamma2(gamma2), rs1(rs1), rs2(rs2) {\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x1 = r/rs1;\n\t\tdouble x2 = r/rs2;\n\t\treturn rho0 * pow(x1, s1) * pow(1+pow(x1, gamma1), (s2-s1)/gamma1) * pow(1+pow(x2, gamma2), (s3-s2)/gamma2);\n\t}\n\tdouble rho0, s1, s2, s3, gamma1, gamma2, rs1, rs2;\n};\n\n\nclass Einasto : public Profile {\npublic:\n\tEinasto(double rho_2, double rs_2, double alpha, double G) : rho_2(rho_2), rs_2(rs_2), alpha(alpha), G(G) {\n\t}\n\tdouble potentialr(double) {\n\t\treturn 0;\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs_2;\n\t\treturn rho_2 * exp((-2/alpha)*(pow(x, alpha)-1));\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t}\n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double) {\n\t\treturn 0;\n\t}\n\tdouble rho_2, rs_2, alpha, G;\n\t/*double M(double r) {\n\t\tdouble x = r/rs_2;\n\t\tdouble a = alpha;\n\t\tdouble Rg;\n\t\tgsl_sf_result R1, R2;\n\t\tgsl_sf_gamma_inc_P_e(3./a, (2*pow(x,a))/a, &Rg)\n\t\t//gsl_sf_gamma_inc_P_e(3./a, (2*pow(x,a))/a, &R1)\n\t\tdouble R = Rg.val * gsl_sf_gamma(3./a);\n\t\treturn 0;\n\t\t//return pow(2, (2.-3./a)) * exp(2./a) * M_PI * pow(pow(1/self.r_2,a)/a, -3./a) * rho_2 * R / a;\n\t}*/\n};\n\n\n\nclass Burkert : public Profile {\npublic:\n\tBurkert(double rho, double rs, double G) : rho(rho), rs(rs), G(G) {\n\t}\n\tdouble potentialr(double) {\n\t\treturn 0;\n\t}\n\tdouble densityr(double r) {\n\t\tdouble x = r/rs;\n\t\treturn rho / ((1+x) * (1+x*x));\n\t}\n\tdouble densityR(double) {\n\t\treturn 0;\n\t}\n\tdouble I(double, double) {\n\t\treturn 0;\n\t}\n\tdouble dphidr(double) {\n\t\treturn 0;\n\t}\n\tdouble rho, rs, G;\n};\n\n}\n", "meta": {"hexsha": "a1ae4e6a6dcd21d59d999b0af51b26e01107bf8f", "size": 12570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/profile.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/profile.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/profile.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": 25.7581967213, "max_line_length": 218, "alphanum_fraction": 0.6329355609, "num_tokens": 4285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438126, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5757485639586267}}
{"text": "#ifndef EXPSUM_HANKEL_MATRIX_VECTOR_PRODUCT_HPP\n#define EXPSUM_HANKEL_MATRIX_VECTOR_PRODUCT_HPP\n\n#include <armadillo>\n\n#include \"fftw3/shared_plan.hpp\"\n\nnamespace expsum\n{\n/*!\n * Fast matrix-vector product for generalized Hankel matrix.\n *\n * A general Hankel matrix is a matrix of special form give as\n *\n * \\f[\n *   A = \\left[ \\begin{array}{cccccc}\n *     h_0 & h_1 & h_2 & h_3 & \\cdots & h_{n-1} \\\\\n *     h_1 & h_2 & h_3 & h_4 & \\cdots & h_{n}   \\\\\n *     h_2 & h_3 & h_4 & h_5 & \\cdots & h_{n+1} \\\\\n *     h_3 & h_4 & h_5 & h_6 & \\cdots & h_{n+2} \\\\\n *     \\vdots & \\vdots & \\vdots &\\vdots &\\ddots & \\vdots \\\\\n *     h_{m-1} & h_{m} & h_{m+1} & h_{m+2} & \\cdots & h_{m+n-1} \\\\\n *   \\end{array} \\right],\n * \\f]\n *\n * where \\f$ m \\f$ and \\f$ n \\f$ are the number of rows and colums of matrix.\n * From the definition above, a general Hankel matrix \\f$ A \\f$ can fully be\n * determined by a vector \\f$ h = [h_0,h_1,...,h_{n+m-1}]^{T}\\f$ composed of the\n * elements of first column and last row where \\f$ A_{ij} = h_{i+j}.\\f$\n *\n * This class compute the matrix-vector product,\n *\n * \\f[\n *   \\bm{y} = A \\bm{x},\n * \\f]\n *\n * where \\f$ \\bm{x} = [x_0,x_1,\\dots,x_{n-1}]^{T} \\f$ and \\f$ \\bm{y} =\n * [y_0,y_1,\\dots,y_{m-1}]^{T}. \\f$ This product can be efficiently computed by\n * the fast Fourier transfor (FFT), as follows.\n *\n * Let define a new vector \\f$ \\hat{\\bm{c}} \\f$ of size \\f$ n + m - 1 \\f$ as\n *\n * \\f[\n *   \\hat{\\bm{c}}=[h_{n-1},\\dots,h_{n+m-2},h_{0},\\dots,h_{n-2}]^{T},\n * \\f]\n *\n * and corresponding circulant matrix\n *\n * \\f[\n *   C = \\left[ \\begin{array}{}\n *         c_0     & c_{n+m-2} & \\cdots    & c_{2}  & c_{1} \\\\\n *         c_1     & c_{0}     & c_{n+m-2} &        & c_{2} \\\\\n *         \\vdots  & c_{1}     & c_{0}     & \\ddots & \\vdots    \\\\\n *         c_{n+m-3} &         & \\ddots    & \\ddots & c_{n+m-2} \\\\\n *         c_{n+m-2} & c_{n+m-3} & \\cdots  & c_{1}  & c_{0}\n *       \\end{array} \\right].\n * \\f]\n *\n * For a given vector \\f$ \\bm{x} \\f$ of length \\f$ n, \\f$ we define a auxilialy\n * vector of length \\f$ n + m - 1 \\f$ as\n *\n * \\f[\n *   \\hat{\\bm{x}}=[x_{n-1},x_{n-2},\\dots,x_{0},0,\\dots,0]^{T}.\n * \\f]\n *\n * Then, the result vector \\f$ \\bm{y} \\f$ can be obtained as the first\n * \\f$ m \\f$-elemets of the vector \\f$ \\hat{\\bm{y}}\\equiv C\\hat{\\bm{x}}. \\f$\n * The produt \\f$ C\\hat{\\bm{x}} \\f$ can be evaluated as,\n *\n * \\f[\n *   \\hat{\\bm{y}} = \\text{IFFT}(\\text{FFT}(\\hat{\\bm{c}}) \\odot\n *                              \\text{FFT}(\\hat{\\bm{x}})).\n * \\f]\n *\n * Here, \\$f \\text{FFT}(\\bm{v}) \\f$ and \\$f \\text{IFFT}(\\bm{v}) \\f$ denote\n * one-dimensional FFT and inverse FFT of vector \\bm{v}, and \\f$ \\odot \\f$\n * denotes a element-wise multiplication of two vectors.\n *\n * The computational complexity of this algorithm is \\f$\n * \\mathcal{O}((m+n-1)\\log(m+n-1)) \\f$, rather than \\f$ \\mathcal{O}(mn) \\f$\n * for ordinary dense matrix-vector operation in BLAS2.\n *\n * For the computational efficiency, the FFT of the vector \\f$ \\hat{\\bm{c}} \\f$\n * is pre-computed and stored internally.\n *\n */\n\ntemplate <typename T>\nclass hankel_gemv\n{\npublic:\n    using size_type   = arma::uword;\n    using value_type  = T;\n    using vector_type = arma::Col<value_type>;\n\n    using real_type           = typename vector_type::pod_type;\n    using complex_type        = std::complex<real_type>;\n    using complex_vector_type = arma::Col<complex_type>;\n\nprivate:\n    using fft  = fftw3::fft<real_type>;\n    using ifft = fftw3::ifft<real_type>;\n\n    typename fft::plan_pointer fft_plan_;\n    typename ifft::plan_pointer ifft_plan_;\n\n    size_type nrows_;\n    size_type ncols_;\n\n    mutable vector_type work_;\n    complex_vector_type caux_;\n    mutable complex_vector_type xaux_;\n\npublic:\n    /// Default constructor\n    hankel_gemv() = default;\n\n    /// Create an Hankel matrix operator with memory preallocation.\n    hankel_gemv(size_type nrows, size_type ncols, size_type fft_size = 0)\n        : fft_plan_(),\n          ifft_plan_(),\n          nrows_(nrows),\n          ncols_(ncols),\n          work_(std::max(fft_size, nrows + ncols - 1)),\n          caux_(arma::is_complex<value_type>::value ? work_.size()\n                                                    : work_.size() / 2 + 1),\n          xaux_(caux_.size())\n    {\n        set_fft_plans();\n    }\n\n    /// Copy constructor (default)\n    hankel_gemv(const hankel_gemv&) = default;\n\n    /// Move constructor (default)\n    hankel_gemv(hankel_gemv&&) = default;\n\n    /// Destructor (default)\n    ~hankel_gemv() = default;\n\n    /// Copy assignment operator\n    hankel_gemv& operator=(const hankel_gemv&) = default;\n\n    /// Move assignment operator\n    hankel_gemv& operator=(hankel_gemv&&) = default;\n\n    /// @return the number of rows of the Hankel matrix\n    size_type nrows() const\n    {\n        return nrows_;\n    }\n    /// @return the number of columns of the Hankel matrix\n    size_type ncols() const\n    {\n        return ncols_;\n    }\n    /// @return number of coefficients that defines this Hankel matrix\n    size_type size() const\n    {\n        return nrows() + ncols() - 1;\n    }\n\n    /// Reallocate internal memory space\n    void resize(size_type nrows, size_type ncols, size_type fft_size = 0)\n    {\n        fft_size = std::max(fft_size, nrows + ncols - 1);\n\n        nrows_ = nrows;\n        ncols_ = ncols;\n        work_.set_size(fft_size);\n        caux_.set_size(arma::is_complex<value_type>::value\n                           ? work_.size()\n                           : work_.size() / 2 + 1);\n        xaux_.set_size(caux_.size());\n\n        set_fft_plans();\n    }\n    ///\n    /// Set coefficients that defines the Hankel matrix.\n    ///\n    template <typename T1>\n    typename std::enable_if<arma::is_arma_type<T1>::value>::type\n    set_coeffs(const T1& coeffs)\n    {\n        assert(coeffs.is_vec() && coeffs.n_elem == size());\n        //\n        // Set first column of circulant matrix C. Then compute the discrete\n        // Fourier transform this vector and store the result into \\c caux.\n        //\n        const auto nhead    = nrows();\n        const auto ntail    = ncols() - 1;\n        const auto npadding = work_.size() - nhead - ntail;\n\n        work_.head(nhead) = coeffs.tail(nhead);\n        if (npadding > size_type())\n        {\n            work_.subvec(nhead, nhead + npadding - 1).zeros();\n        }\n        work_.tail(ntail) = coeffs.head(ntail);\n\n        // caux_ <-- FFT[work_]\n        fft::run(fft_plan_, work_.memptr(), caux_.memptr());\n        caux_ *= real_type(1) / work_.size();\n    }\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.is_vec() && x.n_elem == ncols());\n        assert(y.is_vec() && y.n_elem == nrows());\n        //\n        // Form new vector x' = [x(n-1),x(n-2),...,x(0),0....0] of length\n        // n + m - 1, and compute FFT.\n        //\n        work_.head(ncols()) = arma::flipud(x);\n        work_.tail(work_.size() - ncols()).zeros();\n        // xaux_ <-- FFT[work_]\n        fft::run(fft_plan_, work_.memptr(), xaux_.memptr());\n        //\n        // y[0:nrows] = IFFT(FFT(c') * FFT(x'))[0:nrows]\n        //\n        xaux_ %= caux_;\n        ifft::run(ifft_plan_, xaux_.memptr(), work_.memptr());\n        if (beta == value_type())\n        {\n            y = work_.head(nrows());\n        }\n        else\n        {\n            y = work_.head(nrows()) + beta * y;\n        }\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.is_vec() && x.n_rows == nrows());\n        assert(y.is_vec() && y.n_rows == ncols());\n        //\n        // Form new vector x' = [0,0,...,0,x(m-1),x(m-2),...,x(0)] of length\n        // n + m - 1, and compute FFT.\n        //\n        work_.head(work_.size() - nrows()).zeros();\n        work_.tail(nrows()) = arma::conj(arma::flipud(x));\n        // xaux_ <-- FFT[work_]\n        fft::run(fft_plan_, work_.memptr(), xaux_.memptr());\n        //\n        // y[0:nrows-1] = IFFT(FFT(c') * FFT(x'))[0:nrows-1]\n        //\n        xaux_ %= caux_;\n        ifft::run(ifft_plan_, xaux_.memptr(), work_.memptr());\n        if (beta == value_type())\n        {\n            y = arma::conj(work_.tail(ncols()));\n        }\n        else\n        {\n            y = arma::conj(work_.tail(ncols())) + beta * y;\n        }\n    }\n\nprivate:\n    void set_fft_plans()\n    {\n        const int n       = static_cast<int>(work_.size());\n        const int howmany = 1;\n        fft_plan_ = fft::make_plan(n, howmany, work_.memptr(), xaux_.memptr());\n        ifft_plan_ =\n            ifft::make_plan(n, howmany, xaux_.memptr(), work_.memptr());\n    }\n};\n\n/*!\n * Create a Hankel matrix in dense form from the sequence of elements.\n *\n * This function creates a \\f$ m \\times n \\f$ Hankel matrix \\f$ A \\f$ in the\n * dense form from a given vector of matrix element \\f$ h =\n * [h_0,h_1,...,h_{n+m-1}]^{T}\\f$ such that,\n *\n * \\f[\n *   A = \\left[ \\begin{array}{}\n *     h_0 & h_1 & h_2 & h_3 & \\cdots & h_{n-1} \\\\\n *     h_1 & h_2 & h_3 & h_4 & \\cdots & h_{n}   \\\\\n *     h_2 & h_3 & h_4 & h_5 & \\cdots & h_{n+1} \\\\\n *     h_3 & h_4 & h_5 & h_6 & \\cdots & h_{n+2} \\\\\n *     \\vdots & \\vdots & \\vdots &\\vdots &\\ddots & \\vdots \\\\\n *     h_{m-1} & h_{m} & h_{m+1} & h_{m+2} & \\cdots & h_{m+n-1} \\\\\n *   \\end{array} \\right]\n * \\f]\n *\n * \\param[in] nrows number of rows, \\f$ m \\f$\n * \\param[in] ncols number of columns, \\f$ n \\f$\n * \\param[in] h vector of elments of Hankel matrix with length \\c nrows+ncols-1\n * \\return \\c arma::Mat with same scalar type of input vector type \\c T1.\n */\ntemplate <typename T1>\ntypename std::enable_if<arma::is_arma_type<T1>::value,\n                        arma::Mat<typename T1::elem_type>>::type\nmake_dense_hankel(arma::uword nrows, arma::uword ncols, const T1& h)\n{\n    assert(h.n_elem == nrows + ncols - 1);\n    arma::Mat<typename T1::elem_type> A(nrows, ncols);\n\n    for (arma::uword col = 0; col < ncols; ++col)\n    {\n        for (arma::uword row = 0; row < nrows; ++row)\n        {\n            A(row, col) = h(row + col);\n        }\n    }\n\n    return A;\n}\n\nnamespace detail\n{\ntemplate <typename T>\ninline T abs2(T x)\n{\n    return x * x;\n}\n\ntemplate <typename T>\ninline T abs2(std::complex<T> x)\n{\n    return std::real(x) * std::real(x) + std::imag(x) * std::imag(x);\n}\n} // namespace: detail\n\n/*!\n * Compute the Frobenius norm of general Hankel matrix.\n *\n * This function computes the Frobenius norm of \\c nrows-by-ncols general Hankel\n * matrix defined by the given vector of elements.\n *\n * \\param[in] nrows number of rows\n * \\param[in] ncols number of columns\n * \\param[in] h a vector that determines the Hankel matrix \\f$ A \\f$.  If <tt>\n * h.size() >= N </tt> with <tt> N = nrows + ncols - 1, </tt> first \\c N elemnts\n * are refered as the elements of Hankel matrix. If <tt> h.size() < N, </tt>\n * rest of elements are assumed to be zero.\n */\n\ntemplate <typename T1>\ntypename T1::pod_type fnorm_hankel(arma::uword nrows, arma::uword ncols,\n                                   const T1& h)\n{\n    arma::uword m, n;\n    std::tie(m, n) = std::minmax(nrows, ncols);\n    arma::uword l = m + n - 1;\n\n    auto sqsum = typename T1::pod_type();\n\n    if (h.n_elem > m)\n    {\n        for (arma::uword i = 0; i < m; ++i)\n        {\n            sqsum += (i + 1) * std::norm(h(i));\n        }\n\n        if (h.n_elem > n)\n        {\n            for (arma::uword i = m; i < n; ++i)\n            {\n                sqsum += m * std::norm(h(i));\n            }\n\n            for (arma::uword i = n; i < std::min(l, h.n_elem); ++i)\n            {\n                sqsum += (l - i) * std::norm(h(i));\n            }\n        }\n        else\n        {\n            for (arma::uword i = m; i < h.n_elem; ++i)\n            {\n                sqsum += m * std::norm(h(i));\n            }\n        }\n    }\n    else\n    {\n        for (arma::uword i = 0; i < h.n_elem; ++i)\n        {\n            sqsum += (i + 1) * std::norm(h(i));\n        }\n    }\n\n    return std::sqrt(sqsum);\n}\n} // namespace: expsum\n\n#endif /* EXPSUM_HANKEL_MATRIX_VECTOR_PRODUCT_HPP */\n", "meta": {"hexsha": "e9508fe1c02cfcd70d3108466e526ce869455432", "size": 12408, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/hankel_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/hankel_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/hankel_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": 30.5615763547, "max_line_length": 80, "alphanum_fraction": 0.5321566731, "num_tokens": 3961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240791017536, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5757292264344783}}
{"text": "/**\n * @file locallaplaceqfe.cc\n * @brief NPDE homework ParametricElementMatrices code\n * @author Simon Meierhans\n * @date 27/03/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"locallaplaceqfe.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Dense>\n\nnamespace DebuggingFEM {\n\nEigen::Matrix<double, 6, 6> LocalLaplaceQFE1::Eval(\n    const lf::mesh::Entity &cell) {\n  // Query (topological) type of cell/reference element\n  const lf::base::RefEl ref_el{cell.RefEl()};\n  // Verify that the cell is a triangle\n  LF_ASSERT_MSG(ref_el == lf::base::RefEl::kTria(),\n                \"Implemented for triangles only not for \" << ref_el);\n  // The final element matrix has size 6x6\n  Eigen::Matrix<double, 6, 6> result{};\n  // Obtain the vertex coordinates of the triangle\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  LF_ASSERT_MSG(geo_ptr != nullptr, \"Invalid geometry!\");\n  // Matrix storing corner coordinates in its columns\n  Eigen::Matrix<double, 2, 3> vertices{geo_ptr->Global(ref_el.NodeCoords())};\n  // Comopute element matrix for negative Laplacian and lowest-order Lgrangian\n  // finite elements as in Remark 2.4.5.9. in the course notes\n  Eigen::Matrix<double, 3, 3> X;  // temporary matrix\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = vertices.transpose();\n  const double area = 0.5 * std::abs(X.determinant());\n  // Initialize gradients!\n  auto grad_bary_coords{X.inverse().block<2, 3>(1, 0)};\n\n  // Returns all gradients of the local shape functions for quadatic Lagrangian\n  // finite elements in the columns of a matrix. The gradients are evaluated at\n  // a point specified by its reference coordinates.\n  auto gradientsLocalShapeFunctions =\n      [&grad_bary_coords](\n          const Eigen::Vector2d xh) -> Eigen::Matrix<double, 2, 6> {\n    Eigen::Matrix<double, 2, 6> gradients;\n    // barycentric coordinate functions\n    const std::array<double, 3> l{1.0 - xh[0] - xh[1], xh[0], xh[1]};\n    gradients.col(0) = grad_bary_coords.col(0) * (4 * l[0] - 1);\n    gradients.col(1) = grad_bary_coords.col(1) * (4 * l[1] - 1);\n    gradients.col(2) = grad_bary_coords.col(2) * (4 * l[2] - 1);\n    gradients.col(3) =\n        4 * (grad_bary_coords.col(0) * l[1] + grad_bary_coords.col(1) * l[0]);\n    gradients.col(4) =\n        4 * (grad_bary_coords.col(1) * l[2] + grad_bary_coords.col(2) * l[1]);\n    gradients.col(5) =\n        4 * (grad_bary_coords.col(0) * l[2] + grad_bary_coords.col(2) * l[0]);\n    return gradients;\n  };\n\n  const auto grad_vt_0{gradientsLocalShapeFunctions(Eigen::Vector2d(0, 0))};\n  const auto grad_vt_1{gradientsLocalShapeFunctions(Eigen::Vector2d(1, 0))};\n  const auto grad_vt_2{gradientsLocalShapeFunctions(Eigen::Vector2d(0, 1))};\n  result =\n      area / 3.0 *\n      (grad_vt_0.transpose() * grad_vt_0 + grad_vt_1.transpose() * grad_vt_1 +\n       grad_vt_2.transpose() * grad_vt_2);\n  return result;\n}\n\nEigen::Matrix<double, 6, 6> LocalLaplaceQFE2::Eval(\n    const lf::mesh::Entity &cell) {\n  // Query (topological) type of cell/reference element\n  const lf::base::RefEl ref_el{cell.RefEl()};\n  // Verify that the cell is a triangle\n  LF_ASSERT_MSG(ref_el == lf::base::RefEl::kTria(),\n                \"Implemented for triangles only not for \" << ref_el);\n  // The final element matrix has size 6x6\n  Eigen::Matrix<double, 6, 6> result{};\n  // Obtain the vertex coordinates of the triangle\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  LF_ASSERT_MSG(geo_ptr != nullptr, \"Invalid geometry!\");\n  // Matrix storing corner coordinates in its columns\n  Eigen::Matrix<double, 2, 3> vertices{geo_ptr->Global(ref_el.NodeCoords())};\n  // Comopute element matrix for negative Laplacian and lowest-order Lgrangian\n  // finite elements as in Remark 2.4.5.9. in the course notes\n  Eigen::Matrix<double, 3, 3> X;  // temporary matrix\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = vertices.transpose();\n  const double area = 0.5 * std::abs(X.determinant());\n  auto grad_bary_coords{X.inverse().block<2, 3>(1, 0)};\n  auto L{grad_bary_coords.transpose() * grad_bary_coords};\n\n  // See Example 2.7.5.7 in course notes for derivation of the formulas\n  result << 3. * L(0, 0), -L(0, 1), -L(0, 2), 4. * L(0, 1), 0, 4. * L(0, 2),\n      -L(0, 1), 3. * L(1, 1), -L(1, 2), 4. * L(0, 1), 4. * L(1, 2), 0, -L(0, 2),\n      -L(1, 2), 3. * L(2, 2), 0, 4. * L(2, 1), 4. * L(2, 0), 4. * L(0, 1),\n      4. * L(0, 1), 0, 8. * (L(0, 0) + L(0, 1) + L(1, 1)), 8 * L(0, 2),\n      8 * L(1, 2), 0, 4. * L(1, 2), 4. * L(2, 1), 8. * L(0, 2),\n      8. * (L(1, 1) + L(1, 2) + L(2, 2)), 8 * L(0, 1), 4 * L(0, 2), 0,\n      4. * L(2, 0), 8. * L(1, 2), 8. * L(0, 1),\n      8. * (L(0, 0) + L(0, 2) + L(2, 2));\n  result *= (area / 3.);\n  return result;\n}\n\n// implementation\nEigen::Matrix<double, 6, 6> LocalLaplaceQFE3::Eval(\n    const lf::mesh::Entity &cell) {\n  // Obtain the element matrix for piecewise linear Lagrangian FEM by using\n  // a built-in class of LehrFEM++\n  auto linear_lapl_element_matrix = lf::uscalfe::LinearFELaplaceElementMatrix();\n  Eigen::Matrix4d L = linear_lapl_element_matrix.Eval(cell);\n  // Variable for returning the final 6x6 element matrix\n  Eigen::Matrix<double, 6, 6> result{};\n\n  // The element matrix for quadratic finite elements can be constructed from\n  // the element matrix for linear FEM, see Example 2.7.5.7. in the lecture\n  // notes.\n  result << 3. * L(0, 0), -L(0, 1), -L(0, 2), 4. * L(0, 1), 0, 4. * L(0, 2),\n      -L(0, 1), 3. * L(1, 1), -L(1, 2), 4. * L(0, 1), 4. * L(1, 2), 0, -L(0, 2),\n      -L(1, 2), 3. * L(2, 2), 0, 4. * L(2, 1), 4. * L(2, 0), 4. * L(0, 1),\n      4. * L(0, 1), 0, 8. * (L(0, 0) + L(0, 1) + L(1, 1)), 8 * L(0, 2),\n      8 * L(1, 2), 0, 4. * L(1, 2), 4. * L(2, 1), 8. * L(0, 2),\n      8. * (L(1, 1) + L(1, 2) + L(2, 2)), 8 * L(0, 1), 4 * L(0, 2), 0,\n      4. * L(2, 0), 8. * L(1, 2), 8. * L(0, 1),\n      8. * (L(0, 0) + L(0, 2) + L(2, 2));\n  // A hideous manipulation introducces an error !\n  result(3, 3) *= 1.000001;\n  return (result / 3.0);\n}\n\n}  // namespace DebuggingFEM\n", "meta": {"hexsha": "fbe91b5b446c71acba7df799f2547458abf28464", "size": 6106, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DebuggingFEM/templates/locallaplaceqfe.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DebuggingFEM/templates/locallaplaceqfe.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DebuggingFEM/templates/locallaplaceqfe.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": 44.5693430657, "max_line_length": 80, "alphanum_fraction": 0.6138224697, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.575719545792012}}
{"text": "// Copyright 2021, Autonomous Space Robotics Lab (ASRL)\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * \\file geometry_tools.cpp\n * \\brief Source file for the ASRL vision package\n * \\details\n *\n * \\author Autonomous Space Robotics Lab (ASRL)\n */\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <opencv2/opencv.hpp>\n\n#include <vtr_logging/logging.hpp>\n#include <vtr_vision/geometry/geometry_tools.hpp>\n\nnamespace vtr {\nnamespace vision {\n\n/////////////////////////////////////////////////////////////////////////////////\n// @brief Triangulates a point from a rig and keypoints\n/////////////////////////////////////////////////////////////////////////////////\nEigen::Vector3d triangulateFromRig(const RigCalibration &rig_calibration,\n                                   const std::vector<cv::Point2f> &keypoints,\n                                   const FeatureInfos &kp_infos,\n                                   double *covariance) {\n  return triangulateFromCameras(rig_calibration.intrinsics,\n                                rig_calibration.extrinsics, keypoints, kp_infos,\n                                covariance);\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n/// @brief Triangulates a point (linearly) from a set of cameras and keypoints\n/////////////////////////////////////////////////////////////////////////////////\nEigen::Vector3d triangulateFromCameras(\n    const CameraIntrinsics &intrinsics, const Transforms &extrinsics,\n    const std::vector<cv::Point2f> &keypoints,\n    const vision::FeatureInfos &kp_infos, double *covariance) {\n  // sanity check\n  assert(intrinsics.size() == keypoints.size());\n  assert(extrinsics.size() == keypoints.size());\n\n  // make up the solution matrix\n  Eigen::MatrixXd Z = Eigen::MatrixXd::Zero(keypoints.size() * 2, 4);\n  for (unsigned ii = 0; ii < keypoints.size(); ii++) {\n    // grab each observation and add it to the matrix to solve\n    Eigen::Matrix<double, 3, 4> P =\n        intrinsics[ii] * extrinsics[ii].matrix().block(0, 0, 3, 4);\n    Z.row(ii * 2) = keypoints[ii].x * P.row(2) - P.row(0);\n    Z.row(ii * 2 + 1) = keypoints[ii].y * P.row(2) - P.row(1);\n  }\n\n  // solve the linear triangulation problem using SVD\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n      Z, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::MatrixXd V = svd.matrixV();\n\n  // extract the 3D point\n  Eigen::Vector3d X = V.col(3).hnormalized();\n\n  // calculate the covariance if required\n  if (covariance) {\n    // wrap the covariance and zero-initialize\n    Eigen::Map<Eigen::Matrix3d> cov_map(covariance);\n    cov_map.setZero();\n\n    // loop over the contribution of each measurement\n    for (unsigned ii = 0; ii < keypoints.size(); ii++) {\n      // Reproject the solved point for linearization\n      Eigen::Matrix<double, 3, 4> P =\n          intrinsics[ii] * extrinsics[ii].matrix().block(0, 0, 3, 4);\n      Eigen::Vector3d xii = P * X.homogeneous();\n      const auto &xii2 = xii(2);\n      auto xii2_2 = xii2 * xii2;  // helpers\n\n      // homogeneous to cartesian Jacobian for image points\n      Eigen::Matrix<double, 2, 3> h2c_jac;\n      h2c_jac << 1 / xii2, 0, -xii(0) / xii2_2, 0, 1 / xii2, -xii(1) / xii2_2;\n\n      // full camera projection Jacobian\n      auto jac = h2c_jac * P.leftCols<3>();\n      // sum the (linearized) precision contributions of each measurement\n      cov_map += jac.transpose() * kp_infos[ii].covariance.inverse() * jac;\n    }\n    // from precision matrix to covariance matrix\n    cov_map = cov_map.inverse().eval();\n  }\n\n  // return the linearly triangulated 3D point\n  return X;\n}\n#if 0\n/////////////////////////////////////////////////////////////////////////////////\n/// @brief Estimates a plane from a PCL point cloud\n/////////////////////////////////////////////////////////////////////////////////\nbool estimatePlane(const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud,\n                              const double distance_thresh,\n                              pcl::ModelCoefficients &coefficients,\n                              pcl::PointIndices &inliers) {\n\n\n  // Create the segmentation object\n  pcl::SACSegmentation<pcl::PointXYZ> seg;\n  // Optional\n  seg.setOptimizeCoefficients (true);\n  // Mandatory\n  seg.setModelType (pcl::SACMODEL_PLANE);\n  seg.setMethodType (pcl::SAC_RANSAC);\n  seg.setDistanceThreshold (distance_thresh);\n  seg.setInputCloud (cloud);\n  seg.segment (inliers, coefficients);\n\n  return !inliers.indices.empty();\n}\n#endif\n/////////////////////////////////////////////////////////////////////////////////\n/// @brief Estimate the distance from a plane\n/////////////////////////////////////////////////////////////////////////////////\ndouble estimatePlaneDepth(const Eigen::Vector3d &point,\n                          const Eigen::Vector4f &coefficients) {\n  // rename for clarity\n  const double &a = point(0);\n  const double &b = point(1);\n  const double &c = point(2);\n  const float &pa = coefficients(0);\n  const float &pb = coefficients(1);\n  const float &pc = coefficients(2);\n  const float &pd = coefficients(3);\n\n  // numerator\n  double num = std::fabs(a * pa + b * pb + c * pc + pd);\n\n  // denominator\n  double den = std::sqrt(pa * pa + pb * pb + pc * pc);\n\n  // result\n  double dist = num / den;\n\n  return dist;\n}\n\n}  // namespace vision\n}  // namespace vtr\n", "meta": {"hexsha": "9d689b229f8db303a33d56fcb8f30b0ff3253056", "size": 5811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/src/vtr_vision/src/geometry/geometry_tools.cpp", "max_stars_repo_name": "utiasASRL/vtr3", "max_stars_repo_head_hexsha": "b4edca56a19484666d3cdb25a032c424bdc6f19d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T03:42:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:40:01.000Z", "max_issues_repo_path": "main/src/vtr_vision/src/geometry/geometry_tools.cpp", "max_issues_repo_name": "shimp-t/vtr3", "max_issues_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T19:18:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T11:15:40.000Z", "max_forks_repo_path": "main/src/vtr_vision/src/geometry/geometry_tools.cpp", "max_forks_repo_name": "shimp-t/vtr3", "max_forks_repo_head_hexsha": "bdcad784ffe26fabfa737d0e195bcb3bacb930c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T01:31:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T05:09:37.000Z", "avg_line_length": 37.25, "max_line_length": 81, "alphanum_fraction": 0.5785579074, "num_tokens": 1368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5757195432518505}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015 - 2016.\r\n// Distributed under the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n\r\n// fixed_point_detail_hypergeometric.hpp implements templates\r\n// for computing hypergeometric series used for Taylor-series-like\r\n// expansions. These are used by certain <cmath> functions to\r\n// simplify typing and reduce the complexity of the code.\r\n\r\n#ifndef FIXED_POINT_DETAIL_HYPERGEOMETRIC_2015_08_21_HPP_\r\n  #define FIXED_POINT_DETAIL_HYPERGEOMETRIC_2015_08_21_HPP_\r\n\r\n  #include <cmath>\r\n  #include <cstdint>\r\n  #include <limits>\r\n\r\n  #include <boost/config.hpp>\r\n\r\n  namespace boost { namespace fixed_point { namespace detail {\r\n\r\n  template<typename NumericType>\r\n  NumericType hypergeometric_0f0(const NumericType& x)\r\n  {\r\n    // Compute the series representation of hypergeometric_0f0.\r\n\r\n    // There are no checks on input range or parameter boundaries\r\n    // in this series calculation.\r\n\r\n    // As such, this function is designed for small-argument\r\n    // Taylor-series-like expansions only. It is not intended\r\n    // for general purpose calculations of hypergeometric_0f0.\r\n\r\n    NumericType term(x);\r\n    NumericType h0f0(1U + term);\r\n\r\n    BOOST_CONSTEXPR_OR_CONST std::uint_fast16_t maximum_number_of_iterations = UINT16_C(10000);\r\n\r\n    // Perform the series expansion of hypergeometric_0f0(; ; x).\r\n    for(std::uint_fast16_t n = UINT16_C(2); n < maximum_number_of_iterations; ++n)\r\n    {\r\n      term *= x;\r\n      term /= n;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (n > UINT16_C(3));\r\n\r\n      using std::fabs;\r\n\r\n      if(   minimum_number_of_iterations_is_complete\r\n         && (fabs(term) <= std::numeric_limits<NumericType>::epsilon()))\r\n      {\r\n        break;\r\n      }\r\n\r\n      h0f0 += term;\r\n    }\r\n\r\n    return h0f0;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType hypergeometric_0f1(const NumericType& b,\r\n                                 const NumericType& x)\r\n  {\r\n    // Compute the series representation of hypergeometric_0f1.\r\n\r\n    // There are no checks on input range or parameter boundaries\r\n    // in this series calculation.\r\n\r\n    // As such, this function is designed for small-argument\r\n    // Taylor-series-like expansions only. It is not intended\r\n    // for general purpose calculations of hypergeometric_0f1.\r\n\r\n    NumericType bp(b);\r\n\r\n    NumericType term(x / bp);\r\n    NumericType h0f1(1U + term);\r\n\r\n    BOOST_CONSTEXPR_OR_CONST std::uint_fast16_t maximum_number_of_iterations = UINT16_C(10000);\r\n\r\n    // Perform the series expansion of hypergeometric_0f1(; b; x).\r\n    for(std::uint_fast16_t n = UINT16_C(2); n < maximum_number_of_iterations; ++n)\r\n    {\r\n      term *= x;\r\n      term /= n;\r\n\r\n      ++bp;\r\n\r\n      term /= bp;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (n > UINT16_C(3));\r\n\r\n      using std::fabs;\r\n\r\n      if(   minimum_number_of_iterations_is_complete\r\n         && (fabs(term) <= std::numeric_limits<NumericType>::epsilon()))\r\n      {\r\n        break;\r\n      }\r\n\r\n      h0f1 += term;\r\n    }\r\n\r\n    return h0f1;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType hypergeometric_2f1(const NumericType& a,\r\n                                 const NumericType& b,\r\n                                 const NumericType& c,\r\n                                 const NumericType& x)\r\n  {\r\n    // Compute the series representation of hypergeometric_2f1 taken from\r\n    // Abramowitz and Stegun 15.1.1.\r\n\r\n    // There are no checks on input range or parameter boundaries\r\n    // in this series calculation.\r\n\r\n    // As such, this function is designed for small-argument\r\n    // Taylor-series-like expansions only. It is not intended\r\n    // for general purpose calculations of hypergeometric_2f1.\r\n\r\n    NumericType ap(a);\r\n    NumericType bp(b);\r\n    NumericType cp(c);\r\n\r\n    NumericType term(((ap * bp) / cp) * x);\r\n    NumericType h2f1(1U + term);\r\n\r\n    BOOST_CONSTEXPR_OR_CONST std::uint_fast16_t maximum_number_of_iterations = UINT16_C(10000);\r\n\r\n    // Perform the series expansion of hypergeometric_2f1(a, b; c; x).\r\n    for(std::uint_fast16_t n = UINT16_C(2); n < maximum_number_of_iterations; ++n)\r\n    {\r\n      term *= x;\r\n      term /= n;\r\n\r\n      ++ap;\r\n      term *= ap;\r\n\r\n      ++cp;\r\n      term /= cp;\r\n\r\n      ++bp;\r\n      term *= bp;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (n > UINT16_C(3));\r\n\r\n      using std::fabs;\r\n\r\n      if(   minimum_number_of_iterations_is_complete\r\n         && (fabs(term) <= std::numeric_limits<NumericType>::epsilon()))\r\n      {\r\n        break;\r\n      }\r\n\r\n      h2f1 += term;\r\n    }\r\n\r\n    return h2f1;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType two_to_the_power_of_x(const NumericType& x,\r\n                                    const NumericType& my_ln_two)\r\n  {\r\n    // Compute the series representation of (2^x),\r\n    // which is very closely related to a hypergeometric\r\n    // series.\r\n\r\n    // There are no checks on input range or parameter boundaries\r\n    // in this series calculation.\r\n\r\n    // As such, this function is designed for small-argument\r\n    // Taylor-series-like expansions only. It is not intended\r\n    // for general purpose calculations of (2^x).\r\n\r\n    const NumericType ln_two_times_x(my_ln_two * x);\r\n\r\n    NumericType term(ln_two_times_x);\r\n    NumericType sum (1U + term);\r\n\r\n    BOOST_CONSTEXPR_OR_CONST std::uint_fast16_t maximum_number_of_iterations = UINT16_C(10000);\r\n\r\n    // Perform the series expansion of (2^x).\r\n    for(std::uint_fast16_t n = UINT16_C(2); n < maximum_number_of_iterations; ++n)\r\n    {\r\n      term *= ln_two_times_x;\r\n      term /= n;\r\n\r\n      const bool minimum_number_of_iterations_is_complete = (n > UINT16_C(3));\r\n\r\n      using std::fabs;\r\n\r\n      if(   minimum_number_of_iterations_is_complete\r\n         && (fabs(term) <= std::numeric_limits<NumericType>::epsilon()))\r\n      {\r\n        break;\r\n      }\r\n\r\n      sum += term;\r\n    }\r\n\r\n    return sum;\r\n  }\r\n\r\n  } } } // namespace boost::fixed_point::detail\r\n\r\n#endif // FIXED_POINT_DETAIL_HYPERGEOMETRIC_2015_08_21_HPP_\r\n", "meta": {"hexsha": "ba1f7e45673e723a81af8467166d361febc08d7b", "size": 6235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_hypergeometric.hpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_hypergeometric.hpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_hypergeometric.hpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4103773585, "max_line_length": 96, "alphanum_fraction": 0.6304731355, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5756845742104942}}
{"text": "/**\n * @file main.cpp\n * @brief Entry-point for dynamic notch filter example\n * @author Parker Lusk <parkerclusk@gmail.com>\n * @date 8 Dec 2020\n */\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/FFT>\n\n#include <plot.hpp>\n\n#include <adaptnotch/adaptnotch.h>\n\n#include \"csv.h\"\n\nstatic constexpr int DATUMS = 4; // number of columns to be extracted from CSV\nusing Data = Eigen::Matrix<double, Eigen::Dynamic, DATUMS>;\n\nvoid usage(int argc, char const *argv[])\n{\n  std::cout << argv[0] << \" <input csv data> [axis] [plot]\" << std::endl << std::endl;\n  std::cout << \"\\tRun adaptive notching algorithm on gyro data stored in CSV.\";\n  std::cout << std::endl << \"\\t\";\n  std::cout << \"CSV file expected to have been generated from sfpro or to be \";\n  std::cout << std::endl << \"\\t\";\n  std::cout << \"in same format. A gyro axis to analyze may be specified as\";\n  std::cout << std::endl << \"\\t\";\n  std::cout << \"(1, 2, 3) which corresponds to axes (x, y, z).\";\n  std::cout << std::endl << std::endl;\n  std::cout << \"\\tIf a 3rd argument is specified (e.g., '1'), an ASCII plot\";\n  std::cout << std::endl << \"\\t\";\n  std::cout << \"of the pre- and post-spectrum is shown in the terminal.\";\n  std::cout << std::endl << std::endl;\n}\n\n// ----------------------------------------------------------------------------\n\nData parseCSV(const std::string& file)\n{\n\n  // count number of entries (estimate)\n  std::ifstream ifile(file);\n  const int N = std::count(std::istreambuf_iterator<char>(ifile),\n                            std::istreambuf_iterator<char>(), '\\n');\n  ifile.close();\n\n  io::CSVReader<DATUMS> in(file);\n  in.next_line(); // ignore \"dsp clock\" message\n\n  // we only care about these four (DATUMS) columns\n  in.read_header(io::ignore_extra_column,\n                  \"timestamp(us)\", \"ang_x\", \"ang_y\", \"ang_z\");\n\n  Data D = Data::Zero(N, DATUMS);\n  int i = 0;\n  int time_us;\n  double wx, wy, wz;\n  while (in.read_row(time_us, wx, wy, wz)) {\n    D.row(i++) << time_us*1e-6, wx, wy, wz;\n  }\n\n  // resize to however many valid entries there were\n  D.conservativeResize(i, DATUMS);\n\n  return D;\n}\n\n// ----------------------------------------------------------------------------\n\nvoid plotResults(const adaptnotch::AdaptiveNotch& filter,\n            const Eigen::VectorXd& gyro, const Eigen::VectorXd& gyrof, int n)\n{\n  static const int N = filter.params().NFFT;\n  static Eigen::FFT<double> fft;\n  static plot::TerminalInfo term;\n  static bool init = false;\n  if (!init) {\n    term.detect();\n    fft.SetFlag(Eigen::FFT<double>::Unscaled);\n    fft.SetFlag(Eigen::FFT<double>::HalfSpectrum);\n    init = true;\n  }\n  constexpr float ymax = 0.2f; // arbitrary FFT mag scaling\n  static plot::RealCanvas<plot::BrailleCanvas> prefilter({ { 0.0f, ymax }, { N/2.0f, 0.0f } }, plot::Size(60, 10), term);\n  static plot::RealCanvas<plot::BrailleCanvas> postfilter({ { 0.0f, ymax }, { N/2.0f, 0.0f } }, plot::Size(60, 10), term);\n\n  // Build block layout\n  auto layout =\n      plot::alignment(\n          { term.size().x, 0 },\n          plot::margin(\n                  plot::vbox(\n                      plot::frame(u8\"Original Spectrum\", plot::Align::Center, &prefilter),\n                      plot::frame(u8\"Filtered Spectrum\", plot::Align::Center, &postfilter))));\n\n  // pre-filter spectrum\n  const Eigen::VectorXd Y = filter.spectrum() / N;\n\n  // select N most recent filtered measurements\n  const size_t s = (n-N<0) ? 0 : n-N;\n  const Eigen::VectorXd yf = gyrof.segment(s,N);\n\n  // post-filter spectrum\n  Eigen::VectorXcd Yfc;\n  fft.fwd(Yfc, yf);\n  const Eigen::VectorXd Yf = Yfc.array().abs() / N;\n\n  // Plot spectrum pre-filtering\n  prefilter.clear();\n  for (size_t i=1; i<N/2; i++) {\n    prefilter.path(plot::palette::royalblue,{{static_cast<float>(i-1), static_cast<float>(Y(i-1))},\n                                          {static_cast<float>(i), static_cast<float>(Y(i))}});\n  }\n\n  // Plot spectrum post-filtering\n  postfilter.clear();\n  for (size_t i=1; i<N/2; i++) {\n    postfilter.path(plot::palette::royalblue,{{static_cast<float>(i-1), static_cast<float>(Yf(i-1))},\n                                          {static_cast<float>(i), static_cast<float>(Yf(i))}});\n  }\n\n  for (auto const& line: layout)\n    std::cout << term.clear_line() << line << std::endl;\n  std::cout << term.move_up(layout.size().y) << std::flush;\n}\n\n// ----------------------------------------------------------------------------\n\nint main(int argc, char const *argv[])\n{\n\n  int axis = 1;     ///< x, y, or z axis of gyro to analyze\n  std::string file; ///< input data from IMU\n  bool shouldPlot = false; ///< show FFT plots in terminal\n\n  if (argc < 2) {\n    std::cerr << \"Not enough input arguments.\" << std::endl << std::endl;\n    usage(argc, argv);\n    return -1;\n  } else if (argc >= 2) {\n    file = std::string(argv[1]);\n  }\n\n  if (argc >= 3) {\n    axis = std::stoi(argv[2]);\n    if (axis < 1 || axis > 3) axis = 1;\n  }\n\n  if (argc >= 4) shouldPlot = true;\n\n  //\n  // Process raw IMU data\n  //\n\n  Data D = parseCSV(file);\n\n  const Eigen::VectorXd diff = D.col(0).bottomRows(D.rows()-1) - D.col(0).topRows(D.rows()-1);\n  const double Ts = diff.mean();\n  const double Fs = 1./Ts;\n  const int N = D.rows();\n\n  //\n  // Adaptive notch filter setup\n  //\n\n  adaptnotch::AdaptiveNotch::Params params;\n  adaptnotch::AdaptiveNotch filter(params);\n\n  //\n  // Main loop - simulated gyro sampling\n  //\n\n  Eigen::VectorXd gyrof = Eigen::VectorXd::Zero(N);\n  const auto start = std::chrono::steady_clock::now();\n\n\n  for (size_t n=0; n<N; n++) {\n    const double gyro = D(n, axis);\n    gyrof(n) = filter.apply(gyro);\n    if (shouldPlot) plotResults(filter, D.col(axis), gyrof, n);\n  }\n\n\n  //\n  // Timing stats\n  //\n\n  const auto end = std::chrono::steady_clock::now();\n  const double duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() * 1e-6;\n\n  const double timu = D(N-1,0) - D(0,0);\n\n  std::cout << \"Processed \" << timu << \" seconds (\" << N << \" samples) of IMU\";\n  std::cout << \" data in \" << duration << \" seconds\" << std::endl;\n  std::cout << \"Real-time factor: \" << timu / duration << std::endl;\n  std::cout << \"Estimated peak freq: \" << filter.peakFreq() << std::endl;\n\n  //\n  // Write data to file\n  //\n\n  Eigen::MatrixXd out(N, 3);\n  out << Eigen::VectorXd::LinSpaced(N, 0, N*Ts), D.col(axis), gyrof;\n\n  std::ofstream of(\"data_processed.txt\");\n  of << out << std::endl;\n  of.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "7f89c762391022da962aee9750600beeb874a53c", "size": 6489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "plusk01/adaptive-gyro-filtering", "max_stars_repo_head_hexsha": "6e2565694a6b9cba3007958670fc2b85975b2868", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-10T01:59:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T06:33:11.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "plusk01/adaptive-gyro-filtering", "max_issues_repo_head_hexsha": "6e2565694a6b9cba3007958670fc2b85975b2868", "max_issues_repo_licenses": ["MIT"], "max_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": "plusk01/adaptive-gyro-filtering", "max_forks_repo_head_hexsha": "6e2565694a6b9cba3007958670fc2b85975b2868", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T06:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T06:33:13.000Z", "avg_line_length": 29.7660550459, "max_line_length": 122, "alphanum_fraction": 0.5832948066, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430604060731, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5756845670818146}}
{"text": "//  Copyright (c) 2019 AUTHORS\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#include \"octotiger/grid.hpp\"\n\n#include <hpx/runtime/threads/run_as_os_thread.hpp>\n\n#include \"octotiger/test_problems/blast.hpp\"\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <unordered_map>\n#include <vector>\n\n#if !defined(OCTOTIGER_HAVE_BOOST_MULTIPRECISION)\n#include <quadmath.h>\nusing sed_real = __float128;\n#else\n#include <boost/multiprecision/cpp_bin_float.hpp>\nusing sed_real = boost::multiprecision::cpp_bin_float_quad;\n#endif\n\n/*extern \"C\" {*/\n/* Subroutine */int sed_1d__(sed_real *time, int *nstep, sed_real *xpos, sed_real *eblast, sed_real *omega_in__, sed_real *xgeom_in__, sed_real *rho0,\n\t\tsed_real *vel0, sed_real *ener0, sed_real *pres0, sed_real *cs0, sed_real *gam0, sed_real *den, sed_real *ener, sed_real *pres, sed_real *vel,\n\t\tsed_real *cs);\n//}\n\nconstexpr real blast_wave_t0 = 7e-4;\n\nstd::vector<real> blast_wave_analytic(real x, real y, real z, real t) {\n\tstatic const auto dxmin = 2.0 * opts().xscale / INX / double(1 << opts().max_level);\n\treal r = std::sqrt(x * x + y * y + z * z);\n\tr = std::max(r, dxmin * 1.0e-3);\n\tt += blast_wave_t0;\n\treal rmax = 3.0 * opts().xscale;\n\treal d, v, p;\n\tsedov::solution(t, r, rmax, d, v, p);\n\tstd::vector<real> u(opts().n_fields, 0.0);\n\tu[rho_i] = u[spc_i] = std::max(d, 1.0e-20);\n\treal s = d * v;\n\tu[sx_i] = s * x / r;\n\tu[sy_i] = s * y / r;\n\tu[sz_i] = s * z / r;\n\treal e = std::max(p / (grid::get_fgamma() - 1), 1.0e-20);\n\tu[egas_i] = e + s * v * 0.5;\n\tu[tau_i] = std::pow(e, 1 / grid::get_fgamma());\n\treturn u;\n}\n\nstd::vector<real> blast_wave(real x, real y, real z, real dx) {\n\tstd::vector<real> u(opts().n_fields, 0.0);\n\tu[rho_i] = u[spc_i] = 1.0;\n\tconst auto r2 = x * x + y * y + z * z;\n\tconst auto rmax = dx * 3.5;\n\tif (r2 < rmax * rmax) {\n\t\tu[egas_i] = opts().eblast0 / (dx * dx * dx)  / 160.0;\n\t} else {\n\t\tu[egas_i] = 1.0e-20;\n\t}\n\tu[tau_i] = std::pow(u[egas_i], 1.0 / grid::get_fgamma());\n\treturn u;\n\n}\n", "meta": {"hexsha": "f5f482f2606d8c1415fa3b642272d5ad1f63e47f", "size": 2103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_problems/blast/sedov.cpp", "max_stars_repo_name": "cclauss/octotiger", "max_stars_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_stars_repo_licenses": ["BSL-1.0"], "max_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_problems/blast/sedov.cpp", "max_issues_repo_name": "cclauss/octotiger", "max_issues_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_issues_repo_licenses": ["BSL-1.0"], "max_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_problems/blast/sedov.cpp", "max_forks_repo_name": "cclauss/octotiger", "max_forks_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_forks_repo_licenses": ["BSL-1.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.9264705882, "max_line_length": 150, "alphanum_fraction": 0.6514503091, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5756845631431646}}
{"text": "// c10e14ExprWithSimbolTable.cpp: определяет точку входа для консольного приложения.\n//\n\n#include \"stdafx.h\"\n#include <boost/regex.hpp>\n#include <iostream>\n#include <sstream>\ntypedef std::string str;\nclass Expr\n{\npublic:\n\tExpr(const char* a) { s0 = a;reed(); }\n\tint Eval()\n\t{\n\t\tstd::vector<str> ter = terms;\n\t\tstd::vector<str> sig = signs;\n\t\tboost::smatch sm;\n\t\tfor (auto &t : ter)\n\t\t{\n\t\t\twhile (boost::regex_search(t, sm, boost::regex(\"([0-9]+)(\" + ops[0] + \")([0-9]+)\")))\n\t\t\t{\n\t\t\t\tt.replace(sm.position(),sm.length(),f(sm[1], sm[2], sm[3]) );\n\t\t\t\tstd::cout << t << std::endl;\n\t\t\t}\n\t\t}\n\t\tfor (auto t : ter)\n\t\t\tstd::cout << t << std::endl;\n\t\tif (ter.size() == sig.size()) ter.insert(ter.begin(), \"0\");\n\t\twhile (ter.size() > 1)\n\t\t{\n\t\t\tter[0] = f(ter[0], sig[0], ter[1]);\n\t\t\tter.erase(ter.begin());\n\t\t\tsig.erase(sig.begin());\n\t\t}\n/*\n\t\tstr s = s0;\n\t\t\n\t\tboost::smatch f00;\n\t\tfor (auto o : ops)\n\t\t{\n\t\t\twhile (boost::regex_search(s, f00, boost::regex(str(\"((?:^-)?([0-9]+))([\") + o + \"])((?2))\")))\n\t\t\t{\n\t\t\t\ts.replace(f00.position(), f00.length(),f(f00[1], f00[3], f00[4]));\n\t\t\t}\n\t\t}\n\t\ti = s_to_i(s);*/\n\t\ti = s_to_i(ter[0]);\n\t\treturn i;\n\t}\n\t//void print() { std::cout << i << std::endl; }\n\tvoid printBrackets()\n\t{\n\t\t\n\t\tstd::vector<str> ter = terms;\n\t\tint ts = ter.size();\n\t\tint ss = signs.size();\n\t\tif (ts > ss) { std::cout << '(' << ter[0] << ')'; ter.erase(ter.begin()); }\n\t\tfor (int i = 0; i < ts; i++)\n\t\t{\n\t\t\tstd::cout << signs[i] << '(' << ter[i] << ')';\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\t\nprivate:\n\tstr s0;\n\tint s_to_i(str z)\n\t{\n\t\tstd::stringstream io;\n\t\tio << z;\n\t\tint i;\n\t\tio >> i;\n\t\treturn i;\n\t}\n\tint i;\n\tstd::vector<str> ops = { \"\\\\*|/\",\"+-\" };\n\tstd::vector<str> terms;\n\tstd::vector<str> signs;\n\tvoid reed()\n\t{\n\t\tboost::regex e(\"([+-])?([^+-]+)\");\n\t\tboost::sregex_iterator it(s0.begin(), s0.end(), e);\n\t\tboost::sregex_iterator itend;\n\t\twhile (it != itend)\n\t\t{\n\t\t\tstr z = (*it)[1];\n\t\t\tif(z.size()>0) signs.push_back(z);\n\t\t\tterms.push_back((*it)[2]);\n\t\t\tit++;\n\t\t}\n\t}\n\tstr f(str x0, str op0, str y0)\n\t{\n\t\tint x = s_to_i(x0);\n\t\tint y = s_to_i(y0);\n\t\tchar op = op0[0];\n\t\tint r;\n\t\tswitch (op)\n\t\t{\n\t\tcase '+':\n\t\t\tr= x + y;\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tr = x - y;\n\t\t\tbreak;\n\t\tcase '*': r = x*y; \n\t\t\tbreak;\n\t\tcase '/':r = x / y;\n\t\t\tbreak;\n\t\t}\n\t\tstr st = (std::to_string(int(r)));\n\t\tstd::cout <<x0<<op0<<y0<<'='<< r << std::endl;\n\t\treturn st;\n\t}\n};\nint main()\n{\n\tExpr ex(\"-3-2+4*3/2\");\n\t//ex.Eval();\n\tex.printBrackets();\n\tstd::cout << ex.Eval() << std::endl;\n\t\n\t/*str s = \"3-2+4*3/2\";\n\tboost::smatch sm;\n\tboost::regex e(\"^([\\\\+\\\\-])?([^\\\\+\\\\-]+)(?:([\\\\+\\\\-])([^\\\\+\\\\-]+))*\");\n\tboost::regex_match(s, sm, e, boost::match_extra);\n\tfor(auto i:sm)\n\t\tstd::cout << i << std::endl;\n\tboost::regex e1(\"([+-])?([^+-]+)\");\n\tboost::sregex_iterator it(s.begin(),s.end(), e1);\n\tboost::sregex_iterator itend;\n\twhile (it != itend)\n\t{\n\t\tstd::cout << (*it)[1]<<'\\n'<< (*it)[2] << std::endl;\n\t\tit++;\n\t}*/\n}\n\n", "meta": {"hexsha": "c93db19eb6015f31f7069c1ef16129f30ff0f3f4", "size": 2877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable.cpp", "max_stars_repo_name": "abicorios/MyCppExercises", "max_stars_repo_head_hexsha": "e8ca408c1aac6a780eaf92018aa7da4fd692459a", "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": "c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable.cpp", "max_issues_repo_name": "abicorios/MyCppExercises", "max_issues_repo_head_hexsha": "e8ca408c1aac6a780eaf92018aa7da4fd692459a", "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": "c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable/c10e14ExprWithSimbolTable.cpp", "max_forks_repo_name": "abicorios/MyCppExercises", "max_forks_repo_head_hexsha": "e8ca408c1aac6a780eaf92018aa7da4fd692459a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6978417266, "max_line_length": 97, "alphanum_fraction": 0.5064303094, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.575684558390712}}
{"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#include <string>\n\nusing namespace std::string_literals;\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/complex_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#include \"miMaS/iteration.h\"\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*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\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\ndouble\nerror_H ( std::size_t Nx , std::size_t Nv , double dt )\n{\n  const double Tf = 5.;\n\n  field<double,1> fh(boost::extents[Nv][Nx]);\n  complex_field<double,1> hfh(boost::extents[Nv][Nx]);\n\n  const double Kx = 0.5;\n  fh.range.v_min = -8.; fh.range.v_max = 8.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n  fh.compute_steps();\n\n  ublas::vector<double> v(Nv,0.);\n  std::generate( v.begin() , v.end() , [&,k=0]() mutable {return (k++)*fh.step.dv+fh.range.v_min;} );\n\n  ublas::vector<double> kx(Nx); // beware, Nx need to be odd\n  {\n    double l = fh.range.len_x();\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  }\n\n  const double alpha = 0.2 , ui = 2.;\n  auto tb_M1 = maxwellian( 0.5*alpha , ui , 1. ) , tb_M2 = maxwellian( 0.5*alpha , -ui , 1. );\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n    fft::fft(fh[k].begin(),fh[k].end(),hfh[k].begin());\n  }\n\n  std::size_t iter = 0;\n  double current_time = 0.;\n\n  ublas::vector<double> uc(Nx,0.);\n  ublas::vector<double> E (Nx,0.);\n\n  std::vector<double> H; H.reserve(int(std::ceil(Tf/dt))+1);\n\n  const double rho_c = 1.-alpha;\n  const double sqrt_rho_c = std::sqrt(rho_c);\n\n  // init E with Poisson solver, init also ee, Emax, H and times\n  {\n    poisson<double> poisson_solver(Nx,fh.range.len_x());\n    ublas::vector<double> rho(Nx,0.); rho = fh.density(); // compute density from init hot data\n    for ( auto i=0 ; i<Nx ; ++i ) { rho[i] += (1.-alpha); } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n\n    double total_energy = energy(fh,E);\n    total_energy += 0.; // sum(rho_c*u_c*u_c) = 0 because u_c = 0 at time 0\n    H.push_back( total_energy );\n  }\n\n  // initialize memory for all temporary variables\n  ublas::vector<double> J(Nx,0.);\n  fft::spectrum_ d(Nx);\n  field<double,1> Edvf(tools::array_view<const std::size_t>(fh.shape(),2));\n  ublas::vector<double> uc1(Nx) , uc2(Nx) , uc3(Nx) , uc4(Nx) , uc5(Nx) , uc6(Nx) , uc7(Nx),\n                        E1 (Nx) , E2 (Nx) , E3 (Nx) , E4 (Nx) , E5 (Nx) , E6 (Nx) , E7 (Nx);\n  complex_field<double,1> hfh1(boost::extents[Nv][Nx]) , hfh2(boost::extents[Nv][Nx]) ,\n                          hfh3(boost::extents[Nv][Nx]) , hfh4(boost::extents[Nv][Nx]) ,\n                          hfh5(boost::extents[Nv][Nx]) , hfh6(boost::extents[Nv][Nx]) ,\n                          hfh7(boost::extents[Nv][Nx]) ;\n  fh.write(\"init.dat\");\n\n  while (  current_time < Tf ) {\n\n///////////////////////////////////////////////////////////////////////////////\n// DP4(3) /////////////////////////////////////////////////////////////////////\n\n    // STAGE 1\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E);\n\n      double c05 = std::cos(0.5*dt*sqrt_rho_c), s05 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        uc1[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c - 0.5*dt*J[i]*s05/sqrt_rho_c;\n        E1[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<Nx ; ++i ) {\n          hfh1[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) - 0.5*dt*d[i]*std::exp(-0.5*I*kx[i]*v[k]*dt);\n        }\n      }\n    } // end stage 1\n\n    // STAGE 2\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh1[k].begin(),hfh1[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E1);\n\n      double c05 = std::cos(0.5*dt*sqrt_rho_c), s05 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        uc2[i] =  uc[i]*c05 + E[i]*s05/sqrt_rho_c;\n        E2[i]  = -uc[i]*s05*sqrt_rho_c + E[i]*c05 - 0.5*dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<Nx ; ++i ) {\n          hfh2[k][i] = hfh[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) - 0.5*dt*d[i];\n        }\n      }\n    } // end stage 2\n\n    // STAGE 3\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh2[k].begin(),hfh2[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E2);\n\n      double c1  = std::cos(dt*sqrt_rho_c)     , s1  = std::sin(dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*dt*sqrt_rho_c) , s05 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        uc3[i] =  uc[i]*c1 + E[i]*s1/sqrt_rho_c - dt*J[i]*s05/sqrt_rho_c;\n        E3[i]  = -uc[i]*s1*sqrt_rho_c + E[i]*c1 - dt*J[i]*c05;\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<Nx ; ++i ) {\n          hfh3[k][i] = hfh[k][i]*std::exp(-I*kx[i]*v[k]*dt) - dt*d[i]*std::exp(-0.5*I*kx[i]*v[k]*dt);\n        }\n      }\n    } // end stage 3\n\n    // STAGE 4\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh3[k].begin(),hfh3[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E3);\n\n      double c1  = std::cos(dt*sqrt_rho_c)     , s1  = std::sin(dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*dt*sqrt_rho_c) , s05 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        uc4[i] = -(1./3.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./3.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./3.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/3.;\n        E4[i]  = -(1./3.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./3.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./3.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/3. - (1./6.)*dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<Nx ; ++i ) {\n          hfh4[k][i] = -(1./3.)*hfh[k][i]*std::exp(-I*kx[i]*v[k]*dt) + (1./3.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) + (2./3.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) + hfh3[k][i]/3. - (1./6.)*dt*d[i];\n        }\n      }\n    } // end stage 4\n\n    // STAGE 5\n    {\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh4[k].begin(),hfh4[k].end(),fh[k].begin()); }\n      J = fh.courant();\n      Edvf = weno::trp_v(fh,E4);\n\n      double c1  = std::cos(dt*sqrt_rho_c)     , s1  = std::sin(dt*sqrt_rho_c)    ,\n             c05 = std::cos(0.5*dt*sqrt_rho_c) , s05 = std::sin(0.5*dt*sqrt_rho_c);\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        uc5[i] = -(1./5.)*(  uc[i]*c1 + E[i]*s1/sqrt_rho_c ) + (1./5.)*(  uc1[i]*c05 + E1[i]*s05/sqrt_rho_c ) + (2./5.)*(  uc2[i]*c05 + E2[i]*s05/sqrt_rho_c ) + uc3[i]/5. + (2./5.)*uc4[i];\n        E5[i]  = -(1./5.)*( -uc[i]*s1*sqrt_rho_c + E[i]*c1 ) + (1./5.)*( -uc1[i]*s05*sqrt_rho_c + E1[i]*c05 ) + (2./5.)*( -uc2[i]*s05*sqrt_rho_c + E2[i]*c05 ) + E3[i]/5. + (2./5.)*E4[i] - (1./10.)*dt*J[i];\n      }\n      for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) {\n        d.fft(&(Edvf[k][0]));\n        for ( auto i=0 ; i<Nx ; ++i ) {\n          hfh5[k][i] = -(1./5.)*hfh[k][i]*std::exp(-I*kx[i]*v[k]*dt) + (1./5.)*hfh1[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) + (2./5.)*hfh2[k][i]*std::exp(-0.5*I*kx[i]*v[k]*dt) + hfh3[k][i]/5. + (2./5.)*hfh4[k][i] - 0.1*dt*d[i];\n        }\n      }\n    } // end stage 5\n\n///////////////////////////////////////////////////////////////////////////////\n// MONITORING /////////////////////////////////////////////////////////////////\n\n    // SAVE TIME STEP\n    std::copy(  uc4.begin() ,  uc4.end() ,  uc.begin() );\n    std::copy(   E4.begin() ,   E4.end() ,   E.begin() );\n    std::copy( hfh4.begin() , hfh4.end() , hfh.begin() );\n\n    for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n    double total_energy = energy(fh,E);\n    {\n      auto rhoh = fh.density();\n      fft::spectrum_ hrhoh(Nx); hrhoh.fft(&rhoh[0]);\n      fft::spectrum_ hE(Nx); hE.fft(&E[0]);\n      fft::spectrum_ hrhoc(Nx);\n      hrhoc[0] = I*kx[0]*hE[0] - hrhoh[0] + 1.;\n      for ( auto i=1 ; i<Nx ; ++i )\n        { hrhoc[i] = I*kx[i]*hE[i] - hrhoh[i]; }\n      ublas::vector<double> rhoc (Nx,0.); hrhoc.ifft(rhoc.begin());\n\n      for ( auto i=0 ; i<Nx ; ++i )\n        { total_energy += rhoc[i]*uc[i]*uc[i]; }\n    }\n    H.push_back( total_energy );\n\n    // increment time\n    current_time += dt;\n\n    ++iter;\n    if ( current_time+dt > Tf ) { dt = Tf - current_time; }\n  } // while (  current_time < Tf ) // end of time loop\n\n  for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(hfh[k].begin(),hfh[k].end(),fh[k].begin()); }\n  fh.write(\"vp.dat\");\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  return std::abs((h-H[0])/std::abs(H[0]));\n}\n\nint\nmain ( int argc , char const * argv[] )\n{\n  const std::size_t Nx = 75 , Nv = 1024;\n  const double dt_max = 3.*16./Nv;\n\n  for ( auto i=1 ; i<6 ; ++i ) {\n    double dt = dt_max/double(i);\n    std::cout << dt << \" \" << std::flush;\n    double h = error_H(Nx,Nv,dt);\n    std::cout << h << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "98191a715050b73d2e720afdde02e8bb37631ca3", "size": 10203, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/order_H_dp4.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/order_H_dp4.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/order_H_dp4.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": 38.6477272727, "max_line_length": 224, "alphanum_fraction": 0.4982848182, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.575507762352161}}
{"text": "///////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::normal::normalizing_constant.hpp         //\n//                                                                               //\n//  (C) Copyright 2009 Erwann Rogard                                             //\n//  Use, modification and distribution are subject to the                        //\n//  Boost Software License, Version 1.0. (See accompanying file                  //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)             //\n///////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_NORMALIZING_CONSTANT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_NORMALIZING_CONSTANT_HPP_ER_2009\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/distributions/normal.hpp>\n\nnamespace boost{\nnamespace math{\n\ntemplate<typename T,typename P>\nT normalizing_constant(const boost::math::normal_distribution<T,P>& d){\n    static T pi = boost::math::constants::pi<T>;\n    static T two = static_cast<T>(2);\n    return sqrt(two * pi) * d.scale();\n}\n\n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "db57389bb0cfc16a432c72d4f458be90d8ddda43", "size": 1264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/normalizing_constant.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/normalizing_constant.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/normalizing_constant.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": 43.5862068966, "max_line_length": 92, "alphanum_fraction": 0.5506329114, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.575507752794639}}
{"text": "#define __STDCPP_WANT_MATH_SPEC_FUNCS__ 1\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n#include <cmath>\r\n#include <limits>\r\n#include <SFML/Graphics.hpp>\r\n#include <SFML/Window.hpp>\r\n#include <boost/math/special_functions/beta.hpp>\r\n#include \"readdata.h\"\r\n#include \"classes.h\"\r\n\r\n\r\n#define STOP 1.0e-8\r\n#define TINY 1.0e-30\r\n\r\n//stolen incomplete beta function cuz im too lazy to implement\r\ndouble incbeta(double a, double b, double x) {\r\n    if (x < 0.0 || x > 1.0) return 1.0/0.0;\r\n\r\n    /*The continued fraction converges nicely for x < (a+1)/(a+b+2)*/\r\n    if (x > (a+1.0)/(a+b+2.0)) {\r\n        return (1.0-incbeta(b,a,1.0-x)); /*Use the fact that beta is symmetrical.*/\r\n    }\r\n\r\n    /*Find the first part before the continued fraction.*/\r\n    const double lbeta_ab = lgamma(a)+lgamma(b)-lgamma(a+b);\r\n    const double front = exp(log(x)*a+log(1.0-x)*b-lbeta_ab) / a;\r\n\r\n    /*Use Lentz's algorithm to evaluate the continued fraction.*/\r\n    double f = 1.0, c = 1.0, d = 0.0;\r\n\r\n    int i, m;\r\n    for (i = 0; i <= 200; ++i) {\r\n        m = i/2;\r\n\r\n        double numerator;\r\n        if (i == 0) {\r\n            numerator = 1.0; /*First numerator is 1.0.*/\r\n        } else if (i % 2 == 0) {\r\n            numerator = (m*(b-m)*x)/((a+2.0*m-1.0)*(a+2.0*m)); /*Even term.*/\r\n        } else {\r\n            numerator = -((a+m)*(a+b+m)*x)/((a+2.0*m)*(a+2.0*m+1)); /*Odd term.*/\r\n        }\r\n\r\n        /*Do an iteration of Lentz's algorithm.*/\r\n        d = 1.0 + numerator * d;\r\n        if (fabs(d) < TINY) d = TINY;\r\n        d = 1.0 / d;\r\n\r\n        c = 1.0 + numerator / c;\r\n        if (fabs(c) < TINY) c = TINY;\r\n\r\n        const double cd = c*d;\r\n        f *= cd;\r\n\r\n        /*Check for stop.*/\r\n        if (fabs(1.0-cd) < STOP) {\r\n            return front * (f-1.0);\r\n        }\r\n    }\r\n\r\n    return 1.0/0.0; /*Needed more loops, did not converge.*/\r\n}\r\n\r\ndouble commulDistribution(double v, double t)\r\n{\r\n\tdouble incbetaVal = (v/(pow(t,2)+v));\r\n\tdouble incbetaAns = incbeta((v/2),0.5,incbetaVal);\r\n\t/*\r\n\tstd::cout << \"func value small thingy yeah: \"  << (v/(pow(t,2)+v)) << std::endl;\r\n\tstd::cout << \"inc beta func: \" << incbetaAns << std::endl;\r\n\tstd::cout << \"real beta func: \"  << std::beta((v/2),0.5) << std::endl;\r\n\tdouble regularizedIncBeta = incbetaAns/std::beta((v/2),0.5);*/\r\n\t\r\n\tdouble commulDistr = 1-incbetaAns/2;\r\n\t\r\n\treturn commulDistr;\r\n}\r\n\r\ndouble invCommulDistribution(double v, double t)\r\n{\r\n\tdouble signVal = (t-0.5) < 0 ? -1: 1;\r\n\tdouble pVal = t<0.5 ? (2*t) : (2*(1-t));\r\n\tdouble val2Divis = boost::math::ibeta_inv((v/2),0.5,pVal);\r\n\tdouble val2 = v*(1/val2Divis-1);\r\n\tdouble val2Sqrt = sqrt(val2);\r\n\t/*std::cout << \"(signVal: \"  << signVal << \")\" << std::endl;\r\n\tstd::cout << \"(pVal: \"  << pVal << \")\" << std::endl;\r\n\tstd::cout << \"(val2Divis: \"  << val2Divis << \")\" << std::endl;\r\n\tstd::cout << \"(val2: \"  << val2 << \")\" << std::endl;*/\r\n\tdouble invCommulDistr = signVal * val2Sqrt;\r\n\t\r\n\treturn invCommulDistr;\r\n}\r\n\r\nvoid windowFunc(int width, int height, std::vector<DataValues> data)\r\n{\r\n\tsf::RenderWindow window(sf::VideoMode(width,height),\"Graph view\");\r\n\r\n\tDate firstDate = data[0].date;\r\n\tDate lastDate = data[data.size()-1].date;\r\n\tint dateSpanDays = lastDate.ToDays()-firstDate.ToDays();\r\n\tfloat lowestVar = std::numeric_limits<float>::infinity();\r\n\tfloat highestVar = -std::numeric_limits<float>::infinity();\r\n\tfor(DataValues datai : data)\r\n\t{\r\n\t\tif(lowestVar>datai.value)\r\n\t\t{\r\n\t\t\tlowestVar=datai.value;\r\n\t\t}\r\n\t\tif(highestVar<datai.value)\r\n\t\t{\r\n\t\t\thighestVar=datai.value;\r\n\t\t}\r\n\t}\r\n\r\n\tfloat highlowDiff = highestVar-lowestVar;\r\n\r\n\tfloat lineWidth = 2.5;\r\n\tfloat textScale = 0.5;\r\n\tfloat statsPointRadius = 4;\r\n\tint floatPrecision = 2;\r\n\r\n\r\n\t//drawing bla bla bla\r\n\tsf::Font font;\r\n\tsf::FloatRect bounds;\r\n\t#ifdef _WIN32\r\n\tfont.loadFromFile(\"c:/windows/fonts/arial.ttf\");\r\n\t#endif\r\n\t#ifdef linux\r\n\tfont.loadFromFile(\"/usr/share/fonts/truetype/freefont/FreeSans.ttf\");\r\n\t#endif\r\n\tstd::vector<sf::RectangleShape> shapes;\r\n\tstd::vector<sf::Text> texts;\r\n\r\n\tsf::RectangleShape lineHor(sf::Vector2f(width-(width/8), lineWidth));\r\n\tlineHor.setOrigin((width-(width/8))/2,lineWidth/2);\r\n\tlineHor.setPosition(width/1.85,height-(height/6));\r\n\t\r\n\tshapes.push_back(lineHor);\r\n\t\r\n\tsf::RectangleShape lineVer(sf::Vector2f(height-(height/5.5), lineWidth));\r\n\tlineVer.setOrigin((height-(height/5.5))/2,lineWidth/2);\r\n\tlineVer.setPosition((width/1.85)-(width/2)+(width/8)/2,(height-(height/6))-((height-(height/5.5))/2)+lineWidth/2);\r\n\tlineVer.setRotation(90);\r\n\t\r\n\tshapes.push_back(lineVer);\r\n\t\r\n\tstd::ostringstream outstr;\r\n\toutstr.precision(floatPrecision);\r\n\toutstr << std::fixed << (lowestVar-highlowDiff/2);\r\n\tsf::Text lowNumText(outstr.str(),font);\r\n\tbounds = lowNumText.getLocalBounds();\r\n\tlowNumText.setOrigin(bounds.width,bounds.height);\r\n\tlowNumText.setScale(textScale, textScale);\r\n\tlowNumText.setPosition((width/1.85)-(width/2)+(width/8)/2-textScale*30,height-(height/6)-textScale*10);\r\n\toutstr.str(\"\");\r\n\t\r\n\ttexts.push_back(lowNumText);\r\n\t\r\n\toutstr << std::fixed << (highestVar+highlowDiff/2);\r\n\tsf::Text highNumText(outstr.str(),font);\r\n\tbounds = highNumText.getLocalBounds();\r\n\thighNumText.setOrigin(bounds.width,0);\r\n\thighNumText.setScale(textScale, textScale);\r\n\thighNumText.setPosition((width/1.85)-(width/2)+(width/8)/2-bounds.height/2,height-(height-(height/5.5)+(height/6))+textScale*10);\r\n\t\r\n\ttexts.push_back(highNumText);\r\n\t\r\n\tstd::string dateStr = std::to_string(firstDate.year)+\"/\"+std::to_string(firstDate.month)+\"/\"+std::to_string(firstDate.day);\r\n\tsf::Text lowDateText(dateStr,font);\r\n\tbounds = lowDateText.getLocalBounds();\r\n\tlowDateText.setOrigin(0,0);\r\n\tlowDateText.setScale(textScale, textScale);\r\n\tlowDateText.setPosition((width/1.85)-(width/2)+(width/8)/2,height-(height/6)+textScale*10);\r\n\t\r\n\ttexts.push_back(lowDateText);\r\n\t\r\n\tdateStr = std::to_string(lastDate.year)+\"/\"+std::to_string(lastDate.month)+\"/\"+std::to_string(lastDate.day);\r\n\tsf::Text highDateText(dateStr,font);\r\n\tbounds = highDateText.getLocalBounds();\r\n\thighDateText.setOrigin(bounds.width,0);\r\n\thighDateText.setScale(textScale, textScale);\r\n\thighDateText.setPosition(width/1.85+(width-(width/8))/2,height-(height/6)+textScale*10);\r\n\t\r\n\ttexts.push_back(highDateText);\r\n\t\r\n\tfor(int i = 0; i < texts.size(); i++)\r\n\t{\r\n\t\ttexts[i].setFillColor(sf::Color(100, 150, 255));\r\n\t}\r\n\t//drawing over\r\n\t\r\n\t//drawing the graph now\r\n\t\r\n\tstd::vector<sf::CircleShape> circles;\r\n\t\r\n\tfloat topStart = height-(height-(height/5.5)+(height/6));\r\n\tfloat verticalHeight = height-(height/5.5);\r\n\tfloat pixelPerOne = verticalHeight/((highestVar+highlowDiff/2)-(lowestVar-highlowDiff/2));\r\n\tfloat leftStart = (width/1.85)-(width/2)+(width/8)/2;\r\n\tfloat horizontalHeight = width-(width/8);\r\n\tfloat pixelPerOneDate = horizontalHeight/dateSpanDays;\r\n\t\r\n\tfloat lastX = 0;\r\n\tfloat lastY = 0;\r\n\t\r\n\tfor(DataValues datapoint : data)\r\n\t{\r\n\t\tsf::CircleShape circle;\r\n\t\tcircle.setRadius(statsPointRadius);\r\n\t\tcircle.setOrigin(statsPointRadius,statsPointRadius);\r\n\t\tfloat x = leftStart+(dateSpanDays-(lastDate.ToDays()-datapoint.date.ToDays()))*pixelPerOneDate;\r\n\t\tfloat y = topStart+((highestVar+highlowDiff/2)-datapoint.value)*pixelPerOne;\r\n\t\tcircle.setPosition(x,y);\r\n\t\tcircles.push_back(circle);\r\n\t\tif(lastX!=0 || lastY!=0)\r\n\t\t{\r\n\t\t\tfloat triangleWidth = x-lastX;\r\n\t\t\tfloat triangleHeight = y-lastY;\r\n\t\t\tfloat triangleBigSide = std::sqrt(std::pow(triangleWidth,2)+std::pow(triangleHeight,2));\r\n\t\t\tfloat angle = std::atan2(triangleWidth,-triangleHeight)-M_PI/2;\r\n\t\t\t\r\n\t\t\tsf::RectangleShape graphLine(sf::Vector2f(triangleBigSide, lineWidth));\r\n\t\t\tgraphLine.setOrigin(lineWidth/2,lineWidth/2);\r\n\t\t\tgraphLine.setPosition(lastX,lastY);\r\n\t\t\tgraphLine.setRotation(angle*(180/M_PI));\r\n\t\t\t\r\n\t\t\tshapes.push_back(graphLine);\r\n\t\t}\r\n\t\tlastX = x;\r\n\t\tlastY = y;\r\n\t}\r\n\t\r\n\tfor(int i = 0; i < circles.size(); i++)\r\n\t{\r\n\t\tcircles[i].setFillColor(sf::Color(100, 150, 255));\r\n\t}\r\n\t\r\n\tfor(int i = 0; i < shapes.size(); i++)\r\n\t{\r\n\t\tshapes[i].setFillColor(sf::Color(50, 100, 250));\r\n\t}\r\n\t\r\n\t//drawing the graph ends here\r\n\r\n    while(window.isOpen())\r\n    {\r\n        sf::Event event;\r\n        while(window.pollEvent(event))\r\n        {\r\n            if(event.type == sf::Event::Closed)\r\n            {\r\n                window.close();\r\n            }\r\n        }\r\n\r\n        window.clear();\r\n\t\tfor(sf::CircleShape circlei : circles)\r\n\t\t{\r\n\t\t\twindow.draw(circlei);\r\n\t\t}\r\n        for(sf::RectangleShape rectanglei : shapes)\r\n\t\t{\r\n\t\t\twindow.draw(rectanglei);\r\n\t\t}\r\n\t\tfor(sf::Text texti : texts)\r\n\t\t{\r\n\t\t\twindow.draw(texti);\r\n\t\t}\r\n        window.display();\r\n    }\r\n}\r\n\r\nvoid calculateStats(std::string datapath, std::string searchstr)\r\n{\r\n\tstd::vector<DataValues> data;\r\n\t\r\n\treadfile(datapath, data);\r\n\t\r\n\tstd::cout << std::endl << std::endl;\r\n\t\r\n\tstd::vector<DataValues> varVec;\r\n\tdouble averageVariable = 0;\r\n\t\r\n\tfor(int i = 0; i < data.size(); i++)\r\n\t{\r\n\t\tstd::cout << data[i].name << \" (\" << data[i].date.day << \"): \" << data[i].value << std::endl;\r\n\t\tif(data[i].name.find(searchstr)!=std::string::npos)\r\n\t\t{\r\n\t\t\taverageVariable+=data[i].value;\r\n\t\t\tvarVec.push_back(data[i]);\r\n\t\t}\r\n\t}\r\n\t\r\n\tif(varVec.size()==0)\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\t\r\n\taverageVariable/=varVec.size();\r\n\t\r\n\tdouble sStandardDev = 0;\r\n\tfor(int i = 0; i < varVec.size(); i++)\r\n\t{\r\n\t\tsStandardDev+=pow(averageVariable-varVec[i].value,2);\r\n\t}\r\n\tsStandardDev = sqrt(sStandardDev/(varVec.size()-1));\r\n\t\r\n\tdouble sdStandardDev = sStandardDev/(sqrt(varVec.size()));\r\n\t\r\n\tdouble tvalue = invCommulDistribution(varVec.size()-1,0.975);\r\n\tdouble marginOfError = tvalue*sdStandardDev;\r\n\t\r\n\tstd::cout << std::endl;\r\n\tstd::cout << \"Average variable: \" << averageVariable << std::endl;\r\n\tstd::cout << \"Sample standard deviation: \" << sStandardDev << std::endl;\r\n\tstd::cout << \"Sampling distribution standard deviation: \" << sdStandardDev << std::endl;\r\n\tstd::cout << \"T Value for 95%, \" << varVec.size()-1 << \" df: \" << tvalue << std::endl;\r\n\tstd::cout << \"Margin of error: \" << marginOfError << std::endl;\r\n\t\r\n\tstd::cout << \"\\nReal value between \" << averageVariable-marginOfError << \" and \" << averageVariable+marginOfError << std::endl;\r\n\t\r\n\twindowFunc(640,480,varVec);\r\n}\r\n\r\nint main()\r\n{\r\n\tstd::string datapath;\r\n\tstd::string searchstr;\r\n\r\n\tstd::cout << \"path to data: \" << std::endl;\r\n\tgetline(std::cin, datapath);\r\n\t\r\n\tstd::cout << \"variable name: \" << std::endl;\r\n\tgetline(std::cin, searchstr);\r\n\twhile(true)\r\n\t{\r\n\t\tcalculateStats(datapath, searchstr);\r\n\t\t\r\n\t\tstd::string userAction;\r\n\t\t\r\n\t\tstd::cout << \"\\n\\nPress enter to quit\" << \"\\nType path to change path\" << \"\\nType var to change the variable\" << \"\\nType update to run with same settings\\n\";\r\n\t\tgetline(std::cin, userAction);\r\n\t\tif(userAction==\"path\")\r\n\t\t{\r\n\t\t\tstd::cout << \"\\nnew path to data: \" << std::endl;\r\n\t\t\tgetline(std::cin, datapath);\r\n\t\t}\r\n\t\telse if(userAction==\"var\")\r\n\t\t{\r\n\t\t\tstd::cout << \"\\nnew variable name: \" << std::endl;\r\n\t\t\tgetline(std::cin, searchstr);\r\n\t\t}\r\n\t\telse if(userAction==\"update\")\r\n\t\t{\r\n\t\t} else\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "e6170a8f6696b243ae9ad329cab1702e62ecc467", "size": 10943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Xzyaihni/statisticsthing", "max_stars_repo_head_hexsha": "f40d8aa10af8d7470c4deea2bde147bd71b7c063", "max_stars_repo_licenses": ["MIT"], "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": "Xzyaihni/statisticsthing", "max_issues_repo_head_hexsha": "f40d8aa10af8d7470c4deea2bde147bd71b7c063", "max_issues_repo_licenses": ["MIT"], "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": "Xzyaihni/statisticsthing", "max_forks_repo_head_hexsha": "f40d8aa10af8d7470c4deea2bde147bd71b7c063", "max_forks_repo_licenses": ["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.8174386921, "max_line_length": 160, "alphanum_fraction": 0.6237777575, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.575507738296957}}
{"text": "#include <iostream>\n#include <NTL/ZZ.h>\n#include <fstream>\n\nuint64_t msb(uint64_t n) {\n    if (n == 0)\n        return 0;\n\n    uint64_t tmp;\n    tmp = n >> (uint) 1;\n\n    uint64_t mask = 1;\n    while (tmp != 0) {\n        tmp >>= (uint) 1;\n        mask <<= (uint) 1;\n    }\n\n    return mask;\n}\n\nNTL::ZZ fibonacci(uint64_t n) {\n    NTL::ZZ V_l;\n    V_l = 2;\n    NTL::ZZ V_h;\n    V_h = 1;\n\n    NTL::ZZ Q_l;\n    Q_l = 1;\n    NTL::ZZ Q_h;\n    Q_h = 1;\n\n    uint64_t mask = msb(n);\n    while (mask != 0) {\n        Q_l = Q_l * Q_h;\n        if (n & mask) {\n            Q_h = -Q_l;\n            V_l = V_h * V_l - Q_l;\n            V_h = V_h * V_h - 2 * Q_h;\n        }\n        else {\n            Q_h = Q_l;\n            V_h = V_h * V_l - Q_l;\n            V_l = V_l * V_l - 2 * Q_h;\n        }\n\n        mask >>= (uint) 1;\n    }\n\n    return (2 * V_h - V_l) / 5;\n}\n\nint main() {\n    std::ofstream outfile(\"case2_output.txt\", std::ios::app);\n    std::ifstream infile(\"case2_input.txt\");\n\n    long k;\n    while (infile >> k) {\n        std::cout << k << std::endl;\n\n        NTL::ZZ x;\n        x = NTL::power2_ZZ(k-1)-1;\n        NTL::ZZ y;\n        y = fibonacci(k+1);\n        NTL::ZZ res;\n        res = NTL::GCD(x, y);\n\n        outfile << k << \" \" << res << std::endl;\n\n        std::cout << res << std::endl;\n        std::cout << std::endl;\n    }\n\n    infile.close();\n    outfile.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "80a9291531b086a80593f4a5aee1ac35fd7f6ee8", "size": 1383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "even_primes/case2.cpp", "max_stars_repo_name": "okrcma/pseudoprimes", "max_stars_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "even_primes/case2.cpp", "max_issues_repo_name": "okrcma/pseudoprimes", "max_issues_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "even_primes/case2.cpp", "max_forks_repo_name": "okrcma/pseudoprimes", "max_forks_repo_head_hexsha": "a700c3dd2d16e11bb460314be7683828411e0458", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7307692308, "max_line_length": 61, "alphanum_fraction": 0.4295010846, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5754923545600433}}
{"text": "// This file is part of PolyMPC, a lightweight C++ template library\n// for real-time nonlinear optimization and optimal control.\n//\n// Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch>\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#ifndef BFGS_HPP\n#define BFGS_HPP\n\n#include <Eigen/Dense>\n#include <limits>\n\n/** Damped BFGS update\n * Implements \"Procedure 18.2 Damped BFGS updating for SQP\" form Numerical Optimization by Nocedal.\n *\n * @param[in,out]   B hessian matrix, is updated by this function\n * @param[in]       s step vector (x - x_prev)\n * @param[in]       y gradient change (grad - grad_prev)\n */\ntemplate <typename Mat, typename Vec>\nvoid BFGS_update(Eigen::MatrixBase<Mat>& B, const Eigen::MatrixBase<Vec>& s, const Eigen::MatrixBase<Vec>& y)\n{\n    using Scalar = typename Mat::Scalar;\n    Scalar sy, sr, sBs;\n    typename Vec::PlainObject Bs, r;\n\n    Bs.noalias() = B * s;\n    sBs = s.dot(Bs);\n    sy = s.dot(y);\n\n    if (sy < 0.2 * sBs) {\n        // damped update to enforce positive definite B\n        Scalar theta;\n        theta = 0.8 * sBs / (sBs - sy);\n        r.noalias() = theta * y + (1 - theta) * Bs;\n        sr = theta * sy + (1 - theta) * sBs;\n    } else {\n        // unmodified BFGS\n        r = y;\n        sr = sy;\n    }\n\n    if (sr < std::numeric_limits<Scalar>::epsilon()) {\n        return;\n    }\n\n    B.noalias() += -Bs * Bs.transpose() / sBs;\n    B.noalias() += r * r.transpose() / sr;\n}\n\n#endif /* BFGS_HPP */\n", "meta": {"hexsha": "ac9e4751a90e6478cc8ca479dbed2a06f97be327", "size": 1603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polympc/src/solvers/bfgs.hpp", "max_stars_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_stars_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polympc/src/solvers/bfgs.hpp", "max_issues_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_issues_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polympc/src/solvers/bfgs.hpp", "max_forks_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_forks_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1454545455, "max_line_length": 109, "alphanum_fraction": 0.6150966937, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5753788915275859}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\n*                                                                               *\n*  The MIT License                                                              *\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 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 NON INFRINGEMENT. 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*  Author(s):                                                                   *\n*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/matrix.h>\n#include <Eigen/Eigenvalues>\n\nnamespace cinolib\n{\n\n// http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html\n//\nCINO_INLINE\nvoid eigen_decomposition_2x2(const double   a00,\n                             const double   a01,\n                             const double   a10,\n                             const double   a11,\n                                   vec2d  & v_min, // eigenvectors\n                                   vec2d  & v_max,\n                                   double & min,   // eigenvalues\n                                   double & max)\n{\n    eigenvalues_2x2(a00,a01,a10,a11,min,max);\n\n    if(std::fabs(a10)>1e-5)\n    {\n        v_max = vec2d(max-a11,a10);\n        v_min = vec2d(min-a11,a10);\n    }\n    else if(std::fabs(a01)>1e-5)\n    {\n        v_max = vec2d(a01,max-a00);\n        v_min = vec2d(a01,min-a00);\n    }\n    else\n    {\n        v_max = (a00>=a11) ? vec2d(1,0) : vec2d(0,1);\n        v_min = (a00>=a11) ? vec2d(0,1) : vec2d(1,0);\n    }\n\n    v_max.normalize();\n    v_min.normalize();\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n// http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html\n//\nCINO_INLINE\nvoid eigenvalues_2x2(const double   a00,\n                     const double   a01,\n                     const double   a10,\n                     const double   a11,\n                           double & min,\n                           double & max)\n{\n    double T = a00 + a11; // trace\n    double D = determinant_2x2(a00,a01,a10,a11);\n\n    min = T/2.0 - sqrt(T*T/4.0-D);\n    max = T/2.0 + sqrt(T*T/4.0-D);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid eigenvectors_2x2(const double   a00,\n                      const double   a01,\n                      const double   a10,\n                      const double   a11,\n                            vec2d  & v_min,\n                            vec2d  & v_max)\n{\n    double min, max;\n    eigen_decomposition_2x2(a00, a01, a10, a11, v_min, v_max, min, max);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\ndouble determinant_2x2(const double a00, const double a01, const double a10, const double a11)\n{\n    return ((a00*a11) - (a10*a01));\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\ndouble determinant_2x2(const vec2d a0, const vec2d a1)\n{\n    return determinant_2x2(a0[0], a0[1], a1[0], a1[1]);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid eigen_decomposition_3x3(const double   a[3][3],\n                                   vec3d  & v_min, // eigenvectors\n                                   vec3d  & v_mid,\n                                   vec3d  & v_max,\n                                   double & min,   // eigenvalues\n                                   double & mid,\n                                   double & max)\n{\n    eigen_decomposition_3x3(a[0][0], a[0][1], a[0][2],\n                            a[1][0], a[1][1], a[1][2],\n                            a[2][0], a[2][1], a[2][2],\n                            v_min, v_mid, v_max,\n                            min, mid, max);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid eigen_decomposition_3x3(const double   a00,\n                             const double   a01,\n                             const double   a02,\n                             const double   a10,\n                             const double   a11,\n                             const double   a12,\n                             const double   a20,\n                             const double   a21,\n                             const double   a22,\n                                   vec3d  & v_min, // eigenvectors\n                                   vec3d  & v_mid,\n                                   vec3d  & v_max,\n                                   double & min,   // eigenvalues\n                                   double & mid,\n                                   double & max)\n{\n    Eigen::Matrix3d m;\n    m << a00, a01, a02,\n         a10, a11, a12,\n         a20, a21, a22;\n\n    bool symmetric = (a10==a01) && (a20==a02) && (a21==a12);\n\n    if(symmetric)\n    {\n        // eigen decomposition for self-adjoint matrices\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(m);\n        assert(eig.info() == Eigen::Success);\n\n        v_min = vec3d(eig.eigenvectors()(0,0), eig.eigenvectors()(1,0), eig.eigenvectors()(2,0));\n        v_mid = vec3d(eig.eigenvectors()(0,1), eig.eigenvectors()(1,1), eig.eigenvectors()(2,1));\n        v_max = vec3d(eig.eigenvectors()(0,2), eig.eigenvectors()(1,2), eig.eigenvectors()(2,2));\n\n        min = eig.eigenvalues()[0];\n        mid = eig.eigenvalues()[1];\n        max = eig.eigenvalues()[2];\n    }\n    else\n    {\n        // eigen decomposition for general matrices\n        Eigen::EigenSolver<Eigen::Matrix3d> eig(m);\n        assert(eig.info() == Eigen::Success);\n\n        // WARNING: I am taking only the real part!\n        v_min = vec3d(eig.eigenvectors()(0,0).real(), eig.eigenvectors()(1,0).real(), eig.eigenvectors()(2,0).real());\n        v_mid = vec3d(eig.eigenvectors()(0,1).real(), eig.eigenvectors()(1,1).real(), eig.eigenvectors()(2,1).real());\n        v_max = vec3d(eig.eigenvectors()(0,2).real(), eig.eigenvectors()(1,2).real(), eig.eigenvectors()(2,2).real());\n\n        // WARNING: I am taking only the real part!\n        min = eig.eigenvalues()[0].real();\n        mid = eig.eigenvalues()[1].real();\n        max = eig.eigenvalues()[2].real();\n    }\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid eigenvalues_3x3(const double   a00,\n                     const double   a01,\n                     const double   a02,\n                     const double   a10,\n                     const double   a11,\n                     const double   a12,\n                     const double   a20,\n                     const double   a21,\n                     const double   a22,\n                           double & min,\n                           double & mid,\n                           double & max)\n{\n    vec3d v_min, v_mid, v_max;\n    eigen_decomposition_3x3(a00, a01, a02, a10, a11, a12, a20, a21, a22, v_min, v_mid, v_max, min, mid, max);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid eigenvectors_3x3(const double   a00,\n                      const double   a01,\n                      const double   a02,\n                      const double   a10,\n                      const double   a11,\n                      const double   a12,\n                      const double   a20,\n                      const double   a21,\n                      const double   a22,\n                            vec3d  & v_min,\n                            vec3d  & v_mid,\n                            vec3d  & v_max)\n{\n    double min, mid, max;\n    eigen_decomposition_3x3(a00, a01, a02, a10, a11, a12, a20, a21, a22, v_min, v_mid, v_max, min, mid, max);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\ndouble determinant_3x3(const double a00, const double a01, const double a02,\n                       const double a10, const double a11, const double a12,\n                       const double a20, const double a21, const double a22)\n{\n    return a00 * determinant_2x2(a11, a12, a21, a22) -\n           a01 * determinant_2x2(a10, a12, a20, a22) +\n           a02 * determinant_2x2(a10, a11, a20, a21);\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid from_std_3x3_to_Eigen_3x3(const double stdM[3][3], Eigen::Matrix3d & eigenM)\n{\n    eigenM.coeffRef(0,0) = stdM[0][0];  eigenM.coeffRef(0,1) = stdM[0][1];  eigenM.coeffRef(0,2) = stdM[0][2];\n    eigenM.coeffRef(1,0) = stdM[1][0];  eigenM.coeffRef(1,1) = stdM[1][1];  eigenM.coeffRef(1,2) = stdM[1][2];\n    eigenM.coeffRef(2,0) = stdM[2][0];  eigenM.coeffRef(2,1) = stdM[2][1];  eigenM.coeffRef(2,2) = stdM[2][2];\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid from_eigen_3x3_to_std_3x3(const Eigen::Matrix3d & eigenM, double stdM[3][3])\n{\n    stdM[0][0] = eigenM.coeffRef(0,0);  stdM[0][1] = eigenM.coeffRef(0,1);  stdM[0][2] = eigenM.coeffRef(0,2);\n    stdM[1][0] = eigenM.coeffRef(1,0);  stdM[1][1] = eigenM.coeffRef(1,1);  stdM[1][2] = eigenM.coeffRef(1,2);\n    stdM[2][0] = eigenM.coeffRef(2,0);  stdM[2][1] = eigenM.coeffRef(2,1);  stdM[2][2] = eigenM.coeffRef(2,2);\n}\n\n}\n", "meta": {"hexsha": "67f86dbfca224be7f0a42c3d23ba8a4855ec1298", "size": 11479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/matrix.cpp", "max_stars_repo_name": "bbrrck/cinolib", "max_stars_repo_head_hexsha": "c7cceefd041646e1e1113339e681e212a9bba7e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-22T00:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-22T00:23:45.000Z", "max_issues_repo_path": "include/cinolib/matrix.cpp", "max_issues_repo_name": "snowfox1939/cinolib", "max_issues_repo_head_hexsha": "6017d9dd7461e7008df8198563d63526db3ed86a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cinolib/matrix.cpp", "max_forks_repo_name": "snowfox1939/cinolib", "max_forks_repo_head_hexsha": "6017d9dd7461e7008df8198563d63526db3ed86a", "max_forks_repo_licenses": ["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.8941605839, "max_line_length": 118, "alphanum_fraction": 0.4246014461, "num_tokens": 2789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629214, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5753788769775242}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2019-2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef NYARUGA_UTIL_PARTIAL_DIFF_HPP\n#define NYARUGA_UTIL_PARTIAL_DIFF_HPP\n\n#pragma once\n\n#include <concepts>\n#include <type_traits>\n#include <nyaruga_util/diff.hpp>\n#include <nyaruga_util/bind_select_arg_replace.hpp>\n#include <boost/hana/functional/arg.hpp>\n\nnamespace nyaruga {\n\nnamespace util {\n\nnamespace hana = boost::hana;\n\n// Partial differentiation\ntemplate <std::size_t count, typename NumType = num_t, typename F>\nconstexpr auto partial_diff(F && f) noexcept\n{\n   return [f](auto&& ... args) noexcept -> NumType\n   {\n      return diff<NumType>(bind_select_arg_replace<count>(std::forward<decltype(f)>(f), args...))\n         (hana::arg<count>(std::forward<decltype(args)>(args)...));\n   };\n}\n\n} // namespace nyaruga::util\n\n/* usage\n#include <iostream>\n#include <nyaruga_util/partial_diff.hpp>\n\nint main()\n{\n   auto lambda = [](auto ... a) { return static_cast<nyaruga::util::num_t>((a * ... )); };\n\n   std::cout << std::setprecision(18) << nyaruga::util::partial_diff<1>(lambda)(nyaruga::util::num_t(2), 5., 6.);\n}\n*/\n\n#endif // #ifndef NYARUGA_UTIL_PARTIAL_DIFF_HPP", "meta": {"hexsha": "920630d272ef15fc9d20001de4413d37a8bd8481", "size": 1282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/partial_diff.hpp", "max_stars_repo_name": "alphya/nyaruga_util", "max_stars_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nyaruga_util/partial_diff.hpp", "max_issues_repo_name": "alphya/nyaruga_util", "max_issues_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nyaruga_util/partial_diff.hpp", "max_forks_repo_name": "alphya/nyaruga_util", "max_forks_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6538461538, "max_line_length": 113, "alphanum_fraction": 0.6996879875, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5753788738091998}}
{"text": "/*\n * Copyright (c) 2019 Nobuyuki Umetani\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <chrono>\n#include <Eigen/Core>\n#if defined(_WIN32) // windows\n#  define NOMINMAX   // to remove min,max macro\n#  include <windows.h>  // should put before glfw3.h\n#endif\n#define GL_SILENCE_DEPRECATION\n#include <GLFW/glfw3.h>\n\n#include \"delfem2/mshuni.h\"\n#include \"delfem2/dtri2_v2dtri.h\"\n#include \"delfem2/dtri.h\"\n#include \"delfem2/eigen/ls_dense.h\"\n#include \"delfem2/eigen/ls_sparse.h\"\n#include \"delfem2/eigen/ls_ilu_sparse.h\"\n#include \"delfem2/lsitrsol.h\"\n#include \"delfem2/femsolidlinear.h\"\n#include \"delfem2/glfw/viewer3.h\"\n#include \"delfem2/glfw/util.h\"\n#include \"delfem2/opengl/old/mshuni.h\"\n\n\nnamespace dfm2 = delfem2;\n\nvoid MakeMesh(\n    std::vector<double>& aXY1,\n    std::vector<unsigned int>& aTri1,\n    std::vector<int>& aBCFlag,\n    unsigned int ndim)\n{\n  std::vector< std::vector<double> > aaXY;\n  const double len = 1.0;\n  {\n    aaXY.resize(1);\n    aaXY[0].push_back(-len); aaXY[0].push_back(-len);\n    aaXY[0].push_back(-len); aaXY[0].push_back(+len);\n    aaXY[0].push_back(+len); aaXY[0].push_back(+len);\n    aaXY[0].push_back(+len); aaXY[0].push_back(-len);\n  }\n  std::vector<delfem2::CDynPntSur> aPo2D;\n  std::vector<delfem2::CDynTri> aETri;\n  std::vector<delfem2::CVec2d> aVec2;\n  delfem2::GenMesh(aPo2D,aETri,aVec2,\n                   aaXY,0.05,0.05);\n  MeshTri2D_Export(\n      aXY1,aTri1,\n      aVec2,aETri);\n  const unsigned int np = aXY1.size()/2;\n  aBCFlag.assign(np*ndim, 0);\n  for(unsigned int ip=0;ip<np;++ip){\n//    const double px = aXY1[ip*2+0];\n    const double py = aXY1[ip*2+1];\n    if( fabs(py-len) > 0.0001 ){ continue; }\n    for(unsigned int idim=0;idim<ndim;++idim) {\n      aBCFlag[ip * 2 + idim] = 1;\n    }\n  }\n  std::cout<<\"  ntri;\"<<aTri1.size()/3<<\"  nXY:\"<<aXY1.size()/2<<std::endl;\n}\n\nvoid Solve1(\n    std::vector<double>& aVal,\n    const std::vector<double>& aXY1,\n    const std::vector<unsigned int>& aTri1,\n    const std::vector<int>& aBCFlag)\n{\n  const unsigned int np = aXY1.size()/2;\n  const unsigned int nDoF = np*2;\n  // -----------\n  std::vector<unsigned int> psup_ind0, psup0;\n  dfm2::JArray_PSuP_MeshElem(\n      psup_ind0, psup0,\n      aTri1.data(), aTri1.size()/3, 3,\n      aXY1.size()/2);\n  // -------------\n  delfem2::CMatrixSparseBlock<Eigen::Matrix2d,Eigen::aligned_allocator<Eigen::Matrix2d>> mA;\n  mA.Initialize(np);\n  mA.SetPattern(psup_ind0.data(), psup_ind0.size(), psup0.data(), psup0.size());\n  // ----------------------\n  double myu = 10.0;\n  double lambda = 10.0;\n  double rho = 1.0;\n  double g_x = 0.0;\n  double g_y = -3.0;\n  mA.setZero();\n  Eigen::VectorXd vec_b(nDoF);\n  vec_b.setZero();\n  dfm2::MergeLinSys_SolidLinear_Static_MeshTri2D(\n      mA,vec_b.data(),\n      myu,lambda,rho,g_x,g_y,\n      aXY1.data(), aXY1.size()/2,\n      aTri1.data(), aTri1.size()/3,\n      aVal.data());\n  SetFixedBC_Dia(mA, aBCFlag.data(), 1.f);\n  SetFixedBC_Col(mA, aBCFlag.data());\n  SetFixedBC_Row(mA, aBCFlag.data());\n  delfem2::setZero_Flag(vec_b, aBCFlag,0);\n  // ---------------\n  Eigen::VectorXd vec_x(vec_b.size());\n  {\n    double conv_ratio = 1.0e-6;\n    int iteration = 1000;\n    const std::size_t n = vec_b.size();\n    Eigen::VectorXd tmp0(n), tmp1(n);\n    std::vector<double> aConv = delfem2::Solve_CG(\n        vec_b, vec_x, tmp0, tmp1,\n        conv_ratio, iteration, mA);\n    std::cout << aConv.size() << std::endl;\n  }\n//  SolveLinSys_PCG(mat_A,vec_b,vec_x,ilu_A, conv_ratio,iteration);\n  // --------------\n  {\n    delfem2::CILU_SparseBlock<Eigen::Matrix2d,Eigen::aligned_allocator<Eigen::Matrix2d>> ilu;\n    delfem2::ILU_SetPattern0(ilu,mA);\n    delfem2::ILU_CopyValue(ilu,mA);\n    delfem2::ILU_Decompose(ilu);\n    Eigen::VectorXd vecX1(vec_b.size());\n  }\n  // --------------\n  delfem2::XPlusAY(aVal,\n      aBCFlag,\n      1.0,vec_x);\n}\n\nint main()\n{\n  std::vector<unsigned int> aTri1;\n  std::vector<double> aXY1;\n  std::vector<int> aBCFlag; // master slave flag\n  MakeMesh(\n      aXY1, aTri1, aBCFlag,\n      2);\n  // ---\n  std::vector<double> aVal;\n  {\n    const unsigned int np = aXY1.size()/2;\n    aVal.assign(np * 2, 0.0);\n    Solve1(aVal,aXY1,aTri1,aBCFlag);\n  }\n  // --------\n  dfm2::glfw::CViewer3 viewer(1.5);\n  dfm2::glfw::InitGLOld();\n  viewer.OpenWindow();\n  // ---------\n  while(!::glfwWindowShouldClose(viewer.window)){\n    viewer.DrawBegin_oldGL();\n    delfem2::opengl::DrawMeshTri2D_FaceDisp2D(\n        aXY1.data(), aXY1.size()/2,\n        aTri1.data(), aTri1.size()/3,\n        aVal.data(), 2);\n    viewer.SwapBuffers();\n    glfwPollEvents();\n    viewer.ExitIfClosed();\n  }\n}\n", "meta": {"hexsha": "7d96120112b86c90be0c1d99d4bee3c7acad0c78", "size": 4695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples_oldgl_glfw_eigen/02_FemSolidLinear2/main.cpp", "max_stars_repo_name": "mmer547/delfem2", "max_stars_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T17:03:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T17:03:36.000Z", "max_issues_repo_path": "examples_oldgl_glfw_eigen/02_FemSolidLinear2/main.cpp", "max_issues_repo_name": "mmer547/delfem2", "max_issues_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples_oldgl_glfw_eigen/02_FemSolidLinear2/main.cpp", "max_forks_repo_name": "mmer547/delfem2", "max_forks_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2831325301, "max_line_length": 93, "alphanum_fraction": 0.6300319489, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920068519376, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.575372786300108}}
{"text": "#include <iostream>\n#include <cmath>\nusing namespace std; \n#include <Eigen/Core>\n#include <Eigen/Geometry>\n \n// 李群李代数 库 \n#include \"sophus/so3.hpp\"\n#include \"sophus/se3.hpp\"\n\n#include<stdio.h>\n#include\"mex.h\"\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){\n    // nlhs represent the number of parameters of the output\n    // plhs is a array of the mxarray pointers, each pointing to the output\n    // nrhs represents the number of parameters of the input\n    // prhs is a array of the mxarray pointers, each pointing to the input\n\n    // prhs[0], 6x1 matrix\n    // prhs[1], Mx1 cell, each cell with NX3 points\n    // prhs[2], Mx1 cell, each cell with PXQ single matrix\n    // prhs[3], 1x2, or 1x3, or 1x4, or 1x5 matrix\n    // prhs[4], 3x3 matrix\n    // prhs[5], 1x2 matrix\n\n    if(nrhs < 1){\n        mexErrMsgIdAndTxt( \"euler2se3Mex:invalidNumInputs\", \"at least 1 input arguments required\");\n        return;\n    }\n\n    // get the euler transformation\n    const size_t *dimArrayOfSe3 = mxGetDimensions(prhs[0]);\n    size_t sizeRowsSe3 = *(dimArrayOfSe3 + 0);\n    size_t sizeColsSe3 = *(dimArrayOfSe3 + 1);\n    if(sizeRowsSe3 != 6 || sizeColsSe3 != 1){\n        mexErrMsgIdAndTxt( \"EdgeSE3ProjectDirectWithDirstortJacobian:invalidInputs\", \"the 1st param should be 6x1\");\n        return;\n    }\n    double *ptrSe3 = (double *)(mxGetPr(prhs[0]));\n    Eigen::Matrix<double, 6, 1> se3;\n    for(int i = 0; i < 6; i++){\n        se3(i, 0) = *(ptrSe3 + i);\n    }\n\n    Sophus::SE3<double> SE3 = Sophus::SE3<double>::exp(se3);\n    Eigen::Matrix<double, 4, 4> SE3Matrix = SE3.matrix();\n\n    // cout<<\"SE3 updated = \"<<endl<<SE3Matrix<<endl;\n\n    // the eulerTransform will be 4x4\n    size_t dimArrayOfEulerTransform[2] = { 4, 4 };\n    plhs[0] = mxCreateNumericArray(2, dimArrayOfEulerTransform, mxDOUBLE_CLASS, mxREAL);\n    double *ptrEulerTransform = (double *)mxGetData(plhs[0]);\n    for(int i = 0; i < 4; i++){\n        for(int j = 0; j < 4; j++){\n            ptrEulerTransform[i * 4 + j] = SE3Matrix(j, i);\n        }\n    }\n}", "meta": {"hexsha": "b260b12f834d066534b132c57b112cc7a0fac5d4", "size": 2043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/optimization/cpp/se32eulerMex.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/se32eulerMex.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/se32eulerMex.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": 34.05, "max_line_length": 116, "alphanum_fraction": 0.6343612335, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5753569607002209}}
{"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#include <Eigen/Core>\n#include <smooth/feedback/ocp.hpp>\n\ntemplate<typename T>\nusing X = Eigen::Vector<T, 2>;\n\ntemplate<typename T>\nusing U = Eigen::Vector<T, 1>;\n\ntemplate<typename T, std::size_t N>\nusing Vec = Eigen::Vector<T, N>;\n\n/// @brief Objective function\nstruct DITheta\n{\n  template<typename T>\n  T operator()(T, const X<T> &, const X<T> &, const Vec<T, 1> & q) const\n  {\n    return q.x();\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(1, 6);\n    ret.coeffRef(0, 5) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(6, 6);\n    return ret;\n  }\n};\n\nstruct DIDyn\n{\n  template<typename T>\n  smooth::Tangent<X<T>> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    return {x.y(), u.x()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(2, 4);\n    ret.coeffRef(0, 2) = 1;\n    ret.coeffRef(1, 3) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(4, 8);\n    return ret;\n  }\n};\n\nstruct DIIntegral\n{\n  template<typename T>\n  Vec<T, 1> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    return Vec<T, 1>{x.squaredNorm() + u.squaredNorm()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> & x, const U<double> & u) const\n  {\n    Eigen::SparseMatrix<double> ret(1, 4);\n    ret.coeffRef(0, 1) = 2 * x.x();\n    ret.coeffRef(0, 2) = 2 * x.y();\n    ret.coeffRef(0, 3) = 2 * u.x();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(4, 4);\n    ret.coeffRef(1, 1) = 2;\n    ret.coeffRef(2, 2) = 2;\n    ret.coeffRef(3, 3) = 2;\n    return ret;\n  }\n};\n\nstruct DICr\n{\n  template<typename T>\n  Vec<T, 2> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    return Vec<T, 2>{x.y(), u.x()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(2, 4);\n    ret.coeffRef(0, 2) = 1;\n    ret.coeffRef(1, 3) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(4, 8);\n    return ret;\n  }\n};\n\nstruct DICe\n{\n  template<typename T>\n  Vec<T, 5> operator()(T tf, const X<T> & x0, const X<T> & xf, const Vec<T, 1> &) const\n  {\n    Vec<T, 5> ret;\n    ret << tf, x0, xf;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(5, 6);\n    ret.coeffRef(0, 0) = 1;\n    ret.coeffRef(1, 1) = 1;\n    ret.coeffRef(2, 2) = 1;\n    ret.coeffRef(3, 3) = 1;\n    ret.coeffRef(4, 4) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(6, 30);\n    return ret;\n  }\n};\n\nusing OcpDI = smooth::feedback::OCP<X<double>, U<double>, DITheta, DIDyn, DIIntegral, DICr, DICe>;\n\ninline const OcpDI ocp_di{\n  .theta = DITheta{},\n  .f     = DIDyn{},\n  .g     = DIIntegral{},\n  .cr    = DICr{},\n  .crl   = Vec<double, 2>{{-0.5, -1}},\n  .cru   = Vec<double, 2>{{1.5, 1}},\n  .ce    = DICe{},\n  .cel   = Vec<double, 5>{{5, 1, 1, 0.1, 0}},\n  .ceu   = Vec<double, 5>{{5, 1, 1, 0.1, 0}},\n};\n", "meta": {"hexsha": "e9c5e3f45a83a40acc7c8901cffd10e5cee729b9", "size": 4911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/ocp_doubleintegrator.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ocp_doubleintegrator.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ocp_doubleintegrator.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4357541899, "max_line_length": 98, "alphanum_fraction": 0.6330686215, "num_tokens": 1535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5753569599708787}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include math.hpp directly!\"\n#endif\n\n#pragma once\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include \"matheval.hpp\"\n#if defined(__linux__)\n#include <fenv.h>\n#endif\n\nnamespace matheval {\n\nnamespace math {\n\n/// @brief Sign function\ntemplate <typename T>\nT sgn(T x) {\n    return (T{0} < x) - (x < T{0});\n}\n\n/// @brief isnan function with adjusted return type\ntemplate <typename T>\nT isnan(T x) {\n    return std::isnan(x);\n}\n\n/// @brief isinf function with adjusted return type\ntemplate <typename T>\nT isinf(T x) {\n    return std::isinf(x);\n}\n\n/// @brief Convert radians to degrees\ntemplate <typename T>\nT deg(T x) {\n    return x * boost::math::constants::radian<T>();\n}\n\n/// @brief Convert degrees to radians\ntemplate <typename T>\nT rad(T x) {\n    return x * boost::math::constants::degree<T>();\n}\n\n/// @brief acosinus\ntemplate <typename T>\nT acos(T x) {\n  if (std::fabs(x) > 1) {\n    throw matheval::acosInvalid{x};\n  }\n  return std::acos(x);\n}\n\n/// @brief cosinus\ntemplate <typename T>\nT cos(T x) {\n  if (std::isinf(x)) {\n    throw matheval::cosInvalid{};\n  }\n  return std::cos(x);\n}\n\n/// @brief inverse hyperbolic cosine\ntemplate <typename T>\nT acosh(T x) {\n  if (x < 1.0) {\n    throw matheval::acoshInvalid{x};\n  }\n  return std::acosh(x);\n}\n\n/// @brief asinus\ntemplate <typename T>\nT asin(T x) {\n  if (std::fabs(x) > 1) {\n    throw matheval::asinInvalid{x};\n  }\n  return std::asin(x);\n}\n\n/// @brief inverse hyperbolic tangent\ntemplate <typename T>\nT atanh(T x) {\n  const T abs_x = std::fabs(x);\n  if (abs_x > 1) {\n    throw matheval::atanhInvalid{x};\n  } else if (abs_x == 1.0) {\n    throw matheval::atanhDivideByZero{};\n  }\n  return std::atanh(x);\n}\n\n/// @brief unary plus\ntemplate <typename T>\nT plus(T x) {\n    return x;\n}\n\n/// @brief natural logarithm\ntemplate <typename T>\nT log(T x) {\n  if (x == 0.0) {\n    throw matheval::logDivideByZero{};\n  } else if (x < 0.0) {\n    throw matheval::logInvalid{x};\n  }\n  return std::log(x);\n}\n\n/// @brief log2\ntemplate <typename T>\nT log2(T x) {\n  if (x == 0.0) {\n    throw matheval::logDivideByZero{};\n  } else if (x < 0.0) {\n    throw matheval::logInvalid{x};\n  }\n  return std::log2(x);\n}\n\n/// @brief log10\ntemplate <typename T>\nT log10(T x) {\n  if (x == 0.0) {\n    throw matheval::logDivideByZero{};\n  } else if (x < 0.0) {\n    throw matheval::logInvalid{x};\n  }\n  return std::log10(x);\n}\n\n/// @brief sinus\ntemplate <typename T>\nT sin(T x) {\n  if (isinf(x)) {\n    throw matheval::sinInvalid{};\n  }\n  return std::sin(x);\n}\n\n/// @brief square root\ntemplate <typename T>\nT sqrt(T x) {\n  if (x < 0.0) {\n    throw matheval::sqrtInvalid{x};\n  }\n  return std::sqrt(x);\n}\n\n/// @brief tangens\ntemplate <typename T>\nT tan(T x) {\n  if (isinf(x)) {\n    throw matheval::tanInvalid{};\n  }\n  return std::tan(x);\n}\n\n/// @brief gamma\ntemplate <typename T>\nT tgamma(T x) {\n  if (x == 0) {\n    throw matheval::tgammaDivideByZero{};\n  } else if (x == -INFINITY) {\n    throw matheval::tgammaInvalid{x};\n  } else if (x < 0 && x == ceil(x)) {\n    throw matheval::tgammaInvalid{x};\n  }\n#if 0\n  int psigngam;\n  return lgamma_r(x, &psigngam);\n#else\n  return std::tgamma(x);\n#endif\n}\n\n/// @brief if/else function\ntemplate <typename T>\nT ifelse(T expr, T res_true, T res_false) {\n  return expr ? res_true : res_false;\n}\n\n/// @brief binary plus\ntemplate <typename T>\nT plus(T x, T y) {\n    return x + y;\n}\n\n/// @brief unary minus\ntemplate <typename T>\nT minus(T x) {\n    return -x;\n}\n\n/// @brief binary minus\ntemplate <typename T>\nT minus(T x, T y) {\n    return x - y;\n}\n\n/// @brief multiply\ntemplate <typename T>\nT multiplies(T x, T y) {\n    return x * y;\n}\n\n/// @brief divide\ntemplate <typename T>\nT divides(T x, T y) {\n  if (y == 0) {\n    throw matheval::divideByZero{};\n  }\n    return x / y;\n}\n\n/// @brief modulo\ntemplate <typename T>\nT fmod(T x, T y) {\n  if (y == 0) {\n    throw matheval::moduloByZero{};\n  }\n  if (isinf(x)) {\n    throw matheval::moduloWithInfinity{};\n  }\n  return std::fmod(x,y);\n}\n\n/// @brief power\ntemplate <typename T>\nT pow(T x, T y) {\n#if defined(__linux__)\n  errno = 0;\n  feclearexcept(FE_ALL_EXCEPT);\n  T res = std::pow(x,y);\n  if (fetestexcept(FE_INVALID)) {\n    throw matheval::powInvalid{};\n  } else if (fetestexcept(FE_DIVBYZERO)) {\n    throw matheval::powDivideByZero{};\n  } else if (fetestexcept(FE_OVERFLOW)) {\n    throw matheval::powOverflow{};\n  } else if (fetestexcept(FE_UNDERFLOW)) {\n    throw matheval::powUnderflow{};\n  }\n  return res;\n#elif defined(__APPLE__) && defined(__clang__)\n  if (y < 0) {\n    throw matheval::powDivideByZero{};\n  } else if (x < 0 &&\n\t     isfinite(y) &&\n\t     y != floor(y)) {\n    throw matheval::powInvalid{};\n  } else if (x == 0 && y < 0) {\n    throw matheval::powInvalid{};\n  }\n  return std::pow(x,y);\n#else\n#error unknown platform\n#endif\n}\n\n/// @brief unary not\ntemplate <typename T>\nT unary_not(T x) {\n    return !x;\n}\n\n/// @brief logical and\ntemplate <typename T>\nT logical_and(T x, T y) {\n    return x && y;\n}\n\n/// @brief logical or\ntemplate <typename T>\nT logical_or(T x, T y) {\n    return x || y;\n}\n\n/// @brief less\ntemplate <typename T>\nT less(T x, T y) {\n    return x < y;\n}\n\n/// @brief less equals\ntemplate <typename T>\nT less_equals(T x, T y) {\n    return x <= y;\n}\n\n/// @brief greater\ntemplate <typename T>\nT greater(T x, T y) {\n    return x > y;\n}\n\n/// @brief greater equals\ntemplate <typename T>\nT greater_equals(T x, T y) {\n    return x >= y;\n}\n\n/// @brief equals\ntemplate <typename T>\nT equals(T x, T y) {\n    return x == y;\n}\n\n/// @brief not equals\ntemplate <typename T>\nT not_equals(T x, T y) {\n    return x != y;\n}\n\n} // namespace math\n\n} // namespace matheval\n", "meta": {"hexsha": "476976c9e8101c7a1e9046bba2dd3145ff83ebaa", "size": 5636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math.hpp", "max_stars_repo_name": "doj/boost_matheval", "max_stars_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_stars_repo_licenses": ["BSL-1.0"], "max_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.hpp", "max_issues_repo_name": "doj/boost_matheval", "max_issues_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_issues_repo_licenses": ["BSL-1.0"], "max_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.hpp", "max_forks_repo_name": "doj/boost_matheval", "max_forks_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.6125, "max_line_length": 51, "alphanum_fraction": 0.6133782825, "num_tokens": 1800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5753569577288525}}
{"text": "#include \"bigssMathEigen.h\"\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\n#include <Eigen/Dense>\r\n\r\nvoid BIGSS::ax_xb(const Eigen::MatrixX4d &A, const Eigen::MatrixX4d &B, Eigen::Matrix4d &X)\r\n{\r\n  Eigen::Matrix3d mList, xtmp, mat;\r\n  Eigen::Vector3d rotMat;\r\n\r\n  Eigen::MatrixXd C;\r\n  Eigen::VectorXd d;\r\n\r\n  size_t nX = A.rows() / 4;\r\n\r\n  mat.setZero();\r\n  mList.setZero();\r\n  xtmp.setZero();\r\n\r\n  X.setIdentity();\r\n\r\n  C = Eigen::MatrixXd::Zero(3 * nX, 3);\r\n  d = Eigen::VectorXd::Zero(3 * nX);\r\n\r\n  for (size_t i = 0; i<nX; i++) {\r\n    Eigen::Matrix3d ablk = A.block(4 * i, 0, 3, 3);\r\n    Eigen::Matrix3d bblk = B.block(4 * i, 0, 3, 3);\r\n    std::cout << ablk << std::endl << std::endl;\r\n    Eigen::AngleAxisd arot, brot;\r\n    arot.fromRotationMatrix(ablk);\r\n    brot.fromRotationMatrix(bblk);\r\n\r\n    Eigen::Vector3d aax = arot.axis();\r\n    Eigen::Vector3d bax = brot.axis();\r\n\r\n    xtmp = bax * aax.transpose();\r\n\r\n    mList += brot.angle() * arot.angle() * xtmp;\r\n  }\r\n\r\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(mList, Eigen::ComputeFullU | Eigen::ComputeFullV);\r\n  Eigen::Vector3d sv = svd.singularValues();\r\n  Eigen::Matrix3d v = svd.matrixV();\r\n\r\n  mat(0, 0) = 1 / sv[0];\r\n  mat(1, 1) = 1 / sv[1];\r\n  mat(2, 2) = 1 / sv[2];\r\n\r\n  xtmp = v * mat * v.transpose() * mList.transpose();\r\n  std::cout << xtmp << std::endl;\r\n\r\n  Eigen::AngleAxisd xax;\r\n  xax.fromRotationMatrix(xtmp);\r\n\r\n  Eigen::Matrix3d I = Eigen::Matrix3d::Identity();\r\n  for (size_t i = 0; i<nX; i++) {\r\n    Eigen::MatrixXd dref = d.segment(3 * i, 3);\r\n\r\n    Eigen::MatrixXd ablk = A.block(4 * i, 0, 3, 3);\r\n    C.block(3 * i, 0, 3, 3) = I - ablk;\r\n    Eigen::VectorXd aref = A.block(4 * i, 3, 3, 1);\r\n    Eigen::VectorXd bblk = B.block(4 * i, 3, 3, 1);\r\n    Eigen::VectorXd cc = aref - xtmp * bblk;\r\n    d.segment(3 * i, 3) = cc;\r\n  }\r\n\r\n  Eigen::MatrixXd P = C.transpose() * C;\r\n  Eigen::Vector3d trans = P.inverse() * C.transpose() * d;\r\n\r\n  X.block<3, 3>(0, 0) = xtmp;\r\n  X.block<3, 1>(0, 3) = trans;\r\n}\r\n\r\nEigen::MatrixXd BIGSS::princomp(const Eigen::MatrixXd &X)\r\n{\r\n  Eigen::MatrixXd centered = X.rowwise() - X.colwise().mean();\r\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(centered, Eigen::ComputeThinV);\r\n  Eigen::MatrixXd Vt = svd.matrixV();\r\n\r\n  return Vt;\r\n}\r\n\r\nvoid BIGSS::fit3DLine(const Eigen::MatrixXd &points, Eigen::Vector3d &point, Eigen::Vector3d &vec)\r\n{\r\n  Eigen::MatrixXd W = princomp(points);\r\n  vec = W.col(0);\r\n  point = points.colwise().mean();\r\n}\r\n\r\nbool BIGSS::computeTransform(const Eigen::Matrix3Xd &ptsMoving, const Eigen::Matrix3Xd &ptsFixed, Eigen::Affine3d &T)\r\n{\r\n  T.setIdentity();\r\n\r\n  if (ptsMoving.cols() != ptsFixed.cols())\r\n    return false;\r\n\r\n  if (ptsMoving.cols() < 3)\r\n    return false;\r\n\r\n  Eigen::Matrix3Xd aBar = ptsMoving.colwise() - ptsMoving.rowwise().mean();\r\n  Eigen::Matrix3Xd bBar = ptsFixed.colwise() - ptsFixed.rowwise().mean();\r\n\r\n  Eigen::Matrix3d H = aBar * bBar.transpose();\r\n\r\n  double traceH = H.trace();\r\n\r\n  Eigen::Vector3d delta;\r\n  delta(0) = H(1, 2) - H(2, 1);\r\n  delta(1) = H(2, 0) - H(0, 2);\r\n  delta(2) = H(0, 1) - H(1, 0);\r\n\r\n  Eigen::Matrix4d G;\r\n  G(0, 0) = traceH;\r\n  G.block<1, 3>(0, 1) = delta.transpose();\r\n  G.block<3, 1>(1, 0) = delta;\r\n  G.block<3, 3>(1, 1) = H + H.transpose() - (traceH * Eigen::Matrix3d::Identity());\r\n\r\n  Eigen::EigenSolver<Eigen::Matrix4d> eig(G, true);\r\n  Eigen::Matrix4cd evecs = eig.eigenvectors();\r\n  Eigen::Vector4cd evals = eig.eigenvalues();\r\n  Eigen::Vector4d::Index idx;\r\n  //evals.maxCoeff(&idx);\r\n  evals.real().maxCoeff(&idx);\r\n  Eigen::Vector4cd ee = evecs.col(idx);\r\n  //Eigen::Vector4d evec = ee.cast<Eigen::Vector4d>();\r\n  //Eigen::Vector4d evec = evecs.col(idx).cast<Eigen::Vector4d>();\r\n\r\n  Eigen::Quaterniond quat(ee(0).real(), ee(1).real(), ee(2).real(), ee(3).real());\r\n  T = T.rotate(quat);\r\n  Eigen::Vector3d p = ptsFixed.rowwise().mean() - T * ptsMoving.rowwise().mean();\r\n  T = T.pretranslate(p);\r\n\r\n  return true;\r\n}\r\n\r\nbool BIGSS::computeCorrespondencelessTransform(Eigen::Matrix3Xd &ptsMoving, const Eigen::Matrix3Xd &ptsFixed, Eigen::Affine3d &T, Eigen::VectorXi &ordering)\r\n{\r\n  T.setIdentity();\r\n  Eigen::Affine3d guessT;\r\n  int nPts = ptsMoving.cols();\r\n\r\n  if (nPts != ptsFixed.cols())\r\n    return false;\r\n\r\n  if (nPts > 5)\r\n    return false;\r\n\r\n  // compute number of permutations\r\n  int nPerms = 1;\r\n  for (int i = 1; i < nPts; i++)\r\n    nPerms *= (i + 1);\r\n\r\n  // generate the permutations\r\n  Eigen::VectorXi indices;\r\n  indices.setLinSpaced(nPts, 0, nPts - 1);\r\n\r\n  Eigen::Matrix3Xd bestPts;\r\n\r\n  double maxError = std::numeric_limits<double>::max();\r\n  Eigen::VectorXd errors;\r\n  errors.setZero(nPerms);\r\n  int i = 0;\r\n  do// (int i = 0; i < nPerms; i++)\r\n  {\r\n    Eigen::Matrix3Xd newPts = ptsMoving;\r\n\r\n    // find the next permutation\r\n    //std::next_permutation(indices.data(), indices.data() + nPts);\r\n    for (int j = 0; j < nPts; j++)\r\n    {\r\n      newPts.col(indices(j)) = ptsMoving.col(j);\r\n    }\r\n\r\n    // compute the transform\r\n    computeTransform(newPts, ptsFixed, guessT);\r\n\r\n    // compute the error\r\n    Eigen::MatrixXd dt = guessT * newPts - ptsFixed;\r\n    Eigen::VectorXd res = dt.colwise().norm();\r\n    errors(i) = res.sum();\r\n    if (errors(i) < maxError)\r\n    {\r\n      ordering = indices;\r\n      maxError = errors(i);\r\n      bestPts = newPts;\r\n      T = guessT;\r\n    }\r\n    i++;\r\n  } while (std::next_permutation(indices.data(), indices.data() + nPts));\r\n\r\n  ptsMoving = bestPts;\r\n\r\n  return true;\r\n}\r\n\r\n", "meta": {"hexsha": "ee2e207c45ad75a17c791bdd3764d56104140cbb", "size": 5437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/bigssMath/bigssMathEigen.cpp", "max_stars_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_stars_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-11-16T08:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T11:08:55.000Z", "max_issues_repo_path": "lib/bigssMath/bigssMathEigen.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "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/bigssMath/bigssMathEigen.cpp", "max_forks_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_forks_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-16T08:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T08:17:42.000Z", "avg_line_length": 27.4595959596, "max_line_length": 157, "alphanum_fraction": 0.5966525658, "num_tokens": 1791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5750963389246245}}
{"text": "//============================================================================\n// Name        : generatetable.cpp\n// Author      : \n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <algorithm>\n#include <math.h>\n//#include <boost/lambda/bind.hpp>\n//#include <boost/lambda/lambda.hpp>\n#include <boost/spirit/home/phoenix.hpp>\n#include <boost/function.hpp>\n#include <boost/foreach.hpp>\n#include <eigen3/Eigen/Dense>\n#include <time.h>\n#include <vector>\n#include <map>\n#include <cstring>\n#include <signal.h>\n#include <limits>\n#include <boost/program_options.hpp>\n\n//using namespace boost::lambda;\nusing namespace boost::phoenix;\nusing namespace Eigen;\nnamespace po = boost::program_options;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::cerr;\nusing std::ostream;\nusing std::ofstream;\nusing std::fstream;\nusing std::map;\nusing std::max;\nusing std::numeric_limits;\nusing boost::result_of;\n\nnamespace bp = boost::phoenix;\n\n//boost::lambda::placeholder1_type X;\nactor<argument<0> > X;\n\n\nbool quitting = false;\n\nconst double pi = 3.141592653589793238462643383279502884197169399;\nvoid quit(int);\n\nint numberOfThreads=3;\n\nclass Uniform {\npublic:\n\tdouble width;\n\tUniform(double width): width(width){}\n\tinline double operator()(double x) const{\n\t\treturn 1/width;\n\t}\n\tdouble getIntBegin() const {\n\t\treturn -width/2;\n\t}\n\tdouble getIntEnd() const {\n\t\treturn width/2;\n\t}\n};\n\nclass Gaussian {\npublic:\n\tdouble mean;\n\tdouble var;\n\tdouble weight;\n\tGaussian(double var): mean(0), var(var), weight(1){}\n\tGaussian(double mean, double var): mean(mean),var(var), weight(1){}\n\tGaussian(double mean, double var, double weight): mean(mean),var(var), weight(weight){}\n\tinline double operator()(double x) const{\n\t\treturn 1/sqrt(2*pi*var)*exp(-(x-mean)*(x-mean)/(2*var));\n\t}\n\tvoid setMean(double mean) {this->mean=mean;}\n\n\tinline bool operator<(const Gaussian & other) const {\n\t\treturn mean<other.mean;\n\t}\n\tdouble getIntBegin() const {\n\t\treturn mean - 4 * sqrt(var); //integralBegin\n\t}\n\tdouble getIntEnd() const {\n\t\treturn mean + 4 * sqrt(var); //integralEnd\n\t}\n};\n\ntypedef map<double, vector<Gaussian> >::iterator tableIterator;\ntypedef vector<Gaussian>::iterator vectorIterator;\n\ninline double normal(double x,double mean, double var) {\n\treturn 1/sqrt(2*pi*var)*exp(-(x-mean)*(x-mean)/(2*var));\n}\n\ntemplate <class F>\ninline typename boost::result_of<F(double)>::type integrate(double from, double to, double increment, F const &f, typename boost::result_of<F(double)>::type accumulator = 0) {\n\tint N = (to-from)/increment;\n\tdouble x;\n\tint i;\n\ttypename boost::result_of<F(double)>::type perThreadAccumulator;\n\t#pragma omp parallel private(x,perThreadAccumulator,i) num_threads(numberOfThreads)\n\t{\n\t\tperThreadAccumulator = accumulator;\n\t\t#pragma omp for schedule(dynamic, N/40)\n\t\tfor(i=0;i<N; i++) {\n\t\t\tx=from+i*increment;\n\t\t\tperThreadAccumulator += f(x);\n\t\t}\n\t\t#pragma omp critical\n\t\taccumulator += perThreadAccumulator;\n\t}\n\taccumulator*=increment;\n\treturn accumulator;\n}\n\n//template <class F>\n//inline double integrate_(double from, double to, double increment, F const &f) {\n//\tdouble result=0;\n//\tint N = (to-from)/increment;\n//\tdouble x;\n//\t#pragma omp parallel for private(x) reduction(+:result) schedule(dynamic, N/40) num_threads(numberOfThreads)\n//\tfor(int i=0;i<N; i++) {\n//\t\tx=from+i*increment;\n//\t\tresult += f(x);\n//\t}\n//\tresult*=increment;\n//\treturn result;\n//}\n\n\ntemplate <class Distribution>\nVectorXd EMintegrand (double x, const Distribution& original, const vector<Gaussian>& splitted) {\n\tdouble denominator = 0;\n\tfor (vector<Gaussian>::const_iterator it = splitted.begin(); it!=splitted.end(); ++it) {\n\t\tdenominator+=(*it)(x)*it->weight;\n\t}\n\tif(denominator==0) return VectorXd::Zero(splitted.size());\n\tVectorXd result(splitted.size());\n\tconst double constTerm = original(x)/denominator;\n\tfor(uint i=0; i<splitted.size(); i++) {\n\t\tresult(i) = splitted[i].weight*splitted[i](x)*constTerm;\n\t}\n\treturn result;\n}\n\n\n//template <class Distribution>\n//double EMintegrand (double x, int index, const Distribution& original, const vector<Gaussian>& splitted) {\n//\tdouble denominator = 0;\n//\tfor (vector<Gaussian>::const_iterator it = splitted.begin(); it!=splitted.end(); ++it) {\n//\t\tdenominator+=(*it)(x)*it->weight;\n//\t}\n//\tif(denominator==0) return 0;\n//\treturn splitted[index].weight*splitted[index](x)*original(x)/denominator;\n//}\n\ntemplate <class Distribution>\ndouble DistIntegrand (double x, const Distribution& original, const vector<Gaussian>& splitted) {\n\tdouble originalValue = original(x);\n\tdouble approximatingValue = 0;\n\tBOOST_FOREACH(const Gaussian & hyp, splitted) {\n\t\tapproximatingValue += hyp(x)*hyp.weight;\n\t}\n\treturn originalValue*log(originalValue/approximatingValue);\n}\n\ndouble calculateChange(vector<Gaussian> & oldHyps, vector<Gaussian> & newHyps) {\n\tdouble change = 0;\n\tfor(vectorIterator oldIt = oldHyps.begin(), newIt = newHyps.begin(); oldIt!= oldHyps.end(); oldIt++, newIt++) {\n\t\tchange = max(change,fabs(oldIt->mean-newIt->mean));\n\t\tchange = max(change,fabs(oldIt->var-newIt->var));\n\t\tchange = max(change,fabs(oldIt->weight-newIt->weight));\n\t}\n\treturn change;\n}\n\nvoid printHypotheses(vector<Gaussian> & hypotheses) {\n\tBOOST_FOREACH(Gaussian & g, hypotheses) {\n\t\tcout<< g.mean << \", \"<<g.var<<\": \"<<g.weight<< \" ||\\n\";\n\t}\n}\n\ntemplate<class Distribution>\ndouble EM(vector<Gaussian> & splitted, const Distribution original, double maxVar = 1, bool print = true) {\n\tcout<<\"---- Starting a new EM ---- \\n\";\n\tdouble Dist = numeric_limits<double>::quiet_NaN(); // Bhattacharyya coefficient\n\tdouble ib = original.getIntBegin(); //integralBegin\n\tdouble ie = original.getIntEnd(); //integralEnd\n\tdouble iinc = (ie - ib) / 2000; //integralIncrement\n\tvector<Gaussian> oldHypotheses = splitted;\n\n\tfor(int j=0; j<100000; j++) {\n\t\tif(print) cout<<\"it \"<<j<< \": \";\n\n\t\tVectorXd newWeights_ = integrate(ib,ie,iinc,bp::bind(EMintegrand<Distribution>,X,original,splitted),VectorXd::Zero(splitted.size()));\n\t\tVectorXd newMeans_ =   integrate(ib,ie,iinc,bp::bind(EMintegrand<Distribution>,X,original,splitted)*X,VectorXd::Zero(splitted.size())).cwiseQuotient(newWeights_);\n\t\tVectorXd secondMoments = integrate(ib,ie,iinc,bp::bind(EMintegrand<Distribution>,X,original,splitted)*X*X,VectorXd::Zero(splitted.size())).cwiseQuotient(newWeights_);\n\t\tVectorXd newVars_ = secondMoments - newMeans_.cwiseProduct(newMeans_);\n\n\t\tfor (uint i=0; i<splitted.size(); ++i) {\n\t\t\tsplitted[i].weight = newWeights_(i);\n\t\t\tsplitted[i].mean = newMeans_(i);\n\t\t\tif(newVars_(i)<maxVar) splitted[i].var = newVars_(i);\n\t\t\telse {splitted[i].var=maxVar;}\n\t\t}\n\t\tdouble newDist = integrate(ib,ie,iinc,bp::bind(DistIntegrand<Distribution>,X,original,splitted));\n\t\tcout << newDist;\n\t\tdouble change = calculateChange(splitted,oldHypotheses);\n\t\t//if((Dist - newDist) < 1e-6) break;\n\t\tDist = newDist;\n\t\tif(change<1e-5) break; else oldHypotheses = splitted;\n\t\tif(print) cout << \"\\r\";\n\t\tfflush(stdout);\n\t\tif(quitting) {\n\t\t\tcout<<\"\\ninterrupted\";\n\t\t\tbreak;\n\t\t}\n\t}\n\tcout<<\"\\n\";\n\tprintHypotheses(splitted);\n\treturn Dist;\n}\n\nvoid expandHypotheses(vector<Gaussian> &hypotheses) {\n\tif(hypotheses.size()%2) { //odd case\n\t\tint middleIndex = hypotheses.size()/2;\n\t\tGaussian &g = hypotheses.at(middleIndex);\n\t\tGaussian g1(g.mean-sqrt(g.var), g.var/sqrt(2),g.weight/2);\n\t\tGaussian g2(g.mean+sqrt(g.var), g.var/sqrt(2),g.weight/2);\n\t\thypotheses.erase(hypotheses.begin()+middleIndex);\n\t\thypotheses.push_back(g1);\n\t\thypotheses.push_back(g2);\n\t} else { // even case\n\t\tint rightIndex = hypotheses.size()/2;\n\t\tint leftIndex = rightIndex-1;\n\t\tGaussian &oldLeft = hypotheses.at(leftIndex);\n\t\tGaussian &oldRight = hypotheses.at(rightIndex);\n\t\tGaussian gm((oldLeft.mean+oldRight.mean)/2, (oldLeft.var+oldRight.var)/2, (oldLeft.weight+oldRight.weight)/4);\n\t\tGaussian gl((oldLeft.mean-sqrt(oldLeft.var)),oldLeft.var/sqrt(2),oldLeft.weight/2);\n\t\tGaussian gr((oldRight.mean+sqrt(oldRight.var)),oldRight.var/sqrt(2),oldRight.weight/2);\n\t\thypotheses.erase(hypotheses.begin()+leftIndex);\n\t\thypotheses.erase(hypotheses.begin()+rightIndex);\n\t\thypotheses.push_back(gl);\n\t\thypotheses.push_back(gm);\n\t\thypotheses.push_back(gr);\n\t}\n\tstd::sort(hypotheses.begin(), hypotheses.end());\n}\n\nvoid stretchHypotheses(vector<Gaussian>&hypotheses, double ratio) {\n\tBOOST_FOREACH(Gaussian & g, hypotheses) {\n\t\tg.mean*=sqrt(ratio);\n\t}\n}\n\ndouble linearIncrement(int step, double maxvariance, int tableSize) {return 1+(maxvariance-1)*(step+1)/(tableSize);}\ndouble geometricIncrement(int step, double maxvariance, int tableSize) {\n\tdouble logmax = log(maxvariance);\n\tdouble logstep = logmax*(step+1)/tableSize;\n\treturn exp(logstep);\n}\n\nbool nonSaturatedCriterion(vector<Gaussian> hypotheses) {\n\tBOOST_FOREACH(Gaussian & g, hypotheses) {\n\t\tif(g.var<1) return true;\n\t}\n\treturn false;\n}\n\nbool KLdivUpperBoundCriterion(double KLdiv, double KLdivUpperBound) {\n\treturn KLdiv < KLdivUpperBound;\n}\n\nenum Criterion { KLDIVUPPERBOUND, SATURATION};\n\ntemplate <class Distribution>\nvoid fillTable(map<double,vector<Gaussian> > &table,int tableSize,bool geometricTableSteps, double maxvariance, double maxVar, Criterion criterion, double KLdivUpperBound) {\n\tvector <Gaussian> splitted;\n\tsplitted.push_back(Gaussian(0,1,1));\n\tdouble oldVariance = 1;\n\tfor(int i=0; i<tableSize && !quitting; i++) {\n\t\tdouble variance;\n\t\tif(geometricTableSteps) variance = geometricIncrement(i,maxvariance,tableSize);\n\t\telse variance = linearIncrement(i,maxvariance,tableSize);\n\t\tcout<<\"\\n\\nGenerating Table Entry #\"<< i+1 << \" With Variance: \"<<variance<< \"\\n\";\n\t\tDistribution original(variance);\n\t\tstretchHypotheses(splitted,variance/oldVariance);\n\n\t\tbool isApproximatedWell = false;\n\t\twhile(!isApproximatedWell && !quitting) {\n\t\t\tdouble KLdiv = EM(splitted, original, maxVar);\n\t\t\tswitch (criterion) {\n\t\t\tcase SATURATION: isApproximatedWell = nonSaturatedCriterion(splitted); break;\n\t\t\tcase KLDIVUPPERBOUND:\tisApproximatedWell = KLdivUpperBoundCriterion(KLdiv,KLdivUpperBound); break;\n\t\t\tdefault: std::cerr<<\"Undefined criterion!!!\"; exit(1);\n\t\t\t}\n\t\t\tif(!isApproximatedWell) expandHypotheses(splitted);\n\t\t}\n\n\t\ttable[variance] = splitted;\n\t\toldVariance=variance;\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\tsignal(SIGINT,quit);\n\tdouble maxVar=1;\n\t//\tint iterations = 1000;\n\t//\tint hypotheses = 5;\n\tdouble maxvariance = 2;\n\tint tableSize = 2;\n\tbool geometricTableSteps = true;\n\tbool uniformTable = false;\n\tdouble KLdivUpperBound = 1e-3;\n\tCriterion criterion = KLDIVUPPERBOUND;\n\tstd::string filename=\"\";\n\t\n\t// Declare the supported options.\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t    (\"help\", \"produce help message\")\n\t    (\"output-file,o\", po::value<std::string>(&filename), \"The output file name, dumps the table to the standard output if none provided\")\n\t    (\"maxvariance,m\", po::value<double>(&maxvariance)->default_value(2), \"The maximum source Gaussian variance to be included in the table\")\n\t    (\"tablesize,s\",   po::value<int>(&tableSize)->default_value(2), \"The number of entries in the table\")\n\t    (\"geometric,g\", \"Indicates that the variance values for consequtive entries should increase geometrically (Default)\")\n\t    (\"linear,l\", \"Indicates that the variance values for consequtive entries should increase linearly\")\n\t    (\"numofthreads,n\", po::value<int>(&numberOfThreads)->default_value(3), \"The number of threads to use for the computation of the table\")\n\t    (\"usekldiv\", \"Use an upper-bound for the Kulbeck-Leibler distance of the mixture to stop refining a table entry(Default)\")\n\t    (\"usesaturation\", \"Use a special saturation condition to stop refining a table entry, the condition is that the resulting mixture starts to contain hypoteses that are narrower than the maximum allowed\")\n\t    (\"klupperbound,k\", po::value<double>(&KLdivUpperBound)->default_value(1e-3), \"The upper bound for the Kulbeck-Leibler distance of the splitted mixture to the original\")\n\t    (\"uniform,u\", \"Indicates that the original distribution to be splitted is a uniform distribution\")\n\t    (\"width,w\", po::value<double>(&maxvariance)->default_value(2), \"The width of the uniform distribution (The distribution is 1/width from/to (-/+) 1/(2*width)\")\n\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);    \n\n\tif (vm.count(\"help\")) {\n\t    cout << desc << \"\\n\";\n\t    return 1;\n\t}\n\n\tif (vm.count(\"linear\")) {\n\t\tgeometricTableSteps = false;\n\t} \n\t\n\tif (vm.count(\"usesaturation\")) {\n\t\tcriterion = SATURATION;\n\t} \n\n\tmap<double,vector<Gaussian> > table;\n\n\tif(uniformTable) {\n\t\tcout<<\"creating a uniform table\\n\";\n\t\tfillTable<Uniform>(table,tableSize,geometricTableSteps,maxvariance,maxVar,criterion,KLdivUpperBound);\n\t} else\t{\n\t\tfillTable<Gaussian>(table,tableSize,geometricTableSteps,maxvariance,maxVar,criterion,KLdivUpperBound);\n\t}\n\n\t//\tvector <Gaussian> splitted;\n\t//\tsplitted.push_back(Gaussian(0,1,1));\n\t//\tdouble oldVariance = 1;\n\t//\tfor(int i=0; i<tableSize && !quitting; i++) {\n\t//\t\tdouble variance;\n\t//\t\tif(geometricTableSteps) variance = geometricIncrement(i,maxvariance,tableSize);\n\t//\t\telse variance = linearIncrement(i,maxvariance,tableSize);\n\t//\t\tcout<<\"\\n\\nGenerating Table Entry #\"<< i+1 << \" With Variance: \"<<variance<< \"\\n\";\n\t//\t\tGaussian original(0,variance,1);\n\t//\t\tstretchHypotheses(splitted,variance/oldVariance);\n\t//\n\t//\t\tbool isApproximatedWell = false;\n\t//\t\twhile(!isApproximatedWell) {\n\t//\t\t\tdouble KLdiv = EM(splitted, original, maxVar);\n\t//\t\t\tswitch (criterion) {\n\t//\t\t\tcase SATURATION: isApproximatedWell = nonSaturatedCriterion(splitted); break;\n\t//\t\t\tcase KLDIVUPPERBOUND:\tisApproximatedWell = KLdivUpperBoundCriterion(KLdiv,KLdivUpperBound); break;\n\t//\t\t\tdefault: std::cerr<<\"Undefined criterion!!!\"; exit(1);\n\t//\t\t\t}\n\t//\t\t\tif(!isApproximatedWell) expandHypotheses(splitted);\n\t//\t\t}\n\t//\n\t//\t\ttable[variance] = splitted;\n\t//\t\toldVariance=variance;\n\t//\t}\n\n\tcout<< endl;\n\tofstream the_file;\n\tostream* hypothesisout;\n\tif(filename==\"\")\thypothesisout=&cout;\n\telse {\n\t\tthe_file.open(filename.c_str());\n\t\thypothesisout=&the_file;\n\t}\n\n\tfor(tableIterator it=table.begin(); it!=table.end(); it++) {\n\t\t*hypothesisout<<\"\\n\"<<it->first<<\" \"<<it->second.size()<<\"\\n\";\n\t\tBOOST_FOREACH(Gaussian & g, it->second) {\n\t\t\t*hypothesisout<<\"\\t\"<<g.mean<<\"  \"<<g.var<< \"  \"<<g.weight<<\"\\n\";\n\t\t}\n\t}\n\n\t//\t//*hypothesisout << original.mean<< \" \" << original.var << \" \" <<original.weight << endl;\n\t//\tfor (uint i=0; i<splitted.size(); ++i) {\n\t//\t\t*hypothesisout<< splitted[i].mean<< \" \" << splitted[i].var << \" \" << splitted[i].weight << endl;\n\t//\t}\n\tif(the_file.is_open()) the_file.close();\n\n\treturn 0;\n}\n\nvoid quit(int in) {\n\tquitting=true;\n}\n", "meta": {"hexsha": "12486176529bdcc20fe9b068a809cb7eba974002", "size": 14702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generatetable/src/generatetable.cpp", "max_stars_repo_name": "enobayram/MHFlib", "max_stars_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T08:50:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-29T08:50:55.000Z", "max_issues_repo_path": "generatetable/src/generatetable.cpp", "max_issues_repo_name": "enobayram/MHFlib", "max_issues_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generatetable/src/generatetable.cpp", "max_forks_repo_name": "enobayram/MHFlib", "max_forks_repo_head_hexsha": "bfb978aee59ac1916b0a54ce881d4eb35311e763", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.756501182, "max_line_length": 207, "alphanum_fraction": 0.7014011699, "num_tokens": 4017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5750963093502385}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n#include <cilantro/core/space_transformations.hpp>\n#include <cilantro/core/common_pair_evaluators.hpp>\n\nnamespace cilantro {\n    namespace internal {\n        template <typename ScalarT>\n        inline ScalarT sqrtHuberLoss(ScalarT x, ScalarT delta = (ScalarT)1.0) {\n            const ScalarT x_abs = std::abs(x);\n            if (x_abs > delta) {\n                return std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta));\n            } else {\n                return std::sqrt((ScalarT)(0.5))*x_abs;\n            }\n        }\n\n        template <typename ScalarT>\n        inline ScalarT sqrtHuberLossDerivative(ScalarT x, ScalarT delta = (ScalarT)1.0) {\n            const ScalarT x_abs = std::abs(x);\n            if (x < (ScalarT)0.0) {\n                if (x_abs > delta) {\n                    return -delta/((ScalarT)(2.0)*std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta)));\n                } else {\n                    return -std::sqrt((ScalarT)(0.5));\n                }\n            } else {\n                if (x_abs > delta) {\n                    return delta/((ScalarT)(2.0)*std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta)));\n                } else {\n                    return std::sqrt((ScalarT)0.5);\n                }\n            }\n        }\n\n        template <typename ScalarT>\n        void computeRotationTerms(ScalarT a, ScalarT b, ScalarT c,\n                                  Eigen::Matrix<ScalarT,3,3> &rot_coeffs,\n                                  Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_da,\n                                  Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_db,\n                                  Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_dc)\n        {\n            const ScalarT sina = std::sin(a);\n            const ScalarT cosa = std::cos(a);\n            const ScalarT sinb = std::sin(b);\n            const ScalarT cosb = std::cos(b);\n            const ScalarT sinc = std::sin(c);\n            const ScalarT cosc = std::cos(c);\n\n            rot_coeffs(0,0) = cosc*cosb;\n            rot_coeffs(1,0) = -sinc*cosa + cosc*sinb*sina;\n            rot_coeffs(2,0) = sinc*sina + cosc*sinb*cosa;\n            rot_coeffs(0,1) = sinc*cosb;\n            rot_coeffs(1,1) = cosc*cosa + sinc*sinb*sina;\n            rot_coeffs(2,1) = -cosc*sina + sinc*sinb*cosa;\n            rot_coeffs(0,2) = -sinb;\n            rot_coeffs(1,2) = cosb*sina;\n            rot_coeffs(2,2) = cosb*cosa;\n\n            d_rot_coeffs_da(0,0) = (ScalarT)0.0;\n            d_rot_coeffs_da(1,0) = sinc*sina + cosc*sinb*cosa;\n            d_rot_coeffs_da(2,0) = sinc*cosa - cosc*sinb*sina;\n            d_rot_coeffs_da(0,1) = (ScalarT)0.0;\n            d_rot_coeffs_da(1,1) = -cosc*sina + sinc*sinb*cosa;\n            d_rot_coeffs_da(2,1) = -cosc*cosa - sinc*sinb*sina;\n            d_rot_coeffs_da(0,2) = (ScalarT)0.0;\n            d_rot_coeffs_da(1,2) = cosb*cosa;\n            d_rot_coeffs_da(2,2) = -cosb*sina;\n\n            d_rot_coeffs_db(0,0) = -cosc*sinb;\n            d_rot_coeffs_db(1,0) = cosc*cosb*sina;\n            d_rot_coeffs_db(2,0) = cosc*cosb*cosa;\n            d_rot_coeffs_db(0,1) = -sinc*sinb;\n            d_rot_coeffs_db(1,1) = sinc*cosb*sina;\n            d_rot_coeffs_db(2,1) = sinc*cosb*cosa;\n            d_rot_coeffs_db(0,2) = -cosb;\n            d_rot_coeffs_db(1,2) = -sinb*sina;\n            d_rot_coeffs_db(2,2) = -sinb*cosa;\n\n            d_rot_coeffs_dc(0,0) = -sinc*cosb;\n            d_rot_coeffs_dc(1,0) = -cosc*cosa - sinc*sinb*sina;\n            d_rot_coeffs_dc(2,0) = cosc*sina - sinc*sinb*cosa;\n            d_rot_coeffs_dc(0,1) = cosc*cosb;\n            d_rot_coeffs_dc(1,1) = -sinc*cosa + cosc*sinb*sina;\n            d_rot_coeffs_dc(2,1) = sinc*sina + cosc*sinb*cosa;\n            d_rot_coeffs_dc(0,2) = (ScalarT)0.0;\n            d_rot_coeffs_dc(1,2) = (ScalarT)0.0;\n            d_rot_coeffs_dc(2,2) = (ScalarT)0.0;\n        }\n    } // namespace internal\n\n    // Locally rigid dense warp field, 2D\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Isometry) && TransformT::Dim == 2,bool>::type\n    estimateDenseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &dst_p,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &dst_n,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &src_p,\n                                         const PointCorrSetT &point_to_point_correspondences,\n                                         typename TransformT::Scalar point_to_point_weight,\n                                         const PlaneCorrSetT &point_to_plane_correspondences,\n                                         typename TransformT::Scalar point_to_plane_weight,\n                                         const RegNeighborhoodSetT &regularization_neighborhoods,\n                                         typename TransformT::Scalar regularization_weight,\n                                         TransformSet<TransformT> &transforms,\n                                         typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                         size_t max_gn_iter = 10,\n                                         typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         size_t max_cg_iter = 1000,\n                                         typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                         const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                         const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if ((!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(src_p.cols());\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 3*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 3*src_p.cols();\n        const size_t num_point_to_point_equations = 2*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = 3*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n        const size_t num_non_zeros = 3*num_data_term_equations + 2*num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        At.reserve(num_non_zeros);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n#pragma omp parallel\n        {\n#pragma omp for nowait\n            for (size_t i = 0; i < num_data_term_equations + 1; i++) {\n                outer_ptr[i] = 3*i;\n            }\n#pragma omp for nowait\n            for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n                outer_ptr[num_data_term_equations + i] = 3*num_data_term_equations + 2*i;\n            }\n        }\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (rotation angle and translation offsets per point)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(Eigen::Matrix<ScalarT,Eigen::Dynamic,1>::Zero(num_unknowns, 1));\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, diff, d_sqrt_huber_loss)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = 3*corr.indexInSecond;\n                        weight = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        const ScalarT cosa = std::cos(tforms_vec[offset]);\n                        const ScalarT sina = std::sin(tforms_vec[offset]);\n\n                        Eigen::Matrix<ScalarT,2,1> s_t(cosa*s[0] - sina*s[1] + tforms_vec[offset + 1], sina*s[0] + cosa*s[1] + tforms_vec[offset + 2]);\n\n                        eq_ind = 2*i;\n                        nz_ind = 6*i;\n\n                        values[nz_ind] = (-sina*s[0] - cosa*s[1])*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 2;\n                        b[eq_ind++] = (d[0] - s_t[0])*weight;\n\n                        values[nz_ind] = (cosa*s[0] - sina*s[1])*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = weight;\n                        inner_ind[nz_ind++] = offset + 2;\n                        b[eq_ind++] = (d[1] - s_t[1])*weight;\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = 3*corr.indexInSecond;\n                        weight = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        const ScalarT cosa = std::cos(tforms_vec[offset]);\n                        const ScalarT sina = std::sin(tforms_vec[offset]);\n\n                        Eigen::Matrix<ScalarT,2,1> s_t(cosa*s[0] - sina*s[1] + tforms_vec[offset + 1], sina*s[0] + cosa*s[1] + tforms_vec[offset + 2]);\n\n                        eq_ind = num_point_to_point_equations + i;\n                        nz_ind = 3*num_point_to_point_equations + 3*i;\n\n                        values[nz_ind] = (n[0]*(-sina*s[0] - cosa*s[1]) + n[1]*(cosa*s[0] - sina*s[1]))*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = n[0]*weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = n[1]*weight;\n                        inner_ind[nz_ind++] = offset + 2;\n\n                        b[eq_ind] = n.dot(d - s_t)*weight;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = 3*num_data_term_equations + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = 3*neighbors[0].index;\n                        auto n_offset = 3*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 0;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 0;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 1;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 1;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 2;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 2;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < src_p.cols(); i++) {\n                curr_delta_sq = delta.template segment<3>(3*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(src_p.cols());\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = Eigen::Rotation2D<ScalarT>(tforms_vec[3*i]).toRotationMatrix();\n            transforms[i].translation() = tforms_vec.template segment<2>(3*i + 1);\n        }\n\n        return has_converged;\n    }\n\n    // Locally rigid dense warp field, 3D\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Isometry) && TransformT::Dim == 3,bool>::type\n    estimateDenseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &dst_p,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &dst_n,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &src_p,\n                                         const PointCorrSetT &point_to_point_correspondences,\n                                         typename TransformT::Scalar point_to_point_weight,\n                                         const PlaneCorrSetT &point_to_plane_correspondences,\n                                         typename TransformT::Scalar point_to_plane_weight,\n                                         const RegNeighborhoodSetT &regularization_neighborhoods,\n                                         typename TransformT::Scalar regularization_weight,\n                                         TransformSet<TransformT> &transforms,\n                                         typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                         size_t max_gn_iter = 10,\n                                         typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         size_t max_cg_iter = 1000,\n                                         typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                         const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                         const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if ((!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(src_p.cols());\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 6*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 6*src_p.cols();\n        const size_t num_point_to_point_equations = 3*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = 6*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n        const size_t num_non_zeros = 6*num_data_term_equations + 2*num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        At.reserve(num_non_zeros);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n#pragma omp parallel\n        {\n#pragma omp for nowait\n            for (size_t i = 0; i < num_data_term_equations + 1; i++) {\n                outer_ptr[i] = 6*i;\n            }\n#pragma omp for nowait\n            for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n                outer_ptr[num_data_term_equations + i] = 6*num_data_term_equations + 2*i;\n            }\n        }\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (Euler angles and translation offsets per point)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(Eigen::Matrix<ScalarT,Eigen::Dynamic,1>::Zero(num_unknowns, 1));\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,BlockDiagonalPreconditioner<ScalarT,6>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,3,3> rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc;\n        Eigen::Matrix<ScalarT,3,1> trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, diff, d_sqrt_huber_loss, rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc, trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = 6*corr.indexInSecond;\n                        weight = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        internal::computeRotationTerms(tforms_vec[offset], tforms_vec[offset + 1], tforms_vec[offset + 2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n                        const auto trans_coeffs = tforms_vec.template segment<3>(offset + 3);\n\n                        trans_s.noalias() = d - (rot_coeffs.transpose()*s + trans_coeffs);\n                        d_rot_da_s.noalias() = d_rot_coeffs_da.transpose()*s;\n                        d_rot_db_s.noalias() = d_rot_coeffs_db.transpose()*s;\n                        d_rot_dc_s.noalias() = d_rot_coeffs_dc.transpose()*s;\n\n                        eq_ind = 3*i;\n                        nz_ind = 18*i;\n\n                        values[nz_ind] = d_rot_da_s[0]*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = d_rot_db_s[0]*weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = d_rot_dc_s[0]*weight;\n                        inner_ind[nz_ind++] = offset + 2;\n                        values[nz_ind] = weight;\n                        inner_ind[nz_ind++] = offset + 3;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 4;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 5;\n                        b[eq_ind++] = trans_s[0]*weight;\n\n                        values[nz_ind] = d_rot_da_s[1]*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = d_rot_db_s[1]*weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = d_rot_dc_s[1]*weight;\n                        inner_ind[nz_ind++] = offset + 2;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 3;\n                        values[nz_ind] = weight;\n                        inner_ind[nz_ind++] = offset + 4;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 5;\n                        b[eq_ind++] = trans_s[1]*weight;\n\n                        values[nz_ind] = d_rot_da_s[2]*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = d_rot_db_s[2]*weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = d_rot_dc_s[2]*weight;\n                        inner_ind[nz_ind++] = offset + 2;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 3;\n                        values[nz_ind] = (ScalarT)0.0;\n                        inner_ind[nz_ind++] = offset + 4;\n                        values[nz_ind] = weight;\n                        inner_ind[nz_ind++] = offset + 5;\n                        b[eq_ind++] = trans_s[2]*weight;\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = 6*corr.indexInSecond;\n                        weight = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        internal::computeRotationTerms(tforms_vec[offset], tforms_vec[offset + 1], tforms_vec[offset + 2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n                        const auto trans_coeffs = tforms_vec.template segment<3>(offset + 3);\n\n                        trans_s.noalias() = d - (rot_coeffs.transpose()*s + trans_coeffs);\n                        d_rot_da_s.noalias() = d_rot_coeffs_da.transpose()*s;\n                        d_rot_db_s.noalias() = d_rot_coeffs_db.transpose()*s;\n                        d_rot_dc_s.noalias() = d_rot_coeffs_dc.transpose()*s;\n\n                        eq_ind = num_point_to_point_equations + i;\n                        nz_ind = 6*num_point_to_point_equations + 6*i;\n\n                        values[nz_ind] = (n.dot(d_rot_da_s))*weight;\n                        inner_ind[nz_ind++] = offset;\n                        values[nz_ind] = (n.dot(d_rot_db_s))*weight;\n                        inner_ind[nz_ind++] = offset + 1;\n                        values[nz_ind] = (n.dot(d_rot_dc_s))*weight;\n                        inner_ind[nz_ind++] = offset + 2;\n                        values[nz_ind] = n[0]*weight;\n                        inner_ind[nz_ind++] = offset + 3;\n                        values[nz_ind] = n[1]*weight;\n                        inner_ind[nz_ind++] = offset + 4;\n                        values[nz_ind] = n[2]*weight;\n                        inner_ind[nz_ind++] = offset + 5;\n                        b[eq_ind] = n.dot(trans_s)*weight;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = 6*num_data_term_equations + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = 6*neighbors[0].index;\n                        auto n_offset = 6*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 1;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 1;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 2;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 2;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 3] - tforms_vec[n_offset + 3];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 3;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 3;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 4] - tforms_vec[n_offset + 4];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 4;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 4;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 5] - tforms_vec[n_offset + 5];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 5;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 5;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < src_p.cols(); i++) {\n                curr_delta_sq = delta.template segment<6>(6*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(src_p.cols());\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = (Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 2],Eigen::Matrix<ScalarT,3,1>::UnitZ()) *\n                                                Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 1],Eigen::Matrix<ScalarT,3,1>::UnitY()) *\n                                                Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 0],Eigen::Matrix<ScalarT,3,1>::UnitX())).matrix();\n            transforms[i].linear() = transforms[i].rotation();\n            transforms[i].translation() = tforms_vec.template segment<3>(6*i + 3);\n        }\n\n        return has_converged;\n    }\n\n    // Locally affine dense warp field, general dimension\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Affine) || int(TransformT::Mode) == int(Eigen::AffineCompact),bool>::type\n    estimateDenseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &dst_p,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &dst_n,\n                                         const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &src_p,\n                                         const PointCorrSetT &point_to_point_correspondences,\n                                         typename TransformT::Scalar point_to_point_weight,\n                                         const PlaneCorrSetT &point_to_plane_correspondences,\n                                         typename TransformT::Scalar point_to_plane_weight,\n                                         const RegNeighborhoodSetT &regularization_neighborhoods,\n                                         typename TransformT::Scalar regularization_weight,\n                                         TransformSet<TransformT> &transforms,\n                                         typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                         size_t max_gn_iter = 10,\n                                         typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         size_t max_cg_iter = 1000,\n                                         typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                         const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                         const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                         const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n        enum {\n            Dim = TransformT::Dim,\n            NumUnknownsLocal = TransformT::Dim*(TransformT::Dim + 1),\n            NumNonZerosPointToPoint = TransformT::Dim + 1,\n            NumNonZerosPointToPlane = TransformT::Dim*(TransformT::Dim + 1)\n        };\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if ((!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(src_p.cols());\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + NumUnknownsLocal*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = NumUnknownsLocal*src_p.cols();\n        const size_t num_point_to_point_equations = Dim*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = NumUnknownsLocal*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n        const size_t num_non_zeros_data_term = NumNonZerosPointToPoint*num_point_to_point_equations + NumNonZerosPointToPlane*num_point_to_plane_equations;\n        const size_t num_non_zeros = num_non_zeros_data_term + 2*num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        At.reserve(num_non_zeros);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n#pragma omp parallel\n        {\n#pragma omp for nowait\n            for (size_t i = 0; i < num_point_to_point_equations + 1; i++) {\n                outer_ptr[i] = NumNonZerosPointToPoint*i;\n            }\n#pragma omp for nowait\n            for (size_t i = 1; i < num_point_to_plane_equations + 1; i++) {\n                outer_ptr[num_point_to_point_equations + i] = NumNonZerosPointToPoint*num_point_to_point_equations + NumNonZerosPointToPlane*i;\n            }\n#pragma omp for nowait\n            for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n                outer_ptr[num_data_term_equations + i] = num_non_zeros_data_term + 2*i;\n            }\n        }\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(num_unknowns, 1);\n#pragma omp parallel for\n        for (size_t i = 0; i < src_p.cols(); i++) {\n            Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + i*NumUnknownsLocal, Dim, Dim).setIdentity();\n            tforms_vec.template segment<Dim>(i*NumUnknownsLocal + Dim*Dim).setZero();\n        }\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, diff, d_sqrt_huber_loss)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = NumUnknownsLocal*corr.indexInSecond;\n                        weight = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        auto linear = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + offset, Dim, Dim);\n                        auto translation = tforms_vec.template segment<Dim>(offset + Dim*Dim);\n                        Eigen::Matrix<ScalarT,Dim,1> s_t = linear*s + translation;\n\n                        eq_ind = Dim*i;\n                        nz_ind = Dim*NumNonZerosPointToPoint*i;\n\n                        for (size_t eq = 0; eq < Dim; eq++) {\n                            for (size_t nz = 0; nz < Dim; nz++) {\n                                values[nz_ind] = weight*s_t[nz];\n                                inner_ind[nz_ind++] = offset + Dim*eq + nz;\n                            }\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + Dim*Dim + eq;\n                        }\n                        b.template segment<Dim>(eq_ind) = weight*(d - s_t);\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n                        const auto offset = NumUnknownsLocal*corr.indexInSecond;\n                        weight = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n\n                        auto linear = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + offset, Dim, Dim);\n                        auto translation = tforms_vec.template segment<Dim>(offset + Dim*Dim);\n                        Eigen::Matrix<ScalarT,Dim,1> s_t = linear*s + translation;\n\n                        eq_ind = num_point_to_point_equations + i;\n                        nz_ind = NumNonZerosPointToPoint*num_point_to_point_equations + NumNonZerosPointToPlane*i;\n\n                        for (size_t block = 0; block < Dim; block++) {\n                            for (size_t curr = 0; curr < Dim; curr++) {\n                                values[nz_ind] = weight*n[block]*s_t[curr];\n                                inner_ind[nz_ind++] = offset + Dim*block + curr;\n                            }\n                        }\n                        for (size_t curr = 0; curr < Dim; curr++) {\n                            values[nz_ind] = weight*n[curr];\n                            inner_ind[nz_ind++] = offset + Dim*Dim + curr;\n                        }\n\n                        b[eq_ind] = (n.dot(d - s_t))*weight;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = num_non_zeros_data_term + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = NumUnknownsLocal*neighbors[0].index;\n                        auto n_offset = NumUnknownsLocal*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        for (size_t eq = 0; eq < NumUnknownsLocal; eq++) {\n                            diff = tforms_vec[s_offset + eq] - tforms_vec[n_offset + eq];\n                            d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                            values[nz_ind] = d_sqrt_huber_loss;\n                            inner_ind[nz_ind++] = s_offset + eq;\n                            values[nz_ind] = -d_sqrt_huber_loss;\n                            inner_ind[nz_ind++] = n_offset + eq;\n                            b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                        }\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < src_p.cols(); i++) {\n                curr_delta_sq = delta.template segment<NumUnknownsLocal>(NumUnknownsLocal*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(src_p.cols());\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + i*NumUnknownsLocal, Dim, Dim);\n            transforms[i].translation() = tforms_vec.template segment<Dim>(NumUnknownsLocal*i + Dim*Dim);\n        }\n\n        return has_converged;\n    }\n\n    // Locally rigid sparse warp field, 2D\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class CtrlNeighborhoodSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class ControlWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Isometry) && TransformT::Dim == 2,bool>::type\n    estimateSparseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &dst_p,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &dst_n,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,2> &src_p,\n                                          const PointCorrSetT &point_to_point_correspondences,\n                                          typename TransformT::Scalar point_to_point_weight,\n                                          const PlaneCorrSetT &point_to_plane_correspondences,\n                                          typename TransformT::Scalar point_to_plane_weight,\n                                          const CtrlNeighborhoodSetT &src_to_ctrl_neighborhoods,\n                                          size_t num_ctrl_points,\n                                          const RegNeighborhoodSetT &regularization_neighborhoods,\n                                          typename TransformT::Scalar regularization_weight,\n                                          TransformSet<TransformT> &transforms,\n                                          typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                          size_t max_gn_iter = 10,\n                                          typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          size_t max_cg_iter = 1000,\n                                          typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                          const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                          const ControlWeightEvaluatorT &control_evaluator = ControlWeightEvaluatorT(),\n                                          const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if (src_to_ctrl_neighborhoods.size() != src_p.cols() ||\n            (!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(num_ctrl_points);\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Sort control nodes by index and compute total weight\n        CtrlNeighborhoodSetT src_to_ctrl_sorted(src_to_ctrl_neighborhoods.size());\n        std::vector<ScalarT> total_weight(src_to_ctrl_sorted.size());\n        std::vector<char> has_data_term(src_to_ctrl_neighborhoods.size(), 0);\n#pragma omp parallel shared (src_to_ctrl_sorted, total_weight, has_data_term)\n        {\n            if (has_point_to_point_terms) {\n#pragma omp for nowait\n                for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                    has_data_term[point_to_point_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n            if (has_point_to_plane_terms) {\n#pragma omp for\n                for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                    has_data_term[point_to_plane_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n#pragma omp for schedule (dynamic)\n            for (size_t i = 0; i < has_data_term.size(); i++) {\n                if (has_data_term[i]) {\n                    total_weight[i] = (ScalarT)0.0;\n                    src_to_ctrl_sorted[i].resize(src_to_ctrl_neighborhoods[i].size());\n                    for (size_t j = 0; j < src_to_ctrl_neighborhoods[i].size(); j++) {\n                        src_to_ctrl_sorted[i][j].index = src_to_ctrl_neighborhoods[i][j].index;\n                        src_to_ctrl_sorted[i][j].value = control_evaluator(i, src_to_ctrl_neighborhoods[i][j].index, src_to_ctrl_neighborhoods[i][j].value);\n                        total_weight[i] += src_to_ctrl_sorted[i][j].value;\n                    }\n                    std::sort(src_to_ctrl_sorted[i].begin(), src_to_ctrl_sorted[i].end(), typename CtrlNeighborhoodSetT::value_type::value_type::IndexLessComparator());\n                }\n            }\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 3*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 3*num_ctrl_points;\n        const size_t num_point_to_point_equations = 2*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = 3*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n        outer_ptr[0] = 0;\n        if (has_point_to_point_terms) {\n            for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                const size_t nnz_per_eq = 3*src_to_ctrl_sorted[point_to_point_correspondences[i].indexInSecond].size();\n                outer_ptr[2*i + 1] = outer_ptr[2*i] + nnz_per_eq;\n                outer_ptr[2*i + 2] = outer_ptr[2*i] + nnz_per_eq + nnz_per_eq;\n            }\n        }\n        if (has_point_to_plane_terms) {\n            for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                outer_ptr[num_point_to_point_equations + i + 1] = outer_ptr[num_point_to_point_equations + i] + 3*src_to_ctrl_sorted[point_to_plane_correspondences[i].indexInSecond].size();\n            }\n        }\n#pragma omp parallel for\n        for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n            outer_ptr[num_data_term_equations + i] = outer_ptr[num_data_term_equations] + 2*i;\n        }\n        At.reserve(outer_ptr[num_equations]);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (rotation angle and translation offsets per control node)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(Eigen::Matrix<ScalarT,Eigen::Dynamic,1>::Zero(num_unknowns, 1));\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        ScalarT angle_curr;\n        Eigen::Matrix<ScalarT,2,1> trans_curr;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, angle_curr, trans_curr)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        angle_curr = (ScalarT)0.0;\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 3*ctrl_neighbors[j].index;\n                            angle_curr += ctrl_neighbors[j].value*tforms_vec[offset];\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<2>(offset + 1);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            angle_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        const ScalarT cosa = std::cos(angle_curr);\n                        const ScalarT sina = std::sin(angle_curr);\n\n                        Eigen::Matrix<ScalarT,2,1> s_t(cosa*s[0] - sina*s[1] + trans_curr[0], sina*s[0] + cosa*s[1] + trans_curr[1]);\n\n                        eq_ind = 2*i;\n\n                        const ScalarT coeff1 = -sina*s[0] - cosa*s[1];\n                        const ScalarT coeff2 = cosa*s[0] - sina*s[1];\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 3*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            nz_ind = outer_ptr[eq_ind] + 3*j;\n                            values[nz_ind] = coeff1*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 2;\n\n                            nz_ind = outer_ptr[eq_ind + 1] + 3*j;\n                            values[nz_ind] = coeff2*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                        }\n\n                        b.template segment<2>(eq_ind) = (d - s_t)*corr_weight_sqrt;\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        angle_curr = (ScalarT)0.0;\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 3*ctrl_neighbors[j].index;\n                            angle_curr += ctrl_neighbors[j].value*tforms_vec[offset];\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<2>(offset + 1);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            angle_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        const ScalarT cosa = std::cos(angle_curr);\n                        const ScalarT sina = std::sin(angle_curr);\n\n                        Eigen::Matrix<ScalarT,2,1> s_t(cosa*s[0] - sina*s[1] + trans_curr[0], sina*s[0] + cosa*s[1] + trans_curr[1]);\n\n                        eq_ind = num_point_to_point_equations + i;\n\n                        const ScalarT dot_val = (n[0]*(-sina*s[0] - cosa*s[1]) + n[1]*(cosa*s[0] - sina*s[1]));\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 3*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            // Point to plane\n                            nz_ind = outer_ptr[eq_ind] + 3*j;\n                            values[nz_ind] = dot_val*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = n[0]*weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = n[1]*weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                        }\n\n                        b[eq_ind] = n.dot(d - s_t)*corr_weight_sqrt;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = outer_ptr[num_data_term_equations] + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = 3*neighbors[0].index;\n                        auto n_offset = 3*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 1;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 1;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 2;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 2;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < num_ctrl_points; i++) {\n                curr_delta_sq = delta.template segment<3>(3*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(num_ctrl_points);\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = Eigen::Rotation2D<ScalarT>(tforms_vec[3*i]).toRotationMatrix();\n            transforms[i].translation() = tforms_vec.template segment<2>(3*i + 1);\n        }\n\n        return has_converged;\n    }\n\n    // Locally rigid sparse warp field, 3D\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class CtrlNeighborhoodSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class ControlWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Isometry) && TransformT::Dim == 3,bool>::type\n    estimateSparseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &dst_p,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &dst_n,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,3> &src_p,\n                                          const PointCorrSetT &point_to_point_correspondences,\n                                          typename TransformT::Scalar point_to_point_weight,\n                                          const PlaneCorrSetT &point_to_plane_correspondences,\n                                          typename TransformT::Scalar point_to_plane_weight,\n                                          const CtrlNeighborhoodSetT &src_to_ctrl_neighborhoods,\n                                          size_t num_ctrl_points,\n                                          const RegNeighborhoodSetT &regularization_neighborhoods,\n                                          typename TransformT::Scalar regularization_weight,\n                                          TransformSet<TransformT> &transforms,\n                                          typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                          size_t max_gn_iter = 10,\n                                          typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          size_t max_cg_iter = 1000,\n                                          typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                          const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                          const ControlWeightEvaluatorT &control_evaluator = ControlWeightEvaluatorT(),\n                                          const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if (src_to_ctrl_neighborhoods.size() != src_p.cols() ||\n            (!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(num_ctrl_points);\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Sort control nodes by index and compute total weight\n        CtrlNeighborhoodSetT src_to_ctrl_sorted(src_to_ctrl_neighborhoods.size());\n        std::vector<ScalarT> total_weight(src_to_ctrl_sorted.size());\n        std::vector<char> has_data_term(src_to_ctrl_neighborhoods.size(), 0);\n#pragma omp parallel shared (src_to_ctrl_sorted, total_weight, has_data_term)\n        {\n            if (has_point_to_point_terms) {\n#pragma omp for nowait\n                for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                    has_data_term[point_to_point_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n            if (has_point_to_plane_terms) {\n#pragma omp for\n                for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                    has_data_term[point_to_plane_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n#pragma omp for schedule (dynamic)\n            for (size_t i = 0; i < has_data_term.size(); i++) {\n                if (has_data_term[i]) {\n                    total_weight[i] = (ScalarT)0.0;\n                    src_to_ctrl_sorted[i].resize(src_to_ctrl_neighborhoods[i].size());\n                    for (size_t j = 0; j < src_to_ctrl_neighborhoods[i].size(); j++) {\n                        src_to_ctrl_sorted[i][j].index = src_to_ctrl_neighborhoods[i][j].index;\n                        src_to_ctrl_sorted[i][j].value = control_evaluator(i, src_to_ctrl_neighborhoods[i][j].index, src_to_ctrl_neighborhoods[i][j].value);\n                        total_weight[i] += src_to_ctrl_sorted[i][j].value;\n                    }\n                    std::sort(src_to_ctrl_sorted[i].begin(), src_to_ctrl_sorted[i].end(), typename CtrlNeighborhoodSetT::value_type::value_type::IndexLessComparator());\n                }\n            }\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 6*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 6*num_ctrl_points;\n        const size_t num_point_to_point_equations = 3*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = 6*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n        outer_ptr[0] = 0;\n        if (has_point_to_point_terms) {\n            for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                const size_t nnz_per_eq = 6*src_to_ctrl_sorted[point_to_point_correspondences[i].indexInSecond].size();\n                outer_ptr[3*i + 1] = outer_ptr[3*i] + nnz_per_eq;\n                outer_ptr[3*i + 2] = outer_ptr[3*i] + nnz_per_eq + nnz_per_eq;\n                outer_ptr[3*i + 3] = outer_ptr[3*i] + nnz_per_eq + nnz_per_eq + nnz_per_eq;\n            }\n        }\n        if (has_point_to_plane_terms) {\n            for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                outer_ptr[num_point_to_point_equations + i + 1] = outer_ptr[num_point_to_point_equations + i] + 6*src_to_ctrl_sorted[point_to_plane_correspondences[i].indexInSecond].size();\n            }\n        }\n#pragma omp parallel for\n        for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n            outer_ptr[num_data_term_equations + i] = outer_ptr[num_data_term_equations] + 2*i;\n        }\n        At.reserve(outer_ptr[num_equations]);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (Euler angles and translation offsets per control node)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(Eigen::Matrix<ScalarT,Eigen::Dynamic,1>::Zero(num_unknowns, 1));\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,BlockDiagonalPreconditioner<ScalarT,6>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,3,3> rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc;\n        Eigen::Matrix<ScalarT,3,1> trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s;\n        Eigen::Matrix<ScalarT,3,1> angles_curr, trans_curr;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, angles_curr, trans_curr, rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc, trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        angles_curr.setZero();\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 6*ctrl_neighbors[j].index;\n                            angles_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<3>(offset);\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<3>(offset + 3);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            angles_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        internal::computeRotationTerms(angles_curr[0], angles_curr[1], angles_curr[2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n\n                        trans_s.noalias() = d - (rot_coeffs.transpose()*s + trans_curr);\n                        d_rot_da_s.noalias() = d_rot_coeffs_da.transpose()*s;\n                        d_rot_db_s.noalias() = d_rot_coeffs_db.transpose()*s;\n                        d_rot_dc_s.noalias() = d_rot_coeffs_dc.transpose()*s;\n\n                        eq_ind = 3*i;\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 6*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            nz_ind = outer_ptr[eq_ind] + 6*j;\n                            values[nz_ind] = d_rot_da_s[0]*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = d_rot_db_s[0]*weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = d_rot_dc_s[0]*weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + 3;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 4;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 5;\n\n                            nz_ind = outer_ptr[eq_ind + 1] + 6*j;\n                            values[nz_ind] = d_rot_da_s[1]*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = d_rot_db_s[1]*weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = d_rot_dc_s[1]*weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 3;\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + 4;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 5;\n\n                            nz_ind = outer_ptr[eq_ind + 2] + 6*j;\n                            values[nz_ind] = d_rot_da_s[2]*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = d_rot_db_s[2]*weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = d_rot_dc_s[2]*weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 3;\n                            values[nz_ind] = (ScalarT)0.0;\n                            inner_ind[nz_ind++] = offset + 4;\n                            values[nz_ind] = weight;\n                            inner_ind[nz_ind++] = offset + 5;\n                        }\n\n                        b.template segment<3>(eq_ind) = trans_s*corr_weight_sqrt;\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        angles_curr.setZero();\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 6*ctrl_neighbors[j].index;\n                            angles_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<3>(offset);\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<3>(offset + 3);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            angles_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        internal::computeRotationTerms(angles_curr[0], angles_curr[1], angles_curr[2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n\n                        trans_s.noalias() = d - (rot_coeffs.transpose()*s + trans_curr);\n                        d_rot_da_s.noalias() = d_rot_coeffs_da.transpose()*s;\n                        d_rot_db_s.noalias() = d_rot_coeffs_db.transpose()*s;\n                        d_rot_dc_s.noalias() = d_rot_coeffs_dc.transpose()*s;\n\n                        eq_ind = num_point_to_point_equations + i;\n\n                        const ScalarT dot1 = n.dot(d_rot_da_s);\n                        const ScalarT dot2 = n.dot(d_rot_db_s);\n                        const ScalarT dot3 = n.dot(d_rot_dc_s);\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = 6*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            // Point to plane\n                            nz_ind = outer_ptr[eq_ind] + 6*j;\n                            values[nz_ind] = dot1*weight;\n                            inner_ind[nz_ind++] = offset;\n                            values[nz_ind] = dot2*weight;\n                            inner_ind[nz_ind++] = offset + 1;\n                            values[nz_ind] = dot3*weight;\n                            inner_ind[nz_ind++] = offset + 2;\n                            values[nz_ind] = n[0]*weight;\n                            inner_ind[nz_ind++] = offset + 3;\n                            values[nz_ind] = n[1]*weight;\n                            inner_ind[nz_ind++] = offset + 4;\n                            values[nz_ind] = n[2]*weight;\n                            inner_ind[nz_ind++] = offset + 5;\n                        }\n\n                        b[eq_ind] = n.dot(trans_s)*corr_weight_sqrt;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = outer_ptr[num_data_term_equations] + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = 6*neighbors[0].index;\n                        auto n_offset = 6*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 1;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 1;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 2;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 2;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 3] - tforms_vec[n_offset + 3];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 3;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 3;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 4] - tforms_vec[n_offset + 4];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 4;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 4;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                        diff = tforms_vec[s_offset + 5] - tforms_vec[n_offset + 5];\n                        d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                        values[nz_ind] = d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = s_offset + 5;\n                        values[nz_ind] = -d_sqrt_huber_loss;\n                        inner_ind[nz_ind++] = n_offset + 5;\n                        b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < num_ctrl_points; i++) {\n                curr_delta_sq = delta.template segment<6>(6*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(num_ctrl_points);\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = (Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 2],Eigen::Matrix<ScalarT,3,1>::UnitZ()) *\n                                                Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 1],Eigen::Matrix<ScalarT,3,1>::UnitY()) *\n                                                Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 0],Eigen::Matrix<ScalarT,3,1>::UnitX())).matrix();\n            transforms[i].linear() = transforms[i].rotation();\n            transforms[i].translation() = tforms_vec.template segment<3>(6*i + 3);\n        }\n\n        return has_converged;\n    }\n\n    // Locally affine sparse warp field, general dimension\n    template <class TransformT, class PointCorrSetT, class PlaneCorrSetT, class CtrlNeighborhoodSetT, class RegNeighborhoodSetT, class PointCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class PlaneCorrWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class ControlWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>, class RegWeightEvaluatorT = UnityWeightEvaluator<typename TransformT::Scalar,typename TransformT::Scalar>>\n    typename std::enable_if<int(TransformT::Mode) == int(Eigen::Affine) || int(TransformT::Mode) == int(Eigen::AffineCompact),bool>::type\n    estimateSparseWarpFieldCombinedMetric(const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &dst_p,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &dst_n,\n                                          const ConstVectorSetMatrixMap<typename TransformT::Scalar,TransformT::Dim> &src_p,\n                                          const PointCorrSetT &point_to_point_correspondences,\n                                          typename TransformT::Scalar point_to_point_weight,\n                                          const PlaneCorrSetT &point_to_plane_correspondences,\n                                          typename TransformT::Scalar point_to_plane_weight,\n                                          const CtrlNeighborhoodSetT &src_to_ctrl_neighborhoods,\n                                          size_t num_ctrl_points,\n                                          const RegNeighborhoodSetT &regularization_neighborhoods,\n                                          typename TransformT::Scalar regularization_weight,\n                                          TransformSet<TransformT> &transforms,\n                                          typename TransformT::Scalar huber_boundary = (typename TransformT::Scalar)(1e-4),\n                                          size_t max_gn_iter = 10,\n                                          typename TransformT::Scalar gn_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          size_t max_cg_iter = 1000,\n                                          typename TransformT::Scalar cg_conv_tol = (typename TransformT::Scalar)1e-5,\n                                          const PointCorrWeightEvaluatorT &point_corr_evaluator = PointCorrWeightEvaluatorT(),\n                                          const PlaneCorrWeightEvaluatorT &plane_corr_evaluator = PlaneCorrWeightEvaluatorT(),\n                                          const ControlWeightEvaluatorT &control_evaluator = ControlWeightEvaluatorT(),\n                                          const RegWeightEvaluatorT &reg_evaluator = RegWeightEvaluatorT())\n    {\n        typedef typename TransformT::Scalar ScalarT;\n        enum {\n            Dim = TransformT::Dim,\n            NumUnknownsLocal = TransformT::Dim*(TransformT::Dim + 1),\n            NumNonZerosPointToPoint = TransformT::Dim + 1,\n            NumNonZerosPointToPlane = TransformT::Dim*(TransformT::Dim + 1)\n        };\n\n        const bool has_point_to_point_terms = !point_to_point_correspondences.empty() && (point_to_point_weight > (ScalarT)0.0);\n        const bool has_point_to_plane_terms = !point_to_plane_correspondences.empty() && (point_to_plane_weight > (ScalarT)0.0);\n\n        if (src_to_ctrl_neighborhoods.size() != src_p.cols() ||\n            (!has_point_to_point_terms && !has_point_to_plane_terms) ||\n            (has_point_to_plane_terms && dst_p.cols() != dst_n.cols()))\n        {\n            transforms.resize(num_ctrl_points);\n            transforms.setIdentity();\n            return false;\n        }\n\n        // Sort control nodes by index and compute total weight\n        CtrlNeighborhoodSetT src_to_ctrl_sorted(src_to_ctrl_neighborhoods.size());\n        std::vector<ScalarT> total_weight(src_to_ctrl_sorted.size());\n        std::vector<char> has_data_term(src_to_ctrl_neighborhoods.size(), 0);\n#pragma omp parallel shared (src_to_ctrl_sorted, total_weight, has_data_term)\n        {\n            if (has_point_to_point_terms) {\n#pragma omp for nowait\n                for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                    has_data_term[point_to_point_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n            if (has_point_to_plane_terms) {\n#pragma omp for\n                for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                    has_data_term[point_to_plane_correspondences[i].indexInSecond] = 1;\n                }\n            }\n\n#pragma omp for schedule (dynamic)\n            for (size_t i = 0; i < has_data_term.size(); i++) {\n                if (has_data_term[i]) {\n                    total_weight[i] = (ScalarT)0.0;\n                    src_to_ctrl_sorted[i].resize(src_to_ctrl_neighborhoods[i].size());\n                    for (size_t j = 0; j < src_to_ctrl_neighborhoods[i].size(); j++) {\n                        src_to_ctrl_sorted[i][j].index = src_to_ctrl_neighborhoods[i][j].index;\n                        src_to_ctrl_sorted[i][j].value = control_evaluator(i, src_to_ctrl_neighborhoods[i][j].index, src_to_ctrl_neighborhoods[i][j].value);\n                        total_weight[i] += src_to_ctrl_sorted[i][j].value;\n                    }\n                    std::sort(src_to_ctrl_sorted[i].begin(), src_to_ctrl_sorted[i].end(), typename CtrlNeighborhoodSetT::value_type::value_type::IndexLessComparator());\n                }\n            }\n        }\n\n        // Get regularization equation count and indices\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + NumUnknownsLocal*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = NumUnknownsLocal*num_ctrl_points;\n        const size_t num_point_to_point_equations = Dim*has_point_to_point_terms*point_to_point_correspondences.size();\n        const size_t num_point_to_plane_equations = has_point_to_plane_terms*point_to_plane_correspondences.size();\n        const size_t num_data_term_equations = num_point_to_point_equations + num_point_to_plane_equations;\n        const size_t num_regularization_equations = NumUnknownsLocal*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns, num_equations);\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n        outer_ptr[0] = 0;\n        if (has_point_to_point_terms) {\n            for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                const size_t nnz_per_eq = NumNonZerosPointToPoint*src_to_ctrl_sorted[point_to_point_correspondences[i].indexInSecond].size();\n                for (size_t j = 0; j < Dim; j++) {\n                    outer_ptr[Dim*i + j + 1] = outer_ptr[Dim*i + j] + nnz_per_eq;\n                }\n            }\n        }\n        if (has_point_to_plane_terms) {\n            for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                outer_ptr[num_point_to_point_equations + i + 1] = outer_ptr[num_point_to_point_equations + i] + NumNonZerosPointToPlane*src_to_ctrl_sorted[point_to_plane_correspondences[i].indexInSecond].size();\n            }\n        }\n#pragma omp parallel for\n        for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n            outer_ptr[num_data_term_equations + i] = outer_ptr[num_data_term_equations] + 2*i;\n        }\n        At.reserve(outer_ptr[num_equations]);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(num_unknowns, 1);\n#pragma omp parallel for\n        for (size_t i = 0; i < num_ctrl_points; i++) {\n            Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + i*NumUnknownsLocal, Dim, Dim).setIdentity();\n            tforms_vec.template segment<Dim>(i*NumUnknownsLocal + Dim*Dim).setZero();\n        }\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Parameters\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT regularization_weight_sqrt = std::sqrt(regularization_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,Dim*Dim,1> linear_curr;\n        Eigen::Matrix<ScalarT,Dim,1> trans_curr;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n#pragma omp parallel shared (At, b) private (eq_ind, nz_ind, weight, corr_weight_sqrt, corr_weight_nrm, diff, d_sqrt_huber_loss, linear_curr, trans_curr)\n            {\n                // Data term\n                if (has_point_to_point_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_point_correspondences.size(); i++) {\n                        const auto& corr = point_to_point_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        linear_curr.setZero();\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = NumUnknownsLocal*ctrl_neighbors[j].index;\n                            linear_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<Dim*Dim>(offset);\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<Dim>(offset + Dim*Dim);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            linear_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_point_weight_sqrt*std::sqrt(point_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        Eigen::Matrix<ScalarT,Dim,1> s_t = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(linear_curr.data(), Dim, Dim)*s + trans_curr;\n\n                        eq_ind = Dim*i;\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = NumUnknownsLocal*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            for (size_t eq = 0; eq < Dim; eq++) {\n                                nz_ind = outer_ptr[eq_ind + eq] + NumNonZerosPointToPoint*j;\n                                for (size_t nz = 0; nz < Dim; nz++) {\n                                    values[nz_ind] = weight*s_t[nz];\n                                    inner_ind[nz_ind++] = offset + Dim*eq + nz;\n                                }\n                                values[nz_ind] = weight;\n                                inner_ind[nz_ind++] = offset + Dim*Dim + eq;\n                            }\n                        }\n\n                        b.template segment<Dim>(eq_ind) = corr_weight_sqrt*(d - s_t);\n                    }\n                }\n\n                if (has_point_to_plane_terms) {\n#pragma omp for nowait\n                    for (size_t i = 0; i < point_to_plane_correspondences.size(); i++) {\n                        const auto& corr = point_to_plane_correspondences[i];\n                        const auto& ctrl_neighbors = src_to_ctrl_sorted[corr.indexInSecond];\n\n                        // Compute weighted influence from control nodes\n                        linear_curr.setZero();\n                        trans_curr.setZero();\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = NumUnknownsLocal*ctrl_neighbors[j].index;\n                            linear_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<Dim*Dim>(offset);\n                            trans_curr.noalias() += ctrl_neighbors[j].value*tforms_vec.template segment<Dim>(offset + Dim*Dim);\n                        }\n                        if (total_weight[corr.indexInSecond] != (ScalarT)0.0) {\n                            weight = (ScalarT)(1.0)/total_weight[corr.indexInSecond];\n                            linear_curr *= weight;\n                            trans_curr *= weight;\n\n                            corr_weight_sqrt = point_to_plane_weight_sqrt*std::sqrt(plane_corr_evaluator(corr.indexInFirst, corr.indexInSecond, corr.value));\n                            corr_weight_nrm = corr_weight_sqrt/total_weight[corr.indexInSecond];\n                        } else {\n                            corr_weight_sqrt = (ScalarT)0.0;\n                            corr_weight_nrm = (ScalarT)0.0;\n                        }\n\n                        const auto d = dst_p.col(corr.indexInFirst);\n                        const auto n = dst_n.col(corr.indexInFirst);\n                        const auto s = src_p.col(corr.indexInSecond);\n\n                        Eigen::Matrix<ScalarT,Dim,1> s_t = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(linear_curr.data(), Dim, Dim)*s + trans_curr;\n\n                        eq_ind = num_point_to_point_equations + i;\n\n                        for (size_t j = 0; j < ctrl_neighbors.size(); j++) {\n                            const auto offset = NumUnknownsLocal*ctrl_neighbors[j].index;\n                            weight = corr_weight_nrm*ctrl_neighbors[j].value;\n\n                            nz_ind = outer_ptr[eq_ind] + NumUnknownsLocal*j;\n\n                            for (size_t block = 0; block < Dim; block++) {\n                                for (size_t curr = 0; curr < Dim; curr++) {\n                                    values[nz_ind] = weight*n[block]*s_t[curr];\n                                    inner_ind[nz_ind++] = offset + Dim*block + curr;\n                                }\n                            }\n                            for (size_t curr = 0; curr < Dim; curr++) {\n                                values[nz_ind] = weight*n[curr];\n                                inner_ind[nz_ind++] = offset + Dim*Dim + curr;\n                            }\n                        }\n\n                        b[eq_ind] = (n.dot(d - s_t))*corr_weight_sqrt;\n                    }\n                }\n\n                // Regularization\n#pragma omp for nowait\n                for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                    eq_ind = num_data_term_equations + reg_eq_ind[i];\n                    nz_ind = outer_ptr[num_data_term_equations] + 2*reg_eq_ind[i];\n                    const auto& neighbors = regularization_neighborhoods[i];\n\n                    for (size_t j = 1; j < neighbors.size(); j++) {\n                        auto s_offset = NumUnknownsLocal*neighbors[0].index;\n                        auto n_offset = NumUnknownsLocal*neighbors[j].index;\n                        weight = regularization_weight_sqrt*std::sqrt(reg_evaluator(neighbors[0].index, neighbors[j].index, neighbors[j].value));\n\n                        if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                        for (size_t eq = 0; eq < NumUnknownsLocal; eq++) {\n                            diff = tforms_vec[s_offset + eq] - tforms_vec[n_offset + eq];\n                            d_sqrt_huber_loss = weight*internal::sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                            values[nz_ind] = d_sqrt_huber_loss;\n                            inner_ind[nz_ind++] = s_offset + eq;\n                            values[nz_ind] = -d_sqrt_huber_loss;\n                            inner_ind[nz_ind++] = n_offset + eq;\n                            b[eq_ind++] = -weight*internal::sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                        }\n                    }\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb.noalias() = At*b;\n\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < num_ctrl_points; i++) {\n                curr_delta_sq = delta.template segment<NumUnknownsLocal>(NumUnknownsLocal*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(num_ctrl_points);\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear().noalias() = Eigen::Map<Eigen::Matrix<ScalarT,Dim,Dim,Eigen::RowMajor>>(tforms_vec.data() + i*NumUnknownsLocal, Dim, Dim);\n            transforms[i].translation() = tforms_vec.template segment<Dim>(NumUnknownsLocal*i + Dim*Dim);\n        }\n\n        return has_converged;\n    }\n}\n", "meta": {"hexsha": "a3491cf21f9d2d3f1099cd9429c6c1f18930c17f", "size": 115758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cilantro/registration/warp_field_estimation.hpp", "max_stars_repo_name": "eecn/cilantro", "max_stars_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 719.0, "max_stars_repo_stars_event_min_datetime": "2017-08-07T08:30:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T07:08:52.000Z", "max_issues_repo_path": "include/cilantro/registration/warp_field_estimation.hpp", "max_issues_repo_name": "eecn/cilantro", "max_issues_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T13:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-16T13:58:32.000Z", "max_forks_repo_path": "include/cilantro/registration/warp_field_estimation.hpp", "max_forks_repo_name": "eecn/cilantro", "max_forks_repo_head_hexsha": "467824bb7551e4537b2b7d1f697156f68f608260", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 152.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:02:48.000Z", "avg_line_length": 57.2209589718, "max_line_length": 572, "alphanum_fraction": 0.5602463761, "num_tokens": 26034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5750121132725909}}
{"text": "#pragma once\r\n\r\n#include <Eigen/Core>\r\n#include <vector>\r\n\r\n#include \"../common.hpp\"\r\n\r\nnamespace Discregrid\r\n{\r\n\r\n/**\r\n * \\brief Computes smallest enclosing spheres of pointsets using Welzl's algorithm\r\n * \\Author: Tassilo Kugelstadt\r\n */\r\nclass BoundingSphere\r\n{\r\n\r\npublic:\r\n\r\n\t/**\r\n\t * \\brief default constructor sets the center and radius to zero.\r\n\t */\r\n\tBoundingSphere() : m_x(Vector3r::Zero()), m_r(0.0) {}\r\n\r\n\t/**\r\n\t * \\brief constructor which sets the center and radius\r\n\t *\r\n\t * \\param x\t3d coordinates of the center point\r\n\t * \\param r radius of the sphere\r\n\t */\r\n\tBoundingSphere(const Vector3r& x, Real r) : m_x(x), m_r(r) {}\r\n\r\n\t/**\r\n\t * \\brief\tconstructs a sphere for one point (with radius 0)\r\n\t *\r\n\t * \\param a\t3d coordinates of point a\r\n\t */\r\n\tBoundingSphere(const Vector3r& a)\r\n\t{\r\n\t\tm_x = a;\r\n\t\tm_r = 0.0;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\tconstructs the smallest enclosing sphere for two points\r\n\t *\r\n\t * \\param a 3d coordinates of point a\r\n\t * \\param b 3d coordinates of point b\r\n\t */\r\n\tBoundingSphere(const Vector3r& a, const Vector3r& b)\r\n\t{\r\n\t\tconst Vector3r ba = b - a;\r\n\r\n\t\tm_x = (a + b) * 0.5;\r\n\t\tm_r = 0.5 * ba.norm();\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\tconstructs the smallest enclosing sphere for three points\r\n\t *\r\n\t * \\param a 3d coordinates of point a\r\n\t * \\param b 3d coordinates of point b\r\n\t * \\param c 3d coordinates of point c\r\n\t */\r\n\tBoundingSphere(const Vector3r& a, const Vector3r& b, const Vector3r& c)\r\n\t{\r\n\t\tconst Vector3r ba = b - a;\r\n\t\tconst Vector3r ca = c - a;\r\n\t\tconst Vector3r baxca = ba.cross(ca);\r\n\t\tVector3r r;\r\n\t\tMatrix3r T;\r\n\t\tT << ba[0], ba[1], ba[2],\r\n\t\t\tca[0], ca[1], ca[2],\r\n\t\t\tbaxca[0], baxca[1], baxca[2];\r\n\r\n\t\tr[0] = 0.5 * ba.squaredNorm();\r\n\t\tr[1] = 0.5 * ca.squaredNorm();\r\n\t\tr[2] = 0.0;\r\n\r\n\t\tm_x = T.inverse() * r;\r\n\t\tm_r = m_x.norm();\r\n\t\tm_x += a;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief constructs the smallest enclosing sphere for four points\r\n\t *\r\n\t * \\param a 3d coordinates of point a\r\n\t * \\param b 3d coordinates of point b\r\n\t * \\param c 3d coordinates of point c\r\n\t * \\param d 3d coordinates of point d\r\n\t */\r\n\tBoundingSphere(const Vector3r& a, const Vector3r& b, const Vector3r& c, const Vector3r& d)\r\n\t{\r\n\t\tconst Vector3r ba = b - a;\r\n\t\tconst Vector3r ca = c - a;\r\n\t\tconst Vector3r da = d - a;\r\n\t\tVector3r r;\r\n\t\tMatrix3r T;\r\n\t\tT << ba[0], ba[1], ba[2],\r\n\t\t\tca[0], ca[1], ca[2],\r\n\t\t\tda[0], da[1], da[2];\r\n\r\n\t\tr[0] = 0.5 * ba.squaredNorm();\r\n\t\tr[1] = 0.5 * ca.squaredNorm();\r\n\t\tr[2] = 0.5 * da.squaredNorm();\r\n\t\tm_x = T.inverse() * r;\r\n\t\tm_r = m_x.norm();\r\n\t\tm_x += a;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\tconstructs the smallest enclosing sphere a given pointset\r\n\t *\r\n\t * \\param p vertices of the points\r\n\t */\r\n\tBoundingSphere(const std::vector<Vector3r>& p)\r\n\t{\r\n\t\tm_r = 0;\r\n\t\tm_x.setZero();\r\n\t\tsetPoints(p);\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\tGetter for the center of the sphere\r\n\t *\r\n\t * \\return\tconst reference of the sphere center\r\n\t */\r\n\tVector3r const& x() const { return m_x; }\r\n\r\n\t/**\r\n\t * \\brief\tAccess function for center of the sphere\r\n\t *\r\n\t * \\return\treference of the sphere center\r\n\t */\r\n\tVector3r& x() { return m_x; }\r\n\r\n\t/**\r\n\t * \\brief\tGetter for the radius\r\n\t *\r\n\t * \\return\tRadius of the sphere\r\n\t */\r\n\tReal r() const { return m_r; }\r\n\r\n\t/**\r\n\t * \\brief\tAccess function for the radius\r\n\t *\r\n\t * \\return\tReference to the radius of the sphere\r\n\t */\r\n\tReal& r() { return m_r; }\r\n\r\n\t/**\r\n\t * \\brief\tconstructs the smallest enclosing sphere a given pointset\r\n\t *\r\n\t * \\param p vertices of the points\r\n\t */\r\n\tvoid setPoints(const std::vector<Vector3r>& p)\r\n\t{\r\n\t\t//remove duplicates\r\n\t\tstd::vector<Vector3r> v(p);\r\n\t\tstd::sort(v.begin(), v.end(), [](const Vector3r& a, const Vector3r& b)\r\n\t\t\t{\r\n\t\t\t\tif (a[0] < b[0]) return true;\r\n\t\t\t\tif (a[0] > b[0]) return false;\r\n\t\t\t\tif (a[1] < b[1]) return true;\r\n\t\t\t\tif (a[1] > b[1]) return false;\r\n\t\t\t\treturn (a[2] < b[2]);\r\n\t\t\t});\r\n\t\tv.erase(std::unique(v.begin(), v.end(), [](Vector3r& a, Vector3r& b) { return a.isApprox(b); }), v.end());\r\n\r\n\t\tVector3r d;\r\n\t\tconst int n = int(v.size());\r\n\r\n\t\t//generate random permutation of the points and perturb the points by epsilon to avoid corner cases\r\n\t\tconst Real epsilon = 1.0e-6;\r\n\t\tfor (int i = n - 1; i > 0; i--)\r\n\t\t{\r\n\t\t\tconst Vector3r epsilon_vec = epsilon * Vector3r::Random();\r\n\t\t\tconst int j = static_cast<int>(floor(i * Real(rand()) / RAND_MAX));\r\n\t\t\td = v[i] + epsilon_vec;\r\n\t\t\tv[i] = v[j] - epsilon_vec;\r\n\t\t\tv[j] = d;\r\n\t\t}\r\n\r\n\t\tBoundingSphere S = BoundingSphere(v[0], v[1]);\r\n\r\n\t\tfor (int i = 2; i < n; i++)\r\n\t\t{\r\n\t\t\t//SES0\r\n\t\t\td = v[i] - S.x();\r\n\t\t\tif (d.squaredNorm() > S.r()* S.r())\r\n\t\t\t\tS = ses1(i, v, v[i]);\r\n\t\t}\r\n\r\n\t\tm_x = S.m_x;\r\n\t\tm_r = S.m_r + epsilon;\t//add epsilon to make sure that all non-perturbed points are inside the sphere\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\t\tintersection test for two spheres\r\n\t *\r\n\t * \\param other other sphere to be tested for intersection\r\n\t * \\return\t\treturns true when this sphere and the other sphere are intersecting\r\n\t */\r\n\tbool overlaps(BoundingSphere const& other) const\r\n\t{\r\n\t\tconst Real rr = m_r + other.m_r;\r\n\t\treturn (m_x - other.m_x).squaredNorm() < rr * rr;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\t\ttests whether the given sphere other is contained in the sphere\r\n\t *\r\n\t * \\param\t\tother bounding sphere\r\n\t * \\return\t\treturns true when the other is contained in this sphere or vice versa\r\n\t */\r\n\tbool contains(BoundingSphere const& other) const\r\n\t{\r\n\t\tconst Real rr = r() - other.r();\r\n\t\treturn (x() - other.x()).squaredNorm() < rr * rr;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\t\ttests whether the given point other is contained in the sphere \r\n\t *\r\n\t * \\param\t\tother 3d coordinates of a point\r\n\t * \\return\t\treturns true when the point is contained in the sphere\r\n\t */\r\n\tbool contains(Vector3r const& other) const\r\n\t{\r\n\t\treturn (x() - other).squaredNorm() < m_r * m_r;\r\n\t}\r\n\r\nprivate:\r\n\r\n\t/**\r\n\t * \\brief\t\tconstructs the smallest enclosing sphere for n points with the points q1, q2, and q3 on the surface of the sphere\r\n\t *\r\n\t * \\param n\t\tnumber of points\r\n\t * \\param p\t\tvertices of the points\r\n\t * \\param q1\t3d coordinates of a point on the surface\r\n\t * \\param q2\t3d coordinates of a second point on the surface\r\n\t * \\param q3\t3d coordinates of a third point on the surface\r\n\t * \\return\t\tsmallest enclosing sphere\r\n\t */\r\n\tBoundingSphere ses3(int n, std::vector<Vector3r>& p, Vector3r& q1, Vector3r& q2, Vector3r& q3)\r\n\t{\r\n\t\tBoundingSphere S(q1, q2, q3);\r\n\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t{\r\n\t\t\tVector3r d = p[i] - S.x();\r\n\t\t\tif (d.squaredNorm() > S.r()* S.r())\r\n\t\t\t\tS = BoundingSphere(q1, q2, q3, p[i]);\r\n\t\t}\r\n\t\treturn S;\r\n\t}\r\n\r\n\t/**\r\n\t * \\brief\t\tconstructs the smallest enclosing sphere for n points with the points q1 and q2 on the surface of the sphere\r\n\t *\r\n\t * \\param n\t\tnumber of points\r\n\t * \\param p\t\tvertices of the points\r\n\t * \\param q1\t3d coordinates of a point on the surface\r\n\t * \\param q2\t3d coordinates of a second point on the surface\r\n\t * \\return\t\tsmallest enclosing sphere\r\n\t */\r\n\tBoundingSphere ses2(int n, std::vector<Vector3r>& p, Vector3r& q1, Vector3r& q2)\r\n\t{\r\n\t\tBoundingSphere S(q1, q2);\r\n\r\n\t\tfor (int i = 0; i < n; i++)\r\n\t\t{\r\n\t\t\tVector3r d = p[i] - S.x();\r\n\t\t\tif (d.squaredNorm() > S.r()* S.r())\r\n\t\t\t\tS = ses3(i, p, q1, q2, p[i]);\r\n\t\t}\r\n\t\treturn S;\r\n\t}\r\n\t/**\r\n\t * \\brief\t\tconstructs the smallest enclosing sphere for n points with the point q1 on the surface of the sphere\r\n\t *\r\n\t * \\param n\t\tnumber of points\r\n\t * \\param p\t\tvertices of the points\r\n\t * \\param q1\t3d coordinates of a point on the surface\r\n\t * \\return\t\tsmallest enclosing sphere\r\n\t */\r\n\tBoundingSphere ses1(int n, std::vector<Vector3r>& p, Vector3r& q1)\r\n\t{\r\n\t\tBoundingSphere S(p[0], q1);\r\n\r\n\t\tfor (int i = 1; i < n; i++)\r\n\t\t{\r\n\t\t\tVector3r d = p[i] - S.x();\r\n\t\t\tif (d.squaredNorm() > S.r()* S.r())\r\n\t\t\t\tS = ses2(i, p, q1, p[i]);\r\n\t\t}\r\n\t\treturn S;\r\n\t}\r\n\r\n\tVector3r m_x;\r\n\tReal m_r;\r\n};\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "be3455af427299cf428eab4a4dcd53a2469b2842", "size": 7718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_stars_repo_name": "kennychufk/Discregrid", "max_stars_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_issues_repo_name": "kennychufk/Discregrid", "max_issues_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discregrid/include/Discregrid/acceleration/bounding_sphere.hpp", "max_forks_repo_name": "kennychufk/Discregrid", "max_forks_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1400651466, "max_line_length": 126, "alphanum_fraction": 0.5975641358, "num_tokens": 2500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5749781332147353}}
{"text": "#include <iostream>\n\n#include <El.hpp>\n#include <boost/mpi.hpp>\n#include <boost/format.hpp>\n\n#define SKYLARK_NO_ANY\n#include <skylark.hpp>\n\nconst int m = 50000;\nconst int n = 500;\n\n\ntemplate<typename MatrixType, typename RhsType, typename SolType>\nvoid check_solution(const MatrixType &A, const RhsType &b, const SolType &x, \n    const RhsType &r0,\n    double &res, double &resAtr, double &resFac) {\n    RhsType r(b);\n    skylark::base::Gemv(El::NORMAL, -1.0, A, x, 1.0, r);\n    res = skylark::base::Nrm2(r);\n\n    SolType Atr(x.Height(), x.Width(), x.Grid());\n    skylark::base::Gemv(El::TRANSPOSE, 1.0, A, r, 0.0, Atr);\n    resAtr = skylark::base::Nrm2(Atr);\n\n    skylark::base::Axpy(-1.0, r0, r);\n    RhsType dr(b);\n    skylark::base::Axpy(-1.0, r0, dr);\n    resFac = skylark::base::Nrm2(r) / skylark::base::Nrm2(dr);\n}\n\ntemplate<typename MatrixType, typename RhsType, typename SolType>\nvoid experiment() {\n    typedef MatrixType matrix_type;\n    typedef RhsType rhs_type;\n    typedef SolType sol_type;\n\n    double res, resAtr, resFac;\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    skylark::base::context_t context(23234);\n\n    // Setup problem and righthand side\n    // Using Skylark's uniform generator (as opposed to Elemental's)\n    // will insure the same A and b are generated regardless of the number\n    // of processors.\n    matrix_type A, b;\n    skylark::base::UniformMatrix(A, m, n, context);\n    skylark::base::UniformMatrix(b, m, 1, context);\n\n    sol_type x(n,1);\n    rhs_type r(b);\n\n    boost::mpi::timer timer;\n    double telp;\n\n    // Solve using Elemental. Note: Elemental only supports [MC,MR]...\n    El::DistMatrix<double> A1 = A, b1 = b, x1;\n    timer.restart();\n    El::LeastSquares(El::NORMAL, A1, b1, x1);\n    telp = timer.elapsed();\n    x = x1;\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Elemental:\\t\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \"\\t\\t\\t\\t\\t\\t\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n    double res_opt = res;\n\n    // The following computes the optimal residual (r^\\star in the logs)\n    skylark::base::Gemv(El::NORMAL, -1.0, A, x, 1.0, r);\n\n#if SKYLARK_HAVE_FFTW || SKYLARK_HAVE_FFTWF || SKYLARK_HAVE_KISSFFT\n    // Solve using Sylark\n    timer.restart();\n    skylark::nla::FasterLeastSquares(El::NORMAL, A, b, x, context);\n    telp = timer.elapsed();\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Skylark:\\t\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \" (x \" << boost::format(\"%.5f\") % (res / res_opt) << \")\"\n                  << \"\\t||r - r*||_2 / ||b - r*||_2 = \" << boost::format(\"%.2e\") % resFac\n                  << \"\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n\n    // Approximately solve using Sylark\n    timer.restart();\n    skylark::nla::ApproximateLeastSquares(El::NORMAL, A, b, x, context);\n    telp = timer.elapsed();\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Skylark (approximate):\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \" (x \" << boost::format(\"%.5f\") % (res / res_opt) << \")\"\n                  << \"\\t||r - r*||_2 / ||b - r*||_2 = \" << boost::format(\"%.2e\") % resFac\n                  << \"\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n#else\n    std::cout << \"You need to have Skylark supporting FFTW or FFTWF \" \n              << \"to solve with skylark least_squares.cpp\"\n              << std::endl;\n#endif\n}\n\n\n\nint main(int argc, char** argv) {\n\n    El::Initialize(argc, argv);\n\n    boost::mpi::communicator world;\n    int rank = world.rank();\n\n    if (rank == 0)\n        std::cout << \"Matrix: [VC,STAR], Rhs: [VC,STAR], Sol: [STAR,STAR]\\n\\n\";\n    experiment<El::DistMatrix<double, El::VC, El::STAR>,\n               El::DistMatrix<double, El::VC, El::STAR>,\n               El::DistMatrix<double, El::STAR, El::STAR> > ();\n\n    if (rank == 0)\n        std::cout << \"\\nMatrix: [MC,MR], Rhs: [MC,MR], Sol: [MC,MR]\\n\\n\";\n    experiment<El::DistMatrix<double>, El::DistMatrix<double>,\n               El::DistMatrix<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "f47a46345005da417ca91e17bf8ec3f8d039509d", "size": 4554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/least_squares.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/least_squares.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/least_squares.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.9850746269, "max_line_length": 89, "alphanum_fraction": 0.5450153711, "num_tokens": 1451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.5749194018032826}}
{"text": "/*!\n * \\file hnf.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2020 Jun Yoshida.\n * The project is released under the 2-clause BSD License.\n * \\date August, 2020: created\n */\n\n#pragma once\n\n#include <valarray>\n#include <tuple>\n#include <cmath>\n#include <Eigen/Dense>\n\n#include \"utils.hpp\"\n#include \"hnf_impl_lll.hpp\"\n\n//* For debug\n#include \"debug/debug.hpp\"\n// */\n\nnamespace khover {\n\n/*!\n * Computing the Hermite normal form of a given matrix.\n * The original \"pseudo-code\" is found in the paper\n *   > George Havas, Bohdan S. Majewski & Keith R. Matthews (1998) Extended GCD and Hermite Normal Form Algorithms via Lattice Basis Reduction, Experimental Mathematics, 7:2, 125-136, DOI: 10.1080/10586458.1998.10504362\n * This function also applies the transformation on the target matrix and its adjoint transformation to given matrices.\n * Usage:\n * \\code\n *   // Compute a row echelon form.\n *   auto u0 = u; auto m0 = m; auto v0 = v;\n *   hnf_LLL<typename khover::rowops>(m,std::tie(u),std::tie(v));\n *   assert(is_rowhnf(m));\n *   assert(u*m == u0*m0);\n *   assert(u*v == u0*v0);\n * \\endcode\n *\n * \\code\n *   // Compute a column echelon form.\n *   auto u0 = u; auto m0 = m; auto v0 = v;\n *   hnf_LLL<typename khover::colops>(m,std::tie(u),std::tie(v));\n *   assert(is_colhnf(m));\n *   assert(m*u == m0*u0);\n *   assert(v*u == v0*u0);\n * \\endcode\n * \\tparam Ops A collection of elementary operations; \\see{khover::rowops}, \\see{khover::colops}.\n * \\param m The target matrix to be transformed into its Hermite normal form.\n * \\param us A tuple of matrices subject to the adjoint transformation.\n * \\param vs A tuple of matrices subject to the transformation.\n * \\return If success, the rank of the given matrix over Q (the field of rationals).\n */\ntemplate<\n    class Ops,\n    class MT,int MR, int MC, int MOpt, int MRMax, int MCMax,\n    class...UTs, class...VTs\n    >\nstd::optional<std::size_t> hnf_LLL(\n    Eigen::Matrix<MT,MR,MC,MOpt,MRMax,MCMax> &m,\n    std::tuple<UTs&...> us,\n    std::tuple<VTs&...> vs\n    ) noexcept\n{\n    static_assert(\n        std::conjunction<typename khover::is_pubbase_of_template<Eigen::MatrixBase,UTs>...>::value,\n        \"Matrices U contain a class not derived from Eigen::MatrixBase\");\n    static_assert(\n        std::conjunction<typename khover::is_pubbase_of_template<Eigen::MatrixBase,VTs>...>::value,\n        \"Matices V contain a class not derived from Eigen::MatrixBase\");\n    static_assert(\n        std::conjunction<std::bool_constant<(UTs::Flags & Eigen::LvalueBit) != 0>...>::value,\n        \"Matrices U contain read-only variables\");\n    static_assert(\n        std::conjunction<std::bool_constant<(VTs::Flags & Eigen::LvalueBit) != 0>...>::value,\n        \"Matrices V contain read-only variables\");\n\n    std::size_t nvecs = Ops::dual_t::size(m);\n\n    if (!foldl_tuple(true, us, [nvecs](bool b, auto& u) { return b && Ops::size(u) >= nvecs; })) {\n        ERR_MSG(\"Matricies U with invalid sizes.\");\n        return std::nullopt;\n    }\n\n    if (!foldl_tuple(true, vs, [nvecs](bool b, auto& v) { return b && Ops::dual_t::size(v) >= nvecs; })) {\n        ERR_MSG(\"Matricies V with invalid sizes.\");\n        return std::nullopt;\n    }\n\n    // Nothing to do on empty matrices\n    if (nvecs == 0 || Ops::size(m) == 0) {\n        return std::make_optional(0);\n    }\n\n    // Ensure the pivot of the last vector to be non-negative.\n    std::size_t l = Ops::find_nonzero(\n        m, nvecs-1,\n        [&m,&us,&vs](std::size_t l, auto x) {\n            if (std::signbit(x)) {\n                Ops::scalar(m,0,-1);\n                for_each_tuple(us, [](auto& u){ Ops::dual_t::scalar(u,0,-1); });\n                for_each_tuple(vs, [](auto& v){ Ops::scalar(v,0,-1); });\n            }\n        });\n\n    // If the given matrix consists of a single vector, then all the step is finished.\n    if (nvecs == 1) {\n        return l < Ops::size(m) ? 1 : 0;\n    }\n\n    _impl_LLL::Lambda_t lambda(nvecs);\n\n    // The index of the vector that we currently focus on.\n    std::size_t cur = nvecs - 1;\n    // The rank of the span of vectors below cursor.\n    std::size_t rk = 0;\n    // Flag whether the vector just below the cursor is non-zero or not.\n    bool is_below_nz = false;\n\n    // Proceed the algorithm on the first k rows.\n    while (cur > 0) {\n        //DBG_MSG(\"cur=\" << cur << \"\\n\" << \"rk = \" << rk << \"\\n\" << m);\n\n        auto howswap = _impl_LLL::reduce<Ops,false>(cur-1, cur, m, us, vs, lambda);\n\n        if (howswap & _impl_LLL::HowSwap::ShouldSwap) {\n            _impl_LLL::swap<Ops>(cur-1, m, us, vs, lambda);\n            if (cur+1 < nvecs) {\n                ++cur;\n                if (is_below_nz) {\n                    --rk;\n                    is_below_nz = rk > 0;\n                }\n            }\n        }\n        else if (howswap & _impl_LLL::HowSwap::ZeroReducer) {\n            --cur;\n            is_below_nz = false;\n        }\n        else {\n            for (std::size_t i = cur+1; i < nvecs; ++i)\n                _impl_LLL::reduce<Ops,true>(cur-1, i, m, us, vs, lambda);\n            --cur;\n            ++rk;\n            is_below_nz = true;\n        }\n    }\n\n    if (rk > 0) {\n        return rk+1;\n    }\n    else {\n        return Ops::find_nonzero(m, 0, [](auto,auto){})\n            < Ops::size(m)\n              ? 1 : 0;\n    }\n}\n\n}\n", "meta": {"hexsha": "98e0caa989995ac4988f71e7869e53758a99af0e", "size": 5264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/hnf.hpp", "max_stars_repo_name": "Junology/khover", "max_stars_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T06:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T06:50:39.000Z", "max_issues_repo_path": "src/hnf.hpp", "max_issues_repo_name": "Junology/khover", "max_issues_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hnf.hpp", "max_forks_repo_name": "Junology/khover", "max_forks_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9, "max_line_length": 219, "alphanum_fraction": 0.5809270517, "num_tokens": 1542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.574919395710084}}
{"text": "/**\n *  testAbst.cpp\n *\n *  Test abstraction by using a car kinematics model.\n *\n *  Created by Yinan Li on Nov. 14, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <cmath>\n#include <sys/stat.h>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/grid.h\"\n#include \"src/definitions.h\"\n#include \"src/abstraction.hpp\"\n#include \"src/hdf5io.h\"\n\n\n/* user defined dynamics */\nstruct car_ode {\n    rocs::Rn u;\n    car_ode (const rocs::Rn param): u (param) {}\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]*std::cos(x[2]);\n\tdxdt[1] = u[0]*std::sin(x[2]);\n\tdxdt[2] = u[1];\n    }\n};\n\nconst double h = 0.3;  // sampling time\nconst double dt = 0.001; //integration step size for odeint\n\nstruct carde { // discrete-time model (difference equation)\n    static const int n = 3;  // system dimension\n    static const int m = 2;\n    /**\n     * Discrete-time dynamics\n     * @param h sampling time\n     * @param x system state: [x,y,theta], n=3\n     * @param u control array (size of 2, velocity and steering angle)\n     * @param nu the number of different control values\n     */\n    template<typename S>\n    carde(S &dx, const S &x, rocs::Rn u) {\n\tif (std::fabs(u[0]) < 1e-6) { //v=0\n\t    dx[0] = x[0];\n\t    dx[1] = x[1];\n\t    dx[2] = x[2] + u[1] * h;\n\t} else if (std::fabs(u[1]) < 1e-6) { //w=0\n\t    dx[0] = x[0] + u[0]* cos(x[2])*h;\n\t    dx[1] = x[1] + u[0]* sin(x[2])*h;\n\t    dx[2] = x[2];\n\t} else { //v,w not 0\n\t    dx[0] = x[0] + u[0]/u[1]*2*sin(u[1]*h/2.)*cos(x[2]+u[1]*h/2.);\n\t    dx[1] = x[1] + u[0]/u[1]*2*sin(u[1]*h/2.)*sin(x[2]+u[1]*h/2.);\n\t    dx[2] = x[2] + u[1] * h;\n\t}\n    }\n    \n}; // struct carde\n\n\nstruct twoagent {\n    static const int n = 3;  // system dimension\n    static const int nu = 2;  // control dimension\n    rocs::ivec d{rocs::interval(-0.8, 0.8),\n\t\t rocs::interval(-0.8, 0.8)};\n\n    /* template constructor\n     * @param[out] dx\n     * @param[in] x = [xr, yr, psir]\n     * @param u = [v, w]\n     * @param d = [v', w']\n     */\n    template<typename S>\n    twoagent(S *dx, const S *x, rocs::Rn u) {\n\tdx[0] = -u[0] + d[0]*cos(x[2]) + u[1]*x[1];\n\tdx[1] = d[0]*sin(x[2]) - u[1]*x[0];\n\tdx[2] = d[1] - u[1];\n    }\n};\n\n\nint main()\n{\n    /* Config */\n    clock_t tb, te;\n    boost::numeric::odeint::runge_kutta_cash_karp54<rocs::Rn> rk45;\n\n    /**\n     * Case I\n     */\n    /* Set the state and control space */\n    const int xdim = 3;\n    const int udim = 2;\n    \n    double xlb[] = {-3, -3, -M_PI};\n    double xub[] = {3, 3, M_PI};\n    double eta[] = {0.2, 0.2, 0.2};\n    \n    double ulb[] = {-1.0, -1.0};\n    double uub[] = {1.0, 1.0};\n    double mu[] = {0.3, 0.3};\n\n    /**\n     * Define the two-agent system\n     */\n    double t = 0.3;\n    double delta = 0.01;\n    /* parameters for computing the flow */\n    int kmax = 5;\n    double tol = 0.01;\n    double alpha = 0.5;\n    double beta = 2;\n    rocs::params controlparams(kmax, tol, alpha, beta);\n    rocs::CTCntlSys<twoagent> safety(\"collision-free\", t,\n    \t\t\t\t     twoagent::n, twoagent::nu,\n    \t\t\t\t     delta, &controlparams);\n\n    safety.init_workspace(xlb, xub);\n    safety.init_inputset(mu, ulb, uub);\n    safety.allocate_flows();\n\n    rocs::abstraction< rocs::CTCntlSys<twoagent> > abst(&safety);\n    abst.init_state(eta, xlb, xub);\n    std::cout << \"# of in-domain nodes: \" << abst._x._nv << '\\n';\n    /**\n     * Assign 1 to the target invariant set and 0 to others.\n     * Mark 0 for any box intersect or inside the cylinder: x^2+y^2<=rmin^2, any phi.\n     * The invariant set is the region outside of the cylinder.\n     */\n    auto inv_set = [&abst, &eta](size_t i) {\n    \t\t       const double rmin = 1.21;\n    \t\t       std::vector<double> x(abst._x._dim);\n    \t\t       abst._x.id_to_val(x, i);\n    \t\t       double xl = x[0] - eta[0]/2.;\n    \t\t       double xr = x[0] + eta[0]/2.;\n    \t\t       double yl = x[1] - eta[1]/2.;\n    \t\t       double yr = x[1] + eta[1]/2.;\n    \t\t       double xsqr = (xr*xr) > (xl*xl) ? (xl*xl) : (xr*xr);\n    \t\t       double ysqr = (yr*yr) > (yl*yl) ? (yl*yl) : (yr*yr);\n    \t\t       if(xsqr + ysqr < rmin*rmin)\n    \t\t\t   return 0;\n    \t\t       else\n    \t\t\t   return 1;\n    \t\t   };\n    abst.assign_labels(inv_set);\n    abst.assign_label_outofdomain(1); //out of domain is safe\n    \n    std::string transfile = \"abstca_0.2-0.2-0.2.h5\";\n    struct stat buffer;\n    if(stat(transfile.c_str(), &buffer) == 0) {\n    \t/* Read from a file */\n    \tstd::cout << \"Reading transitions...\\n\";\n    \trocs::h5FileHandler transRdr(transfile, H5F_ACC_RDONLY);\n    \ttb = clock();\n    \ttransRdr.read_transitions(abst._ts);\n    \tte = clock();\n    } else {\n    \tstd::cout << \"No transition file found. Computing transitions...\\n\";\n    \t/* Robustness margins */\n    \tdouble e1[] = {0,0,0};\n    \tdouble e2[] = {0,0,0};\n    \ttb = clock();\n    \tabst.assign_transitions(e1, e2);\n    \tte = clock();\n    \t/* Write transitions to file */\n    \trocs::h5FileHandler transWtr(transfile, H5F_ACC_TRUNC);\n    \ttransWtr.write_transitions(abst._ts);\n    }\n    float time = (float)(te - tb)/CLOCKS_PER_SEC;\n    std::cout << \"Time of reading/computing abstraction: \" << time << '\\n';\n    std::cout << \"# of all nodes: \" << abst._ts._nx << '\\n';\n    std::cout << \"# of actions: \" << abst._ts._nu << '\\n';\n    std::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n\n\n    /**\n     * Case II\n     */\n    // /* Set the state space */\n    // const int xdim = 3;\n    // const int udim = 2;\n    // const double theta = 3.5;\n    // double xlb[] = {0, 0, -theta};\n    // double xub[] = {10, 10, theta};\n    // double eta[] = {0.2, 0.2, 0.2};\n    // /* Set the control values */\n    // double ulb[] = {-1.0, -1.0};\n    // double uub[] = {1.0, 1.0};\n    // double mu[] = {0.3, 0.3};\n    // /* Define the control system */\n    // rocs::DTCntlSys<carde> car(\"DBA\", h, carde::n, carde::m);\n    // car.init_workspace(xlb, xub);\n    // car.init_inputset(mu, ulb, uub);\n    \n    // rocs::abstraction< rocs::DTCntlSys<carde> > abst(&car);\n    // abst.init_state(eta, xlb, xub);\n    // std::cout << \"# of in-domain nodes: \" << abst._x._nv << '\\n';\n    // /* Assign the label of avoid area to -1 */\n    // rocs::UintSmall nAvoid = 4;\n    // double obs[4][4] = {\n    // \t{1.6, 5.7, 4.0, 5.0},\n    // \t{3.0, 5.0, 5.0, 8.0},\n    // \t{4.3, 5.7, 1.8, 4.0},\n    // \t{5.7, 8.5, 1.8, 2.5}\n    // };\n    // auto label_avoid = [&obs, &nAvoid, &abst, &eta](size_t i) {\n    // \t\t     std::vector<double> x(abst._x._dim);\n    // \t\t     abst._x.id_to_val(x, i);\n    // \t\t     double c1= eta[0]/2.0+1e-10;\n    // \t\t     double c2= eta[1]/2.0+1e-10;\n    // \t\t     for(size_t i = 0; i < nAvoid; ++i) {\n    // \t\t\t if ((obs[i][0]-c1) <= x[0] && x[0] <= (obs[i][1]+c1) &&\n    // \t\t\t     (obs[i][2]-c2) <= x[1] && x[1] <= (obs[i][3]+c2))\n    // \t\t\t     return -1;\n    // \t\t     }\n    // \t\t     return 0;\n    // \t\t };\n    // abst.assign_labels(label_avoid);\n    // abst.assign_label_outofdomain(-1);\n    // std::vector<size_t> obstacles;\n    // for (size_t i = 0; i < abst._x._nv; ++i) {\n    // \tif (abst._labels[i] < 0)\n    // \t    obstacles.push_back(i);\n    // }\n\n    // /* Compute/Read abstraction */\n    // float tabst;\n    // std::string transfile = \"abstfull_0.2-0.2-0.2.h5\";\n    // struct stat buffer;\n    // if(stat(transfile.c_str(), &buffer) == 0) {\n    // \t/* Read from a file */\n    // \tstd::cout << \"Reading transitions...\\n\";\n    // \trocs::h5FileHandler transRdr(transfile, H5F_ACC_RDONLY);\n    // \ttb = clock();\n    // \ttransRdr.read_transitions(abst._ts);\n    // \tte = clock();\n    // } else {\n    // \tstd::cout << \"No transition file found. Computing transitions...\\n\";\n    // \t/* Robustness margins */\n    // \tdouble e1[] = {0,0,0};\n    // \tdouble e2[] = {0,0,0};\n    // \ttb = clock();\n    // \tabst.assign_transitions(e1, e2);\n    // \tte = clock();\n    \t\n    // \t/* Write abstraction to file */\n    // \trocs::h5FileHandler transWtr(transfile, H5F_ACC_TRUNC);\n    // \ttransWtr.write_transitions(abst._ts);\n    // }\n    // tabst = (float)(te - tb)/CLOCKS_PER_SEC;\n    // std::cout << \"Time of reading/computing abstraction: \" << tabst << '\\n';\n    // std::cout << \"# of all nodes: \" << abst._ts._nx << '\\n';\n    // std::cout << \"# of actions: \" << abst._ts._nu << '\\n';\n    // std::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n\n\n    /* Test */\n    size_t na = abst._ts._nu;\n    size_t nx = abst._ts._nx;\n    size_t si, sk, k;\n    bool suc = 0;\n    int np;    \n    \n    \n    /* Test post-pre consistency */\n    std::cout << \"Checking post-pre consistency...\\n\";\n    for(size_t i = 0; i < nx; ++i) {\n\tfor(size_t j = 0; j < na; ++j) {\n\t    si = abst._ts._ptrpost[i*na+j];\n\t    for(size_t p=si; p<si+abst._ts._npost[i*na+j]; ++p) {\n\t\tk = abst._ts._idpost[p];\n\t\t/* Test if the pre of post by j contains i */\n\t\tsuc = 0;\n\t\tsk = abst._ts._ptrpre[k*na+j];\n\t\t// /********** logging **********/\n\t\t// if(i == 0 && j == 16 && k == 0) {\n\t\t//     std::cout << \"The predecessors of \" << k << \" with \" << j << \": \";\n\t\t// }\n\t\t// /********** logging **********/\n\t\tfor(size_t pp=sk; pp<sk+abst._ts._npre[k*na+j]; ++pp) {\n\t\t    // /********** logging **********/\n\t\t    // if(i == 0 && j == 16 && k == 0) {\n\t\t    // \tstd::cout << \"idpre[\"<< pp << \"]=\"\n\t\t    // \t\t  << abst._ts._idpre[pp] << '\\n';\n\t\t    // }\n\t\t    // /********** logging **********/\n\t\t    if(abst._ts._idpre[pp] == i) {\n\t\t\tsuc = 1;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif(i == 0 && j == 16 && k == 0) {\n\t\t    std::cout << '\\n';\n\t\t}\n\t\tif(!suc) {//two cases: npre(k,j)=0 or no i in npre(k, j)\n\t\t    std::cout << \"Post and pre transitions are inconsistent \"\n\t\t\t      << i << \"->(\" << j << \")->\" << k << '\\n';\n\t\t    return -1;\n\t\t}\n\t\t    \n\t    }\n\t}\n    }\n    std::cout << \"Every post transition has its corresponding pre transition.\\n\";\n\n    for(size_t i = 0; i < nx; ++i) {\n\tfor(size_t j = 0; j < na; ++j) {\n\t    si = abst._ts._ptrpre[i*na+j];\n\t    for(size_t p=si; p<si+abst._ts._npre[i*na+j]; ++p) {\n\t\tk = abst._ts._idpre[p];\n\t\t/* Test if the post of pre by j contains i */\n\t\tsuc = 0;\n\t\tsk = abst._ts._ptrpost[k*na+j];\n\t\tfor(size_t pp=sk; pp<sk+abst._ts._npost[k*na+j]; ++pp) {\n\t\t    if(abst._ts._idpost[pp] == i) {\n\t\t\tsuc = 1;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\t\tif(!suc) {//two cases: npost(k,j)=0 or no i in npost(k, j)\n\t\t    std::cout << \"Post and pre transitions are inconsistent \"\n\t\t\t      << k << \"->(\" << j << \")->\" << i << '\\n';\n\t\t    return -1;\n\t\t}\n\t\t    \n\t    }\n\t}\n    }\n    std::cout << \"Every pre transition has its corresponding post transition.\\n\";\n\n\n    // /* Test reachable set computation */\n    // std::cout << \"Checking post transitions by rechable set computation...\\n\";\n    // rocs::Rn x(xdim);\n    // rocs::Rn u(udim);\n    // rocs::Rn xpost(xdim);\n    // rocs::ivec box(xdim);\n    // std::vector<rocs::ivec> reachset(na, rocs::ivec(xdim));\n    // // std::vector<rocs::Rn> corners(std::pow(2, xdim), rocs::Rn(xdim));\n    // rocs::Rn corner(xdim);\n    // int quo, rem;\n    // rocs::ivec margin{rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL),\n    // \t\t      rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL),\n    // \t\t      rocs::interval(-rocs::EPSIVAL, rocs::EPSIVAL)};\n    // rocs::ivec yt(xdim);\n    // for(size_t i = 0; i < nx; ++i) {\n    // \t// std::cout << \"State x= \" << '(' << x[0] << ',' << x[1] << ',' << x[2] << \"):\\n\";\n    // \tif(i < abst._x._nv) { //belongs to xgrid\n    // \t    /* Compute the reachable set */\n    // \t    abst._x.id_to_val(x, i); //x is the center of the box i\n    // \t    for(int d = 0; d < xdim; ++d)\n    // \t\tbox.setval(d, rocs::interval(x[d]-eta[d]/2., x[d]+eta[d]/2.));\n    // \t    car.get_reach_set(reachset, box);\n\t    \n    // \t    /* Test valid control inputs */\n    // \t    for(size_t j = 0; j < na; ++j) {\n    // \t\tif(abst._ts._npost[i*na+j] > 0) {\n    // \t\t    car._ugrid.id_to_val(u, j); //get control values\n    // \t\t    /* Test if the reachable set covers ode solutions of all corners */\n    // \t\t    for(int k = 0; k < std::pow(2, xdim); ++k) {\n    // \t\t\tquo = k;\n    // \t\t\tfor(int d = 0; d < xdim; ++d) {\n    // \t\t\t    if(quo % 2) {\n    // \t\t\t\tcorner[d] = x[d]+eta[d]/2.; //upper bound\n    // \t\t\t    } else {\n    // \t\t\t\tcorner[d] = x[d]-eta[d]/2.; //lower bound\n    // \t\t\t    }\n    // \t\t\t    quo /= 2;\n    // \t\t\t}\n    // \t\t\t// std::cout << \"Corner \"\n    // \t\t\t// \t  << '(' << corner[0] << ',' << corner[1] << ',' << corner[2] << \")\\n\";\n    // \t\t\tboost::numeric::odeint::integrate_const(rk45, car_ode(u), corner, 0.0, h, dt);\n    // \t\t\tyt = reachset[j] + margin;\n    // \t\t\tif(!yt.isin(corner)) {\n    // \t\t\t    std::cout << \"The reachable set is incorrect with u=\"\n    // \t\t\t\t      << '(' << u[0] << ',' << u[1] << \"):\"\n    // \t\t\t\t      << '(' << corner[0] << ',' << corner[1] << ',' << corner[2] << ')'\n    // \t\t\t\t      << \" is not in \" << yt << '\\n'\n    // \t\t\t\t      << \"Test terminates.\\n\";\n    // \t\t\t    return -1;\n    // \t\t\t}\n    // \t\t    }\n    // \t\t    /* Test if all post nodes are in the reachable set (soundness) */\n    // \t\t    si = abst._ts._ptrpost[i*na+j];\n    // \t\t    for(size_t p = si; p<si+abst._ts._npost[i*na+j]; ++p) {\n    // \t\t\tabst._x.id_to_val(xpost, abst._ts._idpost[p]); //xpost: post node center\n    // \t\t\tfor(int d = 0; d < xdim; ++d) //box: post interval centered at xpost\n    // \t\t\t    box.setval(d, rocs::interval(xpost[d]-eta[d]/2., xpost[d]+eta[d]/2.));\n    // \t\t\tif(reachset[j].isout(box)) { //box and reachset[j] should intersect\n    // \t\t\t    std::cout << \"Post transition for xid,uid=\" << i << ',' << j\n    // \t\t\t\t      << \" is incorrect.\\n\"\n    // \t\t\t\t      << \"Test terminates.\\n\";\n    // \t\t\t    return -1;\n    // \t\t\t}\n    // \t\t    }\n    // \t\t}\n    // \t    }//end for control values\n    // \t} else { //out-of-domain node\n    // \t    std::cout << \"Checking the out-of-domain node...\\n\";\n    // \t}\n    // }\n\n    return 0;\n}\n", "meta": {"hexsha": "1fa0c18d980dbd2a709253b1c5346245d49d096d", "size": 13885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/testAbst.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": "test/testAbst.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": "test/testAbst.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": 33.0595238095, "max_line_length": 91, "alphanum_fraction": 0.4940583363, "num_tokens": 4933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5749193844639304}}
{"text": "// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2015 Chris Sweeney (cmsweeney@cs.ucsb.edu)\n// Copyright (c) 2016 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_NUMERIC_L1_SOLVER_ADMM_HPP\n#define OPENMVG_NUMERIC_L1_SOLVER_ADMM_HPP\n\n#include <Eigen/Core>\n#ifdef EIGEN_MPL2_ONLY\n#include <Eigen/SparseLU>\n#else\n#include <Eigen/Cholesky>\n#include <Eigen/SparseCholesky>\n#endif\n\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n\nnamespace openMVG {\n\n// These are template overrides that allow the sparse linear solvers to work\n// with sparse or dense matrices. The sparseView() method is not implemented for\n// Eigen::SparseMatrix.\nnamespace l1_solver_internal {\n\ntemplate <typename Linear_SolverT>\ninline void Compute\n(\n  const Eigen::SparseMatrix<double>& spd_mat,\n  Linear_SolverT * linear_solver\n)\n{\n  linear_solver->compute(spd_mat);\n}\n\ntemplate <typename Linear_SolverT>\ninline void Compute\n(\n  const Eigen::MatrixXd& spd_mat,\n  Linear_SolverT * linear_solver\n)\n{\n  linear_solver->compute(spd_mat.sparseView());\n}\n\n}  // namespace l1_solver_internal\n\n// A L1 norm approximation solver. This class will attempt to solve the\n// problem: || A * x - b || under L1-norm (as opposed to L2 i.e. \"least-squares\"\n// norm). This problem can be solved with the alternating direction method of\n// multipliers (ADMM) as a least unsquared deviations minimizer. A full\n// description of the method, including how to use ADMM for L1 minimization can\n// be found in \"Distributed Optimization and Statistical Learning via the\n// Alternating Direction Method of Multipliers\" by Boyd et al, Foundations and\n// Trends in Machine Learning (2012). The paper can be found at:\n//   https://web.stanford.edu/~boyd/papers/pdf/admm_distr_stats.pdf\n//\n// ADMM can be much faster than interior point methods but convergence may be\n// slower. Generally speaking, ADMM solvers converge to good solutions in only a\n// few number of iterations, but can spend many iterations subsequently refining\n// the solution to obtain the global optimum. The speed improvements are because\n// the matrix A only needs to be factorized (by Cholesky decomposition) once, as\n// opposed to every iteration.\n//\n// This implementation is based off of the code found at:\n//   https://web.stanford.edu/~boyd/papers/admm/least_abs_deviations/lad.html\ntemplate <class MatrixType>\nclass L1Solver {\n public:\n  struct Options {\n    int max_num_iterations = 1000;\n    // Rho is the augmented Lagrangian parameter.\n    double rho = 1.0;\n    // Alpha is the over-relaxation parameter (typically between 1.0 and 1.8).\n    double alpha = 1.0;\n\n    double absolute_tolerance = 1e-4;\n    double relative_tolerance = 1e-2;\n  };\n\n  L1Solver\n  (\n    const Options& options,\n    const MatrixType& mat\n  )\n  : options_(options), a_(mat)\n  {\n    // Analyze the sparsity pattern once. Only the values of the entries will be\n    // changed with each iteration.\n    const MatrixType spd_mat = a_.transpose() * a_;\n    l1_solver_internal::Compute(spd_mat, &linear_solver_);\n  }\n\n  void SetMaxIterations\n  (\n    const int max_iterations\n  )\n  {\n    options_.max_num_iterations = max_iterations;\n  }\n\n  bool Status() const\n  {\n    return linear_solver_.info() == Eigen::Success;\n  }\n\n  // Solves ||Ax - b||_1 for the optimal L1 solution given an initial guess for\n  // x. To solve this we introduce an auxiliary variable y such that the\n  // solution to:\n  //        min   1 * y\n  //   s.t. [  A   -I ] [ x ] < [  b ]\n  //        [ -A   -I ] [ y ]   [ -b ]\n  // which is an equivalent linear program.\n  bool Solve\n  (\n    const Eigen::VectorXd& rhs,\n    Eigen::VectorXd* solution\n  )\n  {\n    // Since constructor was called before we check Compute status\n    if (linear_solver_.info() != Eigen::Success)\n    {\n      std::cerr << \"Cannot compute the matrix factorization\" << std::endl;\n      return false;\n    }\n\n    Eigen::VectorXd& x = *solution;\n    Eigen::VectorXd z(a_.rows()), u(a_.rows());\n    z.setZero();\n    u.setZero();\n\n    Eigen::VectorXd a_times_x(a_.rows()), z_old(z.size()), ax_hat(a_.rows());\n    // Precompute some convergence terms.\n    const double rhs_norm = rhs.norm();\n    const double primal_abs_tolerance_eps =\n      std::sqrt(a_.rows()) * options_.absolute_tolerance;\n    const double dual_abs_tolerance_eps =\n      std::sqrt(a_.cols()) * options_.absolute_tolerance;\n\n    for (int i = 0; i < options_.max_num_iterations; ++i)\n    {\n      // Update x.\n      x.noalias() = linear_solver_.solve(a_.transpose() * (rhs + z - u));\n      a_times_x.noalias() = a_ * x;\n      ax_hat.noalias() = options_.alpha * a_times_x;\n      ax_hat.noalias() += (1.0 - options_.alpha) * (z + rhs);\n\n      // Update z and set z_old.\n      std::swap(z, z_old);\n      z.noalias() = Shrinkage(ax_hat - rhs + u, 1.0 / options_.rho);\n\n      // Update u.\n      u.noalias() += ax_hat - z - rhs;\n\n      // Compute the convergence terms.\n      const double r_norm = (a_times_x - z - rhs).norm();\n      const double s_norm =\n        (-options_.rho * a_.transpose() * (z - z_old)).norm();\n      const double max_norm =\n        std::max({a_times_x.norm(), z.norm(), rhs_norm});\n      const double primal_eps =\n        primal_abs_tolerance_eps + options_.relative_tolerance * max_norm;\n      const double dual_eps =\n        dual_abs_tolerance_eps +\n        options_.relative_tolerance *\n          (options_.rho * a_.transpose() * u).norm();\n\n      // Log the result to the screen.\n      // std::ostringstream os;\n      // os << \"Iteration: \" << i << \"\\n\"\n      //   << \"R norm: \" << r_norm << \"\\n\"\n      //   << \"S norm: \" << s_norm << \"\\n\"\n      //   << \"Primal eps: \" << primal_eps << \"\\n\"\n      //   << \"Dual eps: \" << dual_eps << std::endl;\n      // std::cout << os.str() << std::endl;\n\n      // Determine if the minimizer has converged.\n      if (r_norm < primal_eps && s_norm < dual_eps)\n      {\n        return true;\n      }\n    }\n    return false;\n  }\n\n private:\n  Options options_;\n\n  // Matrix A where || Ax - b ||_1 is the problem we are solving.\n  MatrixType a_;\n\n  // Cholesky linear solver.\n#ifdef EIGEN_MPL2_ONLY\n  using Linear_Solver_T = Eigen::SparseLU<Eigen::SparseMatrix<double>>;\n#else\n  // Since our linear system will be a SPD matrix we can\n  // utilize the Cholesky factorization.\n  using Linear_Solver_T = Eigen::SimplicialLLT<Eigen::SparseMatrix<double>>;\n#endif\n  Linear_Solver_T linear_solver_;\n\n  Eigen::VectorXd Shrinkage\n  (\n    const Eigen::VectorXd& vec, const double kappa\n  ) const\n  {\n    Eigen::ArrayXd zero_vec(vec.size());\n    zero_vec.setZero();\n    return zero_vec.max( vec.array() - kappa) -\n           zero_vec.max(-vec.array() - kappa);\n  }\n};\n\n}  // namespace openMVG\n\n#endif  // OPENMVG_NUMERIC_L1_SOLVER_ADMM_HPP\n", "meta": {"hexsha": "0850f7962e3d26b931f7c468f54e7aafd46c0b37", "size": 6915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/l1_solver_admm.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/numeric/l1_solver_admm.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/numeric/l1_solver_admm.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": 30.8705357143, "max_line_length": 80, "alphanum_fraction": 0.6678235719, "num_tokens": 1825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5749193814173309}}
{"text": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#include <boost/compute.hpp>\n#include <boost/compute/types/complex.hpp>\n\n#include <clFFT.h>\n\n#include <ceres/ceres.h>\n\n#include \"image.hpp\"\n#include \"vec2.hpp\"\n\nnamespace compute = boost::compute;\nusing boost::compute::dim;\n\nusing homography_t = std::array<double, 9>;\n\ntemplate <typename T>\nvoid hann(img_t<T>& out, int w, int h, int d=1) {\n    out.resize(w, h, d);\n    out.set_value(0);\n    // with modifications from \"Burst photography for high dynamic range and low-light imaging on mobile cameras\"\n    // namely: half pixel offset and /w|/h instead of /(w-1)|/(h-1)\n    for (int l = 0; l < d; l++) {\n        for (int y = 0; y < h; y++) {\n            T vy = 0.5f * (1 - std::cos(2*M_PI*(y+0.5) / h));\n            for (int x = 0; x < w; x++) {\n                T vx = 0.5 * (1 - std::cos(2*M_PI*(x+0.5) / w));\n                out(x, y, l) = vx * vy;\n            }\n        }\n    }\n}\n\ntemplate <typename T>\nvec2<T> homography_apply(const homography_t& H, vec2<T> x) {\n    T X = H[0]*x[0] + H[1]*x[1] + H[2];\n    T Y = H[3]*x[0] + H[4]*x[1] + H[5];\n    T Z = H[6]*x[0] + H[7]*x[1] + H[8];\n    return { X / Z, Y / Z };\n}\n\nstruct TranslationResidual {\n    TranslationResidual(vec2<double> x, vec2<double> y) : x_(x), y_(y) {}\n\n    template <typename T> bool operator()(const T* const h,\n                                          T* residual) const {\n        T X = h[0]*x_[0] + h[1]*x_[1] + h[2];\n        T Y = h[3]*x_[0] + h[4]*x_[1] + h[5];\n        T Z = h[6]*x_[0] + h[7]*x_[1] + h[8];\n\n        vec2<T> p = { X / Z, Y / Z };\n        residual[0] = y_[0] - p[0];\n        residual[1] = y_[1] - p[1];\n        return true;\n    }\n\n    private:\n    const vec2<double> x_;\n    const vec2<double> y_;\n};\n\nhomography_t homography_from_translations_robust(const std::vector<vec2<vec2<double>>>& translations)\n{\n    homography_t h = {1,0,0, 0,1,0, 0,0,1};\n    ceres::Problem problem;\n    double* ph = &h[0];\n    for (unsigned i = 0; i < translations.size(); i++) {\n        problem.AddResidualBlock(new ceres::AutoDiffCostFunction<TranslationResidual, 2, 9>(\n                                    new TranslationResidual(translations[i][0], translations[i][1])),\n                                 new ceres::SoftLOneLoss(1.0), ph);\n    }\n\n    ceres::Solver::Options options;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    for (int k = 0; k < 9; k++)\n        h[k] /= h[8];\n    return h;\n}\n\ntemplate <typename T>\nimg_t<T> img_from_device(const compute::vector<T>& input,\n                                 int w, int h, int d,\n                                 compute::command_queue& queue) {\n    queue.finish();\n    img_t<T> out(w, h, d);\n    compute::copy(input.begin(), input.end(), out.data.begin(), queue);\n    queue.finish();\n    return out;\n}\n\ncompute::vector<float> img_to_device(const img_t<float>& input, compute::command_queue& queue) {\n    queue.finish();\n    return compute::vector<float>(input.data.begin(), input.data.end(), queue);\n}\n\nconst char kernels_src[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n    typedef float2 cfloat;\n\n    inline cfloat cmult(cfloat a, cfloat b){\n        return (cfloat)( a.x*b.x - a.y*b.y, a.x*b.y + a.y*b.x);\n    }\n\n    inline cfloat cconj(cfloat a){\n        return (cfloat)(a.x, -a.y);\n    }\n\n    __kernel void extract_tile(__global const float* input,\n                               __global float* output,\n                               const int ox, const int oy,\n                               const int w, const int h)\n    {\n        int x = get_global_id(0) + ox;\n        int y = get_global_id(1) + oy;\n        const int dx = get_global_id(0);\n        const int dy = get_global_id(1);\n\n        x = max(0, min(x, w-1));\n        y = max(0, min(y, h-1));\n\n        output[(dx+dy*W)*3+0] = input[(x+y*w)*3+0];\n        output[(dx+dy*W)*3+1] = input[(x+y*w)*3+1];\n        output[(dx+dy*W)*3+2] = input[(x+y*w)*3+2];\n    }\n\n    __kernel void fulltohalf(__global const float* input,\n                             __global float* output)\n    {\n        const int x = get_global_id(0);\n        const int y = get_global_id(1);\n        int dx = (x + W/2) % W;\n        int dy = (y + W/2) % W;\n        if (dx >= W/4 && dx < W*3/4 && dy >= W/4 && dy < W*3/4) {\n            output[(x+y*W)*3+0] = input[(dx+dy*W)*3+0];\n            output[(x+y*W)*3+1] = input[(dx+dy*W)*3+1];\n            output[(x+y*W)*3+2] = input[(dx+dy*W)*3+2];\n        } else {\n            output[(x+y*W)*3+0] = 0.f;\n            output[(x+y*W)*3+1] = 0.f;\n            output[(x+y*W)*3+2] = 0.f;\n        }\n    }\n\n    __kernel void float2complex(__global const float* input,\n                                __global cfloat* output)\n    {\n        const int x = get_global_id(0);\n\n        output[x].x = input[x];\n        output[x].y = 0.f;\n    }\n\n    __kernel void magnitude(__global const cfloat* input,\n                            __global float* out)\n    {\n        const int x = get_global_id(0);\n\n        out[x] = (fast_length(input[x*3+0])\n                + fast_length(input[x*3+1])\n                + fast_length(input[x*3+2])) / 3.f;\n    }\n\n    // /!\\ transposed result\n    __kernel void blur(__global const float* in,\n                       __global float* out,\n                       __global const float* gaussian, int size)\n    {\n        const int x = get_global_id(0);\n        const int y = get_global_id(1);\n\n        float v = 0.;\n        for (int i = -size; i <= size; i++) {\n            v += in[(x+i+W)%W+W*y] * gaussian[i+size];\n        }\n        out[y+W*x] = v;\n    }\n\n    __kernel void pow_(__global float* buf, float p)\n    {\n        const int x = get_global_id(0);\n        buf[x] = pow(buf[x], p);\n    }\n\n    __kernel void crosscorrelation(__global const cfloat* img,\n                                   __global const cfloat* ref,\n                                   __global cfloat* cc)\n    {\n        const int x = get_global_id(0);\n        cc[x] = (cmult(img[x*3+0], cconj(ref[x*3+0]))\n               + cmult(img[x*3+1], cconj(ref[x*3+1]))\n               + cmult(img[x*3+2], cconj(ref[x*3+2]))) / 3.f;\n    }\n\n    __kernel void l2residuals(__global const cfloat* cc,\n                              __global const float* boxfiltered,\n                              __global float* D)\n    {\n        const int x = get_global_id(0);\n        D[x] = boxfiltered[x] - 2.f * cc[x].x;\n    }\n\n    __kernel void translate(__global const float2* in,\n                            __global float2* out,\n                            float dx, float dy)\n    {\n        const int x = get_global_id(0);\n        const int y = get_global_id(1);\n        const int wx = (x + W / 2) % W - W / 2;\n        const int wy = (y + W / 2) % W - W / 2;\n\n        const float d = 2.f * M_PI_F * (wx * dx / W + wy * dy / W);\n        const cfloat phase = (cfloat)(cos(d), sin(d));\n\n        out[(x+y*W)*3+0] = cmult(in[(x+y*W)*3+0], phase);\n        out[(x+y*W)*3+1] = cmult(in[(x+y*W)*3+1], phase);\n        out[(x+y*W)*3+2] = cmult(in[(x+y*W)*3+2], phase);\n    }\n\n    __kernel void accumulate(__global const cfloat* tile,\n                             __global const float* hann,\n                             __global float* image,\n                             __global float* image_weight,\n                             const int ox, const int oy,\n                             const int w, const int h)\n    {\n        int x = get_global_id(0) + ox;\n        int y = get_global_id(1) + oy;\n        const int dx = get_global_id(0);\n        const int dy = get_global_id(1);\n        float weight = hann[dx+dy*W];\n\n        if (x >= 0 && x < w && y >= 0 && y < h) {\n            image_weight[x+y*w] += weight;\n            image[(x+y*w)*3+0] += tile[(dx+dy*W)*3+0].x * weight;\n            image[(x+y*w)*3+1] += tile[(dx+dy*W)*3+1].x * weight;\n            image[(x+y*w)*3+2] += tile[(dx+dy*W)*3+2].x * weight;\n        }\n    }\n\n    __kernel void unweight(__global float* image,\n                           __global const float* image_weight)\n    {\n        int x = get_global_id(0);\n        image[x*3+0] /= image_weight[x];\n        image[x*3+1] /= image_weight[x];\n        image[x*3+2] /= image_weight[x];\n    }\n\n    __kernel void cunweight(__global cfloat* image,\n                            __global const float* image_weight)\n    {\n        int x = get_global_id(0);\n        image[x*3+0] /= image_weight[x];\n        image[x*3+1] /= image_weight[x];\n        image[x*3+2] /= image_weight[x];\n    }\n\n    __kernel void fba(__global cfloat* accum,\n                      __global float* accum_weight,\n                      __global const cfloat* tile,\n                      __global const float* tile_weight)\n    {\n        int x = get_global_id(0);\n        const float weight = tile_weight[x];\n\n        accum_weight[x] += weight + 1e-6;\n        accum[x*3+0].x += tile[x*3+0].x * weight;\n        accum[x*3+0].y += tile[x*3+0].y * weight;\n        accum[x*3+1].x += tile[x*3+1].x * weight;\n        accum[x*3+1].y += tile[x*3+1].y * weight;\n        accum[x*3+2].x += tile[x*3+2].x * weight;\n        accum[x*3+2].y += tile[x*3+2].y * weight;\n    }\n\n    __kernel void sqr(__global const float* in,\n                      __global float* out)\n    {\n        const int x = get_global_id(0);\n        out[x] = in[x] * in[x];\n    }\n\n    // /!\\ unnormalized + transposed output\n    __kernel void boxfilter(__global const float* in,\n                            __global float* out)\n    {\n        const int y = get_global_id(0);\n\n        float v = in[y*W];\n        for (int x = 1; x <= hw; x++) {\n            v += in[x+y*W] + in[(W-x)+y*W];\n        }\n\n        out[y] = v;\n        for (int x = 1; x <= hw; x++) {\n            v += in[(x+hw)+y*W] - in[(W+x-hw-1)+y*W];\n            out[y+x*W] = v;\n        }\n        for (int x = hw + 1; x < W - hw; x++) {\n            v += in[(x+hw)+y*W] - in[(x-hw-1)+y*W];\n            out[y+x*W] = v;\n        }\n        for (int x = W - hw; x < W; x++) {\n            v += in[(x-W+hw)+y*W] - in[(x-hw-1)+y*W];\n            out[y+x*W] = v;\n        }\n    }\n\n    __kernel void rgb(__global const float* input,\n                      __global float* out)\n    {\n        const int x = get_global_id(0);\n        out[x] = (input[x*3+0]\n                + input[x*3+1]\n                + input[x*3+2]) / 3.f;\n    }\n);\n\nstruct tile {\n\n    ///////////////\n    // constants //\n    ///////////////\n\n    int x, y;\n    bool use_for_estimation;\n    img_t<float> src;\n    compute::vector<float> f; // full tiles\n    compute::vector<float> f_sqr; // full tiles\n    compute::vector<float> h; // half tiles\n    compute::vector<std::complex<float>> ff; // fourier full tiles\n    compute::vector<std::complex<float>> fh; // fourier half tiles\n    compute::vector<float> boxfiltered; // W*W*1\n    compute::vector<float> boxfiltered2; // W*W*1\n    compute::vector<float> w; // W*W*1\n    compute::vector<float> magn; // W*W*1\n    compute::vector<float> wblur; // W*W*1\n    compute::vector<char> tmpbuf;\n    compute::vector<char> tmpbufgray;\n\n    ///////////////////\n    // time-variable //\n    ///////////////////\n\n    bool valid;\n    float dx, dy;\n    compute::vector<std::complex<float>> cc; // W*W*1\n    compute::vector<float> l2residuals; // W*W*1\n    compute::vector<std::complex<float>> rff; // registered fourier full tiles\n};\n\nstruct image {\n\n    ///////////////\n    // constants //\n    ///////////////\n\n    int w, h, d, nt;\n    img_t<float> src;\n    compute::vector<float> dev; // w * h * d\n    std::vector<tile> tiles; // nt tiles\n\n    ///////////////////\n    // time-variable //\n    ///////////////////\n\n    bool allocated;\n};\n\nstruct result_tile {\n    int x, y;\n\n    compute::vector<std::complex<float>> rf;\n    compute::vector<std::complex<float>> accum;\n    compute::vector<float> accum_weight;\n    compute::vector<char> tmpbuf;\n};\n\nstruct result {\n    int w, h, d, nt;\n    std::vector<result_tile> tiles;\n\n    compute::vector<float> accumulated; // w * h * d\n    compute::vector<float> accumulated_weight; // w * h\n};\n\nstruct things {\n    int W;\n    int O;\n    float p;\n\n    compute::vector<float> hann;\n    compute::vector<float> gaussian;\n\n    compute::command_queue queue;\n    clfftPlanHandle ftplan;\n    clfftPlanHandle ftplangray;\n    compute::program prog;\n};\n\nvoid to_tiles_with_allocation(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"extract_tile\");\n\n    for (int y = -T.O; y < image.h; y+=T.O) {\n        for (int x = -T.O; x < image.w; x+=T.O) {\n            image.tiles.push_back(tile());\n            tile& t = image.tiles[image.tiles.size()-1];\n            t.x = x;\n            t.y = y;\n            t.f = compute::vector<float>(T.W * T.W * image.d, ctx);\n            kernel.set_args(image.dev, t.f, x, y, image.w, image.h);\n            compute::extents<2> offset = dim(0, 0);\n            compute::extents<2> ts = dim(T.W, T.W);\n            T.queue.enqueue_nd_range_kernel(kernel, 2, offset.data(), ts.data(), 0);\n\n            t.use_for_estimation  = !(t.x+T.W/2 < T.W/2 || t.x+T.W/2 > image.w - T.W/2);\n            t.use_for_estimation &= !(t.y+T.W/2 < T.W/2 || t.y+T.W/2 > image.h - T.W/2);\n        }\n    }\n}\n\nvoid to_tiles_without_allocation(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"extract_tile\");\n\n    compute::extents<2> offset = dim(0, 0);\n    compute::extents<2> ts = dim(T.W, T.W);\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        kernel.set_args(image.dev, t.f, t.x, t.y, image.w, image.h);\n        T.queue.enqueue_nd_range_kernel(kernel, 2, offset.data(), ts.data(), 0);\n    }\n}\n\nvoid fulltohalf(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"fulltohalf\");\n\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        kernel.set_args(t.f, t.h);\n        compute::extents<2> offset = dim(0, 0);\n        compute::extents<2> ts = dim(T.W, T.W);\n        T.queue.enqueue_nd_range_kernel(kernel, 2, offset.data(), ts.data(), 0);\n    }\n}\n\nvoid fftfull(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"float2complex\");\n\n    cl_command_queue q = T.queue;\n    int err;\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n\n        // XXX: this line is necessary even though I don't understand why\n        t.ff = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n\n        kernel.set_args(t.f, t.ff);\n        T.queue.enqueue_1d_range_kernel(kernel, 0, t.ff.size(), 0);\n\n        err = clfftEnqueueTransform(T.ftplan, CLFFT_FORWARD, 1, &q, 0, NULL, NULL,\n                                    &t.ff.get_buffer().get(), NULL, t.tmpbuf.get_buffer().get());\n        assert(!err);\n    }\n}\n\nvoid ffthalf(image& image, things& T)\n{\n    static auto kernel = T.prog.create_kernel(\"float2complex\");\n\n    cl_command_queue q = T.queue;\n    int err;\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        kernel.set_args(t.h, t.fh);\n        T.queue.enqueue_1d_range_kernel(kernel, 0, t.h.size(), 0);\n\n        err = clfftEnqueueTransform(T.ftplan, CLFFT_FORWARD, 1, &q, 0, NULL, NULL,\n                                    &t.fh.get_buffer().get(), NULL, t.tmpbuf.get_buffer().get());\n        assert(!err);\n    }\n}\n\nvoid backtospace(result& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n\n    cl_command_queue q = T.queue;\n    int err;\n    for (int i = 0; i < image.nt; i++) {\n        result_tile& t = image.tiles[i];\n\n        compute::copy(t.accum.begin(), t.accum.end(), t.rf.begin(), T.queue);\n\n        err = clfftEnqueueTransform(T.ftplan, CLFFT_BACKWARD, 1, &q, 0, NULL, NULL,\n                                    &t.rf.get_buffer().get(), NULL, t.tmpbuf.get_buffer().get());\n        assert(!err);\n    }\n}\n\n\nvoid weight(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel_magn = T.prog.create_kernel(\"magnitude\");\n    static auto kernel_pow = T.prog.create_kernel(\"pow_\");\n    static auto kernel_blur = T.prog.create_kernel(\"blur\");\n\n    compute::extents<2> offset = dim(0, 0);\n    compute::extents<2> ts = dim(T.W, T.W);\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n\n        kernel_magn.set_args(t.ff, t.magn);\n        T.queue.enqueue_1d_range_kernel(kernel_magn, 0, t.magn.size(), 0);\n\n        kernel_blur.set_args(t.magn, t.wblur, T.gaussian, (int)T.gaussian.size()/2);\n        T.queue.enqueue_nd_range_kernel(kernel_blur, 2, offset.data(), ts.data(), 0);\n\n        kernel_blur.set_args(t.wblur, t.w, T.gaussian, (int)T.gaussian.size()/2);\n        T.queue.enqueue_nd_range_kernel(kernel_blur, 2, offset.data(), ts.data(), 0);\n\n        kernel_pow.set_args(t.w, T.p);\n        T.queue.enqueue_1d_range_kernel(kernel_pow, 0, t.w.size(), 0);\n    }\n}\n\nvoid boxfilter(image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel_box = T.prog.create_kernel(\"boxfilter\");\n    static auto kernel_sqr = T.prog.create_kernel(\"sqr\");\n    static auto kernel_rgb = T.prog.create_kernel(\"rgb\");\n\n    compute::extents<2> offset = dim(0, 0);\n    compute::extents<2> ts = dim(T.W, T.W);\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        kernel_sqr.set_args(t.f, t.f_sqr);\n        T.queue.enqueue_1d_range_kernel(kernel_sqr, 0, t.f_sqr.size(), 0);\n\n        kernel_rgb.set_args(t.f_sqr, t.boxfiltered);\n        T.queue.enqueue_1d_range_kernel(kernel_rgb, 0, t.boxfiltered.size(), 0);\n\n        kernel_box.set_args(t.boxfiltered, t.boxfiltered2);\n        T.queue.enqueue_1d_range_kernel(kernel_box, 0, T.W, 0);\n\n        kernel_box.set_args(t.boxfiltered2, t.boxfiltered);\n        T.queue.enqueue_1d_range_kernel(kernel_box, 0, T.W, 0);\n    }\n}\n\nvoid l2residuals(struct image& image, const struct image& ref, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel_cc = T.prog.create_kernel(\"crosscorrelation\");\n    static auto kernel = T.prog.create_kernel(\"l2residuals\");\n\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        const tile& tref = ref.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        kernel_cc.set_args(t.ff, tref.fh, t.cc);\n        T.queue.enqueue_1d_range_kernel(kernel_cc, 0, t.cc.size(), 0);\n    }\n\n    cl_command_queue q = T.queue;\n    int err;\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        err = clfftEnqueueTransform(T.ftplangray, CLFFT_BACKWARD, 1, &q, 0, NULL, NULL,\n                                    &t.cc.get_buffer().get(), NULL, t.tmpbufgray.get_buffer().get());\n        assert(!err);\n    }\n\n    T.queue.finish();\n\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        kernel.set_args(t.cc, t.boxfiltered, t.l2residuals);\n        T.queue.enqueue_1d_range_kernel(kernel, 0, t.l2residuals.size(), 0);\n    }\n}\n\nvoid fetch_translations(struct image& image, things& T)\n{\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n        if (!t.use_for_estimation)\n            continue;\n\n        auto it = compute::min_element(t.l2residuals.begin(), t.l2residuals.end(), T.queue);\n        int x = std::distance(t.l2residuals.begin(), it);\n        t.dx = T.W/2 - x % T.W;\n        t.dy = T.W/2 - x / T.W;\n        t.dx = -t.dx;\n        t.dy = -t.dy;\n    }\n}\n\nvoid homshift(struct image& image, homography_t hom, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"translate\");\n\n    for (int i = 0; i < image.nt; i++) {\n        tile& t = image.tiles[i];\n\n        vec2<float> p = {t.x + T.W/2.f, t.y + T.W/2.f};\n        vec2<float> d = homography_apply(hom, p) - p;\n        d[0] = std::round(d[0]);\n        d[1] = std::round(d[1]);\n\n        if (std::abs(d[0]) > T.W/4 || std::abs(d[1]) > T.W/4) {\n            t.valid = false;\n            continue;\n        }\n        t.valid = true;\n\n        kernel.set_args(t.ff, t.rff, d[0], d[1]);\n        compute::extents<2> offset = dim(0, 0);\n        compute::extents<2> ts = dim(T.W, T.W);\n        T.queue.enqueue_nd_range_kernel(kernel, 2, offset.data(), ts.data(), 0);\n    }\n\n    T.queue.finish();\n}\n\nvoid accumulate(result& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"accumulate\");\n\n    auto barrier = T.queue.enqueue_marker();\n\n    compute::fill(image.accumulated.begin(), image.accumulated.end(), 0.f, T.queue);\n    compute::fill(image.accumulated_weight.begin(), image.accumulated_weight.end(), 0.f, T.queue);\n\n    barrier.wait(); // wait for ifft to finish\n\n    for (int i = 0; i < image.nt; i++) {\n        result_tile& t = image.tiles[i];\n        int x = t.x;\n        int y = t.y;\n\n        kernel.set_args(t.rf, T.hann, image.accumulated, image.accumulated_weight, x, y, image.w, image.h);\n        compute::extents<2> offset = dim(0, 0);\n        compute::extents<2> ts = dim(T.W, T.W);\n        T.queue.enqueue_nd_range_kernel(kernel, 2, offset.data(), ts.data(), 0);\n    }\n\n    static auto kernel_unweight = T.prog.create_kernel(\"unweight\");\n    kernel_unweight.set_args(image.accumulated, image.accumulated_weight);\n    T.queue.enqueue_1d_range_kernel(kernel_unweight, 0, image.accumulated_weight.size(), 0);\n}\n\nvoid fba(result& result, std::vector<image*>& images, things& T)\n{\n    auto ctx = T.queue.get_context();\n    static auto kernel = T.prog.create_kernel(\"fba\");\n    static auto kernel_unweight = T.prog.create_kernel(\"cunweight\");\n\n    for (int i = 0; i < result.nt; i++) {\n        result_tile& tbuf = result.tiles[i];\n        compute::fill(tbuf.accum.begin(), tbuf.accum.end(), 0, T.queue);\n        compute::fill(tbuf.accum_weight.begin(), tbuf.accum_weight.end(), 0, T.queue);\n    }\n\n    for (int j = 0; j < images.size(); j++) {\n        image& image = *images[j];\n        for (int i = 0; i < image.nt; i++) {\n            result_tile& tbuf = result.tiles[i];\n            tile& t = image.tiles[i];\n\n            if (!t.valid)  {\n                continue;\n            }\n\n            kernel.set_args(tbuf.accum, tbuf.accum_weight, t.rff, t.w);\n            T.queue.enqueue_1d_range_kernel(kernel, 0, tbuf.accum_weight.size(), 0);\n        }\n    }\n\n    for (int i = 0; i < result.nt; i++) {\n        result_tile& tbuf = result.tiles[i];\n        kernel_unweight.set_args(tbuf.accum, tbuf.accum_weight);\n        T.queue.enqueue_1d_range_kernel(kernel_unweight, 0, tbuf.accum_weight.size(), 0);\n    }\n}\n\nvoid register_all(image& ref, std::vector<image*>& images, things& T)\n{\n    for (unsigned i = 0; i < images.size(); i++) {\n        if (images[i] != &ref)\n            l2residuals(*images[i], ref, T);\n    }\n    for (unsigned i = 0; i < images.size(); i++) {\n        if (images[i] != &ref)\n            fetch_translations(*images[i], T);\n    }\n    for (unsigned i = 0; i < images.size(); i++) {\n        if (images[i] == &ref)\n            continue;\n\n        int W = T.W;\n        std::vector<vec2<vec2<double>>> translations;\n        for (int j = 0; j < images[i]->nt; j++) {\n            tile& t = images[i]->tiles[j];\n            if (!t.use_for_estimation)\n                continue;\n            vec2<vec2<double>> tr;\n            tr[0] = vec2<double>(t.x + T.W/2, t.y + T.W/2);\n            tr[1] = vec2<double>(t.x + T.W/2 + t.dx, t.y + T.W/2 + t.dy);\n            translations.push_back(tr);\n        }\n\n        homography_t H = homography_from_translations_robust(translations);\n        homshift(*images[i], H, T);\n    }\n\n    for (int j = 0; j < ref.nt; j++) {\n        tile& t = ref.tiles[j];\n        t.valid = true;\n        compute::copy_async(t.ff.begin(), t.ff.end(), t.rff.begin(), T.queue);\n    }\n}\n\nvoid fuse_all(result& result, std::vector<image*>& images, things& T)\n{\n    fba(result, images, T);\n    backtospace(result, T);\n    accumulate(result, T);\n}\n\nvoid initialize_result(result& result, const image& image, things& T)\n{\n    auto ctx = T.queue.get_context();\n\n    result.w = image.w;\n    result.h = image.h;\n    result.d = image.d;\n    result.nt = image.nt;\n    result.accumulated = compute::vector<float>(image.w*image.h*image.d, ctx);\n    result.accumulated_weight = compute::vector<float>(image.w*image.h, ctx);\n\n    result.tiles.resize(image.nt);\n    for (int t = 0; t < image.nt; t++) {\n        auto& tt = result.tiles[t];\n        auto& ti = image.tiles[t];\n\n        tt.x = ti.x;\n        tt.y = ti.y;\n        tt.rf = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n        tt.accum = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n        tt.accum_weight = compute::vector<float>(T.W*T.W, ctx);\n        size_t size;\n        clfftGetTmpBufSize(T.ftplan, &size);\n        tt.tmpbuf = compute::vector<char>(size, ctx);\n    }\n}\n\nvoid prepare_image(image& image, const img_t<float>& img, things& T)\n{\n    auto ctx = T.queue.get_context();\n    image.src = img;\n    image.w = img.w;\n    image.h = img.h;\n    image.d = img.d;\n\n    if (!image.allocated) {\n        image.dev = img_to_device(img, T.queue);\n        to_tiles_with_allocation(image, T);\n        image.nt = image.tiles.size();\n\n        for (int t = 0; t < image.nt; t++) {\n            auto& tt = image.tiles[t];\n            tt.h = compute::vector<float>(T.W*T.W*image.d, ctx);\n            tt.f_sqr = compute::vector<float>(T.W*T.W*image.d, ctx);\n            tt.ff = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n            tt.fh = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n            tt.cc = compute::vector<std::complex<float>>(T.W*T.W, ctx);\n            tt.l2residuals = compute::vector<float>(T.W*T.W, ctx);\n            tt.rff = compute::vector<std::complex<float>>(T.W*T.W*image.d, ctx);\n            tt.w = compute::vector<float>(T.W*T.W, ctx);\n            tt.wblur = compute::vector<float>(T.W*T.W, ctx);\n            tt.magn = compute::vector<float>(T.W*T.W, ctx);\n            tt.boxfiltered = compute::vector<float>(T.W*T.W, ctx);\n            tt.boxfiltered2 = compute::vector<float>(T.W*T.W, ctx);\n            size_t size;\n            clfftGetTmpBufSize(T.ftplan, &size);\n            tt.tmpbuf = compute::vector<char>(size, ctx);\n            clfftGetTmpBufSize(T.ftplangray, &size);\n            tt.tmpbufgray = compute::vector<char>(size, ctx);\n        }\n        image.allocated = true;\n    } else {\n        compute::copy(img.data.begin(), img.data.end(), image.dev.begin(), T.queue);\n        to_tiles_without_allocation(image, T);\n    }\n\n    fulltohalf(image, T);\n    fftfull(image, T);\n    ffthalf(image, T);\n    weight(image, T);\n    boxfilter(image, T);\n}\n\nint main(int argc, char** argv)\n{\n    if (argc < 2 || argc > 4) {\n        return fprintf(stderr, \"usage: %s <output_fmt> [file_of_inputs (stdin)]\\n\", argv[0]), 1;\n    }\n\n    char* output_fmt = argv[1];\n    FILE* inputs = stdin;\n    if (argc == 3) {\n        inputs = fopen(argv[2], \"r\");\n        if (!inputs) {\n            return perror(argv[2]), 1;\n        }\n    }\n\n    compute::device device = compute::system::default_device();\n    std::cout << \"device: \" << device.name() << std::endl;\n\n    compute::context ctx(device);\n\n    int W = 256;\n\n    things things;\n    things.queue = compute::command_queue(ctx, device);\n    things.W = W;\n    things.O = W/3;\n    things.p = 3;\n\n    {\n        img_t<float> _hann;\n        ::hann(_hann, W/2, W/2);\n        img_t<float> hann(W, W);\n        hann.set_value(0);\n        for (int y = 0; y < W/2; y++) {\n            for (int x = 0; x < W/2; x++) {\n                hann(W/4 + x, W/4 + y) = _hann(x, y);\n            }\n        }\n        things.hann = img_to_device(hann, things.queue);\n    }\n\n    {\n        float sigma = things.W / 50.f;\n        std::vector<float> gaussian(21);\n        float sum = 0.f;\n        for (int x = 0; x < (int) gaussian.size(); x++) {\n            gaussian[x] = 1.f/std::sqrt(2*M_PI*sigma*sigma)\n                        * std::exp(- std::pow((float)(x-(int)gaussian.size()/2), 2.f) / (2*sigma*sigma));\n            sum += gaussian[x];\n        }\n        for (unsigned x = 0; x < gaussian.size(); x++) {\n            gaussian[x] /= sum;\n        }\n        things.gaussian = compute::vector<float>(gaussian.begin(), gaussian.end(), things.queue);\n    }\n\n    things.prog = compute::program::build_with_source(kernels_src, ctx,\n                                                      \"-D W=\" + std::to_string(W)\n                                                      + \" -D hw=\" + std::to_string(W/4));\n\n    {\n        clfftPlanHandle planHandle;\n        clfftDim dim = CLFFT_2D;\n        size_t clLengths[2] = {(size_t)W, (size_t)W};\n        size_t strides[] = {(size_t)3, (size_t)W*3};\n        int err;\n        clfftSetupData fftSetup;\n        err = clfftInitSetupData(&fftSetup);\n        err = clfftSetup(&fftSetup);\n        err = clfftCreateDefaultPlan(&things.ftplan, ctx, dim, clLengths);\n        err = clfftSetPlanPrecision(things.ftplan, CLFFT_SINGLE);\n        err = clfftSetLayout(things.ftplan, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED);\n        err = clfftSetResultLocation(things.ftplan, CLFFT_INPLACE);\n        err = clfftSetPlanInStride(things.ftplan, dim, strides);\n        err = clfftSetPlanOutStride(things.ftplan, dim, strides);\n        err = clfftSetPlanBatchSize(things.ftplan, 3);\n        err = clfftSetPlanDistance(things.ftplan, 1, 1);\n        cl_command_queue q = things.queue;\n        err = clfftBakePlan(things.ftplan, 1, &q, NULL, NULL);\n        assert(!err);\n    }\n    {\n        clfftPlanHandle planHandle;\n        clfftDim dim = CLFFT_2D;\n        size_t clLengths[2] = {(size_t)W, (size_t)W};\n        size_t strides[] = {(size_t)1, (size_t)W};\n        int err;\n        clfftSetupData fftSetup;\n        err = clfftInitSetupData(&fftSetup);\n        err = clfftSetup(&fftSetup);\n        err = clfftCreateDefaultPlan(&things.ftplangray, ctx, dim, clLengths);\n        err = clfftSetPlanPrecision(things.ftplangray, CLFFT_SINGLE);\n        err = clfftSetLayout(things.ftplangray, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED);\n        err = clfftSetResultLocation(things.ftplangray, CLFFT_INPLACE);\n        err = clfftSetPlanInStride(things.ftplangray, dim, strides);\n        err = clfftSetPlanOutStride(things.ftplangray, dim, strides);\n        err = clfftSetPlanBatchSize(things.ftplangray, 1);\n        err = clfftSetPlanDistance(things.ftplangray, 1, 1);\n        cl_command_queue q = things.queue;\n        err = clfftBakePlan(things.ftplangray, 1, &q, NULL, NULL);\n        assert(!err);\n    }\n\n    std::vector<struct image*> images;\n    struct result result;\n\n    int N = 3;\n    int cur = 0;\n    int i = 0;\n    char file[2048];\n    while (fgets(file, sizeof(file), inputs) && file[0]) {\n        file[strlen(file) - 1] = 0;\n        img_t<float> img = img_t<float>::load(file);\n        float max = img.max();\n        for (auto& v : img.data) v /= max;\n\n        if (images.size() < N) {\n            images.push_back(new struct image);\n            images[images.size()-1]->allocated = false;\n            cur = images.size() - 1;\n        } else {\n            cur = (cur + 1) % images.size();\n        }\n\n        prepare_image(*images[cur], img, things);\n\n        if (images.size() == 1)\n            initialize_result(result, *images[0], things);\n\n        register_all(*images[cur], images, things);\n\n        fuse_all(result, images, things);\n\n        auto accumulated = img_from_device(result.accumulated, img.w, img.h, img.d, things.queue);\n        for (auto& v : accumulated.data) v *= max;\n        std::string output = string_format(output_fmt, i);\n        accumulated.save(output);\n        printf(\"%s\\n\", output.c_str());\n        i++;\n    }\n\n    int err = clfftDestroyPlan(&things.ftplan);\n    err = clfftDestroyPlan(&things.ftplangray);\n    clfftTeardown();\n    return 0;\n}\n", "meta": {"hexsha": "712cc351af447dfa7fa2c5c1ef02855bf0d8a13e", "size": 32000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kidanger/FastFBA", "max_stars_repo_head_hexsha": "3e0bab0d23dd5c4b5de9571f471832f4e0e5ca56", "max_stars_repo_licenses": ["MIT"], "max_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": "kidanger/FastFBA", "max_issues_repo_head_hexsha": "3e0bab0d23dd5c4b5de9571f471832f4e0e5ca56", "max_issues_repo_licenses": ["MIT"], "max_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": "kidanger/FastFBA", "max_forks_repo_head_hexsha": "3e0bab0d23dd5c4b5de9571f471832f4e0e5ca56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-29T06:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T06:39:58.000Z", "avg_line_length": 32.6530612245, "max_line_length": 113, "alphanum_fraction": 0.5394375, "num_tokens": 9312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625321, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5747736695737605}}
{"text": "// Copyright (c) 2020 Chris Richardson\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"raviart-thomas.h\"\n#include \"dof-permutations.h\"\n#include \"lagrange.h\"\n#include \"moments.h\"\n#include \"polyset.h\"\n#include \"quadrature.h\"\n#include <Eigen/Dense>\n#include <numeric>\n#include <vector>\n\nusing namespace libtab;\n\n//----------------------------------------------------------------------------\nFiniteElement libtab::create_rt(cell::type celltype, int degree,\n                                const std::string& name)\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-1) scalar polynomials\n  const int nv = polyset::dim(celltype, degree - 1);\n  // The number of order (degree-2) scalar polynomials\n  const int ns0 = polyset::dim(celltype, degree - 2);\n  // The number of additional polnomials in the polynomial basis for\n  // Raviart-Thomas\n  const int ns = polyset::dim(facettype, degree - 1);\n\n  // Evaluate the expansion polynomials at the quadrature points\n  auto [Qpts, Qwts] = quadrature::make_quadrature(celltype, 2 * degree);\n  Eigen::ArrayXXd Pkp1_at_Qpts\n      = polyset::tabulate(celltype, degree, 0, Qpts)[0];\n\n  // The number of order (degree) polynomials\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 * tdim + ns, psize * tdim);\n  for (int j = 0; j < tdim; ++j)\n  {\n    wcoeffs.block(nv * j, psize * j, nv, nv)\n        = Eigen::MatrixXd::Identity(nv, nv);\n  }\n\n  // Create coefficients for additional polynomials in Raviart-Thomas\n  // polynomial basis\n  for (int i = 0; i < ns; ++i)\n  {\n    for (int k = 0; k < psize; ++k)\n    {\n      for (int j = 0; j < tdim; ++j)\n      {\n        const double w_sum = (Qwts * Pkp1_at_Qpts.col(ns0 + i) * Qpts.col(j)\n                              * Pkp1_at_Qpts.col(k))\n                                 .sum();\n        wcoeffs(nv * tdim + i, k + psize * j) = w_sum;\n      }\n    }\n  }\n\n  // Dual space\n  Eigen::MatrixXd dual = Eigen::MatrixXd::Zero(nv * tdim + ns, psize * tdim);\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 = ns;\n  dual.block(0, 0, facet_count * facet_dofs, psize * tdim)\n      = moments::make_normal_integral_moments(\n          create_dlagrange(facettype, degree - 1), celltype, tdim, degree,\n          quad_deg);\n\n  // Add rows to dualmat for integral moments on interior\n  if (degree > 1)\n  {\n    const int internal_dofs = tdim * ns0;\n    // Interior integral moment\n    dual.block(facet_count * facet_dofs, 0, internal_dofs, psize * tdim)\n        = moments::make_integral_moments(create_dlagrange(celltype, degree - 2),\n                                         celltype, tdim, degree, quad_deg);\n  }\n\n  const std::vector<std::vector<std::vector<int>>> topology\n      = cell::topology(celltype);\n\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\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    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    }\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[2 * face](start + i, start + i) = 0;\n        base_permutations[2 * face](start + i, start + face_rot[i]) = 1;\n        base_permutations[2 * face + 1](start + i, start + i) = 0;\n        base_permutations[2 * face + 1](start + i, start + face_ref[i]) = -1;\n      }\n    }\n  }\n\n  // Raviart-Thomas has ns dofs on each facet, and ns0*tdim in 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(), ns);\n  entity_dofs[tdim] = {ns0 * tdim};\n\n  Eigen::MatrixXd coeffs = compute_expansion_coefficients(wcoeffs, dual);\n  return FiniteElement(name, celltype, degree, {tdim}, coeffs, entity_dofs,\n                       base_permutations);\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "7874bae8ffd56b68918f2205f0d0f472acab2e08", "size": 5064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/raviart-thomas.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/raviart-thomas.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/raviart-thomas.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": 34.6849315068, "max_line_length": 80, "alphanum_fraction": 0.602685624, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5746549250770154}}
{"text": "#include \"Geometry.h\"\r\n#include <cmath>\r\n//#include <boost/polygon/polygon.hpp>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nPoint2D::Point2D(void) { ; }\r\nPoint2D::Point2D(coord_t _x, coord_t _y) : x(_x), y(_y) { ; }\r\nVector2D Point2D::operator - (const Point2D& p) const { return Vector2D(x - p.x, y - p.y); }\r\nPoint2D Point2D::operator + (const Vector2D& v) const { return Point2D(x + v.x, y + v.y); }\r\nPoint2D Point2D::operator - (const Vector2D& v) const { return Point2D(x - v.x, y - v.y); }\r\nbool Point2D::operator == (const Point2D& v) const {\r\n\treturn abs(x - v.x) <= EPSILON\r\n\t\t&& abs(y - v.y) <= EPSILON;\r\n}\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nPoint3D::Point3D(void) { ; }\r\nPoint3D::Point3D(coord_t _x, coord_t _y, coord_t _z) :x(_x), y(_y), z(_z) { ; }\r\n\r\n\r\nVector3D Point3D::to_vector(void) const {\r\n\treturn Vector3D(x, y, z);\r\n}\r\n\r\nPoint3D Point3D::operator - (void) const { return Point3D(-x, -y, -z); }\r\nVector3D Point3D::operator - (const Point3D& p) const { return Vector3D(x - p.x, y - p.y, z - p.z); }\r\nPoint3D Point3D::operator + (const Vector3D& v) const { return Point3D(x + v.x, y + v.y, z + v.z); }\r\nPoint3D Point3D::operator - (const Vector3D& v) const { return Point3D(x - v.x, y - v.y, z - v.z); }\r\n//bool Point3D::operator == (const Point3D& v) const { return x == v.x && y == v.y && z == v.z;  }\r\nbool Point3D::operator == (const Point3D& v) const {\r\n\treturn abs(x - v.x) <= EPSILON\r\n\t\t&& abs(y - v.y) <= EPSILON\r\n\t\t&& abs(z - v.z) <= EPSILON;\r\n}\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nAxisAlignedBoundingBox3D::AxisAlignedBoundingBox3D(void) { ; }\r\nAxisAlignedBoundingBox3D::AxisAlignedBoundingBox3D(const Point3D& _m, const Point3D& _M) : min(_m), max(_M) { ; }\r\nvoid AxisAlignedBoundingBox3D::add(const Point3D& p) {\r\n\tif (min.x > p.x) min.x = p.x;\r\n\tif (min.y > p.y) min.y = p.y;\r\n\tif (min.z > p.z) min.z = p.z;\r\n\r\n\tif (max.x < p.x) max.x = p.x;\r\n\tif (max.y < p.y) max.y = p.y;\r\n\tif (max.z < p.z) max.z = p.z;\r\n}\r\nAxisAlignedBoundingBox3D AxisAlignedBoundingBox3D::operator + (const AxisAlignedBoundingBox3D& operand) const {\r\n\tAxisAlignedBoundingBox3D ret = operand;\r\n\tret.add(max);\r\n\tret.add(min);\r\n\treturn ret;\r\n}\r\n\r\nXYRotatedBoundingBox3D::XYRotatedBoundingBox3D(void)\r\n:min(0,0,0), axis_u(1,0,0), axis_v(0,1,0), xy(0,0), height(0.0) { ; }\r\n\r\nvoid XYRotatedBoundingBox3D::compute(const std::vector<Point3D>& pts){\r\n\tif (pts.empty()) {\r\n\t\t*this = XYRotatedBoundingBox3D();\r\n\t\treturn;\r\n\t}\r\n\tmin.z = pts[0].z;\r\n\theight = 0.0;\r\n\tfor (int i = 1; i < pts.size(); ++i) {\r\n\t\tif (min.z > pts[i].z) {\r\n\t\t\theight += min.z - pts[i].z;\r\n\t\t\tmin.z = pts[i].z;\r\n\t\t}\r\n\t\tif (height < pts[i].z - min.z) {\r\n\t\t\theight = pts[i].z - min.z;\r\n\t\t}\r\n\t}\r\n\r\n\t// TODO: may use the convex hull to improve the complexity\r\n\tscalar_t min_area = -1;\r\n\tPoint3D  ma_p(0, 0, 0);\r\n\tVector2D ma_xy(0, 0);\r\n\tVector3D ma_u(1, 0, 0);\r\n\tVector3D ma_v(0, 1, 0);\r\n\tfor (int i = 0; i < pts.size(); ++i) {\r\n\t\tfor (int j = i + 1; j < pts.size(); ++j) {\r\n\t\t\t//Vector2D delta(pts[j].x - pts[i].x, pts[j].y - pts[i].y);\r\n\t\t\tVector3D u = pts[j] - pts[i];\r\n\t\t\tu.z = 0;\r\n\t\t\tif (u.is_zero()) continue;\r\n\t\t\tu = u.normalized();\r\n\t\t\tVector3D v = Vector3D(0, 0, 1).cross_product(u);\r\n\r\n\t\t\tscalar_t min_u, max_u;\r\n\t\t\tscalar_t min_v, max_v;\r\n\t\t\tmin_u = max_u = pts[0].to_vector().dot_product(u);\r\n\t\t\tmin_v = max_v = pts[0].to_vector().dot_product(v);\r\n\r\n\t\t\tfor (int k = 1; k < pts.size(); ++k) {\r\n\t\t\t\tscalar_t x = pts[k].to_vector().dot_product(u);\r\n\t\t\t\tscalar_t y = pts[k].to_vector().dot_product(v);\r\n\r\n\t\t\t\tif (min_u > x) min_u = x;\r\n\t\t\t\tif (min_v > y) min_v = y;\r\n\r\n\t\t\t\tif (max_u < x) max_u = x;\r\n\t\t\t\tif (max_v < y) max_v = y;\r\n\t\t\t}\r\n\r\n\t\t\tscalar_t area = (max_u - min_u) * (max_v - min_v);\r\n\t\t\tif (min_area < 0 || min_area > area) {\r\n\t\t\t\tmin_area = area;\r\n\t\t\t\tmin = Point3D(0,0,min.z) + (u * min_u + v * min_v);\r\n\t\t\t\txy = Vector2D(max_u - min_u, max_v - min_v);\r\n\t\t\t\taxis_u = u;\r\n\t\t\t\taxis_v = v;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// Post condition:\r\n\t//  \"min\" is the bottom-left corner, \"axis_u\" and \"axis_v\" comprise the unit vectors indicating two sides of the bounding box.\r\n\t//  \"xy\" is (width, height).\r\n\t\r\n};\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nVector2D::Vector2D(void) { ; }\r\nVector2D::Vector2D(coord_t _x, coord_t _y) : x(_x), y(_y) { ; }\r\n\r\nVector2D Vector2D::normalize(void) const {\r\n\tlength_t size = sqrt(dot_product(*this));\r\n\treturn Vector2D(x / size, y / size);\r\n}\r\n\r\nscalar_t Vector2D::dot_product(const Vector2D& v) const { return x * v.x + y * v.y; }\r\narea_t Vector2D::signed_area(const Vector2D& v) const { return x * v.y - y * v.x; }\r\n\r\nlength_t Vector2D::length(void) const {\r\n\treturn sqrt(dot_product(*this));\r\n}\r\n\r\nVector2D Vector2D::operator + (const Vector2D& v) const { return Vector2D(x + v.x, y + v.y); }\r\nVector2D Vector2D::operator - (const Vector2D& v) const { return Vector2D(x - v.x, y - v.y); }\r\nVector2D Vector2D::operator - (void) const { return Vector2D(-x, -y); }\r\nVector2D operator * (scalar_t a, const Vector2D& v) { return Vector2D(a*v.x, a*v.y); }\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nVector3D::Vector3D(void) { ; }\r\nVector3D::Vector3D(coord_t _x, coord_t _y, coord_t _z) :x(_x), y(_y), z(_z) { ; }\r\n\r\nPoint3D Vector3D::to_point(void) const {\r\n\treturn Point3D(x, y, z);\r\n}\r\n\r\nscalar_t Vector3D::dot_product(const Vector3D& v) const { return x * v.x + y * v.y + z * v.z; }\r\nVector3D Vector3D::cross_product(const Vector3D& v) const {\r\n\tfloat xx = y * v.z - z * v.y;\r\n\tfloat yy = z * v.x - x * v.z;\r\n\tfloat zz = x * v.y - y * v.x;\r\n\treturn Vector3D(xx, yy, zz);\r\n}\r\nVector3D Vector3D::normalized(void) const {\r\n\tlength_t size = length();\r\n\treturn Vector3D(x / size, y / size, z / size);\r\n}\r\nlength_t Vector3D::length(void) const {\r\n\treturn sqrt(dot_product(*this));\r\n\r\n}\r\nlength_t Vector3D::length_square(void) const {\r\n\treturn dot_product(*this);\r\n\r\n}\r\nVector3D Vector3D::rotate(const Vector3D& q, radian_t theta) const {\r\n\r\n\tscalar_t rx = sin(theta / 2) * q.x;\r\n\tscalar_t ry = sin(theta / 2) * q.y;\r\n\tscalar_t rz = sin(theta / 2) * q.z;\r\n\tscalar_t rw = cos(theta / 2);\r\n\r\n\tscalar_t ix = rw * x + ry * z - rz * y;\r\n\tscalar_t iy = rw * y + rz * x - rx * z;\r\n\tscalar_t iz = rw * z + rx * y - ry * x;\r\n\tscalar_t iw = -rx * x - ry * y - rz * z;\r\n\r\n\treturn Vector3D(\r\n\t\tix * rw - iw * rx + ry * iz - rz * iy,\r\n\t\tiy * rw - iw * ry + rz * ix - rx * iz,\r\n\t\tiz * rw - iw * rz + rx * iy - ry * ix\r\n\t);\r\n}\r\nVector3D Vector3D::get_projection_component_to(const Vector3D& x) const {\r\n\treturn x.normalized() * dot_product(x) / sqrt(x.dot_product(x));\r\n}\r\nVector3D Vector3D::get_perpendicular_component_to(const Vector3D& x) const {\r\n\treturn *this - get_projection_component_to(x);\r\n}\r\n\r\nVector3D Vector3D::operator + (const Vector3D& v) const { return Vector3D(x + v.x, y + v.y, z + v.z); }\r\nVector3D Vector3D::operator - (const Vector3D& v) const { return Vector3D(x - v.x, y - v.y, z - v.z); }\r\nVector3D operator * (scalar_t a, const Vector3D& v) { return Vector3D(a*v.x, a*v.y, a*v.z); }\r\nVector3D Vector3D::operator * (scalar_t a) const { return Vector3D(a*x, a*y, a*z); }\r\nVector3D Vector3D::operator / (scalar_t a) const { return Vector3D(x / a, y / a, z / a); }\r\n\r\nbool Vector3D::is_zero(void) const {\r\n\treturn x * x + y * y + z * z < EPSILON;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nLine2D::Line2D(const Point2D& _p, const Vector2D& _v) : p(_p), v(_v) { ; }\r\n\r\nPoint2D Line2D::get_projection_of(const Point2D& _p, length_t *_alpha) const {\r\n\tscalar_t denominator = v.dot_product(v);\r\n\tif (denominator == 0) {\r\n\t\tif (_alpha) *_alpha = 0;\r\n\t\treturn p;\r\n\t}\r\n\tlength_t alpha = (_p - p).dot_product(v) / denominator;\r\n\tif (_alpha) *_alpha = alpha;\r\n\treturn p + alpha * v;\r\n}\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\nLine3D::Line3D() { ; }\r\nLine3D::Line3D(const Point3D& _p, const Point3D& _q) : p(_p), v(_q-_p) { ; }\r\nLine3D::Line3D(const Point3D& _p, const Vector3D& _v) : p(_p), v(_v) { ; }\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/*\r\ntypedef boost::polygon::polygon_with_holes_data<scalar_t> boost_polygon;\r\ntypedef boost::polygon::polygon_traits<boost_polygon>::point_type boost_point;\r\nstatic boost_polygon to_boost_polygon(const Polygon2D& poly) {\r\n\tusing namespace boost::polygon;\r\n\tboost_polygon p;\r\n\tstd::vector<boost_point> exterior;\r\n\tfor (int i = 0; i < poly.exterior.size(); ++i) {\r\n\t\texterior.push_back(construct<boost_point>(poly.exterior[i].x, poly.exterior[i].y));\r\n\t}\r\n\r\n\tstd::vector< std::vector<boost_point> > holes;\r\n\tfor (int r = 0; r < poly.hole.size(); ++r) {\r\n\t\tstd::vector<boost_point> hole;\r\n\t\tfor (int i = 0; i < poly.hole[r].size(); ++i) {\r\n\t\t\thole.push_back(construct<boost_point>(poly.hole[r][i].x, poly.hole[r][i].y));\r\n\t\t}\r\n\t\tholes.push_back(hole);\r\n\t}\r\n\t\r\n\tset_points(p, exterior.begin(), exterior.end());\r\n\tset_holes(p, holes.begin(), holes.end());\r\n\r\n\treturn p;\r\n}\r\n\r\nstatic Polygon2D to_polygon2d(const boost_polygon& poly) {\r\n\tPolygon2D ret;\r\n\t\r\n\t\r\n\tfor (auto i = poly.begin(); i != poly.end(); ++i) {\r\n\t\tret.exterior.push_back(Point2D(i->x(), i->y()));\r\n\t}\r\n\r\n\tfor (auto i = poly.begin_holes(); i != poly.end_holes(); ++i) {\r\n\t\tstd::vector<Point2D> hole;\r\n\t\tfor (auto j = i->begin(); j != i->end(); ++j) {\r\n\t\t\thole.push_back(Point2D(j->x(), j->y()));\r\n\t\t}\r\n\t\tret.hole.push_back(hole);\r\n\t}\r\n\r\n\treturn ret;\r\n}\r\nstd::vector<Polygon2D> Polygon2D::intersection(const Polygon2D& x) const {\r\n\tboost_polygon p = to_boost_polygon(*this);\r\n\tboost_polygon q = to_boost_polygon(x);\r\n\tusing namespace boost::polygon::operators;\r\n\t//typedef  PolygonSet;\r\n\t//PolygonSet ps;\r\n\tstd::vector<boost_polygon> intersection_ret;\r\n\tstd::cout << \"DIRTY\" << (p & q).dirty() << std::endl;\r\n\tassign(intersection_ret, p & q);\r\n\r\n\tstd::vector<Polygon2D> ret;\r\n\tfor (int i = 0; i < intersection_ret.size(); ++i) {\r\n\t\tret.push_back(to_polygon2d(intersection_ret[i]));\r\n\t}\r\n\treturn ret;\r\n}\r\n*/\r\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > boost_polygon;\r\ntypedef boost_polygon::point_type boost_point;\r\n\r\nstatic boost_polygon to_boost_polygon(const Polygon2D& poly) {\r\n\tboost_polygon ret;\r\n\tstd::vector<boost_point> pts;\r\n\tfor (int i = 0; i < poly.exterior.size(); ++i) {\r\n\t\tpts.push_back(boost_point(poly.exterior[i].x, poly.exterior[i].y));\r\n\t}\r\n\tpts.push_back(boost_point(poly.exterior[0].x, poly.exterior[0].y));\r\n\tboost::geometry::assign_points(ret, pts);\r\n\treturn ret;\r\n}\r\nstatic Polygon2D to_polygon2d(const boost_polygon& poly) {\r\n\tPolygon2D ret;\r\n\tfor (auto i = poly.outer().begin(); i != poly.outer().end(); ++i) {\r\n\t\tret.exterior.push_back(Point2D((*i).x(), (*i).y()));\r\n\t}\r\n\treturn ret;\r\n}\r\nstd::vector<Polygon2D> Polygon2D::intersection(const Polygon2D& x) const {\r\n\tboost_polygon p = to_boost_polygon(*this);\r\n\tboost_polygon q = to_boost_polygon(x);\r\n\r\n\tstd::vector<boost_polygon> intersection_ret;\r\n\tboost::geometry::intersection(p, q, intersection_ret);\r\n\tstd::vector<Polygon2D> ret;\r\n\tfor (int i = 0; i < intersection_ret.size(); ++i) {\r\n\t\tret.push_back(to_polygon2d(intersection_ret[i]));\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nPlane::Plane(void) { ; }\r\nPlane::Plane(const Point3D& _p, const Vector3D& _h) : p(_p), h(_h) { ; }\r\nPoint3D Plane::project(const Point3D& q, length_t *d) const {\r\n\tlength_t l = (p - q).dot_product(h) / h.length();\r\n\tif (d) *d = l;\r\n\treturn q + l * h.normalized();\r\n}\r\nLine3D Plane::project(const Line3D& l) const {\r\n\tPoint3D proj_p = project(l.p);\r\n\tPoint3D proj_q = project(l.p + l.v);\r\n\tVector3D proj_v = proj_q - proj_p;\r\n\treturn Line3D(proj_p, proj_v);\r\n}\r\n\r\nCoordinatedPlane::CoordinatedPlane(void) { ; }\r\nCoordinatedPlane::CoordinatedPlane(const Point3D& _p, const Vector3D& _x, const Vector3D& _y) : Plane(_p, _x.cross_product(_y)), x(_x), y(_y) { ; }\r\n\r\nPoint3D CoordinatedPlane::convert(const Point2D& q) const { return p + q.x*x + q.y*y; }\r\nPoint2D CoordinatedPlane::convert(const Point3D& q, length_t *d) const {\r\n\tVector3D denominator_vector = x.cross_product(y);\r\n\tscalar_t denominator = denominator_vector.dot_product(denominator_vector);\r\n\tPoint2D ret;\r\n\tret.x = denominator_vector.dot_product((q - p).cross_product(y)) / denominator;\r\n\tret.y = denominator_vector.dot_product((p - q).cross_product(x)) / denominator;\r\n\tif (d) { *d = (q - p).dot_product(denominator_vector) / denominator; }\r\n\treturn ret;\r\n}\r\n\r\nbool Plane::is_parallel(const Plane& plane) const {\r\n\treturn h.cross_product(plane.h).is_zero();\r\n}\r\n\r\nLine3D Plane::intersect(const Plane& plane) const {\r\n\tconst Vector3D& u = h;\r\n\tconst Vector3D& v = plane.h;\r\n\r\n\tVector3D q_p = plane.p - p;\r\n\r\n\tVector3D uv = u.cross_product(v);\r\n\r\n\tVector3D vec_p_to_line = u.cross_product(uv);\r\n\tscalar_t alpha = (q_p).dot_product(v) / vec_p_to_line.dot_product(v);\r\n\tPoint3D start_point = p + alpha * vec_p_to_line;\r\n\r\n\tVector3D vec_line_to_q = v.cross_product(uv);\r\n\tscalar_t beta = (q_p).dot_product(u) / vec_line_to_q.dot_product(u);\r\n\tPoint3D end_point = plane.p - beta * vec_line_to_q;\r\n\r\n\treturn Line3D(start_point, end_point - start_point);\r\n}\r\n\r\nvoid Plane::get_basis(Vector3D* u, Vector3D* v) const {\r\n\tVector3D ux(1, 0, 0);\r\n\tVector3D uy(0, 1, 0);\r\n\tVector3D uz(0, 0, 1);\r\n\tscalar_t dx = abs(h.dot_product(ux));\r\n\tscalar_t dy = abs(h.dot_product(uy));\r\n\tscalar_t dz = abs(h.dot_product(uz));\r\n\r\n\tVector3D base_u, base_v;\r\n\r\n\tif (dx <= dy && dx <= dz) {\r\n\t\tbase_u = ux.get_perpendicular_component_to(h).normalized();\r\n\t\tbase_v = h.cross_product(base_u).normalized();\r\n\t}\r\n\telse if (dy <= dx && dy <= dz) {\r\n\t\tbase_u = uy.get_perpendicular_component_to(h).normalized();\r\n\t\tbase_v = h.cross_product(base_u).normalized();\r\n\t}\r\n\telse if (dz <= dx && dz <= dy) {\r\n\t\tbase_u = uz.get_perpendicular_component_to(h).normalized();\r\n\t\tbase_v = h.cross_product(base_u).normalized();\r\n\t}\r\n\r\n\tif (u) *u = base_u;\r\n\tif (v) *v = base_v;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\nbool interp(const Point3D& x, const Line3D& l, scalar_t *_alpha) {\r\n\t// x = l.p + alpha * l.v + h\r\n\t// where h is perpendicular to l.v\r\n\tscalar_t denominator = l.v.dot_product(l.v);\r\n\tif (abs(denominator) < EPSILON) return false;\r\n\tif (_alpha) {\r\n\t\t*_alpha = (x - l.p).dot_product(l.v) / denominator;\r\n\t}\r\n\treturn true;\r\n}\r\nbool interp(const Line3D& l1, const Line3D& l2, scalar_t *_alpha, scalar_t *_beta) {\r\n\t// l1.p + alpha * l1.v + h = l2.p + beta * l2.v\r\n\t// where h is perpendicular to both l1.v and l2.v\r\n\tVector3D q_p = l2.p - l1.p;\r\n\tVector3D uv = l1.v.cross_product(l2.v);\r\n\tscalar_t denominator = uv.dot_product(uv);\r\n\tif (abs(denominator) < EPSILON) return false;\r\n\tif (_alpha) {\r\n\t\t*_alpha = (q_p.cross_product(l2.v)).dot_product(uv) / denominator;\r\n\t}\r\n\tif (_beta) {\r\n\t\t*_beta = (q_p.cross_product(l1.v)).dot_product(uv) / denominator;\r\n\t}\r\n\treturn true;\r\n}\r\nbool interp(const Point3D& x, const Plane& p, scalar_t *_alpha) {\r\n\t// x = p.p + alpha * p.h + v\r\n\t// where v is a vector perpendicular to p.h\r\n\tif (_alpha) {\r\n\t\t*_alpha = (x - p.p).dot_product(p.h) / p.h.dot_product(p.h);\r\n\t}\r\n\treturn true;\r\n}\r\nbool interp(const Line3D& l, const Plane& p, scalar_t *_alpha) {\r\n\t// l.p + alpha * l.v = p.p + v\r\n\t// where v is a vector perpendicular to p.h\r\n\tscalar_t vh = l.v.dot_product(p.h);\r\n\tif (abs(vh) < EPSILON) return false;\r\n\tif (_alpha) {\r\n\t\t*_alpha = (p.p - l.p).dot_product(p.h) / vh;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool interp(const Plane& p, const Plane& q, Line3D *_line, Point3D *p_proj, Point3D *q_proj) {\r\n\tVector3D uv = p.h.cross_product(q.h);\r\n\tif (uv.is_zero()) return false;\r\n\tVector3D uuv = p.h.cross_product(uv);\r\n\tVector3D vuv = q.h.cross_product(uv);\r\n\r\n\tscalar_t d_alpha = uuv.dot_product(q.h);\r\n\tscalar_t d_gamma = vuv.dot_product(p.h);\r\n\tif (abs(d_alpha) < EPSILON || abs(d_gamma) < EPSILON) return false;\r\n\r\n\tVector3D q_p = q.p - p.p;\r\n\tPoint3D p_p = p.p + (q_p.dot_product(q.h) / d_alpha) * uuv;\r\n\tif (p_proj) {\r\n\t\t*p_proj = p_p;\r\n\t}\r\n\tif (q_proj) {\r\n\t\t*q_proj = q.p - (q_p.dot_product(p.h) / d_gamma) * vuv;\r\n\t}\r\n\tif (_line) {\r\n\t\t*_line = Line3D(p_p, uv.normalized());\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n#include <iostream>\r\nfloat solid_angle(const Point3D& o, const Point3D& p, const Point3D& q, const Point3D& r) {\r\n\tVector3D a = (p - o).normalized();\r\n\tVector3D b = (q - o).normalized();\r\n\tVector3D c = (r - o).normalized();\r\n\r\n\t//std::cout << \"VEC \" << a.x << ' ' << a.y << ' ' << a.z << std::endl;\r\n\t//std::cout << \"VEC \" << b.x << ' ' << b.y << ' ' << b.z << std::endl;\r\n\t//std::cout << \"VEC \" << c.x << ' ' << c.y << ' ' << c.z << std::endl;\r\n\r\n\tscalar_t abc = a.dot_product(b.cross_product(c));\r\n\tscalar_t div = 1 + a.dot_product(b) + a.dot_product(c) + b.dot_product(c);\r\n\r\n\tscalar_t omega = atan(abc/div);\r\n\r\n\t//std::cout << \"NORM \" << omega << '\\t' << abc << '\\t' << div << '\\t';\r\n\r\n\tif (div < 0) {\r\n\t\tif (omega < 0) omega += PI;\r\n\t\telse omega -= PI;\r\n\t}\r\n\r\n\t//std::cout << omega << std::endl;\r\n\t//if ((a + b + c).dot_product((b - a).cross_product(c - a)) < 0) omega = -omega;\r\n\treturn 2*omega;\r\n}", "meta": {"hexsha": "875a4a58bdc8e95b7250b71c0788614867b88cc5", "size": 17604, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geom_impl.cpp", "max_stars_repo_name": "STEMLab/TICA", "max_stars_repo_head_hexsha": "223940aaf67c5140a1db36159773fe65be213b4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T01:29:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T09:43:21.000Z", "max_issues_repo_path": "src/geom_impl.cpp", "max_issues_repo_name": "STEMLab/TICA", "max_issues_repo_head_hexsha": "223940aaf67c5140a1db36159773fe65be213b4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geom_impl.cpp", "max_forks_repo_name": "STEMLab/TICA", "max_forks_repo_head_hexsha": "223940aaf67c5140a1db36159773fe65be213b4f", "max_forks_repo_licenses": ["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.6356275304, "max_line_length": 148, "alphanum_fraction": 0.5869688707, "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5746098164447971}}
{"text": "#include \"eigen_ext.hpp\"\n#include \"parameters.hpp\"\n#include \"stiff.hpp\"\n#include <cassert>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n\nnamespace pear {\nvoid grad_phi(Vec &xp, Vec &yp, double &T, Vec &Dphi2, Vec &Dphi3) {\n\n  Dphi2 << yp(1) - yp(2), yp(2) - yp(0), yp(0) - yp(1);\n  Dphi3 << xp(2) - xp(1), xp(0) - xp(2), xp(1) - xp(0);\n\n  T = xp(1) * yp(2) + xp(0) * yp(1) + xp(2) * yp(0) - xp(1) * yp(0) -\n      xp(0) * yp(2) - xp(2) * yp(1);\n}\n\nMat stiff_block(Vec &xp, Vec &yp, double Dr, double Dz) {\n\n  Mat K_block(3, 3);\n\n  Vec Dphi2(3);\n  Vec Dphi3(3);\n  double T = 1;\n\n  grad_phi(xp, yp, T, Dphi2, Dphi3);\n\n  for (int idx1 = 0; idx1 < 3; idx1++) {\n    for (int idx2 = 0; idx2 < 3; idx2++) {\n      K_block(idx1, idx2) =\n          (xp(0) + xp(1) + xp(2)) *\n          (Dr * Dphi2(idx1) * Dphi2(idx2) + Dz * Dphi3(idx1) * Dphi3(idx2)) /\n          12 / T;\n    }\n  }\n  return K_block;\n}\n\nvoid stiff(Vec &xp, Vec &yp, MatI &t, Mat &Ku, Mat &Kv) {\n  // PRELIMINARIES\n  int np = xp.rows();\n  int nt = t.rows();\n\n  Mat Ku_block(3, 3);\n  Mat Kv_block(3, 3);\n\n  VecI t_loc(3);\n  Vec xp_loc(3);\n  Vec yp_loc(3);\n\n  for (int idxm = 0; idxm < nt; idxm++) {\n    t_loc = t.row(idxm);\n    xp_loc = pear::extract<Vec>(xp, t_loc);\n    yp_loc = pear::extract<Vec>(yp, t_loc);\n\n    Ku_block = stiff_block(xp_loc, yp_loc, pear::Dur, pear::Duz);\n    Kv_block = stiff_block(xp_loc, yp_loc, pear::Dvr, pear::Dvz);\n    for (int idx1 = 0; idx1 < 3; idx1++) {\n      for (int idx2 = 0; idx2 < 3; idx2++) {\n        Ku(t_loc(idx1), t_loc(idx2)) += Ku_block(idx1, idx2);\n        Kv(t_loc(idx1), t_loc(idx2)) += Kv_block(idx1, idx2);\n      }\n    }\n  }\n}\n\n} // namespace pear\n", "meta": {"hexsha": "6f3a521878bfb017d8e7979d2933c6d0588d4c9f", "size": 1675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/stiff.cpp", "max_stars_repo_name": "hdeplaen/the_winning_pear", "max_stars_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stiff.cpp", "max_issues_repo_name": "hdeplaen/the_winning_pear", "max_issues_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stiff.cpp", "max_forks_repo_name": "hdeplaen/the_winning_pear", "max_forks_repo_head_hexsha": "e3eb2f553fdcbdc7d5e5357dbb07fd60e41b8d35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9285714286, "max_line_length": 77, "alphanum_fraction": 0.5432835821, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5746080920391147}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n    boost::math::fft example 05\n    \n    several engines, different complex types.\n*/\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_complex.hpp>\n#include <boost/multiprecision/mpc.hpp>\n#ifdef BOOST_MATH_USE_FLOAT128\n#include <boost/multiprecision/complex128.hpp>\n#endif\n\n#if defined(__GNUC__)\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#endif\n#include <boost/math/fft/bsl_backend.hpp>\n#include <boost/core/demangle.hpp>\n#include <iostream>\n#include <vector>\n#include <complex>\n\ntemplate<class T>\nvoid print(const std::vector< T >& V)\n{\n    for(auto i=0UL;i<V.size();++i)\n        std::cout << \"V[\" << i << \"] = \" << std::setprecision(std::numeric_limits<typename T::value_type>::digits10 + 4)\n            << V[i].real() << \", \" << V[i].imag() << '\\n';\n}\n\ntemplate<class Complex>\nvoid test_bsl() {\n    std::cout << \"BSL engine with \" << boost::core::demangle(typeid(Complex).name()) << \"\\n\";\n    std::cout << \"Real type is    \" << boost::core::demangle(typeid(typename Complex::value_type).name()) << \"\\n\";\n    std::vector< Complex > A{1.0,2.0,3.0,4.0},B(A.size());\n    // forward transform, out-of-place\n    boost::math::fft::transform<boost::math::fft::bsl_dft<Complex>>::forward(A.cbegin(),A.cend(),B.begin());\n    print(B);\n    // backward transform, in-place\n    boost::math::fft::transform<boost::math::fft::bsl_dft<Complex>>::backward(B.cbegin(),B.cend(),B.begin());\n    print(B);\n}\n\n#if defined(__GNUC__)\ntemplate<class Complex>\nvoid test_fftw() {\n    std::cout << \"FFTW engine with \" << boost::core::demangle(typeid(Complex).name()) << \"\\n\";\n    std::vector< Complex > A{1.0,2.0,3.0,4.0},B(A.size());\n    // forward transform, out-of-place\n    boost::math::fft::transform<boost::math::fft::fftw_dft<Complex>>::forward(A.cbegin(),A.cend(),B.begin());\n    print(B);\n    // backward transform, in-place\n    boost::math::fft::transform<boost::math::fft::fftw_dft<Complex>>::backward(B.cbegin(),B.cend(),B.begin());\n    print(B);\n}\n\ntemplate<class Complex>\nvoid test_gsl() {\n    std::cout << \"GSL engine with \" << boost::core::demangle(typeid(Complex).name()) << \"\\n\";\n    std::vector< Complex > A{1.0,2.0,3.0,4.0},B(A.size());\n    // forward transform, out-of-place\n    boost::math::fft::transform<boost::math::fft::gsl_dft<Complex>>::forward(A.cbegin(),A.cend(),B.begin());\n    print(B);\n    // backward transform, in-place\n    boost::math::fft::transform<boost::math::fft::gsl_dft<Complex>>::backward(B.cbegin(),B.cend(),B.begin());\n    print(B);\n}\n#endif\n\nint main()\n{\n    test_bsl<std::complex<float>>();\n    test_bsl<std::complex<double>>();\n    test_bsl<std::complex<long double>>();\n#ifdef BOOST_MATH_USE_FLOAT128\n    test_bsl< boost::multiprecision::complex128 >();\n#endif\n    test_bsl< boost::multiprecision::cpp_complex_50 >();\n    test_bsl< boost::multiprecision::cpp_complex_quad >();\n#if defined(__GNUC__)\n    test_bsl< boost::multiprecision::mpc_complex_50 >();\n#endif\n\n#if defined(__GNUC__)\n    test_fftw<std::complex<float>>();\n    test_fftw<std::complex<double>>();\n    test_fftw<std::complex<long double>>();\n#endif\n#ifdef BOOST_MATH_USE_FLOAT128\n    test_fftw<boost::multiprecision::complex128>();\n#endif\n\n#if defined(__GNUC__)\n    test_gsl<std::complex<double>>();\n#endif\n    return 0;\n}\n\n", "meta": {"hexsha": "562acb2ee39a234366b22bbe3b399f869f7a302f", "size": 3684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fft_ex05.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fft_ex05.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "example/fft_ex05.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 34.1111111111, "max_line_length": 120, "alphanum_fraction": 0.654723127, "num_tokens": 1020, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.574608075768575}}
{"text": "/**\n * si_function.hpp\n *\n * This file defines functions from a shift invariant space. We call these\n * Shift Invariant Functions (si_functions), which is a slight abuse \n * of naming to mean that they come from shift invariant spaces.\n *\n * @author Joshua Horacsek\n **/\n\n#ifndef _SISL_SI_FUNCTION_H_\n#define _SISL_SI_FUNCTION_H_\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <sisl/primitives.hpp>\n#include <sisl/function/base_function.hpp>\n\nnamespace sisl {\n\n\t/*! \\brief Combines a lattice and a generating function.\n\t * \n\t */\n    template<class L, class BF, int N>\n    class si_function : public function {\n    public:\n        /*! \\brief Evaluate the function at a point.\n         */\n        si_function() : _bForceScale(false), _lattice(nullptr), _dBasisScale(1.), _bUseBasisDerivative(true){\n            _mSpaceTransform = Eigen::MatrixXd::Identity(N, N);\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        si_function(L *lattice) : si_function(){\n            _lattice = lattice;\n        }\n\n        virtual ~si_function() {\n\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const double operator()(double d0, ...) const {\n            va_list vl;\n            vector V(N);\n            V[0] = d0;\n\n            va_start(vl, d0);\n            for(unsigned int i = 1; i < N; i++) {\n                V[i] = va_arg(vl, double);\n            }\n            va_end(vl);\n\n            return (*this)(V);\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const double operator()(const vector &p) const {\n            if(_lattice == nullptr) return 0;\n\n            if(!_bForceScale) {\n                return BF::template convolution_sum<N, L, BF>(\n                            _mSpaceTransform*p,\n                            (const L*)_lattice);\n            }\n            return BF::template convolution_sum_h<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_lattice,\n                        _dBasisScale);\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const double d(int component, double d0, ...) const {\n            va_list vl;\n            vector V(N);\n            V[0] = d0;\n\n            va_start(vl, d0);\n            for(unsigned int i = 1; i < N; i++) {\n                V[i] = va_arg(vl, double);\n            }\n            va_end(vl);\n\n            return d(component, V);\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const double d(int component, const vector &p) const {\n            if(_bUseBasisDerivative && BF::has_derivative()) {\n                if(!_bForceScale)\n                    return BF::template convolution_sum_deriv<N, L, BF>(\n                            _mSpaceTransform*p,\n                            (const L*)_lattice,\n                            component);\n                return BF::template convolution_sum_deriv_h<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_lattice,\n                        component,\n                        _dBasisScale);\n\n            }\n            if(!_d[component]) return 0;\n            if(!_bForceScale)\n                return BF::template convolution_sum<N, L, BF>(\n                            _mSpaceTransform*p,\n                            (const L*)_d[component]);\n            return BF::template convolution_sum_h<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_d[component],\n                        _dBasisScale);\n\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const vector grad(double d0, ...) const {\n            va_list vl;\n            vector V(N);\n            V[0] = d0;\n\n            va_start(vl, d0);\n            for(unsigned int i = 1; i < N; i++) {\n                V[i] = va_arg(vl, double);\n            }\n            va_end(vl);\n\n            return grad(V);\n        }\n\n        /*! \\brief Evaluate the function at a point.\n         */\n        virtual const vector grad(const vector &p) const {\n            if(_bUseBasisDerivative && BF::has_derivative()) {\n                if(!_bForceScale)\n                    return BF::template grad_convolution_sum<N, L, BF>(\n                            _mSpaceTransform*p,\n                            (const L*)_lattice);\n                return BF::template grad_convolution_sum_h<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_lattice,\n                        _dBasisScale);\n\n            }\n            if(!_bForceScale)\n                return BF::template grad_convolution_sum<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_lattice,\n                        (const L**)_d);\n            return BF::template grad_convolution_sum_h<N, L, BF>(\n                        _mSpaceTransform*p,\n                        (const L*)_lattice,\n                        (const L**)_d,\n                        _dBasisScale);\n\n        }\n        /*! \\brief Sets a scale for the basis function to use.\n        */\n        void set_basis_scale(const double &h) {\n            _dBasisScale = h;\n            _bForceScale = true;\n        }\n\n        /*! \\brief If the basis has a derivative, this makes the function use\n         * that derivative for derivative reconstruction\n         */\n        void use_basis_gradient() {\n            _bUseBasisDerivative = true;\n        }\n\n        /*! \\brief If the function has derivative lattices, this makes the\n         * function use the given basis to reconstruct derivative values.\n         */\n        void use_derivative_lattice() {\n            _bUseBasisDerivative = false;\n        }\n\n        /*! \\brief Sets the current reconstruction lattice\n         */\n        void set_lattice(L *new_lat) {\n            this->_lattice = new_lat;\n        }\n\n        /*! \\brief Sets the lattice to be used for derivative reconstruction\n         *  use use_derivative_lattice() to use this for reconstruction after\n         *  all lattices have been set.\n         */\n        void set_derivative_lattice(unsigned int component, L *d) {\n            if(component < N)\n                _d[component] = d;\n        }\n\n        /*! \\brief Sets the transform for this space,\n        */\n        void set_transform(const transform &t){\n            if(fabs(t.determinant()) > 1e-8)\n                _mSpaceTransform = t;\n        }\n\n        /*! \\bried Gets the transform assiated to this space,\n         */\n        transform get_transform() const{\n            return _mSpaceTransform;\n        }\n\n        L *get_lattice() {\n            return _lattice;\n        }\n\n        void set_scale(const vector &s) {\n            m_vUserScale = s;\n            _mSpaceTransform *= Eigen::Scaling(s);\n        }\n\n        vector get_scale() const {\n            return m_vUserScale;\n        }\n        virtual const int dim() const {\n        \treturn N;\n        }\n         \n        virtual const double n_d(const int_tuple &order, double d0, ...) const {\n        \tthrow \"Not yet implemnented\";\n\n        }\n\n        virtual const double n_d(const int_tuple &order, vector &p) const {\n        \tthrow \"Not yet implemnented\";\n        }\n\n    private:\n        L *_lattice, *_d[N];\n        bool _bUseBasisDerivative;\n        bool _bForceScale;\n        double _dBasisScale;\n        transform _mSpaceTransform;\n        sisl::vector m_vUserScale;\n    };\n}\n\n#endif // _SISL_SI_FUNCTION_H_\n", "meta": {"hexsha": "e40ea19ee241b31afed5cc929caf87f192086811", "size": 7516, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sisl/function/si_function.hpp", "max_stars_repo_name": "jjh13/sisl_redux", "max_stars_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-01T16:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-19T22:07:44.000Z", "max_issues_repo_path": "include/sisl/function/si_function.hpp", "max_issues_repo_name": "jjh13/sisl_redux", "max_issues_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-19T22:07:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-05T18:36:24.000Z", "max_forks_repo_path": "include/sisl/function/si_function.hpp", "max_forks_repo_name": "jjh13/sisl", "max_forks_repo_head_hexsha": "e4c276e0661729e9f4cfff4828f1ed31401601cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5528455285, "max_line_length": 109, "alphanum_fraction": 0.4974720596, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5746080757685749}}
{"text": "/*\n * StokesM2L.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 <iomanip>\n#include <iostream>\n#include <chrono>\n\n#define DIRECTLAYER 2\n#define PI314 (static_cast<double>(3.1415926535897932384626433))\n\nnamespace Laplace2D3D {\n\nusing EVec3 = Eigen::Vector3d;\n\ninline double ERFC(double x) { return std::erfc(x); }\ninline double ERF(double x) { return std::erf(x); }\n\n// real and wave sum of 2D Laplace kernel Ewald\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 < 1e-14) {\n        return 0;\n    }\n    return ERFC(rnorm * xi) / rnorm;\n}\n\n// xm: target, xn: source\ninline double realSum2(const double xi, const EVec3 &xn, const EVec3 &xm) {\n    double zmn = xm[2] - xn[2];\n    double answer =\n        exp(-xi * xi * zmn * zmn) / xi + sqrt(PI314) * zmn * ERF(xi * zmn);\n    return answer;\n}\n\ninline double gkzxi(const double k, double zmn, double xi) {\n    double answer = exp(k * zmn) * ERFC(k / (2 * xi) + xi * zmn) +\n                    exp(-k * zmn) * ERFC(k / (2 * xi) - xi * zmn);\n    return answer;\n}\n\ninline double selfTerm(double xi) { return -2 * xi / sqrt(PI314); }\n\ninline double gKernelEwald(const EVec3 &xm, const EVec3 &xn) {\n    const double xi = 1.8; // 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    source[0] = source[0] - floor(source[0]);\n    source[1] = source[1] - floor(source[1]);\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            EVec3 rmn = target - source + EVec3(i, j, 0);\n            if (rmn.norm() < 1e-13) {\n                continue;\n            }\n            Kreal += realSum(xi, EVec3(0, 0, 0), rmn);\n        }\n    }\n\n    // wave sum\n    int wLim = 4;\n    double Kwave = 0;\n    EVec3 rmn = target - source;\n    const double rmnnorm = rmn.norm();\n    double zmn = rmn[2];\n    rmn[2] = 0;\n    for (int i = -wLim; i <= wLim; i++) {\n        for (int j = -wLim; j <= wLim; j++) {\n            if (i == 0 && j == 0) {\n                continue;\n            }\n            EVec3 kvec = EVec3(i, j, 0) * (2 * PI314);\n            double knorm = kvec.norm();\n            Kwave += cos(kvec[0] * rmn[0] + kvec[1] * rmn[1]) * (1 / knorm) *\n                     gkzxi(knorm, zmn, xi);\n        }\n    }\n    Kwave *= PI314;\n\n    double Kreal2 = 2 * sqrt(PI314) * realSum2(xi, source, target);\n    double Kself = rmnnorm < 1e-10 ? -2 * xi / sqrt(PI314) : 0;\n\n    return Kreal + Kwave - Kreal2 + Kself;\n}\n\ninline double gKernel(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    return rnorm < 1e-14 ? 0 : 1 / rnorm;\n}\n\n// Out of Direct Sum Layer, far field part\ninline double gKernelFF(const EVec3 &target, const EVec3 &source) {\n    double fEwald = gKernelEwald(target, source);\n    const int N = DIRECTLAYER;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            double gFree = gKernel(target, source - EVec3(i, j, 0));\n            fEwald -= gFree;\n        }\n    }\n\n    //   {\n    //     std::cout << \"source:\" << source << std::endl\n    //               << \"target:\" << target << std::endl\n    //               << \"gKernalFF\" << fEwald << std::endl;\n    //   }\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    // testing Ewald routine\n    double Madelung2D =\n        gKernelEwald(EVec3(0, 0, 0), EVec3(0.5, 0.5, 0)) * (-1) +\n        gKernelEwald(EVec3(0, 0, 0), EVec3(0, 0, 0)) * 1;\n    std::cout << std::setprecision(16) << \"Madelung2D: \" << Madelung2D\n              << \" Error: \" << Madelung2D + 2.2847222932891311 << std::endl;\n\n    //   exit(1);\n\n    std::chrono::high_resolution_clock::time_point t1 =\n        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] = {\n        -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {\n        -(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] = {\n        -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n    const double pCenterLCheck[3] = {\n        -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n    auto pointMEquiv = surface(\n        pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(\n        pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(\n        pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(\n        pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv,\n        0); // 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    Eigen::MatrixXd A(1 * checkN, 1 * equivN);\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                               pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l],\n                                         pointLEquiv[3 * l + 1],\n                                         pointLEquiv[3 * l + 2]);\n            A(k, l) = gKernel(Cpoint, Lpoint);\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\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],\n                                     pointMEquiv[3 * i + 2]);\n        //\t\tstd::cout << \"debug:\" << Mpoint << std::endl;\n\n        // assemble linear system\n        Eigen::VectorXd f(checkN);\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                                   pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            f(k) = gKernelFF(Cpoint, Mpoint);\n        }\n        //\t\tstd::cout << \"debug:\" << f << std::endl;\n\n        M2L.col(i) = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n    std::chrono::high_resolution_clock::time_point t2 =\n        std::chrono::high_resolution_clock::now();\n    auto duration =\n        std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n    std::cout << \"Precomputing time:\" << duration / 1e6 << std::endl;\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\n                      << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        chargePoint(2);\n    std::vector<double> chargeValue(2);\n    chargePoint[0] = Eigen::Vector3d(0.5, 0.5, 0);\n    chargeValue[0] = -1;\n    chargePoint[1] = Eigen::Vector3d(0, 0, 0);\n    chargeValue[1] = 1;\n\n    // solve M\n    A.resize(checkN, equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\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],\n                               pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < chargePoint.size(); p++) {\n            temp = temp + gKernel(Cpoint, chargePoint[p]) * (chargeValue[p]);\n        }\n        f(k) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1],\n                                   pointMEquiv[3 * l + 2]);\n            A(k, l) = gKernel(Mpoint, Cpoint);\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    Eigen::Vector3d samplePoint(0, 0, 0);\n    double Usample = 0;\n    double UsampleSP = 0;\n\n    for (int i = -DIRECTLAYER; i < 1 + DIRECTLAYER; i++) {\n        for (int j = -DIRECTLAYER; j < 1 + DIRECTLAYER; j++) {\n            for (size_t p = 0; p < chargePoint.size(); p++) {\n                Usample +=\n                    gKernel(samplePoint, chargePoint[p] + EVec3(i, j, 0)) *\n                    chargeValue[p];\n            }\n        }\n    }\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n                               pointLEquiv[3 * p + 2]);\n        UsampleSP += gKernel(samplePoint, Lpoint) * M2Lsource[p];\n    }\n\n    std::cout << \"samplePoint:\" << samplePoint << std::endl;\n    std::cout << \"Usample NF:\" << Usample << std::endl;\n    std::cout << \"Usample FF:\" << UsampleSP << std::endl;\n    std::cout << \"Usample FF+NF total:\" << UsampleSP + Usample << std::endl;\n    std::cout << \"Error : \" << UsampleSP + Usample + 2.284722293289131159\n              << std::endl;\n\n    samplePoint = EVec3(0.5, 0.5, 0);\n    Usample = 0;\n    UsampleSP = 0;\n\n    for (int i = -DIRECTLAYER; i < 1 + DIRECTLAYER; i++) {\n        for (int j = -DIRECTLAYER; j < 1 + DIRECTLAYER; j++) {\n            for (size_t p = 0; p < chargePoint.size(); p++) {\n                Usample +=\n                    gKernel(samplePoint, chargePoint[p] + EVec3(i, j, 0)) *\n                    chargeValue[p];\n            }\n        }\n    }\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n                               pointLEquiv[3 * p + 2]);\n        UsampleSP += gKernel(samplePoint, Lpoint) * M2Lsource[p];\n    }\n\n    std::cout << \"samplePoint:\" << samplePoint << std::endl;\n    std::cout << \"Usample NF:\" << Usample << std::endl;\n    std::cout << \"Usample FF:\" << UsampleSP << std::endl;\n    std::cout << \"Usample FF+NF total:\" << UsampleSP + Usample << std::endl;\n    std::cout << \"Error : \" << UsampleSP + Usample - 2.284722293289131159\n              << std::endl;\n\n    return 0;\n}\n\n} // namespace Laplace2D3D\n\n#undef DIRECTLAYER\n#undef PI314\n", "meta": {"hexsha": "3c9080fc9da9f39fcbe7139a4a21d2187cf6b9a9", "size": 13016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2LLaplace/src/Laplace2D3D.cpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "M2LLaplace/src/Laplace2D3D.cpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2LLaplace/src/Laplace2D3D.cpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 35.0835579515, "max_line_length": 80, "alphanum_fraction": 0.5109864782, "num_tokens": 4444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5746080703512123}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// main.cpp\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#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include <functional>\n#include <fstream>\n#include <boost/mpl/size_t.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/delay.hpp>\n#include <boost/accumulators/statistics/acvf_moving_average.hpp>\n#include <boost/accumulators/statistics/acvf.hpp>\n#include <boost/accumulators/statistics/acf.hpp>\n#include <boost/accumulators/statistics/integrated_acf.hpp>\n#include <boost/accumulators/statistics/integrated_acvf.hpp>\n#include <boost/accumulators/statistics/percentage_effective_sample_size.hpp>\n#include <boost/accumulators/statistics/standard_error_autocorrelated.hpp>\n#include <boost/accumulators/statistics/standard_error_iid.hpp>\n#include <boost/accumulators/statistics/acvf_analysis.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/moving_average.hpp>\n#include <boost/bind.hpp>\n#include <boost/ref.hpp>\n#include <boost/assign/std/vector.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/numeric/conversion/converter.hpp>\nint main(){\n\n    const char* filepath = \"./acvf_output\";\n    std::ofstream out(filepath);\n\n    using namespace boost::accumulators;\n    typedef boost::mt19937                                    urng_type;\n    typedef boost::normal_distribution<>                      nd_type;\n    typedef boost::variate_generator<urng_type&,nd_type>      gen_nd_type;\n    typedef double                                            value_type;\n    typedef boost::random::moving_average<value_type>         ma_type;\n    typedef std::vector<value_type>                           ma_vals_type;\n    //typedef default_delay_discriminator                       delaydisrc;\n    typedef default_delay_discriminator                       discr_t;\n    typedef accumulator_set<\n        value_type, stats<\n            tag::acvf<discr_t>,\n            tag::acf<discr_t>,\n            tag::integrated_acvf<discr_t>,\n            tag::percentage_effective_sample_size<discr_t>,\n            tag::standard_error_autocorrelated<discr_t>,\n            tag::standard_error_iid<discr_t>\n            >\n    >            acc_type;\n\n    //model parameters and related quantities\n    std::vector<value_type>     coeffs;\n    std::vector<unsigned int>   lags;\n    std::vector<value_type>     true_acfs;\n    value_type                  true_integrated_acvf = 0.0;\n    std::size_t                 true_ess = 0;\n    //with these coeffs, should expect ess% > 100\n    {using namespace boost::assign; coeffs+=1.0,-0.5,0.2; lags+=0,1,2;}\n    unsigned int  K = coeffs.size()-1;\n    transform(lags.begin(),lags.end(),back_inserter(true_acfs),\n        make_acvf_moving_average(coeffs));\n    true_integrated_acvf\n        = 2*std::accumulate(true_acfs.begin(),true_acfs.end(),0.0);\n    true_integrated_acvf -=  *true_acfs.begin();\n    true_ess = boost::numeric::converter<std::size_t,value_type>::convert(\n        100.0*true_acfs[0]/true_integrated_acvf);\n\n    out << \"->true_acvf: \";\n    copy(true_acfs.begin(),true_acfs.end(),\n        std::ostream_iterator<value_type>(out,\" \"));\n    out << \"<-\" << std::endl;\n    {   value_type div = 1.0/true_acfs[0];\n        transform(true_acfs.begin(),true_acfs.end(),true_acfs.begin(),\n            boost::bind(std::multiplies<value_type>(),_1,div));\n    }\n    out << \"->true_acf: \";\n    copy(true_acfs.begin(),true_acfs.end(),\n        std::ostream_iterator<value_type>(out,\" \")); out << \"<-\" << std::endl;\n    out << \"->true var: \" << true_integrated_acvf << \"<-\" << std::endl;\n    out << \"->true ess%: \" << true_ess << \"<-\" << std::endl;\n\n    //generation of a Moving Average of order K process\n    const unsigned long N = 100000;\n    urng_type urng(0);\n    gen_nd_type gen_nd(urng,nd_type());\n    ma_type ma(boost::make_iterator_range(coeffs.begin(),coeffs.end()));\n    ma_vals_type ma_vals(N);\n    for(ma_vals_type::iterator i=ma_vals.begin(); i<ma_vals.end(); i++)\n    { (*i) = ma(gen_nd); }\n\n    //estimation\n    acc_type acc(tag::delay<discr_t>::cache_size=(K+1));\n    for_each(ma_vals.begin(),ma_vals.end(),\n        boost::bind<void>(boost::ref(acc),_1));\n    out << \"->sample size: \" << N << std::endl;\n    out << \"->estimated acvf: \";\n    copy(begin(acvf<discr_t>(acc)),end(acvf<discr_t>(acc)),\n        std::ostream_iterator<value_type>(out,\" \"));\n    out<<\"<-\"<<std::endl;\n\n    out << \"->estimated acf: \";\n    copy(begin(acf<discr_t>(acc)),end(acf<discr_t>(acc)),\n        std::ostream_iterator<value_type>(out,\" \"));\n    out<<\"<-\"<<std::endl;\n\n    out << \"->estimated var: \"\n        << integrated_acvf<discr_t>(acc) << \"<-\" << std::endl;\n\n    out << \"->estimated ess%: \"\n        << percentage_effective_sample_size<discr_t>(acc)\n        << \"<-\" << std::endl;\n\n    out << \"->estimated standard error assuming iid: \"\n        << standard_error_iid<discr_t>(acc) << \"<-\" << std::endl;\n\n    out << \"->estimated standard error assuming acf is zero after lag \"\n        << K << \": \"\n        << standard_error_autocorrelated<discr_t>(acc) << \"<-\" << std::endl;\n\n    //the above bundled into one class:\n    out << \" --------- \";\n    out << \"output from acvf_analysis:\" << std::endl;\n    const unsigned int offset = 0;\n    const unsigned int stride = 1;\n    const unsigned int assumed_lag = 3;\n    statistics::acvf_analysis<value_type,discr_t> acvf_x(assumed_lag);\n    acvf_x(ma_vals,offset,stride);\n    acvf_x.print(out);\n\n    std::cout << \"output of libs/accumulators/main.cpp was written to\"\n        << filepath << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "16fc223e65d3f77e1a90f7d1d4659d543a54e8b4", "size": 5932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "autocovariance/libs/accumulators/statistics/example/main.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": "autocovariance/libs/accumulators/statistics/example/main.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": "autocovariance/libs/accumulators/statistics/example/main.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": 41.1944444444, "max_line_length": 79, "alphanum_fraction": 0.6360418071, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5745649627300556}}
{"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 \"gps_conversion.h\"\n#include <cmath>\n#include <Eigen/Dense>\n\nnamespace mars\n{\nstd::ostream& operator<<(std::ostream& out, const GpsCoordinates& coordinates)\n{\n  out << \"Lat:\\t\" << coordinates.latitude_ << std::endl;\n  out << \"Long:\\t\" << coordinates.longitude_ << std::endl;\n  out << \"Alt:\\t\" << coordinates.altitude_ << std::endl;\n\n  return out;\n}\n\nEigen::Matrix<double, 3, 1> mars::GpsConversion::get_enu(mars::GpsCoordinates coordinates)\n{\n  return WGS84ToENU(coordinates);\n}\n\nGpsConversion::GpsConversion(mars::GpsCoordinates coordinates)\n{\n  ecef_ref_orientation_.setIdentity();\n  ecef_ref_point_.setZero();\n\n  set_gps_reference(coordinates);\n}\n\nGpsCoordinates mars::GpsConversion::get_gps_reference()\n{\n  return reference_;\n}\n\nvoid GpsConversion::set_gps_reference(mars::GpsCoordinates coordinates)\n{\n  // set gps reference coordinates\n  reference_ = coordinates;\n\n  // set ecef reference, position and orientation\n  const double rad_lat = deg2rad(coordinates.latitude_);\n  const double rad_long = deg2rad(coordinates.longitude_);\n\n  const double s_lat = sin(rad_lat);\n  const double c_lat = cos(rad_lat);\n\n  const double s_long = sin(rad_long);\n  const double c_long = cos(rad_long);\n\n  Eigen::Matrix3d R;\n  R(0, 0) = -s_long;\n  R(0, 1) = c_long;\n  R(0, 2) = 0;\n\n  R(1, 0) = -s_lat * c_long;\n  R(1, 1) = -s_lat * s_long;\n  R(1, 2) = c_lat;\n\n  R(2, 0) = c_lat * c_long;\n  R(2, 1) = c_lat * s_long;\n  R(2, 2) = s_lat;\n\n  ecef_ref_orientation_ = R;\n  ecef_ref_point_ = WGS84ToECEF(coordinates);\n}\n\ndouble GpsConversion::deg2rad(const double& deg)\n{\n  return (M_PI / 180) * deg;\n}\n\nEigen::Matrix<double, 3, 1> GpsConversion::WGS84ToENU(const mars::GpsCoordinates& coordinates)\n{\n  return ECEFToENU(WGS84ToECEF(coordinates));\n}\n\nEigen::Matrix<double, 3, 1> GpsConversion::ECEFToENU(const Eigen::Matrix<double, 3, 1>& ecef)\n{\n  Eigen::Matrix<double, 3, 1> enu = ecef_ref_orientation_ * (ecef - ecef_ref_point_);\n  return enu;\n}\n\nEigen::Matrix<double, 3, 1> GpsConversion::WGS84ToECEF(const mars::GpsCoordinates& coordinates)\n{\n  // WGS84 ellipsoid constants\n  constexpr double a = 6378137.0;             // semi-major axis\n  constexpr double ecc = 8.1819190842622e-2;  // eccentricity of this ellipsoid\n  constexpr double ecc_sq = ecc * ecc;\n\n  const double rad_lat = deg2rad(coordinates.latitude_);\n  const double rad_long = deg2rad(coordinates.longitude_);\n\n  const double s_lat = sin(rad_lat);\n  const double c_lat = cos(rad_lat);\n  const double s_long = sin(rad_long);\n  const double c_long = cos(rad_long);\n\n  const double N = a / sqrt(1 - ecc_sq * s_lat * s_lat);\n\n  Eigen::Matrix<double, 3, 1> ecef;\n  const double h = coordinates.altitude_;\n  ecef(0) = (N + h) * c_lat * c_long;\n  ecef(1) = (N + h) * c_lat * s_long;\n  ecef(2) = (N * (1 - ecc_sq) + h) * s_lat;\n\n  return ecef;\n}\n}\n", "meta": {"hexsha": "0227225adf40e85fde4ea9fc65b8481f0bdbaa42", "size": 3209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/mars/include/mars/sensors/gps/gps_conversion.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/include/mars/sensors/gps/gps_conversion.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/include/mars/sensors/gps/gps_conversion.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": 27.1949152542, "max_line_length": 105, "alphanum_fraction": 0.7011530072, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.574564940852874}}
{"text": "/* -*-c++-*--------------------------------------------------------------------\n * 2019 Bernd Pfrommer bernd.pfrommer@gmail.com\n */\n\n#include \"tagslam/logging.h\"\n#include \"tagslam/rpp.h\"\n#include \"tagslam/quartic.h\"\n#include <boost/range/irange.hpp>\n#include <iostream>\n#include <math.h>\n\n//\n// Implementation of tests for checking if tag can be 'flipped',\n// and a second valid pose can be obtained. This gives a measure of\n// how well the tag-to-camera transform is established.\n//\n// See paper: \"Robust Pose Estimation from a Planar Target\"\n// by Gerald Schweighofer and Alex Pinz\n//\n// Notes:\n//\n// 1) The paper is a bit nebulous about how to compute \\tilde{R}_z^-1.\n//    What it means concretely: decompose\n//\n//    \\tilde{R}_1 = Rz(gamma) * Ry(beta) * Rz(gamma'),\n//\n//    and set \\tilde{R}_z^{-1} = Rz(gamma'). Then \n//\n//    \\tilde{R}_1 * \\tilde{R}_z = Rz(gamma) * Ry(beta),\n//\n//    i.e. only z and y rotations.\n//    \n// 2) top of page 6, beta_t = tan(1/(2*beta)) is wrong, it should\n//    read beta_t = tan(beta/2)\n//\n// 3) I cannot reproduce their expression for the gradient. I think it's\n//    wrong, but not sure. I derived my own, which works. This affects\n//    equations (12) and (13) in the paper:\n//\n//    (12) becomes:\n//\n//    t_opt = -G * sum_i (I-\\tilde{V}_i)^2 R_z(gamma) R_y(beta) \\tilde{p}_i\n//\n//    with G = (sum_i (I-\\tilde{V}_i)^2)^{-1}\n//\n//    (13) is modified accordingly:\n//\n//    E_os = sum_i |... - G sum_j(I -\\tilde{V}_j)^2 R_z  R_y \\tilde{p}_i|^2\n\n// #define DEBUG\n\nnamespace tagslam {\n  namespace rpp {\n    using boost::irange;\n\n    static double eval_poly(double x, const double *a, int n) {\n      double p = 1.0;\n      double sum = 0;\n      for (const auto i: irange(0, n)) {\n        sum += p * a[i];\n        p = p * x;\n      }\n      return (sum);\n    }\n\n    //\n    // computes rotation R_t from the paper: it rotates the optical axis\n    // to face to the origin (center) of the tag.\n    //\n    static Transform rotate_to_z(\n      const Eigen::Vector3d &translat, double *ang) {\n      const double t_norm = translat.norm();\n      const Eigen::Vector3d txz = translat.cross(Eigen::Vector3d::UnitZ());\n      const double sin_a_t_norm = txz.norm();\n      if (std::abs(sin_a_t_norm) < 1e-8) {\n        return Eigen::Isometry3d::Identity();\n      }\n      const double sin_a = sin_a_t_norm / t_norm;\n      const Eigen::Vector3d n = txz / sin_a_t_norm;\n      //const Transform tf = Eigen::AngleAxisd(std::asin(sin_a), n);\n      *ang = std::asin(sin_a);\n      const Transform tf = (Transform) Eigen::AngleAxisd(*ang, n);\n      return (tf);\n    }\n\n    typedef std::vector<Eigen::Matrix3d,\n                        Eigen::aligned_allocator<Eigen::Matrix3d> > M33dVec;\n\n    //\n    // make normalized matrices \\tilde{V}_i from \\tilde{v}_i\n    //\n    static M33dVec V_from_v(const ImgPointsH &v) {\n      M33dVec V(v.rows());\n      for (int i = 0; i < v.rows(); i++) {\n        const double vnsq = v.row(i).squaredNorm();\n        if (vnsq > 1e-12) {\n          V[i] = v.row(i).transpose()*v.row(i) / vnsq;\n        } else {\n          V[i] = Eigen::Matrix3d::Zero();\n        }\n      }\n      return (V);\n    }\n\n    //\n    // computes G from the paper (but using my formula)\n    //\n    static Eigen::Matrix3d compute_G(const M33dVec &V_tilde) {\n      Eigen::Matrix3d ImV_sum = Eigen::Matrix3d::Zero();\n      for (const auto &V_i: V_tilde) {\n        const auto ImV = Eigen::Matrix3d::Identity() - V_i;\n        ImV_sum = ImV_sum + ImV.transpose() * ImV;\n      }\n      return (ImV_sum.inverse());\n    }\n\n    //\n    // little helper matrix K that extracts beta_t to various powers\n    // from R_y(beta_t)*p\n    //\n    static Eigen::Matrix3d make_K(const Eigen::Vector3d &p) {\n      Eigen::Matrix3d K;\n      K <<\n        p(0),  2*p(2), -p(0),\n        p(1),     0.0,  p(1),\n        p(2), -2*p(0), -p(2);\n      return (K);\n    }\n\n    //\n    // compute helper matrix FTF = F^T * F.\n    //\n    // The error E can be expressed then as:\n    //\n    // E_os(beta_t) = (1+beta_t^2)^{-2} * mu^T * (F^T * F) * mu\n    //\n    // where mu = [1, beta_t, beta_t^2]^T\n    //\n\n    static Eigen::Matrix3d compute_FTF(const M33dVec &V_tilde,\n                                       const Transform &R_z,\n                                       const ObjPoints &p_tilde) {\n      const int n = p_tilde.rows(); // number of points\n      const auto G = compute_G(V_tilde);\n      Eigen::Matrix3d C_sum = Eigen::Matrix3d::Zero();\n      M33dVec C(n);\n      for (const auto i: irange(0ul, V_tilde.size())) {\n        const auto ImV_i = Eigen::Matrix3d::Identity() - V_tilde[i];\n        C[i] = ImV_i * R_z * make_K(p_tilde.row(i));\n        C_sum = C_sum + ImV_i.transpose() * C[i];\n      }\n      Eigen::Matrix3d FTF = Eigen::Matrix3d::Zero();\n      for (const auto i: irange(0ul, V_tilde.size())) {\n        const auto ImV_i = Eigen::Matrix3d::Identity() - V_tilde[i];\n        const auto F_i   = C[i] - ImV_i * G * C_sum;\n        FTF = FTF + F_i.transpose() * F_i;\n      }\n      return (FTF);\n    }\n\n    //\n    // Starting from\n    //\n    // E_os(beta_t) = (1+beta_t^2)^{-2} * mu^T * (F^T * F) * mu\n    // where mu = [1, beta_t, beta_t^2]^T\n    //\n    // now express E_os(beta_t) and derivates as polynomials in beta_t\n    //\n    // E_os   = (1+beta^2)^{-2} * (sum_{i=0^n} f[i] beta^i)\n    // E_os'  = (1+beta^2)^{-3} * (sum_{i=0^n} g[i] beta^i)\n    // E_os'' = (1+beta^2)^{-4} * (sum_{i=0^n} h[i] beta^i)\n    //\n    //\n    static void compute_polynomial(const Eigen::Matrix3d &FTF,\n                                   double *f, double *g, double *h) {\n      // polynomial coefficients f[0] == zeroth order etc\n      //\n      // E_os = (f[0] + f[1] * beta_t + ... f[4] * beta_t^4) / (1+beta_t^2)^2\n      //\n      f[0] = FTF(0, 0);\n      f[1] = FTF(0, 1) + FTF(1, 0);\n      f[2] = FTF(0, 2) + FTF(1, 1) + FTF(2, 0);\n      f[3] = FTF(1, 2) + FTF(2, 1);\n      f[4] = FTF(2, 2);\n\n      // first derivate:\n      g[4] = -f[3];\n      g[3] = 4 * f[4] - 2 * f[2];\n      g[2] = 3 * f[3] - 3 * f[1];\n      g[1] = 2 * f[2] - 4 * f[0];\n      g[0] = f[1];\n\n      // second derivative:\n      h[0] =  -4*f[0] +  2*f[2];\n      h[1] = -12*f[1] +  6*f[3];\n      h[2] =  20*f[0] - 16*f[2] + 12 * f[4];\n      h[3] =  12*f[1] - 16*f[3];\n      h[4] =   6*f[2] - 12*f[4];\n      h[5] =   2*f[3];\n    }\n\n    //\n    // Finds locations beta_t of real minima and value E there\n    // Returns number of minima found.\n    //\n\n    static int find_minima(\n      const double *f, // poly coeff for E_os\n      const double *g, // poly coeff first deriv\n      const double *h, // poly coeff second deriv\n      double *beta_min, double *beta_max, double *E_min, double *E_max) { \n      std::complex<double> root[4];\n      // find roots of first derivative\n      const int nroots = quartic::solve_quartic(g[4],g[3],g[2],g[1],g[0],root);\n      \n      int n_min(0);\n      *E_min = 1e90;\n      *E_max = -1e90;\n      // check all real roots, and evaluate second deriv there\n      for (const auto i:irange(0, nroots)) {\n        if (std::imag(root[i]) < 1e-8) {\n          const double beta_t = std::real(root[i]);\n          if (eval_poly(beta_t, h, 6) > 0) {\n            const double opbs = (1.0 + beta_t * beta_t);\n            const double E_os = eval_poly(beta_t, f, 5)/(opbs * opbs);\n            if (E_os < *E_min) {\n              *E_min = E_os;\n              *beta_min = 2.0 * std::atan(beta_t);\n            }\n            if (E_os > *E_max) {\n              *E_max = E_os;\n              *beta_max = 2.0 * std::atan(beta_t);\n            }\n            n_min++;\n          }\n        }\n      }\n      return (n_min);\n    }\n\n    //\n    // computes ratio of error for lowest/(second lowest) minimum error\n    // orientation. The lower the ratio, the better is the pose\n    // established, the more robust it is to flipping.\n    //\n    double check_quality(const ImgPoints &ip, const ObjPoints &op,\n                         const Transform &T, double *beta_orig,\n                         double *beta_min, double *beta_max) {\n      const ImgPointsH iph = ip.rowwise().homogeneous();\n      // compute R_t, the matrix that rotates z to the optical axis\n      double ang;\n      const Transform R_t = rotate_to_z(T.translation(), &ang);\n      const auto R1_tilde = R_t * T;\n      // decompose R1_tilde = Rz * Ry * Rz0\n      const auto   euler_angles = R1_tilde.rotation().eulerAngles(2, 1, 2);\n      const double gamma  = euler_angles[0]; // z  rotation\n      const double beta   = euler_angles[1]; // y  rotation\n      *beta_orig = beta;\n      const double alpha  = euler_angles[2]; // z0 rotation\n      const Transform R_z = (Transform)\n        Eigen::AngleAxisd(gamma, Eigen::Vector3d::UnitZ());\n      const Transform R_z0 = (Transform)\n        Eigen::AngleAxisd(alpha, Eigen::Vector3d::UnitZ());\n      // compute v_tilde from equation (5)\n      const ImgPointsH v_tilde = (R_t.rotation()*iph.transpose()).transpose();\n      // compute p_tilde\n      const ObjPoints p_tilde  = (R_z0.rotation()*op.transpose()).transpose();\n      M33dVec V_tilde = V_from_v(v_tilde);\n      const Eigen::Matrix3d FTF = compute_FTF(V_tilde, R_z, p_tilde);\n      double f[5], g[5], h[6];\n      compute_polynomial(FTF, f, g, h);\n      double E_min, E_max;\n      int n_min = find_minima(f, g, h, beta_min, beta_max, &E_min, &E_max);\n      switch (n_min) {\n      case 2:\n        return (E_min / E_max); // two minima, the usual case\n        break;\n      case 1:\n        return (0.0); // single minimum, assume all is good\n        break;\n      default:\n        ROS_WARN_STREAM(\"found bad num minima: \" << n_min);\n        *beta_min = beta;\n        *beta_max = beta;\n        return (0.0); // close eyes and hope for the best....\n        break;\n      }\n      return (0.0); // should never reach this\n    }\n  } // end of namespace rpp\n}\n", "meta": {"hexsha": "f6de369e88a17b5476668d5dbd1ec0a068d5d6df", "size": 9741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rpp.cpp", "max_stars_repo_name": "Shuhei-YOSHIDA/tagslam", "max_stars_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 210.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T12:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:49:46.000Z", "max_issues_repo_path": "src/rpp.cpp", "max_issues_repo_name": "Shuhei-YOSHIDA/tagslam", "max_issues_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T22:05:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T02:30:57.000Z", "max_forks_repo_path": "src/rpp.cpp", "max_forks_repo_name": "Shuhei-YOSHIDA/tagslam", "max_forks_repo_head_hexsha": "1fa3bef064696b289fece0c98b92001b3fb84fae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 58.0, "max_forks_repo_forks_event_min_datetime": "2018-04-30T02:43:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:48:55.000Z", "avg_line_length": 33.3595890411, "max_line_length": 79, "alphanum_fraction": 0.539061698, "num_tokens": 3131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5745460845835884}}
{"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_SPARSE_HPP_\n#define SMOOTH__INTERNAL__LMPAR_SPARSE_HPP_\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\nnamespace smooth::detail {\n\n/**\n * @brief Calculate the value and derivative of the function\n * \\f[\n * \\phi(\\alpha) = \\left\\| D (J^T J + \\alpha D^T D)^{-1} J^T r \\right\\| - \\Delta\n * \\f]\n *\n * @param J sparse matrix size MxN\n * @param d vector size N representing diagonal of D\n * @param r vector size M\n * @param Delta scalar\n * @param alpha scalar\n *\n * @return Triplet \\f$(x, \\phi(\\alpha), \\phi'(\\alpha))\\f$ where \\f$x\\f$ is a solution to \\f$ J^T J +\n * \\alpha D^T D = -J^T r\\f$.\n */\ntemplate<int N, int M>\nstd::tuple<Eigen::Vector<double, N>, double, double> calc_phi(\n  const auto & J,\n  const Eigen::Vector<double, N> & d,\n  const Eigen::Vector<double, M> & r,\n  double Delta,\n  double alpha)\n{\n  const auto n = J.cols();\n\n  Eigen::SparseMatrix<double> lhs = J.transpose() * J;\n\n  lhs.reserve(Eigen::Vector<double, N>::Ones(n));\n  if (alpha > 0) {\n    for (auto i = 0u; i != n; ++i) { lhs.coeffRef(i, i) += alpha * d(i) * d(i); }\n  }\n  lhs.makeCompressed();\n\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> ldlt;\n  ldlt.compute(lhs);\n\n  if (ldlt.info()) {\n    // computation failed, add small diagonal to ensure positive definiteness\n    for (auto i = 0u; i != n; ++i) { lhs.coeffRef(i, i) += Eigen::NumTraits<double>::epsilon(); }\n    ldlt.compute(lhs);\n  }\n\n  // calculate q\n  const Eigen::Vector<double, N> x = ldlt.solve(-J.transpose() * r);\n  const Eigen::Vector<double, N> q = -d.cwiseProduct(x);\n\n  // calculate phi\n  const double phi = q.stableNorm() - Delta;\n\n  // calculate dphi\n  const Eigen::Vector<double, N> d_q = d.cwiseProduct(q);\n  const Eigen::Vector<double, N> y   = ldlt.solve(d_q);\n  const double dphi                  = -d.cwiseProduct(q.normalized()).dot(y);\n\n  return std::make_tuple(x, phi, dphi);\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 sparse matrix MxN\n * @param d vector size Nx1\n * @param r vector size Mx1\n * @param Delta scalar\n *\n * @return pair(lambda, x) where x solves the least-squares problem for lambda\n */\ntemplate<int N, int M>\nstd::pair<double, Eigen::Vector<double, N>> lmpar_sparse(\n  const auto & J,\n  const Eigen::Vector<double, N> & d,\n  const Eigen::Matrix<double, M, 1> & r,\n  double Delta)\n{\n  double alpha = 0;\n\n  auto [x, phi, dphi] = calc_phi(J, d, r, Delta, alpha);\n\n  if (phi <= 0.1 * Delta) {\n    return std::make_pair(0, std::move(x));  // alpha = 0 solution fulfills condition\n  }\n\n  // initialize bounds\n  double l = std::max<double>(0, -phi / dphi);\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    std::tie(x, phi, dphi) = calc_phi(J, d, r, Delta, alpha);\n\n    if (std::abs(phi) <= 0.1 * Delta) {\n      break;  // condition fulfilled\n    }\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_SPARSE_HPP_\n", "meta": {"hexsha": "84f6aabcb59bdfac306ee0d3a80f444e9e1c31d8", "size": 4876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/lmpar_sparse.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/internal/lmpar_sparse.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/internal/lmpar_sparse.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 32.0789473684, "max_line_length": 100, "alphanum_fraction": 0.6515586546, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5745460707414027}}
{"text": "// Copyright 2017 David Wise\n#include <iostream>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/KroneckerProduct>\n#include \"donorClass.h\"\n\nusing namespace Eigen;\n\nvoid Donor::setNucSpin(const double value) {\n    Donor::coeffs.clear();\n    Donor::nucSpin = value;\n    setSpinsMats();\n}\ndouble Donor::getNucSpin() {\n\treturn nucSpin;\n}\nvoid Donor::setHypCoup(const double value) {\n\tDonor::A = value;\n}\ndouble Donor::getHypCoup() {\n\treturn A;\n}\nvoid Donor::setSpinsMats() {\n//  Set up Electron spin operators\n    Donor::coeffs.clear();\n    Donor::Sx << 0,1,1,0;\n    Donor::Sx *= (h_bar/2);\n    Donor::Sy << 0,-i,i,0;\n    Donor::Sy *= h_bar/2;\n    Donor::Sz << 1,0,0,-1;\n    Donor::Sz *= h_bar/2;\n    Donor::IdS = MatrixXcd::Identity(2*nucSpin+1, 2*nucSpin+1);\n    Donor::IdI = MatrixXcd::Identity(2, 2);\n\n//  Set up Nuclear spin operators\n\n    for (int inc = 1; inc < (2*nucSpin)+1; ++inc) {\n        std::complex<double> cInc = sqrt(2*nucSpin*inc + inc*(1-inc));\n//        std::cout << \"Coeff \"<< inc << \" is \\n\" << cInc << \"\\n\";\n        Donor::coeffs.push_back(cInc);\n    }\n\n    Donor::Icr.resize(nucSpin*2+1, nucSpin*2+1);\n    Donor::Ian.resize(nucSpin*2+1, nucSpin*2+1);\n    for (int inc = 0; inc <= (2*nucSpin-1); ++inc) {\n        Donor::Icr(inc, inc+1) = Donor::coeffs[inc];\n        Donor::Ian(inc+1, inc) = Donor::coeffs[inc];\n    }\n\n    Donor::Ix = h_bar*(1.0/2.0)*(Icr+Ian);\n    Donor::Iy = h_bar*(-i/(2.0))*(Icr-Ian);\n    Donor::Iz = (-i/h_bar)*((Ix*Iy) - (Iy*Ix));\n\n\n\n    Donor::Sx_f = kroneckerProduct(Sx, IdS);\n    Donor::Sy_f = kroneckerProduct(Sy, IdS);\n    Donor::Sz_f = kroneckerProduct(Sz, IdS);\n    Donor::Ix_f = kroneckerProduct(IdI, Ix);\n    Donor::Iy_f = kroneckerProduct(IdI, Iy);\n    Donor::Iz_f = kroneckerProduct(IdI, Iz);\n\n    Donor::S_I = kroneckerProduct(Sx, Ix) + kroneckerProduct(Sy, Iy) + kroneckerProduct(Sz, Iz);\n\n}\n\nMatrixXcd Donor::getEigs(const double B_0) {\n    Donor::Ham = (ge*mu_e/h_bar)*B_0*Sz_f - (gn*mu_n/h_bar)*B_0*Iz_f + A/(pow(h_bar,2))*S_I;\n    ComplexEigenSolver<MatrixXcd> es(Ham);\n    es.compute(Ham);\n    return es.eigenvalues();\n}\n\nvoid Donor::initialise(double nucVal, double hypVal) {\n    if (floor(2*nucVal) != 2*nucVal) {\n        throw std::invalid_argument(\"Please use integer or half-integer value\");\n    };\n    Donor::nucSpin = nucVal;\n    Donor::A = hypVal;\n    Donor::setSpinsMats();\n}", "meta": {"hexsha": "23e596e4df1d34a6d2305beab53c11b5fc846c3a", "size": 2346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "donorClass.cpp", "max_stars_repo_name": "Telthor/cppDonorSimulation", "max_stars_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "donorClass.cpp", "max_issues_repo_name": "Telthor/cppDonorSimulation", "max_issues_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "donorClass.cpp", "max_forks_repo_name": "Telthor/cppDonorSimulation", "max_forks_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_forks_repo_licenses": ["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.962962963, "max_line_length": 96, "alphanum_fraction": 0.615942029, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.5745270792143833}}
{"text": "#include \"amr_momentum_solver.h\"\n\n#include <cmath> \n#include <Eigen/Dense>\n\n#include \"../../tools/cppitertools/zip.hpp\"\n#include \"../../definitions.h\"\n\n\nusing namespace Eigen;\nusing iter::zip;\n\n\n/// Get snapshot current J_i^n+1 from momentum distribution\ntemplate< typename T, int D, int V>\nvoid vlv::MomentumSolver<T,D,V>::update_future_current( vlv::Tile<D>& tile, T cfl)\n{\n  //auto& yee = tile.get_yee();\n  tile.jx1.clear();\n\n  auto& step0 = tile.steps.get(0);\n  for(auto&& block0 : step0) {\n\n    auto Nx = int(block0.Nx),\n         Ny = int(block0.Ny),\n         Nz = int(block0.Nz);\n\n    for (int s=0; s<Nz; s++) {\n      for(int r=0; r<Ny; r++) {\n        for(int q=0; q<Nx; q++) {\n          const auto& M   = block0.block(q,r,s);   // f_i\n\n          T qm = 1.0 / block0.qm;  // charge to mass ratio\n\n          // Jx current; chi(u) = u/gamma = v\n          //\n          // NOTE: needs to be given in units of grid speed \n          //       so we scale with dt/dx\n          //yee.jx1(q,r,s) += qm*\n          tile.jx1(q,r,s) += qm*cfl*\n            integrate_moment(\n                M,\n                [](std::array<T,3> uvel) -> T \n                { return uvel[0]/gamma<T,3>(uvel); }\n                );\n        }\n      }\n    }\n\n  }// end of loop over species\n\n  }\n\n\n\n/*! \\brief Solve Vlasov tile contents\n *\n * Exposes the actual momentum mesh from the Vlasov Tile containers\n * and feeds those to the mesh solver.\n */\ntemplate< typename T, int D, int V>\nvoid vlv::MomentumSolver<T,D,V>::solve( vlv::Tile<D>& tile, T step_size)\n{\n\n  // init lock/mutex for mesh.clear()\n\n  // get reference to the Vlasov fluid that we are solving\n  auto& step0 = tile.steps.get(0);\n  auto& step1 = tile.steps.get(1);\n\n\n  // get reference to the Yee grid \n  auto& yee = tile.get_yee();\n\n  // timestep\n  //auto dt   = (T) tile.dt;      \n  //auto dx   = (T) tile.dx;      \n  //T cfl  = step_size*dt/dx;\n  auto cfl = step_size*tile.cfl;\n\n  // block limits\n  auto mins = tile.mins;\n  //auto maxs = tile.maxs;\n\n\n  /// Now get future current\n  update_future_current(tile, cfl);\n\n  // param object for solve_mesh\n  vlv::tools::Params<T> params = {};\n  params.cfl = cfl;\n\n\n  // loop over different particle species (zips current [0] and new [1] solutions)\n  for(auto&& blocks : zip(step0, step1) ) {\n      \n    // loop over the tile's internal grid\n    auto& block0 = std::get<0>(blocks);\n    auto& block1 = std::get<1>(blocks);\n\n      \n\n    for(int q=0; q<block0.Nx; q++) {\n      for(int r=0; r<block0.Ny; r++) {\n        for(int s=0; s<block0.Nz; s++) {\n          T qm = 1.0 / block0.qm;  // charge to mass ratio\n\n\n          // Get local field components\n          vec \n            B = \n            {{\n               (T) yee.bx(q,r,s),\n               (T) yee.by(q,r,s),\n               (T) yee.bz(q,r,s)\n            }},              \n\n            // E-field interpolated to the middle of the tile\n            // E_i = (E_i+1/2 + E_i-1/2)\n            // XXX\n            E =                \n            {{                 \n               (T) (0.5*(yee.ex(q,r,s) + yee.ex(q-1,r,   s  ))),\n               (T) (0.5*(yee.ey(q,r,s) + yee.ey(q,  r-1, s  ))),\n               (T) (0.5*(yee.ez(q,r,s) + yee.ez(q,  r,   s-1)))\n            }};\n\n          // Now push E field to future temporarily\n          //E[0] -= yee.jx1(q,r,s) * 0.5;\n\n\n          // dig out velomeshes from blocks\n          auto& mesh0 = block0.block(q,r,s);\n          auto& mesh1 = block1.block(q,r,s);\n\n          // fmt::print(\"solving for srq ({},{},{})\\n\",s,r,q);\n          params.qm = qm;\n          params.xloc = mins[0] + static_cast<T>(q);\n\n          // then the final call to the actual mesh solver\n          solve_mesh( mesh0, mesh1, E, B, params);\n        }\n      }\n    }\n  }\n\n  // XXX update jx1 for debug\n  //update_future_current(tile, cfl);\n  //\n  \n\n  }\n\n//--------------------------------------------------\n// explicit template instantiation\ntemplate class vlv::MomentumSolver<Realf, 1, 1>;\n\n\n", "meta": {"hexsha": "bba5ac7e3fa409bc2a56398ba3118e80cc95ee71", "size": 3940, "ext": "c++", "lang": "C++", "max_stars_repo_path": "vlasov/momentum-solvers/amr_momentum_solver.c++", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T07:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T06:47:37.000Z", "max_issues_repo_path": "vlasov/momentum-solvers/amr_momentum_solver.c++", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T08:50:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T20:11:12.000Z", "max_forks_repo_path": "vlasov/momentum-solvers/amr_momentum_solver.c++", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["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.7798742138, "max_line_length": 82, "alphanum_fraction": 0.5032994924, "num_tokens": 1193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5745098865930489}}
{"text": "#include \"wave/optimization/ceres/odom_gp/point_to_line_gp.hpp\"\n#include <Eigen/QR>\n\nnamespace wave {\n\nSE3PointToLineGP::SE3PointToLineGP(const double *const p,\n                                   const double *const pA,\n                                   const double *const pB,\n                                   SE3PointToLineGPObjects &objects,\n                                   const Mat3 &CovZ,\n                                   bool calculate_weight)\n    : pt(p), ptA(pA), ptB(pB), objects(objects) {\n    this->objects.JP_T.setZero();\n    this->objects.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->objects.Jres_P(0, 0) = 1 - (diff[0] * diff[0] / bottom);\n    this->objects.Jres_P(0, 1) = -(diff[0] * diff[1] / bottom);\n    this->objects.Jres_P(0, 2) = -(diff[0] * diff[2] / bottom);\n    this->objects.Jres_P(1, 0) = -(diff[1] * diff[0] / bottom);\n    this->objects.Jres_P(1, 1) = 1 - (diff[1] * diff[1] / bottom);\n    this->objects.Jres_P(1, 2) = -(diff[1] * diff[2] / bottom);\n    this->objects.Jres_P(2, 0) = -(diff[2] * diff[0] / bottom);\n    this->objects.Jres_P(2, 1) = -(diff[2] * diff[1] / bottom);\n    this->objects.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    auto skew = Transformation<>::skewSymmetric3(v);\n    this->objects.rotation = Eigen::Matrix3d::Identity() + skew + skew * skew * ((1 - c) / (s * s));\n\n    this->objects.Jres_P = this->objects.rotation * this->objects.Jres_P;\n\n    if (calculate_weight) {\n        auto rotated = this->objects.Jres_P * CovZ * this->objects.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 SE3PointToLineGP::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    Eigen::Map<const Vec6> vel_kp1(parameters[3], 6, 1);\n\n    if (jacobians) {\n        Transformation<Mat34, true>::interpolateAndJacobians(Tk,\n                                                             Tkp1,\n                                                             vel_k,\n                                                             vel_kp1,\n                                                             this->objects.hat,\n                                                             this->objects.candle,\n                                                             this->objects.T_current,\n                                                             this->objects.JT_Ti,\n                                                             this->objects.JT_Tip1,\n                                                             this->objects.JT_Wi,\n                                                             this->objects.JT_Wip1);\n    } else {\n        Transformation<Mat34, true>::interpolate(\n          Tk, Tkp1, vel_k, vel_kp1, this->objects.hat, this->objects.candle, this->objects.T_current);\n    }\n\n    Eigen::Map<const Vec3> PT(this->pt, 3, 1);\n    Vec3 point = this->objects.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->objects.rotation * (point - pt_Tl)).block<2, 1>(0, 0);\n\n    if (jacobians != nullptr) {\n        this->objects.JP_T(0, 1) = point(2);\n        this->objects.JP_T(0, 2) = -point(1);\n        this->objects.JP_T(1, 0) = -point(2);\n        this->objects.JP_T(1, 2) = point(0);\n        this->objects.JP_T(2, 0) = point(1);\n        this->objects.JP_T(2, 1) = -point(0);\n\n        // Jres_P already has rotation incorporated during construction\n        this->objects.Jr_T = this->objects.Jres_P * this->objects.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->objects.Jr_T.block<2, 6>(0, 0) * this->objects.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->objects.Jr_T.block<2, 6>(0, 0) * this->objects.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->objects.Jr_T.block<2, 6>(0, 0) * this->objects.JT_Wi;\n        }\n        if (jacobians[3]) {\n            Eigen::Map<Eigen::Matrix<double, 2, 6, Eigen::RowMajor>> jac_map(jacobians[3], 2, 6);\n            jac_map = this->weight_matrix * this->objects.Jr_T.block<2, 6>(0, 0) * this->objects.JT_Wip1;\n        }\n    }\n\n    return true;\n}\n\n}  // namespace wave\n", "meta": {"hexsha": "cd37e31881cc628ac69b915af924f14790781f41", "size": 6453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_optimization/src/ceres/odom_gp/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/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/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": 44.5034482759, "max_line_length": 123, "alphanum_fraction": 0.5234774523, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.574509885542243}}
{"text": "#include \"Tests_pcp.h\"\n\n#include <fstream>\n#include <Eigen/Dense>\n#include \"Tresca.h\"\n#include \"test_material_models.h\"\n\nnamespace\n{\n\tenum class AnalysisType : unsigned char\n\t{\n\t\tTriaxialDrained = 0,\n\t\tTriaxialUndrained = 1,\n\t\tConsolidation = 2,\n\t\tSpecified = 3\n\t};\n\t\n\tvoid output_var(\n\t\tstd::ostream &os,\n\t\tdouble cohesion,\n\t\tconst double out_strain[3],\n\t\tconst double out_stress[6],\n\t\tconst double out_pstrain[3]\n\t\t)\n\t{\n\t\tEigen::Matrix3d s_mat;\n\t\ts_mat << out_stress[0], out_stress[3], out_stress[5],\n\t\t\t\t out_stress[3], out_stress[1], out_stress[4],\n\t\t\t\t out_stress[5], out_stress[4], out_stress[2];\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver(s_mat);\n\t\tconst Eigen::Vector3d& pstress = eigen_solver.eigenvalues();\n\t\tdouble smax = pstress[0];\n\t\tif (smax < pstress[1])\n\t\t\tsmax = pstress[1];\n\t\tif (smax < pstress[2])\n\t\t\tsmax = pstress[2];\n\t\tdouble smin = pstress[0];\n\t\tif (smin > pstress[1])\n\t\t\tsmin = pstress[1];\n\t\tif (smin > pstress[2])\n\t\t\tsmin = pstress[2];\n\t\tos << out_strain[0] << \", \"\n\t\t\t<< out_strain[1] << \", \"\n\t\t\t<< out_strain[2] << \", \"\n\t\t\t<< out_stress[0] << \", \"\n\t\t\t<< out_stress[1] << \", \"\n\t\t\t<< out_stress[2] << \", \"\n\t\t\t<< out_stress[3] << \", \"\n\t\t\t<< out_stress[4] << \", \"\n\t\t\t<< out_stress[5] << \", \"\n\t\t\t<< out_pstrain[0] << \", \"\n\t\t\t<< out_pstrain[1] << \", \"\n\t\t\t<< out_pstrain[2] << \", \"\n\t\t\t<< smax - smin - 2.0 * cohesion << \"\\n\";\n\t}\n}\n\nvoid test_tresca()\n{\n\tdouble de11, de22, de33;\n\t//AnalysisType tp = AnalysisType::Specified;\n\tAnalysisType tp = AnalysisType::TriaxialDrained;\n\t// tresca 1\n\t//de11 = -0.05;\n\t//de22 = 0.0;\n\t//de33 = 0.0;\n\t// tresca 2\n\tde11 = 0.05;\n\tde22 = 0.0;\n\tde33 = 0.0;\n\t// tresca 3\n\t//de11 = 0.05;\n\t//de22 = 0.0;\n\t//de33 = -0.05;\n\tsize_t inc_num = 5000;\n\tsize_t out_num = 100;\n\n\tdouble ini_stress[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };\n\tMatModel::Tresca tc;\n\ttc.set_param(1000.0, 0.1, 1.0, ini_stress);\n\n\tstd::fstream res_file;\n\tres_file.open(\"Tresca_res.csv\", std::ios::out | std::ios::binary);\n\tres_file << \"e11, e22, e33, s11, s22, s33, s12, s23, s31,\"\n\t\t\t\t\"dep11, dep22, dep33, f\\n\";\n\n\tde11 /= double(inc_num);\n\tde22 /= double(inc_num);\n\tde33 /= double(inc_num);\n\tsize_t out_inv = inc_num / out_num;\n\tdouble out_strain[3] = { 0.0, 0.0, 0.0 };\n\tconst double(*Dep_mat)[6];\n\tdouble dstrain[6];\n\tfor (size_t i = 0; i < inc_num; ++i)\n\t{\n\t\tif (i % out_inv == 0) // output\n\t\t\toutput_var(res_file, tc.get_cohesion(), out_strain, tc.get_stress(), tc.get_dstrain_p());\n\n\t\tswitch (tp)\n\t\t{\n\t\tcase AnalysisType::TriaxialDrained:\n\t\t\tDep_mat = reinterpret_cast<const double(*)[6]>(tc.get_Dep_mat());\n\t\t\tdstrain[0] = de11;\n\t\t\tdstrain[1] = -Dep_mat[1][0] / (Dep_mat[1][1] + Dep_mat[1][2]) * de11;\n\t\t\tdstrain[2] = -Dep_mat[2][0] / (Dep_mat[2][1] + Dep_mat[2][2]) * de11;\n\t\t\tdstrain[3] = 0.0;\n\t\t\tdstrain[4] = 0.0;\n\t\t\tdstrain[5] = 0.0;\n\t\t\tbreak;\n\t\tcase AnalysisType::TriaxialUndrained:\n\t\t\tdstrain[0] = de11;\n\t\t\tdstrain[1] = -0.5 * de11;\n\t\t\tdstrain[2] = -0.5 * de11;\n\t\t\tdstrain[3] = 0.0;\n\t\t\tdstrain[4] = 0.0;\n\t\t\tdstrain[5] = 0.0;\n\t\t\tbreak;\n\t\tcase AnalysisType::Consolidation:\n\t\t\tdstrain[0] = de11;\n\t\t\tdstrain[1] = 0.0;\n\t\t\tdstrain[2] = 0.0;\n\t\t\tdstrain[3] = 0.0;\n\t\t\tdstrain[4] = 0.0;\n\t\t\tdstrain[5] = 0.0;\n\t\t\tbreak;\n\t\tcase AnalysisType::Specified:\n\t\t\tdstrain[0] = de11;\n\t\t\tdstrain[1] = de22;\n\t\t\tdstrain[2] = de33;\n\t\t\tdstrain[3] = 0.0;\n\t\t\tdstrain[4] = 0.0;\n\t\t\tdstrain[5] = 0.0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tres_file.close();\n\t\t\treturn;\n\t\t}\n\n\t\tint res = tc.integrate(dstrain);\n\n\t\tout_strain[0] += dstrain[0];\n\t\tout_strain[1] += dstrain[1];\n\t\tout_strain[2] += dstrain[2];\n\t}\n\n\toutput_var(res_file, tc.get_cohesion(), out_strain, tc.get_stress(), tc.get_dstrain_p());\n\tres_file.close();\n}\n", "meta": {"hexsha": "3c9d8d56b438cf78580b70080059edf2f6dbb10b", "size": 3618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/test_tresca.cpp", "max_stars_repo_name": "COFS-UWA/MPM3D", "max_stars_repo_head_hexsha": "1a0c5dc4e92dff3855367846002336ca5a18d124", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/test_tresca.cpp", "max_issues_repo_name": "COFS-UWA/MPM3D", "max_issues_repo_head_hexsha": "1a0c5dc4e92dff3855367846002336ca5a18d124", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T02:03:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-19T16:34:39.000Z", "max_forks_repo_path": "Tests/test_tresca.cpp", "max_forks_repo_name": "COFS-UWA/MPM3D", "max_forks_repo_head_hexsha": "1a0c5dc4e92dff3855367846002336ca5a18d124", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-28T00:33:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T00:33:14.000Z", "avg_line_length": 24.2818791946, "max_line_length": 92, "alphanum_fraction": 0.6006080708, "num_tokens": 1454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.5745098774745212}}
{"text": "#include \"additional_functions.h\"\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n\nint ipow(int base, int exp)\n{\n\tint result = 1;\n\twhile (exp)\n\t{\n\t\tif (exp & 1)\n\t\t{\n\t\t\tresult *= base;\n\t\t}\n\t\texp >>= 1;\n\t\tbase *= base;\n\t}\n\n\treturn result;\n}\n\n\nbool stationaritycheck(const double n[], int d)\n{\n\tbool indicator = false;\n\tEigen::MatrixXd stat_mat(d, d);\n\tfor (int i = 0; i != d; ++i)\n\t{\n\t\tfor (int j = 0; j != d; ++j)\n\t\t\tstat_mat(i, j) = n[i * d + j];\n\t}\n\tEigen::EigenSolver<Eigen::MatrixXd> eigsol;\n\teigsol.compute(stat_mat, false);\n\tEigen::VectorXd eigsol_real = eigsol.eigenvalues().real();\n\tfor (int i = 0; i != d; ++i)\n\t{\n\t\tif (fabs(eigsol_real(i)) >= 1)\n\t\t{\n\t\t\tindicator = true;\n\t\t}\n\t}\n\n\treturn indicator;\n}\n\n\nbool stationaritycheck(const double x[], const double y[], int d)\n{\n\tbool indicator = false;\n\tEigen::MatrixXd stat_mat(d, d);\n\tfor (int i = 0; i != d; ++i)\n\t{\n\t\tfor (int j = 0; j != d; ++j)\n\t\t{\n\t\t\tstat_mat(i, j) = x[i * d + j] / y[i * d + j];\n\t\t}\n\t}\n\tEigen::EigenSolver<Eigen::MatrixXd> eigsol;\n\teigsol.compute(stat_mat, false);\n\tEigen::VectorXd eigsol_real = eigsol.eigenvalues().real();\n\tfor (int i = 0; i != d; ++i)\n\t{\n\t\tif (fabs(eigsol_real(i)) >= 1)\n\t\t{\n\t\t\tindicator = true;\n\t\t}\n\t}\n\n\treturn indicator;\n}\n\n\ndouble random_check() {\n\tdouble random = rand();\n\tif (random == 0 || random == RAND_MAX)\n\t{\n\t\treturn random_check();\n\t}\n\telse\n\t{\n\t\treturn random;\n\t}\n}\n", "meta": {"hexsha": "8add3c74332bf0eb5fea0c44b88d80f9df42ad81", "size": 1378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/additional_functions.cpp", "max_stars_repo_name": "ragoragino/py-hawkes", "max_stars_repo_head_hexsha": "0737c2ce71d32ac83895187020501a7356592ccf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-11-26T13:56:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T10:50:10.000Z", "max_issues_repo_path": "lib/additional_functions.cpp", "max_issues_repo_name": "ragoragino/py-hawkes", "max_issues_repo_head_hexsha": "0737c2ce71d32ac83895187020501a7356592ccf", "max_issues_repo_licenses": ["MIT"], "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/additional_functions.cpp", "max_forks_repo_name": "ragoragino/py-hawkes", "max_forks_repo_head_hexsha": "0737c2ce71d32ac83895187020501a7356592ccf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-15T15:59:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T06:04:05.000Z", "avg_line_length": 16.4047619048, "max_line_length": 65, "alphanum_fraction": 0.5870827286, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5744153290849322}}
{"text": "/**\n * Implementation of Rules to eliminate\n * Design points. Check Risk-Base Allocation.pptx\n * for more details.\n */\n#include <iostream>\n#include <vector>\n#include <set>\n#include <iterator>\n#include <math.h>\n#include <chrono>\n#include <exception>\n#include <queue>\n#include <boost/math/distributions/normal.hpp>\n#include <sys/time.h>\n#include \"ptss_dse.hpp\"\n\n/* HI - Test Editing */\nusing namespace std;\nusing boost::math::normal;\n\n\n// a == b ?\nbool is_eq(const alloc_t &a, const alloc_t &b) {\n    return (a == b);\n}\n\n// a > b ?\nbool is_gt(const alloc_t &a, const alloc_t &b) {\n    bool ret = !(is_eq(a,b));\n    int idx = 0;\n    for(auto it = a.begin();\n        it != a.end();\n        it++) {\n            if (*it >= b[idx++])\n                ret = ret && true;\n            else\n                ret = ret && false;\n    }\n    return ret;\n}\n\n// a < b ?\nbool is_lt(const alloc_t &a, const alloc_t &b) {\n    bool ret = !(is_eq(a,b));\n    int idx = 0;\n    for(auto it = a.begin();\n        it != a.end();\n        it++) {\n            if (*it <= b[idx++])\n                ret = ret && true;\n            else\n                ret = ret && false;\n    }\n    return ret;\n}\n\n// a and b are not comparable\nbool is_incomparable(const alloc_t &a, const alloc_t &b) {\n    bool ret = (!is_gt(a,b)) && \\\n               (!is_lt(a,b)) && \\\n               (!is_eq(a,b));\n    return ret;\n}\n\n// lexicographic comparison of two allocations ( a < b ? )\nbool lex_comp(const alloc_t &a, const alloc_t &b) {\n    auto it2 = b.begin();\n    for (auto it = a.begin(); it != a.end(); it++, it2++) {\n        if (*it2 < *it)\n            return false;\n    }\n    return true;\n}\n\n\n// just for the sample -- print the data sets\nstd::ostream& operator<<(std::ostream& os, const alloc_t& vi) {\n  os << \"(|\";\n  std::copy(vi.begin(), vi.end(), std::ostream_iterator<int>(os, \"|\"));\n  os << \")\";\n  return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const all_alloc_t& vvi) { \n  os << \"{\\n\";\n  for(auto it = vvi.begin();\n      it != vvi.end();\n      it++) {\n      os << \"  \" << *it << \"\\n\";\n  }\n  os << \"}\";\n  return os;\n}\n\n// Profiled Data\nstatic double mua  [] = {269.568837,\t141.985532, 99.508883, 79.006262, 66.454092, 58.649068, 52.804705, 48.960141, 45.73406, 43.455542, 41.386889, 40.046129, 38.695398, 37.750183, 36.840822, 36.41925, 35.715777, 35.350802, 34.767695, 34.493228, 34.033093, 33.944396, 33.676262, 33.871417, 33.654013, 33.737325, 33.825452, 34.021759, 34.223725, 34.479067, 34.694037, 35.157394}; \nstatic double stda [] = {0.676473946, 0.335842225, 0.208458629, 0.319806191, 0.313754681, 0.340024999, 0.340440891, 0.441634464, 0.424892928, 0.45393722, 0.470011702, 0.479161768, 0.496199557, 0.493329504, 0.524060111, 0.523248507, 0.564837145, 0.590188106, 0.584813646, 0.602546264, 0.597015913, 0.600979201, 0.59552246, 0.595876665, 0.587283577, 0.645952011, 0.666749578, 0.732030737, 0.836999403, 0.942281274, 1.046115194, 1.103043517}; \n\ndouble compute_risk(const alloc_t &x) {\n    double mu = 0.0, var = 0.0;\n    for(auto jt = x.begin();\n        jt != x.end();\n        jt++) {\n                mu  += mua[*jt-1];\n                var += (stda[*jt-1])*(stda[*jt-1]);\n    }\n    /* Create a normal distribution and evaluate the risk */\n    double sd = sqrt(var);\n    normal dist(mu,sd);\n    \n    double risk = 1 - cdf(dist,D);\n    return risk;\n}\n\ndouble compute_execution_time(const alloc_t &x) {\n    double sum = 0.0;\n    for(auto jt = x.begin(); jt != x.end(); jt++) {\n        sum += mua[*jt-1];\n    }\n    return sum;\n}\n\ndouble compute_estimated_util(const alloc_t &x) {\n    double util = 0;\n    for(auto jt = x.begin();\n        jt != x.end();\n        jt++) {\n            util += (*jt) * mua[*jt-1];\n    }\n    return util;\n}\n\n/* recursively construct and add allocations */\nvoid construct_alloc(all_alloc_t &vvi, int ph) {\n    alloc_t vi2;\n    static long unsigned int cnt = 0;\n    long unsigned int r   = M;\n    long unsigned int dec;\n    long unsigned int j   = 0;\n\n    if (ph == NPH) {\n        //cout << \"ph : \" << ph << \", invoc : \" << cnt << endl;\n        dec = cnt++;\n\n        /* Resolve cnt into M-radix number */\n        for (j = 0; j < NPH; j++) {\n            //cout << dec%r + 1 << \",\";\n            vi2.push_back(dec%r + 1);\n            dec = dec/r;\n        }\n        vvi.insert(vi2);\n        //cout << \"}\\n\";\n        return;\n    }\n    for (int m = 1; m <= M; m++) {\n        construct_alloc(vvi,ph+1);\n    }\n}\n\n\nvoid ptss_DSE::display() {\n    cout << this->search_space << \"\\n\";\n    cout << \"Lower : \";\n    cout << this->lower << \"\\n\";\n    cout << \"Upper : \";\n    cout << this->upper << \"\\n\";\n}\n\n// Create All points\nptss_DSE::ptss_DSE() {\n    construct_alloc(this->search_space,0);\n    this->is_initialized = true;\n    this->dmr = 1.0;\n}\n\nptss_DSE::ptss_DSE(double dmr) {\n    construct_alloc(this->search_space,0);\n    this->init_point(dmr);\n    this->is_initialized = true;\n    this->dmr = dmr;\n}\n\n\n// Evaluate all points\nvoid ptss_DSE::evaluate_all() {\n    this->opt_point = this->lower;\n    this->opt_util  = 10e9;\n    this->opt_risk  = 1;\n\n    // cout << \"Search space size \" << search_space.size();\n    for(auto it = search_space.begin();\n        it != search_space.end();\n        it++) {\n        \n        double risk = compute_risk(*it);\n        double util = compute_estimated_util(*it);\n\n        if (risk <= this->dmr && util <= this->opt_util) {\n            this->opt_point = *it;\n            this->opt_util  = util;\n            this->opt_risk  = risk;\n        }\n        // cout << *it << \",\" << risk << \",\" << util << \"\\n\";\n        usleep(50);\n    }\n    cout << this->opt_point << \",\" << this->opt_risk << \",\" << this->opt_util << \"\\n\";\n}\n\nvoid ptss_DSE::init_point(double dmr) {\n    alloc_t tmp;\n    double risk;\n    int m;\n    \n    for (m = 1; m <= M; m++) {\n        tmp.clear();\n\n        // Create a uniform allocation\n        for (int ph = 0; ph < NPH; ph++)\n            tmp.push_back(m);\n        \n        // Compute the risk\n        risk = compute_risk(tmp);\n\n        if (risk <= dmr) {\n            this->upper = tmp;\n            break;\n        }\n    }\n\n    tmp.clear();\n    for (int ph = 0; ph < NPH; ph++)\n        tmp.push_back(m-1);    \n    this->lower = tmp;\n\n    cout << \"lower\" << this->lower << \", dmr = \" << compute_risk(this->lower) << endl;\n    cout << \"upper\" << this->upper << \", dmr = \" << compute_risk(this->upper) << endl;\n}\n\n\n\n/*\n * The action to generate a\n * set of all (child) points is to \n * select a src and dst from \n * startpoint and\n * transfer a single core\n * from one src to destitation.\n */\nvoid epsilon_move2_rule1(all_alloc_t &children,\\\n                         const alloc_t startpoint,\\\n                         const all_alloc_t fbidden) {\n    /* Expand all the elements of the frontier */\n    for (int idx = 0; idx < NPH; idx++) {\n        alloc_t tmp2  = startpoint;   \n        if (tmp2[idx] > 1) {\n            tmp2[idx]--;\n\n            /* Inert only when it doesn't exist in forbidden set */\n            // if (fbidden.find(tmp2) == fbidden.end())\n                children.insert(tmp2);\n        }\n    }\n}\n\nvoid epsilon_move2_rule2(all_alloc_t &children,\\\n                         const alloc_t startpoint,\\\n                         const all_alloc_t fbidden) {\n     /* Expand all the elements of the frontier */\n    for (int idx = 0; idx < NPH; idx++) {\n        alloc_t tmp2  = startpoint;   \n        if (tmp2[idx] < M) {\n            tmp2[idx]++;\n\n            /* Inert only when it doesn't exist in forbidden set */\n            // if (fbidden.find(tmp2) == fbidden.end())\n                children.insert(tmp2);\n        }\n    }\n}\n\nvoid epsilon_move2_rule3(all_alloc_t &children,\\\n                         const alloc_t startpoint,\\\n                         const all_alloc_t fbidden) {\n    int i, j;\n\n    for (i = 0; i < NPH; i++) {\n        for (j = 0; j < NPH; j++) {\n            if (i != j) {\n                if (startpoint[i] > 1) {\n                    /* Transfer a core from i to j */\n                    alloc_t new_point = startpoint;\n                    new_point[i]--;\n                    new_point[j]++;\n\n                    /* Check Execution Time before insert */\n                    if (compute_execution_time(new_point) > compute_execution_time(startpoint)) {\n                        // if (fbidden.find(new_point) == fbidden.end())\n                            children.insert(new_point);\n\n                        /* Also insert other points derived from it */\n                        alloc_t new_point2 = new_point;\n                        while (--new_point2[i] > 0) {\n                            if (++new_point2[j] <= NPH)\n                                // if (fbidden.find(new_point2) == fbidden.end())\n                                    children.insert(new_point2);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\n\n\nvoid epsilon_move2_test() {\n    alloc_t startpoint = {5,5,6,4,4};\n    all_alloc_t fbidden;\n    all_alloc_t children = {};\n    epsilon_move2_rule3(children, startpoint,fbidden);\n    cout << \"Start Point\" << startpoint << endl;\n    cout << \"Rule-34 children\" << children << endl;\n    // cout << \"Number of children \" << children.size() << \"\\n\\n\";\n    // cout << \"Valid Actions \" << valid_actions << \"\\n\\n\";\n}\n\n/* Comparison based elimination */\n// void ptss_DSE::eliminate_points_rule12() {\n//     // if (!this->is_initialized) {\n//     //     throw domain_error(\"Object not initialized correctly\");\n//     // }\n//     // /* Apply recursively */\n//     // all_alloc_t children;\n//     // set<alloc_t> fset1 = {this->upper};\n//     // set<alloc_t> fset2 = {this->upper};\n//     // set<alloc_t> aset;\n\n//     // expand_rule1(children,fset1,aset,0);\n//     // aset.clear(); \n//     // expand_rule2(children,fset2,aset,0);\n//     // cout << children << endl;\n\n//     // cout << \"Eliminated \" << children.size() << endl;\n// }\n\n\n/*\n * Whenever the DMR constraint is violated\n * by a point say \"init\", \n * Rule1 and Rule3 will (recursively) be expanded\n * to create, sibling solutions which are guaranteed\n * to violate the DMR (Check the slides and the [PAPER])\n * \n * fbidden : A set that holds all the discarded points.\n * aset    : Children of \"init\" point expanded according to rule 1 and rule 3\n * aset2   : An auxiliary aset. \n * \n */\nvoid apply_action_rule13(all_alloc_t &fbidden,\\\n                         all_alloc_t &fset,\\\n                         all_alloc_t &aset,\\\n                         int actv_id) {\n    bool no_child = true;\n    int i, j;\n    \n    /* Expand the children and create the new frontier */\n    for (set<alloc_t>::iterator it = fset.begin(); it != fset.end(); it++) {\n        \n        // cout << \"Inserting to fbidden set (activ-\"<<actv_id<<\"): \" << *it << endl;\n        // fbidden.insert(*it); // Insert all the elements of frontier set into fbidden set.\n\n        /* Expand all the elements of the frontier */\n        // epsilon_move2_rule1(aset,*it,fbidden);\n        // epsilon_move2_rule3(aset,*it,fbidden);\n        \n        alloc_t tmp = *it;\n        fbidden.insert(tmp);\n\n        /* Rule 1 Expansion */\n        for (int idx = 0; idx < NPH; idx++) {\n            alloc_t tmp2  = tmp;   \n            if (tmp2[idx] > 1) {\n                tmp2[idx]--;\n                if (fbidden.count(tmp2) < 1)\n                    aset.insert(tmp2);\n            }\n        }\n\n        /* Rule 3 Expansion */\n        for (i = 0; i < NPH; i++) {\n            for (j = 0; j < NPH; j++) {\n                // cout << \"Expr : (\"<<i<<\",\"<<j<<\") \" << ((i != j) && (tmp[i] > 1) && (tmp[j] < M));\n                if ((i != j) && (tmp[i] > 1) && (tmp[j] < M)) {\n                    /* Transfer a core from i to j */\n                    alloc_t new_point = tmp;\n                    new_point[i]--;\n                    new_point[j]++;\n                    /* Check Execution Time before insert */\n                    if (compute_execution_time(new_point) > compute_execution_time(tmp)) {\n                        if (fbidden.count(new_point) < 1)\n                            aset.insert(new_point);\n                        /* Also insert other points derived from it */\n                        alloc_t new_point2 = new_point;\n                        while ((new_point2[i] > 1) && (new_point2[j] < M)) {\n                                new_point2[i]--;\n                                new_point2[j]++;\n                                if (fbidden.count(new_point) < 1)\n                                    aset.insert(new_point2);\n                        }\n                    }\n                    // cout << \"Blah : \"<< \"i = \"<< i << \",j = \" << j << \", tmp[i] = \" << tmp[i] << \", tmp[j] = \" << tmp[j] << endl; \n                } else {\n                    // cout << \"i = \"<< i << \",j = \" << j << \", tmp[i] = \" << tmp[i] << \", tmp[j] = \" << tmp[j] << endl; \n                }\n            }\n        }\n    }\n    fset.clear();\n    no_child = no_child && (aset.empty()?true:false);\n    \n    if (!no_child) {\n        apply_action_rule13(fbidden,aset,fset,++actv_id);\n    }\n\n}\n\nvoid ptss_DSE::explore() {\n    all_alloc_t tmp1 = {this->lower}, tmp2;\n    apply_action_rule13(this->discarded_space,tmp1,tmp2,0);\n    cout << \"Search points discarded : \"<<this->discarded_space.size()<<endl;\n}\n/********************************************************************/\nint main () {\n\n    struct timeval t1, t2;\n    gettimeofday(&t1,NULL);\n    ptss_DSE obj(0.25);\n    // cout << obj;\n    // obj.display();\n    // obj.explore();\n    obj.evaluate_all();\n    gettimeofday(&t2,NULL);\n    double elapsed  = (t2.tv_sec-t1.tv_sec)*1000000+(t2.tv_usec-t1.tv_usec);\n\n    cout << elapsed << \"us\\n\";\n\n    // alloc_t a = {1,2,3,4,5};\n    // alloc_t b = {1,1,3,4,2};\n    // cout << is_lt(b,a) << \"\\n\";\n}\n", "meta": {"hexsha": "2bdfb9f18d12d2258323ecd53b2f0465fb1ab79a", "size": 13697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ptss_dse.cpp", "max_stars_repo_name": "Arka2009/ptss-dse", "max_stars_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ptss_dse.cpp", "max_issues_repo_name": "Arka2009/ptss-dse", "max_issues_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ptss_dse.cpp", "max_forks_repo_name": "Arka2009/ptss-dse", "max_forks_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_forks_repo_licenses": ["BSD-3-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.3030973451, "max_line_length": 440, "alphanum_fraction": 0.4997444696, "num_tokens": 3822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5744153184474337}}
{"text": "#include <iostream>\n#include <cmath>\n#include <boost/random.hpp>\n\ndouble function(double argument)\n{\n   return sin(argument);\n}\n\nint main(int argc, char** argv)\n{\n   // random number setup \n   //\n   typedef boost::mt19937 base_generator_type;\n\n   base_generator_type generator(42u);\n   boost::uniform_real<> uniform_distribution(0,1);\n   boost::variate_generator<base_generator_type&, boost::uniform_real<> > \n      random_uniform(generator, uniform_distribution);\n\n   // integration now from 0 to 1\n   // \n   long number_of_samples = 1000;\n\n   double sum(0);\n\n   for (long i(0); i < number_of_samples; ++i)\n   {\n      double value = function(random_uniform());\n      sum += value;\n   }\n\n   std::cout << \"the approximate result is: \" << sum / number_of_samples << std::endl;\n\n   return 0;\n}\n", "meta": {"hexsha": "bc38b366f0ecb54238dcbcf2ae9c9349b7638a7a", "size": 791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++03/mc_integration.cpp", "max_stars_repo_name": "tzaffi/cpp", "max_stars_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T14:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:28:17.000Z", "max_issues_repo_path": "DMCpp/GottschlingRepo/c++03/mc_integration.cpp", "max_issues_repo_name": "tzaffi/cpp", "max_issues_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T14:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T02:14:07.000Z", "max_forks_repo_path": "DMCpp/GottschlingRepo/c++03/mc_integration.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-29T02:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T08:52:22.000Z", "avg_line_length": 21.3783783784, "max_line_length": 86, "alphanum_fraction": 0.6700379267, "num_tokens": 196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5744153131286843}}
{"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_olae.cpp\n * @brief  OLAE algorithm 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_olae.h>\n#include <mrpt/core/exceptions.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <mrpt/tfest/se3.h>\n#include <Eigen/Dense>\n#include \"visit_correspondences.h\"\n\nusing namespace mp2p_icp;\n\n// Convert to quaternion by normalizing q=[1, optim_rot], then to rot. matrix:\nstatic mrpt::poses::CPose3D gibbs2pose(const Eigen::Vector3d& v)\n{\n    auto       x = v[0], y = v[1], z = v[2];\n    const auto r = 1.0 / std::sqrt(1.0 + x * x + y * y + z * z);\n    x *= r;\n    y *= r;\n    z *= r;\n    auto q = mrpt::math::CQuaternionDouble(r, -x, -y, -z);\n\n    // Quaternion to 3x3 rot matrix:\n    return mrpt::poses::CPose3D(q, .0, .0, .0);\n}\n\n/** The systems built by olae_build_linear_system.\n * The system is: \"M g = v\".\n *\n * However, if the solution is near the Gibbs vector singularity (|Phi|~= \\pi)\n * we may need to use the alternative systems built by the\n * \"sequential rotation method\" [shuster1981attitude].\n *\n * (Refer to technical report for details)\n */\nstruct OLAE_LinearSystems\n{\n    Eigen::Matrix3d M, Mx, My, Mz;\n    Eigen::Vector3d v, vx, vy, vz;\n\n    /** Attitude profile matrix */\n    Eigen::Matrix3d B;\n};\n\n/** Core of the OLAE algorithm  */\nstatic OLAE_LinearSystems olae_build_linear_system(\n    const WeightedPairings& in, const mrpt::math::TPoint3D& ct_other,\n    const mrpt::math::TPoint3D& ct_this, OutlierIndices& in_out_outliers)\n{\n    MRPT_START\n\n    using mrpt::math::TPoint3D;\n    using mrpt::math::TVector3D;\n\n    OLAE_LinearSystems res;\n\n    // Build the linear system: M g = v\n    res.M = Eigen::Matrix3d::Zero();\n    res.v = Eigen::Vector3d::Zero();\n\n    // Attitude profile matrix:\n    res.B = Eigen::Matrix3d::Zero();\n\n    // Lambda: process each pairing:\n    auto lambda_each_pair = [&](const mrpt::math::TVector3D& bi,\n                                const mrpt::math::TVector3D& ri,\n                                const double                 wi) {\n// We will evaluate M from an alternative expression below from the\n// attitude profile matrix B instead, since it seems to be slightly more\n// stable, numerically. The original code for M is left here for\n// reference, though.\n#if 0\n    // M+=(1/2)* ([s_i]_{x})^2\n    // with: s_i = b_i + r_i\n    const double sx = bi.x + ri.x, sy = bi.y + ri.y, sz = bi.z + ri.z;\n\n    /* ([s_i]_{x})^2 is:\n     *\n     *  ⎡    2     2                          ⎤\n     *  ⎢- sy  - sz      sx⋅sy        sx⋅sz   ⎥\n     *  ⎢                                     ⎥\n     *  ⎢                 2     2             ⎥\n     *  ⎢   sx⋅sy     - sx  - sz      sy⋅sz   ⎥\n     *  ⎢                                     ⎥\n     *  ⎢                              2     2⎥\n     *  ⎣   sx⋅sz        sy⋅sz     - sx  - sy ⎦\n     */\n    const double c00 = -sy * sy - sz * sz;\n    const double c11 = -sx * sx - sz * sz;\n    const double c22 = -sx * sx - sy * sy;\n    const double c01 = sx * sy;\n    const double c02 = sx * sz;\n    const double c12 = sy * sz;\n\n    // clang-format off\n    const auto dM = (Eigen::Matrix3d() <<\n       c00, c01, c02,\n       c01, c11, c12,\n       c02, c12, c22 ).finished();\n    // clang-format on\n\n    // res.M += wi * dM;\n\n    // The missing (1/2) from the formulas above:\n    res.M *= 0.5;\n#endif\n        /* v-= weight *  [b_i]_{x}  r_i\n         *  Each term is:\n         *  ⎡by⋅rz - bz⋅ry ⎤   ⎡ B23 - B32 ⎤\n         *  ⎢              ⎥   |           ⎥\n         *  ⎢-bx⋅rz + bz⋅rx⎥ = | B31 - B13 ⎥\n         *  ⎢              ⎥   |           ⎥\n         *  ⎣bx⋅ry - by⋅rx ⎦   ⎣ B12 - B21 ⎦\n         *\n         * B (attitude profile matrix):\n         *\n         * B+= weight * (b_i * r_i')\n         *\n         */\n\n        // clang-format off\n    const auto dV = (Eigen::Vector3d() <<\n       (bi.y * ri.z - bi.z * ri.y),\n       (-bi.x * ri.z + bi.z * ri.x),\n       (bi.x * ri.y - bi.y * ri.x) ).finished();\n        // clang-format on\n\n        res.v -= wi * dV;\n\n        // clang-format off\n    const auto dB = (Eigen::Matrix3d() <<\n       bi.x * ri.x, bi.x * ri.y, bi.x * ri.z,\n       bi.y * ri.x, bi.y * ri.y, bi.y * ri.z,\n       bi.z * ri.x, bi.z * ri.y, bi.z * ri.z).finished();\n        // clang-format on\n        res.B += wi * dB;\n    };  // end lambda for visit_correspondences()\n\n    // Lambda for the final stage after visiting all corres:\n    auto lambda_final = [&](const double w_sum) {\n        // Normalize weights. OLAE assumes \\sum(w_i) = 1.0\n        if (w_sum > .0)\n        {\n            const auto f = (1.0 / w_sum);\n            // res.M *= f;\n            res.v *= f;\n            res.B *= f;\n        }\n        else\n        {\n            // We either had NO input correspondences, or ALL were detected\n            // as outliers... What to do in this case?\n        }\n    };\n\n    visit_correspondences(\n        in, ct_other, ct_this, in_out_outliers, lambda_each_pair, lambda_final,\n        true /* DO make unit point vectors for OLAE */);\n\n    // Now, compute the other three sets of linear systems, corresponding\n    // to the \"sequential rotation method\" [shuster1981attitude], so we can\n    // later keep the best one (i.e. the one with the largest |M|).\n    {\n        const Eigen::Matrix3d S = res.B + res.B.transpose();\n        const double          p = res.B.trace() + 1;\n        const double          m = res.B.trace() - 1;\n        // Short cut:\n        const auto& v = res.v;\n\n        // Set #0: M g=v, without further rotations (the system built above).\n        // clang-format off\n        res.M = (Eigen::Matrix3d() <<\n           S(0,0)-p,  S(0,1), S(0,2),\n           S(0,1),   S(1,1)-p, S(1,2),\n           S(0,2),   S(1,2),  S(2,2)-p ).finished();\n        // clang-format on\n\n        const auto&  M0 = res.M;  // shortcut\n        const double z1 = v[0], z2 = v[1], z3 = v[2];\n\n        // Set #1: rotating 180 deg around \"x\":\n        // clang-format off\n        res.Mx = (Eigen::Matrix3d() <<\n           m     ,      -z3  ,     z2,\n           -z3   ,  M0(2,2),     -S(1,2),\n           z2    ,  -S(1,2),    M0(1,1)).finished();\n        res.vx = (Eigen::Vector3d() <<\n            -z1, S(0,2), -S(0,1)\n            ).finished();\n        // clang-format on\n\n        // Set #2: rotating 180 deg around \"y\":\n        // clang-format off\n        res.My = (Eigen::Matrix3d() <<\n           M0(2,2),     z3  ,     -S(0,2),\n           z3     ,       m ,     -z1,\n         -S(0,2)  ,     -z1 ,   M0(0,0)).finished();\n        res.vy = (Eigen::Vector3d() <<\n            -S(1,2), -z2, S(0,1)\n            ).finished();\n        // clang-format on\n\n        // Set #3: rotating 180 deg around \"z\":\n        // clang-format off\n        res.Mz = (Eigen::Matrix3d() <<\n           M0(1,1),  -S(0,1),     -z2,\n          -S(0,1) ,  M0(0,0),      z1,\n             -z2  ,      z1 ,      m).finished();\n        res.vz = (Eigen::Vector3d() <<\n            S(1,2), -S(0,2), -z3\n            ).finished();\n        // clang-format on\n    }\n\n    return res;\n\n    MRPT_END\n}\n\n// See .h docs, and associated technical report.\nvoid mp2p_icp::optimal_tf_olae(const WeightedPairings& in, OptimalTF_Result& result)\n{\n    MRPT_START\n\n    using mrpt::math::TPoint3D;\n    using mrpt::math::TVector3D;\n\n    // Note on notation: we are search the relative transformation of\n    // the \"other\" frame wrt to \"this\", i.e. \"this\"=\"global\",\n    // \"other\"=\"local\":\n    //   p_this = pose \\oplus p_other\n    //   p_A    = pose \\oplus p_B      --> pB = p_A \\ominus pose\n\n    // Reset output to defaults:\n    result = OptimalTF_Result();\n\n    // Normalize weights for each feature type and for each target (attitude\n    // / translation):\n    ASSERT_(in.attitude_weights.pt2pt >= .0);\n    ASSERT_(in.attitude_weights.l2l >= .0);\n    ASSERT_(in.attitude_weights.pl2pl >= .0);\n\n    // Compute the centroids:\n    auto [ct_other, ct_this] =\n        eval_centroids_robust(in, result.outliers /* empty for now  */);\n\n    // Build the linear system: M g = v\n    OLAE_LinearSystems linsys = olae_build_linear_system(\n        in, ct_other, ct_this, result.outliers /* empty for now  */);\n\n    MRPT_TODO(\"Refactor to avoid duplicated code? Is it possible?\");\n\n    // Re-evaluate the centroids, now that we have a guess on outliers.\n    if (!result.outliers.empty())\n    {\n        // Re-evaluate the centroids:\n        const auto [new_ct_other, new_ct_this] =\n            eval_centroids_robust(in, result.outliers);\n\n        ct_other = new_ct_other;\n        ct_this  = new_ct_this;\n\n        // And rebuild the linear system with the new values:\n        linsys =\n            olae_build_linear_system(in, ct_other, ct_this, result.outliers);\n    }\n\n    // We are finding the optimal rotation \"g\", as a Gibbs vector.\n    // Solve linear system for optimal rotation: M g = v\n\n    const double detM_orig = std::abs(linsys.M.determinant()),\n                 detMx     = std::abs(linsys.Mx.determinant()),\n                 detMy     = std::abs(linsys.My.determinant()),\n                 detMz     = std::abs(linsys.Mz.determinant());\n\n#if 0\n    // clang-format off\n    std::cout << \" |M_orig|= \" << detM_orig << \"\\n\"\n                 \" |M_x|   = \" << detMx << \"\\n\"\n                 \" |M_t|   = \" << detMy << \"\\n\"\n                 \" |M_z|   = \" << detMz << \"\\n\";\n    // clang-format on\n#endif\n\n    if (detM_orig > mrpt::max3(detMx, detMy, detMz))\n    {\n        // original rotation is the best numerically-determined problem:\n        const auto sol0 =\n            gibbs2pose(linsys.M.colPivHouseholderQr().solve(linsys.v));\n        result.optimal_pose = sol0;\n#if 0\n        std::cout << \"M   : |M|=\"\n                  << mrpt::format(\"%16.07f\", linsys.M.determinant())\n                  << \" sol: \" << sol0.asString() << \"\\n\";\n#endif\n    }\n    else if (detMx > mrpt::max3(detM_orig, detMy, detMz))\n    {\n        // rotation wrt X is the best choice:\n        auto sol1 =\n            gibbs2pose(linsys.Mx.colPivHouseholderQr().solve(linsys.vx));\n        sol1                = mrpt::poses::CPose3D(0, 0, 0, 0, 0, M_PI) + sol1;\n        result.optimal_pose = sol1;\n#if 0\n        std::cout << \"M_x : |M|=\"\n                  << mrpt::format(\"%16.07f\", linsys.Mx.determinant())\n                  << \" sol: \" << sol1.asString() << \"\\n\";\n#endif\n    }\n    else if (detMy > mrpt::max3(detM_orig, detMx, detMz))\n    {\n        // rotation wrt Y is the best choice:\n        auto sol2 =\n            gibbs2pose(linsys.My.colPivHouseholderQr().solve(linsys.vy));\n        sol2                = mrpt::poses::CPose3D(0, 0, 0, 0, M_PI, 0) + sol2;\n        result.optimal_pose = sol2;\n#if 0\n        std::cout << \"M_y : |M|=\"\n                  << mrpt::format(\"%16.07f\", linsys.My.determinant())\n                  << \" sol: \" << sol2.asString() << \"\\n\";\n#endif\n    }\n    else\n    {\n        // rotation wrt Z is the best choice:\n        auto sol3 =\n            gibbs2pose(linsys.Mz.colPivHouseholderQr().solve(linsys.vz));\n        sol3                = mrpt::poses::CPose3D(0, 0, 0, M_PI, 0, 0) + sol3;\n        result.optimal_pose = sol3;\n#if 0\n        std::cout << \"M_z : |M|=\"\n                  << mrpt::format(\"%16.07f\", linsys.Mz.determinant())\n                  << \" sol: \" << sol3.asString() << \"\\n\";\n#endif\n    }\n\n    // Use centroids to solve for optimal translation:\n    mrpt::math::TPoint3D pp;\n    result.optimal_pose.composePoint(\n        ct_other.x, ct_other.y, ct_other.z, pp.x, pp.y, pp.z);\n    // Scale, if used, was: pp *= s;\n\n    result.optimal_pose.x(ct_this.x - pp.x);\n    result.optimal_pose.y(ct_this.y - pp.y);\n    result.optimal_pose.z(ct_this.z - pp.z);\n\n    MRPT_END\n}\n", "meta": {"hexsha": "b9a89971f2609dd1416e7b8357745a38989f386d", "size": 11916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimal_tf_olae.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_olae.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_olae.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": 33.2849162011, "max_line_length": 84, "alphanum_fraction": 0.5120006714, "num_tokens": 3712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5743804319820601}}
{"text": "/**\r\n * @brief Partial Least Squares Regression with Eigen\r\n * \r\n * Same source as LDA, \\cite friedman2001elements\r\n * \r\n * @file pls-eigen.hpp\r\n * @author François-David Collin <Francois-David.Collin@umontpellier.fr>\r\n * @brief \r\n * @version 0.1\r\n * @date 2018-11-08\r\n * \r\n * @copyright Copyright (c) 2018\r\n * \r\n */\r\n#pragma once\r\n\r\n#include \"various.hpp\"\r\n#include <Eigen/Dense>\r\n#include <list>\r\n#include <algorithm>\r\n#include <range/v3/all.hpp>\r\n#include \"tqdm.hpp\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nusing namespace ranges;\r\n\r\n/**\r\n * @brief filters out constant variables\r\n * \r\n * @tparam Derived \r\n * @param xr table to filter\r\n * @return std::vector<size_t> indexes of valid vars\r\n */\r\ntemplate<class Derived>\r\nstd::vector<size_t> filterConstantVars(const MatrixBase<Derived>& xr) {\r\n    RowVectorXd meanr = xr.colwise().mean();\r\n    VectorXd stdr = ((xr.rowwise() - meanr).array().square().colwise().sum() / (xr.rows() - 1)).sqrt();;\r\n    std::vector<size_t> validvars(xr.cols());\r\n    size_t m = 0;\r\n    for(size_t i = 0; i< xr.cols(); i++) {\r\n        if (stdr(i) >= 1.0e-8) validvars[m++] = i;\r\n    }\r\n    validvars.resize(m);\r\n    return validvars;\r\n}\r\n\r\n/**\r\n * @brief Apply PLS on x regarding y\r\n * \r\n * @tparam Derived \r\n * @tparam OtherDerived \r\n * @param x input\r\n * @param y output\r\n * @param ncomp number of components expected\r\n * @param Projection the projection matrix\r\n * @param mean mean of variables in x\r\n * @param std standard deviation of variables in x\r\n * @param stopping elbow heuristic enabled\r\n * @return VectorXd explained variance for each computed components\r\n */\r\ntemplate<class Derived, class OtherDerived>\r\nVectorXd pls(const MatrixBase<Derived>& x,\r\n         const MatrixBase<OtherDerived>& y,\r\n         size_t ncomp,\r\n         MatrixXd& Projection,\r\n         RowVectorXd& mean,\r\n         RowVectorXd& std,\r\n         bool stopping = false)\r\n{\r\n    size_t n = x.rows();\r\n    size_t p = x.cols();\r\n    mean = x.colwise().mean();\r\n    ncomp = std::min(std::min(n,p),ncomp);\r\n    std = ((x.rowwise() - mean).array().square().colwise().sum() / (x.rows() - 1)).sqrt();;\r\n    MatrixXd X = (x.rowwise() - mean).array().rowwise() / std.array();\r\n    MatrixXd X0 = X;\r\n    MatrixXd Ptilde(ncomp,p);\r\n    MatrixXd Wstar(p,ncomp);\r\n    VectorXd res(ncomp);\r\n    size_t window_size = std::max(2_z,ncomp/10_z);\r\n\r\n    std::list<unsigned char> stopping_criterium(window_size,0);\r\n    double ymean = y.mean();\r\n    MatrixXd w_k, t_k, p_k, y_k;\r\n    y_k = y;\r\n    double SSTO = (y.array() - ymean).array().square().sum();\r\n    int m = 0;\r\n    tqdm bar;\r\n\r\n    while (m < ncomp)\r\n    {\r\n        bar.progress(m,ncomp);\r\n        // $w_{k}=\\frac{X_{k-1}^{T} y_{k-1}}{\\left\\|X_{k-1}^{T} y_{k-1}\\right\\|}$ \r\n        w_k = X.transpose() * y;   //  (p)   \r\n        w_k /= sqrt((w_k.transpose()*w_k)(0,0));\r\n        // $\\mathbf{W}^{*}_{p \\times K} = [w_1, \\ldots, w_K]$\r\n        Wstar.col(m) = w_k;\r\n        // $t_{k}=X_{k-1}w_{k}$\r\n        t_k = X * w_k; // (n)\r\n        double t_k_s = (t_k.transpose() * t_k)(0,0);\r\n        // $p_{k}=\\frac{X_{k-1}^{T} t_{k}}{t_{k}^{T} t_{k}}$\r\n        p_k = (X.transpose() * t_k) / t_k_s; // (p)\r\n        // $\\widetilde{\\mathbf{P}}_{K \\times p}=\\mathbf{t}\\left[p_{1}, \\ldots, p_{K}\\right]$\r\n        Ptilde.row(m) = p_k.transpose();\r\n        // $q_{k}=\\frac{y_{k-1}^{T} t_{k}}{t_{k}^{T} t_{k}}$\r\n        double q_k = (y_k.transpose() * t_k)(0,0) / t_k_s; //(n,n)\r\n        // $y_{k}=y_{k-1}-q_{k} t_{k}$\r\n        y_k -= q_k * t_k;\r\n        // $X_{k}=X_{k-1}-t_{k} p_{k}^{T}$\r\n        X -= (t_k * p_k.transpose());\r\n\r\n        // $$Yvar^m = \\frac{\\sum_{i=1}^{N}{(\\hat{y}^{m}_{i}-\\bar{y})^2}}{\\sum_{i=1}^{N}{(y_{i}-\\hat{y})^2}}$$\r\n        res(m) = 1 - (y_k.array() - ymean).array().square().sum() / SSTO;\r\n\r\n        // Elbow heuristic\r\n        // $$Yvar^m = \\frac{\\sum_{i=1}^{N}{(\\hat{y}^{m}_{i}-\\bar{y})^2}}{\\sum_{i=1}^{N}{(y_{i}-\\hat{y})^2}}$$\r\n        if ((m >= 2) && stopping) {\r\n            auto lastdiff = res(m) - res(m-1);\r\n            auto lastmean = (res(m) + res(m-1))/2.0;\r\n            size_t remains = ncomp - m;\r\n            stopping_criterium.pop_front();\r\n            stopping_criterium.push_back(lastmean >= 0.99 * remains * lastdiff);\r\n            auto wcrit = ranges::accumulate(stopping_criterium,0);\r\n            if (wcrit == window_size) break;\r\n        }\r\n\r\n        m++;\r\n    }\r\n    if (m < ncomp) {\r\n        m--;\r\n        res = res(seq(0,m)).eval();\r\n    }\r\n\r\n    // $\\mathbf{W}=\\mathbf{W}^{*}\\left(\\widetilde{\\mathbf{P}} \\mathbf{W}^{*}\\right)^{-1}$\r\n    auto solver = (Ptilde*Wstar).completeOrthogonalDecomposition();\r\n    Projection = Wstar*solver.pseudoInverse();\r\n    return res;\r\n}\r\n\r\n// Tenenhaus, M. L’approche PLS. Revue de statistique appliquée 47, 5–40 (1999).\r\n// Vancolen, S. La Régression PLS. Mémoire Postgrade en Statistiques, University of Neuchâtel (Switzerland) 1--28 (2004).\r\n// Wold, S., Sjöström, M. & Eriksson, L. PLS-regression: a basic tool of chemometrics. Chemometrics and intelligent laboratory systems 58, 109–130 (2001).\r\n// Mémoire m2 de ghislain : https://plmbox.math.cnrs.fr/f/1192b14f90ea44a1b26a/\r\n// Krämer, N. An overview on the shrinkage properties of partial least squares regression. Computational Statistics 22, 249–273 (2007).", "meta": {"hexsha": "2bff4bfb263b0df20fae3a2bda2fc468fcb38192", "size": 5250, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pls-eigen.hpp", "max_stars_repo_name": "diyabc/abcranger", "max_stars_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T12:11:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T16:32:37.000Z", "max_issues_repo_path": "src/pls-eigen.hpp", "max_issues_repo_name": "diyabc/abcranger", "max_issues_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2019-06-20T11:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T04:13:46.000Z", "max_forks_repo_path": "src/pls-eigen.hpp", "max_forks_repo_name": "fradav/abcranger", "max_forks_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-17T03:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T13:31:10.000Z", "avg_line_length": 36.2068965517, "max_line_length": 155, "alphanum_fraction": 0.5674285714, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5743706612678736}}
{"text": "// Copyright 2019 Xanadu Quantum Technologies Inc.\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @file\n * Contains functions for approximating the hafnian of a matrix\n * in a classically efficient manner, for certains classes of matrices.\n */\n\n#pragma once\n#include <stdafx.h>\n#include <numeric>\n#include <random>\n#include <cmath>\n\n#ifdef LAPACKE\n#define EIGEN_SUPERLU_SUPPORT\n#define EIGEN_USE_BLAS\n#define EIGEN_USE_LAPACKE\n\n#define LAPACK_COMPLEX_CUSTOM\n#define lapack_complex_float std::complex<float>\n#define lapack_complex_double std::complex<double>\n#endif\n\n#include <Eigen/Eigenvalues>\n\n\nnamespace libwalrus {\n\n/**\n* Returns the approximation to the hafnian of a matrix with non-negative entries.\n*\n* The approximation follows an stochastic algorithm according to which the hafnian\n* can be approximated as the sum of determinants of matrices.\n* The accuracy of the approximation increases with increasing number of iterations.\n*\n* @param mat vector representing the flattened matrix\n* @param nsamples positive integer representing the number of samples to perform\n* @return the approximate hafnian\n*/\ntemplate <typename T>\ninline long double hafnian_nonneg(std::vector<T> &mat, int &nsamples) {\n    int n = std::sqrt(static_cast<double>(mat.size()));\n\n    long double mean = 0;\n    long double stdev = 1;\n\n    namespace eg = Eigen;\n    eg::Matrix<T, eg::Dynamic, eg::Dynamic> A = eg::Map<eg::Matrix<T, eg::Dynamic, eg::Dynamic>, eg::Unaligned>(mat.data(), n, n);\n\n#ifdef _OPENMP\n    int nthreads = omp_get_max_threads();\n    omp_set_num_threads(nthreads);\n#else\n    int nthreads = 1;\n#endif\n\n    std::vector<int> threadbound_low(nthreads);\n    std::vector<int> threadbound_hi(nthreads);\n\n    std::default_random_engine generator;\n    std::normal_distribution<double> distribution(mean, stdev);\n\n    std::vector<long double> determinants(nsamples);\n\n    #pragma omp parallel for shared(determinants)\n    for (int k = 0; k < nsamples; k++) {\n        std::vector<T> matrand(n * n, 0);\n        std::vector<T> g(n * n, 0);\n        std::vector<T> gt(n * n, 0);\n        eg::Matrix<T, eg::Dynamic, eg::Dynamic> W;\n        W.resize(n, n);\n\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                long double randnum = distribution(generator);\n                matrand[i * n + j] = static_cast<T>(randnum);\n                g[i * n + j] = 0.0;\n                gt[i * n + j] = 0.0;\n            }\n        }\n\n        for (int i = 0; i < n; i++) {\n            for (int j = i; j < n; j++) {\n                g[i * n + j] = matrand[i * n + j];\n                gt[j * n + i] = matrand[i * n + j];\n            }\n        }\n\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                int id = i * n + j;\n                W(i, j) = (g[id] - gt[id]) * std::sqrt(std::abs(A(i, j)));\n            }\n        }\n\n        long double det = std::real(W.determinant());\n\n        determinants[k] = det;\n    }\n\n    long double final = 0.0;\n\n    for (int i = 0; i < nsamples; i++) {\n        final += determinants[i];\n    }\n\n    final = final / (static_cast<long double>(nsamples));\n\n    return final;\n\n}\n\n/**\n* Returns the approximation to the hafnian of a matrix with non-negative entries.\n*\n* The approximation follows an stochastic algorithm according to which the hafnian\n* can be approximated as the sum of determinants of matrices.\n* The accuracy of the approximation increases with increasing number of iterations.\n*\n* This is a wrapper around the templated function `libwalrus::hafnian_nonneg` for Python\n* integration. It accepts and returns double numeric types, and\n* returns sensible values for empty and non-even matrices.\n*\n* In addition, this wrapper function automatically casts all matrices\n* to type `long double`, allowing for greater precision than supported\n* by Python and NumPy.\n*\n* @param mat vector representing the flattened matrix\n* @param nsamples positive integer representing the number of samples to perform\n* @return the approximate hafnian\n*/\ndouble hafnian_approx(std::vector<double> &mat, int &nsamples) {\n    std::vector<long double> matq(mat.begin(), mat.end());\n    int n = std::sqrt(static_cast<double>(mat.size()));\n    long double haf;\n\n    if (n == 0)\n        haf = 1.0;\n    else if (n % 2 != 0)\n        haf = 0.0;\n    else\n        haf = hafnian_nonneg(matq, nsamples);\n\n    return static_cast<double>(haf);\n}\n\n}\n", "meta": {"hexsha": "910db7f80cafa5d9139b0590f2ef40cee2e9bc21", "size": 4916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hafnian_approx.hpp", "max_stars_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_stars_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/hafnian_approx.hpp", "max_issues_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_issues_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/hafnian_approx.hpp", "max_forks_repo_name": "NunoEdgarGFlowHub/thewalrus", "max_forks_repo_head_hexsha": "487957ec04a7d7da4a5007a0a9b9d209c4bee51f", "max_forks_repo_licenses": ["Apache-2.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.725, "max_line_length": 130, "alphanum_fraction": 0.6486981286, "num_tokens": 1269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5743706448385766}}
{"text": "// Copyright (c) 2013, Manuel Blum\n// All rights reserved.\n\n// Define this symbol to enable runtime tests for allocations\n//#define EIGEN_RUNTIME_NO_MALLOC \n\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <string>\n\n#include \"nn.h\"\n\ninline void swap(int &val)\n{\n\tval = (val<<24) | ((val<<8) & 0x00ff0000) | ((val>>8) & 0x0000ff00) | (val>>24);\n}\n\nmatrix_t read_mnist_images(std::string filename)\n{\n  matrix_t X;\n  std::ifstream fs(filename.c_str(), std::ios::binary);\n  if(fs) {\n    int magic_number, num_images, num_rows, num_columns;\n    fs.read((char*)&magic_number, sizeof(magic_number));\n    fs.read((char*)&num_images, sizeof(num_images));\n    fs.read((char*)&num_rows, sizeof(num_rows));\n    fs.read((char*)&num_columns, sizeof(num_columns));\n    if (magic_number != 2051) {\n      swap(magic_number);\n      swap(num_images);\n      swap(num_rows);\n      swap(num_columns);\n    }\n\n    X = matrix_t::Zero(num_images, num_rows*num_columns);\n\n    for (size_t i=0; i<num_images; ++i) {\n      for (size_t j=0; j<num_rows*num_columns; ++j) {\n        unsigned char temp=0;\n        fs.read((char*)&temp,sizeof(temp));\n        X(i,j) = (double) temp;        \n      }\n    }\n    fs.close();\n  } else {\n    std::cout << \"error reading file: \" << filename << std::endl;\n    exit(1);\n  }\n  return X;\n}\n\nmatrix_t read_mnist_labels(std::string  filename)\n{\n  matrix_t Y;\n  std::ifstream fs(filename.c_str(), std::ios::binary);\n  if(fs) {\n    int magic_number, num_images, num_rows, num_columns;\n    fs.read((char*)&magic_number, sizeof(magic_number));\n    fs.read((char*)&num_images, sizeof(num_images));\n    if (magic_number != 2049) {\n      swap(magic_number);\n      swap(num_images);\n    }\n\n    Y = matrix_t::Zero(num_images, 10);\n\n    for (size_t i=0; i<num_images; ++i) {\n      unsigned char temp=0;\n      fs.read((char*)&temp,sizeof(temp));\n      Y(i,(int) temp) = 1.0;        \n    }\n    fs.close();\n  } else {\n    std::cout << \"error reading file: \" << filename << std::endl;\n    exit(1);\n  }\n  return Y;\n}\n\nint main (int argc, const char* argv[]) {\n\n  if (argc != 2) {\n    std::cout << \"please provide path to mnist data ...\" << std::endl;\n    std::cout << \"you can download the dataset at http://yann.lecun.com/exdb/mnist/\" << std::endl;\n    std::cout << std::endl << \"usage: \" << argv[0] << \" path_to_data\" << std::endl << std::endl;\n    return 1;\n  }\n\n  std::string path = argv[1];\n\n  std::cout << \"reading data\" << std::endl;\n\n  matrix_t X_train = read_mnist_images(path + \"/train-images-idx3-ubyte\");\n  matrix_t Y_train = read_mnist_labels(path + \"/train-labels-idx1-ubyte\");\n  matrix_t X_test = read_mnist_images(path + \"/t10k-images-idx3-ubyte\");\n  matrix_t Y_test = read_mnist_labels(path + \"/t10k-labels-idx1-ubyte\");\n\n  // number of optimization steps\n  int max_steps = 600;\n  // regularization parameter\n  double lambda = 0.0;\n\n  // specify network topology\n  Eigen::VectorXi topo(3);\n  topo << X_train.cols(), 300, Y_test.cols();\n  std::cout << \"topology: \" << topo.transpose() << std::endl;\n\n  // initialize a neural network with given topology\n  std::cout << \"initializing network\" << std::endl;\n  NeuralNet nn(topo);\n\n  std::cout << \"scaling the data\" << std::endl;\n  nn.autoscale(X_train, Y_train);\n  \n  // train the network\n  std::cout << \"starting training\" << std::endl;\n  std::cout << \"iter        error\" << std::endl;\n  double err;\n  for (int i = 0; i < max_steps; ++i) {\n    err = nn.loss(X_train, Y_train, lambda);\n    nn.rprop();\n    printf(\"%4i   %10.7f\\n\", i, err);\n  }\n\n  // test accuracy\n  nn.forward_pass(X_test);\n  matrix_t prediction = nn.get_activation();\n  int correct = 0;\n  int k;\n  for (size_t i=0; i<Y_test.rows(); ++i) {\n    prediction.row(i).maxCoeff(&k);\n    correct += Y_test(i, k);\n  }\n\n  std::cout << \"test accuracy: \" << correct*1.0/Y_test.rows() << std::endl;\n\n  nn.write(\"mnist.nn\");\n\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "504d78dfb7161218680a03bb65e250c148a2626c", "size": 3886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mnist.cpp", "max_stars_repo_name": "mblum/nn", "max_stars_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-05-27T11:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T14:57:31.000Z", "max_issues_repo_path": "mnist.cpp", "max_issues_repo_name": "mblum/nn", "max_issues_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mnist.cpp", "max_forks_repo_name": "mblum/nn", "max_forks_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-25T11:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T04:36:25.000Z", "avg_line_length": 26.6164383562, "max_line_length": 98, "alphanum_fraction": 0.6163149768, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5743706335012447}}
{"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 <cstdlib>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"NAOS/constants.hpp\"\n#include \"NAOS/basicMath.hpp\"\n#include \"NAOS/basicAstro.hpp\"\n#include \"NAOS/misc.hpp\"\n#include \"NAOS/ellipsoidGravitationalAcceleration.hpp\"\n\nnamespace naos\n{\n\n//! equations of motion (for a particle around the asteroid modelled as a spheroid)\n/*!\n * first order differential equations describing the motion of a particle or spacecraft around a\n * central body modeled as a spheroid using ellipsoid gravitational model.\n */\nclass equationsOfMotionParticleAroundSpheroid\n{\n    // declare parameters, gravitational parameter and the radius of the spheroid\n    const double gravParameter;\n    const double alpha;\n    const double zRotation;\n\npublic:\n    // Default constructor with member initializer list, get the gravitational parameter\n    equationsOfMotionParticleAroundSpheroid( const double aGravParameter,\n                       const double aAlpha,\n                       const double aZRotation )\n                    : gravParameter( aGravParameter ),\n                      alpha( aAlpha ),\n                      zRotation( aZRotation )\n    { }\n    void operator() ( const std::vector< double > &stateVector,\n                      std::vector< double > &dXdt,\n                      const double currentTime )\n    {\n        // calculate the gravitational accelerations first\n        std::vector< double > gravAcceleration( 3, 0.0 );\n\n        computeEllipsoidGravitationalAcceleration( alpha,\n                                                   alpha,\n                                                   alpha,\n                                                   gravParameter,\n                                                   stateVector[ xPositionIndex ],\n                                                   stateVector[ yPositionIndex ],\n                                                   stateVector[ zPositionIndex ],\n                                                   gravAcceleration );\n\n        // now calculate the derivatives\n        dXdt[ xPositionIndex ] = stateVector[ xVelocityIndex ];\n        dXdt[ yPositionIndex ] = stateVector[ yVelocityIndex ];\n        dXdt[ zPositionIndex ] = stateVector[ zVelocityIndex ];\n\n        dXdt[ xVelocityIndex ] = gravAcceleration[ xPositionIndex ]\n                                + 2.0 * zRotation * stateVector[ yVelocityIndex ]\n                                + zRotation * zRotation * stateVector[ xPositionIndex ];\n\n        dXdt[ yVelocityIndex ] = gravAcceleration[ yPositionIndex ]\n                                - 2.0 * zRotation * stateVector[ xVelocityIndex ]\n                                + zRotation * zRotation * stateVector[ yPositionIndex ];\n\n        dXdt[ zVelocityIndex ] = gravAcceleration[ zPositionIndex ];\n    }\n};\n\n//! Store intermediate state values and time( if needed )\n/*!\n * This structure contains members that will save all intermediate state values and times when\n * an object of this structure is passed as an argument to the integrator function.\n */\nstruct pushBackStateAndTime\n{\n    // declare containers to store state and time\n    std::vector< std::vector< double > > &stateContainer;\n    std::vector< double > &timeContainer;\n\n    //member initializer list\n    pushBackStateAndTime( std::vector< std::vector< double > > &aState,\n                          std::vector< double > &aTime )\n                : stateContainer( aState ),\n                  timeContainer( aTime )\n    { }\n\n    void operator() ( const std::vector< double > &singleStateVector, const double singleTime )\n    {\n        // store the intermediate state and time values in the containers\n        stateContainer.push_back( singleStateVector );\n        timeContainer.push_back( singleTime );\n    }\n};\n\n//! particle around spheroid integration\n/*!\n * integrate the equations of motion for a particle around a spheroid. The gravitational accelerations\n * calculated using the ellipsoid gravitational potential model.\n */\nvoid executeParticleAroundSpheroid( const double alpha,\n                                    const double gravParameter,\n                                    std::vector< double > asteroidRotationVector,\n                                    std::vector< double > &initialOrbitalElements,\n                                    const double initialStepSize,\n                                    const double startTime,\n                                    const double endTime,\n                                    std::ostringstream &outputFilePath,\n                                    const int dataSaveIntervals )\n{\n    //! open the output csv file to save data. Declare file headers.\n    std::ofstream outputFile;\n    outputFile.open( outputFilePath.str( ) );\n    outputFile << \"x\" << \",\";\n    outputFile << \"y\" << \",\";\n    outputFile << \"z\" << \",\";\n    outputFile << \"vx\" << \",\";\n    outputFile << \"vy\" << \",\";\n    outputFile << \"vz\" << \",\";\n    outputFile << \"t\" << std::endl;\n    outputFile.precision( 16 );\n\n    //! convert the initial orbital elements to cartesian state\n    std::vector< double > initialStateInertial( 6, 0.0 );\n    initialStateInertial = convertKeplerianElementsToCartesianCoordinates( initialOrbitalElements,\n                                                                           gravParameter );\n\n    std::vector< double > inertialPositionVector = { initialStateInertial[ xPositionIndex ],\n                                                     initialStateInertial[ yPositionIndex ],\n                                                     initialStateInertial[ zPositionIndex ] };\n    std::vector< double > omegaCrossPosition( 3, 0.0 );\n    omegaCrossPosition = crossProduct( asteroidRotationVector, inertialPositionVector );\n\n    std::vector< double > initialState( 6, 0.0 );\n    initialState[ xPositionIndex ] = initialStateInertial[ xPositionIndex ];\n    initialState[ yPositionIndex ] = initialStateInertial[ yPositionIndex ];\n    initialState[ zPositionIndex ] = initialStateInertial[ zPositionIndex ];\n\n    initialState[ xVelocityIndex ]\n                = initialStateInertial[ xVelocityIndex ] - omegaCrossPosition[ 0 ];\n\n    initialState[ yVelocityIndex ]\n                = initialStateInertial[ yVelocityIndex ] - omegaCrossPosition[ 1 ];\n\n    initialState[ zVelocityIndex ]\n                = initialStateInertial[ zVelocityIndex ] - omegaCrossPosition[ 2 ];\n\n    // set up boost odeint\n    const double absoluteTolerance = 1.0e-15;\n    const double relativeTolerance = 1.0e-15;\n    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;\n\n    // state step size guess (at each step this initial guess will be used)\n    double stepSizeGuess = initialStepSize;\n\n    // initialize the ode system\n    const double zRotation = asteroidRotationVector[ zPositionIndex ];\n    equationsOfMotionParticleAroundSpheroid particleAroundSpheroidProblem( gravParameter, alpha, zRotation );\n\n    // initialize current state vector and time\n    std::vector< double > currentStateVector = initialState;\n    double currentTime = startTime;\n    double intermediateEndTime = currentTime + dataSaveIntervals;\n\n    // save the initial state vector\n    outputFile << currentStateVector[ xPositionIndex ] << \",\";\n    outputFile << currentStateVector[ yPositionIndex ] << \",\";\n    outputFile << currentStateVector[ zPositionIndex ] << \",\";\n    outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n    outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n    outputFile << currentTime << std::endl;\n\n    // start the integration outer loop\n    while( intermediateEndTime <= endTime )\n    {\n        // perform integration, integrated result stored in currentStateVector\n        size_t steps = boost::numeric::odeint::integrate_adaptive(\n                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),\n                            particleAroundSpheroidProblem,\n                            currentStateVector,\n                            currentTime,\n                            intermediateEndTime,\n                            stepSizeGuess );\n\n        // update the time variables\n        currentTime = intermediateEndTime;\n        intermediateEndTime = currentTime + dataSaveIntervals;\n\n        // save data\n        outputFile << currentStateVector[ xPositionIndex ] << \",\";\n        outputFile << currentStateVector[ yPositionIndex ] << \",\";\n        outputFile << currentStateVector[ zPositionIndex ] << \",\";\n        outputFile << currentStateVector[ xVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ yVelocityIndex ] << \",\";\n        outputFile << currentStateVector[ zVelocityIndex ] << \",\";\n        outputFile << currentTime << std::endl;\n\n    } // end of outer while loop for integration\n\n    outputFile.close( );\n}\n\n} // namespace naos\n", "meta": {"hexsha": "400d7d07ef41a2f82d04c1de1dd42f6db49662d0", "size": 9199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/particleAroundSpheroidAndEllipsoidGravitationalPotential.cpp", "max_stars_repo_name": "agrawalabhishek/NAOS", "max_stars_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/particleAroundSpheroidAndEllipsoidGravitationalPotential.cpp", "max_issues_repo_name": "agrawalabhishek/NAOS", "max_issues_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particleAroundSpheroidAndEllipsoidGravitationalPotential.cpp", "max_forks_repo_name": "agrawalabhishek/NAOS", "max_forks_repo_head_hexsha": "25ae383d2c3f9a52ecd2e06f34661e52e239478b", "max_forks_repo_licenses": ["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.587962963, "max_line_length": 109, "alphanum_fraction": 0.6125665833, "num_tokens": 1792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5743687846124629}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <limits>\n#include <numeric>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include \"losslessops.h\"\n\nusing namespace crolol;\nusing namespace backend;\nnamespace mp = boost::multiprecision;\nusing std::int64_t;\nusing slims = std::numeric_limits<int64_t>;\nusing int128 = mp::int128_t;\nusing float128 = mp::cpp_bin_float_quad;\n\nstatic constexpr int64_t slmax = slims::max();\nstatic constexpr int64_t slmin = slims::min();\nstatic constexpr int64_t scale = 1000;\nstatic const float128 slmaxlog2 = mp::log2(static_cast<float128>(slmax) / scale);\nstatic const float128 slminlog2 = mp::log2(-static_cast<float128>(slmax) / scale);\n\nstatic saferet clamp(const int128& n)\n{\n\tsaferet out;\n\tout.val = static_cast<int64_t>(n);\n\t\n\tif (n > static_cast<int128>(slmax))\n\t\tout.flow = overflow;\n\telse if (n < static_cast<int128>(slmin))\n\t\tout.flow = underflow;\n\n\treturn out;\n}\n\nstatic saferet make_error(const flowstatus flow)\n{\n\tsaferet out;\n\tout.flow = flow;\n\t\n\treturn out;\n}\n\nstatic saferet make_badarg(const int64_t val)\n{\n\tsaferet out = make_error(badarg);\n\tout.val = val;\n\t\n\treturn out;\n}\n\nsaferet backend::multiply(int64_t n, int64_t m)\n{\n\treturn clamp((static_cast<int128>(n) * static_cast<int128>(m))\n\t\t/ static_cast<int128>(scale));\n}\n\nsaferet backend::divide(int64_t n, int64_t m)\n{\n\tif (m == 0) return make_badarg(n);\n\telse return clamp((static_cast<int128>(n) * scale)\n\t\t/ static_cast<int128>(m));\n}\n\nsaferet backend::pow(int64_t n, int64_t m)\n{\n\tif (n < 0 && m % scale != 0) return make_badarg(m);\n\telse if (n == 0 && m == 0) return clamp(scale);\n\telse if (n == 0 && m < 0) return make_badarg(m);\n\telse if (n == scale || m == 0) return clamp(scale);\n\telse if (m == scale) return clamp(n);\n\t\n\tconst float128 nf = static_cast<float128>(n) / scale;\n\tconst float128 mf = static_cast<float128>(m) / scale;\n\tconst float128 size = mp::log2(mp::abs(nf)) * mf;\n\t\n\tif (size > slmaxlog2) return clamp(slmax);\n\telse if (mp::abs(size) > slminlog2) return clamp(slmin);\n\telse return clamp(static_cast<int128>(\n\t\tmp::llrint(mp::trunc(mp::pow(nf, mf) * scale))\n\t));\n}\n\nsaferet backend::factorial(int64_t n)\n{\n\tif (n < 0 or n % scale != 0) return make_badarg(n);\n\t\n\tsaferet acc = clamp(scale);\n\t\n\tfor (int64_t i = 0; i < n && acc.flow == noflow; i += scale)\n\t\tacc = multiply(acc.val, i);\n\t\n\treturn acc;\n}\n\nstatic const int64_t cr2pi = std::llrintl(std::truncl(M_PI * 2.L * scale));\nstatic constexpr long double radtodeg = 360.L / (M_PI * 2.L);\nstatic constexpr long double degtorad = (M_PI * 2.L) / 360.L;\n\nstatic long double trigmod(int64_t n)\n{\n\treturn static_cast<long double>(n % cr2pi) * degtorad / scale;\n}\n\nsaferet backend::sin(int64_t n)\n{\n\treturn clamp(static_cast<int128>(\n\t\tstd::truncl(std::sin(trigmod(n))) * scale\n\t));\n}\n\nsaferet backend::cos(int64_t n)\n{\n\treturn clamp(static_cast<int128>(\n\t\tstd::truncl(std::cos(trigmod(n))) * scale\n\t));\n}\n\nsaferet backend::tan(int64_t n)\n{\n\treturn clamp(static_cast<int128>(\n\t\tstd::truncl(std::tan(trigmod(n))) * scale\n\t));\n}\n\nsaferet backend::asin(int64_t n)\n{\n\tif (n > scale or n < -scale) return make_badarg(n);\n\telse return clamp(static_cast<int128>(\n\t\tstd::truncl(std::asin(\n\t\t\tstatic_cast<long double>(n) / scale\n\t\t)) * scale * radtodeg\n\t));\n}\n\nsaferet backend::acos(int64_t n)\n{\n\tif (n > scale or n < -scale) return make_badarg(n);\n\telse return clamp(static_cast<int128>(\n\t\tstd::truncl(std::acos(\n\t\t\tstatic_cast<long double>(n) / scale\n\t\t)) * scale * radtodeg\n\t));\n}\n\nsaferet backend::atan(int64_t n)\n{\n\treturn clamp(static_cast<int128>(\n\t\tstd::truncl(std::atan(\n\t\t\tstatic_cast<long double>(n) / scale\n\t\t)) * scale * radtodeg\n\t));\n}", "meta": {"hexsha": "016910f51adef02f61bbb52bdd9c43ffe34e37cc", "size": 3678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/losslessops.cpp", "max_stars_repo_name": "ocornoc/crolol", "max_stars_repo_head_hexsha": "292268d81a01ac00dae382f3ba51d9c300438ed5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T15:30:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-05T21:17:02.000Z", "max_issues_repo_path": "src/losslessops.cpp", "max_issues_repo_name": "ocornoc/crolol", "max_issues_repo_head_hexsha": "292268d81a01ac00dae382f3ba51d9c300438ed5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/losslessops.cpp", "max_forks_repo_name": "ocornoc/crolol", "max_forks_repo_head_hexsha": "292268d81a01ac00dae382f3ba51d9c300438ed5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T02:00:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-05T02:00:18.000Z", "avg_line_length": 23.8831168831, "max_line_length": 82, "alphanum_fraction": 0.6859706362, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5743687831959746}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2019 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 \"rigid_alignment.h\"\n#include \"polar_svd.h\"\n#include <Eigen/Sparse>\n#include <Eigen/Cholesky>\n#include <vector>\n#include <iostream>\n\ntemplate <\n  typename DerivedX,\n  typename DerivedP,\n  typename DerivedN,\n  typename DerivedR,\n  typename Derivedt\n>\nIGL_INLINE void igl::rigid_alignment(\n  const Eigen::MatrixBase<DerivedX> & _X,\n  const Eigen::MatrixBase<DerivedP> & P,\n  const Eigen::MatrixBase<DerivedN> & N,\n  Eigen::PlainObjectBase<DerivedR> & R,\n  Eigen::PlainObjectBase<Derivedt> & t)\n{\n  typedef typename DerivedX::Scalar Scalar;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixXS;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorXS;\n  typedef Eigen::Matrix<Scalar,3,3> Matrix3S;\n  const int k = _X.rows();\n  VectorXS Z = VectorXS::Zero(k,1);\n  VectorXS I = VectorXS::Ones(k,1);\n\n  DerivedX X = _X;\n  R = DerivedR::Identity(3,3);\n  t = Derivedt::Zero(1,3);\n  // See gptoolbox, each iter could be O(1) instead of O(k)\n  const int max_iters = 5;\n  for(int iters = 0;iters<max_iters;iters++)\n  {\n    MatrixXS A(k*3,6);\n    A <<\n               Z, X.col(2),-X.col(1),I,Z,Z,\n       -X.col(2),        Z, X.col(0),Z,I,Z,\n        X.col(1),-X.col(0),        Z,Z,Z,I;\n    VectorXS B(k*3,1);\n    B<<\n      P.col(0)-X.col(0),\n      P.col(1)-X.col(1),\n      P.col(2)-X.col(2);\n    std::vector<Eigen::Triplet<Scalar> > NNIJV;\n    for(int i = 0;i<k;i++)\n    {\n      for(int c = 0;c<3;c++)\n      {\n        NNIJV.emplace_back(i,i+k*c,N(i,c));\n      }\n    }\n    Eigen::SparseMatrix<Scalar> NN(k,k*3);\n    NN.setFromTriplets(NNIJV.begin(),NNIJV.end());\n    A = (NN * A).eval();\n    B = (NN * B).eval();\n    VectorXS u = (A.transpose() * A).ldlt().solve(A.transpose() * B);\n    Derivedt ti = u.tail(3).transpose();\n\n    Matrix3S W;\n    W<<\n          0, u(2),-u(1),\n      -u(2),    0, u(0),\n       u(1),-u(0),    0;\n    // strayed from a perfect rotation. Correct it.\n    const double x = u.head(3).stableNorm();\n    DerivedR Ri;\n    if(x == 0)\n    {\n      Ri = DerivedR::Identity(3,3);\n    }else\n    {\n      Ri = \n        DerivedR::Identity(3,3) + \n        sin(x)/x*W + \n        (1.0-cos(x))/(x*x)*W*W;\n    }\n    \n    R = (R*Ri).eval();\n    t = (t*Ri + ti).eval();\n    X = ((_X*R).rowwise()+t).eval();\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::rigid_alignment<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, 3, 3, 0, 3, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 3, 0, 3, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&);\n#endif\n", "meta": {"hexsha": "fdff2ddc0c7f8414701bfb3970fba8c27067817e", "size": 3219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/rigid_alignment.cpp", "max_stars_repo_name": "GitZHCODE/zspace_modules", "max_stars_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T14:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T14:10:51.000Z", "max_issues_repo_path": "cpp/depends/igl/headers/igl/rigid_alignment.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/rigid_alignment.cpp", "max_forks_repo_name": "GitZHCODE/zspace_modules", "max_forks_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-23T10:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T14:09:55.000Z", "avg_line_length": 32.8469387755, "max_line_length": 573, "alphanum_fraction": 0.5924200062, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5743687751638312}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <stdint.h>\n#include <Eigen/Dense>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n#include <dpMM/global.hpp>\n\n#ifndef PI\n#  define PI 3.141592653589793\n#endif\n#define LOG_PI 1.1447298858494002\n#define LOG_2 0.69314718055994529\n#define LOG_2PI 1.8378770664093453\n\nusing namespace Eigen;\n\ntemplate<typename T>\nclass Distribution\n{\npublic:\n  Distribution(boost::mt19937* pRndGen) : pRndGen_(pRndGen)\n  {};\n  virtual ~Distribution()\n  {};\n\n//  virtual logProb()\n  boost::mt19937* pRndGen_;\nprivate:\n};\n\n\ntemplate<typename T, typename T2>\ninline Matrix<T,Dynamic,1> counts(const Matrix<T2,Dynamic,1> & z, T2 K)\n{\n  Matrix<T,Dynamic,1> N(K);\n  N.setZero(K);\n  for (T2 i=0; i<z.size(); ++i)\n    N(z(i))++;\n  return N;\n};\n\n//inline VectorXd counts(const VectorXu& z, uint32_t K)\n//{\n//  VectorXd N(K);\n//  N.setZero(K);\n//  for (uint32_t i=0; i<z.size(); ++i)\n//    N(z(i))++;\n//  return N;\n//};\n\n/* multivariate gamma function of dimension p */\ninline double lgamma_mult(double x,uint32_t p)\n{\n  assert(x+0.5*(1.-p) > 0.);\n  double lgam_p = p*(p-1.)*0.25*LOG_PI;\n  for (uint32_t i=1; i<p+1; ++i)\n  {\n//    cout<<\"digamma_mult of \"<<(x + (1.0-double(i))/2)<<\" = \"<<digamma(x + (1.0-double(i))/2)<<endl;\n    lgam_p += boost::math::lgamma(x + 0.5*(1.0-double(i)));\n  }\n  return lgam_p;\n}\n\ntemplate<typename T>\ninline T logsumexp(T x1, T x2)                                   \n{                                                                               \n   if (x1>x2)                                                                   \n      return x1 + log(1.+exp(x2-x1));                                            \n   else                                                                         \n      return x2 + log(1.+exp(x1-x2));                                            \n}\n", "meta": {"hexsha": "d855319fbccb1cca37ead936de0e2ec247061c39", "size": 2014, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/distribution.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/distribution.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/distribution.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": 25.4936708861, "max_line_length": 101, "alphanum_fraction": 0.5243296922, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.5742608187318917}}
{"text": "#include <iostream>\r\n\r\n#include <deal.II/base/tensor.h>\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n    const unsigned int dim = 2;\r\n   \r\n    dealii::Tensor<2, dim> T;\r\n    \r\n    std::cout << \"T = \";\r\n    \r\n    for (unsigned int i = 0; i < T.n_independent_components; ++i)\r\n    {\r\n        auto indices = T.unrolled_to_component_indices(i);\r\n        \r\n        std::cout << \"T_{\" << indices[0] + 1 << indices[1] + 1 << \"}\" << \" \";\r\n        \r\n    }\r\n    \r\n    for (unsigned int i = 1; i < (dim + 1); ++i)\r\n    {\r\n        for (unsigned int j = 1; j < (dim + 1); ++j)\r\n        {\r\n            T[i - 1][j - 1] = 10*i + j;\r\n        }\r\n    }\r\n\r\n    std::cout << std::endl << std::endl << \"T = \" << T << std::endl;\r\n    \r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "5d92a593b5ba9d2878c502a660470c859ee5b6a8", "size": 726, "ext": "cc", "lang": "C++", "max_stars_repo_path": "doc/extra/tensor_indexing.cc", "max_stars_repo_name": "geo-fluid-dynamics/phaseflow", "max_stars_repo_head_hexsha": "5c2f27ec9debba9ac91c29aef09e8697d8bfb74c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T00:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-16T15:16:15.000Z", "max_issues_repo_path": "doc/extra/tensor_indexing.cc", "max_issues_repo_name": "geo-fluid-dynamics/phaseflow", "max_issues_repo_head_hexsha": "5c2f27ec9debba9ac91c29aef09e8697d8bfb74c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T10:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-05T05:38:00.000Z", "max_forks_repo_path": "doc/extra/tensor_indexing.cc", "max_forks_repo_name": "geo-fluid-dynamics/phaseflow-dealii", "max_forks_repo_head_hexsha": "5c2f27ec9debba9ac91c29aef09e8697d8bfb74c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-06-02T11:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-02T11:21:52.000Z", "avg_line_length": 22.0, "max_line_length": 78, "alphanum_fraction": 0.4242424242, "num_tokens": 228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5741578259472271}}
{"text": "/** \n * This code has been downloaded from the website of Bojan Nikolic\n * see http://www.bnikolic.co.uk/blog/cpp-khachiyan-min-cov-ellipsoid.html\n * the code implements Khachiyan's algorithm to compute the Minimum volume\n * enclosing ellipsoid approximately. \n *\n * Some parts were written inefficiently so have been changed.\n */\n\n#include \"MVE.h\"\n#include \"RMSUtils.h\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"cholesky.h\"\n\nnamespace ublas=boost::numeric::ublas;\n\ntemplate<class T>\nbool InvertMatrix(const ublas::matrix<T> &input, ublas::matrix<T> &inverse) {\n    using namespace boost::numeric::ublas;\n\n    typedef permutation_matrix<std::size_t> pmatrix;\n    matrix<T> A(input);\n    pmatrix pm(A.size1());\n    int res = lu_factorize(A, pm);\n    if (res != 0) return false;\n    inverse.assign(identity_matrix<T>(A.size1()));\n    lu_substitute(A, pm, inverse);\n    return true;\n}\n\nvoid InvertLP(const ublas::matrix<double> &Lambdap, ublas::matrix<double> &LpInv) {\n    bool res = InvertMatrix(Lambdap, LpInv);\n    if (not res) {\n        throw std::runtime_error(\"Could not invert Matrix\");\n    }\n}\n\nvoid Lift(const ublas::matrix<double> &A, ublas::matrix<double> &Ap) {\n    Ap.resize(A.size1() + 1,\n              A.size2());\n    ublas::matrix_range<ublas::matrix<double> >\n            sub(Ap,\n                ublas::range(0, A.size1()),\n                ublas::range(0, A.size2()));\n    sub.assign(A);\n    ublas::row(Ap, Ap.size1() - 1) = ublas::scalar_vector<double>(A.size2(), 1.0);\n\n}\n\nvoid genDiag(const ublas::vector<double> &p,\n             ublas::matrix<double> &res) {\n    res.assign(ublas::zero_matrix<double>(p.size(),\n                                          p.size()));\n    for (size_t i = 0; i < p.size(); ++i) {\n        res(i, i) = p(i);\n    }\n}\n\nvoid KaLambda(const ublas::matrix<double> &Ap,\n              const ublas::vector<double> &p,\n              ublas::matrix<double> &Lambdap) {\n    //cout << \"KaLambda: Ap.size1() = \" << Ap.size1() << \", Ap.size2() = \"\n    //\t << Ap.size2() << \", p.size() = \" << p.size() << endl;\n    assert(p.size() == Ap.size2());\n\n    /** \n        This code is very inefficient (It is trying to allocate a matrix\n        of size m x m where m = # of points which is simply infeasible\n        for large data sets\n\n        It is basically trying to compute the sum of p_i q_i q_i^t for \n        i in 1 to m where m is the number of points and p is a m dimensional\n        vector p = (p_1, ...., p_m)^t. Since each q_i is a n x 1 vector\n        the return value of this is a n x n matrix.\t\n     **/\n    /*\n    ublas::matrix<double> dp(p.size(), p.size());\n    genDiag(p, dp);\n\n    dp=ublas::prod(dp, ublas::trans(Ap));\n    Lambdap=ublas::prod(Ap,\n                        dp);\n    */\n\n    /* Recall that Lambda(p) is a matrix of size n x n where it is simply\n       defined as Lambda(p) = sum of p_i q_i q_i^t for i from 1 to m\n       and q_i are the n x 1 vectors representing the (lifted points)\n       The matrix Ap is (q_i .... q_m). It is a n x m matrix\n    */\n    size_t n = Ap.size1();\n    ublas::matrix<double> sum(n, n);\n    sum.assign(ublas::zero_matrix<double>(n, n));\n\n    /* directly invoke the correct formula for matrix product */\n    for (size_t i = 0; i < p.size(); i++) {\n        for (size_t j = 0; j < n; j++)\n            for (size_t k = 0; k < n; k++)\n                sum(j, k) += p(i) * Ap(j, i) * Ap(k, i);\n    }\n    Lambdap = sum;\n}\n\n\ndouble KhachiyanIter(const ublas::matrix<double> &Ap,\n                     ublas::vector<double> &p) {\n    /// Dimensionality of the problem\n    const size_t d = Ap.size1() - 1;\n\n    ublas::matrix<double> Lp;\n    KaLambda(Ap, p, Lp);\n    ublas::matrix<double> ILp(Lp.size1(), Lp.size2());\n    InvertLP(Lp, ILp);\n\n\n    /**\n        * This code is very inefficient as it is trying to allocate\n        * a matrix of size m x m where m is the number of data\n        * points simply to get the diagonal elements of M !!\n\n        * Basically it is trying to do the following:\n\t* M = ILp * Ap where ILp is a n x n matrix and\n\t* Ap is a n x m matrix (n is dimension, m is number\n\t* of points). The needed output is a set of m numbers\n\t* where the i-th number is basically <Ap_i^t, M_i>\n\t* i.e. the dot product of the transpose of the i-th\n\t* column of Ap and the i-th column of M. \n\n    ublas::matrix<double> M;\n    M=ublas::prod(ILp, Ap);\n    M=ublas::prod(ublas::trans(Ap), M);\n\n    double maxval=0;\n    size_t maxi=0;\n    for(size_t i=0; i<M.size1(); ++i)\n    {\n        if (M(i,i) > maxval)\n        {\n            maxval=M(i,i);\n            maxi=i;\n        }\n    }\n    **/\n\n    double maxval = 0;\n    size_t maxi = 0;\n    ublas::matrix<double> M = ublas::prod(ILp, Ap);\n    ublas::matrix<double> Apt = ublas::trans(Ap);\n    assert(M.size1() == Apt.size2());\n\n    for (size_t i = 0; i < Ap.size2(); i++) {\n        //evaluate the product c_i^t (ILp) c_i\n        ublas::matrix_column<ublas::matrix<double> > mc(M, i);\n        ublas::matrix_row<ublas::matrix<double> > mr(Apt, i);\n\n        //evaluate the left product of row and column\n        double prod = 0;\n        for (size_t j = 0; j < mc.size(); j++)\n            prod += mr(j) * mc(j);\n\n        if (prod > maxval) {\n            maxval = prod;\n            maxi = i;\n        }\n\n    }\n\n    const double step_size = (maxval - d - 1) / ((d + 1) * (maxval - 1));\n    ublas::vector<double> newp = p * (1 - step_size);\n    newp(maxi) += step_size;\n\n    const double err = ublas::norm_2(newp - p);\n    p = newp;\n    return err;\n\n}\n\nvoid KaInvertDual(const ublas::matrix<double> &A,\n                  const ublas::vector<double> &p,\n                  ublas::matrix<double> &Q,\n                  ublas::vector<double> &c\n) {\n    const size_t d = A.size1();\n    /** This part of the code is not efficient. It is trying\n        to allocate a matrix dp of size m x m where m is the\n        number of points\n\n\tBasically it is trying to do the following: \n\tHere A is a n x m matrix (where n is dimension\n\tand m is number of points)\n\n\tThe output of this code is PN a m x n matrix where\n\tthe row i is the transpose of the i-th column of A\n\tmultiplied by p_i where p is a m-vector.\n    **/\n/*\n    ublas::matrix<double> dp(p.size(), p.size());\n    genDiag(p, dp);\n\n    ublas::matrix<double> PN=ublas::prod(dp, ublas::trans(A));\n*/\n    //========= Begin replacement code ===============\n    ublas::matrix<double> PN = ublas::trans(A);\n    assert(p.size() == PN.size1());\n    for (size_t i = 0; i < PN.size1(); i++)\n        for (size_t j = 0; j < PN.size2(); j++)\n            PN(i, j) *= p(i);\n    //======== End replacement code ===================\n\n    PN = ublas::prod(A, PN);\n\n    ublas::vector<double> M2 = ublas::prod(A, p);\n    ublas::matrix<double> M3 = ublas::outer_prod(M2, M2);\n\n    ublas::matrix<double> invert(PN.size1(), PN.size2());\n    InvertLP(PN - M3, invert);\n\n    Q.assign(1.0 / d * invert);\n    c = ublas::prod(A, p);\n}\n\n\ndouble KhachiyanAlgo(const ublas::matrix<double> &A,\n                     double eps,\n                     size_t maxiter,\n                     ublas::matrix<double> &Q,\n                     ublas::vector<double> &c) {\n    ublas::vector<double> p = ublas::scalar_vector<double>(A.size2(), 1.0) * (1.0 / A.size2());\n\n    ublas::matrix<double> Ap;\n    Lift(A, Ap);\n\n    double ceps = eps * 2;\n    for (size_t i = 0; i < maxiter && ceps > eps; ++i) {\n        ceps = KhachiyanIter(Ap, p);\n    }\n\n    KaInvertDual(A, p, Q, c);\n\n    return ceps;\n}\n\n\nvoid print_matrix(const ublas::matrix<double> &A) {\n    for (size_t i = 0; i < A.size1(); i++) {\n        for (size_t j = 0; j < A.size2(); j++)\n            cout << A(i, j) << \"  \";\n        cout << endl;\n    }\n}\n\n\nvoid print_vector(const ublas::vector<double> &v) {\n    if (v.size() == 1) {\n        cout << v(0) << endl;\n        return;\n    }\n\n    cout << \"---     ---\" << endl;\n    for (size_t i = 0; i < v.size(); i++) {\n        cout << \"||\" << \" \" << v(i) << \" \" << \"||\" << endl;\n    }\n\n    cout << \"---     ---\" << endl;\n}\n\nvoid MVEUtil::GetNormalizedMVE(const vector<Point> &dataP,\n                               float epsilon,\n                               vector<Point> &normalizedP,\n                               double &outer_rad,\n                               double &inner_rad\n) {\n    using namespace boost::numeric::ublas;\n\n    if (dataP.size() == 0)\n        return;\n\n    size_t d = dataP[0].get_dimension();\n\n    ublas::matrix<double> A(d, dataP.size());\n\n    size_t j = 0;\n\n    for (size_t i = 0; i < dataP.size(); i++) {\n        for (size_t k = 0; k < d; k++)\n            A(k, j) = dataP[i].get_coordinate(k);\n        ++j;\n    }\n\n    //try Khachiyans algorithm\n    //cout << \"Running Khachiyan algorithm \" << endl;\n\n\n    ublas::matrix<double> Q(d, d);\n    ublas::vector<double> c(d);\n\n    size_t maxiter = 1024 * dataP.size() * d;\n    double ceps = KhachiyanAlgo(A, epsilon, maxiter, Q, c);\n    if (ceps > epsilon) {\n        throw std::runtime_error(\"Khachiyan failed ... \");\n    }\n\n    /** Only for debug    \n    cout << \"Khachiyan returned \" << ceps << endl;\n    cout << \"Printing the matrix Q \" << endl;\n    print_matrix(Q);\n    **/\n\n    /**\n        The equation of the ellipse that is returned\n\tby Khachiyan algorithm is (x - c)^T Q (x - c) <= 1\n        Unfortunately all the points of the data set\n\tdo not satisfy it (but they do satisfy it\n\tapproximately). Now we can put (1+epsilon) * dim\n\ton the right hand side and the points will\n\tstill satisfy it, but this may be too loose\n\tan approximation. Instead, we find the maximum\n\tof (x-c)^T Q (x-c) over all the data points,\n\tadd 0.01, and take that as the RHS.\n\tThe square root of this gives the radius of\n\tthe outer sphere, when we apply a linear \n\ttransform to turn the ellipsoid into a ball\n    **/\n    double max_val = 0;\n    for (size_t i = 0; i < dataP.size(); i++) {\n        ublas::vector<double> ublasp = Point::to_ublas(dataP[i]);\n\n        //compute p - c\n        ublasp = ublasp - c;\n\n        //compute Q (p - c)\n        ublas::vector<double> prod1 = ublas::prod(Q, ublasp);\n\n        //compute (p - c)^T\n        ublas::matrix<double> ublasptr(1, d);\n        for (size_t j = 0; j < d; j++)\n            ublasptr(0, j) = ublasp[j];\n\n        //compute (p-c)^T Q (p-c)\n        ublas::vector<double> x = ublas::prod(ublasptr, prod1);\n\n        if (x(0) > max_val) max_val = x(0);\n\n        /** for debug\n        cout << \"Printing (p-c)^T Q (p -c ) \" ;\n        print_vector(x);\n        cout << endl;\n        **/\n    }\n\n    //the radius of the outer sphere\n    outer_rad = sqrt(max_val + 0.01);\n\n\n    //now compute the linear transformation\n    ublas::matrix<double> L(d, d);\n    //compute a Cholesky factorization\n    int res = cholesky_decompose(Q, L);\n\n    if (res != 0) {\n        cout << \"Cholesky decomposition failed \" << res << endl;\n        exit(1);\n    }\n\n    /** debug \n    cout << \"Printing cholesky decomposition \" << endl;\n    print_matrix(L);\n    **/\n\n    //get the transpose of L\n    ublas::matrix<double> LTr(d, d);\n    LTr = ublas::trans(L);\n\n    //ublas::matrix<double> chprod = ublas::prod(L, LTr);\n    //print_matrix(chprod);\n\n    normalizedP = dataP;\n\n    for (size_t i = 0; i < dataP.size(); i++) {\n        ublas::vector<double> ublasp = Point::to_ublas(normalizedP[i]);\n\n        //compute the linear transformation\n        ublasp = ublasp - c;\n        ublasp = ublas::prod(LTr, ublasp);\n        normalizedP[i] = Point::from_ublas(ublasp);\n    }\n\n    inner_rad = 1 / ((1 + epsilon) * d);\n\n\n    /* save this matrix into RandomUtil class for further use */\n    /* the use requires the inverse of (matrix transpose) of Ltr */\n    ublas::matrix<double> IL(d, d);\n    InvertLP(L, IL);\n    RMSUtils::dimension = d;\n    RMSUtils::transformation_matrix = IL;\n    RMSUtils::center = c;\n\n    return;\n}\n\n", "meta": {"hexsha": "2b33e6bd0221b2f2b5daca7a6915d8851abccf33", "size": 11837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ANN/MVE.cpp", "max_stars_repo_name": "yhwang1990/minimum-coresets", "max_stars_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-19T13:01:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T13:01:43.000Z", "max_issues_repo_path": "ANN/MVE.cpp", "max_issues_repo_name": "yhwang1990/minimum-coresets", "max_issues_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANN/MVE.cpp", "max_forks_repo_name": "yhwang1990/minimum-coresets", "max_forks_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2995049505, "max_line_length": 95, "alphanum_fraction": 0.5568133818, "num_tokens": 3493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5741126084287541}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2015-2020 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// Calculating free energy, energy, and specific heat of triangular lattice Ising model\n\n#include <iomanip>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include \"triangle/infinite.hpp\"\n\nint main(int argc, char **argv) {\n  typedef double real_t;\n  real_t Ja, Jb, Jc, t_min, t_max, t_step;\n  if (argc == 7) {\n    Ja = boost::lexical_cast<real_t>(argv[1]);\n    Jb = boost::lexical_cast<real_t>(argv[2]);\n    Jc = boost::lexical_cast<real_t>(argv[3]);\n    t_min = boost::lexical_cast<real_t>(argv[4]);\n    t_max = boost::lexical_cast<real_t>(argv[5]);\n    t_step = boost::lexical_cast<real_t>(argv[6]);\n  } else if (argc == 1) {\n    std::cin >> Ja >> Jb >> Jc >> t_min >> t_max >> t_step;\n  } else {\n    std::cerr << \"Usage: \" << argv[0] << \" [Ja Jb Jc t_min t_max t_step]\\n\";\n    return 127;\n  }\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10);\n  std::cout << \"# triangular lattice Ising model\\n\";\n  std::cout << \"# Ja, Jb, Jc, T, free energy density, energy density, specific heat\\n\";\n  for (real_t t = t_min; t <= t_max; t += t_step) {\n    real_t beta = 1 / t;\n    auto result = ising::triangle::infinite(beta, Ja, Jb, Jc);\n    std::cout << Ja << ' ' << Jb << ' ' << Jc << ' ' << t << ' ' << std::get<0>(result) << ' '\n              << std::get<1>(result) << ' ' << std::get<2>(result) << std::endl;\n  }\n}\n", "meta": {"hexsha": "aa7b2b528d22a3715f9926cc591184c8b491f105", "size": 1746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ising/triangle/free_energy.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "test/ising/triangle/free_energy.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "test/ising/triangle/free_energy.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6046511628, "max_line_length": 94, "alphanum_fraction": 0.5612829324, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5741065822763659}}
{"text": "/* \n    Author: hauptmech <hauptmech@gmail.com>, Nov 2013 \n\n    This is free and unencumbered software released into the public domain.\n\n    Anyone is free to copy, modify, publish, use, compile, sell, or\n    distribute this software, either in source code form or as a compiled\n    binary, for any purpose, commercial or non-commercial, and by any\n    means.\n\n    In jurisdictions that recognize copyright laws, the author or authors\n    of this software dedicate any and all copyright interest in the\n    software to the public domain. We make this dedication for the benefit\n    of the public at large and to the detriment of our heirs and\n    successors. We intend this dedication to be an overt act of\n    relinquishment in perpetuity of all present and future rights to this\n    software under copyright law.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n    OTHER DEALINGS IN THE SOFTWARE.\n\n    For more information, please refer to <http://unlicense.org/>\n*/\n\n\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n    // Init a fixed size 3x3 matrix\n    Matrix3d m3 {{1.2,2.2,3.3},{4.2,2.5,6.3},{7.2,8.2,9.3}};\n    std::cout << \"\\nm3:\\n\" << m3 << std::endl;\n\n\n    // Initialize a variable length Matrix to 2x2\n    MatrixXd mY {{1.2,2.2},{3.2,4.5}};\n    std::cout << \"\\nmY:\\n\" << mY << std::endl;\n\n    // Initialize a variable length Matrix (Vector) to 9x1\n    // 2D Matrices are initialized column-wise\n    MatrixXd mX {1.2,2.2,3.3, 4.2,2.5,6.3, 7.2,8.2,9.3};\n    std::cout << \"\\nmX:\\n\" << mX << std::endl;\n\n    // Init a 3 element vector\n    Vector3d v3  {1,3,3};\n    std::cout << \"\\nv3:\\n\" << v3 << std::endl;\n\n\n\n\n\n\n    // Init a fixed size 3x3 array\n    Array33d a3 {{1.2,2.2,3.3},{4.2,2.5,6.3},{7.2,8.2,9.3}};\n    std::cout << \"\\na3:\\n\" << a3 << std::endl;\n\n\n    // Initialize a variable length Array to 2x2\n    ArrayXXd aY {{1.2,2.2},{3.2,4.5}};\n    std::cout << \"\\naY:\\n\" << aY << std::endl;\n\n    // Initialize a variable length Array to 9x1\n    // 2D Arrays are initialized column-wise\n    ArrayXXd aX {1.2,2.2,3.3, 4.2,2.5,6.3, 7.2,8.2,9.3};\n    std::cout << \"\\naX:\\n\" << aX << std::endl;\n\n    // Init a 3 element array\n    Array3d w3  {1,3,3};\n    std::cout << \"\\nw3:\\n\" << w3 << std::endl;\n}\n\n", "meta": {"hexsha": "3acdf4a50ebbd2f7f1c1a0b6916e94c070a9e2a9", "size": 2626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_initializer_list_demo.cpp", "max_stars_repo_name": "tsmithe/eigen-initializer_list", "max_stars_repo_head_hexsha": "a2a8551c61ed490332c7c017ce67122da84885bc", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-07-11T23:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T10:46:34.000Z", "max_issues_repo_path": "src/eigen_initializer_list_demo.cpp", "max_issues_repo_name": "tsmithe/eigen-initializer_list", "max_issues_repo_head_hexsha": "a2a8551c61ed490332c7c017ce67122da84885bc", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-04-30T09:38:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-24T08:29:42.000Z", "max_forks_repo_path": "src/eigen_initializer_list_demo.cpp", "max_forks_repo_name": "tsmithe/eigen-initializer_list", "max_forks_repo_head_hexsha": "a2a8551c61ed490332c7c017ce67122da84885bc", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-07-23T22:52:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T13:52:14.000Z", "avg_line_length": 32.825, "max_line_length": 75, "alphanum_fraction": 0.6466108149, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.5740207818152967}}
{"text": "/**\n * @file\n * @brief NPDE homework \"Handling degrees of freedom (DOFs) in LehrFEM++\"\n * @author Julien Gacon\n * @date March 1st, 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"lfppdofhandling.h\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <memory>\n\n#include \"lf/assemble/assemble.h\"\n#include \"lf/base/base.h\"\n#include \"lf/geometry/geometry.h\"\n#include \"lf/mesh/mesh.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nnamespace LFPPDofHandling {\n\n/* SAM_LISTING_BEGIN_1 */\nstd::array<std::size_t, 3> countEntityDofs(\n    const lf::assemble::DofHandler &dofhandler) {\n  std::array<std::size_t, 3> entityDofs;\n  //====================\n  // Your code goes here\n  //====================\n  for (int codim=0; codim<3; codim++){\n    entityDofs[codim] = 0;\n  }\n\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n\n  for (int codim=0; codim<3; codim++){\n    for (const auto *entity : mesh->Entities(codim)){\n      if (entity->RefEl() == lf::base::RefEl::kQuad()){\n        throw(\"Error\");\n      }\n      entityDofs[codim] += dofhandler.NumInteriorDofs(*entity);\n    }\n  }\n  return entityDofs;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::size_t countBoundaryDofs(const lf::assemble::DofHandler &dofhandler) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  // given an entity, bd\\_flags(entity) == true, if the entity is on the\n  // boundary\n  lf::mesh::utils::AllCodimMeshDataSet<bool> bd_flags(\n      lf::mesh::utils::flagEntitiesOnBoundary(mesh));\n  std::size_t no_dofs_on_bd = 0;\n  //====================\n  // Your code goes here\n  //====================\n\n  for (const auto *vertex : mesh->Entities(2)){\n    if (bd_flags(*vertex)){\n      no_dofs_on_bd+=1;\n    }\n  }\n  return no_dofs_on_bd;\n}\n/* SAM_LISTING_END_2 */\n\n// clang-format off\n/* SAM_LISTING_BEGIN_3 */\ndouble integrateLinearFEFunction(\n    const lf::assemble::DofHandler& dofhandler,\n    const Eigen::VectorXd& mu) {\n  double I = 0;\n  //====================\n  // Your code goes here\n  //====================\n\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  double area;\n  for (const auto *cell : mesh->Entities(0)){\n    lf::base::size_type cell_local_dofs = dofhandler.NumLocalDofs(*cell);\n    if (cell_local_dofs!=3){\n      throw(\"Error\");\n    }\n    lf::geometry::Geometry *cell_geo = cell->Geometry();\n    area = lf::geometry::Volume(*cell_geo);\n    const auto global_idxs = dofhandler.GlobalDofIndices(*cell);\n    for (auto idx_p=global_idxs.begin() ; idx_p<global_idxs.end() ; ++idx_p){\n      I += area/3.0 * mu(*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  //====================\n  // Your code goes here\n  //====================\n  //\n  std::shared_ptr<const lf::mesh::Mesh> mesh = dofhandler.Mesh();\n  double area;\n  for (const auto *cell : mesh->Entities(0)){\n    lf::base::size_type cell_local_dofs = dofhandler.NumLocalDofs(*cell);\n    if (cell_local_dofs!=6){\n      throw(\"Error\");\n    }\n    lf::geometry::Geometry *cell_geo = cell->Geometry();\n    area = lf::geometry::Volume(*cell_geo);\n    const auto global_idxs = dofhandler.GlobalDofIndices(*cell);\n    for (int i=3; i<6; i++){\n      I += (area/3.0 * mu[global_idxs[i]]);\n    }\n  }\n  return I;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd convertDOFsLinearQuadratic(\n    const lf::assemble::DofHandler &dofh_Linear_FE,\n    const lf::assemble::DofHandler &dofh_Quadratic_FE,\n    const Eigen::VectorXd &mu) {\n  if (dofh_Linear_FE.Mesh() != dofh_Quadratic_FE.Mesh()) {\n    throw \"Underlying meshes must be the same for both DOF handlers!\";\n  }\n  std::shared_ptr<const lf::mesh::Mesh> mesh =\n      dofh_Linear_FE.Mesh();                          // get the mesh\n  Eigen::VectorXd zeta(dofh_Quadratic_FE.NumDofs());  // initialise empty zeta\n  // safety guard: always set zero if you're not sure to set every entry later\n  // on for us this shouldn't be a problem, but just to be sure\n  zeta.setZero();\n\n  for (const auto *cell : mesh->Entities(0)) {\n    // check if the spaces are actually linear and quadratic\n    //====================\n    // Your code goes here\n    //====================\n    // get the global dof indices of the linear and quadratic FE spaces, note\n    // that the vectors obey the LehrFEM++ numbering, which we will make use of\n    // lin\\_dofs will have size 3 for the 3 dofs on the nodes and\n    // quad\\_dofs will have size 6, the first 3 entries being the nodes and\n    // the last 3 the edges\n    //====================\n    // Your code goes here\n    // assign the coefficients of mu to the correct entries of zeta, use\n    // the previous subproblem 2-9.a\n    //====================\n\n    if (dofh_Linear_FE.NumLocalDofs(*cell) != 3 ||\n        dofh_Quadratic_FE.NumLocalDofs(*cell) != 6){\n      throw(\"Error\");\n    }\n    nonstd::span<const lf::assemble::gdof_idx_t> lin_idxs = dofh_Linear_FE.GlobalDofIndices(*cell);\n    nonstd::span<const lf::assemble::gdof_idx_t> quad_idxs = dofh_Quadratic_FE.GlobalDofIndices(*cell);\n    for (int i=0; i<3; i++){\n      zeta(quad_idxs[i]) = mu(lin_idxs[i]);\n      zeta(quad_idxs[i+3]) = 0.5*mu(lin_idxs[i])+0.5*mu(lin_idxs[(i+1)%3]);\n    }\n  }\n  return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace LFPPDofHandling\n", "meta": {"hexsha": "2c3df822c49bc86f65dd22cdaacdd9df6bcddded", "size": 5412, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_issues_repo_name": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_forks_repo_name": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.649122807, "max_line_length": 103, "alphanum_fraction": 0.6239837398, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.5740207735248434}}
{"text": "/*\n * @file File for Eigen helper functions\n * Eigen_Utils.hpp\n *\n *  Created on: 25.07.2018\n *      Author: tomlucas\n */\n\n#ifndef EIGEN_UTILS_HPP_\n#define EIGEN_UTILS_HPP_\n\n#include <Eigen/Geometry>\n#include <math.h>\n#include \"ZaVI_Utils.hpp\"\n#include <ceres/ceres.h>\nnamespace zavi\n::eigen_util {\n\t/**\n\t * Rotates a vector with the given quaternion\n\t * @param vector The vector to rotate\n\t * @param quat The quaternion\n\t * @return the rotatet vector\n\t */\n\tinline ::Eigen::Vector3d rotateVector(const ::Eigen::Vector3d &vector, const ::Eigen::Quaterniond &quat) {\n\t\t::Eigen::Quaterniond vec(0, 0, 0, 0);\n\t\tvec.w() = 0;\n\t\tvec.vec() = vector;\n\t\treturn (quat * vec * quat.conjugate()).vec();\n\t}\n\t/**\n\t * Euler rodriguez formula\n\t *\n\t * Calculates a rotation matrix as if roll pitch and yaw happend simultaenously\n\t * taken from C. Hertzberg 2013\n\t * @param roll the roll angle\n\t * @param pitch   the pitch angle\n\t * @param yaw  the yaw angle\n\t * @return a 3x3 rotation matrix\n\t */\n\ttemplate<typename T>\n\t::Eigen::Matrix<T, 3, 3> eulerRodriguez(const T & roll,const T & pitch,const T & yaw);\n\n\t/**\n\t * Euler rodriguez formula\n\t *\n\t * Calculates a rotation matrix as if roll pitch and yaw happend simultaenously\n\t * taken from C. Hertzberg 2013\n\t * @param vec roll pitch and yaw as vector\n\t * @return a 3x3 rotation matrix\n\t */\n\ttemplate<typename T>\n\tinline ::Eigen::Matrix<T, 3, 3> eulerRodriguez(const Eigen::Matrix<T, 3, 1> &vec) {\n\t\treturn eulerRodriguez<T>(vec(0, 0), vec(1, 0), vec(2, 0));\n\t}\n\n\t/**\n\t * Wraps an angle to -PI + PI\n\t * @param angle the angle\n\t * @return the wrapped angle\n\t */\n\ttemplate<typename T>\n\tT wrapAngle(const T & angle) {\n\t\tT temp=angle+M_PI;\n\t\ttemp = fmod(temp,2*M_PI);\n\t\tif (temp < T(0.))\n\t\ttemp += 2*M_PI;\n\t\treturn temp - M_PI;\n\t}\n\n\t/**\n\t * Wraps an angle to -PI + PI\n\t * @param angle the angle\n\t * @return the wrapped angle\n\t */\n\ttemplate<typename T,int size>\n\tceres::Jet<T,size> wrapAngle(const ceres::Jet<T,size> & angle) {\n\t\tceres::Jet<T,size> temp=angle;\n\t\ttemp.a=wrapAngle(temp.a);\n\t\treturn temp;\n\t}\n\t/**\n\t * wraps the angles to -M_PI to M_PI\n\t * @param matrix a eigen matrix or expression\n\t * @return\n\t */\n\ttemplate<typename Derived>\n\tinline ::Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1> wrapAngles(\n\t\t\tconst ::Eigen::MatrixBase<Derived> & matrix) {\n\t\t::Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, 1> temp = matrix;\n\t\tfor (int i = 0; i < matrix.RowsAtCompileTime; i++) {\n\t\t\ttemp(i) = wrapAngle(temp(i));\n\t\t}\n\t\treturn temp;\n\t}\n\t/**\n\t * retrieve the euler angles from an euler rodriguez rotation matrix\n\t * @param rotation the rotation matrix\n\t * @return euler angles as 3,1 matrix\n\t */\n\ttemplate<typename T>\n\tEigen::Matrix<T, 3, 1> inverseEulerRodriguez(const ::Eigen::Matrix<T, 3, 3> & rotation);\n\n\t/**\n\t * Generates an quaternion from euler angle\n\t *\n\t *taken from https://stackoverflow.com/questions/31589901/euler-to-quaternion-quaternion-to-euler-using-eigen\n\t *\n\t * @param roll  roll in radians\n\t * @param pitch pitch in radians\n\t * @param yaw  yaw in radians\n\t * @return\n\t */\n\tinline ::Eigen::Quaterniond eulerToQuaternion(double roll, double pitch, double yaw) {\n\t\tEigen::Quaterniond q(eulerRodriguez<double>(roll, pitch, yaw));\n\t\treturn q;\n\t}\n\n\t/**\n\t * Transfers a vector to  a quaternion\n\t * @param state the state vector\n\t * @param startindex the start index of the euler angles\n\t * @return an eigen Quaterniond\n\t *\n\t * state_dim dimension of the state\n\t */\n\ttemplate<int state_dim>\n\tinline ::Eigen::Quaterniond stateToQuaternion(Eigen::Matrix<double, state_dim, 1> & state, int startindex) {\n\t\treturn ::Eigen::Quaterniond(state(startindex + 0), state(startindex + 1), state(startindex + 2),\n\t\t\t\tstate(startindex + 3));\n\t}\n\n\t/**\n\t * Object to call a function\n\t *\n\t * implements operator() to be called like a function and return a Eigen::Vector instead of a template pointer (ceres requirement)\n\t *\n\t * Implements an implicit type erasure so every function which needs a FuncCaller will accept snx objrvz ehivh implements the function (double * time, double * result, bool expand_noise)\n\t */\n\tclass FuncCaller {\n\tprivate:\n\n\t\tstruct TypeErasure {\n\t\t\tvirtual ~TypeErasure() {}\n\t\t\tvirtual Eigen::Vector3d operator()(double time, bool expand_noise = false)const =0;\n\n\t\t};\n\t\ttemplate<typename functor>\n\t\tstruct FunctionWrapper: public TypeErasure {\n\t\t\tFunctionWrapper(const functor &function):function(function) {}\n\n\t\t\tvirtual Eigen::Vector3d operator()(double time, bool expand_noise = false) const {\n\t\t\t\tdouble result[3];\n\t\t\t\tfunction(&time, result, expand_noise);\n\t\t\t\treturn Eigen::Vector3d(result[0], result[1], result[2]);\n\t\t\t}\n\t\t\tfunctor function;\n\t\t};\n\tpublic:\n\t\t/**\n\t\t * Calls the stored functor with parameters\n\t\t * @param time time_point on wich the function es evaluated\n\t\t * @param expand_noise whether to add a noisy increment\n\t\t * @return a Eigen 3D Vector as the function result\n\t\t */\n\t\tEigen::Vector3d operator()(double time, bool expand_noise = false) const {\n\t\t\treturn (*function)(time,expand_noise);\n\t\t}\n\t\t/**\n\t\t * Create the funcCaller from an arbitrary object which implements the operator()((double * time, double * result, bool expand_noise)\n\t\t * @param func function object\n\t\t */\n\t\ttemplate<typename functor>\n\t\tFuncCaller(const functor & func) :\n\t\tfunction(new FunctionWrapper<functor>(func)) {\n\t\t}\n\t\t/**\n\t\t * Copy constructor\n\t\t * @param func another FuncCaller\n\t\t */\n\t\tFuncCaller(FuncCaller & func):\n\t\tfunction(func.function) {\n\t\t}\n\n\tprotected:\n\t\tstd::shared_ptr<TypeErasure> function;\n\t};\n\n\t/**\n\t * First order numerical derivative\n\t * @param time the time point\n\t * @param function FunctionCaller   to derive\n\t * @param itv the intervall for numeric derivation\n\t * @return first order derivate at time\n\t */\n\n\tinline Eigen::Vector3d diff1(double time,const FuncCaller & function, double itv = 1e-6) {\n\t\treturn (function(time) - function(time - itv)) / itv;\n\t}\n\t/**\n\t * Second order numerical derivative\n\t * @param time the time point\n\t * @param function  FunctionCaller   to derive\n\t * @param itv the intervall for numeric derivation\n\t * @return second order derivate at time\n\t */\n\tinline Eigen::Vector3d diff2(double time,const FuncCaller & function, double itv = 1e-6) {\n\t\treturn (diff1(time, function, itv) - diff1(time - itv, function, itv)) / itv;\n\t}\n\t/**\n\t * Calculates the euler rotation angles of a function at a given time\n\t *\n\t * taken from https://stackoverflow.com/questions/18558910/direction-vector-to-rotation-matrix\n\t *\n\t * @param time  the time point\n\t * @param function FunctionCaller   to calculate the orientation off\n\t * @param itv the intervall for derivation purposes\n\t * @param roll_function a function to determine roll, if not given roll is 0\n\t * @return a vector with the 3 euler angles representing the orientation\n\t */\n\tinline Eigen::Matrix3d orientationFromFunctor(double time,const FuncCaller & function, double itv,\n\t\t\tFuncCaller * ref_function = NULL) {\n\t\tEigen::Vector3d vector_orient = diff1(time, function, itv);\n\t\tvector_orient.normalize();\n\t\tEigen::Vector3d ref_axis =\n\t\tref_function == NULL ? Eigen::Vector3d(0, 0, 1) : Eigen::Vector3d(ref_function->operator ()(time));\n\t\tEigen::Vector3d xaxis = ref_axis.cross(vector_orient);\n\t\txaxis.normalize();\n\t\tEigen::Vector3d yaxis = vector_orient.cross(xaxis);\n\t\tyaxis.normalize();\n\t\tEigen::Matrix3d orient;\n\t\torient.col(1) = xaxis;\n\t\torient.col(2) = yaxis;\n\t\torient.col(0) = vector_orient;\n\t\tassert(abs(orient.determinant()-1)< 1e-3);\n\t\treturn orient;\n\t}\n\t/**\n\t * Wraps a rotation delta ( x,y,z) to -M_PI  + M_PI\n\t * @param delta the vector to wrap\n\t * @return a delta vector with values between -M_PI and + M_PI\n\t */\n\ttemplate<typename T>\n\tEigen::Matrix<T,3,1> wrapRotDeltaVector(const Eigen::Matrix<T,3,1> & delta) {\n\t\tT sqnorm=delta.squaredNorm();\n\t\tif(sqnorm==T(0.)) {\n\t\t\treturn delta;\n\t\t}\n\t\tT norm=sqrt(sqnorm);\n\t\tif(norm > M_PI) {\n\t\t\tT wrapped_norm=zavi::eigen_util::wrapAngle(norm);\n\t\t\treturn delta*wrapped_norm/norm;\n\t\t}\n\t\telse\n\t\treturn delta;\n\t}\n\t/**\n\t * make s skew symmetric from w so that Q'=S(w)*Q  where Q is a rotation matrix and w its change\n\t * @param w a 3 element vector\n\t * @return a skew symmetric matrix of w\n\t */\n\ttemplate<typename T>\n\tEigen::Matrix<T,3,3> makeSkewSymmetric(const Eigen::Matrix<T,3,1> & w) {\n\t\tEigen::Matrix<T,3,3> S=S.Zero();\n\t\tS(0,1)=-w(2,0);\n\t\tS(0,2)=w(1,0);\n\t\tS(1,2)=-w(0,0);\n\n\t\tS(1,0)=w(2,0);\n\t\tS(2,0)=-w(1,0);\n\t\tS(2,1)=w(0,0);\n\t\treturn S;\n\t}\n\t/**\n\t * Determine whether a line intersects a plane\n\t *\n\t * where the line is l+t*l_d\n\t *\n\t * and the plane is p+u*p_d1 +v*p_d2\n\t *\n\t * with t,u,v variables in [0,1]\n\t *\n\t * length of vectors determines the line length / plane width/height\n\t *\n\t * @param line_base line start point\n\t * @param line_dir  line direction vector\n\t * @param plane_base plane start point\n\t * @param plane_dir1  first plane direction vector\n\t * @param plane_dir2  second plane direction vector\n\t * @return\n\t */\n\ttemplate<typename T>\n\tbool lineIntersectsPlane(const Eigen::Matrix<T,3,1> &line_base,const Eigen::Matrix<T,3,1> &line_dir, const Eigen::Matrix<T,3,1> &plane_base, const Eigen::Matrix<T,3,1> &plane_dir1,const Eigen::Matrix<T,3,1> &plane_dir2 ) {\n\t\tEigen::Matrix<T,3,3> A;\n\t\tA << -line_dir,plane_dir1 , plane_dir2;\n\t\tif(A.determinant() == 0.) {\n\t\t\tLOG(WARNING)<< \"Unhandled Special case in lineIntersectsPlane. Line may be inside plane.\";\n\t\t\treturn false;\n\t\t}\n\t\tEigen::Matrix<T,3,1> tuv=A.inverse()*(line_base-plane_base);\n\t\tbool intersects=true;\n\t\tfor(unsigned int i=0; i < 3; i++) {\n\t\t\tif(tuv(i) < T(0.) or tuv(i) > T(1.))\n\t\t\tintersects=false;\n\t\t}\n\t\treturn intersects;\n\t}\n\n\t/**\n\t * For use from other functions\n\t * @param a 3d Orientation matrix\n\t * @param b 3d orientation matrix\n\t * @return b boxminus a\n\t */\n\ttemplate<typename T, typename T2>\n\tinline static auto boxMinusOrientation(const Eigen::Matrix<T, 3, 3> &a,\n\t\t\tconst Eigen::Matrix<T2, 3, 3> &b) ->Eigen::Matrix<decltype(a(0,0)*b(0,0)),3,1> {\n\t\tEigen::Matrix<decltype(a(0,0)*b(0,0)), 3, 3> product= a.inverse() * b;\n\t\treturn zavi::eigen_util::inverseEulerRodriguez<decltype(a(0,0)*b(0,0))>(product);\n\t}\n\n\t/**\n\t * For use from other functions\n\t * @param a Angle Axis vector\n\t * @param b Angle Axis vector\n\t * @return b boxminus a\n\t */\n\ttemplate<typename T, typename T2>\n\tinline static auto boxMinusEuler(const Eigen::Matrix<T, 3, 1> &a,\n\t\t\tconst Eigen::Matrix<T2, 3, 1> &b) ->Eigen::Matrix<decltype(a(0,0)*b(0,0)),3,1> {\n\t\treturn wrapAngles(b-a);\n\t}\n\n\t/**\n\t * For use from other functions\n\t * @param a Angle Axis vector\n\t * @param b Angle Axis vector\n\t * @return a boxplus b\n\t */\n\ttemplate<typename T, typename T2>\n\tinline static auto boxPlusEuler(const Eigen::Matrix<T, 3, 1> &state,\n\t\t\tconst Eigen::Matrix<T2, 3, 1> &delta) ->Eigen::Matrix<decltype(state(0,0)*delta(0,0)),3,1> {\n\t\treturn wrapAngles(state+delta);\n\t}\n\n\n\n\t/**\n\t * boxplus operator for rotations\n\t * @param state  the rotation matrix\n\t * @param delta  the rotation change axis angle\n\t * @return state boxplus delta\n\t */\n\ttemplate<typename T>\n\tinline static Eigen::Matrix<T, 3, 3> boxPlusOrientation(const Eigen::Matrix<T, 3, 3> &state,\n\t\t\tconst Eigen::Matrix<T, 3, 1> &delta) {\n\t\t//assert(abs(state.determinant() - T(1.)) < T(1e-2));\n\t\tEigen::Matrix<T, 3, 3> product = state* eigen_util::eulerRodriguez(wrapRotDeltaVector(delta));\n\t\t//assert(abs(product.determinant() - T(1.)) < T(1e-6));\n\t\treturn product;\n\n\t}\n\n\tinline static Eigen::Matrix3d normaliseRotation(const Eigen::Matrix3d & rotation) {\n\t\tEigen::Matrix3d Q= rotation.householderQr().householderQ();\n\t\tfor(int i=0; i < 3 ; i ++){\n\t\t\tif(Q(i,i)<0.){\n\t\t\t\tQ.col(i)=-(Q.col(i));\n\t\t\t}\n\t\t}\n\t\treturn Q;\n\t}\n\n\tinline double norm(const double a, const double b, const double c) {\n\t\treturn sqrt(pow(a, 2) + pow(b, 2) + pow(c, 2));\n\t}\n\n\ttemplate <typename T, int N> inline\n\tceres::Jet<T, N> norm(const ceres::Jet<T, N>& a, const ceres::Jet<T, N>& b, const ceres::Jet<T, N>& c) {\n\t\tceres::Jet<T, N> out;\n\n\t\tT const temp1 =sqrt(pow(a.a, 2) + pow(b.a, 2) + pow(c.a, 2));\n\t\tT const multiplier= 1./(temp1);\n\t\tT const temp2 = temp1==T(0.)? T(1./sqrt(3.)): multiplier*(a.a);\n\t\tT const temp3 = temp1==T(0.)? T(1./sqrt(3.)): multiplier*(b.a);\n\t\tT const temp4 = temp1==T(0.)? T(1./sqrt(3.)): multiplier*(c.a);\n\n\t\tout.a = temp1;\n\t\tout.v = temp2 * a.v + temp3 * b.v+temp4*c.v;\n\t\treturn out;\n\t}\n\n}\n//zavi::eigen_util\n\n#include \"Eigen_Utils.tpp\"\n#endif /* EIGEN_UTILS_HPP_ */\n", "meta": {"hexsha": "ab45af5790d2371c5fb376057f1560e2121e90f6", "size": 12309, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/Eigen_Utils.hpp", "max_stars_repo_name": "TomLKoller/BaVI-pose-tracking", "max_stars_repo_head_hexsha": "2475604aa499663643e342629734433ab2758171", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/Eigen_Utils.hpp", "max_issues_repo_name": "TomLKoller/BaVI-pose-tracking", "max_issues_repo_head_hexsha": "2475604aa499663643e342629734433ab2758171", "max_issues_repo_licenses": ["MIT"], "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/Eigen_Utils.hpp", "max_forks_repo_name": "TomLKoller/BaVI-pose-tracking", "max_forks_repo_head_hexsha": "2475604aa499663643e342629734433ab2758171", "max_forks_repo_licenses": ["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.0050377834, "max_line_length": 223, "alphanum_fraction": 0.6752782517, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.574020765528743}}
{"text": "// 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\nvoid testcase() {\n\n    int c, g, b, k, a; \n    std::cin >> c >> g >> b >> k >> a;\n    // Create graph, edge adder class and propery maps\n    graph G(c + g);\n    edge_adder adder(G);  \n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n    const int v_source = boost::add_vertex(G);\n\n    int sum_elephants = 0;\n    for(int i = 0; i < g; i++) {\n        int x, y, d, e;\n        std::cin >> x >> y >> d >> e;\n        sum_elephants += e;\n        adder.add_edge(x, c + i, e, d);\n        adder.add_edge(c + i, y, e, 0);\n    }\n    \n    // source\n    adder.add_edge(v_source, k, sum_elephants, 0);\n\n    int l = 0;\n    int s_flow = 0;\n    out_edge_it e, eend;\n    boost::successive_shortest_path_nonnegative_weights(G, v_source, a);\n    int cost = boost::find_flow_cost(G);\n    \n    for(boost::tie(e, eend) = boost::out_edges(boost::vertex(v_source,G), G); e != eend; ++e) {\n        s_flow += c_map[*e] - rc_map[*e];     \n    }\n\n    // this is a simple heuristic: we save the binary search\n    // if cost is not the bottleneck anyway\n    if(cost <= b) { \n        std::cout << s_flow << std::endl;\n        return;\n    }\n\n    int r = s_flow;\n    while(l <= r) {\n        int mid = (l + r) / 2;\n        // change capacity\n        const edge_desc e_s = boost::edge(v_source, k, G).first;\n        const edge_desc rev_e = r_map[e_s];\n        c_map[e_s] = mid;\n        c_map[rev_e] = 0; // reverse edge has no capacity!\n        boost::successive_shortest_path_nonnegative_weights(G, v_source, a);\n        int cost = boost::find_flow_cost(G);\n        out_edge_it e, eend;\n        if(cost <= b) { // cost is okay, i.e. go higher\n            l = mid + 1;\n        } else {\n            r = mid;\n            if(l == r) break;\n        }\n    }\n    std::cout << l - 1 << std::endl;\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": "4b0264d5ee37901f3e5838e1e6e18d8216783c98", "size": 3743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week14-potw-india/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/week14-potw-india/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/week14-potw-india/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.8333333333, "max_line_length": 114, "alphanum_fraction": 0.6072668982, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5739108106094876}}
{"text": "/**\n * @date Mon May 16 21:45:27 2011 +0200\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n * @author Andre Anjos <andre.anjos@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <algorithm>\n#include <vector>\n#include <boost/shared_array.hpp>\n\n#include <bob.math/eig.h>\n\n#include <bob.core/assert.h>\n#include <bob.core/check.h>\n#include <bob.core/array_copy.h>\n\n// Generalized eigenvalue decomposition of a real matrix\n//   (dgeev)\nextern \"C\" void dgeev_( const char *jobvl, const char *jobvr,\n  const int *N, double *A, const int *lda, double *wr, double *wi,\n  double *vl, const int *ldvl, double *vr, const int *ldvr,\n  double *work, const int *lwork, int *info);\n\n// Declaration of the external LAPACK functions\n// Eigenvalue decomposition of a real symmetric matrix (dsyevd)\n//   (Divide and conquer version which is supposed to be faster than dsyev)\nextern \"C\" void dsyevd_( const char *jobz, const char *uplo, const int *N,\n  double *A, const int *lda, double *W, double *work, const int *lwork,\n  int *iwork, const int *liwork, int *info);\n\n// Generalized eigenvalue decomposition of a real symmetric definite matrix\n//   (dsygvd)\n//   (Divide and conquer version which is supposed to be faster than dsygv)\nextern \"C\" void dsygvd_( const int *itype, const char *jobz, const char *uplo,\n  const int *N, double *A, const int *lda, double *B, const int *ldb,\n  double *W, double *work, const int *lwork, const int *iwork,\n  const int *liwork, int *info);\n\nvoid bob::math::eig(const blitz::Array<double,2>& A,\n  blitz::Array<std::complex<double>,2>& V,\n  blitz::Array<std::complex<double>,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n  const blitz::TinyVector<int,1> shape1(N);\n  const blitz::TinyVector<int,2> shape2(N,N);\n\n  // Check\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(V);\n  bob::core::array::assertZeroBase(D);\n\n  bob::core::array::assertSameShape(A,shape2);\n  bob::core::array::assertSameShape(V,shape2);\n  bob::core::array::assertSameShape(D,shape1);\n\n  bob::math::eig_(A, V, D);\n}\n\nvoid bob::math::eig_(const blitz::Array<double,2>& A,\n  blitz::Array<std::complex<double>,2>& V,\n  blitz::Array<std::complex<double>,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n\n  // Prepares to call LAPACK function\n  // Initialises LAPACK variables\n  const char jobvl = 'N'; // Do NOT compute left eigen-vectors\n  const char jobvr = 'V'; // Compute right eigen-vectors\n  int info = 0;\n  const int lda = N;\n  const int ldvr = N;\n  double VL = 0; // notice we don't compute the left eigen-values\n  const int ldvl = 1;\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_lapack = bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0));\n\n  // temporary arrays to receive LAPACK's eigen-values and eigen-vectors\n  blitz::Array<double,1> WR(D.shape()); //real part\n  blitz::Array<double,1> WI(D.shape()); //imaginary part\n  blitz::Array<double,2> VR(A.shape()); //right eigen-vectors\n\n  // Calls the LAPACK function\n  // A/ Queries the optimal size of the working arrays\n  const int lwork_query = -1;\n  double work_query;\n  dgeev_( &jobvl, &jobvr, &N, A_lapack.data(), &lda, WR.data(), WI.data(),\n      &VL, &ldvl, VR.data(), &ldvr, &work_query, &lwork_query, &info);\n\n  // B/ Computes the eigenvalue decomposition\n  const int lwork = static_cast<int>(work_query);\n  boost::shared_array<double> work(new double[lwork]);\n  dgeev_( &jobvl, &jobvr, &N, A_lapack.data(), &lda, WR.data(), WI.data(),\n      &VL, &ldvl, VR.data(), &ldvr, work.get(), &lwork, &info);\n\n  // Checks info variable\n  if (info != 0) {\n    throw std::runtime_error(\"the QR algorithm failed to compute all the eigenvalues, and no eigenvectors have been computed.\");\n  }\n\n  // Copy results back from WR, WI => D\n  blitz::real(D) = WR;\n  blitz::imag(D) = WI;\n\n  // Copy results back from VR => V, with two rules:\n  // 1) If the j-th eigenvalue is real, then v(j) = VR(:,j), the j-th column of\n  //    VR.\n  // 2) If the j-th and (j+1)-st eigenvalues form a complex conjugate pair,\n  // then v(j) = VR(:,j) + i*VR(:,j+1) and v(j+1) = VR(:,j) - i*VR(:,j+1).\n  blitz::Range a = blitz::Range::all();\n  int i=0;\n  while (i<N) {\n    if (std::imag(D(i)) == 0.) { //real eigen-value, consume 1\n      blitz::real(V(a,i)) = VR(i,a);\n      blitz::imag(V(a,i)) = 0.;\n      ++i;\n    }\n    else { //complex eigen-value, consume 2\n      blitz::real(V(a,i)) = VR(i,a);\n      blitz::imag(V(a,i)) = VR(i+1,a);\n      blitz::real(V(a,i+1)) = VR(i,a);\n      blitz::imag(V(a,i+1)) = -VR(i+1,a);\n      i += 2;\n    }\n  }\n}\n\nvoid bob::math::eigSym(const blitz::Array<double,2>& A,\n  blitz::Array<double,2>& V, blitz::Array<double,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n  const blitz::TinyVector<int,1> shape1(N);\n  const blitz::TinyVector<int,2> shape2(N,N);\n\n  // Check\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(V);\n  bob::core::array::assertZeroBase(D);\n\n  bob::core::array::assertSameShape(A,shape2);\n  bob::core::array::assertSameShape(V,shape2);\n  bob::core::array::assertSameShape(D,shape1);\n\n  bob::math::eigSym_(A, V, D);\n}\n\nvoid bob::math::eigSym_(const blitz::Array<double,2>& A,\n  blitz::Array<double,2>& V, blitz::Array<double,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n\n  // Prepares to call LAPACK function\n  // Initialises LAPACK variables\n  const char jobz = 'V'; // Get both the eigenvalues and the eigenvectors\n  const char uplo = 'U';\n  int info = 0;\n  const int lda = N;\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack;\n  // Tries to use V directly\n  blitz::Array<double,2> Vt = V.transpose(1,0);\n  const bool V_direct_use = bob::core::array::isCZeroBaseContiguous(Vt);\n  if (V_direct_use)\n  {\n    A_blitz_lapack.reference(Vt);\n    // Ugly fix for non-const transpose\n    A_blitz_lapack = const_cast<blitz::Array<double,2>&>(A).transpose(1,0);\n  }\n  else\n    // Ugly fix for non-const transpose\n    A_blitz_lapack.reference(\n      bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double *A_lapack = A_blitz_lapack.data();\n  blitz::Array<double,1> D_blitz_lapack;\n  const bool D_direct_use = bob::core::array::isCZeroBaseContiguous(D);\n  if (D_direct_use)\n    D_blitz_lapack.reference(D);\n  else\n    D_blitz_lapack.resize(D.shape());\n  double *D_lapack = D_blitz_lapack.data();\n\n  // Calls the LAPACK function\n  // A/ Queries the optimal size of the working arrays\n  const int lwork_query = -1;\n  double work_query;\n  const int liwork_query = -1;\n  int iwork_query;\n  dsyevd_( &jobz, &uplo, &N, A_lapack, &lda, D_lapack, &work_query,\n    &lwork_query, &iwork_query, &liwork_query, &info);\n  // B/ Computes the eigenvalue decomposition\n  const int lwork = static_cast<int>(work_query);\n  boost::shared_array<double> work(new double[lwork]);\n  const int liwork = static_cast<int>(iwork_query);\n  boost::shared_array<int> iwork(new int[liwork]);\n  dsyevd_( &jobz, &uplo, &N, A_lapack, &lda, D_lapack, work.get(), &lwork,\n    iwork.get(), &liwork, &info);\n\n  // Checks info variable\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK function 'dsyevd' returned a non-zero value.\");\n\n  // Copy singular vectors back to V if required\n  if (!V_direct_use)\n    Vt = A_blitz_lapack;\n\n  // Copy result back to sigma if required\n  if (!D_direct_use)\n    D = D_blitz_lapack;\n}\n\n\nvoid bob::math::eigSym(const blitz::Array<double,2>& A, const blitz::Array<double,2>& B,\n  blitz::Array<double,2>& V, blitz::Array<double,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n  const blitz::TinyVector<int,1> shape1(N);\n  const blitz::TinyVector<int,2> shape2(N,N);\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(B);\n  bob::core::array::assertZeroBase(V);\n  bob::core::array::assertZeroBase(D);\n\n  bob::core::array::assertSameShape(A,shape2);\n  bob::core::array::assertSameShape(B,shape2);\n  bob::core::array::assertSameShape(V,shape2);\n  bob::core::array::assertSameShape(D,shape1);\n\n  bob::math::eigSym_(A, B, V, D);\n}\n\nvoid bob::math::eigSym_(const blitz::Array<double,2>& A, const blitz::Array<double,2>& B,\n  blitz::Array<double,2>& V, blitz::Array<double,1>& D)\n{\n  // Size variable\n  const int N = A.extent(0);\n\n  // Prepares to call LAPACK function\n  // Initialises LAPACK variables\n  const int itype = 1;\n  const char jobz = 'V'; // Get both the eigenvalues and the eigenvectors\n  const char uplo = 'U';\n  int info = 0;\n  const int lda = N;\n  const int ldb = N;\n\n  // Initialises LAPACK arrays\n  blitz::Array<double,2> A_blitz_lapack;\n  // Tries to use V directly\n  blitz::Array<double,2> Vt = V.transpose(1,0);\n  const bool V_direct_use = bob::core::array::isCZeroBaseContiguous(Vt);\n  if (V_direct_use)\n  {\n    A_blitz_lapack.reference(Vt);\n    // Ugly fix for non-const transpose\n    A_blitz_lapack = const_cast<blitz::Array<double,2>&>(A).transpose(1,0);\n  }\n  else\n    // Ugly fix for non-const transpose\n    A_blitz_lapack.reference(\n      bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(A).transpose(1,0)));\n  double *A_lapack = A_blitz_lapack.data();\n  // Ugly fix for non-const transpose\n  blitz::Array<double,2> B_blitz_lapack(\n    bob::core::array::ccopy(const_cast<blitz::Array<double,2>&>(B).transpose(1,0)));\n  double *B_lapack = B_blitz_lapack.data();\n  blitz::Array<double,1> D_blitz_lapack;\n  const bool D_direct_use = bob::core::array::isCZeroBaseContiguous(D);\n  if (D_direct_use)\n    D_blitz_lapack.reference(D);\n  else\n    D_blitz_lapack.resize(D.shape());\n  double *D_lapack = D_blitz_lapack.data();\n\n  // Calls the LAPACK function\n  // A/ Queries the optimal size of the working arrays\n  const int lwork_query = -1;\n  double work_query;\n  const int liwork_query = -1;\n  int iwork_query;\n  dsygvd_( &itype, &jobz, &uplo, &N, A_lapack, &lda, B_lapack, &ldb, D_lapack,\n    &work_query, &lwork_query, &iwork_query, &liwork_query, &info);\n  // B/ Computes the generalized eigenvalue decomposition\n  const int lwork = static_cast<int>(work_query);\n  boost::shared_array<double> work(new double[lwork]);\n  const int liwork = static_cast<int>(iwork_query);\n  boost::shared_array<int> iwork(new int[liwork]);\n  dsygvd_( &itype, &jobz, &uplo, &N, A_lapack, &lda, B_lapack, &ldb, D_lapack,\n    work.get(), &lwork, iwork.get(), &liwork, &info);\n\n  // Checks info variable\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK function 'dsygvd' returned a non-zero value. This might be caused by a non-positive definite B matrix.\");\n\n  // Copy singular vectors back to V if required\n  if (!V_direct_use)\n    V = A_blitz_lapack.transpose(1,0);\n\n  // Copy result back to sigma if required\n  if (!D_direct_use)\n    D = D_blitz_lapack;\n}\n", "meta": {"hexsha": "2adae9941c1f7e9c50ad6a3484d0c9d42ec6107c", "size": 10725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/eig.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/eig.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/eig.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": 34.4855305466, "max_line_length": 146, "alphanum_fraction": 0.6721678322, "num_tokens": 3405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5739107990446302}}
{"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 aak_reduction.hpp\n///\n/// Sparse approximation of exponential sum using modified Prony method.\n///\n#ifndef MXPFIT_MODIFIED_PRONY_REDUCTION_HPP\n#define MXPFIT_MODIFIED_PRONY_REDUCTION_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\n#include <mxpfit/exponential_sum.hpp>\n\nnamespace mxpfit\n{\n///\n/// ### ModifiedPronyReduction\n///\n/// \\brief Find a truncated exponential sum function with smaller number of\n///        terms by the modified balanced truncation method.\n///\n/// \\tparam T  Scalar type of exponential sum function.\n///\n/// Let us consider an exponential sum function, in which the weights and\n/// exponetns are strictly positive, i.e.,\n///\n/// \\f[\n///   f(t)=\\sum_{j=1}^{n} w_{j}^{} e^{-a_{j}^{} t}, \\quad\n///   (a_{j} > 0, \\, w_{j} > 0).\n/// \\f]\n///\n/// This class calculates truncated exponential \\f$\\hat{f}(t)\\f$ sum such that\n///\n/// \\f[\n///   \\hat{f}(t)=\\sum_{j=1}^{k} \\hat{w}_{j}^{}e^{-\\hat{a}_{j}^{} t}, \\quad\n///   \\left| f(t)-\\hat{f}(t) \\right| < \\epsilon, \\, (k < n)\n/// \\f]\n///\n/// where \\f$\\epsilon > 0\\f$ is the prescribed accuracy. The weights\n/// \\f$\\hat{w}_{j}\\f$ and exponents \\f$\\hat{w}_{j}\\f$ in the trucated sum are\n/// all positive.\n///\n/// The modified Prony method proposed by Beylkin and Monzon are adopted. We\n/// refer to the literature listed below for the detial about the method.\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 ModifiedPronyReduction\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 VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using ResultType = ExponentialSum<Scalar, Scalar>;\n\n    ///\n    /// Compute truncated exponential sum \\f$ \\hat{f}(t) \\f$\n    ///\n    /// \\tparam DerivedF type of exponential sum inheriting ExponentialSumBase\n    ///\n    /// \\param[in] orig original exponential sum function, \\f$ f(t) \\f$\n    /// \\param[in] n_target Index smaller than `orig.size()`, which denotes\n    ///            number of terms to be target for reduction.\n    /// \\param[in] threshold  prescribed accuracy \\f$0 < \\epsilon \\ll 1\\f$\n    ///\n    /// \\pre The weights \\f$w_{j}\\f$ and exponents \\f${a_{j}}\\f$ are strictly\n    /// positive and \\f$a_{j}\\f$ must be sorted in ascending order.\n    ///\n    /// \\remark The exponents \\f$\\hat{a}_{j}\\f$ of truncated sum are obtained as\n    /// a root of Prony polynomials, which might not be real and positive.\n    /// Internaly, obtaind roots of polynomial is casted to be a real number,\n    /// which might introduce significant errors in the approximation.\n    ///\n    /// \\return An instance of ExponentialSum represents \\f$\\hat{f}(t)\\f$\n    ///\n    template <typename DerivedF>\n    ResultType compute(const ExponentialSumBase<DerivedF>& orig, Index n_target,\n                       RealScalar threshold);\n};\n\ntemplate <typename T>\ntemplate <typename DerivedF>\ntypename ModifiedPronyReduction<T>::ResultType\nModifiedPronyReduction<T>::compute(const ExponentialSumBase<DerivedF>& orig,\n                                   Index n_target, RealScalar eps)\n{\n    using Eigen::numext::abs;\n    using Eigen::numext::real;\n    assert(Index(0) <= n_target && n_target <= orig.size());\n    assert(eps > RealScalar());\n\n    if (n_target == Index())\n    {\n        ResultType ret(orig);\n        return ret; // quick return\n    }\n\n    //\n    // Compute a sequence\n    //\n    // \\f[\n    //   h_{j} = \\sum_{k=1}^{n} w_{k} a_{k}^{j}\n    // \\f]\n    //\n    VectorType h(2 * n_target);\n    const auto w_target = orig.weights().head(n_target);\n    const auto a_target = orig.exponents().head(n_target);\n    VectorType a_pow(a_target);\n\n    h(0) = w_target.sum();\n    h(1) = -(w_target * a_pow.array()).sum();\n\n    Index m        = 1;\n    auto factorial = RealScalar(1);\n    for (; m < n_target; ++m)\n    {\n        a_pow.array() *= a_target;\n        h(2 * m + 0) = (w_target * a_pow.array()).sum();\n        a_pow.array() *= a_target;\n        h(2 * m + 1) = -(w_target * a_pow.array()).sum();\n        factorial *= RealScalar(2 * m * (2 * m + 1));\n\n        if (abs(h(2 * m + 1)) / factorial < eps)\n        {\n            // Taylor expansion converges with the tolerance eps.\n            ++m;\n            break;\n        }\n    }\n\n    if (m == n_target)\n    {\n        // no further reduction\n        ResultType ret(orig);\n        return ret;\n    }\n\n    //\n    // Construct a Hankel matrix from the sequence h, and solve the linear\n    // equation, H q = b, with b = -h(m:2m-1).\n    //\n    MatrixType H(m, m);\n    for (Index i = 0; i < m; ++i)\n    {\n        H.col(i) = h.segment(i, m);\n    }\n    VectorType q(H.colPivHouseholderQr().solve(-h.segment(m, m)));\n\n    //\n    // Find the roots of the Prony polynomial,\n    //\n    // q(z) = \\sum_{k=0}^{m-1} q_k z^{k}.\n    //\n    // The roots of q(z) can be obtained as the eigenvalues of the companion\n    // matrix,\n    //\n    //     (0  0  ...  0 -p[0]  )\n    //     (1  0  ...  0 -p[1]  )\n    // C = (0  1  ...  0 -p[2]  )\n    //     (.. .. ...  .. ..    )\n    //     (0  0  ...  1 -p[m-1])\n    //\n\n    MatrixType companion(MatrixType::Zero(m, m));\n    companion.diagonal(-1).setOnes();\n    companion.col(m - 1) = -q;\n    VectorType gamma(companion.eigenvalues().real());\n\n    // --- Update exponents & weights\n    const Index keep = orig.size() - n_target;\n    ResultType ret(keep + m);\n    ret.exponents().head(m)    = -gamma;\n    ret.exponents().tail(keep) = orig.exponents().tail(keep);\n\n    //\n    // Construct Vandermonde matrix from Prony roots\n    //\n    MatrixType V(2 * m, m);\n    for (Index i = 0; i < m; ++i)\n    {\n        const RealScalar z = gamma(i);\n        V(0, i)            = RealScalar(1);\n        for (Index j = 1; j < V.rows(); ++j)\n        {\n            V(j, i) = V(j - 1, i) * z; // z[i]**j\n        }\n    }\n\n    //\n    // Solve overdetermined Vandermonde system,\n    //\n    // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)\n    //\n    // by the least square method.\n    //\n    ret.weights().head(m)    = V.colPivHouseholderQr().solve(h.head(2 * m));\n    ret.weights().tail(keep) = orig.weights().tail(keep);\n\n    return ret;\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_MODIFIED_PRONY_REDUCTION_HPP */\n", "meta": {"hexsha": "b9ca44d82f6fd13207ee99b1a6cb5351da0d8508", "size": 7784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/modified_prony_reduction.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/modified_prony_reduction.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/modified_prony_reduction.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": 32.2987551867, "max_line_length": 80, "alphanum_fraction": 0.6017471737, "num_tokens": 2224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.5738407536478045}}
{"text": "#pragma once\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\n#define D2R(x) (x * (M_PI/180))\n#define R2D(x) (x * (180/M_PI))\n\nclass Geodesy{\npublic:\n\t/**WGS84 ellipsoid semi-major axis*/\n\tstatic constexpr double a = 6378137.0;\n\n\t/**WGS84 ellipsoid first eccentricity squared*/\n\tstatic constexpr double e2 = 0.081819190842622 * 0.081819190842622;\n\n\n\tstatic void getPositionECEF(Eigen::Vector3d & positionECEF, double longitude, double latitude,double ellipsoidalHeight) {\n\t\tdouble clat = cos(latitude);\n\t\tdouble slat = sin(latitude);\n\t\tdouble clon = cos(longitude);\n\t\tdouble slon = sin(longitude);\n\n\t\tdouble N = a / (sqrt(1 - e2 * slat * slat));\n\t\tdouble xTRF = (N + ellipsoidalHeight) * clat * clon;\n\t\tdouble yTRF = (N + ellipsoidalHeight) * clat * slon;\n\t\tdouble zTRF = (N * (1 - e2) + ellipsoidalHeight) * slat;\n\n\t\tpositionECEF << xTRF, yTRF, zTRF;\n\t}\n};\n", "meta": {"hexsha": "932852f5669008b55db2b17fc4cf7fa1c274fb77", "size": 852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Geodesy.hpp", "max_stars_repo_name": "glabmoris/LidarToolkit", "max_stars_repo_head_hexsha": "c5cc2c6b5aabbc2c646f7920fef6d85ce45e2114", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Geodesy.hpp", "max_issues_repo_name": "glabmoris/LidarToolkit", "max_issues_repo_head_hexsha": "c5cc2c6b5aabbc2c646f7920fef6d85ce45e2114", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Geodesy.hpp", "max_forks_repo_name": "glabmoris/LidarToolkit", "max_forks_repo_head_hexsha": "c5cc2c6b5aabbc2c646f7920fef6d85ce45e2114", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-03T16:55:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T19:01:28.000Z", "avg_line_length": 25.8181818182, "max_line_length": 122, "alphanum_fraction": 0.6866197183, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.573837831740166}}
{"text": "///\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/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// BGL graph definitions\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\n// Main\nvoid testcase() {\n  // build graph\n  int n;\n  std::cin >> n;\n  graph G(n);\n  edge_adder adder(G);\n  // auto rc_map = boost::get(boost::edge_residual_capacity, G);\n  const int v_source = boost::add_vertex(G);\n  const int v_sink = boost::add_vertex(G);\n  \n  \n  std::vector<int> a_and_c(2*n);\n  for(int i = 0; i < n; i++) {\n    int a, c;\n    std::cin >> a >> c;\n    a_and_c[2 * i] = a;\n    a_and_c[2 * i + 1] = c;\n    // adder.add_edge(v_source, i, a, c);\n  }\n  \n  int sum_students = 0;\n  int max_price = 0;\n  std::vector<int> s_and_p(2*n);\n  for(int i = 0; i < n; i++) {\n    int s, p;\n    std::cin >> s >> p;\n    sum_students += s;\n    s_and_p[2 * i] = s;\n    s_and_p[2 * i + 1] = p;\n    max_price = std::max(max_price, p);\n  }\n  \n  for(int i = 0; i < n; i++) {\n    int a = a_and_c[2 * i];\n    int c = a_and_c[2 * i + 1];\n    adder.add_edge(v_source, i, a, c);\n  }\n  \n  for(int i = 0; i < n; i++) {\n    int s = s_and_p[2 * i];\n    int p = s_and_p[2 * i + 1];\n    adder.add_edge(i, v_sink, s, - p + max_price);\n  }\n  \n  for(int i = 0; i < n - 1; i++) {\n    int v, e;\n    std::cin >> v >> e;\n    adder.add_edge(i, i + 1, v, e);\n  }\n\n  \n  // int flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  // boost::cycle_canceling(G);\n  // int cost = boost::find_flow_cost(G);\n  \n  \n  boost::successive_shortest_path_nonnegative_weights(G, v_source, v_sink);\n  int cost = boost::find_flow_cost(G);\n  // Iterate over all edges leaving the source to sum up the flow values.\n  int flow = 0;\n  out_edge_it e, eend;\n  auto c_map = boost::get(boost::edge_capacity, G);\n  auto rc_map = boost::get(boost::edge_residual_capacity, G);  \n  for(boost::tie(e, eend) = boost::out_edges(boost::vertex(v_source,G), G); e != eend; ++e) {\n      // std::cout << \"edge from \" << boost::source(*e, G) << \" to \" << boost::target(*e, G) \n      //     << \" with capacity \" << c_map[*e] << \" and residual capacity \" << rc_map[*e] << \"\\n\";\n      flow += c_map[*e] - rc_map[*e];     \n  }\n  if(flow == sum_students) {\n    std::cout << \"possible \";\n  } else {\n    std::cout << \"impossible \";\n  }\n  std::cerr << flow * max_price << std::endl;\n  std::cout << flow << \" \" << -(cost - (flow * max_price)) << \"\\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": "abc8b9881d689dab232f08bf5313de166278120c", "size": 5260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week09-canteen/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-canteen/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-canteen/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": 33.5031847134, "max_line_length": 114, "alphanum_fraction": 0.6180608365, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5737971719247246}}
{"text": "#include <iostream>\n#include <array>\n#include <string>\n#include <cstring>\n#include <fstream>\n#include <exception>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <vector>\n#include \"port_authority.hpp\"\n\nusing namespace std;\nusing namespace pauth;\n\n#include <boost/program_options/options_description.hpp>\n#include <boost/program_options/parsers.hpp>\n#include <boost/program_options/variables_map.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/token_functions.hpp>\n\nusing namespace boost;\nusing namespace boost::program_options;\n\n#include \"mpi.h\"\n\nint main(int argc, char* argv[]) {\n\n  int taskid, numtasks;\n  MPI_Init(nullptr, nullptr);\n  MPI_Comm_size(MPI_COMM_WORLD, &numtasks);\n  MPI_Comm_rank(MPI_COMM_WORLD, &taskid);\n\n  options_description desc(\"\\nMetropolis simulation of a harmonic oscillator.\"\n                           \"\\n\\nAllowed arguments\");\n\n  double delta_max, x0, dx, sk;\n  unsigned long nsteps;\n\n  desc.add_options()\n    (\"help,h\", \"Produce this help message.\")\n    (\"x0,x\", value<double>(&x0)->default_value(0.0), \"Initial position.\")\n    (\"spring-const,k\", value<double>(&sk)->default_value(1.0), \"Spring constant.\")\n    (\"beta,b\", value<double>()->default_value(1.0), \"1 / kT\")\n    (\"delta,d\", value<double>(&delta_max)->default_value(2.0), \"Maximum step size.\")\n    (\"num-steps,n\", value<size_t>(&nsteps)->default_value(100000), \"Number of steps.\")\n    (\"dx,e\", value<double>(&dx)->default_value(0.1), \"Threshold size for \"\n      \"approximating <dirac_delta(x - x0)> which is used to approximate Z.\")\n    (\"plot-histogram,p\", \"Plot histogram.\");\n\n  variables_map vm;\n  try {\n    store(command_line_parser(argc, argv).options(desc).run(), vm);\n    notify(vm);\n  } catch(std::exception &e) {\n    cout << endl << e.what() << endl;\n    cout << desc << endl;\n  }\n\n  if (vm.count(\"help\")) {\n    if(taskid == 0) {\n      cout << \"--help specified\" << endl;\n      cout << desc << endl;\n    }\n    MPI_Finalize();\n    return EXIT_SUCCESS;\n  }\n\n  const double T = 1.0;\n  const double kB = 1.0 / vm[\"beta\"].as<double>();\n\n  const molecular_id id = molecular_id::Test1;\n  const size_t N = 1;\n  const size_t D = 1;\n  const double L = 1.0;\n  const metric m = euclidean;\n  const bc boundary = no_bc;\n  const_k_spring_potential pot(sk);\n  vector<double> xs;\n  \n  metropolis sim(id, N, D, L, continuous_trial_move(delta_max), \n                 &pot, T, kB, m, boundary, metropolis_acc, \n                 hardware_entropy_seed_gen, true);\n  sim.positions()(0, 0) = x0;\n  const double u0 = accessors::U(sim);\n\n  if (vm.count(\"plot-histogram\")) {\n    sim.add_callback([&](const metropolis &sim) -> void {\n      xs.push_back(sim.positions()(0, 0));\n    });\n  }\n\n  metropolis_suite msuite(sim, 0, 1, info_lvl_flag::VERBOSE);\n\n  msuite.add_variable_to_average(\"x\", [](const metropolis &sim) {\n    return sim.positions()(0, 0);\n  });\n  msuite.add_variable_to_average(\"x^2\", [](const metropolis &sim) {\n    return sim.positions()(0, 0) * sim.positions()(0, 0);\n  });\n  msuite.add_variable_to_average(\"U\", accessors::U);\n  msuite.add_variable_to_average(\"delta(x - x0)\", [=](const metropolis &sim) {\n    const double x = sim.positions()(0, 0);\n    return (x < x0 + dx && x > x0 - dx) ? 1 : 0;\n  });\n\n  msuite.simulate(nsteps);\n\n  if(taskid == 0) {\n    auto averages = msuite.averages();\n\n    const double exp_x = averages[\"x\"];\n    const double exp_xsq = averages[\"x^2\"];\n    cout << \"<x>      =     \" << exp_x << '\\n';\n    cout << \"<x^2>    =     \" << exp_xsq << '\\n';\n    cout << \"kT/k     =     \" << kB * T / sk << '\\n';\n    cout << \"Delta x  =     \" << sqrt(exp_xsq - exp_x*exp_x) << '\\n';\n    cout << \"<E>      =     \" << averages[\"U\"] << '\\n';\n    cout << \"kT / 2   =     \" << kB * T / 2.0 << '\\n';\n    cout << \"Z        =     \" << (2.0 * dx * exp(-u0 / (kB * T)) \n                                  / averages[\"delta(x - x0)\"]) << '\\n';\n    cout << \"Z (an)   =     \" << sqrt(2.0 * M_PI * kB * T / sk) << '\\n';\n\n    if (vm.count(\"plot-histogram\")) {\n      throw \"Not yet implemented.\";\n    }\n  }\n\n  MPI_Finalize();\n\n  return 0;\n}\n", "meta": {"hexsha": "82c5fcd40c1cd3cda12bdffcd15ed4dd3520ebbc", "size": 4037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/harmonic/harmonic1d.cpp", "max_stars_repo_name": "grasingerm/port-authority", "max_stars_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_stars_repo_licenses": ["MIT"], "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/harmonic/harmonic1d.cpp", "max_issues_repo_name": "grasingerm/port-authority", "max_issues_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_issues_repo_licenses": ["MIT"], "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/harmonic/harmonic1d.cpp", "max_forks_repo_name": "grasingerm/port-authority", "max_forks_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_forks_repo_licenses": ["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.5833333333, "max_line_length": 86, "alphanum_fraction": 0.5969779539, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5737911525376087}}
{"text": "/*\nThis is SCRIMP++, as published by Zhua, Yeh, Zimmerman et al. at https://sites.google.com/site/scrimpplusplus/\nIt is provided as a baseline for our work and republished with kind permission of Prof. Eamonn Keogh\nAll rights belong the original authors and they shall be asked for licensing, if required.\nFew modifications to the code were made to adapt it in our framework\n\nDetails of the SCRIMP++ algorithm can be found at:\n(author information ommited for ICDM review),\n\"SCRIMP++: Motif Discovery at Interactive Speeds\", submitted to ICDM 2018.\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <fftw3.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <timing.h>\n#include <logging.hpp>\n\n#include <ScrimpppOrig.hpp>\n#include <boost/filesystem.hpp>\n\nusing namespace matrix_profile;\n\nstatic FactoryRegistration<ScrimpppOrig> s_origRegistration(\"scrimppp_orig\");\nstatic const int notification_interval_iter = 10000;\n\nvoid ScrimpppOrig::initialize(const Scrimppp_params &params) {\n\n}\n\nvoid ScrimpppOrig::compute_matrix_profile(const Scrimppp_params& params)\n{\n\t// start timer\n\t//time_t tstart, tend;\n\t//tstart = time(0);\n\tTimepoint tstart, tend;\n\tTimespan time_elapsed;\n\n\n\t// read time series and subsequence length (windowSize).\n\tstd::fstream timeSeriesFile(params.time_series_filename, std::ios_base::in);\n\n\tint windowSize = params.query_window_len;\n\tint stepSize = floor(params.prescrimp_stride*windowSize);\n\n\tconst std::string preoutfilename = params.output_filename + \"_prescrimp\";\n\n\tif (!timeSeriesFile.is_open())\n\t{\n\t\tthrow std::runtime_error(\"Could not open input file\");\n\t}\n\n\tstd::vector<double> A;\n\tdouble tempval;\n\tint timeSeriesLength = 0;\n\twhile (timeSeriesFile >> tempval)\n\t{\n\t\tA.push_back(tempval);\n\t\ttimeSeriesLength++;\n\t}\n\tEXEC_INFO( \"loaded time series of length \" << timeSeriesLength );\n\n\tif (timeSeriesLength < windowSize) {\n\t\tthrow std::runtime_error(\"ERROR: Time series is shorter than the window length, can not proceed\");\n\t}\n\n\ttimeSeriesFile.close();\n\n\t// set exclusion zone\n\tint exclusionZone = windowSize / 4;\n\n\t// set Matrix Profile Length\n\tint ProfileLength = timeSeriesLength - windowSize + 1;\n\n\t// preprocess, statistics, get the mean and standard deviation of every subsequence in the time series\n\tdouble* ACumSum = new double[timeSeriesLength];\n\tACumSum[0] = A[0];\n\tfor (int i = 1; i < timeSeriesLength; i++)\n\t\tACumSum[i] = A[i] + ACumSum[i - 1];\n\tdouble* ASqCumSum = new double[timeSeriesLength];\n\tASqCumSum[0] = A[0] * A[0];\n\tfor (int i = 1; i < timeSeriesLength; i++)\n\t\tASqCumSum[i] = A[i] * A[i] + ASqCumSum[i - 1];\n\tdouble* ASum = new double[ProfileLength];\n\tASum[0] = ACumSum[windowSize - 1];\n\tfor (int i = 0; i < timeSeriesLength - windowSize; i++)\n\t\tASum[i + 1] = ACumSum[windowSize + i] - ACumSum[i];\n\tdouble* ASumSq = new double[ProfileLength];\n\tASumSq[0] = ASqCumSum[windowSize - 1];\n\tfor (int i = 0; i < timeSeriesLength - windowSize; i++)\n\t\tASumSq[i + 1] = ASqCumSum[windowSize + i] - ASqCumSum[i];\n\tdouble* AMean = new double[ProfileLength];\n\tfor (int i = 0; i < ProfileLength; i++)\n\t\tAMean[i] = ASum[i] / windowSize;\n\tdouble* ASigmaSq = new double[ProfileLength];\n\tfor (int i = 0; i < ProfileLength; i++)\n\t\tASigmaSq[i] = ASumSq[i] / windowSize - AMean[i] * AMean[i];\n\tdouble* ASigma = new double[ProfileLength];\n\tfor (int i = 0; i < ProfileLength; i++)\n\t\tASigma[i] = sqrt(ASigmaSq[i]);\n\tdelete [] ACumSum;\n\tdelete [] ASqCumSum;\n\tdelete [] ASum;\n\tdelete [] ASumSq;\n\tdelete [] ASigmaSq;\n\n\t//Initialize Matrix Profile and Matrix Profile Index\n\tdouble* profile = new double[ProfileLength];\n\tint* profileIndex = new int[ProfileLength];\n\tfor (int i=0; i<ProfileLength; i++)\n\t{\n\t\tprofile[i]=std::numeric_limits<double>::infinity();\n\t\tprofileIndex[i]=0;\n\t}\n\ttstart = get_cur_time();\n\n\t//int fftsize = pow(2,ceil(log2(timeSeriesLength)));\n\tint fftsize = timeSeriesLength; //fftsize must be at least 2*windowSize\n\tfftsize = fftsize > 2 * windowSize ? fftsize : 2 * windowSize;\n\tEXEC_TRACE ( \"length of fft input: \" << fftsize );\n\n\n\t/*******************************PreSCRIMP***************************************/\n\n\tfftw_plan plan;\n\tfftw_complex* ATime = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\tfftw_complex* AFreq = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\n\tfor (int i = 0; i < fftsize; i++)\n\t{\n\t\tATime[i][1] = 0;\n\t\tif (i < timeSeriesLength)\n\t\t\tATime[i][0] = A[i];\n\t\telse\n\t\t\tATime[i][0] = 0;\n\t}\n\n\tplan = fftw_plan_dft_1d(fftsize, ATime, AFreq, FFTW_FORWARD, FFTW_ESTIMATE);\n\tfftw_execute(plan);\n\tfftw_free(ATime);\n\n\tfftw_complex* queryTime = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\tfftw_complex* queryFreq = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\tfftw_complex* AQueryTime = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\tfftw_complex* AQueryFreq = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * fftsize);\n\n\t//Sample subsequences with a fixed stepSize, then random shuffle their computation order\n\tstd::vector<int> idx;\n\tfor (int i = 0; i < timeSeriesLength - windowSize + 1; i += stepSize)\n\t\tidx.push_back(i);\n\tstd::random_shuffle(idx.begin(), idx.end());\n\n\tdouble* query = new double[windowSize];\n\n\tfor (int idx_i = 0; idx_i < idx.size(); idx_i++)\n\t{\n\t\tint i = idx[idx_i];\n\t\tfor (int j = 0; j < windowSize; j++)\n\t\t{\n\t\t\tquery[j] = A[i + j];\n\t\t}\n\t\tdouble queryMean = AMean[i];\n\t\tdouble queryStd = ASigma[i];\n\n\t\tfor (int j = 0; j < fftsize; j++)\n\t\t{\n\t\t\tqueryTime[j][1] = 0;\n\n\t\t\tif (j < windowSize)\n\t\t\t\tqueryTime[j][0] = query[windowSize - j - 1];\n\t\t\telse\n\t\t\t\tqueryTime[j][0] = 0;\n\t\t}\n\n\t\tplan = fftw_plan_dft_1d(fftsize, queryTime, queryFreq, FFTW_FORWARD, FFTW_ESTIMATE);\n\t\tfftw_execute(plan);\n\n\t\tfor (int j = 0; j < fftsize; j++)\n\t\t{\n\t\t\tAQueryFreq[j][0] = AFreq[j][0] * queryFreq[j][0] - AFreq[j][1] * queryFreq[j][1];\n\t\t\tAQueryFreq[j][1] = AFreq[j][1] * queryFreq[j][0] + AFreq[j][0] * queryFreq[j][1];\n\t\t}\n\n\t\tplan = fftw_plan_dft_1d(fftsize, AQueryFreq, AQueryTime, FFTW_BACKWARD, FFTW_ESTIMATE);\n\t\tfftw_execute(plan);\n\n\t\tint exclusionZoneStart = i - exclusionZone;\n\t\tint exclusionZoneEnd = i + exclusionZone;\n\t\tdouble minimumDistance = std::numeric_limits<double>::infinity();\n\t\tint minimumDistanceIndex;\n\t\tfor (int j = 0; j < timeSeriesLength - windowSize + 1; j++)\n\t\t{\n\t\t\tdouble distance;\n\t\t\tif ((j > exclusionZoneStart) && (j < exclusionZoneEnd))\n\t\t\t\tdistance = std::numeric_limits<double>::infinity();\n\t\t\telse\n\t\t\t{\n\t\t\t\tdistance = 2 * (windowSize - (AQueryTime[windowSize + j - 1][0] / fftsize - windowSize * AMean[j] * queryMean) / (ASigma[j] * queryStd));\n\t\t\t}\n\n\t\t\tif (distance < minimumDistance)\n\t\t\t{\n\t\t\t\tminimumDistance = distance;\n\t\t\t\tminimumDistanceIndex = j;\n\t\t\t}\n\n\t\t\tif (distance < profile[j])\n\t\t\t{\n\t\t\t\tprofile[j] = distance;\n\t\t\t\tprofileIndex[j] = i;\n\t\t\t}\n\t\t}\n\t\tprofile[i] = minimumDistance;\n\t\tprofileIndex[i] = minimumDistanceIndex;\n\n\t\tint j = profileIndex[i];\n\t\tdouble lastz = (windowSize - profile[i] / 2) * (ASigma[j] * ASigma[i]) + windowSize * AMean[j] * AMean[i];\n\t\tdouble lastzz = lastz;\n\t\tdouble distance;\n\t\tfor (int k = 1; k < stepSize && i + k < timeSeriesLength - windowSize + 1 && j + k < timeSeriesLength - windowSize + 1; k++)\n\t\t{\n\t\t\tlastz = lastz - A[i + k - 1] * A[j + k - 1] + A[i + k + windowSize - 1] * A[j + k + windowSize - 1];\n\t\t\tdistance = 2 * (windowSize - (lastz - windowSize * AMean[j + k] * AMean[i + k]) / (ASigma[j + k] * ASigma[i + k]));\n\t\t\tif (distance < profile[i + k])\n\t\t\t{\n\t\t\t\tprofile[i + k] = distance;\n\t\t\t\tprofileIndex[i + k] = j + k;\n\t\t\t}\n\t\t\tif (distance < profile[j + k])\n\t\t\t{\n\t\t\t\tprofile[j + k] = distance;\n\t\t\t\tprofileIndex[j + k] = i + k;\n\t\t\t}\n\t\t}\n\t\tlastz = lastzz;\n\t\tfor (int k = 1; k < stepSize && i - k >= 0 && j - k >= 0; k++)\n\t\t{\n\t\t\tlastz = lastz - A[i - k + windowSize] * A[j - k + windowSize] + A[i - k] * A[j - k];\n\t\t\tdistance = 2 * (windowSize - (lastz - windowSize * AMean[j - k] * AMean[i - k]) / (ASigma[j - k] * ASigma[i - k]));\n\t\t\tif (distance < profile[i - k])\n\t\t\t{\n\t\t\t\tprofile[i - k] = distance;\n\t\t\t\tprofileIndex[i - k] = j - k;\n\t\t\t}\n\t\t\tif (distance < profile[j - k])\n\t\t\t{\n\t\t\t\tprofile[j - k] = distance;\n\t\t\t\tprofileIndex[j - k] = i - k;\n\t\t\t}\n\t\t}\n\t}\n\n\tfftw_destroy_plan(plan);\n\tfftw_free(AFreq);\n\tfftw_free(queryTime);\n\tfftw_free(queryFreq);\n\tfftw_free(AQueryTime);\n\tfftw_free(AQueryFreq);\n\tdelete[] query;\n\n\ttend = get_cur_time();\n\ttime_elapsed = tend - tstart;\n\n\t// output\n\tEXEC_INFO(\"finished prescrimp\")\n\tPERF_LOG( \"Time for PreSCRIMP: \" << std::setprecision(std::numeric_limits<double>::digits10 + 2) << time_elapsed );\n\n\tstd::fstream preprofileOutFile(preoutfilename.c_str(), std::ios_base::out);\n\n\t// Write PreSCRIMP Matrix Profile and Matrix Profile Index to file.\n\tfor (int i = 0; i < timeSeriesLength - windowSize + 1; i++)\n\t{\n\t\tpreprofileOutFile << std::setprecision(std::numeric_limits<double>::digits10 + 2) << sqrt(abs(profile[i])) << \" \" << std::setprecision(std::numeric_limits<int>::digits10 + 1) << profileIndex[i] << std::endl;\n\t}\n\n\tpreprofileOutFile.close();\n\n\t/******************** SCRIMP ********************/\n\n\t//Random shuffle the computation order of the diagonals of the distance matrix\nstd::srand(1);//TODO: remove. Introduced for constistent evaluation order among all algorithms during debugging!\n    idx.clear();\n\tfor (int i = exclusionZone+1; i < ProfileLength; i++)\n\t\tidx.push_back(i);\n\tstd::random_shuffle(idx.begin(), idx.end());\n\n\tdouble* dotproduct = new double[timeSeriesLength];\n\n\t//iteratively evaluate the diagonals of the distance matrix\n\tfor (int ri = 0; ri < idx.size(); ri++)\n\t    {\n\t\t//select a random diagonal\n\t\tint diag = idx[ri];\n\n\t\t//calculate the dot product of every two time series values that ar diag away\n\t\tfor (int j=diag; j < timeSeriesLength; j++)\n\t\t\tdotproduct[j]=A[j]*A[j-diag];\n\n\t\t//evaluate the fist distance value in the current diagonal\n\t\tdouble distance;\n\t\tdouble lastz=0; //the dot product of a subsequence\n\t\tfor (int k = 0; k < windowSize; k++)\n\t\t\tlastz += dotproduct[k+diag];\n\n\t\t//j is the column index, i is the row index of the current distance value in the distance matrix\n\t\tint j=diag, i=j-diag;\n\n\t\t//evaluate the distance based on the dot product\n\t\tdistance = 2 * (windowSize - (lastz - windowSize * AMean[j] * AMean[i]) / (ASigma[j] * ASigma[i]));\n\n\t\t//update matrix profile and matrix profile index if the current distance value is smaller\n\t\tif (distance < profile[j])\n\t\t{\n\t\t\tprofile[j] = distance;\n\t\t\tprofileIndex [j] = i;\n\t\t}\n\t\tif (distance < profile[i])\n\t\t{\n\t\t\tprofile[i] = distance;\n\t\t\tprofileIndex [i] = j;\n\t\t}\n\n//std::cout << \"diag \" << diag << \" lastz \" << lastz << std::endl;\n\t\t//evaluate the second to the last distance values along the diagonal and update the matrix profile/matrix profile index.\n\t\tfor (j=diag+1; j<ProfileLength; j++)\n\t\t{\n\t\t\ti=j-diag;\n\t\t\tlastz = lastz + dotproduct[j+windowSize-1] - dotproduct [j-1];\n\t\t\tdistance = 2 * (windowSize - (lastz - windowSize * AMean[j] * AMean[i]) / (ASigma[j] * ASigma[i]));\n\n//std::cout << \"eval i: \" << i << \" j: \" << j << \" lastz\" << lastz << std::endl;\n\t\t\tif (distance < profile[j])\n\t\t\t{\n\t\t\t\tprofile[j] = distance;\n\t\t\t\tprofileIndex [j] = i;\n\t\t\t}\n\t\t\tif (distance < profile[i])\n\t\t\t{\n\t\t\t\tprofile[i] = distance;\n\t\t\t\tprofileIndex [i] = j;\n\t\t\t}\n\t\t}\n\n\t\t//Show time per 10000 iterations\n\t\tif ( (ri+1) % notification_interval_iter == 0)\n\t\t{\n\t\t\ttend = get_cur_time();\n\t\t\ttime_elapsed = tend - tstart;\n\t\t\t//std::cout << \"Time spent: \" << std::setprecision(std::numeric_limits<double>::digits10 + 2) << difftime(time(0), tstart) << \" seconds.\" << std::endl;\n\t\t\tPERF_TRACE( \"completed \" << notification_interval_iter << \" iterations in: \" << time_elapsed );\n\t\t}\n\n\t\t//The following commented section is to produce provisional results. Basically, if you would like to enable interrupt and look at the current matrix profile/matrix profile index, you can uncomment this section, and revise line 182 according to the intterupt mechanism you're using.\n\n\t\t/*if (interrupt_detected) //revise this line to enable your interrupt mechanism\n\t\t{\n\t\t\tstd::fstream prov_profileOutFile(outfilename_provisional.c_str(), std::ios_base::out);\n\n\t\t\t// Write Current Matrix Profile and Matrix Profile Index to file.\n\t\t\tfor (int k = 0; k < timeSeriesLength - windowSize + 1; k++)\n\t\t\t\tprov_profileOutFile << std::setprecision(std::numeric_limits<double>::digits10 + 2) << sqrt(abs(profile[k])) << \" \" << std::setprecision(std::numeric_limits<int>::max()) << profileIndex[k] << std::endl;\n\t\t\tprov_profileOutFile.close();\n\t\t}\n\t\t*/\n\t}\n\n\t// end timer\n\t//tend = time(0);\n\ttend = get_cur_time();\n\ttime_elapsed = tend - tstart;\n\n\tPERF_LOG ( \"total computation time: \" << time_elapsed << \" seconds.\" );\n\tconst double triang_len = ProfileLength-exclusionZone;\n\tPERF_LOG ( \"throughput computations: \" << triang_len * triang_len / get_seconds(time_elapsed) << \" matrix entries/second\");\n\tEXEC_INFO( \"Writing result to file\");\n\n\tif (params.output_filename.empty()) {\n\t\tthrow std::runtime_error(\"Empty output file name specified!\");\n\t}\n\tstd::fstream profileOutFile(params.output_filename.c_str(), std::ios_base::out);\n\n\t// Write final Matrix Profile and Matrix Profile Index to file.\n\tfor (int i = 0; i < timeSeriesLength - windowSize + 1; i++)\n\t{\n\t\tprofile[i] = sqrt(abs(profile[i]));\n\t\tprofileOutFile << std::setprecision(std::numeric_limits<double>::digits10 + 2) << profile[i] << \" \" << std::setprecision(std::numeric_limits<int>::digits10+1) << profileIndex[i] << std::endl;\n\t}\n\n\tprofileOutFile.close();\n\n\tdelete [] dotproduct;\n\tdelete [] AMean;\n\tdelete [] ASigma;\n\tdelete [] profile;\n\tdelete [] profileIndex;\n}\n", "meta": {"hexsha": "8ae097926a3242f2308e0514192fa608e9a903f5", "size": 13541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/ScrimpppOrig.cpp", "max_stars_repo_name": "franzbischoff/ThesisCode", "max_stars_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T22:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:14:16.000Z", "max_issues_repo_path": "scrimppp/src/ScrimpppOrig.cpp", "max_issues_repo_name": "franzbischoff/ThesisCode", "max_issues_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrimppp/src/ScrimpppOrig.cpp", "max_forks_repo_name": "franzbischoff/ThesisCode", "max_forks_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T22:41:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T09:15:48.000Z", "avg_line_length": 33.5173267327, "max_line_length": 283, "alphanum_fraction": 0.665608153, "num_tokens": 4046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5737911421391956}}
{"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_RASTER_VARIATE_HPP\n#define RJMCMC_RASTER_VARIATE_HPP\n\n#include <boost/random/uniform_real.hpp>\n#include <vector>\n#include <algorithm>\n\nnamespace rjmcmc {\n\n\n    // this variate generates a point in [0,1]^N with a piecewise uniform density where the pieces are given by a uniform rectangular voxel grid.\n    // int *size gives the number of elements of the grid in each dimension\n    // T *pdf gives the unnormalized pdf values of each voxel as a N dimensional array of size (size)\n\n    template<int N>\n    class raster_variate\n    {\n        typedef boost::uniform_real<> rand_type;\n        mutable rand_type m_rand;\n\n    public:\n        typedef double value_type;\n        enum { dimension = N };\n        template<typename Engine, typename OutputIterator>\n        inline double operator()(Engine& e, OutputIterator it) const {\n            double x = m_rand(e);\n            int offset = int(std::upper_bound(m_cdf.begin()+1,m_cdf.end(),x)-(m_cdf.begin()+1));\n            double pdf = (m_cdf[offset+1]-m_cdf[offset])*m_totsize;\n            for(int i=0; i<N; ++i)\n            {\n                int ix = offset % m_size[i];\n                *it++ = (ix+m_rand(e))/m_size[i];\n                offset /= m_size[i];\n            }\n            return pdf;\n        }\n        template<typename InputIterator>\n        inline double pdf(InputIterator it) const {\n            int offset = 0;\n            int stride = 1;\n            for(int i=0; i<N; ++i)\n            {\n                double x = *it++;\n                if(x<0. || x>=1.) return 0.;\n                int ix = int(x*m_size[i]);\n                offset += stride*ix;\n                stride *= m_size[i];\n            }\n            return (m_cdf[offset+1]-m_cdf[offset])*m_totsize;\n        }\n        template<typename T>\n        raster_variate(T* pdf, int *size) {\n            m_size.resize(N);\n            m_totsize = 1;\n            for(int i=0; i<N; ++i) { m_totsize *= size[i]; m_size[i] = size[i]; }\n            m_sum = 0;\n            m_cdf.resize(m_totsize+1);\n            m_cdf[0] = 0.;\n            for(int i=0; i<m_totsize; ++i) m_sum = m_cdf[i+1] = m_sum + pdf[i]; // assert(pdf[i]>=0)\n            for(int i=0; i<m_totsize; ++i) m_cdf[i+1]/=m_sum;\n        }\n    private:\n        std::vector<double> m_cdf;\n        std::vector<int> m_size;\n        int m_totsize;\n        double m_sum;\n    };\n\n\n}; // namespace rjmcmc\n\n#endif // RJMCMC_RASTER_VARIATE_HPP\n", "meta": {"hexsha": "38db840ff7796ce56e4b7eb9d36c1bfcb122c1f4", "size": 4220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/kernel/raster_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/raster_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/raster_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": 38.7155963303, "max_line_length": 145, "alphanum_fraction": 0.628436019, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5737911293278705}}
{"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\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    Eigen::Matrix3d imu2ned;\n    CoordinateTransform::getDCM(imu2ned,attitude);\n\n    //Convert position to ECEF\n    Eigen::Vector3d positionECEF;\n    CoordinateTransform::getPositionECEF(positionECEF,position);\n\n    //Convert ping to ECEF\n    Eigen::Vector3d pingVector;\n    Raytracing::rayTrace(pingVector,ping,svp);\n\n    Eigen::Vector3d pingECEF = ned2ecef * (imu2ned * boresight * pingVector);\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  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    //Center position wrt centroid\n    Position pos(\n      position.getTimestamp(),\n      position.getLatitude() \t\t- centroid->getLatitude(),\n      position.getLongitude()\t\t- centroid->getLongitude(),\n      position.getEllipsoidalHeight()\t- centroid->getEllipsoidalHeight()\n    );\n\n    //Convert position's geographic coordinates to ECEF, and then from ECEF to NED\n    Eigen::Vector3d positionECEF;\n    CoordinateTransform::getPositionECEF(positionECEF,pos);\n    Eigen::Vector3d positionNED = ecef2ned * positionECEF;\n\n    //Convert ping to NED\n    Eigen::Vector3d pingVector;\n    Raytracing::rayTrace(pingVector,ping,svp);\n\n    Eigen::Vector3d pingNED = imu2ned * boresight * pingVector;\n\n    //Convert lever arm to NED\n    Eigen::Vector3d leverArmNED =  imu2ned * leverArm;\n\n    //Compute total NED vector\n\n    georeferencedPing = positionNED + pingNED + leverArmNED;\n  }\n\n  /**\n  * Sets centroid and inits ECEF 2 NED matrix\n  */\n  void setCentroid(Position * centroid){\n    this->centroid = centroid;\n    CoordinateTransform::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\nprivate:\n  Position * centroid = NULL; //in geographic coordinates\n  Eigen::Matrix3d ecef2ned;\n};\n\n#endif\n", "meta": {"hexsha": "334986bc19f239c811ad0e3ec2ce3001c926a9a2", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Georeferencing.hpp", "max_stars_repo_name": "EmileGagne/MBES-lib", "max_stars_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Georeferencing.hpp", "max_issues_repo_name": "EmileGagne/MBES-lib", "max_issues_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Georeferencing.hpp", "max_forks_repo_name": "EmileGagne/MBES-lib", "max_forks_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2080536913, "max_line_length": 201, "alphanum_fraction": 0.7286021505, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5737114574482922}}
{"text": "#define EIGEN_USE_MKL_ALL\n#define EIGEN_VECTORIZE_SSE4_2\n\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <gflags/gflags.h>\n#include <boost/math/special_functions/bessel.hpp>\n\n#include \"frpca/frpca.h\"\n#include \"frpca/matrix_vector_functions_intel_mkl.h\"\n#include \"frpca/matrix_vector_functions_intel_mkl_ext.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace boost;\n\nconst float EPS = 0.00000000001f;\ntypedef Eigen::SparseMatrix<float, Eigen::RowMajor> SMatrixXf;\n\n\nDEFINE_string(filename, \"data/PPI.ungraph\", \"Filename for edgelist file.\");\nDEFINE_string(emb1, \"sparse.emb\", \"Filename for svd results.\");\nDEFINE_string(emb2, \"spectral.emb\", \"Filename for svd results.\");\nDEFINE_int32(num_node, 3890, \"Number of node in the graph.\");\nDEFINE_int32(num_rank, 128, \"Embedding dimension.\");\nDEFINE_int32(num_step, 10, \"Number of order for recursion.\");\nDEFINE_int32(num_iter, 5, \"Number of iter in randomized svd.\");\nDEFINE_int32(num_thread, 10, \"Number of threads.\");\nDEFINE_double(theta, 0.5, \"Parameter of ProNE\");\nDEFINE_double(mu, 0.1, \"Parameter of ProNE\");\n\n\nSMatrixXf readGraph(string filename, int num_node){\n    SMatrixXf A(num_node, num_node);\n    typedef Eigen::Triplet<float> T;\n    vector<T> tripletList;\n    ifstream fin(filename.c_str());\n    while (1)\n    {\n        string x, y;\n        if (!(fin >> x >> y))\n            break;\n        int a = atoi(x.c_str()), b = atoi(y.c_str());\n        if (a==b) continue;\n        tripletList.push_back(T(a, b, 1));\n        tripletList.push_back(T(b, a, 1));\n    }\n    A.setFromTriplets(tripletList.begin(), tripletList.end());\n    return A;\n}\n\nSMatrixXf l1Normalize(SMatrixXf & mat){\n    SMatrixXf mat2(mat.rows(), mat.cols());\n    for (int k=0; k<mat.outerSize(); ++k){\n        int num_neighbor = mat.row(k).sum();\n        for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n            mat2.insert(k, it.col()) = it.value()/num_neighbor;\n    }\n    return mat2;\n}\n\nMatrixXf & l2Normalize(MatrixXf & mat){\n    for (int i = 0; i < mat.rows(); ++i){\n        float ssn = sqrt(mat.row(i).squaredNorm());\n        if (ssn < EPS) ssn = EPS;\n        mat.row(i) = mat.row(i) / ssn;\n      }\n    return mat;\n}\n\nSMatrixXf & validate(SMatrixXf & mat){\n    for (int k=0; k<mat.outerSize(); ++k)\n          for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n              if (it.value() <=0)\n                mat.coeffRef(k, it.col()) = 1;\n    return mat;\n}\n\nSMatrixXf & smfLog(SMatrixXf & mat){\n    for (int k=0; k<mat.outerSize(); ++k)\n          for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n              mat.coeffRef(it.row(), it.col()) = log(it.value());\n    return mat;\n}\n\nfloat bessel(int a, float b){\n    return boost::math::cyl_bessel_i(a, b);\n}\n\n\nMatrixXf getEmbbeddingViaDenseSvd(MatrixXf &data, int rank){\n    Eigen::BDCSVD<Eigen::MatrixXf> svdOfC(data, Eigen::ComputeThinU);\n    MatrixXf emb = svdOfC.matrixU() * svdOfC.singularValues().cwiseSqrt().asDiagonal();\n    emb = l2Normalize(emb);\n    return emb;\n}\n\n\nMatrixXf runFrPCA(SMatrixXf & input, int rank, int iter)\n{\n    int m = input.rows(), nnz = input.nonZeros();\n    mat_coo *A = coo_matrix_new(m, m, nnz);\n    A->nnz = nnz;\n    int i=0;\n    for (int k=0; k<input.outerSize(); ++k)\n        for (SMatrixXf::InnerIterator it(input,k); it; ++it)\n          {\n            A->rows[i] = k+1;\n            A->cols[i] = it.col()+1;\n            A->values[i] = it.value();\n            i += 1;\n          }\n    cout << \"read matrix done...\" <<endl;\n    // coo_matrix_print(A);\n\n    //transform it to CSR format\n    mat_csr* D = csr_matrix_new();\n    csr_init_from_coo(D, A);\n    coo_matrix_delete(A);\n\n    //the test for frPCA\n    mat *U = matrix_new(m, rank);\n    mat *S = matrix_new(rank, 1);\n    mat *V = matrix_new(m, rank);    \n    frPCA(D, &U, &S, &V, rank, iter);\n\n    // matrix_print(U);\n    // matrix_print(S);\n\n    MatrixXf emb = MatrixXf::Random(m, rank);\n    for (int i=0; i<m; i++)\n        for (int j=0; j<rank; j++)\n            emb(i, j) = matrix_get_element(U,i,j) *  sqrt(matrix_get_element(S,j,0));\n    cout << \"matrix decomposition done\" <<endl;\n    return emb;\n}\n\n\nMatrixXf getSparseEmbedding(SMatrixXf & A, int rank, int num_iter){\n    time_t t1 = time(NULL);\n    int row = A.rows(), col = A.cols();\n    SMatrixXf B = l1Normalize(A);\n    SMatrixXf C = B.transpose();\n    SMatrixXf D(col, col), E(row, col), F(row, col);\n    for (int i = 0; i < row; ++i){\n        D.insert(i, i) = pow(C.row(i).sum(), 0.75);\n    }\n\n    D = D / D.sum();\n    E = A * D;\n\n    B = validate(B);\n    E = validate(E);\n\n    B = smfLog(B);\n    E = smfLog(E);\n    F = B - E;\n    cout << \"preprocess time: \"<< (time(NULL) - t1 + 0.0) << endl;\n    cout << \"number of nnz: \"<< F.nonZeros() <<endl;\n\n    MatrixXf emb = runFrPCA(F, rank, num_iter);\n\n    emb = l2Normalize(emb); \n    return emb;\n}\n\n\nMatrixXf getSpectralEmbedding(SMatrixXf & A, MatrixXf & a, int step, float theta, float mu){\n    time_t t1 = time(NULL);\n    cout << \"Chebyshev series --------------- \" << endl;\n    if (step==1) return a;\n    int num_node = a.rows(), rank = a.cols();\n    SMatrixXf I(num_node, num_node);\n    for (int i = 0; i < num_node; ++i)\n        I.insert(i, i) = 1;\n    A = A + I;\n    SMatrixXf B = l1Normalize(A);\n    SMatrixXf L = I - B;\n    SMatrixXf M = L - mu * I;\n\n\n    MatrixXf Lx0 = a;\n    MatrixXf Lx1 = M * a, Lx2;\n    Lx1 = 0.5 * M * Lx1 - a;\n\n    MatrixXf conv = bessel(0, theta)* Lx0;\n    conv -= 2 * bessel(1, theta)* Lx1;\n    for(int i=2; i<step; i++){\n        Lx2 = M * Lx1;\n        Lx2 = (M * Lx2 - 2 * Lx1) - Lx0;\n\n        if (i % 2 == 0)\n            conv += 2 * bessel(i, theta) * Lx2;\n        else\n            conv -= 2 * bessel(i, theta) * Lx2;\n        Lx0 = Lx1;\n        Lx1 = Lx2;\n        cout << \"Bessell time: \" << i <<\"\\t\"<< (time(NULL) - t1 + 0.0) << endl;\n    }\n    MatrixXf emb = A * (a - conv);\n    cout << \"Chebyshev time: \"<< (time(NULL) - t1 + 0.0) << endl;\n    \n    // time_t t2 = time(NULL);\n    // MatrixXf emb = getEmbbeddingViaDenseSvd(emb, rank);\n    // cout << \"dense svd time: \"<< (time(NULL) - t2 + 0.0) << endl;\n    emb = l2Normalize(emb); \n    return emb;\n}\n\n\nvoid saveEmbedding(MatrixXf &data, string output){\n    int m = data.rows(), d = data.cols();\n    FILE *emb = fopen(output.c_str(), \"wb\");\n    fprintf(emb, \"%d %d\\n\", m, d);\n    for (int i = 0; i < m; i++)\n    {\n        fprintf(emb, \"%d\", i);\n        for (int j = 0; j < d; j++)\n            fprintf(emb, \" %f\", data(i, j));\n        fprintf(emb, \"\\n\");\n    }\n    fclose(emb);\n}\n\n\nint main(int argc, char** argv)\n{\n    gflags::ParseCommandLineFlags(&argc, &argv, true);\n    Eigen::setNbThreads(FLAGS_num_thread);\n\n    time_t t1 = time(NULL);\n    SMatrixXf A = readGraph(FLAGS_filename, FLAGS_num_node);\n\n    MatrixXf feature = getSparseEmbedding(A, FLAGS_num_rank, FLAGS_num_iter);\n    time_t t2 = time(NULL);\n    cout << \"Running time of get sparse embedding: \" << (t2 - t1 + 0.0) << endl;\n\n    MatrixXf embedding = getSpectralEmbedding(A, feature, FLAGS_num_step, FLAGS_theta, FLAGS_mu);\n    time_t t3 = time(NULL);\n    cout << \"Running time of get spectral embedding: \" << (t3 - t2 + 0.0)  << endl;\n    cout << \"Running time of ProNE: \" << (t3 - t1 + 0.0) << endl;\n\n    saveEmbedding(feature, FLAGS_emb1);\n    saveEmbedding(embedding, FLAGS_emb2);\n    cout << \"Embedding save done \" << endl;\n\n}\n", "meta": {"hexsha": "1d19204c7f57f1f0a5299a17c98298452e6798b6", "size": 7380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProNE.cpp", "max_stars_repo_name": "abcbdf/ProNE", "max_stars_repo_head_hexsha": "0e192073f1c596da711b65a997eb5a9375c88f8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 196.0, "max_stars_repo_stars_event_min_datetime": "2019-05-31T02:34:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T03:11:26.000Z", "max_issues_repo_path": "ProNE.cpp", "max_issues_repo_name": "abcbdf/ProNE", "max_issues_repo_head_hexsha": "0e192073f1c596da711b65a997eb5a9375c88f8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-06-10T17:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-10T03:30:08.000Z", "max_forks_repo_path": "ProNE.cpp", "max_forks_repo_name": "abcbdf/ProNE", "max_forks_repo_head_hexsha": "0e192073f1c596da711b65a997eb5a9375c88f8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2019-06-17T01:48:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:39:32.000Z", "avg_line_length": 29.1699604743, "max_line_length": 97, "alphanum_fraction": 0.5823848238, "num_tokens": 2376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5737114514871807}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <math.h>\n#include <vector>  \n#include <random>\n#include <thread>  \n#include <boost/multi_array.hpp>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n\nusing namespace std;\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n#include \"Layers.cpp\"\n\n// precision for floating numbers written in files\nconstexpr int prec_write_file = 16; \n\n// define a standard normal distribution\nstd::random_device rd;  \nstd::mt19937 gen(rd()); \nstd::normal_distribution<> dis(0.,1.);\n\n// uniform dictribution\nstd::uniform_real_distribution<> uni(0.,1.);\n\nstruct double_and_int{\n\tdouble d = 0.;\n\tint i = 0;\n};\n\nclass CNN3{\n\n\tprivate: \n\n\t\tint num_CLs; // number of convolution layers\n\t\tint num_FCs; // number of FullCon layers\n\t\tint img_h_i; // image height\n\t\tint img_w_i; // image width\n\t\tint img_h; // image height before the fully connected layers\n\t\tint img_w; // image width before the fully connected layers\n\t\tint num_images; // number of images\n\t\tint num_labels; // number of different possible labels\n\t\tint n_channels; // number of channels\n\t\t\n\t\tvector<int> CL_size_filters; // Convolution layers: filter sizes\n\t\tvector<int> CL_num_filters; // Convolution layers: numbers of filters\n\t\tvector<int> MP_size; // Maxpool layers: pool sizes\n\t\tvector<int> FC_size; // FullCon layers: number of neurons\n\t\t\n\t\t// These four vectors will contain the layers\n\t\tvector<ConvLayer> CLs; // Convolution layers\n\t\tvector<ReLU> RLUs; // ReLU layers\n\t\tvector<MaxPool> MPs; // Maxpool layers\n\t\tvector<FullCon> FCs; // FullCon layers\n\t\tvector<SoftMax> SMs; // Softmax layers\n\n\tpublic: \n\n\t\tCNN3(){\n\t\t\tnp::initialize(); // required to create numpy arrays (otherwise leads to segmentation faults)\n\t\t}\t\n\n\t\tCNN3(\n\t\t\tint img_w_, // image width \n\t\t\tint img_h_, // image height\n\t\t\tint n_channels_, // number of channels\n\t\t\tp::list& CL_size_filters_, // list of filter sizes\n\t\t\tp::list& CL_num_filters_, // list of numbers of filters\n\t\t\tp::list& MP_size_, // list of pool sizes\n\t\t\tp::list& FC_size_, // list of FullCon sizes\n\t\t\tint num_labels_ // number of different possible labels\n\t\t) \n\t\t{\n\t\t\t// initialization\n\t\t\timg_w_i = img_w_;\n\t\t\timg_h_i = img_h_;\n\t\t\timg_w = img_w_;\n\t\t\timg_h = img_h_;\n\t\t\tnum_labels = num_labels_;\n\t\t\tn_channels = n_channels_;\n\t\t\tCL_size_filters = int_list_to_vector(CL_size_filters_);\n\t\t\tCL_num_filters = int_list_to_vector(CL_num_filters_);\n\t\t\tMP_size = int_list_to_vector(MP_size_);\n\t\t\tFC_size = int_list_to_vector(FC_size_);\n\t\t\tnum_CLs = len(CL_size_filters_);\n\t\t\tnum_FCs = len(FC_size_);\n\t\t\t\n\t\t\tnum_images = n_channels; // tracks the number of images\n\n\t\t\t// build the layers\n\t\t\tfor(int i=0; i<num_CLs; i++){\n\t\t\t\tCLs.push_back(ConvLayer(CL_size_filters[i], num_images, CL_num_filters[i], gen, dis));\n\t\t\t\tnum_images = CL_num_filters[i];\n\t\t\t\timg_w = img_w + 1 - CL_size_filters[i];\n\t\t\t\timg_h = img_h + 1 - CL_size_filters[i];\n\t\t\t\tRLUs.push_back(ReLU());\n\t\t\t\tMPs.push_back(MaxPool(MP_size[i]));\n\t\t\t\timg_w = (int) img_w / MP_size[i];\n\t\t\t\timg_h = (int) img_h / MP_size[i];\n\t\t\t}\n\t\t\tlong int n_inputs = num_images*img_h*img_w;\n\t\t\tfor(int i=0; i<num_FCs; i++){\n\t\t\t\tint n_neurons = FC_size[i];\n\t\t\t\tFCs.push_back(FullCon(n_inputs, n_neurons, gen, dis));\n\t\t\t\tn_inputs = n_neurons;\n\t\t\t}\n\t\t\tSMs.push_back(SoftMax(n_inputs, num_labels, gen, dis));\n\n\t\t\tnp::initialize(); // required to create numpy arrays (otherwise leads to segmentation faults)\n\t\t}\n\n\t\t// save the CNN parameters to a file\n\t\tvoid save(char* filename){\n\t\t\tofstream file;\n\t\t\tfile.open(filename);\n\t\t\tfile << fixed << setprecision(prec_write_file);\n\t\t\tfile << num_CLs << sep_val << num_FCs << sep_val << n_channels << sep_val << img_w_i << sep_val << img_h_i << sep_val << img_w << sep_val << img_h << sep_val << num_images << sep_line;\n\t\t\tsave_vector(CL_size_filters, file);\n\t\t\tsave_vector(CL_num_filters, file);\n\t\t\tsave_vector(MP_size, file); \n\t\t\tfor(int i=0; i<num_CLs; i++){\n\t\t\t\tCLs[i].save(file);\n\t\t\t\tRLUs[i].save(file);\n\t\t\t\tMPs[i].save(file);\n\t\t\t}\n\t\t\tfor(int i=0; i<num_FCs; i++){\n\t\t\t\tFCs[i].save(file);\n\t\t\t}\n\t\t\tSMs[0].save(file);\n\t\t\tfile.close();\n\t\t}\n\t\t\n\t\t// load the CNN parameters from a file\n\t\tvoid load(char* filename){\n\t\t\tifstream file;\n\t\t\tfile.open(filename);\n\t\t\tchar c;\n\t\t\tfile >> num_CLs >> c >> num_FCs >> c >> n_channels >> c >> img_w_i >> c >> img_h_i >> c >> img_w >> c >> img_h >> c >> num_images >> c;\n\t\t\tCL_size_filters = load_vector<int>(file);\n\t\t\tCL_num_filters = load_vector<int>(file);\n\t\t\tMP_size = load_vector<int>(file); \n\t\t\tCLs.clear();\n\t\t\tRLUs.clear();\n\t\t\tCLs.clear();\n\t\t\tSMs.clear();\n\t\t\tfor(int i=0; i<num_CLs; i++){\n\t\t\t\tCLs.push_back(ConvLayer());\n\t\t\t\tCLs[i].load(file);\n\t\t\t\tRLUs.push_back(ReLU());\n\t\t\t\tRLUs[i].load(file);\n\t\t\t\tMPs.push_back(MaxPool());\n\t\t\t\tMPs[i].load(file);\n\t\t\t}\n\t\t\tfor(int i=0; i<num_FCs; i++){\n\t\t\t\tFCs.push_back(FullCon());\n\t\t\t\tFCs[i].load(file);\n\t\t\t}\n\t\t\tSMs.push_back(SoftMax());\n\t\t\tSMs[0].load(file);\n\t\t\tfile.close();\n            num_labels = SMs[0].output.size();\n\t\t}\n\n\t\t// forward pass\n\t\tvector<double> forward(d3_array_type &input, double p_dropout = 0.){\n\t\t\t\n\t\t\t// number and dimensions of images\n\t\t\tint nim = input.shape()[0];\n\t\t\tint h = input.shape()[1];\n\t\t\tint w = input.shape()[2];\n\t\t\tif(h != img_h_i || w != img_w_i || nim != n_channels){\n\t\t\t\tcout << \"\\nInvalid input dimensions!\\n\" << endl;\n\t\t\t}\n\t\t\tfor(int i=0; i<num_CLs; i++){\n\t\t\t\td3_array_type output1 = CLs[i].forward(input);\n\t\t\t\tinput.resize(boost::extents[output1.shape()[0]][output1.shape()[1]][output1.shape()[2]]);\n\t\t\t\tinput = output1;\n\n\t\t\t\td3_array_type output2 = MPs[i].forward(input);\n\t\t\t\tinput.resize(boost::extents[output2.shape()[0]][output2.shape()[1]][output2.shape()[2]]);\n\t\t\t\tinput = output2;\n\n\t\t\t\td3_array_type output3 = RLUs[i].forward(input);\n\t\t\t\tinput.resize(boost::extents[output3.shape()[0]][output3.shape()[1]][output3.shape()[2]]);\n\t\t\t\tinput = output3;\n\t\t\t}\n\t\t\n\t\t\tvector<double> input_vec;\n\t\t\tauto input_shape = input.shape();\n\t\t\tfor(int i=0; i<num_images; i++){\n\t\t\t\tfor(int j=0; j<img_h; j++){\n\t\t\t\t\tfor(int k=0; k<img_w; k++){\n\t\t\t\t\t\tinput_vec.push_back(input[i][j][k]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i=0; i<num_FCs; i++){\n\t\t\t\tinput_vec = FCs[i].forward(input_vec, gen, uni, p_dropout);\n\t\t\t}\n\t\t\t\n\t\t\treturn SMs[0].forward(input_vec);\n\t\t}\n\t\t\n\t\t// backpropagation\n\t\tvoid backprop(vector<double> d_L_d_out_i, double learn_rate){\n\t\t\t\n\t\t\td3_array_type d_L_d_in(boost::extents[num_images][img_h][img_w]); \n\t\t\n\t\t\tvector<double> d_L_d_in_vec = SMs[0].backprop(d_L_d_out_i, learn_rate);\n\t\t\t\n\t\t\tfor(int i=num_FCs-1; i>=0; i--){\n\t\t\t\td_L_d_in_vec = FCs[i].backprop(d_L_d_in_vec, learn_rate);\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i=0; i<num_images; i++){\n\t\t\t\tfor(int j=0; j<img_h; j++){\n\t\t\t\t\tfor(int k=0; k<img_w; k++){\n\t\t\t\t\t\td_L_d_in[i][j][k] = d_L_d_in_vec[i*img_h*img_w + j*img_w + k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i=num_CLs-1; i>=0; i--){\n\t\t\t\td3_array_type d_L_d_in3 = RLUs[i].backprop(d_L_d_in);\n\t\t\t\tauto shape = d_L_d_in3.shape();\n\t\t\t\td_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n\t\t\t\td_L_d_in = d_L_d_in3;\n\t\t\t\n\t\t\t\td3_array_type d_L_d_in2 = MPs[i].backprop(d_L_d_in);\n\t\t\t\tshape = d_L_d_in2.shape();\n\t\t\t\td_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n\t\t\t\td_L_d_in = d_L_d_in2;\n\t\t\t\t\n\t\t\t\td3_array_type d_L_d_in1 = CLs[i].backprop(d_L_d_in, learn_rate);\n\t\t\t\tshape = d_L_d_in1.shape();\n\t\t\t\td_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n\t\t\t\td_L_d_in = d_L_d_in1;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// loss function and accuracy (1 if correct answer, 0 otherwise)\n\t\tdouble_and_int loss_acc(vector<double> &output, int label){\n\t\t\tdouble_and_int results;\n\t\t\tresults.d = -log(output[label]); \n\t\t\tresults.i = 1;\n\t\t\tfor(int i=0; i<output.size(); i++){\n\t\t\t\tif(output[i] > output[label]){\n\t\t\t\t\tresults.i = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn results;\n\t\t}\n\n\t\t// Completes a training step on the image 'image' with label 'label'.\n\t\t// Returns the corss-entropy and accuracy.\n\t\tdouble_and_int train(d3_array_type image, int label, double learn_rate = 0.005, double p_dropout = 0.) {\n\t\t\n\t\t\t// forward pass\n\t\t\tvector<double> output_forward = forward(image, p_dropout);\n\t\n\t\t\t// gradient of the loss function with respect to the output\n\t\t\tvector<double> d_L_d_out;\n\t\t\tfor(int i=0; i<num_labels; i++){\n\t\t\t\td_L_d_out.push_back(0.);\n\t\t\t}\n\t\t\td_L_d_out[label] = -1./output_forward[label];\n\n\t\t\t// backpropagation\n\t\t\tbackprop(d_L_d_out, learn_rate);\n\n\t\t\t// return loss and accuracy\n\t\t\treturn loss_acc(output_forward, label);\n\t\t}\n\n\t\t// full forward propagation - Python wrapper\n\t\t// input: 2d numpy array\n\t\tnp::ndarray forward_python(np::ndarray image){\n\t\t\td3_array_type input = d3_numpy_to_multi_array(image);\n\t\t\treturn vector_to_numpy(forward(input));\n\t\t}\n\n\t\t// forward - return loss and accuracy - Python wrapper\n\t\tp::list forward_la_python(np::ndarray image, int label){\n\t\t\td3_array_type input = d3_numpy_to_multi_array(image);\n\t\t\tvector<double> output = forward(input);\n\t\t\tdouble_and_int results = loss_acc(output, label);\n\t\t\tp::list results_p;\n\t\t\tresults_p.append(results.d);\n\t\t\tresults_p.append(results.i);\n\t\t\treturn results_p;\n\t\t}\n\t\t\n\t\t// full backpropagation - Python wrapper\n\t\tvoid backprop_python(np::ndarray d_L_d_out, double learn_rate){\n\t\t\tbackprop(numpy_to_vector(d_L_d_out), learn_rate);\n\t\t}\n\t\t\n\t\t// train - Python wrapper\n\t\tp::list train_python(np::ndarray image, int label, double learn_rate, double p_dropout) {\n\t\t\tdouble_and_int results;\n\t\t\tresults = train(d3_numpy_to_multi_array(image), label, learn_rate, p_dropout);\n\t\t\tp::list results_p;\n\t\t\tresults_p.append(results.d);\n\t\t\tresults_p.append(results.i);\n\t\t\treturn results_p;\n\t\t}\n\n};\n\nBOOST_PYTHON_MODULE(CNN3)\n{\n    p::class_<CNN3>(\"CNN3\", p::init<int, int, int, p::list&, p::list&, p::list&, p::list&, int>())\n\t\t.def(p::init<>())\n\t\t.def(\"forward\", &CNN3::forward_python)\n\t\t.def(\"backprop\", &CNN3::backprop_python)\n\t\t.def(\"train\", &CNN3::train_python)\n\t\t.def(\"save\", &CNN3::save)\n\t\t.def(\"load\", &CNN3::load)\n\t\t.def(\"forward_la\", &CNN3::forward_la_python)\n\t;\n}\n", "meta": {"hexsha": "ca9cccc45fccf26be356907bdde968483f7c34e8", "size": 9870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/CNN3.cpp", "max_stars_repo_name": "FlorentCLMichel/CNN_in_Cpp", "max_stars_repo_head_hexsha": "5568e71ec23c45be144a0673e2fc36d4c6f1c5de", "max_stars_repo_licenses": ["MIT"], "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++/CNN3.cpp", "max_issues_repo_name": "FlorentCLMichel/CNN_in_Cpp", "max_issues_repo_head_hexsha": "5568e71ec23c45be144a0673e2fc36d4c6f1c5de", "max_issues_repo_licenses": ["MIT"], "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++/CNN3.cpp", "max_forks_repo_name": "FlorentCLMichel/CNN_in_Cpp", "max_forks_repo_head_hexsha": "5568e71ec23c45be144a0673e2fc36d4c6f1c5de", "max_forks_repo_licenses": ["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.2760736196, "max_line_length": 187, "alphanum_fraction": 0.6595744681, "num_tokens": 2968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5737104944126473}}
{"text": "#include \"formant.h\"\n#include <Eigen/Dense>\n\nusing namespace Analysis::Formant;\nusing Analysis::FormantResult;\n\nusing namespace Eigen;\n\nstruct Analysis::Formant::KarmaState\n{\n    int numF;\n    VectorXd y;\n    MatrixXd F;\n    MatrixXd Q;\n    MatrixXd R;\n    VectorXd m_up;\n    VectorXd P_up;\n};\n\nconstexpr int ncep = 15;\nconstexpr int numF = 3;\n\nKarma::Karma()\n    : state(new KarmaState)\n{\n    state->F.setIdentity(2 * numF, 2 * numF);\n\n    state->Q.setZero(2 * numF, 2 * numF);\n    state->Q.diagonal().head(numF).setConstant(320 * 320);\n    state->Q.diagonal().tail(numF).setConstant(100 * 100);\n    \n    state->R.setZero(ncep, ncep);\n    for (int i = 0; i < ncep; ++i) {\n        state->R(i, i) = 1.0 / (double) (i + 1);\n    }\n\n    VectorXd x0(2 * numF);\n    x0 << 500, 1500, 2500,\n           80,  120,  160;\n\n    state->m_up = x0;\n    state->P_up = state->Q;\n}\n\nKarma::~Karma()\n{\n    delete state;\n}\n\nstatic VectorXd calcCepstrumCoefs(const double *lpc, int lpcOrder, int ncep);\nstatic MatrixXd calcMatrixH(const VectorXd& m, int cepOrder, double Fs);\nstatic VectorXd calcCepstrumMapping(const VectorXd& m, int cepOrder, double Fs);\n\nFormantResult Karma::solve(const double *lpc, int lpcOrder, double sampleRate)\n{\n    auto& F  = state->F;\n    auto  Ft = state->F.transpose();\n    auto& Q  = state->Q;\n    auto& R  = state->R;\n\n    auto m_pred = F * state->m_up;\n    auto P_pred = F * state->P_up * Ft + Q;\n\n    auto H  = calcMatrixH(m_pred, ncep, sampleRate);\n    auto Ht = H.transpose();\n   \n    auto S = H * P_pred * Ht + R;\n    auto K = (P_pred * Ht) * S.colPivHouseholderQr().inverse();\n\n    auto y_pred = calcCepstrumMapping(m_pred, ncep, sampleRate);\n    auto y      = calcCepstrumCoefs(lpc, lpcOrder, ncep);\n\n    state->m_up = m_pred + K * (y - y_pred);\n    state->P_up = P_pred - K * H * P_pred;\n\n    rpm::vector<FormantData> formants(numF);\n    for (int i = 0; i < numF; ++i) {\n        formants[i] = {\n            .frequency = state->m_up(i),\n            .bandwidth = state->m_up(numF + i),\n        };\n    }\n\n    return { .formants = formants };\n}\n\nVectorXd calcCepstrumCoefs(const double *lpc, int lpcOrder, int ncep)\n{\n    VectorXd C(ncep);\n\n    for (int n = 1; n <= ncep; ++n) {\n        if (n == 1) {\n            C(n - 1) = lpc[n - 1];\n        }\n        else if (n <= lpcOrder) {\n            C(n - 1) = lpc[n - 1];\n            for (int i = 1; i <= ncep - 1; ++i) {\n                C(n - 1) += (double) i / (double) n * lpc[n - i - 1] * C(i - 1);\n            }\n        }\n        else {\n            C(n - 1) = 0.0;\n            for (int i = ncep - lpcOrder; i <= ncep - 1; ++i) {\n                C(n - 1) += (double) i / (double) n * lpc[n - i - 1] * C(i - 1);\n            }\n        }\n    }\n\n    return C;\n}\n\nMatrixXd calcMatrixH(const VectorXd &m, int cepOrder, double Fs)\n{\n    const int numF = m.size() / 2;\n    auto freq = m.segment(0, numF);\n    auto band = m.segment(numF, numF);\n\n    MatrixXd H(cepOrder, 2 * numF);\n\n    for (int i = 0; i < cepOrder; ++i) {\n        for (int j = 0; j < numF; ++j) {\n            const double bwTerm = exp((-M_PI * (i + 1) * band(j)) / Fs);\n\n            H(i, j)        = -4.0 * M_PI / Fs * bwTerm * sin((2.0 * M_PI * (i + 1) * freq(j)) / Fs);\n            H(i, numF + j) = -2.0 * M_PI / Fs * bwTerm * cos((2.0 * M_PI * (i + 1) * freq(j)) / Fs);\n        }\n    }\n\n    return H;\n}\n\nVectorXd calcCepstrumMapping(const VectorXd& m, int cepOrder, double Fs)\n{\n    const int numF = m.size() / 2;\n    auto freq = m.segment(0, numF);\n    auto band = m.segment(numF, numF);\n\n    VectorXd C_int(numF);\n    VectorXd C(cepOrder);\n\n    for (int i = 0; i < cepOrder; ++i) {\n        for (int p = 0; p < numF; ++p) {\n            const double bwTerm = (2.0 / (double) (i + 1)) * exp((-M_PI * (i + 1) * band(p)) / Fs);\n            C_int(p) = bwTerm * cos((2.0 * M_PI * (i + 1) * freq(p)) / Fs);\n        }\n        C(i) = C_int.sum();\n    }\n\n    return C;\n}\n", "meta": {"hexsha": "301b87220f52590b2e133b5dcdceae0df8ac8ed9", "size": 3886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/formant/karma.cpp", "max_stars_repo_name": "alargepileofash/in-formant", "max_stars_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 55.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T20:22:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:58:36.000Z", "max_issues_repo_path": "src/analysis/formant/karma.cpp", "max_issues_repo_name": "alargepileofash/in-formant", "max_issues_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-12-06T22:02:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-19T09:37:56.000Z", "max_forks_repo_path": "src/analysis/formant/karma.cpp", "max_forks_repo_name": "alargepileofash/in-formant", "max_forks_repo_head_hexsha": "3fc77925b68e349b96d7cf20c00223a4b343d04d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-12-16T16:06:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-15T15:28:31.000Z", "avg_line_length": 25.7350993377, "max_line_length": 100, "alphanum_fraction": 0.5216160576, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.5737104784578977}}
{"text": "#pragma once\n\n#include <armadillo>\n\nclass AmbientFluid;\n\n/*!\n * Namespace for some utilities.\n */\nnamespace utils {\n\n    /*!\n     * \\brief Calculate thermal conductivity of natural gas at given pressure.\n     *\n     * This is some kind of empirical relation or fitting, with an unknown source.\n     * It should probably be replaced with something else. See for example\n     * <a href=\"https://doi.org/10.1016/j.jngse.2014.04.005\"><i>A simple correlation to estimate natural gas thermal conductivity</i> (Azad Jarrahiana and Ehsan Heidaryan, Journal of Natural Gas Science and Engineering, Volume 18, May 2014)</a>.\n     *\n     * \\param pressure Gas pressure [Pa].\n     * \\return Thermal conductivity [W/(m K)]\n     */\n    double calcGasThermalConductivity(const double pressure);\n\n    /*!\n     * \\brief Calculate outer film coefficient for a given outer diameter and\n     * AmbientFluid.\n     *\n     * This is just a wrapper around utils::calcOuterWallFilmCoefficient(const double, const double, const double, const double, const double, const double)\n     *\n     * \\param diameter Outer diameter [m]\n     * \\param fluid AmbientFluid describing the fluid\n     * \\return Outer film coefficient [W/(m2 K)]\n     */\n    double calcOuterWallFilmCoefficient(\n            const double diameter,\n            const AmbientFluid& fluid\n            );\n\n    /*!\n     * \\brief Calculate the outer film coefficient for external flow normal to a\n     * circular cylinder.\n     *\n     * Uses eq. 7.52 from Fundamentals of heat and mass transfer (7th Ed, 2011) (Bergman, Lavine, Incropera, DeWitt).\n     *\n     * \\param diameter Outer diameter [m]\n     * \\param heatCapacityConstantPressure Fluid heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param viscosity Fluid dynamic viscosity [Pa s] = [kg/m*s]\n     * \\param thermalConductivity Fluid thermal conductivity [W/(m K)]\n     * \\param density Fluid density [kg/m3]\n     * \\param velocity Fluid velocity [m/s]\n     * \\return Outer film coefficient [W/(m2 K)]\n     */\n    double calcOuterWallFilmCoefficient(\n            const double diameter,\n            const double heatCapacityConstantPressure = 4200, // [J/kg K]\n            const double viscosity = 1.05/1000.0, // [Pa s] = [kg/m*s]\n            const double thermalConductivity = 0.57, // [W/m K]\n            const double density = 1020, // [kg/m3]\n            const double velocity = 0.1 // [m/s]\n            );\n\n    /*!\n     * \\brief Calculate inner wall film coefficient for flow inside a cylinder.\n     *\n     * This uses the Dittus-Boelter equation at Reynolds numbers abve 1e4,\n     * eq. 8.55 Fundamentals of heat and mass transfer (7th Ed, 2011) (Bergman, Lavine, Incropera, DeWitt)\n     * at Reynolds number between 1e4 and 4e4, and returns 0 below 4e4.\n     *\n     * \\param diameter Inner diameter [m]\n     * \\param fluidPressure Fluid pressure [Pa]\n     * \\param fluidReynoldsNumber Fluid Reynolds number [-]\n     * \\param fluidHeatCapacityConstantPressure Fluid heat capacity (\\f$c_p\\f$) [J/(kg K)]\n     * \\param fluidViscosity Fluid dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return Inner film coefficient [W/(m2 K)]\n     */\n    double calcInnerWallFilmCoefficient(\n            const double diameter,\n            const double fluidPressure,\n            const double fluidReynoldsNumber,\n            const double fluidHeatCapacityConstantPressure,\n            const double fluidViscosity);\n\n    /*!\n     * \\brief Calculate equivalent burial layer thickness.\n     *\n     * For a pipeline buried in a medium at a given depth, this function\n     * calculates the thickness of an equivalent cylinder shell of the same\n     * medium around the pipeline which gives the same heat transfer between\n     * the fluid in the pipeline and the ambient medium. The calculation is\n     * based on equations in the documentation of the OLGA simulation software.\n     *\n     * Using the thickness from this function ensures the same results are\n     * achieved with steady state and unsteady heat transfer models.\n     *\n     * \\see utils::calcEquivalentBurialLayerRadius()\n     *\n     * \\param innerDiameter Pipeline inner diameter [m]\n     * \\param wallThickness Pipeline wall thickness [m]\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     * \\param burialMediumConductivity Thermal conductivity of burial medium [W/(m K)]\n     * \\return\n     */\n    double calcEquivalentBurialLayerWidth(\n            const double innerDiameter,\n            const double wallThickness,\n            const double burialDepth,\n            const double burialMediumConductivity = 2.0);\n\n    /*!\n     * \\brief calcEquivalentBurialLayerRadius\n     *\n     * For a pipeline buried in a medium at a given depth, this function\n     * calculates the outer radius of an equivalent cylinder shell of the same\n     * medium around the pipeline which gives the same heat transfer between\n     * the fluid in the pipeline and the ambient medium. The calculation is\n     * based on equations in the documentation of the OLGA simulation software.\n     *\n     * \\param innerDiameter Pipeline inner diameter [m]\n     * \\param wallThickness Pipeline wall thickness [m]\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     * \\param burialMediumConductivity Thermal conductivity of burial medium [W/(m K)]\n     * \\return Outer radius of equivalent cylinder shell of burial medium [m]\n     */\n    double calcEquivalentBurialLayerRadius(\n            const double innerDiameter,\n            const double wallThickness,\n            const double burialDepth,\n            const double burialMediumConductivity = 2.0);\n\n    /*!\n     * \\brief Calculate logarithmically (log10) spaced cylinder shell widths.\n     *\n     * This function calculates the widths of nShells cylinder shells,\n     * logarithmically (log10) spaced between innerRadius and outerRadius.\n     *\n     * \\param innerRadius Inner radius [m]\n     * \\param outerRadius Outer radius [m]\n     * \\param nShells Number of cylinder shells\n     * \\return arma::vec of shell widths [m]\n     */\n    arma::vec calcLogSpacedShellWidths(\n            const double innerRadius,\n            const double outerRadius,\n            const arma::uword nShells = 10);\n\n    /*!\n     * \\brief Calculate the widths of equivalent burial cylinder shells.\n     *\n     * This is just a wrapper around utils::calcEquivalentBurialLayerRadius()\n     * and utils::calcLogSpacedShellWidths() that divides the shell into\n     * several logarithmically spaced shells.\n     *\n     * \\see utils::calcEquivalentBurialLayerRadius()\n     * \\see utils::calcLogSpacedShellWidths()\n     *\n     * \\param innerDiameter Inner diameter [m]\n     * \\param wallThickness Wall thickness [m]\n     * \\param burialDepth Distance from top of pipe to top of burial medium [m]\n     * \\param burialMediumConductivity Thermal conductivity of burial medium [W/(m K)]\n     * \\param nShells Number of shells\n     * \\return Widths of logarithmically spaced cylinder shells.\n     */\n    arma::vec calcEquivalentBurialLayerWidths(\n            const double innerDiameter,\n            const double wallThickness,\n            const double burialDepth,\n            const double burialMediumConductivity = 2.0,\n            const arma::uword nShells = 10);\n}\n", "meta": {"hexsha": "a73c5e2c8b1ea8d7231eab2102d8da3e2efe074a", "size": 7261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heattransfer/utils.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/heattransfer/utils.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/heattransfer/utils.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": 42.7117647059, "max_line_length": 245, "alphanum_fraction": 0.6701556259, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5737095724868849}}
{"text": "//==============================================================================\n//         Copyright 2015 - J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_TENPOWER_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/tenpower.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/ten.hpp>\n#include <boost/simd/include/functions/abs.hpp>\n#include <boost/simd/include/functions/sqr.hpp>\n#include <boost/simd/include/functions/scalar/is_odd.hpp>\n#include <boost/simd/include/functions/scalar/rec.hpp>\n#include <boost/dispatch/attributes.hpp>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( tenpower_, tag::cpu_\n                            , (A0)\n                            , (scalar_< int_<A0> >)\n                            )\n  {\n    typedef  typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 exp) const\n    {\n      result_type result = One<result_type>();\n      result_type base = Ten<result_type>();\n      bool neg = exp < 0;\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_IMPLEMENT  ( tenpower_, tag::cpu_\n                            , (A0)\n                            , (scalar_< uint_<A0> >)\n                            )\n  {\n    typedef  typename dispatch::meta::as_floating<A0>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 exp) const\n    {\n      result_type result = One<result_type>();\n      result_type base = Ten<result_type>();\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#endif\n", "meta": {"hexsha": "191ad0cdd056c8d789b0ce1f3c668fe0bbb6636d", "size": 2249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/tenpower.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/tenpower.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/tenpower.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.1285714286, "max_line_length": 80, "alphanum_fraction": 0.5598043575, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5735945632548705}}
{"text": "// Copyright (c) 2020 Chris Richardson & Garth Wells\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"lattice.h\"\n#include \"cell.h\"\n#include \"elements/lagrange.h\"\n#include \"quadrature.h\"\n#include <Eigen/Dense>\n\nusing namespace basix;\n\nnamespace\n{\n//-----------------------------------------------------------------------------\nEigen::ArrayXd warp_function(int n, Eigen::ArrayXd& x)\n{\n  [[maybe_unused]] auto [pts, wts]\n      = quadrature::gauss_lobatto_legendre_line_rule(n + 1);\n  wts.setZero();\n\n  pts *= 0.5;\n  for (int i = 0; i < n + 1; ++i)\n    pts[i] += (0.5 - static_cast<double>(i) / static_cast<double>(n));\n\n  FiniteElement L = create_dlagrange(cell::type::interval, n);\n  Eigen::MatrixXd v = L.tabulate(0, x)[0];\n  return v * pts.matrix();\n}\n//-----------------------------------------------------------------------------\n\n} // namespace\n\n//-----------------------------------------------------------------------------\nEigen::ArrayXXd lattice::create(cell::type celltype, int n,\n                                lattice::type lattice_type, bool exterior)\n{\n  switch (celltype)\n  {\n  case cell::type::point:\n    return Eigen::ArrayXXd::Zero(1, 1);\n  case cell::type::interval:\n  {\n    if (n == 0)\n      return Eigen::ArrayXXd::Constant(1, 1, 0.5);\n\n    Eigen::ArrayXd x;\n    if (exterior)\n      x = Eigen::VectorXd::LinSpaced(n + 1, 0.0, 1.0);\n    else\n    {\n      const double h = 1.0 / static_cast<double>(n);\n      x = Eigen::VectorXd::LinSpaced(n - 1, h, 1.0 - h);\n    }\n\n    if (lattice_type == lattice::type::gll_warped)\n      x += warp_function(n, x);\n\n    return x;\n  }\n  case cell::type::quadrilateral:\n  {\n    if (n == 0)\n      return Eigen::ArrayXXd::Constant(1, 2, 0.5);\n\n    Eigen::ArrayXd r;\n    if (exterior)\n      r = Eigen::VectorXd::LinSpaced(n + 1, 0.0, 1.0);\n    else\n    {\n      const double h = 1.0 / static_cast<double>(n);\n      r = Eigen::VectorXd::LinSpaced(n - 1, h, 1.0 - h);\n    }\n\n    if (lattice_type == lattice::type::gll_warped)\n      r += warp_function(n, r);\n\n    const int m = r.size();\n    Eigen::ArrayX2d x(m * m, 2);\n    int c = 0;\n    for (int j = 0; j < m; ++j)\n      for (int i = 0; i < m; ++i)\n        x.row(c++) << r[i], r[j];\n\n    return x;\n  }\n  case cell::type::hexahedron:\n  {\n    if (n == 0)\n      return Eigen::ArrayXXd::Constant(1, 3, 0.5);\n\n    Eigen::ArrayXd r;\n    if (exterior)\n      r = Eigen::VectorXd::LinSpaced(n + 1, 0.0, 1.0);\n    else\n    {\n      const double h = 1.0 / static_cast<double>(n);\n      r = Eigen::VectorXd::LinSpaced(n - 1, h, 1.0 - h);\n    }\n    if (lattice_type == lattice::type::gll_warped)\n      r += warp_function(n, r);\n\n    const int m = r.size();\n    Eigen::ArrayXXd x(m * m * m, 3);\n    int c = 0;\n    for (int k = 0; k < m; ++k)\n      for (int j = 0; j < m; ++j)\n        for (int i = 0; i < m; ++i)\n          x.row(c++) << r[i], r[j], r[k];\n\n    return x;\n  }\n  case cell::type::triangle:\n  {\n    if (n == 0)\n      return Eigen::ArrayXXd::Constant(1, 2, 1.0 / 3.0);\n\n    // Warp points: see Hesthaven and Warburton, Nodal Discontinuous Galerkin\n    // Methods, pp. 175-180\n\n    const int b = exterior ? 0 : 1;\n\n    // Points\n    Eigen::ArrayX2d p((n - 3 * b + 1) * (n - 3 * b + 2) / 2, 2);\n\n    // Displacement from GLL points in 1D, scaled by 1/(r(1-r))\n    Eigen::ArrayXd r = Eigen::VectorXd::LinSpaced(2 * n + 1, 0.0, 1.0);\n    Eigen::ArrayXd wbar = warp_function(n, r);\n    const auto s = r.segment(1, 2 * n - 1);\n    wbar.segment(1, 2 * n - 1) /= s * (1 - s);\n\n    int c = 0;\n    for (int j = b; j < (n - b + 1); ++j)\n    {\n      for (int i = b; i < (n - b + 1 - j); ++i)\n      {\n        const int l = n - j - i;\n        const double x = r[2 * i];\n        const double y = r[2 * j];\n        const double a = r[2 * l];\n        p.row(c) << x, y;\n        if (lattice_type == lattice::type::gll_warped)\n        {\n          p(c, 0) += x * (a * wbar(n + i - l) + y * wbar(n + i - j));\n          p(c, 1) += y * (a * wbar(n + j - l) + x * wbar(n + j - i));\n        }\n\n        ++c;\n      }\n    }\n\n    return p;\n  }\n  case cell::type::tetrahedron:\n  {\n    if (n == 0)\n      return Eigen::ArrayXXd::Constant(1, 3, 0.25);\n\n    const int b = exterior ? 0 : 1;\n    Eigen::ArrayX3d p((n - 4 * b + 1) * (n - 4 * b + 2) * (n - 4 * b + 3) / 6,\n                      3);\n    Eigen::ArrayXd r = Eigen::VectorXd::LinSpaced(2 * n + 1, 0.0, 1.0);\n    Eigen::ArrayXd wbar = warp_function(n, r);\n    const auto s = r.segment(1, 2 * n - 1);\n    wbar.segment(1, 2 * n - 1) /= s * (1 - s);\n    int c = 0;\n    for (int k = b; k < (n - b + 1); ++k)\n    {\n      for (int j = b; j < (n - b + 1 - k); ++j)\n      {\n        for (int i = b; i < (n - b + 1 - j - k); ++i)\n        {\n          const int l = n - k - j - i;\n          const double x = r[2 * i];\n          const double y = r[2 * j];\n          const double z = r[2 * k];\n          const double a = r[2 * l];\n          p.row(c) << x, y, z;\n          if (lattice_type == lattice::type::gll_warped)\n          {\n            const double dx = x\n                              * (a * wbar(n + i - l) + y * wbar(n + i - j)\n                                 + z * wbar(n + i - k));\n            const double dy = y\n                              * (a * wbar(n + j - l) + z * wbar(n + j - k)\n                                 + x * wbar(n + j - i));\n            const double dz = z\n                              * (a * wbar(n + k - l) + x * wbar(n + k - i)\n                                 + y * wbar(n + k - j));\n            p(c, 0) += dx;\n            p(c, 1) += dy;\n            p(c, 2) += dz;\n          }\n\n          ++c;\n        }\n      }\n    }\n\n    return p;\n  }\n  case cell::type::prism:\n  {\n    if (n == 0)\n    {\n      Eigen::ArrayXXd x = Eigen::ArrayXXd::Constant(1, 3, 1.0 / 3.0);\n      x(0, 2) = 0.5;\n      return x;\n    }\n\n    const Eigen::ArrayXXd tri_pts\n        = lattice::create(cell::type::triangle, n, lattice_type, exterior);\n    const Eigen::ArrayXXd line_pts\n        = lattice::create(cell::type::interval, n, lattice_type, exterior);\n\n    Eigen::ArrayX3d x(tri_pts.rows() * line_pts.rows(), 3);\n    x.leftCols(2) = tri_pts.replicate(line_pts.rows(), 1);\n    for (int i = 0; i < line_pts.rows(); ++i)\n      x.block(i * tri_pts.rows(), 2, tri_pts.rows(), 1) = line_pts(i, 0);\n    return x;\n  }\n  case cell::type::pyramid:\n  {\n    if (n == 0)\n    {\n      Eigen::ArrayXXd x = Eigen::ArrayXXd::Constant(1, 3, 0.4);\n      x(0, 2) = 0.2;\n      return x;\n    }\n    else\n    {\n      const double h = 1.0 / static_cast<double>(n);\n\n      // Interpolate warp factor along interval\n      std::tuple<Eigen::ArrayXXd, Eigen::ArrayXd> pw\n          = quadrature::gauss_lobatto_legendre_line_rule(n + 1);\n      Eigen::VectorXd pts = std::get<0>(pw) * 0.5;\n      for (int i = 0; i < n + 1; ++i)\n        pts[i] += (0.5 - static_cast<double>(i) / static_cast<double>(n));\n      FiniteElement L = create_dlagrange(cell::type::interval, n);\n\n      // Get interpolated value at r in range [-1, 1]\n      auto w = [&](double r) {\n        Eigen::ArrayXd rr = Eigen::ArrayXd::Constant(1, 0.5 * (r + 1.0));\n        Eigen::VectorXd v = L.tabulate(0, rr)[0].row(0);\n        return v.dot(pts);\n      };\n\n      int b = (exterior == false) ? 1 : 0;\n      n -= b * 3;\n      int m = (n + 1) * (n + 2) * (2 * n + 3) / 6;\n      Eigen::ArrayX3d points(m, 3);\n      int c = 0;\n      for (int k = 0; k < n + 1; ++k)\n        for (int j = 0; j < n + 1 - k; ++j)\n          for (int i = 0; i < n + 1 - k; ++i)\n          {\n            double x = h * (i + b);\n            double y = h * (j + b);\n            double z = h * (k + b);\n\n            if (lattice_type == lattice::type::gll_warped)\n            {\n              // Barycentric coordinates of triangle in x-z plane\n              const double l1 = x;\n              const double l2 = z;\n              const double l3 = 1 - x - z;\n              // Barycentric coordinates of triangle in y-z plane\n              const double l4 = y;\n              const double l5 = z;\n              const double l6 = 1 - y - z;\n\n              // b1-b6 are the blending factors for each edge\n              double b1, f1, f2;\n              if (std::fabs(l1) < 1e-12)\n              {\n                b1 = 1.0;\n                f1 = 0.0;\n                f2 = 0.0;\n              }\n              else\n              {\n                b1 = 2.0 * l3 / (2.0 * l3 + l1) * 2.0 * l2 / (2.0 * l2 + l1);\n                f1 = l1 / (l1 + l4);\n                f2 = l1 / (l1 + l6);\n              }\n\n              // r1-r4 are the edge positions for each of the z>0 edges\n              // calculated so that they use the barycentric coordinates\n              // of the triangle, if the point lies on a triangular face.\n              // f1-f4 are face selecting functions, which blend between\n              // adjacent triangular faces\n              const double r1 = (l2 - l3) * f1 + (l5 - l6) * (1 - f1);\n              const double r2 = (l2 - l3) * f2 + (l5 - l4) * (1 - f2);\n\n              double b2;\n              if (std::fabs(l2) < 1e-12)\n                b2 = 1.0;\n              else\n                b2 = 2.0 * l3 / (2.0 * l3 + l2) * 2.0 * l1 / (2.0 * l1 + l2);\n\n              double b3, f3, f4;\n              if (std::fabs(l3) < 1e-12)\n              {\n                b3 = 1.0;\n                f3 = 0.0;\n                f4 = 0.0;\n              }\n              else\n              {\n                b3 = 2.0 * l2 / (2.0 * l2 + l3) * 2.0 * l1 / (2.0 * l1 + l3);\n                f3 = l3 / (l3 + l4);\n                f4 = l3 / (l3 + l6);\n              }\n\n              const double r3 = (l2 - l1) * f3 + (l5 - l6) * (1.0 - f3);\n              const double r4 = (l2 - l1) * f4 + (l5 - l4) * (1.0 - f4);\n\n              double b4;\n              if (std::fabs(l4) < 1e-12)\n                b4 = 1.0;\n              else\n                b4 = 2 * l6 / (2.0 * l6 + l4) * 2.0 * l5 / (2.0 * l5 + l4);\n\n              double b5;\n              if (std::fabs(l5) < 1e-12)\n                b5 = 1.0;\n              else\n                b5 = 2.0 * l6 / (2.0 * l6 + l5) * 2.0 * l4 / (2.0 * l4 + l5);\n\n              double b6;\n              if (std::fabs(l6) < 1e-12)\n                b6 = 1.0;\n              else\n                b6 = 2.0 * l4 / (2.0 * l4 + l6) * 2.0 * l5 / (2.0 * l5 + l6);\n\n              double dx = -b3 * b4 * w(r3) - b3 * b6 * w(r4) + b2 * w(l1 - l3);\n              double dy = -b1 * b6 * w(r2) - b3 * b6 * w(r4) + b5 * w(l4 - l6);\n              double dz = b1 * b4 * w(r1) + b1 * b6 * w(r2) + b3 * b4 * w(r3)\n                          + b3 * b6 * w(r4);\n\n              x += dx;\n              y += dy;\n              z += dz;\n            }\n\n            points.row(c++) << x, y, z;\n          }\n\n      return points;\n    }\n  }\n  default:\n    throw std::runtime_error(\"Unsupported cell for lattice\");\n  }\n}\n\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "973d48a267b3210e7732afc3722eadd7779e36ec", "size": 10795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/core/lattice.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/core/lattice.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/core/lattice.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": 30.069637883, "max_line_length": 79, "alphanum_fraction": 0.4226956925, "num_tokens": 3656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5735725475181814}}
{"text": "#pragma once\n#include <iostream>\n#include <array>\n#include <Eigen/Dense>\n#include \"Types/SFINAE.hpp\"\n\n///@file\n///@brief Contains the class \\ref mackey::Z_mod\n\nnamespace mackey {\n\t///////////////////////////////////\n\t///The class of Z/N coefficients where N is prime.\n\n\t///The operators are self explanatory. User must ensure that N is prime for division to work.\n\t/////////////////////////////////\n\ttemplate<int64_t N, typename T = int64_t>\n\tclass Z_mod {\n\tpublic:\n\t\tconstexpr static int64_t order = N; ///<The N of Z/N\n\t\tT x; ///< A modulo N number\n\t\tZ_mod() : x(0) {} ///<Default value 0\n\t\tZ_mod(bool x) : x(x) {} ///<Initialize from 0,1\n\t\tZ_mod(int x); ///<Initialize from int\n\t\tZ_mod(int64_t x); ///<Initialize from 64bit int\n\t\texplicit operator char() const;\n\t\texplicit operator short() const;\n\t\texplicit operator int() const;\n\t\texplicit operator int64_t() const;\n\t\texplicit operator unsigned char() const;\n\t\texplicit operator unsigned short() const;\n\t\texplicit operator unsigned int() const;\n\t\texplicit operator uint64_t() const;\n\t\tZ_mod<N, T> operator +(Z_mod<N, T> b) const;\n\t\tZ_mod<N, T> operator -(Z_mod<N, T> b) const;\n\t\tZ_mod<N, T>& operator +=(Z_mod<N, T> b);\n\t\tZ_mod<N, T>& operator -=(Z_mod<N, T> b);\n\t\tZ_mod<N, T>& operator *=(Z_mod<N, T> b);\n\t\tZ_mod<N, T>& operator /=(Z_mod<N, T> b);\n\t\tbool operator ==(Z_mod<N, T> a) const;\n\t\tbool operator !=(Z_mod<N, T> a) const;\n\t\tbool operator <=(Z_mod<N, T> a) const; ///<Needed for Eigen pruning; standard order on 0,...,N-1\n\t};\n\n\n\ttemplate<int64_t N, typename T>\n\tZ_mod<N, T> operator -(Z_mod<N, T> a);\n\n\ttemplate<int64_t N, typename T>\n\tZ_mod<N, T> operator *(Z_mod<N, T> a, Z_mod<N, T> b); //Eigen needs this to be non member\n\n\ttemplate<int64_t N, typename T>\n\tZ_mod<N, T> operator /(Z_mod<N, T> a, Z_mod<N, T> b);\n\n\t///The usual absolute value for integer and Z/N types\n\ttemplate<typename T>\n\tT abs(T a);\n\n\ttemplate<int64_t N, typename T> //Eigen needs this to be non member\n\tstd::ostream& operator<<(std::ostream& out, const Z_mod<N, T> a);\n\n\t///The \\f$\\mathbf Z/2\\f$ coefficients\n\tusing Z2 = Z_mod<2, bool>;\n}\n\n///See the Eigen documentation for this. \nnamespace Eigen {\n\tusing namespace mackey;\n\n\t///Specializing NumTraits to Z/nZ coefficients\n\ttemplate<int64_t N, typename T>\n\tstruct NumTraits<Z_mod<N, T>>\n\t{\n\t\ttypedef Z_mod<N, T> Real;\n\t\ttypedef Z_mod<N, T> Nested;\n\t\ttypedef int Literal;\n\t\tenum {\n\t\t\tIsComplex = 0,\n\t\t\tIsInteger = 0,\n\t\t\tIsSigned = 0,\n\t\t\tRequireInitialization = 0,\n\t\t\tReadCost = 1,\n\t\t\tAddCost = 1,\n\t\t\tMulCost = 1\n\t\t};\n\t\tstatic inline Z_mod<N, T> dummy_precision() { return Z_mod<N, T>(0); }\n\t\tstatic inline int digits10() { return 0; }\n\t};\n}\n\n#include \"impl/Z_n.ipp\"\n", "meta": {"hexsha": "2b24e03b8e817943c7c4f8b1cfb78ab26a4b9eec", "size": 2652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/Coefficients/Z_n.hpp", "max_stars_repo_name": "NickG-Math/Mackey", "max_stars_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_stars_repo_licenses": ["MIT"], "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/Coefficients/Z_n.hpp", "max_issues_repo_name": "NickG-Math/Mackey", "max_issues_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_issues_repo_licenses": ["MIT"], "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/Coefficients/Z_n.hpp", "max_forks_repo_name": "NickG-Math/Mackey", "max_forks_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_forks_repo_licenses": ["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.1428571429, "max_line_length": 98, "alphanum_fraction": 0.6447963801, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.5735725378976027}}
{"text": "#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <random>\n#include <string>\n#include <iomanip>\n#include <chrono>\n\n#include <Eigen/Eigen>\n#include \"sparse_gemm_problems.h\"\n\nusing namespace Eigen;\n\n#ifndef ITERS\n#define ITERS 10\n#endif\n\ntemplate<typename T, int U = ColMajor>\nMatrix<T, Dynamic, Dynamic, U> generate_random_matrix(int rows, int cols) {\n    return Matrix<T, Dynamic, Dynamic, U>::Random(rows, cols);\n}\n\ntemplate<typename T> \nMatrix<T, Dynamic, 1> generate_random_vector(int entries) {\n    return Matrix<T, Dynamic, 1>::Random(entries);\n}\n\ntemplate<typename T, int U>\nstd::tuple <int, int> time_sparse_gemv(const SparseMatrix<T, U>& sp_A, const Matrix<T, Dynamic, Dynamic, U>& A, const Matrix<T, Dynamic, 1>& B, Matrix<T, Dynamic, 1>& C) {\n\n    // Try dense-dense multiplication\n    auto start = std::chrono::steady_clock::now();\n    for (int i = 0; i < ITERS; ++i) {\n        C = A * B;\n        C[0]++;  // dummy instruction to prevent optimizing away prev line\n    }\n    auto end = std::chrono::steady_clock::now();\n    int d_time = static_cast<int>(std::chrono::duration<double, std::micro>(end - start).count() / ITERS);\n\n    // Try sparse-dense multiplication\n    start = std::chrono::steady_clock::now();\n    for (int i = 0; i < ITERS; ++i) {\n        C = sp_A * B;\n        C[0]++;  // dummy instruction to prevent optimizing away prev line\n    }\n    end = std::chrono::steady_clock::now();\n    int sp_time = static_cast<int>(std::chrono::duration<double, std::micro>(end - start).count() / ITERS);\n    return std::tuple<int, int>(sp_time, d_time);\n}\n\ntemplate<typename T, int U, int V, int W>\nstd::tuple <int, int> time_sparse_gemm(const SparseMatrix<T, U>& sp_A, const Matrix<T, Dynamic, Dynamic, U>& A, const Matrix<T, Dynamic, Dynamic, V>& B, Matrix<T, Dynamic, Dynamic, W>& C) {\n\n    // Try dense-dense multiplication\n    auto start = std::chrono::steady_clock::now();\n    for (int i = 0; i < ITERS; ++i) {\n        C = A * B;\n        C(0,0)++;  // dummy instruction to prevent optimizing away prev line\n    }\n    auto end = std::chrono::steady_clock::now();\n    int d_time = static_cast<int>(std::chrono::duration<double, std::micro>(end - start).count() / ITERS);\n\n    // Try sparse-dense multiplication\n    start = std::chrono::steady_clock::now();\n    for (int i = 0; i < ITERS; ++i) {\n        C = sp_A * B;\n        C(0,0)++;  // dummy instruction to prevent optimizing away prev line\n    }\n    end = std::chrono::steady_clock::now();\n    int sp_time = static_cast<int>(std::chrono::duration<double, std::micro>(end - start).count() / ITERS);\n    return std::tuple<int, int>(sp_time, d_time);\n}\n\n\ntemplate<typename T>\nstd::tuple<int, int> time_sparse_bench_helper(int m, int n, int k, float sparsity, std::default_random_engine & e, std::uniform_real_distribution<double> & rng) {\n    \n    const int U = RowMajor;\n\n    // Note: We've determined empirically that B,C in ColMajor is best for\n    // both sparse and dense gemm implementations.\n    const int V = ColMajor;\n    const int W = ColMajor;\n\n    auto A = generate_random_matrix<T, U>(m, k);\n    for (int j = 0; j < k; ++j) {\n        for (int i = 0; i < m; ++i) {\n            if (rng(e) < sparsity) {\n                A(i, j) = 0;\n            }\n        }\n    }\n    SparseMatrix<T, U> sp_A = A.sparseView();\n\n    if (n == 1) {\n        auto B = generate_random_vector<T>(k);\n        auto C = generate_random_vector<T>(m);\n        return time_sparse_gemv<T, U>(sp_A, A, B, C);\n    }\n    else {\n        auto B = generate_random_matrix<T, V>(k, n);\n        auto C = generate_random_matrix<T, W>(m, n);\n        return time_sparse_gemm<T, U, V, W>(sp_A, A, B, C);\n    }\n}\n\nint main() {\n\n    // Set up RNG\n    std::random_device r;\n    std::default_random_engine e(r());\n    std::uniform_real_distribution<double> rng(0, 1);\n\n    std::cout << std::setw(30) << \"Times\" << std::endl;\n    std::cout << std::setfill('-') << std::setw(110) << \"-\" << std::endl;\n    std::cout << std::setfill(' ');\n    std::cout << \"    m       n      k      a_t    b_t    sparsity  precision  sparse time (usec) dense time (usec)   speedup \" << std::endl;\n\n    std::vector<std::string> types = {\"uint8_t\", \"float\"};\n\n    for (const auto &type_name : types) {\n\n        for (const auto &problem : inference_device_set) {\n\n            int m,n,k;\n            bool a_t, b_t;\n            float sparsity;\n            \n            std::tie(m, n, k, a_t, b_t, sparsity) = problem;\n\n            std::cout << std::setw(7) << m;\n            std::cout << std::setw(7) << n;\n            std::cout << std::setw(7) << k;\n            std::cout << std::setw(7) << a_t ? \"t\" : \"n\";\n            std::cout << std::setw(7) << b_t ? \"t\" : \"n\";\n            std::cout << std::setw(11) << sparsity;\n            std::cout << std::setw(12) << type_name;\n\n            int sp_time, d_time;\n\n            if (type_name == \"uint8_t\") {\n                std::tie(sp_time, d_time) = time_sparse_bench_helper<std::uint8_t>(m, n, k, sparsity, e, rng);\n            } else if (type_name == \"float\") {\n                std::tie(sp_time, d_time) = time_sparse_bench_helper<float>(m, n, k, sparsity, e, rng);\n            } else {\n                throw std::runtime_error(\"Unsupported type_name\");\n            }\n\n            std::cout << std::setw(15) << sp_time;\n            std::cout << std::setw(15) << d_time;\n            std::cout << std::setw(20) << float(d_time)/sp_time;\n            std::cout << std::endl;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d54ed5c1152ad2b8371f0006337c119daf732bf9", "size": 5471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/arm/sparse_bench.cpp", "max_stars_repo_name": "marsupialtail/mydeepbench", "max_stars_repo_head_hexsha": "eb63e97361b9bca95dd7e167d282fe75bc3e2d0f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1048.0, "max_stars_repo_stars_event_min_datetime": "2016-09-26T21:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:23:23.000Z", "max_issues_repo_path": "code/arm/sparse_bench.cpp", "max_issues_repo_name": "marsupialtail/mydeepbench", "max_issues_repo_head_hexsha": "eb63e97361b9bca95dd7e167d282fe75bc3e2d0f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 108.0, "max_issues_repo_issues_event_min_datetime": "2016-09-30T06:44:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T09:44:12.000Z", "max_forks_repo_path": "code/arm/sparse_bench.cpp", "max_forks_repo_name": "marsupialtail/mydeepbench", "max_forks_repo_head_hexsha": "eb63e97361b9bca95dd7e167d282fe75bc3e2d0f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 260.0, "max_forks_repo_forks_event_min_datetime": "2016-09-26T20:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T06:32:00.000Z", "avg_line_length": 34.6265822785, "max_line_length": 189, "alphanum_fraction": 0.5761286785, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.5733267622202944}}
{"text": "#include <unistd.h>\t// sleep\n#include <armadillo>\n#include \"Functions.h\"\n\nusing namespace arma;\nusing namespace std;\n\n\n\n/* Description: Parallel Stochastic Iterative Hard Thresholding (StoIHT) algorithm \n to approximate the vector x from measurements u = A*x.\npublication:  Linear Convergence of Stochastic Iterative Greedy Algorithms with Sparse Constraints\nhttps://arxiv.org/abs/1407.0088\n*/\nvec parallel_Sto_IHT(const mat A, const vec y, const int sparsity, const vec prob_vec,\n\t\tconst unsigned int max_iter, const double gamma, const double tol, \n\t\tunsigned int &num_iters, const simulation_parameters simulation_params){\n\t// signal parameters\n\tconst unsigned int sig_dim = A.n_cols;\n\tconst unsigned int meas_num = A.n_rows;\n\tconst unsigned int num_block = prob_vec.n_elem;\n\tconst unsigned int block_size = meas_num/num_block;\n\n\t// initialization of variables that are shared among cores\n\tvec x_hat(sig_dim,fill::zeros);\t// estimation of the signal\n\tbool done = false;\t\t// flag to check the convergence criteria\n\tunsigned int i = 0;\t\t// total number of iterations\n\n\t// parallel section of the code starts here\n\t#pragma omp parallel num_threads(simulation_params.num_cores)\n\t{\n\t\n\t// initializaiotn of variables that are local to each core\n\tvec x_hat_local(sig_dim,fill::zeros);\n\tunsigned int selected_block,first_ind_block,last_ind_block;\n\tmat A_block;\t\t\t// submatrix of A\n\tvec y_block,gradient,b;\t\n\tuvec sorted_ind,est_supp;\n\n\t// iterations to find the solutions\n\twhile(!done){\n\t\t// master thread uses the tally vector to check the convergence criteria\n\t\tif (omp_get_thread_num() == 0 ){\n\t\t\t// check exit criteria\n\t\t\tif (norm (y - A*x_hat) < tol || i >= max_iter){\n\t\t\t\tdone = true;\t// the flag 'done' is shared among the cores\n\t\t\t}\n\t\t\tif (omp_get_num_threads()  > 1){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\ti++;\n\t\t// randomize\n\t\tselected_block = floor(randu()*num_block);\n\t\tfirst_ind_block = block_size*selected_block;\n\t\tlast_ind_block = block_size*(selected_block+1)-1;\n\n\t\t// Proxy\n\t\tA_block = A.rows(first_ind_block,last_ind_block);\n\t\ty_block = y.subvec(first_ind_block,last_ind_block);\n\t\t#pragma omp critical\n\t\t{x_hat_local = x_hat;\t}\t// read the global estimate while memory is locked\n\n\t\tgradient = -2 * A_block.t() *\t(y_block - A_block*x_hat_local);\n\t\tb = x_hat_local - gradient * gamma/(num_block*prob_vec(selected_block));\n\t\t\n\t\t// Identify\n\t\tsorted_ind = sort_index(abs(b),\"descend\");\n\t\test_supp = sorted_ind(span(0,sparsity - 1));\n\n\t\t// Estimate\n\t\tx_hat_local.zeros();\n\t\tx_hat_local(est_supp) = b(est_supp);\n\t\t\n\t\t#pragma omp critical\n\t\t{x_hat = x_hat_local;}\t//write the global estimate while memory is locked\n\t\t\n\n\t\t\n\t}\n\t}\n\t// parallel section of the code ends here\n\tnum_iters = i;\n\treturn x_hat;\n}\n\n/* Asynchronous StoIHT Iteration\nAlgorithm 2 in An Asynchronous Parallel Approach to Sparse Recovery\nhttps://arxiv.org/abs/1701.03458*/\n\nuvec Sto_IHT_async_iteration(vec &x_hat,const vec &tally,const mat &A,const vec &y,\n \t\t\tconst int sparsity, const vec prob_vec, const double gamma){\n\t// randomize\n\tconst unsigned int num_block = prob_vec.n_elem;\n\tconst unsigned int block_size = y.n_elem / num_block;\n\tconst unsigned int selected_block = floor(randu()*num_block);\n\tconst unsigned int first_ind_block = block_size*selected_block;\n\tconst unsigned int last_ind_block = block_size*(selected_block+1)-1;\n\n\t// Proxy\n\tconst mat A_block = A.rows(first_ind_block,last_ind_block);\n\tconst vec y_block = y.subvec(first_ind_block,last_ind_block);\n\tconst vec gradient = -2 * A_block.t() *\t(y_block - A_block*x_hat);\n\tconst vec b = x_hat - gradient * gamma/(num_block*prob_vec(selected_block));\n\t\n\tx_hat.zeros();  // this variable is local to each core. NOTE: passed by reference\n\t// Identify using b (local)\n\tuvec sorted_ind = sort_index(abs(b),\"descend\"); \n\tconst uvec est_supp_local = sorted_ind(span(0,sparsity - 1)); \n\t// Estimate using b (local)\t\t\n\tx_hat(est_supp_local) = b(est_supp_local);\n\n\t// Identify using tally (collective)\n\tsorted_ind = sort_index(tally,\"descend\"); \n\tconst uvec est_supp_collective = sorted_ind(span(0,sparsity - 1));  \n\t// Estimate using tally (collective)\n\tx_hat(est_supp_collective) = b(est_supp_collective);\t\n\n\treturn \test_supp_local;\n}\n\n\nvoid update_tally(vec &tally,const uvec est_supp_local,const uvec prev_est_supp,const unsigned int iter_local){\n\t/* update the tally score according the rules in:\n\tAn Asynchronous Parallel Approach to Sparse Recovery\n\thttps://arxiv.org/abs/1701.03458*/\n\ttally(est_supp_local) += iter_local; \n\tif (iter_local >= 2){\n\t\ttally(prev_est_supp) -= iter_local-1;\n\t}\n\treturn;\n}\n\n\n/* Description: Parallel Stochastic Iterative Hard Thresholding (StoIHT) algorithm with tally score to approximate the vector x from measurements u = A*x.\nPublication: An Asynchronous Parallel Approach to Sparse Recovery\nhttps://arxiv.org/abs/1701.03458*/\n\nvec tally_Sto_IHT(const mat &A, const vec &y, const int sparsity, const vec prob_vec,\n\t\tconst unsigned int max_iter, const double gamma,const double tol, \n\t\tunsigned int &num_iters, const simulation_parameters simulation_params){\n\tuvec slow_cores;\n\tset_slow_cores(slow_cores, simulation_params);\n\n\tconst unsigned int sig_dim = A.n_cols;\n\n\t// initialization of variables that are shared among cores\n\tvec tally(sig_dim,fill::zeros);\t\t// vector of tally scores\n\tvec x_hat_total(sig_dim,fill::zeros);\t// estimation of the signal\n\tbool done = false;\t\t\t// flag to check the convergence criteria\n\tunsigned int i = 0;\t\t\t// total number of iterations\n\n\t// parallel section of the code starts here\n\t#pragma omp parallel num_threads(simulation_params.num_cores)\n\t{\n\t//#pragma omp single // a single core executes the following line\n\n\t// initializaiotn of variables that are local to each core\n\tuvec prev_est_supp;\t\t\t// estimated support in previous iteration\n\tvec x_hat_local(sig_dim,fill::zeros);  \t// this is local to each core\n\tunsigned int iter_local = 0;\t\t// number of iteration for this core\n\n\t// iterations to find the solutions\n\twhile(!done){\n\t\t// master thread uses the tally vector to check the convergence criteria\n\t\tif (omp_get_thread_num() == 0){\t\n\t\t\tconst uvec sorted_ind = sort_index(abs(tally),\"descend\");\t\n\t\t\tconst uvec est_supp = sorted_ind(span(0,sparsity - 1));\n\t\t\tconst mat A_supp = A.cols(est_supp);\n\t\t\tx_hat_local.zeros();\n\t\t\tx_hat_local(est_supp) = solve(A_supp,y);\n\t\t\tif (norm (y - A*x_hat_local) < tol || i >= max_iter){\n\t\t\t\tx_hat_total = x_hat_local;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\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\n\t\ti++;\n\t\titer_local++;\n\n\t\t// update the local estimate of the support\n\t\tuvec est_supp_local;\n        try{\n        est_supp_local = Sto_IHT_async_iteration(x_hat_local, tally, A, y, \t\n            sparsity, prob_vec, gamma);\n        }\n        catch(std::logic_error)\n        {\n            // algorithm did not converge\n            i = max_iter;\n            done = true;\n        }\n\t\t// Update Tally\n        update_tally(tally,est_supp_local,prev_est_supp,iter_local);\n\n\t\tprev_est_supp = est_supp_local;\t\t\n\t}\n\t}\n\t// parallel section of the code ends here\n\t//cout << endl;\n\tnum_iters = i;\n\treturn x_hat_total;\n}\n\n", "meta": {"hexsha": "1db0d0a30e3f42123da8152243876ad96a8f4ed3", "size": 7167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sto_IHT.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": "Sto_IHT.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": "Sto_IHT.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": 33.9668246445, "max_line_length": 154, "alphanum_fraction": 0.7281986884, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5733140409502249}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n#include <boost/timer.hpp>\n\n// for sophus\n#include <sophus/se3.hpp>\n\nusing Sophus::SE3d;\n\n// for eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"plot.h\"\n\nusing namespace cv;\n\n\n/**\n * Dataset from:\n * \n *   http://rpg.ifi.uzh.ch/datasets/remode_test_data.zip\n * \n * */\n\n\n// ------------------------------------------------------------------\n// parameters\nconst int boarder = 20;\nconst int width = 640;\nconst int height = 480;\nconst double fx = 481.2f;\nconst double fy = -480.0f;\nconst double cx = 319.5f;\nconst double cy = 239.5f;\nconst int ncc_window_size = 3;\nconst int ncc_area = (2 * ncc_window_size + 1) * (2 * ncc_window_size + 1);\nconst double min_cov = 0.1;\nconst double max_cov = 10;\nconst double epsilon = 1e-10;\n// ------------------------------------------------------------------\n\n\n\ninline double getBilinearInterpolatedValue_eigen(const Mat &img, const Eigen::Vector2d &pt) {\n    uchar *d = &img.data[int(pt[1]) * img.step + int(pt[0])];\n    double xx = pt[0] - floor(pt[0]);\n    double yy = pt[1] - floor(pt[1]);\n    return ((1 - xx) * (1 - yy) * double(d[0]) +\n            xx * (1 - yy) * double(d[1]) +\n            (1 - xx) * yy * double(d[img.step]) +\n            xx * yy * double(d[img.step + 1])) / 255.0;\n}\n\n\n\n// ------------------------------------------------------------------\n\ninline Vector3d px2cam(const Vector2d& px) {\n    return Vector3d(\n        (px(0, 0) - cx) / fx,\n        (px(1, 0) - cy) / fy,\n        1\n    );\n}\n\ninline Vector2d cam2px(const Vector3d& p_cam) {\n    return Vector2d(\n        p_cam(0, 0) * fx / p_cam(2, 0) + cx,\n        p_cam(1, 0) * fy / p_cam(2, 0) + cy\n    );\n}\n\ninline bool inside(const Vector2d &pt) {\n    return pt(0, 0) >= boarder && pt(1, 0) >= boarder\n           && pt(0, 0) + boarder < width && pt(1, 0) + boarder <= height;\n}\n\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    vector<SE3d> &poses,\n    cv::Mat &ref_depth\n);\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate);\n// ------------------------------------------------------------------\n\n\ndouble ZNCC(const cv::Mat& im1, const Eigen::Vector2d& pt1, const cv::Mat& im2, Eigen::Vector2d& pt2)\n{\n    // no need to consider block partly outside because of boarder\n    // std::vector<double> v1(ncc_area, 0.0), v2(ncc_area, 0.0); // much slower\n    double v1[ncc_area], v2[ncc_area];\n    double s1 = 0.0, s2 = 0.0;\n    int idx = 0;\n    for (int i = -ncc_window_size; i <= ncc_window_size; ++i)\n    {\n        for (int j = -ncc_window_size; j <= ncc_window_size; ++j)\n        {\n            double val_1 = static_cast<double>(im1.at<uchar>(pt1.y()+i, pt1.x()+j)) / 255;\n            Eigen::Vector2d temp_p2 = pt2;\n            temp_p2[0] += j;\n            temp_p2[1] += i;\n            double val_2 = getBilinearInterpolatedValue_eigen(im2, temp_p2);\n\n            s1 += val_1;\n            s2 += val_2;\n            v1[idx] = val_1;\n            v2[idx] = val_2;\n            ++idx;\n        }\n    }\n\n    double mean_1 = s1 / ncc_area;\n    double mean_2 = s2 / ncc_area;\n\n    double numerator = 0.0;\n    double den1 = 0.0, den2 = 0.0;\n    for (int i = 0; i < ncc_area; ++i)\n    {\n        double zv1 = v1[i] - mean_1;\n        double zv2 = v2[i] - mean_2;\n        numerator += zv1*zv2;\n        den1 += zv1 * zv1;\n        den2 += zv2 * zv2;\n    }\n    auto zncc =  numerator / (std::sqrt(den1 * den2 + epsilon));\n    // std::cout << \"zncc = \" << zncc << \"\\n\";\n    return zncc;\n}\n\nbool epipolar_search(const cv::Mat& ref, const cv::Mat& cur, const Sophus::SE3d& Tcr, const Eigen::Vector2d& pt, double depth_mu, double depth_sigma2, Eigen::Vector2d& best_pc, Eigen::Vector2d& epipolar_dir)\n{\n    double depth_sigma = std::sqrt(depth_sigma2);\n    double dmax = depth_mu + 3 * depth_sigma;\n    double dmin = depth_mu - 3 * depth_sigma;\n    dmin = std::max(0.1, dmin);\n\n    Eigen::Vector3d pn((pt.x()-cx) / fx, (pt.y() - cy) / fy, 1.0);\n    pn.normalize();\n    Eigen::Vector3d P_max = pn * dmax;\n    Eigen::Vector3d P_min = pn * dmin;\n    Eigen::Vector3d P_mu = pn * depth_mu;\n\n\n    Eigen::Vector2d pc_max = cam2px(Tcr * P_max);\n    Eigen::Vector2d pc_min = cam2px(Tcr * P_min);\n    Eigen::Vector2d pc_mu = cam2px(Tcr * P_mu);\n\n    Eigen::Vector2d epipolar_line = pc_max - pc_min;\n    epipolar_dir = epipolar_line.normalized();\n\n    double step = 0.7;\n    int nb_samples = std::ceil(epipolar_line.norm() / step);\n\n\n    double half_range = 0.5 * epipolar_line.norm();\n    if (half_range > 100) half_range = 100;\n\n    Eigen::Vector2d p = pc_min;\n    double best_zncc = -1.0;\n    best_pc = pc_mu;\n\n\n    // for (int i = 0; i < nb_samples; ++i)\n    for (double l = -half_range; l<= half_range; l+= 0.7)\n    {\n        Eigen::Vector2d p = pc_mu + l * epipolar_dir;\n\n        if (p.x() < boarder || p.x() >= width-boarder || p.y() < boarder || p.y() >= height-boarder)\n            continue; // p is outside the cur image\n\n        double zncc = ZNCC(ref, pt, cur, p);\n        if (zncc > best_zncc)\n        {\n            best_zncc = zncc;\n            best_pc = p;\n        }\n\n        // p += epipolar_dir * step;\n    }\n\n    // std::cout << best_zncc << \"\\n\";\n    if (best_zncc < 0.85)\n        return false;\n    else\n        return true;\n}\n\nvoid update_depth_filter(const Eigen::Vector2d& pr, const Eigen::Vector2d& pc, const Sophus::SE3d& Tcr, const Eigen::Vector2d& epipolar_dir, cv::Mat& depth, cv::Mat& cov2)\n{\n    Sophus::SE3d Trc = Tcr.inverse();\n\n    Eigen::Vector3d fr = px2cam(pr);\n    fr.normalize();\n    Eigen::Vector3d fc = px2cam(pc);\n    fc.normalize();\n    Eigen::Vector3d f2 = Trc.so3() * fc;\n    Eigen::Vector3d trc = Trc.translation();\n\n\n    // Solve the system of equation for triangulating depth\n    Eigen::Matrix2d A;\n    Eigen::Vector2d b;\n    A(0, 0) = fr.dot(fr);\n    A(0, 1) = -fr.dot(f2);\n    A(1, 0) = f2.dot(fr);\n    A(1, 1) = -f2.dot(f2);\n    b[0] = fr.dot(trc);\n    b[1] = f2.dot(trc);\n    Eigen::Vector2d res = A.inverse() * b;\n    Eigen::Vector3d P1 = fr * res[0];\n    Eigen::Vector3d P2 = trc + fc * res[1];\n    Eigen::Vector3d P_est = (P1 + P2) * 0.5;\n    double depth_obs = P_est.norm(); //depth obs\n\n    // Estimate depth uncertainty \n    Eigen::Vector3d P = fr * depth_obs;\n    Eigen::Vector3d a = P - trc;\n    Eigen::Vector3d t = trc.normalized();\n    double alpha = std::acos(fr.dot(t));\n    double beta = std::acos(a.normalized().dot(-t));\n    Eigen::Vector2d pc2 = pc + epipolar_dir;\n    Eigen::Vector3d fc2 = px2cam(pc2);\n    fc2.normalize();\n    double beta_2 = std::acos(fc2.dot(-t));\n    double gamma = M_PI - alpha - beta_2;\n    double d_noise = trc.norm() * std::sin(beta_2) / std::sin(gamma); // sinus law\n    double sigma_obs = depth_obs - d_noise;\n    double sigma2_obs = sigma_obs * sigma_obs; // sigma2 obs\n\n    // Depth fusion\n    double d = depth.at<double>(static_cast<int>(pr.y()), static_cast<int>(pr.x()));\n    double sigma2 = cov2.at<double>(static_cast<int>(pr.y()), static_cast<int>(pr.x()));\n\n    double d_fused = (sigma2_obs * d + sigma2 * depth_obs) / (sigma2 + sigma2_obs);\n    double sigma2_fused = (sigma2 * sigma2_obs) / (sigma2 + sigma2_obs);\n\n    depth.at<double>(static_cast<int>(pr.y()), static_cast<int>(pr.x())) = d_fused;\n    cov2.at<double>(static_cast<int>(pr.y()), static_cast<int>(pr.x())) = sigma2_fused;\n}\n\n\nvoid update(const cv::Mat& ref, const cv::Mat& cur, const Sophus::SE3d& Tcr, cv::Mat &depth, cv::Mat &cov2)\n{\n    Eigen::Vector2d pc;\n    Eigen::Vector2d epipolar_dir;\n    for (int j = boarder; j < width-boarder; ++j)\n    {\n        for (int i = boarder; i < height-boarder; ++i)\n        {\n            double depth_mu = depth.at<double>(i, j);\n            double depth_sigma2 = cov2.at<double>(i, j);\n            if (depth_sigma2 < min_cov || depth_sigma2 > max_cov) \n                continue;\n            Eigen::Vector2d pr(j, i);\n            bool found = epipolar_search(ref, cur, Tcr, pr, depth_mu, depth_sigma2, pc, epipolar_dir);\n            if (!found)\n                continue;\n\n            // showEpipolarMatch(ref, cur, pr, pc);\n\n            update_depth_filter(pr, pc, Tcr, epipolar_dir, depth, cov2);\n        }\n    }\n    // std::cout << depth << \"\\n\";\n\n}\n\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        cout << \"Usage: dense_mapping path_to_test_dataset\" << endl;\n        return -1;\n    }\n\n    // Read dataset\n    vector<string> color_image_files;\n    vector<SE3d> poses_TWC;\n    Mat ref_depth;\n    bool ret = readDatasetFiles(argv[1], color_image_files, poses_TWC, ref_depth);\n    if (ret == false) {\n        cout << \"Reading image files failed!\" << endl;\n        return -1;\n    }\n    cout << \"read total \" << color_image_files.size() << \" files.\" << endl;\n\n    // Initial depth image\n    Mat ref = imread(color_image_files[0], 0); // gray-scale image\n    SE3d pose_ref_TWC = poses_TWC[0];\n    double init_depth = 3.0;\n    double init_cov2 = 3.0;\n    Mat depth(height, width, CV_64F, init_depth);\n    Mat depth_cov2(height, width, CV_64F, init_cov2);\n\n    for (int index = 1; index < color_image_files.size(); index++) {\n        cout << \"*** loop \" << index << \" ***\" << endl;\n        Mat curr = imread(color_image_files[index], 0);\n        if (curr.data == nullptr) continue;\n        SE3d pose_curr_TWC = poses_TWC[index];\n        SE3d pose_T_C_R = pose_curr_TWC.inverse() * pose_ref_TWC;   // T_C_W * T_W_R = T_C_R\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        update(ref, curr, pose_T_C_R, depth, depth_cov2);\n        chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n        auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n        std::cout << \"Time used: \" << time_used.count() << \"s\\n\";\n        evaludateDepth(ref_depth, depth);\n        plotDepth(ref_depth, depth);\n        plotCur(curr);\n    }\n\n    cout << \"estimation returns, saving depth map ...\" << endl;\n    imwrite(\"depth.png\", depth);\n    cout << \"done.\" << endl;\n\n    return 0;\n}\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    std::vector<SE3d> &poses,\n    cv::Mat &ref_depth) {\n    ifstream fin(path + \"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if (!fin) return false;\n\n    while (!fin.eof()) {\n        // 数据格式：图像文件名 tx, ty, tz, qx, qy, qz, qw ，注意是 TWC 而非 TCW\n        string image;\n        fin >> image;\n        double data[7];\n        for (double &d:data) fin >> d;\n\n        color_image_files.push_back(path + string(\"/images/\") + image);\n        poses.push_back(\n            SE3d(Quaterniond(data[6], data[3], data[4], data[5]),\n                 Vector3d(data[0], data[1], data[2]))\n        );\n        if (!fin.good()) break;\n    }\n    fin.close();\n\n    // load reference depth\n    fin.open(path + \"/depthmaps/scene_000.depth\");\n    ref_depth = cv::Mat(height, width, CV_64F);\n    if (!fin) return false;\n    for (int y = 0; y < height; y++)\n        for (int x = 0; x < width; x++) {\n            double depth = 0;\n            fin >> depth;\n            ref_depth.ptr<double>(y)[x] = depth / 100.0;\n        }\n\n    return true;\n}\n\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate) {\n    double ave_depth_error = 0;\n    double ave_depth_error_sq = 0;\n    int cnt_depth_data = 0;\n    for (int y = boarder; y < depth_truth.rows - boarder; y++)\n        for (int x = boarder; x < depth_truth.cols - boarder; x++) {\n            double error = depth_truth.ptr<double>(y)[x] - depth_estimate.ptr<double>(y)[x];\n            ave_depth_error += error;\n            ave_depth_error_sq += error * error;\n            cnt_depth_data++;\n        }\n    ave_depth_error /= cnt_depth_data;\n    ave_depth_error_sq /= cnt_depth_data;\n\n    cout << \"Average squared error = \" << ave_depth_error_sq << \", average error: \" << ave_depth_error << endl;\n}\n", "meta": {"hexsha": "732db790e68754376b03b15d226d3be50426f101", "size": 11984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_mono/dense_mapping_custom.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch12/dense_mono/dense_mapping_custom.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch12/dense_mono/dense_mapping_custom.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8865979381, "max_line_length": 207, "alphanum_fraction": 0.5733477971, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5733140399341539}}
{"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_TCC_\n#define NTLFP_TCC_\n\n#include <cassert>\n#include <cstdlib>\n#include <cmath>\n#include <NTL/ZZ.h>\n\n#include <libff/algebra/fields/fp_aux.tcc>\n#include <libff/algebra/fields/field_utils.hpp>\n\nnamespace libsnark {\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>::NTLFp_model()\n{\n    NTL::ZZ_p::init(mod_zz());\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>::NTLFp_model(long x)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value = x;\n}\n\ntemplate <unsigned long modulus>\nNTLFp_model<modulus>::NTLFp_model(const NTLFp_model &other)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value = other.value;\n}\n\ntemplate<unsigned long modulus>\nbool NTLFp_model<modulus>::operator==(const NTLFp_model& other) const\n{\n    return (this->value == other.value);\n}\n\ntemplate<unsigned long modulus>\nbool NTLFp_model<modulus>::operator!=(const NTLFp_model& other) const\n{\n    return (this->value != other.value);\n}\n\ntemplate<unsigned long modulus>\nbool NTLFp_model<modulus>::is_zero() const\n{\n    return NTL::IsZero(this->value);\n}\n\ntemplate<unsigned long modulus>\nvoid NTLFp_model<modulus>::print() const\n{\n    std::cout << *this;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::zero()\n{\n    NTL::ZZ_p::init(mod_zz());\n    NTLFp_model<modulus> z(NTL::ZZ_p::zero());\n    return z;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::one()\n{\n    NTL::ZZ_p::init(mod_zz());\n    NTLFp_model<modulus> o(NTL::ZZ_p::zero() + 1);\n    return o;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator+=(const NTLFp_model<modulus>& other)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value += other.value;\n    return *this;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator-=(const NTLFp_model<modulus>& other)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value -= other.value;\n    return *this;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator*=(const NTLFp_model<modulus>& other)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value *= other.value;\n    return *this;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator^=(const NTLFp_model<modulus>& other)\n{\n    return this^=other.as_long();\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator^=(const libff::bigint<1>& pwr)\n{\n    return this^=pwr.as_ulong();\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::operator^=(const unsigned long pwr)\n{\n    NTL::ZZ_p::init(mod_zz());\n    this->value = NTL::power(this->value, pwr);\n    return (*this);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator+(const NTLFp_model<modulus>& other) const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r += other);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator-(const NTLFp_model<modulus>& other) const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r -= other);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator*(const NTLFp_model<modulus>& other) const\n{\n    NTLFp_model<modulus> r;\n    NTL::mul(r.value, value, other.value);\n    r.value = value * other.value;\n    return r;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator^(const NTLFp_model<modulus>& other) const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r ^= other);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator^(const unsigned long pwr) const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r ^= pwr);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator^(const libff::bigint<1>& pwr) const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r ^= pwr.as_ulong());\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::operator-() const\n{\n    NTLFp_model<modulus> r(modulus - this->value);\n    return r;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::squared() const\n{\n    NTLFp_model<modulus> r(*this);\n    return (r *= r);\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus>& NTLFp_model<modulus>::invert()\n{\n    NTL::ZZ_p inverse = 1 / this->value;;\n    this->value = inverse;\n    return *this;\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::inverse() const\n{\n    NTLFp_model<modulus> r(*this);\n    return r.invert();\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::random_element()\n{\n    NTL::ZZ_p::init(mod_zz());\n    NTLFp_model<modulus> r;\n    r.value = NTL::ZZ_p(NTL::RandomBnd(modulus));\n    return r;\n}\n\ntemplate<unsigned long modulus>\nvoid NTLFp_model<modulus>::get_s_and_t(unsigned long& s, unsigned long& t)\n{\n    s = modulus - 1;\n    t = 0;\n    while (s % 2 == 0) {\n        s /= 2;\n        t++;\n    }\n}\n\ntemplate<unsigned long modulus>\nNTLFp_model<modulus> NTLFp_model<modulus>::sqrt() const\n{\n    NTL::ZZ_p::init(mod_zz());\n    NTL::ZZ_p sqrt = NTL::to_ZZ_p(NTL::SqrRootMod(NTL::rep(this->value), mod_zz()));\n    NTLFp_model<modulus> root;\n    root.value = sqrt;\n\n    return root;\n}\n\ntemplate<unsigned long modulus>\nstd::ostream& operator<<(std::ostream &out, const NTLFp_model<modulus> &p)\n{\n    out << p.value;\n    return out;\n}\n\ntemplate<unsigned long modulus>\nstd::istream& operator>>(std::istream &in, NTLFp_model<modulus> &p)\n{\n    in >> p.value;\n    return in;\n}\n\n} // libsnark\n\n#endif // NTLFP_TCC_\n", "meta": {"hexsha": "61a2b955d9f0e9a1e4f6ec26f72ceb927de239d5", "size": 5978, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "lattice_snarg/algebra/fields/ntlfp.tcc", "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.tcc", "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.tcc", "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": 23.912, "max_line_length": 93, "alphanum_fraction": 0.6701237872, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5732342199104971}}
{"text": "#include <iostream>\n#include <boost/math/special_functions/daubechies_scaling.hpp>\n#include <boost/math/special_functions/chebyshev_transform.hpp>\n\ntemplate<typename Real, int p>\nvoid bootstrap()\n{\n    std::cout << \"Computing phi. . .\\n\";\n    auto phi = boost::math::daubechies_scaling<Real, p>();\n    std::cout << \"Computing Chebyshev transform of phi.\\n\";\n    auto cheb = boost::math::chebyshev_transform(phi, phi.support().first, phi.support().second);\n    std::cout << \"Number of coefficients = \" << cheb.coefficients().size() << \"\\n\";\n}\n\nint main()\n{\n    bootstrap<long double, 9>();\n}", "meta": {"hexsha": "b158fabcd3fb34fe85b00f233f1f5edcd0a168cc", "size": 590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/daubechies_wavelets/bootstrap_chebyshev.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/bootstrap_chebyshev.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": "Libs/boost_1_76_0/libs/math/example/daubechies_wavelets/bootstrap_chebyshev.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 32.7777777778, "max_line_length": 97, "alphanum_fraction": 0.686440678, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5732342163157245}}
{"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// With contributions from Cornelius Steinhardt\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n\n#ifndef MTL_MATRIX_QR_INCLUDE\n#define MTL_MATRIX_QR_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/mtl/mtl_fwd.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/matrix/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\nnamespace mtl { namespace matrix {\n\n\n/// QR-Factorization of matrix A(m x n)\n/** Return pair R upper triangel matrix and Q= orthogonal matrix. R and Q are always dense2D **/\ntemplate <typename Matrix, typename MatrixQ, typename MatrixR>\nvoid qr(const Matrix& A, MatrixQ& Q, MatrixR& R)\n{\n\tvampir_trace<4013> tracer;\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Collection<Matrix>::size_type    size_type;\n    typedef typename Magnitude<value_type>::type      magnitude_type;\n    typedef mtl::vector::dense_vector<value_type, vector::parameters<> >       vector_type;\n    \n    size_type        ncols = num_cols(A), nrows = num_rows(A), \n                     mini= ncols == nrows ? ncols - 1 : (nrows >= ncols ? ncols : nrows);\n    magnitude_type   factor= magnitude_type(2);\n\n    Q= 1;\n    for (size_type i = 0; i < mini; i++) {\n\tirange r(i, imax); // Intervals [i, n-1]\n\tvector_type   w(R[r][i]), v(householder_s(w)); \n\n\t// R-= 2*v*(v'*R)\n\tMatrixR Rsub(R[r][r]);\n\tvector_type tmp(-factor * trans(Rsub) * v);\n\trank_one_update(Rsub, v, tmp);\n\t\n\t//update Q: Q-= 2*(v*Q)*v'\n\tMatrixQ Qsub(Q[iall][r]);\n\tvector_type qtmp(-factor * Qsub * v);\n\trank_one_update(Qsub, qtmp, v);\n    } //end for\n}\n\n/// QR-Factorization of matrix A(m x n)\ntemplate <typename Matrix>\nstd::pair<mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> >,\n \t  mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> > > \ninline qr(const Matrix& A)\n{\n    mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> >  R(A), Q(num_rows(A),num_rows(A));\n    qr(A, Q, R);\n    return std::make_pair(Q,R);\n}\n\n\n\n// QR-Factorization of matrix A\n// Return Q and R with A = Q*R   R upper triangle and Q othogonal\ntemplate <typename Matrix>\nstd::pair<typename mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> >,\n\t  typename mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> > >\ninline qr_factors(const Matrix& A)\n{\n\tvampir_trace<4014> 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);\n    value_type       zero= math::zero(A[0][0]), one= math::one(A[0][0]);\n\n    //evaluation of Q\n    Matrix  Q(nrows, nrows), Qk(nrows, nrows), HEL(nrows, ncols), R(nrows, ncols), R_tmp(nrows, ncols);\n    Q= one; R= zero; HEL= zero;\n\n    boost::tie(Q, R_tmp)= qr(A);\n    R= upper(R_tmp);\n   \n    return std::make_pair(Q,R);\n}\n\n}} // namespace mtl::matrix\n\n\n#endif // MTL_MATRIX_QR_INCLUDE\n\n", "meta": {"hexsha": "f75de404e24ab3a01009507ccb9928c3d0d47435", "size": 4020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr.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": 36.2162162162, "max_line_length": 123, "alphanum_fraction": 0.6985074627, "num_tokens": 1106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5732164804683869}}
{"text": "#include \"DenoiseSystem.h\"\n\n#include \"../Components/DenoiseData.h\"\n\n#include <_deps/imgui/imgui.h>\n\n#include <spdlog/spdlog.h>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n#include <vector>\n#include <deque>\n#include <set>\n\nusing namespace Eigen;\nusing namespace Ubpa;\n\nusing vertpair = std::pair<int, int>;\n\nenum collapse_method {\n\tCOLLAPSE_TO_V1,\n\tCOLLAPSE_TO_V2,\n\tCOLLAPSE_TO_MEAN\n};\n\ninline Vector4f homogenous(const valf3& vec) {\n\treturn Vector4f(vec[0], vec[1], vec[2], 1);\n}\n\nfloat error(const Vector4f& homo, const Matrix4f& Q) {\n\treturn abs((float)(homo.transpose() * Q * homo));\n}\n\nclass Contr {\npublic:\n\tvertpair vp;\n\tMatrix4f Q;\n\tVector4f loc;\n\tcollapse_method method;\n\tfloat resultError;\n\n\tContr(\n\t\tconst vertpair& vertp, const std::vector<Vertex*>& verteces,\n\t\tconst std::vector<Matrix4f>& initialQ) {\n\t\tvp = vertp;\n\t\tfindMinError(verteces, initialQ);\n\t}\n\n\tvoid findMinError(const std::vector<Vertex*>& verteces,\n\t\tconst std::vector<Matrix4f>& initialQ) {\n\t\tVector4f loc_v1 = homogenous(verteces[vp.first]->position);\n\t\tVector4f loc_v2 = homogenous(verteces[vp.second]->position);\n\t\tVector4f loc_vm = (loc_v1 + loc_v2) / 2;\n\n\t\tQ = initialQ[vp.first] + initialQ[vp.second];\n\n\t\tfloat err_v1 = error(loc_v1, Q),\n\t\t\terr_v2 = error(loc_v2, Q),\n\t\t\terr_vm = error(loc_vm, Q);\n\n\n\t\tif (err_v1 < err_v2) {\n\t\t\tif (err_vm < err_v1) method = COLLAPSE_TO_MEAN;\n\t\t\telse method = COLLAPSE_TO_V1;\n\t\t}\n\t\telse {\n\t\t\tif (err_vm < err_v2) method = COLLAPSE_TO_MEAN;\n\t\t\telse method = COLLAPSE_TO_V2;\n\t\t}\n\n\t\tif (method == COLLAPSE_TO_V1) {\n\t\t\tloc = loc_v1;\n\t\t\tresultError = err_v1;\n\t\t}\n\t\telse if (method == COLLAPSE_TO_V2) {\n\t\t\tloc = loc_v2;\n\t\t\tresultError = err_v2;\n\t\t}\n\t\telse {\n\t\t\tloc = loc_vm;\n\t\t\tresultError = err_vm;\n\t\t}\n\t}\n\n\tbool operator<(const Contr& other) const {\n\t\treturn resultError < other.resultError;\n\t}\n\n\tbool contains(int vid) {\n\t\treturn vid == vp.first || vid == vp.second;\n\t}\n\n\tvoid perform(std::vector<Vertex*>& verteces, std::vector<Matrix4f>& initialQ,\n\t\tstd::vector<std::vector<Triangle*> >& vertexToFaces,\n\t\tstd::set<int>& facesToRemove,\n\t\tstd::set<int>& verticesToRemove,\n\t\tstd::deque<Contr>& edges,\n\t\tstd::set<vertpair>& existingedges,\n\t\tstd::vector<std::vector<Vertex*> >&\n\t\tfaceAdjVert) {\n\n\t\tinitialQ[vp.first] = Q;\n\n\t\tint keep = vp.first, remove = vp.second;\n\t\tif (method == COLLAPSE_TO_MEAN) {\n\t\t\tvalf3 tmp = verteces[keep]->position;\n\t\t\ttmp += verteces[remove]->position;\n\t\t\ttmp /= 2;\n\t\t\tverteces[keep]->position = tmp;\n\t\t}\n\t\telse if (method == COLLAPSE_TO_V2) {\n\t\t\tverteces[keep]->position = verteces[remove]->position;\n\t\t}\n\n\t\tstd::vector<Triangle*> faces = vertexToFaces[remove];\n\t\tfor (int i = 0; i < faces.size(); i++) {\n\t\t\tTriangle* f = faces[i];\n\n\t\t\tint v1idx = -1, v2idx = -1;\n\t\t\tfor (int j = 0; j < faceAdjVert[f->id].size(); j++) {\n\t\t\t\tif (faceAdjVert[f->id][j]->id == keep) v1idx = j;\n\t\t\t\telse if (faceAdjVert[f->id][j]->id == remove) v2idx = j;\n\t\t\t}\n\n\t\t\tverticesToRemove.insert(remove);\n\t\t\tfaceAdjVert[f->id][v2idx] = verteces[keep];\n\t\t\tif (v1idx == -1) {\n\t\t\t\tvertexToFaces[keep].push_back(f);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfacesToRemove.insert(f->id);\n\t\t\t}\n\t\t}\n\n\t\tstd::deque<int> edgesToRemove;\n\t\tfor (int i = 0; i < edges.size(); i++) {\n\t\t\tif (vp == edges[i].vp) continue;\n\t\t\tif (edges[i].contains(keep)) {\n\t\t\t\tedges[i].findMinError(verteces, initialQ);\n\t\t\t}\n\t\t\telse if (edges[i].contains(remove)) {\n\t\t\t\tvertpair possible;\n\t\t\t\tif (edges[i].vp.first == remove) {\n\t\t\t\t\tpossible = std::make_pair(edges[i].vp.second, keep);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpossible = std::make_pair(edges[i].vp.first, keep);\n\t\t\t\t}\n\n\t\t\t\tif (existingedges.find(possible) != existingedges.end()) {\n\t\t\t\t\tedgesToRemove.push_back(i);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tedges[i].vp = possible;\n\t\t\t\t\tedges[i].findMinError(verteces, initialQ);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tint offset = 0;\n\t\tfor (int i = 0; i < edgesToRemove.size(); i++) {\n\t\t\texistingedges.erase(edges[edgesToRemove[i]].vp);\n\t\t\tedges.erase(edges.begin() + edgesToRemove[i] + offset);\n\t\t\toffset--;\n\t\t}\n\n\t\tvertexToFaces[remove].clear();\n\t}\n};\n\nContr popmin(std::deque<Contr>& edges) {\n\tContr best = edges.front();\n\tint bestidx = 0;\n\tfor (int i = 1; i < edges.size(); i++) {\n\t\tif (edges[i] < best) {\n\t\t\tbestidx = i;\n\t\t\tbest = edges[i];\n\t\t}\n\t}\n\tedges[bestidx] = edges.back();\n\tedges.pop_back();\n\treturn best;\n}\n\nvoid DenoiseSystem::OnUpdate(Ubpa::UECS::Schedule& schedule) {\n\tschedule.RegisterCommand([](Ubpa::UECS::World* w) {\n\t\tauto data = w->entityMngr.GetSingleton<DenoiseData>();\n\t\tif (!data)\n\t\t\treturn;\n\n\t\tif (ImGui::Begin(\"Denoise\")) {\n\t\t\tif (ImGui::Button(\"Mesh to HEMesh\")) {\n\t\t\t\tdata->heMesh->Clear();\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (data->mesh->GetSubMeshes().size() != 1) {\n\t\t\t\t\t\tspdlog::warn(\"number of submeshes isn't 1\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->copy = *data->mesh;\n\n\t\t\t\t\tstd::vector<size_t> indices(data->mesh->GetIndices().begin(), data->mesh->GetIndices().end());\n\n\t\t\t\t\tdata->heMesh->Init(indices, 3);\n\t\t\t\t\tif (!data->heMesh->IsTriMesh())\n\t\t\t\t\t\tspdlog::warn(\"HEMesh init fail\");\n\t\t\t\t\t\n\t\t\t\t\tfor (size_t i = 0; i < data->mesh->GetPositions().size(); i++) {\n\t\t\t\t\t\tdata->heMesh->Vertices().at(i)->position = data->mesh->GetPositions().at(i);\n\t\t\t\t\t\tdata->heMesh->Vertices().at(i)->id = -1;\n\t\t\t\t\t}\n\n\t\t\t\t\tspdlog::info(\"Mesh to HEMesh success\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"QEM\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->heMesh->IsTriMesh()) {\n\t\t\t\t\t\tspdlog::warn(\"HEMesh isn't triangle mesh\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst auto vertices = data->heMesh->Vertices();\n\t\t\t\t\tauto total = vertices.size();\n\t\t\t\t\tfor (int i = 0; i < total; ++i) vertices[i]->id = i;\n\n\t\t\t\t\tdata->faces.clear();\n\t\t\t\t\tdata->faces.resize(data->heMesh->Polygons().size() + 1, std::vector<Vertex*>());\n\n\t\t\t\t\tstd::vector<Vertex*> verteces(total + 1, NULL);\n\t\t\t\t\tstd::vector<Matrix4f> initialQ(total + 1, Matrix4f::Zero());\n\t\t\t\t\tstd::vector<std::vector<Triangle*> > vertexToFaces(total + 1, std::vector<Triangle*>());\n\n\t\t\t\t\tstd::set<vertpair> edgeset;\n\n\t\t\t\t\tfor (int i = 0; i < data->heMesh->Polygons().size(); i++) {\n\t\t\t\t\t\tTriangle* f = data->heMesh->Polygons()[i];\n\t\t\t\t\t\tf->id = i;\n\n\t\t\t\t\t\tconst auto& adj = f->AdjVertices();\n\n\t\t\t\t\t\tvalf3 v1 = adj[0]->position;\n\t\t\t\t\t\tvalf3 v2 = adj[1]->position;\n\t\t\t\t\t\tvalf3 v3 = adj[2]->position;\n\n\t\t\t\t\t\tVector4f p;\n\t\t\t\t\t\t/* http://paulbourke.net/geometry/planeeq/ */\n\t\t\t\t\t\tp[0] = v1[1] * (v2[2] - v3[2]) + v2[1] * (v3[2] - v1[2]) + v3[1] * (v1[2] - v2[2]);\n\t\t\t\t\t\tp[1] = v1[2] * (v2[0] - v3[0]) + v2[2] * (v3[0] - v1[0]) + v3[2] * (v1[0] - v2[0]);\n\t\t\t\t\t\tp[2] = v1[0] * (v2[1] - v3[1]) + v2[0] * (v3[1] - v1[1]) + v3[0] * (v1[1] - v2[1]);\n\t\t\t\t\t\tp[3] = -(v1[0] * (v2[1] * v3[2] - v3[1] * v2[2]) +\n\t\t\t\t\t\t\tv2[0] * (v3[1] * v1[2] - v1[1] * v3[2]) +\n\t\t\t\t\t\t\tv3[0] * (v1[1] * v2[2] - v2[1] * v1[2]));\n\n\t\t\t\t\t\tMatrix4f pp = p * p.transpose();\n\n\t\t\t\t\t\tfor (auto vert : f->AdjVertices()) {\n\t\t\t\t\t\t\tverteces[vert->id] = vert;\n\t\t\t\t\t\t\tvertexToFaces[vert->id].push_back(f);\n\t\t\t\t\t\t\tdata->faces[f->id].push_back(vert);\n\n\t\t\t\t\t\t\tinitialQ[vert->id] += pp;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (const auto& edge : f->AdjEdges()) {\n\t\t\t\t\t\t\tstd::vector<Vertex*> tmpV;\n\t\t\t\t\t\t\tfor (const auto& vert : edge->AdjVertices()) {\n\t\t\t\t\t\t\t\ttmpV.push_back(vert);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvertpair vp = vertpair(tmpV[0]->id, tmpV[1]->id);\n\t\t\t\t\t\t\tedgeset.insert(vp);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tstd::deque<Contr> edges;\n\t\t\t\t\tfor (auto edge = edgeset.begin(); edge != edgeset.end(); edge++) {\n\t\t\t\t\t\tedges.push_back(Contr(*edge, verteces, initialQ));\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->facesToRemove.clear();\n\t\t\t\t\tdata->verticesToRemove.clear();\n\n\t\t\t\t\tint target_edges = (int)(data->scale * (float)edges.size());\n\t\t\t\t\twhile (edges.size() > target_edges) {\n\t\t\t\t\t\tContr best = popmin(edges);\n\t\t\t\t\t\tbest.perform(verteces, initialQ, vertexToFaces, data->facesToRemove, data->verticesToRemove, edges, edgeset, data->faces);\n\t\t\t\t\t}\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"HEMesh to Mesh\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!data->heMesh->IsTriMesh() || data->heMesh->IsEmpty()) {\n\t\t\t\t\t\tspdlog::warn(\"HEMesh isn't triangle mesh or is empty\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->mesh->SetToEditable();\n\n\t\t\t\t\tconst size_t N = data->heMesh->Vertices().size();\n\t\t\t\t\tconst size_t M = data->heMesh->Polygons().size();\n\t\t\t\t\tstd::vector<Ubpa::pointf3> positions;\n\t\t\t\t\tstd::vector<uint32_t> indices;\n\t\t\t\t\tstd::vector<int> remapping(N + 1, -1);\n\t\t\t\t\tfor (size_t i = 0; i < N; i++) {\n\t\t\t\t\t\tint id = data->heMesh->Vertices().at(i)->id;\n\t\t\t\t\t\t//if (data->verticesToRemove.find(id) == data->verticesToRemove.end()) {\n\t\t\t\t\t\t\tpositions.push_back(data->heMesh->Vertices().at(i)->position);\n\t\t\t\t\t\t\tremapping[id] = static_cast<int>(positions.size() - 1);\n\t\t\t\t\t\t//}\n\t\t\t\t\t}\n\t\t\t\t\tfor (size_t i = 0; i < M; i++) {\n\t\t\t\t\t\tint id = i;\n\t\t\t\t\t\tif (data->facesToRemove.find(id) == data->facesToRemove.end()) {\n\t\t\t\t\t\t\t/*if (remapping[data->faces[id][0]->id] == -1 ||\n\t\t\t\t\t\t\t\tremapping[data->faces[id][1]->id] == -1 ||\n\t\t\t\t\t\t\t\tremapping[data->faces[id][2]->id] == -1) continue;*/\n\t\t\t\t\t\t\tindices.push_back(static_cast<uint32_t>(remapping[data->faces[id][0]->id]));\n\t\t\t\t\t\t\tindices.push_back(static_cast<uint32_t>(remapping[data->faces[id][1]->id]));\n\t\t\t\t\t\t\tindices.push_back(static_cast<uint32_t>(remapping[data->faces[id][2]->id]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tconst size_t M3 = indices.size();\n\t\t\t\t\tdata->mesh->SetColors({});\n\t\t\t\t\tdata->mesh->SetUV({});\n\t\t\t\t\tdata->mesh->SetNormals({});\n\t\t\t\t\tdata->mesh->SetPositions(std::move(positions));\n\t\t\t\t\tdata->mesh->SetIndices(std::move(indices));\n\t\t\t\t\tdata->mesh->SetSubMeshCount(1);\n\t\t\t\t\tdata->mesh->SetSubMesh(0, { 0, M3 });\n\t\t\t\t\tdata->mesh->GenUV();\n\t\t\t\t\tdata->mesh->GenNormals();\n\t\t\t\t\tdata->mesh->GenTangents();\n\n\t\t\t\t\tspdlog::info(\"HEMesh to Mesh success\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Recover Mesh\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (data->copy.GetPositions().empty()) {\n\t\t\t\t\t\tspdlog::warn(\"copied mesh is empty\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t*data->mesh = data->copy;\n\n\t\t\t\t\tspdlog::info(\"recover success\");\n\t\t\t\t}();\n\t\t\t}\n\t\t}\n\t\tImGui::End();\n\t});\n}\n", "meta": {"hexsha": "6a75b9745be1d881115c0c9aa295a43f6894229f", "size": 10054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homeworks/HW9/Systems/DenoiseSystem.cpp", "max_stars_repo_name": "g1n0st/GAMES102", "max_stars_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T16:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T23:49:36.000Z", "max_issues_repo_path": "homeworks/HW9/Systems/DenoiseSystem.cpp", "max_issues_repo_name": "g1n0st/GAMES102", "max_issues_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_issues_repo_licenses": ["MIT"], "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/HW9/Systems/DenoiseSystem.cpp", "max_forks_repo_name": "g1n0st/GAMES102", "max_forks_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T08:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T02:36:06.000Z", "avg_line_length": 27.0997304582, "max_line_length": 128, "alphanum_fraction": 0.5844440024, "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.5731803393292465}}
{"text": "/**\n * Matrix-free finite element method introduced in doi:10.1002/nme.5263\n *\n * This library provides classes to compute the modal stiffness\n * matrices and strain-displacement vectors in Fourier space for a\n * homogeneous, periodic unit-cell. Combined with a FFT library, these\n * can be used to compute the solution to any problem of homogeneous,\n * periodic linear elasticity.\n */\n\n#pragma once\n\n#include <array>\n#include <cmath>\n#include <concepts>\n#include <numbers>\n#include <numeric>\n\n#include <complex>\n#include <cstddef>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n#include <Eigen/Dense>\n\nnamespace bri17 {\n/**\n * A rectangular grid with fixed spacing in each direction.\n *\n * @tparam T the scalar type\n * @tparam DIM the number of spatial dimensions (must be 2 or 3)\n */\ntemplate <typename T, int DIM>\nrequires(std::floating_point<T> &&\n         ((DIM == 2) || (DIM == 3))) class CartesianGrid {\n public:\n  /** Number of nodes per cell: `2 ** DIM`. */\n  static constexpr int num_nodes_per_cell = 1 << DIM;\n\n  /** Number of cells in each direction. */\n  std::array<int, DIM> const shape;\n\n  /** Size of the grid in each direction (arbitrary units of length). */\n  std::array<T, DIM> const L;\n\n  /** Total number of cells: `shape[0] * shape[1] * ... * shape[DIM-1]`. */\n  int const size;\n\n  /**\n   * @param shape number of cells in each direction\n   * @param L size of the grid in each direction (arbitrary units of length)\n   */\n  CartesianGrid(std::array<int, DIM> shape, std::array<T, DIM> L)\n      : shape{shape},\n        L{L},\n        size{std::reduce(shape.cbegin(), shape.cend(), int{1},\n                         std::multiplies())} {}\n\n  /** Return a string representation of this object. */\n  std::string repr() const {\n    std::ostringstream stream;\n    stream << \"CartesianGrid<\" << typeid(T).name() << \",\" << DIM << \">{shape={\";\n    for (auto n : shape) stream << n << \",\";\n    stream << \"},L={\";\n    for (auto x : L) stream << x << \",\";\n    stream << \"}}\";\n    return stream.str();\n  }\n\n  /**\n   * Return the index of the node located at <tt>[i, j]</tt>.\n   *\n   * This method cannot be called with a 3D grid (this condition is\n   * checked at compile time). Nodes numbering follows the row-major\n   * order convention.\n   */\n  int get_node_at(int i, int j) const {\n    static_assert(DIM == 2, \"this method expects a 2D grid\");\n    return i * shape[1] + j;\n  }\n\n  /**\n   * Return the index of the node located at <tt>[i, j, k]</tt>.\n   *\n   * This method cannot be called with a 2D grid (this condition is\n   * checked at compile time). Nodes numbering follows the row-major\n   * order convention.\n   */\n  int get_node_at(int i, int j, int k) const {\n    static_assert(DIM == 3, \"this method expects a 3D grid\");\n    return (i * shape[1] + j) * shape[2] + k;\n  }\n\n  /**\n   * Return the indices of the vertices of a specific cell.\n   *\n   * Numbering of vertices in 2D\n   *\n   * ```\n   * 2────4\n   * │    │\n   * │    │\n   * 1────3\n   * ```\n   *\n   *\n   * Numbering of vertices in 3D\n   *\n   * ```\n   *      4────────8\n   *     ╱│       ╱│\n        ╱ │      ╱ │\n   *   ╱  │     ╱  │\n   *  ╱   │    ╱   │\n   * 2────────6 ───7\n   * │   ╱3   │   ╱\n   * │  ╱     │  ╱\n     │ ╱      │ ╱\n   * │╱       │╱\n   * 1────────5\n   * ```\n   *\n   * @param cell index of the cell (row-major order)\n   * @return array of node indices\n   */\n  std::array<int, num_nodes_per_cell> get_cell_nodes(int cell) const {\n    std::array<int, num_nodes_per_cell> nodes;\n    if constexpr (DIM == 2) {\n      const int i1 = cell / shape[1];\n      const int j1 = cell % shape[1];\n      const int i2 = i1 == shape[0] - 1 ? 0 : i1 + 1;\n      const int j2 = j1 == shape[1] - 1 ? 0 : j1 + 1;\n      nodes[0] = get_node_at(i1, j1);\n      nodes[1] = get_node_at(i1, j2);\n      nodes[2] = get_node_at(i2, j1);\n      nodes[3] = get_node_at(i2, j2);\n    } else if constexpr (DIM == 3) {\n      const int k1 = cell % shape[2];\n      const int ij1 = cell / shape[2];\n      const int j1 = ij1 % shape[1];\n      const int i1 = ij1 / shape[1];\n      const int i2 = i1 == shape[0] - 1 ? 0 : i1 + 1;\n      const int j2 = j1 == shape[1] - 1 ? 0 : j1 + 1;\n      const int k2 = k1 == shape[2] - 1 ? 0 : k1 + 1;\n      nodes[0] = get_node_at(i1, j1, k1);\n      nodes[1] = get_node_at(i1, j1, k2);\n      nodes[2] = get_node_at(i1, j2, k1);\n      nodes[3] = get_node_at(i1, j2, k2);\n      nodes[4] = get_node_at(i2, j1, k1);\n      nodes[5] = get_node_at(i2, j1, k2);\n      nodes[6] = get_node_at(i2, j2, k1);\n      nodes[7] = get_node_at(i2, j2, k2);\n    } else {\n      throw std::logic_error(\"This should never occur\");\n    }\n    return nodes;\n  }\n};\n\n/** Print the grid to the specified `ostream`. */\ntemplate <typename T, int DIM>\nstd::ostream &operator<<(std::ostream &os, const CartesianGrid<T, DIM> &grid) {\n  return os << grid.repr();\n}\n\n/**\n * Implementation of the results of [Bri17] per se.\n *\n * This class provides methods to compute the modal strain-displacement and\n * stiffness matrices.\n *\n * @tparam T the scalar type\n * @tparam DIM the number of spatial dimensions (must be 2 or 3)\n */\ntemplate <typename T, int DIM>\nrequires(std::floating_point<T> && ((DIM == 2) || (DIM == 3))) class Hooke {\n public:\n  /** The shear modulus of the material. */\n  T const mu;\n\n  /** The Poisson ratio of the material. */\n  T const nu;\n\n  /** Geometric description of the underlying FE grid. */\n  CartesianGrid<T, DIM> const grid;\n\n  /**\n   * @param mu shear modulus\n   * @param nu Poisson ratio\n   * @param grid the FE grid\n   */\n  Hooke(T mu, T nu, CartesianGrid<T, DIM> &grid)\n      : mu{mu}, nu{nu}, grid{grid} {};\n\n  /** Return a string representation of this object. */\n  std::string repr() const {\n    std::ostringstream stream;\n    stream << \"Hooke<\" << typeid(T).name() << \",\" << DIM << \">{mu=\" << mu\n           << \",nu=\" << nu << \",grid=\" << grid << std::endl;\n    return stream.str();\n  }\n\n  /**\n   * Compute modal strain-displacement vector for specified spatial frequency.\n   *\n   * The output parameter `B` must be a preallocated array of size `DIM`.\n   *\n   * @param k the multi-index in the frequency domain\n   * @param B the strain-displacement vector `B^[k, :]` (output parameter)\n   */\n  void modal_strain_displacement(int const *k, std::complex<T> *B) const {\n    T c[DIM];\n    T s[DIM];\n    T sum_alpha{};  // TODO Check that initializes to 0\n\n    for (int i = 0; i < DIM; i++) {\n      T alpha = std::numbers::pi_v<T> * k[i] / grid.shape[i];\n      sum_alpha += alpha;\n      c[i] = cos(alpha);\n      s[i] = sin(alpha) * grid.shape[i] / grid.L[i];\n    }\n\n    std::complex<T> prefactor{-2 * sin(sum_alpha), 2 * cos(sum_alpha)};\n\n    if constexpr (DIM == 2) {\n      B[0] = prefactor * s[0] * c[1];\n      B[1] = prefactor * c[0] * s[1];\n    } else if constexpr (DIM == 3) {\n      B[0] = prefactor * s[0] * c[1] * c[2];\n      B[1] = prefactor * c[0] * s[1] * c[2];\n      B[2] = prefactor * c[0] * c[1] * s[2];\n    } else {\n      throw std::logic_error(\"this should never occur\");\n    }\n  }\n\n  /**\n   * Compute modal stiffness matrix for specified spatial frequency.\n   *\n   * The output parameter `K` must be a preallocated array of size\n   * `DIM * DIM`.\n   *\n   * @param k the multi-index in the frequency domain\n   * @param K the stiffness matrix `K^[k, :, :]` (output parameter)\n   */\n  void modal_stiffness(int const *k, std::complex<T> *K) const {\n    // In the notation of [Bri17, see Eq. (B.17)]\n    //\n    // phi[i] = phi(z_i) / h_i\n    // chi[i] = chi(z_i) * h_i\n    // psi[i] = psi(z_i)\n    //\n    // Which simplifies the expression of H_k (there are no h_i's).\n    T phi[DIM];\n    T psi[DIM];\n    T chi[DIM];\n    for (int i = 0; i < DIM; i++) {\n      T h = grid.L[i] / grid.shape[i];\n      T beta = 2 * std::numbers::pi_v<T> * k[i] / grid.shape[i];\n      phi[i] = 2 * (1 - cos(beta)) / h / h;\n      chi[i] = (2 + cos(beta)) / 3;\n      psi[i] = sin(beta) / h;\n    }\n\n    const double scaling = mu / (1. - 2. * nu);\n    if constexpr (DIM == 2) {\n      auto H_00 = phi[0] * chi[1];\n      auto H_11 = chi[0] * phi[1];\n      auto K_diag = mu * (H_00 + H_11);\n      K[0] = scaling * H_00 + K_diag;\n      K[1] = scaling * psi[0] * psi[1];\n      K[2] = K[1];\n      K[3] = scaling * H_11 + K_diag;\n    } else if constexpr (DIM == 3) {\n      auto H_00 = phi[0] * chi[1] * chi[2];\n      auto H_11 = chi[0] * phi[1] * chi[2];\n      auto H_22 = chi[0] * chi[1] * phi[2];\n      auto K_diag = mu * (H_00 + H_11 + H_22);\n      K[0] = scaling * H_00 + K_diag;             // [0, 0]\n      K[1] = scaling * psi[0] * psi[1] * chi[2];  // [0, 1]\n      K[2] = scaling * psi[0] * chi[1] * psi[2];  // [0, 2]\n      K[3] = K[1];                                // [1, 0]\n      K[4] = scaling * H_11 + K_diag;             // [1, 1]\n      K[5] = scaling * chi[0] * psi[1] * psi[2];  // [1, 2]\n      K[6] = K[2];                                // [2, 0]\n      K[7] = K[5];                                // [2, 1]\n      K[8] = scaling * H_22 + K_diag;             // [2, 2]\n    } else {\n      throw std::logic_error(\"this should never occur\");\n    }\n  }\n\n  /**\n   * Compute the strains induced by the specified eigenstresses.\n   *\n   * The eigenstresses `τ[n, i, j]` are constant in each cell n. They induce the\n   * average strains `ε[n, i, j]`.\n   *\n   * This method computes the **opposite** of the induced strain!\n   *\n   * @param k multi-index of the Fourier component\n   * @param tau the `k`-th Fourier component of the eigenstress `τ`,\n   *            `τ^[k, :, :]`\n   * @param eta the `k`-th Fourier component of `-ε`, `-ε^[k, :, :]`\n   *            (output parameter).\n   */\n  void modal_eigenstress_to_opposite_strain(int const *k,\n                                            std::complex<T> const *tau,\n                                            std::complex<T> *eta) const {\n    using Vector = Eigen::Matrix<std::complex<T>, DIM, 1>;\n    using Matrix = Eigen::Matrix<std::complex<T>, DIM, DIM>;\n    constexpr T const sqrt2 = std::numbers::sqrt2_v<T>;\n    constexpr std::complex<T> zero{};\n    constexpr int const sym = DIM == 2 ? 3 : 6;\n    Vector B{};\n    modal_strain_displacement(k, B.data());\n    Matrix K{};\n    modal_stiffness(k, K.data());\n    Matrix tau_mat;\n    bool null_frequency = false;\n    if constexpr (DIM == 2) {\n      // clang-format off\n      tau_mat <<         tau[0], tau[2] / sqrt2,\n                 tau[2] / sqrt2,         tau[1];\n      // clang-format on\n      null_frequency = (k[0] == 0) && (k[1] == 0);\n    } else if constexpr (DIM == 3) {\n      // clang-format off\n      tau_mat <<         tau[0], tau[5] / sqrt2, tau[4] / sqrt2,\n                 tau[5] / sqrt2,         tau[1], tau[3] / sqrt2,\n                 tau[4] / sqrt2, tau[3] / sqrt2,         tau[2];\n      // clang-format on\n      null_frequency = (k[0] == 0) && (k[1] == 0) && (k[2] == 0);\n    }\n    if (null_frequency) {\n      for (int i = 0; i < sym; i++) eta[i] = zero;\n      return;\n    }\n    Vector rhs = tau_mat * B.conjugate();\n    Vector u = K.llt().solve(rhs);\n    Matrix eta_mat = 0.5 * (B * u.transpose() + u * B.transpose());\n    if constexpr (DIM == 2) {\n      eta[0] = eta_mat(0, 0);\n      eta[1] = eta_mat(1, 1);\n      eta[2] = sqrt2 * eta_mat(0, 1);\n    } else if constexpr (DIM == 3) {\n      eta[0] = eta_mat(0, 0);\n      eta[1] = eta_mat(1, 1);\n      eta[2] = eta_mat(2, 2);\n      eta[3] = sqrt2 * eta_mat(1, 2);\n      eta[4] = sqrt2 * eta_mat(2, 0);\n      eta[5] = sqrt2 * eta_mat(0, 1);\n    }\n  }\n};\n\n/** Print the grid to the specified `ostream`. */\ntemplate <typename T, int DIM>\nstd::ostream &operator<<(std::ostream &os, const Hooke<T, DIM> &hooke) {\n  return os << hooke.repr();\n}\n\n}  // namespace bri17\n", "meta": {"hexsha": "b1afa669004c2635e5ca34ab4b00732a042d0d7e", "size": 11609, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bri17/bri17.hpp", "max_stars_repo_name": "sbrisard/bri17", "max_stars_repo_head_hexsha": "e2e9856ec1bcd6a3bde43cd979943f958e0d49bf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/bri17/bri17.hpp", "max_issues_repo_name": "sbrisard/bri17", "max_issues_repo_head_hexsha": "e2e9856ec1bcd6a3bde43cd979943f958e0d49bf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-05-16T15:56:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-23T13:34:07.000Z", "max_forks_repo_path": "include/bri17/bri17.hpp", "max_forks_repo_name": "sbrisard/bri17", "max_forks_repo_head_hexsha": "e2e9856ec1bcd6a3bde43cd979943f958e0d49bf", "max_forks_repo_licenses": ["BSD-3-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.8054794521, "max_line_length": 80, "alphanum_fraction": 0.5373417176, "num_tokens": 3719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.573155577993479}}
{"text": "#ifndef MATH_HPP\n#define MATH_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\ntemplate<class T, int M = Eigen::Dynamic, int N = Eigen::Dynamic>\nusing matrix = Eigen::Matrix<T, M, N>;\n\ntemplate<class T, int M = Eigen::Dynamic>\nusing vector = matrix<T, M, 1>;\n\nusing real = double;\n\nusing vec = vector<real>;\n\nusing vec4 = vector<real, 4>;\nusing vec3 = vector<real, 3>;\nusing vec2 = vector<real, 2>;\nusing vec1 = vector<real, 1>;\n\nusing mat = matrix<real>;\nusing mat4x4 = matrix<real, 4, 4>;\nusing mat3x3 = matrix<real, 3, 3>;\n\n\ntemplate<class T>\nusing quaternion = Eigen::Quaternion<T>;\n\nusing quat = quaternion<real>;\n\n\nstruct rigid {\n  quat orient;\n  vec3 pos;\n\n  rigid(): orient(1, 0, 0, 0), pos(0, 0, 0) {}\n\n  static rigid translation(real x, real y, real z) {\n    rigid res;\n    res.pos = {x, y, z};\n    return res;\n  }\n\n  static rigid translation(vec3 t) {\n    return translation(t.x(), t.y(), t.z());\n  }\n\n  static rigid rotation(quat q) {\n    rigid res;\n    res.orient = q;\n    return res;\n  }\n  \n  rigid operator*(const rigid& other) const {\n    rigid res;\n    res.orient = orient * other.orient;\n    res.pos = pos + orient * other.pos;\n    return res;\n  }\n\n  rigid inv() const {\n    rigid res;\n    res.orient = orient.conjugate();\n    res.pos = -(res.orient * pos);\n    return res;\n  }\n  \n};\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "df0c827d4bedbd0f12304968ed5caa5e2a3fb0fc", "size": 1319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3552631579, "max_line_length": 65, "alphanum_fraction": 0.6209249431, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5731555778463825}}
{"text": "//          Copyright Jean Pierre Cimalando 2018.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <jsl/math>\n#include <boost/predef/architecture.h>\n#include <cmath>\n\nnamespace jsl {\n\ntemplate <class R>\ninline R clamp(R x, R min, R max)\n{\n  x = (x < min) ? min : x;\n  x = (x > max) ? max : x;\n  return x;\n}\n\ntemplate <class R>\ninline R square(R x)\n{\n    return x * x;\n}\n\ntemplate <class R>\ninline R cube(R x)\n{\n    return x * x * x;\n}\n\ntemplate <class R>\nR sinc(R x)\n{\n    return (x == 0) ? 1 : (std::sin(x) / x);\n}\n\ntemplate <class R>\nR binom(unsigned n, unsigned k)\n{\n  R r = 1;\n  for (unsigned i = 1; i <= k; ++i)\n    r *= (n + 1 - i) / (R)i;\n  return r;\n}\n\ntemplate <class R>\nvoid poly(gsl::span<const R> z, gsl::span<R> p)\n{\n    Expects(p.size() == z.size() + 1);\n    size_t n = z.size();\n    p[0] = 1;\n    for (size_t j = 0; j < n; ++j)\n        p[j + 1] = 0;\n    for (size_t j = 0; j < n; ++j)\n        for (size_t k = j + 1; k-- > 0;)\n            p[k + 1] -= z[j] * p[k];\n}\n\ntemplate <class R>\nR polyval(gsl::span<const R> p, R x)\n{\n    R y = 0;\n    R xi = 1;\n    for (size_t i = 0, n = p.size(); i < n; ++i) {\n        y += xi * p[i];\n        xi *= x;\n    }\n    return y;\n}\n\n#if BOOST_ARCH_X86_32 || BOOST_ARCH_X86_64\nstruct denormal_disabler {\n    denormal_disabler() noexcept\n    {\n        int csr = get_csr();\n        csr_ = csr;\n        set_csr(csr | 0x8040);\n    }\n\n    ~denormal_disabler() noexcept\n    {\n        set_csr(csr_);\n    }\n\nprivate:\n    int csr_ = 0;\n\n    static int get_csr() noexcept {\n        int csr;\n        asm volatile(\"stmxcsr %0\" : \"=m\"(csr));\n        return csr;\n    }\n\n    static void set_csr(int csr) noexcept {\n        asm volatile(\"ldmxcsr %0\" : : \"m\"(csr));\n    }\n};\n#elif BOOST_ARCH_ARM\nstruct denormal_disabler {\n    denormal_disabler() noexcept\n    {\n        int fpcsr = get_fpcsr();\n        fpcsr_ = fpcsr;\n        set_fpcsr(fpcsr | (1 << 24));\n    }\n\n    ~denormal_disabler() noexcept\n    {\n        set_fpcsr(fpcsr_);\n    }\n\nprivate:\n    int fpcsr_ = 0;\n\n    static int get_fpcsr() noexcept {\n        int fpcsr;\n        asm volatile(\"mrs %[fpcsr], FPCR\" : [fpcsr] \"=r\"(fpcsr));\n        return fpcsr;\n    }\n\n    static void set_fpcsr(int fpcsr) noexcept {\n        asm volatile(\"msr FPCR, %[fpcsr]\" : : [fpcsr]\"r\"(fpcsr));\n    }\n};\n#else\nstruct denormal_disabler {\n    denormal_disabler() noexcept {}\n    ~denormal_disabler() noexcept {}\n};\n#endif\n\nnamespace ilog2_detail {\n\ntemplate <class T>\nstruct ilog2 {\n    T operator()(T value)\n    {\n        T l = 0;\n        while((value >> l) > 1)\n            ++l;\n        return l;\n    }\n};\n\n#if defined(__GNUC__)\ntemplate <>\nstruct ilog2<unsigned> {\n    unsigned operator()(unsigned value)\n    {\n        return sizeof(unsigned) * 8 - __builtin_clz(value) - 1;\n    }\n};\n\ntemplate <>\nstruct ilog2<unsigned long> {\n    unsigned long operator()(unsigned long value)\n    {\n        return sizeof(unsigned long) * 8 - __builtin_clzl(value) - 1;\n    }\n};\n\ntemplate <>\nstruct ilog2<unsigned long long> {\n    unsigned long long operator()(unsigned long long value)\n    {\n        return sizeof(unsigned long long) * 8 - __builtin_clzll(value) - 1;\n    }\n};\n#endif\n\n}  // namespace ilog2_detail\n\ntemplate <class T>\nT ilog2(T value)\n{\n    ilog2_detail::ilog2<T> fn;\n    return fn(value);\n}\n\n}  // namespace jsl\n", "meta": {"hexsha": "34a0947f0fadc418b001419c05eb624f69c2a85e", "size": 3404, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "thirdparty/jsl/include/jsl/bits/math.tcc", "max_stars_repo_name": "jpcima/ensemble-chorus", "max_stars_repo_head_hexsha": "59baeb86b8851f521bc8162e22e3f15061662cc3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-09-04T11:34:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T19:31:30.000Z", "max_issues_repo_path": "thirdparty/jsl/include/jsl/bits/math.tcc", "max_issues_repo_name": "jpcima/ensemble-chorus", "max_issues_repo_head_hexsha": "59baeb86b8851f521bc8162e22e3f15061662cc3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-08-13T17:35:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T15:56:11.000Z", "max_forks_repo_path": "thirdparty/jsl/include/jsl/bits/math.tcc", "max_forks_repo_name": "jpcima/ensemble-chorus", "max_forks_repo_head_hexsha": "59baeb86b8851f521bc8162e22e3f15061662cc3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T14:49:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T21:50:52.000Z", "avg_line_length": 18.7032967033, "max_line_length": 75, "alphanum_fraction": 0.5543478261, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.573099482308307}}
{"text": "#pragma once\n#include \"Optimizer.hpp\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <limits>\n#include <nlohmann/json.hpp>\n\nnamespace yavque\n{\nclass AdaMax : public Optimizer\n{\npublic:\n\tstatic constexpr std::array<double, 3> DEFAULT_PARAMS = {0.002, 0.9, 0.999};\n\nprivate:\n\tconst double alpha_;\n\tconst double beta1_;\n\tconst double beta2_;\n\n\tint t_ = 0;\n\n\tEigen::VectorXd m_;\n\tEigen::VectorXd u_;\n\npublic:\n\texplicit AdaMax(double alpha = DEFAULT_PARAMS[0], double beta1 = DEFAULT_PARAMS[1],\n\t                double beta2 = DEFAULT_PARAMS[2])\n\t\t: alpha_(alpha), beta1_(beta1), beta2_(beta2)\n\t{\n\t}\n\n\texplicit AdaMax(const nlohmann::json& params)\n\t\t: alpha_(params.value(\"alpha\", DEFAULT_PARAMS[0])),\n\t\t  beta1_(params.value(\"beta1\", DEFAULT_PARAMS[1])),\n\t\t  beta2_(params.value(\"beta2\", DEFAULT_PARAMS[2]))\n\t{\n\t}\n\n\tstatic nlohmann::json defaultParams()\n\t{\n\t\treturn nlohmann::json{{\"name\", \"AdaMax\"},\n\t\t                      {\"alhpa\", DEFAULT_PARAMS[0]},\n\t\t                      {\"beta1\", DEFAULT_PARAMS[1]},\n\t\t                      {\"beta2\", DEFAULT_PARAMS[2]}};\n\t}\n\n\t[[nodiscard]] nlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json{{\"name\", \"AdaMax\"},\n\t\t                      {\"alhpa\", alpha_},\n\t\t                      {\"beta1\", beta1_},\n\t\t                      {\"beta2\", beta2_}};\n\t}\n\n\tEigen::VectorXd getUpdate(const Eigen::VectorXd& grad) override\n\t{\n\t\tusing std::pow;\n\t\tif(t_ == 0)\n\t\t{\n\t\t\tm_ = Eigen::VectorXd::Zero(grad.rows());\n\t\t\tu_ = Eigen::VectorXd::Zero(grad.rows());\n\t\t}\n\t\t++t_;\n\t\tm_ *= beta1_;\n\t\tm_ += (1.0 - beta1_) * grad;\n\n\t\tu_ *= beta2_;\n\t\tu_ = u_.cwiseMax(grad.cwiseAbs());\n\t\tu_ = u_.cwiseMax(std::numeric_limits<double>::min());\n\n\t\treturn -(alpha_ / (1 - pow(beta1_, t_))) * m_.cwiseQuotient(u_);\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "5b6b2329b1ee10cbfe1336cb84099635594588c3", "size": 1757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Optimizers/AdaMax.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Optimizers/AdaMax.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Optimizers/AdaMax.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1184210526, "max_line_length": 84, "alphanum_fraction": 0.6015936255, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5730994715805319}}
{"text": "#ifndef SOFTMAX_H\n#define SOFTMAX_H\n\n#include \"../../ml/utility/gradient_checking.hpp\"\n#include \"../../eigen/eigen.hpp\"\n\n#include <opencv2/core.hpp>\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <limits>\n#include <map>\n#include <random>\n#include <set>\n#include <vector>\n\n/*! \\file softmax.hpp\n    \\brief implement the algorithm--softmax regression based on\\n\n    the description of UFLDL, these codes are develop based\\n\n    on the example on the website(http://eric-yuan.me/softmax-regression-cv/#comment-8781).\n*/\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup ml\n *  @{\n */\nnamespace ml{\n\ntemplate<typename T = double>\nclass softmax\n{\npublic:\n    static_assert(std::is_floating_point<T>::value,\n                  \"T should be floating point\");\n\n    using EigenMat = eigen::MatRowMajor<T>;\n\n    softmax();\n\n    /**\n     * @brief get the weight of softmax\n     * @return weight of softmax\n     */\n    EigenMat const& get_weight() const\n    {\n        return weight_;\n    }\n\n    std::vector<int> const& batch_predicts\n    (Eigen::Ref<const EigenMat> const &input);\n    std::vector<int> const& batch_predicts(cv::Mat const &input);\n    int predict(Eigen::Ref<const EigenMat> const &input);\n    int predict(cv::Mat const &input);\n\n    /**\n     * @brief Set the batch size of mini-batch\n     * @param batch_size batch size of mini-batch,default\\n\n     * value is 100, if the train data is smaller than\\n\n     * the batch size, the batch size will be same as the\\n\n     * batch size\n     */\n    void set_batch_size(int batch_size)\n    {\n        params_.batch_size_ = batch_size;\n    }\n\n    /**\n     * @brief softmax::set_epsillon\n     * @param epsillon The desired accuracy or change\\n\n     *  in parameters at which the iterative algorithm stops.\\n\n     *  Default value is 1e-5\n     */\n    void set_epsillon(double epsillon)\n    {\n        params_.epsillon_ = epsillon;\n    }\n\n    /**\n     * @brief Setup the lambda\n     * @param lambda the lambda value which determine the effect\\n\n     * of penalizes term.Default value is 2.0\n     */\n    void set_lambda(double lambda)\n    {\n        params_.lambda_ = lambda;\n    }\n\n    /**\n     * @brief Set the learning rate\n     * @param lrate The larger the learning rate, the faster\\n\n     * the convergence speed, but larger value may cause divergence too.\\n\n     * Default value is 0.2\n     */\n    void softmax::set_learning_rate(double lrate)\n    {\n        params_.lrate_ = lrate;\n    }\n\n    /**\n     * @brief Set max iterateration times\n     * @param max_iter max iteration time, default value is 10000\n     */\n    void softmax::set_max_iter(int max_iter)\n    {\n        params_.max_iter_ = max_iter;\n    }\n\n    void read(const std::string &file);\n\n    void train(const Eigen::Ref<const EigenMat> &train,\n               const std::vector<int> &labels);\n\n    void write(const std::string &file) const;\n\nprivate:    \n    double compute_cost(Eigen::Ref<const EigenMat> const &train,\n                        Eigen::Ref<const EigenMat> const &weight,\n                        Eigen::Ref<const EigenMat> const &ground_truth);\n\n    void compute_gradient(Eigen::Ref<const EigenMat> const &train,\n                          Eigen::Ref<const EigenMat> const &weight,\n                          Eigen::Ref<const EigenMat> const &ground_truth);\n\n    void compute_hypothesis(Eigen::Ref<const EigenMat> const &train,\n                            Eigen::Ref<const EigenMat> const &weight);\n\n    int get_batch_size(int sample_size) const\n    {\n        return std::min(sample_size, params_.batch_size_);\n    }\n\n    EigenMat get_ground_truth(int NumClass,\n                              int samples_size,\n                              std::map<int, int> const &unique_labels,\n                              std::vector<int> const &labels) const;\n    std::map<int, int> softmax::\n    get_unique_labels(const std::vector<int> &labels) const;\n\n    void gradient_check()\n    {\n        std::vector<int> const Labels{0, 1, 2, 0};\n        auto const UniqueLabels = get_unique_labels(Labels);\n        auto const NumClass = UniqueLabels.size();\n        EigenMat const Train = EigenMat::Random(10, 2);\n        weight_ = EigenMat::Random(NumClass, Train.rows());\n        grad_ = EigenMat::Zero(NumClass, Train.rows());\n        int const TrainCols = static_cast<int>(Train.cols());\n        EigenMat const GroundTruth = get_ground_truth(NumClass, TrainCols,\n                                                      UniqueLabels,\n                                                      Labels);\n        gradient_checking gc;\n        auto func = [&](EigenMat &theta)->double\n        {\n            return compute_cost(Train, theta, GroundTruth);\n        };\n\n        EigenMat const WeightBuffer = weight_;\n        EigenMat const Gradient =\n                gc.compute_gradient(weight_, func);\n\n        compute_cost(Train, WeightBuffer, GroundTruth);\n        compute_gradient(Train, WeightBuffer, GroundTruth);\n\n        std::cout<<std::boolalpha<<\"gradient checking pass : \"\n                <<gc.compare_gradient(grad_, Gradient)<<\"\\n\";//*/\n    }\n\n\n    struct criteria\n    {\n        criteria();\n        int batch_size_;\n        double cost_;\n        double epsillon_;\n        double lambda_;\n        double lrate_;\n        int max_iter_;\n    };\n\n    EigenMat hypothesis_;\n    EigenMat grad_;\n    EigenMat max_exp_power_;\n    criteria params_;\n    std::vector<int> predicts_;\n    EigenMat probability_;\n    EigenMat weight_;\n    EigenMat weight_sum_;\n};\n\ntemplate<typename T>\nsoftmax<T>::softmax()\n{\n\n}\n\n/**\n *@brief Predicts the response for input samples(multiple samples)\n *@param input input data for prediction, each col associate\\n\n * with one sample\n *@return Output prediction responses for corresponding samples\n *@pre rows are the features, cols are the corresponding samples.\\n\n * This function can predict multiple samples\n */\ntemplate<typename T>\nstd::vector<int> const& softmax<T>::\nbatch_predicts(Eigen::Ref<const EigenMat> const &input)\n{\n    predicts_.resize(input.cols());\n    compute_hypothesis(input, weight_);\n    for(size_t i = 0; i != predicts_.size(); ++i){\n        probability_ = (hypothesis_.col(i) *\n                        input.col(i).transpose()).\n                rowwise().sum();\n        EigenMat::Index max_row = 0, max_col = 0;\n        probability_.maxCoeff(&max_row, &max_col);\n        predicts_[i] = static_cast<int>(max_row);\n    }\n\n    return predicts_;\n}\n\n/**\n *@brief Predicts the response for input samples(multiple samples)\n *@param input input data for prediction, each col associate\\n\n * with one sample\n *@return Output prediction responses for corresponding samples\n *@pre rows are the features, cols are the corresponding samples.\\n\n * This function can predict multiple samples\n */\ntemplate<typename T>\nstd::vector<int> const& softmax<T>::\nbatch_predicts(cv::Mat const &input)\n{\n    Eigen::Map<EigenMat> const Map(reinterpret_cast<*>(input.data),\n                                   input.rows,\n                                   input.step / sizeof(T));\n    return batch_predicts(Map.block(0, 0, input.rows, input.cols));\n}\n\n/**\n *@brief Predicts the response for input sample(one sample)\n *@param input input data for prediction, each col associate\\n\n * with one sample\n *@return Output prediction responses for corresponding sample\n *@pre rows are the features, col is the corresponding sample.\\n\n * This function can predict one sample only\n */\ntemplate<typename T>\nint softmax<T>::predict(Eigen::Ref<const EigenMat> const &input)\n{    \n    CV_Assert(input.cols() == 1);\n    compute_hypothesis(input, weight_);\n    probability_ = (hypothesis_ * input.transpose()).\n            rowwise().sum();\n    EigenMat::Index max_row = 0, max_col = 0;\n    probability_.maxCoeff(&max_row, &max_col);\n\n    return max_row;\n}\n\n/**\n *@brief Predicts the response for input sample(one sample)\n *@param input input data for prediction\n *@return Output prediction responses for corresponding sample\n *@pre rows are the features, col is the corresponding sample.\\n\n * This function can predict one sample only\n */\ntemplate<typename T>\nint softmax<T>::predict(cv::Mat const &input)\n{\n    Eigen::Map<EigenMat> const Map(reinterpret_cast<*>(input.data),\n                                   input.rows,\n                                   input.step / sizeof(T));\n    return predict(Map.block(0, 0, input.rows, input.cols));\n}\n\n/**\n * @brief read the training result into the data\n * @param file the name of the file\n */\ntemplate<typename T>\nvoid softmax<T>::read(const std::string &file)\n{\n    cv::FileStorage in(file, cv::FileStorage::READ);\n\n    in[\"batch_size\"]>>params_.batch_size_;\n    in[\"cost_\"]>>params_.cost_;\n    in[\"epsillon_\"]>>params_.epsillon_;\n    in[\"lambda_\"]>>params_.lambda_;\n    in[\"lrate_\"]>>params_.lrate_;\n    in[\"max_iter_\"]>>params_.max_iter_;\n    cv::Mat weight;\n    in[\"weight\"]>>weight;\n    eigen::cv2eigen_cpy(weight, weight_);\n}\n\n/**\n * @brief Train the input data by softmax algorithm\n * @param train Training data, input contains one\\n\n *  training example per column\n * @param labels The label of each training example\n */\ntemplate<typename T>\nvoid softmax<T>::train(const Eigen::Ref<const EigenMat> &train,\n                       const std::vector<int> &labels)\n{\n#ifdef OCV_TEST_SOFTMAX\n    gradient_check();\n#endif\n\n    auto const UniqueLabels = get_unique_labels(labels);\n    auto const NumClass = UniqueLabels.size();\n    weight_ = EigenMat::Random(NumClass, train.rows());\n    grad_ = EigenMat::Zero(NumClass, train.rows());\n    auto const TrainCols = static_cast<int>(train.cols());\n    EigenMat const GroundTruth = get_ground_truth(static_cast<int>(NumClass),\n                                                  TrainCols,\n                                                  UniqueLabels,\n                                                  labels);\n\n    std::random_device rd;\n    std::default_random_engine re(rd());\n    int const Batch = (get_batch_size(TrainCols));\n    int const RandomSize = TrainCols != Batch ?\n                TrainCols - Batch - 1 : 0;\n    std::uniform_int_distribution<int>\n            uni_int(0, RandomSize);\n    for(size_t i = 0; i != params_.max_iter_; ++i){\n        auto const Cols = uni_int(re);\n        auto const &TrainBlock =\n                train.block(0, Cols, train.rows(), Batch);\n        auto const &GTBlock =\n                GroundTruth.block(0, Cols, NumClass, Batch);\n        auto const Cost = compute_cost(TrainBlock, weight_, GTBlock);\n        if(std::abs(params_.cost_ - Cost) < params_.epsillon_ ||\n                Cost < 0){\n            break;\n        }\n        params_.cost_ = Cost;\n        compute_gradient(TrainBlock, weight_, GTBlock);\n        weight_.array() -= grad_.array() * params_.lrate_;//*/\n    }\n}\n\ntemplate<typename T>\nvoid softmax<T>::write(const std::string &file) const\n{\n    cv::FileStorage out(file, cv::FileStorage::WRITE);\n\n    out<<\"batch_size\"<<params_.batch_size_;\n    out<<\"cost_\"<<params_.cost_;\n    out<<\"epsillon_\"<<params_.epsillon_;\n    out<<\"lambda_\"<<params_.lambda_;\n    out<<\"lrate_\"<<params_.lrate_;\n    out<<\"max_iter_\"<<params_.max_iter_;\n    cv::Mat const Weight = eigen::eigen2cv_ref(weight_);\n    out<<\"weight\"<<Weight;\n}\n\ntemplate<typename T>\ndouble softmax<T>::compute_cost(const Eigen::Ref<const EigenMat> &train,\n                                const Eigen::Ref<const EigenMat> &weight,\n                                const Eigen::Ref<const EigenMat> &ground_truth)\n{    \n    compute_hypothesis(train, weight);\n    double const NSamples = static_cast<double>(train.cols());\n    return  -1.0 * (hypothesis_.array().log() *\n                    ground_truth.array()).sum() / NSamples +\n            weight.array().pow(2.0).sum() * params_.lambda_ / 2.0;\n}\n\ntemplate<typename T>\nvoid softmax<T>::compute_gradient(Eigen::Ref<const EigenMat> const &train,\n                                  Eigen::Ref<const EigenMat> const &weight,\n                                  Eigen::Ref<const EigenMat> const &ground_truth)\n{\n    grad_.noalias() =\n            (ground_truth.array() - hypothesis_.array())\n            .matrix() * train.transpose();\n    auto const NSamples = static_cast<double>(train.cols());\n    grad_.array() = grad_.array() / -NSamples +\n            params_.lambda_ * weight.array();\n}\n\ntemplate<typename T>\nvoid softmax<T>::compute_hypothesis(Eigen::Ref<const EigenMat> const &train,\n                                    Eigen::Ref<const EigenMat> const &weight)\n{    \n    hypothesis_.noalias() = weight * train;\n    max_exp_power_ = hypothesis_.colwise().maxCoeff();\n    for(size_t i = 0; i != hypothesis_.cols(); ++i){\n        hypothesis_.col(i).array() -= max_exp_power_(0, i);\n    }\n\n    hypothesis_ = hypothesis_.array().exp();\n    weight_sum_ = hypothesis_.array().colwise().sum();\n    for(size_t i = 0; i != hypothesis_.cols(); ++i){\n        if(weight_sum_(0, i) != T(0)){\n            hypothesis_.col(i) /= weight_sum_(0, i);\n        }\n    }\n    hypothesis_ = (hypothesis_.array() != 0 ).\n            select(hypothesis_, T(0.1));\n}\n\ntemplate<typename T>\ntypename softmax<T>::EigenMat softmax<T>::\nget_ground_truth(int NumClass, int samples_size,\n                 std::map<int, int> const &unique_labels,\n                 std::vector<int> const &labels) const\n{\n    EigenMat ground_truth = EigenMat::Zero(NumClass, samples_size);\n    for(size_t i = 0; i != ground_truth.cols(); ++i){\n        auto it = unique_labels.find(labels[i]);\n        if(it != std::end(unique_labels)){\n            ground_truth(it->second, i) = 1;\n        }\n    }\n\n    return ground_truth;\n}\n\ntemplate<typename T>\nstd::map<int, int> softmax<T>::\nget_unique_labels(const std::vector<int> &labels) const\n{\n    std::set<int> const UniqueLabels(std::begin(labels),\n                                     std::end(labels));\n    std::map<int, int> result;\n    int i = 0;\n    for(auto it = std::begin(UniqueLabels);\n        it != std::end(UniqueLabels); ++it){\n        if(result.find(*it) ==\n                std::end(result)){\n            result.emplace(*it, i++);\n        }\n    }\n\n    return result;\n}\n\ntemplate<typename T>\nsoftmax<T>::criteria::criteria() :\n    batch_size_{100},\n    cost_{std::numeric_limits<double>::max()},\n    epsillon_{1e-5},\n    lambda_{2.0},\n    lrate_{0.2},\n    max_iter_{10000}\n{\n\n}\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // SOFTMAX_H\n", "meta": {"hexsha": "8e0f74cbc13287aeb3dbed25441f7c7bfef878d2", "size": 14347, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/deep_learning/softmax.hpp", "max_stars_repo_name": "stereomatchingkiss/ocv_libs", "max_stars_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-12-17T05:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T02:59:29.000Z", "max_issues_repo_path": "ml/deep_learning/softmax.hpp", "max_issues_repo_name": "stereomatchingkiss/ocv_libs", "max_issues_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/deep_learning/softmax.hpp", "max_forks_repo_name": "stereomatchingkiss/ocv_libs", "max_forks_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-05-10T11:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T17:06:06.000Z", "avg_line_length": 30.7875536481, "max_line_length": 91, "alphanum_fraction": 0.6122534328, "num_tokens": 3362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5730994662166441}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2016 - 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: Ryan Grove, Clemson University \n *         Timo Heister, Clemson University \n */ \n\n\n// @sect3{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/base/utilities.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/block_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_gmres.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#include <deal.II/grid/grid_refinement.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/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n#include <deal.II/lac/sparse_direct.h> \n\n#include <deal.II/lac/sparse_ilu.h> \n#include <deal.II/grid/grid_out.h> \n\n// 我们需要包括以下文件来做计时。\n\n#include <deal.II/base/timer.h> \n\n// 这包括我们使用几何多网格所需的文件\n\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#include <iostream> \n#include <fstream> \n\nnamespace Step56 \n{ \n  using namespace dealii; \n\n// 为了便于在所使用的不同求解器之间进行切换，我们声明了一个枚举，可以作为参数传递给主类的构造函数。\n\n  enum class SolverType \n  { \n    FGMRES_ILU, \n    FGMRES_GMG, \n    UMFPACK \n  }; \n// @sect3{Functions for Solution and Righthand side}  \n\n//Solution类用于定义边界条件和计算数值解的误差。请注意，我们需要定义数值和梯度，以便计算L2和H1误差。在这里，我们决定使用模板的特殊化来分离2D和3D的实现。\n\n// 请注意，前几个分量是速度分量，最后一个分量是压力。\n\n  template <int dim> \n  class Solution : public Function<dim> \n  { \n  public: \n    Solution() \n      : Function<dim>(dim + 1) \n    {} \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n    virtual Tensor<1, dim> \n    gradient(const Point<dim> & p, \n             const unsigned int component = 0) const override; \n  }; \n\n  template <> \n  double Solution<2>::value(const Point<2> &   p, \n                            const unsigned int component) const \n  { \n    Assert(component <= 2 + 1, ExcIndexRange(component, 0, 2 + 1)); \n\n    using numbers::PI; \n    const double x = p(0); \n    const double y = p(1); \n\n    if (component == 0) \n      return sin(PI * x); \n    if (component == 1) \n      return -PI * y * cos(PI * x); \n    if (component == 2) \n      return sin(PI * x) * cos(PI * y); \n\n    return 0; \n  } \n\n  template <> \n  double Solution<3>::value(const Point<3> &   p, \n                            const unsigned int component) const \n  { \n    Assert(component <= 3 + 1, ExcIndexRange(component, 0, 3 + 1)); \n\n    using numbers::PI; \n    const double x = p(0); \n    const double y = p(1); \n    const double z = p(2); \n\n    if (component == 0) \n      return 2.0 * sin(PI * x); \n    if (component == 1) \n      return -PI * y * cos(PI * x); \n    if (component == 2) \n      return -PI * z * cos(PI * x); \n    if (component == 3) \n      return sin(PI * x) * cos(PI * y) * sin(PI * z); \n\n    return 0; \n  } \n\n// 注意，对于梯度，我们需要返回一个Tensor<1,dim>。\n\n  template <> \n  Tensor<1, 2> Solution<2>::gradient(const Point<2> &   p, \n                                     const unsigned int component) const \n  { \n    Assert(component <= 2, ExcIndexRange(component, 0, 2 + 1)); \n\n    using numbers::PI; \n    const double x = p(0); \n    const double y = p(1); \n\n    Tensor<1, 2> return_value; \n    if (component == 0) \n      { \n        return_value[0] = PI * cos(PI * x); \n        return_value[1] = 0.0; \n      } \n    else if (component == 1) \n      { \n        return_value[0] = y * PI * PI * sin(PI * x); \n        return_value[1] = -PI * cos(PI * x); \n      } \n    else if (component == 2) \n      { \n        return_value[0] = PI * cos(PI * x) * cos(PI * y); \n        return_value[1] = -PI * sin(PI * x) * sin(PI * y); \n      } \n\n    return return_value; \n  } \n\n  template <> \n  Tensor<1, 3> Solution<3>::gradient(const Point<3> &   p, \n                                     const unsigned int component) const \n  { \n    Assert(component <= 3, ExcIndexRange(component, 0, 3 + 1)); \n\n    using numbers::PI; \n    const double x = p(0); \n    const double y = p(1); \n    const double z = p(2); \n\n    Tensor<1, 3> return_value; \n    if (component == 0) \n      { \n        return_value[0] = 2 * PI * cos(PI * x); \n        return_value[1] = 0.0; \n        return_value[2] = 0.0; \n      } \n    else if (component == 1) \n      { \n        return_value[0] = y * PI * PI * sin(PI * x); \n        return_value[1] = -PI * cos(PI * x); \n        return_value[2] = 0.0; \n      } \n    else if (component == 2) \n      { \n        return_value[0] = z * PI * PI * sin(PI * x); \n        return_value[1] = 0.0; \n        return_value[2] = -PI * cos(PI * x); \n      } \n    else if (component == 3) \n      { \n        return_value[0] = PI * cos(PI * x) * cos(PI * y) * sin(PI * z); \n        return_value[1] = -PI * sin(PI * x) * sin(PI * y) * sin(PI * z); \n        return_value[2] = PI * sin(PI * x) * cos(PI * y) * cos(PI * z); \n      } \n\n    return return_value; \n  } \n\n// 实现  $f$  。更多信息请参见介绍。\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\n  template <> \n  double RightHandSide<2>::value(const Point<2> &   p, \n                                 const unsigned int component) const \n  { \n    Assert(component <= 2, ExcIndexRange(component, 0, 2 + 1)); \n\n    using numbers::PI; \n    double x = p(0); \n    double y = p(1); \n    if (component == 0) \n      return PI * PI * sin(PI * x) + PI * cos(PI * x) * cos(PI * y); \n    if (component == 1) \n      return -PI * PI * PI * y * cos(PI * x) - PI * sin(PI * y) * sin(PI * x); \n    if (component == 2) \n      return 0; \n\n    return 0; \n  } \n\n  template <> \n  double RightHandSide<3>::value(const Point<3> &   p, \n                                 const unsigned int component) const \n  { \n    Assert(component <= 3, ExcIndexRange(component, 0, 3 + 1)); \n\n    using numbers::PI; \n    double x = p(0); \n    double y = p(1); \n    double z = p(2); \n    if (component == 0) \n      return 2 * PI * PI * sin(PI * x) + \n             PI * cos(PI * x) * cos(PI * y) * sin(PI * z); \n    if (component == 1) \n      return -PI * PI * PI * y * cos(PI * x) + \n             PI * (-1) * sin(PI * y) * sin(PI * x) * sin(PI * z); \n    if (component == 2) \n      return -PI * PI * PI * z * cos(PI * x) + \n             PI * cos(PI * z) * sin(PI * x) * cos(PI * y); \n    if (component == 3) \n      return 0; \n\n    return 0; \n  } \n\n//  @sect3{ASPECT BlockSchurPreconditioner}  \n\n// 在下文中，我们将实现一个预处理程序，它扩展了  step-22  的结果部分所讨论的想法。具体来说，我们1.使用一个上块三角的预处理器，因为我们想使用右预处理。2.可选择允许对速度块使用内部求解器，而不是使用单一的预处理程序。3.不使用InverseMatrix，而是明确地调用SolverCG。这种方法也用于ASPECT代码（见https:aspect.geodynamics.org），该代码在模拟地幔对流的背景下求解斯托克斯方程，该代码已被用于解决成千上万个处理器上的问题。\n\n//构造函数中的bool标志 @p do_solve_A 允许我们对速度块应用一次预处理，或者使用内部迭代求解器来代替更精确的近似。\n\n// 注意我们是如何跟踪内部迭代的总和（预处理程序的应用）的。\n\n  template <class PreconditionerAType, class PreconditionerSType> \n  class BlockSchurPreconditioner : public Subscriptor \n  { \n  public: \n    BlockSchurPreconditioner( \n      const BlockSparseMatrix<double> &system_matrix, \n      const SparseMatrix<double> &     schur_complement_matrix, \n      const PreconditionerAType &      preconditioner_A, \n      const PreconditionerSType &      preconditioner_S, \n      const bool                       do_solve_A);\n\n    void vmult(BlockVector<double> &dst, const BlockVector<double> &src) const; \n\n    mutable unsigned int n_iterations_A; \n    mutable unsigned int n_iterations_S; \n\n  private: \n    const BlockSparseMatrix<double> &system_matrix; \n    const SparseMatrix<double> &     schur_complement_matrix; \n    const PreconditionerAType &      preconditioner_A; \n    const PreconditionerSType &      preconditioner_S; \n\n    const bool do_solve_A; \n  }; \n\n  template <class PreconditionerAType, class PreconditionerSType> \n  BlockSchurPreconditioner<PreconditionerAType, PreconditionerSType>:: \n    BlockSchurPreconditioner( \n      const BlockSparseMatrix<double> &system_matrix, \n      const SparseMatrix<double> &     schur_complement_matrix, \n      const PreconditionerAType &      preconditioner_A, \n      const PreconditionerSType &      preconditioner_S, \n      const bool                       do_solve_A) \n    : n_iterations_A(0)  \n    , n_iterations_S(0) \n    , system_matrix(system_matrix) \n    , schur_complement_matrix(schur_complement_matrix) \n    , preconditioner_A(preconditioner_A) \n    , preconditioner_S(preconditioner_S) \n    , do_solve_A(do_solve_A) \n  {} \n\n  template <class PreconditionerAType, class PreconditionerSType> \n  void \n  BlockSchurPreconditioner<PreconditionerAType, PreconditionerSType>::vmult( \n    BlockVector<double> &      dst, \n    const BlockVector<double> &src) const \n  { \n    Vector<double> utmp(src.block(0)); \n\n// 首先用S的近似值求解\n\n    { \n      SolverControl solver_control(1000, 1e-6 * src.block(1).l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n\n      dst.block(1) = 0.0; \n      cg.solve(schur_complement_matrix, \n               dst.block(1), \n               src.block(1), \n               preconditioner_S); \n\n      n_iterations_S += solver_control.last_step(); \n      dst.block(1) *= -1.0; \n    } \n\n// 第二，应用右上方的块（B^T\n\n    { \n      system_matrix.block(0, 1).vmult(utmp, dst.block(1)); \n      utmp *= -1.0; \n      utmp += src.block(0); \n    } \n\n// 最后，要么用左上角的块求解，要么只应用一个预设条件器扫频\n\n    if (do_solve_A == true) \n      { \n        SolverControl            solver_control(10000, utmp.l2_norm() * 1e-4); \n        SolverCG<Vector<double>> cg(solver_control); \n\n        dst.block(0) = 0.0; \n        cg.solve(system_matrix.block(0, 0), \n                 dst.block(0), \n                 utmp, \n                 preconditioner_A); \n\n        n_iterations_A += solver_control.last_step(); \n      } \n    else \n      { \n        preconditioner_A.vmult(dst.block(0), utmp); \n        n_iterations_A += 1; \n      } \n  } \n// @sect3{The StokesProblem class}  \n\n// 这是该问题的主类。\n\n  template <int dim> \n  class StokesProblem \n  { \n  public: \n    StokesProblem(const unsigned int pressure_degree, \n                  const SolverType   solver_type); \n    void run(); \n\n  private: \n    void setup_dofs(); \n    void assemble_system(); \n    void assemble_multigrid(); \n    void solve(); \n    void compute_errors(); \n    void output_results(const unsigned int refinement_cycle) const; \n\n    const unsigned int pressure_degree; \n    const SolverType   solver_type; \n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      velocity_fe; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n    DoFHandler<dim>    velocity_dof_handler; \n\n    AffineConstraints<double> constraints; \n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n    SparseMatrix<double>      pressure_mass_matrix; \n\n    BlockVector<double> solution; \n    BlockVector<double> system_rhs; \n\n    MGLevelObject<SparsityPattern>      mg_sparsity_patterns; \n    MGLevelObject<SparseMatrix<double>> mg_matrices; \n    MGLevelObject<SparseMatrix<double>> mg_interface_matrices; \n    MGConstrainedDoFs                   mg_constrained_dofs; \n\n    TimerOutput computing_timer; \n  }; \n\n  template <int dim> \n  StokesProblem<dim>::StokesProblem(const unsigned int pressure_degree, \n                                    const SolverType   solver_type) \n\n    : pressure_degree(pressure_degree) \n    , solver_type(solver_type) \n    , triangulation(Triangulation<dim>::maximum_smoothing) \n    , \n\n// 仅为速度的有限元。\n\n    velocity_fe(FE_Q<dim>(pressure_degree + 1), dim) \n    , \n\n// 整个系统的有限元。\n\n    fe(velocity_fe, 1, FE_Q<dim>(pressure_degree), 1) \n    , dof_handler(triangulation) \n    , velocity_dof_handler(triangulation) \n    , computing_timer(std::cout, TimerOutput::never, TimerOutput::wall_times) \n  {} \n\n//  @sect4{StokesProblem::setup_dofs}  \n\n// 这个函数设置了DoFHandler、矩阵、向量和Multigrid结构（如果需要）。\n\n  template <int dim> \n  void StokesProblem<dim>::setup_dofs() \n  { \n    TimerOutput::Scope scope(computing_timer, \"Setup\"); \n\n    system_matrix.clear(); \n    pressure_mass_matrix.clear(); \n\n// 主DoFHandler只需要活动的DoF，所以我们不在这里调用distribution_mg_dofs()\n\n    dof_handler.distribute_dofs(fe); \n\n// 这个块结构将dim速度分量与压力分量（用于重新排序）分开。注意，我们有2个而不是像 step-22 中的dim+1块，因为我们的FESystem是嵌套的，dim速度分量作为一个块出现。\n\n    std::vector<unsigned int> block_component(2); \n    block_component[0] = 0; \n    block_component[1] = 1; \n\n// 速度从组件0开始。\n\n    const FEValuesExtractors::Vector velocities(0); \n\n//如果我们应用重新排序来减少填充，\n//ILU的表现会更好。对于其他求解器来说，这样做并没有什么好处。\n\n    if (solver_type == SolverType::FGMRES_ILU) \n      { \n        TimerOutput::Scope ilu_specific(computing_timer, \"(ILU specific)\"); \n        DoFRenumbering::Cuthill_McKee(dof_handler); \n      } \n\n// 这确保了所有的速度DoFs在压力未知数之前被列举出来。这允许我们使用块来处理向量和矩阵，并允许我们为dof_handler和velocity_dof_handler获得相同的DoF编号。\n\n    DoFRenumbering::block_wise(dof_handler); \n\n    if (solver_type == SolverType::FGMRES_GMG) \n      { \n        TimerOutput::Scope multigrid_specific(computing_timer, \n                                              \"(Multigrid specific)\"); \n        TimerOutput::Scope setup_multigrid(computing_timer, \n                                           \"Setup - Multigrid\"); \n\n// 这将在一个单独的DoFHandler中分配速度空间的主动道夫和多网格道夫，如介绍中所述。\n\n        velocity_dof_handler.distribute_dofs(velocity_fe); \n        velocity_dof_handler.distribute_mg_dofs(); \n\n// 下面的代码块初始化了MGConstrainedDofs（使用速度的边界条件），以及每个层次的稀疏模式和矩阵。MGLevelObject<T>的resize()函数将破坏所有现有的包含对象。\n\n        std::set<types::boundary_id> zero_boundary_ids; \n        zero_boundary_ids.insert(0); \n\n        mg_constrained_dofs.clear(); \n        mg_constrained_dofs.initialize(velocity_dof_handler); \n        mg_constrained_dofs.make_zero_boundary_constraints(velocity_dof_handler, \n                                                           zero_boundary_ids); \n        const unsigned int n_levels = triangulation.n_levels(); \n\n        mg_interface_matrices.resize(0, n_levels - 1); \n        mg_matrices.resize(0, n_levels - 1); \n        mg_sparsity_patterns.resize(0, n_levels - 1); \n\n        for (unsigned int level = 0; level < n_levels; ++level) \n          { \n            DynamicSparsityPattern csp(velocity_dof_handler.n_dofs(level), \n                                       velocity_dof_handler.n_dofs(level)); \n            MGTools::make_sparsity_pattern(velocity_dof_handler, csp, level); \n            mg_sparsity_patterns[level].copy_from(csp); \n\n            mg_matrices[level].reinit(mg_sparsity_patterns[level]); \n            mg_interface_matrices[level].reinit(mg_sparsity_patterns[level]); \n          } \n      } \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    const unsigned int n_p = dofs_per_block[1]; \n\n    { \n      constraints.clear(); \n\n// 下面利用分量掩码对速度的边界值进行插值，这在矢量值dealii  step-20 教程中进一步说明。\n\n      DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               0, \n                                               Solution<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n\n// 正如在介绍中所讨论的，我们需要固定压力变量的一个自由度以确保问题的可解性。在这里，我们将第一个压力自由度标记为受限自由度，该自由度的索引为n_u。\n\n      if (solver_type == SolverType::UMFPACK) \n        constraints.add_line(n_u); \n\n      constraints.close(); \n    } \n\n    std::cout << \"\\tNumber of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"\\tNumber of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (\" << n_u << '+' << n_p << ')' << std::endl; \n\n    { \n      BlockDynamicSparsityPattern csp(dofs_per_block, dofs_per_block); \n      DoFTools::make_sparsity_pattern(dof_handler, csp, constraints, false); \n      sparsity_pattern.copy_from(csp); \n    } \n    system_matrix.reinit(sparsity_pattern); \n\n    solution.reinit(dofs_per_block); \n    system_rhs.reinit(dofs_per_block); \n  } \n// @sect4{StokesProblem::assemble_system}  \n\n// 在这个函数中，系统矩阵被组装起来。我们在(1,1)块中组装压力质量矩阵（如果需要），并在此函数结束时将其移出此位置。\n\n  template <int dim> \n  void StokesProblem<dim>::assemble_system() \n  { \n    TimerOutput::Scope assemble(computing_timer, \"Assemble\"); \n    system_matrix = 0; \n    system_rhs    = 0; \n\n// 如果为真，我们将在(1,1)块中装配压力质量矩阵。\n\n    const bool assemble_pressure_mass_matrix = \n      (solver_type == SolverType::UMFPACK) ? false : true; \n\n    QGauss<dim> quadrature_formula(pressure_degree + 2); \n\n    FEValues<dim> fe_values(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    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      { \n        fe_values.reinit(cell); \n        local_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                      (2 * (symgrad_phi_u[i] * symgrad_phi_u[j]) - \n                       div_phi_u[i] * phi_p[j] - phi_p[i] * div_phi_u[j] + \n                       (assemble_pressure_mass_matrix ? phi_p[i] * phi_p[j] : \n                                                        0)) * \n                      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) * 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            local_matrix(i, j) = local_matrix(j, i); \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      } \n\n    if (solver_type != SolverType::UMFPACK) \n      { \n        pressure_mass_matrix.reinit(sparsity_pattern.block(1, 1)); \n        pressure_mass_matrix.copy_from(system_matrix.block(1, 1)); \n        system_matrix.block(1, 1) = 0; \n      } \n  } \n// @sect4{StokesProblem::assemble_multigrid}  \n\n// 在这里，与 step-16 中一样，我们有一个函数，用于组装多网格预处理程序所需的水平矩阵和界面矩阵。\n\n  template <int dim> \n  void StokesProblem<dim>::assemble_multigrid() \n  { \n    TimerOutput::Scope multigrid_specific(computing_timer, \n                                          \"(Multigrid specific)\"); \n    TimerOutput::Scope assemble_multigrid(computing_timer, \n                                          \"Assemble Multigrid\"); \n\n    mg_matrices = 0.; \n\n    QGauss<dim> quadrature_formula(pressure_degree + 2); \n\n    FEValues<dim> fe_values(velocity_fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points | \n                              update_JxW_values | update_gradients); \n\n    const unsigned int dofs_per_cell = velocity_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 FEValuesExtractors::Vector velocities(0); \n\n    std::vector<SymmetricTensor<2, dim>> symgrad_phi_u(dofs_per_cell); \n\n    std::vector<AffineConstraints<double>> boundary_constraints( \n      triangulation.n_levels()); \n    std::vector<AffineConstraints<double>> boundary_interface_constraints( \n      triangulation.n_levels()); \n    for (unsigned int level = 0; level < triangulation.n_levels(); ++level) \n      { \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        boundary_constraints[level].close(); \n\n        IndexSet idx = mg_constrained_dofs.get_refinement_edge_indices(level) & \n                       mg_constrained_dofs.get_boundary_indices(level); \n\n        boundary_interface_constraints[level].add_lines(idx); \n        boundary_interface_constraints[level].close(); \n      } \n\n// 这个迭代器会覆盖所有的单元格（不仅仅是活动的）。\n\n    for (const auto &cell : velocity_dof_handler.cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        cell_matrix = 0; \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              symgrad_phi_u[k] = fe_values[velocities].symmetric_gradient(k, q); \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int j = 0; j <= i; ++j) \n                { \n                  cell_matrix(i, j) += \n                    (symgrad_phi_u[i] * symgrad_phi_u[j]) * 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            cell_matrix(i, j) = cell_matrix(j, i); \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_matrices[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.at_refinement_edge(cell->level(), \n                                                        local_dof_indices[i]) || \n                mg_constrained_dofs.at_refinement_edge(cell->level(), \n                                                       local_dof_indices[j])) \n              cell_matrix(i, j) = 0; \n\n        boundary_interface_constraints[cell->level()] \n          .distribute_local_to_global(cell_matrix, \n                                      local_dof_indices, \n                                      mg_interface_matrices[cell->level()]); \n      } \n  } \n// @sect4{StokesProblem::solve}  \n\n// 这个函数根据你想使用ILU或GMG作为预处理程序的情况进行不同的设置。 这两种方法共享相同的求解器（FGMRES），但需要初始化不同的预处理器。在这里，我们不仅为整个求解函数计时，还为预处理程序的设置以及求解本身分别计时。\n\n  template <int dim> \n  void StokesProblem<dim>::solve() \n  { \n    TimerOutput::Scope solve(computing_timer, \"Solve\"); \n    constraints.set_zero(solution); \n\n    if (solver_type == SolverType::UMFPACK) \n      { \n        computing_timer.enter_subsection(\"(UMFPACK specific)\"); \n        computing_timer.enter_subsection(\"Solve - Initialize\"); \n\n        SparseDirectUMFPACK A_direct; \n        A_direct.initialize(system_matrix); \n\n        computing_timer.leave_subsection(); \n        computing_timer.leave_subsection(); \n\n        { \n          TimerOutput::Scope solve_backslash(computing_timer, \n                                             \"Solve - Backslash\"); \n          A_direct.vmult(solution, system_rhs); \n        } \n\n        constraints.distribute(solution); \n        return; \n      } \n\n// 这里我们必须确保以 \"足够好 \"的精度求解残差\n\n    SolverControl solver_control(system_matrix.m(), \n                                 1e-10 * system_rhs.l2_norm()); \n    unsigned int  n_iterations_A; \n    unsigned int  n_iterations_S; \n\n// 这是用来传递我们是否要在预处理程序中解决A的问题。 我们可以把它改为false，看看是否还能收敛，如果能收敛，那么程序的运行速度是快是慢？\n\n    const bool use_expensive = true; \n\n    SolverFGMRES<BlockVector<double>> solver(solver_control); \n\n    if (solver_type == SolverType::FGMRES_ILU) \n      { \n        computing_timer.enter_subsection(\"(ILU specific)\"); \n        computing_timer.enter_subsection(\"Solve - Set-up Preconditioner\"); \n\n        std::cout << \"   Computing preconditioner...\" << std::endl \n                  << std::flush; \n\n        SparseILU<double> A_preconditioner; \n        A_preconditioner.initialize(system_matrix.block(0, 0)); \n\n        SparseILU<double> S_preconditioner; \n        S_preconditioner.initialize(pressure_mass_matrix); \n\n        const BlockSchurPreconditioner<SparseILU<double>, SparseILU<double>> \n          preconditioner(system_matrix, \n                         pressure_mass_matrix, \n                         A_preconditioner, \n                         S_preconditioner, \n                         use_expensive); \n\n        computing_timer.leave_subsection(); \n        computing_timer.leave_subsection(); \n\n        { \n          TimerOutput::Scope solve_fmgres(computing_timer, \"Solve - FGMRES\"); \n\n          solver.solve(system_matrix, solution, system_rhs, preconditioner); \n          n_iterations_A = preconditioner.n_iterations_A; \n          n_iterations_S = preconditioner.n_iterations_S; \n        } \n      } \n    else \n      { \n        computing_timer.enter_subsection(\"(Multigrid specific)\"); \n        computing_timer.enter_subsection(\"Solve - Set-up Preconditioner\"); \n\n// 在各级之间转移运算符\n\n        MGTransferPrebuilt<Vector<double>> mg_transfer(mg_constrained_dofs); \n        mg_transfer.build(velocity_dof_handler); \n\n// 设置粗略的网格解算器\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        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\n// Multigrid作为CG的预处理程序时，需要是一个对称的运算器，所以平滑器必须是对称的\n\n        mg_smoother.set_symmetric(true); \n\n        mg::Matrix<Vector<double>> mg_matrix(mg_matrices); \n        mg::Matrix<Vector<double>> mg_interface_up(mg_interface_matrices); \n        mg::Matrix<Vector<double>> mg_interface_down(mg_interface_matrices); \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          A_Multigrid(velocity_dof_handler, mg, mg_transfer); \n\n        SparseILU<double> S_preconditioner; \n        S_preconditioner.initialize(pressure_mass_matrix, \n                                    SparseILU<double>::AdditionalData()); \n\n        const BlockSchurPreconditioner< \n          PreconditionMG<dim, \n                         Vector<double>, \n                         MGTransferPrebuilt<Vector<double>>>, \n          SparseILU<double>> \n          preconditioner(system_matrix, \n                         pressure_mass_matrix, \n                         A_Multigrid, \n                         S_preconditioner, \n                         use_expensive); \n\n        computing_timer.leave_subsection(); \n        computing_timer.leave_subsection(); \n\n        { \n          TimerOutput::Scope solve_fmgres(computing_timer, \"Solve - FGMRES\"); \n          solver.solve(system_matrix, solution, system_rhs, preconditioner); \n          n_iterations_A = preconditioner.n_iterations_A; \n          n_iterations_S = preconditioner.n_iterations_S; \n        } \n      } \n\n    constraints.distribute(solution); \n\n    std::cout \n      << std::endl \n      << \"\\tNumber of FGMRES iterations: \" << solver_control.last_step() \n      << std::endl \n      << \"\\tTotal number of iterations used for approximation of A inverse: \" \n      << n_iterations_A << std::endl \n      << \"\\tTotal number of iterations used for approximation of S inverse: \" \n      << n_iterations_S << std::endl \n      << std::endl; \n  } \n// @sect4{StokesProblem::process_solution}  \n\n// 这个函数计算出解决方案的L2和H1误差。为此，我们需要确保压力的平均值为零。\n\n  template <int dim> \n  void StokesProblem<dim>::compute_errors() \n  { \n\n// 计算平均压力 $\\frac{1}{\\Omega} \\int_{\\Omega} p(x) dx $ ，然后从每个压力系数中减去它。这将产生一个平均值为零的压力。这里我们利用了压力是分量 $dim$ 和有限元空间是结点的事实。\n\n    const double mean_pressure = VectorTools::compute_mean_value( \n      dof_handler, QGauss<dim>(pressure_degree + 2), solution, dim); \n    solution.block(1).add(-mean_pressure); \n    std::cout << \"   Note: The mean value was adjusted by \" << -mean_pressure \n              << std::endl; \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    Vector<float> difference_per_cell(triangulation.n_active_cells()); \n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(pressure_degree + 2), \n                                      VectorTools::L2_norm, \n                                      &velocity_mask); \n\n    const double Velocity_L2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(pressure_degree + 2), \n                                      VectorTools::L2_norm, \n                                      &pressure_mask); \n\n    const double Pressure_L2_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::L2_norm); \n\n    VectorTools::integrate_difference(dof_handler, \n                                      solution, \n                                      Solution<dim>(), \n                                      difference_per_cell, \n                                      QGauss<dim>(pressure_degree + 2), \n                                      VectorTools::H1_norm, \n                                      &velocity_mask); \n\n    const double Velocity_H1_error = \n      VectorTools::compute_global_error(triangulation, \n                                        difference_per_cell, \n                                        VectorTools::H1_norm); \n\n    std::cout << std::endl \n              << \"   Velocity L2 Error: \" << Velocity_L2_error << std::endl \n              << \"   Pressure L2 Error: \" << Pressure_L2_error << std::endl \n              << \"   Velocity H1 Error: \" << Velocity_H1_error << std::endl; \n  } \n// @sect4{StokesProblem::output_results}  \n\n// 这个函数生成图形输出，就像在  step-22  中所做的那样。\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    data_out.build_patches(); \n\n    std::ofstream output( \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n\n//  @sect4{StokesProblem::run}  \n\n// 斯托克斯类的最后一步是像往常一样，生成初始网格的函数，并按各自的顺序调用其他函数。\n\n  template <int dim> \n  void StokesProblem<dim>::run() \n  { \n    GridGenerator::hyper_cube(triangulation); \n    triangulation.refine_global(6 - dim); \n\n    if (solver_type == SolverType::FGMRES_ILU) \n      std::cout << \"Now running with ILU\" << std::endl; \n    else if (solver_type == SolverType::FGMRES_GMG) \n      std::cout << \"Now running with Multigrid\" << std::endl; \n    else \n      std::cout << \"Now running with UMFPACK\" << std::endl; \n\n    for (unsigned int refinement_cycle = 0; refinement_cycle < 3; \n         ++refinement_cycle) \n      { \n        std::cout << \"Refinement cycle \" << refinement_cycle << std::endl; \n\n        if (refinement_cycle > 0) \n          triangulation.refine_global(1); \n\n        std::cout << \"   Set-up...\" << std::endl; \n        setup_dofs(); \n\n        std::cout << \"   Assembling...\" << std::endl; \n        assemble_system(); \n\n        if (solver_type == SolverType::FGMRES_GMG) \n          { \n            std::cout << \"   Assembling Multigrid...\" << std::endl; \n\n            assemble_multigrid(); \n          } \n\n        std::cout << \"   Solving...\" << std::flush; \n        solve(); \n\n        compute_errors(); \n\n        output_results(refinement_cycle); \n\n        Utilities::System::MemoryStats mem; \n        Utilities::System::get_memory_stats(mem); \n        std::cout << \"   VM Peak: \" << mem.VmPeak << std::endl; \n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n      } \n  } \n} // namespace Step56 \n// @sect3{The main function}  \nint main() \n{ \n  try \n    { \n      using namespace Step56; \n\n      const int degree = 1; \n      const int dim    = 3; \n\n// SolverType的选项。umfpack fgmres_ilu fgmres_gmg\n\n      StokesProblem<dim> flow_problem(degree, SolverType::FGMRES_GMG); \n\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\n", "meta": {"hexsha": "0c903917c9c98822aa1172173077dcb2192a97c2", "size": 37190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-56/step-56.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-56/step-56.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-56/step-56.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": 33.4442446043, "max_line_length": 243, "alphanum_fraction": 0.5820919602, "num_tokens": 10599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5730994659607497}}
{"text": "/*\n * L2L2.cpp\n *\n *  Created on: 13.03.2018\n *      Author: thies\n */\n\n#include <deal.II/numerics/vector_tools.h>\n#include <norms/L2L2.h>\n\nusing namespace dealii;\n\nnamespace wavepi {\nnamespace norms {\n\ntemplate <int dim>\ndouble L2L2<dim>::absolute_error(const DiscretizedFunction<dim>& u, Function<dim>& v) {\n  auto mesh     = u.get_mesh();\n  double result = 0;\n\n  // trapezoidal rule in time:\n  for (size_t i = 0; i < mesh->length(); i++) {\n    Vector<double> cellwise_error;\n\n    v.set_time(mesh->get_time(i));\n    VectorTools::integrate_difference(*mesh->get_dof_handler(i), u[i], v, cellwise_error, QGauss<dim>(5),\n                                      VectorTools::NormType::L2_norm);\n\n    double nrm =\n        VectorTools::compute_global_error(*mesh->get_triangulation(i), cellwise_error, VectorTools::NormType::L2_norm);\n\n    if (i > 0) result += nrm * nrm / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += nrm * nrm / 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 L2L2<dim>::norm(const DiscretizedFunction<dim>& u) const {\n  auto mesh     = u.get_mesh();\n  double result = 0;\n\n  // trapezoidal rule in time:\n  for (size_t i = 0; i < mesh->length(); i++) {\n    double nrm2 = mesh->get_mass_matrix(i)->matrix_norm_square(u[i]);\n\n    if (i > 0) result += nrm2 / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += nrm2 / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  // assume that function is linear in time (consistent with crank-nicolson!)\n  // and integrate that exactly (Simpson rule)\n  // problem when mesh changes in time!\n  //   for (size_t i = 0; i < mesh->length(); i++) {\n  //      double nrm2 = mesh->get_mass_matrix(i)->matrix_norm_square(function_coefficients[i]);\n  //\n  //      if (i > 0)\n  //         result += nrm2 / 3 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n  //\n  //      if (i < mesh->length() - 1)\n  //         result += nrm2 / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n  //\n  //   for (size_t i = 0; i < mesh->length() - 1; i++) {\n  //      double tmp = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            function_coefficients[i + 1]);\n  //\n  //      result += tmp / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n\n  return std::sqrt(result);\n}\n\ntemplate <int dim>\ndouble L2L2<dim>::dot(const DiscretizedFunction<dim>& u, const DiscretizedFunction<dim>& v) const {\n  auto mesh     = u.get_mesh();\n  double result = 0.0;\n\n  // trapezoidal rule in time:\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\n    if (i > 0) result += doti / 2 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n    if (i < mesh->length() - 1) result += doti / 2 * (std::abs(mesh->get_time(i + 1) - mesh->get_time(i)));\n  }\n\n  // assume that both functions are linear in time (consistent with crank-nicolson!)\n  // and integrate that exactly (Simpson rule)\n  // problem when mesh changes in time!\n  //   for (size_t i = 0; i < mesh->length(); i++) {\n  //      Assert(function_coefficients[i].size() == V.function_coefficients[i].size(),\n  //            ExcDimensionMismatch (function_coefficients[i].size() , V.function_coefficients[i].size()));\n  //\n  //      double doti = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            V.function_coefficients[i]);\n  //\n  //      if (i > 0)\n  //         result += doti / 3 * (std::abs(mesh->get_time(i) - mesh->get_time(i - 1)));\n  //\n  //      if (i < mesh->length() - 1)\n  //         result += doti / 3 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n  //\n  //   for (size_t i = 0; i < mesh->length() - 1; i++) {\n  //      Assert(function_coefficients[i].size() == V.function_coefficients[i+1].size(),\n  //            ExcDimensionMismatch (function_coefficients[i].size() , V.function_coefficients[i+1].size()));\n  //      Assert(function_coefficients[i+1].size() == V.function_coefficients[i].size(),\n  //             ExcDimensionMismatch (function_coefficients[i+1].size() , V.function_coefficients[i].size()));\n  //\n  //      double dot1 = mesh->get_mass_matrix(i)->matrix_scalar_product(function_coefficients[i],\n  //            V.function_coefficients[i + 1]);\n  //      double dot2 = mesh->get_mass_matrix(i + 1)->matrix_scalar_product(function_coefficients[i + 1],\n  //            V.function_coefficients[i]);\n  //\n  //      result += (dot1 + dot2) / 6 * (std::abs(mesh->get_time(i+1) - mesh->get_time(i)));\n  //   }\n\n  return result;\n}\n\ntemplate <int dim>\nvoid L2L2<dim>::dot_transform(DiscretizedFunction<dim>& u) {\n  u.mult_mass();\n  dot_solve_mass_and_transform(u);\n}\n\ntemplate <int dim>\nvoid L2L2<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u) {\n  u.solve_mass();\n  dot_mult_mass_and_transform_inverse(u);\n}\n\ntemplate <int dim>\nvoid L2L2<dim>::dot_solve_mass_and_transform(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\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    u[i] *= factor;\n  }\n}\n\ntemplate <int dim>\nvoid L2L2<dim>::dot_mult_mass_and_transform_inverse(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\n  // trapezoidal rule in time:\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    u[i] /= factor;\n  }\n}\n\ntemplate <int dim>\nstd::string L2L2<dim>::name() const {\n  return \"L²([0,T], L²(Ω))\";\n}\n\ntemplate <int dim>\nstd::string L2L2<dim>::unique_id() const {\n  return \"L²([0,T], L²(Ω))\";\n}\n\ntemplate class L2L2<1>;\ntemplate class L2L2<2>;\ntemplate class L2L2<3>;\n\n} /* namespace norms */\n} /* namespace wavepi */\n", "meta": {"hexsha": "57daa6796e4e3bdb2c7c5627910cdf51160603e0", "size": 6177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/norms/L2L2.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/L2L2.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/L2L2.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": 34.5083798883, "max_line_length": 119, "alphanum_fraction": 0.6051481302, "num_tokens": 1920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6297746074044135, "lm_q1q2_score": 0.5730363228863629}}
{"text": "// Copyright John Maddock 2015\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Comparison of finding roots using TOMS748, Newton-Raphson, Halley & Schroder algorithms.\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// This program also writes files in Quickbook tables mark-up format.\n\n#include <boost/cstdlib.hpp>\n#include <boost/config.hpp>\n#include <boost/array.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\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   }\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\ntemplate <class T>\nboost::uintmax_t cbrt_noderiv(T x, T guess)\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   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;                  // Initially 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   bracket_and_solve_root(cbrt_functor_noderiv<T>(x), guess, factor, is_rising, tol, it);\n   return it;\n}\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\ntemplate <class T>\nboost::uintmax_t cbrt_deriv(T x, T guess)\n{\n   // return cube root of x using 1st derivative and Newton_Raphson.\n   using namespace boost::math::tools;\n   T min = guess / 100;                     // We don't really know what this should be!\n   T max = guess * 100;                     // We don't really know what this should be!\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   newton_raphson_iterate(cbrt_functor_deriv<T>(x), guess, min, max, get_digits, it);\n   return it;\n}\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\ntemplate <class T>\nboost::uintmax_t cbrt_2deriv(T x, T guess)\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   T min = guess / 100;                     // We don't really know what this should be!\n   T max = guess * 100;                     // We don't really know what this should be!\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   halley_iterate(cbrt_functor_2deriv<T>(x), guess, min, max, get_digits, maxit);\n   return maxit;\n}\n\ntemplate <class T>\nboost::uintmax_t cbrt_2deriv_s(T x, T guess)\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   T min = guess / 100;                     // We don't really know what this should be!\n   T max = guess * 100;                     // We don't really know what this should be!\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   schroder_iterate(cbrt_functor_2deriv<T>(x), guess, min, max, get_digits, maxit);\n   return maxit;\n}\n\ntemplate <typename T = double>\nstruct elliptic_root_functor_noderiv\n{ \n   elliptic_root_functor_noderiv(T const& arc, T const& radius) : m_arc(arc), m_radius(radius)\n   { // Constructor just stores value a to find root of.\n   }\n   T operator()(T const& x)\n   {\n      // return the difference between required arc-length, and the calculated arc-length for an\n      // ellipse with radii m_radius and x:\n      T a = (std::max)(m_radius, x);\n      T b = (std::min)(m_radius, x);\n      T k = sqrt(1 - b * b / (a * a));\n      return 4 * a * boost::math::ellint_2(k) - m_arc;\n   }\nprivate:\n   T m_arc;     // length of arc.\n   T m_radius;  // one of the two radii of the ellipse\n}; // template <class T> struct elliptic_root_functor_noderiv\n\ntemplate <class T = double>\nboost::uintmax_t elliptic_root_noderiv(T radius, T arc, T guess)\n{ // return the other radius of an ellipse, given one radii and the arc-length\n   using namespace std;  // Help ADL of std functions.\n   using namespace boost::math::tools; // For bracket_and_solve_root.\n\n   T factor = 2;                       // How big steps to take when searching.\n\n   const boost::uintmax_t maxit = 50;  // Limit to maximum iterations.\n   boost::uintmax_t it = maxit;        // Initially our chosen max iterations, but updated with actual.\n   bool is_rising = true;              // arc-length increases if one radii increases, so function is rising\n   // Define a termination condition, stop when nearly all digits are correct, but allow for\n   // the fact that we are returning a range, and must have some inaccuracy in the elliptic integral:\n   eps_tolerance<T> tol(std::numeric_limits<T>::digits - 2);\n   // Call bracket_and_solve_root to find the solution, note that this is a rising function:\n   bracket_and_solve_root(elliptic_root_functor_noderiv<T>(arc, radius), guess, factor, is_rising, tol, it);\n   return it;\n} \n\ntemplate <class T = double>\nstruct elliptic_root_functor_1deriv\n{ // Functor also returning 1st derivative.\n   BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n\n   elliptic_root_functor_1deriv(T const& arc, T const& radius) : m_arc(arc), m_radius(radius)\n   { // Constructor just stores value a to find root of.\n   }\n   std::pair<T, T> operator()(T const& x)\n   {\n      // Return the difference between required arc-length, and the calculated arc-length for an\n      // ellipse with radii m_radius and x, plus it's derivative.\n      // See http://www.wolframalpha.com/input/?i=d%2Fda+[4+*+a+*+EllipticE%281+-+b^2%2Fa^2%29]\n      // We require two elliptic integral calls, but from these we can calculate both\n      // the function and it's derivative:\n      T a = (std::max)(m_radius, x);\n      T b = (std::min)(m_radius, x);\n      T a2 = a * a;\n      T b2 = b * b;\n      T k = sqrt(1 - b2 / a2);\n      T Ek = boost::math::ellint_2(k);\n      T Kk = boost::math::ellint_1(k);\n      T fx = 4 * a * Ek - m_arc;\n      T dfx = 4 * (a2 * Ek - b2 * Kk) / (a2 - b2);\n      return std::make_pair(fx, dfx);\n   }\nprivate:\n   T m_arc;     // length of arc.\n   T m_radius;  // one of the two radii of the ellipse\n};  // struct elliptic_root__functor_1deriv\n\ntemplate <class T = double>\nboost::uintmax_t elliptic_root_1deriv(T radius, T arc, T guess)\n{\n   using namespace std;  // Help ADL of std functions.\n   using namespace boost::math::tools; // For newton_raphson_iterate.\n\n   BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n\n   T min = 0;   // Minimum possible value is zero.\n   T max = arc; // Maximum possible value is the arc length.\n\n   // Accuracy doubles at each step, so stop when just over half of the digits are\n   // correct, and rely on that step to polish off the remainder:\n   int get_digits = static_cast<int>(std::numeric_limits<T>::digits * 0.6);\n   const boost::uintmax_t maxit = 20;\n   boost::uintmax_t it = maxit;\n   newton_raphson_iterate(elliptic_root_functor_1deriv<T>(arc, radius), guess, min, max, get_digits, it);\n   return it;\n}\n\ntemplate <class T = double>\nstruct elliptic_root_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n   BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n\n   elliptic_root_functor_2deriv(T const& arc, T const& radius) : m_arc(arc), m_radius(radius) {}\n   std::tuple<T, T, T> operator()(T const& x)\n   {\n      // Return the difference between required arc-length, and the calculated arc-length for an\n      // ellipse with radii m_radius and x, plus it's derivative.\n      // See http://www.wolframalpha.com/input/?i=d^2%2Fda^2+[4+*+a+*+EllipticE%281+-+b^2%2Fa^2%29]\n      // for the second derivative.\n      T a = (std::max)(m_radius, x);\n      T b = (std::min)(m_radius, x);\n      T a2 = a * a;\n      T b2 = b * b;\n      T k = sqrt(1 - b2 / a2);\n      T Ek = boost::math::ellint_2(k);\n      T Kk = boost::math::ellint_1(k);\n      T fx = 4 * a * Ek - m_arc;\n      T dfx = 4 * (a2 * Ek - b2 * Kk) / (a2 - b2);\n      T dfx2 = 4 * b2 * ((a2 + b2) * Kk - 2 * a2 * Ek) / (a * (a2 - b2) * (a2 - b2));\n      return std::make_tuple(fx, dfx, dfx2);\n   }\nprivate:\n   T m_arc;     // length of arc.\n   T m_radius;  // one of the two radii of the ellipse\n};\n\ntemplate <class T = double>\nboost::uintmax_t elliptic_root_2deriv(T radius, T arc, T guess)\n{\n   using namespace std;                // Help ADL of std functions.\n   using namespace boost::math::tools; // For halley_iterate.\n\n   BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n\n   T min = 0;                                   // Minimum possible value is zero.\n   T max = arc;                                 // radius can't be larger than the arc length.\n\n   // Accuracy triples at each step, so stop when just over one-third of the digits\n   // are correct, and the last iteration will polish off the remaining digits:\n   int get_digits = static_cast<int>(std::numeric_limits<T>::digits * 0.4);\n   const boost::uintmax_t maxit = 20;\n   boost::uintmax_t it = maxit;\n   halley_iterate(elliptic_root_functor_2deriv<T>(arc, radius), guess, min, max, get_digits, it);\n   return it;\n} // nth_2deriv Halley\n//]\n// Using 1st and 2nd derivatives using Schroder algorithm.\n\ntemplate <class T = double>\nboost::uintmax_t elliptic_root_2deriv_s(T radius, T arc, T guess)\n{ // return nth root of x using 1st and 2nd derivatives and Schroder.\n\n   using namespace std;  // Help ADL of std functions.\n   using namespace boost::math::tools; // For schroder_iterate.\n\n   BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n\n   T min = 0; // Minimum possible value is zero.\n   T max = arc; // radius can't be larger than the arc length.\n\n   int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n   int get_digits = static_cast<int>(digits * 0.4);\n   const boost::uintmax_t maxit = 20;\n   boost::uintmax_t it = maxit;\n   schroder_iterate(elliptic_root_functor_2deriv<T>(arc, radius), guess, min, max, get_digits, it);\n   return it;\n} // T elliptic_root_2deriv_s Schroder\n\n\nint main()\n{\n   try\n   {\n      double to_root = 500;\n      double answer = 7.93700525984;\n\n      std::cout << \"[table\\n\"\n         << \"[[Initial Guess=][-500% ([approx]1.323)][-100% ([approx]3.97)][-50% ([approx]3.96)][-20% ([approx]6.35)][-10% ([approx]7.14)][-5% ([approx]7.54)]\"\n         \"[5% ([approx]8.33)][10% ([approx]8.73)][20% ([approx]9.52)][50% ([approx]11.91)][100% ([approx]15.87)][500 ([approx]47.6)]]\\n\";\n      std::cout << \"[[bracket_and_solve_root][\"\n         << cbrt_noderiv(to_root, answer / 6)\n         << \"][\" << cbrt_noderiv(to_root, answer / 2)\n         << \"][\" << cbrt_noderiv(to_root, answer - answer * 0.5)\n         << \"][\" << cbrt_noderiv(to_root, answer - answer * 0.2)\n         << \"][\" << cbrt_noderiv(to_root, answer - answer * 0.1)\n         << \"][\" << cbrt_noderiv(to_root, answer - answer * 0.05)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer * 0.05)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer * 0.1)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer * 0.2)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer * 0.5)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer)\n         << \"][\" << cbrt_noderiv(to_root, answer + answer * 5) << \"]]\\n\";\n\n      std::cout << \"[[newton_iterate][\"\n         << cbrt_deriv(to_root, answer / 6)\n         << \"][\" << cbrt_deriv(to_root, answer / 2)\n         << \"][\" << cbrt_deriv(to_root, answer - answer * 0.5)\n         << \"][\" << cbrt_deriv(to_root, answer - answer * 0.2)\n         << \"][\" << cbrt_deriv(to_root, answer - answer * 0.1)\n         << \"][\" << cbrt_deriv(to_root, answer - answer * 0.05)\n         << \"][\" << cbrt_deriv(to_root, answer + answer * 0.05)\n         << \"][\" << cbrt_deriv(to_root, answer + answer * 0.1)\n         << \"][\" << cbrt_deriv(to_root, answer + answer * 0.2)\n         << \"][\" << cbrt_deriv(to_root, answer + answer * 0.5)\n         << \"][\" << cbrt_deriv(to_root, answer + answer)\n         << \"][\" << cbrt_deriv(to_root, answer + answer * 5) << \"]]\\n\";\n\n      std::cout << \"[[halley_iterate][\"\n         << cbrt_2deriv(to_root, answer / 6)\n         << \"][\" << cbrt_2deriv(to_root, answer / 2)\n         << \"][\" << cbrt_2deriv(to_root, answer - answer * 0.5)\n         << \"][\" << cbrt_2deriv(to_root, answer - answer * 0.2)\n         << \"][\" << cbrt_2deriv(to_root, answer - answer * 0.1)\n         << \"][\" << cbrt_2deriv(to_root, answer - answer * 0.05)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer * 0.05)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer * 0.1)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer * 0.2)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer * 0.5)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer)\n         << \"][\" << cbrt_2deriv(to_root, answer + answer * 5) << \"]]\\n\";\n\n      std::cout << \"[[schr'''&#xf6;'''der_iterate][\"\n         << cbrt_2deriv_s(to_root, answer / 6)\n         << \"][\" << cbrt_2deriv_s(to_root, answer / 2)\n         << \"][\" << cbrt_2deriv_s(to_root, answer - answer * 0.5)\n         << \"][\" << cbrt_2deriv_s(to_root, answer - answer * 0.2)\n         << \"][\" << cbrt_2deriv_s(to_root, answer - answer * 0.1)\n         << \"][\" << cbrt_2deriv_s(to_root, answer - answer * 0.05)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer * 0.05)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer * 0.1)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer * 0.2)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer * 0.5)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer)\n         << \"][\" << cbrt_2deriv_s(to_root, answer + answer * 5) << \"]]\\n]\\n\\n\";\n\n\n      double radius_a = 10;\n      double arc_length = 500;\n      double radius_b = 123.6216507967705;\n\n      std::cout << std::setprecision(4) << \"[table\\n\"\n         << \"[[Initial Guess=][-500% ([approx]\" << radius_b / 6 << \")][-100% ([approx]\" << radius_b / 2 << \")][-50% ([approx]\"\n         << radius_b - radius_b * 0.5 << \")][-20% ([approx]\" << radius_b - radius_b * 0.2 << \")][-10% ([approx]\" << radius_b - radius_b * 0.1 << \")][-5% ([approx]\" << radius_b - radius_b * 0.05 << \")]\"\n         \"[5% ([approx]\" << radius_b + radius_b * 0.05 << \")][10% ([approx]\" << radius_b + radius_b * 0.1 << \")][20% ([approx]\" << radius_b + radius_b * 0.2 << \")][50% ([approx]\" << radius_b + radius_b * 0.5 \n         << \")][100% ([approx]\" << radius_b + radius_b << \")][500 ([approx]\" << radius_b + radius_b * 5 << \")]]\\n\";\n      std::cout << \"[[bracket_and_solve_root][\"\n         << elliptic_root_noderiv(radius_a, arc_length, radius_b / 6)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b / 2)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b - radius_b * 0.5)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b - radius_b * 0.2)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b - radius_b * 0.1)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b - radius_b * 0.05)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b * 0.05)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b * 0.1)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b * 0.2)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b * 0.5)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b)\n         << \"][\" << elliptic_root_noderiv(radius_a, arc_length, radius_b + radius_b * 5) << \"]]\\n\";\n\n      std::cout << \"[[newton_iterate][\"\n         << elliptic_root_1deriv(radius_a, arc_length, radius_b / 6)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b / 2)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b - radius_b * 0.5)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b - radius_b * 0.2)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b - radius_b * 0.1)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b - radius_b * 0.05)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b * 0.05)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b * 0.1)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b * 0.2)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b * 0.5)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b)\n         << \"][\" << elliptic_root_1deriv(radius_a, arc_length, radius_b + radius_b * 5) << \"]]\\n\";\n\n      std::cout << \"[[halley_iterate][\"\n         << elliptic_root_2deriv(radius_a, arc_length, radius_b / 6)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b / 2)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b - radius_b * 0.5)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b - radius_b * 0.2)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b - radius_b * 0.1)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b - radius_b * 0.05)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b * 0.05)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b * 0.1)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b * 0.2)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b * 0.5)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b)\n         << \"][\" << elliptic_root_2deriv(radius_a, arc_length, radius_b + radius_b * 5) << \"]]\\n\";\n\n      std::cout << \"[[schr'''&#xf6;'''der_iterate][\"\n         << elliptic_root_2deriv_s(radius_a, arc_length, radius_b / 6)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b / 2)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b - radius_b * 0.5)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b - radius_b * 0.2)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b - radius_b * 0.1)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b - radius_b * 0.05)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b * 0.05)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b * 0.1)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b * 0.2)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b * 0.5)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b)\n         << \"][\" << elliptic_root_2deriv_s(radius_a, arc_length, radius_b + radius_b * 5) << \"]]\\n]\\n\\n\";\n\n      return boost::exit_success;\n   }\n   catch(std::exception ex)\n   {\n      std::cout << \"exception thrown: \" << ex.what() << std::endl;\n      return boost::exit_failure;\n   }\n} // int main()\n\n", "meta": {"hexsha": "ba1e437af6efeccf27038d665a45118ad6578b68", "size": 22723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/root_finding_start_locations.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/root_finding_start_locations.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": "Libs/boost_1_76_0/libs/math/example/root_finding_start_locations.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 50.4955555556, "max_line_length": 208, "alphanum_fraction": 0.6169959952, "num_tokens": 6785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5730319326628828}}
{"text": "#ifndef _SPHERE_MESH_GEN_H_\n#define _SPHERE_MESH_GEN_H_\n#include <array>\n#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"compat.h\"\ntemplate <typename Scalar>\nclass SphereMeshFactory{\n    typedef mtao::compat::array<int, 3> Face;\n    typedef mtao::compat::array<int, 2> Edge;\n    public:\n    typedef Scalar Scalar;\n    typedef typename Eigen::Matrix<Scalar,3,1> Vector;\n    using VecVector = mtao::vector<Vector>;\n    SphereMeshFactory(int depth=3);\n    void triforce(const Face & f, int depth);\n    int add_edge(Edge e);\n    void write(const std::string & filename);\n    void write(std::ostream & outstream);\n    const std::vector<Face> faces() const {return m_faces;}\n    const VecVector vertices() const {return m_vertices;}\n\n    private:\n    const int m_depth = 0;\n    VecVector m_vertices;\n    std::vector<Face> m_faces;\n    std::map<Edge,  int> m_edges;\n\n};\n\n\n\ntemplate <typename T>\nSphereMeshFactory<T>::SphereMeshFactory(int depth): m_depth(depth) {\n    //Create icosahedron base\n\n    Scalar gr = .5 * (1 + std::sqrt(Scalar(5)));\n    m_vertices.resize(12);\n\n    m_vertices[ 0] = Vector(     0,    - 1,     gr);\n    m_vertices[ 1] = Vector(    gr,      0,      1);\n    m_vertices[ 2] = Vector(    gr,      0,    - 1);\n    m_vertices[ 3] = Vector(   -gr,      0,    - 1);\n    m_vertices[ 4] = Vector(   -gr,      0,      1);\n    m_vertices[ 5] = Vector(   - 1,     gr,      0);\n    m_vertices[ 6] = Vector(     1,     gr,      0);\n    m_vertices[ 7] = Vector(     1,    -gr,      0);\n    m_vertices[ 8] = Vector(   - 1,    -gr,      0);\n    m_vertices[ 9] = Vector(     0,    - 1,    -gr);\n    m_vertices[10] = Vector(     0,      1,    -gr);\n    m_vertices[11] = Vector(     0,      1,     gr);\n    for(auto&& v: m_vertices) {\n        v.normalize();\n    }\n\n    triforce({{ 1 ,  2 ,  6}},depth); \n    triforce({{ 1 ,  7 ,  2}},depth); \n    triforce({{ 3 ,  4 ,  5}},depth); \n    triforce({{ 4 ,  3 ,  8}},depth); \n    triforce({{ 6 ,  5 , 11}},depth); \n    triforce({{ 5 ,  6 , 10}},depth); \n    triforce({{ 9 , 10 ,  2}},depth); \n    triforce({{10 ,  9 ,  3}},depth); \n    triforce({{ 7 ,  8 ,  9}},depth); \n    triforce({{ 8 ,  7 ,  0}},depth); \n    triforce({{11 ,  0 ,  1}},depth); \n    triforce({{ 0 , 11 ,  4}},depth); \n    triforce({{ 6 ,  2 , 10}},depth); \n    triforce({{ 1 ,  6 , 11}},depth); \n    triforce({{ 3 ,  5 , 10}},depth); \n    triforce({{ 5 ,  4 , 11}},depth); \n    triforce({{ 2 ,  7 ,  9}},depth); \n    triforce({{ 7 ,  1 ,  0}},depth); \n    triforce({{ 3 ,  9 ,  8}},depth); \n    triforce({{ 4 ,  8 ,  0}},depth); \n\n\n\n}\ntemplate <typename T>\nvoid SphereMeshFactory<T>::triforce(const Face & f, int depth) {\n    if(depth <= 0) {\n        m_faces.push_back(f);\n    } else {\n        int e01 = add_edge({{f[0],f[1]}});\n        int e12 = add_edge({{f[1],f[2]}});\n        int e02 = add_edge({{f[0],f[2]}});\n        triforce({{f[0],e01,e02}},depth-1);\n        triforce({{f[1],e12,e01}},depth-1);\n        triforce({{f[2],e02,e12}},depth-1);\n        triforce({{e01 ,e12,e02}},depth-1);\n    }\n\n}\n\ntemplate <typename T>\nint SphereMeshFactory<T>::add_edge(Edge e) {\n    if(e[0] > e[1]) {\n        int tmp = e[0];\n        e[0] = e[1];\n        e[1] = tmp;\n    }\n    auto it = m_edges.find(e);\n    if(it != m_edges.end()) {\n        return it->second;\n    } else {\n        m_edges[e] = m_vertices.size();\n        m_vertices.push_back(\n                (m_vertices[e[0]] + m_vertices[e[1]]).normalized()\n                );\n        return m_vertices.size()-1;\n    }\n\n\n}\n\n\ntemplate <typename T>\nvoid SphereMeshFactory<T>::write(const std::string & filename) {\n    std::ofstream outstream(filename.c_str());\n    write(outstream);\n}\n\ntemplate <typename T>\nvoid SphereMeshFactory<T>::write(std::ostream & outstream) {\n    outstream << \"#Icosahedral subdivision to depth \" << m_depth << std::endl;\n    for(auto&& v: m_vertices) {\n        outstream << \"v \" << v.transpose() << std::endl;\n    }\n\n    for(auto&& f: m_faces) {\n        outstream << \"f \" << f[0]+1 << \" \" << f[1]+1 << \" \" << f[2]+1 << std::endl;\n    }\n}\n#endif\n", "meta": {"hexsha": "c7d7aefe0a7c7cb6997d58a96e2b0834ca5c4734", "size": 4079, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/constructors/sphere.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/mesh/constructors/sphere.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/constructors/sphere.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.345323741, "max_line_length": 83, "alphanum_fraction": 0.5300318706, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.5730319304202406}}
{"text": "/*-----------------------------------------------------------------------------+\r\nInterval Container Library\r\nAuthor: Joachim Faulhaber\r\nCopyright (c) 2007-2010: Joachim Faulhaber\r\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\r\n+------------------------------------------------------------------------------+\r\n   Distributed under the Boost Software License, Version 1.0.\r\n      (See accompanying file LICENCE.txt or copy at\r\n           http://www.boost.org/LICENSE_1_0.txt)\r\n+-----------------------------------------------------------------------------*/\r\n/** Example interval.cpp \\file interval.cpp\r\n    \\brief Intervals for integral and continuous instance types. \r\n           Closed and open interval borders.\r\n\r\n    Much of the library code deals with intervals which are implemented\r\n    by interval class templates. This program gives a very short samlpe of \r\n    different interval instances.\r\n\r\n    \\include interval_/interval.cpp\r\n*/\r\n//[example_interval\r\n#include <iostream>\r\n#include <string>\r\n#include <math.h>\r\n\r\n// Dynamically bounded intervals\r\n#include <boost/icl/discrete_interval.hpp>\r\n#include <boost/icl/continuous_interval.hpp>\r\n\r\n// Statically bounded intervals\r\n#include <boost/icl/right_open_interval.hpp>\r\n#include <boost/icl/left_open_interval.hpp>\r\n#include <boost/icl/closed_interval.hpp>\r\n#include <boost/icl/open_interval.hpp>\r\n\r\n#include \"../toytime.hpp\"\r\n#include <boost/icl/rational.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\nusing namespace boost::icl;\r\n\r\nint main()\r\n{\r\n    cout << \">>Interval Container Library: Sample interval.cpp <<\\n\";\r\n    cout << \"----------------------------------------------------\\n\";\r\n\r\n    // Class template discrete_interval can be used for discrete data types\r\n    // like integers, date and time and other types that have a least steppable\r\n    // unit.\r\n    discrete_interval<int>      int_interval  \r\n        = construct<discrete_interval<int> >(3, 7, interval_bounds::closed());\r\n\r\n    // Class template continuous_interval can be used for continuous data types\r\n    // like double, boost::rational or strings.\r\n    continuous_interval<double> sqrt_interval \r\n        = construct<continuous_interval<double> >(1/sqrt(2.0), sqrt(2.0));\r\n                                                 //interval_bounds::right_open() is default\r\n    continuous_interval<string> city_interval \r\n        = construct<continuous_interval<string> >(\"Barcelona\", \"Boston\", interval_bounds::left_open());\r\n\r\n    discrete_interval<Time>     time_interval \r\n        = construct<discrete_interval<Time> >(Time(monday,8,30), Time(monday,17,20), \r\n                                              interval_bounds::open());\r\n\r\n    cout << \"Dynamically bounded intervals:\\n\";\r\n    cout << \"  discrete_interval<int>:    \" << int_interval  << endl;\r\n    cout << \"continuous_interval<double>: \" << sqrt_interval << \" does \" \r\n                                            << string(contains(sqrt_interval, sqrt(2.0))?\"\":\"NOT\") \r\n                                            << \" contain sqrt(2)\" << endl;\r\n    cout << \"continuous_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval,\"Barcelona\")?\"\":\"NOT\") \r\n                                            << \" contain 'Barcelona'\" << endl;\r\n    cout << \"continuous_interval<string>: \" << city_interval << \" does \"  \r\n                                            << string(contains(city_interval, \"Berlin\")?\"\":\"NOT\") \r\n                                            << \" contain 'Berlin'\" << endl;\r\n    cout << \"  discrete_interval<Time>:   \" << time_interval << \"\\n\\n\";\r\n\r\n    // There are statically bounded interval types with fixed interval borders\r\n    right_open_interval<string>   fix_interval1; // You will probably use one kind of static intervals\r\n                                                 // right_open_intervals are recommended.\r\n    closed_interval<unsigned int> fix_interval2; // ... static closed, left_open and open intervals\r\n    left_open_interval<float>     fix_interval3; // are implemented for sake of completeness but\r\n    open_interval<short>          fix_interval4; // are of minor practical importance.\r\n\r\n    right_open_interval<rational<int> > range1(rational<int>(0,1),  rational<int>(2,3));\r\n    right_open_interval<rational<int> > range2(rational<int>(1,3),  rational<int>(1,1));\r\n\r\n    // This middle third of the unit interval [0,1)\r\n    cout << \"Statically bounded interval:\\n\";\r\n    cout << \"right_open_interval<rational<int>>: \" << (range1 & range2) << endl;\r\n\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n\r\n//>>Interval Container Library: Sample interval.cpp <<\r\n//----------------------------------------------------\r\n//Dynamically bounded intervals\r\n//  discrete_interval<int>:    [3,7]\r\n//continuous_interval<double>: [0.707107,1.41421) does NOT contain sqrt(2)\r\n//continuous_interval<string>: (Barcelona,Boston] does NOT contain 'Barcelona'\r\n//continuous_interval<string>: (Barcelona,Boston] does  contain 'Berlin'\r\n//  discrete_interval<Time>:   (mon:08:30,mon:17:20)\r\n//\r\n//Statically bounded interval\r\n//right_open_interval<rational<int>>: [1/3,2/3)\r\n\r\n//]\r\n\r\n", "meta": {"hexsha": "db8f11a6bb88138600f4dc1b5e106d4feafd3446", "size": 5190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/interval_/interval.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/icl/example/interval_/interval.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/icl/example/interval_/interval.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 46.3392857143, "max_line_length": 104, "alphanum_fraction": 0.5907514451, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5730319279643049}}
{"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_MEAN_AND_VARIANCE\n#define METRO_MEAN_AND_VARIANCE\n\n#include <limits>\n#include <Eigen/Dense>\n\nnamespace metro {\n\t// Compute mean and variance for a vector.\n\t// All values must be non-missing (i.e. not NaN.)\n\ttemplate< typename Data >\n\tstd::pair< double, double > compute_mean_and_variance( Data const& data ) {\n\t\tdouble const mean = data.sum() / data.size() ;\n\t\tdouble variance = std::numeric_limits< double >::quiet_NaN() ;\n\t\tif( data.size() > 1 ) {\n\t\t\tvariance = ( data.array() - mean ).square().sum() / ( data.size() - 1  ) ;\n\t\t}\n\t\treturn std::make_pair( mean, variance ) ;\n\t}\n\n\t// Compute mean and variance for a vector ignoring missing values.\n\ttemplate< typename Data >\n\tstd::pair< double, double > compute_mean_and_variance( Data const& data, Data const& nonmissingness ) {\n\t\tassert( data.size() == nonmissingness.size() ) ;\n\t\t// Ensure all non-missing values are zero.\n\t\tdouble const mean = ( data.array() * nonmissingness.array() ).sum() / nonmissingness.sum() ;\n\t\tdouble variance = std::numeric_limits< double >::quiet_NaN() ;\n\t\tif( data.size() > 1 ) {\n\t\t\tvariance = (( data.array() - mean ) * nonmissingness.array() ).square().sum() / ( nonmissingness.sum() - 1 ) ;\n\t\t}\n\t\treturn std::make_pair( mean, variance ) ;\n\t}\n\t\n\t\n\t\n\t// This struct implements an \"on-line\" algorithm for computing the mean and variance.\n\t// see http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm\n\t// This implementation computes mean and per-element variance (but not covariance) of a matrix\n\t// of values.\n\tstruct OnlineElementwiseMeanAndVariance {\n\t\ttypedef Eigen::MatrixXd Storage ;\n\tpublic:\n\t\ttemplate< typename Data, typename Nonmissingness >\n\t\tvoid accumulate( Data const& data, Nonmissingness const& nonmissingness ) {\n\t\t\tassert( data.rows() == nonmissingness.rows() ) ;\n\t\t\tassert( data.cols() == nonmissingness.cols() ) ;\n\t\t\tif( m_mean.rows() == 0 ) {\n\t\t\t\tm_nonmissingness = nonmissingness ;\n\t\t\t\t// resize storage to match data\n\t\t\t\tm_mean.setZero( data.rows(), data.cols() ) ;\n\t\t\t\tm_sum_of_squares_of_differences.setZero( data.rows(), data.cols() ) ;\n\t\t\t} else {\n\t\t\t\tassert( data.rows() == m_mean.rows() ) ;\n\t\t\t\tassert( data.cols() == m_mean.cols() ) ;\n\t\t\t\tassert( nonmissingness.rows() == m_mean.rows() ) ;\n\t\t\t\tassert( nonmissingness.cols() == m_mean.cols() ) ;\n\t\t\t\tm_nonmissingness += nonmissingness ;\n\t\t\t}\n\t\t\tm_delta = data - m_mean ;\n\t\t\t\n\t\t\t//std::cerr << \"m_nonmissingness =\\n\" << m_nonmissingness.block( 0, 0, 10, 4 ) << \"\\n\" ;\n\t\t\t//std::cerr << \"m_delta =\\n\" << m_delta.block( 0, 0, 10, 4 ) << \"\\n\" ;\n\t\t\t//std::cerr << \"m_mean =\\n\" << m_mean.block( 0, 0, 10, 4 ) << \"\\n\" ;\n\t\t\tm_mean.array() += nonmissingness.array() * ( m_delta.array() / ( m_nonmissingness.array() + ( m_nonmissingness.array() == 0 ).cast< double >() )) ;\n\t\t\t//std::cerr << \"m_mean after update =\\n\" << m_mean.block( 0, 0, 10, 4 ) << \"\\n\" ;\n\t\t\tm_sum_of_squares_of_differences.array() += nonmissingness.array() * ( m_delta.array() * ( data - m_mean ).array() ) ;\n\t\t}\n\t\t\n\t\ttemplate< typename Data >\n\t\tvoid accumulate( Data const& data ) {\n\t\t\tStorage const nonmissingness = Storage::Constant( data.rows(), data.cols(), 1 ) ;\n\t\t\tthis->accumulate( data, nonmissingness ) ;\n\t\t}\n\n\t\tStorage get_mean() const ;\n\t\tStorage get_variance() const ;\n\t\tdouble get_count( int row, int column ) const ;\n\t\tdouble get_mean( int row, int column ) const ;\n\t\tdouble get_variance( int row, int column ) const ;\n\t\t\n\tprivate:\n\t\tStorage m_nonmissingness ;\n\t\tStorage m_mean ;\n\t\tStorage m_sum_of_squares_of_differences ;\n\t\tStorage m_delta ;\n\t} ;\n}\n\n#endif\n", "meta": {"hexsha": "3d5b77d31cf0abce2f154b87410073d4242723bb", "size": 3755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/mean_and_variance.hpp", "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/include/metro/mean_and_variance.hpp", "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/include/metro/mean_and_variance.hpp", "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": 39.5263157895, "max_line_length": 150, "alphanum_fraction": 0.6607190413, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5730266049914825}}
{"text": "#include <iostream>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <opencv2/core/core.hpp>\n#include <cmath>\n\nusing namespace std;\nusing namespace Eigen;\n\n\n//顶点，即待优化变量，目标值\nclass CurveFittingVertex: public g2o::BaseVertex<4,Vector4d> \n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    CurveFittingVertex():BaseVertex<4,Vector4d>()\n    {\n\n    }\n    \n    virtual void setToOriginImpl()\n    {\n        _estimate << 0,0,0,0;\n    }\n\n    virtual void oplusImpl(const double *update_) //更新顶点\n    {\n        Eigen::Map<const Vector4d> up(update_);\n        _estimate += up;\n        // cout<<\"eee\" <<_estimate<<endl;\n    }\n\n    bool read(std::istream& is){}\n    bool write(std::ostream& os) const{}\n\n\n};\n\n//边，描述顶点之间的关系\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1,double,CurveFittingVertex>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    CurveFittingEdge():g2o::BaseUnaryEdge<1,double,CurveFittingVertex>(){}\n// 计算误差\n    void computeError()\n    {\n        const CurveFittingVertex *v = static_cast<const CurveFittingVertex *>(_vertices[0]);\n        const Vector4d abcd = v->estimate();\n        double A = abcd[0],B = abcd[1],C = abcd[2],D = abcd[3];\n        _error(0,0) = _measurement - (A*sin(B*_x)+C*cos(D*_x)+pow(_x,2)); // 观测量减去估计量\n        // cout << \"cee \"<<_error << endl;\n\n    }\n// 计算雅可比矩阵\n    void linearizeOplus()\n    {\n        CurveFittingVertex *vi = static_cast<CurveFittingVertex *>(_vertices[0]);\n        Vector4d abcd = vi->estimate();\n        double A = abcd[0],B = abcd[1],C = abcd[2],D = abcd[3];\n        // cout << \" ddd\" << endl;\n        //误差项对待优化变量的Jacobian\n        _jacobianOplusXi(0,0) = -sin(B*_x);\n        _jacobianOplusXi(0,1) = -A*_x*cos(B*_x);\n        _jacobianOplusXi(0,2) = -cos(D*_x);\n        _jacobianOplusXi(0,3) = C*_x*sin(D*_x);\n        \n        \n    }\n\n    bool read(istream &is){}\n    bool write(ostream &os) const {}\n\npublic:\n    double _x;\n};\n\nint main(int argc, char**argv)\n{\n    // double a = 5.0,b = 1.0,c = 10.0,d = 2.0;\n    // int N = 100;\n\n    // double w_sigma = 2.0;\n\n    // cv::RNG rng;\n\n    // double abcd[4] = {0.0,0.0,0.0};\n\n    // vector<double> x_data,y_data;\n\n    // cout << \"generate data\" << endl;\n\n    // for (int i = 0; i < N; i++)\n    // {\n    //     double x = rng.uniform(-10,10);\n    //     double y = a*sin(b*x)+c*cos(d*x)+rng.gaussian(w_sigma);\n    //     x_data.push_back(x);\n    //     y_data.push_back(y);\n\n    //     // cout << x_data[i] << \" ,\" << y_data[i] << endl;\n\n    // }\n\n    // // 每个误差项优化变量维度为 4，误差值维度为1\n    // typedef g2o::BlockSolver<g2o::BlockSolverTraits<4,1>> Block;\n    // // 线性方程求解器： 稠密的增量方程\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n\n    // // 矩阵块求解器\n    // Block* solver_ptr = new Block(std::unique_ptr<Block::LinearSolverType>(linearSolver));\n    \n    // // 梯度下降方法\n    // // g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(std::unique_ptr<Block>(solver_ptr));\n    // g2o::OptimizationAlgorithmDogleg *solver = new g2o::OptimizationAlgorithmDogleg(std::unique_ptr<Block>(solver_ptr));\n    \n    // g2o::SparseOptimizer optimizer;\n    // optimizer.setAlgorithm(solver);\n    // optimizer.setVerbose(true);\n\n    // CurveFittingVertex *v = new CurveFittingVertex();\n    // // 初始值\n    // v->setEstimate(Eigen::Vector4d(1.6,1.4,6.2,1.7));\n    // v->setId(0);\n    // v->setFixed(false);\n    // optimizer.addVertex(v);//添加顶点\n\n    // for(int i=0;i< N;i++)\n    // {\n    //     CurveFittingEdge *edge = new CurveFittingEdge();\n    //     edge->setId(i+1);\n    //     edge->setVertex(0,v);//设置连接的顶点\n    //     edge->setMeasurement(y_data[i]);\n\n    //     //信息矩阵： 协方差矩阵之逆\n    //     edge->setInformation(Eigen::Matrix<double,1,1>::Identity()*1/(w_sigma*w_sigma));\n    //     edge->_x = x_data[i];\n    //     optimizer.addEdge(edge);\n\n    // }\n\n    // cout << \"start optimization\" << endl;\n\n    // chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    // optimizer.initializeOptimization();\n    // optimizer.optimize(100);\n\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 << \" time_used: \" << time_used.count() << \" seconds\" << endl;\n\n    // Eigen::Vector4d abcd_estimate = v->estimate();\n    // cout << \"estimated \\n\" << abcd_estimate << endl;\n\n    // return 0;\n\n\n    double a = 5.0, b = 1.0, c = 10.0, d = 2.0; // 真实参数值\n    int N = 100;\n    double w_sigma = 2.0;   // 噪声值Sigma\n    cv::RNG rng;    // 随机数产生器OpenCV\n    double abcd[4] = {0, 0, 0, 0};  // 参数的估计值abc\n\n    vector<double> x_data, y_data;\n\n    cout << \"generate random data\" << endl;\n\n    for(int i = 0; i < N; i++)\n    {\n        //generate a random variable [-10 10]\n        double x = rng.uniform(-10., 10.);\n        double y = a * sin(b*x) + c* cos(d *x)+pow(x,2) + rng.gaussian(w_sigma);\n        // double y = a * sin(b*x) + c * cos(d *x);\n        x_data.push_back(x);\n        y_data.push_back(y);\n\n        // cout << x_data[i] << \" , \" << y_data[i] << endl;\n    }\n\n    // 构建图优化，先设定g2o\n    // 矩阵块：每个误差项优化变量维度为4 ，误差值维度为1\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<4, 1> > Block;\n    // 线性方程求解器：稠密的增量方程\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n\n    typedef g2o::LinearSolverDense<Block::PoseMatrixType> MyLinearSolver;\n    // Block* solver_ptr = new Block(linearSolver);    // 矩阵块求解器\n\n    // // 梯度下降方法，从GN, LM, DogLeg 中选\n    // g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( solver_ptr );\n    // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n    // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n    // 矩阵块求解器\n    // Block* solver_ptr = new Block(std::make_unique<Block::LinearSolverType>(linearSolver));\n    // g2o::OptimizationAlgorithmDogleg *solver = new g2o::OptimizationAlgorithmDogleg(std::unique_ptr<Block>(solver_ptr));\n    g2o::SparseOptimizer optimizer;     // 图模型\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(g2o::make_unique<Block>(g2o::make_unique<MyLinearSolver>()));\n    // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg(g2o::make_unique<Block>(g2o::make_unique<MyLinearSolver>()));\n    \n    optimizer.setAlgorithm( solver );   // 设置求解器\n    optimizer.setVerbose(true);     // 打开调试输出\n\n    // 往图中增加顶点\n    CurveFittingVertex *v = new CurveFittingVertex();\n    // 设置优化初始估计值\n    v->setEstimate( Eigen::Vector4d(1.6, 1.4, 6.2, 1.7));\n    v->setId(0);\n    // v->setFixed(false);\n    optimizer.addVertex(v);\n\n    // 往图中增加边\n    for(int i = 0; i < N; i++)\n    {\n        CurveFittingEdge* edge = new CurveFittingEdge();\n        edge->setId(i+1);\n        edge->setVertex(0, v);      // 设置连接的顶点\n        edge->setMeasurement( y_data[i] );      // 观测数值\n\n        // 信息矩阵：协方差矩阵之逆\n        edge->setInformation( Eigen::Matrix<double, 1, 1>::Identity() );\n\n        edge->_x = x_data[i];\n\n        optimizer.addEdge( edge );\n    }\n\n    // 执行优化\n    cout << \"strat optimization\" << endl;\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\n    optimizer.initializeOptimization();\n    optimizer.optimize(500);\n\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 << \"solve time cost = \" << time_used.count() << \" seconds.\" << endl;\n\n    // 输出优化值\n    Eigen::Vector4d abcd_estimate = v->estimate();\n    cout << \"estimated module: \" <<  endl << abcd_estimate << endl;\n\n    return 0;\n    \n\n}\n\n\n", "meta": {"hexsha": "af83a4c069393dabe00f8a392e3605ef30f756fe", "size": 8042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/em/em-g2o.cpp", "max_stars_repo_name": "1667/PythonRobotics", "max_stars_repo_head_hexsha": "f0b02ba4401a0399db6cc33c5e4b25b8b7613a65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "g2o/em/em-g2o.cpp", "max_issues_repo_name": "1667/PythonRobotics", "max_issues_repo_head_hexsha": "f0b02ba4401a0399db6cc33c5e4b25b8b7613a65", "max_issues_repo_licenses": ["MIT"], "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/em/em-g2o.cpp", "max_forks_repo_name": "1667/PythonRobotics", "max_forks_repo_head_hexsha": "f0b02ba4401a0399db6cc33c5e4b25b8b7613a65", "max_forks_repo_licenses": ["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.8122605364, "max_line_length": 151, "alphanum_fraction": 0.617135041, "num_tokens": 2688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.847967769904032, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5730265906319343}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <boost/geometry.hpp>\n#include <cmath>\n#include <tuple>\n\nnamespace pyinterp::detail::math {\n\n/// Abstract class for bivariate interpolation\ntemplate <template <class> class Point, typename T>\nstruct Bivariate {\n  /// Default constructor\n  Bivariate() = default;\n\n  /// Default destructor\n  virtual ~Bivariate() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Bivariate(const Bivariate& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Bivariate(Bivariate&& rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Bivariate& rhs) -> Bivariate& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Bivariate&& rhs) noexcept -> Bivariate& = default;\n\n  /// Performs the interpolation\n  ///\n  /// @param p Query point\n  /// @param p0 Point of coordinate (x0, y0)\n  /// @param p1 Point of coordinate (x1, y1)\n  /// @param q00 Point value for the coordinate (x0, y0)\n  /// @param q01 Point value for the coordinate (x0, y1)\n  /// @param q10 Point value for the coordinate (x1, y0)\n  /// @param q11 Point value for the coordinate (x1, y1)\n  /// @return interpolated value at coordinate (x, y)\n  virtual auto evaluate(const Point<T>& p, const Point<T>& p0,\n                        const Point<T>& p1, const T& q00, const T& q01,\n                        const T& q10, const T& q11) const -> T = 0;\n};\n\n/// Bilinear interpolation\ntemplate <template <class> class Point, typename T>\nstruct Bilinear : public Bivariate<Point, T> {\n  /// Default constructor\n  Bilinear() = default;\n\n  /// Default destructor\n  virtual ~Bilinear() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Bilinear(const Bilinear& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Bilinear(Bilinear&& rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Bilinear& rhs) -> Bilinear& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Bilinear&& rhs) noexcept -> Bilinear& = default;\n\n  /// Performs the bilinear interpolation\n  constexpr auto evaluate(const Point<T>& p, const Point<T>& p0,\n                          const Point<T>& p1, const T& q00, const T& q01,\n                          const T& q10, const T& q11) const -> T final {\n    auto dx = boost::geometry::get<0>(p1) - boost::geometry::get<0>(p0);\n    auto dy = boost::geometry::get<1>(p1) - boost::geometry::get<1>(p0);\n    auto t = (boost::geometry::get<0>(p) - boost::geometry::get<0>(p0)) / dx;\n    auto u = (boost::geometry::get<1>(p) - boost::geometry::get<1>(p0)) / dy;\n    return (T(1) - t) * (T(1) - u) * q00 + t * (T(1) - u) * q10 +\n           (T(1) - t) * u * q01 + t * u * q11;\n  }\n};\n\n/// Inverse distance weighting interpolation\n///\n/// @see https://en.wikipedia.org/wiki/Inverse_distance_weighting\n///\ntemplate <template <class> class Point, typename T>\nstruct InverseDistanceWeighting : public Bivariate<Point, T> {\n  /// Default constructor (p=2)\n  InverseDistanceWeighting() = default;\n\n  /// Explicit definition of the parameter p.\n  explicit InverseDistanceWeighting(const int exp) : exp_(exp) {}\n\n  /// Return the exponent used by this instance\n  [[nodiscard]] inline auto exp() const noexcept -> int { return exp_; }\n\n  /// Default destructor\n  virtual ~InverseDistanceWeighting() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  InverseDistanceWeighting(const InverseDistanceWeighting& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  InverseDistanceWeighting(InverseDistanceWeighting&& rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const InverseDistanceWeighting& rhs)\n      -> InverseDistanceWeighting& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(InverseDistanceWeighting&& rhs) noexcept\n      -> InverseDistanceWeighting& = default;\n\n  /// Performs the interpolation\n  inline auto evaluate(const Point<T>& p, const Point<T>& p0,\n                       const Point<T>& p1, const T& q00, const T& q01,\n                       const T& q10, const T& q11) const -> T final {\n    auto distance = boost::geometry::distance(\n        p, Point<T>{boost::geometry::get<0>(p0), boost::geometry::get<1>(p0)});\n    if (distance <= std::numeric_limits<T>::epsilon()) {\n      return q00;\n    }\n\n    auto w = 1 / std::pow(distance, exp_);\n    auto wu = q00 * w;\n\n    distance = boost::geometry::distance(\n        p, Point<T>{boost::geometry::get<0>(p0), boost::geometry::get<1>(p1)});\n\n    if (distance <= std::numeric_limits<T>::epsilon()) {\n      return q01;\n    }\n\n    auto wi = 1 / std::pow(distance, exp_);\n    w += wi;\n    wu += q01 * wi;\n\n    distance = boost::geometry::distance(\n        p, Point<T>{boost::geometry::get<0>(p1), boost::geometry::get<1>(p0)});\n\n    if (distance <= std::numeric_limits<T>::epsilon()) {\n      return q10;\n    }\n\n    wi = 1 / std::pow(distance, exp_);\n    w += wi;\n    wu += q10 * wi;\n\n    distance = boost::geometry::distance(\n        p, Point<T>{boost::geometry::get<0>(p1), boost::geometry::get<1>(p1)});\n\n    if (distance <= std::numeric_limits<T>::epsilon()) {\n      return q11;\n    }\n\n    wi = 1 / std::pow(distance, exp_);\n    w += wi;\n    wu += q11 * wi;\n\n    return wu / w;\n  }\n\n private:\n  int exp_{2};\n};\n\n/// Nearest interpolation\ntemplate <template <class> class Point, typename T>\nstruct Nearest : public Bivariate<Point, T> {\n  /// Default constructor\n  Nearest() = default;\n\n  /// Default destructor\n  virtual ~Nearest() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Nearest(const Nearest& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Nearest(Nearest&& rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Nearest& rhs) -> Nearest& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Nearest&& rhs) noexcept -> Nearest& = default;\n\n  /// Performs the interpolation\n  inline auto evaluate(const Point<T>& p, const Point<T>& p0,\n                       const Point<T>& p1, const T& q00, const T& q01,\n                       const T& q10, const T& q11) const -> T final {\n    auto distance = boost::geometry::comparable_distance(\n        p, Point<T>{boost::geometry::get<0>(p0), boost::geometry::get<1>(p0)});\n    auto result = std::make_tuple(distance, q00);\n\n    distance = boost::geometry::comparable_distance(\n        p, Point<T>{boost::geometry::get<0>(p0), boost::geometry::get<1>(p1)});\n    if (std::get<0>(result) > distance) {\n      result = std::make_tuple(distance, q01);\n    }\n\n    distance = boost::geometry::comparable_distance(\n        p, Point<T>{boost::geometry::get<0>(p1), boost::geometry::get<1>(p0)});\n    if (std::get<0>(result) > distance) {\n      result = std::make_tuple(distance, q10);\n    }\n\n    distance = boost::geometry::comparable_distance(\n        p, Point<T>{boost::geometry::get<0>(p1), boost::geometry::get<1>(p1)});\n    if (std::get<0>(result) > distance) {\n      result = std::make_tuple(distance, q11);\n    }\n    return std::get<1>(result);\n  }\n};\n\n}  // namespace pyinterp::detail::math\n", "meta": {"hexsha": "b47613c97077ae35b3076aefe4aae52f5a118ec4", "size": 7520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/bivariate.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/bivariate.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/bivariate.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.08, "max_line_length": 79, "alphanum_fraction": 0.6218085106, "num_tokens": 2065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.573026577650264}}
{"text": "#include \"socpInterface.hpp\"\n\n#include <array>\n#include <iostream>\n#include <chrono>\n\n#include <Eigen/Dense>\n\n// This example solves a simple random second order cone problem\n// based on https://www.cvxpy.org/examples/basic/socp.html\n\nint main()\n{\n    // Set up problem data.\n\n    // number of second order cone constraints\n    const size_t m = 3;\n    // number of variables\n    const size_t n = 10;\n    // dimension of equality constraints\n    const size_t p = 5;\n    // dimension of second order cone constraints\n    const size_t n_i = 5;\n\n    std::array<Eigen::Matrix<double, n_i, n>, m> A;\n    std::array<Eigen::Matrix<double, n_i, 1>, m> b;\n    std::array<Eigen::Matrix<double, n, 1>, m> c;\n    std::array<double, m> d;\n\n    Eigen::Matrix<double, n, 1> x0;\n    x0.setRandom();\n    Eigen::Matrix<double, n, 1> f;\n    f.setRandom();\n\n    for (size_t i = 0; i < m; i++)\n    {\n        A[i].setRandom();\n        b[i].setRandom();\n        c[i].setRandom();\n        d[i] = (A[i] * x0).norm() - c[i].dot(x0);\n    }\n\n    Eigen::Matrix<double, p, n> F;\n    F.setRandom();\n    Eigen::Matrix<double, p, 1> g = F * x0;\n\n    // Formulate SOCP.\n    auto t0 = std::chrono::high_resolution_clock::now();\n\n    // Create the SOCP instance.\n    op::SecondOrderConeProgram socp;\n\n    // Add variables. Those can be scalars, vectors or matrices.\n    op::Variable x = socp.createVariable(\"x\", n);\n\n    // Add constraints.\n    for (size_t i = 0; i < m; i++)\n    {\n        socp.addConstraint(op::norm2(op::Parameter(A[i]) * x + op::Parameter(b[i])) <=\n                           op::Parameter(c[i]).transpose() * x + op::Parameter(d[i]));\n    }\n    socp.addConstraint(op::Parameter(F) * x == op::Parameter(g));\n\n    // Here we use a pointer to a parameter. This allows changing it dynamically.\n    socp.addMinimizationTerm(op::Parameter(&f).transpose() * x);\n\n    // Print the problem for inspection.\n    std::cout << socp << \"\\n\\n\";\n\n    // Create the solver instance.\n    op::Solver solver(socp);\n    solver.initialize();\n\n    auto t = std::chrono::high_resolution_clock::now();\n    auto t_setup = std::chrono::duration_cast<std::chrono::microseconds>(t - t0).count();\n    std::cout << \"\\nSetup duration: \" << t_setup << \"μs.\\n\\n\";\n\n    // Solve the problem and show solver output.\n    t0 = std::chrono::high_resolution_clock::now();\n    const bool success = solver.solveProblem(true);\n    if (not success)\n    {\n        // This should not happen in this example.\n        throw std::runtime_error(\"Solver returned a critical error.\");\n    }\n    std::cout << \"Solver message: \" << solver.getResultString() << \"\\n\";\n\n    // Check if the solver has produced a valid solution.\n    assert(socp.isFeasible());\n\n    t = std::chrono::high_resolution_clock::now();\n    auto t_solve = std::chrono::duration_cast<std::chrono::microseconds>(t - t0).count();\n    std::cout << \"\\nSolver duration: \" << t_solve << \"μs.\\n\\n\";\n\n    // Get Solution.\n    Eigen::Matrix<double, n, 1> x_sol;\n    socp.readSolution(\"x\", x_sol);\n\n    // Print the first solution.\n    std::cout << \"First solution:\\n\"\n              << x_sol << \"\\n\\n\";\n\n    // Change the problem parameters and solve again.\n    f.setRandom();\n    solver.solveProblem(false);\n    socp.readSolution(\"x\", x_sol);\n\n    // Print the new solution.\n    std::cout << \"Solution after changing the cost function:\\n\"\n              << x_sol << \"\\n\\n\";\n}", "meta": {"hexsha": "ed50a1c3e70dc28d5e9948266c19dcf68114d8d1", "size": 3365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/socp_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/socp_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/socp_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": 30.3153153153, "max_line_length": 89, "alphanum_fraction": 0.603268945, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.5729351142073263}}
{"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 <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ndouble f(double) { cout << \"double\\n\"; return 1.0; } \ncomplex<double> f(complex<double>) { cout << \"complex\\n\"; return complex<double>(1.0, -1.0); }\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    cout << \"\\n\" << name << \"\\n\";\n\n    typedef typename mtl::Collection<Matrix>::size_type   size_type;\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    typedef typename mtl::dense_vector<Scalar>            Vector;\n\n    std::size_t size= num_cols(A);\n    Matrix L(size, size), U(size, size);\n\n    Scalar c= f(Scalar(1));   \n    cout << \"c is: \" << c << \"\\n\";\n\n    for (std::size_t i= 0; i < size; i++)\n\tfor(std::size_t j= 0; j < size; j++) {\n\t    U[i][j]= i <= j ? c * Scalar(i+j+2) : Scalar(0);\n\t    L[i][j]= i > j ? c * Scalar(i+j+1) : (i == j ? Scalar(1) : Scalar(0));\n\t}\n    \n    cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n    A= L * U;\n\n    Vector v(size);\n    for (std::size_t i= 0; i < size; i++)\n\tv[i]= Scalar(i);\n\n    Vector w( A*v );\n\n    cout << \"A is:\\n\" << A;\n\n    Matrix PLU(A);\n\n    mtl::dense_vector<size_type> Pv(size);\n    lu(PLU, Pv);\n    typename mtl::mat::traits::permutation<>::type P(permutation(Pv));\n    \n    cout << \"Permuted A is \\n\" << Matrix(P * A);\n\n    Matrix I(size, size);\n    I= Scalar(1);\n\n    Matrix PL(I + strict_lower(PLU)), PU(upper(PLU)), PA2(PL * PU);\n    cout << \"L [permuted] is:\\n\" << PL << \"U [permuted] is:\\n\" << PU \n\t << \"L * U [permuted] is:\\n\" << PA2\n\t << \"L * U is:\\n\" << Matrix(trans(P) * PA2);\n \n    MTL_THROW_IF(one_norm(Matrix(trans(P) * PA2 - A)) > 0.1, mtl::runtime_error(\"Error in permuted LU factorization.\"));\n\n    Matrix PUI(inv_upper(PU));\n    cout << \"inv(U) [permuted] is:\\n\" << PUI << \"PUI * PU is:\\n\" << Matrix(PUI * PU);\n    MTL_THROW_IF(one_norm(Matrix(PUI * PU - I)) > 0.1, mtl::runtime_error(\"Error in upper inversion.\"));\n\n    Matrix PLI(inv_lower(PL));\n    cout << \"inv(L) [permuted] is:\\n\" << PLI << \"PLI * PL is:\\n\" << Matrix(PLI * PL);\n    MTL_THROW_IF(one_norm(Matrix(PLI * PL - I)) > 0.1, mtl::runtime_error(\"Error in lower inversion.\"));\n\n    Matrix AI(PUI * PLI * P);\n    cout << \"inv(A) [inv(U) * inv(L) * P] is \\n\" << AI << \"A * AI is\\n\" << Matrix(AI * A);\n    MTL_THROW_IF(one_norm(Matrix(AI * A - I)) > 0.1, mtl::runtime_error(\"Error in inversion.\"));\n\n    typename mtl::mat::traits::inv<Matrix>::type A_inv(inv(A));\n    cout << \"inv(A) is \\n\" << A_inv << \"A * AI is\\n\" << Matrix(A_inv * A);\n    MTL_THROW_IF(one_norm(Matrix(A_inv * A - I)) > 0.1, mtl::runtime_error(\"Error in inversion.\"));\n}\n\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    std::size_t size= 4;\n    \n    dense2D<double>                                      dr(size, size);\n    dense2D<complex<double> >                            dz(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    // compressed2D<double>                                 cr(size, size);\n\n    test(dr, \"Row-major dense\");\n    test(dz, \"Row-major dense with complex numbers\");\n    test(dc, \"Column-major dense\");\n\n    return 0;\n}\n", "meta": {"hexsha": "4bdc1ff6727f4de89e0a9ade4a07eb0a67edc428", "size": 3557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/inv_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/inv_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/inv_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.9351851852, "max_line_length": 120, "alphanum_fraction": 0.5687377003, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.572911577007072}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nextern \"C\" void kgain_(float *xENS, float *yEns, float *dy, int *nx, int *ny, int *nEns, float *s,\n\t\t       float *dx)\n{\n  int i, j;\n  mat xENSa(*nx,*nEns),yENSa(*ny,*nEns);\n  vec dya(*ny);\n  //    kGain=dot(covXY,linalg.inv(covYY+R*eye(ny)))\n  //    xRet=xEns.mean()+dot(kGain,dy)\n\t\n  //vec dy=vec(*n),sol;\n  for(i=0;i<*nEns;i++)\n    for(j=0;j<*nx;j++)\n      {\n\txENSa(j,i)=xENS[j*(*nEns)+i];\n      }\n  for(j=0;j<*nx;j++)\n    {\n      float xmean=0;\n      for(i=0;i<*nEns;i++)\n\txmean+=xENSa(j,i);\n      xENSa(j,span(0,*nEns-1))-=(xmean/(*nEns));\n    }\n  for(i=0;i<*nEns;i++)\n    for(j=0;j<*ny;j++)\n      {\n\tyENSa(j,i)=yEns[j*(*nEns)+i];\n      }\n\n  for(j=0;j<*ny;j++)\n    {\n      float ymean=0;\n      for(i=0;i<*nEns;i++)\n\tymean+=yENSa(j,i);\n      yENSa(j,span(0,*nEns-1))-=(ymean/(*nEns));\n    }\n  mat covYY=(yENSa*yENSa.t())/(*nEns-1);\n  mat covXY=(xENSa*yENSa.t())/(*nEns-1);\n  //cout<<covYY;\n  for(j=0;j<*ny;j++)\n    {\n      covYY(j,j)+=*s;\n      dya(j)=dy[j];\n    }\n  vec sol,dxa;\n  sol=solve(covYY,dya);\n  dxa=covXY*sol;\n  for(i=0;i<*nx;i++)\n    dx[i]=dxa(i);\n\n  /*\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",zobs[i]);\n  printf(\"\\n\");\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",z[i]);\n  printf(\"\\n\");\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",sol[i]);\n  printf(\"\\n\");\n  printf(\"****\\n\");\n  */\n}\n\nextern \"C\" void gauss_newton_(float *dzdn, float *z, float *zobs, int *n, float *s,\n                            float *dn)\n{\n  int i, j;\n  mat gradZ(*n,*n),temp;\n  vec dy=vec(*n),sol;\n  for(i=0;i<*n;i++)\n    for(j=0;j<*n;j++)\n    {\n      gradZ(i,j)=dzdn[j*(*n)+i];\n    }\n\n  temp=gradZ.t()*gradZ;\n  for(i=0;i<*n;i++)\n    {\n      temp(i,i)+=*s;\n      if(zobs[i]>10 && z[i]>5)\n\tdy(i)=zobs[i]-z[i];\n      else\n\tdy(i)=0;\n    }\n  vec graddy=gradZ.t()*dy;\n  sol=solve(temp,graddy);\n  for(i=0;i<*n;i++)\n    dn[i]=sol(i);\n\n  /*\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",zobs[i]);\n  printf(\"\\n\");\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",z[i]);\n  printf(\"\\n\");\n  for(i=0;i<*n;i++)\n    printf(\"%6.2f \",sol[i]);\n  printf(\"\\n\");\n  printf(\"****\\n\");\n  */\n}\n\n\nextern \"C\" void interp_arm_(float *x, float *y, int *n,\n                            float *xi, float *yi, int *ni)\n{\n  int i;\n  vec xa=vec(*n);\n  vec ya=vec(*n);\n  vec xia=vec(*ni);\n  vec yia=vec(*ni);\n  for(i=0;i<*n;i++)\n    {\n      xa(i)=x[i];\n      ya(i)=y[i];\n    }\n  for(i=0;i<*ni;i++)\n    xia(i)=xi[i];\n  \n  \n  interp1(xa, ya, xia, yia);\n  for(i=0;i<*ni;i++)\n    {\n      yi[i]=yia(i);\n      printf(\"%i %g \\n\",i,yia(i));\n    }\n}\n\nextern \"C\" void kgainc_(float *dtb, int *n, float *s, float *kgain)\n{\n  mat A(*n,*n);\n  int i,j;\n  for(i=0;i<*n;i++)\n    {\n      for(j=0;j<*n;j++)\n        A(i,j)=dtb[i]*dtb[j];\n      A(i,i)=A(i,i)+(*s);\n    }\n  //A.print(\"A=:\");\n  mat B=pinv(A,0.0001);\n  //B.print(\"B=:\");\n  \n  for(i=0;i<*n;i++)\n    {\n      kgain[i]=0;\n      for(j=0;j<*n;j++)\n        kgain[i]+=dtb[j]*B(j,i);\n    }\n}\n//pinv=linalg.pinv(dot(dtb.T,dtb)+eye(6)*4)\n//  kgain=dot(dtb,pinv)\n\nextern \"C\" void interp_armi_(int *x, float *y, int *n,\n                             int *xi, float *yi, int *ni)\n{\n  int i;\n  vec xa=vec(*n);\n  vec ya=vec(*n);\n  vec xia=vec(*ni);\n  vec yia;\n  for(i=0;i<*n;i++)\n    {\n      xa(i)=x[i];\n      ya(i)=y[i];\n    }\n  for(i=0;i<*ni;i++)\n    {\n      xia(i)=xi[i];\n      //printf(\"%g \\n\",xi[i]);\n    }\n  //  xia.print(\"xi:\");\n  \n  interp1(xa, ya, xia, yia);\n  //printf(\" %i %i \\n\",*n,*ni);\n  for(i=0;i<*ni;i++)\n    {\n      yi[i]=yia(i);\n      //  printf(\"%i %lg %lg \\n\",i,xia(i),yia(i));\n    }\n}\n", "meta": {"hexsha": "a25ef0cc719a1e5bb0ec4a8821b006ffb6fcee44", "size": 3546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src_c/armadillo_funcs.cpp", "max_stars_repo_name": "mgrecu35/cmbv7", "max_stars_repo_head_hexsha": "5fe0f2cc2a98d6fa0ce8b3864b3735b371b07958", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src_c/armadillo_funcs.cpp", "max_issues_repo_name": "mgrecu35/cmbv7", "max_issues_repo_head_hexsha": "5fe0f2cc2a98d6fa0ce8b3864b3735b371b07958", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src_c/armadillo_funcs.cpp", "max_forks_repo_name": "mgrecu35/cmbv7", "max_forks_repo_head_hexsha": "5fe0f2cc2a98d6fa0ce8b3864b3735b371b07958", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8617021277, "max_line_length": 98, "alphanum_fraction": 0.4503666103, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5729115765457381}}
{"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/planar_face_traversal.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n\nusing namespace boost;\n\n\n\n// Some planar face traversal visitors that will \n// print the vertices and edges on the faces\n\nstruct output_visitor : public planar_face_traversal_visitor\n{\n  void begin_face() { std::cout << \"New face: \"; }\n  void end_face() { std::cout << std::endl; }\n};\n\n\n\nstruct vertex_output_visitor : public output_visitor\n{\n  template <typename Vertex> \n  void next_vertex(Vertex v) \n  { \n    std::cout << v << \" \"; \n  }\n};\n\n\n\nstruct edge_output_visitor : public output_visitor\n{\n  template <typename Edge> \n  void next_edge(Edge e) \n  { \n    std::cout << e << \" \"; \n  }\n};\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 graph - this is a biconnected, 3 x 3 grid.\n  // It should have four small (four vertex/four edge) faces and\n  // one large face that contains all but the interior vertex\n  graph g(9);\n\n  add_edge(0,1,g);\n  add_edge(1,2,g);\n\n  add_edge(3,4,g);\n  add_edge(4,5,g);\n  \n  add_edge(6,7,g);\n  add_edge(7,8,g);\n\n\n  add_edge(0,3,g);\n  add_edge(3,6,g);\n\n  add_edge(1,4,g);\n  add_edge(4,7,g);\n\n  add_edge(2,5,g);\n  add_edge(5,8,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 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  \n  std::cout << std::endl << \"Vertices on the faces: \" << std::endl;\n  vertex_output_visitor v_vis;\n  planar_face_traversal(g, &embedding[0], v_vis);\n\n  std::cout << std::endl << \"Edges on the faces: \" << std::endl;\n  edge_output_visitor e_vis;\n  planar_face_traversal(g, &embedding[0], e_vis);\n\n  return 0;  \n}\n", "meta": {"hexsha": "8d4daab464ad851178566cbf013193d7a446f23b", "size": 3118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/planar_face_traversal.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/planar_face_traversal.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/planar_face_traversal.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": 24.944, "max_line_length": 73, "alphanum_fraction": 0.6241180244, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5729115765457381}}
{"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/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/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=1;\n  banded_matrix A(n, n, k, 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      A(j, i)=A(i, j);\n    }\n  }\n  {\n    vector d(n), e(n-1);\n    for (size_type j=0; j<n; ++j) {\n      d(j)=A(j, j);\n      if (j<n-1)\n\te(j)=A(j+1, j);\n    }\n    matrix vr(n ,n);\n    int info=lapack::stev('V', n, d, e, vr);\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(A, v)-d(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": "23250844024064ee45a01967ccb6693b9ae5777c", "size": 1964, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/stev.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/stev.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/stev.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.6774193548, "max_line_length": 74, "alphanum_fraction": 0.650203666, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.572911576545738}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"abeem.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(ABEEM)\n\n\nstd::vector<double> ABEEM::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.atoms().size();\n    size_t m = molecule.bonds().size();\n    size_t mn = n + m + 1;\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(mn, mn);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(mn);\n\n    const double k = parameters_->common()->parameter(common::k);\n\n    // atom-atom part\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = molecule.atoms()[i];\n        A(i, i) = parameters_->atom()->parameter(atom::b)(atom_i);\n        b(i) = -parameters_->atom()->parameter(atom::a)(atom_i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = molecule.atoms()[j];\n            double off = k / distance(atom_i, atom_j);\n            A(i, j) = off;\n            A(j, i) = off;\n        }\n    }\n\n    // atom-bond part\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom = molecule.atoms()[i];\n        for (size_t j = 0; j < m; j++) {\n            const auto &bond = molecule.bonds()[j];\n            if (bond.hasAtom(atom)) {\n                A(i, n + j) = parameters_->atom()->parameter(atom::c)(atom);\n            } else {\n                A(i, n + j) = k / distance(atom, bond, true);\n            }\n        }\n\n    }\n\n    // bond-atom part\n    for (size_t i = 0; i < m; i++) {\n        const auto &bond = molecule.bonds()[i];\n        b(n + i) = -parameters_->bond()->parameter(bond::A)(bond);\n        for (size_t j = 0; j < n; j++) {\n            const auto &atom = molecule.atoms()[j];\n            if (bond.hasAtom(atom)) {\n                if (bond.first() == atom) {\n                    A(n + i, j) = parameters_->bond()->parameter(bond::D)(bond);\n                } else {\n                    A(n + i, j) = parameters_->bond()->parameter(bond::C)(bond);\n                }\n            } else {\n                A(n + i, j) = k / distance(atom, bond, true);\n            }\n        }\n    }\n\n    // bond-bond part\n    for (size_t i = 0; i < m; i++) {\n        const auto &bond_i = molecule.bonds()[i];\n        A(n + i, n + i) = parameters_->bond()->parameter(bond::B)(bond_i);\n        for (size_t j = i + 1; j < m; j++) {\n            const auto &bond_j = molecule.bonds()[j];\n            double off = k / distance(bond_i, bond_j, true);\n            A(n + i, n + j) = off;\n            A(n + j, n + i) = off;\n        }\n    }\n\n    for (size_t i = 0; i < n + m; i++) {\n        A(i, n + m) = 1;\n        A(n + m, i) = 1;\n    }\n\n    A(n + m, n + m) = 0;\n    b(n + m) = molecule.total_charge();\n\n    Eigen::VectorXd q = A.partialPivLu().solve(b).head(mn);\n\n    // Redistribute the bond charges to the corresponding atoms\n    for(size_t i = 0; i < m; i++) {\n        const auto &bond = molecule.bonds()[i];\n        q(bond.first().index())+= 0.5 * q(n + i);\n        q(bond.second().index()) += 0.5 * q(n + i);\n    }\n\n    return std::vector<double>(q.data(), q.data() + n);\n}\n", "meta": {"hexsha": "b106d69ae972fc3e524681548cce39a6bf5a00f7", "size": 3092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/abeem.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/abeem.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/abeem.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": 30.0194174757, "max_line_length": 80, "alphanum_fraction": 0.4760672704, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5728416105959919}}
{"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/PolygonRasterize.h\"\n#include \"SDOT/RegularGrid.h\"\n#include \"SDOT/DiscretizedDistribution.h\"\n#include \"SDOT/OptionUtilities.h\"\n#include \"SDOT/Distances/Wasserstein2.h\"\n\nusing namespace sdot;\nusing namespace sdot::distances;\n\nvoid AddCircle(Eigen::MatrixXd &dens, double x, double y, double r, double dx, double dy)\n{\n  for(int j=0; j<dens.cols(); ++j){\n    double yj = double(j)*dy;//  + 0.5*dy;\n\n    for(int i=0; i<dens.rows(); ++i){\n      double xi = double(i)*dx;// + 0.5*dx;\n\n      if((xi-x)*(xi-x) + (yj-y)*(yj-y) < r*r)\n        dens(i,j) = 1.0;\n    }\n  }\n}\n\n\nint main(int argc, char* argv[])\n{\n  OptionList opts;\n  opts[\"Print Level\"] = 1;\n  opts[\"Max Steps\"] = 300;\n  opts[\"GTol Abs\"] = 1e-8;\n  opts[\"XTol Abs\"] = 1e-9;\n\n  int N = 1;\n\n  Eigen::Matrix2Xd domain(2,4);\n  domain << 0.0, 2.0, 2.0, 0.0,\n            0.0, 0.0, 2.0, 2.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), N, N);\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*grid->dx*grid->dy);\n\n  //double radius = 0.1001;\n  //AddCircle(density, 0.4,0.8, radius, grid->dx, grid->dy);\n  //AddCircle(density, 1.4,0.4, radius, grid->dx, grid->dy);\n\n  std::cout << \"Density = \\n\" << density << std::endl;\n\n  Eigen::MatrixXd pts(2,2);\n  pts << 0.1, 1.5,\n         1.0, 1.0;\n  //pts << 1.26996324, 1.11996324, 1.11996324, 0.83003676, 0.68003676, 0.68003676,\n  //       1.64491023, 1.73151277, 1.55830769, 0.60508977, 0.69169231, 0.51848723;\n  unsigned int numPts = pts.cols();\n\n  auto dist = std::make_shared<DiscretizedDistribution>(grid, density);\n\n  // Evalaute the SDOT objective\n  Eigen::VectorXd discrProbs = Eigen::VectorXd::Ones(pts.cols());\n  discrProbs /= pts.cols();\n\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), opts);\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::cout << \"Working on \" <<  polyInd << std::endl;\n    std::shared_ptr<PolygonRasterizeIter::Polygon_2> poly = lagDiag->GetCell(polyInd)->ToCGAL();\n\n    if(poly->size()>0){\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\n\n  // Check the gradient wrt the points\n  Eigen::Matrix2Xd grad = sdot->PointGradient();\n\n  // Compute a finite difference approximation\n  double fdStep = 1e-5;\n  Eigen::VectorXd newPrices;\n  double newVal;\n\n  for(int ptInd=0; ptInd<pts.cols(); ++ptInd){\n    Eigen::MatrixXd newPts = pts;\n    newPts(0,ptInd) += fdStep;\n\n    auto newSdot = std::make_shared<SemidiscreteOT<Wasserstein2>>(dist, newPts, discrProbs);\n    std::tie(newPrices,newVal) = newSdot->Solve(Eigen::VectorXd::Ones(numPts), opts);\n\n    std::cout << \"Point \" << ptInd << std::endl;\n    std::cout << \"  FD Deriv:   \" << (newVal-optVal)/fdStep << std::endl;\n    std::cout << \"  True Deriv: \" << grad(0,ptInd) << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "d0eec22bf48f74cc14fa93819658c6db1eddafc1", "size": 3679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/CircleProblem.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/CircleProblem.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/CircleProblem.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": 30.4049586777, "max_line_length": 112, "alphanum_fraction": 0.6232671922, "num_tokens": 1253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5727253263048504}}
{"text": "\n/*\nexpressionGenerator.cpp - This file is part of the Bayesembler (v1.1.1)\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Lasse Maretty and Jonas Andreas Sibbesen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include <expressionGenerator.h>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\ntypedef boost::random::mt19937* mt_rng_pt_t;\ntypedef boost::random::uniform_01<boost::random::mt19937*> uniform_01_sampler_t;\ntypedef boost::random::gamma_distribution<> gamma_distribution_t;\ntypedef boost::random::variate_generator<boost::random::mt19937*, boost::random::gamma_distribution<> > gamma_sampler_t;\ntypedef boost::random::uniform_int_distribution<> uniform_sampler_t;\n\nExpressionGenerator::ExpressionGenerator(int num_fragments_in, int num_transcripts_in, mt_rng_pt_t mt_rng_pt_in) {\n\t\n\tnum_fragments = num_fragments_in;\n\tnum_transcripts = num_transcripts_in;\n\tmt_rng_pt = mt_rng_pt_in;\n}\n\nExpressionValueContainer ExpressionGenerator::generateEnsembleExpression(vector<int> indices, double gamma, CountValueContainer map_counts) {\n\t\n\t// Init container\n\tExpressionValueContainer expression(num_transcripts); \n\t\n\t// Sample gammas for s-plus\n\tdouble norm_const_expression = 0;\n\t    \n\tfor (int i = 0; i < indices.size(); i++) {\n\t        \n\t    int trans_id = indices[i];\n\t\n\t    gamma_distribution_t gamma_dist((map_counts.getCount(trans_id) + gamma),1);\n        gamma_sampler_t sample_gamma(mt_rng_pt, gamma_dist);\n\t\t\n        double gamma_sample = sample_gamma();\n        \n\t    norm_const_expression += gamma_sample;\n\t    expression.setBinaryOn(trans_id);\n\t    expression.setValue(gamma_sample, trans_id);\n        expression.addToPlus(trans_id);\n\t}\n\t\n\texpression.normalise(norm_const_expression);\n\t\n\treturn expression;\n}\n\nExpressionValueContainer ExpressionGenerator::generateExpression(int b, double gamma, CountValueContainer map_counts) {\n\t\n\t// Init container\n\tExpressionValueContainer expression(num_transcripts); \n\t\n\t// Sample gammas for s-plus\n\tdouble norm_const_expression = 0;\n\t\n\tfor (int i = 0; i < map_counts.getPlusSize(); i++) {\n\t        \n\t    int trans_id = map_counts.getPlus(i);\n\t\n\t    gamma_distribution_t gamma_dist((map_counts.getCount(trans_id) + gamma),1);\n        gamma_sampler_t sample_gamma(mt_rng_pt, gamma_dist);\n\t\t\n        double gamma_sample = sample_gamma();\n        \n\t    norm_const_expression += gamma_sample;\n\t    expression.setBinaryOn(trans_id);\n\t    expression.setValue(gamma_sample, trans_id);\n        expression.addToPlus(trans_id);\n\t}\n\t\n    gamma_distribution_t gamma_dist_base (gamma, 1);\n    gamma_sampler_t sample_gamma_base (mt_rng_pt, gamma_dist_base);\n\n\t// Sample gammas for the expanded simplex\n\tfor (int i = map_counts.getPlusSize(); i < b ; i++) {\n\t       \n\t    uniform_sampler_t sample_trans(0,(map_counts.getNullSize()-1));\n\t        \n\t    int s_null_idx = sample_trans(*mt_rng_pt);\n\t    int trans_id = map_counts.getNull(s_null_idx);\n\t\t\n\t    assert (map_counts.getCount(trans_id) == 0);\n\t        \t\n\t    double gamma_base_sample = sample_gamma_base();\n\t    assert(gamma_base_sample >= double_underflow);\n\n            \n        // if (gamma_base_sample < almost_zero) {\n            \n        //     gamma_base_sample = almost_zero;    \n        // }\n        \n\t    norm_const_expression += gamma_base_sample;\n\t    expression.setBinaryOn(trans_id);\n\t    expression.setValue(gamma_base_sample, trans_id);\n        expression.addToPlus(trans_id);\n\t    map_counts.eraseNull(s_null_idx);\t\n\t}\n\t\n\texpression.normalise(norm_const_expression);\n\t\n\treturn expression;\n}\n\n\n", "meta": {"hexsha": "1846de39e22656b671841d87565947dc31ed0ffb", "size": 4618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/expressionGenerator.cpp", "max_stars_repo_name": "bhurwitz33/bayesembler", "max_stars_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T15:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-10T15:43:12.000Z", "max_issues_repo_path": "src/expressionGenerator.cpp", "max_issues_repo_name": "bhurwitz33/bayesembler", "max_issues_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/expressionGenerator.cpp", "max_forks_repo_name": "bhurwitz33/bayesembler", "max_forks_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_forks_repo_licenses": ["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.2074074074, "max_line_length": 141, "alphanum_fraction": 0.7438284972, "num_tokens": 1015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523327, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5727116268351357}}
{"text": "#include <iostream>\n#include <chrono>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n\n#include \"utils/FileUtil.h\"\n#include \"algorithm/BFFSolver.h\"\n#include \"algorithm/BonSolver.h\"\n\nusing namespace boost;\nusing namespace std;\nusing namespace std::chrono;\n\n\nint **computeAllShortestPaths2(vector<pair<int, int>> &edges_vec, int n) {\n    const int m = edges_vec.size();\n\n    typedef adjacency_list<vecS, vecS, undirectedS, no_property,\n            property<edge_weight_t, int, property<edge_weight2_t, int>>>\n            Graph;\n\n    typedef std::pair<int, int> Edge;\n    Edge edges_array[m];\n    for (int i = 0; i < m; ++i)\n        edges_array[i] = Edge(edges_vec[i].first, edges_vec[i].second);\n\n    Graph G(edges_array, edges_array + m, n);\n\n    property_map<Graph, edge_weight_t>::type w = get(edge_weight, G);\n    int weights[m];\n    std::fill(weights, weights + m, 1);\n    int *wp = weights;\n\n    graph_traits<Graph>::edge_iterator e, e_end;\n    for (boost::tie(e, e_end) = edges(G); e != e_end; ++e)\n        w[*e] = *wp++;\n\n    int **D = new int *[n];\n    for (int i = 0; i < n; ++i) {\n        D[i] = new int[n];\n    }\n    johnson_all_pairs_shortest_paths(G, D);\n    return D;\n}\n\nint **computeAllShortestPaths(vector<vector<int>> &adj, int n) {\n\n    int **D = new int *[n];\n    for (int i = 0; i < n; ++i) {\n        D[i] = new int[n];\n        fill(D[i], D[i] + n, n);\n        D[i][i] = 0;\n    }\n\n    for (int i = 0; i < n; ++i) {\n        queue<int> q;\n        vector<bool> visited(n);\n        q.push(i);\n        visited[i] = true;\n        while (!q.empty()) {\n            int s = q.front();\n            q.pop();\n            for (auto u: adj[s]) {\n                if (!visited[u]) {\n                    D[i][u] = D[i][s] + 1;\n                    visited[u] = true;\n                    q.push(u);\n                }\n            }\n        }\n    }\n\n    return D;\n}\n\nint main(int argc, char **argv) {\n\n    string input_file = argv[1];\n    string alg = argv[2];\n\n    // read instance\n    vector<pair<int, int>> edges_vec;\n    int n;\n    tie(edges_vec, n) = FileUtil::load_graph(input_file);\n    vector<vector<int>> adj = AlgUtils::createAdjList(edges_vec, n);\n\n    // time of compute all shortest paths\n    auto start = high_resolution_clock::now();\n    int **D = computeAllShortestPaths(adj, n);\n\n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(stop - start);\n    double time_APSP = duration.count() / (double) 1000;\n    // end computations of all shortest paths\n    cout << \"Compute all shortest paths running time: \" << time_APSP << \" seconds\" << endl;\n\n    // time of algorithm\n    vector<int> f;\n    start = high_resolution_clock::now();\n\n    if (alg == \"bon\") {\n        BonSolver solver(n, D);\n        f = solver.run();\n    } else if (alg == \"bff\") {\n        BFFSolver solver(n, D, adj);\n        f = solver.run();\n    } else if (alg == \"bff+\") {\n        BFFSolver solver(n, D, adj);\n        solver.setPlus(true);\n        f = solver.run();\n    } else {\n        cerr << \"Invalid algorithm!\" << endl;\n    }\n    stop = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(stop - start);\n    double time_alg = duration.count() / (double) 1000;\n\n    // print computations times and solution\n    cout << \"Algorithm running time: \" << time_alg << \" seconds\" << endl;\n\n    cout << \"[\";\n    for (int i = 0; i < f.size() - 1; ++i) {\n        cout << f[i] << \", \";\n    }\n    cout << f.back() << \"]\" << endl;\n    cout << f.size() << endl;\n\n    // clear memory\n    for (int i = 0; i < n; ++i) {\n        delete[] D[i];\n    }\n    return 0;\n}\n", "meta": {"hexsha": "df5697fcedc1a2be2f74ca57145697bcf246577c", "size": 3765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "alex-cornejo/bff_alg", "max_stars_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_stars_repo_licenses": ["Apache-2.0"], "max_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": "alex-cornejo/bff_alg", "max_issues_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_issues_repo_licenses": ["Apache-2.0"], "max_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": "alex-cornejo/bff_alg", "max_forks_repo_head_hexsha": "9a06a0d2c8178751cfa9ba434eddf214c89f1eb1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-04T15:17:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T15:17:01.000Z", "avg_line_length": 27.4817518248, "max_line_length": 91, "alphanum_fraction": 0.5561752988, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5727116072237229}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <unordered_map>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Generate the n'th term for the factorial sequence. Uses a cache to speed up results.\r\ncpp_int factorial(int n) {\r\n\tstatic unordered_map<int, cpp_int> cache;\r\n\tif(auto it = cache.find(n); it != cache.end()) {\r\n\t\treturn (*it).second;\r\n\t}\r\n\tif(n > 1) {\r\n\t\tcpp_int res = n * factorial(n - 1);\r\n\t\tcache.insert({n, res});\r\n\t\treturn res;\r\n\t} else {\r\n\t\treturn 1;\r\n\t}\r\n}\r\n\r\n// Gets the combination.\r\ncpp_int nCr(int n, int r) {\r\n\treturn (factorial(n) / (factorial(r) * factorial(n - r)));\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tint over_million_count = 0;\r\n\tfor(int n = 1; n < 101; n++) {\r\n\t\tfor(int r = 1; r <= n; r++) {\r\n\t\t\tif(nCr(n, r) > 1'000'000) {\r\n\t\t\t\tover_million_count++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcout << over_million_count << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "c12e9e69aef27a712e9de19de61717d9fa207540", "size": 903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/53/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/53/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/51-100/53/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 23.1538461538, "max_line_length": 88, "alphanum_fraction": 0.6079734219, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5727116072237229}}
{"text": "#include <geometrycentral/direction_fields.h>\n\n#include \"geometrycentral/linear_solvers.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseQR>\n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\n\n// Anonymous namespace for helper functions\nnamespace {\n\nVertexData<Complex> computeSmoothestVertexDirectionField_noBoundary(Geometry<Euclidean>* geometry, int nSym,\n                                                                    bool alignCurvature) {\n  HalfedgeMesh* mesh = geometry->getMesh();\n  size_t N = mesh->nVertices();\n\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireVertexTransportCoefs();\n  gc.requireEdgeCotanWeights();\n  gc.requireVertexIndices();\n  gc.requireVertexDualAreas();\n\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(\n      N, N); // have to use ColMajor because LU solver below demands it\n\n  // Supposedly reserving space in the matrix makes construction real zippy\n  // below\n  Eigen::VectorXi nEntries(N);\n  for (VertexPtr v : mesh->vertices()) {\n    nEntries[gc.vertexIndices[v]] = v.degree() + 1;\n  }\n  energyMatrix.reserve(nEntries);\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(N, N);\n  massMatrix.reserve(1);\n\n  // === Build matrices\n\n  // Build the mass matrix\n  for (VertexPtr v : mesh->vertices()) {\n    size_t i = gc.vertexIndices[v];\n    massMatrix.insert(i, i) = gc.vertexDualAreas[v];\n  }\n\n  // Build the energy matrix\n  for (VertexPtr v : mesh->vertices()) {\n    size_t i = gc.vertexIndices[v];\n\n    std::complex<double> weightISum = 0;\n    for (HalfedgePtr he : v.incomingHalfedges()) {\n      size_t j = gc.vertexIndices[he.vertex()];\n      std::complex<double> rBar = std::pow(gc.vertexTransportCoefs[he], nSym);\n      double weight = gc.edgeCotanWeights[he.edge()];\n      energyMatrix.insert(i, j) = -weight * rBar;\n      weightISum += weight;\n    }\n\n    energyMatrix.insert(i, i) = weightISum;\n  }\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<Complex> eye(N, N);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    gc.requirePrincipalDirections();\n\n    Eigen::VectorXcd dirVec(N);\n    if (nSym == 2) {\n      for (VertexPtr v : mesh->vertices()) {\n        dirVec[gc.vertexIndices[v]] = gc.principalDirections[v];\n      }\n    } else if (nSym == 4) {\n      for (VertexPtr v : mesh->vertices()) {\n        dirVec[gc.vertexIndices[v]] = std::pow(gc.principalDirections[v], 2);\n      }\n    }\n\n    // Normalize the alignment field\n    double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n    dirVec /= scale;\n\n    double lambdaT = 0.0; // this is something of a magical constant, see\n                          // \"Globally Optimal Direction Fields\", eqn 16\n\n    // Eigen::VectorXcd RHS = massMatrix * dirVec;\n    Eigen::VectorXcd RHS = dirVec;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n    solution = solveSquare(LHS, RHS);\n  }\n  // Otherwise find the smallest eigenvector\n  else {\n    std::cout << \"Solving smoothest field eigenvalue problem...\" << std::endl;\n    solution = smallestEigenvectorPositiveDefinite(energyMatrix, massMatrix);\n  }\n\n  // Copy the result to a VertexData vector\n  VertexData<Complex> toReturn(mesh);\n  for (VertexPtr v : mesh->vertices()) {\n    toReturn[v] = solution[gc.vertexIndices[v]] / std::abs(solution[gc.vertexIndices[v]]);\n  }\n\n  return toReturn;\n}\n\nVertexData<Complex> computeSmoothestVertexDirectionField_boundary(Geometry<Euclidean>* geometry, int nSym,\n                                                                  bool alignCurvature) {\n  HalfedgeMesh* mesh = geometry->getMesh();\n  size_t nInterior = mesh->nInteriorVertices();\n\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireVertexTransportCoefs();\n  gc.requireEdgeCotanWeights();\n  gc.requireVertexBases();\n  gc.requireInteriorVertexIndices();\n  gc.requireVertexDualAreas();\n\n  // Compute the boundary values\n  VertexData<std::complex<double>> boundaryValues(mesh);\n  for (VertexPtr v : mesh->vertices()) {\n    if (v.isBoundary()) {\n      Vector3 b = geometry->boundaryNormal(v);\n      Complex bC(dot(gc.vertexBases[v][0], b), dot(gc.vertexBases[v][1], b)); // TODO can do better\n      bC = unit(bC);\n      boundaryValues[v] = std::pow(bC, nSym);\n    } else {\n      boundaryValues[v] = 0;\n    }\n  }\n\n  VertexData<size_t> vertInd = mesh->getInteriorVertexIndices();\n\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(nInterior, nInterior);\n\n  Eigen::VectorXi nEntries(nInterior);\n  for (VertexPtr v : mesh->vertices()) {\n    if (v.isBoundary()) {\n      continue;\n    }\n    nEntries[gc.interiorVertexIndices[v]] = v.degree() + 1;\n  }\n  energyMatrix.reserve(nEntries);\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(nInterior, nInterior);\n  massMatrix.reserve(1);\n\n  // RHS\n  Eigen::VectorXcd b(nInterior);\n\n  // === Build matrices\n\n  // Build the mass matrix and zero b\n  for (VertexPtr v : mesh->vertices()) {\n    if (v.isBoundary()) {\n      continue;\n    }\n    size_t i = gc.interiorVertexIndices[v];\n    b(i) = 0.0;\n    massMatrix.insert(i, i) = gc.vertexDualAreas[v];\n  }\n\n  // Build the energy matrix\n  for (VertexPtr v : mesh->vertices()) {\n    if (v.isBoundary()) {\n      continue;\n    }\n    size_t i = gc.interiorVertexIndices[v];\n\n    std::complex<double> weightISum = 0;\n    for (HalfedgePtr he : v.incomingHalfedges()) {\n      std::complex<double> rBar = std::pow(gc.vertexTransportCoefs[he], nSym);\n      double w = gc.edgeCotanWeights[he.edge()];\n\n      // Interior-boundary term\n      if (he.vertex().isBoundary()) {\n        std::complex<double> bVal = boundaryValues[he.vertex()];\n        b(i) += w * rBar * bVal;\n      } else { // Interior-interior term\n        size_t j = gc.interiorVertexIndices[he.vertex()];\n        energyMatrix.insert(i, j) = -w * rBar;\n      }\n      weightISum += w;\n    }\n\n    energyMatrix.insert(i, i) = weightISum;\n  }\n\n  // Shift to avoid singularities\n  Eigen::SparseMatrix<Complex> eye(nInterior, nInterior);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Compute the actual solution\n  std::cout << \"Solving linear problem...\" << std::endl;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    gc.requirePrincipalDirections();\n\n    Eigen::VectorXcd dirVec(nInterior);\n    for (VertexPtr v : mesh->vertices()) {\n      if (v.isBoundary()) {\n        continue;\n      }\n\n      Complex directionVal = gc.principalDirections[v];\n      if (nSym == 4) {\n        directionVal = std::pow(directionVal, 2);\n      }\n\n      // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n      // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals and\n      // the magnitude of the desired field.  Be careful when interpreting this as opposed to the usual direction field\n      // optimization.\n      dirVec[gc.interiorVertexIndices[v]] = directionVal / std::abs(directionVal);\n    }\n\n    double t = 0.01; // this is something of a magical constant, see \"Globally\n                     // Optimal Direction Fields\", eqn 9\n\n    Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    solution = solveSquare(LHS, RHS);\n  }\n  // Otherwise find the general closest solution\n  else {\n    std::cout << \"Solving smoothest field dirichlet problem...\" << std::endl;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    Eigen::VectorXcd RHS = massMatrix * b;\n    solution = solveSquare(LHS, RHS);\n  }\n\n  // Copy the result to a VertexData vector for both the boudary and interior\n  VertexData<Complex> toReturn(mesh);\n  for (VertexPtr v : mesh->vertices()) {\n    if (v.isBoundary()) {\n      toReturn[v] = boundaryValues[v];\n    } else {\n      toReturn[v] = unit(solution[gc.interiorVertexIndices[v]]);\n    }\n  }\n\n  return toReturn;\n}\n}; // namespace\n\nVertexData<Complex> computeSmoothestVertexDirectionField(Geometry<Euclidean>* geometry, int nSym, bool alignCurvature) {\n  std::cout << \"Computing globally optimal direction field\" << std::endl;\n\n  if (alignCurvature && !(nSym == 2 || nSym == 4)) {\n    throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or \"\n                           \"4\");\n  }\n\n  // Dispatch to either the boundary of no boundary variant depending on the\n  // mesh type\n  bool hasBoundary = false;\n  for (VertexPtr v : geometry->getMesh()->vertices()) {\n    hasBoundary |= v.isBoundary();\n  }\n\n  if (hasBoundary) {\n    std::cout << \"Mesh has boundary, computing dirichlet boundary condition solution\" << std::endl;\n    return computeSmoothestVertexDirectionField_boundary(geometry, nSym, alignCurvature);\n  } else {\n    std::cout << \"Mesh has no boundary, computing unit-norm solution\" << std::endl;\n    return computeSmoothestVertexDirectionField_noBoundary(geometry, nSym, alignCurvature);\n  }\n}\n\n// Helpers for computing face-based direction fields\nnamespace {\n\nFaceData<Complex> computeSmoothestFaceDirectionField_noBoundary(Geometry<Euclidean>* geometry, int nSym,\n                                                                bool alignCurvature) {\n\n  HalfedgeMesh* mesh = geometry->getMesh();\n  unsigned int N = mesh->nFaces();\n\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireFaceTransportCoefs();\n  gc.requireFaceNormals();\n  gc.requireFaceAreas();\n  gc.requireDihedralAngles();\n  gc.requireFaceIndices();\n\n  // === Allocate matrices\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(N, N);\n  energyMatrix.reserve(Eigen::VectorXi::Constant(N, 4));\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(N, N);\n  massMatrix.reserve(Eigen::VectorXi::Constant(N, 1));\n\n\n  // === Build matrices\n\n  // Build the mass matrix\n  for (FacePtr f : mesh->faces()) {\n    size_t i = gc.faceIndices[f];\n    massMatrix.insert(i, i) = gc.faceAreas[f];\n  }\n\n  // Build the energy matrix\n  for (FacePtr f : mesh->faces()) {\n    size_t i = gc.faceIndices[f];\n\n    std::complex<double> weightISum = 0;\n    for (HalfedgePtr he : f.adjacentHalfedges()) {\n\n      if (!he.twin().isReal()) {\n        continue;\n      }\n\n      FacePtr neighFace = he.twin().face();\n      unsigned int j = gc.faceIndices[neighFace];\n\n      // LC connection between the faces\n      Complex rBar = std::pow(gc.faceTransportCoefs[he.twin()], nSym);\n\n      double weight = 1; // FIXME TODO figure out weights\n      energyMatrix.insert(i, j) = -weight * rBar;\n      weightISum += weight;\n    }\n\n    energyMatrix.insert(i, i) = weightISum;\n  }\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<Complex> eye(N, N);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    Eigen::VectorXcd dirVec(N);\n    for (FacePtr f : mesh->faces()) {\n\n      // Compute something like the principal directions\n      double weightSum = 0;\n      Complex sum = 0;\n\n      for (HalfedgePtr he : f.adjacentHalfedges()) {\n\n        double dihedralAngle = std::abs(gc.dihedralAngles[he.edge()]);\n        double weight = norm(geometry->vector(he));\n        weightSum += weight;\n        double angleCoord = angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), gc.faceNormals[f]);\n        Complex coord = std::exp(angleCoord * IM_I *\n                                 (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n        sum += coord * weight * dihedralAngle;\n      }\n\n      sum /= weightSum;\n\n      dirVec[gc.faceIndices[f]] = sum;\n    }\n\n    // Normalize the alignment field\n    double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n    dirVec /= scale;\n\n    double lambdaT = 0.0; // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n\n    // Eigen::VectorXcd RHS = massMatrix * dirVec;\n    Eigen::VectorXcd RHS = dirVec;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n    solution = solveSquare(LHS, RHS);\n\n  }\n  // Otherwise find the smallest eigenvector\n  else {\n    std::cout << \"Solving smoothest field eigenvalue problem...\" << std::endl;\n    solution = smallestEigenvectorPositiveDefinite(energyMatrix, massMatrix);\n  }\n\n\n  // Copy the result to a FaceData object\n  FaceData<Complex> field(mesh);\n  for (FacePtr f : mesh->faces()) {\n    field[f] = solution[gc.faceIndices[f]] / std::abs(solution[gc.faceIndices[f]]);\n  }\n\n  return field;\n}\n\nFaceData<Complex> computeSmoothestFaceDirectionField_boundary(Geometry<Euclidean>* geometry, int nSym,\n                                                              bool alignCurvature) {\n\n  HalfedgeMesh* mesh = geometry->getMesh();\n\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireFaceTransportCoefs();\n  gc.requireFaceNormals();\n  gc.requireFaceAreas();\n  gc.requireDihedralAngles();\n\n\n  // Index interior faces\n  size_t nInteriorFace = 0;\n  FaceData<size_t> interiorFaceInd(mesh, -77);\n  FaceData<char> isInterior(mesh);\n  for (FacePtr f : mesh->faces()) {\n    bool isBoundary = false;\n    for (EdgePtr e : f.adjacentEdges()) {\n      isBoundary |= e.isBoundary();\n    }\n    isInterior[f] = !isBoundary;\n    if (!isBoundary) {\n      interiorFaceInd[f] = nInteriorFace++;\n    }\n  }\n\n  // Compute boundary values\n  FaceData<Complex> boundaryValues(mesh);\n  for (FacePtr f : mesh->faces()) {\n    if (isInterior[f]) {\n      boundaryValues[f] = 0;\n    } else {\n      Vector3 bVec = Vector3::zero();\n      for (HalfedgePtr he : f.adjacentHalfedges()) {\n        if (he.edge().isBoundary()) {\n          bVec += geometry->vector(he).rotate_around(gc.faceNormals[f], -PI / 2.0);\n        }\n      }\n      Complex bC(dot(gc.faceBases[f][0], bVec), dot(gc.faceBases[f][1], bVec));\n      bC = unit(bC);\n      boundaryValues[f] = std::pow(bC, nSym);\n    }\n  }\n\n\n  // === Allocate matrices\n  // Energy matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> energyMatrix(nInteriorFace, nInteriorFace);\n  energyMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 4));\n\n  // Mass matrix\n  Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> massMatrix(nInteriorFace, nInteriorFace);\n  massMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 1));\n\n  // RHS\n  Eigen::VectorXcd b(nInteriorFace);\n\n  // === Build matrices\n\n  // Build the mass matrix\n  for (FacePtr f : mesh->faces()) {\n    if (isInterior[f]) {\n      size_t i = interiorFaceInd[f];\n      massMatrix.insert(i, i) = gc.faceAreas[f];\n    }\n  }\n\n  // Build the energy matrix\n  for (FacePtr f : mesh->faces()) {\n    if (isInterior[f]) {\n      size_t i = interiorFaceInd[f];\n\n      std::complex<double> weightISum = 0;\n      for (HalfedgePtr he : f.adjacentHalfedges()) {\n\n        FacePtr neighFace = he.twin().face();\n        double weight = 1; // FIXME TODO figure out weights\n        Complex rBar = std::pow(gc.faceTransportCoefs[he.twin()], nSym);\n\n        if (isInterior[neighFace]) {\n          size_t j = interiorFaceInd[neighFace];\n          energyMatrix.insert(i, j) = -weight * rBar;\n        } else {\n          std::complex<double> bVal = boundaryValues[neighFace];\n          b(i) += weight * rBar * bVal;\n        }\n\n        weightISum += weight;\n      }\n\n      energyMatrix.insert(i, i) = weightISum;\n    }\n  }\n\n  // Shift to avoid singularity\n  Eigen::SparseMatrix<Complex> eye(nInteriorFace, nInteriorFace);\n  eye.setIdentity();\n  energyMatrix += 1e-4 * eye;\n\n  // Store the solution here\n  Eigen::VectorXcd solution;\n\n  // If requested, align to principal curvatures\n  if (alignCurvature) {\n\n    Eigen::VectorXcd dirVec(nInteriorFace);\n    for (FacePtr f : mesh->faces()) {\n      if (isInterior[f]) {\n\n        // Compute something like the principal directions\n        double weightSum = 0;\n        Complex sum = 0;\n\n        for (HalfedgePtr he : f.adjacentHalfedges()) {\n\n          double dihedralAngle = std::abs(gc.dihedralAngles[he.edge()]);\n          double weight = norm(geometry->vector(he));\n          weightSum += weight;\n          double angleCoord = angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), gc.faceNormals[f]);\n          Complex coord = std::exp(angleCoord * IM_I *\n                                   (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n          sum += coord * weight * dihedralAngle;\n        }\n\n        sum /= weightSum;\n\n        // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n        // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals\n        // and the magnitude of the desired field.  Be careful when interpreting this as opposed to the usual direction\n        // field optimization.\n        dirVec[interiorFaceInd[f]] = unit(sum);\n      }\n    }\n\n\n    double t = 0.1;  // this is something of a magical constant, see \"Globally\n                     // Optimal Direction Fields\", eqn 9\n                     // NOTE: This value is different from the one used for vertex fields; seems to work better?\n\n    std::cout << \"Solving smoothest field dirichlet problem with curvature term...\" << std::endl;\n    Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    solution = solveSquare(LHS, RHS);\n\n  }\n  // Otherwise find the general closest solution\n  else {\n    std::cout << \"Solving smoothest field dirichlet problem...\" << std::endl;\n    Eigen::SparseMatrix<std::complex<double>, Eigen::ColMajor> LHS = energyMatrix;\n    Eigen::VectorXcd RHS = massMatrix * b;\n    solution = solveSquare(LHS, RHS);\n  }\n\n\n  // Copy the result to a FaceData object\n  FaceData<Complex> field(mesh);\n  for (FacePtr f : mesh->faces()) {\n    if (isInterior[f]) {\n      field[f] = unit(solution[interiorFaceInd[f]]);\n    } else {\n      field[f] = unit(boundaryValues[f]);\n    }\n  }\n\n  return field;\n}\n\n} // namespace\n\nFaceData<Complex> computeSmoothestFaceDirectionField(Geometry<Euclidean>* geometry, int nSym, bool alignCurvature) {\n\n  std::cout << \"Computing globally optimal direction field in faces\" << std::endl;\n\n  if (alignCurvature && !(nSym == 2 || nSym == 4)) {\n    throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or \"\n                           \"4\");\n  }\n\n  // Dispatch to either the boundary of no boundary variant depending on the mesh type\n  bool hasBoundary = false;\n  for (VertexPtr v : geometry->getMesh()->vertices()) {\n    hasBoundary |= v.isBoundary();\n  }\n\n\n  if (hasBoundary) {\n    std::cout << \"Mesh has boundary, computing dirichlet boundary condition solution\" << std::endl;\n    return computeSmoothestFaceDirectionField_boundary(geometry, nSym, alignCurvature);\n  } else {\n    std::cout << \"Mesh has no boundary, computing unit-norm solution\" << std::endl;\n    return computeSmoothestFaceDirectionField_noBoundary(geometry, nSym, alignCurvature);\n  }\n}\n\n\nFaceData<int> computeFaceIndex(Geometry<Euclidean>* geometry, VertexData<Complex> directionField, int nSym) {\n  HalfedgeMesh* mesh = geometry->getMesh();\n\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireFaceTransportCoefs();\n\n  // Store the result here\n  FaceData<int> indices(mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (FacePtr f : mesh->faces()) {\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = 0;\n\n    for (HalfedgePtr he : f.adjacentHalfedges()) {\n      // Compute the rotation along the halfedge implied by the field\n      Complex x0 = directionField[he.vertex()];\n      Complex x1 = directionField[he.twin().vertex()];\n      Complex transport = std::pow(gc.vertexTransportCoefs[he], nSym);\n\n      // Find the difference in angle\n      double theta0 = std::arg(transport * x0);\n      double theta1 = std::arg(x1);\n      double deltaTheta = regularizeAngle(theta1 - theta0 + PI) - PI; // regularize to [-PI,PI]\n\n      totalRot += deltaTheta; // accumulate\n    }\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[f] = index;\n  }\n\n  return indices;\n}\n\n\nVertexData<int> computeVertexIndex(Geometry<Euclidean>* geometry, FaceData<Complex> directionField, int nSym) {\n\n  HalfedgeMesh* mesh = geometry->getMesh();\n  GeometryCache<Euclidean>& gc = geometry->cache;\n  gc.requireFaceTransportCoefs();\n\n  // Store the result here\n  VertexData<int> indices(mesh);\n\n  // TODO haven't tested that this correctly reports the index when it is larger\n  // than +-1\n\n  for (VertexPtr v : mesh->vertices()) {\n\n    // Trace the direction field around the face and see how many times it\n    // spins!\n    double totalRot = 0;\n\n    for (HalfedgePtr he : v.incomingHalfedges()) {\n      // Compute the rotation along the halfedge implied by the field\n      Complex x0 = directionField[he.face()];\n      Complex x1 = directionField[he.twin().face()];\n      Complex transport = std::pow(gc.faceTransportCoefs[he], nSym);\n\n      // Find the difference in angle\n      double theta0 = std::arg(transport * x0);\n      double theta1 = std::arg(x1);\n      double deltaTheta = std::arg(x1 / (transport * x0));\n\n      totalRot += deltaTheta;\n    }\n\n    double angleDefect = geometry->angleDefect(v);\n    totalRot += angleDefect * nSym;\n\n    // Compute the net rotation and corresponding index\n    int index = static_cast<int>(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n    indices[v] = index;\n  }\n\n  return indices;\n}\n\n} // namespace geometrycentral\n", "meta": {"hexsha": "e97ac6bccff019407d3c54a5e08a0df4cbbecfe6", "size": 22266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/direction_fields.cpp", "max_stars_repo_name": "connorzl/geometry-central", "max_stars_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-21T04:54:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-21T03:51:53.000Z", "max_issues_repo_path": "src/direction_fields.cpp", "max_issues_repo_name": "connorzl/geometry-central", "max_issues_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/direction_fields.cpp", "max_forks_repo_name": "connorzl/geometry-central", "max_forks_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-14T21:48:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-14T21:48:51.000Z", "avg_line_length": 32.0374100719, "max_line_length": 120, "alphanum_fraction": 0.651621306, "num_tokens": 5720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5726790732938648}}
{"text": "#include <Eigen/Eigen>\n#include <Eigen/Eigenvalues>\n\n#include \"py4dgeo/compute.hpp\"\n#include \"py4dgeo/kdtree.hpp\"\n#include \"py4dgeo/openmp.hpp\"\n#include \"py4dgeo/py4dgeo.hpp\"\n\n#include <algorithm>\n#include <complex>\n#include <vector>\n\nnamespace py4dgeo {\n\nvoid\ncompute_multiscale_directions(const Epoch& epoch,\n                              EigenPointCloudConstRef corepoints,\n                              const std::vector<double>& scales,\n                              EigenNormalSetConstRef orientation,\n                              EigenNormalSetRef result)\n{\n  // Instantiate a container for the first thrown exception in\n  // the following parallel region.\n  CallbackExceptionVault vault;\n#ifdef PY4DGEO_WITH_OPENMP\n#pragma omp parallel for schedule(dynamic, 1)\n#endif\n  for (IndexType i = 0; i < corepoints.rows(); ++i) {\n    vault.run([&]() {\n      double highest_planarity = 0.0;\n      for (auto scale : scales) {\n        // Find the working set on this scale\n        KDTree::RadiusSearchResult points;\n        auto qp = corepoints.row(i).eval();\n        epoch.kdtree.radius_search(&(qp(0, 0)), scale, points);\n        auto subset = epoch.cloud(points, Eigen::all).cast<double>();\n\n        // Calculate covariance matrix\n        auto centered = subset.rowwise() - subset.colwise().mean();\n        auto cov = (centered.adjoint() * centered) / double(subset.rows() - 1);\n        auto coveval = cov.eval();\n\n        // Calculate Eigen vectors\n        Eigen::SelfAdjointEigenSolver<decltype(coveval)> solver(coveval);\n        const auto& evalues = solver.eigenvalues();\n\n        // Calculate planarity\n        double planarity = (evalues[1] - evalues[0]) / evalues[2];\n        if (planarity > highest_planarity) {\n          highest_planarity = planarity;\n\n          double prod =\n            (solver.eigenvectors().col(0).dot(orientation.row(0).transpose()));\n          double sign = (prod < 0.0) ? -1.0 : 1.0;\n          result.row(i) = sign * solver.eigenvectors().col(0);\n        }\n      }\n    });\n  }\n\n  // Potentially rethrow an exception that occurred in above parallel region\n  vault.rethrow();\n}\n\n}", "meta": {"hexsha": "57e39ff3e372f3753bfb41a39e58017a5d5c71a2", "size": 2112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/directions.cpp", "max_stars_repo_name": "ssciwr/geolib4d", "max_stars_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T14:18:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T21:52:43.000Z", "max_issues_repo_path": "lib/directions.cpp", "max_issues_repo_name": "ssciwr/geolib4d", "max_issues_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-06-18T14:10:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T06:12:58.000Z", "max_forks_repo_path": "lib/directions.cpp", "max_forks_repo_name": "ssciwr/py4dgeo", "max_forks_repo_head_hexsha": "dd79a746559235e47c2cb5e7c7ba71ef3ae21e29", "max_forks_repo_licenses": ["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.4923076923, "max_line_length": 79, "alphanum_fraction": 0.6202651515, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5726790633245367}}
{"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_SVD_INCLUDE\n#define MTL_MATRIX_SVD_INCLUDE\n\n#include <cmath>\n#include <limits>\n#include <algorithm>\n#include <boost/numeric/mtl/matrix/strict_upper.hpp>\n#include <boost/numeric/mtl/operation/diagonal.hpp>\n#include <boost/numeric/mtl/operation/one_norm.hpp>\n#include <boost/numeric/mtl/operation/sub_matrix.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/operation/two_norm.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\nnamespace mtl { namespace mat {\n\n/// Returns A=S*V*D' for matrix A as references\ntemplate <typename Matrix>\ninline void svd(const Matrix& A, Matrix& S, Matrix& V, Matrix& D, double tol= 10e-10)\n{\n\tvampir_trace<3037> tracer;\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), loops, col= ncols, row= nrows;\n    value_type       ref, zero= math::zero(ref), one= math::one(ref); \n    double \t     err(std::numeric_limits<double>::max()), e, f;\n\n    if (nrows != ncols) // important for right dimension\n\tstd::swap(row, col);\n    \n     //init\n    Matrix Q(row,row),  R(row,col),  VT(row,col), E(row,col), \n \t   QT(col,col), RT(col,row);\n\n    loops= 100 * std::max(nrows,ncols);\n    S= one; D= one; E= zero;\n    for (size_type i= 0; err > tol && i < loops; ++i) {\n\tboost::tie(QT, RT)= qr(V);\n \tS*= QT;\n\tVT= trans(RT);\n\tboost::tie(Q, R)= qr(VT);\n\tD*= Q;\n\tE= triu(R,1);\n\tV= trans(R);\n\n\t//ready for exit when upper(R)=0\n\tf= two_norm(diagonal(R));\n\te= one_norm(E);\n\tif ( f== zero ) f= 1;\n\terr= e/f;\n    } //end for\n    \n    {\n\tV= 0;  \n\tmtl::mat::inserter<Matrix>  ins_V(V);\n\tmtl::mat::inserter<Matrix,  mtl::operations::update_times<value_type> > ins_S(S);\n\n\tfor (size_type i= 0, end= std::min(nrows, ncols); i < end; i++) {\n\t    ins_V[i][i] << std::abs(R[i][i]);\n\t    if (R[i][i] < zero) \t\n\t\tfor (size_type j= 0; j < nrows; j++) \n\t\t    ins_S[j][i] << -1;  //carefull changing: multiplication with minus one\n\t}\n    }\n}\n\n/// Returns A=S*V*D' for matrix A as triplet\ntemplate <typename Matrix>\nboost::tuple<Matrix, Matrix, Matrix >\ninline svd(const Matrix& A, double tol= 10e-10)\n{\n\tvampir_trace<3038> tracer;\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type    ncols= num_cols(A), nrows= num_rows(A), col= ncols, row= nrows;\n    if (nrows != ncols) // important for right dimension\n\tstd::swap(row, col);\n\n    Matrix       ST(col,col), V(A), D(row,row);\n    svd(A, ST, V, D, tol);\n    return boost::make_tuple(ST, V, D);\n}\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_SVD_INCLUDE\n", "meta": {"hexsha": "3875c113b63cef0dc2e8fe4b5735605e17578446", "size": 3148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/svd.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/svd.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/svd.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": 30.862745098, "max_line_length": 94, "alphanum_fraction": 0.6591486658, "num_tokens": 933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5726365379725865}}
{"text": "#include <cmath>\n#include <array>\n#include <stdexcept>\n#ifdef HAS_EIGEN3\n#include <Eigen/Eigenvalues>\n#endif\n\n#include <Kernels/precision.hpp>\n#include <Physics/InitialField.h>\n#include <Model/Setup.h>\n#include <Solver/Interoperability.h>\n\nextern seissol::Interoperability e_interoperability;\n\nseissol::physics::Planarwave::Planarwave(real phase)\n  : m_setVar(27),\n    m_kVec{3.14159265358979323846, 3.14159265358979323846, 3.14159265358979323846},\n    m_phase(phase)\n{\n#ifdef HAS_EIGEN3\n  const double rho = 1.0;\n  const double mu = 1.0;\n  const double lambda = 2.0;\n  const double Qp = 20.0;\n  const double Qs = 10.0;\n\n\n  seissol::model::Material material;\n  e_interoperability.fitAttenuation(rho, mu, lambda, Qp, Qs, material);\n\n  std::complex<real> planeWaveOperator[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES];\n  model::getPlaneWaveOperator(material, m_kVec.data(), planeWaveOperator);\n\n  using Matrix = Eigen::Matrix<std::complex<real>, NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES, Eigen::ColMajor>;\n  using Vector = Eigen::Matrix<std::complex<real>, NUMBER_OF_QUANTITIES, 1, Eigen::ColMajor>;\n  Matrix A(planeWaveOperator);\n  Eigen::ComplexEigenSolver<Matrix> ces;\n  ces.compute(A);\n\n  auto eigenvalues = ces.eigenvalues();\n  for (size_t i = 0; i < NUMBER_OF_QUANTITIES; ++i) {\n    m_lambdaA[i] = eigenvalues(i,0);\n  }\n\n  Vector ic;\n  for (size_t j = 0; j < 9; ++j) {\n    ic(j) = 1.0;\n  }\n  for (size_t j = 9; j < NUMBER_OF_QUANTITIES; ++j) {\n    ic(j) = 0.0;\n  }\n\n  auto eigenvectors = ces.eigenvectors();\n  Vector amp = eigenvectors.colPivHouseholderQr().solve(ic);\n  for (int j = 0; j < m_setVar; ++j) {\n    m_varField.push_back(j);\n    m_ampField.push_back(amp(j));\n  }\n\n  auto R = yateto::DenseTensorView<2,std::complex<real>>(m_eigenvectors, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});\n  for (size_t j = 0; j < NUMBER_OF_QUANTITIES; ++j) {\n    for (size_t i = 0; i < NUMBER_OF_QUANTITIES; ++i) {\n      R(i,j) = eigenvectors(i,j);\n    }\n  }\n#else\n  throw std::runtime_error(\"Eigen3 required for anelastic planarwave.\");\n#endif\n}\n\nvoid seissol::physics::Planarwave::evaluate(  double time,\n                                              std::vector<std::array<double, 3>> const& points,\n                                              yateto::DenseTensorView<2,real,unsigned>& dofsQP ) const\n{\n  dofsQP.setZero();\n\n  auto R = yateto::DenseTensorView<2,std::complex<real>>(\n             const_cast<std::complex<real>*>(m_eigenvectors),\n             {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES}\n           );\n  for (int v = 0; v < m_setVar; ++v) {\n    const auto omega =  m_lambdaA[m_varField[v]];\n    for (unsigned j = 0; j < dofsQP.shape(1); ++j) {\n      for (size_t i = 0; i < points.size(); ++i) {\n        dofsQP(i,j) += (R(j,m_varField[v]) * m_ampField[v] *\n                        std::exp(std::complex<real>(0.0, 1.0) * (\n                          omega * time - m_kVec[0]*points[i][0] - m_kVec[1]*points[i][1] - m_kVec[2]*points[i][2] + m_phase\n                        ))).real();\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "3a1a2d4d51bb73e3cd18ae891da65800a1ce35a7", "size": 3016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Equations/viscoelastic2/Physics/InitialField.cpp", "max_stars_repo_name": "ivotron/SeisSol", "max_stars_repo_head_hexsha": "51c2935566998480f948caf2b66b27b80df4b2c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Equations/viscoelastic2/Physics/InitialField.cpp", "max_issues_repo_name": "ivotron/SeisSol", "max_issues_repo_head_hexsha": "51c2935566998480f948caf2b66b27b80df4b2c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Equations/viscoelastic2/Physics/InitialField.cpp", "max_forks_repo_name": "ivotron/SeisSol", "max_forks_repo_head_hexsha": "51c2935566998480f948caf2b66b27b80df4b2c4", "max_forks_repo_licenses": ["BSD-3-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.4301075269, "max_line_length": 123, "alphanum_fraction": 0.6352785146, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5726365278977064}}
{"text": "#include <utility>\n#include <random>\n#include <vector>\n#include <random>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n#include <Eigen/Dense>\n\ntypedef std::pair<double, double> CoordinatePair;\ntypedef struct {\n  double value;\n  CoordinatePair location;\n} Target;\n\nconst std::string ln = \"\\r\\n\";\nconst std::string del = \" \";\n\nconst char* DATA_FILE_ARG = \"data\";\nconst char* NUM_NODES_ARG = \"nodes\";\nconst char* SENSING_RANGE_ARG = \"sense_range\";\nconst char* COMMUNICATION_RANGE_ARG = \"comm_range\";\nconst char* FIELD_X_ARG = \"x\";\nconst char* FIELD_Y_ARG = \"y\";\nconst char* FIELD_CELLS_ARG = \"cells\";\n\nconst double C_W_CONSTANT = 0.01;\n\nconst int SEED = 5;\nconst double NO_READING = -9999.9999;\n\nconst double ERROR_THRESHOLD = 0.0001;\n\nclass Configurations{\n public:\n  std::string data_file_name;\n  int number_of_sensor_nodes;\n  double sensing_range;\n  double communication_range;\n  double field_x_size;\n  double field_y_size;\n  int field_cells;\n\n  Configurations() {\n    data_file_name = \"data_files_should_have_names\";\n    number_of_sensor_nodes = 10;\n    sensing_range = 1.6;\n    communication_range = 1.5;\n    field_x_size = 4.0;\n    field_y_size = 4.0;\n    field_cells = 25;\n  };\n};\n\n\nConfigurations ProcessCommandLineArguments(int pArgc, char** pArguments);\n\nCoordinatePair GenerateNewCoordinatePair(\n  std::default_random_engine& random_generator,\n  const Configurations& configurations);\n\ndouble GenerateNoisyReading(\n  Target target,\n  double constant,\n  CoordinatePair sensor_node_location,\n  CoordinatePair average_sensor_location,\n  double sensing_range,\n  std::default_random_engine generator);\n\ndouble ComputeDistance(\n  CoordinatePair node_location,\n  CoordinatePair reckoning_point);\n\ndouble ComputeNoiseCovariance(\n  const CoordinatePair& node_coordinates,\n  const CoordinatePair& reckoning_point,\n  double p_weight_constant,\n  double p_node_sensing_range);\n\nint CountNeighbors(\n  double communication_range,\n  CoordinatePair source,\n  std::vector<CoordinatePair> all_nodes);\n\nint CountNeighborsWhoSenseTarget(\n  double communication_range,\n  CoordinatePair source,\n  std::vector<CoordinatePair> all_nodes,\n  Eigen::VectorXd estimates);\n\ndouble ComputeAverageEstimate(\n  Eigen::VectorXd estimates,\n  Eigen::MatrixXd weights,\n  std::function<double(Eigen::VectorXd, Eigen::MatrixXd)> averaging_method);\n\ndouble ComputeMaxDegreeWeight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights);\n\ndouble ComputeMetropolisWeight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights);\n\nbool EmptyEstimatePresent(Eigen::VectorXd estimates);\n\nbool SomeNodeNotConverged(\n  Eigen::VectorXd estimates,\n  double average_estimate,\n  double error_threshold,\n  bool method);\n\nvoid DumpResultsToFile(\n  Configurations configurations,\n  std::string filename,\n  std::vector<CoordinatePair> nodes,\n  std::vector<Eigen::VectorXd> estimates);\n\nstd::vector<Eigen::VectorXd> MaxDegreeAnalysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates);\n\nstd::vector<Eigen::VectorXd> MetropolisAnalysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates);\n\nstd::vector<Eigen::VectorXd> WeightDesign1Analysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates);\n\nstd::vector<Eigen::VectorXd> WeightDesign2Analysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates);\n\ndouble ComputeWeightDesign1Weight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  double sensing_range,\n  CoordinatePair target_location,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights);\n\ndouble ComputeWeightDesign2Weight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  double sensing_range,\n  CoordinatePair target_location,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights,\n  Eigen::VectorXd estimates);\n\nstd::vector<Target> ReadInData(Configurations configurations, std::string filename);\n\nvoid DumpFieldDataToFile(\n  Configurations configurations,\n  std::string filename,\n  std::vector<CoordinatePair> nodes,\n  std::vector<double> estimates);\n\nint\nmain(int arg_count, char** arg_values) {\n  Configurations configurations = ProcessCommandLineArguments(\n    arg_count,\n    arg_values\n  );\n\n  // setup (RNGs 'n' stuff)\n  std::default_random_engine random_generator(1);\n\n  // generate targets\n  std::vector<Target> targets;\n  targets.push_back({50.0, {0.0, 0.0}});\n\n  // generate node coordinates\n  std::vector<CoordinatePair> sensor_nodes;\n  CoordinatePair average_node_location = {0.0, 0.0};\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    sensor_nodes.push_back(\n      GenerateNewCoordinatePair(random_generator, configurations)\n    );\n\n    std::cout << \"x: \" << sensor_nodes[i].first << \" y: \" << sensor_nodes[i].second << std::endl;\n\n    average_node_location.first += sensor_nodes[i].first;\n      average_node_location.second += sensor_nodes[i].second;\n  }\n  average_node_location.first /= (double) configurations.number_of_sensor_nodes;\n  average_node_location.second /=\n    (double) configurations.number_of_sensor_nodes;\n\n  std::cout << \"x: \" << average_node_location.first << \" y: \" << average_node_location.second << std::endl;\n\n  // for each target\n  for (Target target : targets) {\n\n    Eigen::VectorXd estimates(configurations.number_of_sensor_nodes);\n    for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n      estimates(i) = GenerateNoisyReading(\n        target,\n        0.01,\n        sensor_nodes[i],\n        average_node_location,\n        configurations.sensing_range,\n        random_generator\n      );\n\n      std::cout << \"estimate: \" << estimates(i) << std::endl;\n    }\n\n    std::vector<Eigen::VectorXd> results = MaxDegreeAnalysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n    DumpResultsToFile(configurations, \"MaxDegreeResults.txt\", sensor_nodes, results);\n\n    results = MetropolisAnalysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n    DumpResultsToFile(configurations, \"MetropolisResults.txt\", sensor_nodes, results);\n\n    results = WeightDesign1Analysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n    DumpResultsToFile(configurations, \"WeightDesign1Results.txt\", sensor_nodes, results);\n\n    results = WeightDesign2Analysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n    DumpResultsToFile(configurations, \"WeightDesign2Results.txt\", sensor_nodes, results);\n  }\n\n  // part 2/////////////////////////////////////////////////////////////////////////////////\n  configurations.field_x_size = 12.0;\n  configurations.field_y_size = 12.0;\n  configurations.field_cells = 25;\n  configurations.number_of_sensor_nodes = 30;\n  configurations.sensing_range = 5.0;\n  configurations.communication_range = 4.5;\n\n\n  sensor_nodes.clear();\n  average_node_location = {0.0, 0.0};\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    sensor_nodes.push_back(\n      {0.0, 0.0}\n    );\n\n    std::cout << \"x: \" << sensor_nodes[i].first << \" y: \" << sensor_nodes[i].second << std::endl;\n\n    average_node_location.first += sensor_nodes[i].first;\n      average_node_location.second += sensor_nodes[i].second;\n  }\n  average_node_location.first /= (double) configurations.number_of_sensor_nodes;\n  average_node_location.second /=\n    (double) configurations.number_of_sensor_nodes;\n\n  std::cout << \"x: \" << average_node_location.first << \" y: \" << average_node_location.second << std::endl;\n\n  std::vector<double> final_cell_estimates_1;\n  std::vector<double> final_cell_estimates_2;\n\n  std::vector<Target> new_targets = ReadInData(configurations, \"field1.txt\");\n\n  // for each target\n  for (Target target : new_targets) {\n\n    Eigen::VectorXd estimates(configurations.number_of_sensor_nodes);\n    for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n      estimates(i) = GenerateNoisyReading(\n        target,\n        0.01,\n        sensor_nodes[i],\n        average_node_location,\n        configurations.sensing_range,\n        random_generator\n      );\n\n      std::cout << \"estimate: \" << estimates(i) << std::endl;\n    }\n\n    std::vector<Eigen::VectorXd> wd1_results = WeightDesign1Analysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n    std::vector<Eigen::VectorXd> wd2_results = WeightDesign2Analysis(\n      configurations,\n      target,\n      sensor_nodes,\n      average_node_location,\n      random_generator,\n      estimates\n    );\n\n    final_cell_estimates_1.push_back(wd1_results.back()(0));\n    final_cell_estimates_2.push_back(wd2_results.back()(0));\n  }\n\n  DumpFieldDataToFile(configurations, \"WeightDesign1_field.txt\", sensor_nodes, final_cell_estimates_1);\n  DumpFieldDataToFile(configurations, \"WeightDesign2_field.txt\", sensor_nodes, final_cell_estimates_2);\n\n  return 0;\n}\n\n\nConfigurations\nProcessCommandLineArguments(int pArgc, char** pArguments) {\n  Configurations configurations;\n\n  for (int i = 1; i < pArgc; ++i) {\n    char* arg_value_pair = pArguments[i];\n    std::string argument = strtok(arg_value_pair, \"-=\");\n    char* value = strtok(NULL, \"=\");\n\n    if (argument == DATA_FILE_ARG) {\n      configurations.data_file_name = value;\n      printf(\n        \"Data File: %s\\n\",\n        configurations.data_file_name.c_str()\n      );\n    } else if (argument == NUM_NODES_ARG) {\n      configurations.number_of_sensor_nodes = atoi(value);\n      printf(\n        \"Number of senor nodes: %i\\n\",\n        configurations.number_of_sensor_nodes\n      );\n    } else if (argument == SENSING_RANGE_ARG) {\n      configurations.sensing_range = strtod(value,NULL);\n      printf(\n        \"Node sensing range: %f\\n\",\n        configurations.sensing_range\n      );\n    } else if (argument == COMMUNICATION_RANGE_ARG) {\n      configurations.communication_range = strtod(value, NULL);\n      printf(\n        \"Node communication range: %f\\n\",\n        configurations.communication_range\n      );\n    } else if (argument == FIELD_X_ARG) {\n      configurations.field_x_size = strtod(value, NULL);\n      printf(\n        \"Field X size: %f\\n\",\n        configurations.field_x_size\n      );\n    } else if (argument == FIELD_Y_ARG) {\n      configurations.field_y_size = strtod(value, NULL);\n      printf(\n        \"Field Y size: %f\\n\",\n        configurations.field_y_size\n      );\n    } else if (argument == FIELD_CELLS_ARG) {\n      configurations.field_cells = atoi(value);\n      printf(\n        \"Cells per side of the field: %i\\n\",\n        configurations.field_cells\n      );\n    }else {\n      printf(\n        \"%s is an unrecognized argument. Program terminating.\\n\",\n        argument.c_str()\n      );\n      throw std::exception();\n    }\n  }\n\n  return configurations;\n}\n\n\nCoordinatePair\nGenerateNewCoordinatePair(\n  std::default_random_engine& random_generator,\n  const Configurations& configurations) {\n\n  CoordinatePair new_coordinates;\n\n  new_coordinates.first =\n    random_generator() % (int) (configurations.field_x_size * 5.0);\n  new_coordinates.first /= 10.0;\n  if (random_generator() % 2 == 0) {\n    new_coordinates.first *= -1.0;\n  }\n\n  new_coordinates.second =\n    random_generator() % (int) (configurations.field_y_size * 5.0);\n  new_coordinates.second /= 10.0;\n  if (random_generator() % 2 == 0) {\n    new_coordinates.second *= -1.0;\n  }\n\n  return new_coordinates;\n}\n\ndouble GenerateNoisyReading(\n  Target target,\n  double constant,\n  CoordinatePair sensor_node_location,\n  CoordinatePair average_sensor_location,\n  double sensing_range,\n  std::default_random_engine generator) {\n\n  double distance = ComputeDistance(sensor_node_location, target.location);\n\n  if (distance <= sensing_range) {\n    std::normal_distribution<double> noise_distribution(\n      target.value,\n      ComputeNoiseCovariance(\n        sensor_node_location,\n        average_sensor_location,\n        constant,\n        sensing_range\n      )\n    );\n\n    return noise_distribution(generator);\n  } else {\n    return NO_READING;\n  }\n}\n\ndouble ComputeDistance(\n  CoordinatePair node_location,\n  CoordinatePair reckoning_point) {\n\n  // Euclidean Distance = sqrt((x_0 - x_1)^2 + (y_0 - y_1)^2)\n\n  double x_diff = node_location.first - reckoning_point.first;\n  double y_diff = node_location.second - reckoning_point.second;\n\n  return sqrt((x_diff * x_diff) + (y_diff * y_diff));\n}\n\ndouble ComputeNoiseCovariance(\n  const CoordinatePair& node_coordinates,\n  const CoordinatePair& reckoning_point,\n  double constant,\n  double sensing_range) {\n\n  double distance = ComputeDistance(\n    node_coordinates,\n    reckoning_point\n  );\n\n  double numerator = (distance * distance) + constant;\n\n  return numerator / (sensing_range * sensing_range);\n}\n\ndouble ComputeAverageEstimate(\n  Eigen::VectorXd estimates,\n  Eigen::MatrixXd weights,\n  std::function<double(Eigen::VectorXd, Eigen::MatrixXd)> averaging_method) {\n\n  double sum = 0.0;\n  int n = 0;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      sum += estimates(i);\n      n++;\n    }\n  }\n\n  return sum / (double) n;\n}\n\ndouble ComputeMaxDegreeWeight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights) {\n\n  if (source_node_index != neighbor_index) {\n    if (source_node_measurement == NO_READING) {\n      return 0.0;\n    }\n\n\n    int num_neighbors = 0;\n    for (int i = 0; i < sensor_nodes.size(); ++i) {\n      if (i != source_node_index) {\n        double separation = ComputeDistance(\n          sensor_nodes[source_node_index],\n          sensor_nodes[neighbor_index]\n        );\n\n        if (separation <= communication_range) {\n          num_neighbors++;\n        }\n      }\n    }\n    \n    if (neighbor_measurement != NO_READING) {\n      double separation = ComputeDistance(\n        sensor_nodes[source_node_index],\n        sensor_nodes[neighbor_index]\n      );\n\n      if (separation <= communication_range) {\n        return 1.0 / (double) sensor_nodes.size();\n      } \n    }\n\n    return 0.0;\n  } else {\n    if (source_node_measurement == NO_READING) {\n      return 1.0;\n    } else {\n      double neighbor_weights = 0.0;\n\n      for (int j = 0; j < sensor_nodes.size(); ++j) {\n        if (j != source_node_index) {\n          neighbor_weights += weights(source_node_index, j);\n        }\n      }\n\n      return 1.0 - neighbor_weights;\n    }\n  }\n}\n\nbool EmptyEstimatePresent(Eigen::VectorXd estimates) {\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) == NO_READING) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nbool SomeNodeNotConverged(\n  Eigen::VectorXd estimates,\n  double average_estimate,\n  double error_threshold,\n  bool method) {\n\n  if (method) {\n    for (int i = 0; i < estimates.size(); ++i) {\n      if (estimates(i) != NO_READING &&\n          fabs(estimates(i) - average_estimate) >= error_threshold) {\n        return true;\n      }\n    }\n  } else {\n    double estimate = 0.0;\n    for (int i = 0; i < estimates.size(); ++i) {\n      if (estimate == 0.0 && estimates(i) != NO_READING) {\n        estimate = estimates(i);\n        break;\n      }\n    }\n\n    for (int i = 0; i < estimates.size(); ++i) {\n      if (estimates(i) != NO_READING && \n          (estimates(i) < (estimate - error_threshold) || (estimate + error_threshold) < estimates(i))) {\n        return true;\n      }\n    }\n  }\n\n  return false;\n}\n\n\nvoid DumpResultsToFile(\n  Configurations configurations,\n  std::string filename,\n  std::vector<CoordinatePair> nodes,\n  std::vector<Eigen::VectorXd> estimates) {\n\n  std::ofstream fout;\n  fout.open(filename.c_str());\n\n  for (CoordinatePair source : nodes) {\n    int num_neighbors = 0;\n    for (CoordinatePair neighbor : nodes) {\n      if (configurations.communication_range <\n          ComputeDistance(source, neighbor)) {\n        num_neighbors++;\n      }\n    }\n\n    fout << source.first << del << source.second << del << num_neighbors\n         << ln;\n  }\n\n  for (Eigen::VectorXd snapshot : estimates) {\n    fout << snapshot.transpose() << ln;\n  }\n\n  fout.close();\n}\n\n\nstd::vector<Eigen::VectorXd> MaxDegreeAnalysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates) {\n\n  // take initial measurements\n  Eigen::VectorXd estimates = initial_estimates;\n\n\n  // determine weight matrix\n  Eigen::MatrixXd weights(\n    configurations.number_of_sensor_nodes,\n    configurations.number_of_sensor_nodes\n  );\n  weights.setZero();\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    for (int j = 0; j < configurations.number_of_sensor_nodes; ++j) {\n      if (i != j) {\n        weights(i, j) = ComputeMaxDegreeWeight(\n          i,\n          estimates(i),\n          j,\n          estimates(j),\n          configurations.communication_range,\n          sensor_nodes,\n          weights\n        );\n      }\n    }\n\n    weights(i, i) = ComputeMaxDegreeWeight(i, estimates(i), i, estimates(i), configurations.communication_range, sensor_nodes, weights);\n  }\n\n  std::cout << \"Max-Degree weights\" << std::endl << weights << std::endl;\n\n  std::function<double(Eigen::VectorXd, Eigen::MatrixXd)> averaging_method;\n  double average_estimate = 0;\n  average_estimate = ComputeAverageEstimate(\n    estimates,\n    weights,\n    averaging_method\n  );\n\n  std::cout << \"average: \" << average_estimate << std::endl;\n\n  // iterate til consensus\n  std::vector<Eigen::VectorXd> estimate_history;\n  estimate_history.push_back(estimates);\n  int l = 0;\n  while (SomeNodeNotConverged(estimates, average_estimate, ERROR_THRESHOLD, true)) {\n    estimates = weights * estimates;\n    l++;\n    estimate_history.push_back(estimates);\n  }\n\n\n  // update nodes that didn't see the target\n  double consensus;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      consensus = estimates(i);\n      break;\n    }\n  }\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) == NO_READING) {\n      estimates(i) = consensus;\n    }\n  }\n  estimate_history.push_back(estimates);\n\n  return estimate_history; \n}\n\nstd::vector<Eigen::VectorXd> MetropolisAnalysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates) {\n\n  // take initial measurements\n  Eigen::VectorXd estimates = initial_estimates;\n\n  // determine weight matrix\n  Eigen::MatrixXd weights(\n    configurations.number_of_sensor_nodes,\n    configurations.number_of_sensor_nodes\n  );\n  weights.setZero();\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    for (int j = 0; j < configurations.number_of_sensor_nodes; ++j) {\n      if (i != j) {\n        weights(i, j) = ComputeMetropolisWeight(\n          i,\n          estimates(i),\n          j,\n          estimates(j),\n          configurations.communication_range,\n          sensor_nodes,\n          weights\n        );\n      }\n    }\n\n    weights(i, i) = ComputeMetropolisWeight(i, estimates(i), i, estimates(i), configurations.communication_range, sensor_nodes, weights);\n  }\n\n  std::cout << \"Metropolis Weights: \" << std::endl << weights << std::endl;\n\n  double average_estimate = 0.0;\n  int num_in_average = 0;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      average_estimate += estimates(i);\n      num_in_average++;\n    }\n  }\n  average_estimate /= (double) num_in_average;\n\n  std::cout << \"average: \" << average_estimate << std::endl;\n\n  // iterate til consensus\n  std::vector<Eigen::VectorXd> estimate_history;\n  estimate_history.push_back(estimates);\n  int l = 0;\n  while (SomeNodeNotConverged(estimates, average_estimate, ERROR_THRESHOLD, true)) {\n    estimates = weights * estimates;\n    l++;\n    estimate_history.push_back(estimates);\n  }\n\n  // update nodes that didn't see the target\n  double consensus;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      consensus = estimates(i);\n      break;\n    }\n  }\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) == NO_READING) {\n      estimates(i) = consensus;\n    }\n  }\n  estimate_history.push_back(estimates);\n\n  return estimate_history; \n}\n\n\nint CountNeighbors(\n  double communication_range,\n  CoordinatePair source,\n  std::vector<CoordinatePair> all_nodes) {\n\n  int num_neighbors = 0;\n\n  for (CoordinatePair node : all_nodes) {\n    if (node != source &&\n        ComputeDistance(source, node) <= communication_range) {\n\n      num_neighbors++;\n    }\n  }\n\n  return num_neighbors;\n}\n\n\ndouble ComputeMetropolisWeight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights) {\n\n  if (source_node_index != neighbor_index) {\n    if (source_node_measurement != NO_READING &&\n        neighbor_measurement != NO_READING &&\n        ComputeDistance(sensor_nodes[source_node_index], sensor_nodes[neighbor_index]) <= communication_range) {\n\n      return 1.0 / std::max(\n        CountNeighbors(\n          communication_range,\n          sensor_nodes[source_node_index],\n          sensor_nodes\n        ),\n        CountNeighbors(\n          communication_range,\n          sensor_nodes[neighbor_index],\n          sensor_nodes\n        )\n      );\n    }\n\n    return 0.0;\n  } else {\n    if (source_node_measurement == NO_READING) {\n      return 1.0;\n    } else {\n      double neighbor_weights = 0.0;\n\n      for (int j = 0; j < sensor_nodes.size(); ++j) {\n        if (j != source_node_index) {\n          neighbor_weights += weights(source_node_index, j);\n        }\n      }\n\n      return 1.0 - neighbor_weights;\n    }\n  }\n}\n\n\n\nstd::vector<Eigen::VectorXd> WeightDesign1Analysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates) {\n\n  // take initial measurements\n  Eigen::VectorXd estimates = initial_estimates;\n\n  // determine weight matrix\n  Eigen::MatrixXd weights(\n    configurations.number_of_sensor_nodes,\n    configurations.number_of_sensor_nodes\n  );\n  weights.setZero();\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    for (int j = 0; j < configurations.number_of_sensor_nodes; ++j) {\n      if (i != j) {\n        weights(i, j) = ComputeWeightDesign1Weight(\n          i,\n          estimates(i),\n          j,\n          estimates(j),\n          configurations.communication_range,\n          configurations.sensing_range,\n          target.location,\n          sensor_nodes,\n          weights\n        );\n      }\n    }\n\n    weights(i, i) = ComputeWeightDesign1Weight(i, estimates(i), i, estimates(i),\n      configurations.communication_range,\n      configurations.sensing_range,\n      target.location,\n      sensor_nodes,\n      weights\n    );\n  }\n\n  std::cout << \"Weight Design 1 Weights:\" << std::endl << weights << std::endl;\n\n  double average_estimate = 0.0;\n  double total_weight = 0.0;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      average_estimate += estimates(i) * weights(i, i);\n      total_weight += weights(i, i);\n    }\n  }\n  average_estimate /= total_weight;\n\n  std::cout << \"weighted average: \" << average_estimate << std::endl;\n\n  // iterate til consensus\n  std::vector<Eigen::VectorXd> estimate_history;\n  estimate_history.push_back(estimates);\n  int l = 0;\n  while (SomeNodeNotConverged(estimates, average_estimate, ERROR_THRESHOLD, false)) {\n    estimates = weights * estimates;\n    l++;\n    estimate_history.push_back(estimates);\n\n// char y;\n// std::cin >> y;\n// std::cout << estimates.transpose() << std::endl;\n  }\n\n  // update nodes that didn't see the target\n  double consensus;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      consensus = estimates(i);\n      break;\n    }\n  }\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) == NO_READING) {\n      estimates(i) = consensus;\n    }\n  }\n  estimate_history.push_back(estimates);\n\n  return estimate_history; \n}\n\n\ndouble ComputeWeightDesign1Weight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  double sensing_range,\n  CoordinatePair target_location,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights) {\n\n  if (source_node_index != neighbor_index) {\n    if (source_node_measurement != NO_READING &&\n        neighbor_measurement != NO_READING &&\n        ComputeDistance(sensor_nodes[source_node_index], sensor_nodes[neighbor_index]) <= communication_range) {\n\n\n      return C_W_CONSTANT /\n        (ComputeNoiseCovariance(\n          sensor_nodes[source_node_index],\n          target_location,\n          C_W_CONSTANT,\n          sensing_range\n        ) +\n        ComputeNoiseCovariance(\n          sensor_nodes[source_node_index],\n          target_location,\n          C_W_CONSTANT,\n          sensing_range\n        ))\n      ;\n    }\n\n    return 0.0;\n  } else {\n    if (source_node_measurement == NO_READING) {\n      return 1.0;\n    } else {\n      double neighbor_weights = 0.0;\n\n      for (int j = 0; j < sensor_nodes.size(); ++j) {\n        if (j != source_node_index) {\n          neighbor_weights += weights(source_node_index, j);\n        }\n      }\n\n      return 1.0 - neighbor_weights;\n    }\n  }\n}\n\n\nstd::vector<Eigen::VectorXd> WeightDesign2Analysis(\n  Configurations configurations,\n  Target target,\n  std::vector<CoordinatePair> sensor_nodes,\n  CoordinatePair average_node_location,\n  std::default_random_engine random_generator,\n  Eigen::VectorXd initial_estimates) {\n\n  // take initial measurements\n  Eigen::VectorXd estimates = initial_estimates;\n\n  // determine weight matrix\n  Eigen::MatrixXd weights(\n    configurations.number_of_sensor_nodes,\n    configurations.number_of_sensor_nodes\n  );\n  weights.setZero();\n  for (int i = 0; i < configurations.number_of_sensor_nodes; ++i) {\n    weights(i, i) = ComputeWeightDesign2Weight(i, estimates(i), i, estimates(i),\n      configurations.communication_range,\n      configurations.sensing_range,\n      target.location,\n      sensor_nodes,\n      weights,\n      estimates\n    );\n\n    for (int j = 0; j < configurations.number_of_sensor_nodes; ++j) {\n      if (i != j) {\n        weights(i, j) = ComputeWeightDesign2Weight(\n          i,\n          estimates(i),\n          j,\n          estimates(j),\n          configurations.communication_range,\n          configurations.sensing_range,\n          target.location,\n          sensor_nodes,\n          weights,\n          estimates\n        );\n      }\n    }\n  }\n\n  std::cout << \"Weight Design 2 Weights:\" << std::endl << weights << std::endl;\n\n  double average_estimate = 0.0;\n  double total_weight = 0.0;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      average_estimate += estimates(i) * weights(i, i);\n      total_weight += weights(i, i);\n    }\n  }\n  average_estimate /= total_weight;\n\n  std::cout << \"weighted average: \" << average_estimate << std::endl;\n\n  // iterate til consensus\n  std::vector<Eigen::VectorXd> estimate_history;\n  estimate_history.push_back(estimates);\n  int l = 0;\n  while (SomeNodeNotConverged(estimates, average_estimate, ERROR_THRESHOLD, false)) {\n    estimates = weights * estimates;\n    l++;\n    estimate_history.push_back(estimates);\n\n// char y;\n// std::cin >> y;\n// std::cout << estimates.transpose() << std::endl;\n  }\n\n  // update nodes that didn't see the target\n  double consensus;\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) != NO_READING) {\n      consensus = estimates(i);\n      break;\n    }\n  }\n  for (int i = 0; i < estimates.size(); ++i) {\n    if (estimates(i) == NO_READING) {\n      estimates(i) = consensus;\n    }\n  }\n  estimate_history.push_back(estimates);\n\n  return estimate_history; \n}\n\n\ndouble ComputeWeightDesign2Weight(\n  int source_node_index,\n  double source_node_measurement,\n  int neighbor_index,\n  double neighbor_measurement,\n  double communication_range,\n  double sensing_range,\n  CoordinatePair target_location,\n  const std::vector<CoordinatePair>& sensor_nodes,\n  const Eigen::MatrixXd weights,\n  Eigen::VectorXd estimates) {\n\n  if (source_node_index != neighbor_index) {\n    if (source_node_measurement != NO_READING &&\n        neighbor_measurement != NO_READING &&\n        ComputeDistance(sensor_nodes[source_node_index], sensor_nodes[neighbor_index]) <= communication_range) {\n\n        return (1.0 - weights(source_node_index, source_node_index)) /\n          (double) CountNeighborsWhoSenseTarget(communication_range, sensor_nodes[source_node_index], sensor_nodes, estimates);\n    }\n\n    return 0.0;\n  } else {\n    if (source_node_measurement == NO_READING) {\n      return 1.0;\n    } else {\n      return C_W_CONSTANT / ComputeNoiseCovariance(sensor_nodes[source_node_index], target_location, C_W_CONSTANT, sensing_range);\n    }\n  }\n}\n\n\nint CountNeighborsWhoSenseTarget(\n  double communication_range,\n  CoordinatePair source,\n  std::vector<CoordinatePair> all_nodes,\n  Eigen::VectorXd estimates) {\n\n  int num_neighbors = 0;\n\n  for (int i = 0; i < all_nodes.size(); ++i) {\n    CoordinatePair node = all_nodes[i];\n\n    if (node != source &&\n        ComputeDistance(source, node) <= communication_range &&\n        estimates(i) != NO_READING) {\n\n      num_neighbors++;\n    }\n  }\n\n  return num_neighbors;\n}\n\nstd::vector<Target> ReadInData(Configurations configurations, std::string filename) {\n\n  std::ifstream fin;\n  fin.open(filename.c_str());\n\n  std::vector<Target> targets;\n\n  char dummy;\n\n  double x;\n  double y;\n\n  double increment = 0.5;\n  double startval = -6.0;\n\n  y = startval;\n  for (int i = 0; i < configurations.field_cells; ++i) {\n    x = startval;\n    for (int j = 0; j < configurations.field_cells; ++j) {\n      Target target;\n      fin >> target.value >> dummy;\n      target.value *= 1;\n      target.location = {x, y};\n      targets.push_back(target);\n\nstd::cout << target.value << \", \";\n\n      x += increment;\n    }\n\nstd::cout << std::endl;\n\n    y += increment;\n  }\n\nchar c;\nstd::cin >> c;\n\n  fin.close();\n\n  return targets;\n}\n\nvoid DumpFieldDataToFile(\n  Configurations configurations,\n  std::string filename,\n  std::vector<CoordinatePair> nodes,\n  std::vector<double> estimates) {\n\n  std::ofstream fout;\n  fout.open(filename.c_str());\n\n  for (CoordinatePair source : nodes) {\n    int num_neighbors = 0;\n    for (CoordinatePair neighbor : nodes) {\n      if (configurations.communication_range <\n          ComputeDistance(source, neighbor)) {\n        num_neighbors++;\n      }\n    }\n\n    fout << source.first << \", \" << source.second << \", \" << num_neighbors\n         << ln;\n  }\n\n  for (int i = 0; i < configurations.field_cells; ++i) {\n    for (int j = 0; j < configurations.field_cells; ++j) {\n      fout << estimates[(i * configurations.field_cells) + j] << \", \";\n    }\n    fout << ln;\n  }\n\n  fout.close();\n}", "meta": {"hexsha": "d5eaa809640e9b6c206492de6e3b791cf185b314", "size": 32593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS791x_Fall14/Project02_ConsensusFilter/code/simple.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": "CS791x_Fall14/Project02_ConsensusFilter/code/simple.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": "CS791x_Fall14/Project02_ConsensusFilter/code/simple.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": 26.3910931174, "max_line_length": 137, "alphanum_fraction": 0.673887031, "num_tokens": 7695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.572615297195259}}
{"text": "#include \"KD.h\"\n#include \"Ray.h\"\n#include \"Material.h\"\n#include \"Triangle.h\"\n\n#include <algorithm>\n\n#include <Eigen/Dense>\n\nstd::vector<KdNode> kd_tree;\n\nbool AABB::intersects(const Ray& ray) const {\n    auto p = ray.p;\n    auto d = ray.d;\n\n    auto d_inv = Eigen::Vector3f(1.0f/d[0], 1.0f/d[1], 1.0f/d[2]);\n\n    float mins[3] = {min.x, min.y, min.z};\n    float maxs[3] = {max.x, max.y, max.z};\n\n    float t1 = (mins[0] - p[0]) * d_inv[0];\n    float t2 = (maxs[0] - p[0]) * d_inv[0];\n \n    float tmin = std::min(t1, t2);\n    float tmax = std::max(t1, t2);\n \n    for (int i = 1; i < 3; ++i) {\n        t1 = (mins[i] - p[i]) * d_inv[i];\n        t2 = (maxs[i] - p[i]) * d_inv[i];\n \n        tmin = std::max(tmin, std::min(std::min(t1, t2), tmax));\n        tmax = std::min(tmax, std::max(std::max(t1, t2), tmin));\n    }\n \n    return tmax > std::max(tmin, 0.0f);\n}\n\nbool kd_load(const char* fileName, std::vector<KdNode> &kdTree) {\n    FILE* fp = fopen(fileName, \"r+\");\n    if (!fp) {\n        fprintf(stderr, \"Could not load %s\\n\", fileName);\n        return false;\n    }\n    char temp[256];\n    int nodeId = -1;\n    while (true) {\n        *temp = '\\0';\n        nodeId++;\n        int ignore = fscanf(fp, \"%s{ \", temp);\n        if (!ignore) {\n            fprintf(stderr, \"Something catastrophic went wrong\\n\");\n            exit(EXIT_FAILURE);\n        }\n        if (strcmp(temp, \"inner{\") == 0) {\n            KdNode kd;\n            kd.nodeId = nodeId;\n            kd.isLeaf = false;\n            int ignore = fscanf(fp, \"%f %f %f %f %f %f ; %d %d %d %f }\", \n                                &kd.boundingBox.min.x, \n                                &kd.boundingBox.min.y, \n                                &kd.boundingBox.min.z, \n                                &kd.boundingBox.max.x, \n                                &kd.boundingBox.max.y, \n                                &kd.boundingBox.max.z, \n                                &kd.leftChildId, \n                                &kd.rightChildId, \n                                &kd.splitAxis, \n                                &kd.splitPosition);\n            if (!ignore) {\n                fprintf(stderr, \"Something catastrophic went wrong\\n\");\n                exit(EXIT_FAILURE);\n            }\n            kdTree.push_back(kd);\n        } else if (strcmp(temp, \"leaf{\") == 0) {\n            KdNode kd;\n            kd.nodeId = nodeId;\n            kd.isLeaf = true;\n            int ignore = fscanf(fp, \"%f %f %f %f %f %f ;\", \n                                &kd.boundingBox.min.x, \n                                &kd.boundingBox.min.y, \n                                &kd.boundingBox.min.z, \n                                &kd.boundingBox.max.x, \n                                &kd.boundingBox.max.y, \n                                &kd.boundingBox.max.z);\n            if (!ignore) {\n                fprintf(stderr, \"Something catastrophic went wrong\\n\");\n                exit(EXIT_FAILURE);\n            }\n            char token[256];\n            while (true) {\n                int ignore = fscanf(fp, \" %s\", token);\n                if (!ignore) {\n                    fprintf(stderr, \"Something catastrophic went wrong\\n\");\n                    exit(EXIT_FAILURE);\n                }\n                if (strcmp(token, \"}\") == 0)\n                    break;\n                int triIndex = atoi(token);\n                kd.triIndex.push_back(triIndex);\n            }\n            kdTree.push_back(kd);\n        } else {\n            break;\n        }\n    }\n    return true;\n}\n\nSurfaceList kd_intersect(const Ray& ray, const std::vector<KdNode>& kd_tree, int id, const Material& mt) {\n    auto node = kd_tree[id];\n    if (node.isLeaf) {\n        // Construct all leaf triangles\n        SurfaceList leaves;\n        for (int i : node.triIndex) {\n            int k0 = gTriangles[i].indices[0];\n            int k1 = gTriangles[i].indices[1];\n            int k2 = gTriangles[i].indices[2];\n\n            auto a = Eigen::Vector3f(gPositions[k0].x, gPositions[k0].y, gPositions[k0].z);\n            auto b = Eigen::Vector3f(gPositions[k1].x, gPositions[k1].y, gPositions[k1].z);\n            auto c = Eigen::Vector3f(gPositions[k2].x, gPositions[k2].y, gPositions[k2].z);\n\n            auto n = ((b-a).cross(c-a)).normalized();\n\n            auto triangle1 = std::unique_ptr<Triangle>(new Triangle(a,b,c,n,mt));\n            auto triangle2 = std::unique_ptr<Triangle>(new Triangle(c,b,a,-n,mt));\n\n            leaves.add(std::move(triangle1));\n            leaves.add(std::move(triangle2));\n        }\n        return leaves;\n    } else {\n        SurfaceList surfaces;\n\n        // Recurse on children whose bounding boxes intersect ray\n        auto left_node  = kd_tree[node.leftChildId];\n        auto right_node = kd_tree[node.rightChildId];\n        if (left_node.boundingBox.intersects(ray)) {\n            auto left_triangles = kd_intersect(ray, kd_tree, node.leftChildId, mt);\n            surfaces.add(left_triangles);\n        }\n        if (right_node.boundingBox.intersects(ray)) {\n            auto right_triangles = kd_intersect(ray, kd_tree, node.rightChildId, mt);\n            surfaces.add(right_triangles);\n        }\n\n        return surfaces;\n    }\n}\n", "meta": {"hexsha": "3339bbecaba57e7161d27e0221d18005ae28326c", "size": 5170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/KD.cpp", "max_stars_repo_name": "fmenozzi/raytracer", "max_stars_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T20:31:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T20:31:51.000Z", "max_issues_repo_path": "src/KD.cpp", "max_issues_repo_name": "fmenozzi/raytracer", "max_issues_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KD.cpp", "max_forks_repo_name": "fmenozzi/raytracer", "max_forks_repo_head_hexsha": "23a67c7a11bea5198b691ebb0ab7fd4bb3758097", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4666666667, "max_line_length": 106, "alphanum_fraction": 0.4794970986, "num_tokens": 1301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.5724400735308076}}
{"text": "#include \"filter.h\"\n#include \"../../modules/math/constants.h\"\n#include \"../../synthesis/synthesis.h\"\n#include <complex>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nusing namespace Eigen;\n\nVectorXcf poly(const VectorXcf& z) {\n    VectorXcf poly(z.size() + 1);\n    poly.setOnes();\n\n    poly(0) = 1.0;\n\n    for (int j = 0; j < z.size(); ++j) {\n        for (int i = j; i >= 0; --i) {\n            poly(i + 1) -= z(j) * poly(i);\n        }\n    }\n\n    return poly;\n}\n\nstd::vector<std::complex<double>> poly(const std::vector<std::complex<double>>& z) {\n    std::vector<std::complex<double>> poly(z.size() + 1, 1.0);\n\n    poly[0] = 1.0;\n\n    for (int j = 0; j < z.size(); ++j) {\n        for (int i = j; i >= 0; --i) {\n            poly[i + 1] -= z[j] * poly[i];\n        }\n    }\n\n    return poly;\n}\n\nstd::vector<std::array<double, 6>> Analysis::butterworthHighpass(int N, double fc, double fs)\n{\n    const double Wn = fc / (fs / 2.0);\n    const double Wo = tanf(Wn * M_PI / 2.0);\n\n    std::vector<std::complex<double>> p;\n\n    // Step 1. Get Butterworth analog lowpass prototype.\n    for (int i = 2 + N - 1; i <= 3 * N - 1; i += 2) {\n        p.push_back(std::polar<double>(1, (M_PI * i) / (2.0 * N)));\n    }\n\n    // Step 2. Transform to high pass filter.\n    std::complex<double> Sg = 1.0,\n                        prodSp = 1.0,\n                        prodSz = 1.0;\n\n    std::vector<std::complex<double>> Sp(p.size()), Sz(p.size());\n\n    for (int i = 0; i < p.size(); ++i) {\n        Sg *= -p[i];\n        Sp[i] = Wo / p[i];\n        Sz[i] = 0.0;\n        prodSp *= (1.0 - Sp[i]);\n        prodSz *= (1.0 - Sz[i]);\n    }\n    Sg = 1.0 / Sg;\n\n    // Step 3. Transform to digital filter.\n    std::vector<std::complex<double>> P(Sp.size()), Z(Sp.size());\n    \n    double G = std::real(Sg * prodSz / prodSp);\n\n    for (int i = 0; i < Sp.size(); ++i) {\n        P[i] = (1.0 + Sp[i]) / (1.0 - Sp[i]);\n        Z[i] = (1.0 + Sz[i]) / (1.0 - Sz[i]);\n    }\n    \n    // Step 6. Convert to SOS.\n    \n    return zpk2sos(Z, P, G);\n}\n\nstd::vector<std::array<double, 6>> Analysis::butterworthLowpass(int N, double fc, double fs)\n{\n    const double Wn = fc / (fs / 2.0);\n    const double Wo = tanf(Wn * M_PI / 2.0);\n\n    std::vector<std::complex<double>> p;\n\n    // Step 1. Get Butterworth analog lowpass prototype.\n    for (int i = 2 + N - 1; i <= 3 * N - 1; i += 2) {\n        p.push_back(std::polar<double>(1, (M_PI * i) / (2.0 * N)));\n    }\n\n    // Step 2. Transform to low pass filter.\n    std::complex<double> Sg = 1.0,\n                        prodSp = 1.0;\n\n    std::vector<std::complex<double>> Sp(p.size()), Sz(0);\n\n    for (int i = 0; i < p.size(); ++i) {\n        Sg *= Wo;\n        Sp[i] = Wo * p[i];\n        prodSp *= (1.0 - Sp[i]);\n    }\n\n    // Step 3. Transform to digital filter.\n    std::vector<std::complex<double>> P(Sp.size()), Z(Sp.size(), -1);\n   \n    double G = std::real(Sg / prodSp);\n\n    for (int i = 0; i < Sp.size(); ++i) {\n        P[i] = (1.0 + Sp[i]) / (1.0 - Sp[i]);\n    }\n    \n    // Step 6. Convert to SOS.\n    \n    return zpk2sos(Z, P, G);\n}\n\n", "meta": {"hexsha": "d9d80b704394e2ace0ad44bdd8e4aa2c8e1ad89b", "size": 3069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/filter/butterworth.cpp", "max_stars_repo_name": "dequis/in-formant", "max_stars_repo_head_hexsha": "129b9b399c75cdbd834b68f04dabcb1d406af250", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analysis/filter/butterworth.cpp", "max_issues_repo_name": "dequis/in-formant", "max_issues_repo_head_hexsha": "129b9b399c75cdbd834b68f04dabcb1d406af250", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analysis/filter/butterworth.cpp", "max_forks_repo_name": "dequis/in-formant", "max_forks_repo_head_hexsha": "129b9b399c75cdbd834b68f04dabcb1d406af250", "max_forks_repo_licenses": ["Apache-2.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.3636363636, "max_line_length": 93, "alphanum_fraction": 0.4881068752, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5724285623104025}}
{"text": "//\n//  Copyright (c) 2010 Athanasios Iliopoulos\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace boost::numeric::ublas;\n\nint main() {\n        // Simple vector fill\n    vector<double> a(3);\n    a <<= 0, 1, 2;\n    std::cout << a << std::endl;\n    // [ 0 1 2]\n\n    // Vector from vector\n    vector<double> b(7);\n    b <<= a, 10, a;\n    std::cout << b << std::endl;\n    // [ 0 1 2 10 0 1 2]\n\n    // Simple matrix fill\n    matrix<double> A(3,3);\n    A <<= 0, 1, 2,\n         3, 4, 5,\n         6, 7, 8;\n    std::cout << A << std::endl;\n    // [ 0 1 2 ]\n    // [ 3 4 5 ]\n    // [ 6 7 8 ]\n\n    // Matrix from vector\n    A <<= 0, 1, 2,\n         3, 4, 5,\n         a;\n    std::cout << A << std::endl;\n    // [ 0 1 2 ]\n    // [ 3 4 5 ]\n    // [ 0 1 2 ]\n\n    // Matrix from vector - column assignment\n    A <<= move(0,2), traverse_policy::by_column(),\n         a;\n    std::cout << A << std::endl;\n    // [ 0 1 0 ]\n    // [ 3 4 1 ]\n    // [ 0 1 2 ]\n\n    // Another matrix from vector example (watch the wraping);\n    vector<double> c(9); c <<= 1, 2, 3, 4, 5, 6, 7, 8, 9;\n    A <<= c;\n    std::cout << A << std::endl;\n    // [ 1 2 3 ]\n    // [ 4 5 6 ]\n    // [ 7 8 9 ]\n\n    // If for performance(Benchmarks are not definite about that) or consistency reasons you need to disable wraping:\n    static next_row_manip endr; //This can be defined globally\n    A <<= traverse_policy::by_row_no_wrap(),\n            1, 2, 3, endr,\n            4, 5, 6, endr,\n            7, 8, 9, endr;\n    // [ 1 2 3 ]\n    // [ 4 5 6 ]\n    // [ 7 8 9 ]\n    // If by default you need to disable wraping define\n    // BOOST_UBLAS_DEFAULT_NO_WRAP_POLICY, in the compilation options,\n    // so that you avoid typing the \"traverse_policy::by_row_no_wrap()\".\n\n    //  Plus and minus assign:\n    A <<= fill_policy::index_plus_assign(),\n         3,2,1;\n    std::cout << A << std::endl;\n    // [ 4 4 4 ]\n    // [ 4 5 6 ]\n    // [ 7 8 9 ]\n\n    // Matrix from proxy\n    A <<= 0, 1, 2,\n         project(b, range(3,6)),\n         a;\n    std::cout << A << std::endl;\n    // [ 0 1 2 ]\n    // [10 0 1 ]\n    // [ 6 7 8 ]\n\n    // Matrix from matrix\n    matrix<double> B(6,6);\n    B <<= A, A,\n         A, A;\n    std::cout << B << std::endl;\n    // [ A A ]\n    // [ A A ]\n\n    // Matrix range (vector is similar)\n    B = zero_matrix<double>(6,6);\n    matrix_range<matrix<double> > mrB (B, range (1, 4), range (1, 4));\n    mrB <<= 1,2,3,4,5,6,7,8,9;\n    std::cout << B << std::endl;\n    // [ 0 0 0 0 0 0]\n    // [ 0 1 2 3 0 0]\n    // [ 0 4 5 6 0 0]\n    // [ 0 0 0 0 0 0]\n    // [ 0 0 0 0 0 0]\n    // [ 0 0 0 0 0 0]\n\n    // Horizontal concatenation can be achieved using this trick:\n    matrix<double> BH(3,9);\n    BH <<= A, A, A;\n    std::cout << BH << std::endl;\n    // [ A A A]\n\n    // Vertical concatenation can be achieved using this trick:\n    matrix<double> BV(9,3);\n    BV <<= A,\n          A,\n          A;\n    std::cout << BV << std::endl;\n    // [ A ]\n    // [ A ]\n    // [ A ]\n\n    // Watch the difference when assigning matrices for different traverse policies:\n    matrix<double> BR(9,9, 0);\n    BR <<= traverse_policy::by_row(), // This is the default, so this might as well be omitted.\n          A, A, A;\n    std::cout << BR << std::endl;\n    // [ A A A]\n    // [ 0 0 0]\n    // [ 0 0 0]\n\n    matrix<double> BC(9,9, 0);\n    BC <<= traverse_policy::by_column(),\n          A, A, A;\n    std::cout << BC << std::endl;\n    // [ A 0 0]\n    // [ A 0 0]\n    // [ A 0 0]\n\n    // The following will throw a run-time exception in debug mode (matrix mid-assignment wrap is not allowed) :\n    // matrix<double> C(7,7);\n    // C <<= A, A, A;\n\n    // Matrix from matrix with index manipulators\n    matrix<double> C(6,6,0);\n    C <<= A, move(3,0), A;\n    // [ A 0 ]\n    // [ 0 A ]\n\n    // A faster way for to construct this dense matrix.\n    matrix<double> D(6,6);\n    D <<= A, zero_matrix<double>(3,3),\n         zero_matrix<double>(3,3), A;\n    // [ A 0 ]\n    // [ 0 A ]\n\n    // The next_row and next_column index manipulators:\n    // note: next_row and next_column functions return\n    // a next_row_manip and and next_column_manip object.\n    // This is the manipulator we used earlier when we disabled\n    // wrapping.\n    matrix<double> E(2,4,0);\n    E <<= 1, 2, next_row(),\n         3, 4, next_column(),5;\n    std::cout << E << std::endl;\n    // [ 1 2 0 5 ]\n    // [ 3 4 0 0 ]\n\n    // The begin1 (moves to the begining of the column) index manipulator, begin2 does the same for the row:\n    matrix<double> F(2,4,0);\n    F <<= 1, 2, next_row(),\n         3, 4, begin1(),5;\n    std::cout << F << std::endl;\n    // [ 1 2 5 0 ]\n    // [ 3 4 0 0 ]\n\n    // The move (relative) and move_to(absolute) index manipulators (probably the most useful manipulators):\n    matrix<double> G(2,4,0);\n    G <<= 1, 2, move(0,1), 3,\n         move_to(1,3), 4;\n    std::cout << G << std::endl;\n    // [ 1 2 0 3 ]\n    // [ 0 0 0 4 ]\n\n    // Static equivallents (faster) when sizes are known at compile time:\n    matrix<double> Gs(2,4,0);\n    Gs <<= 1, 2, move<0,1>(), 3,\n         move_to<1,3>(), 4;\n    std::cout << Gs << std::endl;\n    // [ 1 2 0 3 ]\n    // [ 0 0 0 4 ]\n\n    // Choice of traverse policy (default is \"row by row\" traverse):\n\n    matrix<double> H(2,4,0);\n    H <<= 1, 2, 3, 4,\n         5, 6, 7, 8;\n    std::cout << H << std::endl;\n    // [ 1 2 3 4 ]\n    // [ 5 6 7 8 ]\n\n    H <<= traverse_policy::by_column(),\n        1, 2, 3, 4,\n        5, 6, 7, 8;\n    std::cout << H << std::endl;\n    // [ 1 3 5 7 ]\n    // [ 2 4 6 8 ]\n\n    // traverse policy can be changed mid assignment if desired.\n     matrix<double> H1(4,4,0);\n     H1 <<= 1, 2, 3, traverse_policy::by_column(), 1, 2, 3;\n\n    std::cout << H << std::endl;\n    // [1 2 3 1]\n    // [0 0 0 2]\n    // [0 0 0 3]\n    // [0 0 0 0]\n\n    // note: fill_policy and traverse_policy are namespaces, so you can use them\n    // by a using statement.\n\n    // For compressed and coordinate matrix types a push_back or insert fill policy can be chosen for faster assginment:\n    compressed_matrix<double> I(2, 2);\n    I <<=    fill_policy::sparse_push_back(),\n            0, 1, 2, 3;\n    std::cout << I << std::endl;\n    // [ 0 1 ]\n    // [ 2 3 ]\n\n    coordinate_matrix<double> J(2,2);\n    J<<=fill_policy::sparse_insert(),\n        1, 2, 3, 4;\n    std::cout << J << std::endl;\n    // [ 1 2 ]\n    // [ 3 4 ]\n\n    // A sparse matrix from another matrix works as with other types.\n    coordinate_matrix<double> K(3,3);\n    K<<=fill_policy::sparse_insert(),\n        J;\n    std::cout << K << std::endl;\n    // [ 1 2 0 ]\n    // [ 3 4 0 ]\n    // [ 0 0 0 ]\n\n    // Be careful this will not work:\n    //compressed_matrix<double> J2(4,4);\n    //J2<<=fill_policy::sparse_push_back(),\n     //   J,J;\n    // That's because the second J2's elements\n    // are attempted to be assigned at positions\n    // that come before the elements already pushed.\n    // Unfortunatelly that's the only thing you can do in this case\n    // (or of course make a custom agorithm):\n    compressed_matrix<double> J2(4,4);\n    J2<<=fill_policy::sparse_push_back(),\n        J, fill_policy::sparse_insert(),\n        J;\n\n    std::cout << J2 << std::endl;\n    // [  J   J  ]\n    // [ 0 0 0 0 ]\n    // [ 0 0 0 0 ]\n\n    // A different traverse policy doesn't change the result, only they order it is been assigned.\n    coordinate_matrix<double> L(3,3);\n    L<<=fill_policy::sparse_insert(), traverse_policy::by_column(),\n        J;\n    std::cout << L << std::endl;\n    // (same as previous)\n    // [ 1 2 0 ]\n    // [ 3 4 0 ]\n    // [ 0 0 0 ]\n\n    typedef coordinate_matrix<double>::size_type cmst;\n    const cmst size = 30;\n    //typedef fill_policy::sparse_push_back spb;\n    // Although the above could have been used the following is may be faster if\n    //  you use the policy often and for relatively small containers.\n    static fill_policy::sparse_push_back spb;\n\n    // A block diagonal sparse using a loop:\n    compressed_matrix<double> M(size, size, 4*15);\n    for (cmst i=0; i!=size; i+=J.size1())\n        M <<= spb, move_to(i,i), J;\n\n\n    // If typedef was used above the last expression should start\n    // with M <<= spb()...\n\n    // Displaying so that blocks can be easily seen:\n    for (unsigned int i=0; i!=M.size1(); i++) {\n        std::cout << M(i,0);\n        for (unsigned int j=1; j!=M.size2(); j++) std::cout << \", \" << M(i,j);\n        std::cout << \"\\n\";\n    }\n    // [ J 0 0 0 ... 0]\n    // [ 0 J 0 0 ... 0]\n    // [ 0 . . . ... 0]\n    // [ 0 0 ... 0 0 J]\n\n\n    // A \"repeat\" trasverser may by provided so that this becomes faster and an on-liner like:\n    // M <<= spb, repeat(0, size, J.size1(), 0, size, J.size1()), J;\n    // An alternate would be to create a :repeater\" matrix and vector expression that can be used in other places as well. The latter is probably better,\n    return 0;\n}\n\n", "meta": {"hexsha": "bfad1f54ed477ed0057915e4d4c82505dabe3c82", "size": 9241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/ublas/doc/samples/assignment_examples.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "boost/libs/numeric/ublas/doc/samples/assignment_examples.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "boost/libs/numeric/ublas/doc/samples/assignment_examples.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": 28.878125, "max_line_length": 153, "alphanum_fraction": 0.5365220214, "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.5724188244122784}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <stdio.h>\n#include <math.h>\n#include <vector>\n#include <numeric>\n#include <strings.h>\n#include <assert.h>\n\n#include <dirent.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <fstream>\n#include <sstream> \nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\n\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > Polygon;\n\nnamespace py = pybind11;\nusing namespace std;\n\nstruct box{\n  float ry;\n  float l;\n  float w;\n  float h;\n  float x;\n  float z;\n  float y;\n  int cls_num;\n  float is_obj;\n  float wx0;\n  float wx1;\n  float wx2;\n  float wx3;\n  float wy0;\n  float wy1;\n  float wy2;\n  float wy3;\n  \n};\n\nvoid compute_4_points(vector<box> &boxes)\n{\n  for(int i=0;i<boxes.size();i++)\n  {\n    float ry = boxes[i].ry;\n    float x = boxes[i].x; \n    float z = boxes[i].z;\n    float l = boxes[i].l; \n    float w = boxes[i].w; \n    using namespace boost::numeric::ublas;\n    using namespace boost::geometry;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(ry); mref(0, 1) = sin(ry);\n    mref(1, 0) = -sin(ry); mref(1, 1) = cos(ry);\n\n    matrix<double> corners(2, 4);\n    double data[] = {l / 2, l / 2, -l / 2, -l / 2,\n                     w / 2, -w / 2, -w / 2, w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = prod(mref, corners);\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += x;\n        gc(1, i) += z;\n    }\n    boxes[i].wx0 = gc(0, 0); boxes[i].wy0=gc(1, 0);\n    boxes[i].wx1 = gc(0, 1); boxes[i].wy1=gc(1, 1);\n    boxes[i].wx2 = gc(0, 2); boxes[i].wy2=gc(1, 2);\n    boxes[i].wx3 = gc(0, 3); boxes[i].wy3=gc(1, 3);\n  }\n\n}\n\nPolygon toPolygon_py(double ry,double l,double w,double x,double z) \n{\n    using namespace boost::numeric::ublas;\n    using namespace boost::geometry;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(ry); mref(0, 1) = sin(ry);\n    mref(1, 0) = -sin(ry); mref(1, 1) = cos(ry);\n\n    static int count = 0;\n    matrix<double> corners(2, 4);\n    double data[] = {l / 2, l / 2, -l / 2, -l / 2,\n                     w / 2, -w / 2, -w / 2, w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = prod(mref, corners);\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += x;\n        gc(1, i) += z;\n    }\n\n    double points[][2] = {{gc(0, 0), gc(1, 0)},{gc(0, 1), gc(1, 1)},{gc(0, 2), gc(1, 2)},{gc(0, 3), gc(1, 3)},{gc(0, 0), gc(1, 0)}};\n    Polygon poly;\n    append(poly, points);\n    return poly;\n}\ndouble groundBoxOverlap_py(double ry1,double l1,double w1,double x1,double z1,\\\n  double ry2,double l2,double w2,double x2,double z2, int criterion = -1)\n{\n  using namespace boost::geometry;\n  Polygon gp = toPolygon_py(ry1,l1,w1,x1,z1);\n  Polygon dp = toPolygon_py(ry2,l2,w2,x2,z2);\n\n  std::vector<Polygon> in, un;\n  intersection(gp, dp, in);\n  union_(gp, dp, un);\n\n  double inter_area = in.empty() ? 0 : area(in.front());\n  double union_area = area(un.front());\n  double o;\n  if(criterion==-1)     // union\n      o = inter_area / union_area;\n  else if(criterion==0) // bbox_a\n      o = inter_area / area(dp);\n  else if(criterion==1) // bbox_b\n      o = inter_area / area(gp);\n\n  return o;\n}\n\n\nPolygon toPolygon(box a) \n{\n    using namespace boost::numeric::ublas;\n    using namespace boost::geometry;\n    matrix<double> mref(2, 2);\n    mref(0, 0) = cos(a.ry); mref(0, 1) = sin(a.ry);\n    mref(1, 0) = -sin(a.ry); mref(1, 1) = cos(a.ry);\n\n    static int count = 0;\n    matrix<double> corners(2, 4);\n    double data[] = {a.l / 2, a.l / 2, -a.l / 2, -a.l / 2,\n                     a.w / 2, -a.w / 2, -a.w / 2, a.w / 2};\n    std::copy(data, data + 8, corners.data().begin());\n    matrix<double> gc = prod(mref, corners);\n    for (int i = 0; i < 4; ++i) {\n        gc(0, i) += a.x;\n        gc(1, i) += a.z;\n    }\n\n    double points[][2] = {{gc(0, 0), gc(1, 0)},{gc(0, 1), gc(1, 1)},{gc(0, 2), gc(1, 2)},{gc(0, 3), gc(1, 3)},{gc(0, 0), gc(1, 0)}};\n    Polygon poly;\n    append(poly, points);\n    return poly;\n}\n\n\nfloat compute_iou_ground(box a,box b, int criterion = -1)\n{\n  using namespace boost::geometry;\n  Polygon gp = toPolygon(a);\n  Polygon dp = toPolygon(b);\n\n  std::vector<Polygon> in, un;\n  intersection(gp, dp, in);\n  union_(gp, dp, un);\n\n  double inter_area = in.empty() ? 0 : area(in.front());\n  double union_area = area(un.front());\n  double o;\n  if(criterion==-1)     // union\n      o = inter_area / union_area;\n  else if(criterion==0) // bbox_a\n      o = inter_area / area(dp);\n  else if(criterion==1) // bbox_b\n      o = inter_area / area(gp);\n\n  return o;\n}\n\n\nfloat compute_iou_rect(box rectA,box rectB)\n{\n  float xa1 = max(max(max(rectA.wx0,rectA.wx1),rectA.wx2),rectA.wx3);\n  float xa0 = min(min(min(rectA.wx0,rectA.wx1),rectA.wx2),rectA.wx3);\n  float ya1 = max(max(max(rectA.wy0,rectA.wy1),rectA.wy2),rectA.wy3);\n  float ya0 = min(min(min(rectA.wy0,rectA.wy1),rectA.wy2),rectA.wy3);\n\n  float xb1 = max(max(max(rectB.wx0,rectB.wx1),rectB.wx2),rectB.wx3);\n  float xb0 = min(min(min(rectB.wx0,rectB.wx1),rectB.wx2),rectB.wx3);\n  float yb1 = max(max(max(rectB.wy0,rectB.wy1),rectB.wy2),rectB.wy3);\n  float yb0 = min(min(min(rectB.wy0,rectB.wy1),rectB.wy2),rectB.wy3);\n\n  if (xa0 > xb1) { return 0.; }\n\tif (ya0 > yb1) { return 0.; }\n\tif ((xa1) < xb0) { return 0.; }\n\tif ((ya1) < yb0) { return 0.; }\n\tfloat colInt = min(xa1, xb1) - max(xa0, xb0);\n\tfloat rowInt = min(ya1, yb1) - max(ya0, yb0);\n\tfloat intersection = colInt * rowInt;\n\tfloat areaA = (xa1-xa0) * (ya1-ya0);\n\tfloat areaB = (xb1-xb0) * (yb1-yb0);\n\tfloat intersectionPercent = intersection / (areaA + areaB - intersection);\n\treturn intersectionPercent;\n}\n\n\nfloat sigmoid(float x)\n{\n  float s = 1.0 / (1.0 + exp(-x));\n  return s;\n}\n\nvoid nms2(\n        const std::vector<box>& srcRects,\n        const std::vector<float>& scores,\n        std::vector<box>& resRects,\n        float thresh,\n        int neighbors = 0,\n        float minScoresSum = 0.f\n        )\n{\n    resRects.clear();\n\n    const size_t size = srcRects.size();\n    if (!size)\n    {\n        return;\n    }\n\n    assert(srcRects.size() == scores.size());\n\n    std::multimap<float, size_t> idxs;\n    for (size_t i = 0; i < size; ++i)\n    {\n        idxs.insert(std::pair<float, size_t>(scores[i], i));\n    }\n\n    while (idxs.size() > 0)\n    {\n        auto lastElem = --std::end(idxs);\n        box rect1 = srcRects[lastElem->second];\n\n        int neigborsCount = 0;\n        float score = lastElem->first;\n        float scoresSum = lastElem->first;\n\n        idxs.erase(lastElem);\n\n        for (auto pos = std::begin(idxs); pos != std::end(idxs); )\n        { \n            box rect2 = srcRects[pos->second];\n            float distance2 = (rect1.x-rect2.x)*(rect1.x-rect2.x)\\\n              +(rect1.z-rect2.z)*(rect1.z-rect2.z);\n            if(distance2>15*15)\n            {\n              ++pos;\n              continue;\n            }\n            \n            float overlap=0;\n            if((abs(rect1.ry)<70.0*3.14158/180 && abs(rect1.ry)>20.0*3.14158/180) || \\\n              (abs(rect2.ry)<70.0*3.14158/180 && abs(rect2.ry)>20.0*3.14158/180))\n            {\n              overlap  = compute_iou_ground(rect1,rect2);\n            }\n            {\n              overlap  = compute_iou_rect(rect1,rect2);\n            }\n            if (overlap > thresh)\n            {\n                scoresSum += pos->first;\n                pos = idxs.erase(pos);\n                ++neigborsCount;\n            }\n            else\n            {\n                ++pos;\n            }\n        }\n        if (neigborsCount >= neighbors &&\n                scoresSum >= minScoresSum)\n        {\n            resRects.push_back(rect1);\n        }\n    }\n}\n\npy::array_t<float> cal_result(py::array_t<float> &feature_out,\\\n  float obj_th,float OVERLAP,float Z_MIN, int img_height,int img_width,float DX,float DY,float DZ,\\\n  float nms_th)\n{\n\n  auto feature_map = feature_out.unchecked<3>();\n\n  int feature_height = img_height/8+0.5;\n  int feature_width = img_width/8+0.5;\n  int grid_height = img_height/feature_height+0.5;\n  int grid_width = img_width/feature_width+0.5;\n\n  std::vector<box> objs;\n  std::vector<float> scores;\n  objs.clear();\n  scores.clear();\n\n  float cut_dis = OVERLAP-Z_MIN;\n\n  for(int height_i=0;height_i<feature_height;height_i++)\n  {\n    for(int width_i=0;width_i<feature_width;width_i++)\n    {\n      float is_obj = sigmoid(feature_map(height_i,width_i,0));\n      \n      float reg_dy = feature_map(height_i,width_i,13);\n      reg_dy = reg_dy*grid_height;\n      float center_y = height_i*grid_height+reg_dy;\n      float m_y = (center_y*DY);\n      float reg_dx = feature_map(height_i,width_i,11);\n      reg_dx = reg_dx*grid_width;\n      float center_x = width_i*grid_width+reg_dx;\n      float m_x = (center_x-img_width/2)*DX;\n      float sin_theta = feature_map(height_i,width_i,7);\n      float cos_theta = feature_map(height_i,width_i,9);\n      float theta = atan2(sin_theta,cos_theta)/2;\n      float reg_ln_l = feature_map(height_i,width_i,17);\n      float reg_l = exp(reg_ln_l);\n      float reg_ln_h = feature_map(height_i,width_i,21);\n      float reg_h = exp(reg_ln_h);\n      if(m_y>cut_dis)\n      {\n        m_y=m_y-cut_dis-OVERLAP;\n        if(m_y-reg_l/2<-10)\n          is_obj*=0.2;\n      }\n      else\n      {\n        m_x*=-1;\n        m_y=-1*(m_y-OVERLAP);\n        if(m_y+reg_l/2>10)\n          is_obj*=0.2;\n      }\n\n      if(m_y>100 && abs(theta)<45*3.14158/180)\n      {\n        is_obj*=0.2;\n      }\n\n      float m_obj_th = obj_th;\n      if(m_y>100)\n        m_obj_th=obj_th*0.5;\n      if(m_y>150)\n        m_obj_th=obj_th*0.4;\n      if(m_y>180)\n        m_obj_th=obj_th*0.3;\n\n      if(is_obj>m_obj_th)\n      {\n        int cls_num=0;\n        float is_cls0=feature_map(height_i,width_i,2);\n        float is_cls1=feature_map(height_i,width_i,3);\n        float is_cls2=feature_map(height_i,width_i,4);\n        float reg_ln_w = feature_map(height_i,width_i,15);\n        float reg_w = exp(reg_ln_w);\n        float m_z = feature_map(height_i,width_i,19);   \n        if(is_cls0>is_cls1 && is_cls0>is_cls2)\n        {\n          cls_num = 0;\n        }\n        else if(is_cls1>is_cls0 && is_cls1>is_cls2)\n        {\n          cls_num = 1;\n          if (is_obj<0.88 && m_y<100 && abs(m_x)<40 && abs(m_x)>5 && m_y>10)\n            continue;\n        }\n        else\n        {\n          cls_num = 2;\n          if (is_obj<0.88 && m_y<100 && abs(m_x)<40 && abs(m_x)>5 && m_y>10)\n            continue;\n        }\n        box one_obj;\n        one_obj.ry = theta;\n        one_obj.l = reg_l;\n        one_obj.w = reg_w;\n        one_obj.x = m_x;\n        one_obj.z = m_y;\n        one_obj.cls_num=cls_num;\n        one_obj.is_obj=is_obj;\n        one_obj.h = reg_h;\n        one_obj.y = m_z;\n        objs.push_back(one_obj);\n\n        scores.push_back(is_obj);\n\n      }\n\n      is_obj= sigmoid(feature_map(height_i,width_i,1));\n      if(is_obj>obj_th)\n      {\n        int cls_num=0;\n        float is_cls3=feature_map(height_i,width_i,5);\n        float is_cls4=feature_map(height_i,width_i,6);\n        if(is_cls3>is_cls4)\n        {\n          cls_num = 3;\n        }\n        else\n        {\n          cls_num = 4;\n        }\n        \n        float sin_theta = feature_map(height_i,width_i,8);\n        float cos_theta = feature_map(height_i,width_i,10);\n        float reg_dx = feature_map(height_i,width_i,12);\n        float reg_dy = feature_map(height_i,width_i,14);\n        float reg_ln_w = feature_map(height_i,width_i,16);\n        float reg_ln_l = feature_map(height_i,width_i,18);\n        float m_z = feature_map(height_i,width_i,20);\n        float reg_ln_h = feature_map(height_i,width_i,22);\n        float theta = atan2(sin_theta,cos_theta)/2;\n        reg_dx = reg_dx*grid_width;\n        reg_dy = reg_dy*grid_height;\n        float center_x = width_i*grid_width+reg_dx;\n        float center_y = height_i*grid_height+reg_dy;\n        float m_x = (center_x-img_width/2)*DX;\n        float m_y = (center_y*DY);\n        float reg_w = exp(reg_ln_w);\n        float reg_l = exp(reg_ln_l);\n        float reg_h = exp(reg_ln_h);\n\n        if(m_y>cut_dis)\n        {\n          m_y=m_y-cut_dis-OVERLAP;\n        }\n        else\n        {\n          m_x*=-1;\n          m_y=-1*(m_y-OVERLAP);\n        }\n   \n\n        box one_obj;\n        one_obj.ry = theta;\n        one_obj.l = reg_l;\n        one_obj.w = reg_w;\n        one_obj.x = m_x;\n        one_obj.z = m_y;\n        one_obj.cls_num=cls_num;\n        one_obj.is_obj=is_obj;\n        one_obj.h = reg_h;\n        one_obj.y = m_z;\n        objs.push_back(one_obj);\n\n        scores.push_back(is_obj);\n\n      }\n    }\n  }\n\n  std::vector<box> results;\n  compute_4_points(objs);\n  nms2(objs,scores,results,nms_th);\n\n  int obj_num = results.size();\n\n  auto result = py::array_t<float>(obj_num*9);\n  result.resize({obj_num,9});\n  py::buffer_info buf_result = result.request();\n  float* ptr_result = (float*)buf_result.ptr;\n\n  for(int i=0;i<obj_num;i++)\n  {\n    ptr_result[i*9 + 0] = results[i].is_obj;\n    ptr_result[i*9 + 1] = results[i].cls_num;\n    ptr_result[i*9 + 2] = results[i].ry;\n    ptr_result[i*9 + 3] = results[i].l;\n    ptr_result[i*9 + 4] = results[i].w;\n    ptr_result[i*9 + 5] = results[i].x;\n    ptr_result[i*9 + 6] = results[i].z;\n    ptr_result[i*9 + 7] = results[i].h;\n    ptr_result[i*9 + 8] = results[i].y;\n  }\n\n  return result;\n}\n\nPYBIND11_MODULE(lib_cpp, m) \n{\n    m.def(\"cal_result\", &cal_result);\n}\n\n\n\n\nint32_t main() {\n\n\n  return 0;\n}\n\n", "meta": {"hexsha": "8e91713af8864b0c2b42ce14d8ffd9b46daae2b7", "size": 13633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "livox_detection-master/utils/lib_cpp/lib_cpp.cpp", "max_stars_repo_name": "cs481-ekh/f21-na", "max_stars_repo_head_hexsha": "cf9717fcce353d39db4b3a250e60a501cbeab808", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "livox_detection-master/utils/lib_cpp/lib_cpp.cpp", "max_issues_repo_name": "cs481-ekh/f21-na", "max_issues_repo_head_hexsha": "cf9717fcce353d39db4b3a250e60a501cbeab808", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "livox_detection-master/utils/lib_cpp/lib_cpp.cpp", "max_forks_repo_name": "cs481-ekh/f21-na", "max_forks_repo_head_hexsha": "cf9717fcce353d39db4b3a250e60a501cbeab808", "max_forks_repo_licenses": ["Apache-2.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.1573705179, "max_line_length": 132, "alphanum_fraction": 0.5686202597, "num_tokens": 4412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5722244730078133}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// CollapsePreventionEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Sheet material energy density that prevents elements from collapsing into\n//  degenerate configurations (which will break the bending energy...) with\n//  an infinite energy barrier:\n//      (-log((det(C) - activationThreshold) / activationThreshold + 1))^2\n//  for det(C) < activationThreshold, 0 otherwise\n//\n//  This energy term is C1. We could make it C2 (to avoid the single point\n//  where the Hessian is undefined) by raising the power from 2 to 3--at the\n//  expense of a faster ramp-up (greater nonlinearity).\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  05/30/2019 17:23:18\n////////////////////////////////////////////////////////////////////////////////\n#ifndef COLLAPSEPREVENTIONENERGY_HH\n#define COLLAPSEPREVENTIONENERGY_HH\n#include <cmath>\n\n#include <Eigen/Dense>\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n#include \"SVDSensitivity.hh\"\n#include \"InflatableSheet.hh\"\n\nstruct BarrierFuncLogSq {\n    using Real = InflatableSheet::Real;\n\n    constexpr static Real inf = std::numeric_limits<double>::infinity();\n\n    static Real   b(Real x) { if (x <= 0) return inf; if (x >= 1.0) return 0.0; return 0.5 * std::pow(log(x), 2); }\n    static Real  db(Real x) { if (x <= 0) return inf; if (x >= 1.0) return 0.0; return log(x) / x; }\n    static Real d2b(Real x) { if (x <= 0) return inf; if (x >= 1.0) return 0.0; return (1 - log(x)) / (x * x); }\n};\n\ntemplate<class BarrierFunc>\nstruct NormalizedBarrierFunction {\n    using Real = typename BarrierFunc::Real;\n    using BF = BarrierFunc;\n\n    void setActivationThreshold(Real val) { m_a = val; }\n    Real activationThreshold() const { return m_a; }\n\n    Real   b(Real x) const { return BF::  b(x / m_a); }\n    Real  db(Real x) const { return BF:: db(x / m_a) / m_a; }\n    Real d2b(Real x) const { return BF::d2b(x / m_a) / (m_a * m_a); }\n\nprotected:\n    Real m_a = 1.0;\n};\n\ntemplate<class BarrierFunc>\nstruct CollapsePreventionDet : public NormalizedBarrierFunction<BarrierFunc> {\n    using BF = NormalizedBarrierFunction<BarrierFunc>;\n    using M2d  = InflatableSheet::M2d;\n    using Real = InflatableSheet::Real;\n\n    template<typename Derived>\n    void setMatrix(const Eigen::MatrixBase<Derived> &C) {\n        static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n        m_det = C.determinant();\n        m_grad_det <<  C(1, 1), -C(1, 0),\n                      -C(0, 1),  C(0, 0);\n    }\n\n    Real energy() const { return BF::b(m_det); }\n    M2d denergy() const { return BF::db(m_det) * m_grad_det; }\n\n    template<typename Derived>\n    M2d delta_denergy(const Eigen::MatrixBase<Derived> &dC) const {\n        static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n\n        M2d delta_grad_det;\n        delta_grad_det <<  dC(1, 1), -dC(1, 0),\n                          -dC(0, 1),  dC(0, 0);\n\n        return ((BF::d2b(m_det) * doubleContract(m_grad_det, dC.template cast<Real>()))) * m_grad_det\n               + BF:: db(m_det) * delta_grad_det;\n    }\n\n    // For debugging scalar function of det + its derivatives\n    void setDet(Real det) { m_det = det; }\n    Real det() const { return m_det; }\n    Real normalizedDet()  const { return m_det / BF::m_a; }\n    Real denergy_ddet()   const { return BF::db(m_det);  }\n    Real d2energy_d2det() const { return BF::d2b(m_det); }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    Real m_det;\n    M2d m_grad_det;\n};\n\ntemplate<class BarrierFunc>\nstruct CollapsePreventionSingularValues : public NormalizedBarrierFunction<BarrierFunc> {\n    using BFRaw = BarrierFunc;\n    using BF    = NormalizedBarrierFunction<BarrierFunc>;\n    using V2d   = InflatableSheet::V2d;\n    using M2d   = InflatableSheet::M2d;\n    using Real  = InflatableSheet::Real;\n\n    // The activation threshold for the singular value barriers should be the\n    // square root of the area barrier activation threshold.\n    void setActivationThreshold(Real val) { BF::setActivationThreshold(std::sqrt(val)); }\n    Real activationThreshold() const { return std::pow(BF::activationThreshold(), 2); }\n\n    template<typename Derived>\n    void setMatrix(const Eigen::MatrixBase<Derived> &F) { m_svd.setMatrix(F); m_det = F.determinant(); }\n\n    Real energy() const {\n        if (m_det < 0.0) return std::numeric_limits<double>::infinity();\n        Real result = BF::b(m_svd.sigma(0)) + BF::b(m_svd.sigma(1));\n        if (applyStretchBarrier) {\n            Real scale = 1.0 / (stretchBarrierLimit - stretchBarrierActivation);\n            result += BFRaw::b(scale * (stretchBarrierLimit - m_svd.sigma(0)))\n                   +  BFRaw::b(scale * (stretchBarrierLimit - m_svd.sigma(1)));\n        }\n        return result;\n    }\n\n    M2d denergy() const {\n        if (m_det < 0.0) {\n            M2d result;\n            result.setConstant(std::numeric_limits<double>::infinity());\n        }\n        V2d dE_dsigma(BF::db(m_svd.sigma(0)),\n                      BF::db(m_svd.sigma(1)));\n        if (applyStretchBarrier) {\n            Real scale = 1.0 / (stretchBarrierLimit - stretchBarrierActivation);\n            dE_dsigma -= scale * V2d(BFRaw::db(scale * (stretchBarrierLimit - m_svd.sigma(0))),\n                                     BFRaw::db(scale * (stretchBarrierLimit - m_svd.sigma(1))));\n        }\n\n        return m_svd.U() * (dE_dsigma.asDiagonal() * m_svd.V().transpose());\n    }\n\n    const SVDSensitivity &svd() const { return m_svd; }\n    Real det() const { return m_det; }\n\n    // Second derivatives blow up when sigma_0 == sigma_1!!!\n    template<typename Derived>\n    M2d delta_denergy(const Eigen::MatrixBase<Derived> &/* dF */) const {\n        static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n        throw std::runtime_error(\"Second derivative of SVD collapse prevention unsupported; will blow up at sigma_0 == sigma_2.\");\n    #if 0\n        // SVDSensitivity doesn't yet implement delta_dsigma...\n        return (BF::d2b(m_svd.sigma(0)) * m_svd.dsigma(0, dF)) * m_svd.dsigma(0) +\n               (BF::d2b(m_svd.sigma(1)) * m_svd.dsigma(1, dF)) * m_svd.dsigma(1) +\n                BF:: db(m_svd.sigma(0)) * m_svd.delta_dsigma(0, dF) +\n                BF:: db(m_svd.sigma(1)) * m_svd.delta_dsigma(1, dF);\n    #endif\n    }\n\n    bool applyStretchBarrier = false;\n    Real stretchBarrierActivation = 1.75; // threshold below which barrier term is smoothly deactivated\n    Real stretchBarrierLimit      = 2.25; // placement of the infinite barrier\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    SVDSensitivity m_svd;\n    Real m_det;\n};\n\nusing CollapsePreventionEnergyDet = CollapsePreventionDet<BarrierFuncLogSq>;\nusing CollapsePreventionEnergySV  = CollapsePreventionSingularValues<BarrierFuncLogSq>;\n\n#endif /* end of include guard: COLLAPSEPREVENTIONENERGY_HH */\n", "meta": {"hexsha": "c46bbfd0dc2d4b9eb2ae4a59061a45a0678d2a8d", "size": 7064, "ext": "hh", "lang": "C++", "max_stars_repo_path": "CollapsePreventionEnergy.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": "CollapsePreventionEnergy.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": "CollapsePreventionEnergy.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": 41.798816568, "max_line_length": 130, "alphanum_fraction": 0.6275481314, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5722093813881184}}
{"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-2015 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\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/norms.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"   // ContinuousHierarchicMapper\n#include \"linalg/direct.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n//#include \"linalg/partialDirectPreconditioner.hh\"\n#include \"linalg/additiveschwarz.hh\"\n#include \"linalg/iluprecond.hh\"      // PrecondType::ILUT, PrecondType::ILUK, PrecondType::ARMS\n#include \"linalg/iccprecond.hh\"\n#include \"linalg/icc0precond.hh\"\n#include \"linalg/hyprecond.hh\"       // BoomerAMG, Euclid\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/cg.hh\"\n#include \"mg/hb.hh\"\n#include \"utilities/enums.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare, createUnitCube\n#include \"io/vtk.hh\"\n#include \"io/gnuplot.hh\"\n//#include \"io/amira.hh\"\n#include \"utilities/kaskopt.hh\"\n\nusing namespace Kaskade;\n#include \"ht.hh\"\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n  std::cout << \"Start heat transfer tutorial program\" << 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\", 5),\n       order       =  getParameter(pt, \"order\", 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 << \"output level (verbosity)       : \" << verbosity << std::endl;\n\n  int  direct, onlyLowerTriangle = false;\n    \n  DirectType directType;\n//  IterateType iterateType = IterateType::CG;\n  MatrixProperties property = MatrixProperties::SYMMETRIC;\n  PrecondType precondType = PrecondType::NONE;\n  std::string empty;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  direct = getParameter(pt, s, 0);\n    \n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  directType = static_cast<DirectType>(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  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 PrecondType::ICC preconditioner ===> onlyLowerTriangle is set to true!\" \n      << std::endl;\n  }\n\n  boost::timer::cpu_timer gridTimer;\n//   two-dimensional space: dim=2\n  constexpr int dim=2;        \n  using Grid = Dune::UGGrid<dim>;\n  using LeafView = Grid::LeafGridView;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;\n  // using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<double,LeafView> >;\n  using Spaces = boost::fusion::vector<H1Space const*>;\n  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using Functional = HeatFunctional<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 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  std::cout << \"computing time for generation of initial mesh: \" << (double)(gridTimer.elapsed().user)/1e9 << \"s\\n\";\n\n  \n  // construction of finite element space for the scalar solution T.\n  H1Space temperatureSpace(gridManager,gridManager.grid().leafGridView(),order);\n    \n  Spaces spaces(&temperatureSpace);\n    \n  // construct variable list.\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        \n  std::string varNames[1] = { \"u\" };\n    \n  VariableSet variableSet(spaces,varNames);\n\n  // construct variational functional\n    \n  double kappa = 1.0;\n  double q = 1.0;\n  Functional F(kappa,q);\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  std::cout << std::endl << \"no of variables = \" << nvars << std::endl;\n  std::cout << \"no of equations = \" << neq   << std::endl;\n  size_t dofs = variableSet.degreesOfFreedom(0,nvars);\n  std::cout << \"number of degrees of freedom = \" << dofs   << std::endl;\n\n  \n  //construct Galerkin representation\n  \n  Assembler assembler(gridManager,spaces);\n  VariableSet::VariableSet u(variableSet);\n  VariableSet::VariableSet du(variableSet);\n\n  size_t nnz = assembler.nnz(0,neq,0,nvars,onlyLowerTriangle);\n  std::cout << \"number of nonzero elements in the stiffness matrix: \" << nnz << std::endl << std::endl;\n  boost::timer::cpu_timer assembTimer;\n  \n  CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<0,neq>::init(spaces));\n  solution = 0;\n  \n  assembler.assemble(linearization(F,u));\n  CoefficientVectors rhs(assembler.rhs());\n  AssembledGalerkinOperator<Assembler,0,neq,0,nvars> A(assembler, onlyLowerTriangle);\n  MatrixAsTriplet<double> tri = A.get<MatrixAsTriplet<double> >();\n  std::cout << \"computing time for assemble: \" << (double)(assembTimer.elapsed().user)/1e9 << \"s\\n\";\n\n//     for (k=0; k< nnz; k++)\n//       {\n//         printf(\"%3d %3d %e\\n\", tri.ridx[k], tri.cidx[k], tri.data[k]);\n//       }\n\n  if (direct)\n  {\n    boost::timer::cpu_timer directTimer;\n    directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n    u.data = solution.data;\n    std::cout << \"computing time for direct solve: \" << (double)(directTimer.elapsed().user)/1e9 << \"s\\n\";\n  }\n  else\n  {\n    boost::timer::cpu_timer iteTimer;\n    Dune::InverseOperatorResult res;\n    const DefaultDualPairing<LinearSpace,LinearSpace> defaultScalarProduct{};\n    int iteSteps = getParameter(pt, \"solver.iteMax\", 2000);\n    double iteEps = getParameter(pt, \"solver.iteEps\", 1.0e-10);\n    StrakosTichyPTerminationCriterion<double> termination(iteEps,iteSteps);\n    int lookAhead;\n    switch (precondType)\n    {\n      case PrecondType::NONE:\n      case PrecondType::HB:   lookAhead=50; break;\n      default:                lookAhead=3; break;\n    }\n    lookAhead = getParameter(pt, \"solver.lookAhead\", lookAhead);\n    termination.setLookAhead(lookAhead);\n\n    switch (precondType)\n    {\n      case PrecondType::NONE:\n      {\n        std::cout << \"selected preconditioner: NONE\" << std::endl;\n        TrivialPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > trivial;\n        CG<LinearSpace,LinearSpace> cg(A,trivial,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ADDITIVESCHWARZ:\n      {\n        std::cout << \"selected preconditioner: ADDITIVESCHWARZ\" << std::endl;\n        std::pair<size_t,size_t> idx = temperatureSpace.mapper().globalIndexRange(gridManager.grid().leafIndexSet().geomTypes(dim)[0]);\n        AdditiveSchwarzPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > addschwarz(A,idx.first,idx.second,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,addschwarz,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ILUT:\n      {\n        std::cout << \"selected preconditioner: ILUT\" << std::endl;\n//        std::cout << \"Note that this preconditioner combined with the BICGSTAB solver\" << std::endl;\n        std::cout << \"needs matrix.property = GENERAL\" << std::endl;\n        int lfil = getParameter(pt, \"solver.ILUT.lfil\", 140);\n        double dropTol = getParameter(pt, \"solver.ILUT.dropTol\", 0.01);\n        ILUTPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > ilut(A,lfil,dropTol,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,ilut,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n//         Dune::BiCGSTABSolver<LinearSpace> cg(A,ilut,iteEps,iteSteps,verbosity);\n//         cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ILUK:\n      {\n        std::cout << \"selected preconditioner: ILUK\" << std::endl;\n//        std::cout << \"Note that this preconditioner combined with the BICGSTAB solver\" << std::endl;\n        std::cout << \"needs matrix.property = GENERAL\" << std::endl;\n        int fill_lev = getParameter(pt, \"solver.ILUK.fill_lev\", 3);\n        ILUKPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > iluk(A,fill_lev,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,iluk,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n//         Dune::BiCGSTABSolver<LinearSpace> cg(A,iluk,iteEps,iteSteps,verbosity);\n//         cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ARMS:\n      {\n        int lfil = getParameter(pt, \"solver.ARMS.lfil\", 140);\n        int lev_reord = getParameter(pt, \"solver.ARMS.lev_reord\", 1);\n        double dropTol = getParameter(pt, \"solver.ARMS.dropTol\", 0.01);\n        double tolind = getParameter(pt, \"solver.ARMS.tolind\", 0.2);\n        ARMSPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > iluk(A,lfil,dropTol,lev_reord,tolind,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,iluk,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ICC:\n      {\n        std::cout << \"selected preconditioner: ICC\" << std::endl;\n        if (property != MatrixProperties::SYMMETRIC) \n        {\n          std::cout << \"PrecondType::ICC preconditioner of TAUCS lib has to be used with matrix.property==MatrixProperties::SYMMETRIC\\n\";\n          std::cout << \"i.e., call the executable with option --solver.property MatrixProperties::SYMMETRIC\\n\\n\";\n        }\n        double dropTol = getParameter(pt, \"solver.ICC.dropTol\", 0.01);;\n        ICCPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > icc(A,dropTol);\n        CG<LinearSpace,LinearSpace> cg(A,icc,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::ICC0:\n      {\n        std::cout << \"selected preconditioner: ICC0\" << std::endl;\n        ICC_0Preconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > icc0(A);\n        CG<LinearSpace,LinearSpace> cg(A,icc0,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::HB:\n      {\n        std::cout << \"selected preconditioner: HB\" << std::endl;\n        HierarchicalBasisPreconditioner<Grid,AssembledGalerkinOperator<Assembler,0,neq,0,nvars>::range_type, AssembledGalerkinOperator<Assembler,0,neq,0,nvars>::range_type > hb(gridManager.grid());\n        CG<LinearSpace,LinearSpace> cg(A,hb,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::BOOMERAMG:\n      {\n        int steps = getParameter(pt, \"solver.BOOMERAMG.steps\", iteSteps);\n        int coarsentype = getParameter(pt, \"solver.BOOMERAMG.coarsentype\", 21);\n        int interpoltype = getParameter(pt, \"solver.BOOMERAMG.interpoltype\", 0);\n        int cycleType = getParameter(pt, \"solver.BOOMERAMG.cycleType\", 1);\n        int relaxType = getParameter(pt, \"solver.BOOMERAMG.relaxType\", 3);\n        int variant = getParameter(pt, \"solver.BOOMERAMG.variant\", 0);\n        int overlap = getParameter(pt, \"solver.BOOMERAMG.overlap\", 1);\n        double tol = getParameter(pt, \"solver.BOOMERAMG.tol\", iteEps);\n        double strongThreshold = getParameter(pt, \"solver.BOOMERAMG.strongThreshold\", (dim==2)?0.25:0.6);\n        BoomerAMG<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> >\n                  boomerAMGPrecon(A,steps,coarsentype,interpoltype,tol,cycleType,relaxType,\n                  strongThreshold,variant,overlap,1,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,boomerAMGPrecon,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n//         Dune::LoopSolver<LinearSpace> cg(A,boomerAMGPrecon,iteEps,iteSteps,verbosity);\n//         cg.apply(solution,rhs,res);\n      }\n      break;\n      case PrecondType::EUCLID:\n      {\n        std::cout << \"selected preconditioner: EUCLID\" << std::endl;\n        int level      = getParameter(pt, \"solver.EUCLID.level\",1);\n        double droptol = getParameter(pt, \"solver.EUCLID.droptol\",0.01);\n        int printlevel = 0;\n        if (verbosity>2) printlevel=verbosity-2;\n        printlevel = getParameter(pt,\"solver.EUCLID.printlevel\",printlevel);\n        int bj = getParameter(pt, \"solver.EUCLID.bj\",0);\n        Euclid<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > EuclidPrecon(A,level,droptol,printlevel,bj,verbosity);\n        CG<LinearSpace,LinearSpace> cg(A,EuclidPrecon,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n     }\n      break;\n      case PrecondType::JACOBI:\n      default:\n      {\n        std::cout << \"selected preconditioner: JACOBI\" << std::endl;\n        JacobiPreconditioner<AssembledGalerkinOperator<Assembler,0,neq,0,nvars> > jacobi(A,1.0);\n        CG<LinearSpace,LinearSpace> cg(A,jacobi,defaultScalarProduct,termination,verbosity);\n        cg.apply(solution,rhs,res);\n      }\n      break;\n    }\n    solution *= -1.0;\n    u.data = solution.data;\n    \n    std::cout << \"iterative solve eps= \" << iteEps << \": \" \n              << (res.converged?\"converged\":\"failed\") << \" after \"\n              << res.iterations << \" steps, rate=\"\n              << res.conv_rate << \", computing time=\" << (double)(iteTimer.elapsed().user)/1e9 << \"s\\n\";\n  }\n  \n  // compute L2 norm of the solution\n  boost::timer::cpu_timer outputTimer;\n  L2Norm l2Norm;\n  std::cout << \"L2norm(solution) = \" << l2Norm(boost::fusion::at_c<0>(u.data)) << 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  writeVTKFile(u,\"temperature\",IoOptions().setOrder(order));\n  std::cout << \"graphical output finished, data in VTK format is written into file temperature.vtu \\n\";\n  IoOptions gnuplotOptions{};\n  //    gnuplotOptions.info = IoOptions::none; // or IoOptions::summary or IoOptions::detail\n  writeGnuplotFile(u,\"temperature\",gnuplotOptions);\n  std::cout << \"graphical output finished, Gnuplot data are written into file temperature.data \\n\";\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,variableSet,u,\"temperature\",options);\n\n  std::cout << \"computing time for output: \" << (double)(outputTimer.elapsed().user)/1e9 << \"s\\n\";\n\n  std::cout << \"total computing time: \" << (double)(totalTimer.elapsed().user)/1e9 << \"s\\n\";\n  std::cout << \"End heat transfer tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "e7a957b87d307899d731d1c4a191cbce5adda903", "size": 16734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/stationary_heattransfer/ht_gnuplot.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/stationary_heattransfer/ht_gnuplot.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/stationary_heattransfer/ht_gnuplot.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": 46.226519337, "max_line_length": 197, "alphanum_fraction": 0.655073503, "num_tokens": 4587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5722093588894162}}
{"text": "#include <stdio.h>\n#include <iostream>\n#include <g2o/core/block_solver.h>\n#include <g2o/solvers/eigen/linear_solver_eigen.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/types/slam2d/types_slam2d.h>\n#include <Eigen/Core>\n\ntypedef struct{\n    int s, e;\n    Eigen::Vector2d pose;\n} Edge;\ntypedef g2o::BlockSolver< g2o::BlockSolverTraits<2, 2> >  SlamBlockSolver;\ntypedef g2o::LinearSolverEigen<SlamBlockSolver::PoseMatrixType> SlamLinearSolver;\n\nint main(int argc, const char * argv[]) {\n\n    std::vector<Edge> edgeData = {\n        {0, 1, {1, 1}},\n        {1, 2, {1, -1}},\n        {2, 3, {-1, -1}},\n        {3, 0, {-0.5, 0.5}},\n    };\n    \n    std::unique_ptr<SlamLinearSolver> linearSolver = g2o::make_unique<SlamLinearSolver>();\n    linearSolver->setBlockOrdering(false);\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(g2o::make_unique<SlamBlockSolver>(std::move(linearSolver)));\n\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n    auto maxEdge = std::max_element(edgeData.begin(), edgeData.end(), [](const Edge& a, const Edge& b){\n        return std::max(a.e, a.s) < std::max(b.e, b.s);\n    });\n    int maxIndex = std::max(maxEdge->s, maxEdge->e);\n\n    for(int i = 0; i < maxIndex+1; i++){\n        g2o::VertexPointXY *v = new g2o::VertexPointXY();\n        v->setId(i);\n        v->setEstimate(g2o::Vector2());\n        if(i == 0){\n            v->setFixed(true);\n        }\n        optimizer.addVertex(v);\n    }\n\n    for(const auto& pData: edgeData){\n        g2o::EdgePointXY* edge = new g2o::EdgePointXY();\n        edge->setVertex( 0, optimizer.vertex(pData.s));\n        edge->setVertex( 1, optimizer.vertex(pData.e));\n        edge->setInformation(  Eigen::Matrix< double, 2,2 >::Identity() );// 信息矩阵表示2维上侧重哪一维，xy是一样重要的，所以就是单位矩阵，但是在6维的位姿中，有可能更侧重优化旋转或者位移，就需要设置信息矩阵\n        edge->setMeasurement(pData.pose );\n        optimizer.addEdge(edge);\n    }\n    \n    optimizer.initializeOptimization();\n    optimizer.optimize(500);\n    for(int i = 0; i < maxIndex+1; i++){\n        g2o::VertexPointXY* vertex = dynamic_cast<g2o::VertexPointXY*>(optimizer.vertex( i ));\n        g2o::Vector2 pose = vertex->estimate();\n        std::cout << i << \":\\n\" << pose << std::endl ;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "f4b5860da16cffc8be067d67b5876f7076fb91d8", "size": 2304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/main.cpp", "max_stars_repo_name": "zhigangjiang/CV-Experiment", "max_stars_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T02:22:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T10:05:04.000Z", "max_issues_repo_path": "g2o/main.cpp", "max_issues_repo_name": "zhigangjiang/CV-Experiment", "max_issues_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_issues_repo_licenses": ["MIT"], "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/main.cpp", "max_forks_repo_name": "zhigangjiang/CV-Experiment", "max_forks_repo_head_hexsha": "9846dd3700dbb575ceaf23af7357d54af5be366e", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 150, "alphanum_fraction": 0.6319444444, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.572209358889416}}
{"text": "#include <string>\n#include <fstream>\n#include <vector>\n#include <utility> // std::pair\n#include <sstream>\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\nusing namespace std;\n\nvector<vector<double>> read_csv( string filename ){\n    // Reads a CSV file with 2 columns into a vector of <vector<double>>\n    vector<vector<double>> result(2);\n\n    // Create an input filestream\n\t//const char *c = filename.c_str();\n    ifstream myFile(filename.c_str());\n\t\n    // Make sure the file is open\n    if(!myFile.is_open()) throw runtime_error(\"Could not open file\");\n\n    // Helper vars\n    string line;\n    double val;\n\n\tif(myFile.good())\n\t{\n\t\t// Read data, line by line\n\t\twhile(getline(myFile, line))\n\t\t{\n\t\t\t// Create a stringstream of the current line\n\t\t\tstringstream ss(line);\n\t\t\t\n\t\t\t// Keep track of the current column index\n\t\t\tint colIdx = 0;\n\t\t\t// Extract each integer\n\t\t\twhile(ss >> val){\n\t\t\t\t\n\t\t\t\t// Add the current integer to the 'colIdx' column's values vector\n\t\t\t\tresult[colIdx].push_back(val);\n\t\t\t\t\n\t\t\t\t// If the next token is a comma, ignore it and move on\n\t\t\t\tif(ss.peek() == ',') ss.ignore();\n\t\t\t\t\n\t\t\t\t// Increment the column index\n\t\t\t\tcolIdx++;\n\t\t\t}\n\t\t}\n\t}\n\n    // Close file\n    myFile.close();\n    return result;\n}\n\ndouble getyL(string ref, double positionx , double positiony, bool debug)\n{\n\ttypedef boost::geometry::model::d2::point_xy<double> point_type;\n\ttypedef boost::geometry::model::linestring<point_type> linestring_type;\n\t\n\tif (debug) cout << \"Entry: Read CSV\" << endl;\n    vector<vector<double>> gold_ref = read_csv(ref);\n\tif (debug) cout << \"Exit: Read CSV\" << endl;\n\t\n\tpoint_type p(positionx, positiony);\n\tlinestring_type line;\n\tdouble x = 0;\n\tdouble y = 0;\n\t\n\tfor (int i = 0; i < gold_ref[0].size(); ++i)\n    {\n\t\tfor(int j = 0; j < gold_ref.size(); ++j)\n\t\t{\n\t\t\tif (j == 0) x = gold_ref[j][i];\n\t\t\telse y = gold_ref[j][i];\n\t\t\t\n\t\t}\n\t\tline.push_back(point_type(x,y));\n        //cout << x << \" , \" << y << \"\\n\" ;\n    }\n\t\n\tdouble yl = boost::geometry::distance(p, line);\n\t//cout << \"Point-Line: \" << yl << endl;\n\treturn yl;\n}\n \n/*int main(int argc , char *argv[])\n  {\n\ttypedef boost::geometry::model::d2::point_xy<double> point_type;\n\ttypedef boost::geometry::model::linestring<point_type> linestring_type;\n    vector<vector<double>> gold_ref = read_csv(\"/home/sayandipde/Approx_IBC/hil/client/Webots/worlds/city_ref.csv\");\n\t\n\tpoint_type p(1,2);\n\tlinestring_type line;\n\tdouble x = 0;\n\tdouble y = 0;\n\t\n\tfor (int i = 0; i < gold_ref[0].size(); ++i)\n    {\n\t\tfor(int j = 0; j < gold_ref.size(); ++j)\n\t\t{\n\t\t\t//cout << gold_ref[j][i];\n\t\t\t//if(j != gold_ref.size() - 1) cout << \",\"; // No comma at end of line\n\t\t\tif (j == 0) x = gold_ref[j][i];\n\t\t\telse y = gold_ref[j][i];\n\t\t\t\n\t\t}\n\t\tline.push_back(point_type(x,y));\n        cout << x << \" , \" << y << \"\\n\" ;\n    }\n\t\n\tcout << \"Point-Line: \" << boost::geometry::distance(p, line) << endl;\n\treturn 0;\n  }*/\n", "meta": {"hexsha": "016ed1d3c36e5592cac513c57adaa17e5c0fdc89", "size": 2969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_webots_api/other-sources/get_yL_fromref.cpp", "max_stars_repo_name": "sayandipde/robust_dynamic_sesning", "max_stars_repo_head_hexsha": "2add247b67e03d36fc9057a2ae4afa0eb5c86702", "max_stars_repo_licenses": ["Apache-2.0"], "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_webots_api/other-sources/get_yL_fromref.cpp", "max_issues_repo_name": "sayandipde/robust_dynamic_sesning", "max_issues_repo_head_hexsha": "2add247b67e03d36fc9057a2ae4afa0eb5c86702", "max_issues_repo_licenses": ["Apache-2.0"], "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_webots_api/other-sources/get_yL_fromref.cpp", "max_forks_repo_name": "sayandipde/robust_dynamic_sesning", "max_forks_repo_head_hexsha": "2add247b67e03d36fc9057a2ae4afa0eb5c86702", "max_forks_repo_licenses": ["Apache-2.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.1610169492, "max_line_length": 116, "alphanum_fraction": 0.6190636578, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.5721721119982663}}
{"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 decorrelated_gaussian.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 <vector>\n#include <string>\n#include <cstddef>\n#include <type_traits>\n\n#include <fl/util/traits.hpp>\n#include <fl/exception/exception.hpp>\n#include <fl/distribution/interface/moments.hpp>\n#include <fl/distribution/interface/evaluation.hpp>\n#include <fl/distribution/interface/standard_gaussian_mapping.hpp>\n#include <fl/distribution/gaussian.hpp>\n\nnamespace fl\n{\n\n/**\n * \\class DecorrelatedGaussian\n *\n * \\brief General Decorrelated Gaussian Distribution\n * \\ingroup distributions\n * \\{\n *\n * The Gaussian is a general purpose distribution representing a multi-variate\n * \\f${\\cal N}(x; \\mu, \\Sigma)\\f$. It can be used in various\n * ways while maintaining efficienty at the same time. This is due to it's\n * multi-representation structure. The distribution can be represented either by\n *\n *  - the covariance matrix \\f$\\Sigma\\f$,\n *  - the precision matrix \\f$\\Sigma^{-1} = \\Lambda\\f$,\n *  - the covariance square root matrix (Cholesky decomposition or LDLT)\n *    \\f$\\sqrt{\\Sigma} = L\\sqrt{D}\\f$,\n *  - or the diagonal form of the previous three options\n *    \\f$diag(\\sigma_1, \\ldots, \\sigma_n)\\f$.\n *\n * A change in one representation results in change of all other\n * representations.\n *\n * Two key features of the distribution are its aibility to evaluation the\n * probability of a given sample and to map a noise sample into the distribution\n * sample space.\n *\n * \\cond internal\n * The Gaussian internal structure uses lazy assignments or write on read\n * technique. Due to the multi-representation of the Gaussian, modifying one\n * representation affects all remaining ones. If one of the representation is\n * modified, the other representations are only then updated when needed. This\n * minimizes redundant computation and increases efficienty.\n * \\endcond\n */\ntemplate <typename Variate>\nclass DecorrelatedGaussian\n    : public Moments<Variate, typename DiagonalSecondMomentOf<Variate>::Type>,\n      public Evaluation<Variate>,\n      public StandardGaussianMapping<Variate, SizeOf<Variate>::Value>\n{\npublic:\n    typedef Evaluation<Variate> EvaluationInterface;\n\n    typedef Moments<\n                Variate, typename DiagonalSecondMomentOf<Variate>::Type\n            > MomentsInterface;\n\n    typedef StandardGaussianMapping<\n                Variate, SizeOf<Variate>::Value\n            > StdGaussianMappingInterface;\n\n    /**\n     * \\brief Second moment matrix type, i.e covariance matrix, precision\n     *        matrix, and their diagonal and square root representations\n     */\n    typedef typename DiagonalSecondMomentOf<Variate>::Type DiagonalSecondMoment;\n\n    typedef typename SecondMomentOf<Variate>::Type DenseSecondMoment;\n\n    /**\n     * \\brief Represents the StandardGaussianMapping standard variate type which\n     *        is of the same dimension as the Gaussian Variate. The\n     *        StandardVariate type is used to sample from a standard normal\n     *        Gaussian and map it to this Gaussian\n     */\n    typedef\n    typename StdGaussianMappingInterface::StandardVariate StandardVariate;\n\nprotected:\n    /** \\cond internal */\n    /**\n     * \\enum Attribute\n     * Implementation attributes. The enumeration lists the different\n     * representations along with other properties such as the rank of the\n     * second moment and the log normalizer.\n     */\n    enum Attribute\n    {\n        DiagonalCovarianceMatrix = 0,/**< Diagonal form of of cov. mat. */\n        DiagonalPrecisionMatrix,     /**< Diagonal form of inv cov. mat. */\n        DiagonalSquareRootMatrix,    /**< Diagonal form of Cholesky decomp. */\n        Rank,                        /**< Covariance Rank */\n        Normalizer,                  /**< Log probability normalizer */\n        Determinant,                 /**< Determinant of covariance */\n\n        Attributes                   /**< Total number of attribute */\n    };\n\n    /**\n     * \\brief Flags array type which contains the content status if different\n     *        distribution representation\n     */\n    typedef std::array<bool, Attributes> FlagArray;\n    /** \\endcond */\n\npublic:\n    /**\n     * Creates a dynamic or fixed size Gaussian.\n     *\n     * \\param dimension Dimension of the Gaussian. The default is defined by the\n     *                  dimension of the variable type \\em Vector. If the size\n     *                  of the Vector at compile time is fixed, this will be\n     *                  adapted. For dynamic-sized Variable the dimension is\n     *                  initialized to 0.\n     */\n    explicit DecorrelatedGaussian(int dim = DimensionOf<Variate>()):\n        StdGaussianMappingInterface(dim)\n    {\n        static_assert(SizeOf<Variate>::Value != 0, \"Illegal static dimension\");\n\n        std::fill(dirty_.begin(), dirty_.end(), true);\n        set_standard();\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~DecorrelatedGaussian() noexcept { }\n\n    /**\n     * \\return Gaussian dimension\n     */\n    virtual int dimension() const\n    {\n        return StdGaussianMappingInterface::standard_variate_dimension();\n    }\n\n    /**\n     * \\return Gaussian first moment\n     */\n    virtual const Variate& mean() const\n    {\n        return mean_;\n    }\n\n    /**\n     * \\return Gaussian second centered moment\n     *\n     * Computes the covariance from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of the\n     *         representation can be used as a source\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#CovarianceMatrix}\n     * \\endcond\n     */\n    virtual const DiagonalSecondMoment& covariance() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(DiagonalCovarianceMatrix))\n        {\n            switch (select_first_representation<2>(\n                        {{ DiagonalSquareRootMatrix,\n                           DiagonalPrecisionMatrix }}))\n            {\n            case DiagonalSquareRootMatrix:\n            {\n                covariance_.diagonal() = square_root_.diagonal().cwiseProduct(\n                                            square_root_.diagonal());\n             } break;\n\n            case DiagonalPrecisionMatrix:\n            {\n                covariance_.diagonal() = precision_.diagonal().cwiseInverse();\n            } break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(DiagonalCovarianceMatrix);\n        }\n\n        return covariance_;\n    }\n\n    /**\n     * \\return Gaussian second centered moment in the precision form (inverse\n     * of the covariance)\n     *\n     * Computes the precision from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of the\n     *         representation can be used as a source\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#PrecisionMatrix}\n     * \\endcond\n     */\n    virtual const DiagonalSecondMoment& precision() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(DiagonalPrecisionMatrix))\n        {\n            switch (select_first_representation<2>(\n                        {{ DiagonalCovarianceMatrix,\n                           DiagonalSquareRootMatrix}}))\n            {\n            case DiagonalCovarianceMatrix:\n            case DiagonalSquareRootMatrix:\n                precision_.diagonal() = covariance().diagonal().cwiseInverse();\n                break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(DiagonalPrecisionMatrix);\n        }\n\n        return precision_;\n    }\n\n\n    /**\n     * \\return Gaussian second centered moment in the square root form (\n     * Cholesky decomposition)\n     *\n     * Computes the square root from other representation of not available\n     *\n     * \\throws GaussianUninitializedException if the Gaussian is of dynamic-size\n     *         and has not been initialized using SetStandard(dimension).\n     * \\throws InvalidGaussianRepresentationException if non-of the\n     *         representation can be used as a source\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#SquareRootMatrix}\n     * \\endcond\n     */\n    virtual const DiagonalSecondMoment& square_root() const\n    {\n        if (dimension() == 0)\n        {\n            fl_throw(GaussianUninitializedException());\n        }\n\n        if (is_dirty(DiagonalSquareRootMatrix))\n        {\n            switch (select_first_representation<2>(\n                        {{ DiagonalCovarianceMatrix,\n                           DiagonalPrecisionMatrix }}))\n            {\n            case DiagonalCovarianceMatrix:\n            case DiagonalPrecisionMatrix:\n            {\n                square_root_.diagonal() = covariance().diagonal().cwiseSqrt();\n            } break;\n\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(DiagonalSquareRootMatrix);\n        }\n\n        return square_root_;\n    }\n\n    /**\n     * \\return True if the covariance matrix has a full rank\n     *\n     * \\throws see covariance()\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#CovarianceMatrix}\n     * \\endcond\n     */\n    virtual bool has_full_rank() const\n    {\n        if (is_dirty(Rank))\n        {\n            full_rank_ = true;\n\n            switch (select_first_representation<3>(\n                        {{ DiagonalCovarianceMatrix,\n                           DiagonalPrecisionMatrix,\n                           DiagonalSquareRootMatrix }}))\n            {\n            case DiagonalCovarianceMatrix:\n                full_rank_ = has_full_rank(covariance());\n                break;\n            case DiagonalPrecisionMatrix:\n                full_rank_ = has_full_rank(precision());\n                break;\n            case DiagonalSquareRootMatrix:\n                full_rank_ = has_full_rank(square_root());\n                break;\n            default:\n                fl_throw(InvalidGaussianRepresentationException());\n                break;\n            }\n\n            updated_internally(Rank);\n        }\n\n        return full_rank_;\n    }\n\n    /**\n     * \\return Log normalizing constant\n     *\n     * \\throws see has_full_rank()\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#CovarianceMatrix}\n     * \\endcond\n     */\n    virtual Real log_normalizer() const\n    {\n        if (is_dirty(Normalizer))\n        {\n            if (has_full_rank())\n            {\n                log_norm_ = -0.5\n                    * (log(covariance_determinant())\n                       + Real(covariance().rows()) * log(2.0 * M_PI));\n            }\n            else\n            {\n                log_norm_ = 0.0; // FIXME\n            }\n\n            updated_internally(Normalizer);\n        }\n\n        return log_norm_;\n    }\n\n    /**\n     * \\return Covariance determinant\n     *\n     * \\throws see covariance\n     */\n    virtual Real covariance_determinant() const\n    {\n        if (is_dirty(Determinant))\n        {\n            determinant_ = covariance().diagonal().prod();\n\n            updated_internally(Determinant);\n        }\n\n        return determinant_;\n    }\n\n    /**\n     * \\return Log of the probability of the given sample \\c vector\n     *\n     * \\param vector sample which should be evaluated\n     *\n     * \\throws see has_full_rank()\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#PrecisionMatrix}\n     * \\endcond\n     */\n    virtual Real log_probability(const Variate& vector) const\n    {\n        if(has_full_rank())\n        {\n            return log_normalizer() - 0.5\n                    * (vector - mean()).transpose()\n                    * precision()\n                    * (vector - mean());\n        }\n\n        return -std::numeric_limits<Real>::infinity();\n    }\n\n    /**\n     * \\return a Gaussian sample of the type \\c Vector determined by mapping a\n     * noise sample into the Gaussian sample space\n     *\n     * \\param sample    Noise Sample\n     *\n     * \\throws see square_root()\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#SquareRootMatrix}\n     * \\endcond\n     */\n    virtual Variate map_standard_normal(const StandardVariate& sample) const\n    {\n        return mean() + square_root() * sample;\n    }\n\n    /**\n     * Sets the Gaussian to a standard distribution with zero mean and identity\n     * covariance.\n     *\n     * \\cond internal\n     * \\pre {}\n     * \\post\n     *  - Fully ranked covariance\n     *  - {Valid representations} = {#CovarianceMatrix}\n     * \\endcond\n     */\n    virtual void set_standard()\n    {\n        mean_.resize(dimension());\n        covariance_.resize(dimension());\n        precision_.resize(dimension());\n        square_root_.resize(dimension());\n\n        mean(Variate::Zero(dimension()));\n\n        auto cov = DiagonalSecondMoment(dimension());\n        cov.setIdentity(dimension());\n        covariance(cov);\n\n        full_rank_ = true;\n        updated_internally(Rank);\n    }\n\n    /**\n     * Changes the dimension of the dynamic-size Gaussian and sets it to a\n     * standard distribution with zero mean and identity covariance.\n     *\n     * \\param new_dimension New dimension of the Gaussian\n     *\n     * \\cond internal\n     * \\pre {}\n     * \\post\n     *  - Fully ranked covariance\n     *  - {Valid representations} = {#CovarianceMatrix}\n     * \\endcond\n     *\n     * \\throws ResizingFixedSizeEntityException\n     *         see GaussianMap::standard_variate_dimension(int)\n     */\n    virtual void dimension(int new_dimension)\n    {\n        StdGaussianMappingInterface::standard_variate_dimension(new_dimension);\n        set_standard();\n    }\n\n    /**\n     * Sets the mean\n     *\n     * \\param mean New Gaussian mean\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void mean(const Variate& mean) noexcept\n    {\n        if (mean_.size() != mean.size())\n        {\n            fl_throw(fl::WrongSizeException(mean.size(), mean_.size()));\n        }\n\n        mean_ = mean;\n    }\n\n    /**\n     * Sets the covariance matrix as a diagonal matrix\n     *\n     * \\param diag_covariance New diagonal covariance matrix\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalCovarianceMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void covariance(\n        const DiagonalSecondMoment& diag_covariance) noexcept\n    {\n        if (diag_covariance.size() != covariance_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_covariance.size(), covariance_.size()));\n        }\n\n        covariance_ = diag_covariance;\n        updated_externally(DiagonalCovarianceMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal square root form\n     *\n     * \\param diag_square_root New diagonal square root of the covariance\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalSquareRootMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void square_root(\n        const DiagonalSecondMoment& diag_square_root) noexcept\n    {\n        if (diag_square_root.size() != square_root_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_square_root.size(), square_root_.size()));\n        }\n\n        square_root_ = diag_square_root;\n        updated_externally(DiagonalSquareRootMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal precision form\n     *\n     * \\param diag_precision New diagonal precision matrix\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalPrecisionMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void precision(\n        const DiagonalSecondMoment& diag_precision) noexcept\n    {\n        if (diag_precision.size() != precision_.size())\n        {\n            fl_throw(\n                fl::WrongSizeException(\n                    diag_precision.size(), precision_.size()));\n        }\n\n        precision_ = diag_precision;\n        updated_externally(DiagonalPrecisionMatrix);\n    }\n\n    /**\n     * Sets the covariance matrix as a diagonal matrix\n     *\n     * \\param diag_covariance New diagonal covariance matrix\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalCovarianceMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void covariance(\n        const Eigen::MatrixBase<DenseSecondMoment>& cov) noexcept\n    {\n        covariance(cov.diagonal().asDiagonal());\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal square root form\n     *\n     * \\param diag_square_root New diagonal square root of the covariance\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalSquareRootMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void square_root(\n        const Eigen::MatrixBase<DenseSecondMoment>& sqrt) noexcept\n    {\n        square_root(sqrt.diagonal().asDiagonal());\n    }\n\n    /**\n     * Sets the covariance matrix in its diagonal precision form\n     *\n     * \\param diag_precision New diagonal precision matrix\n     *\n     * \\cond internal\n     * \\pre |{Valid Representations}| > 0\n     * \\post {Valid Representations}\n     *       = {Valid Representations} \\f$ \\cup \\f$ {#DiagonalPrecisionMatrix}\n     * \\endcond\n     *\n     * \\throws WrongSizeException\n     */\n    virtual void precision(\n        const Eigen::MatrixBase<DenseSecondMoment>& prec) noexcept\n    {\n        precision(prec.diagonal().asDiagonal());\n    }\n\nprotected:\n    /** \\cond internal */\n    /**\n     * Flags the specified attribute as valid and the rest of attributes as\n     * dirty.\n     *\n     * \\param attribute Modified attribute\n     */\n    virtual void updated_externally(Attribute attribute) const noexcept\n    {\n        std::fill(dirty_.begin(), dirty_.end(), true);\n        updated_internally(attribute);\n    }\n\n    /**\n     * Flags the specified attribute as valid.\n     *\n     * \\param attribute Modified attribute\n     */\n    virtual void updated_internally(Attribute attribute) const noexcept\n    {\n        dirty_[attribute] = false;\n    }\n\n    /**\n     * \\return True if any of the other representation was modified.\n     * \\param attribute     Attribute in question\n     */\n    virtual bool is_dirty(Attribute attribute) const noexcept\n    {\n        return dirty_[int(attribute)];\n    }\n\n    /**\n     * \\return First representation ID that is available\n     *\n     * \\param representations   Representation list\n     *\n     * Example:\n     * If the last invoked functions were\n     *\n     * \\code\n     * diagonal_covariance(my_diagonal);\n     * my_covariance = covariance();\n     * \\endcode\n     *\n     * Now, the representation is set to \\c DiagonalCovarianceMatrix and\n     * \\c CovarianceMatrix since \\c diagonal_covariance() was used to set the\n     * covariance matrix followed by requesting \\c covariance().\n     * The following subsequent call\n     *\n     * \\code\n     * Attribute att = SelectRepresentation({SquareRoot,\n     *                                       DiagonalCovarianceMatrix,\n     *                                       CovarianceMatrix});\n     * \\endcode\n     *\n     * will assign att to DiagonalCovarianceMatrix since that is the first\n     * available representation within the initializer-list\n     * <tt>{#SquareRoot, #DiagonalCovarianceMatrix, #CovarianceMatrix}</tt>.\n     *\n     * This method is used to determine the best suitable representation\n     * for conversion. It is recommanded to put the diagonal forms at the\n     * beginning of the initialization-list. Diagonal forms can be converted\n     * most efficiently other  representations.\n     */\n    template <int AttributeCount>\n    Attribute select_first_representation(\n        const std::array<Attribute, AttributeCount>& representations\n    ) const noexcept\n    {\n        for (auto& rep: representations)  if (!is_dirty(rep)) return rep;\n        return Attributes;\n    }\n\n    /**\n     * \\brief has_full_rank check implementation\n     */\n    virtual bool has_full_rank(const DiagonalSecondMoment& mat) const\n    {\n        bool full_rank = true;\n\n        const auto& diag = mat.diagonal();\n\n        for (int i = 0; i < diag.size(); ++i)\n        {\n            if (std::fabs(diag(i)) < 1e-24)\n            {\n                full_rank = false;\n                break;\n            }\n        }\n\n        return full_rank;\n    }\n    /** \\endcond */\n\nprotected:\n    /** \\cond internal */\n    Variate mean_;                            /**< \\brief first moment vector */\n    mutable DiagonalSecondMoment covariance_; /**< \\brief cov. form */\n    mutable DiagonalSecondMoment precision_;  /**< \\brief cov. inverse form */\n    mutable DiagonalSecondMoment square_root_;/**< \\brief cov. square root  */\n    mutable bool full_rank_;                  /**< \\brief full rank flag */\n    mutable Real log_norm_;                   /**< \\brief log normalizing const */\n    mutable Real determinant_;         /**< \\brief determinant of covariance */\n    mutable FlagArray dirty_;          /**< \\brief data validity flags */\n    /** \\endcond */\n};\n\n/** \\} */\n\n}\n", "meta": {"hexsha": "83e8653de4fbb84bd820f1f2eae07c89a376a3b1", "size": 23428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/decorrelated_gaussian.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/decorrelated_gaussian.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/decorrelated_gaussian.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": 30.2687338501, "max_line_length": 82, "alphanum_fraction": 0.59574014, "num_tokens": 5162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5720293479692149}}
{"text": "/*\n correlation.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 <algorithm>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <cmath>\n#include <numeric>\n#include <vector>\n\n#include \"correlation.hxx\"\n#include \"neighbour.hxx\"\n#include \"supercell.hxx\"\n#include \"utils.hxx\"\n\nCorrelation::Correlation() {\n}\n\nvoid Correlation::Calculate(const Neighbour& neighbour_table,\n                            Supercell& supercell) {\n\n  ublas::matrix<double> table = neighbour_table.Sites;\n\n  std::vector<double> pairs = {};\n  std::vector<long> count = {};\n  std::vector<double> corrs = {};\n\n  auto nsum = 0;\n\n  for (auto i = 0; i < supercell.number_of_atoms; i++) {\n    ublas::matrix_row<ublas::matrix<double>> ib(supercell.basis_vectors,i);\n    auto ip = supercell.pointers(i);\n    for (auto j = 0; j < neighbour_table.Total(i); j++) {\n      auto ptr = neighbour_table.Pointers(nsum+j);\n      auto jbsp = neighbour_table.BasisPointers(ptr);\n      auto jp = supercell.pointers(jbsp);\n\n      ublas::matrix_row<ublas::matrix<double>> jb(table,ptr);\n\n      double r = ublas::norm_2(jb-ib);\n      double corr = static_cast<double>(ip*jp);\n      long index = linear_search(pairs,r,1e-6);\n\n      if (index == pairs.size()) {\n        pairs.insert(pairs.begin(),r);\n        count.insert(count.begin(),1);\n        corrs.insert(corrs.begin(),corr);\n      } else {\n        count[index]++;\n        corrs[index] += corr;\n      }\n    }\n    nsum += neighbour_table.Total(i);\n  }\n\n  /* Normalize */\n  for (auto i = 0; i < pairs.size(); i++) {\n    corrs[i] /= count[i];\n  }\n\n  /* Sorting */\n  std::vector<std::size_t> indices(pairs.size());\n  std::iota(indices.begin(),indices.end(),0);\n  std::sort(indices.begin(), indices.end(),\n            [&pairs](std::size_t left, std::size_t right) {\n              return pairs[left] < pairs[right];\n            });\n\n  std::vector<double> sort_pairs = pairs;\n  std::vector<long> sort_count = count;\n  std::vector<double> sort_corrs = corrs;\n\n  number = pairs.size();\n  for (auto i = 0; i < number; i++) {\n    sort_pairs[i] = pairs[indices[i]];\n    sort_count[i] = count[indices[i]];\n    sort_corrs[i] = corrs[indices[i]];\n  }\n\n  pair_clusters = sort_pairs;\n  pair_count = sort_count;\n  pair_correlations = sort_corrs;\n\n}\n\ndouble Correlation::ErrorFunction(double x) {\n\n  double error = (2*x-1)*(2*x-1);\n  ublas::vector<double> efs(number);\n\n  for (auto i = 0; i < number; i++) {\n    efs(i) = std::fabs(error-pair_correlations[i]);\n  }\n\n  errors = efs;\n  return ublas::sum(efs)/number;\n\n}\n", "meta": {"hexsha": "9b9452ca8edde281eb5a571eb7eb3f68b11131f1", "size": 2776, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/correlation.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/correlation.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/correlation.cxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9439252336, "max_line_length": 75, "alphanum_fraction": 0.632925072, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5720293308571707}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::students_t_distribution.hpp                                      //\n//                                                                          //\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_RANDOM_STUDENTS_T_HPP_ER_2009\n#define BOOST_RANDOM_STUDENTS_T_HPP_ER_2009\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/chi_squared.hpp>\n\nnamespace boost{\nnamespace random{\n\n    // Samples from a students_t distribution\n    template<typename T>\n    class students_t_distribution{\n            typedef boost::normal_distribution<T>           nd_;\n            typedef random::chi_squared_distribution<T>     cs_;\n        public:\n            typedef typename nd_::input_type input_type;\n            typedef typename nd_::result_type result_type;\n\n        students_t_distribution():df_(2){}\n        students_t_distribution(unsigned df):df_(df){}\n\n        template<typename U>\n        result_type\n        operator()(U& urng){\n            static nd_ nd(0,1);\n            static cs_ cs(df_);\n            result_type z = nd(urng);\n            result_type d = cs(urng);\n            d /= static_cast<result_type>(df_);\n            d = sqrt(d);\n            return z / d;\n        }\n\n        unsigned df()const{ return df_; }\n\n        private:\n            unsigned df_;\n    };\n\n\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "0c62623fa198016ef33d4450f0aac8d8391a3e9d", "size": 1976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/students_t.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/students_t.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/students_t.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.0689655172, "max_line_length": 78, "alphanum_fraction": 0.5025303644, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5720293308571707}}
{"text": "/*\n * Copyright (c) 2016-2018 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http://opensource.org/licenses/MIT)\n */\n\n#include \"../exception_internal.hpp\"\n#include \"../utils/misc.hpp\"\n#include \"../database/database_common.hpp\"\n\n#include <pkmn/config.hpp>\n#include <pkmn/exception.hpp>\n#include <pkmn/calculations/moves/hidden_power.hpp>\n\n#include <boost/config.hpp>\n\n#include <cmath>\n\nnamespace pkmn { namespace calculations {\n\n    // Most significant bit\n    #define MSB(var) (((var) >> 3) & 1)\n\n    /*\n     * There is no Normal-type Hidden Power, so all type indices\n     * are offset from normal.\n     */\n    inline pkmn::e_type gen2_hidden_power_type(\n        int IV_attack, int IV_defense\n    )\n    {\n        return static_cast<pkmn::e_type>(\n                   (4 * (IV_attack % 4) + (IV_defense % 4)) + 2\n               );\n    }\n\n    inline int gen2_hidden_power_base_power(\n        uint8_t v, uint8_t w, uint8_t x,\n        uint8_t y, uint8_t Z\n    )\n    {\n        return int(std::floor<int>(((5 * (v + (w<<1) + (x<<2) + (y<<3)) + Z) / 2) + 31));\n    }\n\n    hidden_power gen2_hidden_power(\n        int IV_attack,\n        int IV_defense,\n        int IV_speed,\n        int IV_special\n    ) {\n        // Input validation\n        pkmn::enforce_IV_bounds(\"Attack\",  IV_attack,  false);\n        pkmn::enforce_IV_bounds(\"Defense\", IV_defense, false);\n        pkmn::enforce_IV_bounds(\"Speed\",   IV_speed,   false);\n        pkmn::enforce_IV_bounds(\"Special\", IV_special, false);\n\n        uint8_t v = MSB(IV_special);\n        uint8_t w = MSB(IV_speed);\n        uint8_t x = MSB(IV_defense);\n        uint8_t y = MSB(IV_attack);\n        uint8_t Z = (IV_special % 4);\n\n        return hidden_power(\n                   gen2_hidden_power_type(IV_attack, IV_defense),\n                   gen2_hidden_power_base_power(v, w, x, y, Z)\n               );\n    }\n\n    // Least significant bit\n    #define LSB(var)  ((var) & 1)\n    // Second-least significant bit\n    #define LSB2(var) (((var) & 2) >> 1)\n\n    inline pkmn::e_type modern_hidden_power_type(\n        uint8_t a, uint8_t b, uint8_t c,\n        uint8_t d, uint8_t e, uint8_t f\n    )\n    {\n         return static_cast<pkmn::e_type>(static_cast<int>(\n                    (std::floor<int>(((a + (b<<1) + (c<<2) + (d<<3) + (e<<4) + (f<<5)) * 15) / 63)) + 2\n                ));\n    }\n\n    inline int modern_hidden_power_base_power(\n        uint8_t u, uint8_t v, uint8_t w,\n        uint8_t x, uint8_t y, uint8_t z\n    )\n    {\n        return int(std::floor<int>((((u + (v<<1) + (w<<2) + (x<<3) + (y<<4) + (z<<5)) * 40) / 63) + 30));\n    }\n\n    hidden_power modern_hidden_power(\n        int IV_HP,\n        int IV_attack,\n        int IV_defense,\n        int IV_speed,\n        int IV_spatk,\n        int IV_spdef\n    )\n    {\n        // Input validation\n        pkmn::enforce_IV_bounds(\"HP\",              IV_HP,      true);\n        pkmn::enforce_IV_bounds(\"Attack\",          IV_attack,  true);\n        pkmn::enforce_IV_bounds(\"Defense\",         IV_defense, true);\n        pkmn::enforce_IV_bounds(\"Speed\",           IV_speed,   true);\n        pkmn::enforce_IV_bounds(\"Special Attack\",  IV_spatk,   true);\n        pkmn::enforce_IV_bounds(\"Special Defense\", IV_spdef,   true);\n\n        uint8_t a = LSB(IV_HP);\n        uint8_t b = LSB(IV_attack);\n        uint8_t c = LSB(IV_defense);\n        uint8_t d = LSB(IV_speed);\n        uint8_t e = LSB(IV_spatk);\n        uint8_t f = LSB(IV_spdef);\n\n        uint8_t u = LSB2(IV_HP);\n        uint8_t v = LSB2(IV_attack);\n        uint8_t w = LSB2(IV_defense);\n        uint8_t x = LSB2(IV_speed);\n        uint8_t y = LSB2(IV_spatk);\n        uint8_t z = LSB2(IV_spdef);\n\n        return hidden_power(\n                   modern_hidden_power_type(a, b, c, d, e, f),\n                   modern_hidden_power_base_power(u, v, w, x, y, z)\n               );\n    }\n\n}}\n", "meta": {"hexsha": "6f1c07dac104cf3f11ea2fe87d1ad3ebbf79571e", "size": 3904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/calculations/moves/hidden_power.cpp", "max_stars_repo_name": "ncorgan/libpkmn", "max_stars_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-06-10T13:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T21:20:19.000Z", "max_issues_repo_path": "lib/calculations/moves/hidden_power.cpp", "max_issues_repo_name": "PMArkive/libpkmn", "max_issues_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T11:13:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-03T14:31:03.000Z", "max_forks_repo_path": "lib/calculations/moves/hidden_power.cpp", "max_forks_repo_name": "PMArkive/libpkmn", "max_forks_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-22T21:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T21:20:20.000Z", "avg_line_length": 29.8015267176, "max_line_length": 105, "alphanum_fraction": 0.559170082, "num_tokens": 1157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5720293212874715}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2015-2020 by Synge Todo <wistaria@phy.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// Calculating free energy, energy, and specific heat of square lattice Ising model\n\n#include <iomanip>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include \"square/infinite.hpp\"\n\nint main(int argc, char **argv) {\n  typedef double real_t;\n  real_t Jx, Jy, t_min, t_max, t_step;\n  if (argc == 6) {\n    Jx = boost::lexical_cast<real_t>(argv[1]);\n    Jy = boost::lexical_cast<real_t>(argv[2]);\n    t_min = boost::lexical_cast<real_t>(argv[3]);\n    t_max = boost::lexical_cast<real_t>(argv[4]);\n    t_step = boost::lexical_cast<real_t>(argv[5]);\n  } else if (argc == 1) {\n    std::cin >> Jx >> Jy >> t_min >> t_max >> t_step;\n  } else {\n    std::cerr << \"Usage: \" << argv[0] << \" [Jx Jy t_min t_max t_step]\\n\";\n    return 127;\n  }\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10);\n  std::cout << \"# square lattice Ising model\\n\";\n  std::cout << \"# Jx, Jy, T, free energy density, energy density, specific heat\\n\";\n  for (real_t t = t_min; t <= t_max; t += t_step) {\n    real_t beta = 1 / t;\n    auto result = ising::square::infinite(beta, Jx, Jy);\n    std::cout << Jx << ' ' << Jy << ' ' << t << ' ' << std::get<0>(result) << ' '\n              << std::get<1>(result) << ' ' << std::get<2>(result) << std::endl;\n  }\n}\n", "meta": {"hexsha": "37a44e4964e7330e5d0e388cd20e382cffe0caf8", "size": 1652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ising/square/free_energy.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "test/ising/square/free_energy.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "test/ising/square/free_energy.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3333333333, "max_line_length": 91, "alphanum_fraction": 0.5599273608, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.5720188635070436}}
{"text": "// gray_code_iterator.hpp\n//\n// Produces all n-tuples of {0,1} in a minimal change ordering \n// (i.e. Gray code). In particular, two consecutive elements\n// have Hamming distance equal to 1. The algorithm is a loopless\n// generation method described in:\n//\n//   Bitner, James R., Gideon Ehrlich, and Edward M. Reingold. \n//   \"Efficient generation of the binary reflected Gray code and its applications.\"\n//   Communications of the ACM 19.9 (1976): 517-521.\n\n#ifndef GRAY_CODE_ITERATOR_HPP\n#define GRAY_CODE_ITERATOR_HPP\n\n#include <cstdint>\n#include <numeric>\n#include <type_traits>\n\n#include <boost/iterator/iterator_facade.hpp>\n\ntemplate <typename T>\nclass gray_code_iterator\n\t: public boost::iterator_facade <\n\tgray_code_iterator<T>,\n\tconst T&,\n\tboost::forward_traversal_tag\n\t>\n{\nprivate:\n\ttypedef std::uint_fast8_t focus_ptr_t;\n\tstatic_assert(std::is_integral<T>::value, \"T must be integral\");\n\npublic:\n\tgray_code_iterator() : end_(true), n_(0), a_(0), f_(0) { }\n\n\texplicit gray_code_iterator(int n) : end_(false), n_(n), a_(0), f_(new focus_ptr_t[n + 1])\n\t{\n\t\tassert(n <= sizeof(T) * 8 && \"T not large enough to hold n tuples\");\n\n\t\tstd::iota(f_, f_ + n + 1, 0);\n\n\t\tassert(a_ == 0);\n\t}\n\n\t~gray_code_iterator()\n\t{\n\t\tif (f_)\n\t\t{\n\t\t\tdelete[] f_;\n\t\t}\n\t}\n\nprivate:\n\tfriend class boost::iterator_core_access;\n\n\tvoid increment()\n\t{\n\t\tconst focus_ptr_t j = f_[0];\n\n\t\tif (j == n_)\n\t\t{\n\t\t\tend_ = true;\n\t\t\treturn;\n\t\t}\n\n\t\tf_[0] = 0;\n\t\tf_[j] = f_[j + 1];\n\t\tf_[j + 1] = j + 1;\n\n\t\ta_ ^= (1 << j);\n\t}\n\n\tbool equal(const gray_code_iterator& other) const\n\t{\n\t\treturn end_ == other.end_;\n\t}\n\n\tconst T& dereference() const\n\t{\n\t\treturn a_;\n\t}\n\n\tbool end_;\n\tconst int n_;\n\tT a_;\n\tfocus_ptr_t* f_;\n};\n\n#endif\n", "meta": {"hexsha": "ec298618e9d767b8e491490e7ede9b1e82c2916f", "size": 1690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gray_code_iterator.hpp", "max_stars_repo_name": "euler314/combinatorics", "max_stars_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-12T22:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-21T13:16:09.000Z", "max_issues_repo_path": "gray_code_iterator.hpp", "max_issues_repo_name": "euler314/combinatorics", "max_issues_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gray_code_iterator.hpp", "max_forks_repo_name": "euler314/combinatorics", "max_forks_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T18:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T18:32:14.000Z", "avg_line_length": 18.7777777778, "max_line_length": 91, "alphanum_fraction": 0.6639053254, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7606506635289835, "lm_q1q2_score": 0.5720188632125284}}
{"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 * This tutorial program was contributed by Martin Kronbichler \n */ \n\n\n// @sect3{Include files}  \n\n// 本教程的包含文件与  step-6  中的基本相同。重要的是，我们将使用的TransfiniteInterpolationManifold类是由`deal.II/grid/manifold_lib.h`提供。\n\n#include <deal.II/base/timer.h> \n\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/sparse_matrix.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/grid/manifold_lib.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_generic.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/error_estimator.h> \n#include <deal.II/numerics/vector_tools.h> \n\n#include <fstream> \n\n// 唯一的新include文件是MappingQCache类的文件。\n\n#include <deal.II/fe/mapping_q_cache.h> \n\nnamespace Step65 \n{ \n  using namespace dealii; \n// @sect3{Analytical solution and coefficient}  \n\n// 在这个教程程序中，我们要解决泊松方程，其系数沿半径为0.5的球体跳跃，并使用一个恒定的右手边值 $f(\\mathbf{x}) = -3$  。（这个设置与 step-5 和 step-6 相似，但系数和右手边的具体数值不同）。由于系数的跳跃，分析解必须有一个结点，即系数从一个值切换到另一个值。为了保持简单，我们选择了一个在所有分量中都是二次的分析解，即在半径为0.5的球中为 $u(x,y,z) = x^2 + y^2 + z^2$ ，在域的外部为 $u(x,y,z) = 0.1(x^2 + y^2 + z^2) + 0.25-0.025$ 。这个分析解在内球的系数为0.5，外球的系数为5的情况下与右手边兼容。它也是沿着半径为0.5的圆连续的。\n\n  template <int dim> \n  class ExactSolution : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/ = 0) const override \n    { \n      if (p.norm_square() < 0.25) \n        return p.norm_square(); \n      else \n        return 0.1 * p.norm_square() + (0.25 - 0.025); \n    } \n\n    virtual Tensor<1, dim> \n    gradient(const Point<dim> &p, \n             const unsigned int /*component*/ = 0) const override \n    { \n      if (p.norm_square() < 0.25) \n        return 2. * p; \n      else \n        return 0.2 * p; \n    } \n  }; \n\n  template <int dim> \n  double coefficient(const Point<dim> &p) \n  { \n    if (p.norm_square() < 0.25) \n      return 0.5; \n    else \n      return 5.0; \n  } \n\n//  @sect3{The PoissonProblem class}  \n\n// 泊松问题的实现与我们在  step-5  教程中使用的非常相似。两个主要的区别是，我们向程序中的各个步骤传递了一个映射对象，以便在两种映射表示法之间进行切换，正如介绍中所解释的那样，还有一个`计时器'对象（TimerOutput类型），将用于测量各种情况下的运行时间。(映射对象的概念在 step-10 和 step-11 中首次提出，如果你想查一下这些类的用途的话)。\n\n  template <int dim> \n  class PoissonProblem \n  { \n  public: \n    PoissonProblem(); \n    void run(); \n\n  private: \n    void create_grid(); \n    void setup_system(const Mapping<dim> &mapping); \n    void assemble_system(const Mapping<dim> &mapping); \n    void solve(); \n    void postprocess(const Mapping<dim> &mapping); \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> constraints; \n    SparsityPattern           sparsity_pattern; \n    SparseMatrix<double>      system_matrix; \n    Vector<double>            solution; \n    Vector<double>            system_rhs; \n\n    TimerOutput timer; \n  }; \n\n// 在构造函数中，我们设置了定时器对象来记录墙的时间，但在正常执行过程中是安静的。我们将在 `PoissonProblem::run()` 函数中查询它的计时细节。此外，我们为正在使用的有限元选择了一个相对较高的多项式三度。\n\n  template <int dim> \n  PoissonProblem<dim>::PoissonProblem() \n    : fe(3) \n    , dof_handler(triangulation) \n    , timer(std::cout, TimerOutput::never, TimerOutput::wall_times) \n  {} \n\n//  @sect3{Grid creation and initialization of the manifolds}  \n\n// 接下来的函数介绍了TransfiniteInterpolationManifold的典型用法。第一步是创建所需的网格，这可以通过GridGenerator的两个网格的组合来完成。内球网格是很简单的。我们以原点为中心运行 GridGenerator::hyper_cube() ，半径为0.5（第三个函数参数）。第二个网格更有趣，构建方法如下。我们希望有一个在内部是球形的，但在外表面是平的网格。此外，内球的网格拓扑结构应该与外球的网格兼容，即它们的顶点重合，这样才能使两个网格合并起来。从 GridGenerator::hyper_shell 出来的网格满足了内侧的要求，如果它是用 $2d$ 的粗大单元创建的（在3D中我们将使用6个粗大单元）&ndash；这与球的边界面的单元数量相同。对于外表面，我们利用这样一个事实：没有流形附着的壳表面的6个面将退化为立方体的表面。我们仍然缺少的是外壳边界的半径。由于我们想要一个范围为 $[-1, 1]$ 的立方体，而6单元壳将其8个外顶点放在8条对角线上，我们必须将点 $(\\pm 1, \\pm 1, \\pm 1)$ 转化为半径。显然，在 $d$ 维度上，半径必须是 $\\sqrt{d}$ ，也就是说，对于我们要考虑的三维情况，半径是 $\\sqrt{3}$ 。\n\n// 这样，我们就有了一个计划。在创建了球的内部三角形和外壳的三角形之后，我们将这两个网格合并，但是将GridGenerator中的函数可能从产生的三角形中设置的所有流形移除，以确保我们对流形有充分的控制。特别是，我们希望在细化过程中在边界上添加的额外点能够遵循平坦的流形描述。为了开始添加更合适的流形ID的过程，我们给所有的网格实体（单元、面、线）分配流形ID 0，这些实体以后将与TransfiniteInterpolationManifold相关联。然后，我们必须识别沿着半径为0.5的球体的面和线，并给它们标记一个不同的流形ID，以便随后给这些面和线分配一个SphericalManifold。由于我们在调用 GridGenerator::hyper_ball(), 后丢弃了所有预先存在的流形，我们手动检查了网格的单元格和所有的面。如果四个顶点的半径都是0.5，我们就在球体上找到了一个面，或者像我们在程序中写的那样，有  $r^2-0.25 \\approx 0$  。注意，我们调用`cell->face(f)->set_all_manifold_ids(1)`来设置面和周围线上的流形id。此外，我们希望通过一个材料ID来区分球内和球外的单元，以便于可视化，对应于介绍中的图片。\n\n  template <int dim> \n  void PoissonProblem<dim>::create_grid() \n  { \n    Triangulation<dim> tria_inner; \n    GridGenerator::hyper_ball(tria_inner, Point<dim>(), 0.5); \n\n    Triangulation<dim> tria_outer; \n    GridGenerator::hyper_shell( \n      tria_outer, Point<dim>(), 0.5, std::sqrt(dim), 2 * dim); \n\n    GridGenerator::merge_triangulations(tria_inner, tria_outer, triangulation); \n\n    triangulation.reset_all_manifolds(); \n    triangulation.set_all_manifold_ids(0); \n\n    for (const auto &cell : triangulation.cell_iterators()) \n      { \n        for (const auto &face : cell->face_iterators()) \n          { \n            bool face_at_sphere_boundary = true; \n            for (const auto v : face->vertex_indices()) \n              { \n                if (std::abs(face->vertex(v).norm_square() - 0.25) > 1e-12) \n                  face_at_sphere_boundary = false; \n              } \n            if (face_at_sphere_boundary) \n              face->set_all_manifold_ids(1); \n          } \n        if (cell->center().norm_square() < 0.25) \n          cell->set_material_id(1); \n        else \n          cell->set_material_id(0); \n      } \n\n// 有了所有单元格、面和线的适当标记，我们可以将流形对象附加到这些数字上。流形ID为1的实体将得到一个球形流形，而流形ID为0的其他实体将被分配到TransfiniteInterpolationManifold。正如介绍中提到的，我们必须通过调用 TransfiniteInterpolationManifold::initialize() 显式初始化当前网格的流形，以获取粗略的网格单元和连接到这些单元边界的流形。我们还注意到，我们在这个函数中本地创建的流形对象是允许超出范围的（就像它们在函数范围结束时那样），因为Triangulation对象在内部复制它们。\n\n// 在连接了所有的流形之后，我们最后将去细化网格几次，以创建一个足够大的测试案例。\n\n    triangulation.set_manifold(1, SphericalManifold<dim>()); \n\n    TransfiniteInterpolationManifold<dim> transfinite_manifold; \n    transfinite_manifold.initialize(triangulation); \n    triangulation.set_manifold(0, transfinite_manifold); \n\n    triangulation.refine_global(9 - 2 * dim); \n  } \n\n//  @sect3{Setup of data structures}  \n\n// 下面的函数在其他教程中是众所周知的，它枚举了自由度，创建了一个约束对象并为线性系统设置了一个稀疏矩阵。唯一值得一提的是，该函数接收了一个映射对象的引用，然后我们将其传递给 VectorTools::interpolate_boundary_values() 函数，以确保我们的边界值在用于装配的高阶网格上被评估。在本例中，这并不重要，因为外表面是平的，但对于弯曲的外单元，这将导致边界值的更精确的近似。\n\n  template <int dim> \n  void PoissonProblem<dim>::setup_system(const Mapping<dim> &mapping) \n  { \n    dof_handler.distribute_dofs(fe); \n    std::cout << \"   Number of active cells:       \" \n              << triangulation.n_global_active_cells() << std::endl; \n    std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl; \n\n    { \n      TimerOutput::Scope scope(timer, \"Compute constraints\"); \n\n      constraints.clear(); \n\n      DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n      VectorTools::interpolate_boundary_values( \n        mapping, dof_handler, 0, ExactSolution<dim>(), constraints); \n\n      constraints.close(); \n    } \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n\n    sparsity_pattern.copy_from(dsp); \n    system_matrix.reinit(sparsity_pattern); \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n  } \n// @sect3{Assembly of the system matrix and right hand side}  \n\n// 组装线性系统的函数在前面的教程程序中也是众所周知的。有一点需要注意的是，我们将正交点的数量设置为多项式的度数加2，而不是像其他大多数教程中的度数加1。这是因为我们期望有一些额外的精度，因为映射也涉及到比解的多项式多一度的程度。\n\n// 汇编中唯一有点不寻常的代码是我们计算单元格矩阵的方式。我们没有使用正交点索引、行和矩阵列的三个嵌套循环，而是首先收集形状函数的导数，乘以系数和积分因子`JxW`的乘积的平方根，放在一个单独的矩阵`partial_matrix`中。为了计算单元矩阵，我们在 \"partial_matrix.mTmult(cell_matrix, partial_matrix); \"一行中执行 \"cell_matrix = partial_matrix * transpose(partial_matrix)\"。为了理解这一点，我们要知道矩阵与矩阵的乘法是对`partial_matrix`的各列进行求和。如果我们用 \n// $a(\\mathbf{x}_q)$ 表示系数，临时矩阵的条目是 $\\sqrt{\\text{det}(J) w_q a(x)} \\frac{\\partial \\varphi_i(\\boldsymbol\n//  \\xi_q)}{\\partial x_k}$ 。如果我们将该矩阵的第<i>i</i>行与第<i>j</i>列相乘，我们计算出一个涉及 $\\sum_q \\sum_{k=1}^d \\sqrt{\\text{det}(J) w_q a(x)} \\frac{\\partial\n//  \\varphi_i(\\boldsymbol \\xi_q)}{\\partial x_k} \\sqrt{\\text{det}(J) w_q a(x)}\n//  \\frac{\\partial \\varphi_j(\\boldsymbol \\xi_q)}{\\partial x_k} = \\sum_q\n//  \\sum_{k=1}^d\\text{det}(J) w_q a(x)\\frac{\\partial \\varphi_i(\\boldsymbol\n//  \\xi_q)}{\\partial x_k} \\frac{\\partial \\varphi_j(\\boldsymbol\n//  \\xi_q)}{\\partial x_k}$ 的嵌套和，这正是拉普拉斯方程的双线性形式所需的条款。\n\n// 选择这种有点不寻常的方案的原因是由于计算三维中相对较高的多项式程度的单元矩阵所涉及的繁重工作。由于我们想在这个教程程序中强调映射的成本，我们最好以优化的方式进行装配，以便不追逐已经被社区解决的瓶颈。矩阵-矩阵乘法是HPC背景下最好的优化内核之一， FullMatrix::mTmult() 函数将调用到那些优化的BLAS函数。如果用户在配置deal.II时提供了一个好的BLAS库（如OpenBLAS或英特尔的MKL），那么单元矩阵的计算将执行到接近处理器的峰值算术性能。顺便提一下，尽管有优化的矩阵-矩阵乘法，但目前的策略在复杂性方面是次优的，因为要做的工作与 $(p+1)^9$ 度 $p$ 的运算成正比（这也适用于用FEValues的通常评估）。我们可以通过利用形状函数的张量乘积结构，用 $\\mathcal O((p+1)^7)$ 的操作来计算单元格矩阵，就像交易二中的无矩阵框架那样。我们参考 step-37 和张量积感知评估器FEEvaluation的文档，以了解如何实现更有效的单元矩阵计算的细节。\n\n  template <int dim> \n  void PoissonProblem<dim>::assemble_system(const Mapping<dim> &mapping) \n  { \n    TimerOutput::Scope scope(timer, \"Assemble linear system\"); \n\n    const QGauss<dim> quadrature_formula(fe.degree + 2); \n    FEValues<dim>     fe_values(mapping, \n                            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    FullMatrix<double> partial_matrix(dofs_per_cell, dim * n_q_points); \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_rhs = 0.; \n        fe_values.reinit(cell); \n\n        for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) \n          { \n            const double current_coefficient = \n              coefficient(fe_values.quadrature_point(q_index)); \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              { \n                for (unsigned int d = 0; d < dim; ++d) \n                  partial_matrix(i, q_index * dim + d) = \n                    std::sqrt(fe_values.JxW(q_index) * current_coefficient) * \n                    fe_values.shape_grad(i, q_index)[d]; \n                cell_rhs(i) += \n                  (fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                   (-dim) *                            // f(x_q) \n                   fe_values.JxW(q_index));            // dx \n              } \n          } \n\n        partial_matrix.mTmult(cell_matrix, partial_matrix); \n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global( \n          cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs); \n      } \n  } \n\n//  @sect3{Solution of the linear system}  \n\n// 对于线性系统的求解，我们选择一个简单的雅可比条件共轭梯度求解器，类似于早期教程中的设置。\n\n  template <int dim> \n  void PoissonProblem<dim>::solve() \n  { \n    TimerOutput::Scope scope(timer, \"Solve linear system\"); \n\n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> solver(solver_control); \n\n    PreconditionJacobi<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix); \n\n    solver.solve(system_matrix, solution, system_rhs, preconditioner); \n    constraints.distribute(solution); \n\n    std::cout << \"   Number of solver iterations:  \" \n              << solver_control.last_step() << std::endl; \n  } \n\n//  @sect3{Output of the solution and computation of errors}  \n\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 PoissonProblem<dim>::postprocess(const Mapping<dim> &mapping) \n  { \n    { \n      TimerOutput::Scope scope(timer, \"Write output\"); \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      Vector<double> material_ids(triangulation.n_active_cells()); \n      for (const auto &cell : triangulation.active_cell_iterators()) \n        material_ids[cell->active_cell_index()] = cell->material_id(); \n      data_out.add_data_vector(material_ids, \"material_ids\"); \n\n      data_out.build_patches(mapping, \n                             fe.degree, \n                             DataOut<dim>::curved_inner_cells); \n\n      std::ofstream file( \n        (\"solution-\" + \n         std::to_string(triangulation.n_global_levels() - 10 + 2 * dim) + \n         \".vtu\") \n          .c_str()); \n\n      data_out.write_vtu(file); \n    } \n\n// 后处理函数的下一个操作是对照分析解计算 $L_2$ 和 $H^1$ 误差。由于分析解是一个二次多项式，我们期望在这一点上得到一个非常准确的结果。如果我们是在一个具有平面面的简单网格上求解，并且系数的跳动与单元间的面对齐，那么我们会期望数值结果与分析解相吻合，直至舍去精度。然而，由于我们使用的是跟随球体的变形单元，这些单元只能由4度的多项式跟踪（比有限元的度数多一个），我们会发现在 $10^{-7}$ 附近有一个误差。我们可以通过增加多项式的度数或细化网格来获得更多的精度。\n\n    { \n      TimerOutput::Scope scope(timer, \"Compute error norms\"); \n\n      Vector<double> norm_per_cell_p(triangulation.n_active_cells()); \n\n      VectorTools::integrate_difference(mapping, \n                                        dof_handler, \n                                        solution, \n                                        ExactSolution<dim>(), \n                                        norm_per_cell_p, \n                                        QGauss<dim>(fe.degree + 2), \n                                        VectorTools::L2_norm); \n      std::cout << \"   L2 error vs exact solution:   \" \n                << norm_per_cell_p.l2_norm() << std::endl; \n\n      VectorTools::integrate_difference(mapping, \n                                        dof_handler, \n                                        solution, \n                                        ExactSolution<dim>(), \n                                        norm_per_cell_p, \n                                        QGauss<dim>(fe.degree + 2), \n                                        VectorTools::H1_norm); \n      std::cout << \"   H1 error vs exact solution:   \" \n                << norm_per_cell_p.l2_norm() << std::endl; \n    } \n\n// 我们在这里做的最后一个后处理操作是用KellyErrorEstimator计算出一个误差估计。我们使用了与 step-6 教程程序中完全相同的设置，只是我们还交出了映射，以确保误差是沿着曲线元素评估的，与程序的其余部分一致。然而，我们并没有真正使用这里的结果来驱动网格适应步骤（会沿着球体细化材料界面周围的网格），因为这里的重点是这个操作的成本。\n\n    { \n      TimerOutput::Scope scope(timer, \"Compute error estimator\"); \n\n      Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n      KellyErrorEstimator<dim>::estimate( \n        mapping, \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      std::cout << \"   Max cell-wise error estimate: \" \n                << estimated_error_per_cell.linfty_norm() << std::endl; \n    } \n  } \n\n//  @sect3{The PoissonProblem::run() function}  \n\n// 最后，我们定义了`run()`函数，控制我们如何执行这个程序（由main()函数以常规方式调用）。我们首先调用`create_grid()`函数，用适当的流形设置我们的几何体。然后我们运行两个求解器链的实例，从方程的设置开始，组装线性系统，用一个简单的迭代求解器求解，以及上面讨论的后处理。这两个实例在使用映射的方式上有所不同。第一个使用传统的MappingQGeneric映射对象，我们将其初始化为比有限元多一级的程度；毕竟，我们期望几何表示是瓶颈，因为分析解只是二次多项式。实际上，事情在相当程度上是相互关联的，因为实坐标中多项式的评估涉及到高阶多项式的映射，而高阶多项式代表一些光滑的有理函数。因此，高阶多项式还是有回报的，所以进一步增加映射的度数是没有意义的)。一旦第一遍完成，我们就让定时器打印出各个阶段的计算时间的摘要。\n\n  template <int dim> \n  void PoissonProblem<dim>::run() \n  { \n    create_grid(); \n\n    { \n      std::cout << std::endl \n                << \"====== Running with the basic MappingQGeneric class ====== \" \n                << std::endl \n                << std::endl; \n\n      MappingQGeneric<dim> mapping(fe.degree + 1); \n      setup_system(mapping); \n      assemble_system(mapping); \n      solve(); \n      postprocess(mapping); \n\n      timer.print_summary(); \n      timer.reset(); \n    } \n\n// 对于第二个实例，我们转而设置了MappingQCache类。它的使用非常简单。在构建好它之后（考虑到我们希望它在其他情况下显示正确的度数功能，所以用度数），我们通过 MappingQCache::initialize() 函数填充缓存。在这个阶段，我们为缓存指定我们想要使用的映射（很明显，与之前的MappingQGeneric相同，以便重复相同的计算），然后再次运行相同的函数，现在交出修改后的映射。最后，我们再次打印重置后的累计壁挂时间，看看这些时间与原来的设置相比如何。\n\n    { \n      std::cout \n        << \"====== Running with the optimized MappingQCache class ====== \" \n        << std::endl \n        << std::endl; \n\n      MappingQCache<dim> mapping(fe.degree + 1); \n      { \n        TimerOutput::Scope scope(timer, \"Initialize mapping cache\"); \n        mapping.initialize(MappingQGeneric<dim>(fe.degree + 1), triangulation); \n      } \n      std::cout << \"   Memory consumption cache:     \" \n                << 1e-6 * mapping.memory_consumption() << \" MB\" << std::endl; \n\n      setup_system(mapping); \n      assemble_system(mapping); \n      solve(); \n      postprocess(mapping); \n\n      timer.print_summary(); \n    } \n  } \n} // namespace Step65 \n\nint main() \n{ \n  Step65::PoissonProblem<3> test_program; \n  test_program.run(); \n  return 0; \n} \n\n\n", "meta": {"hexsha": "39cc3f7d3ce3906cf79606c6fe07cdfdc2fe8777", "size": 18426, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-65/step-65.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-65/step-65.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-65/step-65.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.3194748359, "max_line_length": 555, "alphanum_fraction": 0.66015413, "num_tokens": 7665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872075132152, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.5719159284851301}}
{"text": "// Copyright (c) 2020 Chris Richardson\n// FEniCS Project\n// SPDX-License-Identifier:    MIT\n\n#include \"polyset.h\"\n#include \"cell.h\"\n#include \"indexing.h\"\n#include <Eigen/Dense>\n#include <array>\n#include <cmath>\n\nusing namespace basix;\n\nnamespace\n{\n// Compute coefficients in the Jacobi Polynomial recurrence relation\nconstexpr std::array<double, 3> jrc(int a, int n)\n{\n  double an = (a + 2 * n + 1) * (a + 2 * n + 2)\n              / static_cast<double>(2 * (n + 1) * (a + n + 1));\n  double bn = a * a * (a + 2 * n + 1)\n              / static_cast<double>(2 * (n + 1) * (a + n + 1) * (a + 2 * n));\n  double cn = n * (a + n) * (a + 2 * n + 2)\n              / static_cast<double>((n + 1) * (a + n + 1) * (a + 2 * n));\n  return {an, bn, cn};\n}\n//-----------------------------------------------------------------------------\n// Compute the complete set of derivatives from 0 to nderiv, for all the\n// polynomials up to order n on a line segment. The polynomials used are\n// Legendre Polynomials, with the recurrence relation given by\n// n P(n) = (2n - 1) x P_{n-1} - (n - 1) P_{n-2} in the interval [-1, 1]. The\n// range is rescaled here to [0, 1].\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_line_derivs(int degree, int nderiv, const Eigen::ArrayXXd& x)\n{\n  assert(x.cols() == 1);\n  const Eigen::ArrayXXd X = x * 2.0 - 1.0;\n\n  const int m = (degree + 1);\n\n  std::vector<Eigen::ArrayXXd> dresult(nderiv + 1);\n  for (int k = 0; k < nderiv + 1; ++k)\n  {\n    // Get reference to this derivative\n    Eigen::ArrayXXd result(x.rows(), m);\n\n    if (k == 0)\n      result.col(0).fill(1.0);\n    else\n      result.col(0).setZero();\n\n    for (int p = 1; p < degree + 1; ++p)\n    {\n      const double a = 1.0 - 1.0 / static_cast<double>(p);\n      result.col(p) = X * result.col(p - 1) * (a + 1.0);\n      if (k > 0)\n        result.col(p) += 2 * k * dresult[k - 1].col(p - 1) * (a + 1.0);\n      if (p > 1)\n        result.col(p) -= result.col(p - 2) * a;\n    }\n\n    dresult[k] = result;\n  }\n\n  // Normalise\n  for (int k = 0; k < nderiv + 1; ++k)\n  {\n    for (int p = 0; p < degree + 1; ++p)\n      dresult[k].col(p) *= std::sqrt(p + 0.5);\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\n// Compute the complete set of derivatives from 0 to nderiv, for all the\n// polynomials up to order n on a triangle in [0, 1][0, 1].\n// The polynomials P_{pq} are built up in sequence, firstly along q = 0, which\n// is a line segment, as in tabulate_polyset_interval_derivs above, but with a\n// change of variables. The polynomials are then extended in the q direction,\n// using the relation given in Sherwin and Karniadakis 1995\n// (https://doi.org/10.1016/0045-7825(94)00745-9)\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_triangle_derivs(int n, int nderiv, const Eigen::ArrayXXd& pts)\n\n{\n  assert(pts.cols() == 2);\n\n  Eigen::ArrayXXd x = pts * 2.0 - 1.0;\n\n  const int m = (n + 1) * (n + 2) / 2;\n  const int md = (nderiv + 1) * (nderiv + 2) / 2;\n  std::vector<Eigen::ArrayXXd> dresult(md);\n\n  // f3 = ((1-y)/2)^2\n  const Eigen::ArrayXd f3 = (1.0 - x.col(1)).square() * 0.25;\n\n  // Iterate over derivatives in increasing order, since higher derivatives\n  // depend on earlier calculations\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int k = 0; k < nderiv + 1; ++k)\n  {\n    for (int kx = 0; kx < k + 1; ++kx)\n    {\n      const int ky = k - kx;\n\n      if (kx == 0 and ky == 0)\n        result.col(0).fill(1.0);\n      else\n        result.col(0).setZero();\n\n      for (int p = 1; p < n + 1; ++p)\n      {\n        const double a\n            = static_cast<double>(2 * p - 1) / static_cast<double>(p);\n        result.col(idx(p, 0))\n            = (x.col(0) + 0.5 * x.col(1) + 0.5) * result.col(idx(p - 1, 0)) * a;\n        if (kx > 0)\n        {\n          result.col(idx(p, 0))\n              += 2 * kx * a * dresult[idx(kx - 1, ky)].col(idx(p - 1, 0));\n        }\n\n        if (ky > 0)\n        {\n          result.col(idx(p, 0))\n              += ky * a * dresult[idx(kx, ky - 1)].col(idx(p - 1, 0));\n        }\n\n        if (p > 1)\n        {\n          // y^2 terms\n          result.col(idx(p, 0)) -= f3 * result.col(idx(p - 2, 0)) * (a - 1.0);\n\n          if (ky > 0)\n          {\n            result.col(idx(p, 0))\n                -= ky * (x.col(1) - 1.0)\n                   * dresult[idx(kx, ky - 1)].col(idx(p - 2, 0)) * (a - 1.0);\n          }\n\n          if (ky > 1)\n          {\n            result.col(idx(p, 0))\n                -= ky * (ky - 1) * dresult[idx(kx, ky - 2)].col(idx(p - 2, 0))\n                   * (a - 1.0);\n          }\n        }\n      }\n\n      for (int p = 0; p < n; ++p)\n      {\n        result.col(idx(p, 1))\n            = result.col(idx(p, 0)) * (x.col(1) * (1.5 + p) + 0.5 + p);\n        if (ky > 0)\n        {\n          result.col(idx(p, 1))\n              += 2 * ky * (1.5 + p) * dresult[idx(kx, ky - 1)].col(idx(p, 0));\n        }\n\n        for (int q = 1; q < n - p; ++q)\n        {\n          const auto [a1, a2, a3] = jrc(2 * p + 1, q);\n          result.col(idx(p, q + 1))\n              = result.col(idx(p, q)) * (x.col(1) * a1 + a2)\n                - result.col(idx(p, q - 1)) * a3;\n          if (ky > 0)\n          {\n            result.col(idx(p, q + 1))\n                += 2 * ky * a1 * dresult[idx(kx, ky - 1)].col(idx(p, q));\n          }\n        }\n      }\n\n      // Store this derivative\n      dresult[idx(kx, ky)] = result;\n    }\n  }\n\n  // Normalisation\n  for (std::size_t j = 0; j < dresult.size(); ++j)\n  {\n    for (int p = 0; p < n + 1; ++p)\n      for (int q = 0; q < n - p + 1; ++q)\n        dresult[j].col(idx(p, q)) *= std::sqrt((p + 0.5) * (p + q + 1));\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_tetrahedron_derivs(int n, int nderiv,\n                                    const Eigen::ArrayXXd& pts)\n{\n  assert(pts.cols() == 3);\n\n  Eigen::ArrayXXd x = pts * 2.0 - 1.0;\n\n  const int m = (n + 1) * (n + 2) * (n + 3) / 6;\n  const int md = (nderiv + 1) * (nderiv + 2) * (nderiv + 3) / 6;\n  std::vector<Eigen::ArrayXXd> dresult(md);\n\n  const Eigen::ArrayXd f2 = (x.col(1) + x.col(2)).square() * 0.25;\n  const Eigen::ArrayXd f3 = (1.0 + x.col(1) * 2.0 + x.col(2)) * 0.5;\n  const Eigen::ArrayXd f4 = (1.0 - x.col(2)) * 0.5;\n  const Eigen::ArrayXd f5 = f4 * f4;\n\n  // Traverse derivatives in increasing order\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int k = 0; k < nderiv + 1; ++k)\n  {\n    for (int j = 0; j < k + 1; ++j)\n    {\n      for (int kx = 0; kx < j + 1; ++kx)\n      {\n        const int ky = j - kx;\n        const int kz = k - j;\n        if (kx == 0 and ky == 0 and kz == 0)\n          result.col(0).fill(1.0);\n        else\n          result.col(0).setZero();\n\n        for (int p = 1; p < n + 1; ++p)\n        {\n          double a = static_cast<double>(2 * p - 1) / static_cast<double>(p);\n          result.col(idx(p, 0, 0))\n              = (x.col(0) + 0.5 * (x.col(1) + x.col(2)) + 1.0)\n                * result.col(idx(p - 1, 0, 0)) * a;\n          if (kx > 0)\n          {\n            result.col(idx(p, 0, 0))\n                += 2 * kx * a\n                   * dresult[idx(kx - 1, ky, kz)].col(idx(p - 1, 0, 0));\n          }\n\n          if (ky > 0)\n          {\n            result.col(idx(p, 0, 0))\n                += ky * a * dresult[idx(kx, ky - 1, kz)].col(idx(p - 1, 0, 0));\n          }\n\n          if (kz > 0)\n          {\n            result.col(idx(p, 0, 0))\n                += kz * a * dresult[idx(kx, ky, kz - 1)].col(idx(p - 1, 0, 0));\n          }\n\n          if (p > 1)\n          {\n            result.col(idx(p, 0, 0))\n                -= f2 * result.col(idx(p - 2, 0, 0)) * (a - 1.0);\n            if (ky > 0)\n            {\n              result.col(idx(p, 0, 0))\n                  -= ky * (x.col(1) + x.col(2))\n                     * dresult[idx(kx, ky - 1, kz)].col(idx(p - 2, 0, 0))\n                     * (a - 1.0);\n            }\n\n            if (ky > 1)\n            {\n              result.col(idx(p, 0, 0))\n                  -= ky * (ky - 1)\n                     * dresult[idx(kx, ky - 2, kz)].col(idx(p - 2, 0, 0))\n                     * (a - 1.0);\n            }\n\n            if (kz > 0)\n            {\n              result.col(idx(p, 0, 0))\n                  -= kz * (x.col(1) + x.col(2))\n                     * dresult[idx(kx, ky, kz - 1)].col(idx(p - 2, 0, 0))\n                     * (a - 1.0);\n            }\n\n            if (kz > 1)\n            {\n              result.col(idx(p, 0, 0))\n                  -= kz * (kz - 1)\n                     * dresult[idx(kx, ky, kz - 2)].col(idx(p - 2, 0, 0))\n                     * (a - 1.0);\n            }\n\n            if (ky > 0 and kz > 0)\n            {\n              result.col(idx(p, 0, 0))\n                  -= 2.0 * ky * kz\n                     * dresult[idx(kx, ky - 1, kz - 1)].col(idx(p - 2, 0, 0))\n                     * (a - 1.0);\n            }\n          }\n        }\n\n        for (int p = 0; p < n; ++p)\n        {\n          result.col(idx(p, 1, 0))\n              = result.col(idx(p, 0, 0))\n                * ((1.0 + x.col(1)) * p\n                   + (2.0 + x.col(1) * 3.0 + x.col(2)) * 0.5);\n          if (ky > 0)\n          {\n            result.col(idx(p, 1, 0))\n                += 2 * ky * dresult[idx(kx, ky - 1, kz)].col(idx(p, 0, 0))\n                   * (1.5 + p);\n          }\n\n          if (kz > 0)\n          {\n            result.col(idx(p, 1, 0))\n                += kz * dresult[idx(kx, ky, kz - 1)].col(idx(p, 0, 0));\n          }\n\n          for (int q = 1; q < n - p; ++q)\n          {\n            auto [aq, bq, cq] = jrc(2 * p + 1, q);\n            result.col(idx(p, q + 1, 0))\n                = result.col(idx(p, q, 0)) * (f3 * aq + f4 * bq)\n                  - result.col(idx(p, q - 1, 0)) * f5 * cq;\n\n            if (ky > 0)\n            {\n              result.col(idx(p, q + 1, 0))\n                  += 2 * ky * dresult[idx(kx, ky - 1, kz)].col(idx(p, q, 0))\n                     * aq;\n            }\n\n            if (kz > 0)\n            {\n              result.col(idx(p, q + 1, 0))\n                  += kz * dresult[idx(kx, ky, kz - 1)].col(idx(p, q, 0))\n                         * (aq - bq)\n                     + kz * (1.0 - x.col(2))\n                           * dresult[idx(kx, ky, kz - 1)].col(idx(p, q - 1, 0))\n                           * cq;\n            }\n\n            if (kz > 1)\n            {\n              // Quadratic term in z\n              result.col(idx(p, q + 1, 0))\n                  -= kz * (kz - 1)\n                     * dresult[idx(kx, ky, kz - 2)].col(idx(p, q - 1, 0)) * cq;\n            }\n          }\n        }\n\n        for (int p = 0; p < n; ++p)\n        {\n          for (int q = 0; q < n - p; ++q)\n          {\n            result.col(idx(p, q, 1))\n                = result.col(idx(p, q, 0))\n                  * ((1.0 + p + q) + x.col(2) * (2.0 + p + q));\n            if (kz > 0)\n            {\n              result.col(idx(p, q, 1))\n                  += 2 * kz * (2.0 + p + q)\n                     * dresult[idx(kx, ky, kz - 1)].col(idx(p, q, 0));\n            }\n          }\n        }\n\n        for (int p = 0; p < n - 1; ++p)\n        {\n          for (int q = 0; q < n - p - 1; ++q)\n          {\n            for (int r = 1; r < n - p - q; ++r)\n            {\n              auto [ar, br, cr] = jrc(2 * p + 2 * q + 2, r);\n              result.col(idx(p, q, r + 1))\n                  = result.col(idx(p, q, r)) * (x.col(2) * ar + br)\n                    - result.col(idx(p, q, r - 1)) * cr;\n              if (kz > 0)\n              {\n                result.col(idx(p, q, r + 1))\n                    += 2 * kz * ar\n                       * dresult[idx(kx, ky, kz - 1)].col(idx(p, q, r));\n              }\n            }\n          }\n        }\n\n        // Store this derivative\n        dresult[idx(kx, ky, kz)] = result;\n      }\n    }\n  }\n\n  for (Eigen::ArrayXXd& result : dresult)\n  {\n    for (int p = 0; p < n + 1; ++p)\n    {\n      for (int q = 0; q < n - p + 1; ++q)\n      {\n        for (int r = 0; r < n - p - q + 1; ++r)\n        {\n          result.col(idx(p, q, r))\n              *= std::sqrt((p + 0.5) * (p + q + 1.0) * (p + q + r + 1.5));\n        }\n      }\n    }\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_pyramid_derivs(int n, int nderiv, const Eigen::ArrayXXd& pts)\n{\n  assert(pts.cols() == 3);\n\n  Eigen::ArrayXXd x = pts * 2.0 - 1.0;\n\n  const int m = (n + 1) * (n + 2) * (2 * n + 3) / 6;\n  const int md = (nderiv + 1) * (nderiv + 2) * (nderiv + 3) / 6;\n  std::vector<Eigen::ArrayXXd> dresult(md);\n\n  // Indexing for pyramidal basis functions\n  auto pyr_idx = [&n](int p, int q, int r) -> int {\n    const int rv = n - r + 1;\n    const int r0 = r * (n + 1) * (n - r + 2) + (2 * r - 1) * (r - 1) * r / 6;\n    return r0 + p * rv + q;\n  };\n\n  const Eigen::ArrayXd f2 = (1.0 - x.col(2)).square() * 0.25;\n\n  // Traverse derivatives in increasing order\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int k = 0; k < nderiv + 1; ++k)\n  {\n    for (int j = 0; j < k + 1; ++j)\n    {\n      for (int kx = 0; kx < j + 1; ++kx)\n      {\n        const int ky = j - kx;\n        const int kz = k - j;\n        result.setZero();\n\n        const int pyramidal_index = pyr_idx(0, 0, 0);\n        assert(pyramidal_index < m);\n        if (kx == 0 and ky == 0 and kz == 0)\n          result.col(pyramidal_index).fill(1.0);\n        else\n          result.col(pyramidal_index).setZero();\n\n        // r = 0\n        for (int p = 0; p < n + 1; ++p)\n        {\n          if (p > 0)\n          {\n            const double a\n                = static_cast<double>(p - 1) / static_cast<double>(p);\n            result.col(pyr_idx(p, 0, 0)) = (0.5 + x.col(0) + x.col(2) * 0.5)\n                                           * result.col(pyr_idx(p - 1, 0, 0))\n                                           * (a + 1.0);\n            if (kx > 0)\n            {\n              result.col(pyr_idx(p, 0, 0))\n                  += 2.0 * kx\n                     * dresult[idx(kx - 1, ky, kz)].col(pyr_idx(p - 1, 0, 0))\n                     * (a + 1.0);\n            }\n\n            if (kz > 0)\n            {\n              result.col(pyr_idx(p, 0, 0))\n                  += kz * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p - 1, 0, 0))\n                     * (a + 1.0);\n            }\n\n            if (p > 1)\n            {\n              result.col(pyr_idx(p, 0, 0))\n                  -= f2 * result.col(pyr_idx(p - 2, 0, 0)) * a;\n\n              if (kz > 0)\n              {\n                result.col(pyr_idx(p, 0, 0))\n                    += kz * (1.0 - x.col(2))\n                       * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p - 2, 0, 0))\n                       * a;\n              }\n\n              if (kz > 1)\n              {\n                // quadratic term in z\n                result.col(pyr_idx(p, 0, 0))\n                    -= kz * (kz - 1)\n                       * dresult[idx(kx, ky, kz - 2)].col(pyr_idx(p - 2, 0, 0))\n                       * a;\n              }\n            }\n          }\n\n          for (int q = 1; q < n + 1; ++q)\n          {\n            const double a\n                = static_cast<double>(q - 1) / static_cast<double>(q);\n            result.col(pyr_idx(p, q, 0)) = (0.5 + x.col(1) + x.col(2) * 0.5)\n                                           * result.col(pyr_idx(p, q - 1, 0))\n                                           * (a + 1.0);\n            if (ky > 0)\n            {\n              result.col(pyr_idx(p, q, 0))\n                  += 2.0 * ky\n                     * dresult[idx(kx, ky - 1, kz)].col(pyr_idx(p, q - 1, 0))\n                     * (a + 1.0);\n            }\n\n            if (kz > 0)\n            {\n              result.col(pyr_idx(p, q, 0))\n                  += kz * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p, q - 1, 0))\n                     * (a + 1.0);\n            }\n\n            if (q > 1)\n            {\n              result.col(pyr_idx(p, q, 0))\n                  -= f2 * result.col(pyr_idx(p, q - 2, 0)) * a;\n\n              if (kz > 0)\n              {\n                result.col(pyr_idx(p, q, 0))\n                    += kz * (1.0 - x.col(2))\n                       * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p, q - 2, 0))\n                       * a;\n              }\n\n              if (kz > 1)\n              {\n                result.col(pyr_idx(p, q, 0))\n                    -= kz * (kz - 1)\n                       * dresult[idx(kx, ky, kz - 2)].col(pyr_idx(p, q - 2, 0))\n                       * a;\n              }\n            }\n          }\n        }\n\n        // Extend into r > 0\n        for (int p = 0; p < n; ++p)\n        {\n          for (int q = 0; q < n; ++q)\n          {\n            result.col(pyr_idx(p, q, 1))\n                = result.col(pyr_idx(p, q, 0))\n                  * ((1.0 + p + q) + x.col(2) * (2.0 + p + q));\n            if (kz > 0)\n            {\n              result.col(pyr_idx(p, q, 1))\n                  += 2 * kz * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p, q, 0))\n                     * (2.0 + p + q);\n            }\n          }\n        }\n\n        for (int r = 1; r < n + 1; ++r)\n        {\n          for (int p = 0; p < n - r; ++p)\n          {\n            for (int q = 0; q < n - r; ++q)\n            {\n              auto [ar, br, cr] = jrc(2 * p + 2 * q + 2, r);\n              result.col(pyr_idx(p, q, r + 1))\n                  = result.col(pyr_idx(p, q, r)) * (x.col(2) * ar + br)\n                    - result.col(pyr_idx(p, q, r - 1)) * cr;\n              if (kz > 0)\n              {\n                result.col(pyr_idx(p, q, r + 1))\n                    += ar * 2 * kz\n                       * dresult[idx(kx, ky, kz - 1)].col(pyr_idx(p, q, r));\n              }\n            }\n          }\n        }\n\n        dresult[idx(kx, ky, kz)] = result;\n      }\n    }\n  }\n\n  for (Eigen::ArrayXXd& result : dresult)\n  {\n    for (int r = 0; r < n + 1; ++r)\n    {\n      for (int p = 0; p < n - r + 1; ++p)\n\n      {\n        for (int q = 0; q < n - r + 1; ++q)\n        {\n          result.col(pyr_idx(p, q, r))\n              *= std::sqrt((q + 0.5) * (p + 0.5) * (p + q + r + 1.5));\n        }\n      }\n    }\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_quad_derivs(int n, int nderiv, const Eigen::ArrayXXd& pts)\n{\n  assert(pts.cols() == 2);\n  const int m = (n + 1) * (n + 1);\n  const int md = (nderiv + 1) * (nderiv + 2) / 2;\n\n  std::vector<Eigen::ArrayXXd> dresult(md);\n  std::vector<Eigen::ArrayXXd> px\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(0));\n  std::vector<Eigen::ArrayXXd> py\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(1));\n\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int kx = 0; kx < nderiv + 1; ++kx)\n  {\n    for (int ky = 0; ky < nderiv + 1 - kx; ++ky)\n    {\n      int c = 0;\n      for (int i = 0; i < px[kx].cols(); ++i)\n        for (int j = 0; j < py[ky].cols(); ++j)\n          result.col(c++) = px[kx].col(i) * py[ky].col(j);\n      dresult[idx(kx, ky)] = result;\n    }\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_hex_derivs(int n, int nderiv, const Eigen::ArrayXXd& pts)\n{\n  assert(pts.cols() == 3);\n  const int m = (n + 1) * (n + 1) * (n + 1);\n  const int md = (nderiv + 1) * (nderiv + 2) * (nderiv + 3) / 6;\n\n  std::vector<Eigen::ArrayXXd> px\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(0));\n  std::vector<Eigen::ArrayXXd> py\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(1));\n  std::vector<Eigen::ArrayXXd> pz\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(2));\n\n  std::vector<Eigen::ArrayXXd> dresult(md);\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int kx = 0; kx < nderiv + 1; ++kx)\n  {\n    for (int ky = 0; ky < nderiv + 1 - kx; ++ky)\n    {\n      for (int kz = 0; kz < nderiv + 1 - kx - ky; ++kz)\n      {\n        int c = 0;\n        for (int i = 0; i < px[kx].cols(); ++i)\n          for (int j = 0; j < py[ky].cols(); ++j)\n            for (int k = 0; k < pz[kz].cols(); ++k)\n              result.col(c++) = px[kx].col(i) * py[ky].col(j) * pz[kz].col(k);\n\n        dresult[idx(kx, ky, kz)] = result;\n      }\n    }\n  }\n\n  return dresult;\n}\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd>\ntabulate_polyset_prism_derivs(int n, int nderiv, const Eigen::ArrayXXd& pts)\n{\n  assert(pts.cols() == 3);\n  const int m = (n + 1) * (n + 1) * (n + 2) / 2;\n  const int md = (nderiv + 1) * (nderiv + 2) * (nderiv + 3) / 6;\n\n  std::vector<Eigen::ArrayXXd> pxy\n      = tabulate_polyset_triangle_derivs(n, nderiv, pts.leftCols(2));\n  std::vector<Eigen::ArrayXXd> pz\n      = tabulate_polyset_line_derivs(n, nderiv, pts.col(2));\n\n  std::vector<Eigen::ArrayXXd> dresult(md);\n  Eigen::ArrayXXd result(pts.rows(), m);\n  for (int kx = 0; kx < nderiv + 1; ++kx)\n  {\n    for (int ky = 0; ky < nderiv + 1 - kx; ++ky)\n    {\n      for (int kz = 0; kz < nderiv + 1 - kx - ky; ++kz)\n      {\n        int c = 0;\n        for (int i = 0; i < pxy[idx(kx, ky)].cols(); ++i)\n          for (int k = 0; k < pz[kz].cols(); ++k)\n            result.col(c++) = pxy[idx(kx, ky)].col(i) * pz[kz].col(k);\n\n        dresult[idx(kx, ky, kz)] = result;\n      }\n    }\n  }\n\n  return dresult;\n}\n} // namespace\n//-----------------------------------------------------------------------------\nstd::vector<Eigen::ArrayXXd> polyset::tabulate(cell::type celltype, int n,\n                                               int nderiv,\n                                               const Eigen::ArrayXXd& pts)\n{\n  switch (celltype)\n  {\n  case cell::type::interval:\n    return tabulate_polyset_line_derivs(n, nderiv, pts);\n  case cell::type::triangle:\n    return tabulate_polyset_triangle_derivs(n, nderiv, pts);\n  case cell::type::tetrahedron:\n    return tabulate_polyset_tetrahedron_derivs(n, nderiv, pts);\n  case cell::type::quadrilateral:\n    return tabulate_polyset_quad_derivs(n, nderiv, pts);\n  case cell::type::prism:\n    return tabulate_polyset_prism_derivs(n, nderiv, pts);\n  case cell::type::pyramid:\n    return tabulate_polyset_pyramid_derivs(n, nderiv, pts);\n  case cell::type::hexahedron:\n    return tabulate_polyset_hex_derivs(n, nderiv, pts);\n  default:\n    throw std::runtime_error(\"Polynomial set: Unsupported cell type\");\n  }\n}\n//-----------------------------------------------------------------------------\nint polyset::dim(cell::type celltype, int n)\n{\n  switch (celltype)\n  {\n  case cell::type::triangle:\n    return (n + 1) * (n + 2) / 2;\n  case cell::type::tetrahedron:\n    return (n + 1) * (n + 2) * (n + 3) / 6;\n  case cell::type::prism:\n    return (n + 1) * (n + 1) * (n + 2) / 2;\n  case cell::type::pyramid:\n    return (n + 1) * (n + 2) * (2 * n + 3) / 6;\n  case cell::type::interval:\n    return (n + 1);\n  case cell::type::quadrilateral:\n    return (n + 1) * (n + 1);\n  case cell::type::hexahedron:\n    return (n + 1) * (n + 1) * (n + 1);\n  default:\n    return 1;\n  }\n}\n//-----------------------------------------------------------------------------\n", "meta": {"hexsha": "4062cbe98b75ce1225747467ef57338e64916406", "size": 23008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/core/polyset.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/core/polyset.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/core/polyset.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": 30.7593582888, "max_line_length": 80, "alphanum_fraction": 0.3973400556, "num_tokens": 7753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.5719159204225649}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\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,\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//\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#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <rl/math/Polynomial.h>\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cout << \"Usage: rlPolynomialRootsDemo C0 ... CN\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\tstd::vector<rl::math::Real> c(argc - 1);\n\t\n\tfor (std::size_t i = 0; i < c.size(); ++i)\n\t{\n\t\tc[i] = boost::lexical_cast<rl::math::Real>(argv[i + 1]);\n\t\tstd::cout << (i > 0 ? \" + \" : \"\") << c[i] << \" * x^\" << i;\n\t}\n\t\n\tstd::cout << \" = 0\" << std::endl;\n\t\n\tstd::vector<rl::math::Real> roots = rl::math::Polynomial<rl::math::Real>::realRoots(c);\n\t\n\tstd::cout << roots.size() << \" solution\" << (roots.size() != 1 ? \"(s)\" : \"\") << std::endl;\n\t\n\tfor (std::size_t i = 0; i < roots.size(); ++i)\n\t{\n\t\tstd::cout << \"x[\" << i << \"] = \" << roots[i] << std::endl;\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ffa753c279492a13e37cbca3dbb7d0446be270e3", "size": 2185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/rlPolynomialRootsDemo/rlPolynomialRootsDemo.cpp", "max_stars_repo_name": "Broekman/rl", "max_stars_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "demos/rlPolynomialRootsDemo/rlPolynomialRootsDemo.cpp", "max_issues_repo_name": "jencureboy/rl", "max_issues_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "demos/rlPolynomialRootsDemo/rlPolynomialRootsDemo.cpp", "max_forks_repo_name": "jencureboy/rl", "max_forks_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 35.8196721311, "max_line_length": 91, "alphanum_fraction": 0.6805491991, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.5717615838341463}}
{"text": "// Copyright (c) 2013, Manuel Blum\n// All rights reserved.\n\n// Define this symbol to enable runtime tests for allocations\n//#define EIGEN_RUNTIME_NO_MALLOC\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <string>\n#include <ctime>\n#include \"nn.h\"\n\nusing namespace std;\n\ntypedef vector<int> vi;\ntypedef vector<vi> vvi;\ninline void swap(int &val)\n{\n    val = (val << 24) | ((val << 8) & 0x00ff0000) | ((val >> 8) & 0x0000ff00) | (val >> 24);\n}\nclass batch_manager\n{\n    int num_samples;\n    int current_count;\n    int batch_size;\n\n  public:\n    batch_manager(int num_samples, int batch_size)\n    {\n        this->num_samples = num_samples;\n        this->batch_size = batch_size;\n        current_count = 0;\n    }\n    pair<int, int> next_batch()\n    {\n        pair<int, int> res = make_pair(current_count, current_count + batch_size);\n        if (current_count + batch_size > num_samples)\n        {\n            //cout << \"Current count: \" << current_count << endl;\n            if (current_count == num_samples)\n            {\n                current_count = 0;\n                return make_pair(0, batch_size);\n            }\n            res.second = num_samples;\n            current_count = 0;\n\n            return res;\n        }\n        current_count += res.second - res.first;\n        return res;\n    }\n};\nmatrix_t read_mnist_images(std::string filename)\n{\n\n    matrix_t X;\n    std::ifstream fs(filename.c_str(), std::ios::binary);\n    if (fs)\n    {\n        int magic_number, num_images, num_rows, num_columns;\n        fs.read((char *)&magic_number, sizeof(magic_number));\n        fs.read((char *)&num_images, sizeof(num_images));\n        fs.read((char *)&num_rows, sizeof(num_rows));\n        fs.read((char *)&num_columns, sizeof(num_columns));\n        if (magic_number != 2051)\n        {\n            swap(magic_number);\n            swap(num_images);\n            swap(num_rows);\n            swap(num_columns);\n        }\n\n        X = matrix_t::Zero(num_images, num_rows * num_columns);\n\n        for (size_t i = 0; i < num_images; ++i)\n        {\n            for (size_t j = 0; j < num_rows * num_columns; ++j)\n            {\n                unsigned char temp = 0;\n                fs.read((char *)&temp, sizeof(temp));\n                X(i, j) = (double)temp;\n            }\n        }\n        fs.close();\n    }\n    else\n    {\n        std::cout << \"error reading file: \" << filename << std::endl;\n        exit(1);\n    }\n    return X;\n}\n\nmatrix_t read_mnist_labels(std::string filename)\n{\n    matrix_t Y;\n    std::ifstream fs(filename.c_str(), std::ios::binary);\n    if (fs)\n    {\n        int magic_number, num_images, num_rows, num_columns;\n        fs.read((char *)&magic_number, sizeof(magic_number));\n        fs.read((char *)&num_images, sizeof(num_images));\n        if (magic_number != 2049)\n        {\n            swap(magic_number);\n            swap(num_images);\n        }\n\n        Y = matrix_t::Zero(num_images, 10);\n\n        for (size_t i = 0; i < num_images; ++i)\n        {\n            unsigned char temp = 0;\n            fs.read((char *)&temp, sizeof(temp));\n            Y(i, (int)temp) = 1.0;\n        }\n        fs.close();\n    }\n    else\n    {\n        std::cout << \"error reading file: \" << filename << std::endl;\n        exit(1);\n    }\n    return Y;\n}\n\ndouble measure_accuracy(matrix_t Y, matrix_t Y_test)\n{\n    int correct = 0;\n    for (int i = 0; i < Y.rows(); i++)\n    {\n        int j = 0;\n        for (; j < Y.cols(); j++)\n        {\n            int out = Y_test(i, j) > 0.7 ? 1 : 0;\n            //printf(\"%3i   %4.4f\", (int)Y(i, j), Y_test(i, j));\n\n            if (out != Y(i, j))\n                break;\n        }\n        //cout << endl;\n        if (j == Y.cols())\n        {\n            correct++;\n        }\n        else\n        {\n            //cout << Y_test.row(i) << endl;\n        }\n    }\n    //cout << \"Correct answer \" << correct << \" among \" << Y.rows() << \" test\" << endl;\n    double accuracy = (double)correct / (double)Y.rows() * 100;\n    return accuracy;\n    //cout << \"Accuracy: \" <<  accuracy << \"%\" << endl;\n}\n\nvoid fill_type_info(matrix_t &Y, vi &type_info)\n{\n    int num_sample = Y.rows();\n    int num_type = Y.cols();\n    for (int i = 0; i < num_sample; i++)\n    {\n        for (int j = 0; j < num_type; j++)\n        {\n            if (Y(i, j) == 1)\n            {\n                type_info[j]++;\n                break;\n            }\n        }\n    }\n}\n\nvoid fill_position(matrix_t &Y, vvi &position)\n{\n    int num_sample = Y.rows();\n    int num_type = Y.cols();\n    for (int i = 0; i < num_sample; i++)\n    {\n        for (int j = 0; j < num_type; j++)\n        {\n            if (Y(i, j) == 1)\n            {\n                position[j].push_back(i);\n                break;\n            }\n        }\n    }\n}\n\nint distribution_in_batch(vi &type_distribution, vi &type_info, int proposed_batch_size, int num_sample)\n{\n    int batch_size = 0;\n    int num_type = type_info.size();\n    for (int i = 0; i < num_type; i++)\n    {\n        type_distribution[i] = (int)ceil((double)(type_info[i] * proposed_batch_size) / (double)num_sample);\n        batch_size += type_distribution[i];\n    }\n    return batch_size;\n}\n\nvoid distribute_into_batch(matrix_t &X, matrix_t &Y, matrix_t &Xm, matrix_t &Ym, vi &type_distribution, vvi &position, int batch_size, vi &type_point, int batch_no)\n{\n    int cnt = 0;\n    for (int i = 0; i < type_distribution.size(); i++)\n    {\n        for (int j = 0; j < type_distribution[i]; j++)\n        {\n            if (batch_no * batch_size + cnt == Xm.rows())\n            {\n                Xm.conservativeResize(Xm.rows() + batch_size - cnt, Xm.cols());\n                Ym.conservativeResize(Ym.rows() + batch_size - cnt, Ym.cols());\n            }\n            Xm.row(batch_no * batch_size + cnt) = X.row(position[i][type_point[i]]);\n            Ym.row(batch_no * batch_size + cnt) = Y.row(position[i][type_point[i]]);\n            cnt++;\n            type_point[i]++;\n            if (type_point[i] >= position[i].size())\n            {\n                type_point[i] = 0;\n            }\n        }\n    }\n}\nvoid distribute_into_matrix(matrix_t &X, matrix_t &Y, matrix_t &Xm, matrix_t &Ym, vi &type_info, vi &type_distribution, vvi &position, int batch_size)\n{\n    vi type_point(type_info.size(), 0);\n    int num_batch = (int)ceil((double)Y.rows() / (double)batch_size);\n\n    for (int i = 0; i < num_batch; i++)\n    {\n        distribute_into_batch(X, Y, Xm, Ym, type_distribution, position, batch_size, type_point, i);\n    }\n}\npair<matrix_t, matrix_t> make_uniform_dataset(matrix_t &X, matrix_t &Y, int &batch_size)\n{\n    int num_sample = Y.rows();\n    int num_type = Y.cols();\n\n    vi type_info(num_type, 0);\n    fill_type_info(Y, type_info);\n\n    vi type_distribution(num_type, 0);\n    batch_size = distribution_in_batch(type_distribution, type_info, batch_size, num_sample);\n\n    vvi position(num_type);\n    fill_position(Y, position);\n\n    matrix_t Xm(num_sample, X.cols());\n    matrix_t Ym(num_sample, num_type);\n\n    distribute_into_matrix(X, Y, Xm, Ym, type_info, type_distribution, position, batch_size);\n\n    return make_pair(Xm, Ym);\n}\npair<matrix_t, matrix_t> make_worst_batch(matrix_t &X, matrix_t &Y)\n{\n    matrix_t Xm(X.rows(), X.cols());\n    matrix_t Ym(Y.rows(), Y.cols());\n\n    int num_sample = Y.rows();\n    int num_type = Y.cols();\n\n    vi type_info(num_type, 0);\n    fill_type_info(Y, type_info);\n\n    vvi position(num_type);\n    fill_position(Y, position);\n    int cnt = 0;\n    for (int i = 0; i < num_type; i++)\n    {\n        for (int j = 0; j < position[i].size(); j++)\n        {\n            Xm.row(cnt) = X.row(position[i][j]);\n            Ym.row(cnt) = Y.row(position[i][j]);\n            cnt++;\n        }\n    }\n\n    return make_pair(Xm, Ym);\n}\nint main(int argc, const char *argv[])\n{\n\n    if (argc != 2)\n    {\n        std::cout << \"please provide path to mnist data ...\" << std::endl;\n        std::cout << \"you can download the dataset at http://yann.lecun.com/exdb/mnist/\" << std::endl;\n        std::cout << std::endl\n                  << \"usage: \" << argv[0] << \" path_to_data\" << std::endl\n                  << std::endl;\n        return 1;\n    }\n\n    std::string path = argv[1];\n\n    std::cout << \"reading data\" << std::endl;\n\n    // matrix_t X_train = read_mnist_images(path + \"/train-images.idx3-ubyte\");\n    // matrix_t Y_train = read_mnist_labels(path + \"/train-labels.idx1-ubyte\");\n    // matrix_t X_test = read_mnist_images(path + \"/t10k-images.idx3-ubyte\");\n    // matrix_t Y_test = read_mnist_labels(path + \"/t10k-labels.idx1-ubyte\");\n\n    matrix_t X_train = read_mnist_images(path + \"/train-images.idx3-ubyte\");\n    matrix_t Y_train = read_mnist_labels(path + \"/train-labels.idx1-ubyte\");\n    matrix_t X_test = read_mnist_images(path + \"/t10k-images.idx3-ubyte\");\n    matrix_t Y_test = read_mnist_labels(path + \"/t10k-labels.idx1-ubyte\");\n\n    //cout << \"Number of training sample: \" << X_train.rows() << endl;\n    int max_steps = 1500;\n    double lambda = 0.001;\n\n    // specify network topology\n    Eigen::VectorXi topo(3);\n    topo << X_train.cols(), 300, Y_test.cols();\n    std::cout << \"topology: \" << topo.transpose() << std::endl;\n\n    // initialize a neural network with given topology\n    std::cout << \"initializing network\" << std::endl;\n    NeuralNet nn(topo);\n\n    int batch_size = 100;\n    // pair<matrix_t, matrix_t> xy = make_uniform_dataset(X_train, Y_train, batch_size);\n\n    // X_train = xy.first;\n    // Y_train = xy.second;\n\n    // pair<matrix_t, matrix_t> xy = make_worst_batch(X_train, Y_train);\n\n    // X_train = xy.first;\n    // Y_train = xy.second;\n\n    std::cout<< \"scaling the data\" << std::endl;\n    nn.autoscale(X_train, Y_train);\n\n    int num_attribute = X_train.cols();\n    int num_type = Y_train.cols();\n    batch_manager batch(X_train.rows(), batch_size);\n\n    std::cout << \"starting training\" << std::endl;\n    std::cout << \"iter        error\" << std::endl;\n\n    double err;\n    clock_t begin = clock();\n    for (int i = 0; i < max_steps; ++i)\n    {\n        pair<int, int> start_end = batch.next_batch();\n        const int batch_size = start_end.second - start_end.first;\n\n        matrix_t Xm = X_train.block(start_end.first, 0, batch_size, num_attribute);\n        matrix_t Ym = Y_train.block(start_end.first, 0, batch_size, num_type);\n\n        err = nn.loss(Xm, Ym, lambda);\n        nn.rprop();\n        printf(\"%4i   %10.7f\\n\", i, err);\n    }\n    clock_t end = clock();\n    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;\n    cout << \"Training time: \" << elapsed_secs << endl;\n\n    // test accuracy\n    nn.forward_pass(X_test);\n    matrix_t prediction = nn.get_activation();\n    int correct = 0;\n    int k;\n    for (size_t i = 0; i < Y_test.rows(); ++i)\n    {\n        prediction.row(i).maxCoeff(&k);\n        correct += Y_test(i, k);\n    }\n\n    std::cout << \"test accuracy: \" << correct * 1.0 / Y_test.rows() * 100 << \"%\" << std::endl;\n    // double accuracy = measure_accuracy(Y_test, prediction);\n    // std::cout << \"Accuracy: \" << accuracy << std::endl;\n    nn.write(\"mnist.nn\");\n\n    return 0;\n}\n", "meta": {"hexsha": "c4676ecd6dceab97645c3d6b4bc1c0afa9753fc9", "size": 11043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rprop_batch.cpp", "max_stars_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_stars_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rprop_batch.cpp", "max_issues_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_issues_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rprop_batch.cpp", "max_forks_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_forks_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8328981723, "max_line_length": 164, "alphanum_fraction": 0.555917776, "num_tokens": 2979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5717554517352391}}
{"text": "// Copyright 2018-2019 Hans Dembinski and Henry Schreiner\n//\n// Distributed under the Boost Software License, version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Based on boost/histogram/accumulators/weighted_mean.hpp\n//\n// Changes:\n//  * Internal values are public for access from Python\n//  * A special constructor added for construction from Python\n\n#pragma once\n\n#include <boost/core/nvp.hpp>\n#include <boost/histogram/weight.hpp>\n\nnamespace accumulators {\n\n/**\n  Calculates mean and variance of weighted sample.\n\n  Uses West's incremental algorithm to improve numerical stability\n  of mean and variance computation.\n*/\ntemplate <typename ValueType>\nstruct weighted_mean {\n    using value_type      = ValueType;\n    using const_reference = const value_type&;\n\n    weighted_mean() = default;\n\n    weighted_mean(const value_type& wsum,\n                  const value_type& wsum2,\n                  const value_type& mean,\n                  const value_type& variance)\n        : sum_of_weights(wsum)\n        , sum_of_weights_squared(wsum2)\n        , value(mean)\n        , sum_of_weighted_deltas_squared(\n              variance * (sum_of_weights - sum_of_weights_squared / sum_of_weights)) {}\n\n    weighted_mean(const value_type& wsum,\n                  const value_type& wsum2,\n                  const value_type& mean,\n                  const value_type& sum_of_weighted_deltas_squared,\n                  bool /* tag to trigger Python internal constructor */)\n        : sum_of_weights(wsum)\n        , sum_of_weights_squared(wsum2)\n        , value(mean)\n        , sum_of_weighted_deltas_squared(sum_of_weighted_deltas_squared) {}\n\n    void operator()(const value_type& x) { operator()(boost::histogram::weight(1), x); }\n\n    void operator()(const boost::histogram::weight_type<value_type>& w,\n                    const value_type& x) {\n        sum_of_weights += w.value;\n        sum_of_weights_squared += w.value * w.value;\n        const auto delta = x - value;\n        value += w.value * delta / sum_of_weights;\n        sum_of_weighted_deltas_squared += w.value * delta * (x - value);\n    }\n\n    weighted_mean& operator+=(const weighted_mean& rhs) {\n        if(sum_of_weights != 0 || rhs.sum_of_weights != 0) {\n            const auto tmp = value * sum_of_weights + rhs.value * rhs.sum_of_weights;\n            sum_of_weights += rhs.sum_of_weights;\n            sum_of_weights_squared += rhs.sum_of_weights_squared;\n            value = tmp / sum_of_weights;\n        }\n        sum_of_weighted_deltas_squared += rhs.sum_of_weighted_deltas_squared;\n        return *this;\n    }\n\n    weighted_mean& operator*=(const value_type& s) {\n        value *= s;\n        sum_of_weighted_deltas_squared *= s * s;\n        return *this;\n    }\n\n    bool operator==(const weighted_mean& rhs) const noexcept {\n        return sum_of_weights == rhs.sum_of_weights\n               && sum_of_weights_squared == rhs.sum_of_weights_squared\n               && value == rhs.value\n               && sum_of_weighted_deltas_squared == rhs.sum_of_weighted_deltas_squared;\n    }\n\n    bool operator!=(const weighted_mean rhs) const noexcept { return !operator==(rhs); }\n\n    value_type variance() const {\n        return sum_of_weighted_deltas_squared\n               / (sum_of_weights - sum_of_weights_squared / sum_of_weights);\n    }\n\n    template <class Archive>\n    void serialize(Archive& ar, unsigned /* version */) {\n        ar& boost::make_nvp(\"sum_of_weights\", sum_of_weights);\n        ar& boost::make_nvp(\"sum_of_weights_squared\", sum_of_weights_squared);\n        ar& boost::make_nvp(\"value\", value);\n        ar& boost::make_nvp(\"sum_of_weighted_deltas_squared\",\n                            sum_of_weighted_deltas_squared);\n    }\n\n    value_type sum_of_weights{};\n    value_type sum_of_weights_squared{};\n    value_type value{};\n    value_type sum_of_weighted_deltas_squared{};\n};\n\n} // namespace accumulators\n", "meta": {"hexsha": "41d05f30fd6762050c43d1da45b25361dfa49c03", "size": 3940, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bh_python/accumulators/weighted_mean.hpp", "max_stars_repo_name": "HDembinski/boost-histogram", "max_stars_repo_head_hexsha": "6071588d8b58504938f72818d22ff3ce2a5b45dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/bh_python/accumulators/weighted_mean.hpp", "max_issues_repo_name": "HDembinski/boost-histogram", "max_issues_repo_head_hexsha": "6071588d8b58504938f72818d22ff3ce2a5b45dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bh_python/accumulators/weighted_mean.hpp", "max_forks_repo_name": "HDembinski/boost-histogram", "max_forks_repo_head_hexsha": "6071588d8b58504938f72818d22ff3ce2a5b45dc", "max_forks_repo_licenses": ["BSD-3-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.4954954955, "max_line_length": 88, "alphanum_fraction": 0.6568527919, "num_tokens": 879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.571755446940189}}
{"text": "#include <iostream>\n#include <chrono>\n#include <memory>\n#include <cmath>\n#include <Eigen/Dense>\n#include <Eigen/Dense>\n#include \"minimize.h\"\n\nusing Matrix = minimize::Matrix;\nusing Vector = minimize::Vector;\n\n\n// Define interpolation procedure for minimization algorithm\ndouble minimize::interpolate(double x2, double f2, double d2, double x3, double f3, double d3, double f0, double INT, double RHO)\n{\n\n  // choose subinterval\n  // move point 3 to point 4\n  double x4 = x3;\n  double f4 = f3;\n  double d4 = d3;\n\n  //double tolerance = 1e-32;\n  double tolerance = 1e-64;\n\n  if ( f4 > f0 )\n    {\n      double denom = f4-f2-d2*(x4-x2);\n      if ( std::abs(denom) < tolerance )\n        // bisect\n        x3 = (x2+x4)/2;\n      else\n        // quadratic interpolation\n        x3 = x2-(0.5*d2*std::pow(x4-x2,2))/(denom);\n    }\n  else\n    {\n      // cubic interpolation\n      double A = 6*(f2-f4)/(x4-x2)+3*(d4+d2);                        \n      double B = 3*(f4-f2)-(2*d2+d4)*(x4-x2);\n      double radical = B*B-A*d2*std::pow(x4-x2,2);\n\n      if ( ( radical < 0 ) || ( std::abs(A) < tolerance ) )\n        x3 = (x2+x4)/2;\n      else\n        x3 = x2+( std::sqrt(radical) - B)/A;\n    }\n\n  // don't accept too close\n  if ( x4-INT*(x4-x2) < x3 )\n    x3 = x4-INT*(x4-x2);\n\n  if ( x2+INT*(x4-x2) > x3 )\n    x3 = x2+INT*(x4-x2);\n\n  return x3;\n};\n\n\n\n// Define cubic extrapolation routine for minimization algorithm\ndouble minimize::cubic_extrap(double x1, double x2, double f1, double f2, double d1, double d2, double EXT, double INT)\n{\n  // make cubic extrapolation\n  double A = 6*(f1-f2)+3*(d2+d1)*(x2-x1);\n  double B = 3*(f2-f1)-(2*d1+d2)*(x2-x1);\n\n  double x3;\n  //double tolerance = 1e-32;\n  double tolerance = 1e-64;\n  double radical = B*B-A*d1*(x2-x1);\n\n  if ( radical < 0.0 )\n    x3 = x2*EXT;\n  else if ( B + std::sqrt(radical) < tolerance )\n    x3 = x2*EXT;\n  else\n    {\n      x3 = x1-d1*std::pow(x2-x1,2)/( B + std::sqrt(radical) );\n\n      if ( ( x3 < 0 ) || ( x3 > x2*EXT ) )\n        x3 = x2*EXT;\n      else if ( x3 < x2+INT*(x2-x1) )\n        x3 = x2+INT*(x2-x1);\n    }\n\n  return x3;\n};\n    \n\n\n//\n//  ORIGINAL CODE BY CARL EDWARD RASMUSSEN\n//  http://learning.eng.cam.ac.uk/carl/code/minimize/\n//\n//  % Minimize a differentiable multivariate function. \n//  %\n//  % Usage: [X, fX, i] = minimize(X, f, length, P1, P2, P3, ... )\n//  %\n//  % where the starting point is given by \"X\" (D by 1), and the function named in\n//  % the string \"f\", must return a function value and a vector of partial\n//  % derivatives of f wrt X, the \"length\" gives the length of the run: if it is\n//  % positive, it gives the maximum number of line searches, if negative its\n//  % absolute gives the maximum allowed number of function evaluations. You can\n//  % (optionally) give \"length\" a second component, which will indicate the\n//  % reduction in function value to be expected in the first line-search (defaults\n//  % to 1.0). The parameters P1, P2, P3, ... are passed on to the function f.\n//  %\n//  % The function returns when either its length is up, or if no further progress\n//  % can be made (ie, we are at a (local) minimum, or so close that due to\n//  % numerical problems, we cannot get any closer). NOTE: If the function\n//  % terminates within a few iterations, it could be an indication that the\n//  % function values and derivatives are not consistent (ie, there may be a bug in\n//  % the implementation of your \"f\" function). The function returns the found\n//  % solution \"X\", a vector of function values \"fX\" indicating the progress made\n//  % and \"i\" the number of iterations (line searches or function evaluations,\n//  % depending on the sign of \"length\") used.\n//  %\n//  % The Polack-Ribiere flavour of conjugate gradients is used to compute search\n//  % directions, and a line search using quadratic and cubic polynomial\n//  % approximations and the Wolfe-Powell stopping criteria is used together with\n//  % the slope ratio method for guessing initial step sizes. Additionally a bunch\n//  % of checks are made to make sure that exploration is taking place and that\n//  % extrapolation will not be unboundedly large.\n//  %\n//  % See also: checkgrad \n//  %\n//  % Copyright (C) 2001 - 2006 by Carl Edward Rasmussen (2006-09-08).\n//  \n//  INT = 0.1;    % don't reevaluate within 0.1 of the limit of the current bracket\n//  EXT = 3.0;                  % extrapolate maximum 3 times the current step-size\n//  MAX = 20;                         % max 20 function evaluations per line search\n//  RATIO = 10;                                       % maximum allowed slope ratio\n//  SIG = 0.1; RHO = SIG/2; % SIG and RHO are the constants controlling the Wolfe-\n//  % Powell conditions. SIG is the maximum allowed absolute ratio between\n//  % previous and new slopes (derivatives in the search direction), thus setting\n//  % SIG to low (positive) values forces higher precision in the line-searches.\n//  % RHO is the minimum allowed fraction of the expected (from the slope at the\n//  % initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1.\n//  % Tuning of SIG (depending on the nature of the function to be optimized) may\n//  % speed up the minimization; it is probably not worth playing much with RHO.\n//  \n//  % The code falls naturally into 3 parts, after the initial line search is\n//  % started in the direction of steepest descent. 1) we first enter a while loop\n//  % which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we\n//  % have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we\n//  % enter the second loop which takes p2, p3 and p4 chooses the subinterval\n//  % containing a (local) minimum, and interpolates it, unil an acceptable point\n//  % is found (Wolfe-Powell conditions). Note, that points are always maintained\n//  % in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using\n//  % conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there\n//  % was a problem in the previous line-search. Return the best value so far, if\n//  % two consecutive line-searches fail, or whenever we run out of function\n//  % evaluations or line-searches. During extrapolation, the \"f\" function may fail\n//  % either with an error or returning Nan or Inf, and minimize should handle this\n//  % gracefully.\n//  \n\n\n  \n// Conjugate gradient minimization algorithm\nvoid minimize::cg_minimize(Vector & X, minimize::GradientObj * target, Vector & D, int length, double SIG, double EXT, double INT, int MAX)\n{\n  // specify optimization hyperparameters\n  //double RATIO = 10.0;\n  double RATIO = 100.0;\n  double RHO = SIG/2;\n\n  // determine problem dimension\n  int N = static_cast<int>(X.size());\n\n  // initialize values\n  int i = 0;\n  bool ls_failed = false;\n  Vector df0(N);\n  double f0;\n  (*target).computeValueAndGradient(X, f0, df0);\n\n  // initial search direction (steepest) and slope \n  Vector s = -df0;\n  double d0 = -s.transpose()*s;\n\n  // initial step is 1/(|s|+1)\n  double x3 = 1/(1-d0);     \n\n  // declare placeholders for storing optimal values\n  Vector X0(N);\n  double F0;\n  Vector dF0(N);\n\n  // declare variables in main loop\n  int M;\n  bool continue_extrap;\n  double x1, f1, d1, x2, f2, d2, f3, d3;\n  Vector df3(N);\n\n  // \"realmin\" = smallest positive normalized floating-point number in IEEE double precision format\n  double realmin = 2.2251e-308;\n\n  // MAIN LOOP\n  bool request_break = false;\n  while ( ( i < length ) && ( !request_break ) )\n    {\n      i++;\n\n      // make a copy of current values\n      X0 = X;\n      F0 = f0;\n      dF0 = df0;\n\n      // Display current parameter values\n      //std::cout << \" X  =  \" << X.transpose().array().exp().matrix() << std::endl;\n      \n      // initialize iteration count\n      M = MAX;\n\n      // EXTRAPOLATE\n      continue_extrap = true;\n      while ( continue_extrap )\n        {\n          x2 = 0.0;\n          f2 = f0;\n          d2 = d0;\n          M = M - 1;\n          (*target).computeValueAndGradient(X+x3*s, f3, df3);\n\n          // keep best values\n          if ( f3 < F0 )\n            {\n              X0 = X+x3*s;\n              F0 = f3;\n              dF0 = df3;\n            }\n\n          // new slope                \n          d3 = df3.transpose()*s;                    \n\n          // are we done extrapolating?\n          if ( ( ( d3 > SIG*d0 ) || ( f3 > f0+x3*RHO*d0 ) ) || ( M == 0 ) )\n              continue_extrap = false;\n\n          // move point 2 to point 1\n          x1 = x2;\n          f1 = f2;\n          d1 = d2;\n          // move point 3 to point 2\n          x2 = x3;\n          f2 = f3;\n          d2 = d3;\n\n          // cubic extrapolation\n          x3 = cubic_extrap(x1, x2, f1, f2, d1, d2, EXT, INT);\n\n        } // END EXTRAPOLATE\n\n\n      // INTERPOLATE\n      while ( ( ( std::abs(d3) > -SIG*d0 ) || ( f3 > f0+x3*RHO*d0) )  &&  ( M > 0 ) )\n        {\n\n          x3 = interpolate(x2, f2, d2, x3, f3, d3, f0, INT, RHO);\n\n          (*target).computeValueAndGradient(X+x3*s, f3, df3);\n\n          // keep best values\n          if ( f3 < F0 )\n            {\n              X0 = X+x3*s;\n              F0 = f3;\n              dF0 = df3;\n            }\n\n          // decrement line-search count\n          M = M - 1;\n\n          // new slope            \n          d3 = df3.transpose()*s;\n\n        } // END INTERPOLATE\n\n\n\n      //  START COMPUTE NEW SEARCH DIRECTION\n      if ( ( std::abs(d3) < -SIG*d0 ) && ( f3 < f0+x3*RHO*d0 ) )            \n        {\n          // if line search succeeded\n          // update variables            \n          X = X+x3*s;\n          f0 = f3;\n\n          // Polack-Ribiere CG direction\n          s = ( (df3.transpose()*df3 - df0.transpose()*df3)(0) / (df0.transpose()*df0)(0) )*s - df3;\n\n          // swap derivatives\n          df0 = df3;\n          d3 = d0;\n          d0 = df0.transpose()*s;\n\n          // new slope must be negative\n          if ( d0 > 0 )\n            {\n              // otherwise use steepest direction\n              s = -df0;\n              d0 = -s.transpose()*s;\n            }\n\n          // slope ratio but max RATIO\n          if ( RATIO <  d3/(d0-realmin) )\n            {\n              x3 = x3 * RATIO;\n              //std::cout << \"\\n[*] RATIO parameter enforced\\n\";\n            }\n          else\n              x3 = x3 * d3/(d0-realmin);\n\n          // this line search did not fail\n          ls_failed = false;                                          \n        }\n\n      else\n        {\n          // restore best point so far\n          X = X0;\n          f0 = F0;\n          df0 = dF0;                             \n\n          // line search failed twice in a row\n          // or we ran out of time, so we give up\n          if ( ( ls_failed ) || ( i > length ) )        \n              request_break = true;                               \n\n\n          // DEBUGGING INFO TO SEE WHY OPTIMIZATION EXITS EARLY\n          /*\n          if ( ls_failed )\n            {\n              std::cout << \"\\n[*] Line Search Failed  ( i = \" << i << \" )\\n\";\n              std::cout << \"\\n The following conditions failed:   [ SIG = \" << SIG << \" , RHO = \" << RHO << \" ]\\n\";\n              if ( std::abs(d3) >= -SIG*d0 )\n                {\n                  double lhs = std::abs(d3);\n                  double rhs = -SIG*d0;\n                  std::cout << \"abs(\" << d3 << \")   <   -SIG * \" << d0 << \" [   i.e. \" << lhs << \" < \" << rhs << \" ]\\n\";\n                }\n              if ( f3 >= f0+x3*RHO*d0 )\n                {\n                  double lhs = f3;\n                  double rhs = f0+x3*RHO*d0;\n                  std::cout <<  f3 << \"   <   \" << f0 << \" + \" << x3 << \" * RHO * \" << d0 << \"   [ i.e. \" << lhs << \" < \" << rhs << \" ]\\n\";\n                }\n            }\n          if ( i > length )\n            std::cout << \"\\n[*] Exceeded 'length' value\\n\";\n          */\n          \n          // try steepest\n          s = -df0;\n          d0 = -s.transpose()*s;           \n          x3 = 1/(1-d0);\n\n          // this line search failed\n          ls_failed = true;                   \n\n        } // END COMPUTE NEW SEARCH DIRECTION\n\n    }  // END MAIN LOOP\n  \n  //std::cout << \"\\nMinimized Function Value (???) :\\n\";\n  //std::cout << f0 << std::endl;\n\n};\n\n", "meta": {"hexsha": "5a000038b3f0c6a846797b929e283d2366be333e", "size": 12113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/minimize.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/minimize.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/minimize.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 32.4745308311, "max_line_length": 139, "alphanum_fraction": 0.5415669116, "num_tokens": 3537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424411924673, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5716579617814193}}
{"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 MATH_POWER_INCLUDE\n#define MATH_POWER_INCLUDE\n\n#include <concepts>\n#include <boost/numeric/linear_algebra/concepts.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <stdexcept>\n\n\nnamespace math {\n\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\tstd::cout << \"[Magma] \";\n\tif (n < 1) throw std::range_error(\"power [magma]: n must be > 0\");\n\n\tElement value= a;\n\tfor (; n > 1; --n)\n\t    value= op(value, a);\n\treturn value;\n    }\n\n#if 0\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires SemiGroup<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element multiply_and_square_horner(const Element& a, Exponent n, Op op) \n    {\n\tif (n < 1) throw std::range_error(\"mult&square Horner: n must be > 0\");\n\n        // Set mask to highest bit\n        Exponent mask= 1 << (8 * sizeof(mask) - 1);\n\n        // If this is a negative number right shift can insert 1s instead of 0s -> infinite loop\n        // Therefore we take the 2nd-highest bit\n        if (mask < 0)\n\t    mask= 1 << (8 * sizeof(mask) - 2);\n\n        // Find highest 1 bit\n        while(!bool(mask & n)) mask>>= 1;\n\n        Element value= a;\n        for (mask>>= 1; mask; mask>>= 1) {\n\t    value= op(value, value);\n\t    if (n & mask) \n\t\tvalue= op(value, a);\n        }\n        return value;\n    }\n\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires SemiGroup<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\treturn multiply_and_square_horner(a, n, op);\n    }\n#endif\n\n\n#if 1\n    // With Horner scheme we can avoid recursion  \n    // This one is more intuitive (I believe)      \n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires SemiGroup<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\tstd::cout << \"[SemiGroup] \";\n\tif (n < 1) throw std::range_error(\"power [SemiGroup]: n must be > 0\");\n\n\tExponent half(n / 2);\n        // If half is 0 then n must be 1 and the result is a\n        if (half == 0)\n\t    return a;\n\n        // Compute power of downward rounded exponent and \"square\" the result\n        Element value= power(a, half, op);\n        value= op(value, value);\n\n        // If n is odd another operation with a is needed\n        if (n & 1) \n\t    value= op(value, a);\n        return value;\n    }\n#endif\n\n\n\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires Monoid<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element multiply_and_square(const Element& a, Exponent n, Op op) \n    {\n\t// Same as the simpler form except that the first multiplication is made before \n\t// the loop and one squaring is saved this way\n\tif (n < 0) throw std::range_error(\"mult&square: n must be >= 0\");\n\t\n\tusing math::identity;\n\tElement value= bool(n & 1) ? Element(a) : Element(identity(op, a)), square= a;\n\t\n\tfor (n>>= 1; n > 0; n>>= 1) {\n\t    square= op(square, square); \n\t    if (n & 1) \n\t\tvalue= op(value, square);\n\t}\n\treturn value;  \n    } \n\n\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires Monoid<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\tstd::cout << \"[Monoid] \";\n\treturn multiply_and_square(a, n, op);\n    }\n\n\n\n\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires PIMonoid<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\tstd::cout << \"[PIMonoid] \";\n\tif (n < 0 && !is_invertible(op, a)) \n\t    throw std::range_error(\"power [PIMonoid]: a must be invertible with n < 0\");\n\n\treturn n < 0 ? multiply_and_square(Element(inverse(op, a)), Exponent(-n), op)\n\t             : multiply_and_square(a, n, op);\n    }\n\n#if 1\n    template <typename Op, std::Semiregular Element, Integral Exponent>\n        requires Group<Op, Element> \n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\tstd::cout << \"[Group] \";\n\t// For groups we don't need any range test\n\n\treturn n < 0 ? multiply_and_square(Element(inverse(op, a)), Exponent(-n), op)\n\t             : multiply_and_square(a, n, op);\n    }\n#endif\n\n\n#if 0\n    template <typename Op, typename Element, typename Exponent>\n        requires Group<Op, Element> \n              && Integral<Exponent>\n              && std::Semiregular<Element>\n              && std::Callable2<Op, Element, Element>\n              && std::Convertible<std::Callable2<Op, Element, Element>::result_type, Element>\n              && std::Semiregular<math::Inversion<Op, Element>::result_type>\n              && std::HasNegate<Exponent>\n              && math::Monoid<Op, math::Inversion<Op, Element>::result_type>\n              && Integral< std::HasNegate<Exponent>::result_type>\n              && std::Callable2<Op, math::Inversion<Op, Element>::result_type, \n\t\t\t\tmath::Inversion<Op, Element>::result_type>\n              && std::Convertible<std::Callable2<Op, math::Inversion<Op, Element>::result_type, \n\t\t\t\t\t\t math::Inversion<Op, Element>::result_type>::result_type, \n\t\t\t\t  math::Inversion<Op, Element>::result_type>\n    inline Element power(const Element& a, Exponent n, Op op)\n    {\n\treturn n < 0 ? multiply_and_square(inverse(op, a), -n, op)\n\t             : multiply_and_square(a, n, op);\n    }\n#endif\n\n} // namespace math\n\n#endif // MATH_POWER_INCLUDE\n", "meta": {"hexsha": "d3ee807e08faa27186fab55cfce884d7bd7e2a7b", "size": 6982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/power.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/linear_algebra/power.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/linear_algebra/power.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": 35.0854271357, "max_line_length": 96, "alphanum_fraction": 0.6231738757, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246077301781, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5716185712174856}}
{"text": "//\n//  ClosedFormSVDSVD2d.hpp\n//  IPC\n//\n//  Created by Minchen Li on 8/31/18.\n//  based on https://www.researchgate.net/publication/263580188_Closed_Form_SVD_Solutions_for_2_x_2_Matrices_-_Rev_2\n//\n\n#ifndef ClosedFormSVD2d_hpp\n#define ClosedFormSVD2d_hpp\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n\nnamespace IPC {\n\ntemplate <typename MatrixType>\nclass AutoFlipSVD : Eigen::JacobiSVD<MatrixType> {\n    typedef Eigen::JacobiSVD<MatrixType> Base;\n\npublic:\n    AutoFlipSVD(void) {}\n    AutoFlipSVD(const MatrixType& mtr, unsigned int computationOptions = 0)\n        : Base(2, 2, computationOptions)\n    {\n        if (MatrixType::RowsAtCompileTime == Eigen::Dynamic) {\n            assert(mtr.rows() == 2);\n        }\n        else {\n            assert(MatrixType::RowsAtCompileTime == 2);\n        }\n\n        if (MatrixType::ColsAtCompileTime == Eigen::Dynamic) {\n            assert(mtr.cols() == 2);\n        }\n        else {\n            assert(MatrixType::ColsAtCompileTime == 2);\n        }\n\n        Base::m_isInitialized = true;\n\n        compute(mtr);\n    }\n\npublic:\n    AutoFlipSVD& compute(const MatrixType& A)\n    {\n        bool computeU = (Base::m_computeFullU || Base::m_computeThinU);\n        bool computeV = (Base::m_computeFullV || Base::m_computeThinV);\n\n        const double a = A(0, 0);\n        const double b = A(1, 0);\n        const double c = A(0, 1);\n        const double d = A(1, 1);\n\n        const double ad = a * d;\n        const double bc = b * c;\n        const double _2admbc = 2.0 * (ad - bc);\n        const double sqn = A.squaredNorm();\n\n        const double sum = sqn + _2admbc;\n        const double dif = sqn - _2admbc;\n        if (dif <= 0.0) {\n            // avoid dividing by 0 in general formula\n            const double aa = (a + d) / 2.0;\n            const double bb = (b - c) / 2.0;\n            const double lambda = std::sqrt(aa * aa + bb * bb);\n            Base::m_singularValues.setConstant(lambda);\n\n            if (computeU) {\n                if (lambda == 0.0) {\n                    // avoid dividing by 0\n                    Base::m_matrixU.setIdentity();\n                }\n                else {\n                    const double cosl = aa / lambda;\n                    const double sinl = bb / lambda;\n                    Base::m_matrixU << cosl, -sinl, sinl, cosl;\n                }\n            }\n\n            if (computeV) {\n                Base::m_matrixV.setIdentity();\n            }\n        }\n        else if (sum <= 0.0) {\n            // avoid dividing by 0 in general formula\n            // symmetric matrix with a=-d\n            const double aa = (a - d) / 2.0;\n            const double bb = (b + c) / 2.0;\n            const double lambda = std::sqrt(aa * aa + bb * bb);\n            Base::m_singularValues << lambda, -lambda;\n\n            if (computeU || computeV) {\n                if (bb == 0.0) {\n                    // avoid dividing by 0 and sqrt(<0)\n                    if (computeU) {\n                        Base::m_matrixU.setIdentity();\n                    }\n\n                    if (computeV) {\n                        Base::m_matrixV.setIdentity();\n                    }\n                }\n                else {\n                    const double a_div_lambda_half = aa / lambda / 2.0;\n                    bool neg_b = (bb < 0.0);\n                    const double cos2 = 0.5 + a_div_lambda_half;\n                    const double cos = ((cos2 <= 0.0) ? 0.0 : std::sqrt(cos2));\n                    const double sin2 = 0.5 - a_div_lambda_half;\n                    const double sin = ((sin2 <= 0.0) ? 0.0 : (neg_b ? -std::sqrt(sin2) : std::sqrt(sin2)));\n                    if (computeU) {\n                        Base::m_matrixU << cos, -sin, sin, cos;\n                    }\n\n                    if (computeV) {\n                        Base::m_matrixV << cos, -sin, sin, cos;\n                    }\n                }\n            }\n        }\n        else {\n            const double sqrt_sum = std::sqrt(sum); // safe\n            const double sqrt_dif = std::sqrt(dif); // safe\n\n            Base::m_singularValues[0] = (sqrt_sum + sqrt_dif) / 2.0;\n            Base::m_singularValues[1] = ((_2admbc < 0.0) ? (-std::abs(sqrt_sum - sqrt_dif) / 2.0) : (std::abs(sqrt_sum - sqrt_dif) / 2.0));\n\n            if (computeU || computeV) {\n                const double a2 = a * a;\n                const double b2 = b * b;\n                const double c2 = c * c;\n                const double d2 = d * d;\n\n                const double denom = sqrt_sum * sqrt_dif * 2.0;\n\n                const double a2md2 = a2 - d2;\n                const double b2mc2 = b2 - c2;\n\n                const double ab = a * b;\n                const double cd = c * d;\n                const bool neg_ab_p_cd = ((ab + cd) < 0);\n\n                if (computeU) {\n                    const double a2md2_m_b2mc2_div_ = (a2md2 - b2mc2) / denom; // safe\n\n                    // avoid sqrt(<0)\n                    const double cosl2 = 0.5 + a2md2_m_b2mc2_div_;\n                    const double cosl = ((cosl2 <= 0.0) ? 0.0 : std::sqrt(cosl2));\n                    const double sinl2 = 0.5 - a2md2_m_b2mc2_div_;\n                    const double sinl = ((sinl2 <= 0.0) ? 0.0 : (neg_ab_p_cd ? -std::sqrt(sinl2) : std::sqrt(sinl2)));\n\n                    Base::m_matrixU << cosl, -sinl, sinl, cosl;\n                }\n\n                if (computeV) {\n                    const double ac = a * c;\n                    const double bd = b * d;\n                    const bool neg_ac_p_bd = ((ac + bd) < 0);\n                    const double a2md2_p_b2mc2_div_ = (a2md2 + b2mc2) / denom; // safe\n\n                    // avoid sqrt(<0)\n                    const double cosr2 = 0.5 + a2md2_p_b2mc2_div_;\n                    const double cosr = ((cosr2 <= 0.0) ? 0.0 : std::sqrt(cosr2));\n                    const double sinr2 = 0.5 - a2md2_p_b2mc2_div_;\n                    const double sinr = ((sinr2 <= 0.0) ? 0.0 : (neg_ac_p_bd ? -std::sqrt(sinr2) : std::sqrt(sinr2)));\n\n                    const bool s = neg_ab_p_cd ^ neg_ac_p_bd;\n                    const bool neg_apsd = ((a + (s ? -d : d)) < 0.0);\n                    if (neg_apsd) {\n                        Base::m_matrixV << -cosr, sinr, -sinr, -cosr;\n                    }\n                    else {\n                        Base::m_matrixV << cosr, -sinr, sinr, cosr;\n                    }\n                }\n            }\n        }\n\n        return *this;\n    }\n    AutoFlipSVD& compute(const MatrixType& mtr, unsigned int computationOptions)\n    {\n        if (MatrixType::RowsAtCompileTime == Eigen::Dynamic) {\n            assert(mtr.rows() == 2);\n        }\n        else {\n            assert(MatrixType::RowsAtCompileTime == 2);\n        }\n\n        if (MatrixType::ColsAtCompileTime == Eigen::Dynamic) {\n            assert(mtr.cols() == 2);\n        }\n        else {\n            assert(MatrixType::ColsAtCompileTime == 2);\n        }\n\n        allocate(computationOptions);\n        Base::m_isInitialized = true;\n\n        compute(mtr);\n\n        return *this;\n    }\n\nprotected:\n    void allocate(unsigned int computationOptions)\n    {\n        if (Base::m_isAllocated && 2 == Base::m_rows && 2 == Base::m_cols && computationOptions == Base::m_computationOptions) {\n            return;\n        }\n\n        Base::m_rows = 2;\n        Base::m_cols = 2;\n        Base::m_isInitialized = false;\n        Base::m_isAllocated = true;\n        Base::m_computationOptions = computationOptions;\n        Base::m_computeFullU = (computationOptions & Eigen::ComputeFullU) != 0;\n        Base::m_computeThinU = (computationOptions & Eigen::ComputeThinU) != 0;\n        Base::m_computeFullV = (computationOptions & Eigen::ComputeFullV) != 0;\n        Base::m_computeThinV = (computationOptions & Eigen::ComputeThinV) != 0;\n        eigen_assert(!(Base::m_computeFullU && Base::m_computeThinU) && \"JacobiSVD: you can't ask for both full and thin U\");\n        eigen_assert(!(Base::m_computeFullV && Base::m_computeThinV) && \"JacobiSVD: you can't ask for both full and thin V\");\n        eigen_assert(EIGEN_IMPLIES(Base::m_computeThinU || Base::m_computeThinV,\n                         MatrixType::ColsAtCompileTime == Eigen::Dynamic)\n            && \"JacobiSVD: thin U and V are only available when your matrix has a dynamic number of columns.\");\n\n        Base::m_diagSize = 2;\n        Base::m_singularValues.resize(2);\n        Base::m_matrixU.resize(2, 2);\n        Base::m_matrixV.resize(2, 2);\n        Base::m_workMatrix.resize(2, 2);\n    }\n\npublic:\n    const typename Eigen::JacobiSVD<MatrixType>::SingularValuesType& singularValues(void) const\n    {\n        return Base::m_singularValues;\n    }\n    const MatrixType& matrixU(void) const\n    {\n        return Base::m_matrixU;\n    }\n    const MatrixType& matrixV(void) const\n    {\n        return Base::m_matrixV;\n    }\n};\n\n} // namespace IPC\n\n#endif /* ClosedFormSVD2d_hpp */\n", "meta": {"hexsha": "d694d0c8816f364c071886189e8df0ca8c702901", "size": 8847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/ClosedFormSVD2d.hpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/Utils/ClosedFormSVD2d.hpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/Utils/ClosedFormSVD2d.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": 34.8307086614, "max_line_length": 139, "alphanum_fraction": 0.5007347123, "num_tokens": 2373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5716185463203871}}
{"text": "#include \"stdafx.h\"\n#include \"KinectDistortionModel.h\"\n#include <Eigen\\Dense>\n\nusing namespace DirectX;\nusing namespace Eigen;\n\nnamespace k4u\n{\n  float ApplyMediaFoundationRadialDistortion(const DirectX::XMFLOAT3& coeffs, float r)\n  {\n    return 1 +\n      coeffs.x * pow(r, 2.f) +\n      coeffs.y * pow(r, 4.f) +\n      coeffs.z * pow(r, 6.f);\n  }\n  \n  float ApplyKinectRadialDistortion(const DirectX::XMFLOAT3& coeffsA, const DirectX::XMFLOAT3& coeffsB, float r)\n  {\n    auto a = ApplyMediaFoundationRadialDistortion(coeffsA, r);\n    auto b = ApplyMediaFoundationRadialDistortion(coeffsB, r);\n    auto bi = b == 0.f ? 1.f : 1.f / b;\n    return a * bi;\n  }\n\n  DirectX::XMFLOAT3 ConvertKinectRadialDistortionToMediaFoundation(const k4a_calibration_camera_t& calibration)\n  {\n    const int sampleSize = 100;\n    Matrix<float, sampleSize, 1> y1;\n    Matrix<float, sampleSize, 3> x;\n\n    auto& params = calibration.intrinsics.parameters.param; \n    XMFLOAT3 coeffsA{ params.k1, params.k2, params.k3 };\n    XMFLOAT3 coeffsB{ params.k4, params.k5, params.k6 };\n\n    auto rStep = calibration.metric_radius / (sampleSize - 1);\n    auto rCurrent = 0.f;\n    for (auto i = 0; i < sampleSize; i++)\n    {\n      auto r = rCurrent;\n      y1(i) = ApplyKinectRadialDistortion(coeffsA, coeffsB, r) - 1;\n\n      auto r2 = r * r;\n      auto r4 = r2 * r2;\n      auto r6 = r4 * r2;\n\n      x(i, 0) = r2;\n      x(i, 1) = r4;\n      x(i, 2) = r6;\n      rCurrent += rStep;\n    }\n\n    auto k = x.fullPivHouseholderQr().solve(y1);\n    return { k(0), k(1), k(2) };\n  }\n}", "meta": {"hexsha": "8f3f1a4fd51af163f198834eb0bb0e453a754e94", "size": 1537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MediaSource/KinectDistortionModel.cpp", "max_stars_repo_name": "axodox/Azure-Kinect-UWP-Adapter", "max_stars_repo_head_hexsha": "8cfc8edd909b123ecf5fec417aad4e8c0d9c4fb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-02T13:48:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T13:48:39.000Z", "max_issues_repo_path": "MediaSource/KinectDistortionModel.cpp", "max_issues_repo_name": "axodox/Azure-Kinect-UWP-Adapter", "max_issues_repo_head_hexsha": "8cfc8edd909b123ecf5fec417aad4e8c0d9c4fb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-30T18:06:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T00:39:13.000Z", "max_forks_repo_path": "MediaSource/KinectDistortionModel.cpp", "max_forks_repo_name": "axodox/Azure-Kinect-UWP-Adapter", "max_forks_repo_head_hexsha": "8cfc8edd909b123ecf5fec417aad4e8c0d9c4fb9", "max_forks_repo_licenses": ["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.4464285714, "max_line_length": 112, "alphanum_fraction": 0.6350032531, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.57161854097036}}
{"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_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$\\frac{\\sinh(x)}{\\cosh(x)}\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = tanh(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sinh(x)/cosh(x);\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::tanh_> tanh = {};\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": "825189fe669b2bd21638b15507465d109fd8fe06", "size": 1089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/tanh.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/tanh.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/tanh.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.2244897959, "max_line_length": 100, "alphanum_fraction": 0.5656565657, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245828938678, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5716185381309511}}
{"text": "#include \"utils.h\"\n#include \"soft_clustering.h\"\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace std;\n\nHyperparam::Hyperparam(AdaCluster& mdl_)\n    : copt::BoundedProblem<double>(mdl_.get_n_dims()),\n      mdl(mdl_),\n      k(mdl_.get_k()),\n      n_samples(mdl_.get_n_samples()),\n      n_dims(mdl_.get_n_dims()),\n      kappa(mdl_.get_kappa()),\n      log_pi(mdl_.get_log_pi()),\n      data(mdl_.get_data()),\n      log_asg(mdl_.get_log_asg()),\n      mu(mdl_.get_mu()) {\n  buffer.resize(k);\n}\n\ndouble Hyperparam::value(const copt::Vector<double>& x) {\n  // x = alpha\n  double obj = 0.0;\n  for (size_t i = 0; i < n_samples; ++i) {\n    for (size_t c = 0; c < k; ++c) {\n      buffer[c] = log_pi[c];\n      for (unsigned long int j = 0; j < n_dims; ++j){\n        if (!isnan(data[i][j])){\n          double dist = mdl.distance(data[i][j], mu[c][j], x[j], j) / kappa[j];\n          double var = mdl.variance(data[i][j], x[j], j);\n          double upd = dist + 0.5 * (log(2 * M_PI) + log(kappa[j]) + log(var));\n          // if (isnan(buffer[c])){\n          //   cout << \"buffer nan is detected \";\n          //   cout << m_lowerBound[j] << \" \" << m_upperBound[j] << \" \";\n          //   cout << data[i][j] << \" \" << mu[c][j] << \" \" << x[j] << \" \";\n          //   cout << mdl.distance(data[i][j], mu[c][j], x[j], j) / kappa[j] << \" \";\n          //   cout << mdl.variance(data[i][j], x[j], j) << endl;\n          //   break;\n          // }\n          if (!isnan(upd))\n            buffer[c] -= upd;\n        }\n      }\n    }\n    obj += logsumexp(buffer);\n  }\n  return -obj;\n}\n\nvoid Hyperparam::gradient(const copt::Vector<double>& x,\n                          copt::Vector<double>& grad) {\n  bool terminate = 0;\n  double gr = 0.0;\n  for (unsigned long int j = 0; j < n_dims; ++j) {\n    terminate = 0;\n    gr = 0.0;\n    for (size_t i = 0; i < n_samples; ++i){\n      for (size_t c = 0; c < k; ++c)\n        if (!isnan(data[i][j])){\n          double diff_dist = mdl.diff_distance(data[i][j], mu[c][j], x[j], j) / kappa[j];\n          double diff_var = mdl.diff_variance(data[i][j], x[j], j);\n          double var = mdl.variance(data[i][j], x[j], j);\n          double pr_asg = exp(log_asg[i][c]);\n          double upd = 0.0;\n          if (diff_var == 0.0)\n            upd = pr_asg * diff_dist;\n          else\n            upd = pr_asg * (diff_dist + 0.5 * diff_var / var);\n          gr += upd;\n          // if (isnan(gr)){\n          //   cout << \"grad nan is detected\";\n          //   cout << m_lowerBound[j] << \" \" << m_upperBound[j] << \" \";\n          //   cout << data[i][j] << \" \" << mu[c][j] << \" \" << x[j] << \" \";\n          //   cout << mdl.diff_distance(data[i][j], mu[c][j], x[j], j) / kappa[j] << \" \";\n          //   cout << mdl.diff_variance(data[i][j], x[j], j) << \" \";\n          //   cout << mdl.variance(data[i][j], x[j], j) << endl;\n          //   break;\n          // }\n          if (isnan(upd)){\n            terminate = 1;\n            break;\n          }\n        }\n      if (terminate)\n        break;\n    }\n    if (terminate)\n      grad[j] = 0;\n    else\n      grad[j] = gr;\n  }\n}\n\nAdaCluster::AdaCluster(const vector<vector<double>>& data_,\n                       const vector<unsigned long int>& label_,\n                       unsigned long int max_round_, unsigned long int k_)\n    : data(data_), label(label_) {\n  max_round = max_round_;\n  k = k_;\n  nmis.resize(max_round);\n  fill(nmis.begin(), nmis.end(), 0);\n  logliks.resize(max_round);\n  fill(logliks.begin(), logliks.end(), -numeric_limits<double>::max());\n  n_samples = data.size();\n  n_dims = data[0].size();\n  log_pi.resize(k);\n  fill(log_pi.begin(), log_pi.end(), -log(k));\n  log_asg_sum.resize(k);\n  max_log_pi.resize(k);\n  kappa.resize(n_dims);\n  kappa_a.resize(n_dims);\n  kappa_b.resize(n_dims);\n  mu.resize(k);\n  mu_a.resize(k);\n  mu_b.resize(k);\n  for (size_t c = 0; c < k; ++c){\n    mu[c].resize(n_dims);\n    mu_a[c].resize(n_dims);\n    mu_b[c].resize(n_dims);\n  }\n  log_asg.resize(n_samples);\n  asg.resize(n_samples);\n  for (size_t i = 0; i < n_samples; ++i) log_asg[i].resize(k);\n  attr_discrete.resize(n_dims);\n  attr_positive.resize(n_dims);\n  attr_nonnegative.resize(n_dims);\n\n  alpha.resize(n_dims);\n  lb.resize(n_dims);\n  ub.resize(n_dims);\n  for (unsigned long int j = 0; j < n_dims; ++j) {\n    attr_discrete[j] = is_discrete(data, j);\n    attr_positive[j] = is_positive(data, j);\n    attr_nonnegative[j] = attr_positive[j];\n    if (!attr_positive[j]) attr_nonnegative[j] = is_nonnegative(data, j);\n  }\n  for (unsigned long int j = 0; j < n_dims; ++j) {\n    if (attr_discrete[j]) {\n      if (attr_nonnegative[j]) {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      } else {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      }\n    } else {\n      if (attr_positive[j]) {\n        alpha[j] = 0;\n        // lb[j] = -numeric_limits<double>::max();\n        lb[j] = -10;\n        ub[j] = 2;\n      } else if (attr_nonnegative[j]) {\n        alpha[j] = 0.5;\n        lb[j] = 0;\n        ub[j] = 1;\n      } else {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      }\n    }\n  }\n}\n\ndouble AdaCluster::distance(const double x,\n                            const double y,\n                            const double alpha,\n                            const unsigned long int dim) {\n  // return nnc_distance(x, y, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_distance(x, y, alpha);\n    else\n      return rc_distance(x, y, alpha);\n  } else{\n    if (attr_nonnegative[dim])\n      return nnc_distance(x, y, alpha);\n    else\n      return rc_distance(x, y, alpha);\n  }\n}\n\ndouble AdaCluster::variance(const double x,\n                            const double alpha,\n                            const unsigned long int dim){\n  // return nnc_variance(x, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_variance(x, alpha);\n    else\n      return rc_variance(x, alpha);\n  } else {\n    if (attr_nonnegative[dim])\n      return nnc_variance(x, alpha);\n    else\n      return rc_variance(x, alpha);\n  }\n}\n\ndouble AdaCluster::diff_distance(const double x,\n                                 const double y,\n                                 const double alpha,\n                                 const unsigned long int dim) {\n  // return nnc_diff_distance(x, y, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_diff_distance(x, y, alpha);\n    else\n      return rc_diff_distance(x, y, alpha);\n  } else {\n    if (attr_nonnegative[dim])\n      return nnc_diff_distance(x, y, alpha);\n    else\n      return rc_diff_distance(x, y, alpha);\n  }\n}\n\n\ndouble AdaCluster::diff_variance(const double x,\n                                 const double alpha,\n                                 const unsigned long int dim) {\n  // return nnc_diff_variance(x, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_diff_variance(x, alpha);\n    else\n      return rc_diff_variance(x, alpha);\n  } else {\n    if (attr_nonnegative[dim])\n      return nnc_diff_variance(x, alpha);\n    else\n      return rc_diff_variance(x, alpha);\n  }\n}\n\nunsigned long int AdaCluster::get_k() { return k; }\n\nunsigned long int AdaCluster::get_max_round() { return max_round; }\n\nunsigned long int AdaCluster::get_n_dims() { return n_dims; }\n\nunsigned long int AdaCluster::get_n_samples() { return n_samples; }\n\nvector<double>& AdaCluster::get_kappa() { return kappa; }\n\nvector<double>& AdaCluster::get_log_pi() { return log_pi; }\n\nvector<double>& AdaCluster::get_logliks() { return logliks; }\n\nvector<double>& AdaCluster::get_nmis() { return nmis; }\n\ncopt::Vector<double>& AdaCluster::get_alpha() { return alpha; }\n\ncopt::Vector<double>& AdaCluster::get_lb() { return lb; }\n\ncopt::Vector<double>& AdaCluster::get_ub() { return ub; }\n\nconst vector<vector<double>>& AdaCluster::get_data() { return data; }\n\nvector<vector<double>>& AdaCluster::get_log_asg() { return log_asg; }\n\nvector<vector<double>>& AdaCluster::get_mu() { return mu; }\n\nvoid AdaCluster::initialize_random() {\n  unsigned long int ri;\n  for (size_t c = 0; c < k; ++c) {\n    ri = rand() % n_samples;\n    for (unsigned long int j = 0; j < n_dims; ++j){\n      mu[c][j] = data[ri][j];\n      mu_a[c][j] = mu[c][j];\n      mu_b[c][j] = 1.0;\n    }\n  }\n  for (unsigned long int j = 0; j < n_dims; ++j){\n    kappa[j] = 1.0;\n    kappa_a[j] = 1.0;\n    kappa_b[j] = 1e-9;\n  }\n}\n\nvoid AdaCluster::initialize_k_plus_plus() {\n  boost::mt19937 gen;\n  unsigned long int ri, k_eff;\n  ri = rand() % n_samples;\n  for (unsigned long int j = 0; j < n_dims; ++j) mu[0][j] = data[ri][j];\n  k_eff = 1;\n  vector<double> probs(n_samples, 0);\n  double dist, best_dist;\n  do {\n    for (size_t i = 0; i < n_samples; ++i) {\n      best_dist = numeric_limits<double>::max();\n      for (size_t c = 0; c < k_eff; ++c) {\n        dist = 0;\n        for (unsigned long int j = 0; j < n_dims; ++j){\n          // dist += distance(data[i][j], mu[c][j], alpha[j], j);\n          dist += pow(data[i][j] - mu[c][j], 2);\n        }\n        if (dist < best_dist) best_dist = dist;\n      }\n      probs[i] = pow(best_dist, 2);\n    }\n    boost::random::discrete_distribution<> dist(probs.begin(), probs.end());\n    ri = dist(gen);\n    for (unsigned long int j = 0; j < n_dims; ++j) mu[k_eff][j] = data[ri][j];\n    k_eff += 1;\n  } while (k_eff != k);\n\n  for (unsigned long int j = 0; j < n_dims; ++j)\n    if (attr_nonnegative[j])\n      for (size_t c = 0; c < k_eff; ++c)\n        if (mu[c][j] == 0)\n          mu[c][j] = 1e-9;\n  for (unsigned long int j = 0; j < n_dims; ++j){\n    kappa[j] = 1.0;\n    kappa_a[j] = 1.0;\n    kappa_b[j] = 1.0;\n  }\n  for (size_t c = 0; c < k_eff; ++c)\n    for (unsigned long int j = 0; j < n_dims; ++j){\n      mu_a[c][j] = mu[c][j];\n      mu_b[c][j] = 1.0;\n    }\n}\n\nvoid AdaCluster::fit() {\n  bool updated = 0;\n  double loglik = 0;\n  double nmi = 0;\n  double dist = 0;\n  double best_dist = 0;\n  unsigned long int best_asg = -1;\n  Hyperparam prblm(*this);\n  prblm.setLowerBound(lb);\n  prblm.setUpperBound(ub);\n  for (size_t r = 0; r < max_round; r++) {\n    updated = 0;\n    loglik = 0.0;\n    fill(max_log_pi.begin(), max_log_pi.end(), -numeric_limits<double>::max());\n    for (size_t i = 0; i < n_samples; ++i) {\n      for (size_t c = 0; c < k; ++c) {\n        log_asg[i][c] = log_pi[c];\n        for (unsigned long int j = 0; j < n_dims; ++j)\n          if (!isnan(data[i][j])){\n            double dist = distance(data[i][j], mu[c][j], alpha[j], j) / kappa[j];\n            double var = variance(data[i][j], alpha[j], j);\n            log_asg[i][c] -= dist + 0.5 * (log(2 * M_PI) + log(kappa[j]) + log(var));\n          }\n      }\n      double norm = logsumexp(log_asg[i]);\n      for (size_t c = 0; c < k; ++c) log_asg[i][c] -= norm;\n      loglik += norm;\n      for (size_t c = 0; c < k; ++c)\n        if (log_asg[i][c] > max_log_pi[c]) max_log_pi[c] = log_asg[i][c];\n    }\n    for (size_t c = 0; c < k; ++c) {\n      log_asg_sum[c] = 0.0;\n      for (size_t i = 0; i < n_samples; ++i)\n        log_asg_sum[c] += exp(log_asg[i][c] - max_log_pi[c]);\n      log_asg_sum[c] = log(log_asg_sum[c]) + max_log_pi[c];\n      log_pi[c] = log_asg_sum[c] - log(n_samples);\n    }\n\n    for (size_t c = 0; c < k; c++)\n      for (unsigned long int j = 0; j < n_dims; ++j) {\n        double tmp = 0.0;\n        for (size_t i = 0; i < n_samples; ++i)\n          if (!isnan(data[i][j]))\n            tmp += exp(log_asg[i][c])*data[i][j];\n        mu[c][j] = (kappa[j]*mu_a[c][j]*mu_b[c][j] + tmp\n          )/(kappa[j]*mu_b[c][j] + exp(log_asg_sum[c]));\n        // vector<double> pos(n_samples, 0);\n        // vector<double> neg(n_samples, 0);\n        // double zero_count = 0;\n        // for (size_t i = 0; i < n_samples; ++i){\n        //   if (data[i][j] > 0)\n        //     pos[i] = log_asg[i][c] + log(data[i][j]);\n        //   else if (data[i][j] < 0)\n        //     neg[i] = log_asg[i][c] + log(-data[i][j]);\n        //   else\n        //     zero_count += 1;\n        // }\n        // mu[c][j] = (kappa[j]*mu_a[c][j] + exp(logsumexp(pos)) - exp(logsumexp(neg))\n        //             )/(kappa[j]*mu_b[c][j] + exp(log_asg_sum[c]));\n      }\n\n    double pr_asg = 0.0;\n    double nom = 0.0;\n    double denom = 0.0;\n    for (unsigned long int j = 0; j < n_dims; ++j) {\n      nom = 0.0;\n      denom = 0.0;\n      for (size_t i = 0; i < n_samples; ++i)\n        for (size_t c = 0; c < k; c++) {\n          pr_asg = exp(log_asg[i][c]);\n          if (!isnan(data[i][j])) {\n            nom += pr_asg * distance(data[i][j], mu[c][j], alpha[j], j);\n            denom += pr_asg;\n          }\n        }\n      kappa[j] =  (kappa_b[j] + nom) / (kappa_a[j] + 0.5*denom);\n    }\n\n    copt::Vector<double> alpha_prev(alpha);\n    // cout << alpha.transpose() << endl;\n    copt::LbfgsbSolver<Hyperparam> solver;\n    solver.minimize(prblm, alpha);\n    // cout << alpha.transpose() << endl;\n\n    for (unsigned long int j = 0; j < n_dims; ++j)\n      if (isnan(alpha[j]))\n        alpha[j] = alpha_prev[j];\n\n    for (size_t i = 0; i < n_samples; ++i) {\n      best_dist = log_asg[i][0];\n      best_asg = 0;\n      for (size_t c = 1; c < k; ++c)\n        if (log_asg[i][c] > best_dist) {\n          best_dist = log_asg[i][c];\n          best_asg = c;\n        }\n      if (asg[i] != best_asg) {\n        asg[i] = best_asg;\n        updated = 1;\n      }\n    }\n    nmi = calc_nmi(label, asg);\n    nmis[r] = nmi;\n    cout << \"round=\" << r << \" nmi=\" << nmi << \" loglik=\" << loglik << endl;\n    if (!updated) break;\n  }\n  cout << \"Alpha=\";\n  for (unsigned long int j = 0; j < n_dims; ++j)\n      cout << alpha[j] << \" \";\n  cout << endl;\n  cout << \"Kappa=\";\n  for (unsigned long int j = 0; j < n_dims; ++j)\n      cout << kappa[j] << \" \";\n  cout << endl;\n  for (size_t c = 0; c < k; ++c){\n    cout << \"mu[\" << c << \"]=\";\n    for (unsigned long int j = 0; j < n_dims; ++j)\n        cout << mu[c][j] << \" \";\n    cout << endl;\n  }\n}\n\n// GMM::GMM(const vector<vector<double>>& data_,\n//          const vector<unsigned long int>& label_, unsigned long int max_round_,\n//          unsigned long int k_)\n//     : AdaCluster(data_, label_, max_round_, k_) {}\n\n// double GMM::log_base_measure(unsigned long int sample, unsigned long int dim) {\n//   return -0.5 * log(M_PI) - 0.5 * log(kappa[dim]);\n// }\n\n// double GMM::distance(const double x, double y, unsigned long int dim) {\n//   return pow(x - y, 2) / 2.0;\n// }\n\n// void GMM::update_hyperparams() {}\n\n// BSC::BSC(const vector<vector<double>>& data_,\n//          const vector<unsigned long int>& label_, unsigned long int max_round_,\n//          unsigned long int k_)\n//     : AdaCluster(data_, label_, max_round_, k_) {\n//   beta.resize(n_dims);\n//   for (unsigned long int j = 0; j < n_dims; ++j) beta[j] = 2.0;\n//   sum_log_data.resize(n_dims);\n//   fill(sum_log_data.begin(), sum_log_data.end(), 0);\n//   for (unsigned long int j = 0; j < n_dims; ++j)\n//     for (size_t i = 0; i < n_samples; ++i) sum_log_data[j] += log_data[i][j];\n// }\n\n// vector<double>& BSC::get_beta() { return beta; }\n\n// double BSC::log_base_measure(unsigned long int sample, unsigned long int dim) {\n//   return -0.5 * log(M_PI) - 0.5 * log(kappa[dim]) -\n//          0.5 * (2.0 - beta[dim]) * log_data[sample][dim];\n// }\n\n// double BSC::distance(const double x, double y, unsigned long int dim) {\n//   return beta_div(x, y, beta[dim]);\n// }\n\n// void BSC::update_hyperparams() {\n//   vector<double> x(n_dims);\n//   vector<double> lb(n_dims);\n//   vector<double> ub(n_dims);\n//   for (unsigned long int j = 0; j < n_dims; ++j) {\n//     lb[j] = -numeric_limits<double>::max();\n//     ub[j] = numeric_limits<double>::max();\n//     // lb[j] = -5.0;\n//     // ub[j] = 5.0;\n//   }\n//   Saddle saddle(data, log_data, log_asg, log_pi, mu, kappa);\n//   saddle.setLowerBound(lb);\n//   saddle.setUpperBound(ub);\n//   copt::LbfgsbSolver<double> solver;\n//   int max_trial = 1;\n//   double estimate = 0.0;\n//   bool success = 1;\n//   for (int trial = 0; trial < max_trial; trial++) {\n//     for (unsigned long int j = 0; j < n_dims; ++j) x[j] = beta[j];\n//     solver.minimize(saddle, x);\n//     success = 1;\n//     for (unsigned long int j = 0; j < n_dims; ++j)\n//       if (std::isnan(x[j]) || !std::isfinite(x[j])) {\n//         success = 0;\n//         break;\n//       }\n//     if (success) break;\n//   }\n//   for (unsigned long int j = 0; j < n_dims; ++j) {\n//     beta[j] = x[j];\n//     // cout << \" beta[\" << j << \"]=\" << beta[j];\n//   }\n//   // cout << endl;\n// }\n", "meta": {"hexsha": "d7210ea6e3782e9a848cc513c3115014849f70d5", "size": 16599, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/soft_clustering.cc", "max_stars_repo_name": "mehmetbasbug/adacluster", "max_stars_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-19T14:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-14T21:44:43.000Z", "max_issues_repo_path": "src/soft_clustering.cc", "max_issues_repo_name": "mehmetbasbug/adacluster", "max_issues_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/soft_clustering.cc", "max_forks_repo_name": "mehmetbasbug/adacluster", "max_forks_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_forks_repo_licenses": ["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.6171428571, "max_line_length": 90, "alphanum_fraction": 0.5261160311, "num_tokens": 5169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5715487741578383}}
{"text": "#include \"Nodal.h\"\n#include \"Functions.h\"\n#include \"quadrules/GaussJacobi.h\"\n#include \"quadrules/IntervalQuadratureRule.h\"\n#include \"util/Combinatorics.h\"\n\n#include <Eigen/LU>\n\n#include <algorithm>\n#include <cassert>\n#include <iterator>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace tndm {\n\nstd::vector<double> LegendreGaussLobattoPoints(unsigned n, unsigned a, unsigned b) {\n    assert(n >= 2);\n\n    auto gjPoints = GaussJacobi(n - 2, a + 1, b + 1).points();\n    std::vector<double> glPoints;\n    glPoints.reserve(n);\n    glPoints.push_back(-1.0);\n    std::copy(gjPoints.rbegin(), gjPoints.rend(), std::back_inserter(glPoints));\n    glPoints.push_back(1.0);\n    return glPoints;\n}\n\ntemplate <std::size_t D>\nMatrixXd Vandermonde(unsigned degree, std::vector<std::array<double, D>> const& points) {\n    assert(binom(degree + D, D) == points.size());\n\n    MatrixXd vandermonde(points.size(), binom(degree + D, D));\n\n    for (std::size_t i = 0; i < points.size(); ++i) {\n        std::size_t bf = 0;\n        for (auto j : AllIntegerSums<D>(degree)) {\n            vandermonde(i, bf++) = DubinerP(j, points[i]);\n        }\n    }\n\n    return vandermonde;\n}\n\ntemplate <std::size_t D>\nLebesgueFunction<D>::LebesgueFunction(unsigned degree,\n                                      std::vector<std::array<double, D>> const& nodes)\n    : degree(degree), phi(nodes.size()), L(nodes.size()) {\n    auto vandermonde = Vandermonde(degree, nodes);\n    vInvT = vandermonde.transpose().inverse();\n}\n\ntemplate <std::size_t D> double LebesgueFunction<D>::operator()(std::array<double, D> const& xi) {\n    std::size_t bf = 0;\n    for (auto j : AllIntegerSums<D>(degree)) {\n        phi(bf++) = DubinerP(j, xi);\n    }\n    assert(bf == vInvT.cols());\n    L = vInvT * phi;\n    return L.lpNorm<1>();\n}\n\ntemplate MatrixXd Vandermonde<1u>(unsigned, std::vector<std::array<double, 1u>> const&);\ntemplate MatrixXd Vandermonde<2u>(unsigned, std::vector<std::array<double, 2u>> const&);\ntemplate MatrixXd Vandermonde<3u>(unsigned, std::vector<std::array<double, 3u>> const&);\n\ntemplate class LebesgueFunction<1u>;\ntemplate class LebesgueFunction<2u>;\ntemplate class LebesgueFunction<3u>;\n\n} // namespace tndm\n", "meta": {"hexsha": "5d80743f22ea9f7a321866199d92cf2a87af5fdc", "size": 2184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/Nodal.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "src/basis/Nodal.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "src/basis/Nodal.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 29.9178082192, "max_line_length": 98, "alphanum_fraction": 0.657967033, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5714625703637626}}
{"text": "﻿#include \"sbs/common/primitive.h\"\n\n#include <Eigen/Geometry>\n\nnamespace sbs {\nnamespace common {\n\nline_segment_t::line_segment_t(point_t const& p, point_t const& q) : p(p), q(q) {}\n\ntriangle_t::triangle_t(point_t const& a, point_t const& b, point_t const& c) : p_{a, b, c} {}\n\nnormal_t triangle_t::normal() const\n{\n    Eigen::Vector3d const ab = b() - a();\n    Eigen::Vector3d const ac = c() - a();\n    return ab.cross(ac).normalized();\n}\n\ndouble triangle_t::area() const\n{\n    return 0.5 * (b() - a()).cross(c() - a()).norm();\n}\n\nstd::array<line_segment_t, 3u> triangle_t::edges() const\n{\n    return std::array<line_segment_t, 3u>{\n        line_segment_t{p1(), p2()},\n        line_segment_t{p2(), p3()},\n        line_segment_t{p3(), p1()}};\n}\n\nstd::array<point_t, 3u> const& triangle_t::nodes() const\n{\n    return p_;\n}\n\nstd::array<point_t, 3u>& triangle_t::nodes()\n{\n    return p_;\n}\n\npoint_t const& triangle_t::p1() const\n{\n    return p_[0];\n}\n\npoint_t const& triangle_t::p2() const\n{\n    return p_[1];\n}\n\npoint_t const& triangle_t::p3() const\n{\n    return p_[2];\n}\n\npoint_t& triangle_t::p1()\n{\n    return p_[0];\n}\n\npoint_t& triangle_t::p2()\n{\n    return p_[1];\n}\n\npoint_t& triangle_t::p3()\n{\n    return p_[2];\n}\n\npoint_t const& triangle_t::a() const\n{\n    return p1();\n}\n\npoint_t const& triangle_t::b() const\n{\n    return p2();\n}\n\npoint_t const& triangle_t::c() const\n{\n    return p3();\n}\n\npoint_t& triangle_t::a()\n{\n    return p1();\n}\n\npoint_t& triangle_t::b()\n{\n    return p2();\n}\n\npoint_t& triangle_t::c()\n{\n    return p3();\n}\n\nray_t::ray_t(point_t const& p, direction_t const& v) : p(p), v(v) {}\n\nsphere_t::sphere_t(point_t const& center, double radius) : center(center), radius(radius) {}\n\nsphere_t sphere_t::from(tetrahedron_t const& t)\n{\n    common::point_t const approx_barycenter =\n        0.25 * t.p1() + 0.25 * t.p2() + 0.25 * t.p3() + 0.25 * t.p4();\n    auto const d1     = (approx_barycenter - t.p1()).norm();\n    auto const d2     = (approx_barycenter - t.p2()).norm();\n    auto const d3     = (approx_barycenter - t.p3()).norm();\n    auto const d4     = (approx_barycenter - t.p4()).norm();\n    auto const radius = std::max({d1, d2, d3, d4});\n    sphere_t const sphere{approx_barycenter, radius};\n    return sphere;\n}\n\nsphere_t sphere_t::from(triangle_t const& t)\n{\n    common::point_t const approx_barycenter = 0.33 * t.p1() + 0.33 * t.p2() + 0.34 * t.p3();\n    auto const d1                           = (approx_barycenter - t.p1()).norm();\n    auto const d2                           = (approx_barycenter - t.p2()).norm();\n    auto const d3                           = (approx_barycenter - t.p3()).norm();\n    auto const radius                       = std::max({d1, d2, d3});\n    sphere_t const sphere{approx_barycenter, radius};\n    return sphere;\n}\n\nbool operator==(line_segment_t const& l1, line_segment_t const& l2)\n{\n    return l1.p.isApprox(l2.p) && l1.q.isApprox(l2.q);\n}\n\nbool operator!=(line_segment_t const& l1, line_segment_t const& l2)\n{\n    return !(l1 == l2);\n}\n\nline_segment_t operator+(line_segment_t const& l, vector3d_t const& t)\n{\n    return line_segment_t(l.p + t, l.q + t);\n}\n\nline_segment_t operator+(vector3d_t const& t, line_segment_t const& l)\n{\n    return l + t;\n}\n\nline_segment_t operator*(Eigen::Matrix3d const& R, line_segment_t const& l)\n{\n    return line_segment_t(R * l.p, R * l.q);\n}\n\nstd::tuple<double, double, double>\nbarycentric_coordinates(point_t const& A, point_t const& B, point_t const& C, point_t const& p)\n{\n    Eigen::Vector3d const v0 = B - A;\n    Eigen::Vector3d const v1 = C - A;\n    Eigen::Vector3d const v2 = p - A;\n\n    Eigen::Vector3d const AB = B - A;\n    Eigen::Vector3d const AC = C - A;\n    Eigen::Vector3d const AP = p - A;\n\n    double const d00   = AB.dot(AB);\n    double const d01   = AB.dot(AC);\n    double const d11   = AC.dot(AC);\n    double const d20   = AP.dot(AB);\n    double const d21   = AP.dot(AC);\n    double const denom = d00 * d11 - d01 * d01;\n    double const v     = (d11 * d20 - d01 * d21) / denom;\n    double const w     = (d00 * d21 - d01 * d20) / denom;\n    double const u     = 1.0 - v - w;\n\n    return std::make_tuple(u, v, w);\n}\n\nbool intersects(tetrahedron_t const& t1, tetrahedron_t const& t2)\n{\n    std::array<common::normal_t, 44u> separating_axis{};\n    auto const& t1_triangles = t1.faces();\n    auto const& t2_triangles = t2.faces();\n\n    auto const face_axis_transform = [](common::triangle_t const& f) {\n        return f.normal();\n    };\n\n    auto separating_axis_it = std::transform(\n        t1_triangles.begin(),\n        t1_triangles.end(),\n        separating_axis.begin(),\n        face_axis_transform);\n    separating_axis_it = std::transform(\n        t2_triangles.begin(),\n        t2_triangles.end(),\n        separating_axis_it,\n        face_axis_transform);\n\n    auto const t1_edges = t1.edges();\n    auto const t2_edges = t2.edges();\n\n    for (auto const& edge : t1_edges)\n    {\n        auto const edge_edge_separating_axis_transform_op =\n            [&edge](common::line_segment_t const& e) {\n                Eigen::Vector3d const d1 = edge.q - edge.p;\n                Eigen::Vector3d d2       = e.q - e.p;\n\n                auto axis = d1.cross(d2);\n\n                double constexpr eps = std::numeric_limits<double>::epsilon();\n                // Check if edges are parallel up to numerical precision eps\n                if (axis.isZero(eps))\n                {\n                    d2   = e.p - edge.p;\n                    axis = d1.cross(d2);\n                }\n                // Check if edges are on the same line up to numerical precision eps\n                if (axis.isZero(eps))\n                {\n                    // Cancel this axis as a potential separating axis. When projecting\n                    // nodes onto this axis, everything will be zeroed out, and thus no\n                    // separating interval can be found. The separating axis test for\n                    // this axis will fail.\n                    axis.setZero();\n                }\n\n                return axis;\n            };\n        separating_axis_it = std::transform(\n            t2_edges.begin(),\n            t2_edges.end(),\n            separating_axis_it,\n            edge_edge_separating_axis_transform_op);\n    }\n\n    auto const is_separating_axis = [&t1, &t2](common::normal_t const& axis) {\n        if (axis.isZero())\n            return false;\n\n        auto const project = [axis](common::point_t const& p) {\n            return p.dot(axis);\n        };\n\n        std::array<double, 4u> const projection1{\n            project(t1.p1()),\n            project(t1.p2()),\n            project(t1.p3()),\n            project(t1.p4())};\n\n        std::array<double, 4u> const projection2{\n            project(t2.p1()),\n            project(t2.p2()),\n            project(t2.p3()),\n            project(t2.p4())};\n\n        auto const [min_it1, max_it1] = std::minmax_element(projection1.begin(), projection1.end());\n        auto const [min_it2, max_it2] = std::minmax_element(projection2.begin(), projection2.end());\n\n        bool const has_separating_interval = (*max_it1 < *min_it2) || (*max_it2 < *min_it1);\n        return has_separating_interval;\n    };\n\n    return std::none_of(separating_axis.begin(), separating_axis.end(), is_separating_axis);\n}\n\nbool intersects(triangle_t const& triangle, tetrahedron_t const& tetrahedron)\n{\n    std::array<common::normal_t, 23u> separating_axis{};\n    auto const& tet_triangles = tetrahedron.faces();\n\n    auto const face_axis_transform = [](common::triangle_t const& f) {\n        return f.normal();\n    };\n\n    separating_axis.front() = triangle.normal();\n\n    auto separating_axis_it = separating_axis.begin() + 1u;\n    separating_axis_it      = std::transform(\n        tet_triangles.begin(),\n        tet_triangles.end(),\n        separating_axis_it,\n        face_axis_transform);\n\n    auto const t1_edges = triangle.edges();\n    auto const t2_edges = tetrahedron.edges();\n\n    for (auto const& edge : t1_edges)\n    {\n        auto const edge_edge_separating_axis_transform_op =\n            [&edge](common::line_segment_t const& e) {\n                Eigen::Vector3d const d1 = edge.q - edge.p;\n                Eigen::Vector3d d2       = e.q - e.p;\n\n                auto axis = d1.cross(d2);\n\n                double constexpr eps = std::numeric_limits<double>::epsilon();\n                // Check if edges are parallel up to numerical precision eps\n                if (axis.isZero(eps))\n                {\n                    d2   = e.p - edge.p;\n                    axis = d1.cross(d2);\n                }\n                // Check if edges are on the same line up to numerical precision eps\n                if (axis.isZero(eps))\n                {\n                    // Cancel this axis as a potential separating axis. When projecting\n                    // nodes onto this axis, everything will be zeroed out, and thus no\n                    // separating interval can be found. The separating axis test for\n                    // this axis will fail.\n                    axis.setZero();\n                }\n\n                return axis;\n            };\n        separating_axis_it = std::transform(\n            t2_edges.begin(),\n            t2_edges.end(),\n            separating_axis_it,\n            edge_edge_separating_axis_transform_op);\n    }\n\n    auto const is_separating_axis = [&triangle, &tetrahedron](common::normal_t const& axis) {\n        if (axis.isZero())\n            return false;\n\n        auto const project = [axis](common::point_t const& p) {\n            return p.dot(axis);\n        };\n\n        std::array<double, 3u> const projection1{\n            project(triangle.p1()),\n            project(triangle.p2()),\n            project(triangle.p3())};\n\n        std::array<double, 4u> const projection2{\n            project(tetrahedron.p1()),\n            project(tetrahedron.p2()),\n            project(tetrahedron.p3()),\n            project(tetrahedron.p4())};\n\n        auto const [min_it1, max_it1] = std::minmax_element(projection1.begin(), projection1.end());\n        auto const [min_it2, max_it2] = std::minmax_element(projection2.begin(), projection2.end());\n\n        bool const has_separating_interval = (*max_it1 < *min_it2) || (*max_it2 < *min_it1);\n        return has_separating_interval;\n    };\n\n    return std::none_of(separating_axis.begin(), separating_axis.end(), is_separating_axis);\n}\n\nbool intersects(point_t const& point, tetrahedron_t const& tetrahedron)\n{\n    auto const project = [](common::point_t const& p, common::triangle_t const& triangle) {\n        auto const n = triangle.normal();\n        auto const d = p - triangle.p1();\n        return n.dot(d);\n    };\n    std::array<common::triangle_t, 4u> const faces = tetrahedron.faces();\n    std::array<double, 4u> const projections{\n        project(point, faces[0]),\n        project(point, faces[1]),\n        project(point, faces[2]),\n        project(point, faces[3])};\n\n    return std::none_of(projections.begin(), projections.end(), [](double const s) {\n        return s > 0.;\n    });\n}\n\nstd::optional<point_t> intersect(line_segment_t const& segment, triangle_t const& triangle)\n{\n    Eigen::Vector3d const ab = triangle.b() - triangle.a();\n    Eigen::Vector3d const ac = triangle.c() - triangle.a();\n    Eigen::Vector3d const qp = segment.p - segment.q;\n\n    Eigen::Vector3d const n = ab.cross(ac);\n\n    double const d = qp.dot(n);\n    if (d <= 0.)\n        return {};\n\n    Eigen::Vector3d const ap = segment.p - triangle.a();\n    double const t           = ap.dot(n);\n    if (t < 0.)\n        return {};\n    if (t > d)\n        return {};\n\n    Eigen::Vector3d const e = qp.cross(ap);\n    double v                = ac.dot(e);\n    if (v < 0. || v > d)\n        return {};\n\n    double w = -ab.dot(e);\n    if (w < 0. || (v + w) > d)\n        return {};\n\n    double const ood = 1. / d;\n    v *= ood;\n    w *= ood;\n    double const u             = 1. - v - w;\n    point_t const intersection = u * triangle.a() + v * triangle.b() + w * triangle.c();\n    return intersection;\n}\n\nstd::optional<point_t> intersect(ray_t const& ray, triangle_t const& triangle)\n{\n    Eigen::Vector3d const& p = ray.p;\n    Eigen::Vector3d const& q = ray.p + 1. * ray.v;\n    Eigen::Vector3d const ab = triangle.b() - triangle.a();\n    Eigen::Vector3d const ac = triangle.c() - triangle.a();\n    Eigen::Vector3d const qp = p - q;\n\n    Eigen::Vector3d const n = ab.cross(ac);\n\n    double const d = qp.dot(n);\n    if (d <= 0.)\n        return {};\n\n    Eigen::Vector3d const ap = p - triangle.a();\n    double const t           = ap.dot(n);\n    if (t < 0.)\n        return {};\n\n    Eigen::Vector3d const e = qp.cross(ap);\n    double v                = ac.dot(e);\n    if (v < 0. || v > d)\n        return {};\n\n    double w = -ab.dot(e);\n    if (w < 0. || (v + w) > d)\n        return {};\n\n    double const ood = 1. / d;\n    // t *= ood;\n    v *= ood;\n    w *= ood;\n    double const u             = 1. - v - w;\n    point_t const intersection = u * triangle.a() + v * triangle.b() + w * triangle.c();\n    return intersection;\n}\n\nstd::optional<point_t> intersect_twoway(line_segment_t const& segment, triangle_t const& triangle)\n{\n    auto const intersection = intersect(segment, triangle);\n    if (intersection.has_value())\n        return intersection;\n\n    line_segment_t const flipped_segment{segment.q, segment.p};\n    return intersect(flipped_segment, triangle);\n}\n\nstd::optional<point_t> intersect_twoway(ray_t const& ray, triangle_t const& triangle)\n{\n    auto const intersection = intersect(ray, triangle);\n    if (intersection.has_value())\n        return intersection;\n\n    triangle_t const flipped_triangle{triangle.a(), triangle.c(), triangle.b()};\n    return intersect(ray, flipped_triangle);\n}\n\nstd::optional<point_t> intersect(line_segment_t const& segment, plane_t const& plane)\n{\n    double const d           = plane.p.dot(plane.n);\n    Eigen::Vector3d const pq = segment.q - segment.p;\n    double const t           = (d - plane.n.dot(segment.p)) / (plane.n.dot(pq));\n\n    if (t >= 0.0 && t <= 1.0)\n    {\n        Eigen::Vector3d const intersection = segment.p + t * pq;\n        return intersection;\n    }\n    return {};\n}\n\n/**\n * @brief\n * Implementation of closest point on triangle to a point P from Christer Ericson's Real-Time\n * Collision Detection\n * @param p Point off triangle\n * @param t Triangle on which we wish to find the closest point to p\n * @return The closest point q on triangle t to point p\n */\npoint_t closest_point(point_t const& p, triangle_t const& t)\n{\n    auto const& a = t.a();\n    auto const& b = t.b();\n    auto const& c = t.c();\n\n    // Check if P in vertex region outside A\n    common::vector3d_t const ab = b - a;\n    common::vector3d_t const ac = c - a;\n    common::vector3d_t const ap = p - a;\n    double const d1             = ab.dot(ap);\n    double const d2             = ac.dot(ap);\n    if (d1 <= 0.0 && d2 <= 0.0)\n        return a; // barycentric coordinates (1,0,0)\n\n    // Check if P in vertex region outside B\n    common::vector3d_t const bp = p - b;\n    double const d3             = ab.dot(bp);\n    double const d4             = ac.dot(bp);\n    if (d3 >= 0.0 && d4 <= d3)\n        return b; // barycentric coordinates (0,1,0)\n\n    // Check if P in edge region of AB, if so return projection of P onto AB\n    double const vc = d1 * d4 - d3 * d2;\n    if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0)\n    {\n        double const v = d1 / (d1 - d3);\n        return a + v * ab; // barycentric coordinates (1-v, v,0)\n    }\n\n    // Check if P in vertex region outside C\n    common::vector3d_t const cp = p - c;\n    double const d5             = ab.dot(cp);\n    double const d6             = ac.dot(cp);\n    if (d6 >= 0.0 && d5 <= d6)\n        return c; // barycentric coordinates (0,0,1)\n\n    // Check if P in edge region of AC, if so return projection of P onto AC\n    double const vb = d5 * d2 - d1 * d6;\n    if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0)\n    {\n        double const w = d2 / (d2 - d6);\n        return a + w * ac; // barycentric coordinates (1-w, 0, w)\n    }\n\n    // Check if P in edge region of BC, if so return projection of P onto BC\n    double const va = d3 * d6 - d5 * d4;\n    if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0)\n    {\n        double const w = (d4 - d3) / ((d4 - d3) + (d5 - d6));\n        return b + w * (c - b); // barycentric coordinates (0,1-w, w)\n    }\n\n    // P inside face region. Compute Q through its barycentric coordinates (u, v, w)\n    double const denom = 1.0 / (va + vb + vc);\n    double const v     = vb * denom;\n    double const w     = vc * denom;\n    return a + ab * v + ac * w; //=u*a+v*b+w*c,u=va* denom=1.0f−v−w\n}\n\ntetrahedron_t::tetrahedron_t(\n    point_t const& p1,\n    point_t const& p2,\n    point_t const& p3,\n    point_t const& p4)\n    : p_{p1, p2, p3, p4}\n{\n}\n\ndouble tetrahedron_t::unsigned_volume() const\n{\n    return std::abs(signed_volume());\n}\n\ndouble tetrahedron_t::signed_volume() const\n{\n    vector3d_t const p21 = p2() - p1();\n    vector3d_t const p31 = p3() - p1();\n    vector3d_t const p41 = p4() - p1();\n    return p21.cross(p31).dot(p41);\n}\n\nstd::array<triangle_t, 4u> tetrahedron_t::faces() const\n{\n    return std::array<triangle_t, 4u>{\n        triangle_t{p1(), p2(), p4()},\n        triangle_t{p2(), p3(), p4()},\n        triangle_t{p3(), p1(), p4()},\n        triangle_t{p1(), p3(), p2()}};\n}\n\nstd::array<line_segment_t, 6u> tetrahedron_t::edges() const\n{\n    return std::array<line_segment_t, 6u>{\n        line_segment_t{p1(), p2()},\n        line_segment_t{p2(), p3()},\n        line_segment_t{p3(), p1()},\n        line_segment_t{p1(), p4()},\n        line_segment_t{p2(), p4()},\n        line_segment_t{p3(), p4()},\n    };\n}\n\nstd::array<point_t, 4u> const& tetrahedron_t::nodes() const\n{\n    return p_;\n}\n\nstd::array<point_t, 4u>& tetrahedron_t::nodes()\n{\n    return p_;\n}\n\npoint_t const& tetrahedron_t::p1() const\n{\n    return p_[0];\n}\n\npoint_t const& tetrahedron_t::p2() const\n{\n    return p_[1];\n}\n\npoint_t const& tetrahedron_t::p3() const\n{\n    return p_[2];\n}\n\npoint_t const& tetrahedron_t::p4() const\n{\n    return p_[3];\n}\n\npoint_t& tetrahedron_t::p1()\n{\n    return p_[0];\n}\n\npoint_t& tetrahedron_t::p2()\n{\n    return p_[1];\n}\n\npoint_t& tetrahedron_t::p3()\n{\n    return p_[2];\n}\n\npoint_t& tetrahedron_t::p4()\n{\n    return p_[3];\n}\n\naabb_t::aabb_t(point_t const& min, point_t const& max) : min(min), max(max) {}\n\nbool aabb_t::contains(point_t const& p) const\n{\n    return (p.x() >= min.x() && p.x() <= max.x()) && (p.y() >= min.y() && p.y() <= max.y()) &&\n           (p.z() >= min.z() && p.z() <= max.z());\n}\n\naabb_t aabb_t::from(tetrahedron_t const& t)\n{\n    constexpr double inf = std::numeric_limits<double>::infinity();\n    point_t min{inf, inf, inf}, max{-inf, -inf, -inf};\n    for (auto const& p : t.nodes())\n    {\n        if (p.x() > max.x())\n            max.x() = p.x();\n        if (p.y() > max.y())\n            max.y() = p.y();\n        if (p.z() > max.z())\n            max.z() = p.z();\n\n        if (p.x() < min.x())\n            min.x() = p.x();\n        if (p.y() < min.y())\n            min.y() = p.y();\n        if (p.z() < min.z())\n            min.z() = p.z();\n    }\n    return aabb_t{min, max};\n}\n\naabb_t aabb_t::from(triangle_t const& t)\n{\n    constexpr double inf = std::numeric_limits<double>::infinity();\n    point_t min{inf, inf, inf}, max{-inf, -inf, -inf};\n    for (auto const& p : t.nodes())\n    {\n        if (p.x() > max.x())\n            max.x() = p.x();\n        if (p.y() > max.y())\n            max.y() = p.y();\n        if (p.z() > max.z())\n            max.z() = p.z();\n\n        if (p.x() < min.x())\n            min.x() = p.x();\n        if (p.y() < min.y())\n            min.y() = p.y();\n        if (p.z() < min.z())\n            min.z() = p.z();\n    }\n    return aabb_t{min, max};\n}\n\nplane_t::plane_t(point_t const& p, normal_t const& n) : p(p), n(n) {}\n\nplane_t::plane_t(triangle_t const& t) : p(t.a()), n()\n{\n    n = (t.b() - t.a()).cross(t.c() - t.a()).normalized();\n}\n\ndouble plane_t::signed_distance(point_t const& q) const\n{\n    return (q - p).dot(n);\n}\n\n} // namespace common\n} // namespace sbs", "meta": {"hexsha": "3ce2dff9d93cd720eea6e98ac06fda09be775307", "size": 20010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/primitive.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/common/primitive.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/common/primitive.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": 28.3026874116, "max_line_length": 100, "alphanum_fraction": 0.563918041, "num_tokens": 5710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5714625647832727}}
{"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_HBEV_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HBEV_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\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 banded Hermitian matrix.\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * hbev() computes the eigenvalues and optionally the associated\n     * eigenvectors of a banded Hermitian matrix A. A matrix is Hermitian\n     * when herm( A ) == A. When A is real, a Hermitian matrix is also\n     * called symmetric.\n     *\n     * The eigen decomposition is A = U S * herm(U)  where  U  is a\n     * unitary matrix and S is a diagonal matrix. The eigenvalues of A\n     * are on the main diagonal of S. The eigenvalues are real.\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 ) - 2\n     *  workspace( work, rwork ) for complex matrices where work is a complex\n     *                           array with vector_size( work ) >= matrix_size1( a )\n     *                           and rwork is a real array with\n     *                           vector_size( rwork ) >= 3 * matrix_size1( a ) - 2.\n     */\n\n    /*\n     * If uplo=='L' only the lower triangular part is stored.\n     * If uplo=='U' only the upper triangular part is stored.\n     *\n     * The matrix is assumed to be stored in LAPACK band format, i.e.\n     * matrices are stored columnwise, in a compressed format so that when e.g. uplo=='U'\n     * the (i,j) element with j>=i is in position  (i-j) + j * (KD+1) + KD  where KD is the\n     * half bandwidth of the matrix. For a triadiagonal matrix, KD=1, for a diagonal matrix\n     * KD=0.\n     * When uplo=='L', the (i,j) element with j>=i is in position  (i-j) + j * (KD+1).\n     *\n     * The matrix A is thus a rectangular matrix with KD+1 rows and N columns.\n     */ \n\n    namespace detail {\n      inline \n      void hbev (char const jobz, char const uplo, int const n, int const kd,\n                 float* ab, int const ldab, float* w, float* z, int const ldz,\n                 float* work, int& info) \n      {\n\t      //for (int i=0; i<n*kd; ++i) std::cout << *(ab+i) << \" \" ;\n\t      //std::cout << \"\\n\" ;\n        LAPACK_SSBEV (&jobz, &uplo, &n, &kd, ab, &ldab, w, z, &ldz,\n                      work, &info);\n      }\n\n      inline \n      void hbev (char const jobz, char const uplo, int const n, int const kd,\n                 double* ab, int const ldab, double* w, double* z, int const ldz,\n                 double* work, int& info) \n      {\n        LAPACK_DSBEV (&jobz, &uplo, &n, &kd, ab, &ldab, w, z, &ldz,\n                      work, &info);\n      }\n\n      inline \n      void hbev (char const jobz, char const uplo, int const n, int const kd,\n                 traits::complex_f* ab, int const ldab, float* w,\n                 traits::complex_f* z, int const ldz,\n                 traits::complex_f* work, float* rwork, int& info) \n      {\n        LAPACK_CHBEV (&jobz, &uplo, &n, &kd, traits::complex_ptr(ab), &ldab,\n                      w, traits::complex_ptr(z), &ldz,\n                      traits::complex_ptr(work), rwork, &info);\n      }\n\n      inline \n      void hbev (char const jobz, char const uplo, int const n, int const kd,\n                 traits::complex_d* ab, int const ldab, double* w,\n                 traits::complex_d* z, int const ldz,\n                 traits::complex_d* work, double* rwork, int& info) \n      {\n        LAPACK_ZHBEV (&jobz, &uplo, &n, &kd, traits::complex_ptr(ab), &ldab,\n                      w, traits::complex_ptr(z), &ldz,\n                      traits::complex_ptr(work), rwork, &info);\n      }\n    } \n\n\n    namespace detail {\n       template <int N>\n       struct Hbev{};\n\n\n       /// Handling of workspace in the case of one workarray.\n       template <>\n       struct Hbev< 1 > {\n          template <typename T, typename R>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, minimal_workspace , int& info ) const {\n             traits::detail::array<T> work( 3*n-2 );\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work ),\n                   info );\n          }\n\n          template <typename T, typename R>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, optimal_workspace , int& info ) const {\n             traits::detail::array<T> work( 3*n-2 );\n\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work ),\n                   info );\n          }\n\n          template <typename T, typename R, typename W>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, detail::workspace1<W> work,\n                           int& info ) const {\n             assert( traits::vector_size( work.w_ ) >= 3*n-2 );\n\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work.w_ ),\n                   info );\n          }\n       }; // Hbev< 1 >\n\n\n       /// Handling of workspace in the case of two workarrays.\n       template <>\n       struct Hbev< 2 > {\n          template <typename T, typename R>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, minimal_workspace , int& info ) const {\n             traits::detail::array<T> work( n );\n             traits::detail::array<R> rwork( 3*n-2 );\n\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work ),\n                   traits::vector_storage( rwork ),\n                   info );\n          }\n\n          template <typename T, typename R>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, optimal_workspace , int& info ) const {\n             traits::detail::array<T> work( n );\n             traits::detail::array<R> rwork( 3*n-2 );\n\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work ),\n                   traits::vector_storage( rwork ),\n                   info );\n          }\n\n          template <typename T, typename R, typename W, typename RW>\n          void operator() (char const jobz, char const uplo, int const n,\n                           int const kd, T* ab, int const ldab, R* w, T* z,\n                           int const ldz, detail::workspace2<W,RW> work,\n                           int& info ) const {\n             assert( traits::vector_size( work.wr_ ) >= 3*n-2 );\n             assert( traits::vector_size( work.w_ ) >= n );\n\n             hbev( jobz, uplo, n, kd, ab, ldab, w, z, ldz,\n                   traits::vector_storage( work.w_ ),\n                   traits::vector_storage( work.wr_ ),\n                   info );\n          }\n       }; // Hbev< 2 >\n    \n\n\n       /// Compute eigendecomposition of the banded Hermitian matrix ab.\n       /// if jobz=='N' only the eigenvalues are computed.\n       /// if jobz=='V' compute the eigenvalues a and the eigenvectors.\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 )-2\n       ///  workspace( work, rwork ) for complex matrices where work is a complex\n       ///                           array with vector_size( work ) >= matrix_size1( a )\n       ///                           and rwork is a real array with\n       ///                           vector_size( rwork ) >= 3*matrix_size1( a )-2.\n       template <typename AB, typename Z, typename W, typename Work>\n       int hbev( char const jobz, AB& ab, W& w, Z& z, Work work ) {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<AB>::matrix_structure, \n           traits::hermitian_t\n         >::value)); \n#endif \n\n         typedef typename AB::value_type                            value_type ;\n\n         int const n = traits::matrix_size2 (ab);\n         assert (n == traits::matrix_size1 (z)); \n         assert (n == traits::vector_size (w));\n         assert ( jobz=='N' || jobz=='V' );\n\n         int info ; \n         detail::Hbev< n_workspace_args<value_type>::value >() (jobz,\n                       traits::matrix_uplo_tag( ab ), n,\n                       traits::matrix_upper_bandwidth(ab),\n                       traits::matrix_storage (ab), \n                       traits::leading_dimension (ab),\n                       traits::vector_storage (w),\n                       traits::matrix_storage (z),\n                       traits::leading_dimension (z),\n                       work, info);\n\t return info ;\n       } // hbev()\n       \n       } // namespace detail\n\n\n       /// Compute eigendecomposition without eigenvectors\n       template <typename AB, typename W, typename Work>\n       inline\n       int hbev (AB& ab, W& w, Work work) {\n          return detail::hbev( 'N', ab, w, ab, work );\n       } // hbev()\n\n\n       /// Compute eigendecomposition with eigenvectors\n       template <typename AB, typename W, typename Z, typename Work>\n       inline\n       int hbev (AB& ab, W& w, Z& z, Work work) {\n         BOOST_STATIC_ASSERT((boost::is_same<\n           typename traits::matrix_traits<Z>::matrix_structure, \n           traits::general_t\n         >::value)); \n         int const n = traits::matrix_size2 (ab);\n          assert (n == traits::matrix_size1 (z)); \n          assert (n == traits::matrix_size2 (z)); \n          return detail::hbev( 'V', ab, w, z, work );\n       } // hbev()\n\n  }\n\n}}}\n\n#endif \n", "meta": {"hexsha": "b4c1a84fcd0fe2676dfa98d2b4f4c5121cbb7aad", "size": 11620, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/hbev.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/hbev.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/hbev.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.0600706714, "max_line_length": 97, "alphanum_fraction": 0.5318416523, "num_tokens": 2934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.571462564313038}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <queue>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <vector>\n\nnamespace calculator {\nusing std::string;\nusing std::vector;\n\nstatic int _calc_expr_without_paretheses(const string& input) {\n  vector<string> parts;\n  boost::split(parts, input, [](char c) { return c == ' '; });\n  parts.erase(std::remove_if(parts.begin(), parts.end(),\n                             [](const string& part) { return part.empty(); }),\n              parts.end());\n  vector<string> phase1;\n  int i = 0;\n  while (i < parts.size()) {\n    const auto& op = parts[i];\n    if (op == \"*\" || op == \"/\") {\n      const auto& lhs = phase1.back();\n      const auto& rhs = parts[i + 1];\n      i += 2;\n      const int lval = atoi(lhs.c_str());\n      const int rval = atoi(rhs.c_str());\n      const int val = op == \"*\" ? lval * rval : lval / rval;\n      phase1.pop_back();\n      phase1.push_back(std::to_string(val));\n    } else {\n      phase1.push_back(op);\n      i += 1;\n    }\n  }\n  int result = atoi(phase1[0].c_str());\n  for (int i = 1; i < phase1.size() - 1; i++) {\n    auto& op = phase1[i];\n    int rhs = atoi(phase1[i + 1].c_str());\n    if (op == \"+\") {\n      result += rhs;\n    } else {\n      result -= rhs;\n    }\n  }\n  return result;\n}\n\nint calc(const string input) {\n  const string source(input);\n  const int N = source.size();\n  int pos = 0;\n  vector<string> exprs;\n  string expr;\n  for (char ch : source) {\n    if (ch == '(') {\n      exprs.push_back(expr);\n      expr.clear();\n    } else if (ch == ')') {\n      int result = _calc_expr_without_paretheses(expr);\n      expr = exprs.back();\n      exprs.pop_back();\n      expr += \" \" + std::to_string(result) + \" \";\n    } else {\n      expr += ch;\n    }\n  }\n  int result = _calc_expr_without_paretheses(expr);\n  return result;\n}\n\nstruct Token {\n  // // 字母 D 表示数值类型\n  char kind;\n  double value;\n  Token() : kind('D'), value(0) {}\n};\n\nstatic inline bool is_operator(char ch) {\n  return ch == '+' || ch == '-' || ch == '*' || ch == '/';\n}\n\nstatic vector<Token> tokenize(string input) {\n  std::stringstream cin(input);\n  vector<Token> tokens;\n  bool leading = true;\n  while (cin) {\n    Token token;\n    char ch = cin.peek();\n    if (isdigit(ch)) {\n      cin >> token.value;\n      leading = false;\n    } else if (leading && (ch == '+' || ch == '-')) {\n      cin >> token.value;\n      leading = false;\n    } else {\n      cin >> ch;\n      if (isspace(ch)) {  // skip\n        continue;\n      }\n      token.kind = ch;\n      leading = (ch == '(' || is_operator(ch));\n    }\n    tokens.push_back(token);\n  }\n  return tokens;\n}\n\nstatic inline int op_priority(char ch) {\n  switch (ch) {\n    case '*':\n    case '/':\n      return 30;\n    case '+':\n    case '-':\n      return 20;\n    default:\n      return 0;\n  }\n}\nstatic bool is_integer(double num) {\n  return isfinite(num) && floor(num) == num;\n}\n\nstatic string fmt_double(double d) {\n  if (is_integer(d)) {\n    long num = static_cast<long>(d);\n    return std::to_string(num);\n  } else {\n    string str = std::to_string(d);\n    str.erase(str.find_last_not_of('0') + 1, string::npos);\n    return str;\n  }\n}\n\nstring infix_to_postfix(string input) {\n  std::vector<string> output;\n  std::stack<char> operators;\n\n  vector<Token> tokens = tokenize(input);\n\n  for (Token& token : tokens) {\n    const char ch = token.kind;\n    if (is_operator(ch)) {\n      const int op_pri = op_priority(ch);\n      while (!operators.empty()) {\n        char prev_op = operators.top();\n        const int pre_op_pri = op_priority(prev_op);\n        if (pre_op_pri >= op_pri) {\n          output.push_back(string(1, prev_op));\n          operators.pop();\n        } else {\n          break;\n        }\n      }\n      operators.push(ch);\n    } else if (token.kind == 'D') {\n      output.push_back(fmt_double(token.value));\n    } else if (ch == '(') {\n      operators.push(ch);\n    } else if (ch == ')') {\n      char prev_op = operators.top();\n      while (prev_op != '(') {\n        output.push_back(string(1, prev_op));\n        operators.pop();\n        prev_op = operators.top();\n      }\n      operators.pop();\n    } else {\n      // skip\n    }\n  }\n\n  while (!operators.empty()) {\n    char ch = operators.top();\n    output.push_back(string(1, ch));\n    operators.pop();\n  }\n\n  return boost::join(output, \" \");\n}\n\ndouble calc_v2(string input) {\n  return 0;\n}\n}  // namespace calculator", "meta": {"hexsha": "fc5c5c44832789097105afb7321f2b4e9f45bebc", "size": 4398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calculator/Calculator.hpp", "max_stars_repo_name": "codetalks-new/learn-cpp", "max_stars_repo_head_hexsha": "ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-29T15:12:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-29T15:12:14.000Z", "max_issues_repo_path": "calculator/Calculator.hpp", "max_issues_repo_name": "codetalks-new/learn-cpp", "max_issues_repo_head_hexsha": "ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calculator/Calculator.hpp", "max_forks_repo_name": "codetalks-new/learn-cpp", "max_forks_repo_head_hexsha": "ec91c2cfba70c4c5aad52898f97e5bd2d35d9d8b", "max_forks_repo_licenses": ["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.2698412698, "max_line_length": 78, "alphanum_fraction": 0.548431105, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5714625489822721}}
{"text": "#ifndef __DIRICHLET_H__\n#define __DIRICHLET_H__\n\n#include <armadillo>\n\n#include <cmath>\n#include <numeric>\n#include <vector>\n\n#include <besiq/config.h>\n#ifndef HAVE_TR1_RANDOM\n#include <random>\ntypedef std::mt19937 prg_type;\n#else\n#include <tr1/random>\ntypedef std::tr1::mt19937 prg_type;\n#endif\n\n/**\n * Computes the dirichlet multinomial probability of a vector\n * x with prior parameter alpha.\n * \n * @param x The observations.\n * @param alpha The prior parameters of the dirichlet density.\n *\n * @return The posterior probability of x.\n */\ndouble dirmult(const arma::vec &x, const arma::vec &alpha);\n\n/**\n * Computes the dirichlet multinomial log probability of a vector\n * x with prior parameter alpha.\n * \n * @param x The observations.\n * @param alpha The prior parameters of the dirichlet density.\n *\n * @return The log posterior probability of x.\n */\ndouble ldirmult(const arma::vec &x, const arma::vec &alpha);\n\n/**\n * Computes the log of the binomial coefficient (n choose k).\n *\n * @param n Number of elements to draw from.\n * @param k Number of elements to draw.\n *\n * @return The log of the binomial coefficient.\n */\ndouble lbinomial(double n, double k);\n\n/**\n * This class is responsible for generating samples from a\n * dirichlet distribution. It does so by using the fact that\n * gamma(a_i, b) / sum_i gamma( a_i, b ) is dirichlet distributed\n * with parameter a_i.\n */\nclass dir_generator\n{\npublic:\n    /**\n     * Constructor.\n     *\n     * Initializes the random generator with the given seed.\n     *\n     * @param seed The seed given to the random generator.\n     */\n    dir_generator(unsigned long seed);\n\n    /**\n     * Generates a random sample from the dirichlet distribution\n     * with the given parameters.\n     *\n     * @param x The parameters of the dirichlet density.\n     *\n     * @return A sample from the dirichlet density.\n     */\n    arma::vec sample(const arma::vec &alpha);\n\nprivate:\n    /**\n     * Mersenne twister random generator.\n     */\n    prg_type m_generator;\n};\n\n#endif /* End of __DIRICHLET_H__ */\n", "meta": {"hexsha": "15c707b1ce0d742e26157a48816b02e472a2e83f", "size": 2043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/besiq/stats/dirichlet.hpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "libs/besiq/stats/dirichlet.hpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "libs/besiq/stats/dirichlet.hpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 23.4827586207, "max_line_length": 65, "alphanum_fraction": 0.6901615272, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5713921818381429}}
{"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 * factor_graph_solve.cpp\n *\n *  Created on: Mar 23, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n\n#include \"mrob/factor_graph_solve.hpp\"\n//#include \"mrob/CustomCholesky.hpp\"\n\n#include <iostream>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseQR>\n\nusing namespace mrob;\nusing namespace std;\nusing namespace Eigen;\n\n\nFGraphSolve::FGraphSolve(matrixMethod method, optimMethod optim):\n\tFGraph(), matrixMethod_(method), optimMethod_(optim), N_(0), M_(0),\n\tlambda_(1e-6), solutionTolerance_(1e-2)\n{\n\n}\n\nFGraphSolve::~FGraphSolve() = default;\n\n\nvoid FGraphSolve::solve(optimMethod method, uint_t maxIters)\n{\n    /**\n     * 2800 2D nodes on M3500\n     * Time profile :13.902 % build Adjacency matrix,\n     *               34.344 % build Information,\n     *               48.0506 % build Cholesky,\n     *               2.3075 % solve forward and back substitution,\n     *               1.3959 % update values,\n     *\n     */\n    optimMethod_ = method; // updates the optimization method\n    time_profiles_.reset();\n\n    // Optimization\n    switch(optimMethod_)\n    {\n      case GN:\n        this->optimize_gauss_newton();// false => lambda = 0\n        this->update_nodes();\n        break;\n      case LM:\n        this->optimize_levenberg_marquardt(maxIters);\n        break;\n      default:\n        assert(0 && \"FGraphSolve:: optimization method unknown\");\n    }\n\n\n\n\n    if (0)\n        time_profiles_.print();\n}\n\nvoid FGraphSolve::build_problem(bool useLambda)\n{\n\n    // 1) Adjacency matrix A, it has to\n    //    linearize and calculate the Jacobians and required matrices\n    time_profiles_.start();\n    this->build_adjacency();\n    time_profiles_.stop(\"Adjacency\");\n\n    // 1.2) builds specifically the information\n    switch(matrixMethod_)\n    {\n      case ADJ:\n        time_profiles_.start();\n        this->build_info_adjacency();\n        time_profiles_.stop(\"Info Adjacency\");\n        break;\n      case SCHUR:\n      default:\n        assert(0 && \"FGraphSolve: method not implemented\");\n    }\n\n    // Structure for LM and dampening GN-based methods\n    if (useLambda)\n    {\n        diagL_ = L_.diagonal();\n    }\n}\n\nvoid FGraphSolve::optimize_gauss_newton(bool useLambda)\n{\n    // requires a Column-storage matrix\n    SimplicialLDLT<SMatCol,Lower, AMDOrdering<SMatCol::StorageIndex>> cholesky;\n\n    this->build_problem(useLambda);\n\n    // compute cholesky solution\n    time_profiles_.start();\n    if (useLambda)\n    {\n        for (uint_t n = 0 ; n < N_; ++n)\n            L_.coeffRef(n,n) = lambda_ + diagL_(n);//Circunference =>  diagL_(n) + lambda_\n            //L_.coeffRef(n,n) = (1.0 + lambda_)*diagL_(n);//Elipsoid, for circunference =>  diagL_(n) + lambda.\n    }\n    cholesky.compute(L_);\n    time_profiles_.stop(\"Gauss Newton create Cholesky\");\n    time_profiles_.start();\n    dx_ = cholesky.solve(b_);\n    time_profiles_.stop(\"Gauss Newton solve Cholesky\");\n\n}\n\nuint_t FGraphSolve::optimize_levenberg_marquardt(uint_t maxIters)\n{\n    //SimplicialLDLT<SMatCol,Lower, AMDOrdering<SMatCol::StorageIndex>> cholesky;\n\n\n    // LM trust region as described in Bertsekas (p.105)\n\n    // 0) parameter initialization\n    lambda_ = 1e-5;\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    //matData_t lambdaMax, lambdaMin; // XXX lower bound unnecessary\n\n    matData_t currentChi2, deltaChi2, modelFidelity;\n    uint_t iter = 0;\n\n    do{\n        iter++;\n        // 1) solve subproblem and current error\n        this->optimize_gauss_newton(true);// Test if solved anything? no nans\n        currentChi2 = this->chi2(false);// TODO residuals don't need to be calculated again (see optimizer.cpp)\n        this->synchronize_nodes_auxiliary_state();// book-keeps states to undo updates\n        this->update_nodes();\n\n\n        // 1.2) Check for convergence, needs update and re-evaluaiton of errors\n        deltaChi2 = currentChi2 - this->chi2(true);\n        std::cout << \"\\nFGraphSolve::optimize_levenberg_marquardt: iteration \"\n                  << iter << \" lambda = \" << lambda_ << \", error \" << currentChi2\n                  << \", and delta = \" << deltaChi2\n                  << std::endl;\n        if (deltaChi2 < 0)\n        {\n            // proposed dx did not improve, repeat 1) and reduce area of optimization = increase lambda\n            lambda_ *= beta1;\n            this->synchronize_nodes_state();\n            continue;\n        }\n\n        // 1.3) check for convergence\n        if (deltaChi2 < solutionTolerance_)\n            return iter;\n\n\n        // 2) Fidelity of the quadratized model vs non-linear chi2 evaluation.\n        // f = chi2(x_k) - chi2(x_k + dx)\n        //     chi2(x_k) - m_k(dx)\n        // where m_k is the quadratized model = ||r||^2 - dx'*J' r + 0.5 dx'(J'J + lambda*D2)dx\n        modelFidelity = deltaChi2 / (dx_.dot(b_) - 0.5*dx_.dot(L_* dx_));\n        std::cout << \"model fidelity = \" << modelFidelity << \" and m_k = \" << dx_.dot(b_) << std::endl;\n\n        //3) update lambda\n        if (modelFidelity < sigma1)\n            lambda_ *= beta1;\n        if (modelFidelity > sigma2)\n            lambda_ *= beta2;\n\n\n    } while (iter < maxIters);\n\n    // output\n    std::cout << \"FGraphSolve::optimize_levenberg_marquardt: failed to converge after \"\n              << iter << \" iterations and error \" << currentChi2\n              << \", and delta = \" << deltaChi2\n              << std::endl;\n    return 0; //\n\n}\n\nvoid FGraphSolve::build_adjacency()\n{\n    // 0) resize properly matrices (if needed)\n    r_.resize(obsDim_,1);//dense vector TODO is it better to reserve and push_back??\n    A_.resize(obsDim_, stateDim_);//Sparse matrix clear data\n    W_.resize(obsDim_, obsDim_);//TODO should we reinitialize this all the time? an incremental should be fairly easy\n\n    // 1) create the vector's structures\n    std::deque<std::shared_ptr<Factor> >* factors;\n    std::deque<std::shared_ptr<Node> >* nodes;\n    // TODO: optimizing subgraph is not an option now, but we maintain generality\n    factors = &factors_;\n    nodes = &nodes_;\n\n    // 2) vector structure to bookkeep the starting Nodes indices inside A\n\n    // 2.2) Node indexes bookeept\n    std::vector<uint_t> indNodesMatrix;\n    indNodesMatrix.reserve(nodes->size());\n\n    N_ = 0;\n    for (id_t i = 0; i < nodes->size(); ++i)\n    {\n        // calculate the indices to access\n        uint_t dim = (*nodes)[i]->get_dim();\n        indNodesMatrix.push_back(N_);\n        N_ += dim;\n\n    }\n    assert(N_ == stateDim_ && \"FGraphSolve::buildAdjacency: State Dimensions are not coincident\\n\");\n\n    // 3) Evaluate every factor given the current state and bookeeping of Factor indices\n    std::vector<uint_t> reservationA;\n    reservationA.reserve( obsDim_ );\n    std::vector<uint_t> reservationW;\n    reservationW.reserve( obsDim_ );\n    std::vector<uint_t> indFactorsMatrix;\n    indFactorsMatrix.reserve(factors->size());\n    M_ = 0;\n    for (uint_t i = 0; i < factors->size(); ++i)\n    {\n        auto f = (*factors)[i];\n        f->evaluate_residuals();\n        f->evaluate_jacobians();\n        f->evaluate_chi2();\n\n        // calculate dimensions for reservation and bookeping vector\n        uint_t dim = f->get_dim();\n        uint_t allDim = f->get_all_nodes_dim();\n        for (uint_t j = 0; j < dim; ++j)\n        {\n            reservationA.push_back(allDim);\n            reservationW.push_back(dim-j);\n        }\n        indFactorsMatrix.push_back(M_);\n        M_ += dim;\n    }\n    assert(M_ == obsDim_ && \"FGraphSolve::buildAdjacency: Observation dimensions are not coincident\\n\");\n    A_.reserve(reservationA); //Exact allocation for elements.\n    W_.reserve(reservationW); //same\n\n\n    // XXX This could be subject to parallelization, maybe on two steps: eval + build\n    for (uint_t i = 0; i < factors->size(); ++i)\n    {\n        auto f = (*factors)[i];\n\n        // 4) Get the calculated residual\n        r_.block(indFactorsMatrix[i], 0, f->get_dim(), 1) <<  f->get_residual();\n\n        // 5) build Adjacency matrix as a composition of rows\n        // 5.1) Get the number of nodes involved. It is a vector of nodes\n        auto neighNodes = f->get_neighbour_nodes();\n        // Iterates over the Jacobian row\n        for (uint_t l=0; l < f->get_dim() ; ++l)\n        {\n            uint_t totalK = 0;\n            // Iterates over the number of neighbour Nodes (ordered by construction)\n            for (uint_t j=0; j < neighNodes->size(); ++j)\n            {\n                uint_t indNode = (*neighNodes)[j]->get_id();\n                uint_t dimNode = (*neighNodes)[j]->get_dim();\n                for(uint_t k = 0; k < dimNode; ++k)\n                {\n                    // order according to the permutation vector\n                    uint_t iRow = indFactorsMatrix[i] + l;\n                    uint_t iCol = indNodesMatrix[indNode] + k;\n                    // This is an ordered insertion\n                    A_.insert(iRow,iCol) = f->get_jacobian()(l, k + totalK);\n                }\n                totalK += dimNode;\n            }\n        }\n\n\n        // 5) Get information matrix for every factor\n        for (uint_t l = 0; l < f->get_dim(); ++l)\n        {\n            // only iterates over the upper triangular part\n            for (uint_t k = l; k < f->get_dim(); ++k)\n            {\n                uint_t iRow = indFactorsMatrix[i] + l;\n                uint_t iCol = indFactorsMatrix[i] + k;\n                W_.insert(iRow,iCol) = f->get_information_matrix()(l,k);\n                // If QR, then we need the following, but we dont suppoort QR anyway\n                //W_.insert(iRow,iCol) = f->get_trans_sqrt_information_matrix()(l,k);\n            }\n        }\n    } //end factors loop\n\n\n}\n\nvoid FGraphSolve::build_info_adjacency()\n{\n    /**\n     * L_ dx = b_ corresponds to the normal equation A'*W*A dx = A'*W*r\n     * only store the lower part of the information matrix (symmetric)\n     *\n     * XXX: In terms of speed, using the selfadjointview does not improve,\n     * Eigen stores a temporary object and then copy only the upper part.\n     *\n     */\n    L_ = (A_.transpose() * W_.selfadjointView<Eigen::Upper>() * A_);\n    b_ = A_.transpose() * W_.selfadjointView<Eigen::Upper>() * r_;\n}\n\nmatData_t FGraphSolve::chi2(bool evaluateResidualsFlag)\n{\n    matData_t totalChi2 = 0.0;\n    for (uint_t i = 0; i < factors_.size(); ++i)\n    {\n        auto f = factors_[i];\n        if (evaluateResidualsFlag)\n        {\n            f->evaluate_residuals();\n            f->evaluate_chi2();\n        }\n        totalChi2 += f->get_chi2();\n    }\n    return totalChi2;\n}\n\nvoid FGraphSolve::update_nodes()\n{\n    int acc_start = 0;\n    for (uint_t i = 0; i < nodes_.size(); i++)\n    {\n        // node update is the negative of dx just calculated.\n        // x = x - alpha * H^(-1) * Grad = x - dx\n        // Depending on the optimization, it is already taking care of the step alpha, so we assume alpha = 1\n        auto node_update = -dx_.block(acc_start, 0, nodes_[i]->get_dim(), 1);\n        nodes_[i]->update(node_update);\n\n        acc_start += nodes_[i]->get_dim();\n    }\n}\n\nvoid FGraphSolve::synchronize_nodes_auxiliary_state()\n{\n    for (auto n : nodes_)\n        n->set_auxiliary_state(n->get_state());\n}\n\n\nvoid FGraphSolve::synchronize_nodes_state()\n{\n    for (auto n : nodes_)\n        n->set_state(n->get_auxiliary_state());\n}\n\n// method to output (to python) or other programs the current state of the system.\nstd::vector<MatX> FGraphSolve::get_estimated_state()\n{\n    vector<MatX> results;\n    results.reserve(nodes_.size());\n\n    for (uint_t i = 0; i < nodes_.size(); i++)\n    {\n        //nodes_[i]->print();\n        MatX updated_pos = nodes_[i]->get_state();\n        results.emplace_back(updated_pos);\n    }\n\n    return results;\n}\n\nMatX1 FGraphSolve::get_chi2_array()\n{\n    MatX1 results(factors_.size());\n\n    for (uint_t i = 0; i < factors_.size(); ++i)\n    {\n        auto f = factors_[i];\n        results(i) = f->get_chi2();\n    }\n\n    return results;\n}\n", "meta": {"hexsha": "4f45a4069c0034d7bc5ba6f29b377a30fdd0dd16", "size": 12807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FGraph/factor_graph_solve.cpp", "max_stars_repo_name": "nosmokingsurfer/mrob", "max_stars_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/FGraph/factor_graph_solve.cpp", "max_issues_repo_name": "nosmokingsurfer/mrob", "max_issues_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FGraph/factor_graph_solve.cpp", "max_forks_repo_name": "nosmokingsurfer/mrob", "max_forks_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_forks_repo_licenses": ["Apache-2.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.6222222222, "max_line_length": 117, "alphanum_fraction": 0.6056843913, "num_tokens": 3427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.571392176547386}}
{"text": "#include \"quadric_error_metric.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n\nnamespace {\n\tconst double eps = 1e-7;\n\tconst double uv_weight = 1e6;\n}\nvoid quadric_error_metric(\n\tconst Eigen::MatrixXd& V, \n\tconst Eigen::MatrixXi& F, \n\tstd::vector< Eigen::MatrixXd >& Q)\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\t\n\t// array of 4x4 matrices\n\tQ.resize( V.rows() );\n\tfor( int i=0; i<Q.size(); i++ )\n\t\tQ[i] = Matrix4d::Zero();\n\t\n\tconst auto & face_from_three_points = [](const Vector3d& v1, const Vector3d& v2, const Vector3d& v3)\n\t{\n\t\tVector3d n = (v2-v1).cross(v3-v1);\n\t\tn.normalize();\n\t\tdouble d = -n.dot(v1);\n\t\t\n\t\tVector4d res;\n\t\tres << n(0), n(1), n(2), d;\n\t\t\n\t\treturn res;\n\t};\n\t\n\t// the metric at each vertex equals to the sum of metric of its attached faces\n\tfor( int i=0; i<F.rows(); i++ ) {\n\t\tVector3d v1 = V.row( F(i,0) );\n\t\tVector3d v2 = V.row( F(i,1) );\n\t\tVector3d v3 = V.row( F(i,2) );\n\t\tVector4d p = face_from_three_points(v1, v2, v3);\n\t\tMatrix4d metric = p*p.transpose();\n\t\t\n\t\tQ[ F(i,0) ] += metric;\n\t\tQ[ F(i,1) ] += metric;\n\t\tQ[ F(i,2) ] += metric;\n\t}\n\t\n\t// the cost v.T*Q*v should equal to zero\n\tfor( int i=0; i<V.rows(); i++ ) {\n\t\t// cout << fabs(v * Q[i] * v.transpose()) << endl;\n\t\tassert( fabs(V.row(i).homogeneous() * Q[i] * V.row(i).homogeneous().transpose()) <= eps );\n\t}\n}\n\nvoid qslim_5d(\n\tconst Eigen::MatrixXd& V, \n\tconst Eigen::MatrixXi& F,\n\tconst Eigen::MatrixXd& TC, \n\tconst Eigen::MatrixXi& FT, \n\tstd::vector< Eigen::MatrixXd >& Q)\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\t\n\tassert( F.rows() == FT.rows() );\n\tconst int nF = F.rows();\n\t// array of 6x6 matrices\n\tQ.resize( V.rows() );\n\tfor( int i=0; i<Q.size(); i++ ) {\n\t\tMatrixXd metric(6,6);\n\t\tmetric.setZero();\n\t\tQ[i] = metric;\n\t}\n\t\n\tfor(int i=0; i<nF; i++) {\n\t\tVectorXd p1(5),p2(5),p3(5);\n\t\tp1.head(3) = V.row( F(i,0) );\n\t\tp2.head(3) = V.row( F(i,1) );\n\t\tp3.head(3) = V.row( F(i,2) );\n\t\tp1.tail(2) = TC.row( FT(i,0) );\n\t\tp2.tail(2) = TC.row( FT(i,1) );\n\t\tp3.tail(2) = TC.row( FT(i,2) );\n\t\t// Paper Section 5.1\n\t\tVectorXd e1 = (p2-p1)/(p2-p1).norm();\n\t\tVectorXd e2 = p3-p1-(e1.dot(p3-p1))*e1;\n\t\te2 /= e2.norm();\n\t\tconst double eps = 1e-7;\n\t\tassert( fabs(e1.norm() - 1) <= eps );\n\t\tassert( fabs(e2.norm() - 1) <= eps );\n\t\t\n\t\tMatrixXd A(5,5);\n\t\tA.setIdentity();\n\t\tA = A - e1*e1.transpose() - e2*e2.transpose();\n\t\tVectorXd b = p1.dot(e1)*e1 + p1.dot(e2)*e2 - p1;\n\t\tdouble c = p1.dot(p1) - p1.dot(e1)*p1.dot(e1) - p1.dot(e2)*p1.dot(e2);\n\t\t\n\t\t// Paper Section 3.4\n\t\tMatrixXd metric(6,6);\n\t\tmetric.block(0,0,5,5) = A;\n\t\tmetric.block(0,5,5,1) = b;\n\t\tmetric.block(5,0,1,5) = b.transpose();\n\t\tmetric(5,5) = c;\n\t\t\n\t\t// add metric to each vertex\n\t\tQ[ F(i,0) ] += metric;\n\t\tQ[ F(i,1) ] += metric;\n\t\tQ[ F(i,2) ] += metric;\n\t}\n}\n\t\nvoid half_edge_qslim_5d(\n\tconst Eigen::MatrixXd& V, \n\tconst Eigen::MatrixXi& F,\n\tconst Eigen::MatrixXd& TC, \n\tconst Eigen::MatrixXi& FT, \n\tMapV5d & hash_Q)\n{\n\tusing namespace std;\n\tusing namespace Eigen;\n\t\n\t// initialize 5d vertex map, key is (vi,ti), value is zero metric\n\tassert( F.rows() == FT.rows() );\n\tconst int nF = F.rows();\n\tfor(int i=0; i<nF; i++) {\n\t\n\t\t/// A. compute metric for each face\n\t\tVectorXd p1(5),p2(5),p3(5);\n\t\tp1.head(3) = V.row( F(i,0) );\n\t\tp2.head(3) = V.row( F(i,1) );\n\t\tp3.head(3) = V.row( F(i,2) );\n\t\tp1.tail(2) = TC.row( FT(i,0) );\n\t\tp2.tail(2) = TC.row( FT(i,1) );\n\t\tp3.tail(2) = TC.row( FT(i,2) );\n\t\t// Paper Section 5.1\n\t\tVectorXd e1 = (p2-p1)/(p2-p1).norm();\n\t\tVectorXd e2 = p3-p1-(e1.dot(p3-p1))*e1;\n\t\te2 /= e2.norm();\n\t\tconst double eps = 1e-7;\n\t\tassert( fabs(e1.norm() - 1) <= eps );\n\t\tassert( fabs(e2.norm() - 1) <= eps );\n\t\t\n\t\tMatrixXd A(5,5);\n\t\tA.setIdentity();\n\t\tA = A - e1*e1.transpose() - e2*e2.transpose();\n\t\tVectorXd b = p1.dot(e1)*e1 + p1.dot(e2)*e2 - p1;\n\t\tdouble c = p1.dot(p1) - p1.dot(e1)*p1.dot(e1) - p1.dot(e2)*p1.dot(e2);\n\t\t\n\t\t// Paper Section 3.4\n\t\tMatrixXd metric(6,6);\n\t\tmetric.block(0,0,5,5) = A;\n\t\tmetric.block(0,5,5,1) = b;\n\t\tmetric.block(5,0,1,5) = b.transpose();\n\t\tmetric(5,5) = c;\t\n\t\n\t\t/// B. assign the face metric to each 5d vertex, if it hasn't appeared, initialize\n\t\t/// it with the metric, otherwise, add the metric to its original metric. \n\t\tfor(int j=0; j<3; j++) {\n\t\t\tint vi = F(i,j);\n\t\t\tint ti = FT(i,j);\n\t\t\tif( hash_Q[vi].count(ti) == 0 ) {\n\t\t\t\thash_Q[vi][ti] = metric;\n\t\t\t} \n\t\t\telse {\n\t\t\t\thash_Q[vi][ti] += metric;\n\t\t\t}\n\t\t}\n\t}\n\t\n}\t\n", "meta": {"hexsha": "d9b551b1cd1328e1e91a0ea3f07f90351b577b7e", "size": 4313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quadric_error_metric.cpp", "max_stars_repo_name": "unclearness/SeamAwareDecimater", "max_stars_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 380.0, "max_stars_repo_stars_event_min_datetime": "2017-09-18T02:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:04:03.000Z", "max_issues_repo_path": "quadric_error_metric.cpp", "max_issues_repo_name": "unclearness/SeamAwareDecimater", "max_issues_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2017-09-17T03:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T17:13:06.000Z", "max_forks_repo_path": "quadric_error_metric.cpp", "max_forks_repo_name": "unclearness/SeamAwareDecimater", "max_forks_repo_head_hexsha": "c69934356ecdb0dd91070a6fc0520cdb0cc4d983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2017-09-18T02:07:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T02:34:33.000Z", "avg_line_length": 25.5207100592, "max_line_length": 101, "alphanum_fraction": 0.5740783677, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5713921707214475}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <math.h>\n#include <vector>\n#include \"hybrid_astar.h\"\n#include <boost/heap/binomial_heap.hpp>\n\nusing namespace std;\n\n\n/**\n * Initializes HAS\n */\nHAS::HAS() {\n\n}\n\nHAS::~HAS() {}\n\n\n//heap optimization method\nstruct Compare_cost {\n\n  bool operator()(const HAS::Node3D & lhs, const HAS::Node3D & rhs) const {\n    return lhs.f > rhs.f;\n  }\n\n};\ntypedef boost::heap::binomial_heap< HAS::Node3D,\n                                    boost::heap::compare<Compare_cost>> SortedQueue;\n\ndouble HAS::heuristic(double x, double y,\n                      vector<int> goal,\n                      string heuristic_method){\n\n      double dx  = fabs(y - goal[0]);\n      double dy  = fabs(x - goal[1]);\n      double tie = (1.0 + 1.0/10);\n\n      //http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#speed-or-accuracy\n      if (heuristic_method == \"Manhattan\")       return dx + dy;\n      if (heuristic_method == \"Chebyshev\")       return (dx + dy) -  min(dx, dy);\n      if (heuristic_method == \"Octile\")          return 2*(dx + dy) - (3-2*2)*min(dx, dy);\n      if (heuristic_method == \"Euclidean\")       return sqrt(dx * dx + dy * dy);\n      if (heuristic_method == \"Octile_breaktie\") return tie*(2*(dx + dy) - (3-2*2)*min(dx, dy));\n      //\n\n}\n\n\n/* HAS::theta_to_stack_number(double theta)\nTakes an angle (in radians) and returns which \"stack\" in the 3D configuration space\nthis angle corresponds to. Angles near 0 go in the lower stacks while angles near\n2 * pi go in the higher stacks.\n*/\nint HAS::theta_to_stack_number(double theta){\n\n  double new_theta = fmod((theta + 2 * M_PI),(2 * M_PI));\n  int stack_number = (int)(round(new_theta * NUM_THETA_CELLS / (2*M_PI))) % NUM_THETA_CELLS;\n  return stack_number;\n}\n\n/*\nReturns the index into the grid for continuous position. So if x is 3.621, then this\nwould return 3 to indicate that 3.621 corresponds to array index 3.\n*/\nint HAS::idx(double float_num) {\n\n  return int(floor(float_num));\n}\n\ndouble HAS::turning_cost(double next_turn_angle,\n                         double max_turnable,\n                         double turning_weight){\n\n    return turning_weight * fabs(next_turn_angle)/max_turnable;\n\n}\n\nvector<HAS::Node3D> HAS::expand(HAS::Node3D state,\n                                vector<int> goal,\n                                string heuristic_method) {\n\n  int    g     = state.g;\n  double x     = state.x;\n  double y     = state.y;\n  double theta = state.theta;\n\n  int g2 = g + 1 ;\n  vector<HAS::Node3D> next_states;\n\n  for(double delta_i = -max_turnable;\n             delta_i < (max_turnable + turning_res);\n             delta_i += turning_res) {\n\n    // Update next state\n    double delta  = M_PI / 180.0 * delta_i;\n    double omega  = SPEED / LENGTH * tan(delta);\n\n    double theta2 = theta + omega;\n    theta2        = fmod(theta2, 2*M_PI);\n    if(theta2 < 0) { theta2 += 2*M_PI;}\n\n    double x2 = x + SPEED * cos(theta);\n    double y2 = y + SPEED * sin(theta);\n\n\n    // Update next state cost\n    int f2    = g2\n                + turning_cost(delta_i, max_turnable, 1)\n                + heuristic(x2, y2, goal, heuristic_method);\n\n    // Create a new State object with all of the \"next\" values.\n    HAS::Node3D state2 {g2, f2, x2, y2, theta2,};\n    next_states.emplace_back(state2);\n\n  }\n  return next_states;\n  \n}\n\nHAS::grid_path HAS::search_heap(vector<vector<int>> grid,\n                                vector<double> start,\n                                vector<int> goal,\n                                string heuristic_method) {\n\n  vector<vector<vector<int> > >    closed(NUM_THETA_CELLS,\n                                          vector<vector<int>>(grid[0].size(), vector<int>(grid.size())));\n  vector<vector<vector<Node3D> > > came_from(NUM_THETA_CELLS,\n                                             vector<vector<Node3D>>(grid[0].size(), vector<Node3D>(grid.size())));\n  double theta = start[2];\n  int stack    = theta_to_stack_number(theta);\n  int g        = 0;\n  int f        = g + heuristic(start[0], start[1], goal, heuristic_method);\n\n  // Create new state object to start the search with.\n  Node3D state {g, f, start[0], start[1], theta};\n\n  closed[stack][idx(state.x)][idx(state.y)]    = 1;\n  came_from[stack][idx(state.x)][idx(state.y)] = state;\n\n  int total_closed = 1;\n\n  // Heap Method\n  SortedQueue opened_heap;\n  opened_heap.push(state);\n\n  bool finished = false;\n\n  while(!opened_heap.empty()) {\n\n    // Heap Method\n    Node3D current = opened_heap.top();// get smallest value\n    opened_heap.pop();// delete\n\n    int x = current.x;\n    int y = current.y;\n\n    // Check if reach the goal\n    if(idx(x) == goal[0] && idx(y) == goal[1]){\n      cout << \" found path to goal in \" << total_closed << \" expansions\" << endl;\n      grid_path path {closed, came_from, current,};\n\n      return path;\n    }\n\n    // Otherwise, expand the current state to get\n    // a list of possible next states.\n    vector<Node3D> next_state = expand(current, goal, heuristic_method);\n\n    for(int i = 0; i < next_state.size(); i++) {\n      int g2        = next_state[i].g;\n      double x2     = next_state[i].x;\n      double y2     = next_state[i].y;\n      double theta2 = next_state[i].theta;\n\n\n      // If we have expanded outside the grid, skip this next_state.\n      if((x2 < 0 || x2 >= grid.size()) || (y2 < 0 || y2 >= grid[0].size())) {\n        //invalid cell\n        continue;\n      }\n\n      int stack2 = theta_to_stack_number(theta2);\n\n      //Otherwise, check that we haven't already visited this cell and\n      //that there is not an obstacle in the grid there.\n      if(closed[stack2][idx(x2)][idx(y2)] == 0 && grid[idx(x2)][idx(y2)] == 0) {\n\n        // The state can be added to the opened stack.\n        opened_heap.push(next_state[i]);\n\n        //The stack_number, idx(next_state.x), idx(next_state.y) tuple\n        //has now been visited, so it can be closed.\n        closed[stack2][idx(x2)][idx(y2)] = 1;\n\n        //The next_state came from the current state, and that is recorded.\n        came_from[stack2][idx(x2)][idx(y2)] = current;\n\n        total_closed += 1;\n      }\n\n\n    }\n\n  }\n  cout << \"no valid path.\" << endl;\n  HAS::grid_path path {closed, came_from, state,};\n\n  return path;\n\n}\n\nvector<HAS::Node3D> HAS::retrace_path(vector< vector< vector<HAS::Node3D> > > came_from,\n                                      vector<double> start,\n                                      HAS::Node3D final){\n\n\tvector<Node3D> path = {final};\n\tNode3D current = came_from[theta_to_stack_number(final.theta)]\n                            [idx(final.x)][idx(final.y)];\n\n  while( current.x !=  start[0] || current.y != start[1] || current.theta != start[2]){\n    // add each node from final node\n\t\tpath.emplace_back(current);\n    current = came_from[theta_to_stack_number(current.theta)]\n                       [idx(current.x)][idx(current.y)];\n\t}\n  path.emplace_back(current); //add start node\n  //reverse path from start\n  std::reverse(path.begin(),path.end());\n\n\treturn path;\n\n}\n\n\nvector<HAS::Node3D> HAS::smooth_path(vector<Node3D> path,\n                                     double weight, double smooth, double tolerance){\n\n  vector<Node3D> newpath;\n  // make a copy of old path into newpath\n  newpath = path;\n\n  double change = tolerance;\n  while (change >= tolerance){\n\n    change = 0.0;\n    for (auto node = path.begin()+1; node != path.end()-1; ++node){\n      auto index = std::distance(path.begin(), node);\n\n      double aux = newpath[index].x;\n      newpath[index].x = newpath[index].x\n                         + weight * (path[index].x - newpath[index].x);\n      newpath[index].x = newpath[index].x\n                         + smooth * (newpath[index-1].x + newpath[index+1].x\n                                     - 2.0* newpath[index].x);\n      change += abs(aux - newpath[index].x);\n\n      aux = newpath[index].y;\n      newpath[index].y = newpath[index].y\n                         + weight * (path[index].y - newpath[index].y);\n      newpath[index].y = newpath[index].y\n                         + smooth * (newpath[index-1].y + newpath[index+1].y\n                                     - 2.0* newpath[index].y);\n      change += abs(aux - newpath[index].y);\n\n    }\n  }\n\n  return newpath;\n\n}\n", "meta": {"hexsha": "3e5f69fefe3c76fec704b950b049c4cf3e66fb0e", "size": 8250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hastar_navi/src/hybrid_astar.cpp", "max_stars_repo_name": "LUUTHIENXUAN/Udacity-CarND-Hybird-A-", "max_stars_repo_head_hexsha": "f453d9d41a3ccf024cbd1d6e154b9a2a23cb22b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-15T00:40:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T11:53:21.000Z", "max_issues_repo_path": "hastar_navi/src/hybrid_astar.cpp", "max_issues_repo_name": "LUUTHIENXUAN/Udacity-CarND-Hybird-A-", "max_issues_repo_head_hexsha": "f453d9d41a3ccf024cbd1d6e154b9a2a23cb22b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hastar_navi/src/hybrid_astar.cpp", "max_forks_repo_name": "LUUTHIENXUAN/Udacity-CarND-Hybird-A-", "max_forks_repo_head_hexsha": "f453d9d41a3ccf024cbd1d6e154b9a2a23cb22b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-11-27T15:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T15:27:47.000Z", "avg_line_length": 30.0, "max_line_length": 114, "alphanum_fraction": 0.5791515152, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5713921654306907}}
{"text": "#include \"Util.h\"\n\n#include <Eigen/SVD>\n\n#include <iostream>\n\nusing namespace std;\n\nbool Ubpa::PDIPM_QP::CheckSettingsValid() const {\n\t//float gamma{ 1.05f }; // t multiplier\n\t//float epsilon_feas{ 0.001f }; // residule error\n\t//float epsilon{ 0.001f }; // gap error\n\t//float beta{ 0.99f }; // alpha shrink multiplier\n\t//float tau{ 0.02f }; // backtracking\n\n\tif (gamma <= 1.f)\n\t\treturn false;\n\n\tif (epsilon_feas <= 0 || epsilon <= 0)\n\t\treturn false;\n\n\tif (beta <= 0 || beta >= 1)\n\t\treturn false;\n\n\tif (tau <= 0 || tau >= 1)\n\t\treturn false;\n#ifndef NDEBUG\n\telse {\n\t\tif (tau < 0.01 || tau > 0.1)\n\t\t\tassert(\"tau is typically chosen in the range 0.01 to 0.1\");\n\t}\n#endif // !NDEBUG\n\n\treturn true;\n}\n\nbool Ubpa::PDIPM_QP::SetProblem(\n\tEigen::MatrixXf P, // n x n\n\tEigen::VectorXf q, // n x 1\n\tfloat           r,\n\n\tEigen::MatrixXf G, // m x n\n\tEigen::VectorXf h, // m x 1\n\n\tEigen::MatrixXf A, // p x n\n\tEigen::VectorXf b  // p x 1\n) {\n\tsize_t n = P.rows();\n\tsize_t m = G.rows();\n\tsize_t p = A.rows();\n\n\tif (P.cols() != n\n\t\t|| q.size() != n\n\t\t|| G.cols() != n\n\t\t|| h.size() != m\n\t\t|| A.cols() != n\n\t\t|| b.size() != p)\n\t{\n\t\treturn false;\n\t}\n\n\tthis->P = std::move(P);\n\tthis->q = std::move(q);\n\tthis->r = r;\n\n\tthis->G = std::move(G);\n\tthis->h = std::move(h);\n\n\tthis->A = std::move(A);\n\tthis->b = std::move(b);\n\n\tthis->n = n;\n\tthis->m = m;\n\tthis->p = p;\n\n\treturn true;\n}\n\nvoid Ubpa::PDIPM_QP::Init() {\n\t// f(x) < 0\n\t// => Gx - h = -1\n\t// => x = pinv(G) * (h - 1)\n\n\t// presudo inverse of G\n\tEigen::JacobiSVD<Eigen::MatrixXf> G_svd(G, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tconst auto& SV = G_svd.singularValues();\n\tEigen::MatrixXf ISV;\n\tISV.setZero(G.cols(), G.rows());\n\tfor (size_t i = 0; i < SV.size(); i++) {\n\t\tif (SV(i) > 0.000001f)\n\t\t\tISV(i, i) = 1.f / SV(i);\n\t}\n\tEigen::MatrixXf pinv_G = G_svd.matrixV() * ISV * G_svd.matrixU().transpose();\n\n\tx = pinv_G * (h - Eigen::VectorXf::Ones(m));\n\n\tlambda.setOnes(m); // > 0\n\tnu.setZero(p);\n\n\tEigen::VectorXf f_x = -Eigen::VectorXf::Ones(m); // G * x - h\n\n\teta = m; // -f_x.dot(lambda);\n\tfloat t = gamma; /* *m / eta */;\n\n\tEigen::MatrixXf diag_lambda;\n\tdiag_lambda.setZero(m, m);\n\tfor (size_t i = 0; i < m; i++)\n\t\tdiag_lambda(i, i) = lambda(i);\n\n\tr_dual = P * x + q + G.transpose() * lambda; /* + A.transpose() * nu */\n\tr_cent = -diag_lambda * f_x - (1.f / t) * Eigen::VectorXf::Ones(m);\n\tr_pri = A * x - b;\n}\n\nvoid Ubpa::PDIPM_QP::Iterate() {\n\t// [[ 1. compute Newton step ]]\n\n\tEigen::MatrixXf M(n + m + p, n + m + p);\n\tM.setZero();\n\n\tEigen::VectorXf f_x = G * x - h;\n\n\t// (0, 0) - (n-1, n-1)\n\t// P\n\tfor (size_t i = 0; i < n; i++) {\n\t\tfor (size_t j = 0; j < n; j++)\n\t\t\tM(i, j) = P(i, j);\n\t}\n\n\t// (0, n) - (n-1, n+m-1)\n\t// G^T\n\tfor (size_t i = 0; i < n; i++) {\n\t\tfor (size_t j = 0; j < m; j++)\n\t\t\tM(i, j + n) = G(j, i);\n\t}\n\n\t// (0, n+m) - (n-1, n+m+p-1)\n\t// A^T\n\tfor (size_t i = 0; i < n; i++) {\n\t\tfor (size_t j = 0; j < p; j++)\n\t\t\tM(i, j + n + m) = A(j, i);\n\t}\n\n\t// (n, 0) - (n+m-1, n-1)\n\t// - diag(lambda)G\n\n\tEigen::MatrixXf diag_lambda;\n\tdiag_lambda.setZero(m, m);\n\tfor (size_t i = 0; i < m; i++)\n\t\tdiag_lambda(i, i) = lambda(i);\n\tEigen::MatrixXf diag_lambda_G = diag_lambda * G;\n\tfor (size_t i = 0; i < m; i++) {\n\t\tfor (size_t j = 0; j < n; j++)\n\t\t\tM(i + n, j) = -diag_lambda_G(i, j);\n\t}\n\n\t// (n, n) - (n+m-1, n+m-1)\n\t// - diag(f(x))\n\tfor (size_t i = 0; i < m; i++)\n\t\tM(i + n, i + n) = -f_x(i);\n\n\t// (n+m, 0) - (n+m+p-1, n-1)\n\t// A\n\tfor (size_t i = 0; i < p; i++) {\n\t\tfor (size_t j = 0; j < n; j++)\n\t\t\tM(i + n + m, j) = A(i, j);\n\t}\n\n\tEigen::VectorXf r(n + m + p);\n\tfor (size_t i = 0; i < n; i++)\n\t\tr(i, 0) = r_dual(i);\n\tfor (size_t i = 0; i < m; i++)\n\t\tr(i + n, 0) = r_cent(i);\n\tfor (size_t i = 0; i < p; i++)\n\t\tr(i + n + m, 0) = r_pri(i);\n\n\t// y = (x, lambda, nu)\n\t// (n + m + p) x 1\n\tEigen::VectorXf delta_y = M.colPivHouseholderQr().solve(-r);\n\n\tEigen::VectorXf delta_x(n);\n\tEigen::VectorXf delta_lambda(m);\n\tEigen::VectorXf delta_nu(p);\n\n\tfor (size_t i = 0; i < n; i++)\n\t\tdelta_x(i, 0) = delta_y(i);\n\tfor (size_t i = 0; i < m; i++)\n\t\tdelta_lambda(i, 0) = delta_y(i + n);\n\tfor (size_t i = 0; i < p; i++)\n\t\tdelta_nu(i, 0) = delta_y(i + n + m);\n\n\t// [[ 2. backtracking line search ]]\n\n\tfloat alpha_max = 1.f;\n\tfor (size_t i = 0; i < m; i++) {\n\t\tif (delta_lambda(i) < 0) {\n\t\t\tfloat cur = -lambda(i) / delta_lambda(i);\n\t\t\tif (cur < alpha_max)\n\t\t\t\talpha_max = cur;\n\t\t}\n\t}\n\n\tfloat alpha = 0.99f * alpha_max;\n\tbool flag1 = false;\n\tbool flag2 = false;\n\n\twhile (!flag1) {\n\t\tEigen::VectorXf x_plus = x + alpha * delta_x;\n\t\tEigen::VectorXf f_x_plus = G * x_plus - h;\n\t\tfor (size_t i = 0; i < m; i++) {\n\t\t\tif (f_x_plus(i) >= 0) {\n\t\t\t\talpha *= beta;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (i == m - 1)\n\t\t\t\tflag1 = true;\n\t\t}\n\t}\n\n\tfloat rt_norm = Get_residule();\n\n\twhile (!flag2) {\n\t\tEigen::VectorXf x_plus = x + alpha * delta_x;\n\t\tEigen::VectorXf lambda_plus = lambda + alpha * delta_lambda;\n\t\tEigen::VectorXf nu_plus = nu + alpha * delta_nu;\n\n\t\tEigen::MatrixXf diag_lambda_plus;\n\t\tdiag_lambda_plus.setZero(m, m);\n\t\tfor (size_t i = 0; i < m; i++)\n\t\t\tdiag_lambda_plus(i, i) = lambda_plus(i);\n\n\t\tEigen::VectorXf f_x_plus = G * x_plus - h;\n\n\t\teta = -f_x_plus.dot(lambda_plus);\n\t\tfloat t = gamma * m / eta;\n\n\t\tr_dual = P * x_plus + q + G.transpose() * lambda_plus + A.transpose() * nu_plus;\n\t\tr_cent = -diag_lambda_plus * f_x_plus - (1.f / t) * Eigen::VectorXf::Ones(m);\n\t\tr_pri = A * x_plus - b;\n\n\t\tfloat rt_norm_plus = Get_residule();\n\n\t\tif (rt_norm_plus <= (1 - tau * alpha) * rt_norm)\n\t\t\tflag2 = true;\n\t\telse\n\t\t\talpha *= beta;\n\t}\n\n\t// [[ 3. update ]]\n\t// x, lambda, nu\n\n\tx += alpha * delta_x;\n\tlambda += alpha * delta_lambda;\n\tnu += alpha * delta_nu;\n}\n\nbool Ubpa::PDIPM_QP::IsStoppable() {\n\tif (r_dual.norm() > epsilon_feas\n\t\t|| r_pri.norm() > epsilon_feas\n\t\t|| eta > epsilon)\n\t{\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nfloat Ubpa::PDIPM_QP::Get_residule() const {\n\treturn std::sqrt(\n\t\tr_dual.squaredNorm()\n\t\t+ r_cent.squaredNorm()\n\t\t+ r_pri.squaredNorm());\n}", "meta": {"hexsha": "100aa7ce1fd1e2096c65a481417d8e8c224b736b", "size": 5874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020Spring/Optimization/homeworks/final/convex/src/core/Util.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/Optimization/homeworks/final/convex/src/core/Util.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/Optimization/homeworks/final/convex/src/core/Util.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": 21.5164835165, "max_line_length": 87, "alphanum_fraction": 0.5469867211, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5711653908277269}}
{"text": "#ifndef CANNON_PHYSICS_SYSTEMS_DYNAMIC_CAR_H\n#define CANNON_PHYSICS_SYSTEMS_DYNAMIC_CAR_H \n\n#include <random>\n#include <cassert>\n\n#include <ompl/control/ODESolver.h>\n#include <ompl/control/spaces/RealVectorControlSpace.h>\n#include <ompl/base/spaces/SO2StateSpace.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n\n#include <Eigen/Dense>\n\n#include <cannon/physics/rk4_integrator.hpp>\n#include <cannon/physics/systems/system.hpp>\n#include <cannon/graphics/geometry/plane.hpp>\n#include <cannon/log/registry.hpp>\n\nusing namespace Eigen;\n\nusing namespace cannon::log;\n\nnamespace oc = ompl::control;\nnamespace ob = ompl::base;\n\nnamespace cannon {\n  namespace physics {\n    namespace systems {\n\n      struct DynamicCarSystem : System {\n        DynamicCarSystem(double l = 1.0) : l_(l) {}\n\n        virtual void operator()(const VectorXd& s, VectorXd& dsdt, const double /*t*/) override {\n          double th = s[2];\n          double v = s[3];\n          double dth = s[4];\n          double ua = s[5];\n          double uth = s[6];\n\n          // From http://planning.cs.uiuc.edu/node658.html\n          dsdt.resize(7);\n          dsdt[0] = v * std::cos(th);\n          dsdt[1] = v * std::sin(th);\n          dsdt[2] = (v / l_) * std::tan(dth);\n          dsdt[3] = ua;\n          dsdt[4] = uth;\n          dsdt[5] = 0.0;\n          dsdt[6] = 0.0;\n        }\n\n        virtual void ompl_ode_adaptor(const oc::ODESolver::StateType& q, \n            const oc::Control* control, oc::ODESolver::StateType& qdot) override {\n\n          const double ua = control->as<oc::RealVectorControlSpace::ControlType>()->values[0];\n          const double uth = control->as<oc::RealVectorControlSpace::ControlType>()->values[1];\n\n          VectorXd s(7);\n          s[0] = q[0];\n          s[1] = q[1];\n          s[2] = q[2];\n          s[3] = q[3];\n          s[4] = q[4];\n          s[5] = ua;\n          s[6] = uth;\n          VectorXd dsdt(7);\n\n          (*this)(s, dsdt, 0.0);\n\n          qdot.resize(q.size(), 0);\n          for (unsigned int i = 0; i < q.size(); i++) {\n            qdot[i] = dsdt[i];\n          }\n        }\n\n        virtual std::tuple<MatrixXd, MatrixXd, VectorXd> get_linearization(const VectorXd& x) override {\n          assert(x.size() == 5);\n\n          double th = x[2];\n          double v = x[3];\n          double dth = x[4];\n\n          // TODO Don't hardcode timestep at some point\n          double timestep = 0.01;\n\n          MatrixXd A(5, 5);\n          A << 1, 0, -v * std::sin(th) * timestep, std::cos(th) * timestep, 0,\n               0, 1, v * std::cos(th) * timestep, std::sin(th) * timestep, 0,\n               0, 0, 1, (tan(dth) / l_) * timestep, (v / l_) * (1.0 / (cos(dth) * cos(dth))) * timestep,\n               0, 0, 0, 1, 0,\n               0, 0, 0, 0, 1;\n\n          MatrixXd B(5, 2);\n          B << 0, 0,\n               0, 0,\n               0, 0,\n               timestep, 0,\n               0, timestep;\n\n          \n          VectorXd c(5); \n          c << x[0] + v * std::cos(th) * timestep,\n               x[1] + v * std::cos(th) * timestep,\n               th + (v / l_) * tan(dth) * timestep,\n               v,\n               dth;\n\n          // We linearize around u = 0, so no additional term is subtracted from c\n          return std::make_tuple(A, B, c - A * x);\n        }\n\n        virtual void\n        get_continuous_time_linearization(const oc::ODESolver::StateType &q,\n                                          Ref<MatrixXd> A, Ref<MatrixXd> B) override {\n          double c = cos(q[2]), s = sin(q[2]);\n          A = 1e-3 * Eigen::MatrixXd::Identity(5, 5);\n          A(0, 2) = -q[3] * s;\n          A(0, 3) = c;\n          A(1, 2) = q[3] * c;\n          A(1, 3) = s;\n          A(2, 3) = (1.0 / l_) * tan(q[4]);\n          A(2, 4) = q[3] * (1.0 / l_) / (cos(q[4]) * cos(q[4]));\n\n          B = Eigen::MatrixXd::Zero(5, 2);\n          B(3, 0) = B(4, 1) = 1.;\n        }\n\n        static void ompl_post_integration(const ob::State* /*state*/, const\n            oc::Control* /*control*/, const double /*duration*/, ob::State *result) {\n\n          ob::SO2StateSpace SO2;\n          SO2.enforceBounds(result->as<ob::CompoundStateSpace::StateType>()\n                                ->as<ob::SE2StateSpace::StateType>(0)\n                                ->as<ob::SO2StateSpace::StateType>(1));\n        }\n\n        // Parameters\n        double l_;\n      };\n\n      class DynamicCar {\n        public:\n          DynamicCar() = delete;\n\n          DynamicCar(VectorXd s, VectorXd g, double l = 1.0)\n              : s_(l), e_(s_, 7, time_step), start_(s), goal_(g) {\n            std::random_device rd;\n            gen_ = std::mt19937(rd());  \n\n            xy_dis_ = std::uniform_real_distribution<double>(-1.0, 1.0);\n            th_dis_ = std::uniform_real_distribution<double>(-M_PI, M_PI);\n\n            state_ = VectorXd::Zero(7);\n            reset();\n          }\n\n          std::pair<VectorXd, double> step(double ua, double uth) {\n            //double clipped_uth = std::max(-M_PI * 2.0 / 180.0, std::min(uth, M_PI * 2.0 / 180.0));\n            \n            //double clipped_uth = std::max(-M_PI, std::min(uth, M_PI));\n           \n            state_[5] = ua;\n            state_[6] = uth;\n\n            double goal_r = -std::pow((state_.head(2) - goal_.head(2)).norm(), 2.0);\n            double control_r = -std::pow((std::abs(uth) + std::abs(ua)), 2.0);\n            double reward = goal_r + 0.001*control_r;\n\n\n            e_.set_state(state_);\n            state_ = e_.step();\n\n            return std::make_pair(state_.head(5), reward);\n          }\n          \n          VectorXd reset() {\n            state_[0] = xy_dis_(gen_);\n            state_[1] = xy_dis_(gen_);\n            state_[2] = th_dis_(gen_);\n            state_[3] = 0.0;\n            state_[4] = 0.0;\n            \n            state_[4] = 0.0;\n            state_[5] = 0.0;\n\n            return state_.head(5);\n          }\n\n          \n          VectorXd reset(const VectorXd& s) {\n            assert(s.size() == 5);\n\n            state_[0] = s[0];\n            state_[1] = s[1];\n            state_[2] = s[2];\n            state_[3] = s[3];\n            state_[4] = s[4];\n            \n            state_[5] = 0.0;\n            state_[6] = 0.0;\n\n            return state_.head(5);\n          }\n\n          // In seconds\n          const double time_step = 0.01;\n\n          DynamicCarSystem s_;\n          \n        private:\n          RK4Integrator e_;\n\n          VectorXd state_;\n\n          VectorXd start_;\n          VectorXd goal_;\n\n          std::mt19937 gen_;\n          std::uniform_real_distribution<double> xy_dis_;\n          std::uniform_real_distribution<double> th_dis_;\n      };\n\n\n    } // namespace physics\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_SYSTEMS_DYNAMIC_CAR_H */\n", "meta": {"hexsha": "877af35139a843fc048753a18343ad022c8a9e71", "size": 6742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/systems/dynamic_car.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/physics/systems/dynamic_car.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/physics/systems/dynamic_car.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": 29.5701754386, "max_line_length": 104, "alphanum_fraction": 0.4859092257, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162772, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5711653908277268}}
{"text": "#include <string>\n\n#include <CGAL/boost/graph/properties.h>\n#include <Eigen/SparseCore>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n#include <Euclid/Util/Assert.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/MatOp/SparseSymShiftSolve.h>\n#include <Spectra/MatOp/SymShiftInvert.h>\n#include <Spectra/SymEigsShiftSolver.h>\n#include <Spectra/SymGEigsShiftSolver.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename T, typename DerivedA, typename DerivedB>\nunsigned sym_solve(const Eigen::SparseMatrix<T>& L,\n                   int k,\n                   int nv,\n                   unsigned max_iter,\n                   double tolerance,\n                   Eigen::MatrixBase<DerivedA>& lambdas,\n                   Eigen::MatrixBase<DerivedB>& phis)\n{\n    // use shift-invert mode to get the smallest eigenvalues fast\n    auto convergence = std::min(2 * k + 1, nv);\n    using Operator = Spectra::SparseSymShiftSolve<T>;\n    using Solver = Spectra::SymEigsShiftSolver<Operator>;\n    Operator op(L);\n    Solver eigensolver(op, k, convergence, -1.0);\n    eigensolver.init();\n    unsigned n = eigensolver.compute(Spectra::SortRule::LargestMagn,\n                                     max_iter,\n                                     static_cast<T>(tolerance),\n                                     Spectra::SortRule::SmallestMagn);\n    if (eigensolver.info() != Spectra::CompInfo::Successful) {\n        throw std::runtime_error(\"Eigen decomposition failed.\");\n    }\n    lambdas = eigensolver.eigenvalues();\n    phis = eigensolver.eigenvectors();\n    return n;\n}\n\ntemplate<typename T, typename DerivedA, typename DerivedB>\nunsigned gen_solve(const Eigen::SparseMatrix<T>& S,\n                   const Eigen::SparseMatrix<T>& D,\n                   int k,\n                   int nv,\n                   unsigned max_iter,\n                   double tolerance,\n                   Eigen::MatrixBase<DerivedA>& lambdas,\n                   Eigen::MatrixBase<DerivedB>& phis)\n{\n    int convergence = std::min(2 * k + 1, nv);\n    using Operator = Spectra::SymShiftInvert<T, Eigen::Sparse, Eigen::Sparse>;\n    using BOperator = Spectra::SparseSymMatProd<T>;\n    using Solver =\n        Spectra::SymGEigsShiftSolver<Operator,\n                                     BOperator,\n                                     Spectra::GEigsMode::ShiftInvert>;\n    Operator op(S, D);\n    BOperator bop(D);\n    Solver eigensolver(op, bop, k, convergence, -1.0);\n    eigensolver.init();\n    unsigned n = eigensolver.compute(Spectra::SortRule::LargestMagn,\n                                     max_iter,\n                                     static_cast<T>(tolerance),\n                                     Spectra::SortRule::SmallestMagn);\n    if (eigensolver.info() != Spectra::CompInfo::Successful) {\n        throw std::runtime_error(\"Eigen decomposition failed.\");\n    }\n    lambdas = eigensolver.eigenvalues();\n    phis = eigensolver.eigenvectors();\n    return n;\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh, typename DerivedA, typename DerivedB>\nunsigned spectrum(const Mesh& mesh,\n                  unsigned k,\n                  Eigen::MatrixBase<DerivedA>& lambdas,\n                  Eigen::MatrixBase<DerivedB>& phis,\n                  SpecOp op,\n                  unsigned max_iter,\n                  double tolerance)\n{\n    using T = typename CGAL::Kernel_traits<typename boost::property_traits<\n        typename boost::property_map<Mesh, boost::vertex_point_t>::type>::\n                                               value_type>::Kernel::FT;\n    using SpMat = Eigen::SparseMatrix<T>;\n    auto nv = num_vertices(mesh);\n\n    if (k > nv) {\n        std::string err(\"You've requested \");\n        err.append(std::to_string(k));\n        err.append(\" eigenvalues but there are only \");\n        err.append(std::to_string(nv));\n        err.append(\" vertices in your mesh.\");\n        EWARNING(err);\n        k = nv;\n    }\n\n    unsigned n;\n    if (op == SpecOp::mesh_laplacian) {\n        SpMat C = Euclid::cotangent_matrix(mesh);\n        SpMat D = Euclid::mass_matrix(mesh);\n        n = _impl::gen_solve(C, D, k, nv, max_iter, tolerance, lambdas, phis);\n    }\n    else {\n        auto result = Euclid::adjacency_matrix(mesh);\n        SpMat A = std::get<0>(result);\n        SpMat D = std::get<1>(result);\n        SpMat L = D - A;\n        n = _impl::sym_solve(L, k, nv, max_iter, tolerance, lambdas, phis);\n    }\n\n    if (n < k) {\n        auto str = std::to_string(k);\n        str.append(\" eigenvalues are requested, but only \");\n        str.append(std::to_string(n));\n        str.append(\" values converged in computation.\");\n        EWARNING(str);\n    }\n    EASSERT(lambdas.rows() == n);\n    EASSERT(phis.cols() == n);\n    EASSERT(phis.rows() == nv);\n\n    return n;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "c390a8c0c48dac873a2b5c569365c8c8228dae9b", "size": 4766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Geometry/src/Spectral.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Geometry/src/Spectral.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Geometry/src/Spectral.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 35.0441176471, "max_line_length": 78, "alphanum_fraction": 0.5780528745, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5711653633089631}}
{"text": "#ifndef __Linear_regression__\n#define __Linear_regression__\n#include<iostream>\n#include<Eigen/Dense>\n#include<utility>\n#include<string>\n#include\"generate_data.hpp\"\n#include<random>\n#include <Eigen/Cholesky>\n#include<cmath>\n\nEigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> shuffling_data(size_t n)\n{\n    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> shuffled(n);\n    shuffled.setIdentity();\n    std::random_shuffle(shuffled.indices().data(), shuffled.indices().data() + shuffled.indices().size());\n    return shuffled;\n}\n\nfloat compute_mse(const Eigen::VectorXf& pred, const Eigen::VectorXf& y)\n{\n    float value = (1.0f/pred.rows()) * ((y - pred).transpose() * (y-pred)).sum();\n    return value;\n\n}\nEigen::VectorXf gradient_descent(const Eigen::MatrixXf& X, const Eigen::MatrixXf& y, float learning_rate, size_t num_rows)\n{\n    //I already assume that X is padded with 1's\n    Eigen::VectorXf B = Eigen::VectorXf::Random(X.cols());\n    B(0) = 0.0f;\n    size_t blocks_size = (size_t) (X.rows()/num_rows);\n    //in case if the num_rows was larger than the number of rows of X\n    if(blocks_size == 0)\n    {\n        blocks_size = 1;\n        num_rows = X.rows();\n    }\n    int counter = 0;\n    Eigen::MatrixXf block_of_X = Eigen::MatrixXf::Zero(num_rows, X.cols());\n    Eigen::VectorXf block_of_y = Eigen::VectorXf::Zero(num_rows);\n    for(int iter = 0; iter < 100; iter++)\n    {\n        counter = 0;\n        block_of_X = Eigen::MatrixXf(num_rows, X.cols());\n        block_of_y = Eigen::VectorXf(num_rows);\n\n        for(int block=0; block < blocks_size; block++)\n        {\n            //taking a slice from X, it appears that I don't have Eigen::seq\n            for(int row=0; row < num_rows; row++)\n            {\n                block_of_X.row(row) = X.row(row + counter);\n                block_of_y.row(row) = y.row(row + counter);\n            }\n            //updating B\n            //std::cout << block_of_y << std::endl;\n            // std::cout << \"x\\t\" << block_of_X <<\"\\n\" << std::endl;\n            // std::cout << \"xT\\t\" << block_of_X.transpose() <<\"\\n\" << std::endl;\n\n            B = B - learning_rate * 1.0f/(block_of_X.rows()) * block_of_X.transpose() * (block_of_X * B - block_of_y);\n            Eigen::VectorXf pred = Eigen::VectorXf(block_of_X.rows());\n            pred = block_of_X * B;\n            float error = compute_mse(pred, block_of_y);\n            std::cout << \"Step: \" << block + iter * blocks_size  << \" error: \" << error << std::endl;\n\n\n            counter += num_rows;\n        } \n        if(counter < X.rows())\n        {\n            int rest_of_rows = X.rows() - counter;\n            block_of_X = Eigen::MatrixXf(rest_of_rows, X.cols());\n            block_of_y = Eigen::VectorXf(rest_of_rows);\n\n            for(int row=0; row < rest_of_rows; row++)\n            {\n                block_of_X.row(row) = X.row(row + counter);\n                block_of_y.row(row) = y.row(row + counter);\n            }\n            //updating B\n            //std::cout << \"rows: \" << block_of_X.rows() << std::endl;\n            B = B - learning_rate * block_of_X.transpose() * ( block_of_X * B - block_of_y );\n            Eigen::VectorXf pred = Eigen::VectorXf(rest_of_rows);\n            pred = block_of_X * B;\n            float error = compute_mse(pred, block_of_y);\n            std::cout << \"Step: \" << blocks_size + 1 + + iter * blocks_size << \" error: \" << error << std::endl;\n\n        }\n    }\n   \n    //std::cout << \"B\\n \" << B << std::endl; \n\n    return B;\n}\nfloat estimate_variance(const Eigen::MatrixXf& X, const Eigen::MatrixXf& y, const Eigen::VectorXf& B)\n{\n    //I will use the biased estimate in which I willn't divide by n-1\n    float sigma = (1.0f/y.rows()) * ((y - X * B).transpose() * (y - X * B)).sum();\n    return sigma;\n}\nvoid make_prediction(const Eigen::VectorXf& B, const Eigen::MatrixXf& x, float sigma, const float true_y);\n\n//I will only deal with metric/conttinuous data\nvoid Linear_regression_training(const std::string file_name, float lr, int num_rows)\n{\n    std::pair<Eigen::MatrixXf, Eigen::MatrixXf> data = load_csv_for_LinearR(file_name);\n    Eigen::MatrixXf X = data.first;\n    Eigen::MatrixXf X_with_pad = Eigen::MatrixXf(X.rows(), X.cols() + 1 );\n    //pad X for the intercept term\n    Eigen::VectorXf b0 = Eigen::VectorXf::Ones(X.rows());\n    //shifting columns\n    X_with_pad.col(0) = b0;\n    for(int i=1; i < X_with_pad.cols(); i++)\n    {\n        X_with_pad.col(i) = X.col(i - 1);\n    }\n    Eigen::MatrixXf y = data.second;\n    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> shuffled_indeces(shuffling_data(X.rows()));\n    //shuffling data\n    X_with_pad = shuffled_indeces * X_with_pad;\n    y = shuffled_indeces * y;\n    //standard normalize X\n    // float* means = new float[X_with_pad.cols() - 1];\n    // float* std_ = new float[X_with_pad.cols() - 1];\n    // Eigen::VectorXf tmp = Eigen::VectorXf::Ones(X_with_pad.rows());\n\n    // for(int i=1; i < X_with_pad.cols(); i++)\n    // {\n    //     means[i - 1] = X_with_pad.col(i).mean();\n    //     X_with_pad.col(i) = X_with_pad.col(i) - tmp * means[i -1];\n    //     std_[i - 1] = 1/X_with_pad.rows() * (X_with_pad.col(i).transpose() * X_with_pad.col(i)).sum();\n    //     tmp = X_with_pad.col(i);\n    //     std::cout << X_with_pad << std::endl;\n    //     std::cout << \"m \" << means[i - 1] << \" std: \" << std_[i -1] << std::endl;\n    //     tmp = tmp / std_[i-1];\n    //     std::cout << tmp << std::endl;\n    //     X_with_pad.col(i) = tmp;\n    // }\n    // float meany, std_y;\n    // //standard normalize y\n    // meany = y.mean();\n    // y = y - tmp * meany;\n    // std_y = 1/y.rows() * (y.transpose() * y).sum();\n    // tmp = y;\n    // y = tmp/std_y;\n    //use meany, std_y, means and std_ for prediction stage.\n\n    //Finding Value of B\n    Eigen::VectorXf B = gradient_descent(X_with_pad, y, lr, num_rows);\n    Eigen::VectorXf B_ols = (X_with_pad.transpose() * X_with_pad).inverse() * X_with_pad.transpose() * y;\n    \n    std::cout << \"Mini-batch GD estimat of of B: \\n\" << B << std::endl;\n    std::cout << \"Error in prediction GD: \" << compute_mse(X_with_pad * B, y) << std::endl;\n    std::cout << \"Sigma Estimate by GD: \" << estimate_variance(X_with_pad, y, B) << std::endl;\n    std::cout << \"OLS of B: \\n\" << B_ols << std::endl;\n    std::cout << \"Error in prediction OLS: \" << compute_mse(X_with_pad * B_ols, y) << std::endl;\n    // std::cout << X_with_pad << std::endl;\n    // std::cout << y << std::endl;\n    make_prediction(B, X_with_pad.row(10).transpose(), estimate_variance(X_with_pad, y, B), y.row(10).sum());\n\n}\n\nvoid make_prediction(const Eigen::VectorXf& B, const Eigen::MatrixXf& x, float sigma, const float true_y)\n{\n    auto f = [](float pred, float true_v){\n\n        return std::sqrt((pred - true_v) * (pred - true_v));\n    };\n    std::cout << \"B: \" << B.transpose().cols() << std::endl;\n    std::cout << \"x: \" << x.rows() << std::endl;\n    float y = (B.transpose() * x).sum();\n    std::cout << \"Prediciton: \" << y << \" true value: \" << true_y << \" rms: \" << f(y, true_y) << std::endl;\n\n}\n\n\n\n#endif /*__Linear_regression__*/", "meta": {"hexsha": "e7a442423e7417e95ec2abc179917ed35cfd123d", "size": 7069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/machine_learning_basics/Linear_regression_Model.hpp", "max_stars_repo_name": "AlazzR/Computer-Vision-Cpp-ML", "max_stars_repo_head_hexsha": "725ad6830341a2ed2ff088d50cb99b7f9117783b", "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": "Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/machine_learning_basics/Linear_regression_Model.hpp", "max_issues_repo_name": "AlazzR/Computer-Vision-Cpp-ML", "max_issues_repo_head_hexsha": "725ad6830341a2ed2ff088d50cb99b7f9117783b", "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": "Computer_Vision/Revision_DIP_Linear_and_Softmax_Regression/machine_learning_basics/Linear_regression_Model.hpp", "max_forks_repo_name": "AlazzR/Computer-Vision-Cpp-ML", "max_forks_repo_head_hexsha": "725ad6830341a2ed2ff088d50cb99b7f9117783b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7134831461, "max_line_length": 122, "alphanum_fraction": 0.5824020371, "num_tokens": 2060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5711478914913981}}
{"text": "//\n//  main.cpp\n//  Assignment 2 - Bearings\n//\n//  Created by - on 2016/09/27.\n//  Copyright © 2016 Eddie Of the Ren. All rights reserved.\n//\n#include <iostream>\n//#include \"stdafx.h\"\nusing namespace std;\n#include <stdio.h>      /* printf */\n#include <math.h>\n//#include <boost/lexical_cast.hpp>\n#include <string>\n\nint cardinalNum1 = 0;\nint cardinalNum2 = 0;\n\n//This function converts the cardinal string to a number that can fit in an array\nint cardinalStrToNum(string cardinalStr) {\n    int cardinalNum = 0;\n    if (cardinalStr== \"N\") {\n        cardinalNum = 2;\n    } else if (cardinalStr == \"E\") {\n        cardinalNum = 3;\n    } else if (cardinalStr == \"S\") {\n        cardinalNum = 4;\n    } else if (cardinalStr == \"W\") {\n        cardinalNum = 5;\n    }\n    return cardinalNum;\n    \n}\n\n//This checks if a string is a number that is composed only of \"-.0123456789\"\nbool is_number(const std::string& s)\n{\n    return( strspn( s.c_str(), \"-.0123456789\" ) == s.size() );\n}\n\n//If the user enters a bearing that is not within 0 to 359, this converts it to within that limit\nint getBearing(int x) {\n    double customBearing = 0;\n    //Turning negative values positive\n    while (x < 0) {\n        x = x + 360;\n    }\n    //Turning overweight values smaller\n    while (x >= 360) {\n        x = x - 360;\n    }\n    customBearing = x;\n    \n    return (customBearing);\n}\n\n//This function will accept a bearing direction and turn it into a compass direction\nint bearingToCompass(double bearing, string gameChoice) {\n    double choiceInt = 0;\n    \n    int quadrant = 0;\n    bool CW = false;\n    string cardinals [6] = {\"W\", \"N\", \"E\", \"S\", \"W\", \"N\"};\n    \n    //getBearing will convert the user entered value into a value between 1 and 360, discrimination is currently enforced to favor 0° over 360°\n    \n    //These two lines turn the bearing into a value between 0 and 359 and finds the inverse quadrant it resides in. The quadrants are counted clockwise, NOT counter-clockwise\n    bearing = getBearing(bearing);\n    quadrant = floor(bearing/90);\n    \n    //If this if statement is true, that means the degree applies in a clockwise direction relative to the first cardinal. Ex: N32E. the direciton is 32 east (clockwise) FROM north\n    if ((bearing - 90*quadrant) <45) {\n        CW = false;\n        cout << cardinals[(quadrant + 1)] << (bearing - 90*quadrant) << cardinals[(quadrant+2)] <<endl;\n        if (gameChoice == \"1\") {\n            \n            cout << \"Primary compass direction:             \" << cardinals[(quadrant + 1)] << endl;\n            cout << \"Compass angle relative to direction:   \" << (bearing - 90*quadrant) << endl;\n            cout << \"Secondary compass direction:           \" << cardinals[(quadrant+2)]<< endl;\n        }\n    \n    }\n    //If this if statement is true, that means the degree applies in a counter-clockwise direction relative to the first cardinal. Ex: N65E. The direction is 65 north (counterclockwise) FROM east. This is equivalent to E25N which is a better way of representing the direction.\n    else if ((bearing - 90*quadrant) >45) {\n        CW = true;\n        cout << cardinals[(quadrant + 2)] << (90-(bearing - 90*quadrant)) << cardinals[(quadrant+1)] <<endl;\n        \n        if (gameChoice == \"1\") {\n            cout << \"Primary compass direction:             \" << cardinals[(quadrant + 2)] << endl;\n            //The line of code below ensures that the angle is between 1° and 44°\n            cout << \"Compass angle                          \" << (90-(bearing - 90*quadrant)) << \"°\" <<     endl;\n            cout << \"Secondary compass direction:           \"<< cardinals[(quadrant+1)]<< endl;\n        }\n    }\n    //When the angle is 45° or exactly between two cardinals, the bearing is not displayed\n    else if ((bearing - 90*quadrant) == 45) {\n        cout << cardinals[(quadrant + 1)]  << cardinals[(quadrant+2)] <<endl;\n        \n        if (gameChoice == \"1\") {\n            cout << \"Primary compass direction:             \" << cardinals[(quadrant + 1)] << endl;\n            cout << \"Compass angle relative to direction:   \" << endl;\n            cout << \"Secondary compass direction:           \" << cardinals[(quadrant+2)]<< endl;\n        }\n    }\n    \n    //cout << cardinals[(quadrant+1)] << endl;\n    //cout << bearing<< endl;\n    return 0;\n    \n}\n\n//This functions checks the cardinals and angle the user entered are valid or not.\nbool cardinalCheck (string primaryCardinal, string secondaryCardinal, string angleStr) {\n    bool redo = false;\n    if (primaryCardinal != \"N\"&& primaryCardinal!= \"E\" && primaryCardinal != \"W\" && primaryCardinal != \"S\") {\n        redo = true;\n        cout << \"Your primary cardinal direciton is not one of N, E, S, W \" << endl;\n    } else if (secondaryCardinal != \"N\"&& secondaryCardinal!= \"E\" && secondaryCardinal != \"W\" && secondaryCardinal != \"S\") {\n        redo = true;\n        cout << \"Your secondary cardinal direciton is not one of N, E, S, W \" << endl;\n    } else if (is_number(angleStr) == 0)  {\n        redo = true;\n        cout << \"Your angle is not a number \" << endl;\n    } else {\n        //following statements ensure that the user has not entered two identical or opposite cardinals, such as N20N or N20S\n        cardinalNum1 = cardinalStrToNum(primaryCardinal);\n        cardinalNum2 = cardinalStrToNum(secondaryCardinal);\n        if (cardinalNum1 - cardinalNum2 >= 0) {\n            if ((cardinalNum1-cardinalNum2)%2 == 0) {\n                redo = true;\n                cout<< \"These coordinates are invalid\"<< endl;\n            }\n        } else if (cardinalNum1 - cardinalNum2 < 0) {\n            if ((-(cardinalNum1-cardinalNum2))%2 == 0) {\n                redo = true;\n                cout<< \"These coordinates are invalid\"<< endl;\n            }\n        }\n    }\n    return redo;\n}\n\n\n//This is the main function\nint main() {\n    \n    //Getting user to choose which game mode to play\n    cout << \"You have been unfortunately chosen by the OCDSB to mark Eddie's compass project\" << endl;\n    cout << \"\" << endl;\n    cout << \"To begin choose whether you want to play in:\" << endl;\n    cout << \"     ENTER 1 to play in BEARING mode (bearing to compass)\" << endl;\n    cout << \"     ENTER 2 to play in COMPASS mode (compass to bearing, one step)\" << endl;\n    cout << \"     ENTER 3 to play in COMPASS mode (compass to bearing, three step)\" << endl;\n    \n    \n    string gameChoice = \"3\";\n    bool correctInput = false;\n    cin >> gameChoice;\n    \n    do  {\n        //This do while loop ensures that the user has entered a value between 1 and 3\n        if ((gameChoice == \"1\") || (gameChoice == \"2\" || gameChoice == \"3\")) {\n            correctInput = true;\n        } else {\n            cout << \"You have not entered a valid input, please try again\" << endl;\n            cin >> gameChoice;\n        }\n        cout << correctInput << endl;\n    } while (correctInput == false);\n    \n    if (gameChoice == \"3\") {\n        //These are the critical variable inputs\n        string primaryCardinal = \"derp\";\n        string angleStr = \"derp\";\n        string secondaryCardinal = \"derp\";\n        \n        double angle;\n        double originalAngle = 0;\n        bool redo = false;\n        \n        do {\n            //Asks the user for necessary inputs and checks the inputs to see if they are valid\n            cout <<\"Please enter your compass direction: \" << endl;\n            cin >> primaryCardinal;\n            cout <<\"Please enter your angle: \" << endl;\n            cin >> angleStr;\n            cout <<\"Please enter your secondary direciton: \" << endl;\n            cin >> secondaryCardinal;\n            \n            redo = cardinalCheck(primaryCardinal, secondaryCardinal, angleStr);\n            \n        } while (redo == true);\n        \n        //Some necessary calculations\n        angle = stod(angleStr);\n        angle = getBearing(angle);\n        originalAngle = angle;\n        cout << angle << endl;\n        string cardinals [6] = {\"W\", \"N\", \"E\", \"S\", \"W\", \"N\"};\n        int cardinalNumSave = 0;\n        \n        //Turns the cardinals into bearing values\n        if (secondaryCardinal == cardinals[cardinalNum1]) {\n            angle = ((cardinalNum1-2)*90) + angle;\n        } else if (secondaryCardinal == cardinals[cardinalNum1-2]) {\n            angle = ((cardinalNum1-2)*90) - angle;\n        } else {\n            cout << \"Something went here calculating the bearing angle\" << endl;\n        }\n        //Makes sure the bearing values are between 0° and 359°\n        angle = getBearing(angle);\n        cout << \"Your bearing is \"<<angle<< \"°C right fron North. Your direction is:  \"<< bearingToCompass(angle, gameChoice)<< endl;\n        \n    } else if (gameChoice == \"2\") {\n        \n        cout << \"You have been unfortunately chosen by the OCDSB to mark Eddie's compass project\" << endl;\n        bool redo = false;\n        string directionStr = \"bleBLERPBLERPrp\";\n        string primaryCardinal = \"blerp\";\n        string secondaryCardinal = \"blBLERPerp\";\n        string angleStr = \"0\";\n        double angle = 0;\n        \n        \n        do {\n            //Gets input for the direction\n            cout << \"Please enter your direction in the form of N40E starting with a cardinal, bearing and secondary cardinal.\" << endl;\n            cin >> directionStr;\n            \n            //Segments this direction into cardinals and angle\n            primaryCardinal = directionStr[0];\n            secondaryCardinal = directionStr[directionStr.length()-1];\n            angleStr = directionStr.substr(1, directionStr.length()-2);\n            \n            //Checks if these are valid entries\n            redo = cardinalCheck(primaryCardinal, secondaryCardinal, angleStr);\n        } while (redo == true);\n        \n        angle = stod(angleStr);\n        angle = getBearing(angle);\n        double originalAngle = angle;\n        cout << angle << endl;\n        string cardinals [6] = {\"W\", \"N\", \"E\", \"S\", \"W\", \"N\"};\n        int cardinalNumSave = 0;\n        \n        //Converts cardinals to proper angle measures which are added to the inputted angle\n        if (secondaryCardinal == cardinals[cardinalNum1]) {\n            angle = ((cardinalNum1-2)*90) + angle;\n        } else if (secondaryCardinal == cardinals[cardinalNum1-2]) {\n            angle = ((cardinalNum1-2)*90) - angle;\n        } else {\n            cout << \"Something went here calculating the bearing angle\" << endl;\n        }\n        //Makes sure the bearing is between 0° and 359°\n        angle = getBearing(angle);\n        \n        //Outputs the bearing and a correct direction\n        cout << \"Your bearing is \"<<angle<< \"°C right fron North. Your direction is:  \"<< bearingToCompass(angle, gameChoice)<< endl;\n        \n    } else if (gameChoice == \"1\") {\n        cout << \"Please enter your bearing in degrees\"<< endl;\n        double bearing = 0;\n        string bearingStr = \"hi\";\n        \n        do {\n            //Gets user to input a bearing and checks if it is a number\n            cin >> bearingStr;\n            if (is_number(bearingStr) == 0) {\n                cout << \"You have not entered a numeric value for the bearing, please try again my friend\" << endl;\n            }\n        } while (is_number(bearingStr) == 0);\n        std::string str = \"3.14\";\n        double strVal;\n        \n        bearing = stod(bearingStr);\n        cout << bearing << endl;\n        //Converts bearing to compass direction\n        bearingToCompass(bearing, gameChoice);\n        \n        \n        //cin >> gameChoice;\n        \n        return 0;\n    }\n}\n", "meta": {"hexsha": "a21f5465fe1983a41fce8a9b9f1a8cd125431df4", "size": 11468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignment 2 - Bearings/PROJECT: BEARING/main.cpp", "max_stars_repo_name": "NyteCore/Senior_School_Projects", "max_stars_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-17T01:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-28T23:52:48.000Z", "max_issues_repo_path": "Assignment 2 - Bearings/PROJECT: BEARING/main.cpp", "max_issues_repo_name": "EdwaRen/Senior_School_Projects", "max_issues_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignment 2 - Bearings/PROJECT: BEARING/main.cpp", "max_forks_repo_name": "EdwaRen/Senior_School_Projects", "max_forks_repo_head_hexsha": "2a6e9e6bbdfaf62b8282e511bcf84fd9700ad949", "max_forks_repo_licenses": ["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.0979020979, "max_line_length": 276, "alphanum_fraction": 0.5766480642, "num_tokens": 2898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.5710637335804138}}
{"text": "// The code is open source under the MIT license.\n// Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group\n// https://ibr.cs.tu-bs.de/alg\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n// of the Software, and to permit persons to whom the Software is furnished to do\n// 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// Created by Phillip Keldenich on 11.11.19.\n//\n\n#pragma once\n\n#include \"ivarp/number.hpp\"\n#include <boost/iterator/iterator_facade.hpp>\n#include <cassert>\n\nnamespace ivarp {\n    /// Computes split intervals for a given range and a fixed number of subdivisions n.\n    /// Valid indices are [0,n).\n    template<typename IntervalType> class Splitter {\n    public:\n        using Interval = IntervalType;\n        using Number = typename Interval::NumberType;\n\n        static_assert(IsIntervalType<IntervalType>::value, \"Splitter requires an interval type to work on!\");\n\n        IVARP_SUPPRESS_HD\n        explicit IVARP_HD Splitter(const IntervalType& i, int n) :\n            m_range(i), m_n(n), m_ind_width((i.ub() - i.lb()) / n)\n        {}\n\n        IVARP_SUPPRESS_HD\n        IVARP_HD Number split_point(int i) const {\n            if(i >= m_n) {\n                return m_range.ub();\n            }\n            return m_range.lb() + i * m_ind_width;\n        }\n\n        IVARP_SUPPRESS_HD\n        IVARP_HD IntervalType subrange(int i) const {\n            return IntervalType{split_point(i), split_point(i+1)};\n        }\n\n        IVARP_HD int size() const noexcept {\n            return m_n;\n        }\n\n        class Iterator :\n            public boost::iterator_facade<Iterator, IntervalType, std::random_access_iterator_tag, IntervalType, int>\n        {\n        public:\n            Iterator() noexcept : m_splitter(nullptr), i(0) {}\n            Iterator(const Iterator&) noexcept = default;\n            Iterator &operator=(const Iterator&) noexcept = default;\n\n        private:\n            explicit Iterator(const Splitter* s, int i) :\n                m_splitter(s), i(i)\n            {}\n\n            friend class Splitter;\n            friend class boost::iterator_core_access;\n\n            IntervalType dereference() const {\n                return m_splitter->subrange(i);\n            }\n\n            void increment() noexcept {\n                ++i;\n            }\n\n            void decrement() noexcept {\n                --i;\n            }\n\n            void advance(int n) noexcept {\n                i += n;\n            }\n\n            int distance_to(const Iterator& o) const noexcept {\n                return o.i - i;\n            }\n\n            bool equal(const Iterator& o) const noexcept {\n                return i == o.i;\n            }\n\n            const Splitter* m_splitter;\n            int i;\n        };\n\n        Iterator begin() const noexcept {\n            return Iterator{this, 0};\n        }\n\n        Iterator end() const noexcept {\n            return Iterator{this, m_n};\n        }\n\n    private:\n        IntervalType m_range; ///< The outer range.\n        int m_n; ///< The number of subintervals.\n        Number m_ind_width; ///< The width of each individual subinterval.\n    };\n}\n", "meta": {"hexsha": "c2ebb660cf6ea954b56c8a31097f0de13c0373d2", "size": 4025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ivarp/include/ivarp/splitter.hpp", "max_stars_repo_name": "phillip-keldenich/squares-in-disk", "max_stars_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ivarp/include/ivarp/splitter.hpp", "max_issues_repo_name": "phillip-keldenich/squares-in-disk", "max_issues_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ivarp/include/ivarp/splitter.hpp", "max_forks_repo_name": "phillip-keldenich/squares-in-disk", "max_forks_repo_head_hexsha": "501ebeb00b909b9264a9611fd63e082026cdd262", "max_forks_repo_licenses": ["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.7235772358, "max_line_length": 117, "alphanum_fraction": 0.6114285714, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.5710637208411499}}
{"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 balanced_truncation.hpp\n///\n/// Balanced truncation method specialized for exponential sum function\n///\n#ifndef MXPFIT_BALANCED_TRUNCATION_HPP\n#define MXPFIT_BALANCED_TRUNCATION_HPP\n#include <cassert>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include <mxpfit/exponential_sum.hpp>\n#include <mxpfit/quasi_cauchy_rrd.hpp>\n#include <mxpfit/self_adjoint_coneigensolver.hpp>\n\nnamespace mxpfit\n{\n\n///\n/// ### BalancedTruncation\n///\n/// \\brief Find a truncated exponential sum function with smaller number of\n///        terms by the modified balanced truncation method.\n///\n/// \\tparam T  Scalar type of exponential sum function.\n///\n/// For a given exponential sum function,\n///\n/// \\f[\n///   f(t)=\\sum_{j=1}^{n} c_{j}^{} e^{-a_{j}^{} t}, \\quad\n///   (\\mathrm{Re}(a_{j}) > 0),\n/// \\f]\n///\n/// and prescribed accuracy \\f$\\epsilon > 0,\\f$ this class calculates truncated\n/// exponential \\f$\\hat{f}(t)\\f$ sum such that\n///\n/// \\f[\n///   \\hat{f}(t)=\\sum_{j=1}^{k} \\hat{c}_{j}^{}e^{-\\hat{a}_{j}^{} t}, \\quad\n///   \\left| f(t)-\\hat{f}(t) \\right| < \\epsilon,\n/// \\f]\n///\n/// where \\f$k \\leq n.\\f$ Let \\f$F(s)\\f$ and \\f$\\hat{F}(s)\\f$ be the Laplace\n/// transform of \\f$f(t)\\f$ and \\f$\\hat{f}(t),\\f$ respectively. \\f$F(s)\\f$ can\n/// be evaluated analytically as\n///\n/// \\f[\n///  F(s)=\\sum_{j=1}^{n}\\frac{c_{j}^{}}{s+a_{j}^{}}\n/// \\f]\n///\n/// and similar to \\f$\\hat{F}(s).\\f$ Now, the problem can be rewritten as\n/// finding optimal rational sum approximation \\f$\\hat{F}(s)\\f$ such that \\f$\n/// \\left|F(s)-\\hat{F}(s)\\right| < \\epsilon.\\f$\n///\n/// This class computes the truncated rational sum approximation\n/// \\f$\\hat{F}(s)\\f$ by the modified balanced truncation method combined with\n/// the first and accurate con-eigensolver of a quasi-Cauchy matrix.\n///\n///\n/// #### References\n///\n/// 1. K. Xu and S. Jiang, \"A Bootstrap Method for Sum-of-Poles Approximations\",\n///    J. Sci. Comput. **55** (2013) 16-39.\n///    [DOI: https://doi.org/10.1007/s10915-012-9620-9]\n/// 2. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n///    FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n///    (2012) 1101-1125.\n///    [DOI: https://doi.org/10.1137/110821901]\n/// 3. W. H. A. Schilders, H. A. van der Vorst, and J. Rommes, \"Model Order\n///    Reduction: Theory, Research Aspects and Applications\", Springer (2008).\n///    [DOI: https://doi.org/10.1007/978-3-540-78841-6]\n///\n\ntemplate <typename T>\nclass BalancedTruncation\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 VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using ResultType = ExponentialSum<Scalar>;\n\n    ///\n    /// Compute truncated exponential sum \\f$ \\hat{f}(t) \\f$\n    ///\n    /// \\tparam DerivedF type of exponential sum inheriting ExponentialSumBase\n    ///\n    /// \\param[in] orig original exponential sum function, \\f$ f(t) \\f$\n    /// \\param[in] threshold  prescribed accuracy \\f$0 < \\epsilon \\ll 1\\f$\n    ///\n    /// \\return An instance of ExponentialSum represents \\f$\\hat{f}(t)\\f$\n    ///\n    template <typename DerivedF>\n    ResultType compute(const ExponentialSumBase<DerivedF>& orig,\n                       RealScalar threshold);\n\nprivate:\n    enum\n    {\n        IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n    };\n\n    using EigenSolverType = typename Eigen::internal::conditional<\n        IsComplex, Eigen::ComplexEigenSolver<MatrixType>,\n        Eigen::SelfAdjointEigenSolver<MatrixType>>::type;\n    using ConeigenSolverType = SelfAdjointConeigenSolver<Scalar>;\n};\n\ntemplate <typename T>\ntemplate <typename DerivedF>\ntypename BalancedTruncation<T>::ResultType\nBalancedTruncation<T>::compute(const ExponentialSumBase<DerivedF>& fn,\n                               RealScalar threshold)\n{\n    //--------------------------------------------------------------------------\n    //\n    // The controllability Gramian matrix of the system is defined as\n    //\n    //   C(i, j) = sqrt(w[i] * conj(w[j])) / (p[i] + p[j]).\n    //\n    // C is a quasi-Cauchy matrix. Then compute partial Cholesky factorization\n    // of matrix `C`\n    //\n    //   C = (P * L) * D^2 * (P * L)^H,\n    //\n    // where\n    //\n    //   - L: (n, m) matrix\n    //   - D: (m, m) real diagonal matrix\n    //   - P: (n, n) permutation matrix\n    //\n    // and `m = rank(C)`\n    //\n    //--------------------------------------------------------------------------\n    static const RealScalar eps = Eigen::NumTraits<RealScalar>::epsilon();\n\n    const Index n0 = fn.size();\n    VectorType b(n0);\n    b.array() = fn.weights().sqrt();\n\n    const RealScalar rrd_threshold = threshold * eps * eps;\n    SelfAdjointQuasiCauchyRRD<T> rrd;\n    rrd.setThreshold(rrd_threshold);\n    rrd.compute(b, fn.exponents());\n\n    if (rrd.rank() == Index(0))\n    {\n        return ResultType();\n    }\n\n    //--------------------------------------------------------------------------\n    //\n    // Compute con-eigendecomposition of the controllability Gramian matrix\n    //\n    //   C = X D^2 X^H = U^C S U^T,\n    //\n    // where\n    //\n    //   - `X = P * L`: Cholesky factor (n, k)\n    //   - `S`: (k, k) diagonal matrix. Diagonal elements `S(i,i)` are\n    //          con-eigenvalues sorted in decreasing order.\n    //   - `U`: (n, k) matrix. k-th column hold a con-eigenvector corresponding\n    //          to k-th con-eigenvalue. The columns of `U` are orthogonal in the\n    //          sense that `U^T * U = I`.\n    //\n    //---------------------------------------------------------------------------\n    //\n    // `diag` is overwritten by con-eigenvalues, and first k column of `matX` is\n    // overwritten by con-eigenvectors `U`\n    //\n    ConeigenSolverType ceig;\n    ceig.compute(rrd.matrixPL(), rrd.vectorD());\n    //--------------------------------------------------------------------------\n    //\n    // Truncation\n    //\n    // Determines the order of reduced system, \\f$ k \\f$ from the error bound\n    // computed from the Hankel singular values system. The Hankel singular\n    // values are coincide with con-eigenvalues of the Gramian matrix.\n    //\n    // \\f[\n    //   \\|\\Sigma-\\hat{\\Sigma}\\| \\leq 2 \\sum_{i=k+1}^{n} \\sigma_{i}\n    // \\f]\n    //\n    //--------------------------------------------------------------------------\n    auto sum_sigma       = RealScalar();\n    const auto& sigma    = ceig.coneigenvalues();\n    const auto sigma_tol = threshold * sigma(0);\n    Index n1             = sigma.size();\n    while (n1)\n    {\n        sum_sigma += sigma(n1 - 1);\n        if (2 * sum_sigma > sigma_tol)\n        {\n            break;\n        }\n        --n1;\n    }\n\n    if (n1 == Index())\n    {\n        return ResultType();\n    }\n\n    //--------------------------------------------------------------------------\n    //\n    // Apply transformation matrix\n    //\n    //  A1 = U.adjoint() * S * U.conjugate()\n    //  b1 = U.adjoint() * b\n    //\n    //--------------------------------------------------------------------------\n\n    MatrixType A1(n1, n1);\n    VectorType b1(n1);\n    auto U = ceig.coneigenvectors().leftCols(n1);\n    A1.noalias() =\n        U.adjoint() * fn.exponents().matrix().asDiagonal() * U.conjugate();\n    b1.noalias() = U.adjoint() * b;\n\n    //--------------------------------------------------------------------------\n    //\n    // Compute eigenvalue decomposition of the (k x k) matrix, A1. Since A1\n    // real/complex symmetric matrix, the eigen decomposition has the form\n    //\n    //   A1 = X2 * D * X2.transpose(), (X2.transpose() * X2 = I).\n    //\n    //--------------------------------------------------------------------------\n    EigenSolverType eig(A1, Eigen::ComputeEigenvectors);\n\n    if (IsComplex)\n    {\n        //\n        // Enforce X2.transpose() * X2 = I\n        //\n        using EigenVectorsType = typename Eigen::internal::remove_all<decltype(\n            eig.eigenvectors())>::type;\n        auto& X2 = *const_cast<EigenVectorsType*>(&eig.eigenvectors());\n        for (Index j = 0; j < X2.cols(); ++j)\n        {\n            auto xj          = X2.col(j);\n            const auto t     = (xj.transpose() * xj).value();\n            const auto scale = RealScalar(1) / std::sqrt(t);\n            xj *= scale;\n        }\n    }\n\n    //\n    // Apply the state space transformation by X2,\n    //\n    // A2 = X2.transpose() * A1 * X2 = D\n    // b2 = X2.transpose() * b1\n    // c2 = b1 * X2 = b2.transpose()\n    //\n    // Finally parameters for truncated exponential sum can be obtained as\n    //\n    // p' = D.diagonal()\n    // w' = c2 * b2 = square(b2)\n    //\n    auto b2      = b.head(n1);\n    b2.noalias() = eig.eigenvectors().transpose() * b1;\n    return ResultType(eig.eigenvalues(), b2.array().square());\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_BALANCED_TRUNCATION_HPP */\n", "meta": {"hexsha": "f7a70450231850feb0e12072a075e6527e22cfeb", "size": 10089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/balanced_truncation.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/balanced_truncation.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/balanced_truncation.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": 34.0844594595, "max_line_length": 81, "alphanum_fraction": 0.5598176232, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5710419739120148}}
{"text": "/**\n * @file MPCExample.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the BSD 3-Clause License\n * @date 2018\n */\n\n\n// osqp-eigen\n#include \"OsqpEigen/OsqpEigen.h\"\n\n// eigen\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <fstream>\n\nvoid setDynamicsMatrices(Eigen::Matrix<double, 2, 2> &a, Eigen::Matrix<double, 2, 1> &b)\n{\n    a << 1.,      0.020,\n        0.,      0.9661;\n\n    b << 0.,\n        0.0315;\n}\n\n\nvoid setInequalityConstraints(Eigen::Matrix<double, 2, 1> &xMax, Eigen::Matrix<double, 2, 1> &xMin,\n                              Eigen::Matrix<double, 1, 1> &uMax, Eigen::Matrix<double, 1, 1> &uMin)\n{\n    double u0 = 0.0;\n\n    // input inequality constraints\n    uMin << -6.0 - u0;\n\n    uMax << 10.0 - u0;\n\n    // state inequality constraints\n    // TODO : change to present pos +/- ranges\n    xMin << -100, -6.0;\n\n    xMax << 100, 10.0;\n}\n\nvoid setWeightMatrices(Eigen::DiagonalMatrix<double, 2> &Q, Eigen::DiagonalMatrix<double, 1> &R)\n{\n    Q.diagonal() << 2, 0;\n    R.diagonal() << 0.2;\n}\n\nvoid castMPCToQPHessian(const Eigen::DiagonalMatrix<double, 2> &Q, const Eigen::DiagonalMatrix<double, 1> &R, int mpcWindow,\n                        Eigen::SparseMatrix<double> &hessianMatrix, int Nx, int Nu)\n{\n\n    hessianMatrix.resize(Nx*(mpcWindow+1) + Nu * mpcWindow, Nx*(mpcWindow+1) + Nu * mpcWindow);\n\n    //populate hessian matrix\n    for(int i = 0; i<Nx*(mpcWindow+1) + Nu * mpcWindow; i++){\n        if(i < Nx*(mpcWindow+1)){\n            int posQ=i%Nx;\n            float value = Q.diagonal()[posQ];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n        else{\n            int posR=i%Nu;\n            float value = R.diagonal()[posR];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n    }\n}\n\nvoid castMPCToQPGradient(const Eigen::DiagonalMatrix<double, 2> &Q, const Eigen::Matrix<double, 2, 1> &xRef, int mpcWindow,\n                         Eigen::VectorXd &gradient, int Nx, int Nu)\n{\n\n    Eigen::Matrix<double,2,1> Qx_ref;\n    Qx_ref = Q * (-xRef);\n\n    // populate the gradient vector\n    gradient = Eigen::VectorXd::Zero(Nx*(mpcWindow+1) +  Nu*mpcWindow, 1);\n    for(int i = 0; i<Nx*(mpcWindow+1); i++){\n        int posQ=i%Nx;\n        float value = Qx_ref(posQ,0);\n        gradient(i,0) = value;\n    }\n}\n\nvoid castMPCToQPConstraintMatrix(const Eigen::Matrix<double, 2, 2> &dynamicMatrix, const Eigen::Matrix<double, 2, 1> &controlMatrix,\n                                 int mpcWindow, Eigen::SparseMatrix<double> &constraintMatrix, int Nx, int Nu)\n{\n    constraintMatrix.resize(Nx*(mpcWindow+1)  + Nx*(mpcWindow+1) + Nu * mpcWindow, Nx*(mpcWindow+1) + Nu * mpcWindow);\n\n    // populate linear constraint matrix\n    for(int i = 0; i<Nx*(mpcWindow+1); i++){\n        constraintMatrix.insert(i,i) = -1;\n    }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j<Nx; j++)\n            for(int k = 0; k<Nx; k++){\n                float value = dynamicMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(Nx * (i+1) + j, Nx * i + k) = value;\n                }\n            }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j < Nx; j++)\n            for(int k = 0; k < Nu; k++){\n                float value = controlMatrix(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(Nx*(i+1)+j, Nu*i+k+Nx*(mpcWindow + 1)) = value;\n                }\n            }\n\n    for(int i = 0; i<Nx*(mpcWindow+1) + Nu*mpcWindow; i++){\n        constraintMatrix.insert(i+(mpcWindow+1)*Nx,i) = 1;\n    }\n}\n\nvoid castMPCToQPConstraintVectors(const Eigen::Matrix<double, 2, 1> &xMax, const Eigen::Matrix<double, 2, 1> &xMin,\n                                   const Eigen::Matrix<double, 1, 1> &uMax, const Eigen::Matrix<double, 1, 1> &uMin,\n                                   const Eigen::Matrix<double, 2, 1> &x0,\n                                   int mpcWindow, Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound, int Nx, int Nu)\n{\n    // evaluate the lower and the upper inequality vectors\n    Eigen::VectorXd lowerInequality = Eigen::MatrixXd::Zero(Nx*(mpcWindow+1) +  Nu * mpcWindow, 1);\n    Eigen::VectorXd upperInequality = Eigen::MatrixXd::Zero(Nx*(mpcWindow+1) +  Nu * mpcWindow, 1);\n    for(int i=0; i<mpcWindow+1; i++){\n        lowerInequality.block(Nx*i,0,Nx,1) = xMin;\n        upperInequality.block(Nx*i,0,Nx,1) = xMax;\n    }\n    for(int i=0; i<mpcWindow; i++){\n        lowerInequality.block(Nu * i + Nx * (mpcWindow + 1), 0, Nu, 1) = uMin;\n        upperInequality.block(Nu * i + Nx * (mpcWindow + 1), 0, Nu, 1) = uMax;\n    }\n\n    // evaluate the lower and the upper equality vectors\n    Eigen::VectorXd lowerEquality = Eigen::MatrixXd::Zero(Nx*(mpcWindow+1),1 );\n    Eigen::VectorXd upperEquality;\n    lowerEquality.block(0,0,Nx,1) = -x0;\n    upperEquality = lowerEquality;\n    lowerEquality = lowerEquality;\n\n    // merge inequality and equality vectors\n    lowerBound = Eigen::MatrixXd::Zero(2*Nx*(mpcWindow+1) +  Nu*mpcWindow,1 );\n    lowerBound << lowerEquality,\n        lowerInequality;\n\n    upperBound = Eigen::MatrixXd::Zero(2*Nx*(mpcWindow+1) +  Nu*mpcWindow,1 );\n    upperBound << upperEquality,\n        upperInequality;\n}\n\n\nvoid updateConstraintVectors(const Eigen::Matrix<double, 2, 1> &x0,\n                             Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound, int Nx)\n{\n    lowerBound.block(0,0,Nx,1) = -x0;\n    upperBound.block(0,0,Nx,1) = -x0;\n}\n\n\ndouble getErrorNorm(const Eigen::Matrix<double, 2, 1> &x,\n                    const Eigen::Matrix<double, 2, 1> &xRef, int Nx)\n{\n    // evaluate the error\n    Eigen::Matrix<double, 2, 1> error = x - xRef;\n\n    // return the norm\n    return error.norm();\n}\n\n\nint main()\n{\n    // set the preview window\n    int mpcWindow = 200;\n    const int Nx = 2;\n    const int Nu = 1;\n\n    // allocate the dynamics matrices\n    Eigen::Matrix<double, Nx, Nx> a;\n    Eigen::Matrix<double, Nx, Nu> b;\n\n    // allocate the constraints vector\n    Eigen::Matrix<double, Nx, 1> xMax;\n    Eigen::Matrix<double, Nx, 1> xMin;\n    Eigen::Matrix<double, Nu, 1> uMax;\n    Eigen::Matrix<double, Nu, 1> uMin;\n\n    // allocate the weight matrices\n    Eigen::DiagonalMatrix<double, Nx> Q;\n    Eigen::DiagonalMatrix<double, Nu> R;\n\n    // allocate the initial and the reference state space\n    Eigen::Matrix<double, Nx, 1> x0;\n    Eigen::Matrix<double, Nx, 1> xRef;\n\n    // allocate QP problem matrices and vectores\n    Eigen::SparseMatrix<double> hessian;\n    Eigen::VectorXd gradient;\n    Eigen::SparseMatrix<double> linearMatrix;\n    Eigen::VectorXd lowerBound;\n    Eigen::VectorXd upperBound;\n\n    // set the initial and the desired states\n    x0 << 0, 0 ;\n    xRef <<  1/0.127, 0;\n\n    // set MPC problem quantities\n    setDynamicsMatrices(a, b);\n    setInequalityConstraints(xMax, xMin, uMax, uMin);\n    setWeightMatrices(Q, R);\n\n    // cast the MPC problem as QP problem\n    castMPCToQPHessian(Q, R, mpcWindow, hessian, Nx, Nu);\n    castMPCToQPGradient(Q, xRef, mpcWindow, gradient, Nx, Nu);\n    castMPCToQPConstraintMatrix(a, b, mpcWindow, linearMatrix, Nx, Nu);\n    castMPCToQPConstraintVectors(xMax, xMin, uMax, uMin, x0, mpcWindow, lowerBound, upperBound, Nx, Nu);\n\n    // instantiate the solver\n    OsqpEigen::Solver solver;\n\n    // settings\n    //solver.settings()->setVerbosity(false);\n    solver.settings()->setWarmStart(true);\n\n    // set the initial data of the QP solver\n    solver.data()->setNumberOfVariables(Nx * (mpcWindow + 1) + Nu * mpcWindow);\n    solver.data()->setNumberOfConstraints(2 * Nx * (mpcWindow + 1) + Nu * mpcWindow);\n    if(!solver.data()->setHessianMatrix(hessian)) return 1;\n    if(!solver.data()->setGradient(gradient)) return 1;\n    if(!solver.data()->setLinearConstraintsMatrix(linearMatrix)) return 1;\n    if(!solver.data()->setLowerBound(lowerBound)) return 1;\n    if(!solver.data()->setUpperBound(upperBound)) return 1;\n\n    // instantiate the solver\n    if(!solver.initSolver()) return 1;\n\n    // controller input and QPSolution vector\n    Eigen::VectorXd ctr;\n    Eigen::VectorXd QPSolution;\n\n    // number of iteration steps\n    int numberOfSteps = 200;\n\n    std::ofstream myfile;\n    myfile.open (\"mpc_log.csv\");\n    myfile << \"Log of MPC by osqp in C++.\\n\";\n    myfile << \"x1,x2,\\n\";\n\n    for (int i = 0; i < numberOfSteps; i++){\n\n        // solve the QP problem\n        if(solver.solveProblem() != OsqpEigen::ErrorExitFlag::NoError) return 1;\n\n        // get the controller input\n        QPSolution = solver.getSolution();\n        ctr = QPSolution.block(Nx * (mpcWindow + 1), 0, Nu, 1);\n\n        // save data into file\n        auto x0Data = x0.data();\n\n        // propagate the model\n        x0 = a * x0 + b * ctr;\n        myfile << x0[0] << \",\" << x0[1] <<\",\\n\";\n\n\n        // update the constraint bound\n        updateConstraintVectors(x0, lowerBound, upperBound, Nx);\n        if(!solver.updateBounds(lowerBound, upperBound)) return 1;\n      }\n    myfile.close();\n    return 0;\n}\n", "meta": {"hexsha": "8cb804718b884b379a4cb247017e96af20706e24", "size": 8983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/src/MPCExampleFlaptterParam.cpp", "max_stars_repo_name": "marunmurali/osqp-eigen", "max_stars_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/src/MPCExampleFlaptterParam.cpp", "max_issues_repo_name": "marunmurali/osqp-eigen", "max_issues_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/src/MPCExampleFlaptterParam.cpp", "max_forks_repo_name": "marunmurali/osqp-eigen", "max_forks_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_forks_repo_licenses": ["BSD-3-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.1971326165, "max_line_length": 132, "alphanum_fraction": 0.5957920517, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.5710419718859693}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include \"datatypes.hpp\"\n#include <Eigen/Eigen>\n#include \"profile.hpp\"\n#include \"integration.hpp\"\n#include \"transformation.hpp\"\n\nnamespace gd {\n\nusing namespace std;\nUSING_PART_OF_NAMESPACE_EIGEN\n\nclass Grid1d {\npublic:\n\tvirtual int findindex(double) { return 0; }\n\tvirtual double indexto_x(int) { return 0; }\n\t//virtual void indexto_x(int) { return 0; }\n\tvirtual bool inrange(double) { return false; }\n\tvirtual int length() {return 0;}\n};\n\ntemplate<class Base=Grid1d>\nclass Grid1dRegular : public Base {\npublic:\n\tGrid1dRegular(double x1, double x2, int gridpoints) : x1(x1), x2(x2), _gridpoints(gridpoints) {}\n\tint findindex(double x) {\n\t\treturn x < x1 ? 0 :\n\t\t\t(x >= x2 ? _gridpoints-1 : (int)((x-x1)/(x2-x1)*(_gridpoints-1)));\n\t}\n\tdouble indexto_x(int i) {\n\t\treturn x1 + (x2-x1)/(length()-1)*i;\n\t}\n\tbool inrange(double r) {\n\t\treturn (r >= x1) && (r < x2); \n\t}\n\tint length() { return _gridpoints; }\n\tdouble x1, x2;\n\tint _gridpoints;\n};\n\n/*class Grid2d {\npublic:\n\tvirtual int findindex(double, double) { return 0; }\n\tvirtual bool inrange(double, double) { return false; }\n\tvirtual int length() {return 0;}\n};*/\n\ntemplate<class GridX=Grid1d, class GridY=Grid1d>\nclass Grid2d {\npublic:\n\ttypedef GridX GridXType;\n\ttypedef GridY GridYType;\n\tGrid2d(GridX* gridx, GridY* gridy) : gridx(gridx), gridy(gridy) {}\n\tvoid findindex2d(double x, double y, int& xi, int &yi) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI); \n\t\txi = gridx->findindex(x);\n\t\tyi = gridy->findindex(y);\n\t} \n\tint findindex(double x, double y) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI); \n\t\treturn gridx->findindex(x) * gridy->length() + gridy->findindex(y);;\n\t} \n\tvoid indexto_xy(int i, int j, double &x, double &y) {\n\t\tx = gridx->indexto_x(i);\n\t\ty = gridy->indexto_x(j);\n\t}\n\tbool inrange(double x, double y) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI);\n\t\treturn gridx->inrange(x) && gridy->inrange(y);\n\t}\n\tint length() {\n\t\treturn gridx->length() * gridy->length();\n\t}\n\tGridX* gridx;\n\tGridY* gridy;\n};\n\ntemplate<class GridX=Grid1d, class GridY=Grid1d, class GridZ=Grid1d>\nclass Grid3d {\npublic:\n\ttypedef GridX GridXType;\n\ttypedef GridY GridYType;\n\ttypedef GridZ GridZType;\n\tGrid3d(GridX* gridx, GridY* gridy, GridZ* gridz) : gridx(gridx), gridy(gridy), gridz(gridz) {}\n\tvoid findindex3d(double x, double y, double z, int& xi, int &yi, int &zi) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI); \n\t\txi = gridx->findindex(x);\n\t\tyi = gridy->findindex(y);\n\t\tzi = gridz->findindex(z);\n\t} \n\tint findindex(double x, double y, double z) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI); \n\t\treturn (gridx->findindex(x) * gridy->length() + gridy->findindex(y)) * gridz->length() + gridz->findindex(z);\n\t} \n\tvoid indexto_xyz(int i, int j, int k, double &x, double &y, double &z) {\n\t\tx = gridx->indexto_x(i);\n\t\ty = gridy->indexto_x(j);\n\t\tz = gridz->indexto_x(k);\n\t}\n\tbool inrange(double x, double y, double z) {\n\t\t//double r = sqrt(x*x+y*y);\n\t\t//double phi = fmod(atan2(y,x)+2*M_PI, 2*M_PI);\n\t\treturn gridx->inrange(x) && gridy->inrange(y) && gridz->inrange(z);\n\t}\n\tint length() {\n\t\treturn gridx->length() * gridy->length() * gridz->length();\n\t}\n\tGridX* gridx;\n\tGridY* gridy;\n\tGridZ* gridz;\n};\n\n/*\n\t\tbasis_evaluator<2, Basis::degree, Basis> basis_evaluator;\n\t\tif(mesh.inrange(x))\n\t\t\tvalue = basis_evaluator.eval(solution, this, xi, u, yi, v);\n*/\n\ntemplate<int DIM, class B, int I=B::degree, class BI=B, class T=double>\nstruct basis_evaluator;\n\ntemplate<int DIM, class B, int I, class BI, class T>\nstruct basis_evaluator\n{\n\ttypedef basis_evaluator<DIM, B, I-1, typename BI::next_type, T> next_typeI;\n\ttypedef basis_evaluator<DIM-1, B, B::degree, B, T> next_typeDIM;\n\tnext_typeI nextI;\n\tnext_typeDIM nextDIM;\n\n\ttemplate<class... Ts>\n\tT eval(int i, double u, Ts... ts) {\n\t\tif((i % (B::degree+1)) == I) { // first search for right i\n\t\t\tBI basis;\n\t\t\treturn basis(u) * nextDIM.eval(i/(B::degree+1), ts...);\n\t\t} else {\n\t\t\treturn nextI.eval(i, u, ts...); \n\t\t}\n\t}\n};\n\ntemplate<int DIM, class B,  class BI, class T>\nstruct basis_evaluator<DIM, B, -1, BI, T>\n{\n\ttemplate<class... Ts>\n\tT eval(int, double, Ts...) {\n\t\treturn 1;\n\t}\n};\n\ntemplate<class B, int I, class BI, class T>\nstruct basis_evaluator<0, B, I, BI, T>\n{\n\tT eval(int) {\n\t\treturn 1;\n\t}\n};\n\n\ntemplate<int DIM, int I, class B, class BI, class T>\nstruct basis_function_integrator;\n\n//template<int DIM, int I, class B, class BI, class T>\n//struct basis_function_integrator<2,I,B,BI,T>\ntemplate<int DIM, int I, class B, class BI, class T>\nstruct basis_function_integrator\n{\n\ttypedef basis_function_integrator<DIM,   I-1, B, typename BI::next_type, T> next_typeI;\n\ttypedef basis_function_integrator<DIM-1, B::degree, B, B, T> next_typeDIM;\n\tT x1, x2;\n\tnext_typeI nextI;\n\tnext_typeDIM nextDIM;\n\n\ttemplate<class... Ts>\n\tbasis_function_integrator(T x1, T x2, Ts... ts) : x1(x1), x2(x2), nextI(x1, x2, ts...), nextDIM(ts...) {\n\t\t//cout << \"DIM \" << DIM << \" \" << x1 << \" \" << x2 << endl;\n\t} \n\t\n\ttemplate<class F>\n\tT integrate_function2d(F f, int i) {\n\t\tif((i % (B::degree+1)) == I) { // first search for right i\n\t\t\tBI basis;\n\t\t\tdouble dx = (x2-x1);\n\t\t\tauto fi = [&](double x) -> double { return basis((x-this->x1)/dx) / dx  * this->nextDIM.integrate_function2d_y(f, i / (B::degree+1), x); };\n\t\t\tIntegratorGSL<> integratorGSL(fi);\n\t\t\t//cout << \"integrate: \" << x1 << \" to \" << x2 << endl;\n\t\t\treturn integratorGSL.integrate(x1, x2);\n\t\t} else {\n\t\t\treturn nextI.integrate_function2d(f, i);\n\t\t}\n\t}\n\ttemplate<class F>\n\tT integrate_function2d_y(F f, int i, double x) {\n\t\tif((i % (B::degree+1)) == I) { // first search for right i\n\t\t\tBI basis;\n\t\t\tdouble dx = (x2-x1);\n\t\t\tauto fi = [&](double y) -> double { return basis((y-this->x1)/dx)/dx * f(x, y); };\n\t\t\tIntegratorGSL<> integratorGSL(fi);\n\t\t\t//cout << \"integrate: \" << x1 << \" to \" << x2 << endl;\n\t\t\treturn integratorGSL.integrate(x1, x2);\n\t\t} else {\n\t\t\treturn nextI.integrate_function2d_y(f, i, x);\n\t\t}\n\t}\n};\n\ntemplate<int DIM, class B, class BI, class T>\nstruct basis_function_integrator<DIM, -1, B, BI, T>\n{\n\ttemplate<class... Ts>\n\tbasis_function_integrator(T, T, Ts...) {} \n\ttemplate<class F>\n\tT integrate_function2d(F, int) { return 1; }\n\ttemplate<class F>\n\tT integrate_function2d_y(F, int, double) { return 1; }\n};\n\ntemplate<int I, class B, class BI, class T>\nstruct basis_function_integrator<0, I, B, BI, T>\n{\n\ttemplate<class F>\n\tT integrate_function(F, int) { return 1; }\n};\n\n\ntemplate<int DIM, int I, int J, class B, class BI, class BJ, class T=double>\nstruct basis_integrator;\n\ntemplate<int DIM, int I, int J, class B, class BI, class BJ, class T>\nstruct basis_integrator\n{\n\ttypedef basis_integrator<DIM, I-1, J, B, typename BI::next_type, BJ, T> next_typeI;\n\ttypedef basis_integrator<DIM, I, J-1, B, BI, typename BJ::next_type, T> next_typeJ;\n\ttypedef basis_integrator<DIM-1, B::degree, B::degree, B, B, B, T> next_typeDIM;\n\tnext_typeI nextI;\n\tnext_typeJ nextJ;\n\tnext_typeDIM nextDIM;\n\n\n\t//template<class... Ts>\n\tT integrate(int i, int j) {\n\t\tif((i % (B::degree+1)) == I) { // first search for right i\n\t\t\tif((j  % (B::degree+1)) == J) { // then right j\n\t\t\t\tBI basis1;\n\t\t\t\tBJ basis2;\n\t\t\t\tauto f = [&](double x) ->double { return basis1(x) * basis2(x) * this->nextDIM.integrate(i / (B::degree+1), j / (B::degree+1)); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f);\n\t\t\t\treturn integratorGSL.integrate(0, 1);\n\t\t\t}  else {\n\t\t\t\treturn nextJ.integrate(i, j);\n\t\t\t}\n\t\t} else {\n\t\t\treturn nextI.integrate(i, j);\n\t\t}\n\t}\n};\n\n// sentinels\ntemplate<int I, int J, class B, class BI, class BJ, class T>\nstruct basis_integrator<0, I, J, B, BI, BJ, T>\n{\n\ttemplate<class... Ts>\n\tT integrate(int, int) {\n\t\treturn 1;\n\t}\n};\n\ntemplate<int DIM, int J, class B, class BI, class BJ, class T>\nstruct basis_integrator<DIM, -1, J, B, BI, BJ, T>\n{\n\ttemplate<class... Ts>\n\tT integrate(int, int) {\n\t\treturn 1;\n\t}\n};\n\ntemplate<int DIM, int I, class B, class BI, class BJ, class T>\nstruct basis_integrator<DIM, I, -1, B, BI, BJ, T>\n{\n\ttemplate<class... Ts>\n\tT integrate(int, int) {\n\t\treturn 1;\n\t}\n};\n\n\n\n\ntemplate<int DIM, class Basis, class T=double>\nstruct MeshRegularNodalHelper;\n\ntemplate<class Basis, class T>\nstruct MeshRegularNodalHelper<0, Basis, T> {\n\ttypedef Basis basis_type;\n\tenum { dof_per_cell = 1 };\n};\n\n\ntemplate<int DIM, class Basis, class T>\nstruct MeshRegularNodalHelper {\n\ttypedef Basis basis_type;\n\ttypedef MeshRegularNodalHelper<DIM, Basis, T> type;\n\ttypedef MeshRegularNodalHelper<DIM-1, Basis, T> sub_type;\n\tenum { dof_per_cell = (Basis::degree+1) * sub_type::dof_per_cell };\n\n\t/*int get_dof() { return dof;}\n\tint get_n_cells() { return n_cells;}\n\tint dof_index(int cell_index, int local_index) {\n\t\treturn  cell_index*(dof_per_cell-1)+local_index;\n\t}*/\n};\n\n\n\n\n\ntemplate<int DIM, class Basis, class T=double>\nclass MeshRegularNodal;\n\ntemplate<class Basis, class T>\nclass MeshRegularNodal<2, Basis, T> {\npublic:\n\ttypedef Basis basis_type;\n\tT x1, x2;\n\tint n_cells_x;\n\tint n_cells_y;\n\tGrid1dRegular<> xgrid;\n\tGrid1dRegular<> ygrid;\n\tGrid2d<Grid1dRegular<>, Grid1dRegular<>> grid;\n\tMatrixXd M;\n\t//Transformation1d_in_3d* transformation;\n\tint dof, dofx, dofy;\n\tint dof1d;\n\tenum { dof_per_cell = MeshRegularNodalHelper<2, Basis, T>::dof_per_cell };\n\tenum { dof_per_cell1d = MeshRegularNodalHelper<1, Basis, T>::dof_per_cell };\n\n\tMeshRegularNodal(T x1, T y1, T x2, T y2, int n_cells_x, int n_cells_y) : n_cells_x(n_cells_x), n_cells_y(n_cells_y), xgrid(x1, x2, n_cells_x+1), ygrid(y1, y2, n_cells_y+1), grid(&xgrid, &ygrid), M(1, 1) {\n\t\t\n\t\tif(Basis::degree == 0) {\n\t\t\tdofx = n_cells_x;\n\t\t\tdofy = n_cells_y;\n\t\t} else {\n\t\t\tdofx = (1 + n_cells_x) + (dof_per_cell1d-2)*n_cells_x; // 1 dof per border + dofs inside the cel\n\t\t\tdofy = (1 + n_cells_y) + (dof_per_cell1d-2)*n_cells_y; // 1 dof per border + dofs inside the cel\n\t\t}\n\t\tdof = dofx * dofy;\n\t\t//cout << \"n_cells_x = \" << n_cells_x << \" dofx = \" << dofx << endl; \n\t\t//cout << \"n_cells_y = \" << n_cells_y << \" dofy = \" << dofy << endl; \n\t\t//cout << \"dof = \" << dof << \" dof_per_cell = \" << dof_per_cell << endl;\n\t\t//MatrixXd m = MatrixXd::Zero(dof, dof);\n\t\tM.resize(dof, dof);\n\t\tM =  MatrixXd::Zero(dof, dof);\n\t\t//T scale = 1; //TODO: (x2-x1)/n_cells;\n\n\t\t//basis_integrator<1, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t\t//cout  << \"test 00 \" << bi.integrate(0, 0) << endl;\n\t\t//cout  << \"test 01 \" << bi.integrate(0, 1) << endl;\n\t\t//cout  << \"test 11 \" << bi.integrate(1, 1) << endl;\n\n\t\tT integrals[dof_per_cell][dof_per_cell];\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < (j+1); k++) {\n\t\t\t\tbasis_integrator<2, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t\t\t\tT integral = bi.integrate(j, k);\n\t\t\t\t//typedef selfintegrator<Basis::degree, Basis::degree> selfintegrator_type;\n\t\t\t\t//selfintegrator_type si; \n\t\t\t\t//double integral = si.integrate(j,k);\n\t\t\t\t//cout << j << \" \" << k << \" \" << integral << endl;\n\t\t\t\tintegrals[j][k] = integral;\n\t\t\t\tintegrals[k][j] = integral;\n\t\t\t}\n\t\t}\n\t\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\t\tfor(int yi = 0; yi < n_cells_y; yi++) {\n\t\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\tint i1 = this->dof_index(xi, yi, j);\n\t\t\t\t\tint i2 = this->dof_index(xi, yi, k);\n\t\t\t\t\t//cout << \"xi = \" << xi << \" yi = \" << yi << \" j = \" << j << \" k = \" << k;\n\t\t\t\t\t//cout << \"            i1 = \" << i1 << \" i2 = \" << i2 << endl;\n\t\t\t\t\tM(i1, i2) += integrals[j][k];\n\t\t\t\t}}\n\t\t\t}\n\t\t}\n\t\t/*for(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\tint i1 = i*(dof_per_cell-1)+j;\n\t\t\t\t\tint i2 = i*(dof_per_cell-1)+k;\n\t\t\t\t\tm(i1, i2) = m(i1, i2) + integrals[j][k];\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\t\t//cout << M << endl;\n\t\t//m = m * scale;\n\t\t//ctrans = m.inverse();\n\t}\n\n\tdouble eval_(double_vector solution_, double x, double y) {\n\t\tVectorXd solution = VectorXd::Map(solution_.data().begin(), solution_.size());\n\t\treturn eval(solution, x, y);\n\t}\n\n\tdouble eval(VectorXd& solution, double x, double y) {\n\t\t/*int cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\t*/\n\t\tint xi = xgrid.findindex(x);\n\t\tint yi = ygrid.findindex(y);\n\t\tT x1 = xgrid.indexto_x(xi);\n\t\tT x2 = xgrid.indexto_x(xi+1);\n\t\tT y1 = ygrid.indexto_x(yi);\n\t\tT y2 = ygrid.indexto_x(yi+1);\n\t\tdouble u = (x-x1)/(x2-x1);\n\t\tdouble v = (y-y1)/(y2-y1);\n\t\t//grid.index\n\t\t//T dx = xright-xleft;\n\t\tdouble value = 0;\n\t\t//cout << \"xi = \" << xi;\n\t\t//cout << \" yi = \" << yi;\n\t\tif(grid.inrange(x, y)) {\n\t\t\tbasis_evaluator<2, Basis> basis_evaluator;\n\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\t//cout << \" i = \" << i;\n\t\t\t\t//cout << \" index = \" << dof_index(xi, yi, i) << endl;\n\t\t\t\tdouble a = solution(dof_index(xi, yi, i));\n\t\t\t\tvalue += a * basis_evaluator.eval(i, u, v);\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"x and y not in range: (\" << x << \",\" << y << \")\" << endl;\n\t\t}\n\t\treturn value;\n\t}\n\n\tdouble basis_uv(int i, double u, double v) {\n\t\tbasis_evaluator<2, Basis> basis_evaluator;\n\t\treturn basis_evaluator.eval(i, u, v);\n\t}\n\n\tvoid solve_coordinates(double_vector inner_products, double_vector coordinates) {\n\t\tassert((int)inner_products.size() == dof);\n\t\tassert((int)coordinates.size() == dof);\n\t\tVectorXd x = VectorXd::Map(inner_products.data().begin(), inner_products.size());\n\t\tVectorXd a(dof);\n\t\tM.llt().solve(x, &a);\n\t\tVectorXd::Map(coordinates.data().begin(), coordinates.size()) = a;\n\t}\n\n\tvoid test(double_vector result_, double scale1, double scale2) {\n\t\tauto f = [&](double x, double y) -> double { return cos(x * scale1 + y * scale2); };\n\t\tVectorXd x = VectorXd::Zero(dof);\n\t\tassert((int)result_.size() == dof);\n\t\tfor(int yi = 0; yi < n_cells_y; yi++) {\n\t\t\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\t\tdouble x1, x2;\n\t\t\t\t\tdouble y1, y2;\n\t\t\t\t\tgrid.indexto_xy(xi, yi, x1, y1); \n\t\t\t\t\tgrid.indexto_xy(xi+1, yi+1, x2, y2);\n\t\t\t\t\t//cout << \"integrate x[\" << x1 << \" \" << x2 << \"] y[\" << y1 << \" \" << y2 << \"]\";\n\t\t\t\t\tbasis_function_integrator<2, Basis::degree, Basis, Basis, T> bfi(x1, x2, y1, y2);\n\t\t\t\t\tdouble a = bfi.integrate_function2d(f, i);\n\t\t\t\t\tx(dof_index(xi, yi, i)) += a;\n\t\t\t\t\t//cout << \" \" << a;\n \t\t\t\t\t//cout << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tVectorXd a(dof);\n\t\tM.llt().solve(x, &a);\n\t\t//VectorXd result = VectorXd::Map(result_.data().begin(), result_.size());\n\t\tVectorXd::Map(result_.data().begin(), result_.size()) = a;\n\t\t//result = a;\n\t}\n\n\t//int get_dof() { return dof; }\n\tint dof_index(int x_index, int y_index, int basis_index) {\n\t\tif(Basis::degree == 0) {\n\t\t\treturn x_index + y_index * dofx;\n\t\t}\n\t\tint xi = x_index*(dof_per_cell1d-1) + basis_index % dof_per_cell1d;\n\t\tint yi = y_index*(dof_per_cell1d-1) + basis_index / dof_per_cell1d;\n\t\treturn xi + yi * dofx;\n\t}\n\tint get_dof() { return dof; }\n\tint get_dof_per_cell() { return dof_per_cell; } \n\t/*int get_n_cells() { return grid->;}\n\tint dof_index(int cell_index, int local_index) {\n\t\treturn  cell_index*(dof_per_cell-1)+local_index;\n\t}*/\n\n}; // class MeshRegularNodal<2...>\n\n\ntemplate<class Basis, class T>\nclass MeshRegularNodal<3, Basis, T> {\n\tpublic:\n\t\ttypedef Basis basis_type;\n\t\tT x1, x2;\n\t\tint n_cells_x;\n\t\tint n_cells_y;\n\t\tint n_cells_z;\n\t\tGrid1dRegular<> xgrid;\n\t\tGrid1dRegular<> ygrid;\n\t\tGrid1dRegular<> zgrid;\n\t\tGrid3d<Grid1dRegular<>, Grid1dRegular<>, Grid1dRegular<>> grid;\n\t\tMatrixXd M;\n\t//Transformation1d_in_3d* transformation;\n\t\tint dof, dofx, dofy, dofz;\n\t\tint dof1d;\n\t\tenum { dof_per_cell = MeshRegularNodalHelper<3, Basis, T>::dof_per_cell };\n\t\tenum { dof_per_cell1d = MeshRegularNodalHelper<1, Basis, T>::dof_per_cell };\n\t\t\n\tMeshRegularNodal(T x1, T y1, T z1, T x2, T y2, T z2, int n_cells_x, int n_cells_y, int n_cells_z) : n_cells_x(n_cells_x), n_cells_y(n_cells_y), n_cells_z(n_cells_z), xgrid(x1, x2, n_cells_x+1), ygrid(y1, y2, n_cells_y+1), zgrid(z1, z2, n_cells_z+1), grid(&xgrid, &ygrid, &zgrid), M(1, 1) {\n\t\t\n\t\tif(Basis::degree == 0) {\n\t\t\tdofx = n_cells_x;\n\t\t\tdofy = n_cells_y;\n\t\t\tdofz = n_cells_z;\n\t\t} else {\n\t\t\tdofx = (1 + n_cells_x) + (dof_per_cell1d-2)*n_cells_x; // 1 dof per border + dofs inside the cel\n\t\t\tdofy = (1 + n_cells_y) + (dof_per_cell1d-2)*n_cells_y; // 1 dof per border + dofs inside the cel\n\t\t\tdofz = (1 + n_cells_z) + (dof_per_cell1d-2)*n_cells_z; // 1 dof per border + dofs inside the cel\n\t\t}\n\t\tdof = dofx * dofy * dofz;\n\t\tcout << \"n_cells_x = \" << n_cells_x << \" dofx = \" << dofx << endl; \n\t\tcout << \"n_cells_y = \" << n_cells_y << \" dofy = \" << dofy << endl; \n\t\tcout << \"n_cells_z = \" << n_cells_z << \" dofz = \" << dofz << endl; \n\t\tcout << \"dof = \" << dof << \" dof_per_cell = \" << dof_per_cell << endl;\n\t\t//MatrixXd m = MatrixXd::Zero(dof, dof);\n\t\tM.resize(dof, dof);\n\t\tM =  MatrixXd::Zero(dof, dof);\n\t\t//T scale = 1; //TODO: (x2-x1)/n_cells;\n\t\t\n\t\t//basis_integrator<1, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t\t//cout  << \"test 00 \" << bi.integrate(0, 0) << endl;\n\t\t//cout  << \"test 01 \" << bi.integrate(0, 1) << endl;\n\t\t//cout  << \"test 11 \" << bi.integrate(1, 1) << endl;\n\t\t\n\t\tT integrals[dof_per_cell][dof_per_cell];\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < (j+1); k++) {\n\t\t\t\tbasis_integrator<2, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t\t\t\tT integral = bi.integrate(j, k);\n\t\t\t\t//typedef selfintegrator<Basis::degree, Basis::degree> selfintegrator_type;\n\t\t\t\t//selfintegrator_type si; \n\t\t\t\t//double integral = si.integrate(j,k);\n\t\t\t\t//cout << j << \" \" << k << \" \" << integral << endl;\n\t\t\t\tintegrals[j][k] = integral;\n\t\t\t\tintegrals[k][j] = integral;\n\t\t\t}\n\t\t}\n\t\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\t\tfor(int yi = 0; yi < n_cells_y; yi++) {\n\t\t\t\tfor(int zi = 0; zi < n_cells_z; zi++) {\n\t\t\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\t\t\tint i1 = this->dof_index(xi, yi, zi, j);\n\t\t\t\t\t\t\tint i2 = this->dof_index(xi, yi, zi, k);\n\t\t\t\t\t\t\t//cout << \"xi = \" << xi << \" yi = \" << yi << \" zi = \" << zi << \" j = \" << j << \" k = \" << k;\n\t\t\t\t\t\t\t//cout << \"            i1 = \" << i1 << \" i2 = \" << i2 << endl;\n\t\t\t\t\t\t\tM(i1, i2) += integrals[j][k];\n\t\t\t\t\t}}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/*for(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\tint i1 = i*(dof_per_cell-1)+j;\n\t\t\t\t\tint i2 = i*(dof_per_cell-1)+k;\n\t\t\t\t\tm(i1, i2) = m(i1, i2) + integrals[j][k];\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\t\t//cout << M << endl;\n\t\t//m = m * scale;\n\t\t//ctrans = m.inverse();\n\t}\n\t\t\n\t\tdouble eval_(double_vector solution_, double x, double y, double z) {\n\t\t\tVectorXd solution = VectorXd::Map(solution_.data().begin(), solution_.size());\n\t\t\treturn eval(solution, x, y, z);\n\t\t}\n\t\t\n\t\tdouble eval(VectorXd& solution, double x, double y, double z) {\n\t\t/*int cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\t*/\n\t\t\tint xi = xgrid.findindex(x);\n\t\t\tint yi = ygrid.findindex(y);\n\t\t\tint zi = zgrid.findindex(z);\n\t\t\tT x1 = xgrid.indexto_x(xi);\n\t\t\tT x2 = xgrid.indexto_x(xi+1);\n\t\t\tT y1 = ygrid.indexto_x(yi);\n\t\t\tT y2 = ygrid.indexto_x(yi+1);\n\t\t\tT z1 = zgrid.indexto_x(zi);\n\t\t\tT z2 = zgrid.indexto_x(zi+1);\n\t\t\tdouble u = (x-x1)/(x2-x1);\n\t\t\tdouble v = (y-y1)/(y2-y1);\n\t\t\tdouble w = (z-z1)/(z2-z1);\n\t\t//grid.index\n\t\t//T dx = xright-xleft;\n\t\t\tdouble value = 0;\n\t\t//cout << \"xi = \" << xi;\n\t\t//cout << \" yi = \" << yi;\n\t\t\tif(grid.inrange(x, y, z)) {\n\t\t\t\tbasis_evaluator<3, Basis> basis_evaluator;\n\t\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\t//cout << \" i = \" << i;\n\t\t\t\t//cout << \" index = \" << dof_index(xi, yi, i) << endl;\n\t\t\t\t\tdouble a = solution(dof_index(xi, yi, zi, i));\n\t\t\t\t\tvalue += a * basis_evaluator.eval(i, u, v, w);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcout << \"x, y and z not in range: (\" << x << \",\" << y << \",\" << z << \")\" << endl;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t\t\n\t\tdouble basis_uv(int i, double u, double v, double w) {\n\t\t\tbasis_evaluator<3, Basis> basis_evaluator;\n\t\t\treturn basis_evaluator.eval(i, u, v, w);\n\t\t}\n\t\t\n\t\tvoid solve_coordinates(double_vector inner_products, double_vector coordinates) {\n\t\t\tassert((int)inner_products.size() == dof);\n\t\t\tassert((int)coordinates.size() == dof);\n\t\t\tVectorXd x = VectorXd::Map(inner_products.data().begin(), inner_products.size());\n\t\t\tVectorXd a(dof);\n\t\t\tM.llt().solve(x, &a);\n\t\t\tVectorXd::Map(coordinates.data().begin(), coordinates.size()) = a;\n\t\t}\n\t\t\n\t\t/*void test(double_vector result_, double scale1, double scale2) {\n\t\t\tauto f = [&](double x, double y) -> double { return cos(x * scale1 + y * scale2); };\n\t\t\tVectorXd x = VectorXd::Zero(dof);\n\t\t\tassert(result_.size() == dof);\n\t\t\tfor(int yi = 0; yi < n_cells_y; yi++) {\n\t\t\t\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\t\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\t\t\tdouble x1, x2;\n\t\t\t\t\t\tdouble y1, y2;\n\t\t\t\t\t\tgrid.indexto_xy(xi, yi, x1, y1); \n\t\t\t\t\t\tgrid.indexto_xy(xi+1, yi+1, x2, y2);\n\t\t\t\t\t//cout << \"integrate x[\" << x1 << \" \" << x2 << \"] y[\" << y1 << \" \" << y2 << \"]\";\n\t\t\t\t\t\tbasis_function_integrator<2, Basis::degree, Basis, Basis, T> bfi(x1, x2, y1, y2);\n\t\t\t\t\t\tdouble a = bfi.integrate_function2d(f, i);\n\t\t\t\t\t\tx(dof_index(xi, yi, i)) += a;\n\t\t\t\t\t//cout << \" \" << a;\n \t\t\t\t\t//cout << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tVectorXd a(dof);\n\t\t\tM.llt().solve(x, &a);\n\t\t//VectorXd result = VectorXd::Map(result_.data().begin(), result_.size());\n\t\t\tVectorXd::Map(result_.data().begin(), result_.size()) = a;\n\t\t//result = a;\n\t\t}*/\n\t\t\n\t//int get_dof() { return dof; }\n\t\tint dof_index(int x_index, int y_index, int z_index, int basis_index) {\n\t\t\tif(Basis::degree == 0) {\n\t\t\t\treturn x_index + y_index * dofx + z_index * dofx * dofy;\n\t\t\t}\n\t\t\tint xi = x_index*(dof_per_cell1d-1) + basis_index % dof_per_cell1d;\n\t\t\tint yi = y_index*(dof_per_cell1d-1) + (basis_index / dof_per_cell1d)  % dof_per_cell1d ;\n\t\t\tint zi = z_index*(dof_per_cell1d-1) + basis_index / (dof_per_cell1d * dof_per_cell1d);\n\t\t\treturn xi + yi * dofx + zi * dofx * dofy;\n\t\t}\n\t\tint get_dof() { return dof; }\n\t\tint get_dof_per_cell() { return dof_per_cell; } \n\t/*int get_n_cells() { return grid->;}\n\tint dof_index(int cell_index, int local_index) {\n\t\treturn  cell_index*(dof_per_cell-1)+local_index;\n\t}*/\n\t\t\n\t};\n\ntemplate<class Basis, class T>\nclass MeshRegularNodal<1, Basis, T> {\npublic:\n\ttypedef Basis basis_type;\n\tT x1, x2;\n\tint n_cells_x;\n\tGrid1dRegular<> xgrid;\n\tGrid1dRegular<>& grid;\n\tMatrixXd M;\n//Transformation1d_in_3d* transformation;\n\tint dof, dofx;\n\tint dof1d;\n\tenum { dof_per_cell = MeshRegularNodalHelper<1, Basis, T>::dof_per_cell };\n\tenum { dof_per_cell1d = MeshRegularNodalHelper<1, Basis, T>::dof_per_cell };\n\t\n\tMeshRegularNodal(T x1, T x2, int n_cells_x) : n_cells_x(n_cells_x), xgrid(x1, x2, n_cells_x+1), grid(xgrid), M(1, 1) {\n\t\n\tif(Basis::degree == 0) {\n\t\tdofx = n_cells_x;\n\t} else {\n\t\tdofx = (1 + n_cells_x) + (dof_per_cell1d-2)*n_cells_x; // 1 dof per border + dofs inside the cel\n\t}\n\tdof = dofx;\n\tcout << \"n_cells_x = \" << n_cells_x << \" dofx = \" << dofx << endl; \n\tcout << \"dof = \" << dof << \" dof_per_cell = \" << dof_per_cell << endl;\n\t//MatrixXd m = MatrixXd::Zero(dof, dof);\n\tM.resize(dof, dof);\n\tM =  MatrixXd::Zero(dof, dof);\n\t//T scale = 1; //TODO: (x2-x1)/n_cells;\n\t\n\t//basis_integrator<1, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t//cout  << \"test 00 \" << bi.integrate(0, 0) << endl;\n\t//cout  << \"test 01 \" << bi.integrate(0, 1) << endl;\n\t//cout  << \"test 11 \" << bi.integrate(1, 1) << endl;\n\t\n\tT integrals[dof_per_cell][dof_per_cell];\n\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\tfor(int k = 0; k < (j+1); k++) {\n\t\t\tbasis_integrator<2, Basis::degree, Basis::degree, Basis, Basis, Basis, T> bi;\n\t\t\tT integral = bi.integrate(j, k);\n\t\t\t//typedef selfintegrator<Basis::degree, Basis::degree> selfintegrator_type;\n\t\t\t//selfintegrator_type si; \n\t\t\t//double integral = si.integrate(j,k);\n\t\t\t//cout << j << \" \" << k << \" \" << integral << endl;\n\t\t\tintegrals[j][k] = integral;\n\t\t\tintegrals[k][j] = integral;\n\t\t}\n\t}\n\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\tint i1 = this->dof_index(xi, j);\n\t\t\t\tint i2 = this->dof_index(xi, k);\n\t\t\t\t//cout << \"xi = \" << xi << \" yi = \" << yi << \" zi = \" << zi << \" j = \" << j << \" k = \" << k;\n\t\t\t\t//cout << \"            i1 = \" << i1 << \" i2 = \" << i2 << endl;\n\t\t\t\tM(i1, i2) += integrals[j][k];\n\t\t\t}}\n\t}\n\t/*for(int i = 0; i < n_cells; i++) {\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\tint i1 = i*(dof_per_cell-1)+j;\n\t\t\t\tint i2 = i*(dof_per_cell-1)+k;\n\t\t\t\tm(i1, i2) = m(i1, i2) + integrals[j][k];\n\t\t\t}\n\t\t}\n\t}*/\n\t//cout << M << endl;\n\t//m = m * scale;\n\t//ctrans = m.inverse();\n}\n\t\n\tdouble eval_(double_vector solution_, double x) {\n\t\tVectorXd solution = VectorXd::Map(solution_.data().begin(), solution_.size());\n\t\treturn eval(solution, x);\n\t}\n\t\n\ttemplate<class Array>\n\tdouble eval(Array& solution, double x) {\n\t/*int cell_index = mesh.findindex(x);\n\tT xleft = mesh.indexto_x(cell_index);\n\tT xright = mesh.indexto_x(cell_index+1);\n\t*/\n\t\tint xi = xgrid.findindex(x);\n\t\tT x1 = xgrid.indexto_x(xi);\n\t\tT x2 = xgrid.indexto_x(xi+1);\n\t\tdouble u = (x-x1)/(x2-x1);\n\t//grid.index\n\t//T dx = xright-xleft;\n\t\tdouble value = 0;\n\t//cout << \"xi = \" << xi;\n\t//cout << \" yi = \" << yi;\n\t\tif(grid.inrange(x)) {\n\t\t\tbasis_evaluator<1, Basis> basis_evaluator;\n\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t//cout << \" i = \" << i;\n\t\t\t//cout << \" index = \" << dof_index(xi, yi, i) << endl;\n\t\t\t\tdouble a = solution[dof_index(xi, i)];\n\t\t\t\tvalue += a * basis_evaluator.eval(i, u);\n\t\t\t}\n\t\t} else {\n\t\tcout << \"x not in range: (\" << x << endl;\n\t\t}\n\t\treturn value;\n\t}\t\n\t\n\tdouble eval(VectorXd& solution, double x) {\n\t/*int cell_index = mesh.findindex(x);\n\tT xleft = mesh.indexto_x(cell_index);\n\tT xright = mesh.indexto_x(cell_index+1);\n\t*/\n\t\tint xi = xgrid.findindex(x);\n\t\tT x1 = xgrid.indexto_x(xi);\n\t\tT x2 = xgrid.indexto_x(xi+1);\n\t\tdouble u = (x-x1)/(x2-x1);\n\t//grid.index\n\t//T dx = xright-xleft;\n\t\tdouble value = 0;\n\t//cout << \"xi = \" << xi;\n\t//cout << \" yi = \" << yi;\n\t\tif(grid.inrange(x)) {\n\t\t\tbasis_evaluator<1, Basis> basis_evaluator;\n\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t//cout << \" i = \" << i;\n\t\t\t//cout << \" index = \" << dof_index(xi, yi, i) << endl;\n\t\t\t\tdouble a = solution(dof_index(xi, i));\n\t\t\t\tvalue += a * basis_evaluator.eval(i, u);\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"x not in range: (\" << x << endl;\n\t\t}\n\t\treturn value;\n\t}\n\t\n\tdouble basis_uv(int i, double u) {\n\t\tbasis_evaluator<1, Basis> basis_evaluator;\n\t\treturn basis_evaluator.eval(i, u);\n\t}\n\t\n\tvoid solve_coordinates(double_vector inner_products, double_vector coordinates) {\n\t\tassert((int)inner_products.size() == dof);\n\t\tassert((int)coordinates.size() == dof);\n\t\tVectorXd x = VectorXd::Map(inner_products.data().begin(), inner_products.size());\n\t\tVectorXd a(dof);\n\t\tM.llt().solve(x, &a);\n\t\tVectorXd::Map(coordinates.data().begin(), coordinates.size()) = a;\n\t}\n\t\n\t/*void test(double_vector result_, double scale1, double scale2) {\n\t\tauto f = [&](double x, double y) -> double { return cos(x * scale1 + y * scale2); };\n\t\tVectorXd x = VectorXd::Zero(dof);\n\t\tassert(result_.size() == dof);\n\t\tfor(int yi = 0; yi < n_cells_y; yi++) {\n\t\t\tfor(int xi = 0; xi < n_cells_x; xi++) {\n\t\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\t\tdouble x1, x2;\n\t\t\t\t\tdouble y1, y2;\n\t\t\t\t\tgrid.indexto_xy(xi, yi, x1, y1); \n\t\t\t\t\tgrid.indexto_xy(xi+1, yi+1, x2, y2);\n\t\t\t\t//cout << \"integrate x[\" << x1 << \" \" << x2 << \"] y[\" << y1 << \" \" << y2 << \"]\";\n\t\t\t\t\tbasis_function_integrator<2, Basis::degree, Basis, Basis, T> bfi(x1, x2, y1, y2);\n\t\t\t\t\tdouble a = bfi.integrate_function2d(f, i);\n\t\t\t\t\tx(dof_index(xi, yi, i)) += a;\n\t\t\t\t//cout << \" \" << a;\n\t\t\t\t//cout << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tVectorXd a(dof);\n\t\tM.llt().solve(x, &a);\n\t//VectorXd result = VectorXd::Map(result_.data().begin(), result_.size());\n\t\tVectorXd::Map(result_.data().begin(), result_.size()) = a;\n\t//result = a;\n\t}*/\n\t\n//int get_dof() { return dof; }\n\tint dof_index(int x_index, int basis_index) {\n\t\tif(Basis::degree == 0) {\n\t\t\treturn x_index;\n\t\t}\n\t\tint xi = x_index*(dof_per_cell1d-1) + basis_index % dof_per_cell1d;\n\t\treturn xi;\n\t}\n\tint get_dof() { return dof; }\n\tint get_dof_per_cell() { return dof_per_cell; } \n/*int get_n_cells() { return grid->;}\nint dof_index(int cell_index, int local_index) {\n\treturn  cell_index*(dof_per_cell-1)+local_index;\n}*/\n\t\n};\n\n}", "meta": {"hexsha": "24de1f68b3bac253c762870364f8c004e74bc515", "size": 28140, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/mesh2.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/mesh2.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/mesh2.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": 31.9772727273, "max_line_length": 290, "alphanum_fraction": 0.607782516, "num_tokens": 9829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5709904719454801}}
{"text": "//\n// Created by h on 20/07/18.\n//\n\n#include \"species.h\"\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n\nSpecies::Species(const boost::python::object &species, double B) {\n    charge = p::extract<double>(species.attr(\"charge\"));\n    mass = p::extract<double>(species.attr(\"mass\"));\n    density = p::extract<double>(species.attr(\"density\"));\n    wc = B * abs(charge) / mass;\n    wp = pow(density * charge * charge / (e0 * mass), 0.5);\n\n    vpara_h = arrayutils::extract1d(species.attr(\"vpara_h\"));\n    vperp_h = arrayutils::extract1d(species.attr(\"vperp_h\"));\n\n    npara = vpara_h.size();\n    nperp = vperp_h.size();\n\n    df_dvpara_h = arrayutils::extract2d(species.attr(\"df_dvpara_h\"), npara, nperp);\n    df_dvperp_h = arrayutils::extract2d(species.attr(\"df_dvperp_h\"), npara, nperp);\n\n    p::list pyns = p::extract<p::list>(species.attr(\"ns\"));\n    for (int i = 0; i < len(pyns); ++i) {\n        int n{p::extract<int>(pyns[i])};\n        ns.push_back(n);\n        jns.push_back(arr1d(nperp));\n        jnps.push_back(arr1d(nperp));\n        qs.push_back({arr1d(npara), arr1d(npara), arr1d(npara), arr1d(npara), arr1d(npara), arr1d(npara)});\n        q_ms.push_back({arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1),\n                        arr1d(npara - 1)});\n        q_cs.push_back({arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1), arr1d(npara - 1),\n                        arr1d(npara - 1)});\n    }\n\n    dvperp_h = arr1d(nperp - 1);\n    vpara_hp = arr1d(npara - 1);\n    vpara_hm = arr1d(npara - 1);\n    dv1 = arr1d(npara - 1);\n    dv2 = arr1d(npara - 1);\n    dv3 = arr1d(npara - 1);\n    dv4 = arr1d(npara - 1);\n    dv5 = arr1d(npara - 1);\n    dv6 = arr1d(npara - 1);\n    dv7 = arr1d(npara - 1);\n    dv8 = arr1d(npara - 1);\n\n    for (size_t i = 0; i < nperp - 1; i++) {\n        dvperp_h[i] = vperp_h[i + 1] - vperp_h[i];\n    }\n\n    for (size_t i = 0; i < npara - 1; i++) {\n        vpara_hm[i] = vpara_h[i];\n        vpara_hp[i] = vpara_h[i + 1];\n        dv1[i] = pow(vpara_hp[i], 1) - pow(vpara_hm[i], 1);\n        dv2[i] = pow(vpara_hp[i], 2) - pow(vpara_hm[i], 2);\n        dv3[i] = pow(vpara_hp[i], 3) - pow(vpara_hm[i], 3);\n        dv4[i] = pow(vpara_hp[i], 4) - pow(vpara_hm[i], 4);\n        dv5[i] = pow(vpara_hp[i], 5) - pow(vpara_hm[i], 5);\n        dv6[i] = pow(vpara_hp[i], 6) - pow(vpara_hm[i], 6);\n        dv7[i] = pow(vpara_hp[i], 7) - pow(vpara_hm[i], 7);\n        dv8[i] = pow(vpara_hp[i], 8) - pow(vpara_hm[i], 8);\n    }\n\n}\n\nvoid Species::push_kperp(const double kperp) {\n    for (size_t ni = 0; ni < ns.size(); ni++) {\n        int n{ns[ni]};\n        double jns0 = bm::cyl_bessel_j(n, -(kperp / wc) * vperp_h[0]);\n        double jnps0 = bm::cyl_bessel_j(n, -(kperp / wc) * vperp_h[0]);\n        for (size_t j = 0; j < nperp; j++) {\n            jns[ni][j] = bm::cyl_bessel_j(n, (kperp / wc) * vperp_h[j]);\n            jnps[ni][j] = bm::cyl_bessel_j_prime(n, (kperp / wc) * vperp_h[j]);\n        }\n        for (size_t i = 0; i < npara; i++) {\n            double qh[6]{};\n            qh[0] = 0.5 * jns0 * jns0 * df_dvperp_h[i][0] * dvperp_h[0];\n            qh[1] = 0.5 * jns0 * jns0 * vperp_h[0] * df_dvpara_h[i][0] * dvperp_h[0];\n            qh[2] = 0.5 * jns0 * jnps0 * vperp_h[0] * df_dvperp_h[i][0] * dvperp_h[0];\n            qh[3] = 0.5 * jns0 * jnps0 * vperp_h[0] * vperp_h[0] * df_dvpara_h[i][0] * dvperp_h[0];\n            qh[4] = 0.5 * jnps0 * jnps0 * vperp_h[0] * vperp_h[0] * df_dvperp_h[i][0] * dvperp_h[0];\n            qh[5] = 0.5 * jnps0 * jnps0 * vperp_h[0] * vperp_h[0] * vperp_h[0] * df_dvpara_h[i][0] * dvperp_h[0];\n            for (size_t j = 0; j < nperp - 1; j++) {\n                qh[0] += jns[ni][j] * jns[ni][j] * df_dvperp_h[i][j] * dvperp_h[j];\n                qh[1] += jns[ni][j] * jns[ni][j] * vperp_h[j] * df_dvpara_h[i][j] * dvperp_h[j];\n                qh[2] += jns[ni][j] * jnps[ni][j] * vperp_h[j] * df_dvperp_h[i][j] * dvperp_h[j];\n                qh[3] += jns[ni][j] * jnps[ni][j] * vperp_h[j] * vperp_h[j] * df_dvpara_h[i][j] * dvperp_h[j];\n                qh[4] += jnps[ni][j] * jnps[ni][j] * vperp_h[j] * vperp_h[j] * df_dvperp_h[i][j] * dvperp_h[j];\n                qh[5] += jnps[ni][j] * jnps[ni][j] * vperp_h[j] * vperp_h[j] * vperp_h[j] * df_dvpara_h[i][j] *\n                         dvperp_h[j];\n            }\n            for (size_t k = 0; k < 6; k++) {\n                qs[ni][k][i] = qh[k];\n            }\n        }\n        for (size_t i = 0; i < npara - 1; i++) {\n            for (size_t k = 0; k < 6; k++) {\n                q_ms[ni][k][i] = (qs[ni][k][i + 1] - qs[ni][k][i]) / dv1[i];\n                q_cs[ni][k][i] = qs[ni][k][i] - q_ms[ni][k][i] * vpara_hm[i];\n            }\n        }\n    }\n}\n\narray<array<cdouble, 3>, 3> Species::push_omega(const double kpara, const double kperp, const double wr, const double wi) {\n    array<array<cdouble, 3>, 3> XP{};\n    for (size_t ni = 0; ni < ns.size(); ni++) {\n        int n{ns[ni]};\n        double a{wr};\n        double b{wi};\n        double b2{b * b};\n        double d{n * wc};\n        cdouble apb{a, b};\n        cdouble apbmd{a - d, b};\n        cdouble apbmd2 = apbmd*apbmd;\n        cdouble apbmd3 = apbmd2*apbmd;\n        cdouble iapb{1.0 / apb};\n        cdouble iapbmd{1.0 / apbmd};\n\n        array<cdouble, 6> s_L0_q_m{};\n        array<cdouble, 6> s_L0_q_c{};\n        array<cdouble, 6> s_L1_q_m{};\n        array<cdouble, 6> s_L1_q_c{};\n        array<cdouble, 6> s_L2_q_m{};\n        array<cdouble, 6> s_L2_q_c{};\n        array<cdouble, 6> s_L3_q_m{};\n\n        for (size_t i = 0; i < npara - 1; i++) {\n            //cdouble clogfac{log((apb - d - vpara_hp[i]*kpara)/(apb - d - vpara_hm[i]*kpara))};\n            //cdouble clogfac{log((apb - d - vpara_hm[i]*kpara - dv1[i]*kpara)/(apb - d - vpara_hm[i]*kpara))};\n            //cdouble clogfac{log(1.0 - (dv1[i]*kpara)/(apb - d - vpara_hm[i]*kpara))};\n\n            //Wish to taylor expand in kpara.\n            //cdouble cx = (-dv1[i]*kpara)/(apbmd - vpara_hm[i]*kpara);\n            cdouble cx = kpara*iapbmd;\n            cdouble L0, L1, L2, L3;\n            const double narr[]{1./1., 1./2., 1./3., 1./4., 1./5., 1./5., 1./7., 1./8.};\n            if ((vpara_hm[i]+vpara_hp[i])*(vpara_hm[i]+vpara_hp[i])*(cx.real()*cx.real() + cx.imag()*cx.imag()) < -0.000001){\n                cdouble logfacsum{0.0, 0.0};\n                cdouble powarr[8];\n                const cdouble dvarr[]{dv1[i], dv2[i], dv3[i], dv4[i], dv5[i], dv6[i],dv7[i], dv8[i]};\n                powarr[0] = cx;\n                for (size_t i = 1; i < 8;i++){\n                    powarr[i] = powarr[i-1]*(cx);\n                }\n                for (size_t i = 8; i > 3; i--) {\n                    logfacsum -= powarr[i-1]*(narr[i-1]*dvarr[i-1]);\n                }\n                L3 = logfacsum;\n                L2 = L3 - powarr[2]*narr[2]*dvarr[2];\n                L1 = L2 - powarr[1]*narr[1]*dvarr[1];\n                L0 = L1 - powarr[0]*narr[0]*dvarr[0];\n                if (wi<0.0){\n                    cdouble di = I*L0.imag();\n                    L0 -= di;\n                    L1 -= di;\n                    L2 -= di;\n                    L3 -= di;\n                }\n            }else{\n                double advkm = a - d - vpara_hm[i] * kpara;\n                double rlogfac = 0.5 * log1p(dv1[i] * kpara * (dv1[i] * kpara - 2.0 * advkm) / (advkm * advkm + b2));\n                double ilogfac = atan2(abs(b)*dv1[i]*kpara, (advkm + dv1[i]*kpara)*advkm + b2);\n                L0 = cdouble(rlogfac, ilogfac);\n                cdouble powarr[3];\n                const cdouble dvarr[]{dv1[i], dv2[i], dv3[i]};\n                powarr[0] = cx;\n                for (size_t i = 1; i < 3;i++){\n                    powarr[i] = powarr[i-1]*(cx);\n                }\n                L1 = L0 + powarr[0]*narr[0]*dvarr[0];\n                L2 = L1 + powarr[1]*narr[1]*dvarr[1];\n                L3 = L2 + powarr[2]*narr[2]*dvarr[2];\n            }\n\n            for (size_t k = 0; k < 6; k++) {\n                s_L0_q_m[k] += L0 * q_ms[ni][k][i];\n                s_L0_q_c[k] += L0 * q_cs[ni][k][i];\n                s_L1_q_m[k] += L1 * q_ms[ni][k][i];\n            }\n\n            for (size_t k = 0; k < 5; k++) {\n                s_L1_q_c[k] += L1 * q_cs[ni][k][i];\n                s_L2_q_m[k] += L2 * q_ms[ni][k][i];\n            }\n\n            s_L2_q_c[0] += L2 * q_cs[ni][0][i];\n            s_L2_q_c[2] += L2 * q_cs[ni][2][i];\n            s_L3_q_m[0] += L3 * q_ms[ni][0][i];\n            s_L3_q_m[2] += L3 * q_ms[ni][2][i];\n        }\n\n        double kpara2 = kpara*kpara;\n        double kpara3 = kpara2*kpara;\n        double kpara4 = kpara3*kpara;\n        double kperp2 = kperp*kperp;\n\n        cdouble c00 = M_PI * 2.0 * wp * wp * wc * wc * n * n * iapb * iapb;\n        XP[0][0] -= c00*apb*(kpara2*apbmd*s_L1_q_m[0] + kpara3*s_L0_q_c[0]);\n        XP[0][0] -= c00*(kpara3*apbmd*s_L1_q_m[1] + kpara4*s_L0_q_c[1]);\n        XP[0][0] += c00*(kpara2*apbmd2*s_L2_q_m[0] + kpara3*apbmd*s_L1_q_c[0]);\n\n        cdouble c01 = M_PI * 2.0 * wp * wp * n * wc * I * iapb * iapb * kperp;\n        XP[0][1] -= c01*apb*(kpara2*apbmd*s_L1_q_m[2] + kpara3*s_L0_q_c[2]);\n        XP[0][1] -= c01*(kpara3*apbmd*s_L1_q_m[3] + kpara4*s_L0_q_c[3]);\n        XP[0][1] += c01*(kpara2*apbmd2*s_L2_q_m[2] + kpara3*apbmd*s_L1_q_c[2]);\n\n        cdouble c02 = M_PI * 2.0 * wp * wp * n * wc * iapb * iapb * kperp;\n        XP[0][2] -= c02*apb*(kpara*apbmd2*s_L2_q_m[0] + kpara2*apbmd*s_L1_q_c[0]);\n        XP[0][2] -= c02*(kpara2*apbmd2*s_L2_q_m[1] + kpara3*apbmd*s_L1_q_c[1]);\n        XP[0][2] += c02*(kpara*apbmd3*s_L3_q_m[0] + kpara2*apbmd2*s_L2_q_c[0]);\n\n        cdouble c11 = M_PI * 2.0 * wp * wp * iapb * iapb * kperp2;\n        XP[1][1] -= c11*apb*(kpara2*apbmd*s_L1_q_m[4] + kpara3*s_L0_q_c[4]);\n        XP[1][1] -= c11*(kpara3*apbmd*s_L1_q_m[5] + kpara4*s_L0_q_c[5]);\n        XP[1][1] += c11*(kpara2*apbmd2*s_L2_q_m[4] + kpara3*apbmd*s_L1_q_c[4]);\n\n        cdouble c12 = M_PI * 2.0 * wp * wp * -I * iapb * iapb * kperp2;\n        XP[1][2] -= c12*apb*(kpara*apbmd2*s_L2_q_m[2] + kpara2*apbmd*s_L1_q_c[2]);\n        XP[1][2] -= c12*(kpara2*apbmd2*s_L2_q_m[3] + kpara3*apbmd*s_L1_q_c[3]);\n        XP[1][2] += c12*(kpara*apbmd3*s_L3_q_m[2] + kpara2*apbmd2*s_L2_q_c[2]);\n\n        cdouble c22 = M_PI * 2.0 * wp * wp * iapb * iapb * kperp2;\n        XP[2][2] -= c22*apbmd*(kpara*apbmd2*s_L2_q_m[1] + kpara2*apbmd*s_L1_q_c[1]);\n        XP[2][2] -= c22*d*(apbmd3*s_L2_q_m[0] + kpara*apbmd2*s_L2_q_c[0]);\n    }\n\n    XP[1][0] = -XP[0][1];\n    XP[2][0] = XP[0][2];\n    XP[2][1] = -XP[1][2];\n\n    return XP;\n}\n", "meta": {"hexsha": "bbac4db9f4f6e7684ae3e551f3ad035f8ca01aea", "size": 10574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/KineticDispersion/species.cpp", "max_stars_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_stars_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-03T17:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:56:16.000Z", "max_issues_repo_path": "src/KineticDispersion/species.cpp", "max_issues_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_issues_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-03T03:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-09T09:41:23.000Z", "max_forks_repo_path": "src/KineticDispersion/species.cpp", "max_forks_repo_name": "SamuelIrvine/Kinetic-Dispersion-Solver", "max_forks_repo_head_hexsha": "6056ece40e9c241d8c2df3ce8a089d3f10fb99b1", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 125, "alphanum_fraction": 0.4884622659, "num_tokens": 4338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5708715191536692}}
{"text": "#include <Engine/MeshEdit/Simulate_fast.h>\n\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid Simulate::Clear() {\n\tthis->positions.clear();\n}\n\nbool Simulate::Init() {\n\tm = positions.size() / 3; // number of vertices\n\ts = edgelist.size() / 2;  // number of springs\n\tg = 9.8;\n\th = 1 / 30;\n\titeration = 10;\n\n\t// init q_n-1, q_n, q_n+1\n\tx.resize(3 * m); // vector x, initialized to be y\n\ty.resize(3 * m); // vector y = 2q_n - q_n-1\n\tfor (int i = 0; i < m; i++) {\n\t\tx.segment(3 * i, 3) << positions[i][0]\n\t\t\t<< positions[i][1]\n\t\t\t<< positions[i][2];\n\t\ty.segment(3 * i, 3) = x.segment(3 * i, 3);\n\t}\n\n\t// init Mass\n\tM.resize(3 * m);\n\tM.setOnes();\n\n\t// init force_ext, i.e. gravity\n\tf_ext.resize(3 * m);\n\tfor (int i = 0; i < m; i++)\n\t\tf_ext.segment(3 * i, 3) = Vector3d(0, 0, -1);\n\n\tL = MatrixXd::Zero(m * 3, m * 3);\n\tbuildL();\n\tJ = MatrixXd::Zero(m * 3, m * 3);\n\tbuildJ();\n\n\tFixPoint();\n\tbuildK();\n\tgetb();\n\n\t// prefactorization\n\tMatrixXd A_ = K * (M + h * h * L) * K.transpose() * K;\n\tA = A_.sparseView();\n\tLLT_.compute(A);\n\n\treturn true;\n}\n\nvoid Simulate::SetLeftFix()\n{\n\t//固定网格x坐标最小点\n\tfixed_id.clear();\n\tdouble x = 100000;\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (positions[i][0] < x)\n\t\t{\n\t\t\tx = positions[i][0];\n\t\t}\n\t}\n\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (abs(positions[i][0] - x) < 1e-5)\n\t\t{\n\t\t\tfixed_id.push_back(i);\n\t\t}\n\t}\n\n\tInit();\n}\n\nvoid Simulate::FixPoint() {\n\tfixed_id.push_back(0);\n\tfixed_id.push_back(m / 4);\n}\n\nvoid Simulate::buildK() {\n\tK = MatrixXd::Ones(m * 3 - 3 * fixed_id.size(), m * 3);\n\n\tfor (int i = 0, j = 0; i < xk.size(); i++) {\n\t\tif (fix.find(i) == fix.end()) {\n\t\t\tK(j++, i) = 1;\n\t\t}\n\t}\n\n\t// Eigen::MatrixXd xt;\n\t// xt.resize((x.size()),1);\n\t// b.resize(x.size());\n\n\t// for (int i = 0; i < x.size(); i++)\n\t// \txt(i, 0) = x[i]; \n\t// Eigen::MatrixXd t = K.transpose() * K * xt;\n\n\t// for (int i = 0; i < xk.size(); i++)\n\t// \tb[i] = x[i] - t(i, 0);\n}\n\nvoid Simulate::buildL() {\n\tsize_t m = positions.size() / 3;\n\tsize_t s = edgelist.size() / 2;\n\n\tMatrixXd temp = MatrixXd::Zero(m, m);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tVectorXd Ai = VectorXd::Zero(m);\n\t\tAi(index1 - 1) += 1;\n\t\tAi(index2 - 1) -= 1;\n\t\ttemp += stiff * Ai * Ai.transpose();\n\t}\n\n\tMatrix3d I3 = Matrix3d::Identity();\n\n\t// kronecker product, L = kronecker(temp, I3)\n\tfor (int i = 0; i < m; i++) {\n\t\tL.block(i * 3, i * 3, 3, 3) = temp(i, i) * I3;\n\t}\n}\n\nvoid Simulate::buildJ() {\n\tMatrixXd temp = MatrixXd::Zero(m, s);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tVectorXd Ai = VectorXd::Zero(m);\n\t\tVectorXd Si = VectorXd::Zero(s);\n\t\tAi(index1 - 1) += 1;\n\t\tAi(index2 - 1) -= 1;\n\t\tSi(i) += 1;\n\t\ttemp += stiff * Ai * Si.transpose();\n\t}\n\n\tMatrix3d I3 = Matrix3d::Identity();\n\n\t// kronecker product, L = kronecker(temp, I3)\n\tfor (int i = 0; i < m; i++) {\n\t\tL.block(i * 3, i * 3, 3, 3) = temp(i, i) * I3;\n\t}\n\n}\n\nvoid Simulate::local() {\n\td = VectorXd::Ones(s * 3);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tpointf3 p1 = positions[index1];\n\t\tpointf3 p2 = positions[index2];\n\t\tvecf3 r = p1 - p2;\n\n\t\tVectorXd di(3);\n\t\tdi << r[0], r[1], r[2];\n\n\t\td.segment(3 * i, 3) = l[i] * di / pointf3::distance(p1, p2);\n\t}\n\n}\n\nvoid Simulate::global() {\n\tVectorXd RHS = K * (h * h * J * d + M * y - h * h * f_ext - (M + h * h * L) * b);\n\n\tVectorXd xf = LLT_.solve(RHS);\n\n\tx = K.transpose() * xf + b;\n\n}\n\nvoid Simulate::getb() {\n\tb = x - K.transpose() * K * x;\n}\n\nvoid Simulate::UpdatePos() {\n\tfor (int i = 0; i < m * 3; i++)\n\t\tpositions[i / 3][i % 3] = x(i);\n}\n\nvoid Simulate::SimulateOnce() {\n\t//update y, y = 2q_n - q_n-1\n\ty = 2 * x - y;\n\tsize_t step = 0;\n\twhile (step < iteration) {\n\t\tlocal();\n\t\tglobal();\n\t}\n\tUpdatePos();\n}\n\nbool Simulate::Run() {\n\tSimulateOnce();\n\treturn true;\n}", "meta": {"hexsha": "cd7644b442b98006e5846d08273f2d8d0d9cb8e0", "size": 3990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Simulate_fast.cpp", "max_stars_repo_name": "L-JIN/USTC-CG", "max_stars_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_stars_repo_licenses": ["MIT"], "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/Simulate_fast.cpp", "max_issues_repo_name": "L-JIN/USTC-CG", "max_issues_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_issues_repo_licenses": ["MIT"], "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/Simulate_fast.cpp", "max_forks_repo_name": "L-JIN/USTC-CG", "max_forks_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_forks_repo_licenses": ["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.1826923077, "max_line_length": 82, "alphanum_fraction": 0.5438596491, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5707679645468865}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2021 Paul Ferrand\n\n#include \"helpers.h\"\n#define EIGEN_MPL2_ONLY\n#include <Eigen/Dense>\n#include <numeric>\n\nusing namespace std::complex_literals;\n\ntemplate<class T>\nconstexpr T pi = T { 3.14159265358979323846 };\n\nstd::pair<float, std::complex<float>> frequencyPeakSearch(float* signal, size_t size, float coarseFrequency, \n    float sampleRate, float range, int resolution)\n{\n    using namespace Eigen;\n\n    // Build the super-resolution time-frequency matrix around the coarse frequency\n    VectorXf freq = VectorXf::LinSpaced(2 * resolution + 1, coarseFrequency - range, coarseFrequency + range);\n    VectorXf time = VectorXf::LinSpaced(size, 0, static_cast<float>(size - 1)) / sampleRate;\n\n    MatrixXcf projectionMatrix = \n        exp(2.0if * pi<float> * (freq * time.transpose()).array());\n\n    // Project the signal on the matrix\n    VectorXcf projected = projectionMatrix * Map<VectorXf>(signal, size);\n\n    // Find the highest harmonic\n    unsigned maxIdx = 0;\n    float maxHarmonic = 0.0f;\n    for (unsigned i = 0; i < projected.size(); ++i) {\n        float harmonic = std::abs(projected[i]);\n        if (harmonic > maxHarmonic) {\n            maxIdx = i;\n            maxHarmonic = harmonic;\n        }\n    }\n\n    return std::make_pair(freq[maxIdx], projected[maxIdx]);\n}\n\nstd::vector<float> buildWavetable(const HarmonicVector& harmonics, int size, bool normalizePower)\n{\n    using namespace Eigen;\n    \n    std::vector<double> table;\n    std::vector<float> output;\n    table.resize(size);\n    output.reserve(size);\n    std::fill(table.begin(), table.end(), 0.0);\n\n    if (harmonics.empty()) {\n        std::fill_n(std::back_inserter(output), size, 0.0f);\n        return output;\n    }\n\n    using RowArrayXd = Array<double, 1, Dynamic>;\n    ArrayXd time = ArrayXd::LinSpaced(size, 0, static_cast<double>(size - 1));\n    time /= static_cast<double>(size);\n    Map<ArrayXd> mappedTable { table.data(), size };\n\n    for (const auto& [f, h] : harmonics) {\n        double freqIndex = std::round(f / harmonics.front().first);\n        double phase = std::arg(h);\n        double magnitude = std::abs(h);\n        // fmt::print(\"Harmonic at {:.2f} ({}) Hz: {:.3f} exp (i pi {:.3f})\\n\", f, freqIndex, magnitude, phase);\n        mappedTable += magnitude * (2.0 * pi<double> * freqIndex * time + phase).sin();\n    }\n\n    // Normalize the overall power\n    if (normalizePower) {\n        double squaredNorm = std::accumulate(harmonics.begin(), harmonics.end(), 0.0, \n            [] (double lhs, const auto& rhs) { return lhs + std::pow(std::abs(rhs.second), 2); });\n        double norm = std::sqrt(squaredNorm);\n        mappedTable /= norm;\n    }\n\n    // Roll the wavetable to start around 0\n    size_t zeroIndex = 0;\n    double zeroValue = mappedTable.maxCoeff();\n    for (int i = 0; i < size; ++i) {\n        double absValue = std::abs(mappedTable[i]);\n        if (absValue < zeroValue) {\n            zeroIndex = i;\n            zeroValue = absValue;\n        }\n    }\n    ArrayXd head = mappedTable.head(zeroIndex);\n    ArrayXd tail = mappedTable.tail(size - zeroIndex);\n    mappedTable << tail, head;\n\n    std::transform(table.begin(), table.end(), std::back_inserter(output),\n            [](double x) { return static_cast<float>(x); });\n\n    return output;\n}\n\nstd::vector<float> extractSignalRange(const float* source, double regionStart, double regionEnd, \n    double samplePeriod, int stride, int offset)\n{\n    std::vector<float> signal;\n\n    if (regionStart > regionEnd)\n        std::swap(regionStart, regionEnd);\n\n    int rangeStart = static_cast<int>(regionStart / samplePeriod);\n    int rangeEnd = static_cast<int>(regionEnd / samplePeriod);\n    int rangeSize = rangeEnd - rangeStart;\n    if (rangeSize == 0)\n        return signal;\n        \n    signal.resize(rangeSize);\n    for (int t = 0, s = rangeStart; s < rangeEnd; ++t, ++s)\n        signal[t] = source[stride * s + offset];\n    \n    return signal;\n}", "meta": {"hexsha": "8fcd6eb614d25b62c7eeef371c0bee1f3caee6ca", "size": 3952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helpers.cpp", "max_stars_repo_name": "paulfd/wextract", "max_stars_repo_head_hexsha": "c97a03ffc4d0d4cc1d30267a878ca73b5f90d9b4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-04-20T16:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-22T04:21:53.000Z", "max_issues_repo_path": "src/helpers.cpp", "max_issues_repo_name": "tomasguillen/wextract", "max_issues_repo_head_hexsha": "c97a03ffc4d0d4cc1d30267a878ca73b5f90d9b4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-03T10:21:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T12:59:41.000Z", "max_forks_repo_path": "src/helpers.cpp", "max_forks_repo_name": "tomasguillen/wextract", "max_forks_repo_head_hexsha": "c97a03ffc4d0d4cc1d30267a878ca73b5f90d9b4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-04T20:57:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T20:57:16.000Z", "avg_line_length": 33.4915254237, "max_line_length": 112, "alphanum_fraction": 0.6328441296, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5707679548693084}}
{"text": "#include <Eigen/Cholesky>\n/*\n * Member function definitions of Kalman template class.\n * See kalman.h for template class declaration.\n */\n\nnamespace observer {\n\ntemplate <typename T>\nKalman<T>::Kalman(T& system) : Observer<T>(system, state_t::Zero()) {\n    reset();\n}\n\ntemplate <typename T>\nKalman<T>::Kalman(T& system, const state_t& x0) : Observer<T>(system, x0) {\n    reset();\n}\n\ntemplate <typename T>\nKalman<T>::Kalman(T& system, const state_t& x0,\n        const process_noise_covariance_t& Q,\n        const measurement_noise_covariance_t& R,\n        const error_covariance_t& P0) : Observer<T>(system, x0),\n            m_P(P0), m_Q(Q), m_R(R) {\n    m_K.setZero();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::reset() {\n    m_x.setZero();\n    m_P.setIdentity();\n    m_Q.setIdentity();\n    m_R.setIdentity();\n    m_K.setZero();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::update_state(const input_t& u, const measurement_t& z) {\n    time_update(u);\n    measurement_update(z);\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update() {\n    time_update_state();\n    time_update_error_covariance();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update(const process_noise_covariance_t& Q) {\n    time_update_state();\n    time_update_error_covariance(Q);\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update(const input_t& u) {\n    time_update_state(u);\n    time_update_error_covariance();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update(const input_t& u, const process_noise_covariance_t& Q) {\n    time_update_state(u);\n    time_update_error_covariance(Q);\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update(const measurement_t& z) {\n    measurement_update_kalman_gain();\n    measurement_update_state(z);\n    measurement_update_error_covariance();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update(const measurement_t& z, const measurement_noise_covariance_t& R) {\n    measurement_update_kalman_gain(R);\n    measurement_update_state(z);\n    measurement_update_error_covariance();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update_state() {\n    m_x = m_system.normalize_state(m_system.Ad()*m_x);\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update_state(const input_t& u) {\n    m_x = m_system.normalize_state(m_system.Ad()*m_x + m_system.Bd()*u);\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update_error_covariance() {\n    m_P = m_system.Ad()*m_P*m_system.Ad().transpose() + m_Q;\n}\n\ntemplate <typename T>\nvoid Kalman<T>::time_update_error_covariance(const process_noise_covariance_t& Q) {\n    m_P = m_system.Ad()*m_P*m_system.Ad().transpose() + Q;\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update_kalman_gain() {\n    // S = C*P*C' + R\n    // K = P*C'*S^-1 - > K' = S^-1*C*P'\n    Eigen::LDLT<measurement_noise_covariance_t> S_ldlt(\n            m_system.Cd()*m_P*m_system.Cd().transpose() + m_R);\n    m_K.noalias() = S_ldlt.solve(m_system.Cd()*m_P.transpose()).transpose();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update_kalman_gain(const measurement_noise_covariance_t& R) {\n    // S = C*P*C' + R\n    // K = P*C'*S^-1 - > K' = S^-1*C*P'\n    Eigen::LDLT<measurement_noise_covariance_t> S_ldlt(\n            m_system.Cd()*m_P*m_system.Cd().transpose() + R);\n    m_K.noalias() = S_ldlt.solve(m_system.Cd()*m_P.transpose()).transpose();\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update_state(const measurement_t& z) {\n    m_x = m_system.normalize_state(m_x + m_K*(\n                m_system.normalize_output(z - m_system.Cd()*m_x)));\n}\n\ntemplate <typename T>\nvoid Kalman<T>::measurement_update_error_covariance() {\n    m_P = (error_covariance_t::Identity() - m_K*m_system.Cd())*m_P;\n}\n\n} // namespace observer\n", "meta": {"hexsha": "d621da90856274573abde61df71532acabf43dd9", "size": 3657, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kalman.hh", "max_stars_repo_name": "oliverlee/biketest", "max_stars_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-12-14T01:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T05:15:04.000Z", "max_issues_repo_path": "src/kalman.hh", "max_issues_repo_name": "oliverlee/biketest", "max_issues_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T15:20:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-02T16:09:37.000Z", "max_forks_repo_path": "src/kalman.hh", "max_forks_repo_name": "oliverlee/biketest", "max_forks_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-07T05:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T05:15:05.000Z", "avg_line_length": 27.9160305344, "max_line_length": 101, "alphanum_fraction": 0.6945583812, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.5706116153605183}}
{"text": "#ifndef MATH_QUAT_HPP\n#define MATH_QUAT_HPP\n\n#include <boost/operators.hpp>\n\nnamespace Math {\n\n\ttemplate<typename R = float>\n\tstruct quat: public boost::operators<quat<R>> {\n\t\tR w, x, y, z;\n\t\t\n\t\t/* Unary operators */\n\n\t\t/** Multiplicative inverse */\n\t\tquat<R> operator!(void) const;\n\t\t/** Additive inverse */\n\t\tquat<R> operator-(void) const;\n\t\t/** Conjugate */\n\t\tquat<R> operator~(void) const;\n\t\t/** Cast operator, as Euclidean norm */\n\t\texplicit operator R(void) const;\n\t\t/** Squared Euclidean norm */\n\t\tR operator()(void) const;\n\t\t/** Simple promotion */\n\t\texplicit operator dual<R>(void) const;\n\n\t\t/** Distributes equality test */\n\t\tbool operator==(quat<R> const& rhs) const;\n\t\t/** Apply (lhs * rhs * ~lhs) */\n\t\tquat<R> operator()(quat<R> const& rhs) const;\n\t\t/** Apply (lhs * rhs * ~lhs) */\n\t\tdual<R> operator()(dual<R> const& rhs) const;\n\t\t\n\t\t/*quat<R> operator+(quat<R> const& rhs) const;\n\t\tquat<R> operator-(quat<R> const& rhs) const;\n\t\tquat<R> operator/(quat<R> const& rhs) const;\n\t\tquat<R> operator/(R const& rhs) const;*/\n\n\n\t\tquat<R>& operator+=(quat<R> const& rhs);\n\t\tquat<R>& operator-=(quat<R> const& rhs);\n\t\tquat<R>& operator*=(R const& rhs);\n\t\tquat<R>& operator*=(quat<R> const& rhs);\n\t\tquat<R>& operator/=(R const& rhs);\n\t\tquat<R>& operator/=(quat<R> const& rhs);\n\n\t\tquat(void) = default;\n\t\tquat(const R w, const R x = 0, const R y = 0, const R z = 0):\n\t\t\tw(w), x(x), y(y), z(z) {}\n\t};\n\ttemplate<typename R>\n\tquat<R> quat<R>::operator-(void) const {\n\t\treturn {-w,-x,-y,-z};\n\t}\n\ttemplate<typename R>\n\tquat<R> quat<R>::operator!(void) const {\n\t\treturn ~(*this)/((*this)());\n\t}\n\ttemplate<typename R>\n\tquat<R> quat<R>::operator~(void) const {\n\t\treturn {w,-x,-y,-z};\n\t}\n\ttemplate<typename R>\n\tquat<R>::operator R(void) const {\n\t\treturn sqrt((*this)());\n\t}\n\ttemplate<typename R>\n\tR quat<R>::operator()(void) const {\n\t\treturn w*w + x*x + y*y + z*z;\n\t}\n\ttemplate<typename R>\n\tquat<R>::operator dual<R>(void) const {\n\t\treturn {*this, 0};\n\t}\n\n\ttemplate<typename R>\n\tbool quat<R>::operator==(quat<R> const& rhs) const {\n\t\treturn w == rhs.w && x == rhs.x \n\t\t\t&& y == rhs.y && z == rhs.z;\n\t}\n\ttemplate<typename R>\n\tquat<R> quat<R>::operator()(quat<R> const& rhs) const {\n\t\treturn *this * rhs * ~*this;\n\t}\n\n\ttemplate<typename R>\n\tquat<R>& quat<R>::operator+=(quat<R> const& rhs) {\n\t\tw += rhs.w; x += rhs.x; y += rhs.y; z += rhs.z;\n\t\treturn *this;\n\t}\n\ttemplate<typename R>\n\tquat<R>& quat<R>::operator-=(quat<R> const& rhs) {\n\t\tw -= rhs.w; x -= rhs.x; y -= rhs.y; z -= rhs.z;\n\t\treturn *this;\n\t}\n\ttemplate<typename R>\n\tquat<R>& quat<R>::operator*=(R const& rhs) {\n\t\tw *= rhs; x *= rhs;\n\t\ty *= rhs; z *= rhs;\n\t\treturn *this;\n\t}\n\ttemplate<typename R>\n\tquat<R>& quat<R>::operator*=(quat<R> const& r) {\n\t\tR lw = w, lx = x, ly = y, lz = z,\n\t\t  rw = r.w, rx = r.x, ry = r.y, rz = r.z;\n\t\tw = lw*rw - lx*rx - ly*ry - lz*rz;\n\t\tx = lw*rx + lx*rw + ly*rz - lz*ry;\n\t\ty = lw*ry - lx*rz + ly*rw + lz*rx;\n\t\tz = lw*rz + lx*ry - ly*rx + lz*rw;\n\t\treturn *this;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "0dd33c5537c4c267fea15185da8b789b0241ae0c", "size": 2955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/quat.hpp", "max_stars_repo_name": "XPCX/CitaDel", "max_stars_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/quat.hpp", "max_issues_repo_name": "XPCX/CitaDel", "max_issues_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/quat.hpp", "max_forks_repo_name": "XPCX/CitaDel", "max_forks_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_forks_repo_licenses": ["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.6956521739, "max_line_length": 63, "alphanum_fraction": 0.5847715736, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5705693786486382}}
{"text": "/* $Id: RescalePseudoLog.cpp,v 1.3 2013/04/08 07:36:16 severin Exp $ */\n\n/***\n\nNAME - EEDB::SPStreams::RescalePseudoLog\n\nSYNOPSIS\n\nDESCRIPTION\n\n  A simple signal procesor which rescale expression level as pseudo log\nLog transformation is convenient to vizualize data whose expression levels\nvaries in a wide range of values, but zero values are common places and\nlog(base,0) is not defined and we would thus need to recurse to pseudocount\n(typically arbitrarily adding 0.5).\n\nAlternatively we can use pseudolog defined as asinh(x/2) / log(base), which\nhas the following nice properties\n   * is defined for all real x values\n   * pseudolog(base, 0) = 0\n   * pseudolog(base, -x) = -1* pseudolog(base, x)\n   * pseudolog(base, x) ~ log(base, x) for x > base values\n           [ For information :                                         ]\n           [       pseudolog(10,1)  = 0.2089876; log10(1)  = 0         ]\n           [       pseudolog(10,2)  = 0.3827757; log10(2)  = 0.3010300 ]\n           [       pseudolog(10,3)  = 0.5188791; log10(3)  = 0.4771213 ]\n           [       pseudolog(10,4)  = 0.6269629; log10(4)  = 0.6020600 ]\n           [       pseudolog(10,5)  = 0.7153834; log10(5)  = 0.6989700 ]\n           [       pseudolog(10,10) = 1.0042792; log10(10) = 1         ]\n           [       pseudolog(10,100)= 2.0000430; log10(100)= 2         ]\n           [       pseudolog(2,1)  = 0.6942419; log2(1)  = 0           ]\n           [       pseudolog(2,2)  = 1.2715533; log2(2)  = 1           ]\n           [       pseudolog(2,3)  = 1.7236790; log2(3)  = 1.584963    ]\n           [       pseudolog(2,4)  = 2.0827257; log2(4)  = 2           ]\n           [       pseudolog(2,5)  = 2.3764522; log2(5)  = 2.321928    ]\n           [       pseudolog(2,10) = 3.3361433; log2(10) = 3.321928    ]\n           [       pseudolog(2,100)= 6.6440004; log2(100)= 6.643856    ]\n\nCONTACT\n\nNicolas Bertin <nbertin@gsc.riken.jp>\nJessica Severin <severin@gsc.riken.jp>\n\nLICENSE\n\n * Software License Agreement (BSD License)\n * EdgeExpressDB [eeDB] system\n * copyright (c) 2007-2013 Jessica Severin RIKEN OSC\n * All rights reserved.\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 Jessica Severin RIKEN OSC 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 ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS 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\nAPPENDIX\n\nThe rest of the documentation details each of the object methods. Internal methods are usually preceded with a _\n\n***/\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <string>\n#include <stdarg.h>\n#include <rapidxml.hpp>  //rapidxml must be include before boost\n#include <boost/algorithm/string.hpp>\n#include <EEDB/Feature.h>\n#include <EEDB/Expression.h>\n#include <EEDB/Experiment.h>\n#include <EEDB/SPStream.h>\n#include <EEDB/SPStreams/RescalePseudoLog.h>\n\nusing namespace std;\nusing namespace MQDB;\n\nconst char*  EEDB::SPStreams::RescalePseudoLog::class_name = \"EEDB::SPStreams::RescalePseudoLog\";\n\n//function prototypes\nvoid _spstream_rescalepseudolog_delete_func(MQDB::DBObject *obj) { \n  delete (EEDB::SPStreams::RescalePseudoLog*)obj;\n}\nMQDB::DBObject* _spstream_rescalepseudolog_next_in_stream_func(EEDB::SPStream* node) {\n  return ((EEDB::SPStreams::RescalePseudoLog*)node)->_next_in_stream();\n}\nvoid _spstream_rescalepseudolog_xml_func(MQDB::DBObject *obj, string &xml_buffer) { \n  ((EEDB::SPStreams::RescalePseudoLog*)obj)->_xml(xml_buffer);\n}\nstring _spstream_rescalepseudolog_display_desc_func(MQDB::DBObject *obj) { \n  return ((EEDB::SPStreams::RescalePseudoLog*)obj)->_display_desc();\n}\n\n\nEEDB::SPStreams::RescalePseudoLog::RescalePseudoLog() {\n  init();\n}\n\nEEDB::SPStreams::RescalePseudoLog::~RescalePseudoLog() {\n}\n\nvoid EEDB::SPStreams::RescalePseudoLog::init() {\n  EEDB::SPStream::init();\n  _classname                 = EEDB::SPStreams::RescalePseudoLog::class_name;\n  _module_name               = \"RescalePseudoLog\";\n  _funcptr_delete            = _spstream_rescalepseudolog_delete_func;\n  _funcptr_xml               = _spstream_rescalepseudolog_xml_func;\n  _funcptr_simple_xml        = _spstream_rescalepseudolog_xml_func;\n  _funcptr_display_desc      = _spstream_rescalepseudolog_display_desc_func;\n\n  //function pointer code\n  _funcptr_next_in_stream         = _spstream_rescalepseudolog_next_in_stream_func;\n\n  //attribute variables \n  // default to base 10 (aka pseudolog10)\n  base(10);\n}\n\n\nvoid EEDB::SPStreams::RescalePseudoLog::base(long value) {\n  _base = value;\n  char buffer[17];\n  snprintf(buffer, 16, \"_pseudolog%ld\", value);\n  _base_str = buffer;\n}\n\nvoid EEDB::SPStreams::RescalePseudoLog::base(char* value) {\n  if(value==NULL) { return; }\n  _base_str = string(\"_pseudolog\") + value;\n  _base = strtol(value, NULL, 10);\n}\n\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n//  creation from XML section\n//\n////////////////////////////////////////////////////////////////////////////\n\n\nEEDB::SPStreams::RescalePseudoLog::RescalePseudoLog(void *xml_node) {\n  //constructor using a rapidxml <spstream> description\n  init();\n  if(xml_node==NULL) { return; }\n  \n  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node; \n  rapidxml::xml_node<>      *node;\n\n  if(string(root_node->name()) != \"spstream\") { return; }\n\n  if((node = root_node->first_node(\"base\")) != NULL) {\n    //base(strtol(node->value(), NULL, 10));\n    base(node->value());\n  }\n}\n\nstring EEDB::SPStreams::RescalePseudoLog::_display_desc() {\n  char buffer[256];\n  snprintf(buffer, 256, \"RescalePseudoLog%ld\", _base);\n  return buffer;\n}\n\n\nvoid EEDB::SPStreams::RescalePseudoLog::_xml(string &xml_buffer) {\n  _xml_start(xml_buffer);  //from SPStream superclass\n  \n  char buffer[256];\n  snprintf(buffer, 256, \"<base>%ld</base>\", _base);\n  xml_buffer.append(buffer);\n  \n  _xml_end(xml_buffer);  //from superclass\n}\n\n\n\n\n////////////////////////////////////////////////////////////////////////////\n//\n// callback methods \n//\n////////////////////////////////////////////////////////////////////////////\n\n\nMQDB::DBObject* EEDB::SPStreams::RescalePseudoLog::_next_in_stream() {\n  if(_source_stream == NULL) { return NULL; }\n\n  MQDB::DBObject *obj = _source_stream->next_in_stream();\n  if(obj == NULL) { return NULL; }\n\n  if(obj->classname() == EEDB::Expression::class_name) {\n    EEDB::Expression *express = (EEDB::Expression*)obj;\n    _process_expression(express);\n  }\n  \n  else if(obj->classname() == EEDB::Feature::class_name) {\n    EEDB::Feature *feature = (EEDB::Feature*)obj;\n    vector<EEDB::Expression*>  expression = feature->expression_array();\n    for(unsigned int i=0; i<expression.size(); i++) {\n      _process_expression(expression[i]);\n    }\n    feature->rebuild_expression_hash();\n  } \n  //other classes are not modified\n  \n  //everything is just passed through\n  return obj;\n}\n\n\nvoid  EEDB::SPStreams::RescalePseudoLog::_process_expression(EEDB::Expression *express) {\n  if(express == NULL) { return; }\n  EEDB::Experiment *exp = express->experiment();\n  if(exp == NULL) { return; }\n  EEDB::Datatype *dtype = express->datatype();\n  if(dtype == NULL) { return; }\n\n  double tval =  asinh( express->value() / 2) / log(_base) ;\n  express->value(tval);\n  express->datatype(dtype->type() + _base_str);\n}\n\n\n", "meta": {"hexsha": "d5397eda8875c66311b2f701f099d5a5836c3f8a", "size": 8481, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/EEDB/SPStreams/RescalePseudoLog.cpp", "max_stars_repo_name": "jessica-severin/ZENBU_2.11.1", "max_stars_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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": "c++/EEDB/SPStreams/RescalePseudoLog.cpp", "max_issues_repo_name": "jessica-severin/ZENBU_2.11.1", "max_issues_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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++/EEDB/SPStreams/RescalePseudoLog.cpp", "max_forks_repo_name": "jessica-severin/ZENBU_2.11.1", "max_forks_repo_head_hexsha": "694dd8fb178f3cbde2e058b8ee6a57e5a4c09cc7", "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.1908713693, "max_line_length": 112, "alphanum_fraction": 0.654639783, "num_tokens": 2370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.5705598868721129}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <complex>\n#include <set>\n#include <cmath>\n#include <map>\n#include <ctime>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <gflags/gflags.h>\n#include <redsvd/redsvd.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nusing namespace Eigen;\nusing namespace REDSVD;\nusing namespace boost;\nusing namespace std;\n\nconst float EPS = 0.00000000001f;\n\nDEFINE_string(filename, \"test.ungraph\", \"Filename for edgelist file.\");\nDEFINE_string(emb1, \"sparse.emb\", \"Filename for svd results.\");\nDEFINE_string(emb2, \"spectral.emb\", \"Filename for svd results.\");\nDEFINE_int32(num_node, 4, \"Number of node in the graph.\");\nDEFINE_int32(num_rank, 2, \"Embedding dimension.\");\nDEFINE_int32(num_step, 5, \"Number of order for recursion.\");\nDEFINE_int32(num_iter, 2, \"Number of iter in randomized svd.\");\nDEFINE_int32(num_thread, 10, \"Number of threads.\");\nDEFINE_double(theta, 0.5, \"Parameter of ProNE\");\nDEFINE_double(mu, 0.1, \"Parameter of ProNE\");\n\nSMatrixXf readGraph(string filename, int num_node){\n    SMatrixXf A(num_node, num_node);\n    typedef Eigen::Triplet<float> T;\n    vector<T> tripletList;\n    ifstream fin(filename.c_str());\n    while (1)\n    {\n        string x, y;\n        if (!(fin >> x >> y))\n            break;\n        int a = atoi(x.c_str()), b = atoi(y.c_str());\n        if (a==b) continue;\n        tripletList.push_back(T(a, b, 1));\n        tripletList.push_back(T(b, a, 1));\n    }\n    A.setFromTriplets(tripletList.begin(), tripletList.end());\n    return A;\n}\n\nvoid saveEmbedding(MatrixXf &data, string output){\n    int m = data.rows(), d = data.cols();\n    FILE *emb = fopen(output.c_str(), \"wb\");\n    fprintf(emb, \"%d %d\\n\", m, d);\n    for (int i = 0; i < m; i++)\n    {\n        fprintf(emb, \"%d\", i);\n        for (int j = 0; j < d; j++)\n            fprintf(emb, \" %f\", data(i, j));\n        fprintf(emb, \"\\n\");\n    }\n    fclose(emb);\n}\n\nSMatrixXf l1Normalize(SMatrixXf & mat){\n    SMatrixXf mat2(mat.rows(), mat.cols());\n    for (int k=0; k<mat.outerSize(); ++k){\n        int num_neighbor = mat.row(k).sum();\n        for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n            mat2.insert(k, it.col()) = it.value()/num_neighbor;\n    }\n    return mat2;\n}\n\nMatrixXf & l2Normalize(MatrixXf & mat){\n    for (int i = 0; i < mat.rows(); ++i){\n        float ssn = sqrt(mat.row(i).squaredNorm());\n        if (ssn < EPS) ssn = EPS;\n        mat.row(i) = mat.row(i) / ssn;\n      }\n    return mat;\n}\n\nSMatrixXf & validate(SMatrixXf & mat){\n    for (int k=0; k<mat.outerSize(); ++k)\n          for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n              if (it.value() <=0)\n                mat.coeffRef(k, it.col()) = 1;\n    return mat;\n}\n\nSMatrixXf & smfLog(SMatrixXf & mat){\n    for (int k=0; k<mat.outerSize(); ++k)\n          for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n              mat.coeffRef(it.row(), it.col()) = log(it.value());\n    return mat;\n}\n\nfloat bessel(int a, float b){\n    return boost::math::cyl_bessel_i(a, b);\n}\n\nvoid printSmf(SMatrixXf & mat){\n    for (int k=0; k<mat.outerSize(); ++k)\n          for (SMatrixXf::InnerIterator it(mat,k); it; ++it)\n            cout <<\"(\" <<k << \", \"<<it.col()<<\", \"<<it.value()<<\")\"<<endl;\n}\n\n\nMatrixXf & svdFlip(MatrixXf & mat){\n    VectorXf max_abs_num = mat.cwiseAbs().colwise().maxCoeff(); \n    for (int i = 0; i < mat.cols(); ++i){\n        float sign = max_abs_num(i) >= 0? 1.0:-1.0;\n        mat.col(i) = mat.col(i) * sign;\n      }\n    return mat;\n}\n\nMatrixXf randomizedRangeFinder(SMatrixXf &A, int size, int num_iter){\n    int n_samples = A.rows(), n_features= A.cols();\n    MatrixXf Q = MatrixXf::Random(n_features, size), L(n_samples, size);\n    Eigen::FullPivLU<MatrixXf> lu1(n_samples, size);\n    Eigen::FullPivLU<MatrixXf> lu2(n_features, size);\n    for(int i=0; i<num_iter;i++)\n    {\n        lu1.compute(A * Q);\n        L.setIdentity();\n        L.block(0, 0, n_samples, size).triangularView<Eigen::StrictlyLower>() = lu1.matrixLU();\n        L = lu1.permutationP().inverse() * L; \n\n        lu2.compute(A.transpose() * L);\n        Q.setIdentity();\n        Q.block(0, 0, n_features, size).triangularView<Eigen::StrictlyLower>() = lu2.matrixLU();\n        Q = lu2.permutationP().inverse() * Q;\n    }\n    Eigen::ColPivHouseholderQR<MatrixXf> qr(A * Q);\n    // return qr.colsPermutation().inverse() * qr.householderQ();\n    return qr.householderQ() * MatrixXf::Identity(n_samples, size);\n}\n\nMatrixXf randomizedSvd(SMatrixXf &data, int rank, int num_iter){\n    int n_oversamples = 10;\n    int n_random = rank + n_oversamples;\n    int n_samples = data.rows(), n_features= data.cols();\n    if(n_random > min(n_samples, n_features))\n        n_random = min(n_samples, n_features);\n    \n    MatrixXf Q = randomizedRangeFinder(data, n_random, num_iter);\n    cout <<\"Q computed done\"<<endl;\n    MatrixXf B = Q.transpose() * data;\n    \n    // Eigen::JacobiSVD<MatrixXf> svdOfB(B, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::BDCSVD<Eigen::MatrixXf> svdOfB(B, Eigen::ComputeThinU);\n    \n    VectorXf s = svdOfB.singularValues();\n    // MatrixXf V = svdOfB.matrixV();\n    MatrixXf U = Q * svdOfB.matrixU();\n\n    U = svdFlip(U);\n    \n    MatrixXf newU = U.block(0, 0, n_samples, rank);\n    // MatrixXf V = svdOfB.matrixV().block(0, 0, n_samples, rank);\n    VectorXf newS = s.head(rank);\n\n    MatrixXf emb = newU * newS.cwiseSqrt().asDiagonal();\n\n    emb = l2Normalize(emb);\n    return emb;\n}\n\n\nMatrixXf getEmbbeddingViaSvd(SMatrixXf &data, int rank){\n    RedSVD redsvd;\n    redsvd.run(data, rank);\n    MatrixXf emb = redsvd.matrixU() * redsvd.singularValues().cwiseSqrt().asDiagonal();\n    emb = l2Normalize(emb);\n    return emb;\n}\n\nMatrixXf getEmbbeddingViaDenseSvd(MatrixXf &data, int rank){\n    // Eigen::JacobiSVD<Eigen::MatrixXf> svdOfC(data, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    // Eigen::BDCSVD<Eigen::MatrixXf> svdOfC(data, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::BDCSVD<Eigen::MatrixXf> svdOfC(data, Eigen::ComputeThinU);\n    MatrixXf emb = svdOfC.matrixU() * svdOfC.singularValues().cwiseSqrt().asDiagonal();\n    emb = l2Normalize(emb);\n    return emb;\n}\n\nMatrixXf getSparseEmbedding(SMatrixXf & A, int rank, int num_iter){\n    time_t t1 = time(NULL);\n    // cout << \"number of nnz: \"<< A.nonZeros() <<endl;\n    int row = A.rows(), col = A.cols();\n    SMatrixXf B = l1Normalize(A);\n    SMatrixXf C = B.transpose();\n    SMatrixXf D(col, col), E(row, col), F(row, col);\n    for (int i = 0; i < row; ++i){\n        D.insert(i, i) = pow(C.row(i).sum(), 0.75);\n    }\n\n    D = D / D.sum();\n    E = A * D;\n\n    B = validate(B);\n    E = validate(E);\n\n    B = smfLog(B);\n    E = smfLog(E);\n    F = B - E;\n    cout << \"preprocess time: \"<< (time(NULL) - t1 + 0.0) << endl;\n    // printSmf(F);\n    //cout << \"number of nnz: \"<< F.nonZeros() <<endl;\n\n    MatrixXf emb = getEmbbeddingViaSvd(F, rank);\n    //MatrixXf emb = randomizedSvd(F, rank, num_iter);\n    return emb;\n}\n\nMatrixXf getSpectralEmbedding(SMatrixXf & A, MatrixXf & a, int step, float theta, float mu){\n    time_t t1 = time(NULL);\n    cout << \"Chebyshev series --------------- \" << endl;\n    if (step==1) return a;\n    int num_node = a.rows(), rank = a.cols();\n    SMatrixXf I(num_node, num_node);\n    for (int i = 0; i < num_node; ++i)\n        I.insert(i, i) = 1;\n    A = A + I;\n    SMatrixXf B = l1Normalize(A);\n    SMatrixXf L = I - B;\n    SMatrixXf M = L - mu * I;\n    // cout << \"number of nnz: \"<< M.nonZeros() <<endl;\n    // printSmf(M);\n\n    MatrixXf Lx0 = a;\n    MatrixXf Lx1 = M * a, Lx2;\n    Lx1 = 0.5 * M * Lx1 - a;\n\n    MatrixXf conv = bessel(0, theta)* Lx0;\n    conv -= 2 * bessel(1, theta)* Lx1;\n    for(int i=2; i<step; i++){\n        Lx2 = M * Lx1;\n        Lx2 = (M * Lx2 - 2 * Lx1) - Lx0;\n\n        if (i % 2 == 0)\n            conv += 2 * bessel(i, theta) * Lx2;\n        else\n            conv -= 2 * bessel(i, theta) * Lx2;\n        Lx0 = Lx1;\n        Lx1 = Lx2;\n        cout << \"Bessell time: \" << i <<\"\\t\"<< (time(NULL) - t1 + 0.0) << endl;\n    }\n    MatrixXf F = A * (a - conv);\n    cout << \"Chebyshev time: \"<< (time(NULL) - t1 + 0.0) << endl;\n    time_t t2 = time(NULL);\n\n    MatrixXf emb = getEmbbeddingViaDenseSvd(F, rank);\n    cout << \"dense svd time: \"<< (time(NULL) - t2 + 0.0) << endl;\n    return emb;\n}\n\n\nint main(int argc, char** argv)\n{\n    gflags::ParseCommandLineFlags(&argc, &argv, true);\n    time_t start_time = time(NULL);\n    Eigen::setNbThreads(FLAGS_num_thread);\n\n    SMatrixXf A = readGraph(FLAGS_filename, FLAGS_num_node);\n    time_t t1 = time(NULL);\n    cout << \"Running time of read graph: \" << (t1 - start_time + 0.0)<< endl;\n\n    MatrixXf feature = getSparseEmbedding(A, FLAGS_num_rank, FLAGS_num_iter);\n    time_t t2 = time(NULL);\n    cout << \"Running time of get sparse embedding: \" << (t2 - t1 + 0.0) << endl;\n\n    MatrixXf embedding = getSpectralEmbedding(A, feature, FLAGS_num_step, FLAGS_theta, FLAGS_mu);\n    time_t t3 = time(NULL);\n    cout << \"Running time of get spectral embedding: \" << (t3 - t2 + 0.0)  << endl;\n    cout << \"Running time of ProNE: \" << (t3 - start_time + 0.0) << endl;\n    saveEmbedding(feature, FLAGS_emb1);\n    saveEmbedding(feature, FLAGS_emb2);\n\n}\n", "meta": {"hexsha": "cb7b605a7e9bdfed08a5676ad7632e4a6847ad3f", "size": 9151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProNE.cpp", "max_stars_repo_name": "ericxsun/ProNE", "max_stars_repo_head_hexsha": "9bc7d1adfd6da95f7c0f7d42f8c2da1123b6ae93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ProNE.cpp", "max_issues_repo_name": "ericxsun/ProNE", "max_issues_repo_head_hexsha": "9bc7d1adfd6da95f7c0f7d42f8c2da1123b6ae93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ProNE.cpp", "max_forks_repo_name": "ericxsun/ProNE", "max_forks_repo_head_hexsha": "9bc7d1adfd6da95f7c0f7d42f8c2da1123b6ae93", "max_forks_repo_licenses": ["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.2218309859, "max_line_length": 97, "alphanum_fraction": 0.5981859906, "num_tokens": 2941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5705460106505913}}
{"text": "#include <signal.h>\n\n// ROS\n#include <ros/ros.h>\n// ROS msgs\n#include <vive_bridge/TrackedDevicesStamped.h>\n#include <sensor_msgs/JoyFeedback.h>\n\n// tf2\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <tf2_ros/static_transform_broadcaster.h>\n#include <tf2_ros/transform_listener.h>\n\n// RViz\n#include <rviz_visual_tools/rviz_visual_tools.h>\n\n// Eigen\n#include \"tf2_eigen/tf2_eigen.h\"\n#include <Eigen/Dense>\n\n// Sophus - C++ implementation of Lie Groups using Eigen\n#include <sophus/se3.hpp>\n\n#include \"sophus_ros_conversions/eigen.hpp\"\n#include \"sophus_ros_conversions/geometry.hpp\"\n\n#include \"test/ceres/local_parameterization_se3.hpp\"\n\n// Ceres NLS solver solver\n#include <ceres/ceres.h>\n\n\n// Handle signal [ctrl + c]\nbool sigint_flag = true;\n\nvoid IntHandler(int signal) {\n    sigint_flag = false;\n}\n\n\nenum E_CalibrationStates {\n    STATE_SPHERE_POINTS = 0,\n    STATE_CHECKERBOARD_POINTS\n};\n\nnamespace Eigen {\n    namespace internal {\n        template <class T, int N, typename NewType>\n            struct cast_impl<ceres::Jet<T, N>, NewType> {\n            EIGEN_DEVICE_FUNC\n            \n            static inline NewType run(ceres::Jet<T, N> const& x) {\n                return static_cast<NewType>(x.a);\n            }\n        };\n    }  // namespace internal\n}  // namespace Eigen\n\nstruct SphereCostFunctor {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    SphereCostFunctor(Eigen::Vector3d SurfacePoint) : SurfacePoint(SurfacePoint) {}\n\n    template <class T>\n    bool operator()(T const* const sCenterPoint,\n                    T const* const sRadius,\n                    T* sResiduals) const\n    {\n        using Vector3T = Eigen::Matrix<T, 3, 1>;\n        Eigen::Map<Vector3T const> const CenterPoint(sCenterPoint);\n\n        sResiduals[0] = (SurfacePoint.cast<T>() - CenterPoint).squaredNorm() - T(sRadius[0])*T(sRadius[0]);\n\n        return true;\n    }\n\n    Eigen::Vector3d SurfacePoint;\n};\n\nstruct CheckerboardCostFunctor {\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CheckerboardCostFunctor(Sophus::SE3d T_s, Sophus::SE3d::Point p_t) : T_s(T_s), p_t(p_t) {}\n\n    template <class T>\n    bool operator()(T const* const sT_x, T* sResiduals) const\n    {\n        Eigen::Map<Sophus::SE3<T> const> const T_x(sT_x);\n        Eigen::Map<Eigen::Matrix<T, 3, 1> > residuals(sResiduals);\n\n        // residuals = ((T_a.cast<T>()*T_x).inverse()*(T_x*T_b.cast<T>() ) ).log();\n        residuals = T_s.cast<T>() * T_x * p_t.cast<T>() - T_x.inverse() * T_s.translation().cast<T>();\n\n        return true;\n    }\n\n    Sophus::SE3d T_s;\n    Sophus::SE3d::Point p_t;\n};\n\n\nclass ToolCalibratingNode {\n    ros::NodeHandle nh_;\n    ros::Rate loop_rate_;\n\n    // Publishers\n    ros::Publisher joy_feedback_pub_;\n\n    // Subscribers\n    ros::Subscriber devices_sub_;\n    ros::Subscriber joy_sub_;\n\n    void DevicesCb(const vive_bridge::TrackedDevicesStamped& msg_);\n    void JoyCb(const sensor_msgs::Joy& msg_);\n\n    // ROS msgs\n    geometry_msgs::TransformStamped tf_msg_, tf_msg_tool_;\n    sensor_msgs::JoyFeedback joy_feedback_msg_;\n\n    // RViz\n    rviz_visual_tools::RvizVisualToolsPtr rviz_tools_, rviz_mesh_tools_;\n\n    // tf2\n    tf2_ros::Buffer tf_buffer_;\n    tf2_ros::TransformListener *tf_listener_;\n    tf2_ros::StaticTransformBroadcaster static_tf_broadcaster_;\n\n    std::string controller_frame, tool_frame, tracker_frame, world_frame;\n    unsigned int controller_id, tracker_id;\n\n    // Eigen\n    Eigen::Affine3d eigen_msg_, eigen_tool_;\n\n    std::vector<Eigen::Vector3d> points_;\n    Eigen::Vector3d eigen_point_, eigen_c_, vecs_[3], basis_[3];\n    double radius;\n\n    Sophus::SE3d T_x;\n    std::vector<Sophus::SE3d> tracker_poses_;\n    std::vector<Sophus::SE3d::Point> checkerboard_points_;\n\n    unsigned int state;\n\n    public:\n        ToolCalibratingNode(int frequency);\n        ~ToolCalibratingNode();\n\n        bool Init();\n        void Loop();\n        void Shutdown();\n};\n\nvoid ToolCalibratingNode::DevicesCb(const vive_bridge::TrackedDevicesStamped& msg_) {\n    /**\n     * Update information about the currently tracked devices.\n     */\n\n    for (int i = 0; i < msg_.device_count; i++) {\n        if (msg_.device_classes[i] == msg_.CONTROLLER) {\n            controller_frame = msg_.device_frames[i];\n            controller_id = i;\n        }\n        if (msg_.device_classes[i] == msg_.TRACKER) {\n            tracker_frame = msg_.device_frames[i];\n            tracker_id = i;\n        }\n    }\n}\n\nToolCalibratingNode::ToolCalibratingNode(int frequency)\n    : loop_rate_(frequency),\n      static_tf_broadcaster_(),\n      tf_listener_(new tf2_ros::TransformListener(tf_buffer_) )\n{\n    // Publishers\n    joy_feedback_pub_ = nh_.advertise<sensor_msgs::JoyFeedback>(\"/vive_node/joy/haptic_feedback\", 10, true);\n    // Subscribers\n    devices_sub_ = nh_.subscribe(\"/vive_node/tracked_devices\", 1, &ToolCalibratingNode::DevicesCb, this);\n\n    // RViz\n    rviz_tools_.reset(new rviz_visual_tools::RvizVisualTools(world_frame, \"/rviz_visual_markers\") );\n    rviz_mesh_tools_.reset(new rviz_visual_tools::RvizVisualTools(world_frame, \"/vive_node/rviz_mesh_markers\") );\n\n    // Define joy feedback message\n    joy_feedback_msg_.type = joy_feedback_msg_.TYPE_RUMBLE;\n    joy_feedback_msg_.intensity = .1;\n\n    state = STATE_SPHERE_POINTS;\n\n    eigen_tool_.setIdentity();\n\n    const double W = 0.02;\n    const double L = 0.02;\n    const int m = 3;\n    const int n = 9;\n\n    checkerboard_points_.resize(m*n);\n    for (int j = 0; j < m; j++) {\n        for (int i = 0; i < n; i++) {\n            checkerboard_points_[j*n + i] << L*i, W*j, 0;\n        }\n    }\n}\nToolCalibratingNode::~ToolCalibratingNode() {\n}\n\nvoid ToolCalibratingNode::JoyCb(const sensor_msgs::Joy& msg_) {\n      /**\n     * Handle VIVE Controller inputs\n     */\n\n    if (msg_.axes[0] + msg_.axes[1] + msg_.axes[2] == 0.) {\n        if (msg_.buttons[1]) { // Grip button\n            std::string pError;\n            if (tf_buffer_.canTransform(world_frame, tracker_frame, ros::Time(0), &pError) ) {\n                // Get tracked device location from tf server\n                tf_msg_ = tf_buffer_.lookupTransform(world_frame, tracker_frame, ros::Time(0) );\n                eigen_msg_ = tf2::transformToEigen(tf_msg_);\n                eigen_point_ = eigen_msg_.translation();\n\n                // Trigger controller haptic feedback\n                joy_feedback_pub_.publish(joy_feedback_msg_);\n\n                // Publish sphere at sampled point\n                rviz_tools_->publishSphere(eigen_point_, rviz_visual_tools::BLUE, rviz_visual_tools::MEDIUM);\n                rviz_tools_->trigger();\n\n                if (state == STATE_SPHERE_POINTS) {\n                    points_.push_back(eigen_point_);\n                    int n_points = points_.size();\n                    ROS_INFO_STREAM(\"Point \" << n_points << \": \\n\" << eigen_point_.matrix() );\n\n                    if (n_points >= 4) {\n                        // Compute solver seed from linear solution\n                        if (n_points == 4) {\n                            Eigen::Matrix4d eigen_A_;\n                            eigen_A_ << points_[0].transpose(), 1,\n                                        points_[1].transpose(), 1,\n                                        points_[2].transpose(), 1,\n                                        points_[3].transpose(), 1;\n\n                            Eigen::Vector4d eigen_b_;\n                            eigen_b_ << points_[0].squaredNorm(),\n                                        points_[1].squaredNorm(),\n                                        points_[2].squaredNorm(),\n                                        points_[3].squaredNorm();\n                            \n                            Eigen::Vector4d eigen_x_ = eigen_A_.fullPivHouseholderQr().solve(eigen_b_);\n                            eigen_c_ = -0.5*eigen_x_.head<3>();\n                            radius = 0.5*std::sqrt(eigen_c_.squaredNorm() - 4*eigen_x_(3) );\n                        }\n\n                        // Ceres NLS solver\n                        ceres::Problem ceres_problem;\n                        ceres::Solver::Options ceres_options;\n                        ceres::Solver::Summary ceres_summary;\n\n                        // Residual blocks\n                        for (std::vector<Eigen::Vector3d>::iterator it_ = points_.begin(); it_ != points_.end(); ++it_) {\n                            ceres::CostFunction* cost_function =\n                                new ceres::AutoDiffCostFunction<SphereCostFunctor, 1, 3, 1>\n                                                                (new SphereCostFunctor(*it_) );\n                            ceres_problem.AddResidualBlock(cost_function, NULL, eigen_c_.data(), &radius);\n                        }\n\n                        // Set solver options\n                        ceres_options.linear_solver_type = ceres::DENSE_SCHUR;\n\n                        // Solve NLS problem\n                        Solve(ceres_options, &ceres_problem, &ceres_summary);\n                        // ROS_INFO_STREAM(ceres_summary.FullReport() << std::endl);\n\n                        // for (std::vector<Eigen::Vector3d>::iterator it_ = points_.begin(); it_ != points_.end(); ++it_) {\n                        //     eigen_tool_.translation() += eigen_msg_.rotation().inverse()*(eigen_c_ - *it_);\n                        // }\n                        // eigen_tool_.translation() /= n_points;\n\n\n                        if (n_points > 4) {\n                            eigen_tool_.translation() += (eigen_msg_.rotation().inverse()*(eigen_c_ - eigen_point_) - \n                                                          eigen_tool_.translation() ) / n_points;\n                        } else {\n                            eigen_tool_.translation() = eigen_msg_.rotation().inverse()*(eigen_c_ - eigen_point_);\n                        }\n                        \n                        \n                        // eigen_tool_.translation() = Eigen::Vector3d(0., 0., std::abs(radius) );\n                        tf_msg_tool_.transform = tf2::eigenToTransform(eigen_tool_).transform;\n                        static_tf_broadcaster_.sendTransform(tf_msg_tool_);\n\n                        T_x = sophus_ros_conversions::transformMsgToSophus(tf_msg_tool_.transform).cast<double>();\n\n                        ROS_INFO_STREAM(\"Sphere center point (relative to tracker): \\n\" << eigen_tool_.translation().matrix() );\n                        ROS_INFO_STREAM(\"Sphere radius: \" << eigen_tool_.translation().norm() );\n                        ROS_INFO_STREAM(\"rosrun tf2_ros static_transform_publisher \" << tf_msg_tool_.transform.translation.x << \" \"\n                                                                                     << tf_msg_tool_.transform.translation.y << \" \"\n                                                                                     << tf_msg_tool_.transform.translation.z << \" \"\n                                                                                     << tf_msg_tool_.transform.rotation.x << \" \"\n                                                                                     << tf_msg_tool_.transform.rotation.y << \" \"\n                                                                                     << tf_msg_tool_.transform.rotation.z << \" \"\n                                                                                     << tf_msg_tool_.transform.rotation.w << \" \"\n                                                                                     << tracker_frame << \" \" << tool_frame);\n\n                        rviz_tools_->deleteAllMarkers();\n                        rviz_tools_->publishSphere(eigen_c_, rviz_visual_tools::BLUE, 2*radius);\n                        rviz_tools_->trigger();\n\n                        if (n_points == 4) {\n                            // Publish tool mesh\n                            rviz_mesh_tools_->publishMesh(Eigen::Affine3d::Identity(),\n                                                        \"package://vive_calibrating/meshes/spike.dae\",\n                                                        rviz_visual_tools::BLACK,\n                                                        1,\n                                                        tool_frame);\n                            rviz_mesh_tools_->trigger();\n                        }\n                    }\n                }\n\n                // if (state == STATE_CHECKERBOARD_POINTS) {\n                //     tracker_poses_.push_back(sophus_ros_conversions::transformMsgToSophus(tf_msg_.transform).cast<double>() );\n                //     ROS_INFO_STREAM(\"Pose \" << tracker_poses_.size() << \"/\" << checkerboard_points_.size() << \":\");\n\n                //     rviz_tools_->publishSphere((eigen_msg_ * eigen_tool_).translation(), rviz_visual_tools::BLUE, rviz_visual_tools::XLARGE);\n\n                //     if (tracker_poses_.size() == checkerboard_points_.size() ) {\n                //         // Ceres NLS solver\n                //         ceres::Problem ceres_problem;\n                //         ceres::Solver::Options ceres_options;\n                //         ceres::Solver::Summary ceres_summary;\n\n                //         ceres_problem.AddParameterBlock(T_x.data(), Sophus::SE3d::num_parameters,\n                //                                         new Sophus::test::LocalParameterizationSE3);\n\n                //         // Residual blocks\n                //         for (int i = 0; i < tracker_poses_.size(); i++) {\n                //             ceres::CostFunction* cost_function =\n                //                 new ceres::AutoDiffCostFunction<CheckerboardCostFunctor, 3, Sophus::SE3d::num_parameters>\n                //                                                 (new CheckerboardCostFunctor(tracker_poses_[i],\n                //                                                                              checkerboard_points_[i]) );\n                //             ceres_problem.AddResidualBlock(cost_function, NULL, T_x.data() );\n                //         }\n\n                //         // Set solver options\n                //         ceres_options.linear_solver_type = ceres::DENSE_SCHUR;\n\n                //         // Solve NLS problem\n                //         Solve(ceres_options, &ceres_problem, &ceres_summary);\n                //         ROS_INFO_STREAM(ceres_summary.FullReport() << std::endl);\n\n                //         tf_msg_tool_.transform = sophus_ros_conversions::sophusToTransformMsg(T_x.cast<float>() );\n                //         tf_msg_tool_.header.stamp = ros::Time::now();\n\n                //         static_tf_broadcaster_.sendTransform(tf_msg_tool_);\n                //         ROS_INFO_STREAM(tf_msg_tool_);\n                //     }\n                // }\n            } else {\n                ROS_WARN_STREAM(\"Can't transform from \" + world_frame + \" to \" + tracker_frame + \": \" + pError);\n            }\n        }\n    }\n\n    // if (msg_.buttons[0]) { // Menu button\n    //     if (state == STATE_SPHERE_POINTS) {\n    //         if (points_.size() >= 4) {\n    //             ROS_INFO_STREAM(\"Define checkerboard points\");\n    //             state = STATE_CHECKERBOARD_POINTS;\n    //         }\n    //     }\n    // }\n\n    // if (msg_.buttons[3]) { // Trigger button\n    //     joy_feedback_pub_.publish(joy_feedback_msg_);\n\n    //     points_.push_back(eigen_point_);\n    //     ROS_INFO_STREAM(\"Point \" << n_points << \": \\n\" << eigen_point_.matrix() );\n    // }\n}\n\nbool ToolCalibratingNode::Init() {\n      /**\n     * Check if the necessary transforms are available and initialize the node\n     */\n\n    nh_.param<std::string>(\"/vive_node/world_frame\", world_frame, \"root\");\n\n    // Get available controller\n    while ((controller_frame.empty() || tracker_frame.empty() ) && sigint_flag) {\n        ROS_INFO(\"Waiting for controller and tracker...\");\n        \n        ros::spinOnce();\n        ros::Duration(3.0).sleep();\n    }\n\n    // Handle sigint\n    if (!sigint_flag) {\n        return false;\n    }\n\n    ROS_INFO_STREAM(\"Using \" + controller_frame + \" and \" + tracker_frame + \" for calibration\");\n\n    // Subscribe to joy topic\n    joy_sub_ = nh_.subscribe(\"/vive_node/joy/\" + controller_frame, 1, &ToolCalibratingNode::JoyCb, this);\n\n    // Check if transforms are available\n    std::string pError;\n    if (!tf_buffer_.canTransform(controller_frame,\n                                 world_frame, ros::Time(0),\n                                 ros::Duration(10.0), &pError) )\n    {\n        ROS_ERROR_STREAM(\"Can't transform from \" + world_frame + \" to \" + controller_frame + \": \" + pError);\n\n        return false;\n    }\n    if (!tf_buffer_.canTransform(tracker_frame,\n                                    world_frame, ros::Time(0),\n                                    ros::Duration(0.), &pError) )\n    {\n        ROS_WARN_STREAM(\"Can't transform from \" + world_frame + \" to \" + tracker_frame + \": \" + pError);\n\n        return false;\n    }\n\n    joy_feedback_msg_.id = controller_id;\n\n    tool_frame = tracker_frame + \"_tool0\";\n    tf_msg_tool_.header.frame_id = tracker_frame;\n    tf_msg_tool_.child_frame_id = tool_frame;\n\n    // Limited marker lifetime\n    rviz_tools_->setAlpha(0.5);\n    rviz_tools_->setLifetime(0.);\n\n    rviz_tools_->setBaseFrame(tracker_frame);\n    rviz_tools_->enableFrameLocking();\n\n    // Publish red sphere at tracker's position\n    rviz_tools_->publishSphere(Eigen::Vector3d(0., 0., 0.), rviz_visual_tools::RED, rviz_visual_tools::XLARGE);\n    rviz_tools_->trigger();\n\n    rviz_tools_->setBaseFrame(world_frame);\n    rviz_tools_->enableFrameLocking(false);\n\n    rviz_mesh_tools_->loadMarkerPub(false, true);\n    rviz_mesh_tools_->enableFrameLocking();\n    rviz_mesh_tools_->setBaseFrame(tool_frame);\n    rviz_mesh_tools_->setLifetime(0.);\n    \n    return true;\n}\n\nvoid ToolCalibratingNode::Loop() {\n    ros::spinOnce();\n    loop_rate_.sleep();\n}\nvoid ToolCalibratingNode::Shutdown() {\n      /**\n     * Runs before shutting down the node\n     */\n\n    ros::shutdown();\n}\n\n\nint main(int argc, char** argv) {\n    ros::init(argc, argv, \"tool_calibration_node\");\n\n    // Handle signal [ctrl + c]\n    signal(SIGINT, IntHandler);\n\n    ToolCalibratingNode node_(60);\n\n    if (!node_.Init() ) {\n        node_.Shutdown();\n\n        // Handle sigint\n        if (sigint_flag) {\n            exit(EXIT_SUCCESS);\n        } else {\n            exit(EXIT_FAILURE);\n        }\n    }\n\n    while (ros::ok() && sigint_flag) {\n        node_.Loop();\n    }\n\n    node_.Shutdown();\n    exit(EXIT_SUCCESS);\n}", "meta": {"hexsha": "ea57e3689b8cf65406fdaf4334aeec79843bb442", "size": 18428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vive_calibrating/src/tool_calibrating_node.cpp", "max_stars_repo_name": "mortaas/vive_rrcc", "max_stars_repo_head_hexsha": "cdec4645dd3bc1510e15af4be20c7f8dfef321e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T02:19:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-14T02:19:56.000Z", "max_issues_repo_path": "vive_calibrating/src/tool_calibrating_node.cpp", "max_issues_repo_name": "mortaas/vive_rrcc", "max_issues_repo_head_hexsha": "cdec4645dd3bc1510e15af4be20c7f8dfef321e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vive_calibrating/src/tool_calibrating_node.cpp", "max_forks_repo_name": "mortaas/vive_rrcc", "max_forks_repo_head_hexsha": "cdec4645dd3bc1510e15af4be20c7f8dfef321e0", "max_forks_repo_licenses": ["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.6850715746, "max_line_length": 144, "alphanum_fraction": 0.537551552, "num_tokens": 4118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5703544148275731}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// survival::modelss::exponential::scalar::meta::failure_time_distribution.hpp \t//\n//                                                                              //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                   //\n//  Software License, Version 1.0. (See accompanying file                       //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)            //\n//////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_FAILURE_TIME_DISTRIBUTION_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_FAILURE_TIME_DISTRIBUTION_HPP_ER_2009\n#include <cmath>\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/is_math_distribution.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/exponential/random.hpp>\n#include <boost/statistics/detail/distribution/survival/failure_time/meta/distribution.hpp>\n#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/model.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival{\nnamespace failure_time{\n\n    template<typename T,typename L>\n    struct distribution< exponential_model<T,L> >\n    {\n\n        typedef exponential_model<T,L> model_;\n        typedef boost::math::exponential_distribution<T> type;\n        \n        template<typename X>\n        static type call(const X& x, const model_& mo){\n            T lambda = mo.log_rate(x);\n            lambda = exp( lambda );\n            return type(\n                lambda\n            );\n        }        \n    };\n\n}// failure_time\n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "a4c81986f278a25353c0a37402182f0f425ba431", "size": 1959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/failure_time_distribution.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/failure_time_distribution.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/models/exponential/scalar/meta/failure_time_distribution.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8125, "max_line_length": 122, "alphanum_fraction": 0.6334864727, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.570354396502281}}
{"text": "// std includes\n#include <iostream> // cout, endl\n#include <vector>\n#include <random> // random_device, default_random_engine, uniform_int_distribution\n#include <algorithm> // generate\n// thirdparties includes\n#include <Eigen/Dense>\n// lib includes\n#include \"m0sh/non_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::NonUniform<TypeVector, TypeRef, TypeContainer>;\n// Data\nconst std::size_t n = 10;\nconst double dx = 0.1;\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    // Build axis\n    TypeContainer<double> axis(n+1);\n    std::generate(axis.begin(), axis.end(), [x = 0.0] () mutable { return x += dx; });\n    // Build grid\n    TypeContainer<TypeContainer<double>> grid(DIM, axis);\n    // Build mesh finally\n    TypeMesh mesh(grid, 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(0, n);\n    // Print\n    print(mesh, uniform, e);\n    print(mesh, uniform, e);\n    print(mesh, uniform, e);\n}\n", "meta": {"hexsha": "1c23e11a5940f08cdc49977bf3cb0223ed64f00e", "size": 1982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/non_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/non_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/non_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": 34.1724137931, "max_line_length": 138, "alphanum_fraction": 0.6190716448, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5703294210978743}}
{"text": "//\n//  meanie3D-detect\n//  cf-algorithms\n//\n//  Created by Jürgen Lorenz Simon on 5/3/12.\n//  Copyright (c) 2012 Jürgen Lorenz Simon. All rights reserved.\n//\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/progress.hpp>\n#include <boost/date_time.hpp>\n#include <boost/date_time/local_time/local_time.hpp>\n#include <sstream>\n\n#include <meanie3D/meanie3D.h>\n#include <radolan/radolan.h>\n\n#include <map>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <exception>\n#include <locale>\n#include <limits>\n#include <stdlib.h>\n#include <netcdf>\n#include <time.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost;\nusing namespace netCDF;\nusing namespace m3D;\n\nnamespace fs = boost::filesystem;\n\ntypedef enum\n{\n    ShiftedPropertiesSatellite = 0,\n    ShiftedPropertiesOthers = 1,\n} ShiftedProperties;\n\n\n#pragma mark -\n#pragma mark Definitions\n\n#define WRITE_PARALLAX_VECTORS 1\n\n/** Feature-space data type\n */\ntypedef double T;\n\n#pragma mark -\n#pragma mark Command line parsing\n\nvoid parse_commmandline(program_options::variables_map vm,\n        string &filename,\n        ShiftedProperties &shifted)\n{\n    if (vm.count(\"file\") == 0)\n    {\n        cerr << \"Missing 'file' argument\" << endl;\n\n        exit(1);\n    }\n\n    filename = vm[\"file\"].as<string>();\n\n    std::string shifted_name = vm[\"shifted\"].as<string>();\n\n    if (!(shifted_name == \"satellite\" || shifted_name == \"other\"))\n    {\n        cerr << \"Illegal value for argument 'shifted'. Only 'satellite' or 'others' are accepted.\" << endl;\n        exit(1);\n    }\n\n    if (shifted_name == \"satellite\")\n    {\n        shifted = ShiftedPropertiesSatellite;\n    } else\n    {\n        shifted = ShiftedPropertiesOthers;\n    }\n};\n\n#pragma mark -\n#pragma mark Worker Methods\n\ntemplate <typename T>\nT SQR(const T &x)\n{\n    return x * x;\n}\n\n/** This is a c++ translation of the method sent to me by Marianne Koenig (in F90):\n *\n * <cite>\n * Subroutine does a parallax correction for something seen at some\n * height in a position lat/lon by the satellite given by satheight,\n * satlat, satlon. The new coordinates are returned in latcorr and loncorr\n * </cite>\n *\n * @param satheight (REAL): height of the satellite in km\n * @param satlat (REAL): subsatellite latitude (deg, N is positive)\n * @param satlon (REAL): subsatellite longitude (deg, E is positive)\n * @param height (REAL): height of the cloud (km)\n * @param lat (REAL): latitude of the satellite pixel (N is positive)\n * @param lon (REAL): longitude of the satellite pixel (E is positive)\n */\ntemplate <typename T>\nvoid parallax(T satheight, T satlat, T satlon, T height, T lat, T lon, T& latcorr, T& loncorr)\n{\n    T dpi;\n    T radius_eq;\n    T radius_pole;\n    T radius_ratio;\n    T mean_radius;\n    T dheight;\n    T alat, alon;\n    T asatlat, asatlon;\n    T satlat_geod, satlon_geod;\n    T xsat, ysat, zsat;\n    T xsurf, ysurf, zsurf;\n    T alat_geod;\n    T radius_surf;\n    T radius_ratio_local;\n    T xdiff, ydiff, zdiff;\n    T xfact, zen;\n    T e1, e2, e3;\n    T corr;\n    T xcorr, ycorr, zcorr;\n\n    dpi = 3.14159265;\n\n    // varius earth radius information\n\n    radius_eq = 6378.077;\n    dheight = satheight;\n    radius_pole = 6356.577;\n    radius_ratio = radius_eq / radius_pole;\n    mean_radius = 0.5 * (radius_eq + radius_pole);\n    zdiff = 0.0;\n\n    //     angle conversion to radians\n\n    asatlat = satlat * dpi / 180.0;\n    asatlon = satlon * dpi / 180.0;\n    alat = lat * dpi / 180.0;\n    alon = lon * dpi / 180.0;\n\n    //     cartesian coordinates for the satellite\n    //     satlat_geod is the geodetic satellite latitude\n\n    satlat_geod = atan(tan(asatlat) * SQR(radius_ratio));\n    xsat = dheight * cos(satlat_geod) * sin(asatlon);\n    ysat = dheight * sin(satlat_geod);\n    zsat = dheight * cos(satlat_geod) * cos(asatlon);\n\n    //     cartesian coordinates of the surface point\n\n    alat_geod = atan(tan(alat) * SQR(radius_ratio));\n    radius_surf = radius_eq / sqrt(SQR(cos(alat_geod)) + SQR(radius_ratio) * SQR(sin(alat_geod)));\n    xsurf = radius_surf * cos(alat_geod) * sin(alon);\n    ysurf = radius_surf * sin(alat_geod);\n    zsurf = radius_surf * cos(alat_geod) * cos(alon);\n\n    //     compute new radius ratio depending on height\n\n    radius_ratio_local = SQR((radius_eq + height) / (radius_pole + height));\n\n    //     Satellite minus surface location\n\n    xdiff = xsat - xsurf;\n    ydiff = ysat - ysurf;\n    zdiff = zsat - zdiff;\n\n    //     compute local zenith angle\n\n    xfact = sqrt(SQR(xdiff) + SQR(ydiff) + SQR(zdiff));\n    zen = (xdiff * xsurf + ydiff * ysurf + zdiff * zsurf) / (mean_radius * xfact);\n    zen = acos(zen);\n    zen = zen * 180.0 / dpi;\n\n    //     equation to solve for the line of sight at height Z\n\n    e1 = SQR(xdiff) + radius_ratio_local * SQR(ydiff) + SQR(zdiff);\n    e2 = 2.0 * (xsurf * xdiff + radius_ratio_local * ysurf * ydiff + zsurf * zdiff);\n    e3 = SQR(xsurf) + SQR(zsurf) + radius_ratio_local * SQR(ysurf) - SQR(radius_eq + height);\n\n    corr = (sqrt(e2 * e2 - 4.0 * e1 * e3) - e2) / 2.0 / e1;\n\n    //     corrected surface coordinates\n\n    xcorr = xsurf + corr*xdiff;\n    ycorr = ysurf + corr*ydiff;\n    zcorr = zsurf + corr*zdiff;\n\n    //     convert back to latitude and longitude\n\n    latcorr = atan(ycorr / sqrt(SQR(xcorr) + SQR(zcorr)));\n    latcorr = atan(tan(latcorr) / SQR(radius_ratio)) * 180.0 / dpi;\n\n    loncorr = atan2(xcorr, zcorr) * 180.0 / dpi;\n}\n\ntemplate <typename T>\nT** allocate_array(size_t dim_y, size_t dim_x)\n{\n    T **array = new T*[dim_y];\n    for (int i = 0; i < dim_y; ++i)\n        array[i] = new T[dim_x];\n    return array;\n}\n\n#define deallocate_array(array,dim) for (int i=0; i<dim; i++) delete[] array[i]; delete[] array;\n\n/** Corrects the parallax on all seviri satellite variables\n * in the national 2D OASE composite\n * @param in_path path to the netcdf file to be corrected. The data\n * in the file is overwritten.\n */\nvoid correct_parallax(boost::filesystem::path in_path, const ShiftedProperties shifted)\n{\n    // Some constants\n    const double SAT_LON = 9.5; // longitude of METEOSAT-9\n    const double SAT_LAT = 0.0; // latitute of METEOSAT-9\n    const double SAT_HEIGHT = 35785.83; // height of METEOSAT-9 [km]\n\n#define dim_x 900\n#define dim_y 900\n\n    try\n    {\n        NcFile file(in_path.generic_string(), NcFile::write);\n\n        try\n        {\n            std::string type;\n            file.getAtt(\"parallax_corrected\").getValues(type);\n            cout << \"Parallax is already corrected (parallax_corrected=\" << type << \")\" << endl;\n            cout << \"Skipping file\" << endl;\n            return;\n        } catch (const netCDF::exceptions::NcBadId &e)\n        {\n        }\n\n        typedef std::multimap<std::string, NcVar> vmap_t;\n\n        vmap_t variables = file.getVars();\n\n        // Cloud-Top-Height is needed as input\n\n        static float cloud_top_height[dim_y][dim_x];\n\n        float cth_min = std::numeric_limits<float>::max();\n        float cth_max = std::numeric_limits<float>::min();\n\n        vmap_t::iterator fi = variables.find(\"msevi_l2_nwcsaf_cth\");\n        if (fi == variables.end())\n        {\n            cerr << \"ERROR: could not find cloud top height (msevi_l2_nwcsaf_cth) variable\" << endl;\n            return;\n        }\n\n        fi->second.getVar(&cloud_top_height[0][0]);\n\n        float cth_scale_factor = 1.0;\n        float cth_offset = 0.0;\n        float cth_valid_min, cth_valid_max;\n        float cth_fill_value = std::numeric_limits<float>::min();\n\n        fi->second.getAtt(\"scale_factor\").getValues(&cth_scale_factor);\n        fi->second.getAtt(\"add_offset\").getValues(&cth_offset);\n        fi->second.getAtt(\"_FillValue\").getValues(&cth_fill_value);\n        fi->second.getAtt(\"valid_min\").getValues(&cth_valid_min);\n        fi->second.getAtt(\"valid_max\").getValues(&cth_valid_max);\n\n        // create a variable for input and one for output\n\n        static int corrected_iy[dim_y][dim_x];\n        static int corrected_ix[dim_y][dim_x];\n\n        // initialize output data with flag to find pixels\n        // later that have not been set\n\n        for (size_t iy = 0; iy < dim_y; iy++)\n        {\n            for (size_t ix = 0; ix < dim_x; ix++)\n            {\n                corrected_ix[iy][ix] = 0;\n                corrected_iy[iy][ix] = 0;\n\n                if (cloud_top_height[iy][ix] < cth_valid_min\n                        || cloud_top_height[iy][ix] > cth_valid_max\n                        || cloud_top_height[iy][ix] == cth_fill_value)\n                {\n                    cloud_top_height[iy][ix] = 0.0;\n                } else\n                {\n                    cloud_top_height[iy][ix] = cth_scale_factor * cloud_top_height[iy][ix] + cth_offset;\n                }\n\n                if (cloud_top_height[iy][ix] > cth_max)\n                    cth_max = cloud_top_height[iy][ix];\n\n                if (cloud_top_height[iy][ix] < cth_min)\n                    cth_min = cloud_top_height[iy][ix];\n            }\n        }\n\n        // cout << endl << \"cth_min=\" << cth_min << \" cth_max=\" << cth_max << endl;\n\n        // Coordinate system for lat/lon transformation\n\n        RDCoordinateSystem rcs(RD_RX);\n\n        typedef std::vector< std::vector<T> > vec_list_t;\n\n#if WRITE_PARALLAX_VECTORS\n        vec_list_t origins;\n        vec_list_t correction_vectors;\n#endif\n        // correct the parallax\n\n        for (size_t iy = 0; iy < dim_y; iy++)\n        {\n            for (size_t ix = 0; ix < dim_x; ix++)\n            {\n                RDGridPoint gp = rdGridPoint(ix, iy);\n\n                // get lat/lon for this pixel\n                RDGeographicalPoint coord = rcs.geographicalCoordinate(gp);\n\n                // Get Marianne Koenig's correction values\n\n                T cth = boost::numeric_cast<float> (cloud_top_height[iy][ix]) / 1000.0f;\n\n                T lat_corrected = 0;\n                T lon_corrected = 0;\n\n                parallax<double> (SAT_HEIGHT, SAT_LAT, SAT_LON, cth, coord.latitude, coord.longitude, lat_corrected, lon_corrected);\n\n                //                if (cth > 0)\n                //                {\n                //                    T lat_corr_0, lon_corr_0;\n                //                    parallax<double> ( SAT_HEIGHT, SAT_LAT, SAT_LON, 0, coord.latitude, coord.longitude, lat_corr_0, lon_corr_0 );\n                //                    cout << \"(lat=\"<<coord.latitude << \"N,lon=\"<<coord.longitude<<\"E,cth=\"<<cth<<\"km)\"\n                //                        << \" (lat_corr=\"<<lat_corrected<<\",lon_corr=\"<<lon_corrected<<\")\"\n                //                        << \" @cth=0.0:\"\n                //                        << \" (lat_corr=\"<<lat_corr_0<<\",lon_corr=\"<<lon_corr_0<<\")\"\n                //                        << endl;\n                //                }\n\n                RDGeographicalPoint coord_corrected;\n\n                // Figure out the grid point again and set\n                // data at corrected position\n\n                if (shifted == ShiftedPropertiesSatellite)\n                {\n                    // The correction shifts the satellite data to the\n                    // corrected position. The parallax of the satellite\n                    // is now corrected, but the other data stays in place\n\n                    coord_corrected.latitude = lat_corrected;\n                    coord_corrected.longitude = lon_corrected;\n                } else\n                {\n                    // The correction shifts the other data to the\n                    // corrected position. The parallax of the satellite\n                    // is not corrected, but the other data is shifted\n                    // to be congruent\n\n                    // Experimental\n\n                    T dLat = (lat_corrected - coord.latitude);\n                    T dLon = (lon_corrected - coord.longitude);\n\n                    coord_corrected.latitude = coord.latitude - dLat;\n                    coord_corrected.longitude = coord.longitude - dLon;\n                }\n\n                bool is_inside = false;\n                RDGridPoint gp_corrected = rcs.gridPoint(coord_corrected, is_inside);\n\n                // Figure out the parallax vector\n                RDCartesianPoint cartesian = rcs.cartesianCoordinate(gp);\n                RDCartesianPoint cartesian_corr = rcs.cartesianCoordinate(gp_corrected);\n\n                // TODO: what if two pixels are moved to the same place?\n                // The way things are now is 'last write wins'\n\n                if (is_inside)\n                {\n#if WRITE_PARALLAX_VECTORS\n                    vector<T> origin(2);\n                    origin[0] = cartesian.x;\n                    origin[1] = cartesian.y;\n                    origins.push_back(origin);\n\n                    vector<T> correction(2);\n                    correction[0] = cartesian_corr.x - cartesian.x;\n                    correction[1] = cartesian_corr.y - cartesian.y;\n                    correction_vectors.push_back(correction);\n#endif\n                    corrected_ix[iy][ix] = gp_corrected.ix;\n                    corrected_iy[iy][ix] = gp_corrected.iy;\n                }\n            }\n        }\n#if WITH_VTK\n#if WRITE_PARALLAX_VECTORS\n\n        string vector_path = in_path.filename().stem().string() + \"-parallax.vtk\";\n        VisitUtils<T>::write_vectors_vtk(vector_path, origins, correction_vectors, \"parallax\");\n#endif\n#endif\n\n        static int input_data[dim_y][dim_x];\n        static int output_data[dim_y][dim_x];\n\n        for (vmap_t::iterator vi = variables.begin(); vi != variables.end(); vi++)\n        {\n            NcVar variable = vi->second;\n\n            int fill_value = 0;\n            try\n            {\n                // Get the official _FillValue value if the\n                // variable has one\n                NcVarAtt fillValue = variable.getAtt(\"_FillValue\");\n                fillValue.getValues(&fill_value);\n            } catch (netCDF::exceptions::NcException e)\n            {\n                // if not, put the value just outside the valid range\n                int valid_min = std::numeric_limits<int>::min();\n                fill_value = valid_min - 1;\n            }\n\n            if ((shifted == ShiftedPropertiesSatellite && boost::starts_with(variable.getName(), \"msevi_\"))\n                    || (shifted == ShiftedPropertiesOthers && !boost::starts_with(variable.getName(), \"msevi_\")))\n            {\n                // Initialize arrays\n\n                cout << \"Correcting \" << variable.getName() << \" ... \";\n\n                for (size_t iy = 0; iy < dim_y; iy++)\n                {\n                    for (size_t ix = 0; ix < dim_x; ix++)\n                    {\n                        input_data[iy][ix] = 0;\n                        output_data[iy][ix] = fill_value;\n                    }\n                }\n\n                // Read the satellite variable\n\n                variable.getVar(&input_data[0][0]);\n\n                // apply the correction derived from cloud top height\n\n                for (size_t iy = 0; iy < dim_y; iy++)\n                {\n                    for (size_t ix = 0; ix < dim_x; ix++)\n                    {\n                        // get corrected indicees\n\n                        size_t iy_corr = corrected_iy[iy][ix];\n                        size_t ix_corr = corrected_ix[iy][ix];\n\n                        // copy data over\n\n                        output_data[iy_corr][ix_corr] = input_data[iy][ix];\n                    }\n                }\n\n                // TODO: post-processing of points that got no values\n\n                for (size_t iy = 0; iy < dim_y; iy++)\n                {\n                    for (size_t ix = 0; ix < dim_x; ix++)\n                    {\n                        if (output_data[iy][ix] == fill_value)\n                        {\n                            if (variable.getName() == \"msevi_l2_nwcsaf_ct\" || variable.getName() == \"msevi_l2_nwcsaf_cma\")\n                            {\n                                // use the most prevalent value in 25 neighborhood\n                                map<int, int> value_count;\n\n                                int num_values = 0;\n                                int interpolation_width = 2;\n                                int min_neighbours = 8;\n\n                                for (int iiy = iy - interpolation_width; iiy < iy + interpolation_width; iiy++)\n                                {\n                                    for (int iix = ix - interpolation_width; iix < ix + interpolation_width; iix++)\n                                    {\n                                        if (iix == ix && iiy == iy) continue;\n\n                                        if (iiy >= 0 && iiy < dim_y && iix >= 0 && iix < dim_x)\n                                        {\n                                            if (output_data[iiy][iix] != fill_value)\n                                            {\n                                                int val = boost::numeric_cast<int>(output_data[iiy][iix]);\n\n                                                map<int, int>::iterator mi = value_count.find(val);\n\n                                                if (mi == value_count.end())\n                                                {\n                                                    value_count[val] = 1;\n                                                } else\n                                                {\n                                                    mi->second = mi->second + 1;\n                                                }\n\n                                                num_values++;\n                                            }\n                                        }\n                                    }\n                                }\n\n                                // only replace if you have at least 4 valid neighbours\n\n                                if (num_values >= min_neighbours)\n                                {\n                                    int most_used = value_count.begin()->first;\n\n                                    for (map<int, int>::iterator mi = value_count.begin(); mi != value_count.end(); ++mi)\n                                    {\n                                        if (mi->second > value_count[most_used])\n                                        {\n                                            most_used = mi->first;\n                                        }\n                                    }\n\n                                    output_data[iy][ix] = most_used;\n                                }\n                            } else\n                            {\n                                // replace with geometric average of 25 neighborhood\n\n                                T sum = 0.0;\n                                int num_values = 0;\n\n                                int interpolation_width = 2;\n                                int min_neighbours = 8;\n\n                                for (int iiy = iy - interpolation_width; iiy < iy + interpolation_width; iiy++)\n                                {\n                                    for (int iix = ix - interpolation_width; iix < ix + interpolation_width; iix++)\n                                    {\n                                        if (iix == ix && iiy == iy) continue;\n\n                                        if (iiy >= 0 && iiy < dim_y && iix >= 0 && iix < dim_x)\n                                        {\n                                            if (output_data[iiy][iix] != fill_value)\n                                            {\n                                                sum += output_data[iiy][iix];\n                                                num_values++;\n                                            }\n                                        }\n                                    }\n                                }\n\n                                // only replace if you have at least 4 valid neighbours\n\n                                if (num_values >= min_neighbours)\n                                {\n                                    output_data[iy][ix] = (sum / num_values);\n                                }\n                            }\n                        }\n                    }\n                }\n\n                // Write data back\n\n                variable.putVar(&output_data[0][0]);\n\n                cout << \"done.\" << endl;\n            }\n        }\n\n        nc_redef(file.getId());\n        file.putAtt(\"parallax_corrected\", (shifted == ShiftedPropertiesSatellite ? \"satellite\" : \"others\"));\n        nc_enddef(file.getId());\n\n    } catch (netCDF::exceptions::NcException &e)\n    {\n        cerr << \"ERROR:exception \" << e.what() << endl;\n        return;\n    }\n\n}\n\n#pragma mark -\n#pragma mark MAIN\n\n/* MAIN\n */\nint main(int argc, char** argv)\n{\n    using namespace m3D;\n\n    // Declare the supported options.\n\n    program_options::options_description desc(\"Applies parallax correction to mseviri satellite data in OASE composite files.\");\n    desc.add_options()\n            (\"help\", \"Produces this help.\")\n            (\"version\", \"print version information and exit\")\n            (\"file,f\", program_options::value<string>(), \"A single file or a directory to be processed. Only files ending in .nc will be processed.\")\n            (\"shifted,s\", program_options::value<string>()->default_value(\"satellite\"), \"Which values are to be shifted? [satellite|other] (default:satellite)\");\n\n    program_options::variables_map vm;\n\n    try\n    {\n        program_options::store(program_options::parse_command_line(argc, argv, desc), vm);\n        program_options::notify(vm);\n    } catch (std::exception &e)\n    {\n        cerr << \"ERROR:parsing command line caused exception: \" << e.what()\n                << \":check meanie3D-trackplot --help for command line options\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // Version\n\n    if (vm.count(\"version\") != 0)\n    {\n        cout << m3D::VERSION << endl;\n        exit(EXIT_SUCCESS);\n    }\n\n    if (vm.count(\"help\") == 1 || argc < 2)\n    {\n        cout << desc << \"\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    // Evaluate user input\n\n    string source_path;\n    ShiftedProperties shifted = ShiftedPropertiesSatellite;\n\n    try\n    {\n        parse_commmandline(vm, source_path, shifted);\n    } catch (const std::exception &e)\n    {\n        cerr << \"FATAL:\" << e.what() << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    typedef set<fs::path> fset_t;\n\n    fset_t files;\n\n    if (fs::is_directory(source_path))\n    {\n        fs::directory_iterator dir_iter(source_path);\n        fs::directory_iterator end;\n\n        while (dir_iter != end)\n        {\n            fs::path f = dir_iter->path();\n\n            if (fs::is_regular_file(f) && fs::extension(f) == \".nc\")\n            {\n                //cout << \"Adding \" << f.generic_string() << endl;\n                files.insert(f);\n            } else\n            {\n                cout << \"Skipping \" << f.generic_string() << endl;\n            }\n\n            dir_iter++;\n        }\n    } else\n    {\n        fs::path f = fs::path(source_path);\n\n        std::string extension = fs::extension(f);\n\n        if (fs::is_regular_file(f) && extension == \".nc\")\n        {\n            files.insert(f);\n        }\n    }\n\n    fset_t::iterator it;\n\n    //\tboost::progress_display *progress = NULL;\n\n    //\tif ( files.size() > 1 ) {\n    //\t\tprogress = new progress_display ( files.size() );\n    //\t}\n\n    for (it = files.begin(); it != files.end(); ++it)\n    {\n        //\t\tif ( progress != NULL ) {\n        //\t\t\tprogress->operator++();\n        //\t\t}\n\n        boost::filesystem::path path = *it;\n\n        // Correct\n\n        try\n        {\n            cout << \"Correcting \" << path << \"...\";\n            correct_parallax(path, shifted);\n            cout << \"done.\" << endl;\n        } catch (std::exception &e)\n        {\n            cerr << \"ERORO:Exception processing \" << path.filename().generic_string()\n                    << \":\" << e.what() << endl;\n        }\n    }\n\n    //\tif ( progress != NULL ) {\n    //\t\tdelete progress;\n    //\t}\n\n    return 0;\n};\n", "meta": {"hexsha": "121cc1f647d6804ab957f2dd2e83c46e06ad62e4", "size": 24071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/executables/meanie3D-parallax_correction.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-parallax_correction.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-parallax_correction.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": 32.9739726027, "max_line_length": 161, "alphanum_fraction": 0.4971127082, "num_tokens": 5457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.5703294047387395}}
{"text": "/*\nТест алгоритма нахождения минимального остовного дерева\nиз библиотеки boost. Минимальное остовное дерево соединяет\nвершины графа так, что суммарный вес дерева минимальный.\n\nВ программе при компиляции граф можно представить как в\nвиде списка смежности (ADJ_LIST), так и в виде матрицы\nсмежности (ADJ_MATRIX)\n*/\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/graph_traits.hpp>\n\n#include <iostream>\n#include <utility>\n#include <algorithm>\n\n//использовать только совместно\n#include <boost/type_traits/ice.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n\n//#define ADJ_MATRIX\n#define ADJ_LIST\n\nusing namespace boost;\n\n//свойство ребер - вес (для нас - расстояние)\ntypedef property<edge_weight_t, double> EdgeWeightProperty;\n#ifdef ADJ_LIST\n//граф представлен в виде списка смежности\ntypedef boost::adjacency_list<vecS,vecS,undirectedS,no_property,EdgeWeightProperty> mygraph;\n#endif\n#ifdef ADJ_MATRIX\n//граф представлен в виде матрицы смежности\ntypedef boost::adjacency_matrix<undirectedS, no_property, EdgeWeightProperty> mygraph;\n#endif\n\ntypedef mygraph::edge_descriptor Edge;\n\nstruct Point2D\n{\n\tfloat x;\n\tfloat y;\n};\n\n//случайное число в интервале\nfloat RandomNum(float min, float max)\n{\n\treturn\n\t\tmin + static_cast<float>(rand()) \n\t\t/ (static_cast<float>(RAND_MAX) / (max - min));\n}\n\n//случайная точка\nPoint2D RandomPoint(float xmin,float ymin,float xmax,float ymax)\n{\n\tPoint2D p;\n\tp.x = RandomNum(xmin, xmax);\n\tp.y = RandomNum(ymin, ymax);\n\treturn p;\n}\n\n//расстояние между точками\nfloat Distance(Point2D a, Point2D b)\n{\n\tfloat dx = a.x - b.x;\n\tfloat dy = a.y - b.y;\n\treturn sqrt(dx*dx + dy*dy);\n}\n\nint main()\n{\n\tusing std::cout;\n\n\t//число точек\n\tconst int pnum = 600;\n\t//граничное расстояние между точками\n\t//если расстояние между точками меньше max_dst,\n\t//то между точками создается ребро графа,\n\t//иначе нет. Нужно для оптимизации расхода памяти программы\n\tconst float max_dst = 10.0;\n\t//создаем массив из хаотично расположенных точек\n\tPoint2D points[pnum];\n\tfor (int i = 0;i < pnum;i++)\n\t\tpoints[i] = RandomPoint(-100.0, -100.0, 100.0, 100.0);\n\n\tmygraph g(pnum);\n\n\t//в граф записываем все хаотично расположенные точки\n\tfor (int i = 0;i < pnum;i++)\n\t\tfor (int j = 0;j < pnum;j++)\n\t\t{\n\t\t\tfloat dst = Distance(points[i], points[j]);\n\t\t\tif (dst < max_dst)\n\t\t\t\tadd_edge(i, j, Distance(points[i], points[j]), g);\n\t\t}\n\n\n\tcout << \"number of edges: \" << num_edges(g) << std::endl;\n\tcout << \"number of vertices: \" << num_vertices(g) << std::endl;\n\t\n\t//обход графа\n\n\t//находим минимальное остовное дерево\n\t//оно в виде списка пар вершин\n\tstd::list<Edge> spanning_tree;\n\tkruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\t\n\tcout << \"spanning tree length: \" << spanning_tree.size() << std::endl;\n\n\tfor (std::list<Edge>::iterator i = spanning_tree.begin();\n\ti != spanning_tree.end();i++)\n\t{\n\t\t//достаем индексы вершин из spanning_tree\n\t\tEdge e = *i;\n\t\t//вершина, из которой идет ребро\n\t\tsize_t source_index = e.m_source;\n\t\t//вершина, в которую идет ребро\n\t\tsize_t dest_index = e.m_target;\n\t\t//просто выводим индексы, хотя можем делать что-то полезное\n\t\t//например, строить мостики между полигонами с заданными индексами\n\t\tprintf(\"src = %zd target = %zd\\n\", source_index, dest_index);\n\t}\n\tcout << std::endl;\n\n\tgetc(stdin);\n\treturn 0;\n}\n", "meta": {"hexsha": "c24790244b96ee6256e15d0ceba8079e015a1e93", "size": 3400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/msttest/Test.cpp", "max_stars_repo_name": "vladimir-inoz/maputils", "max_stars_repo_head_hexsha": "554fe1df70d8a77e572058b9e28ae717977ebc0a", "max_stars_repo_licenses": ["MIT"], "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/msttest/Test.cpp", "max_issues_repo_name": "vladimir-inoz/maputils", "max_issues_repo_head_hexsha": "554fe1df70d8a77e572058b9e28ae717977ebc0a", "max_issues_repo_licenses": ["MIT"], "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/msttest/Test.cpp", "max_forks_repo_name": "vladimir-inoz/maputils", "max_forks_repo_head_hexsha": "554fe1df70d8a77e572058b9e28ae717977ebc0a", "max_forks_repo_licenses": ["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.9541984733, "max_line_length": 92, "alphanum_fraction": 0.7282352941, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5702791291449617}}
{"text": "#include <g2o/core/base_unary_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/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <chrono>\n#include <iostream>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\nusing namespace std;\nusing namespace cv;\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// 像素坐标转相机归一化坐标\nPoint2d pixel2cam(const Point2d& p, const Mat& K);\n\nvoid bundleAdjustment(const vector<Point3f> points_3d,\n                      const vector<Point2f> points_2d, const Mat& K, Mat& R,\n                      Mat& t);\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  //-- 读取图像\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],\n                  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;\n  for (DMatch m : matches) {\n    ushort d = d1.ptr<unsigned short>(\n        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 / 1000.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  Mat r, t;\n  solvePnP(pts_3d, pts_2d, K, Mat(), r, t,\n           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  bundleAdjustment(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  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  // );\n  Ptr<DescriptorMatcher> matcher =\n      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  //即是最相似的和最不相似的两组点之间的距离\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  //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d& p, const Mat& K) {\n  return Point2d((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\nvoid bundleAdjustment(const vector<Point3f> points_3d,\n                      const vector<Point2f> points_2d, const Mat& K, Mat& R,\n                      Mat& t) {\n  // 初始化g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>>\n      Block;  // pose 维度为 6, landmark 维度为 3\n  Block::LinearSolverType* linearSolver =\n      new g2o::LinearSolverCSparse<Block::PoseMatrixType>();  // 线性方程求解器\n  Block* solver_ptr = new Block(linearSolver);  // 矩阵块求解器\n  g2o::OptimizationAlgorithmLevenberg* solver =\n      new g2o::OptimizationAlgorithmLevenberg(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 << 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, Eigen::Vector3d(t.at<double>(0, 0), t.at<double>(1, 0),\n                             t.at<double>(2, 0))));\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),\n      Eigen::Vector2d(K.at<double>(0, 2), K.at<double>(1, 2)), 0);\n  camera->setId(0);\n  optimizer.addParameter(camera);\n\n  // edges\n  index = 1;\n  for (const Point2f p : points_2d) {\n    g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n    edge->setId(index);\n    edge->setVertex(\n        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 =\n      chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"optimization costs time: \" << time_used.count() << \" seconds.\"\n       << endl;\n\n  cout << endl << \"after optimization:\" << endl;\n  cout << \"T=\" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n", "meta": {"hexsha": "0b2409144d28e7ae078e74f87a9c466abdebdb04", "size": 7140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d2d.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": "ch7/pose_estimation_3d2d.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": "ch7/pose_estimation_3d2d.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": 35.0, "max_line_length": 79, "alphanum_fraction": 0.6421568627, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5702791233555736}}
{"text": "#include \"test.hpp\"\n#include \"geometry/utils.hpp\"\n#include \"geometry/plane.hpp\"\n#include \"optim/deformingMesh.hpp\"\n#include <functional>\n\n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n\n#include \"polyscope/polyscope.h\"\n#include \"polyscope/surface_mesh.h\"\n#include \"polyscope/point_cloud.h\"\n\n#include <Eigen/Sparse>\n\n\n// Static variables declaration\nstd::unique_ptr<VertexPositionGeometry> Test::geometryFlat;\nstd::unique_ptr<VertexPositionGeometry> Test::newGeometry;\nstd::unique_ptr<ManifoldSurfaceMesh> Test::meshFlat;\nstd::unique_ptr<FaceData<Vector3>> Test::normals;\nFaceData<Vector3> Test::refNormals;\nstd::unique_ptr<VertexData<Vector3>> Test::bLoopData;\npolyscope::SurfaceMesh* Test::psReconsMesh;\nVertexData<Vector3> Test::debugGradient;\nfloat Test::lr = 0.04f;\nfloat Test::nw = 1.0f;\nint i = 0;\nint cpt = 0;\n\nTest::Test() {\n \n}\n\nbool adjacent(int i, int j, int W, int H){\n    return (i-j == -1 || i-j == 1 || i-j == W || i-j == -W);\n}\n\nvoid Test::callback1(){\n    // ImGui\n    ImGui::PushItemWidth(100);\n\n    ImGui::InputInt(\"Iterations : \", &i);            \n    ImGui::SliderFloat(\"LR : \", &lr, 0.001f, 0.05f);\n    ImGui::SliderFloat(\"Normal weight : \", &nw, 0.1f, 100.0f);\n\n    ImGui::PopItemWidth();\n\n    i++;\n    newGeometry = DeformingMesh::iterativeSolve(*meshFlat, *newGeometry, *geometryFlat, *bLoopData, *normals, debugGradient, lr, nw);\n    Utils::centerPoints(*newGeometry);\n    psReconsMesh->updateVertexPositions(newGeometry->vertexPositions);\n    psReconsMesh->addVertexVectorQuantity(\"Debug Gradient\", debugGradient);\n\n}\n\nvoid Test::callback2(){\n    // ImGui\n    ImGui::PushItemWidth(100);\n\n    ImGui::InputInt(\"Iterations : \", &i);            \n    ImGui::SliderFloat(\"LR : \", &lr, 0.001f, 0.05f);\n    ImGui::SliderFloat(\"Normal weight : \", &nw, 0.1f, 100.0f);\n\n    ImGui::PopItemWidth();\n\n    i++;\n    newGeometry = DeformingMesh::iterativeSolve(*meshFlat, *newGeometry, *geometryFlat, refNormals, debugGradient, lr, nw);\n    //Utils::centerPoints(*newGeometry);\n    psReconsMesh->updateVertexPositions(newGeometry->vertexPositions);\n    psReconsMesh->addVertexVectorQuantity(\"Debug Gradient\", debugGradient);\n    newGeometry->requireFaceNormals();\n    psReconsMesh->addFaceVectorQuantity(\"Real Normals\", newGeometry->faceNormals);\n}\n\nvoid Test::callback3(){\n    // ImGui\n    ImGui::PushItemWidth(100);\n\n    ImGui::InputInt(\"Iterations : \", &i);            \n    ImGui::SliderFloat(\"LR : \", &lr, 0.001f, 0.05f);\n    ImGui::SliderFloat(\"Normal weight : \", &nw, 0.1f, 100.0f);\n\n    ImGui::PopItemWidth();\n\n    /*\n    int W = 10, H = 10;\n    // Laplacian Solve\n    double t = 1000.0;\n    Eigen::SparseMatrix<double> lap(W*H, W*H);\n    Eigen::SparseMatrix<double> Id(W*H, W*H);\n    Id.setIdentity();\n\n    Eigen::VectorXd u_0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd phi_0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd v_x0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd v_y0 = Eigen::VectorXd::Zero(W*H);\n\n    v_x0[27] = 1.0;\n    v_y0[27] = 1.0;\n    u_0[27] = std::sqrt(2.0);\n    phi_0[27] = 1.0;\n\n    v_x0[72] = -1.0;\n    v_y0[72] = -1.0;\n    u_0[72] = std::sqrt(3.0);\n    phi_0[72] = 1.0;\n\n    double theta = 2*3.141592*double(cpt++)/20;\n    double x = cos(theta);\n    double y = sin(theta);\n    v_x0[11] = x;\n    v_y0[11] = y;\n    u_0[11] = std::sqrt(1.0);\n    phi_0[11] = 1.0;\n\n    for(auto i=0; i < W*H; ++i){\n        for(auto j=0; j < W*H; ++j){\n            if(i == j)\n                lap.coeffRef(i, j) = -4.0;\n            if(adjacent(i,j,W,H))\n                lap.coeffRef(i,j) = 1.0;\n        }\n    }\n    \n    Eigen::SparseMatrix<double> A = Id - t*lap;\n    Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> >   solver;\n    solver.analyzePattern(A); \n    solver.factorize(A); \n\n    Eigen::VectorXd u_t = solver.solve(u_0);\n    Eigen::VectorXd phi_t = solver.solve(phi_0);\n    Eigen::VectorXd v_xt = solver.solve(v_x0);\n    Eigen::VectorXd v_yt = solver.solve(v_y0);\n\n    Eigen::VectorXd final_x(W*H);\n    Eigen::VectorXd final_y(W*H);\n\n\n    for(auto i=0; i < W*H; ++i){\n        final_x[i] = v_xt[i] / std::sqrt((v_xt[i]*v_xt[i] + v_yt[i]*v_yt[i])) * u_t[i] / phi_t[i];\n        final_y[i] = v_yt[i] / std::sqrt((v_xt[i]*v_xt[i] + v_yt[i]*v_yt[i])) * u_t[i] / phi_t[i];\n    }\n\n    // Fill\n    std::vector<Vector3> final(W*H);\n    int i = 0;\n    for(Vector3& val : final){\n        val = Vector3{final_x[i], 0.0f, final_y[i]};\n        \n        i++;\n    }\n\n    polyscope::getPointCloud(\"VF\")->addVectorQuantity(\"Value\", final);*/\n    \n}\n\nvoid Test::test1() {\n    \n    // Creates a planar mesh with height values\n    std::unique_ptr<ManifoldSurfaceMesh> mesh;\n    std::unique_ptr<VertexPositionGeometry> geometry;\n    std::tie(mesh, geometry) = Utils::createMeshPlane(30, 30, 5, 5, [](float x, float y)->float{return sin(x)*sin(y);});\n    Utils::centerPoints(*geometry);\n    geometry->requireVertexNormals();\n\n    // Creates a planar mesh\n    //std::unique_ptr<ManifoldSurfaceMesh> meshFlat;\n    std::tie(meshFlat, geometryFlat) = Utils::createMeshPlane(30, 30, 5, 5, [](float x, float y)->float{return 0.0f;});\n\n    // Gives projected normals\n    std::unique_ptr<FaceData<Vector3>> projectedPoints;\n    std::unique_ptr<FaceData<Vector3>> projectedNormals;\n    std::tie(projectedPoints, projectedNormals) = Utils::getProjectedNormals(*mesh, *geometry);\n\n    // Gives normals from projected normals\n    normals = Utils::getNormals(*projectedNormals);\n\n    // Find boundary loop\n    bLoopData = Utils::setBoundaryPositions(*mesh, *geometry);\n    \n    // Deforms a planar mesh so that the geometry matches given normals\n    debugGradient = VertexData<Vector3>(*mesh);\n    newGeometry = DeformingMesh::iterativeSolve(*meshFlat, *geometryFlat, *geometryFlat, *bLoopData, *normals, debugGradient, lr, nw);\n    Utils::centerPoints(*newGeometry);\n\n    // Visualization with polyscope\n    polyscope::init();\n\n    polyscope::SurfaceMesh* psMesh = polyscope::registerSurfaceMesh(\"Surface Mesh\", geometry->vertexPositions, mesh->getFaceVertexList());\n    psMesh->addVertexVectorQuantity(\"Vertex Normals\", geometry->vertexNormals);\n\n    psReconsMesh = polyscope::registerSurfaceMesh(\"Reconstructed Surface Mesh\", newGeometry->vertexPositions, mesh->getFaceVertexList());\n    psReconsMesh->addFaceVectorQuantity(\"Normals\", *normals);\n    psReconsMesh->addVertexVectorQuantity(\"Debug Gradient\", debugGradient);\n\n    polyscope::PointCloud* psPC = polyscope::registerPointCloud(\"Projected Points\", *projectedPoints);\n    psPC->addVectorQuantity(\"Projected Normals\", *projectedNormals);\n    psPC->addVectorQuantity(\"Normals\", *normals);\n\n    //polyscope::state::userCallback = Test::callback1;\n\n    polyscope::show();\n\n}\n\nvoid Test::test2() {\n    \n    // Creates an icosphere and twitched its normals\n    std::unique_ptr<ManifoldSurfaceMesh> meshIco;\n    std::unique_ptr<VertexPositionGeometry> geometryIco;\n    std::tie(meshIco, geometryIco) = Utils::createIcoSphere(2);\n    geometryIco->requireFaceNormals();\n    refNormals = geometryIco->faceNormals;\n    Utils::twitchNormals(refNormals);\n\n    std::tie(meshFlat, geometryFlat) = Utils::createIcoSphere(2);\n\n\n    // Deforms an icosphere so that the geometry matches given normals\n    debugGradient = VertexData<Vector3>(*meshIco);\n    newGeometry = DeformingMesh::iterativeSolve(*meshFlat, *geometryFlat, *geometryFlat, refNormals, debugGradient, lr, nw);\n\n\n    // Visualization with polyscope\n    polyscope::init();\n\n    psReconsMesh = polyscope::registerSurfaceMesh(\"Icosphere\", newGeometry->vertexPositions, meshIco->getFaceVertexList());\n    psReconsMesh->addFaceVectorQuantity(\"Real Normals\", geometryIco->faceNormals);\n    psReconsMesh->addFaceVectorQuantity(\"Twitched Normals\", refNormals);\n    std::cout << refNormals.size() << std::endl;\n\n    polyscope::state::userCallback = Test::callback2;\n\n    polyscope::show();\n\n}\n\n\n\nvoid Test::test3() {\n    \n    // Creates a 2D vector Field\n    int W = 40, H = 40;\n    \n    std::vector<Vector3> pts = Utils::createPointsPlane(W, H);\n    std::vector<Vector3> values(W*H);\n    for(Vector3& val : values){\n        float theta = 2*3.141592*polyscope::randomUnit();\n        float x = cos(theta);\n        float y = sin(theta);\n        val = Vector3{x, 0.0f, y};\n    }\n    \n    // Creates a planar mesh with height values\n    std::unique_ptr<ManifoldSurfaceMesh> mesh;\n    std::unique_ptr<VertexPositionGeometry> geometry;\n    std::tie(mesh, geometry) = Utils::createMeshPlane(W, H, 5, 5, [](float x, float y)->float{return sin(x)*sin(y);});\n    Utils::centerPoints(*geometry);\n    geometry->requireVertexNormals();\n    geometry->requireFaceNormals();\n\n    // Creates a planar mesh\n    //std::unique_ptr<ManifoldSurfaceMesh> meshFlat;\n    std::tie(meshFlat, geometryFlat) = Utils::createMeshPlane(W, H, 5, 5, [](float x, float y)->float{return 0.0f;});\n\n    // Gives projected normals\n    std::unique_ptr<VertexData<Vector3>> projectedPoints;\n    std::unique_ptr<VertexData<Vector3>> projectedNormals;\n    std::tie(projectedPoints, projectedNormals) = Utils::getProjectedVertexNormals(*mesh, *geometry);\n\n    // Laplacian Solve\n    double t = 0.01;\n    Eigen::SparseMatrix<double> lap(W*H, W*H);\n    Eigen::SparseMatrix<double> Id(W*H, W*H);\n    Id.setIdentity();\n\n    Eigen::VectorXd u_0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd phi_0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd v_x0 = Eigen::VectorXd::Zero(W*H);\n    Eigen::VectorXd v_y0 = Eigen::VectorXd::Zero(W*H);\n\n    std::vector<int> preservedNormalsId = {0,1,2,3,4,5,6,7,8,9,90,91,92,93,94,95,96,97,98,99,10,20,30,40,50,60,70,80,19,29,39,49,59,69,79,89};\n\n    //for(int id : preservedNormalsId){\n    for(int id = 0; id < 1600; ++id){\n        v_x0[id] = (*projectedNormals)[id][0];\n        v_y0[id] = (*projectedNormals)[id][2];\n        u_0[id] = norm((*projectedNormals)[id]);\n        phi_0[id] = 1.0;\n    }\n    /*\n    v_x0[27] = 1.0;\n    v_y0[27] = 1.0;\n    u_0[27] = std::sqrt(2.0);\n    phi_0[27] = 1.0;\n\n    v_x0[72] = -1.0;\n    v_y0[72] = -1.0;\n    u_0[72] = std::sqrt(6.0);\n    phi_0[72] = 1.0;\n\n    double theta = 2*3.141592*double(cpt++)/360;\n    double x = cos(theta);\n    double y = sin(theta);\n    v_x0[11] = x;\n    v_y0[11] = y;\n    u_0[11] = std::sqrt(1.0);\n    phi_0[11] = 1.0; */\n\n    for(auto i=0; i < W*H; ++i){\n        for(auto j=0; j < W*H; ++j){\n            if(i == j){\n                lap.coeffRef(i, j) = -4.0;\n                if(i == 0 || i == W*H-1 || j == 0 || j == W*H-1)\n                    lap.coeffRef(i, j) = -3.0;\n            }\n                \n            if(adjacent(i,j,W,H))\n                lap.coeffRef(i,j) = 1.0;\n        }\n    }\n    \n    Eigen::SparseMatrix<double> A = Id - t*lap;\n    Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> >   solver;\n    solver.analyzePattern(A); \n    solver.factorize(A); \n\n    Eigen::VectorXd u_t = solver.solve(u_0);\n    Eigen::VectorXd phi_t = solver.solve(phi_0);\n    Eigen::VectorXd v_xt = solver.solve(v_x0);\n    Eigen::VectorXd v_yt = solver.solve(v_y0);\n\n    Eigen::VectorXd final_x(W*H);\n    Eigen::VectorXd final_y(W*H);\n\n\n    for(auto i=0; i < W*H; ++i){\n        final_x[i] = v_xt[i] / std::sqrt((v_xt[i]*v_xt[i] + v_yt[i]*v_yt[i])) * u_t[i] / phi_t[i];\n        final_y[i] = v_yt[i] / std::sqrt((v_xt[i]*v_xt[i] + v_yt[i]*v_yt[i])) * u_t[i] / phi_t[i];\n    }\n\n    // Fill\n    std::vector<Vector3> final(W*H);\n    VertexData<Vector3> estimatedProjectedVertexNormals(*meshFlat);\n    int i = 0;\n    for(Vector3& val : final){\n        val = Vector3{final_x[i], 0.0f, final_y[i]};\n        estimatedProjectedVertexNormals[i] = Vector3{final_x[i], 0.0f, final_y[i]};\n        i++;\n    }\n\n    std::unique_ptr<FaceData<Vector3>> estimatedProjectedFaceNormals = Utils::getFaceNormalsFromVertexNormals(estimatedProjectedVertexNormals, *meshFlat);\n\n    // Gives normals from projected normals\n    normals = Utils::getNormals(*estimatedProjectedFaceNormals);\n\n    // Find boundary loop\n    bLoopData = Utils::setBoundaryPositions(*mesh, *geometry);\n    \n    // Deforms a planar mesh so that the geometry matches given normals\n    debugGradient = VertexData<Vector3>(*mesh);\n    newGeometry = DeformingMesh::iterativeSolve(*meshFlat, *geometryFlat, *geometryFlat, *bLoopData, *normals, debugGradient, lr, nw);\n    Utils::centerPoints(*newGeometry);\n    newGeometry->requireFaceNormals();\n\n\n    // Visualization with polyscope\n    polyscope::init();\n\n    polyscope::PointCloud* pointCloudVF = polyscope::registerPointCloud(\"VF\", *projectedPoints);\n    pointCloudVF->addVectorQuantity(\"Estimated Normals\", final);\n    pointCloudVF->addVectorQuantity(\"Real Normals\", *projectedNormals);\n\n    psReconsMesh = polyscope::registerSurfaceMesh(\"Reconstructed Mesh\", newGeometry->vertexPositions, mesh->getFaceVertexList());\n    psReconsMesh->addFaceVectorQuantity(\"Estimated normals\", *normals);\n    psReconsMesh->addFaceVectorQuantity(\"Groundtruth\", geometry->faceNormals);\n    psReconsMesh->addFaceVectorQuantity(\"Real normals\", newGeometry->faceNormals);\n\n    polyscope::SurfaceMesh* psMesh = polyscope::registerSurfaceMesh(\"Surface Mesh\", geometry->vertexPositions, mesh->getFaceVertexList());\n\n\n    //polyscope::state::userCallback = Test::callback3;\n\n    polyscope::show();\n\n}", "meta": {"hexsha": "fd6563b876d5dff3b80831c0bd61e6a0a8dea9c7", "size": 13290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "Neckrome/vectorFieldSurface", "max_stars_repo_head_hexsha": "91afebadf9815e6a2dc658cdce82691fddd603ee", "max_stars_repo_licenses": ["MIT"], "max_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": "Neckrome/vectorFieldSurface", "max_issues_repo_head_hexsha": "91afebadf9815e6a2dc658cdce82691fddd603ee", "max_issues_repo_licenses": ["MIT"], "max_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": "Neckrome/vectorFieldSurface", "max_forks_repo_head_hexsha": "91afebadf9815e6a2dc658cdce82691fddd603ee", "max_forks_repo_licenses": ["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.1645244216, "max_line_length": 154, "alphanum_fraction": 0.6507900677, "num_tokens": 3975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5702791231583108}}
{"text": "/*\n * Copyright (c) 2011 Seiya Tokui <beam.web@gmail.com>\n * Copyright (c) 2014 Burkhard Ritter <burkhard@ualberta.ca>\n * This code is distributed under the MIT license.\n *\n * Performance and accuracy of the ARPACK eigensolver compared to the Eigen\n * eigensolver. \n *\n * Computes execution time of both the ARPACK and the Eigen eigensolver for\n * random symmetric matrices for a range of matrix dimensions. Computes the mean\n * error of the ARPACK eigenvalues and eigenvectors as well. The number of\n * eigenvalues to be computed (for ARPACK) and the number of zeros in each matrix\n * can be specified as a percentage of the matrix dimension. Produces output\n * suitable for plotting.\n *\n * Note: This program uses the Arpaca solver in a very simple, black-box like\n * fashion. It is very likely possible to achieve better performance by tuning\n * various parameters.\n *\n * To compile this program: \n * g++ \\\n *    -std=c++11 \\\n *    -I [/path/to/eigen] \\\n *    -O3 \\\n *    -DNDEBUG \\\n *    performance_plot.cpp \\\n *    -L [/path/to/libarpack.a] \\\n *    -larpack \\\n *    -o performance_plot\n *\n * This assumes that arpaca.hpp is in the same directory.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <random>\n#include <chrono>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"arpaca.hpp\"\nusing namespace Eigen;\nusing namespace arpaca;\nusing namespace std::chrono;\n\nstd::mt19937 generator(42);\n\nVectorXd diagonalize_random_matrix(int n_dim, double r_ev, double r_zeros)\n{\n    const int n_ev = r_ev * n_dim;\n    int n_zeros = r_zeros * n_dim*n_dim;\n    if (n_zeros%2 != 0) n_zeros--;\n\n    /*\n     * Create matrix\n     *\n     * Is there an easier way to get a random symmetric matrix with a specified\n     * number of zero elements?\n     */\n    MatrixXd dm = MatrixXd::Random(n_dim,n_dim).selfadjointView<Upper>();\n    std::uniform_int_distribution<int> distribution(0,n_dim-1);\n    int n_diag = n_zeros / n_dim;\n    if (n_diag%2 != 0) n_diag--;\n    int n_rest = n_zeros - n_diag;\n    while (n_diag > 0)\n    {\n        int i = distribution(generator);\n        if (dm(i,i) != 0)\n        {\n            dm(i,i) = 0;\n            n_diag--;\n        }\n    }\n    while (n_rest > 0)\n    {\n        int i = distribution(generator);\n        int j = distribution(generator);\n        if (i!=j && dm(i,j)!=0)\n        {\n            dm(i,j) = 0;\n            dm(j,i) = 0;\n            n_rest -= 2;\n        }\n    }\n    SparseMatrix<double> sm = dm.sparseView();\n    assert(sm.nonZeros() == n_dim*n_dim - n_zeros);\n\n    /*\n     * Diagonalize Arpaca\n     *\n     * Arpaca (and ARPACK?) do not seem to support the calculation of all\n     * eigenvalues directly. The most primitive way to work around this is to\n     * calculate n_ev-1 eigenvalues from the bottom and 1 eigenvalue from the\n     * top, and that's what I do here.\n     */\n    steady_clock::time_point begin_a;\n    steady_clock::time_point end_a;\n    Eigen::VectorXd eigenvalues_a(n_ev);\n    Eigen::MatrixXd eigenvectors_a(n_ev,n_ev);\n    SymmetricEigenSolver<double> s_a;\n    SymmetricEigenSolver<double> s_a_;\n    if (n_ev < n_dim)\n    { \n        begin_a = steady_clock::now();\n        s_a = Solve(sm, n_ev, ALGEBRAIC_SMALLEST);\n        end_a = steady_clock::now();\n        // We could avoid copying the vector and matrix by using references.\n        eigenvalues_a = s_a.eigenvalues();\n        eigenvectors_a = s_a.eigenvectors();\n    }\n    else // n_ev == n_dim\n    {\n        begin_a = steady_clock::now();\n        s_a = Solve(sm, n_ev-1, ALGEBRAIC_SMALLEST);\n        s_a_ = Solve(sm, 1, ALGEBRAIC_LARGEST);\n        end_a = steady_clock::now();\n        \n        eigenvalues_a.head(n_ev-1) = s_a.eigenvalues();\n        eigenvectors_a.leftCols(n_ev-1) = s_a.eigenvectors();\n        \n        eigenvalues_a.tail(1) = s_a_.eigenvalues();\n        eigenvectors_a.rightCols(1) = s_a_.eigenvectors();\n    }\n    duration<double> d_a = duration_cast<duration<double>>(end_a - begin_a);\n    double time_a = d_a.count();\n\n    /*\n     * Diagonalize Eigen\n     */\n    Eigen::VectorXd eigenvalues_e(n_ev);\n    Eigen::MatrixXd eigenvectors_e(n_ev,n_ev);\n\n    steady_clock::time_point begin_e = steady_clock::now();\n    SelfAdjointEigenSolver<MatrixXd> s_e(dm);\n    steady_clock::time_point end_e = steady_clock::now();\n    \n    // We could avoid copying the vector and matrix by using references.\n    eigenvalues_e = s_e.eigenvalues().topRows(n_ev);\n    eigenvectors_e = s_e.eigenvectors().leftCols(n_ev);\n    \n    duration<double> d_e = duration_cast<duration<double>>(end_e - begin_e);\n    double time_e = d_e.count();\n\n    /*\n     * Calculate error\n     */\n    double error_values = (eigenvalues_a - eigenvalues_e).cwiseAbs().mean();\n    double error_vectors = 0;\n    for (int i = 0; i < n_ev; i++)\n    {\n        double d1 = \n            (eigenvectors_a.col(i) - eigenvectors_e.col(i)).cwiseAbs().mean();\n        double d2 =\n            (eigenvectors_a.col(i) + eigenvectors_e.col(i)).cwiseAbs().mean();\n        error_vectors += std::min(d1, d2);\n    }\n    error_vectors /= n_ev;\n\n    /*\n     * Output\n     */\n    /*\n    std::cout << \"Matrix: \" << std::endl;\n    std::cout << dm << std::endl << std::endl;\n    std::cout << \"Arpack eigenvalues: \" << std::endl;\n    std::cout << eigenvalues_a << std::endl << std::endl;\n    std::cout << \"Eigen eigenvalues: \" << std::endl;\n    std::cout << eigenvalues_e << std::endl << std::endl;\n    std::cout << \"Time in seconds of Arpaca: \" << time_a << std::endl;\n    std::cout << \"Time in seconds of Eigen: \" << time_e << std::endl;\n    std::cout << \"Mean error of eigenvalues: \" << error_values << std::endl;\n    std::cout << \"Mean error of eigenvectors: \" << error_vectors << std::endl;\n    std::cout << \"info: \" << s_a.GetInfo() << std::endl;\n    std::cout << \"# actual iterations: \"\n              << s_a.num_actual_iterations() << std::endl;\n    std::cout << \"# converged eigenvalues: \"\n              << s_a.num_converged_eigenvalues() << std::endl;\n    */\n\n    /*\n     * Result\n     */\n    VectorXd r(6);\n    r << time_a, time_e, error_values, error_vectors, \n         s_a.num_actual_iterations(), \n         s_a.num_converged_eigenvalues();\n    return r;\n}\n\nvoid print_usage(char* program)\n{\n    std::cerr \n        << \"Performance and accuracy of the ARPACK eigensolver compared \"\n        << std::endl\n        << \"to the Eigen eigensolver.\" << std::endl << std::endl\n        << \"Computes execution time and error over matrix dimensions. \" \n        << std::endl\n        << \"Produces output suitable for plotting.\" << std::endl\n        << std::endl\n        << \"Usage: \" << std::endl\n        << \"   \" << program\n        << \" [n_dim_min] [n_dim_max] [n_dp] [n_rep] [r_ev] [r_zeros]\"\n        << std::endl << std::endl\n        << \"with: \" << std::endl\n        << \"   n_dim_min: start value for matrix dimension\" << std::endl\n        << \"   n_dim_end: end value for matrix dimension\" << std::endl\n        << \"   n_dp: number of data points to compute\" << std::endl\n        << \"   n_rep: number of repetitions for each matrix dimension\" << std::endl\n        << \"   r_ev: number of eigenvalues to compute as a percentage\" << std::endl \n        << \"         of matrix dimension, ranges from 0 to 1\" << std::endl\n        << \"   r_zeros: number of zeros in matrix as a percentage of\" << std::endl\n        << \"            matrix size, ranges from 0 to 1\" << std::endl\n        << std::endl\n        << \"Example: \" << std::endl\n        << \"   \" << program\n        << \" 100 1000 10 10 0.3 0.1\" << std::endl;\n}\n\nvoid print_header(int n_rep, double r_ev, double r_zeros, int w)\n{\n    std::cout << std::setprecision(6);\n    std::cout << std::left;\n    std::cout \n        << \"# Performance and accuracy of the ARPACK eigensolver compared \"\n        << \"to the Eigen eigensolver.\" << std::endl\n        << \"# \" << std::endl\n        << \"# n_rep=\"  << n_rep << std::endl\n        << \"# r_ev=\" << r_ev << std::endl\n        << \"# r_zeros=\" << r_zeros << std::endl\n        << \"# \" << std::endl\n        << \"# \" \n        << std::setw(w-2) << \"n_dim\"\n        << std::setw(w) << \"time_a\"\n        << std::setw(w) << \"time_e\"\n        << std::setw(w) << \"error_values\"\n        << std::setw(w) << \"error_vectors\"\n        << std::setw(w) << \"n_it\"\n        << std::setw(w) << \"n_conv\"\n        << std::endl;\n}\n\nint main (int argc, char** argv)\n{\n    if (argc != 7)\n    {\n        print_usage(argv[0]);\n        std::exit(EXIT_SUCCESS);\n    }\n    \n    int n_dim_min = std::atoi(argv[1]);\n    int n_dim_max = std::atoi(argv[2]);\n    int n_dp = std::atoi(argv[3]);\n    int n_rep = std::atoi(argv[4]);\n    double r_ev = std::atof(argv[5]);\n    double r_zeros = std::atof(argv[6]);\n\n    if (n_dim_min < 1) n_dim_min = 1;\n    if (n_dim_max < n_dim_min) n_dim_max = n_dim_min;\n    if (n_dp < 1) n_dp = 1;\n    if (n_rep < 1) n_rep = 1;\n    if (r_ev < 0) r_ev = 0;\n    if (r_ev > 1) r_ev = 1;\n    if (r_zeros < 0) r_zeros = 0;\n    if (r_zeros > 1) r_zeros = 1;\n\n    int delta_dim = n_dim_max - n_dim_min + 1;\n    if (n_dp > 1)\n        delta_dim = (n_dim_max - n_dim_min) / (n_dp-1);\n    if (delta_dim == 0) delta_dim = 1;\n\n    const int w = 15;\n    print_header(n_rep, r_ev, r_zeros, w);\n    for (int n_dim = n_dim_min; n_dim <= n_dim_max; n_dim += delta_dim)\n    {\n        Eigen::VectorXd v(6);\n        v.setZero();\n        for (int i=0; i<n_rep; i++)\n        {\n            VectorXd r = diagonalize_random_matrix(n_dim,r_ev,r_zeros);\n            v += r;\n        }\n        v /= n_rep;\n        std::cout << std::setw(w) << n_dim;\n        for (int i=0; i<v.size(); i++)\n            std::cout << std::setw(w) << v(i);\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "689f802fe41254d78664eec133d79555ec6552be", "size": 9598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance_plot.cpp", "max_stars_repo_name": "meznom/arpaca", "max_stars_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-05T17:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-05T17:29:06.000Z", "max_issues_repo_path": "performance_plot.cpp", "max_issues_repo_name": "meznom/arpaca", "max_issues_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "performance_plot.cpp", "max_forks_repo_name": "meznom/arpaca", "max_forks_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_forks_repo_licenses": ["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.0965517241, "max_line_length": 84, "alphanum_fraction": 0.5798082934, "num_tokens": 2759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5702791177634476}}
{"text": "#include \"cpu_impl.hpp\"\n\n#include <util/logging.hpp>\n\n#include <exception>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace simplex {\nnamespace cpu {\n\nTableau<double> create_tableau(const Problem& problem_stmt) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"create_tableau\");\n\n\tconst auto num_constraints = problem_stmt.num_constraints();\n\tconst auto num_variables = problem_stmt.num_variables();\n\n\tdout(DL::DBG1) << \"num_variables = \" << num_variables << \"\\nnum_constraints = \" << num_constraints << '\\n';\n\n\tEigen::MatrixXd constraint_matrix(num_constraints + 1, num_variables + 1);\n\tconstraint_matrix.setZero();\n\n\t{int constr_count = 0;\n\tfor (const auto& constr : problem_stmt.constraints()) {\n\t\tauto current_cm_row = constraint_matrix.row(constr_count + 1);\n\n\t\tcurrent_cm_row(0) = constr.m_rhs;\n\t\tfor (const auto& varid_and_val : constr.m_coeffs) {\n\t\t\tcurrent_cm_row(varid_and_val.first.getValue() + 1) = varid_and_val.second;\n\t\t}\n\n\t\tconstr_count += 1;\n\t}}\n\n\t{auto objective_coeffs = constraint_matrix.row(0);\n\tfor (const auto& var_and_info : problem_stmt.variables()) {\n\t\tobjective_coeffs(var_and_info.first.getValue() + 1) = var_and_info.second.m_coeff;\n\t}}\n\n\tdout(DL::DBG3) << \"constraint matrix\\n\" << constraint_matrix << '\\n';\n\n\tconst auto& constraint_consts = constraint_matrix.leftCols<1>().segment(1, num_constraints);\n\tconst auto& basis = Eigen::MatrixXd::Identity(num_constraints,num_constraints);\n\tconst auto& basic_coeff = Eigen::RowVectorXd::Zero(num_constraints);\n\tconst auto& nonbasics = constraint_matrix.bottomRightCorner(num_constraints, num_variables);\n\tconst auto& nonbasics_coeff = constraint_matrix.topRows<1>().segment(1, num_variables);\n\n\tconst auto& inv_basis = basis.inverse();\n\tconst auto& inv_basis_times_nonbasis = inv_basis*nonbasics;\n\tconst auto& inv_basis_times_constraint_coeffs = inv_basis*constraint_consts;\n\n\tconst auto& upper_right = basic_coeff*inv_basis_times_nonbasis - nonbasics_coeff;\n\tconst auto& lower_right = inv_basis_times_nonbasis;\n\n\tconst auto& upper_left = basic_coeff*inv_basis_times_constraint_coeffs;\n\tconst auto& lower_left = inv_basis_times_constraint_coeffs;\n\n\t(void)upper_right; // dout(DL::DBG3) << \"upper_right:\\n\" << upper_right << '\\n';\n\t(void)lower_right; // dout(DL::DBG3) << \"lower_right:\\n\" << lower_right << '\\n';\n\n\t(void)upper_left; // dout(DL::DBG3) << \"upper_left:\\n\" << upper_left << '\\n';\n\t(void)lower_left; // dout(DL::DBG3) << \"lower_left:\\n\" << lower_left << '\\n';\n\n\t// Eigen::MatrixXd tableau_data(num_constraints+1, num_variables+1); tableau_data <<\n\t// \tupper_left, upper_right, lower_left, lower_right\n\t// ;\n\n\tconstraint_matrix.row(0) *= -1;\n\tconstraint_matrix(0,0) = 0; // upper_left(0,0); // always zero\n\tconst auto& tableau_data = constraint_matrix;\n\n\tdout(DL::DBG3) << \"tableau_data:\\n\" << tableau_data << '\\n';\n\n\tTableau<double> result (\n\t\tnew double[static_cast<std::size_t>(tableau_data.rows() * tableau_data.cols())],\n\t\ttableau_data.rows(),\n\t\ttableau_data.cols()\n\t);\n\n\tfor (std::ptrdiff_t irow = 0; irow < tableau_data.rows(); ++irow) {\n\t\tfor (std::ptrdiff_t icol = 0; icol < tableau_data.cols(); ++icol) {\n\t\t\tresult.at(irow, icol) = tableau_data(irow, icol);\n\t\t}\n\t}\n\n\treturn result;\n}\n\nboost::optional<VariableIndex> find_entering_variable(const util::PointerAndSize<double>& first_row) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"find_entering_variable\");\n\tdout(DL::DBG2) << \"first row given: \";\n\tutil::print_container(dout(DL::DBG2), first_row);\n\tdout(DL::DBG2) << '\\n';\n\n\tdouble lowest_value = 0;\n\tboost::optional<VariableIndex> result;\n\n\tfor (int icol = 1; icol < first_row.size(); ++icol) {\n\t\tconst auto& val = first_row.at(icol);\n\t\tif (val < lowest_value) {\n\t\t\tlowest_value = val;\n\t\t\tresult = util::make_id<VariableIndex>(icol);\n\t\t}\n\t}\n\n\tif (result) {\n\t\tdout(DL::DBG1) << \"found entering variable: \" << *result << '\\n';\n\t} else {\n\t\tdout(DL::DBG1) << \"did not find a entering variable\\n\";\n\t}\n\n\treturn result;\n}\n\nThetaValuesAndEnteringColumn<double> get_theta_values_and_entering_column(const Tableau<double>& tab, VariableIndex entering) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"get_theta_values_and_entering_column\");\n\tThetaValuesAndEnteringColumn<double> result (\n\t\ttab.height()\n\t);\n\n\tfor (int irow = 0; irow < tab.height(); ++irow) {\n\t\tconst auto& val_at_entering = tab.at(irow, entering);\n\t\tresult.entering_column.at((std::size_t)irow) = val_at_entering;\n\t\tresult.theta_values.at((std::size_t)irow) = tab.at(irow, 0)/val_at_entering;\n\t}\n\n\tdout(DL::DBG1) << \"theta_values computed: \";\n\tutil::print_container(dout(DL::DBG1), result.theta_values);\n\tdout(DL::DBG1) << \"\\nentering_column copied: \";\n\tutil::print_container(dout(DL::DBG1), result.entering_column);\n\tdout(DL::DBG1) << '\\n';\n\n\treturn result;\n}\n\nboost::optional<VariableIndex> find_leaving_variable(const ThetaValuesAndEnteringColumn<double>& tvals_and_centering) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"find_leaving_variable\");\n\tdout(DL::DBG2) << \"theta_values given: \";\n\tutil::print_container(dout(DL::DBG2), tvals_and_centering.theta_values);\n\tdout(DL::DBG2) << \"\\nentering_column given: \";\n\tutil::print_container(dout(DL::DBG2), tvals_and_centering.entering_column);\n\tdout(DL::DBG2) << '\\n';\n\n\tauto lowest_theta_value = std::numeric_limits<double>::max();\n\tboost::optional<VariableIndex> result;\n\n\tfor (int irow = 1; irow < (int)tvals_and_centering.theta_values.size(); ++irow) {\n\t\tconst auto& theta_val = tvals_and_centering.theta_values.at((std::size_t)irow);\n\t\tconst auto& tab_val = tvals_and_centering.entering_column.at((std::size_t)irow);\n\t\tif (tab_val > 0 && (!result || theta_val < lowest_theta_value)) {\n\t\t\tlowest_theta_value = theta_val;\n\t\t\tresult = util::make_id<VariableIndex>(irow);\n\t\t}\n\t}\n\n\tif (result) {\n\t\tdout(DL::DBG1) << \"found leaving variable: \" << *result << '\\n';\n\t} else {\n\t\tdout(DL::DBG1) << \"did not find a leaving variable\\n\";\n\t}\n\n\treturn result;\n}\n\nTableau<double> update_leaving_row(Tableau<double>&& tab, const std::vector<double>& entering_column, VariablePair leaving_and_entering) {\n\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"update_leaving_row\");\n\n\tauto denom = entering_column.at((std::size_t)leaving_and_entering.leaving.getValue());\n\t// dout(DL::LINDA) << \"index: \" << (std::size_t)leaving_and_entering.leaving.getValue() << '\\n';\n\t// dout(DL::LINDA) << \"denom: \" << denom << '\\n';\n\n\tfor (int icol = 0; icol < tab.width(); ++icol) {\n\t\ttab.at(leaving_and_entering.leaving, icol) /= denom;\n\t}\n\n\tdout(DL::DBG2) << \"tableau after:\\n\" << tab << '\\n';\n\n\treturn tab;\n}\n\nTableau<double> update_rest_of_basis(Tableau<double>&& tab, const std::vector<double>& entering_column, VariableIndex leaving) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"update_rest_of_basis\");\n\n\tfor (int irow = 0; irow < tab.height(); ++irow) {\n\t\tif (irow == leaving.getValue()) { continue; }\n\t\tconst auto& entering_col_val = entering_column.at((std::size_t)irow);\n\n\t\tfor (int icol = 0; icol < tab.width(); ++icol) {\n\t\t\t// dout(DL::LINDA) << \"entering_col_val: \" << entering_col_val << \" tab.at(leaving, icol): \" << tab.at(leaving, icol) << \" leaving: \" << leaving << \" icol: \" << icol << \"\\n\";\n\t\t\ttab.at(irow, icol) -= tab.at(leaving, icol) * entering_col_val;\n\t\t}\n\t}\n\n\tdout(DL::DBG2) << \"tableau after:\\n\" << tab << '\\n';\n\n\treturn tab;\n}\n\nTableau<double> update_entering_column(Tableau<double>&& tab, const std::vector<double>& entering_column, VariablePair leaving_and_entering) {\n\tconst auto indent = dout(DL::DBG1).indentWithTitle(\"update_entering_column\");\n\n\tauto denom = entering_column.at((std::size_t)leaving_and_entering.leaving.getValue());\n\n\t// printf(\"index: %d denom: %f\\n\", leaving_and_entering.leaving.getValue(), denom);\n\n\tfor (int irow = 0; irow < tab.height(); ++irow) {\n\t\tif (irow == leaving_and_entering.leaving.getValue()) {\n\t\t\ttab.at(irow, leaving_and_entering.entering) = 1/denom;\n\t\t} else {\n\t\t\ttab.at(irow, leaving_and_entering.entering) = - entering_column.at((std::size_t)irow)/denom;\n\t\t}\n\t}\n\n\tdout(DL::DBG2) << \"tableau after:\\n\" << tab << '\\n';\n\n\treturn tab;\n}\n\n} // end namespace simplex\n} // end namespace cpu\n", "meta": {"hexsha": "5325eefe570f337b75baa83483622120a5864fb0", "size": 8077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/impl/cpu_impl.cpp", "max_stars_repo_name": "golvok/simplex-gpu", "max_stars_repo_head_hexsha": "ff152cd99b8969348d6bffce4db2e46579f745a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-27T13:50:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T02:12:46.000Z", "max_issues_repo_path": "src/impl/cpu_impl.cpp", "max_issues_repo_name": "yidong72/simplex-gpu", "max_issues_repo_head_hexsha": "ff152cd99b8969348d6bffce4db2e46579f745a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/impl/cpu_impl.cpp", "max_forks_repo_name": "yidong72/simplex-gpu", "max_forks_repo_head_hexsha": "ff152cd99b8969348d6bffce4db2e46579f745a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-23T20:04:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-23T20:04:16.000Z", "avg_line_length": 36.2197309417, "max_line_length": 177, "alphanum_fraction": 0.7078123065, "num_tokens": 2281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5702791125658472}}
{"text": "/*\n\nProgram that compares lines from ancestor and endpoint common lines file and estimates mut rate.\nNote that these input files are preprocessed and derived from pileups. (ATCG data)\nWe have two files with the same number of lines and the two files correspond line by line.\n\nThis program takes 3 argument: extant ancestor_common_processed_pileup endpoint_common_processed_pileup\n\n\textant: for defining minimum mut_freq to consider endpoint as muted\n\t\n\textant must be in {8, 12, 16, 20, 24, 28, 32, 48, 75, 100}\n\t\nThis program, for all couples of lines in the two files:\n\n1) Reads one line from ancestor file and one from endpoint; \n2) Parses them to get muted frequency and coverage;\n3) Applies thresholds and in case skips lines;\n4) Checks if lines that are fine with thresholds are muted or not. \n\nTresholds:\n\n\t- For both files discards lines with reference base different from A, T, C, G\n\t\n\t- For ancestor discard lines with\n\t\t coverage < 100\n\t\t mut_freq > 0.0\n\t\n\t- For endpoint discard lines with:\n\t\tmut_freq > 0.2 \n\t\tunbalanced forward and reverse muted reads.\n\n\n\nCounts base as muted if endpoint frequency \n\n\tf >= Cutoff(Coverage, f_min) e Coverage = TotCoverage/3\n\n\tcutoff (Coverage, f_min) = f_min + alpha/Sqrt[Coverage]\n\nbased on extant f_min and corresponding alphas are\n\n\tf_min = {1/8, 1/12, 1/16, 1/20, 1/24, 1/28, 1/32, 1/48, 1/75, 1/100}\n\n\talpha = {0.52, 0.45, 0.36, 0.32, 0.3, 0.28, 0.25, 0.2, 0.18, 0.15} \n*/\n\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <cassert>\n#include <cmath>\n#include <algorithm> // std::max(a,b)\n\n//Boost \n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n\nusing namespace std;\n\ndouble compute_mut_rate(double P_hat, double death_prob, int extant);\n\nbool endpoint_muted(float mut_freq, int total_coverage, int extant);\n\nint main(int argc, char** argv){\n\n\t//*******************************************\n\t//          COMMAND LINE ARGS\n\t//*******************************************\n\t\n\tif (argc != 4){\n\t\tcerr << \"Usage: \" << argv[0] << \" extant ancestor_common_lines_file endpoint_common_lines_file\" << endl;\n\t\treturn -1;\n\t}\n\t\n\t\n\tint extant = atoi(argv[1]);\n\t\n\tstring ancestor_file = argv[2];\n\tstring endpoint_file = argv[3];\n\t\n\t\n\tif (extant != 8 && extant != 12 &&extant != 16 && extant != 20 && extant != 24 && extant != 28 && extant != 32 && extant != 48 && extant != 75 && extant != 100){\n\t\tcerr << \"Extant must be of following: {8, 12, 16, 20, 24, 28, 32, 48, 75, 100}\" \n\t\t<< endl;\n\t\treturn -1;\n\t}\n\t\n\t\n\t//*******************************************\n\t//          FIXED THRESHOLDS \n\t//*******************************************\n\t//ancestor\n\tint coverage_min_ancestor = 100;\n\tfloat freq_max_ancestor_confirm_reference = 0.;\n\t//endpoint\n\tfloat endpoint_freq_max = 0.2;\n\t\n\t//*******************************************\n\t//          COMPRESSED INPUT\n\t//*******************************************\n\t\n\n\t//open and unzip ancestor file\n\tifstream file_1(ancestor_file, ios_base::in | ios_base::binary);\n\t\n\tif (file_1.is_open() == false) {\n\t\tcerr << \"Ancestor not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> file_1_inbuf;\n    \tfile_1_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tfile_1_inbuf.push(file_1);\n    \t//Convert streambuf to istream\n    \tistream file_1_instream(&file_1_inbuf);\n\t\n\tcout << endl << \"Ancestor file opened.\" << endl;\n\t\n\t//open and unzip endpoint file\n\tifstream file_2(endpoint_file, ios_base::in | ios_base::binary);\n\t\n\tif (file_2.is_open() == false) {\n\t\tcerr << \"Endopint file not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> file_2_inbuf;\n    \tfile_2_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tfile_2_inbuf.push(file_2);\n    \t//Convert streambuf to istream\n    \tistream file_2_instream(&file_2_inbuf);\n\t\n\tcout << \"Endpoint file opened.\" << endl << endl;\n\t\n\t//*******************************************\n\t//          PARSING VARIABLES\n\t//*******************************************\n\t//Ancestor parsing variables-------------\n\tstring ancestor_line; //line of the file to parse\n\tstring ancestor_chromosome; //pos\n\tint ancestor_chromosome_number = 0;\n\tlong int ancestor_base_number = 0; //1-based\n\tstring ancestor_ATCG_data; \n\tchar ancestor_reference;\n\tint ancestor_A_counter = 0;\n\tint ancestor_T_counter = 0;\n\tint ancestor_C_counter = 0;\n\tint ancestor_G_counter = 0;\n\tint ancestor_a_counter = 0;\n\tint ancestor_t_counter = 0;\n\tint ancestor_c_counter = 0;\n\tint ancestor_g_counter = 0;\n\tint ancestor_coverage = 0;\n\tdouble ancestor_mut_freq = 0;\n\t\n\t//Endpoint parsing variables-------------\n\tstring endpoint_line; //line of the file to parse\n\tstring endpoint_chromosome; \n\tint endpoint_chromosome_number = 0;\n\tlong int endpoint_base_number = 0; \n\tstring endpoint_ATCG_data; \n\tchar endpoint_reference;\n\tint endpoint_A_counter = 0;\n\tint endpoint_T_counter = 0;\n\tint endpoint_C_counter = 0;\n\tint endpoint_G_counter = 0;\n\tint endpoint_a_counter = 0;\n\tint endpoint_t_counter = 0;\n\tint endpoint_c_counter = 0;\n\tint endpoint_g_counter = 0;\n\tint endpoint_coverage = 0;\n\tdouble endpoint_mut_freq = 0;\n\tchar endpoint_muted_in;\n\t\n\t//*******************************************\n\t//          OTHERS \n\t//*******************************************\n\tlong int count_line = 0; //all lines in file\n\tlong int discarded_lines = 0; //not matching thresholds\n\tlong int muted_bases = 0;\n\tlong int not_muted_bases = 0;\n\tdouble P_hat;\n\t\n\t//******************************************\n\t//--------------------------------------\n\t// \t\t    START\n\t// \n\t// read line by line both ancestor and endpoint\n\t// check thresholds and count muted lines\n\t//--------------------------------------\n\t//******************************************\n\t\n\tcout << \"Start reading files.\" << endl << endl;\n\t\n\t//Loop for all line in file 2 (endpoint)\n\twhile (getline(file_2_instream, endpoint_line)) { //until file_2 EOF\n\t\t\n\t\t//reset counters\n\t\tendpoint_coverage = 0;\n\t\tancestor_coverage = 0;\n\t\t\n\t\t//*******************************************\n\t\t// READ AND PARSE A LINE FROM ENDPOINT FILE\n\t\t//*******************************************\n\t\t\n\t\t//Parse file 2 input line\n\t\tstringstream file_2_linestream(endpoint_line);\n\t\t//get file_2 line pos finding the separator ('\\t')\n\t\tgetline(file_2_linestream, endpoint_chromosome, '\\t');\n\t\t//get file_2 loc\n\t\tfile_2_linestream >> endpoint_base_number;\n\t\t//we need chromosome numeber and loc\n\t\t//extract chromosome number from chromosome string\n\t\t// \"chrN\", N integer\n\t\t//     ^        \n\t\tendpoint_chromosome_number = atoi(&endpoint_chromosome[3]);\n\t\t//get file_2 ATCG data finding the separator ('\\n')\n\t\tgetline(file_2_linestream, endpoint_ATCG_data, '\\n');\n\t\t\n\t\t//parse endpoint ATCG data\n\t\tstringstream endpoint_ATCG_linestream(endpoint_ATCG_data);\n\t\t//endpoint reference\n\t\tendpoint_ATCG_linestream >> endpoint_reference;\n\t\t//counters\n\t\tendpoint_ATCG_linestream >> endpoint_A_counter; endpoint_coverage += endpoint_A_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_T_counter; endpoint_coverage += endpoint_T_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_C_counter; endpoint_coverage += endpoint_C_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_G_counter; endpoint_coverage += endpoint_G_counter;\n\t\n\t\tendpoint_ATCG_linestream >> endpoint_a_counter; endpoint_coverage += endpoint_a_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_t_counter; endpoint_coverage += endpoint_t_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_c_counter; endpoint_coverage += endpoint_c_counter;\n\t\tendpoint_ATCG_linestream >> endpoint_g_counter; endpoint_coverage += endpoint_g_counter;\n\t\t\n\t\t//**********************************************\n\t\t// COMPUTE MUTED READS AND MUT FREQ FOR ENDPOINT\n\t\t//**********************************************\n\t\tint A = endpoint_A_counter + endpoint_a_counter;\n\t\tint T = endpoint_T_counter + endpoint_t_counter;\n\t\tint C = endpoint_C_counter + endpoint_c_counter;\n\t\tint G = endpoint_G_counter + endpoint_g_counter;\n\t\t\n\t\tif (endpoint_reference == 'A'){\n\t\t\tint muted_reads = max(T,C);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tendpoint_mut_freq = double(muted_reads)/double(endpoint_coverage);\n\t\t\tif (muted_reads != 0) {\n\t\t\t\tif (muted_reads == T) endpoint_muted_in = 'T';\n\t\t\t\tif (muted_reads == C) endpoint_muted_in = 'C';\n\t\t\t\tif (muted_reads == G) endpoint_muted_in = 'G';\n\t\t\t} else endpoint_muted_in = ' ';\n\t\t}\n\t\tif (endpoint_reference == 'T'){\n\t\t\tint muted_reads = max(A,C);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tendpoint_mut_freq = double(muted_reads)/double(endpoint_coverage);\n\t\t\tif (muted_reads != 0) {\n\t\t\t\tif (muted_reads == A) endpoint_muted_in = 'A';\n\t\t\t\tif (muted_reads == C) endpoint_muted_in = 'C';\n\t\t\t\tif (muted_reads == G) endpoint_muted_in = 'G';\n\t\t\t} else endpoint_muted_in = ' ';\n\t\t}\n\t\tif (endpoint_reference == 'C'){\n\t\t\tint muted_reads = max(A,T);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tendpoint_mut_freq = double(muted_reads)/double(endpoint_coverage);\n\t\t\tif (muted_reads != 0) {\n\t\t\t\tif (muted_reads == A) endpoint_muted_in = 'A';\n\t\t\t\tif (muted_reads == T) endpoint_muted_in = 'T';\n\t\t\t\tif (muted_reads == G) endpoint_muted_in = 'G';\n\t\t\t} else endpoint_muted_in = ' ';\n\t\t}\n\t\tif (endpoint_reference == 'G'){\n\t\t\tint muted_reads = max(A,T);\n\t\t\tmuted_reads = max(muted_reads,C);\n\t\t\tendpoint_mut_freq = double(muted_reads)/double(endpoint_coverage);\n\t\t\tif (muted_reads != 0) {\n\t\t\tif (muted_reads == A) endpoint_muted_in = 'A';\n\t\t\tif (muted_reads == T) endpoint_muted_in = 'T';\n\t\t\tif (muted_reads == C) endpoint_muted_in = 'C';\n\t\t\t} else endpoint_muted_in = ' ';\n\t\t}\n\t\t\n\t\t//*******************************************\n\t\t// READ AND PARSE A LINE FROM ENDPOINT FILE\n\t\t//*******************************************\n\t\t//take line from file 1\n\t\tgetline(file_1_instream, ancestor_line);\n\t\tstringstream file_1_linestream(ancestor_line);\n\t\tgetline(file_1_linestream, ancestor_chromosome, '\\t');\n\t\t// \"chrN\", N integer\n\t\t//     ^        \n\t\tancestor_chromosome_number = atoi(&ancestor_chromosome[3]);\n\t\tfile_1_linestream >> ancestor_base_number;\n\t\tgetline(file_1_linestream, ancestor_ATCG_data, '\\n'); \n\t\t\n\t\t//parse ancestor ATCG data\n\t\tstringstream ancestor_ATCG_linestream(ancestor_ATCG_data);\n\t\t//ancestor reference\n\t\tancestor_ATCG_linestream >> ancestor_reference;\n\t\t//counters\n\t\tancestor_ATCG_linestream >> ancestor_A_counter; ancestor_coverage += ancestor_A_counter;\n\t\tancestor_ATCG_linestream >> ancestor_T_counter; ancestor_coverage += ancestor_T_counter;\n\t\tancestor_ATCG_linestream >> ancestor_C_counter; ancestor_coverage += ancestor_C_counter;\n\t\tancestor_ATCG_linestream >> ancestor_G_counter; ancestor_coverage += ancestor_G_counter;\n\t\n\t\tancestor_ATCG_linestream >> ancestor_a_counter; ancestor_coverage += ancestor_a_counter;\n\t\tancestor_ATCG_linestream >> ancestor_t_counter; ancestor_coverage += ancestor_t_counter;\n\t\tancestor_ATCG_linestream >> ancestor_c_counter; ancestor_coverage += ancestor_c_counter;\n\t\tancestor_ATCG_linestream >> ancestor_g_counter; ancestor_coverage += ancestor_g_counter;\n\t\t\n\t\t//**********************************************\n\t\t// COMPUTE MUTED READS AND MUT FREQ FOR ANCESTOR\n\t\t//**********************************************\n\t\tA = ancestor_A_counter + ancestor_a_counter;\n\t\tT = ancestor_T_counter + ancestor_t_counter;\n\t\tC = ancestor_C_counter + ancestor_c_counter;\n\t\tG = ancestor_G_counter + ancestor_g_counter;\n\t\t\n\t\tif (ancestor_reference == 'A'){\n\t\t\tint muted_reads = max(T,C);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tancestor_mut_freq = double(muted_reads)/double(ancestor_coverage);\n\t\t}\n\t\tif (ancestor_reference == 'T'){\n\t\t\tint muted_reads = max(A,C);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tancestor_mut_freq = double(muted_reads)/double(ancestor_coverage);\n\t\t}\n\t\tif (ancestor_reference == 'C'){\n\t\t\tint muted_reads = max(A,T);\n\t\t\tmuted_reads = max(muted_reads,G);\n\t\t\tancestor_mut_freq = double(muted_reads)/double(ancestor_coverage);\n\t\t}\n\t\tif (ancestor_reference == 'G'){\n\t\t\tint muted_reads = max(A,T);\n\t\t\tmuted_reads = max(muted_reads,C);\n\t\t\tancestor_mut_freq = double(muted_reads)/double(ancestor_coverage);\n\t\t}\n\n\t\t\n\t\tcount_line++; //all lines in files\n\t\t\n\t\t//**********************************************\n\t\t// APPLY THRESHOLDS (and do checks)\n\t\t//**********************************************\n\t\t\n\t\t//rarely there are \"M\",\"N\", or \"R\" in reference\n\t\t//we need to discard that line\n\t\tif(ancestor_reference != 'A' && ancestor_reference != 'T' \n\t\t&& ancestor_reference != 'C' && ancestor_reference != 'G') {\n\t\t\t//reference is not A, T, C, G\n\t\t\tdiscarded_lines++;\n\t\t\tcontinue; //skip this line\n\t\t}\n\t\t\n\t\tif(endpoint_reference != 'A' && endpoint_reference != 'T' \n\t\t&& endpoint_reference != 'C' && endpoint_reference != 'G') {\n\t\t\t//reference is not A, T, C, G\n\t\t\tdiscarded_lines++;\n\t\t\tcontinue; //skip this line\n\t\t}\n\t\t\n\t\t// check that we loaded corresponding lines\n\t\t// (common lines file are ok!)\n\t\tassert(endpoint_chromosome_number == ancestor_chromosome_number);\n\t\tassert(endpoint_base_number == ancestor_base_number);\n\t\tassert(endpoint_reference == ancestor_reference);\n\t\t\n\t\t// apply fixed threshold on ancestor's coverage min\n\t\tif (ancestor_coverage < coverage_min_ancestor) {\n\t\t\tdiscarded_lines++;\n\t\t\tcontinue; //skip this line\n\t\t}\n\t\t\n\t\t// apply theshold on ancestor mut_freq\n\t\t//same as check if == zero \n\t\tif(ancestor_mut_freq > freq_max_ancestor_confirm_reference){\n\t\t\tdiscarded_lines++;\n\t\t\tcontinue; //skip this line\n\t\t}\n\t\t\n\t\t// apply theshold on endpoint mut_freq max\n\t\tif(endpoint_mut_freq > endpoint_freq_max) {\n\t\t\tdiscarded_lines++;\n\t\t\tcontinue; //skip this line\n\t\t}\n\t\t\n\t\t//are forward and reverse reads balanced?\n\t\t// example: endpoint muted in A\n\t\t// accept line if \n\t\t// (1/2 - 1/sqrt(#(A + a))) < #(A) / #(A + a) < (1/2 + 1/sqrt(#(A + a)))\n\t\t\n\t\tif(endpoint_muted_in == 'A') {\n\t\t\tfloat forward_reads = float(endpoint_A_counter);\n\t\t\tfloat total = forward_reads + float(endpoint_a_counter);\n\t\t\tfloat x = forward_reads / total ;\n\t\t\t\n\t\t\tif ( (x < 0.5 - 1./sqrt(total)) || (x > 0.5 + 1./sqrt(total)) ){\n\t\t\t\tdiscarded_lines++;\n\t\t\t\tcontinue; //skip this line\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tif(endpoint_muted_in == 'T') {\n\t\t\tfloat forward_reads = float(endpoint_T_counter);\n\t\t\tfloat total = forward_reads + float(endpoint_t_counter);\n\t\t\tfloat x = forward_reads / total ;\n\t\t\t\n\t\t\tif ( (x < 0.5 - 1./sqrt(total)) || (x > 0.5 + 1./sqrt(total)) ){\n\t\t\t\tdiscarded_lines++;\n\t\t\t\tcontinue; //skip this line\n\t\t\t}\n\t\t}\t\n\t\tif(endpoint_muted_in == 'C') {\n\t\t\tfloat forward_reads = float(endpoint_C_counter);\n\t\t\tfloat total = forward_reads + float(endpoint_c_counter);\n\t\t\tfloat x = forward_reads / total ;\n\t\t\t\n\t\t\tif ( (x < 0.5 - 1./sqrt(total)) || (x > 0.5 + 1./sqrt(total)) ){\n\t\t\t\tdiscarded_lines++;\n\t\t\t\tcontinue; //skip this line\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(endpoint_muted_in == 'G') {\n\t\t\tfloat forward_reads = float(endpoint_G_counter);\n\t\t\tfloat total = forward_reads + float(endpoint_g_counter);\n\t\t\tfloat x = forward_reads / total ;\n\t\t\t\n\t\t\tif ( (x < 0.5 - 1./sqrt(total)) || (x > 0.5 + 1./sqrt(total)) ){\n\t\t\t\tdiscarded_lines++;\n\t\t\t\tcontinue; //skip this line\n\t\t\t}\n\t\t}\n\t\t\n\t\t//**********************************************\n\t\t// DECIDE IF MUTED OR NOT\n\t\t//**********************************************\n\t\t// finally if here theese lines are fine with all thresholds\n\t\t//check if to be considered muted or not \n\t\t\n\t\tif( endpoint_muted(endpoint_mut_freq, endpoint_coverage, extant)){\n\t\t\t//muted -> Numerator & denominator\n\t\t\tmuted_bases++; \n\t\t} else {\n\t\t\t//not muted -> Denominator\n\t\t\tnot_muted_bases++;\n\t\t}\n\t} //EOF\n\t\n\t//Print result summary\n\t\n\tcout << \"File readings ended: total lines \" << count_line << endl;\n\tcout << \"Discarded: \" << discarded_lines << endl;\n\tcout << \"Parameter used extant = \" << extant << endl;\n\t\n\tassert(count_line - discarded_lines == muted_bases + not_muted_bases);\n\t\n\t// compute muted/(muted + not_muted)\t\n\tcout << \"Muted bases:\" << muted_bases << endl;\n\tcout << \"Not muted bases: \" << not_muted_bases << endl;\n\t\n\tP_hat = double (muted_bases) / double (muted_bases + not_muted_bases);\n\t\n\tcout << \"muted/(muted + not_muted) = \" << P_hat <<endl; \n\t\n\tcout << \"Mutatior rate min [d/(b+d) = 0.45] = \" << compute_mut_rate(P_hat, 0.45, extant) << endl;\n\t\n\tcout << \"Mutation rate max [d/(b+d) = 0.1] = \" << compute_mut_rate(P_hat, 0.1, extant) << endl;\n\t\n\t//Cleanup\n\tfile_1.close();\n\tfile_2.close();\n\t\n\treturn 0;\n} // main\n\t\t\n\t\t\ndouble compute_mut_rate(double P_hat, double death_prob, int extant){\n\n\t// gen = log_{2*(1-death_prob)} extant\n\tfloat generations = log(extant)/log(2.*(1.-death_prob));\n\t\n\t//integral estimate with continuous time\n\tfloat attempts = (1. - death_prob*death_prob) * (\n\t\t\t\t( pow((2*(1-death_prob)), generations - 1.) - 1.) /\n\t\t\t  \tlog(2.*(1.- death_prob))\n\t\t\t  \t) + extant;\n\t\t\t  \t\t\t  \t\n\tdouble mut_rate = -1. *( log(1. - P_hat)/attempts);\n\t\n\treturn mut_rate;\n}\n\nbool endpoint_muted(float mut_freq, int total_coverage, int extant){\n/*\nCount base as muted if endpoint frequency \n\n\tf >= Cutoff(Coverage, f_min) e Coverage = TotCoverage/3\n\n\tcutoff (Coverage, f_min) = f_min + alpha/Sqrt[Coverage]\n\nbased on extant f_min and corresponding alphas are\n\n\tf_min = {1/8, 1/12, 1/16, 1/20, 1/24, 1/28, 1/32, 1/48, 1/75, 1/100}\n\n\talpha = {0.52, 0.45, 0.36, 0.32, 0.3, 0.28, 0.25, 0.2, 0.18, 0.15} \n*/\n\tfloat f_min= 0.;\n\tfloat coverage = float(total_coverage)/3.;\n\tdouble alpha = 0.;\n\t\n\tif (extant == 8){\n\t\tf_min = 1./extant;\n\t\talpha = 0.52;\n\t}\n\tif (extant == 12){\n\t\tf_min = 1./extant;\n\t\talpha = 0.45;\n\t}\n\t\n\tif (extant == 16){\n\t\tf_min = 1./extant;\n\t\talpha = 0.36;\n\t}\n\tif (extant == 20){\n\t\tf_min = 1./extant;\n\t\talpha = 0.32;\n\t}\n\tif (extant == 24){\n\t\tf_min = 1./extant;\n\t\talpha = 0.3;\n\t}\n\tif (extant == 28){\n\t\tf_min = 1./extant;\n\t\talpha = 0.28;\n\t}\n\tif (extant == 32){\n\t\tf_min = 1./extant;\n\t\talpha = 0.25;\n\t}\n\tif (extant == 48){\n\t\tf_min = 1./extant;\n\t\talpha = 0.2;\n\t}\n\t\n\tif (extant == 75){\n\t\tf_min = 1./extant;\n\t\talpha = 0.18;\n\t}\n\tif (extant == 100){\n\t\tf_min = 1./extant;\n\t\talpha = 0.15;\n\t}\n\t\n\tif ( mut_freq >= f_min + alpha/sqrt(coverage) ) {\n\t\t//muted\n\t\treturn true;\n\t} else {\n\t\t//not muted\n\t\treturn false;\n\t}\n}\n", "meta": {"hexsha": "5e72e1b26234bd39806c3cb40709ffc9870fe0bc", "size": 18002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LD_Data_Analysis/Code/estimate_mut_rate.cpp", "max_stars_repo_name": "PietroRivetti/LD-mut-rate", "max_stars_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LD_Data_Analysis/Code/estimate_mut_rate.cpp", "max_issues_repo_name": "PietroRivetti/LD-mut-rate", "max_issues_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LD_Data_Analysis/Code/estimate_mut_rate.cpp", "max_forks_repo_name": "PietroRivetti/LD-mut-rate", "max_forks_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_forks_repo_licenses": ["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.5824561404, "max_line_length": 162, "alphanum_fraction": 0.6404288412, "num_tokens": 5052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5702791123685845}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n#ifndef _DAVIDSON_SOLVER_\n#define _DAVIDSON_SOLVER_\n\nclass DavidsonSolver\n{\n\n\tpublic:\n\n\t\tDavidsonSolver();\n\n\t\tvoid set_iter_max(int N) { this->iter_max = N; }\n\t\tvoid set_tolerance(double eps) { this->tol = eps; }\n\t\tvoid set_max_search_space(int N) { this->max_search_space = N;}\n\t\tvoid set_initial_guess_size(int N) {this->size_initial_guess=N;}\n\t\tvoid set_linsolve_tol(double tol){this->linsolve_tol=tol;}\n\t\tvoid set_guess_vectors(std::string method){this->guess_vectors=method;} \n\n\t\tvoid set_correction(std::string method); \n\t\tvoid set_jacobi_linsolve(std::string method);\n\n\t\tEigen::VectorXd eigenvalues() const {return this->_eigenvalues;}\n\t\tEigen::MatrixXd eigenvectors() const {return this->_eigenvectors;}\n\n\n\n\t\ttemplate <typename MatrixReplacement>\n\t\tvoid solve(MatrixReplacement &A, int neigen, int size_initial_guess = 0)\n\t\t{\n\n\t\t    std::cout << std::endl;\n\t\t    std::cout << \"===========================\" << std::endl; \n\t\t    if(this->correction == CORR::JACOBI)  std::cout << \"= Jacobi-Davidson  : \" << this->jacobi_linsolve <<  std::endl; \n\t\t    \n\t\t    else if (this->correction == CORR::OLSEN)  std::cout << \"= Olsen-Davidson  : \" <<  std::endl;    \n\t\t    \n\t\t    else  std::cout << \"= Davidson (DPR)\" <<  std::endl; \n\n\t\t    std::cout << \"===========================\" << std::endl;\n\t\t    std::cout << std::endl;\n\n\t\t    //double res_norm;\n\t\t    Eigen::ArrayXd res_norm = Eigen::ArrayXd::Zero(neigen);\n\t\t    Eigen::ArrayXd root_converged = Eigen::ArrayXd::Zero(neigen);\n\t\t    Eigen::ArrayXd lambda_conv = Eigen::ArrayXd::Zero(neigen);\n\t\t    int size = A.rows();\n\t\t    bool has_converged = false;\n\n\t\t    // initial guess size\n\t\t    if (size_initial_guess == 0) {\n\t\t    \tsize_initial_guess = 2 * neigen;\n\t\t    \tif (size_initial_guess < 10)\n\t\t    \t\tsize_initial_guess = 10;\n\t\t    }\n\t\t    int search_space = size_initial_guess;\n\t\t    max_search_space = 2*size_initial_guess;\n\n\t\t    // initialize the guess eigenvector\n\t\t    Eigen::VectorXd Adiag = A.diagonal();    \n\t\t    Eigen::MatrixXd V = DavidsonSolver::_get_initial_eigenvectors(Adiag,size_initial_guess);\n\t\t    \n\n\t\t    Eigen::VectorXd lambda; // eigenvalues hodlers\n\t\t    Eigen::VectorXd old_val = Eigen::VectorXd::Zero(neigen);\n\t\t    \n\t\t    // temp varialbes \n\t\t    Eigen::MatrixXd T, U, q;\n\t\t    Eigen::VectorXd w, tmp;\n\t\t    \n\n\t\t    // project the matrix on the trial subspace\n\t\t    T = A * V;\n\t\t    T = V.transpose()*T;\n\n\t\t    printf(\"iter\\tSearch Space\\tNorm/%.0e\\n\",tol);\n\t\t    std::cout << \"-----------------------------------\" << std::endl;\n\t\t    for (int iiter = 0; iiter < iter_max; iiter ++ )\n\t\t    {\n\t\t        \n\t\t        // std::cout << \"\\nT:\\n\" << T << std::endl;\n\t\t        // diagonalize the small subspace\n\t\t        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(T);\n\t\t        lambda = es.eigenvalues();\n\t\t        U = es.eigenvectors();\n\n\t\t        // Ritz eigenvectors\n\t\t        q = V*U.block(0,0,U.rows(),neigen);\n\n\t\t        // residue and correction vectors\n\t\t        for (int j=0; j<neigen; j++) {   \n\n\t\t        \t// (not root_converged[j]) {\n\n\t\t\t            // residue vector\n\t\t\t            w = A*q.col(j) - lambda(j)*q.col(j);\n\t\t\t            res_norm[j] = w.norm();\n\n\t\t\t            // jacobi-davidson correction\n\t\t\t            if (this->correction == CORR::JACOBI) {\n\t\t\t                tmp = q.col(j);\n\t\t\t                w = DavidsonSolver::_jacobi_correction<MatrixReplacement>(A,w,tmp,lambda(j));\n\t\t\t            }\n\n\t\t\t            else if (this->correction == CORR::OLSEN) {\n\t\t\t            \ttmp = q.col(j);\n\t\t\t                w = DavidsonSolver::_olsen_correction(w,tmp,Adiag,lambda(j));\n\t\t\t            }\n\t\t\t            \n\t\t\t            // Davidson DPR\n\t\t\t            else  {\n\t\t\t                w = DavidsonSolver::_dpr_correction(w,Adiag,lambda(j));\n\t\t\t            }\n\n\t\t\t            // append the correction vector to the search space\n\t\t\t            V.conservativeResize(Eigen::NoChange,V.cols()+1);\n\t\t\t            V.col(V.cols()-1) = w.normalized();\n\n\t\t\t            // check the root\n\t\t\t            root_converged[j] = res_norm[j] < tol;\n\t\t\t        //}\n\t\t            \n\t\t        }\n\n\t\t        // eigenvalue norm\n\t\t        lambda_conv = (lambda.head(neigen)-old_val).array().abs();\n\t\t        printf(\"%4d\\t%12d\\t%4.2e\\t%4.2e\\t%4.1f%% converged\\n\", iiter,search_space,res_norm.maxCoeff(),lambda_conv.maxCoeff(),100*root_converged.sum()/neigen);\n\n\t\t        // update \n\t\t        search_space = V.cols();\n\t\t        old_val = lambda.head(neigen);\n\t\t        \t\t       \n\t\t        // break if converged, update otherwise\n\t\t        if((res_norm<tol).all()) {\n\t\t        //if((lambda_conv<tol).all()) {\n\t\t            has_converged = true;\n\t\t            break;\n\t\t        }\n\n\t\t        // check if we need to restart\n\t\t        if (search_space > max_search_space or search_space > size )\n\t\t        {\n\n\t\t            V = q.block(0,0,V.rows(),neigen);\n\t\t            for (int j=0; j<neigen; j++) {\n\t\t                V.col(j) = V.col(j).normalized();\n\t\t            }\n\t\t            search_space = neigen;\n\n\t\t            // recompute the projected matrix\n\t\t            T = V.transpose()*(A * V);\n\t\t        }\n\n\t\t        // continue otherwise\n\t\t        else\n\t\t        {\n\t\t            // orthogonalize the V vectors\n\t\t            //V = DavidsonSolver::_QR(V);\n\t\t            V = DavidsonSolver::_gramschmidt(V,V.cols()-neigen);\n\t\t            \n\t\t            // update the T matrix : avoid recomputing V.T A V \n\t\t            // just recompute the element relative to the new eigenvectors\n\t\t            DavidsonSolver::_update_projected_matrix<MatrixReplacement>(T,A,V);\n\t\t            \n\t\t        }\n\t\t        \n\t\t    }\n\n\t\t    // store the eigenvalues/eigenvectors\n\t\t    this->_eigenvalues = lambda.head(neigen);\n\t\t    this->_eigenvectors = q.block(0,0,q.rows(),neigen);\n\n\t\t    // normalize the eigenvectors\n\t\t    for (int i=0; i<neigen; i++){\n\t\t        this->_eigenvectors.col(i).normalize();\n\t\t    }\n\n\t\t    std::cout << \"-----------------------------------\" << std::endl;\n\t\t    if (!has_converged) {\n\t\t        std::cout << \"- Warning : Davidson didn't converge ! \" <<  std::endl; \n\t\t        this->_eigenvalues = Eigen::VectorXd::Zero(neigen);\n\t\t        this->_eigenvectors = Eigen::MatrixXd::Zero(size,neigen);\n\t\t    }\n\t\t    else   {\n\t\t        std::cout << \"- Davidson converged \" <<  std::endl; \n\t\t        printf(\"- final residue norm %4.2e\\n\",res_norm.maxCoeff());\n\t\t        printf(\"- final eigenvalue norm %4.2e\\n\",lambda_conv.maxCoeff());\n\t\t    }\n\t\t    std::cout << \"-----------------------------------\" << std::endl;\n\t\t    \n\t\t}\n\n\n\tprivate :\n\n\t\tint iter_max = 1000;\n\t\tdouble tol = 1E-6;\n\t\tint max_search_space = 100;\n\t\tint size_initial_guess = 0;\n\t\tdouble linsolve_tol = 1E-3;\n\n\t\tstd::string guess_vectors = \"target\";\n\t\tenum CORR {DPR,JACOBI,OLSEN};\n\t\tenum LSOLVE {CG,GMRES,LLT};\n\t\t\n\t\tCORR correction = CORR::DPR;\n\t\tLSOLVE jacobi_linsolve = LSOLVE::CG;\n\n\n\n\t\tEigen::VectorXd _eigenvalues;\n\t\tEigen::MatrixXd _eigenvectors; \n\n\t\tEigen::ArrayXd _sort_index(Eigen::VectorXd &V) const;\n\t\tEigen::MatrixXd _get_initial_eigenvectors(Eigen::VectorXd &D, int size ) const;\n\t\tEigen::MatrixXd _solve_linear_system(Eigen::MatrixXd &A, Eigen::VectorXd &b) const; \n\t\tEigen::MatrixXd _QR(Eigen::MatrixXd &A) const;\n\t\tEigen::MatrixXd _gramschmidt( Eigen::MatrixXd &A, int nstart ) const;\n\n\t\ttemplate <typename MatrixReplacement>\n\t\tEigen::MatrixXd _jacobi_correction(MatrixReplacement &A, Eigen::VectorXd &r, Eigen::VectorXd &u, double lambda) const\n\t\t{\n\n\t\t\tstd::chrono::time_point<std::chrono::system_clock> start, end;\n    \t\tstd::chrono::duration<double> elapsed_time;\n\n    \t\tstart = std::chrono::system_clock::now();\n\t\t    // form the projector  P = I -u * u.T\n\t\t    Eigen::MatrixXd P = -u*u.transpose();\n\t\t    P.diagonal().array() += 1.0;\n\n\t\t    // project the matrix P * (A - lambda*I) * P^T\n\t\t    Eigen::MatrixXd projA = A*P.transpose();\n\t\t    projA -= lambda*P.transpose();\n\t\t    projA = P * projA;\n\t\t    end = std::chrono::system_clock::now();\n\t\t    elapsed_time = end-start;\n\t\t    std::cout << \"_ form linear system \" << this->jacobi_linsolve << \" in \" << elapsed_time.count() << \" secs\" <<  std::endl;\n\t\t    return DavidsonSolver::_solve_linear_system(projA,r);\n\t\t}\n\n\t\tEigen::VectorXd _dpr_correction(Eigen::VectorXd &w, Eigen::VectorXd &A0, double lambda) const;\n\t\tEigen::VectorXd _olsen_correction(Eigen::VectorXd &r, Eigen::VectorXd &x, Eigen::VectorXd &D, double lambda) const;\n\n\t\ttemplate<class MatrixReplacement>\n\t\tvoid _update_projected_matrix(Eigen::MatrixXd &T, MatrixReplacement &A, Eigen::MatrixXd &V) const\n\t\t{\n\t\t    int nvec_old = T.cols();\n\t\t    int nvec = V.cols();\n\t\t    int nnew_vec = nvec-nvec_old;\n\n\t\t    Eigen::MatrixXd _tmp = A * V.block(0,nvec_old,nvec,nnew_vec);\n\t\t    T.conservativeResize(nvec,nvec);\n\t\t    T.block(0,nvec_old,nvec,nnew_vec) = V.transpose() * _tmp;\n\t\t    T.block(nvec_old,0,nnew_vec,nvec_old) = T.block(0,nvec_old,nvec_old,nnew_vec).transpose();\n\n\t\t    return;\n\t\t}\n};\n\n\n#endif", "meta": {"hexsha": "17e321a47c6bcc505358a86cba20d7f70649509a", "size": 8927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DavidsonSolver.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/DavidsonSolver.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/DavidsonSolver.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": 33.8143939394, "max_line_length": 160, "alphanum_fraction": 0.5709644898, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5702791069737214}}
{"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_CONJUGATE_GRADIENT_HPP\n#define BOOST_UBLAS_CONJUGATE_GRADIENT_HPP\n\n#include \"krylov_solvers_config.hpp\"\n\n#include <boost/numeric/ublas/vector.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\nnamespace detail {\n\ntemplate<class F1, class F2, class E, class V, typename Int, typename Floating>\nstd::tuple<Int, Floating>\nconjugate_gradient_impl(const F1& A, const F2& PInv, const vector_expression<E>& b, V& x,\n           Int max_iter_, Floating tol_, std::false_type) {\n    typedef typename V::value_type value_type;\n    typedef typename V::size_type size_type;\n    typedef vector<value_type> vector_type;\n    typedef std::tuple<Int, Floating> return_type;\n\n    BOOST_UBLAS_CHECK(b().size() == x.size(), bad_size());\n    BOOST_UBLAS_CHECK(max_iter_ > Int/*zero*/(), bad_argument());\n    BOOST_UBLAS_CHECK(tol_ > Floating/*zero*/(), bad_argument());\n\n    size_type max_iter = static_cast<size_type>(max_iter_);\n    value_type tol = static_cast<value_type>(tol_);\n\n    size_type n = x.size();\n    // adjust max_iter\n    max_iter = std::min(n, max_iter);\n\n    value_type b_norm = norm_2(b);\n    if (b_norm == value_type/*zero*/()) {\n        x *= value_type/*zero*/();\n        return return_type(Int/*zero*/(), Floating/*zero*/());\n    }\n\n    vector_type r = b - A(x);\n    value_type error = norm_2(r) / b_norm;\n    if (error < tol) {\n        return return_type(Int/*zero*/(), error);\n    }\n\n    vector_type z = PInv(r);\n    vector_type p(z);\n\n    value_type r_sq_old = inner_prod(r, z);\n\n    size_type num_iter = 1;\n    for (; num_iter <= max_iter; ++num_iter) {\n        vector_type Ap = A(p);\n        value_type alpha = r_sq_old / inner_prod(p, Ap);\n        x.plus_assign(alpha*p);\n        r.minus_assign(alpha*Ap);\n        z.assign(PInv(r));\n        value_type r_sq_new = inner_prod(r, z);\n        error = norm_2(r) / b_norm;\n        if (error < tol) {\n            return return_type(num_iter, error);\n        }\n\n        p = z + (r_sq_new / r_sq_old)*p;\n        r_sq_old = r_sq_new;\n    }\n\n    return return_type(n, norm_2(r) / b_norm);\n}\n\ntemplate<class M, class F, class E, class V, typename Int, typename Floating>\nstd::tuple<Int, Floating>\nconjugate_gradient_impl(const M& A, const F& PInv, const vector_expression<E>& b, V& x,\n           Int max_iter_, Floating tol_, std::true_type) {\n    return conjugate_gradient_impl([&A](const auto& v){return ublas::prod(A, v);}, PInv,\n                      b, x, max_iter_, tol_, std::false_type());\n}\n\n} // end namespace detail\n\n\ntemplate <class M, class F = identity_precond<M> >\nclass conjugate_gradient {\npublic:\n    // param\n    struct param {\n        int max_iter = 10;\n        int restart_iter = 10;\n        double tol = 1e-5;\n    };\n\n    typedef std::tuple<int, double> return_type;\n\n    conjugate_gradient(const M& A)\n        : A_(A), PInv_(A) {}\n\n    conjugate_gradient(const M& A, const param& p)\n        : A_(A), PInv_(A), param_(p) {}\n\n    conjugate_gradient(const M& A, const F& PInv)\n        : A_(A), PInv_(PInv) {}\n\n    conjugate_gradient(const M& A, F&& PInv)\n        : A_(A), PInv_(std::move(PInv)) {}\n\n    conjugate_gradient(const M& A, const F& PInv, const param& p)\n        : A_(A), PInv_(PInv), param_(p) {}\n\n    conjugate_gradient(const M& A, F&& PInv, const param& p)\n        : A_(A), PInv_(PInv), param_(p) {}\n\n    conjugate_gradient(const conjugate_gradient&) = delete;\n    conjugate_gradient(conjugate_gradient&&) = delete;\n    conjugate_gradient& operator=(const conjugate_gradient&) = delete;\n    conjugate_gradient& operator=(conjugate_gradient&&) = delete;\n\n    param get_param() const {\n        return param_;\n    }\n\n    void set_param(const param& p) {\n        param_ = p;\n    }\n\n    template<class E, class V>\n    return_type operator()(const vector_expression<E>& b, V& x) const {\n        return detail::conjugate_gradient_impl(A_, PInv_, b, x,\n                                       param_.max_iter,\n                                       param_.tol,\n                                       detail::is_matrix_expression_t<M>());\n    }\n\nprivate:\n    const M& A_;\n    F PInv_;\n    param param_;\n};\n\n} // end namespace linear\n} // end namespace solver\n} // end namespace math\n\n\n#endif\n\n", "meta": {"hexsha": "a1553b5fe969e45f06872725e7ca794d18e057a0", "size": 5270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/conjugate_gradient.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/conjugate_gradient.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/conjugate_gradient.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": 31.369047619, "max_line_length": 89, "alphanum_fraction": 0.6554079696, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5702786252209803}}
{"text": "#include <iostream>\n#include <climits>\n// BGL include\n#include <boost/graph/adjacency_list.hpp>\n\n// BGL flow include *NEW*\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/edmonds_karp_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\nusing namespace std;\n\n\nint c_to_i (char c) {\n  return c - 'A';\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\nvoid make_it_flow() {\n  int h, w;\n  cin >> h; cin >> w;\n  string note; cin >> note;\n  int n = note.length();\n  graph G(26 * 26 + 26);\n  edge_adder adder(G);\n  // Add special vertices source and sink\n  const vertex_desc v_source = boost::add_vertex(G);\n  const vertex_desc v_sink = boost::add_vertex(G);\n\n  vector<int> char_count(26, 0);\n  for(int i = 0; i < n; i++) {\n    char c = note[i];\n    char_count[c_to_i(c)]++;\n  }\n  \n  vector<int> pair_count(26*26, 0);\n  vector<string> front(h);\n  for(int i = 0; i < h; i++) {\n    string line; cin >> line;\n    front[i] = line;  \n    // for(int j = 0; j < w; j++) {\n    //   char c = line[j];\n    //   adder.add_edge(i * w + j, h * w + c_to_i(c), 1);\n    // }\n  }\n  vector<string> back(h);\n  for(int i = 0; i < h; i++) {\n    string line; cin >> line;\n    back[i] = line;\n    // for(int j = w - 1; j >= 0; j--) {\n    //   char c = line[w - j - 1];\n    //   adder.add_edge(i * w + j, h * w + c_to_i(c), 1);\n    // }\n  }\n  \n  for(int i = 0; i < h; i++) {\n    string line_front = front[i];\n    string line_back = back[i];\n    for(int j = 0; j < w; j++) {\n      char c_front = line_front[j];\n      char c_back = line_back[w - j - 1];\n      int i_front = c_to_i(c_front);\n      int i_back = c_to_i(c_back);\n      pair_count[i_front * 26 + i_back]++;\n    }\n  }\n  \n  for(int i = 0; i < 26; i++) {\n    for(int j = 0; j < 26; j++) {\n      adder.add_edge(i * 26 + j, 26 * 26 + i, INT_MAX);\n      adder.add_edge(i * 26 + j, 26 * 26 + j, INT_MAX);\n    }\n  }\n  \n  for(int i = 0; i < 26 * 26; i++) {\n    adder.add_edge(v_source, i, pair_count[i]);\n  }\n  \n  \n  for(int i = 0; i < 26; i++) {\n    adder.add_edge(26 * 26 + i, v_sink, char_count[i]);\n  }\n  \n  // Calculate flow from source to sink\n  // The flow algorithm uses the interior properties (managed in the edge adder)\n  // - edge_capacity, edge_reverse (read access),\n  // - edge_residual_capacity (read and write access).\n  long flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  if(flow == n) {\n    std::cout << \"Yes\" << \"\\n\";\n  } else {\n    std::cout << \"No\" << \"\\n\";\n  }\n  \n  \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); // Always!\n  int t; cin >> t;\n  while(t--) {\n    // cerr << \"-----------------testcase done\" << endl;\n    make_it_flow();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "d75824ab2d575afb46f532ec6d3fb044d84b9311", "size": 4347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week07-london/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/week07-london/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/week07-london/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7739726027, "max_line_length": 94, "alphanum_fraction": 0.5988037727, "num_tokens": 1328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6757646075489391, "lm_q1q2_score": 0.5702744374840796}}
{"text": "// Filename: matrix_free_1.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\tassert(int(size(v)) == m * n);\n\tVector w(m * n);\n\t\n\tfor (int i= 0; i < m; i++)\n\t    for (int j= 0; j < n; j++) {\n\t\tint k= i * n + j; // offset\n\t\tw[k]= 4 * v[k];\n\t\tif (i > 0) w[k]-= v[k-n];   // upper neighbor\n\t\tif (i < m-1) w[k]-= v[k+n]; // lower neighbor\n\t\tif (j > 0) w[k]-= v[k-1];   // left neighbor\n\t\tif (j < n-1) w[k]-= v[k+1]; // right neighbor\n\t    }\n\treturn w;\n    }\n    int m, n;\n};\n\nnamespace mtl { namespace ashape {\n    template <> struct ashape_aux<poisson2D_dirichlet> \n    {\ttypedef nonscal type;    };\n}}\n\nint main(int, char**)\n{\n    using namespace std;\n\n    mtl::dense_vector<double> v(20);\n    iota(v);\n\n    poisson2D_dirichlet A(4, 5);\n    cout << \"A * v is \" << A * v << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "4f716c83dfe24bef6c6d5dfd8028eed4c2f6da92", "size": 1006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_free_1.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_1.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_1.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 20.9583333333, "max_line_length": 55, "alphanum_fraction": 0.5536779324, "num_tokens": 358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5702718549870102}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_BITWISE_FUNCTIONS_SIMD_COMMON_POPCNT_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_SIMD_COMMON_POPCNT_HPP_INCLUDED\n\n#include <boost/simd/bitwise/functions/popcnt.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/bitwise_notand.hpp>\n#include <boost/simd/include/functions/simd/bitwise_and.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/rem.hpp>\n#include <boost/simd/include/functions/simd/shri.hpp>\n#include <boost/simd/include/constants/digits.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::popcnt_, tag::cpu_, (A0)(X)\n                            , ((simd_<int8_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, unsigned>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      const result_type m1  = boost::simd::integral_constant<result_type,0x55>(); //binary: 0101...\n      const result_type m2  = boost::simd::integral_constant<result_type,0x33>(); //binary: 00110011..\n      const result_type m4  = boost::simd::integral_constant<result_type,0x0f>(); //binary:  4 zeros,  4 ones ...\n      result_type x = simd::bitwise_cast<result_type>(a0);\n      x -= (shri(x, 1)) & m1;             //put count of each 2 bits into those 2 bits\n      x = (x & m2) + (shri(x, 2) & m2); //put count of each 4 bits into those 4 bits\n      x = (x + shri(x, 4)) & m4;        //put count of each 8 bits into those 8 bits\n      return x & boost::simd::integral_constant<result_type,0x7f > ();\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::popcnt_, tag::cpu_, (A0)(X)\n                            , ((simd_<int64_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, unsigned>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      const result_type m1  = boost::simd::integral_constant<result_type,0x5555555555555555ULL>(); //binary: 0101...\n      const result_type m2  = boost::simd::integral_constant<result_type,0x3333333333333333ULL>(); //binary: 00110011..\n      const result_type m4  = boost::simd::integral_constant<result_type,0x0f0f0f0f0f0f0f0fULL>(); //binary:  4 zeros,  4 ones ...\n      result_type x = simd::bitwise_cast<result_type>(a0);\n      x -= (shri(x, 1)) & m1;             //put count of each 2 bits into those 2 bits\n      x = (x & m2) + (shri(x, 2) & m2); //put count of each 4 bits into those 4 bits\n      x = (x + shri(x, 4)) & m4;        //put count of each 8 bits into those 8 bits\n      x += shri(x, 8);  //put count of each 16 bits into their lowest 8 bits\n      x += shri(x, 16);  //put count of each 32 bits into their lowest 8 bits\n      x += shri(x, 32);  //put count of each 64 bits into their lowest 8 bits\n      return x & boost::simd::integral_constant<result_type,0x7f > ();\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::popcnt_, tag::cpu_, (A0)(X)\n                            , ((simd_<int16_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, unsigned>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      const result_type m1  = boost::simd::integral_constant<result_type,0x5555>(); //binary: 0101...\n      const result_type m2  = boost::simd::integral_constant<result_type,0x3333>(); //binary: 00110011..\n      const result_type m4  = boost::simd::integral_constant<result_type,0x0f0f>(); //binary:  4 zeros,  4 ones ...\n      result_type x = simd::bitwise_cast<result_type>(a0);\n      x -= (shri(x, 1)) & m1;             //put count of each 2 bits into those 2 bits\n      x = (x & m2) + (shri(x, 2) & m2); //put count of each 4 bits into those 4 bits\n      x = (x + shri(x, 4)) & m4;        //put count of each 8 bits into those 8 bits\n      x += shri(x, 8);  //put count of each 16 bits into their lowest 8 bits\n      return x & boost::simd::integral_constant<result_type,0x7f > ();\n      }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::popcnt_, tag::cpu_, (A0)(X)\n                            , ((simd_<int32_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, unsigned>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      const result_type m1  = boost::simd::integral_constant<result_type,0x55555555>(); //binary: 0101...\n      const result_type m2  = boost::simd::integral_constant<result_type,0x33333333>(); //binary: 00110011..\n      const result_type m4  = boost::simd::integral_constant<result_type,0x0f0f0f0f>(); //binary:  4 zeros,  4 ones ...\n      result_type x = simd::bitwise_cast<result_type>(a0);\n      x -= (shri(x, 1)) & m1;             //put count of each 2 bits into those 2 bits\n      x = (x & m2) + (shri(x, 2) & m2); //put count of each 4 bits into those 4 bits\n      x = (x + shri(x, 4)) & m4;        //put count of each 8 bits into those 8 bits\n      x += shri(x, 8);  //put count of each 16 bits into their lowest 8 bits\n      x += shri(x, 16);  //put count of each 32 bits into their lowest 8 bits\n      return x & boost::simd::integral_constant<result_type,0x7f > ();\n      }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::popcnt_, tag::cpu_, (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_integer<A0, unsigned>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      return popcnt(simd::bitwise_cast<result_type>(a0));\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "40a44d5e7df9bfeb825b7cdd1ff8f720f3130620", "size": 6129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/common/popcnt.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/common/popcnt.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/bitwise/include/boost/simd/bitwise/functions/simd/common/popcnt.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.2956521739, "max_line_length": 130, "alphanum_fraction": 0.6110295317, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5701495438748546}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <future>\n#include <random>\n#include <stdexcept>\n#include <thread>\n#include <tuple>\n#include <unordered_map>\n\n#include \"argcheck.hpp\"\n\nnamespace irspack {\nnamespace sparse_util {\n\ntemplate <typename Real>\nusing CSRMatrix = Eigen::SparseMatrix<Real, Eigen::RowMajor>;\n\ntemplate <typename Real>\nusing DenseVector = Eigen::Matrix<Real, Eigen::Dynamic, 1>;\n\ntemplate <typename Real>\nusing CSCMatrix = Eigen::SparseMatrix<Real, Eigen::ColMajor>;\n\ntemplate <typename Real>\ninline CSRMatrix<Real> parallel_sparse_product(const CSRMatrix<Real> &left,\n                                               const CSCMatrix<Real> &right,\n                                               const size_t n_thread) {\n  CSRMatrix<Real> result(left.rows(), right.cols());\n  check_arg(n_thread > 0, \"n_thraed must be > 0\");\n  const int n_row = left.rows();\n  const int rows_per_block = n_row / n_thread;\n  const int remnant = n_row % n_thread;\n  int start = 0;\n  std::vector<std::future<CSRMatrix<Real>>> workers;\n  for (int i = 0; i < static_cast<int>(n_thread); i++) {\n    int block_size = rows_per_block;\n    if (i < remnant) {\n      ++block_size;\n    }\n    workers.emplace_back(std::async(std::launch::async, [&left, &right, start,\n                                                         block_size]() {\n      CSRMatrix<Real> local_result = left.middleRows(start, block_size) * right;\n      return local_result;\n    }));\n    start += block_size;\n  }\n  start = 0;\n  for (int i = 0; i < static_cast<int>(n_thread); i++) {\n    int block_size = rows_per_block;\n    if (i < remnant) {\n      ++block_size;\n    }\n    result.middleRows(start, block_size) = workers[i].get();\n    start += block_size;\n  }\n  return result;\n}\n\ntemplate <typename Real, typename Integer = int64_t>\nstd::pair<CSCMatrix<Real>, CSRMatrix<Real>>\ntrain_test_split_rowwise(const CSRMatrix<Real> &X, const double test_ratio,\n                         std::int64_t random_seed) {\n  using Triplet = Eigen::Triplet<Integer>;\n  std::mt19937 random_state(random_seed);\n  check_arg(((test_ratio <= 1.0 && (test_ratio >= 0.0))),\n            \"test_ratio must be within [0, 1]\");\n  std::vector<Integer> col_buffer;\n  std::vector<Real> data_buffer;\n  std::vector<uint64_t> index_;\n  std::vector<Triplet> train_data, test_data;\n  for (int row = 0; row < X.outerSize(); ++row) {\n    col_buffer.clear(); // does not change capacity\n    data_buffer.clear();\n    index_.clear();\n    Integer cnt = 0;\n    for (typename CSRMatrix<Real>::InnerIterator it(X, row); it; ++it) {\n      index_.push_back(cnt);\n      col_buffer.push_back(it.col());\n      data_buffer.push_back(it.value());\n      cnt += 1;\n    }\n    std::shuffle(index_.begin(), index_.end(), random_state);\n    size_t n_test = static_cast<Integer>(std::floor(cnt * test_ratio));\n    for (size_t i = 0; i < n_test; i++) {\n      test_data.emplace_back(row, col_buffer[index_[i]],\n                             data_buffer[index_[i]]);\n    }\n    for (size_t i = n_test; i < col_buffer.size(); i++) {\n      train_data.emplace_back(row, col_buffer[index_[i]],\n                              data_buffer[index_[i]]);\n    }\n  }\n  CSRMatrix<Real> X_train(X.rows(), X.cols()), X_test(X.rows(), X.cols());\n  auto dupfunction = [](const Integer &a, const Integer &b) { return a + b; };\n  X_train.setFromTriplets(train_data.begin(), train_data.end(), dupfunction);\n  X_test.setFromTriplets(test_data.begin(), test_data.end(), dupfunction);\n  X_train.makeCompressed();\n  X_test.makeCompressed();\n  return {X_train, X_test};\n}\n\ntemplate <typename Real>\nCSRMatrix<Real> okapi_BM_25_weight(const CSRMatrix<Real> &X, Real k1, Real b) {\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  DenseVector<Real> idf(X.cols());\n  DenseVector<Real> doc_length(N);\n  idf.array() = 0;\n  doc_length.array() = 0;\n\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(X, i); iter; ++iter) {\n      idf(iter.col()) += 1;\n      doc_length(i) += iter.value();\n    }\n  }\n  Real avgdl = doc_length.sum() / N;\n  idf.array() =\n      (N / (idf.array() + static_cast<Real>(1)) + static_cast<Real>(1)).log();\n  for (int i = 0; i < N; i++) {\n    Real regularizer = k1 * (1 - b + b * doc_length(i) / avgdl);\n    for (itertype iter(result, i); iter; ++iter) {\n      iter.valueRef() = idf(iter.col()) * (iter.valueRef() * (k1 + 1)) /\n                        (iter.valueRef() + regularizer);\n    }\n  }\n  return result;\n}\n\ntemplate <typename Real>\nCSRMatrix<Real> tf_idf_weight(const CSRMatrix<Real> &X, bool smooth) {\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  DenseVector<Real> idf(X.cols());\n  idf.array() = 0;\n\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(X, i); iter; ++iter) {\n      idf(iter.col()) += 1;\n    }\n  }\n  idf.array() = (N / (idf.array() + static_cast<Real>(smooth))).log();\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(result, i); iter; ++iter) {\n      iter.valueRef() *= idf(iter.col());\n    }\n  }\n  return result;\n}\n\ntemplate <typename Real>\nCSRMatrix<Real> remove_diagonal(const CSRMatrix<Real> &X) {\n  check_arg(X.rows() == X.cols(), \"X must be square\");\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(result, i); iter; ++iter) {\n      if (i == iter.col()) {\n        iter.valueRef() = static_cast<Real>(0);\n      }\n    }\n  }\n  return result;\n}\n\n} // namespace sparse_util\n} // namespace irspack\n", "meta": {"hexsha": "3995ea6557d0fe5a810af453e939400194e86edb", "size": 5683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp_source/util.hpp", "max_stars_repo_name": "wararaki/irspack", "max_stars_repo_head_hexsha": "650cc012924d46b3ecb87f1a6f806aee735a9559", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-11T18:34:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T18:34:30.000Z", "max_issues_repo_path": "cpp_source/util.hpp", "max_issues_repo_name": "kiminh/irspack", "max_issues_repo_head_hexsha": "45e448bb741b5f08b1b93d47ca293b981dd5f8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp_source/util.hpp", "max_forks_repo_name": "kiminh/irspack", "max_forks_repo_head_hexsha": "45e448bb741b5f08b1b93d47ca293b981dd5f8af", "max_forks_repo_licenses": ["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.4742857143, "max_line_length": 80, "alphanum_fraction": 0.6144641914, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.5700549172607684}}
{"text": "#pragma once\n#ifndef DOWNHILL_SIMPLEX_HPP_HPP\n#define DOWNHILL_SIMPLEX_HPP_HPP\n\n#include <cmath>\n#include <chrono>\n#include <vector>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n#include <boost/config.hpp>\n\ntemplate<typename _ObjectiveFunction, typename _ContainerType,\n         typename _DurationValueType = std::chrono::hours::rep,\n         typename _DurationRatio = std::chrono::hours::period>\n_ContainerType downhill_simplex(const _ObjectiveFunction& eval, std::vector<_ContainerType> guess,\n                         const typename _ContainerType::value_type tolerance = 0.0,\n                         const size_t maxIteration = std::numeric_limits<size_t>::max(),\n                         const std::chrono::duration<_DurationValueType, _DurationRatio>\n                                maxDuration = std::chrono::hours(24 * 365))\n{\n    using namespace std::chrono;\n    using vt = typename _ContainerType::value_type;\n    if (guess.empty())\n        return {};\n\n    const system_clock::time_point start = system_clock::now();\n    const size_t numDimensions = guess.front().size();\n    if (guess.size() < numDimensions + 1){\n        // initialize simplex points\n        _ContainerType avg(numDimensions, 0.0);\n        for (const auto& e : guess)\n            std::transform(e.cbegin(), e.cend(), avg.cbegin(), avg.begin(), std::plus<vt>());\n\n        std::transform(avg.cbegin(), avg.cend(), avg.begin(), [&guess](const vt& v) -> vt{ return v / guess.size(); });\n\n        guess.reserve(numDimensions - guess.size() + 1);\n        for (size_t i = 0; guess.size() < numDimensions + 1; ++i){\n            // add adjusted value to guess\n            // adjustment: 1 parameter will get +10%\n            guess.push_back(avg);\n            auto iter = guess.back().begin();\n            std::advance(iter, i);\n            (*iter) *= 1.10;\n        }\n    }\n    // Paramter\n    constexpr const double para_reflect = 1.0, para_expand = 1.0, para_contract = 0.5;\n\n    std::vector<vt> y_currentSimplex;\n    y_currentSimplex.reserve(guess.size());\n    for (const auto& e : guess)\n        y_currentSimplex.push_back(eval(e));\n\n    _ContainerType x_centroid(numDimensions);\n    _ContainerType x_expanded(numDimensions);\n    _ContainerType x_reflected(numDimensions);\n    _ContainerType x_contracted(numDimensions);\n    size_t idx_min = std::numeric_limits<size_t>::max();\n    size_t idx_max = std::numeric_limits<size_t>::max();\n\n    size_t varianceCounter = 0;\n    auto optimizationFinish = [&guess, &varianceCounter, &y_currentSimplex, &tolerance, &maxDuration, &start]() -> bool{\n        // time constraint\n        if (BOOST_UNLIKELY(system_clock::now() - start > maxDuration))\n            return true;\n\n        // tolerance constraint, based on y- or x-value varinace\n#ifndef DOWNHILL_SIMPLEX_Y_VLAUE_VARIATION\n        double coefVariance = 0.0;\n        for (const auto& data : guess){\n#else\n            const auto& data = y_currentSimplex;\n#endif\n            double mean = 0.0;\n            for (const auto& e : data)\n                mean += e;\n            mean /= double(data.size());\n\n            double variance = 0.0;\n            for (const auto& e : data){\n                const double tmp = e - mean;\n                variance += tmp * tmp;\n            }\n#ifndef DOWNHILL_SIMPLEX_Y_VLAUE_VARIATION\n            coefVariance += std::sqrt(variance) / std::abs(mean);\n        }\n        coefVariance /= double(guess.size());\n#else\n        const double coefVariance = std::sqrt(variance) / mean;\n#endif\n\n        if (BOOST_UNLIKELY(coefVariance <= tolerance)){\n            ++varianceCounter;\n            if (varianceCounter > 3)\n                return true;\n        }\n        else\n            varianceCounter = 0;\n\n        return false;\n    };\n\n    auto accept = [&idx_max, &guess, &y_currentSimplex](const _ContainerType& x_value, const vt& y_value){\n        y_currentSimplex[idx_max] = y_value;\n        guess[idx_max] = x_value;\n    };\n    size_t iterationCounter = 0;\n    for (; iterationCounter < maxIteration; ++iterationCounter){\n        size_t idx_2ndMax;\n        idx_min = 0;\n        idx_max = 0;\n\n        // find min, max and 2ndMax\n        for (size_t i = 1; i < y_currentSimplex.size(); ++i){\n            if (y_currentSimplex[idx_min] > y_currentSimplex[i])\n                idx_min = i;\n            else if (y_currentSimplex[idx_max] < y_currentSimplex[i])\n                idx_max = i;\n        }\n\n        idx_2ndMax = idx_min;\n        for (size_t i = 1; i < y_currentSimplex.size(); ++i){\n            if (y_currentSimplex[idx_2ndMax] < y_currentSimplex[i] && y_currentSimplex[i] < y_currentSimplex[idx_max])\n                idx_2ndMax = i;\n        }\n\n        // calculate centroid\n        std::fill(x_centroid.begin(), x_centroid.end(), vt(0.0));\n        for (const auto& e : guess)\n            std::transform(e.cbegin(), e.cend(), x_centroid.cbegin(), x_centroid.begin(), std::plus<vt>());\n\n        std::transform(x_centroid.cbegin(), x_centroid.cend(), guess[idx_max].cbegin(), x_centroid.begin(), std::minus<vt>());\n        std::transform(x_centroid.cbegin(), x_centroid.cend(), x_centroid.begin(), [&numDimensions](const vt& v) -> vt{\n            return v / vt(numDimensions);\n        });\n\n        // reflection\n        std::transform(x_centroid.cbegin(), x_centroid.cend(), guess[idx_max].cbegin(), x_reflected.begin(),\n                       [](const vt& v_centroid, const vt& v_guess) -> vt{\n            return (1.0 + para_reflect) * v_centroid - para_reflect * v_guess;\n        });\n\n        /// TODO\n        /// change to c++17 if with initializer statements\n        const vt y_reflected = eval(x_reflected);\n        if (y_reflected < y_currentSimplex[idx_min]){ // expansion\n            std::transform(x_centroid.cbegin(), x_centroid.cend(), x_reflected.cbegin(), x_expanded.begin(),\n                           [](const vt& v_centroid, const vt& v_reflected) -> vt{\n                return (1.0 + para_expand) * v_reflected - para_expand * v_centroid;\n            });\n\n            /// TODO\n            /// change to c++17 if with initializer statements\n            const vt y_expanded = eval(x_expanded);\n            if (y_expanded < y_currentSimplex[idx_min])\n            //if (y_expanded < y_reflected) // IGD version uses this if\n                accept(x_expanded, y_expanded);\n            else\n                accept(x_reflected, y_reflected);\n        }\n        else if (y_reflected <= y_currentSimplex[idx_2ndMax])\n            accept(x_reflected, y_reflected);\n        else { // contraction\n            if (y_reflected < y_currentSimplex[idx_max])\n                accept(x_reflected, y_reflected);\n\n            std::transform(x_centroid.cbegin(), x_centroid.cend(), guess[idx_max].cbegin(), x_contracted.begin(),\n                           [](const vt& v_centroid, const vt& v_guess) -> vt{\n                return para_contract * v_guess + (1.0 - para_contract) * v_centroid;\n            });\n\n            /// TODO\n            /// change to c++17 if with initializer statements\n            const vt y_contracted = eval(x_contracted);\n            if (y_contracted < y_currentSimplex[idx_max])\n                accept(x_contracted, y_contracted);\n            else{\n                // shrink simplex\n                for (size_t i = 0; i < guess.size(); ++i){\n                    if (BOOST_UNLIKELY(i == idx_min))\n                        continue;\n\n                    std::transform(guess[i].cbegin(), guess[i].cend(), guess[idx_min].cbegin(), guess[i].begin(),\n                                   [](const vt& lhs, const vt& rhs) -> vt{ return (lhs + rhs) * 0.5; });\n\n                    y_currentSimplex[i] = eval(guess[i]);\n                }\n            }\n        }\n        if (optimizationFinish())\n            break;\n    }\n    idx_min = 0;\n    for (size_t i = 1; i < y_currentSimplex.size(); ++i){\n        if (y_currentSimplex[i] < y_currentSimplex[idx_min])\n            idx_min = i;\n    }\n    double requiredTime = double(duration_cast<microseconds>(system_clock::now() - start).count()) / 1000.0;\n    std::string timeExtension = \"ms\";\n\n#define TMP_TIME_RATIO(nextRatio, nextExtension)                               \\\n    if (requiredTime > nextRatio) {                                            \\\n        requiredTime /= nextRatio;                                             \\\n        timeExtension = nextExtension;\n\n    TMP_TIME_RATIO(1000.0, \"s\")\n        TMP_TIME_RATIO(60.0, \"min\")\n            TMP_TIME_RATIO(60.0, \"h\")\n                TMP_TIME_RATIO(24.0, \"days\")\n                    TMP_TIME_RATIO(7.0, \"weeks\")\n    }   }   }   }   }\n#undef TMP_TIME_RATIO\n\n    std::cout << \"\\nDownhillsimplex finished!\\nrequired iterations:  \" << iterationCounter\n              << \"\\nrequired   time    :  \" << double(int(requiredTime * 100) / 100.0) << ' '\n              << timeExtension << '\\n' << std::endl;\n    return guess.at(idx_min);\n}\n\n\n#endif // DOWNHILL_SIMPLEX_HPP_HPP\n\n", "meta": {"hexsha": "c3c9ca8afbe2f0d74ca827e02589b98c59611137", "size": 8896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "optimizer/DownhillSimplex.hpp", "max_stars_repo_name": "sWombacher/Utility", "max_stars_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_stars_repo_licenses": ["WTFPL", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-25T21:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-25T21:56:12.000Z", "max_issues_repo_path": "optimizer/DownhillSimplex.hpp", "max_issues_repo_name": "sWombacher/Utility", "max_issues_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_issues_repo_licenses": ["WTFPL", "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": "optimizer/DownhillSimplex.hpp", "max_forks_repo_name": "sWombacher/Utility", "max_forks_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_forks_repo_licenses": ["WTFPL", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7142857143, "max_line_length": 126, "alphanum_fraction": 0.570256295, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5700549121514136}}
{"text": "/***********************************************************************/\n/**                                                                    */\n/** vector2d.hpp                                                       */\n/**                                                                    */\n/** Copyright (c) 2016, Service Robotics Lab.                          */\n/**                     http://robotics.upo.es                         */\n/**                                                                    */\n/** All rights reserved.                                               */\n/**                                                                    */\n/** Authors:                                                           */\n/** Ignacio Perez-Hurtado (maintainer)                                 */\n/** Jesus Capitan                                                      */\n/** Fernando Caballero                                                 */\n/** Luis Merino                                                        */\n/**                                                                    */\n/** This software may be modified and distributed under the terms      */\n/** of the BSD license. See the LICENSE file for details.              */\n/**                                                                    */\n/** http://www.opensource.org/licenses/BSD-3-Clause                    */\n/**                                                                    */\n/***********************************************************************/\n\n#ifndef _VECTOR2D_HPP_\n#define _VECTOR2D_HPP_\n\n#include <iostream>\n#include <cmath>\n//#include <geometry_msgs/Point.h>\n#include <boost/functional/hash.hpp>\n\n#include \"angle.hpp\"\n\nnamespace utils\n{\nclass Vector2d\n{\npublic:\n  Vector2d() : x(0), y(0)\n  {\n  }\n  Vector2d(double x, double y) : x(x), y(y)\n  {\n  }\n  virtual ~Vector2d()\n  {\n  }\n  double operator()(int index) const\n  {\n    return index == 0 ? x : y;\n  }\n  double operator[](int index) const\n  {\n    return index == 0 ? x : y;\n  }\n  bool operator==(const Vector2d& other) const\n  {\n    return x == other.x && y == other.y;\n  }\n  bool operator<(const Vector2d& other) const\n  {\n    return x < other.x || (x == other.x && y < other.y);\n  }\n  double getX() const\n  {\n    return x;\n  }\n  double getY() const\n  {\n    return y;\n  }\n\n  /*geometry_msgs::Point toPoint() const\n  {\n    geometry_msgs::Point p;\n    p.x = x;\n    p.y = y;\n    p.z = 0;\n    return p;\n  }*/\n\n  Vector2d& set(double x, double y)\n  {\n    Vector2d::x = x;\n    Vector2d::y = y;\n    return *this;\n  }\n  Vector2d& setX(double x)\n  {\n    Vector2d::x = x;\n    return *this;\n  }\n\n  Vector2d& setY(double y)\n  {\n    Vector2d::y = y;\n    return *this;\n  }\n\n  Vector2d& incX(double inc_x)\n  {\n    x += inc_x;\n    return *this;\n  }\n\n  Vector2d& incY(double inc_y)\n  {\n    y += inc_y;\n    return *this;\n  }\n\n  Vector2d& inc(double inc_x, double inc_y)\n  {\n    x += inc_x;\n    y += inc_y;\n    return *this;\n  }\n\n\n  const Angle angle() const\n  {\n    return Angle::fromRadian(std::atan2(y, x));\n  }\n\n  Angle angleTo(const Vector2d& other) const\n  {\n    return other.angle() - angle();\n  }\n\n  double squaredNorm() const\n  {\n    return x * x + y * y;\n  }\n\n  double norm() const\n  {\n    return std::sqrt(squaredNorm());\n  }\n\n  double dot(const Vector2d& other) const\n  {\n    return x * other.x + y * other.y;\n  }\n\n  Vector2d& normalize()\n  {\n    double n = norm();\n    if (n > 0)\n    {\n      x /= n;\n      y /= n;\n    }\n    return *this;\n  }\n\n  Vector2d normalized() const\n  {\n    Vector2d v(*this);\n    v.normalize();\n    return v;\n  }\n\n  Vector2d& operator*=(double scalar)\n  {\n    x *= scalar;\n    y *= scalar;\n    return *this;\n  }\n  Vector2d operator*(double scalar) const\n  {\n    return Vector2d(x * scalar, y * scalar);\n  }\n\n  Vector2d& operator/=(double scalar)\n  {\n    x /= scalar;\n    y /= scalar;\n    return *this;\n  }\n  Vector2d operator/(double scalar) const\n  {\n    return Vector2d(x / scalar, y / scalar);\n  }\n\n  Vector2d leftNormalVector() const\n  {\n    return Vector2d(-y, x);\n  }\n\n  Vector2d rightNormalVector() const\n  {\n    return Vector2d(y, -x);\n  }\n\n  Vector2d& operator+=(const Vector2d& other)\n  {\n    set(x + other.x, y + other.y);\n    return *this;\n  }\n  Vector2d operator+(const Vector2d& other) const\n  {\n    return Vector2d(x + other.x, y + other.y);\n  }\n  Vector2d& operator-=(const Vector2d& other)\n  {\n    set(x - other.x, y - other.y);\n    return *this;\n  }\n  Vector2d operator-(const Vector2d& other) const\n  {\n    return Vector2d(x - other.x, y - other.y);\n  }\n  Vector2d operator-() const\n  {\n    return Vector2d(-x, -y);\n  }\n\n\n\n  static const Vector2d& Zero()\n  {\n    static Vector2d zero;\n    return zero;\n  }\n\n\nprivate:\n  double x;\n  double y;\n};\n}\n\ninline utils::Vector2d operator*(double scalar, const utils::Vector2d& v)\n{\n  utils::Vector2d w(v);\n  w *= scalar;\n  return w;\n}\n\nnamespace std\n{\ninline ostream& operator<<(ostream& stream, const utils::Vector2d& v)\n{\n  stream << \"(\" << v.getX() << \",\" << v.getY() << \")\";\n  return stream;\n}\n\ntemplate <>\nstruct hash<utils::Vector2d>\n{\n  size_t operator()(const utils::Vector2d& v) const\n  {\n    using boost::hash_value;\n    using boost::hash_combine;\n    std::size_t seed = 0;\n    hash_combine(seed, hash_value(v[0]));\n    hash_combine(seed, hash_value(v[1]));\n    return seed;\n  }\n};\n}\n\n#endif\n", "meta": {"hexsha": "884d9d4a75a70ed933f953ede0cce26f75e9cf59", "size": 5348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vector2d.hpp", "max_stars_repo_name": "robotics-upo/lightsfm", "max_stars_repo_head_hexsha": "81d8696c9afe9f41afc3fd53f91d9144758b9513", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T09:53:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T10:45:08.000Z", "max_issues_repo_path": "include/vector2d.hpp", "max_issues_repo_name": "robotics-upo/lightsfm", "max_issues_repo_head_hexsha": "81d8696c9afe9f41afc3fd53f91d9144758b9513", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-12T03:05:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T21:36:30.000Z", "max_forks_repo_path": "include/vector2d.hpp", "max_forks_repo_name": "robotics-upo/lightsfm", "max_forks_repo_head_hexsha": "81d8696c9afe9f41afc3fd53f91d9144758b9513", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-15T10:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T10:17:55.000Z", "avg_line_length": 20.3346007605, "max_line_length": 73, "alphanum_fraction": 0.4614809274, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.5699214867043224}}
{"text": "// remainder_tree_array.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include <iostream>\n#include <chrono>\n#include <cmath>\n#include <cassert>\n#include <random>\n#include <vector>\n#include <NTL/ZZ.h>\n#include <NTL/vector.h>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace NTL;\n/*\n * To compile and run in Linux:\n * g++ -o remainder_tree_array remainder_tree_array.cpp -lntl -lgmp -pthread\n * ./remainder_tree_array\n *\n */\n\n/* \n * Returns C[], an array of residues A0 mod m0, A0A1 mod m0m1, etc.\n * A: array of A0, A1, ...\n * m: array of m0, m1, ...\n */\nvoid remainder_tree(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m);\nvoid print_tree(Vec<ZZ> &tree);\nvoid complexity_graph(int N, int d);\n\nint main()\n{\n\t\n\t//complexity_graph(1<<20, 1);\n\n\n\t\n\tint bound = 1<<20;\n\n\t// Testing Wilson's Theorem\n\tVec<ZZ> A;\n\tA.SetLength(bound);\n\tVec<ZZ> m;\n\tm.SetLength(bound);\n\n\tfor(int i = 0; i < bound; i++){\n\t\tA[i] = i+1;\n\t\tm[i] = ProbPrime(ZZ(i+1)) ? i+1 : 1;\n\t}\n\n\t/*for(int i = 0; i < A.length(); i++){\n\t\tcout << A[i] << \" \";\n\t}\n\tcout << endl;\n\n\tfor(int i = 0; i < m.length(); i++){\n\t\tcout << m[i] << \" \";\n\t}\n\tcout << endl;\n\t*/\n\tVec<ZZ> C;\n\tC.SetLength(bound);\n\n\tremainder_tree(C, A, m);\n\t\n\n\t/*for(int i = 0; i < C.length(); i++){\n\t\tcout << C[i] << \" \";\n\t}\n\tcout << endl;\n\t*/\n\t\n\n}\n\n/*\n * Original Remainder Tree method \n * No space optimizations\n */\n\nvoid remainder_tree(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m) {\n\t// Assert that lengths of A, m, C match\n\tassert(A.length() == m.length());\n\tassert(A.length() == C.length());\n\n\t// Set N = length of input arrays\n\tint N = A.length();\n\n\t// Don't do anything if arrays are trivial\n\tif(N == 0){\n\t\treturn;\n\t}\n\n\t// Index of leaf at the bottom left\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\n\t// Declare trees (always of length 2N for any N)\n\tVec<ZZ> ATree;\n\tATree.SetLength(2 * N);\n\tVec<ZZ> mTree;\n\tmTree.SetLength(2 * N);\n\tVec<ZZ> CTree;\n\tCTree.SetLength(2 * N);\n\n\t/* \n\t * For example when N=11 the leaves are in this order:\n\t *     / \\       /\\   /\\    /\\\n\t *    /   \\     /  7 8  9 10  11\n\t *   /\\   /\\   /\\  \n\t *  1  2 3  4 5  6\n\t *\n\t */\n\n\t// Initialize the leaves in ATree and mTree\n\tfor (int i = leftmost; i < 2 * N; i++) { // leaves on lowest layer\n\t\tATree[i] = A[i - leftmost];\n\t\tmTree[i] = m[i - leftmost];\n\t}\n\tfor (int i = N; i < leftmost; i++) { // leaves on second lowest layer\n\t\tATree[i] = A[i + N - leftmost];\n\t\tmTree[i] = m[i + N - leftmost];\n\t}\n\n\t// Calculate the rest of the product tree mTree\n\tfor (int i = N - 1; i > 0; i--) {\n\t\tmTree[i] = mTree[2 * i] * mTree[2 * i + 1]; // parent is product of leaves\n\t}\n\n\t// Calculate the rest of the product tree aTree, taking mod mTree[1] = m[0]*...*m[N-1]\n\tfor(int i = N - 1; i > 0; i--) {\n\t\tif ((i & (i+1)) != 0) { // Don't do calculation if on a node in right-most branch\n\t\t\tATree[i] = (ATree[2 * i] * ATree[2 * i + 1]) % mTree[1]; // parent is product of leaves mod mTree[1]\n\t\t}\n\t}\n\n\t// Calculate accumulating remainder tree\n\tCTree[1] = 1;\n\tfor (int i = 1; i < N; i++) {\n\t\tCTree[2 * i] = CTree[i] % mTree[2 * i]; // Left branch\n\t\tCTree[2 * i + 1] = (CTree[i] * ATree[2 * i]) % mTree[2 * i + 1]; // Right branch\n\t}\n\n\t//print_tree(ATree);\n\t//print_tree(mTree);\n\t//print_tree(CTree);\n\n\tfor (int i = leftmost; i < 2 * N; i++) {\n\t\tC[i - leftmost] = CTree[i];\n\t}\n\tfor (int i = N; i < leftmost; i++) {\n\t\tC[i + N - leftmost] = CTree[i];\n\t}\n\n\treturn;\n}\n\n/*\n * Prints a tree given in Vec<ZZ> form\n */\nvoid print_tree(Vec<ZZ> &tree){\n\tint top = 1;\n\tint counter = 0;\n\tfor(int i = 1; i < tree.length(); i++){\n\t\tcout << tree[i] << \" \";\n\t\tcounter++;\n\t\tif (counter == top){\n\t\t\tcout << endl;\n\t\t\tcounter = 0;\n\t\t\ttop *= 2;\n\t\t}\n\t}\n\tcout << endl;\n}\n\n/*\n * Gives data points on size of input vs. computation time.\n * N = max size of data, d = number of data points\n */\n\nvoid complexity_graph(int N, int d){\n\tvector<int> x;\n\tvector<int> y;\n\n\tint interval = N/d;\n\tint B = 0;\n\twhile(B <= N){\n\n\t\tint testSize = B;\n\t\tint numSize = B;\n\t\t\n\t\tVec<ZZ> test_A;\n\t\ttest_A.SetLength(testSize);\n\t\tVec<ZZ> test_m;\n\t\ttest_m.SetLength(testSize);\n\t\tfor (int i = 0; i < testSize; i++) {\n\t\t\ttest_A[i] = rand() % numSize + 1;\n\t\t\ttest_m[i] = rand() % numSize + 1;\n\t\t}\n\t\t/*\n\t\tfor (int i = 0; i < testSize; i++) {\n\t\t\tcout << test_A[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\n\t\tfor (int i = 0; i < testSize; i++) {\n\t\t\tcout << test_m[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\t*/\n\n\t\tuint64_t start = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\tVec<ZZ> test_C;\n\t\ttest_C.SetLength(testSize);\n\t\tremainder_tree(test_C, test_A, test_m);\n\n\t\t/*for (int i = 0; i < testSize; i++) {\n\t\t\tcout << test_C[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t\t*/\n\n\t\tuint64_t end = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\n\t\tx.push_back(B);\n\t\ty.push_back(end-start);\n\n\t\tB += interval;\n\t}\n\n\tfor(int i = 0; i < x.size(); i++){\n\t\tcout << x[i] << \", \";\n\t}\t\t\n\tcout << endl;\n\n\tfor(int i = 0; i < y.size(); i++){\n\t\tcout << y[i] << \", \";\n\t}\t\t\n\tcout << endl;\n\n\n}\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": "10f30eaa32244bded70ec32172174862ee9f0ba7", "size": 5596, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/to_incorporate/remainder_tree_array.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/to_incorporate/remainder_tree_array.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/to_incorporate/remainder_tree_array.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": 21.9450980392, "max_line_length": 135, "alphanum_fraction": 0.5788062902, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.5698966373973514}}
{"text": "/*!\n * @file dirichlet_bc.hpp\n * @brief Contains implementation of Dirichlet boundary conditions.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_DIRICHLET_BC_HPP_\n#define INCLUDE_DIRICHLET_BC_HPP_\n\n// Deal.ii\n#include <deal.II/base/function.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class DirichletBC\n * @brief Class implements scalar Dirichlet conditions.\n */\ntemplate <int dim>\nclass DirichletBC : public Function<dim>\n{\npublic:\n\tDirichletBC() : Function<dim>() {}\n\n\tvirtual double value(const Point<dim> &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n};\n\n\ntemplate <int dim>\ndouble\nDirichletBC<dim>::value(const Point<dim>& p,\n\t\t\t\t\t\t\t   const unsigned int /*component*/) const\n{\n\tdouble return_value = (p(0)-0.5) * (p(0)-0.5) + (p(1)-0.5) * (p(1)-0.5);\n\n\treturn return_value;\n}\n\n\ntemplate <int dim>\nvoid\nDirichletBC<dim>::value_list(const std::vector<Point<dim>> &points,\n\t\t\t\t\t\t\t\tstd::vector<double>  &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\n\tfor ( unsigned int p=0; p<points.size(); ++p)\n\t{\n\t\tvalues[p] = (points[p](0)-0.5) * (points[p](0)-0.5) + (points[p](1)-0.5) * (points[p](1)-0.5);\n\t} // end ++p\n}\n\n} // end namespace Coefficients\n\n#endif /* INCLUDE_DIRICHLET_BC_HPP_ */\n", "meta": {"hexsha": "3b0ff707f52af8ec69c8c999259f4268fd437ece", "size": 1600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dirichlet_bc.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/dirichlet_bc.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dirichlet_bc.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 22.2222222222, "max_line_length": 96, "alphanum_fraction": 0.669375, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.5698709080598003}}
{"text": "#ifndef __KALMANFILTER_HPP__\n#define __KALMANFILTER_HPP__\n\n#include <Eigen/Dense>\n#include <utility>\n\n\nclass KalmanFilter {\n public:\n \tstruct KalmanState {\n \t\tEigen::VectorXd state;\n \t\tEigen::MatrixXd errorCovariance;\n \t};\n\n\n \tKalmanFilter(\n    const int pStateDimensionality,\n    const int pMeasurementDimensionality);\n\n  void setNaturalModel(const Eigen::MatrixXd& pNewModel);\n  void setControlModel(const Eigen::MatrixXd& pNewModel);\n  void setTransitionModel(const Eigen::MatrixXd& pNewModel);\n  void setStateNoiseCovariance(const Eigen::MatrixXd& pNewCovariance);\n  void setMeasurementNoiseCovariance(const Eigen::MatrixXd& pNewCovariance);\n\n\tKalmanState KalmanFilterIteration(\n\t\tconst KalmanState& pPreviousState,\n\t\tconst Eigen::MatrixXd& pMeasurementVector,\n\t\tconst Eigen::VectorXd& pControlVector);\n\n \tEigen::MatrixXd computeStatePrediction(\n \t\tconst Eigen::VectorXd& pPreviousState,\n \t\tconst Eigen::VectorXd& pControlVector);\n\n \tEigen::MatrixXd computeObservationPrediction(\n \t\tconst Eigen::VectorXd& pStatePrediction);\n\n \tEigen::MatrixXd computeErrorCovariancePrediction(\n \t\tconst Eigen::MatrixXd& pPreviousPredictionCovariance);\n\n \tEigen::MatrixXd computeKalmanGainFactor(\n \t\tconst Eigen::MatrixXd& pPredictionCovarianceEstimate);\n\n \tEigen::MatrixXd computeStateEstimate(\n \t\tconst Eigen::VectorXd& pStatePrediction,\n \t\tconst Eigen::MatrixXd& pKalmanGainFactor,\n \t\tconst Eigen::VectorXd& pMeasurementVector,\n \t\tconst Eigen::VectorXd& pObservationPrediction);\n\n \tEigen::MatrixXd computeErrorCovariance(\n \t\tconst Eigen::MatrixXd& pPredictionCovarianceEstimate,\n \t\tconst Eigen::MatrixXd& pKalmanGainFactor);\n\n private:\n  int mStateDimensionality;       // aka n\n  int mMeasurementDimensionality; // aka m\n  Eigen::MatrixXd mNaturalModel;  // aka A; n x n; describes how the system\n                                  // evolves naturally, i.e. without controls\n                                  // or noise\n  Eigen::MatrixXd mControlModel;  // aka B; n x n; describes how controls alter\n                                  // the system\n  Eigen::MatrixXd mTransitionModel; // aka H; m x n; describes how to map from\n                                    // a state to an observation\n  Eigen::VectorXd mStateNoise;    // aka \\epsilon; n x 1; has covariance Q\n  Eigen::MatrixXd mStateNoiseCovariance;  // aka Q;\n  Eigen::VectorXd mMeasurementNoise; // aka \\sigma; m x 1; has covariance R\n  Eigen::MatrixXd mMeasurementNoiseCovariance;  // aka R; m x m\n};\n\n\n#endif //__KALMANFILTER_HPP__", "meta": {"hexsha": "ee3435a3f898915d1a9cc4722d71b8e102453774", "size": 2485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter.hpp", "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": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter.hpp", "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": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter.hpp", "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": 35.0, "max_line_length": 79, "alphanum_fraction": 0.7259557344, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.5698544007575708}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2015-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_THOMAS_INVERSE_HPP\n#define BOOST_GEOMETRY_FORMULAS_THOMAS_INVERSE_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_inverse.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with second order terms.\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD0703541\n*/\ntemplate <\n    typename CT,\n    bool EnableDistance,\n    bool EnableAzimuth,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false\n>\nclass thomas_inverse\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcAzimuths = EnableAzimuth || EnableReverseAzimuth || CalcQuantities;\n    static const bool CalcFwdAzimuth = EnableAzimuth || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;\n\npublic:\n    typedef result_inverse<CT> result_type;\n\n    template <typename T1, typename T2, typename Spheroid>\n    static inline result_type apply(T1 const& lon1,\n                                    T1 const& lat1,\n                                    T2 const& lon2,\n                                    T2 const& lat2,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        // coordinates in radians\n\n        if ( math::equals(lon1, lon2) && math::equals(lat1, lat2) )\n        {\n            return result;\n        }\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n        CT const c4 = 4;\n\n        CT const pi_half = math::pi<CT>() / c2;\n        CT const f = formula::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n\n//        CT const tan_theta1 = one_minus_f * tan(lat1);\n//        CT const tan_theta2 = one_minus_f * tan(lat2);\n//        CT const theta1 = atan(tan_theta1);\n//        CT const theta2 = atan(tan_theta2);\n\n        CT const theta1 = math::equals(lat1, pi_half) ? lat1 :\n                          math::equals(lat1, -pi_half) ? lat1 :\n                          atan(one_minus_f * tan(lat1));\n        CT const theta2 = math::equals(lat2, pi_half) ? lat2 :\n                          math::equals(lat2, -pi_half) ? lat2 :\n                          atan(one_minus_f * tan(lat2));\n\n        CT const theta_m = (theta1 + theta2) / c2;\n        CT const d_theta_m = (theta2 - theta1) / c2;\n        CT const d_lambda = lon2 - lon1;\n        CT const d_lambda_m = d_lambda / c2;\n\n        CT const sin_theta_m = sin(theta_m);\n        CT const cos_theta_m = cos(theta_m);\n        CT const sin_d_theta_m = sin(d_theta_m);\n        CT const cos_d_theta_m = cos(d_theta_m);\n        CT const sin2_theta_m = math::sqr(sin_theta_m);\n        CT const cos2_theta_m = math::sqr(cos_theta_m);\n        CT const sin2_d_theta_m = math::sqr(sin_d_theta_m);\n        CT const cos2_d_theta_m = math::sqr(cos_d_theta_m);\n        CT const sin_d_lambda_m = sin(d_lambda_m);\n        CT const sin2_d_lambda_m = math::sqr(sin_d_lambda_m);\n\n        CT const H = cos2_theta_m - sin2_d_theta_m;\n        CT const L = sin2_d_theta_m + H * sin2_d_lambda_m;\n        CT const cos_d = c1 - c2 * L;\n        CT const d = acos(cos_d);\n        CT const sin_d = sin(d);\n\n        CT const one_minus_L = c1 - L;\n\n        if ( math::equals(sin_d, c0)\n          || math::equals(L, c0)\n          || math::equals(one_minus_L, c0) )\n        {\n            return result;\n        }\n\n        CT const U = c2 * sin2_theta_m * cos2_d_theta_m / one_minus_L;\n        CT const V = c2 * sin2_d_theta_m * cos2_theta_m / L;\n        CT const X = U + V;\n        CT const Y = U - V;\n        CT const T = d / sin_d;\n        CT const D = c4 * math::sqr(T);\n        CT const E = c2 * cos_d;\n        CT const A = D * E;\n        CT const B = c2 * D;\n        CT const C = T - (A - E) / c2;\n\n        CT const f_sqr = math::sqr(f);\n        CT const f_sqr_per_64 = f_sqr / CT(64);\n    \n        if ( BOOST_GEOMETRY_CONDITION(EnableDistance) )\n        {\n            CT const n1 = X * (A + C*X);\n            CT const n2 = Y * (B + E*Y);\n            CT const n3 = D*X*Y;\n\n            CT const delta1d = f * (T*X-Y) / c4;\n            CT const delta2d = f_sqr_per_64 * (n1 - n2 + n3);\n\n            CT const a = get_radius<0>(spheroid);\n\n            //result.distance = a * sin_d * (T - delta1d);\n            result.distance = a * sin_d * (T - delta1d + delta2d);\n        }\n    \n        if ( BOOST_GEOMETRY_CONDITION(CalcAzimuths) )\n        {\n            // NOTE: if both cos_latX == 0 then below we'd have 0 * INF\n            // it's a situation when the endpoints are on the poles +-90 deg\n            // in this case the azimuth could either be 0 or +-pi\n            // but above always 0 is returned\n\n            CT const F = c2*Y-E*(c4-X);\n            CT const M = CT(32)*T-(CT(20)*T-A)*X-(B+c4)*Y;\n            CT const G = f*T/c2 + f_sqr_per_64 * M;\n            \n            // TODO:\n            // If d_lambda is close to 90 or -90 deg then tan(d_lambda) is big\n            // and F is small. The result is not accurate.\n            // In the edge case the result may be 2 orders of magnitude less\n            // accurate than Andoyer's.\n            CT const tan_d_lambda = tan(d_lambda);\n            CT const Q = -(F*G*tan_d_lambda) / c4;\n            CT const d_lambda_m_p = (d_lambda + Q) / c2;\n            CT const tan_d_lambda_m_p = tan(d_lambda_m_p);\n\n            CT const v = atan2(cos_d_theta_m, sin_theta_m * tan_d_lambda_m_p);\n            CT const u = atan2(-sin_d_theta_m, cos_theta_m * tan_d_lambda_m_p);\n\n            CT const pi = math::pi<CT>();\n\n            if (BOOST_GEOMETRY_CONDITION(EnableAzimuth))\n            {\n                CT alpha1 = v + u;\n                if (alpha1 > pi)\n                {\n                    alpha1 -= c2 * pi;\n                }\n\n                result.azimuth = alpha1;\n            }\n\n            if (BOOST_GEOMETRY_CONDITION(EnableReverseAzimuth))\n            {\n                CT alpha2 = pi - (v - u);\n                if (alpha2 > pi)\n                {\n                    alpha2 -= c2 * pi;\n                }\n\n                result.reverse_azimuth = alpha2;\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\n        {\n            typedef differential_quantities<CT, EnableReducedLength, EnableGeodesicScale, 2> quantities;\n            quantities::apply(lon1, lat1, lon2, lat2,\n                              result.azimuth, result.reverse_azimuth,\n                              get_radius<2>(spheroid), f,\n                              result.reduced_length, result.geodesic_scale);\n        }\n\n        return result;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_THOMAS_INVERSE_HPP\n", "meta": {"hexsha": "6db3285e0c6df58f4f93fa584b03747f2c9f77c9", "size": 7695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/formulas/thomas_inverse.hpp", "max_stars_repo_name": "taken20090/ext-boost", "max_stars_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "max_stars_repo_licenses": ["BSL-1.0"], "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/geometry/formulas/thomas_inverse.hpp", "max_issues_repo_name": "taken20090/ext-boost", "max_issues_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "max_issues_repo_licenses": ["BSL-1.0"], "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/thomas_inverse.hpp", "max_forks_repo_name": "taken20090/ext-boost", "max_forks_repo_head_hexsha": "0518d698a8a0fd86a88e5e1d0f67f30e9bbc4181", "max_forks_repo_licenses": ["BSL-1.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.9772727273, "max_line_length": 105, "alphanum_fraction": 0.5749187784, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5698543988381221}}
{"text": "/**\n * @file stableevaluationatapoint.cc\n * @brief NPDE homework StableEvaluationAtAPoint\n * @author Amélie Loher, Erick Schulz & Philippe Peter\n * @date 29.11.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"stableevaluationatapoint.h\"\n\n#include <lf/base/base.h>\n#include <lf/fe/fe.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/quad/quad.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <memory>\n\nnamespace StableEvaluationAtAPoint {\n\ndouble MeshSize(const std::shared_ptr<const lf::mesh::Mesh> &mesh_p) {\n  double mesh_size = 0.0;\n  // Find maximal edge length\n  for (const lf::mesh::Entity *edge : mesh_p->Entities(1)) {\n    // Compute the length of the edge\n    double edge_length = lf::geometry::Volume(*(edge->Geometry()));\n    mesh_size = std::max(edge_length, mesh_size);\n  }\n  return mesh_size;\n}\n\nEigen::Vector2d OuterNormalUnitSquare(Eigen::Vector2d x) {\n  // Use shortcut: x is on the unit square\n  if (x(0) > x(1) && x(0) < 1.0 - x(1)) {\n    return Eigen::Vector2d(0.0, -1.0);\n  }\n  if (x(0) > x(1) && x(0) > 1.0 - x(1)) {\n    return Eigen::Vector2d(1.0, 0.0);\n  }\n  if (x(0) < x(1) && x(0) > 1.0 - x(1)) {\n    return Eigen::Vector2d(0.0, 1.0);\n  }\n  return Eigen::Vector2d(-1.0, 0.0);\n}\n\ndouble FundamentalSolution::operator()(Eigen::Vector2d y) {\n  LF_ASSERT_MSG(x_ != y, \"G not defined for these coordinates!\");\n  return -1.0 / (2.0 * M_PI) * std::log((x_ - y).norm());\n}\n\nEigen::Vector2d FundamentalSolution::grad(Eigen::Vector2d y) {\n  LF_ASSERT_MSG(x_ != y, \"G not defined for these coordinates!\");\n  return (x_ - y) / (2.0 * M_PI * (x_ - y).squaredNorm());\n}\n\ndouble PointEval(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  double error = 0.0;\n#if SOLUTION\n  const auto u = [](Eigen::Vector2d x) -> double {\n    Eigen::Vector2d one(1.0, 0.0);\n    return std::log((x + one).norm());\n  };\n  const auto gradu = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    Eigen::Vector2d one(1.0, 0.0);\n    return (x + one) / (x + one).squaredNorm();\n  };\n  // Define a Functor for the dot product of grad u(x) * n(x)\n  const auto gradu_dot_n = [gradu](const Eigen::Vector2d x) -> double {\n    // Determine the normal vector n on the unit square\n    Eigen::Vector2d n = OuterNormalUnitSquare(x);\n    return gradu(x).dot(n);\n  };\n\n  // Compute right hand side\n  const Eigen::Vector2d x(0.3, 0.4);\n  const double rhs = PSL(mesh_p, gradu_dot_n, x) - PDL(mesh_p, u, x);\n  // Compute the error\n  error = std::abs(u(x) - rhs);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return error;\n}\n\ndouble Psi::operator()(Eigen::Vector2d y) {\n  const double c = M_PI / (0.5 * std::sqrt(2) - 1.0);\n  const double dist = (y - center_).norm();\n\n  if (dist <= 0.25 * std::sqrt(2)) {\n    return 0.0;\n  } else if (dist >= 0.5) {\n    return 1.0;\n  } else {\n    return std::pow(std::cos(c * (dist - 0.5)), 2);\n  }\n}\n\nEigen::Vector2d Psi::grad(Eigen::Vector2d y) {\n  double c = M_PI / (0.5 * std::sqrt(2) - 1.0);\n  double dist = (y - center_).norm();\n\n  if (dist <= 0.25 * std::sqrt(2)) {\n    return Eigen::Vector2d(0.0, 0.0);\n\n  } else if (dist >= 0.5) {\n    return Eigen::Vector2d(0.0, 0.0);\n  } else {\n    return -2.0 * std::cos(c * (dist - 0.5)) * std::sin(c * (dist - 0.5)) *\n           (c / dist) * (y - center_);\n  }\n}\n\ndouble Psi::lapl(Eigen::Vector2d y) {\n  double c = M_PI / (0.5 * std::sqrt(2) - 1.0);\n  double c2 = c * c;\n  double dist = (y - center_).norm();\n\n  if (dist <= 0.25 * std::sqrt(2)) {\n    return 0.0;\n  } else if (dist >= 0.5) {\n    return 0.0;\n  } else {\n    double sineval = std::sin(c * (dist - 0.5));\n    double coseval = std::cos(c * (dist - 0.5));\n    return 2 * c2 * sineval * sineval - 2 * c2 * coseval * coseval -\n           2 * c * sineval * coseval / dist;\n  }\n}\n\ndouble Jstar(std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space,\n             Eigen::VectorXd uFE, const Eigen::Vector2d x) {\n  double val = 0.0;\n  Psi psi(Eigen::Vector2d(0.5, 0.5));\n  FundamentalSolution G(x);\n#if SOLUTION\n\n  // Mesh covering a unit square domain\n  std::shared_ptr<const lf::mesh::Mesh> mesh = fe_space->Mesh();\n  // Use midpoint quadrature rule\n  const lf::quad::QuadRule qr = lf::quad::make_TriaQR_MidpointRule();\n  // Quadrature points\n  const Eigen::MatrixXd zeta_ref{qr.Points()};\n  // Quadrature weights\n  const Eigen::VectorXd w_ref{qr.Weights()};\n  // Number of quadrature points\n  const lf::base::size_type P = qr.NumPoints();\n  // Create mesh function to be evaluated at the quadrature points\n  auto uFE_mf = lf::fe::MeshFunctionFE(fe_space, uFE);\n\n  // Loop over all cells\n  for (const lf::mesh::Entity *entity : mesh->Entities(0)) {\n    // Standard way to apply a local quadrature rule\n    const lf::geometry::Geometry &geo{*entity->Geometry()};\n    // Quadrature points on actual cell\n    const Eigen::MatrixXd zeta{geo.Global(zeta_ref)};\n    const Eigen::VectorXd gram_dets{geo.IntegrationElement(zeta_ref)};\n    // Values of finite element function on all quadrature points\n    auto u_vals = uFE_mf(*entity, zeta_ref);\n\n    // Quadrature loop\n    for (int l = 0; l < P; l++) {\n      const double w = w_ref[l] * gram_dets[l];\n      val += w * (-u_vals[l]) *\n             (2.0 * (G.grad(zeta.col(l))).dot(psi.grad(zeta.col(l))) +\n              G(zeta.col(l)) * psi.lapl(zeta.col(l)));\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return val;\n}\n\ndouble StablePointEvaluation(\n    std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space,\n    Eigen::VectorXd uFE, const Eigen::Vector2d x) {\n  double res = 0.0;\n\n  Eigen::Vector2d center(0.5, 0.5);\n  if ((x - center).norm() <= 0.25) {\n    res = Jstar(fe_space, uFE, x);\n  } else {\n    std::cerr << \"The point does not fulfill the assumptions\" << std::endl;\n  }\n\n  return res;\n}\n\ndouble EvaluateFEFunction(\n    std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space,\n    const Eigen::VectorXd &uFE, Eigen::Vector2d global, double tol) {\n  // Extract mesh\n  auto mesh_p = fe_space->Mesh();\n  // wrap coefficient vector into a FE mesh-function\n  lf::fe::MeshFunctionFE mf(fe_space, uFE);\n\n  for (const lf::mesh::Entity *entity_p : mesh_p->Entities(0)) {\n    LF_ASSERT_MSG(lf::base::RefEl::kTria() == entity_p->RefEl(),\n                  \"Function only defined for triangular cells\");\n\n    // compute geometric information about the cell\n    const lf::geometry::Geometry *geo_p = entity_p->Geometry();\n    Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n\n    // transform global coordinates to local coordinates on the cell\n    Eigen::Matrix2d A;\n    A << corners.col(1) - corners.col(0), corners.col(2) - corners.col(0);\n    Eigen::Vector2d b;\n    b << global - corners.col(0);\n    Eigen::Vector2d loc = A.fullPivLu().solve(b);\n\n    // evaluate meshfunction, if local coordinates lie in the reference triangle\n    if (loc(0) >= 0 - tol && loc(1) >= 0 - tol && loc(0) + loc(1) <= 1 + tol) {\n      return mf(*entity_p, loc)[0];\n    }\n  }\n  return 0.0;\n}\n\n}  // namespace StableEvaluationAtAPoint", "meta": {"hexsha": "b85ac0f3bd4fe1fba4ec0826dafd56141d9a7b5e", "size": 7107, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint.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": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint.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": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint.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": 31.0349344978, "max_line_length": 80, "alphanum_fraction": 0.6174194456, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5697590814574902}}
{"text": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <time.h>\n#include \"func.hpp\"\nusing namespace std;\n\nconst int max_iter = 200;\nconst double err_norm = 1e-14;\n\narma::vec Iterator(long long unsigned int n, arma::vec iter_values, double alpha);\narma::mat derivative_matrix(long long unsigned int n, double x2, double p1, double alpha);\narma::vec method_newton(long long unsigned int n, arma::mat D, double x2, double p1, double alpha);\narma::vec runge_kutta_5(long long unsigned int n, double x1, double x2, double p1, double p2, double alpha);\narma::vec ini_k(arma::vec Y, double alpha, double t, double h);\narma::mat inverse_matrix(arma::mat D);\ndouble fedorenko_norm(arma::mat D, arma::vec iter_values, long long unsigned int n, double alpha);\n\narma::vec Iterator(long long unsigned int n, arma::vec iter_values, double alpha) {\n    arma::mat d_matrix(static_cast<arma::uword>(2), static_cast<arma::uword>(2), arma::fill::zeros);\n    double norm;\n\n    for (int iter = 0; iter < max_iter; iter++){\n        d_matrix = derivative_matrix(n, iter_values(0), iter_values(1), alpha);\n        norm = fedorenko_norm(d_matrix, iter_values, n, alpha);\n        if (norm < err_norm) {\n            cout << setprecision(2) << defaultfloat << \"step = \" << iter << endl;\n\t\t\tcout << setprecision(2) << defaultfloat << \"alpha = \" << alpha << endl;\n\t\t\tcout << \"------\" << endl;\n            cout << setprecision(13) << fixed << \"x2(0) = \" << iter_values(0) << endl;\n\t\t\tcout << setprecision(13) << fixed << \"p1(0) = \" << iter_values(1) << endl;\n            cout << scientific << \"norm = \" << norm << endl << endl;\n            return iter_values;\n        }\n        d_matrix = inverse_matrix(d_matrix);\n        iter_values = method_newton(n, d_matrix, iter_values(0), iter_values(1), alpha);\n    }\n\n    return iter_values;\n}\n\narma::mat derivative_matrix(long long unsigned int n, double x2, double p1, double alpha) {\n    arma::vec value(n + 1, arma::fill::zeros);\n    arma::mat d_matrix(static_cast<arma::uword>(2), static_cast<arma::uword>(2), arma::fill::zeros);\n    double h = 1e-10;\n\n    value = runge_kutta_5(n, 1.0, x2 + h, p1, 0.0, alpha);\n    d_matrix(0, 0) += value(n - 1);\n    d_matrix(1, 0) += value(n);\n    value = runge_kutta_5(n, 1.0, x2 - h, p1, 0.0, alpha);\n    d_matrix(0, 0) -= value(n - 1);\n\td_matrix(1, 0) -= value(n);\n    value = runge_kutta_5(n, 1.0, x2, p1 + h, 0.0, alpha);\n    d_matrix(0, 1) += value(n - 1);\n    d_matrix(1, 1) += value(n);\n\tvalue = runge_kutta_5(n, 1.0, x2, p1 - h, 0.0, alpha);\n    d_matrix(0, 1) -= value(n - 1);\n    d_matrix(1, 1) -= value(n);\n\n    d_matrix = d_matrix/(2.0 * h);\n    return d_matrix;\n}\n\ndouble fedorenko_norm(arma::mat d_matrix, arma::vec iter_values, long long unsigned int n, double alpha) {\n    arma::vec value(n + 1, arma::fill::zeros);\n\n    value = runge_kutta_5(n, 1.0, iter_values(0), iter_values(1), 0.0, alpha);\n\n    return sqrt((value(n - 1)*value(n - 1)/(d_matrix(0,0)*d_matrix(0,0) + d_matrix(0,1)*d_matrix(0,1))) + (value(n)*value(n)/(d_matrix(1,0)*d_matrix(1,0) + d_matrix(1,1)*d_matrix(1,1))));\n}\n\narma::mat inverse_matrix(arma::mat d_matrix) {\n    double temp = 0.0;\n    arma::mat value_matrix(static_cast<arma::uword>(2), static_cast<arma::uword>(2), arma::fill::zeros);\n\n    temp = 1/((d_matrix(0,0)*d_matrix(1,1)) - (d_matrix(0,1)*d_matrix(1,0)));\n    value_matrix(0, 0) = temp*d_matrix(1, 1);\n    value_matrix(0, 1) = - temp*d_matrix(0, 1);\n    value_matrix(1, 0) = - temp*d_matrix(1, 0);\n    value_matrix(1, 1) = temp*d_matrix(0, 0);\n    return value_matrix;\n}\n\narma::vec method_newton(long long unsigned int n, arma::mat D, double x2, double p1, double alpha) {\n    arma::vec value(n + 1, arma::fill::zeros);\n    arma::vec iter_values(2, arma::fill::zeros);\n\n    value = runge_kutta_5(n, 1.0, x2, p1, 0.0, alpha);\n    iter_values(0) = x2 - D(0, 0) * value(n-1) - D(0, 1) * value(n);\n    iter_values(1) = p1 - D(1, 0) * value(n-1) - D(1, 1) * value(n);\n\n    return iter_values;\n}\n\narma::vec runge_kutta_5(long long unsigned int n, double x1, double x2, double p1, double p2, double alpha) {\n    arma::vec ODE(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec ODE1(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec ODE2(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec value(n + 1, arma::fill::zeros);\n    double h = 1.0/static_cast<double>(n);\n    double t = 0.0;\n    double err = 1e-15;\n    bool working = true;\n\n    ODE(0) = x1;\n    ODE(1) = x2;\n    ODE(2) = p1;\n    ODE(3) = p2;\n\n    while (working) {\n        if (t + h >= 1.0) {\n            h = 1.0 - t;\n            working = false;\n        }\n\t\tODE1 = ini_k(ODE, alpha, t, h/2.0);\n        ODE2 = ODE1 + ini_k(ODE + ODE1, alpha, t, h/2.0);\n        ODE1 = ini_k(ODE, alpha, t, h);\n\n        if (arma::max(arma::abs(ODE1 - ODE2)) > err) {\n            h = h/2.0;\n        } else\n        if (arma::max(arma::abs(ODE1 - ODE2)) < err/16) {\n            t += h;\n            h = h*1.5;\n            ODE += ODE2;\n        } else {\n            t += h;\n            ODE += ODE2;\n        }\n    }\n\n    value(n-1) = ODE(0);\n    value(n) = ODE(1);\n\n    return value;\n}\n\narma::vec ini_k(arma::vec Y, double alpha, double t, double h) {\n    arma::vec k1(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec k2(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec k3(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec k4(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec k5(static_cast<arma::uword>(4), arma::fill::zeros);\n    arma::vec k6(static_cast<arma::uword>(4), arma::fill::zeros);\n\n    k1 = h * init_func(Y, alpha, t);\n    k2 = h * init_func(Y + (k1/2.0), alpha, t);\n    k3 = h * init_func(Y + ((k1 + k2)/4.0), alpha, t);\n    k4 = h * init_func(Y - k2 + 2.0 * k3, alpha, t);\n    k5 = h * init_func(Y + ((7.0 * k1 + 10.0 * k2 + k4)/27.0), alpha, t);\n    k6 = h * init_func(Y + ((28.0 * k1 - 125.0 * k2 + 546.0 * k3 + 54.0 * k4 - 378 * k5)/625.0), alpha, t);\n    return k1/24.0 + (5.0 * k4)/48.0 + (27.0 * k5)/56.0 + (125.0 * k6)/336.0;\n}\n", "meta": {"hexsha": "f50d88599887d60a466d3d3a47e52e42ca9f9fcf", "size": 6173, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "7th-half/2nd-task/progs/c/iterator.hpp", "max_stars_repo_name": "pmpavl/workshop", "max_stars_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7th-half/2nd-task/progs/c/iterator.hpp", "max_issues_repo_name": "pmpavl/workshop", "max_issues_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7th-half/2nd-task/progs/c/iterator.hpp", "max_forks_repo_name": "pmpavl/workshop", "max_forks_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_forks_repo_licenses": ["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.3416149068, "max_line_length": 187, "alphanum_fraction": 0.5920946055, "num_tokens": 2172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505273888291, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5697259432967245}}
{"text": "#pragma once\n\n#if USE_STAN\n#include <stan/math.hpp>\n#include <stan/math/fwd.hpp>\n#endif\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"spatial_vector.hpp\"\n\nnamespace tds {\n\ntemplate <typename ScalarT = double>\nstruct EigenAlgebraT {\n  using Index = Eigen::Index;\n  using Scalar = ScalarT;\n  using EigenAlgebra = EigenAlgebraT<Scalar>;\n  using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n  using VectorX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n  using Matrix3 = Eigen::Matrix<Scalar, 3, 3>;\n  using Matrix6 = Eigen::Matrix<Scalar, 6, 6>;\n  using Matrix3X = Eigen::Matrix<Scalar, 3, Eigen::Dynamic>;\n  using MatrixX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n  using Quaternion = Eigen::Quaternion<Scalar>;\n  using SpatialVector = tds::SpatialVector<EigenAlgebra>;\n  using MotionVector = tds::MotionVector<EigenAlgebra>;\n  using ForceVector = tds::ForceVector<EigenAlgebra>;\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto transpose(const T &matrix) {\n    return matrix.transpose();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto inverse(const T &matrix) {\n    return matrix.inverse();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto inverse_transpose(const T &matrix) {\n    return matrix.inverse().transpose();\n  }\n\n  template <typename T1, typename T2>\n  EIGEN_ALWAYS_INLINE static auto cross(const T1 &vector_a,\n                                        const T2 &vector_b) {\n    return vector_a.cross(vector_b);\n  }\n\n  /**\n   * V1 = mv(w1, v1)\n   * V2 = mv(w2, v2)\n   * V1 x V2 = mv(w1 x w2, w1 x v2 + v1 x w2)\n   */\n  static inline MotionVector cross(const MotionVector &a,\n                                   const MotionVector &b) {\n    return MotionVector(a.top.cross(b.top),\n                        a.top.cross(b.bottom) + a.bottom.cross(b.top));\n  }\n\n  /**\n   * V = mv(w, v)\n   * F = fv(n, f)\n   * V x* F = fv(w x n + v x f, w x f)\n   */\n  static inline ForceVector cross(const MotionVector &a, const ForceVector &b) {\n    return ForceVector(a.top.cross(b.top) + a.bottom.cross(b.bottom),\n                       a.top.cross(b.bottom));\n  }\n\n  EIGEN_ALWAYS_INLINE static Index size(const VectorX &v) { return v.size(); }\n\n  EIGEN_ALWAYS_INLINE static Matrix3X create_matrix_3x(int num_cols) {\n    return Matrix3X(3, num_cols);\n  }\n  EIGEN_ALWAYS_INLINE static MatrixX create_matrix_x(int num_rows,\n                                                     int num_cols) {\n    return MatrixX(num_rows, num_cols);\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static int num_rows(const T &matrix) {\n    return matrix.rows();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static int num_cols(const T &matrix) {\n    return matrix.cols();\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar determinant(const Matrix3 &m) {\n    return m.determinant();\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar determinant(const MatrixX &m) {\n    return m.determinant();\n  }\n\n  /**\n   * Returns true if the matrix `mat` is positive-definite, and assigns\n   * `mat_inv` to the inverse of mat.\n   * `mat` must be a symmetric matrix.\n   */\n  static bool symmetric_inverse(const MatrixX &mat, MatrixX &mat_inv) {\n    Eigen::LLT<MatrixX> llt(mat);\n    if (llt.info() == Eigen::NumericalIssue) {\n      return false;\n    }\n    mat_inv = mat.inverse();\n    return true;\n  }\n\n  /**\n   * V = mv(w, v)\n   * F = mv(n, f)\n   * V.F = w.n + v.f\n   */\n  EIGEN_ALWAYS_INLINE static Scalar dot(const MotionVector &a,\n                                        const ForceVector &b) {\n    return a.top.dot(b.top) + a.bottom.dot(b.bottom);\n  }\n  EIGEN_ALWAYS_INLINE static Scalar dot(const ForceVector &a,\n                                        const MotionVector &b) {\n    return dot(b, a);\n  }\n\n  template <typename T1, typename T2>\n  EIGEN_ALWAYS_INLINE static auto dot(const T1 &vector_a, const T2 &vector_b) {\n    return vector_a.dot(vector_b);\n  }\n\n  TINY_INLINE static Scalar norm(const MotionVector &v) {\n    using std::sqrt;\n    return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] +\n                v[4] * v[4] + v[5] * v[5]);\n  }\n  TINY_INLINE static Scalar norm(const ForceVector &v) {\n    using std::sqrt;\n    return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3] +\n                v[4] * v[4] + v[5] * v[5]);\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static Scalar norm(const T &v) {\n    return v.norm();\n  }\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static Scalar sqnorm(const T &v) {\n    return v.squaredNorm();\n  }\n\n  template <typename T>\n  EIGEN_ALWAYS_INLINE static auto normalize(T &v) {\n    v.normalize();\n    return v;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 cross_matrix(const Vector3 &v) {\n    Matrix3 tmp;\n    tmp << 0., -v[2], v[1], v[2], 0., -v[0], -v[1], v[0], 0.;\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 zero33() { return Matrix3::Zero(); }\n\n  EIGEN_ALWAYS_INLINE static VectorX zerox(Index size) {\n    return VectorX::Zero(size);\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Vector3 &v) {\n    Matrix3 tmp;\n    tmp << v[0], 0, 0, 0, v[1], 0, 0, 0, v[2];\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 diagonal3(const Scalar &v) {\n    Matrix3 tmp;\n    tmp << v, 0, 0, 0, v, 0, 0, 0, v;\n    return tmp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 eye3() { return Matrix3::Identity(); }\n  EIGEN_ALWAYS_INLINE static void set_identity(Quaternion &quat) {\n    quat = Quaternion(1., 0., 0., 0.);\n  }\n\n  EIGEN_ALWAYS_INLINE static Scalar zero() { return 0; }\n  EIGEN_ALWAYS_INLINE static Scalar one() { return 1; }\n  EIGEN_ALWAYS_INLINE static Scalar two() { return 2; }\n  EIGEN_ALWAYS_INLINE static Scalar half() { return 0.5; }\n  EIGEN_ALWAYS_INLINE static Scalar pi() { return M_PI; }\n  EIGEN_ALWAYS_INLINE static Scalar fraction(int a, int b) {\n    return ((double)a) / b;\n  }\n\n  static Scalar scalar_from_string(const std::string &s) {\n    return std::stod(s);\n  }\n\n  EIGEN_ALWAYS_INLINE static Vector3 zero3() { return Vector3::Zero(); }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_x() { return Vector3(1, 0, 0); }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_y() { return Vector3(0, 1, 0); }\n  EIGEN_ALWAYS_INLINE static Vector3 unit3_z() { return Vector3(0, 0, 1); }\n\n  EIGEN_ALWAYS_INLINE static VectorX segment(const VectorX &vec,\n                                             int start_index, int length) {\n    return vec.segment(start_index, length);\n  }\n\n  EIGEN_ALWAYS_INLINE static MatrixX block(const MatrixX &mat,\n                                           int start_row_index,\n                                           int start_col_index, int rows,\n                                           int cols) {\n    return mat.block(start_row_index, start_col_index, rows, cols);\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix3X &output,\n                                               const Matrix3 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix6 &output,\n                                               const Matrix3 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(Matrix3 &output,\n                                               const Matrix6 &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_block(MatrixX &output,\n                                               const MatrixX &input, int i,\n                                               int j, int m = -1, int n = -1,\n                                               int input_i = 0,\n                                               int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  template <int Rows1, int Cols1, int Rows2, int Cols2>\n  EIGEN_ALWAYS_INLINE static void assign_block(\n      Eigen::Matrix<Scalar, Rows1, Cols1> &output,\n      const Eigen::Matrix<Scalar, Rows2, Cols2> &input, int i, int j,\n      int m = -1, int n = -1, int input_i = 0, int input_j = 0) {\n    if (m < 0) m = input.rows();\n    if (n < 0) n = input.cols();\n    assert(i + m <= output.rows() && j + n <= output.cols());\n    assert(input_i + m <= input.rows() && input_j + n <= input.cols());\n    for (int ii = 0; ii < m; ++ii) {\n      for (int jj = 0; jj < n; ++jj) {\n        output(ii + i, jj + j) = input(ii + input_i, jj + input_j);\n      }\n    }\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i,\n                                                const Vector3 &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3 &m, Index i,\n                                                const Matrix6 &v) {\n    m.col(i) = v;\n  }\n  EIGEN_ALWAYS_INLINE static void assign_column(Matrix3X &m, Index i,\n                                                const Vector3 &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i,\n                                                const MatrixX &v) {\n    m.col(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_column(MatrixX &m, Index i,\n                                                const SpatialVector &v) {\n    m.block(0, i, 3, 1) = v.top;\n    m.block(3, i, 3, 1) = v.bottom;\n  }\n  template <int Rows, int Cols, typename Derived>\n  EIGEN_ALWAYS_INLINE static void assign_column(\n      Eigen::Matrix<Scalar, Rows, Cols> &m, Index i,\n      const Eigen::DenseBase<Derived> &v) {\n    assign_column(m, i, v.eval());\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i,\n                                             const MatrixX &v) {\n    m.row(i) = v;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_row(MatrixX &m, Index i,\n                                             const SpatialVector &v) {\n    m.block(i, 0, 1, 3) = v.top;\n    m.block(i, 3, 1, 3) = v.bottom;\n  }\n\n  EIGEN_ALWAYS_INLINE static void assign_horizontal(MatrixX &mat,\n                                                    const VectorX &vec,\n                                                    int start_row_index,\n                                                    int start_col_index) {\n    mat.block(start_row_index, start_col_index, 1, vec.cols()) = vec;\n  }\n\n  template <int Rows>\n  EIGEN_ALWAYS_INLINE static void assign_vertical(\n      MatrixX &mat, const Eigen::Matrix<Scalar, Rows, 1> &vec,\n      int start_row_index, int start_col_index) {\n    mat.block(start_row_index, start_col_index, vec.cols(), 1) = vec;\n  }\n\n  template <int Rows, int Cols>\n  TINY_INLINE static VectorX mul_transpose(\n      const Eigen::Matrix<Scalar, Rows, Cols> &mat,\n      const Eigen::Matrix<Scalar, Cols, 1> &vec) {\n    return mat.transpose() * vec;\n  }\n  TINY_INLINE static VectorX mul_transpose(const MatrixX &mat,\n                                           const VectorX &vec) {\n    return mat.transpose() * vec;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Quaternion &quat) {\n    // NOTE: Eigen requires quat to be normalized\n    return quat.toRotationMatrix();\n  }\n  EIGEN_ALWAYS_INLINE static Matrix3 quat_to_matrix(const Scalar &x,\n                                                    const Scalar &y,\n                                                    const Scalar &z,\n                                                    const Scalar &w) {\n    return Quaternion(w, x, y, z).toRotationMatrix();\n  }\n  EIGEN_ALWAYS_INLINE static Quaternion matrix_to_quat(const Matrix3 &m) {\n    return Quaternion(m);\n  }\n  EIGEN_ALWAYS_INLINE static Quaternion axis_angle_quaternion(\n      const Vector3 &axis, const Scalar &angle) {\n    return Quaternion(Eigen::AngleAxis(angle, axis));\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_x_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n    temp << 1, 0, 0, 0, c, s, 0, -s, c;\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_y_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n    temp << c, 0, -s, 0, 1, 0, s, 0, c;\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Matrix3 rotation_z_matrix(const Scalar &angle) {\n    using std::cos, std::sin;\n    Scalar c = cos(angle);\n    Scalar s = sin(angle);\n    Matrix3 temp;\n    temp << c, s, 0, -s, c, 0, 0, 0, 1;\n    return temp;\n  }\n\n  static Matrix3 rotation_zyx_matrix(const Scalar &r, const Scalar &p,\n                                     const Scalar &y) {\n    using std::cos, std::sin;\n    Scalar ci(cos(r));\n    Scalar cj(cos(p));\n    Scalar ch(cos(y));\n    Scalar si(sin(r));\n    Scalar sj(sin(p));\n    Scalar sh(sin(y));\n    Scalar cc = ci * ch;\n    Scalar cs = ci * sh;\n    Scalar sc = si * ch;\n    Scalar ss = si * sh;\n    Matrix3 temp;\n    temp << cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc,\n        sj * cs - sc, -sj, cj * si, cj * ci;\n    return temp;\n  }\n\n  EIGEN_ALWAYS_INLINE static Vector3 rotate(const Quaternion &q,\n                                            const Vector3 &v) {\n    return q * v;\n  }\n\n  /**\n   * Computes the quaternion delta given current rotation q, angular velocity w,\n   * time step dt.\n   */\n  EIGEN_ALWAYS_INLINE static Quaternion quat_velocity(const Quaternion &q,\n                                                      const Vector3 &w,\n                                                      const Scalar &dt) {\n    Quaternion delta((-q.x() * w[0] - q.y() * w[1] - q.z() * w[2]) * (0.5 * dt),\n                     (q.w() * w[0] + q.y() * w[2] - q.z() * w[1]) * (0.5 * dt),\n                     (q.w() * w[1] + q.z() * w[0] - q.x() * w[2]) * (0.5 * dt),\n                     (q.w() * w[2] + q.x() * w[1] - q.y() * w[0]) * (0.5 * dt));\n    return delta;\n  }\n\n  EIGEN_ALWAYS_INLINE static void quat_increment(Quaternion &a,\n                                                 const Quaternion &b) {\n    a.x() += b.x();\n    a.y() += b.y();\n    a.z() += b.z();\n    a.w() += b.w();\n  }\n\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_x(const Quaternion &q) {\n    return q.x();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_y(const Quaternion &q) {\n    return q.y();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_z(const Quaternion &q) {\n    return q.z();\n  }\n  EIGEN_ALWAYS_INLINE static const Scalar &quat_w(const Quaternion &q) {\n    return q.w();\n  }\n  EIGEN_ALWAYS_INLINE static const Quaternion quat_from_xyzw(const Scalar &x,\n                                                             const Scalar &y,\n                                                             const Scalar &z,\n                                                             const Scalar &w) {\n    // Eigen specific constructor coefficient order\n    return Quaternion(w, x, y, z);\n  }\n\n  EIGEN_ALWAYS_INLINE static void set_zero(Matrix3X &m) { m.setZero(); }\n  EIGEN_ALWAYS_INLINE static void set_zero(Vector3 &m) { m.setZero(); }\n  EIGEN_ALWAYS_INLINE static void set_zero(VectorX &m) { m.setZero(); }\n\n  EIGEN_ALWAYS_INLINE static void set_zero(MatrixX &m) { m.setZero(); }\n  template <int Size1, int Size2 = 1>\n  EIGEN_ALWAYS_INLINE static void set_zero(\n      Eigen::Array<Scalar, Size1, Size2> &v) {\n    v.setZero();\n  }\n  EIGEN_ALWAYS_INLINE static void set_zero(MotionVector &v) {\n    v.top.setZero();\n    v.bottom.setZero();\n  }\n  EIGEN_ALWAYS_INLINE static void set_zero(ForceVector &v) {\n    v.top.setZero();\n    v.bottom.setZero();\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  TINY_INLINE static bool is_zero(const Scalar &a) { return a == zero(); }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool less_than(const Scalar &a, const Scalar &b) {\n    return a < b;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool less_than_zero(const Scalar &a) {\n    return a < 0.;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool greater_than_zero(const Scalar &a) {\n    return a > 0.;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool greater_than(const Scalar &a,\n                                               const Scalar &b) {\n    return a > b;\n  }\n\n  /**\n   * Non-differentiable comparison operator.\n   */\n  EIGEN_ALWAYS_INLINE static bool equals(const Scalar &a, const Scalar &b) {\n    return a == b;\n  }\n\n#ifdef USE_STAN\n  template <typename InnerScalar>\n  TINY_INLINE static std::enable_if_t<\n      !std::is_same_v<Scalar, stan::math::fvar<InnerScalar>>, double>\n  to_double(const stan::math::fvar<InnerScalar> &s) {\n    return stan::math::value_of(s);\n  }\n#endif\n\n  TINY_INLINE static double to_double(const Scalar &s) {\n#ifdef USE_STAN\n    if constexpr (std::is_same_v<Scalar, stan::math::var> ||\n                  std::is_same_v<Scalar, stan::math::fvar<double>>) {\n      return stan::math::value_of(s);\n    } else {\n      return static_cast<double>(s);\n    }\n#else\n    return static_cast<double>(s);\n#endif\n  }\n\n  TINY_INLINE static Scalar from_double(double s) {\n    return static_cast<Scalar>(s);\n  }\n\n  template <int Size1, int Size2>\n  static void print(const std::string &title,\n                    Eigen::Matrix<Scalar, Size1, Size2> &m) {\n    std::cout << title << \"\\n\" << m << std::endl;\n  }\n  template <int Size1, int Size2 = 1>\n  static void print(const std::string &title,\n                    Eigen::Array<Scalar, Size1, Size2> &v) {\n    std::cout << title << \"\\n\" << v << std::endl;\n  }\n  static void print(const std::string &title, const Scalar &v) {\n    std::cout << title << \"\\n\" << to_double(v) << std::endl;\n  }\n  template <typename T>\n  static void print(const std::string &title, const T &abi) {\n    abi.print(title.c_str());\n  }\n\n  template <typename T>\n  TINY_INLINE static auto sin(const T &s) {\n    using std::sin;\n    return sin(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto cos(const T &s) {\n    using std::cos;\n    return cos(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto tan(const T &s) {\n    using std::tan;\n    return tan(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto atan2(const T &dy, const T &dx) {\n    using std::atan2;\n    return atan2(dy, dx);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto abs(const T &s) {\n    using std::abs;\n    return abs(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto sqrt(const T &s) {\n    using std::sqrt;\n    return sqrt(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto tanh(const T &s) {\n    using std::tanh;\n    return tanh(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto exp(const T &s) {\n    using std::exp;\n    return exp(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto log(const T &s) {\n    using std::log;\n    return log(s);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto max(const T &x, const T &y) {\n    using std::max;\n    return max(x, y);\n  }\n\n  template <typename T>\n  TINY_INLINE static auto min(const T &x, const T &y) {\n    using std::min;\n    return min(x, y);\n  }\n\n  EigenAlgebraT<Scalar>() = delete;\n};\n\ntypedef EigenAlgebraT<double> EigenAlgebra;\n\n}  // end namespace tds\n", "meta": {"hexsha": "29f16f89fce3f05ec403148cb293015214fe1ce0", "size": 20970, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/eigen_algebra.hpp", "max_stars_repo_name": "rozgo/tiny-differentiable-simulator", "max_stars_repo_head_hexsha": "bcb3794b0ef2e265735c0577467ce629a31d45ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-18T01:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-18T01:25:50.000Z", "max_issues_repo_path": "src/math/eigen_algebra.hpp", "max_issues_repo_name": "rozgo/tiny-differentiable-simulator", "max_issues_repo_head_hexsha": "bcb3794b0ef2e265735c0577467ce629a31d45ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/eigen_algebra.hpp", "max_forks_repo_name": "rozgo/tiny-differentiable-simulator", "max_forks_repo_head_hexsha": "bcb3794b0ef2e265735c0577467ce629a31d45ed", "max_forks_repo_licenses": ["Apache-2.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.0642201835, "max_line_length": 80, "alphanum_fraction": 0.5607534573, "num_tokens": 5673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5696786801643435}}
{"text": "#ifndef MULTINOMIAL_MODEL_HPP\n#define MULTINOMIAL_MODEL_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <stdexcept>\n#include <vector>\n\n/**\n * Return the softmax of the specified vector.  Softmax is defined by\n *\n * ```\n * softmax(alpha) = exp(alpha) / sum(exp(alpha))\n * ```\n *\n * using offsets to prevent underflow of the exponentiation.\n *\n * @param alpha unconstrained input vector\n * @return softmax of input\n */\nEigen::VectorXf softmax(const Eigen::VectorXf& alpha) {\n  using std::exp;\n  auto delta = Eigen::VectorXf::Constant(alpha.size(), alpha.maxCoeff());\n  Eigen::VectorXf phi = (alpha - delta).array().exp();\n  return delta + phi / phi.sum();\n}\n\n/**\n * This class defines a Bayesian model implementing the joint density\n *\n * ```\n * log p(y, alpha | xt)\n *   = log multinomial(y | xt * softmax(alpha)) + log normal(alpha | 0, 3)\n *   = y' * log(xt * softmax(alpha)) - 1 / (2 * 3^2) * alpha' * alpha\n * ```\n *\n * K: kmer size\n * M: number of k-mers (4^K)\n * N: number of reads\n * T: number of isoforms\n * y: (M x 1) matrix of shredded reads\n * x: (T x M) sparse matrix of kmers per isoform with simplex rows\n * xt: (M x T) sparse matrix of kmers per isoform with simplex columns\n * alpha: (T x 1) vector of log odds\n */\nstruct multinomial_model {\n  const Eigen::Map<Eigen::SparseMatrix<float, Eigen::RowMajor>>& xt_;\n  const Eigen::VectorXf& y_;\n\n  multinomial_model(\n      const Eigen::Map<Eigen::SparseMatrix<float, Eigen::RowMajor>>& xt,\n      const Eigen::VectorXf& y)\n      : xt_(xt), y_(y) {\n    if (xt.cols() != y.rows()) {\n       throw std::runtime_error(\"xt rows must equal y cols\");\n    }\n  }\n\n  float log_density(const Eigen::VectorXf& beta) {\n    Eigen::VectorXf theta = softmax(beta);\n    std::cout << \"beta.size() = \" << beta.size()\n              << \"; theta.size() = \" << theta.size()\n              << std::endl;\n    std::cout << \"model:  xt_.rows() = \" << xt_.rows() << std::endl;\n    std::cout << \"model:  xt_.cols() = \" << xt_.cols() << std::endl;\n    // Eigen::VectorXf xt_sm_a =  (xt_ * theta).array().log();\n    float log_likelihood = 0;\n    // float log_likelihood = y_.transpose() * xt_sm_a;\n    float log_prior = -0.125 * beta.transpose() * beta;\n    return log_likelihood + log_prior;\n  }\n\n  void grad_log_density(const Eigen::VectorXf& beta, Eigen::VectorXf& grad) {\n    Eigen::VectorXf t1 = softmax(beta);\n    Eigen::VectorXf t2 = xt_ * t1;\n    Eigen::VectorXf t3 = (y_.cwiseProduct(t2.cwiseInverse()).transpose() * xt_).transpose();\n    Eigen::VectorXf grad_likelihood = t1.cwiseProduct(t3) - t1.dot(t3) * t1;\n    Eigen::VectorXf grad_prior = -0.25 * beta;\n    grad = grad_likelihood + grad_prior;\n  }\n\n  //   std::vector<int> sample(uint64_t N, const Eigen::VectorXf& beta) {\n  // return std::multinomial_rng(N, xt_ * softmax(beta));\n  // }\n\n  // std::vector<int> sample(uint64_t N, double mu, double sigma) {\n  // return std::vector<int>();\n  // }\n};\n\n#endif\n", "meta": {"hexsha": "44735215775200935dfebdc49e45f451fde44bd0", "size": 2929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kmers/src/kmers/multinomial-model.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/multinomial-model.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/multinomial-model.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": 31.4946236559, "max_line_length": 92, "alphanum_fraction": 0.6302492318, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5696786720768505}}
{"text": "/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#define _USE_MATH_DEFINES\n#include <Eigen/Core>\n#include <cmath>\n#include <random>\n\n#include \"beanmachine/graph/distribution/log_normal.h\"\n\nnamespace beanmachine {\nnamespace distribution {\n\nusing namespace graph;\n\nLogNormal::LogNormal(AtomicType sample_type, const std::vector<Node*>& in_nodes)\n    : Distribution(DistributionType::LOG_NORMAL, sample_type) {\n  // a Log Normal distribution has two parents\n  // mean of logarithm distribution -> real,\n  // standard deviation of logarithm distribution -> positive real\n  if (in_nodes.size() != 2) {\n    throw std::invalid_argument(\n        \"LogNormal distribution must have exactly two parents\");\n  }\n  if (in_nodes[0]->value.type != graph::AtomicType::REAL or\n      in_nodes[1]->value.type != graph::AtomicType::POS_REAL) {\n    throw std::invalid_argument(\n        \"LogNormal parents must be a real number and a positive real number\");\n  }\n  if (sample_type != AtomicType::POS_REAL) {\n    throw std::invalid_argument(\n        \"LogNormal distribution produces positive real number samples\");\n  }\n}\n\ndouble LogNormal::_double_sampler(std::mt19937& gen) const {\n  std::lognormal_distribution<double> dist(\n      in_nodes[0]->value._double, in_nodes[1]->value._double);\n  return dist(gen);\n}\n\n// log_prob of a log normal:\n//    - log(s) - 0.5 log(2*pi) - 0.5 (log(x) - m)^2 / s^2 - log(x)\n// grad  w.r.t. value x: (m - log(x) - s^2) / (x * s^2)\n// grad2 w.r.t. value x: (s^2 + log(x) - m - 1) / (s^2 * x^2)\n// grad  w.r.t. s : -1/s + (log(x)-m)^2 / s^3\n// grad2 w.r.t. s : 1/s^2 - 3 (log(x)-m)^2 / s^4\n// grad  w.r.t. m : (log(x) - m) / s^2\n// grad2 w.r.t. m : -1 / s^2\n// First order chain rule: f(g(x))' = f'(g(x)) g'(x),\n// - In backward propagation, f'(g(x)) is given by adjunct, the above equation\n// computes g'(x). [g is the current function f is the final target]\n// - In forward propagation, g'(x) is given by in_nodes[x]->grad1,\n// the above equation computes f'(g) [f is the current function g is the input]\ndouble LogNormal::log_prob(const NodeValue& value) const {\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double result, sum_logx, sum_logx_sq;\n  int size;\n\n  if (value.type.variable_type == graph::VariableType::SCALAR) {\n    size = 1;\n    sum_logx = std::log(value._double);\n    sum_logx_sq = sum_logx * sum_logx;\n  } else if (\n      value.type.variable_type == graph::VariableType::BROADCAST_MATRIX) {\n    size = static_cast<int>(value._matrix.size());\n    sum_logx = value._matrix.array().log().matrix().sum();\n    sum_logx_sq = value._matrix.array().log().matrix().squaredNorm();\n  } else {\n    throw std::runtime_error(\n        \"LogNormal::log_prob applied to invalid variable type\");\n  }\n  result = (-std::log(s) - 0.5 * std::log(2 * M_PI)) * size -\n      0.5 * (sum_logx_sq - 2 * m * sum_logx + m * m * size) / (s * s) -\n      sum_logx;\n  return result;\n}\n\nvoid LogNormal::log_prob_iid(\n    const graph::NodeValue& value,\n    Eigen::MatrixXd& log_probs) const {\n  assert(value.type.variable_type == graph::VariableType::BROADCAST_MATRIX);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic> logs =\n      value._matrix.array().log();\n  log_probs = (-std::log(s) - 0.5 * std::log(2 * M_PI)) -\n      0.5 * (logs - m).pow(2) / (s * s) - logs;\n}\n\nvoid LogNormal::_grad1_log_prob_value(\n    double& grad1,\n    double val,\n    double m,\n    double s_sq) {\n  grad1 += (m - std::log(val) - s_sq) / (val * s_sq);\n};\n\nvoid LogNormal::_grad2_log_prob_value(\n    double& grad2,\n    double val,\n    double m,\n    double s_sq) {\n  grad2 += (s_sq + std::log(val) - m - 1) / (val * val * s_sq);\n};\n\nvoid LogNormal::gradient_log_prob_value(\n    const NodeValue& value,\n    double& grad1,\n    double& grad2) const {\n  assert(value.type.variable_type == graph::VariableType::SCALAR);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n  _grad1_log_prob_value(grad1, value._double, m, s_sq);\n  _grad2_log_prob_value(grad2, value._double, m, s_sq);\n}\n\nvoid LogNormal::gradient_log_prob_param(\n    const NodeValue& value,\n    double& grad1,\n    double& grad2) const {\n  assert(value.type.variable_type == graph::VariableType::SCALAR);\n  double log_x = std::log(value._double);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n  // gradients of m should be non-zero before computing gradients w.r.t. m\n  double m_grad = in_nodes[0]->grad1;\n  double m_grad2 = in_nodes[0]->grad2;\n  if (m_grad != 0 or m_grad2 != 0) {\n    double grad_m = (log_x - m) / s_sq;\n    double grad2_m2 = -1 / s_sq;\n    grad1 += grad_m * m_grad;\n    grad2 += grad2_m2 * m_grad * m_grad + grad_m * m_grad2;\n  }\n  double s_grad = in_nodes[1]->grad1;\n  double s_grad2 = in_nodes[1]->grad2;\n  if (s_grad != 0 or s_grad2 != 0) {\n    double grad_s = -1 / s + (log_x - m) * (log_x - m) / (s * s * s);\n    double grad2_s2 = 1 / s_sq - 3 * (log_x - m) * (log_x - m) / (s_sq * s_sq);\n    grad1 += grad_s * s_grad;\n    grad2 += grad2_s2 * s_grad * s_grad + grad_s * s_grad2;\n  }\n}\n\nvoid LogNormal::backward_value(\n    const graph::NodeValue& value,\n    graph::DoubleMatrix& back_grad,\n    double adjunct) const {\n  assert(value.type.variable_type == graph::VariableType::SCALAR);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n  double increment = 0.0;\n  _grad1_log_prob_value(increment, value._double, m, s_sq);\n  back_grad += adjunct * increment;\n}\n\nvoid LogNormal::backward_value_iid(\n    const graph::NodeValue& value,\n    graph::DoubleMatrix& back_grad) const {\n  assert(value.type.variable_type == graph::VariableType::BROADCAST_MATRIX);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n  back_grad +=\n      (m - value._matrix.array().log() - s_sq) / (value._matrix.array() * s_sq);\n}\n\nvoid LogNormal::backward_value_iid(\n    const graph::NodeValue& value,\n    graph::DoubleMatrix& back_grad,\n    Eigen::MatrixXd& adjunct) const {\n  assert(value.type.variable_type == graph::VariableType::BROADCAST_MATRIX);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n  back_grad += (adjunct.array()) * (m - value._matrix.array().log() - s_sq) /\n      (value._matrix.array() * s_sq);\n}\n\nvoid LogNormal::backward_param(const graph::NodeValue& value, double adjunct)\n    const {\n  assert(value.type.variable_type == graph::VariableType::SCALAR);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double log_x = std::log(value._double);\n  double s_sq = s * s;\n  double jacob_0 = (log_x - m) / s_sq;\n\n  if (in_nodes[0]->needs_gradient()) {\n    in_nodes[0]->back_grad1 += adjunct * jacob_0;\n  }\n  if (in_nodes[1]->needs_gradient()) {\n    in_nodes[1]->back_grad1 += adjunct * (-1 / s + jacob_0 * jacob_0 * s);\n  }\n}\n\nvoid LogNormal::backward_param_iid(const graph::NodeValue& value) const {\n  assert(value.type.variable_type == graph::VariableType::BROADCAST_MATRIX);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n\n  int size = static_cast<int>(value._matrix.size());\n  double sum_logx = value._matrix.array().log().sum();\n  if (in_nodes[0]->needs_gradient()) {\n    in_nodes[0]->back_grad1 += sum_logx / s_sq - size * m / s_sq;\n  }\n  if (in_nodes[1]->needs_gradient()) {\n    double sum_logx_sq = value._matrix.array().log().matrix().squaredNorm();\n    in_nodes[1]->back_grad1 +=\n        (-size / s +\n         (sum_logx_sq - 2 * m * sum_logx + m * m * size) / (s * s_sq));\n  }\n}\n\nvoid LogNormal::backward_param_iid(\n    const graph::NodeValue& value,\n    Eigen::MatrixXd& adjunct) const {\n  assert(value.type.variable_type == graph::VariableType::BROADCAST_MATRIX);\n  double m = in_nodes[0]->value._double;\n  double s = in_nodes[1]->value._double;\n  double s_sq = s * s;\n\n  double sum_logx = (value._matrix.array().log() * adjunct.array()).sum();\n  double sum_adjunct = adjunct.sum();\n  if (in_nodes[0]->needs_gradient()) {\n    in_nodes[0]->back_grad1 += sum_logx / s_sq - sum_adjunct * m / s_sq;\n  }\n  if (in_nodes[1]->needs_gradient()) {\n    double sum_logx_sq =\n        (value._matrix.array().log().pow(2) * adjunct.array()).sum();\n    in_nodes[1]->back_grad1 +=\n        (-sum_adjunct / s +\n         (sum_logx_sq - 2 * m * sum_logx + m * m * sum_adjunct) / (s * s_sq));\n  }\n}\n\n} // namespace distribution\n} // namespace beanmachine\n", "meta": {"hexsha": "6c7a0f37771e37fc160ea437d048d7b8facbea25", "size": 8719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beanmachine/graph/distribution/log_normal.cpp", "max_stars_repo_name": "facebookresearch/beanmachine", "max_stars_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 177.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T14:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T05:48:10.000Z", "max_issues_repo_path": "src/beanmachine/graph/distribution/log_normal.cpp", "max_issues_repo_name": "facebookresearch/beanmachine", "max_issues_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 171.0, "max_issues_repo_issues_event_min_datetime": "2021-12-11T06:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:26:29.000Z", "max_forks_repo_path": "src/beanmachine/graph/distribution/log_normal.cpp", "max_forks_repo_name": "facebookresearch/beanmachine", "max_forks_repo_head_hexsha": "225114d9964b90c3a49adddc4387b4a47d1b4262", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2021-12-11T06:27:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T13:31:56.000Z", "avg_line_length": 35.1572580645, "max_line_length": 80, "alphanum_fraction": 0.6529418511, "num_tokens": 2628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5695203004209719}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Anderson Jr., J.D. , Fundamentals of Aerodynamics, 3rd edition, McGraw Hill, 2001.\n *      Gentry, A., Smyth, D., and Oliver, W. . The Mark IV Supersonic-Hypersonic Arbitrary Body\n *          Program, Volume II - Program Formulation, Douglas Aircraft Company, 1973.\n *      Anderson Jr., J.D, Hypersonic and High-Temperature Gas Dynamics, 2nd edition, AIAA\n *          Education Series, 2006.\n *\n */\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamics.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/equilibriumWallTemperature.h\"\n\n#include <memory>\n#include <boost/make_shared.hpp>\n\nnamespace tudat\n{\nnamespace aerodynamics\n{\n\nusing mathematical_constants::PI;\nusing std::atan;\nusing std::exp;\nusing std::log;\nusing std::pow;\nusing std::sqrt;\nusing std::tan;\n\n//! Compute local-to-static pressure ratio.\ndouble computeLocalToStaticPressureRatio( double machNumber,\n                                          double ratioOfSpecificHeats )\n{\n    // Return local-to-static pressure ratio.\n    return pow( 2.0 / ( 2.0 + ( ratioOfSpecificHeats - 1.0 ) * pow( machNumber, 2.0 ) ),\n                ratioOfSpecificHeats / ( ratioOfSpecificHeats - 1.0 ) );\n}\n\n//! Compute Prandtl-Meyer function.\ndouble computePrandtlMeyerFunction( double machNumber, double ratioOfSpecificHeats )\n{\n    // Declare local variables.\n    // Declare Mach number squared.\n    double machNumberSquared_ = pow( machNumber, 2.0 );\n\n    // Return value of Prandtl-Meyer function.\n    return sqrt ( ( ratioOfSpecificHeats + 1.0 ) / ( ratioOfSpecificHeats - 1.0 ) )\n            * atan ( sqrt ( ( ratioOfSpecificHeats - 1.0 ) / ( ratioOfSpecificHeats + 1.0 )\n                            * ( machNumberSquared_ - 1.0 ) ) )\n            - atan( sqrt ( machNumberSquared_ - 1.0 ) );\n}\n\n//! Compute stagnation pressure coefficient in supersonic flow.\ndouble computeStagnationPressure( double machNumber,\n                                  double ratioOfSpecificHeats )\n{\n    // Declare local variables.\n    // Declare Mach number squared.\n    double machNumberSquared_ = pow( machNumber, 2.0 );\n\n    // Return stagnation pressure coefficient.\n    return 2.0 / ( ratioOfSpecificHeats * machNumberSquared_ )\n            * ( pow ( pow( ( ratioOfSpecificHeats + 1.0 ) * machNumber, 2.0 )\n                      / ( 4.0 * ratioOfSpecificHeats * machNumberSquared_\n                          - 2.0 * ( ratioOfSpecificHeats - 1.0 ) ),\n                      ratioOfSpecificHeats / ( ratioOfSpecificHeats - 1.0 ) )\n                * ( ( 1.0 - ratioOfSpecificHeats\n                      + 2.0 * ratioOfSpecificHeats * machNumberSquared_ )\n                    / ( ratioOfSpecificHeats + 1.0 ) ) - 1.0 );\n}\n\n//! Compute pressure coefficient based on Newtonian theory.\ndouble computeNewtonianPressureCoefficient( double inclinationAngle )\n{\n    // Return pressure coefficient.\n    return 2.0 * pow( sin( inclinationAngle ), 2.0 );\n}\n\n//! Compute pressure coefficient based on modified Newtonian theory.\ndouble computeModifiedNewtonianPressureCoefficient(\n    double inclinationAngle, double stagnationPressureCoefficient )\n{\n    // Return pressure coefficient.\n    return stagnationPressureCoefficient * pow( sin( inclinationAngle ), 2.0 );\n}\n\n//! Compute pressure coefficient using empirical tangent wedge method.\ndouble computeEmpiricalTangentWedgePressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variable.\n    double machNumberSine_;\n\n    // Set local variable.\n    machNumberSine_ = machNumber * sin( inclinationAngle );\n\n    // Return pressure coefficient approximation.\n    return ( pow( 1.2 * machNumberSine_ + exp( -0.6 * machNumberSine_ ), 2.0 )\n             - 1.0 ) / ( 0.6 * pow( machNumber, 2.0 ) );\n}\n\n//! Compute pressure coefficient using empirical tangent cone method.\ndouble computeEmpiricalTangentConePressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variables.\n    double machNumberSine_;\n    double temporaryValue_;\n\n    // Set local variables.\n    machNumberSine_ = machNumber * sin ( inclinationAngle );\n    temporaryValue_ = pow( ( 1.090909 * machNumberSine_\n                             +  exp( -0.5454545 * machNumberSine_ ) ), 2.0 );\n\n    // Return pressure coefficient approximation.\n    return ( 48.0 * temporaryValue_ * pow( sin( inclinationAngle), 2.0 ) )\n            / ( 23.0 * temporaryValue_ - 5.0 );\n}\n\n//! Compute pressure coefficient using modified Dahlem-Buck method.\ndouble computeModifiedDahlemBuckPressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variables.\n    double checkAngle_ = 22.5 * PI / 180.0;\n    double factor1_;\n    double factor2_;\n    double exponent_;\n    double pressureCoefficient_;\n\n    // Check if inclination angle is greater than check angle. If so, use\n    // Newtonian approximation.\n    if ( inclinationAngle > checkAngle_ )\n    {\n        pressureCoefficient_\n                = computeNewtonianPressureCoefficient( inclinationAngle );\n    }\n\n    // Else use Dahlem-Buck method.\n    else\n    {\n        pressureCoefficient_\n                = ( 1.0 + sin( 4.0 * pow( inclinationAngle , 0.75 ) ) )\n                / ( pow( 4.0 * cos( inclinationAngle )\n                         * cos( 2.0 * inclinationAngle ), 0.75 ) )\n                * pow( sin( inclinationAngle ), 1.25 );\n    }\n\n    // For mach < 20, a correction term should be applied.\n    if ( machNumber > 20.0 )\n    {\n        factor2_ = 1.0;\n    }\n    else\n    {\n        // Determine correction term.\n        factor1_ = ( 6.0 - 0.3 * machNumber ) + sin( PI * ( log( machNumber ) - 0.588 ) / 1.20 );\n\n        exponent_ = 1.15 + 0.5 * sin( PI * ( log( machNumber ) - 0.916 ) / 3.29 );\n\n        factor2_ = 1.0 + factor1_ * pow( inclinationAngle * 180.0 / PI, -1.0 * exponent_ );\n    }\n\n    // Return pressure coefficient.\n    return pressureCoefficient_ * factor2_;\n}\n\n//! Compute pressure coefficient using the Hankey flat surface method.\ndouble computeHankeyFlatSurfacePressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variables.\n    double stagnationPressureCoefficient_;\n\n    // Calculate 'effective' stagnation pressure coefficient for low\n    // inclination angle.\n    if( inclinationAngle < PI / 18.0 )\n    {\n        stagnationPressureCoefficient_ = ( 0.195 + 0.222594 / pow( machNumber, 0.3 ) - 0.4 )\n                * inclinationAngle * 180.0 / PI + 4.0;\n    }\n    // Calculate 'effective' stagnation pressure coefficient for other\n    // inclination angle.\n    else\n    {\n        stagnationPressureCoefficient_ = 1.95 + 0.3925 / ( pow( machNumber, 0.3 )\n                                                           * tan( inclinationAngle ) );\n    }\n\n    // Return pressure coefficient using 'effective' stagnation pressure\n    // coefficient.\n    return computeModifiedNewtonianPressureCoefficient(\n                inclinationAngle, stagnationPressureCoefficient_ );\n}\n\n//! Compute pressure coefficient using the Smyth delta wing method.\ndouble computeSmythDeltaWingPressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variables.\n    double machNumberSine_;\n    double correctedInclinationAngle_;\n\n    // Calculate inclination angle for use in calculations ( angles lower than\n    // 1 degree not allowed ).\n    if ( inclinationAngle < PI / 180.0 )\n    {\n        correctedInclinationAngle_ = PI / 180.0;\n    }\n\n    else\n    {\n        correctedInclinationAngle_ = inclinationAngle;\n    }\n\n    // Pre-compute for efficiency.\n    machNumberSine_ = machNumber * sin( correctedInclinationAngle_ );\n\n    // Employ empirical correlation to calculate pressure coefficient.\n    // Return pressure coefficient.\n    return 1.66667 * ( pow( 1.09 * machNumberSine_ + exp( -0.49 * machNumberSine_ ), 2.0 ) - 1.0 )\n            / pow( machNumber, 2.0 );\n}\n\n//! Compute pressure coefficient using the van Dyke unified method.\ndouble computeVanDykeUnifiedPressureCoefficient(\n    double inclinationAngle, double machNumber,\n    double ratioOfSpecificHeats, int type )\n{\n    // Declare and initialize local variables and pre-compute for efficiency.\n    double ratioOfSpecificHeatsTerm_ = ( ratioOfSpecificHeats + 1.0 ) / 2.0;\n    double machNumberTerm_ = sqrt( pow( machNumber , 2.0 ) - 1.0 );\n    double exponent_ = 2.0 * ratioOfSpecificHeats / ( ratioOfSpecificHeats - 1.0 );\n\n    // Declare and initialize value.\n    double pressureCoefficient_ = 0.0;\n\n    // Calculate compression pressure coefficient.\n    if ( inclinationAngle >= 0.0 && type == 1 )\n    {\n        pressureCoefficient_ = pow( inclinationAngle, 2.0 )\n                * ( ratioOfSpecificHeatsTerm_\n                    + sqrt( pow( ratioOfSpecificHeatsTerm_, 2.0 )\n                            + 4.0 / ( pow(  inclinationAngle * machNumberTerm_, 2.0 ) ) ) );\n    }\n\n    // Calculate expansion pressure coefficient.\n    else if ( inclinationAngle < 0.0 && type == -1 )\n    {\n        // Calculate vacuum pressure coefficient.\n        double vacuumPressureCoefficient_ = computeVacuumPressureCoefficient(\n                    machNumber, ratioOfSpecificHeats );\n\n        // Check to see if pressure coefficient will be lower than vacuum case,\n        // set to vacuum if so.\n        if ( -1.0 * inclinationAngle * machNumberTerm_\n             > 2.0 / ( ratioOfSpecificHeats - 1.0 ) )\n        {\n            pressureCoefficient_ = vacuumPressureCoefficient_;\n        }\n        else\n        {\n            pressureCoefficient_\n                    = 2.0 / ( ratioOfSpecificHeats * pow( machNumberTerm_, 2.0 ) )\n                    * ( pow( 1.0 - ( ratioOfSpecificHeats - 1.0 ) / 2.0\n                             * - 1.0 * inclinationAngle * machNumberTerm_, exponent_ ) - 1.0 );\n\n            if ( pressureCoefficient_ < vacuumPressureCoefficient_ )\n            {\n                pressureCoefficient_ = vacuumPressureCoefficient_;\n            }\n        }\n    }\n\n    // Return pressure coefficient.\n    return pressureCoefficient_;\n}\n\n//! Compute pressure coefficient using Prandtl-Meyer expansion.\ndouble computePrandtlMeyerFreestreamPressureCoefficient(\n    double inclinationAngle, double machNumber,\n    double ratioOfSpecificHeats, double freestreamPrandtlMeyerFunction )\n{\n    // Declare local variables.\n    double prandtlMeyerFunction_;\n    double pressureCoefficient_;\n\n    // Determine Prandtl-Meyer function value.\n    prandtlMeyerFunction_ = freestreamPrandtlMeyerFunction - inclinationAngle;\n\n    // If Prandtl-Meyer function is greater than the vacuum value, set vacuum\n    // pressure coefficient.\n    if ( prandtlMeyerFunction_ > maximumPrandtlMeyerFunctionValue )\n    {\n        pressureCoefficient_ = computeVacuumPressureCoefficient(\n                    machNumber, ratioOfSpecificHeats );\n    }\n\n    else\n    {\n        // Determine local mach number.\n        double localMachNumber_\n                = computeInversePrandtlMeyerFunction( prandtlMeyerFunction_ );\n\n        // Determine local to freestream pressure ratio.\n        double pressureRatio_\n                = computeLocalToStaticPressureRatio( localMachNumber_,\n                                                     ratioOfSpecificHeats )\n                / computeLocalToStaticPressureRatio( machNumber,\n                                                     ratioOfSpecificHeats );\n\n        // Form pressure coefficient.\n        pressureCoefficient_ = 2.0 / ( ratioOfSpecificHeats * pow( machNumber, 2.0 ) )\n                * ( pressureRatio_ - 1.0 );\n    }\n\n    // Return pressure coefficient.\n    return pressureCoefficient_;\n}\n\n//! Compute pressure coefficient at vacuum.\ndouble computeVacuumPressureCoefficient(\n    double machNumber, double ratioOfSpecificHeats )\n{\n    // Return pressure coefficient.\n    return -2.0 / ( ratioOfSpecificHeats * pow( machNumber, 2.0 ) );\n}\n\n//! Compute high Mach base pressure coefficient.\ndouble computeHighMachBasePressure( double machNumber )\n{\n    // Calculate pressure coefficient.\n    return -1.0 / pow( machNumber, 2.0 );\n}\n\n//! Compute pressure coefficient using the ACM empirical method.\ndouble computeAcmEmpiricalPressureCoefficient(\n    double inclinationAngle, double machNumber )\n{\n    // Declare local variables.\n    double pressureCoefficient_;\n    double minimumPressureCoefficient_;\n    double preliminaryPressureCoefficient_;\n\n    // Set minimum pressure coefficient.\n    minimumPressureCoefficient_ = -1.0 / pow( machNumber, 2.0 );\n\n    // Calculate preliminary pressure coefficient.\n    preliminaryPressureCoefficient_ = 180.0 / PI * inclinationAngle\n            / ( 16.0 * pow( machNumber, 2.0 ) );\n\n    // If necessary, correct preliminary pressure coefficient.\n    if ( minimumPressureCoefficient_ > preliminaryPressureCoefficient_ )\n    {\n        pressureCoefficient_ = minimumPressureCoefficient_;\n    }\n\n    else\n    {\n        pressureCoefficient_ = preliminaryPressureCoefficient_;\n    }\n\n    // Return pressure coefficient.\n    return pressureCoefficient_;\n}\n\n//! Compute Mach number from Prandtl-Meyer function.\ndouble computeInversePrandtlMeyerFunction( double prandtlMeyerFunctionValue )\n{\n    // Declare local variables.\n    double inputVariableForCorrelation_;\n    double machNumber_;\n\n    // Determine input variable for correlation.\n    inputVariableForCorrelation_ = pow( prandtlMeyerFunctionValue\n                                        / maximumPrandtlMeyerFunctionValue, 2.0 / 3.0 );\n\n    // Calculate Mach number.\n    machNumber_ = ( 1.0 + inputVariableForCorrelation_\n                    * ( PrandtlMeyerParameter1 + inputVariableForCorrelation_\n                        * ( PrandtlMeyerParameter2 + inputVariableForCorrelation_\n                            * PrandtlMeyerParameter3 ) ) )\n            / ( 1.0 + inputVariableForCorrelation_ * ( PrandtlMeyerParameter4\n                                                       + inputVariableForCorrelation_\n                                                       * PrandtlMeyerParameter5 ) );\n\n    // Return Mach number.\n    return machNumber_;\n}\n\n//! Compute ratio of post- to pre-shock pressure.\ndouble computeShockPressureRatio( double normalMachNumber,\n                                  double ratioOfSpecificHeats )\n{\n    // Return pressure ratio.\n    return 1.0 + 2.0 * ratioOfSpecificHeats / ( ratioOfSpecificHeats + 1.0 )\n            * ( normalMachNumber * normalMachNumber - 1.0 );\n}\n\n//! Compute ratio of post- to pre-shock density.\ndouble computeShockDensityRatio( double normalMachNumber,\n                                 double ratioOfSpecificHeats )\n{\n    // Declare local variables.\n    double machNumberSquared_;\n\n    // Calculate mach number squared for efficiency.\n    machNumberSquared_ = pow( normalMachNumber, 2.0 );\n\n    // Return density ratio.\n    return ( ratioOfSpecificHeats + 1.0 ) * machNumberSquared_\n            / ( 2.0 + ( ratioOfSpecificHeats - 1.0 ) * machNumberSquared_ );\n}\n\n//! Compute ratio of post- to pre-shock temperature.\ndouble computeShockTemperatureRatio( double normalMachNumber,\n                                     double ratioOfSpecificHeats )\n{\n    // Return temperature ratio from perfect gas law.\n    return 1.0 / computeShockDensityRatio( normalMachNumber, ratioOfSpecificHeats )\n            * computeShockPressureRatio( normalMachNumber, ratioOfSpecificHeats );\n}\n\n//! Compute jump in entropy across a shock wave.\ndouble computeShockEntropyJump( double normalMachNumber,\n                                double ratioOfSpecificHeats,\n                                double specificGasConstant )\n{\n    // Declare local variables.\n    double specificHeatConstantPressure_;\n\n    // Calculate specific heat at constant pressure.\n    specificHeatConstantPressure_ = ratioOfSpecificHeats * specificGasConstant\n            / ( ratioOfSpecificHeats - 1.0 );\n\n    // Return entropy jump from temperature and pressure ratio.\n    return specificHeatConstantPressure_\n            * log( computeShockTemperatureRatio( normalMachNumber, ratioOfSpecificHeats ) )\n            - specificGasConstant\n            * log( computeShockPressureRatio( normalMachNumber, ratioOfSpecificHeats ) );\n}\n\n//! Compute post- to pre-shock total pressure ratio.\ndouble computeShockTotalPressureRatio( double normalMachNumber,\n                                       double ratioOfSpecificHeats,\n                                       double specificGasConstant )\n{\n    // Return total pressure ratio from entropy jump.\n    return exp( -1.0 * computeShockEntropyJump( normalMachNumber, ratioOfSpecificHeats,\n                                                specificGasConstant ) / specificGasConstant );\n}\n\n//! Compute shock deflection angle.\ndouble computeShockDeflectionAngle( double shockAngle, double machNumber,\n                                    double ratioOfSpecificHeats )\n{\n    // Declare local variables.\n    double tangentOfDeflectionAngle_;\n\n    // Calculate tangent of deflection angle.\n    tangentOfDeflectionAngle_ = 2.0 * ( pow( machNumber * sin( shockAngle ), 2.0 ) - 1.0 )\n            / ( tan( shockAngle ) * ( pow( machNumber, 2.0 )\n                                      * ( ratioOfSpecificHeats\n                                          + cos( 2.0 * shockAngle ) ) + 2.0 ) );\n\n    // Return deflection angle.\n    return atan( tangentOfDeflectionAngle_ );\n}\n\n//! Function to compute the speed of sound in a gas\ndouble computeSpeedOfSound( const double temperature, const double ratioOfSpecificHeats,\n                            const double specificGasConstant )\n{\n    return std::sqrt( temperature * ratioOfSpecificHeats * specificGasConstant );\n}\n\n//! Compute Mach number\ndouble computeMachNumber( const double speed, const double speedOfSound )\n{\n    return speed / speedOfSound;\n}\n\n//! Function to compute the mean free path of a particle.\ndouble computeMeanFreePath( const double weightedAverageCollisionDiameter, const double averageNumberDensity )\n{\n    return 1.0 / ( std::sqrt( 2.0 ) * mathematical_constants::PI * weightedAverageCollisionDiameter *\n                   weightedAverageCollisionDiameter * averageNumberDensity );\n}\n\n//! Compute the aerodynamic load experienced by a vehicle.\ndouble computeAerodynamicLoad( const double airDensity,\n                               const double airSpeed,\n                               const double referenceArea,\n                               const double vehicleMass,\n                               const Eigen::Vector3d& aerodynamicForceCoefficients )\n{\n    return computeAerodynamicLoadFromAcceleration(\n                0.5 * airDensity * airSpeed * airSpeed * referenceArea * aerodynamicForceCoefficients / vehicleMass );\n}\n\n\n//! Function to compute the aerodynamic load experienced by a vehicle.\ndouble computeAerodynamicLoadFromAcceleration( const Eigen::Vector3d& aerodynamicAccelerationVector )\n{\n    return aerodynamicAccelerationVector.norm( ) / physical_constants::SEA_LEVEL_GRAVITATIONAL_ACCELERATION;\n}\n\n//! Funtion to compute the equilibrium heat flux experienced by a vehicle\ndouble computeEquilibriumHeatflux( const std::function< double( const double ) > heatTransferFunction,\n                                   const double wallEmmisivity,\n                                   const double adiabaticWallTemperature )\n{\n    return heatTransferFunction( computeEquilibiumWallTemperature(\n                                     heatTransferFunction, wallEmmisivity, adiabaticWallTemperature ) );\n}\n\n//! Function to compute the heat flux experienced by a vehicle, assuming an equlibrium wall temperature.\ndouble computeEquilibriumFayRiddellHeatFlux( const double airDensity,\n                                             const double airSpeed,\n                                             const double airTemperature,\n                                             const double machNumber,\n                                             const double noseRadius,\n                                             const double wallEmissivity )\n{\n    // Compute adiabatic wall temperature.\n    double adiabaticWallTemperature\n            = computeAdiabaticWallTemperature( airTemperature , machNumber );\n\n    std::function< double( const double ) > heatTransferFunction = std::bind(\n                &computeFayRiddellHeatFlux, airDensity, airSpeed, airTemperature, noseRadius, std::placeholders::_1 );\n\n    return computeEquilibriumHeatflux( heatTransferFunction, wallEmissivity, adiabaticWallTemperature );\n}\n\n//! Function to compute the heat flux experienced by a vehicle.\ndouble computeFayRiddellHeatFlux( const double airDensity,\n                                  const double airSpeed,\n                                  const double airTemperature,\n                                  const double noseRadius,\n                                  const double wallTemperature )\n{\n    // Compute the current heat flux.\n    return FAY_RIDDEL_HEAT_FLUX_CONSTANT * sqrt( airDensity * std::pow( airSpeed , 2.0 ) / noseRadius )\n            * ( 0.5 * std::pow( airSpeed , 2.0 ) + 1004.0 * ( airTemperature - wallTemperature ) );\n}\n\n//! Compute the adiabatic wall temperature experienced by a vehicle.\ndouble computeAdiabaticWallTemperature(\n        const double airTemperature, const double machNumber, const double ratioSpecificHeats,\n        const double recoveryFactor )\n{\n    double totalTemperature\n            = airTemperature * ( 1 + 0.5 * ( ratioSpecificHeats - 1 ) * machNumber * machNumber );\n\n    return airTemperature + recoveryFactor * ( totalTemperature - airTemperature );\n}\n\n} // namespace aerodynamics\n} // namespace tudat\n", "meta": {"hexsha": "a814ab129fb178ad3a32492332f4284d39636f56", "size": 22068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/aerodynamics.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/Aerodynamics/aerodynamics.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/Aerodynamics/aerodynamics.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": 38.4459930314, "max_line_length": 118, "alphanum_fraction": 0.6508972268, "num_tokens": 4992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.6442251064863695, "lm_q1q2_score": 0.5695202964845629}}
{"text": "//\n//  util.cpp\n//  calib\n//\n//  Created by jimmy on 2017-07-27.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"util.h\"\n#include <iostream>\n\n#include <dirent.h>\n#include <string.h>\n\n// Eigen\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\nusing std::cout;\nusing std::endl;\n\nstatic Eigen::Vector3d rotation_to_rodrigues(const Eigen::Matrix3d &r)\n{\n    Eigen::AngleAxisd aa(r);\n    \n   // Eigen::Vector3d axis = aa.axis()*aa.angle();\n    \n    \n    double ang = aa.angle();\n    if (ang == 0.0) {\n        return Eigen::Vector3d::Zero();\n    }\n    return aa.axis()*(ang);\n}\n\nbool writeCamera(const char *fileName, const char *imageName, const perspective_camera & camera)\n{\n    assert(fileName);\n    assert(imageName);\n    \n    FILE *pf = fopen(fileName, \"w\");\n    if (!pf) {\n        printf(\"can not create file %s\\n\", fileName);\n        return false;\n    }\n   \n    fprintf(pf, \"%s\\n\", imageName);\n    fprintf(pf, \"ppx\\t ppy\\t focal length\\t Rx\\t Ry\\t Rz\\t Cx\\t Cy\\t Cz\\n\");\n    double ppx = camera.principal_point().x();\n    double ppy = camera.principal_point().y();\n    double fl = camera.get_calibration()(0, 0);\n    Eigen::Matrix3d r = camera.get_rotation();\n    Eigen::Vector3d rod = rotation_to_rodrigues(r);\n    \n    double Rx = rod.x();\n    double Ry = rod.y();\n    double Rz = rod.z();\n    double Cx = camera.get_camera_center().x();\n    double Cy = camera.get_camera_center().y();\n    double Cz = camera.get_camera_center().z();\n    fprintf(pf, \"%f\\t %f\\t %f\\t %f\\t %f\\t %f\\t %f\\t %f\\t %f\\n\", ppx, ppy, fl, Rx, Ry, Rz, Cx, Cy, Cz);\n    fclose(pf);\n    return true;\n}\n\nbool readCamera(const char *fileName, string & imageName, perspective_camera & camera)\n{\n    assert(fileName);\n    FILE *pf = fopen(fileName, \"r\");\n    if (!pf) {\n        printf(\"can not open file %s\\n\", fileName);\n        return false;\n    }\n    char buf[1024] = {NULL};\n    int num = fscanf(pf, \"%s\\n\", buf);\n    assert(num == 1);\n    imageName = string(buf);\n    for (int i = 0; i<1; i++) {\n        char lineBuf[BUFSIZ] = {NULL};\n        fgets(lineBuf, sizeof(lineBuf), pf);\n        cout<<lineBuf;\n    }\n    double ppx, ppy, fl, rx, ry, rz, cx, cy, cz;\n    int ret = fscanf(pf, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf\", &ppx, &ppy, &fl, &rx, &ry, &rz, &cx, &cy, &cz);\n    if (ret != 9) {\n        printf(\"Error: read camera parameters!\\n\");\n        return false;\n    }\n    \n    Eigen::Matrix3d K;\n    K.setIdentity();\n    K(0, 0) = fl;\n    K(1, 1) = fl;\n    K(0, 2) = ppx;\n    K(1, 2) = ppy;\n    \n    Eigen::Vector3d rod(rx, ry, rz);\n    Eigen::Vector3d cc(cx, cy, cz);\n    \n    camera.set_calibration(K);\n    camera.set_rotation(rod);\n    camera.set_camera_center(cc);\n    fclose(pf);\n\n    return true;\n}\n\nvoid readFilenames(const char *folder, vector<string> & file_names)\n{\n    const char *post_fix = strrchr(folder, '.');\n    string pre_str(folder);\n    pre_str = pre_str.substr(0, pre_str.rfind('/') + 1);\n    //printf(\"pre_str is %s\\n\", pre_str.c_str());\n    \n    assert(post_fix);\n    // vcl_vector<vcl_string> file_names;\n    DIR *dir = NULL;\n    struct dirent *ent = NULL;\n    if ((dir = opendir (pre_str.c_str())) != NULL) {\n        /* print all the files and directories within directory */\n        while ((ent = readdir (dir)) != NULL) {\n            const char *cur_post_fix = strrchr( ent->d_name, '.');\n            if (!cur_post_fix ) {\n                continue;\n            }\n            //printf(\"cur post_fix is %s %s\\n\", post_fix, cur_post_fix);\n            \n            if (!strcmp(post_fix, cur_post_fix)) {\n                file_names.push_back(pre_str + string(ent->d_name));\n                //  cout<<file_names.back()<<endl;\n            }\n            \n            //printf (\"%s\\n\", ent->d_name);\n        }\n        closedir (dir);\n    }\n    printf(\"read %lu files\\n\", file_names.size());\n}\n\nnamespace {\n    struct PureRotateFunctor\n    {\n        typedef double Scalar;\n        \n        typedef Eigen::VectorXd InputType;\n        typedef Eigen::VectorXd ValueType;\n        typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> JacobianType;\n        \n        enum {\n            InputsAtCompileTime = Eigen::Dynamic,\n            ValuesAtCompileTime = Eigen::Dynamic\n        };\n        \n        vector<Eigen::Vector2d > pts1_;\n        vector<Eigen::Vector2d > pts2_;\n        Eigen::Matrix3d invR1_;\n        Eigen::Matrix3d invK1_;\n        Eigen::Vector2d pp_;   // principle point\n        \n        int m_inputs;\n        int m_values;\n        \n        PureRotateFunctor()\n        {\n            m_inputs = 5;\n            m_values = 10;\n        }\n        \n        void setValue(const vector<Eigen::Vector2d >& pts1,\n                      const vector<Eigen::Vector2d >& pts2,\n                      const Eigen::Matrix3d& invR1,\n                      const Eigen::Matrix3d& invK1,\n                      const Eigen::Vector2d& pp)\n        {\n            pts1_ = pts1;\n            pts2_ = pts2;\n            invR1_ = invR1;\n            invK1_ = invK1;\n            pp_ = pp;\n            m_inputs = 5;\n            m_values = 2*(int)pts1.size();\n        }\n        \n        \n        int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fx) const\n        {\n            double fl = x[0];\n            double qx = x[1];\n            double qy = x[2];\n            double qz = x[3];\n            double qw = x[4];\n            \n            Eigen::Quaternion<double> q(qw, qx, qy, qz);\n            Eigen::Matrix3d R2 = q.normalized().toRotationMatrix();\n            \n            Eigen::Matrix3d K2;\n            K2.fill(0);\n            K2(0, 0) = K2(1, 1) = fl;\n            K2(0, 2) = pp_.x();\n            K2(1, 2) = pp_.y();\n            K2(2, 2) = 1.0;\n            \n            // x2 = K_2 * R_2 * R_1^{-1} * K_1^{-1} x1\n            int idx = 0;\n            for (int i = 0; i<pts1_.size(); i++) {\n                Eigen::Vector3d p(pts1_[i].x(), pts1_[i].y(), 1.0);\n                Eigen::Vector3d q = K2 * R2 * invR1_ * invK1_ * p;\n                double x = q[0]/q[2];\n                double y = q[1]/q[2];\n                \n                fx[idx] = pts2_[i].x() - x;\n                idx++;\n                fx[idx] = pts2_[i].y() - y;\n                idx++;\n            }\n            \n            return 0;\n        }\n        \n        int inputs() const { return m_inputs; }// inputs is the dimension of x.\n        int values() const { return m_values; } // \"values\" is the number of f_i and\n        \n        void setCameraMatrixRotation(const Eigen::VectorXd& x,\n                                     cvx::perspective_camera& camera)\n        {\n            double fl = x[0];\n            double qx = x[1];\n            double qy = x[2];\n            double qz = x[3];\n            double qw = x[4];\n            \n            Eigen::Quaternion<double> q(qw, qx, qy, qz);\n            Eigen::Matrix3d R2 = q.normalized().toRotationMatrix();\n            camera.set_rotation(R2);\n            \n            camera.set_calibration(fl, pp_.x(), pp_.y());\n        }\n    };\n}\n\n\n\nbool calibratePureRotateCamera(const vector<Eigen::Vector2d > & pts1,\n                               const vector<Eigen::Vector2d > & pts2,\n                               const cvx::perspective_camera & camera1,\n                               cvx::perspective_camera & camera2)\n{\n    assert(pts1.size() == pts2.size());\n    assert(pts1.size() >= 4);\n    \n   // vnl_matrix_fixed<double, 3, 3> invR1 = vnl_inverse(camera1.get_rotation().as_matrix());\n   // vnl_matrix_fixed<double, 3, 3> invK1 = vnl_inverse(camera1.get_calibration().get_matrix());\n   // vgl_point_2d<double> pp = camera1.get_calibration().principal_point();\n    Eigen::Matrix3d invR1 = camera1.get_rotation().inverse();\n    Eigen::Matrix3d invK1 = camera1.get_calibration().inverse();\n    Eigen::Vector2d pp = camera1.principal_point();\n    \n    Eigen::Quaternion<double> q(camera1.get_rotation());\n    \n    Eigen::VectorXd x(5);\n    x[0] = camera1.focal_length();\n    x[1] = q.x();\n    x[2] = q.y();\n    x[3] = q.z();\n    x[4] = q.w();\n    \n    PureRotateFunctor myFunctor;\n    myFunctor.setValue(pts1, pts2, invR1, invK1, pp);\n    Eigen::NumericalDiff<PureRotateFunctor> numericalDiffMyFunctor(myFunctor);\n    Eigen::LevenbergMarquardt<Eigen::NumericalDiff<PureRotateFunctor>, double> levenbergMarquardt(numericalDiffMyFunctor);\n    \n    levenbergMarquardt.parameters.ftol = 1e-6;\n    levenbergMarquardt.parameters.xtol = 1e-6;\n    levenbergMarquardt.parameters.maxfev = 100; // Max iterations\n    \n    Eigen::VectorXd xmin = x; // initialize\n    levenbergMarquardt.minimize(xmin);\n    \n    myFunctor.setCameraMatrixRotation(xmin, camera2);\n    camera2.set_camera_center(camera1.get_camera_center());\n    \n   // std::cout << \"x that minimizes the function: \" << xmin << std::endl;\n    \n   // x[1] = camera1.get_rotation().as_rodrigues()[0];\n   // x[2] = camera1.get_rotation().as_rodrigues()[1];\n   // x[3] = camera1.get_rotation().as_rodrigues()[2];\n    \n    /*\n    \n    calibrate_pure_rotate_camera_residual residual(pts1, pts2, invR1, invK1, pp);\n    \n    \n    \n    vnl_levenberg_marquardt lmq(residual);\n    lmq.set_f_tolerance(0.0001);\n    \n    bool isMinized = lmq.minimize(x);\n    if (!isMinized) {\n        vcl_cerr<<\"Error: minimization failed.\\n\";\n        lmq.diagnose_outcome();\n        return false;\n    }\n    lmq.diagnose_outcome();\n    \n    residual.setCameraMatrixRotation(x, camera2);\n    camera2.set_camera_center(camera1.get_camera_center());\n    return true;\n     */\n\n    return true;\n}", "meta": {"hexsha": "a08d8a27929400cf6da0f3121dc99f286153de49", "size": 9514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/referenceFrameCalib_v2/src/eigen_util/util.cpp", "max_stars_repo_name": "lood339/CalibMe", "max_stars_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-07T10:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T10:52:45.000Z", "max_issues_repo_path": "src/referenceFrameCalib_v2/src/eigen_util/util.cpp", "max_issues_repo_name": "lood339/CalibMe", "max_issues_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/referenceFrameCalib_v2/src/eigen_util/util.cpp", "max_forks_repo_name": "lood339/CalibMe", "max_forks_repo_head_hexsha": "03c4f51e63b2ec0824d47fae6daeae8ef52040c7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4935897436, "max_line_length": 122, "alphanum_fraction": 0.5421484129, "num_tokens": 2654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.5694849330364578}}
{"text": "#include <iostream>\n#include <vector>\n#include <boost/algorithm/string.hpp>\nusing namespace std;\n\n\ndouble measureAUC(vector <float> &score, vector <int> &labels){\n\n    int numInst = score.size();\n    vector<pair<float, float> > scorelabels;\n    for(int j=0; j<numInst; j++){\n        scorelabels.push_back(make_pair(score[j], labels[j]));\n    }\n\n    //Sort the scores in descending order.\n    sort(scorelabels.rbegin(), scorelabels.rend()); \n\n    //Update the score and labels vectors to make them appear in the sorted order of scores.\n    for(int i=0; i<numInst; i++){\n        score[i]=scorelabels[i].first;\n        labels[i]=scorelabels[i].second;\n    }\n    \n    //posLabel = 1: Data Anomalies\n    //negLabel = 0: Normal Data\n    int posLabel = 1;\n    int negLabel = 0;\n    int countPos = 0;\n    int countNeg = 0;\n\n    for(int j=0; j<numInst; j++){\n        if(labels[j]==1){\n            countPos++;\n        }\n        else{\n            countNeg++;\n        }\n    }\n\n    double accumPos = 0;\n    double accumNeg = 0;\n    double accumAuc = 0;\n\n    double unitPos = (double)1/(double)countPos;\n    double unitNeg = (double)1/(double)countNeg;\n\n    int i=0;\n    while(i<numInst){\n\n        double temp = accumPos;\n        if (i<numInst-2 && score[i] == score[i + 1]){\n            while (i<numInst-2 && score[i] == score[i + 1]){\n                if(labels[i] == negLabel){\n                    accumNeg = accumNeg + 1;\n                }\n                else{\n                    accumPos = accumPos + 1;\n                }\n                i++;\n            }\n\n            if(labels[i] == negLabel){\n                accumNeg = accumNeg + 1;\n            }\n            else{\n                accumPos = accumPos + 1;\n            }\n\n            accumAuc = accumAuc + (accumPos + temp) * unitPos * accumNeg * unitNeg / 2;\n            accumNeg = 0;\n        }       \n        else{\n            if(labels[i] == negLabel){\n                accumNeg = accumNeg + 1;\n                accumAuc = accumAuc + accumPos * unitPos * accumNeg * unitNeg;\n                accumNeg = 0;\n            }\n            else{\n                accumPos = accumPos + 1;\n            }\n        }\n        i++;\n    }\n    return accumAuc;\n\n}", "meta": {"hexsha": "9950d5ba1c5f7e8de6a857926b740b837f67b2dd", "size": 2191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "traceStream/stream/Measure_AUC.cpp", "max_stars_repo_name": "imperial-qore/openforest", "max_stars_repo_head_hexsha": "1f8e880b1de7f76137baad949705744812319dc8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "traceStream/stream/Measure_AUC.cpp", "max_issues_repo_name": "imperial-qore/openforest", "max_issues_repo_head_hexsha": "1f8e880b1de7f76137baad949705744812319dc8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "traceStream/stream/Measure_AUC.cpp", "max_forks_repo_name": "imperial-qore/openforest", "max_forks_repo_head_hexsha": "1f8e880b1de7f76137baad949705744812319dc8", "max_forks_repo_licenses": ["BSD-3-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.476744186, "max_line_length": 92, "alphanum_fraction": 0.4874486536, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.569482715093}}
{"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\r\n/*\r\n ------------------ Author: Tiziana Sabatini  ------------------------------------------------\r\n ------------------ E-mail: (tiziana.sabatini@yahoo.it) --------------------------------------\r\n Patched by Guillermo to correct the behaviour of the + button on the 3rd body selection panel. Nov 09\r\n */\r\n\r\n#include \"perturbations.h\"\r\n#include \"Atmosphere/AtmosphereModel.h\"\r\n#include \"cartesianTOorbital.h\"\r\n#include \"cartesianTOspherical.h\"\r\n#include \"statevector.h\"\r\n#include \"stabody.h\"\r\n#include \"stamath.h\"\r\n#include \"date.h\"\r\n#include \"math.h\"\r\n#include \"inertialTOfixed.h\"\r\n#include \"getGreenwichHourAngle.h\"\r\n#include <QFile>\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n#include \"Entry/capsule.h\"\r\n#include <QErrorMessage>\r\n#include <QDebug>\r\n\r\nconst double PI = 3.141592;\r\n\r\nPerturbations::Perturbations()\r\n{\r\n}\r\n\r\nPerturbations::~Perturbations()\r\n{\r\n}\r\n\r\n// TODO: This method should be abstract\r\nVector3d\r\nPerturbations::calculateAcceleration(sta::StateVector /* state */, double /* time */, double /* dt */)\r\n{\r\n    return Vector3d::Zero();\r\n}\r\n\r\n/////////////////////////////// Gravity Field Perturbation ///////////////////////////////\r\nGravityPerturbations::GravityPerturbations(const StaBody* centralBody,\r\n                                           const ScenarioGravityModel* gravityModel)\r\n{\r\n    m_body = centralBody;\r\n    m_modelName = gravityModel->modelName();\r\n    m_zonalCount = gravityModel->numberOfZonals();\r\n    m_tesseralCount = gravityModel->numberOfTesserals();\r\n\r\n    //Assigning dimension to matrices of harmonical coefficients\r\n    J.resize(m_zonalCount + 1);\r\n    JJ.resize(m_zonalCount + 1 , m_tesseralCount + 1);\r\n    gamma.resize(m_zonalCount + 1, m_tesseralCount + 1);\r\n\r\n    loadGravityConstants();\r\n}\r\n\r\n\r\nGravityPerturbations::~GravityPerturbations()\r\n{\r\n}\r\n\r\nVector3d GravityPerturbations::calculateAcceleration(sta::StateVector state, double time, double dt)\r\n{\r\n    double R = body()->equatorialRadius();\r\n    double mu = body()->mu();\r\n    double greenwich = getGreenwichHourAngle (time);\r\n\r\n    int n_zonals = zonalCount();\r\n    int m_tesserals = tesseralCount();\r\n\r\n    //Operating coordinate conversion from inertial cartesian to earth-fixed spherical\r\n    double longitude, latitude, r, V, g, chi;\r\n    VectorXd state_f(6);\r\n\r\n    //TO DO : change the number 0 and put directly the stabody\r\n    inertialTOfixed(0, greenwich,\r\n                state.position.x(), state.position.y(), state.position.z(),\r\n                state.position.x(), state.position.y(), state.position.z(),\r\n                state_f(0), state_f(1), state_f(2), state_f(3), state_f(4), state_f(5));\r\n\r\n    cartesianTOspherical(state_f(0), state_f(1), state_f(2), state_f(3), state_f(4), state_f(5),\r\n                         longitude, latitude, r, V, g, chi);\r\n\r\n    //Calculating the accelerations\r\n    double derivative_r_zonals(0);\r\n    double derivative_r_tesserals(0);\r\n    double derivative_lat_zonals(0);\r\n    double derivative_lat_tesserals(0);\r\n    double derivative_long_tesserals(0);\r\n\r\n    double x = sin(latitude);\r\n\r\n    //P Legendre Polynomials, PP associated Legendre functions of the first kind\r\n    VectorXd P(n_zonals + 1);\r\n    MatrixXd PP(n_zonals + 1, m_tesserals + 1);\r\n\r\n    //Assign values of P and PP with index below 2\r\n    P(0) = 1;\r\n    PP(0,0) = P(0);\r\n    if (n_zonals != 0)\r\n    {\r\n        P(1) = x;\r\n        PP(1,0) = P(1);\r\n    }\r\n    if (m_tesserals != 0)\r\n        PP(1,1) = - pow((1 - pow(x,2.0)),0.5);\r\n\r\n    for (int n = 2; n <= n_zonals ; n++)\r\n    {\r\n        //Legendre polynomials calculation:\r\n        P(n) = ((2*n - 1) * P(n-1) * x - (n-1) * P(n-2)) / n;  //three term recurrence relation\r\n        PP(n,0) = P(n);\r\n\r\n        //Spherical coordinates derivative calculation (zonals terms):\r\n        derivative_r_zonals += ((n+1) * J(n) * pow(R,n) * P(n) * pow(r,-(n+2)));\r\n        derivative_lat_zonals += - cos(latitude) * J(n) * pow(r,-(n+2)) * pow(R,n) * (1.0  / (pow(x,2) - 1) * n * (x*P(n) - P(n-1)));\r\n\r\n        for (int m = 1; (m <= m_tesserals && m <= n) ; m++)\r\n        {\r\n            //Associated Legendre functions calculation:\r\n            if(n == m)\r\n            {\r\n                PP(n,m) = pow(-1.0,n) * doublefactorial(2*n - 1) * pow((1 - pow(x,2.0)),n/2);\r\n            }\r\n            else if(n == m+1)\r\n            {\r\n                PP(n,m) = x * (2*m + 1) * PP(n-1,m);\r\n            }\r\n            else\r\n            {\r\n                PP(n,m) = 1/(n-m) * ((2*n-1) * x * PP(n-1,m) - (n+m-1) * PP(n-2,m));\r\n            }\r\n\r\n            //Spherical coordinates derivative calculation (tesserals terms):\r\n            derivative_r_tesserals += (n+1) * JJ(n,m) * pow(R,n) * PP(n,m) * pow(r,-(n+2)) * cos(m * (longitude - gamma(n,m)));\r\n            derivative_lat_tesserals += - sin(latitude)/pow(r,n+2) * JJ(n,m) * pow(R,n) * (-(n+m) * (n-m+1) * sqrt(1 - (pow(x,2))) / ((pow(x,2)) -1) * PP(n,m-1) - m * x * PP(n,m) / (pow(x,2) - 1)) * cos(m * (longitude - gamma(n,m)));\r\n            derivative_long_tesserals +=  ((1/pow(r,n+2) * JJ(n,m) * pow(R,n) * PP(n,m)) * m * sin(m*(longitude - gamma(n,m))))/cos(latitude) ;\r\n\r\n        }\r\n    }\r\n\r\n    Vector3d acc_spherical;\r\n    acc_spherical.x() = mu * (derivative_r_zonals + derivative_r_tesserals);\r\n    acc_spherical.y() = -mu * (derivative_lat_zonals + derivative_lat_tesserals);\r\n    acc_spherical.z() = mu * derivative_long_tesserals;\r\n\r\n    //TO DO change the following line and use astro-core functions\r\n    //Coordinates transformation from spherical/fixed to cartesian/inertial\r\n    Vector3d acceleration;\r\n    Matrix3d rotation1, rotation2;\r\n\r\n    rotation1 << cos(latitude) * cos(longitude), -sin(longitude)*cos(latitude), -sin(latitude),\r\n                sin(longitude), cos(longitude), 0,\r\n                sin(latitude) * cos(longitude), -sin(latitude) * sin(longitude), cos(latitude);\r\n    rotation2 << cos(greenwich), -sin(greenwich), 0,\r\n                sin(greenwich), cos(greenwich), 0,\r\n                0, 0, 1;\r\n\r\n    acceleration = rotation1 * rotation2 * acc_spherical;\r\n\r\n    return acceleration;\r\n}\r\n\r\nvoid GravityPerturbations::loadGravityConstants()\r\n{\r\n    //Assign a null value to constant harmonics below index 2\r\n    J(0) = 0;\r\n    J(1) = 0;\r\n    JJ(0,0) = 0;    gamma(0,0) = 0;\r\n    JJ(1,0) = 0;    gamma(1,0) = 0;\r\n    if (m_tesseralCount != 0)\r\n    {\r\n        JJ(1,1) = 0;\r\n        gamma(1,1) = 0;\r\n    }\r\n\r\n    //Open the file .stad containing the normalized gravity constants.\r\n    //The number of loaded constants is consistent with the accuracy order the user selected.\r\n    QString path = QString(\"data/bodies/\");\r\n    path.append(m_modelName);\r\n\r\n    //QTextStream out (stdout); out << \"===> bodies path: \" << path << endl;\r\n\r\n    QFile gravity(path);\r\n\r\n    if (!gravity.open(QIODevice::ReadOnly))\r\n    {\r\n        // TODO: It's an error if the gravity model doesn't exist! Need a mechanism\r\n        // for reporting this to the user.\r\n        return;\r\n    }\r\n\r\n    QTextStream gravitystream(&gravity);\r\n\r\n    MatrixXd C(m_zonalCount + 1, m_zonalCount + 1), S(m_zonalCount + 1, m_zonalCount + 1);\r\n    int n = 0, m = 0;\r\n\r\n    while (gravitystream.status() == QTextStream::Ok)\r\n    {\r\n        gravitystream >> n;\r\n        if (n > m_zonalCount) break;\r\n        gravitystream >> m;\r\n        gravitystream >> C(n,m);\r\n        gravitystream >> S(n,m);\r\n    }\r\n    gravity.close();\r\n\r\n    //Converting the gravity constants.\r\n    for (int i = 2 ; i <= m_zonalCount ; i++)\r\n    {\r\n        J(i) = - sqrt(2*i + 1.0) * C(i,0);\r\n        if (m_tesseralCount != 0)\r\n        {\r\n            for (int j = 1 ; (j <= m_tesseralCount && j <= i) ; j++)\r\n            {\r\n                gamma(i,j) = atan(S(i,j)/C(i,j)) / j;\r\n                JJ(i,j) = - fabs(sqrt(factorial(i-j) * (2*i + 1) * 2 / factorial(i+j)) * C(i,j) / cos(j * gamma(i,j)));\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\ndouble factorial(int num)\r\n{\r\n    if (num==0 || num==1)\r\n    return 1.0;\r\n    return factorial(num-1)*num;\r\n}\r\n\r\ndouble doublefactorial(int num)\r\n{\r\n    if (num==0 || num==1)\r\n    return 1.0;\r\n    return doublefactorial(num-2)*num;\r\n}\r\n\r\n/////////////////////////////// Atmospheric Drag Perturbation ///////////////////////////////\r\nAtmosphericDragPerturbations::AtmosphericDragPerturbations(const QString& atmosphereModel)\r\n{\r\n#if OLDSCENARIO\r\n    m_atmosphericModel = perturbation->atmosphericModel();\r\n    m_body = perturbation->centralBody();\r\n    m_surface = properties->physicalProperties()->physicalCharacteristics()->surfaceArea();\r\n    m_cdCoefficients = properties->aerodynamicProperties()->CDCoefficients();\r\n    m_mass = properties->physicalProperties()->physicalCharacteristics()->mass();\r\n#endif\r\n}\r\n\r\nAtmosphericDragPerturbations::~AtmosphericDragPerturbations()\r\n{\r\n}\r\n\r\nVector3d\r\nAtmosphericDragPerturbations::calculateAcceleration(sta::StateVector state, double time, double dt)\r\n{\r\n    //Conversion from kilometers to meters has been made.\r\n    //Calculating the density from the altitude:\r\n    AtmosphereModel atmosphere;\r\n    atmosphere.selectModel(atmosphericModel());\r\n    double h = altitude(body(), state, time);\r\n    double rho = atmosphere.density(h * pow(10,3.0)) * pow(10,9.0);\r\n\r\n    //Calculating the CD coefficient from the altitude (calling re-entry module functions)\r\n    capsule_class vehicle;\r\n    vehicle.selectCdCprofile(cdCoefficients());\r\n    double cd = vehicle.cdc(h * pow(10,3.0));\r\n\r\n    //Considering the atmosphere rotating with the Earth\r\n    //TO DO put omega as a property of StaBody; only earth rotation has been considered\r\n    double omega = 7.29211585494e-5;\r\n    state.velocity.x() += omega * state.position.y();\r\n    state.velocity.y() -= omega * state.position.x();\r\n\r\n    //Calculating the accelerations vector\r\n    Vector3d acceleration = - 0.5 * rho * state.velocity.norm() * state.velocity * (cd * surface()*pow(10,-6.0))/mass();\r\n\r\n    return acceleration;\r\n}\r\n\r\n/////////////////////////////// Solar Pressure Perturbation ///////////////////////////////\r\nSolarPressurePerturbations::SolarPressurePerturbations(StaBody* centralBody,\r\n                                                       double reflectivity,\r\n                                                       double albedo,\r\n                                                       double ir,\r\n                                                       double mass,\r\n                                                       double surfaceArea) :\r\n    m_body(centralBody),\r\n    m_reflectivity(reflectivity),\r\n    m_albedo(albedo),\r\n    m_ir(ir),\r\n    m_mass(mass),\r\n    m_surface(surfaceArea)\r\n{\r\n}\r\n\r\nSolarPressurePerturbations::~SolarPressurePerturbations()\r\n{\r\n}\r\n\r\nVector3d\r\nSolarPressurePerturbations::calculateAcceleration(sta::StateVector state, double time, double dt)\r\n{\r\n    //calculation of the Sun position via the ephemeris\r\n    sta::StateVector sunVector = STA_SOLAR_SYSTEM->sun()->stateVector(time, body(), sta::COORDSYS_EME_J2000);\r\n\r\n    double sunAscension = atan(sunVector.position.y()/sunVector.position.x());\r\n    double sunDeclination = atan(sunVector.position.z() / sqrt(pow(sunVector.position.y(),2.0) + pow(sunVector.position.x(),2.0)));\r\n\r\n    double distancePlanetSun = sunVector.position.norm();\r\n    double distancePlanetSat = state.position.norm();\r\n    double distanceSunSat = (sunVector.position - state.position).norm();\r\n\r\n    //Modeling the solar radiation (using Km)\r\n    double sigma = 5.6704 * pow(10,-8.0); //Boltzmann constant\r\n    double Tsun = 5778; //Sun temperature\r\n    double Rsun = 6.955 * pow(10,5.0); // Sun radius\r\n\r\n    double W = sigma * pow(Tsun, 4.0) * pow((Rsun / distanceSunSat), 2.0);\r\n\r\n    //Calculation of the acceleration module\r\n    double c = 300000;\r\n    double fp = (1 + reflectivity()) * W * (surface() * pow(10,-6.0)) / c / mass();\r\n\r\n    Vector3d accelerationAlbedo(0,0,0);\r\n    Vector3d accelerationIR(0,0,0);\r\n    //Calculation of the albedo and infra-red radiations\r\n    if (albedo())\r\n    {\r\n        double Walbedo = albedoReflectivityCoefficient(body()) * W * pow((body()->meanRadius() / distancePlanetSat), 2.0);\r\n        double fpalbedo = (1 + reflectivity()) * Walbedo * (surface() * pow(10,-6.0)) / c / mass();\r\n        accelerationAlbedo = fpalbedo * state.position/distancePlanetSat;\r\n    }\r\n\r\n    if (ir())\r\n    {\r\n        double Wir = irRadiationFlux(body()) * pow((body()->meanRadius() / distancePlanetSat), 2.0);\r\n        double fpir = (1 + reflectivity()) * Wir * (surface() * pow(10,-6.0)) / c / mass();\r\n        accelerationIR = fpir * state.position/distancePlanetSat;\r\n    }\r\n\r\n    Vector3d acceleration(-fp * cos(sunAscension) * cos(sunDeclination),\r\n                          -fp * sin(sunAscension) * cos(sunDeclination),\r\n                          -fp * sin(sunDeclination));\r\n\r\n    //calculation of the Earth shadow; if the spacecraft is overshadowed by the Earth the solar pressure will be ignored\r\n    double gamma = acos((pow(distanceSunSat,2.0) + pow(distancePlanetSun,2.0) - pow(distancePlanetSat,2.0)) / (2 * distancePlanetSun * distanceSunSat));\r\n    double gamma_c = atan(body()->meanRadius() / distancePlanetSun);\r\n//\r\n//    if (gamma < gamma_c)\r\n//    {\r\n//        if (distanceSunSat > distancePlanetSun)\r\n//            acceleration << 0, 0, 0;\r\n//    }\r\n\r\n    acceleration += accelerationAlbedo + accelerationIR;\r\n\r\n    return acceleration;\r\n}\r\n\r\ndouble albedoReflectivityCoefficient(const StaBody* body)\r\n{\r\n    switch(body->id())\r\n    {\r\n    case STA_MERCURY:\r\n        return 0.53;\r\n    case STA_VENUS:\r\n        return 0.76;\r\n    case STA_EARTH:\r\n        return 0.35;\r\n    case STA_MARS:\r\n        return 0.16;\r\n    case STA_JUPITER:\r\n        return 0.73;\r\n    case STA_SATURN:\r\n        return 0.76;\r\n    case STA_URANUS:\r\n        return 0.93;\r\n    case STA_NEPTUNE:\r\n        return 0.84;\r\n    case STA_PLUTO:\r\n        return 0.14;\r\n    case STA_SUN:\r\n        return 0;\r\n    case STA_MOON:\r\n        return 0.067;\r\n    default:\r\n        return 0;\r\n    }\r\n}\r\n\r\ndouble irRadiationFlux(const StaBody* body)\r\n{\r\n    switch(body->id())\r\n    {\r\n    case STA_MERCURY:\r\n        return 2139;\r\n    case STA_VENUS:\r\n        return 155;\r\n    case STA_EARTH:\r\n        return 240;\r\n    case STA_MARS:\r\n        return 123;\r\n    case STA_JUPITER:\r\n        return 3.4;\r\n    case STA_SATURN:\r\n        return 0.9;\r\n    case STA_URANUS:\r\n        return 0.063;\r\n    case STA_NEPTUNE:\r\n        return 0.06;\r\n    case STA_PLUTO:\r\n        return 0.191;\r\n    case STA_SUN:\r\n        return 0;\r\n    case STA_MOON:\r\n        return 316;\r\n    default:\r\n        return 0;\r\n    }\r\n}\r\n\r\n\r\n/////////////////////////////// Third Body Perturbation ///////////////////////////////\r\n\r\nExternalBodyPerturbations::ExternalBodyPerturbations(const StaBody* centralBody,\r\n                                                     const QList<const StaBody*>& bodies) :\r\n    m_body(centralBody),\r\n    m_perturbingBodyList(bodies)\r\n{\r\n}\r\n\r\n\r\nExternalBodyPerturbations::~ExternalBodyPerturbations()\r\n{\r\n}\r\n\r\n\r\nVector3d\r\nExternalBodyPerturbations::calculateAcceleration(sta::StateVector state, double time, double dt)\r\n{\r\n    Vector3d acceleration(0.0, 0.0, 0.0);\r\n\r\n    foreach(const StaBody* thirdbody,  perturbingBodyList())\r\n    {\r\n        double mu = thirdbody->mu();\r\n        sta::StateVector thirdbodystate = thirdbody->stateVector(time, body(), sta::COORDSYS_EME_J2000);\r\n\r\n        acceleration += mu * ((thirdbodystate.position - state.position) / pow((thirdbodystate.position - state.position).norm(),3.0) - thirdbodystate.position / pow(thirdbodystate.position.norm(), 3.0));\r\n    }\r\n\r\n    return acceleration;\r\n}\r\n\r\n/////////////////////////////// Space Debris Perturbation ///////////////////////////////\r\n\r\nDebrisPerturbations::DebrisPerturbations(const StaBody* centralBody,\r\n                                         double mass,\r\n                                         double surfaceArea) :\r\n    m_body(centralBody),\r\n    m_mass(mass),\r\n    m_surface(surfaceArea),\r\n    m_time(0)\r\n{\r\n    m_counterDebris.resize(25);\r\n    m_counterDebris.setZero();\r\n    m_counterMeteoroids.resize(25);\r\n    m_counterMeteoroids.setZero();\r\n}\r\n\r\n\r\nDebrisPerturbations::~DebrisPerturbations()\r\n{\r\n}\r\n\r\n\r\nVector3d\r\nDebrisPerturbations::calculateAcceleration(sta::StateVector state, double time, double dt)\r\n{\r\n    double mu = body()->mu();\r\n    m_time += dt;\r\n    sta::KeplerianElements keplerian = cartesianTOorbital(mu, state);\r\n\r\n    //Trajectory analysis:\r\n    double h = keplerian.SemimajorAxis * (1 - pow(keplerian.Eccentricity, 2)) / (1 + keplerian.Eccentricity * cos(keplerian.TrueAnomaly)) - body()->meanRadius();\r\n\r\n    int Ndatapoints = 0;\r\n    VectorXd diameter, Ndebris, Nmet, Ntot;\r\n\r\n    // TODO: Shouldn't we use the absolute value of inclination here???\r\n    double inclinationDeg = sta::radToDeg(keplerian.Inclination);\r\n\r\n    if ( 300 <= h && h <= 500 && 46.6 <= inclinationDeg && inclinationDeg <= 57.6 )\r\n        loadStatistics(\"debris_impact_low_altitude.stad\", diameter, Ndebris, Nmet, Ntot, Ndatapoints);\r\n\r\n    else if ( 700 <= h && h <= 900 && 70 <= inclinationDeg && inclinationDeg <= 90 )\r\n        loadStatistics(\"debris_impact_medium_altitude.stad\", diameter, Ndebris, Nmet, Ntot, Ndatapoints);\r\n\r\n    else if ( 35600 <= h && h <= 35900 && 0 <= inclinationDeg && inclinationDeg <= 5.0 )\r\n        loadStatistics(\"debris_impact_geo_altitude.stad\", diameter, Ndebris, Nmet, Ntot, Ndatapoints);\r\n\r\n    else return Vector3d(0.0, 0.0, 0.0);\r\n\r\n    double density_deb = 0.0028; //kg/cm^3\r\n    double density_met = 0.0025; //kg/cm^3\r\n    double deltaT = 0.0001; //10^-4 s\r\n    double accelerationDebris = 0;\r\n    /* double accelerationMeteoroids = 0; */\r\n    VectorXd nDebris(Ndatapoints), diffDebris(Ndatapoints);\r\n    VectorXd nMeteoroids(Ndatapoints), diffMeteoroids(Ndatapoints);\r\n    Vector3d acceleration(0.0, 0.0, 0.0);\r\n\r\n    nDebris = Ndebris/365/24/60/60 * m_time * surface();\r\n    nMeteoroids = Nmet/365/24/60/60 * m_time * surface();\r\n\r\n    for (int i = 0; i < Ndatapoints; i++)\r\n    {\r\n        if (i != Ndatapoints-1)\r\n        {\r\n            diffDebris(i) = nDebris(i) - nDebris(i + 1);\r\n            diffMeteoroids(i) = nMeteoroids(i) - nMeteoroids(i + 1);\r\n        }\r\n        else\r\n        {\r\n            diffDebris(i) = nDebris(i);\r\n            diffMeteoroids(i) = nMeteoroids(i);\r\n        }\r\n\r\n        // Debris collisions calculation\r\n        if (floor(diffDebris(i)) > counterDebris()(i))\r\n        {\r\n            setCounterDebris(i, nDebris(i));\r\n\r\n            double accDebrisModule;\r\n            if (i == 0)\r\n                accDebrisModule = 3 * (density_deb * 4/3 * PI * pow(0.5 * randomNumber(0, diameter(i)),3)) / mass() * randomNumber(4.5,5.5) / deltaT;\r\n            else\r\n                accDebrisModule = 3 * (density_deb * 4/3 * PI * pow(0.5 * randomNumber(diameter(i-1),diameter(i)),3)) / mass() * randomNumber(4.5,5.5) / deltaT;\r\n\r\n            //generate a random direction\r\n            double alpha = randomNumber(0, 2*PI);\r\n            double beta = randomNumber(-PI, PI);\r\n            acceleration.x() += accDebrisModule * cos(alpha) * cos(beta);\r\n            acceleration.y() += accDebrisModule * sin(alpha) * cos(beta);\r\n            acceleration.z() += accDebrisModule * sin(beta);\r\n        }\r\n\r\n        // Meteoroids collisions calculation\r\n        if (floor(diffMeteoroids(i)) > counterMeteoroids()(i))\r\n        {\r\n            setCounterMeteoroids(i, nMeteoroids(i));\r\n\r\n            double accMeteoroidsModule;\r\n            if (i == 0)\r\n                accMeteoroidsModule = 3 * (density_met * 4/3 * PI * pow(0.5 * randomNumber(0, diameter(i)),3)) / mass() * randomNumber(4.5,5.5) / deltaT;\r\n            else\r\n                accMeteoroidsModule = 3 * (density_met * 4/3 * PI * pow(0.5 * randomNumber(diameter(i-1),diameter(i)),3)) / mass() * randomNumber(4.5,5.5) / deltaT;\r\n\r\n            //generate a random direction\r\n            double alpha = randomNumber(0, 2*PI);\r\n            double beta = randomNumber(-PI, PI);\r\n            acceleration.x() += accMeteoroidsModule * cos(alpha) * cos(beta);\r\n            acceleration.y() += accMeteoroidsModule * sin(alpha) * cos(beta);\r\n            acceleration.z() += accMeteoroidsModule * sin(beta);\r\n        }\r\n    }\r\n    return acceleration;\r\n}\r\n\r\nvoid\r\nDebrisPerturbations::loadStatistics(QString filename, VectorXd& diameter, VectorXd& Ndebris, VectorXd& Nmet, VectorXd& Ntot, int& Ndatapoints)\r\n{\r\n    QString path(\"data/atmospheres/\");\r\n    path.append(filename);\r\n    QFile model(\"data/atmospheres/debris_impact_low_altitude.stad\");\r\n\r\n    model.open(QIODevice::ReadOnly);\r\n    QTextStream modelstream(&model);\r\n\r\n    while (!modelstream.atEnd())\r\n    {\r\n        modelstream.readLine();\r\n        Ndatapoints ++;\r\n    }\r\n    model.close();\r\n    diameter.resize(Ndatapoints); Ndebris.resize(Ndatapoints); Nmet.resize(Ndatapoints); Ntot.resize(Ndatapoints);\r\n\r\n    model.open(QIODevice::ReadOnly);\r\n    for (int i = 0; i < Ndatapoints; i++)\r\n    {\r\n        modelstream >> diameter(i);\r\n        modelstream >> Ndebris(i);\r\n        modelstream >> Nmet(i);\r\n        modelstream >> Ntot(i);\r\n    }\r\n    model.close();\r\n}\r\n\r\ndouble randomNumber(double inf, double sup)\r\n{\r\n    const float scale = rand()/float(RAND_MAX);\r\n    return inf + scale * (sup - inf);\r\n}\r\n\r\n\r\n\r\n\r\n/**\r\n * Function: evaluation of Legendre's associated function using recursive form.\r\n * Source: Vallado, Fundamentals of Astrodynamics and Applications\r\n * @param x The argument\r\n * @param l The degree of polynomial\r\n * @param m The order of derivative\r\n * @return The evaluation of Legendre associated function\r\n * Author: Michele Scotti\r\n * E-mail: michele.scotti@gmail.com\r\n */\r\ndouble legendre (double x, int l, int m)\r\n{\r\n        if (m > l)\t\t\t\t\t\t// m > l;\r\n                return 0;\r\n        else if ((l == 0) && (m == 0))\t// l = 0; m = 0;\r\n                return 1;\r\n        else if ((l == 1) && (m == 0))\t// l = 1; m = 0;\r\n                return x;\r\n        else if ((l == 1) && (m == 1))\t// l = 1; m = 1;\r\n                return sqrt(1 - x*x);\r\n        else if (l >= 2 && m == 0)\r\n            return ((2*l-1)*x*legendre(x, l-1, 0) - (l-1)*legendre(x, l-2, 0)) / (l);\r\n        else if (m != 0 && m < l)\r\n            return (legendre(x, l-2, m) + (2*l-1)*(sqrt(1- x*x))*legendre(x, l-1, m-1));\r\n        else if(l == m)\r\n            return ((2*l-1)*sqrt(1-x*x)*legendre(x, l-1, l-1));\r\n        else\r\n            return -1;\r\n}\r\n", "meta": {"hexsha": "743d96b6c0703d66b5153d29ff6e73fa16017edd", "size": 23121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/perturbations.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/perturbations.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/perturbations.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": 34.9788199697, "max_line_length": 234, "alphanum_fraction": 0.5827170105, "num_tokens": 6206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5694827106956754}}
{"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#include <boost/math/special_functions/log1p.hpp>\r\n#include <boost/math/special_functions/erf.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <map>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include \"mp_t.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n//\r\n// This program calculates the coefficients of the polynomials\r\n// used for the regularized incomplete gamma functions gamma_p\r\n// and gamma_q when parameter a is large, and sigma is small\r\n// (where sigma = fabs(1 - x/a) ).\r\n//\r\n// See \"The Asymptotic Expansion of the Incomplete Gamma Functions\"\r\n// N. M. Temme.\r\n// Siam J. Math Anal. Vol 10 No 4, July 1979, p757.\r\n// Coeffient calculation is described from Eq 3.8 (p762) onwards.\r\n//\r\n\r\n//\r\n// Alpha:\r\n//\r\nmp_t alpha(unsigned k)\r\n{\r\n   static map<unsigned, mp_t> data;\r\n   if(data.empty())\r\n   {\r\n      data[1] = 1;\r\n   }\r\n\r\n   map<unsigned, mp_t>::const_iterator pos = data.find(k);\r\n   if(pos != data.end())\r\n      return (*pos).second;\r\n   //\r\n   // OK try and calculate the value:\r\n   //\r\n   mp_t result = alpha(k-1);\r\n   for(unsigned j = 2; j <= k-1; ++j)\r\n   {\r\n      result -= j * alpha(j) * alpha(k-j+1);\r\n   }\r\n   result /= (k+1);\r\n   data[k] = result;\r\n   return result;\r\n}\r\n\r\nmp_t gamma(unsigned k)\r\n{\r\n   static map<unsigned, mp_t> data;\r\n\r\n   map<unsigned, mp_t>::const_iterator pos = data.find(k);\r\n   if(pos != data.end())\r\n      return (*pos).second;\r\n\r\n   mp_t result = (k&1) ? -1 : 1;\r\n\r\n   for(unsigned i = 1; i <= (2 * k + 1); i += 2)\r\n      result *= i;\r\n   result *= alpha(2 * k + 1);\r\n   data[k] = result;\r\n   return result;\r\n}\r\n\r\nmp_t Coeff(unsigned n, unsigned k)\r\n{\r\n   map<unsigned, map<unsigned, mp_t> > data;\r\n   if(data.empty())\r\n      data[0][0] = mp_t(-1) / 3;\r\n\r\n   map<unsigned, map<unsigned, mp_t> >::const_iterator p1 = data.find(n);\r\n   if(p1 != data.end())\r\n   {\r\n      map<unsigned, mp_t>::const_iterator p2 = p1->second.find(k);\r\n      if(p2 != p1->second.end())\r\n      {\r\n         return p2->second;\r\n      }\r\n   }\r\n\r\n   //\r\n   // If we don't have the value, calculate it:\r\n   //\r\n   if(k == 0)\r\n   {\r\n      // special case:\r\n      mp_t result = (n+2) * alpha(n+2);\r\n      data[n][k] = result;\r\n      return result;\r\n   }\r\n   // general case:\r\n   mp_t result = gamma(k) * Coeff(n, 0) + (n+2) * Coeff(n+2, k-1);\r\n   data[n][k] = result;\r\n   return result;\r\n}\r\n\r\nvoid calculate_terms(double sigma, double a, unsigned bits)\r\n{\r\n   cout << endl << endl;\r\n   cout << \"Sigma:        \" << sigma << endl;\r\n   cout << \"A:            \" << a << endl;\r\n   double lambda = 1 - sigma;\r\n   cout << \"Lambda:       \" << lambda << endl;\r\n   double y = a * (-sigma - log1p(-sigma));\r\n   cout << \"Y:            \" << y << endl;\r\n   double z = -sqrt(2 * (-sigma - log1p(-sigma)));\r\n   cout << \"Z:            \" << z << endl;\r\n   double dom = erfc(sqrt(y)) / 2;\r\n   cout << \"Erfc term:    \" << dom << endl;\r\n   double lead = exp(-y) / sqrt(2 * constants::pi<double>() * a);\r\n   cout << \"Remainder factor: \" << lead << endl;\r\n   double eps = ldexp(1.0, 1 - static_cast<int>(bits));\r\n   double target = dom * eps / lead;\r\n   cout << \"Target smallest term: \" << target << endl;\r\n\r\n   unsigned max_n = 0;\r\n\r\n   for(unsigned n = 0; n < 10000; ++n)\r\n   {\r\n      double term = tools::real_cast<double>(Coeff(n, 0) * pow(z, (double)n));\r\n      if(fabs(term) < target)\r\n      {\r\n         max_n = n-1;\r\n         break;\r\n      }\r\n   }\r\n   cout << \"Max n required:  \" << max_n << endl;\r\n\r\n   unsigned max_k;\r\n   for(unsigned k = 1; k < 10000; ++k)\r\n   {\r\n      double term = tools::real_cast<double>(Coeff(0, k) * pow(a, -((double)k)));\r\n      if(fabs(term) < target)\r\n      {\r\n         max_k = k-1;\r\n         break;\r\n      }\r\n   }\r\n   cout << \"Max k required:  \" << max_k << endl << endl;\r\n\r\n   bool code = false;\r\n   cout << \"Print code [0|1]? \";\r\n   cin >> code;\r\n\r\n   int prec = 2 + (static_cast<double>(bits) * 3010LL)/10000;\r\n   std::cout << std::scientific << std::setprecision(40);\r\n\r\n   if(code)\r\n   {\r\n      cout << \"   T workspace[\" << max_k+1 << \"];\\n\\n\";\r\n      for(unsigned k = 0; k <= max_k; ++k)\r\n      {\r\n         cout <<\r\n            \"   static const T C\" << k << \"[] = {\\n\";\r\n         for(unsigned n = 0; n < 10000; ++n)\r\n         {\r\n            double term = tools::real_cast<double>(Coeff(n, k) * pow(a, -((double)k)) * pow(z, (double)n));\r\n            if(fabs(term) < target)\r\n            {\r\n               break;\r\n            }\r\n            cout << \"      \" << Coeff(n, k) << \"L,\\n\";\r\n         }\r\n         cout << \r\n            \"   };\\n\"\r\n            \"   workspace[\" << k << \"] = tools::evaluate_polynomial(C\" << k << \", z);\\n\\n\";\r\n      }\r\n      cout << \"   T result = tools::evaluate_polynomial(workspace, 1/a);\\n\\n\";\r\n   }\r\n}\r\n\r\n\r\nint main()\r\n{\r\n   bool cont;\r\n   do{\r\n      cont  = false;\r\n      double sigma;\r\n      cout << \"Enter max value for sigma (sigma = |1 - x/a|): \";\r\n      cin >> sigma;\r\n      double a;\r\n      cout << \"Enter min value for a: \";\r\n      cin >> a;\r\n      unsigned precision;\r\n      cout << \"Enter number of bits precision required: \";\r\n      cin >> precision;\r\n\r\n      calculate_terms(sigma, a, precision);\r\n\r\n      cout << \"Try again[0|1]: \";\r\n      cin >> cont;\r\n\r\n   }while(cont);\r\n\r\n\r\n   return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "73d62cf53b96b9c8fbd9b2077bdc4ee3a602d047", "size": 5435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/tools/igamma_temme_large_coef.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/tools/igamma_temme_large_coef.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/tools/igamma_temme_large_coef.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": 26.2560386473, "max_line_length": 108, "alphanum_fraction": 0.5120515179, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5694827046600963}}
{"text": "/*******************************************************************************\nCopyright (c) 2011, Dr. D. Studios\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 other\nmaterials provided with the distribution.\nNeither the name of the Dr. D. Studios nor the names of its contributors may be\nused to endorse or promote products derived from this software without specific\nprior 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 DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; 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 ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************/\n\n#ifndef _PIMATH_ROOTS__H_\n#define _PIMATH_ROOTS__H_\n\n#include <boost/python.hpp>\n#include <ImathMath.h>\n#include <ImathRoots.h>\n#include \"util.h\"\n\n/**\n * These functions have been changed to return tuples rather than the root count.\n * If there are no roots, an empty tuple will be returned (rather than None).\n * Return arguments have been removed.\n */\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\n\ttemplate<typename T>\n\tstruct RootsBind\n\t{\n\t\tRootsBind()\n\t\t{\n\t\t\tbp::def(\"solveLinear\", solveLinear);\n\t\t\tbp::def(\"solveQuadratic\", solveQuadratic);\n\t\t\tbp::def(\"solveNormalizedCubic\", solveNormalizedCubic );\n\t\t\tbp::def(\"solveCubic\", solveCubic );\n\t\t}\n\n\t\tstatic bp::object\n\t\tsolveLinear( T a, T b )\n\t\t{\n\t\t\tT rv;\n\t\t\treturn Imath::solveLinear( a, b, rv ) == 1 ?\n\t\t\t\t\tbp::make_tuple( rv ) : bp::make_tuple();\n\t\t}\n\n\t\tstatic bp::object\n\t\tsolveQuadratic( T a, T b, T c )\n\t\t{\n\t\t\tT x[2];\n\t\t\tint count = Imath::solveQuadratic( a, b, c, x );\n\t\t\tswitch( count )\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\treturn bp::make_tuple(x[0]);\n\t\t\t\tcase 2:\n\t\t\t\t\treturn bp::make_tuple(x[0], x[1]);\n\t\t\t}\n\t\t\treturn bp::make_tuple();\n\t\t}\n\n\t\tstatic bp::object\n\t\tsolveNormalizedCubic( T r, T s, T t )\n\t\t{\n\t\t\tT x[3];\n\t\t\tint count = Imath::solveNormalizedCubic( r, s, t, x );\n\t\t\tswitch( count )\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\treturn bp::make_tuple(x[0]);\n\t\t\t\tcase 2:\n\t\t\t\t\treturn bp::make_tuple(x[0],x[1]);\n\t\t\t\tcase 3:\n\t\t\t\t\treturn bp::make_tuple(x[0],x[1],x[2]);\n\t\t\t}\n\t\t\treturn bp::make_tuple();\n\t\t}\n\n\t\tstatic bp::object\n\t\tsolveCubic( T a, T b, T c, T d )\n\t\t{\n\t\t\tT x[3];\n\t\t\tint count = Imath::solveCubic( a, b, c, d, x );\n\t\t\tswitch( count )\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\treturn bp::make_tuple(x[0]);\n\t\t\t\tcase 2:\n\t\t\t\t\treturn bp::make_tuple(x[0],x[1]);\n\t\t\t\tcase 3:\n\t\t\t\t\treturn bp::make_tuple(x[0],x[1],x[2]);\n\t\t\t}\n\t\t\treturn bp::make_tuple();\n\t\t}\n\t};\n}\n\n#endif\n\n", "meta": {"hexsha": "e1bcbf7bcc0b6e88e3e3246cb8443229b283f9a3", "size": 3429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Roots.hpp", "max_stars_repo_name": "madpianist/pimath", "max_stars_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:32:34.000Z", "max_issues_repo_path": "src/Roots.hpp", "max_issues_repo_name": "madpianist/pimath", "max_issues_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Roots.hpp", "max_forks_repo_name": "madpianist/pimath", "max_forks_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_forks_repo_licenses": ["BSD-3-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.575, "max_line_length": 82, "alphanum_fraction": 0.6646252552, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5693858006577388}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2000 - 2019 by the deal.II authors\n *\n * This file is modification of the version in 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 * Modified version.\n */\n#include <deal.II/base/quadrature_lib.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/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.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/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/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <fstream>\n\n\n#include <bench_base.hpp>\n\n\nDEFINE_uint32(\n    num_refine_cycles, 1,\n    \"Number of refinement cycles for the adaptive refinement within deal.ii\");\nDEFINE_uint32(init_refine_level, 4,\n              \"Initial level for the refinement of the mesh.\");\nDEFINE_bool(dealii_orig, false, \"Solve with dealii iterative CG\");\nDEFINE_bool(vis_sol, false, \"Print the solution for visualization\");\n\n#define CHECK_HERE std::cout << \"Here \" << __LINE__ << std::endl;\n\n\nusing namespace dealii;\ntemplate <int dim, typename ValueType = double, typename IndexType = int,\n          typename MixedValueType = double>\nclass BenchDealiiLaplace : public BenchBase<ValueType, IndexType> {\npublic:\n    BenchDealiiLaplace();\n    void run();\n    void run(MPI_Comm mpi_communicator);\n\nprivate:\n    void setup_system();\n    void assemble_system();\n    void solve();\n    void solve(MPI_Comm mpi_communicator);\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    AffineConstraints<double> constraints;\n    SparseMatrix<double> system_matrix;\n    SparsityPattern sparsity_pattern;\n    Vector<double> solution;\n    Vector<double> system_rhs;\n};\n\n\ntemplate <int dim>\ndouble coefficient(const Point<dim> &p)\n{\n    if (p.square() < 0.5 * 0.5)\n        return 20;\n    else\n        return 1;\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nBenchDealiiLaplace<dim, ValueType, IndexType,\n                   MixedValueType>::BenchDealiiLaplace()\n    : fe(2), dof_handler(triangulation)\n{}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType,\n                        MixedValueType>::setup_system()\n{\n    dof_handler.distribute_dofs(fe);\n    solution.reinit(dof_handler.n_dofs());\n    system_rhs.reinit(dof_handler.n_dofs());\n    constraints.clear();\n    DoFTools::make_hanging_node_constraints(dof_handler, constraints);\n    VectorTools::interpolate_boundary_values(\n        dof_handler, 0, Functions::ZeroFunction<dim>(), constraints);\n    constraints.close();\n    DynamicSparsityPattern dsp(dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints,\n                                    /*keep_constrained_dofs = */ false);\n    sparsity_pattern.copy_from(dsp);\n    system_matrix.reinit(sparsity_pattern);\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType,\n                        MixedValueType>::assemble_system()\n{\n    const QGauss<dim> quadrature_formula(fe.degree + 1);\n    FEValues<dim> fe_values(fe, quadrature_formula,\n                            update_values | update_gradients |\n                                update_quadrature_points | update_JxW_values);\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points = quadrature_formula.size();\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n    Vector<double> cell_rhs(dofs_per_cell);\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n    for (const auto &cell : dof_handler.active_cell_iterators()) {\n        cell_matrix = 0;\n        cell_rhs = 0;\n        fe_values.reinit(cell);\n        for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) {\n            const double current_coefficient =\n                coefficient<dim>(fe_values.quadrature_point(q_index));\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                        (current_coefficient *               // a(x_q)\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                cell_rhs(i) +=\n                    (1.0 *                                // f(x)\n                     fe_values.shape_value(i, q_index) *  // phi_i(x_q)\n                     fe_values.JxW(q_index));             // dx\n            }\n        }\n        cell->get_dof_indices(local_dof_indices);\n        constraints.distribute_local_to_global(cell_matrix, cell_rhs,\n                                               local_dof_indices, system_matrix,\n                                               system_rhs);\n    }\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType, MixedValueType>::solve()\n{\n    SolverControl solver_control(1000, 1e-12);\n    SolverCG<> solver(solver_control);\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n    auto start_time = std::chrono::steady_clock::now();\n    solver.solve(system_matrix, solution, system_rhs, preconditioner);\n    auto elapsed_time = std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - start_time);\n    std::cout << \"Time for solve only: \" << elapsed_time.count() << std::endl;\n    constraints.distribute(solution);\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType, MixedValueType>::solve(\n    MPI_Comm mpi_communicator)\n{\n    schwz::Metadata<ValueType, IndexType> metadata;\n    schwz::Settings settings(FLAGS_executor);\n\n    // Set solver metadata from command line args.\n    metadata.mpi_communicator = mpi_communicator;\n    MPI_Comm_rank(metadata.mpi_communicator, &metadata.my_rank);\n    MPI_Comm_size(metadata.mpi_communicator, &metadata.comm_size);\n    metadata.tolerance = FLAGS_set_tol;\n    metadata.max_iters = FLAGS_num_iters;\n    metadata.num_subdomains = metadata.comm_size;\n    metadata.num_threads = FLAGS_num_threads;\n    metadata.oned_laplacian_size = FLAGS_set_1d_laplacian_size;\n\n    // Generic settings\n    settings.write_debug_out = FLAGS_enable_debug_write;\n    settings.write_perm_data = FLAGS_write_perm_data;\n    settings.write_iters_and_residuals = FLAGS_write_iters_and_residuals;\n    settings.print_matrices = FLAGS_print_matrices;\n    settings.shifted_iter = FLAGS_shifted_iter;\n\n    // Set solver settings from command line args.\n    // Comm settings\n    settings.comm_settings.enable_onesided = FLAGS_enable_onesided;\n    if (FLAGS_remote_comm_type == \"put\") {\n        settings.comm_settings.enable_put = true;\n        settings.comm_settings.enable_get = false;\n    } else if (FLAGS_remote_comm_type == \"get\") {\n        settings.comm_settings.enable_put = false;\n        settings.comm_settings.enable_get = true;\n    }\n    settings.comm_settings.enable_one_by_one = FLAGS_enable_one_by_one;\n    settings.comm_settings.stage_through_host = FLAGS_stage_through_host;\n    settings.comm_settings.enable_overlap = FLAGS_enable_comm_overlap;\n    if (FLAGS_flush_type == \"flush-all\") {\n        settings.comm_settings.enable_flush_all = true;\n    } else if (FLAGS_flush_type == \"flush-local\") {\n        settings.comm_settings.enable_flush_all = false;\n        settings.comm_settings.enable_flush_local = true;\n    }\n    if (FLAGS_lock_type == \"lock-all\") {\n        settings.comm_settings.enable_lock_all = true;\n    } else if (FLAGS_lock_type == \"lock-local\") {\n        settings.comm_settings.enable_lock_all = false;\n        settings.comm_settings.enable_lock_local = true;\n    }\n\n    // Convergence settings\n    settings.convergence_settings.put_all_local_residual_norms =\n        FLAGS_enable_put_all_local_residual_norms;\n    settings.convergence_settings.enable_global_check_iter_offset =\n        FLAGS_enable_global_check_iter_offset;\n    settings.convergence_settings.enable_global_check =\n        FLAGS_enable_global_check;\n    if (FLAGS_global_convergence_type == \"centralized-tree\") {\n        settings.convergence_settings.enable_global_simple_tree = true;\n    } else if (FLAGS_global_convergence_type == \"decentralized\") {\n        settings.convergence_settings.enable_decentralized_leader_election =\n            true;\n        settings.convergence_settings.enable_accumulate =\n            FLAGS_enable_decentralized_accumulate;\n    }\n\n    // General solver settings\n    metadata.local_solver_tolerance = FLAGS_local_tol;\n    metadata.local_precond = FLAGS_local_precond;\n    metadata.local_max_iters = FLAGS_local_max_iters;\n    metadata.updated_max_iters = FLAGS_updated_max_iters;\n    settings.non_symmetric_matrix = FLAGS_non_symmetric_matrix;\n    settings.restart_iter = FLAGS_restart_iter;\n    settings.enable_logging = FLAGS_enable_logging;\n    metadata.precond_max_block_size = FLAGS_precond_max_block_size;\n    settings.matrix_filename = FLAGS_matrix_filename;\n    settings.explicit_laplacian = FLAGS_explicit_laplacian;\n    settings.enable_random_rhs = FLAGS_enable_random_rhs;\n    settings.use_mixed_precision = FLAGS_use_mixed_precision;\n    settings.overlap = FLAGS_overlap;\n    settings.naturally_ordered_factor = FLAGS_factor_ordering_natural;\n    settings.reorder = FLAGS_local_reordering;\n    settings.factorization = FLAGS_local_factorization;\n    if (FLAGS_partition == \"metis\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_metis;\n        settings.metis_objtype = FLAGS_metis_objtype;\n    } else if (FLAGS_partition == \"regular\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_regular;\n    } else if (FLAGS_partition == \"regular2d\") {\n        settings.partition =\n            schwz::Settings::partition_settings::partition_regular2d;\n    }\n    if (FLAGS_local_solver == \"iterative-ginkgo\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::iterative_solver_ginkgo;\n    } else if (FLAGS_local_solver == \"direct-cholmod\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_cholmod;\n    } else if (FLAGS_local_solver == \"direct-umfpack\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_umfpack;\n    } else if (FLAGS_local_solver == \"direct-ginkgo\") {\n        settings.local_solver =\n            schwz::Settings::local_solver_settings::direct_solver_ginkgo;\n    }\n    settings.debug_print = FLAGS_debug;\n    MixedValueType dummy = 0.0;\n    int gsize = 0;\n    if (metadata.my_rank == 0) {\n        metadata.global_size = system_matrix.m();\n        std::cout << \" Running on the \" << FLAGS_executor << \" executor on \"\n                  << metadata.num_subdomains << \" ranks with \"\n                  << FLAGS_num_threads << \" threads\" << std::endl;\n        std::cout << \" MixedValueType: \" << typeid(dummy).name() << std::endl;\n        std::cout << \" Problem Size: \" << metadata.global_size\n                  << \" Number of non-zeros: \"\n                  << system_matrix.n_nonzero_elements() << std::endl;\n        gsize = metadata.global_size;\n    }\n    MPI_Bcast(&gsize, 1, MPI_INT, 0, MPI_COMM_WORLD);\n    metadata.global_size = gsize;\n    if (FLAGS_print_config) {\n        if (metadata.my_rank == 0) {\n            this->print_config();\n        }\n    }\n    using vec_vtype = gko::matrix::Dense<ValueType>;\n    std::shared_ptr<vec_vtype> solution_vector;\n    schwz::SolverRAS<ValueType, IndexType, MixedValueType> solver(settings,\n                                                                  metadata);\n    solver.initialize(system_matrix, system_rhs);\n    auto start_time = std::chrono::steady_clock::now();\n    solver.run(solution_vector);\n    auto elapsed_time = std::chrono::duration<double>(\n        std::chrono::steady_clock::now() - start_time);\n    if (metadata.my_rank == 0) {\n        std::cout << \"Time for solve only: \" << elapsed_time.count()\n                  << std::endl;\n    }\n    if (FLAGS_timings_file != \"null\") {\n        std::string rank_string = std::to_string(metadata.my_rank);\n        if (metadata.my_rank < 10) {\n            rank_string = \"0\" + std::to_string(metadata.my_rank);\n        }\n        std::string filename = FLAGS_timings_file + \"_\" + rank_string + \".csv\";\n        this->write_timings(metadata.time_struct, filename,\n                            settings.comm_settings.enable_onesided);\n    }\n    if (FLAGS_write_comm_data) {\n        std::string rank_string = std::to_string(metadata.my_rank);\n        if (metadata.my_rank < 10) {\n            rank_string = \"0\" + std::to_string(metadata.my_rank);\n        }\n        std::string filename_send = \"num_send_\" + rank_string + \".csv\";\n        std::string filename_recv = \"num_recv_\" + rank_string + \".csv\";\n        this->write_comm_data(metadata.num_subdomains, metadata.my_rank,\n                              metadata.comm_data_struct, filename_send,\n                              filename_recv);\n    }\n\n    if (metadata.my_rank == 0) {\n        std::copy(solution_vector->get_values(),\n                  solution_vector->get_values() + metadata.global_size,\n                  solution.begin());\n        constraints.distribute(solution);\n    }\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType,\n                        MixedValueType>::refine_grid()\n{\n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n    KellyErrorEstimator<dim>::estimate(\n        dof_handler, QGauss<dim - 1>(fe.degree + 1),\n        std::map<types::boundary_id, const Function<dim> *>(), solution,\n        estimated_error_per_cell);\n    GridRefinement::refine_and_coarsen_fixed_number(\n        triangulation, estimated_error_per_cell, 0.3, 0.03);\n    triangulation.execute_coarsening_and_refinement();\n}\n\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType, MixedValueType>::\n    output_results(const unsigned int cycle) const\n{\n    {\n        GridOut grid_out;\n        std::ofstream output(\"grid-\" + std::to_string(cycle) + \".gnuplot\");\n        GridOutFlags::Gnuplot gnuplot_flags(false, 5);\n        grid_out.set_flags(gnuplot_flags);\n        MappingQGeneric<dim> mapping(3);\n        grid_out.write_gnuplot(triangulation, output, &mapping);\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();\n        std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\");\n        data_out.write_vtu(output);\n    }\n}\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType, MixedValueType>::run()\n{\n    int num_cycles = FLAGS_num_refine_cycles;\n\n    for (unsigned int cycle = 0; cycle < num_cycles; ++cycle) {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0) {\n            GridGenerator::hyper_cube(triangulation);\n            triangulation.refine_global(FLAGS_init_refine_level);\n        } else\n            refine_grid();\n        std::cout << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells() << std::endl;\n        setup_system();\n        std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs()\n                  << std::endl;\n        assemble_system();\n        this->solve();\n        if (FLAGS_vis_sol) {\n            output_results(cycle);\n        }\n    }\n}\n\ntemplate <int dim, typename ValueType, typename IndexType,\n          typename MixedValueType>\nvoid BenchDealiiLaplace<dim, ValueType, IndexType, MixedValueType>::run(\n    MPI_Comm mpi_communicator)\n{\n    int num_cycles = FLAGS_num_refine_cycles;\n    int mpi_size, mpi_rank;\n    MPI_Comm_size(mpi_communicator, &mpi_size);\n    MPI_Comm_rank(mpi_communicator, &mpi_rank);\n\n    for (unsigned int cycle = 0; cycle < num_cycles; ++cycle) {\n        if (mpi_rank == 0) {\n            std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n            if (cycle == 0) {\n                GridGenerator::hyper_cube(triangulation);\n                triangulation.refine_global(FLAGS_init_refine_level);\n            } else\n                refine_grid();\n            std::cout << \"   Number of active cells:       \"\n                      << triangulation.n_active_cells() << std::endl;\n            setup_system();\n            std::cout << \"   Number of degrees of freedom: \"\n                      << dof_handler.n_dofs() << std::endl;\n            assemble_system();\n        }\n        this->solve(MPI_COMM_WORLD);\n        if (mpi_rank == 0) {\n            if (FLAGS_vis_sol) {\n                output_results(cycle);\n            }\n        }\n    }\n}\n\n\nint main(int argc, char **argv)\n{\n    try {\n        initialize_argument_parsing(&argc, &argv);\n        BenchDealiiLaplace<3, double, int, float> laplace_problem;\n        if (FLAGS_num_threads > 1) {\n            int req_thread_support = MPI_THREAD_MULTIPLE;\n            int prov_thread_support = MPI_THREAD_MULTIPLE;\n\n            MPI_Init_thread(&argc, &argv, req_thread_support,\n                            &prov_thread_support);\n            if (prov_thread_support != req_thread_support) {\n                std::cout << \"Required thread support is \" << req_thread_support\n                          << \" but provided thread support is only \"\n                          << prov_thread_support << std::endl;\n            }\n        } else {\n            MPI_Init(&argc, &argv);\n        }\n\n        int rank = 0;\n        MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n        if (FLAGS_dealii_orig) {\n            if (rank == 0) {\n                auto start_time = std::chrono::steady_clock::now();\n                laplace_problem.run();\n                auto elapsed_time = std::chrono::duration<double>(\n                    std::chrono::steady_clock::now() - start_time);\n                std::cout << \"Total Time for setup+solve: \"\n                          << elapsed_time.count() << std::endl;\n            }\n        } else {\n            auto start_time = std::chrono::steady_clock::now();\n            laplace_problem.run(MPI_COMM_WORLD);\n            auto elapsed_time = std::chrono::duration<double>(\n                std::chrono::steady_clock::now() - start_time);\n            if (rank == 0) {\n                std::cout << \"Total Time for setup+solve: \"\n                          << elapsed_time.count() << std::endl;\n            }\n        }\n        MPI_Finalize();\n    } catch (std::exception &exc) {\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    } catch (...) {\n        std::cerr << std::endl\n                  << std::endl\n                  << \"----------------------------------------------------\"\n                  << std::endl;\n        std::cerr << \"Unknown exception!\" << std::endl\n                  << \"Aborting!\" << std::endl\n                  << \"----------------------------------------------------\"\n                  << std::endl;\n        return 1;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "dd3feddfa80b46e93eda996596bfb9ffa156472e", "size": 20963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarking/dealii_ex_6.cpp", "max_stars_repo_name": "soumyadipghosh/schwarz-lib", "max_stars_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-23T07:37:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-19T09:39:01.000Z", "max_issues_repo_path": "benchmarking/dealii_ex_6.cpp", "max_issues_repo_name": "soumyadipghosh/schwarz-lib", "max_issues_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2020-03-23T14:20:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T07:43:27.000Z", "max_forks_repo_path": "benchmarking/dealii_ex_6.cpp", "max_forks_repo_name": "soumyadipghosh/schwarz-lib", "max_forks_repo_head_hexsha": "7a9a97dd0bde49fa0dd4bd386c6f185bef128fe0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-23T15:38:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T19:50:50.000Z", "avg_line_length": 40.236084453, "max_line_length": 80, "alphanum_fraction": 0.6260077279, "num_tokens": 4645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5693857827460178}}
{"text": "//  Copyright (c) 2017 Zahra Khatami \n//\n// Train your data, then record them in an output file stated in \"retrieving_weights_multi_classes_into_text_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\n#define MAX_FLOAT (std::numeric_limits<float>::max())\n#define MIN_FLOAT (std::numeric_limits<float>::min())\n\nclass multinomial_logistic_regression_model {\n\n\tstd::size_t number_of_experiments;\n\tstd::size_t number_of_features;\n\tstd::size_t number_of_classes;\n\tfloat threshold; \t\t\t\t\t\t\t//the convergence for estimating the final weights\n\tfloat eta;\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 weightsm; \t\t\t\t\t\t\t//weights of our learning network : F * K\n\tMatrixXf weightsm_trans;\t\t\t\t\t//transpose of weights : K * F\n\tMatrixXf new_weightsm;\t\t\t\t\t\t//updated weights after each step : F * K\n\tint* real_output;\t\t\t\t\t\t\t//real output of each experimental results\n\tMatrixXf targets_multi_class;\t\t\t\t//binary real output of each experimental results : N * K\n\tMatrixXf outputsm;\t\t\t\t\t\t\t//outputs of the training data : N * K\n\tMatrixXf gradient;\t\t\t\t\t\t\t//gradient of E : F * K\n\tMatrixXf sum_w_experimental_results;\t\t//used for computing output : N \n\tint* predicted_output_multi_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\n\t\n\n\tvoid normalizing_weights_multi_class();\n\tvoid convert_target_to_binary(int* target_src, MatrixXf& targets_dst);\t\n\tint eye_kj(std::size_t k, std::size_t j);\n\tvoid computing_all_output();\n\tvoid computing_all_gradient();\n\tvoid learning_weights_multi_classes();\n\tvoid new_values_for_weightsm();\n\tfloat computing_new_least_squared_err_multi_class();\t\n\tvoid updating_values_of_weights_multi_class();\n\tvoid printing_weights_multi_class();\n\tvoid estimating_output_multiclass();\n\tvoid printing_computed_values(std::size_t row, std::size_t col, MatrixXf& mat);\n\t\npublic:\n\tmultinomial_logistic_regression_model(std::size_t number_of_expr, std::size_t number_of_ftrs, std::size_t number_of_cls, \n\t\t\t\t\t\t\t\t\t\t\tfloat th, float** expr_results, int* target_expr, float** exec_time) {\n\t\tnumber_of_experiments = number_of_expr;\n\t\tnumber_of_features = number_of_ftrs;\n\t\tnumber_of_classes = number_of_cls;\n\t\tthreshold = th;\n\t\teta = 0.01;\n\t\n\t\tsum_w_experimental_results = MatrixXf::Random(number_of_experiments, 1);\t\t\n\t\tweightsm = MatrixXf::Random(number_of_features, number_of_classes);\n\t\tweightsm_trans = MatrixXf::Random(number_of_classes, number_of_features);\t\t\t\t\t\t\t\n\t\tnew_weightsm = MatrixXf::Random(number_of_features, number_of_classes);\n\t\tgradient = MatrixXf::Random(number_of_features, number_of_classes);\n\t\texperimental_results = MatrixXf(number_of_experiments, number_of_features);\n\t\texperimental_results_trans = MatrixXf::Random(number_of_features, number_of_experiments);\n\t\texecution_times = MatrixXf::Random(number_of_experiments, number_of_classes);\n\t\ttargets_multi_class = MatrixXf::Random(number_of_experiments, number_of_classes);\n\t\toutputsm = MatrixXf::Random(number_of_experiments, number_of_classes);\n\t\tpredicted_output_multi_class = new int[number_of_experiments];\n\t\treal_output = 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 f = 0; f < number_of_features; f++) {\n\t\t\tfor(std::size_t k = 0; k < number_of_classes; k++) {\n\t\t\t\tweightsm(f, k) = 0.1;\n\t\t\t}\n\t\t}\n\n\t\tfor(std::size_t i = 0; i < number_of_experiments; i++) {\n\n\t\t\t//initializing experimental_results\n\t\t\tfor(std::size_t f = 0; f < number_of_features; f++) {\n\t\t\t\texperimental_results(i, f) = expr_results[i][f];\n\t\t\t}\n\n\t\t\t//initializing execution_times\n\t\t\tfor(std::size_t c = 0; c < number_of_classes; c++) {\n\t\t\t\texecution_times(i, c) = exec_time[i][c];\n\t\t\t}\n\n\t\t\t//initializing real outputs\n\t\t\treal_output[i] = target_expr[i];\n\t\t}\t\n\t\t\n\t\t//initializing targets_multi_class\n\t\tconvert_target_to_binary(target_expr, targets_multi_class);\n\t\toutputsm = targets_multi_class;\n\t}\n\n\tvoid learning_multi_classes();\n\tvoid retrieving_weights_multi_classes_into_text_file();\n\tvoid printing_predicted_output_multi_class();\n\tvoid finalizing_step();\n};\n\n//it prints computed values : for testing\nvoid multinomial_logistic_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 multinomial_logistic_regression_model::convert_target_to_binary(int* target_src, MatrixXf& targets_multi_class) {\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tfor(std::size_t k = 0; k < number_of_classes; k++) {\n\t\t\tif(target_src[n] == k) {\n\t\t\t\ttargets_multi_class(n, k) = 1.0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttargets_multi_class(n, k) = 0.0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n//Ikj\nint multinomial_logistic_regression_model::eye_kj(std::size_t k, std::size_t j) {\n\tif(k == j) {\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\n//computing outputs\nvoid multinomial_logistic_regression_model::computing_all_output() {\n\tweightsm_trans = weightsm.transpose();\n\t//w^T * Q\n\tMatrixXf W_TQ_trans = MatrixXf::Random(number_of_classes, number_of_experiments);\n\tW_TQ_trans = weightsm_trans * experimental_results_trans;\n\tMatrixXf W_TQ = MatrixXf::Random(number_of_experiments, number_of_classes);\n\tW_TQ = W_TQ_trans.transpose();\n\n\t//sigma(exp(wQ))\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tsum_w_experimental_results(n, 0) = 0.0;\n\t\tfor(std::size_t k = 0; k < number_of_classes; k++) {\n\t\t\tsum_w_experimental_results(n, 0) += exp(W_TQ(n, k));\n\t\t}\n\t}\n\n\t//ynk\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tfor(std::size_t k = 0; k < number_of_classes; k++) {\t\t\n\t\t\toutputsm(n, k) = float(exp(W_TQ(n, k))/sum_w_experimental_results(n, 0)); \n\t\t}\n\t}\n}\n\n//computing gradient \nvoid multinomial_logistic_regression_model::computing_all_gradient(){\n\t//initializing\n\tgradient *= 0.0;\n\tfor(std::size_t k = 0; k < number_of_classes; k++) {\n\t\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\t\tgradient.col(k) += (outputsm(n, k) - targets_multi_class(n, k)) * experimental_results_trans.col(n);\n\t\t}\n\t}\n}\n\nvoid multinomial_logistic_regression_model::new_values_for_weightsm() {\t\n\tnew_weightsm = weightsm\t- eta * gradient;\n}\n\n//computing leas squares err\nfloat multinomial_logistic_regression_model::computing_new_least_squared_err_multi_class() {\t\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_multi_class[n]) - execution_times(n, real_output[n])) > 0.2) {\n\t\t\tnum_err++;\n\t\t}\t\t\n\t}\n\tfloat prec = float(num_err) / number_of_experiments;\n\treturn prec;\n}\n\n//updating weights\nvoid multinomial_logistic_regression_model::updating_values_of_weights_multi_class() {\t\n\tweightsm = new_weightsm;\n}\n\nvoid multinomial_logistic_regression_model::printing_weights_multi_class() {\n\tprinting_computed_values(number_of_features, number_of_classes, weightsm);\n\tstd::cout<<\"\\n --------------------\\n\";\n}\n\n//estimating class of each experimental results based on the computed weights\nvoid multinomial_logistic_regression_model::estimating_output_multiclass() {\t\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\n\t\tfloat prob = MIN_FLOAT;\n\t\tfor(std::size_t k = 0; k < number_of_classes; k++) {\n\t\t\tif(prob < outputsm(n, k)) {\n\t\t\t\tpredicted_output_multi_class[n] = k;\n\t\t\t\tprob = outputsm(n, k);\n\t\t\t}\n\t\t}\n\t}\n}\n\n//updating weights till error meets the defined threshold\nvoid multinomial_logistic_regression_model::learning_weights_multi_classes() {\n\tfloat least_squared_err = MAX_FLOAT;\n\tstd::size_t itr = 1;\n\n\t//for some test, only for statring updating weights:\n\tcomputing_all_gradient();\t\t\t\t\n\tnew_values_for_weightsm();\t\t\t\t\n\tupdating_values_of_weights_multi_class();\n\tcomputing_all_output();\n\testimating_output_multiclass();\n\n\twhile(threshold < least_squared_err) {\n\t\tcomputing_all_gradient();\t\t\t\t\n\t\tnew_values_for_weightsm();\t\t\t\t\n\t\tupdating_values_of_weights_multi_class();\n\t\tcomputing_all_output();\n\t\testimating_output_multiclass();\n\t\tleast_squared_err = computing_new_least_squared_err_multi_class();\n\t\tstd::cout<<\"(\"<<itr<<\")\"<<\"Least_squared_err =\\t\" << least_squared_err<<std::endl;\t\t\n\t\tprinting_weights_multi_class();\t\t\n\t\titr++;\n\t}\n\tstd::cout<<\"(\"<<itr<<\") => \"<<\"Least_squared_err =\\t\" << least_squared_err<<std::endl;\n}\n\nvoid multinomial_logistic_regression_model::normalizing_weights_multi_class() {\t\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 = 0; j < number_of_features; j++) {\n\t\t\taverages[j] += experimental_results(i, j);\n\t\t\taverages_2[j] += (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 = 0; f < number_of_features; f++) {\n\t\t\texperimental_results(n, f) = float((experimental_results(n, f) - averages[f])/var[f]);\n\t\t}\n\t}\n}\n\nvoid multinomial_logistic_regression_model::learning_multi_classes() {\n\tnormalizing_weights_multi_class();\n\texperimental_results_trans = experimental_results.transpose();\n\tlearning_weights_multi_classes();\n}\n\n//retrieving information into the external file, which is going to be used at runtime\nvoid multinomial_logistic_regression_model::retrieving_weights_multi_classes_into_text_file() {\t\n  \n  // for learning model on chunk_size training data\n\tstd::ofstream outputFile(\"inputs/data_chunk.dat\");\n  \n  // for learning model on prefetching distance training data:\n  //std::ofstream outputFile(\"inputs/data_prefetch.dat\");\n\n\t//normalization parameters (variance and average) in the first line\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 c = 0; c < number_of_classes; c++) {\n\t\tfor(std::size_t f = 0; f < number_of_features - 1; f++) {\n\t\t\toutputFile << weightsm(f, c) << \" \";\n\t\t}\n\t\toutputFile << weightsm(number_of_features - 1, c);\n\t\tif(c != number_of_classes - 1) {\n\t\t\toutputFile << std::endl;\n\t\t}\n\t}\n}\n\nvoid multinomial_logistic_regression_model::printing_predicted_output_multi_class(){\n\tstd::size_t num_err = 0;\n\tfor(std::size_t n = 0; n < number_of_experiments; n++) {\t\t\n\t\tif(abs(execution_times(n, predicted_output_multi_class[n]) - execution_times(n, real_output[n])) > 0.2){\n\t\t\tnum_err++;\n\t\t\tstd::cout << \"\\n [\" << n << \"] =\\t\" << predicted_output_multi_class[n] << \"\\t\" << real_output[n];\n\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 multinomial_logistic_regression_model::finalizing_step() {\n\n\t//releasing memory\n\tdelete[] averages;\n\tdelete[] averages_2;\n\tdelete[] var;\n\tdelete[] predicted_output_multi_class;\n\tdelete[] real_output;\n}", "meta": {"hexsha": "6900610302bca21f5d3e96303af41456fc626524", "size": 11981, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "logisticRegressionModel/algorithms/models/multinomial_regression_model_gradient_descent.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/multinomial_regression_model_gradient_descent.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/multinomial_regression_model_gradient_descent.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": 35.0321637427, "max_line_length": 122, "alphanum_fraction": 0.7198898256, "num_tokens": 3290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5693707494155166}}
{"text": "/**\n * @file numerical_functions.cpp\n */\n\n#include \"numerical_functions.h\"\n#include <Eigen/Dense>\n#include <algorithm>\n#include <numeric>\n#include <limits>\n\nusing namespace himan;\nusing namespace numerical_functions;\nusing namespace Eigen;\n\ntemplate <typename T>\nmatrix<T> numerical_functions::Filter2D(const matrix<T>& A, const matrix<T>& B, bool useCuda)\n{\n#ifdef HAVE_CUDA\n\tif (useCuda)\n\t{\n\t\treturn Filter2DGPU(A, B);\n\t}\n#endif\n\treturn Reduce2D<T>(A, B,\n\t                   [](T& val1, T& val2, const T& a, const T& b) {\n\t\t                   if (IsValid(a * b))\n\t\t                   {\n\t\t\t                   val1 += a * b;\n\t\t\t                   val2 += b;\n\t\t                   }\n\t                   },\n\t                   [](const T& val1, const T& val2) { return val2 == T(0) ? MissingValue<T>() : val1 / val2; },\n\t                   T(0), T(0));\n}\n\ntemplate matrix<double> numerical_functions::Filter2D(const matrix<double>&, const matrix<double>& B, bool);\ntemplate matrix<float> numerical_functions::Filter2D(const matrix<float>&, const matrix<float>& B, bool);\n\ntemplate <typename T>\nmatrix<T> numerical_functions::Max2D(const matrix<T>& A, const matrix<T>& B, bool useCuda)\n{\n#ifdef HAVE_CUDA\n\tif (useCuda)\n\t{\n\t\treturn Max2DGPU(A, B);\n\t}\n#endif\n\treturn Reduce2D<T>(A, B,\n\t                   [](T& val1, T& val2, const T& a, const T& b) {\n\t\t                   if (IsValid(a * b))\n\t\t\t                   val1 = !(a * b <= val1) ? a : val1;\n\t                   },\n\t                   [](const T& val1, const T& val2) { return val1; }, MissingValue<T>(), T(0));\n}\n\ntemplate matrix<double> numerical_functions::Max2D(const matrix<double>&, const matrix<double>& B, bool);\ntemplate matrix<float> numerical_functions::Max2D(const matrix<float>&, const matrix<float>& B, bool);\n\ntemplate <typename T>\nmatrix<T> numerical_functions::Min2D(const matrix<T>& A, const matrix<T>& B, bool useCuda)\n{\n#ifdef HAVE_CUDA\n\tif (useCuda)\n\t{\n\t\treturn Min2DGPU(A, B);\n\t}\n#endif\n\treturn Reduce2D<T>(A, B,\n\t                   [](T& val1, T& val2, const T& a, const T& b) {\n\t\t                   if (IsValid(a * b))\n\t\t\t                   val1 = !(a * b >= val1) ? a : val1;\n\t                   },\n\t                   [](const T& val1, const T& val2) { return val1; }, MissingValue<T>(), T(0));\n}\n\ntemplate matrix<double> numerical_functions::Min2D(const matrix<double>&, const matrix<double>& B, bool);\ntemplate matrix<float> numerical_functions::Min2D(const matrix<float>&, const matrix<float>& B, bool);\n\ntemplate <typename T>\nmatrix<size_t> numerical_functions::IndexMax2D(const matrix<T>& A, const matrix<T>& B)\n{\n\treturn FindIndex2D(A, B,\n\t\t\t[](T& current_max, const T& a, const T& b) {\n\t\t\t\treturn (a > current_max) & IsValid(b);\n\t\t\t}, std::numeric_limits<T>::lowest());\n}\n\ntemplate matrix<size_t> numerical_functions::IndexMax2D(const matrix<float>& A, const matrix<float>& B);\ntemplate matrix<size_t> numerical_functions::IndexMax2D(const matrix<double>& A, const matrix<double>& B);\n\ntemplate <typename T>\nstd::pair<std::vector<T>, std::vector<T>> numerical_functions::LegGauss(size_t N, bool computeWeights)\n{\n\t// Set up Eigenvalue problem\n\t//-------------------------------------------------------------------------------------------------------\n\tMatrix<T, Dynamic, Dynamic> J(N, N);\n\n\tDiagonal<Matrix<T, Dynamic, Dynamic>, 0> Jdiag0(J);\n\tDiagonal<Matrix<T, Dynamic, Dynamic>, 1> Jdiag1(J);\n\n\tfor (size_t n = 0; n < N; ++n)\n\t{\n\t\tJdiag0[n] = 0.0;\n\t}\n\n\tfor (size_t n = 0; n < N - 1; ++n)\n\t{\n\t\tJdiag1[n] = static_cast<T>(T(n + 1) * 1.0 / std::sqrt(2 * (n) + 1) * 1.0 / std::sqrt(2 * (n + 1) + 1));\n\t}\n\t//-------------------------------------------------------------------------------------------------------\n\n\t// Solve Eigenvalue problem\n\t//-------------------------------------------------------------------------------------------------------\n\tSelfAdjointEigenSolver<Matrix<T, Dynamic, Dynamic>> es(N);\n\t//-------------------------------------------------------------------------------------------------------\n\n\tes.computeFromTridiagonal(Jdiag0, Jdiag1, computeWeights ? ComputeEigenvectors : EigenvaluesOnly);\n\n\t// Extract Quadrature points and weights from eigenvalues and eigenvectors\n\t//-------------------------------------------------------------------------------------------------------\n\tstd::vector<T> r(N);\n\tstd::vector<T> w;\n\n\tMap<Matrix<T, Dynamic, Dynamic>> R(r.data(), N, 1);\n\tR = es.eigenvalues().real();\n\n\tif (computeWeights)\n\t{\n\t\tw.resize(N);\n\t\tMap<Array<T, Dynamic, Dynamic>> W(w.data(), 1, N);\n\n\t\tW = es.eigenvectors().real().row(0);\n\t\tW = W * W * 2;\n\t}\n\t//-------------------------------------------------------------------------------------------------------\n\n\treturn std::make_pair(r, w);\n}\ntemplate std::pair<std::vector<float>, std::vector<float>> numerical_functions::LegGauss(size_t, bool);\ntemplate std::pair<std::vector<double>, std::vector<double>> numerical_functions::LegGauss(size_t, bool);\n\ntemplate <typename T>\nT numerical_functions::Mean(const std::vector<T>& data)\n{\n\tif (data.size() == 0)\n\t{\n\t\treturn himan::MissingValue<T>();\n\t}\n\n\treturn std::accumulate(data.begin(), data.end(), 0.0f) / static_cast<T>(data.size());\n}\n\ntemplate double numerical_functions::Mean(const std::vector<double>&);\ntemplate float numerical_functions::Mean(const std::vector<float>&);\n\ntemplate <typename T>\nT numerical_functions::Variance(const std::vector<T>& data)\n{\n\tif (data.size() == 0)\n\t{\n\t\treturn himan::MissingValue<T>();\n\t}\n\n\tconst auto mean = Mean(data);\n\n\tT sum = 0.0f;\n\n\tfor (const auto& x : data)\n\t{\n\t\tconst auto t = x - mean;\n\t\tsum += t * t;\n\t}\n\n\treturn sum / static_cast<T>(data.size());\n}\n\ntemplate double numerical_functions::Variance(const std::vector<double>&);\ntemplate float numerical_functions::Variance(const std::vector<float>&);\n", "meta": {"hexsha": "6b9aee1f19c664bc82b4ec0d28116968dc6265a1", "size": 5758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-lib/source/numerical_functions.cpp", "max_stars_repo_name": "fox91/himan", "max_stars_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T18:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:12:49.000Z", "max_issues_repo_path": "himan-lib/source/numerical_functions.cpp", "max_issues_repo_name": "fox91/himan", "max_issues_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-07-05T02:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T09:36:51.000Z", "max_forks_repo_path": "himan-lib/source/numerical_functions.cpp", "max_forks_repo_name": "fox91/himan", "max_forks_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T06:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:17:09.000Z", "avg_line_length": 32.1675977654, "max_line_length": 112, "alphanum_fraction": 0.5547064953, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5693344506721183}}
{"text": "/**\n * UnscentedKalmanFilterX.hpp\n * @author koide\n * 16/02/01\n **/\n#ifndef KKL_UNSCENTED_KALMAN_FILTER_X_HPP\n#define KKL_UNSCENTED_KALMAN_FILTER_X_HPP\n\n#include <random>\n#include <Eigen/Dense>\n\nnamespace kkl {\n  namespace alg {\n\n/**\n * @brief Unscented Kalman Filter class\n * @param T        scaler type\n * @param System   system class to be estimated\n */\ntemplate<typename T, class System>\nclass UnscentedKalmanFilterX {\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXt;\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXt;\npublic:\n  /**\n   * @brief constructor\n   * @param system               system to be estimated\n   * @param state_dim            state vector dimension\n   * @param input_dim            input vector dimension\n   * @param measurement_dim      measurement vector dimension\n   * @param process_noise        process noise covariance (state_dim x state_dim)\n   * @param measurement_noise    measurement noise covariance (measurement_dim x measuremend_dim)\n   * @param mean                 initial mean\n   * @param cov                  initial covariance\n   */\n  UnscentedKalmanFilterX(const System& system, int state_dim, int input_dim, int measurement_dim, const MatrixXt& process_noise, const MatrixXt& measurement_noise, const VectorXt& mean, const MatrixXt& cov)\n    : state_dim(state_dim),\n    input_dim(input_dim),\n    measurement_dim(measurement_dim),\n    N(state_dim),\n    M(input_dim),\n    K(measurement_dim),\n    S(2 * state_dim + 1),\n    mean(mean),\n    cov(cov),\n    system(system),\n    process_noise(process_noise),\n    measurement_noise(measurement_noise),\n    lambda(1),\n    normal_dist(0.0, 1.0)\n  {\n    weights.resize(S, 1);\n    sigma_points.resize(S, N);\n    ext_weights.resize(2 * (N + K) + 1, 1);\n    ext_sigma_points.resize(2 * (N + K) + 1, N + K);\n    expected_measurements.resize(2 * (N + K) + 1, K);\n\n    // initialize weights for unscented filter\n    weights[0] = lambda / (N + lambda);\n    for (int i = 1; i < 2 * N + 1; i++) {\n      weights[i] = 1 / (2 * (N + lambda));\n    }\n\n    // weights for extended state space which includes error variances\n    ext_weights[0] = lambda / (N + K + lambda);\n    for (int i = 1; i < 2 * (N + K) + 1; i++) {\n      ext_weights[i] = 1 / (2 * (N + K + lambda));\n    }\n  }\n\n  /**\n   * @brief predict\n   * @param control  input vector\n   */\n  void predict(const VectorXt& control) {\n    // calculate sigma points\n    ensurePositiveFinite(cov);\n    computeSigmaPoints(mean, cov, sigma_points);\n    for (int i = 0; i < S; i++) {\n      sigma_points.row(i) = system.f(sigma_points.row(i), control);\n    }\n\n    const auto& R = process_noise;\n\n    // unscented transform\n    VectorXt mean_pred(mean.size());\n    MatrixXt cov_pred(cov.rows(), cov.cols());\n\n    mean_pred.setZero();\n    cov_pred.setZero();\n    for (int i = 0; i < S; i++) {\n      mean_pred += weights[i] * sigma_points.row(i);\n    }\n    for (int i = 0; i < S; i++) {\n      VectorXt diff = sigma_points.row(i).transpose() - mean;\n      cov_pred += weights[i] * diff * diff.transpose();\n    }\n    cov_pred += R;\n\n    mean = mean_pred;\n    cov = cov_pred;\n  }\n\n  /**\n   * @brief correct\n   * @param measurement  measurement vector\n   */\n  void correct(const VectorXt& measurement) {\n    // create extended state space which includes error variances\n    VectorXt ext_mean_pred = VectorXt::Zero(N + K, 1);\n    MatrixXt ext_cov_pred = MatrixXt::Zero(N + K, N + K);\n    ext_mean_pred.topLeftCorner(N, 1) = VectorXt(mean);\n    ext_cov_pred.topLeftCorner(N, N) = MatrixXt(cov);\n    ext_cov_pred.bottomRightCorner(K, K) = measurement_noise;\n\n    ensurePositiveFinite(ext_cov_pred);\n    computeSigmaPoints(ext_mean_pred, ext_cov_pred, ext_sigma_points);\n\n    // unscented transform\n    expected_measurements.setZero();\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      expected_measurements.row(i) = system.h(ext_sigma_points.row(i).transpose().topLeftCorner(N, 1));\n      expected_measurements.row(i) += VectorXt(ext_sigma_points.row(i).transpose().bottomRightCorner(K, 1));\n    }\n\n    VectorXt expected_measurement_mean = VectorXt::Zero(K);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      expected_measurement_mean += ext_weights[i] * expected_measurements.row(i);\n    }\n    MatrixXt expected_measurement_cov = MatrixXt::Zero(K, K);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      VectorXt diff = expected_measurements.row(i).transpose() - expected_measurement_mean;\n      expected_measurement_cov += ext_weights[i] * diff * diff.transpose();\n    }\n\n    // calculated transformed covariance\n    MatrixXt sigma = MatrixXt::Zero(N + K, K);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      auto diffA = (ext_sigma_points.row(i).transpose() - ext_mean_pred);\n      auto diffB = (expected_measurements.row(i).transpose() - expected_measurement_mean);\n      sigma += ext_weights[i] * (diffA * diffB.transpose());\n    }\n\n    kalman_gain = sigma * expected_measurement_cov.inverse();\n    const auto& K = kalman_gain;\n\n    VectorXt ext_mean = ext_mean_pred + K * (measurement - expected_measurement_mean);\n    MatrixXt ext_cov = ext_cov_pred - K * expected_measurement_cov * K.transpose();\n\n    mean = ext_mean.topLeftCorner(N, 1);\n    cov = ext_cov.topLeftCorner(N, N);\n  }\n\n  /*\t\t\tgetter\t\t\t*/\n  const VectorXt& getMean() const { return mean; }\n  const MatrixXt& getCov() const { return cov; }\n  const MatrixXt& getSigmaPoints() const { return sigma_points; }\n\n  System& getSystem() { return system; }\n  const System& getSystem() const { return system; }\n  const MatrixXt& getProcessNoiseCov() const { return process_noise; }\n  const MatrixXt& getMeasurementNoiseCov() const { return measurement_noise; }\n\n  const MatrixXt& getKalmanGain() const { return kalman_gain; }\n\n  /*\t\t\tsetter\t\t\t*/\n  UnscentedKalmanFilterX& setMean(const VectorXt& m) { mean = m;\t\t\treturn *this; }\n  UnscentedKalmanFilterX& setCov(const MatrixXt& s) { cov = s;\t\t\treturn *this; }\n\n  UnscentedKalmanFilterX& setProcessNoiseCov(const MatrixXt& p) { process_noise = p;\t\t\treturn *this; }\n  UnscentedKalmanFilterX& setMeasurementNoiseCov(const MatrixXt& m) { measurement_noise = m;\treturn *this; }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n  const int state_dim;\n  const int input_dim;\n  const int measurement_dim;\n\n  const int N;\n  const int M;\n  const int K;\n  const int S;\n\npublic:\n  VectorXt mean;\n  MatrixXt cov;\n\n  System system;\n  MatrixXt process_noise;\t\t//\n  MatrixXt measurement_noise;\t//\n\n  T lambda;\n  VectorXt weights;\n\n  MatrixXt sigma_points;\n\n  VectorXt ext_weights;\n  MatrixXt ext_sigma_points;\n  MatrixXt expected_measurements;\n\nprivate:\n  /**\n   * @brief compute sigma points\n   * @param mean          mean\n   * @param cov           covariance\n   * @param sigma_points  calculated sigma points\n   */\n  void computeSigmaPoints(const VectorXt& mean, const MatrixXt& cov, MatrixXt& sigma_points) {\n    const int n = mean.size();\n    assert(cov.rows() == n && cov.cols() == n);\n\n    Eigen::LLT<MatrixXt> llt;\n    llt.compute((n + lambda) * cov);\n    MatrixXt l = llt.matrixL();\n\n    sigma_points.row(0) = mean;\n    for (int i = 0; i < n; i++) {\n      sigma_points.row(1 + i * 2) = mean + l.col(i);\n      sigma_points.row(1 + i * 2 + 1) = mean - l.col(i);\n    }\n  }\n\n  /**\n   * @brief make covariance matrix positive finite\n   * @param cov  covariance matrix\n   */\n  void ensurePositiveFinite(MatrixXt& cov) {\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      if (D(i, i) < eps) {\n        D(i, i) = eps;\n      }\n    }\n\n    cov = V * D * V.inverse();\n  }\n\npublic:\n  MatrixXt kalman_gain;\n\n  std::mt19937 mt;\n  std::normal_distribution<T> normal_dist;\n};\n\n  }\n}\n\n\n#endif\n", "meta": {"hexsha": "6010cef6e3e6b7795f4582305b2e19e7fdb81ce8", "size": 7828, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/alg/unscented_kalman_filter.hpp", "max_stars_repo_name": "walterchenchn/hdl_localization", "max_stars_repo_head_hexsha": "d7f3c9ab0908db4f2bac0322d9597d610d26d79a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-25T08:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:03:12.000Z", "max_issues_repo_path": "include/kkl/alg/unscented_kalman_filter.hpp", "max_issues_repo_name": "walterchenchn/hdl_localization", "max_issues_repo_head_hexsha": "d7f3c9ab0908db4f2bac0322d9597d610d26d79a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T15:09:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T15:09:18.000Z", "max_forks_repo_path": "include/kkl/alg/unscented_kalman_filter.hpp", "max_forks_repo_name": "walterchenchn/hdl_localization", "max_forks_repo_head_hexsha": "d7f3c9ab0908db4f2bac0322d9597d610d26d79a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-24T03:24:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T07:48:35.000Z", "avg_line_length": 30.6980392157, "max_line_length": 206, "alphanum_fraction": 0.6524016352, "num_tokens": 2194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5693344490296725}}
{"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\nusing namespace std;\nusing namespace NTL;\n\n\n\n//==============================================================================\n// Takes in input a random value and samples from distribution D_{\\sigma_2}^+,   \n// Samples an element in Z+ with probability proportionnal to 2^{-x^2}       \n//==============================================================================\nunsigned int Sample0(unsigned long alea)\n{\n    if((alea&1UL)==0UL)\n    {\n        return 0;\n    }\n    unsigned int i;\n    unsigned int k = 1;\n    unsigned long mask=0;\n    unsigned long aux;\n    for(i=1; i<1000;)\n    {\n        aux = (alea&mask);\n        alea = (alea>>k);     \n        if(aux)\n        {\n            return Sample0(alea);\n        }\n        else\n        {\n            if((alea&1UL)==0UL)\n            {\n                return i;\n            }\n        }\n        i++;\n        k += 2;\n        mask = (mask<<2)|6UL;\n    }\n    cout << \"ERROR\" << endl;\n    return 999999;\n}\n\n\n\n//==============================================================================\n// Samples from distribution D_{k\\sigma_2}^+, ie \n// Samples an element in Z+ with probability proportionnal to 2^{-(x/k)^2} \n//==============================================================================\nunsigned int Sample1(const unsigned int k)\n{\n    unsigned int x, y, z;\n    unsigned long alea = rand();\n\n    x = Sample0(alea);\n    y = rand()%k;\n    z = k*x + y;\n    RR_t w = y*( (z<<1) - y );\n    RR_t borne =  LDRMX / exp( w*log_2/(k*k) );\n    alea = rand();\n    if(alea>borne)\n    {\n        return Sample1(k);\n    }\n    else\n    {\n        return z;\n    }\n    cout << \"ERROR\" << endl;\n    return 999999;\n}\n\n\n\n\n//==============================================================================\n// Samples from distribution D_{k\\sigma_2}, ie                \n// Samples an element in Z with probability proportionnal to 2^{-(x/k)^2} \n//==============================================================================\nsigned int Sample2(const unsigned int k)\n{\n    signed int signe;\n    signed int x;\n    unsigned long alea = rand();\n    while(1)\n    {\n        x = Sample1(k);\n        if( (x!=0) || ((alea&1)==1) )\n        {\n            alea >>= 1;\n            signe = 1 - 2*(alea&1);\n            x *= signe;\n            return x;\n        }\n        alea >>= 1;\n    }\n}\n\n\n//==============================================================================\n// Samples from distribution D_{sigma}, ie                                       \n// Samples an element in Z with probability proportionnal to e^{-x^2/2*(sigma^2)}\n//==============================================================================\nsigned int Sample3(const RR_t sigma128)\n{\n    signed int x;\n    double alea, borne;\n\n    const RR_t sigma = sigma128;\n    const unsigned long k = ( (unsigned long) ceil( (RR_t) sigma/sigma_1 ) );\n    while(1)\n\n    {\n        x = Sample2(k);\n        alea = ((RR_t)rand()) / LDRMX;\n        borne = exp( -x*x*( 1/(2*sigma*sigma) - 1/(2*k*k*sigma_1*sigma_1) )   );\n        assert(borne<=1);\n        if(alea<borne)\n        {\n            return x;\n        }\n    }\n}\n\n\n//==============================================================================\n// Samples from distribution D_{c,sigma}, ie                                              \n// Samples an element in Z with probability proportionnal to e^{-(c-x)^2/2*(sigma^2)}    \n//==============================================================================\nsigned int Sample4(RR_t c, RR_t sigma)\n{\n    RR_t alea, borne;\n    signed int x;\n    unsigned int coin;\n\n    const signed int intc = ( (signed int) floor(c) );\n    const RR_t fracc = c-intc;\n    coin = rand();\n    const RR_t denom = 1/(2*sigma*sigma);\n\n    while(1)\n    {\n        x = Sample3(sigma);\n        x += (coin&1);\n        if(abs(x)>8){cout << x << endl;}\n        coin >>= 1;\n        borne = exp(-(x-fracc)*(x-fracc)*denom)/ ( exp(-x*x*denom) + exp(-(x-1)*(x-1)*denom) );\n\n        assert(borne<1);\n        alea = ( (RR_t)rand() ) / LDRMX;\n        if(alea<borne)\n        {\n            return (x+intc);\n        }\n    }\n}\n", "meta": {"hexsha": "e5fab3bd58a4824c6b35e0dc3aedb42e86ae6f09", "size": 4283, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/Sampling.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": "Sampling.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/Sampling.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": 25.3431952663, "max_line_length": 95, "alphanum_fraction": 0.4069577399, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5693344468930791}}
{"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/** \\example sparse.cpp\n*\n*   This tutorial demonstrates the use of sparse matrices.\n*   The primary operation for sparse matrices in ViennaCL is the sparse matrix-vector product.\n*\n*   We start with including the respective headers:\n**/\n\n// system headers\n#include <iostream>\n\n// ublas headers\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#include <boost/numeric/ublas/io.hpp>\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n// ViennaCL includes\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\n// Additional helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n\n// Shortcut for writing 'ublas::' instead of 'boost::numeric::ublas::'\nusing namespace boost::numeric;\n\n/**\n*   We setup a sparse matrix in uBLAS and populate it with values.\n*   Then, the respective ViennaCL sparse matrix is created and initialized with data from the uBLAS matrix.\n*   After a direct manipulation of the ViennaCL matrix, matrix-vector products are computed with both matrices.\n**/\nint main()\n{\n  typedef float       ScalarType;\n\n  std::size_t size = 5;\n\n  /**\n  * Set up some ublas objects\n  **/\n  ublas::vector<ScalarType> rhs = ublas::scalar_vector<ScalarType>(size, ScalarType(size));\n  ublas::compressed_matrix<ScalarType> ublas_matrix(size, size);\n\n  ublas_matrix(0,0) =  2.0f; ublas_matrix(0,1) = -1.0f;\n  ublas_matrix(1,0) = -1.0f; ublas_matrix(1,1) =  2.0f; ublas_matrix(1,2) = -1.0f;\n  ublas_matrix(2,1) = -1.0f; ublas_matrix(2,2) =  2.0f; ublas_matrix(2,3) = -1.0f;\n  ublas_matrix(3,2) = -1.0f; ublas_matrix(3,3) =  2.0f; ublas_matrix(3,4) = -1.0f;\n  ublas_matrix(4,3) = -1.0f; ublas_matrix(4,4) =  2.0f;\n\n  std::cout << \"ublas matrix: \" << ublas_matrix << std::endl;\n\n  /**\n  * Set up some ViennaCL objects and initialize with data from uBLAS objects\n  **/\n  viennacl::vector<ScalarType> vcl_rhs(size);\n  viennacl::compressed_matrix<ScalarType> vcl_compressed_matrix(size, size);\n\n  viennacl::copy(rhs, vcl_rhs);\n  viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n\n  // just get the data directly from the GPU and print it:\n  ublas::compressed_matrix<ScalarType> temp(size, size);\n  viennacl::copy(vcl_compressed_matrix, temp);\n  std::cout << \"ViennaCL: \" << temp << std::endl;\n\n  // now modify GPU data directly:\n  std::cout << \"Modifying vcl_compressed_matrix a bit: \" << std::endl;\n  vcl_compressed_matrix(0, 0) =  3.0f;\n  vcl_compressed_matrix(2, 3) = -3.0f;\n  vcl_compressed_matrix(4, 2) = -3.0f;  //this is a new nonzero entry\n  vcl_compressed_matrix(4, 3) = -3.0f;\n\n  // and print it again:\n  viennacl::copy(vcl_compressed_matrix, temp);\n  std::cout << \"ViennaCL matrix copied to uBLAS matrix: \" << temp << std::endl;\n\n  /**\n  *  Compute matrix-vector products and output the results (should match):\n  **/\n  std::cout << \"ublas: \" << ublas::prod(temp, rhs) << std::endl;\n  std::cout << \"ViennaCL: \" << viennacl::linalg::prod(vcl_compressed_matrix, vcl_rhs) << std::endl;\n\n  /**\n  *  That's it. Print a success message and exit.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "cde759aedf580b6135b9e22697f438915ae691ff", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/sparse.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/sparse.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/sparse.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.264957265, "max_line_length": 111, "alphanum_fraction": 0.6478429472, "num_tokens": 1148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.5692468432445973}}
{"text": "#pragma once\n\n#include <array>\n#include <unordered_map>\n#include <cmath>\n#include <Eigen/Dense>\n\n#include \"rfobject.hpp\"\n#include \"mmap.hpp\"\n\nnamespace lamon\n{\n    template<typename _ArrayTy>\n    auto gelu(_ArrayTy&& x) -> decltype(0.f * x * (0.f + (0.f * (x + 0.f * x * x * x)).tanh()))\n    {\n        const float c1 = std::sqrt(2 / 3.14159265), c2 = 0.044715;\n        return 0.5f * x * (1.f + (c1 * (x + c2 * x * x * x)).tanh());\n    }\n\n    template<typename _ArrayTy>\n    auto sigmoid(_ArrayTy&& x) -> decltype(((-x).exp() + 1).inverse())\n    {\n        return ((-x).exp() + 1).inverse();\n    }\n\n    template<typename _ArrayTy>\n    auto logsoftmax(_ArrayTy&& x) -> decltype(x - 0.f)\n    {\n        auto max = x.maxCoeff();\n        max += std::log((x - max).exp().sum());\n        return x - max;\n    }\n\n    struct EmbeddingLookup\n    {\n        ConstMatrix<float> embs;\n        EmbeddingLookup(const utils::Object& o)\n            : embs{ o.template to_matrix<float>() }\n        {\n        }\n\n        EmbeddingLookup(const ConstMatrix<float>& o)\n            : embs{ o }\n        {\n        }\n\n        size_t get_embedding_size() const { return embs.rows(); }\n        size_t get_vocab_size() const { return embs.cols(); }\n\n        auto operator[](size_t idx) const -> decltype(embs.col(idx))\n        {\n            return embs.col(idx);\n        }\n    };\n\n    struct LayerNorm\n    {\n        ConstVector<float> beta;\n        ConstVector<float> gamma;\n\n        LayerNorm(const utils::ObjectCollection& objs, const std::string& keys)\n            : beta{ objs[keys + \"/beta:0\"].template to_vector<float>() },\n            gamma{ objs[keys + \"/gamma:0\"].template to_vector<float>() }\n        {\n        }\n\n        template<typename _DestTy>\n        void apply_inplace(_DestTy&& dest) const\n        {\n            int cnt = dest.rows();\n            for (int i = 0; i < dest.cols(); ++i)\n            {\n                auto col = dest.col(i);\n                float avg = col.sum() / cnt;\n                float std = std::sqrt(((col.array() * col.array()).sum() / cnt - avg * avg) + 1e-12f);\n                col = (col.array() - avg) / std * gamma.array() + beta.array();\n            }\n        }\n\n        template<typename _DestTy, typename _SrcTy>\n        void apply(_DestTy&& dest, _SrcTy&& src) const\n        {\n            int cnt = src.rows();\n            for (int i = 0; i < src.cols(); ++i)\n            {\n                auto col = src.col(i);\n                float avg = col.sum() / cnt;\n                float std = std::sqrt(((col.array() * col.array()).sum() / cnt - avg * avg) + 1e-12f);\n                dest.col(i) = (col.array() - avg) / std * gamma.array() + beta.array();\n            }\n        }\n    };\n\n    struct Dense\n    {\n        ConstMatrix<float> kernel;\n        ConstVector<float> bias;\n\n        Dense(const utils::ObjectCollection& objs, const std::string& keys)\n            : kernel{ objs[keys + \"/kernel:0\"].template to_matrix<float>() },\n            bias{ objs[keys + \"/bias:0\"].template to_vector<float>() }\n        {\n        }\n\n        size_t input_size() const\n        {\n            return kernel.rows();\n        }\n\n        size_t output_size() const\n        {\n            return kernel.cols();\n        }\n\n        template<typename _EigenTy>\n        auto operator()(_EigenTy&& x) const\n            -> decltype((kernel.transpose()* x).colwise() + bias)\n        {\n            return (kernel.transpose() * x).colwise() + bias;\n        }\n\n        template<typename _Ty1, typename _Ty2>\n        auto apply_concated(_Ty1&& x, _Ty2&& y) const\n            -> decltype((kernel.topRows(x.rows()).transpose()* x\n                + kernel.bottomRows(y.rows()).transpose() * y).colwise() + bias)\n        {\n            return (kernel.topRows(x.rows()).transpose() * x\n                + kernel.bottomRows(y.rows()).transpose() * y).colwise() + bias;\n        }\n\n        template<typename _EigenTy>\n        auto partial(_EigenTy&& x, size_t begin, size_t size) const\n            -> decltype((kernel.middleCols(begin, size).transpose()* x).colwise() + bias.segment(begin, size))\n        {\n            return (kernel.middleCols(begin, size).transpose() * x).colwise() + bias.segment(begin, size);\n        }\n\n        template<typename _EigenTy>\n        float partial(_EigenTy&& x, size_t idx) const\n        {\n            return (kernel.col(idx).transpose() * x)(0) + bias(idx);\n        }\n    };\n\n    struct LSTMCell : public Dense\n    {\n        LSTMCell(const utils::ObjectCollection& objs, const std::string& keys)\n            : Dense{ objs, keys }\n        {\n        }\n\n        size_t h_size() const\n        {\n            return bias.size() / 4;\n        }\n\n        size_t input_size() const\n        {\n            return kernel.rows() - h_size();\n        }\n\n        template<typename _EigenTy1, typename _EigenTy2, typename _EigenTy3>\n        _EigenTy3& operator()(_EigenTy1&& input, _EigenTy2& c_state, _EigenTy3& h_state) const\n        {\n            Eigen::VectorXf gates = ((kernel.topRows(input.rows()).transpose() * input) + kernel.bottomRows(h_state.rows()).transpose() * h_state).colwise() + bias;\n            const size_t gate_size = h_size();\n            auto input_gate = gates.middleRows(0, gate_size).array();\n            auto new_input = gates.middleRows(gate_size, gate_size).array();\n            auto forget_gate = gates.middleRows(gate_size * 2, gate_size).array();\n            auto output_gate = gates.middleRows(gate_size * 3, gate_size).array();\n\n            c_state = (c_state.array() * sigmoid(forget_gate + 1)) + (sigmoid(input_gate) * new_input.tanh());\n            h_state = c_state.array().tanh() * sigmoid(output_gate);\n            return h_state;\n        }\n\n        template<typename _EigenTy1, typename _EigenTy2>\n        _EigenTy1& operator()(_EigenTy1& input_h, _EigenTy2& c_state) const\n        {\n            Eigen::VectorXf gates = (kernel.transpose() * input_h).colwise() + bias;\n            const size_t gate_size = h_size();\n            auto input_gate = gates.middleRows(0, gate_size).array();\n            auto new_input = gates.middleRows(gate_size, gate_size).array();\n            auto forget_gate = gates.middleRows(gate_size * 2, gate_size).array();\n            auto output_gate = gates.middleRows(gate_size * 3, gate_size).array();\n\n            c_state = (c_state.array() * sigmoid(forget_gate + 1)) + (sigmoid(input_gate) * new_input.tanh());\n            input_h.bottomRows(gate_size) = c_state.array().tanh() * sigmoid(output_gate);\n            return input_h;\n        }\n    };\n}\n", "meta": {"hexsha": "6278e01c7f0378d929b6afb8bf46f269907984fe", "size": 6510, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/layers.hpp", "max_stars_repo_name": "bab2min/lamonpy", "max_stars_repo_head_hexsha": "7a610a620cb1a1d14c51de12fa31bf1a6f70bfac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-09-26T09:16:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T22:34:26.000Z", "max_issues_repo_path": "src/layers.hpp", "max_issues_repo_name": "bab2min/lamonpy", "max_issues_repo_head_hexsha": "7a610a620cb1a1d14c51de12fa31bf1a6f70bfac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-15T16:56:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-15T17:29:40.000Z", "max_forks_repo_path": "src/layers.hpp", "max_forks_repo_name": "bab2min/lamonpy", "max_forks_repo_head_hexsha": "7a610a620cb1a1d14c51de12fa31bf1a6f70bfac", "max_forks_repo_licenses": ["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.7305699482, "max_line_length": 164, "alphanum_fraction": 0.5387096774, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5690655811063988}}
{"text": "#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <HElib/PAlgebra.h>\n#include <NTL/ZZX.h>\n\n#include \"SMP/HElib.hpp\"\nlong inner_product(NTL::zz_pX const& a, \n                   NTL::zz_pX const& b) \n{\n    NTL::zz_p ip(0);\n    long deg = NTL::deg(a);\n    for (long i = 0; i <= deg; i++) {\n        ip += (NTL::coeff(a, i) * NTL::coeff(b, deg - i));\n    }\n    return ip._zz_p__rep;\n}\n\nlong inner_product(NTL::ZZX const& a, \n                   NTL::ZZX const& b,\n\t\t\t\t   long p) \n{\n    long deg = NTL::deg(a);\n\tNTL::ZZ ip(0);\n\tNTL::ZZ P(p);\n    for (long i = 0; i <= deg; i++) {\n        ip += NTL::MulMod(NTL::coeff(a, i), NTL::coeff(b, deg - i), P);\n    }\n    return NTL::to_long(ip) % p;\n}\n\nvoid random_poly(NTL::ZZX &poly, long coeff, long degree)\n{\n\tpoly.SetLength(degree);\n\tfor (long i = 0; i < degree; i++)\n\t\tNTL::SetCoeff(poly, i, NTL::RandomBnd(coeff) + 1);\n}\n\nvoid test_with_normal_encode() {\n    long m = 4096<<2;\n    long p = 769;\n    FHEcontext context(m, p, 1);\n    buildModChain(context, 4);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n\n    const auto &factors = context.alMod.getFactorsOverZZ();\n\t//auto ea = context.ea;\n    EncryptedArray *ea = new EncryptedArray(context, factors[0]);\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\tfor (long _i = 0; _i < 100; _i++) {\n\t\tNTL::ZZX B;\n\t\trandom_poly(B, p, d);\n\n\t\tstd::vector<NTL::ZZX> Vec_A(l);\n\t\tstd::vector<long> inner_products(l);\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\trandom_poly(Vec_A[i], p, d);\n\t\t\tinner_products[i] = inner_product(Vec_A[i], B, p);\n\t\t}\n\n\t\tCtxt ctx(sk);\n\t\tea->skEncrypt(ctx, sk, std::vector<NTL::ZZX>(l, B));\n\t\tNTL::ZZX encoded_A;\n\n\t\tea->encode(encoded_A, Vec_A);\n\t\tctx.multByConstant(encoded_A);\n\t\tstd::vector<NTL::ZZX> results;\n\t\tea->decrypt(ctx, sk, results);\n\t\tstd::vector<long> computed;\n\t\tfor (auto &s : results) {\n\t\t\tcomputed.push_back(NTL::to_long(NTL::coeff(s, d - 1)));\n\t\t}\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tif (computed.at(i) != inner_products.at(i)) {\n\t\t\t\tstd::cout << NTL::deg(Vec_A[i]) << \"->\";\n\t\t\t\tstd::cout << \"computed \" << computed.at(i) << \" but want \" <<\n\t\t\t\t\tinner_products.at(i) << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid test_it() {\n    long m = 4096 << 2;\n    long p = 769;\n    FHEcontext context(m, p, 1);\n    buildModChain(context, 4);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n\n\tauto ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\n\tfor (long _i = 0; _i <100; _i++) {\n\t\tNTL::zz_p::init(p);\n\n\t\tNTL::zz_pX b;\n\t\tNTL::ZZX B;\n\t\tNTL::random(b, d);\n\t\tNTL::conv(B, b);\n\n\t\tstd::vector<NTL::zz_pX> vec_A(l);\n\t\tstd::vector<long> inner_products(l);\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tNTL::random(vec_A[i], d);\n\t\t\tNTL::SetCoeff(vec_A[i], d - 1, 1); // make sure full degree\n\t\t\tinner_products[i] = inner_product(vec_A[i], b);\n\t\t}\n\n\t\tNTL::ZZX encoded_A;\n\t\trawEncode(encoded_A, vec_A, context);\n\n\t\tCtxt ctx(sk);\n\t\tsk.Encrypt(ctx, B);\n\t\tctx.multByConstant(encoded_A);\n\n\t\tNTL::ZZX decrypted;\n\t\tsk.Decrypt(decrypted, ctx);\n\n\t\tstd::vector<NTL::zz_pX> results;\n        rawDecode(results, decrypted, context);\n\n\t\tstd::vector<long> computed;\n\t\tfor (auto &s : results) {\n\t\t\tcomputed.push_back(NTL::coeff(s, d - 1)._zz_p__rep);\n\t\t}\n\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tif (computed.at(i) != inner_products.at(i)) {\n\t\t\t\tstd::cout << NTL::deg(vec_A[i]) << \"->\";\n\t\t\t\tstd::cout << \"computed \" << computed.at(i) << \" but want \" <<\n\t\t\t\t\tinner_products.at(i) << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid test_double_pack() {\n    long m = 4096;\n    long p = 113;\n    FHEcontext context(m, p, 1);\n    buildModChain(context, 4);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n\n\tauto ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\tconst auto &factors = context.alMod.getFactorsOverZZ();\n\n\tfor (long _i = 0; _i < 1; _i++) {\n\t\tNTL::zz_p::init(p);\n\n\t\tstd::vector<NTL::zz_pX> vec_A(l);\n\t\tstd::vector<NTL::zz_pX> vec_B(l);\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tNTL::random(vec_B[i], d);\n\t\t\tNTL::SetCoeff(vec_B[i], d - 1, 1); // make sure full degree\n        }\n\n\t\tstd::vector<long> inner_products(l);\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tNTL::random(vec_A[i], d);\n\t\t\tNTL::SetCoeff(vec_A[i], d - 1, 1); // make sure full degree\n\t\t\tlong sm = 0;\n\t\t\tfor (const auto& vec_b : vec_B) {\n\t\t\t\tsm += inner_product(vec_A[i], vec_B[i]);\n\t\t\t\tsm %= p;\n\t\t\t}\n\t\t\tstd::cout << sm << \" \";\n\t\t\tinner_products[l] = sm;\n\t\t}\n\t\tstd::cout << \"\\n\" << std::endl;\n\n\t\tNTL::ZZX Vec_B;\n\t\tVec_B.SetLength(l * d);\n\t\tauto itr = Vec_B.rep.begin();\n\t\tfor (long i = 0; i < l; i++) {\n\t\t\tlong factor = NTL::to_long(factors[i][0]);\n\t\t\tfactor = NTL::PowerMod(factor, i, p); // alpha_i^(i+1) mod p\n\t\t\tauto inv = NTL::InvMod(factor, p);\n\t\t\tif (i & 1)\n\t\t\t\tinv *= -1;\n\t\t\tstd::cout << factor << \" \" << inv << \",\";\n\t\t\tfor (const auto &b : vec_B[i].rep) {\n\t\t\t\tNTL::conv(*itr++, inv * b);\n\t\t\t}\n\t\t}\n\t\tstd::cout << '\\n';\n\n\t\tNTL::ZZX encoded_A;\n\t\trawEncode(encoded_A, vec_A, context);\n\n\t\tCtxt ctx(sk);\n\t\tsk.Encrypt(ctx, Vec_B);\n\t\tctx.multByConstant(encoded_A);\n\n\t\tNTL::ZZX decrypted;\n\t\tsk.Decrypt(decrypted, ctx);\n\n\t\tstd::vector<NTL::zz_pX> results;\n        rawDecode(results, decrypted, context);\n\n\t\tstd::vector<long> computed;\n\t\tfor (auto &s : results) {\n\t\t\tcomputed.push_back(NTL::coeff(s, d - 1)._zz_p__rep);\n\t\t\tstd::cout << NTL::coeff(s, d - 1) << \" \";\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t\t// for (long i = 0; i < l; i++) {\n\t\t// \tif (computed.at(i) != inner_products.at(i)) {\n\t\t// \t\tstd::cout << NTL::deg(vec_A[i]) << \"->\";\n\t\t// \t\tstd::cout << \"computed \" << computed.at(i) << \" but want \" <<\n\t\t// \t\t\tinner_products.at(i) << std::endl;\n\t\t// \t}\n\t\t// }\n\t}\n}\nint main() {\n\ttest_double_pack();\n\t// auto st = std::clock();\n    // test_it();\n\t// std::cout << (std::clock() - st) / (double)CLOCKS_PER_SEC << std::endl;\n    //\n\t// st = std::clock();\n\t// test_with_normal_encode();\n\t// std::cout << (std::clock() - st) / (double)CLOCKS_PER_SEC << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "351badd5defe2494b28ea7574c99513ed2c0076c", "size": 5902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_mult_in_slots.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": "test/test_mult_in_slots.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": "test/test_mult_in_slots.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": 25.330472103, "max_line_length": 75, "alphanum_fraction": 0.5655709929, "num_tokens": 2121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.5690311148744344}}
{"text": "/********************************************************\n  Stanford Driving Software\n  Copyright (c) 2011 Stanford University\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with \n  or without modification, are permitted provided that the \n  following conditions are met:\n\n* Redistributions of source code must retain the above \n  copyright notice, this list of conditions and the \n  following disclaimer.\n* Redistributions in binary form must reproduce the above\n  copyright notice, this list of conditions and the \n  following disclaimer in the documentation and/or other\n  materials provided with the distribution.\n* The names of the contributors may not be used to endorse\n  or promote products derived from this software\n  without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n  CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \n  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n  DAMAGE.\n ********************************************************/\n\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <aw_geometry_3d.h>\n\nusing namespace Eigen;\n\nnamespace vlr {\n\n//== CONSTANTS ========================================================\n#define INSIDE  false\n#define OUTSIDE true\n\n// two vectors, a and b, starting from c\nfloat dot(const Vector3f& a, const Vector3f& b) {\n  return a.dot(b);\n}\n\n// two vectors, a and b\nVector3f cross(const Vector3f& a, const Vector3f& b) {\n  return a.cross(b);\n}\n\n// two vectors, a and b, starting from c\nVector3f cross(const Vector3f& a, const Vector3f& b, const Vector3f& c) {\n  float a0 = a(0) - c(0);\n  float a1 = a(1) - c(1);\n  float a2 = a(2) - c(2);\n  float b0 = b(0) - c(0);\n  float b1 = b(1) - c(1);\n  float b2 = b(2) - c(2);\n  return Vector3f(a1 * b2 - a2 * b1, a2 * b0 - a0 * b2, a0 * b1 - a1 * b0);\n}\n\nfloat dist2(const Vector3f& a, const Vector3f& b) {\n  float x = a(0) - b(0);\n  float y = a(1) - b(1);\n  float z = a(2) - b(2);\n  return x * x + y * y + z * z;\n}\n\nfloat dist(const Vector3f& a, const Vector3f& b) {\n  return sqrtf(dist2(a, b));\n}\n\n// linear interpolation\nVector3f lerp(float t, const Vector3f& a, const Vector3f& b) {\n  float v[3];\n  float u = 1.0 - t;\n  v[0] = u * a(0) + t * b(0);\n  v[1] = u * a(1) + t * b(1);\n  v[2] = u * a(2) + t * b(2);\n  return Vector3f(v[0], v[1], v[2]);\n}\n\n// is the ball centered at b with radius r\n// fully within the box centered at bc, with radius br?\nbool ball_within_bounds(const Vector3f& b, float r, const Vector3f& bc, float br) {\n  r -= br;\n  if ((b(0) - bc(0) <= r) || (bc(0) - b(0) <= r) || (b(1) - bc(1) <= r) || (bc(1) - b(1) <= r) || (b(2) - bc(2) <= r) || (bc(2) - b(2) <= r)) return false;\n  return true;\n}\n\n// is the ball centered at b with radius r\n// fully within the box centered from min to max?\nbool ball_within_bounds(const Vector3f& b, float r, const Vector3f& min, const Vector3f& max) {\n  if ((b(0) - min(0) <= r) || (max(0) - b(0) <= r) || (b(1) - min(1) <= r) || (max(1) - b(1) <= r) || (b(2) - min(2) <= r) || (max(2) - b(2) <= r)) return false;\n  return true;\n}\n\n// does the ball centered at b, with radius r,\n// intersect the box centered at bc, with radius br?\nbool bounds_overlap_ball(const Vector3f& b, float r, const Vector3f& bc, float br) {\n  float sum = 0.0, tmp;\n  if ((tmp = bc(0) - br - b(0)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  else if ((tmp = b(0) - (bc(0) + br)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  if ((tmp = bc(1) - br - b(1)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  else if ((tmp = b(1) - (bc(1) + br)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  if ((tmp = bc(2) - br - b(2)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  else if ((tmp = b(2) - (bc(2) + br)) > 0.0) {\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  return (sum < r * r);\n}\n\nbool bounds_overlap_ball(const Vector3f& b, float r, const Vector3f& min, const Vector3f& max) {\n  float sum = 0.0, tmp;\n  if (b(0) < min(0)) {\n    tmp = min(0) - b(0);\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  else if (b(0) > max(0)) {\n    tmp = b(0) - max(0);\n    if (tmp > r) return false;\n    sum += tmp * tmp;\n  }\n  if (b(1) < min(1)) {\n    tmp = min(1) - b(1);\n    sum += tmp * tmp;\n  }\n  else if (b(1) > max(1)) {\n    tmp = b(1) - max(1);\n    sum += tmp * tmp;\n  }\n  r *= r;\n  if (sum > r) return false;\n  if (b(2) < min(2)) {\n    tmp = min(2) - b(2);\n    sum += tmp * tmp;\n  }\n  else if (b(2) > max(2)) {\n    tmp = b(2) - max(2);\n    sum += tmp * tmp;\n  }\n  return (sum < r);\n}\n\n// calculate barycentric coordinates of the point p\n// (already on the triangle plane) with normal vector n\n// and two edge vectors v1 and v2,\n// starting from a common vertex t0\nvoid bary_fast(const Vector3f& p, const Vector3f& n, const Vector3f& t0, const Vector3f& v1, const Vector3f& v2, float &b1, float &b2, float &b3) {\n  // see bary above\n  int i = 0;\n  if (n(1) > n(0)) i = 1;\n  if (n(2) > n(i)) {\n    // ignore z\n    float d = 1.0 / (v1(0) * v2(1) - v1(1) * v2(0));\n    float x0 = (p(0) - t0(0));\n    float x1 = (p(1) - t0(1));\n    b1 = (x0 * v2(1) - x1 * v2(0)) * d;\n    b2 = (v1(0) * x1 - v1(1) * x0) * d;\n  }\n  else if (i == 0) {\n    // ignore x\n    float d = 1.0 / (v1(1) * v2(2) - v1(2) * v2(1));\n    float x0 = (p(1) - t0(1));\n    float x1 = (p(2) - t0(2));\n    b1 = (x0 * v2(2) - x1 * v2(1)) * d;\n    b2 = (v1(1) * x1 - v1(2) * x0) * d;\n  }\n  else {\n    // ignore y\n    float d = 1.0 / (v1(2) * v2(0) - v1(0) * v2(2));\n    float x0 = (p(2) - t0(2));\n    float x1 = (p(0) - t0(0));\n    b1 = (x0 * v2(0) - x1 * v2(2)) * d;\n    b2 = (v1(2) * x1 - v1(0) * x0) * d;\n  }\n  b3 = 1.0 - b1 - b2;\n}\n\nbool closer_on_lineseg(const Vector3f& x, Vector3f& cp, const Vector3f& a, const Vector3f& b, float &d2) {\n  Vector3f ba(b(0) - a(0), b(1) - a(1), b(2) - a(2));\n  Vector3f xa(x(0) - a(0), x(1) - a(1), x(2) - a(2));\n\n  float xa_ba = dot(xa, ba);\n  // if the dot product is negative, the point is closest to a\n  if (xa_ba < 0.0) {\n    float nd = dist2(x, a);\n    if (nd < d2) {\n      cp = a;\n      d2 = nd;\n      return true;\n    }\n    return false;\n  }\n\n  // if the dot product is greater than squared segment length,\n  // the point is closest to b\n  float fact = xa_ba / ba.squaredNorm();\n  if (fact >= 1.0) {\n    float nd = dist2(x, b);\n    if (nd < d2) {\n      cp = b;\n      d2 = nd;\n      return true;\n    }\n    return false;\n  }\n\n  // take the squared dist x-a, squared dot of x-a to unit b-a,\n  // use Pythagoras' rule\n  float nd = xa.squaredNorm() - xa_ba * fact;\n  if (nd < d2) {\n    d2 = nd;\n    cp(0) = a(0) + fact * ba(0);\n    cp(1) = a(1) + fact * ba(1);\n    cp(2) = a(2) + fact * ba(2);\n    return true;\n  }\n  return false;\n}\n\nvoid distance_point_line(const Vector3f& x, const Vector3f& a, const Vector3f& b, float &d2, Vector3f& cp) {\n  Vector3f ba(b(0) - a(0), b(1) - a(1), b(2) - a(2));\n  Vector3f xa(x(0) - a(0), x(1) - a(1), x(2) - a(2));\n\n  float xa_ba = dot(xa, ba);\n\n  // if the dot product is negative, the point is closest to a\n  if (xa_ba < 0.0) {\n    d2 = dist2(x, a);\n    cp = a;\n    return;\n  }\n\n  // if the dot product is greater than squared segment length,\n  // the point is closest to b\n  float fact = xa_ba / ba.squaredNorm();\n  if (fact >= 1.0) {\n    d2 = dist2(x, b);\n    cp = b;\n    return;\n  }\n\n  // take the squared dist x-a, squared dot of x-a to unit b-a,\n  // use Pythagoras' rule\n  d2 = xa.squaredNorm() - xa_ba * fact;\n  cp(0) = a(0) + fact * ba(0);\n  cp(1) = a(1) + fact * ba(1);\n  cp(2) = a(2) + fact * ba(2);\n  return;\n}\n\nvoid distance_point_tri(const Vector3f& x, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, float &d2, Vector3f& cp) {\n  // calculate the normal and distance from the plane\n  Vector3f v1(t2(0) - t1(0), t2(1) - t1(1), t2(2) - t1(2));\n  Vector3f v2(t3(0) - t1(0), t3(1) - t1(1), t3(2) - t1(2));\n  Vector3f n = cross(v1, v2);\n  float n_inv_mag2 = 1.0 / n.squaredNorm();\n  float tmp = (x(0) - t1(0)) * n(0) + (x(1) - t1(1)) * n(1) + (x(2) - t1(2)) * n(2);\n  float distp2 = tmp * tmp * n_inv_mag2;\n\n  // calculate the barycentric coordinates of the point\n  // (projected onto tri plane) with respect to v123\n  float b1, b2, b3;\n  float f = tmp * n_inv_mag2;\n  Vector3f pp(x(0) - f * n(0), x(1) - f * n(1), x(2) - f * n(2));\n  bary_fast(pp, n, t1, v1, v2, b1, b2, b3);\n\n  // all non-negative, the point is within the triangle\n  if (b1 >= 0.0 && b2 >= 0.0 && b3 >= 0.0) {\n    d2 = distp2;\n    cp = pp;\n    return;\n  }\n\n  // look at the signs of the barycentric coordinates\n  // if there are two negative signs, the positive\n  // one tells the vertex that's closest\n  // if there's one negative sign, the opposite edge\n  // (with endpoints) is closest\n\n  if (b1 < 0.0) {\n    if (b2 < 0.0) {\n      d2 = dist2(x, t3);\n      cp = t3;\n    }\n    else if (b3 < 0.0) {\n      d2 = dist2(x, t2);\n      cp = t2;\n    }\n    else {\n      distance_point_line(x, t2, t3, d2, cp);\n    }\n  }\n  else if (b2 < 0.0) {\n    if (b3 < 0.0) {\n      d2 = dist2(x, t1);\n      cp = t1;\n    }\n    else {\n      distance_point_line(x, t1, t3, d2, cp);\n    }\n  }\n  else {\n    distance_point_line(x, t1, t2, d2, cp);\n  }\n  return;\n}\n\nbool closer_on_tri(const Vector3f& x, Vector3f& cp, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, float &d2) {\n  // calculate the normal and distance from the plane\n  Vector3f v1(t2(0) - t1(0), t2(1) - t1(1), t2(2) - t1(2));\n  Vector3f v2(t3(0) - t1(0), t3(1) - t1(1), t3(2) - t1(2));\n  Vector3f n = cross(v1, v2);\n  float n_inv_mag2 = 1.0 / n.squaredNorm();\n  float tmp = (x(0) - t1(0)) * n(0) + (x(1) - t1(1)) * n(1) + (x(2) - t1(2)) * n(2);\n  float distp2 = tmp * tmp * n_inv_mag2;\n  if (distp2 >= d2) return false;\n\n  // calculate the barycentric coordinates of the point\n  // (projected onto tri plane) with respect to v123\n  float b1, b2, b3;\n  float f = tmp * n_inv_mag2;\n  Vector3f pp(x(0) - f * n(0), x(1) - f * n(1), x(2) - f * n(2));\n  bary_fast(pp, n, t1, v1, v2, b1, b2, b3);\n\n  // all non-negative, the point is within the triangle\n  if (b1 >= 0.0 && b2 >= 0.0 && b3 >= 0.0) {\n    d2 = distp2;\n    cp = pp;\n    return true;\n  }\n\n  // look at the signs of the barycentric coordinates\n  // if there are two negative signs, the positive\n  // one tells the vertex that's closest\n  // if there's one negative sign, the opposite edge\n  // (with endpoints) is closest\n\n  if (b1 < 0.0) {\n    if (b2 < 0.0) {\n      float nd = dist2(x, t3);\n      if (nd < d2) {\n        d2 = nd;\n        cp = t3;\n        return true;\n      }\n      else {\n        return false;\n      }\n    }\n    else if (b3 < 0.0) {\n      float nd = dist2(x, t2);\n      if (nd < d2) {\n        d2 = nd;\n        cp = t2;\n        return true;\n      }\n      else {\n        return false;\n      }\n    }\n    else return closer_on_lineseg(x, cp, t2, t3, d2);\n  }\n  else if (b2 < 0.0) {\n    if (b3 < 0.0) {\n      float nd = dist2(x, t1);\n      if (nd < d2) {\n        d2 = nd;\n        cp = t1;\n        return true;\n      }\n      else {\n        return false;\n      }\n    }\n    else return closer_on_lineseg(x, cp, t1, t3, d2);\n  }\n  else return closer_on_lineseg(x, cp, t1, t2, d2);\n}\n\n// calculate the intersection of a line going through p\n// to direction dir with a plane spanned by t1,t2,t3\n// (modified from Graphics Gems, p.299)\nbool line_plane_X(const Vector3f& p, const Vector3f& dir, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, Vector3f& x, float &dist) {\n  // note: normal doesn't need to be unit vector\n  Vector3f nrm = cross(t1, t2, t3);\n  float tmp = dot(nrm, dir);\n  if (tmp == 0.0) {\n    std::cerr << \"Cannot intersect plane with a parallel line\" << std::endl;\n    return false;\n  }\n  // d  = -dot(nrm,t1)\n  // t  = - (d + dot(p,nrm))/dot(dir,nrm)\n  // is = p + dir * t\n  x = dir;\n  dist = (dot(nrm, t1) - dot(nrm, p)) / tmp;\n  x *= dist;\n  x += p;\n  if (dist < 0.0) dist = -dist;\n  return true;\n}\n\nbool line_plane_X(const Vector3f& p, const Vector3f& dir, const Vector3f& nrm, float d, Vector3f& x, float &dist) {\n  float tmp = dot(nrm, dir);\n  if (tmp == 0.0) {\n    std::cerr << \"Cannot intersect plane with a parallel line\" << std::endl;\n    return false;\n  }\n  x = dir;\n  dist = -(d + dot(nrm, p)) / tmp;\n  x *= dist;\n  x += p;\n  if (dist < 0.0) dist = -dist;\n  return true;\n}\n\n// calculate barycentric coordinates of the point p\n// on triangle t1 t2 t3\nvoid bary(const Vector3f& p, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, float &b1, float &b2, float &b3) {\n  // figure out the plane onto which to project the vertices\n  // by calculating a cross product and finding its largest dimension\n  // then use Cramer's rule to calculate two of the\n  // barycentric coordinates\n  // e.g., if the z coordinate is ignored, and v1 = t1-t3, v2 = t2-t3\n  // b1 = det(gx(0)g v2(0); x(1) v2(1)) / det(v1(0) v2(0); v1(1) v2(1))\n  // b2 = det(gv1(0)g x(0); v1(1) x(1)) / det(v1(0) v2(0); v1(1) v2(1))\n  float v10 = t1(0) - t3(0);\n  float v11 = t1(1) - t3(1);\n  float v12 = t1(2) - t3(2);\n  float v20 = t2(0) - t3(0);\n  float v21 = t2(1) - t3(1);\n  float v22 = t2(2) - t3(2);\n  float c[2];\n  c[0] = fabs(v11 * v22 - v12 * v21);\n  c[1] = fabs(v12 * v20 - v10 * v22);\n  int i = 0;\n  if (c[1] > c[0]) i = 1;\n  if (fabs(v10 * v21 - v11 * v20) > c[i]) {\n    // ignore z\n    float d = 1.0f / (v10 * v21 - v11 * v20);\n    float x0 = (p(0) - t3(0));\n    float x1 = (p(1) - t3(1));\n    b1 = (x0 * v21 - x1 * v20) * d;\n    b2 = (v10 * x1 - v11 * x0) * d;\n  }\n  else if (i == 0) {\n    // ignore x\n    float d = 1.0f / (v11 * v22 - v12 * v21);\n    float x0 = (p(1) - t3(1));\n    float x1 = (p(2) - t3(2));\n    b1 = (x0 * v22 - x1 * v21) * d;\n    b2 = (v11 * x1 - v12 * x0) * d;\n  }\n  else {\n    // ignore y\n    float d = 1.0f / (v12 * v20 - v10 * v22);\n    float x0 = (p(2) - t3(2));\n    float x1 = (p(0) - t3(0));\n    b1 = (x0 * v20 - x1 * v22) * d;\n    b2 = (v12 * x1 - v10 * x0) * d;\n  }\n  b3 = 1.0f - b1 - b2;\n}\n\n// calculate barycentric coordinates for the intersection of\n// a line starting from p, going to direction dir, and the plane\n// of the triangle t1 t2 t3\nbool bary(const Vector3f& p, const Vector3f& dir, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, float &b1, float &b2, float &b3) {\n  Vector3f x;\n  float d;\n  if (!line_plane_X(p, dir, t1, t2, t3, x, d)) return false;\n  bary(x, t1, t2, t3, b1, b2, b3);\n\n  return true;\n}\n\n// calculate the intersection of a line starting from p,\n// going to direction dir, and the triangle t1 t2 t3\nbool line_tri_X(const Vector3f& p, const Vector3f& dir, const Vector3f& t1, const Vector3f& t2, const Vector3f& t3, Vector3f& x, float& d) {\n  float b1, b2, b3;\n  Vector3f x_temp;\n  float d_temp;\n  if (!line_plane_X(p, dir, t1, t2, t3, x_temp, d_temp)) return false;\n\n  bary(x_temp, t1, t2, t3, b1, b2, b3);\n  // all non-negative, the point is within the triangle\n  if (b1 >= 0.0 && b2 >= 0.0 && b3 >= 0.0) {\n    x = x_temp;\n    d = d_temp;\n    return true;\n  }\n  return false;\n}\n\n} // namespace vlr\n", "meta": {"hexsha": "7d36323f13c6b51bb9a38d3643deed4541e2d6db", "size": 15572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_geometry/src/aw_geometry_3d.cpp", "max_stars_repo_name": "EatAllBugs/autonomous_learning", "max_stars_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T14:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T08:49:57.000Z", "max_issues_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_geometry/src/aw_geometry_3d.cpp", "max_issues_repo_name": "yinflight/autonomous_learning", "max_issues_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "11_learning_materials/stanford_self_driving_car/planner/aw_geometry/src/aw_geometry_3d.cpp", "max_forks_repo_name": "yinflight/autonomous_learning", "max_forks_repo_head_hexsha": "02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T00:58:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:16:09.000Z", "avg_line_length": 29.7175572519, "max_line_length": 161, "alphanum_fraction": 0.5588877472, "num_tokens": 5954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5690311057877921}}
{"text": "/* chi_squared_test.hpp header file\r\n *\r\n * Copyright Steven Watanabe 2010\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#ifndef BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED\r\n#define BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED\r\n\r\n#include <vector>\r\n\r\n#include <boost/math/special_functions/pow.hpp>\r\n#include <boost/math/distributions/chi_squared.hpp>\r\n\r\n// This only works for discrete distributions with fixed\r\n// upper and lower bounds.\r\n\r\ntemplate<class IntType>\r\nstruct chi_squared_collector {\r\n\r\n    static const IntType cutoff = 5;\r\n\r\n    chi_squared_collector()\r\n      : chi_squared(0),\r\n        variables(0),\r\n        prev_actual(0),\r\n        prev_expected(0),\r\n        current_actual(0),\r\n        current_expected(0)\r\n    {}\r\n\r\n    void operator()(IntType actual, double expected) {\r\n        current_actual += actual;\r\n        current_expected += expected;\r\n\r\n        if(current_expected >= cutoff) {\r\n            if(prev_expected != 0) {\r\n                update(prev_actual, prev_expected);\r\n            }\r\n            prev_actual = current_actual;\r\n            prev_expected = current_expected;\r\n\r\n            current_actual = 0;\r\n            current_expected = 0;\r\n        }\r\n    }\r\n\r\n    void update(IntType actual, double expected) {\r\n        chi_squared += boost::math::pow<2>(actual - expected) / expected;\r\n        ++variables;\r\n    }\r\n\r\n    double cdf() {\r\n        if(prev_expected != 0) {\r\n            update(prev_actual + current_actual, prev_expected + current_expected);\r\n            prev_actual = 0;\r\n            prev_expected = 0;\r\n            current_actual = 0;\r\n            current_expected = 0;\r\n        }\r\n        if(variables <= 1) {\r\n            return 0;\r\n        } else {\r\n            return boost::math::cdf(boost::math::chi_squared(variables - 1), chi_squared);\r\n        }\r\n    }\r\n\r\n    double chi_squared;\r\n    std::size_t variables;\r\n    \r\n    IntType prev_actual;\r\n    double prev_expected;\r\n    \r\n    IntType current_actual;\r\n    double current_expected;\r\n};\r\n\r\ntemplate<class IntType>\r\ndouble chi_squared_test(const std::vector<IntType>& results, const std::vector<double>& probabilities, IntType iterations) {\r\n    chi_squared_collector<IntType> calc;\r\n    for(std::size_t i = 0; i < results.size(); ++i) {\r\n        calc(results[i], iterations * probabilities[i]);\r\n    }\r\n    return calc.cdf();\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "8b0a055138edd0c4cb52fcbe706d5eaac8778aee", "size": 2497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/chi_squared_test.hpp", "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/random/test/chi_squared_test.hpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/chi_squared_test.hpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 26.8494623656, "max_line_length": 125, "alphanum_fraction": 0.608329996, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5690310962682527}}
{"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 <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/cbrt.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\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\n}} // namespaces\n\n#endif // BOOST_MATH_AIRY_HPP\n", "meta": {"hexsha": "86d3c0b5a09e41c7079cce3723f6af7ae802d26e", "size": 7793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/special_functions/airy.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T01:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T00:41:48.000Z", "max_issues_repo_path": "boost/boost/math/special_functions/airy.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T10:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-06T09:10:33.000Z", "max_forks_repo_path": "boost/boost/math/special_functions/airy.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T02:03:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:41:50.000Z", "avg_line_length": 31.5506072874, "max_line_length": 183, "alphanum_fraction": 0.6182471449, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5690310952947589}}
{"text": "/**\n * \\file SinusGeneratorFilter.cpp\n */\n\n#include \"SimpleSinusGeneratorFilter.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n#include <cstdint>\n\nnamespace ATK\n{\n  template<class DataType_>\n  SimpleSinusGeneratorFilter<DataType_>::SimpleSinusGeneratorFilter()\n  :TypedBaseFilter<DataType_>(0, 1)\n  {\n  }\n  \n  template<class DataType_>\n  void SimpleSinusGeneratorFilter<DataType_>::set_amplitude(DataType_ amplitude)\n  {\n    this->amplitude = amplitude;\n  }\n  \n  template<class DataType_>\n  void SimpleSinusGeneratorFilter<DataType_>::set_frequency(int frequency)\n  {\n    this->frequency = frequency;\n  }\n  \n  template<class DataType_>\n  void SimpleSinusGeneratorFilter<DataType_>::process_impl(gsl::index size) const\n  {    \n    double real_increment = 2. / output_sampling_rate * frequency;\n    \n    for(gsl::index i = 0; i < size; ++i)\n    {\n      state += real_increment;\n      outputs[0][i] = static_cast<DataType_>(amplitude * std::sin(state * boost::math::constants::pi<double>()));\n    }\n  }\n  \n  template class SimpleSinusGeneratorFilter<std::int16_t>;\n  template class SimpleSinusGeneratorFilter<std::int32_t>;\n  template class SimpleSinusGeneratorFilter<int64_t>;\n  template class SimpleSinusGeneratorFilter<float>;\n  template class SimpleSinusGeneratorFilter<double>;\n}\n", "meta": {"hexsha": "dc00422d16099563c6713aa8b56975bfb4900c4d", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Mock/SimpleSinusGeneratorFilter.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/Mock/SimpleSinusGeneratorFilter.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/Mock/SimpleSinusGeneratorFilter.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": 26.06, "max_line_length": 113, "alphanum_fraction": 0.7313891021, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.5689977651041741}}
{"text": "/*\n * NativeCommonOps.cpp\n *\n *  Created on: Nov 27, 2018\n *      Author: Georg Wiedebach\n */\n\n#include <jni.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"us_ihmc_matrixlib_NativeCommonOpsWrapper.h\"\n\nusing Eigen::MatrixXd;\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_mult(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows, jint aCols, jint bCols)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aCols);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aCols, bCols);\n\n\tMatrixXd AB = A * B;\n\n\tjdouble *resultDataArray = new jdouble[aRows * bCols];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aRows, bCols) = AB;\n\tenv->SetDoubleArrayRegion(result, 0, aRows * bCols, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\tdelete resultDataArray;\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_multQuad(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows, jint aCols)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aCols);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aRows, aRows);\n\n\tMatrixXd AtBA = A.transpose() * B * A;\n\n\tjdouble *resultDataArray = new jdouble[aCols * aCols];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aCols, aCols) = AtBA;\n\tenv->SetDoubleArrayRegion(result, 0, aCols * aCols, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\tdelete resultDataArray;\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_invert(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jint aRows)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aRows);\n\n\tMatrixXd x = A.lu().inverse();\n\n\tjdouble *resultDataArray = new jdouble[aRows * aRows];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aRows, aRows) = x;\n\tenv->SetDoubleArrayRegion(result, 0, aRows * aRows, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tdelete resultDataArray;\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_solve(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aRows);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aRows, 1);\n\n\tMatrixXd x = A.lu().solve(B);\n\n\tjdouble *resultDataArray = new jdouble[aRows];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aRows, 1) = x;\n\tenv->SetDoubleArrayRegion(result, 0, aRows, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n}\n\nJNIEXPORT jboolean JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_solveCheck(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aRows);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aRows, 1);\n\n\tconst Eigen::FullPivLU<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> > fullPivLu = A.fullPivLu();\n\tif (fullPivLu.isInvertible())\n\t{\n\t\tMatrixXd x = fullPivLu.solve(B);\n\n\t\tjdouble *resultDataArray = new jdouble[aRows];\n\t\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aRows, 1) = x;\n\t\tenv->SetDoubleArrayRegion(result, 0, aRows, resultDataArray);\n\n\t\tdelete resultDataArray;\n\t\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\t\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\t\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\t\treturn false;\n\t}\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_solveRobust(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows, jint aCols)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aCols);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aRows, 1);\n\n\tMatrixXd x = A.householderQr().solve(B);\n\n\tjdouble *resultDataArray = new jdouble[aCols];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aCols, 1) = x;\n\tenv->SetDoubleArrayRegion(result, 0, aCols, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\tdelete resultDataArray;\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_solveDamped(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows, jint aCols, jdouble alpha)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aCols);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, aRows, 1);\n\n\tMatrixXd outer = A * A.transpose() + MatrixXd::Identity(aRows, aRows) * alpha * alpha;\n\tMatrixXd x = A.transpose() * outer.llt().solve(B);\n\n\tjdouble *resultDataArray = new jdouble[aCols];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aCols, 1) = x;\n\tenv->SetDoubleArrayRegion(result, 0, aCols, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\tdelete resultDataArray;\n}\n\nJNIEXPORT void JNICALL Java_us_ihmc_matrixlib_NativeCommonOpsWrapper_projectOnNullspace(JNIEnv *env, jobject thisObj,\n\t\tjdoubleArray result, jdoubleArray aData, jdoubleArray bData, jint aRows, jint aCols, jint bRows, jdouble alpha)\n{\n\tjdouble *aDataArray = env->GetDoubleArrayElements(aData, NULL);\n\tjdouble *bDataArray = env->GetDoubleArrayElements(bData, NULL);\n\tMatrixXd A = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(aDataArray, aRows, aCols);\n\tMatrixXd B = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(bDataArray, bRows, aCols);\n\n\tMatrixXd BtB = B.transpose() * B;\n\tMatrixXd outer = BtB + MatrixXd::Identity(aCols, aCols) * alpha * alpha;\n\tMatrixXd x = A * (MatrixXd::Identity(aCols, aCols) - outer.llt().solve(BtB));\n\n\tjdouble *resultDataArray = new jdouble[aRows * aCols];\n\tEigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(resultDataArray, aRows, aCols) = x;\n\tenv->SetDoubleArrayRegion(result, 0, aRows * aCols, resultDataArray);\n\n\tenv->ReleaseDoubleArrayElements(aData, aDataArray, 0);\n\tenv->ReleaseDoubleArrayElements(bData, bDataArray, 0);\n\tdelete resultDataArray;\n}\n", "meta": {"hexsha": "773e357602b6b0bbd2dae2160690531fe41782de", "size": 8439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NativeCommonOps/NativeCommonOps.cpp", "max_stars_repo_name": "ihmcrobotics/ihmc-matrix-library", "max_stars_repo_head_hexsha": "da0f7865c2ef37f309ce1fd62e7e0434b00ad4f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T17:56:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T17:56:01.000Z", "max_issues_repo_path": "NativeCommonOps/NativeCommonOps.cpp", "max_issues_repo_name": "ihmcrobotics/ihmc-matrix-library", "max_issues_repo_head_hexsha": "da0f7865c2ef37f309ce1fd62e7e0434b00ad4f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T22:08:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T22:08:27.000Z", "max_forks_repo_path": "NativeCommonOps/NativeCommonOps.cpp", "max_forks_repo_name": "ihmcrobotics/ihmc-matrix-library", "max_forks_repo_head_hexsha": "da0f7865c2ef37f309ce1fd62e7e0434b00ad4f8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9488636364, "max_line_length": 123, "alphanum_fraction": 0.7628865979, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5689977609794853}}
{"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/trans.hpp>\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 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    matrix A_t(ublas::trans(A));\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::gemv(alpha, A, x, beta, y2);\n    vector y3(y);\n    blas::gemv(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  {\n    typedef std::complex<double> complex;\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    size_type m=6, n=8;\n    rand_normal<complex>::reset();\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    matrix A_t(A.transpose());\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*A*x+beta*y);\n    vector y2(y);\n    blas::gemv(alpha, A, x, beta, y2);\n    vector y3(y);\n    blas::gemv(alpha, blas::trans(A_t), x, beta, y3);\n    std::cout << \"testing eigen++ containers\\n\"\n\t      << \"using eigen++         : \" << 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": "a1ad0127334c746be1da9d4044299eeed2bf7561", "size": 2905, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/blas/gemv.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/gemv.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/gemv.cc", "max_forks_repo_name": "rabauke/numeric_bindings", "max_forks_repo_head_hexsha": "f4de93bd7a01a8b31c9367fad35c81d086768f99", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5833333333, "max_line_length": 74, "alphanum_fraction": 0.6065404475, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5689900851063863}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Johannes Goettker-Schnetmann\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\n#include <ql/experimental/finitedifferences/squarerootprocessrndcalculator.hpp>\n\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\nnamespace QuantLib {\n\n    SquareRootProcessRNDCalculator::SquareRootProcessRNDCalculator(\n        Real v0, Real kappa, Real theta, Real sigma)\n    : v0_(v0), kappa_(kappa), theta_(theta),\n      d_(4*kappa/(sigma*sigma)), df_(d_*theta) {    }\n\n\n    Real SquareRootProcessRNDCalculator::pdf(Real v, Time t) const {\n        const Real e   = std::exp(-kappa_*t);\n        const Real k   = d_/(1-e);\n        const Real ncp = k*v0_*e;\n\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(df_, ncp);\n\n        return boost::math::pdf(dist, v*k) * k;\n    }\n\n    Real SquareRootProcessRNDCalculator::cdf(Real v, Time t) const {\n        const Real e   = std::exp(-kappa_*t);\n        const Real k   = d_/(1-e);\n        const Real ncp = k*v0_*e;\n\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(df_, ncp);\n\n        return boost::math::cdf(dist, v*k);\n    }\n\n    Real SquareRootProcessRNDCalculator::invcdf(Real q, Time t) const {\n        const Real e   = std::exp(-kappa_*t);\n        const Real k   = d_/(1-e);\n        const Real ncp = k*v0_*e;\n\n        const boost::math::non_central_chi_squared_distribution<Real>\n            dist(df_, ncp);\n\n        return boost::math::quantile(dist, q) / k;\n    }\n\n    Real SquareRootProcessRNDCalculator::stationary_pdf(Real v) const {\n        const Real alpha = 0.5*df_;\n        const Real beta = alpha/theta_;\n\n        return std::pow(beta, alpha)*std::pow(v, alpha-1)\n                *std::exp(-beta*v-boost::math::lgamma(alpha));\n    }\n\n    Real SquareRootProcessRNDCalculator::stationary_cdf(Real v) const {\n        const Real alpha = 0.5*df_;\n        const Real beta = alpha/theta_;\n\n        return boost::math::gamma_p(alpha, beta*v);\n    }\n\n    Real SquareRootProcessRNDCalculator::stationary_invcdf(Real q) const {\n        const Real alpha = 0.5*df_;\n        const Real beta = alpha/theta_;\n\n        return boost::math::gamma_p_inv(alpha, q)/beta;\n    }\n}\n", "meta": {"hexsha": "fa8bb56d9db2206305dacee9c0a6f4c1d4416e95", "size": 2962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/finitedifferences/squarerootprocessrndcalculator.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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/finitedifferences/squarerootprocessrndcalculator.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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/finitedifferences/squarerootprocessrndcalculator.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "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": 33.2808988764, "max_line_length": 79, "alphanum_fraction": 0.663403106, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5689900806577187}}
{"text": "#ifndef _DEPTH_ESTIMATOR_H_\n#define _DEPTH_ESTIMATOR_H_\n\n#include <vector>\n#include <Eigen/Dense>\n#include <memory>\n#include <ceres/ceres.h>\n\nnamespace depth_estimator {\n\n  class CostFunction {\n  public:\n    explicit inline CostFunction(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2,\n                                 int idx1, int idx2,\n                                 double target_dist)\n      : x1_(p1[0]), y1_(p1[1]),\n        x2_(p2[0]), y2_(p2[1]),\n        idx1_(idx1), idx2_(idx2),\n        dist_(target_dist) {}\n\n    template <typename T>\n    inline bool operator() (const T* const d, T* residual) const {\n      residual[0] = T(dist_) - ceres::sqrt(ceres::pow(d[idx1_] * T(x1_) - d[idx2_] * T(x2_), 2) +\n                                           ceres::pow(d[idx1_] * T(y1_) - d[idx2_] * T(y2_), 2) +\n                                           ceres::pow(d[idx1_]          - d[idx2_],          2));\n      return true;\n    }\n\n  private:\n    const double x1_;\n    const double y1_;\n    const double x2_;\n    const double y2_;\n    const int idx1_;\n    const int idx2_;\n    const double dist_;\n  };\n\n  template <int N>\n  class DepthEstimator {\n  public:\n    inline DepthEstimator(const std::vector<Eigen::Vector2d>& points_2d,\n                          const std::vector<Eigen::Vector3d>& points_3d) \n      : points_2d_(points_2d), points_3d_(points_3d) {}\n\n    inline Eigen::VectorXd Estimate() {\n      std::vector<double> depths(N, 1.0);\n\n      ceres::Problem problem;\n\n      for (int i = N - 1; i >= 1; --i) {\n        for (int j = i - 1; j >= 0; --j) {\n          problem.AddResidualBlock(\n            new ceres::AutoDiffCostFunction<CostFunction, 1, N>(\n              new CostFunction(points_2d_[i], points_2d_[j],\n                               i, j,\n                               (points_3d_[i] - points_3d_[j]).norm())),\n            nullptr, depths.data());\n        }\n      }\n\n      ceres::Solver::Options options;\n      options.linear_solver_type = ceres::DENSE_QR;\n      options.minimizer_progress_to_stdout = false;\n      options.parameter_tolerance = 0.01;\n\n      ceres::Solver::Summary summary;\n      ceres::Solve(options, &problem, &summary);\n\n      Eigen::VectorXd result(N);\n      for (int i = 0; i < N; ++i) {\n        result[i] = depths[i];\n      }\n      return result;\n    }\n\n  private:\n    const std::vector<Eigen::Vector2d>& points_2d_;\n    const std::vector<Eigen::Vector3d>& points_3d_;\n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "d0a68c7b6a7b8fcb85cbb599bce3be1bd603e5aa", "size": 2434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gate_est/src/depth_estimator.hpp", "max_stars_repo_name": "Veilkrand/drone_race", "max_stars_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gate_est/src/depth_estimator.hpp", "max_issues_repo_name": "Veilkrand/drone_race", "max_issues_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gate_est/src/depth_estimator.hpp", "max_forks_repo_name": "Veilkrand/drone_race", "max_forks_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-15T10:34:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T15:08:20.000Z", "avg_line_length": 28.6352941176, "max_line_length": 97, "alphanum_fraction": 0.5468364832, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.568990071760383}}
{"text": "#ifndef USE_CUDA\n\n#include <iostream>\n\n#include <kernel.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// C++ Version\nnamespace Kernel\n{\n    double dot(const std::vector<Eigen::Vector3d> & v1, const std::vector<Eigen::Vector3d> & v2)\n    {\n        double x=0;\n        for (int i=0; i<v1.size(); ++i)\n        {\n            x += v1[i].dot(v2[i]);\n        }\n        return x;\n    }\n\n    void run_eigen_solver(const std::vector<Eigen::Matrix3f> &m)\n    {\n        for (int i = 0; i < m.size(); ++i){\n            Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> es(m[i]);\n            std::cout << \"Matrix \" << i << \":\" << std::endl << m[i] << std::endl;\n            std::cout << \"The eigenvalues :\" << std::endl << es.eigenvalues() << std::endl;\n            std::cout << \"The eigenvectors :\" << std::endl << es.eigenvectors() << std::endl;\n            std::cout << \"==================================================================\" << std::endl;\n        }\n    }\n}\n\n#endif", "meta": {"hexsha": "abf03115e92d35fd6744197936543edc5fccda4e", "size": 969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel.cpp", "max_stars_repo_name": "Robslhc/eigen-cuda", "max_stars_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kernel.cpp", "max_issues_repo_name": "Robslhc/eigen-cuda", "max_issues_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernel.cpp", "max_forks_repo_name": "Robslhc/eigen-cuda", "max_forks_repo_head_hexsha": "31c4b1488730d2ea4d5612e6d0769369a2b376b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 107, "alphanum_fraction": 0.4778121775, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5688936315939471}}
{"text": "\n#include <boost/lexical_cast.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\n#include \"quadrature/qmaxwell.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\n\n\n// template<typename MAP>\n// void print(const MAP& m, std::ofstream& fout, string title)\n// {\n//   fout << \"----- \" << title << endl;\n//   for (auto it = m.begin(); it != m.end(); ++it) {\n//     fout << it->first.first << \"\\t\"\n//          << it->first.second\n//          << \"\\t\"\n//          << setprecision(16) << it->second\n//          << endl;\n//   }\n// }\n\n// template<typename CONT>\n// void print_basis(const CONT& cont, std::ofstream& fout)\n// {\n//   for (int i = 0; i < cont.size(); ++i) {\n//     fout  << cont[i].get_id() << endl;\n//   }\n// }\n\n// ----------------------------------------------------------------------\nint main(int argc, char *argv[])\n{\n  const double beta = 2;\n\n  if (argc < 2) {\n    cerr << \"info: \" << argv[0] << \" N\" << endl << \"q: No. quad. points\\n\";\n    return 1;\n  }\n  int N = atoi(argv[1]);\n\n  int digits = 128;\n  QMaxwell qmaxwell(1, N, digits);\n\n  std::ofstream fout(\"quadrule_order\" + boost::lexical_cast<string>(N) + \"_\" +\n                     boost::lexical_cast<string>(digits) + \".dat\");\n  for (int i = 0; i < qmaxwell.size(); ++i) {\n    fout << setprecision(30) << qmaxwell.pts(i) << \"\\t\" << setprecision(30) << qmaxwell.wts(i)\n         << endl;\n  }\n  fout.close();\n\n  // test integration\n  cout << \"evaluate integral: \\\\int_0^{2pi} \\\\int_0^\\\\infty e^{-r^} r \\\\dd r\"\n       << \"\\n\";\n  double sum = 0;\n  for (int i = 0; i < N; ++i) {\n    sum += qmaxwell.wts(i);\n  }\n  const double pi = boost::math::constants::pi<double>();\n  sum *= 2 * pi;\n  cout << \"\\terror:\" << std::abs(sum - pi) << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "5c27edae7372107f02ae05ec282de2415fcc87cb", "size": 1807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/maxwell_quadrature/main.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/maxwell_quadrature/main.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/maxwell_quadrature/main.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0972222222, "max_line_length": 94, "alphanum_fraction": 0.5185390149, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5688936262214094}}
{"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_QUASI_NEWTON_INCLUDE\n#define ITL_QUASI_NEWTON_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/operators.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n#include <boost/numeric/mtl/utility/gradient.hpp>\n\n// #include <iostream>\n\nnamespace itl {\n\n/// Quasi-Newton method\ntemplate <typename Matrix, typename Vector, typename F, typename Grad, \n\t  typename Step, typename Update, typename Iter>\nVector quasi_newton(Vector& x, F f, Grad grad_f, Step step, Update update, Iter& iter) \n{    \n    typedef typename mtl::Collection<Vector>::value_type value_type;\n    Vector         d, y, x_k, s;\n    Matrix         H(size(x), size(x));\n    \n    H= 1;\n    for (; !iter.finished(two_norm(grad_f(x))); ++iter) {\n\td= H * -grad_f(x);                                                  // std::cout << \"d is \" << d << '\\n'; \n\tvalue_type alpha= step(x, d, f, grad_f); assert(alpha == alpha);\n\tx_k= x + alpha * d;                                                 // std::cout << \"x_k is \" << x_k << '\\n';\n\ts= alpha * d;                                                       // std::cout << \"alpha is \" << alpha << '\\n';\n\ty= grad_f(x_k) - grad_f(x);\n\tupdate(H, y, s);                               \n\tx= x_k;                                                             \n    }\n    return x;\n}\n\n/// Quasi-Newton method\ntemplate <typename Vector, typename F, typename Grad, typename Step, typename Update, typename Iter>\nVector inline quasi_newton(Vector& x, F f, Grad grad_f, Step step, Update update, Iter& iter) \n{\n    typedef typename mtl::traits::gradient<Vector>::type hessian_type;\n    // typedef typename mtl::Collection<Vector>::value_type value_type;\n    return quasi_newton<hessian_type>(x, f, grad_f, step, update, iter);\n}\n\n\n} // namespace itl\n\n#endif // ITL_QUASI_NEWTON_INCLUDE\n", "meta": {"hexsha": "2136952be262c5f759f42ae149c939687b7de40b", "size": 2380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/minimization/quasi_newton.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/itl/minimization/quasi_newton.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/itl/minimization/quasi_newton.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": 38.3870967742, "max_line_length": 114, "alphanum_fraction": 0.6142857143, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5688759835029084}}
{"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/omni-field-persistence.h>\n#include <dionysus/diagram.h>\n\nnamespace d = dionysus;\n\n#include <format.h>\n\nusing Simplex       = d::Simplex<>;\nusing Filtration    = d::Filtration<Simplex>;\nusing Persistence   = d::OmniFieldPersistence<>;\n\nint main()\n{\n    // Klein bottle\n    Filtration filtration\n    {\n      {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8},\n      {0,1}, {1,2}, {2,0}, {0,3}, {3,4}, {4,0},\n      {1,5}, {5,6}, {6,2}, {2,7}, {7,8}, {8,1},\n      {3,5}, {5,7}, {7,3}, {4,6}, {6,8}, {8,4},\n      {0,5}, {1,7}, {2,3}, {3,6}, {5,8}, {7,4},\n      {4,2}, {6,1}, {8,0},\n      {0,3,5}, {0,1,5}, {1,5,7}, {1,2,7}, {2,7,3}, {2,3,0},\n      {3,4,6}, {3,5,6}, {5,6,8}, {5,7,8}, {7,8,4}, {7,3,4},\n      {4,0,2}, {4,6,2}, {6,2,1}, {6,8,1}, {8,1,0}, {8,4,0}\n    };\n\n    fmt::print(\"Boundary matrix over Q\\n\");\n    d::Q<> q;\n    for (auto& s : filtration)\n    {\n        fmt::print(\"{} at {}\\n\", s, filtration.index(s));\n        for (auto sb : s.boundary(q))\n            fmt::print(\"   {} * {} at {}\\n\", sb.element(), sb.index(), filtration.index(sb.index()));\n    }\n\n    Persistence     persistence;\n    for(auto& s : filtration)\n    {\n        using SimplexChainEntry = d::ChainEntry<Persistence::Field, Simplex>;\n        using ChainEntry        = d::ChainEntry<Persistence::Field, Persistence::Index>;\n        persistence.add(s.boundary(persistence.field()) |\n                                                 ba::transformed([&filtration](const SimplexChainEntry& e)\n                                                 { return ChainEntry(e.element(), filtration.index(e.index())); }));\n    }\n    fmt::print(\"Reduction finished\\n\");\n\n    fmt::print(\"Special primes:\");\n    for (auto x : persistence.primes())\n        fmt::print(\" {}\", x);\n    fmt::print(\"\\n\");\n\n    unsigned i = 0;\n    fmt::print(\"Q chains finished\\n\");\n    for (auto& c : persistence.q_chains())\n    {\n        fmt::print(\"{}: \", i);\n        for (auto& ce : c)\n            fmt::print(\" + {} * {}\", ce.element(), ce.index());\n        fmt::print(\"\\n\");\n        ++i;\n    }\n\n    fmt::print(\"Zp chains finished\\n\");\n    for (auto& x : persistence.zp_chains())\n    {\n        unsigned i = x.first;\n        fmt::print(\"{}:\\n\", i);\n        for (auto& ec : x.second)\n        {\n            auto& e = ec.first;\n            auto& c = ec.second;\n\n            fmt::print(\"  mod {}:\", e);\n\n            for (auto& ce : c)\n                fmt::print(\" + {} * {}\", ce.element(), ce.index());\n        }\n        fmt::print(\"\\n\");\n    }\n\n    auto primes = persistence.primes();\n    primes.emplace(primes.begin(), 1);\n    for (auto& p : primes)\n    {\n        if (p == 1)\n            fmt::print(\"Over Z_p (for all p, except those specified explicitly)\\n\");\n        else\n            fmt::print(\"Over Z_{}:\\n\", p);\n        auto diagrams = init_diagrams(prime_adapter(persistence, p), filtration,\n                                      [&](const Simplex& s) -> float  { return filtration.index(s); },        // inefficient, but works\n                                      [](Persistence::Index i)        { return i; });\n        i = 0;\n        for (auto& dgm : diagrams)\n        {\n            fmt::print(\"  Dimension {}:\\n\", i++);\n            for (auto& pt : dgm)\n                fmt::print(\"    {} {}\\n\", pt.birth(), pt.death());\n        }\n    }\n}\n", "meta": {"hexsha": "16ac818ed4c5e28ba9dd82a93ab454be94030767", "size": 3465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/omni-field/omni-field-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/omni-field/omni-field-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/omni-field/omni-field-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": 31.5, "max_line_length": 135, "alphanum_fraction": 0.470995671, "num_tokens": 1045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5688054809997665}}
{"text": "// distribution_construction.cpp\r\n\r\n// Copyright Paul A. Bristow 2007, 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// 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//[distribution_construction1\r\n\r\n/*`\r\n\r\nThe structure of distributions is rather different from some other statistical libraries,\r\nfor example in less object-oriented language like FORTRAN and C,\r\nthat provide a few arguments to each free function.\r\nThis library provides each distribution as a template C++ class.\r\nA distribution is constructed with a few arguments, and then\r\nmember and non-member functions are used to find values of the\r\ndistribution, often a function of a random variate.\r\n\r\nFirst we need some includes to access the negative binomial distribution\r\n(and the binomial, beta and gamma too).\r\n\r\n*/\r\n\r\n#include <boost/math/distributions/negative_binomial.hpp> // for negative_binomial_distribution\r\n  using boost::math::negative_binomial_distribution; // default type is double.\r\n  using boost::math::negative_binomial; // typedef provides default type is double.\r\n#include <boost/math/distributions/binomial.hpp> // for binomial_distribution.\r\n#include <boost/math/distributions/beta.hpp> // for beta_distribution.\r\n#include <boost/math/distributions/gamma.hpp> // for gamma_distribution.\r\n#include <boost/math/distributions/normal.hpp> // for normal_distribution.\r\n/*`\r\nSeveral examples of constructing distributions follow:\r\n*/\r\n//] [/distribution_construction1 end of Quickbook in C++ markup]\r\n\r\nint main()\r\n{\r\n//[distribution_construction2\r\n/*`\r\nFirst, a negative binomial distribution with 8 successes\r\nand a success fraction 0.25, 25% or 1 in 4, is constructed like this:\r\n*/\r\n  boost::math::negative_binomial_distribution<double> mydist0(8., 0.25);\r\n  /*`\r\n  But this is inconveniently long, so we might be tempted to write\r\n  */\r\n  using namespace boost::math;\r\n  /*`\r\n  but this might risk ambiguity with names in std random so\r\n  *much better is explicit `using boost::math:: ` * ... statements like\r\n  */\r\n  using boost::math::negative_binomial_distribution;\r\n  /*`\r\n  and we can still reduce typing.\r\n\r\n  Since the vast majority of applications use will be using double precision,\r\n  the template argument to the distribution (RealType) defaults\r\n  to type double, so we can also write:\r\n  */\r\n\r\n  negative_binomial_distribution<> mydist9(8., 0.25); // Uses default RealType = double.\r\n\r\n  /*`\r\n  But the name \"negative_binomial_distribution\" is still inconveniently long,\r\n  so for most distributions, a convenience typedef is provided, for example:\r\n\r\n     typedef negative_binomial_distribution<double> negative_binomial; // Reserved name of type double.\r\n\r\n  [caution\r\n  This convenience typedef is /not/ provided if a clash would occur\r\n  with the name of a function: currently only \"beta\" and \"gamma\"\r\n  fall into this category.\r\n  ]\r\n\r\n  So, after a using statement,\r\n  */\r\n\r\n  using boost::math::negative_binomial;\r\n\r\n  /*`\r\n  we have a convenient typedef to `negative_binomial_distribution<double>`:\r\n  */\r\n  negative_binomial mydist(8., 0.25);\r\n\r\n  /*`\r\n  Some more examples using the convenience typedef:\r\n  */\r\n  negative_binomial mydist10(5., 0.4); // Both arguments double.\r\n  /*`\r\n  And automatic conversion takes place, so you can use integers and floats:\r\n  */\r\n  negative_binomial mydist11(5, 0.4); // Using provided typedef double, int and double arguments.\r\n  /*`\r\n  This is probably the most common usage.\r\n  */\r\n  negative_binomial mydist12(5., 0.4F); // Double and float arguments.\r\n  negative_binomial mydist13(5, 1); // Both arguments integer.\r\n\r\n  /*`\r\n  Similarly for most other distributions like the binomial.\r\n  */\r\n  binomial mybinomial(1, 0.5); // is more concise than\r\n  binomial_distribution<> mybinomd1(1, 0.5);\r\n\r\n  /*`\r\n  For cases when the typdef distribution name would clash with a math special function\r\n  (currently only beta and gamma)\r\n  the typedef is deliberately not provided, and the longer version of the name\r\n  must be used.  For example do not use:\r\n\r\n     using boost::math::beta;\r\n     beta mybetad0(1, 0.5); // Error beta is a math FUNCTION!\r\n\r\n  Which produces the error messages:\r\n\r\n  [pre\r\n  error C2146: syntax error : missing ';' before identifier 'mybetad0'\r\n  warning C4551: function call missing argument list\r\n  error C3861: 'mybetad0': identifier not found\r\n  ]\r\n\r\n  Instead you should use:\r\n  */\r\n  using boost::math::beta_distribution;\r\n  beta_distribution<> mybetad1(1, 0.5);\r\n  /*`\r\n  or for the gamma distribution:\r\n  */\r\n  gamma_distribution<> mygammad1(1, 0.5);\r\n\r\n  /*`\r\n  We can, of course, still provide the type explicitly thus:\r\n  */\r\n\r\n  // Explicit double precision:\r\n  negative_binomial_distribution<double>        mydist1(8., 0.25);\r\n\r\n  // Explicit float precision, double arguments are truncated to float:\r\n  negative_binomial_distribution<float>         mydist2(8., 0.25);\r\n\r\n  // Explicit float precision, integer & double arguments converted to float.\r\n  negative_binomial_distribution<float>         mydist3(8, 0.25);\r\n\r\n  // Explicit float precision, float arguments, so no conversion:\r\n  negative_binomial_distribution<float>         mydist4(8.F, 0.25F);\r\n\r\n  // Explicit float precision, integer arguments promoted to float.\r\n  negative_binomial_distribution<float>         mydist5(8, 1);\r\n\r\n  // Explicit double precision:\r\n  negative_binomial_distribution<double>        mydist6(8., 0.25);\r\n\r\n  // Explicit long double precision:\r\n  negative_binomial_distribution<long double>   mydist7(8., 0.25);\r\n\r\n  /*`\r\n  And if you have your own RealType called MyFPType,\r\n  for example NTL RR (an arbitrary precision type), then we can write:\r\n\r\n     negative_binomial_distribution<MyFPType>  mydist6(8, 1); // Integer arguments -> MyFPType.\r\n\r\n  [heading Default arguments to distribution constructors.]\r\n\r\n  Note that default constructor arguments are only provided for some distributions.\r\n  So if you wrongly assume a default argument you will get an error message, for example:\r\n\r\n     negative_binomial_distribution<> mydist8;\r\n\r\n  [pre error C2512 no appropriate default constructor available.]\r\n\r\n  No default constructors are provided for the negative binomial,\r\n  because it is difficult to chose any sensible default values for this distribution.\r\n  For other distributions, like the normal distribution,\r\n  it is obviously very useful to provide 'standard'\r\n  defaults for the mean and standard deviation thus:\r\n\r\n      normal_distribution(RealType mean = 0, RealType sd = 1);\r\n\r\n  So in this case we can write:\r\n  */\r\n  using boost::math::normal;\r\n\r\n  normal norm1;       // Standard normal distribution.\r\n  normal norm2(2);    // Mean = 2, std deviation = 1.\r\n  normal norm3(2, 3); // Mean = 2, std deviation = 3.\r\n\r\n  return 0;\r\n}  // int main()\r\n\r\n/*`There is no useful output from this program, of course. */\r\n\r\n//] [/end of distribution_construction2]\r\n\r\n", "meta": {"hexsha": "5116763f427332a357bf2d379ae5ecf20486fea8", "size": 7097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/distribution_construction.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/distribution_construction.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/distribution_construction.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.485, "max_line_length": 104, "alphanum_fraction": 0.7179089756, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.568805478174331}}
{"text": "#include <iostream>\n\n#include <elemental.hpp>\n#include <boost/mpi.hpp>\n#include <boost/format.hpp>\n#include <skylark.hpp>\n\n/*******************************************/\nnamespace bmpi =  boost::mpi;\nnamespace skybase = skylark::base;\nnamespace skysk =  skylark::sketch;\nnamespace skynla = skylark::nla;\nnamespace skyalg = skylark::algorithms;\nnamespace skyutil = skylark::utility;\n/*******************************************/\n\nconst int m = 50000;\nconst int n = 500;\n\ntypedef elem::DistMatrix<double, elem::VC, elem::STAR> matrix_type;\ntypedef elem::DistMatrix<double, elem::VC, elem::STAR> rhs_type;\ntypedef elem::DistMatrix<double, elem::STAR, elem::STAR> sol_type;\n\ntemplate<typename MatrixType, typename RhsType, typename SolType>\nvoid check_solution(const MatrixType &A, const RhsType &b, const SolType &x, \n    const RhsType &r0,\n    double &res, double &resAtr, double &resFac) {\n    RhsType r(b);\n    skybase::Gemv(elem::NORMAL, -1.0, A, x, 1.0, r);\n    res = skybase::Nrm2(r);\n\n    SolType Atr(x.Height(), x.Width(), x.Grid());\n    skybase::Gemv(elem::TRANSPOSE, 1.0, A, r, 0.0, Atr);\n    resAtr = skybase::Nrm2(Atr);\n\n    skybase::Axpy(-1.0, r0, r);\n    RhsType dr(b);\n    skybase::Axpy(-1.0, r0, dr);\n    resFac = skybase::Nrm2(r) / skybase::Nrm2(dr);\n}\n\nint main(int argc, char** argv) {\n    double res, resAtr, resFac;\n\n    elem::Initialize(argc, argv);\n\n    bmpi::communicator world;\n    int rank = world.rank();\n\n    skybase::context_t context(23234);\n\n    // Setup problem and righthand side\n    // Using Skylark's uniform generator (as opposed to Elemental's)\n    // will insure the same A and b are generated regardless of the number\n    // of processors.\n    matrix_type A =\n        skyutil::uniform_matrix_t<matrix_type>::generate(m,\n            n, elem::DefaultGrid(), context);\n    matrix_type b =\n        skyutil::uniform_matrix_t<matrix_type>::generate(m,\n            1, elem::DefaultGrid(), context);\n\n    sol_type x(n,1);\n    rhs_type r(b);\n\n    boost::mpi::timer timer;\n    double telp;\n\n    // Solve using Elemental. Note: Elemental only supports [MC,MR]...\n    elem::DistMatrix<double> A1 = A, b1 = b, x1;\n    timer.restart();\n    elem::LeastSquares(elem::NORMAL, A1, b1, x1);\n    telp = timer.elapsed();\n    x = x1;\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Elemental:\\t\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \"\\t\\t\\t\\t\\t\\t\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n    double res_opt = res;\n\n    skybase::Gemv(elem::NORMAL, -1.0, A, x, 1.0, r);\n\n    // Solve using Sylark\n    timer.restart();\n    skynla::FastLeastSquares(elem::NORMAL, A, b, x, context);\n    telp = timer.elapsed();\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Skylark:\\t\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \" (x \" << boost::format(\"%.5f\") % (res / res_opt) << \")\"\n                  << \"\\t||r - r*||_2 / ||b - r*||_2 = \" << boost::format(\"%.2e\") % resFac\n                  << \"\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n\n    // Approximately solve using Sylark\n    timer.restart();\n    skynla::ApproximateLeastSquares(elem::NORMAL, A, b, x, context);\n    telp = timer.elapsed();\n    check_solution(A, b, x, r, res, resAtr, resFac);\n    if (rank == 0)\n        std::cout << \"Skylark (approximate):\\t\\t||r||_2 =  \"\n                  << boost::format(\"%.2f\") % res\n                  << \" (x \" << boost::format(\"%.5f\") % (res / res_opt) << \")\"\n                  << \"\\t||r - r*||_2 / ||b - r*||_2 = \" << boost::format(\"%.2e\") % resFac\n                  << \"\\t||A' * r||_2 = \" << boost::format(\"%.2e\") % resAtr\n                  << \"\\t\\tTime: \" << boost::format(\"%.2e\") % telp << \" sec\"\n                  << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "6129429aaa50f9f8f51b0856dedd7b50dfc2a892", "size": 4062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/least_squares.cpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "examples/least_squares.cpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/least_squares.cpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0172413793, "max_line_length": 89, "alphanum_fraction": 0.5374199902, "num_tokens": 1246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.568805469698024}}
{"text": "#ifndef NCA_HPP\n#define NCA_HPP\n\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Core>\n\nvoid nearest_neighbors(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string>& label) {\n    unsigned int correct = 0;\n\n    for(unsigned int i = 0; i < input.size(); ++i) {\n        double min_norm = std::numeric_limits<double>::infinity();\n        std::string min_norm_label;\n        for(unsigned int j = 0; j < input.size(); ++j) {\n            if(i == j) continue;\n            double norm = (input[i] - input[j]).norm();\n            if(norm < min_norm) {\n                min_norm = norm;\n                min_norm_label = label[j];\n            }\n        }\n\n        if(label[i] == min_norm_label) {\n            ++correct;\n        }\n    }\n\n    std::cout << \"Got \" << correct << \" correct out of \" << input.size() << std::endl;\n}\n\nEigen::MatrixXd scaling_matrix(const std::vector<Eigen::VectorXd>& input) {\n    Eigen::MatrixXd A;\n    if(input.size() == 0) return A;\n\n    int size = input[0].size();\n\n    std::vector< std::pair<double, double> > minmax(size, std::make_pair(std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()));\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        for(int j = 0; j < i->size(); ++j) {\n            double val = (*i)[j];\n            if(val < minmax[j].first) {\n                minmax[j] = std::make_pair(val, minmax[j].second);\n            }\n            if(val > minmax[j].second) {\n                minmax[j] = std::make_pair(minmax[j].first, val);\n            }\n        }\n    }\n\n    A = Eigen::MatrixXd::Identity(size, size);\n    for(unsigned int i = 0; i < minmax.size(); ++i) {\n        A(i, i) = 1.0/(minmax[i].second - minmax[i].first);\n    }\n\n    return A;\n}\n\nstd::vector<Eigen::VectorXd> scale(const Eigen::MatrixXd& ScaleA, const std::vector<Eigen::VectorXd>& input) {\n    std::vector<Eigen::VectorXd> scaled_input;\n    for(std::vector<Eigen::VectorXd>::const_iterator i = input.begin(); i != input.end(); ++i) {\n        scaled_input.push_back(ScaleA * (*i));\n    }\n\n    return scaled_input;\n}\n\nEigen::MatrixXd neighborhood_components_analysis(const std::vector<Eigen::VectorXd>& input, const std::vector<std::string>& label, const Eigen::MatrixXd& init, unsigned int iterations, double learning_rate) {\n    Eigen::MatrixXd A = init;\n    for(unsigned int it = 0; it < iterations; ++it) {\n        unsigned int i = it % input.size();\n\n        double softmax_normalization = 0.0;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            softmax_normalization += std::exp(-(A*input[i] - A*input[k]).squaredNorm());\n        }\n\n        std::vector<double> softmax;\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) softmax.push_back(0.0);\n            else {\n                softmax.push_back(std::exp(-(A*input[i] - A*input[k]).squaredNorm()) / softmax_normalization);\n            }\n        }\n\n        double p = 0.0;\n        for(unsigned int k = 0; k < softmax.size(); ++k) {\n            if(label[k] == label[i]) p += softmax[k];\n        }\n\n        Eigen::MatrixXd first_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        Eigen::MatrixXd second_term = Eigen::MatrixXd::Zero(input[0].size(), input[0].size());\n        for(unsigned int k = 0; k < input.size(); ++k) {\n            if(k == i) continue;\n            Eigen::VectorXd xik = input[i] - input[k];\n            Eigen::MatrixXd term = softmax[k] * (xik * xik.transpose());\n\n            first_term += term;\n            if(label[k] == label[i]) second_term += term;\n        }\n        first_term *= p;\n\n        A += learning_rate*A*(first_term - second_term);\n    }\n\n    return A;\n}\n\n#endif // NCA_HPP\n", "meta": {"hexsha": "ea9de495e0b1bcf8ca7459d29eefdd86c1734542", "size": 3792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nca.hpp", "max_stars_repo_name": "jhseu/nca", "max_stars_repo_head_hexsha": "2e0bf94661079e61bdc5ce89f1e8d0d6312d676d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-07-23T12:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T11:14:01.000Z", "max_issues_repo_path": "nca.hpp", "max_issues_repo_name": "beniz/nca", "max_issues_repo_head_hexsha": "555e1f7b28018fa48696c805a5e4d85294848955", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nca.hpp", "max_forks_repo_name": "beniz/nca", "max_forks_repo_head_hexsha": "555e1f7b28018fa48696c805a5e4d85294848955", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-10-26T02:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-04T06:34:15.000Z", "avg_line_length": 33.8571428571, "max_line_length": 208, "alphanum_fraction": 0.5516877637, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5687539215061093}}
{"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 \"vision-precomp.h\"\t // Precompiled headers\n//\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n\n#include \"posit.h\"\n\nmrpt::vision::pnp::posit::posit(\n\tEigen::MatrixXd obj_pts_, Eigen::MatrixXd img_pts_,\n\tEigen::MatrixXd camera_intrinsic_, int n0)\n{\n\tobj_pts = obj_pts_;\n\timg_pts = img_pts_.block(0, 0, n0, 2);\n\tcam_intrinsic = camera_intrinsic_;\n\tR = Eigen::MatrixXd::Identity(3, 3);\n\tt = Eigen::VectorXd::Zero(3);\n\tf = (cam_intrinsic(0, 0) + cam_intrinsic(1, 1)) / 2;\n\n\tobj_matrix =\n\t\t(obj_pts.transpose() * obj_pts).inverse() * obj_pts.transpose();\n\n\tn = n0;\n\n\tobj_vecs = Eigen::MatrixXd::Zero(n0, 3);\n\n\tfor (int i = 0; i < n; i++)\n\t\tobj_vecs.row(i) = obj_pts.row(i) - obj_pts.row(0);\n\n\timg_vecs = Eigen::MatrixXd::Zero(n0, 2);\n\timg_vecs_old = img_vecs;\n\n\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\n\tint i;\n\tdouble scale;\n\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\n\tI0_norm = I0.norm();\n\tJ0_norm = J0.norm();\n\n\tscale = (I0_norm + J0_norm) / 2;\n\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\n\t/* Computing ROTATION */\n\tr1 = I0 / I0_norm;\n\tr2 = J0 / J0_norm;\n\tr3 = r1.cross(r2);\n\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,\n1995.\n*/\nbool mrpt::vision::pnp::posit::compute_pose(\n\tEigen::Ref<Eigen::Matrix3d> R_, Eigen::Ref<Eigen::Vector3d> t_)\n{\n\tEigen::FullPivLU<Eigen::MatrixXd> lu(obj_pts);\n\tif (lu.rank() < 3) return false;\n\n\tint i, iCount;\n\tlong imageDiff = 1000;\n\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\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\n\t\t\t// Corrected image vectors\n\t\t\tfor (i = 0; i < n; i++)\n\t\t\t{\n\t\t\t\timg_vecs.row(i) =\n\t\t\t\t\timg_pts.row(i) * (1 + epsilons(i)) - img_pts.row(0);\n\t\t\t}\n\n\t\t\timageDiff = this->get_img_diff();\n\t\t}\n\n\t\timg_vecs_old = img_vecs;\n\n\t\tthis->POS();\n\n\t\tif (iCount > 0 && imageDiff == 0) break;\n\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}\n\tR_ = R;\n\tt_ = t;\n\n\treturn true;\n}\n\nlong mrpt::vision::pnp::posit::get_img_diff()\n{\n\tdouble sumOfDiffs = 0;\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tsumOfDiffs += std::abs(\n\t\t\t\tfloor(0.5 + img_vecs(i, j)) - floor(0.5 + img_vecs_old(i, j)));\n\t\t}\n\t}\n\treturn static_cast<long>(sumOfDiffs);\n}\n", "meta": {"hexsha": "28e5a58675ccd5b634c7d2217ccabff5901613c9", "size": 3487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/posit.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/vision/src/pnp/posit.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/vision/src/pnp/posit.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 22.7908496732, "max_line_length": 80, "alphanum_fraction": 0.5497562375, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727028, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5687539169463596}}
{"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\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(double focalLen, double pxDim, int width, int height)\n{\n\n    focalLen = focalLen * 10e-3;\n    double u0 = width / 2.0;\n    double v0 = height / 2.0;\n    Matrix4h camMat;\n    double diagEntry = focalLen / pxDim;\n    camMat << diagEntry, 0.0d, u0, 0.0d,\n        0.0d, diagEntry, v0, 0.0d,\n        0.0d, 0.0d, 1.0d, 0.0d,\n        0.0d, 0.0d, 0.0d, 1.0d;\n\n    return camMat;\n}\n\nMatrix4h getInvCameraMat(double focalLen, double pxDim, int width, int height)\n{\n    focalLen = focalLen * 10e-3;\n    double u0 = width / 2.0;\n    double v0 = height / 2.0;\n    Matrix4h camMat;\n    camMat << pxDim / focalLen, 0.0d, -pxDim * u0 / focalLen, 0.0d,\n        0.0d, pxDim / focalLen, -pxDim * v0 / focalLen, 0.0d,\n        0.0d, 0.0d, 1.0d, 0.0d,\n        0.0d, 0.0d, 0.0d, 1.0d;\n\n    return camMat;\n}\n\nMatrix4h getTransMatProjToCam()\n{\n    Matrix4h transMat;\n    Expr f64 = cast<double>(0.1d);\n    transMat << cast<double>(0.9945219), 0.0d, -0.10452846d, -0.2d,\n        0.0d, 1.0d, 0.0d, 0.0d,\n        0.10452846d, 0.0d, 0.9945219d, 0.0d,\n        0.0d, 0.0d, 0.0d, 1.0d;\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<double> &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 saveImageEXR(Expr result, int width, int height, const char fileName[])\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = result;\n    Buffer<double> 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    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<double> 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 = \"depth-image-gt.exr\";\n    const double FOCAL_LEN = 36.1;\n    const double PX_DIM = 10 * 10e-5;\n\n    Array2D<Rgba> pixels;\n    int width, height;\n    tie(width, height) = readOpenEXR(INPUTFILE.c_str(), pixels);\n    Buffer<double> input(width, height);\n    exrArrayToHalideBuffer(pixels, input, width, height);\n    cout << \"Width: \" << width << \"  Height: \" << height << endl;\n    Matrix4h camMat = getCameraMatrix(FOCAL_LEN, PX_DIM, width, height);\n    Matrix4h camMatInv = getInvCameraMat(FOCAL_LEN, PX_DIM, width, height);\n    Matrix4h transfMatProjToCam = getTransMatProjToCam();\n    cout << \"Camera matrix\" << endl;\n    cout << camMat << endl;\n    cout << \"Inverse camera matrix\" << endl;\n    cout << camMatInv << endl;\n    cout << camMatInv(0, 0) << endl;\n    cout << \"Transformation matrix projector to camera\" << endl;\n    cout << transfMatProjToCam << endl;\n\n    Expr zDepthCam = input(x, y);\n    Vector4h pxCam{x, y, 1.0f, 0.0f};\n    Vector4h normCam = camMatInv * pxCam;\n    debugImageEXR(normCam(0), normCam(1), normCam(2), width, height, \"normCam.exr\");\n    Vector4h ptCam = normCam / normCam(2) * zDepthCam;\n    ptCam(3) = 1.0f;\n    debugImageEXR(ptCam(0), ptCam(1), ptCam(2), width, height, \"ptCam.exr\");\n    Vector4h ptProj = transfMatProjToCam * ptCam;\n    debugImageEXR(ptProj(0), ptProj(1), ptProj(2), width, height, \"ptProj.exr\");\n    Vector4h normProj = ptProj / ptProj(2);\n    ptProj(3) = 0.0f;\n    Vector4h pxProj = camMat * normProj;\n    //normProj = normProj / normProj(2);\n    debugImageEXR(pxProj(0), pxProj(1), pxProj(2), width, height, \"normProj.exr\");\n    Expr xPxProj = pxProj(0);\n    //saveImage(xValProj, width, height, \"x-val-proj-gt\");\n    saveImageEXR(xPxProj, width, height, \"x-val-proj-gt.exr\");\n\n    return 0;\n}\n", "meta": {"hexsha": "e7c0783e1850b97eafa4f31d28bc18232e4090b0", "size": 7279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "structured_light/cpp/depth-img-to-proj-x/depthImgToProjX_double.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_double.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_double.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": 31.5108225108, "max_line_length": 121, "alphanum_fraction": 0.6069515043, "num_tokens": 2455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5687539159520701}}
{"text": "#ifndef _COCONUT_PULP_MATH_MATRIX_HPP_\n#define _COCONUT_PULP_MATH_MATRIX_HPP_\n\n#include <array>\n#include <cmath>\n#include <type_traits>\n#include <iosfwd>\n#include <algorithm>\n#include <functional>\n\n#include <boost/operators.hpp>\n\n#include \"coconut-tools/utils/InfixOstreamIterator.hpp\"\n\n#include \"Angle.hpp\"\n#include \"Handedness.hpp\"\n#include \"Vector.hpp\"\n#include \"ScalarEqual.hpp\"\n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\ntemplate <class NextViewType, class GetElementFunc>\nclass MatrixView {\npublic:\n\n\tusing MatrixType = typename GetElementFunc::MatrixType;\n\n\tusing Scalar = typename MatrixType::Scalar;\n\n\tstatic const auto ROWS = GetElementFunc::ROWS;\n\n\tstatic const auto COLUMNS = GetElementFunc::COLUMNS;\n\n\tconstexpr MatrixView(NextViewType nextView, GetElementFunc getElementFunc = GetElementFunc()) :\n\t\tnext_(nextView), // TODO: can't use std::move here when NextViewType is a reference. Figure out this view type better.\n\t\tgetElementFunc_(std::move(getElementFunc))\n\t{\n\t}\n\n\tconstexpr auto get(size_t row, size_t column) const noexcept -> decltype(auto) {\n\t\treturn getElementFunc_(next_, row, column);\n\t}\n\n\ttemplate <size_t ROWS_ = ROWS>\n\tauto determinant() const noexcept {\n\t\tstatic_assert(ROWS_ == ROWS, \"Rows count changed\");\n\t\tstatic_assert(ROWS == COLUMNS, \"Determinant only available for square matrices\");\n\n\t\tauto result = MatrixType::Scalar(0);\n\t\tfor (size_t columnIndex = 0; columnIndex < COLUMNS; ++columnIndex) {\n\t\t\tconst auto absElement = get(0, columnIndex) * submatrix(*this, 0, columnIndex).determinant();\n\t\t\tif (columnIndex % 2 == 0) {\n\t\t\t\tresult += absElement;\n\t\t\t} else {\n\t\t\t\tresult -= absElement;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\ttemplate <>\n\tauto determinant<1>() const noexcept {\n\t\tstatic_assert(ROWS == COLUMNS, \"Determinant only available for square matrices\");\n\t\treturn get(0, 0);\n\t}\n\n\tauto cofactor(size_t rowIndex, size_t columnIndex) const noexcept {\n\t\tconst auto det = submatrix(*this, rowIndex, columnIndex).determinant();\n\t\treturn ((rowIndex + columnIndex) % 2 == 0) ? det : -det;\n\t}\n\n\ttemplate <size_t ROWS_ = ROWS>\n\tauto inverse() const noexcept {\n\t\tstatic_assert(ROWS_ == ROWS, \"Rows count changed\");\n\t\tstatic_assert(ROWS == COLUMNS, \"Inverse only available for square matrices\");\n\n\t\tconst auto det = determinant();\n\t\tassert(det != Scalar(0));\n\t\tconst auto detInverse = Scalar(1) / det;\n\n\t\tauto result = MatrixType();\n\n\t\tfor (size_t rowIndex = 0; rowIndex < COLUMNS; ++rowIndex) {\n\t\t\tfor (size_t columnIndex = 0; columnIndex < COLUMNS; ++columnIndex) {\n\t\t\t\tresult[rowIndex][columnIndex] = detInverse * cofactor(columnIndex, rowIndex);\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\nprivate:\n\n\tNextViewType next_;\n\n\tGetElementFunc getElementFunc_;\n\n};\n\ntemplate <class MatrixT>\nclass MatrixViewFunc {\npublic:\n\n\tusing MatrixType = MatrixT;\n\n\tstatic const auto ROWS = MatrixType::ROWS;\n\n\tstatic const auto COLUMNS = MatrixType::COLUMNS;\n\n\tconstexpr auto operator()(MatrixType& matrix, size_t row, size_t column) const noexcept\n\t\t-> decltype(auto)\n\t{\n\t\treturn matrix[row][column];\n\t}\n\n};\n\ntemplate <class MatrixType>\nconstexpr auto viewMatrix(MatrixType& matrix) noexcept {\n\treturn MatrixView<MatrixType&, MatrixViewFunc<MatrixType>>(matrix);\n}\n\ntemplate <class NextViewType>\nclass TransposedViewFunc {\npublic:\n\n\tusing MatrixType = typename NextViewType::MatrixType;\n\n\tstatic const auto ROWS = NextViewType::ROWS;\n\n\tstatic const auto COLUMNS = NextViewType::COLUMNS;\n\n\tconstexpr auto operator()(NextViewType nextView, size_t row, size_t column) const noexcept\n\t\t-> decltype(auto)\n\t{\n\t\treturn nextView.get(column, row);\n\t}\n\n};\n\ntemplate <class NextViewType>\nconstexpr auto transpose(NextViewType nextView) noexcept {\n\treturn MatrixView<NextViewType, TransposedViewFunc<NextViewType>>(std::move(nextView));\n}\n\ntemplate <class MatrixType>\nconstexpr auto viewMatrixTransposed(MatrixType& matrix) noexcept {\n\treturn transpose(viewMatrix(matrix));\n}\n\ntemplate <class NextViewType>\nclass SubmatrixViewFunc {\npublic:\n\n\tusing MatrixType = typename NextViewType::MatrixType;\n\n\tstatic const auto ROWS = NextViewType::ROWS - 1;\n\n\tstatic const auto COLUMNS = NextViewType::COLUMNS - 1;\n\n\tconstexpr SubmatrixViewFunc(size_t noRow, size_t noColumn) :\n\t\tnoRow_(noRow),\n\t\tnoColumn_(noColumn)\n\t{\n\t\tassert(noRow < NextViewType::ROWS);\n\t\tassert(noColumn < NextViewType::COLUMNS);\n\t}\n\n\tconstexpr auto operator()(NextViewType nextView, size_t row, size_t column) const noexcept\n\t\t-> decltype(auto)\n\t{\n\t\treturn nextView.get((row < noRow_) ? row : row + 1, (column < noColumn_) ? column : column + 1);\n\t}\n\nprivate:\n\n\tsize_t noRow_;\n\n\tsize_t noColumn_;\n\n};\n\ntemplate <class NextViewType>\nconstexpr auto submatrix(NextViewType nextView, size_t noRow, size_t noColumn) noexcept {\n\treturn MatrixView<NextViewType, SubmatrixViewFunc<NextViewType>>(\n\t\tstd::move(nextView), SubmatrixViewFunc<NextViewType>(noRow, noColumn));\n}\n\ntemplate <class MatrixType>\nconstexpr auto viewSubmatrix(MatrixType& matrix, size_t noRow, size_t noColumn) noexcept {\n\treturn submatrix(viewMatrix(matrix), noRow, noColumn);\n}\n\ntemplate <\n\tclass ScalarType,\n\tsize_t ROWS_PARAM,\n\tsize_t COLUMNS_PARAM,\n\tclass ScalarEqualityFunc = ScalarEqual<ScalarType>\n\t>\nclass Matrix :\n\tboost::equality_comparable<Matrix<ScalarType, ROWS_PARAM, COLUMNS_PARAM, ScalarEqualityFunc>,\n\tboost::additive<Matrix<ScalarType, ROWS_PARAM, COLUMNS_PARAM, ScalarEqualityFunc>,\n\tboost::multiplicative<Matrix<ScalarType, ROWS_PARAM, COLUMNS_PARAM, ScalarEqualityFunc>, ScalarType\n\t>>>\n{\npublic:\n\n\tusing Scalar = ScalarType;\n\n\tstatic const auto ROWS = ROWS_PARAM;\n\n\tstatic const auto COLUMNS = COLUMNS_PARAM;\n\n\tstatic const Matrix IDENTITY;\n\n\tusing Row = Vector<ScalarType, COLUMNS, ScalarEqualityFunc>;\n\n\tusing Column = Vector<ScalarType, ROWS, ScalarEqualityFunc>;\n\n\tstatic constexpr auto IS_ROW_MAJOR = true;\n\n\tstatic constexpr auto IS_COLUMN_MAJOR = !IS_ROW_MAJOR;\n\n\tstatic constexpr auto VECTOR_IS_SINGLE_ROW_MATRIX = false;\n\n\tstatic constexpr auto VECTOR_IS_SINGLE_COLUMN_MATRIX = !VECTOR_IS_SINGLE_ROW_MATRIX;\n\n\t// --- CONSTRUCTORS AND OPERATORS\n\n\ttemplate <class... CompatibleVectorType>\n\texplicit constexpr Matrix(CompatibleVectorType&&... rows) noexcept :\n\t\telements_{ std::forward<CompatibleVectorType>(rows)... }\n\t{\n\t\tstatic_assert(sizeof...(rows) == ROWS, \"Bad number of arguments\");\n\t}\n\n\ttemplate <class... CompatibleScalarType>\n\texplicit constexpr Matrix(std::initializer_list<CompatibleScalarType>... rows) noexcept :\n\t\telements_{ rows... }\n\t{\n\t\tstatic_assert(sizeof...(rows) == ROWS || sizeof...(rows) == 0, \"Bad number of arguments\");\n\t}\n\n\ttemplate <class NVT, class GEF>\n\tMatrix(const MatrixView<NVT, GEF>& view) {\n\t\tfor (size_t rowIndex = 0; rowIndex < ROWS; ++rowIndex) {\n\t\t\tfor (size_t columnIndex = 0; columnIndex < COLUMNS; ++columnIndex) {\n\t\t\t\t(*this)[rowIndex][columnIndex] = view.get(rowIndex, columnIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const Matrix& matrix) {\n\t\tos << '<';\n\t\tstd::copy(matrix.elements_.begin(), matrix.elements_.end(),\n\t\t\tcoconut_tools::InfixOstreamIterator<Row>(os, \", \"));\n\t\tos << '>';\n\t\treturn os;\n\t}\n\n\tfriend bool operator==(const Matrix& lhs, const Matrix& rhs) noexcept {\n\t\treturn std::equal(lhs.elements_.begin(), lhs.elements_.end(), rhs.elements_.begin());\n\t}\n\n\tMatrix& operator+=(const Matrix& other) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), other.elements_.begin(), elements_.begin(), std::plus<>());\n\t\treturn *this;\n\t}\n\n\tMatrix& operator-=(const Matrix& other) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), other.elements_.begin(), elements_.begin(), std::minus<>());\n\t\treturn *this;\n\t}\n\n\tMatrix operator-() noexcept {\n\t\tauto result = Matrix();\n\t\tstd::transform(elements_.begin(), elements_.end(), result.elements_.begin(), std::negate<>());\n\t\treturn result;\n\t}\n\n\ttemplate <class CompatibleMatrixType>\n\tfriend std::enable_if_t<\n\t\tCOLUMNS == CompatibleMatrixType::ROWS,\n\t\tMatrix<ScalarType, ROWS, CompatibleMatrixType::COLUMNS, ScalarEqualityFunc>\n\t\t> operator*(const Matrix& lhs, const CompatibleMatrixType& rhs) noexcept\n\t{\n\t\tauto result = Matrix<ScalarType, ROWS, CompatibleMatrixType::COLUMNS, ScalarEqualityFunc>();\n\t\tfor (auto rowIndex = 0u; rowIndex < ROWS; ++rowIndex) {\n\t\t\tfor (auto columnIndex = 0u; columnIndex < CompatibleMatrixType::COLUMNS; ++columnIndex) {\n\t\t\t\tresult[rowIndex][columnIndex] = dot(lhs[rowIndex], rhs.column(columnIndex));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\ttemplate <class CompatibleMatrixType>\n\tstd::enable_if_t<\n\t\tCOLUMNS == ROWS &&\n\t\tCompatibleMatrixType::COLUMNS == CompatibleMatrixType::ROWS &&\n\t\tROWS == CompatibleMatrixType::ROWS,\n\t\tMatrix&\n\t\t> operator*=(const CompatibleMatrixType& rhs) noexcept\n\t{\n\t\tconst auto result = *this * rhs;\n\t\t*this = result;\n\t\treturn *this;\n\t}\n\n\tMatrix& operator*=(Scalar scalar) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), elements_.begin(), [scalar](auto element) {\n\t\t\treturn element * scalar;\n\t\t});\n\t\treturn *this;\n\t}\n\n\tfriend Vector<Scalar, ROWS, ScalarEqualityFunc> operator*(\n\t\tconst Matrix& matrix,\n\t\tconst Vector<Scalar, ROWS, ScalarEqualityFunc>& vector\n\t\t) noexcept\n\t{\n\t\tauto result = Vector<Scalar, ROWS, ScalarEqualityFunc>();\n\t\tfor (auto columnIndex = 0u; columnIndex < COLUMNS; ++columnIndex) {\n\t\t\tresult[columnIndex] = dot(matrix.column(columnIndex), vector);\n\t\t}\n\t\treturn result;\n\t}\n\n\tMatrix& operator/=(Scalar scalar) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), elements_.begin(), [scalar](auto element) {\n\t\t\treturn element / scalar;\n\t\t});\n\t\treturn *this;\n\t}\n\n\t// --- MATRIX-SPECIFIC OPERATIONS\n\n\tconstexpr Matrix<Scalar, COLUMNS, ROWS, ScalarEqualityFunc> transpose() const noexcept {\n\t\treturn viewMatrixTransposed(*this);\n\t}\n\n\tScalar determinant() const noexcept {\n\t\treturn viewMatrix(*this).determinant();\n\t}\n\n\tScalar cofactor(size_t rowIndex, size_t columnIndex) const noexcept {\n\t\treturn viewMatrix(*this).cofactor(rowIndex, columnIndex);\n\t}\n\n\tMatrix inverse() const noexcept {\n\t\treturn viewMatrix(*this).inverse();\n\t}\n\n\t// --- ACCESSORS\n\n\tconstexpr const Row& operator[](size_t rowIndex) const noexcept {\n\t\tassert(rowIndex < ROWS);\n\t\treturn elements_[rowIndex];\n\t}\n\n\tRow& operator[](size_t rowIndex) noexcept {\n\t\tassert(rowIndex < ROWS);\n\t\treturn elements_[rowIndex];\n\t}\n\n\ttemplate <size_t ROW, size_t COLUMN>\n\tconstexpr std::enable_if_t<(ROW < ROWS && COLUMN < COLUMNS), const Scalar&> get() const noexcept {\n\t\treturn elements_[ROW].get<COLUMN>();\n\t}\n\n\ttemplate <size_t ROW, size_t COLUMN>\n\tstd::enable_if_t<(ROW < ROWS && COLUMN < COLUMNS), Scalar&> get() noexcept {\n\t\treturn elements_[ROW].get<COLUMN>();\n\t}\n\n\tconstexpr const Row& row(size_t rowIndex) const noexcept {\n\t\tassert(rowIndex < ROWS);\n\t\treturn elements_[rowIndex];\n\t}\n\n\tRow& row(size_t rowIndex) noexcept {\n\t\tassert(rowIndex < ROWS);\n\t\treturn elements_[rowIndex];\n\t}\n\n\tColumn column(size_t columnIndex) const noexcept {\n\t\tassert(columnIndex < COLUMNS);\n\t\tauto column = Column();\n\t\tgetColumn_<>(column, columnIndex);\n\t\treturn column;\n\t}\n\n\tauto view() const noexcept {\n\t\treturn viewMatrix(*this);\n\t}\n\n\tauto view() noexcept {\n\t\treturn viewMatrix(*this);\n\t}\n\nprivate:\n\n\tstd::array<Row, ROWS> elements_;\n\n\ttemplate <size_t ROW = 0>\n\tvoid getColumn_(Column& column, size_t columnIndex) const {\n\t\tcolumn.get<ROW>() = elements_[ROW][columnIndex];\n\t\tgetColumn_<ROW + 1>(column, columnIndex);\n\t}\n\n\ttemplate <>\n\tvoid getColumn_<ROWS>(Column&, size_t) const {\n\t}\n\n};\n\nusing Matrix4x4 = Matrix<float, 4, 4>;\nstatic_assert(sizeof(Matrix4x4) == sizeof(float) * 16, \"Empty base optimisation didn't work\");\nstatic_assert(std::is_trivially_copyable<Matrix4x4>::value, \"Matrix is not trivially copyable\");\n\nnamespace detail {\n\ntemplate <class ST, size_t R, size_t C, class SEF>\nMatrix<ST, R, C, SEF> makeIdentity() {\n\tauto identity = Matrix<ST, R, C, SEF>();\n\tfor (auto row = 0u; row < R; ++row) {\n\t\tidentity[row][row] = ST(1);\n\t}\n\treturn identity;\n}\n\n} // namespace detail\n\ntemplate <class ST, size_t R, size_t C, class SEF>\nconst Matrix<ST, R, C, SEF>\tMatrix<ST, R, C, SEF>::IDENTITY =\n\tdetail::makeIdentity<ST, R, C, SEF>();\n\n} // namespace math\n\nusing math::Matrix;\nusing math::Matrix4x4;\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_MATH_MATRIX_HPP_ */\n", "meta": {"hexsha": "aed9236c050f287cd1a60b9a8801ee7e8f67288d", "size": 12135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Matrix.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Matrix.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Matrix.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0870535714, "max_line_length": 120, "alphanum_fraction": 0.7244334569, "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.5687538999528127}}
{"text": "#ifndef RSVD_GRAMSCHMIDT_HPP_\n#define RSVD_GRAMSCHMIDT_HPP_\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <limits>\n\nnamespace Rsvd {\n\nnamespace Internal {\n\n/// \\brief Orthonormalize matrix columns inplace. Deflate if needed.\n///\n/// \\warning This is a self-implemented algorithm, use it with caution. Use\n/// #Rsvd::SubspaceIterationConditioner::Lu or #Rsvd::SubspaceIterationConditioner::Qr if numerical\n/// stability and implementation quality is important.\n///\n/// \\long This function implements the modified Gram--Schmidt process with deflation.\n///\n/// The deflation is implemented as follows: Let \\f$i\\f$ be the index of the current matrix column.\n/// Let \\f$n_i\\f$ be its norm after projection onto a subspace orthogonal to the subspace spanned\n/// by the previous columns \\f$1, \\ldots, n - 1\\f$. Obviously, if \\f$n_i\\f$ is equal to zero, then\n/// the \\f$i\\f$-th column is a linear combination of previous columns. Due to the limited precision\n/// of the floating-point computations, \\f$n_i\\f$ will be small but greater than zero. Hence, we\n/// use the following heuristic rule: If \\f[ n_i < \\max\\{n_1, \\ldots, n_{i - 1}\\} \\cdot\n/// \\varepsilon_{\\mathrm{mach}} \\cdot 100, \\f] then the \\f$i\\f$-th column is deemed to be linearly\n/// dependent and is filled with zeros.\n///\n/// Here, \\f$ \\varepsilon_{\\mathrm{mach}} \\f$ is the machine epsilon.\n///\n/// \\note Although this function deflates if needed, it asserts that the matrix has fewer columns\n/// than rows. This might help during debugging. If compiled without assertions, this function will\n/// silently deflate on column rank loss.\n///\n/// \\tparam MatrixType Eigen matrix type.\n///\n/// \\param a Matrix whose columns should be orthonormalized inplace. The matrix can be over a real\n/// or complex field.\ntemplate <typename MatrixType> void modifiedGramSchmidt(MatrixType &a) {\n  using RealType = typename Eigen::NumTraits<typename MatrixType::Scalar>::Real;\n\n  RealType largestNormSeen{0};\n  // 100 is just an educated guess...\n  const RealType tol{100 * std::numeric_limits<RealType>::epsilon()};\n\n  // If a matrix has fewer rows than columns then the columns are linearly dependent\n  assert(a.cols() <= a.rows());\n\n  Eigen::Index currCol;\n  for (currCol = 0; currCol < a.cols(); ++currCol) {\n    for (Eigen::Index prevCol{0}; prevCol < currCol; ++prevCol) {\n      /// \\note Implementation detail: The order in the dot product is important for vectors over\n      /// complex fields!\n      a.col(currCol) -= a.col(prevCol).dot(a.col(currCol)) * a.col(prevCol);\n    }\n\n    // If the current column has near zero norm, it is a linear combination of previous columns\n    const auto currColNorm{a.col(currCol).norm()};\n    if (currColNorm < tol * largestNormSeen) {\n      // Deflate\n      a.col(currCol).setZero();\n    } else {\n      // Normalize\n      a.col(currCol) /= currColNorm;\n      largestNormSeen = std::max(largestNormSeen, currColNorm);\n    }\n  }\n}\n\n} // namespace Internal\n\n} // namespace Rsvd\n\n#endif\n", "meta": {"hexsha": "283759f29b4be5b10cbf0efa0683faad70d2d1ae", "size": 2978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rsvd/GramSchmidt.hpp", "max_stars_repo_name": "mooreryan/coda", "max_stars_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T09:12:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T15:40:04.000Z", "max_issues_repo_path": "include/rsvd/GramSchmidt.hpp", "max_issues_repo_name": "mooreryan/coda", "max_issues_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rsvd/GramSchmidt.hpp", "max_forks_repo_name": "mooreryan/coda", "max_forks_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T18:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T18:45:56.000Z", "avg_line_length": 39.7066666667, "max_line_length": 99, "alphanum_fraction": 0.7055070517, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.5686839780533527}}
{"text": "#include <limits>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n\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\nstruct Request {\n    int si;\n    int ti;\n    int di;\n    int ai;\n    int pi;\n};\n\nvoid testcase() {\n    long n, s;\n    std::cin >> n >> s;\n    std::vector<int> l(s);\n    long total_cars = 0;\n    for(int i = 0; i < s; i++) {\n        std::cin >> l[i];\n        total_cars += l[i];\n    }\n    \n    std::vector<std::set<int>> timestamps_per_s(s);\n    \n    std::vector<Request> requests(n);\n    long max_arrival = 100'000;\n    long max_p = 100;\n    for(int i = 0; i < n; i++) {\n        int si, ti, di, ai, pi;\n        std::cin >> si >> ti >> di >> ai >> pi;\n        requests[i] = {si - 1, ti - 1, di, ai, pi};\n        if(di != 0) timestamps_per_s[si - 1].insert(di);\n        if(ai != max_arrival) timestamps_per_s[ti - 1].insert(ai);\n        // std::cerr << s * di / 30 + si - 1 << \" \" << s * ai / 30 + ti - 1 <<  \" \" << pi << std::endl;\n    }\n\n    int sum_dist_nodes = 0;\n    std::vector<std::unordered_map<int, int>> map_to_g(s); // map (si, ti) -> j in graph\n    for(int i = 0; i < s; i++) {\n        map_to_g[i].insert({0, sum_dist_nodes++});\n        map_to_g[i].insert({max_arrival, sum_dist_nodes++});\n        for(auto t : timestamps_per_s[i]) {\n            map_to_g[i].insert({t, sum_dist_nodes++});\n            // std::cerr << \"i \" << i << \" \" << t  << \"\\n\";\n        }\n    }\n    graph G(sum_dist_nodes);\n    const int v_source = boost::add_vertex(G);\n    const int v_sink = boost::add_vertex(G);\n    edge_adder adder(G);\n    \n    for(auto r : requests) {\n        int si, ti, di, ai, pi;\n        si = r.si; ti = r.ti; di = r.di;\n        ai = r.ai; pi = r.pi;\n        // std::cerr << -pi + max_p * (ai - di) << std::endl;\n        adder.add_edge(map_to_g[si].at(di) , map_to_g[ti].at(ai), 1, -pi + max_p * (ai - di));\n    }\n\n    for(int i = 0; i < s; i++) {\n        // source to time 0\n        adder.add_edge(v_source, map_to_g[i].at(0), l[i], 0);\n        adder.add_edge(map_to_g[i].at(max_arrival), v_sink, total_cars, 0);\n        // time 0 to first time\n        if(timestamps_per_s[i].size() > 0) {\n            auto t1 = timestamps_per_s[i].begin();\n            // zero to first time\n            adder.add_edge(map_to_g[i].at(0), map_to_g[i].at(*t1), total_cars, *t1 * max_p);\n            auto t2 = timestamps_per_s[i].begin(); t2++;\n            for(; t2 != timestamps_per_s[i].end(); t1++, t2++) {\n                adder.add_edge(map_to_g[i].at(*t1), map_to_g[i].at(*t2), total_cars, (*t2 - *t1) * max_p);\n            }\n            // second to last to max time\n            adder.add_edge(map_to_g[i].at(*t1), map_to_g[i].at(max_arrival), total_cars, (max_arrival - *t1) * max_p);\n        } else {\n            adder.add_edge(map_to_g[i].at(0), map_to_g[i].at(max_arrival), total_cars, (max_arrival) * max_p);\n        }\n    }\n\n    boost::successive_shortest_path_nonnegative_weights(G, v_source, v_sink);\n    long cost = boost::find_flow_cost(G);\n    // std::cout << -(cost) << \"\\n\";\n    std::cout << -(cost - (total_cars * max_p * max_arrival)) << \"\\n\";\n\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//   std::cerr << v_source << \" \" << v_sink;\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//               << \" with capacity \" << c_map[edge] \n//               << \" runs \" << flow_through_edge\n//               << \" units of flow (negative for reverse direction). \\n\";\n//   }\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": "c301276944732e5c030643a6e8a253d972bd87a7", "size": 5738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week12-car_sharing/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-car_sharing/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-car_sharing/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": 37.0193548387, "max_line_length": 118, "alphanum_fraction": 0.5845242245, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5686101460420999}}
{"text": "#ifndef CANNON_ML_RECURSIVE_PIECEWISE_LSTD_H\n#define CANNON_ML_RECURSIVE_PIECEWISE_LSTD_H \n\n/*!\n * \\file cannon/ml/piecewise_recursive_lstd.hpp\n * \\brief File containing PiecewiseRecursiveLSTDFilter class definition.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Class representing a Least-Squares Temporal Difference (LSTD)\n     * approximator using a feature set that produces a piecewise-affine value\n     * function approximation. This is for use in reinforcement learning\n     * algorithms. This version of the algorithm is similar to a recursive\n     * least squares filter.\n     */\n    class PiecewiseRecursiveLSTDFilter {\n      public:\n        PiecewiseRecursiveLSTDFilter() = delete;\n\n        /*!\n         * \\brief Constructor taking state space dimension, number of affine\n         * regions, and discount factor.\n         */\n        PiecewiseRecursiveLSTDFilter(unsigned int in_dim, unsigned int num_refs, double\n            discount_factor, double alpha=1.0) : in_dim_(in_dim + 1),\n        param_dim_(in_dim_ * num_refs), num_refs_(num_refs),\n        discount_factor_(discount_factor), alpha_(alpha) {\n          a_inv_ = MatrixXd::Identity(param_dim_, param_dim_) * alpha_;\n          theta_ = VectorXd::Zero(param_dim_);\n        }\n\n        /*!\n         * \\brief Update this approximation in light of a single data point,\n         * which is a transition from one state to another with associated\n         * reward.\n         *\n         * \\param in_vec Feature vector for first state.\n         * \\param next_in_vec Feature vector for next state.\n         * \\param idx Region index for first state.\n         * \\param next_idx Region index for next state.\n         * \\param reward Reward associated with this state transition.\n         */\n        void process_datum(const VectorXd& in_vec, const VectorXd& next_in_vec,\n            unsigned int idx, unsigned int next_idx, double reward);\n\n        /*!\n         * \\brief Get the matrix representing the linear portion of the local,\n         * affine approximation in the region with for the input index.\n         *\n         * \\param idx Region index\n         *\n         * \\returns Estimated local linear approximation parameter matrix.\n         */\n        VectorXd get_mat(unsigned int idx) const;\n\n        /*!\n         * \\brief Predict the value of the input state using the estimated\n         * piecewise-affine value function.\n         *\n         * \\param in_vec Feature vector for the state.\n         * \\param idx Region index of the state.\n         *\n         * \\returns Value function prediction.\n         */\n        double predict(const VectorXd& in_vec, unsigned int idx) const;\n\n        /*!\n         * \\brief Reset this value function approximation.\n         */\n        void reset();\n\n      private:\n        /*!\n         * \\brief Make internal feature vector for the input state in the\n         * region with the input index.\n         *\n         * \\param in_vec Input features for state.\n         * \\param idx Region index for the state.\n         *\n         * \\returns Internal feature representation leading to piecewise-affine\n         * function.\n         */\n        SparseMatrix<double>\n        make_feature_vec_(VectorXd in_vec, unsigned int idx) const;\n\n        /*!\n         * \\brief Update approximation of the linear portion of the LSTD filter\n         * given a particular state transition.\n         *\n         * \\param a_inv_feat_t A^-1 * feat.transpose()\n         * \\param diff feat - (discount_factor_ * next_feat)\n         * \\param inv_denom 1.0 / (diff * A^-1 * feat^T)\n         */\n        void update_a_inv_(const Ref<const VectorXd> &a_inv_feat_t,\n                           const Ref<const SparseMatrix<double>> &diff,\n                           double inv_denom);\n\n        // Parameters\n        unsigned int in_dim_; //!< Dimension of input\n        unsigned int param_dim_; //!< Dimension of internal feature space\n        unsigned int num_refs_; //!< Number of linear regions\n        double discount_factor_; //!< Discount factor for value function\n        double alpha_; //!< L2 regularization parameter\n\n        // Matrices\n        MatrixXd a_inv_; //!< Linear portion of LSTD filter\n        VectorXd theta_; //!< Parameters of value function approximation\n    };\n    \n  } // namespace ml\n} // namespace cannon\n#endif /* ifndef CANNON_ML_RECURSIVE_PIECEWISE_LSTD_H */\n", "meta": {"hexsha": "812df40fbf9efe97401743f02634ee0e200b6156", "size": 4443, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/piecewise_recursive_lstd.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/piecewise_recursive_lstd.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/piecewise_recursive_lstd.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": 36.7190082645, "max_line_length": 87, "alphanum_fraction": 0.6297546703, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.56861014072023}}
{"text": "#ifndef ESKF_IMPL\n#define ESKF_IMPL\n\n#include \"ESKF.h\"\n#include \"utilities.h\"\n\n#include <Eigen/LU>\n#include <Wire.h>\n\n#ifndef SGN\n#define SGN(X) ((X > 0) - (X < 0))\n#endif\n\n#ifndef RAD_TO_DEG\n#define RAD_TO_DEG (180.0 / M_PI)\n#endif\n\n#ifndef DEG_TO_RAD\n#define DEG_TO_RAD (M_PI / 180.0)\n#endif\n\n#ifndef MS2_TO_G\n#define MS2_TO_G (1.0 / 9.81)\n#endif\n\n#ifndef G_TO_MS2\n#define G_TO_MS2 (9.81)\n#endif\n\nnamespace IMU_EKF\n{\n\ntemplate <typename precision>\nESKF<precision>::ESKF()\n{\n    init();\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::init()\n{\n    qref_ = Quaternion<precision>();\n    x_.setZero();\n    P_.setIdentity();\n    Q_.setIdentity();\n    // TODO don't hardcode this\n    Q_(0, 0) = 0.05;\n    Q_(1, 1) = 0.05;\n    Q_(2, 2) = 0.05;\n    Q_(3, 3) = 0.05;\n    Q_(4, 4) = 0.05;\n    Q_(5, 5) = 0.05;\n    Q_(6, 6) = 0.025;\n    Q_(7, 7) = 0.025;\n    Q_(8, 8) = 0.025;\n    Q_(9, 9) = 0.025;\n    Q_(10, 10) = 0.025;\n    Q_(11, 11) = 0.025;\n    Q_(12, 12) = 0.01;\n    Q_(13, 13) = 0.01;\n    Q_(14, 14) = 0.01;\n\n    R_Gyr_.setIdentity();\n    R_Gyr_(0, 0) = 0.0000045494 * DEG_TO_RAD;\n    R_Gyr_(1, 1) = 0.0000039704 * DEG_TO_RAD;\n    R_Gyr_(2, 2) = 0.0000093844 * DEG_TO_RAD;\n\n    R_Acc_.setIdentity();\n    R_Acc_(0, 0) = 0.0141615383 * G_TO_MS2;\n    R_Acc_(1, 1) = 0.0164647549 * G_TO_MS2;\n    R_Acc_(2, 2) = 0.0100094303 * G_TO_MS2;\n\n    R_Mag_.setIdentity();\n    R_Mag_(0, 0) = 0.00004;\n    R_Mag_(1, 1) = 0.00004;\n    R_Mag_(2, 2) = 0.00004;\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::initWithAcc(const float ax, const float ay, const float az)\n{\n    init();\n\n    // see https://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf\n    // rotation sequence R = Rx * Ry * Rz\n    // eq. 38\n    precision roll = std::atan2(ay, SGN(-az) * std::sqrt(az * az + 0.01 * ax * ax));\n    // eq. 37\n    precision pitch = std::atan(-ax / std::sqrt(ay * ay + az * az));\n\n    precision sr05 = std::sin(0.5 * roll);\n    precision cr05 = std::cos(0.5 * roll);\n    precision sp05 = std::sin(0.5 * pitch);\n    precision cp05 = std::cos(0.5 * pitch);\n    qref_ = Quaternion<precision>(sr05, 0, 0, cr05) * Quaternion<precision>(0, sp05, 0, cp05);\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::initWithAccAndMag(const float ax, const float ay, const float az, const float mx, const float my, const float mz, const Eigen::Matrix<precision, 3, 3> &Winv, const Eigen::Matrix<precision, 3, 1> &V)\n{\n    init();\n\n    // see https://cache.freescale.com/files/sensors/doc/app_note/AN3461.pdf\n    // rotation sequence R = Rx * Ry * Rz\n    // eq. 38\n    precision roll = std::atan2(ay, SGN(-az) * std::sqrt(az * az + 0.01 * ax * ax));\n    // eq. 37\n    precision pitch = std::atan(-ax / std::sqrt(ay * ay + az * az));\n\n    // see https://www.nxp.com/docs/en/application-note/AN4246.pdf\n    // eq. 6 - 10\n    precision sr = std::sin(roll);\n    precision cr = std::cos(roll);\n    precision sp = std::sin(pitch);\n    precision cp = std::cos(pitch);\n\n    Eigen::Matrix<precision, 3, 3> RxT;\n    RxT << 1, 0, 0,\n        0, cr, sr,\n        0, -sr, cr;\n    Eigen::Matrix<precision, 3, 3> RyT;\n    RyT << cp, 0, -sp,\n        0, 1, 0,\n        sp, 0, cp;\n\n    Eigen::Matrix<precision, 3, 1> Bp;\n    Bp << mx, my, mz;\n\n    Eigen::Matrix<precision, 3, 1> Bf;\n    Bf = RyT * RxT * Winv * (Bp - V);\n\n    precision yaw = -atan2(-Bf(1), Bf(0));\n\n    precision sr05 = std::sin(0.5 * roll);\n    precision cr05 = std::cos(0.5 * roll);\n    precision sp05 = std::sin(0.5 * pitch);\n    precision cp05 = std::cos(0.5 * pitch);\n    precision sy05 = std::sin(0.5 * yaw);\n    precision cy05 = std::cos(0.5 * yaw);\n\n    qref_ = Quaternion<precision>(sr05, 0, 0, cr05) * Quaternion<precision>(0, sp05, 0, cp05) * Quaternion<precision>(0, 0, sy05, cy05);\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::predict(precision dt)\n{\n    // eq. 23\n    Quaternion<precision> angular_velocity_quat(x_[12], x_[13], x_[14], 0);\n    qref_ += dt * ((0.5 * angular_velocity_quat) * qref_);\n    qref_.normalize();\n\n    Eigen::Matrix<precision, 9, 9> A;\n    A.setIdentity();\n    A(0, 3) = dt;\n    A(0, 6) = dt * dt * 0.5;\n    A(1, 4) = dt;\n    A(1, 7) = dt * dt * 0.5;\n    A(2, 5) = dt;\n    A(2, 8) = dt * dt * 0.5;\n    A(3, 6) = dt;\n    A(4, 7) = dt;\n    A(4, 8) = dt;\n\n    x_.segment(0, 9) = A * x_.segment(0, 9);\n    P_.topLeftCorner(9, 9) = A * P_.topLeftCorner(9, 9) * A.transpose() + dt * Q_.topLeftCorner(9, 9);\n\n    // eq. 38\n    Eigen::Matrix<precision, 3, 1> angular_velocity = x_.segment(12, 3);\n    Eigen::Matrix<precision, 3, 1> error = x_.segment(9, 3);\n    Eigen::Matrix<precision, 6, 6> Jac = Eigen::Matrix<precision, 6, 6>::Zero();\n    Jac.topLeftCorner(3, 3) = toCrossMatrix<precision>(error);\n    Jac.topRightCorner(3, 3) = -toCrossMatrix<precision>(angular_velocity);\n    // eq. 39\n    Eigen::Matrix<precision, 6, 6> G = Eigen::Matrix<precision, 6, 6>::Identity();\n    G.bottomRightCorner(3, 3) *= -1;\n\n    // eq. 33 adpated\n    P_.bottomRightCorner(6, 6) = Jac * P_.bottomRightCorner(6, 6) * Jac.transpose() + G * dt * Q_.bottomRightCorner(6, 6) * G.transpose();\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::correctGyr(const float gx, const float gy, const float gz)\n{\n    // z\n    Eigen::Matrix<precision, MEASSUREMENT_GYR_SIZE, 1> z;\n    z << gx * DEG_TO_RAD, gy * DEG_TO_RAD, gz * DEG_TO_RAD;\n\n    // Kalman Gain\n    // K = P * H' (H * P * H' + V * R * V')^-\n    // H = eye(3)\n    Eigen::Matrix<precision, 3, MEASSUREMENT_GYR_SIZE> K;\n    K = P_.bottomRightCorner(3, 3) * (P_.bottomRightCorner(3, 3) + R_Gyr_).inverse();\n\n    // x = x + K * (z - H * x)\n    x_.segment(12, 3) += K * (z - x_.segment(12, 3));\n\n    // P = (I - KH)P\n    Eigen::Matrix<precision, 3, 3> IKH = Eigen::Matrix<precision, 3, 3>::Identity();\n    IKH -= K;\n\n    P_.bottomRightCorner(3, 3) = IKH * P_.bottomRightCorner(3, 3);\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::correctAcc(const float ax, const float ay, const float az)\n{\n    // z\n    Eigen::Matrix<precision, MEASSUREMENT_ACC_SIZE, 1> z;\n    z << ax * G_TO_MS2, ay * G_TO_MS2, az * G_TO_MS2;\n\n    Eigen::Matrix<precision, 3, 1> gravity;\n    gravity << 0.0, 0.0, -9.81;\n\n    if (std::abs(z.norm() - 9.81) < 0.7)\n    {\n        // set acc to zero\n        // z\n        Eigen::Matrix<precision, 3, 1> z_acc = Eigen::Matrix<precision, 3, 1>::Zero();\n\n        // Kalman Gain\n        // K = P * H' (H * P * H' + V * R * V')^-\n        // H = eye(3)\n        Eigen::Matrix<precision, 3, 3> K_acc;\n        K_acc = P_.block(6, 6, 3, 3) * (P_.block(6, 6, 3, 3) + R_Acc_).inverse();\n\n        // x = x + K * (z - H * x)\n        x_.segment(6, 3) += K_acc * (z_acc - x_.segment(6, 3));\n\n        // P = (I - KH)P\n        Eigen::Matrix<precision, 3, 3> IKH = Eigen::Matrix<precision, 3, 3>::Identity();\n        IKH -= K_acc;\n\n        P_.block(6, 6, 3, 3) = IKH * P_.block(6, 6, 3, 3);\n\n        // correct tilt\n        Eigen::Matrix<precision, 3, 1> vi = gravity;\n\n        // eq. 42\n        Eigen::Matrix<precision, 3, 1> error = x_.segment(9, 3);\n        // Eigen::Matrix<precision, 3, 3> Aa = toRotationMatrix<precision>(error);\n        Eigen::Matrix<precision, 3, 3> Aq = qref_.toRotationMatrix();\n        Eigen::Matrix<precision, 3, 1> vb_pred = Aq * vi;\n\n        // H\n        // eq. 44\n        Eigen::Matrix<precision, 3, 3> Ha = toCrossMatrix<precision>(vb_pred);\n\n        // eq. 46\n        Eigen::Matrix<precision, 3, 3> K;\n        K = P_.block(9, 9, 3, 3) * Ha.transpose() * (Ha * P_.block(9, 9, 3, 3) * Ha.transpose() + R_Acc_).inverse();\n\n        // eq. 47\n        // h = vb_pred\n        x_.segment(9, 3) += K * (z - vb_pred - Ha * error);\n\n        // eq. 48\n        P_.block(9, 9, 3, 3) -= K * Ha * P_.block(9, 9, 3, 3);\n    }\n    else\n    {\n        Eigen::Matrix<precision, 3, 1> vi = gravity + x_.segment(6, 3);\n\n        // eq. 42\n        Eigen::Matrix<precision, 3, 1> error = x_.segment(9, 3);\n        Eigen::Matrix<precision, 3, 3> Aa = toRotationMatrix<precision>(error);\n        Eigen::Matrix<precision, 3, 3> Aq = qref_.toRotationMatrix();\n        Eigen::Matrix<precision, 3, 1> vb_pred = Aq * vi;\n\n        // H\n        // eq. 44\n        Eigen::Matrix<precision, 3, 6> H;\n        Eigen::Matrix<precision, 3, 3> Ha = toCrossMatrix<precision>(vb_pred);\n        H.topLeftCorner(3, 3) = Aa * Aq;\n        H.bottomRightCorner(3, 3) = Ha;\n\n        // eq. 46\n        Eigen::Matrix<precision, 6, 3> K;\n        K = P_.block(6, 6, 6, 6) * H.transpose() * (H * P_.block(6, 6, 6, 6) * H.transpose() + R_Acc_).inverse();\n\n        // eq. 47\n        // h = v_bred\n        x_.segment(6, 6) += K * (z - vb_pred - Ha * error);\n\n        // eq. 48\n        P_.block(6, 6, 6, 6) -= K * H * P_.block(6, 6, 6, 6);\n    }\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::correctMag(const float mx, const float my, const float mz, const float incl, const float B, const Eigen::Matrix<precision, 3, 3> &W, const Eigen::Matrix<precision, 3, 1> &V)\n{\n    // z\n    Eigen::Matrix<precision, MEASSUREMENT_MAG_SIZE, 1> z;\n    z << mx, my, mz;\n\n    Eigen::Matrix<precision, 3, 1> vi;\n    vi << std::cos(incl), 0, -std::sin(incl);\n    vi = B * vi;\n\n    // eq. 42\n    Eigen::Matrix<precision, 3, 1> error = x_.segment(9, 3);\n    // Eigen::Matrix<precision, 3, 3> Aa = toRotationMatrix<precision>(error);\n    Eigen::Matrix<precision, 3, 3> Aq = qref_.toRotationMatrix();\n    Eigen::Matrix<precision, 3, 1> vb_pred = Aq * vi;\n\n    // h(v) = W * v + V\n    Eigen::Matrix<precision, 3, 1> h = W * vb_pred + V;\n\n    // H\n    // eq. 44\n    Eigen::Matrix<precision, 3, 3> Ha = W * toCrossMatrix<precision>(vb_pred);\n\n    // eq. 46\n    Eigen::Matrix<precision, 3, 3> K;\n    K = P_.block(9, 9, 3, 3) * Ha.transpose() * (Ha * P_.block(9, 9, 3, 3) * Ha.transpose() + R_Mag_).inverse();\n\n    // eq. 47\n    x_.segment(9, 3) += K * (z - h - Ha * error);\n\n    // eq. 48\n    P_.block(9, 9, 3, 3) -= K * Ha * P_.block(9, 9, 3, 3);\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::reset()\n{\n    // eq. 21\n    qref_ = Quaternion<precision>(x_(9), x_(10), x_(11), 2.0) * qref_;\n    // eq. 22\n    qref_.normalize();\n    x_(9) = 0.0;\n    x_(10) = 0.0;\n    x_(11) = 0.0;\n}\n\ntemplate <typename precision>\nEigen::Matrix<precision, STATE_SIZE, 1> ESKF<precision>::getState() const\n{\n    return x_;\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::getAttitude(float &roll, float &pitch, float &yaw) const\n{\n    Eigen::Matrix<precision, 3, 1> angles = qref_.toEulerAngles();\n    roll = angles(0);\n    pitch = angles(1);\n    yaw = angles(2);\n}\n\ntemplate <typename precision>\nQuaternion<precision> ESKF<precision>::getAttitude() const\n{\n    return qref_;\n}\n\ntemplate <typename precision>\nvoid ESKF<precision>::getAcceleration(float &x, float &y, float &z) const\n{\n    x = x_(6);\n    y = x_(7);\n    z = x_(8);\n}\n} // namespace IMU_EKF\n\n#endif // ESKF_IMPL", "meta": {"hexsha": "cbbd326063cc7ca4adb651a59e913fb41d201a1b", "size": 10740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ESKF.cpp", "max_stars_repo_name": "hobbeshunter/IMU_EKF", "max_stars_repo_head_hexsha": "ef08a6c7a3f5d82489f63629e5c8b18cbfd5215f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-11-22T10:41:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T02:32:20.000Z", "max_issues_repo_path": "src/ESKF.cpp", "max_issues_repo_name": "hobbeshunter/IMU_EKF", "max_issues_repo_head_hexsha": "ef08a6c7a3f5d82489f63629e5c8b18cbfd5215f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ESKF.cpp", "max_forks_repo_name": "hobbeshunter/IMU_EKF", "max_forks_repo_head_hexsha": "ef08a6c7a3f5d82489f63629e5c8b18cbfd5215f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-20T18:12:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T18:12:26.000Z", "avg_line_length": 29.3442622951, "max_line_length": 220, "alphanum_fraction": 0.5685288641, "num_tokens": 4087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5685289463657124}}
{"text": "//\n//  Family.hpp\n//  test_rcpp\n//\n//  Created by Dongjie Wu on 18/11/2021.\n//\n\n#ifndef Family_hpp\n#define Family_hpp\n\n#include <stdio.h>\n#include <RcppArmadillo.h>\n//#include <boost/math/distributions/normal.hpp>\n//#include <boost/multiprecision/cpp_bin_float.hpp>\n//#include \"distribution.hpp\"\n//using namespace boost::math;\nusing namespace Rcpp;\n\n// [[Rcpp::depends(RcppArmadillo)]]\n\n\n// !! need to decide provide the option of not log\ntemplate <class T>\nclass Family {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false) {\n    return(static_cast<T*>(this) -> logLik(theta, Y, X, lg));\n  }\n  \n};\n\nclass FamilyNormal : public Family<FamilyNormal> {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n  {\n    arma::mat mean_mat = (X * theta.subvec(1,(theta.n_elem-1)));\n    double sd = sqrt(theta[0] * theta[0]);\n    arma::mat l = arma::zeros(Y.n_rows, Y.n_cols);\n    for (int i=0; i<Y.n_rows;++i) {\n      for (int j=0; j<Y.n_cols;++j) {\n          //normal_distribution nd(mean_mat.at(i,j),sd);\n          l.at(i,j) = R::dnorm4(Y.at(i,j), mean_mat.at(i,j), sd, lg);\n      }\n    }\n    return l;\n  }\n};\n\nclass FamilyPoisson : public Family<FamilyPoisson> {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n  {\n    arma::mat mean_mat = arma::exp(X * theta); // the precision problem\n    arma::mat l = arma::zeros(Y.n_rows, Y.n_cols);\n\n    for (int i=0; i<Y.n_rows;++i) {\n      for (int j=0; j<Y.n_cols;++j) {\n          l.at(i,j) = R::dpois(Y.at(i,j), mean_mat.at(i,j), lg);\n      }\n    }\n    return l;\n  }\n};\n\nclass FamilyLogit : public Family<FamilyLogit> {\npublic:\n  arma::mat sigmoid(arma::mat x) {\n          return (1/(1+arma::exp(-x)));\n      };\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n  {\n//      arma::mat mean_t = (X * theta);\n//      arma::mat mean_mat = log(sigmoid(mean_t));\n//      arma::mat l = arma::zeros(Y.n_rows, Y.n_cols);\n//      for (int i=0; i<Y.n_rows;i++) {\n//        for (int j=0; j<Y.n_cols; j++) {\n//           l.at(i,j) = R::dbinom(Y.at(i,j), 1, mean_mat.at(i,j), lg);\n//        }\n//      }\n//      return l;\n    arma::mat mean_t = (X * theta);\n    arma::mat l = arma::zeros(Y.n_rows, Y.n_cols);\n    l = (Y % mean_t) - arma::log1p(arma::exp(mean_t));\n    return l;\n  }\n};\n\nclass FamilyMultiNomial : public Family<FamilyMultiNomial> {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n  {\n    arma::mat theta_t = arma::mat(theta);\n    theta_t.reshape(X.n_cols, Y.n_cols);\n    arma::mat mean_mat = (X * theta_t);\n    arma::vec r = arma::sum((Y % mean_mat), 1) - log(1 + arma::sum(arma::exp(mean_mat), 1));\n    arma::mat l = arma::mat(r);\n    return l;\n  }\n};\n\nclass FamilyConditionalLogit : public Family<FamilyConditionalLogit> {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n // The group variable is the last variable of X.\n  {\n    //auto t1 = std::chrono::high_resolution_clock::now();\n    arma::uvec gV = arma::conv_to<arma::uvec>::from(X.col(X.n_cols-1));\n    arma::uvec g = unique(gV);\n    arma::mat l = arma::zeros(g.n_elem, 1);\n    arma::mat l1 = arma::zeros(g.n_elem, 1);\n    arma::mat l2 = arma::zeros(g.n_elem, 1);\n    //auto t2 = std::chrono::high_resolution_clock::now();\n    for (arma::uword i=0, nr=Y.n_rows; i<nr; ++i) {\n        arma::uword j = X.at(i,X.n_cols-1)-1;\n        double mean_x = 0;\n        for (arma::uword k=0, nc=X.n_cols; k<nc-1; ++k) {\n            mean_x += theta.at(k) * X.at(i, k);\n        }\n        l1.at(j, 0) += Y.at(i, 0) * mean_x;\n        l2.at(j, 0) += exp(mean_x);\n    }\n    //auto t3 = std::chrono::high_resolution_clock::now();\n    l = l1 - log(l2);\n    //auto t4 = std::chrono::high_resolution_clock::now();\n\n    /*\n    const arma::mat& Xd = X.cols(0, X.n_cols-2);\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    arma::cube Xc1(Y.n_rows, Y.n_cols, 1);\n    Xc1.slice(0) = Y % (Xd * theta);\n    Xc1.reshape(gV.n_elem/g.n_elem, Y.n_cols, g.n_elem);\n    arma::cube Xc2(Y.n_rows, Y.n_cols, 1);\n    Xc2.slice(0) = arma::exp(Xd * theta);\n    Xc2.reshape(gV.n_elem/g.n_elem, Y.n_cols, g.n_elem);\n    auto t3 = std::chrono::high_resolution_clock::now();\n\n    for (arma::uword i=0; i<g.n_elem;++i) {\n      l.at(i, 0) = arma::accu(Xc1.slice(i)) -     log(arma::accu(Xc2.slice(i)));\n    }\n    auto t4 = std::chrono::high_resolution_clock::now();\n    \n    std::chrono::duration<double, std::milli> d1 = t2 - t1;\n    std::chrono::duration<double, std::milli> d2 = t3 - t2;\n    std::chrono::duration<double, std::milli> d3 = t4 - t3;\n    std::cout << d1.count() << \"ms\" << std::endl;\n    std::cout << d2.count() << \"ms\" << std::endl;\n    std::cout << d3.count() << \"ms\" << std::endl;\n     */\n    return l;\n  }\n};\n\nclass FamilyUnidiff : public Family<FamilyUnidiff> {\npublic:\n  arma::mat logLik(const arma::vec& theta, const arma::mat& Y,\n                   const arma::mat& X, const bool& lg = false)\n // The group variable is the last variable of X.\n    {\n        if (Y.n_cols != 1 ) {\n            throw std::invalid_argument(\"Y should only have 1 column!\");\n        }\n        if (X.n_cols != 2 ) {\n            throw std::invalid_argument(\"X should have 2 columns!\");\n        }\n        arma::vec uY = arma::unique(Y);\n        arma::mat X_X = fast_dummy(X.col(0));\n        arma::mat X_Z = fast_dummy(X.col(1));\n        arma::mat Y_Y = fast_dummy(Y.col(0));\n        arma::mat W = arma::ones(X_Z.n_rows, (X_Z.n_cols+1));\n        W(arma::span::all,arma::span(1,W.n_cols-1)) = X_Z;\n        arma::uword colX = X_X.n_cols;\n        arma::uword colZ = X_Z.n_cols;\n        arma::uword colY = Y_Y.n_cols;\n        if (theta.n_elem != (colY*(colZ+1)+colY*colX+colZ)) {\n            throw std::invalid_argument(\"Wrong size of theta!\");\n        }\n        arma::uword end = colY*(colZ+1)-1;\n        arma::uword end2 = colY*colX;\n        arma::uword end3 = colZ;\n        arma::mat theta_y = arma::mat(theta(arma::span(0, end)));\n        theta_y.reshape(colZ+1, colY);\n        arma::mat psi_y = arma::mat(theta(arma::span(end+1, end+end2)));\n        psi_y.reshape(colX, colY);\n        arma::mat phi = arma::mat(theta(arma::span(end+end2+1,end+end2+end3)));\n        phi.reshape(colZ,1);\n        arma::mat expZ = arma::exp(X_Z * phi);\n        arma::mat phiX = X_X  * psi_y;\n        arma::mat part2 = phiX.each_col() % expZ;\n        arma::mat sum_part = W * theta_y + part2;\n        arma::mat first = arma::sum(Y_Y % sum_part, 1);\n        arma::mat second = log(1+arma::sum(arma::exp(sum_part), 1));\n        arma::mat l = first - second;\n        return l;\n    }\n    arma::mat fast_dummy(const arma::vec& x) {\n        arma::vec vec_u = arma::unique(x);\n        vec_u = vec_u(arma::span(1,vec_u.n_elem-1)); // Remove the baseline\n        arma::mat mats = arma::zeros(x.n_elem, (vec_u.n_elem));\n        for (arma::uword i=0; i<vec_u.n_elem; ++i) {\n            mats.col(i) = x;\n            double idx = vec_u.at(i);\n            mats.col(i).for_each([idx](arma::vec::elem_type& val){\n                (val == idx) ? (val = 1) : (val = 0);\n            });\n        }\n        return mats;\n    }\n};\n\n\n\n#endif /* Family_hpp */\n", "meta": {"hexsha": "321bf9c2e3448e68c5665258f8446974895651fd", "size": 7469, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Family.hpp", "max_stars_repo_name": "wudongjie/fmmr6", "max_stars_repo_head_hexsha": "032e8fec69dfdfeac83a5b81970bbbffef79b8a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Family.hpp", "max_issues_repo_name": "wudongjie/fmmr6", "max_issues_repo_head_hexsha": "032e8fec69dfdfeac83a5b81970bbbffef79b8a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Family.hpp", "max_forks_repo_name": "wudongjie/fmmr6", "max_forks_repo_head_hexsha": "032e8fec69dfdfeac83a5b81970bbbffef79b8a2", "max_forks_repo_licenses": ["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.95, "max_line_length": 92, "alphanum_fraction": 0.5613870665, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5685289418079909}}
{"text": "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#include <Python.h>\n#include <boost/python.hpp>\n#include <numpy/arrayobject.h> \nusing namespace boost::python;\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include <mrpt/config.h>\n\n#include <mrpt/vision/pnp_algos.h>\nmrpt::vision::pnp::CPnP pnp_algos;\n\n#if MRPT_HAS_OPENCV\n    #include <opencv2/opencv.hpp>\n    #include <opencv2/core/eigen.hpp>\n    using namespace cv;\n#endif\n\nclass PnPAlgos\n{\npublic:\n\tPnPAlgos( int new_m );\n\t~PnPAlgos();\n\t#if MRPT_HAS_OPENCV\n        int epnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n        int dls_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n        int upnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n    #endif\n    int p3p_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n    int ppnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n\tint rpnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n\tint posit_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n\tint lhm_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n\tint so3_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat);\n\t\nprivate:\n\tint dummy;\n};\n\nPnPAlgos::PnPAlgos( int new_m ){\n\tdummy = new_m;\n    #if MRPT_HAS_OPENCV\n    std::cout <<\" Using OpenCV dependency for PnP Algorithms - EPnP, DLS-PnP, UPnP(Broken) \" << std::endl << std::endl; \n    #else \n    std::cout << \" Initializing PnP class \" << std::endl << std::endl;\n    #endif\n}\nPnPAlgos::~PnPAlgos(){\n}\n#if MRPT_HAS_OPENCV\n    int PnPAlgos::epnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n        Map<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n        Map<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n        Map<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n        Map<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n        \n        return pnp_algos.epnp(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n    }\n\n    int PnPAlgos::dls_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n        Map<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n        Map<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n        Map<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n        Map<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n        \n        return pnp_algos.dls(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n    }\n\n\n    int PnPAlgos::upnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n        Map<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n        Map<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n        Map<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n        Map<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n        \n        return pnp_algos.upnp(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n    }\n#endif\n\nint PnPAlgos::p3p_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n    Map<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n    Map<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n    Map<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n    Map<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n    \n    return pnp_algos.p3p(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nint PnPAlgos::ppnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n\tMap<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n\tMap<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n\tMap<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n\tMap<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n\t\n\treturn pnp_algos.ppnp(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nint PnPAlgos::rpnp_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n\tMap<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n\tMap<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n\tMap<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n\tMap<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n\t\n\treturn pnp_algos.rpnp(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nint PnPAlgos::posit_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n\tMap<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n\tMap<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n\tMap<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n\tMap<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n\t\n\treturn pnp_algos.posit(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nint PnPAlgos::lhm_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n\tMap<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n\tMap<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n\tMap<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n\tMap<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n\t\n\treturn pnp_algos.lhm(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nint PnPAlgos::so3_solve(PyObject* obj_pts, PyObject* img_pts, int n, PyObject* cam_intrinsic, PyObject* pose_mat){\n\tMap<MatrixXd> _obj_pts((double *) PyArray_DATA((PyArrayObject*)obj_pts),3,n);\n\tMap<MatrixXd> _img_pts((double *) PyArray_DATA((PyArrayObject*)img_pts),3,n);\n\tMap<MatrixXd> _pose_mat((double *) PyArray_DATA((PyArrayObject*)pose_mat),6,1);\n\tMap<MatrixXd> _cam_intrinsic((double *) PyArray_DATA((PyArrayObject*)cam_intrinsic),3,3);\n\t\n\treturn pnp_algos.so3(_obj_pts, _img_pts, n, _cam_intrinsic, _pose_mat);\n}\n\nvoid export_pnp()\n{\n    class_<PnPAlgos>(\"pnp\", init<int>(args(\"m\")))\n        #if MRPT_HAS_OPENCV\n            .def(\"epnp\", &PnPAlgos::epnp_solve)\n            .def(\"dls\", &PnPAlgos::dls_solve)\n            .def(\"upnp\", &PnPAlgos::upnp_solve)\n        #endif\n        .def(\"p3p\", &PnPAlgos::p3p_solve)\n        .def(\"ppnp\", &PnPAlgos::ppnp_solve)\n        .def(\"rpnp\", &PnPAlgos::rpnp_solve)\n        .def(\"posit\", &PnPAlgos::posit_solve)\n        .def(\"lhm\", &PnPAlgos::lhm_solve)\n        .def(\"so3\", &PnPAlgos::so3_solve)\n    ;\n}\n", "meta": {"hexsha": "f0612fd9b14167bc11bfc8000e2b8d52ffaa0c2e", "size": 7313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "python/src/pnp_bindings.cpp", "max_stars_repo_name": "yhexie/mrpt", "max_stars_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "python/src/pnp_bindings.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": "python/src/pnp_bindings.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": 47.7973856209, "max_line_length": 120, "alphanum_fraction": 0.721591686, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5685289356713693}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/MPRealSupport>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/mpfr.hpp>\n#include <iomanip>\n#include <iostream>\n\n#include \"gauss_hermite_quadrature.hpp\"\n#include \"spectral/mpfr/import_std_math.hpp\"\n\n//#include <quadmath.h>\n\nnamespace boltzmann {\n\nnamespace mp = boost::multiprecision;\nusing namespace mpfr;\n\ntypedef mp::mpfr_float_backend<100000> mfloat_t;\ntypedef mp::number<mfloat_t> mpfr_float_t;\n\nusing namespace std;\n\nvoid gauss_hermite_roots(std::vector<double>& roots, const int N, const int ndigits)\n{\n  mpreal::set_default_prec(ndigits);\n  typedef mpreal mfloat_t;\n  //  typedef double mfloat_t;\n  typedef Eigen::Matrix<mfloat_t, Eigen::Dynamic, Eigen::Dynamic> MatrixXmp;\n  MatrixXmp A(N, N);\n  A.fill(0);\n  for (int i = 0; i < N - 1; ++i) {\n    const double beta = ::math::sqrt(1.0 * (i + 1)) / ::math::sqrt(2.0);\n    A(i, i + 1) = beta;\n    A(i + 1, i) = beta;\n  }\n\n  Eigen::SelfAdjointEigenSolver<MatrixXmp> eigensolver;\n  // Eigen::EigenSolver<MatrixXmp> eigensolver;\n  eigensolver.compute(A, Eigen::EigenvaluesOnly);\n\n  const auto w = eigensolver.eigenvalues();\n\n  for (int i = 0; i < N; ++i) {\n    roots[i] = w(i).toDouble();\n  }\n\n  // sort\n  std::sort(roots.begin(), roots.end());\n}\n}  // end namespace boltzmann\n", "meta": {"hexsha": "91f6dfba1c37281bf0732e562680e61665b43a72", "size": 1376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectral/quadrature/gauss_hermite_roots.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "spectral/quadrature/gauss_hermite_roots.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectral/quadrature/gauss_hermite_roots.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 25.9622641509, "max_line_length": 84, "alphanum_fraction": 0.6984011628, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5685289356713693}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include<opencv2/core/eigen.hpp>\n#include <chrono>\n#include <sophus/se3.hpp>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n// 相机内参\nMat K = (Mat_<double>(3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches);\n\nvoid pose_estimation_3d3d(const vector<Point3d> &pts1, const vector<Point3d> &pts2,\n                          Mat &R, Mat &t);\n\nvoid bundelAdjustment(const vector<Point3d> &pts1, const vector<Point3d> &pts2, \n                      Mat &R, Mat &t);\n\n\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam(const Point2d &p);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nint main(int argc, char **argv){\n\n  // 读取图像\n  Mat img_1 = imread(\"../1.png\", CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(\"../2.png\", CV_LOAD_IMAGE_COLOR);\n  assert(img_1.data && img_2.data);\n  cout << \"读取图像 完成！\" << endl;\n\n\n  // 特征点匹配\n  cout << \"开始特征点匹配 ......\" << endl;\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n  cout << \"特征点匹配 完成！ 一共找到了\" << matches.size() << \"组匹配点\" << endl << endl;\n  // for (DMatch m:matches) {\n  //   cout << keypoints_1[m.queryIdx].pt.x << \" \" << keypoints_1[m.queryIdx].pt.y << endl;\n  // }\n\n\n\n  // 读取深度图，建立3D点\n  Mat img_depth_1 = imread(\"../1_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n  Mat img_depth_2 = imread(\"../2_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n\n  vector<Point3d> points_1;\n  vector<Point3d> points_2;\n\n  for (DMatch m:matches){\n    ushort d1 = img_depth_1.at<unsigned short>((int)keypoints_1[m.queryIdx].pt.y, (int)keypoints_1[m.queryIdx].pt.x);\n    ushort d2 = img_depth_2.at<unsigned short>((int)keypoints_2[m.trainIdx].pt.y, (int)keypoints_2[m.trainIdx].pt.x);\n\n    if (d1==0 || d2==0) continue;\n\n    float dd2 = d2 / 5000.0;\n    float dd1 = d1 / 5000.0;\n    \n    Point2d p1_2d = pixel2cam(keypoints_1[m.queryIdx].pt);\n    Point2d p2_2d = pixel2cam(keypoints_2[m.trainIdx].pt);\n\n    points_1.push_back(Point3d(p1_2d.x * dd1, p1_2d.y*dd1, dd1));\n    points_2.push_back(Point3d(p2_2d.x * dd2, p2_2d.y*dd2, dd2));\n  }\n  cout << \"valid 3d-3d pairs: \" << points_1.size() << endl;\n\n  Mat R, t;\n  cout << \"开始SVD求解 ......\" << endl;\n  pose_estimation_3d3d(points_1, points_2, R, t);\n  cout << \"ICP via SVD results: \" << endl;\n  cout << \"R = \" << R << endl;\n  cout << \"t = \" << t << endl;\n  cout << endl;\n\n  cout << \"开始BA求解 ......\" << endl;\n  bundelAdjustment(points_1, points_2, R, t);\n  cout << \"R = \" << R << endl;\n  cout << \"t = \" << t << endl;\n  cout << endl;\n\n  return 0;\n} \n\n\n\n\n\n\n\n\n\n\n\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  virtual void setToOriginImpl() override {\n    _estimate = Sophus::SE3d();\n  }\n\n  /// left multiplication on SE3\n  virtual void oplusImpl(const double *update) override {\n    Eigen::Matrix<double, 6, 1> update_eigen;\n    update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n    _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n};\n\n\nclass EdgeProjectXYZRGBDPoseOnly: public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPose>{\n  public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  EdgeProjectXYZRGBDPoseOnly(const Eigen::Vector3d &point): _point(point){}\n\n  virtual void computeError() override {\n    const VertexPose *pose = static_cast<const VertexPose *>(_vertices[0]);\n    _error = _measurement - pose->estimate() * _point;\n  }\n\n  virtual void linearizeOplus() override {\n    const VertexPose *pose = static_cast<VertexPose *>(_vertices[0]);\n    Sophus::SE3d T = pose->estimate();\n    Eigen::Vector3d xyz_trans = T * _point;\n    _jacobianOplusXi.block<3, 3>(0, 0) = - Eigen::Matrix3d::Identity();\n    _jacobianOplusXi.block<3, 3>(0, 3) = Sophus::SO3d::hat(xyz_trans);\n  }\n\n  bool read(istream &in) {}\n  bool write(ostream &out) const {}\n\n  protected:\n  Eigen::Vector3d _point;\n};\n\n\nvoid bundelAdjustment(const vector<Point3d> &pts2, const vector<Point3d> &pts1, \n                      Mat &R, Mat &t){\n  typedef g2o::BlockSolverX BlockSolverType;\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType;\n\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  VertexPose *vertex_pose = new VertexPose();\n  vertex_pose->setId(0);\n  vertex_pose->setEstimate(Sophus::SE3d());\n  optimizer.addVertex(vertex_pose);\n\n  for(size_t i=0; i < pts1.size(); i++){\n    EdgeProjectXYZRGBDPoseOnly *edge = new EdgeProjectXYZRGBDPoseOnly(Eigen::Vector3d(pts2[i].x,\n    pts2[i].y, pts2[i].z));\n    edge->setId(i);\n    edge->setVertex(0, vertex_pose);\n    edge->setMeasurement(Eigen::Vector3d(pts1[i].x, pts1[i].y, pts1[i].z));\n    edge->setInformation(Eigen::Matrix3d::Identity());\n    optimizer.addEdge(edge);\n  }\n\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  cout << \"T=\\n\" << vertex_pose->estimate().matrix() << endl;\n\n  Eigen::Matrix3d R_ = vertex_pose->estimate().rotationMatrix();\n  Eigen::Vector3d t_ = vertex_pose->estimate().translation();\n\n  cv::eigen2cv(R_, R);\n  cv::eigen2cv(t_, t);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// 注意pts2和pts1顺序\nvoid pose_estimation_3d3d(const vector<Point3d> &pts2, const vector<Point3d> &pts1,\n                          Mat &R, Mat &t){\n  \n  assert(pts1.size() == pts2.size());\n  int N = pts1.size();\n\n  Point3d p1, p2;\n  for (int i=0; i<N; i++){\n    p1 += pts1[i];\n    p2 += pts2[i];\n  }\n\n  p1 = p1 / N;\n  p2 = p2 / N;\n\n  vector<Point3d> q1(N), q2(N);\n  for (int i=0; i<N; i++){\n    q1[i] = pts1[i] - p1;\n    q2[i] = pts2[i] - p2;\n  }\n\n  Matrix3d W = Matrix3d::Zero();\n  for (int i=0; i<N; i++){\n    Vector3d q1_eig(q1[i].x, q1[i].y, q1[i].z);\n    Vector3d q2_eig(q2[i].x, q2[i].y, q2[i].z);\n    W += q1_eig * q2_eig.transpose();\n  }\n  cout << \"W = \" << W << endl;\n\n  Eigen::JacobiSVD<Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n  cout << \"U=\" << U << endl;\n  cout << \"V=\" << V << endl;\n\n  Eigen::Matrix3d R_eig = U * V.transpose();\n  if (R_eig.determinant() < 0){\n    R_eig = -R_eig;\n  }\n\n  Vector3d p1_eig(p1.x, p1.y, p1.z);\n  Vector3d p2_eig(p2.x, p2.y, p2.z);\n  Eigen::Vector3d t_eig = p1_eig - R_eig*p2_eig;\n\n  cv::eigen2cv(R_eig, R);\n  cv::eigen2cv(t_eig, t);\n}\n\n\n\n\n\nvoid find_feature_matches(\n  const Mat &img_1, const Mat &img_2,\n  std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,\n  std::vector<DMatch> &matches){\n\n    Mat descriptors_1, descriptors_2;\n    Ptr<FeatureDetector> detector = ORB::create();\n    Ptr<DescriptorExtractor> descriptor = ORB::create();\n    Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n\n    // --第一步：检测Oriented Fast角点位置\n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    cout << \"--第一步完成：检测Oriented Fast角点位置\" << endl;\n\n    // --第二步：根据角点位置计算BRIEF描述子\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    cout << \"--第二步完成：根据角点位置计算BRIEF描述子\" << endl;\n\n    // -- 第三步：对两幅图像中的BRIEF描述子进行匹配，使用Hamming距离\n    vector<DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    cout << \"--第三步完成：对两幅图像中的BRIEF描述子进行匹配，使用Hamming距离\" << endl;\n\n    // --第四步：匹配点对 筛选\n    auto min_max = minmax_element(match.begin(), match.end(),\n                [] (const DMatch &m1, const DMatch &m2) {return m1.distance < m2.distance;});\n    double min_dist = min_max.first->distance;\n    double max_dist = min_max.second->distance;\n\n    for (int i=0; i<descriptors_1.rows; i++){\n        if(match[i].distance <= max(2*min_dist, 30.0)){\n            matches.push_back(match[i]);\n        }\n    }\n    cout << \"--第四步完成：匹配点对 筛选\" << endl;\n}\n\n\n\n\n\n\nPoint2d pixel2cam(const Point2d &p) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\n", "meta": {"hexsha": "d9153c67441053bf838ca68c54571a3f1f6545ee", "size": 8917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch7/pose_estimation_3d3d/pose_estimation_3d3d.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_1/ch7/pose_estimation_3d3d/pose_estimation_3d3d.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_1/ch7/pose_estimation_3d3d/pose_estimation_3d3d.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6179104478, "max_line_length": 117, "alphanum_fraction": 0.6539194796, "num_tokens": 3064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5685289356713693}}
{"text": "#include <CGAL/minkowski_sum_2.h>\n#include <CGAL/Polygon_vertical_decomposition_2.h>\n#include <CGAL/Polygon_triangulation_decomposition_2.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/Small_side_angle_bisector_decomposition_2.h>\n\n#include \"read_polygon.h\"\n\n#include <string.h>\n#include <list>\n#include <boost/timer.hpp>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\ntypedef CGAL::Polygon_2<Kernel> Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<Kernel> Polygon_with_holes_2;\n\nbool are_equal(const Polygon_with_holes_2& ph1,\n               const Polygon_with_holes_2& ph2)\n{\n  std::list<Polygon_with_holes_2> sym_diff;\n  CGAL::symmetric_difference(ph1, ph2, std::back_inserter(sym_diff));\n  return sym_diff.empty();\n}\n\ntypedef enum {\n  REDUCED_CONVOLUTION,\n  VERTICAL_DECOMPOSITION,\n  TRIANGULATION_DECOMPOSITION,\n  VERTICAL_AND_ANGLE_BISECTOR_DECOMPOSITION,\n  TRIANGULATION_AND_ANGLE_BISECTOR_DECOMPOSITION,\n  OPTIMAL_DECOMPOSITION,\n} Strategy;\n\nstatic const char* strategy_names[] = {\n  \"reduced convolution\",\n  \"vertical decomposition\",\n  \"constrained triangulation decomposition\",\n  \"vertical and angle bisector decomposition\",\n  \"constrained triangulation and angle bisector decomposition\",\n  \"optimal decomposition\"\n};\n\nPolygon_with_holes_2 compute_minkowski_sum_2(Polygon_with_holes_2& p,\n                                             Polygon_with_holes_2& q,\n                                             Strategy strategy)\n{\n  switch (strategy) {\n   case REDUCED_CONVOLUTION:\n     return CGAL::minkowski_sum_by_reduced_convolution_2(p, q);\n\n   case VERTICAL_DECOMPOSITION:\n    {\n     CGAL::Polygon_vertical_decomposition_2<Kernel> decomp;\n     return CGAL::minkowski_sum_2(p, q, decomp);\n    }\n\n   case TRIANGULATION_DECOMPOSITION:\n    {\n     CGAL::Polygon_triangulation_decomposition_2<Kernel> decomp;\n     return CGAL::minkowski_sum_2(p, q, decomp);\n    }\n\n   case VERTICAL_AND_ANGLE_BISECTOR_DECOMPOSITION:\n    {\n     typedef CGAL::Small_side_angle_bisector_decomposition_2<Kernel>\n                                                No_holes_decomposition;\n     typedef CGAL::Polygon_vertical_decomposition_2<Kernel>\n                                                With_holes_decomposition;\n\n     if (0 == p.number_of_holes()) {\n       const Polygon_2& pnh = p.outer_boundary();\n       No_holes_decomposition decomp_no_holes;\n       if  (0 == q.number_of_holes()) {\n         const Polygon_2& qnh = q.outer_boundary();\n         return CGAL::minkowski_sum_2(pnh, qnh, decomp_no_holes, decomp_no_holes);\n       }\n\n       With_holes_decomposition decomp_with_holes;\n       return CGAL::minkowski_sum_2(pnh, q, decomp_no_holes, decomp_with_holes);\n     }\n\n     With_holes_decomposition decomp_with_holes;\n     if (0 == q.number_of_holes()) {\n       const Polygon_2& qnh = q.outer_boundary();\n       No_holes_decomposition decomp_no_holes;\n       return CGAL::minkowski_sum_2(p, qnh, decomp_with_holes, decomp_no_holes);\n     }\n\n     return CGAL::minkowski_sum_2(p, q, decomp_with_holes, decomp_with_holes);\n    }\n\n   case TRIANGULATION_AND_ANGLE_BISECTOR_DECOMPOSITION:\n    {\n     typedef CGAL::Small_side_angle_bisector_decomposition_2<Kernel>\n                                                No_holes_decomposition;\n     typedef CGAL::Polygon_triangulation_decomposition_2<Kernel>\n                                                With_holes_decomposition;\n     if (0 == p.number_of_holes()) {\n       const Polygon_2& pnh = p.outer_boundary();\n       No_holes_decomposition decomp_no_holes;\n       if (0 == q.number_of_holes()) {\n         const Polygon_2& qnh = q.outer_boundary();\n         return CGAL::minkowski_sum_2(pnh, qnh, decomp_no_holes, decomp_no_holes);\n       }\n\n       With_holes_decomposition decomp_with_holes;\n       return CGAL::minkowski_sum_2(pnh, q, decomp_no_holes, decomp_with_holes);\n     }\n\n     With_holes_decomposition decomp_with_holes;\n     if (0 == q.number_of_holes()) {\n       const Polygon_2& qnh = q.outer_boundary();\n       No_holes_decomposition decomp_no_holes;\n       return CGAL::minkowski_sum_2(p, qnh, decomp_with_holes, decomp_no_holes);\n     }\n\n     return CGAL::minkowski_sum_2(p, q, decomp_with_holes, decomp_with_holes);\n    }\n\n   case OPTIMAL_DECOMPOSITION:\n    {\n     CGAL::Small_side_angle_bisector_decomposition_2<Kernel> decomp_no_holes;\n     CGAL::Polygon_triangulation_decomposition_2<Kernel> decomp_with_holes;\n     return CGAL::minkowski_sum_by_decomposition_2(p, q,\n                                                   decomp_no_holes,\n                                                   decomp_with_holes);\n    }\n\n   default:\n    std::cerr << \"Invalid strategy\" << std::endl;\n    return Polygon_with_holes_2();\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  if (argc < 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" [-method flag] [polygon files]...\"\n              << std::endl;\n    std::cerr << \"For the method flag, use a subset of the letters 'rfsohg'.\"\n              << std::endl;\n    std::cerr << \"The program will compute the Minkowski sum of the first \"\n              << \"and second polygon, of the third and fourth, and so on.\"\n              << std::endl;\n    return 1;\n  }\n\n  Polygon_with_holes_2 p, q;\n  boost::timer timer;\n\n  std::list<Strategy> strategies;\n\n  int i(1);\n  while (i < argc) {\n    if (argv[i][0] == '-') {\n      strategies.clear();\n      for (std::size_t j = 1; j < strlen(argv[i]); ++j) {\n        switch (argv[i][j]) {\n         case 'r': strategies.push_back(REDUCED_CONVOLUTION); break;\n         case 'v': strategies.push_back(VERTICAL_DECOMPOSITION); break;\n         case 't': strategies.push_back(TRIANGULATION_DECOMPOSITION); break;\n         case 'w':\n          strategies.push_back(VERTICAL_AND_ANGLE_BISECTOR_DECOMPOSITION);\n          break;\n\n         case 'u':\n          strategies.push_back(TRIANGULATION_AND_ANGLE_BISECTOR_DECOMPOSITION);\n          break;\n\n         case 'd': strategies.push_back(OPTIMAL_DECOMPOSITION); break;\n         default:\n          std::cerr << \"Unknown flag '\" << argv[i][j] << \"'\" << std::endl;\n          return -1;\n        }\n      }\n      ++i;\n      continue;\n    }\n\n    std::cout << \"Testing \" << argv[i] << \" + \" << argv[i+1] << std::endl;\n    if (!read_polygon(argv[i], p)) return -1;\n    if (!read_polygon(argv[i+1], q)) return -1;\n\n    bool compare = false;\n    Polygon_with_holes_2 reference;\n    std::list<Strategy>::iterator it;\n    for (it = strategies.begin(); it != strategies.end(); ++it) {\n      std::cout << \"Using \" << strategy_names[*it] << \": \";\n      timer.restart();\n      Polygon_with_holes_2 result = compute_minkowski_sum_2(p, q, *it);\n      double secs = timer.elapsed();\n      std::cout << secs << \" s \" << std::flush;\n\n      if (compare) {\n        if (are_equal(reference, result)) std::cout << \"(OK)\";\n        else {\n          std::cout << \"(ERROR: different result)\";\n          return 1;\n        }\n      }\n      else {\n        compare = true;\n        reference = result;\n\n        std::size_t n = result.outer_boundary().size();\n        Polygon_with_holes_2::Hole_const_iterator it = result.holes_begin();\n        while(it != result.holes_end()) n += (*it++).size();\n\n        std::cout << std::endl << \"Result has \" << n << \" vertices and \"\n                  << result.number_of_holes() << \" holes.\";\n      }\n      std::cout << std::endl;\n    }\n\n    std::cout << std::endl;\n    i += 2;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "6a3fe2917b1dfa4751a3e75166906b128bd30d3c", "size": 7380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Minkowski_sum_2/test/Minkowski_sum_2/test_minkowski_sum_with_holes.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-10T00:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-10T00:33:20.000Z", "max_issues_repo_path": "Minkowski_sum_2/test/Minkowski_sum_2/test_minkowski_sum_with_holes.cpp", "max_issues_repo_name": "gaschler/cgal", "max_issues_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Minkowski_sum_2/test/Minkowski_sum_2/test_minkowski_sum_with_holes.cpp", "max_forks_repo_name": "gaschler/cgal", "max_forks_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "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": 33.3936651584, "max_line_length": 82, "alphanum_fraction": 0.6334688347, "num_tokens": 1933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.6442251201477015, "lm_q1q2_score": 0.5684822062559947}}
{"text": "//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//% Code implementing the paper \"Accelerated Quadratic Proxy for Geometric Optimization\", SIGGRAPH 2016.\n//% Disclaimer: The code is provided as-is for academic use only and without any guarantees. \n//%             Please contact the author to report any bugs.\n//% Written by Shahar Kovalsky (http://www.wisdom.weizmann.ac.il/~shaharko/)\n//%            Meirav Galun (http://www.wisdom.weizmann.ac.il/~/meirav/)\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n#include \"mex.h\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mexHelpers.cpp\"\n\nusing namespace Eigen;\n\nvoid helperFcuntionalIsoDist2x2(VectorXd &pA, const VectorXd &areas, int dim, double& val, bool& flips)\n{\n\tint block_size = dim*dim;\n\tint num_blocks = pA.size() / block_size;\n\tMap<Matrix2d> currA(pA.data(), dim, dim);\n\tMatrix2d currA_inv;\n\n\t// project\n\tval = 0;\n\tflips = 0;\n\tfor (int ii = 0; ii < num_blocks; ii++)\n\t{\n\t\t// get current block\n\t\tnew (&currA) Map<MatrixXd>(pA.data() + ii*block_size, dim, dim);\n\t\t// check inverse\n\t\tflips = flips || (currA.determinant() < 0);\n\t\t// compute inverse\n\t\tcurrA_inv = currA.inverse();\n\t\tval = val + areas(ii) * (currA.squaredNorm() + currA_inv.squaredNorm());\n\t\t// compute Tx_grad\n\t\tcurrA = 2 * areas(ii) * (currA - currA_inv.transpose()*currA_inv*currA_inv.transpose());\n\t}\n}\n\nvoid helperFcuntionalIsoDist3x3(VectorXd &pA, const VectorXd &areas, int dim, double& val, bool& flips)\n{\n\tint block_size = dim*dim;\n\tint num_blocks = pA.size() / block_size;\n\tMap<Matrix3d> currA(pA.data(), dim, dim);\n\tMatrix3d currA_inv;\n\n\t// project\n\tval = 0;\n\tflips = 0;\n\tfor (int ii = 0; ii < num_blocks; ii++)\n\t{\n\t\t// get current block\n\t\tnew (&currA) Map<MatrixXd>(pA.data() + ii*block_size, dim, dim);\n\t\t// check inverse\n\t\tflips = flips || (currA.determinant() < 0);\n\t\t// compute inverse\n\t\tcurrA_inv = currA.inverse();\n\t\tval = val + areas(ii) * (currA.squaredNorm() + currA_inv.squaredNorm());\n\t\t// compute Tx_grad\n\t\tcurrA = 2 * areas(ii) * (currA - currA_inv.transpose()*currA_inv*currA_inv.transpose());\n\t}\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n{\n\t// assign input\n\tint A_rows = mxGetM(prhs[0]); // # rows of A\n\tint A_cols = mxGetN(prhs[0]); // # cols of A\n\tint areas_rows = mxGetM(prhs[1]); // # rows of A\n\tint areas_cols = mxGetN(prhs[1]); // # cols of A\n\tdouble *dim;\n\tdouble val;\n\tbool flips;\n\tconst Map<VectorXd> A(mxGetPr(prhs[0]), A_rows, A_cols);\n\tconst Map<VectorXd> areas(mxGetPr(prhs[1]), areas_rows, areas_cols);\n\tdim = mxGetPr(prhs[2]);\n\n\tif (A_cols!=1)\n\t\tmexErrMsgIdAndTxt(\"MATLAB:wrong_input\", \"first argument must be a column vector\");\n\tif (areas_cols != 1)\n\t\tmexErrMsgIdAndTxt(\"MATLAB:wrong_input\", \"second argument must be a column vector\");\n\n\t// copy\n\tVectorXd pA(A_rows);\n\tpA = A;\n\n\t// compute\n\tif (*dim == 2)\n\t\thelperFcuntionalIsoDist2x2(pA, areas, *dim, val, flips);\n\telse if (*dim == 3)\n\t\thelperFcuntionalIsoDist3x3(pA, areas, *dim, val, flips);\n\telse\n\t\tmexErrMsgIdAndTxt(\"MATLAB:wrong_dimension\", \"dim must be either 2 or 3\");\n\t\n\t// output\n\tplhs[0] = mxCreateDoubleScalar(val); // functional value\n\tmapDenseMatrixToMex(pA, &(plhs[1])); // return Tx_grad\n\tplhs[2] = mxCreateLogicalScalar(flips); // were there any flips\n}", "meta": {"hexsha": "b981f7f06381153004dec9a668b094f650443988", "size": 3298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mex/computeFunctionalIsoDistMex.cpp", "max_stars_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_stars_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T11:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T06:45:26.000Z", "max_issues_repo_path": "mex/computeFunctionalIsoDistMex.cpp", "max_issues_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_issues_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mex/computeFunctionalIsoDistMex.cpp", "max_forks_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_forks_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-10-17T12:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-18T14:03:11.000Z", "avg_line_length": 32.98, "max_line_length": 104, "alphanum_fraction": 0.6464523954, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5684821943044892}}
{"text": "/*\n * \n * Independent implementation of \n *     Successive Convexification for 6-DoF Mars Rocket Powered Landing \n *     with Free-Final-Time (Michael Szmuk, Behcet Acikmese)\n * \n * https://arxiv.org/abs/1802.03827\n * \n */\n\n#include \"active_model.hpp\"\n#include \"EcosWrapper.hpp\"\n#include \"MosekWrapper.hpp\"\n#include \"Discretization.hpp\"\n#include \"SuccessiveConvexificationSOCP.hpp\"\n#include \"timing.hpp\"\n\n#include <iostream>\n#include <array>\n#include <cmath>\n#include <ctime>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n\nusing std::array;\nusing std::cout;\nusing std::endl;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::setw;\nusing std::setfill;\n\nstring get_output_path() {\n    return \"../output/\" + Model::get_name() + \"/\";\n}\n\nvoid clear_output_path() {\n    string command = \"rm -r \" + get_output_path();\n    assert(system(command.c_str()) == 0);\n}\n\nvoid make_output_path() {\n    string command = \"mkdir -p \" + get_output_path();\n    assert(system(command.c_str()) == 0);\n}\n\nint main() {\n    clear_output_path();\n    make_output_path();\n    Model model;\n\n    double weight_trust_region_sigma = 1e-3;\n    double weight_trust_region_xu = 1e-3;\n    double weight_virtual_control = 1e3;\n\n    double nu_tol = 1e-3;\n    double delta_tol = 1e-3;\n\n    const size_t n_states = Model::n_states;\n    const size_t n_inputs = Model::n_inputs;\n\n    Eigen::Matrix<double, n_states, K> X;\n    Eigen::Matrix<double, n_inputs, K> U;\n\n    model.initialize(X, U);\n    \n    double sigma = model.total_time_guess();\n\n    array<Model::StateMatrix,   (K-1)> A_bar;\n    array<Model::ControlMatrix, (K-1)> B_bar;\n    array<Model::ControlMatrix, (K-1)> C_bar;\n    array<Model::StateVector,   (K-1)> Sigma_bar;\n    array<Model::StateVector,   (K-1)> z_bar;\n\n\n    optimization_problem::SecondOrderConeProgram socp = build_successive_convexification_SOCP ( \n        model, weight_trust_region_sigma, weight_trust_region_xu, weight_virtual_control, X, U, sigma, A_bar, B_bar, C_bar, Sigma_bar, z_bar );\n\n\n    // Cache indices for performance\n    const size_t sigma_index = socp.get_tensor_variable_index(\"sigma\", {});\n    size_t X_indices[n_states][K];\n    size_t U_indices[n_inputs][K];\n    for (size_t k = 0; k < K; k++) {\n        for (size_t i = 0; i < n_states; ++i) X_indices[i][k] = socp.get_tensor_variable_index(\"X\",{i,k});\n        for (size_t i = 0; i < n_inputs; ++i) U_indices[i][k] = socp.get_tensor_variable_index(\"U\",{i,k});\n    }\n\n    EcosWrapper solver(socp);\n//    MosekWrapper solver(socp);\n\n    const size_t iterations = 40;\n    for(size_t it = 0; it < iterations; it++) {\n\n        weight_trust_region_xu *= 1.2;\n\n        const double timer_total = tic();\n        double timer = tic();\n        calculate_discretization ( model, sigma, X, U, A_bar, B_bar, C_bar, Sigma_bar, z_bar );\n        cout << \"Time, discretization: \" << toc(timer) << \" ms\" << endl;\n\n\n\n        // Write problem to file\n        timer = tic();\n        string file_name_prefix;\n        {\n            ostringstream file_name_prefix_ss;\n            file_name_prefix_ss << get_output_path() << \"iteration\"\n            << setfill('0') << setw(3) << it << \"_\";\n            file_name_prefix = file_name_prefix_ss.str();\n        }\n        \n        {\n            ofstream f(file_name_prefix + \"problem.txt\");\n            socp.print_problem(f);\n        }\n        cout << \"Time, problem file: \" << toc(timer) << \" ms\" << endl;\n\n\n\n        timer = tic();\n        solver.solve_problem();\n        cout << \"Time, solver: \" << toc(timer) << \" ms\" << endl;\n\n\n\n//        timer = tic();\n//        if(!socp.feasibility_check(solver.get_solution_vector())) {\n//            cout << \"ERROR: Solver produced an invalid solution.\" << endl;\n//            return EXIT_FAILURE;\n//        }\n//        cout << \"Time, solution check: \" << toc(timer) << \" ms\" << endl;\n\n\n\n        // Read solution\n        for (size_t k = 0; k < K; k++) {\n            for (size_t i = 0; i < n_states; ++i) X(i,k) = solver.get_solution_value(X_indices[i][k]);\n            for (size_t i = 0; i < n_inputs; ++i) U(i,k) = solver.get_solution_value(U_indices[i][k]);\n        }\n        sigma = solver.get_solution_value(sigma_index);\n\n\n        // Write solution to files\n        timer = tic();\n        {\n            ofstream f(file_name_prefix + \"X.txt\");\n            f << X;\n        }\n        {\n            ofstream f(file_name_prefix + \"U.txt\");\n            f << U;\n        }\n        cout << \"Time, solution files: \" << toc(timer) << \" ms\" << endl;\n\n        cout << \"sigma   \" << sigma << endl;\n        cout << \"norm2_nu   \" << solver.get_solution_value(\"norm2_nu\", {}) << endl;\n        cout << \"Delta_sigma   \" << solver.get_solution_value(\"Delta_sigma\", {}) << endl;\n        cout << \"norm2_Delta   \" << solver.get_solution_value(\"norm2_Delta\", {}) << endl;\n        cout << \"Time, total: \" << toc(timer_total) << \" ms\" << endl;\n        cout << \"==========================================================\" << endl;\n\n        if (solver.get_solution_value(\"norm2_Delta\", {}) < delta_tol\n           && solver.get_solution_value(\"norm2_nu\", {}) < nu_tol){\n            cout << \"Converged after \" << it << \" iterations.\";\n            break;\n        }\n    }\n}", "meta": {"hexsha": "6c0e763584ca54725f840a2792f11cc1da7e8ec7", "size": 5282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_stars_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T13:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-09T16:50:13.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_issues_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "jonnyhyman/SuccessiveConvexificationCpp", "max_forks_repo_head_hexsha": "7243687d7dac88bf4d66ddb4cfb2016cb70cbb67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-20T10:16:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T06:27:22.000Z", "avg_line_length": 30.3563218391, "max_line_length": 143, "alphanum_fraction": 0.5872775464, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5684721446866263}}
{"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_focal_length.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/sfm/pose/four_point_focal_length_helper.h\"\n\nnamespace theia {\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nnamespace {\nvoid GetRigidTransform(const Matrix<double, 3, 4>& points1,\n                       const Matrix<double, 3, 4>& points2,\n                       const bool left_handed_coordinates,\n                       Eigen::Matrix3d* rotation,\n                       Vector3d* translation) {\n  // Move the centroid to th origin.\n  const Vector3d mean_points1 = points1.rowwise().mean();\n  const Vector3d mean_points2 = points2.rowwise().mean();\n\n  const Matrix<double, 3, 4> points1_shifted = points1.colwise() - mean_points1;\n  const Matrix<double, 3, 4> points2_shifted = points2.colwise() - mean_points2;\n\n  // Normalize to unit size.\n  const Matrix<double, 3, 4> points1_normalized =\n      points1_shifted.colwise().normalized();\n  const Matrix<double, 3, 4> points2_normalized =\n      points2_shifted.colwise().normalized();\n\n  // Compute the necessary rotation from the difference in points.\n  Matrix3d rotation_diff = points2_normalized * points1_normalized.transpose();\n  Eigen::JacobiSVD<Matrix3d> svd(rotation_diff,\n                                 Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  Matrix3d s = Matrix3d::Zero();\n  s(0, 0) = svd.singularValues()(0) < 0 ? -1.0 : 1.0;\n  s(1, 1) = svd.singularValues()(1) < 0 ? -1.0 : 1.0;\n  const double sign =\n      (svd.matrixU() * svd.matrixV().transpose()).determinant() < 0 ? -1.0\n                                                                    : 1.0;\n\n  if (left_handed_coordinates) {\n    s(2, 2) = -sign;\n  } else {\n    s(2, 2) = sign;\n  }\n  *rotation = svd.matrixU() * s * svd.matrixV().transpose();\n  *translation = - *rotation * mean_points1 + mean_points2;\n}\n\n}  // namespace\n\nint FourPointPoseAndFocalLength(\n    const std::vector<Eigen::Vector2d>& feature_vectors,\n    const std::vector<Eigen::Vector3d>& world_points_vector,\n    std::vector<Eigen::Matrix<double, 3, 4> >* projection_matrices) {\n  Eigen::Map<const Matrix<double, 2, 4> > features(feature_vectors[0].data());\n  Eigen::Map<const Matrix<double, 3, 4> > world_points(world_points_vector[0]\n                                                           .data());\n\n  // Normalize the points such that the mean = 0, variance = sqrt(2.0).\n  const Vector3d mean_world_point = world_points.rowwise().mean();\n  Eigen::Matrix<double, 3, 4> world_point_normalized =\n      world_points.colwise() - mean_world_point;\n  const double world_point_variance =\n      world_point_normalized.colwise().norm().mean();\n  world_point_normalized /= world_point_variance;\n\n  // Scale 2D data so variance = sqrt(2.0).\n  const double features_variance = features.colwise().norm().mean();\n  Eigen::Matrix<double, 2, 4> features_normalized =\n      features / features_variance;\n\n  // Precompute monomials.\n  const double glab = (world_point_normalized.col(0) -\n                       world_point_normalized.col(1)).squaredNorm();\n  const double glac = (world_point_normalized.col(0) -\n                       world_point_normalized.col(2)).squaredNorm();\n  const double glad = (world_point_normalized.col(0) -\n                       world_point_normalized.col(3)).squaredNorm();\n  const double glbc = (world_point_normalized.col(1) -\n                       world_point_normalized.col(2)).squaredNorm();\n  const double glbd = (world_point_normalized.col(1) -\n                       world_point_normalized.col(3)).squaredNorm();\n  const double glcd = (world_point_normalized.col(2) -\n                       world_point_normalized.col(3)).squaredNorm();\n\n  if (glab * glac * glad * glbc * glbd * glcd < 1e-15) {\n    return -1;\n  }\n\n  // Call the helper function.\n  std::vector<double> focal_length;\n  std::vector<Vector3d> depths;\n\n  FourPointFocalLengthHelper(glab, glac, glad, glbc, glbd, glcd,\n                             features_normalized, &focal_length, &depths);\n\n  if (focal_length.size() == 0) {\n    return -1;\n  }\n\n  // Get the rotation and translation.\n  for (int i = 0; i < focal_length.size(); i++) {\n    // Create world points in camera coordinate system.\n    Matrix<double, 3, 4> adjusted_world_points;\n    adjusted_world_points.block<2, 4>(0, 0) = features_normalized;\n    adjusted_world_points.row(2).setConstant(focal_length[i]);\n    adjusted_world_points.col(1) *= depths[i].x();\n    adjusted_world_points.col(2) *= depths[i].y();\n    adjusted_world_points.col(3) *= depths[i].z();\n\n    // Fix the scale.\n    Matrix<double, 6, 1> d;\n    d(0) = sqrt(glab / (adjusted_world_points.col(0) -\n                        adjusted_world_points.col(1)).squaredNorm());\n    d(1) = sqrt(glac / (adjusted_world_points.col(0) -\n                        adjusted_world_points.col(2)).squaredNorm());\n    d(2) = sqrt(glad / (adjusted_world_points.col(0) -\n                        adjusted_world_points.col(3)).squaredNorm());\n    d(3) = sqrt(glbc / (adjusted_world_points.col(1) -\n                        adjusted_world_points.col(2)).squaredNorm());\n    d(4) = sqrt(glbd / (adjusted_world_points.col(1) -\n                        adjusted_world_points.col(3)).squaredNorm());\n    d(5) = sqrt(glcd / (adjusted_world_points.col(2) -\n                        adjusted_world_points.col(3)).squaredNorm());\n\n    const double gta = d.mean();\n\n    adjusted_world_points *= gta;\n\n    // Get the transformation by aligning the points.\n    Matrix3d rotation;\n    Vector3d translation;\n    GetRigidTransform(world_point_normalized, adjusted_world_points, false,\n                      &rotation, &translation);\n\n    translation =\n        world_point_variance * translation - rotation * mean_world_point;\n\n    focal_length[i] *= features_variance;\n\n    Matrix<double, 3, 4> transformation_matrix;\n    transformation_matrix.block<3, 3>(0, 0) = rotation;\n    transformation_matrix.col(3) = translation;\n    Matrix3d camera_matrix =\n        Eigen::DiagonalMatrix<double, 3>(focal_length[i], focal_length[i], 1.0);\n    projection_matrices->push_back(camera_matrix * transformation_matrix);\n  }\n  return projection_matrices->size();\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "8134bc4acc17311621bee3514c6b046829851db8", "size": 8065, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_focal_length.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_focal_length.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_focal_length.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.7875647668, "max_line_length": 80, "alphanum_fraction": 0.667699938, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5684721342708259}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// MetricFittingEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Sheet material energy that is a function of the **deformation gradient**.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  05/30/2019 17:15:18\n////////////////////////////////////////////////////////////////////////////////\n#ifndef METRICFITTINGENERGY_HH\n#define METRICFITTINGENERGY_HH\n\n#include <Eigen/Dense>\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n\nstruct MetricFittingEnergy {\n    using M2d = Eigen::Matrix2d;\n\n    M2d targetMetric;\n\n    void setMatrix(Eigen::Ref<const M2d> C) {\n        m_C = C;\n    }\n\n    double energy() const {\n        return 0.5 * (m_C - targetMetric).squaredNorm();\n    }\n\n    M2d denergy() const { return m_C - targetMetric; }\n\n    auto delta_denergy(Eigen::Ref<const M2d> dC) const { return dC; } // 4th order identity tensor\n\n    M2d currMetric() const {\n        return m_C;\n    }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    M2d m_C, m_diff;\n};\n\n#endif /* end of include guard: METRICFITTINGENERGY_HH */\n", "meta": {"hexsha": "6da7c9a0bd9ce29854aa575b29432b49860f2b83", "size": 1179, "ext": "hh", "lang": "C++", "max_stars_repo_path": "MetricFittingEnergy.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": "MetricFittingEnergy.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": "MetricFittingEnergy.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": 27.4186046512, "max_line_length": 98, "alphanum_fraction": 0.5385920271, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5684721342708259}}
{"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 <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\nint main()\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 = params.num_cell;   //create a local num_cell so don't have to type params.num_cell everywhere\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 = 100.*params.tolerance_i;\n    const int N = params.num_cell -1;\n    const int num_rows = N*N*N;  //number of rows in the solution vectors (V, n, p)\n    //NOTE: num_rows is the same as num_elements\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 use indicies for n and p... starting from 1 --> since is more natural--> corresponds to 1st node inside the device...\n    //NOTE: ALL THESE INCLUDE THE INTERIOR ELEMENTS ONLY\n    std::vector<double> n(num_rows+ 1), p(num_rows+ 1), oldp(num_rows+ 1), newp(num_rows+ 1), oldn(num_rows+ 1), newn(num_rows+ 1);\n    std::vector<double> oldV(num_rows+ 1), newV(num_rows+ 1), V(num_rows+ 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_Xd(num_rows);  //vector for storing solutions to the  sparse solver (indexed from 0, so only num_rows size)\n\n    //For the following, only need gen rate on insides, so N+1 size is enough\n    std::vector<double> Un(num_rows+1); //will store generation rate as vector, for easy use in rhs\n    std::vector<double> Up = Un;\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+1, num_cell+1, num_cell+1), J_total_X(num_cell+1, num_cell+1, num_cell+1), J_total_Y(num_cell+1, num_cell+1, num_cell+1);                  //matrices for spacially dependent current\n\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    //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//------------------------------------------------------------------------------------\n    //Construct objects\n    Poisson poisson(params);\n    Recombo recombo(params);\n    Continuity_p continuity_p(params);  //note this also sets up the constant top and bottom electrode BC's\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\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 = 0;\n    poisson.set_V_bottomBC(params, Va);\n    poisson.set_V_topBC(params, Va);\n\n    //Initial conditions\n    //std::vector<double> diff;\n    //for (int x = 0; x <= num_cell; x++)\n       //diff[x] = (poisson.get_V_topBC()[x] - poisson.get_V_bottomBC()[x])/num_cell;    //note, the difference can be different at different x values..., diff is in Z directiont\n\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;  //this is  calculated correctly\n\n    int index = 0;\n    for (int k = 1; k <= N; k++) {\n        index++;\n        V[index] = poisson.get_V_bottomBC(0,0) + diff*k;   //for now just  use 1 pt on bottom BC, since is uniform anyway\n        for (int i = 2; i <= N*N; i++) {//  %elements along the x and y directions assumed to have same V\n            index++;\n            V[index] = V[index-1];\n        }\n    }\n\n    //side BCs, insulating BC's\n    poisson.set_V_leftBC_X(V);\n    poisson.set_V_rightBC_X(V);\n    poisson.set_V_leftBC_Y(V);\n    poisson.set_V_rightBC_Y(V);\n\n    //Fill n and p with initial conditions (need for error calculation)\n    double min_dense = continuity_n.get_n_bottomBC(1,1) < continuity_p.get_p_topBC(1,1) ? continuity_n.get_n_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 = 1; i<= num_rows; i++) {\n        n[i] = min_dense;\n        p[i] = min_dense;\n    }\n\n    //Convert the n and p to n_matrix and p_matrix\n    continuity_n.to_matrix(n);\n    continuity_p.to_matrix(p);\n\n    poisson.setup_matrix();  //outside of loop since matrix never changes\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+1);  //note: since n and p solutions are in vector form, can use vector form here also\n\n    for (Va_cnt = 0; Va_cnt <= num_V +1; Va_cnt++) {  //+1 b/c 1st Va is the equil run\n        not_converged = false;\n        not_cnv_cnt = 0;\n        if (params.tolerance > 1e-5)\n            std::cerr<<\"ERROR: Tolerance has been increased to > 1e-5\" <<std::endl;\n\n        if (Va_cnt==0) {\n            params.use_tolerance_eq();  //relaxed tolerance for equil. run\n            params.use_w_eq();\n            Va = 0;\n        }\n        else {\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        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        //-----------------------------------------------------------\n        error_np = 1.0;\n        iter = 0;\n\n        while (error_np > params.tolerance) {\n            //std::cout << \"Va \" << Va <<std::endl;\n\n            //-----------------Solve Poisson Equation------------------------------------------------------------------     \n            poisson.set_rhs(n, p);  //this finds netcharge and sets rhs\n            //std::cout << poisson.get_sp_matrix() << std::endl;\n            oldV = V;\n\n\n\n            if (iter == 0) { //INSTEAD OF HAVING IF here, can move these 2 lines, outside of the loop\n                poisson_LU.analyzePattern(poisson.get_sp_matrix());  //by doing only on first iter, since pattern never changes, save a bit cpu\n                poisson_LU.factorize(poisson.get_sp_matrix());\n            }\n            soln_Xd = poisson_LU.solve(poisson.get_rhs());\n\n\n/*\n            if (iter == 0) {  //This is slower than  LU\n                SCholesky.analyzePattern(poisson.get_sp_matrix());\n                SCholesky.factorize(poisson.get_sp_matrix());         //since numerical values of Poisson matrix don't change for 1 set of BC's, can factorize, just on 1st iter\n            }\n            soln_Xd = SCholesky.solve(poisson.get_rhs());\n            */\n            //std::cout << soln_Xd << 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 = 1; i<=num_rows; i++) {\n                newV[i] = soln_Xd(i-1);   //fill VectorXd  rhs of the equation\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 side BC's and V_matrix\n            poisson.set_V_leftBC_X(V);\n            poisson.set_V_rightBC_X(V);\n            poisson.set_V_leftBC_Y(V);\n            poisson.set_V_rightBC_Y(V);\n            poisson.to_matrix(V);\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            if (Va_cnt > 0) {\n                for (int i = 1; i <= num_rows; i++) {\n                    Un[i] = params.Photogen_scaling;  //This is what was used in Matlab version for testing.   photogen.getPhotogenRate()(i,j); //- R_Langevin(i,j);\n                }\n                Up = Un;\n            }\n\n            //--------------------------------Solve equations for n and p------------------------------------------------------------ \n\n            continuity_n.setup_eqn(poisson.get_V_matrix(), Un, n);\n            oldn = n;\n\n            //std::chrono::high_resolution_clock::time_point start2 = std::chrono::high_resolution_clock::now();  //start clock timer\n\n            if (iter == 0 ) //can move this outside of the loop, instead of using if here...\n                cont_n_LU.analyzePattern(continuity_n.get_sp_matrix());  //by doing only on first iter, since pattern never changes, save a bit cpu\n            cont_n_LU.factorize(continuity_n.get_sp_matrix());  //need to do on each iter, b/c matrix elements change\n            soln_Xd = cont_n_LU.solve(continuity_n.get_rhs());\n\n            //std::chrono::high_resolution_clock::time_point finish2 = std::chrono::high_resolution_clock::now();\n            //std::chrono::duration<double> time2 = std::chrono::duration_cast<std::chrono::duration<double>>(finish2-start2);\n            //std::cout << \"CPU time = \" << time2.count() << std::endl;\n\n            //std::cout << \"solver error \" << continuity_n.get_sp_matrix() * soln_Xd - continuity_n.get_rhs() << std::endl;\n/*\n            input = continuity_n.get_sp_matrix();\n            if (iter == 0)\n                BiCGStab_solver.analyzePattern(input);\n            BiCGStab_solver.factorize(input);  //this computes preconditioner, if use along with analyzePattern (for 1st iter)\n            //BiCGStab_solver.compute(input);  //this computes the preconditioner.\n            soln_Xd = BiCGStab_solver.solve(continuity_n.get_rhs());\n            //std::cout << soln_Xd << std::endl;\n            */\n\n            //std::cout << \"#iterations:     \" << solver.iterations() << std::endl;\n            //std::cout << \"estimated error: \" << BiCGStab_solver.error()      << std::endl;\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 = 1; i<=num_rows; i++) {\n                newn[i] = soln_Xd(i-1);   //fill VectorXd  rhs of the equation\n            }\n\n            //-------------------------------------------------------\n            continuity_p.setup_eqn(poisson.get_V_matrix(), Up, p);\n            //std::cout << continuity_p.get_sp_matrix() << std::endl;   //Note: get rhs, returns an Eigen VectorXd\n            oldp = p;\n/*\n            input = continuity_p.get_sp_matrix();\n            if (iter == 0)\n                BiCGStab_solver.analyzePattern(input);\n            BiCGStab_solver.factorize(input);  //this computes preconditioner, if use along with analyzePattern (for 1st iter)\n            //BiCGStab_solver.compute(input);  //this computes the preconditioner..compute(input);\n            soln_Xd = BiCGStab_solver.solve(continuity_p.get_rhs());\n*/\n\n            if (iter == 0 )\n                cont_p_LU.analyzePattern(continuity_p.get_sp_matrix());\n            cont_p_LU.factorize(continuity_p.get_sp_matrix());\n            soln_Xd = cont_p_LU.solve(continuity_p.get_rhs());\n\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 = 1; i<=num_rows; i++) {\n                newp[i] = soln_Xd(i-1);   //fill VectorXd  rhs of the equation\n            }\n\n            //------------------------------------------------\n\n            //if get negative p's or n's set them = 0\n            for (int i = 1; i <= num_rows; i++) {\n                if (newp[i] < 0.0) newp[i] = 0;\n                if (newn[i] < 0.0) newn[i] = 0;\n            }\n\n            //calculate the error\n            old_error = error_np;\n\n            //THIS CAN BE MOVED TO A FUNCTION IN UTILS\n            for (int i = 1; i <= num_rows; i++) {\n                if (newp[i]!=0 && newn[i] !=0) {\n                    error_np_vector[i] = (abs(newp[i]-oldp[i]) + abs(newn[i]-oldn[i]))/abs(oldp[i]+oldn[i]);\n                }\n            }\n            error_np = *std::max_element(error_np_vector.begin()+1,error_np_vector.end());  //+1 b/c we are not using the 0th element\n            std::fill(error_np_vector.begin(), error_np_vector.end(),0.0);  //refill with 0's so have fresh one for next iter\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 > 2000) {\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 = utils.linear_mix(params, newn, oldn);\n\n            //Apply side continuity equation  BC's\n            //WE ARE UPDATING BC'S here b/c we need them for setting up the n and p matrices below\n            //Bc's are also updated when setup continuity eqn.\n            continuity_n.set_n_leftBC_X(n);  //this sets both x and y left BC's\n            continuity_n.set_n_rightBC_X(n);\n            continuity_n.set_n_leftBC_Y(n);  //this sets both x and y left BC's\n            continuity_n.set_n_rightBC_Y(n);\n\n            continuity_p.set_p_leftBC_X(p);\n            continuity_p.set_p_rightBC_X(p);\n            continuity_p.set_p_leftBC_Y(p);\n            continuity_p.set_p_rightBC_Y(p);\n            //note: top and bottom BC's don't need to be changed for now, since assumed to be constant... (they are set when initialize continuity objects)\n\n            //Convert the n and p to n_matrix and p_matrix\n            continuity_n.to_matrix(n);\n            continuity_p.to_matrix(p);\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();\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        //---------------------Write to file----------------------------------------------------------------\n        utils.write_details(params, Va, poisson.get_V_matrix(), p, n, J_total_Z, Un);\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": "b6b1d8782fb8740d1e659629bdd74d6f8f9060cd", "size": 19765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3D/C++_implementation/Two-charge-carriers/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/Two-charge-carriers/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/Two-charge-carriers/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": 48.5626535627, "max_line_length": 264, "alphanum_fraction": 0.5959524412, "num_tokens": 4903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915994285382, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5684721331146729}}
{"text": "//\n// Created by Hamza El-Kebir on 6/6/21.\n//\n\n#ifndef LODESTAR_TESTAUXFUNCTIONS_HPP\n#define LODESTAR_TESTAUXFUNCTIONS_HPP\n\n#include <Eigen/Dense>\n\n// A(x, u)\nEigen::Matrix<double, 2, 2> jacStates(const double x, const double y, const double u, const double t) {\n    Eigen::Matrix<double, 2, 2> mat;\n    mat <<  y+u+2.0*x, x,\n            0.0, 2.0*y;\n\n    return mat;\n}\n// B(x, u)\nEigen::Matrix<double, 2, 1> jacInputs(const double x, const double y, const double u, const double t) {\n    Eigen::Matrix<double, 2, 1> mat;\n    mat <<  x+2e-01,\n            2.0;\n\n    return mat;\n}\n\n#endif //LODESTAR_TESTAUXFUNCTIONS_HPP\n", "meta": {"hexsha": "07b34d92049fb33a664e3944480460663b02a3d9", "size": 618, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/TestAuxFunctions.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": "tests/TestAuxFunctions.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": "tests/TestAuxFunctions.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": 22.0714285714, "max_line_length": 103, "alphanum_fraction": 0.6343042071, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5684010784119626}}
{"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/heat_method_distance.h\"\n#include \"geometrycentral/surface/halfedge_factories.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/surface_centers.h\"\n#include \"geometrycentral/surface/vector_heat_method.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include <sstream>\n#include <chrono>\n\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// Algorithm parameters for Vector Heat method\nfloat tCoef = 1.0;\nstd::unique_ptr<VectorHeatMethodSolver> solver;\n\n// HELPER FUNCTIONS ------------------------------------------------------------\n\n// Loads a mesh from a NumPy array\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// Precompute parallel transport and logarithmic map for a given neighborhood.\nEigen::MatrixXd precomputeHarmonic(Vertex& sourceV, Eigen::Matrix<size_t, Eigen::Dynamic, 1> targetVs,\n                                  Eigen::Matrix<size_t, Eigen::Dynamic, 1>& sample_points) {\n  if (solver == nullptr) {\n    solver.reset(new VectorHeatMethodSolver(*geometry, tCoef));\n  }\n\n  // Coordinate systems are aligned to smoothed principal curvature directions\n  Vector2 sourcePrincipalCurvature = geometry->vertexPrincipalCurvatureDirections[sourceV].normalize();\n\n  // To compute parallel transport from point i (targetV) to point j (sourceV),\n  // we transport the x-axis (the principal curvature direction) from sourceV to targetV.\n\n  // First, set the source vectors to the principal curvature directions.\n  std::vector<std::tuple<SurfacePoint, Vector2>> points;\n  points.emplace_back(sourceV, sourcePrincipalCurvature);\n\n  // Then, compute parallel transport of source vectors.\n  VertexData<Vector2> connection = solver->transportTangentVectors(points);\n\n  // And compute the logarithmic map from point i to j\n  VertexData<Vector2> logmap = solver->computeLogMap(sourceV);\n\n  // Store the results in an Eigen matrix, which can be accessed as a NumPy array.\n  Eigen::MatrixXd res(targetVs.rows(), 4);\n\n  // For every target point\n  for (size_t i = 0; i < targetVs.rows(); i++) {\n    size_t v = sample_points(targetVs(i));\n\n    // The original logarithmic map is computed with a coordinate system aligned to the first edge.\n    // To align the logarithmic map to the principal curvature directions,\n    // we rotate the logmap by the principal curvature direction at the source point.\n    Vector2 targetCoords = logmap[v] / sourcePrincipalCurvature;\n\n    // Likewise for parallel transport, but we rotate by the principal curvature direction at the target point.\n    Vector2 targetPrincipalCurvature = geometry->vertexPrincipalCurvatureDirections[v].normalize();\n    Vector2 targetConnection = connection[v] / targetPrincipalCurvature;\n\n    // Store the parallel transport (connection) and logarithmic map.\n    res(i, 0) = targetConnection.x;\n    res(i, 1) = targetConnection.y;\n    res(i, 2) = targetCoords.x;\n    res(i, 3) = targetCoords.y;\n  }\n\n  return res;\n}\n\n// PRECOMPUTATION for HSN ------------------------------------------------------------\n\n// Precomputes the logarithmic map and parallel transport, given a mesh.\n// The mesh should be provides as a NumPy array of vertex positions and a NumPy array of face indices.\n// Additionally, one should provide a NumPy array of edge indices (source, target),\n// a NumPy array with the degree of every source vertex, and indices of sampled points to return values for.\nEigen::MatrixXd precompute(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces,\n        Eigen::Matrix<size_t, Eigen::Dynamic, 2>& edge_index, Eigen::Matrix<size_t, Eigen::Dynamic, 1> degree,\n        Eigen::Matrix<size_t, Eigen::Dynamic, 1>& sample_points) {\n\n  // Load mesh\n  std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n\n  geometry->requireVertexIndices();\n  geometry->requireVertexLumpedMassMatrix();\n  geometry->requireVertexPrincipalCurvatureDirections();\n\n  // Setup solver for Vector Heat Method.\n  solver.reset(new VectorHeatMethodSolver(*geometry, tCoef));\n\n  // Store the results in an Eigen matrix, which can be accessed as a NumPy array.\n  Eigen::MatrixXd res(edge_index.rows(), 4);\n  size_t index = 0;\n  // For each sampled point:\n  for (size_t row = 0; row < sample_points.rows(); row++) {\n    Vertex v = mesh->vertex(sample_points(row));\n\n    // Compute parallel transport and logarithmic map for neighborhood.\n    res.block(index, 0, degree(row), 4) = precomputeHarmonic(v, edge_index.block(index, 1, degree(row), 1), sample_points);\n    index += degree(row);\n  }\n\n  geometry->unrequireVertexPrincipalCurvatureDirections();\n  geometry->unrequireVertexLumpedMassMatrix();\n  geometry->unrequireVertexIndices();\n  return res;\n}\n\n// Computes the vertex lumped mass matrix for each sampled vertex,\n// automatically adding the weights from nearest geodesic neighbors.\nEigen::MatrixXd weights(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces,\n        Eigen::Matrix<size_t, Eigen::Dynamic, 1>& sample_points, Eigen::Matrix<size_t, Eigen::Dynamic, 1>& labels) {\n\n  // Load mesh\n  std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n\n  geometry->requireVertexIndices();\n  geometry->requireVertexLumpedMassMatrix();\n\n  // We use short-time heat diffusion to retrieve geodesic nearest neighbors.\n  VectorHeatMethodSolver vhmSolver(*geometry, 0.0001);\n\n  // Set up indices of sampled points to diffuse.\n  std::vector<std::tuple<SurfacePoint, double>> points;\n  for (size_t row = 0; row < sample_points.rows(); row++) {\n    points.emplace_back(SurfacePoint(mesh->vertex(sample_points(row))), labels(row));\n  }\n\n  // Solve heat diffusion.\n  VertexData<double> scalarExtension = vhmSolver.extendScalar(points);\n\n  // Store the results in an Eigen matrix, which can be accessed as a NumPy array.\n  Eigen::MatrixXd res = Eigen::MatrixXd::Zero(sample_points.rows(), 1);\n  // For each vertex:\n  for (size_t row = 0; row < pos.rows(); row++) {\n    size_t to_idx = std::lround(scalarExtension[mesh->vertex(row)]);\n\n    // Clamp nearest neighbor index from heat diffusion to range [0, n_vertices]\n    if (to_idx >= sample_points.rows()) {\n      to_idx = sample_points.rows() - 1;\n    } else if (to_idx < 0) {\n      to_idx = 0;\n    }\n\n    // Add vertex lumped mass to nearest sampled vertex.\n    res(to_idx) += geometry->vertexLumpedMassMatrix.coeff(row, row);\n  }\n  \n  geometry->unrequireVertexLumpedMassMatrix();\n  geometry->unrequireVertexIndices();\n\n  return res;\n}\n\n// UTILITIES for HSN ------------------------------------------------------------\n\n// Compute the surface area of a mesh.\ndouble surface_area(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces) {\n\n  // Load mesh\n  std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n\n  float surfaceArea = 0.0f;\n  for (Face f : mesh->faces()) {\n    surfaceArea += geometry->faceArea(f);\n  }\n\n  return surfaceArea;\n}\n\n// Compute geodesic nearest neighbors\nEigen::MatrixXd nearest(Eigen::MatrixXd& pos, Eigen::Matrix<size_t, Eigen::Dynamic, Eigen::Dynamic>& faces,\n        Eigen::Matrix<size_t, Eigen::Dynamic, 1>& selected_points, Eigen::Matrix<size_t, Eigen::Dynamic, 1>& labels) {\n\n  // Load mesh\n  std::tie(mesh, geometry) = loadMesh_np(pos, faces);\n\n  geometry->requireVertexIndices();\n\n  // We use short-time heat diffusion to retrieve geodesic nearest neighbors.\n  VectorHeatMethodSolver vhmSolver(*geometry, 0.0001);\n\n  // Set up indices of sampled points to diffuse.\n  std::vector<std::tuple<SurfacePoint, double>> points;\n  for (size_t row = 0; row < selected_points.rows(); row++) {\n    points.emplace_back(SurfacePoint(mesh->vertex(selected_points(row))), labels(row));\n  }\n\n  // Solve heat diffusion\n  VertexData<double> scalarExtension = vhmSolver.extendScalar(points);\n\n  // Store the results in an Eigen matrix, which can be accessed as a NumPy array.\n  Eigen::MatrixXd res(pos.rows(), 1);\n  for (size_t row = 0; row < pos.rows(); row++) {\n    res(row) = scalarExtension[mesh->vertex(row)];\n  }\n  \n  geometry->unrequireVertexIndices();\n\n  return res;\n}\n\nPYBIND11_MODULE(vectorheat, m) {\n    m.doc() = R\"pbdoc(\n        Harmonic Surface Networks precomputation module.\n        -----------------------\n\n        .. currentmodule:: precomputation\n\n        .. autosummary::\n           :toctree: _generate\n\n           add\n           precompute\n           diameter\n    )pbdoc\";\n\n    m.def(\"precompute\", &precompute, py::return_value_policy::copy, R\"pbdoc(\n        Precompute parallel transport and logarithmic map for meshes given by pos, face, edges and degree.\n    )pbdoc\");\n\n    m.def(\"surface_area\", &surface_area, py::return_value_policy::copy, R\"pbdoc(\n        Computes surface area of the given mesh.\n    )pbdoc\");\n\n    m.def(\"weights\", &weights, py::return_value_policy::copy, R\"pbdoc(\n        Computes vertex lumped mass matrix for sampled points.\n    )pbdoc\");\n\n    m.def(\"nearest\", &nearest, py::return_value_policy::copy, R\"pbdoc(\n        Returns a mapping from all vertices to the nearest sampled points.\n    )pbdoc\");\n\n#ifdef VERSION_INFO\n    m.attr(\"__version__\") = VERSION_INFO;\n#else\n    m.attr(\"__version__\") = \"dev\";\n#endif\n}\n", "meta": {"hexsha": "1f4a8efad8dac036bbf1b8c439f275f297246cc7", "size": 10075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vectorheat/src/main.cpp", "max_stars_repo_name": "rubenwiersma/hsn", "max_stars_repo_head_hexsha": "f8eeccb407a92f09788f2c98b865ec35da6051a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2020-05-01T21:02:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:48:02.000Z", "max_issues_repo_path": "vectorheat/src/main.cpp", "max_issues_repo_name": "rubenwiersma/hsn", "max_issues_repo_head_hexsha": "f8eeccb407a92f09788f2c98b865ec35da6051a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-25T18:10:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-15T12:21:20.000Z", "max_forks_repo_path": "vectorheat/src/main.cpp", "max_forks_repo_name": "rubenwiersma/hsn", "max_forks_repo_head_hexsha": "f8eeccb407a92f09788f2c98b865ec35da6051a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T04:06:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T22:27:41.000Z", "avg_line_length": 37.3148148148, "max_line_length": 123, "alphanum_fraction": 0.6998511166, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.5684010593921658}}
{"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_COSH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COSH_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 cosine: \\f$(e^{x}+e^{-x})/2\\f$.\n\n    @see sinh, tanh, sech, csch, sinhcosh\n\n\n    @par Header <boost/simd/function/cosh.hpp>\n\n    @par Example:\n\n      @snippet cosh.cpp cosh\n\n    @par Possible output:\n\n      @snippet cosh.txt cosh\n  **/\n  IEEEValue cosh(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cosh.hpp>\n#include <boost/simd/function/simd/cosh.hpp>\n\n#endif\n", "meta": {"hexsha": "519483348ab4215a6dfc1d34c7eff426d0f40774", "size": 1020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/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/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/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": 23.1818181818, "max_line_length": 100, "alphanum_fraction": 0.5666666667, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5683750714032133}}
{"text": "#pragma once\n#include \"utils.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace khmot {\n\nconst int STATE_SIZE = 6;\nconst int OBSERVATION_SIZE = 3;\nconst double EPSILON = 1e-9;\nconst double PI = M_PI;\nconstexpr double TAU = 2 * M_PI;\n\n// clang-format off\n// TODO: noise covariance matrix should be configurable\nconst auto defaultNoiseCov =\n    (Eigen::MatrixXd(STATE_SIZE, STATE_SIZE) << 0.5, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.5, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, .05, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, 0.0, 0.1, 0.0, 0.0,\n                                                0.0, 0.0, 0.0, 0.0, 0.1, 0.0,\n                                                0.0, 0.0, 0.0, 0.0, 0.0, .01)\n        .finished();\nconst auto defaultObsMatrix = // observe x, y, yaw\n    (Eigen::MatrixXd(STATE_SIZE, STATE_SIZE) << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 1.0, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, 1.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                                0.0, 0.0, 0.0, 0.0, 0.0, 0.0)\n        .finished();\n// clang-format on\n\nusing State = Eigen::Matrix<double, STATE_SIZE, 1>;\nusing Covariance = Eigen::Matrix<double, STATE_SIZE, STATE_SIZE>;\n\nenum StateMembers {\n  StateMemberX = 0,\n  StateMemberY,\n  StateMemberYaw,\n  StateMemberVx,\n  StateMemberVy,\n  StateMemberVyaw\n};\n\nstruct KalmanObservation {\n  State state = Eigen::VectorXd::Zero(STATE_SIZE);\n  Covariance covariance =\n      Eigen::MatrixXd::Identity(STATE_SIZE, STATE_SIZE) * EPSILON;\n  double timestamp = 0.0;\n};\n\nclass Kalman {\n public:\n  Kalman(bool omnidirectional = true,\n         Eigen::MatrixXd noiseCov = defaultNoiseCov);\n  const Covariance& covariance() const { return P_; };\n  const State& state() const { return state_; };\n\n  void correct(KalmanObservation obs);\n  void predict(const double timestamp);\n  double lastObsTime() const { return lastObsTime_; };\n  void reset();\n  void wrapYaw();\n\n private:\n  bool initialized_;\n  bool omnidirectional_;  // Restrict motion sideways for non-omnidirectional\n                          // robots\n  double lastPredTime_;\n  double lastObsTime_;\n  Eigen::MatrixXd H_;  // KalmanObservation matrix\n  Eigen::MatrixXd F_;  // State transition matrix (system dynamics)\n  Eigen::MatrixXd Q_;  // Process noise covariance matrix\n  State state_;        // Estimated state vector\n  Covariance P_;       // Estimated error covariance matrix\n};\n\ndouble clampRotation(double rotation);\nvoid preprocessObs(KalmanObservation& obs);\n\n}  // namespace khmot\n", "meta": {"hexsha": "2b57434d68519c5992e1bb71847a1698fb2c1183", "size": 2822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "khmot/src/kalman.hpp", "max_stars_repo_name": "r7vme/khmot", "max_stars_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T11:05:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T20:01:37.000Z", "max_issues_repo_path": "khmot/src/kalman.hpp", "max_issues_repo_name": "r7vme/khmot", "max_issues_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-12T02:10:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-25T15:35:58.000Z", "max_forks_repo_path": "khmot/src/kalman.hpp", "max_forks_repo_name": "r7vme/khmot", "max_forks_repo_head_hexsha": "2920ed01c66e906d9099a80bbfd3e5adbbac6633", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T06:01:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-15T06:01:26.000Z", "avg_line_length": 33.5952380952, "max_line_length": 77, "alphanum_fraction": 0.5506732814, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5683750694925835}}
{"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: Abner Salgado, Texas A&M University 2009 \n */ \n\n\n// @sect3{Include files}  \n\n// 我们首先包括所有必要的deal.II头文件和一些C++相关的文件。它们中的每一个都已经在以前的教程程序中讨论过了，所以我们在这里就不做详细介绍了。\n\n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/base/point.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/multithread_info.h> \n#include <deal.II/base/thread_management.h> \n#include <deal.II/base/work_stream.h> \n#include <deal.II/base/parallel.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/conditional_ostream.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/solver_gmres.h> \n#include <deal.II/lac/sparse_ilu.h> \n#include <deal.II/lac/sparse_direct.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/grid/grid_in.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/dofs/dof_renumbering.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_tools.h> \n#include <deal.II/fe/fe_system.h> \n\n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <cmath> \n#include <iostream> \n\n// 最后这和以前的所有程序一样。\n\nnamespace Step35 \n{ \n  using namespace dealii; \n// @sect3{Run time parameters}  \n\n// 由于我们的方法有几个可以微调的参数，我们把它们放到一个外部文件中，这样就可以在运行时确定它们。\n\n// 这尤其包括辅助变量  $\\phi$  的方程表述，为此我们声明一个  <code>enum</code>  。接下来，我们声明一个类，它将读取和存储我们的程序运行所需的所有参数。\n\n  namespace RunTimeParameters \n  { \n    enum class Method \n    { \n      standard, \n      rotational \n    }; \n\n    class Data_Storage \n    { \n    public: \n      Data_Storage(); \n\n      void read_data(const std::string &filename); \n\n      Method form; \n\n      double dt; \n      double initial_time; \n      double final_time; \n\n      double Reynolds; \n\n      unsigned int n_global_refines; \n\n      unsigned int pressure_degree; \n\n      unsigned int vel_max_iterations; \n      unsigned int vel_Krylov_size; \n      unsigned int vel_off_diagonals; \n      unsigned int vel_update_prec; \n      double       vel_eps; \n      double       vel_diag_strength; \n\n      bool         verbose; \n      unsigned int output_interval; \n\n    protected: \n      ParameterHandler prm; \n    }; \n\n// 在这个类的构造函数中，我们声明所有的参数。这方面的细节已经在其他地方讨论过了，例如在  step-29  。\n\n    Data_Storage::Data_Storage() \n      : form(Method::rotational) \n      , dt(5e-4) \n      , initial_time(0.) \n      , final_time(1.) \n      , Reynolds(1.) \n      , n_global_refines(0) \n      , pressure_degree(1) \n      , vel_max_iterations(1000) \n      , vel_Krylov_size(30) \n      , vel_off_diagonals(60) \n      , vel_update_prec(15) \n      , vel_eps(1e-12) \n      , vel_diag_strength(0.01) \n      , verbose(true) \n      , output_interval(15) \n    { \n      prm.declare_entry(\"Method_Form\", \n                        \"rotational\", \n                        Patterns::Selection(\"rotational|standard\"), \n                        \" Used to select the type of method that we are going \" \n                        \"to use. \"); \n      prm.enter_subsection(\"Physical data\"); \n      { \n        prm.declare_entry(\"initial_time\", \n                          \"0.\", \n                          Patterns::Double(0.), \n                          \" The initial time of the simulation. \"); \n        prm.declare_entry(\"final_time\", \n                          \"1.\", \n                          Patterns::Double(0.), \n                          \" The final time of the simulation. \"); \n        prm.declare_entry(\"Reynolds\", \n                          \"1.\", \n                          Patterns::Double(0.), \n                          \" The Reynolds number. \"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Time step data\"); \n      { \n        prm.declare_entry(\"dt\", \n                          \"5e-4\", \n                          Patterns::Double(0.), \n                          \" The time step size. \"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Space discretization\"); \n      { \n        prm.declare_entry(\"n_of_refines\", \n                          \"0\", \n                          Patterns::Integer(0, 15), \n                          \" The number of global refines we do on the mesh. \"); \n        prm.declare_entry(\"pressure_fe_degree\", \n                          \"1\", \n                          Patterns::Integer(1, 5), \n                          \" The polynomial degree for the pressure space. \"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Data solve velocity\"); \n      { \n        prm.declare_entry( \n          \"max_iterations\", \n          \"1000\", \n          Patterns::Integer(1, 1000), \n          \" The maximal number of iterations GMRES must make. \"); \n        prm.declare_entry(\"eps\", \n                          \"1e-12\", \n                          Patterns::Double(0.), \n                          \" The stopping criterion. \"); \n        prm.declare_entry(\"Krylov_size\", \n                          \"30\", \n                          Patterns::Integer(1), \n                          \" The size of the Krylov subspace to be used. \"); \n        prm.declare_entry(\"off_diagonals\", \n                          \"60\", \n                          Patterns::Integer(0), \n                          \" The number of off-diagonal elements ILU must \" \n                          \"compute. \"); \n        prm.declare_entry(\"diag_strength\", \n                          \"0.01\", \n                          Patterns::Double(0.), \n                          \" Diagonal strengthening coefficient. \"); \n        prm.declare_entry(\"update_prec\", \n                          \"15\", \n                          Patterns::Integer(1), \n                          \" This number indicates how often we need to \" \n                          \"update the preconditioner\"); \n      } \n      prm.leave_subsection(); \n\n      prm.declare_entry(\"verbose\", \n                        \"true\", \n                        Patterns::Bool(), \n                        \" This indicates whether the output of the solution \" \n                        \"process should be verbose. \"); \n\n      prm.declare_entry(\"output_interval\", \n                        \"1\", \n                        Patterns::Integer(1), \n                        \" This indicates between how many time steps we print \" \n                        \"the solution. \"); \n    } \n\n    void Data_Storage::read_data(const std::string &filename) \n    { \n      std::ifstream file(filename); \n      AssertThrow(file, ExcFileNotOpen(filename)); \n\n      prm.parse_input(file); \n\n      if (prm.get(\"Method_Form\") == std::string(\"rotational\")) \n        form = Method::rotational; \n      else \n        form = Method::standard; \n\n      prm.enter_subsection(\"Physical data\"); \n      { \n        initial_time = prm.get_double(\"initial_time\"); \n        final_time   = prm.get_double(\"final_time\"); \n        Reynolds     = prm.get_double(\"Reynolds\"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Time step data\"); \n      { \n        dt = prm.get_double(\"dt\"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Space discretization\"); \n      { \n        n_global_refines = prm.get_integer(\"n_of_refines\"); \n        pressure_degree  = prm.get_integer(\"pressure_fe_degree\"); \n      } \n      prm.leave_subsection(); \n\n      prm.enter_subsection(\"Data solve velocity\"); \n      { \n        vel_max_iterations = prm.get_integer(\"max_iterations\"); \n        vel_eps            = prm.get_double(\"eps\"); \n        vel_Krylov_size    = prm.get_integer(\"Krylov_size\"); \n        vel_off_diagonals  = prm.get_integer(\"off_diagonals\"); \n        vel_diag_strength  = prm.get_double(\"diag_strength\"); \n        vel_update_prec    = prm.get_integer(\"update_prec\"); \n      } \n      prm.leave_subsection(); \n\n      verbose = prm.get_bool(\"verbose\"); \n\n      output_interval = prm.get_integer(\"output_interval\"); \n    } \n  } // namespace RunTimeParameters \n\n//  @sect3{Equation data}  \n\n// 在下一个命名空间中，我们声明初始和边界条件。\n\n  namespace EquationData \n  { \n\n// 由于我们选择了一个完全解耦的公式，我们将不利用deal.II处理矢量值问题的能力。然而，我们确实希望为方程数据使用一个独立于维度的接口。为了做到这一点，我们的函数应该能够知道我们目前在哪个空间分量上工作，而且我们应该能够有一个通用的接口来做到这一点。下面的类是在这个方向上的一个尝试。\n\n    template <int dim> \n    class MultiComponentFunction : public Function<dim> \n    { \n    public: \n      MultiComponentFunction(const double initial_time = 0.); \n      void set_component(const unsigned int d); \n\n    protected: \n      unsigned int comp; \n    }; \n\n    template <int dim> \n    MultiComponentFunction<dim>::MultiComponentFunction( \n      const double initial_time) \n      : Function<dim>(1, initial_time) \n      , comp(0) \n    {} \n\n    template <int dim> \n    void MultiComponentFunction<dim>::set_component(const unsigned int d) \n    { \n      Assert(d < dim, ExcIndexRange(d, 0, dim)); \n      comp = d; \n    } \n\n// 有了这个类的定义，我们声明描述速度和压力的边界条件的类。\n\n    template <int dim> \n    class Velocity : public MultiComponentFunction<dim> \n    { \n    public: \n      Velocity(const double initial_time = 0.0); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \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\n    template <int dim> \n    Velocity<dim>::Velocity(const double initial_time) \n      : MultiComponentFunction<dim>(initial_time) \n    {} \n\n    template <int dim> \n    void Velocity<dim>::value_list(const std::vector<Point<dim>> &points, \n                                   std::vector<double> &          values, \n                                   const unsigned int) const \n    { \n      const unsigned int n_points = points.size(); \n      Assert(values.size() == n_points, \n             ExcDimensionMismatch(values.size(), n_points)); \n      for (unsigned int i = 0; i < n_points; ++i) \n        values[i] = Velocity<dim>::value(points[i]); \n    } \n\n    template <int dim> \n    double Velocity<dim>::value(const Point<dim> &p, const unsigned int) const \n    { \n      if (this->comp == 0) \n        { \n          const double Um = 1.5; \n          const double H  = 4.1; \n          return 4. * Um * p(1) * (H - p(1)) / (H * H); \n        } \n      else \n        return 0.; \n    } \n\n    template <int dim> \n    class Pressure : public Function<dim> \n    { \n    public: \n      Pressure(const double initial_time = 0.0); \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override; \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\n    template <int dim> \n    Pressure<dim>::Pressure(const double initial_time) \n      : Function<dim>(1, initial_time) \n    {} \n\n    template <int dim> \n    double Pressure<dim>::value(const Point<dim> & p, \n                                const unsigned int component) const \n    { \n      (void)component; \n      AssertIndexRange(component, 1); \n      return 25. - p(0); \n    } \n\n    template <int dim> \n    void Pressure<dim>::value_list(const std::vector<Point<dim>> &points, \n                                   std::vector<double> &          values, \n                                   const unsigned int component) const \n    { \n      (void)component; \n      AssertIndexRange(component, 1); \n      const unsigned int n_points = points.size(); \n      Assert(values.size() == n_points, \n             ExcDimensionMismatch(values.size(), n_points)); \n      for (unsigned int i = 0; i < n_points; ++i) \n        values[i] = Pressure<dim>::value(points[i]); \n    } \n  } // namespace EquationData \n\n//  @sect3{The <code>NavierStokesProjection</code> class}  \n\n// 现在是程序的主类。它实现了纳维-斯托克斯方程的各种版本的投影方法。考虑到介绍中给出的实现细节，所有方法和成员变量的名称应该是不言自明的。\n\n  template <int dim> \n  class NavierStokesProjection \n  { \n  public: \n    NavierStokesProjection(const RunTimeParameters::Data_Storage &data); \n\n    void run(const bool verbose = false, const unsigned int n_plots = 10); \n\n  protected: \n    RunTimeParameters::Method type; \n\n    const unsigned int deg; \n    const double       dt; \n    const double       t_0; \n    const double       T; \n    const double       Re; \n\n    EquationData::Velocity<dim>               vel_exact; \n    std::map<types::global_dof_index, double> boundary_values; \n    std::vector<types::boundary_id>           boundary_ids; \n\n    Triangulation<dim> triangulation; \n\n    FE_Q<dim> fe_velocity; \n    FE_Q<dim> fe_pressure; \n\n    DoFHandler<dim> dof_handler_velocity; \n    DoFHandler<dim> dof_handler_pressure; \n\n    QGauss<dim> quadrature_pressure; \n    QGauss<dim> quadrature_velocity; \n\n    SparsityPattern sparsity_pattern_velocity; \n    SparsityPattern sparsity_pattern_pressure; \n    SparsityPattern sparsity_pattern_pres_vel; \n\n    SparseMatrix<double> vel_Laplace_plus_Mass; \n    SparseMatrix<double> vel_it_matrix[dim]; \n    SparseMatrix<double> vel_Mass; \n    SparseMatrix<double> vel_Laplace; \n    SparseMatrix<double> vel_Advection; \n    SparseMatrix<double> pres_Laplace; \n    SparseMatrix<double> pres_Mass; \n    SparseMatrix<double> pres_Diff[dim]; \n    SparseMatrix<double> pres_iterative; \n\n    Vector<double> pres_n; \n    Vector<double> pres_n_minus_1; \n    Vector<double> phi_n; \n    Vector<double> phi_n_minus_1; \n    Vector<double> u_n[dim]; \n    Vector<double> u_n_minus_1[dim]; \n    Vector<double> u_star[dim]; \n    Vector<double> force[dim]; \n    Vector<double> v_tmp; \n    Vector<double> pres_tmp; \n    Vector<double> rot_u; \n\n    SparseILU<double>   prec_velocity[dim]; \n    SparseILU<double>   prec_pres_Laplace; \n    SparseDirectUMFPACK prec_mass; \n    SparseDirectUMFPACK prec_vel_mass; \n\n    DeclException2(ExcInvalidTimeStep, \n                   double, \n                   double, \n                   << \" The time step \" << arg1 << \" is out of range.\" \n                   << std::endl \n                   << \" The permitted range is (0,\" << arg2 << \"]\"); \n\n    void create_triangulation_and_dofs(const unsigned int n_refines); \n\n    void initialize(); \n\n    void interpolate_velocity(); \n\n    void diffusion_step(const bool reinit_prec); \n\n    void projection_step(const bool reinit_prec); \n\n    void update_pressure(const bool reinit_prec); \n\n  private: \n    unsigned int vel_max_its; \n    unsigned int vel_Krylov_size; \n    unsigned int vel_off_diagonals; \n    unsigned int vel_update_prec; \n    double       vel_eps; \n    double       vel_diag_strength; \n\n    void initialize_velocity_matrices(); \n\n    void initialize_pressure_matrices(); \n\n// 接下来的几个结构和函数是用来做各种并行的事情。它们遵循 @ref threads 中规定的方案，使用WorkStream类。正如那里所解释的，这需要我们为每个装配器声明两个结构，一个是每个任务的数据，一个是scratch数据结构。然后，这些结构被移交给组装本地贡献的函数，并将这些本地贡献复制到全局对象上。\n\n// 这个程序的一个特殊之处在于，我们并不是只有一个DoFHandler对象来代表速度和压力，而是为这两种变量使用单独的DoFHandler对象。当我们想把涉及这两个变量的条款，如速度的发散和压力的梯度，乘以各自的测试函数时，我们要为这种优化付费。在这样做的时候，我们不能只使用一个FEValues对象，而是需要两个，而且需要用单元格迭代器来初始化它们，这些单元格迭代器指向三角形中的同一个单元格，但不同的DoFHandlers。\n\n// 为了在实践中做到这一点，我们声明一个 \"同步 \"迭代器--一个内部由几个（在我们的例子中是两个）迭代器组成的对象，每次同步迭代器向前移动一步，内部存储的每个迭代器也向前移动一步，从而始终保持同步。碰巧的是，有一个deal.II类可以促进这种事情。这里重要的是要知道，建立在同一个三角形上的两个DoFHandler对象将以相同的顺序走过三角形的单元。\n\n    using IteratorTuple = \n      std::tuple<typename DoFHandler<dim>::active_cell_iterator, \n                 typename DoFHandler<dim>::active_cell_iterator>; \n\n    using IteratorPair = SynchronousIterators<IteratorTuple>; \n\n    void initialize_gradient_operator(); \n\n    struct InitGradPerTaskData \n    { \n      unsigned int                         d; \n      unsigned int                         vel_dpc; \n      unsigned int                         pres_dpc; \n      FullMatrix<double>                   local_grad; \n      std::vector<types::global_dof_index> vel_local_dof_indices; \n      std::vector<types::global_dof_index> pres_local_dof_indices; \n\n      InitGradPerTaskData(const unsigned int dd, \n                          const unsigned int vdpc, \n                          const unsigned int pdpc) \n        : d(dd) \n        , vel_dpc(vdpc) \n        , pres_dpc(pdpc) \n        , local_grad(vdpc, pdpc) \n        , vel_local_dof_indices(vdpc) \n        , pres_local_dof_indices(pdpc) \n      {} \n    }; \n\n    struct InitGradScratchData \n    { \n      unsigned int  nqp; \n      FEValues<dim> fe_val_vel; \n      FEValues<dim> fe_val_pres; \n      InitGradScratchData(const FE_Q<dim> &  fe_v, \n                          const FE_Q<dim> &  fe_p, \n                          const QGauss<dim> &quad, \n                          const UpdateFlags  flags_v, \n                          const UpdateFlags  flags_p) \n        : nqp(quad.size()) \n        , fe_val_vel(fe_v, quad, flags_v) \n        , fe_val_pres(fe_p, quad, flags_p) \n      {} \n      InitGradScratchData(const InitGradScratchData &data) \n        : nqp(data.nqp) \n        , fe_val_vel(data.fe_val_vel.get_fe(), \n                     data.fe_val_vel.get_quadrature(), \n                     data.fe_val_vel.get_update_flags()) \n        , fe_val_pres(data.fe_val_pres.get_fe(), \n                      data.fe_val_pres.get_quadrature(), \n                      data.fe_val_pres.get_update_flags()) \n      {} \n    }; \n\n    void assemble_one_cell_of_gradient(const IteratorPair & SI, \n                                       InitGradScratchData &scratch, \n                                       InitGradPerTaskData &data); \n\n    void copy_gradient_local_to_global(const InitGradPerTaskData &data); \n\n// 同样的一般布局也适用于以下实现平流项组装的类和函数。\n\n    void assemble_advection_term(); \n\n    struct AdvectionPerTaskData \n    { \n      FullMatrix<double>                   local_advection; \n      std::vector<types::global_dof_index> local_dof_indices; \n      AdvectionPerTaskData(const unsigned int dpc) \n        : local_advection(dpc, dpc) \n        , local_dof_indices(dpc) \n      {} \n    }; \n\n    struct AdvectionScratchData \n    { \n      unsigned int                nqp; \n      unsigned int                dpc; \n      std::vector<Point<dim>>     u_star_local; \n      std::vector<Tensor<1, dim>> grad_u_star; \n      std::vector<double>         u_star_tmp; \n      FEValues<dim>               fe_val; \n      AdvectionScratchData(const FE_Q<dim> &  fe, \n                           const QGauss<dim> &quad, \n                           const UpdateFlags  flags) \n        : nqp(quad.size()) \n        , dpc(fe.n_dofs_per_cell()) \n        , u_star_local(nqp) \n        , grad_u_star(nqp) \n        , u_star_tmp(nqp) \n        , fe_val(fe, quad, flags) \n      {} \n\n      AdvectionScratchData(const AdvectionScratchData &data) \n        : nqp(data.nqp) \n        , dpc(data.dpc) \n        , u_star_local(nqp) \n        , grad_u_star(nqp) \n        , u_star_tmp(nqp) \n        , fe_val(data.fe_val.get_fe(), \n                 data.fe_val.get_quadrature(), \n                 data.fe_val.get_update_flags()) \n      {} \n    }; \n\n    void assemble_one_cell_of_advection( \n      const typename DoFHandler<dim>::active_cell_iterator &cell, \n      AdvectionScratchData &                                scratch, \n      AdvectionPerTaskData &                                data); \n\n    void copy_advection_local_to_global(const AdvectionPerTaskData &data); \n\n// 最后几个函数实现了扩散解以及输出的后处理，包括计算速度的曲线。\n\n    void diffusion_component_solve(const unsigned int d); \n\n    void output_results(const unsigned int step); \n\n    void assemble_vorticity(const bool reinit_prec); \n  }; \n\n//  @sect4{ <code>NavierStokesProjection::NavierStokesProjection</code> }  \n\n// 在构造函数中，我们只是从作为参数传递的 <code>Data_Storage</code> 对象中读取所有数据，验证我们读取的数据是否合理，最后，创建三角形并加载初始数据。\n\n  template <int dim> \n  NavierStokesProjection<dim>::NavierStokesProjection( \n    const RunTimeParameters::Data_Storage &data) \n    : type(data.form) \n    , deg(data.pressure_degree) \n    , dt(data.dt) \n    , t_0(data.initial_time) \n    , T(data.final_time) \n    , Re(data.Reynolds) \n    , vel_exact(data.initial_time) \n    , fe_velocity(deg + 1) \n    , fe_pressure(deg) \n    , dof_handler_velocity(triangulation) \n    , dof_handler_pressure(triangulation) \n    , quadrature_pressure(deg + 1) \n    , quadrature_velocity(deg + 2) \n    , vel_max_its(data.vel_max_iterations) \n    , vel_Krylov_size(data.vel_Krylov_size) \n    , vel_off_diagonals(data.vel_off_diagonals) \n    , vel_update_prec(data.vel_update_prec) \n    , vel_eps(data.vel_eps) \n    , vel_diag_strength(data.vel_diag_strength) \n  { \n    if (deg < 1) \n      std::cout \n        << \" WARNING: The chosen pair of finite element spaces is not stable.\" \n        << std::endl \n        << \" The obtained results will be nonsense\" << std::endl; \n\n    AssertThrow(!((dt <= 0.) || (dt > .5 * T)), ExcInvalidTimeStep(dt, .5 * T)); \n\n    create_triangulation_and_dofs(data.n_global_refines); \n    initialize(); \n  } \n// @sect4{<code>NavierStokesProjection::create_triangulation_and_dofs</code>}  \n\n// 创建三角形的方法，并将其细化到所需的次数。在创建三角形之后，它创建了与网格相关的数据，即分配自由度和重新编号，并初始化我们将使用的矩阵和向量。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::create_triangulation_and_dofs( \n    const unsigned int n_refines) \n  { \n    GridIn<dim> grid_in; \n    grid_in.attach_triangulation(triangulation); \n\n    { \n      std::string   filename = \"nsbench2.inp\"; \n      std::ifstream file(filename); \n      Assert(file, ExcFileNotOpen(filename.c_str())); \n      grid_in.read_ucd(file); \n    } \n\n    std::cout << \"Number of refines = \" << n_refines << std::endl; \n    triangulation.refine_global(n_refines); \n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl; \n\n    boundary_ids = triangulation.get_boundary_ids(); \n\n \n    DoFRenumbering::boost::Cuthill_McKee(dof_handler_velocity); \n    dof_handler_pressure.distribute_dofs(fe_pressure); \n    DoFRenumbering::boost::Cuthill_McKee(dof_handler_pressure); \n\n    initialize_velocity_matrices(); \n    initialize_pressure_matrices(); \n    initialize_gradient_operator(); \n\n    pres_n.reinit(dof_handler_pressure.n_dofs()); \n    pres_n_minus_1.reinit(dof_handler_pressure.n_dofs()); \n    phi_n.reinit(dof_handler_pressure.n_dofs()); \n    phi_n_minus_1.reinit(dof_handler_pressure.n_dofs()); \n    pres_tmp.reinit(dof_handler_pressure.n_dofs()); \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        u_n[d].reinit(dof_handler_velocity.n_dofs()); \n        u_n_minus_1[d].reinit(dof_handler_velocity.n_dofs()); \n        u_star[d].reinit(dof_handler_velocity.n_dofs()); \n        force[d].reinit(dof_handler_velocity.n_dofs()); \n      } \n    v_tmp.reinit(dof_handler_velocity.n_dofs()); \n    rot_u.reinit(dof_handler_velocity.n_dofs()); \n\n    std::cout << \"dim (X_h) = \" << (dof_handler_velocity.n_dofs() * dim) // \n              << std::endl                                               // \n              << \"dim (M_h) = \" << dof_handler_pressure.n_dofs()         // \n              << std::endl                                               // \n              << \"Re        = \" << Re << std::endl                       // \n              << std::endl; \n  } \n// @sect4{ <code>NavierStokesProjection::initialize</code> }  \n\n// 该方法创建常数矩阵并加载初始数据。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::initialize() \n  { \n    vel_Laplace_plus_Mass = 0.; \n    vel_Laplace_plus_Mass.add(1. / Re, vel_Laplace); \n    vel_Laplace_plus_Mass.add(1.5 / dt, vel_Mass); \n\n    EquationData::Pressure<dim> pres(t_0); \n    VectorTools::interpolate(dof_handler_pressure, pres, pres_n_minus_1); \n    pres.advance_time(dt); \n    VectorTools::interpolate(dof_handler_pressure, pres, pres_n); \n    phi_n         = 0.; \n    phi_n_minus_1 = 0.; \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        vel_exact.set_time(t_0); \n        vel_exact.set_component(d); \n        VectorTools::interpolate(dof_handler_velocity, \n                                 vel_exact, \n                                 u_n_minus_1[d]); \n        vel_exact.advance_time(dt); \n        VectorTools::interpolate(dof_handler_velocity, vel_exact, u_n[d]); \n      } \n  } \n// @sect4{ <code>NavierStokesProjection::initialize_*_matrices</code> }  \n\n// 在这组方法中，我们初始化了稀疏模式、约束条件（如果有的话）并组装了不依赖于时间步长的矩阵  <code>dt</code>  。请注意，对于拉普拉斯矩阵和质量矩阵，我们可以使用库中的函数来做这件事。因为这个函数的昂贵操作--创建两个矩阵--是完全独立的，我们原则上可以把它们标记为可以使用 Threads::new_task 函数进行%并行工作的任务。我们不会在这里这样做，因为这些函数在内部已经被并行化了，特别是由于当前的函数在每个程序运行中只被调用一次，所以在每个时间步长中不会产生费用。然而，必要的修改将是非常直接的。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::initialize_velocity_matrices() \n  { \n    { \n      DynamicSparsityPattern dsp(dof_handler_velocity.n_dofs(), \n                                 dof_handler_velocity.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler_velocity, dsp); \n      sparsity_pattern_velocity.copy_from(dsp); \n    } \n    vel_Laplace_plus_Mass.reinit(sparsity_pattern_velocity); \n    for (unsigned int d = 0; d < dim; ++d) \n      vel_it_matrix[d].reinit(sparsity_pattern_velocity); \n    vel_Mass.reinit(sparsity_pattern_velocity); \n    vel_Laplace.reinit(sparsity_pattern_velocity); \n    vel_Advection.reinit(sparsity_pattern_velocity); \n\n    MatrixCreator::create_mass_matrix(dof_handler_velocity, \n                                      quadrature_velocity, \n                                      vel_Mass); \n    MatrixCreator::create_laplace_matrix(dof_handler_velocity, \n                                         quadrature_velocity, \n                                         vel_Laplace); \n  } \n\n//作用于压力空间的矩阵的初始化与作用于速度空间的矩阵相似。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::initialize_pressure_matrices() \n  { \n    { \n      DynamicSparsityPattern dsp(dof_handler_pressure.n_dofs(), \n                                 dof_handler_pressure.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler_pressure, dsp); \n      sparsity_pattern_pressure.copy_from(dsp); \n    } \n\n    pres_Laplace.reinit(sparsity_pattern_pressure); \n    pres_iterative.reinit(sparsity_pattern_pressure); \n    pres_Mass.reinit(sparsity_pattern_pressure); \n\n    MatrixCreator::create_laplace_matrix(dof_handler_pressure, \n                                         quadrature_pressure, \n                                         pres_Laplace); \n    MatrixCreator::create_mass_matrix(dof_handler_pressure, \n                                      quadrature_pressure, \n                                      pres_Mass); \n  } \n\n// 对于梯度算子，我们从初始化稀疏模式和压缩它开始。这里需要注意的是，梯度算子从压力空间作用到速度空间，所以我们必须处理两个不同的有限元空间。为了保持循环的同步，我们使用之前定义的别名，即 <code>PairedIterators</code> and <code>IteratorPair</code>  。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::initialize_gradient_operator() \n  { \n    { \n      DynamicSparsityPattern dsp(dof_handler_velocity.n_dofs(), \n                                 dof_handler_pressure.n_dofs()); \n      DoFTools::make_sparsity_pattern(dof_handler_velocity, \n                                      dof_handler_pressure, \n                                      dsp); \n      sparsity_pattern_pres_vel.copy_from(dsp); \n    } \n\n    InitGradPerTaskData per_task_data(0, \n                                      fe_velocity.n_dofs_per_cell(), \n                                      fe_pressure.n_dofs_per_cell()); \n    InitGradScratchData scratch_data(fe_velocity, \n                                     fe_pressure, \n                                     quadrature_velocity, \n                                     update_gradients | update_JxW_values, \n                                     update_values); \n\n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        pres_Diff[d].reinit(sparsity_pattern_pres_vel); \n        per_task_data.d = d; \n        WorkStream::run( \n          IteratorPair(IteratorTuple(dof_handler_velocity.begin_active(), \n                                     dof_handler_pressure.begin_active())), \n          IteratorPair(IteratorTuple(dof_handler_velocity.end(), \n                                     dof_handler_pressure.end())), \n          *this, \n          &NavierStokesProjection<dim>::assemble_one_cell_of_gradient, \n          &NavierStokesProjection<dim>::copy_gradient_local_to_global, \n          scratch_data, \n          per_task_data); \n      } \n  } \n\n  template <int dim> \n  void NavierStokesProjection<dim>::assemble_one_cell_of_gradient( \n    const IteratorPair & SI, \n    InitGradScratchData &scratch, \n    InitGradPerTaskData &data) \n  { \n    scratch.fe_val_vel.reinit(std::get<0>(*SI)); \n    scratch.fe_val_pres.reinit(std::get<1>(*SI)); \n\n    std::get<0>(*SI)->get_dof_indices(data.vel_local_dof_indices); \n    std::get<1>(*SI)->get_dof_indices(data.pres_local_dof_indices); \n\n    data.local_grad = 0.; \n    for (unsigned int q = 0; q < scratch.nqp; ++q) \n      { \n        for (unsigned int i = 0; i < data.vel_dpc; ++i) \n          for (unsigned int j = 0; j < data.pres_dpc; ++j) \n            data.local_grad(i, j) += \n              -scratch.fe_val_vel.JxW(q) * \n              scratch.fe_val_vel.shape_grad(i, q)[data.d] * \n              scratch.fe_val_pres.shape_value(j, q); \n      } \n  } \n\n  template <int dim> \n  void NavierStokesProjection<dim>::copy_gradient_local_to_global( \n    const InitGradPerTaskData &data) \n  { \n    for (unsigned int i = 0; i < data.vel_dpc; ++i) \n      for (unsigned int j = 0; j < data.pres_dpc; ++j) \n        pres_Diff[data.d].add(data.vel_local_dof_indices[i], \n                              data.pres_local_dof_indices[j], \n                              data.local_grad(i, j)); \n  } \n// @sect4{ <code>NavierStokesProjection::run</code> }  \n\n// 这是时间行进函数，从 <code>t_0</code> 开始，使用时间步长 <code>dt</code> 的投影法在时间上前进，直到 <code>T</code>  。\n\n// 它的第二个参数 <code>verbose</code> 表示该函数是否应该输出它在任何特定时刻正在做什么的信息：例如，它将说明我们是否正在进行扩散、投影子步骤；更新前置条件器等等。我们没有使用像\n// @code\n//    if (verbose) std::cout << \"something\";\n//  @endcode\n//  那样的代码来实现这种输出，而是使用ConditionalOStream类来为我们做这个。该类接受一个输出流和一个条件，该条件表明你传递给它的东西是否应该被传递到给定的输出流，或者应该被忽略。这样，上面的代码就变成了\n//  @code\n//    verbose_cout << \"something\";\n//  @endcode，并且在任何情况下都会做正确的事情。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::run(const bool         verbose, \n                                        const unsigned int output_interval) \n  { \n    ConditionalOStream verbose_cout(std::cout, verbose); \n\n    const auto n_steps = static_cast<unsigned int>((T - t_0) / dt); \n    vel_exact.set_time(2. * dt); \n    output_results(1); \n    for (unsigned int n = 2; n <= n_steps; ++n) \n      { \n        if (n % output_interval == 0) \n          { \n            verbose_cout << \"Plotting Solution\" << std::endl; \n            output_results(n); \n          } \n        std::cout << \"Step = \" << n << \" Time = \" << (n * dt) << std::endl; \n        verbose_cout << \"  Interpolating the velocity \" << std::endl; \n\n        interpolate_velocity(); \n        verbose_cout << \"  Diffusion Step\" << std::endl; \n        if (n % vel_update_prec == 0) \n          verbose_cout << \"    With reinitialization of the preconditioner\" \n                       << std::endl; \n        diffusion_step((n % vel_update_prec == 0) || (n == 2)); \n        verbose_cout << \"  Projection Step\" << std::endl; \n        projection_step((n == 2)); \n        verbose_cout << \"  Updating the Pressure\" << std::endl; \n        update_pressure((n == 2)); \n        vel_exact.advance_time(dt); \n      } \n    output_results(n_steps); \n  } \n\n  template <int dim> \n  void NavierStokesProjection<dim>::interpolate_velocity() \n  { \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        u_star[d].equ(2., u_n[d]); \n        u_star[d] -= u_n_minus_1[d]; \n      } \n  } \n// @sect4{<code>NavierStokesProjection::diffusion_step</code>}  \n\n// 扩散步骤的实现。请注意，昂贵的操作是函数末尾的扩散解，我们必须为每个速度分量做一次。为了加快进度，我们允许以%并行方式进行，使用 Threads::new_task 函数，确保 <code>dim</code> 的求解都得到处理，并被安排到可用的处理器上：如果你的机器有一个以上的处理器核心，并且这个程序的其他部分目前没有使用资源，那么扩散求解将以%并行方式运行。另一方面，如果你的系统只有一个处理器核心，那么以%并行方式运行将是低效的（因为它导致了，例如，缓存拥堵），事情将被顺序地执行。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::diffusion_step(const bool reinit_prec) \n  { \n    pres_tmp.equ(-1., pres_n); \n    pres_tmp.add(-4. / 3., phi_n, 1. / 3., phi_n_minus_1); \n\n    assemble_advection_term(); \n\n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        force[d] = 0.; \n        v_tmp.equ(2. / dt, u_n[d]); \n        v_tmp.add(-.5 / dt, u_n_minus_1[d]); \n        vel_Mass.vmult_add(force[d], v_tmp); \n\n        pres_Diff[d].vmult_add(force[d], pres_tmp); \n        u_n_minus_1[d] = u_n[d]; \n\n        vel_it_matrix[d].copy_from(vel_Laplace_plus_Mass); \n        vel_it_matrix[d].add(1., vel_Advection); \n\n        vel_exact.set_component(d); \n        boundary_values.clear(); \n        for (const auto &boundary_id : boundary_ids) \n          { \n            switch (boundary_id) \n              { \n                case 1: \n                  VectorTools::interpolate_boundary_values( \n                    dof_handler_velocity, \n                    boundary_id, \n                    Functions::ZeroFunction<dim>(), \n                    boundary_values); \n                  break; \n                case 2: \n                  VectorTools::interpolate_boundary_values(dof_handler_velocity, \n                                                           boundary_id, \n                                                           vel_exact, \n                                                           boundary_values); \n                  break; \n                case 3: \n                  if (d != 0) \n                    VectorTools::interpolate_boundary_values( \n                      dof_handler_velocity, \n                      boundary_id, \n                      Functions::ZeroFunction<dim>(), \n                      boundary_values); \n                  break; \n                case 4: \n                  VectorTools::interpolate_boundary_values( \n                    dof_handler_velocity, \n                    boundary_id, \n                    Functions::ZeroFunction<dim>(), \n                    boundary_values); \n                  break; \n                default: \n                  Assert(false, ExcNotImplemented()); \n              } \n          } \n        MatrixTools::apply_boundary_values(boundary_values, \n                                           vel_it_matrix[d], \n                                           u_n[d], \n                                           force[d]); \n      } \n\n    Threads::TaskGroup<void> tasks; \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        if (reinit_prec) \n          prec_velocity[d].initialize(vel_it_matrix[d], \n                                      SparseILU<double>::AdditionalData( \n                                        vel_diag_strength, vel_off_diagonals)); \n        tasks += Threads::new_task( \n          &NavierStokesProjection<dim>::diffusion_component_solve, *this, d); \n      } \n    tasks.join_all(); \n  } \n\n  template <int dim> \n  void \n  NavierStokesProjection<dim>::diffusion_component_solve(const unsigned int d) \n  { \n    SolverControl solver_control(vel_max_its, vel_eps * force[d].l2_norm()); \n    SolverGMRES<Vector<double>> gmres( \n      solver_control, \n      SolverGMRES<Vector<double>>::AdditionalData(vel_Krylov_size)); \n    gmres.solve(vel_it_matrix[d], u_n[d], force[d], prec_velocity[d]); \n  } \n// @sect4{ <code>NavierStokesProjection::assemble_advection_term</code> }  \n\n// 下面的几个函数是关于集合平流项的，平流项是扩散步骤的系统矩阵的一部分，在每个时间步骤中都会发生变化。如上所述，我们将使用WorkStream类和文件模块 @ref threads 中描述的其他设施，在所有单元上平行运行装配循环。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::assemble_advection_term() \n  { \n    vel_Advection = 0.; \n    AdvectionPerTaskData data(fe_velocity.n_dofs_per_cell()); \n    AdvectionScratchData scratch(fe_velocity, \n                                 quadrature_velocity, \n                                 update_values | update_JxW_values | \n                                   update_gradients); \n    WorkStream::run( \n      dof_handler_velocity.begin_active(), \n      dof_handler_velocity.end(), \n      *this, \n      &NavierStokesProjection<dim>::assemble_one_cell_of_advection, \n      &NavierStokesProjection<dim>::copy_advection_local_to_global, \n      scratch, \n      data); \n  } \n\n  template <int dim> \n  void NavierStokesProjection<dim>::assemble_one_cell_of_advection( \n    const typename DoFHandler<dim>::active_cell_iterator &cell, \n    AdvectionScratchData &                                scratch, \n    AdvectionPerTaskData &                                data) \n  { \n    scratch.fe_val.reinit(cell); \n    cell->get_dof_indices(data.local_dof_indices); \n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        scratch.fe_val.get_function_values(u_star[d], scratch.u_star_tmp); \n        for (unsigned int q = 0; q < scratch.nqp; ++q) \n          scratch.u_star_local[q](d) = scratch.u_star_tmp[q]; \n      } \n\n    for (unsigned int d = 0; d < dim; ++d) \n      { \n        scratch.fe_val.get_function_gradients(u_star[d], scratch.grad_u_star); \n        for (unsigned int q = 0; q < scratch.nqp; ++q) \n          { \n            if (d == 0) \n              scratch.u_star_tmp[q] = 0.; \n            scratch.u_star_tmp[q] += scratch.grad_u_star[q][d]; \n          } \n      } \n\n    data.local_advection = 0.; \n    for (unsigned int q = 0; q < scratch.nqp; ++q) \n      for (unsigned int i = 0; i < scratch.dpc; ++i) \n        for (unsigned int j = 0; j < scratch.dpc; ++j) \n          data.local_advection(i, j) += (scratch.u_star_local[q] *            // \n                                           scratch.fe_val.shape_grad(j, q) *  // \n                                           scratch.fe_val.shape_value(i, q)   // \n                                         +                                    // \n                                         0.5 *                                // \n                                           scratch.u_star_tmp[q] *            // \n                                           scratch.fe_val.shape_value(i, q) * // \n                                           scratch.fe_val.shape_value(j, q))  // \n                                        * scratch.fe_val.JxW(q); \n  } \n\n  template <int dim> \n  void NavierStokesProjection<dim>::copy_advection_local_to_global( \n    const AdvectionPerTaskData &data) \n  { \n    for (unsigned int i = 0; i < fe_velocity.n_dofs_per_cell(); ++i) \n      for (unsigned int j = 0; j < fe_velocity.n_dofs_per_cell(); ++j) \n        vel_Advection.add(data.local_dof_indices[i], \n                          data.local_dof_indices[j], \n                          data.local_advection(i, j)); \n  } \n\n//  @sect4{<code>NavierStokesProjection::projection_step</code>}  \n\n// 这实现了投影的步骤。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::projection_step(const bool reinit_prec) \n  { \n    pres_iterative.copy_from(pres_Laplace); \n\n    pres_tmp = 0.; \n    for (unsigned d = 0; d < dim; ++d) \n      pres_Diff[d].Tvmult_add(pres_tmp, u_n[d]); \n\n    phi_n_minus_1 = phi_n; \n\n    static std::map<types::global_dof_index, double> bval; \n    if (reinit_prec) \n      VectorTools::interpolate_boundary_values(dof_handler_pressure, \n                                               3, \n                                               Functions::ZeroFunction<dim>(), \n                                               bval); \n\n    MatrixTools::apply_boundary_values(bval, pres_iterative, phi_n, pres_tmp); \n\n    if (reinit_prec) \n      prec_pres_Laplace.initialize(pres_iterative, \n                                   SparseILU<double>::AdditionalData( \n                                     vel_diag_strength, vel_off_diagonals)); \n\n    SolverControl solvercontrol(vel_max_its, vel_eps * pres_tmp.l2_norm()); \n    SolverCG<Vector<double>> cg(solvercontrol); \n    cg.solve(pres_iterative, phi_n, pres_tmp, prec_pres_Laplace); \n\n    phi_n *= 1.5 / dt; \n  } \n// @sect4{ <code>NavierStokesProjection::update_pressure</code> }  \n\n// 这是投影法的压力更新步骤。它实现了该方法的标准表述，即\n//  @f[ p^{n+1} = p^n +\n//  \\phi^{n+1}, \n//  @f]\n//  或旋转形式，即\n//  @f[ p^{n+1} = p^n +\n//  \\phi^{n+1} - \\frac{1}{Re} \\nabla\\cdot u^{n+1}. \n//  @f] \n\n  template <int dim> \n  void NavierStokesProjection<dim>::update_pressure(const bool reinit_prec) \n  { \n    pres_n_minus_1 = pres_n; \n    switch (type) \n      { \n        case RunTimeParameters::Method::standard: \n          pres_n += phi_n; \n          break; \n        case RunTimeParameters::Method::rotational: \n          if (reinit_prec) \n            prec_mass.initialize(pres_Mass); \n          pres_n = pres_tmp; \n          prec_mass.solve(pres_n); \n          pres_n.sadd(1. / Re, 1., pres_n_minus_1); \n          pres_n += phi_n; \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      }; \n  } \n// @sect4{ <code>NavierStokesProjection::output_results</code> }  \n\n// 该方法绘制了当前的解决方案。主要的困难是，我们想创建一个单一的输出文件，其中包含所有的速度分量、压力以及流动的涡度的数据。另一方面，速度和压力存在于不同的DoFHandler对象中，因此不能用一个DataOut对象写入同一个文件。因此，我们必须更努力地把各种数据放到一个DoFHandler对象中，然后用它来驱动图形输出。\n\n// 我们不会在这里详细说明这个过程，而是参考  step-32  ，那里使用了一个类似的程序（并有记录），为所有变量创建一个联合的 DoFHandler 对象。\n\n// 我们还注意到，我们在这里将涡度作为一个单独的函数中的标量来计算，使用 $L^2$ 量的投影 $\\text{curl} u$ 到用于速度成分的有限元空间。但原则上，我们也可以从速度中计算出一个点状量，并通过 step-29 和 step-33 中讨论的DataPostprocessor机制实现。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::output_results(const unsigned int step) \n  { \n    assemble_vorticity((step == 1)); \n    const FESystem<dim> joint_fe( \n      fe_velocity, dim, fe_pressure, 1, fe_velocity, 1); \n    DoFHandler<dim> joint_dof_handler(triangulation); \n    joint_dof_handler.distribute_dofs(joint_fe); \n    Assert(joint_dof_handler.n_dofs() == \n             ((dim + 1) * dof_handler_velocity.n_dofs() + \n              dof_handler_pressure.n_dofs()), \n           ExcInternalError()); \n    Vector<double> joint_solution(joint_dof_handler.n_dofs()); \n    std::vector<types::global_dof_index> loc_joint_dof_indices( \n      joint_fe.n_dofs_per_cell()), \n      loc_vel_dof_indices(fe_velocity.n_dofs_per_cell()), \n      loc_pres_dof_indices(fe_pressure.n_dofs_per_cell()); \n    typename DoFHandler<dim>::active_cell_iterator \n      joint_cell = joint_dof_handler.begin_active(), \n      joint_endc = joint_dof_handler.end(), \n      vel_cell   = dof_handler_velocity.begin_active(), \n      pres_cell  = dof_handler_pressure.begin_active(); \n    for (; joint_cell != joint_endc; ++joint_cell, ++vel_cell, ++pres_cell) \n      { \n        joint_cell->get_dof_indices(loc_joint_dof_indices); \n        vel_cell->get_dof_indices(loc_vel_dof_indices); \n        pres_cell->get_dof_indices(loc_pres_dof_indices); \n        for (unsigned int i = 0; i < joint_fe.n_dofs_per_cell(); ++i) \n          switch (joint_fe.system_to_base_index(i).first.first) \n            { \n              case 0: \n                Assert(joint_fe.system_to_base_index(i).first.second < dim, \n                       ExcInternalError()); \n                joint_solution(loc_joint_dof_indices[i]) = \n                  u_n[joint_fe.system_to_base_index(i).first.second]( \n                    loc_vel_dof_indices[joint_fe.system_to_base_index(i) \n                                          .second]); \n                break; \n              case 1: \n                Assert(joint_fe.system_to_base_index(i).first.second == 0, \n                       ExcInternalError()); \n                joint_solution(loc_joint_dof_indices[i]) = \n                  pres_n(loc_pres_dof_indices[joint_fe.system_to_base_index(i) \n                                                .second]); \n                break; \n              case 2: \n                Assert(joint_fe.system_to_base_index(i).first.second == 0, \n                       ExcInternalError()); \n                joint_solution(loc_joint_dof_indices[i]) = rot_u( \n                  loc_vel_dof_indices[joint_fe.system_to_base_index(i).second]); \n                break; \n              default: \n                Assert(false, ExcInternalError()); \n            } \n      } \n    std::vector<std::string> joint_solution_names(dim, \"v\"); \n    joint_solution_names.emplace_back(\"p\"); \n    joint_solution_names.emplace_back(\"rot_u\"); \n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(joint_dof_handler); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      component_interpretation( \n        dim + 2, DataComponentInterpretation::component_is_part_of_vector); \n    component_interpretation[dim] = \n      DataComponentInterpretation::component_is_scalar; \n    component_interpretation[dim + 1] = \n      DataComponentInterpretation::component_is_scalar; \n    data_out.add_data_vector(joint_solution, \n                             joint_solution_names, \n                             DataOut<dim>::type_dof_data, \n                             component_interpretation); \n    data_out.build_patches(deg + 1); \n    std::ofstream output(\"solution-\" + Utilities::int_to_string(step, 5) + \n                         \".vtk\"); \n    data_out.write_vtk(output); \n  } \n\n// 下面是一个辅助函数，通过将 $\\text{curl} u$ 项投影到用于速度分量的有限元空间来计算涡度。这个函数只有在我们生成图形输出时才会被调用，所以不是很频繁，因此我们没有像对待其他装配函数那样，麻烦地使用WorkStream概念来并行化它。不过，如果需要的话，这应该不会太复杂。此外，我们在这里的实现只适用于2D，所以如果不是这种情况，我们就放弃了。\n\n  template <int dim> \n  void NavierStokesProjection<dim>::assemble_vorticity(const bool reinit_prec) \n  { \n    Assert(dim == 2, ExcNotImplemented()); \n    if (reinit_prec) \n      prec_vel_mass.initialize(vel_Mass); \n\n    FEValues<dim>      fe_val_vel(fe_velocity, \n                             quadrature_velocity, \n                             update_gradients | update_JxW_values | \n                               update_values); \n    const unsigned int dpc = fe_velocity.n_dofs_per_cell(), \n                       nqp = quadrature_velocity.size(); \n    std::vector<types::global_dof_index> ldi(dpc); \n    Vector<double>                       loc_rot(dpc); \n\n    std::vector<Tensor<1, dim>> grad_u1(nqp), grad_u2(nqp); \n    rot_u = 0.; \n\n    for (const auto &cell : dof_handler_velocity.active_cell_iterators()) \n      { \n        fe_val_vel.reinit(cell); \n        cell->get_dof_indices(ldi); \n        fe_val_vel.get_function_gradients(u_n[0], grad_u1); \n        fe_val_vel.get_function_gradients(u_n[1], grad_u2); \n        loc_rot = 0.; \n        for (unsigned int q = 0; q < nqp; ++q) \n          for (unsigned int i = 0; i < dpc; ++i) \n            loc_rot(i) += (grad_u2[q][0] - grad_u1[q][1]) * // \n                          fe_val_vel.shape_value(i, q) *    // \n                          fe_val_vel.JxW(q); \n\n        for (unsigned int i = 0; i < dpc; ++i) \n          rot_u(ldi[i]) += loc_rot(i); \n      } \n\n    prec_vel_mass.solve(rot_u); \n  } \n} // namespace Step35 \n// @sect3{ The main function }  \n\n// 主函数看起来和其他所有的教程程序非常相似，所以这里没有什么可评论的。\n\nint main() \n{ \n  try \n    { \n      using namespace Step35; \n\n      RunTimeParameters::Data_Storage data; \n      data.read_data(\"parameter-file.prm\"); \n\n      deallog.depth_console(data.verbose ? 2 : 0); \n\n      NavierStokesProjection<2> test(data); \n      test.run(data.verbose, data.output_interval); \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  std::cout << \"----------------------------------------------------\" \n            << std::endl \n            << \"Apparently everything went fine!\" << std::endl \n            << \"Don't forget to brush your teeth :-)\" << std::endl \n            << std::endl; \n  return 0; \n} \n\n", "meta": {"hexsha": "35f636bc23eefe97948fac8a38272dcde23f1e9d", "size": 48636, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-35/step-35.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-35/step-35.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-35/step-35.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.2414307004, "max_line_length": 265, "alphanum_fraction": 0.5734846616, "num_tokens": 13781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.5682517407888346}}
{"text": "#pragma once\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <Eigen/Dense>\n#include <memory>\n#include <vector>\n#include <iostream>\n#include <cmath>\n\nnamespace py = pybind11;\n\nnamespace dummyml{\n\nusing EigenMatrix = Eigen::Matrix<\n    double,\n    Eigen::Dynamic,\n    Eigen::Dynamic,\n    Eigen::RowMajor\n>;\nusing EigenVector = Eigen::VectorXd;\n\nclass mean_variance\n{\nprivate:\n    std::vector<double> _mean;\n    std::vector<double> _variance;\npublic:\n    mean_variance() = default;\n    mean_variance(size_t size): _mean(size), _variance(size){}\n    inline size_t size() const {\n        return _mean.size();\n    }\n    inline const    double& mean    (size_t index) const {\n        return _mean.at(index);\n    }\n    inline          double& mean    (size_t index) {\n        return _mean.at(index);\n    }\n    inline const    double& variance(size_t index) const {\n        return _variance.at(index);\n    }\n    inline          double& variance(size_t index) {\n        return _variance.at(index);\n    }\n    inline static double normalDistribution(double m, double v, double x, bool ignore_const = false) {\n        return exp(-pow(x-m,2.0) / (ignore_const ? v : 2.0*v)) / sqrt(ignore_const ? v : v*M_PI_2);\n    }\n    inline static double logNormalDistribution(double m, double v, double x, bool ignore_const = false) {\n        return -pow(x-m,2.0) / (ignore_const ? v : 2.0*v) - 0.5*log(ignore_const ? v : v*M_PI_2);\n    }\n    double* mean_data(){\n        return _mean.data();\n    }\n    double* variance_data(){\n        return _variance.data();\n    }\n};\n\nclass kernel{\npublic:\n    enum type{\n        NoneKernel = 0,\n        LinearKernel,\n        RadialBasisFunctionKernel\n    } _T;\n    kernel() = default;\n    virtual double operator()(const double &x1, const double &x2) = 0;\n    virtual double operator()(\n        Eigen::Ref<EigenVector> x1,\n        Eigen::Ref<EigenVector> x2) = 0;\n};\n\nclass linear_kernel: public kernel{\npublic:\n    linear_kernel(): kernel(){\n        _T = LinearKernel;\n    }\n    double operator()(const double &x1, const double &x2){\n        return x1*x2;\n    }\n    double operator()(\n        Eigen::Ref<EigenVector> x1,\n        Eigen::Ref<EigenVector> x2){\n        return x1.dot(x2);\n    }\n};\n\nclass radial_basis_function_kernel: public kernel{\nprivate:\n    double gamma;\npublic:\n    radial_basis_function_kernel(double g = 0.1): kernel(), gamma(g){\n        _T = RadialBasisFunctionKernel;\n    }\n    void set_gamma(double g){\n        gamma = g;\n    }\n    double operator()(const double &x1, const double &x2){\n        return exp(-gamma*(x1-x2)*(x1-x2));\n    }\n    double operator()(\n        Eigen::Ref<EigenVector> x1,\n        Eigen::Ref<EigenVector> x2){\n        return exp(-gamma*((x1-x2).squaredNorm()));\n    }\n};\n\nstd::unique_ptr<kernel> get_kernel(kernel::type);\n\nstd::vector<double> softmax(const std::vector<double>&);\n\ntemplate<typename To, typename From>\nTo dummy_cast(From ptr){\n    return static_cast<To>(static_cast<void*>(ptr));\n}\n\n} // namespace dummyml\n\nvoid export_utils(py::module_ &m);", "meta": {"hexsha": "f931841b9ce655281811b67ff5fa0e0817fb0e0b", "size": 3036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dummyml/utils.hpp", "max_stars_repo_name": "BlenderWang9487/DummyML", "max_stars_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/dummyml/utils.hpp", "max_issues_repo_name": "BlenderWang9487/DummyML", "max_issues_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dummyml/utils.hpp", "max_forks_repo_name": "BlenderWang9487/DummyML", "max_forks_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_forks_repo_licenses": ["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.512605042, "max_line_length": 105, "alphanum_fraction": 0.6268115942, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.568251739222622}}
{"text": "#include <boost/math/distributions/hypergeometric.hpp>\n#include <algorithm> // for min and max\n#include <Rcpp.h>\n\nusing namespace Rcpp;\nusing namespace boost::math;\nusing namespace std;\n\ndouble fisher_exact_test(double a, double b, double c, double d) {\n  double N = a + b + c + d;\n  double r = a + c;\n  double n = c + d;\n  double max_for_k = min(r, n); \n  double min_for_k = (double)max(0.0, double(r + n - N));\n  hypergeometric_distribution<> hgd(r, n, N); \n  double cutoff = pdf(hgd, c);\n  double tmp_p = 0.0;\n  for(int k = min_for_k; k < max_for_k+1; k++) {\n    double p = pdf(hgd, k);\n    if(p <= cutoff) {\n      tmp_p += p;\n    }\n  }\n  return tmp_p;\n}\n\n// [[Rcpp::export]]\nSEXP fisherExactTest(SEXP a, SEXP b, SEXP c, SEXP d) {\n  \n  Rcpp::IntegerVector a_(a), b_(b), c_(c), d_(d);\n  Rcpp::NumericVector pval(a);\n  int n = a_.size();\n  \n  for(int i = 0; i < n; i++) {\n    pval(i) = fisher_exact_test(a_(i), b_(i), c_(i), d_(i));\n  }\n  \n  return wrap(pval);\n}\n", "meta": {"hexsha": "ccbae2232978a450c5cf40198f924b6dcfa5b4c6", "size": 964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fisherExactTest.cpp", "max_stars_repo_name": "julian-gehring/HighSpeedStats", "max_stars_repo_head_hexsha": "61ae063d9720497a21597f6bcb5dbe5a988103df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T12:36:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-31T12:36:56.000Z", "max_issues_repo_path": "src/fisherExactTest.cpp", "max_issues_repo_name": "julian-gehring/HighSpeedStats", "max_issues_repo_head_hexsha": "61ae063d9720497a21597f6bcb5dbe5a988103df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fisherExactTest.cpp", "max_forks_repo_name": "julian-gehring/HighSpeedStats", "max_forks_repo_head_hexsha": "61ae063d9720497a21597f6bcb5dbe5a988103df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1, "max_line_length": 66, "alphanum_fraction": 0.6026970954, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5682431081423255}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n *    (See accompanying file LICENSE_1_0.txt or copy at\n *          http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#include \"../config.h\"\n#include <fstream>\n#include <iomanip>\n#include <map>\n\n#include <boost/logic/tribool.hpp>\n\n#include \"total_unimodularity.hpp\"\n#include \"matroid_decomposition.hpp\"\n#include \"unimodularity.hpp\"\n#include \"smith_normal_form.hpp\"\n\ntemplate <typename Set, typename Element>\nbool contains(const Set& set, const Element& element)\n{\n  return set.find(element) != set.end();\n}\n\nvoid print_matroid_graph(const unimod::matroid_graph& graph, const std::string& indent = \"\")\n{\n  std::cout << boost::num_vertices(graph) << \" nodes and \" << boost::num_edges(graph) << \" edges:\";\n\n  typedef boost::graph_traits <unimod::matroid_graph> traits;\n  traits::vertex_iterator vertex_iter, vertex_end;\n  traits::out_edge_iterator edge_iter, edge_end;\n\n  for (boost::tie(vertex_iter, vertex_end) = boost::vertices(graph); vertex_iter != vertex_end; ++vertex_iter)\n  {\n    std::cout << '\\n' << indent << *vertex_iter << ':';\n    for (boost::tie(edge_iter, edge_end) = boost::out_edges(*vertex_iter, graph); edge_iter != edge_end; ++edge_iter)\n    {\n      int matroid_element = boost::get(unimod::edge_matroid_element, graph, *edge_iter);\n      std::cout << ' ' << boost::target(*edge_iter, graph) << \" (\" << (matroid_element < 0 ? \"row \" : \"column \") << matroid_element << \") \";\n    }\n  }\n  std::cout << '\\n';\n}\n\nvoid print_decomposition(const unimod::decomposed_matroid* decomposition, std::string indent = \"\")\n{\n  if (decomposition->is_leaf())\n  {\n    unimod::decomposed_matroid_leaf* leaf = (unimod::decomposed_matroid_leaf*) (decomposition);\n\n    if (leaf->is_R10())\n    {\n      std::cout << indent << \"R10:\";\n      for (unimod::matroid_element_set::const_iterator iter = leaf->elements().begin(); iter != leaf->elements().end(); ++iter)\n        std::cout << \" \" << *iter;\n      std::cout << \"\\n\";\n    }\n    else if (leaf->is_graphic() && leaf->is_cographic())\n    {\n      std::cout << indent << \"planar binary matroid.\\n\";\n      std::cout << indent << \"graph:\\n\" << indent << \"{ \";\n      print_matroid_graph(*leaf->graph(), indent + \"  \");\n      std::cout << indent << \"}\\n\" << indent << \"cograph:\\n\" << indent << \"{ \";\n      print_matroid_graph(*leaf->cograph(), indent + \"  \");\n      std::cout << indent << \"}\\n\";\n    }\n    else if (leaf->is_graphic())\n    {\n      std::cout << indent << \"graphic binary matroid.\\n\";\n      std::cout << indent << \"graph:\\n\" << indent << \"{ \";\n      print_matroid_graph(*leaf->graph(), indent + \"  \");\n      std::cout << indent << \"}\\n\";\n    }\n    else if (leaf->is_cographic())\n    {\n      std::cout << indent << \"cographic binary matroid.\\n\";\n      std::cout << indent << \"cograph:\\n\" << indent << \"{ \";\n      print_matroid_graph(*leaf->cograph(), indent + \"  \");\n      std::cout << indent << \"}\\n\";\n    }\n    else\n    {\n      std::cout << indent << \"irregular matroid.\\n\";\n    }\n  }\n  else\n  {\n    unimod::decomposed_matroid_separator* separator = (unimod::decomposed_matroid_separator*) (decomposition);\n\n    if (separator->separation_type() == unimod::decomposed_matroid_separator::ONE_SEPARATION)\n    {\n      std::cout << indent << \"1-separation:\\n\";\n\n    }\n    else if (separator->separation_type() == unimod::decomposed_matroid_separator::TWO_SEPARATION)\n    {\n      std::cout << indent << \"2-separation:\\n\";\n    }\n    else if (separator->separation_type() == unimod::decomposed_matroid_separator::THREE_SEPARATION)\n    {\n      std::cout << indent << \"3-separation:\\n\";\n    }\n    else\n    {\n      std::cout << indent << \"invalid separation:\\n\";\n    }\n    std::cout << indent << \"{\\n\";\n    print_decomposition(separator->first(), indent + \"  \");\n    print_decomposition(separator->second(), indent + \"  \");\n    std::cout << indent << \"}\\n\";\n  }\n}\n\nvoid print_violator(const unimod::integer_matrix& matrix, const unimod::submatrix_indices& violator)\n{\n  typedef boost::numeric::ublas::matrix_indirect <const unimod::integer_matrix, unimod::submatrix_indices::indirect_array_type> indirect_matrix_t;\n\n  const indirect_matrix_t indirect_matrix(matrix, violator.rows, violator.columns);\n\n  for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n  {\n    for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n    {\n      std::cout << std::setw(4) << indirect_matrix(row, column);\n    }\n    std::cout << '\\n';\n  }\n  std::cout << \"\\nRow indices in range [0,\" << (matrix.size1() - 1) << \"]:\\n\";\n  for (size_t row = 0; row < violator.rows.size(); ++row)\n    std::cout << (row == 0 ? \"\" : \" \") << violator.rows[row];\n  std::cout << \"\\n\\nColumn indices in range [0,\" << (matrix.size2() - 1) << \"]:\\n\";\n  for (size_t column = 0; column < violator.columns.size(); ++column)\n    std::cout << (column == 0 ? \"\" : \" \") << violator.columns[column] << ' ';\n  std::cout << std::endl;\n}\n\nvoid print_result(std::ostream& stream, const std::string& name, boost::logic::tribool result)\n{\n  stream << std::setw(20) << name << \": \";\n\n  if (result)\n    stream << \"yes\\n\";\n  else if (!result)\n    stream << \"no\\n\";\n  else\n    stream << \"not determined\\n\";\n}\n\nbool test_total_unimodularity(unimod::integer_matrix& matrix, bool show_certificates, unimod::log_level level)\n{\n  bool result;\n\n  if (show_certificates)\n  {\n    unimod::submatrix_indices violator;\n    unimod::decomposed_matroid* decomposition;\n\n    result = unimod::is_totally_unimodular(matrix, decomposition, violator, level);\n\n    if (result)\n    {\n      std::cout << \"\\nThe matrix is totally unimodular due to the following decomposition:\\n\" << std::endl;\n\n      print_decomposition(decomposition);\n    }\n    else\n    {\n      int det = unimod::submatrix_determinant(matrix, violator);\n      assert (violator.rows.size() == violator.columns.size());\n      std::cout << \"\\nThe matrix is not totally unimodular due to the following \" << violator.rows.size() << \" x \" << violator.columns.size()\n          << \" submatrix with determinant \" << det << \".\" << std::endl;\n      print_violator(matrix, violator);\n    }\n    delete decomposition;\n  }\n  else\n  {\n    result = unimod::is_totally_unimodular(matrix, level);\n    std::cout << \"The matrix is \" << (result ? \"\" : \"not \") << \"totally unimodular.\" << std::endl;\n  }\n\n  return result;\n}\n\nint run(const std::string& file_name, const std::set <char>& tests, bool show_certificates, unimod::log_level level)\n{\n  /// Open the file\n\n  std::ifstream file(file_name.c_str());\n  if (!file.good())\n  {\n    std::cout << \"Error: cannot open file \\\"\" << file_name << \"\\\".\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /// Read height and width\n\n  size_t height, width;\n  file >> height >> width;\n  if (!file.good())\n  {\n    std::cout << \"Error: cannot read matrix size from input file.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /// Read matrix entries\n\n  unimod::integer_matrix matrix(height, width);\n  for (size_t row = 0; row < height; ++row)\n  {\n    for (size_t column = 0; column < width; ++column)\n    {\n      if (!file.good())\n      {\n        std::cout << \"Error: cannot read matrix data.\" << std::endl;\n      }\n      int value;\n      file >> value;\n      matrix(row, column) = value;\n    }\n  }\n\n  file.close();\n  std::cout << \"Read a \" << matrix.size1() << \" x \" << matrix.size2() << \" matrix.\\n\" << std::endl;\n\n  std::map <char, boost::logic::tribool> results;\n  for (size_t i = 0; i < 5; ++i)\n    results[\"tUuMm\"[i]] = boost::logic::indeterminate;\n  size_t rank = 0;\n  bool know_rank = false;\n  unsigned int k = 0;\n\n  if (contains(tests, 't'))\n  {\n    /// Let's test for total unimodularity.\n\n    results['t'] = test_total_unimodularity(matrix, show_certificates, level);\n    k = 1;\n  }\n\n  if (results['t'])\n  {\n    for (size_t i = 0; i < 4; ++i)\n    {\n      results[\"uUmM\"[i]] = true;\n    }\n  }\n  else\n  {\n    if (contains(tests, 'm') || contains(tests, 'M'))\n    {\n      if (level != unimod::LOG_QUIET)\n        std::cout << \"Testing matrix for k-modularity... \" << std::flush;\n      results['m'] = unimod::is_k_modular(matrix, rank, k, unimod::LOG_PROGRESSIVE);\n      std::cout << \"The matrix is \" << (results['m'] ? \"\" : \"not \") << \"k-modular.\\n\" << std::flush;\n\n      results['u'] = (results['m'] && k == 1);\n      if (results['m'])\n        std::cout << \"The matrix is \" << (results['u'] ? \"\" : \"not \") << \"unimodular.\\n\" << std::flush;\n\n      if (!results['m'])\n        results['M'] = false;\n      if (!results['u'])\n      {\n        results['U'] = false;\n        results['t'] = false;\n      }\n      know_rank = true;\n    }\n    else if (contains(tests, 'u') || contains(tests, 'U'))\n    {\n      if (level != unimod::LOG_QUIET)\n        std::cout << \"Testing matrix for unimodularity... \" << std::flush;\n      results['u'] = unimod::is_unimodular(matrix, rank, unimod::LOG_QUIET);\n      std::cout << \"The matrix is \" << (results['u'] ? \"\" : \"not \") << \"unimodular.\\n\" << std::flush;\n\n      if (results['u'])\n        results['m'] = true;\n      if (!results['u'])\n      {\n        results['U'] = false;\n        results['t'] = false;\n      }\n      know_rank = true;\n    }\n    if (contains(tests, 'M') && boost::logic::indeterminate(results['M']))\n    {\n      if (level != unimod::LOG_QUIET)\n        std::cout << \"Testing transpose of matrix for k-modularity... \" << std::flush;\n      unimod::matrix_transposed <unimod::integer_matrix> transposed(matrix);\n      results['M'] = unimod::is_k_modular(transposed, rank, k, unimod::LOG_QUIET);\n      std::cout << \"The transpose is \" << (results['M'] ? \"\" : \"not \") << \"k-modular.\\n\" << std::flush;\n\n      results['U'] = (results['M'] && k == 1);\n      if (results['M'])\n        std::cout << \"The transpose is \" << (results['U'] ? \"\" : \"not \") << \"unimodular.\\n\" << std::flush;\n\n      if (!results['U'])\n        results['t'] = false;\n      know_rank = true;\n    }\n    else if (contains(tests, 'U') && boost::logic::indeterminate(results['U']))\n    {\n      if (level != unimod::LOG_QUIET)\n        std::cout << \"Testing transpose of matrix for unimodularity... \" << std::flush;\n      unimod::matrix_transposed <unimod::integer_matrix> transposed(matrix);\n      results['U'] = unimod::is_unimodular(transposed, rank, unimod::LOG_QUIET);\n      std::cout << \"The transpose is \" << (results['U'] ? \"\" : \"not \") << \"unimodular.\\n\" << std::flush;\n\n      if (!results['U'])\n        results['t'] = false;\n      know_rank = true;\n    }\n  }\n\n  /// Print a summary\n\n  if (know_rank)\n    std::cout << \"\\nSummary of rank \" << rank << \" matrix:\\n\\n\";\n  else\n    std::cout << \"\\nSummary:\\n\\n\";\n\n  print_result(std::cout, \"Totally unimodular\", results['t']);\n  print_result(std::cout, \"Strongly unimodular\", results['U']);\n  print_result(std::cout, \"Unimodular\", results['u']);\n  print_result(std::cout, \"Strongly k-modular\", results['M']);\n  print_result(std::cout, \"k-modular\", results['m']);\n  if (results['m'])\n    std::cout << \"                  k = \" << k << \"\\n\";\n  if (know_rank)\n    print_result(std::cout, \"Dantzig property\", results['m'] && rank == matrix.size1());\n\n  std::cout << std::flush;\n\n  return EXIT_SUCCESS;\n}\n\nbool extract_option(char c, std::set <char>& tests, bool& certs, unimod::log_level& level, bool& help)\n{\n  if (c == 't' || c == 'u' || c == 'm' || c == 'U' || c == 'M')\n    tests.insert(c);\n  else if (c == 'a')\n  {\n    tests.insert('t');\n    tests.insert('u');\n    tests.insert('U');\n    tests.insert('m');\n    tests.insert('M');\n  }\n  else if (c == 'h')\n    help = true;\n  else if (c == 'c')\n    certs = true;\n  else if (c == 'q')\n    level = unimod::LOG_QUIET;\n  else if (c == 'p')\n    level = unimod::LOG_PROGRESSIVE;\n  else if (c == 'v')\n    level = unimod::LOG_VERBOSE;\n  else\n    return false;\n\n  return true;\n}\n\nint main(int argc, char **argv)\n{\n  /// Possible parameters\n  std::string matrix_file_name = \"\";\n  bool certs = false;\n  unimod::log_level level = unimod::LOG_PROGRESSIVE;\n  bool help = false;\n  std::set <char> tests;\n\n  bool options_done = false;\n  for (int a = 1; a < argc; ++a)\n  {\n    const std::string current = argv[a];\n    if (!options_done)\n    {\n      if (current == std::string(\"--\"))\n      {\n        options_done = true;\n        continue;\n      }\n      else if (current != \"\" && current[0] == '-')\n      {\n        for (size_t i = 1; i < current.size(); ++i)\n        {\n          if (!extract_option(current[i], tests, certs, level, help))\n          {\n            std::cerr << \"Unknown option: -\" << current[i] << \"\\nSee \" << argv[0] << \" -h for usage.\" << std::endl;\n            return EXIT_FAILURE;\n          }\n        }\n        continue;\n      }\n    }\n\n    if (matrix_file_name != \"\")\n    {\n      std::cerr << \"Matrix file was given twice!\\nSee \" << argv[0] << \" -h for usage.\" << std::endl;\n      return EXIT_FAILURE;\n    }\n    matrix_file_name = current;\n  }\n\n  if (tests.empty())\n  {\n    tests.insert('t');\n    tests.insert('u');\n    tests.insert('U');\n    tests.insert('m');\n    tests.insert('M');\n  }\n\n  if (help)\n  {\n    std::cerr << \"Usage: \" << argv[0] << \" [OPTIONS] [--] MATRIX_FILE\\n\";\n    std::cerr << \"Options:\\n\";\n    std::cerr << \" -h Shows a help message.\\n\";\n    std::cerr << \" -a Test for everything possible (default).\\n\";\n    std::cerr << \" -t Test for total unimodularity.\\n\";\n    std::cerr << \" -U Test for strong unimodularity.\\n\";\n    std::cerr << \" -u Test for unimodularity.\\n\";\n    std::cerr << \" -M Test for strong k-modularity.\\n\";\n    std::cerr << \" -m Test for k-modularity.\\n\";\n    std::cerr << \" -c Prints certificates: Try to find certificates for the results.\\n\";\n    std::cerr << \" -p Progressive logging (default).\\n\";\n    std::cerr << \" -v Verbose logging.\\n\";\n    std::cerr << \" -q No logging at all.\\n\";\n    std::cerr << std::flush;\n    return EXIT_SUCCESS;\n  }\n\n  if (matrix_file_name == \"\")\n  {\n    std::cerr << \"No matrix file was given!\\nSee \" << argv[0] << \" -h for usage.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  return run(matrix_file_name, tests, certs, level);\n}\n", "meta": {"hexsha": "e8d560fc027f265ca795657e63578ba81a407176", "size": 13969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/unimodularity_test_main.cpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/unimodularity_test_main.cpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unimodularity_test_main.cpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.391011236, "max_line_length": 146, "alphanum_fraction": 0.5787100007, "num_tokens": 4065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.5682077089180191}}
{"text": "#include \"nonThermalLosses.h\"\n#include <fparameters/parameters.h>\n#include <fmath/physics.h>\n#include <gsl/gsl_math.h>\n#include <boost/property_tree/ptree.hpp>\n#include <gsl/gsl_sf_bessel.h>\n\ndouble adiabaticLosses(double E, double z, double vel_lat, double gamma)  //en [erg/s]\n{\n\tstatic const double openingAngle = GlobalConfig.get<double>(\"openingAngle\");\n\n\tdouble jetRadius = z*openingAngle;\n\n\treturn gamma*2.0*(vel_lat*E / (3.0*jetRadius));  \n\t//en el sist lab es sin Gamma\n\t//termina quedando return 2.0*cLight*E / (3.0*z);\n}\n\ndouble BohmDiffusionCoeff(double E, double B)\n{\n\tdouble larmorR = E/(electronCharge*B);\n\treturn 1.0/3.0 * larmorR * cLight;\n}\n\ndouble diffusionTimeParallel(double E, double height, double B)\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble diffCoeff = zeda * BohmDiffusionCoeff(E,B);\n\treturn height*height/diffCoeff;\n}\n\ndouble diffusionTimePerpendicular(double E, double height, double B)\n{\n\tdouble larmorR = E/(electronCharge*B);\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble meanFreePath = larmorR/(3.0*zeda) * pow(height/larmorR,q-1.0);\n\tdouble diffCoeff = zeda * BohmDiffusionCoeff(E,B) / (1.0 + P2(meanFreePath/larmorR));\n\treturn height*height/diffCoeff;\n}\n\ndouble diffCoeff_p(double E, Particle& p, double height, double B, double rho)\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble g = E / (p.mass*cLight2);\n\tdouble kMin = 1.0/height;\n\tdouble vA = B / sqrt(4.0*pi*rho);\n\tdouble rL = E/(electronCharge*B);\n\treturn zeda * gsl_pow_2(p.mass*cLight)* (cLight*kMin) *gsl_pow_2(vA/cLight) * pow(rL*kMin,q-2) * g*g;\n}\n\ndouble diffCoeff_g(double g, Particle& p, double height, double B, double rho)\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble kMin = 1.0/height;\n\tdouble vA = B / sqrt(4.0*pi*rho);\n\tdouble rL = g*p.mass*cLight2/(electronCharge*B);\n\treturn zeda * (cLight*kMin) *gsl_pow_2(vA/cLight) * pow(rL*kMin,q-2) * g*g;\n}\n\ndouble diffCoeff_r(double g, Particle& p, double height, double B)\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble kMin = 1.0/height;\n\tdouble rL = g*p.mass*cLight2/(electronCharge*B);\n\treturn 1.0/9.0 * cLight / zeda * rL * pow(kMin*rL,1-q);\n}\n\ndouble diffLength(double g, Particle& p, double r, double height, double B, double vR)\n{\n\treturn diffCoeff_r(g,p,height,B)/abs(vR);\n}\n\n\ndouble diffusionTimeTurbulence(double E, double height, Particle& p, double B)   //en [s]\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble larmorRadius = E/(electronCharge*B);\n\tdouble tEscape = height/cLight;\n\treturn 9.0*zeda*tEscape*pow(larmorRadius/height, q-2.0);\n}\n\ndouble accelerationTimeSDA(double E, Particle& p, double B, double height, double rho)\n{\n\tdouble zeda = GlobalConfig.get<double>(\"nonThermal.injection.SDA.fractionTurbulent\");\n\tdouble q = GlobalConfig.get<double>(\"nonThermal.injection.SDA.powerSpectrumIndex\");\n\tdouble larmorRadius = E/(electronCharge*B);\n\tdouble tEscape = height/cLight;\n\tdouble alfvenVel = B/sqrt(4.0*pi*rho);\n\treturn (1.0/zeda) / P2(alfvenVel/cLight) * tEscape * pow(larmorRadius/height,2.0-q);\n}\n\ndouble accelerationRateSDA(double E, Particle& p, double B, double height, double rho)\n{\n\tdouble gamma = E / (p.mass*cLight2);\n\treturn diffCoeff_g(gamma,p,height,B,rho) / (gamma*gamma);\n}\n\n\ndouble relaxTime_e(double E, double temp, double dens) {\n\t\n\tdouble gamma = E / electronRestEnergy;\n\tdouble lnLambda = 20.0;\n\tdouble theta = boltzmann*temp / electronRestEnergy;\n\t\n\tif (gamma > 2.0 && theta > 0.3) {\n\t\tdouble k1 = gsl_sf_bessel_K1(1.0/theta);\n\t\tdouble k2 = gsl_sf_bessel_Kn(2, 1.0/theta);\n\t\tdouble factor = abs(k1/k2 - 1.0/gamma);\n\t\treturn 2.0/3.0 * gamma / (dens*thomson*cLight*(lnLambda+9.0/16.0-0.5*log(2.0))) /\n\t\t\t\tfactor;\n\t} else\n\t\treturn 4.0*sqrt(pi)*pow(theta, 1.5) / (dens*thomson*cLight*lnLambda);\n}\n\ndouble relaxTime_p(double E, double temp, double dens) {\n\t\n\tdouble gamma = E / (protonMass*cLight2);\n\tdouble lnLambda = 20.0;\n\tdouble theta = boltzmann*temp / (protonMass*cLight2);\n\tdouble b1 = 70e6*EV_TO_ERG / (protonMass*cLight2);\n\tdouble b2 = 500e6*EV_TO_ERG / (protonMass*cLight2);\n\tif ( gamma-1.0 > b1 && gamma-1.0 < b2 ) {\n\t\tdouble beta = sqrt(1.0-1.0/(gamma*gamma));\n\t\tdouble sigma_h = 2.3e-26;\n\t\treturn 4.0 * gamma*gamma * beta / (gamma*gamma - 1.0) / (dens*sigma_h*cLight);\n\t} else\n\t\treturn 4.0*sqrt(pi)*pow(theta, 1.5) * P2(protonMass/electronMass) / (dens*thomson*cLight*lnLambda);\n}\n\ndouble accelerationRate(double E, double B) //en [s]^-1\n{\n\tdouble accEff = GlobalConfig.get<double>(\"nonThermal.injection.PL.accEfficiency\");\n\treturn accEff*cLight*electronCharge*B/E;\n}\n\n\ndouble escapeRate(double size, double vel) //en [1/s]\n{\n\t//static const double Gamma = GlobalConfig.get<double>(\"Gamma\");\n\n\treturn vel /size;  //ver si necesito algun gamma para escribirlo en el FF\n}", "meta": {"hexsha": "c5508347f89a96e7a015581dfb26e89604108f25", "size": 5395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/flosses/nonThermalLosses.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/lib/flosses/nonThermalLosses.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/flosses/nonThermalLosses.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7006802721, "max_line_length": 102, "alphanum_fraction": 0.725115848, "num_tokens": 1675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5682076943674624}}
{"text": "#include <svo/direct/elder_zucker.h>\n#ifdef __SSSE3__\n#include <tmmintrin.h>\n#endif\n#include <boost/math/special_functions/erf.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\nnamespace svo {\nnamespace elder_zucker {\n\nvoid detectEdges(\n    const std::vector<cv::Mat>& img_pyr,\n    const double sigma,\n    cv::Mat& edge_map,\n    cv::Mat& level_map)\n{\n//  printf(\"detect edges\\n\");\n  const float pi = 3.14159265358979323846264;\n  const float sn = sigma;\n  const float alpha_p = 2e-7;\n  const int n_levels = img_pyr.size()-1;\n\n  // STEP-1: Use local scale control to realiably estimate the intensity\n  // gradient at each image point.\n  std::vector<cv::Mat> img_pyr_smoothed(n_levels);\n  std::vector<cv::Mat> angle_pyr(n_levels);\n  for(int L=0; L<n_levels; ++L)\n  {\n    // smooth image pyramid\n    cv::GaussianBlur(img_pyr[L], img_pyr_smoothed[L], cv::Size(3,3), 0);\n\n    // compute image first derivative\n    const int delta=0;\n    cv::Mat dx, dy;\n    cv::Scharr(img_pyr_smoothed[L], dx, CV_16S, 1, 0, 1, delta, cv::BORDER_DEFAULT );\n    cv::Scharr(img_pyr_smoothed[L], dy, CV_16S, 0, 1, 1, delta, cv::BORDER_DEFAULT );\n\n    // compute critical threshold 1\n    const float scale = L+1;\n    const float s1 = sn * (1.0 / (2.0*sqrt(2.0*pi)*scale*scale));\n    const float c1 = s1 * sqrt(-2.0*log(alpha_p));\n//    printf(\"c1 = %f\\n\", c1);\n\n    // compute angle and magnitude in angle direction\n    const int n_rows = img_pyr_smoothed[L].rows;\n    const int n_cols = img_pyr_smoothed[L].cols;\n    angle_pyr[L] = cv::Mat(dx.size(), CV_32F);\n    for(int y=0; y<n_rows; ++y)\n    {\n      int16_t* p_dx = dx.ptr<int16_t>(y);\n      int16_t* p_dy = dy.ptr<int16_t>(y);\n      float* p_a = angle_pyr[L].ptr<float>(y);\n      for(int x=0; x<n_cols; ++x)\n      {\n        p_a[x] = std::atan2(p_dy[x], p_dx[x]);\n        float mag = std::cos(p_a[x])*p_dx[x]+std::sin(p_a[x])*p_dy[x];\n        if(std::abs(mag) < c1)\n          p_a[x]=0;\n      }\n    }\n  }\n\n  // find minimum level\n  cv::Mat angle(img_pyr_smoothed[0].size(), CV_32FC1, cv::Scalar(0));\n  for(int y=0; y<img_pyr_smoothed[0].rows; ++y)\n  {\n    float* p_a = angle.ptr<float>(y);\n    uint8_t* p_lev = level_map.ptr<uint8_t>(y);\n    for(int x=0; x<img_pyr_smoothed[0].cols; ++x)\n    {\n      for(int L=0; L<n_levels; ++L)\n      {\n        const float a = angle_pyr[L].at<float>(y/(1<<L), x/(1<<L));\n        if(a != 0.0) // TODO: what if angle is actually 0.0?\n        {\n          p_a[x] = a;\n          break;\n        }\n      }\n    }\n  }\n\n  std::vector<cv::Mat> lap_of_gau_pyr(img_pyr_smoothed.size());\n  for(int L=0; L<n_levels; ++L)\n  {\n    // compute image second derivative\n    cv::Mat dxdx1, dydy1, dxdy1;\n    getCovarEntries(img_pyr_smoothed[L], dxdx1, dydy1, dxdy1);\n\n    // smooth\n    cv::Mat dxdx, dydy, dxdy;\n    filterGauss3by316S(dxdx1, dxdx);\n    filterGauss3by316S(dydy1, dydy);\n    filterGauss3by316S(dxdy1, dxdy);\n\n    // compute critical threshold 2\n    const float scale = L+1;\n    const float s2 = sn / (4.0 * sqrt(pi/3.0)*scale*scale*scale);\n    const float c2 = sqrt(2.0) * s2 * (boost::math::erf_inv(1-alpha_p));\n\n    // compute laplacian of gaussians\n    const int n_rows = img_pyr_smoothed[L].rows;\n    const int n_cols = img_pyr_smoothed[L].cols;\n    lap_of_gau_pyr[L] = cv::Mat(img_pyr_smoothed[L].size(), CV_32F);\n    for(int y=0; y<n_rows; ++y)\n    {\n      int16_t* p_dxdx = dxdx.ptr<int16_t>(y);\n      int16_t* p_dxdy = dxdy.ptr<int16_t>(y);\n      int16_t* p_dydy = dydy.ptr<int16_t>(y);\n      float* p_a = angle.ptr<float>(y);\n      float* p_l = lap_of_gau_pyr[L].ptr<float>(y);\n      for(int x=0; x<n_cols; ++x)\n      {\n        const float ca = cos(p_a[x]);\n        const float sa = sin(p_a[x]);\n        p_l[x] = (ca*ca*p_dxdx[x])+(sa*sa*p_dydy[x])-(2*ca*sa*p_dxdy[x]);\n        if(fabs(p_l[x]) < c2)\n          p_l[x]=0;\n      }\n    }\n  }\n\n  // find minimum level\n  edge_map = cv::Mat(img_pyr_smoothed[0].size(), CV_32FC1, cv::Scalar(0));\n  level_map = cv::Mat(img_pyr_smoothed[0].size(), CV_8UC1, cv::Scalar(0));\n  for(int y=0; y<img_pyr_smoothed[0].rows; ++y)\n  {\n    float* p_e = edge_map.ptr<float>(y);\n    uint8_t* p_lev = level_map.ptr<uint8_t>(y);\n    for(int x=0; x<img_pyr_smoothed[0].cols; ++x)\n    {\n      for(int L=0; L<n_levels; ++L)\n      {\n        const float e = lap_of_gau_pyr[L].at<float>(y/(1<<L), x/(1<<L));\n        if(e != 0.0)\n        {\n          p_e[x] = e;\n          p_lev[x] = L;\n          break;\n        }\n      }\n    }\n  }\n}\n\n\nvoid getCovarEntries(\n    const cv::Mat& src,\n    cv::Mat& dxdx,\n    cv::Mat& dydy,\n    cv::Mat& dxdy)\n{\n#ifdef __SSSE3__\n  cv::Mat kernel=cv::Mat::zeros(3,3,CV_8S);\n  kernel.at<char>(0,0)=3*8;\n  kernel.at<char>(1,0)=10*8;\n  kernel.at<char>(2,0)=3*8;\n  kernel.at<char>(0,2)=-3*8;\n  kernel.at<char>(1,2)=-10*8;\n  kernel.at<char>(2,2)=-3*8;\n\n  const unsigned int X=3; // kernel size\n  const unsigned int Y=3; // kernel size\n  const unsigned int cx=1;\n  const unsigned int cy=1;\n\n  // dest will be 16 bit\n  dxdx=cv::Mat::zeros(src.rows,src.cols,CV_16S);\n  dydy=cv::Mat::zeros(src.rows,src.cols,CV_16S);\n  dxdy=cv::Mat::zeros(src.rows,src.cols,CV_16S);\n\n  const unsigned int maxJ=((src.cols-2)/16)*16;\n  const unsigned int maxI=src.rows-2;\n  const unsigned int stride=src.cols;\n\n  __m128i mask_hi = _mm_set_epi8(0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF);\n  __m128i mask_lo = _mm_set_epi8(0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00);\n\n  for(unsigned int i=0; i<maxI; ++i)\n  {\n    bool end=false;\n    for(unsigned int j=0; j<maxJ; )\n    {\n      //__m128i result = _mm_set_epi16 ( -127,-127,-127,-127,-127,-127,-127,-127,-127,-127);\n      __m128i result_hi_dx = _mm_set_epi16 ( 0,0,0,0,0,0,0,0);\n      __m128i result_lo_dx = _mm_set_epi16 ( 0,0,0,0,0,0,0,0);\n      __m128i result_hi_dy = _mm_set_epi16 ( 0,0,0,0,0,0,0,0);\n      __m128i result_lo_dy = _mm_set_epi16 ( 0,0,0,0,0,0,0,0);\n\n      // enter convolution with kernel\n      for(unsigned int x=0;x<X;++x)\n      {\n        //if(dx&&x==1)continue; // jump, 0 kernel\n        for(unsigned int y=0;y<Y;++y)\n        {\n          //if(!dx&&y==1)continue; // jump, 0 kernel\n          const char m_dx=kernel.at<char>(y,x);\n          const char m_dy=kernel.at<char>(x,y);\n          __m128i mult_dx = _mm_set_epi16(m_dx,m_dx,m_dx,m_dx,m_dx,m_dx,m_dx,m_dx);\n          __m128i mult_dy = _mm_set_epi16(m_dy,m_dy,m_dy,m_dy,m_dy,m_dy,m_dy,m_dy);\n          uchar* p=(src.data+(stride*(i+y))+x+j);\n          __m128i i0 = _mm_loadu_si128 ((__m128i*)p);\n          __m128i i0_hi=_mm_and_si128(i0,mask_hi);\n          __m128i i0_lo=_mm_srli_si128(_mm_and_si128(i0,mask_lo),1);\n\n          if(m_dx!=0)\n          {\n            __m128i i_hi_dx = _mm_mullo_epi16 (i0_hi, mult_dx);\n            __m128i i_lo_dx = _mm_mullo_epi16 (i0_lo, mult_dx);\n            result_hi_dx=_mm_add_epi16(result_hi_dx,i_hi_dx);\n            result_lo_dx=_mm_add_epi16(result_lo_dx,i_lo_dx);\n          }\n\n          if(m_dy!=0)\n          {\n            __m128i i_hi_dy = _mm_mullo_epi16 (i0_hi, mult_dy);\n            __m128i i_lo_dy = _mm_mullo_epi16 (i0_lo, mult_dy);\n            result_hi_dy=_mm_add_epi16(result_hi_dy,i_hi_dy);\n            result_lo_dy=_mm_add_epi16(result_lo_dy,i_lo_dy);\n          }\n        }\n      }\n\n      // calculate covariance entries - remove precision (ends up being 4 bit), then remove 4 more bits\n      __m128i i_hi_dx_dx = _mm_srai_epi16(_mm_mulhi_epi16 (result_hi_dx, result_hi_dx),4);\n      __m128i i_hi_dy_dy = _mm_srai_epi16(_mm_mulhi_epi16 (result_hi_dy, result_hi_dy),4);\n      __m128i i_hi_dx_dy = _mm_srai_epi16(_mm_mulhi_epi16 (result_hi_dy, result_hi_dx),4);\n      __m128i i_lo_dx_dx = _mm_srai_epi16(_mm_mulhi_epi16 (result_lo_dx, result_lo_dx),4);\n      __m128i i_lo_dy_dy = _mm_srai_epi16(_mm_mulhi_epi16 (result_lo_dy, result_lo_dy),4);\n      __m128i i_lo_dx_dy = _mm_srai_epi16(_mm_mulhi_epi16 (result_lo_dy, result_lo_dx),4);\n\n      // store\n      uchar* p_lo_dxdx=(dxdx.data+(2*stride*(i+cy)))+2*cx+2*j;\n      uchar* p_hi_dxdx=(dxdx.data+(2*stride*(i+cy)))+2*cx+2*j+16;\n      _mm_storeu_si128 ((__m128i*)p_hi_dxdx,_mm_unpackhi_epi16 (i_hi_dx_dx, i_lo_dx_dx));\n      _mm_storeu_si128 ((__m128i*)p_lo_dxdx,_mm_unpacklo_epi16 (i_hi_dx_dx, i_lo_dx_dx));\n      uchar* p_lo_dydy=(dydy.data+(2*stride*(i+cy)))+2*cx+2*j;\n      uchar* p_hi_dydy=(dydy.data+(2*stride*(i+cy)))+2*cx+2*j+16;\n      _mm_storeu_si128 ((__m128i*)p_hi_dydy,_mm_unpackhi_epi16 (i_hi_dy_dy, i_lo_dy_dy));\n      _mm_storeu_si128 ((__m128i*)p_lo_dydy,_mm_unpacklo_epi16 (i_hi_dy_dy, i_lo_dy_dy));\n      uchar* p_lo_dxdy=(dxdy.data+(2*stride*(i+cy)))+2*cx+2*j;\n      uchar* p_hi_dxdy=(dxdy.data+(2*stride*(i+cy)))+2*cx+2*j+16;\n      _mm_storeu_si128 ((__m128i*)p_hi_dxdy,_mm_unpackhi_epi16 (i_hi_dx_dy, i_lo_dx_dy));\n      _mm_storeu_si128 ((__m128i*)p_lo_dxdy,_mm_unpacklo_epi16 (i_hi_dx_dy, i_lo_dx_dy));\n\n      // take care about end\n      j+=16;\n      if(j>=maxJ&&!end)\n      {\n        j=stride-2-16;\n        end=true;\n      }\n    }\n  }\n#endif\n}\n\nvoid filterGauss3by316S(\n    const cv::Mat& src,\n    cv::Mat& dst)\n{\n#ifdef __SSSE3__\n  // sanity check\n  const unsigned int X=3;\n  const unsigned int Y=3;\n  assert(X%2!=0);\n  assert(Y%2!=0);\n  int cx=X/2;\n  int cy=Y/2;\n\n  // dest will be 16 bit\n  dst=cv::Mat::zeros(src.rows,src.cols,CV_16S);\n  const unsigned int maxJ=((src.cols-2)/8)*8;\n  const unsigned int maxI=src.rows-2;\n  const unsigned int stride=src.cols;\n\n  for(unsigned int i=0; i<maxI; ++i)\n  {\n    bool end=false;\n    for(unsigned int j=0; j<maxJ; )\n    {\n      // enter convolution with kernel. do the multiplication with 2/4 at the same time\n      __m128i i00 = _mm_loadu_si128 ((__m128i*)&src.at<short>(i,j));\n      __m128i i10 = _mm_slli_epi16(_mm_loadu_si128 ((__m128i*)&src.at<short>(i+1,j)),1);\n      __m128i i20 = _mm_loadu_si128 ((__m128i*)&src.at<short>(i+2,j));\n      __m128i i01 = _mm_slli_epi16(_mm_loadu_si128 ((__m128i*)&src.at<short>(i,j+1)),1);\n      __m128i i11 = _mm_slli_epi16(_mm_loadu_si128 ((__m128i*)&src.at<short>(i+1,j+1)),2);\n      __m128i i21 = _mm_slli_epi16(_mm_loadu_si128 ((__m128i*)&src.at<short>(i+2,j+1)),1);\n      __m128i i02 = _mm_loadu_si128 ((__m128i*)&src.at<short>(i,j+2));\n      __m128i i12 = _mm_slli_epi16(_mm_loadu_si128 ((__m128i*)&src.at<short>(i+1,j+2)),1);\n      __m128i i22 = _mm_loadu_si128 ((__m128i*)&src.at<short>(i+2,j+2));\n      __m128i result = i11;\n\n      // add up\n      result=_mm_add_epi16(result,i00);\n      result=_mm_add_epi16(result,i20);\n      result=_mm_add_epi16(result,i02);\n      result=_mm_add_epi16(result,i22);\n\n      result=_mm_add_epi16(result,i10);\n      result=_mm_add_epi16(result,i01);\n      result=_mm_add_epi16(result,i12);\n      result=_mm_add_epi16(result,i21);\n\n      // store\n      //uchar* p_r=(dst.data+(2*stride*(i+cy)))+2*cx+2*j;\n      _mm_storeu_si128 ((__m128i*)&dst.at<short>(i+cy,j+cx),result);\n\n      // take care about end\n      j+=8;\n      if(j>=maxJ&&!end)\n      {\n              j=stride-2-8;\n              end=true;\n      }\n    }\n  }\n#endif\n}\n\n} // namespace elder_zucker\n} // namespace svo\n\n\n", "meta": {"hexsha": "d1448eb4ed752cb1a1f31d62dd3287b91d1f6069", "size": 11036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "svo_direct/src/elder_zucker.cpp", "max_stars_repo_name": "jsz0913/rpg_dvs_evo_open", "max_stars_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T09:34:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T01:58:09.000Z", "max_issues_repo_path": "svo_direct/src/elder_zucker.cpp", "max_issues_repo_name": "jsz0913/rpg_dvs_evo_open", "max_issues_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-06-14T13:01:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:49:57.000Z", "max_forks_repo_path": "svo_direct/src/elder_zucker.cpp", "max_forks_repo_name": "jsz0913/rpg_dvs_evo_open", "max_forks_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T09:34:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T15:23:29.000Z", "avg_line_length": 33.8527607362, "max_line_length": 114, "alphanum_fraction": 0.6198803914, "num_tokens": 4003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.568202557115012}}
{"text": "#include <state_estimation/filters/ekf_vs.h>\n#include <state_estimation/utilities/data_subset_utilities.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nvoid EKFVS::myPredict(const Eigen::VectorXd& u, double dt) {\n    system_model_->update(filter_state_.x, u, dt);\n\n    // Update the state and covariance. For the covariance the update will happen on the state\n    // subsets then be converted back to the full dimensionality.\n    filter_state_.x = system_model_->g();\n\n    const Eigen::MatrixXd cov_subset =\n        getSubset(filter_state_.covariance, system_model_->activeStates());\n    const Eigen::MatrixXd G_subset = getSubset(system_model_->G(), system_model_->activeStates());\n    const Eigen::MatrixXd Rc_subset =\n        getSubset(system_model_->Rc(), system_model_->activeControls());\n    const Eigen::MatrixXd P_subset =\n        getSubset(system_model_->P(), system_model_->activeStates(), {});\n    const Eigen::MatrixXd V_subset = getSubset(system_model_->V(), system_model_->activeStates(),\n                                               system_model_->activeControls());\n\n    const Eigen::MatrixXd cov_prime_subset = G_subset * cov_subset * G_subset.transpose() +\n                                             P_subset * system_model_->Rp() * P_subset.transpose() +\n                                             V_subset * Rc_subset * V_subset.transpose();\n\n    convertSubsetToFull(cov_prime_subset, &filter_state_.covariance, system_model_->activeStates());\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 EKFVS::myCorrect(const Eigen::VectorXd& z,\n                      measurement_models::NonlinearMeasurementModel* model, double dt) {\n    // Update our measurement model\n    model->update(filter_state_.x, dt);\n\n    // Get our sub matrices/vectors\n    const Eigen::MatrixXd cov_subset =\n        getSubset(filter_state_.covariance, system_model_->activeStates());\n    const Eigen::MatrixXd H_subset =\n        getSubset(model->H(), model->activeMeasurements(), system_model_->activeStates());\n    const Eigen::MatrixXd meas_cov_subset =\n        getSubset(model->covariance(), model->activeMeasurements());\n\n    // Compute the Kalman gain\n    const Eigen::MatrixXd cov_H_T = cov_subset * H_subset.transpose();\n    const Eigen::MatrixXd K = cov_H_T * (H_subset * cov_H_T + meas_cov_subset).inverse();\n\n    // Update the state\n    const Eigen::VectorXd dz_full = model->subtractVectors(z, model->h());\n    const Eigen::VectorXd dz_subset = getSubset(dz_full, model->activeMeasurements());\n    const Eigen::VectorXd dx_subset = K * dz_subset;\n    const Eigen::VectorXd dx_full = convertSubsetToFullZeroed(\n        dx_subset, system_model_->activeStates(), system_model_->stateSize());\n\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx_full);\n\n    // Update the covariance\n    const Eigen::MatrixXd I = Eigen::MatrixXd::Identity(cov_subset.rows(), cov_subset.rows());\n    const Eigen::MatrixXd cov_prime = (I - K * H_subset) * cov_subset;\n\n    convertSubsetToFull(cov_prime, &filter_state_.covariance, system_model_->activeStates());\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_full) << 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": "ee519daeb053c1498644bc49c1e4c533f90b082c", "size": 4420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/ekf_vs.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_vs.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_vs.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": 46.5263157895, "max_line_length": 100, "alphanum_fraction": 0.6321266968, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5681111110925905}}
{"text": "// g++ -std=c++11 mandel2.cpp -o mandel2 -O3 -lpng\n\n#include <iostream>\n#include <array>\n#include <complex>\n#include <utility>\n#include <tuple>\n#include <sstream>\n\n#define png_infopp_NULL (png_infopp)NULL\n#define int_p_NULL (int*)NULL\n\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/io/png_io.hpp>\n\n#include <boost/format.hpp> \n\nclass FrAdapter;\n\nclass Fr\n{\npublic:\n\tfriend class FrAdapter;\n\n\tusing fl_t = double;\n\tusing cp_t = std::complex<fl_t>;\n\n\tFr() = default;\n\tFr(const Fr&) = default;\n\t~Fr() = default;\n\n\tstd::pair<fl_t, fl_t> step() const {\n\t\treturn std::make_pair(\n\t\t\t((xmax_ - xmin_) / res_x_)\n\t\t\t, ((ymax_ - ymin_) / res_y_)\n\t\t\t);\n\t}\n\n\tchar project_iter(unsigned i) const {\n\t\treturn ccc_[i * ccc_.size() / static_cast<fl_t>(max_)];\n\t}\n\n\tunsigned iterate(const cp_t& c) const {\n\t\tcp_t cc = c;\n\t\tunsigned i = 0;\n\t\twhile(i < max_) {\n\t\t\tif (abs(cc) > 4.0)\n\t\t\t\treturn i;\n\t\t\tcc = pow(cc, this->pow_) + c;\n\t\t\t++i;\n\t\t}\n\t\treturn max_ - 1;\n\t}\n\n\tfl_t iterate_d(const cp_t& c) const {\n\t\treturn this->iterate(c) / static_cast<fl_t>(max_);\n\t}\n\n\tvoid render(std::ostream& o = std::cout) const {\n\t\tfl_t fx, fy;\n\t\tstd::tie(fx, fy) = this->step();\n\t\tfor(unsigned ry = 0; ry < res_y_; ++ry) {\n\t\t\tfl_t y = ymax_ - ry * fy;\n\t\t\tfor(unsigned rx = 0; rx < res_x_; ++rx) {\n\t\t\t\tunsigned i = this->iterate(cp_t(xmin_ + rx * fx, y));\n\t\t\t\to << this->project_iter(i);\n\t\t\t}\n\t\t\to << std::endl;\n\t\t}\n\t} \n\n\tvoid fit_range_to_res(fl_t fd = 0.5) {\n\t\t//std::pair<fl_t, fl_t> old = std::make_pair(res_x_, res_y_);\n\t\tfl_t fr = static_cast<fl_t>(res_x_) / static_cast<fl_t>(res_y_) * fd;\n\t\t//std::cout << \"fr \" << fr << std::endl;\n\t\tauto lx = (xmax_ - xmin_);\n\t\tauto ly = (ymax_ - ymin_);\n\t\tfl_t fw = lx / ly;\n\t\t//std::cout << \"fw \" << fw << std::endl;\n\t\tif (fr > fw) {\n\t\t\t// stretch x\n\t\t\tauto lxn = ly * fr;\n\t\t\tauto lxd = lxn - lx;\n\t\t\txmin_ -= lxd / 2.0;\n\t\t\txmax_ += lxd / 2.0;\n\t\t} else if (fr < fw) {\n\t\t\t// stretch y\n\t\t\t// fr = 5/4 = 1.25\n\t\t\t// fw = 3/2 = 1.5\n\t\t\t// fwn= 3/\n\t\t\tauto lyn = lx * 1 / fr;\n\t\t\tauto lyd = lyn - ly;\n\t\t\tymin_ -= lyd / 2.0;\n\t\t\tymax_ += lyd / 2.0;\n\t\t}\n\t}\n\n\tvoid set_res(unsigned rx, unsigned ry) {\n\t\tstd::tie(this->res_x_, this->res_y_) = std::make_tuple(rx, ry);\n\t}\n\n\tvoid set_pow(fl_t p) {\n\t\tthis->pow_ = p;\n\t}\n\n\tvoid set_max(unsigned m) {\n\t\tthis->max_ = m;\n\t}\n\n\tvoid set_window(const std::tuple<fl_t, fl_t, fl_t, fl_t>& w) {\n\t\tstd::tie(xmin_, ymin_, xmax_, ymax_) = w;\n\t\tif (xmin_ > xmax_)\n\t\t\tstd::swap(xmin_, xmax_);\n\t\tif (ymin_ > ymax_)\n\t\t\tstd::swap(ymin_, ymax_);\n\t}\n\nprivate:\n\tfl_t xmin_{-2.0}, ymin_{-1.2}, xmax_{0.8}, ymax_{1.2};\n\tfl_t pow_{2.0};\n\tunsigned max_ {256};\n\tunsigned res_x_ {1000}, res_y_{500};\n\tstd::array<char, 14> ccc_ {{'-', '.', ',', ':', ';', '+', '*', '=', 'o', 'O', '0', '#', 'M', ' '}};\n};\n\nclass FrAdapter {\npublic:\n\ttypedef boost::gil::point2<ptrdiff_t>   point_t;\n\n    typedef FrAdapter           const_t;\n    typedef boost::gil::gray8_pixel_t       value_type;\n    typedef value_type          reference;\n    typedef value_type          const_reference;\n    typedef point_t             argument_type;\n    typedef reference           result_type;\n    BOOST_STATIC_CONSTANT(bool, is_mutable=false);\n\n    FrAdapter(const point_t& siz = point_t(200,76), Fr::fl_t pow = 2.0) {\n    \tfr_.set_res(siz.x, siz.y);\n    \tfr_.fit_range_to_res(1.0);\n    \tfr_.set_pow(pow);\n    }\n\n    Fr::cp_t map_to_complex(const point_t& p) const {\n    \treturn Fr::cp_t(((p.x / static_cast<Fr::fl_t>(fr_.res_x_)) * (fr_.xmax_ - fr_.xmin_)) + fr_.xmin_\n    \t\t\t      , ((p.y / static_cast<Fr::fl_t>(fr_.res_y_)) * (fr_.ymax_ - fr_.ymin_)) + fr_.ymin_\n    \t\t);\n    }\n    result_type operator()(const point_t& p) const {\n    \tauto c = this->map_to_complex(p);\n    \t//std::cerr << fr_.xmax_ - fr_.xmin_ << \" \";\n    \t//std::cerr << \"(\" << p.x << \"; \" << p.y << \") -> \" << c << std::endl; //<< c.real() << \", \" << c.imag() << \")\" << std::endl;\n    \tauto i = fr_.iterate_d(c);\n    \treturn value_type((boost::gil::bits8)(pow(i,this->pow_)*255));\n    }\n\n    Fr& fr() {return fr_;};\n\n    void set_pow(Fr::fl_t p) {\n    \tthis->pow_ = p;\n    }\n\nprivate:\n\tFr fr_;\n\tFr::fl_t pow_{0.5};\n};\n\nint main(int argc, char const *argv[])\n{\n\t//Fr f;\n\t//std::cout << f.step().first << \" \" << f.step().second << std::endl;\n\t//f.render();\n\t//f.set_res(200, 76);\n\t//f.set_res(400, 150);\n\t//f.set_res(800, 300);\n\t//f.set_res(4000, 1600);\n\t//f.render();\n\t//f.fit_range_to_res();\n\t//std::cout << f.step().first << \" \" << f.step().second << std::endl;\n\t//f.render();\n\ttypedef boost::gil::virtual_2d_locator<FrAdapter,false> locator_t;\n\ttypedef boost::gil::image_view<locator_t> my_virt_view_t;\n\tFrAdapter::point_t res(1000,1000);\n\n\tfor(double d = 2.0; d < 2.1; d += 0.025) {\n\t\tfor(double p = 0.5; p < 0.6; p += 0.1) {\n\t\t\tstd::ostringstream oss;\n\t\t\toss << boost::format{\"p_%3.2f_%2.1f.png\"} % d % p;\n\t\t\tstd::string filename = oss.str();\n\t\t\tstd::cout << filename << std::endl; \n\t\t\tFrAdapter fra(res, d);\n\t\t\t//fra.fr().set_window(std::make_tuple(-2.0, -1.5, 1.0, 1.5));\n\t\t\tfra.fr().set_window(std::make_tuple(-0.0, -0.9, 0.4, -0.4));\n\t\t\tfra.fr().fit_range_to_res(1.0);\n\t\t\tfra.set_pow(p);\n\t\t\tmy_virt_view_t mandel(res, locator_t(FrAdapter::point_t(0, 0), FrAdapter::point_t(1, 1), fra));\n\n\t\t\t//boost::gil::gray8s_image_t img(res);\n\t\t\tboost::gil::png_write_view(filename, mandel);\n\t\n\t\t}\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "f2e5d3d82e363256d84cce3f24a51cb0e8813f34", "size": 5280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp14/mandel2/mandel2.cpp", "max_stars_repo_name": "noeld/cpp", "max_stars_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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": "cpp14/mandel2/mandel2.cpp", "max_issues_repo_name": "noeld/cpp", "max_issues_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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": "cpp14/mandel2/mandel2.cpp", "max_forks_repo_name": "noeld/cpp", "max_forks_repo_head_hexsha": "572a145f8c79f7292b7b0611822ed34792df4e9c", "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.756097561, "max_line_length": 130, "alphanum_fraction": 0.578030303, "num_tokens": 1885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5678925400496694}}
{"text": "#include <TSR.h>\n#include <Eigen/Geometry>\n#include <ompl/util/RandomNumbers.h>\n#include <vector>\n\nusing namespace or_ompl;\n\nTSR::TSR() : _initialized(false) {\n\n}\n\nTSR::TSR(const Eigen::Affine3d &T0_w, const Eigen::Affine3d &Tw_e, const Eigen::Matrix<double, 6, 2> &Bw) :\n\t_T0_w(T0_w), _Tw_e(Tw_e), _Bw(Bw), _initialized(true) {\n\n\t_T0_w_inv = _T0_w.inverse();\n\t_Tw_e_inv = _Tw_e.inverse();\n\n}\n\nbool TSR::deserialize(std::stringstream &ss) {\n\n\t// TODO: Do we need this stuff? \n\tint manipind_ignored;\n    ss >> manipind_ignored;\n\n\tstd::string relativebodyname_ignored;\n    ss >> relativebodyname_ignored;\n   \n    if( relativebodyname_ignored != \"NULL\" )\n    {\n\t\tstd::string relativelinkname_ignored;\n        ss >> relativelinkname_ignored;  \n    }  \n    \n\t// Read in the T0_w matrix \n\tdouble tmp;\n\tfor(unsigned int c=0; c < 3; c++){\n\t\tfor(unsigned int r=0; r < 3; r++){\n\t\t\tss >> tmp;\n\t\t\t_T0_w.matrix()(r,c) = tmp;\n\t\t}\n\t}\n\n\tfor(unsigned int idx=0; idx < 3; idx++){\n\t\tss >> tmp;\n\t\t_T0_w.translation()(idx) = tmp;\n\t}\t\n\n\t// Read in the Tw_e matrix \n\tfor(unsigned int c=0; c < 3; c++){\n\t\tfor(unsigned int r=0; r < 3; r++){\n\t\t\tss >> tmp;\n\t\t\t_Tw_e.matrix()(r,c) = tmp;\n\t\t}\n\t}\n\n\tfor(unsigned int idx=0; idx < 3; idx++){\n\t\tss >> tmp;\n\t\t_Tw_e.translation()(idx) = tmp;\n\t}\n\n\t// Read in the Bw matrix \n\tfor(unsigned int r=0; r < 6; r++){\n\t\tfor(unsigned int c=0; c < 2; c++){\n\t\t\tss >> tmp;\n\t\t\t_Bw(r,c) = tmp;\n\t\t}\n\t}\n\n\t_T0_w_inv = _T0_w.inverse();\n\t_Tw_e_inv = _Tw_e.inverse();\n\n\t_initialized = true;\n\n    return _initialized;\n}\n\n\nEigen::Matrix<double, 6, 1> TSR::distance(const Eigen::Affine3d &ee_pose) const {\n\tEigen::Matrix<double, 6, 1> dist = Eigen::Matrix<double, 6, 1>::Zero();\n\n\t// First compute the pose of the w frame in world coordinates, given the ee_pose\n\tEigen::Affine3d w_in_world = ee_pose * _Tw_e_inv;\n\t\n\t// Next compute the pose of the w frame relative to its original pose (as specified by T0_w)\n\tEigen::Affine3d w_offset = _T0_w_inv * w_in_world;\n\n\t// Now compute the elements of the distance matrix\n\tdist(0,0) = w_offset.translation()(0);\n\tdist(1,0) = w_offset.translation()(1);\n\tdist(2,0) = w_offset.translation()(2);\n\tdist(3,0) = atan2(w_offset.rotation()(2,1), w_offset.rotation()(2,2));\n\tdist(4,0) = -asin(w_offset.rotation()(2,0));\n\tdist(5,0) = atan2(w_offset.rotation()(1,0), w_offset.rotation()(0,0));\n\n\treturn dist;\n}\n\nEigen::Matrix<double, 6, 1> TSR::displacement(const Eigen::Affine3d &ee_pose) const {\n\n\tEigen::Matrix<double, 6, 1> dist = distance(ee_pose);\n\tEigen::Matrix<double, 6, 1> disp = Eigen::Matrix<double, 6, 1>::Zero();\n\n\tfor(unsigned int idx=0; idx < 6; idx++){\n\t\t\n\t\tif(dist(idx,0) < _Bw(idx,0)){\n\t\t\tdisp(idx,0) = dist(idx,0) - _Bw(idx,0);\n\t\t}else if(dist(idx,0) > _Bw(idx,1)){\n\t\t\tdisp(idx,0) = dist(idx,0) - _Bw(idx,1);\n\t\t}\n\t}\n\n\treturn disp;\n}\n\nEigen::Affine3d TSR::sampleDisplacementTransform(void) const {\n\n\t// First sample uniformly betwee each of the bounds of Bw\n\tstd::vector<double> d_sample(6);\n\t\n\tompl::RNG rng;\n\tfor(unsigned int idx=0; idx < d_sample.size(); idx++){\n\t\tif(_Bw(idx,1) > _Bw(idx,0)){\n\t\t\td_sample[idx] = rng.uniformReal(_Bw(idx,0), _Bw(idx,1)); \t\t\n\t\t}\n\t}\n\n\tEigen::Affine3d return_tf;\n\treturn_tf.translation() << d_sample[0], d_sample[1], d_sample[2];\n\n\t// Convert to a transform matrix\n\tdouble roll = d_sample[3];\n\tdouble pitch = d_sample[4];\n\tdouble yaw = d_sample[5];\n\n\tdouble A = cos(yaw);\n\tdouble B = sin(yaw);\n\tdouble C = cos(pitch);\n\tdouble D = sin(pitch);\n\tdouble E = cos(roll);\n\tdouble F = sin(roll);\n\treturn_tf.linear() << A*C, A*D*F - B*E, B*F + A*D*E,\n\t\tB*C, A*E + B*D*F, B*D*E - A*F,\n\t\t-D, C*F, C*E;\n\n\treturn return_tf;\n}\n\nEigen::Affine3d TSR::sample() const {\n\n\tEigen::Affine3d tf = sampleDisplacementTransform(); \n\t\n\treturn _T0_w * tf * _Tw_e;\n}\n", "meta": {"hexsha": "e3ec6a88717cf2e627a42eca4d6152e811011ff5", "size": 3712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TSR.cpp", "max_stars_repo_name": "DavidB-CMU/or_ompl", "max_stars_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "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/TSR.cpp", "max_issues_repo_name": "DavidB-CMU/or_ompl", "max_issues_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "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/TSR.cpp", "max_forks_repo_name": "DavidB-CMU/or_ompl", "max_forks_repo_head_hexsha": "ebdc809a48bf2d3adc0c723967eb42bc36fd3acd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-19T13:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-19T13:23:06.000Z", "avg_line_length": 23.9483870968, "max_line_length": 107, "alphanum_fraction": 0.6376616379, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5678925400496694}}
{"text": "///\n/// \\file vandermonde.hpp\n///\n#ifndef MXPFIT_VANDERMONDE_LEAST_SQUARES_HPP\n#define MXPFIT_VANDERMONDE_LEAST_SQUARES_HPP\n\n#include <cassert>\n\n#include <Eigen/Core>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <mxpfit/matrix_free_gemv.hpp>\n#include <mxpfit/vandermonde_matrix.hpp>\n\nnamespace mxpfit\n{\n\nnamespace detail\n{\n\n///\n/// \\internal\n///\n/// Compute Cholesky decomposition of the gramian matrix of column Vandermonde\n/// matrix.\n///\n/// This function compute the LDL decomposition of the gramian matrix,\n///\n/// \\f[ G = V^{\\ast} V = L^{} D L^{\\ast}, \\f]\n///\n/// where \\f$ V=[v_{j}^{i}]_{i=1,\\dots,m}^{n=1,\\dots,n}\\f$ is the column\n/// Vandermonde matrix, \\f$ L \\f$ is a lower unit triangular matrix, and \\f$ D\n/// \\f$ is a diagonal matrix.\n///\n/// \\param[in] V  An \\f$ m \\times n \\f$ column Vandermonde matrix to be\n///   decomposed.\n/// \\param[out] ldlt  An \\ f$ n \\times n \\f$ matrix to store the result of\n///   decomposition. On exit, the diagonal elements of `ldlt` are those of\n///   matrix \\f$ D, \\f$ and strict lower triangular part contains the off\n///   diagonal elements of factor \\f$ L \\f$.\n///\n/// \\param[out] work  An \\f$ n \\times 4 \\f$ matrix used for workspace\n///\ntemplate <typename T, typename MatrixT, typename MatrixWork>\nvoid cholesky_vandermonde_gramian(const VandermondeMatrix<T>& V, MatrixT& ldlt,\n                                  MatrixWork& work)\n{\n    using Scalar       = typename VandermondeMatrix<T>::Scalar;\n    using CoeffsVector = typename VandermondeMatrix<T>::CoeffsVector;\n    using RealScalar   = typename Eigen::NumTraits<Scalar>::Real;\n    using Index        = Eigen::Index;\n\n    using Eigen::numext::abs;\n    using Eigen::numext::abs2;\n    using Eigen::numext::conj;\n    using Eigen::numext::real;\n    using Eigen::numext::sqrt;\n\n    static const auto tiny   = sqrt(std::numeric_limits<RealScalar>::min());\n    constexpr const auto one = Scalar(1);\n\n    auto z        = V.coeffs();\n    const Index m = V.rows();\n    const Index n = V.cols();\n\n    assert(ldlt.rows() == n && ldlt.cols() == n);\n    assert(work.rows() == n && work.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 = [&](Index i, Index j) {\n        const auto arg = conj(z(i)) * z(j);\n        return arg == one ? Scalar(m) : (one - std::pow(arg, m)) / (one - arg);\n    };\n\n    auto sigma2 = gramian(0, 0);\n    auto b0     = ldlt.col(0);\n    b0(0)       = one;\n    for (Index j = 1; j < n; ++j)\n    {\n        b0(j) = gramian(j, 0) / sigma2;\n    }\n\n    y1 = CoeffsVector::Ones(n) - b0;\n    y2 = z.array().conjugate().pow(m);\n    y2 -= y2(0) * b0;\n    x1 = z.array().conjugate().inverse();\n    x1 -= x1(0) * b0;\n    x2 = -z.array().conjugate().pow(m - 1);\n    x2 -= x2(0) * b0;\n\n    b0(0) = sigma2;\n\n    for (Index k = 1; k < n; ++k)\n    {\n        auto bk = ldlt.col(k);\n\n        auto mu1 = x1(k);\n        auto mu2 = x2(k);\n        auto nu1 = conj(y1(k));\n        auto nu2 = conj(y2(k));\n\n        auto zk_inv = one / z(k);\n        auto denom  = conj(zk_inv) - z(k);\n\n        if (abs(denom) < tiny)\n        {\n            sigma2         = RealScalar(m);\n            const auto bkk = real(ldlt(k, k));\n            for (Index j = 0; j < k; ++j)\n            {\n                const auto bkj = ldlt(k, j);\n                sigma2 -= abs2(bkj) * bkk;\n            }\n        }\n        else\n        {\n            sigma2 = (mu1 * nu1 + mu2 * nu2) / denom;\n        }\n\n        bk(k) = sigma2;\n\n        Index nt    = n - k - 1;\n        bk.tail(nt) = (conj(mu1) / sigma2 * y1.tail(nt) +\n                       conj(mu2) / sigma2 * y2.tail(nt));\n        bk.array().tail(nt) /=\n            (CoeffsVector::Constant(nt, zk_inv) - z.tail(nt).conjugate())\n                .array();\n\n        x1.tail(nt) -= mu1 * bk.tail(nt);\n        x2.tail(nt) -= mu2 * bk.tail(nt);\n        y1.tail(nt) -= conj(nu1) * bk.tail(nt);\n        y2.tail(nt) -= conj(nu2) * bk.tail(nt);\n    }\n\n    return;\n}\n\n} // namespace detail\n\n///\n/// Preconditioner specialized for of Vandermonde matrix\n///\ntemplate <typename T>\nclass VandermondePreconditioner\n{\npublic:\n    using Scalar     = T;\n    using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n    using StorageIndex = typename Matrix::StorageIndex;\n    using Index        = Eigen::Index;\n\n    using VandermondeGEMV = MatrixFreeGEMV<VandermondeMatrix<Scalar>>;\n    enum\n    {\n        ColsAtCompileTime    = Eigen::Dynamic,\n        MaxColsAtCompileTime = Eigen::Dynamic,\n    };\n\n    VandermondePreconditioner() = default;\n\n    ~VandermondePreconditioner() = default;\n\n    Index rows() const\n    {\n        return m_ldlt.rows();\n    }\n\n    Index cols() const\n    {\n        return m_ldlt.cols();\n    }\n\n    VandermondePreconditioner& analyzePattern(const VandermondeGEMV&)\n    {\n        return *this;\n    }\n\n    VandermondePreconditioner& factorize(const VandermondeGEMV& mat)\n    {\n        const Index n = mat.cols();\n\n        m_ldlt.resize(n, n);\n        m_invdiag.resize(n);\n        Matrix work(n, 4);\n        //\n        // Compute Cholesky decomposition of the Gramian matrix of the form\n        // \\f$ V^{\\ast} V = L D L^{\\ast} \\f$\n        //\n        detail::cholesky_vandermonde_gramian(mat.nestedExpression(), m_ldlt,\n                                             work);\n\n        for (Index i = 0; i < n; ++i)\n        {\n            if (m_ldlt(i, i) == Scalar())\n            {\n                m_invdiag(i) = RealScalar(1);\n            }\n            else\n            {\n                m_invdiag(i) = RealScalar(1) / m_ldlt(i, i);\n            }\n        }\n        m_is_initialized = true;\n        return *this;\n    }\n\n    VandermondePreconditioner& compute(const VandermondeGEMV& mat)\n    {\n        return factorize(mat);\n    }\n\n    template <typename Rhs, typename Dest>\n    void _solve_impl(const Rhs& b, Dest& x) const\n    {\n        auto matL = m_ldlt.template triangularView<Eigen::UnitLower>();\n        x         = matL.solve(b);\n        x.array() *= m_invdiag.array();\n        matL.adjoint().solveInPlace(x);\n    }\n\n    template <typename Rhs>\n    inline const Eigen::Solve<VandermondePreconditioner, Rhs>\n    solve(const Eigen::MatrixBase<Rhs>& b) const\n    {\n        eigen_assert(m_is_initialized &&\n                     \"VandermondePreconditioner is not initialized.\");\n        eigen_assert(m_ldlt.cols() == b.rows() &&\n                     \"VandermondePreconditioner::solve(): invalid \"\n                     \"number of rows of the right hand side matrix b\");\n        return Eigen::Solve<VandermondePreconditioner, Rhs>(*this, b.derived());\n    }\n\n    Eigen::ComputationInfo info()\n    {\n        return Eigen::Success;\n    }\n\nprivate:\n    Matrix m_ldlt;\n    Vector m_invdiag;\n    bool m_is_initialized;\n};\n\n///\n/// ### VandermondeLeastSquaresSolver\n///\n/// Solve a least squares problem, \\f$V \\boldsymbol{x}=\\boldsymbol{b},\\f$ where\n/// \\f$V\\f$ is a column Vandermonde matrix.\n///\ntemplate <typename T>\nusing VandermondeLeastSquaresSolver =\n    Eigen::LeastSquaresConjugateGradient<MatrixFreeGEMV<VandermondeMatrix<T>>,\n                                         VandermondePreconditioner<T>>;\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_VANDERMONDE_LEAST_SQUARES_HPP */\n", "meta": {"hexsha": "60dd93a748eee318355264b3200906775218c127", "size": 7355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/vandermonde_least_squares.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/vandermonde_least_squares.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/vandermonde_least_squares.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5468164794, "max_line_length": 80, "alphanum_fraction": 0.5643779742, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6548947290421276, "lm_q1q2_score": 0.5678171579857044}}
{"text": "/**\n * @file instances_helper.hpp\n * @author francois.hamonic@gmail.com\n * @brief parse specific instances datas\n * @version 0.1\n * @date 2020-05-08\n */\n#ifndef INSTANCES_HELPER_HPP\n#define INSTANCES_HELPER_HPP\n\n#include <math.h>\n#include <algorithm>\n#include <execution>\n#include <numeric>\n#include <random>\n\n#include <lemon/adaptors.h>\n\n#include <boost/range/algorithm/sort.hpp>\n\n#include \"landscape/mutable_landscape.hpp\"\n#include \"solvers/concept/instance.hpp\"\n\n#include \"fast-cpp-csv-parser/csv.h\"\n#include \"utils/random_chooser.hpp\"\n\nvoid addCostNoise(Instance & instance, double deviation_ratio = 0.2,\n                  int seed = 456) {\n    std::default_random_engine generator(seed);\n    std::normal_distribution<double> distribution(1.0, deviation_ratio);\n\n    auto noise = [&generator, &distribution](double value) {\n        return std::max(std::numeric_limits<double>::epsilon(),\n                        value * distribution(generator));\n    };\n\n    for(const RestorationPlan<MutableLandscape>::Option i :\n        instance.plan.options())\n        instance.plan.setCost(i, noise(instance.plan.getCost(i)));\n}\n\nInstance make_instance_aude(const double median,\n                            const double fish_ladder_prob) {\n    Instance instance;\n\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    std::array<MutableLandscape::Node, 45> nodes;\n    MutableLandscape::Graph::NodeMap<double> troncons_lengths(graph);\n    // MutableLandscape::Graph::NodeMap<int> depth_id(graph);\n\n    auto p = [median](const double d) {\n        return std::exp(d / median * std::log(0.5));\n    };\n\n    io::CSVReader<4> patches(\"../landscape_opt_datas/Aude/aude.patches\");\n    patches.read_header(io::ignore_extra_column, \"id\", \"length\", \"x\", \"y\");\n    int id;\n    double length, X, Y;\n    while(patches.read_row(id, length, X, Y)) {\n        MutableLandscape::Node u = landscape.addNode(length, Point(X, Y));\n        nodes[id] = u;\n        troncons_lengths[u] = length;\n    }\n\n    io::CSVReader<3> links(\"../landscape_opt_datas/Aude/aude.links\");\n    links.read_header(io::ignore_extra_column, \"source_id\", \"target_id\", \"dam\");\n    int source_id, target_id, dam;\n    while(links.read_row(source_id, target_id, dam)) {\n        MutableLandscape::Node u = nodes[source_id];\n        MutableLandscape::Node v = nodes[target_id];\n\n        const double prob = p((troncons_lengths[u] + troncons_lengths[v]) / 2);\n\n        if(!dam) {\n            MutableLandscape::Arc a =\n                landscape.addArc(nodes[source_id], nodes[target_id], prob);\n            continue;\n        }\n        MutableLandscape::Arc a =\n            landscape.addArc(nodes[source_id], nodes[target_id], 0);\n        RestorationPlan<MutableLandscape>::Option option = plan.addOption(1);\n        plan.addArc(option, a, fish_ladder_prob * prob);\n    }\n\n    return instance;\n}\n\nInstance make_instance_quebec_leam(double pow, double thresold, double median,\n                                   double decreased_prob,\n                                   Point orig = Point(240548, 4986893),\n                                   Point dim = Point(32360, 20000)) {\n    Instance instance;\n\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    auto p = [median, pow](const double d) {\n        return std::exp(std::pow(d, pow) / std::pow(median, pow) *\n                        std::log(0.5));\n    };\n\n    std::array<MutableLandscape::Node, 8248> node_correspondance;\n    node_correspondance.fill(lemon::INVALID);\n\n    using ThreatData = struct {\n        MutableLandscape::Node node;\n        double area;\n    };\n    std::vector<ThreatData> threaten_list;\n\n    io::CSVReader<5> patches(\n        \"../landscape_opt_datas/quebec_leam_v3/raw/sommets_leam_v3.csv\");\n    patches.read_header(io::ignore_extra_column, \"count\", \"area\", \"xcoord\",\n                        \"ycoord\", \"count2050\");\n    int id;\n    double area, xcoord, ycoord, count2050;\n    while(patches.read_row(id, area, xcoord, ycoord, count2050)) {\n        if(xcoord < orig.x) continue;\n        if(xcoord >= orig.x + dim.x) continue;\n        if(ycoord < orig.y) continue;\n        if(ycoord >= orig.y + dim.y) continue;\n\n        MutableLandscape::Node u =\n            landscape.addNode(count2050, Point(xcoord, ycoord));\n        node_correspondance[id] = u;\n\n        if(area == count2050) continue;\n        if(area > 0 && count2050 == 0) {\n            threaten_list.push_back(ThreatData{u, area});\n            continue;\n        }\n\n        const double area_loss = area - count2050;\n        RestorationPlan<MutableLandscape>::Option option =\n            plan.addOption(area_loss);\n        plan.addNode(option, u, area_loss);\n    }\n\n    io::CSVReader<3> links(\n        \"../landscape_opt_datas/quebec_leam_v3/raw/aretes_leam_v3.csv\");\n    links.read_header(io::ignore_extra_column, \"from\", \"to\", \"Dist\");\n    int from, to;\n    double Dist;\n    while(links.read_row(from, to, Dist)) {\n        MutableLandscape::Node u = node_correspondance[from];\n        MutableLandscape::Node v = node_correspondance[to];\n        if(u == lemon::INVALID || v == lemon::INVALID) continue;\n        double probability = p(Dist);\n        if(probability < thresold) continue;\n        landscape.addArc(u, v, probability);\n        landscape.addArc(v, u, probability);\n    }\n\n    for(ThreatData data : threaten_list) {\n        MutableLandscape::Node v1 = data.node;\n        RestorationPlan<MutableLandscape>::Option option =\n            plan.addOption(data.area);\n        landscape.setCoords(v1, landscape.getCoords(v1) + Point(-200, 0));\n        MutableLandscape::Node v2 =\n            landscape.addNode(0, landscape.getCoords(v1) + Point(200, 0));\n\n        for(MutableLandscape::Graph::OutArcIt a(graph, v1), next_a = a;\n            a != lemon::INVALID; a = next_a) {\n            ++next_a;\n            landscape.changeSource(a, v2);\n        }\n        MutableLandscape::Arc v1v2 = landscape.addArc(v1, v2, decreased_prob);\n        plan.addArc(option, v1v2, 1);\n        plan.addNode(option, v2, data.area);\n    }\n\n    return instance;\n}\n\nInstance make_instance_quebec_frog(double pow, double thresold, double median) {\n    Instance instance;\n\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    auto p = [median, pow](const double d) {\n        return std::exp(std::pow(d, pow) / std::pow(median, pow) *\n                        std::log(0.5));\n    };\n\n    std::array<MutableLandscape::Node, 3032> node_correspondance;\n    node_correspondance.fill(lemon::INVALID);\n\n    using ThreatData = struct {\n        MutableLandscape::Node node;\n        double area;\n    };\n    std::vector<ThreatData> threaten_list;\n\n    io::CSVReader<5> patches(\n        \"../landscape_opt_datas/quebec_438_RASY/vertices_438_RASY.csv\");\n    patches.read_header(io::ignore_extra_column, \"name\", \"area\", \"xcoord\",\n                        \"ycoord\", \"per_menace\");\n    int id;\n    double area_in_2000, xcoord, ycoord, per_menace;\n    while(patches.read_row(id, area_in_2000, xcoord, ycoord, per_menace)) {\n        area_in_2000 /= 100;\n        const double area_loss_by_2050 = area_in_2000 * per_menace;\n        const double area_in_2050 = area_in_2000 - area_loss_by_2050;\n\n        MutableLandscape::Node u =\n            landscape.addNode(area_in_2050, Point(xcoord, ycoord));\n        node_correspondance[id] = u;\n\n        if(per_menace == 0) continue;\n        if(per_menace == 1) {\n            threaten_list.push_back(ThreatData{u, area_in_2000});\n            continue;\n        }\n\n        RestorationPlan<MutableLandscape>::Option option =\n            plan.addOption(area_loss_by_2050);\n        plan.addNode(option, u, area_loss_by_2050);\n    }\n\n    io::CSVReader<3> links(\n        \"../landscape_opt_datas/quebec_438_RASY/edges_438_RASY.csv\");\n    links.read_header(io::ignore_extra_column, \"from\", \"to\", \"Dist\");\n    int from, to;\n    double Dist;\n    while(links.read_row(from, to, Dist)) {\n        MutableLandscape::Node u = node_correspondance[from];\n        MutableLandscape::Node v = node_correspondance[to];\n        if(u == lemon::INVALID || v == lemon::INVALID) continue;\n        double probability = p(Dist);\n        if(probability < thresold) continue;\n        landscape.addArc(u, v, probability);\n        landscape.addArc(v, u, probability);\n    }\n\n    for(ThreatData data : threaten_list) {\n        MutableLandscape::Node v1 = data.node;\n        RestorationPlan<MutableLandscape>::Option option =\n            plan.addOption(data.area);\n        landscape.setCoords(v1, landscape.getCoords(v1) + Point(-200, 0));\n        MutableLandscape::Node v2 =\n            landscape.addNode(0, landscape.getCoords(v1) + Point(200, 0));\n\n        for(MutableLandscape::Graph::OutArcIt a(graph, v1), next_a = a;\n            a != lemon::INVALID; a = next_a) {\n            ++next_a;\n            landscape.changeSource(a, v2);\n        }\n        MutableLandscape::Arc v1v2 = landscape.addArc(v1, v2, 0);\n        plan.addArc(option, v1v2, 1);\n        plan.addNode(option, v1, data.area);\n    }\n\n    return instance;\n}\n\nInstance make_instance_biorevaix_level_2_v7(const double restoration_coef = 2,\n                                            const double distance_coef = 1) {\n    Instance instance;\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    auto prob = [distance_coef](const double cost) {\n        return cost == 1     ? std::pow(1, distance_coef)\n               : cost == 10  ? std::pow(0.98, distance_coef)\n               : cost == 150 ? std::pow(0.8, distance_coef)\n               : cost == 300 ? std::pow(0.6, distance_coef)\n               : cost == 800 ? std::pow(0.4, distance_coef)\n                             : 0;\n    };\n\n    std::array<MutableLandscape::Node, 688402> nodes;\n    nodes.fill(lemon::INVALID);\n    MutableLandscape::Graph::NodeMap<double> node_prob(graph, 0.0);\n    MutableLandscape::Graph::NodeMap<RestorationPlan<MutableLandscape>::Option>\n        troncon_option(graph);\n    std::array<RestorationPlan<MutableLandscape>::Option, 2008> id_tronc_option;\n    id_tronc_option.fill(-1);\n\n    io::CSVReader<7> patches(\n        \"../landscape_opt_datas/BiorevAix/vertexN2_v7.txt\");\n    patches.read_header(io::ignore_extra_column, \"N2_id\", \"X\", \"Y\", \"N4_id\",\n                        \"area2\", \"area4\", \"cost_mode\");\n    int N2_id, N4_id;\n    int area2, area4;\n    double X, Y, cost;\n    while(patches.read_row(N2_id, X, Y, N4_id, area2, area4, cost)) {\n        if(!area2) continue;\n        // if(!area4) continue;\n        if(cost == 1000) continue;\n        MutableLandscape::Node u =\n            landscape.addNode((cost == 1 ? 1 : 0), Point(X, Y));\n        nodes[N2_id] = u;\n        node_prob[u] = prob(cost);\n        troncon_option[u] = -1;\n\n        if(cost != 800) continue;\n        RestorationPlan<MutableLandscape>::Option & option =\n            id_tronc_option[N4_id];\n        if(option == -1) option = plan.addOption(0);\n        troncon_option[u] = option;\n        plan.setCost(option, plan.getCost(option) + 1);\n    }\n\n    io::CSVReader<2> links(\"../landscape_opt_datas/BiorevAix/AL_N2.txt\");\n    links.read_header(io::ignore_extra_column, \"from\", \"to\");\n    int from, to;\n    while(links.read_row(from, to)) {\n        const MutableLandscape::Node u = nodes[from];\n        const MutableLandscape::Node v = nodes[to];\n        if(u == lemon::INVALID || v == lemon::INVALID) continue;\n        if(node_prob[u] == 0 || node_prob[v] == 0) continue;\n\n        RestorationPlan<MutableLandscape>::Option option_u = troncon_option[u];\n        RestorationPlan<MutableLandscape>::Option option_v = troncon_option[v];\n        if(option_u > 0 && option_v > 0 && option_u != option_v) {\n            const MutableLandscape::Node w = landscape.addNode(\n                0, (landscape.getCoords(u) + landscape.getCoords(v)) / 2);\n\n            const MutableLandscape::Arc uw =\n                landscape.addArc(u, w, std::sqrt(node_prob[u]));\n            const MutableLandscape::Arc wu =\n                landscape.addArc(w, u, std::sqrt(node_prob[u]));\n            const MutableLandscape::Arc wv =\n                landscape.addArc(w, v, std::sqrt(node_prob[v]));\n            const MutableLandscape::Arc vw =\n                landscape.addArc(v, w, std::sqrt(node_prob[v]));\n\n            const double restored_prob_u =\n                std::pow(node_prob[u], 1 / (2 * restoration_coef));\n            const double restored_prob_v =\n                std::pow(node_prob[v], 1 / (2 * restoration_coef));\n\n            plan.addArc(option_u, uw, restored_prob_u);\n            plan.addArc(option_u, wu, restored_prob_u);\n            plan.addArc(option_v, vw, restored_prob_v);\n            plan.addArc(option_v, wv, restored_prob_v);\n            continue;\n        };\n\n        double probability = std::sqrt(node_prob[u] * node_prob[v]);\n        probability = std::max(std::min(probability, 1.0), 0.0);\n\n        const MutableLandscape::Arc uv = landscape.addArc(u, v, probability);\n        const MutableLandscape::Arc vu = landscape.addArc(v, u, probability);\n\n        if(option_u < 0 && option_v < 0) continue;\n\n        RestorationPlan<MutableLandscape>::Option option =\n            std::max(option_u, option_v);\n        double restored_prob =\n            std::pow(node_prob[u],\n                     1 / (2 * (option_u >= 0 ? restoration_coef : 1))) *\n            std::pow(node_prob[v],\n                     1 / (2 * (option_v >= 0 ? restoration_coef : 1)));\n        if(restored_prob <= probability) continue;\n        plan.addArc(option, uv, restored_prob);\n        plan.addArc(option, vu, restored_prob);\n    }\n    return instance;\n}\n\nInstance make_instance_biorevaix_level_2_all_troncons(\n    const double restoration_coef = 2, const double distance_coef = 1) {\n    Instance instance;\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    auto prob = [distance_coef](const double cost) {\n        return cost == 1     ? std::pow(1, distance_coef)\n               : cost == 10  ? std::pow(0.98, distance_coef)\n               : cost == 150 ? std::pow(0.8, distance_coef)\n               : cost == 300 ? std::pow(0.6, distance_coef)\n               : cost == 800 ? std::pow(0.4, distance_coef)\n                             : 0;\n    };\n\n    std::array<MutableLandscape::Node, 98344> nodes;\n    nodes.fill(lemon::INVALID);\n    MutableLandscape::Graph::NodeMap<double> node_prob(graph, 0.0);\n\n    io::CSVReader<6> patches(\n        \"../landscape_opt_datas/BiorevAix/vertexN2_v7.txt\");\n    patches.read_header(io::ignore_extra_column, \"N2_id\", \"X\", \"Y\", \"area2\",\n                        \"area4\", \"cost_mode\");\n    int N2_id;\n    int area2, area4;\n    double X, Y, cost;\n    while(patches.read_row(N2_id, X, Y, area2, area4, cost)) {\n        // if(!area2) continue;\n        // if(!area4) continue;\n        if(cost == 1000) continue;\n        MutableLandscape::Node u =\n            landscape.addNode((cost == 1 ? 1 : 0), Point(X, Y));\n        nodes[N2_id] = u;\n        node_prob[u] = prob(cost);\n    }\n\n    io::CSVReader<2> links(\"../landscape_opt_datas/BiorevAix/AL_N2.txt\");\n    links.read_header(io::ignore_extra_column, \"from\", \"to\");\n    int from, to;\n    while(links.read_row(from, to)) {\n        const MutableLandscape::Node u = nodes[from];\n        const MutableLandscape::Node v = nodes[to];\n        if(u == lemon::INVALID || v == lemon::INVALID) continue;\n        if(node_prob[u] == 0 || node_prob[v] == 0) continue;\n\n        double probability = std::sqrt(node_prob[u] * node_prob[v]);\n        probability = std::max(std::min(probability, 1.0), 0.0);\n\n        const MutableLandscape::Arc uv = landscape.addArc(u, v, probability);\n        const MutableLandscape::Arc vu = landscape.addArc(v, u, probability);\n    }\n\n    std::array<RestorationPlan<MutableLandscape>::Option, 5460> troncon_option;\n    for(int i=0; i<5460; ++i) {\n        troncon_option[i] = plan.addOption(0);\n    }\n    io::CSVReader<2> troncons(\n        \"../landscape_opt_datas/BiorevAix/croisemt_troncon_hexagN2.txt\");\n    troncons.read_header(io::ignore_extra_column, \"troncon_id\", \"N2_id\");\n    int troncon_id;\n    while(troncons.read_row(troncon_id, N2_id)) {\n        const MutableLandscape::Node u = nodes[N2_id];\n\n        RestorationPlan<MutableLandscape>::Option option =\n            troncon_option[troncon_id];\n\n        plan.setCost(option, plan.getCost(option) + 1);\n\n        for(MutableLandscape::Graph::OutArcIt uv(graph, u);\n            uv != lemon::INVALID; ++uv) {\n            const MutableLandscape::Node v = graph.target(uv);\n            const double probability = landscape.getProbability(uv);\n            double restored_prob =\n                std::pow(node_prob[u], 1 / (2 * restoration_coef)) *\n                std::pow(node_prob[v], 1 / 2);\n            if(restored_prob <= probability) continue;\n            plan.addArc(option, uv, restored_prob);\n        }\n    }\n    return instance;\n}\n\nInstance make_instance_marseille(double pow, double thresold, double median,\n                                 int nb_friches = 100) {\n    Instance instance;\n\n    MutableLandscape & landscape = instance.landscape;\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    RestorationPlan<MutableLandscape> & plan = instance.plan;\n\n    auto d = [&landscape](MutableLandscape::Node u, MutableLandscape::Node v) {\n        return std::sqrt(\n            (landscape.getCoords(u) - landscape.getCoords(v)).normSquare());\n    };\n    auto p = [median, pow](const double d) {\n        return std::exp(std::pow(d, pow) / std::pow(median, pow) *\n                        std::log(0.5));\n    };\n\n    using FricheData = struct {\n        Point p;\n        double area;\n        double price;\n        MutableLandscape::Node node;\n    };\n    RandomChooser<FricheData> friches_chooser(9876);\n    std::vector<FricheData> friches_list;\n\n    io::CSVReader<5> patches(\n        \"../landscape_opt_datas/Marseille/vertices_marseillec.csv\");\n    patches.read_header(io::ignore_extra_column, \"category\", \"x\", \"y\", \"area2\",\n                        \"price_rel\");\n    std::string category;\n    double x, y, area, price_rel;\n    while(patches.read_row(category, x, y, area, price_rel)) {\n        if(category.compare(\"\\\"massif\\\"\") == 0) {\n            landscape.addNode(20, Point(x, y));\n            continue;\n        }\n        if(category.compare(\"\\\"parc\\\"\") == 0) {\n            landscape.addNode(area, Point(x, y));\n            continue;\n        }\n        if(category.compare(\"\\\"friche\\\"\") == 0) {\n            friches_chooser.add(\n                FricheData{Point(x, y), area, price_rel * area, lemon::INVALID},\n                1);\n            continue;\n        }\n        assert(false);\n    }\n    for(int i = 0; i < nb_friches; i++) {\n        if(!friches_chooser.canPick()) break;\n        FricheData data = friches_chooser.pick();\n        MutableLandscape::Node u = landscape.addNode(0, data.p);\n        data.node = u;\n        friches_list.push_back(data);\n    }\n\n    for(MutableLandscape::NodeIt u(graph); u != lemon::INVALID; ++u) {\n        for(MutableLandscape::NodeIt v(graph); v != lemon::INVALID; ++v) {\n            if(v < u || u == v) continue;\n            double dist = d(u, v);\n            double probability = p(dist);\n            if(probability < thresold) continue;\n            landscape.addArc(u, v, probability);\n            landscape.addArc(v, u, probability);\n        }\n    }\n\n    for(FricheData data : friches_list) {\n        MutableLandscape::Node v1 = data.node;\n        RestorationPlan<MutableLandscape>::Option option =\n            plan.addOption(data.price);\n        MutableLandscape::Node v2 = landscape.addNode(\n            0, landscape.getCoords(v1) + Point(0.0001, 0.0001));\n\n        for(MutableLandscape::Graph::OutArcIt a(graph, v1), next_a = a;\n            a != lemon::INVALID; a = next_a) {\n            ++next_a;\n            landscape.changeSource(a, v2);\n        }\n        MutableLandscape::Arc v1v2 = landscape.addArc(v1, v2, 0);\n        plan.addArc(option, v1v2, 1);\n        plan.addNode(option, v2, data.area);\n    }\n\n    return instance;\n}\n\n#endif  // INSTANCES_HELPER_HPP", "meta": {"hexsha": "ecf1aacedb1ef0e89309690de32ab56c6ac20431", "size": 20567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/instances_helper.hpp", "max_stars_repo_name": "fhamonic/landscape_opt", "max_stars_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:09.000Z", "max_issues_repo_path": "include/instances_helper.hpp", "max_issues_repo_name": "fhamonic/landscape_opt", "max_issues_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/instances_helper.hpp", "max_forks_repo_name": "fhamonic/landscape_opt", "max_forks_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-27T16:58:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:58:19.000Z", "avg_line_length": 38.087037037, "max_line_length": 80, "alphanum_fraction": 0.6084018087, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5678171395556054}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2011 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 exponentialjump1dmesher.cpp\n    \\brief mesher for a exponential jump mesher with high \n           mean reversion rate and low jump intensity\n*/\n\n#include <ql/math/incompletegamma.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/distributions/gammadistribution.hpp>\n#include <ql/methods/finitedifferences/meshers/exponentialjump1dmesher.hpp>\n\n#include <boost/bind.hpp>\n\nnamespace QuantLib {\n    ExponentialJump1dMesher::ExponentialJump1dMesher(\n          Size steps, Real beta, Real jumpIntensity, Real eta, Real eps)\n    : Fdm1dMesher(steps),\n      beta_(beta), jumpIntensity_(jumpIntensity), eta_(eta)\n   {\n        QL_REQUIRE(eps > 0.0 && eps < 1.0, \"eps > 0.0 and eps < 1.0\");\n        QL_REQUIRE(steps > 1, \"minimum number of steps is two\");\n        \n        const Real start = 0.0;\n        const Real end   = 1.0-eps;    \n        const Real dx    = (end-start)/(steps-1);\n    \n        for (Size i=0; i < steps; ++i) {\n            const Real p = start + i*dx;\n            locations_[i] = -1.0/eta*std::log(1.0-p);\n        }\n        for (Size i=0; i < steps-1; ++i) {\n            dminus_[i+1] = dplus_[i] = locations_[i+1]-locations_[i];\n        }\n        dplus_.back() = dminus_.front() = Null<Real>();\n    }\n                                    \n                                    \n    Real ExponentialJump1dMesher::jumpSizeDensity(Real x, Time t) const {\n        const Real a    = 1.0-jumpIntensity_/beta_;\n        const Real norm = 1.0-std::exp(-jumpIntensity_*t);\n        const Real gammaValue \n            = std::exp(GammaFunction().logValue(1.0-jumpIntensity_/beta_));\n        return jumpIntensity_*gammaValue/norm\n                    *( incompleteGammaFunction(a, x*std::exp(beta_*t)*eta_)\n                      -incompleteGammaFunction(a, x*eta_))\n                    *std::pow(eta_, jumpIntensity_/beta_)\n                    /(beta_*std::pow(x, a));\n    }\n    \n    Real ExponentialJump1dMesher::jumpSizeDensity(Real x) const {\n        const Real a = 1.0-jumpIntensity_/beta_;\n        const Real gammaValue \n                = std::exp(GammaFunction().logValue(jumpIntensity_/beta_));\n        return std::exp(-x*eta_)*std::pow(x, -a) * std::pow(eta_, 1.0-a) \n                / gammaValue;\n    }\n\n    Real ExponentialJump1dMesher::jumpSizeDistribution(Real x, Time t) const {\n        const Real xmin = std::min(x, 1.0e-100);\n        \n        return GaussLobattoIntegral(1000000, 1e-12)(\n            boost::bind(&ExponentialJump1dMesher::jumpSizeDensity, this, _1, t),\n            xmin, std::max(x, xmin));\n    }\n\n    Real ExponentialJump1dMesher::jumpSizeDistribution(Real x) const {\n        const Real a    = jumpIntensity_/beta_;\n        const Real xmin = std::min(x, QL_EPSILON);\n        const Real gammaValue \n                = std::exp(GammaFunction().logValue(jumpIntensity_/beta_));\n        \n        const Real lowerEps = \n            (std::pow(xmin, a)/a - std::pow(xmin, a+1)/(a+1))/gammaValue;\n        \n        return lowerEps + GaussLobattoIntegral(10000, 1e-12)(\n            boost::bind(&ExponentialJump1dMesher::jumpSizeDensity, this, _1),\n            xmin/eta_, std::max(x, xmin/eta_));\n    }\n}\n", "meta": {"hexsha": "730957cfc446217af7cf586b81b067c92d72d57a", "size": 3957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/meshers/exponentialjump1dmesher.cpp", "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/methods/finitedifferences/meshers/exponentialjump1dmesher.cpp", "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/methods/finitedifferences/meshers/exponentialjump1dmesher.cpp", "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": 40.3775510204, "max_line_length": 80, "alphanum_fraction": 0.6186504928, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5678171386453997}}
{"text": "#ifndef gaussian_process_regression_hpp\n#define gaussian_process_regression_hpp\n\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    class GaussianProcessRegression\n    {\n    public:\n        // Construction with input data\n        GaussianProcessRegression(const Eigen::MatrixXd& X, const Eigen::VectorXd& y);\n\n        // Estimation methods\n        double EstimateY(const Eigen::VectorXd& x) const;\n        double EstimateVariance(const Eigen::VectorXd& x) const;\n\n        // Hyperparameters setup methods\n        void SetHyperparameters(double sigma_squared_f,\n                                double sigma_squared_n,\n                                const Eigen::VectorXd& length_scales);\n        void PerformMaximumLikelihood(double sigma_squared_f_initial,\n                                      double sigma_squared_n_initial,\n                                      const Eigen::VectorXd& length_scales_initial);\n\n        // Getter methods\n        const Eigen::MatrixXd& GetX() const { return X; }\n        const Eigen::VectorXd& GetY() const { return y; }\n\n    private:\n\n        // Data points\n        Eigen::MatrixXd X;\n        Eigen::VectorXd y;\n\n        // Derivative data\n        Eigen::MatrixXd K;\n        Eigen::MatrixXd K_inv;\n\n        // Hyperparameters\n        double          sigma_squared_f;\n        double          sigma_squared_n;\n        Eigen::VectorXd length_scales;\n    };\n}\n\n#endif /* gaussian_process_regression_hpp */\n", "meta": {"hexsha": "0da2cdc2b4216bb69cf8207698dedccd994f821c", "size": 1438, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/gaussian-process-regression.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "include/mathtoolbox/gaussian-process-regression.hpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mathtoolbox/gaussian-process-regression.hpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 29.9583333333, "max_line_length": 86, "alphanum_fraction": 0.6077885953, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5678156937552392}}
{"text": "#include \"spline.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include \"quadpp.h\"\n\nint main()\n{\n  const std::size_t npts = 1001;\n  const double low = 0, high = 1;\n\n  Eigen::ArrayXd xs, rs, ys, jac;\n  quadpp::SemiInfiniteIntegralMesh(npts, low, high, xs, rs, jac);\n  ys = jac * Eigen::exp(-rs);\n  ys.tail(1) = 0;\n\n  auto result1 =\n      quadpp::spline::Integrate(xs, ys, quadpp::spline::SplineType::Steffen);\n  auto result2 =\n      quadpp::spline::Integrate(xs, ys, quadpp::spline::SplineType::Cubic);\n  auto result3 =\n      quadpp::spline::Integrate(xs, ys, quadpp::spline::SplineType::Akima);\n\n  std::cout << \"Integrating exp(-r) from 0 to ∞.\"\n            << \"\\n\";\n  std::cout << \"Using Steffen splines: \" << std::setprecision(10) << std::fixed\n            << result1 << \"\\n\";\n  std::cout << \"Using Cubic splines: \" << result2 << \"\\n\";\n  std::cout << \"Using Akima splines: \" << result3 << \"\\n\";\n}\n", "meta": {"hexsha": "11ee2ee6e60eaded21397b1a51cee4876112d94a", "size": 937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spline_test.cpp", "max_stars_repo_name": "e-eight/quadpp", "max_stars_repo_head_hexsha": "f3433b7744d78f8e74a16a601562743586a684ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spline_test.cpp", "max_issues_repo_name": "e-eight/quadpp", "max_issues_repo_head_hexsha": "f3433b7744d78f8e74a16a601562743586a684ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline_test.cpp", "max_forks_repo_name": "e-eight/quadpp", "max_forks_repo_head_hexsha": "f3433b7744d78f8e74a16a601562743586a684ca", "max_forks_repo_licenses": ["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.5588235294, "max_line_length": 79, "alphanum_fraction": 0.6093916756, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5677763290530603}}
{"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/** \\example blas2.cpp\n*\n*   In this tutorial the BLAS level 2 functionality in ViennaCL is demonstrated.\n*\n*   We start with including the required header files:\n**/\n\n// System headers\n#include <iostream>\n\n// uBLAS headers\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/vector_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n// ViennaCL headers\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n#include \"viennacl/linalg/prod.hpp\"       //generic matrix-vector product\n#include \"viennacl/linalg/norm_2.hpp\"     //generic l2-norm for vectors\n#include \"viennacl/linalg/lu.hpp\"         //LU substitution routines\n\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n\n// Make `boost::numeric::ublas` available under the shortcut `ublas`:\nusing namespace boost::numeric;\n\n/**\n* We do not need any auxiliary functions in this example, so let us start directly in main():\n**/\nint main()\n{\n  typedef float       ScalarType;\n\n  /**\n  * Set up some uBLAS vectors and a matrix.\n  * They will be later used for filling the ViennaCL objects with data.\n  **/\n  ublas::vector<ScalarType> rhs(12);\n  for (unsigned int i = 0; i < rhs.size(); ++i)\n    rhs(i) = random<ScalarType>();\n  ublas::vector<ScalarType> rhs2 = rhs;\n  ublas::vector<ScalarType> result = ublas::zero_vector<ScalarType>(10);\n  ublas::vector<ScalarType> result2 = result;\n  ublas::vector<ScalarType> rhs_trans = rhs;\n  rhs_trans.resize(result.size(), true);\n  ublas::vector<ScalarType> result_trans = ublas::zero_vector<ScalarType>(rhs.size());\n\n  ublas::matrix<ScalarType> matrix(result.size(),rhs.size());\n\n  /**\n  * Fill the uBLAS-matrix\n  **/\n  for (unsigned int i = 0; i < matrix.size1(); ++i)\n    for (unsigned int j = 0; j < matrix.size2(); ++j)\n      matrix(i,j) = random<ScalarType>();\n\n  /**\n  * Use some plain STL types:\n  **/\n  std::vector< ScalarType > stl_result(result.size());\n  std::vector< ScalarType > stl_rhs(rhs.size());\n  std::vector< std::vector<ScalarType> > stl_matrix(result.size());\n  for (unsigned int i=0; i < result.size(); ++i)\n  {\n    stl_matrix[i].resize(rhs.size());\n    for (unsigned int j = 0; j < matrix.size2(); ++j)\n    {\n      stl_rhs[j] = rhs[j];\n      stl_matrix[i][j] = matrix(i,j);\n    }\n  }\n\n  /**\n  * Set up some ViennaCL objects (initialized with zeros) and then copy data from the uBLAS objects.\n  **/\n  viennacl::vector<ScalarType> vcl_rhs(rhs.size());\n  viennacl::vector<ScalarType> vcl_result(result.size());\n  viennacl::matrix<ScalarType> vcl_matrix(result.size(), rhs.size());\n  viennacl::matrix<ScalarType> vcl_matrix2(result.size(), rhs.size());\n\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n  viennacl::copy(matrix, vcl_matrix);     //copy from ublas dense matrix type to ViennaCL type\n\n  /**\n  * Some basic matrix operations with ViennaCL are as follows:\n  **/\n  vcl_matrix2 = vcl_matrix;\n  vcl_matrix2 += vcl_matrix;\n  vcl_matrix2 -= vcl_matrix;\n  vcl_matrix2 = vcl_matrix2 + vcl_matrix;\n  vcl_matrix2 = vcl_matrix2 - vcl_matrix;\n\n  viennacl::scalar<ScalarType> vcl_3(3.0);\n  vcl_matrix2 *= ScalarType(2.0);\n  vcl_matrix2 /= ScalarType(2.0);\n  vcl_matrix2 *= vcl_3;\n  vcl_matrix2 /= vcl_3;\n\n  /**\n  * A matrix can be cleared directly:\n  **/\n  vcl_matrix.clear();\n\n  /**\n  * Other ways of data transfers between matrices in main memory and a ViennaCL matrix:\n  **/\n  viennacl::copy(stl_matrix, vcl_matrix); //alternative: copy from STL vector< vector<> > type to ViennaCL type\n\n  //for demonstration purposes (no effect):\n  viennacl::copy(vcl_matrix, matrix); //copy back from ViennaCL to ublas type.\n  viennacl::copy(vcl_matrix, stl_matrix); //copy back from ViennaCL to STL type.\n\n  /**\n  * <h2> Matrix-Vector Products </h2>\n  *\n  * Compute matrix-vector products\n  **/\n  std::cout << \"----- Matrix-Vector product -----\" << std::endl;\n  result = ublas::prod(matrix, rhs);                            //the ublas way\n  stl_result = viennacl::linalg::prod(stl_matrix, stl_rhs);     //using STL\n  vcl_result = viennacl::linalg::prod(vcl_matrix, vcl_rhs);     //the ViennaCL way\n\n  /**\n  * Compute transposed matrix-vector products\n  **/\n  std::cout << \"----- Transposed Matrix-Vector product -----\" << std::endl;\n  result_trans = prod(trans(matrix), rhs_trans);\n\n  viennacl::vector<ScalarType> vcl_rhs_trans(rhs_trans.size());\n  viennacl::vector<ScalarType> vcl_result_trans(result_trans.size());\n  viennacl::copy(rhs_trans.begin(), rhs_trans.end(), vcl_rhs_trans.begin());\n  vcl_result_trans = viennacl::linalg::prod(trans(vcl_matrix), vcl_rhs_trans);\n\n\n\n  /**\n  * <h2>Direct Solver</h2>\n  *\n  * In order to demonstrate the direct solvers, we first need to setup suitable square matrices.\n  * This is again achieved by running the setup on the CPU and then copy the data over to ViennaCL types:\n  **/\n  ublas::matrix<ScalarType> tri_matrix(10,10);\n  for (std::size_t i=0; i<tri_matrix.size1(); ++i)\n  {\n    for (std::size_t j=0; j<i; ++j)\n      tri_matrix(i,j) = 0.0;\n\n    for (std::size_t j=i; j<tri_matrix.size2(); ++j)\n      tri_matrix(i,j) = matrix(i,j);\n  }\n\n  viennacl::matrix<ScalarType> vcl_tri_matrix = viennacl::identity_matrix<ScalarType>(tri_matrix.size1());\n  viennacl::copy(tri_matrix, vcl_tri_matrix);\n\n  // Bring vectors to correct size:\n  rhs.resize(tri_matrix.size1(), true);\n  rhs2.resize(tri_matrix.size1(), true);\n  vcl_rhs.resize(tri_matrix.size1(), true);\n\n  viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n  vcl_result.resize(10);\n\n\n  /**\n  * Run a triangular solver on the upper triangular part of the matrix:\n  **/\n  std::cout << \"----- Upper Triangular solve -----\" << std::endl;\n  result = ublas::solve(tri_matrix, rhs, ublas::upper_tag());                                    //ublas\n  vcl_result = viennacl::linalg::solve(vcl_tri_matrix, vcl_rhs, viennacl::linalg::upper_tag());  //ViennaCL\n\n  /**\n  * Inplace variants of triangular solvers:\n  **/\n  ublas::inplace_solve(tri_matrix, rhs, ublas::upper_tag());                                //ublas\n  viennacl::linalg::inplace_solve(vcl_tri_matrix, vcl_rhs, viennacl::linalg::upper_tag());  //ViennaCL\n\n\n  /**\n  * Set up a full system for full solver using LU factorizations:\n  **/\n  std::cout << \"----- LU factorization -----\" << std::endl;\n  std::size_t lu_dim = 300;\n  ublas::matrix<ScalarType> square_matrix(lu_dim, lu_dim);\n  ublas::vector<ScalarType> lu_rhs(lu_dim);\n  viennacl::matrix<ScalarType> vcl_square_matrix(lu_dim, lu_dim);\n  viennacl::vector<ScalarType> vcl_lu_rhs(lu_dim);\n\n  for (std::size_t i=0; i<lu_dim; ++i)\n    for (std::size_t j=0; j<lu_dim; ++j)\n      square_matrix(i,j) = random<ScalarType>();\n\n  //put some more weight on diagonal elements:\n  for (std::size_t j=0; j<lu_dim; ++j)\n  {\n    square_matrix(j,j) += ScalarType(10.0);\n    lu_rhs(j) = random<ScalarType>();\n  }\n\n  viennacl::copy(square_matrix, vcl_square_matrix);\n  viennacl::copy(lu_rhs, vcl_lu_rhs);\n  viennacl::linalg::lu_factorize(vcl_square_matrix);\n  viennacl::linalg::lu_substitute(vcl_square_matrix, vcl_lu_rhs);\n  viennacl::copy(square_matrix, vcl_square_matrix);\n  viennacl::copy(lu_rhs, vcl_lu_rhs);\n\n\n  /**\n  * Full solver with Boost.uBLAS:\n  **/\n  ublas::lu_factorize(square_matrix);\n  ublas::inplace_solve (square_matrix, lu_rhs, ublas::unit_lower_tag ());\n  ublas::inplace_solve (square_matrix, lu_rhs, ublas::upper_tag ());\n\n\n  /**\n  * Full solver with ViennaCL:\n  **/\n  viennacl::linalg::lu_factorize(vcl_square_matrix);\n  viennacl::linalg::lu_substitute(vcl_square_matrix, vcl_lu_rhs);\n\n  /**\n  *  That's it.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "d98df7d2aa177c02ecab0502c6b23dda83a6e5a6", "size": 8772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/blas2.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/blas2.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/blas2.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": 33.6091954023, "max_line_length": 111, "alphanum_fraction": 0.6565207478, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.5677059448316333}}
{"text": "/*\n * ground_filter.cpp\n *\n * Created on\t: May 19, 2017\n * Author\t: Patiphon Narksri\t\t\t\t\t\n */\n#include <ros/ros.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <pcl_ros/point_cloud.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_types.h>\n#include <velodyne_pointcloud/point_types.h>\n#include <opencv/cv.h>\n\n#include <boost/lexical_cast.hpp> //U\n#include <boost/chrono.hpp> //U\n#include <iostream> //U\n\nenum Label\n{\n        GROUND = 0,\n        VERTICAL = 1,\n        UNKNOWN = 3\n};\n\nclass GroundFilter\n{\npublic:\n\t\n\tGroundFilter();\n\nprivate:\n\n\tros::NodeHandle n;\n        ros::Subscriber sub;\n\tros::Publisher vertical_points_pub;\n\tros::Publisher ground_points_pub;\n\n        std::string     point_topic;\n\tint \t\tsensor_model;\n\tdouble \t\tsensor_height;\n\tdouble \t\tmax_slope;\n\tdouble \t\tgap_thres;\n        bool            floor_removal; \n\tdouble \t\tradius_coeff_close;\n\tdouble\t\tradius_coeff_far;\n\n\tdouble \t\tpoint_distance;\n\tint \t\tmin_point;\n\n\tint \t\tvertical_res;\n\tint \t\thorizontal_res;\n\tdouble \t\tlimiting_ratio;\n\tcv::Mat \tindex_map;\n\tLabel \t\tclass_label[64];\n\tdouble \t\toptimal_radius[64];\n\n\t//These will be deleted\n\tint\t\toriginal_point;\n\tint\t\tremaining_point;\n\tint\t\tpoint_after_tf;\n\n\tboost::chrono::high_resolution_clock::time_point t1;\n\tboost::chrono::high_resolution_clock::time_point t2;\n\tboost::chrono::nanoseconds elap_time;\n\n\tvoid initLabelArray(int model);\n\tvoid initRadiusArray(double radius[], int model);\n\tvoid initDepthMap(int width);\n\tvoid publishPoint(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg,\n\t\t\t\tint index[], int &index_size, \n\t\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &topic);\n\n\n\tvoid velodyneCallback(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg);\n\tvoid groundSeparate(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg, \n\t\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &vertical_points, \n\t\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &ground_points);\n\n};\n\nGroundFilter::GroundFilter() : n(\"~\")\n{\n\n\tn.param<std::string>(\"point_topic\", point_topic, \"/points_raw\");\n\t//If it set to False it will publish the original PointCloud\n \tn.param(\"remove_floor\",  floor_removal,  true);\n\t//Can be selected between 16, 32 and 64 (Have never tested on 16 though)\n        n.param(\"sensor_model\", sensor_model, 64);\n\t//This is the height of Velodyne measured from center of Velodyne to ground\n        n.param(\"sensor_height\", sensor_height, 1.80);\n\t//Maximum allowable slope i.e., any surface steeper than this angle[deg] will not be removed\n        n.param(\"max_slope\", max_slope, 15.0);\n\n\t//These parameters have been tested to be the optimal values for this algorithm\n\t//Shouldn't have to be changed for normal use\n        n.param(\"min_point\", min_point, 2);\n\tn.param(\"gap_thres\", gap_thres, 0.15);\n\tn.param(\"radius_coeff_close\", radius_coeff_close, 0.2);\n\tn.param(\"radius_coeff_far\", radius_coeff_far, 0.7);\n\n\t//Number of laser rays in vertical direction\n\tvertical_res \t= 64;\n\t//Number of laser rays in horizontal direction (will be recalculated every rotation)\n\thorizontal_res \t= 2000;\n\t//Use tan instead of max_slope in degree for more efficient computation\n\tlimiting_ratio \t= tan(20.0*M_PI/180);\n\n\tvertical_res = sensor_model;\n\tinitLabelArray(sensor_model);\n\tlimiting_ratio = tan(max_slope*M_PI/180);\n\tinitRadiusArray(optimal_radius, sensor_model); \t\n       \n\tsub = n.subscribe(point_topic, 10, &GroundFilter::velodyneCallback, this);\n        vertical_points_pub = n.advertise<sensor_msgs::PointCloud2>(\"/points_lanes\", 10);\n        ground_points_pub = n.advertise<sensor_msgs::PointCloud2>(\"/points_ground\", 10);\n\n}\n//This loop calculate the expected spaced between consecutive rings\nvoid GroundFilter::initRadiusArray(double radius[], int model)\n{\n        if (model == 32)\n        {\n                double start_angle = 92.0/3;\n                double angle_res = 4.0/3;\n                for (int i = 0; i < model; i++)\n                {\n                        if (i == 0)\n                        {\n                                radius[i] = 999999;\n                        } else {\n                                double theta = start_angle - i*angle_res;\n                                theta = theta*M_PI/180.0;\n                                radius[i] = sensor_height*(1.0/tan(theta) - 1.0/tan(theta + angle_res*M_PI/180.0)); \n                        }\n\n\t\t\tif (i <= 12)\n\t\t\t{\n\t\t\t\tradius[i] = radius_coeff_close*radius[i];\n\t\t\t} else if (i <= 20) {\n\t\t\t\tradius[i] = radius_coeff_far*radius[i];\n\t\t\t} else {\t\n\t\t\t\tradius[i] = radius[20];\n\t\t\t}\n                }\n        } else {\n                for (int i = 0; i < model; i++)\n                {\n                        if (i < 32)\n                        {\n                                double start_angle = 73.0/3;\n                                double angle_res = 1.0/2;\n                                if (i == 0)\n                                {\n                                        radius[i] = 999999;\n                                } else {\n                                        double theta = start_angle - i*angle_res;\n                                        theta = theta*M_PI/180.0;\n                                        radius[i] = sensor_height*(1.0/tan(theta) - 1.0/tan(theta + angle_res*M_PI/180.0)); \n                                }\n                        } else {\n                                double start_angle = 25.0/3;\n                                double angle_res = 1.0/3;\n                                if (i == 32)\n                                {\n                                        double theta = start_angle;\n                                        theta = theta*M_PI/180.0;\n                                        radius[i] = sensor_height*(1.0/tan(theta) - 1.0/tan(theta + 0.5*M_PI/180.0)); \n                                } else {\n                                        double theta = start_angle - (i-32)*angle_res;\n                                        theta = theta*M_PI/180.0;\n                                        radius[i] = sensor_height*(1.0/tan(theta) - 1.0/tan(theta + angle_res*M_PI/180.0)); \n                                }\n                        }\n\t\t\t\n\t\t\tif (i <= 15) \n\t\t\t{\n\t\t\t\tradius[i] = radius_coeff_close*radius[i];\n\t\t\t} else if (i <= 40) {\n\t\t\t\tradius[i] = radius_coeff_far*radius[i];\n\t\t\t} else {\n\t\t\t\tradius[i] = radius[40];\n\t\t\t}\n                }\n        }       \n}\n\n//Create an enum array to store the current status of each point in the same bearing angle\nvoid GroundFilter::initLabelArray(int model)\n{\n\tfor(int a = 0; a < vertical_res; a++)\n\t{\n\t\tclass_label[a] = UNKNOWN;\n\t}\n}\n\n//Create a depth map that has a size of vertical_res x horizontal_res\nvoid GroundFilter::initDepthMap(int width)\n{\n\tconst int mOne = -1;\n\tindex_map = cv::Mat_<int>(vertical_res, width, mOne);\n}\n\n//Used for publish the separated PointCloud to a defined topic\nvoid GroundFilter::publishPoint(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg,\n\t\t\t\tint index[], int &index_size, \n\t\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &topic)\n{\n\n\tvelodyne_pointcloud::PointXYZIR point;\n\tfor (int i = 0; i < index_size; i++)\n\t{\n\t\tpoint.x = msg->points[index[i]].x;\n\t\tpoint.y = msg->points[index[i]].y;\n\t\tpoint.z = msg->points[index[i]].z;\n\t\tpoint.intensity = msg->points[index[i]].intensity;\n\t\tpoint.ring = msg->points[index[i]].ring;\n\t\ttopic.push_back(point);\n\n\t\tremaining_point++;\n\t}\n\tindex_size = 0;\t\n\n}\n\n//Main calculation is done in this function\nvoid GroundFilter::groundSeparate(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg, \n\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &vertical_points, \n\t\t\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> &ground_points)\n{\n\n        velodyne_pointcloud::PointXYZIR point;\n\t\n        horizontal_res = int(msg->points.size()*1.8 / vertical_res);\n        initDepthMap(horizontal_res);\n\n\toriginal_point = msg->points.size();\n\tremaining_point = 0;\n\tpoint_after_tf = 0;\t\n\n\t//This conversion has some losses\n\t//Convert coordinate of each point from Cartesian to Spherical (XYZ -> DepthMap)\n        for (int i = 0; i < msg->points.size(); i++)\n        {\n                double u = atan2(msg->points[i].y,msg->points[i].x) * 180/M_PI;\n                if (u < 0) u = 360 + u;  \n                int column = horizontal_res - (int)((double)horizontal_res * u / 360.0) - 1;   \n                int row = vertical_res - 1 - msg->points[i].ring;\n\t\tindex_map.at<int>(row, column) = i;\n        }\n\n\t//Iterate through each bearing angle (each horizontal angle)\n\tfor (int i = 0; i < horizontal_res; i++)\n        {\n                Label point_class[vertical_res];\n\t\tint unknown_index[vertical_res];\n\t\tint point_index[vertical_res];\n\t\tint unknown_index_size = 0;\n\t\tint point_index_size = 0;\n\t\tdouble z_ref = 0;\n\t\tdouble r_ref = 0;\n\t\t//Initialize the enum array to be UKNOWN in every elements before calculation\n\t\t//Of each bearing angle\n\t\tstd::copy(class_label, class_label + vertical_res, point_class); \n\n\t\t//Iterate through each vertical angle (each laser ray) starting from lowest ray\n\t\tfor (int j = vertical_res - 1; j >= 0; j--)\n                {\n\t\t\t//If the point has already been processed and already classified\n\t\t\t//It will not be processed again\n                        if (index_map.at<int>(j,i) > -1 && point_class[j] == UNKNOWN)\n                        {\n\t\t\t\tpoint_after_tf++;\n\t\t\t\tdouble x0 = msg->points[index_map.at<int>(j, i)].x;\n\t\t\t\tdouble y0 = msg->points[index_map.at<int>(j, i)].y;\n\t\t\t\tdouble z0 = msg->points[index_map.at<int>(j, i)].z;\n\t\t\t\tdouble r0 = sqrt(x0*x0 + y0*y0);\n\t\t\t\tdouble r_diff = r0 - r_ref;\n\t\t\t\tdouble z_diff = fabs(z0 - z_ref);\n\t\t\t\tdouble pair_angle = z_diff/r_diff;\n\t\t\t\t//Check if the angle between the current and the previous point is less than a defined maximum_slope\n\t\t\t\t//If the angle is less than maximum_slope, add the current point to \"Candidate group\"\n\t\t\t\tif (((pair_angle > 0 && pair_angle < limiting_ratio) && z_diff < gap_thres) || point_index_size == 0)\n\t\t\t\t{\n\t\t\t\t\tr_ref = r0;\n\t\t\t\t\tz_ref = z0;\n\t\t\t\t\tpoint_index[point_index_size] = j;\n\t\t\t\t\tpoint_index_size++;\n\t\t\t\t} else {\n\t\t\t\t\t//If the angle exceeds the maximum slope\n\t\t\t\t\t//Check number of point in \"Candidate group\", if exceeds the minimum_point threshold\n\t\t\t\t\t//Publish them as ground points\n\t\t\t\t\tif (point_index_size > min_point)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int m = 0; m < point_index_size; m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tint index = index_map.at<int>(point_index[m],i);\n\t\t\t\t\t\t\t\tpoint.x = msg->points[index].x;\n\t\t\t\t\t\t\t\tpoint.y = msg->points[index].y;\n\t\t\t\t\t\t\t\tpoint.z = msg->points[index].z;\n\t\t\t\t\t\t\t\tpoint.intensity = msg->points[index].intensity;\n\t\t\t\t\t\t\t\tpoint.ring = msg->points[index].ring;\n\t\t\t\t\t\t\t\tground_points.push_back(point);\n\t\t\t\t\t\t\t\tpoint_class[point_index[m]] = GROUND;\n\n\t\t\t\t\t\t\t\tremaining_point++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpoint_index_size = 0;\n\t\t\t\t\t//If the number of point in \"Candidate group\" is less than the threshold, continue the calculation\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (int m = 0; m < point_index_size; m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint index = index_map.at<int>(point_index[m],i);\n\t\t\t\t\t\t\tpoint.x = msg->points[index].x;\n\t\t\t\t\t\t\tpoint.y = msg->points[index].y;\n\t\t\t\t\t\t\tpoint.z = msg->points[index].z;\n\t\t\t\t\t\t\tpoint.intensity = msg->points[index].intensity;\n\t\t\t\t\t\t\tpoint.ring = msg->points[index].ring;\n\t\t\t\t\t\t\tunknown_index[unknown_index_size] = index;\n\t\t\t\t\t\t\tunknown_index_size++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpoint_index_size = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tr_ref = r0;\n\t\t\t\t\tz_ref = z0;\n\t\t\t\t\tpoint_index[point_index_size] = j;\n\t\t\t\t\tpoint_index_size++;\n\t\t\t\t}\n  \t\t\t}\n\t\t\t//If the highest ray is reached\n                        if (j == 0)\n                        {\n\t\t\t\t//First, check if the \"Candidate group\" contain any point, if so classify them using\n\t\t\t\t//the same criteria as above\n\t\t\t\tif (point_index_size != 0)\n\t\t\t\t{\n\t\t\t\t\tif (point_index_size > min_point)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int m = 0; m < point_index_size; m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tint index = index_map.at<int>(point_index[m],i);\n\t\t\t\t\t\t\t\tpoint.x = msg->points[index].x;\n\t\t\t\t\t\t\t\tpoint.y = msg->points[index].y;\n\t\t\t\t\t\t\t\tpoint.z = msg->points[index].z;\n\t\t\t\t\t\t\t\tpoint.intensity = msg->points[index].intensity;\n\t\t\t\t\t\t\t\tpoint.ring = msg->points[index].ring;\n\t\t\t\t\t\t\t\tground_points.push_back(point);\n\t\t\t\t\t\t\t\tpoint_class[point_index[m]] = GROUND;\n\n\t\t\t\t\t\t\t\tremaining_point++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpoint_index_size = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (int m = 0; m < point_index_size; m++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint index = index_map.at<int>(point_index[m],i);\n\t\t\t\t\t\t\tpoint.x = msg->points[index].x;\n\t\t\t\t\t\t\tpoint.y = msg->points[index].y;\n\t\t\t\t\t\t\tpoint.z = msg->points[index].z;\n\t\t\t\t\t\t\tpoint.intensity = msg->points[index].intensity;\n\t\t\t\t\t\t\tpoint.ring = msg->points[index].ring;\n\t\t\t\t\t\t\tunknown_index[unknown_index_size] = index;\n\t\t\t\t\t\t\tunknown_index_size++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpoint_index_size = 0;\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t\t//Lastly, the remaining unknown points are checked using different approach\n\t\t\t\t//Check if the radial distance between two consecutive points is less than \n\t\t\t\t//point_distance threshold, if so classify them as vertical\n\t\t\t\tdouble centroid = 0;\n\t\t\t\tint centroid_ring = 0;\n\t\t\t\tint cluster_index[vertical_res];\n\t\t\t\tint cluster_index_size = 0;\n\t\t\t\tfor (int m = unknown_index_size - 1; m >= 0; m--)\n\t\t\t\t{\n\t\t\t\t\tdouble x0 = msg->points[unknown_index[m]].x;\n\t\t\t\t\tdouble y0 = msg->points[unknown_index[m]].y;\n\t\t\t\t\tdouble r0 = sqrt(x0*x0 + y0*y0);\n\t\t\t\t\tdouble r_diff = fabs(r0 - centroid);\n\t\t\t\t\tpoint_distance = optimal_radius[centroid_ring];\n\t\t\t\t\tif ((r_diff < point_distance) || cluster_index_size == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tcluster_index[cluster_index_size] = unknown_index[m];\n\t\t\t\t\t\tcluster_index_size++;\n\t\t\t\t\t\tcentroid = r0;\n\t\t\t\t\t\tcentroid_ring = msg->points[unknown_index[m]].ring;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(cluster_index_size > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpublishPoint(msg, cluster_index\t, cluster_index_size, vertical_points);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpublishPoint(msg, cluster_index, cluster_index_size, ground_points);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcluster_index[cluster_index_size] = unknown_index[m];\n\t\t\t\t\t\tcluster_index_size++;\n\t\t\t\t\t\tcentroid = r0;\n\t\t\t\t\t\tcentroid_ring = msg->points[unknown_index[m]].ring;\n\t\t\t\t\t}\n\t\t\t\t\tif (m == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(cluster_index_size > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpublishPoint(msg, cluster_index, cluster_index_size, vertical_points);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpublishPoint(msg, cluster_index, cluster_index_size, ground_points);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n                        }\n                }\n\t}\n}\n\nvoid GroundFilter::velodyneCallback(const pcl::PointCloud<velodyne_pointcloud::PointXYZIR>::ConstPtr &msg)\n{\n\tt1 = boost::chrono::high_resolution_clock::now();\n\t\n\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> vertical_points;\n\tpcl::PointCloud<velodyne_pointcloud::PointXYZIR> ground_points;\n\tvertical_points.header = msg->header;\n        ground_points.header = msg->header;\n        vertical_points.clear();\n        ground_points.clear();\n\n\tgroundSeparate(msg, vertical_points, ground_points);\n\n\tif (!floor_removal)\n\t{\n\t\tvertical_points = *msg;\n\t} \n\t\n\tvertical_points_pub.publish(vertical_points);\n        ground_points_pub.publish(ground_points);\n\n\tt2 = boost::chrono::high_resolution_clock::now();\n        elap_time = (boost::chrono::duration_cast<boost::chrono::nanoseconds>(t2-t1));\n        std::cout << \"Computational time for each frame is \" << elap_time << \" for total \" << remaining_point << \" points\" << std::endl;\n        //std::cout << \"Original point is \" << original_point << \" The remaining point is \" << remaining_point << \n\t//\" Lost point is \" << original_point - remaining_point << \" Point after transform \" << point_after_tf<<\n\t//\" Real missing point is \" << point_after_tf - remaining_point  << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n\n        ros::init(argc, argv, \"ground_filter\");\n\tGroundFilter node;\n        ros::spin();\n\n\treturn 0;\n\n}\n", "meta": {"hexsha": "2f86d8d149ac0db6a028477e1f4218649fbc6308", "size": 15743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ground_filter.cpp", "max_stars_repo_name": "n-patiphon/ground_filter", "max_stars_repo_head_hexsha": "a4d74c4a2e95228ac5b67804d9c847d79ec7b789", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-07-26T00:48:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-18T06:49:22.000Z", "max_issues_repo_path": "src/ground_filter.cpp", "max_issues_repo_name": "n-patiphon/ground_filter", "max_issues_repo_head_hexsha": "a4d74c4a2e95228ac5b67804d9c847d79ec7b789", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ground_filter.cpp", "max_forks_repo_name": "n-patiphon/ground_filter", "max_forks_repo_head_hexsha": "a4d74c4a2e95228ac5b67804d9c847d79ec7b789", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-09-14T02:42:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:28:18.000Z", "avg_line_length": 34.3733624454, "max_line_length": 136, "alphanum_fraction": 0.6031887188, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5674624895635427}}
{"text": "#include <Eigen/Dense>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/features/normal_3d.h>\n#include \"principal_curvatures_can.hpp\"\n\n#define R 2\n#define r 1\n#define N 10000\n#define THETA_SCALE (M_PI / 2)\n#define THETA_OFFSET (M_PI / 2)\n#define PHI_SCALE (M_PI / 4)\n#define SEARCH_RADIUS 0.1\n\nint main(void) {\n  Eigen::VectorXf theta = THETA_SCALE * Eigen::VectorXf::Random(N) + Eigen::VectorXf::Constant(N, THETA_OFFSET);\n  Eigen::VectorXf phi = PHI_SCALE * Eigen::VectorXf::Random(N);\n  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>());\n  for(int i=0;i<N;i++) {\n    pcl::PointXYZ point;\n    point.x = (R + r * cos(theta(i))) * cos(phi(i));\n    point.y = (R + r * cos(theta(i))) * sin(phi(i));\n    point.z = r * sin(theta(i));\n    cloud->points.push_back(point);\n  }\n  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>());\n  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimation;\n  normal_estimation.setInputCloud(cloud);\n  normal_estimation.setSearchMethod(tree);\n  normal_estimation.setRadiusSearch(SEARCH_RADIUS);\n  normal_estimation.setViewPoint(0, 0, std::numeric_limits<float>::infinity());\n  pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>());\n  normal_estimation.compute(*normals);\n  PrincipalCurvaturesEstimationCAN curvature_estimation;\n  curvature_estimation.setInputCloud(cloud);\n  curvature_estimation.setInputNormals(normals);\n  curvature_estimation.setSearchMethod(tree);\n  curvature_estimation.setRadiusSearch(SEARCH_RADIUS);\n  pcl::PointCloud<pcl::PrincipalCurvatures>::Ptr curvatures (new pcl::PointCloud<pcl::PrincipalCurvatures>());\n  curvature_estimation.compute(*curvatures);\n  for(int i=0;i<N;i++) {\n    pcl::PrincipalCurvatures curve_point = curvatures.get()->points[i];\n    std::cout\n      << theta(i) << \" \"\n      << phi(i) << \" \"\n      << curve_point.pc1 * curve_point.pc2 << \" \"\n      << cos(theta(i)) / (r * (R + r * cos(theta(i))))\n      << std::endl;\n  }\n}\n", "meta": {"hexsha": "e9a6448436553be6785b08970da57c12d13bf137", "size": 2022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example.cpp", "max_stars_repo_name": "CameronDevine/PCL-Principal-Curvature-CAN", "max_stars_repo_head_hexsha": "3ea82bee4a685690605c9da23c87c90cd2f6d17e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/example.cpp", "max_issues_repo_name": "CameronDevine/PCL-Principal-Curvature-CAN", "max_issues_repo_head_hexsha": "3ea82bee4a685690605c9da23c87c90cd2f6d17e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/example.cpp", "max_forks_repo_name": "CameronDevine/PCL-Principal-Curvature-CAN", "max_forks_repo_head_hexsha": "3ea82bee4a685690605c9da23c87c90cd2f6d17e", "max_forks_repo_licenses": ["BSD-3-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.6470588235, "max_line_length": 112, "alphanum_fraction": 0.6988130564, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5674426383275669}}
{"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_POW_EXPANDER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_POW_EXPANDER_HPP_INCLUDED\n\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/sqr.hpp>\nnamespace boost { namespace simd { namespace ext\n{\n\n  template<std::uintmax_t Exp, std::uintmax_t Odd = Exp%2>\n  struct pow_expander;\n\n  template<std::uintmax_t Exp>\n  struct pow_expander<Exp, 0ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call( A0 const& a0) BOOST_NOEXCEPT\n    {\n      return pow_expander<Exp/2>::call(sqr(a0));\n    }\n  };\n\n  template<std::uintmax_t Exp>\n  struct pow_expander<Exp, 1ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call( A0 const& a0) BOOST_NOEXCEPT\n    {\n      return a0*pow_expander<Exp/2>::call(sqr(a0));\n    }\n  };\n\n  template<>\n  struct pow_expander<0ULL, 0ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call( A0 const&) BOOST_NOEXCEPT\n    {\n      return One<A0>();\n    }\n  };\n\n  template<>\n  struct pow_expander<0ULL, 1ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call( A0 const&) BOOST_NOEXCEPT\n    {\n      return One<A0>();\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "cb3e3756aaf61ff9cfb60f15c30c9cade6afd4de", "size": 1576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/generic/pow_expander.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/pow_expander.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/pow_expander.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 24.625, "max_line_length": 100, "alphanum_fraction": 0.6053299492, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5674426110614811}}
{"text": "/*\n * dcdc.cc\n *\n *  created on: 18.04.2016\n *      author: rungger\n */\n\n/*\n * demonstration of the boost ode solver usage\n *\n */\n\n#include <array>\n#include <iostream>\n\n#include \"cuddObj.hh\"\n\n#include \"SymbolicSet.hh\"\n#include \"SymbolicModelGrowthBound.hh\"\n\n#include \"TicToc.hh\"\n#include <boost/numeric/odeint.hpp>\n\n\n/* state space dim */\n#define sDIM 2\n#define iDIM 1\n\n/* data types for the ode solver */\ntypedef std::array<double,2> state_type;\ntypedef std::array<double,1> input_type;\n\ntypedef boost::numeric::odeint::runge_kutta_dopri5< state_type > stepper_type;\n\n\n/* we integrate the dcdc ode by 0.5 sec (the result is stored in x)  */\nauto  dcdc_post = [](state_type &x, input_type &u) -> void {\n\n  /* the ode describing the system */\n  auto  system_ode = [&](const state_type &x, state_type &dxdt, const double) -> void {\n\n    const double r0=1.0 ; \n    const double vs = 1.0 ;\n    const double rl = 0.05 ;\n    const double rc = rl / 10 ;\n    const double xl = 3.0 ;\n    const double xc = 70.0 ;\n\n    const double b[2]={vs/xl, 0};\n\n    double a[2][2];\n    if(u[0]==1) {\n      a[0][0] = -rl / xl;\n      a[0][1] = 0;\n      a[1][0] = 0;\n      a[1][1] = (-1 / xc) * (1 / (r0 + rc));\n    } else {\n      a[0][0] = (-1 / xl) * (rl + ((r0 * rc) / (r0 + rc))) ;\n      a[0][1] =  ((-1 / xl) * (r0 / (r0 + rc))) / 5 ;\n      a[1][0] = 5 * (r0 / (r0 + rc)) * (1 / xc);\n      a[1][1] =(-1 / xc) * (1 / (r0 + rc)) ;\n    }\n\n    dxdt[0] = a[0][0]*x[0]+a[0][1]*x[1] + b[0];\n    dxdt[1] = a[1][0]*x[0]+a[1][1]*x[1] + b[1];\n\n  };\n  boost::numeric::odeint::integrate_adaptive(make_controlled(1E-12 ,1E-12,stepper_type()),system_ode,x,0.0,0.5,0.5);\n};\n\n/* computation of the growth bound (the result is stored in r)  */\nauto radius_post = [](state_type &r, input_type &u) -> void {\n\n  /* the ode to determine the radius of the cell which over-approximates the\n   * attainable set see: http://arxiv.org/abs/1503.03715v1 */\n  auto growth_bound_ode = [&](const state_type &r, state_type &drdt, const double t) {\n    /* for the dcdc boost converter the growth bound is simply given by the metzler matrix of the system matrices */ \n    const double r0=1.0 ; \n    const double rl = 0.05 ;\n    const double rc = rl / 10 ;\n    const double xl = 3.0 ;\n    const double xc = 70.0 ;\n\n    double a[2][2];\n    if(u[0]==1) {\n      a[0][0] = -rl / xl;\n      a[0][1] = 0;\n      a[1][0] = 0;\n      a[1][1] = (-1 / xc) * (1 / (r0 + rc));\n    } else {\n      a[0][0] = (-1 / xl) * (rl + ((r0 * rc) / (r0 + rc))) ;\n      a[0][1] =  ((1 / xl) * (r0 / (r0 + rc))) / 5 ;\n      a[1][0] = 5 * (r0 / (r0 + rc)) * (1 / xc);\n      a[1][1] =(-1 / xc) * (1 / (r0 + rc)) ;\n    }\n\n    drdt[0] = a[0][0]*r[0]+a[0][1]*r[1];\n    drdt[1] = a[1][0]*r[0]+a[1][1]*r[1];\n  };\n\n  boost::numeric::odeint::integrate_adaptive(make_controlled(1E-12,1E-12,stepper_type()),growth_bound_ode,r,0.0,0.5,0.5);\n};\n\n\nint main() {\n  /* to measure time */\n  TicToc tt;\n  /* there is one unique manager to organize the bdd variables */\n  Cudd mgr;\n\n  /****************************************************************************/\n  /* construct SymbolicSet for the state space */\n  /****************************************************************************/\n  /* setup the workspace of the synthesis problem and the uniform grid */\n  /* lower bounds of the hyper rectangle */\n  double lb[sDIM]={1.15,5.45};  \n  /* upper bounds of the hyper rectangle */\n  double ub[sDIM]={1.55,5.85}; \n  /* grid node distance diameter */\n  double eta[sDIM]={2/4e3,2/4e3};   \n  scots::SymbolicSet ss(mgr,sDIM,lb,ub,eta);\n  ss.addGridPoints();\n\n  /****************************************************************************/\n  /* construct SymbolicSet for the input space */\n  /****************************************************************************/\n  double ilb[iDIM]={1};  \n  double iub[iDIM]={2}; \n  double ieta[iDIM]={1};   \n  scots::SymbolicSet is(mgr,iDIM,ilb,iub,ieta);\n  is.addGridPoints();\n\n  /****************************************************************************/\n  /* setup class for symbolic model computation */\n  /****************************************************************************/\n  /* create SymbolicSet for the post domain postX in preX x U x postX\n   * by coping preX and assigning new BDD IDs */\n  scots::SymbolicSet sspost(ss,1);\n  scots::SymbolicModelGrowthBound<state_type,input_type> abs(&ss, &is, &sspost);\n  /* compute the transition relation */\n  tt.tic();\n  abs.computeTransitionRelation(dcdc_post, radius_post);\n  std::cout << std::endl;\n  tt.toc();\n  /* get the number of elements in the transition relation */\n  std::cout << std::endl << \"Number of elements in the transition relation: \" << abs.getSize() << std::endl;\n\n  /* get SymbolicSet containing the transition relation with domain X x U x X */\n  scots::SymbolicSet tr=abs.getTransitionRelation();\n  /* write SymbolicSet to file */\n  tr.writeToFile(\"dcdc_abs.bdd\");\n\n  /* read SymbolicSet containing the transition relation from file */\n  scots::SymbolicSet trset(mgr,\"dcdc_abs.bdd\");\n\n\n\n  return 1;\n}\n", "meta": {"hexsha": "c385581ad404e05a855c7650906093840df5c444", "size": 5025, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/bdd/boostsolver/dcdc.cc", "max_stars_repo_name": "YunjunBai/scots_negotiation", "max_stars_repo_head_hexsha": "074af778db12087644de641a76b354cf9d3f6e7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/bdd/boostsolver/dcdc.cc", "max_issues_repo_name": "YunjunBai/scots_negotiation", "max_issues_repo_head_hexsha": "074af778db12087644de641a76b354cf9d3f6e7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/bdd/boostsolver/dcdc.cc", "max_forks_repo_name": "YunjunBai/scots_negotiation", "max_forks_repo_head_hexsha": "074af778db12087644de641a76b354cf9d3f6e7b", "max_forks_repo_licenses": ["BSD-3-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.40625, "max_line_length": 121, "alphanum_fraction": 0.5373134328, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.567442611061481}}
{"text": "#include \"incidencematrices.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <array>\n#include <memory>\n\nnamespace IncidenceMatrices {\n\n/** @brief Create the mesh consisting of a triangle and quadrilateral\n *         from the exercise sheet.\n * @return Shared pointer to the hybrid2d mesh.\n */\nstd::shared_ptr<lf::mesh::Mesh> createDemoMesh() {\n  // builder for a hybrid mesh in a world of dimension 2\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // Add points\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 0});    // (0)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 0});    // (1)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{1, 1});    // (2)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0, 1});    // (3)\n  mesh_factory_ptr->AddPoint(Eigen::Vector2d{0.5, 1});  // (4)\n\n  // Add the triangle\n  // First set the coordinates of its nodes:\n  Eigen::MatrixXd nodesOfTria(2, 3);\n  nodesOfTria << 1, 1, 0.5, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kTria(),  // we want a triangle\n      std::array<lf::mesh::Mesh::size_type, 3>{\n          {1, 2, 4}},  // indices of the nodes\n      std::make_unique<lf::geometry::TriaO1>(nodesOfTria));  // node coords\n\n  // Add the quadrilateral\n  Eigen::MatrixXd nodesOfQuad(2, 4);\n  nodesOfQuad << 0, 1, 0.5, 0, 0, 0, 1, 1;\n  mesh_factory_ptr->AddEntity(\n      lf::base::RefEl::kQuad(),\n      std::array<lf::mesh::Mesh::size_type, 4>{{0, 1, 4, 3}},\n      std::make_unique<lf::geometry::QuadO1>(nodesOfQuad));\n\n  std::shared_ptr<lf::mesh::Mesh> demoMesh_p = mesh_factory_ptr->Build();\n\n  return demoMesh_p;\n}\n\n/** @brief Compute the edge-vertex incidence matrix G for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The edge-vertex incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix<int> computeEdgeVertexIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store edge-vertex incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> G;\n\n  //====================\n\n\n  // Get number of edges: codim = 1\n  // Get number of nodes: codim = 0\n  const lf::mesh::Mesh::size_type numEdges = mesh.NumEntities(1),\n                                  numNodes = mesh.NumEntities(2);\n\n  // We know, G has exactly 2 non-zero entries per row.\n  G = Eigen::SparseMatrix<int, Eigen::RowMajor> (numEdges, numNodes);\n  G.reserve(Eigen::VectorXi::Constant(numEdges, 2)); //size=numEdges, value=2\n  \n  // 1. Iterate over alledges\n  // 2. Check index of nodes which are endpoints of the edges\n  // ! We cannot iterate ver vertices. LehrFem++ does not allow to visit !\n  // ! edges adjacent to a vertex.                                       !\n\n  for ( const lf::mesh::Entity *edge : mesh.Entities(1) ) {\n    // Get index of this edge\n    lf::mesh::Mesh::size_type edgeIdx = mesh.Index(*edge);\n\n    // Get nodes and their indices.\n    // ! Now codim(nodes)=1 - because it's a relative codim !\n    // ! Seen from the edge, a node has codim 1 !\n\n    auto nodes = edge->SubEntities(1); // ! Relativ Codim !\n    lf::mesh::Mesh::size_type firstNodeIdx = mesh.Index(*nodes[0]);\n    lf::mesh::Mesh::size_type lastNodeIdx = mesh.Index(*nodes[1]);\n\n    // Add matrix entries to G\n    G.coeffRef(edgeIdx, firstNodeIdx) = 1.0;\n    G.coeffRef(edgeIdx, lastNodeIdx) = -1.0;\n  }\n\n  //====================\n\n  return G;\n}\n/* SAM_LISTING_END_1 */\n\n/** @brief Compute the cell-edge incidence matrix D for a given mesh\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *        such as lf::mesh::hybrid2d::Mesh)\n * @return The cell-edge incidence matrix as Eigen::SparseMatrix<int>\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::SparseMatrix<int> computeCellEdgeIncidenceMatrix(\n    const lf::mesh::Mesh &mesh) {\n  // Store cell-edge incidence matrix here\n  Eigen::SparseMatrix<int, Eigen::RowMajor> D;\n\n  //====================\n\n  // Get number of cells and edges\n  const lf::mesh::Mesh::size_type numCells = mesh.NumEntities(0),\n                                  numEdges = mesh.NumEntities(1);\n\n  // Sparse init. of D. D has at most 4 nnz-entries per row.\n  D = Eigen::SparseMatrix<int, Eigen::RowMajor> (numCells, numEdges);\n  D.reserve( Eigen::VectorXi::Constant(numCells, 4) );\n\n  // Loop over all cells.\n  for ( const lf::mesh::Entity *cell : mesh.Entities(0) ) {\n    // Get cell index\n    lf::mesh::Mesh::size_type cellIdx = mesh.Index(*cell);\n\n    // Get edges of current cell\n    auto edges = cell->SubEntities(1);\n\n    // Check orientation of all cells\n    auto edgeOrientations = cell->RelativeOrientations();\n\n    // Iterate over both and add to D\n    auto edgeIt = edges.begin();\n    auto orntIt = edgeOrientations.begin();\n\n    // Fill D by comparing the orientation of the edges of the current cell\n    for(; edgeIt != edges.end() && orntIt != edgeOrientations.end();\n        ++edgeIt, ++orntIt) {\n      lf::mesh::Mesh::size_type edgeIdx = mesh.Index(**edgeIt);\n      D.coeffRef(cellIdx, edgeIdx) += lf::mesh::to_sign(*orntIt);\n    }\n  }\n\n  //====================\n\n  return D;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief For a given mesh test if the product of cell-edge and edge-vertex\n *        incidence matrix is zero: D*G == 0?\n * @param mesh The input mesh of type lf::mesh::Mesh (or of derived type,\n *             such as lf::mesh::hybrid2d::Mesh)\n * @return true, if the product is zero and false otherwise\n */\n/* SAM_LISTING_BEGIN_3 */\nbool testZeroIncidenceMatrixProduct(const lf::mesh::Mesh &mesh) {\n  bool isZero = false;\n\n  //====================\n  Eigen::SparseMatrix<int> G = computeEdgeVertexIncidenceMatrix(mesh);\n  Eigen::SparseMatrix<int> D = computeCellEdgeIncidenceMatrix(mesh);\n\n  isZero = ( (D*G).norm() == 0);\n\n  //====================\n  return isZero;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace IncidenceMatrices\n", "meta": {"hexsha": "aa03c22d06f449cd33c037c48f498df4d1c410cb", "size": 6054, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/IncidenceMatrices/mysolution/incidencematrices.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/IncidenceMatrices/mysolution/incidencematrices.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/IncidenceMatrices/mysolution/incidencematrices.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": 34.2033898305, "max_line_length": 77, "alphanum_fraction": 0.64271556, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.5674070348015886}}
{"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_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/detail/precise_math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Adaptive precision predicate to check at which side of a segment a point lies:\n    left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation (numeric_limits<ct>::epsilon() and numeric_limits<ct>::digits must be supported for calculation type ct)\n\\tparam robustness Number that determines maximum precision. Values from 0 to 2 may make the calculation terminate faster for inputs that may require higher precision to ensure correctness.\n\\details This predicate determines at which side of a segment a point lies using an algorithm that is adapted from orient2d as described in \"Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates\" by Jonathan Richard Shewchuk ( https://dl.acm.org/citation.cfm?doid=237218.237337 ). More information and copies of the paper can also be found at https://www.cs.cmu.edu/~quake/robust.html . It is designed to be adaptive in the sense that it should be fast for inputs that lead to correct results with plain float operations but robust for inputs that require higher precision arithmetics.\n */\ntemplate\n<\n    typename CalculationType = void,\n    int robustness = 3\n>\nstruct side_robust\n{\npublic:\n    //! \\brief Computes double the signed area of the CCW triangle p1, p2, p\n    template\n    <\n        typename CoordinateType,\n        typename PromotedType,\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline PromotedType side_value(P1 const& p1, P2 const& p2,\n        P const& p)\n    {\n        std::array<PromotedType, 2> pa {{ get<0>(p1), get<1>(p1) }};\n        std::array<PromotedType, 2> pb {{ get<0>(p2), get<1>(p2) }};\n        std::array<PromotedType, 2> pc {{ get<0>(p), get<1>(p) }};\n        return ::boost::geometry::detail::precise_math::orient2d\n            <PromotedType, robustness>(pa, pb, pc);\n    }\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename coordinate_type<P1>::type coordinate_type1;\n        typedef typename coordinate_type<P2>::type coordinate_type2;\n        typedef typename coordinate_type<P>::type coordinate_type3;\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                                coordinate_type1, coordinate_type2\n                            >::type,\n                        coordinate_type3\n                    >::type,\n                CalculationType\n            >::type coordinate_type;\n        typedef typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type promoted_type;\n\n\n        promoted_type sv =\n            side_value<coordinate_type, promoted_type>(p1, p2, p);\n        return sv > 0 ? 1\n            : sv < 0 ? -1\n            : 0;\n    }\n#endif\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n", "meta": {"hexsha": "04b4c424dce66b25cad5c99e591a684e93d718af", "size": 3983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.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/triangulation/strategies/cartesian/side_robust.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/triangulation/strategies/cartesian/side_robust.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": 38.2980769231, "max_line_length": 613, "alphanum_fraction": 0.6695957821, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5673774335087803}}
{"text": "// This file is part of the dune-xt-common project:\n//   https://github.com/dune-community/dune-xt-common\n// Copyright 2009-2018 dune-xt-common developers and contributors. All rights reserved.\n// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)\n//          with \"runtime exception\" (http://www.dune-project.org/license.html)\n// Authors:\n//   René Fritze    (2018)\n//   Tobias Leibner (2018)\n\n#ifndef DUNE_XT_COMMON_COORDINATES_HH\n#define DUNE_XT_COMMON_COORDINATES_HH\n\n\n#include <dune/xt/common/disable_warnings.hh>\n#include <boost/geometry.hpp>\n#include <dune/xt/common/reenable_warnings.hh>\n\n#include <dune/xt/common/fvector.hh>\n\nnamespace Dune {\nnamespace XT {\nnamespace Common {\n\n\n/** Converts from (x, y, z) to (theta, phi) on the unit sphere s.t.\n * (x, y, z) = (sin(theta) cos(phi), sin(theta) sin(phi), cos(theta))\n * with 0 \\leq \\theta \\leq \\pi and 0 \\leq \\varphi < 2\\pi. **/\ntemplate <class DomainFieldType>\nclass CoordinateConverter\n{\n  typedef typename boost::geometry::model::point<DomainFieldType, 3, typename boost::geometry::cs::cartesian>\n      BoostCartesianCoordType;\n  typedef typename boost::geometry::model::\n      point<DomainFieldType, 2, typename boost::geometry::cs::spherical<boost::geometry::radian>>\n          BoostSphericalCoordType;\n\npublic:\n  typedef FieldVector<DomainFieldType, 3> CartesianCoordType;\n  typedef FieldVector<DomainFieldType, 2> SphericalCoordType;\n\n  static SphericalCoordType to_spherical(const CartesianCoordType& x)\n  {\n    BoostCartesianCoordType x_boost(x[0], x[1], x[2]);\n    BoostSphericalCoordType x_spherical_boost;\n    boost::geometry::transform(x_boost, x_spherical_boost);\n    return SphericalCoordType{boost::geometry::get<1>(x_spherical_boost), boost::geometry::get<0>(x_spherical_boost)};\n  }\n\n  static CartesianCoordType to_cartesian(const SphericalCoordType& x_spherical, bool first_is_cosine = false)\n  {\n    // if first_is_cosine, the first coordinate is not theta but rather cos(theta)\n    if (first_is_cosine) {\n      const auto& mu = x_spherical[0];\n      const auto& phi = x_spherical[1];\n      return CartesianCoordType{\n          std::sqrt(1 - std::pow(mu, 2)) * std::cos(phi), std::sqrt(1 - std::pow(mu, 2)) * std::sin(phi), mu};\n    } else {\n      BoostSphericalCoordType x_spherical_boost(x_spherical[1], x_spherical[0]);\n      BoostCartesianCoordType x_boost;\n      boost::geometry::transform(x_spherical_boost, x_boost);\n      return CartesianCoordType{\n          boost::geometry::get<0>(x_boost), boost::geometry::get<1>(x_boost), boost::geometry::get<2>(x_boost)};\n    }\n  }\n};\n\n\n} // namespace Common\n} // namespace XT\n} // namespace Dune\n\n#endif // DUNE_XT_COMMON_COORDINATES_HH\n", "meta": {"hexsha": "8265b909bbc79bc61207aad3067d2dc8a30c7f50", "size": 2773, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/xt/common/coordinates.hh", "max_stars_repo_name": "ftschindler-work/dune-xt-common", "max_stars_repo_head_hexsha": "1748530e13dbf683b5bf14289bf3e134485755a8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-01-05T14:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:09:13.000Z", "max_issues_repo_path": "dune/xt/common/coordinates.hh", "max_issues_repo_name": "ftschindler-work/dune-xt-common", "max_issues_repo_head_hexsha": "1748530e13dbf683b5bf14289bf3e134485755a8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-01-06T16:32:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-25T08:28:53.000Z", "max_forks_repo_path": "dune/xt/common/coordinates.hh", "max_forks_repo_name": "ftschindler-work/dune-xt-common", "max_forks_repo_head_hexsha": "1748530e13dbf683b5bf14289bf3e134485755a8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-13T08:03:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-13T10:59:17.000Z", "avg_line_length": 37.472972973, "max_line_length": 118, "alphanum_fraction": 0.7165524702, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5673774287523536}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n#include <vector>\n\n#include \"mtao/eigen/shape_checks.hpp\"\n#include \"mtao/quadrature/simpsons.hpp\"\n\n//#include \"mtao/geometry/mesh/dual_volumes.hpp\"\n\nnamespace mtao::simulation::hexahedral {\ntemplate <typename Scalar, int D>\nEigen::Matrix<Scalar, 1 << D, 1 << D> laplacian_stencil() {\n    using Vec = mtao::Vector<Scalar, D>;\n    Eigen::Matrix<Scalar, 1 << D, 1 << D> S;\n    S.setZero();\n    auto eval = [](int elem, const std::array<Scalar, D>& vec) {\n        Vec coeffs;\n        Vec grad;\n        for (size_t idx = 0; idx < D; ++idx) {\n            if (elem & (1 << idx)) {\n                grad(idx) = -1;\n                coeffs(idx) = (Scalar(1) - vec[idx]);\n            } else {\n                grad(idx) = 1;\n                coeffs(idx) = (vec[idx]);\n            }\n        }\n        for (size_t idx = 0; idx < D; ++idx) {\n            for (size_t j = 0; j < D; ++j) {\n                if (j != idx) {\n                    grad(idx) *= coeffs(j);\n                }\n            }\n        }\n\n        return grad;\n    };\n\n    auto quad = [&](int i, int j) {\n        const int num_samples = 256;\n        Scalar val = Scalar(0);\n\n        val = quadrature::multidim_simpsons_rule<D, Scalar>(\n            [&](const std::array<Scalar, D>& p) -> Scalar {\n                return eval(i, p).dot(eval(j, p));\n            },\n            0., 1., num_samples);\n        return val;\n    };\n\n    /*\n    std::array<Scalar, D + 1> memo;\n    for (int j = 0; j <= D; ++j) {\n        memo[j] = quad(0, (1 << (j)) - 1);\n        std::cout << memo[j] << std::endl;\n    }\n    */\n    for (int i = 0; i < S.rows(); ++i) {\n        S(i, i) = quad(i, i);\n        // S(i, i) = memo[0];\n        for (int j = i + 1; j < S.cols(); ++j) {\n            /*\n            int v = i ^ j;\n            int count = 0;\n            for (int u = 0; u < D; ++u) {\n                if (v & (1 << u)) {\n                    count++;\n                }\n            }\n            */\n            // S(j, i) = S(i, j) = memo[count];\n            S(j, i) = S(i, j) = quad(i, j);\n        }\n    }\n    return S;\n}\n\n}  // namespace mtao::simulation::hexahedral\n", "meta": {"hexsha": "5951fe8865b79d1e5f4e4e8512de2febe58449f5", "size": 2131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/simulation/hexahedral/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/hexahedral/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/hexahedral/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": 26.6375, "max_line_length": 64, "alphanum_fraction": 0.4124824026, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5673774284909637}}
{"text": "/**\n * @file dynkin.hpp\n * @author freol35241\n * @brief A toolkit for 3D dynamics and kinematics of rigid bodies using\n * the YPR euler angle convention.\n * @version 0.3.0\n * @date 2021-01-30\n * \n * @copyright Copyright (c) 2021\n * \n */\n#include <cmath>\n#include <memory>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <unsupported/Eigen/EulerAngles>\n\nnamespace Eigen {\n    typedef Eigen::Matrix<double,6,1> Vector6d;\n    typedef Eigen::Matrix<double,6,6> Matrix6d;\n}\n\n/**\n * @brief `dynkin` namespace\n * \n */\nnamespace dynkin {\n\n    struct _Frame;\n    using Frame = std::shared_ptr<_Frame>;\n    struct Transform;\n    Transform transform(Frame zeroth, Frame end);\n\n    /**\n     * @brief Convert a 3x3 rotation matrix to euler angles using\n     * the YPR euler angle convention\n     * \n     * @param rotation A 3x3 rotation matrix\n     * @return Calculated euler angles [roll, pitch, yaw]\n     */\n    inline Eigen::Vector3d rotation_to_euler(const Eigen::Matrix3d& rotation){\n        return rotation.eulerAngles(2,1,0).reverse();\n    }\n\n    /**\n     * @brief Convert a vector of euler angles to a rotation matrix\n     * using the YPR uler angle convention\n     * \n     * @param attitude A vector of euler angles [roll, pitch, yaw]\n     * @return Calculated 3x3 rotation matrix\n     */\n    inline Eigen::Matrix3d euler_to_rotation(const Eigen::Vector3d& attitude){\n        return (\n            Eigen::AngleAxisd(attitude(2), Eigen::Vector3d::UnitZ())\n            * Eigen::AngleAxisd(attitude(1), Eigen::Vector3d::UnitY())\n            * Eigen::AngleAxisd(attitude(0), Eigen::Vector3d::UnitX())\n            ).toRotationMatrix();\n    }\n\n    /**\n     * @brief Representing a transform between two `Frames`\n     * \n     */\n    struct Transform{\n        Eigen::Isometry3d HTM;\n\n        Transform(const Eigen::Isometry3d& HTM):HTM(HTM){}\n\n        /**\n         * @brief Apply this transformation to a vector\n         * \n         * @param vector Vector to be transformed\n         * @return Transformed vector\n         */\n        Eigen::Vector3d apply_vector(const Eigen::Vector3d& vector){\n            return this->HTM.linear()*vector;\n        }\n\n        /**\n         * @brief Apply this transformation to a position vector\n         * \n         * @param position Position vector to be transformed\n         * @return Transformed position vector\n         */\n        Eigen::Vector3d apply_position(const Eigen::Vector3d& position){\n            return this->HTM*position;\n        }\n\n        /**\n         * @brief Apply this transformation to a wrench\n         * \n         * @param wrench Wrench to be transformed\n         * @return Transformed wrench\n         */\n        Eigen::Vector6d apply_wrench(const Eigen::Vector6d& wrench){\n            Eigen::Vector6d out;\n            out.head(3) = this->apply_vector(wrench.head(3));\n            out.tail(3) = this->apply_vector(wrench.tail(3)) + this->HTM.translation().cross(out.head<3>());\n            return out;\n        }\n\n        /**\n         * @brief Create a Transform which is the inverse of this\n         * \n         * @return Inverted transform\n         */\n        Transform inverse(){\n            return Transform(this->HTM.inverse());\n        }\n\n    };\n\n    /**\n     * @brief Create a Frame object\n     * \n     * @param parent The parent frame of the new frame\n     * @return A new Frame\n     */\n    Frame create_frame(Frame parent = nullptr){\n      return std::make_shared<_Frame>(parent);\n    }\n\n    /**\n     * @brief Representing a coordinate frame\n     * \n     */\n    struct _Frame: public std::enable_shared_from_this<_Frame>{\n        Eigen::Isometry3d HTM = Eigen::Isometry3d::Identity();\n        Eigen::Vector3d _linear_velocity = Eigen::Vector3d::Zero();\n        Eigen::Vector3d _angular_velocity = Eigen::Vector3d::Zero();\n        Frame parent;\n\n        _Frame(Frame parent):parent(parent){};\n\n        /**\n         * @brief Create a new Frame with this Frame as parent\n         * \n         * @return Child Frame\n         */\n        Frame create_child(){\n          return create_frame(this->shared_from_this());\n        }\n\n        /**\n         * @brief Position of this Frame in relation to parent Frame\n         * \n         * @return Position (3x1)\n         */\n        auto position(){\n            return this->HTM.translation();\n        }\n\n        /**\n         * @brief Rotation of this Frame in relation to parent Frame\n         * \n         * @return Rotation matrix 3x3\n         */\n        auto rotation(){\n            return this->HTM.linear();\n        }\n\n        /**\n         * @brief Linear velocity of this Frame in relation to parent Frame,\n         * decomposed in this Frame\n         * \n         * @return Linear velocity (3x1)\n         */\n        Eigen::Vector3d& linear_velocity(){\n            return this->_linear_velocity;\n        }\n\n        /**\n         * @brief Angular velocity of this Frame in relation to parent Frame,\n         * decomposed in this Frame\n         * \n         * @return Angular velocity (3x1)\n         */\n        Eigen::Vector3d& angular_velocity(){\n            return this->_angular_velocity;\n        }\n\n        /**\n         * @brief Get attitude of this Frame in relation to parent Frame\n         * \n         * @return Attitude (euler angles)(3x1)\n         */\n        Eigen::Vector3d get_attitude(){\n            return rotation_to_euler(this->rotation());\n        }\n\n        /**\n         * @brief Set attitude of this Frame in relation to parent Frame\n         * \n         * @param attitude Attitude (euler angles)(3x1)\n         */\n        void set_attitude(const Eigen::Vector3d& attitude){\n            this->rotation() = euler_to_rotation(attitude);\n        }\n\n        /**\n         * @brief Get pose of this Frame in relation to the inertial Frame\n         * \n         * @return Pose (6x1)\n         */\n        Eigen::Vector6d get_pose(){\n            Eigen::Vector6d out;\n            Transform t = transform(nullptr, this->shared_from_this());\n            out.head(3) = t.HTM.translation();\n            out.tail(3) = rotation_to_euler(t.HTM.linear());\n            return out;\n        }\n\n        /**\n         * @brief Get twist of this Frame in relation to the inertial Frame\n         * \n         * @return Twist (6x1) \n         */\n        Eigen::Vector6d get_twist(){\n            Eigen::Vector6d out;\n\n            Eigen::Vector3d v = this->linear_velocity();\n            Eigen::Vector3d w = this->angular_velocity();\n\n            if (this->parent != nullptr){\n                Eigen::Vector6d twist_p = this->parent->get_twist();\n                Transform t = transform(this->shared_from_this(), this->parent);\n                v += t.apply_vector(twist_p.head(3)) + twist_p.tail<3>().cross(this->position());\n                w += t.apply_vector(twist_p.tail(3));\n            }\n            out.head(3) = v;\n            out.tail(3) = w;\n            return out;\n        }\n\n    };\n\n    /**\n     * @brief Find transform between two frames\n     * \n     * @param zeroth Zeroth frame of transform\n     * @param end End frame of transform\n     * @return Transform from zeroth to end\n     */\n    inline Transform transform(Frame zeroth, Frame end){\n\n        Eigen::Isometry3d HTM = Eigen::Isometry3d::Identity();\n        Frame f = end;\n\n        while (f != nullptr){\n            if (f == zeroth){\n                return Transform(HTM);\n            }\n\n            HTM = f->HTM*HTM;\n            f = f->parent;\n\n        }\n\n        // If we get to here, the least common base frame is the inertial frame (nullptr)\n        Transform T = Transform(HTM);\n\n        if (zeroth == nullptr){\n            return T;\n        }\n\n        Transform T_ = transform(nullptr, zeroth).inverse();\n\n        return Transform(T_.HTM*T.HTM);\n    }\n\n    /**\n     * @brief `rigidbody`namespace\n     * \n     */\n    namespace rigidbody{\n\n        /**\n         * @brief Create a skew matrix (3x3) from a (3x1) vector\n         * \n         * @param v Vector to create skew matrix from\n         * @return Skew matrix\n         */\n        inline Eigen::Matrix3d skew(const Eigen::Vector3d& v){\n            Eigen::Matrix3d out;\n            out <<  0,  -v(2),  v(1),\n                    v(2),   0,  -v(0),\n                    -v(1),  v(0),   0;\n            return out;\n        }\n\n        /**\n         * @brief Create a Motion Transformation Matrix (6x6)\n         * \n         * @param position Position vector defining the transformation\n         * @return Motion Transformation Matrix\n         */\n        inline Eigen::Matrix6d motion_transformation_matrix(const Eigen::Vector3d& position){\n            Eigen::Matrix6d out = Eigen::Matrix6d::Identity();\n            out.block<3,3>(0,3) = skew(position).transpose();\n            return out;\n        }\n\n        /**\n         * @brief Create Generalized Inertia Matrix (6x6)\n         * \n         * @param mass Rigid body mass\n         * @param gyradii Rigid body gyradii (3x1)\n         * @return Generalized Inertia Matrix (6x6)\n         */\n        inline Eigen::Matrix6d generalized_inertia_matrix(const double& mass, const Eigen::Vector3d& gyradii){\n            if (mass <= 0.0){\n                throw std::invalid_argument(\"mass must be greater than zero!\");\n            }\n            if ((gyradii.array() <= 0.0).any()){\n                throw std::invalid_argument(\"All gyradii must be greater than zero!\");\n            }\n\n            Eigen::Matrix6d H = Eigen::Matrix6d::Zero();\n            H.block<3,3>(0,0) = Eigen::Matrix3d::Identity() * mass;\n            H.block<3,3>(3,3) = (mass*gyradii.array().square()).matrix().asDiagonal();\n            return H;\n        }\n\n        /**\n         * @brief Create an Eulerian Matrix (3x3) relating angular velocity to euler angle derivatives\n         * \n         * @param attitude Attitude (3x1)\n         * @return Eulerian Matrix (3x3)\n         */\n        inline Eigen::Matrix3d eulerian(const Eigen::Vector3d& attitude){\n            double fi = attitude(0);\n            double theta = attitude(1);\n            Eigen::Matrix3d out;\n            out <<  1,      sin(fi)*cos(theta),     cos(fi)*tan(theta),\n                    0,      cos(fi),                -sin(fi),\n                    0,      sin(fi)/cos(theta),     cos(fi)/cos(theta);\n            return out;\n        }\n\n        /**\n         * @brief Convert angular velocities to euler angle derivatives\n         * \n         * @param attitude Attitude of rigid body (3x1)\n         * @param angular_velocity Angular velocity of rigid body (3x1)\n         * @return Euler angle derivatives of rigid body (3x1)\n         */\n        inline Eigen::Vector3d angular_velocity_to_deuler(\n            const Eigen::Vector3d& attitude,\n            const Eigen::Vector3d& angular_velocity\n        ){\n            return eulerian(attitude)*angular_velocity;\n        }\n\n        /**\n         * @brief Representing an ideal rigid body\n         * \n         */\n        struct RigidBody {\n            Eigen::Matrix6d inertia = Eigen::Matrix6d::Identity();\n            const Frame origin = create_frame();\n            const Frame CoG = create_frame(origin);\n\n            /**\n             * @brief Construct a new Rigid Body object\n             * \n             * @param inertia Generalized Inertia of the rigid body (6x6)\n             * @param cog Position vector relating the origin and the CoG of the (3x1)\n             * rigid body\n             */\n            RigidBody(\n                const Eigen::Matrix6d inertia,\n                const Eigen::Vector3d& cog = Eigen::Vector3d::Zero()\n                ): inertia(inertia)\n                {\n                    this->CoG->position() = cog;\n                };\n\n            /**\n             * @brief Returns the mass of this rigid body\n             * \n             * @return Mass\n             */\n            double mass(){\n                return this->inertia(0,0);\n            }\n\n            /**\n             * @brief Assemble Coriolis-Centripetal Matrix \n             * \n             * @param inertia Generalized Inertia Matrix of rigid body (6x6)\n             * @param twist Twist of rigid body (3x1)\n             * @return Coriolis-Centripetal Matrix (6x6)\n             */\n            Eigen::Matrix6d coriolis_centripetal_matrix(\n                const Eigen::Matrix6d inertia,\n                const Eigen::Vector6d twist\n            ){\n                Eigen::Matrix6d C = Eigen::Matrix6d::Zero();\n                C.block<3,3>(0,0) = this->mass()*skew(twist.tail(3));\n                C.block<3,3>(3,3) = -skew(inertia.block<3,3>(3,3)*twist.tail(3));\n                return C;\n            }\n\n            /**\n             * @brief Generalized coordinates of this rigid body\n             * [x, y, z, fi, theta, psi]\n             * \n             * @return Generalized coordinates (6x1)\n             */\n            Eigen::Vector6d generalized_coordinates(){\n                return this->origin->get_pose();\n            }\n\n            /**\n             * @brief Generalized velocities of this rigid body\n             * [dx, dy, dz, dfi, dtheta, dpsi]\n             * \n             * @return Generalized velocities (6x1)\n             */\n            Eigen::Vector6d generalized_velocities(){\n                Eigen::Vector6d twist = this->origin->get_twist();\n                Transform t = transform(nullptr, this->origin);\n\n                Eigen::Vector6d out = Eigen::Vector6d::Zero();\n                out.head(3) = t.apply_vector(twist.head(3));\n                out.tail(3) = angular_velocity_to_deuler(\n                    this->origin->get_attitude(), twist.tail(3)\n                );\n\n                return out;\n            }\n\n            /**\n             * @brief Returns the resulting acceleration from the given wrench\n             * \n             * @param wrench Wrench acting on the rigid body (6x1)\n             * @param additional_inertia Inertia in addition to the inertia of this\n             * rigid body that should be accelerated (6x6)\n             * @return Acceleration (6x1)\n             */\n            Eigen::Vector6d acceleration(\n                const Eigen::Vector6d& wrench,\n                const Eigen::Matrix6d& additional_inertia = Eigen::Matrix6d::Zero()\n            ){\n                Eigen::Vector6d twist, f_cc, f;\n                Eigen::Matrix6d H, I_cg, C_cg, I_b, C_b;\n\n                f = wrench;\n                twist = this->origin->get_twist();\n\n                H = motion_transformation_matrix(this->CoG->position());\n                I_cg = (this->inertia.array() + additional_inertia.array()).matrix();\n                C_cg = this->coriolis_centripetal_matrix(I_cg, twist);\n                I_b = H.transpose() * I_cg * H;\n                C_b = H.transpose() * C_cg * H;\n\n                f_cc = C_b * twist;\n                f -= f_cc;\n\n                return I_b.lu().solve(f);\n            }\n\n            /**\n             * @brief Returns the required wrench to obtain the given acceleration\n             * \n             * @param acceleration Given acceleration (6x1)\n             * @param additional_inertia Inertia in addition to the inertia of this\n             * rigid body that should be accelerated (6x6)\n             * @return Wrench (6x1)\n             */\n            Eigen::Vector6d wrench(\n                const Eigen::Vector6d& acceleration,\n                const Eigen::Matrix6d& additional_inertia = Eigen::Matrix6d::Zero()\n            ){\n                Eigen::Vector6d twist, f_cc, f;\n                Eigen::Matrix6d H, I_cg, C_cg, I_b, C_b;\n\n                twist = this->origin->get_twist();\n\n                H = motion_transformation_matrix(this->CoG->position());\n                I_cg = (this->inertia.array() + additional_inertia.array()).matrix();\n                C_cg = this->coriolis_centripetal_matrix(I_cg, twist);\n                I_b = H.transpose() * I_cg * H;\n                C_b = H.transpose() * C_cg * H;\n\n                f = I_b * acceleration;\n                f_cc = C_b * twist;\n                f += f_cc;\n\n                return f;\n            }\n\n        };\n\n\n    }\n\n\n}\n", "meta": {"hexsha": "e000938d49839a41deb2a7d4c8255dbc84e6f6d8", "size": 15953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dynkin/dynkin.hpp", "max_stars_repo_name": "freol35241/dynkin", "max_stars_repo_head_hexsha": "12fecae1ba5a856c56ba64c65c4cba198abf4979", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-03T23:28:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T23:28:54.000Z", "max_issues_repo_path": "include/dynkin/dynkin.hpp", "max_issues_repo_name": "freol35241/dynkin", "max_issues_repo_head_hexsha": "12fecae1ba5a856c56ba64c65c4cba198abf4979", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-04T18:45:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-28T15:44:02.000Z", "max_forks_repo_path": "include/dynkin/dynkin.hpp", "max_forks_repo_name": "freol35241/dynkin", "max_forks_repo_head_hexsha": "12fecae1ba5a856c56ba64c65c4cba198abf4979", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-05T13:16:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T13:16:46.000Z", "avg_line_length": 31.906, "max_line_length": 110, "alphanum_fraction": 0.5236632608, "num_tokens": 3720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5673774121305619}}
{"text": "#include \"MyConditionalPrior.h\"\n#include \"DNest4/code/DNest4.h\"\n#include <cmath>\n#include <boost/math/distributions/normal.hpp>\n\nnamespace Obscurity\n{\n\nMyConditionalPrior::MyConditionalPrior()\n{\n\n}\n\nvoid MyConditionalPrior::from_prior(DNest4::RNG& rng)\n{\n    sigma = rng.rand();\n\n    mu_mass = exp(log(1E-3) + log(1E6)*rng.rand());\n    mu_width = exp(log(1E-3) + log(1E6)*rng.rand());\n}\n\ndouble MyConditionalPrior::perturb_hyperparameters(DNest4::RNG& rng)\n{\n\tdouble logH = 0.0;\n\n    int which = rng.rand_int(3);\n\n    if(which == 0)\n    {\n        sigma += rng.randh();\n        DNest4::wrap(sigma, 0.0, 1.0);\n    }\n    else if(which == 1)\n    {\n        mu_mass = log(mu_mass);\n        mu_mass += log(1E6)*rng.randh();\n        DNest4::wrap(mu_mass, log(1E-3), log(1E3));\n        mu_mass = exp(mu_mass);\n    }\n    else\n    {\n        mu_width = log(mu_width);\n        mu_width += log(1E6)*rng.randh();\n        DNest4::wrap(mu_width, log(1E-3), log(1E3));\n        mu_width = exp(mu_width);\n    }\n\n\treturn logH;\n}\n\n// vec = {xc, yc, mass, width}\n\ndouble MyConditionalPrior::log_pdf(const std::vector<double>& vec) const\n{\n    double logp = 0.0;\n\n    if(vec[2] < 0 || vec[3] < 0.999*mu_width || vec[3] > 1.001*mu_width)\n        return -1E300;\n\n    logp += -log(2*M_PI*sigma*sigma)\n                -0.5*(vec[0]*vec[0] + vec[1]*vec[1])/(sigma*sigma);\n    logp += -log(mu_mass) - vec[2]/mu_mass;\n\n\treturn logp;\n}\n\n#include <iostream>\nvoid MyConditionalPrior::from_uniform(std::vector<double>& vec) const\n{\n    const boost::math::normal standard_normal(0.0, 1.0);\n    vec[0] = sigma*quantile(standard_normal, vec[0]);\n    vec[1] = sigma*quantile(standard_normal, vec[1]);\n    vec[2] = -mu_mass*log(1.0 - vec[2]);\n    vec[3] = mu_width*(0.999 + 0.002*vec[3]);\n}\n\nvoid MyConditionalPrior::to_uniform(std::vector<double>& vec) const\n{\n    const boost::math::normal standard_normal(0.0, 1.0);\n    vec[0] = cdf(standard_normal, vec[0]/sigma);\n    vec[1] = cdf(standard_normal, vec[1]/sigma);\n    vec[2] = 1.0 - exp(-vec[2]/mu_mass);\n    vec[3] = (vec[3]/mu_width - 0.999)/0.002;\n}\n\nvoid MyConditionalPrior::print(std::ostream& out) const\n{\n\tout<<sigma<<' '<<mu_mass<<' '<<mu_width<<' ';\n}\n\n} // namespace Obscurity\n\n", "meta": {"hexsha": "a3c6a355445f7c9964b3c972b99365953a68e3bb", "size": 2200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/MyConditionalPrior.cpp", "max_stars_repo_name": "eggplantbren/Obscurity", "max_stars_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_stars_repo_licenses": ["MIT"], "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/MyConditionalPrior.cpp", "max_issues_repo_name": "eggplantbren/Obscurity", "max_issues_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_issues_repo_licenses": ["MIT"], "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/MyConditionalPrior.cpp", "max_forks_repo_name": "eggplantbren/Obscurity", "max_forks_repo_head_hexsha": "29cba90a1a050807db0fbbb52d0137ef40ae8f1a", "max_forks_repo_licenses": ["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.6559139785, "max_line_length": 72, "alphanum_fraction": 0.6068181818, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5673678378022698}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003 Ferdinando Ametrano\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\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/*! \\file incrementalstatistics.hpp\n    \\brief statistics tool based on incremental accumulation\n           in the meantime, this is just a wrapper to the boost\n           accumulator library, kept for backward compatibility\n*/\n\n#ifndef quantlib_incremental_statistics_hpp\n#define quantlib_incremental_statistics_hpp\n\n#include <ql/utilities/null.hpp>\n#include <ql/errors.hpp>\n\n#if defined(__clang__)\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wc++11-extensions\"\n#endif\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n#include <boost/accumulators/statistics/weighted_variance.hpp>\n#include <boost/accumulators/statistics/weighted_skewness.hpp>\n#include <boost/accumulators/statistics/weighted_kurtosis.hpp>\n#include <boost/accumulators/statistics/weighted_moment.hpp>\n#if defined(__clang__)\n#pragma clang diagnostic pop\n#endif\n\n#include <iomanip>\n\nnamespace QuantLib {\n\n    //! Statistics tool based on incremental accumulation\n    /*! It can accumulate a set of data and return statistics (e.g: mean,\n        variance, skewness, kurtosis, error estimation, etc.).\n        This class is a wrapper to the boost accumulator library.\n    */\n\n    class IncrementalStatistics {\n      public:\n        typedef Real value_type;\n        IncrementalStatistics();\n        //! \\name Inspectors\n        //@{\n        //! number of samples collected\n        Size samples() const;\n\n        //! sum of data weights\n        Real weightSum() const;\n\n        /*! returns the mean, defined as\n            \\f[ \\langle x \\rangle = \\frac{\\sum w_i x_i}{\\sum w_i}. \\f]\n        */\n        Real mean() const;\n\n        /*! returns the variance, defined as\n            \\f[ \\frac{N}{N-1} \\left\\langle \\left(\n                x-\\langle x \\rangle \\right)^2 \\right\\rangle. \\f]\n        */\n        Real variance() const;\n\n        /*! returns the standard deviation \\f$ \\sigma \\f$, defined as the\n            square root of the variance.\n        */\n        Real standardDeviation() const;\n\n        /*! returns the error estimate \\f$ \\epsilon \\f$, defined as the\n            square root of the ratio of the variance to the number of\n            samples.\n        */\n        Real errorEstimate() const;\n\n        /*! returns the skewness, defined as\n            \\f[ \\frac{N^2}{(N-1)(N-2)} \\frac{\\left\\langle \\left(\n                x-\\langle x \\rangle \\right)^3 \\right\\rangle}{\\sigma^3}. \\f]\n            The above evaluates to 0 for a Gaussian distribution.\n        */\n        Real skewness() const;\n\n        /*! returns the excess kurtosis, defined as\n            \\f[ \\frac{N^2(N+1)}{(N-1)(N-2)(N-3)}\n                \\frac{\\left\\langle \\left(x-\\langle x \\rangle \\right)^4\n                \\right\\rangle}{\\sigma^4} - \\frac{3(N-1)^2}{(N-2)(N-3)}. \\f]\n            The above evaluates to 0 for a Gaussian distribution.\n        */\n        Real kurtosis() const;\n\n        /*! returns the minimum sample value */\n        Real min() const;\n\n        /*! returns the maximum sample value */\n        Real max() const;\n\n        //! number of negative samples collected\n        Size downsideSamples() const;\n\n        //! sum of data weights for negative samples\n        Real downsideWeightSum() const;\n\n        /*! returns the downside variance, defined as\n            \\f[ \\frac{N}{N-1} \\times \\frac{ \\sum_{i=1}^{N}\n                \\theta \\times x_i^{2}}{ \\sum_{i=1}^{N} w_i} \\f],\n            where \\f$ \\theta \\f$ = 0 if x > 0 and\n            \\f$ \\theta \\f$ =1 if x <0\n        */\n        Real downsideVariance() const;\n\n        /*! returns the downside deviation, defined as the\n            square root of the downside variance.\n        */\n        Real downsideDeviation() const;\n\n        //@}\n\n        //! \\name Modifiers\n        //@{\n        //! adds a datum to the set, possibly with a weight\n        /*! \\pre weight must be positive or null */\n        void add(Real value, Real weight = 1.0);\n        //! adds a sequence of data to the set, with default weight\n        template <class DataIterator>\n        void addSequence(DataIterator begin, DataIterator end) {\n            for (;begin!=end;++begin)\n                add(*begin);\n        }\n        //! adds a sequence of data to the set, each with its weight\n        /*! \\pre weights must be positive or null */\n        template <class DataIterator, class WeightIterator>\n        void addSequence(DataIterator begin, DataIterator end,\n                         WeightIterator wbegin) {\n            for (;begin!=end;++begin,++wbegin)\n                add(*begin, *wbegin);\n        }\n        //! resets the data to a null set\n        void reset();\n        //@}\n     private:\n       typedef boost::accumulators::accumulator_set<\n           Real,\n           boost::accumulators::stats<\n               boost::accumulators::tag::count, boost::accumulators::tag::min,\n               boost::accumulators::tag::max,\n               boost::accumulators::tag::weighted_mean,\n               boost::accumulators::tag::weighted_variance,\n               boost::accumulators::tag::weighted_skewness,\n               boost::accumulators::tag::weighted_kurtosis,\n               boost::accumulators::tag::sum_of_weights>,\n           Real> accumulator_set;\n        accumulator_set acc_;\n        typedef boost::accumulators::accumulator_set<\n            Real, boost::accumulators::stats<\n                      boost::accumulators::tag::count,\n                      boost::accumulators::tag::weighted_moment<2>,\n                      boost::accumulators::tag::sum_of_weights>,\n            Real> downside_accumulator_set;\n        downside_accumulator_set downsideAcc_;\n    };\n\n    // implementation\n\n    inline IncrementalStatistics::IncrementalStatistics() {\n        reset();\n    }\n\n    inline Size IncrementalStatistics::samples() const {\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::count>(acc_);\n    }\n\n    inline Real IncrementalStatistics::weightSum() const {\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::sum_of_weights>(acc_);\n    }\n\n    inline Real IncrementalStatistics::mean() const {\n        QL_REQUIRE(weightSum() > 0.0, \"sampleWeight_= 0, unsufficient\");\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::weighted_mean>(acc_);\n    }\n\n    inline Real IncrementalStatistics::variance() const {\n        QL_REQUIRE(weightSum() > 0.0, \"sampleWeight_= 0, unsufficient\");\n        QL_REQUIRE(samples() > 1, \"sample number <= 1, unsufficient\");\n        Real n = static_cast<Real>(samples());\n        return n / (n - 1.0) *\n               boost::accumulators::extract_result<\n                   boost::accumulators::tag::weighted_variance>(acc_);\n    }\n\n    inline Real IncrementalStatistics::standardDeviation() const {\n        return std::sqrt(variance());\n    }\n\n    inline Real IncrementalStatistics::errorEstimate() const {\n        return std::sqrt(variance() / (samples()));\n    }\n\n    inline Real IncrementalStatistics::skewness() const {\n        QL_REQUIRE(samples() > 2, \"sample number <= 2, unsufficient\");\n        Real n = static_cast<Real>(samples());\n        Real r1 = n / (n - 2.0);\n        Real r2 = (n - 1.0) / (n - 2.0);\n        return std::sqrt(r1 * r2) * \n               boost::accumulators::extract_result<\n                   boost::accumulators::tag::weighted_skewness>(acc_);\n    }\n\n    inline Real IncrementalStatistics::kurtosis() const {\n        QL_REQUIRE(samples() > 3,\n                   \"sample number <= 3, unsufficient\");\n        boost::accumulators::extract_result<\n            boost::accumulators::tag::weighted_kurtosis>(acc_);\n        Real n = static_cast<Real>(samples());\n        Real r1 = (n - 1.0) / (n - 2.0);\n        Real r2 = (n + 1.0) / (n - 3.0);\n        Real r3 = (n - 1.0) / (n - 3.0);\n        return ((3.0 + boost::accumulators::extract_result<\n                           boost::accumulators::tag::weighted_kurtosis>(acc_)) *\n                    r2 -\n                3.0 * r3) *\n               r1;\n    }\n\n    inline Real IncrementalStatistics::min() const {\n        QL_REQUIRE(samples() > 0, \"empty sample set\");\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::min>(acc_);\n    }\n\n    inline Real IncrementalStatistics::max() const {\n        QL_REQUIRE(samples() > 0, \"empty sample set\");\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::max>(acc_);\n    }\n\n    inline Size IncrementalStatistics::downsideSamples() const {\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::count>(downsideAcc_);\n    }\n\n    inline Real IncrementalStatistics::downsideWeightSum() const {\n        return boost::accumulators::extract_result<\n            boost::accumulators::tag::sum_of_weights>(downsideAcc_);\n    }\n\n    inline Real IncrementalStatistics::downsideVariance() const {\n        QL_REQUIRE(downsideWeightSum() > 0.0, \"sampleWeight_= 0, unsufficient\");\n        QL_REQUIRE(downsideSamples() > 1, \"sample number <= 1, unsufficient\");\n        Real n = static_cast<Real>(downsideSamples());\n        Real r1 = n / (n - 1.0);\n        return r1 *\n               boost::accumulators::extract_result<\n                   boost::accumulators::tag::moment<2> >(downsideAcc_);\n    }\n\n    inline Real IncrementalStatistics::downsideDeviation() const {\n        return std::sqrt(downsideVariance());\n    }\n\n    inline void IncrementalStatistics::add(Real value, Real valueWeight) {\n        QL_REQUIRE(valueWeight >= 0.0, \"negative weight (\" << valueWeight\n                                                           << \") not allowed\");\n        acc_(value, boost::accumulators::weight = valueWeight);\n        if(value < 0.0)\n            downsideAcc_(value, boost::accumulators::weight = valueWeight);\n    }\n\n    inline void IncrementalStatistics::reset() {\n        acc_ = accumulator_set();\n        downsideAcc_ = downside_accumulator_set();\n    }\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "605858a246fdfc11c15191824e1e4b77bd1d4be5", "size": 11126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/statistics/incrementalstatistics.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/statistics/incrementalstatistics.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/statistics/incrementalstatistics.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 36.8410596026, "max_line_length": 80, "alphanum_fraction": 0.6115405357, "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5673678378022697}}
{"text": "#ifndef PCP_ALGORITHM_COVARIANCE_HPP\n#define PCP_ALGORITHM_COVARIANCE_HPP\n\n/**\n * @file\n * @ingroup algorithm\n */\n\n#include \"pcp/common/vector3d_queries.hpp\"\n#include \"pcp/traits/point_map.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <utility>\n\nnamespace pcp {\nnamespace algorithm {\n\n/**\n * @ingroup algorithm\n * @brief Computes the covariance matrix of a point set\n * @tparam ForwardIter Iterator type of input point set\n * @tparam PointMap Type satisfying PointMap concept\n * @param begin Start iterator to input point set\n * @param end End iterator to input point set\n * @param point_map The point map property map\n * @return A pair of the mean and covariance matrix [mu, Cov]\n */\ntemplate <class ForwardIter, class PointMap>\nstd::pair<\n    Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        1>,\n    Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        3>>\ncovariance(ForwardIter begin, ForwardIter end, PointMap const& point_map)\n{\n    using element_type = typename std::iterator_traits<ForwardIter>::value_type;\n\n    static_assert(\n        traits::is_point_map_v<PointMap, element_type>,\n        \"point_map must satisfy PointMap concept\");\n\n    using point_type  = std::invoke_result_t<PointMap, element_type>;\n    using scalar_type = typename point_type::coordinate_type;\n    using vector_type = Eigen::Matrix<scalar_type, 3, 1>;\n    using matrix_type = Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        3>;\n\n    /**\n     * element 0 : x*x\n     * element 1 : y*y\n     * element 2 : z*z\n     * element 3 : x*y\n     * element 4 : x*z\n     * element 5 : y*z\n     */\n    std::array<scalar_type, 6u> cov{0.};\n\n    point_type const mu = common::center_of_geometry(begin, end, point_map);\n    std::for_each(begin, end, [&](element_type const& e) {\n        auto const& p = point_map(e);\n        auto const pp = p - mu;\n\n        auto const xx = pp.x() * pp.x();\n        auto const yy = pp.y() * pp.y();\n        auto const zz = pp.z() * pp.z();\n        auto const xy = pp.x() * pp.y();\n        auto const xz = pp.x() * pp.z();\n        auto const yz = pp.y() * pp.z();\n\n        cov[0] += xx;\n        cov[1] += yy;\n        cov[2] += zz;\n        cov[3] += xy;\n        cov[4] += xz;\n        cov[5] += yz;\n    });\n\n    matrix_type Cov;\n    Cov(0, 0) = cov[0];\n    Cov(1, 1) = cov[1];\n    Cov(2, 2) = cov[2];\n\n    Cov(0, 1) = cov[3];\n    Cov(0, 2) = cov[4];\n    Cov(1, 2) = cov[5];\n    Cov(1, 0) = Cov(0, 1);\n    Cov(2, 0) = Cov(0, 2);\n    Cov(2, 1) = Cov(1, 2);\n\n    return {vector_type{mu.x(), mu.y(), mu.z()}, Cov};\n}\n\n/**\n * @ingroup algorithm\n * @brief Sorts eigenvalues and eigenvectors in increasing order\n * @tparam ScalarType Coefficient type\n * @param lambda Vector of eigen values\n * @param v Matrix of eigen vectors\n * @return a pair = (sorted eigen values, sorted eigen vectors)\n */\ntemplate <class ScalarType>\nstd::pair<Eigen::Matrix<ScalarType, 3, 1>, Eigen::Matrix<ScalarType, 3, 3>> eigen_sorted(\n    Eigen::Matrix<ScalarType, 3, 1> const& lambda,\n    Eigen::Matrix<ScalarType, 3, 3> const& v)\n{\n    using vector_type = Eigen::Matrix<ScalarType, 3, 1>;\n    using matrix_type = Eigen::Matrix<ScalarType, 3, 3>;\n\n    std::array<int, 3u> indices{0, 1, 2};\n    std::sort(indices.begin(), indices.end(), [&](int const i, int const j) {\n        return lambda(i) < lambda(j);\n    });\n\n    vector_type const eigen_values{lambda(indices[0]), lambda(indices[1]), lambda(indices[2])};\n    matrix_type eigen_vectors(3, 3);\n    eigen_vectors.col(0) = v.col(indices[0]);\n    eigen_vectors.col(1) = v.col(indices[1]);\n    eigen_vectors.col(2) = v.col(indices[2]);\n\n    return {eigen_values, eigen_vectors};\n}\n\n/**\n * @ingroup algorithm\n * @brief Sorts eigenvalues and eigenvectors in increasing order\n * @tparam ScalarType Coefficient type\n * @param Cov The covariance matrix\n * @return a pair = (sorted eigen values, sorted eigen vectors)\n */\ntemplate <class ScalarType>\nstd::pair<Eigen::Matrix<ScalarType, 3, 1>, Eigen::Matrix<ScalarType, 3, 3>>\neigen_sorted(Eigen::Matrix<ScalarType, 3, 3> const& Cov)\n{\n    using vector_type = Eigen::Matrix<ScalarType, 3, 1>;\n    using matrix_type = Eigen::Matrix<ScalarType, 3, 3>;\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix<ScalarType, 3, 3>> A(Cov);\n    vector_type const& lambda = A.eigenvalues();\n    matrix_type const& v      = A.eigenvectors();\n\n    return eigen_sorted(lambda, v);\n}\n\n/**\n * @ingroup algorithm\n * @brief Returns the sorted eigen values and eigen vectors of the covariance matrix of a point set\n * @tparam ForwardIter Iterator type of input point set\n * @tparam PointMap Type satisfying PointMap concept\n * @param begin Start iterator to the input point set\n * @param end End iterator to the input point set\n * @param point_map The point map property map\n * @return A pair = (sorted eigen values, sorted eigen vectors)\n */\ntemplate <class ForwardIter, class PointMap>\nstd::pair<\n    Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        1>,\n    Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        3>>\npca(ForwardIter begin, ForwardIter end, PointMap const& point_map)\n{\n    using matrix_type = Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        3>;\n\n    using vector_type = Eigen::Matrix<\n        typename std::invoke_result_t<\n            PointMap,\n            typename std::iterator_traits<ForwardIter>::value_type>::coordinate_type,\n        3,\n        1>;\n\n    auto const [mu, sigma] = covariance(begin, end, point_map);\n    matrix_type const& Cov = sigma;\n\n    return eigen_sorted(Cov);\n}\n\n} // namespace algorithm\n} // namespace pcp\n\n#endif // PCP_ALGORITHM_COVARIANCE_HPP\n", "meta": {"hexsha": "eec804c98b9164d8bdbc77bc7441764b094a2a43", "size": 6333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcp/algorithm/covariance.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/covariance.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/covariance.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": 30.5942028986, "max_line_length": 99, "alphanum_fraction": 0.6414021791, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5673678264128428}}
{"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; // std::complex<double>;\n\tusing tensor_t = tensor<value_t,format_t>;\n\tusing matrix_t = matrix<value_t,format_t>;\n\tusing vector_t = vector<value_t>;\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,2);\n\t\tauto q = 0u; // contraction mode\n\n\t\t// C1(j,k) = T2(j,k) + A(i,j,k)*T1(i);\n\t\tq = 1u;\n\t\ttensor_t C1 = matrix_t(n[1],n[2],2) + prod(A,vector_t(n[q-1],1),q);\n\n\t\t// C2(i,k) = A(i,j,k)*T1(j) + 4;\n\t\tq = 2u;\n\t\ttensor_t C2 = prod(A,vector_t(n[q-1],1),q) + 4;\n\n\t\t// C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);\t\t\n\t\ttensor_t C3 = prod(prod(prod(A,vector_t(n[0],1),1),vector_t(n[1],1),1),vector_t(n[2],1),1);\n\n\t\t// C4(i,j) = A(k,i,j)*T1(k) + 4;\n\t\tq = 1u;\n\t\ttensor_t C4 = prod(trans(A,{2,3,1}),vector_t(n[2],1),q) + 4;\n\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) = T2(j,k) + A(i,j,k)*T1(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)*T1(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() = A(i,j,k)*T1(i)*T2(j)*T2(k);\" << std::endl << std::endl;\n\t\tstd::cout << \"C3()=\" << C3(0) << \";\" << 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 << \"% C4(i,j) = A(k,i,j)*T1(k) + 4;\" << std::endl << std::endl;\n\t\tstd::cout << \"C4=\" << C4 << \";\" << std::endl << std::endl;\n\n\t}\n\n\n\t// Tensor-Matrix-Multiplications - Including Transposition\n\t{\n\n\t\tauto n = shape{3,4,2};\n\t\tauto A = tensor_t(n,2);\n\t\tauto m = 5u;\n\t\tauto q = 0u; // contraction mode\n\n\t\t// C1(l,j,k) = T2(l,j,k) + A(i,j,k)*T1(l,i);\n\t\tq = 1u;\n\t\ttensor_t C1 = tensor_t(shape{m,n[1],n[2]},2) + prod(A,matrix_t(m,n[q-1],1),q);\n\n\t\t// C2(i,l,k) = A(i,j,k)*T1(l,j) + 4;\n\t\tq = 2u;\n\t\ttensor_t C2 = prod(A,matrix_t(m,n[q-1],1),q) + 4;\n\n\t\t// C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);\n\t\tq = 3u;\n\t\ttensor_t C3 = prod(prod(A,matrix_t(m+1,n[q-2],1),q-1),matrix_t(m+2,n[q-1],1),q);\n\n\t\t// C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\n\t\ttensor_t C4 = prod(prod(A,matrix_t(m+2,n[q-1],1),q),matrix_t(m+1,n[q-2],1),q-1);\n\n\t\t// C5(i,k,l) = A(i,k,j)*T1(l,j) + 4;\n\t\tq = 3u;\n\t\ttensor_t C5 = prod(trans(A,{1,3,2}),matrix_t(m,n[1],1),q) + 4;\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) = T2(l,j,k) + A(i,j,k)*T1(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)*T1(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\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C4(i,l1,l2) = A(i,j,k)*T2(l2,k)*T1(l1,j);\" << std::endl << std::endl;\n\t\tstd::cout << \"C4=\" << C4 << \";\" << std::endl << std::endl;\n\t\tstd::cout << \"% C3 and C4 should have the same values, true? \" << std::boolalpha << (C3 == C4) << \"!\" << std::endl;\n\n\n\t\t// formatted output\n\t\tstd::cout << \"% --------------------------- \" << std::endl;\n\t\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\t\tstd::cout << \"% C5(i,k,l) = A(i,k,j)*T1(l,j) + 4;\" << std::endl << std::endl;\n\t\tstd::cout << \"C5=\" << C5 << \";\" << std::endl << std::endl;\n\t}\n\n\n\n\n\n\t// Tensor-Tensor-Multiplications Including Transposition\n\t{\n\n\t\tusing perm_t = std::vector<std::size_t>;\n\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\n\n\t\t// C1(j,l) = T(j,l) + A(i,j,k)*A(i,j,l) + 5;\n\t\ttensor_t C1 = tensor_t(shape{na[2],na[2]},2) + prod(A,A,perm_t{1,2}) + 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) = T(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) = T(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;\n\t\ttensor_t C2 = tensor_t(shape{na[2],nb[1],nb[3]},2) + prod(A,B,perm_t{1,2},perm_t{3,1}) + 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) = T(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\n\t\t// C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\n\t\ttensor_t C3 = tensor_t(shape{na[2],nb[1],nb[3]},2) + prod(A,trans(B,{2,3,1,4}),perm_t{1,2}) + 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 << \"%  C3(k,l,m) = T(k,l,m) + A(i,j,k)*trans(B(j,l,i,m),{2,3,1,4})+ 5;\" << std::endl << std::endl;\n\t\tstd::cout << \"C3=\" << C3 << \";\" << std::endl << std::endl;\n\n\t}\n}\n", "meta": {"hexsha": "6ff725214023898558f3d0f952ab1cb718609775", "size": 6633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/examples/tensor/prod_expressions.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/prod_expressions.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/prod_expressions.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": 36.0489130435, "max_line_length": 117, "alphanum_fraction": 0.4626865672, "num_tokens": 2461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5673332549409037}}
{"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// g++ -o cgauss -I/usr/local/include cgauss.cpp -L/usr/local/lib -lntl -lm\n\n// So this confirms that E(s^k)/H^k = k!\n\n#include <NTL/ZZ.h>\n\n#include <complex>\n\n\nNTL_CLIENT\n\n\n\n//evaluate f at e^{2 pi i/m}, returning a complex number\n\ncomplex<double> evalPoly(double *f, long i, long m)\n{\n  complex<double> t(0.0, 2*M_PI*i/((double) m));\n  complex<double> x = exp(t);\n\n  complex<double> res = 0.0;\n  for (long j = m-1; j >= 0; j--)\n    res = res*x + f[j];\n\n  return res;\n}\n\n\n\nint main()\n{\n   long m = 1001;\n   long h = 100;\n\n   long maxpow = 7;\n   long iter = 100000;\n\n   double *s = new double[m];\n   complex<double> *pow = new complex<double> [m];\n   double *sum = new double[maxpow+1];\n\n   for (long k = 1; k <= maxpow; k++) sum[k] = 0;\n\n   complex<double> t(0.0, 2*M_PI*1/((double) m));\n   complex<double> x = exp(t);\n   complex<double> xi = 1.0;\n   for (long i = 0; i < m; i++) {\n      pow[i] = xi;\n      xi *= x;\n   }\n\n   for (long u = 0; u < iter; u++) {\n      complex<double> v = 0.0;\n      for (long i = 0; i < m; i++) {\n         if (RandomBnd(m) < h) { // true w/ prob. h/m\n            if (RandomBnd(2) == 0)\n               v += pow[i];\n            else\n               v -= pow[i];\n         }\n      }\n\n      double nv = norm(v);\n      double nvk = nv;\n\n      for (long k = 1; k <= maxpow; k++) {\n         sum[k] += nvk;\n         nvk *= nv;\n      }\n   }\n\n   for (long k = 1; k <= maxpow; k++) {\n      double ave = sum[k]/iter;\n      cout << ave/exp(k*log(h)) << \"\\n\";\n   }\n}\n", "meta": {"hexsha": "7ca0bc9c6391744c0a22361392c98dee4bb87127", "size": 2117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/misc/cgauss.cpp", "max_stars_repo_name": "Valenceo/HElib", "max_stars_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "src/misc/cgauss.cpp", "max_issues_repo_name": "Valenceo/HElib", "max_issues_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T09:26:24.000Z", "max_forks_repo_path": "src/misc/cgauss.cpp", "max_forks_repo_name": "Valenceo/HElib", "max_forks_repo_head_hexsha": "f560416454d672e1253412c81840d2563ab9b456", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 24.0568181818, "max_line_length": 75, "alphanum_fraction": 0.5640056684, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5673332461946552}}
{"text": "/**\n * @file quasiinterpolation.cc\n * @brief NPDE exam TEMPLATE CODE FILE\n * @author Oliver Rietmann\n * @date 15.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"quasiinterpolation.h\"\n\n#include <lf/base/base.h>  // nonstd::span\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/utils/utils.h>\n\n#include <Eigen/Core>\n#include <memory>\n#include <utility>\n\nnamespace QuasiInterpolation {\n\n// Auxiliary function: computing the length of an edge\ndouble edgeLength(const lf::mesh::Entity &edge) {\n  Eigen::Matrix2d corners = lf::geometry::Corners(*(edge.Geometry()));\n  return (corners.col(1) - corners.col(0)).norm();\n}\n\n// Auxiliary function: computing the length of the longest edge\ndouble maxLength(const nonstd::span<const lf::mesh::Entity *const> &edges) {\n  double length = 0.0;\n  for (const lf::mesh::Entity *edge : edges) {\n    length = std::max(length, edgeLength(*edge));\n  }\n  return length;\n}\n\n/* SAM_LISTING_BEGIN_1 */\nlf::mesh::utils::CodimMeshDataSet<\n    std::pair<const lf::mesh::Entity *, unsigned int>>\nfindKp(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  // Variable for returning result\n  lf::mesh::utils::CodimMeshDataSet<\n      std::pair<const lf::mesh::Entity *, unsigned int>>\n      KpMeshDataSet(mesh_p, 2);\n  // Auxiliary array storing size of largest triangle adjacent to a node\n  lf::mesh::utils::CodimMeshDataSet<double> sizeMeshDataSet(mesh_p, 2);\n  // loop over all cells\n  for (const lf::mesh::Entity *triangle : mesh_p->Entities(0)) {\n    LF_ASSERT_MSG(triangle->RefEl() == lf::base::RefEl::kTria(),\n                  \"Only implemented for triangles\");\n    // Fetch coordinates of vertices\n    const Eigen::MatrixXd corners{lf::geometry::Corners(*triangle->Geometry())};\n    // Determine size of triangle\n    const double newSize = std::max({(corners.col(1) - corners.col(0)).norm(),\n                                     (corners.col(2) - corners.col(1)).norm(),\n                                     (corners.col(0) - corners.col(2)).norm()});\n    // Obtain array of pointers to vertex objects of current triangle\n    nonstd::span<const lf::mesh::Entity *const> vertices{\n        triangle->SubEntities(2)};\n    // Loop over vertices and update size of largest adjacent triangle.\n    for (unsigned int i = 0; i < 3; ++i) {\n      // Note that 'size' is a reference!\n      double &size = sizeMeshDataSet(*vertices[i]);\n      // Current triangle is larger than those recorded earlier\n      if (newSize > size) {\n        // Update entry of auxiliary array\n        size = newSize;\n        // Store pointer to current triangle and local vertex index\n        KpMeshDataSet(*vertices[i]) = std::make_pair(triangle, i);\n      }\n    }\n  }  // end of loop over triangles\n  return KpMeshDataSet;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace QuasiInterpolation\n", "meta": {"hexsha": "93e81930be2ba987f1ddc667878e03f532e01e34", "size": 2797, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/QuasiInterpolation/mastersolution/quasiinterpolation.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/QuasiInterpolation/mastersolution/quasiinterpolation.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/QuasiInterpolation/mastersolution/quasiinterpolation.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 36.3246753247, "max_line_length": 80, "alphanum_fraction": 0.6589202717, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.5673164097251078}}
{"text": "#include \"dpmeans.hpp\"\n#include <iostream>\n#include <limits>\n#include <random>\n#include <cmath>\n#include <ctime>\n#include <unordered_set>\n#include <fstream>\n#include <vector>\n\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nmt19937 rng;\n\ndpmeans::dpmeans(const Ref<const MatrixXf>& X)\n{\n\tK = 1;\n\tK_init = 4;\n\tn = X.rows();\n\td = X.cols();\n\tz = VectorXi::Zero(n);        \n\tmu = MatrixXf::Zero(K, d);    \n\t\n\tnk = VectorXf::Zero(K);\n\tpik = VectorXf::Ones(K);\n\t\t\n    //init mu\n\tmu.row(0) = X.colwise().sum() / (float) n;\n\n\tcout << \"mu = \" << endl << mu << endl;\n    //init lambda\n\tlambda = kpp_init(X, K_init);\n\n\tmax_iter = 100;\n\tvector<double> obj(max_iter, 0);\n\tvector<double> em_time(max_iter, 0);\n}\n\nfloat dpmeans::kpp_init(const Ref<const MatrixXf>& X, int k)\n{\n\t// k++ init \n\t// lambda is max distance to k++ means\n\tfloat lambda = 0.0;\n\n\tint n = X.rows();\n\tint d = X.cols();\n\tMatrixXf mu = MatrixXf::Zero(k, d);\n\n\tVectorXf dist = VectorXf::Ones(n);\n\tVectorXf pdist = VectorXf::Zero(n);\n\tdist = dist * numeric_limits<float>::max();\n\n\tuniform_int_distribution<int> dis0n(0,n-1);\n\tuniform_real_distribution<float> dis01(0, 1);\n\tint idx = dis0n(rng);\n\t\n\tmu.row(0) = X.row(idx);\n\tMatrixXf D = MatrixXf::Zero(n, d);\n\t\n\tfor (int i = 1; i < k; ++i)\n\t{\n\t\tD = X - mu.row(i - 1).replicate(n, 1);\n\t\tdist = dist.cwiseMin(D.cwiseProduct(D).rowwise().sum());\n\t\t//cout << \"X = \" << endl << X << endl;\n\t\t//cout << \"mu = \" << endl << mu << endl;\n\t\t//cout << \"dist = \" << endl << dist << endl;\n\n\t\t//sample discrete\n\t\tpdist = dist / dist.sum();\n\n\t\tfor (int j = 1; j < pdist.size(); ++j)\n\t\t{\n\t\t\tpdist[j] = pdist[j] + pdist[j - 1];  //cumsum\n\t\t}\n\n\t\tint pidx = 0;\n\t\tfloat z01 = dis01(rng);\n\t\tfor (int item = 0; item < pdist.size(); ++item)\n\t\t{\n\t\t\tif (z01 < pdist[item])\n\t\t\t{\n\t\t\t\tpidx = item;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tmu.row(i) = X.row(pidx);\t\n\t\tlambda = dist.maxCoeff();\n\t}\n\n\treturn lambda;\n}\n\nVectorXi dpmeans::dpmeans_fit(const Ref<const MatrixXf>& X)\n{\n\n\tint n = X.rows(); \n\tint d = X.cols();\n\tint K = this->K;\n\tint max_iter = this->max_iter;\n\n\tdouble obj_tol = 1e-3;\n\tcout << \"running dp-means...\" << endl;\n\n\t//cout << \"X = \" << endl << X << endl;\n\tfor (int iter = 0; iter < max_iter; ++iter)\n\t{\n\t\tclock_t tic = clock();\n\t\tMatrixXf dist = MatrixXf::Zero(n, K);\n\t\t\n\t\t//assignment step\n\t\tMatrixXf Xm = MatrixXf::Zero(n, d);\n\t\tfor (int k = 0; k < K; ++k)\n\t\t{\n\t\t\tXm = X - mu.row(k).replicate(n, 1);\n\t\t\tdist.col(k) = Xm.cwiseProduct(Xm).rowwise().sum();\t\t\t\n\t\t}\n\t\t//cout << \"mu = \" << endl << mu << endl;\n\t\t//cout << \"dist = \" << endl << dist << endl;\n\n\t\t//update labels\n\t\tVectorXf dmin = VectorXf::Zero(n);\n\t\tfor (int ridx = 0; ridx < n; ++ridx)\n\t\t{\n\t\t\tMatrixXf::Index minIndex;\n\t\t\tdmin(ridx) = dist.row(ridx).minCoeff(&minIndex);\n\t\t\tz(ridx) = minIndex;\n\t\t}\n\t\t//cout << \"dmin = \" << endl << dmin << endl;\n\t\t//cout << \"z = \" << endl << z << endl;\n\t\t//cout << \"lambda = \" << endl << lambda << endl;\n\n\t\tVectorXi dmin_idx = VectorXi::Zero(n);\n\t\tfor (int ridx = 0; ridx < n; ++ridx)\n\t\t{\n\t\t\tif (dmin(ridx) > lambda)\n\t\t\t\tdmin_idx(ridx) = 1;\n\t\t}\n\t\tint num_new = dmin_idx.sum();\n\t\t//cout << \"num_new = \" << endl << num_new << endl;\n\n\t\tif (num_new > 0)\n\t\t{\n\t\t\t//create a new cluster for points\n\t\t\t//with dmin > lambda\n\t\t\tK = K + 1;\n\t\t\t//cout << \"K = \" << endl << K << endl;\n\n\t\t\tVectorXf new_mean = VectorXf::Zero(d);\n\t\t\tfor (int ridx = 0; ridx < n; ++ridx)\n\t\t\t{\n\t\t\t\t// if assigned to new cluster\n\t\t\t\tif (dmin_idx(ridx) > 0)\n\t\t\t\t{\n\t\t\t\t\tz(ridx) = K-1;  // cluster labels: [0,...,K-1]\n\t\t\t\t\tnew_mean = new_mean + X.row(ridx).transpose();\n\t\t\t\t}\n\t\t\t}\n\t\t\t//cout << \"z = \" << endl << z << endl;\n\t\t\tmu.conservativeResize(mu.rows() + 1, NoChange);\n\t\t\t//cout << \"new mean: \" << endl << new_mean << endl;\n\t\t\t//cout << \"num_new: \" << endl << num_new << endl;\n\t\t\tmu.row(K-1) = new_mean / (float) num_new;  // add new mean\t\t\n\n\t\t\tMatrixXf Xm = MatrixXf::Zero(n, d);\n\t\t\tXm = X - mu.row(K-1).replicate(n, 1);\n\t\t\tdist.conservativeResize(NoChange, dist.cols() + 1);\n\t\t\tdist.col(K-1) = Xm.cwiseProduct(Xm).rowwise().sum(); //add dist to new mean\t\t\t\n\t\t\t//cout << \"dist = \" << endl << dist << endl;\n\n\t\t}\n\n\t\t//update step\n\t\tnk = VectorXf::Zero(K);\n\t\tmu = MatrixXf::Zero(K, d);\n\t\t//for (int ridx = 0; ridx < z.size(); ++ridx) { nk(z(ridx))++; } //histogram\n\t\tfor (int k = 0; k < K; ++k)\n\t\t{\n\t\t\tnk(k) = (float) (z.array() == k).count();\n\n\t\t\tfor (int ridx = 0; ridx < z.size(); ++ridx)\n\t\t\t{\n\t\t\t\tif (z(ridx) == k)\n\t\t\t\t{\n\t\t\t\t\tmu.row(k) = mu.row(k) + X.row(ridx);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tmu.row(k) = mu.row(k) / nk(k);\n\t\t}\n\t\tpik = nk / nk.sum();\n\t\tcout << \"mu = \" << endl << mu << endl;\n\t\tcout << \"nk = \" << endl << nk << endl;\n\t\tcout << \"pik = \" << endl << pik << endl;\n\n\t\t//compute objective\n\t\tint kidx = 0;\n\t\tdouble suml2sq = 0.0;\n\t\tfor (int ridx = 0; ridx < n; ++ridx)\n\t\t{\n\t\t\tkidx = z(ridx);\n\t\t\tsuml2sq = suml2sq + dist(ridx, kidx);\n\t\t}\n\t\tsuml2sq += lambda * K;\n\t\tobj.push_back(suml2sq);\n\t\tcout << \"obj = \" << endl << suml2sq << endl;\n\n\t\t//check convergence\n\t\tif (iter > 0 && abs(obj.at(iter) - obj.at(iter - 1)) < obj_tol *obj.at(iter))\n\t\t{\n\t\t\tcout << \"converged in \" << iter << \" iterations.\" << endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tclock_t toc = clock();\n\t\tdouble elapsed_sec = double(toc - tic) / (double) CLOCKS_PER_SEC;\n\t\tcout << \"elapsed sec = \" << endl << elapsed_sec << endl;\n\t\tem_time.push_back(elapsed_sec);\t\t\n\t}\n\n\tthis->K = K;\n\n\treturn z;\n}\n\nfloat dpmeans::compute_nmi(const Ref<const VectorXi>& z1, const Ref<const VectorXi>& z2)\n{\n\t// compute normalized mutual information\n\tfloat nmi = 0.0;\n\n\tint n = z1.size();\n\n\t//compute number of unique\n\t//labels in z1 and z2\n\tunordered_set<int> s1;\n\tunordered_set<int> s2;\n\n\tint item;\n\titem = 0;\n\tfor (int idx = 0; idx < n; ++idx)\n\t{\n\t\titem = z1(idx);\n\t\ts1.insert(item);\n\t}\n\n\titem = 0;\n\tfor (int idx = 0; idx < n; ++idx)\n\t{\n\t\titem = z2(idx);\n\t\ts2.insert(item);\n\t}\n\n\tint k1 = s1.size();\n\tint k2 = s2.size();\n\n\tVectorXf nk1 = VectorXf::Zero(k1);\n\tVectorXf nk2 = VectorXf::Zero(k2);\n\tfor (int idx = 0; idx < k1; ++idx)\n\t{\n\t\tnk1(idx) = (float) (z1.array() == idx).count();\n\t}\n\tfor (int idx = 0; idx < k2; ++idx)\n\t{\n\t\tnk2(idx) = (float) (z2.array() == idx).count();\n\t}\n\n\tVectorXf pk1 = nk1 / (float)nk1.sum();\n\tVectorXf pk2 = nk2 / (float)nk2.sum();\n\n\tMatrixXi nk12 = MatrixXi::Zero(k1, k2);\n\tfor (int idx1 = 0; idx1 < k1; ++idx1)\n\t{\n\t\tfor (int idx2 = 0; idx2 < k2; ++idx2)\n\t\t{\n\t\t\tVectorXi b1 = VectorXi::Zero(n);\t\t\t\t\t\t\n\t\t\tb1 = (z1.array() == idx1).select(VectorXi::Ones(n), VectorXi::Zero(n));\n\n\t\t\tVectorXi b2 = VectorXi::Zero(n);\n\t\t\tb2 = (z2.array() == idx2).select(VectorXi::Ones(n), VectorXi::Zero(n));\n\n\t\t\tVectorXi b1b2 = b1.cwiseProduct(b2);\t\t\n\n\t\t\tnk12(idx1, idx2) = b1b2.sum();\n\t\t}\n\t}\n\tMatrixXf pk12 = nk12.cast<float>() / n;\n\tcout << \"nk12 = \" << endl << nk12 << endl;\n\tcout << \"pk12 = \" << endl << pk12 << endl;\n\n\tVectorXf logpk1 = (pk1 + numeric_limits<float>::epsilon()*VectorXf::Ones(k1)).array().log();\n\tVectorXf logpk2 = (pk2 + numeric_limits<float>::epsilon()*VectorXf::Ones(k2)).array().log();\n\tMatrixXf logpk12 = (pk12 + numeric_limits<float>::epsilon()*MatrixXf::Ones(k1, k2)).array().log();\n\n\tfloat Hx = -pk1.dot(logpk1);\n\tfloat Hy = -pk2.dot(logpk2);\n\tfloat Hxy = -pk12.cwiseProduct(logpk12).sum();\n\n\tfloat MI = Hx + Hy - Hxy;\n\tnmi = MI / (float) (0.5*(Hx + Hy));\n\n\treturn nmi;\n}\n\n\nvoid dpmeans::display_params()\n{\n\tcout << \"K = \" << this->K << endl;\n\tcout << \"K_init = \" << this->K_init << endl;\n\t//cout << \"Labels: \" << endl << this->z << endl;\n\tcout << \"Means: \" << endl << this->mu << endl;\n\tcout << \"Counts: \" << endl << this->nk << endl;\n\tcout << \"Proportions: \" << endl << this->pik << endl;\n\tcout << \"Lambda: \" << this->lambda << endl;\t\n}\n\nvoid load_iris(Ref<MatrixXf> X, Ref<VectorXi> y)\n{\t\n\t\n\t//read-in labels\n\tint cnt = 0;\n\tstring line;\n\tifstream fin2(\"./data/iris_labels.txt\");\n\tif (fin2.is_open())\n\t{\n\t\twhile (getline(fin2, line))\n\t\t{\n\t\t\ty(cnt) = stoi(line);\n\t\t\tcnt++;\n\t\t}\n\t\tfin2.close();\n\t}\n\telse cout << \"Unable to open fin2\\n\";\n\t//cout << \"y = \" << endl << y << endl;\n\t//cout << \"y.size = \" << endl << y.size() << endl;\n\n\t//read-in data\n\tcnt = 0;\n\tint nrows = 0;\n\tint ncols = 0;\n\tifstream fin3(\"./data/iris_data.txt\");\n\tif (fin3.is_open())\n\t{\n\t\tfin3 >> nrows >> ncols;\n\t\tfor (int row = 0; row < nrows; row++)\n\t\t\tfor (int col = 0; col < ncols; col++)\n\t\t\t{\n\t\t\t\tfloat num = 0.0;\n\t\t\t\tfin3 >> num;\n\t\t\t\tX(row, col) = num;\n\t\t\t}\n\t\tfin3.close();\n\t}\n\telse cout << \"Unable to open fin3\\n\";\n\t//cout << \"X = \" << endl << X << endl;\n\t\n}\n\nint main(int argc, char* argv[])\n{\t\n\t\n\t//generate data\n\t//int rows = 150, cols = 4;\n\t//MatrixXf X = MatrixXf::Random(rows, cols);\n\t\n\t//load iris\t\n\tint nrows = 0;\n\tint ncols = 0;\n\tstring line;\n\tifstream fin1(\"./data/iris_data.txt\");\n\tif (fin1.is_open())\n\t{\n\t\tfin1 >> nrows >> ncols;\n\t\tfin1.close();\n\t}\n\telse cout << \"Unable to open data file\\n\";\n\tcout << \"nrows = \" << nrows << endl;\n\tcout << \"ncols = \" << ncols << endl;\n\n\tVectorXi y = VectorXi::Zero(nrows);\n\tMatrixXf X = MatrixXf::Zero(nrows, ncols);\n\n\tload_iris(X,y);\n\t//cout << \"y = \" << endl << y << endl;\n\t//cout << \"X = \" << endl << X << endl;\n\t\n\tdpmeans dp(X);\n\tdp.display_params();\n\n\tVectorXi z;\n\tz = dp.dpmeans_fit(X);\n\t//cout << \"z = \" << endl << z << endl;\n\t\n\tfloat nmi;\n\tnmi = dp.compute_nmi(z, y);\n\tcout << \"nmi = \" << endl << nmi << endl;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "79e9bcf7be50689bf604f7d63da77841489f21dc", "size": 9163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "machine_learning/dpmeans/dpmeans.cpp", "max_stars_repo_name": "vishalbelsare/cpp", "max_stars_repo_head_hexsha": "772178d911e8f90c23e9d3c1d8d32482bc397fc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T03:20:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-06T09:46:17.000Z", "max_issues_repo_path": "machine_learning/dpmeans/dpmeans.cpp", "max_issues_repo_name": "kunalyadav684/cpp", "max_issues_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-01T22:30:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-01T22:30:50.000Z", "max_forks_repo_path": "machine_learning/dpmeans/dpmeans.cpp", "max_forks_repo_name": "kunalyadav684/cpp", "max_forks_repo_head_hexsha": "3ce14b012acb2dcdf91459fb677de4bd0cb46170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T22:44:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-19T10:18:16.000Z", "avg_line_length": 22.7935323383, "max_line_length": 99, "alphanum_fraction": 0.5548401179, "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430311279739, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5673164025877998}}
{"text": "/*******************************************************************************\n * examples/tutorial/k-means_step6.cpp\n *\n * Part of Project Thrill - http://project-thrill.org\n *\n * Copyright (C) 2016 Timo Bingmann <tb@panthema.net>\n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************/\n\n//! \\example examples/tutorial/k-means_step6.cpp\n//!\n//! This example is part of the k-means tutorial. See \\ref kmeans_tutorial_step6\n\n#include <thrill/api/all_gather.hpp>\n#include <thrill/api/cache.hpp>\n#include <thrill/api/generate.hpp>\n#include <thrill/api/print.hpp>\n#include <thrill/api/read_lines.hpp>\n#include <thrill/api/reduce_by_key.hpp>\n#include <thrill/api/sample.hpp>\n#include <thrill/api/write_lines.hpp>\n\n// Boost Spirit Qi is a header-only library\n#include <boost/spirit/include/qi.hpp>\n\n#include <ostream>\n#include <random>\n#include <sstream>\n#include <string>\n#include <vector>\n\n//! A 2-dimensional point with double precision\nstruct Point {\n    //! point coordinates\n    double x, y;\n\n    double DistanceSquare(const Point& b) const {\n        return (x - b.x) * (x - b.x) + (y - b.y) * (y - b.y);\n    }\n    Point operator + (const Point& b) const {\n        return Point { x + b.x, y + b.y };\n    }\n    Point operator / (double s) const {\n        return Point { x / s, y / s };\n    }\n};\n\n//! make ostream-able for Print()\nstd::ostream& operator << (std::ostream& os, const Point& p) {\n    return os << '(' << p.x << ',' << p.y << ')';\n}\n\n//! Assignment of a point to a cluster.\nstruct ClosestCenter {\n    size_t cluster_id;\n    Point  point;\n    size_t count;\n};\n//! make ostream-able for Print()\nstd::ostream& operator << (std::ostream& os, const ClosestCenter& cc) {\n    return os << '(' << cc.cluster_id\n              << ':' << cc.point << ':' << cc.count << ')';\n}\n\n//! our main processing method\nvoid Process(const thrill::DIA<Point>& points, const char* output) {\n\n    // print out the points\n    // points.Print(\"points\");\n\n    // pick some initial random cluster centers\n    thrill::DIA<Point> centers = points.Sample(/* num_clusters */ 10);\n\n    for (size_t iter = 0; iter < /* iterations */ 10; ++iter)\n    {\n        // collect centers in a local vector on each worker\n        std::vector<Point> local_centers = centers.AllGather();\n\n        auto new_centers =\n            points\n            // calculate the closest center for each point\n            .Map(\n                [local_centers](const Point& p) {\n                    double min_dist = p.DistanceSquare(local_centers[0]);\n                    size_t cluster_id = 0;\n\n                    for (size_t i = 1; i < local_centers.size(); ++i) {\n                        double dist = p.DistanceSquare(local_centers[i]);\n                        if (dist < min_dist)\n                            min_dist = dist, cluster_id = i;\n                    }\n                    return ClosestCenter { cluster_id, p, /* count */ 1 };\n                })\n            // new centers as the mean of all points associated with it\n            .ReduceByKey(\n                // key extractor: the cluster id\n                [](const ClosestCenter& cc) { return cc.cluster_id; },\n                // reduction: add points and the counter\n                [](const ClosestCenter& a, const ClosestCenter& b) {\n                    return ClosestCenter {\n                        a.cluster_id, a.point + b.point, a.count + b.count\n                    };\n                })\n            .Map([](const ClosestCenter& cc) {\n                     return cc.point / cc.count;\n                 });\n\n        // new_centers.Print(\"new_centers\");\n\n        // Collapse() is needed to fold lambda chain to DIA<Points>\n        centers = new_centers.Collapse();\n    }\n\n    if (output) {\n        // write output as \"x y\" lines\n        centers\n        .Map([](const Point& p) {\n                 return std::to_string(p.x) + \" \" + std::to_string(p.y);\n             })\n        .WriteLines(output);\n    }\n    else {\n        centers.Print(\"final centers\");\n    }\n}\n\nthrill::DIA<Point> GeneratePoints(thrill::Context& ctx) {\n    std::default_random_engine rng(std::random_device { } ());\n    std::uniform_real_distribution<double> dist(0.0, 1000.0);\n\n    // generate 100 random points using uniform distribution\n    auto points =\n        Generate(\n            ctx, /* size */ 100,\n            [&](const size_t&) {\n                return Point { dist(rng), dist(rng) };\n            });\n    // Execute() is require due to lazy evaluation\n    return points.Cache().Execute();\n}\n\n//! [step6 LoadPoints]\nthrill::DIA<Point> LoadPoints(thrill::Context& ctx, const char* path) {\n\n    // shorthand namespace\n    namespace qi = boost::spirit::qi;\n\n    // load points from text file\n    auto points =\n        ReadLines(ctx, path)\n        .Map(\n            [](const std::string& input) {\n                // parse \"<x> <y>\" lines\n                Point p;\n                std::string::const_iterator begin = input.begin(), end = input.end();\n\n                qi::phrase_parse(\n                    begin, end,                 // iterators\n                    qi::double_ >> qi::double_, // parser grammar: two doubles\n                    qi::ascii::space,           // skip grammar: spaces\n                    p.x, p.y);                  // put directly into the Point\n\n                if (begin != end)               // check that fully parsed\n                    die(\"Could not parse point coordinates: \" << input);\n                return p;\n            });\n    return points.Cache();\n}\n//! [step6 LoadPoints]\n\nint main(int argc, char* argv[]) {\n    // launch Thrill program: the lambda function will be run on each worker.\n    return thrill::Run(\n        [&](thrill::Context& ctx) {\n            if (argc == 1)\n                Process(GeneratePoints(ctx), nullptr);\n            else if (argc == 2)\n                Process(LoadPoints(ctx, argv[1]), nullptr);\n            else if (argc == 3)\n                Process(LoadPoints(ctx, argv[1]), argv[2]);\n            else\n                std::cerr << \"Usage: \" << argv[0]\n                          << \" [points] [output]\" << std::endl;\n        });\n}\n\n/******************************************************************************/\n", "meta": {"hexsha": "2872151c243d2fa6bff0b616e2df4720e495ce91", "size": 6292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/k-means_step6.cpp", "max_stars_repo_name": "stevenybw/thrill", "max_stars_repo_head_hexsha": "a2dc05035f4e24f64af0a22b60155e80843a5ba9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 609.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T11:09:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T21:34:05.000Z", "max_issues_repo_path": "examples/tutorial/k-means_step6.cpp", "max_issues_repo_name": "tim3z/thrill", "max_issues_repo_head_hexsha": "f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 109.0, "max_issues_repo_issues_event_min_datetime": "2015-09-10T21:34:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:46:26.000Z", "max_forks_repo_path": "examples/tutorial/k-means_step6.cpp", "max_forks_repo_name": "tim3z/thrill", "max_forks_repo_head_hexsha": "f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 114.0, "max_forks_repo_forks_event_min_datetime": "2015-08-27T14:54:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-08T07:28:35.000Z", "avg_line_length": 33.291005291, "max_line_length": 85, "alphanum_fraction": 0.5178003814, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5672518344919703}}
{"text": "#include <cmath>\n#include <memory>\n#include <fstream>\n#include <set>\n#include <numeric>\n#include <random>\n#include <iostream>\n\n#include <CandyPretty/CandyPretty.h>\n\n#include <boost/exception/all.hpp>\n#include <boost/variant.hpp>\n\n#if 0\n\n/*\n                D(t)V(t) = E~(D(T)V(T)|F(T))\n */\n\n/*\n        This is the analytic solution to geometric brownian motion with drift\n                        \n                dS = a S dt + b S dw\n\n */\n\n\n\n#include <ql/pricingengines/blackcalculator.hpp>\n\n\n\n\nstruct Differential{\n        virtual ~Differential()=default;\n        /*\n                dx = f(x,dt,dw)\n                x(t + dt ) = x(t) + dx(t)\n         */\n        virtual double Eval(double x, double dt, double std_norm)const=0;\n};\n\nstruct ProcessContext;\n\nstruct ProcessIntegral{\n        ProcessIntegral()=default;\n        ProcessIntegral(ProcessContext& ctx, double x, std::shared_ptr<Differential> dx);\n        void SmallChange(double dt, double std_norm){\n                x_ += dx_->Eval( x_, dt, std_norm );\n        }\n        double Value()const{ return x_; }\nprivate:\n        double x_;\n        std::shared_ptr<Differential> dx_;\n};\n\nstruct ProcessContext{\n        void Register(ProcessIntegral* ptr){\n                procs_.push_back(ptr);\n        }\n        void Step(double dt){\n                auto std_norm = [&](){ return D_(G_); };\n                for(auto ptr : procs_){\n                        ptr->SmallChange(dt, std_norm());\n                }\n        }\nprivate:\n        #if 0\n        std::default_random_engine G_;\n        #else\n        std::random_device G_;\n        #endif\n        std::normal_distribution<double> D_{0.0, 1.0};\n        std::vector<ProcessIntegral*> procs_;\n};\n\ninline ProcessIntegral::ProcessIntegral(ProcessContext& ctx, double x, std::shared_ptr<Differential> dx)\n        :x_(x),\n        dx_(dx)\n{\n        ctx.Register(this);\n}\n\nstruct ProcessView{\n        struct Impl{\n                virtual ~Impl()=default;\n                virtual double Value()const=0;\n        };\n        struct SptrImpl : Impl{\n                explicit SptrImpl(std::shared_ptr<ProcessIntegral const> q_) :q(q_) {}\n                virtual double Value()const{ return q->Value(); }\n                std::shared_ptr<ProcessIntegral const> q;\n        };\n\n        ProcessView()=default;\n        ProcessView(std::shared_ptr<ProcessIntegral> p){\n                impl_ = std::make_shared<SptrImpl>(p);\n        }\n        // assumes objects lifetime exists for as long as it'self\n        ProcessView(ProcessIntegral const& p){\n                std::shared_ptr<ProcessIntegral const> aux(&p, [](auto*){});\n                impl_ = std::make_shared<SptrImpl>(aux);\n        }\n        \n        ProcessView& operator=(std::shared_ptr<ProcessIntegral> p){\n                impl_ = std::make_shared<SptrImpl>(p);\n                return *this;\n        }\n        ProcessView& operator=(ProcessIntegral const& p){\n                std::shared_ptr<ProcessIntegral const> aux(&p, [](auto*){});\n                impl_ = std::make_shared<SptrImpl>(aux);\n                return *this;\n        }\n        \n        \n        double Value()const{ return impl_->Value(); }\n\n        // for printing to csv etc\n        // this is how it is set, p.Name()  = \"Discount ProcessIntegral()\"\n        std::string& Name(){ return name_; }\n        std::string const& Name()const{ return name_; }\nprotected:\n        std::shared_ptr<Impl> impl_;\n        std::string name_{\"ProcessIntegral\"};\n};\n\n\n\nstruct IdentityDifferential : Differential{\n        virtual double Eval(double x, double dt, double std_norm)const override{\n                return dt;\n        }\n};\n\nstruct BankAccountDifferential : Differential{\n        explicit BankAccountDifferential(ProcessView interest_rate)\n                :interest_rate_(interest_rate)\n        {}\n        virtual double Eval(double x, double dt, double std_norm)const override{\n                return x * interest_rate_.Value() * dt;\n        }\nprivate:\n        ProcessView interest_rate_;\n};\n\nstruct GeometricBrownianMotionWithDriftDifferential : Differential{\n        GeometricBrownianMotionWithDriftDifferential(double S0, double r, double sigma)\n                :S0_(S0),\n                r_(r),\n                sigma_(sigma)\n        {}\n        virtual double Eval(double x, double dt, double std_norm)const override{\n                double a = r_ * dt + sigma_ * std_norm * std::sqrt(dt);\n                double b = a * x;\n                return b;\n        }\nprivate:\n        double S0_;\n        double r_;\n        double sigma_;\n};\n\nstruct VasicekDifferential : Differential{\n        VasicekDifferential(double alpha, double beta, double sigma)\n                :alpha_(alpha),\n                beta_(beta),\n                sigma_(sigma)\n        {}\n        virtual double Eval(double x, double dt, double std_norm)const override{\n                double a = ( alpha_ - beta_ * x ) * dt;\n                double b = sigma_ * std_norm * std::sqrt(dt);\n                double c = a + b;\n                return c;\n        }\nprivate:\n        double alpha_;\n        double beta_;\n        double sigma_;\n};\nstruct CoxIngersollRos : Differential{\n        CoxIngersollRos(double alpha, double beta, double sigma)\n                :alpha_(alpha),\n                beta_(beta),\n                sigma_(sigma)\n        {}\n        virtual double Eval(double x, double dt, double std_norm)const override{\n                double a = ( alpha_ - beta_ * x ) * dt;\n                double b = sigma_ * std::sqrt(x) *  std_norm * std::sqrt(dt);\n                double c = a + b;\n                return c;\n        }\nprivate:\n        double alpha_;\n        double beta_;\n        double sigma_;\n};\n\n\n\n\n\nstruct AnaBlack : ProcessView{\n        AnaBlack(ProcessView t){\n                struct AnaBlackImpl : Impl{\n                        AnaBlackImpl(ProcessView t)\n                                :t_(t)\n                        {}\n                        virtual double Value()const override{\n                                double r = 0.02;\n                                double vol = 0.1;\n                                double s0 = 10.0;\n                                double k = 1.5 * s0;\n\n\n                                double T = t_.Value();\n                                auto discount = std::exp( -r * T );\n                                auto fwd = s0 / discount;\n                                auto std_dev = std::sqrt( vol * vol * T);\n                                QuantLib::BlackCalculator bc(QuantLib::Option::Call,\n                                                             k,\n                                                             fwd,\n                                                             std_dev,\n                                                             discount);\n                                return bc.value();\n                        }\n                private:\n                        ProcessView t_;\n                };\n                impl_ = std::make_shared<AnaBlackImpl>(t);\n        }\n};\n\nstruct DiscountProcess : ProcessView{\n        DiscountProcess(ProcessView t, double r){\n                struct DPImpl : Impl{\n                        DPImpl(ProcessView t_, double r_)\n                                :t(t_),\n                                r(r_)\n                        {}\n                        virtual double Value()const override{\n                                return std::exp( - t.Value() * r );\n                        }\n                private:\n                        ProcessView t;\n                        double r;\n                };\n                impl_ = std::make_shared<DPImpl>(t,r);\n        }\n};\n\nstruct AverageView : ProcessView{\n        struct Final : Impl{\n                virtual double Value()const override{\n                        size_t n = v_.size();\n                        double sigma = 0.0;\n                        for(size_t idx=0;idx!=n;++idx){\n                                sigma +=  v_[idx].Value();\n                        }\n                        return sigma / n;\n                }\n        private:\n                friend struct AverageView;\n                std::vector<ProcessView> v_;\n        };\n        AverageView(){\n                impl_ = std::make_shared<Final>();\n        }\n        AverageView& Add(ProcessView view){\n                auto casted = dynamic_cast<Final*>(impl_.get());\n                casted->v_.push_back(view);\n                return *this;\n        }\n        template<class Iter>\n        AverageView(Iter first, Iter last){\n                impl_ = std::make_shared<Final>();\n                for(;first!=last;++first){\n                        Add(*first);\n                }\n        }\n};\n\nstruct Option : ProcessView{\n        Option(ProcessView process, double strike){\n                struct OptionImpl : Impl{\n                        OptionImpl(ProcessView process, double strike)\n                                :process_(process),\n                                strike_(strike)\n                        {}\n                        virtual double Value()const override{\n                                return (std::max)(process_.Value() - strike_, 0.0);\n                        }\n                private:\n                        ProcessView process_;\n                        double strike_;\n                };\n                impl_ = std::make_shared<OptionImpl>(process, strike);\n        }\n};\n\nstruct ProcessViewRenderer{\n        ProcessViewRenderer(std::ostream& out, std::vector<ProcessView> const& views)\n                :out_{std::shared_ptr<std::ostream>(&out, [](auto*){})}, views_(views)\n        {\n                EmitHeader_();\n        }\n        ProcessViewRenderer(std::shared_ptr<std::ostream> out, std::vector<ProcessView> const& views)\n                :out_{out}, views_(views)\n        {\n                EmitHeader_();\n        }\n        void RenderLine(){\n                std::vector<std::string> line;\n                for(auto const& view : views_){\n                        line.push_back(boost::lexical_cast<std::string>(view.Value()));\n                }\n                lines_.push_back(std::move(line));\n        }\n        void Emit(){\n                CandyPretty::RenderTablePretty(*out_, lines_, opts_);\n        }\nprivate:\n        void EmitHeader_(){\n                std::vector<std::string> line;\n                for(auto const& view : views_){\n                        line.push_back(boost::lexical_cast<std::string>(view.Name()));\n                }\n                lines_.push_back(std::move(line));\n        }\n        CandyPretty::RenderOptions opts_{CandyPretty::RenderOptions::CsvOptions()};\n        std::shared_ptr<std::ostream> out_;\n        std::vector<ProcessView> views_;\n        std::vector<CandyPretty::LineItem> lines_;\n};\n\nvoid example_0(){\n        using namespace CandyPretty;\n\n        double r = 0.02;\n        double vol = 0.1;\n        double T = 20;\n        double s0 = 10.0;\n\n        auto gbm = std::make_shared<GeometricBrownianMotionWithDriftDifferential>(s0, r, vol);\n\n        enum{ SampleSize = 4000 };\n        ProcessContext ctx;\n        auto t = std::make_shared<ProcessIntegral>(ctx, 0, std::make_shared<IdentityDifferential>() );\n\n        std::vector<std::shared_ptr<ProcessIntegral> > gbm_sample(SampleSize);\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                gbm_sample[idx] = std::make_shared<ProcessIntegral>(ctx, s0, gbm);\n        }\n\n        DiscountProcess disc(t, r);\n\n        std::vector<AverageView> avg_vec;\n        auto first = &gbm_sample[0];\n        avg_vec.emplace_back( first, first + 10);\n        avg_vec.back().Name() = \"Avg_{10}\";\n        avg_vec.emplace_back( first, first + 100);\n        avg_vec.back().Name() = \"Avg_{100}\";\n        avg_vec.emplace_back( first, first + 1000);\n        avg_vec.back().Name() = \"Avg_{1000}\";\n        avg_vec.emplace_back( first, first + 2000);\n        avg_vec.back().Name() = \"Avg_{2000}\";\n        avg_vec.emplace_back( first, first + 4000);\n        avg_vec.back().Name() = \"Avg_{4000}\";\n\n        \n        std::vector<ProcessView> views;\n        views.push_back(t);\n        views.back().Name() = \"t\";\n        views.push_back(disc);\n        views.back().Name() = \"D(t)\";\n        for(auto const& _ : avg_vec){\n                views.push_back(_);\n        }\n        enum{ GbmViews = 20 };\n        for(size_t idx=0;idx < gbm_sample.size() && idx < GbmViews;++idx){\n                views.push_back(gbm_sample[idx]);\n                std::stringstream sstr;\n                sstr << \"W_{\" << idx << \"}(t)\";\n                views.back().Name() = sstr.str();\n        }\n\n        std::vector<ProcessView>* render_view = &views;\n        \n        #if 0\n\n        AnaBlack black( t);\n\n        std::vector<ProcessView> call_view;\n        call_view.push_back(t);\n        call_view.push_back(disc);\n        call_view.push_back(black);\n\n        std::vector<ProcessView> call_options(SampleSize);\n        std::vector<std::pair<AverageView, size_t> > call_avg;\n        call_avg.emplace_back(AverageView(), 10);\n        call_avg.emplace_back(AverageView(), 100);\n        call_avg.emplace_back(AverageView(), 1000);\n        call_avg.emplace_back(AverageView(), 2000);\n        call_avg.emplace_back(AverageView(), 4000);\n        for(auto& _ : call_avg){\n                call_view.push_back(_.first);\n        }\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                auto& p = gbm_sample[idx];\n                call_options[idx] = Option(p, k);\n                for(auto& _ : call_avg){\n                        if( idx < _.second ){\n                                _.first.Add(call_options[idx]);\n                        }\n                }\n        }\n\n\n\n\n\n\n\n        double ir_0 = 0.05;\n        auto f = 10.0;\n        auto ir_diff = std::make_shared<VasicekDifferential>(1/f, 20/f, 0.1);\n        std::vector<ProcessIntegral> bank_acct_sample(SampleSize);\n        std::vector<ProcessView> ir_view;\n        AverageView bank_acct_avg;\n        AverageView ir_avg;\n\n        ir_view.push_back(t);\n        ir_view.push_back(ir_avg);\n        ir_view.push_back(bank_acct_avg);\n\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                auto irp_p = std::make_shared<ProcessIntegral>(ir_0, ir_diff);\n                ProcessView irp(irp_p);\n                procs.push_back(irp_p.get());\n                auto bank_acct_diff = std::make_shared<BankAccountDifferential>(irp);\n                auto bank_acct_p = std::make_shared<ProcessIntegral>(1.0, bank_acct_diff);\n                ProcessView bank_acct(bank_acct_p);\n                procs.push_back(bank_acct_p.get());\n\n                if( idx < GbmViews ){\n                        ir_view.push_back(irp);\n                        ir_view.push_back( bank_acct);\n                }\n                ir_avg.Add(irp);\n                bank_acct_avg.Add(bank_acct);\n        }\n        #endif\n        \n        \n\n\n        size_t N = 1000;\n        double dt = T / N;\n\n        std::ofstream of{\"RiskNeutralBrownianMotion.csv\"};\n        if( ! of.is_open() )\n                BOOST_THROW_EXCEPTION(std::domain_error(\"unable to open RiskNeutralBrownianMotion.csv\"));\n        ProcessViewRenderer renderer{of, *render_view};\n\n        for(size_t idx=0;idx!=N;++idx){\n                ctx.Step(dt);\n                renderer.RenderLine();\n        }\n        renderer.Emit();\n}\n\n\nvoid example_1(){\n        using namespace CandyPretty;\n\n        double r = 0.02;\n        double vol = 0.1;\n        double T = 40;\n        double s0 = 10.0;\n        double k = 1.5 * s0;\n\n        auto gbm = std::make_shared<GeometricBrownianMotionWithDriftDifferential>(s0, r, vol);\n\n        enum{ SampleSize = 4000 };\n        ProcessContext ctx;\n        auto t = std::make_shared<ProcessIntegral>(ctx, 0, std::make_shared<IdentityDifferential>() );\n\n        std::vector<std::shared_ptr<ProcessIntegral> > gbm_sample(SampleSize);\n        std::vector<ProcessView> call_options(SampleSize);\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                gbm_sample[idx] = std::make_shared<ProcessIntegral>(ctx, s0, gbm);\n                call_options[idx] = Option(gbm_sample[idx], k);\n        }\n\n        DiscountProcess disc(t, r);\n        \n        AnaBlack black( t);\n\n        std::vector<AverageView> avg_vec;\n        auto first = &call_options[0];\n        avg_vec.emplace_back( first, first + 10);\n        avg_vec.back().Name() = \"Avg_{10}\";\n        avg_vec.emplace_back( first, first + 100);\n        avg_vec.back().Name() = \"Avg_{100}\";\n        avg_vec.emplace_back( first, first + 1000);\n        avg_vec.back().Name() = \"Avg_{1000}\";\n        avg_vec.emplace_back( first, first + 2000);\n        avg_vec.back().Name() = \"Avg_{2000}\";\n        avg_vec.emplace_back( first, first + 4000);\n        avg_vec.back().Name() = \"Avg_{4000}\";\n\n        \n        std::vector<ProcessView> views;\n        views.push_back(t);\n        views.back().Name() = \"t\";\n        views.push_back(disc);\n        views.back().Name() = \"D(t)\";\n        views.push_back(black);\n        views.back().Name() = \"BS(.)\";\n        for(auto const& _ : avg_vec){\n                views.push_back(_);\n        }\n        enum{ GbmViews = 20 };\n        for(size_t idx=0;idx < call_options.size() && idx < GbmViews;++idx){\n                views.push_back(call_options[idx]);\n                std::stringstream sstr;\n                sstr << \"Call_{\" << idx << \"}(t)\";\n                views.back().Name() = sstr.str();\n        }\n\n        std::vector<ProcessView>* render_view = &views;\n        \n        #if 0\n\n\n        std::vector<ProcessView> call_view;\n        call_view.push_back(t);\n        call_view.push_back(disc);\n        call_view.push_back(black);\n\n        std::vector<ProcessView> call_options(SampleSize);\n        std::vector<std::pair<AverageView, size_t> > call_avg;\n        call_avg.emplace_back(AverageView(), 10);\n        call_avg.emplace_back(AverageView(), 100);\n        call_avg.emplace_back(AverageView(), 1000);\n        call_avg.emplace_back(AverageView(), 2000);\n        call_avg.emplace_back(AverageView(), 4000);\n        for(auto& _ : call_avg){\n                call_view.push_back(_.first);\n        }\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                auto& p = gbm_sample[idx];\n                call_options[idx] = Option(p, k);\n                for(auto& _ : call_avg){\n                        if( idx < _.second ){\n                                _.first.Add(call_options[idx]);\n                        }\n                }\n        }\n\n\n\n\n\n\n\n        double ir_0 = 0.05;\n        auto f = 10.0;\n        auto ir_diff = std::make_shared<VasicekDifferential>(1/f, 20/f, 0.1);\n        std::vector<ProcessIntegral> bank_acct_sample(SampleSize);\n        std::vector<ProcessView> ir_view;\n        AverageView bank_acct_avg;\n        AverageView ir_avg;\n\n        ir_view.push_back(t);\n        ir_view.push_back(ir_avg);\n        ir_view.push_back(bank_acct_avg);\n\n        for(size_t idx=0;idx!=SampleSize;++idx){\n                auto irp_p = std::make_shared<ProcessIntegral>(ir_0, ir_diff);\n                ProcessView irp(irp_p);\n                procs.push_back(irp_p.get());\n                auto bank_acct_diff = std::make_shared<BankAccountDifferential>(irp);\n                auto bank_acct_p = std::make_shared<ProcessIntegral>(1.0, bank_acct_diff);\n                ProcessView bank_acct(bank_acct_p);\n                procs.push_back(bank_acct_p.get());\n\n                if( idx < GbmViews ){\n                        ir_view.push_back(irp);\n                        ir_view.push_back( bank_acct);\n                }\n                ir_avg.Add(irp);\n                bank_acct_avg.Add(bank_acct);\n        }\n        #endif\n        \n        \n\n\n        size_t N = 1000;\n        double dt = T / N;\n\n        std::ofstream of{\"CallOption.csv\"};\n        if( ! of.is_open() )\n                BOOST_THROW_EXCEPTION(std::domain_error(\"unable to open CallOption.csv\"));\n        ProcessViewRenderer renderer{of, *render_view};\n\n        for(size_t idx=0;idx!=N;++idx){\n                ctx.Step(dt);\n                renderer.RenderLine();\n        }\n        renderer.Emit();\n}\n\n\nvoid example_2(){\n        using namespace CandyPretty;\n\n        double r = 0.02;\n        double vol = 0.1;\n        double T = 40;\n        double s0 = 10.0;\n\n        enum{ SampleSize = 4000 };\n\n        ProcessContext ctx;\n\n        auto t = std::make_shared<ProcessIntegral>(ctx, 0, std::make_shared<IdentityDifferential>() );\n\n        std::vector<ProcessView> interest_rate_samples(SampleSize);\n        std::vector<ProcessView> bank_account_samples(SampleSize);\n\n        double ir_0 = 0.05;\n        auto f = 10.0;\n        auto ir_diff = std::make_shared<VasicekDifferential>(1/f, 20/f, 0.1);\n        \n        for(size_t idx=0;idx!=SampleSize;++idx){\n                interest_rate_samples[idx] = std::make_shared<ProcessIntegral>(ctx, ir_0, ir_diff);\n                auto bank_acct_diff = std::make_shared<BankAccountDifferential>(interest_rate_samples[idx]);\n                bank_account_samples[idx]  = std::make_shared<ProcessIntegral>(ctx, 1.0, bank_acct_diff);\n        }\n\n        \n        std::vector<AverageView> avg_vec;\n        auto first = &bank_account_samples[0];\n        avg_vec.emplace_back( first, first + 10);\n        avg_vec.back().Name() = \"Avg_{10}\";\n        avg_vec.emplace_back( first, first + 100);\n        avg_vec.back().Name() = \"Avg_{100}\";\n        avg_vec.emplace_back( first, first + 1000);\n        avg_vec.back().Name() = \"Avg_{1000}\";\n        avg_vec.emplace_back( first, first + 2000);\n        avg_vec.back().Name() = \"Avg_{2000}\";\n        avg_vec.emplace_back( first, first + 4000);\n        avg_vec.back().Name() = \"Avg_{4000}\";\n\n        \n        std::vector<ProcessView> views;\n        views.push_back(t);\n        views.back().Name() = \"t\";\n        for(auto const& _ : avg_vec){\n                views.push_back(_);\n        }\n        enum{ GbmViews = 20 };\n        for(size_t idx=0;idx < SampleSize && idx < GbmViews;++idx){\n                std::stringstream sstr;\n                views.push_back(interest_rate_samples[idx]);\n                sstr << \"R_{\" << idx << \"}(t)\";\n                views.back().Name() = sstr.str();\n                views.push_back(bank_account_samples[idx]);\n                sstr.str(\"\");\n                sstr << \"B_{\" << idx << \"}(t)\";\n                views.back().Name() = sstr.str();\n        }\n\n        std::vector<ProcessView>* render_view = &views;\n        \n\n\n        size_t N = 1000;\n        double dt = T / N;\n\n        std::ofstream of{\"BankAccount.csv\"};\n        if( ! of.is_open() )\n                BOOST_THROW_EXCEPTION(std::domain_error(\"unable to open BankAccount.csv\"));\n        ProcessViewRenderer renderer{of, *render_view};\n\n        for(size_t idx=0;idx!=N;++idx){\n                ctx.Step(dt);\n                renderer.RenderLine();\n        }\n        renderer.Emit();\n}\n\n#endif\n\nstruct Omega{};\nstruct Nul{};\nstruct Not;\nstruct Union;\nstruct Intersection;\nstruct Interval;\n\nusing BorelSet = boost::variant<\n        Omega,\n        Nul,\n        boost::recursive_wrapper<Not>,\n        boost::recursive_wrapper<Union>,\n        boost::recursive_wrapper<Intersection>,\n        boost::recursive_wrapper<Interval>\n>;\n\nstruct Not{\n        BorelSet child;\n};\nstruct Union{\n        template<class... Args>\n        Union(Args&&... args):children{args...}{}\n\n        void Add(Union const& that){\n                for(auto const& _ : that.children)\n                        children.push_back(_);\n        }\n\n        std::vector<BorelSet> children;\n};\nstruct Intersection{\n        template<class... Args>\n        Intersection(Args&&... args):children{args...}{}\n\n        void Add(Intersection const& that){\n                for(auto const& _ : that.children)\n                        children.push_back(_);\n        }\n\n        std::vector<BorelSet> children;\n};\nstruct IntervalEndPoint{\n        friend std::ostream& operator<<(std::ostream& ostr, IntervalEndPoint const& self){\n                ostr << \"IntervalEndPoint{is_open = \" << self.is_open;\n                ostr << \", point = \" << self.point << \"}\";\n                return ostr;\n        }\n        bool operator<(IntervalEndPoint const& that)const{\n                if( point != that.point )\n                        return point < that.point;\n                return is_open < that.is_open;\n        }\n        bool operator==(IntervalEndPoint const& that)const{\n                return point == that.point && is_open == that.is_open;\n        }\n        bool operator!=(IntervalEndPoint const& that)const{\n                return ! operator==(that);\n        }\n        bool is_open;\n        double point;\n\n        IntervalEndPoint Switch()const{ return IntervalEndPoint{ ! is_open, point }; }\n};\nIntervalEndPoint Open(double x){\n        return IntervalEndPoint{true, x};\n}\nIntervalEndPoint Closed(double x){\n        return IntervalEndPoint{false, x};\n}\n\nstruct IntervalUnion{\n        template<class... Args>\n        IntervalUnion(Args&&... args):children{args...}{}\n        \n        void Add(IntervalUnion const& that){\n                for(auto const& _ : that.children)\n                        children.push_back(_);\n        }\n\n        std::vector<Interval> children;\n\n        operator Union()const{\n                return AsUnion();\n        }\n        Union AsUnion()const{\n                Union tmp;\n                for(auto const& _ : children )\n                        tmp.children.push_back(_);\n                return tmp;\n        }\n\n        #if 0\n        bool operator==(IntervalUnion const& that)const{\n                return children == that.children;\n        }\n        bool operator!=(IntervalUnion const& that)const{\n                return ! operator==(that);\n        }\n        #endif\n        bool operator<(IntervalUnion const& that)const{\n                if( children.size() != that.children.size() ){\n                        return  children.size() < that.children.size();\n                }\n                return children < that.children;\n        }\n};\n\nstruct Interval{\n        IntervalEndPoint left;\n        IntervalEndPoint right;\n\n        static Interval Closed(double x, double y){\n                return Interval{ IntervalEndPoint{ false, x},\n                                 IntervalEndPoint{ false, y} };\n        }\n        static Interval Open(double x, double y){\n                return Interval{ IntervalEndPoint{ false, x},\n                                 IntervalEndPoint{ false, y} };\n        }\n\n        bool operator<(Interval const& that)const{\n                if( left != that.left )\n                        return left < that.left;\n                return right < that.right;\n        }\n\n\n        // homogenous operations are here\n        IntervalUnion Not()const{\n                IntervalUnion result;\n\n                /*\n                        A) this  \\subset world => this\n                        B) world \\subset this => that\n\n                 */\n\n                if( left.point > right.point )\n                        return result;\n\n                if( 0.0 == left.point && left.is_open ){\n                        result.children.push_back(Interval::Closed(0.0, 0.0));\n                } else if( 0.0 < left.point ){\n                        result.children.push_back(Interval{ IntervalEndPoint{false, 0.0}, \n                                                   left.Switch() } );\n                }\n\n                if( 1.0 == right.point && right.is_open ){\n                        result.children.push_back(Interval::Closed(1.0, 1.0));\n                } else if( right.point < 1.0 ){\n                        result.children.push_back(Interval{ right.Switch(),       \n                                                   IntervalEndPoint{false, 1.0} } );\n                }\n\n                return result;\n        }\n\n        bool IsSubsetOf(Interval const& that)const{\n                if( that.left.point > left.point )\n                        return false;\n                if( that.left.point ==left.point ){\n                        if( that.left.is_open != left.is_open && that.left.is_open )\n                                return false;\n                }\n                if( that.right.point < right.point )\n                        return false;\n                if( that.right.point ==right.point ){\n                        if( that.right.is_open != right.is_open && that.right.is_open )\n                                return false;\n                }\n                return true;\n        }\n\n};\n\n\n\n\nstruct SortIntervalUnions{\n        bool operator()(Union const& a, Union const& b)const{\n                if( a.children.size() != b.children.size() )\n                        return a.children.size() < b.children.size();\n                for(size_t idx=0;idx!=a.children.size();++idx){\n                        auto a_interval = boost::get<Interval>(&a.children[idx]);\n                        auto b_interval = boost::get<Interval>(&b.children[idx]);\n                        BOOST_ASSERT( a_interval );\n                        BOOST_ASSERT( b_interval );\n                        if( a_interval->left != b_interval->left )\n                                return  a_interval->left < b_interval->left;\n                        if( a_interval->right != b_interval->right )\n                                return  a_interval->right < b_interval->right;\n                }\n                return false;\n        }\n};\n\nstd::string ToString(BorelSet const& b){\n        struct ToStringImpl{\n                void operator()(Omega const&){\n                        ostr_ << \"Omega\";\n                }\n                void operator()(Nul const&){\n                        ostr_ << \"Nul\";\n                }\n                void operator()(Not const& obj){\n                        ostr_ << \"Not{\";\n                        boost::apply_visitor(*this, obj.child);\n                        ostr_ << \"}\";\n                }\n                void operator()(Union const& obj){\n                        ostr_ << \"Union{\";\n                        for(size_t idx=0;idx!=obj.children.size();++idx){\n                                if( idx != 0 )\n                                        ostr_ << \", \";\n                                boost::apply_visitor(*this, obj.children[idx]);\n                        }\n                        ostr_ << \"}\";\n                }\n                void operator()(Intersection const& obj){\n                        ostr_ << \"Intersection{\";\n                        for(size_t idx=0;idx!=obj.children.size();++idx){\n                                if( idx != 0 )\n                                        ostr_ << \", \";\n                                boost::apply_visitor(*this, obj.children[idx]);\n                        }\n                        ostr_ << \"}\";\n                }\n                void operator()(Interval const& i){\n                        ostr_ << ( i.left.is_open ? \"(\" : \"[\" );\n                        ostr_ << i.left.point;\n                        ostr_ << \",\";\n                        ostr_ << i.right.point;\n                        ostr_ << ( i.right.is_open ? \")\" : \"]\" );\n                }\n                std::stringstream ostr_;\n        };\n        ToStringImpl impl;\n        boost::apply_visitor(impl, b);\n        return impl.ostr_.str();\n}\n\nvoid Display(BorelSet const& b){\n        std::cout << ToString(b) << \"\\n\";\n}\n\n\n\nIntervalUnion ToIntervals(BorelSet const& b){\n        struct ToIntervalsImpl : boost::static_visitor<IntervalUnion>{\n                IntervalUnion operator()(Omega const&)const{\n                        return IntervalUnion{Interval::Closed(0,1)};\n                }\n                IntervalUnion operator()(Nul const&)const{\n                        return IntervalUnion{};\n                }\n                IntervalUnion operator()(Not const& obj)const{\n                        Union result;\n                        for(auto const& i : boost::apply_visitor(*this, obj.child).children ){\n                                result.Add( i.Not().AsUnion() );\n                        }\n                        return operator()(result);\n                }\n                IntervalUnion operator()(Union const& obj)const{\n                        IntervalUnion mapped;\n                        for(auto const& _ : obj.children ){\n                                for( auto const& inner : boost::apply_visitor(*this,_).children ){\n                                        mapped.children.push_back(inner);\n                                }\n                        }\n                        std::vector<Interval const*> subs;\n                        for(auto const& _ : mapped.children ){\n                                subs.push_back(&_);\n                        }\n                        boost::sort( subs, [](auto const& l, auto const& r){\n                                if( l->left.point != r->left.point )\n                                        return l->left.point < r->left.point;\n                                // prefer closed\n                                return l->left.is_open < r->left.is_open;\n                        });\n\n                        IntervalUnion result;\n                        size_t iter = 0;\n                        for(;iter!=subs.size();++iter){\n                                if( subs[iter] == 0 )\n                                        continue;\n\n                                // for debugging\n                                std::vector<Interval const*> dbg_path;\n                                dbg_path.push_back(subs[iter]);\n\n                                IntervalEndPoint left  = subs[iter]->left;\n                                IntervalEndPoint right = subs[iter]->right;\n                                // what is the largest path we can construct\n                                subs[iter] = 0;\n                                for(size_t j=iter+1;j!=subs.size();){\n                                        if( subs[j] == 0 ){\n                                                ++j;\n                                                continue;\n                                        }\n                                        auto head = subs[j];\n\n                                        // do these overlap?\n                                        if( head->left.point < right.point ||\n                                           (head->left.point ==right.point && ! (head->left.is_open && right.is_open) ) ){\n\n                                                // now can we extend right?\n                                                if( right.point < head->right.point ||\n                                                   (right.point ==head->right.point && right.is_open && !head->right.is_open ) ){\n                                                        right = head->right;\n                                                        dbg_path.push_back(head);\n                                                        // restart nice and slow\n                                                        j = iter+1;\n                                                        continue;\n                                                }\n                                        }\n                                        ++j;\n                                }\n                                Interval i{left, right};\n\n                                for(size_t j=iter+1;j!=subs.size();++j){\n                                        if( subs[j] == 0 )\n                                                continue;\n                                        if( subs[j]->IsSubsetOf(i) ){\n                                                subs[j] = 0;\n                                        }\n                                }\n\n\n                                result.children.push_back(i);\n\n                        }\n\n                        return result;\n                }\n                IntervalUnion operator()(Intersection const& obj)const{\n                        if( obj.children.empty() )\n                                return IntervalUnion{};\n                        IntervalUnion mapped;\n                        for(auto const& _ : obj.children ){\n                                for(auto const& inner : boost::apply_visitor(*this,_).children ){\n                                        mapped.children.push_back(inner);\n                                }\n                        }\n\n\n                        auto first = &mapped.children.at(0);\n\n                        IntervalEndPoint const* upper_left  = &first->left;\n                        IntervalEndPoint const* lower_right = &first->right;\n\n\n                        for(auto const& i : mapped.children ){\n                                auto ptr = &i;\n\n                                if( upper_left->point < ptr->left.point )\n                                        upper_left = &ptr->left;\n                                else if(  upper_left->point == ptr->left.point && \n                                          ! upper_left->is_open && \n                                          ptr->left.is_open )\n                                        upper_left = &ptr->left;\n                                \n                                if( lower_right->point > ptr->right.point )\n                                        lower_right = &ptr->right;\n                                else if(  lower_right->point == ptr->right.point && \n                                          ! lower_right->is_open && \n                                          ptr->right.is_open )\n                                        lower_right = &ptr->right;\n                                \n                        }\n\n                        std::cout << \"*upper_left = \" << *upper_left << \"\\n\";\n                        std::cout << \"*lower_right = \" << *lower_right << \"\\n\";\n\n                        if( upper_left->point <  lower_right->point ||\n                            ( upper_left->point == lower_right->point \n                              && ! upper_left->is_open && ! lower_right->is_open ) ){\n                                return IntervalUnion{ Interval{ *upper_left, *lower_right} };\n                        }\n\n                        return IntervalUnion{};\n                        \n                }\n                IntervalUnion operator()(Interval const& i)const{\n                        return IntervalUnion{i};\n                }\n        };\n\n        auto tmp = boost::apply_visitor(ToIntervalsImpl(), b);\n        boost::sort(tmp.children);\n        return tmp;\n}\n\nstruct BorelFamily : std::vector<BorelSet>{\n        using impl_type = std::vector<BorelSet>;\n        template<class... Args>\n        BorelFamily(Args&&... args):impl_type{args...}{}\n        friend std::ostream& operator<<(std::ostream& ostr, BorelFamily const& self){\n                ostr << \"{\";\n                for(size_t idx=0;idx!=self.size();++idx){\n                        ostr << ( idx == 0 ? \"\" : \", \" ) << ToString(self[idx]);\n                }\n                return ostr << \"}\";\n        }\n        void Display(std::ostream& out)const{\n                for(size_t idx=0;idx!=size();++idx){\n                        out << \"    \" << std::setw(2) << idx << \" : \" << ToString(at(idx)) << \"\\n\";\n                }\n        }\n};\n\n#if 1\nBorelFamily GenerateSigmaAlgebra(BorelFamily const& family){\n        BorelFamily head = family;\n        std::vector<BorelSet> to_add;\n\n\n        std::set<IntervalUnion> interval_set;\n        for(auto const& _ : family ){\n                interval_set.insert( ToIntervals(_) );\n        }\n\n        auto test = [&](BorelSet const& b){\n                auto iu = ToIntervals(b);\n                if( ! interval_set.count( iu ) ){\n                        std::cout << \"====== found new ======\\n\";\n                        std::cout << \"    b  = \" << ToString(b) << \"\\n\";\n                        std::cout << \"    iu = \" << ToString(iu.AsUnion()) << \"\\n\";\n\n                        to_add.push_back(b);\n                        interval_set.insert( iu );\n                        return 1;\n                }\n                return 0;\n        };\n\n        for(;;){\n                int changes = 0;\n                for(auto const& _ : head ){\n                        auto complement = Not{_};\n                        changes += test(complement);\n                }\n                for(size_t i=0;i+1<head.size();++i){\n                        for(size_t j=i+1;j<head.size();++j){\n                                auto u = Union{ head[i], head[j] };\n                                changes += test(u);\n                        }\n                }\n                if( changes == 0 )\n                        break;\n                for(auto const& _ : to_add )\n                        head.push_back(_);\n                //break;\n        }\n\n        BorelFamily result;\n        for(auto const& _ : interval_set ){\n                result.push_back( _.AsUnion() );\n        }\n        return result;\n\n\n\n        return head;\n\n}\n#endif\n\nint main(){\n\n        BorelSet b = Intersection{ Interval{ Closed(0.0 ), Closed(0.25) },\n                            Interval{ Open(0.25), Open(0.50) },\n                            Interval{ Closed(0.1), Closed(0.6) } };\n        Display(b);\n\n\n        \n        Display(ToIntervals(b).AsUnion());\n        \n        BorelFamily f0{ Omega(), Nul() };\n        std::cout << \"f0 = \" << f0 << \"\\n\";\n        BorelFamily f1{ Omega(), Nul(),\n                        Interval{ Closed(0.0), Open(0.5) },\n                        Interval{ Closed(0.5), Closed(1.0) } };\n        std::cout << \"f1 = \" << f1 << \"\\n\";\n        BorelFamily f2{ Omega(), Nul(),\n                        Interval{ Closed(0.0), Open(0.25) },\n                        Interval{ Closed(0.25), Open(0.50) },\n                        Interval{ Closed(0.50), Open(0.75) },\n                        Interval{ Closed(0.75), Closed(1.0) } };\n        std::cout << \"f2 = \" << f2 << \"\\n\";\n\n        std::cout << \"GenerateSigmaAlgebra(f2):\\n\";\n        GenerateSigmaAlgebra(f2).Display(std::cout);\n\n        //example_0();\n        //example_1();\n        //example_2();\n\n\n}\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d5b955a6cc0deb15363161266e675b54b36ba6da", "size": 41898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proc.cpp", "max_stars_repo_name": "sweeterthancandy/StochasticSimulation", "max_stars_repo_head_hexsha": "fc593f5170c14c87dc1ff5054d5aedc854933b89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "proc.cpp", "max_issues_repo_name": "sweeterthancandy/StochasticSimulation", "max_issues_repo_head_hexsha": "fc593f5170c14c87dc1ff5054d5aedc854933b89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proc.cpp", "max_forks_repo_name": "sweeterthancandy/StochasticSimulation", "max_forks_repo_head_hexsha": "fc593f5170c14c87dc1ff5054d5aedc854933b89", "max_forks_repo_licenses": ["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.7125103563, "max_line_length": 129, "alphanum_fraction": 0.4585660413, "num_tokens": 8538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5672518287173739}}
{"text": "#include \"thin_lq.hpp\"\n\n#include <armadillo>\n#include <stdexcept>\n\ntemplate <class Real>\nvoid ThinLq(const arma::Mat<Real> &A, arma::Mat<Real> &L, arma::Mat<Real> &Q) {\n    // A = Q * R  =>  A^T = R^T * Q^T\n\n    arma::Mat<Real> L_temp;\n    arma::Mat<Real> Q_temp;\n    bool status = arma::qr_econ(Q_temp, L_temp, A.t());\n\n    if (!status) {\n        throw std::runtime_error(\"RQ decomposition failed\");\n    }\n\n    Q = Q_temp.t();\n    L = L_temp.t();\n}\n\ntemplate void ThinLq<float>(const arma::Mat<float> &A, arma::Mat<float> &L,\n                            arma::Mat<float> &Q);\ntemplate void ThinLq<double>(const arma::Mat<double> &A, arma::Mat<double> &L,\n                             arma::Mat<double> &Q);\n", "meta": {"hexsha": "11e66afcb87555ba806d4cd0e33c8d1c94320baf", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/thin_lq.cpp", "max_stars_repo_name": "saibalde/tensortrain", "max_stars_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/thin_lq.cpp", "max_issues_repo_name": "saibalde/tensortrain", "max_issues_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/thin_lq.cpp", "max_forks_repo_name": "saibalde/tensortrain", "max_forks_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_forks_repo_licenses": ["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.2307692308, "max_line_length": 79, "alphanum_fraction": 0.563559322, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.567190908405704}}
{"text": "/**\n * @file generateData.cpp\n * @brief Create 3D simulation data for ICRA 2012 paper.\n * @author Michael Kaess\n * @author David Rosen\n * @version $Id: generateSpheresICRA2012.cpp 6377 2012-03-30 20:06:44Z kaess $\n */\n\n#include <stdio.h>\n#include <string>\n#include <fstream>\n#include <sstream>\n\n#include <isam/Pose3d.h>\n\nusing namespace std;\nusing namespace isam;\nusing namespace Eigen;\n\n//Number of samples to generate\nconst int num_samples = 1000;\n\n//Covariances\nconst double sigmas[6] = {0.1, 0.1, 0.1, 0.04, 0.04, 0.04};\n\nstring directory_name = \"sphere_data/\";\nstring base_filename = \"sample_\";\nstring file_extension = \".txt\";\n\nchar* write_string = new char[500];\n\nconst bool ADD_NOISE = true;\nconst bool LOOP_CLOSING = true;\n// vehicle on surface of sphere, instead of upright (pitch=roll=0)\nconst bool PERPENDICULAR = true;\n\n// sample from a normal distribution\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\nstatic boost::minstd_rand generator(27u);\ndouble sample_normal(double sigma = 1.0) \n{\n  typedef boost::normal_distribution<double> Normal;\n  Normal dist(0.0, sigma);\n  boost::variate_generator<boost::minstd_rand&, Normal> norm(generator, dist);\n  return(norm());\n}\n\nvoid write_constraint(ofstream& outfile, int id0, int id1, const Pose3d& delta_) {\n  Pose3d delta = delta_;\n  if (ADD_NOISE) {\n    // corrupt measurement with Gaussian noise\n    VectorXd v = delta.vector();\n    for (int i=0; i<6; i++) {\n      v(i) += sample_normal(sigmas[i]);\n    }\n    delta.set(v);\n  }\n\n  // X Y Z roll pitch yaw\n  sprintf(write_string, \"EDGE3 %i %i %g %g %g %g %g %g\",\n          id0, id1, delta.x(), delta.y(), delta.z(), delta.roll(), delta.pitch(), delta.yaw());\n  outfile << write_string;\n  for (int i=0; i<6; i++) {\n    for (int j=i; j<6; j++) {\n      double sqrtinf = 0.;\n      // only diagonal entries populated\n      if (i==j) {\n        // roll,pitch,yaw order\n        if (i<3) {\n          sqrtinf = 1./sigmas[i];\n        } else {\n          sqrtinf = 1./sigmas[8-i];\n        }\n      }\n      sprintf(write_string, \" %g\", sqrtinf);\n      outfile << write_string;\n    }\n  }\n  outfile << \"\\n\";\n}\n\nvoid add_constraint(ofstream& outfile, Pose3d* poses, int id0, int id1) {\n  Pose3d delta = poses[id1].ominus(poses[id0]);\n  write_constraint(outfile, id0, id1, delta);\n}\n\nint main(int argc, const char* argv[])  {\n\n  // Make sure that we have a 'test_data' directory.\n  int ret = system((\"mkdir \" + directory_name).c_str());\n  require(ret!=-1, \"Failed to created directory.\");\n\n  for (int s = 1; s <= num_samples; s++) {\n    // Form the filename that will be used to hold the output of this sample.\n\n    stringstream current_filename;\n\n    current_filename << directory_name;\n    current_filename << base_filename;\n    current_filename << s;\n    current_filename << file_extension;\n\n    // Use this filename to open up a new file for writing.\n    ofstream outfile( (current_filename.str()).c_str());\n\n    // generate poses on the surface of a sphere\n    const int steps = 50; // number of poses for one turn around the sphere\n    const int slices = 50; // number of rounds around the sphere\n    const double radius0 = 2.; // starting radius\n    const double radius = 50.; // sphere radius\n    \n    int n = steps*slices;\n    Pose3d poses[n];\n    int pose_id = 0;\n    // current vertical angle for elevation/slice (starting angle and increment)\n    double alpha = atan(radius0/radius);\n    double d_alpha = (M_PI-2*alpha) / (double)(n);\n    // angle in horizontal plane (starting angle and increment)\n    double phi = 0.;\n    double d_phi = 2*M_PI / (double)steps;\n    for (int i=0; i<steps; i++) {\n      for (int j=0; j<slices; j++) {\n        // calculate position\n        double r = radius * sin(alpha);\n        double h = sqrt(radius*radius - r*r);\n        // bottom half of sphere?\n        if (i<(slices/2)) h = -h;\n        // calculate pose\n        double y = r * sin(phi);\n        double x = r * cos(phi);\n        double z = -(radius + h);\n        double yaw = phi + M_PI/2.0;\n        double roll = 0.;\n        if (PERPENDICULAR) {\n          roll = alpha;\n        }\n        // generate measurements\n        poses[pose_id] = Pose3d(x,y,z, yaw,0.,roll);\n        if (pose_id>0) {\n          \n          add_constraint(outfile, poses, pose_id-1, pose_id);\n          if (LOOP_CLOSING) {\n            if (pose_id >= steps) {\n              add_constraint(outfile, poses, pose_id-steps, pose_id);\n            }\n          }\n        }\n        // update for next step\n        alpha += d_alpha;\n        phi += d_phi;\n        pose_id++;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "6bc29c4c76503030abc786d224bf355061d1d045", "size": 4641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/isam/misc/generateSpheresICRA2012.cpp", "max_stars_repo_name": "DiegoOrtegoP/Software", "max_stars_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_stars_repo_licenses": ["CC-BY-2.0"], "max_stars_count": 196.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T00:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T13:32:37.000Z", "max_issues_repo_path": "catkin_ws/src/isam/misc/generateSpheresICRA2012.cpp", "max_issues_repo_name": "DiegoOrtegoP/Software", "max_issues_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_issues_repo_licenses": ["CC-BY-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2018-11-13T14:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-03T14:27:12.000Z", "max_forks_repo_path": "catkin_ws/src/isam/misc/generateSpheresICRA2012.cpp", "max_forks_repo_name": "DiegoOrtegoP/Software", "max_forks_repo_head_hexsha": "4a07dd2dab29db910ca2e26848fa6b53b7ab00cd", "max_forks_repo_licenses": ["CC-BY-2.0"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2016-05-03T06:11:42.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-01T14:37:38.000Z", "avg_line_length": 29.3734177215, "max_line_length": 95, "alphanum_fraction": 0.6175393234, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.5671909075226834}}
{"text": "//#include <iostream>\n//#include <ostream>\n//#include <fstream>\n//#include <armadillo>\n//#include \"master.hpp\"\n//\n//Rzxy(,)\n//F_A: functions for the Agisoft conventions\n//double yaw_rotZXY(mat Rzxy,bool giveRadians=false)\n//{\n//\n//    double c = (180/datum::pi);\n//\n//    if(giveRadians)\n//    {\n//        c = 1.0f;\n//    }\n//    F_A\n//    return atan2(Rzxy(0,1),Rzxy(1,1)) * c;\n//}\n//\n//double pitch_rotZXY(mat Rzxy,bool giveRadians=false)\n//{\n//    double c = (180/datum::pi);\n//\n//    if(giveRadians)\n//    {\n//        c = 1.0f;\n//    }\n//    F_A\n//    return -asin(Rzxy(2,1)) * c;\n//}\n//\n//double roll_rotZXY(mat Rzxy,bool giveRadians=false)\n//{\n//    double c = (180/datum::pi);\n//\n//    if(giveRadians)\n//    {\n//        c = 1.0f;\n//    }\n//    F_A\n//    return atan2(Rzxy(2,0),Rzxy(2,2)) * c;\n//}\n//\n//mat one_axis_rot(double a,int axis,bool giveInverseT=false,bool isRadians=false)\n//{\n//\n//    these will give you the rotation in a CLOCKWISE way\n//\n//    mat res = eye(3,3);\n//    double c = (datum::pi/180);\n//\n//    if (isRadians)\n//    {\n//        c = 1.0f;\n//    }\n//\n//    double ca = cos(a*c);\n//    double sa = sin(a*c);\n//\n//    if(axis == 1)\n//    {\n//        res(1,1) =  ca;\n//        res(1,2) =  sa;\n//        res(2,1) = -sa;\n//        res(2,2) =  ca;\n//    }\n//    if(axis == 2)\n//    {\n//        res(0,0) =  ca;\n//        res(0,2) = -sa;\n//        res(2,0) =  sa;\n//        res(2,2) =  ca;\n//    }\n//    if (axis == 3)\n//    {\n//        res(0,0) =  ca;\n//        res(0,1) =  sa;\n//        res(1,0) = -sa;\n//        res(1,1) =  ca;\n//    }\n//\n//    if (giveInverseT)\n//    {res = res.t();}\n//\n//    return res;\n//}\n//\n//mat novatel_DCM(double roll,double pitch,double azimuth,bool isRadians=false,bool giveInverseT=false)\n//{\n//    matrix that gives the transformation\n//    FROM   BODY FRAME\n//    TO     LOCAL LEVEL FRAME\n//\n//    accordingly to the manual, is a combination of the following order:\n//    Rz * Rx * Ry  or R3 * R1 * R2 , all of them TRANSPOSED\n//\n//    NOVATEL definitions:\n//    roll   is around the Y axis\n//    pitch  is around the X axis\n//    yaw    is around the Z axis (and also Azimuth)\n//\n//    there is the fourth argument that can be used to give the inverse transformation\n//\n//    mat res = zeros(3,3);\n//\n//    double c = (datum::pi/180);\n//\n//    if (isRadians)\n//    {\n//        c = 1.0f;\n//    }\n//\n//    conversion between azimuth and yaw\n//    double yaw = -azimuth;\n//\n//    double cr = cos(roll * c);\n//    double sr = sin(roll * c);\n//\n//    double cp = cos(pitch * c);\n//    double sp = sin(pitch * c);\n//\n//    double cy = cos(yaw * c);\n//    double sy = sin(yaw * c);\n//\n//    linewise splitted\n//    res(0,0)= cy*cr-sy*sp*sr;\n//    res(0,1)= -sy*cp;\n//    res(0,2)= cy*sr + sy*sp*cr;\n//\n//    res(1,0)=  sy*cr+cy*sp*sr;\n//    res(1,1)=  cy*cp;\n//    res(1,2)=  sy*sr-cy*sp*cr;\n//\n//    res(2,0)=-cp*sr;\n//    res(2,1)= sp;\n//    res(2,2)= cp*cr;\n//\n//    if (giveInverseT)\n//    {res = res.t();}\n//\n//    return res;\n//}\n//\n//\n//struct outputPoseToPhotoscan\n//{\n//    struct for individual data\n//    string img_name;\n//    double lat,lgt,h,yaw,pitch,roll;\n//    double lat0,lgt0,h0; //coordinates of the origin\n//\n//    vec3 v0ECEF;\n//\n//    mat attMat;\n//    outputPoseToPhotoscan(vec3 vecBF,mat bsight,unsigned int ind);\n//};\n//\n//outputPoseToPhotoscan::outputPoseToPhotoscan(vec3 vBF,mat bsight,unsigned int ind)\n//{\n//    constants for multiplication and transformation\n//    double to_deg = 180/datum::pi;\n//    double to_rad = datum::pi/180;\n//\n/// First: position of the camera CP\n//    filling the origin\n//    lat0 = job.finalObsWcovs.at(ind).observation.lat;\n//    lgt0 = job.finalObsWcovs.at(ind).observation.lgt;\n//    h0   = job.finalObsWcovs.at(ind).observation.h;\n//\n//    converting the origin to XYZ\n//    GEODESY_ConvertGeodeticCurvilinearToEarthFixedCartesianCoordinates(\n//    GEODESY_REFERENCE_ELLIPSE_WGS84,\n//    lat0*to_rad,lgt0*to_rad,h0,&v0ECEF(0),&v0ECEF(1),&v0ECEF(2));\n//\n//    compute the rotation matrix\n//    mat R = novatel_DCM(\n//    job.finalObsWcovs.at(ind).observation.roll,\n//    job.finalObsWcovs.at(ind).observation.pitch,\n//    job.finalObsWcovs.at(ind).observation.azimuth);\n//\n//    transform the vector to the LLF\n//    vec3 vLLF = R * vBF;\n//    transform to the ECEF system\n//    vec3 vecECEF = ENU_to_ECEF(vLLF,v0ECEF,lat0,lgt0,h0);\n//\n//    transform to lat, long, h\n//    GEODESY_ConvertEarthFixedCartesianToGeodeticCurvilinearCoordinates(\n//    GEODESY_REFERENCE_ELLIPSE_WGS84,vecECEF(0),vecECEF(1),vecECEF(2),&lat,&lgt,&h);\n//\n//    converting to degrees:\n//    lat *= to_deg;lgt *= to_deg;\n//\n//    / second: orientation\n//\n//         R is from IMU BF to IMU CN LLF\n//\n//        matrix from ECEF to IMU CN LLF\n//        mat Rel1 = R_ecef_enu(lat0,lgt0);\n//\n//        matrix from ECEF to camera CP LLF\n//        mat Rel2 = R_ecef_enu(lat,lgt);\n//\n//        matrix from IMU CN LLF to camera CP LLF\n//        mat Rl1l2 = Rel1 * Rel2.t();\n//\n//        matrix from the camera CP LLF to IMU BF\n//        mat Rl2bf1 = R.t() * Rl1l2.t();\n//\n//        finally, the camera BF to camera CP LLF\n//        the bsight needs to be Rbf2bf1, aka from Camera BF to IMU\n//        attMat = Rl2bf1.t()*bsight.t();\n//\n//        now the yaw pitch roll to photoscan\n//        yaw     = yaw_rotZXY(attMat);\n//        pitch   = pitch_rotZXY(attMat);\n//        roll    = roll_rotZXY(attMat);\n//    }\n//\n//struct outputterToPhotoscan\n//{\n// vector<outputPoseToPhotoscan> individuals;\n//\n//\n//\n// outputterToPhotoscan(void);\n//};\n//\n//outputterToPhotoscan::outputterToPhotoscan(void)\n//{\n// ofstream outL(\"to_photoscan_left.txt\");\n// ofstream outR(\"to_photoscan_right.txt\");\n//\n// string separator = \"   \";\n//\n//    for (unsigned int i=0;i<job.finalObsWcovs.size();i++)\n//    {\n//        outputPoseToPhotoscan  Left(rCalib.LcamLA,rCalib.Rimu_LC.t(),i);\n//        outputPoseToPhotoscan Right(rCalib.RcamLA,rCalib.Rimu_RC.t(),i);\n//\n//        outL<<Left.img_name<<separator<<Left.lat<<separator<<Left.lgt<<separator<<Left.h;\n//        outL<<separator<<Left.yaw<<separator<<Left.pitch<<separator<<Left.roll<<endl;\n//\n//        outR<<Right.img_name<<separator<<Right.lat<<separator<<Right.lgt<<separator<<Left.h;\n//        outR<<separator<<Right.yaw<<separator<<Right.pitch<<separator<<Right.roll<<endl;\n//    }\n//}\n//\n", "meta": {"hexsha": "65b3bd391f4bbe63196d36b5e70ff49f3b3a2b41", "size": 6304, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "outputter.hpp", "max_stars_repo_name": "kauevestena/smmt", "max_stars_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T21:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T21:47:42.000Z", "max_issues_repo_path": "outputter.hpp", "max_issues_repo_name": "kauevestena/smmt", "max_issues_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "outputter.hpp", "max_forks_repo_name": "kauevestena/smmt", "max_forks_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_forks_repo_licenses": ["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.216, "max_line_length": 103, "alphanum_fraction": 0.5726522843, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5671889010644078}}
{"text": "#pragma once\n\n#include <vector>\n#include <boost/numeric/odeint.hpp>\n#include <cmath>\n#include <ros/ros.h>\n# define M_PI           3.14159265358979323846  /* pi */\n#define toRadian( x )\t( (x) / 180 * M_PI )\n#define toDegree( x )\t( (x) / M_PI * 180 )\n\nnamespace cardsflow_gazebo\n{\n    using namespace std;\n\tusing namespace boost::numeric::odeint;\n\t//using namespace gazebo;\n/*\n    struct tendonType {\n\t\tvector<ignition::math::Vector3> MidPoint;\n\t\tvector<ignition::math::Vector3> Vector;\n\t\t//might need it to calculate length\n\t\tvector<ignition::math::Vector3> Orientation;\n\t\tvector<double> Pitch;\n\t\tvector<double> Roll;\n\t};\n*/\n\tstruct SEE {\n\t\tdouble stiffness = 30680.0; // N/m\n\t\tdouble length = 0.056; //m\n\t\tdouble expansion = 0.0; //m\n\t\tdouble force = 0.0;  //\n\t\tdouble length0 = 0; //m\n\t};\n\t\t\n\t\t\n    class ISee {\n\n\t\t// c1-c3 are constand values, c4 is x0. documentation can be found at ____________________\n\t\tdouble c1 = 0.012, c2 = 0.008, c3 = 0.018, c4 = 0.039; //m\n\t\t// the angles alpha_* describe the angle the tendons attach to the see.element\n\t\tdouble alpha_1 = std::atan( c1 / c4 ), alpha_2 = std::atan( c2 /  (c3+c4) ); // radian\n\t\t// the angles beta_* describe the third angles of the corresponding triangles  \n\t\tdouble beta_1  =  M_PI / 4 - alpha_1, beta_2 = M_PI / 4 - alpha_2; // radian\n\t\t// length_* is the tendonlength from the two triangles inside the motor\n\t\tdouble length_1 = sqrt( c1*c1 + c4*c4 ), length_2 = sqrt( c2*c2 + (c3+c4)*(c3+c4) ); //m\n\t\t// length_c* are constand tendonlengths inside the motor\n\t\tdouble length_c1 = 0.04, length_c2 = 0.013; //m\n\t\t// Tendon stiffness (this is a random high number. A real number still has to be set) \n\t\tdouble tendonStiffness = 1e6; // N/m \n\t\tdouble tendonForce = 0; \n\n       public:\n\t\t//deltaX is the displacement of the spring inside the motor\n\t\tdouble deltaX = 0.0; //m\n\t\t// the Length of the tendon inside the motor. the internal length changes depending on the displacement of the spring.\n\t\tdouble internalLength = length_c1 + length_1 + length_2 + length_c2; //m\n        SEE see;\n\n\n        ISee();\n\n\t\t///////////////////////////////////////\n\t\t/// \\brief Calculate elastic force of the series elastic element\n\t\t/// \\param[in] The tandonLength represents the length of the entire tendon.from the motor to the last viapoint.\n\t\t/// \\param[in] The muscleLength representes the length of the tendon forn the outside of the motor to the last viapoint.\n\t\tvoid ElasticElementModel(const double &tendonLength, const double &muscleLength);\n\n\t\t///////////////////////////////////////\n\t\t/// \\brief apply the springForce onto the tendons going to motor and out the muscle. The force depends on the angle the tendons have towards the spring\n\t\t/// \\parm[in] the force going out the muscle\n\t\t/// \\parm[in] the force going toward the motor\n\t\tvoid applyTendonForce( double &_muscleForce , double &_actuatorForce );\n\t};\n}", "meta": {"hexsha": "2f8ca98d3ab6faf064832984cfa858539b4cb67c", "size": 2868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cardsflow_gazebo/muscle/ISee.hpp", "max_stars_repo_name": "CARDSflow/cardsflow_gazebo", "max_stars_repo_head_hexsha": "a83fc2f346291c172548ad8ea5ce7d6d8aacb3f2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cardsflow_gazebo/muscle/ISee.hpp", "max_issues_repo_name": "CARDSflow/cardsflow_gazebo", "max_issues_repo_head_hexsha": "a83fc2f346291c172548ad8ea5ce7d6d8aacb3f2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cardsflow_gazebo/muscle/ISee.hpp", "max_forks_repo_name": "CARDSflow/cardsflow_gazebo", "max_forks_repo_head_hexsha": "a83fc2f346291c172548ad8ea5ce7d6d8aacb3f2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T13:52:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-05T13:52:59.000Z", "avg_line_length": 39.2876712329, "max_line_length": 153, "alphanum_fraction": 0.6705020921, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.5671448406142591}}
{"text": "/*\n [auto_generated]\n libs/numeric/odeint/examples/bind_member_functions.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#include <iostream>\n#include <array>\n#include <type_traits>\n\n#include <boost/numeric/odeint.hpp>\n\nnamespace odeint = boost::numeric::odeint;\n\n\n\ntypedef std::array< double , 3 > state_type;\n\nstruct lorenz\n{\n    void ode( const state_type &x , state_type &dxdt , double t ) const\n    {\n        const double sigma = 10.0;\n        const double R = 28.0;\n        const double b = 8.0 / 3.0;\n\n        dxdt[0] = sigma * ( x[1] - x[0] );\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n        dxdt[2] = -b * x[2] + x[0] * x[1];\n    }\n};\n\nint main( int argc , char *argv[] )\n{\n    using namespace boost::numeric::odeint;\n    //[ bind_member_function_cpp11\n    namespace pl = std::placeholders;\n\n    state_type x = {{ 10.0 , 10.0 , 10.0 }};\n    integrate_const( runge_kutta4< state_type >() ,\n                     std::bind( &lorenz::ode , lorenz() , pl::_1 , pl::_2 , pl::_3 ) ,\n                     x , 0.0 , 10.0 , 0.01  );\n    //]\n    return 0;\n}\n\n", "meta": {"hexsha": "de018854c92444e2dd3925fb09f8551d4c143286", "size": 1297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/bind_member_functions_cpp11.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/bind_member_functions_cpp11.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/bind_member_functions_cpp11.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": 22.7543859649, "max_line_length": 86, "alphanum_fraction": 0.599845798, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5670825210640392}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include \"Point.hpp\"\n\nnamespace Geometry2d {\n// A 2x3 transformation matrix.\n//\n// This is the 2D equivalent of the usual 3D tranformation matrix with the\n// bottom row omitted because the bottom (third) element of a 2D point is always\n// 1.  The third row of the matrix is understood to be [0 0 1].\nclass TransformMatrix {\npublic:\n    TransformMatrix() {\n        _m[0] = 1;\n        _m[1] = 0;\n        _m[2] = 0;\n        _m[3] = 0;\n        _m[4] = 1;\n        _m[5] = 0;\n    }\n\n    TransformMatrix(float a, float b, float c, float d, float e, float f) {\n        _m[0] = a;\n        _m[1] = b;\n        _m[2] = c;\n        _m[3] = d;\n        _m[4] = e;\n        _m[5] = f;\n    }\n\n    TransformMatrix(Geometry2d::Point origin, float rotation = 0,\n                    bool mirror = false, float scale = 1);\n\n    TransformMatrix(const Eigen::Matrix<double, 3, 3>& other) {\n        _m[0] = other(0, 0);\n        _m[1] = other(0, 1);\n        _m[2] = other(0, 2);\n        _m[3] = other(1, 0);\n        _m[4] = other(1, 1);\n        _m[5] = other(1, 2);\n    }\n\n    TransformMatrix operator*(const TransformMatrix& other) const {\n        float a = _m[0] * other._m[0] + _m[1] * other._m[3];\n        float b = _m[0] * other._m[1] + _m[1] * other._m[4];\n        float c = _m[0] * other._m[2] + _m[1] * other._m[5] + _m[2];\n        float d = _m[3] * other._m[0] + _m[4] * other._m[3];\n        float e = _m[3] * other._m[1] + _m[4] * other._m[4];\n        float f = _m[3] * other._m[2] + _m[4] * other._m[5] + _m[5];\n\n        return TransformMatrix(a, b, c, d, e, f);\n    }\n\n    TransformMatrix& operator*=(const TransformMatrix& other) {\n        float a = _m[0] * other._m[0] + _m[1] * other._m[3];\n        float b = _m[0] * other._m[1] + _m[1] * other._m[4];\n        float c = _m[0] * other._m[2] + _m[1] * other._m[5] + _m[2];\n        float d = _m[3] * other._m[0] + _m[4] * other._m[3];\n        float e = _m[3] * other._m[1] + _m[4] * other._m[4];\n        float f = _m[3] * other._m[2] + _m[4] * other._m[5] + _m[5];\n\n        _m[0] = a;\n        _m[1] = b;\n        _m[2] = c;\n        _m[3] = d;\n        _m[4] = e;\n        _m[5] = f;\n\n        return *this;\n    }\n\n    operator Eigen::Matrix<double, 3, 3>() const {\n        Eigen::Matrix<double, 3, 3> result;\n        result << _m[0], _m[1], _m[2], _m[3], _m[4], _m[5], 0, 0, 1;\n        return result;\n    }\n\n    Point operator*(const Point& pt) const {\n        return Point(pt.x() * _m[0] + pt.y() * _m[1] + _m[2],\n                     pt.x() * _m[3] + pt.y() * _m[4] + _m[5]);\n    }\n\n    // Transforms a direction vector (3rd element is zero)\n    Point transformDirection(const Point& dir) const {\n        return Point(dir.x() * _m[0] + dir.y() * _m[1],\n                     dir.x() * _m[3] + dir.y() * _m[4]);\n    }\n\n    // Transforms the given angle in radians\n    float transformAngle(float angle) const;\n\n    // Returns the vector that represents the direction of the transformed\n    // X-axis.\n    Point x() const { return Point(_m[0], _m[3]); }\n\n    // Returns the vector that represents the direction of the transformed\n    // Y-axis.\n    Point y() const { return Point(_m[1], _m[4]); }\n\n    // Returns the origin of the transformed coordinate system\n    Point origin() const { return Point(_m[2], _m[5]); }\n\n    // Returns the scaling along the transformed X-axis.\n    float xScale() const { return x().mag(); }\n\n    // Returns the scaling along the transformed Y-axis.\n    float yScale() const { return y().mag(); }\n\n    // Returns the clockwise angle from the transformed Y axis to the original Y\n    // axis. This is not affected by horizontal reflection.\n    float rotation() const;\n\n    // Returns true if the coordinate system has been mirrored (i.e. is now\n    // left-handed).\n    bool mirrored() const;\n\n    const float* m() const { return _m; }\n\n    ////////////////\n    // Functions to build common transformations:\n\n    // Translation\n    static TransformMatrix translate(const Point& delta) {\n        return TransformMatrix(1, 0, delta.x(), 0, 1, delta.y());\n    }\n\n    static TransformMatrix translate(float x, float y) {\n        return translate(Point(x, y));\n    }\n\n    // Rotation in radians around origin\n    static TransformMatrix rotate(float angle) {\n        float c = cos(angle);\n        float s = sin(angle);\n\n        return TransformMatrix(c, -s, 0, s, c, 0);\n    }\n\n    // Uniform scale\n    static TransformMatrix scale(float s) {\n        return TransformMatrix(s, 0, 0, 0, s, 0);\n    }\n\n    // Non-uniform scale\n    static TransformMatrix scale(float x, float y) {\n        return TransformMatrix(x, 0, 0, 0, y, 0);\n    }\n\n    // Returns a matrix to rotate <angle> radians CCW around <center>.\n    static TransformMatrix rotateAroundPoint(const Point& center, float angle);\n\n    // Returns a matrix to reflect along the line parallel to the Y-axis\n    // containing <center>.\n    static TransformMatrix mirrorAroundPoint(const Point& center);\n\n    static const TransformMatrix identity;\n    static const TransformMatrix mirrorX;\n\nprotected:\n    // Matrix values in row-major order.\n    //\n    // Indices:\n    //   [0 1 2\n    //    3 4 5]\n    float _m[6];\n};\n}  // namespace Geometry2d\n", "meta": {"hexsha": "a724104234d3ea333072a9eb95e282c657ae7745", "size": 5187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/Geometry2d/TransformMatrix.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": "common/Geometry2d/TransformMatrix.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": "common/Geometry2d/TransformMatrix.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": 30.5117647059, "max_line_length": 80, "alphanum_fraction": 0.5594756121, "num_tokens": 1650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.56708249287708}}
{"text": "/*\n * Shared copyright notice and LGPLv3 license statement.\n *\n * Copyright (C) 2010 The Board of Trustees of The Leland Stanford Junior University. All rights reserved.\n * Copyright (C) 2010 University of Texas at Austin. All rights reserved.\n *\n * Authors: Roland Philippsen (Stanford) and Luis Sentis (UT Austin)\n *          http://cs.stanford.edu/group/manips/\n *          http://www.me.utexas.edu/~hcrl/\n *\n * This program is free software: you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  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 program.  If not, see\n * <http://www.gnu.org/licenses/>\n */\n\n#include <utils/pseudo_inverse.hpp>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <stdio.h>\n\nusing namespace std;\n\nnamespace sejong {\n\n    void pseudoInverse(Matrix const & matrix,\n                       double sigmaThreshold,\n                       Matrix & invMatrix,\n                       Vector * opt_sigmaOut)    {\n        \n        if ((1 == matrix.rows()) && (1 == matrix.cols())) {\n            // workaround for Eigen2\n            invMatrix.resize(1, 1);\n            if (matrix.coeff(0, 0) > sigmaThreshold) {\n                invMatrix.coeffRef(0, 0) = 1.0 / matrix.coeff(0, 0);\n            }\n            else {\n                invMatrix.coeffRef(0, 0) = 0.0;\n            }\n            if (opt_sigmaOut) {\n                opt_sigmaOut->resize(1);\n                opt_sigmaOut->coeffRef(0) = matrix.coeff(0, 0);\n            }\n            return;\n        }\n      \n        Eigen::JacobiSVD<Matrix> svd(matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        // not sure if we need to svd.sort()... probably not\n        int const nrows(svd.singularValues().rows());\n        Matrix invS;\n        invS = Matrix::Zero(nrows, nrows);\n        for (int ii(0); ii < nrows; ++ii) {\n            if (svd.singularValues().coeff(ii) > sigmaThreshold) {\n                invS.coeffRef(ii, ii) = 1.0 / svd.singularValues().coeff(ii);\n            }\n            else{\n                // invS.coeffRef(ii, ii) = 1.0/ sigmaThreshold;\n                // printf(\"sigular value is too small: %f\\n\", svd.singularValues().coeff(ii));\n            }\n        }\n        invMatrix = svd.matrixV() * invS * svd.matrixU().transpose();\n        if (opt_sigmaOut) {\n            *opt_sigmaOut = svd.singularValues();\n        }\n    }\n  \n}\n", "meta": {"hexsha": "b003d77be51ae3b7e05ffd230e35ca94a0ef054d", "size": 2801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/src/pseudo_inverse.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/pseudo_inverse.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/pseudo_inverse.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": 36.3766233766, "max_line_length": 106, "alphanum_fraction": 0.5869332381, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.5669337755517969}}
{"text": "#pragma once\n\n#include <armadillo>\n\nclass Composition;\n\nnamespace utils\n{\n    double calculateHeatCapacityConstantVolumeJFH(\n            const double pressure);\n\n    double calculateHeatCapacityConstantVolumeTGNet(\n            const double molarMass,\n            const double pressure,\n            const double temperature);\n\n    double calculateHeatCapacityConstantPressureJFH(\n            const double molarMass,\n            const double pressure,\n            const double temperature);\n\n    double calculateHeatCapacityConstantPressureLangelandsvik(\n            const double molarMass,\n            const double pressure,\n            const double temperature);\n\n    double calculateHeatCapacityConstantPressureTGNet(\n            const double molarMassOfMixture,\n            const double pressure,\n            const double temperature);\n\n    double calculateHeatCapacityConstantPressureKIO(\n            const Composition& comp,\n            const double pressure,\n            const double temperature);\n\n    double calculateIsobaricHeatCapacityJKH(\n            const Composition& comp,\n            const double pressure,\n            const double temperature,\n            const double Z = 0);\n\n    arma::vec calculateViscosity(\n            const arma::vec& molarMass,\n            const arma::vec& temperature,\n            const arma::vec& density);\n\n    arma::vec calculateReynoldsNumber(\n            const arma::vec& massFlow,\n            const arma::vec& diameter,\n            const arma::vec& viscosity);\n\n    arma::vec calculateColebrookWhiteFrictionFactor(\n            const arma::vec& sandGrainEquivalentRoughness,\n            const arma::vec& diameter,\n            const arma::vec& reynoldsNumber);\n\n    double calculateColebrookWhiteFrictionFactor(\n            const double sandGrainEquivalentRoughness,\n            const double diameter,\n            const double reynoldsNumber);\n\n    double calculateHaalandFrictionFactor(\n            const double sandGrainEquivalentRoughness,\n            const double diameter,\n            const double reynoldsNumber);\n\n    namespace details\n    {\n        double KIOidealGasCP(\n                const double specificGravity,\n                const double temperature);\n\n        double KIOdimensionlessResidualCP(\n                const double reducedPressure,\n                const double reducedTemperature);\n\n        double JKHdimensionlessCP(\n                const double molarMass,\n                const double H2S,\n                const double CO2,\n                const double N2,\n                const double H2,\n                const double H2O,\n                const double pressure,\n                const double temperature,\n                const double compressibility);\n\n        double JKHidealGasCP(\n                const Composition& comp,\n                const double specificGravity,\n                const double temperature);\n\n        double JKHidealGasCP(\n                const double specificGravity,\n                const double H2S,\n                const double CO2,\n                const double N2,\n                const double H2,\n                const double H2O,\n                const double temperature);\n\n        double calculateHeatCapacityConstantPressureKIO(\n                const Composition& comp,\n                const double H2S,\n                const double pressure,\n                const double temperature);\n\n        double colebrookWhiteFrictionFactor(\n                const double sandGrainEquivalentRoughness,\n                const double diameter,\n                const double reynoldsNumber);\n\n        double colebrookWhite(\n                const double f,\n                const double sandGrainEquivalentRoughness,\n                const double diameter,\n                const double reynoldsNumber);\n\n        double colebrookWhiteDerivative(\n                const double f,\n                const double sandGrainEquivalentRoughness,\n                const double diameter,\n                const double reynoldsNumber);\n    }\n}\n", "meta": {"hexsha": "63006ee4e824f387612c5a72cfc83e93ead162e2", "size": 4012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/physics.hpp", "max_stars_repo_name": "kewin1983/transient-pipeline-flow", "max_stars_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T03:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T03:30:07.000Z", "max_issues_repo_path": "src/utilities/physics.hpp", "max_issues_repo_name": "kewin1983/transient-pipeline-flow", "max_issues_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/physics.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5905511811, "max_line_length": 62, "alphanum_fraction": 0.5957128614, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5668983886829075}}
{"text": "\n#include <Eigen/Core>\n#include <functional>\n\n#include \"update_ops_cpp.hpp\"\n#include \"utility.hpp\"\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list,\n    UINT target_qubit_index_count, const CTYPE* matrix, CTYPE* state,\n    ITYPE dim) {\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(\n        target_qubit_index_list, target_qubit_index_count);\n    Eigen::Map<const Eigen::Matrix<std::complex<double>, Eigen::Dynamic,\n                   Eigen::Dynamic, Eigen::RowMajor>,\n        Eigen::Aligned>\n        eigen_matrix((std::complex<double>*)matrix, matrix_dim, matrix_dim);\n    Eigen::VectorXcd buffer(matrix_dim);\n    std::complex<double>* eigen_state =\n        reinterpret_cast<std::complex<double>*>(state);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(\n        target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for (state_index = 0; state_index < loop_dim; ++state_index) {\n        // create base index\n        ITYPE basis_0 = state_index;\n        for (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(\n                basis_0, 1ULL << insert_index, insert_index);\n        }\n\n        // fetch vector\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            buffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            eigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list,\n    UINT target_qubit_index_count,\n    const Eigen::Matrix<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic,\n        Eigen::RowMajor>& eigen_matrix,\n    CTYPE* state, ITYPE dim) {\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(\n        target_qubit_index_list, target_qubit_index_count);\n    Eigen::VectorXcd buffer(matrix_dim);\n    std::complex<double>* eigen_state =\n        reinterpret_cast<std::complex<double>*>(state);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(\n        target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for (state_index = 0; state_index < loop_dim; ++state_index) {\n        // create base index\n        ITYPE basis_0 = state_index;\n        for (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(\n                basis_0, 1ULL << insert_index, insert_index);\n        }\n\n        // fetch vector\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            buffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            eigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_dense_matrix_gate_eigen(const UINT* target_qubit_index_list,\n    UINT target_qubit_index_count, const Eigen::MatrixXcd& eigen_matrix,\n    CTYPE* state, ITYPE dim) {\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(\n        target_qubit_index_list, target_qubit_index_count);\n    std::complex<double>* cppstate =\n        reinterpret_cast<std::complex<double>*>(state);\n    Eigen::VectorXcd buffer(matrix_dim);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(\n        target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for (state_index = 0; state_index < loop_dim; ++state_index) {\n        // create base index\n        ITYPE basis_0 = state_index;\n        for (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(\n                basis_0, 1ULL << insert_index, insert_index);\n        }\n\n        // fetch vector\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            buffer[y] = cppstate[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            cppstate[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n\nvoid multi_qubit_sparse_matrix_gate_eigen(const UINT* target_qubit_index_list,\n    UINT target_qubit_index_count,\n    const Eigen::SparseMatrix<std::complex<double>>& eigen_matrix, CTYPE* state,\n    ITYPE dim) {\n    // matrix dim, mask, buffer\n    const ITYPE matrix_dim = 1ULL << target_qubit_index_count;\n    const ITYPE* matrix_mask_list = create_matrix_mask_list(\n        target_qubit_index_list, target_qubit_index_count);\n    Eigen::VectorXcd buffer(matrix_dim);\n    std::complex<double>* eigen_state =\n        reinterpret_cast<std::complex<double>*>(state);\n\n    // insert index\n    const UINT* sorted_insert_index_list = create_sorted_ui_list(\n        target_qubit_index_list, target_qubit_index_count);\n\n    // loop variables\n    const ITYPE loop_dim = dim >> target_qubit_index_count;\n\n    ITYPE state_index;\n    for (state_index = 0; state_index < loop_dim; ++state_index) {\n        // create base index\n        ITYPE basis_0 = state_index;\n        for (UINT cursor = 0; cursor < target_qubit_index_count; cursor++) {\n            UINT insert_index = sorted_insert_index_list[cursor];\n            basis_0 = insert_zero_to_basis_index(\n                basis_0, 1ULL << insert_index, insert_index);\n        }\n\n        // fetch vector\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            buffer[y] = eigen_state[basis_0 ^ matrix_mask_list[y]];\n        }\n\n        buffer = eigen_matrix * buffer;\n\n        // set result\n        for (ITYPE y = 0; y < matrix_dim; ++y) {\n            eigen_state[basis_0 ^ matrix_mask_list[y]] = buffer[y];\n        }\n    }\n    free((UINT*)sorted_insert_index_list);\n    free((ITYPE*)matrix_mask_list);\n}\n", "meta": {"hexsha": "203a7325d07649d017326f3592814e4dbe7290e6", "size": 6882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/csim/update_ops_matrix_dense_multi_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_multi_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_multi_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": 36.2210526316, "max_line_length": 80, "alphanum_fraction": 0.6583841906, "num_tokens": 1693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5668983736754627}}
{"text": "/*-----------------------------------------------------------------------------+\r\nInterval Container Library\r\nAuthor: Joachim Faulhaber\r\nCopyright (c) 2007-2009: Joachim Faulhaber\r\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\r\n+------------------------------------------------------------------------------+\r\n   Distributed under the Boost Software License, Version 1.0.\r\n      (See accompanying file LICENCE.txt or copy at\r\n           http://www.boost.org/LICENSE_1_0.txt)\r\n+-----------------------------------------------------------------------------*/\r\n\r\n/** Example partys_height_average.cpp \\file partys_height_average.cpp\r\n    \\brief Using <i>aggregate on overlap</i> a history of height averages of \r\n           party guests is computed.\r\n\r\n    In partys_height_average.cpp we compute yet another aggregation:\r\n    The average height of guests as it changes over time. This is done by \r\n    defining a class counted_sum that sums up heights and counts the number \r\n    of guests via an operator +=.\r\n    \r\n    Based on the operator += we can aggregate counted sums on addition\r\n    of interval value pairs into an interval_map.\r\n\r\n    \\include partys_height_average_/partys_height_average.cpp\r\n*/\r\n//[example_partys_height_average\r\n// The next line includes <boost/date_time/posix_time/posix_time.hpp>\r\n// and a few lines of adapter code.\r\n#include <boost/icl/ptime.hpp> \r\n#include <iostream>\r\n#include <boost/icl/interval_map.hpp>\r\n#include <boost/icl/split_interval_map.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::posix_time;\r\nusing namespace boost::icl;\r\n\r\n\r\nclass counted_sum\r\n{\r\npublic:\r\n    counted_sum():_sum(0),_count(0){}\r\n    counted_sum(int sum):_sum(sum),_count(1){}\r\n\r\n    int sum()const  {return _sum;}\r\n    int count()const{return _count;}\r\n    double average()const{ return _count==0 ? 0.0 : _sum/static_cast<double>(_count); }\r\n\r\n    counted_sum& operator += (const counted_sum& right)\r\n    { _sum += right.sum(); _count += right.count(); return *this; }\r\n\r\nprivate:\r\n    int _sum;\r\n    int _count;\r\n};\r\n\r\nbool operator == (const counted_sum& left, const counted_sum& right)\r\n{ return left.sum()==right.sum() && left.count()==right.count(); } \r\n\r\n\r\nvoid partys_height_average()\r\n{\r\n    interval_map<ptime, counted_sum> height_sums;\r\n\r\n    height_sums +=\r\n      make_pair( \r\n        discrete_interval<ptime>::right_open(\r\n          time_from_string(\"2008-05-20 19:30\"), \r\n          time_from_string(\"2008-05-20 23:00\")), \r\n        counted_sum(165)); // Mary is 1,65 m tall.\r\n\r\n    height_sums +=\r\n      make_pair( \r\n        discrete_interval<ptime>::right_open(\r\n          time_from_string(\"2008-05-20 19:30\"), \r\n          time_from_string(\"2008-05-20 23:00\")), \r\n        counted_sum(180)); // Harry is 1,80 m tall.\r\n\r\n    height_sums +=\r\n      make_pair( \r\n        discrete_interval<ptime>::right_open(\r\n          time_from_string(\"2008-05-20 20:10\"), \r\n          time_from_string(\"2008-05-21 00:00\")), \r\n        counted_sum(170)); // Diana is 1,70 m tall.\r\n\r\n    height_sums +=\r\n      make_pair( \r\n        discrete_interval<ptime>::right_open(\r\n          time_from_string(\"2008-05-20 20:10\"), \r\n          time_from_string(\"2008-05-21 00:00\")), \r\n        counted_sum(165)); // Susan is 1,65 m tall.\r\n\r\n    height_sums +=\r\n      make_pair( \r\n        discrete_interval<ptime>::right_open(\r\n          time_from_string(\"2008-05-20 22:15\"), \r\n          time_from_string(\"2008-05-21 00:30\")), \r\n        counted_sum(200)); // Peters height is 2,00 m\r\n\r\n    interval_map<ptime, counted_sum>::iterator height_sum_ = height_sums.begin();\r\n    cout << \"-------------- History of average guest height -------------------\\n\";\r\n    while(height_sum_ != height_sums.end())\r\n    {\r\n        discrete_interval<ptime> when = height_sum_->first;\r\n\r\n        double height_average = (*height_sum_++).second.average();\r\n        cout << setprecision(3)\r\n             << \"[\" << first(when) << \" - \" << upper(when) << \")\"\r\n             << \": \" << height_average <<\" cm = \" << height_average/30.48 << \" ft\" << endl;\r\n    }\r\n}\r\n\r\n\r\nint main()\r\n{\r\n    cout << \">>Interval Container Library: Sample partys_height_average.cpp  <<\\n\";\r\n    cout << \"------------------------------------------------------------------\\n\";\r\n    partys_height_average();\r\n    return 0;\r\n}\r\n\r\n// Program output:\r\n/*-----------------------------------------------------------------------------\r\n>>Interval Container Library: Sample partys_height_average.cpp  <<\r\n------------------------------------------------------------------\r\n-------------- History of average guest height -------------------\r\n[2008-May-20 19:30:00 - 2008-May-20 20:10:00): 173 cm = 5.66 ft\r\n[2008-May-20 20:10:00 - 2008-May-20 22:15:00): 170 cm = 5.58 ft\r\n[2008-May-20 22:15:00 - 2008-May-20 23:00:00): 176 cm = 5.77 ft\r\n[2008-May-20 23:00:00 - 2008-May-21 00:00:00): 178 cm = 5.85 ft\r\n[2008-May-21 00:00:00 - 2008-May-21 00:30:00): 200 cm = 6.56 ft\r\n-----------------------------------------------------------------------------*/\r\n//]\r\n\r\n", "meta": {"hexsha": "dc91580081d2db97fd446445a5abb0edd80286eb", "size": 5016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/partys_height_average_/partys_height_average.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/icl/example/partys_height_average_/partys_height_average.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/icl/example/partys_height_average_/partys_height_average.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": 37.1555555556, "max_line_length": 92, "alphanum_fraction": 0.5600079745, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738152021787, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5668680584908913}}
{"text": "// Copyright © 2018 Thomas Nagler\n//\n// This file is part of the wdm library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory\n// or https://github.com/tnagler/wdmcpp/blob/master/LICENSE.\n\n#pragma once\n\n#include <Eigen/Dense>\n#include \"../wdm.hpp\"\n\n\nnamespace wdm {\n    \nnamespace utils {\n\n    inline std::vector<double> convert_vec(const Eigen::VectorXd& x)\n    {\n        std::vector<double> xx(x.size());\n        if (x.size() > 0)\n            Eigen::VectorXd::Map(&xx[0], x.size()) = x;\n        return xx;\n    }\n\n}\n\n//! calculates (weighted) dependence measures.\n//! @param x, y input data.\n//! @param method the dependence measure; see details for possible values. \n//! @param weights an optional vector of weights for the data.\n//! @param remove_missing if `true`, all observations containing a `nan` are\n//!    removed; otherwise throws an error if `nan`s are present.\n//! @details\n//! Available methods:\n//!   - `\"pearson\"`, `\"prho\"`, `\"cor\"`: Pearson correlation  \n//!   - `\"spearman\"`, `\"srho\"`, `\"rho\"`: Spearman's \\f$ \\rho \\f$  \n//!   - `\"kendall\"`, `\"ktau\"`, `\"tau\"`: Kendall's \\f$ \\tau \\f$  \n//!   - `\"blomqvist\"`, `\"bbeta\"`, `\"beta\"`: Blomqvist's \\f$ \\beta \\f$  \n//!   - `\"hoeffding\"`, `\"hoeffd\"`, `\"d\"`: Hoeffding's \\f$ D \\f$  \n//! \n//! @return the dependence measure\ninline double wdm(const Eigen::VectorXd& x,\n                  const Eigen::VectorXd& y,\n                  std::string method,\n                  Eigen::VectorXd weights = Eigen::VectorXd(),\n                  bool remove_missing = true)\n{\n    return wdm(utils::convert_vec(x),\n               utils::convert_vec(y),\n               method,\n               utils::convert_vec(weights),\n               remove_missing);\n}\n\n//! calculates a matrix of (weighted) dependence measures.\n//! @param x input data.\n//! @param method the dependence measure; see details for possible values. \n//! @param weights an optional vector of weights for the data.\n//! @param remove_missing if `true`, all observations containing a `nan` are\n//!    removed; otherwise throws an error if `nan`s are present.\n//! @details\n//! Available methods:\n//!   - `\"pearson\"`, `\"prho\"`, `\"cor\"`: Pearson correlation  \n//!   - `\"spearman\"`, `\"srho\"`, `\"rho\"`: Spearman's \\f$ \\rho \\f$  \n//!   - `\"kendall\"`, `\"ktau\"`, `\"tau\"`: Kendall's \\f$ \\tau \\f$  \n//!   - `\"blomqvist\"`, `\"bbeta\"`, `\"beta\"`: Blomqvist's \\f$ \\beta \\f$  \n//!   - `\"hoeffding\"`, `\"hoeffd\"`, `\"d\"`: Hoeffding's \\f$ D \\f$  \n//! \n//! @return a matrix of pairwise dependence measures.\ninline Eigen::MatrixXd wdm(const Eigen::MatrixXd& x,\n                           std::string method,\n                           Eigen::VectorXd weights = Eigen::VectorXd(),\n                           bool remove_missing = true)\n{\n    size_t d = x.cols();\n    if (d == 1)\n        throw std::runtime_error(\"x must have at least 2 columns.\");\n    \n    Eigen::MatrixXd ms = Eigen::MatrixXd::Identity(d, d);\n    for (size_t i = 0; i < d; i++) {\n        for (size_t j = i + 1; j < d; j++) {\n            ms(i, j) = wdm(utils::convert_vec(x.col(i)),\n                           utils::convert_vec(x.col(j)),\n                           method,\n                           utils::convert_vec(weights),\n                           remove_missing);\n            ms(j, i) = ms(i, j);\n        }\n    }\n\n    return ms;\n}\n\n}\n", "meta": {"hexsha": "a2f15ab93949d7f75113c35ed89c5736babf6ad6", "size": 3349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/wdm/eigen.hpp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/wdm/eigen.hpp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/wdm/eigen.hpp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 35.2526315789, "max_line_length": 76, "alphanum_fraction": 0.555091072, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5668680468700711}}
{"text": "#ifndef HYPSYS1D_FVM_RATE_OF_CHANGE_HPP\n#define HYPSYS1D_FVM_RATE_OF_CHANGE_HPP\n\n#include <memory>\n#include <Eigen/Dense>\n\n#include <ancse/config.hpp>\n#include <ancse/grid.hpp>\n#include <ancse/model.hpp>\n#include <ancse/rate_of_change.hpp>\n#include <ancse/simulation_time.hpp>\n\n/// Compute the rate of change due to FVM.\n/** The semidiscrete approximation of a PDE using FVM is\n *      du_i/dt = - (F_{i+0.5} - F_{i-0.5}) / dx.\n *  This computes the right hand side of the ODE.\n *\n * @tparam NumericalFlux see e.g. `CentralFlux`.\n * @tparam Reconstruction see e.g. `PWConstantReconstruction`.\n */\ntemplate <class NumericalFlux, class Reconstruction>\nclass FVMRateOfChange : public RateOfChange\n{\n    public:\n        FVMRateOfChange(const Grid& grid,\n                        const std::shared_ptr<Model>& model,\n                        const NumericalFlux& numerical_flux,\n                        const Reconstruction& reconstruction)\n            : grid(grid),\n              model(model),\n              numerical_flux(numerical_flux),\n              reconstruction(reconstruction) {}\n\n        virtual void operator()(Eigen::MatrixXd& dudt,\n                                const Eigen::MatrixXd& u0) const override\n        {\n            // implement the flux loop here.\n            const int n_cells= grid.n_cells;\n            const int n_ghost= grid.n_ghost;\n\n            const int n_vars= model->get_nvars();\n\n            const double dx= grid.dx;\n            Eigen::VectorXd fL= Eigen::VectorXd::Zero(n_vars), fR= Eigen::VectorXd::Zero(n_vars);\n            Eigen::VectorXd uL, uR;\n\n            for (int i= n_ghost - 1; i < n_cells - n_ghost; ++i)\n            {\n                std::tie(uL, uR)= reconstruction(u0, i);\n             \n                fL= fR;\n                fR= numerical_flux(uL, uR);\n\n                dudt.col(i)= (fL - fR) / dx;\n            }\n        }\n\n    private:\n        Grid grid;\n        std::shared_ptr<Model> model;\n        NumericalFlux numerical_flux;\n        Reconstruction reconstruction;\n};\n\nstd::shared_ptr<RateOfChange>\nmake_fvm_rate_of_change(const nlohmann::json &config,\n                        const Grid &grid,\n                        const std::shared_ptr<Model> &model,\n                        const std::shared_ptr<SimulationTime> &simulation_time);\n\n#endif // HYPSYS1D_FVM_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "4e664d38cda532a950f5b037c416f0dd9a0466c2", "size": 2333, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/fvm_rate_of_change.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/fvm_rate_of_change.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/fvm_rate_of_change.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 32.4027777778, "max_line_length": 97, "alphanum_fraction": 0.58936991, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5668680335693561}}
{"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_VECTOR3D_HPP\n#define RW_MATH_VECTOR3D_HPP\n\n/**\n * @file Vector3D.hpp\n */\n\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Eigen>\n#endif\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A 3D vector @f$ \\mathbf{v}\\in \\mathbb{R}^3 @f$\n     *\n     * @f$ \\robabx{i}{j}{\\mathbf{v}} = \\left[\n     *  \\begin{array}{c}\n     *  v_x \\\\\n     *  v_y \\\\\n     *  v_z\n     *  \\end{array}\n     *  \\right]\n     *  @f$\n     *\n     *  Usage example:\n     *\n     *  \\code\n     *  const Vector3D<> v1(1.0, 2.0, 3.0);\n     *  const Vector3D<> v2(6.0, 7.0, 8.0);\n     *  const Vector3D<> v3 = cross(v1, v2);\n     *  const double d = dot(v1, v2);\n     *  const Vector3D<> v4 = v2 - v1;\n     *  \\endcode\n     */\n    template< class T = double > class Vector3D\n    {\n      public:\n        //! Eigen type equivalent to Vector3D\n        typedef Eigen::Matrix< T, 3, 1 > EigenVector3D;\n\n        //! Value type.\n        typedef T value_type;\n\n        /**\n         * @brief Creates a 3D vector initialized with 0's\n         */\n        Vector3D ()\n        {\n            _vec[0] = 0;\n            _vec[1] = 0;\n            _vec[2] = 0;\n        }\n\n        /**\n         * @brief Creates a 3D vector\n         * @param x [in] @f$ x @f$\n         * @param y [in] @f$ y @f$\n         * @param z [in] @f$ z @f$\n         */\n        Vector3D (T x, T y, T z)\n        {\n            _vec[0] = x;\n            _vec[1] = y;\n            _vec[2] = z;\n        }\n        \n        /**\n         * @brief Copy constructor\n         * @param vec [in] vector to copy\n         */\n        Vector3D (const Vector3D<T>& copy_vec): _vec(copy_vec._vec)\n        {\n        }\n\n        /**\n         * @brief Creates a 3D vector from vector_expression\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > explicit Vector3D (const Eigen::MatrixBase< R >& r)\n        {\n            _vec[0] = T( r.row (0) (0));\n            _vec[1] = T( r.row (1) (0));\n            _vec[2] = T( r.row (2) (0));\n        }\n\n        /**\n         * @brief construct vector from std::vector\n         * @param vec [in] the vector to construct from\n         */\n        Vector3D (const std::vector< T >& vec)\n        {\n            if (vec.size () != 3u) {\n                RW_THROW (\"Wrong Size vector matrix: N of size:\" << 3 << \" and vector of size: \"\n                                                                 << vec.size () << \"given\");\n            }\n            for (size_t i = 0; i < 3u; i++) {\n                _vec[i] = vec[i];\n            }\n        }\n\n        /**\n         *  @brief The dimension of the vector (i.e. 3).\n         * This method is provided to help support generic algorithms using\n         * size() and operator[].\n         * @return the size\n         */\n        size_t size () const { return 3u; }\n\n        /**\n         * @brief Get zero vector.\n         * @return vector.\n         */\n        static Vector3D< T > zero () { return Vector3D< T > (0, 0, 0); }\n\n        /**\n         * @brief Get x vector (1,0,0)\n         * @return vector.\n         */\n        static Vector3D< T > x () { return Vector3D< T > (1.0, 0, 0); }\n\n        /**\n         * @brief Get y vector (0,1,0)\n         * @return vector.\n         */\n        static Vector3D< T > y () { return Vector3D< T > (0, 1.0, 0); }\n\n        /**\n         * @brief Get z vector (0,0,1)\n         * @return vector.\n         */\n        static Vector3D< T > z () { return Vector3D< T > (0, 0, 1.0); }\n\n        // ###################################################\n        // #                 Math Operations                 #\n        // ###################################################\n\n        // ########## Eigen Operations\n\n        /**\n         * @brief element wise division.\n         * @param rhs [in] the vector being devided with\n         * @return the resulting Vector3D\n         */\n        template< class R > Vector3D< T > elemDivide (const Eigen::MatrixBase< R >& rhs) const\n        {\n            Vector3D< T > ret = *this;\n            for (size_t i = 0; i < size (); i++) {\n                ret._vec[i] /= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Elementweise multiplication.\n         * @param rhs [in] vector\n         * @return the element wise product\n         */\n        template< class R > Vector3D< T > elemMultiply (const Eigen::MatrixBase< R >& rhs) const\n        {\n            Vector3D< T > ret = *this;\n            for (size_t i = 0; i < size (); i++) {\n                ret._vec[i] *= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > Vector3D< T > operator- (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return Vector3D< T > (_vec - rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend Vector3D< T > operator- (const Eigen::MatrixBase< R >& lhs, const Vector3D< T >& rhs)\n        {\n            return Vector3D< T > (lhs - rhs.e ());\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > Vector3D< T > operator+ (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return Vector3D< T > (_vec + rhs);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R >\n        friend Vector3D< T > operator+ (const Eigen::MatrixBase< R >& lhs, const Vector3D< T >& rhs)\n        {\n            return Vector3D< T > (lhs + rhs.e ());\n        }\n\n        // ########## Vector3D Operations\n\n        /**\n         * @brief element wise division.\n         * @param rhs [in] the vector being devided with\n         * @return the resulting Vector3D\n         */\n        Vector3D< T > elemDivide (const Vector3D< T >& rhs) const\n        {\n            return Vector3D< T > (\n                _vec[0] / rhs._vec[0], _vec[1] / rhs._vec[1], _vec[2] / rhs._vec[2]);\n        }\n\n        /**\n         * @brief Elementweise multiplication.\n         * @param rhs [in] vector\n         * @return the element wise product\n         */\n        Vector3D< T > elemMultiply (const Vector3D< T >& rhs) const\n        {\n            return Vector3D< T > (\n                _vec[0] * rhs._vec[0], _vec[1] * rhs._vec[1], _vec[2] * rhs._vec[2]);\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        Vector3D< T > operator- (const Vector3D< T >& b) const\n        {\n            return Vector3D< T > (_vec[0] - b[0], _vec[1] - b[1], _vec[2] - b[2]);\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        Vector3D< T > operator+ (const Vector3D< T >& b) const\n        {\n            return Vector3D< T > (_vec[0] + b[0], _vec[1] + b[1], _vec[2] + b[2]);\n        }\n\n        /**\n         * @brief Unary minus.\n         * @brief negative version\n         */\n        Vector3D< T > operator- () const { return Vector3D< T > (-_vec[0], -_vec[1], -_vec[2]); }\n\n        // ########## Scalar Operations\n\n        /**\n         * @brief Scalar division.\n         * @param s [in] the scalar to devide with\n         * @return result of devision\n         */\n        Vector3D< T > operator/ (T s) const\n        {\n            return Vector3D< T > (_vec[0] / s, _vec[1] / s, _vec[2] / s);\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar division.\n         * @param lhs [in] the scalar to devide with\n         * @param rhs [out] the vector beind devided\n         * @return result of devision\n         */\n        friend Vector3D< T > operator/ (T lhs, const Vector3D< T >& rhs)\n        {\n            return Vector3D< T > (lhs / rhs._vec[0], lhs / rhs._vec[1], lhs / rhs._vec[2]);\n        }\n#endif\n        /**\n         * @brief Scalar multiplication.\n         * @param rhs [in] the scalar to multiply with\n         * @return the product\n         */\n        Vector3D< T > operator* (T rhs) const\n        {\n            return Vector3D< T > (_vec[0] * rhs, _vec[1] * rhs, _vec[2] * rhs);\n        }\n\n        /**\n         * @brief Scalar multiplication.\n         * @param lhs [in] the scalar to multiply with\n         * @param rhs [in] the Vector to be multiplied\n         * @return the product\n         */\n        friend Vector3D< T > operator* (T lhs, const Vector3D< T >& rhs)\n        {\n            return Vector3D< T > (lhs * rhs[0], lhs * rhs[1], lhs * rhs[2]);\n        }\n\n        /**\n         * @brief Scalar multiplication.\n         * @param rhs [in] the Eigen vector^T or matrix to multiply with\n         * @return the product\n         */\n        template< class R > Vector3D< T > operator* (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return Vector3D< T > (this->e()*rhs);\n        }\n\n        /**\n         * @brief Scalar multiplication.\n         * @param lhs [in] the Eigen vector^T or matrix to multiply with\n         * @param rhs [in] the Vector to be multiplied\n         * @return the product\n         */\n        template< class R > friend Vector3D< T > operator* (const Eigen::MatrixBase< R >& lhs, const Vector3D< T >& rhs)\n        {\n            return Vector3D< T > (lhs*rhs.e());\n        }\n\n        /**\n         * @brief Scalar subtraction.\n         */\n        Vector3D< T > elemSubtract (const T rhs) const\n        {\n            return Vector3D< T > (_vec[0] - rhs, _vec[1] - rhs, _vec[2] - rhs);\n        }\n\n        /**\n         * @brief Scalar addition.\n         */\n        Vector3D< T > elemAdd (const T rhs) const\n        {\n            return Vector3D< T > (_vec[0] + rhs, _vec[1] + rhs, _vec[2] + rhs);\n        }\n\n        // ########### Math Functions\n\n        /**\n         * @brief Returns the Euclidean norm (2-norm) of the vector\n         * @return the norm\n         */\n        T norm2 () const\n        {\n            return sqrt (_vec[0] * _vec[0] + _vec[1] * _vec[1] + _vec[2] * _vec[2]);\n        }\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]) + fabs (_vec[2]); }\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            const T f2 = fabs (_vec[2]);\n            if (f2 > res)\n                res = f2;\n            return res;\n        }\n\n        /**\n         * @brief Calculate cross product\n         * @param vec [in] the vector to cross with\n         * @return the cross product\n         */\n        Vector3D< T > cross (const Vector3D& vec) const\n        {\n            return Vector3D< T > (_vec.cross (vec._vec));\n        }\n\n        /**\n         * @brief calculate the dot product\n         * @param vec [in] the vecor to be dotted\n         * @return the dot product\n         */\n        T dot (const Vector3D& vec) const { return _vec.dot (vec._vec); }\n\n        /**\n         * @brief normalize vector to get length 1\n         * @return the normalized Vector\n         */\n        Vector3D< T > normalize ()\n        {\n            T length = norm2 ();\n            if (length != 0)\n                return (*this) / length;\n            else\n                return Vector3D< T > (0, 0, 0);\n        }\n\n        // ###################################################\n        // #                Acces Operators                  #\n        // ###################################################\n\n        /**\n         * @brief Returns Reference to Eigen Vector\n         * @return reference to underling eigen\n         */\n        EigenVector3D& e () { return _vec; }\n\n        /**\n         * @brief Returns Reference to Eigen Vector\n         * @return copy of eigen vector\n         */\n        const EigenVector3D e () const { return _vec; }\n\n#if !defined(SWIG)\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\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#if !defined(SWIG)\n        /**\n         * @brief Streaming operator.\n         * @param out [in/out] the stream to continue\n         * @param v [in] the vector to stream\n         * @param reference to \\b out\n         */\n        friend std::ostream& operator<< (std::ostream& out, const Vector3D< T >& v)\n        {\n            return out << \"Vector3D(\" << v[0] << \", \" << v[1] << \", \" << v[2] << \")\";\n        }\n#else\n        TOSTRING (rw::math::Vector3D< T >);\n#endif\n        // ###################################################\n        // #             assignement Operators               #\n        // ###################################################\n\n        /**\n         * @brief Scalar multiplication.\n         */\n        Vector3D< T >& operator*= (T s)\n        {\n            _vec[0] *= s;\n            _vec[1] *= s;\n            _vec[2] *= s;\n            return *this;\n        }\n\n        /**\n         * @brief Scalar division.\n         */\n        Vector3D< T >& operator/= (T s)\n        {\n            _vec[0] /= s;\n            _vec[1] /= s;\n            _vec[2] /= s;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        Vector3D< T >& operator+= (const Vector3D< T >& v)\n        {\n            _vec[0] += v._vec[0];\n            _vec[1] += v._vec[1];\n            _vec[2] += v._vec[2];\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        Vector3D< T >& operator-= (const Vector3D< T >& v)\n        {\n            _vec[0] -= v._vec[0];\n            _vec[1] -= v._vec[1];\n            _vec[2] -= v._vec[2];\n            return *this;\n        }\n\n        /**\n         * @brief copy a vector from eigen type\n         * @param r [in] an Eigen Vector\n         */\n        template< class R > Vector3D< T >& operator= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec = r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector addition.\n         */\n        template< class R > Vector3D< T >& operator+= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec += r;\n            return *this;\n        }\n\n        /**\n         * @brief Vector subtraction.\n         */\n        template< class R > Vector3D< T >& operator-= (const Eigen::MatrixBase< R >& r)\n        {\n            _vec -= r;\n            return *this;\n        }\n\n        // ###################################################\n        // #                    Comparetors                  #\n        // ###################################################\n\n        /**\n         * @brief Compare with \\b b for equality.\n         * @param b [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const Vector3D< T >& b) const\n        {\n            return _vec[0] == b[0] && _vec[1] == b[1] && _vec[2] == b[2];\n        }\n\n        /**\n           @brief Compare with \\b b for inequality.\n           @param b [in] other vector.\n           @return True if a and b are different, false otherwise.\n        */\n        bool operator!= (const Vector3D< T >& b) const { return !(*this == b); }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R > bool operator== (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return this->_vec == rhs;\n        }\n\n        /**\n         * @brief Compare with \\b rhs for equality.\n         * @param rhs [in] other vector.\n         * @return True if a equals b, false otherwise.\n         */\n        template< class R >\n        friend bool operator== (const Eigen::MatrixBase< R >& lhs, const Vector3D< T >& rhs)\n        {\n            return lhs == rhs._vec;\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param b [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R > bool operator!= (const Eigen::MatrixBase< R >& rhs) const\n        {\n            return !(*this == rhs);\n        }\n\n        /**\n         *  @brief Compare with \\b rhs for inequality.\n         *  @param b [in] other vector.\n         *  @return True if a and b are different, false otherwise.\n         */\n        template< class R >\n        friend bool operator!= (const Eigen::MatrixBase< R >& lhs, const Vector3D< T >& rhs)\n        {\n            return !(lhs == rhs);\n        }\n#if !defined(SWIG)\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator EigenVector3D () const { return this->e (); }\n\n        /**\n         * @brief implicit conversion to EigenVector\n         */\n        operator EigenVector3D& () { return this->e (); }\n#endif\n\n      private:\n        EigenVector3D _vec;\n    };\n\n    /**\n     * @brief Calculates the 3D vector cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the 3D vector cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * The 3D vector cross product is defined as:\n     * @f$\n     * \\mathbf{v1} \\times \\mathbf{v2} = \\left[\\begin{array}{c}\n     *  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     * \\end{array}\\right]\n     * @f$\n     *\n     * @relates Vector3D\n     */\n    template< class T > const Vector3D< T > cross (const Vector3D< T >& v1, const Vector3D< T >& v2)\n    {\n        return Vector3D< T > (v1[1] * v2[2] - v1[2] * v2[1],\n                              v1[2] * v2[0] - v1[0] * v2[2],\n                              v1[0] * v2[1] - v1[1] * v2[0]);\n    }\n\n    /**\n     * @brief Calculates the 3D vector cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     * @param dst [out] the 3D vector cross product @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     *\n     * The 3D vector cross product is defined as:\n     * @f$\n     * \\mathbf{v1} \\times \\mathbf{v2} = \\left[\\begin{array}{c}\n     *  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     * \\end{array}\\right]\n     * @f$\n     *\n     * @relates Vector3D\n     */\n    template< class T >\n    void cross (const Vector3D< T >& v1, const Vector3D< T >& v2, Vector3D< T >& dst)\n    {\n        dst[0] = v1[1] * v2[2] - v1[2] * v2[1];\n        dst[1] = v1[2] * v2[0] - v1[0] * v2[2];\n        dst[2] = 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     * @relates Vector3D\n     */\n    template< class T > T dot (const Vector3D< T >& v1, const Vector3D< T >& v2)\n    {\n        return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];\n        // return inner_prod(v1.m(), v2.m());\n    }\n\n    /**\n     * @brief Returns the normalized vector \\f$\\mathbf{n}=\\frac{\\mathbf{v}}{\\|\\mathbf{v}\\|} \\f$.\n     * In case \\f$ \\|mathbf{v}\\| = 0\\f$ the zero vector is returned.\n     * @param v [in] \\f$ \\mathbf{v} \\f$ which should be normalized\n     * @return the normalized vector \\f$ \\mathbf{n} \\f$\n     *\n     * @relates Vector3D\n     */\n    template< class T > const Vector3D< T > normalize (const Vector3D< T >& v)\n    {\n        T length = v.norm2 ();\n        if (length != 0)\n            return Vector3D< T > (v (0) / length, v (1) / length, v (2) / length);\n        else\n            return Vector3D< T > (0, 0, 0);\n    }\n\n    /**\n     * @brief Calculates the angle from @f$ \\mathbf{v1}@f$ to @f$ \\mathbf{v2} @f$\n     * around the axis defined by @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$ with n\n     * determining the sign.\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     * @param n [in] @f$ \\mathbf{n} @f$\n     *\n     * @return the angle\n     *\n     * @relates Vector3D\n     */\n    template< class T >\n    double angle (const Vector3D< T >& v1, const Vector3D< T >& v2, const Vector3D< T >& n)\n    {\n        const Vector3D< T > nv1 = normalize (v1);\n        const Vector3D< T > nv2 = normalize (v2);\n        const Vector3D< T > nn  = normalize (n);\n        return atan2 (dot (nn, cross (nv1, nv2)), dot (nv1, nv2));\n    }\n\n    /**\n     * @brief Calculates the angle from @f$ \\mathbf{v1}@f$ to @f$ \\mathbf{v2} @f$\n     * around the axis defined by @f$ \\mathbf{v1} \\times \\mathbf{v2} @f$\n     * @param v1 [in] @f$ \\mathbf{v1} @f$\n     * @param v2 [in] @f$ \\mathbf{v2} @f$\n     *\n     * @return the angle\n     *\n     * @relates Vector3D\n     */\n    template< class T > double angle (const Vector3D< T >& v1, const Vector3D< T >& v2)\n    {\n        Vector3D< T > n = cross (v1, v2);\n        return angle (v1, v2, n);\n    }\n\n    /**\n     * @brief Casts Vector3D<T> to Vector3D<Q>\n     * @param v [in] Vector3D with type T\n     * @return Vector3D with type Q\n     *\n     * @relates Vector3D\n     */\n    template< class Q, class T > const Vector3D< Q > cast (const Vector3D< T >& v)\n    {\n        return Vector3D< Q > (\n            static_cast< Q > (v (0)), static_cast< Q > (v (1)), static_cast< Q > (v (2)));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::Vector3D< double >;\n    extern template class rw::math::Vector3D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Vector3Dd, rw::math::Vector3D< double >);\n    SWIG_DECLARE_TEMPLATE (Vector3Df, rw::math::Vector3D< float >);\n#endif\n\n    using Vector3Dd = Vector3D< double >;\n    using Vector3Df = Vector3D< 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::Vector3D\n         */\n        template<>\n        void write (const rw::math::Vector3D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Vector3D\n         */\n        template<>\n        void write (const rw::math::Vector3D< float >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Vector3D\n         */\n        template<>\n        void read (rw::math::Vector3D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Vector3D\n         */\n        template<>\n        void read (rw::math::Vector3D< 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::Vector3D\n     */\n    template< class Archive, class T >\n    void serialize (Archive& archive, rw::math::Vector3D< T >& vector, const unsigned int version)\n    {\n        archive& vector[0];\n        archive& vector[1];\n        archive& vector[2];\n    }\n}}    // namespace boost::serialization\n\n#endif    // end include guard\n", "meta": {"hexsha": "768c4257b94dda66a1896513c31443add03eaa06", "size": 25470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Vector3D.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/Vector3D.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/Vector3D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7237635706, "max_line_length": 120, "alphanum_fraction": 0.4681193561, "num_tokens": 7207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384736, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.5667911258499442}}
{"text": "/*\n * Copyright 2020 Ryan Levy, Xiongjie Yu, and Bryan K. Clark\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *     http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#include <iostream>\n#include <complex>\n#include <Eigen/Dense>\n\n#include \"tblis.h\"\n\nint main(int argc, char const *argv[]) {\n\tint s1=2, s2=3, s3=4;\n\tEigen::MatrixXcd mA(s1,s2);\n\tmA.setRandom();\n\tEigen::MatrixXcd mB(s2,s3);\n\tmB.setRandom();\n\tEigen::MatrixXcd mC(s1,s3);\n\tmC.setRandom();\n\tstd::cout << \"/-------------------------------------------------/\" << '\\n';\n\tstd::cout << \"Matrix mA:\" << '\\n';\n\tstd::cout << mA << '\\n' << '\\n';\n\tstd::cout << \"Matrix mB:\" << '\\n';\n\tstd::cout << mB << '\\n' << '\\n';\n\tstd::cout << \"Matrix mA*mB+mC:\" << '\\n';\n\tstd::cout << mA*mB+mC << '\\n' << '\\n';\n\tstd::cout << \"/-------------------------------------------------/\" << '\\n';\n\n\ttblis::tensor_view< std::complex<double> > A({s1,s2}, mA.data());\n\ttblis::tensor_view< std::complex<double> > B({s2,s3}, mB.data());\n\ttblis::tensor_view< std::complex<double> > C({s1,s3}, mC.data());\n\n\ttblis::mult(std::complex<double>(1.0),A,\"ab\",B,\"bc\",std::complex<double>(1.0),C,\"ac\");\n\n\tstd::cout << \"tblis results:\" << '\\n';\n\tstd::cout << mC << '\\n' << '\\n';\n\n\tstd::cout << \"/-------------------------------------------------/\" << '\\n';\n  return 0;\n}\n", "meta": {"hexsha": "bf5edb48a1a7d2493aec888b5be68075f9266a3e", "size": 1750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deprecated-examples/tblis/main.cpp", "max_stars_repo_name": "ClarkResearchGroup/tensor-tools", "max_stars_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-07-14T01:55:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T14:06:59.000Z", "max_issues_repo_path": "deprecated-examples/tblis/main.cpp", "max_issues_repo_name": "ClarkResearchGroup/tensor-tools", "max_issues_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-31T02:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T16:18:36.000Z", "max_forks_repo_path": "deprecated-examples/tblis/main.cpp", "max_forks_repo_name": "ClarkResearchGroup/tensor-tools", "max_forks_repo_head_hexsha": "25fe4553991d2680b43301aef1960e4c20f1e146", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T03:40:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T03:40:26.000Z", "avg_line_length": 33.0188679245, "max_line_length": 87, "alphanum_fraction": 0.5634285714, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5667395924940587}}
{"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 omni.hpp\n * @author Boston Cleek\n * @date 30 Oct 2020\n * @brief Kinematic omni directional models control wheel velocities or body twist\n */\n#ifndef OMNI_HPP\n#define OMNI_HPP\n\n#include <cmath>\n#include <armadillo>\n\n#include <ergodic_exploration/numerics.hpp>\n\nnamespace ergodic_exploration\n{\nnamespace models\n{\nusing arma::mat;\nusing arma::vec;\n\n/**\n * @brief Kinematic model of 4 mecanum wheel robot\n * @details The state is [x, y, theta] and controls are the angular velocities of each\n * wheel [u0, u1, u2, u3] corresponding to (front left, front right, rear right, rear\n * left). Assumes the mecanum wheel rollers are at +/- 45 degrees\n */\nstruct Mecanum\n{\n  /**\n   * @brief Constructor\n   * @param wheel_radius - radius of wheel\n   * @param wheel_base_x - distance from chassis center to wheel center along x-axis\n   * @param wheel_base_y - distance from chassis center to wheel center along y-axis\n   */\n  Mecanum(double wheel_radius, double wheel_base_x, double wheel_base_y)\n    : wheel_radius(wheel_radius)\n    , wheel_base_x(wheel_base_x)\n    , wheel_base_y(wheel_base_y)\n    , state_space(3)\n  {\n  }\n\n  /**\n   * @brief Convert wheel velocities to a body frame twist\n   * @param u - control [u0, u1, u2, u3]\n   * @return twist in body frame Vb = [vx, vy, w]\n   */\n  vec wheels2Twist(const vec u) const\n  {\n    const auto l = 1.0 / (wheel_base_x + wheel_base_y);\n\n    // pseudo inverse of jacobian matrix\n    const mat Hp = { { 1.0, 1.0, 1.0, 1.0 }, { -1.0, 1.0, -1.0, 1.0 }, { -l, l, l, -l } };\n\n    const vec vb = (wheel_radius / 4.0) * Hp * u;\n\n    return { vb(0), vb(1), vb(2) };\n  }\n\n  /**\n   * @brief Kinematic model of 4 mecanum wheel robot\n   * @param x - state [x, y, theta]\n   * @param u - control [u0, u1, u2, u3]\n   * @return [xdot, ydot, thetadot] = f(x,u)\n   */\n  vec operator()(const vec x, const vec u) const\n  {\n    vec xdot(3);\n    const auto s = (wheel_radius / 4.0) * std::sin(x(2));\n    const auto c = (wheel_radius / 4.0) * std::cos(x(2));\n    const auto l = wheel_radius / (4.0 * (wheel_base_x + wheel_base_y));\n\n    xdot(0) = u(0) * (s + c) + u(1) * (-s + c) + u(2) * (s + c) + u(3) * (-s + c);\n    xdot(1) = u(0) * (s - c) + u(1) * (s + c) + u(2) * (s - c) + u(3) * (s + c);\n    xdot(2) = -u(0) * l + u(1) * l + u(2) * l - u(3) * l;\n\n    return xdot;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the state\n   * @param x - state [x, y, theta]\n   * @param u - control [u0, u1, u2, u3]\n   * @return A = D1(f(x,u)) of shape (3x3)\n   */\n  mat fdx(const vec x, const vec u) const\n  {\n    mat A(3, 3, arma::fill::zeros);\n\n    const auto s = (wheel_radius / 4.0) * std::sin(x(2));\n    const auto c = (wheel_radius / 4.0) * std::cos(x(2));\n\n    const auto df0dth =\n        u(0) * (-s + c) + u(1) * (-s - c) + u(2) * (-s + c) + u(3) * (-s - c);\n    const auto df1dth =\n        u(0) * (s + c) + u(1) * (-s + c) + u(2) * (s + c) + u(3) * (-s + c);\n\n    A(0, 2) = df0dth;\n    A(1, 2) = df1dth;\n\n    return A;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the control\n   * @param x - state [x, y, theta]\n   * @return B = D2(f(x,u)) of shape (3x4)\n   */\n  mat fdu(const vec x) const\n  {\n    const auto s = (wheel_radius / 4.0) * std::sin(x(2));\n    const auto c = (wheel_radius / 4.0) * std::cos(x(2));\n    const auto l = wheel_radius / (4.0 * (wheel_base_x + wheel_base_y));\n\n    const mat B = { { s + c, -s + c, s + c, -s + c },\n                    { s - c, s + c, s - c, s + c },\n                    { -l, l, l, -l } };\n    return B;\n  }\n\n  double wheel_radius;       // radius of wheel\n  double wheel_base_x;       // distance from chassis center to wheel center along x-axis\n  double wheel_base_y;       // distance from chassis center to wheel center along y-axis\n  unsigned int state_space;  // states space dimension\n};\n\n/**\n * @brief Kinematic model of omni directonal robot\n * @details The state is [x, y, theta] and controls are the linear and\n * angular velocities [vx, vy, w] (body twist)\n */\nstruct Omni\n{\n  /** @brief Constructor */\n  Omni() : state_space(3)\n  {\n  }\n\n  /**\n   * @brief Kinematic model of 4 mecanum wheel robot\n   * @param x - state [x, y, theta]\n   * @param u - body twist control [vx, vy, w]\n   * @return [xdot, ydot, thetadot] = f(x,u)\n   */\n  vec operator()(const vec x, const vec u) const\n  {\n    const auto xdot = u(0) * std::cos(x(2)) - u(1) * std::sin(x(2));\n    const auto ydot = u(0) * std::sin(x(2)) + u(1) * std::cos(x(2));\n    return { xdot, ydot, u(2) };\n    // return { xdot, ydot, 0.0 };\n    // return { u(0), u(1), u(2) };\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the state\n   * @param x - state [x, y, theta]\n   * @param u - body twist control [vx, vy, w]\n   * @return A = D1(f(x,u)) of shape (3x3)\n   */\n  mat fdx(const vec x, const vec u) const\n  {\n    mat A(3, 3, arma::fill::zeros);\n    A(0, 2) = -u(0) * std::sin(x(2)) - u(1) * std::cos(x(2));\n    A(1, 2) = u(0) * std::cos(x(2)) - u(1) * std::sin(x(2));\n    return A;\n  }\n\n  /**\n   * @brief Jacobian of the model with respect to the control\n   * @param x - state [x, y, theta]\n   * @return B = D2(f(x,u)) of shape (3x3)\n   */\n  mat fdu(const vec x) const\n  {\n    // mat B(3,3, arma::fill::eye);\n    const mat B = { { std::cos(x(2)), -std::sin(x(2)), 0.0 },\n                    { std::sin(x(2)), std::cos(x(2)), 0.0 },\n                    { 0.0, 0.0, 1.0 } };\n    return B;\n  }\n\n  unsigned int state_space;  // states space dimension\n};\n}  // namespace models\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "8fe70f0439ee2ceabbeda84e9107a2b37ea8ab65", "size": 7244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/models/omni.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/models/omni.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/models/omni.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": 33.0776255708, "max_line_length": 90, "alphanum_fraction": 0.5933186085, "num_tokens": 2294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5667395864875525}}
{"text": "#include <aslam/backend/MEstimatorPolicies.hpp>\n\n#include <cmath>\n\n#include <sstream>\n\n#include <boost/math/distributions/chi_squared.hpp>\n\nnamespace aslam {\nnamespace backend {\n\nMEstimator::~MEstimator() {}\n\nNoMEstimator::~NoMEstimator() {}\ndouble NoMEstimator::getWeight(double /* squaredError */) const { return 1.0; }\nstd::string NoMEstimator::name() const { return \"none\"; }\n\nGemanMcClureMEstimator::GemanMcClureMEstimator(double sigma2) : _sigma2(sigma2) {}\nGemanMcClureMEstimator::~GemanMcClureMEstimator() {}\ndouble GemanMcClureMEstimator::getWeight(double error) const {\n    double se = _sigma2 + error;\n    return (_sigma2) / (se * se);\n}\nstd::string GemanMcClureMEstimator::name() const {\n    std::stringstream ss;\n    ss << \"Geman McClure (\" << _sigma2 << \")\";\n    return ss.str();\n}\n\nCauchyMEstimator::CauchyMEstimator(double sigma2) : _sigma2(sigma2) {}\nCauchyMEstimator::~CauchyMEstimator() {}\ndouble CauchyMEstimator::getWeight(double error) const {\n    double se = error / _sigma2;\n    return 1.0 / (1.0 + se);\n}\nstd::string CauchyMEstimator::name() const {\n    std::stringstream ss;\n    ss << \"Cauchy (\" << _sigma2 << \")\";\n    return ss.str();\n}\n\nHuberMEstimator::~HuberMEstimator() {}\nHuberMEstimator::HuberMEstimator(double k) : _k(k), _k2(k * k) {}\ndouble HuberMEstimator::getWeight(double error) const { return error < _k2 ? 1.0 : _k / sqrt(error); }\nstd::string HuberMEstimator::name() const {\n    std::stringstream ss;\n    ss << \"Huber(\" << _k << \")\";\n    return ss.str();\n}\n\nBlakeZissermanMEstimator::~BlakeZissermanMEstimator() {}\nBlakeZissermanMEstimator::BlakeZissermanMEstimator(size_t df, double pCut, double wCut)\n    : _df(df), _pCut(pCut), _wCut(wCut), _epsilon(computeEpsilon(df, pCut, wCut)) {}\nBlakeZissermanMEstimator::BlakeZissermanMEstimator(const BlakeZissermanMEstimator& other)\n    : MEstimator(other), _df(other._df), _pCut(other._pCut), _wCut(other._wCut), _epsilon(other._epsilon) {}\nBlakeZissermanMEstimator& BlakeZissermanMEstimator::operator=(const BlakeZissermanMEstimator& other) {\n    if (this != &other) {\n        MEstimator::operator=(other);\n        _df = other._df;\n        _pCut = other._pCut;\n        _wCut = other._wCut;\n        _epsilon = other._epsilon;\n    }\n    return *this;\n}\ndouble BlakeZissermanMEstimator::getWeight(double mahalanobis2) const {\n    return exp(-mahalanobis2) / (exp(-mahalanobis2) + _epsilon);\n}\nstd::string BlakeZissermanMEstimator::name() const {\n    std::stringstream ss;\n    ss << \"Blake-Zisserman(\" << _epsilon << \")\";\n    return ss.str();\n}\ndouble BlakeZissermanMEstimator::chi2InvCDF(double p, size_t df) const {\n    return boost::math::quantile(boost::math::chi_squared_distribution<>(df), p);\n}\ndouble BlakeZissermanMEstimator::computeEpsilon(size_t df, double pCut, double wCut) const {\n    return (1 - wCut) / wCut * exp(-chi2InvCDF(pCut, df));\n}\n\n}  // namespace backend\n}  // namespace aslam\n", "meta": {"hexsha": "d4f761ce871e2c82b455fed6dc3d0f4645f7b979", "size": 2888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_optimizer/aslam_backend/src/MEstimatorPolicies.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_optimizer/aslam_backend/src/MEstimatorPolicies.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_optimizer/aslam_backend/src/MEstimatorPolicies.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7951807229, "max_line_length": 108, "alphanum_fraction": 0.7029085873, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5667309715441472}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include math.hpp directly!\"\n#endif\n\n#pragma once\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\nnamespace matheval {\n\nnamespace math {\n\n/// @brief Sign function\ntemplate <typename T>\nT sgn(T x) {\n    return (T(0) < x) - (x < T(0));\n}\n\n/// @brief isnan function with adjusted return type\ntemplate <typename T>\nT isnan(T x) {\n    return std::isnan(x);\n}\n\n/// @brief isinf function with adjusted return type\ntemplate <typename T>\nT isinf(T x) {\n    return std::isinf(x);\n}\n\n/// @brief Convert radians to degrees\ntemplate <typename T>\nT deg(T x) {\n    return x * boost::math::constants::radian<T>();\n}\n\n/// @brief Convert degrees to radians\ntemplate <typename T>\nT rad(T x) {\n    return x * boost::math::constants::degree<T>();\n}\n\n/// @brief unary plus\ntemplate <typename T>\nT plus(T x) {\n    return x;\n}\n\n/// @brief binary plus\ntemplate <typename T>\nT plus(T x, T y) {\n    return x + y;\n}\n\n/// @brief unary minus\ntemplate <typename T>\nT minus(T x) {\n    return -x;\n}\n\n/// @brief binary minus\ntemplate <typename T>\nT minus(T x, T y) {\n    return x - y;\n}\n\n/// @brief multiply\ntemplate <typename T>\nT multiplies(T x, T y) {\n    return x * y;\n}\n\n/// @brief divide\ntemplate <typename T>\nT divides(T x, T y) {\n    return x / y;\n}\n\n/// @brief unary not\ntemplate <typename T>\nT unary_not(T x) {\n    return !x;\n}\n\n/// @brief logical and\ntemplate <typename T>\nT logical_and(T x, T y) {\n    return x && y;\n}\n\n/// @brief logical or\ntemplate <typename T>\nT logical_or(T x, T y) {\n    return x || y;\n}\n\n/// @brief less\ntemplate <typename T>\nT less(T x, T y) {\n    return x < y;\n}\n\n/// @brief less equals\ntemplate <typename T>\nT less_equals(T x, T y) {\n    return x <= y;\n}\n\n/// @brief greater\ntemplate <typename T>\nT greater(T x, T y) {\n    return x > y;\n}\n\n/// @brief greater equals\ntemplate <typename T>\nT greater_equals(T x, T y) {\n    return x >= y;\n}\n\n/// @brief equals\ntemplate <typename T>\nT equals(T x, T y) {\n    return x == y;\n}\n\n/// @brief not equals\ntemplate <typename T>\nT not_equals(T x, T y) {\n    return x != y;\n}\n\n} // namespace math\n\n} // namespace matheval\n", "meta": {"hexsha": "97b0028d3f9862fd69c68c92f78b807a36af52db", "size": 2126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_matheval/src/qi/math.hpp", "max_stars_repo_name": "0um/PrecisionCheck", "max_stars_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T01:58:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:49:05.000Z", "max_issues_repo_path": "libs/boost_matheval/src/qi/math.hpp", "max_issues_repo_name": "0um/PrecisionCheck", "max_issues_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-11-07T04:32:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T06:53:42.000Z", "max_forks_repo_path": "libs/boost_matheval/src/qi/math.hpp", "max_forks_repo_name": "0um/PrecisionCheck", "max_forks_repo_head_hexsha": "dc74ccd6e56e270ec360f0f7e8d5aff2432ee9d3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T03:03:03.000Z", "avg_line_length": 15.4057971014, "max_line_length": 51, "alphanum_fraction": 0.6237064911, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257653, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5667309715441471}}
{"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 <vinecopulib/bicop/family.hpp>\n#include <vinecopulib/misc/tools_interpolation.hpp>\n#include <vinecopulib/misc/tools_stats.hpp>\n#include <wdm/eigen.hpp>\n\nnamespace vinecopulib {\ninline TllBicop::TllBicop()\n{\n  family_ = BicopFamily::tll;\n}\n\ninline Eigen::VectorXd\nTllBicop::gaussian_kernel_2d(const Eigen::MatrixXd& x)\n{\n  return tools_stats::dnorm(x).rowwise().prod();\n}\n\n//! selects the bandwidth matrix for local líkelihood estimator (covariance\n//! times appropriate factor).\ninline Eigen::Matrix2d\nTllBicop::select_bandwidth(const Eigen::MatrixXd& x,\n                           std::string method,\n                           const Eigen::VectorXd& weights)\n{\n  size_t n = x.rows();\n  double cor = wdm::wdm(x, \"cor\", weights)(0, 1);\n  cor = std::min(std::max(cor, -0.95), 0.95);\n  Eigen::Matrix2d cov = Eigen::MatrixXd::Identity(2, 2);\n  cov(0, 1) = cor;\n  cov(1, 0) = cor;\n\n  double mult;\n  if (method == \"constant\") {\n    mult = std::pow(n, -1.0 / 3.0);\n  } else {\n    double degree;\n    if (method == \"linear\") {\n      degree = 1.0;\n    } else {\n      degree = 2.0;\n    }\n    mult = 1.5 * std::pow(n, -1.0 / (2.0 * degree + 1.0));\n  }\n  double mcor = tools_stats::pairwise_mcor(x, weights);\n  double scale = std::pow(std::fabs(cor / mcor), 0.5 * mcor);\n\n  return mult * cov * scale;\n}\n\n//! calculates the cholesky root of a 2x2 matrix.\ninline Eigen::Matrix2d\nchol22(const Eigen::Matrix2d& B)\n{\n\n  Eigen::Matrix2d rB;\n\n  rB(0, 0) = std::sqrt(B(0, 0));\n  rB(0, 1) = 0.0;\n  rB(1, 0) = B(1, 0) / rB(0, 0);\n  rB(1, 1) = std::sqrt(B(1, 1) - rB(1, 0) * rB(1, 0));\n\n  return rB;\n}\n\n//! evaluates local likleihood density estimate.\n//!\n//! @param x Evaluation points.\n//! @param x_data Observations.\n//! @param B Bandwidth matrix.\n//! @param method Order of local polynomial approximation; either `\"constant\"`,\n//!   `\"linear\"`, or `\"quadratic\"`.\n//! @param weights Vector of weights for the observations\n//! @return a two-column matrix; first column is estimated density, second\n//!    column is influence of evaluation point.\ninline Eigen::MatrixXd\nTllBicop::fit_local_likelihood(const Eigen::MatrixXd& x,\n                               const Eigen::MatrixXd& x_data,\n                               const Eigen::Matrix2d& B,\n                               std::string method,\n                               const Eigen::VectorXd& weights)\n{\n  size_t m = x.rows();      // number of evaluation points\n  size_t n = x_data.rows(); // number of observations\n\n  // pre-calculate inverse root of bandwidth matrix and determinant\n  Eigen::Matrix2d irB = chol22(B).inverse();\n  double det_irB = irB.determinant();\n\n  // de-correlate data by applying B^{-1/2}\n  Eigen::MatrixXd z = (irB * x.transpose()).transpose();\n  Eigen::MatrixXd z_data = (irB * x_data.transpose()).transpose();\n\n  Eigen::MatrixXd res(m, 2);\n  res.col(0) = Eigen::VectorXd::Ones(m); // result will be a product\n  Eigen::VectorXd kernels(n);\n  Eigen::Vector2d f1;\n  Eigen::Vector2d b;\n  Eigen::Matrix2d S(B);\n  Eigen::MatrixXd zz(n, 2), zz2(n, 2);\n  for (size_t k = 0; k < m; ++k) {\n    zz = z_data - z.row(k).replicate(n, 1);\n    kernels = gaussian_kernel_2d(zz) * det_irB;\n    if (weights.size() > 0)\n      kernels = kernels.cwiseProduct(weights);\n    double f0 = kernels.mean();\n    if (method != \"constant\") {\n      zz = (irB * zz.transpose()).transpose();\n      f1 = zz.cwiseProduct(kernels.replicate(1, 2)).colwise().mean();\n      b = f1 / f0;\n      if (method == \"quadratic\") {\n        zz2 = zz.cwiseProduct(kernels.replicate(1, 2)) /\n              (f0 * static_cast<double>(n));\n        b = B * b;\n        S = (B * (zz.transpose() * zz2) * B - b * b.transpose()).inverse();\n        res(k) *= std::sqrt(S.determinant()) / det_irB;\n      }\n      res(k) *= std::exp(-0.5 * double(b.transpose() * S * b));\n      if ((boost::math::isnan)(res(k)) | (boost::math::isinf)(res(k))) {\n        // inverse operation might go wrong due to rounding when\n        // true value is equal or close to zero\n        res(k) = 0.0;\n      }\n    }\n    res(k, 0) *= f0;\n    if (weights.size() > 0) {\n      // average weight in neighborhood of evaluation point (essentially a\n      // kernel regression estimate);\n      // kernels have already been multiplied with weights above\n      double w = kernels.sum() / kernels.cwiseQuotient(weights).sum();\n      res(k, 1) = calculate_infl(n, f0, b, B, det_irB, S, method, w);\n    } else {\n      res(k, 1) = calculate_infl(n, f0, b, B, det_irB, S, method, 1.0);\n    }\n  }\n\n  if (weights.size() > 0) {\n    // estimate can be negative if negative weights are used\n    res.col(0) = res.col(0).array().max(0.0);\n  }\n\n  return res;\n}\n\n//! calculate influence for data point for density estimate based on\n//! quantities pre-computed in `fit_local_likelihood()`.\ninline double\nTllBicop::calculate_infl(const size_t& n,\n                         const double& f0,\n                         const Eigen::Vector2d& b,\n                         const Eigen::Matrix2d& B,\n                         const double& det_irB,\n                         const Eigen::Matrix2d& S,\n                         const std::string& method,\n                         const double& weight)\n{\n  Eigen::MatrixXd M;\n  if (method == \"constant\") {\n    M = Eigen::MatrixXd::Constant(1, 1, f0);\n  } else if (method == \"linear\") {\n    M = Eigen::MatrixXd(3, 3);\n    M(0, 0) = f0;\n    M.col(0).tail(2) = B * b * f0;\n    M.row(0).tail(2) = M.col(0).tail(2);\n    M.block(1, 1, 2, 2) = f0 * B + f0 * B * b * b.transpose() * B;\n  } else if (method == \"quadratic\") {\n    M = Eigen::MatrixXd::Zero(6, 6);\n    M(0, 0) = f0;\n    M.col(0).segment(1, 2) = f0 * b;\n    M.row(0).segment(1, 2) = M.col(0).segment(1, 2);\n    M.block(1, 1, 2, 2) = f0 * B + f0 * b * b.transpose();\n    M(3, 0) = 0.5 * M(1, 1);\n    M(4, 0) = 0.5 * M(2, 2);\n    M(5, 0) = M(1, 2);\n    M.row(0).tail(3) = M.col(0).tail(3);\n    Eigen::MatrixXd Si = S.inverse();\n    M(3, 1) = 0.5 * f0 * (3.0 * Si(0, 0) * b(0) + std::pow(b(0), 3));\n    M(4, 2) = 0.5 * f0 * (3.0 * Si(1, 1) * b(1) + std::pow(b(1), 3));\n    M(4, 1) = 0.5 * f0;\n    M(4, 1) *= 2.0 * Si(0, 1) * b(1) + Si(1, 1) * b(0) + b(0) * b(1) * b(1);\n    M(3, 2) = 0.5 * f0;\n    M(3, 2) *= 2.0 * Si(0, 1) * b(0) + Si(0, 0) * b(1) + b(1) * b(0) * b(0);\n    M(5, 1) = 2.0 * M(3, 2);\n    M(5, 2) = 2.0 * M(4, 1);\n    M.block(1, 3, 2, 3) = M.block(3, 1, 3, 2).transpose();\n    M(3, 3) = 0.25 * f0;\n    M(3, 3) *= 3.0 * Si(0, 0) * Si(0, 0) + 6.0 * Si(0, 0) * b(0) * b(0) +\n               std::pow(b(0), 4);\n    M(4, 4) = 0.25 * f0;\n    M(4, 4) *= 3.0 * Si(1, 1) * Si(1, 1) + 6.0 * Si(1, 1) * b(1) * b(1) +\n               std::pow(b(1), 4);\n    M(5, 5) = Si(0, 0) * Si(1, 1) + 2.0 * S(0, 1) + b(0) * b(0) * b(1) * b(1);\n    M(5, 5) += 4.0 * Si(0, 1) * b(0) * b(1);\n    M(5, 5) += Si(0, 0) * b(1) * b(1) + Si(1, 1) * b(0) * b(0);\n    M(5, 5) *= f0;\n    M(4, 3) = M(5, 5) * 0.25;\n    M(3, 4) = M(4, 3);\n    M(5, 3) = 3.0 * Si(0, 0) * Si(0, 1) + 3.0 * Si(0, 1) * b(0) * b(0);\n    M(5, 3) += 3.0 * Si(0, 0) * b(0) * b(1) + b(1) * std::pow(b(0), 3);\n    M(5, 3) *= 0.5 * f0;\n    M(3, 5) = M(5, 3);\n    M(5, 4) = 3.0 * Si(1, 1) * Si(0, 1) + 3.0 * Si(0, 1) * b(1) * b(1);\n    M(5, 4) += 3.0 * Si(1, 1) * b(0) * b(1) + b(0) * std::pow(b(1), 3);\n    M(5, 4) *= 0.5 * f0;\n    M(4, 5) = M(5, 4);\n  }\n\n  double infl = gaussian_kernel_2d(Eigen::MatrixXd::Zero(1, 2))(0) * det_irB;\n  infl *= M.inverse()(0, 0) * weight / static_cast<double>(n);\n  return infl;\n}\n\ninline void\nTllBicop::fit(const Eigen::MatrixXd& data,\n              std::string method,\n              double mult,\n              const Eigen::VectorXd& weights)\n{\n  using namespace tools_interpolation;\n\n  // construct default grid (equally spaced on Gaussian scale)\n  size_t m = 30;\n  auto grid_points = this->make_normal_grid(m);\n\n  // expand the interpolation grid; a matrix with two columns where each row\n  // contains one combination of the grid points\n  auto grid_2d = tools_eigen::expand_grid(grid_points);\n\n  // transform evaluation grid and data by inverse Gaussian cdf\n  Eigen::MatrixXd z = tools_stats::qnorm(grid_2d);\n\n  // use jittering in case observations are discrete\n  auto psobs = tools_stats::to_pseudo_obs(data.leftCols(2), \"random\");\n  Eigen::MatrixXd z_data = tools_stats::qnorm(psobs);\n\n  // find bandwidth matrix\n  Eigen::Matrix2d B = select_bandwidth(z_data, method, weights);\n  B *= mult;\n\n  // compute the density estimator (first column estimate, second influence)\n  Eigen::MatrixXd ll_fit = fit_local_likelihood(z, z_data, B, method, weights);\n\n  // transform density estimate to copula scale\n  Eigen::VectorXd c =\n    ll_fit.col(0).cwiseQuotient(tools_stats::dnorm(z).rowwise().prod());\n  // store values in mxm grid\n  Eigen::MatrixXd values(m, m);\n  values = Eigen::Map<Eigen::MatrixXd>(c.data(), m, m).transpose();\n\n  // for interpolation, we shift the limiting gridpoints to 0 and 1\n  grid_points(0) = 0.0;\n  grid_points(m - 1) = 1.0;\n  interp_grid_ = std::make_shared<InterpolationGrid>(grid_points, values);\n\n  // compute effective degrees of freedom via interpolation ---------\n  // stabilize interpolation by restricting to plausible range\n  Eigen::VectorXd infl_vec = ll_fit.col(1).cwiseMin(1.3).cwiseMax(-0.2);\n  Eigen::MatrixXd infl(m, m);\n  infl = Eigen::Map<Eigen::MatrixXd>(infl_vec.data(), m, m).transpose();\n  // don't normalize margins of the EDF! (norm_times = 0)\n  auto infl_grid = InterpolationGrid(grid_points, infl, 0);\n  if ((var_types_[0] == \"d\") | (var_types_[1] == \"d\")) {\n    // for discrete, use mid ranks to compute EDF and log-likelihood\n    // (this is closer to \"observations\" than jittered or \"upper\" pseudo data)\n    psobs = 0.5 * (data.leftCols(2) + data.rightCols(2)).array();\n    npars_ = tools_eigen::unique(infl_grid.interpolate(psobs)).sum();\n    npars_ = std::max(npars_, 1.0);\n  } else {\n    npars_ = std::max(infl_grid.interpolate(data).sum(), 1.0);\n  }\n  set_loglik(pdf(data).array().log().sum());\n}\n}\n", "meta": {"hexsha": "f6ddd76fba3db42442fc00e7e8848ad8392ad9ee", "size": 10233, "ext": "ipp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/bicop/implementation/tll.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/tll.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/tll.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": 36.5464285714, "max_line_length": 79, "alphanum_fraction": 0.5751001661, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.5666307073274374}}
{"text": "//============================================================================\n// Name        : polynomfit.cpp\n// Author      : \n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C, Ansi-style\n//============================================================================\n\n//#include <stdio.h>\n//#include <stdlib.h>\n#include <Eigen/Dense>\n#include \"monopoly.h\"\n#include \"include/tensor_serie.hh\"\n#include \"full_correlation_tensor_serie.hh\"\n#include <random>\n\n#include <iostream>\n\nusing namespace std;\n\nint main(void) {\n//\tputs(\"Hello World!!!\");\n//\treturn EXIT_SUCCESS;\n\n\tcout << \"Hello world\" << endl;\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic > m_eigen_matrix;\n\tm_eigen_matrix.resize(2,2);\n\n\tm_eigen_matrix << 1, 2,\n\t\t\t\t\t3,4;\n\tcout << m_eigen_matrix << endl;\n\n\n\tstd::vector<std::vector<double> > data(10000, std::vector<double>(2,0.0) );\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::normal_distribution<> d(0,1);\n\tstd::uniform_int_distribution<> distrib(1, 6);\n\tfor(int i = 0; i!= data.size(); i++) {\n\t\tconst double x =  distrib(gen) + d(gen);\n\t\tconst double y = -0.1*x*x*x + 0.7*x*x + 0.01*x + 0.5 + d(gen);\n\t\tdata[i][0] = x;\n\t\tdata[i][1] = y;\n\t}\n\n\tfull_correlation_tensor_serie<double> polynom(1,10);\n\ttensor_serie<double> m_x(1,10*4); //the internal tensors orders are 4 times larger\n\n\tfor(int i=0; i!= data.size(); i++) {\n\t\t//cout<< i << data[i][0] << \" \" << data[i][1] << endl;\n\t\tm_x.create_diad_1dim(data[i][0]);\n\t\tpolynom.fill_1dim(m_x, data[i][1], 1.0);\n\t}\n\tpolynom.normalize();\n\n\tcout << \"Solving for degree 4\" << std::endl;\n\ttensor_serie_function<double> pol4 = polynom.solve(4);\n\tcout << \"chi2\\t expected chi2 \\t the traditional bias \\t full bias\" << endl;\n\tcout << pol4.m_chi2 << \"\\t\" << (pol4.m_chi2 + pol4.m_bias) << \"\\t\" << pol4.m_biaso << \"\\t\" << pol4.m_bias << endl;\n\tcout << \"Solving for degree 10\" << std::endl;\n\ttensor_serie_function<double> pol10 = polynom.solve(10);\n\tcout << \"chi2\\t expected chi2 \\t the traditional bias \\t full bias\" << endl;\n\tcout << pol10.m_chi2 << \"\\t\" << (pol10.m_chi2 + pol10.m_bias) << \"\\t\" << pol10.m_biaso << \"\\t\" << pol4.m_bias << endl;\n\n\tfor(double x=0; x< 1.0; x+=0.1) {\n\t\tdouble y = (-0.1*x*x*x + 0.7*x*x + 0.01*x + 0.5);\n\t\tm_x.create_diad_1dim(x);\n\t\tcout << \"p(\"<<x<<\")=\" << pol4.eval(m_x) << \" vs \" << y << endl;\n\t}\n\n\t//polynom.print(\"10 degree fit\");\n\n\n\n}\n", "meta": {"hexsha": "5df7a951441628bd350a458142e2e906629676ac", "size": 2375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polynomefit-error-propagation.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": "polynomefit-error-propagation.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": "polynomefit-error-propagation.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.8441558442, "max_line_length": 119, "alphanum_fraction": 0.5797894737, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5666306982236419}}
{"text": "#include \"delaunay_cpu_interpolator_base.h\"\n#include <CGAL/Delaunay_triangulation.h>\n#include <CGAL/Epick_d.h>\n#include <Eigen/Dense>\n#include <bitset>\n\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nDelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::DelaunayCPUInterpolatorBase(\n        operator_set_evaluator_iface *supporting_point_evaluator,\n        const std::array<int, N_DIMS> &axes_points,\n        const std::array<double, N_DIMS> &axes_min,\n        const std::array<double, N_DIMS> &axes_max)\n        : InterpolatorBase<index_t, N_DIMS, N_OPS>(supporting_point_evaluator,\n                    axes_points, axes_min, axes_max) {\n    typedef CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<N_DIMS>>> T;\n    std::array<typename T::Point, 1 << N_DIMS> points;\n    for (int j = 0; j < points.size(); ++j) {\n        std::bitset<N_DIMS> binary(j);\n        double point[N_DIMS];\n        for (int i = 0; i < N_DIMS; i++)\n            point[i] = binary[i];\n        typename T::Point p(&point[0], &point[N_DIMS]);\n        points[j] = p;\n    }\n    delaunay_triangulation_.insert(points.begin(), points.end());\n}\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nint DelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::Interpolate(\n        const std::vector<double> &point, std::vector<double> &values) {\n    std::array<int, N_DIMS> hypercube;\n    std::array<double, N_DIMS> scaled_point;\n    this->FindHypercube(point, hypercube, scaled_point);\n\n    Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> vertex_matrix;\n    std::array<std::array<int, N_DIMS>, N_DIMS + 1> simplex;\n    FindSimplex(hypercube, scaled_point, vertex_matrix, simplex);\n\n    Eigen::Matrix<double, N_DIMS + 1, 1> weights;\n    ComputeBarycentricCoordinates(vertex_matrix, scaled_point, weights);\n\n    values.assign(N_OPS, 0.0);\n    for (int dim_i = 0; dim_i <= N_DIMS; dim_i++) {\n        std::array<double, N_OPS> supp_values;\n        this->GetSupportingPoint(simplex[dim_i], supp_values);\n        for (int op_i = 0; op_i < N_OPS; op_i++)\n            values[op_i] += weights[dim_i] * supp_values[op_i];\n    }\n\n    return 0;\n}\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nint\nDelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::InterpolateWithDerivatives(\n        const std::vector<double> &points, const std::vector<int> &points_idxs,\n        std::vector<double> &values, std::vector<double> &derivatives) {\n    \n    for (std::size_t point_i = 0; point_i < points_idxs.size(); point_i++) {\n        int point_offset = points_idxs[point_i];\n\n        std::array<int, N_DIMS> hypercube;\n        std::array<double, N_DIMS> scaled_point;\n        this->FindHypercube(points, hypercube, scaled_point,\n                            point_offset * N_DIMS);\n\n        Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> vertex_matrix;\n        std::array<std::array<int, N_DIMS>, N_DIMS + 1> simplex;\n        FindSimplex(hypercube, scaled_point, vertex_matrix, simplex);\n\n        Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> vertex_matrix_inv;\n        Eigen::Matrix<double, N_DIMS + 1, 1> weights;\n        ComputeBarycentricCoordinatesAndVertexMatrixInv(vertex_matrix,\n                scaled_point, weights, vertex_matrix_inv);\n\n        std::fill(values.begin() + point_offset * N_OPS, values.begin() + (point_offset + 1) * N_OPS, 0);\n        std::fill(derivatives.begin() + point_offset * N_OPS * N_DIMS, derivatives.begin() + (point_offset + 1) * N_OPS * N_DIMS, 0);\n        for (int dim_i = 0; dim_i <= N_DIMS; dim_i++) {\n            std::array<double, N_OPS> supp_values;\n            this->GetSupportingPoint(simplex[dim_i], supp_values);\n            for (int op_i = 0; op_i < N_OPS; op_i++) {\n                values[point_offset * N_OPS + op_i] +=\n                        weights[dim_i] * supp_values[op_i];\n                for (int dim_j = 0; dim_j < N_DIMS; dim_j++)\n                    derivatives[(point_offset * N_OPS + op_i) * N_DIMS + dim_j] +=\n                            vertex_matrix_inv(dim_i, dim_j) * supp_values[op_i];\n            }\n        }\n        for (int op_i = 0; op_i < N_OPS; op_i++)\n            for (int dim_j = 0; dim_j < N_DIMS; dim_j++)\n                derivatives[(point_offset * N_OPS + op_i) * N_DIMS + dim_j] *=\n                        this->axes_step_inv_[dim_j];\n    }\n    return 0;\n}\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nvoid DelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::FindSimplex(\n        const std::array<int, N_DIMS> &hypercube,\n        const std::array<double, N_DIMS> &scaled_point,\n        Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> &vertex_matrix,\n        std::array<std::array<int, N_DIMS>, N_DIMS + 1> &simplex) {\n    typedef CGAL::Delaunay_triangulation<CGAL::Epick_d<CGAL::Dimension_tag<N_DIMS>>> T;\n    typename T::Point t_scaled_point(scaled_point.begin(), scaled_point.end());\n    typename T::Full_cell_handle handle = delaunay_triangulation_.locate(\n            t_scaled_point);\n\n    vertex_matrix.row(N_DIMS) = Eigen::Matrix<double, 1, N_DIMS + 1>::Constant(\n            1.0);\n    for (int vertex_i = 0; vertex_i <= N_DIMS; vertex_i++) {\n        typename T::Point vertex = handle->vertex(vertex_i)->point();\n        for (int dim_i = 0; dim_i < N_DIMS; dim_i++) {\n            simplex[vertex_i][dim_i] = hypercube[dim_i] + vertex[dim_i];\n            vertex_matrix(dim_i, vertex_i) = vertex[dim_i];\n        }\n    }\n}\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nvoid\nDelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::ComputeBarycentricCoordinates(\n        const Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> &vertex_matrix,\n        const std::array<double, N_DIMS> &scaled_point,\n        Eigen::Matrix<double, N_DIMS + 1, 1> &weights) {\n    Eigen::Matrix<double, N_DIMS + 1, 1> scaled_point_vector;\n    for (int dim_i = 0; dim_i < N_DIMS; dim_i++)\n        scaled_point_vector[dim_i] = scaled_point[dim_i];\n    scaled_point_vector[N_DIMS] = 1.0;\n\n    weights = vertex_matrix.colPivHouseholderQr().solve(scaled_point_vector);\n}\n\ntemplate<typename index_t, int N_DIMS, int N_OPS>\nvoid\nDelaunayCPUInterpolatorBase<index_t, N_DIMS, N_OPS>::\n        ComputeBarycentricCoordinatesAndVertexMatrixInv(\n        const Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> &vertex_matrix,\n        const std::array<double, N_DIMS> &scaled_point,\n        Eigen::Matrix<double, N_DIMS + 1, 1> &weights,\n        Eigen::Matrix<double, N_DIMS + 1, N_DIMS + 1> &vertex_matrix_inv) {\n    Eigen::Matrix<double, N_DIMS + 1, 1> scaled_point_vector;\n    for (int dim_i = 0; dim_i < N_DIMS; dim_i++)\n        scaled_point_vector[dim_i] = scaled_point[dim_i];\n    scaled_point_vector[N_DIMS] = 1.0;\n\n    vertex_matrix_inv = vertex_matrix.inverse();\n    weights = vertex_matrix_inv * scaled_point_vector;\n}\n", "meta": {"hexsha": "fd4675e444952dffb711594f386fe9b98c5ffdf0", "size": 6729, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/delaunay_cpu_interpolator_base.tpp", "max_stars_repo_name": "bszhu/interpolators", "max_stars_repo_head_hexsha": "3a3274e5ce89a6532168b3305c013e2ab590a02c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/delaunay_cpu_interpolator_base.tpp", "max_issues_repo_name": "bszhu/interpolators", "max_issues_repo_head_hexsha": "3a3274e5ce89a6532168b3305c013e2ab590a02c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-04-03T23:09:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:07:36.000Z", "max_forks_repo_path": "src/delaunay_cpu_interpolator_base.tpp", "max_forks_repo_name": "bszhu/interpolators", "max_forks_repo_head_hexsha": "3a3274e5ce89a6532168b3305c013e2ab590a02c", "max_forks_repo_licenses": ["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.86, "max_line_length": 133, "alphanum_fraction": 0.650765344, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.6261241772283035, "lm_q1q2_score": 0.5664235784074666}}
{"text": "// clang-format off\n// MUST BE at the beginning before any other <cmath> include (e.g. in armadillo's headers)\n#define _USE_MATH_DEFINES // required for Visual Studio\n#include <cmath>\n// clang-format on\n\n#include \"libKriging/OrdinaryKriging.hpp\"\n\n#include <armadillo>\n#include <optim.hpp>\n#include <tuple>\n#include <cassert>\n\n// #include \"libKriging/covariance.h\"\n\n//' @ref: https://github.com/psbiomech/dace-toolbox-source/blob/master/dace.pdf\n//'  (where CovMatrix<-R, Ft<-M, C<-T, rho<-z)\n//' @ref: https://github.com/cran/DiceKriging/blob/master/R/kmEstimate.R (same variables names)\n\n//' @ref https://github.com/cran/DiceKriging/blob/master/src/CovFuns.c\n// Covariance function on normalized data\nstd::function<double(arma::subview_col<double>&&, arma::subview_col<double>&&)> CovNorm_fun_gauss\n    = [](arma::subview_col<double>&& xi, arma::subview_col<double>&& xj) {\n        //    double temp = 0;\n        //    for (arma::uword k = 0; k < xi.n_elem; k++) {\n        //      double d = (xi(k) - xj(k));\n        //      temp += d * d;\n        //    }\n\n        auto&& diff = (xi - xj);\n        const double temp = arma::dot(diff, diff);\n\n        return exp(-0.5 * temp);\n      };\n\nstd::function<double(arma::subview_col<double>&&, arma::subview_col<double>&&, int)> CovNorm_deriv_gauss\n    = [](arma::subview_col<double>&& xi, arma::subview_col<double>&& xj, int dim) {\n        //    double temp = 0;\n        //    for (arma::uword k = 0; k < xi.n_elem; k++) {\n        //      double d = (xi(k) - xj(k));\n        //      temp += d*d;\n        //    }\n\n        auto&& diff = (xi - xj);\n        const double temp = arma::dot(diff, diff);\n\n        return exp(-.5 * temp) * (xi(dim) - xj(dim)) * (xi(dim) - xj(dim));\n      };\n\nstd::function<double(arma::subview_col<double>&&, arma::subview_col<double>&&)> CovNorm_fun_exp\n    = [](arma::subview_col<double>&& xi, arma::subview_col<double>&& xj) {\n        auto&& diff = (xi - xj);\n        return exp(-arma::sum(arma::abs(diff)));\n      };\n\nstd::function<double(arma::subview_col<double>&&, arma::subview_col<double>&&, int)> CovNorm_deriv_exp\n    = [](arma::subview_col<double>&& xi, arma::subview_col<double>&& xj, int dim) {\n        auto&& diff = (xi - xj);\n        return exp(-arma::sum(arma::abs(diff))) * fabs(xi(dim) - xj(dim));\n      };\n\n/************************************************/\n/** implementation details forward declaration **/\n/************************************************/\n\nnamespace {  // anonymous namespace for local implementation details\nauto regressionModelMatrix(const OrdinaryKriging::RegressionModel& regmodel,\n                           const arma::mat& newX,\n                           arma::uword n,\n                           arma::uword d) -> arma::mat;\n}  // namespace\n\n/************************************************/\n/**      OrdinaryKriging implementation        **/\n/************************************************/\n\n// returns distance matrix form Xp to X\nLIBKRIGING_EXPORT\narma::mat OrdinaryKriging::Cov(const arma::mat& X, const arma::mat& Xp) {\n  arma::mat Xtnorm = trans(X);\n  Xtnorm.each_col() /= m_theta;\n  arma::mat Xptnorm = trans(Xp);\n  Xptnorm.each_col() /= m_theta;\n\n  arma::uword n = X.n_rows;\n  arma::uword np = Xp.n_rows;\n\n  // Should bre replaced by for_each\n  arma::mat R(n, np);\n  R.zeros();\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < np; j++) {\n      R.at(i, j) = OrdinaryKriging::CovNorm_fun(Xtnorm.col(i), Xptnorm.col(j));\n    }\n  }\n  return R;\n}\n\n// Optimized version when Xp=X\nLIBKRIGING_EXPORT\narma::mat OrdinaryKriging::Cov(const arma::mat& X) {\n  // Should be tyaken from covariance.h from nestedKriging ?\n  // return getCrossCorrMatrix(X,Xp,parameters,covType);\n\n  arma::mat Xtnorm = trans(X);\n  Xtnorm.each_col() /= m_theta;\n  arma::uword n = X.n_rows;\n\n  // Should bre replaced by for_each\n  arma::mat R(n, n);\n  R.zeros();\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < i; j++) {\n      R.at(i, j) = OrdinaryKriging::CovNorm_fun(Xtnorm.col(i), Xtnorm.col(j));\n    }\n  }\n\n  R = arma::symmatl(R);  // R + trans(R);\n  R.diag().ones();\n  return R;\n}\n//// same for one point\n// LIBKRIGING_EXPORT arma::colvec OrdinaryKriging::Cov(const arma::mat& X,\n//                                                    const arma::rowvec& x,\n//                                                    const arma::colvec& theta) {\n//  // FIXME mat(x) : an arma::mat from a arma::rowvec ?\n//  return OrdinaryKriging::Cov(&X, arma::mat(&x), &theta).col(1);  // TODO to be optimized...\n//}\n\n// This will create the dist(xi,xj) function above. Need to parse \"covType\".\nvoid OrdinaryKriging::make_Cov(const std::string& covType) {\n  if (covType.compare(\"gauss\") == 0) {\n    CovNorm_fun = CovNorm_fun_gauss;\n    CovNorm_deriv = CovNorm_deriv_gauss;\n  } else if (covType.compare(\"exp\") == 0) {\n    CovNorm_fun = CovNorm_fun_exp;\n    CovNorm_deriv = CovNorm_deriv_exp;\n  } else\n    throw std::invalid_argument(\"Unsupported covariance: \" + covType);\n\n  // arma::cout << \"make_Cov done.\" << arma::endl;\n}\n\n// at least, just call make_Cov(kernel)\nLIBKRIGING_EXPORT OrdinaryKriging::OrdinaryKriging(const std::string& covType) {\n  make_Cov(covType);\n}\n\n// Objective function for fit : -logLikelihood\ndouble OrdinaryKriging::fit_ofn(const arma::vec& _theta,\n                                arma::vec* grad_out,\n                                OrdinaryKriging::OKModel* okm_data) const {\n  OrdinaryKriging::OKModel* fd = okm_data;\n\n  // arma::cout << \"_theta:\" << _theta << arma::endl;\n\n  //' @ref https://github.com/cran/DiceKriging/blob/master/R/logLikFun.R\n  //  model@covariance <- vect2covparam(model@covariance, param)\n  //  model@covariance@sd2 <- 1\t\t# to get the correlation matrix\n  //\n  //  aux <- covMatrix(model@covariance, model@X)\n  //\n  //  R <- aux[[1]]\n  //  T <- chol(R)\n  //\n  //  x <- backsolve(t(T), model@y, upper.tri = FALSE)\n  //  M <- backsolve(t(T), model@F, upper.tri = FALSE)\n  //  z <- compute.z(x=x, M=M, beta=beta)\n  //  sigma2.hat <- compute.sigma2.hat(z)\n  //  logLik <- -0.5*(model@n * log(2*pi*sigma2.hat) + 2*sum(log(diag(T))) + model@n)\n\n  arma::mat Xtnorm = trans(m_X);\n  Xtnorm.each_col() /= _theta;\n\n  arma::uword n = m_X.n_rows;\n\n  // Define regression matrix\n  arma::uword nreg = 1;\n  arma::mat F = arma::ones(n, nreg);\n\n  // Allocate the matrix // arma::mat R = Cov(fd->X, _theta);\n  // Should be replaced by for_each\n  arma::mat R = arma::zeros(n, n);\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < i; j++) {\n      R.at(i, j) = CovNorm_fun(Xtnorm.col(i), Xtnorm.col(j));\n    }\n  }\n  R = arma::symmatl(R);  // R + trans(R);\n  R.diag().ones();\n  // arma::cout << \"R:\" << R << arma::endl;\n\n  // Cholesky decompostion of covariance matrix\n  fd->T = trans(chol(R));\n\n  // Compute intermediate useful matrices\n  fd->M = solve(trimatl(fd->T), m_F, arma::solve_opts::fast);\n  arma::mat Q;\n  arma::mat G;\n  qr_econ(Q, G, fd->M);\n  arma::colvec Yt = solve(trimatl(fd->T), m_y, arma::solve_opts::fast);\n  fd->beta = solve(trimatu(G), trans(Q) * Yt, arma::solve_opts::fast);\n  fd->z = Yt - fd->M * fd->beta;\n\n  //' @ref https://github.com/cran/DiceKriging/blob/master/R/computeAuxVariables.R\n  double sigma2_hat = arma::accu(fd->z % fd->z) / n;\n  // arma::cout << \"sigma2_hat:\" << sigma2_hat << arma::endl;\n\n  double minus_ll = /*-*/ 0.5 * (n * log(2 * M_PI * sigma2_hat) + 2 * sum(log(fd->T.diag())) + n);\n  // arma::cout << \"ll:\" << -minus_ll << arma::endl;\n\n  if (grad_out != nullptr) {\n    //' @ref https://github.com/cran/DiceKriging/blob/master/R/logLikGrad.R\n    //  logLik.derivative <- matrix(0,nparam,1)\n    //  x <- backsolve(T,z)\t\t\t# compute x := T^(-1)*z\n    //  Rinv <- chol2inv(T)\t\t\t# compute inv(R) by inverting T\n    //\n    //  Rinv.upper <- Rinv[upper.tri(Rinv)]\n    //  xx <- x%*%t(x)\n    //  xx.upper <- xx[upper.tri(xx)]\n    //\n    //  for (k in 1:nparam) {\n    //    gradR.k <- CovMatrixDerivative(model@covariance, X=model@X, C0=R, k=k)\n    //    gradR.k.upper <- gradR.k[upper.tri(gradR.k)]\n    //\n    //    terme1 <- sum(xx.upper*gradR.k.upper)   / sigma2.hat\n    //    # quick computation of t(x)%*%gradR.k%*%x /  ...\n    //    terme2 <- - sum(Rinv.upper*gradR.k.upper)\n    //    # quick computation of trace(Rinv%*%gradR.k)\n    //    logLik.derivative[k] <- terme1 + terme2\n    //  }\n\n    arma::mat Linv = solve(trimatl(fd->T), arma::eye(n, n), arma::solve_opts::fast);\n    arma::mat Rinv = trans(Linv) * Linv;  // inv_sympd(R);\n\n    arma::mat x = solve(trimatu(trans(fd->T)), fd->z, arma::solve_opts::fast);\n    arma::mat xx = x * trans(x);\n    // arma::mat xx_upper = trimatu(xx);\n\n    for (arma::uword k = 0; k < m_X.n_cols; k++) {\n      arma::mat gradR_k_upper = arma::zeros(n, n);\n      for (arma::uword i = 0; i < n; i++) {\n        for (arma::uword j = 0; j < i; j++) {\n          gradR_k_upper.at(j, i) = CovNorm_deriv(Xtnorm.col(i), Xtnorm.col(j), k);\n        }\n      }\n      gradR_k_upper /= _theta(k);\n      gradR_k_upper = trans(gradR_k_upper);\n      // arma::mat gradR_k = symmatu(gradR_k_upper);\n      // gradR_k.diag().zeros();\n\n      double terme1\n          = arma::accu(xx /*_upper*/ % gradR_k_upper) / sigma2_hat;  // as_scalar((trans(x) * gradR_k) * x)/ sigma2_hat;\n      double terme2 = -arma::accu(Rinv /*_upper*/ % gradR_k_upper);  //-arma::trace(Rinv * gradR_k);\n      (*grad_out).at(k) = -(terme1 + terme2);\n      // (*grad_out)(k) = - arma::accu(dot(xx / sigma2_hat - Rinv, gradR_k_upper));\n    }\n    // arma::cout << \"Grad: \" << *grad_out <<  arma::endl;\n  }\n\n  return minus_ll;\n}\n\n// Utility function for LOO\narma::colvec DiagABA(const arma::mat& A, const arma::mat& B) {\n  arma::mat D = trimatu(2 * B);\n  D.diag() = B.diag();\n  D = (A * D) % A;\n  arma::colvec c = sum(D, 1);\n\n  return c;\n}\n\n// Objective function for fit : -LOO\ndouble OrdinaryKriging::fit_ofn2(const arma::vec& _theta,\n                                 arma::vec* grad_out,\n                                 OrdinaryKriging::OKModel* okm_data) const {\n  OrdinaryKriging::OKModel* fd = okm_data;\n\n  arma::mat Xtnorm = trans(m_X);\n  Xtnorm.each_col() /= _theta;\n\n  arma::uword n = m_X.n_rows;\n\n  // Allocate the matrix // arma::mat R = Cov(fd->X, _theta);\n  // Should be replaced by for_each\n  arma::mat R(n, n);\n  R.zeros();\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < i; j++) {\n      R(i, j) = CovNorm_fun(Xtnorm.col(i), Xtnorm.col(j));\n    }\n  }\n  R = arma::symmatl(R);  // R + trans(R);\n  R.diag().ones();\n  // arma::cout << \"R:\" << R << arma::endl;\n\n  // Cholesky decompostion of covariance matrix\n  fd->T = trans(chol(R));\n\n  // Compute intermediate useful matrices\n  // arma::mat M = solve(fd->T, F);\n  fd->M = solve(trimatl(fd->T), m_F, arma::solve_opts::fast);\n  // arma::mat Rinv = inv_sympd(R); // didn't find chol2inv equivalent in armadillo\n  arma::mat Rinv = inv(trimatl(fd->T));\n  Rinv = trimatl(Rinv) * trimatl(Rinv);\n  arma::mat RinvF = Rinv * m_F;\n  arma::mat TM = chol(trans(fd->M) * fd->M);  // Can be optimized with a crossprod equivalent in armadillo ?\n  // arma::mat aux = solve(trans(TM), trans(RinvF));\n  arma::mat aux = solve(trimatl(trans(TM)), trans(RinvF), arma::solve_opts::fast);\n  arma::mat Q = Rinv - trans(aux) * aux;  // Can be optimized with a crossprod equivalent in armadillo ?\n  arma::mat Qy = Q * m_y;\n  arma::colvec sigma2LOO = 1 / Q.diag();\n  arma::colvec errorsLOO = sigma2LOO % Qy;\n  double minus_loo = -arma::accu(errorsLOO % errorsLOO) / n;\n\n  if (grad_out != nullptr) {\n    //' @ref hhttps://github.com/cran/DiceKriging/blob/master/R/leaveOneOutGrad.R\n    // LOOfunDer <- matrix(0, nparam, 1)\n    // for (k in 1:nparam) {\n    //\tgradR.k <- covMatrixDerivative(model@covariance, X=model@X, C0=R, k=k)\n    //\tdiagdQ <- - diagABA(A=Q, B=gradR.k)\n    //\tdsigma2LOO <- - (sigma2LOO^2) * diagdQ\n    //\tderrorsLOO <- dsigma2LOO * Q.y - sigma2LOO * (Q%*%(gradR.k%*%Q.y))\n    //\tLOOfunDer[k] <- 2*crossprod(errorsLOO, derrorsLOO)/model@n\n    //}\n\n    for (arma::uword k = 0; k < m_X.n_cols; k++) {\n      arma::mat gradR_k(n, n);\n      gradR_k.zeros();\n      for (arma::uword i = 0; i < n; i++) {\n        for (arma::uword j = 0; j < i; j++) {\n          gradR_k(i, j) = CovNorm_deriv(Xtnorm.col(i), Xtnorm.col(j), k);\n        }\n      }\n      gradR_k /= _theta(k);\n      gradR_k = arma::symmatl(gradR_k);  // gradR_k + trans(gradR_k);\n      gradR_k.diag().zeros();\n\n      arma::colvec diagdQ = -DiagABA(Q, gradR_k);\n      arma::colvec dsigma2LOO = -sigma2LOO % sigma2LOO % diagdQ;\n      arma::colvec derrorsLOO = dsigma2LOO % Qy - sigma2LOO % (Q * (gradR_k * Qy));\n      (*grad_out)(k) = -2 * dot(errorsLOO, derrorsLOO) / n;\n    }\n    // arma::cout << \"Grad: \" << *grad_out <<  arma::endl;\n  }\n\n  return minus_loo;\n}\n\nLIBKRIGING_EXPORT double OrdinaryKriging::logLikelihood(const arma::vec& _theta) {\n  arma::mat T;\n  arma::mat M;\n  arma::mat z;\n  arma::colvec beta;\n  OrdinaryKriging::OKModel okm_data{T, M, z, beta};\n\n  return -fit_ofn(_theta, nullptr, &okm_data);\n}\n\nLIBKRIGING_EXPORT arma::vec OrdinaryKriging::logLikelihoodGrad(const arma::vec& _theta) {\n  arma::mat T;\n  arma::mat M;\n  arma::mat z;\n  arma::colvec beta;\n  OrdinaryKriging::OKModel okm_data{T, M, z, beta};\n\n  arma::vec grad(_theta.n_elem);\n\n  double ll = fit_ofn(_theta, &grad, &okm_data);\n\n  return -grad;\n}\n\nLIBKRIGING_EXPORT double OrdinaryKriging::loofun(const arma::vec& _theta) {\n  arma::mat T;\n  arma::mat M;\n  arma::mat z;\n  arma::colvec beta;\n  OrdinaryKriging::OKModel okm_data{T, M, z, beta};\n\n  return -fit_ofn2(_theta, nullptr, &okm_data);\n}\n\nLIBKRIGING_EXPORT arma::vec OrdinaryKriging::loofungrad(const arma::vec& _theta) {\n  arma::mat T;\n  arma::mat M;\n  arma::mat z;\n  arma::colvec beta;\n  OrdinaryKriging::OKModel okm_data{T, M, z, beta};\n\n  arma::vec grad(_theta.n_elem);\n\n  double ll = fit_ofn2(_theta, &grad, &okm_data);\n\n  return -grad;\n}\n\n/** Fit the kriging object on (X,y):\n * @param y is n length column vector of output\n * @param X is n*d matrix of input\n * @param regmodel is the regression model to be used for the GP mean (choice between contant, linear, quadratic)\n * @param normalize is a boolean to enforce inputs/output normalization\n * @param parameters is starting value for hyper-parameters\n * @param optim_method is an optimizer name from OptimLib, or 'none' to keep parameters unchanged\n * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.\n */\nLIBKRIGING_EXPORT void OrdinaryKriging::fit(const arma::colvec& y,\n                                            const arma::mat& X,\n                                            const RegressionModel& regmodel,\n                                            bool normalize) {  //,\n                                                               // const Parameters& parameters,\n  // const std::string& optim_objective, // will support \"logLik\" or \"leaveOneOut\"\n  // const std::string& optim_method) {\n\n  std::string optim_objective = \"ll\";\n  std::string optim_method = \"bfgs\";\n  Parameters parameters{0, false, arma::vec(1), false};\n\n  arma::uword n = X.n_rows;\n  arma::uword d = X.n_cols;\n  arma::rowvec centerX(d);\n  arma::rowvec scaleX(d);\n  double centerY;\n  double scaleY;\n  // Normalization of inputs and output\n  if (normalize) {\n    centerX = min(X, 0);\n    scaleX = max(X, 0) - min(X, 0);\n    centerY = min(y);\n    scaleY = max(y) - min(y);\n  } else {\n    centerX.zeros();\n    scaleX.ones();\n    centerY = 0;\n    scaleY = 1;\n  }\n  m_centerX = centerX;\n  m_scaleX = scaleX;\n  m_centerY = centerY;\n  m_scaleY = scaleY;\n  {  // FIXME why copies of newX and newy\n    arma::mat newX = X;\n    newX.each_row() -= centerX;\n    newX.each_row() /= scaleX;\n    arma::colvec newy = (y - centerY) / scaleY;\n    this->m_X = newX;\n    this->m_y = newy;\n  }\n\n  // Define regression matrix\n  m_regmodel = regmodel;\n  m_F = regressionModelMatrix(regmodel, m_X, n, d);\n\n  // arma::cout << \"optim_method:\" << optim_method << arma::endl;\n\n  if (optim_method == \"none\") {  // just keep given theta, no optimisation of ll\n    m_theta = parameters.theta;\n  } else if (optim_method.rfind(\"bfgs\", 0) == 0) {\n    arma::mat theta0;\n    // FIXME parameters.has needs to implemtented (no use case in current code)\n    if (!parameters.has_theta) {      // no theta given, so draw 10 random uniform starting values\n      int multistart = 10;            // TODO? stoi(substr(optim_method,)) to hold 'bfgs10' as a 10 multistart bfgs\n      arma::arma_rng::set_seed(123);  // FIXME arbitrary seed for reproducible random sequences\n      theta0 = arma::randu(multistart, X.n_cols);\n    } else {  // just use given theta(s) as starting values for multi-bfgs\n      theta0 = arma::mat(parameters.theta);\n    }\n\n    // arma::cout << \"theta0:\" << theta0 << arma::endl;\n\n    optim::algo_settings_t algo_settings;\n    algo_settings.iter_max = 10;  // TODO change by default?\n    algo_settings.err_tol = 1e-5;\n    algo_settings.vals_bound = true;\n    algo_settings.lower_bounds = 0.001 * arma::ones<arma::vec>(X.n_cols);\n    algo_settings.upper_bounds = 2 * sqrt(X.n_cols) * arma::ones<arma::vec>(X.n_cols);\n    double minus_ll = std::numeric_limits<double>::infinity();\n    for (arma::uword i = 0; i < theta0.n_rows; i++) {  // TODO: use some foreach/pragma to let OpenMP work.\n      arma::vec theta_tmp = trans(theta0.row(i));\n      arma::mat T;\n      arma::mat M;\n      arma::mat z;\n      arma::colvec beta;\n      OrdinaryKriging::OKModel okm_data{T, M, z, beta};\n      bool bfgs_ok = optim::lbfgs(\n          theta_tmp,\n          [&okm_data, this](const arma::vec& vals_inp, arma::vec* grad_out, void*) -> double {\n            return fit_ofn(vals_inp, grad_out, &okm_data);\n          },\n          nullptr,\n          algo_settings);\n\n      // if (bfgs_ok) { // FIXME always succeeds ?\n      double minus_ll_tmp\n          = fit_ofn(theta_tmp,\n                    nullptr,\n                    &okm_data);  // this last call also ensure that T and z are up-to-date with solution found.\n      if (minus_ll_tmp < minus_ll) {\n        m_theta = std::move(theta_tmp);\n        minus_ll = minus_ll_tmp;\n        m_T = std::move(okm_data.T);\n        m_M = std::move(okm_data.M);\n        m_z = std::move(okm_data.z);\n        m_beta = std::move(okm_data.beta);\n      }\n      // }\n    }\n  } else\n    throw std::runtime_error(\"Not a suitable optim_method: \" + optim_method);\n\n  // arma::cout << \"theta:\" << m_theta << arma::endl;\n\n  if (!parameters.has_sigma2) {\n    m_sigma2 = arma::as_scalar(sum(pow(m_z, 2)) / X.n_rows);\n    m_sigma2 = arma::as_scalar(accu(m_z % m_z) / X.n_rows);\n    // Un-normalize\n    m_sigma2 *= scaleY * scaleY;\n  } else {\n    m_sigma2 = parameters.sigma2;\n  }\n\n  // arma::cout << \"sigma2:\" << m_sigma2 << arma::endl;\n}\n\n/** Compute the prediction for given points X'\n * @param Xp is m*d matrix of points where to predict output\n * @param std is true if return also stdev column vector\n * @param cov is true if return also cov matrix between Xp\n * @return output prediction: m means, [m standard deviations], [m*m full covariance matrix]\n */\nLIBKRIGING_EXPORT std::tuple<arma::colvec, arma::colvec, arma::mat> OrdinaryKriging::predict(const arma::mat& Xp,\n                                                                                             bool withStd,\n                                                                                             bool withCov) {\n  arma::uword m = Xp.n_rows;\n  arma::uword n = m_X.n_rows;\n  arma::colvec pred_mean(m);\n  arma::colvec pred_stdev(m);\n  arma::mat pred_cov(m, m);\n  pred_stdev.zeros();\n  pred_cov.zeros();\n\n  arma::mat Xtnorm = trans(m_X);\n  Xtnorm.each_col() /= m_theta;\n  arma::mat Xpnorm = Xp;\n  // Normalize Xp\n  Xpnorm.each_row() -= m_centerX;\n  Xpnorm.each_row() /= m_scaleX;\n\n  // Define regression matrix\n  arma::uword d = m_X.n_cols;\n  arma::mat Ftest = regressionModelMatrix(m_regmodel, Xpnorm, m, d);\n\n  // Compute covariance between training data and new data to predict\n  arma::mat R(n, m);\n  Xpnorm = trans(Xpnorm);\n  Xpnorm.each_col() /= m_theta;\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < m; j++) {\n      R.at(i, j) = CovNorm_fun(Xtnorm.col(i), Xpnorm.col(j));\n    }\n  }\n  arma::mat Tinv_newdata = solve(trimatl(m_T), R, arma::solve_opts::fast);\n  pred_mean = Ftest * m_beta + trans(Tinv_newdata) * m_z;\n  // Un-normalize predictor\n  pred_mean = m_centerY + m_scaleY * pred_mean;\n\n  if (withStd) {\n    double total_sd2 = m_sigma2;\n    // s2.predict.1 <- apply(Tinv.c.newdata, 2, crossprod)\n    arma::colvec s2_predict_1 = m_sigma2 * trans(sum(Tinv_newdata % Tinv_newdata, 0));\n    // Type = \"UK\"\n    // T.M <- chol(t(M)%*%M)\n    arma::mat TM = trans(chol(trans(m_M) * m_M));\n    // s2.predict.mat <- backsolve(t(T.M), t(F.newdata - t(Tinv.c.newdata)%*%M) , upper.tri = FALSE)\n    arma::mat s2_predict_mat = solve(trimatl(TM), trans(Ftest - trans(Tinv_newdata) * m_M), arma::solve_opts::fast);\n    // s2.predict.2 <- apply(s2.predict.mat, 2, crossprod)\n    arma::colvec s2_predict_2 = m_sigma2 * trans(sum(s2_predict_mat % s2_predict_mat, 0));\n    // s2.predict <- pmax(total.sd2 - s2.predict.1 + s2.predict.2, 0)\n    arma::mat s2_predict = total_sd2 - s2_predict_1 + s2_predict_2;\n    s2_predict.elem(find(pred_stdev < 0)).zeros();\n    pred_stdev = sqrt(s2_predict);\n    if (withCov) {\n      // C.newdata <- covMatrix(object@covariance, newdata)[[1]]\n      arma::mat C_newdata(m, m);\n      for (arma::uword i = 0; i < m; i++) {\n        for (arma::uword j = 0; j < m; j++) {\n          C_newdata.at(i, j) = CovNorm_fun(Xpnorm.col(i), Xpnorm.col(j));\n        }\n      }\n      // cond.cov <- C.newdata - crossprod(Tinv.c.newdata)\n      // cond.cov <- cond.cov + crossprod(s2.predict.mat)\n      pred_cov = m_sigma2 * (C_newdata - trans(Tinv_newdata) * Tinv_newdata + trans(s2_predict_mat) * s2_predict_mat);\n    }\n  } else if (withCov) {\n    arma::mat C_newdata(m, m);\n    for (arma::uword i = 0; i < m; i++) {\n      for (arma::uword j = 0; j < m; j++) {\n        C_newdata.at(i, j) = CovNorm_fun(Xpnorm.col(i), Xpnorm.col(j));\n      }\n    }\n    // Need to compute matrices computed in withStd case\n    arma::mat TM = trans(chol(trans(m_M) * m_M));\n    arma::mat s2_predict_mat = solve(trimatl(TM), trans(Ftest - trans(Tinv_newdata) * m_M), arma::solve_opts::fast);\n    pred_cov = m_sigma2 * (C_newdata - trans(Tinv_newdata) * Tinv_newdata + trans(s2_predict_mat) * s2_predict_mat);\n  }\n\n  return std::make_tuple(std::move(pred_mean), std::move(pred_stdev), std::move(pred_cov));\n  /*if (withStd)\n    if (withCov)\n      return std::make_tuple(std::move(pred_mean), std::move(pred_stdev), std::move(pred_cov));\n    else\n      return std::make_tuple(std::move(pred_mean), std::move(pred_stdev), nullptr);\n  else if (withCov)\n    return std::make_tuple(std::move(pred_mean), std::move(pred_cov), nullptr);\n  else\n    return std::make_tuple(std::move(pred_mean), nullptr, nullptr);*/\n}\n\n/** Draw sample trajectories of kriging at given points X'\n * @param Xp is m*d matrix of points where to simulate output\n * @param nsim is number of simulations to draw\n * @return output is m*nsim matrix of simulations at Xp\n */\nLIBKRIGING_EXPORT arma::mat OrdinaryKriging::simulate(const int nsim, const arma::mat& Xp) {\n  // Here nugget.sim = 1e-10 to avoid chol failures of Sigma_cond)\n  double nugget_sim = 1e-10;\n  arma::uword m = Xp.n_rows;\n  arma::uword n = m_X.n_rows;\n  arma::mat yp(m, nsim);\n\n  arma::mat Xpnorm = Xp;\n\n  // Normalize Xp\n  Xpnorm.each_row() -= m_centerX;\n  Xpnorm.each_row() /= m_scaleX;\n\n  // Define regression matrix\n  arma::uword d = m_X.n_cols;\n  arma::mat F_newdata = regressionModelMatrix(m_regmodel, Xpnorm, m, d);\n\n  arma::colvec y_trend = F_newdata * m_beta;\n\n  // Compute covariance between new data\n  arma::mat Sigma(m, m);\n  Xpnorm = trans(Xpnorm);\n  Xpnorm.each_col() /= m_theta;\n  for (arma::uword i = 0; i < m; i++) {\n    for (arma::uword j = 0; j < i; j++) {\n      Sigma.at(i, j) = CovNorm_fun(Xpnorm.col(i), Xpnorm.col(j));\n    }\n  }\n  Sigma = arma::symmatl(Sigma);  // R + trans(R);\n  Sigma.diag().ones();\n  // arma::mat T_newdata = chol(Sigma);\n  // Compute covariance between training data and new data to predict\n  // Sigma21 <- covMat1Mat2(object@covariance, X1 = object@X, X2 = newdata, nugget.flag = FALSE)\n  arma::mat Sigma21(n, m);\n  arma::mat Xtnorm = trans(m_X);\n  Xtnorm.each_col() /= m_theta;\n  for (arma::uword i = 0; i < n; i++) {\n    for (arma::uword j = 0; j < m; j++) {\n      Sigma21.at(i, j) = CovNorm_fun(Xtnorm.col(i), Xpnorm.col(j));\n    }\n  }\n  // Tinv.Sigma21 <- backsolve(t(object@T), Sigma21, upper.tri = FALSE\n  arma::mat Tinv_Sigma21 = solve(trimatl(m_T), Sigma21, arma::solve_opts::fast);\n  // y.trend.cond <- y.trend + t(Tinv.Sigma21) %*% object@z\n  y_trend += trans(Tinv_Sigma21) * m_z;\n  // Sigma.cond <- Sigma11 - t(Tinv.Sigma21) %*% Tinv.Sigma21\n  arma::mat Sigma_cond = Sigma - trans(Tinv_Sigma21) * Tinv_Sigma21;\n  // T.cond <- chol(Sigma.cond + diag(nugget.sim, m, m))\n  Sigma_cond.diag() += nugget_sim;\n  arma::mat T_cond = chol(m_sigma2 * Sigma_cond);\n  // white.noise <- matrix(rnorm(m*nsim), m, nsim)\n  // y.rand.cond <- t(T.cond) %*% white.noise\n  // y <- matrix(y.trend.cond, m, nsim) + y.rand.cond\n  yp.each_col() = y_trend;\n  yp += trans(T_cond) * arma::randn(m, nsim);\n  // Un-normalize simulations\n  yp = m_centerY + m_scaleY * yp;\n\n  return yp;  // NB: move not required due to copy ellision mechanism\n}\n\n/** Add new conditional data points to previous (X,y)\n * @param newy is m length column vector of new output\n * @param newX is m*d matrix of new input\n * @param optim_method is an optimizer name from OptimLib, or 'none' to keep previously estimated parameters unchanged\n * @param optim_objective is 'loo' or 'loglik'. Ignored if optim_method=='none'.\n */\nLIBKRIGING_EXPORT void OrdinaryKriging::update(const arma::vec& newy,\n                                               const arma::mat& newX,\n                                               const std::string& optim_objective,\n                                               const std::string& optim_method) {\n  // rebuild data\n  m_X = join_rows(m_X, newX);\n  m_y = join_rows(m_y, newy);\n\n  // rebuild starting parameters\n  Parameters parameters{this->m_sigma2, true, this->m_theta, true};\n  // re-fit\n  this->fit(m_y, m_X);  //, parameters, optim_objective, optim_method);\n}\n\n/************************************************/\n/**          implementation details            **/\n/************************************************/\n\nnamespace {  // anonymous namespace for local implementation details\n\nauto regressionModelMatrix(const OrdinaryKriging::RegressionModel& regmodel,\n                           const arma::mat& newX,\n                           arma::uword n,\n                           arma::uword d) -> arma::mat {\n  arma::mat F;  // uses modern RTO to avoid returned object copy\n  switch (regmodel) {\n    case OrdinaryKriging::RegressionModel::Constant: {\n      F.set_size(n, 1);\n      F = arma::ones(n, 1);\n      return F;\n    } break;\n\n    case OrdinaryKriging::RegressionModel::Linear: {\n      F.set_size(n, 1 + d);\n      F.col(0) = arma::ones(n, 1);\n      for (arma::uword i = 0; i < d; i++) {\n        F.col(i + 1) = newX.col(i);\n      }\n      return F;\n    } break;\n\n    case OrdinaryKriging::RegressionModel::Quadratic: {\n      F.set_size(n, 1 + 2 * d + d * (d - 1) / 2);\n      F.col(0) = arma::ones(n, 1);\n      arma::uword count = 1;\n      for (arma::uword i = 0; i < d; i++) {\n        F.col(count) = newX.col(i);\n        count += 1;\n        for (arma::uword j = 0; j <= i; j++) {\n          F.col(count) = newX.col(i) % newX.col(j);\n          count += 1;\n        }\n      }\n      return F;\n    } break;\n  }\n}\n\nstatic char const* enum_RegressionModel_strings[] = {\"constant\", \"linear\", \"quadratic\"};\n\n}  // namespace\n\nOrdinaryKriging::RegressionModel OrdinaryKriging::RegressionModelUtils::fromString(const std::string& value) {\n  static auto begin = std::begin(enum_RegressionModel_strings);\n  static auto end = std::end(enum_RegressionModel_strings);\n\n  auto find = std::find(begin, end, value);\n  if (find != end) {\n    return static_cast<RegressionModel>(std::distance(begin, find));\n  } else {\n    // FIXME use std::optional as returned type\n    throw std::exception();\n  }\n}\n\nstd::string OrdinaryKriging::RegressionModelUtils::toString(const OrdinaryKriging::RegressionModel& e) {\n  assert(static_cast<std::size_t>(e) < sizeof(enum_RegressionModel_strings));\n  return enum_RegressionModel_strings[static_cast<int>(e)];\n}\n", "meta": {"hexsha": "0c8ba55609948f839fac48c48cf21feaca7abf69", "size": 28394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/OrdinaryKriging.cpp", "max_stars_repo_name": "yannrichet/libKriging", "max_stars_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_stars_repo_licenses": ["Apache-2.0"], "max_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/OrdinaryKriging.cpp", "max_issues_repo_name": "yannrichet/libKriging", "max_issues_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/OrdinaryKriging.cpp", "max_forks_repo_name": "yannrichet/libKriging", "max_forks_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_forks_repo_licenses": ["Apache-2.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.8274967575, "max_line_length": 120, "alphanum_fraction": 0.5983658519, "num_tokens": 8686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5663684380459693}}
{"text": "/* Distributed Mulit-Message Threshold (DMMT) */\n\n#include \"dmmt.h\"\n\n#include <gcrypt.h>\n#include <NTL/GF2X.h>\n#include <NTL/GF2EX.h>\n#include <NTL/mat_GF2E.h>\n\nusing namespace NTL;\n\nenum {\n    TAG_DERIV_PARAM = 0x0ADA1815\n};\n\n\nstruct dmmt {\n    size_t key_size;\n    size_t block_size;\n    int algo;\n};\n\nstruct dmmt_dom {\n    dmmt_t *d;\n    uint8_t *tag;\n    unsigned int threshold;\n    gcry_cipher_hd_t ctr_handle;\n    GF2EX polynomial;\n};\n\n\ndmmt_stat_t enc_ecb_blk(dmmt_t *d, uint8_t *in, uint8_t *out);\nvoid fill_block_with_int(dmmt_t *d, uint64_t v, uint8_t *out);\nvoid xor_block_with_int(dmmt_t *d, uint64_t v, uint8_t *out);\nvoid fill_GF2X_from_bytes(GF2X &f, const uint8_t *bytes, size_t num_bytes);\nint conv_GF2X_to_bytes(const GF2X &f, long max_len, uint8_t *out);\n\n\n\n/* ############################################################################\n * # DMMT system \n * ############################################################################\n */\n\ndmmt_t *dmmt_create(const char *block_cipher, size_t block_size,\n                    size_t key_len_bits, dmmt_stat_t *status)\n{\n\n    int algo = GCRY_CIPHER_NONE;\n    dmmt_t *d = NULL;\n\n    if (!strcmp(block_cipher, \"AES\")) {\n        if (block_size == 16 && key_len_bits == 128)\n            algo = GCRY_CIPHER_AES128;\n        else\n            *status = DMMT_STAT_UNSUPPORTED_CIPHER_PARAMS;\n    }\n    else\n        *status = DMMT_STAT_UNSUPPORTED_CIPHER;\n\n    if (algo != GCRY_CIPHER_NONE) {\n        d = (dmmt_t*)malloc(sizeof(dmmt_t));\n\n        d->algo = algo;\n        d->key_size = (key_len_bits + 7) / 8;\n        d->block_size = block_size;\n\n        /*\n         * Modulus for GF(2^128) is set to x^128 + x^7 + x^2 + x + 1.\n         * At the moment, only AES-128 is supported so this suffices .\n         * However it is global. TODO: change this.\n         */\n        GF2X modulus;\n        SetCoeff(modulus, 128);\n        SetCoeff(modulus, 7);\n        SetCoeff(modulus, 2);\n        SetCoeff(modulus, 1);\n        SetCoeff(modulus, 0);\n        GF2E::init(modulus);\n\n\n        *status = DMMT_STAT_OK;\n    }\n    else\n        *status = DMMT_STAT_INTERNAL_ERROR;\n\n    return d;\n}\n\ndmmt_dom_t *dmmt_new_dom_from_key(dmmt_t *d, const uint8_t *master_key,\n                                  unsigned int threshold, dmmt_stat_t *stat)\n{\n    gcry_cipher_hd_t h_ecb;\n\n    if (gcry_cipher_open(&h_ecb, d->algo, GCRY_CIPHER_MODE_ECB,\n                         GCRY_CIPHER_SECURE) != 0) {\n        *stat = DMMT_STAT_INTERNAL_ERROR;\n        return NULL;\n    }\n\n    /* Temporary buffers and variables */\n    uint8_t *ibuf = (uint8_t*)malloc(d->block_size);\n    uint8_t *obuf = (uint8_t*)gcry_malloc_secure(d->block_size);\n    GF2E coeff;\n    GF2X coeff_poly;\n    \n    /* New Domain */\n    dmmt_dom_t *dom = (dmmt_dom_t*)gcry_malloc_secure(sizeof(dmmt_dom_t));\n    dom->d = d;\n    dom->threshold = threshold;\n    \n    /* Generate Tag */\n    uint8_t *tag = (uint8_t*)malloc(d->block_size);\n    gcry_cipher_setkey(h_ecb, master_key, d->key_size);\n    fill_block_with_int(d, TAG_DERIV_PARAM, ibuf);\n    gcry_cipher_encrypt(h_ecb, tag, d->block_size, ibuf, d->block_size);\n    dom->tag = tag;\n\n    /* Copy tag to input buf */\n    memcpy(ibuf, tag, d->block_size);\n\n    /* Generate secret key */\n    gcry_cipher_encrypt(h_ecb, obuf, d->block_size, ibuf, d->block_size);\n\n    /* Setup cipher handle with secret key */\n    gcry_cipher_open(&dom->ctr_handle, d->algo, GCRY_CIPHER_MODE_CTR,\n                     GCRY_CIPHER_SECURE); \n    gcry_cipher_setkey(dom->ctr_handle, obuf, d->key_size);\n\n    /* Set secret as constant term of polynomial */\n    fill_GF2X_from_bytes(coeff_poly, obuf, d->block_size);\n    conv(coeff, coeff_poly);\n    SetCoeff(dom->polynomial, 0, coeff);\n    \n    /* Derive the coefficents using the block cipher */\n    uint64_t i;\n    for (i = 1; i < threshold; i++) {\n        /* XOR in next counter value */\n        xor_block_with_int(d, i ^ (i - 1), ibuf);\n\n        gcry_cipher_encrypt(h_ecb, obuf, d->block_size, ibuf, d->block_size);\n        fill_GF2X_from_bytes(coeff_poly, obuf, d->block_size);\n        conv(coeff, coeff_poly);\n        SetCoeff(dom->polynomial, i, coeff);\n    }\n\n    /* Cleanup */\n    gcry_cipher_close(h_ecb);\n    free(ibuf);\n    gcry_free(obuf);\n\n    *stat = DMMT_STAT_OK;\n\n    return dom;\n}\n\n\ndmmt_dom_t *dmmt_new_dom_from_shares(dmmt_t *d, const uint8_t *tag,\n                                     unsigned int threshold,\n                                     const uint8_t * const *shares,\n                                     size_t n_shares, dmmt_stat_t *stat)\n{\n    if (n_shares < threshold) {\n        *stat = DMMT_STAT_BELOW_THRESHOLD;\n        return NULL;\n    }\n\n    /* New Domain */\n    dmmt_dom_t *dom = (dmmt_dom_t*)gcry_malloc_secure(sizeof(dmmt_dom_t));\n    dom->d = d;\n    dom->threshold = threshold;\n    \n    /* Copy Tag */\n    uint8_t *tag_copy = (uint8_t*)malloc(d->block_size);\n    memcpy(tag_copy, tag, d->block_size);\n    dom->tag = tag_copy;\n\n    GF2X f;\n    GF2E x;\n    GF2E y;\n    GF2E coeff;\n    \n    vec_GF2E yvec;\n    vec_GF2E row;\n\n    mat_GF2E V;\n    V.SetDims(threshold, threshold);\n\n    yvec.SetLength(threshold);\n    row.SetLength(threshold);\n\n    for (size_t i = 0; i < threshold; i++) {\n        const uint8_t *share = shares[i];\n        size_t j;\n\n        /* Read x */\n        fill_GF2X_from_bytes(f, share, d->block_size);\n        conv(x, f);\n\n        /* Populate row of Vandermonde matrix */\n        conv(coeff, 1);\n        for (j = 0; j < threshold; j++) {\n            row[j] = coeff;\n            coeff *= x;\n        }\n        \n\n        V[i] = row; /* Set row */\n        \n        /* Read y */\n        fill_GF2X_from_bytes(f, share + d->block_size, d->block_size);\n        conv(yvec[i], f);\n    }\n\n    mat_GF2E Vinv;\n    inv(Vinv, V);\n    vec_GF2E rvec = Vinv * yvec;\n\n    for (size_t i = 0; i < threshold; i++)\n        SetCoeff(dom->polynomial, i, rvec[i]);\n\n    uint8_t *skey = (uint8_t*)gcry_malloc_secure(d->key_size);\n    memset(skey, 0, d->block_size);\n    conv_GF2X_to_bytes(rep(rvec[0]), d->block_size * 8, skey);\n\n    /* Setup cipher handle with secret key */\n    gcry_cipher_open(&dom->ctr_handle, d->algo, GCRY_CIPHER_MODE_CTR,\n                     GCRY_CIPHER_SECURE); \n    gcry_cipher_setkey(dom->ctr_handle, skey, d->key_size);\n\n\n    /* Cleanup */\n    gcry_free(skey);\n\n\n    *stat = DMMT_STAT_OK;\n\n    return dom;\n}\n\ndmmt_stat_t dmmt_free(dmmt_t *d)\n{\n    if (d != NULL)\n        free(d);\n\n    return DMMT_STAT_OK;\n}\n\n\n\n/* ############################################################################\n * # Domain\n * ############################################################################\n */\n\ndmmt_stat_t dmmt_dom_gen_share(dmmt_dom_t *dom, uint8_t *share_out)\n{\n    const dmmt_t *d = dom->d;\n    uint8_t *buf = (uint8_t*)malloc(d->block_size);\n    dmmt_stat_t stat = DMMT_STAT_INTERNAL_ERROR;\n\n    /* Create random x to evaluate at (also first component of share) */\n    GF2E x;\n    GF2X coeff_poly;\n    gcry_create_nonce(buf, d->block_size);\n    fill_GF2X_from_bytes(coeff_poly, buf, d->block_size);\n    conv(x, coeff_poly);\n\n    /* Evaluate polynomial at x */\n    GF2E y;\n    eval(y, dom->polynomial, x);\n\n    /* Write share */\n    memset(share_out, 0, d->block_size * 2);\n    int nb = conv_GF2X_to_bytes(rep(x), d->block_size * 8, share_out);\n    if (nb > 0) {\n        int nb = conv_GF2X_to_bytes(rep(y), d->block_size * 8,\n                                    share_out + d->block_size);\n\n        if (nb > 0) \n            stat = DMMT_STAT_OK;\n    }\n\n    /* Cleanup */\n    free(buf);\n\n    return DMMT_STAT_OK;\n}\n\nconst uint8_t *dmmt_dom_tag(dmmt_dom_t *dom)\n{\n    return dom->tag;\n}\n\n/* NOT THREAD SAFE - one encryption per domain at one time */\ndmmt_stat_t dmmt_dom_encrypt(dmmt_dom_t *dom, const uint8_t *in, size_t in_size, uint8_t *out, size_t out_size)\n{\n    const dmmt_t *d = dom->d;\n\n    /* IV */\n    if (out_size < d->block_size)\n        return DMMT_STAT_UNDERSIZED_BUFFER;\n\n    gcry_create_nonce(out, d->block_size);\n    gcry_cipher_setctr(dom->ctr_handle, out, d->block_size);\n    \n    /* Encrypt (skip over IV in the output buffer) */\n    if (gcry_cipher_encrypt(dom->ctr_handle, out + d->block_size, out_size - d->block_size, in, in_size) != 0)\n        return DMMT_STAT_INTERNAL_ERROR;\n\n    return DMMT_STAT_OK;\n}\n\n/* NOT THREAD SAFE - one decryption per domain at one time */\ndmmt_stat_t dmmt_dom_decrypt(dmmt_dom_t *dom, const uint8_t *in, size_t in_size, uint8_t *out, size_t out_size)\n{\n    const dmmt_t *d = dom->d;\n\n    /* IV */\n    if (in_size < d->block_size)\n        return DMMT_STAT_UNDERSIZED_BUFFER;\n\n    gcry_cipher_setctr(dom->ctr_handle, in, d->block_size);\n    \n    /* Decrypt (skip over IV in the input buffer) */\n    if (gcry_cipher_decrypt(dom->ctr_handle, out, out_size, in + d->block_size, in_size - d->block_size) != 0)\n        return DMMT_STAT_INTERNAL_ERROR;\n    \n    return DMMT_STAT_OK;\n}\n\n\ndmmt_stat_t dmmt_dom_free(dmmt_dom_t *dom)\n{\n    if (dom != NULL) {\n        gcry_cipher_close(dom->ctr_handle);\n        free(dom->tag);\n        gcry_free(dom);\n    }\n\n    return DMMT_STAT_OK;\n}\n\n\n\n/* ############################################################################\n * # Utilities\n * ############################################################################\n */\n\n\ninline void fill_block_with_int(dmmt_t *d, uint64_t v, uint8_t *out)\n{\n    const size_t sz = (d->block_size < sizeof(v)) ? d->block_size : sizeof(v);\n    size_t i;\n\n    for (i = 1; i <= sz; i++) {\n        out[d->block_size - i] = v & 0xFF;\n        v >>= 8;\n    }\n\n    for (; i <= d->block_size; i++)\n        out[d->block_size - i] = 0;\n}\n\ninline void xor_block_with_int(dmmt_t *d, uint64_t v, uint8_t *out)\n{\n    const size_t sz = (d->block_size < sizeof(v)) ? d->block_size : sizeof(v);\n\n    for (size_t i = 1; i <= sz; i++) {\n        out[d->block_size - i] ^= v & 0xFF;\n        v >>= 8;\n    }\n}\n\ninline void fill_GF2X_from_bytes(GF2X &f, const uint8_t *bytes, size_t num_bytes)\n{\n    size_t bitn = 0;\n\n    for (size_t i = 0; i < num_bytes; i++) {\n        uint8_t b = bytes[i];\n\n        for (size_t j = 0; j < 8; j++) {\n            SetCoeff(f, bitn++, b & 0x01);\n            b >>= 1;\n        }\n    }\n}\n\n/** Returns the number of BITS written */\ninline int conv_GF2X_to_bytes(const GF2X &f, long max_len, uint8_t *out)\n{\n    size_t i;\n    size_t j;\n    size_t bitn = 0;\n    const long lenf = deg(f) + 1;\n    const long len = (lenf < max_len) ? lenf : max_len;\n\n    if (len < 0)\n        return -1;\n\n    const size_t count = (size_t)len;\n    const size_t nbytes = count / 8;\n    uint8_t b;\n    \n    for (i = 0; i < nbytes; i++) {\n        b = 0;\n\n        for (j = 0; j < 8; j++) {\n            b |= rep(coeff(f, bitn++)) << j;\n        }\n\n        out[i] = b;\n    }\n\n    if (bitn < count) {\n        j = 0;\n        b = 0;\n        do {\n            b |= rep(coeff(f, bitn++)) << j++;\n        }\n        while (bitn < count);\n        out[i] = b;\n    }\n    \n    return (int)count; // number of bits\n}\n", "meta": {"hexsha": "00e9b2fcc6f01cf4cd1568379075763494029f4d", "size": 10924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dmmt.cpp", "max_stars_repo_name": "ciphron/DMMT", "max_stars_repo_head_hexsha": "9dc94096d9f06ceee569abb1ba556a5ad31dca82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dmmt.cpp", "max_issues_repo_name": "ciphron/DMMT", "max_issues_repo_head_hexsha": "9dc94096d9f06ceee569abb1ba556a5ad31dca82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dmmt.cpp", "max_forks_repo_name": "ciphron/DMMT", "max_forks_repo_head_hexsha": "9dc94096d9f06ceee569abb1ba556a5ad31dca82", "max_forks_repo_licenses": ["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.523364486, "max_line_length": 111, "alphanum_fraction": 0.5632552179, "num_tokens": 3174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.566368417876081}}
{"text": "#ifndef SH_PROCESS_HPP\n#define SH_PROCESS_HPP\n#include <vector>\n#include <cmath>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/math/special_functions/legendre.hpp>\n#include \"image/image.hpp\"\n#define _USE_MATH_DEFINES\n\n\nstruct SHDecomposition : public BaseProcess\n{\n\n    std::vector<float> UPiB;\n    unsigned int half_odf_size;\n        std::vector<unsigned int> b0_index;\n\n    static float Yj(int l,int m,float theta,float phi)\n    {\n        if (m == 0)\n            return boost::math::spherical_harmonic_r(l,m,theta,phi);\n        if (m < 0)\n            return M_SQRT2*boost::math::spherical_harmonic_r(l,m,theta,phi);\n        else\n            return M_SQRT2*boost::math::spherical_harmonic_i(l,m,theta,phi);\n    }\n\n    static int getJ(int m,int n)\n    {\n        return (n*n+n)/2+m;\n    }\npublic:\n    virtual void init(Voxel& voxel)\n    {\n\n\n\t\tb0_index.clear();\n                for(unsigned int index = 0;index < voxel.bvalues.size();++index)\n\t\t\tif(voxel.bvalues[index] == 0)\n\t\t\t    b0_index.push_back(index);\n\n\n        half_odf_size = voxel.ti.vertices_count/2;\n        float lambda = voxel.param[0];\n        unsigned int max_l = voxel.param[1];\n        const unsigned int R = ((max_l+1)*(max_l+2)/2);\n        std::vector<std::pair<int,int> > j_map(R);\n        for (int k = 0; k <= max_l; k += 2)\n            for (int m = -k; m <= k; ++m)\n                j_map[getJ(m,k)] = std::make_pair(m,k);\n\n        std::vector<float> Bt(R*voxel.bvectors.size());\n        for (unsigned int j = 0,index = 0; j < R; ++j)\n            for (unsigned int n = 0; n < voxel.bvectors.size(); ++n,++index)\n            {\n                float atan2_xy = std::atan2(voxel.bvectors[n][1],voxel.bvectors[n][0]);\n                if (atan2_xy < 0.0f)\n                    atan2_xy += float(2.0f*M_PI);\n                Bt[index] = Yj(j_map[j].second,j_map[j].first,std::acos(voxel.bvectors[n][2]),atan2_xy);\n            }\n        std::vector<float> UP(half_odf_size*R);\n        {\n            std::vector<float> U(half_odf_size*R);\n            for (unsigned int n = 0,index = 0; n < half_odf_size; ++n)\n                for (unsigned int j = 0; j < R; ++j,++index)\n                {\n                    float atan2_xy = std::atan2(voxel.ti.vertices[n][1],voxel.ti.vertices[n][0]);\n                    if (atan2_xy < 0.0f)\n                        atan2_xy += float(2.0f*M_PI);\n                    U[index] = Yj(j_map[j].second,j_map[j].first,std::acos(voxel.ti.vertices[n][2]),atan2_xy);\n                }\n            std::vector<float> P(R*R);\n            for (unsigned int i = 0,index = 0; i < R; ++i,index += R+1)\n                P[index] = boost::math::legendre_p(j_map[i].second,0.0)*2.0*M_PI;\n\n            image::mat::product(U.begin(),P.begin(),UP.begin(),image::dyndim(half_odf_size,R),image::dyndim(R,R));\n        }\n\n        std::vector<float> iB(Bt.size());\n        {\n            std::vector<float> BtB(R*R); // BtB = Bt * trans(Bt);\n            image::mat::square(Bt.begin(),BtB.begin(),image::dyndim(R,voxel.bvectors.size()));\n            for (unsigned int i = 0,index = 0; i < R; ++i,index += R+1)\n            {\n                float l = j_map[i].second;\n                BtB[index] += l*l*(l+1.0)*(l+1.0)*lambda;\n            }\n            std::vector<unsigned int> pivot(R);\n            image::mat::lu_decomposition(BtB.begin(),pivot.begin(),image::dyndim(R,R));\n\n            //iB = inv(BtB)*Bt;\n            image::mat::lu_solve(BtB.begin(),pivot.begin(),Bt.begin(),iB.begin(),image::dyndim(R,R),image::dyndim(R,voxel.bvectors.size()));\n        }\n\n\n        UPiB.resize(half_odf_size*voxel.bvectors.size());\n        image::mat::product(UP.begin(),iB.begin(),UPiB.begin(),image::dyndim(half_odf_size,R),image::dyndim(R,voxel.bvectors.size()));\n\n\n\n\n    }\npublic:\n    virtual void run(Voxel&, VoxelData& data)\n    {\n\n\t\t// remove the b0 signal\n                for(unsigned int index = 0;index < b0_index.size();++index)\n\t\t\tdata.space[b0_index[index]] = 0;\n        \n                image::mat::vector_product(&*UPiB.begin(),&*data.space.begin(),&*data.odf.begin(),image::dyndim(half_odf_size,data.space.size()));\n        for (unsigned int index = 0; index < data.odf.size(); ++index)\n            if (data.odf[index] < 0.0)\n                data.odf[index] = 0.0;\n    }\n};\n\n#endif//SH_PROCESS_HPP\n", "meta": {"hexsha": "4ad448306efce660aaf0006f3f3bd6fa77fd4724", "size": 4301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/dsi/sh_process.hpp", "max_stars_repo_name": "cbutakoff/DSI-Studio", "max_stars_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/dsi/sh_process.hpp", "max_issues_repo_name": "cbutakoff/DSI-Studio", "max_issues_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/dsi/sh_process.hpp", "max_forks_repo_name": "cbutakoff/DSI-Studio", "max_forks_repo_head_hexsha": "d77dffa4526d66da421fa84f7187e85bca6bce7c", "max_forks_repo_licenses": ["BSD-3-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.1428571429, "max_line_length": 146, "alphanum_fraction": 0.547314578, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5663665497991023}}
{"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\tusing Vector = std::conditional<std::is_same<SolveReal, float>::value, Eigen::VectorXf, Eigen::VectorXd>::type;\n\n\tUniformGrid<CellLabels> domainCellLabels;\n\tVectorGrid<StoreReal> boundaryWeights;\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> rhsA(domainCellLabels.size(), 0);\n\tUniformGrid<StoreReal> rhsB(domainCellLabels.size(), 0);\n\t\n\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int> &range)\n\t{\n\t\tstd::default_random_engine generator;\n\t\tstd::uniform_real_distribution<StoreReal> distribution(0, 1);\n\n\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\t\t\t\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\trhsA(cell) = distribution(generator);\n\t\t\t\trhsB(cell) = distribution(generator);\n\t\t\t}\n\t\t}\n\t});\n\n\tTransform xform(dx, Vec2f(0));\n\tstd::cout.precision(10);\n\t{\n\t\tUniformGrid<StoreReal> solutionA(domainCellLabels.size(), 0);\n\t\tUniformGrid<StoreReal> solutionB(domainCellLabels.size(), 0);\n\n\t\tstd::vector<Vec2i> boundaryCells = buildBoundaryCells(domainCellLabels, 3);\n\n\t\t// Test Jacobi symmetry\n\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, dx, &boundaryWeights);\n\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, dx, &boundaryWeights);\n\n\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\tSolveReal dotA = dotProduct<SolveReal>(solutionA, rhsB, domainCellLabels);\n\t\tSolveReal dotB = dotProduct<SolveReal>(solutionB, rhsA, domainCellLabels);\n\n\t\tstd::cout << \"Jacobi smoother symmetry test: \" << dotA << \", \" << dotB << std::endl;\n\t\tassert(fabs(dotA - dotB) / fabs(std::max(dotA, dotB)) < 1E-10);\n\t}\n\t{\n\t\t// Test direct solve symmetry\n\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<SolveReal>> myCoarseSolver;\n\t\tEigen::SparseMatrix<SolveReal> sparseMatrix;\n\n\t\t// Pre-build matrix at the coarsest level\n\t\tint interiorCellCount = 0;\n\t\tUniformGrid<int> directSolverIndices(domainCellLabels.size(), -1);\n\t\t{\n\t\t\tforEachVoxelRange(Vec2i(0), domainCellLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\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\tdirectSolverIndices(cell) = interiorCellCount++;\n\t\t\t});\n\n\t\t\t// Build rows\n\t\t\tstd::vector<Eigen::Triplet<SolveReal>> sparseElements;\n\n\t\t\tSolveReal gridScale = 1. / sqr(dx);\n\t\t\tforEachVoxelRange(Vec2i(0), domainCellLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\n\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL)\n\t\t\t\t{\n\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t\tassert(domainCellLabels(adjacentCell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\t\t\t\tdomainCellLabels(adjacentCell) == CellLabels::BOUNDARY_CELL);\n\n\t\t\t\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\t\t\t\t\t\t\tassert(boundaryWeights(face, axis) == 1);\n\n\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScale);\n\t\t\t\t\t\t}\n\t\t\t\t\tsparseElements.emplace_back(index, index, 4. * gridScale);\n\t\t\t\t}\n\t\t\t\telse if (domainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t{\n\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\tSolveReal diagonal = 0;\n\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t\tif (domainCellLabels(adjacentCell) == CellLabels::INTERIOR_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\t\t\t\t\t\t\t\tassert(boundaryWeights(face, axis) == 1);\n\n\t\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScale);\n\t\t\t\t\t\t\t\t++diagonal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (domainCellLabels(adjacentCell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\t\t\t\t\t\t\t\tSolveReal weight = boundaryWeights(face, axis);\n\n\t\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScale * weight);\n\t\t\t\t\t\t\t\tdiagonal += weight;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (domainCellLabels(adjacentCell) == CellLabels::DIRICHLET_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex == -1);\n\n\t\t\t\t\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\t\t\t\t\t\t\t\tSolveReal weight = boundaryWeights(face, axis);\n\n\t\t\t\t\t\t\t\tdiagonal += weight;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tassert(domainCellLabels(adjacentCell) == CellLabels::EXTERIOR_CELL);\n\t\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex == -1);\n\n\t\t\t\t\t\t\t\tVec2i face = cellToFace(cell, axis, direction);\n\t\t\t\t\t\t\t\tassert(boundaryWeights(face, axis) == 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tsparseElements.emplace_back(index, index, gridScale * diagonal);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Solve system\n\t\t\tsparseMatrix = Eigen::SparseMatrix<SolveReal>(interiorCellCount, interiorCellCount);\n\t\t\tsparseMatrix.setFromTriplets(sparseElements.begin(), sparseElements.end());\n\t\t\tsparseMatrix.makeCompressed();\n\n\t\t\tmyCoarseSolver.compute(sparseMatrix);\n\n\t\t\tassert(myCoarseSolver.info() == Eigen::Success);\n\t\t}\n\n\t\tUniformGrid<StoreReal> solutionA(domainCellLabels.size(), 0);\n\n\t\t{\n\t\t\tVector coarseRHSVector = Vector::Zero(interiorCellCount);\n\t\t\t// Copy to Eigen and direct solve\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseRHSVector(index) = rhsA(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tVector directSolution = myCoarseSolver.solve(coarseRHSVector);\n\n\t\t\t// Copy solution back\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tsolutionA(cell) = directSolution(index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tUniformGrid<StoreReal> solutionB(domainCellLabels.size(), 0);\n\n\t\t{\n\t\t\tVector coarseRHSVector = Vector::Zero(interiorCellCount);\n\t\t\t// Copy to Eigen and direct solve\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseRHSVector(index) = rhsB(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tVector directSolution = myCoarseSolver.solve(coarseRHSVector);\n\n\t\t\t// Copy solution back\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, domainCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = domainCellLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (domainCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tdomainCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tsolutionB(cell) = directSolution(index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Compute dot products\n\t\tSolveReal dotA = dotProduct<SolveReal>(solutionA, rhsB, domainCellLabels);\n\t\tSolveReal dotB = dotProduct<SolveReal>(solutionB, rhsA, domainCellLabels);\n\n\t\tstd::cout << \"Direct solver symmetry test: \" << dotA << \", \" << dotB << std::endl;\n\t\tassert(fabs(dotA - dotB) / fabs(std::max(dotA, dotB)) < 1E-10);\n\t}\n\n\t{\n\t\t// Test down and up sampling\n\t\tUniformGrid<CellLabels> coarseDomainLabels = buildCoarseCellLabels(domainCellLabels);\n\n\t\tassert(unitTestBoundaryCells<StoreReal>(coarseDomainLabels) && unitTestBoundaryCells<StoreReal>(domainCellLabels, &boundaryWeights));\n\t\tassert(unitTestExteriorCells(coarseDomainLabels) && unitTestExteriorCells(domainCellLabels));\n\t\tassert(unitTestCoarsening(coarseDomainLabels, domainCellLabels));\n\n\t\tUniformGrid<StoreReal> coarseRhs(coarseDomainLabels.size(), 0);\n\n\t\tUniformGrid<StoreReal> solutionA(domainCellLabels.size(), 0);\n\n\t\t{\n\t\t\tdownsample<SolveReal>(coarseRhs, rhsA, coarseDomainLabels, domainCellLabels);\n\t\t\tupsampleAndAdd<SolveReal>(solutionA, coarseRhs, domainCellLabels, coarseDomainLabels);\n\t\t}\n\t\t\n\t\tUniformGrid<StoreReal> solutionB(domainCellLabels.size(), 0);\n\t\t\n\t\t{\n\t\t\tdownsample<SolveReal>(coarseRhs, rhsB, coarseDomainLabels, domainCellLabels);\n\t\t\tupsampleAndAdd<SolveReal>(solutionB, coarseRhs, domainCellLabels, coarseDomainLabels);\n\t\t}\n\n\t\t// Compute dot products\n\t\tSolveReal dotA = dotProduct<SolveReal>(solutionA, rhsB, domainCellLabels);\n\t\tSolveReal dotB = dotProduct<SolveReal>(solutionB, rhsA, domainCellLabels);\n\n\t\tstd::cout << \"Coarse transfer symmetry test: \" << dotA << \", \" << dotB << std::endl;\n\t\tassert(fabs(dotA - dotB) / fabs(std::max(dotA, dotB)) < 1E-10);\n\t}\n\t{\n\t\t// Test single level correction\n\t\tUniformGrid<CellLabels> coarseDomainLabels = buildCoarseCellLabels(domainCellLabels);\n\n\t\tassert(unitTestBoundaryCells<StoreReal>(coarseDomainLabels) && unitTestBoundaryCells<StoreReal>(domainCellLabels, &boundaryWeights));\n\t\tassert(unitTestExteriorCells(coarseDomainLabels) && unitTestExteriorCells(domainCellLabels));\n\t\tassert(unitTestCoarsening(coarseDomainLabels, domainCellLabels));\n\t\n\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<SolveReal>> myCoarseSolver;\n\t\tEigen::SparseMatrix<SolveReal> sparseMatrix;\n\n\t\t// Pre-build matrix at the coarsest level\n\t\tint interiorCellCount = 0;\n\t\tUniformGrid<int> directSolverIndices(coarseDomainLabels.size(), -1);\n\t\t{\n\t\t\tforEachVoxelRange(Vec2i(0), coarseDomainLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\n\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\tcoarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\tdirectSolverIndices(cell) = interiorCellCount++;\n\t\t\t});\n\n\t\t\t// Build rows\n\t\t\tstd::vector<Eigen::Triplet<SolveReal>> sparseElements;\n\n\t\t\tSolveReal gridScale = 1. / sqr(2. * dx);\n\t\t\tforEachVoxelRange(Vec2i(0), coarseDomainLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\n\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL)\n\t\t\t\t{\n\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t\tauto adjacentLabels = coarseDomainLabels(adjacentCell);\n\t\t\t\t\t\t\tassert(adjacentLabels == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\t\t\tadjacentLabels == CellLabels::BOUNDARY_CELL);\n\n\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScale);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tsparseElements.emplace_back(index, index, 4. * gridScale);\n\t\t\t\t}\n\t\t\t\telse if (coarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t{\n\t\t\t\t\tSolveReal diagonal = 0;\n\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t\tauto cellLabels = coarseDomainLabels(adjacentCell);\n\t\t\t\t\t\t\tif (cellLabels == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\t\t\tcellLabels == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint adjacentIndex = directSolverIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScale);\n\t\t\t\t\t\t\t\t++diagonal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (cellLabels == CellLabels::DIRICHLET_CELL)\n\t\t\t\t\t\t\t\t++diagonal;\n\t\t\t\t\t\t}\n\n\t\t\t\t\tsparseElements.emplace_back(index, index, diagonal * gridScale);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tsparseMatrix = Eigen::SparseMatrix<SolveReal>(interiorCellCount, interiorCellCount);\n\t\t\tsparseMatrix.setFromTriplets(sparseElements.begin(), sparseElements.end());\n\t\t\tsparseMatrix.makeCompressed();\n\n\t\t\tmyCoarseSolver.compute(sparseMatrix);\n\n\t\t\tassert(myCoarseSolver.info() == Eigen::Success);\n\t\t}\n\n\t\t// Transfer rhs to coarse rhs as if it was a residual with a zero initial guess\n\t\tUniformGrid<StoreReal> solutionA(domainCellLabels.size(), 0);\n\t\t{\n\t\t\t// Pre-smooth to get an initial guess\n\t\t\tstd::vector<Vec2i> boundaryCells = buildBoundaryCells(domainCellLabels, 3);\n\n\t\t\t// Test Jacobi symmetry\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, dx, &boundaryWeights);\n\t\t\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\t\t\n\t\t\t// Compute new residual\n\t\t\tUniformGrid<StoreReal> residualA(domainCellLabels.size(), 0);\n\n\t\t\tcomputePoissonResidual<SolveReal>(residualA, solutionA, rhsA, domainCellLabels, dx, &boundaryWeights);\n\n\t\t\tUniformGrid<StoreReal> coarseRhs(coarseDomainLabels.size(), 0);\n\t\t\tdownsample<SolveReal>(coarseRhs, residualA, coarseDomainLabels, domainCellLabels);\n\n\t\t\tVector coarseRHSVector = Vector::Zero(interiorCellCount);\n\t\t\t\n\t\t\t// Copy to Eigen and direct solve\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseDomainLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = coarseDomainLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseRHSVector(index) = coarseRhs(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tUniformGrid<StoreReal> coarseSolution(coarseDomainLabels.size(), 0);\n\n\t\t\tVector directSolution = myCoarseSolver.solve(coarseRHSVector);\n\n\t\t\t// Copy solution back\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseDomainLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = coarseDomainLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseSolution(cell) = directSolution(index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tupsampleAndAdd<SolveReal>(solutionA, coarseSolution, domainCellLabels, coarseDomainLabels);\n\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, dx, &boundaryWeights);\n\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionA, rhsA, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\t\t}\n\n\t\tUniformGrid<StoreReal> solutionB(domainCellLabels.size(), 0);\n\t\t{\n\t\t\t// Pre-smooth to get an initial guess\n\t\t\tstd::vector<Vec2i> boundaryCells = buildBoundaryCells(domainCellLabels, 3);\n\n\t\t\t// Test Jacobi symmetry\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, dx, &boundaryWeights);\n\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\t\t// Compute new residual\n\t\t\tUniformGrid<StoreReal> residualB(domainCellLabels.size(), 0);\n\n\t\t\tcomputePoissonResidual<SolveReal>(residualB, solutionB, rhsB, domainCellLabels, dx, &boundaryWeights);\n\n\t\t\tUniformGrid<StoreReal> coarseRhs(coarseDomainLabels.size(), 0);\n\t\t\tdownsample<SolveReal>(coarseRhs, residualB, coarseDomainLabels, domainCellLabels);\n\n\t\t\tVector coarseRHSVector = Vector::Zero(interiorCellCount);\n\n\t\t\t// Copy to Eigen and direct solve\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseDomainLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = coarseDomainLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseRHSVector(index) = coarseRhs(cell);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tUniformGrid<StoreReal> coarseSolution(coarseDomainLabels.size(), 0);\n\n\t\t\tVector directSolution = myCoarseSolver.solve(coarseRHSVector);\n\n\t\t\t// Copy solution back\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseDomainLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = coarseDomainLabels.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseDomainLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseDomainLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = directSolverIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseSolution(cell) = directSolution(index);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tupsampleAndAdd<SolveReal>(solutionB, coarseSolution, domainCellLabels, coarseDomainLabels);\n\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\n\t\t\tinteriorJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, dx, &boundaryWeights);\n\n\t\t\tfor (int iteration = 0; iteration < 3; ++iteration)\n\t\t\t\tboundaryJacobiPoissonSmoother<SolveReal>(solutionB, rhsB, domainCellLabels, boundaryCells, dx, &boundaryWeights);\n\t\t}\n\n\t\tSolveReal dotA = dotProduct<SolveReal>(solutionA, rhsB, domainCellLabels);\n\t\tSolveReal dotB = dotProduct<SolveReal>(solutionB, rhsA, domainCellLabels);\n\n\t\tstd::cout << \"One level correction symmetry: \" << dotA << \", \" << dotB << std::endl;\n\t\tassert(fabs(dotA - dotB) / fabs(std::max(dotA, dotB)) < 1E-10);\n\t}\n\n\t{\n\t\t// Pre-build multigrid preconditioner\n\t\tGeometricMultigridPoissonSolver mgSolver(domainCellLabels, boundaryWeights, mgLevels, dx);\n\n\t\tUniformGrid<StoreReal> solutionA(domainCellLabels.size(), 0);\n\t\tmgSolver.applyMGVCycle(solutionA, rhsA);\n\t\tmgSolver.applyMGVCycle(solutionA, rhsA, true);\n\t\tmgSolver.applyMGVCycle(solutionA, rhsA, true);\n\t\tmgSolver.applyMGVCycle(solutionA, rhsA, true);\n\n\t\tUniformGrid<StoreReal> solutionB(domainCellLabels.size(), 0);\n\t\tmgSolver.applyMGVCycle(solutionB, rhsB);\n\t\tmgSolver.applyMGVCycle(solutionB, rhsB, true);\n\t\tmgSolver.applyMGVCycle(solutionB, rhsB, true);\n\t\tmgSolver.applyMGVCycle(solutionB, rhsB, true);\n\n\t\tSolveReal dotA = dotProduct<SolveReal>(solutionA, rhsB, domainCellLabels);\n\t\tSolveReal dotB = dotProduct<SolveReal>(solutionB, rhsA, domainCellLabels);\n\n\t\tstd::cout << \"4 v-cycle symmetry: \" << dotA << \", \" << dotB << std::endl;\n\t\tassert(fabs(dotA - dotB) / fabs(std::max(dotA, dotB)) < 1E-10);\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>(\"MG Symmetry 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 cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t{\n\t\t\tVec2i cell = tempGrid.unflatten(cellIndex);\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": "22c0f701b7f07ff4d367d597a818d4444a38676b", "size": 22851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Projects/Tests/TestGeometricMGPoissonSolver/TestSymmetry/TestSymmetry.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/TestSymmetry/TestSymmetry.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/TestSymmetry/TestSymmetry.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": 36.0995260664, "max_line_length": 142, "alphanum_fraction": 0.7099032865, "num_tokens": 6269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5663472527568675}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n//! Makes a coordinate transform that maps \n//!\n//! e1 to a1\n//! e2 to a2\n//! \n//! where {e1, e2} is the standard basis for R^2.\ntemplate<class Point>\nEigen::Matrix2d makeCoordinateTransform(const Point& a1, const Point& a2) {\n    Eigen::Matrix2d coordinateTransform;\n\n    coordinateTransform << a1(0), a2(0),\n                           a1(1), a2(1);\n\n    return coordinateTransform;\n}\n", "meta": {"hexsha": "6831894af2eebde5d5d7e2c2eb33e1054185360f", "size": 422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_solution/2d-poissonlFEM/coordinate_transform.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_handout/2d-poissonlFEM/coordinate_transform.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series0_handout/2d-poissonlFEM/coordinate_transform.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 22.2105263158, "max_line_length": 75, "alphanum_fraction": 0.6374407583, "num_tokens": 116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5662864127085717}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include \"square_matrix_multiply.hpp\"\n\nint main ()\n{\n    using namespace boost::numeric::ublas;\n    matrix<int> lhs(2,2), rhs(2,2);\n\n    lhs(0,0) = 1;\n    lhs(0,1) = 3;\n    lhs(1,0) = 7;\n    lhs(1,1) = 5;\n\n    rhs(0,0) = 6;\n    rhs(0,1) = 8;\n    rhs(1,0) = 4;\n    rhs(1,1) = 2;\n\n    std::cout << clrs::ch4::square_matrix_multiply_recursive(lhs,rhs)  << std::endl;\n    std::cout << clrs::ch4::square_matrix_multiply(lhs,rhs)            << std::endl;\n    std::cout << clrs::ch4::square_matrix_multiply_strassen(lhs,rhs)   << std::endl;\n\n}\n", "meta": {"hexsha": "ef5be2eb588866d20a87c6e94fd34864a96cf9a2", "size": 595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch04/main.cpp", "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": "ch04/main.cpp", "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": "ch04/main.cpp", "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.8, "max_line_length": 84, "alphanum_fraction": 0.5831932773, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5662864065511085}}
{"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#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n#include <ostream>\n\nint main()\n{\n\tusing namespace boost::numeric::ublas;\n\tusing namespace boost::multiprecision;\t\n\n\n\t// creates a three-dimensional tensor with extents 3,4 and 2\n\t// tensor A stores single-precision floating-point number according\n\t// to the first-order storage format\n\tusing ftype = float;\n\tauto A = tensor<ftype>{3,4,2};\n\n\t// initializes the tensor with increasing values along the first-index\n\t// using a single index.\n\tauto vf = ftype(0);\n\tfor(auto i = 0u; i < A.size(); ++i, vf += ftype(1))\n\t\tA[i] = vf;\n\n\t// formatted output\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"A=\" << A << \";\" << std::endl << std::endl;\n\n\t// creates a four-dimensional tensor with extents 5,4,3 and 2\n\t// tensor A stores complex floating-point extended double precision numbers\n\t// according to the last-order storage format\n\t// and initializes it with the default value.\n\tusing ctype = std::complex<cpp_bin_float_double_extended>;\n\tauto B = tensor<ctype,last_order>(shape{5,4,3,2},ctype{});\n\n\t// initializes the tensor with increasing values along the last-index\n\t// using a single-index\n\tauto vc = ctype(0,0);\n\tfor(auto i = 0u; i < B.size(); ++i, vc += ctype(1,1))\n\t\tB[i] = vc;\n\n\t// formatted output\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"B=\" << B << \";\" << std::endl << std::endl;\n\n\n\n\tauto C = tensor<ctype,last_order>(B.extents());\n\t// computes the complex conjugate of elements of B\n\t// using multi-index notation.\n\tfor(auto i = 0u; i < B.size(0); ++i)\n\t\tfor(auto j = 0u; j < B.size(1); ++j)\n\t\t\tfor(auto k = 0u; k < B.size(2); ++k)\n\t\t\t\tfor(auto l = 0u; l < B.size(3); ++l)\n\t\t\t\t\tC.at(i,j,k,l) = std::conj(B.at(i,j,k,l));\n\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"C=\" << C << \";\" << std::endl << std::endl;\n\n\n\t// computes the complex conjugate of elements of B\n\t// using iterators.\n\tauto D = tensor<ctype,last_order>(B.extents());\n\tstd::transform(B.begin(), B.end(), D.begin(), [](auto const& b){ return std::conj(b); });\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"D=\" << D << \";\" << std::endl << std::endl;\n\n\t// reshaping tensors.\n\tauto new_extents = B.extents().base();\n\tstd::next_permutation( new_extents.begin(), new_extents.end() );\n\tD.reshape( shape(new_extents)  );\n\tstd::cout << \"% --------------------------- \" << std::endl;\n\tstd::cout << \"% --------------------------- \" << std::endl << std::endl;\n\tstd::cout << \"newD=\" << D << \";\" << std::endl << std::endl;\n}\n", "meta": {"hexsha": "053690c7902ce4c356e6e18c5b1ab34767c61fd0", "size": 3225, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/examples/tensor/construction_access.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/construction_access.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/construction_access.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": 35.8333333333, "max_line_length": 90, "alphanum_fraction": 0.5680620155, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.5662863961767609}}
{"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/KepToCartToTLE.hpp\"\n\n\nnamespace KepToCartToTLE{\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 KepToCartToTLE( int newLimit, Vector2D randKepElem )\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    Vector2D CartPos( newLimit, std::vector< Real >( 3 ) ); // empty 2D vector to store position coordinates\n\t    Vector2D CartVel( newLimit, std::vector< Real >( 3 ) ); // empty 2D vector to store velocity components\n\t    Vector6 tempKep( 6 ); // temporary storage vector to store a given set of keplerian elements\n\t    Vector3 tempPos( 3 ); // temp storage vector for cartesian position\n\t    Vector3 tempVel( 3 ); // temp storage vector for cartesian velocity\n\t    Real rangeMag = 0; // magnitude range\n\t    Real velocityMag = 0; // velocity magnitude\n\t    for(int k = 0; k < newLimit; k++)\n\t    {\n\t        tempKep = randKepElem[ k ]; // transferring an entire row of the 2D vector which contains a single set of orbital elements\n\t        kep_toolbox::par2ic( tempKep, muEarth, tempPos, tempVel );\n\t        CartPos[ k ] = tempPos; // storing the output position coordinates in a row of the final 2D vector\n\t        CartVel[ k ] = tempVel; // same as above comment but this time for velocity    \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    \n\t    //store randomly generated keplerian element sets into a CSV file for easy viewing and use in future debugging of ATOM\n\t    std::ofstream RandomKepElemFile;\n\t    RandomKepElemFile.open(\"RandomKepElemFile_deletedScenes.csv\"); //file will be overwritten each time the code is run unless the name is changed here and the code recompiled\n\t    RandomKepElemFile << \"semi-major axis [km]\" << \",\" << \"eccentricity\" << \",\";\n\t    RandomKepElemFile << \"Inclination [deg]\" << \",\" << \"RAAN [deg]\" << \",\";\n\t    RandomKepElemFile << \"AOP [deg]\" << \",\" << \"Eccentric Anomaly [deg]\" << std::endl;\n\t    for(int i = 0; i < newLimit; i++)\n\t    {\n\t        RandomKepElemFile << ( randKepElem[ i ][ 0 ]/1000 ) << \",\";\n\t        RandomKepElemFile << randKepElem[ i ][ 1 ] << \",\";\n\t        RandomKepElemFile << sml::convertRadiansToDegrees( randKepElem[ i ][ 2 ] ) << \",\";\n\t        RandomKepElemFile << sml::convertRadiansToDegrees( randKepElem[ i ][ 3 ] ) << \",\";\n\t        RandomKepElemFile << sml::convertRadiansToDegrees( randKepElem[ i ][ 4 ] ) << \",\";\n\t        RandomKepElemFile << sml::convertRadiansToDegrees( randKepElem[ i ][ 5 ] ) << std::endl;\n\t    }\n\t    RandomKepElemFile.close();\n\n\n\t    //store the converted cartesian elements in a CSV file \n\t    std::ofstream RandomCartesianFile;\n\t    RandomCartesianFile.open(\"RandomCartesianFile_deletedScenes.csv\");\n\t    RandomCartesianFile << \"X [km]\" << \",\" << \"Y [km]\" << \",\" << \"Z [km]\" << \",\" << \"Range [km]\" << \",\";\n\t    RandomCartesianFile << \"Vx [km/s]\" << \",\" << \"Vy [km/s]\" << \",\" << \"Vz [km/s]\" << \",\" << \"Velocity [km/s]\" << std::endl;\n\t    for(int j = 0; j < newLimit; j++)\n\t    {\n\t        RandomCartesianFile << ( CartPos[ j ][ 0 ]/1000 ) << \",\";\n\t        RandomCartesianFile << ( CartPos[ j ][ 1 ]/1000 ) << \",\";\n\t        RandomCartesianFile << ( CartPos[ j ][ 2 ]/1000 ) << \",\";\n\t        rangeMag = sqrt( pow( CartPos[ j ][ 0 ], 2 ) + pow( CartPos[ j ][ 1 ], 2 ) + pow( CartPos[ j ][ 2 ], 2 ) );\n\t        RandomCartesianFile << ( rangeMag/1000 ) << \",\";\n\n\t        RandomCartesianFile << ( CartVel[ j ][ 0 ]/1000 ) << \",\";\n\t        RandomCartesianFile << ( CartVel[ j ][ 1 ]/1000 ) << \",\";\n\t        RandomCartesianFile << ( CartVel[ j ][ 2 ]/1000 ) << \",\";\n\t        velocityMag = sqrt( pow( CartVel[ j ][ 0 ], 2 ) + pow( CartVel[ j ][ 1 ], 2 ) + pow( CartVel[ j ][ 2 ], 2 ) );\n\t        RandomCartesianFile << ( velocityMag/1000 ) << std::endl;\n\t    }\n\t    RandomCartesianFile.close();\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    std::string SolverStatus;\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    // some other bookkeeping variables, these are not used in the convert to tle function\n\t    std::size_t findSuccess;\n\t    // file storage\n\t    std::ofstream tlefile;\n\t    tlefile.open(\"TLEfile.csv\");\n\t    tlefile << \"Conversion Status\" << \",\" << \"Iteration Count\" << \",\" << \",\" << \"Converted TLE\" << \",\" << \"Failure/Success Index\" << std::endl;\n\n\t    for(int i = 0; i < newLimit; i++)\n\t    {\n\t        // std::cout << \"loop count = \" << i << std::endl;\n\t        int IterationCount = 0; // counter for total iterations undertaken in a given instance of cartesian to TLE conversion\n\t        // important note, the atom function converting cartesian to TLEs takes in values in km and km/s.\n\t        cartesianState[ 0 ] = CartPos[ i ][ 0 ]/1000;\n\t        cartesianState[ 1 ] = CartPos[ i ][ 1 ]/1000;\n\t        cartesianState[ 2 ] = CartPos[ i ][ 2 ]/1000;\n\t        cartesianState[ 3 ] = CartVel[ i ][ 0 ]/1000;\n\t        cartesianState[ 4 ] = CartVel[ i ][ 1 ]/1000;\n\t        cartesianState[ 5 ] = CartVel[ i ][ 2 ]/1000;\n\t        convertedTle = atom::convertCartesianStateToTwoLineElements< Real, Vector6 >( cartesianState, DateTime( ), SolverStatus, \n\t            IterationCount, referenceTle, kMU, kXKMPER, absTol, relTol, maxItr );\n\t        findSuccess = SolverStatus.find(\"success\");    \n\t        if(findSuccess == std::string::npos)\n\t        {\n\t            std::cout << \"Cartesian to TLE Conversion Failed\" << std::endl;\n\t            tlefile << \"Failure\" << \",\";\n\t            tlefile << \",\" << \",\" << \",\" << \",\" << \",\" << i+2 << std::endl;\n\n\t        }\n\t        else\n\t        {\n\t            tlefile << \"Success\" << \",\";\n\t            tlefile << IterationCount << \",\" << \",\";\n\t            tlefile << \"Epoch = \" << convertedTle.Epoch() << \",\" << i+2 << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Mean motion Dt2 = \" << convertedTle.MeanMotionDt2() << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Mean motion Ddt6 = \" << convertedTle.MeanMotionDdt6() << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"B(*) = \" << convertedTle.BStar() << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Inclination = \" << convertedTle.Inclination(1) << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"RAAN = \" << convertedTle.RightAscendingNode(1) << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Eccentricity = \" << convertedTle.Eccentricity() << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"AOP = \" << convertedTle.ArgumentPerigee(1) << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Mean Anomaly = \" << convertedTle.MeanAnomaly(1) << std::endl;\n\t            tlefile << \",\" << \",\" << \",\" << \"Mean motion = \" << convertedTle.MeanMotion() << std::endl << std::endl;\n\t        }   \n\t    }\n\t    tlefile.close();\n\t}\n}", "meta": {"hexsha": "a561871221d7b0ff7aba44db4744f981ceae90d7", "size": 9342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/KepToCartToTLE.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": "examples/KepToCartToTLE.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": "examples/KepToCartToTLE.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": 50.2258064516, "max_line_length": 176, "alphanum_fraction": 0.5981588525, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.5662658354663059}}
{"text": "/*! \\file 2d_full.cpp\n  \\brief 2D plot of functions from map of doubles showing use of more options.\n  \\author Jacob Voytko\n  \\date 2007\n*/\n\n// Copyright Jacob Voytko 2007\n// Distributed under the Boost Software License, Version 1.0.\n// For more information, see http://www.boost.org\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing namespace boost::svg;\n\n#include <map>\nusing std::map;\n#include <cmath>\nusing ::sqrt;\n\n// Some functions to plot.\ndouble f(double x)\n{\n  return sqrt(x);\n}\n\ndouble g(double x)\n{\n  return -2 + x*x;\n}\n\ndouble h(double x)\n{\n  return -1 + 2*x;\n}\n\nint main()\n{\n  map<double, double> data1, data2, data3;\n\n  for(double i=0; i<=10.; i+=1.)\n  {\n    data1[i] = f(i);\n    data2[i] = g(i);\n    data3[i] = h(i);\n  }\n\n  svg_2d_plot my_plot;\n\n  // Size/scale settings.\n  my_plot.size(700, 500)\n         .x_range(-1, 10)\n         .y_range(-5, 100);\n\n  // Text settings.\n  my_plot.title(\"Plot of Mathematical Functions\")\n         .title_font_size(29)\n         .x_label(\"X Axis Units\");\n\n  // Commands.\n  my_plot.legend_on(true)\n         .plot_window_on(true)\n         .x_label_on(true)\n         .x_major_labels_side(true);\n\n  // Color settings.\n  my_plot.background_color(svg_color(67, 111, 69))\n         .legend_background_color(svg_color(207, 202,167))\n         .legend_border_color(svg_color(102, 102, 84))\n         .plot_background_color(svg_color(136, 188, 126))\n         .title_color(white);\n\n  //X axis settings.\n  my_plot.x_major_interval(2)\n         .x_major_tick_length(14)\n         .x_major_tick_width(1)\n         .x_minor_tick_length(7)\n         .x_minor_tick_width(1)\n         .x_num_minor_ticks(3)\n\n  //Y axis settings.\n         .y_major_interval(10)\n         .y_num_minor_ticks(3);\n\n  //legend settings\n  my_plot.legend_title_font_size(15);\n\n  my_plot.plot(data1, \"Sqrt(x)\").stroke_color(red);\n  my_plot.plot(data2, \"-2 + x^2\").stroke_color(orange);\n  my_plot.plot(data3, \"-1 + 2x\").stroke_color(yellow).shape(square).size(5);\n\n  my_plot.write(\"./2d_full.svg\");\n\n  return 0;\n} // int main()\n", "meta": {"hexsha": "76c052dab21a56e2233689a2c4c90c21c829fbc6", "size": 2021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/2d_full.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/2d_full.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/2d_full.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": 21.5, "max_line_length": 78, "alphanum_fraction": 0.6373082632, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.5662658293270799}}
{"text": "/*\n * This file is part of bogus, a C++ sparse block matrix library.\n *\n * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n*/\n\n/*! \\file\n\tNecessary bindings to use Eigen matrices as block types, and\n\t\\c operator* specialization for matrix/vector products\n*/\n\n\n#ifndef BLOCK_EIGENBINDINGS_HPP\n#define BLOCK_EIGENBINDINGS_HPP\n\n#include <Eigen/Core>\n\n#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE\n#include \"SparseHeader.hpp\"\n#endif\n\n#include \"../Block/BlockMatrixBase.hpp\"\n#include \"../Block/Expressions.hpp\"\n\n#ifndef BOGUS_BLOCK_WITHOUT_LINEAR_SOLVERS\n#include \"EigenLinearSolvers.hpp\"\n#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE\n#include \"EigenSparseLinearSolvers.hpp\"\n#endif\n#endif\n\n#include \"../Utils/CppTools.hpp\"\n\n#define BOGUS_EIGEN_NEW_EXPRESSIONS EIGEN_VERSION_AT_LEAST(3,2,90)\n\nnamespace bogus\n{\n\n// transpose_block, is_zero, resize, set_identity\n\ntemplate< typename EigenDerived >\ninline bool is_zero ( const Eigen::MatrixBase< EigenDerived >& block,\n                 typename EigenDerived::Scalar precision )\n{\n\treturn block.isZero( precision ) ;\n}\n\ntemplate< typename EigenDerived >\ninline void set_zero ( Eigen::MatrixBase< EigenDerived >& block )\n{\n\tblock.derived().setZero( ) ;\n}\n\ntemplate< typename EigenDerived >\ninline void set_identity ( Eigen::MatrixBase< EigenDerived >& block )\n{\n\tblock.derived().setIdentity( ) ;\n}\n\ntemplate< typename EigenDerived >\ninline void resize ( Eigen::MatrixBase< EigenDerived >& block, int rows, int cols )\n{\n\tblock.derived().resize( rows, cols ) ;\n}\n\ntemplate< typename EigenDerived >\ninline const typename EigenDerived::Scalar* data_pointer ( const Eigen::MatrixBase< EigenDerived >& block )\n{\n\treturn block.derived().data() ;\n}\n\n#ifndef BOGUS_BLOCK_WITHOUT_EIGEN_SPARSE\n\n#if !BOGUS_EIGEN_NEW_EXPRESSIONS\ntemplate < typename BlockT >\nstruct BlockTransposeTraits< Eigen::SparseMatrixBase < BlockT > > {\n\ttypedef const Eigen::Transpose< const BlockT > ReturnType ;\n} ;\ntemplate<typename _Scalar, int _Flags, typename _Index>\nstruct BlockTransposeTraits< Eigen::SparseMatrix < _Scalar, _Flags, _Index > >\n        : public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::SparseMatrix < _Scalar, _Flags, _Index > > >\n{} ;\ntemplate<typename _Scalar, int _Flags, typename _Index>\nstruct BlockTransposeTraits< Eigen::SparseVector < _Scalar, _Flags, _Index > >\n        : public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::SparseVector < _Scalar, _Flags, _Index > > >\n{} ;\ntemplate<typename _Scalar, int _Flags, typename _Index>\nstruct BlockTransposeTraits< Eigen::MappedSparseMatrix < _Scalar, _Flags, _Index > >\n        : public BlockTransposeTraits< Eigen::SparseMatrixBase< Eigen::MappedSparseMatrix < _Scalar, _Flags, _Index > > >\n{} ;\n\ntemplate< typename EigenDerived >\ninline const Eigen::Transpose< const EigenDerived >\ntranspose_block( const Eigen::SparseMatrixBase< EigenDerived >& block )\n{\n\treturn block.transpose() ;\n}\n#endif\n\ntemplate< typename EigenDerived >\ninline bool is_zero ( const Eigen::SparseMatrixBase< EigenDerived >& block,\n                 typename EigenDerived::Scalar precision )\n{\n\treturn block.isZero( precision ) ;\n}\n\ntemplate < typename Scalar, int Options, typename Index >\ninline void set_identity ( Eigen::SparseMatrix< Scalar, Options, Index >& block )\n{\n\treturn block.setIdentity( ) ;\n}\n\ntemplate < typename Scalar, int Options, typename Index >\ninline void resize ( Eigen::SparseMatrix< Scalar, Options, Index >& block, Index rows, Index cols )\n{\n\tblock.resize( rows, cols ) ;\n}\n\n#endif\n\n// Block traits for Eigen::Matrix\n\ntemplate< typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols >\nstruct BlockTraits < Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >\n{\n\ttypedef _Scalar Scalar ;\n\tenum {\n\t\tRowsAtCompileTime = _Rows,\n\t\tColsAtCompileTime = _Cols,\n\t\tuses_plain_array_storage = 1,\n\t\tis_row_major = !!( _Options & Eigen::RowMajor ),\n\t\tis_self_transpose = ( _Rows == _Cols ) && ( _Rows == 1 )\n\t} ;\n\n\t// Manipulates _Options so that row and column vectorz have the correct RowMajor value\n\t// Should we default to _Options ^ Eigen::RowMajor ?\n\ttypedef Eigen::Matrix< _Scalar, _Cols, _Rows,\n\t( _Options | ((_Cols==1&&_Rows!=1)?Eigen::RowMajor:0)) & ~((_Rows==1&&_Cols!=1)?Eigen::RowMajor:0),\n\t_MaxCols, _MaxRows >\n\tTransposeStorageType ;\n\n} ;\n\n// Block/block product return type\n\ntemplate<\n    typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols,\n    typename _Scalar2, int _Rows2, int _Cols2, int _Options2, int _MaxRows2, int _MaxCols2,\n    bool TransposeLhs, bool TransposeRhs >\nstruct BlockBlockProductTraits <\n         Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>,\n         Eigen::Matrix<_Scalar2, _Rows2, _Cols2, _Options2, _MaxRows2, _MaxCols2>,\n        TransposeLhs, TransposeRhs >\n{\n\ttypedef Eigen::Matrix< _Scalar,\n\t    SwapIf< TransposeLhs, _Rows, _Cols >::First,\n\t    SwapIf< TransposeRhs, _Rows2, _Cols2 >::Second,\n\t    _Options,\n\t    SwapIf< TransposeLhs, _MaxRows, _MaxCols >::First,\n\t    SwapIf< TransposeRhs, _MaxRows2, _MaxCols2 >::Second >\n\tReturnType ;\n} ;\n\ntemplate< typename Derived >\ninline typename Eigen::internal::plain_matrix_type<Derived>::type\nget_mutable_vector( const Eigen::MatrixBase< Derived > & )\n{\n\treturn typename Eigen::internal::plain_matrix_type<Derived>::type() ;\n}\n\n} //ns bogus\n\n// Matrix vector product return types and operator*\n\nnamespace bogus {\nnamespace mv_impl {\n\n//! Wrapper so our SparseBlockMatrix can be used inside Eigen expressions\ntemplate< typename Derived >\nstruct EigenBlockWrapper : public Eigen::EigenBase< EigenBlockWrapper< Derived > >\n{\n\ttypedef EigenBlockWrapper Nested ;\n\ttypedef EigenBlockWrapper NestedExpression ;\n\ttypedef EigenBlockWrapper PlainObject ;\n\ttypedef Eigen::internal::traits< EigenBlockWrapper< Derived > > Traits ;\n\ttypedef typename Traits::Scalar Scalar ;\n\ttypedef typename Traits::Index Index ;\n\n\tenum { Flags = Traits::Flags, IsVectorAtCompileTime = 0,\n\tMaxRowsAtCompileTime = Traits::MaxRowsAtCompileTime,\n\tMaxColsAtCompileTime = Traits::MaxColsAtCompileTime\n\t     } ;\n\n\tEigenBlockWrapper ( const Derived &obj_, Scalar s = 1 )\n\t    : obj( obj_ ), scaling(s)\n\t{}\n\n\tIndex rows() const { return obj.rows() ; }\n\tIndex cols() const { return obj.cols() ; }\n\n\t// Mult by scalar\n\n\tinline EigenBlockWrapper\n\toperator*(const Scalar& scalar) const\n\t{ return EigenBlockWrapper( obj, scaling * scalar ) ; }\n\n\tinline friend EigenBlockWrapper\n\toperator*(const Scalar& scalar, const EigenBlockWrapper& matrix)\n\t{ return EigenBlockWrapper( matrix.obj, matrix.scaling * scalar ) ; }\n\n\n\t// Product with other Eigen expr\n#if BOGUS_EIGEN_NEW_EXPRESSIONS\n\ttemplate < typename EigenDerived >\n\tinline Eigen::Product< EigenBlockWrapper, EigenDerived > operator* (\n\t    const EigenDerived &rhs ) const\n\t{\n\t\treturn Eigen::Product< EigenBlockWrapper, EigenDerived > (*this, rhs) ;\n\t}\n\ttemplate < typename EigenDerived >\n\tfriend inline Eigen::Product< EigenDerived, EigenBlockWrapper > operator* (\n\t    const EigenDerived &lhs, const EigenBlockWrapper &matrix )\n\t{\n\t\treturn Eigen::Product< EigenDerived, EigenBlockWrapper > (lhs, matrix) ;\n\t}\n#endif\n\n\tconst Derived &obj ;\n\tconst Scalar scaling ;\n};\n\n//! SparseBlockMatrix / Dense producty expression\n\ntemplate< typename Lhs, typename Rhs >\nstruct block_product_impl;\n\n#if BOGUS_EIGEN_NEW_EXPRESSIONS\ntemplate < typename Lhs, typename Rhs >\nstruct BlockEigenProduct\n        : public Eigen::Product< Lhs, Rhs >\n{\n\ttypedef Eigen::Product< Lhs, Rhs > Base ;\n\n\tBlockEigenProduct( const Lhs& lhs, const Rhs& rhs )\n\t    : Base( lhs, rhs)\n\t{}\n} ;\n#else\n\ntemplate < typename Lhs, typename Rhs >\nstruct BlockEigenProduct\n        : public Eigen::ProductBase< BlockEigenProduct< Lhs, Rhs>, Lhs, Rhs >\n{\n\ttypedef Eigen::ProductBase< BlockEigenProduct, Lhs, Rhs > Base ;\n\n\tBlockEigenProduct( const Lhs& lhs, const Rhs& rhs )\n\t    : Base( lhs, rhs)\n\t{}\n\n\tEIGEN_DENSE_PUBLIC_INTERFACE( BlockEigenProduct )\n\tusing Base::m_lhs;\n\tusing Base::m_rhs;\n\ttypedef block_product_impl< typename Base::LhsNested, typename Base::RhsNested > product_impl ;\n\n\ttemplate<typename Dest> inline void evalTo(Dest& dst) const\n\t{\n\t\tproduct_impl::evalTo( dst, m_lhs, this->m_rhs ) ;\n\t}\n\ttemplate<typename Dest> inline void scaleAndAddTo(Dest& dst, Scalar alpha) const\n\t{\n\t\tproduct_impl::scaleAndAddTo( dst, m_lhs, m_rhs, alpha ) ;\n\t}\n};\n#endif\n\ntemplate< typename Derived, typename EigenDerived >\nBlockEigenProduct< EigenBlockWrapper< Derived >, EigenDerived >  block_eigen_product(\n        const Derived &matrix, const EigenDerived &vector, typename Derived::Scalar scaling = 1 )\n{\n\treturn BlockEigenProduct< EigenBlockWrapper< Derived >, EigenDerived > ( EigenBlockWrapper< Derived >(matrix, scaling), vector ) ;\n}\n\ntemplate< typename Derived, typename EigenDerived >\nBlockEigenProduct< EigenDerived, EigenBlockWrapper< Derived > >  eigen_block_product(\n        const EigenDerived &vector, const Derived &matrix, typename Derived::Scalar scaling = 1 )\n{\n\treturn BlockEigenProduct< EigenDerived, EigenBlockWrapper< Derived > > ( vector, EigenBlockWrapper< Derived >(matrix, scaling) ) ;\n}\n\ntemplate<typename Derived, typename EigenDerived >\nstruct block_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived >\n{\n\ttypedef bogus::mv_impl::EigenBlockWrapper<Derived> Lhs ;\n\ttypedef EigenDerived Rhs ;\n\ttypedef typename Derived::Scalar Scalar;\n\n\ttemplate<typename Dst>\n\tstatic void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)\n\t{\n\t\tlhs.obj.template multiply< false >( rhs.derived(), dst, lhs.scaling, 0 ) ;\n\t}\n\ttemplate<typename Dst>\n\tstatic void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)\n\t{\n\t\tlhs.obj.template multiply< false >( rhs.derived(), dst, alpha*lhs.scaling, 1 ) ;\n\t}\n};\n\ntemplate<typename Derived, typename EigenDerived >\n        struct block_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived> >\n{\n\ttypedef EigenDerived Lhs ;\n\ttypedef bogus::mv_impl::EigenBlockWrapper<Derived> Rhs ;\n\ttypedef typename Derived::Scalar Scalar;\n\n\ttemplate<typename Dst>\n\tstatic void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)\n\t{\n\t\tEigen::Transpose< Dst > transposed( dst.transpose() ) ;\n\t\trhs.obj.template multiply< true >( lhs.transpose(), transposed, rhs.scaling, 0 ) ;\n\t}\n\ttemplate<typename Dst>\n\tstatic void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)\n\t{\n\t\tEigen::Transpose< Dst > transposed( dst.transpose() ) ;\n\t\trhs.obj.template multiply< true >( lhs.transpose(), transposed, alpha * rhs.scaling, 1 ) ;\n\t}\n};\n\n} //namespace mv_impl\n} //namespace bogus\n\n\n#if BOGUS_EIGEN_NEW_EXPRESSIONS\nnamespace Eigen {\nnamespace internal {\n\ntemplate<typename Derived, typename EigenDerived, int ProductType >\nstruct generic_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived, SparseShape, DenseShape, ProductType>\n        : public generic_product_impl_base <\n            bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived,\n            generic_product_impl< bogus::mv_impl::EigenBlockWrapper<Derived>, EigenDerived, SparseShape, DenseShape, ProductType > >\n{\n\ttypedef bogus::mv_impl::EigenBlockWrapper<Derived> Lhs ;\n\ttypedef EigenDerived Rhs ;\n\ttypedef typename Derived::Scalar Scalar;\n\n\ttypedef typename nested_eval<Rhs,Dynamic>::type RhsNested;\n\ttypedef bogus::mv_impl::block_product_impl< Lhs, RhsNested > product_impl ;\n\n\ttemplate<typename Dst>\n\tstatic void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)\n\t{\n\t\tRhsNested rhsNested( rhs ) ;\n\t\tproduct_impl::evalTo( dst, lhs, rhsNested ) ;\n\t}\n\ttemplate<typename Dst>\n\tstatic void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, Scalar alpha)\n\t{\n\t\tRhsNested rhsNested( rhs ) ;\n\t\tproduct_impl::scaleAndAddTo( dst, lhs, rhsNested, alpha ) ;\n\t}\n};\n\ntemplate<typename Derived, typename EigenDerived, int ProductType >\nstruct generic_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>, DenseShape, SparseShape, ProductType >\n        : public generic_product_impl_base <\n            EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>,\n            generic_product_impl< EigenDerived, bogus::mv_impl::EigenBlockWrapper<Derived>, DenseShape, SparseShape, ProductType > >\n{\n\ttypedef EigenDerived Lhs ;\n\ttypedef bogus::mv_impl::EigenBlockWrapper<Derived> Rhs ;\n\ttypedef typename Derived::Scalar Scalar;\n\n\ttypedef typename nested_eval<Lhs,Dynamic>::type LhsNested;\n\ttypedef bogus::mv_impl::block_product_impl< LhsNested, Rhs > product_impl ;\n\n\ttemplate<typename Dst>\n\tstatic void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs)\n\t{\n\t\tLhsNested lhsNested(lhs);\n\t\tproduct_impl::evalTo( dst, lhsNested, rhs) ;\n\t}\n\ttemplate<typename Dst>\n\tstatic void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha)\n\t{\n\t\tLhsNested lhsNested(lhs);\n\t\tproduct_impl::scaleAndAddTo( dst, lhsNested, rhs, alpha ) ;\n\t}\n};\n\n// s * (A * V) -> ( (s*A) * V )\n// (A already includes a scaling parameter)\n// TODO adapt to other orderings\ntemplate<typename Derived, typename Rhs, typename Scalar1, typename Scalar2, typename Plain1>\nstruct evaluator<CwiseBinaryOp<internal::scalar_product_op<Scalar1,Scalar2>,\n                               const CwiseNullaryOp<internal::scalar_constant_op<Scalar1>, Plain1>,\n                               const Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > >\n : public evaluator<Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> >\n{\n  typedef CwiseBinaryOp<internal::scalar_product_op<Scalar1,Scalar2>,\n\t                           const CwiseNullaryOp<internal::scalar_constant_op<Scalar1>, Plain1>,\n\t                           const Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > XprType;\n  typedef evaluator<Product<bogus::mv_impl::EigenBlockWrapper<Derived>, Rhs, DefaultProduct> > Base;\n\n  explicit evaluator(const XprType& xpr)\n\t: Base( bogus::mv_impl::EigenBlockWrapper<Derived>(\n\t            xpr.rhs().lhs().obj, xpr.lhs().functor().m_other * xpr.rhs().lhs().scaling)\n\t        * xpr.rhs().rhs() )\n   {}\n\n };\n\n} //internal\n} //Eigen\n\n\n#endif\n\n\n\n// Eigen traits for our new structs\nnamespace Eigen{\nnamespace internal {\n\ntemplate < typename Lhs, typename Rhs >\nstruct traits< bogus::mv_impl::BlockEigenProduct< Lhs, Rhs > >\n#if BOGUS_EIGEN_NEW_EXPRESSIONS\n        : public traits< typename bogus::mv_impl::BlockEigenProduct< Lhs, Rhs >::Base >\n        #else\n        : public traits< ProductBase< bogus::mv_impl::BlockEigenProduct< Lhs, Rhs >, Lhs, Rhs > >\n        #endif\n{\n  typedef Dense StorageKind;\n} ;\n\ntemplate<typename Derived>\nstruct traits<bogus::mv_impl::EigenBlockWrapper<Derived> >\n{\n  typedef typename Derived::Scalar Scalar;\n  typedef typename Derived::Index Index;\n  typedef typename Derived::Index StorageIndex;\n#if BOGUS_EIGEN_NEW_EXPRESSIONS\n  typedef Sparse StorageKind;\n#else\n  typedef Dense StorageKind;\n#endif\n  typedef MatrixXpr XprKind;\n  enum {\n\tRowsAtCompileTime = Dynamic,\n\tColsAtCompileTime = Dynamic,\n\tMaxRowsAtCompileTime = Dynamic,\n\tMaxColsAtCompileTime = Dynamic,\n\tFlags = 0\n  };\n};\n}\n\n} //namespace Eigen\n\n\n// Matrix-Vector operators\n\nnamespace bogus{\n\ntemplate < typename Derived, typename EigenDerived >\nmv_impl::BlockEigenProduct< mv_impl::EigenBlockWrapper<Derived>, EigenDerived > operator* (\n        const BlockObjectBase< Derived >& lhs,\n        const Eigen::MatrixBase< EigenDerived > &rhs )\n{\n\tassert( rhs.rows() == lhs.cols() ) ;\n\treturn mv_impl::block_eigen_product ( lhs.derived(), rhs.derived() ) ;\n}\n\ntemplate < typename Derived, typename EigenDerived >\nmv_impl::BlockEigenProduct< mv_impl::EigenBlockWrapper<Derived>, EigenDerived > operator* (\n        const Scaling< Derived >& lhs,\n        const Eigen::MatrixBase< EigenDerived > &rhs )\n{\n\tassert( rhs.rows() == lhs.cols() ) ;\n\treturn mv_impl::block_eigen_product ( lhs.operand.object, rhs.derived(), lhs.operand.scaling ) ;\n}\n\ntemplate < typename Derived, typename EigenDerived >\nmv_impl::BlockEigenProduct< EigenDerived, mv_impl::EigenBlockWrapper<Derived> > operator* (\n        const Eigen::MatrixBase< EigenDerived > &lhs,\n        const BlockObjectBase< Derived >& rhs )\n{\n\tassert( lhs.cols() == rhs.rows() ) ;\n\treturn mv_impl::eigen_block_product ( lhs.derived(), rhs.derived() ) ;\n}\n\ntemplate < typename Derived, typename EigenDerived >\nmv_impl::BlockEigenProduct< EigenDerived, mv_impl::EigenBlockWrapper<Derived> > operator* (\n        const Eigen::MatrixBase< EigenDerived > &lhs,\n        const Scaling< Derived >& rhs )\n{\n\tassert( lhs.cols() == rhs.rows() ) ;\n\treturn mv_impl::eigen_block_product ( lhs.derived(), rhs.operand.object, rhs.operand.scaling ) ;\n}\n\n\n} //namespace bogus\n\n#endif // EIGENBINDINGS_HPP\n", "meta": {"hexsha": "22a6a5c640aa2ad3a51dfa7495eea54e0685b051", "size": 16791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/src/Core/Eigen/BlockBindings.hpp", "max_stars_repo_name": "sjokic/WallDestruction", "max_stars_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "include/src/Core/Eigen/BlockBindings.hpp", "max_issues_repo_name": "sjokic/WallDestruction", "max_issues_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/src/Core/Eigen/BlockBindings.hpp", "max_forks_repo_name": "sjokic/WallDestruction", "max_forks_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_forks_repo_licenses": ["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.9235294118, "max_line_length": 132, "alphanum_fraction": 0.7319992853, "num_tokens": 4230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5662658233193626}}
{"text": "\n#include \"ear/decorrelate.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <complex>\n#include <random>\n#include \"ear/layout.hpp\"\n#include \"kissfft/kissfft.hh\"\n\nconst double PI = boost::math::constants::pi<double>();\n\nnamespace ear {\n\n  std::vector<long> genRandMt19937(int seed, int n) {\n    std::mt19937 mtRand(seed);\n    std::vector<long> ret;\n    for (int i = 0; i < n; ++i) {\n      ret.push_back(mtRand());\n    }\n    return ret;\n  }\n\n  std::vector<double> genRandFloat(int seed, int n) {\n    std::vector<double> ret;\n    for (long randomValue : genRandMt19937(seed, n)) {\n      ret.push_back(randomValue / static_cast<double>(0x100000000l));\n    }\n    return ret;\n  }\n\n  /** @brief Design an all-pass random-phase FIR filter.\n   *\n   * @param decorrelator_id Random seed, to obtain different filters.\n   * @param size filter length.\n   *\n   * @return  Filter coefficients.\n   */\n  std::vector<double> designDecorrelatorBasic(int decorrelatorId, int size) {\n    std::vector<double> rand = genRandFloat(decorrelatorId, size / 2 - 1);\n    std::vector<std::complex<double>> freqDomainData(size);\n    freqDomainData[0] = std::complex<double>(1.0, 0.0);\n    for (size_t i = 0; i < rand.size(); ++i) {\n      freqDomainData[i + 1] =\n          std::exp(std::complex<double>(0.0, 2.0 * PI * rand[i]));\n    }\n    freqDomainData[size / 2] = std::complex<double>(1.0, 0.0);\n    for (size_t i = 0; i < freqDomainData.size() / 2; ++i) {\n      freqDomainData[size / 2 + i] = std::conj(freqDomainData[size / 2 - i]);\n    }\n    kissfft<double> fft(size, true);\n    std::vector<std::complex<double>> timeDomainData(size);\n    fft.transform(&freqDomainData[0], &timeDomainData[0]);\n    std::vector<double> timeDomainDataReal(size);\n    for (size_t i = 0; i < timeDomainData.size(); ++i) {\n      timeDomainDataReal[i] = timeDomainData[i].real() / size;\n    }\n    return timeDomainDataReal;\n  }\n\n  const int decorrelator_size = 512;\n\n  template <>\n  std::vector<std::vector<double>> designDecorrelators<double>(Layout layout) {\n    std::vector<std::string> channelNames = layout.channelNames();\n    std::vector<std::string> channelNamesSorted(channelNames);\n    std::sort(channelNamesSorted.begin(), channelNamesSorted.end());\n    std::vector<std::vector<double>> decorrelators;\n    for (auto channelName : channelNames) {\n      auto it =\n          std::find_if(channelNamesSorted.begin(), channelNamesSorted.end(),\n                       [&channelName](const std::string name) -> bool {\n                         return channelName == name;\n                       });\n      int index =\n          static_cast<int>(std::distance(channelNamesSorted.begin(), it));\n      std::vector<double> coefficients =\n          designDecorrelatorBasic(index, decorrelator_size);\n      decorrelators.push_back(coefficients);\n    }\n    return decorrelators;\n  }\n\n  template <>\n  EAR_EXPORT std::vector<std::vector<float>> designDecorrelators<float>(\n      Layout layout) {\n    auto decorrelators = designDecorrelators<double>(layout);\n    std::vector<std::vector<float>> decorrelators_float;\n\n    for (auto &decorrelator : decorrelators) {\n      std::vector<float> decorrelator_float(decorrelator.size());\n\n      for (size_t i = 0; i < decorrelator.size(); i++)\n        decorrelator_float[i] = (float)decorrelator[i];\n\n      decorrelators_float.emplace_back(std::move(decorrelator_float));\n    }\n\n    return decorrelators_float;\n  }\n\n  int decorrelatorCompensationDelay() { return (decorrelator_size - 1) / 2; }\n}  // namespace ear\n", "meta": {"hexsha": "b8e9435826a697aa31429cfbd5731d65e07a2fb9", "size": 3526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/decorrelate.cpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/decorrelate.cpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decorrelate.cpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9038461538, "max_line_length": 79, "alphanum_fraction": 0.6497447533, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5662438032884354}}
{"text": "\n/******************************************************\n *\n *\n *\n * mex -I/usr/include/eigen3 ssimcpp.cpp\n ******************************************************/\n\n#include <iostream>\n#include <math.h>\n#include <Eigen/Dense>\n#include \"mex.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n\n  const mwSize *dim;\n  dim = mxGetDimensions(prhs[0]);\n  \n  double *Aptr, *Bptr;\n  Aptr = mxGetPr(prhs[0]);\n  Bptr = mxGetPr(prhs[1]);\n   \n  MatrixXd A, B, A2, B2;\n  A.resize(dim[0],dim[1]);\n  A << Map<MatrixXd>(Aptr, dim[0], dim[1]);\n  B.resize(dim[0],dim[1]);\n  B << Map<MatrixXd>(Bptr, dim[0], dim[1]);\n  \n  A2.resize(dim[0],dim[1]);\n  B2.resize(dim[0],dim[1]);\n    \n  const double mA = A.mean();\n  const double mB = B.mean();\n  \n  A2 = (A- mA*MatrixXd::Ones(dim[0], dim[1]));\n  B2 = (B- mB*MatrixXd::Ones(dim[0], dim[1]));\n  \n  const double N = dim[0]*dim[1];\n  const double sA = A2.cwiseAbs2().sum()/N;\n  const double sB = B2.cwiseAbs2().sum()/N;\n  \n  double sAB = 0.0;\n  uint i, j;\n  for (i=0; i<N; i++){\n      for (j=0; j<N; j++){\n          if (j>i) sAB = sAB+(A(i)-A(j))*(B(i)-B(j));\n      }\n  }\n  sAB = sAB/(N*N);\n  \n  plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);\n  double *Out;\n  Out = mxGetPr(plhs[0]);\n  MatrixXd::Map(Out, 1, 1) << (2*mA*mB+0.001)*(2*sAB+0.009)/((mB*mB+mA*mA+0.001)*(sB+sA+0.009));\n  return;\n  \n}\n\n//EOF", "meta": {"hexsha": "8d42ed105cde1a5511f4816603775d3006a3c385", "size": 1403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ssimcpp.cpp", "max_stars_repo_name": "ysraell/gcbsrd", "max_stars_repo_head_hexsha": "bc2eb59030ed47951523cc52d386edb86bb98a86", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-22T06:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T09:19:34.000Z", "max_issues_repo_path": "ssimcpp.cpp", "max_issues_repo_name": "ysraell/gcbsrd", "max_issues_repo_head_hexsha": "bc2eb59030ed47951523cc52d386edb86bb98a86", "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": "ssimcpp.cpp", "max_forks_repo_name": "ysraell/gcbsrd", "max_forks_repo_head_hexsha": "bc2eb59030ed47951523cc52d386edb86bb98a86", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-24T09:23:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-24T09:23:44.000Z", "avg_line_length": 21.921875, "max_line_length": 96, "alphanum_fraction": 0.5160370634, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5661667306917635}}
{"text": "//\n// Created by jachu on 05.02.18.\n//\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include <EKFPlane.hpp>\n\n#include \"Types.hpp\"\n#include \"Misc.hpp\"\n#include \"EKFPlane.hpp\"\n\nusing namespace std;\n\n\nEKFPlane::EKFPlane() {}\n\nEKFPlane::EKFPlane(const Eigen::Quaterniond &xq, const Eigen::Matrix4d &Pq) {\n    init(xq, Pq);\n}\n\nEKFPlane::EKFPlane(const Eigen::Quaterniond &xq, int npts) {\n    init(xq, npts);\n}\n\n\n\nvoid EKFPlane::init(const Eigen::Quaterniond &xq, const Eigen::Matrix4d &Pq) {\n    x = xq;\n    Eigen::MatrixXd J = jacob_dom_dq(xq);\n    P = J * Pq * J.transpose();\n}\n\nvoid EKFPlane::init(const Eigen::Quaterniond &xq, int npts) {\n    x = xq;\n    EKFPlane::npts = npts;\n}\n\nvoid EKFPlane::update(const Eigen::Quaterniond &zq, const Eigen::Matrix4d &Rq) {\n    // jacobian of transformation from quaternion to log-map of quaternion\n    Eigen::MatrixXd J_dom_dq = jacob_dom_dq(zq);\n    // covariance in log-map representation\n    Eigen::Matrix3d R = J_dom_dq * Rq * J_dom_dq.transpose();\n    \n    update(zq, R);\n}\n\nvoid EKFPlane::update(const Eigen::Quaterniond &zq, const Eigen::Matrix3d &R) {\n//    cout << endl << \"x = \" << x.coeffs().transpose() << endl;\n//    cout << \"P = \" << P << endl;\n//    cout << \"zq = \" << zq.coeffs().transpose() << endl;\n//    cout << \"R = \" << R << endl;\n    // innovation\n    Eigen::Vector3d v = Misc::logMap(zq * x.inverse());\n//    cout << \"v = \" << v.transpose() << endl;\n    // innovation covariance\n    Eigen::Matrix3d S = P + R;\n//    cout << \"S = \" << S << endl;\n    // Kalman gain\n    Eigen::Matrix3d K = P * S.inverse();\n//    {\n//        Eigen::EigenSolver<Eigen::Matrix3d> evd(R);\n//\n//        Eigen::Matrix3d evecs;\n//        Eigen::Vector3d evals;\n//        for(int i = 0; i < 3; ++i){\n//            evecs.col(i) = evd.eigenvectors().col(2 - i).real();\n//            evals(i) = evd.eigenvalues()(2 - i).real();\n//        }\n////        if(evals(0) > 1.0){\n//            cout << endl << \"evecs = \" << evecs << endl;\n//            cout << \"evals = \" << evals.transpose() << endl;\n//\n//            cout  << \"x = \" << x.coeffs().transpose() << endl;\n//            cout  << \"log(x) = \" << Misc::logMap(x).transpose() << endl;\n//            cout << \"zq = \" << zq.coeffs().transpose() << endl;\n//            cout  << \"log(zq) = \" << Misc::logMap(zq).transpose() << endl;\n//            cout << \"v = \" << v.transpose() << endl;\n//            cout << \"updated x = \" << (Misc::expMap(K * v) * x).coeffs().transpose() << endl;\n//            cout  << \"log(updated x) = \" << Misc::logMap(Misc::expMap(K * v) * x).transpose() << endl;\n//            cout << \"P = \" << P << endl;\n//            cout << \"R = \" << R << endl;\n//            cout << \"S = \" << S << endl;\n//            cout << \"S.inverse() = \" << S.inverse() << endl;\n//            cout << \"K = \" << K << endl;\n//            cout << \"K * v = \" << (K * v).transpose() << endl;\n//\n////            char a;\n////            cin >> a;\n////        }\n//    }\n//    cout << \"K = \" << K << endl;\n    // update of state\n//    cout << \"K * v = \" << K * v << endl;\n    x = Misc::expMap(K * v) * x;\n//    cout << \"updated x = \" << x.coeffs().transpose() << endl;\n    // update of covariance\n    P = (Eigen::Matrix3d::Identity() - K) * P;\n//    cout << \"updated P = \" << P << endl;\n}\n\n//void EKFPlane::transform(const Eigen::Matrix4d T)\n//{\n//    Eigen::Matrix4d Tinv = T.inverse();\n//    Eigen::Matrix4d Tinvt = Tinv.transpose();\n//\n//    Eigen::Vector4d planeEq = Tinvt * x.coeffs();\n//    Eigen::Matrix4d covarQuat = Tinvt * covarQuat * Tinv;\n//}\n\nvoid EKFPlane::update(const Eigen::Quaterniond &zq, int znpts) {\n//    cout << \"updating\" << endl;\n    // innovation\n    Eigen::Vector3d v = Misc::logMap(zq * x.inverse());\n    x = Misc::expMap((double)znpts/(znpts + npts) * v) * x;\n    \n//    Eigen::Vector3d meanLogMap;\n//    meanLogMap << 0.0, 0.0, 0.0;\n//    int sumPoints = 0;\n//    {\n//        Eigen::Vector3d z = Misc::logMap(zq);\n//        meanLogMap += z * znpts;\n//        sumPoints += znpts;\n//        cout << \"z = \" << zq.coeffs().transpose() << endl;\n//        cout << \"logMap(z) = \" << z.transpose() << endl;\n//    }\n//    {\n//        Eigen::Vector3d xu = Misc::logMap(x);\n//        meanLogMap += xu * npts;\n//        sumPoints += npts;\n//        cout << \"x = \" << x.coeffs().transpose() << endl;\n//        cout << \"logMap(x) = \" << xu.transpose() << endl;\n//    }\n//    meanLogMap /= sumPoints;\n//\n//    cout << \"meanLogMap = \" << meanLogMap.transpose() << endl;\n    \n    \n    npts += znpts;\n}\n\ndouble EKFPlane::distance(const Eigen::Quaterniond &xcq) const {\n//    Eigen::Matrix3d inf = P.inverse();\n//    cout << \"P = \" << P << endl;\n//    cout << \"inf = \" << inf << endl;\n//    Eigen::Vector3d e = Misc::logMap(xcq * x.inverse());\n//    cout << \"x = \" << x.coeffs().transpose() << endl;\n//    cout << \"xcq = \" << xcq.coeffs().transpose() << endl;\n//    cout << \"diff = \" << (xcq * x.inverse()).coeffs().transpose() << endl;\n    \n//    return e.transpose() * inf * e;\n//    return e.transpose() * e;\n    \n    Eigen::Vector4d plEq = x.coeffs();\n    plEq /= plEq.head<3>().norm();\n    if(plEq(3) < 0){\n        plEq = -plEq;\n    }\n    Eigen::Vector4d plEqc = xcq.coeffs();\n    plEqc /= plEqc.head<3>().norm();\n    if(plEqc(3) < 0){\n        plEqc = -plEqc;\n    }\n    double dd = plEq(3) - plEqc(3);\n    dd = dd * dd;\n    double da = acos(plEq.head<3>().dot(plEqc.head<3>()));\n    da = da * da;\n    \n    double drange = 4;\n    double arange = M_PI;\n    \n    return (dd * arange + da * drange)/(drange + arange);\n}\n\nvoid EKFPlane::compPlaneEqAndCovar(const Eigen::MatrixXd &pts,\n                                   Eigen::Quaterniond &q,\n                                   Eigen::Matrix4d &R)\n{\n//    // Compute mean\n//    mean_ = Eigen::Vector4f::Zero ();\n//    compute3DCentroid (*input_, *indices_, mean_);\n//    // Compute demeanished cloud\n//    Eigen::MatrixXf cloud_demean;\n//    demeanPointCloud (*input_, *indices_, mean_, cloud_demean);\n//    assert (cloud_demean.cols () == int (indices_->size ()));\n//    // Compute the product cloud_demean * cloud_demean^T\n//    Eigen::Matrix3f alpha = static_cast<Eigen::Matrix3f> (cloud_demean.topRows<3> () * cloud_demean.topRows<3> ().transpose ());\n//\n//    // Compute eigen vectors and values\n//    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> evd (alpha);\n//    // Organize eigenvectors and eigenvalues in ascendent order\n//    for (int i = 0; i < 3; ++i)\n//    {\n//        eigenvalues_[i] = evd.eigenvalues () [2-i];\n//        eigenvectors_.col (i) = evd.eigenvectors ().col (2-i);\n//    }\n    Eigen::Vector3d mean = Eigen::Vector3d::Zero();\n    for(int i = 0; i < pts.cols(); ++i){\n        mean += pts.col(i);\n    }\n    mean /= pts.cols();\n    \n    Eigen::MatrixXd demeanPts = pts;\n    for(int i = 0; i < demeanPts.cols(); ++i){\n        demeanPts.col(i) -= mean;\n    }\n    \n    Eigen::Matrix3d covar = demeanPts * demeanPts.transpose();\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> evd(covar);\n    \n    Eigen::Matrix3d evecs;\n    Eigen::Vector3d evals;\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    cout << \"evals = \" << (evals.array()/demeanPts.cols()).sqrt() << endl;\n    \n    // the smallest eigenvalue corresponds to the eigenvector that is normal to the plane\n    double varD = evals(2) / demeanPts.cols();\n    double varX = evals(2) / evals(0);\n    double varY = evals(2) / evals(1);\n    \n    Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n    T.block<3, 3>(0, 0) = evecs;\n    T.block<3, 1>(0, 3) = mean;\n    Eigen::Matrix4d Tinv = T.inverse();\n    Eigen::Matrix4d Tinvt = Tinv.transpose();\n    \n    // plane with normal (0, 0, 1) and distance 0;\n    Eigen::Vector4d planeEq;\n    planeEq << 0.0, 0.0, 1.0, 0.0;\n    // transform it to destination pose\n    planeEq = Tinvt * planeEq;\n    \n    Eigen::Matrix4d covarQuat = Eigen::Matrix4d::Zero();\n    covarQuat(0, 0) = varX;\n    covarQuat(1, 1) = varY;\n    covarQuat(2, 2) = 0;\n    covarQuat(3, 3) = varD;\n    covarQuat = Tinvt * covarQuat * Tinv;\n    \n//    Eigen::Matrix4d J_dqn_dq = jacob_dqn_dq(Eigen::Quaterniond(planeEq(3), planeEq(0), planeEq(1), planeEq(2)));\n//    planeEq.normalize();\n//    R = J_dqn_dq * covarQuat * J_dqn_dq.transpose();\n    \n    double planeEqNorm = planeEq.norm();\n    planeEq /= planeEqNorm;\n    R = covarQuat / (planeEqNorm * planeEqNorm);\n    \n    q.coeffs() = planeEq;\n}\n\n//[ (2*acos(qw)*(qy^2 + qz^2))/(qx^2 + qy^2 + qz^2)^(3/2),        -(2*qx*qy*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2),        -(2*qx*qz*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2), -(2*qx)/((1 - qw^2)^(1/2)*(qx^2 + qy^2 + qz^2)^(1/2))]\n//[        -(2*qx*qy*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2), (2*acos(qw)*(qx^2 + qz^2))/(qx^2 + qy^2 + qz^2)^(3/2),        -(2*qy*qz*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2), -(2*qy)/((1 - qw^2)^(1/2)*(qx^2 + qy^2 + qz^2)^(1/2))]\n//[        -(2*qx*qz*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2),        -(2*qy*qz*acos(qw))/(qx^2 + qy^2 + qz^2)^(3/2), (2*acos(qw)*(qx^2 + qy^2))/(qx^2 + qy^2 + qz^2)^(3/2), -(2*qz)/((1 - qw^2)^(1/2)*(qx^2 + qy^2 + qz^2)^(1/2))]\n\nEigen::MatrixXd EKFPlane::jacob_dom_dq(const Eigen::Quaterniond &q) {\n    Eigen::MatrixXd J(3, 4);\n    double qx = q.x();\n    double qy = q.y();\n    double qz = q.z();\n    double qw = q.w();\n    double sqVecNorm = qx*qx + qy*qy + qz*qz;\n    double vecNorm = sqrt(sqVecNorm);\n    double den = sqVecNorm * vecNorm;\n    J << (2*acos(qw)*(qy*qy + qz*qz))/den,          -(2*qx*qy*acos(qw))/den,          -(2*qx*qz*acos(qw))/den, -(2*qx)/(sqrt(1 - qw*qw)*vecNorm),\n        -(2*qx*qy*acos(qw))/den,           (2*acos(qw)*(qx*qx + qz*qz))/den,          -(2*qy*qz*acos(qw))/den, -(2*qy)/(sqrt(1 - qw*qw)*vecNorm),\n        -(2*qx*qz*acos(qw))/den,                    -(2*qy*qz*acos(qw))/den, (2*acos(qw)*(qx*qx + qy*qy))/den, -(2*qz)/(sqrt(1 - qw*qw)*vecNorm);\n    \n    return J;\n}\n\n\n//[ (qw^2 + qy^2 + qz^2)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qx*qy)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qx*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qw*qx)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2)]\n//[             -(qx*qy)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2), (qw^2 + qx^2 + qz^2)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qy*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qw*qy)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2)]\n//[             -(qx*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qy*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2), (qw^2 + qx^2 + qy^2)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qw*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2)]\n//[             -(qw*qx)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qw*qy)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2),             -(qw*qz)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2), (qx^2 + qy^2 + qz^2)/(qw^2 + qx^2 + qy^2 + qz^2)^(3/2)]\nEigen::MatrixXd EKFPlane::jacob_dqn_dq(const Eigen::Quaterniond &q) {\n    Eigen::MatrixXd J(4, 4);\n    double qx = q.x();\n    double qy = q.y();\n    double qz = q.z();\n    double qw = q.w();\n    double sqVecNorm = qx*qx + qy*qy + qz*qz + qw*qw;\n    double vecNorm = sqrt(sqVecNorm);\n    double den = sqVecNorm * vecNorm;\n    \n    J << (qw*qw + qy*qy + qz*qz)/den,                -(qx*qy)/den,                -(qx*qz)/den,                -(qw*qx)/den,\n                        -(qx*qy)/den, (qw*qw + qx*qx + qz*qz)/den,                -(qy*qz)/den,                -(qw*qy)/den,\n                        -(qx*qz)/den,                -(qy*qz)/den, (qw*qw + qx*qx + qy*qy)/den,                -(qw*qz)/den,\n                        -(qw*qx)/den,                -(qw*qy)/den,                -(qw*qz)/den, (qx*qx + qy*qy + qz*qz)/den;\n    \n    return J;\n}\n\nconst Eigen::Quaterniond &EKFPlane::getX() const {\n    return x;\n}\n\nconst Eigen::Matrix3d &EKFPlane::getP() const {\n    return P;\n}\n\n\n\n\n", "meta": {"hexsha": "4f898357a5ecc2ffc20815f95fde0b1a79a9656f", "size": 11753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EKFPlane.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/EKFPlane.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/EKFPlane.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": 37.9129032258, "max_line_length": 227, "alphanum_fraction": 0.5004679656, "num_tokens": 4245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5661667203199268}}
{"text": "#include <array>                    // for std::array\n#include <chrono>                   // for std::chrono\n#include <iostream>                 // for std::cout\n#include <boost/format.hpp>         // for boost::format\n#include <boost/numeric/odeint.hpp> // for boost::numeric::odeint\n\nusing state_type = std::array<double, 2>;\n\nvoid rhs(state_type const & y, state_type & dydx, double const x);\n\nint main()\n{\n    using namespace std::chrono;\n    using namespace boost::numeric::odeint;\n    using stepper_type = boost::numeric::odeint::bulirsch_stoer<state_type>;\n    \n    auto const start = system_clock::now();\n\n    auto const x1 = 0.00001;\n    auto const xf = 11.0;\n    auto const dx = 0.001;\n    \n    state_type y1 = { 0.99998416139571, -1.58175227379914 };\n\n    integrate_const(\n        stepper_type(1.0E-15, 1.0E-15),\n        [](state_type const & y, state_type & dydx, double const x)\n        {\n\t        dydx[0] = y[1];\n\t        dydx[1] = y[0] * std::sqrt(y[0] / x);\n        },\n        y1,\n        x1,\n        xf,\n        dx);\n    auto const end = system_clock::now();\n\n    std::cout << boost::format(\"y[1] = %.14f, y[2] = %.14f\\n\") % y1[0] % y1[1];\n    std::cout << boost::format(\"計算時間 = %.14f（秒）\\n\") % duration_cast< duration<double> >(end - start).count();\n}\n", "meta": {"hexsha": "c2d8679fd9472da577e7c79a8cf81dc151799b84", "size": 1269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solveode.cpp", "max_stars_repo_name": "dc1394/solveode_cppvsjulia", "max_stars_repo_head_hexsha": "3aea5824271f0ae8db776c0dc6d9549289d75979", "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": "solveode.cpp", "max_issues_repo_name": "dc1394/solveode_cppvsjulia", "max_issues_repo_head_hexsha": "3aea5824271f0ae8db776c0dc6d9549289d75979", "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": "solveode.cpp", "max_forks_repo_name": "dc1394/solveode_cppvsjulia", "max_forks_repo_head_hexsha": "3aea5824271f0ae8db776c0dc6d9549289d75979", "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.9512195122, "max_line_length": 109, "alphanum_fraction": 0.5626477541, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.56603392033636}}
{"text": "/*\n *  callbond_test.cpp\n *  bondgeek\n *\n *  Created by BART MOSLEY on 6/3/12.\n *  Copyright 2012 BG Research LLC. All rights reserved.\n *\n */\n\n#include <bg/bondgeek.hpp>\n\n#include <iostream>\n#include <algorithm>\n\n#include <boost/timer.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\nusing namespace bondgeek;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n    Integer sessionId() { return 0; }\n}\n#endif\n\nboost::shared_ptr<YieldTermStructure>\nflatRate(const Date& today,\n         const boost::shared_ptr<Quote>& forward,\n         const DayCounter& dc,\n         const Compounding& compounding,\n         const Frequency& frequency) {\n    return boost::shared_ptr<YieldTermStructure>(\n                                                 new FlatForward(today,\n                                                                 Handle<Quote>(forward),\n                                                                 dc,\n                                                                 compounding,\n                                                                 frequency));\n}\n\n\nboost::shared_ptr<YieldTermStructure>\nflatRate(const Date& today,\n         Rate forward,\n         const DayCounter& dc,\n         const Compounding &compounding,\n         const Frequency &frequency) {\n    return flatRate(today,\n                    boost::shared_ptr<Quote>(new SimpleQuote(forward)),\n                    dc,\n                    compounding,\n                    frequency);\n}\n\nint main (int argc, char * const argv[]) \n{\n    \n    Date today = Date(16,October,2007);\n    Settings::instance().evaluationDate() = today;\n    \n    cout <<  endl;\n    cout << \"Pricing a callable fixed rate bond using\" << endl;\n    cout << \"Hull White model w/ reversion parameter = 0.03\" << endl;\n    cout << \"BAC4.65 09/15/12  ISIN: US06060WBJ36\" << endl;\n    cout << \"roughly five year tenor, \";\n    cout << \"quarterly coupon and call dates\" << endl;\n    cout << \"reference date is : \" << today << endl;\n    cout << \"3 day settle: \" << TARGET().advance(today, 3, Days) << endl << endl;\n    \n    /* Bloomberg OAS1: \"N\" model (Hull White)\n     varying volatility parameter\n     \n     The curve entered into Bloomberg OAS1 is a flat curve,\n     at constant yield = 5.5%, semiannual compounding.\n     Assume here OAS1 curve uses an ACT/ACT day counter,\n     as documented in PFC1 as a \"default\" in the latter case.\n     */\n    \n    // set up a flat curve corresponding to Bloomberg flat curve\n    \n    Rate bbCurveRate = 0.055;\n    DayCounter bbDayCounter = ActualActual(ActualActual::Bond);\n    InterestRate bbIR(bbCurveRate,bbDayCounter,Compounded,Semiannual);\n    \n    Handle<YieldTermStructure> termStructure(flatRate(today,\n                                                      bbIR.rate(),\n                                                      bbIR.dayCounter(),\n                                                      bbIR.compounding(),\n                                                      bbIR.frequency()));\n    \n    // set up the call schedule\n    \n    CallabilitySchedule callSchedule;\n    Real callPrice = 100.;\n    Size numberOfCallDates = 19;\n    Date callDate = Date(15, December, 2007);\n    \n    Date sDate(callDate.serialNumber());\n    for (Size i=0; i< numberOfCallDates; i++) {\n        Calendar nullCalendar = NullCalendar();\n        \n        Callability::Price myPrice(callPrice,\n                                   Callability::Price::Clean);\n        callSchedule.push_back(\n                               boost::shared_ptr<Callability>(\n                                                              new Callability(myPrice,\n                                                                              Callability::Call,\n                                                                              sDate )));\n        sDate = nullCalendar.advance(sDate, 3, Months);\n    }\n    \n    cout << \"calls: \" << callDate << \" to \" << sDate << endl;\n    \n    // set up the callable bond\n    \n    Date dated = Date(16,September,2004);\n    Date issue = dated;\n    Date maturity = Date(15,September,2012);\n    Natural settlementDays = 3;  // Bloomberg OAS1 settle is Oct 19, 2007\n    Calendar bondCalendar = UnitedStates(UnitedStates::GovernmentBond);\n    \n    //Real coupon = .0465;\n    Real coupon = .06;\n    Frequency frequency = Quarterly;\n    Real redemption = 100.0;\n    Real faceAmount = 100.0;\n    \n    /* The 30/360 day counter Bloomberg uses for this bond cannot\n     reproduce the US Bond/ISMA (constant) cashflows used in PFC1.\n     Therefore use ActAct(Bond)\n     */\n    DayCounter bondDayCounter = ActualActual(ActualActual::Bond);\n    \n    // PFC1 shows no indication dates are being adjusted\n    // for weekends/holidays for vanilla bonds\n    BusinessDayConvention accrualConvention = Unadjusted;\n    BusinessDayConvention paymentConvention = Unadjusted;\n    \n    Schedule sch(dated, maturity, Period(frequency), bondCalendar,\n                 accrualConvention, accrualConvention,\n                 DateGeneration::Backward, false);\n    \n    Size maxIterations = 1000;\n    Real accuracy = 1e-8;\n    Integer gridIntervals = 60;\n    Real reversionParameter = .03;\n    \n    // output price/yield results for varying volatility parameter\n    \n    Real sigma = max(0.03, QL_EPSILON); // core dumps if zero on Cygwin\n    \n    boost::shared_ptr<ShortRateModel> hw0(\n                                          new HullWhite(termStructure,reversionParameter,sigma));\n    \n    boost::shared_ptr<PricingEngine> engine0(\n                                             new TreeCallableFixedRateBondEngine(hw0,gridIntervals));\n    \n    CallableFixedRateBond callableBond(settlementDays, faceAmount, sch,\n                                       vector<Rate>(1, coupon),\n                                       bondDayCounter, paymentConvention,\n                                       redemption, issue, callSchedule);\n    callableBond.setPricingEngine(engine0);\n    \n    cout << setprecision(5)\n    << \"Flat Rate: \" << bbCurveRate << \" | disc factor: \" << 100.0*termStructure.currentLink()->discount(10.0) << endl;\n    \n    cout << setprecision(2)\n    << showpoint\n    << fixed\n    << \"sigma/vol (%) = \"\n    << 100.*sigma\n    << \", mean reversion = \" << reversionParameter \n    << endl;\n    \n    cout << \"\\nQuantLib price/yld (%)  \";\n    cout << callableBond.cleanPrice() << \" / \"\n    << 100. * callableBond.yield(bondDayCounter,\n                                 Compounded,\n                                 frequency,\n                                 accuracy,\n                                 maxIterations)\n    << endl;\n\n    cout << \"\\nNow price with a bg curve \" << endl;\n    string depotenors[] = {\"1W\", \"1M\", \"3M\", \"6M\", \"9M\", \"1y\"};\n    double depospots[] = {.055, .055, .055, .055, .055, .055};\n    string swaptenors[] = {\"2y\", \"3y\", \"5y\", \"10y\", \"15y\", \"20y\", \"30y\"};\n    double swapspots[] = {.055, .055, .055, .055, .055, .055, .055};\n    \n    cout << \"Test with new curve \" << endl;\n    RateHelperCurve acurve = RateHelperCurve(USDLiborCurve(\"3M\"));\n    acurve.update(depotenors, \n                  depospots, \n                  6,\n                  swaptenors,                                                                      \n                  swapspots,\n                  7,\n                  today);\n    \n    cout << \"Curve: \" \n    << acurve.discountingTermStructure().currentLink()->referenceDate() << \"/\"\n    << acurve.discountingTermStructure().currentLink()->maxDate() << endl;\n    \n    cout << setprecision(3) \n    << \"quote:  \" << io::rate(acurve.tenorquote(\"10Y\")) ;\n    \n    cout << setprecision(5)\n    << \" | disc factor: \" << 100.0*acurve.discountingTermStructure().currentLink()->discount(10.0) << endl;\n    \n    boost::shared_ptr<ShortRateModel> hw1(\n                                          new HullWhite(acurve.discountingTermStructure(), \n                                                        reversionParameter, \n                                                        sigma));\n    \n    boost::shared_ptr<PricingEngine> engine1(\n                                             new TreeCallableFixedRateBondEngine(hw1,\n                                                                                 gridIntervals));\n    \n    callableBond.setPricingEngine(engine1);\n    \n    \n    cout << \"price/yld (%)  \";\n    cout << callableBond.cleanPrice() << \" / \"\n    << 100. * callableBond.yield(bondDayCounter,\n                                 Compounded,\n                                 frequency,\n                                 accuracy,\n                                 maxIterations)\n    << endl;\n    \n    \n    cout << \"\\nbondgeek::CallBond\\n\";\n    cout << setprecision(3)\n    << \"cpn: \" << io::rate(coupon) \n    << \" mty: \" << maturity \n    << \" call: \" << callDate \n    << \" @ \" << callPrice \n    << endl;\n    \n    CallBond noncallbond(coupon, \n                         maturity,\n                         dated, \n                         bondCalendar, \n                         settlementDays,\n                         bondDayCounter,\n                         frequency, \n                         redemption,\n                         faceAmount,\n                         accrualConvention,\n                         paymentConvention\n                         );\n    \n    CallBond zeronc_bond(0.0, \n                         Date(15, February, 2023),\n                         Date(29, June, 1995), \n                         bondCalendar, \n                         settlementDays,\n                         Thirty360(Thirty360::BondBasis),\n                         Semiannual, \n                         redemption,\n                         faceAmount,\n                         accrualConvention,\n                         paymentConvention\n                         );\n    \n    BulletBond bulletbond(coupon, \n                          maturity, \n                          dated, \n                          bondCalendar, \n                          settlementDays,\n                          bondDayCounter,\n                          frequency,\n                          redemption,\n                          faceAmount,\n                          accrualConvention,\n                          paymentConvention\n                          );\n    \n    CallBond callbnd(coupon, \n                     maturity, \n                     callDate, \n                     callPrice, \n                     dated, \n                     bondCalendar, \n                     settlementDays,\n                     bondDayCounter,\n                     frequency,\n                     frequency,\n                     redemption,\n                     faceAmount,\n                     accrualConvention,\n                     paymentConvention);\n        \n    cout << \"Call Schedule\" << endl;\n    CallabilitySchedule  callbndsched1 = callableBond.callability();\n    CallabilitySchedule  callbndsched2 = callbnd.callability();\n    CallabilitySchedule  callbndsched3 = noncallbond.callability();\n    \n    vector< boost::shared_ptr<Callability> >::size_type sz1 = callbndsched1.size();\n    vector< boost::shared_ptr<Callability> >::size_type sz2 = callbndsched2.size();\n    vector< boost::shared_ptr<Callability> >::size_type sz3 = callbndsched3.size();\n    \n    cout << \"Call sizes: \" << endl <<\n    \"1) \" << sz1 << endl <<\n    \"2) \" << sz2 << endl <<\n    \"3) \" << sz3 << endl;\n    \n    if (sz1 != sz2) {\n        cout << \"\\nCall schedules not equal!!! \" << sz1 << \" vs \" << sz2 << endl;\n        for (int i=0; i<sz1; i++) {\n            cout << callbndsched1[i]->date() << \" | \" << callbndsched1[i]->price().amount() << endl;\n        }\n        for (int i=0; i<sz2; i++) {\n            cout << callbndsched2[i]->date() << \" | \" << callbndsched2[i]->price().amount() << endl;\n        }\n        return 1;\n    } \n    \n    callbnd.setPricingEngine(engine1);\n    noncallbond.setPricingEngine(engine1);\n    bulletbond.setPricingEngine(engine1);\n    cout << \"test value: \" << callbnd.cleanPrice() << endl << endl;\n    cout << \"test value (noncall): \" << noncallbond.cleanPrice() << endl << endl;\n    cout << \"test value (bullet): \" << bulletbond.cleanPrice() << endl << endl;\n    cout << \"test value (bullet, toPrice): \" << bulletbond.toPrice() << endl << endl;\n    \n    cout << \"\\n\\nMuni Schedules \" << endl;\n    CallabilitySchedule muniSched = createBondCallSchedule(Date(15, December, 2007),\n                                                           102.,\n                                                           Date(15, December, 2009),\n                                                           maturity\n                                                           );\n    \n    CallBond callbnd_sched(coupon,\n                           maturity,\n                           muniSched,\n                           dated, \n                           bondCalendar, \n                           settlementDays,\n                           bondDayCounter,\n                           frequency,\n                           redemption,\n                           faceAmount,\n                           accrualConvention,\n                           paymentConvention\n                           );\n\n    CallBond callbnd_sched1(coupon,\n                           maturity,\n                           Date(15, December, 2007),\n                           102.,\n                           Date(15, December, 2009),\n                           dated, \n                           bondCalendar, \n                           settlementDays,\n                           bondDayCounter,\n                           frequency,\n                           Annual,\n                           redemption,\n                           faceAmount,\n                           accrualConvention,\n                           paymentConvention\n                           );\n    \n    \n    CallabilitySchedule muniSched1 = callbnd_sched1.callability();\n    vector< boost::shared_ptr<Callability> >::size_type sz_m = muniSched1.size();\n    \n    for (int i=0; i<sz_m; i++) \n    {\n        cout << muniSched1[i]->date() << \" | \" << muniSched1[i]->price().amount() << endl;\n    }\n    \n    callbnd_sched.setPricingEngine(engine1);\n    callbnd_sched1.setPricingEngine(engine1);\n    \n    cout << \"test value: \" << callbnd_sched.toPrice() << \" | \" << callbnd_sched1.toPrice() << endl;\n    cout << \"yield to worst: \" << callbnd_sched.toYield() << \" | \" << callbnd_sched1.toYield() << endl;\n    cout << \"price from ytw: \" << callbnd_sched.toPrice(callbnd_sched.toYield()) \n    << \" | \" << callbnd_sched1.toPrice(callbnd_sched1.toYield()) << \n    endl << endl;\n    \n    //TODO: create vol/mean reversion matrix\n    cout << \"\\nHull-White (normal) pricing \" << endl;    \n    Real sig[3] = {0.0, .01, .03};\n    \n    cout << \"mean reversion = \" << reversionParameter << endl;\n    \n    for (int i=0; i<3; i++) {\n        callbnd.setEngine(acurve, reversionParameter, sig[i], false);\n        zeronc_bond.setEngine(acurve, reversionParameter, sig[i], false);\n        noncallbond.setEngine(acurve, reversionParameter, sig[i], false);\n        bulletbond.setEngine(acurve);\n        \n        cout << setprecision(3) << \"sigma: \" << io::rate(sig[i]); \n        cout << setprecision(5) << \" | value: \" << callbnd.cleanPrice() ;\n        cout << \" | nc1: \" << noncallbond.cleanPrice();\n        cout << \" bullet: \" << bulletbond.cleanPrice();\n        cout << \" zero: \" << zeronc_bond.cleanPrice() << \"/\"\n        << 100. * zeronc_bond.yield(Thirty360(Thirty360::BondBasis),\n                                    Compounded,\n                                    Semiannual,\n                                    accuracy,\n                                    maxIterations);\n        cout << endl;\n    }\n        \n    cout << \"\\nLognormal pricing \" << endl;\n    \n    Real mr = 0.0;\n    Real v[3] = {0.0, .2017, .6763};\n    \n    cout << \"mean reversion = \" << mr  \n    << endl;\n        \n    callbnd.oasEngine(acurve, mr, v[0], 0.0);\n    \n    for (int i=0; i<3; i++) {\n        noncallbond.setEngine(acurve, mr, v[i]);\n        bulletbond.setEngine(acurve);\n        \n        cout << setprecision(3) << \"vol: \" << io::rate(v[i]); \n        cout << setprecision(5) << \" | value: \" << callbnd.oasValue(0.0, v[i], mr);\n        cout << \" nc1: \" << noncallbond.cleanPrice();\n        cout << \" bullet: \" << bulletbond.cleanPrice();\n        \n    }\n    \n    Real testPx[] = {80., 85., 90., 95., 100., 100.25};\n    \n    cout << \" vol: \" << v[1] << endl << endl;\n    \n    boost::timer timer;\n    \n    for (int i=0; i<6; i++) {\n        Real oasx = callbnd.oasT<Secant>(testPx[i], v[1]);\n    \n        cout << fixed << setprecision(5) \n        << \"OAS: \" << oasx ;\n        cout << \" > value: \" << callbnd.oasValue(oasx) << endl;\n\n    }\n    Real t1 = timer.elapsed();\n    cout << fixed << setprecision(3)\n    << t1 << \" s\\n\" << endl;\n    Real t0=t1;\n\n    for (int i=0; i<6; i++) {\n        Real oasx = callbnd.oasT<Brent>(testPx[i], v[1]);\n        \n        cout << fixed << setprecision(5) \n        << \"OAS: \" << oasx ;\n        cout << \" > value: \" << callbnd.oasValue(oasx) << endl;\n        \n    }\n    \n    t1  = timer.elapsed();\n    cout << fixed << setprecision(3)\n    << t1-t0 << \" s\\n\" << endl;\n    t0=t1;\n    \n    Real testspread = 0.01543;\n    Real xvol = callbnd.oasImpliedVol(90., testspread);\n    \n    cout << \"\\nImpVol \" << xvol \n    << \" value \" << callbnd.oasValue(testspread, xvol, 0.0, true)\n    << endl ;\n    \n    \n    t1  = timer.elapsed();\n    cout << fixed << setprecision(3)\n    << t1-t0 << \" s\\n\" << endl;\n        \n    return 0;\n}\n", "meta": {"hexsha": "f182bfba704bda3f3bed346846a009dee8fe22b6", "size": 17517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/callbond_example.cpp", "max_stars_repo_name": "bondgeek/pybg", "max_stars_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T05:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-14T05:39:15.000Z", "max_issues_repo_path": "examples/callbond_example.cpp", "max_issues_repo_name": "bondgeek/pybg", "max_issues_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/callbond_example.cpp", "max_forks_repo_name": "bondgeek/pybg", "max_forks_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8004201681, "max_line_length": 119, "alphanum_fraction": 0.4773648456, "num_tokens": 3961, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5660176613289722}}
{"text": "#ifndef DISTRIBUTION_HPP\n#define DISTRIBUTION_HPP\n\n#include <assert.h>\n#include <memory>\n#include <mutex>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <iostream>\n\nnamespace jaco2_utils {\nnamespace math {\nnamespace statistic {\ntemplate<bool limit_covariance = false>\nclass Distribution {\npublic:\n    typedef std::shared_ptr<Distribution<limit_covariance>> Ptr;\n\n    typedef Eigen::VectorXd       PointType;\n    typedef Eigen::MatrixXd       MatrixType;\n    typedef Eigen::MatrixXd       EigenValueSetType;\n    typedef Eigen::MatrixXd       EigenVectorSetType;\n    typedef Eigen::VectorXcd      ComplexVectorType;\n    typedef Eigen::MatrixXcd      ComplexMatrixType;\n\n    static constexpr double sqrt_2_M_PI = std::sqrt(2 * M_PI);\n    static constexpr double lambda_ratio = 1e-2;\n\n    Distribution(std::size_t dim = 1) :\n        dim_(dim),\n        mean(PointType::Zero(dim_)),\n        correlated(MatrixType::Zero(dim_, dim_)),\n        n(1),\n        n_1(0),\n        covariance(MatrixType::Zero(dim_, dim_)),\n        inverse_covariance(MatrixType::Zero(dim_, dim_)),\n        eigen_values(EigenValueSetType::Zero(dim_, dim_)),\n        eigen_vectors(EigenVectorSetType::Zero(dim_, dim_)),\n        determinant(0.0),\n        dirty(false),\n        dirty_eigen(false)\n    {\n    }\n\n    Distribution(const Distribution &other) = default;\n    Distribution& operator=(const Distribution &other) = default;\n\n    inline void reset()\n    {\n        mean = PointType::Zero(dim_);\n        covariance = MatrixType::Zero(dim_, dim_);\n        correlated = MatrixType::Zero(dim_, dim_);\n        n = 1;\n        n_1 = 0;\n        dirty = true;\n        dirty_eigen = true;\n    }\n\n    /// Modification\n    inline void add(const PointType &_p)\n    {\n        mean = (mean * n_1 + _p) / n;\n        for(std::size_t i = 0 ; i < dim_ ; ++i) {\n            for(std::size_t j = i ; j < dim_ ; ++j) {\n                correlated(i, j) = (correlated(i, j) * n_1 + _p(i) * _p(j)) / (double) n;\n            }\n        }\n        ++n;\n        ++n_1;\n        dirty = true;\n        dirty_eigen = true;\n    }\n\n    inline Distribution& operator+=(const PointType &_p)\n    {\n        add(_p);\n        return *this;\n    }\n\n    inline Distribution& operator+=(const Distribution &other)\n    {\n        std::size_t _n = n_1 + other.n_1;\n        PointType   _mean = (mean * n_1 + other.mean * other.n_1) / (double) _n;\n        MatrixType  _corr = (correlated * n_1 + other.correlated * other.n_1) / (double) _n;\n        n   = _n + 1;\n        n_1 = _n;\n        mean = _mean;\n        correlated = _corr;\n        dirty = true;\n        dirty_eigen = true;\n        return *this;\n    }\n\n    /// Distribution properties\n    inline std::size_t getN() const\n    {\n        return n_1;\n    }\n\n    inline PointType getMean() const\n    {\n        return mean;\n    }\n\n    inline void getMean(PointType &_mean) const\n    {\n        _mean = mean;\n    }\n\n    inline MatrixType getCovariance() const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            return covariance;\n        }\n        return MatrixType::Zero(dim_, dim_);\n    }\n\n    inline void getCovariance(MatrixType &_covariance) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            _covariance = covariance;\n        } else {\n            _covariance = MatrixType::Zero();\n        }\n    }\n\n    inline MatrixType getInformationMatrix() const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            return inverse_covariance;\n        }\n        return MatrixType::Zero(dim_, dim_);\n    }\n\n    inline void getInformationMatrix(MatrixType &_inverse_covariance) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            _inverse_covariance = inverse_covariance;\n        } else {\n            _inverse_covariance = MatrixType::Zero(dim_, dim_);\n        }\n    }\n\n    inline EigenValueSetType getEigenValues(const bool _abs = false) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            if(dirty_eigen)\n                updateEigen();\n\n            if(_abs)\n                return eigen_values.cwiseAbs();\n            else\n                return eigen_values;\n        }\n        return EigenValueSetType::Zero(dim_, dim_);\n    }\n\n    inline void getEigenValues(EigenValueSetType &_eigen_values,\n                               const double _abs = false) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            if(dirty_eigen)\n                updateEigen();\n\n            if(_abs)\n                _eigen_values = eigen_values.cwiseAbs();\n            else\n                _eigen_values = eigen_values;\n        } else {\n            _eigen_values = EigenValueSetType::Zero(dim_, dim_);\n        }\n    }\n\n    inline EigenVectorSetType getEigenVectors() const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            if(dirty_eigen)\n                updateEigen();\n\n            return eigen_vectors;\n        }\n        return EigenVectorSetType::Zero();\n    }\n\n    inline void getEigenVectors(EigenVectorSetType &_eigen_vectors) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            if(dirty_eigen)\n                updateEigen();\n\n            _eigen_vectors = eigen_vectors;\n        } else {\n            _eigen_vectors = EigenVectorSetType::Zero(dim_, dim_);\n        }\n    }\n\n    /// Evaluation\n    inline double sample(const PointType &_p) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            PointType  q = _p - mean;\n            double exponent = -0.5 * double(q.transpose() * inverse_covariance * q);\n            double denominator = 1.0 / (covariance.determinant() * sqrt_2_M_PI);\n            return denominator * exp(exponent);\n        }\n        return 0.0;\n    }\n\n    inline double sample(const PointType &_p,\n                         PointType &_q) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            _q = _p - mean;\n            double exponent = -0.5 * double(_q.transpose() * inverse_covariance * _q);\n            double denominator = 1.0 / (determinant * sqrt_2_M_PI);\n            return denominator * exp(exponent);\n        }\n        return 0.0;\n    }\n\n    inline double sampleNonNormalized(const PointType &_p) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n\n            PointType  q = _p - mean;\n            double exponent = -0.5 * double(q.transpose() * inverse_covariance * q);\n            return exp(exponent);\n        }\n        return 0.0;\n    }\n\n    inline double sampleNonNormalized(const PointType &_p,\n                                      PointType &_q) const\n    {\n        if(n_1 >= 2) {\n            if(dirty)\n                update();\n            _q = _p - mean;\n            double exponent = -0.5 * double(_q.transpose() * inverse_covariance * _q);\n            return exp(exponent);\n        }\n        return 0.0;\n    }\n\nprivate:\n    const std::size_t            dim_;\n    PointType                    mean;\n    MatrixType                   correlated;\n    std::size_t                  n;\n    std::size_t                  n_1;            /// actual amount of points in distribution\n\n    mutable MatrixType           covariance;\n    mutable MatrixType           inverse_covariance;\n    mutable EigenValueSetType    eigen_values;\n    mutable EigenVectorSetType   eigen_vectors;\n    mutable double               determinant;\n\n    mutable bool                 dirty;\n    mutable bool                 dirty_eigen;\n\n    inline void update() const\n    {\n        double scale = n_1 / (double)(n_1 - 1);\n        for(std::size_t i = 0 ; i < dim_ ; ++i) {\n            for(std::size_t j = i ; j < dim_ ; ++j) {\n                covariance(i, j) = (correlated(i, j) - (mean(i) * mean(j))) * scale;\n                covariance(j, i) = covariance(i, j);\n            }\n        }\n\n        if(limit_covariance) {\n            if(dirty_eigen)\n                updateEigen();\n\n            double max_lambda = std::numeric_limits<double>::lowest();\n            for(std::size_t i = 0 ; i < dim_ ; ++i) {\n                if(eigen_values(i) > max_lambda)\n                    max_lambda = eigen_values(i);\n            }\n            MatrixType Lambda = MatrixType::Zero(dim_, dim_);\n            double l = max_lambda * lambda_ratio;\n            for(std::size_t i = 0 ; i < dim_; ++i) {\n                if(fabs(eigen_values(i)) < fabs(l)) {\n                    Lambda(i,i) = l;\n                } else {\n                    Lambda(i,i) = eigen_values(i);\n                }\n            }\n            covariance = eigen_vectors * Lambda * eigen_vectors.transpose();\n            inverse_covariance = eigen_vectors * Lambda.inverse() * eigen_vectors.transpose();\n        } else {\n            inverse_covariance = covariance.inverse();\n        }\n\n        determinant = covariance.determinant();\n        dirty = false;\n        dirty_eigen = true;\n    }\n\n    inline void updateEigen() const\n    {\n        Eigen::EigenSolver<MatrixType> solver;\n        solver.compute(covariance);\n        eigen_vectors = solver.eigenvectors().real();\n        eigen_values  = solver.eigenvalues().real();\n        dirty_eigen = false;\n    }\n};\n}\n}\n}\n\n#endif /* DISTRIBUTION_HPP */\n", "meta": {"hexsha": "0f9f9cadeb3fcf45af960e11fadaefcb439b43ba", "size": 9337, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "jaco2_utils/include/jaco2_utils/distribution.hpp", "max_stars_repo_name": "cogsys-tuebingen/jaco2_ros", "max_stars_repo_head_hexsha": "13147ae2e69a41936115a40739feb0f358af6f91", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-01T23:44:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T06:01:24.000Z", "max_issues_repo_path": "jaco2_utils/include/jaco2_utils/distribution.hpp", "max_issues_repo_name": "cogsys-tuebingen/jaco2_ros", "max_issues_repo_head_hexsha": "13147ae2e69a41936115a40739feb0f358af6f91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jaco2_utils/include/jaco2_utils/distribution.hpp", "max_forks_repo_name": "cogsys-tuebingen/jaco2_ros", "max_forks_repo_head_hexsha": "13147ae2e69a41936115a40739feb0f358af6f91", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-15T06:10:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T06:10:19.000Z", "avg_line_length": 27.7886904762, "max_line_length": 94, "alphanum_fraction": 0.5180464817, "num_tokens": 2202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5660176464101566}}
{"text": "/*!\n * @file diffusion_problem.hpp\n * @brief Contains implementation of the main object.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_DIFFUSION_PROBLEM_HPP_\n#define INCLUDE_DIFFUSION_PROBLEM_HPP_\n\n// Deal.ii\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/logstream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/affine_constraints.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n\n// STL\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n// My Headers\n#include \"matrix_coeff.hpp\"\n#include \"right_hand_side.hpp\"\n#include \"neumann_bc.hpp\"\n#include \"dirichlet_bc.hpp\"\n\n/*!\n * @namespace DiffusionProblem\n * @brief Contains implementation of the main object\n * and all functions to solve a\n * Dirichlet-Neumann problem on a unit square.\n */\nnamespace DiffusionProblem\n{\nusing namespace dealii;\n\n/*!\n * @class DiffusionProblem\n * @brief Main class to solve\n * Dirichlet-Neumann problem on a unit square.\n */\ntemplate <int dim>\nclass DiffusionProblem\n{\npublic:\n\tDiffusionProblem (unsigned int n_refine);\n\tvoid run ();\n\nprivate:\n\tvoid make_grid ();\n\tvoid setup_system ();\n\tvoid assemble_system ();\n\tvoid solve_iterative ();\n\tvoid output_results () const;\n\n\tTriangulation<dim>   \t\t\ttriangulation;\n\tFE_Q<dim>            \t\t\tfe;\n\tDoFHandler<dim>      \t\t\tdof_handler;\n\n\tAffineConstraints<double> \t\tconstraints;\n\n\tSparsityPattern      \t\t\tsparsity_pattern;\n\tSparseMatrix<double> \t\t\tsystem_matrix;\n\n\t/*!\n\t * Current solution. Needed forping.\n\t */\n\tVector<double>       \t\t\tsolution;\n\n\t/*!\n\t * Contains all parts of the right-hand side needed to\n\t * solve the linear system.\n\t */\n\tVector<double>       \t\t\tsystem_rhs;\n\n\t/*!\n\t * Number of initial grid refinements.\n\t */\n\tunsigned int n_refine;\n};\n\n\n/*!\n * Default constructor.\n */\ntemplate <int dim>\nDiffusionProblem<dim>::DiffusionProblem (unsigned int n_refine) :\n  fe (1),\n  dof_handler (triangulation),\n  n_refine (n_refine)\n{}\n\n\n/*!\n * @brief Set up the grid with a certain number of refinements.\n *\n * Generate a triangulation of \\f$[0,1]^{\\rm{dim}}\\f$ with edges/faces\n * numbered form \\f$1,\\dots,2\\rm{dim}\\f$.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::make_grid ()\n{\n\tGridGenerator::hyper_cube (triangulation, 0, 1, /* colorize */ true);\n\n\ttriangulation.refine_global (n_refine);\n\n\tstd::cout << \"Number of active cells: \"\n\t\t\t<< triangulation.n_active_cells()\n\t\t\t<< std::endl;\n}\n\n\n/*!\n * @brief Setup sparsity pattern and system matrix.\n *\n * Compute sparsity pattern and reserve memory for the sparse system matrix\n * and a number of right-hand side vectors. Also build a constraint object\n * to take care of Dirichlet boundary conditions.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::setup_system ()\n{\n\tdof_handler.distribute_dofs (fe);\n\n\tstd::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n\t\t\t<< std::endl\n\t\t\t<< \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n\t\t\t<< std::endl\n\t\t\t<< std::endl;\n\n\n\tconstraints.clear();\n\tDoFTools::make_hanging_node_constraints(dof_handler, constraints);\n\n\t/*\n\t * Set up Dirichlet boundary conditions.\n\t */\n\tconst Coefficients::DirichletBC<dim> dirichlet_bc;\n\tfor (unsigned int i = 0; i<dim; ++i)\n\t{\n\t\tVectorTools::interpolate_boundary_values(dof_handler,\n\t\t\t\t\t\t\t\t\t\t\t\t\t/*boundary id*/ 2*i, // only even boundary id\n\t\t\t\t\t\t\t\t\t\t\t\t\tdirichlet_bc,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconstraints);\n\t}\n\n\tconstraints.close();\n\n\tDynamicSparsityPattern dsp(dof_handler.n_dofs());\n\tDoFTools::make_sparsity_pattern (dof_handler,\n\t\t\t\t\t\t\t\t\tdsp,\n\t\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t\t\t/*keep_constrained_dofs =*/ true); // forping this is essential to be true\n\n\tsparsity_pattern.copy_from(dsp);\n\n\tsystem_matrix.reinit (sparsity_pattern);\n\n\tsolution.reinit (dof_handler.n_dofs());\n\tsystem_rhs.reinit (dof_handler.n_dofs());\n}\n\n\n/*!\n * @brief Assemble the system matrix and the static right hand side.\n *\n * Assembly routine to build the time-independent (static)part.\n * Neumann boundary conditions will be put on edges/faces\n * with odd number. Constraints are not applied here yet.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::assemble_system ()\n{\n\tQGauss<dim>  quadrature_formula(fe.degree + 1);\n\tQGauss<dim - 1> face_quadrature_formula(fe.degree + 1);\n\n\tFEValues<dim> \tfe_values (fe, quadrature_formula,\n\t\t\t\t\t\t\t\tupdate_values    |  update_gradients |\n\t\t\t\t\t\t\t\tupdate_quadrature_points  |  update_JxW_values);\n\n\tFEFaceValues<dim> \tfe_face_values(fe,\n\t\t\t\t\t\t\t\t\t\tface_quadrature_formula,\n\t\t\t\t\t\t\t\t\t\tupdate_values | update_quadrature_points |\n\t\t\t\t\t\t\t\t\t\tupdate_normal_vectors |\n\t\t\t\t\t\t\t\t\t\tupdate_JxW_values);\n\n\tconst unsigned int   \tdofs_per_cell = fe.dofs_per_cell;\n\tconst unsigned int   \tn_q_points    = quadrature_formula.size();\n\tconst unsigned int \tn_face_q_points = face_quadrature_formula.size();\n\n\tFullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\tVector<double>       cell_rhs (dofs_per_cell);\n\n\tstd::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n\t/*\n\t * Matrix coefficient and vector to store the values.\n\t */\n\tconst Coefficients::MatrixCoeff<dim> \t\tmatrix_coeff;\n\tstd::vector<Tensor<2,dim>> \tmatrix_coeff_values(n_q_points);\n\n\t/*\n\t * Right hand side and vector to store the values.\n\t */\n\tconst Coefficients::RightHandSide<dim> \tright_hand_side;\n\tstd::vector<double>      \trhs_values(n_q_points);\n\n\t/*\n\t * Neumann BCs and vector to store the values.\n\t */\n\tconst Coefficients::NeumannBC<dim> \tneumann_bc;\n\tstd::vector<double>  \tneumann_values(n_face_q_points);\n\n\t/*\n\t * Integration over cells.\n\t */\n\tfor (const auto &cell: dof_handler.active_cell_iterators())\n\t{\n\t\tcell_matrix = 0;\n\t\tcell_rhs = 0;\n\n\t\tfe_values.reinit (cell);\n\n\t\t// Now actually fill with values.\n\t\tmatrix_coeff.value_list(fe_values.get_quadrature_points (),\n\t\t\t\t\t\t  \t  \t  matrix_coeff_values);\n\t\tright_hand_side.value_list(fe_values.get_quadrature_points(),\n\t\t\t\t\t\t\t\t\t   rhs_values);\n\n\t\tfor (unsigned int q_index=0; q_index<n_q_points; ++q_index)\n\t\t{\n\t\t\tfor (unsigned int i=0; i<dofs_per_cell; ++i)\n\t\t\t{\n\t\t\t\tfor (unsigned int j=0; j<dofs_per_cell; ++j)\n\t\t\t\t{\n\n\t\t\t\t\tcell_matrix(i,j) += fe_values.shape_grad(i,q_index) *\n\t\t\t\t\t\t\t\t\t\t matrix_coeff_values[q_index] *\n\t\t\t\t\t\t\t\t\t\t fe_values.shape_grad(j,q_index) *\n\t\t\t\t\t\t\t\t\t\t fe_values.JxW(q_index);\n\t\t\t\t} // end ++j\n\n\t\t\t\tcell_rhs(i) += fe_values.shape_value(i,q_index) *\n\t\t\t\t\t\t\t\t   rhs_values[q_index] *\n\t\t\t\t\t\t\t\t   fe_values.JxW(q_index);\n\t\t\t} // end ++i\n\t\t} // end ++q_index\n\n\t\t/*\n\t\t * Boundary integral for Neumann values for odd boundary_id.\n\t\t */\n\t\tfor (unsigned int face_number = 0;\n\t\t\t face_number < GeometryInfo<dim>::faces_per_cell;\n\t\t\t ++face_number)\n\t\t{\n\t\t\tif (cell->face(face_number)->at_boundary() &&\n\t\t\t\t\t(\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 1) ||\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 3) ||\n\t\t\t\t\t\t(cell->face(face_number)->boundary_id() == 5)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tfe_face_values.reinit(cell, face_number);\n\n\t\t\t\t/*\n\t\t\t\t * Fill in values at this particular face.\n\t\t\t\t */\n\t\t\t\tneumann_bc.value_list(fe_face_values.get_quadrature_points(),\n\t\t\t\t\t\t\t\t\t\t   neumann_values);\n\n\t\t\t\tfor (unsigned int q_face_point = 0; q_face_point < n_face_q_points; ++q_face_point)\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tcell_rhs(i) += neumann_values[q_face_point] // g(x_q)\n\t\t\t\t\t\t\t\t\t\t* fe_face_values.shape_value(i, q_face_point) // phi_i(x_q)\n\t\t\t\t\t\t\t\t\t\t* fe_face_values.JxW(q_face_point); // dS\n\t\t\t\t\t} // end ++i\n\t\t\t\t} // end ++q_face_point\n\t\t\t} // end if\n\t\t} // end ++face_number\n\n\n\t\t// get global indices\n\t\tcell->get_dof_indices (local_dof_indices);\n\t\t/*\n\t\t * Now add the cell matrix and rhs to the right spots\n\t\t * in the global matrix and global rhs. Constraints will\n\t\t * be taken care of later.\n\t\t */\n\t\tfor (unsigned int i = 0; i < dofs_per_cell; ++i)\n\t\t{\n\t\t\tfor (unsigned int j = 0; j < dofs_per_cell; ++j)\n\t\t\t{\n\t\t\t\tsystem_matrix.add(local_dof_indices[i],\n\t\t\t\t\t\t\tlocal_dof_indices[j],\n\t\t\t\t\t\t\tcell_matrix(i, j));\n\t\t\t}\n\t\t\tsystem_rhs(local_dof_indices[i]) += cell_rhs(i);\n\t\t}\n\t} // end ++cell\n}\n\n\n/*!\n * @brief Iterative solver.\n *\n * CG-based solver with SSOR-preconditioning.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::solve_iterative ()\n{\n\tSolverControl           solver_control (1000, 1e-12);\n\tSolverCG<>              solver (solver_control);\n\n\tPreconditionSSOR<> preconditioner;\n\tpreconditioner.initialize(system_matrix, 1.2);\n\n\tsolver.solve (system_matrix,\n\t\t\t\tsolution,\n\t\t\t\tsystem_rhs,\n\t\t\t\tpreconditioner);\n\n\tconstraints.distribute (solution);\n\n\tstd::cout << \"   \" << solver_control.last_step()\n\t\t\t<< \" CG iterations needed to obtain convergence.\"\n\t\t\t<< std::endl;\n}\n\n\n/*!\n * @brief Write results to disk.\n *\n * Write results to disk in vtu-format.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::output_results () const\n{\n\tDataOut<dim> data_out;\n\tdata_out.attach_dof_handler (dof_handler);\n\tdata_out.add_data_vector (solution, \"solution\");\n\tdata_out.build_patches ();\n\n\tstd::string filename = (dim == 2 ?\n\t\t\t\t\t\t\t\t\"solution-std_2d\" :\n\t\t\t\t\t\t\t\t\"solution-std_3d\" );\n\tfilename += \"_refinements-\" + Utilities::int_to_string(n_refine, 1)\n\t\t\t\t+ \".vtu\";\n\n\tstd::ofstream output (filename.c_str());\n\tdata_out.write_vtu (output);\n}\n\n\n/*!\n * @brief Run function of the object.\n *\n * Run the computation after object is built. Implements theping loop.\n */\ntemplate <int dim>\nvoid DiffusionProblem<dim>::run ()\n{\n\tstd::cout << std::endl\n\t\t\t\t<< \"===========================================\" << std::endl;\n\tstd::cout << \"Solving problem in \" << dim << \" space dimensions.\" << std::endl;\n\n\tmake_grid ();\n\n\tsetup_system ();\n\n\tassemble_system ();\n\n\t// Now solve\n\tconstraints.condense(system_matrix, system_rhs);\n\tsolve_iterative ();\n\n\toutput_results ();\n\n\tstd::cout << std::endl\n\t\t\t<< \"===========================================\" << std::endl;\n}\n\n} // end namespace DiffusionProblem\n\n\n#endif /* INCLUDE_DIFFUSION_PROBLEM_HPP_ */\n", "meta": {"hexsha": "6d84e205d9de635ff3bbed9cc856cf0d0eea7dd2", "size": 10373, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/diffusion_problem.hpp", "max_stars_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_stars_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/diffusion_problem.hpp", "max_issues_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_issues_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/diffusion_problem.hpp", "max_forks_repo_name": "konsim83/deal.ii-9.1.1_SS19_demo_elliptic_multiscale_fem", "max_forks_repo_head_hexsha": "cde9eabcbdee1271f4d36ce67d9168b65251ad32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-19T15:42:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-19T15:42:43.000Z", "avg_line_length": 25.177184466, "max_line_length": 87, "alphanum_fraction": 0.6786850477, "num_tokens": 2752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860733563595}}
{"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//// Interpolation from panel to sub-panel\n// Interpolate linearly surface singularities from panel vertices to sub-panels\n//\n// Inputs:\n// - idP: current panel index\n// - bPan: body panels (structure)\n// - mu0, mu1, mu2, mu3: doublet at interpolation points (vertices)\n// - tau0, tau1, tau2, tau3: sources at interpolation points (vertices)\n//\n// Output:\n// - spis: interpolated singularities (row = sub-panel number; col 0 = doublet, col 1 = source)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"interp_sp.h\"\n#include \"interp.h\"\n\nusing namespace Eigen;\n\nMatrixXd interp_sp(int idP, Network &bPan, Subpanel &sp,\n                   double mu0, double mu1, double mu2, double mu3,\n                   double tau0, double tau1, double tau2, double tau3) {\n\n    // Temporary variables\n    double x0, x1, x2, x3, y0, y1, y2, y3, z0, z1, z2, z3; // vertices coordinates\n    double a, b; // interpolation parameters\n    double X, Y, Z; // sub-panel center\n    MatrixXd spis; // Interpolated singularities\n    spis.resize(sp.NS, 2);\n\n    // Copy vertices ton local variables\n    x0 = bPan.v0(idP,0);\n    x1 = bPan.v1(idP,0);\n    x2 = bPan.v2(idP,0);\n    x3 = bPan.v3(idP,0);\n    y0 = bPan.v0(idP,1);\n    y1 = bPan.v1(idP,1);\n    y2 = bPan.v2(idP,1);\n    y3 = bPan.v3(idP,1);\n    z0 = bPan.v0(idP,2);\n    z1 = bPan.v1(idP,2);\n    z2 = bPan.v2(idP,2);\n    z3 = bPan.v3(idP,2);\n\n    // Computation of sub-panel centers in global axes\n    int idx = 0, j = 0;\n    for (int jj = 0; jj < sp.NSs; jj++) {\n        int i = 0;\n        for (int ii = 0; ii < sp.NSs; ii++) {\n            // Compute weight factors\n            a = (double) (i+1)/sp.NSs/2;\n            b = (double) (j+1)/sp.NSs/2;\n            // Compute center point\n            X = (1-b)*((1-a)*x0 + a*x1) + b*(a*x2 + (1-a)*x3);\n            Y = (1-b)*((1-a)*y0 + a*y1) + b*(a*y2 + (1-a)*y3);\n            Z = (1-b)*((1-a)*z0 + a*z1) + b*(a*z2 + (1-a)*z3);\n\n            // Interpolate singularities\n            spis(idx,0) = interp(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3,\n                                 mu0, mu1, mu2, mu3,\n                                 X, Y, Z);\n            spis(idx,1) = interp(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3,\n                                 tau0, tau1, tau2, tau3,\n                                 X, Y, Z);\n            idx++;\n            i += 2;\n        }\n        j += 2;\n    }\n    return spis;\n}", "meta": {"hexsha": "150501db0bb51c2557945087bdc1bb9fdf66aa7b", "size": 3038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interp_sp.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/interp_sp.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interp_sp.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": 33.7555555556, "max_line_length": 95, "alphanum_fraction": 0.5589203423, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.5659860676384134}}
{"text": "//\n//  main.cpp\n//  g2obatest\n//\n//  Created by Seung-Chan Kim on 1/11/17.\n//  based on https://github.com/gaoxiang12/g2o_ba_example\n//  http://nimbro.net/OP/Doc/html/Localization_8hpp_source.html\n\n#include <iostream>\n\n//#include <Eigen/Core>\n//#include <Eigen/StdVector>\n\n// opencv\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n\n// g2o\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/robust_kernel.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/slam3d/se3quat.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\nusing namespace std;\nusing namespace g2o;\nusing namespace cv;\n\nint     findCorrespondingPoints( const cv::Mat& img1, const cv::Mat& img2, vector<cv::Point2f>& points1, vector<cv::Point2f>& points2 );\n\ndouble cx = 325.5;\ndouble cy = 253.5;\ndouble fx = 518.0;\ndouble fy = 519.0;\n\nint main(int argc, const char * argv[]) {\n    \n    cv::Mat img1;\n    cv::Mat img2;\n    \n    if (argc != 3)\n    {\n        img1 =cv::imread(\"../../../data/set1/1.png\");\n        img2 =cv::imread(\"../../../data/set1/2.png\");\n    }\n    else\n    {\n        img1 = cv::imread( argv[1] );\n        img2 = cv::imread( argv[2] );\n    }\n    cout << \"loaded \" << img1.size().width << \" X \" << img1.size().height << \" X \" << img1.channels() << endl;\n    \n    \n    vector<cv::Point2f> pts1, pts2;\n    if ( findCorrespondingPoints( img1, img2, pts1, pts2 ) == false )\n    {\n        cout<<\"too few feature matches！ # of matches = \"<< pts1.size() << endl;\n        return 0;\n    }\n    cout<<\"# of matches = \"<< pts1.size() << endl;\n    \n    g2o::SparseOptimizer    optimizer;\n    \n#if 1\n    // create the linear solver\n    g2o::BlockSolver_6_3::LinearSolverType* linearSolver = new  g2o::LinearSolverCholmod<g2o::BlockSolver_6_3::PoseMatrixType> ();\n    \n    // create the block solver on the top of the linear solver\n    // solver for BA/3D SLAM\n    // typedef BlockSolver< BlockSolverTraits<6, 3> > BlockSolver_6_3;\n    g2o::BlockSolver_6_3* block_solver = new g2o::BlockSolver_6_3( linearSolver );\n    \n#else\n    // create the linear solver\n    BlockSolverX::LinearSolverType * linearSolver;\n    linearSolver = new LinearSolverCSparse<BlockSolverX::PoseMatrixType>();\n    \n    // create the block solver on the top of the linear solver\n    // variable size solver\n    // typedef BlockSolver< BlockSolverTraits<Eigen::Dynamic, Eigen::Dynamic> > BlockSolverX;\n   \n    BlockSolverX* block_solver;\n    block_solver = new BlockSolverX(linearSolver);\n\n#endif\n    \n    //create the algorithm to carry out the optimization\n    g2o::OptimizationAlgorithmLevenberg* algorithm = new g2o::OptimizationAlgorithmLevenberg( block_solver );\n    \n    optimizer.setAlgorithm( algorithm );\n    \n    \n    for ( int i=0; i<2; i++ )\n    {\n        // SE3 Vertex parameterized internally with a transformation matrix and externally with its exponential map\n        g2o::VertexSE3Expmap* v = new g2o::VertexSE3Expmap();\n        v->setId(i);\n        if ( i == 0)\n            v->setFixed( true );\n        \n        v->setEstimate( g2o::SE3Quat() );\n        optimizer.addVertex( v );\n    }\n    cout << g2o::SE3Quat()  << endl;\n    for ( size_t i=0; i<pts1.size(); i++ )\n    {\n        g2o::VertexSBAPointXYZ* v = new g2o::VertexSBAPointXYZ();\n        v->setId( 2 + i );\n        \n        double z = 1;\n        double x = ( pts1[i].x - cx ) * z / fx;\n        double y = ( pts1[i].y - cy ) * z / fy;\n        v->setMarginalized(true);\n        v->setEstimate( Eigen::Vector3d(x,y,z) );\n        optimizer.addVertex( v );\n    }\n    \n    g2o::CameraParameters* camera = new g2o::CameraParameters( fx, Eigen::Vector2d(cx, cy), 0 );\n    camera->setId(0);\n    optimizer.addParameter( camera );\n    \n    // First frame\n    vector<g2o::EdgeProjectXYZ2UV*> edges;\n    for ( size_t i=0; i<pts1.size(); i++ )\n    {\n        g2o::EdgeProjectXYZ2UV*  edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setVertex( 0, dynamic_cast<g2o::VertexSBAPointXYZ*>   (optimizer.vertex(i+2)) );\n        edge->setVertex( 1, dynamic_cast<g2o::VertexSE3Expmap*>     (optimizer.vertex(0)) );\n        edge->setMeasurement( Eigen::Vector2d(pts1[i].x, pts1[i].y ) );\n        edge->setInformation( Eigen::Matrix2d::Identity() );\n        edge->setParameterId(0, 0);\n        \n        edge->setRobustKernel( new g2o::RobustKernelHuber() );\n        optimizer.addEdge( edge );\n        edges.push_back(edge);\n    }\n\n    // Second frame\n    for ( size_t i=0; i<pts2.size(); i++ )\n    {\n        g2o::EdgeProjectXYZ2UV*  edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setVertex( 0, dynamic_cast<g2o::VertexSBAPointXYZ*>   (optimizer.vertex(i+2)) );\n        edge->setVertex( 1, dynamic_cast<g2o::VertexSE3Expmap*>     (optimizer.vertex(1)) );\n        edge->setMeasurement( Eigen::Vector2d(pts2[i].x, pts2[i].y ) );\n        edge->setInformation( Eigen::Matrix2d::Identity() );\n        edge->setParameterId(0,0);\n        \n        edge->setRobustKernel( new g2o::RobustKernelHuber() );\n        optimizer.addEdge( edge );\n        edges.push_back(edge);\n    }\n    \n    optimizer.setVerbose(true);\n    optimizer.initializeOptimization();\n    optimizer.optimize(10);\n    \n    cout << \"Optimization done..\" << endl;\n    \n    g2o::VertexSE3Expmap* v0 = dynamic_cast<g2o::VertexSE3Expmap*>( optimizer.vertex(0) );\n    Eigen::Isometry3d pose0 = v0->estimate();\n    cout<<\"Pose (fixed) =\"<<endl<<pose0.matrix()<<endl;\n    \n    g2o::VertexSE3Expmap* v = dynamic_cast<g2o::VertexSE3Expmap*>( optimizer.vertex(1) );\n    Eigen::Isometry3d pose = v->estimate();\n    cout<<\"Pose=\"<<endl<<pose.matrix()<<endl;\n    \n    if(0)\n    for ( size_t i=0; i<pts1.size(); i++ )\n    {\n        g2o::VertexSBAPointXYZ* v = dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(i+2));\n        cout<<\"vertex id \"<<i+2<<\", pos = \";\n        Eigen::Vector3d pos = v->estimate();\n        cout<<pos(0)<<\",\"<<pos(1)<<\",\"<<pos(2)<<endl;\n    }\n    \n    int inliers = 0;\n    for ( auto e:edges )\n    {\n        e->computeError();\n        \n        if ( e->chi2() > 1 )\n        {\n            cout<<\"error = \"<<e->chi2()<<endl;\n        }\n        else\n        {\n            inliers++;\n        }\n    }\n    \n    cout<<\"inliers in total points: \"<<inliers<<\"/\"<<pts1.size()+pts2.size()<<endl;\n    optimizer.save(\"ba.g2o\");\n    \n    imshow(\"img1\", img1);\n    imshow(\"img2\", img2);\n    cv::waitKey(-1);\n    \n    std::cout << \"Done !\\n\";\n    \n    // TODO\n    // : compute camera poses via epipolar geometry and triangulate the points.\n    // : compare the results.\n    return 0;\n}\n\n\nint     findCorrespondingPoints( const cv::Mat& img1, const cv::Mat& img2, vector<cv::Point2f>& points1, vector<cv::Point2f>& points2 )\n{\n    cv::Ptr<cv::FeatureDetector>\t\tdetector;\n    cv::Ptr<cv::DescriptorExtractor>\textractor;\n    \n    detector = cv::ORB::create();\n    extractor = cv::ORB::create();\n    \n    vector<cv::KeyPoint> kp1, kp2;\n    cv::Mat desc1, desc2;\n    \n    detector->detect(img1, kp1);\n    detector->detect(img2, kp2);\n    \n    extractor->compute(img1,kp1,desc1);\n    extractor->compute(img2,kp2,desc2);\n    \n    //cv::ORB orb;\n    \n    cout<<\"# of kp= \"<<kp1.size()<<\" & \"<<kp2.size()<<endl;\n    \n    cv::Ptr<cv::DescriptorMatcher>  matcher = cv::DescriptorMatcher::create( \"BruteForce-Hamming\");\n    \n    double knn_match_ratio=0.8;\n    vector< vector<cv::DMatch> > matches_knn;\n    matcher->knnMatch( desc1, desc2, matches_knn, 2 );\n    vector< cv::DMatch > matches;\n    for ( size_t i=0; i<matches_knn.size(); i++ )\n    {\n        if (matches_knn[i][0].distance < knn_match_ratio * matches_knn[i][1].distance )\n            matches.push_back( matches_knn[i][0] );\n    }\n    \n    if (matches.size() <= 20)\n        return false;\n    \n    for ( auto m:matches )\n    {\n        points1.push_back( kp1[m.queryIdx].pt );\n        points2.push_back( kp2[m.trainIdx].pt );\n    }\n    \n    \n    \n    return true;\n}\n\n\n\n\n", "meta": {"hexsha": "db1a22805bbb36b6afe86fc9ed5f50560245fbd5", "size": 8059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Optimization/g2o/g2obatest/g2obatest/main.cpp", "max_stars_repo_name": "faipaz/Algorithms", "max_stars_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-08-19T14:00:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T09:11:48.000Z", "max_issues_repo_path": "Optimization/g2o/g2obatest/g2obatest/main.cpp", "max_issues_repo_name": "faipaz/Algorithms", "max_issues_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T19:20:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T19:20:47.000Z", "max_forks_repo_path": "Optimization/g2o/g2obatest/g2obatest/main.cpp", "max_forks_repo_name": "faipaz/Algorithms", "max_forks_repo_head_hexsha": "738991d5e4372ef6ba8e489ea867d92ea406b729", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-06-21T15:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-09T10:55:36.000Z", "avg_line_length": 30.7595419847, "max_line_length": 136, "alphanum_fraction": 0.6020598089, "num_tokens": 2416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5659860626842093}}
{"text": "#pragma once\n\n#ifdef _MSC_VER\n#pragma warning( push )\n#pragma warning( disable : 4996)\n#endif\n#include <boost/numeric/ublas/blas.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#ifdef _MSC_VER\n#pragma warning( pop ) \n#endif\n\nnamespace dungeng\n{\n    namespace blas = ::boost::numeric::ublas;\n\n    /*template <size_t N>\n    using vec = blas::bounded_vector<double, N>;*/\n\n    template <size_t N>\n    class vec : public blas::bounded_vector<double, N>\n    {\n    private:\n        using base = blas::bounded_vector<double, N>;\n        using ArrayOfDouble = const double[N];\n\n    public:\n        using base::base;\n\n        constexpr vec(ArrayOfDouble& src)\n            : base(Initer(src))\n        {\n        }\n\n    private:\n        constexpr static base Initer(ArrayOfDouble& src)\n        {\n            base result;\n            std::copy(std::cbegin(src), std::cend(src), std::begin(result));\n            return result;\n        }\n    };\n\n    /*template <size_t M, size_t N>\n    using mat = blas::bounded_matrix<double, M, N>;*/\n\n    template <size_t M, size_t N>\n    class mat : public blas::bounded_matrix<double, M, N>\n    {\n\tprivate:\n\t\tusing base = blas::bounded_matrix<double, M, N>;\n        using ArrayOfDouble = const double[N];\n        using ArrayWithArrayOfDouble = const ArrayOfDouble[M];\n\n    public:\n        using base::base;\n        \n        constexpr mat(ArrayWithArrayOfDouble& src)\n            : base(Initer(src))\n        {\n        }\n\n    private:\n        constexpr static base Initer(ArrayWithArrayOfDouble& src)\n        {\n            base result;\n            for (size_t i = 0; i < std::size(src); ++i)\n                for (size_t j = 0; j < std::size(src[i]); ++j)\n                    result(i, j) = src[i][j];\n            return result;\n        }\n    };\n    \n    using vec2 = vec<2>;\n    using vec3 = vec<3>;\n\n    using mat33 = mat<3, 3>;\n\n    mat33 rotate_matrix_ccw(double angle);\n    mat33 translate_matrix(const vec3& xy);\n    mat33 translate_matrix(const vec2& xy);\n    mat33 scale_matrix(const vec3& xy);\n    mat33 scale_matrix(const vec2& xy);\n}", "meta": {"hexsha": "4b5d47b9ff32b80a467dc5c81a4c837b2e13afbb", "size": 2105, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dungeon_engine/include/dungeng/math.hpp", "max_stars_repo_name": "SergeyZhuravlev/DungeonEngine", "max_stars_repo_head_hexsha": "d5774a01de7222731681cf57d69f4e8cf9d6afac", "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": "dungeon_engine/include/dungeng/math.hpp", "max_issues_repo_name": "SergeyZhuravlev/DungeonEngine", "max_issues_repo_head_hexsha": "d5774a01de7222731681cf57d69f4e8cf9d6afac", "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": "dungeon_engine/include/dungeng/math.hpp", "max_forks_repo_name": "SergeyZhuravlev/DungeonEngine", "max_forks_repo_head_hexsha": "d5774a01de7222731681cf57d69f4e8cf9d6afac", "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.7647058824, "max_line_length": 76, "alphanum_fraction": 0.5843230404, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5659763312918329}}
{"text": "\r\n#include <entity.hh>\r\n#include <vector.hh>\r\n#include <pow.hh>\r\n#include <linear_system.hh>\r\n#include <Utils/statistics.hh>\r\n#include \"PolygonTriangularization/poly_triang.hh\"\r\n#include \"Utils/error_handling.hh\"\r\n\r\n#define JACOBI\r\n#ifdef JACOBI\r\n#pragma warning( push )\r\n#pragma warning( disable : 4714 )\r\n#include <Eigen/Dense>\r\n#endif\r\n\r\n#include <vector>\r\n\r\nnamespace {\r\nbool check_par(double _t) { return _t >= 0 && _t <= 1; }\r\nbool check_par(double _u, double _v)\r\n{\r\n  return _u >= 0 && _v >= 0 && (1 - _u - _v) >= 0;\r\n}\r\n}//namespace\r\n\r\nnamespace Gen\r\n{\r\ntemplate <class TypeT, size_t DimT, bool Inf1T, bool Inf2T>\r\nbool closest_point(const Segment<TypeT, DimT>& _seg_a, const Segment<TypeT, DimT>& _seg_b,\r\n                   Geo::Vector<TypeT, DimT>* _clsst_pt, double _t[2], double * _dist_sq)\r\n{\r\n  Geo::Vector<TypeT, DimT> a[2] = {\r\n    _seg_a[1] - _seg_a[0],\r\n    _seg_b[0] - _seg_b[1] };\r\n  Eigen::MatrixXd A(a[0].size(), std::size(a));\r\n  Eigen::VectorXd B(a[0].size());\r\n  for (int i = 0; i < a[0].size(); ++i)\r\n  {\r\n    B(i) = _seg_b[0][i] - _seg_a[0][i];\r\n    for (int j = 0; j < std::size(a); ++j)\r\n      A(i, j) = a[j][i];\r\n  }\r\n  Eigen::VectorXd  res = (A.transpose() * A).ldlt().solve(A.transpose() * B);\r\n  if (constexpr(!Inf1T))\r\n  {\r\n    if (!check_par(res(0)))\r\n      return false;\r\n  }\r\n  if (constexpr(!Inf2T))\r\n  {\r\n    if (!check_par(res(1)))\r\n      return false;\r\n  }\r\n  auto pt_a = evaluate(_seg_a, res(0));\r\n  auto pt_b = evaluate(_seg_b, res(1));\r\n  if (_clsst_pt != nullptr)\r\n    *_clsst_pt = (pt_a + pt_b) / 2.;\r\n  if (_dist_sq != nullptr)\r\n    *_dist_sq = Geo::length_square(pt_a - pt_b);\r\n  if (_t != nullptr)\r\n  {\r\n    _t[0] = res(0);\r\n    _t[1] = res(1);\r\n  }\r\n  return true;\r\n}\r\n\r\n#define INST_CLOSEST_POINT_SEG_SEG(TYPE, NUM, INF)                        \\\r\ntemplate bool closest_point<TYPE, NUM, INF, INF>(                              \\\r\n  const Segment<TYPE, NUM>& _seg_a, const Segment<TYPE, NUM>& _seg_b,\\\r\n  Geo::Vector<TYPE, NUM>* _clsst_pt, double _t[2], double * _dist);\r\n\r\nINST_CLOSEST_POINT_SEG_SEG(double, 2, false)\r\nINST_CLOSEST_POINT_SEG_SEG(double, 2, true)\r\n\r\nINST_CLOSEST_POINT_SEG_SEG(double, 3, false)\r\nINST_CLOSEST_POINT_SEG_SEG(double, 3, true)\r\n\r\n} // namespace Gen\r\n\r\nnamespace Geo {\r\n\r\nPoint evaluate(const Segment& _seg, double _t)\r\n{\r\n  return (1 - _t) * _seg[0] + _t * _seg[1];\r\n}\r\n\r\nPoint evaluate(const Triangle& _tri, double _u, double _v)\r\n{\r\n  return (1 - _u - _v) * _tri[0] +_u * _tri[1] + _v * _tri[2];\r\n}\r\n\r\nnamespace {\r\nstruct PolygonalFace : public IPolygonalFace\r\n{\r\n  virtual bool triangle(size_t _idx, Triangle& _tri) const\r\n  {\r\n    if (_idx > tris_.size())\r\n      return false;\r\n    _tri = tris_[_idx];\r\n    return true;\r\n  }\r\n  virtual size_t triangle_number() const { return tris_.size(); }\r\n\r\n  virtual Point normal() const;\r\n\r\nprotected:\r\n  virtual size_t make_new_loop() override\r\n  {\r\n    ptss_.emplace_back();\r\n    return ptss_.size() - 1;\r\n  }\r\n  virtual void add_point(const Point& _pt, size_t _loop_num) override\r\n  {\r\n    ptss_[_loop_num].push_back(_pt);\r\n  }\r\n  virtual void compute() override;\r\n\r\nprivate:\r\n  std::vector<Triangle> tris_;\r\n  std::vector<std::vector<Point>> ptss_;\r\n};\r\n\r\nvoid PolygonalFace::compute()\r\n{\r\n  if (ptss_.empty())\r\n    return;\r\n  auto ptg = IPolygonTriangulation::make();\r\n  for (auto& pts : ptss_)\r\n  {\r\n    THROW_IF(pts.size() < 3, \"Loop withless than 3 points.\");\r\n    ptg->add(pts);\r\n  }\r\n  const auto& tris = ptg->triangles();\r\n  const auto& poly = ptg->polygon();\r\n  for (const auto& tri : tris)\r\n  {\r\n    tris_.push_back({\r\n      poly[tri[0]],\r\n      poly[tri[1]],\r\n      poly[tri[2]] });\r\n  }\r\n}\r\n\r\nPoint PolygonalFace::normal() const\r\n{\r\n  Point normal{ 0,0,0 };\r\n  for (auto& tri : tris_)\r\n    normal += (tri[1] - tri[0]) % (tri[2] - tri[0]);\r\n  auto len = length(normal);\r\n  if (len > 0)\r\n    normal /= len;\r\n  return normal;\r\n}\r\n\r\n}//namespace\r\n\r\nstd::shared_ptr<IPolygonalFace> IPolygonalFace::make()\r\n{\r\n  return std::make_shared<PolygonalFace>();\r\n}\r\n\r\n// Finds u and v such that the distance between pt and\r\n// _tri[0] * u + _tri[1] * v + _tri[2] * (1 - u - v)\r\n// is minimal. u and v must be > 0 and u + v < 1.\r\n// If the constraints are not satisfied, returns false.\r\nbool closest_point(const Triangle& _tri, const Point& _pt,\r\n  Point* _clsst_pt, double * _dist_sq)\r\n{\r\n  double A[2][2], B[2];\r\n  auto v0 = _tri[0] - _tri[2];\r\n  auto v1 = _tri[1] - _tri[2];\r\n  auto dp = _pt - _tri[2];\r\n\r\n  A[0][0] = length_square(v0);\r\n  A[1][1] = length_square(v1);\r\n  A[0][1] = A[1][0] = v0 * v1;\r\n\r\n  B[0] = dp * v0;\r\n  B[1] = dp * v1;\r\n\r\n  double uv[2];\r\n  if (!solve_2x2(A, uv, B))\r\n    return false;\r\n  if (!check_par(uv[0], uv[1]))\r\n    return false;\r\n  auto clsst_pt = _tri[2] + uv[0] * (_tri[0] - _tri[2]) + uv[1] * (_tri[1] - _tri[2]);\r\n  if (_clsst_pt != nullptr)\r\n    *_clsst_pt = clsst_pt;\r\n  if (_dist_sq != nullptr)\r\n    *_dist_sq = length(clsst_pt - _pt);\r\n  return true;\r\n}\r\n\r\nbool closest_point(const IPolygonalFace& _face, const Point& _pt,\r\n  Point* _clsst_pt, double * _dist_sq)\r\n{\r\n  Utils::StatisticsT<double> dist_stats;\r\n  Triangle tri;\r\n  Point clsst_pt;\r\n  const auto tri_nmbr = _face.triangle_number();\r\n  for (size_t i = 0; i < tri_nmbr; ++i)\r\n  {\r\n    if (!_face.triangle(i, tri))\r\n      continue;\r\n    double dist_sq = 0;\r\n    if (!closest_point(tri, _pt, &clsst_pt, &dist_sq))\r\n      continue;\r\n    if ((dist_stats.add(dist_sq) & dist_stats.Smallest) && _clsst_pt != nullptr)\r\n      *_clsst_pt = clsst_pt;\r\n  }\r\n  if (dist_stats.count() == 0)\r\n    return false;\r\n  if (_dist_sq != nullptr)\r\n    *_dist_sq = dist_stats.min();\r\n  return true;\r\n}\r\n\r\nbool closest_point(const Triangle& _tri, const Segment& _seg,\r\n  Point* _clsst_pt, double * _t, double * _dist_sq)\r\n{\r\n  const auto a = _seg[0] - _tri[0];\r\n  const Point coeff[] =\r\n  { _tri[1] - _tri[0], _tri[2] - _tri[0], _seg[0] - _seg[1] };\r\n\r\n  Eigen::MatrixXd A(3, 3);\r\n  Eigen::VectorXd B(3);\r\n  for (int i = 0; i < 3; ++i)\r\n  {\r\n    for (int j = 0; j < 3; ++j)\r\n      A(j, i) = coeff[i][j];\r\n    B(i) = a[i];\r\n  }\r\n#if 1\r\n  Eigen::VectorXd  uvt = (A.transpose() * A).ldlt().solve(A.transpose() * B);\r\n#else\r\n  const auto& jsvd =\r\n    A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\r\n  Eigen::VectorXd uvt = jsvd.solve(B);\r\n#endif\r\n\r\n  if (!check_par(uvt[0], uvt[1]) || !check_par(uvt[2]))\r\n    return false;\r\n  auto pt_seg = evaluate(_seg, uvt[2]);\r\n  auto pt_tri = evaluate(_tri, uvt[0], uvt[1]);\r\n  if (_clsst_pt!= nullptr)\r\n    *_clsst_pt = (pt_seg + pt_tri) / 2.;\r\n  if (_t != nullptr)\r\n    *_t = uvt[2];\r\n  if (_dist_sq != nullptr)\r\n    *_dist_sq = length_square(pt_seg - pt_tri);\r\n  return true;\r\n}\r\n\r\nbool closest_point(const IPolygonalFace& _face, const Segment& _pt,\r\n  Point* _clsst_pt, double * _t, double * _dist_sq)\r\n{\r\n  Utils::StatisticsT<double> dist_stats;\r\n  Triangle tri;\r\n  Point clsst_pt;\r\n  for (size_t i = 0; i < _face.triangle_number(); ++i)\r\n  {\r\n    if (!_face.triangle(i, tri))\r\n      continue;\r\n    double dist_sq = 0, t;\r\n    if (!closest_point(tri, _pt, &clsst_pt, &t, &dist_sq))\r\n      continue;\r\n    if (dist_stats.add(dist_sq) & dist_stats.Smallest)\r\n    {\r\n      if (_clsst_pt != nullptr)\r\n        *_clsst_pt = clsst_pt;\r\n      if (_t != nullptr)\r\n        *_t = t;\r\n    }\r\n  }\r\n  if (dist_stats.count() == 0)\r\n    return false;\r\n  if (_dist_sq != nullptr)\r\n    *_dist_sq = dist_stats.min();\r\n  return true;\r\n}\r\n\r\n}//namespace Geo", "meta": {"hexsha": "e5ff0b8e84a698b81ddc1c32a740cad432f6d87c", "size": 7386, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main/src/Geo/entity.cc", "max_stars_repo_name": "marcomanno/ploygon_triangulation", "max_stars_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/src/Geo/entity.cc", "max_issues_repo_name": "marcomanno/ploygon_triangulation", "max_issues_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/src/Geo/entity.cc", "max_forks_repo_name": "marcomanno/ploygon_triangulation", "max_forks_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0070422535, "max_line_length": 91, "alphanum_fraction": 0.5893582453, "num_tokens": 2407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5659763088007757}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_QR_HPP\n#define ODE_QR_HPP\n\n// ODE using QR Decomposition\n\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/qr.hpp>\n#include <kv/vleq.hpp>\n#include <kv/ode.hpp>\n#include <kv/ode-autodif.hpp>\n#include <kv/ode-param.hpp>\n#include <kv/ode-callback.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nint\nodelong_qr(\n\tF f,\n\tub::vector< interval<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>(),\n\tub::matrix< interval<T> >* mat = NULL\n) {\n\tint s = init.size();\n\tint i, j;\n\n\tub::vector< interval<T> > c;\n\tub::vector< interval<T> > fc;\n\tub::vector< autodif< interval<T> > > Iad;\n\n\tub::vector< interval<T> > result_i;\n\tub::matrix< interval<T> > result_d;\n\n\tub::vector< interval<T> > x, x1;\n\tinterval<T> t, t1;\n\tub::matrix< interval<T> > M;\n\tint ret_ode, ret_ode2;\n\tint ret_val = 0;\n\tbool bo;\n\tbool ret_callback;\n\n\tub::matrix<T> Q, Q2, R, Q2t;\n\tub::matrix< interval<T> > AQ, QAQ, Q2i;\n\tub::vector< interval<T> > y, y1, y2, tmp;\n\n\tub::vector< psa< interval<T> > > result_psa;\n\n\n\tif (mat != NULL) {\n\t\tM = ub::identity_matrix< interval<T> >(s);\n\t}\n\n\tt = start;\n\tx = init;\n\n\tc = mid(x);\n\ty = x - c;\n\tQ = ub::identity_matrix<T>(s);\n\n\tode_param<T> p2;\n\n\twhile (1) {\n\t\tx1 = x;\n\t\tt1 = end;\n\n\t\tIad = autodif< interval<T> >::init(x1);\n\t\tp2 = p;\n\t\tp2.set_autostep(true);\n\t\t// NOTICE: below must be autodif version of ode\n\t\tret_ode = ode(f, Iad, t, t1, p2, &result_psa);\n\t\tif (ret_ode == 0) break;\n\n\t\tfc = c;\n\t\t// Step size should be same as above ode call.\n\t\t// Because above ode call is with autodif and interval input and\n\t\t// below ode call is without autodif and point input,\n\t\t// below ode call is supposed to be easier to succeed than above.\n\t\t// If below ode call fails, force success by increasing order.\n\t\tp2 = p;\n\t\tp2.set_autostep(false);\n\t\twhile (1) {\n\t\t\tret_ode2 = ode(f, fc, t, t1, p2);\n\t\t\tif (ret_ode2 != 0) break;\n\t\t\tp2.order++;\n\t\t\tstd::cout << \"increase order: \" << p2.order << \"\\n\";\n\t\t}\n\n\t\tautodif< interval<T> >::split(Iad, result_i, result_d);\n\n\t\t#if 0\n\t\t// centering result_d\n\t\tfc += prod(result_d - mid(result_d), x - c);\n\t\tresult_d =  mid(result_d);\n\t\t#endif\n\n\t\tAQ = prod(result_d, Q);\n\t\tbo = qr(mid(AQ), Q2, R);\n\t\tif (bo == false) break;\n\t\tQ2i = Q2;\n\t\tQ2t = trans(Q2);\n\t\t// bo = vleq(Q2i, AQ, QAQ);\n\t\tbo = vleq(Q2i, AQ, QAQ, &Q2t);\n\t\tif (bo == false) break;\n\t\tQ2i = Q2;\n\t\ty1 = prod(QAQ, y);\n\t\tc = mid(fc);\n\t\ttmp = fc - c;\n\t\t// bo = vleq(Q2i, tmp, y2);\n\t\tbo = vleq(Q2i, tmp, y2, &Q2t);\n\t\tif (bo == false) break;\n\t\ty = y1 + y2;\n\t\tx1 = prod(Q2, y) + c;\n\n\t\t// below seems to have some efficiency.\n\t\t// we comment out below because we have not study it\n\t\t// theoretically yet.\n\n\t\t// x1 = intersect(x1, result_i);\n\n\t\tQ = Q2;\n\n\t\tret_val = 1;\n\n\t\tif (mat != NULL) M = prod(result_d, M);\n\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << x1 << \"\\n\";\n\t\t}\n\n\t\tret_callback = callback(t, t1, x, x1, result_psa);\n\n\t\tif (ret_callback == false) {\n\t\t\tret_val = 3;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (ret_ode == 2) {\n\t\t\tret_val = 2;\n\t\t\tbreak;\n\t\t}\n\n\t\tt = t1;\n\t\tx = x1;\n\t}\n\n\tif (ret_val >= 1) {\n\t\tinit = x1;\n\t\tif (mat != NULL) *mat = M;\n\t}\n\tif (ret_val == 1) {\n\t\tend = t;\n\t}\n\tif (ret_val == 3) {\n\t\tend = t1;\n\t}\n\n\treturn ret_val;\n}\n\n\ntemplate <class T, class F>\nint\nodelong_qr(\n\tF f,\n\tub::vector< autodif< interval<T> > >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end, ode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tint i, j;\n\tub::vector< interval<T> > x;\n\tub::matrix< interval<T> > M, M_tmp;\n\tint r;\n\n\tautodif< interval<T> >::split(init, x, M);\n\tint s2 = M.size2();\n\n\tr = odelong_qr(f, x, start, end, p, callback, &M_tmp);\n\n\tif (r == 0) return 0;\n\n\tM = prod(M_tmp, M);\n\n\tfor (i=0; i<s; i++) {\n\t\tinit(i).v = x(i);\n\t\tinit(i).d.resize(s2);\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tinit(i).d(j) = M(i, j);\n\t\t}\n\t}\n\t\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // ODE_QR_HPP\n", "meta": {"hexsha": "2e79cb997f0dee41bb802ba3357b0e44a4c07944", "size": 4230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-qr.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/ode-qr.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/ode-qr.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 19.4930875576, "max_line_length": 67, "alphanum_fraction": 0.5938534279, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5659763036006925}}
{"text": "#pragma once\n\n#include \"GaussianDistribution.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n\n#include <array>\n\nnamespace icarus {\n    template<typename T, size_t N>\n    struct MerweScaledSigmaPoints\n    {\n        explicit MerweScaledSigmaPoints(T alpha, T beta = 2, T kappa = 3 - T(N))\n        {\n            mLambda = alpha * alpha * (T(N) + kappa) - T(N);\n            mFirstMeanWeight = mLambda / (T(N) + mLambda);\n            mCovarianceWeight = mFirstMeanWeight + 1 - alpha * alpha + beta;\n            mNextWeights = T(1) / (2 * (T(N) + mLambda));\n        }\n\n        static constexpr size_t size()\n        {\n            return 2 * N + 1;\n        }\n\n        std::array<Eigen::Matrix<T, N, 1>, size()> operator()(GaussianDistribution<T, N> const & distribution) const\n        {\n            Eigen::Matrix<T, N, N> offsets = ((T(N) + mLambda) * distribution.covariance).llt().matrixL();\n\n            std::array<Eigen::Matrix<T, N, 1>, size()> ret;\n            ret[0] = distribution.mean;\n\n            for (int i = 0; i < N; ++i) {\n                ret[1 + 2 * i + 0] = distribution.mean + offsets.col(i);\n                ret[1 + 2 * i + 1] = distribution.mean - offsets.col(i);\n            }\n\n            return ret;\n        }\n\n        template<int M>\n        GaussianDistribution<T, M> unscentedTransform(std::array<Eigen::Matrix<T, M, 1>, 2 * N + 1> const & points) const\n        {\n            GaussianDistribution<T, M> ret;\n\n            ret.mean = mFirstMeanWeight * points[0];\n\n            for (int i = 1; i < 2 * N + 1; ++i) {\n                ret.mean += mNextWeights * points[i];\n            }\n\n            auto difference = (points[0] - ret.mean).eval();\n            ret.covariance.template triangularView<Eigen::Lower>() = mCovarianceWeight * difference * difference.transpose();\n\n            for (int i = 1; i < 2 * N + 1; ++i) {\n                difference = (points[i] - ret.mean).eval();\n                ret.covariance.template selfadjointView<Eigen::Lower>().rankUpdate(difference, mNextWeights);\n            }\n\n            return ret;\n        }\n\n        T covarianceWeight(size_t index) const\n        {\n            if (index == 0) {\n                return mCovarianceWeight;\n            } else {\n                return mNextWeights;\n            }\n        }\n    private:\n        T mLambda;\n        T mFirstMeanWeight;\n        T mCovarianceWeight;\n        T mNextWeights;\n    };\n}\n", "meta": {"hexsha": "e0e7f27cd5c15ebc9cd4b29ae8178e73d71c2baa", "size": 2399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensorFusion/MerweScaledSigmaPoints.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icarus/include/icarus/sensorFusion/MerweScaledSigmaPoints.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icarus/include/icarus/sensorFusion/MerweScaledSigmaPoints.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3670886076, "max_line_length": 125, "alphanum_fraction": 0.5147978324, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544824, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5659763033893517}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Sebastian Schlenkrich\n\n*/\n\n/*! \\file integratorsT.hpp\n    \\brief provide template functions for numerical integration\n*/\n\n\n#ifndef quantlib_templateintegrators_hpp\n#define quantlib_templateintegrators_hpp\n\n#include <boost/function.hpp>\n//#include <boost/math/special_functions/erf.hpp>\n//#include <ql/experimental/template/auxilliaries/MinimADVariable2.hpp>\n\n\nnamespace TemplateAuxilliaries {\n\n    // evaluate \\int_a^b v(t) f(t) dt = \\sum v_i [F(t_i) - F(t_i-1)] with\n    // v(t) piece-wise left-constant,\n    // F'(t) = f(t)\n    template <typename PassiveType, typename ActiveType, typename FuncType>\n    class PieceWiseConstantIntegral {\n    private:\n        std::vector<PassiveType> t_;\n        std::vector<ActiveType> v_;\n        FuncType F_;\n    public:\n        PieceWiseConstantIntegral(const std::vector<PassiveType>& t, const std::vector<ActiveType>& v, const FuncType& F) : t_(t), v_(v), F_(F) {}\n        ActiveType operator()(PassiveType startTime, PassiveType endTime) {\n            int sgn = 1;\n            if (startTime>endTime) {  // we want to ensure startTime <= endTime\n                PassiveType t = startTime;\n                startTime = endTime;\n                endTime = t;\n                sgn = -1;\n            }\n            // organising indices\n            size_t idx_min  = 0;\n            size_t idx_max  = std::min(t_.size(),v_.size())-1;\n            size_t idx_last = idx_max;\n            // enforce a < t_min <= t_max < b or special treatment\n            while ((startTime>=t_[idx_min])&&(idx_min<idx_last)) ++idx_min;\n            while ((endTime  <=t_[idx_max])&&(idx_max>0       )) --idx_max;\n            ActiveType tmp = sgn * ( F_(endTime) - F_(startTime) );\n            if (endTime<=t_[0])    return v_[0]        * tmp;  // short end\n            if (idx_min==idx_last) return v_[idx_last] * tmp;  // long end\n            if (idx_min> idx_max)  return v_[idx_min]  * tmp;  // integration within grid interval\n            // integral a ... x_min\n            tmp = v_[idx_min] * ( F_(t_[idx_min]) - F_(startTime) );\n            // integral x_min ... x_max\n            for (size_t i=idx_min; i<idx_max; ++i) tmp += v_[i+1] * ( F_(t_[i+1]) - F_(t_[i]) );\n            // integral x_max ... b\n            if (idx_max<idx_last) tmp += v_[idx_max+1] * ( F_(endTime) - F_(t_[idx_max]) );\n            else                  tmp += v_[idx_max]   * ( F_(endTime) - F_(t_[idx_max]) );\n            // finished\n            return sgn * tmp;\n        }\n    };\n\n    // evaluate \\int_x(0)^x(n) v(x) f(x) dx via trapezoidal rule\n    // v(x) interpolated values on variable x-grid \n    // f(x) scalar function as functor\n    class TrapezoidalIntegral {\n    public:\n        template <typename PassiveType, typename ActiveType, typename FuncType>\n        ActiveType operator()(const std::vector<PassiveType>& x, const std::vector<ActiveType>& v, const FuncType& f) {\n            size_t n=std::min(x.size(),v.size());\n            if (n<2) return (ActiveType)0.0;\n            ActiveType sum=0;\n            for (size_t i=0; i<n-1; ++i) sum += 0.5*(v[i]*f(x[i]) + v[i+1]*f(x[i+1]))*(x[i+1] - x[i]);\n            return sum;\n        }\n    };\n\n    // evaluate \\int_x[0]^x[n-1] v(x) f(x) dx via Gau�-Tschebyschow-Integration\n    // x[0] left boundary, x[n-1] right boundary\n    // x[1], ..., x[n-2] Gauss-Tschebyschow grid points\n    // v(x) interpolated values on x-grid \n    // f(x) scalar function as functor\n    class GaussTschebyschowIntegral {\n    public:\n        template <typename PassiveType>\n        std::vector<PassiveType> getGrid(PassiveType a, PassiveType b, size_t n) {\n            std::vector<PassiveType> x(n);\n            if (n==0) return x;\n            if (n==1) { x[0] = 0.5*(a+b); return x; }\n            x[0] = a; \n            x[n-1] = b; \n            if (n==2) return x; \n            // n>2\n            for (size_t k=1; k<n-1; ++k) {\n                x[k] = -cos( (2.0*k-1.0) / (2.0*(n-2.0)) * M_PI );      // x \\in (-1, 1)\n                x[k] = 0.5*(b-a)*(x[k]+1) + a;                 // x \\in ( a, b)\n            }\n            return x;\n        }\n        template <typename PassiveType, typename ActiveType, typename FuncType>\n        ActiveType operator()(const std::vector<PassiveType>& x, const std::vector<ActiveType>& v, const FuncType& f) {\n            size_t n=std::min(x.size(),v.size());\n            if (n<3) return TrapezoidalIntegral()(x,v,f);\n            ActiveType sum=0;\n            for (size_t k=1; k<n-1; ++k) {\n                sum += v[k] * f(x[k]) * sin( (2*k-1)/(2*(n-2))*M_PI );\n            }\n            sum *= M_PI / (n-2);\n            return sum;\n        }\n    };\n\n\n    // 4th order Runge Kutta step for y' = f(t,y)\n    // via y1   = y0 + b^T k dt\n    //     k_i  = f(t+c_i dt, y0 + a_i^T k dt)\n    template <typename DateType, typename ActiveType>\n    void rungeKuttaStep( const std::vector<ActiveType>&                                                                      y0, \n                         const DateType                                                                                      t, \n                         const boost::function< void (const DateType, const std::vector<ActiveType>&, std::vector<ActiveType>&) >& f,\n                         const DateType                                                                                      dt,\n                         std::vector<ActiveType>&                                                                      y1  ) {\n        std::vector<ActiveType> k1(y0.size()), k2(y0.size()), k3(y0.size()), k4(y0.size());\n        y1 = y0;\n        // we add an epsilon in case we are at a boundary of piecewise constant parameters\n        DateType eps = 1.0e-8*dt;\n        // k1 = f(t,y0)\n        f( t+eps,    y0, k1);\n        for (size_t i=0; i<y0.size(); ++i) y1[i] += 1.0/6.0 * dt * k1[i];\n        // k2 = f(t + 0.5dt, y0 + 0.5 k1)\n        for (size_t i=0; i<y0.size(); ++i) k1[i] = y0[i] + 0.5 * dt * k1[i];\n        f( t+0.5*dt, k1, k2);\n        for (size_t i=0; i<y0.size(); ++i) y1[i] += 1.0/3.0 * dt * k2[i];\n        // k3 = f(t + 0.5dt, y0 + 0.5 k2)\n        for (size_t i=0; i<y0.size(); ++i) k2[i] = y0[i] + 0.5 * dt * k2[i];\n        f( t+0.5*dt, k2, k3);\n        for (size_t i=0; i<y0.size(); ++i) y1[i] += 1.0/3.0 * dt * k3[i];\n        // k4 = f(t + dt, y0 + k3)\n        for (size_t i=0; i<y0.size(); ++i) k3[i] = y0[i] + dt * k3[i];\n        f( t+1.0*dt-eps, k3, k4);\n        for (size_t i=0; i<y0.size(); ++i) y1[i] += 1.0/6.0 * dt * k4[i];\n        return;\n    }\n\n}\n\n#endif  /* quantlib_templateintegrators_hpp */\n", "meta": {"hexsha": "9386c5182053bc9da5a44524212f51faf3befcc4", "size": 6646, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/integratorsT.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/auxilliaries/integratorsT.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/auxilliaries/integratorsT.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": 44.3066666667, "max_line_length": 146, "alphanum_fraction": 0.4945832079, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5659297075670386}}
{"text": "/*\n *  mgbvtd.cpp\n *  vortrac\n *\n *  Created by Xiaowen Tang on 5/28/13.\n *  Copyright 2013 University Corporation for Atmospheric Research.\n *  All rights reserved.\n *\n */\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <armadillo>\n#include \"mgbvtd.h\"\n\nMGBVTD::MGBVTD(float x0, float y0, float hgt, float rmw, GriddedData& cappi):\nm_cappi(cappi)\n{\n\tm_centerx = x0;\n\tm_centery = y0;\n\tm_centerz = hgt;\n\tm_rmw     = rmw;\n}\n\nfloat MGBVTD::computeCrossBeamWind(float guessMax, QString& velField, GBVTD* gbvtd, Hvvp* hvvp)\n{\n\tconst float Rt = sqrt(m_centerx*m_centerx+m_centery*m_centery);\n\n\t//1. calculate Vt profile first\n\tstd::vector<float> vt;\n\tstd::vector<float> vt_rng;\n\t//1. compute the radial profile of symmetric tangential wind  \n\tfor(float rng=m_rmw*1.2; rng<=.6*Rt; rng+=1.){\n\t\tm_cappi.setCartesianReferencePoint(m_centerx, m_centery, m_centerz);\n\t\tint numData = m_cappi.getCylindricalAzimuthLength(rng, m_centerz);\n\t\tfloat* ringData = new float[numData];\n\t\tfloat* ringAzi  = new float[numData];\n\t\tm_cappi.getCylindricalAzimuthData(velField, numData, rng, m_centerz, ringData);\n        m_cappi.getCylindricalAzimuthPosition(numData, rng, m_centerz, ringAzi);\n\t\tCoefficient* coeff = new Coefficient[20];\n\t\tfloat vtdDev;\n\t\tif(gbvtd->analyzeRing(m_centerx, m_centery, rng, m_centerz, numData, ringData, ringAzi, coeff, vtdDev)){\n\t\t\tif(coeff[0].getParameter()==\"VTC0\"){\n\t\t\t\tvt.push_back(coeff[0].getValue());\n\t\t\t\tvt_rng.push_back(rng);\n\t\t\t}\n\t\t}\n\t\tdelete[] ringAzi;\n\t\tdelete[] ringData;\n\t\tdelete[] coeff;\n\t}\n\tif(vt.size()<15) {\n\t\t// std::cout<<std::endl;\n\t\treturn 0.f;\n\t}\n\t\n\t//Compute hvvp first\n\tfloat cc0, cc6, vt_std, hvvp_std;\n\tif(!hvvp->computeCrossBeamWind(m_centerz, cc0, cc6, hvvp_std)) {\n\t\t// std::cout<<std::endl;\n\t\treturn 0.f;\n\t}\n\t// printf(\"cc0=%5.2f, cc6=%5.2f, \", cc0, cc6);\n\t\n\t//Iterate through all possible values of cross-beam wind\n\tarma::fmat A(vt.size(), 2);\n\tfor(int ii=0; ii<vt.size(); ++ii){\n\t\tA(ii,0) = log(Rt/vt_rng[ii]);\n\t\tA(ii,1) = 1;\n\t}\n\t\n\tstd::vector<float> guessWinds;\n\tfor(float currentWind=-fabs(guessMax); currentWind<fabs(guessMax)+1.; currentWind+=1.)\n\t\tguessWinds.push_back(currentWind);\n\t\n\tstd::vector<bool> flag(guessWinds.size(), false);\n\tarma::fmat B(vt.size(), guessWinds.size());\n\tB.fill(0.f);\n\tarma::fvec b(vt.size());\n\tfor(std::vector<float>::iterator it=guessWinds.begin(); it!=guessWinds.end(); ++it){\n\t\tint idx = std::distance(guessWinds.begin(), it);\n\t\tfor(int ii=0; ii<vt.size(); ++ii)\n\t\t\tb(ii) = vt[ii]-*it*vt_rng[ii]/Rt;\n\t\tif( b.min()>0.f){\n\t\t\tB.col(idx) = arma::log(b);\n\t\t\tflag[idx]  = true;\n\t\t}\n\t}\n\tarma::fmat X=arma::solve(A, B);\n\tarma::fmat E=(A*X-B);\n\tvt_std = sqrt(arma::accu(arma::square(E))/E.size());\n\t// printf(\"min_Xt=%5.2f, max_Xt=%5.2f, \", arma::min(X.row(0)), arma::max(X.row(0)));\n\t\n\t//Compare results and find the best one\n\tfloat curDev=999., tmpBest=0., tmpXt=999.;\n\tfor(std::vector<float>::iterator it=guessWinds.begin(); it!=guessWinds.end(); ++it){\n\t\tint idx = std::distance(guessWinds.begin(), it);\n\t\tif(!flag[idx] || X(0,idx)<=0.f ) continue;\n\t\tfloat hvvp_vm = cc0-Rt*cc6/(X(0,idx)+1.);\n\t\tif(fabs(*it-hvvp_vm)<curDev){\n\t\t\tcurDev  = fabs(*it-hvvp_vm);\n\t\t\ttmpBest = *it;\n\t\t\ttmpXt   = X(0,idx);\n\t\t}\n\t}\n\t\n\t// printf(\"num_vt_fit=%3d, vt_std=%5.2f, hvvp_std=%5.2f, tmpXt=%5.2f, vm=%5.2f, dev=%5.2f\\n\", vt.size(), vt_std, hvvp_std, tmpXt, tmpBest, curDev);\n\tif(curDev>4.0f)\n\t\treturn 0.0f;\n\telse\t\n\t\treturn tmpBest;\n}\n", "meta": {"hexsha": "7aa8c42492a80c34436e69c3218c76305cdd9b7d", "size": 3400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/VTD/mgbvtd.cpp", "max_stars_repo_name": "FoolishPineapple/vortrac", "max_stars_repo_head_hexsha": "a682e6080e83f7ae8fa34f33cc68ea0739390d0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-07-29T00:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T01:44:10.000Z", "max_issues_repo_path": "src/VTD/mgbvtd.cpp", "max_issues_repo_name": "FoolishPineapple/vortrac", "max_issues_repo_head_hexsha": "a682e6080e83f7ae8fa34f33cc68ea0739390d0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/VTD/mgbvtd.cpp", "max_forks_repo_name": "FoolishPineapple/vortrac", "max_forks_repo_head_hexsha": "a682e6080e83f7ae8fa34f33cc68ea0739390d0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-05-22T16:15:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T03:05:29.000Z", "avg_line_length": 30.0884955752, "max_line_length": 148, "alphanum_fraction": 0.6611764706, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.5659145575595868}}
{"text": "#pragma once\n\n#include \"utils.hpp\"\n#include <Eigen/Core>\n\ntemplate <typename MI, typename Tree>\nstd::vector<Eigen::VectorXd> FD(const MI& info, Tree& tree, const std::vector<Eigen::VectorXd>& Tau)\n{\n    constexpr int ord = Tree::order;\n    const auto& mb = info.model.mb;\n    const auto& pred = mb.predecessors();\n    const auto& succ = mb.successors();\n\n    std::vector<Eigen::MatrixXd> C(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> CD(mb.nrBodies());\n    std::vector<Eigen::VectorXd> PA(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> IA(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> G(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> U(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> UD(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> D(mb.nrBodies());\n    std::vector<Eigen::VectorXd> T(mb.nrBodies());\n    std::vector<Eigen::VectorXd> y(mb.nrBodies());\n\n    for (int i = 0; i < mb.nrBodies(); ++i) {\n        C[i] = tree.joints[i].inverse().template matrix<ord>();\n        CD[i] = tree.joints[i].template dualMatrix<ord>();\n        G[i] = makeDiag<ord>(mb.joint(i).motionSubspace());\n        IA[i].setZero(6 * ord, 6 * ord);\n        PA[i].setZero(6 * ord);\n    }\n\n    for (int i = mb.nrBodies() - 1; i >= 0; --i) {\n        IA[i] += makeDiag<ord>(mb.body(i).inertia().matrix());\n        U[i] = IA[i] * G[i];\n        UD[i] = G[i].transpose() * IA[i];\n        D[i] = G[i].transpose() * U[i];\n\n        y[i] = D[i].inverse() * (Tau[i] - G[i].transpose() * PA[i]);\n        if (pred[i] != -1) {\n            auto tmp1 = IA[i] - U[i] * D[i].inverse() * UD[i];\n            IA[pred[i]] += CD[i] * tmp1 * C[i];\n            auto tmp2 = PA[i] + U[i] * y[i];\n            PA[pred[i]] += CD[i] * tmp2;\n        }\n    }\n\n    for (int i = 0; i < mb.nrJoints(); ++i) {\n        int dof = mb.joint(i).dof();\n        if (pred[i] != -1) {\n            y[i] -= D[i].inverse() * UD[i] * C[i] * T[pred[i]];\n        }\n        T[i] = G[i] * y[i];\n        if (pred[i] != -1) {\n            T[i] += C[i] * T[pred[i]];\n        }\n    }\n\n    return y;\n}\n\ntemplate <typename MI, typename Tree>\nEigen::VectorXd standard_FD(const MI& info, Tree& tree, const Eigen::VectorXd& tau)\n{\n    constexpr int ord = Tree::order;\n    const auto& mb = info.model.mb;\n    const auto& pred = mb.predecessors();\n    const auto& succ = mb.successors();\n    const auto& jpd = mb.jointsPosInDof();\n\n    std::vector<Eigen::Vector6d> PA(mb.nrBodies());\n    std::vector<Eigen::Matrix6d> IA(mb.nrBodies());\n    std::vector<Eigen::Matrix6d> X(mb.nrBodies());\n    std::vector<Eigen::Vector6d> T(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> U(mb.nrBodies());\n    std::vector<Eigen::MatrixXd> D(mb.nrBodies());\n    Eigen::VectorXd y(tau.size());\n\n    for (int i = 0; i < mb.nrBodies(); ++i) {\n        IA[i].setZero();\n        PA[i].setZero();\n        X[i] = tree.joints[i].transform().inverse().matrix();\n    }\n\n    for (int i = mb.nrBodies() - 1; i >= 0; --i) {\n        const auto& S = mb.joint(i).motionSubspace();\n        int dof = mb.joint(i).dof();\n        IA[i] += mb.body(i).inertia().matrix();\n        U[i] = IA[i] * S;\n        D[i] = S.transpose() * U[i];\n\n        y.segment(jpd[i], dof) = D[i].inverse() * (tau.segment(jpd[i], dof) - S.transpose() * PA[i]);\n        if (pred[i] != -1) {\n            auto tmp1 = IA[i] - U[i] * D[i].inverse() * U[i].transpose();\n            IA[pred[i]] += X[i].transpose() * tmp1 * X[i];\n            auto tmp2 = PA[i] + U[i] * y.segment(jpd[i], dof);\n            PA[pred[i]] += X[i].transpose() * tmp2;\n        }\n    }\n\n    for (int i = 0; i < mb.nrJoints(); ++i) {\n        int dof = mb.joint(i).dof();\n        if (pred[i] != -1) {\n            y.segment(jpd[i], dof) -= D[i].inverse() * U[i].transpose() * X[i] * T[pred[i]];\n        }\n        T[i] = mb.joint(i).motionSubspace() * y.segment(jpd[i], dof);\n        if (pred[i] != -1) {\n            T[i] += X[i] * T[pred[i]];\n        }\n    }\n\n    return y;\n}\n", "meta": {"hexsha": "b9536ae2c68a453cddf56113a2d77faf4b682d4a", "size": 3901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algo_v0/FD.hpp", "max_stars_repo_name": "vsamy/cdm", "max_stars_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:29.000Z", "max_issues_repo_path": "algo_v0/FD.hpp", "max_issues_repo_name": "vsamy/cdm", "max_issues_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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": "algo_v0/FD.hpp", "max_forks_repo_name": "vsamy/cdm", "max_forks_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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.2192982456, "max_line_length": 101, "alphanum_fraction": 0.5085875417, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5658342029216034}}
{"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#include <opengv/triangulation/methods.hpp>\n#include <Eigen/Eigenvalues>\n\nopengv::point_t\nopengv::triangulation::triangulate(\n    const relative_pose::RelativeAdapterBase & adapter,\n    size_t index )\n{\n  translation_t t12 = adapter.gett12();\n  rotation_t R12 = adapter.getR12();\n  Eigen::Matrix<double,3,4> P1 = Eigen::Matrix<double,3,4>::Zero();\n  P1.block<3,3>(0,0) = Eigen::Matrix3d::Identity();\n  Eigen::Matrix<double,3,4> P2 = Eigen::Matrix<double,3,4>::Zero();\n  P2.block<3,3>(0,0) = R12.transpose();\n  P2.block<3,1>(0,3) = -R12.transpose()*t12;\n  bearingVector_t f1 = adapter.getBearingVector1(index);\n  bearingVector_t f2 = adapter.getBearingVector2(index);\n\n  Eigen::MatrixXd A(4,4);\n  A.row(0) = f1[0] * P1.row(2) - f1[2] * P1.row(0);\n  A.row(1) = f1[1] * P1.row(2) - f1[2] * P1.row(1);\n  A.row(2) = f2[0] * P2.row(2) - f2[2] * P2.row(0);\n  A.row(3) = f2[1] * P2.row(2) - f2[2] * P2.row(1);\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > mySVD(A, Eigen::ComputeFullV );\n  point_t worldPoint;\n  worldPoint[0] = mySVD.matrixV()(0,3);\n  worldPoint[1] = mySVD.matrixV()(1,3);\n  worldPoint[2] = mySVD.matrixV()(2,3);\n  worldPoint = worldPoint / mySVD.matrixV()(3,3);\n\n  return worldPoint;\n};\n\n\nopengv::point_t\nopengv::triangulation::triangulate(bearingVector_t const & f1, bearingVector_t const &  f2,\n    translation_t const &  t12, rotation_t const &  R12)\n{\n  Eigen::Matrix<double,3,4> P1 = Eigen::Matrix<double,3,4>::Zero();\n  P1.block<3,3>(0,0) = Eigen::Matrix3d::Identity();\n  Eigen::Matrix<double,3,4> P2 = Eigen::Matrix<double,3,4>::Zero();\n  P2.block<3,3>(0,0) = R12.transpose();\n  P2.block<3,1>(0,3) = -R12.transpose()*t12;\n\n  Eigen::MatrixXd A(4,4);\n  A.row(0) = f1[0] * P1.row(2) - f1[2] * P1.row(0);\n  A.row(1) = f1[1] * P1.row(2) - f1[2] * P1.row(1);\n  A.row(2) = f2[0] * P2.row(2) - f2[2] * P2.row(0);\n  A.row(3) = f2[1] * P2.row(2) - f2[2] * P2.row(1);\n\n  Eigen::JacobiSVD< Eigen::MatrixXd > mySVD(A, Eigen::ComputeFullV );\n  point_t worldPoint;\n  worldPoint[0] = mySVD.matrixV()(0,3);\n  worldPoint[1] = mySVD.matrixV()(1,3);\n  worldPoint[2] = mySVD.matrixV()(2,3);\n  worldPoint = worldPoint / mySVD.matrixV()(3,3);\n\n  return worldPoint;\n};\n\nopengv::point_t\nopengv::triangulation::triangulate2(\n    const relative_pose::RelativeAdapterBase & adapter,\n    size_t index )\n{\n  translation_t t12 = adapter.gett12();\n  rotation_t R12 = adapter.getR12();\n  bearingVector_t f1 = adapter.getBearingVector1(index);\n  bearingVector_t f2 = adapter.getBearingVector2(index);\n\n  bearingVector_t f2_unrotated = R12 * f2;\n  Eigen::Vector2d b;\n  b[0] = t12.dot(f1);\n  b[1] = t12.dot(f2_unrotated);\n  Eigen::Matrix2d A;\n  A(0,0) = f1.dot(f1);\n  A(1,0) = f1.dot(f2_unrotated);\n  A(0,1) = -A(1,0);\n  A(1,1) = -f2_unrotated.dot(f2_unrotated);\n  Eigen::Vector2d lambda = A.inverse() * b;\n  Eigen::Vector3d xm = lambda[0] * f1;\n  Eigen::Vector3d xn = t12 + lambda[1] * f2_unrotated;\n  point_t point = ( xm + xn )/2;\n  return point;\n};\n", "meta": {"hexsha": "51d93f508eaf7d9fef361e1a17fe05f4a169fcc2", "size": 5250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matchinglib_poselib/source/poselib/thirdparty/opengv/src/triangulation/methods.cpp", "max_stars_repo_name": "josefmaierfl/matchinglib_poselib", "max_stars_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-30T14:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:58:18.000Z", "max_issues_repo_path": "matchinglib_poselib/source/poselib/thirdparty/opengv/src/triangulation/methods.cpp", "max_issues_repo_name": "josefmaierfl/matchinglib_poselib", "max_issues_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:11:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-19T16:11:15.000Z", "max_forks_repo_path": "matchinglib_poselib/source/poselib/thirdparty/opengv/src/triangulation/methods.cpp", "max_forks_repo_name": "josefmaierfl/matchinglib_poselib", "max_forks_repo_head_hexsha": "3bd7125a1ddfea68dfa95c8b3f978cba4a678348", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T13:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T10:56:02.000Z", "avg_line_length": 44.4915254237, "max_line_length": 91, "alphanum_fraction": 0.5952380952, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5658313340711096}}
{"text": "// Copyright 2014, Max Planck Society.\r\n// Distributed under the BSD 3-Clause license.\r\n// (See accompanying file LICENSE.txt or copy at\r\n// http://opensource.org/licenses/BSD-3-Clause)\r\n\r\n#ifndef GRASSMANN_AVERAGES_PCA_TRIMMED_HPP__\r\n#define GRASSMANN_AVERAGES_PCA_TRIMMED_HPP__\r\n\r\n\r\n\r\n/*!@file\r\n * Grassmann averages for robust PCA functions, following the paper of Soren Hauberg.\r\n *\r\n * This file contains the implementation of the trimmed version. \r\n */\r\n\r\n\r\n// for the thread pools\r\n#include <boost/asio/io_service.hpp>\r\n#include <boost/bind.hpp>\r\n#include <boost/thread/thread.hpp>\r\n\r\n#include <boost/scoped_array.hpp>\r\n#include <boost/function.hpp>\r\n\r\n// utilities\r\n#include <include/private/utilities.hpp>\r\n\r\n\r\nnamespace grassmann_averages_pca\r\n{\r\n\r\n\r\n  namespace details\r\n  {\r\n\r\n    //!@internal\r\n    //!Helper object for the updates\r\n    template <class scalar_t>\r\n    struct s_dimension_update\r\n    {\r\n      size_t dimension;\r\n      scalar_t value;\r\n    };\r\n\r\n    /*!@internal\r\n     * @brief Adaptation of merger_addition concept for accumulator and count at the same time.\r\n     * \r\n     * The trimmed version of the grassmann pca algorithm may strip some element along each dimension. \r\n     * In order to compute the @f$\\mu@f$ properly, the count should also be transfered.\r\n     */\r\n    template <class data_t>\r\n    struct merger_update_specific_dimension\r\n    {\r\n      typedef data_t input_t;\r\n      bool operator()(input_t &current_state, s_dimension_update<typename data_t::value_type> const& update_value) const\r\n      {\r\n        current_state(update_value.dimension) += update_value.value;\r\n        return true;\r\n      }\r\n    };\r\n    \r\n  }\r\n\r\n\r\n\r\n\r\n  /*!@brief Grassmann Average algorithm for robust PCA computation, with trimming of outliers.\r\n   *\r\n   * This class implements the Grassmann average for computing the robust PCA, which also includes the trimming of \"outliers\". \r\n   * Its purpose is to compute the PCA of a dataset @f$\\mathbf{X} = \\{X_i\\}@f$, where each @f$X_i@f$ is a vector of dimension\r\n   * D, and also by being less sensitive to the outliers of the original data.\r\n   * \r\n   * The algorithm is the following:\r\n   * - pick a random or a given @f$\\mu_{k, 0}@f$, where @f$k@f$ is the current basis vector being computed and @f$0@f$ is the current iteration number (0). \r\n   * - ensure this @f$\\mu_{k, 0}@f$ is orthogonal to the previous detected @f$\\mu_{k', 0},\\, \\forall k' \\in [0, k)@f$\r\n   * - until the sequence @f$(\\mu_{k, t})_t@f$ converges, do:\r\n   *   - computes the sign @f$s_{j, t}@f$ of the projection of the input vectors @f$X_j@f$ onto @f$\\mu_{i, t}@f$. We have @f[s_{j, t} = X_j \\cdot \\mu_{k, t} \\geq 0@f]\r\n   *   - for each dimension @f$0 \\lt d \\leq D@f$, do:\r\n   *     - For all @f$j@f$, consider the multiplied data set projected onto dimension @f$d@f$: \r\n   *       @f[\\mathbf{X_\\mu^{(d)}} = \\left\\{proj_d \\left(s_{j, t} \\cdot X_j\\right) \\right\\} = \\left\\{s_{j, t} \\cdot X_j^{(d)}\\right\\}@f]\r\n   *       which is a 1-D sequence\r\n   *     - compute the indexes @f$J_d@f$ of the @f$\\frac{K}{2}@f$ lowest and biggest points of this 1-D sequence @f$\\mathbf{X_\\mu^{(d)}}@f$\r\n   *     - compute the update of @f$\\mu_{k, .}@f$ for dimension @f$d@f$ : \r\n   *       @f[\\mu_{k, t+1}^{(d)} = \\frac{\\sum_{j \\notin J_d} proj_d \\left(s_{j, t} \\cdot X_j \\right)}{\\# J - \\# J_d} @f]\r\n   *   - normalize @f[\\mu_{k, t+1} = \\frac{\\left(\\mu_{k, t+1}^{(1)}, \\ldots \\mu_{k, t+1}^{(D)}\\right)^t}{\\left\\|\\left(\\mu_{k, t+1}^{(1)}, \\ldots \\mu_{k, t+1}^{(D)}\\right)^t\\right\\|}@f]\r\n   * - project the @f$X_j@f$'s onto the orthogonal subspace of @f$\\mu_{k} = \\lim_{t \\rightarrow +\\infty} \\mu_{k, t}@f$: @f[\\forall j, X_{j} = X_{j} - X_{j}\\cdot\\mu_{k} @f]\r\n   *\r\n   * The range taken by @f$k@f$ is a parameter of the algorithm: @c max_dimension_to_compute (see grassmann_pca::batch_process). \r\n   * The range taken by @f$t@f$ is also a parameter of the algorithm: @c max_iterations (see grassmann_pca::batch_process).\r\n   * The test for convergence is delegated to the class details::convergence_check.\r\n   *\r\n   * The computation is distributed among several threads. The multithreading strategy is \r\n   * - to split the computation of @f$\\sum_j s_{j, t} X_j@f$ among several independant chunks. This computation involves the inner product and the sign. Each chunk addresses \r\n   *   a subset of the data @f$\\{X_j\\}@f$ without any overlap with other chunks. The maximal size of a chunk can be configured through the function grassmann_pca::set_max_chunk_size.\r\n   *   By default, the size of the chunk would be the size of the data divided by the number of threads.\r\n   * - to compute the @f$\\frac{K}{2}@f$ extremal points along each dimension in parallel\r\n   * - to split the computation of the projection onto the orthogonal subspace of @f$\\mu_{k}@f$.\r\n   * - to split the computation of the regular PCA algorithm (if any) into several independant chunks.\r\n   *\r\n   * The number of threads can be configured through the function grassmann_pca::set_nb_processors.\r\n   * \r\n   * @note\r\n   * The algorithm may also perform a few \"regular PCA\" steps, which is the computation of the basis vector with highest \"eigen-value\". This can be configured through the function\r\n   * grassmann_pca_with_trimming::set_nb_steps_pca. Also, the data can be centered before applying any computation (see grassmann_pca_with_trimming::set_centering). This is \r\n   * convenient especially when the input data iterator is just a stub that provides data read from the disk for instance (see the application of Grassmann applied on videos).\r\n   *\r\n   * @tparam data_t type of vectors used for the computation. \r\n   * @tparam norm_mu_t norm used to normalize the basis vectors and project them onto the unit circle.\r\n   * @tparam observer_t an observer type following the signature of the class grassmann_trivial_callback\r\n   *\r\n   * @author Soren Hauberg, Raffi Enficiaud\r\n   */\r\n  template <class data_t, \r\n            class observer_t = grassmann_trivial_callback<data_t>,\r\n            class norm_mu_t = details::norm2 >\r\n  struct grassmann_pca_with_trimming\r\n  {\r\n  private:\r\n    //! Random generator for initialising @f$\\mu@f$ at each dimension. \r\n    details::random_data_generator<data_t> random_init_op;\r\n\r\n    //! Norm used for normalizing @f$\\mu@f$.\r\n    norm_mu_t norm_op;\r\n    \r\n\r\n    //! The percentage of the data that should be trimmed.\r\n    //! The trimming is performed symmetrically in the upper and lower distribution of the data, hence\r\n    //! each side is trimmed by trimming_percentage/2.\r\n    double trimming_percentage;\r\n\r\n    //! Number of parallel tasks that will be used for computing.\r\n    size_t nb_processors;\r\n\r\n    //! Maximal size of a chunk (infinity by default).\r\n    size_t max_chunk_size;\r\n\r\n    //! Number of steps for the initial PCA like algorithm (defaults to 3).\r\n    size_t nb_steps_pca;\r\n\r\n    //! Type of the element of data_t. \r\n    typedef typename data_t::value_type scalar_t;\r\n\r\n    //! Type of the vector used for counting the element falling into the non-trimmed range.\r\n    typedef boost::numeric::ublas::vector<size_t> count_vector_t;\r\n\r\n    //! Indicates that the incoming data is not centered and a centering should be performed prior\r\n    //! to the computation of the PCA or the trimmed grassmann average.\r\n    bool need_centering;\r\n\r\n\r\n    //! An instance observing the steps of the algorithm\r\n    observer_t *observer;\r\n\r\n\r\n    //!@internal\r\n    //!@brief Contains the logic for processing part of the accumulator\r\n    struct s_grassmann_averages_trimmed_processor_inner_products\r\n    {\r\n    private:\r\n      //! Scalar type of the data\r\n      typedef typename data_t::value_type scalar_t;\r\n      \r\n      typedef details::s_dimension_update<scalar_t> accumulator_element_t;\r\n\r\n      \r\n      size_t nb_elements;                 //!< The size of the current dataset\r\n      size_t data_dimension;              //!< The dimension of the data\r\n      size_t k_first_last;                //!< The number of elements to remove from the lower and upper distributions.\r\n      \r\n      typedef boost::function<void ()> connector_counter_t;\r\n      connector_counter_t signal_counter;\r\n\r\n      typedef boost::function<void (accumulator_element_t const*)> connector_accumulator_dimension_t;\r\n      connector_accumulator_dimension_t signal_acc_dimension;\r\n\r\n      std::vector<accumulator_element_t> v_accumulated_per_dimension;\r\n\r\n \r\n      //! The matrix containing a copy of the data\r\n      scalar_t *p_c_matrix;\r\n      \r\n      //! The result of the inner products\r\n      std::vector<scalar_t> inner_prod_results;\r\n  \r\n      void compute_inner_products(data_t const &mu)\r\n      {\r\n        scalar_t *out = &inner_prod_results[0];\r\n        scalar_t mu_element = mu(0);\r\n        scalar_t const * current_line = p_c_matrix;\r\n        \r\n        for(int column = 0; column < nb_elements; column++)\r\n        {\r\n          out[column] = mu_element * current_line[column];\r\n        }\r\n        current_line += nb_elements;\r\n        \r\n        for(int line = 1; line < data_dimension; line ++, current_line += nb_elements)\r\n        {\r\n          mu_element = mu(line);    \r\n          for(int column = 0; column < nb_elements; column++)\r\n          {\r\n            out[column] += mu_element * current_line[column];\r\n          }               \r\n        }\r\n        \r\n      }                    \r\n\r\n\r\n    public:\r\n      s_grassmann_averages_trimmed_processor_inner_products() : \r\n        nb_elements(0), \r\n        data_dimension(0), \r\n        k_first_last(0),\r\n        p_c_matrix(0)\r\n      {\r\n      }\r\n\r\n      ~s_grassmann_averages_trimmed_processor_inner_products()\r\n      {\r\n        delete [] p_c_matrix;\r\n      }\r\n      \r\n      \r\n      //! Returns the connected object that will receive the notification of the end of the current process.\r\n      connector_counter_t& connector_counter()\r\n      {\r\n        return signal_counter;\r\n      }     \r\n      \r\n      connector_accumulator_dimension_t& connector_accumulator()\r\n      {\r\n        return signal_acc_dimension;\r\n      }\r\n      \r\n      //! Sets the data range\r\n      template <class container_iterator_t>\r\n      bool set_data_range(container_iterator_t const &b, container_iterator_t const& e)\r\n      {\r\n        if(data_dimension <= 0)\r\n        {\r\n          return false;\r\n        }\r\n        \r\n        nb_elements = std::distance(b, e);\r\n\r\n        assert(data_dimension > 0);\r\n        assert(nb_elements > 0);\r\n        \r\n        delete [] p_c_matrix;\r\n        p_c_matrix = new scalar_t[nb_elements*data_dimension];\r\n        \r\n        container_iterator_t bb(b);\r\n        \r\n        for(int column = 0; column < nb_elements; column++, ++bb)\r\n        {\r\n          scalar_t* current_line = p_c_matrix + column;\r\n          for(int line = 0; line < data_dimension; line ++, current_line += nb_elements)\r\n          {         \r\n            *current_line = (*bb)(line);\r\n          }\r\n          \r\n        }\r\n        \r\n        inner_prod_results.resize(nb_elements);\r\n        \r\n        signal_counter();\r\n        return true;\r\n      }\r\n\r\n      //! Sets the dimension of the data vectors\r\n      //! @pre data_dimensions_ is strictly positive\r\n      void set_data_dimensions(size_t data_dimensions_)\r\n      {\r\n        assert(data_dimensions_ > 0);\r\n        data_dimension = data_dimensions_;\r\n        v_accumulated_per_dimension.resize(data_dimension);\r\n      }\r\n\r\n      //! Sets the number of element to remove in the upper and lower distributions.\r\n      void set_nb_elements_to_remove(int k_first_last_)\r\n      {\r\n        assert(k_first_last_ >= 0);\r\n        k_first_last = k_first_last_;\r\n      }\r\n\r\n\r\n      //! Centering the data in case it was not possible to do it beforehand\r\n      void data_centering_first_phase(size_t full_dataset_size)\r\n      {\r\n        scalar_t const * current_line = p_c_matrix;\r\n        for(size_t dimension = 0; dimension < data_dimension; dimension++)\r\n        {\r\n          scalar_t acc = 0;\r\n          for(size_t s = 0; s < nb_elements; s++)\r\n          {\r\n            acc += *current_line++;\r\n          }\r\n\r\n          // posts the new value to the listeners for the current dimension\r\n          accumulator_element_t &result = v_accumulated_per_dimension[dimension];\r\n          result.dimension = dimension;\r\n          result.value = acc / full_dataset_size;\r\n          signal_acc_dimension(&result);\r\n        }\r\n\r\n        signal_counter();\r\n\r\n      }\r\n\r\n      //! Project the data onto the orthogonal subspace of the provided vector\r\n      void data_centering_second_phase(data_t const &mean_value)\r\n      {\r\n        scalar_t *current_element_ptr = p_c_matrix;\r\n        \r\n        for(int line = 0; line < data_dimension; line++)\r\n        {\r\n          const scalar_t scalar = mean_value(line);   \r\n          scalar_t * const current_line_end = current_element_ptr + nb_elements;\r\n          for(; current_element_ptr < current_line_end; current_element_ptr++)\r\n          {\r\n            *current_element_ptr -= scalar;\r\n          }               \r\n        }\r\n\r\n        signal_counter();\r\n      }\r\n\r\n\r\n      //! PCA steps\r\n      void pca_accumulation(data_t const &mu)\r\n      {\r\n        compute_inner_products(mu);\r\n               \r\n        scalar_t const * const p_inner_product = &inner_prod_results[0];\r\n\r\n        for(size_t dimension = 0; dimension < data_dimension; dimension++)\r\n        {\r\n          scalar_t const * const current_line = p_c_matrix + dimension*nb_elements;\r\n          scalar_t acc = 0;\r\n          for(size_t s = 0; s < nb_elements; s++)\r\n          {\r\n            acc += p_inner_product[s] * current_line[s];\r\n          }\r\n\r\n          // posts the new value to the listeners for the current dimension\r\n          accumulator_element_t &result = v_accumulated_per_dimension[dimension];\r\n          result.dimension = dimension;\r\n          result.value = acc;\r\n          signal_acc_dimension(&result);\r\n        }\r\n\r\n        signal_counter();\r\n      }\r\n\r\n      \r\n      //! Computes the inner products and stores the signed result where appropriate.\r\n      void compute_data_matrix(data_t const &mu, scalar_t* p_out, size_t padding)\r\n      {\r\n        // updates the internal inner products\r\n        compute_inner_products(mu);\r\n        \r\n        // the current line is spans a particular dimension\r\n        scalar_t *current_line = p_c_matrix;\r\n\r\n        // this spans the inner product results for all dimensions\r\n\r\n        std::vector<int> v_mult(nb_elements);\r\n        for(size_t element(0); element < nb_elements; element++)\r\n        {\r\n          v_mult[element] = inner_prod_results[element] >= 0 ? 1 : -1;\r\n        }\r\n        int const * const out = &v_mult[0];\r\n\r\n        for(size_t current_dimension = 0; \r\n            current_dimension < data_dimension; \r\n            current_dimension++, current_line += nb_elements, p_out+= padding)\r\n        {\r\n          for(size_t element(0); element < nb_elements; element++)\r\n          {\r\n            p_out[element] = out[element] * current_line[element];\r\n          }\r\n        }\r\n        \r\n        // signals the main merger\r\n        signal_counter();\r\n      }\r\n      \r\n      //! Computes the mean on the subset of the data where the k first and last elements are removed.\r\n      void compute_bounded_accumulation(size_t dimension, size_t nb_total_elements, scalar_t* p_data)\r\n      {\r\n        accumulator_element_t &result = v_accumulated_per_dimension[dimension];\r\n        result.dimension = dimension;\r\n        result.value = details::compute_mean_within_bounds(p_data, nb_total_elements, k_first_last);\r\n\r\n        // signals the update\r\n        signal_acc_dimension(&result);\r\n        // signals the main merger\r\n        signal_counter();\r\n      }\r\n      \r\n      //! Project the data onto the orthogonal subspace of the provided vector\r\n\t    template <class vector_t>\r\n      void project_onto_orthogonal_subspace(vector_t const &mu)\r\n      {\r\n        compute_inner_products(mu);\r\n        scalar_t *current_line = p_c_matrix;\r\n        \r\n        for(int line = 0; line < data_dimension; line ++, current_line += nb_elements)\r\n        {\r\n          scalar_t mu_element = mu(line);    \r\n          for(int column = 0; column < nb_elements; column++)\r\n          {\r\n            current_line[column] -= mu_element * inner_prod_results[column];\r\n          }               \r\n        }\r\n\r\n        signal_counter();\r\n      }\r\n\r\n    };\r\n\r\n\r\n    /*!@internal\r\n     * @brief Merges the result of all workers and signals the results to the main thread.\r\n     *\r\n     * The purpose of this class is to add the computed accumulator of each thread to the final result\r\n     * which contains the sum of all accumulators. \r\n     *\r\n     */\r\n    struct asynchronous_results_merger : \r\n      details::threading::asynchronous_results_merger<\r\n        data_t,\r\n        details::merger_update_specific_dimension<data_t>,\r\n        details::threading::initialisation_vector_specific_dimension<data_t>,\r\n        details::s_dimension_update<typename data_t::value_type>\r\n      >\r\n    {\r\n    public:\r\n      typedef data_t result_t;\r\n\r\n    private:\r\n      typedef details::threading::initialisation_vector_specific_dimension<data_t> data_init_type;\r\n      typedef details::merger_update_specific_dimension<data_t> merger_type;\r\n\r\n\r\n      const size_t data_dimension;\r\n      \r\n    public:\r\n      typedef details::threading::asynchronous_results_merger<\r\n        result_t,\r\n        merger_type, \r\n        data_init_type,\r\n        details::s_dimension_update<typename data_t::value_type>\r\n      > parent_type;\r\n      typedef typename parent_type::lock_t lock_t;\r\n\r\n      /*!Constructor\r\n       *\r\n       * @param dimension_ the number of dimensions of the vector to accumulate\r\n       */\r\n      asynchronous_results_merger(size_t data_dimension_) : \r\n        parent_type(data_init_type(data_dimension_)),\r\n        data_dimension(data_dimension_)\r\n      {}\r\n\r\n    };\r\n\r\n\r\n\r\n\r\n\r\n  public:\r\n    /*!@brief Constructor\r\n     *\r\n     * Constructs an instance of the RobustPCA with trimming with the provided percentage of trimming.\r\n     *\r\n     * @param[in] trimming_percentage_ the percentage of data that should be trimmed from the lower and upper distributions.\r\n     * @note By default the number of processors used for computation is set to 1.\r\n     * The maximum size of the chunks is \"infinite\": each chunk will receive in that case the size of the data\r\n     * divided by the number of running threads.\r\n     */\r\n    grassmann_pca_with_trimming(double trimming_percentage_ = 0) :\r\n      random_init_op(details::fVerySmallButStillComputable, details::fVeryBigButStillComputable),\r\n      trimming_percentage(trimming_percentage_),\r\n      nb_processors(1),\r\n      max_chunk_size(std::numeric_limits<size_t>::max()),\r\n      nb_steps_pca(3),\r\n      need_centering(false),\r\n      observer(0)\r\n    {\r\n      assert(trimming_percentage_ >= 0 && trimming_percentage_ <= 1);\r\n    }\r\n\r\n\r\n    //! Sets the observer of the algorithm. \r\n    //!\r\n    //! The lifetime of the observer is not managed by this class. Set to 0 to disable\r\n    //! observation.\r\n    bool set_observer(observer_t* observer_)\r\n    {\r\n      observer = observer_;\r\n      return true;\r\n    }\r\n\r\n\r\n    //! Sets the number of parallel tasks used for computing.\r\n    bool set_nb_processors(size_t nb_processors_)\r\n    {\r\n      assert(nb_processors_ >= 1);\r\n      nb_processors = nb_processors_;\r\n      return true;\r\n    }\r\n    \r\n    /*!@brief Sets the maximum chunk size. \r\n     *\r\n     * By default, the chunk size is the size of the data divided by the number of processing threads.\r\n     * Lowering the chunk size should provid better granularity in the overall processing time at the end \r\n     * of the processing.\r\n     */\r\n    bool set_max_chunk_size(size_t chunk_size)\r\n    {\r\n      if(chunk_size == 0)\r\n      {\r\n        return false;\r\n      }\r\n      max_chunk_size = chunk_size;\r\n      return true;\r\n    }\r\n\r\n    //! Sets the number of iterations for the initial PCA like algorithm. \r\n    bool set_nb_steps_pca(size_t nb_steps)\r\n    {\r\n      nb_steps_pca = nb_steps;\r\n      return true;\r\n    }\r\n\r\n    //! Sets the centering flags.\r\n    //!\r\n    //! If set to true, a centering will be performed before applying any computation (PCA and Grassmann averages). \r\n    bool set_centering(bool need_centering_)\r\n    {\r\n      need_centering = need_centering_;\r\n      return true;\r\n    }\r\n\r\n    \r\n    \r\n\r\n\r\n    /*!@brief Performs the computation of the current subspace on the elements given by the two iterators.\r\n     *\r\n     * @tparam it_t an input forward iterator to input vectors points. Each element pointed by the underlying iterator should be iterable and\r\n     *   should provide a vector point.\r\n     * @tparam it_o_basisvectors_t an output iterator for storing the computed basis vectors. This iterator should model a forward output iterator.\r\n     *\r\n     * @param[in] max_iterations the maximum number of iterations at each dimension.\r\n     * @param[in] max_dimension_to_compute the maximum number of data_dimension to compute in the PCA (only the first max_dimension_to_compute will be\r\n     *            computed).\r\n     * @param[in] it input iterator at the beginning of the data\r\n     * @param[in] ite input iterator at the end of the data\r\n     * @param[in] initial_guess if provided, the initial vectors will be initialized to this value.\r\n     * @param[out] it_basisvectors an iterator on the beginning of the area where the detected basis vectors will be stored. The space should be at least max_dimension_to_compute.\r\n     *\r\n     * @returns true on success, false otherwise\r\n     * @pre\r\n     * - @c !(it >= ite)\r\n     * - all the vectors given by the iterators pair should be of the same size (no check is performed).\r\n     */\r\n    template <class it_t, class it_o_basisvectors_t>\r\n    bool batch_process(\r\n      const size_t max_iterations,\r\n      size_t max_dimension_to_compute,\r\n      it_t const it,\r\n      it_t const ite,\r\n      it_o_basisvectors_t it_basisvectors,\r\n      std::vector<data_t> const * initial_guess = 0)\r\n    {\r\n      // add some log information\r\n      if(it >= ite)\r\n      {\r\n        return false;\r\n      }\r\n\r\n\r\n      // preparing the thread pool, to avoid individual thread creation/deletion at each step.\r\n      // we perform the init here because it might take some time for the thread to really start.\r\n      boost::asio::io_service ioService;\r\n      boost::thread_group threadpool;\r\n\r\n\r\n      // in case of non clean exit (or even in case of clean one).\r\n      details::threading::safe_stop worker_lock_guard(ioService, threadpool);\r\n\r\n\r\n      // this is exactly the number of processors\r\n      boost::asio::io_service::work work(ioService);\r\n      for(int i = 0; i < nb_processors; i++)\r\n      {\r\n        threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));\r\n      }\r\n\r\n\r\n      // contains the number of elements. In case the iterator is random access, could be deduced simply \r\n      // by a call to distance.\r\n      const size_t size_data(std::distance(it, ite));\r\n\r\n      // size of the chunks.\r\n      const size_t chunks_size = std::min(max_chunk_size, static_cast<size_t>(ceil(double(size_data)/nb_processors)));\r\n      const size_t nb_chunks = (size_data + chunks_size - 1) / chunks_size;\r\n\r\n\r\n      // number of dimensions of the data vectors\r\n      const size_t number_of_dimensions = it->size();\r\n      max_dimension_to_compute = std::min(max_dimension_to_compute, number_of_dimensions);\r\n\r\n\r\n      // initial iterator on the output basis vectors\r\n      it_o_basisvectors_t const it_output_basis_vector_beginning(it_basisvectors);\r\n      it_o_basisvectors_t it_output_basis_vector_end(it_output_basis_vector_beginning);\r\n      std::advance(it_output_basis_vector_end, max_dimension_to_compute);\r\n\r\n      // the initialisation of mus\r\n      {\r\n        it_o_basisvectors_t it_basis(it_output_basis_vector_beginning);\r\n        for(int i = 0; it_basis != it_output_basis_vector_end; ++it_basis, ++i)\r\n        {\r\n          *it_basis = initial_guess != 0 ? (*initial_guess)[i] : random_init_op(*it);\r\n        }\r\n      }\r\n      if(!details::gram_schmidt_orthonormalisation(it_output_basis_vector_beginning, it_output_basis_vector_end, it_output_basis_vector_beginning, norm_op))\r\n      {\r\n        return false;\r\n      }\r\n\r\n\r\n      // preparing mu\r\n      data_t mu(*it_basisvectors);\r\n      assert(mu.size() == number_of_dimensions);\r\n      \r\n\r\n\r\n      // number of elements to remove, lower bound\r\n      const int K_elements = static_cast<int>(trimming_percentage*size_data/2);\r\n\r\n\r\n      // preparing the ranges on which each processing thread will run.\r\n      // the number of objects can be much more than the current number of processors, in order to\r\n      // avoid waiting too long for a thread (better granularity) but involving a slight overhead in memory and\r\n      // processing at the synchronization point.\r\n      typedef s_grassmann_averages_trimmed_processor_inner_products async_processor_t;\r\n      std::vector<async_processor_t> v_individual_accumulators(nb_chunks);\r\n\r\n      asynchronous_results_merger async_merger(number_of_dimensions);\r\n\r\n\r\n      {\r\n        it_t it_current_begin(it);\r\n        for(int i = 0; i < nb_chunks; i++)\r\n        {\r\n          // setting the range\r\n          it_t it_current_end;\r\n          if(i == nb_chunks - 1)\r\n          {\r\n            // just in case the division giving the chunk has some rounding (the parenthesis are important\r\n            // otherwise it is a + followed by a -, which can be out of range after the first +)\r\n            it_current_end = it_current_begin + (size_data - chunks_size*(nb_chunks - 1));\r\n          }\r\n          else\r\n          {\r\n            it_current_end = it_current_begin + chunks_size;\r\n          }\r\n\r\n          // the processor object for this new range\r\n          async_processor_t &current_acc_object = v_individual_accumulators[i];\r\n\r\n          // updating the dimension of the problem\r\n          current_acc_object.set_data_dimensions(number_of_dimensions);\r\n\r\n          // setting the number of elements to remove\r\n          current_acc_object.set_nb_elements_to_remove(K_elements);\r\n\r\n          // attaching the update object callbacks\r\n          current_acc_object.connector_accumulator() = boost::bind(\r\n              &asynchronous_results_merger::update, \r\n              &async_merger, \r\n              _1);\r\n\r\n          current_acc_object.connector_counter() = boost::bind(&asynchronous_results_merger::notify, &async_merger);\r\n\r\n\r\n          //bool b_result = current_acc_object.set_data_range(it_current_begin, it_current_end);\r\n          //if(!b_result)\r\n          //{\r\n          //  return b_result;\r\n          //}\r\n          \r\n          // pushing the asynchronous copy, which saves a lot of time when loading \r\n          // data lazily from disk\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::template set_data_range<it_t>, \r\n              boost::ref(v_individual_accumulators[i]), \r\n              it_current_begin, it_current_end));\r\n\r\n          // updating the next \r\n          it_current_begin = it_current_end;\r\n        }\r\n        \r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n      }\r\n\r\n\r\n\r\n\r\n      // this matrix is a copy of the data. It is a convenient structure for storing the \r\n      // flipped vectors that will then be trimmed and accumulated. But this is a copy of the initial data:\r\n      // if the memory pressure is too big, then something else should be found (like a vector of vector, being\r\n      // potentially scattered in memory).\r\n      boost::scoped_array<scalar_t> matrix_temp(new scalar_t[number_of_dimensions*size_data]);\r\n\r\n\r\n\r\n\r\n      // Centering the data if needed: \r\n      // - first run the accumulation and gather all results in a multithreaded manner\r\n      // - second center the data with the collected mean\r\n      if(need_centering)\r\n      {\r\n        // Computing the accumulation\r\n        async_merger.init();\r\n\r\n        for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n        {\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::data_centering_first_phase, \r\n              boost::ref(v_individual_accumulators[i]),\r\n              size_data)); // size of the dataset to perform division and avoid doing accumulation over big numerical values\r\n        }\r\n\r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n        // gathering the accumulated, already divided by the size \r\n        data_t mean_vector = async_merger.get_merged_result();\r\n\r\n        // sending result to observer\r\n        if(observer)\r\n        {\r\n          observer->signal_mean(mean_vector);\r\n        }\r\n\r\n\r\n        // centering the data\r\n        async_merger.init();\r\n\r\n        for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n        {\r\n          ioService.post(\r\n            boost::bind(\r\n              &async_processor_t::data_centering_second_phase, \r\n              boost::ref(v_individual_accumulators[i]),\r\n              boost::cref(mean_vector)\r\n              ));\r\n        }\r\n\r\n        // waiting for completion (barrier)\r\n        async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n\r\n      }\r\n\r\n\r\n\r\n\r\n\r\n      // for each requested subspace\r\n      for(int current_subspace_index = 0; current_subspace_index < max_dimension_to_compute; current_subspace_index++, ++it_basisvectors)\r\n      {\r\n\r\n\r\n        // PCA like initial steps\r\n        if(nb_steps_pca)\r\n        {\r\n          for(size_t pca_it = 0; pca_it < nb_steps_pca; pca_it++)\r\n          {\r\n            // reseting the final accumulator\r\n            async_merger.init();\r\n\r\n            // pushing the initialisation of the mu and sign vectors to the pool\r\n            for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n            {\r\n              ioService.post(\r\n                boost::bind(\r\n                  &async_processor_t::pca_accumulation, \r\n                  boost::ref(v_individual_accumulators[i]), \r\n                  boost::cref(mu)));\r\n            }\r\n\r\n            // waiting for completion (barrier)\r\n            async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n            // gathering the first mu\r\n            mu = async_merger.get_merged_result();\r\n            double norm_mu = norm_op(mu);\r\n            if(norm_mu < 1E-12)\r\n            {\r\n              if(observer)\r\n              {\r\n                std::ostringstream o;\r\n                o << \"The result of the PCA is null for subspace \" << current_subspace_index;\r\n                observer->log_error_message(o.str().c_str());\r\n              }\r\n              return false;\r\n            }\r\n            mu *= typename data_t::value_type(1./norm_mu);\r\n          }\r\n\r\n          // sending result to observer\r\n          if(observer)\r\n          {\r\n            observer->signal_pca(mu, current_subspace_index);\r\n          }\r\n        }\r\n\r\n\r\n\r\n\r\n        details::convergence_check<data_t> convergence_op(mu);\r\n\r\n        int iterations = 0;\r\n        for(; (!convergence_op(mu) && iterations < max_iterations) || iterations == 0; iterations++)\r\n        {\r\n\r\n          // reseting the merger object\r\n          async_merger.init();\r\n\r\n          // pushing the computation of the bounds\r\n          for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n          {\r\n            ioService.post(\r\n              boost::bind(\r\n                &async_processor_t::compute_data_matrix, \r\n                boost::ref(v_individual_accumulators[i]), \r\n                boost::cref(mu),\r\n                matrix_temp.get() + i*chunks_size,\r\n                size_data));\r\n          }\r\n\r\n\r\n          // waiting for completion (barrier)\r\n          async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n          // clearing the notifications\r\n          async_merger.init_notifications();\r\n\r\n          // pushing the computation of the trimmed accumulation on each dimension\r\n          for(int dim_to_compute = 0; dim_to_compute < number_of_dimensions; dim_to_compute++)\r\n          {\r\n            ioService.post(\r\n              boost::bind(\r\n                &async_processor_t::compute_bounded_accumulation, \r\n                boost::ref(v_individual_accumulators[0]), \r\n                dim_to_compute,\r\n                size_data,\r\n                matrix_temp.get() + dim_to_compute*size_data));\r\n          }\r\n\r\n\r\n          // waiting for completion (barrier)\r\n          async_merger.wait_notifications(number_of_dimensions);\r\n          \r\n\r\n          // gathering the mus\r\n          mu = async_merger.get_merged_result();\r\n          \r\n          // normalize mu on the sphere\r\n          mu *= typename data_t::value_type(1./norm_op(mu));\r\n\r\n          // sending result to observer\r\n          if(observer)\r\n          {\r\n            observer->signal_intermediate_result(mu, current_subspace_index, iterations);\r\n          }\r\n\r\n        }\r\n\r\n\r\n\r\n        // orthogonalisation against previous basis vectors\r\n        bool renormalise(false);\r\n        for(it_o_basisvectors_t it_mus(it_output_basis_vector_beginning); it_mus < it_basisvectors; ++it_mus)\r\n        {\r\n          mu -= boost::numeric::ublas::inner_prod(mu, *it_mus) * (*it_mus);\r\n          renormalise = true;\r\n        }\r\n        if(renormalise)\r\n        {\r\n          double norm_mu = norm_op(mu);\r\n          if(norm_mu < 1E-12)\r\n          {\r\n            if(observer)\r\n            {\r\n              std::ostringstream o;\r\n              o << \"The result of the subspace computation is null (subspace \" << current_subspace_index << \")\";\r\n              observer->log_error_message(o.str().c_str());\r\n            }\r\n            return false;\r\n          }\r\n\r\n          mu *= typename data_t::value_type(1./norm_mu);\r\n        }\r\n        \r\n\r\n        // mu is the basis vector of the current dimension, we store it in the output vector\r\n        *it_basisvectors = mu;\r\n\r\n\r\n        // sending result to observer\r\n        if(observer)\r\n        {\r\n          observer->signal_eigenvector(*it_basisvectors, current_subspace_index);\r\n        }\r\n\r\n\r\n        // projection onto the orthogonal subspace\r\n        if(current_subspace_index < max_dimension_to_compute - 1)\r\n        {\r\n          async_merger.init_notifications();\r\n\r\n          // pushing the update of the mu (and signs)\r\n          for(int i = 0; i < v_individual_accumulators.size(); i++)\r\n          {\r\n\r\n\t\t\t      ioService.post(\r\n\t\t\t\t      boost::bind(\r\n\t\t\t\t\t      &async_processor_t::template project_onto_orthogonal_subspace<typename it_o_basisvectors_t::value_type>,\r\n\t\t\t\t\t      boost::ref(v_individual_accumulators[i]),\r\n\t\t\t\t\t      *it_basisvectors)); // this is not mu, since we are changing it before the process ends here\r\n          }\r\n\r\n          // this is to follow the matlab implementation, but the idea is the following:\r\n          // each time we pick a new candidate vector, we project it to the orthogonal subspace of the previously computed \r\n          // basis vectors. This can be done in two ways:\r\n          // 1. compute the projection on the orthogonal subspace of the current (or next) candidate\r\n          // 2. compute the projection on the orthogonal subspace of the remainder elements\r\n          //\r\n          // in order to be consistent with the matlab implementation, the second choice is implemented here\r\n          if(current_subspace_index+1 < max_dimension_to_compute)\r\n          {\r\n            it_o_basisvectors_t remainder(it_basisvectors);\r\n            ++remainder;\r\n\r\n            if(!details::gram_schmidt_orthonormalisation(it_output_basis_vector_beginning, it_output_basis_vector_end, remainder, norm_op))\r\n            {\r\n              return false;\r\n            }\r\n\r\n            mu = *remainder;\r\n          }\r\n\r\n\r\n          // wait for the workers\r\n          async_merger.wait_notifications(v_individual_accumulators.size());\r\n\r\n          \r\n        }\r\n\r\n      }\r\n\r\n      return true;\r\n    }\r\n\r\n  };\r\n\r\n}\r\n\r\n\r\n#endif /* GRASSMANN_AVERAGES_PCA_TRIMMED_HPP__ */\r\n", "meta": {"hexsha": "526506716fc1d8c7f4babea5587883ff358dae92", "size": 36009, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/grassmann_pca_with_trimming.hpp", "max_stars_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_stars_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-07-15T11:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T01:47:55.000Z", "max_issues_repo_path": "include/grassmann_pca_with_trimming.hpp", "max_issues_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_issues_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-11-20T11:08:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-01T17:40:30.000Z", "max_forks_repo_path": "include/grassmann_pca_with_trimming.hpp", "max_forks_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_forks_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-11T12:33:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:51:49.000Z", "avg_line_length": 36.6690427699, "max_line_length": 185, "alphanum_fraction": 0.6180677053, "num_tokens": 7875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5658118633478532}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"gradient.hpp\"\n#include \"hllc.hpp\"\n#include \"mesh.hpp\"\n#include \"slope_limiter.hpp\"\n\n// Note: this class will compute the rate of change due to the fluxes.\n// Note: the reason we made this a class is that it allows you to allocate\n//       buffers, once at the beginning of the simulation. Add these buffers\n//       as needed.\nclass FluxRateOfChange {\n  public:\n    explicit FluxRateOfChange(int n_cells) : n_cells(n_cells) {}\n\n    void operator()(Eigen::MatrixXd &dudt,\n                    const Eigen::MatrixXd &u,\n                    const Mesh &mesh) const\n    {\n        // Compute the rate of change of u.\n        // Note: Please use the method `computeFlux` to abstract\n        // away the details of computing the flux through a\n        // given interface.\n        // Note: You can use `assert_valid_flux` to check\n        // if what `computeFlux` returns makes any sense.\n        // Note: Do not assume `dudt` is filled with zeros.\n\n        // sanity check:\n        assert ((mesh.getNumberOfTriangles() == n_cells));\n        \n        // reset dudt to zero:\n        dudt*= 0.0;\n\n        // iterate over cells then over the 3 edges within each cell:\n        for (int i= 0; i < n_cells; ++i)\n            for (int k= 0; k < 3; ++k)\n            {\n                EulerState edge_flux= computeFlux(u, i, k, mesh);\n                assert_valid_flux(mesh, i, k, edge_flux);\n                dudt.row(i)+= edge_flux;\n            }\n    }\n\n    void assert_valid_flux(const Mesh &mesh,\n                           int i,\n                           int k,\n                           const EulerState &nF) const {\n        // This is mostly for debugging (but also important to check in\n        // real simulations!): Make sure our flux contribution is not\n        // nan (ie. it is not not a number, ie it is a number)\n        if (!euler::isValidFlux(nF)) {\n            // clang-format off\n            throw std::runtime_error(\n                \"invalid value detected in numerical flux, \" + euler::to_string(nF)\n                + \"\\nat triangle: \" + std::to_string(i)\n                + \"\\nedge:        \" + std::to_string(k)\n                + \"\\nis_boundary: \" + std::to_string(!mesh.isValidNeighbour(i, k)));\n            // clang-format on\n        }\n    }\n\n    /// Compute the flux through the k-th interface of cell i.\n    EulerState computeFlux(const Eigen::MatrixXd &U,\n                           int i,\n                           int k,\n                           const Mesh &mesh) const\n    {\n        auto boundary_type = mesh.getBoundaryType(i, k);\n\n        if (boundary_type == Mesh::BoundaryType::INTERIOR_EDGE)\n        {\n            return computeInteriorFlux(U, i, k, mesh);\n        }\n        else\n        {\n            if (boundary_type == Mesh::BoundaryType::OUTFLOW_EDGE)\n            {\n                return computeOutflowFlux(U, i, k, mesh);\n            }\n            else /* boundary_type == Mesh::BoundaryType::WING_EDGE */\n            {\n                return computeReflectiveFlux(U, i, k, mesh);\n            }\n        }\n    }\n\n    /// Compute the outflow flux through the k-th interface of cell i.\n    /** Note: you know that edge k is an outflow edge.\n     */\n    EulerState computeOutflowFlux(const Eigen::MatrixXd &U,\n                                  int i,\n                                  int k,\n                                  const Mesh &mesh) const\n    {\n        // Implement the outflow flux boundary condition.\n        auto u_aligned= rotate_align(U.row(i), i, k, mesh);\n\n        auto f_aligned= euler::flux(u_aligned);\n\n        auto f= rotate_dealign(f_aligned, i, k, mesh);\n\n        return mesh.getEdgeLength(i, k) * f; // eqn (35)\n    }\n\n    /// Compute the reflective boundary flux through the k-th edge of cell i.\n    /** Note: you know that edge k is a reflective/wall boundary edge.\n     */\n    EulerState computeReflectiveFlux(const Eigen::MatrixXd &U,\n                                     int i,\n                                     int k,\n                                     const Mesh &mesh) const\n    {\n        // Implement the reflective flux boundary condition.\n        auto u= U.row(i);\n\n        // get unit outward normal and transverse t:\n        auto n= mesh.getUnitNormal(i, k).normalized();\n        auto t= Eigen::Vector2d(-n(1), n(0));\n\n        // assemble u_star:\n        double rho= u[0];\n        Eigen::Vector2d v= u.segment(1, 2);\n        double E= u[3];\n\n        EulerState u_star;\n        u_star[0]=  rho;\n        u_star.segment(1, 2)= -rho * v.dot(n) * n + rho * v.dot(t) * t;\n        u_star[3]=  E;\n\n        // rotate:\n        auto u_aligned= rotate_align(u, i, k, mesh);\n        auto u_star_aligned= - rotate_align(u_star, i, k, mesh); // (-) for reflection\n        \n        // flux:\n        auto f_aligned= hllc(u_aligned, u_star_aligned); // equation (36)\n\n        // derotate:\n        auto f= rotate_dealign(f_aligned, i, k, mesh);\n        \n        return mesh.getEdgeLength(i, k) * f;\n    }\n\n    /// Compute the flux through the k-th interface of cell i.\n    /** Note: This edge is an interior edge, therefore approximate the flux\n     * through this edge with the appropriate FVM formulas.\n     */\n    EulerState computeInteriorFlux(const Eigen::MatrixXd &U,\n                                   int i,\n                                   int k,\n                                   const Mesh &mesh) const\n    {\n        // Reconstruct the trace values of U and compute\n        // the numerical flux through the k-th interface of\n        // cell i.\n\n        // figure out neighbour of i at edge k and check validity:\n        int j= mesh.getNeighbour(i, k);\n        assert(j >= 0);\n\n        // figure out neighbour j's edge l collocated with i's edge k:\n        int l= mesh.getNeighbourEdge(i, k);\n\n        // reconstruction:\n        auto uL= reconstruction(U.row(i), i, k, mesh);\n        auto uR= reconstruction(U.row(j), j, l, mesh);\n\n        // rotate:\n        auto uL_aligned=   rotate_align(uL, i, k, mesh);\n        auto uR_aligned= - rotate_align(uR, j, l, mesh);\n\n        // flux:\n        auto f_aligned= hllc(uL_aligned, uR_aligned); // equation (32)\n\n        // derotate:\n        auto f= rotate_dealign(f_aligned, i, k, mesh);\n        \n        return mesh.getEdgeLength(i, k) * f;\n    }\n\n\n    private:\n        // generate rotation matrix to align edge k of triangle i with cartesian y-axis:\n        Eigen::Matrix2d rot(int i, int k, const Mesh& mesh) const\n        {\n            auto n= mesh.getUnitNormal(i, k).normalized(); // why is this called UnitNormal if it's not unit normalized?\n\n            Eigen::Matrix2d rot;\n            rot << n(0),  n(1),\n                  -n(1),  n(0);\n\n            return rot;\n        }\n\n        // generate inverse rotation matrix to DEalign edge k of triangle i from cartesian y-axis back to original position:\n        Eigen::Matrix2d rot_inv(int i, int k, const Mesh& mesh) const\n        {\n            // our rotation matrix is orthogonal: RR'=I:\n            return rot(i, k, mesh).transpose();\n        }\n\n        // rotate u to align velocity component [u(1), u(2)] with cartesian x-axis:\n        EulerState rotate_align(EulerState u, int i, int k, const Mesh& mesh) const\n        {\n            u.segment(1, 2)= rot(i, k, mesh) * u.segment(1, 2);\n            return u;\n        }\n\n        // rotate calculated f back to point in original grid position before rotation:\n        EulerState rotate_dealign(EulerState f, int i, int k, const Mesh& mesh) const\n        {\n            f.segment(1, 2)= rot_inv(i, k, mesh) * f.segment(1, 2);\n        }\n\n        // arggh there's probably no time for doing piecewise linear construction in task 2h)\n        EulerState reconstruction(const Eigen::MatrixXd& U, int i, int k, const Mesh& mesh) const\n        {\n            // pass:\n            return U.row(i);\n        }\n\n        int n_cells;\n};\n", "meta": {"hexsha": "8b1a31c70b40aeb86e2057c2569892a14f54e700", "size": 7902, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/unstructured_euler/numerical_flux.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/unstructured_euler/numerical_flux.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/unstructured_euler/numerical_flux.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 35.12, "max_line_length": 124, "alphanum_fraction": 0.539989876, "num_tokens": 1880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673223709251, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5657217852777853}}
{"text": "// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors.\r\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\r\n\r\n/**\r\n * @author Alexander Silva Barbosa <alexander.ti.ufv@gmail.com>\r\n * @date 2019\r\n * Extended Kalman Filter\r\n */\r\n\r\n#pragma once\r\n\r\n#include <Eigen/Dense>\r\n#include <random>\r\n#include <chrono>\r\n#include <thread>\r\n#include <vector>\r\n\r\nusing namespace Eigen;\r\n\r\ntemplate <typename dataType, int states, int inputs, int outputs, int dataConverter = -1>\r\nclass EKF\r\n{\r\n    private:\r\n        typedef Matrix<dataType, states, 1> MatNx1;\r\n        typedef Matrix<dataType, states, states> MatNxN;\r\n        typedef Matrix<dataType, states, inputs> MatNxM;\r\n        typedef Matrix<dataType, states, outputs> MatNxP;\r\n        typedef Matrix<dataType, outputs, states> MatPxN;\r\n        typedef Matrix<dataType, outputs, outputs> MatPxP;\r\n        typedef Matrix<dataType, inputs, 1> MatMx1;\r\n        typedef Matrix<dataType, outputs, 1> MatPx1;\r\n        typedef Matrix<dataType, dataConverter, 1> MatDx1;\r\n        typedef Matrix<dataType, 3, 1> Mat3x1;\r\n\r\n    public:\r\n        typedef MatNx1 State;\r\n        typedef MatMx1 Input;\r\n        typedef MatPx1 Output;\r\n        typedef Input Control;\r\n        typedef Output Sensor;\r\n        typedef MatNxN ModelCovariance;\r\n        typedef MatPxP SensorCovariance;\r\n        typedef MatNxN StateMatrix;\r\n        typedef MatNxM InputMatrix;\r\n        typedef MatPxN OutputMatrix;\r\n        typedef MatNxN ModelJacobian;\r\n        typedef MatPxN SensorJacobian;\r\n        typedef MatDx1 Data;\r\n        typedef Data Landmark;\r\n        typedef Mat3x1 Uncertainty;\r\n\r\n    private:\r\n        typedef void (*ModelFunction)(State &x, Input &u, double dt);\r\n        typedef void (*SensorFunction)(Output &y, State &x, Data &d, double dt);\r\n        typedef void (*ModelJacobianFunction)(ModelJacobian &F, State &x, Input &u, double dt);\r\n        typedef void (*SensorJacobianFunction)(SensorJacobian &H, State &x, Data &d, double dt);\r\n\r\n        std::default_random_engine gen;\r\n        std::normal_distribution<double> distr{0.0, 1.0};\r\n        std::chrono::time_point<std::chrono::high_resolution_clock> start;\r\n\r\n        State x, x_1;\r\n        ModelCovariance Q;\r\n        SensorCovariance R;\r\n        Output z;\r\n\r\n        ModelJacobian F;\r\n        SensorJacobian H;\r\n\r\n        std::vector<Data> dataPoints;\r\n    \r\n        MatNx1 randX;\r\n        MatPx1 randY;\r\n\r\n        MatNxN P;\r\n        MatNxN Qsqrt;\r\n        MatPxP Rsqrt;\r\n\r\n        MatPxP S;\r\n        MatNxP K;\r\n        MatNxN I;\r\n\r\n        ModelFunction modelFn;\r\n        SensorFunction sensorFn;\r\n        ModelJacobianFunction modelJFn;\r\n        SensorJacobianFunction sensorJFn;\r\n\r\n        void init()\r\n        {\r\n            modelFn = NULL;\r\n            sensorFn = NULL;\r\n            modelJFn = NULL;\r\n            sensorJFn = NULL;\r\n\r\n            P = Q;\r\n            I.setIdentity();\r\n\r\n            Qsqrt = Q.cwiseSqrt();\r\n            Rsqrt = R.cwiseSqrt();\r\n\r\n            start = std::chrono::high_resolution_clock::now();\r\n        }\r\n    public:\r\n\r\n        EKF()\r\n        {\r\n            Q.setIdentity();\r\n            R.setIdentity();\r\n            x.setZero();\r\n            init();\r\n        }\r\n\r\n        EKF(State X) : x(X)\r\n        {\r\n            Q.setIdentity();\r\n            R.setIdentity();\r\n            init();\r\n        }\r\n\r\n        EKF(ModelCovariance Q, SensorCovariance R) : Q(Q), R(R)\r\n        {\r\n            x.setZero();\r\n            init();\r\n        }\r\n\r\n        EKF(State X, ModelCovariance Q, SensorCovariance R) : x(X), Q(Q), R(R)\r\n        {\r\n            init();\r\n        }\r\n\r\n        virtual ~EKF()\r\n        {\r\n\r\n        }\r\n\r\n        long long seed()\r\n        {\r\n            long long s = std::chrono::system_clock::now().time_since_epoch().count();\r\n            return seed(s);\r\n        }\r\n\r\n        long long seed(long long s)\r\n        {\r\n            gen = std::default_random_engine(s);\r\n            return s;\r\n        }\r\n\r\n        State state()\r\n        {\r\n            MatNx1 x;\r\n            x.setZero();\r\n            return x;\r\n        }\r\n\r\n        Input input()\r\n        {\r\n            MatMx1 u;\r\n            u.setZero();\r\n            return u;\r\n        }\r\n\r\n        Output output()\r\n        {\r\n            MatPx1 y;\r\n            y.setZero();\r\n            return y;\r\n        }\r\n\r\n        ModelCovariance createQ()\r\n        {\r\n            ModelCovariance Q;\r\n            Q.setZero();\r\n            return Q;\r\n        }\r\n\r\n        SensorCovariance createR()\r\n        {\r\n            SensorCovariance R;\r\n            R.setZero();\r\n            return R;\r\n        }\r\n\r\n        Data createData()\r\n        {\r\n            Data D;\r\n            D.setZero();\r\n            return D;\r\n        }\r\n\r\n        ModelCovariance getP()\r\n        {\r\n            return P;\r\n        }\r\n\r\n        Uncertainty getUncertainty(unsigned int x1, unsigned int x2)\r\n        {\r\n            Uncertainty C;\r\n            C.setZero();\r\n            if(x1 >= states || x2 >= states)\r\n                return C;\r\n            \r\n            Matrix<dataType, 2, 2> p;\r\n            p(0, 0) = P(x1, x1);\r\n            p(0, 1) = P(x1, x2);\r\n            p(1, 0) = P(x2, x1);\r\n            p(1, 1) = P(x2, x2);\r\n\r\n            EigenSolver< Matrix<dataType, 2, 2> > es(p);\r\n            Matrix<dataType, 2, 2> eValue = es.pseudoEigenvalueMatrix();\r\n            Matrix<dataType, 2, 2> eVector = es.pseudoEigenvectors();\r\n\r\n            C[0] = eValue(0,0);\r\n            C[1] = eValue(1,1);\r\n            C[2] = std::atan2(eVector(0, 1), eVector(0, 0));\r\n\r\n            return C;\r\n        }\r\n\r\n        void setQ(ModelCovariance Q)\r\n        {\r\n            this->Q = Q;\r\n            P = Q;\r\n            Qsqrt = Q.cwiseSqrt();\r\n        }\r\n\r\n        void setR(SensorCovariance R)\r\n        {\r\n            this->R = R;\r\n            Rsqrt = R.cwiseSqrt();\r\n        }\r\n\r\n        double time()\r\n        {\r\n            auto end = std::chrono::high_resolution_clock::now();\r\n            std::chrono::duration<double> diff = end - start;\r\n            start = std::chrono::high_resolution_clock::now();\r\n            return diff.count();\r\n        }\r\n\r\n        double delay(double s)\r\n        {\r\n            double ellapsed = time();\r\n            double remain = s - ellapsed;\r\n            if(remain < 0)\r\n                return ellapsed;\r\n            std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9)));\r\n            ellapsed += time();\r\n            return ellapsed;\r\n        }\r\n\r\n        void addData(Data &data)\r\n        {\r\n            dataPoints.push_back(data);\r\n        }\r\n\r\n        void fillData(std::vector<Data> &data)\r\n        {\r\n            dataPoints = data;\r\n        }\r\n\r\n        std::vector<Data>& data()\r\n        {\r\n            return dataPoints;\r\n        }\r\n\r\n        void setModel(ModelFunction fn)\r\n        {\r\n            modelFn = fn;\r\n        }\r\n\r\n        void setSensor(SensorFunction fn)\r\n        {\r\n            sensorFn = fn;\r\n        }\r\n\r\n        void setModelJacobian(ModelJacobianFunction fn)\r\n        {\r\n            modelJFn = fn;\r\n        }\r\n\r\n        void setSensorJacobian(SensorJacobianFunction fn)\r\n        {\r\n            sensorJFn = fn;\r\n        }\r\n\r\n        virtual void model(State &x, Input &u, double dt)\r\n        {\r\n\r\n        }\r\n\r\n        virtual void sensor(Output &z, State &x, Data &d, double dt)\r\n        {\r\n\r\n        }\r\n\r\n        virtual void modelJacobian(ModelJacobian &F, State &x, Input &u, double dt)\r\n        {\r\n\r\n        }\r\n\r\n        virtual void sensorJacobian(SensorJacobian &H, State &x, Data &d, double dt)\r\n        {\r\n\r\n        }\r\n\r\n        void simulate(State &x, Output &y, Input &u, double dt)\r\n        {\r\n            Data data;\r\n            randn(data);\r\n\r\n            if(dataPoints.size() > 0)\r\n                data = dataPoints[0];\r\n\r\n            doModel(x, u, dt);\r\n            randn(randX);\r\n            x = x + Qsqrt * randX;\r\n\r\n            doSensor(y, x, data, dt);            \r\n            randn(randY);\r\n            y = y + Rsqrt * randY;\r\n        }\r\n\r\n        void simulate(State &x, std::vector<Output> &y, Input &u, double dt)\r\n        {\r\n            doModel(x, u, dt);\r\n            randn(randX);\r\n            x = x + Qsqrt * randX;\r\n            \r\n            int j = 0, index = 0;\r\n            if(dataPoints.size() == 0)\r\n                j = -1;\r\n\r\n            MatDx1 data;\r\n            for(int i = 0; i < y.size(); i++)\r\n            {\r\n                if(j == -1)\r\n                {\r\n                    randn(data);\r\n                    doSensor(y[i], x, data, dt);\r\n                }\r\n                else\r\n                {\r\n                    doSensor(y[i], x, dataPoints[j], dt);\r\n                    j = rand() % dataPoints.size();\r\n                }\r\n                randn(randY);\r\n                y[i] = y[i] + Rsqrt * randY;\r\n            }\r\n        }\r\n\r\n        void run(State &xK, Output &y, Input &u, double dt)\r\n        {\r\n            predict(u, dt);\r\n\r\n            std::vector<MatDx1> data(1);\r\n            std::vector<MatPx1> ys(1);\r\n            ys[0] = y;\r\n            dataAssoc(ys, data, dt);\r\n\r\n            update(y, data[0], dt);\r\n            xK = x;\r\n        }\r\n\r\n        void run(State &xK, std::vector<Output> &y, Input &u, double dt)\r\n        {\r\n            predict(u, dt);\r\n\r\n            if(y.size() > 0)\r\n            {\r\n                std::vector<MatDx1> data(y.size());\r\n                dataAssoc(y, data, dt);\r\n\r\n                for(int i = 0; i < y.size(); i++)\r\n                    update(y[i], data[i], dt);\r\n            }\r\n            xK = x;\r\n        }\r\n\r\n    private:\r\n        void predict(Input &u, double dt)\r\n        {\r\n            x_1 = x;\r\n            doModel(x, u, dt);\r\n            doModelJ(F, x_1, u, dt);\r\n            P = F * P * F.transpose() + Q;\r\n        }\r\n\r\n        void update(Output &y, Data &d, double dt)\r\n        {\r\n            doSensorJ(H, x, d, dt);\r\n\r\n            doSensor(z, x, d, dt);\r\n            S = ( H * P * H.transpose() ) + R;\r\n            K = P * H.transpose() * S.inverse();\r\n            x = x + K * (y - z);\r\n            P = (I - K * H) * P;\r\n        }\r\n\r\n        void dataAssoc(std::vector<Output> &y, std::vector<Data> &data, double dt)\r\n        {\r\n            if(dataPoints.size() == 0)\r\n                return;\r\n            MatPx1 v;\r\n            dataType minX, X;\r\n            int minJ;\r\n            Matrix<dataType, 1, 1> Xsq;\r\n            Data d;\r\n\r\n            for(int i = 0; i < y.size(); i++)\r\n            {\r\n                minX = 0;\r\n                minJ = -1;\r\n                for (int j = 0; j < dataPoints.size(); j++)\r\n                {\r\n                    d = dataPoints[j];\r\n                    doSensor(z, x, d, dt);\r\n                    v = z - y[i];\r\n                    doSensorJ(H, x, d, dt);\r\n                    S = H * P * H.transpose() + R;\r\n                    Xsq = v.transpose() * S.inverse() * v;\r\n                    X = sqrt(Xsq(0));\r\n                    if(minJ < 0)\r\n                    {\r\n                        minJ = j;\r\n                        minX = X;\r\n                    }\r\n                    else if(X < minX)\r\n                    {\r\n                        minJ = j;\r\n                        minX = X;\r\n                    }\r\n                }\r\n                data[i] = dataPoints[minJ];\r\n            }\r\n        }\r\n\r\n        void doModel(State &x, Input &u, double dt)\r\n        {\r\n            if(modelFn != NULL)\r\n                modelFn(x, u, dt);\r\n            else\r\n                model(x, u, dt);\r\n        }\r\n\r\n        void doSensor(Output &z, State &x, Data &d, double dt)\r\n        {\r\n            if(sensorFn != NULL)\r\n                sensorFn(z, x, d, dt);\r\n            else\r\n                sensor(z, x, d, dt);\r\n        }\r\n\r\n        void doModelJ(ModelJacobian &F, State &x, Input &u, double dt)\r\n        {\r\n            if(modelJFn != NULL)\r\n                modelJFn(F, x, u, dt);\r\n            else\r\n                modelJacobian(F, x, u, dt);\r\n        }\r\n\r\n        void doSensorJ(SensorJacobian &H, State &x, Data &d, double dt)\r\n        {\r\n            if(sensorJFn != NULL)\r\n                sensorJFn(H, x, d, dt);\r\n            else\r\n                sensorJacobian(H, x, d, dt);\r\n        }\r\n\r\n        template<class T>\r\n        void randn(T &mat)\r\n        {\r\n            for (size_t i = 0; i < mat.rows(); i++)\r\n            {\r\n                for (size_t j = 0; j < mat.cols(); j++)\r\n                {\r\n                    mat(i, j) = distr(gen);\r\n                }\r\n            }\r\n        }\r\n\r\n};", "meta": {"hexsha": "002dce966534aad0167a92e451707827a888321c", "size": 12503, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bflib/EKF.hpp", "max_stars_repo_name": "AlexanderSilvaB/KFs", "max_stars_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-30T07:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:35:29.000Z", "max_issues_repo_path": "bflib/EKF.hpp", "max_issues_repo_name": "AlexanderSilvaB/KFs", "max_issues_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bflib/EKF.hpp", "max_forks_repo_name": "AlexanderSilvaB/KFs", "max_forks_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T08:35:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T09:06:35.000Z", "avg_line_length": 25.9937629938, "max_line_length": 97, "alphanum_fraction": 0.4190194353, "num_tokens": 2960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5655798050282912}}
{"text": "//\n// Expansion Hunter\n// Copyright 2016-2019 Illumina, Inc.\n// All rights reserved.\n//\n// Author: Egor Dolzhenko <edolzhenko@illumina.com>,\n//         Mitch Bekritsky <mbekritsky@illumina.com>, Richard Shaw\n// Concept: Michael Eberle <meberle@illumina.com>\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n//\n\n#include \"genotyping/RegionLengthEstimation.hh\"\n\n#include <boost/lexical_cast.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\nusing boost::lexical_cast;\nusing boost::math::cdf;\nusing boost::math::poisson_distribution;\nusing std::round;\nusing std::vector;\n\nnamespace ehunter\n{\n\n// Uses the standard Lander-Waterman model to estimate length of a workflow. The confidence interval is computed using a\n// generic parametric bootstrap procedure (note that a simpler implementation using Poisson mean CI is possible).\nvoid estimateRegionLength(\n    int readCount, int readLength, double depth, int& regionLength, int& lowerBound, int& upperBound)\n{\n    const double proportionOfReadsStartAtPosition = depth / readLength;\n    // The length of sub-workflow where reads can start and still be fully within the workflow\n    const int extensionLength = static_cast<int>(round(readCount / proportionOfReadsStartAtPosition));\n\n    const int kSeed = 42;\n    std::mt19937 numberGenerator(kSeed);\n\n    // Model for the number of reads that fall within the workflow\n    std::poisson_distribution<> poisson(readCount);\n\n    vector<int> bootstrapSamples;\n    const int kNumSamples = 10000;\n    for (int sampleIndex = 0; sampleIndex < kNumSamples; ++sampleIndex)\n    {\n        const int sampledReadCount = poisson(numberGenerator);\n        const int sampledExtensionLength = static_cast<int>(round(sampledReadCount / proportionOfReadsStartAtPosition));\n        const int bootstrapSample = sampledExtensionLength - extensionLength;\n\n        bootstrapSamples.push_back(bootstrapSample);\n    }\n\n    // Compute 2.5% and 97.5% quantiles\n    std::sort(bootstrapSamples.begin(), bootstrapSamples.end());\n    const int lowerQuantile = *(bootstrapSamples.begin() + static_cast<int>(bootstrapSamples.size() * 0.025));\n    const int upperQuantile = *(bootstrapSamples.begin() + static_cast<int>(bootstrapSamples.size() * 0.975));\n\n    regionLength = extensionLength + readLength;\n\n    lowerBound = readLength;\n    lowerBound += extensionLength - upperQuantile > 0 ? extensionLength - upperQuantile : 0;\n\n    upperBound = readLength;\n    upperBound += extensionLength - lowerQuantile > 0 ? extensionLength - lowerQuantile : 0;\n}\n\n}\n", "meta": {"hexsha": "72a3de2bbb4289498df6aa1df1472c5e7d96b347", "size": 3145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "genotyping/RegionLengthEstimation.cpp", "max_stars_repo_name": "AlesMaver/ExpansionHunter", "max_stars_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_stars_repo_licenses": ["BSL-1.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": "genotyping/RegionLengthEstimation.cpp", "max_issues_repo_name": "AlesMaver/ExpansionHunter", "max_issues_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_issues_repo_licenses": ["BSL-1.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": "genotyping/RegionLengthEstimation.cpp", "max_forks_repo_name": "AlesMaver/ExpansionHunter", "max_forks_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0, "max_line_length": 120, "alphanum_fraction": 0.7421303657, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711680567799, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5655797785759382}}
{"text": "/** \\defgroup main Главный модуль программы\n    @{\n*/\n\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n#include <sstream>\n#include <fstream>\n#include <list>\n#include <mutex>\n\n#include <boost/asio/thread_pool.hpp>\n#include <boost/asio/post.hpp>\n\n//#define debug\n\nusing namespace std;\nusing namespace chrono;\n\n/// Миллисекунды в формате дробного числа.\nusing d_milliseconds = duration<double, milliseconds::period>;\n\n/// Массив с базовыми простыми числами (результат первого этапа алгоритма).\nusing FirstStepResult = vector<size_t>;\n\n/// Массив с найденными простыми числами в ходе выполнения второго этапа алгоритма.\nusing SecondStepResult = vector<uint64_t>;\n\n/// Вывести содержимое контейнера (где есть begin и end).\ntemplate <typename C>\nstring displayContainer(const C& container)\n{\n    typename C::const_iterator it;\n\n    stringstream ss;\n\n    for (it = container.begin(); it != container.end(); ++it)\n    {\n        ss << *it << \" \";\n    }\n\n    ss << endl;\n\n    return ss.str();\n}\n\n/**\n * @brief Бенчмарк.\n * @param func Выполняемая функция.\n * @param args Аргументы выполняемой функции.\n * @return Результат вычисления и время выполнения функции.\n */\ntemplate <typename Result, typename Function, typename... Args>\npair<double, Result> timeBenchmark(const Function& func, const Args&... args)\n{\n    Result calc;\n\n    // начинаем считать время\n    auto start = steady_clock::now();\n\n    // что-то вычисляем\n    calc = func(args...);\n\n    // заканчиваем считать время\n    auto end = steady_clock::now();\n\n    auto time = duration_cast<d_milliseconds>(end-start).count();\n\n    return make_pair(time, calc);\n}\n\n/// Запись данных в файл.\ntemplate <typename T>\nvoid writeToFile(const string& filename, const T& data)\n{\n    ofstream f(filename);\n\n    if (f)\n    {\n        for (auto c: data)\n        {\n            f << c << \" \";\n        }\n    }\n}\n\n/**\n * @brief Первый этап модицифированного последовательного поиска простых чисел.\n * @details\n * Классический метод - решето Эратосфена.\n * Поиск в интервале [2; n]\n * @param n Верхняя граница поиска простых чисел.\n * @return Массив с базовыми простыми числами.\n */\nFirstStepResult getBasePrimeBySieveOfEratosthenes(const size_t n)\n{\n    FirstStepResult basePrime;\n\n    vector<uint8_t> range(n+1, 0);\n    for (size_t i = 2; i <= n; ++i)\n    {\n        // если непомеченное простое число\n        if (!range[i])\n        {\n            basePrime.push_back(i);\n            // пометим другие числа на расстоянии шага i как составные\n            for (size_t j = i + i; j <= n; j += i)\n            {\n                range[j] = 1;\n            }\n        }\n    }\n\n    return basePrime;\n}\n\n\n/**\n * @brief Второй этап модифицированного последовательного поиска простых чисел.\n * @param i_begin Начальный индекс поиска\n * @param i_end Конечный индекс поиска\n * @param basePrime Массив с базовыми простыми числами\n * @return Массив с простыми числами, найденные в диапазоне от (i_begin; i_end]\n */\nSecondStepResult seqModSearch(const uint64_t i_begin,\n                              const uint64_t i_end,\n                              const FirstStepResult &basePrime\n                              )\n{\n    SecondStepResult primeNumbers;\n\n    for (uint64_t number = i_begin + 1; number <= i_end; ++number)\n    {\n        auto isDivide = [&](uint64_t basePrimeNumber)\n        {\n            return number % basePrimeNumber == 0;\n        };\n\n        const auto res = find_if(basePrime.begin(), basePrime.end(), isDivide);\n\n        if (res == basePrime.end())\n        {\n            primeNumbers.push_back(number);\n        }\n    }\n\n    return primeNumbers;\n}\n\n/**\n * @brief Второй этап модифицированного последовательного поиска простых чисел в полном диапазоне.\n * @param[in] i_begin Начальный индекс поиска\n * @param[in] i_end Конечный индекс поиска\n * @param[in] basePrime Массив с базовыми простыми числами\n * @param[in] basePrimeBegin Начальный индекс массива с базовыми простыми числами\n * @param[in] basePrimeEnd Конечный индекс массива с базовыми простыми числами\n * @param[out] fullRange Полный диапазон чисел, где 0 - простое, 1 - составное число.\n */\nvoid seqModSearchInFullRange(const uint64_t i_begin,\n                             const uint64_t i_end,\n                             const FirstStepResult &basePrime,\n                             const ptrdiff_t basePrimeBegin,\n                             const ptrdiff_t basePrimeEnd,\n                             vector<uint8_t> &fullRange\n                             )\n{\n    uint64_t firstNumber = i_begin + 1;\n    for (uint64_t number = firstNumber; number <= i_end; ++number)\n    {\n        auto isDivide = [&](uint64_t basePrimeNumber)\n        {\n            return number % basePrimeNumber == 0;\n        };\n\n        const auto res = find_if(basePrime.begin() + basePrimeBegin, basePrime.begin() + basePrimeEnd, isDivide);\n\n        if (res != basePrime.begin() + basePrimeEnd)\n        {\n            fullRange[number - firstNumber] = 1;\n        }\n    }\n}\n\n/**\n * @brief Второй этап модифицированного последовательного поиска простых чисел в полном диапазоне по одному простому числу.\n * @param[in] i_begin Начальный индекс поиска\n * @param[in] i_end Конечный индекс поиска\n * @param[in] prime Простое число\n * @param[out] fullRange Полный диапазон чисел, где 0 - простое, 1 - составное число.\n */\nvoid seqModSearchInFullRangeByOnePrime(const uint64_t i_begin,\n                                       const uint64_t i_end,\n                                       const size_t prime,\n                                       vector<uint8_t> &fullRange\n                                       )\n{\n    uint64_t firstNumber = i_begin + 1;\n    for (uint64_t number = firstNumber; number <= i_end; ++number)\n    {\n        if (number % prime == 0)\n        {\n            fullRange[number - firstNumber] = 1;\n        }\n    }\n}\n\n/// Параллельная декомпозиция по данным.\nSecondStepResult parDecompositionByData(uint64_t begin,\n                                        uint64_t n,\n                                        const FirstStepResult &basePrime,\n                                        uint8_t threadCount\n                                        )\n{\n#ifdef debug\n    cout << \"> Par decomposition by data [\" << int(threadCount) << \" threads] start...\" << endl;\n#endif\n\n    // Результат - массив с простыми числами из диапазона от (begin, n].\n    SecondStepResult prime;\n\n    list<SecondStepResult> results;\n\n    double range = double(n - begin) / double(threadCount);\n\n#ifdef debug\n    cout << \"data range: \" << range << endl;\n#endif\n\n    list<thread> threads;\n\n    for (size_t i = 0; i < threadCount; ++i)\n    {\n        const auto i_begin = uint64_t(llround(double(i) * range)) + begin;\n        const auto i_end = uint64_t(llround(double(i) * range + range)) + begin;\n\n#ifdef debug\n        cout << i << \" thread - \" << \"begin: \" << i_begin << \" \" << \"end: \" << i_end << endl;\n#endif\n\n        const auto threadHandler = [i_begin, i_end, &basePrime, &results]()\n        {\n            results.push_back(seqModSearch(i_begin, i_end, ref(basePrime)));\n        };\n\n        thread t { threadHandler };\n        threads.push_back(move(t));\n    }\n\n    for (auto &t : threads)\n    {\n        t.join();\n    }\n\n    results.sort([](const SecondStepResult& v1, const SecondStepResult& v2)\n    {\n        return v1.front() < v2.front();\n    });\n\n    for (const auto &res: results)\n    {\n        prime.insert(prime.end(), res.begin(), res.end());\n    }\n\n    return prime;\n}\n\n/// Последовательная декомпозиция набора простых чисел.\nSecondStepResult seqDecompositionByBasePrime(const uint64_t begin,\n                                             const uint64_t n,\n                                             const FirstStepResult &basePrime\n                                             )\n{\n    const auto diff = n - begin;\n    // диапазон чисел (begin, n]\n    // 1  - если составное\n    // 0 - если простое\n    vector<uint8_t> fullRange(diff, 0);\n\n    // Результат - массив с простыми числами из диапазона от (begin, n].\n    SecondStepResult prime;\n\n    seqModSearchInFullRange(begin, n, basePrime, ptrdiff_t(0), ptrdiff_t(basePrime.size()-1), fullRange);\n\n    for (size_t i = 0; i < diff; ++i)\n    {\n        if (!fullRange[i])\n        {\n            prime.push_back(i + (begin + 1));\n        }\n    }\n\n    return prime;\n}\n\n/// Параллельная декомпозиция набора простых чисел.\nSecondStepResult parDecompositionByBasePrime(const uint64_t begin,\n                                             const uint64_t n,\n                                             const FirstStepResult &basePrime,\n                                             const uint8_t threadCount\n                                             )\n{\n\n#ifdef debug\n    cout << \"> Par decomposition by base prime [\" << int(threadCount) << \" threads] start...\" << endl;\n#endif\n\n    const auto diff = n - begin;\n    // диапазон чисел (begin, n]\n    // 1  - если составное\n    // 0 - если простое\n    vector<uint8_t> fullRange(diff, 0);\n\n    // Результат - массив с простыми числами из диапазона от (begin, n].\n    SecondStepResult prime;\n\n    double rangeForThread = double(basePrime.size()) / double(threadCount);\n\n#ifdef debug\n    cout << \"base prime range for thread: \" << rangeForThread << endl;\n#endif\n\n    list<thread> threads;\n\n    for (size_t i = 0; i < threadCount; ++i)\n    {\n        const auto i_begin = ptrdiff_t(llround(double(i) * rangeForThread));\n        const auto i_end = ptrdiff_t(llround(double(i) * rangeForThread + rangeForThread));\n\n#ifdef debug\n        cout << i << \" thread - \" << \"begin: \" << i_begin << \" \" << \"end: \" << i_end << endl;\n#endif\n\n        if (i_begin == i_end)\n        {\n\n#ifdef debug\n            cout << \"skip thread, because i_begin == i_end\" << endl;\n#endif\n            continue;\n        }\n\n        thread t { seqModSearchInFullRange, begin, n, ref(basePrime), i_begin, i_end, ref(fullRange) };\n        threads.push_back(move(t));\n    }\n\n    for (auto &t : threads)\n    {\n        t.join();\n    }\n\n    for (size_t i = 0; i < diff; ++i)\n    {\n        if (!fullRange[i])\n        {\n            prime.push_back(i + (begin + 1));\n        }\n    }\n\n    return prime;\n}\n\n/// Параллельный алгоритм с использованием Thread Pool\nSecondStepResult parThreadPool(uint64_t begin,\n                               uint64_t n,\n                               const FirstStepResult &basePrime,\n                               const uint8_t threadCount\n                               )\n{\n\n#ifdef debug\n    cout << \"> Par thread pool start...\" << endl;\n#endif\n\n    const auto diff = n - begin;\n    // диапазон чисел (begin, n]\n    // 1  - если составное\n    // 0 - если простое\n    vector<uint8_t> fullRange(diff, 0);\n\n    // Результат - массив с простыми числами из диапазона от (begin, n].\n    SecondStepResult prime;\n\n    const auto basePrimeSize = basePrime.size();\n\n    boost::asio::thread_pool pool(threadCount);\n\n    for (size_t i = 0; i < basePrimeSize; ++i)\n    {\n        const auto prime = basePrime[i];\n\n        boost::asio::post(pool, [prime, begin, n, &fullRange]()\n        {\n            seqModSearchInFullRangeByOnePrime(begin, n, prime, fullRange);\n        });\n\n    }\n\n    // ожидаем все потоки в пуле\n    pool.join();\n\n    for (size_t i = 0; i < diff; ++i)\n    {\n        if (!fullRange[i])\n        {\n            prime.push_back(i + (begin + 1));\n        }\n    }\n\n    return prime;\n}\n\n/// Параллельный алгоритм с использованием Thread Pool\nSecondStepResult parPrimeEnumeration(uint64_t begin,\n                                     uint64_t n,\n                                     const FirstStepResult &basePrime,\n                                     const uint8_t threadCount\n                                     )\n{\n\n#ifdef debug\n    cout << \"> Par prime enumeration [\" << int(threadCount) << \" threads] start...\" << endl;\n#endif\n\n    const auto diff = n - begin;\n    // диапазон чисел (begin, n]\n    // 1  - если составное\n    // 0 - если простое\n    vector<uint8_t> fullRange(diff, 0);\n\n    const auto basePrimeSize = basePrime.size();\n\n    list<thread> threads;\n\n    size_t currentPrimeIndex = 0;\n    mutex m;\n\n    for (size_t i = 0; i < threadCount; ++i)\n    {\n        auto handler = [begin, n, basePrimeSize, &basePrime, &m, &currentPrimeIndex, &fullRange]()\n        {\n            while (true)\n            {\n                unique_lock lck {m};\n\n                if (currentPrimeIndex >= basePrimeSize)\n                {\n                    break;\n                }\n\n                auto prime = basePrime[currentPrimeIndex++];\n\n                // разблокируем мьютекс, так как перестали работать\n                // с разделяемым ресурсом (индекс)\n                lck.unlock();\n\n                seqModSearchInFullRangeByOnePrime(begin, n, prime, fullRange);\n            }\n        };\n\n        thread t { handler };\n        threads.push_back(move(t));\n    }\n\n    for (auto &t : threads)\n    {\n        t.join();\n    }\n\n    // Результат - массив с простыми числами из диапазона от (begin, n].\n    SecondStepResult prime;\n\n    for (size_t i = 0; i < diff; ++i)\n    {\n        if (!fullRange[i])\n        {\n            prime.push_back(i + (begin + 1));\n        }\n    }\n\n    return prime;\n}\n\nint main(int argc, char *argv[])\n{\n    cout << thread::hardware_concurrency() << endl;\n\n    constexpr size_t default_n = 100;\n\n    auto n = default_n;\n\n    if (argc >= 2)\n    {\n        n = stoull(argv[1]);\n    }\n\n    const auto sqrtN = static_cast<size_t>(sqrt(n));\n\n    // Первый шаг.\n    const auto firstStepRes = timeBenchmark<FirstStepResult>(getBasePrimeBySieveOfEratosthenes, sqrtN);\n    cout << \"> First step: \" << firstStepRes.first << \" ms\" << endl;\n    writeToFile(\"firstStep.txt\", firstStepRes.second);\n\n    // Последовательная декомпозиция по данным\n    const auto seqDecompositionByDataRes = timeBenchmark<SecondStepResult>(seqModSearch, sqrtN, n, ref(firstStepRes.second));\n    cout << \"> Seq decomposition by data: \" << seqDecompositionByDataRes.first << \" ms\" << endl;\n    writeToFile(\"SeqDecompositionByData.txt\", seqDecompositionByDataRes.second);\n\n    // Параллельная декомпозиция по данным: threadCount потоков\n    const auto doParDecompositionByData = [&](uint8_t threadCount)\n    {\n        const auto parDecompositionByDataRes = timeBenchmark<SecondStepResult>(parDecompositionByData, sqrtN, n, ref(firstStepRes.second), threadCount);\n        cout << \"> Par decomposition by data [\" + to_string(threadCount) + \" threads]: \" << parDecompositionByDataRes.first << \" ms\" << endl;\n        writeToFile(\"ParDecompositionByData_\" + to_string(threadCount) + \"t.txt\", parDecompositionByDataRes.second);\n    };\n\n    doParDecompositionByData(2);\n    doParDecompositionByData(4);\n    doParDecompositionByData(8);\n\n    // Последовательная декомпозиция набора простых чисел\n    const auto seqDecompositionByBasePrimeRes = timeBenchmark<SecondStepResult>(seqDecompositionByBasePrime, sqrtN, n, ref(firstStepRes.second));\n    cout << \"> Seq decomposition by base prime set: \" << seqDecompositionByBasePrimeRes.first << \" ms\" << endl;\n    writeToFile(\"SeqDecompositionByBasePrime.txt\", seqDecompositionByBasePrimeRes.second);\n\n    // Параллельная декомпозиция набора простых чисел: threadCount потоков\n    const auto doParDecompositionByBasePrime = [n, sqrtN, &firstStepRes](uint8_t threadCount)\n    {\n        const auto parDecompositionByBasePrimeRes = timeBenchmark<SecondStepResult>(parDecompositionByBasePrime, sqrtN, n, ref(firstStepRes.second), threadCount);\n        cout << \"> Par decomposition by base prime set [\" + to_string(threadCount) + \" threads]: \" << parDecompositionByBasePrimeRes.first << \" ms\" << endl;\n        writeToFile(\"ParDecompositionByBasePrime_\" + to_string(threadCount) + \"t.txt\", parDecompositionByBasePrimeRes.second);\n    };\n\n    doParDecompositionByBasePrime(2);\n    doParDecompositionByBasePrime(4);\n    doParDecompositionByBasePrime(8);\n\n    // С применением Thread Pool\n    const auto doParThreadPool = [n, sqrtN, &firstStepRes]()\n    {\n        const auto parThreadPoolRes = timeBenchmark<SecondStepResult>(parThreadPool, sqrtN, n, ref(firstStepRes.second), uint8_t(thread::hardware_concurrency()));\n        cout << \"> Par thread pool [\" << thread::hardware_concurrency() << \" threads] [\" + to_string(firstStepRes.second.size()) + \" tasks]: \" << parThreadPoolRes.first << \" ms\" << endl;\n        writeToFile(\"ParThreadPool.txt\", parThreadPoolRes.second);\n    };\n\n    // Пул потоков\n    doParThreadPool();\n\n    // С последовательным перебором простых чисел\n    const auto doParPrimeEnumeration = [n, sqrtN, &firstStepRes](uint8_t threadCount)\n    {\n        const auto parPrimeEnumerationRes = timeBenchmark<SecondStepResult>(parPrimeEnumeration, sqrtN, n, ref(firstStepRes.second), threadCount);\n        cout << \"> Par prime enumeration [\" << int(threadCount) << \" threads]: \" << parPrimeEnumerationRes.first << \" ms\" << endl;\n        writeToFile(\"ParPrimeEnumeration_\" + to_string(threadCount) + \"t.txt\", parPrimeEnumerationRes.second);\n    };\n\n    doParPrimeEnumeration(2);\n    doParPrimeEnumeration(4);\n    doParPrimeEnumeration(8);\n\n    system(\"pause\");\n    return 0;\n}\n/** @} */\n", "meta": {"hexsha": "3fc2e52ad94c3d021911c63b49e22328ae3513bc", "size": 17115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4 course/parallel_programming/lab3/main.cpp", "max_stars_repo_name": "SgAkErRu/labs", "max_stars_repo_head_hexsha": "9cf71e131513beb3c54ad3599f2a1e085bff6947", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4 course/parallel_programming/lab3/main.cpp", "max_issues_repo_name": "SgAkErRu/labs", "max_issues_repo_head_hexsha": "9cf71e131513beb3c54ad3599f2a1e085bff6947", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4 course/parallel_programming/lab3/main.cpp", "max_forks_repo_name": "SgAkErRu/labs", "max_forks_repo_head_hexsha": "9cf71e131513beb3c54ad3599f2a1e085bff6947", "max_forks_repo_licenses": ["BSD-3-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.1320422535, "max_line_length": 186, "alphanum_fraction": 0.6008764242, "num_tokens": 4614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303137346447, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.5655643510434363}}
{"text": "#include <iostream>\n#include <cassert>\n#include <iomanip>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.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, int,\n                                              boost::property<boost::edge_residual_capacity_t, int,\n                                                              boost::property<boost::edge_reverse_t, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, int>>>>>\n    Graph;\n\nconst int unreachable_distance = std::numeric_limits<int>::max();\n\nbool check_shelter_reachable_in_t(const std::vector<std::vector<int>> &distance_matrix, const int t)\n{\n  const int a = distance_matrix.size();\n  const int s = distance_matrix.at(0).size(); // HACK This might be double the s in testcase()\n\n  int next_free_node = 0;\n  const int node_source = next_free_node++;\n  const int node_sink = next_free_node++;\n  const auto get_agent_node = [next_free_node, a](int i) {\n    assert(i >= 0 && i < a);\n    return next_free_node + i;\n  };\n  next_free_node += a;\n  const auto get_shelter_node = [next_free_node, s](int i) {\n    assert(i >= 0 && i < s);\n    return next_free_node + i;\n  };\n  next_free_node += s;\n  const int num_nodes = next_free_node;\n  Graph G(num_nodes);\n\n  const auto add_edge = [&G](int from, int to) {\n    DEBUG(5, \"add_edge(\" << from << \", \" << from << \")\");\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] = 1;\n    c_map[rev_e] = 0;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  };\n\n  for (int i_a = 0; i_a < a; i_a++)\n  {\n    add_edge(node_source, get_agent_node(i_a));\n  }\n  for (int i_s = 0; i_s < s; i_s++)\n  {\n    add_edge(get_shelter_node(i_s), node_sink);\n  }\n  for (int i_a = 0; i_a < a; i_a++)\n  {\n    for (int i_s = 0; i_s < s; i_s++)\n    {\n      const int dist = distance_matrix.at(i_a).at(i_s);\n      if (dist != unreachable_distance && dist <= t)\n      {\n        add_edge(get_agent_node(i_a), get_shelter_node(i_s));\n      }\n    }\n  }\n\n  const int flow = boost::push_relabel_max_flow(G, node_source, node_sink);\n  DEBUG(3, \"t \" << t << \" flow \" << flow);\n  assert(flow >= 0 && flow <= a && flow <= s);\n  return flow == a;\n}\n\nint find_lower_bound(std::function<bool(int)> is_match)\n{\n  if (is_match(0))\n  {\n    return 0;\n  }\n\n  int base = 0;\n  while (!is_match(1 << base))\n  {\n    base++;\n  }\n\n  int low = base == 0 ? 0 : 1 << (base - 1);\n  int high = 1 << base;\n  assert(!is_match(low) && is_match(high));\n  while (low < high)\n  {\n    const int mid = (low + high) / 2;\n    if (is_match(mid))\n    {\n      high = mid;\n    }\n    else\n    {\n      low = mid + 1;\n    }\n  }\n  assert(!is_match(low - 1) && is_match(low));\n  return low;\n}\n\nvoid testcase()\n{\n  int n, m, a, s, c, d;\n  std::cin >> n >> m >> a >> s >> c >> d;\n  assert(n >= 1 && n <= 1e3 && m >= 0 && m <= 5e3);\n  assert(a >= 1 && a <= 1e2 && s >= 1 && s <= 1e2);\n  assert(c >= 1 && c <= 2);\n  assert(d >= 1 && d <= 1e3);\n\n  Graph G(n);\n  const auto add_edge = [&G](int from, int to, int weight) {\n    auto w_map = boost::get(boost::edge_weight, G);\n    const auto e_res = boost::add_edge(from, to, G);\n    const Graph::edge_descriptor e = e_res.first;\n    const bool is_new = e_res.second;\n    w_map[e] = is_new ? weight : std::min(w_map[e], weight);\n  };\n  for (int i = 0; i < m; i++)\n  {\n    std::string w_string;\n    int x, y, z;\n    std::cin >> w_string >> x >> y >> z;\n    assert(w_string == \"S\" || w_string == \"L\");\n    assert(x >= 0 && x < n && y >= 0 && y < n && z >= 1 && z <= 1e4);\n    const bool is_lift = w_string == \"L\";\n\n    add_edge(x, y, z);\n    if (is_lift)\n    {\n      add_edge(y, x, z);\n    }\n  }\n\n  std::vector<int> nodes_by_agent(a);\n  for (int &node : nodes_by_agent)\n  {\n    std::cin >> node;\n    assert(node >= 0 && node < n);\n  }\n\n  std::vector<int> nodes_by_shelter(s);\n  for (int &node : nodes_by_shelter)\n  {\n    std::cin >> node;\n    assert(node >= 0 && node < n);\n  }\n\n  std::vector<std::vector<int>> distance_matrix(a, std::vector<int>(c * s, unreachable_distance));\n  std::vector<int> temp_distances(n);\n  auto temp_distance_map = boost::make_iterator_property_map(temp_distances.begin(), boost::get(boost::vertex_index, G));\n  for (int i_a = 0; i_a < a; i_a++)\n  {\n    boost::dijkstra_shortest_paths(G, nodes_by_agent.at(i_a), boost::distance_map(temp_distance_map).distance_inf(unreachable_distance));\n    for (int i_s = 0; i_s < s; i_s++)\n    {\n      const int dist = temp_distances.at(nodes_by_shelter.at(i_s));\n      if (dist != unreachable_distance)\n      {\n        for (int i_c = 0; i_c < c; i_c++)\n        {\n          const int virtual_i_s = i_c * s + i_s;\n          distance_matrix.at(i_a).at(virtual_i_s) = dist + i_c * d;\n          DEBUG(4, \"distance_matrix.at(\" << i_a << \").at(\" << virtual_i_s << \") = \" << distance_matrix.at(i_a).at(virtual_i_s));\n        }\n      }\n    }\n  }\n\n  int t = find_lower_bound([&distance_matrix](const int test_t) {\n    return check_shelter_reachable_in_t(distance_matrix, test_t);\n  });\n  std::cout << t + d << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::fixed << std::setprecision(0);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "837d2b8090140440f566874a5602f2efcadea35d", "size": 5935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "potw/on-her-majestys-secret-service/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/on-her-majestys-secret-service/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/on-her-majestys-secret-service/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9512195122, "max_line_length": 137, "alphanum_fraction": 0.5715248526, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5655392156142277}}
{"text": "// -----------------------------------------------------------------------------\n// Copyright (c) 2022 Mohamed Aladem\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this softwareand 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 noticeand 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 \"micro_graph_optimizer.h\"\n\n#include <Eigen/Geometry>\n#include <string>\n#include <iostream>\n#include <map>\n#include <fstream>\n\nusing namespace mgo;\n\n// This example demonstrates optimzing a non-linear 2D SLAM problem read from a g2o file.\n\ndouble normalize_angle(double theta_rad)\n{\n  // Normalize the angle to the range [-pi, pi).\n  constexpr double kPI = 3.14159265358979323846;\n  constexpr double k2PI = 2.0 * kPI;\n  return (theta_rad - k2PI * std::floor((theta_rad + kPI) / k2PI));\n}\n\nclass Pose2d : public Variable\n{\npublic:\n  Pose2d(double x, double y, double yaw_rad) :\n    m_x(x), m_y(y), m_yaw_rad(yaw_rad)\n  {\n  }\n\n  virtual int dim()const override { return 3; }\n  virtual void plus(const Eigen::VectorXd& delta) override\n  {\n    m_x += delta[0];\n    m_y += delta[1];\n    m_yaw_rad = normalize_angle(m_yaw_rad + delta[2]);\n  }\n\n  double x()const { return m_x; }\n  double y()const { return m_y; }\n  double yaw_rad()const { return m_yaw_rad; }\n\nprivate:\n  double m_x, m_y, m_yaw_rad;\n};\n\nclass Constraint2d : public Factor\n{\npublic:\n  Constraint2d(Pose2d* v_a, Pose2d* v_b, double x_ab, double y_ab,\n    double yaw_ab_rad, const Eigen::Matrix3d& sqrt_info) :\n    m_pos_ab(x_ab, y_ab), m_yaw_ab_rad(yaw_ab_rad), m_sqrt_info(sqrt_info)\n  {\n    add_variable(v_a);\n    add_variable(v_b);\n  }\n\n  virtual int dim()const { return 3; }\n\n  virtual Eigen::VectorXd error()const override\n  {\n    MGO_ASSERT(this->num_variables() == 2);\n    const Pose2d* v_a = static_cast<Pose2d*>(this->variable_at(0));\n    const Pose2d* v_b = static_cast<Pose2d*>(this->variable_at(1));\n    Eigen::Vector3d r;\n    Eigen::Vector2d pos_ab_pred = { v_b->x() - v_a->x(), v_b->y() - v_a->y() };\n    r.head<2>() = Eigen::Rotation2Dd(v_a->yaw_rad()).toRotationMatrix().transpose() * pos_ab_pred - m_pos_ab;\n    r(2) = normalize_angle((v_b->yaw_rad() - v_a->yaw_rad()) - m_yaw_ab_rad);\n    return r;\n  }\n\n  virtual Eigen::VectorXd subtract_error(const Eigen::VectorXd& e1, const Eigen::VectorXd& e2)const override\n  {\n    Eigen::Vector3d diff;\n    diff << (e1(0) - e2(0)), (e1(1) - e2(1)), normalize_angle(e1(2) - e2(2));\n    return diff;\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\nprivate:\n  Eigen::Vector2d m_pos_ab;\n  double m_yaw_ab_rad;\n  Eigen::Matrix3d m_sqrt_info;\n};\n\nbool read_g2o(const std::string& filename, mgo::FactorGraph* graph)\n{\n  std::ifstream file(filename);\n  if (!file.is_open())\n  {\n    MGO_LOG(\"Failed to open file: %s\", filename.c_str());\n    return false;\n  }\n\n  std::string line;\n  std::map<int, Pose2d*> id_to_pose;\n  while (std::getline(file, line))\n  {\n    std::stringstream ss(line);\n    std::string data_type;\n    ss >> data_type;\n    if (data_type == \"VERTEX_SE2\")\n    {\n      int id;\n      double x, y, th;\n      ss >> id >> x >> y >> th;\n      Pose2d* p = new Pose2d(x, y, normalize_angle(th));\n      graph->add_variable(p);\n      id_to_pose[id] = p;\n    }\n    else if (data_type == \"EDGE_SE2\")\n    {\n      int id_a, id_b;\n      double dx, dy, d_yaw, i11, i12, i13, i22, i23, i33;\n      ss >> id_a >> id_b >> dx >> dy >> d_yaw >> i11 >> i12 >> i13 >> i22 >> i23 >> i33;\n      Eigen::Matrix3d info_mtrx = (Eigen::Matrix3d() <<\n        i11, i12, i13,\n        i12, i22, i23,\n        i13, i23, i33).finished();\n      MGO_ASSERT(id_to_pose.count(id_a) != 0);\n      MGO_ASSERT(id_to_pose.count(id_b) != 0);\n      graph->add_factor(new Constraint2d(id_to_pose[id_a], id_to_pose[id_b], dx, dy,\n        d_yaw, info_mtrx.llt().matrixL()));\n    }\n    else\n    {\n      MGO_LOG(\"Unhandled type: %s\", data_type.c_str());\n      return false;\n    }\n  }\n  return true;\n}\n\nvoid dump_poses(const std::string& filename, const FactorGraph& graph)\n{\n  std::ofstream file(filename);\n  if (!file.is_open())\n  {\n    MGO_LOG(\"Failed to open file: %s\", filename.c_str());\n    return;\n  }\n\n  const std::vector<Variable*>& variables = graph.get_variables();\n  for (int i = 0, count = variables.size(); i < count; ++i)\n  {\n    Pose2d* p = static_cast<Pose2d*>(variables[i]);\n    file << i << \" \" << p->x() << \" \" << p->y() << \" \" << p->yaw_rad() << std::endl;\n  }\n}\n\nint main()\n{\n  FactorGraph graph;\n  // You can get this dataset from: https://lucacarlone.mit.edu/datasets/\n  if (!read_g2o(\"./input_M3500_g2o.g2o\", &graph))\n  {\n    return -1;\n  }\n\n  // Fix the first variable.\n  graph.get_variables()[0]->fixed = true;\n\n  dump_poses(\"./original.txt\", graph);\n  mgo::optimize_gn(&graph);\n  dump_poses(\"./optimized.txt\", graph);\n\n  return 0;\n}\n", "meta": {"hexsha": "c6ab70e381ed8bd4eb10535c660d13a088d6bcff", "size": 5701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/slam2d.cpp", "max_stars_repo_name": "alademm/micro-graph-optimizer", "max_stars_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-14T16:06:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T16:06:28.000Z", "max_issues_repo_path": "examples/slam2d.cpp", "max_issues_repo_name": "alademm/micro-graph-optimizer", "max_issues_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_issues_repo_licenses": ["MIT"], "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/slam2d.cpp", "max_forks_repo_name": "alademm/micro-graph-optimizer", "max_forks_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_forks_repo_licenses": ["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.0052631579, "max_line_length": 109, "alphanum_fraction": 0.6381336608, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5655392096970566}}
{"text": "#include <bits/stdc++.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#define EIGEN_DONT_PARALLELIZE\n\nconst double PI\t=\t3.1415926535897932384;\n#include <map>\nstruct pts2D {\n\tdouble x,y;\n};\n\nclass kernel {\npublic:\n  double a;\n  std::vector<pts2D> particles_X;\n\tstd::vector<pts2D> particles_Y;\n\n\tkernel(std::vector<pts2D>& particles_X, std::vector<pts2D>& particles_Y) {\n\t\t\tthis->particles_X = particles_X;\n\t\t\tthis->particles_Y = particles_Y;\n\t}\n\n\tvirtual double getMatrixEntry(const unsigned i, const unsigned j) {\n\t\tstd::cout << \"virtual getInteraction\" << std::endl;\n\t\treturn 0.0;\n\t}\n\n\tEigen::VectorXd getRow(const int j, std::vector<int> col_indices) {\n\t\tint n_cols = col_indices.size();\n\t\tEigen::VectorXd row(n_cols);\n    #pragma omp parallel for\n    for(int k = 0; k < n_cols; k++) {\n        row(k) = this->getMatrixEntry(j, col_indices[k]);\n    }\n    return row;\n  }\n\n  Eigen::VectorXd getCol(const int k, std::vector<int> row_indices) {\n\t\tint n_rows = row_indices.size();\n    Eigen::VectorXd col(n_rows);\n    #pragma omp parallel for\n    for (int j=0; j<n_rows; ++j) {\n\t\t\tcol(j) = this->getMatrixEntry(row_indices[j], k);\n    }\n    return col;\n  }\n\n  Eigen::MatrixXd getMatrix(std::vector<int> row_indices, std::vector<int> col_indices) {\n\t\tint n_rows = row_indices.size();\n\t\tint n_cols = col_indices.size();\n    Eigen::MatrixXd mat(n_rows, n_cols);\n    #pragma omp parallel for\n    for (int j=0; j < n_rows; ++j) {\n        #pragma omp parallel for\n        for (int k=0; k < n_cols; ++k) {\n            mat(j,k) = this->getMatrixEntry(row_indices[j], col_indices[k]);\n        }\n    }\n    return mat;\n  }\n  ~kernel() {};\n};\n\nclass userkernel: public kernel {\npublic:\n\tdouble chargesFunction(const pts2D r) {\n\t\tdouble q = r.x; //user defined\n\t\treturn q;\n\t};\n\t// #ifdef ONEOVERR\n\t// userkernel(std::vector<pts2D>& particles_X, std::vector<pts2D>& particles_Y): kernel(particles_X, particles_Y) {\n\t// };\n\t// double getMatrixEntry(const unsigned i, const unsigned j) {\n\t// \tpts2D r1 = particles_X[i];\n\t// \tpts2D r2 = particles_X[j];\n\t// \tdouble R2\t=\t(r1.x-r2.x)*(r1.x-r2.x) + (r1.y-r2.y)*(r1.y-r2.y);\n\t// \tdouble R\t=\tsqrt(R2);\n\t// \tif (R < a) {\n\t// \t\treturn R/a;\n\t// \t}\n\t// \telse {\n\t// \t\treturn a/R;\n\t// \t}\n\t// }\n\t// #elif LOGR\n\tuserkernel(std::vector<pts2D> particles_X, std::vector<pts2D> particles_Y): kernel(particles_X, particles_Y) {\n\t};\n\tdouble getMatrixEntry(const unsigned i, const unsigned j) {\n\t\tpts2D r1 = particles_X[i];\n\t\tpts2D r2 = particles_X[j];\n\t\tdouble R2\t=\t(r1.x-r2.x)*(r1.x-r2.x) + (r1.y-r2.y)*(r1.y-r2.y);\n\t\tif (R2 < 1e-10) {\n\t\t\treturn 0.0;\n\t\t}\n\t\telse if (R2 < a*a) {\n\t\t\treturn 0.5*R2*log(R2)/a/a;\n\t\t}\n\t\telse {\n\t\t\treturn 0.5*log(R2);\n\t\t}\n\t}\n\t// #endif\n\t~userkernel() {};\n};\n", "meta": {"hexsha": "4e333f0ede1e3691bc7b2984301e6375f8d434cd", "size": 2712, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel.hpp", "max_stars_repo_name": "sivaramambikasaran/HODLR2", "max_stars_repo_head_hexsha": "6fc2868fb3da859f64ae6db51730f2231768de87", "max_stars_repo_licenses": ["MIT"], "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.hpp", "max_issues_repo_name": "sivaramambikasaran/HODLR2", "max_issues_repo_head_hexsha": "6fc2868fb3da859f64ae6db51730f2231768de87", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "sivaramambikasaran/HODLR2", "max_forks_repo_head_hexsha": "6fc2868fb3da859f64ae6db51730f2231768de87", "max_forks_repo_licenses": ["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.5849056604, "max_line_length": 116, "alphanum_fraction": 0.6268436578, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5655391866524144}}
{"text": "#include <Eigen/Geometry>\n#include <nav_msgs/Odometry.h>\n#include <quadrotor_msgs/SO3Command.h>\n#include <quadrotor_simulator/Quadrotor.h>\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <uav_utils/geometry_utils.h>\n\ntypedef struct _Control\n{\n  double rpm[4];\n} Control;\n\ntypedef struct _Command\n{\n  float force[3];\n  float qx, qy, qz, qw;\n  float kR[3];\n  float kOm[3];\n  float corrections[3];\n  float current_yaw;\n  bool  use_external_yaw;\n} Command;\n\ntypedef struct _Disturbance\n{\n  Eigen::Vector3d f;\n  Eigen::Vector3d m;\n} Disturbance;\n\nstatic Command     command;\nstatic Disturbance disturbance;\n\nvoid stateToOdomMsg(const QuadrotorSimulator::Quadrotor::State& state,\n                    nav_msgs::Odometry&                         odom);\nvoid quadToImuMsg(const QuadrotorSimulator::Quadrotor& quad,\n                  sensor_msgs::Imu&                    imu);\n\nstatic Control\ngetControl(const QuadrotorSimulator::Quadrotor& quad, const Command& cmd)\n{\n  const double _kf = quad.getPropellerThrustCoefficient();\n  const double _km = quad.getPropellerMomentCoefficient();\n  const double kf  = _kf - cmd.corrections[0];\n  const double km  = _km / _kf * kf;\n\n  const double          d       = quad.getArmLength();\n  const Eigen::Matrix3f J       = quad.getInertia().cast<float>();\n  const float           I[3][3] = { { J(0, 0), J(0, 1), J(0, 2) },\n                          { J(1, 0), J(1, 1), J(1, 2) },\n                          { J(2, 0), J(2, 1), J(2, 2) } };\n  const QuadrotorSimulator::Quadrotor::State state = quad.getState();\n\n  // Rotation, may use external yaw\n  Eigen::Vector3d _ypr = uav_utils::R_to_ypr(state.R);\n  Eigen::Vector3d ypr  = _ypr;\n  if (cmd.use_external_yaw)\n    ypr[0] = cmd.current_yaw;\n  Eigen::Matrix3d R;\n  R = Eigen::AngleAxisd(ypr[0], Eigen::Vector3d::UnitZ()) *\n      Eigen::AngleAxisd(ypr[1], Eigen::Vector3d::UnitY()) *\n      Eigen::AngleAxisd(ypr[2], Eigen::Vector3d::UnitX());\n  float R11 = R(0, 0);\n  float R12 = R(0, 1);\n  float R13 = R(0, 2);\n  float R21 = R(1, 0);\n  float R22 = R(1, 1);\n  float R23 = R(1, 2);\n  float R31 = R(2, 0);\n  float R32 = R(2, 1);\n  float R33 = R(2, 2);\n  /*\n    float R11 = state.R(0,0);\n    float R12 = state.R(0,1);\n    float R13 = state.R(0,2);\n    float R21 = state.R(1,0);\n    float R22 = state.R(1,1);\n    float R23 = state.R(1,2);\n    float R31 = state.R(2,0);\n    float R32 = state.R(2,1);\n    float R33 = state.R(2,2);\n  */\n  float Om1 = state.omega(0);\n  float Om2 = state.omega(1);\n  float Om3 = state.omega(2);\n\n  float Rd11 =\n    cmd.qw * cmd.qw + cmd.qx * cmd.qx - cmd.qy * cmd.qy - cmd.qz * cmd.qz;\n  float Rd12 = 2 * (cmd.qx * cmd.qy - cmd.qw * cmd.qz);\n  float Rd13 = 2 * (cmd.qx * cmd.qz + cmd.qw * cmd.qy);\n  float Rd21 = 2 * (cmd.qx * cmd.qy + cmd.qw * cmd.qz);\n  float Rd22 =\n    cmd.qw * cmd.qw - cmd.qx * cmd.qx + cmd.qy * cmd.qy - cmd.qz * cmd.qz;\n  float Rd23 = 2 * (cmd.qy * cmd.qz - cmd.qw * cmd.qx);\n  float Rd31 = 2 * (cmd.qx * cmd.qz - cmd.qw * cmd.qy);\n  float Rd32 = 2 * (cmd.qy * cmd.qz + cmd.qw * cmd.qx);\n  float Rd33 =\n    cmd.qw * cmd.qw - cmd.qx * cmd.qx - cmd.qy * cmd.qy + cmd.qz * cmd.qz;\n\n  float Psi = 0.5f * (3.0f - (Rd11 * R11 + Rd21 * R21 + Rd31 * R31 +\n                              Rd12 * R12 + Rd22 * R22 + Rd32 * R32 +\n                              Rd13 * R13 + Rd23 * R23 + Rd33 * R33));\n\n  float force = 0;\n  if (Psi < 1.0f) // Position control stability guaranteed only when Psi < 1\n    force = cmd.force[0] * R13 + cmd.force[1] * R23 + cmd.force[2] * R33;\n\n  float eR1 = 0.5f * (R12 * Rd13 - R13 * Rd12 + R22 * Rd23 - R23 * Rd22 +\n                      R32 * Rd33 - R33 * Rd32);\n  float eR2 = 0.5f * (R13 * Rd11 - R11 * Rd13 - R21 * Rd23 + R23 * Rd21 -\n                      R31 * Rd33 + R33 * Rd31);\n  float eR3 = 0.5f * (R11 * Rd12 - R12 * Rd11 + R21 * Rd22 - R22 * Rd21 +\n                      R31 * Rd32 - R32 * Rd31);\n\n  float eOm1 = Om1;\n  float eOm2 = Om2;\n  float eOm3 = Om3;\n\n  float in1 = Om2 * (I[2][0] * Om1 + I[2][1] * Om2 + I[2][2] * Om3) -\n              Om3 * (I[1][0] * Om1 + I[1][1] * Om2 + I[1][2] * Om3);\n  float in2 = Om3 * (I[0][0] * Om1 + I[0][1] * Om2 + I[0][2] * Om3) -\n              Om1 * (I[2][0] * Om1 + I[2][1] * Om2 + I[2][2] * Om3);\n  float in3 = Om1 * (I[1][0] * Om1 + I[1][1] * Om2 + I[1][2] * Om3) -\n              Om2 * (I[0][0] * Om1 + I[0][1] * Om2 + I[0][2] * Om3);\n  /*\n    // Robust Control --------------------------------------------\n    float c2       = 0.6;\n    float epsilonR = 0.04;\n    float deltaR   = 0.1;\n    float eA1 = eOm1 + c2 * 1.0/I[0][0] * eR1;\n    float eA2 = eOm2 + c2 * 1.0/I[1][1] * eR2;\n    float eA3 = eOm3 + c2 * 1.0/I[2][2] * eR3;\n    float neA = sqrt(eA1*eA1 + eA2*eA2 + eA3*eA3);\n    float muR1 = -deltaR*deltaR * eA1 / (deltaR * neA + epsilonR);\n    float muR2 = -deltaR*deltaR * eA2 / (deltaR * neA + epsilonR);\n    float muR3 = -deltaR*deltaR * eA3 / (deltaR * neA + epsilonR);\n    // Robust Control --------------------------------------------\n  */\n  float M1 = -cmd.kR[0] * eR1 - cmd.kOm[0] * eOm1 + in1; // - I[0][0]*muR1;\n  float M2 = -cmd.kR[1] * eR2 - cmd.kOm[1] * eOm2 + in2; // - I[1][1]*muR2;\n  float M3 = -cmd.kR[2] * eR3 - cmd.kOm[2] * eOm3 + in3; // - I[2][2]*muR3;\n\n  float w_sq[4];\n  w_sq[0] = force / (4 * kf) - M2 / (2 * d * kf) + M3 / (4 * km);\n  w_sq[1] = force / (4 * kf) + M2 / (2 * d * kf) + M3 / (4 * km);\n  w_sq[2] = force / (4 * kf) + M1 / (2 * d * kf) - M3 / (4 * km);\n  w_sq[3] = force / (4 * kf) - M1 / (2 * d * kf) - M3 / (4 * km);\n\n  Control control;\n  for (int i = 0; i < 4; i++)\n  {\n    if (w_sq[i] < 0)\n      w_sq[i] = 0;\n\n    control.rpm[i] = sqrtf(w_sq[i]);\n  }\n  return control;\n}\n\nstatic void\ncmd_callback(const quadrotor_msgs::SO3Command::ConstPtr& cmd)\n{\n  command.force[0]         = cmd->force.x;\n  command.force[1]         = cmd->force.y;\n  command.force[2]         = cmd->force.z;\n  command.qx               = cmd->orientation.x;\n  command.qy               = cmd->orientation.y;\n  command.qz               = cmd->orientation.z;\n  command.qw               = cmd->orientation.w;\n  command.kR[0]            = cmd->kR[0];\n  command.kR[1]            = cmd->kR[1];\n  command.kR[2]            = cmd->kR[2];\n  command.kOm[0]           = cmd->kOm[0];\n  command.kOm[1]           = cmd->kOm[1];\n  command.kOm[2]           = cmd->kOm[2];\n  command.corrections[0]   = cmd->aux.kf_correction;\n  command.corrections[1]   = cmd->aux.angle_corrections[0];\n  command.corrections[2]   = cmd->aux.angle_corrections[1];\n  command.current_yaw      = cmd->aux.current_yaw;\n  command.use_external_yaw = cmd->aux.use_external_yaw;\n}\n\nstatic void\nforce_disturbance_callback(const geometry_msgs::Vector3::ConstPtr& f)\n{\n  disturbance.f(0) = f->x;\n  disturbance.f(1) = f->y;\n  disturbance.f(2) = f->z;\n}\n\nstatic void\nmoment_disturbance_callback(const geometry_msgs::Vector3::ConstPtr& m)\n{\n  disturbance.m(0) = m->x;\n  disturbance.m(1) = m->y;\n  disturbance.m(2) = m->z;\n}\n\nint\nmain(int argc, char** argv)\n{\n  ros::init(argc, argv, \"quadrotor_simulator_so3\");\n\n  ros::NodeHandle n(\"~\");\n\n  ros::Publisher  odom_pub = n.advertise<nav_msgs::Odometry>(\"odom\", 100);\n  ros::Publisher  imu_pub  = n.advertise<sensor_msgs::Imu>(\"imu\", 10);\n  ros::Subscriber cmd_sub =\n    n.subscribe(\"cmd\", 100, &cmd_callback, ros::TransportHints().tcpNoDelay());\n  ros::Subscriber f_sub =\n    n.subscribe(\"force_disturbance\", 100, &force_disturbance_callback,\n                ros::TransportHints().tcpNoDelay());\n  ros::Subscriber m_sub =\n    n.subscribe(\"moment_disturbance\", 100, &moment_disturbance_callback,\n                ros::TransportHints().tcpNoDelay());\n\n  QuadrotorSimulator::Quadrotor quad;\n  double                        _init_x, _init_y, _init_z;\n  n.param(\"simulator/init_state_x\", _init_x, 0.0);\n  n.param(\"simulator/init_state_y\", _init_y, 0.0);\n  n.param(\"simulator/init_state_z\", _init_z, 1.0);\n\n  Eigen::Vector3d position = Eigen::Vector3d(_init_x, _init_y, _init_z);\n  quad.setStatePos(position);\n\n  double simulation_rate;\n  n.param(\"rate/simulation\", simulation_rate, 1000.0);\n  ROS_ASSERT(simulation_rate > 0);\n\n  double odom_rate;\n  n.param(\"rate/odom\", odom_rate, 100.0);\n  const ros::Duration odom_pub_duration(1 / odom_rate);\n\n  std::string quad_name;\n  n.param(\"quadrotor_name\", quad_name, std::string(\"quadrotor\"));\n\n  QuadrotorSimulator::Quadrotor::State state = quad.getState();\n\n  ros::Rate    r(simulation_rate);\n  const double dt = 1 / simulation_rate;\n\n  Control control;\n\n  nav_msgs::Odometry odom_msg;\n  odom_msg.header.frame_id = \"/world\";\n  odom_msg.child_frame_id  = \"/\" + quad_name;\n\n  sensor_msgs::Imu imu;\n  imu.header.frame_id = \"/simulator\";\n\n  /*\n  command.force[0] = 0;\n  command.force[1] = 0;\n  command.force[2] = quad.getMass()*quad.getGravity() + 0.1;\n  command.qx = 0;\n  command.qy = 0;\n  command.qz = 0;\n  command.qw = 1;\n  command.kR[0] = 2;\n  command.kR[1] = 2;\n  command.kR[2] = 2;\n  command.kOm[0] = 0.15;\n  command.kOm[1] = 0.15;\n  command.kOm[2] = 0.15;\n  */\n\n  ros::Time next_odom_pub_time = ros::Time::now();\n  while (n.ok())\n  {\n    ros::spinOnce();\n\n    auto last = control;\n    control   = getControl(quad, command);\n    for (int i = 0; i < 4; ++i)\n    {\n      //! @bug might have nan when the input is legal\n      if (std::isnan(control.rpm[i]))\n        control.rpm[i] = last.rpm[i];\n    }\n    quad.setInput(control.rpm[0], control.rpm[1], control.rpm[2],\n                  control.rpm[3]);\n    quad.setExternalForce(disturbance.f);\n    quad.setExternalMoment(disturbance.m);\n    quad.step(dt);\n\n    ros::Time tnow = ros::Time::now();\n\n    if (tnow >= next_odom_pub_time)\n    {\n      next_odom_pub_time += odom_pub_duration;\n      odom_msg.header.stamp = tnow;\n      state                 = quad.getState();\n      stateToOdomMsg(state, odom_msg);\n      quadToImuMsg(quad, imu);\n      odom_pub.publish(odom_msg);\n      imu_pub.publish(imu);\n    }\n\n    r.sleep();\n  }\n\n  return 0;\n}\n\nvoid\nstateToOdomMsg(const QuadrotorSimulator::Quadrotor::State& state,\n               nav_msgs::Odometry&                         odom)\n{\n  odom.pose.pose.position.x = state.x(0);\n  odom.pose.pose.position.y = state.x(1);\n  odom.pose.pose.position.z = state.x(2);\n\n  Eigen::Quaterniond q(state.R);\n  odom.pose.pose.orientation.x = q.x();\n  odom.pose.pose.orientation.y = q.y();\n  odom.pose.pose.orientation.z = q.z();\n  odom.pose.pose.orientation.w = q.w();\n\n  odom.twist.twist.linear.x = state.v(0);\n  odom.twist.twist.linear.y = state.v(1);\n  odom.twist.twist.linear.z = state.v(2);\n\n  odom.twist.twist.angular.x = state.omega(0);\n  odom.twist.twist.angular.y = state.omega(1);\n  odom.twist.twist.angular.z = state.omega(2);\n}\n\nvoid\nquadToImuMsg(const QuadrotorSimulator::Quadrotor& quad, sensor_msgs::Imu& imu)\n\n{\n  QuadrotorSimulator::Quadrotor::State state = quad.getState();\n  Eigen::Quaterniond                   q(state.R);\n  imu.orientation.x = q.x();\n  imu.orientation.y = q.y();\n  imu.orientation.z = q.z();\n  imu.orientation.w = q.w();\n\n  imu.angular_velocity.x = state.omega(0);\n  imu.angular_velocity.y = state.omega(1);\n  imu.angular_velocity.z = state.omega(2);\n\n  imu.linear_acceleration.x = quad.getAcc()[0];\n  imu.linear_acceleration.y = quad.getAcc()[1];\n  imu.linear_acceleration.z = quad.getAcc()[2];\n}\n", "meta": {"hexsha": "e55b09f32bf3a6ae42e4935607be23c9b354e80b", "size": 11171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/src/quadrotor_simulator_so3.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/src/quadrotor_simulator_so3.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/src/quadrotor_simulator_so3.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": 32.1930835735, "max_line_length": 79, "alphanum_fraction": 0.5810580969, "num_tokens": 3859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5654306294944755}}
{"text": "/////////////////////////////////////////////////////////\n// (c) 2021 Tetsuro Nagai \n/////////////////////////////////////////////////////////\n\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <cstdio>\n#include <cmath>\n#include <ctime>\n#include <iomanip>\n#include <cstdlib>\n#include<vector>\n#include<algorithm>\n#include<numeric>\n#include<sstream>\n#include <boost/program_options.hpp>\n#include <boost/format.hpp>\n#include <prettyprint.hpp>\n\n#define DEBUG (false)\nnamespace po=boost::program_options;\n  \n\nint L;\nint N;\n\nstd::vector<int> sites;\nstd::vector<int> parent;\n\n\n// The functions init, find, unite, connect, pos2index \n// were taken or adopted from https://github.com/kaityo256/mc/tree/master/percolation/ \n// (c) 2012-2019 H. Watanabe \n\nvoid init(int size){\n    L=size;\n    N = L * L * L;\n    parent.resize(N);\n    sites.resize(N);\n    for(int i = 0; i< N; ++i ){\n        parent[i] = i ;\n    }\n}\n    \nint find(int i){\n    if (i != parent[i]){\n        parent[i] = find(parent[i]); // tree is flattened; https://algo-logic.info/union-find-tree/\n    }\n    return parent[i] ;\n}\n\nvoid unite(int i, int j){  //can be optimized more if necessary \n    i = find(i);\n    j = find(j);\n    parent[j] = i ;  \n}\n\nvoid connect(int i, int j){\n    if(sites[i] == 0){\n        return ;\n    }\n    if(sites[j] == 0){\n        return ;\n    }\n    unite(i,j);\n}\n\nint pos2index(int ix, int iy, int iz){\n    ix =(ix + L) % L;\n    iy =(iy + L) % L;\n    iz =(iz + L) % L;\n    return ix *L*L + iy *L + iz ;\n}\n\ndouble crossing_probability_z(void){\n    for(int ix1 = 0; ix1 < L ; ix1++){\n    for(int iy1 = 0; iy1 < L ; iy1++){\n        int i = pos2index(ix1, iy1, 0);\n        int ci = find(i);\n        for(int ix2 = 0 ; ix2 < L; ++ix2){\n        for(int iy2 = 0 ; iy2 < L; ++iy2){\n            int j = (pos2index(ix2, iy2, L-1));\n            int cj = find(j);\n            if(ci == cj){\n                return 1.0;\n            }\n        }\n        }\n    }\n    }\n    return 0.0;\n}\n\ndouble crossing_probability_y(void){\n    for(int ix1 = 0; ix1 < L ; ix1++){\n    for(int iy1 = 0; iy1 < L ; iy1++){\n        int i = pos2index(ix1, 0, iy1);\n        int ci = find(i);\n        for(int ix2 = 0 ; ix2 < L; ++ix2){\n        for(int iy2 = 0 ; iy2 < L; ++iy2){\n            int j = (pos2index(ix2, L-1, iy2));\n            int cj = find(j);\n            if(ci == cj){\n                return 1.0;\n            }\n        }\n        }\n    }\n    }\n    return 0.0;\n}\n\ndouble crossing_probability_x(void){\n    for(int ix1 = 0; ix1 < L ; ix1++){\n    for(int iy1 = 0; iy1 < L ; iy1++){\n        int i = pos2index(0, ix1,  iy1);\n        int ci = find(i);\n        for(int ix2 = 0 ; ix2 < L; ++ix2){\n        for(int iy2 = 0 ; iy2 < L; ++iy2){\n            int j = (pos2index(L-1, ix2, iy2));\n            int cj = find(j);\n            if(ci == cj){\n                return 1.0;\n            }\n        }\n        }\n    }\n    }\n    return 0.0;\n}\n\nint count_max_cluster(void) {\n      std::vector<int> size(N, 0);\n      for (int i = 0; i < N; i++) {\n        int ci = find(i);\n        size[ci]++;\n      }\n      int max = *std::max_element(size.begin(), size.end());\n      return max;\n}\n\nint count_max_cluster_id(void) {\n      std::vector<int> size(N, 0);\n      for (int i = 0; i < N; i++) {\n        int ci = find(i);\n        size[ci]++;\n      }\n      auto max_el = std::max_element(size.begin(), size.end());\n      int max_id = std::distance(size.begin(), max_el);\n      return max_id;\n}\n\n\nint count_active_sites(void) {\n    int sum = std::accumulate(sites.begin(), sites.end(), 0);\n  return sum;\n}\n\n\nint count_trees(void) {\n    int sum = 0;\n    for (int i = 0; i < N; i++) {\n        if(sites[i] == 1 and parent[i] == i){\n            sum++ ;\n        }\n    }\n    return sum;\n}\n\nvoid put_string_of_time(std::string &starting_date){\n    std::time_t t = std::time(nullptr);\n    std::stringstream ss ;\n    ss<< std::put_time(std::localtime(&t), \"%c %Z\");\n    starting_date+=ss.str();\n}\n\nint main(int argc, char** argv){\n    // getting and printing time\n    std::string starting_date;\n    put_string_of_time(starting_date);\n    std::cout << \"Execution start at \" << starting_date << std::endl;\n  \n    // making command line options\n    std::string  fname_input;\n    double  G0 ;\n    std::string  fout_prefix;\n\n    po::options_description opt(\"This program analyze percolation cluster\");\n    opt.add_options()\n      (\"help,h\" ,                                          \"show help\")\n      (\"finp\"   ,       po::value<std::string>(),          \"file name of input\")\n      (\"G0\"     ,po::value<double>()->default_value(5.0),  \"threshold of G, blow which sites to be connected\")\n      (\"fout_prefix\",   po::value<std::string>(),          \"fout_prefix, a number of files will be made with this prefix  \");\n\n     // analyze argc and argv and results are stored in vm\n    try{\n      po::variables_map vm;\n      store(parse_command_line(argc, argv, opt), vm);\n      notify(vm);\n  \n      if(vm.count(\"help\")){\n        std::cout << opt << std::endl; // show help\n        exit(1);\n      }\n      else if(!vm.count(\"finp\")){\n        std::cerr << \"finp is mandatory \" << std::endl;\n        std::cerr << \"exit!!\" << std::endl;\n        exit(1);\n      }\n      else if(!vm.count(\"fout_prefix\")){\n        std::cerr << vm.count(\"fout_prefix\") << std::endl;\n        std::cerr << \"fout_prefix is mandatory \" << std::endl;\n        std::cerr << \"exit!!\" << std::endl;\n        exit(1);\n      }\n      else\n      {\n        fname_input = vm[\"finp\"].as<std::string>();\n        G0 = vm[\"G0\"].as<double>();\n        fout_prefix = vm[\"fout_prefix\"].as<std::string>();\n        std::cout << \"**** Input parameters ****\"  << std::endl;\n        std::cout << \"input file name: \" << fname_input << std::endl;\n        std::cout << \"fout_prefix: \" << fout_prefix << std::endl;\n        std::cout << \"G0: \" << G0 << std::endl;\n        std::cout << \"*************************\\n\"  << std::endl;\n      }\n    }\n    catch (boost::bad_any_cast &e) {\n        std::cout <<\"something wrong and buggy happened!!\"  << std::endl;\n        std::cout <<\"exit!!\"  << std::endl;\n        exit(1);\n    }\n    catch (std::exception  &e) {\n        std::cout << e.what() << std::endl;\n        std::cout <<\"exit!!\"  << std::endl;\n        exit(1);\n    }\n\n\n    int nixyz[3];\n\n    //open fval files\n    std::string buf;\n    std::ifstream ifs_fmap(fname_input.c_str());\n    if(!ifs_fmap){ std::cerr << \"can not open \" << fname_input << std::endl; exit(1);}\n  \n    // first line is number of grids in each direction\n    std::getline(ifs_fmap, buf);\n    sscanf(buf.c_str(), \"%d %d %d\", &nixyz[0], &nixyz[1], &nixyz[2]);\n\n    if(nixyz[0] != nixyz[1] or nixyz[0] != nixyz[2]){\n        std::cerr << \"ERROR: currently, n_x = n_y = n_z should hold. exit!\" << std::endl;\n        return  EXIT_FAILURE;\n    }\n    init(nixyz[0]);\n\n  \n    //data follows\n    while(std::getline(ifs_fmap, buf)){\n        if(DEBUG) std::cout << buf <<std::endl;\n  \n        int  ix, iy, iz ;\n        double tmp;\n        sscanf(buf.c_str(), \"%d %d %d %lf\", &ix, &iy, &iz, &tmp);\n    \n        if( ix  < 0 or nixyz[0] <= ix ){\n          std::cout << \"error in ix \" << ix << std::endl;\n        }\n        if( iy  < 0 or nixyz[1] <= iy ){\n          std::cout << \"error in iy \" << iy << std::endl;\n        }\n        if( iz  < 0 or nixyz[2] <= iz ){\n          std::cout << \"error in iz \" << iz << std::endl;\n        }\n    \n        if(tmp > G0){\n            sites[pos2index(ix,iy,iz)] = 0 ;\n        }\n        else{\n            sites[pos2index(ix,iy,iz)] = 1 ;\n        }\n  \n    }\n    ifs_fmap.close();\n\n\n    const std::string fname_log_name = fout_prefix+\".log\";\n\n    std::ofstream ofs_log(fname_log_name.c_str());\n    if(!ofs_log){\n      std::cerr << \"can not open: \" << fname_log_name << std::endl;\n      exit(1);\n    }\n      ofs_log << \"Excecution starts at \" << starting_date << \"\\n\" <<std::endl;\n  \n    ofs_log <<  \"executed command should be like: \\n\";\n    for(int i = 0; argv[i] != NULL; i++){\n      ofs_log << boost::format(\"%s \")% argv[i];\n    }\n\n\n    for (int ix = 0; ix < L; ++ix){\n        for (int iy = 0; iy < L; ++iy){\n            for (int iz = 0; iz < L; ++iz){\n                int i = pos2index(ix,iy,iz);\n                if(ix+1 < L){\n                    connect(i, pos2index(ix+1, iy, iz));\n                }\n                if(iy+1 < L){\n                    connect(i, pos2index(ix, iy+1, iz));\n                }\n                if(iz+1 < L){\n                    connect(i, pos2index(ix, iy, iz+1));\n                }\n            }\n        }\n    } \n\n    std::cout << \"G0 corss_x cross_y cross_z max_cluster #activesite #tree #sites maxid \" <<std::endl;\n    std::cout << G0 << \" \" ;\n    std::cout << crossing_probability_x() << \" \" ;\n    std::cout << crossing_probability_y() << \" \" ;\n    std::cout << crossing_probability_z() << \" \" ;\n    std::cout << count_max_cluster() << \" \" ;\n    std::cout << count_active_sites() << \" \" ;\n    std::cout << count_trees() << \" \" ;\n    std::cout << N << \" \" ;\n    std::cout << count_max_cluster_id() << \" \" ;\n    std::cout << std::endl;\n\n    const std::string fname_cluster_id = fout_prefix+\"_cluster_id.dat\";\n    std::ofstream ofs_cluster(fname_cluster_id.c_str());\n    if(!ofs_cluster){\n      std::cerr << \"can not open: \" << fname_log_name << std::endl;\n      exit(1);\n    }\n}\n", "meta": {"hexsha": "ebe7e7bcf8cc28ade80cdcd0b7d6d8fe6e6661ac", "size": 9260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main3d.cpp", "max_stars_repo_name": "tnagai-github/percolation_cluster_analysis", "max_stars_repo_head_hexsha": "a31f36181c86fde27e837c1f95164e5d943b37f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main3d.cpp", "max_issues_repo_name": "tnagai-github/percolation_cluster_analysis", "max_issues_repo_head_hexsha": "a31f36181c86fde27e837c1f95164e5d943b37f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main3d.cpp", "max_forks_repo_name": "tnagai-github/percolation_cluster_analysis", "max_forks_repo_head_hexsha": "a31f36181c86fde27e837c1f95164e5d943b37f8", "max_forks_repo_licenses": ["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.3156342183, "max_line_length": 125, "alphanum_fraction": 0.4909287257, "num_tokens": 2707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.7577943712746407, "lm_q1q2_score": 0.5654199291072315}}
{"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// @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/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/grid/tria.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/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n// 这个是新的。我们想从磁盘上读取一个三角图，做这个的类在下面的文件中声明。\n\n#include <deal.II/grid/grid_in.h> \n\n// 我们将使用一个圆形域，而描述其边界的对象来自这个文件。\n\n#include <deal.II/grid/manifold_lib.h> \n\n// 这是C++ ...\n\n#include <fstream> \n#include <iostream> \n\n// 最后，这在以前的教程程序中已经讨论过了。\n\nusing namespace dealii; \n// @sect3{The <code>Step5</code> class template}  \n\n// 主类大部分和前面的例子一样。最明显的变化是删除了 <code>make_grid</code> 函数，因为现在创建网格是在 <code>run</code> 函数中完成的，其余功能都在 <code>setup_system</code> 中。除此以外，一切都和以前一样。\n\ntemplate <int dim> \nclass Step5 \n{ \npublic: \n  Step5(); \n  void run(); \n\nprivate: \n  void setup_system(); \n  void assemble_system(); \n  void solve(); \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  Vector<double> solution; \n  Vector<double> system_rhs; \n}; \n// @sect3{Working with nonconstant coefficients}  \n\n// 在  step-4  中，我们展示了如何使用非恒定边界值和右手边。 在这个例子中，我们想在椭圆算子中使用一个可变系数来代替。由于我们有一个只取决于空间中的点的函数，我们可以做得更简单一些，使用一个普通的函数而不是继承自Function。\n\n// 这是对单点的系数函数的实现。如果与原点的距离小于0.5，我们让它返回20，否则返回1。\n\ntemplate <int dim> \ndouble coefficient(const Point<dim> &p) \n{ \n  if (p.square() < 0.5 * 0.5) \n    return 20; \n  else \n    return 1; \n} \n// @sect3{The <code>Step5</code> class implementation}  \n// @sect4{Step5::Step5}  \n\n// 这个函数和以前一样。\n\ntemplate <int dim> \nStep5<dim>::Step5() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n\n//  @sect4{Step5::setup_system}  \n\n// 这是前面例子中的函数 <code>make_grid</code> ，减去了生成网格的部分。其他一切都没有变化。\n\ntemplate <int dim> \nvoid Step5<dim>::setup_system() \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()); \n  DoFTools::make_sparsity_pattern(dof_handler, dsp); \n  sparsity_pattern.copy_from(dsp); \n\n  system_matrix.reinit(sparsity_pattern); \n\n  solution.reinit(dof_handler.n_dofs()); \n  system_rhs.reinit(dof_handler.n_dofs()); \n} \n\n//  @sect4{Step5::assemble_system}  \n\n// 和前面的例子一样，这个函数在功能上没有太大变化，但仍有一些优化，我们将展示这些优化。对此，需要注意的是，如果使用高效的求解器（如预设条件的CG方法），组装矩阵和右手边会花费相当的时间，你应该考虑在某些地方使用一到两个优化。\n\n// 该函数的前几部分与之前完全没有变化。\n\ntemplate <int dim> \nvoid Step5<dim>::assemble_system() \n{ \n  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.n_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// 接下来是对所有单元的典型循环，以计算局部贡献，然后将它们转移到全局矩阵和向量中。与 step-4 相比，这部分的唯一变化是我们将使用上面定义的 <code>coefficient()</code> 函数来计算每个正交点的系数值。\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        { \n          const double current_coefficient = \n            coefficient(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 *              // a(x_q) \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              cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                              1.0 *                               // f(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            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// 有了这样构建的矩阵，我们再次使用零边界值。\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                                     solution, \n                                     system_rhs); \n} \n// @sect4{Step5::solve}  \n\n// 求解过程看起来又和前面的例子差不多。然而，我们现在将使用一个预设条件的共轭梯度算法。做出这种改变并不难。事实上，我们唯一需要改变的是，我们需要一个作为预处理程序的对象。我们将使用SSOR（对称连续过度放松），放松系数为1.2。为此， <code>SparseMatrix</code> 类有一个函数可以做一个SSOR步骤，我们需要把这个函数的地址和它应该作用的矩阵（也就是要反转的矩阵）以及松弛因子打包成一个对象。 <code>PreconditionSSOR</code> 类为我们做了这个。(  <code>PreconditionSSOR</code>  类需要一个模板参数，表示它应该工作的矩阵类型。默认值是 <code>SparseMatrix@<double@></code> ，这正是我们在这里需要的，所以我们只需坚持使用默认值，不在角括号中指定任何东西。)\n\n// 请注意，在目前的情况下，SSOR的表现并不比其他大多数预处理程序好多少（尽管比没有预处理好）。在下一个教程程序  step-6  的结果部分，将对不同的预处理进行简要比较。\n\n// 有了这个，函数的其余部分就很简单了：我们现在使用我们声明的预处理程序，而不是之前创建的 <code>PreconditionIdentity</code> 对象，CG求解器将为我们完成其余的工作。\n\ntemplate <int dim> \nvoid Step5<dim>::solve() \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  std::cout << \"   \" << solver_control.last_step() \n            << \" CG iterations needed to obtain convergence.\" << std::endl; \n} \n// @sect4{Step5::output_results and setting output flags}  \n\n// 将输出写入文件的方法与上一个教程中的基本相同。唯一不同的是，我们现在需要为每个细化周期构建一个不同的文件名。\n\n// 这个函数以VTU格式写入输出，这是VTK格式的一个变种，因为它压缩了数据，所以需要更少的磁盘空间。当然，如果你希望使用一个不理解VTK或VTU的可视化程序，DataOut类还支持许多其他格式。\n\ntemplate <int dim> \nvoid Step5<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\n  data_out.build_patches(); \n\n  std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtu\"); \n  data_out.write_vtu(output); \n} \n\n//  @sect4{Step5::run}  \n\n// 在这个程序中，倒数第二件事是对 <code>run()</code> 函数的定义。与之前的程序不同，我们将在一个网格序列上进行计算，在每次迭代后都会进行全局细化。因此，该函数由6个周期的循环组成。在每个循环中，我们首先打印循环编号，然后决定如何处理网格。如果这不是第一个周期，我们就简单地对现有的网格进行一次全局精炼。然而，在运行这些循环之前，我们必须先生成一个网格。\n\n// 在前面的例子中，我们已经使用了 <code>GridGenerator</code> 类中的一些函数。在这里，我们想从一个存储单元的文件中读取网格，这个文件可能来自其他人，也可能是一个网格生成工具的产物。\n\n// 为了从文件中读取网格，我们生成一个数据类型为GridIn的对象，并将三角剖分与之相关联（也就是说，当我们要求它读取文件时，我们告诉它要填充我们的三角剖分对象）。然后我们打开相应的文件，用文件中的数据初始化三角剖分。\n\ntemplate <int dim> \nvoid Step5<dim>::run() \n{ \n  GridIn<dim> grid_in; \n  grid_in.attach_triangulation(triangulation); \n  std::ifstream input_file(\"circle-grid.inp\"); \n\n// 我们现在想读取该文件。但是，输入文件只针对二维三角图，而这个函数是一个任意维度的模板。由于这只是一个演示程序，我们不会为不同的维度使用不同的输入文件，而是在不在二维的情况下迅速杀死整个程序。当然，由于下面的主函数假定我们是在二维空间工作，我们可以跳过这个检查，在这个版本的程序中，不会有任何不良影响。\n\n// 事实证明，90%以上的编程错误都是无效的函数参数，如无效的数组大小等，所以我们在整个deal.II中大量使用断言来捕捉此类错误。为此， <code>Assert</code> 宏是一个很好的选择，因为它确保作为第一个参数的条件是有效的，如果不是，就抛出一个异常（它的第二个参数），通常会终止程序，并给出错误发生的位置和原因的信息。关于 @p Assert 宏的具体作用，可以在 @ref Exceptions \"异常文档模块 \"中找到更详细的讨论）。这通常会大大减少发现编程错误的时间，我们发现断言是快速编程的宝贵手段。\n\n// 另一方面，如果你想做大的计算，所有这些检查（目前库中有超过10000个）不应该使程序太慢。为此， <code>Assert</code> 宏只在调试模式下使用，如果在优化模式下则扩展为零。因此，当你在小问题上测试你的程序并进行调试时，断言会告诉你问题出在哪里。一旦你的程序稳定了，你可以关闭调试，程序将在没有断言的情况下以最大速度运行你的实际计算。更准确地说：通过在优化模式下编译你的程序，关闭库中的所有检查（这些检查可以防止你用错误的参数调用函数，从数组中走出来，等等），通常可以使程序的运行速度提高四倍左右。即使优化后的程序性能更高，我们仍然建议在调试模式下开发，因为它允许库自动发现许多常见的编程错误。对于那些想尝试的人来说。从调试模式切换到优化模式的方法是用<code>make release</code>命令重新编译你的程序。现在 <code>make</code> 程序的输出应该向你表明，该程序现在是以优化模式编译的，以后也会被链接到已经为优化模式编译的库。为了切换回调试模式，只需用  <code>make debug</code>  命令重新编译。\n\n  Assert(dim == 2, ExcInternalError()); \n\n// ExcInternalError是一个全局定义的异常，每当出现严重的错误时就会抛出。通常，人们希望使用更具体的异常，特别是在这种情况下，如果 <code>dim</code> 不等于2，人们当然会尝试做其他事情，例如使用库函数创建一个网格。终止程序通常不是一个好主意，断言实际上只应该用于不应该发生的特殊情况，但由于程序员、用户或其他人的愚蠢而可能发生。上面的情况并不是对Assert的巧妙使用，但是再次强调：这是一个教程，也许值得展示一下什么是不应该做的，毕竟。\n\n// 所以，如果我们通过了断言，我们就知道dim==2，现在我们就可以真正地读取网格。它的格式是UCD（非结构化单元数据）（尽管惯例是使用UCD文件的后缀 <code>inp</code> ）。\n\n  grid_in.read_ucd(input_file); \n\n// 如果你想使用其他输入格式，你必须使用其他 <code>grid_in.read_xxx</code> 函数之一。(参见  <code>GridIn</code>  类的文档，以了解目前支持哪些输入格式)。\n\n// 文件中的网格描述了一个圆。因此，我们必须使用一个流形对象，告诉三角计算在细化网格时将边界上的新点放在哪里。与 step-1 不同的是，由于GridIn不知道域的边界是圆形的（与 GridGenerator::hyper_shell) 不同的是，我们必须在创建三角网格后明确地将流形附加到边界上，以便在细化网格时获得正确的结果。\n\n  const SphericalManifold<dim> boundary; \n  triangulation.set_all_manifold_ids_on_boundary(0); \n  triangulation.set_manifold(0, boundary); \n\n  for (unsigned int cycle = 0; cycle < 6; ++cycle) \n    { \n      std::cout << \"Cycle \" << cycle << ':' << std::endl; \n\n      if (cycle != 0) \n        triangulation.refine_global(1); \n\n// 现在我们有了一个确定的网格，我们写一些输出，做所有我们在前面的例子中已经看到的事情。\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\n      setup_system(); \n      assemble_system(); \n      solve(); \n      output_results(cycle); \n    } \n} \n// @sect3{The <code>main</code> function}  \n\n// 主函数看起来和前面的例子中的函数差不多，所以我们就不进一步评论了。\n\nint main() \n{ \n  Step5<2> laplace_problem_2d; \n  laplace_problem_2d.run(); \n  return 0; \n} \n\n", "meta": {"hexsha": "48394833d8bb54022dce2f1da52328915e669125", "size": 11180, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-5/step-5.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-5/step-5.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-5/step-5.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.8286604361, "max_line_length": 487, "alphanum_fraction": 0.6722719141, "num_tokens": 4862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.5654199250258662}}
{"text": "// Copyright (c) 2016\n// Author: Chrono Law\n#include <std.hpp>\nusing namespace std;\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/numeric/conversion/bounds.hpp>\n#include <boost/numeric/conversion/cast.hpp>\nusing namespace boost;\n\n///////////////////////////////////////\n\nvoid case1()\n{\n    cout << numeric_limits<short>::min();               //-32768\n    cout << numeric_limits<short>::max();               //32767\n\n    cout << numeric_limits<unsigned short>::min();      //0\n    cout << numeric_limits<unsigned short>::max();      //65535\n\n    cout << numeric_limits<float>::min();               //1.17549e-38\n    cout << numeric_limits<float>::max();               //3.40282e+38\n\n    cout << endl;\n\n    using namespace boost::numeric;\n\n    cout << bounds<short>::lowest();                        //-32768\n    cout << bounds<short>::highest();                        //32767;\n    cout << bounds<short>::smallest();                  //1\n\n    cout << bounds<float>::lowest();                        //-3.40282e+38\n    cout << bounds<float>::highest();                       //3.40282e+38\n    cout << bounds<float>::smallest();                  //1.17549e-38\n\n    assert(bounds<short>::lowest()==numeric_limits<short>::min());\n    assert(bounds<float>::lowest()==-numeric_limits<float>::max());\n\n    assert(bounds<float>::lowest()==numeric_limits<float>::lowest());\n\n    cout << endl;\n}\n\n///////////////////////////////////////\n\nvoid case2()\n{\n    using namespace boost::numeric;\n\n    short   s = bounds<short>::highest();\n    int     i = numeric_cast<int>(s);\n    assert(i == s);\n\n    try\n    {\n        char c = numeric_cast<char>(s);\n\n        ignore_unused(c);\n    }\n    catch (std::bad_cast& e)\n    {\n        cout << e.what() << endl;\n    }\n\n}\n\n///////////////////////////////////////\n\nint main()\n{\n    std::cout << \"hello numeric\" << std::endl;\n\n    case1();\n    case2();\n    //case3();\n}\n", "meta": {"hexsha": "5fcea624ee052f94dd638e086c1e29d349808fb4", "size": 1902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utility/numeric.cpp", "max_stars_repo_name": "MaxHonggg/professional_boost", "max_stars_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-05-20T08:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T01:17:07.000Z", "max_issues_repo_path": "utility/numeric.cpp", "max_issues_repo_name": "MaxHonggg/professional_boost", "max_issues_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility/numeric.cpp", "max_forks_repo_name": "MaxHonggg/professional_boost", "max_forks_repo_head_hexsha": "6fff73d3b9832644068dc8fe0443be813c7237b4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-07-25T04:52:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T03:55:08.000Z", "avg_line_length": 24.7012987013, "max_line_length": 74, "alphanum_fraction": 0.5010515247, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5653936736591051}}
{"text": "/**\n * ODE solver - JMU REU 2021\n *\n * @author Mike Lam\n */\n\n// standard headers\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <cmath>\n#include <functional>\nusing namespace std;\n\n// Boost ODEint headers (individual files compile faster than the catch-all)\n#include <boost/numeric/odeint.hpp>\n//#include <boost/numeric/odeint/integrate/integrate_const.hpp>\n//#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\nusing namespace boost::numeric::odeint;\n\n// floating-point precision control (control via compiler parameter -Dreal_t)\n//typedef double real_t;      // 64 bits\n//typedef float real_t;       // 32 bits\n\n// solver state\ntypedef std::vector<real_t> state_t;\n\n// parameters (most read from command line)\nreal_t b, c, x0;\ndouble t0 = 0.0;\ndouble tn, dt;\n\n// output stream\nofstream out;\n\n// ODE system\nvoid ode(const state_t &x, state_t &dxdt, const real_t /*t*/)\n{\n    dxdt[0] = b*x[0] + c;\n}\n\n// debug output helper\nvoid observe(const state_t &x, const real_t t)\n{\n    // known closed-form solution\n    real_t sol = (x0+c/b) * exp(b*t) - c/b;\n\n    out << setw(8) << t << \" \" << setw(12) << x[0]\n         //<< \" \" << setw(12) << sol\n         << \" \" << setw(12) << fabs(sol-x[0]) << endl;\n}\n\nint main(int argc, const char* argv[])\n{\n    // check parameters\n    if (argc != 6) {\n        cout << \"Usage: \" << argv[0] << \" <b> <c> <x0> <tn> <dt>\" << endl;\n        return EXIT_FAILURE;\n    }\n\n    // parse parameters\n    b  = stod(argv[1], NULL);\n    c  = stod(argv[2], NULL);\n    x0 = stod(argv[3], NULL);\n    tn = stod(argv[4], NULL);\n    dt = stod(argv[5], NULL);\n    // TODO: add stepper and t0?\n\n    // initialize state\n    state_t x(1);\n    x[0] = x0;\n\n    // show floating-point width\n    //cout << \"sizeof(real_t)=\" << sizeof(real_t) << endl;\n\n    // stepper\n    runge_kutta4<state_t> stp;\n\n    // integrate w/ debug output\n    out.open(\"out.dat\");\n    /*size_t steps =*/ integrate_const(stp, ode, x, t0, tn, dt, observe);\n    out.close();\n\n    // show final output\n    //cout << \"steps=\" << steps << \" x=\" << x[0] << endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ed557f1a534292d65cf4d1481807caad895e913a", "size": 2142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solve_p1.cpp", "max_stars_repo_name": "delaneygmacd/jmu-reu-ode", "max_stars_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T17:12:01.000Z", "max_issues_repo_path": "solve_p1.cpp", "max_issues_repo_name": "delaneygmacd/jmu-reu-ode", "max_issues_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solve_p1.cpp", "max_forks_repo_name": "delaneygmacd/jmu-reu-ode", "max_forks_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T15:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T15:51:05.000Z", "avg_line_length": 23.2826086957, "max_line_length": 77, "alphanum_fraction": 0.6022408964, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.565291226767648}}
{"text": "/**\n *  This file is part of dvo.\n *\n *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)\n *  For more information see <http://vision.in.tum.de/data/software/dvo>.\n *\n *  dvo 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 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <dvo/core/least_squares.h>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <dvo/core/math_sse.h>\n\nstatic const dvo::core::NumType normalizer = 1.0 / (255.0 * 255.0);\nstatic const dvo::core::NumType normalizer_inverse = 255.0 * 255.0;\n\n// ------ Normal Equations Cholesky ------\n\ndvo::core::NormalEquationsLeastSquares::~NormalEquationsLeastSquares() { }\n\nvoid dvo::core::NormalEquationsLeastSquares::initialize(const size_t maxnum_constraints)\n{\n  A.setZero();\n  A_opt.setZero();\n  b.setZero();\n  error = 0;\n  this->num_constraints = 0;\n  this->maxnum_constraints = maxnum_constraints;\n}\n\nvoid dvo::core::NormalEquationsLeastSquares::update(const dvo::core::Vector6& J, const NumType& res, const NumType& weight)\n{\n  NumType factor = weight;//weight * normalizer; // what happens without the normalizer? nothing!\n  A_opt.rankUpdate(J, factor);\n  //MathSse<Sse::Enabled, NumType>::addOuterProduct(A, J, factor);\n  //A += J * J.transpose() * factor;\n  MathSse<Sse::Enabled, NumType>::add(b, J, -res * factor); // not much difference :(\n  //b -= J * res * factor;\n\n  //error += res * res * factor;\n  num_constraints += 1;\n}\n\nvoid dvo::core::NormalEquationsLeastSquares::update(const Eigen::Matrix<NumType, 2, 6>& J, const Eigen::Matrix<NumType, 2, 1>& res, const Eigen::Matrix<NumType, 2, 2>& weight)\n{\n  A_opt.rankUpdate(J, weight);\n  b -= J.transpose() * weight * res;\n\n  num_constraints += 1;\n}\n\nvoid dvo::core::NormalEquationsLeastSquares::combine(const dvo::core::NormalEquationsLeastSquares& other)\n{\n  A_opt += other.A_opt;\n  b += other.b;\n  //error += other.error;\n  num_constraints += other.num_constraints;\n}\n\nvoid dvo::core::NormalEquationsLeastSquares::finish()\n{\n  A_opt.toEigen(A);\n  //A /= (NumType) num_constraints;\n  //b /= (NumType) num_constraints;\n  //error /= (NumType) num_constraints;\n}\n\nvoid dvo::core::NormalEquationsLeastSquares::solve(dvo::core::Vector6& x)\n{\n  x = A.ldlt().solve(b);\n}\n\n// ------ Normal Equations EVD ------\n\ndvo::core::EvdLeastSquares::~EvdLeastSquares() { }\n\nvoid dvo::core::EvdLeastSquares::solve(dvo::core::Vector6& x)\n{\n  // eigen value decomposition seems to be equivalent to SVD for our matrix A\n  Eigen::SelfAdjointEigenSolver<dvo::core::Matrix6x6> eigensolver(A);\n  dvo::core::Vector6 eigenvalues = eigensolver.eigenvalues();\n  dvo::core::Matrix6x6 eigenvectors = eigensolver.eigenvectors();\n\n  bool singular = false;\n\n  for(int i = 0; i < 6; ++i)\n  {\n    if(eigenvalues(i) < 0.05)\n    {\n      singular = true;\n      throw std::exception();\n    }\n    else\n    {\n      eigenvalues(i) = 1.0 / eigenvalues(i);\n    }\n  }\n\n  x = eigenvectors * eigenvalues.asDiagonal() * eigenvectors.transpose() * b;\n}\n\n// ------ SVD ------\n\ndvo::core::SvdLeastSquares::~SvdLeastSquares() { }\n\nvoid dvo::core::SvdLeastSquares::initialize(const size_t maxnum_constraints)\n{\n  J.resize(maxnum_constraints, Eigen::NoChange);\n  residuals.resize(maxnum_constraints, Eigen::NoChange);\n\n  current = 0;\n}\n\nvoid dvo::core::SvdLeastSquares::update(const dvo::core::Vector6& J, const NumType& res, const NumType& weight)\n{\n  this->J.row(current) = J;\n  this->residuals(current) = res;\n\n  current += 1;\n}\n\nvoid dvo::core::SvdLeastSquares::finish()\n{\n  J.conservativeResize(current, Eigen::NoChange);\n  residuals.conservativeResize(current);\n}\n\nvoid dvo::core::SvdLeastSquares::solve(dvo::core::Vector6& x)\n{\n  x = J.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(residuals);\n}\n\n// ------ Precomputed Normal Equations Cholesky ------\n\ndvo::core::PrecomputedNormalEquationsLeastSquares::~PrecomputedNormalEquationsLeastSquares() { }\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::initialize(const size_t maxnum_constraints)\n{\n  hessian_.setZero();\n  jacobian_cache_.resize(Eigen::NoChange, maxnum_constraints);\n  mask_ = cv::Mat1b::zeros(maxnum_constraints, 1);\n\n  this->num_constraints = 0;\n  this->maxnum_constraints = maxnum_constraints;\n}\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::reset()\n{\n  A = hessian_;\n  hessian_error_.setZero();\n  b.setZero();\n  error = 0;\n\n  mask_ptr_ = mask_.ptr();\n  num_constraints = 0;\n}\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::next()\n{\n  ++mask_ptr_;\n}\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::addConstraint(const size_t& idx, const dvo::core::Vector6& J)\n{\n  //hessian_cache_.block<6, 6>(idx * 6, 0) = J * J.transpose() * normalizer;\n  //hessian_cache_[idx] = J * J.transpose() * normalizer;\n\n  //hessian_ += J * J.transpose() * normalizer;\n  MathSse<Sse::Enabled, NumType>::addOuterProduct(hessian_, J, normalizer);\n\n  jacobian_cache_.col(idx) = J * normalizer;\n  mask_.at<uchar>(idx) = 1;\n}\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::ignoreConstraint(const size_t& idx)\n{\n  if((*mask_ptr_) == 0) return;\n\n  const Vector6& J = jacobian_cache_.col(idx);\n\n  /**\n   *  J is already multiplied with normalizer, so it is:\n   *\n   *    J' * J'.transpose() * normalizer * normalizer\n   *\n   *  multiplying with normalizer_inverse gives:\n   *\n   *    J' * J'.transpose() * normalizer * normalizer * normalizer_inverse\n   *\n   *  resulting in:\n   *\n   *    J' * J'.transpose() * normalizer\n   */\n  hessian_error_ -= J * J.transpose() * normalizer_inverse;\n}\n\nbool dvo::core::PrecomputedNormalEquationsLeastSquares::setResidualForConstraint(const size_t& idx, const NumType& res, const NumType& weight)\n{\n  if(*mask_ptr_ == 0) return false;\n\n  //A += *hessian_cache_it_;\n  b -= jacobian_cache_.col(idx) * res * weight;\n\n  error += res * res * weight * normalizer;\n  this->num_constraints +=1;\n\n  return true;\n}\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::finish()\n{\n  A += hessian_error_;\n  A /= (double) num_constraints;\n  b /= (double) num_constraints;\n  error /= (double) num_constraints;\n}\n\nvoid dvo::core::PrecomputedNormalEquationsLeastSquares::solve(dvo::core::Vector6 & x)\n{\n  x = A.ldlt().solve(b);\n}\n", "meta": {"hexsha": "c89c2027f649484f24fbe2d75c628873f28465bc", "size": 6736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvo_core/src/core/least_squares.cpp", "max_stars_repo_name": "uf-reef-avl/dvo_slam", "max_stars_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 566.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:34:55.000Z", "max_issues_repo_path": "dvo_core/src/core/least_squares.cpp", "max_issues_repo_name": "uf-reef-avl/dvo_slam", "max_issues_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T08:03:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T16:14:35.000Z", "max_forks_repo_path": "dvo_core/src/core/least_squares.cpp", "max_forks_repo_name": "uf-reef-avl/dvo_slam", "max_forks_repo_head_hexsha": "1328904fe2039739f03891f28ebde06f0a5174b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 291.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T23:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:26:17.000Z", "avg_line_length": 28.6638297872, "max_line_length": 175, "alphanum_fraction": 0.6970011876, "num_tokens": 1977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5652243908536867}}
{"text": "// Copyright (c) 2015-2020 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef maths_hpp\n#define maths_hpp\n\n#include <vector>\n#include <cstddef>\n#include <cmath>\n#include <numeric>\n#include <algorithm>\n#include <type_traits>\n#include <iterator>\n#include <functional>\n#include <limits>\n#include <utility>\n#include <stdexcept>\n#include <cassert>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/distributions/geometric.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include \"fmath.hpp\"\n\nnamespace octopus { namespace maths {\n\nnamespace constants\n{\n    template <typename T = double>\n    constexpr T ln10Div10 = T {0.230258509299404568401799145468436420760110148862877297603};\n}\n\ntemplate <typename RealType>\nbool is_subnormal(const RealType x) noexcept\n{\n    return std::fpclassify(x) == FP_SUBNORMAL;\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType round(const RealType val, const unsigned precision = 2)\n{\n    const auto factor = std::pow(RealType {10.0}, precision);\n    return std::round(val * factor) / factor;\n}\n\ntemplate <typename T, typename = typename std::enable_if_t<std::is_floating_point<T>::value>>\nT round_sf(const T x, const int n)\n{\n    // https://stackoverflow.com/a/13094362/2970186\n    if (x == 0.0) return 0;\n    auto factor = std::pow(10.0, n - std::ceil(std::log10(std::abs(x))));\n    return std::round(x * factor) / factor;\n}\n\ntemplate <typename T, typename = typename std::enable_if_t<std::is_floating_point<T>::value>>\nbool almost_equal(const T lhs, T rhs, const int ulp = 1)\n{\n    return lhs == rhs || std::abs(lhs - rhs) < std::numeric_limits<T>::epsilon() * std::abs(lhs + rhs) * ulp;\n}\n\ntemplate <typename T, typename = typename std::enable_if_t<std::is_floating_point<T>::value>>\nbool almost_zero(const T x, const int ulp = 1)\n{\n    return almost_equal(x, T {0}, ulp);\n}\n\ntemplate <typename T, typename = typename std::enable_if_t<std::is_floating_point<T>::value>>\nbool almost_one(const T x, const int ulp = 1)\n{\n    return almost_equal(x, T {1}, ulp);\n}\n\ntemplate <typename T, typename = typename std::enable_if_t<std::is_floating_point<T>::value>>\nint count_leading_zeros(const T x)\n{\n    if (x == 0.0) return 0;\n    return -std::ceil(std::log10(std::abs(x - std::numeric_limits<T>::epsilon())));\n}\n\ntemplate <typename IntegerType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>>\nconstexpr IntegerType ipow(const IntegerType base, const IntegerType exponent) noexcept\n{\n    if (exponent == 0) return 1;\n    if (exponent == 1) return base;\n    const auto y = ipow(base, exponent / 2);\n    return exponent % 2 == 0 ? y * y : base * y * y;\n}\n\ntemplate <typename IntegerType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>>\nbool is_safe_ipow(const IntegerType base, const IntegerType exponent) noexcept\n{\n    return exponent * std::log(base) <= std::log(std::numeric_limits<IntegerType>::max());\n}\n\ntemplate <typename RealType>\nconstexpr RealType exp_maclaurin(const RealType x)\n{\n    return (6 + x * (6 + x * (3 + x))) * 0.16666666;\n}\n\ntemplate <typename RealType>\nconstexpr RealType mercator(const RealType x)\n{\n    return x - x * x / 2 + x * x * x / 3;\n}\n\nstruct IdFunction\n{\n    template <typename T>\n    const T& operator()(const T& x) const noexcept { return x; }\n};\n\ntemplate <typename RealType = double, typename InputIt, typename UnaryOperation>\nauto mean(InputIt first, InputIt last, UnaryOperation unary_op)\n{\n    return std::accumulate(first, last, RealType {0},\n                           [&] (const auto curr, const auto& x) {\n                               return curr + unary_op(x);\n                           }) / std::distance(first, last);\n}\n\ntemplate <typename InputIt>\nauto mean(InputIt first, InputIt last)\n{\n    return mean(first, last, IdFunction {});\n}\n\ntemplate <typename Container>\nauto mean(const Container& values)\n{\n    return mean(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename Container, typename UnaryOperation>\nauto mean(const Container& values, UnaryOperation unary_op)\n{\n    return mean(std::cbegin(values), std::cend(values), unary_op);\n}\n\nnamespace detail {\n\ntemplate <typename T = double, typename ForwardIt>\nT median_unsorted(ForwardIt first, ForwardIt last)\n{\n    const auto n = std::distance(first, last);\n    assert(n > 0);\n    if (n == 1) return *first;\n    if (n == 2) return static_cast<T>(*first + *std::next(first)) / 2;\n    const auto middle = std::next(first, n / 2);\n    std::nth_element(first, middle, last);\n    if (n % 2 == 1) {\n        return *middle;\n    } else {\n        auto prev_middle_itr = std::max_element(first, middle);\n        return static_cast<T>(*prev_middle_itr + *middle) / 2;\n    }\n}\n\ntemplate <typename T = double, typename ForwardIt>\nT median_sorted(ForwardIt first, ForwardIt last)\n{\n    const auto n = std::distance(first, last);\n    assert(n > 0);\n    if (n == 1) return *first;\n    const auto middle = std::next(first, n / 2);\n    if (n % 2 == 1) {\n        return *middle;\n    } else {\n        return static_cast<T>(*std::prev(middle) + *middle) / 2;\n    }\n}\n\ntemplate <typename T = double, typename ForwardIt>\nT median_const(ForwardIt first, ForwardIt last)\n{\n    if (std::is_sorted(first, last)) {\n        return median_sorted<T>(first, last);\n    } else {\n        std::vector<typename std::iterator_traits<ForwardIt>::value_type> tmp {first, last};\n        return median_unsorted<T>(std::begin(tmp), std::end(tmp));\n    }\n}\n\n} // namespace detail\n\ntemplate <typename T = double, typename ForwardIt>\nT median(ForwardIt first, ForwardIt last)\n{\n    return detail::median_unsorted<T>(first, last);\n}\n\ntemplate <typename T = double, typename Range>\nT median(Range& values)\n{\n    return median<T>(std::begin(values), std::end(values));\n}\n\ntemplate <typename T = double, typename Range>\nT median(const Range& values)\n{\n    return detail::median_const<T>(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename ForwardIterator, typename UnaryOperation>\nauto stdev(ForwardIterator first, ForwardIterator last, UnaryOperation unary_op)\n{\n    const auto m = mean(first, last, unary_op);\n    const auto n = std::distance(first, last);\n    const auto sum_square = [&] (auto total, const auto& x) { return total + std::pow(unary_op(x) - m, 2); };\n    const auto ss = std::accumulate(first, last, 0.0, sum_square);\n    return std::sqrt(ss / n);\n}\n\ntemplate <typename ForwardIterator>\nauto stdev(ForwardIterator first, ForwardIterator last)\n{\n    return stdev(first, last, IdFunction {});\n}\n\ntemplate <typename Container>\nauto stdev(const Container& values)\n{\n    return stdev(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename Container, typename UnaryOperation>\nauto stdev(const Container& values, UnaryOperation unary_op)\n{\n    return stdev(std::cbegin(values), std::cend(values), unary_op);\n}\n\ntemplate <typename RealType = double, typename InputIt>\nRealType rmq(InputIt first, InputIt last)\n{\n    if (first == last) return 0.0;\n    return std::sqrt((std::inner_product(first, last, first, RealType {0}))\n                     / static_cast<RealType>(std::distance(first, last)));\n}\n\ntemplate <typename RealType = double, typename Container>\nRealType rmq(const Container& values)\n{\n    return rmq<RealType>(std::cbegin(values), std::cend(values));\n}\n\ninline float fast_exp(const float x) noexcept\n{\n    return fmath::exp(x);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_exp(const RealType x) noexcept\n{\n    return std::exp(x);\n}\n\ninline float fast_log(const float x) noexcept\n{\n    return fmath::log(x);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log(const RealType x) noexcept\n{\n    return std::log(x);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(const RealType a, const RealType b)\n{\n    const auto r = std::minmax(a, b);\n    return r.second + std::log(RealType {1} + std::exp(r.first - r.second));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(const RealType a, const RealType b, const RealType c)\n{\n    const auto max = std::max({a, b, c});\n    return max + std::log(std::exp(a - max) + std::exp(b - max) + std::exp(c - max));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(std::initializer_list<RealType> il)\n{\n    const auto max = std::max(il);\n    return max + std::log(std::accumulate(std::cbegin(il), std::cend(il), RealType {0},\n                                          [max] (const auto curr, const auto x) {\n                                              return curr + std::exp(x - max);\n                                          }));\n}\n\ntemplate <typename ForwardIt,\n          typename = std::enable_if_t<!std::is_floating_point<ForwardIt>::value>>\ninline auto log_sum_exp(ForwardIt first, ForwardIt last)\n{\n    assert(first != last);\n    using RealType = typename std::iterator_traits<ForwardIt>::value_type;\n    const auto max = *std::max_element(first, last);\n    return max + std::log(std::accumulate(first, last, RealType {0},\n                                          [max] (const auto curr, const auto x) {\n                                              return curr + std::exp(x - max);\n                                          }));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(const std::array<RealType, 1>& logs)\n{\n    return logs[0];\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(const std::array<RealType, 2>& logs)\n{\n    return log_sum_exp(logs[0], logs[1]);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType log_sum_exp(const std::array<RealType, 3>& logs)\n{\n    return log_sum_exp(logs[0], logs[1], logs[2]);\n}\n\ntemplate <typename Container>\ninline auto log_sum_exp(const Container& values)\n{\n    return log_sum_exp(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(const RealType a, const RealType b) noexcept\n{\n    const auto r = std::minmax(a, b);\n    return r.second + fast_log(RealType {1} + fast_exp(r.first - r.second));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(const RealType a, const RealType b, const RealType c) noexcept\n{\n    const auto max = std::max({a, b, c});\n    return max + fast_log(fast_exp(a - max) + fast_exp(b - max) + fast_exp(c - max));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(std::initializer_list<RealType> il) noexcept\n{\n    const auto max = std::max(il);\n    return max + fast_log(std::accumulate(std::cbegin(il), std::cend(il), RealType {0},\n                                          [max] (const auto curr, const auto x) noexcept {\n                                              return curr + fast_exp(x - max);\n                                          }));\n}\n\ntemplate <typename ForwardIt,\n          typename = std::enable_if_t<!std::is_floating_point<ForwardIt>::value>>\ninline auto fast_log_sum_exp(ForwardIt first, ForwardIt last) noexcept\n{\n    assert(first != last);\n    using RealType = typename std::iterator_traits<ForwardIt>::value_type;\n    const auto max = *std::max_element(first, last);\n    return max + fast_log(std::accumulate(first, last, RealType {0},\n                                          [max] (const auto curr, const auto x) noexcept {\n                                              return curr + fast_exp(x - max);\n                                          }));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(const std::array<RealType, 1>& logs) noexcept\n{\n    return logs[0];\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(const std::array<RealType, 2>& logs) noexcept\n{\n    return fast_log_sum_exp(logs[0], logs[1]);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\ninline RealType fast_log_sum_exp(const std::array<RealType, 3>& logs) noexcept\n{\n    return fast_log_sum_exp(logs[0], logs[1], logs[2]);\n}\n\ntemplate <typename Container>\ninline auto fast_log_sum_exp(const Container& values) noexcept\n{\n    return fast_log_sum_exp(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename T, typename IntegerType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>>\nT factorial(const IntegerType x)\n{\n    return boost::math::factorial<double>(x);\n}\n\ntemplate <typename RealType, typename IntegerType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>>\nRealType log_factorial(IntegerType x)\n{\n    return std::lgamma(x + 1);\n}\n\ntemplate <typename InputIt, typename Log>\nauto entropy(InputIt first, InputIt last, Log&& log)\n{\n    using RealType = typename std::iterator_traits<InputIt>::value_type;\n    static_assert(std::is_floating_point<RealType>::value,\n                  \"entropy is only defined for floating point values\");\n    const auto add_entropy = [&] (auto total, auto p) { return total + (p > 0 ? p * log(p) : 0); };\n    return -std::accumulate(first, last, RealType {0}, add_entropy);\n}\n\ntemplate <typename Range, typename Log>\nauto entropy(const Range& values, Log&& log)\n{\n    return entropy(std::cbegin(values), std::cend(values), std::forward<Log>(log));\n}\n\ntemplate <typename InputIt>\nauto entropy(InputIt first, InputIt last)\n{\n    return entropy(first, last, [] (auto x) { return std::log(x); });\n}\n\ntemplate <typename Range>\nauto entropy(const Range& values)\n{\n    return entropy(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename InputIt>\nauto entropy2(InputIt first, InputIt last)\n{\n    return entropy(first, last, [] (auto x) { return std::log2(x); });\n}\n\ntemplate <typename Range>\nauto entropy2(const Range& values)\n{\n    return entropy2(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename InputIt>\nauto entropy10(InputIt first, InputIt last)\n{\n    return entropy(first, last, [] (auto x) { return std::log10(x); });\n}\n\ntemplate <typename Range>\nauto entropy10(const Range& values)\n{\n    return entropy10(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename RealType, typename IntegerType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType log_binomial_coefficient(const IntegerType n, const IntegerType k)\n{\n    return log_factorial<RealType>(n) - (log_factorial<RealType>(k) + log_factorial<RealType>(n - k));\n}\n\ntemplate <typename IntegerType, typename RealType = double,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType log_fisher_exact_test(const IntegerType a, const IntegerType b, const IntegerType c, const IntegerType d)\n{\n    return log_binomial_coefficient<RealType>(a + b, b) + log_binomial_coefficient<RealType>(c + d, d)\n                - log_binomial_coefficient<RealType>(a + b + c + d, b + d);\n}\n\ntemplate <typename IntegerType, typename RealType = double,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType fisher_exact_test(const IntegerType a, const IntegerType b, const IntegerType c, const IntegerType d)\n{\n    return std::exp(log_fisher_exact_test<IntegerType, RealType>(a, b, c, d));\n}\n\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType geometric_pdf(const IntegerType k, const RealType p)\n{\n    boost::math::geometric_distribution<RealType> dist {p};\n    return boost::math::pdf(dist, k);\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType binomial_pdf(const IntegerType k, const IntegerType n, const RealType p)\n{\n    boost::math::binomial_distribution<RealType> dist {static_cast<RealType>(n), p};\n    return boost::math::pdf(dist, k);\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType log_poisson_pmf(const IntegerType k, const RealType mu)\n{\n    if (k > 0) {\n        return k * std::log(mu) - std::lgamma(k) - mu;\n    } else {\n        return -mu;\n    }\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType poisson_cdf(const IntegerType k, const RealType mu)\n{\n    return almost_zero(mu) ? 1.0 : boost::math::gamma_q(k + 1, mu);\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType poisson_sf(const IntegerType k, const RealType mu)\n{\n    return almost_zero(mu) ? 0.0 : boost::math::gamma_p(k + 1, mu);\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType log_poisson_cdf(const IntegerType k, const RealType mu)\n{\n    return std::log(poisson_cdf(k, mu));\n}\n\ntemplate <typename IntegerType, typename RealType,\n          typename = std::enable_if_t<std::is_integral<IntegerType>::value>,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType log_poisson_sf(const IntegerType k, const RealType mu)\n{\n    return std::log(poisson_sf(k, mu));\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType normal_cdf(const RealType x, const RealType mu, const RealType sigma)\n{\n    boost::math::normal_distribution<RealType> dist {mu, sigma};\n    return boost::math::cdf(dist, x);\n}\n\ntemplate <typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nRealType normal_sf(const RealType x, const RealType mu, const RealType sigma)\n{\n    boost::math::normal_distribution<RealType> dist {mu, sigma};\n    return boost::math::cdf(boost::math::complement(dist, x));\n}\n\ntemplate <typename ForwardIt>\nauto log_beta(const ForwardIt first, const ForwardIt last)\n{\n    using T = std::decay_t<typename std::iterator_traits<ForwardIt>::value_type>;\n    static_assert(std::is_floating_point<T>::value,\n                  \"log_beta is only defined for floating point types.\");\n    return std::accumulate(first, last, T {0}, [] (const auto curr, const auto x) { return curr + std::lgamma(x); })\n           - std::lgamma(std::accumulate(first, last, T {0}));\n}\n\ntemplate <typename Container>\nauto log_beta(const Container& values)\n{\n    return log_beta(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename ForwardIt1, typename ForwardIt2>\nauto log_dirichlet(ForwardIt1 firstalpha, ForwardIt1 lastalpha, ForwardIt2 firstpi)\n{\n    using T = std::decay_t<typename std::iterator_traits<ForwardIt1>::value_type>;\n    static_assert(std::is_floating_point<T>::value,\n                  \"log_dirichlet is only defined for floating point types.\");\n    return std::inner_product(firstalpha, lastalpha, firstpi, T {0}, std::plus<> {},\n                              [] (const auto a, const auto p) { return (a - 1) * std::log(p); })\n            - log_beta(firstalpha, lastalpha);\n}\n\ntemplate <typename Container1, typename Container2>\nauto log_dirichlet(const Container1& alpha, const Container2& pi)\n{\n    return log_dirichlet(std::cbegin(alpha), std::cend(alpha), std::cbegin(pi));\n}\n\ntemplate <typename ForwardIt>\nauto dirichlet_expectation(ForwardIt first_alpha, ForwardIt last_alpha)\n{\n    using T = std::decay_t<typename std::iterator_traits<ForwardIt>::value_type>;\n    static_assert(std::is_floating_point<T>::value,\n                  \"log_dirichlet is only defined for floating point types.\");\n    const auto K = static_cast<std::size_t>(std::distance(first_alpha, last_alpha));\n    const auto a0 = std::accumulate(first_alpha, last_alpha, T {0});\n    std::vector<T> result(K);\n    std::transform(first_alpha, last_alpha, std::begin(result), [a0] (auto a) { return a / a0; });\n    return result;\n}\n\ntemplate <typename Range>\nauto dirichlet_expectation(const Range& values)\n{\n    return dirichlet_expectation(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename ForwardIt>\nauto dirichlet_expectation(const unsigned i, ForwardIt first_alpha, ForwardIt last_alpha)\n{\n    using T = std::decay_t<typename std::iterator_traits<ForwardIt>::value_type>;\n    static_assert(std::is_floating_point<T>::value,\n                  \"log_dirichlet is only defined for floating point types.\");\n    assert(i < static_cast<unsigned>(std::distance(first_alpha, last_alpha)));\n    return *std::next(first_alpha, i) / std::accumulate(first_alpha, last_alpha, T {0});\n}\n\ntemplate <typename Range>\nauto dirichlet_expectation(const unsigned i, const Range& values)\n{\n    return dirichlet_expectation(i, std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename ForwardIt>\nauto dirichlet_entropy(ForwardIt first_alpha, ForwardIt last_alpha)\n{\n    using T = std::decay_t<typename std::iterator_traits<ForwardIt>::value_type>;\n    static_assert(std::is_floating_point<T>::value,\n                  \"log_dirichlet is only defined for floating point types.\");\n    const auto K = static_cast<T>(std::distance(first_alpha, last_alpha));\n    const auto a0 = std::accumulate(first_alpha, last_alpha, T {0});\n    using boost::math::digamma;\n    return log_beta(first_alpha, last_alpha) + (a0 - K) * digamma(a0)\n           - std::accumulate(first_alpha, last_alpha, T {0}, [] (auto curr, auto a) { return curr + (a - 1) * digamma(a); });\n}\n\ntemplate <typename Range>\nauto dirichlet_entropy(const Range& values)\n{\n    return dirichlet_entropy(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename RealType, typename IntegerType>\ninline RealType log_multinomial_coefficient(std::initializer_list<IntegerType> il)\n{\n    using std::begin; using std::end; using std::cbegin; using std::cend; using std::accumulate;\n    std::vector<RealType> denoms(il.size());\n    std::transform(cbegin(il), cend(il), begin(denoms), log_factorial<RealType, IntegerType>);\n    return log_factorial<RealType>(accumulate(cbegin(il), cend(il), 0))\n            - accumulate(cbegin(denoms), cend(denoms), RealType {0});\n}\n\ntemplate <typename RealType, typename Iterator>\ninline RealType log_multinomial_coefficient(Iterator first, Iterator last)\n{\n    using IntegerType = typename Iterator::value_type;\n    std::vector<RealType> denoms(std::distance(first, last));\n    std::transform(first, last, std::begin(denoms), log_factorial<RealType, IntegerType>);\n    return log_factorial<RealType, IntegerType>(std::accumulate(first, last, IntegerType {0}))\n            - std::accumulate(std::cbegin(denoms), std::cend(denoms), RealType {0});\n}\n\ntemplate <typename RealType, typename Container>\ninline RealType log_multinomial_coefficient(const Container& values)\n{\n    return log_multinomial_coefficient<RealType>(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename RealType, typename IntegerType>\ninline IntegerType multinomial_coefficient(std::initializer_list<IntegerType> il)\n{\n    return static_cast<IntegerType>(std::exp(log_multinomial_coefficient<RealType, IntegerType>(std::move(il))));\n}\n\ntemplate <typename IntegerType, typename RealType, typename Iterator>\ninline IntegerType multinomial_coefficient(Iterator first, Iterator last)\n{\n    return static_cast<IntegerType>(std::exp(log_multinomial_coefficient<RealType>(first, last)));\n}\n\ntemplate <typename IntegerType, typename RealType, typename Container>\ninline IntegerType multinomial_coefficient(const Container& values)\n{\n    return multinomial_coefficient<IntegerType, RealType>(std::cbegin(values), std::cend(values));\n}\n\ntemplate <typename RealType, typename ForwardIt1, typename ForwardIt2>\ninline RealType multinomial_pdf(ForwardIt1 first_z, ForwardIt1 last_z, ForwardIt2 first_p)\n{\n    auto r = std::inner_product(first_z, last_z, first_p, RealType {0}, std::multiplies<> {},\n                                [] (auto z_i, auto p_i) { return std::pow(p_i, z_i); });\n    return multinomial_coefficient<RealType>(first_z, last_z) * r;\n}\n\ntemplate <typename IntegerType, typename RealType>\ninline RealType multinomial_pdf(const std::vector<IntegerType>& z, const std::vector<RealType>& p)\n{\n    assert(z.size() == p.size());\n    return multinomial_pdf<RealType>(std::cbegin(z), std::cend(z), std::cbegin(p));\n}\n\ntemplate <typename RealType, typename ForwardIt1, typename ForwardIt2>\ninline RealType log_multinomial_pdf(ForwardIt1 first_z, ForwardIt1 last_z, ForwardIt2 first_p)\n{\n    auto r = std::inner_product(first_z, last_z, first_p, RealType {0}, std::plus<> {},\n                                [] (auto z_i, auto p_i) { return z_i > 0 ? z_i * std::log(p_i) : 0.0; });\n    return log_multinomial_coefficient<RealType>(first_z, last_z) + r;\n}\n\ntemplate <typename IntegerType, typename RealType>\ninline RealType log_multinomial_pdf(const std::vector<IntegerType>& z, const std::vector<RealType>& p)\n{\n    assert(z.size() == p.size());\n    return log_multinomial_pdf<RealType>(std::cbegin(z), std::cend(z), std::cbegin(p));\n}\n\n// Returns approximate y such that digamma(y) = x\ntemplate <typename RealType>\ninline RealType digamma_inv(const RealType x, const RealType epsilon = 10e-8)\n{\n    RealType l {1};\n    auto y = std::exp(x);\n    while (l > epsilon) {\n        y += l * boost::math::sign(x - boost::math::digamma<RealType>(y));\n        l /= 2;\n    }\n    return y;\n}\n\nnamespace detail {\n\ntemplate <typename T, typename RealType>\nT ifactorial(RealType x, std::true_type)\n{\n    return factorial<T, unsigned>(x);\n}\n\ntemplate <typename T, typename RealType>\nT ifactorial(RealType x, std::false_type)\n{\n    return factorial<T>(x);\n}\n\ntemplate <typename T, typename RealType>\nT ifactorial(RealType x)\n{\n    return ifactorial<T>(x, std::is_floating_point<RealType> {});\n}\n\n} // namespace detail\n\ntemplate <typename RealType>\nRealType dirichlet_multinomial(const RealType z1, const RealType z2, const RealType a1, const RealType a2)\n{\n    auto z_0 = z1 + z2;\n    auto a_0 = a1 + a2;\n    using detail::ifactorial;\n    auto z_m = ifactorial<RealType>(z1) * ifactorial<RealType>(z2);\n    return (ifactorial<RealType>(z_0) / z_m) *\n            (std::tgamma(a_0) / std::tgamma(z_0 + a_0)) *\n            (std::tgamma(z1 + a1) * std::tgamma(z2 + a2)) / (std::tgamma(a1) + std::tgamma(a2));\n}\n\ntemplate <typename RealType>\nRealType dirichlet_multinomial(const RealType z1, const RealType z2, const RealType z3,\n                               const RealType a1, const RealType a2, const RealType a3)\n{\n    auto z_0 = z1 + z2 + z3;\n    auto a_0 = a1 + a2 + a3;\n    using detail::ifactorial;\n    auto z_m = ifactorial<RealType>(z1) * ifactorial<RealType>(z2) * ifactorial<RealType>(z3);\n    return (ifactorial<RealType>(z_0) / z_m) *\n            (std::tgamma(a_0) / std::tgamma(z_0 + a_0)) *\n            (std::tgamma(z1 + a1) * std::tgamma(z2 + a2) *\n            std::tgamma(z3 + a3)) / (std::tgamma(a1) + std::tgamma(a2) + std::tgamma(a3));\n}\n\ntemplate <typename RealType>\nRealType dirichlet_multinomial(const std::vector<RealType>& z, const std::vector<RealType>& a)\n{\n    auto z_0 = std::accumulate(std::cbegin(z), std::cend(z), RealType {0});\n    auto a_0 = std::accumulate(std::cbegin(a), std::cend(a), RealType {0});\n    RealType z_m {1};\n    using detail::ifactorial;\n    for (auto z_i : z) {\n        z_m *= ifactorial<RealType>(z_i);\n    }\n    RealType g {1};\n    for (std::size_t i {0}; i < z.size(); ++i) {\n        g *= std::tgamma(z[i] + a[i]) / std::tgamma(a[i]);\n    }\n    return (ifactorial<RealType>(z_0) / z_m) * (std::tgamma(a_0) / std::tgamma(z_0 + a_0)) * g;\n}\n\ntemplate <typename RealType>\nRealType beta_binomial(const RealType k, const RealType n, const RealType alpha, const RealType beta)\n{\n    return dirichlet_multinomial<RealType>(k, n - k, alpha, beta);\n}\n\nnamespace detail {\n\ntemplate <typename RealType>\nbool is_mldp_converged(std::vector<RealType>& lhs, const std::vector<RealType>& rhs,\n                       const RealType epsilon)\n{\n    std::transform(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), std::begin(lhs),\n                   [] (const auto a, const auto b) { return std::abs(a - b); });\n    return std::all_of(std::cbegin(lhs), std::cend(lhs),\n                       [epsilon] (const auto x) { return x < epsilon; });\n}\n\n} // namespace detail\n\ntemplate <typename RealType>\nstd::vector<RealType>\ndirichlet_mle(std::vector<RealType> pi, const RealType precision,\n              const unsigned max_iterations = 100, const RealType epsilon = 0.0001)\n{\n    std::transform(std::cbegin(pi), std::cend(pi), std::begin(pi),\n                   [] (const auto p) { return std::log(p); });\n    const auto l = pi.size();\n    const RealType u {RealType {1} / l};\n    std::vector<RealType> result(l, u), curr_result(l, u), means(l, u);\n    for (unsigned n {0}; n < max_iterations; ++n) {\n        RealType v {0};\n        for (std::size_t j {0}; j < l; ++j) {\n            v += means[j] * (pi[j] - boost::math::digamma<RealType>(precision * means[j]));\n        }\n        for (std::size_t k {0}; k < l; ++k) {\n            curr_result[k] = digamma_inv<RealType>(pi[k] - v);\n            means[k] = curr_result[k] / std::accumulate(std::cbegin(curr_result), std::cend(curr_result), RealType {0});\n        }\n        if (detail::is_mldp_converged(result, curr_result, epsilon)) {\n            return curr_result;\n        }\n        result = curr_result;\n    }\n    return result;\n}\n\ntemplate <typename NumericType = float, typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nNumericType probability_true_to_phred(const RealType p)\n{\n    return NumericType{-10} * std::log10(std::max(RealType {1} - p, std::numeric_limits<RealType>::epsilon()));\n}\n\ntemplate <typename NumericType = float, typename RealType,\n          typename = std::enable_if_t<std::is_floating_point<RealType>::value>>\nNumericType probability_true_to_phred(const RealType p, const unsigned precision)\n{\n    return round(static_cast<NumericType>(RealType {-10} * std::log10(std::max(RealType {1} - p, std::numeric_limits<RealType>::epsilon()))), precision);\n}\n\ntemplate <typename RealType = double, typename NumericType>\nRealType phred_to_probability(const NumericType phred)\n{\n    return RealType {1} - std::pow(RealType {10}, RealType {-1} * static_cast<RealType>(phred) / RealType {10});\n}\n\ntemplate <typename MapType>\ntypename MapType::key_type sum_keys(const MapType& map)\n{\n    return std::accumulate(std::cbegin(map), std::cend(map), typename MapType::key_type {},\n                           [] (const auto previous, const auto& p) { return previous + p.first; });\n}\n\ntemplate <typename ResultType, typename MapType, typename UnaryOperation>\nResultType sum_keys(const MapType& map, UnaryOperation op)\n{\n    return std::accumulate(std::cbegin(map), std::cend(map), ResultType {0},\n                           [op] (const auto previous, const auto& p) { return previous + op(p.first); });\n}\n\ntemplate <typename MapType>\ntypename MapType::mapped_type sum_values(const MapType& map)\n{\n    return std::accumulate(std::cbegin(map), std::cend(map), typename MapType::mapped_type {},\n                           [] (const auto previous, const auto& p) { return previous + p.second; });\n}\n\ntemplate <typename ResultType, typename MapType, typename UnaryOperation>\nResultType sum_values(const MapType& map, UnaryOperation op)\n{\n    return std::accumulate(std::cbegin(map), std::cend(map), ResultType {0},\n                           [op] (const auto previous, const auto& p) { return previous + op(p.second); });\n}\n\ntemplate <typename Map>\nstd::size_t sum_sizes(const Map& map)\n{\n    return std::accumulate(std::cbegin(map), std::cend(map), std::size_t {0},\n                           [] (const auto& p, const auto& v) { return p + v.second.size(); });\n}\n\ntemplate <typename InputIt1, typename InputIt2, typename InputIt3, typename T,\n          typename BinaryOperation1, typename BinaryOperation2>\nT inner_product(InputIt1 first1, InputIt1 last1,\n                InputIt2 first2, InputIt3 first3, T value,\n                BinaryOperation1 op1, BinaryOperation2 op2)\n{\n    while (first1 != last1) {\n        value = op1(value, op2(*first1, *first2, *first3));\n        ++first1;\n        ++first2;\n        ++first3;\n    }\n    return value;\n}\n\ntemplate <typename InputIt1, typename InputIt2, typename InputIt3, typename InputIt4,\n          typename T, typename BinaryOperation1, typename BinaryOperation2>\nT inner_product(InputIt1 first1, InputIt1 last1,\n                InputIt2 first2, InputIt3 first3,\n                InputIt4 first4, T value,\n                BinaryOperation1 op1, BinaryOperation2 op2)\n{\n    while (first1 != last1) {\n        value = op1(value, op2(*first1, *first2, *first3, *first4));\n        ++first1;\n        ++first2;\n        ++first3;\n        ++first4;\n    }\n    return value;\n}\n\ntemplate <typename RealType>\nRealType beta_cdf(const RealType a, const RealType b, const RealType x)\n{\n    const boost::math::beta_distribution<> beta_dist {a, b};\n    return boost::math::cdf(beta_dist, x);\n}\n\ntemplate <typename RealType>\nRealType beta_sf(const RealType a, const RealType b, const RealType x)\n{\n    const boost::math::beta_distribution<> beta_dist {a, b};\n    return boost::math::cdf(boost::math::complement(beta_dist, x));\n}\n\ntemplate <typename RealType>\nRealType beta_tail_probability(const RealType a, const RealType b, const RealType x)\n{\n    return beta_cdf(a, b, x) + beta_sf(a, b, RealType {1} - x);\n}\n\nnamespace detail {\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nuniform_hdi(const RealType mass)\n{\n    const auto x = RealType {0.5} - mass / 2;\n    return std::make_pair(x, x + mass);\n}\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nbeta_hdi_symmetric(const RealType a, const RealType mass)\n{\n    const auto x = boost::math::ibeta_inv(a, a, (RealType {1} - mass) / 2);\n    return std::make_pair(x, RealType {1} - x);\n}\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nbeta_hdi_unbounded_rhs(const RealType a, const RealType mass)\n{\n    // Reverse J shaped\n    return std::make_pair(boost::math::ibeta_inv(a, RealType {1}, RealType {1} - mass), RealType {1});\n}\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nbeta_hdi_unbounded_lhs(const RealType b, const RealType mass)\n{\n    // J shaped\n    return std::make_pair(RealType {0}, boost::math::ibeta_inv(RealType {1}, b, mass));\n}\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nbeta_hdi_skewed(const RealType a, const RealType b, const RealType mass)\n{\n    const auto c = (RealType {1} - mass) / 2;\n    return std::make_pair(boost::math::ibeta_inv(a, b, c), boost::math::ibeta_inv(a, b, c + mass));\n}\n\n} // namespace detail\n\ntemplate <typename RealType>\nstd::pair<RealType, RealType>\nbeta_hdi(RealType a, RealType b, const RealType mass)\n{\n    static_assert(std::is_floating_point<RealType>::value, \"beta_hdi only works for floating point types\");\n    if (mass < RealType {0} || mass > RealType {1}) {\n        throw std::domain_error {\"beta_hdi: given mass not in range [0, 1]\"};\n    }\n    if (a <= RealType {0} || b <= RealType {0}) {\n        throw std::domain_error {\"beta_hdi: given non-positive parameter\"};\n    }\n    if (mass == RealType {0}) {\n        const auto mean = a / (a + b);\n        return std::make_pair(mean, mean);\n    }\n    if (mass == RealType {1}) {\n        return std::make_pair(RealType {0}, RealType {1});\n    }\n    if (a == b) {\n        if (a == RealType {1}) {\n            return detail::uniform_hdi(mass);\n        } else {\n            return detail::beta_hdi_symmetric(a, mass);\n        }\n    }\n    if (a == RealType {1}) {\n        return detail::beta_hdi_unbounded_lhs(b, mass);\n    }\n    if (b == RealType {1}) {\n        return detail::beta_hdi_unbounded_rhs(a, mass);\n    }\n    return detail::beta_hdi_skewed(a, b, mass);\n}\n\ntemplate <typename RealType>\nRealType dirichlet_variance(const std::vector<RealType>& alphas, const std::size_t k)\n{\n    const auto a_0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), RealType {});\n    return (alphas[k] * (a_0 - alphas[k])) / (a_0 * a_0 * (a_0 + 1));\n}\n\ntemplate <typename RealType>\nRealType dirichlet_marginal_cdf(const std::vector<RealType>& alphas, const std::size_t k, const RealType x)\n{\n    const auto a_0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), RealType {});\n    return beta_cdf(alphas[k], a_0 - alphas[k], x);\n}\n\ntemplate <typename RealType>\nRealType dirichlet_marginal_sf(const std::vector<RealType>& alphas, const std::size_t k, const RealType x)\n{\n    const auto a_0 = std::accumulate(std::cbegin(alphas), std::cend(alphas), RealType {});\n    return beta_sf(alphas[k], a_0 - alphas[k], x);\n}\n\ntemplate <typename Range>\nvoid log_each(Range& values)\n{\n    for (auto& v : values) v = std::log(v);\n}\n\ntemplate <typename Range>\nvoid exp_each(Range& values)\n{\n    for (auto& v : values) v = std::exp(v);\n}\n\ntemplate <typename ForwardIterator>\nauto normalise(const ForwardIterator first, const ForwardIterator last)\n{\n    using T = typename std::iterator_traits<ForwardIterator>::value_type;\n    const auto norm = std::accumulate(first, last, T {});\n    if (norm > 0) std::for_each(first, last, [norm] (auto& value) { value /= norm; });\n    return norm;\n}\n\ntemplate <typename Range>\nauto normalise(Range& values)\n{\n    return normalise(std::begin(values), std::end(values));\n}\n\ntemplate <typename ForwardIterator>\nauto normalise_logs(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto norm = log_sum_exp(first, last);\n    std::for_each(first, last, [norm] (auto& value) { value -= norm; });\n    return norm;\n}\n\ntemplate <typename Range>\nauto normalise_logs(Range& logs)\n{\n    return normalise_logs(std::begin(logs), std::end(logs));\n}\n\ntemplate <typename ForwardIterator>\nauto normalise_exp(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto norm = log_sum_exp(first, last);\n    std::transform(first, last, first, [norm] (auto& value) { return std::exp(value - norm); });\n    return norm;\n}\n\ntemplate <typename Range>\nauto normalise_exp(Range& logs)\n{\n    return normalise_exp(std::begin(logs), std::end(logs));\n}\n\n} // namespace maths\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "649cba37d5893d0e37a527073c24ad7223e9772c", "size": 40071, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/maths.hpp", "max_stars_repo_name": "roryk/octopus", "max_stars_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_stars_repo_licenses": ["MIT"], "max_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/maths.hpp", "max_issues_repo_name": "roryk/octopus", "max_issues_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_issues_repo_licenses": ["MIT"], "max_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/maths.hpp", "max_forks_repo_name": "roryk/octopus", "max_forks_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_forks_repo_licenses": ["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.2737676056, "max_line_length": 153, "alphanum_fraction": 0.6776970877, "num_tokens": 10433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5652243851587777}}
{"text": "#include <iostream>\n#include <ctime>  \n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include \"boost/program_options.hpp\"\n#include \"boost/random.hpp\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace boost::numeric::ublas;\n\ntypedef matrix<double, column_major> uBlasMat;\ntypedef vector<double, column_major> uBlasVec;\ntypedef boost::minstd_rand base_generator_type;\ntypedef boost::variate_generator<base_generator_type&, boost::uniform_real<> > rng;\n\n\nuBlasMat initMatrix(uBlasMat &mat, rng &rnd) {\n\n  for (unsigned i = 0; i < mat.size1(); ++i) {\n    for (unsigned j = 0; j < mat.size2(); ++j) {\n      mat (i, j) = rnd();\n    }\n  }\n\n  return mat;\n}\n\nuBlasVec initVector(uBlasVec &vec, rng &rnd) {\n\n  for (unsigned i = 0; i < mat.size(); ++i) {\n      vec (i) = rnd();\n  }\n\n  return vec;\n}\n\n// m: numRows, n: numCols\ninline double simpleDenseTest_UBlas(int m, int n, int num_trials) {\n  base_generator_type generator(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  rng uni(generator, uni_dist);\n\n  uBlasMat A(m, n); initMatrix(A, uni);\n  uBlasMat B(m, n); initMatrix(B, uni);\n  uBlasMat C(m, n); initMatrix(C, uni);\n  uBlasMat D(m, n); initMatrix(D, uni);\n  uBlasMat E(m, n); initMatrix(E, uni);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    uBlasMat res = element_prod((element_div((A + B), C) - D), E);\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmSanityTest_UBlas(int m, int n, int k, int num_trials) {\n\n  base_generator_type generator(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  rng uni(generator, uni_dist);\n  uBlasMat A(m, n); initMatrix(A, uni);\n  uBlasMat C(n, k); initMatrix(C, uni);\n  uBlasMat E(m, k); initMatrix(E, uni);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E += prod(A, C);\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmDenseTest_UBlas(int m, int n, int k, int num_trials) {\n\n  base_generator_type generator(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  rng uni(generator, uni_dist);\n  uBlasMat A(m, n); initMatrix(A, uni);\n  uBlasMat B(m, n); initMatrix(B, uni);\n  uBlasMat C(n, k); initMatrix(C, uni);\n  uBlasMat D(n, k); initMatrix(D, uni);\n  uBlasMat E(m, k); initMatrix(E, uni);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    E += prod((A + B), (C - D));\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n}\n\ninline double mulDenseTest_UBlas(int a, int b, int c, int d, int num_trials) {\n\n  base_generator_type generator(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  rng uni(generator, uni_dist);\n  uBlasMat A(a, a); initMatrix(A, uni);\n  uBlasMat B(a, b); initMatrix(B, uni);\n  uBlasMat C(b, c); initMatrix(C, uni);\n  uBlasMat D(c, d); initMatrix(D, uni);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    uBlasMat res = uBlasMat(prod(uBlasMat(prod(uBlasMat(prod(A, B)), C)), D));\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n  return duration / num_trials;\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double denseVectorTest_UBlas(int l, int num_trials) {\n\n  base_generator_type generator(42u);\n  boost::uniform_real<> uni_dist(0,1);\n  rng uni(generator, uni_dist);\n  uBlasVec a(l); initVector(a, uni);\n  uBlasVec b(l); initVector(b, uni);\n  uBlasVec c(l); initVector(c, uni);\n  uBlasVec d(l); initVector(d, uni);\n  uBlasVec res(l);\n\n  clock_t start;\n  start = clock();\n  for (unsigned i = 0; i < num_trials; i++) {\n\n    res = a + b + c + d;\n\n  }\n  double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n  return duration / num_trials;\n}\n\nvoid runUBlasTests(int num_trials, int l, int m, int n, int k, int a, int b, int c, int d,\n    bool skip_vec, bool skip_simple, bool skip_gemm, bool skip_mult) {\n\n  if (!skip_vec)\n      cout << \"UBlas Vectors Test:\\t\" << denseVectorTest_UBlas(l, num_trials) << endl;\n  if (!skip_simple)\n    cout << \"UBlas Simple Test:\\t\" << simpleDenseTest_UBlas(m, n, num_trials) << endl;\n  if (!skip_gemm) {\n    cout << \"UBlas gemmSanity Test:\\t\" << gemmDenseTest_UBlas(m, n, k, num_trials) << endl;\n    cout << \"UBlas gemm Test:\\t\" << gemmDenseTest_UBlas(m, n, k, num_trials) << endl;\n  }\n\n  if (!skip_mult)\n    cout << \"UBlas mulDense Test:\\t\" << mulDenseTest_UBlas(a, b, c, d, num_trials) << endl;\n\n}\n\nint main(int argc, char *argv[]) {\n\n    int l, m, n, k, a, b, c, d, trials;\n    bool skip_vec, skip_simple, skip_gemm, skip_mult;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"l\", po::value<int>(&l)->default_value(1048576),\n                    \"length of vectors in vector addition test\")\n        (\"m\", po::value<int>(&m)->default_value(1024),\n            \"numRows of matrices in Simple Test, and gemm Test\")\n        (\"n\", po::value<int>(&n)->default_value(1024),\n            \"numCols of matrices in Simple Test, and gemm Test\")\n        (\"k\", po::value<int>(&k)->default_value(1024),\n            \"numCols of B in gemm Test\")\n        (\"trials\", po::value<int>(&trials)->default_value(10), \"number of trials\")\n        (\"a\", po::value<int>(&a)->default_value(1024),\n            \"size matrix A in mulDense Test\")\n        (\"b\", po::value<int>(&b)->default_value(512),\n            \"size matrix B in mulDense Test\")\n        (\"c\", po::value<int>(&c)->default_value(256),\n            \"size matrix C in mulDense Test\")\n        (\"d\", po::value<int>(&d)->default_value(128),\n            \"size matrix D in mulDense Test\")\n        (\"skip-vec\", po::value<bool>(&skip_vec)->default_value(false),\n            \"skip vectors Test\")\n        (\"skip-simple\", po::value<bool>(&skip_simple)->default_value(false),\n            \"skip simple Test\")\n        (\"skip-gemm\", po::value<bool>(&skip_gemm)->default_value(false),\n            \"skip gemm Tests\")\n        (\"skip-mult\", po::value<bool>(&skip_mult)->default_value(false),\n            \"skip mulDense Test\")\n    ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    runUBlasTests(trials, l, m, n, k, a, b, c, d, skip_vec, skip_simple, skip_gemm, skip_mult);\n\n    return 0;\n}\n", "meta": {"hexsha": "fbd4a8134f20782188cd60655d333b12a73da2fb", "size": 6711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/ublas.cpp", "max_stars_repo_name": "brkyvz/linalg-benchmarks", "max_stars_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/cpp/ublas.cpp", "max_issues_repo_name": "brkyvz/linalg-benchmarks", "max_issues_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/cpp/ublas.cpp", "max_forks_repo_name": "brkyvz/linalg-benchmarks", "max_forks_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3598130841, "max_line_length": 95, "alphanum_fraction": 0.6341826851, "num_tokens": 2070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5652243851587777}}
{"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 <fstream>\n#include <string>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include \"dbscan.h\"\n\nusing namespace std;\nnamespace clustering {\n    DBSCAN::ClusterData DBSCAN::gen_cluster_data( size_t features_num, size_t elements_num ,double* data)//load data for clustering\n{\n    DBSCAN::ClusterData cl_d( elements_num, features_num );\n\n    for ( size_t i = 0; i < elements_num; ++i )\n    {\n        for ( size_t j = 0; j < features_num; ++j )\n        {\n            cl_d( i, j ) = data[i*features_num+j];\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 0;//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 \n    //save clusters\nint DBSCAN::save_labels(std::string name, std::vector <std::string> ndata, std::vector <std::string> uid,std::vector <int>* ind, double * data)\n{\n    std::vector <std::vector <int>> final;\n    std::vector <int> tmp;\n\n    int mm=0;\n    for (int j=0;j<m_labels.size();j++)\n    {\n        if((mm)<m_labels[j])\n            mm=m_labels[j];\n        ind->push_back(m_labels[j]);\n    }\n    \n    //assign a cluster to each unassigned one I need Y to claculate the centres and then\n    \n    for (int j=0;j<=mm;j++)\n    {\n        final.push_back(tmp);\n    }\n    \n    std::ofstream myfile (name);\n    \n  //  std::vector <double> cen;\n  //  std::vector <int> ss;\n    \n/*    for(int i=0;i<=2*mm+1;i++)\n    {\n        cen.push_back(0);\n        ss.push_back(0);\n    }\n    for (int i=0;i<ind->size();i++)\n    {\n        if(ind->at(i)>=0)\n        {\n            cen[ind->at(i)*2+1]=data[i*2+1];\n            cen[ind->at(i)*2]=data[i*2];\n            ss[ind->at(i)*2+1]++;\n            ss[ind->at(i)*2]++;\n        }\n    }\n    \n    for (int i=0;i<cen.size();i++)\n        cen[i]/=ss[i];\n\n    ss.clear();*/\n    for (int j=0;j<ind->size();j++)\n    {\n        if(ind->at(j)>=0)\n            final[ind->at(j)].push_back(j);\n      /*  else\n        {\n            double mind=1000000;\n            int mini=-1;\n            for (int i=0;i<=mm;i++)\n            {\n                double dist=sqrt((data[j*2+1]-cen[i*2+1])*(data[j*2+1]-cen[i*2+1])+(data[j*2]-cen[i*2])*(data[j*2]-cen[i*2]));\n                if(dist<mind)\n                {\n                    mind=dist;\n                    mini=i;\n                }\n            }\n            ind->at(j)=mini;\n            if(mini>=0)\n                final[ind->at(j)].push_back(j);\n        }*/\n        myfile<<ind->at(j)<<\", \";\n    }\n    myfile.close();\n    \n //   cen.clear();\n    for (int j=0;j<final.size();j++)\n    {\n        tmp.clear();\n        copy((final[j]).begin(),final[j].end(),back_inserter(tmp));\n        stringstream ss;\n        ss << j;\n        string str = ss.str();\n        std::string name1=name+str;//static_cast<ostringstream*>( &(ostringstream() << j) )->str();\n        std::ofstream myfile (name1);\n        for (int k=0;k<tmp.size();k++)\n        {\n            myfile<<'>'<< uid[tmp[k]]<<\"\\n\";\n            myfile<<  ndata[tmp[k]]<<\"\\n\";\n        }\n        myfile.close();\n    }\n    final.clear();\n    tmp.clear();\n    return mm;\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": "3cfaa2fa4b14134eb49eecc822a06517c2c51fde", "size": 8380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dbscan.cpp", "max_stars_repo_name": "skouchaki/MLBP_BIN", "max_stars_repo_head_hexsha": "1abeb231b5e7af0e3ae55ee1b0906ccfb911c51a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-17T14:21:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T09:07:22.000Z", "max_issues_repo_path": "dbscan.cpp", "max_issues_repo_name": "skouchaki/MLBP_BIN", "max_issues_repo_head_hexsha": "1abeb231b5e7af0e3ae55ee1b0906ccfb911c51a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-01-09T13:51:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-07T15:53:48.000Z", "max_forks_repo_path": "dbscan.cpp", "max_forks_repo_name": "skouchaki/MLBP_BIN", "max_forks_repo_head_hexsha": "1abeb231b5e7af0e3ae55ee1b0906ccfb911c51a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-01T14:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-13T09:33:59.000Z", "avg_line_length": 24.6470588235, "max_line_length": 143, "alphanum_fraction": 0.5059665871, "num_tokens": 2382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5652243802370985}}
{"text": "#pragma once\n#include <pdqsort.h>\n\n#include <Eigen/Core>\n#include <numeric>\n\nnamespace cpz {\nnamespace {\n  template <typename Derived> bool is_regular(const Eigen::MatrixBase<Derived>& exponents) {\n    const unsigned int num_cols = exponents.cols();\n    for (unsigned int i = 0; i < num_cols - 1; ++i) {\n      const auto& col = exponents.col(i);\n      if (col.isZero()) {\n        return false;\n      }\n\n      if (col == exponents.col(i + 1)) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  template <typename Derived>\n  void permute_cols(Eigen::MatrixBase<Derived>& mat, std::vector<int>& permutation) {\n    const unsigned int num_cols = mat.cols();\n    unsigned int idx            = 0;\n    int swap_start              = -1;\n    unsigned int count          = 0;\n    int permutation_idx         = -1;\n    while (count < num_cols) {\n      // Find the start point of the next chain of swaps\n      ++swap_start;\n      while (swap_start < num_cols && permutation[swap_start] < 0) {\n        ++swap_start;\n      }\n\n      // Follow the chain of swaps\n      idx             = swap_start;\n      permutation_idx = permutation[swap_start];\n      ++count;\n      while (permutation_idx != swap_start) {\n        mat.col(idx).swap(mat.col(permutation_idx));\n        permutation[idx] = -1;\n        idx              = permutation_idx;\n        permutation_idx  = permutation[permutation_idx];\n        ++count;\n      }\n\n      permutation[idx] = -1;\n    }\n  }\n\n  template <typename Derived> auto unique_columns(const Eigen::MatrixBase<Derived>& exponents) {\n    std::vector<std::vector<unsigned int>> column_groups;\n    std::vector<unsigned int> unique_indices = {0};\n    int curr_col                             = 0;\n    std::vector<unsigned int> curr_group     = {0};\n    const unsigned int num_cols              = exponents.cols();\n    for (unsigned int i = 1; i < num_cols; ++i) {\n      if (exponents.col(curr_col) != exponents.col(i)) {\n        column_groups.push_back(curr_group);\n        unique_indices.push_back(i);\n        curr_group.clear();\n        curr_col = i;\n      }\n\n      curr_group.push_back(i);\n    }\n\n    column_groups.push_back(curr_group);\n    return std::make_pair(column_groups, exponents(Eigen::all, unique_indices));\n  }\n\n  template <typename D1, typename D2>\n  auto\n  regularize(const Eigen::MatrixBase<D1>& exponents, const Eigen::MatrixBase<D2>& generators) {\n    const auto [column_groups, new_exponents] = unique_columns(exponents);\n    const unsigned int num_groups             = column_groups.size();\n    D2 new_generators(generators.rows(), num_groups);\n    for (unsigned int i = 0; i < num_groups; ++i) {\n      new_generators.col(i).noalias() = generators(Eigen::all, column_groups[i]).rowwise().sum();\n    }\n\n    return std::make_pair(new_exponents, new_generators);\n  }\n\n  template <typename D1, typename D2>\n  void ensure_regular(Eigen::MatrixBase<D1>& exponents, Eigen::MatrixBase<D2>& generators) {\n    // First, sort the exponents and generators according to the exponents\n    const unsigned int num_cols = exponents.cols();\n    const unsigned int num_rows = exponents.rows();\n    if (num_cols == 0 || num_rows == 0) {\n      return;\n    }\n\n    std::vector<int> permutation(num_cols);\n    std::iota(permutation.begin(), permutation.end(), 0);\n    pdqsort(permutation.begin(),\n            permutation.end(),\n            [&exponents, num_rows](const int i, const int j) -> bool {\n              const auto col_a = exponents.col(i);\n              const auto col_b = exponents.col(j);\n              for (unsigned int i = 0; i < num_rows; ++i) {\n                const auto val_a = col_a[i];\n                const auto val_b = col_b[i];\n                if (val_a != val_b) {\n                  return val_a < val_b;\n                }\n              }\n\n              return false;\n            });\n\n    // Then, apply the permutation in-place to sort the matrices\n    // Because permute_cols modifies the permutation vector, we make a copy\n    std::vector<int> permutation_copy(permutation);\n    permute_cols(exponents, permutation_copy);\n    permute_cols(generators, permutation);\n\n    // Finally, check if the exponents matrix is regular and apply regularization if it is not\n    if (!is_regular(exponents)) {\n      std::tie(exponents, generators) = regularize(exponents, generators);\n    }\n  }\n}  // namespace\n\ntemplate <typename F                  = float,\n          int Dims                    = Eigen::Dynamic,\n          int NumGenerators           = Eigen::Dynamic,\n          int NumFactors              = Eigen::Dynamic,\n          int NumConstraints          = Eigen::Dynamic,\n          int NumConstraintGenerators = Eigen::Dynamic>\nstruct ConstrainedPolynomialZonotope {\n protected:\n  inline void regularize_cpz() noexcept {\n    ensure_regular(this->exponents, this->generators);\n    ensure_regular(this->constraint_exponents, this->constraint_generators);\n  }\n\n  template <int Size> using Vector     = Eigen::Matrix<F, Size, 1>;\n  template <int R, int C> using Matrix = Eigen::Matrix<F, R, C>;\n\n public:\n  Vector<Dims> center;\n  Matrix<Dims, NumGenerators> generators;\n  Matrix<NumFactors, NumGenerators> exponents;\n  Vector<NumConstraints> constraints;\n  Matrix<NumConstraints, NumConstraintGenerators> constraint_generators;\n  Matrix<NumFactors, NumConstraintGenerators> constraint_exponents;\n\n  ConstrainedPolynomialZonotope(\n  const Vector<Dims>& center,\n  const Matrix<Dims, NumGenerators>& generators,\n  const Matrix<NumFactors, NumGenerators>& exponents,\n  const Vector<NumConstraints>& constraints,\n  const Matrix<NumConstraints, NumConstraintGenerators>& constraint_generators,\n  const Matrix<NumFactors, NumConstraintGenerators>& constraint_exponents)\n  : center(center)\n  , generators(generators)\n  , exponents(exponents)\n  , constraints(constraints)\n  , constraint_generators(constraint_generators)\n  , constraint_exponents(constraint_exponents) {\n    regularize_cpz();\n  }\n\n  ConstrainedPolynomialZonotope(\n  const Vector<Dims>&& center,\n  const Matrix<Dims, NumGenerators>&& generators,\n  const Matrix<NumFactors, NumGenerators>&& exponents,\n  const Vector<NumConstraints>&& constraints,\n  const Matrix<NumConstraints, NumConstraintGenerators>&& constraint_generators,\n  const Matrix<NumFactors, NumConstraintGenerators>&& constraint_exponents)\n  : center(center)\n  , generators(generators)\n  , exponents(exponents)\n  , constraints(constraints)\n  , constraint_generators(constraint_generators)\n  , constraint_exponents(constraint_exponents) {\n    regularize_cpz();\n  }\n};\n}  // namespace cpz\n", "meta": {"hexsha": "8536ca0fa3ce081bab9e36fa8514aee37ce646b9", "size": 6539, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/cpzlib.hh", "max_stars_repo_name": "wbthomason/cpzlib", "max_stars_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cpzlib.hh", "max_issues_repo_name": "wbthomason/cpzlib", "max_issues_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cpzlib.hh", "max_forks_repo_name": "wbthomason/cpzlib", "max_forks_repo_head_hexsha": "d0361c91d634480e60988a396c02334b5fccb44e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T19:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T19:25:24.000Z", "avg_line_length": 35.1559139785, "max_line_length": 97, "alphanum_fraction": 0.651781618, "num_tokens": 1552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5651570868431803}}
{"text": "/**\n * Copyright 2021 Huawei Technologies Co., Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"minddata/dataset/audio/kernels/audio_utils.h\"\n\n#include <Eigen/Dense>\n#include <fstream>\n\n#include \"mindspore/core/base/float16.h\"\n#include \"minddata/dataset/core/type_id.h\"\n#include \"minddata/dataset/kernels/data/data_utils.h\"\n#include \"minddata/dataset/util/random.h\"\n#include \"utils/file_utils.h\"\n\nnamespace mindspore {\nnamespace dataset {\n/// \\brief Generate linearly spaced vector.\n/// \\param[in] start - Value of the startpoint.\n/// \\param[in] end - Value of the endpoint.\n/// \\param[in] n - N points in the output tensor.\n/// \\param[out] output - Tensor has n points with linearly space. The spacing between the points is (end-start)/(n-1).\n/// \\return Status return code.\ntemplate <typename T>\nStatus Linspace(std::shared_ptr<Tensor> *output, T start, T end, int n) {\n  if (start > end) {\n    std::string err = \"Linspace: input param end must be greater than start.\";\n    RETURN_STATUS_UNEXPECTED(err);\n  }\n  n = std::isnan(n) ? 100 : n;\n  TensorShape out_shape({n});\n  std::vector<T> linear_vect(n);\n  T interval = (n == 1) ? 0 : ((end - start) / (n - 1));\n  for (auto i = 0; i < linear_vect.size(); ++i) {\n    linear_vect[i] = start + i * interval;\n  }\n  std::shared_ptr<Tensor> out_t;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(linear_vect, out_shape, &out_t));\n  linear_vect.clear();\n  linear_vect.shrink_to_fit();\n  *output = out_t;\n  return Status::OK();\n}\n\n/// \\brief Calculate complex tensor angle.\n/// \\param[in] input - Input tensor, must be complex, <channel, freq, time, complex=2>.\n/// \\param[out] output - Complex tensor angle.\n/// \\return Status return code.\ntemplate <typename T>\nStatus ComplexAngle(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output) {\n  // check complex\n  if (!input->IsComplex()) {\n    std::string err_msg = \"ComplexAngle: input tensor is not in shape of <..., 2>.\";\n    LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg);\n  }\n  TensorShape input_shape = input->shape();\n  TensorShape out_shape({input_shape[0], input_shape[1], input_shape[2]});\n  std::vector<T> phase(input_shape[0] * input_shape[1] * input_shape[2]);\n  int ind = 0;\n\n  for (auto itr = input->begin<T>(); itr != input->end<T>(); itr++, ind++) {\n    auto x = (*itr);\n    itr++;\n    auto y = (*itr);\n    phase[ind] = atan2(y, x);\n  }\n\n  std::shared_ptr<Tensor> out_t;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(phase, out_shape, &out_t));\n  phase.clear();\n  phase.shrink_to_fit();\n  *output = out_t;\n  return Status::OK();\n}\n\n/// \\brief Calculate complex tensor abs.\n/// \\param[in] input - Input tensor, must be complex, <channel, freq, time, complex=2>.\n/// \\param[out] output - Complex tensor abs.\n/// \\return Status return code.\ntemplate <typename T>\nStatus ComplexAbs(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output) {\n  // check complex\n  if (!input->IsComplex()) {\n    std::string err_msg = \"ComplexAngle: input tensor is not in shape of <..., 2>.\";\n    LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg);\n  }\n  TensorShape input_shape = input->shape();\n  TensorShape out_shape({input_shape[0], input_shape[1], input_shape[2]});\n  std::vector<T> abs(input_shape[0] * input_shape[1] * input_shape[2]);\n  int ind = 0;\n  for (auto itr = input->begin<T>(); itr != input->end<T>(); itr++, ind++) {\n    T x = (*itr);\n    itr++;\n    T y = (*itr);\n    abs[ind] = sqrt(pow(y, 2) + pow(x, 2));\n  }\n\n  std::shared_ptr<Tensor> out_t;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(abs, out_shape, &out_t));\n  *output = out_t;\n  return Status::OK();\n}\n\n/// \\brief Reconstruct complex tensor from norm and angle.\n/// \\param[in] abs - The absolute value of the complex tensor.\n/// \\param[in] angle - The angle of the complex tensor.\n/// \\param[out] output - Complex tensor, <channel, freq, time, complex=2>.\n/// \\return Status return code.\ntemplate <typename T>\nStatus Polar(const std::shared_ptr<Tensor> &abs, const std::shared_ptr<Tensor> &angle,\n             std::shared_ptr<Tensor> *output) {\n  // check shape\n  if (abs->shape() != angle->shape()) {\n    std::string err_msg = \"Polar: input tensor shape of abs and angle must be the same.\";\n    LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg);\n  }\n\n  TensorShape input_shape = abs->shape();\n  TensorShape out_shape({input_shape[0], input_shape[1], input_shape[2], 2});\n  std::vector<T> complex_vec(input_shape[0] * input_shape[1] * input_shape[2] * 2);\n  int ind = 0;\n  auto itr_abs = abs->begin<T>();\n  auto itr_angle = angle->begin<T>();\n\n  for (; itr_abs != abs->end<T>(); itr_abs++, itr_angle++) {\n    complex_vec[ind++] = cos(*itr_angle) * (*itr_abs);\n    complex_vec[ind++] = sin(*itr_angle) * (*itr_abs);\n  }\n\n  std::shared_ptr<Tensor> out_t;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(complex_vec, out_shape, &out_t));\n  *output = out_t;\n  return Status::OK();\n}\n\n/// \\brief Pad complex tensor.\n/// \\param[in] input - The complex tensor.\n/// \\param[in] length - The length of padding.\n/// \\param[in] dim - The dim index for padding.\n/// \\param[out] output - Complex tensor, <channel, freq, time, complex=2>.\n/// \\return Status return code.\ntemplate <typename T>\nStatus PadComplexTensor(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int length, int dim) {\n  TensorShape input_shape = input->shape();\n  std::vector<int64_t> pad_shape_vec = {input_shape[0], input_shape[1], input_shape[2], input_shape[3]};\n  pad_shape_vec[dim] += static_cast<int64_t>(length);\n  TensorShape input_shape_with_pad(pad_shape_vec);\n  std::vector<T> in_vect(input_shape_with_pad[0] * input_shape_with_pad[1] * input_shape_with_pad[2] *\n                         input_shape_with_pad[3]);\n  auto itr_input = input->begin<T>();\n  int64_t input_cnt = 0;\n  /*lint -e{446} ind is modified in the body of the for loop */\n  for (int ind = 0; ind < static_cast<int>(in_vect.size()); ind++) {\n    in_vect[ind] = (*itr_input);\n    input_cnt = (input_cnt + 1) % (input_shape[2] * input_shape[3]);\n    itr_input++;\n    // complex tensor last dim equals 2, fill zero count equals 2*width\n    if (input_cnt == 0 && ind != 0) {\n      for (int c = 0; c < length * 2; c++) {\n        in_vect[++ind] = 0.0f;\n      }\n    }\n  }\n  std::shared_ptr<Tensor> out_t;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(in_vect, input_shape_with_pad, &out_t));\n  *output = out_t;\n  return Status::OK();\n}\n\n/// \\brief Calculate phase.\n/// \\param[in] angle_0 - The angle.\n/// \\param[in] angle_1 - The angle.\n/// \\param[in] phase_advance - The phase advance.\n/// \\param[in] phase_time0 - The phase at time 0.\n/// \\param[out] output - Phase tensor.\n/// \\return Status return code.\ntemplate <typename T>\nStatus Phase(const std::shared_ptr<Tensor> &angle_0, const std::shared_ptr<Tensor> &angle_1,\n             const std::shared_ptr<Tensor> &phase_advance, const std::shared_ptr<Tensor> &phase_time0,\n             std::shared_ptr<Tensor> *output) {\n  TensorShape phase_shape = angle_0->shape();\n  std::vector<T> phase(phase_shape[0] * phase_shape[1] * phase_shape[2]);\n  auto itr_angle_0 = angle_0->begin<T>();\n  auto itr_angle_1 = angle_1->begin<T>();\n  auto itr_pa = phase_advance->begin<T>();\n  for (int ind = 0, input_cnt = 0; itr_angle_0 != angle_0->end<T>(); itr_angle_0++, itr_angle_1++, ind++) {\n    if (ind != 0 && ind % phase_shape[2] == 0) {\n      itr_pa++;\n      if (itr_pa == phase_advance->end<T>()) {\n        itr_pa = phase_advance->begin<T>();\n      }\n      input_cnt++;\n    }\n    phase[ind] = (*itr_angle_1) - (*itr_angle_0) - (*itr_pa);\n    phase[ind] = phase[ind] - 2 * PI * round(phase[ind] / (2 * PI)) + (*itr_pa);\n  }\n\n  // concat phase time 0\n  int64_t ind = 0;\n  auto itr_p0 = phase_time0->begin<T>();\n  (void)phase.insert(phase.begin(), (*itr_p0));\n  itr_p0++;\n  while (itr_p0 != phase_time0->end<T>()) {\n    ind += phase_shape[2];\n    phase[ind] = (*itr_p0);\n    itr_p0++;\n  }\n  (void)phase.erase(phase.begin() + static_cast<int>(angle_0->Size()), phase.end());\n\n  // cal phase accum\n  for (ind = 0; ind < static_cast<int64_t>(phase.size()); ind++) {\n    if (ind % phase_shape[2] != 0) {\n      phase[ind] = phase[ind] + phase[ind - 1];\n    }\n  }\n  std::shared_ptr<Tensor> phase_tensor;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(phase, phase_shape, &phase_tensor));\n  *output = phase_tensor;\n  return Status::OK();\n}\n\n/// \\brief Calculate magnitude.\n/// \\param[in] alphas - The alphas.\n/// \\param[in] abs_0 - The norm.\n/// \\param[in] abs_1 - The norm.\n/// \\param[out] output - Magnitude tensor.\n/// \\return Status return code.\ntemplate <typename T>\nStatus Mag(const std::shared_ptr<Tensor> &abs_0, const std::shared_ptr<Tensor> &abs_1, std::shared_ptr<Tensor> *output,\n           const std::vector<T> &alphas) {\n  TensorShape mag_shape = abs_0->shape();\n  std::vector<T> mag(mag_shape[0] * mag_shape[1] * mag_shape[2]);\n  auto itr_abs_0 = abs_0->begin<T>();\n  auto itr_abs_1 = abs_1->begin<T>();\n  for (int ind = 0; itr_abs_0 != abs_0->end<T>(); itr_abs_0++, itr_abs_1++, ind++) {\n    mag[ind] = alphas[ind % mag_shape[2]] * (*itr_abs_1) + (1 - alphas[ind % mag_shape[2]]) * (*itr_abs_0);\n  }\n  std::shared_ptr<Tensor> mag_tensor;\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(mag, mag_shape, &mag_tensor));\n  *output = mag_tensor;\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus TimeStretch(std::shared_ptr<Tensor> input, std::shared_ptr<Tensor> *output, float rate,\n                   std::shared_ptr<Tensor> phase_advance) {\n  // pack <..., freq, time, complex>\n  TensorShape input_shape = input->shape();\n  TensorShape toShape({input->Size() / (input_shape[-1] * input_shape[-2] * input_shape[-3]), input_shape[-3],\n                       input_shape[-2], input_shape[-1]});\n  RETURN_IF_NOT_OK(input->Reshape(toShape));\n  if (rate == 1.0) {\n    *output = input;\n    return Status::OK();\n  }\n  // calculate time step and alphas\n  std::vector<dsize_t> time_steps_0, time_steps_1;\n  std::vector<T> alphas;\n  for (int ind = 0;; ind++) {\n    auto val = ind * rate;\n    if (val >= input_shape[-2]) {\n      break;\n    }\n    int val_int = static_cast<int>(val);\n    time_steps_0.push_back(val_int);\n    time_steps_1.push_back(val_int + 1);\n    alphas.push_back(fmod(val, 1));\n  }\n\n  // calculate phase on time 0\n  std::shared_ptr<Tensor> spec_time0, phase_time0;\n  RETURN_IF_NOT_OK(\n    input->Slice(&spec_time0, std::vector<SliceOption>({SliceOption(true), SliceOption(true),\n                                                        SliceOption(std::vector<dsize_t>{0}), SliceOption(true)})));\n  RETURN_IF_NOT_OK(ComplexAngle<T>(spec_time0, &phase_time0));\n\n  // time pad: add zero to time dim\n  RETURN_IF_NOT_OK(PadComplexTensor<T>(input, &input, 2, 2));\n\n  // slice\n  std::shared_ptr<Tensor> spec_0;\n  RETURN_IF_NOT_OK(input->Slice(&spec_0, std::vector<SliceOption>({SliceOption(true), SliceOption(true),\n                                                                   SliceOption(time_steps_0), SliceOption(true)})));\n  std::shared_ptr<Tensor> spec_1;\n  RETURN_IF_NOT_OK(input->Slice(&spec_1, std::vector<SliceOption>({SliceOption(true), SliceOption(true),\n                                                                   SliceOption(time_steps_1), SliceOption(true)})));\n\n  // new slices angle and abs <channel, freq, time>\n  std::shared_ptr<Tensor> angle_0, angle_1, abs_0, abs_1;\n  RETURN_IF_NOT_OK(ComplexAngle<T>(spec_0, &angle_0));\n  RETURN_IF_NOT_OK(ComplexAbs<T>(spec_0, &abs_0));\n  RETURN_IF_NOT_OK(ComplexAngle<T>(spec_1, &angle_1));\n  RETURN_IF_NOT_OK(ComplexAbs<T>(spec_1, &abs_1));\n\n  // cal phase, there exists precision loss between mindspore and pytorch\n  std::shared_ptr<Tensor> phase_tensor;\n  RETURN_IF_NOT_OK(Phase<T>(angle_0, angle_1, phase_advance, phase_time0, &phase_tensor));\n\n  // calculate magnitude\n  std::shared_ptr<Tensor> mag_tensor;\n  RETURN_IF_NOT_OK(Mag<T>(abs_0, abs_1, &mag_tensor, alphas));\n\n  // reconstruct complex from norm and angle\n  std::shared_ptr<Tensor> complex_spec_stretch;\n  RETURN_IF_NOT_OK(Polar<T>(mag_tensor, phase_tensor, &complex_spec_stretch));\n\n  // unpack\n  auto output_shape_vec = input_shape.AsVector();\n  output_shape_vec.pop_back();\n  output_shape_vec.pop_back();\n  output_shape_vec.push_back(complex_spec_stretch->shape()[-2]);\n  output_shape_vec.push_back(input_shape[-1]);\n  RETURN_IF_NOT_OK(complex_spec_stretch->Reshape(TensorShape(output_shape_vec)));\n  *output = complex_spec_stretch;\n  return Status::OK();\n}\n\nStatus TimeStretch(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, float rate, float hop_length,\n                   float n_freq) {\n  std::shared_ptr<Tensor> phase_advance;\n  switch (input->type().value()) {\n    case DataType::DE_FLOAT32:\n      RETURN_IF_NOT_OK(Linspace<float>(&phase_advance, 0, PI * hop_length, n_freq));\n      RETURN_IF_NOT_OK(TimeStretch<float>(input, output, rate, phase_advance));\n      break;\n    case DataType::DE_FLOAT64:\n      RETURN_IF_NOT_OK(Linspace<double>(&phase_advance, 0, PI * hop_length, n_freq));\n      RETURN_IF_NOT_OK(TimeStretch<double>(input, output, rate, phase_advance));\n      break;\n    default:\n      RETURN_STATUS_UNEXPECTED(\"TimeStretch: input tensor type should be float or double, but got: \" +\n                               input->type().ToString());\n  }\n  return Status::OK();\n}\n\nStatus Dct(std::shared_ptr<Tensor> *output, int n_mfcc, int n_mels, NormMode norm) {\n  TensorShape dct_shape({n_mels, n_mfcc});\n  Tensor::CreateEmpty(dct_shape, DataType(DataType::DE_FLOAT32), output);\n  auto iter = (*output)->begin<float>();\n  float sqrt_2 = 1 / sqrt(2);\n  float sqrt_2_n_mels = sqrt(2.0 / n_mels);\n  for (int i = 0; i < n_mels; i++) {\n    for (int j = 0; j < n_mfcc; j++) {\n      // calculate temp:\n      // 1. while norm = None, use 2*cos(PI*(i+0.5)*j/n_mels)\n      // 2. while norm = Ortho, divide the first row by sqrt(2),\n      //    then using sqrt(2.0 / n_mels)*cos(PI*(i+0.5)*j/n_mels)\n      float temp = PI / n_mels * (i + 0.5) * j;\n      temp = cos(temp);\n      if (norm == NormMode::kOrtho) {\n        if (j == 0) {\n          temp *= sqrt_2;\n        }\n        temp *= sqrt_2_n_mels;\n      } else {\n        temp *= 2;\n      }\n      (*iter++) = temp;\n    }\n  }\n  return Status::OK();\n}\n\nStatus RandomMaskAlongAxis(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t mask_param,\n                           float mask_value, int axis, std::mt19937 rnd) {\n  std::uniform_int_distribution<int32_t> mask_width_value(0, mask_param);\n  TensorShape input_shape = input->shape();\n  int32_t mask_dim_size = axis == 1 ? input_shape[-2] : input_shape[-1];\n  int32_t mask_width = mask_width_value(rnd);\n  std::uniform_int_distribution<int32_t> min_freq_value(0, mask_dim_size - mask_width);\n  int32_t mask_start = min_freq_value(rnd);\n\n  return MaskAlongAxis(input, output, mask_width, mask_start, mask_value, axis);\n}\n\nStatus MaskAlongAxis(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t mask_width,\n                     int32_t mask_start, float mask_value, int32_t axis) {\n  if (axis != 2 && axis != 1) {\n    RETURN_STATUS_UNEXPECTED(\"MaskAlongAxis: only support Time and Frequency masking, axis should be 1 or 2.\");\n  }\n  TensorShape input_shape = input->shape();\n  // squeeze input\n  TensorShape squeeze_shape = TensorShape({-1, input_shape[-2], input_shape[-1]});\n  (void)input->Reshape(squeeze_shape);\n\n  int check_dim_ind = (axis == 1) ? -2 : -1;\n  CHECK_FAIL_RETURN_UNEXPECTED(0 <= mask_start && mask_start <= input_shape[check_dim_ind],\n                               \"MaskAlongAxis: mask_start should be less than the length of chosen dimension.\");\n  CHECK_FAIL_RETURN_UNEXPECTED(mask_start + mask_width <= input_shape[check_dim_ind],\n                               \"MaskAlongAxis: the sum of mask_start and mask_width is out of bounds.\");\n\n  int32_t cell_size = input->type().SizeInBytes();\n\n  if (axis == 1) {\n    // freq\n    for (int ind = 0; ind < input->Size() / input_shape[-2] * mask_width; ind++) {\n      int block_num = ind / (mask_width * input_shape[-1]);\n      auto start_pos = ind % (mask_width * input_shape[-1]) + mask_start * input_shape[-1] +\n                       input_shape[-1] * input_shape[-2] * block_num;\n      auto start_mem_pos = const_cast<uchar *>(input->GetBuffer() + start_pos * cell_size);\n      if (input->type() != DataType::DE_FLOAT64) {\n        // tensor float 32\n        auto mask_val = static_cast<float>(mask_value);\n        CHECK_FAIL_RETURN_UNEXPECTED(memcpy_s(start_mem_pos, cell_size, &mask_val, cell_size) == 0,\n                                     \"MaskAlongAxis: mask failed, memory copy error.\");\n      } else {\n        // tensor float 64\n        CHECK_FAIL_RETURN_UNEXPECTED(memcpy_s(start_mem_pos, cell_size, &mask_value, cell_size) == 0,\n                                     \"MaskAlongAxis: mask failed, memory copy error.\");\n      }\n    }\n  } else {\n    // time\n    for (int ind = 0; ind < input->Size() / input_shape[-1] * mask_width; ind++) {\n      int row_num = ind / mask_width;\n      auto start_pos = ind % mask_width + mask_start + input_shape[-1] * row_num;\n      auto start_mem_pos = const_cast<uchar *>(input->GetBuffer() + start_pos * cell_size);\n      if (input->type() != DataType::DE_FLOAT64) {\n        // tensor float 32\n        auto mask_val = static_cast<float>(mask_value);\n        CHECK_FAIL_RETURN_UNEXPECTED(memcpy_s(start_mem_pos, cell_size, &mask_val, cell_size) == 0,\n                                     \"MaskAlongAxis: mask failed, memory copy error.\");\n      } else {\n        // tensor float 64\n        CHECK_FAIL_RETURN_UNEXPECTED(memcpy_s(start_mem_pos, cell_size, &mask_value, cell_size) == 0,\n                                     \"MaskAlongAxis: mask failed, memory copy error.\");\n      }\n    }\n  }\n  // unsqueeze input\n  (void)input->Reshape(input_shape);\n  *output = input;\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus Norm(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, float power) {\n  // calculate the output dimension\n  auto input_size = input->shape().AsVector();\n  int32_t dim_back = static_cast<int32_t>(input_size.back());\n  CHECK_FAIL_RETURN_UNEXPECTED(\n    dim_back == 2, \"ComplexNorm: expect complex input of shape <..., 2>, but got: \" + std::to_string(dim_back));\n  input_size.pop_back();\n  TensorShape out_shape = TensorShape(input_size);\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(out_shape, input->type(), output));\n\n  // calculate norm, using: .pow(2.).sum(-1).pow(0.5 * power)\n  auto itr_out = (*output)->begin<T>();\n  auto itr_in = input->begin<T>();\n\n  for (; itr_out != (*output)->end<T>(); ++itr_out) {\n    auto a = static_cast<T>(*itr_in);\n    ++itr_in;\n    auto b = static_cast<T>(*itr_in);\n    ++itr_in;\n    auto res = pow(a, 2) + pow(b, 2);\n    *itr_out = static_cast<T>(pow(res, (0.5 * power)));\n  }\n\n  return Status::OK();\n}\n\nStatus ComplexNorm(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, float power) {\n  try {\n    if (input->type().value() >= DataType::DE_INT8 && input->type().value() <= DataType::DE_FLOAT16) {\n      // convert the data type to float\n      std::shared_ptr<Tensor> input_tensor;\n      RETURN_IF_NOT_OK(TypeCast(input, &input_tensor, DataType(DataType::DE_FLOAT32)));\n\n      RETURN_IF_NOT_OK(Norm<float>(input_tensor, output, power));\n    } else if (input->type().value() == DataType::DE_FLOAT32) {\n      RETURN_IF_NOT_OK(Norm<float>(input, output, power));\n    } else if (input->type().value() == DataType::DE_FLOAT64) {\n      RETURN_IF_NOT_OK(Norm<double>(input, output, power));\n    } else {\n      RETURN_STATUS_UNEXPECTED(\"ComplexNorm: input tensor type should be int, float or double, but got: \" +\n                               input->type().ToString());\n    }\n    return Status::OK();\n  } catch (std::runtime_error &e) {\n    RETURN_STATUS_UNEXPECTED(\"ComplexNorm: \" + std::string(e.what()));\n  }\n}\n\ntemplate <typename T>\nfloat sgn(T val) {\n  return static_cast<float>(static_cast<T>(0) < val) - static_cast<float>(val < static_cast<T>(0));\n}\n\ntemplate <typename T>\nStatus Decoding(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, T mu) {\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(input->shape(), input->type(), output));\n  auto itr_out = (*output)->begin<T>();\n  auto itr = input->begin<T>();\n  auto end = input->end<T>();\n\n  while (itr != end) {\n    auto x_mu = *itr;\n    CHECK_FAIL_RETURN_SYNTAX_ERROR(mu != 0, \"mu can not be zero.\");\n    x_mu = ((x_mu) / mu) * 2 - 1.0;\n    x_mu = sgn(x_mu) * expm1(fabs(x_mu) * log1p(mu)) / mu;\n    *itr_out = x_mu;\n    ++itr_out;\n    ++itr;\n  }\n  return Status::OK();\n}\n\nStatus MuLawDecoding(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output,\n                     int32_t quantization_channels) {\n  if (input->type().IsInt() || input->type() == DataType(DataType::DE_FLOAT16) ||\n      input->type() == DataType(DataType::DE_FLOAT32)) {\n    float f_mu = static_cast<float>(quantization_channels) - 1;\n\n    // convert the data type to float\n    std::shared_ptr<Tensor> input_tensor;\n    RETURN_IF_NOT_OK(TypeCast(input, &input_tensor, DataType(DataType::DE_FLOAT32)));\n\n    RETURN_IF_NOT_OK(Decoding<float>(input_tensor, output, f_mu));\n  } else if (input->type() == DataType(DataType::DE_FLOAT64)) {\n    double f_mu = static_cast<double>(quantization_channels) - 1;\n\n    RETURN_IF_NOT_OK(Decoding<double>(input, output, f_mu));\n  } else {\n    RETURN_STATUS_UNEXPECTED(\"MuLawDecoding: input tensor type should be int, float or double, but got: \" +\n                             input->type().ToString());\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus Encoding(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, T mu) {\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(input->shape(), DataType(DataType::DE_INT32), output));\n  auto itr_out = (*output)->begin<int32_t>();\n  auto itr = input->begin<T>();\n  auto end = input->end<T>();\n\n  while (itr != end) {\n    auto x = *itr;\n    x = sgn(x) * log1p(mu * fabs(x)) / log1p(mu);\n    x = (x + 1) / 2 * mu + 0.5;\n    *itr_out = static_cast<int32_t>(x);\n    ++itr_out;\n    ++itr;\n  }\n  return Status::OK();\n}\n\nStatus MuLawEncoding(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output,\n                     int32_t quantization_channels) {\n  if (input->type().IsInt() || input->type() == DataType(DataType::DE_FLOAT16)) {\n    float f_mu = static_cast<float>(quantization_channels) - 1;\n\n    // convert the data type to float\n    std::shared_ptr<Tensor> input_tensor;\n    RETURN_IF_NOT_OK(TypeCast(input, &input_tensor, DataType(DataType::DE_FLOAT32)));\n\n    RETURN_IF_NOT_OK(Encoding<float>(input_tensor, output, f_mu));\n  } else if (input->type() == DataType(DataType::DE_FLOAT32)) {\n    float f_mu = static_cast<float>(quantization_channels) - 1;\n\n    RETURN_IF_NOT_OK(Encoding<float>(input, output, f_mu));\n  } else if (input->type() == DataType(DataType::DE_FLOAT64)) {\n    double f_mu = static_cast<double>(quantization_channels) - 1;\n\n    RETURN_IF_NOT_OK(Encoding<double>(input, output, f_mu));\n  } else {\n    RETURN_STATUS_UNEXPECTED(\"MuLawEncoding: input tensor type should be int, float or double, but got: \" +\n                             input->type().ToString());\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus FadeIn(std::shared_ptr<Tensor> *output, int32_t fade_in_len, FadeShape fade_shape) {\n  T start = 0;\n  T end = 1;\n  RETURN_IF_NOT_OK(Linspace<T>(output, start, end, fade_in_len));\n  for (auto iter = (*output)->begin<T>(); iter != (*output)->end<T>(); iter++) {\n    switch (fade_shape) {\n      case FadeShape::kLinear:\n        break;\n      case FadeShape::kExponential:\n        // Compute the scale factor of the exponential function, pow(2.0, *in_ter - 1.0) * (*in_ter)\n        *iter = static_cast<T>(std::pow(2.0, *iter - 1.0) * (*iter));\n        break;\n      case FadeShape::kLogarithmic:\n        // Compute the scale factor of the logarithmic function, log(*in_iter + 0.1) + 1.0\n        *iter = static_cast<T>(std::log10(*iter + 0.1) + 1.0);\n        break;\n      case FadeShape::kQuarterSine:\n        // Compute the scale factor of the quarter_sine function, sin((*in_iter - 1.0) * PI / 2.0)\n        *iter = static_cast<T>(std::sin((*iter) * PI / 2.0));\n        break;\n      case FadeShape::kHalfSine:\n        // Compute the scale factor of the half_sine function, sin((*in_iter) * PI - PI / 2.0) / 2.0 + 0.5\n        *iter = static_cast<T>(std::sin((*iter) * PI - PI / 2.0) / 2.0 + 0.5);\n        break;\n    }\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus FadeOut(std::shared_ptr<Tensor> *output, int32_t fade_out_len, FadeShape fade_shape) {\n  T start = 0;\n  T end = 1;\n  RETURN_IF_NOT_OK(Linspace<T>(output, start, end, fade_out_len));\n  for (auto iter = (*output)->begin<T>(); iter != (*output)->end<T>(); iter++) {\n    switch (fade_shape) {\n      case FadeShape::kLinear:\n        // In fade out, invert *out_iter\n        *iter = static_cast<T>(1.0 - *iter);\n        break;\n      case FadeShape::kExponential:\n        // Compute the scale factor of the exponential function\n        *iter = static_cast<T>(std::pow(2.0, -*iter) * (1.0 - *iter));\n        break;\n      case FadeShape::kLogarithmic:\n        // Compute the scale factor of the logarithmic function\n        *iter = static_cast<T>(std::log10(1.1 - *iter) + 1.0);\n        break;\n      case FadeShape::kQuarterSine:\n        // Compute the scale factor of the quarter_sine function\n        *iter = static_cast<T>(std::sin((*iter) * PI / 2.0 + PI / 2.0));\n        break;\n      case FadeShape::kHalfSine:\n        // Compute the scale factor of the half_sine function\n        *iter = static_cast<T>(std::sin((*iter) * PI + PI / 2.0) / 2.0 + 0.5);\n        break;\n    }\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus Fade(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t fade_in_len,\n            int32_t fade_out_len, FadeShape fade_shape) {\n  RETURN_IF_NOT_OK(Tensor::CreateFromTensor(input, output));\n  const TensorShape input_shape = input->shape();\n  int32_t waveform_length = static_cast<int32_t>(input_shape[-1]);\n  CHECK_FAIL_RETURN_UNEXPECTED(fade_in_len <= waveform_length, \"Fade: fade_in_len exceeds waveform length.\");\n  CHECK_FAIL_RETURN_UNEXPECTED(fade_out_len <= waveform_length, \"Fade: fade_out_len exceeds waveform length.\");\n  int32_t num_waveform = static_cast<int32_t>(input->Size() / waveform_length);\n  TensorShape toShape = TensorShape({num_waveform, waveform_length});\n  RETURN_IF_NOT_OK((*output)->Reshape(toShape));\n  TensorPtr fade_in;\n  RETURN_IF_NOT_OK(FadeIn<T>(&fade_in, fade_in_len, fade_shape));\n  TensorPtr fade_out;\n  RETURN_IF_NOT_OK(FadeOut<T>(&fade_out, fade_out_len, fade_shape));\n\n  // Add fade in to input tensor\n  auto output_iter = (*output)->begin<T>();\n  for (auto fade_in_iter = fade_in->begin<T>(); fade_in_iter != fade_in->end<T>(); fade_in_iter++) {\n    *output_iter = (*output_iter) * (*fade_in_iter);\n    for (int32_t j = 1; j < num_waveform; j++) {\n      output_iter += waveform_length;\n      *output_iter = (*output_iter) * (*fade_in_iter);\n    }\n    output_iter -= ((num_waveform - 1) * waveform_length);\n    ++output_iter;\n  }\n\n  // Add fade out to input tensor\n  output_iter = (*output)->begin<T>();\n  output_iter += (waveform_length - fade_out_len);\n  for (auto fade_out_iter = fade_out->begin<T>(); fade_out_iter != fade_out->end<T>(); fade_out_iter++) {\n    *output_iter = (*output_iter) * (*fade_out_iter);\n    for (int32_t j = 1; j < num_waveform; j++) {\n      output_iter += waveform_length;\n      *output_iter = (*output_iter) * (*fade_out_iter);\n    }\n    output_iter -= ((num_waveform - 1) * waveform_length);\n    ++output_iter;\n  }\n  (*output)->Reshape(input_shape);\n  return Status::OK();\n}\n\nStatus Fade(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t fade_in_len,\n            int32_t fade_out_len, FadeShape fade_shape) {\n  if (DataType::DE_INT8 <= input->type().value() && input->type().value() <= DataType::DE_FLOAT32) {\n    std::shared_ptr<Tensor> waveform;\n    RETURN_IF_NOT_OK(TypeCast(input, &waveform, DataType(DataType::DE_FLOAT32)));\n    RETURN_IF_NOT_OK(Fade<float>(waveform, output, fade_in_len, fade_out_len, fade_shape));\n  } else if (input->type().value() == DataType::DE_FLOAT64) {\n    RETURN_IF_NOT_OK(Fade<double>(input, output, fade_in_len, fade_out_len, fade_shape));\n  } else {\n    RETURN_STATUS_UNEXPECTED(\"Fade: input tensor type should be int, float or double, but got: \" +\n                             input->type().ToString());\n  }\n  return Status::OK();\n}\n\nStatus Magphase(const TensorRow &input, TensorRow *output, float power) {\n  std::shared_ptr<Tensor> mag;\n  std::shared_ptr<Tensor> phase;\n\n  RETURN_IF_NOT_OK(ComplexNorm(input[0], &mag, power));\n  if (input[0]->type() == DataType(DataType::DE_FLOAT64)) {\n    RETURN_IF_NOT_OK(Angle<double>(input[0], &phase));\n  } else {\n    std::shared_ptr<Tensor> tmp;\n    RETURN_IF_NOT_OK(TypeCast(input[0], &tmp, DataType(DataType::DE_FLOAT32)));\n    RETURN_IF_NOT_OK(Angle<float>(tmp, &phase));\n  }\n  (*output).push_back(mag);\n  (*output).push_back(phase);\n\n  return Status::OK();\n}\n\nStatus MedianSmoothing(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t win_length) {\n  auto channel = input->shape()[0];\n  auto num_of_frames = input->shape()[1];\n  // Centered windowed\n  int32_t pad_length = (win_length - 1) / 2;\n  int32_t out_length = num_of_frames + pad_length - win_length + 1;\n  TensorShape out_shape({channel, out_length});\n  std::vector<int> signal;\n  std::vector<int> out;\n  std::vector<int> indices(channel * (num_of_frames + pad_length), 0);\n  // \"replicate\" padding in any dimension\n  for (auto itr = input->begin<int>(); itr != input->end<int>(); ++itr) {\n    signal.push_back(*itr);\n  }\n  for (int i = 0; i < channel; ++i) {\n    for (int j = 0; j < pad_length; ++j) {\n      indices[i * (num_of_frames + pad_length) + j] = signal[i * num_of_frames];\n    }\n  }\n  for (int i = 0; i < channel; ++i) {\n    for (int j = 0; j < num_of_frames; ++j) {\n      indices[i * (num_of_frames + pad_length) + j + pad_length] = signal[i * num_of_frames + j];\n    }\n  }\n  for (int i = 0; i < channel; ++i) {\n    int32_t index = i * (num_of_frames + pad_length);\n    for (int j = 0; j < out_length; ++j) {\n      std::vector<int> tem(indices.begin() + index, indices.begin() + win_length + index);\n      std::sort(tem.begin(), tem.end());\n      out.push_back(tem[pad_length]);\n      ++index;\n    }\n  }\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(out, out_shape, output));\n  return Status::OK();\n}\n\nStatus DetectPitchFrequency(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t sample_rate,\n                            float frame_time, int32_t win_length, int32_t freq_low, int32_t freq_high) {\n  std::shared_ptr<Tensor> nccf;\n  std::shared_ptr<Tensor> indices;\n  std::shared_ptr<Tensor> smooth_indices;\n  // pack batch\n  TensorShape input_shape = input->shape();\n  TensorShape to_shape({input->Size() / input_shape[-1], input_shape[-1]});\n  RETURN_IF_NOT_OK(input->Reshape(to_shape));\n  if (input->type() == DataType(DataType::DE_FLOAT32)) {\n    RETURN_IF_NOT_OK(ComputeNccf<float>(input, &nccf, sample_rate, frame_time, freq_low));\n    RETURN_IF_NOT_OK(FindMaxPerFrame<float>(nccf, &indices, sample_rate, freq_high));\n  } else if (input->type() == DataType(DataType::DE_FLOAT64)) {\n    RETURN_IF_NOT_OK(ComputeNccf<double>(input, &nccf, sample_rate, frame_time, freq_low));\n    RETURN_IF_NOT_OK(FindMaxPerFrame<double>(nccf, &indices, sample_rate, freq_high));\n  } else {\n    RETURN_IF_NOT_OK(ComputeNccf<float16>(input, &nccf, sample_rate, frame_time, freq_low));\n    RETURN_IF_NOT_OK(FindMaxPerFrame<float16>(nccf, &indices, sample_rate, freq_high));\n  }\n  RETURN_IF_NOT_OK(MedianSmoothing(indices, &smooth_indices, win_length));\n\n  // Convert indices to frequency\n  constexpr double EPSILON = 1e-9;\n  TensorShape freq_shape = smooth_indices->shape();\n  std::vector<float> out;\n  for (auto itr_fre = smooth_indices->begin<int>(); itr_fre != smooth_indices->end<int>(); ++itr_fre) {\n    out.push_back(sample_rate / (EPSILON + *itr_fre));\n  }\n\n  // unpack batch\n  auto shape_vec = input_shape.AsVector();\n  shape_vec[shape_vec.size() - 1] = freq_shape[-1];\n  TensorShape out_shape(shape_vec);\n  RETURN_IF_NOT_OK(Tensor::CreateFromVector(out, out_shape, output));\n  return Status::OK();\n}\n\nStatus GenerateWaveTable(std::shared_ptr<Tensor> *output, const DataType &type, Modulation modulation,\n                         int32_t table_size, float min, float max, float phase) {\n  RETURN_UNEXPECTED_IF_NULL(output);\n  int32_t phase_offset = static_cast<int32_t>(phase / PI / 2 * table_size + 0.5);\n  // get the offset of the i-th\n  std::vector<int32_t> point;\n  for (auto i = 0; i < table_size; i++) {\n    point.push_back((i + phase_offset) % table_size);\n  }\n\n  std::shared_ptr<Tensor> wave_table;\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(TensorShape({table_size}), DataType(DataType::DE_FLOAT32), &wave_table));\n\n  auto iter = wave_table->begin<float>();\n\n  if (modulation == Modulation::kSinusoidal) {\n    for (int i = 0; i < table_size; iter++, i++) {\n      // change phase\n      *iter = (sin(point[i] * PI / table_size * 2) + 1) / 2;\n    }\n  } else {\n    for (int i = 0; i < table_size; iter++, i++) {\n      // change phase\n      *iter = point[i] * 2.0 / table_size;\n      // get complete offset\n      int32_t value = static_cast<int>(4 * point[i] / table_size);\n      // change the value of the square wave according to the number of complete offsets\n      if (value == 0) {\n        *iter = *iter + 0.5;\n      } else if (value == 1 || value == 2) {\n        *iter = 1.5 - *iter;\n      } else if (value == 3) {\n        *iter = *iter - 1.5;\n      }\n    }\n  }\n  for (iter = wave_table->begin<float>(); iter != wave_table->end<float>(); iter++) {\n    *iter = *iter * (max - min) + min;\n  }\n  if (type.IsInt()) {\n    for (iter = wave_table->begin<float>(); iter != wave_table->end<float>(); iter++) {\n      if (*iter < 0) {\n        *iter = *iter - 0.5;\n      } else {\n        *iter = *iter + 0.5;\n      }\n    }\n    RETURN_IF_NOT_OK(TypeCast(wave_table, output, DataType(DataType::DE_INT32)));\n  } else if (type.IsFloat()) {\n    RETURN_IF_NOT_OK(TypeCast(wave_table, output, DataType(DataType::DE_FLOAT32)));\n  }\n\n  return Status::OK();\n}\n\nStatus ReadWaveFile(const std::string &wav_file_dir, std::vector<float> *waveform_vec, int32_t *sample_rate) {\n  RETURN_UNEXPECTED_IF_NULL(waveform_vec);\n  RETURN_UNEXPECTED_IF_NULL(sample_rate);\n  auto wav_realpath = FileUtils::GetRealPath(wav_file_dir.data());\n  if (!wav_realpath.has_value()) {\n    MS_LOG(ERROR) << \"Invalid file, get real path failed, path=\" << wav_file_dir;\n    RETURN_STATUS_UNEXPECTED(\"Invalid file, get real path failed, path=\" + wav_file_dir);\n  }\n\n  const float kMaxVal = 32767.0;\n  const int kDataMove = 2;\n  Path file_path(wav_realpath.value());\n  CHECK_FAIL_RETURN_UNEXPECTED(file_path.Exists() && !file_path.IsDirectory(),\n                               \"Invalid file, failed to find metadata file:\" + file_path.ToString());\n  std::ifstream in(file_path.ToString(), std::ios::in | std::ios::binary);\n  CHECK_FAIL_RETURN_UNEXPECTED(in.is_open(), \"Invalid file, failed to open metadata file:\" + file_path.ToString() +\n                                               \", make sure the file not damaged or permission denied.\");\n  WavHeader *header = new WavHeader();\n  in.read(reinterpret_cast<char *>(header), sizeof(WavHeader));\n  *sample_rate = header->sampleRate;\n  std::unique_ptr<char[]> data = std::make_unique<char[]>(header->subChunk2Size);\n  in.read(data.get(), header->subChunk2Size);\n  float bytesPerSample = header->bitsPerSample / 8;\n  if (bytesPerSample == 0) {\n    in.close();\n    delete header;\n    return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__, \"ReadWaveFile: divide zero error.\");\n  }\n  int numSamples = header->subChunk2Size / bytesPerSample;\n  waveform_vec->resize(numSamples);\n  for (int i = 0; i < numSamples; i++) {\n    (*waveform_vec)[i] = static_cast<int16_t>(data[kDataMove * i] / kMaxVal);\n  }\n  in.close();\n  delete header;\n  return Status::OK();\n}\n\nStatus ComputeCmnStartAndEnd(int32_t cmn_window, int32_t min_cmn_window, bool center, int32_t idx, int32_t num_frames,\n                             int32_t *cmn_window_start_p, int32_t *cmn_window_end_p) {\n  RETURN_UNEXPECTED_IF_NULL(cmn_window_start_p);\n  RETURN_UNEXPECTED_IF_NULL(cmn_window_end_p);\n  CHECK_FAIL_RETURN_UNEXPECTED(\n    cmn_window >= 0, \"SlidingWindowCmn: cmn_window must be non negative, but got: \" + std::to_string(cmn_window));\n  CHECK_FAIL_RETURN_UNEXPECTED(min_cmn_window >= 0, \"SlidingWindowCmn: min_cmn_window must be non negative, but got: \" +\n                                                      std::to_string(min_cmn_window));\n  int32_t cmn_window_start = 0, cmn_window_end = 0;\n  constexpr int window_center = 2;\n  if (center) {\n    cmn_window_start = idx - cmn_window / window_center;\n    cmn_window_end = cmn_window_start + cmn_window;\n  } else {\n    cmn_window_start = idx - cmn_window;\n    cmn_window_end = idx + 1;\n  }\n  if (cmn_window_start < 0) {\n    cmn_window_end -= cmn_window_start;\n    cmn_window_start = 0;\n  }\n  if (!center) {\n    if (cmn_window_end > idx) {\n      cmn_window_end = std::max(idx + 1, min_cmn_window);\n    }\n  }\n  if (cmn_window_end > num_frames) {\n    cmn_window_start -= (cmn_window_end - num_frames);\n    cmn_window_end = num_frames;\n    if (cmn_window_start < 0) {\n      cmn_window_start = 0;\n    }\n  }\n\n  *cmn_window_start_p = cmn_window_start;\n  *cmn_window_end_p = cmn_window_end;\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus ComputeCmnWaveform(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *cmn_waveform_p,\n                          int32_t num_channels, int32_t num_frames, int32_t num_feats, int32_t cmn_window,\n                          int32_t min_cmn_window, bool center, bool norm_vars) {\n  using ArrayXT = Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  constexpr int square_num = 2;\n  int32_t last_window_start = -1, last_window_end = -1;\n  ArrayXT cur_sum = ArrayXT(num_channels, num_feats);\n  ArrayXT cur_sum_sq;\n  if (norm_vars) {\n    cur_sum_sq = ArrayXT(num_channels, num_feats);\n  }\n  for (int i = 0; i < num_frames; ++i) {\n    int32_t cmn_window_start = 0, cmn_window_end = 0;\n    RETURN_IF_NOT_OK(\n      ComputeCmnStartAndEnd(cmn_window, min_cmn_window, center, i, num_frames, &cmn_window_start, &cmn_window_end));\n    int32_t row = cmn_window_end - cmn_window_start * 2;\n    int32_t cmn_window_frames = cmn_window_end - cmn_window_start;\n    for (int32_t m = 0; m < num_channels; ++m) {\n      if (last_window_start == -1) {\n        auto it = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));\n        it += (m * num_frames * num_feats + cmn_window_start * num_feats);\n        auto tmp_map = Eigen::Map<ArrayXT>(it, row, num_feats);\n        if (i > 0) {\n          cur_sum.row(m) += tmp_map.colwise().sum();\n          if (norm_vars) {\n            cur_sum_sq.row(m) += tmp_map.pow(square_num).colwise().sum();\n          }\n        } else {\n          cur_sum.row(m) = tmp_map.colwise().sum();\n          if (norm_vars) {\n            cur_sum_sq.row(m) = tmp_map.pow(square_num).colwise().sum();\n          }\n        }\n      } else {\n        if (cmn_window_start > last_window_start) {\n          auto it = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));\n          it += (m * num_frames * num_feats + last_window_start * num_feats);\n          auto tmp_map = Eigen::Map<ArrayXT>(it, 1, num_feats);\n          cur_sum.row(m) -= tmp_map;\n          if (norm_vars) {\n            cur_sum_sq.row(m) -= tmp_map.pow(square_num);\n          }\n        }\n        if (cmn_window_end > last_window_end) {\n          auto it = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));\n          it += (m * num_frames * num_feats + last_window_end * num_feats);\n          auto tmp_map = Eigen::Map<ArrayXT>(it, 1, num_feats);\n          cur_sum.row(m) += tmp_map;\n          if (norm_vars) {\n            cur_sum_sq.row(m) += tmp_map.pow(square_num);\n          }\n        }\n      }\n\n      auto it = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));\n      auto cmn_it = reinterpret_cast<T *>(const_cast<uchar *>((*cmn_waveform_p)->GetBuffer()));\n      it += (m * num_frames * num_feats + i * num_feats);\n      cmn_it += (m * num_frames * num_feats + i * num_feats);\n      Eigen::Map<ArrayXT>(cmn_it, 1, num_feats) =\n        Eigen::Map<ArrayXT>(it, 1, num_feats) - cur_sum.row(m) / cmn_window_frames;\n      if (norm_vars) {\n        if (cmn_window_frames == 1) {\n          auto cmn_it_1 = reinterpret_cast<T *>(const_cast<uchar *>((*cmn_waveform_p)->GetBuffer()));\n          cmn_it_1 += (m * num_frames * num_feats + i * num_feats);\n          Eigen::Map<ArrayXT>(cmn_it_1, 1, num_feats).setZero();\n        } else {\n          auto variance = (Eigen::Map<ArrayXT>(cur_sum_sq.data(), num_channels, num_feats) / cmn_window_frames) -\n                          (cur_sum.pow(2) / std::pow(cmn_window_frames, 2));\n          auto cmn_it_2 = reinterpret_cast<T *>(const_cast<uchar *>((*cmn_waveform_p)->GetBuffer()));\n          cmn_it_2 += (m * num_frames * num_feats + i * num_feats);\n          Eigen::Map<ArrayXT>(cmn_it_2, 1, num_feats) =\n            Eigen::Map<ArrayXT>(cmn_it_2, 1, num_feats) * (1 / variance.sqrt()).row(m);\n        }\n      }\n    }\n    last_window_start = cmn_window_start;\n    last_window_end = cmn_window_end;\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus SlidingWindowCmnHelper(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t cmn_window,\n                              int32_t min_cmn_window, bool center, bool norm_vars) {\n  int32_t num_frames = input->shape()[Tensor::HandleNeg(-2, input->shape().Size())];\n  int32_t num_feats = input->shape()[Tensor::HandleNeg(-1, input->shape().Size())];\n\n  int32_t first_index = 1;\n  std::vector<dsize_t> input_shape = input->shape().AsVector();\n  std::for_each(input_shape.begin(), input_shape.end(), [&first_index](const dsize_t &item) { first_index *= item; });\n  RETURN_IF_NOT_OK(\n    input->Reshape(TensorShape({static_cast<int>(first_index / (num_frames * num_feats)), num_frames, num_feats})));\n\n  int32_t num_channels = static_cast<int32_t>(input->shape()[0]);\n  TensorPtr cmn_waveform;\n  RETURN_IF_NOT_OK(\n    Tensor::CreateEmpty(TensorShape({num_channels, num_frames, num_feats}), input->type(), &cmn_waveform));\n  RETURN_IF_NOT_OK(ComputeCmnWaveform<T>(input, &cmn_waveform, num_channels, num_frames, num_feats, cmn_window,\n                                         min_cmn_window, center, norm_vars));\n\n  std::vector<dsize_t> re_shape = input_shape;\n  auto r_it = re_shape.rbegin();\n  *r_it++ = num_feats;\n  *r_it = num_frames;\n  RETURN_IF_NOT_OK(cmn_waveform->Reshape(TensorShape(re_shape)));\n\n  constexpr int specify_input_shape = 2;\n  constexpr int specify_first_shape = 1;\n  if (input_shape.size() == specify_input_shape && cmn_waveform->shape()[0] == specify_first_shape) {\n    cmn_waveform->Squeeze();\n  }\n  *output = cmn_waveform;\n  return Status::OK();\n}\n\nStatus SlidingWindowCmn(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t cmn_window,\n                        int32_t min_cmn_window, bool center, bool norm_vars) {\n  TensorShape input_shape = input->shape();\n  CHECK_FAIL_RETURN_UNEXPECTED(input_shape.Size() >= kMinAudioRank,\n                               \"SlidingWindowCmn: input tensor is not in shape of <..., freq, time>.\");\n\n  if (input->type().IsNumeric() && input->type().value() != DataType::DE_FLOAT64) {\n    std::shared_ptr<Tensor> temp;\n    RETURN_IF_NOT_OK(TypeCast(input, &temp, DataType(DataType::DE_FLOAT32)));\n    RETURN_IF_NOT_OK(SlidingWindowCmnHelper<float>(temp, output, cmn_window, min_cmn_window, center, norm_vars));\n  } else if (input->type().value() == DataType::DE_FLOAT64) {\n    RETURN_IF_NOT_OK(SlidingWindowCmnHelper<double>(input, output, cmn_window, min_cmn_window, center, norm_vars));\n  } else {\n    RETURN_STATUS_UNEXPECTED(\"SlidingWindowCmn: input tensor type should be int, float or double, but got: \" +\n                             input->type().ToString());\n  }\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus Pad(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t pad_left, int32_t pad_right,\n           BorderType padding_mode, T value = 0) {\n  CHECK_FAIL_RETURN_UNEXPECTED(input->shape().Size() >= 2, \"Pad: input tensor is not in shape of <..., time>.\");\n  CHECK_FAIL_RETURN_UNEXPECTED(\n    input->type().IsNumeric(),\n    \"Pad: input tensor type should be int, float or double, but got: \" + input->type().ToString());\n  CHECK_FAIL_RETURN_UNEXPECTED(pad_left >= 0 && pad_right >= 0,\n                               \"Pad: left and right padding values must be non negative, but got pad_left: \" +\n                                 std::to_string(pad_left) + \" and pad_right: \" + std::to_string(pad_right));\n  TensorShape input_shape = input->shape();\n  int32_t wave_length = input_shape[-1];\n  int32_t num_wavs = static_cast<int32_t>(input->Size() / wave_length);\n  TensorShape to_shape = TensorShape({num_wavs, wave_length});\n  RETURN_IF_NOT_OK(input->Reshape(to_shape));\n  int32_t pad_length = wave_length + pad_left + pad_right;\n  TensorShape new_shape = TensorShape({num_wavs, pad_length});\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(new_shape, input->type(), output));\n  using MatrixXT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  using Eigen::Map;\n  constexpr int pad_mul = 2;\n  T *input_data = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));\n  T *output_data = reinterpret_cast<T *>(const_cast<uchar *>((*output)->GetBuffer()));\n  auto input_map = Map<MatrixXT>(input_data, num_wavs, wave_length);\n  auto output_map = Map<MatrixXT>(output_data, num_wavs, pad_length);\n  output_map.block(0, pad_left, num_wavs, wave_length) = input_map;\n  if (padding_mode == BorderType::kConstant) {\n    output_map.block(0, 0, num_wavs, pad_left).setConstant(value);\n    output_map.block(0, pad_left + wave_length, num_wavs, pad_right).setConstant(value);\n  } else if (padding_mode == BorderType::kEdge) {\n    output_map.block(0, 0, num_wavs, pad_left).colwise() = input_map.col(0);\n    output_map.block(0, pad_left + wave_length, num_wavs, pad_right).colwise() = input_map.col(wave_length - 1);\n  } else if (padding_mode == BorderType::kReflect) {\n    // First, deal with the pad operation on the right.\n    int32_t current_pad = wave_length - 1;\n    while (pad_right >= current_pad) {\n      // current_pad: the length of pad required for current loop.\n      // pad_right: the length of the remaining pad on the right.\n      output_map.block(0, pad_left + current_pad + 1, num_wavs, current_pad) =\n        output_map.block(0, pad_left, num_wavs, current_pad).rowwise().reverse();\n      pad_right -= current_pad;\n      current_pad += current_pad;\n    }\n    output_map.block(0, pad_length - pad_right, num_wavs, pad_right) =\n      output_map.block(0, pad_length - pad_right * pad_mul - 1, num_wavs, pad_right).rowwise().reverse();\n    // Next, deal with the pad operation on the left.\n    current_pad = wave_length - 1;\n    while (pad_left >= current_pad) {\n      // current_pad: the length of pad required for current loop.\n      // pad_left: the length of the remaining pad on the left.\n      output_map.block(0, pad_left - current_pad, num_wavs, current_pad) =\n        output_map.block(0, pad_left + 1, num_wavs, current_pad).rowwise().reverse();\n      pad_left -= current_pad;\n      current_pad += current_pad;\n    }\n    output_map.block(0, 0, num_wavs, pad_left) =\n      output_map.block(0, pad_left + 1, num_wavs, pad_left).rowwise().reverse();\n  } else if (padding_mode == BorderType::kSymmetric) {\n    // First, deal with the pad operation on the right.\n    int32_t current_pad = wave_length;\n    while (pad_right >= current_pad) {\n      // current_pad: the length of pad required for current loop.\n      // pad_right: the length of the remaining pad on the right.\n      output_map.block(0, pad_left + current_pad, num_wavs, current_pad) =\n        output_map.block(0, pad_left, num_wavs, current_pad).rowwise().reverse();\n      pad_right -= current_pad;\n      current_pad += current_pad;\n    }\n    output_map.block(0, pad_length - pad_right, num_wavs, pad_right) =\n      output_map.block(0, pad_length - pad_right * pad_mul, num_wavs, pad_right).rowwise().reverse();\n    // Next, deal with the pad operation on the left.\n    current_pad = wave_length;\n    while (pad_left >= current_pad) {\n      // current_pad: the length of pad required for current loop.\n      // pad_left: the length of the remaining pad on the left.\n      output_map.block(0, pad_left - current_pad, num_wavs, current_pad) =\n        output_map.block(0, pad_left, num_wavs, current_pad).rowwise().reverse();\n      pad_left -= current_pad;\n      current_pad += current_pad;\n    }\n    output_map.block(0, 0, num_wavs, pad_left) = output_map.block(0, pad_left, num_wavs, pad_left).rowwise().reverse();\n  } else {\n    RETURN_STATUS_UNEXPECTED(\"Pad: unsupported border type.\");\n  }\n  std::vector<dsize_t> shape_vec = input_shape.AsVector();\n  shape_vec[shape_vec.size() - 1] = static_cast<dsize_t>(pad_length);\n  TensorShape output_shape(shape_vec);\n  RETURN_IF_NOT_OK((*output)->Reshape(output_shape));\n  return Status::OK();\n}\n\ntemplate <typename T>\nStatus ComputeDeltasImpl(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int all_freqs,\n                         int n_frame, int n) {\n  using VectorXT = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n  using MatrixXT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  using Eigen::Map;\n  int32_t denom = n * (n + 1) * (n * 2 + 1) / 3;\n  // twice sum of integer squared\n  VectorXT kernel = VectorXT::LinSpaced(2 * n + 1, -n, n);                         // 2n+1\n  T *input_data = reinterpret_cast<T *>(const_cast<uchar *>(input->GetBuffer()));  // [all_freq,n_fram+2n]\n  RETURN_IF_NOT_OK(Tensor::CreateEmpty(TensorShape{all_freqs, n_frame}, input->type(), output));\n  T *output_data = reinterpret_cast<T *>(const_cast<uchar *>((*output)->GetBuffer()));\n  for (int freq = 0; freq < all_freqs; ++freq) {  // conv with im2col\n    auto input_map = Map<MatrixXT, 0, Eigen::OuterStride<1>>(input_data + freq * (n_frame + 2 * n), n_frame,\n                                                             2 * n + 1);  // n_frmae,2n+1\n    Map<VectorXT>(output_data + freq * n_frame, n_frame) = (input_map * kernel).array() / T(denom);\n  }\n  return Status::OK();\n}\n\nStatus ComputeDeltas(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output, int32_t win_length,\n                     const BorderType &mode) {\n  constexpr int min_shape_dim = 2;\n  auto raw_shape = input->shape();\n  CHECK_FAIL_RETURN_UNEXPECTED(raw_shape.Size() >= min_shape_dim,\n                               \"ComputeDeltas: input tensor is not in shape of <..., freq, time>.\");\n  CHECK_FAIL_RETURN_UNEXPECTED(\n    input->type().IsNumeric(),\n    \"ComputeDeltas: input tensor type should be int, float or double, but got: \" + input->type().ToString());\n\n  // reshape Tensor from <..., freq, time> to <-1, time>\n  int32_t n_frames = raw_shape[-1];\n  int32_t all_freqs = raw_shape.NumOfElements() / n_frames;\n  RETURN_IF_NOT_OK(input->Reshape(TensorShape{all_freqs, n_frames}));\n\n  int32_t n = (win_length - 1) / 2;\n\n  std::shared_ptr<Tensor> specgram_local_pad;\n  if (input->type() == DataType(DataType::DE_FLOAT64)) {\n    RETURN_IF_NOT_OK(Pad<double>(input, &specgram_local_pad, n, n, mode));\n    RETURN_IF_NOT_OK(ComputeDeltasImpl<double>(specgram_local_pad, output, all_freqs, n_frames, n));\n  } else {\n    std::shared_ptr<Tensor> float_tensor;\n    RETURN_IF_NOT_OK(TypeCast(input, &float_tensor, DataType(DataType::DE_FLOAT32)));\n    RETURN_IF_NOT_OK(Pad<float>(float_tensor, &specgram_local_pad, n, n, mode));\n    RETURN_IF_NOT_OK(ComputeDeltasImpl<float>(specgram_local_pad, output, all_freqs, n_frames, n));\n  }\n  RETURN_IF_NOT_OK((*output)->Reshape(raw_shape));\n  return Status::OK();\n}\n}  // namespace dataset\n}  // namespace mindspore\n", "meta": {"hexsha": "ce43bcb4e4bd5e103feccd3b521f87674d762b2f", "size": 52654, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mindspore/ccsrc/minddata/dataset/audio/kernels/audio_utils.cc", "max_stars_repo_name": "Greatpanc/mindspore_zhb", "max_stars_repo_head_hexsha": "c2511f7d6815b9232ac4427e27e2c132ed03e0d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mindspore/ccsrc/minddata/dataset/audio/kernels/audio_utils.cc", "max_issues_repo_name": "Greatpanc/mindspore_zhb", "max_issues_repo_head_hexsha": "c2511f7d6815b9232ac4427e27e2c132ed03e0d9", "max_issues_repo_licenses": ["Apache-2.0"], "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/minddata/dataset/audio/kernels/audio_utils.cc", "max_forks_repo_name": "Greatpanc/mindspore_zhb", "max_forks_repo_head_hexsha": "c2511f7d6815b9232ac4427e27e2c132ed03e0d9", "max_forks_repo_licenses": ["Apache-2.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.5157024793, "max_line_length": 120, "alphanum_fraction": 0.6563413986, "num_tokens": 14640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5651164319432698}}
{"text": "#ifndef POLYNOMIAL_H\n#define POLYNOMIAL_H\n\n#include <Eigen/Dense>\n#include <iosfwd>\n\ntemplate <unsigned D> class Polynomial\n{\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\npublic:\n\tEigen::Matrix<float, D + 1, 1> c;\n\n\tstatic Eigen::Matrix<float, D + 1, 1> powers(const float &x);\n\tinline float value(const float &x) const\n\t{\n\t\treturn c.cwiseProduct(powers(x)).sum();\n\t}\n\tPolynomial(const Eigen::Matrix2Xf &xy);\n\tPolynomial() = default;\n\ttemplate <unsigned Deg>\n\tfriend std::ostream &operator<<(std::ostream &os,\n\t\t\t\t\tconst Polynomial<Deg> &p);\n};\n\ntemplate <unsigned D> Polynomial<D>::Polynomial(const Eigen::Matrix2Xf &xy)\n{\n\tconst int N = xy.cols();\n\tassert(N > 0);\n\tEigen::Matrix<float, Eigen::Dynamic, D + 1> X(N, D + 1);\n\tfor (int i = 0; i < N; ++i) {\n\t\tX.row(i) = powers(xy(0, i));\n\t}\n\tc = X.householderQr().solve(xy.row(1).transpose());\n\t// c = X.fullPivHouseholderQr().solve(xy.row(1).transpose());\n}\n\n\ntemplate <unsigned D>\nstd::ostream &operator<<(std::ostream &os, const Polynomial<D> &p)\n{\n\tos << p.c[0];\n\tif (D > 0) {\n\t\tos << \" + \" << p.c[1] << \" * x\";\n\t}\n\tfor (int i = 2; i < D + 1; ++i) {\n\t\tos << \" + \" << p.c[i] << \" * x^\" << i;\n\t}\n\treturn os;\n}\n\ntemplate <> Eigen::Matrix<float, 2, 1> Polynomial<1>::powers(const float &x)\n{\n\treturn Eigen::Matrix<float, 2, 1>(1.0f, x);\n}\n\ntemplate <> Eigen::Matrix<float, 3, 1> Polynomial<2>::powers(const float &x)\n{\n\treturn Eigen::Matrix<float, 3, 1>(1.0f, x, x * x);\n}\n\ntemplate <> Eigen::Matrix<float, 4, 1> Polynomial<3>::powers(const float &x)\n{\n\treturn Eigen::Matrix<float, 4, 1>(1.0f, x, x * x, x * x * x);\n}\n\ntemplate <unsigned int D>\nEigen::Matrix<float, D + 1, 1> Polynomial<D>::powers(const float &x)\n{\n\tEigen::Matrix<float, D + 1, 1> vec;\n\tvec[0] = 1.0f;\n\tfor (auto i = 1; i < D + 1; ++i) {\n\t\tvec[i] = vec[i - 1] * x;\n\t}\n\treturn vec;\n}\n#endif // POLYNOMIAL_H\n", "meta": {"hexsha": "f4a1078046f86b45b8943bf82d1ab29f51536b81", "size": 1809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polynomial.hpp", "max_stars_repo_name": "mdimura/SplineApprox", "max_stars_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T15:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-27T15:30:07.000Z", "max_issues_repo_path": "polynomial.hpp", "max_issues_repo_name": "mdimura/SplineApprox", "max_issues_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polynomial.hpp", "max_forks_repo_name": "mdimura/SplineApprox", "max_forks_repo_head_hexsha": "de558dcdf906d0a556e6ec0fa01bc9a039596c89", "max_forks_repo_licenses": ["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.4935064935, "max_line_length": 76, "alphanum_fraction": 0.6097291321, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5651164220330609}}
{"text": "/**\n * @file qfeinterpolator.cc\n * @brief NPDE homework DebuggingFEM code\n * @author Simon Meierhans\n * @date 27/03/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"qfeinterpolator.h\"\n\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n\nnamespace DebuggingFEM {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d globalCoordinate(int idx, const lf::mesh::Entity &cell) {\n  // Consistency check for arguments\n  LF_ASSERT_MSG(cell.RefEl() == lf::base::RefEl::kTria(),\n                \"Implemented for triangles only\");\n  // Fetch pointer to asscoiated geometry object\n  lf::geometry::Geometry *geom = cell.Geometry();\n  // For returning the global coordinates of the interpolation node\n  Eigen::Vector2d result;\n  // Reference coordinates of the vertices of the triangle\n  Eigen::Matrix<double, 2, 3> corners(2, 3);\n  corners << 0., 1., 0., 0., 0., 1.;\n  switch (idx) {\n    case (0):\n      result = geom->Global(corners.col(0));\n      break;\n    case (1):\n      result = geom->Global(corners.col(1));\n      break;\n    case (2):\n      result = geom->Global(corners.col(2));\n      break;\n    case (3):\n      result = geom->Global((corners.col(0) + corners.col(1)) / 2.);\n      break;\n    case (4):\n      result = geom->Global((corners.col(1) + corners.col(2)) / 2.);\n      break;\n    case (5):\n      result = geom->Global((corners.col(2) + corners.col(0)) / 2.);\n      break;\n    default:\n      throw std::invalid_argument(\"idx needs to be in range [0,5]\");\n  }\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace DebuggingFEM\n", "meta": {"hexsha": "ab2f104b0b03c1cc1ffdec0cfcc204988f6d59fb", "size": 1530, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DebuggingFEM/mastersolution/qfeinterpolator.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/DebuggingFEM/mastersolution/qfeinterpolator.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/DebuggingFEM/mastersolution/qfeinterpolator.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3214285714, "max_line_length": 73, "alphanum_fraction": 0.6287581699, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5651111036326282}}
{"text": "// Compile command: g++ -Wall -Wextra -std=c++17 -O2 -pthread -I/usr/include/eigen3 -I/usr/include/python3.8 -o triangular_distorted triangular_distorted.cpp -lpython3.8\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <complex>\n#include <Eigen/Dense>\n#include <vector>\n#include <utility>\n#include <functional>\n#include <thread>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <ctime>\n#include <iomanip>\n#include <filesystem>\n#include <Python.h>\n#include \"matplotlibcpp.h\"\n#include \"tinycolormap.hpp\"\n\n\nnamespace plt = matplotlibcpp;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix2cd;\nusing Eigen::Vector2cd;\nusing Eigen::Vector3f;\nusing std::vector;\nusing std::sqrt;\nusing std::cos;\nusing std::acos;\nusing std::sin;\nusing namespace std::complex_literals;\n\ntypedef std::complex<double> cd;\ntypedef vector<vector<vector<cd>>> grid_t;\ntypedef std::function<Matrix2cd(int, double, double)> gen_coin_t;\n\n// Settings here: epsilon and size (the factor before /sqrt(eps))\n// Other settings: \ndouble eps = 0.001;\nint num_steps = 10000;\nint deformation = 0;\nint initialState = 0;\nvector<std::string> initialStateName = {\"center\", \"vertical\", \"center-side0\", \"center-side1\", \"center-side2\", \"shift-ur\", \"shift-ur3\", \"sinx\", \"siny\", \"square\"};\ndouble dy = sqrt(3);\nbool showVectField = false; // Set to true to show the vector field\nbool forceSphere = false;\nint xspan = (int)(3/sqrt(eps));\n//int xspan = 200;\nint yspan = (int)(xspan/dy);\nint ntriangles_x = 2*xspan;\nint ntriangles_y = 2*yspan;\nint center[2] = {xspan, yspan};\n\nstd::time_t now = time(0);\nstd::tm *ltm = localtime(&now);\n\nstd::string prefix;\n\ngrid_t zerogrid() {\n    return vector<vector<vector<cd>>>(ntriangles_x, vector<vector<cd>> (ntriangles_y, vector<cd> (3, 0. + 0i)));\n}\n\ngrid_t grid = zerogrid();\n\ndouble sumAmplitudes() {\n    double ret = 0.0;\n    for(int x = -xspan; x < xspan; x++)\n        for(int y = -yspan; y < yspan; y++)\n            for(int side = 0; side < 3; side++) {\n                cd val = grid[x+center[0]][y+center[1]][side];\n                ret += std::real(val*std::conj(val));\n            }\n    return ret;\n}\n\nvoid normalizeGrid() {\n    double target = sumAmplitudes();\n    double mul = 1/sqrt(target);\n    if(target == 0)\n        return;\n    for(int x = -xspan; x < xspan; x++)\n        for(int y = -yspan; y < yspan; y++)\n            for(int side = 0; side < 3; side++)\n                grid[x+center[0]][y+center[1]][side] *= mul;\n}\n\nMatrix2cd H, Q;\n\ninline int modulo(int a, int b) {\n    return (a%b+b)%b;\n}\n\nvoid init_HQ() {\n    H << 1, 1, 1, -1;\n    H /= sqrt(2);\n    Q << 1, -1i, 1, 1i;\n    Q /= sqrt(2);\n}\n\nMatrix2cd gen_Ui(double thetai) {\n    Matrix2cd ret;\n    ret << \n        cos(thetai/2), sin(thetai/2),\n        -sin(thetai/2), cos(thetai/2);\n    return ret;\n}\n\ninline int sign(double d) {\n    if(d>=0)\n        return 1;\n    else\n        return -1;\n}\n\ninline double sq(double d) {\n    return d*d;\n}\n\nvector<std::string> deform_name = {\"ident\", \"conic\", \"3fold\", \"3fold-x\", \"3fold-y\", \"sphere-singul\", \"sphere-nosingul\", \"cone\", \"zeroy\"};\n\nMatrix2cd lamb(double rx, double ry) {\n    Matrix2cd ret;\n    // Identité\n    if(deformation == 0) {\n        ret <<\n            1, 0,\n            0, 1;\n    }\n    // Conique : pas de moyen simple d'éviter la singularité\n    else if(deformation == 1) {\n        if(rx == 0) {\n            if(ry >= 0) {\n                ret <<\n                    -1, 0,\n                    0, 1/sqrt(1+4*ry*ry);\n            }\n            else {\n                ret <<\n                    1, 0,\n                    0, 1/sqrt(1+4*ry*ry);\n            }\n        }\n        else {\n            ret <<\n                -sign(rx)*ry/rx/sqrt(1+sq(ry/rx)),\n                sign(rx)/sqrt(1+sq(2*rx+2*ry*ry/rx)+sq(ry/rx)),\n                sign(rx)/sqrt(1+sq(ry/rx)),\n                sign(rx)*ry/rx/sqrt(1+sq(2*rx+2*ry*ry/rx)+sq(ry/rx));\n        }\n    }\n    else if(deformation == 2) { // 10-fold expansion of space\n        ret <<\n            3, 0,\n            0, 3;\n    }\n    else if(deformation == 3) { // 3-fold expansion of space in x direction\n        ret <<\n            3, 0,\n            0, 1;\n    }\n    else if(deformation == 4) { // 3-fold expansion of space in y direction\n        ret <<\n            1, 0,\n            0, 3;\n    }\n    // Sphérique\n    else if(deformation == 5) { // Sphérique, coordonnées tournantes (singularité en (0,0))\n        if(rx == 0 && ry == 0) {\n            ret <<\n                1, 0,\n                0, 1;\n        }\n        else {\n            Vector2cd er, retheta;\n            double norm = sqrt(rx*rx+ry*ry);\n            double phi = acos(1-4/(norm*norm/2+2));\n            er << rx/norm, ry/norm;\n            retheta << -ry, rx;\n            Vector2cd vect1 = 1/sin(phi)*retheta;\n            Vector2cd vect2 = sq(norm*norm/2+2)*sin(phi)/(4*norm)*er;\n            ret <<\n                vect1(0), vect1(1),\n                vect2(0), vect2(1);\n        }\n    }\n    else if(deformation == 6) { // Sphère, sans singularité\n        double den = sq(rx*rx+ry*ry+4);\n        Vector3f partialx(\n            4*(-rx*rx+ry*ry+4)/den,\n            -8*rx*ry/den,\n            16*rx/den\n        );\n        Vector3f partialy(\n            -8*rx*ry/den,\n            4*(rx*rx-ry*ry+4)/den,\n            16*ry/den\n        );\n        ret <<\n            1/partialx.norm(), 0,\n            0, 1/partialy.norm();\n    }\n    else if(deformation == 7) {\n        double xi = sqrt(rx*rx+ry*ry);\n        if(xi <= 1e-10)\n            return Matrix2cd::Identity();\n        double phi = atan2(ry, rx);\n        const double a = 1.0, c = 1.0;\n        Vector3f partial_xi(\n            cos(phi),\n            sin(phi),\n            c*xi/a/a/sqrt(1+sq(xi)/sq(a)));\n        Vector3f partial_phi(\n            -sin(phi),\n            cos(phi),\n            0\n        );\n        Vector2cd exi(cos(phi), sin(phi));\n        Vector2cd ephi(-sin(phi), cos(phi));\n        Vector2cd vect1 = exi/partial_xi.norm(), vect2 = ephi/partial_phi.norm();\n        ret <<\n            vect1(0), vect2(0),\n            vect1(1), vect2(1);\n    }\n    else if(deformation == 8) {\n        ret <<\n            1, 0,\n            0, 0;\n    }\n    else\n        throw std::runtime_error(\"Invalid deformation\");\n    return ret;\n}\n\nvector<cd> l(double rx, double ry) {\n    Matrix2cd lam = lamb(rx, ry);\n    double sqrt3 = sqrt(3.0);\n    return {lam(0,0), lam(1,0)/sqrt3, -lam(1,0)/sqrt3, lam(0,1), lam(1,1)/sqrt3, -lam(1,1)/sqrt3};\n}\n\ndouble gen_theta(int i, double rx, double ry) {\n    return std::real(M_PI/2 + sqrt(eps)*l(rx, ry)[i]);\n}\n\nMatrix2cd gen_U(int i, double rx, double ry) {\n    return gen_Ui(gen_theta(i, rx, ry));\n}\n\nMatrix2cd gen_Ubis(int i, double rx, double ry) {\n    return gen_U(i+3, rx, ry);\n}\n\nMatrix2cd gen_Ustar(int i, double rx, double ry) {\n    return gen_U(i, rx, ry).adjoint();\n}\n\nMatrix2cd gen_Ubisstar(int i, double rx, double ry) {\n    return gen_Ustar(i+3, rx, ry);\n}\n\ngrid_t shift(grid_t grid) {\n    grid_t ngrid = zerogrid();\n    for(int x = -xspan; x < xspan; x++) {\n        for(int y = -yspan; y < yspan; y++) {\n            for(int i = 0; i < 3; i++) {\n                int iprec = ((i-1)%3+3)%3;\n                ngrid[x+center[0]][y+center[1]][i] = grid[x+center[0]][y+center[1]][iprec];\n            }\n        }\n    }\n    return ngrid;\n}\n\nstd::pair<double, double> real_coords(int iside, int x, int y, bool show = false) {\n    double dec;\n    if(show)\n        dec = .4;\n    else\n        dec = .5;\n    double xcoord, ycoord;\n    if((x+y)%2==0) {\n        if(iside == 0) {\n            xcoord = x-dec;\n            ycoord = y*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x+dec;\n            ycoord = y*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y+dec)*dy;\n        }\n    }\n    else {\n        if(iside == 0) {\n            xcoord = x+dec;\n            ycoord = y*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x-dec;\n            ycoord = y*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y-dec)*dy;\n        }\n    }\n    return std::make_pair(sqrt(eps)*xcoord, sqrt(eps)*ycoord);\n}\n\nconst int DELTAS[][2] = {{-1,0}, {1,0}, {0,1}};\nconst int NUM_THREADS = 8;\n\nvoid applyCoinsPartial(grid_t &ngrid, grid_t &grid, gen_coin_t &gen_coin, int xmin, int xmax) {\n    for(int x = xmin; x < xmax; x++) {\n        for(int y = -yspan; y < yspan; y++) {\n            if((x+y)%2)\n                continue;\n            for(int iside = 0; iside < 3; iside++) {\n                cd thisval = grid[x+center[0]][y+center[1]][iside];\n                int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                cd otherval = grid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside];\n                Vector2cd vect;\n                vect << thisval, otherval;\n                double rx, ry;\n                std::tie(rx, ry) = real_coords(iside, x, y);\n                Matrix2cd coin = gen_coin(iside, rx, ry);\n                Vector2cd newvect = coin*vect;\n                ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                ngrid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside] = newvect(1);\n            }\n        }\n    }\n}\n\ngrid_t applyCoins(grid_t grid, gen_coin_t gen_coin, bool multithread = true) {\n    grid_t ngrid = zerogrid();\n    if(!multithread) {\n        for(int x = -xspan; x < xspan; x++) {\n            for(int y = -yspan; y < yspan; y++) {\n                if((x+y)%2)\n                    continue;\n                for(int iside = 0; iside < 3; iside++) {\n                    cd thisval = grid[x+center[0]][y+center[1]][iside];\n                    int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                    cd otherval = grid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside];\n                    Vector2cd vect;\n                    vect << thisval, otherval;\n                    double rx, ry;\n                    std::tie(rx, ry) = real_coords(iside, x, y);\n                    Matrix2cd coin = gen_coin(iside, rx, ry);\n                    Vector2cd newvect = coin*vect;\n                    ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                    ngrid[modulo(xo+center[0], ntriangles_x)][modulo(yo+center[1], ntriangles_y)][iside] = newvect(1);\n                }\n            }\n        }\n    }\n    else {\n        std::thread threads[NUM_THREADS];\n        int delta_x = ntriangles_x/NUM_THREADS;\n        for(int iThread = 0; iThread < NUM_THREADS-1; iThread++) {\n            threads[iThread] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(gen_coin), -xspan+iThread*delta_x, -xspan+(iThread+1)*delta_x);\n        }\n        threads[NUM_THREADS-1] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(gen_coin), -xspan+(NUM_THREADS-1)*delta_x, xspan);\n        for(int iThread = 0; iThread < NUM_THREADS; iThread++)\n            threads[iThread].join();\n    }\n    return ngrid;\n}\n\nvoid plotVectorField(double minx, double maxx, double miny, double maxy, int gridstep = 20) {\n    vector<double> xloc, yloc;\n    vector<double> vectx, vecty;\n    double dx = (maxx-minx)/gridstep, dy = (maxy-miny)/gridstep;\n    for(double x = minx; x <= maxx; x += dx)\n        for(double y = miny; y <= maxy; y += dy) {\n            for(int i = 0; i < 2; i++) {\n                xloc.push_back(x);\n                yloc.push_back(y);\n                Matrix2cd deform = lamb(x,y);\n                vectx.push_back(std::real(deform(0,i)));\n                vecty.push_back(std::real(deform(1,i)));\n            }\n        }\n    plt::quiver(xloc, yloc, vectx, vecty, {{\"pivot\",\"tail\"}, {\"color\", \"grey\"}});\n}\n\nvector<double> sphereCoords(double x, double y) {\n    double den = .5*(x*x+y*y)+2;\n    return {2*x/den, 2*y/den, 1-4/den};\n}\n\nvoid plotSphere(int iGrid = -1) {\n    vector<vector<double>> xgrid(2*xspan, vector<double>(2*yspan, 0));\n    vector<vector<double>> ygrid(2*xspan, vector<double>(2*yspan, 0));\n    vector<vector<double>> zgrid(2*xspan, vector<double>(2*yspan, 0));\n    vector<vector<double>> colgrid(2*xspan, vector<double>(2*yspan, 0));\n    vector<double> listcol;\n    for(int x = -xspan; x < xspan; x++)\n        for(int y = -yspan; y < yspan; y++) {\n            double rx, ry;\n            std::tie(rx, ry) = real_coords(0, x, y, true);\n            vector<double> coords = sphereCoords(rx, ry);\n            xgrid[x+center[0]][y+center[1]] = coords[0];\n            ygrid[x+center[0]][y+center[1]] = coords[1];\n            zgrid[x+center[0]][y+center[1]] = coords[2];\n            vector<cd> &vals = grid[x+center[0]][y+center[1]];\n            double sum = 0.0;\n            for(int i = 0; i < 3; i++)\n                sum += std::real(vals[i]*std::conj(vals[i]));\n            //sum /= approxArea(rx, ry);\n            colgrid[x+center[0]][y+center[1]] = sum;\n            listcol.push_back(sum);\n        }\n    std::sort(listcol.rbegin(), listcol.rend());\n    double maxcol = (listcol[0]+listcol[1])/2;\n    if(maxcol == 0.0)\n        maxcol = 1.0;\n    maxcol *= .6;\n    vector<vector<vector<double>>> facecolors(2*xspan, vector<vector<double>> (2*yspan, vector<double> (4,1.0)));\n    for(int x = -xspan; x < xspan; x++)\n        for(int y = -yspan; y < yspan; y++) {\n            double val = std::max(0.0, std::min(1.0, colgrid[x+center[0]][y+center[1]]/maxcol));\n            tinycolormap::Color col = tinycolormap::GetGistHeatColor(1-val);\n            for(int i = 0; i < 3; i++)\n                facecolors[x+center[0]][y+center[1]][i] = col.data[i];\n        }\n    PyObject* fig = plt::plot_surface(xgrid, ygrid, zgrid, {}, facecolors, 1000, 1000, {-45.0, 30.0});\n    std::ostringstream filename;\n    filename << prefix << \"_sphere_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename.str());\n    plt::cla();\n    plt::clf();\n    plt::close(fig);\n    Py_DECREF(fig);\n}\n\nvoid plot(int iGrid = -1) {\n    PyObject* fig = plt::figure_size(1000,1000);\n    /*plt::xlim(-xspan*sqrt(eps), xspan*sqrt(eps));\n    plt::ylim(-yspan*sqrt(eps)*dy, yspan*sqrt(eps)*dy);*/\n    plt::set_aspect_equal();\n    vector<vector<double>> imgrid(2*yspan, vector<double>(2*xspan, 0.0));\n    vector<double> listvals;\n    for(int y = -yspan; y < yspan; y++) {\n        for(int x = -xspan; x < xspan; x++) {\n            double sum = 0.0;\n            for(int iside = 0; iside < 3; iside++) {\n                cd val = grid[x+center[0]][y+center[1]][iside];\n                double col = std::real(val*std::conj(val));\n                sum += col;\n            }\n            listvals.push_back(sum);\n            imgrid[y+center[1]][x+center[0]] = sum;\n        }\n    }\n    std::sort(listvals.rbegin(), listvals.rend());\n    double maxi = (listvals[0]+listvals[1])/2;\n    if(maxi == 0.0)\n        maxi = 1.0;\n    maxi *= .6;\n    double minx = sqrt(eps)*(-xspan-.5);\n    double maxx = sqrt(eps)*(xspan-.5);\n    double miny = sqrt(eps)*dy*(-yspan-.5);\n    double maxy = sqrt(eps)*dy*(yspan-.5);\n    plt::imshow(imgrid, {minx, maxx, miny, maxy}, {{\"origin\", \"lower\"}, {\"cmap\", \"gist_heat_r\"}, {\"vmin\", \"0.0\"}, {\"vmax\", std::to_string(maxi)}});\n    if(showVectField)\n        plotVectorField(-xspan*sqrt(eps), (xspan-1)*sqrt(eps), -yspan*sqrt(eps)*dy, (yspan-1)*sqrt(eps)*dy, 20);\n    std::ostringstream filename;\n    filename << prefix << \"_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename.str());\n    plt::cla();\n    plt::clf();\n    plt::close(fig);\n    Py_DECREF(fig);\n}\n\nvoid step_walk(int step = -1) {\n    std::cerr << \"Begin step \" << step << std::endl;\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = H;\n        return ret;\n    });\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ustar);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_U(modulo(i-1,3), rx, ry);\n            return ret;\n        });\n    }\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_U);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ustar(modulo(i-1,3), rx, ry);\n            return ret;\n        });\n    }\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = Q*H;\n        return ret;\n    });\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ubisstar);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ubis(modulo(i-1,3), rx, ry);\n            return ret;\n        });\n    }\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, gen_Ubis);\n        grid = shift(grid);\n        grid = applyCoins(grid, [](int i, double rx, double ry) {\n            Matrix2cd ret = gen_Ubisstar(modulo(i-1,3), rx, ry);\n            return ret;\n        });\n    }\n    grid = applyCoins(grid, [](int i, double rx, double ry) {\n        Matrix2cd ret = Q.adjoint();\n        return ret;\n    });\n    std::cerr << \"Total amplitude: \" << sumAmplitudes() << \"\\n\";\n    std::cerr << \"End step \" << step << std::endl;\n}\n\nvoid print_params() {\n    std::ofstream ostream(prefix + \"/settings.txt\");\n    ostream << \"num_steps = \" << num_steps << \"\\n\";\n    ostream << \"eps = \" << eps << \"\\n\";\n    ostream << \"xspan = \" << xspan << \"\\n\";\n    ostream << \"yspan = \" << yspan << \"\\n\";\n    ostream << \"deformation: \" << deform_name[deformation] << \"\\n\";\n    ostream << \"initial state: \" << initialStateName[initialState] << \"\\n\";\n    /*ostream << \"Deformation matrix at (1,1):\\n\" << lamb(1,1) << \"\\n\";\n    for(int i = 0; i < 6; i++) {\n        ostream << \"U\" << i << \"(1,1):\\n\" << gen_U(i,1,1) << \"\\n\";\n    }\n    ostream << \"H=\\n\" << H << \"\\n\";\n    ostream << \"Q=\\n\" << Q << std::endl;*/\n    ostream.close();\n}\n\nvoid listDeformations() {\n    for(size_t i = 0; i < deform_name.size(); i++) {\n        std::cerr << \"- \" << i << \": \" << deform_name[i] << \"\\n\";\n    }\n}\n\nvoid listInitialStates() {\n    for(size_t i = 0; i < initialStateName.size(); i++)\n        std::cerr << \"- \" << i << \": \" << initialStateName[i] << \"\\n\";\n}\n\nint main(int argc, char **argv)\n{\n    if(argc <= 2) {\n        std::cerr << \"Usage: \" << std::string(argv[0]) << \" <deformation> <initial state> [force sphere].\\n\";\n        std::cerr << \"Deformations:\\n\";\n        listDeformations();\n        std::cerr << \"Initial states:\\n\";\n        listInitialStates();\n        std::cerr << \"Put any non-empty third argument to force plotting on a sphere.\\n\";\n        return 1;\n    }\n    deformation = std::atoi(argv[1]);\n    if(deformation < 0 || deformation >= (int)deform_name.size()) {\n        std::cerr << \"Invalid deformation \" << deformation << \". List of deformations:\\n\";\n        listDeformations();\n        return 2;\n    }\n    initialState = std::atoi(argv[2]);\n    if(initialState < 0 || initialState >= (int)initialStateName.size()) {\n        std::cerr << \"Invalid initial state \" << initialState << \". List of initial states:\\n\";\n        listInitialStates();\n        return 3;\n    }\n    forceSphere = argc >= 4;\n    std::cout << \"Deformation selected: \" << deformation << \" \" << deform_name[deformation] << std::endl;\n    std::ostringstream str;\n    str <<\n        \"simul_distorted_\" << deform_name[deformation] << \"_\" << initialStateName[initialState] << \"_\" <<\n        std::setw(4) << std::setfill('0') << ltm->tm_year+1900 << \"-\" << \n        std::setw(2) << ltm->tm_mon+1 << \"-\" << \n        std::setw(2) << ltm->tm_mday << \"_\" << \n        std::setw(2) << ltm->tm_hour << \"-\" << \n        std::setw(2) << ltm->tm_min << \"-\" << \n        std::setw(2) << ltm->tm_sec;\n    prefix = str.str();\n    std::filesystem::create_directory(prefix);\n    init_HQ();\n    print_params();\n    // Initial state\n    // Vertical\n    if(initialState == 1)\n        for(int y = -yspan; y < yspan; y++)\n            for(int k = 0; k < 3; k++)\n                grid[center[0]][y+center[1]][k] = 1;\n    // Centered\n    else if(initialState == 0)\n        for(int k = 0; k < 3; k++)\n            grid[center[0]][center[1]][k]=1/sqrt(3);\n    // Centered, side 0\n    else if(initialState == 2)\n        grid[center[0]][center[1]][0] = 1;\n    // Centered, side 1\n    else if(initialState == 3)\n        grid[center[0]][center[1]][1] = 1;\n    // Centered, side 2\n    else if(initialState == 4)\n        grid[center[0]][center[1]][2] = 1;\n    // Shifted up-right at half\n    else if(initialState == 5)\n        for(int k = 0; k < 3; k++)\n            grid[center[0]+xspan/2][center[1]+yspan/2][k] = 1/sqrt(3);\n    // Shifted up-right at third\n    else if(initialState == 6)\n        for(int k = 0; k < 3; k++)\n            grid[center[0]+xspan/3][center[1]+yspan/3][k] = 1/sqrt(3);\n    // Sine, x dimension\n    else if(initialState == 7) {\n        const double rxmin = (-xspan-.5)*sqrt(eps);\n        const double rxmax = (xspan-.5)*sqrt(eps);\n        for(int x = -xspan; x < xspan; x++)\n            for(int y = -yspan; y < yspan; y++)\n                for(int k = 0; k < 3; k++) {\n                    double rx, ry;\n                    std::tie(rx, ry) = real_coords(k,x,y);\n                    grid[center[0]+x][center[1]+y][k] = sin(2*M_PI*(float)(rx-rxmin)/(rxmax-rxmin));\n                }\n        normalizeGrid();\n    }\n    // Sine, y dimension\n    else if(initialState == 8) {\n        const double rymin = (-yspan-.5)*sqrt(eps);\n        const double rymax = (yspan-.5)*sqrt(eps);\n        for(int x = -xspan; x < xspan; x++)\n            for(int y = -yspan; y < yspan; y++)\n                for(int k = 0; k < 3; k++) {\n                    double rx, ry;\n                    std::tie(rx, ry) = real_coords(k,x,y);\n                    grid[center[0]+x][center[1]+y][k] = sin(2*M_PI*(float)(ry-rymin)/(rymax-rymin));\n                }\n        normalizeGrid();\n    }\n    // A rectangle\n    else if(initialState == 9) {\n        for(int x = -xspan/5; x <= (xspan-1)/5; x++)\n            for(int y = -yspan/5; y <= (yspan-1)/5; y++)\n                for(int k = 0; k < 3; k++)\n                    grid[center[0]+x][center[1]+y][k] = 1;\n        normalizeGrid();\n    }\n    plot(0);\n    bool isSphere = deformation == 5 || deformation == 6;\n    if(isSphere || forceSphere)\n        plotSphere(0);\n    for(int i = 0; i < num_steps; i++) {\n        step_walk(i);\n        if((i+1)%10 == 0) {\n            plot(i+1);\n            if(isSphere || forceSphere)\n                plotSphere(i+1);\n        }\n    }\n}\n", "meta": {"hexsha": "12cc8b33e6841c2e10f57a9bb695c5da735c4686", "size": 22363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "triangular_distorted.cpp", "max_stars_repo_name": "vdng9338/qw_simul", "max_stars_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "triangular_distorted.cpp", "max_issues_repo_name": "vdng9338/qw_simul", "max_issues_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "triangular_distorted.cpp", "max_forks_repo_name": "vdng9338/qw_simul", "max_forks_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_forks_repo_licenses": ["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.3776119403, "max_line_length": 169, "alphanum_fraction": 0.5095023029, "num_tokens": 6926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5651050747517459}}
{"text": "/* Bubble Dynamics with Chebyshev Spectral Collocation */\n\n#include <iostream>\n#include <fstream>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <vector>\n#include <algorithm>\n#include <random>\n#include <string>\n#include <sstream>\n#include <chrono>\n#include <thread>\n#include <boost/numeric/odeint.hpp>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nconst double rho_L = 9.970639504998557e+02;\nconst double p_inf = 1.0e+5;\nconst double sigma = 0.071977583160056;\n//const double R_E = 10e-6; //1...10u\nconst double gamma = 1.33;\nconst double c_L = 1.497251785455527e+03; // water 25 Celsius\nconst double mu_L = 8.902125058209557e-04; //25 Celsius\nconst double lambda = 0.6084; //water 25 Celsius\nconst double T_inf = 298.15; // 25 Celsius\nconst int N = 16; //24:25s  32:104s 48:731s\nconst double tolerance = 1e-13;\nconst double t_max = 0.5;\nconst int sample = 25000;\n\ntypedef double value_type;\ntypedef vector<value_type> state_type;\ntypedef Eigen::Matrix<value_type, N/2, N/2> matrix_type;\n\nusing namespace boost::numeric;\n\n//ode function of bubble dynamic\nclass bubble {\npublic:\n\tstd::vector<value_type> C; //constants of the right hand side\n\tEigen::Matrix<value_type, N/2, 1> y; //collocation points (half)\n\tEigen::Matrix<value_type, N/2, 1> y_sq;\n\tmatrix_type D_E; //Derivative matrix for even functions\n\tmatrix_type D_O; //Derivative matrix for odd functions\n\tEigen::Matrix<value_type, 1, N/2> D_E0; //first row of even D matrix\n\n\t//p_A pressure amplitude, f pressure frequence, N number of collocation points\n\tbubble(value_type p_A, value_type f, value_type R_E){\n\t\tconst double omega = 2*M_PI*f;\n\t\tvalue_type pi2wRE = 2*M_PI/(omega*R_E);\n\n\t\tC = std::vector<value_type>(13);\n\t\tC[0] = omega*R_E/(2*M_PI*c_L);\n\t\tC[1] = 4*mu_L/(c_L*rho_L*R_E);\n\t\tC[2] = 4*mu_L/(rho_L*R_E)*pi2wRE;\n\t\tC[3] = 2*sigma*pi2wRE*pi2wRE/(rho_L*R_E);\n\t\tC[4] = p_inf/rho_L*pi2wRE*pi2wRE;\n\t\tC[5] = p_A/rho_L*pi2wRE*pi2wRE;\n\t\tC[6] = pi2wRE*p_inf/(c_L*rho_L);\n\t\tC[7] = pi2wRE*p_A/(c_L*rho_L);\n\t\tC[8] = 2*M_PI*pi2wRE*p_A/(c_L*rho_L);\n\t\tC[9] = lambda*(gamma-1)/gamma*pi2wRE/R_E*T_inf/p_inf;\n\t\tC[10] = lambda*(gamma-1)*pi2wRE/R_E*T_inf/p_inf;\n\t\tC[11] = (gamma-1)/gamma;\n\t\tC[12] = 1.0/(3.0*gamma);\n\t\t\n\n\t\tEigen::Matrix<value_type, N, 1> y_full(N);\n\t\tvalue_type rec_cpn =  1.0/(N-1);\n\t\tfor(int i = 0; i < N; i++){\n\t\t\ty_full[i] = cos(M_PI*i*rec_cpn);\n\t\t\t//std::cout << y_full[i] << std::endl;\n\t\t}\n\t\tEigen::Matrix<value_type, N, N> D(N, N);\n\t\tfor(int i = 0; i < N; i++){\n\t\t\tfor(int j = 0; j < N; j++){\n\t\t\t\tif(i == j){\n\t\t\t\t\tif(i == N-1){\n\t\t\t\t\t\tD(N-1,N-1) = -(1+2*(N-1)*(N-1))/6.0;\n\t\t\t\t\t}else if(i == 0){\n\t\t\t\t\t\tD(0,0) = (1+2*(N-1)*(N-1))/6.0;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tD(i,i) = -y_full[i]/(2.0*(1.0-y_full[i]*y_full[i]));\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tD(i,j) = std::pow(-1,i+j)*(i==0 || i==N-1?2.0:1.0)\n\t\t\t\t\t\t\t/((j==0 || j==N-1?2.0:1.0) * (y_full[i]-y_full[j]) );\n\t\t\t\t}\n\t\t\t\t//cout << D(i,j) <<\" \";\n\t\t\t}\n\t\t\t//cout << endl;\n\t\t}\n\t\tD_E = matrix_type(N/2,N/2);\n\t\tD_O = matrix_type(N/2,N/2);\n\t\tfor(int i = 0; i < N/2;i++){\n\t\t    for(int j = 0; j < N/2; j++){\n\t\t    \tD_E(i,j) = D(i,j) + D(i,N-1-j);\n\t\t    \tif(i==0) D_E0(j) = D_E(i,j);\n\t\t    \t//cout << D_E(i,j) <<\" \";\n\t\t\t}\n\t\t    //cout << endl;\n\t\t}\n\t\tfor(int i = 0; i < N/2;i++){\n\t\t\tfor(int j = 0; j < N/2; j++){\n\t\t\t\tD_O(i,j) = D(i,j) - D(i,N-1-j);\n\t\t\t\t//cout << D_O(i,j) <<\" \";\n\t\t    }\n\t\t\t//cout << endl;\n\t\t}\n\t\ty = y_full.head<N/2>();\n\t\ty_sq = y.cwiseProduct(y);\n    }\n\n\tvoid operator()(const state_type &x, state_type &dxdt, const value_type t){\n\t    value_type rec_xR = 1.0 / x[0];\n\t    value_type rec_xp = 1.0 / x[2];\n\n\t    Eigen::Map<const Eigen::Matrix<value_type, N/2,1>> z(x.data()+3);\n\t    Eigen::Map<Eigen::Matrix<value_type, N/2,1>> dzdt(dxdt.data()+3);\n\n\t    Eigen::Matrix<value_type, N/2, 1> De_x = D_E*z; //derivative of z (dimless temperature)\n\t\t/*for(int i = 0; i < N/2; i++){\n\t    \tstd::cout << \"t\" << y_sq[i] << std::endl;\n\t    }*/\n\n\t    //bubble pressure evolution\n\t    dxdt[2] = 3*rec_xR*(C[10]*rec_xR* De_x[0] - gamma*x[1]*x[2]);\n\n\t    //discretized PDE of bubble temperature\n\t    dzdt = De_x.cwiseProduct( x[1]*rec_xR*y - C[9]*rec_xR*rec_xR*rec_xp* De_x //this might show error, but it will not fail at compile time, valid syntax\n\t    \t\t+ C[12]*rec_xp*dxdt[2]*y )\n\t    \t\t+ C[11]*rec_xp*dxdt[2]*z + C[9]*rec_xp*rec_xR*rec_xR* z\n\t\t\t\t.cwiseProduct(y_sq.cwiseInverse()).cwiseProduct(D_O * (y_sq.cwiseProduct(De_x)));\n\t    dxdt[3] = 0.0; //Boundary condition\n\n\t    //Keller-Miksis equation\n\t    dxdt[0] = x[1];\n\t    value_type sin2pit = sin(2*M_PI*t);\n\t    value_type den = x[0] - C[0]*x[0]*x[1] + C[1];\n\t    value_type nom = 0.5*C[0] * x[1]*x[1]*x[1] - 1.5* x[1]*x[1] - C[2]*x[1]*rec_xR - C[3]*rec_xR\n\t    \t\t+ C[4] * x[2] - C[4] - C[5] * sin2pit + C[6] * x[1]*x[2] - C[6] * x[1] - C[7] * x[1]*sin2pit\n\t            - C[8] * x[0]*cos(2*M_PI*t) + C[6] * x[0]*dxdt[2];\n\t    dxdt[1] = nom/den;\n\t}\n};\n\n\n//vector<double> fs = {20e3, 100e3, 500e3, 2e6};\n//vector<double> pAs = {0.5e5, 1.0e5, 1.5e5, 2.0e5};\ntypedef runge_kutta_dopri5< state_type , value_type , state_type , value_type > stepper_type;\n\nint main() {\n\tcout << \"Bubble dynamics runs started\\n\" << setprecision(17) << endl;\n\tauto t1 = chrono::high_resolution_clock::now();\n\t\n\tdouble f = 100e3;\n\tdouble R_E = 10e-6;\n\tdouble p_A = 0.5e5;\n\t\n    std::mt19937 gen;\n\tgen.seed(42); //reporducibility\n    std::uniform_real_distribution<> dis(0.0, 0.5);\n\t\n\tvector<double> times(sample);\n\tfor(int jj=0;jj<sample;jj++){\n\t\ttimes[jj] = dis(gen);\n\t}\n\t/*sort(times.begin(),times.end());\n\tauto last = unique(times.begin(),times.end()); //to get rid of duplicates, if any\n\ttimes.erase(last, times.end());*/\n\tint sampled = times.size();\n\n\tstate_type x(3+N/2);\n\tstate_type dxdt(3+N/2);\n\n\tbubble bubi(p_A, f, R_E);\n\tauto stepper = make_controlled( tolerance , tolerance, stepper_type() );\n\t\t\t\n\tstringstream ss(\"\");\n\tss << \"../data/bubble_sim_p\" << p_A/1e5 << \"_f\" << f/1e3 << \"_Re\" << R_E*1e6 << \"_N\" << N << \"_t\" << t_max << \"_\" << sampled << \".txt\";\n\tstring file_name = ss.str();\n\tofstream ofs(file_name);\n\n\tif(!ofs.is_open()){\n\t\tcout << \"File cannot be opened.\" << endl;\n\t\texit(-1);\n\t}\n\tofs.precision(17);\n\tofs.flags(ios::scientific);\n\t\t\n\tx[0] = 1.0;\n\tx[1] = 0.0;\n\tx[2] = 1.0 + 2.0*sigma/(p_inf*R_E);\n\tfor(int i=0; i < N/2;i++) x[3+i] = 1.0;\n\n\tdouble t_start = 0.0;\n\t\n\ttry{\n\t\tfor(int jj=0; jj < sampled; jj++){\n\t\t\tintegrate_adaptive(boost::ref(stepper), boost::ref(bubi), x, t_start, times[jj], 0.01);\n\t\t\tt_start = times[jj];\n\t\t\tofs << times[jj] << \", \" << x[0];\n\t\t\tfor(int i =1; i < 3+N/2;i++){\n\t\t\t\tofs << \", \" << x[i];\n\t\t\t}\n\t\t\tbubi(x, dxdt, times[jj]);\n\t\t\tfor(int i =0; i < 3+N/2;i++){\n\t\t\t\tofs << \", \" << dxdt[i];\n\t\t\t}\n\t\t\tofs << \", \" << sin(2*M_PI*times[jj]);\n\t\t\tofs << endl;\n\t\t}\n\t\tcout << \"Written \" << sampled << \" lines.\" << endl;\n\t}catch(int i){\n\t\tcout << \" - aborted: R_E=\" << R_E << \", f=\" << f << \", p_A=\" << p_A << endl;\n\t}\n\n\tauto t2 = chrono::high_resolution_clock::now();\n\tcout << \"Fertig\" << endl;\n\tcout << \"Time (ms):\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "9559d349131daaed8bcfe116d133479f8af69acc", "size": 7015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DEM/data_gen/data_gen.cpp", "max_stars_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_stars_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DEM/data_gen/data_gen.cpp", "max_issues_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_issues_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DEM/data_gen/data_gen.cpp", "max_forks_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_forks_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_forks_repo_licenses": ["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.0398230088, "max_line_length": 154, "alphanum_fraction": 0.5866001426, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5651050683021822}}
{"text": "#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <crab/support/os.hpp>\n#include <cstdint>\n#include <gmp.h>\n\n// TODO: replace ikos with crab namespace. This class has nothing to\n// do with the ikos one. Kept for now for compatibility issues with\n// some clients.\nnamespace ikos {\n\nclass z_number {\n  friend class q_number;\n\nprivate:\n  mpz_t _n;\n\n  bool fits_sint() const;\n  bool fits_slong() const;\n\npublic:\n  // overloaded typecast operators\n  explicit operator int64_t() const;\n\n  z_number();\n  z_number(int64_t n);\n  z_number(const std::string &s, unsigned base = 10);\n\n  static z_number from_uint64(uint64_t n);\n  static z_number from_mpz_t(mpz_t n);\n  static z_number from_mpz_srcptr(mpz_srcptr n);\n\n  z_number(const z_number &o);\n  z_number(z_number &&o);\n  z_number &operator=(const z_number &o);\n  z_number &operator=(z_number &&o);\n\n  ~z_number();\n\n  mpz_srcptr get_mpz_t() const { return _n; }\n\n  mpz_ptr get_mpz_t() { return _n; }\n\n  std::string get_str(unsigned base = 10) const;\n\n  std::size_t hash() const;\n\n  bool fits_int64() const;\n\n  z_number operator+(z_number x) const;\n\n  z_number operator*(z_number x) const;\n\n  z_number operator-(z_number x) const;\n\n  z_number operator-() const;\n\n  // signed division\n  z_number operator/(z_number x) const;\n\n  // signed remainder\n  z_number operator%(z_number x) const;\n\n  z_number &operator+=(z_number x);\n\n  z_number &operator*=(z_number x);\n\n  z_number &operator-=(z_number x);\n\n  z_number &operator/=(z_number x);\n\n  z_number &operator%=(z_number x);\n\n  z_number &operator--();\n\n  z_number &operator++();\n\n  z_number operator++(int);\n\n  z_number operator--(int);\n\n  bool operator==(z_number x) const;\n\n  bool operator!=(z_number x) const;\n\n  bool operator<(z_number x) const;\n\n  bool operator<=(z_number x) const;\n\n  bool operator>(z_number x) const;\n\n  bool operator>=(z_number x) const;\n\n  // bitwise-and\n  z_number operator&(z_number x) const;\n\n  // bitwise-or\n  z_number operator|(z_number x) const;\n\n  // bitwise-xor\n  z_number operator^(z_number x) const;\n\n  // left shift\n  z_number operator<<(z_number x) const;\n\n  // arithmetic right shift\n  z_number operator>>(z_number x) const;\n\n  z_number fill_ones() const;\n\n  void write(crab::crab_os &o) const;\n\n}; // class z_number\n\nclass q_number {\n\nprivate:\n  mpq_t _n;\n\npublic:\n  q_number();\n  q_number(double n);\n\n  q_number(const std::string &s, unsigned base = 10);\n  q_number(const z_number &n);\n  q_number(const z_number &n, const z_number &d);\n\n  static q_number from_mpq_t(mpq_t n);\n  static q_number from_mpz_t(mpz_t n);\n  static q_number from_mpq_srcptr(mpq_srcptr q);\n\n  q_number(const q_number &o);\n  q_number(q_number &&o);\n  q_number &operator=(const q_number &o);\n  q_number &operator=(q_number &&o);\n\n  ~q_number();\n\n  mpq_srcptr get_mpq_t() const { return _n; }\n\n  mpq_ptr get_mpq_t() { return _n; }\n\n  double get_double() const;\n\n  std::string get_str(unsigned base = 10) const;\n\n  std::size_t hash() const;\n\n  q_number operator+(q_number x) const;\n\n  q_number operator*(q_number x) const;\n\n  q_number operator-(q_number x) const;\n\n  q_number operator-() const;\n\n  q_number operator/(q_number x) const;\n\n  q_number &operator+=(q_number x);\n\n  q_number &operator*=(q_number x);\n\n  q_number &operator-=(q_number x);\n\n  q_number &operator/=(q_number x);\n\n  q_number &operator--();\n\n  q_number &operator++();\n\n  q_number operator--(int);\n\n  q_number operator++(int);\n\n  bool operator==(q_number x) const;\n\n  bool operator!=(q_number x) const;\n\n  bool operator<(q_number x) const;\n\n  bool operator<=(q_number x) const;\n\n  bool operator>(q_number x) const;\n\n  bool operator>=(q_number x) const;\n\n  z_number numerator() const;\n\n  z_number denominator() const;\n\n  z_number round_to_upper() const;\n\n  z_number round_to_lower() const;\n\n  void write(crab::crab_os &o) const;\n\n}; // class q_number\n\ninline crab::crab_os &operator<<(crab::crab_os &o, const z_number &z) {\n  z.write(o);\n  return o;\n}\n\ninline crab::crab_os &operator<<(crab::crab_os &o, const q_number &q) {\n  q.write(o);\n  return o;\n}\n\n/** for boost::hash_combine **/\ninline std::size_t hash_value(const z_number &z) { return z.hash(); }\n\ninline std::size_t hash_value(const q_number &q) { return q.hash(); }\n} // namespace ikos\n\n/** for specializations of std::hash **/\nnamespace std {\ntemplate <> struct hash<ikos::z_number> {\n  size_t operator()(const ikos::z_number &z) const { return z.hash(); }\n};\n\ntemplate <> struct hash<ikos::q_number> {\n  size_t operator()(const ikos::q_number &q) const { return q.hash(); }\n};\n} // namespace std\n", "meta": {"hexsha": "b7f08377d0a784c5efae5de96a982275cebcba4c", "size": 4536, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/numbers/bignums.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/numbers/bignums.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/numbers/bignums.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": 20.0707964602, "max_line_length": 71, "alphanum_fraction": 0.6909171076, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.565044576653849}}
{"text": "// ///////////////////////////////////////////////////\n// Roy Burstein and Aaron Osgood-Zimmerman\n// August 2017\n// Template file for space-time-Z GPR model.\n// Used for fitting IHME Geospatial MBG models\n// ///////////////////////////////////////////////////\n\n// ///////////////////////////////////////////////////\n// NOTES:\n// 1. Type `Type` is a special TMB type that should be used for all variables, except `int` can be used as well\n// 2. In our nomenclature, Z is a third interaction (ie age) which defaults to AR1\n// 3. Requires same space mesh for all time-Z points\n// 4. Anything in the density namespace (ie SEPARABLE) returns the negative log likelihood and is thus added to accumulator\n//    also, other density function such as dnorm and dbinom return positive log likelihood and are thus subtracted away.\n// 5. ref https://github.com/nmmarquez/re_simulations/blob/master/inla/sta.cpp\n//        https://github.com/nmmarquez/re_simulations/blob/master/inla/SPDEAR1AR1.R\n// ///////////////////////////////////////////////////\n\n// include libraries\n#include <TMB.hpp>\n#include <Eigen/Sparse>\n#include <vector>\nusing namespace density;\nusing Eigen::SparseMatrix;\n\n\n// helper function to make sparse SPDE precision matrix\n// Inputs:\n//    logkappa: log(kappa) parameter value\n//    logtau: log(tau) parameter value\n//    M0, M1, M2: these sparse matrices are output from R::INLA::inla.spde2.matern()$param.inla$M*\ntemplate<class Type>\nSparseMatrix<Type> spde_Q(Type logkappa, Type logtau, SparseMatrix<Type> M0,\n                          SparseMatrix<Type> M1, SparseMatrix<Type> M2) {\n    SparseMatrix<Type> Q;\n    Type kappa2 = exp(2. * logkappa);\n    Type kappa4 = kappa2*kappa2;\n    Q = pow(exp(logtau), 2.)  * (kappa4*M0 + Type(2.0)*kappa2*M1 + M2);\n    return Q;\n}\n\n// helper function for detecting NAs in the data supplied from R\ntemplate<class Type>\nbool isNA(Type x){\n  return R_IsNA(asDouble(x));\n}\n\n// Robust Inverse Logit that sets min and max values to avoid numerical instability\ntemplate<class Type>\nType invlogit_robust(Type x){\n  if (x < -20.723){\n    x = -20.723; // corresponds to p=1e-9\n  } else if ( x > 20.723 ){\n    x = 20.723;  // cooresponds to p=1-1e-9\n  }\n  return 1 / (1 + exp( -1.0 * x ));\n}\n\n\n// AR funtion from neal m\ntemplate<class Type>\nSparseMatrix<Type> ar_Q(int N, Type rho, Type sigma) {\n  SparseMatrix<Type> Q(N,N);\n  Q.insert(0,0) = (1.) / pow(sigma, 2.);\n  for (size_t n = 1; n < N; n++) {\n    Q.insert(n,n) = (1. + pow(rho, 2.)) / pow(sigma, 2.);\n    Q.insert(n-1,n) = (-1. * rho) / pow(sigma, 2.);\n    Q.insert(n,n-1) = (-1. * rho) / pow(sigma, 2.);\n  }\n  Q.coeffRef(N-1,N-1) = (1.) / pow(sigma, 2.);\n  return Q;\n}\n\n// Corresponding list object on the C++ side\ntemplate<class Type>\nstruct option_list {\n  int use_priors;\n  int adreport_off;\n  int nugget;\n  int country_random;\n  int NID_random;\n  int useGP;\n  // Way easier to read these in as vectors of integers and then index the first\n  option_list(SEXP x){\n    use_priors = asVector<int>(getListElement(x,\"use_priors\"))[0];\n    adreport_off = asVector<int>(getListElement(x,\"adreport_off\"))[0];\n    nugget = asVector<int>(getListElement(x,\"nugget\"))[0];\n    country_random = asVector<int>(getListElement(x,\"country_random\"))[0];\n    NID_random = asVector<int>(getListElement(x,\"NID_random\"))[0];\n    useGP = asVector<int>(getListElement(x,\"useGP\"))[0];\n  }\n};\n\n// how to read in an object that is used as a prior for standard devs of res\ntemplate<class Type>\nstruct prior_type_sigma {\n  std::string name;\n  Type par1;\n  Type par2;\n  \n  prior_type_sigma(SEXP x){\n    name = CHAR(STRING_ELT(getListElement(x,\"type\"), 0));\n    par1 = asVector<float>(getListElement(x,\"par1\"))[0];\n    par2 = asVector<float>(getListElement(x,\"par2\"))[0];\n  }\n};\n\n// how to read in an object that is used as a prior for Matern hyperparameters\ntemplate<class Type>\nstruct prior_type_matern {\n  std::string name;\n  Type par1a; //mean logtau / rho0\n  Type par1b; //prec logtau / alpha_rho\n  Type par2a; //mean logkappa / sigma0\n  Type par2b; //prec logkappa / alpha_sigma\n  \n  prior_type_matern(SEXP x){\n    name = CHAR(STRING_ELT(getListElement(x,\"type\"), 0));\n    par1a = asVector<float>(getListElement(x,\"par1\"))[0];\n    par1b = asVector<float>(getListElement(x,\"par1\"))[1];\n    par2a = asVector<float>(getListElement(x,\"par2\"))[0];\n    par2b = asVector<float>(getListElement(x,\"par2\"))[1];\n  }\n};\n\n// evaluate a prior for sigma using the read in object\ntemplate<class Type>\nType eval_prior_sigma(prior_type_sigma<Type> prior, Type log_sigma){\n  Type penalty;\n  // transform log sigma to log tau space to match INLA prior specification\n  // NOTE: log tau --> x=log sigma -->\n  //    transform: log tau = -2x --> Jacobian: |J| = 2\n  // https://becarioprecario.bitbucket.io/inla-gitbook/ch-priors.html#sec:priors\n  Type tau = pow(exp(log_sigma), -2.);\n  Type logtau = log(tau);\n  \n  if(prior.name == \"pc.prec\") {\n    Type lambda = - log(prior.par2) / prior.par1;\n    penalty = -lambda * exp(-logtau/Type(2.0)) - logtau/Type(2.0);\n  } \n  else if(prior.name == \"normal\") {\n    // prior.par2 needs to be in precision space such as in INLA\n    // https://inla.r-inla-download.org/r-inla.org/doc/prior/gaussian.pdf\n    penalty = dnorm(logtau, prior.par1, pow(prior.par2, -.5), true);\n  }\n  else { //loggamma\n    // prior.par2 gamma function for TMB uses shape and scale\n    // https://kaskr.github.io/adcomp/group__R__style__distribution.html#gab0e2205710a698ad6a0ed39e0652c9a3\n    // INLA uses shape and rate so we need to transforma\n    // https://inla.r-inla-download.org/r-inla.org/doc/prior/prior-loggamma.pdf\n    penalty = dlgamma(logtau, prior.par1, 1./prior.par2, true);\n  }\n  \n  return penalty;\n}\n\n// evaluate priors for matern using the read in object\ntemplate<class Type>\nType eval_prior_matern(prior_type_matern<Type> prior, Type logtau, Type logkappa){\n  Type penalty;\n  \n  if(prior.name == \"pc\") {\n    Type d = 2.;\n    Type lambda1 = -log(prior.par1b) * pow(prior.par1a, d/2.);\n    Type lambda2 = -log(prior.par2b) / prior.par2a;\n    Type range   = sqrt(8.0) / exp(logkappa);\n    Type sigma   = 1.0 / sqrt(4.0 * 3.14159265359 * exp(2.0 * logtau) * exp(2.0 * logkappa));\n    \n    penalty = (-d/2. - 1.) * log(range) - lambda1 * pow(range, -d/2.) - lambda2 * sigma;\n    // Note: (rho, sigma) --> (x=log kappa, y=log tau) -->\n    //  transforms: rho = sqrt(8)/e^x & sigma = 1/(sqrt(4pi)*e^x*e^y)\n    //  --> Jacobian: |J| propto e^(-y -2x)\n    Type jacobian = - logtau - 2.0*logkappa;\n    penalty += jacobian;\n  } \n  else { //normal\n    penalty = dnorm(logtau, prior.par1a, 1/sqrt(prior.par1b), true) +\n      dnorm(logkappa, prior.par2a, 1/sqrt(prior.par2b), true);\n  }\n  \n  return penalty;\n}\n\n// Constrain alpha values\ntemplate<class Type>\nvector<Type> constrain_pars(vector<Type> alpha, vector<int> constraints){\n  int K = alpha.size();\n  vector<Type> alpha_c(K);\n  \n  for(int k = 0; k < K; k++){\n    if(constraints[k] == 1){\n      alpha_c[k] = exp(alpha[k]);\n    }\n    if(constraints[k] == -1){\n      alpha_c[k] = -1. * exp(alpha[k]);\n    }\n    if(constraints[k] == 0){\n      alpha_c[k] = alpha[k];\n    }\n  }\n  \n  return alpha_c;\n}\n\n// objective function (ie the likelihood function for the model), returns the evaluated negative log likelihood\ntemplate<class Type>\nType objective_function<Type>::operator() ()\n{\n\n  // ////////////////////////////////////////////////////////////////////////////\n  // INPUTS\n  // ////////////////////////////////////////////////////////////////////////////\n  DATA_INTEGER(flag); // flag=0 => only prior\n\n  // Indices\n  DATA_INTEGER(num_i);       // number of datapts in space-time-Z (aka STZ)\n  DATA_INTEGER(num_s);       // number of mesh pts in space mesh\n  DATA_INTEGER(num_t);       // number of time periods\n  DATA_INTEGER(num_z);       // number of Z groups\n\n  // Data (each, excpect for X_ij is a vector of length num_i)\n  DATA_VECTOR(y_i);          // obs successes per binomial experiment at point i (aka cluster)\n  DATA_VECTOR(n_i);          // trials per cluster\n  DATA_IVECTOR(t_i);         // time period of the data point\n  DATA_IVECTOR(c_re_i);      // country identifiers\n  DATA_IVECTOR(nid_re_i);    // NID identifiers\n  DATA_IVECTOR(w_i);         // weights for observations\n  DATA_MATRIX(X_ij);         // covariate design matrix (num_i by number of fixed effects matrix)\n  DATA_IVECTOR(fconstraints); // constraints of fixed effects\n\n  // instructions for likelihood asessment\n  DATA_VECTOR(lik_gaussian_i); // data likelihood for each row\n  DATA_VECTOR(lik_binomial_i); // data likelihood for each row\n  DATA_VECTOR(sd_i);           // crossalked standard deviation (set to zero if non-existant)\n\n  // SPDE objects\n  DATA_SPARSE_MATRIX(M0);    // used to make gmrf precision\n  DATA_SPARSE_MATRIX(M1);    // used to make gmrf precision\n  DATA_SPARSE_MATRIX(M2);    // used to make gmrf precision\n  DATA_SPARSE_MATRIX(Aproj); // used to project from spatial mesh to data locations\n\n  // Boolean vector of options to be used to select different models/modelling \n  //   options: see above\n  DATA_STRUCT(options, option_list);  \n\n  // Prior specifications\n  DATA_STRUCT(prior_log_nugget_sigma, prior_type_sigma);\n  DATA_STRUCT(prior_log_cre_sigma, prior_type_sigma);\n  DATA_STRUCT(prior_log_nidre_sigma, prior_type_sigma);\n  DATA_STRUCT(prior_matern, prior_type_matern);\n  \n  // Parameters\n  PARAMETER_VECTOR(alpha_j);   // fixed effect coefs, including intercept as first index\n  PARAMETER(logtau);           // log of INLA tau param (precision of space-time covariance mat)\n  PARAMETER(logkappa);         // log of INLA kappa - related to spatial correlation and range\n  PARAMETER(trho);             // temporal autocorrelation parameter for AR1, natural scale\n  PARAMETER(zrho);             // Z autocorrelation parameter for AR1, natural scale\n  PARAMETER(log_nugget_sigma); // log of the standard deviation of the normal error nugget term\n  PARAMETER(log_cre_sigma);    // log of the standard deviation of the country random effect (later do as vec if using Random SLOPE TODO)\n  PARAMETER(log_nidre_sigma);  // log of the standard deviation of the nid random effect\n  PARAMETER(log_gauss_sigma);  // log of sigma for any gaussian observations\n\n  // Random effects\n  PARAMETER_ARRAY(Epsilon_stz);  // Random effects for each STZ mesh location. Should be 3D array of dimensions num_s by num_t by num_z\n  PARAMETER_VECTOR(nug_i);       // Random effects of the nugget\n  PARAMETER_VECTOR(cntry_re);    // Random effects values for country intercept\n  PARAMETER_VECTOR(nid_re);      // Random effects values for nid intercept\n\n  printf(\"Epsilon_stz size: %ld \\n\", Epsilon_stz.size());\n\n  // ////////////////////////////////////////////////////////////////////////////\n  // LIKELIHOOD\n  // ////////////////////////////////////////////////////////////////////////////\n\n  // Define the joint-negative log-likelihood as a parallel_accumulator\n  // this allows us to add or subtract numbers to the object in parallel\n  // parallel_accumulator<Type> jnll(this);\n  Type jnll = 0;\n\n  // print parallel info\n  max_parallel_regions = omp_get_max_threads();\n\n  // Make spatial precision matrix\n  SparseMatrix<Type> Q_ss   = spde_Q(logkappa, logtau, M0, M1, M2);\n  printf(\"Q_ss size: %ld \\n\", Q_ss.size());\n\n  // Make transformations of some of our parameters\n  Type range         = sqrt(8.0) / exp(logkappa);\n  Type sigma         = 1.0 / sqrt(4.0 * 3.14159265359 * exp(2.0 * logtau) * exp(2.0 * logkappa));\n  Type trho_trans    = (exp(trho) - 1) / (exp(trho) + 1); // TRANSOFRM from -inf, inf to -1, 1.. //log((1.1 + trho) / (1.1 - trho));\n  Type zrho_trans    = (exp(zrho) - 1) / (exp(zrho) + 1); //TRANSOFRM from -inf, inf to -1, 1.. // log((1.1 + zrho) / (1.1 - zrho));\n  Type nugget_sigma  = exp(log_nugget_sigma);\n  Type cre_sigma     = exp(log_cre_sigma);\n  Type nidre_sigma   = exp(log_nidre_sigma);\n  Type gauss_sigma   = exp(log_gauss_sigma);\n\n\n  // Define objects for derived values\n  vector<Type> fe_i(num_i);                         // main effect X_ij %*% t(alpha_j)\n  vector<Type> epsilon_stz(num_s * num_t * num_z);  // Epsilon_stz unlisted into a vector for easier matrix multiplication\n  vector<Type> projepsilon_i(num_i);                // value of gmrf at data points\n  vector<Type> prob_i(num_i);                       // Logit estimated prob for each point i\n\n  // Latent field/Random effect contribution to likelihood.\n  // Possibilities of Kronecker include: S, ST, SZ, and STZ\n  if (num_t == 1 & num_z == 1)  {\n    printf(\"GP FOR SPACE  ONLY \\n\");\n    PARALLEL_REGION jnll += GMRF(Q_ss,false)(epsilon_stz);\n  } else if(num_t > 1 & num_z == 1) {\n    printf(\"GP FOR SPACE-TIME \\n\");\n    PARALLEL_REGION jnll += SEPARABLE(AR1(trho_trans),GMRF(Q_ss,false))(Epsilon_stz);\n  } else if (num_t == 1 & num_z > 1) {\n    printf(\"GP FOR SPACE-Z \\n\");\n    PARALLEL_REGION jnll += SEPARABLE(AR1(zrho_trans),GMRF(Q_ss,false))(Epsilon_stz);\n  } else if (num_t > 1 & num_z > 1) {\n    printf(\"GP FOR SPACE-TIME-Z \\n\");\n    PARALLEL_REGION jnll += SEPARABLE(AR1(zrho_trans),SEPARABLE(AR1(trho_trans),GMRF(Q_ss,false)))(Epsilon_stz);\n  }\n  \n  // nugget contribution to the likelihood\n  if(options.nugget == 1){\n    printf(\"Nugget \\n\");\n    for (int i = 0; i < num_i; i++){\n      // binomial models with sd_i, the additional variance gets put into the nugget.\n      // for gaussian models nuggets seem unidentifiable so, the sd_i is in the data likelihood\n      PARALLEL_REGION jnll -= dnorm(nug_i(i), Type(0.0), sqrt( pow(sd_i(i),2) + pow(nugget_sigma,2) ), true);\n    }\n  }\n\n  // country random intercept\n  if(options.country_random == 1){\n    printf(\"Country RE \\n\");\n    for(int i=0; i<cntry_re.size(); i++){\n      PARALLEL_REGION jnll -= dnorm(cntry_re(i), Type(0.0), cre_sigma, true);\n    }\n  }\n\n  // nid random intercept\n  if(options.NID_random == 1){\n    printf(\"NID RE \\n\");\n    for(int i=0; i<nid_re.size(); i++){\n      PARALLEL_REGION jnll -= dnorm(nid_re(i), Type(0.0), nidre_sigma, true);\n    }\n  }\n\n  // Transform GMRFs and make vector form\n  printf(\"Transform GMRF \\n\");\n  for(int s = 0; s < num_s; s++){\n    for(int t = 0; t < num_t; t++){\n      if(num_z == 1) {\n        epsilon_stz[(s + num_s * t )] = Epsilon_stz(s,t);\n      } else {\n        for(int z = 0; z < num_z; z++){\n          epsilon_stz[(s + num_s * t + num_s * num_t * z)] = Epsilon_stz(s,t,z);\n        }\n      }\n    }\n  }\n\n  // Project from mesh points to data points in order to eval likelihood at each data point\n  printf(\"Project Epsilon \\n\");\n  projepsilon_i = Aproj * epsilon_stz.matrix();\n\n  // evaluate fixed effects for alpha_j values\n  vector<Type> calpha_j = constrain_pars(alpha_j, fconstraints);\n  fe_i = X_ij * calpha_j.matrix();\n\n\n  // Return un-normalized density on request\n  if (flag == 0) return jnll;\n  \n  // Prior contribution to likelihood. Values are defaulted.\n  // Only run if options.use_priors==1\n  if(options.use_priors == 1) {\n    PARALLEL_REGION jnll -= eval_prior_matern(prior_matern, logtau, logkappa);\n    if(num_t > 1) {\n      // N(0,2.58^2) prior on log((1+rho)/(1-rho))\n      PARALLEL_REGION jnll -= dnorm(trho, Type(0.0), Type(2.58), true);\n    }\n    if(num_z > 1) {\n      // N(0,2.58^2) prior on log((1+rho)/(1-rho))\n      PARALLEL_REGION jnll -= dnorm(zrho, Type(0.0), Type(2.58), true);\n    }\n    for(int j = 0; j < alpha_j.size(); j++){\n      // N(0,3) prior for fixed effects.\n      PARALLEL_REGION jnll -= dnorm(alpha_j(j), Type(0.0), Type(3.0), true);\n    }\n    // if using nugget (option in 3rd index)\n    if(options.nugget == 1){\n      PARALLEL_REGION jnll -= eval_prior_sigma(prior_log_nugget_sigma, log_nugget_sigma);\n    }\n    // if using country (option in 4th index)\n    if(options.country_random == 1){\n      PARALLEL_REGION jnll -= eval_prior_sigma(prior_log_cre_sigma, log_cre_sigma);\n    }\n    // if using nid (option in 5th index)\n    if(options.NID_random == 1){\n      PARALLEL_REGION jnll -= eval_prior_sigma(prior_log_nidre_sigma, log_nidre_sigma);\n    }\n  }\n\n  // Likelihood contribution from each datapoint i\n  printf(\"Data likelihood \\n\");\n  for (int i = 0; i < num_i; i++){\n\n    // mean model\n    if(options.useGP==1){\n      prob_i(i) = fe_i(i) + projepsilon_i(i) + nug_i(i) + cntry_re(c_re_i(i)) + nid_re(nid_re_i(i));\n    } else {\n      prob_i(i) = fe_i(i) +  nug_i(i) + cntry_re(c_re_i(i)) + nid_re(nid_re_i(i));\n    }\n    \n    if(!isNA(y_i(i))){\n\n      if(lik_binomial_i(i) == 1){\n        PARALLEL_REGION jnll -= dbinom( y_i(i), n_i(i), invlogit_robust(prob_i(i)), true ) * w_i(i);\n      }\n      if(lik_gaussian_i(i) == 1){\n        // this includes any crosswalked sd (sd_i), other variance (gauss_sigma), and is scaled by sample size (n_i)\n        PARALLEL_REGION jnll -= dnorm( y_i(i), prob_i(i),  sqrt( (pow(sd_i(i),2) + (1/n_i(i) * pow(gauss_sigma,2)) ) ), true ) * w_i(i);\n      }\n\n    }\n  }\n\n  // Report estimates\n  if(options.adreport_off == 0){\n    ADREPORT(alpha_j);\n  }\n\n  return jnll;\n}\n", "meta": {"hexsha": "761e341197b4a80da70e8e21db26fc58c8946784", "size": 16875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "antibiotic_usage/mbg_central/mbg_tmb_model.cpp", "max_stars_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_stars_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-24T15:23:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:23:42.000Z", "max_issues_repo_path": "antibiotic_usage/mbg_central/mbg_tmb_model.cpp", "max_issues_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_issues_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "antibiotic_usage/mbg_central/mbg_tmb_model.cpp", "max_forks_repo_name": "NDM-GRAM/Antibiotic-consumption", "max_forks_repo_head_hexsha": "7b6c1c62823dbef23c7441de9fa225438d38ca1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-13T23:06:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-13T23:06:52.000Z", "avg_line_length": 38.9722863741, "max_line_length": 137, "alphanum_fraction": 0.6372148148, "num_tokens": 4967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5648755936336821}}
{"text": "//  (C) Copyright Nick Thompson 2018\n//  (C) Copyright Matt Borland 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#ifndef BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP\n#define BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP\n\n#include <boost/math/tools/config.hpp>\n#include <boost/math/tools/assert.hpp>\n#include <tuple>\n#include <iterator>\n#include <type_traits>\n#include <cmath>\n#include <algorithm>\n#include <valarray>\n#include <stdexcept>\n#include <functional>\n#include <vector>\n\n#ifdef BOOST_HAS_THREADS\n#include <future>\n#include <thread>\n#endif\n\nnamespace boost { namespace math { namespace statistics { namespace detail {\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType mean_sequential_impl(ForwardIterator first, ForwardIterator last)\n{\n    const std::size_t elements {static_cast<std::size_t>(std::distance(first, last))};\n    std::valarray<ReturnType> mu {0, 0, 0, 0};\n    std::valarray<ReturnType> temp {0, 0, 0, 0};\n    ReturnType i {1};\n    const ForwardIterator end {std::next(first, elements - (elements % 4))};\n    ForwardIterator it {first};\n\n    while(it != end)\n    {\n        const ReturnType inv {ReturnType(1) / i};\n        temp = {static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++)};\n        temp -= mu;\n        mu += (temp *= inv);\n        i += 1;\n    }\n\n    const ReturnType num1 {ReturnType(elements - (elements % 4))/ReturnType(4)};\n    const ReturnType num2 {num1 + ReturnType(elements % 4)};\n\n    while(it != last)\n    {\n        mu[3] += (*it-mu[3])/i;\n        i += 1;\n        ++it;\n    }\n\n    return (num1 * std::valarray<ReturnType>(mu[std::slice(0,3,1)]).sum() + num2 * mu[3]) / ReturnType(elements);\n}\n\n// Higham, Accuracy and Stability, equation 1.6a and 1.6b:\n// Calculates Mean, M2, and variance\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType variance_sequential_impl(ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    Real M = *first;\n    Real Q = 0;\n    Real k = 2;\n    Real M2 = 0;\n    std::size_t n = 1;\n\n    for(auto it = std::next(first); it != last; ++it)\n    {\n        Real tmp = (*it - M) / k;\n        Real delta_1 = *it - M;\n        Q += k*(k-1)*tmp*tmp;\n        M += tmp;\n        k += 1;\n        Real delta_2 = *it - M;\n        M2 += delta_1 * delta_2;\n        ++n;\n    }\n\n    return std::make_tuple(M, M2, Q/(k-1), Real(n));\n}\n\n// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType first_four_moments_sequential_impl(ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n    using Size = typename std::tuple_element<4, ReturnType>::type;\n\n    Real M1 = *first;\n    Real M2 = 0;\n    Real M3 = 0;\n    Real M4 = 0;\n    Size n = 2;\n    for (auto it = std::next(first); it != last; ++it)\n    {\n        Real delta21 = *it - M1;\n        Real tmp = delta21/n;\n        M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);\n        M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\n        M2 = M2 + tmp*(n-1)*delta21;\n        M1 = M1 + tmp;\n        n += 1;\n    }\n\n    return std::make_tuple(M1, M2, M3, M4, n-1);\n}\n\n#ifdef BOOST_HAS_THREADS\n\n// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics\n// EQN 3.1: https://www.osti.gov/servlets/purl/1426900\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType first_four_moments_parallel_impl(ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    const auto elements = std::distance(first, last);\n    const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();\n    unsigned num_threads = 2u;\n    \n    // Threading is faster for: 10 + 5.13e-3 N/j <= 5.13e-3N => N >= 10^4j/5.13(j-1).\n    const auto parallel_lower_bound = 10e4*max_concurrency/(5.13*(max_concurrency-1));\n    const auto parallel_upper_bound = 10e4*2/5.13; // j = 2\n\n    // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/\n    if(elements < parallel_lower_bound)\n    {\n        return detail::first_four_moments_sequential_impl<ReturnType>(first, last);\n    }\n    else if(elements >= parallel_upper_bound)\n    {\n        num_threads = max_concurrency;\n    }\n    else\n    {\n        for(unsigned i = 3; i < max_concurrency; ++i)\n        {\n            if(parallel_lower_bound < 10e4*i/(5.13*(i-1)))\n            {\n                num_threads = i;\n                break;\n            }\n        }\n    }\n\n    std::vector<std::future<ReturnType>> future_manager;\n    const auto elements_per_thread = std::ceil(static_cast<double>(elements) / num_threads);\n\n    auto it = first;\n    for(std::size_t i {}; i < num_threads - 1; ++i)\n    {\n        future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, elements_per_thread]() -> ReturnType\n        {\n            return first_four_moments_sequential_impl<ReturnType>(it, std::next(it, elements_per_thread));\n        }));\n        it = std::next(it, elements_per_thread);\n    }\n\n    future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, last]() -> ReturnType\n    {\n        return first_four_moments_sequential_impl<ReturnType>(it, last);\n    }));\n\n    auto temp = future_manager[0].get();\n    Real M1_a = std::get<0>(temp);\n    Real M2_a = std::get<1>(temp);\n    Real M3_a = std::get<2>(temp);\n    Real M4_a = std::get<3>(temp);\n    Real range_a = std::get<4>(temp);\n\n    for(std::size_t i = 1; i < future_manager.size(); ++i)\n    {\n        temp = future_manager[i].get();\n        Real M1_b = std::get<0>(temp);\n        Real M2_b = std::get<1>(temp);\n        Real M3_b = std::get<2>(temp);\n        Real M4_b = std::get<3>(temp);\n        Real range_b = std::get<4>(temp);\n\n        const Real n_ab = range_a + range_b;\n        const Real delta = M1_b - M1_a;\n        \n        M1_a = (range_a * M1_a + range_b * M1_b) / n_ab;\n        M2_a = M2_a + M2_b + delta * delta * (range_a * range_b / n_ab);\n        M3_a = M3_a + M3_b + (delta * delta * delta) * range_a * range_b * (range_a - range_b) / (n_ab * n_ab)    \n               + Real(3) * delta * (range_a * M2_b - range_b * M2_a) / n_ab;\n        M4_a = M4_a + M4_b + (delta * delta * delta * delta) * range_a * range_b * (range_a * range_a - range_a * range_b + range_b * range_b) / (n_ab * n_ab * n_ab)\n               + Real(6) * delta * delta * (range_a * range_a * M2_b + range_b * range_b * M2_a) / (n_ab * n_ab) \n               + Real(4) * delta * (range_a * M3_b - range_b * M3_a) / n_ab;\n        range_a = n_ab;\n    }\n\n    return std::make_tuple(M1_a, M2_a, M3_a, M4_a, elements);\n}\n\n#endif // BOOST_HAS_THREADS\n\n// Follows equation 1.5 of:\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType skewness_sequential_impl(ForwardIterator first, ForwardIterator last)\n{\n    using std::sqrt;\n    BOOST_MATH_ASSERT_MSG(first != last, \"At least one sample is required to compute skewness.\");\n    \n    ReturnType M1 = *first;\n    ReturnType M2 = 0;\n    ReturnType M3 = 0;\n    ReturnType n = 2;\n        \n    for (auto it = std::next(first); it != last; ++it)    \n    {\n        ReturnType delta21 = *it - M1;\n        ReturnType tmp = delta21/n;\n        M3 += tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);\n        M2 += tmp*(n-1)*delta21;\n        M1 += tmp;\n        n += 1;\n    }\n   \n    ReturnType var = M2/(n-1);\n    \n    if (var == 0)\n    {\n        // The limit is technically undefined, but the interpretation here is clear:\n        // A constant dataset has no skewness.\n        return ReturnType(0);\n    }\n    \n    ReturnType skew = M3/(M2*sqrt(var));\n    return skew;\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType gini_coefficient_sequential_impl(ForwardIterator first, ForwardIterator last)\n{\n    ReturnType i = 1;\n    ReturnType num = 0;\n    ReturnType denom = 0;\n\n    for(auto it = first; it != last; ++it)\n    {\n        num += *it*i;\n        denom += *it;\n        ++i;\n    }\n\n    // If the l1 norm is zero, all elements are zero, so every element is the same.\n    if(denom == 0)\n    {\n        return ReturnType(0);\n    }\n    else\n    {\n        return ((2*num)/denom - i)/(i-1);\n    }\n}\n\ntemplate<typename ReturnType, typename ForwardIterator>\nReturnType gini_range_fraction(ForwardIterator first, ForwardIterator last, std::size_t starting_index)\n{\n    using Real = typename std::tuple_element<0, ReturnType>::type;\n\n    std::size_t i = starting_index + 1;\n    Real num = 0;\n    Real denom = 0;\n\n    for(auto it = first; it != last; ++it)\n    {\n        num += *it*i;\n        denom += *it;\n        ++i;\n    }\n\n    return std::make_tuple(num, denom, i);\n}\n\n#ifdef BOOST_HAS_THREADS\n\ntemplate<typename ReturnType, typename ExecutionPolicy, typename ForwardIterator>\nReturnType gini_coefficient_parallel_impl(ExecutionPolicy&&, ForwardIterator first, ForwardIterator last)\n{\n    using range_tuple = std::tuple<ReturnType, ReturnType, std::size_t>;\n    \n    const auto elements = std::distance(first, last);\n    const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();\n    unsigned num_threads = 2u;\n    \n    // Threading is faster for: 10 + 10.12e-3 N/j <= 10.12e-3N => N >= 10^4j/10.12(j-1).\n    const auto parallel_lower_bound = 10e4*max_concurrency/(10.12*(max_concurrency-1));\n    const auto parallel_upper_bound = 10e4*2/10.12; // j = 2\n\n    // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/\n    if(elements < parallel_lower_bound)\n    {\n        return gini_coefficient_sequential_impl<ReturnType>(first, last);\n    }\n    else if(elements >= parallel_upper_bound)\n    {\n        num_threads = max_concurrency;\n    }\n    else\n    {\n        for(unsigned i = 3; i < max_concurrency; ++i)\n        {\n            if(parallel_lower_bound < 10e4*i/(10.12*(i-1)))\n            {\n                num_threads = i;\n                break;\n            }\n        }\n    }\n\n    std::vector<std::future<range_tuple>> future_manager;\n    const auto elements_per_thread = std::ceil(static_cast<double>(elements) / num_threads);\n\n    auto it = first;\n    for(std::size_t i {}; i < num_threads - 1; ++i)\n    {\n        future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, elements_per_thread, i]() -> range_tuple\n        {\n            return gini_range_fraction<range_tuple>(it, std::next(it, elements_per_thread), i*elements_per_thread);\n        }));\n        it = std::next(it, elements_per_thread);\n    }\n\n    future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, last, num_threads, elements_per_thread]() -> range_tuple\n    {\n        return gini_range_fraction<range_tuple>(it, last, (num_threads - 1)*elements_per_thread);\n    }));\n\n    ReturnType num = 0;\n    ReturnType denom = 0;\n\n    for(std::size_t i = 0; i < future_manager.size(); ++i)\n    {\n        auto temp = future_manager[i].get();\n        num += std::get<0>(temp);\n        denom += std::get<1>(temp);\n    }\n\n    // If the l1 norm is zero, all elements are zero, so every element is the same.\n    if(denom == 0)\n    {\n        return ReturnType(0);\n    }\n    else\n    {\n        return ((2*num)/denom - elements)/(elements-1);\n    }\n}\n\n#endif // BOOST_HAS_THREADS\n\ntemplate<typename ForwardIterator, typename OutputIterator>\nOutputIterator mode_impl(ForwardIterator first, ForwardIterator last, OutputIterator output)\n{\n    using Z = typename std::iterator_traits<ForwardIterator>::value_type;\n    using Size = typename std::iterator_traits<ForwardIterator>::difference_type;\n\n    std::vector<Z> modes {};\n    modes.reserve(16);\n    Size max_counter {0};\n\n    while(first != last)\n    {\n        Size current_count {0};\n        ForwardIterator end_it {first};\n        while(end_it != last && *end_it == *first)\n        {\n            ++current_count;\n            ++end_it;\n        }\n\n        if(current_count > max_counter)\n        {\n            modes.resize(1);\n            modes[0] = *first;\n            max_counter = current_count;\n        }\n\n        else if(current_count == max_counter)\n        {\n            modes.emplace_back(*first);\n        }\n\n        first = end_it;\n    }\n\n    return std::move(modes.begin(), modes.end(), output);\n}\n}}}}\n\n#endif // BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP\n", "meta": {"hexsha": "7388509658d3cb522d32177dcf08572a02215daa", "size": 12778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/statistics/detail/single_pass.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/statistics/detail/single_pass.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/statistics/detail/single_pass.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": 31.7860696517, "max_line_length": 165, "alphanum_fraction": 0.6205196431, "num_tokens": 3528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.564875588789225}}
{"text": "// Standard\n#include <iostream> // cout, endl\n#include <cmath> // exp, abs\n#include <vector>\n// Thirdparties\n#include <Eigen/Dense> // Eigen\n// Lib\n#include \"s0s/euler.h\" // s0s\n// Simple\n#include \"func.h\" // Func\n\nconstexpr unsigned int DIM = 10;\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n\nusing TypeFunction = Func<TypeVector>;\n\nint main () { \n    // Parameters\n    TypeScalar dt = 1e-4;\n    TypeScalar tMax = 1e0;\n    std::size_t nt = tMax / dt;\n    TypeFunction f;\n    s0s::SolverEuler<TypeVector, TypeView> solver;\n    // Init\n    TypeVector x = TypeVector::Constant(1.0);\n    TypeScalar t = 0.0;\n    // computation\n    for(unsigned int i = 0; i < nt; i++) {\n        solver(f, x.data(), x.size(), t, dt);\n        t += dt;\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"Solver solved exp(\" << 0.0 << \" -> \" << tMax << \") = \" << std::endl;\n    std::cout << \"\\n\";\n    std::cout << x.transpose() << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "3a5827d4e9ecc9c88a4bf87275ded24bdba2d559", "size": 1074, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/euler/main.cpp", "max_stars_repo_name": "C0PEP0D/s0s", "max_stars_repo_head_hexsha": "7045d4d77a4a53a2672873219914bb176fce4367", "max_stars_repo_licenses": ["MIT"], "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/euler/main.cpp", "max_issues_repo_name": "C0PEP0D/s0s", "max_issues_repo_head_hexsha": "7045d4d77a4a53a2672873219914bb176fce4367", "max_issues_repo_licenses": ["MIT"], "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/euler/main.cpp", "max_forks_repo_name": "C0PEP0D/s0s", "max_forks_repo_head_hexsha": "7045d4d77a4a53a2672873219914bb176fce4367", "max_forks_repo_licenses": ["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.976744186, "max_line_length": 86, "alphanum_fraction": 0.5726256983, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5647695480357047}}
{"text": "\n//System includes\n#include <iostream>\n#include <chrono>\n\n//Eigen includes\n#include <Eigen/Sparse>\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Interpolation_traits_2.h>\n#include <CGAL/natural_neighbor_coordinates_2.h>\n#include <CGAL/interpolation_functions.h>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Delaunay_triangulation_2<K> Delaunay_triangulation;\ntypedef CGAL::Interpolation_traits_2<K> Traits;\ntypedef K::FT Coord_type;\ntypedef K::Point_2 Point;\n\n\nint main(){\n\n    typedef Eigen::Spline<double, 1, 1> spline_type;    \n    typedef typename spline_type::PointType point_type;\n    typedef typename spline_type::ControlPointVectorType cpv_type;\n\n    const Eigen::VectorXd xvals = (Eigen::VectorXd(9) << 0, 0, 0, 1, 1, 1, 2, 2, 2).finished();\n    const Eigen::VectorXd yvals = (Eigen::VectorXd(9) << 0, 1, 2, 0, 1, 2, 0, 1, 2).finished();\n    cpv_type nodes(2,9);\n    nodes.row(0)=xvals;\n    nodes.row(1)=yvals;\n\n    const Eigen::VectorXd zvals = xvals.array().square()+yvals.array().square(); \n\n    const spline_type spline = Eigen::SplineFitting<spline_type>::Interpolate( zvals.transpose(), 1, xvals.transpose());\n\n    Delaunay_triangulation T;\n \n    std::map<Point, Coord_type, K::Less_xy_2> function_values;\n \n    typedef CGAL::Data_access< std::map<Point, Coord_type, K::Less_xy_2 > > Value_access;\n \n    Coord_type a(0.25), bx(1.3), by(-0.7);\n \n    for (int y=0 ; y<3 ; y++)\n\tfor (int x=0 ; x<3 ; x++){\n\t    K::Point_2 p(x,y);\n\t    T.insert(p);\n\t    function_values.insert(std::make_pair(p,a + bx* x+ by*y));\n\t}\n \n    //coordinate computation\n    K::Point_2 p(1.3,0.34);\n \n    std::vector< std::pair< Point, Coord_type > > coords;\n \n    Coord_type norm = CGAL::natural_neighbor_coordinates_2 (T, p,std::back_inserter(coords)).second;\n    Coord_type res = CGAL::linear_interpolation(coords.begin(), coords.end(), norm, Value_access(function_values));\n \n    std::cout << \" Tested interpolation on \" << p << \" interpolation: \" << res << \" exact: \" << a + bx* p.x()+ by* p.y()<< std::endl;\n    std::cout << \"done\" << std::endl;\n \n \n     return 0; \n}\n", "meta": {"hexsha": "24b2a6a0076010df8f1a812ae33819eb2def77b3", "size": 2231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/spline_test.cpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "test/spline_test.cpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/spline_test.cpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8714285714, "max_line_length": 133, "alphanum_fraction": 0.6844464366, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5647695480357047}}
{"text": "#include <state_estimation/filters/ukf.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nUKF::UKF(system_models::NonlinearSystemModel* system_model)\n    : FilterBase::FilterBase(system_model) {\n    initializeSigmaPointParameters();\n}\n\nUKF::UKF(system_models::NonlinearSystemModel* system_model, const Eigen::VectorXd& x,\n         const Eigen::MatrixXd& cov, double timestamp)\n    : FilterBase::FilterBase(system_model, x, cov, timestamp) {\n    initializeSigmaPointParameters();\n}\n\nvoid UKF::setSigmaPointParameters(double alpha, double kappa, double beta) {\n    uint32_t n = system_model_->g().size();\n    num_sigma_pts_ = 2 * system_model_->stateSize() + 1;\n\n    // Compute our lambda value\n    lambda_ = pow(alpha, 2) * (n + kappa) - n;\n\n    // Compute our weight vectors\n    w_mean_.resize(num_sigma_pts_);\n    w_cov_.resize(num_sigma_pts_);\n\n    const double init_w = 0.5 / (n + lambda_);\n    w_mean_ = Eigen::VectorXd::Constant(num_sigma_pts_, init_w);\n    w_cov_ = Eigen::VectorXd::Constant(num_sigma_pts_, init_w);\n\n    w_mean_(0) = lambda_ / (n + lambda_);\n    w_cov_(0) = w_mean_(0) + 1 - pow(alpha, 2) + beta;\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"UKF sigma point initialization\" << std::endl\n              << \"alpha=\" << alpha << std::endl\n              << \"kappa=\" << kappa << std::endl\n              << \"lambda=\" << lambda_ << std::endl\n              << \"Initialized mean weights to [\" << w_mean_.transpose() << \"]\" << std::endl\n              << \"Initialized covariance weights to [\" << w_cov_.transpose() << \"]\" << std::endl;\n#endif\n}\n\nvoid UKF::initializeSigmaPointParameters() {\n    setSigmaPointParameters(0.001, 0, 2);\n}\n\nvoid UKF::myPredict(const Eigen::VectorXd& u, double dt) {\n    // Generate the sigma points and run them through the system model\n    const Eigen::MatrixXd sigma_offset =\n        ((system_model_->stateSize() + lambda_) * filter_state_.covariance).llt().matrixL();\n    Eigen::MatrixXd sigma_pts(system_model_->stateSize(), num_sigma_pts_);\n\n    system_model_->update(filter_state_.x, u, dt);\n    Eigen::VectorXd x = system_model_->g();\n    sigma_pts.col(0) = system_model_->g();\n\n    for (uint32_t i = 0; i < system_model_->stateSize(); ++i) {\n        const uint32_t i_high = i + 1;\n        const uint32_t i_low = i + 1 + system_model_->stateSize();\n\n        const Eigen::VectorXd x_high =\n            system_model_->addVectors(filter_state_.x, sigma_offset.col(i));\n        system_model_->update(x_high, u, dt);\n        sigma_pts.col(i_high) = system_model_->g();\n\n        const Eigen::VectorXd x_low =\n            system_model_->subtractVectors(filter_state_.x, sigma_offset.col(i));\n        system_model_->update(x_low, u, dt);\n        sigma_pts.col(i_low) = system_model_->g();\n    }\n\n    // Compute the weighted mean\n    filter_state_.x = system_model_->weightedSum(w_mean_, sigma_pts);\n\n    // Compute the weighted covariance\n    filter_state_.covariance =\n        system_model_->P() * system_model_->Rp() * system_model_->P().transpose() +\n        system_model_->V() * system_model_->Rc() * system_model_->V().transpose();\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dx =\n            system_model_->subtractVectors(sigma_pts.col(i), filter_state_.x);\n        filter_state_.covariance += w_cov_(i) * dx * dx.transpose();\n    }\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"UKF predicition update:\" << std::endl\n              << \"Sigma offsets=\" << std::endl\n              << printMatrix(sigma_offset) << std::endl\n              << \"Sigma points=\" << std::endl\n              << printMatrix(sigma_pts) << 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 UKF::myCorrect(const Eigen::VectorXd& z, measurement_models::NonlinearMeasurementModel* model,\n                    double dt) {\n    // Generate the sigma points and run them through the measurement model\n    Eigen::MatrixXd sigma_offset =\n        ((system_model_->stateSize() + lambda_) * filter_state_.covariance).llt().matrixL();\n    Eigen::MatrixXd sigma_pts(system_model_->stateSize(), num_sigma_pts_);\n    Eigen::MatrixXd observed_sigma_pts(model->measurementSize(), num_sigma_pts_);\n\n    sigma_pts.col(0) = filter_state_.x;\n    model->update(filter_state_.x, dt);\n    observed_sigma_pts.col(0) = model->h();\n\n    for (uint32_t i = 0; i < system_model_->stateSize(); ++i) {\n        const uint32_t i_high = i + 1;\n        const uint32_t i_low = i + 1 + system_model_->stateSize();\n\n        sigma_pts.col(i_high) = system_model_->addVectors(filter_state_.x, sigma_offset.col(i));\n        model->update(sigma_pts.col(i_high), dt);\n        observed_sigma_pts.col(i_high) = model->h();\n\n        sigma_pts.col(i_low) = system_model_->subtractVectors(filter_state_.x, sigma_offset.col(i));\n        model->update(sigma_pts.col(i_low), dt);\n        observed_sigma_pts.col(i_low) = model->h();\n    }\n\n    // Compute the weighted mean for the predicted measurement\n    Eigen::VectorXd z_pred = model->weightedSum(w_mean_, observed_sigma_pts);\n\n    // Compute the gain\n    Eigen::MatrixXd S = model->covariance();\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dz = model->subtractVectors(observed_sigma_pts.col(i), z_pred);\n        S += w_cov_(i) * dz * dz.transpose();\n    }\n\n    Eigen::MatrixXd cross_covariance =\n        Eigen::MatrixXd::Zero(model->stateSize(), model->measurementSize());\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dx =\n            system_model_->subtractVectors(sigma_pts.col(i), sigma_pts.col(0));\n        const Eigen::VectorXd dz = model->subtractVectors(observed_sigma_pts.col(i), z_pred);\n\n        cross_covariance += w_cov_(i) * dx * dz.transpose();\n    }\n\n    const Eigen::MatrixXd K = cross_covariance * S.inverse();\n\n    // Perform the mean and covariance updates\n    const Eigen::VectorXd dx = K * model->subtractVectors(z, z_pred);\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx);\n    filter_state_.covariance -= K * S * K.transpose();\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"UKF measurement update:\" << std::endl\n              << \"Sigma offsets=\" << std::endl\n              << printMatrix(sigma_offset) << std::endl\n              << \"Sigma points=\" << std::endl\n              << printMatrix(sigma_pts) << std::endl\n              << \"Observed sigma points=\" << std::endl\n              << printMatrix(observed_sigma_pts) << std::endl\n              << \"z_pred=\" << printMatrix(z_pred) << std::endl\n              << \"Q=\" << std::endl\n              << printMatrix(model->covariance()) << std::endl\n              << \"S=\" << std::endl\n              << printMatrix(S) << std::endl\n              << \"Cross Covariance=\" << std::endl\n              << printMatrix(cross_covariance) << std::endl\n              << \"K=\" << std::endl\n              << printMatrix(K) << std::endl\n              << \"x=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\n}  // namespace state_estimation\n", "meta": {"hexsha": "72fb485b3422dc78728d5bb46f74349200bb2942", "size": 7471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/ukf.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/ukf.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/ukf.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": 41.5055555556, "max_line_length": 100, "alphanum_fraction": 0.6218712354, "num_tokens": 1870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695259997887}}
{"text": "#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include \"cmdline.h\"\n#include \"vcf.h\"\n\n\nusing std::size_t;\n\n\n// TODO\n// Chi-squared test for independance\n// void calc_chisq(const std::vector<allele_t> &x, const std::vector<allele_t> &y);\n\n\nnamespace {\n\n\nstruct Parameter\n{\n    std::string vcf;\n    std::string out;\n    std::string loc;\n    double rsq = 0.5;\n    int maxdist = 500000;\n} par ;\n\n\n// LD (D')  -  Lewontin, R.C. (1964). Genetics 49(1), 49-67.\n// LD (r^2) -  Hill, W.G., and Robertson, A. (1968). Theor Appl Genet 38(6), 226-231.\n\nvoid calc_dprime_rsq_kernel(double pa, double pb, double pab, double &dprime, double &rsq)\n{\n    auto D = pab - pa*pb;\n    auto Dmax = D > 0 ? std::min(pa*(1-pb),(1-pa)*pb) : std::min(pa*pb,(1-pa)*(1-pb));\n    dprime = std::fabs(D) / Dmax;  // fabs is required for multi-allelic D'\n    rsq = D*D / (pa * (1-pa) * pb * (1-pb));\n}\n\nvoid calc_dprime_rsq_hap2(const std::vector<allele_t> &x, const std::vector<allele_t> &y, double &dprime, double &rsq)\n{\n    static const allele_t a = 1, b = 1;\n\n    auto n = x.size();\n    int nt = 0, na = 0, nb = 0, nab = 0;\n\n    for (size_t i = 0; i < n; ++i) {\n        if (x[i] && y[i]) {\n            ++nt;\n            if (x[i] == a) {\n                ++na;\n                if (y[i] == b)\n                    ++nab;\n            }\n            if (y[i] == b)\n                ++nb;\n        }\n    }\n\n    dprime = rsq = std::numeric_limits<double>::quiet_NaN();\n\n    if (nt == 0)\n        return;\n\n    double fnt = nt;\n\n    calc_dprime_rsq_kernel(na/fnt, nb/fnt, nab/fnt, dprime, rsq);\n}\n\nvoid calc_dprime_rsq_hap(const std::vector<allele_t> &x, const std::vector<allele_t> &y, double &dprime, double &rsq)\n{\n    auto n = x.size();\n\n    auto xmax = * std::max_element(x.begin(), x.end());\n    auto ymax = * std::max_element(y.begin(), y.end());\n\n    dprime = rsq = std::numeric_limits<double>::quiet_NaN();\n\n    if (xmax < 2 || ymax < 2)\n        return;\n\n    if (xmax == 2 && ymax == 2) {\n        calc_dprime_rsq_hap2(x, y, dprime, rsq);\n        return;\n    }\n\n    std::vector<size_t> idx;\n    idx.reserve(n);\n    for (size_t i = 0; i < n; ++i) {\n        if (x[i] && y[i])\n            idx.push_back(i);\n    }\n\n    if ( idx.empty() )\n        return;\n\n    dprime = rsq = 0.0;\n\n    for (allele_t a = 1; a <= xmax; ++a) {\n        for (allele_t b = 1; b <= ymax; ++b) {\n            int na = 0, nb = 0, nab = 0;\n\n            for (auto i : idx) {\n                if (x[i] == a) {\n                    ++na;\n                    if (y[i] == b)\n                        ++nab;\n                }\n                if (y[i] == b)\n                    ++nb;\n            }\n\n            if (na == 0 || nb == 0)\n                continue;\n\n            double nt = idx.size();\n            double pa = na / nt;\n            double pb = nb / nt;\n            double pab = nab / nt;\n\n            double t1 = 0.0, t2 = 0.0;\n            calc_dprime_rsq_kernel(pa, pb, pab, t1, t2);\n\n            pab = pa * pb;\n            dprime += pab * t1;\n            rsq += pab * t2;\n        }\n    }\n}\n\n// Estimates haplotype frequencies via the EM algorithm\n// AB, Ab, aB, ab, AaBb\nvoid calc_hap_prob_EM(int n11, int n12, int n21, int n22, int ndh, double &p11, double &p12, double &p21, double &p22)\n{\n    static const int maxit = 1000;\n    static const double tol = 1e-10;\n\n    double n = n11 + n12 + n21 + n22 + ndh * 2;\n    p11 = n11 / n;\n    p12 = n12 / n;\n    p21 = n21 / n;\n    p22 = n22 / n;\n\n    if (ndh == 0)\n        return;\n\n    auto cp11 = p11;\n    auto cp12 = p12;\n    auto cp21 = p21;\n    auto cp22 = p22;\n\n    auto h = ndh / n;\n    auto x = h / 2;\n    auto y = h - x;\n\n    for (int i = 0; i < maxit; ++i) {\n        p11 = cp11 + x;\n        p12 = cp12 + y;\n        p21 = cp21 + y;\n        p22 = cp22 + x;\n        auto z = h * p11 * p22 / (p11 * p22 + p12 * p21);\n        if (std::fabs(x - z) < tol)\n            break;\n        x = z;\n        y = h - x;\n    }\n}\n\nvoid calc_dprime_rsq_dip2(const std::vector<allele_t> &x, const std::vector<allele_t> &y, double &dprime, double &rsq)\n{\n    auto n = x.size() / 2;\n\n    int nt = 0;\n    int f[3][3] = { { 0,0,0 }, { 0,0,0 }, { 0,0,0 } };\n\n    for (size_t i = 0; i < n; ++i) {\n        auto j = i*2, k = i*2+1;\n        if (x[j] && x[k] && y[j] && y[k]) {\n            auto a = x[j] + x[k] - 2;\n            auto b = y[j] + y[k] - 2;\n            ++f[a][b];\n            ++nt;\n        }\n    }\n\n    dprime = rsq = std::numeric_limits<double>::quiet_NaN();\n\n    if (nt == 0)\n        return;\n\n    int n11 = f[0][0] * 2 + f[0][1] + f[1][0];\n    int n12 = f[0][2] * 2 + f[0][1] + f[1][2];\n    int n21 = f[2][0] * 2 + f[1][0] + f[2][1];\n    int n22 = f[2][2] * 2 + f[2][1] + f[1][2];\n    int ndh = f[1][1];\n\n    double p11 = 0.0, p12 = 0.0, p21 = 0.0, p22 = 0.0;\n    calc_hap_prob_EM(n11, n12, n21, n22, ndh, p11, p12, p21, p22);\n\n    calc_dprime_rsq_kernel(p11 + p12, p11 + p21, p11, dprime, rsq);\n}\n\n// presuming that gametic phase is known\nvoid calc_dprime_rsq_dip(const std::vector<allele_t> &x, const std::vector<allele_t> &y, double &dprime, double &rsq)\n{\n    auto n = x.size() / 2;\n\n    auto xmax = * std::max_element(x.begin(), x.end());\n    auto ymax = * std::max_element(y.begin(), y.end());\n\n    dprime = rsq = std::numeric_limits<double>::quiet_NaN();\n\n    if (xmax < 2 || ymax < 2)\n        return;\n\n    if (xmax == 2 && ymax == 2) {\n        calc_dprime_rsq_dip2(x, y, dprime, rsq);\n        return;\n    }\n\n    std::vector<size_t> idx;\n    idx.reserve(n);\n    for (size_t i = 0; i < n; ++i) {\n        auto j = i*2, k = i*2+1;\n        if (x[j] && x[k] && y[j] && y[k])\n            idx.push_back(i);\n    }\n\n    if ( idx.empty() )\n        return;\n\n    dprime = rsq = 0.0;\n\n    for (allele_t a = 1; a <= xmax; ++a) {\n        for (allele_t b = 1; b <= ymax; ++b) {\n            int na = 0, nb = 0, nab = 0;\n\n            for (auto i : idx) {\n                auto j = i*2, k = i*2+1;\n                if (x[j] == a) {\n                    ++na;\n                    if (y[j] == b)\n                        ++nab;\n                }\n\n                if (x[k] == a) {\n                    ++na;\n                    if (y[k] == b)\n                        ++nab;\n                }\n\n                if (y[j] == b)\n                    ++nb;\n\n                if (y[k] == b)\n                    ++nb;\n            }\n\n            if (na == 0 || nb == 0)\n                continue;\n\n            double nt = idx.size() * 2;\n            auto pa = na / nt;\n            auto pb = nb / nt;\n            auto pab = nab / nt;\n\n            double t1 = 0.0, t2 = 0.0;\n            calc_dprime_rsq_kernel(pa, pb, pab, t1, t2);\n\n            pab = pa * pb;\n            dprime += pab * t1;\n            rsq += pab * t2;\n        }\n    }\n}\n\nstd::vector<std::string> read_string_list(const std::string &filename)\n{\n    std::vector<std::string> vs;\n\n    std::ifstream ifs(filename);\n\n    if ( ! ifs )\n        std::cerr << \"ERROR: can't open file for reading: \" << filename << \"\\n\";\n    else\n        std::copy(std::istream_iterator<std::string>(ifs), std::istream_iterator<std::string>(),\n                  std::back_inserter(vs));\n\n    return vs;\n}\n\nint ldstat_list(const Genotype &gt)\n{\n    auto loc = read_string_list(par.loc);\n\n    std::sort(loc.begin(), loc.end());\n\n    std::ofstream ofs(par.out + \".sub\");\n    if ( ! ofs ) {\n        std::cerr << \"ERROR: can't open file: \" << par.out << \".list\\n\";\n        return 1;\n    }\n\n    ofs << \"Locus1\\tChromosome1\\tPosition1\\tLocus2\\tChromosome2\\tPosition2\\tDPrime\\tRSquare\\n\";\n\n    auto m = gt.loc.size();\n\n    for (size_t i = 0; i < m; ++i) {\n        if ( ! std::binary_search(loc.begin(), loc.end(), gt.loc[i]) )\n            continue;\n\n        std::cerr << \"INFO: locus \" << gt.loc[i] << \"\\n\";\n\n        for (size_t j = 0; j < m; ++j) {\n            if (gt.loc[j] == gt.loc[i])\n                continue;\n\n            auto n1 = gt.allele[i].size();\n            auto n2 = gt.allele[j].size();\n\n            if (n1 < 2 || n2 < 2)\n                continue;\n\n            auto dprime = std::numeric_limits<double>::quiet_NaN();\n            auto rsq = std::numeric_limits<double>::quiet_NaN();\n\n            if (n1 == 2 && n2 == 2) {\n                if (gt.ploidy == 1)\n                    calc_dprime_rsq_hap2(gt.dat[i], gt.dat[j], dprime, rsq);\n                else\n                    calc_dprime_rsq_dip2(gt.dat[i], gt.dat[j], dprime, rsq);\n            }\n            else {\n                if (gt.ploidy == 1)\n                    calc_dprime_rsq_hap(gt.dat[i], gt.dat[j], dprime, rsq);\n                else\n                    calc_dprime_rsq_dip(gt.dat[i], gt.dat[j], dprime, rsq);\n            }\n\n            if ( ! std::isfinite(dprime) || ! std::isfinite(rsq) )\n                continue;\n\n            if (rsq < par.rsq)\n                continue;\n\n            ofs << gt.loc[i] << \"\\t\" << gt.chr[i] << \"\\t\" << gt.pos[i] << \"\\t\"\n                << gt.loc[j] << \"\\t\" << gt.chr[j] << \"\\t\" << gt.pos[j] << \"\\t\"\n                << dprime << \"\\t\" << rsq << \"\\n\";\n        }\n    }\n\n    return 0;\n}\n\n\n} // namespace\n\n\nint ldstat(int argc, char *argv[])\n{\n    std::cerr << \"LDSTAT (Built on \" __DATE__ \" \" __TIME__ \")\\n\";\n\n    CmdLine cmd;\n\n    cmd.add(\"--vcf\", \"VCF file\", \"\");\n    cmd.add(\"--loc\", \"locus list file\", \"\");\n    cmd.add(\"--loc-min-r2\", \"minimum LD (r2) threshold for locus list\", \"0.5\");\n    cmd.add(\"--out\", \"output file\", \"ldstat.out\");\n    cmd.add(\"--maxdist\", \"maximum inter-variant distance\", \"500000\");\n\n    cmd.parse(argc, argv);\n\n    if (argc < 2) {\n        cmd.show();\n        return 1;\n    }\n\n    par.vcf = cmd.get(\"--vcf\");\n    par.loc = cmd.get(\"--loc\");\n    par.out = cmd.get(\"--out\");\n    par.rsq = std::stod(cmd.get(\"--loc-min-r2\"));\n    par.maxdist = std::stoi(cmd.get(\"--maxdist\"));\n\n    Genotype gt;\n\n    std::cerr << \"INFO: reading genotype file...\\n\";\n    if (read_vcf(par.vcf, gt) != 0)\n        return 2;\n    std::cerr << \"INFO: \" << gt.ind.size() << \" individuals, \" << gt.loc.size() << \" loci\\n\";\n\n    if ( ! par.loc.empty() )\n        return ldstat_list(gt);\n\n    std::ofstream ofs1(par.out + \".all\");\n    if ( ! ofs1 ) {\n        std::cerr << \"ERROR: can't open file: \" << par.out << \".all\\n\";\n        return 1;\n    }\n\n    ofs1 << \"Chromosome\\tLocus1\\tPosition1\\tLocus2\\tPosition2\\tDistance\\tDPrime\\tRSquare\\n\";\n\n    int n = par.maxdist / 1000;\n    using namespace boost::accumulators;\n    std::vector< accumulator_set<double, stats<tag::count, tag::mean> > > acc1(n), acc2(n);\n\n    auto m = gt.loc.size();\n\n    for (size_t i = 0; i < m; ++i) {\n        for (size_t j = i + 1; j < m; ++j) {\n            if (gt.chr[j] != gt.chr[i])\n                continue;\n\n            auto dist = std::abs(gt.pos[j] - gt.pos[i]);\n            if (dist > par.maxdist)\n                continue;\n\n            auto n1 = gt.allele[i].size();\n            auto n2 = gt.allele[j].size();\n\n            if (n1 < 2 || n2 < 2)\n                continue;\n\n            auto dprime = std::numeric_limits<double>::quiet_NaN();\n            auto rsq = std::numeric_limits<double>::quiet_NaN();\n\n            if (n1 == 2 && n2 == 2) {\n                if (gt.ploidy == 1)\n                    calc_dprime_rsq_hap2(gt.dat[i], gt.dat[j], dprime, rsq);\n                else\n                    calc_dprime_rsq_dip2(gt.dat[i], gt.dat[j], dprime, rsq);\n            }\n            else {\n                if (gt.ploidy == 1)\n                    calc_dprime_rsq_hap(gt.dat[i], gt.dat[j], dprime, rsq);\n                else\n                    calc_dprime_rsq_dip(gt.dat[i], gt.dat[j], dprime, rsq);\n            }\n\n            if ( ! std::isfinite(dprime) || ! std::isfinite(rsq) )\n                continue;\n\n            int k = dist / 1000;\n            if (dist % 1000 == 0)\n                --k;\n\n            acc1[k](dprime);\n            acc2[k](rsq);\n\n            ofs1 << gt.chr[i] << \"\\t\"\n                 << gt.loc[i] << \"\\t\" << gt.pos[i] << \"\\t\"\n                 << gt.loc[j] << \"\\t\" << gt.pos[j] << \"\\t\"\n                 << dist << \"\\t\" << dprime << \"\\t\" << rsq << \"\\n\";\n        }\n    }\n\n    std::ofstream ofs2(par.out + \".sum\");\n    if ( ! ofs2 ) {\n        std::cerr << \"ERROR: can't open file: \" << par.out << \".sum\\n\";\n        return 1;\n    }\n\n    ofs2 << \"Group\\tCount\\tDPrime\\tRSquare\\n\";\n\n    for (int i = 0; i < n; ++i) {\n        auto c = count(acc1[i]);\n        ofs2 << (i + 1) * 1000 << \"\\t\" << c << \"\\t\";\n        if (c != 0)\n            ofs2 << mean(acc1[i]) << \"\\t\" << mean(acc2[i]) << \"\\n\";\n        else\n            ofs2 << \"NA\\tNA\\n\";\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "1b59f8fc135bbbeb15892432c36a7b123d554c60", "size": 12633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ldstat.cpp", "max_stars_repo_name": "njau-sri/ldstat", "max_stars_repo_head_hexsha": "aef6c48123bad0077c1836c650ad3e52e4ab08d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T06:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T06:29:18.000Z", "max_issues_repo_path": "ldstat.cpp", "max_issues_repo_name": "njau-sri/ldstat", "max_issues_repo_head_hexsha": "aef6c48123bad0077c1836c650ad3e52e4ab08d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ldstat.cpp", "max_forks_repo_name": "njau-sri/ldstat", "max_forks_repo_head_hexsha": "aef6c48123bad0077c1836c650ad3e52e4ab08d9", "max_forks_repo_licenses": ["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.31875, "max_line_length": 118, "alphanum_fraction": 0.450565978, "num_tokens": 4042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.857768094082276, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5647695188178842}}
{"text": "/*\n * StokesM2L.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 <chrono>\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n#define PI314 3.1415926535897932384626433\n\nnamespace Stokes3D3D {\n\ninline double ERFC(double x) { return std::erfc(x); }\ninline double ERF(double x) { return std::erf(x); }\n\n/*\n * def AEW(xi,rvec):\n r=np.sqrt(rvec.dot(rvec))\n A = 2*(xi*np.exp(-(xi**2)*(r**2))/(np.sqrt(np.pi)*r**2)+ss.erfc(xi*r)/(2*r**3))\n *(r*r*np.identity(3)+np.outer(rvec,rvec)) -\n 4*xi/np.sqrt(np.pi)*np.exp(-(xi**2)*(r**2))*np.identity(3)\n return A\n *\n * */\ninline Eigen::Matrix3d AEW(const double xi, const Eigen::Vector3d &rvec) {\n    const double r = rvec.norm();\n    Eigen::Matrix3d A = 2 * (xi * exp(-(xi * xi) * (r * r)) / (sqrt(PI314) * r * r) + erfc(xi * r) / (2 * r * r * r)) *\n                            (r * r * Eigen::Matrix3d::Identity() + (rvec * rvec.transpose())) -\n                        4 * xi / sqrt(PI314) * exp(-(xi * xi) * (r * r)) * Eigen::Matrix3d::Identity();\n    return A;\n}\n\n/*\n *\n def BEW(xi,kvec):\n k=np.sqrt(kvec.dot(kvec))\n B =\n 8*np.pi*(1+k*k/(4*(xi**2)))*((k**2)*np.identity(3)-np.outer(kvec,kvec))/(k**4)\n return B*np.exp(-k**2/(4*xi**2))\n *\n * */\ninline Eigen::Matrix3d BEW(const double xi, const Eigen::Vector3d &kvec) {\n    const double k = kvec.norm();\n    Eigen::Matrix3d B = 8 * PI314 * (1 + k * k / (4 * (xi * xi))) *\n                        ((k * k) * Eigen::Matrix3d::Identity() - (kvec * kvec.transpose())) / (k * k * k * k);\n    B *= exp(-k * k / (4 * xi * xi));\n    return B;\n}\n\n/*\n * def stokes3DEwald(rvec,force):\n xi = 2\n r=np.sqrt(rvec.dot(rvec))\n real = 0\n N=4\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n real = real + AEW(xi,rvec+1.0*np.array([i,j,k])).dot(force)\n wave = 0\n N=4\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n kvec=2*np.pi*np.array([i,j,k]) # L = 1\n if(i==0 and j==0 and k==0):\n continue\n else:\n wave = wave + BEW(xi,kvec).dot(force)*np.exp(-complex(0,1)*kvec.dot(rvec))\n\n return (np.real(wave)+real)\n\n * */\ninline void GkernelEwald(const Eigen::Vector3d &rvec, Eigen::Matrix3d &Gsum) {\n    const double xi = 2;\n    const double r = rvec.norm();\n    Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n    const int N = 5;\n    if (r < 1e-14) {\n        auto Gself = -4 * xi / sqrt(PI314) * Eigen::Matrix3d::Identity(); // the self term\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                    if (i == 0 && j == 0 && k == 0) {\n                        continue;\n                    }\n                    real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, k));\n                }\n            }\n        }\n        real += Gself;\n    } else {\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                    real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, k));\n                }\n            }\n        }\n    }\n    Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\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                Eigen::Vector3d kvec(2 * PI314 * i, 2 * PI314 * j, 2 * PI314 * k);\n                if (i == 0 and j == 0 and k == 0) {\n                    continue;\n                } else {\n                    wave = wave + BEW(xi, kvec) * cos(kvec.dot(rvec));\n                }\n            }\n        }\n    }\n    Gsum = real + wave;\n}\n\ninline void Gkernel(const Eigen::Vector3d &target, const Eigen::Vector3d &source, Eigen::Matrix3d &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-14) {\n        answer = Eigen::Matrix3d::Zero();\n        return;\n    }\n    auto part2 = rst * rst.transpose() / (rnorm * rnorm * rnorm);\n    auto part1 = Eigen::Matrix3d::Identity() / rnorm;\n    answer = part1 + part2;\n}\n\n/*\n *\n def stokes3DM2L(rvec,force):\n uEwald=stokes3DEwald(rvec,force)\n uNB=0\n N=3\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n uNB=uNB+Gkernel(rvec-np.array([i,j,k])).dot(force)\n return uEwald-uNB\n * */\n// Out of Layer 1\ninline void GkernelEwaldO1(const Eigen::Vector3d &rvec, Eigen::Matrix3d &GsumO1) {\n    Eigen::Matrix3d Gfree = Eigen::Matrix3d::Zero();\n    GkernelEwald(rvec, GsumO1);\n    const int N = DIRECTLAYER;\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                Gkernel(rvec, Eigen::Vector3d(i, j, k), Gfree);\n                GsumO1 -= Gfree;\n            }\n        }\n    }\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    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n\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,\n                               0); // 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,\n                               0); // 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,\n                               0); // 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,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    //\tfor (int i = 0; i < pointLEquiv.size() / 3; i++) {\n    //\t\tstd::cout << pointLEquiv[3 * i] << \" \" << pointLEquiv[3 * i + 1]\n    //<< \" \" << pointLEquiv[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n    //\n    //\tfor (int i = 0; i < pointLCheck.size() / 3; i++) {\n    //\t\tstd::cout << pointLCheck[3 * i] << \" \" << pointLCheck[3 * i + 1]\n    //<< \" \" << pointLCheck[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n\n    // const int imageN = 100; // images to sum\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(3 * equivN, 3 * equivN);\n    Eigen::MatrixXd A(3 * checkN, 3 * equivN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\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            Gkernel(Cpoint, Lpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\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        //\t\tstd::cout<<\"debug:\"<<Mpoint<<std::endl;\n        // assemble linear system\n        Eigen::MatrixXd f(3 * checkN, 3);\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Matrix3d temp = Eigen::Matrix3d::Zero();\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            // use 3D Ewald subtract the first layer\n            GkernelEwaldO1(Cpoint - Mpoint, temp);\n            f.block<3, 3>(3 * k, 0) = temp;\n        }\n\n        M2L.block(0, 3 * i, 3 * equivN, 3) = (ApinvU.transpose() * (ApinvVT.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 < 3 * equivN; i++) {\n        for (int j = 0; j < 3 * 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    /*\n     * pointForce=[(np.array([1.0,0,0]),np.array([0.1,0.55,0.2]))\n     ,(np.array([-1.0,1.0,1.0]),np.array([0.5,0.1,0.3]))\n     ,(np.array([0.0,0.0,-1.0]),np.array([0.8,0.5,0.7]))]\n     * */\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> forcePoint(3);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> forceValue(3);\n    forcePoint[0] = Eigen::Vector3d(0.1, 0.55, 0.2);\n    forceValue[0] = Eigen::Vector3d(1, 0, 0);\n    forcePoint[1] = Eigen::Vector3d(0.5, 0.1, 0.3);\n    forceValue[1] = Eigen::Vector3d(-1, 1, 1);\n    forcePoint[2] = Eigen::Vector3d(0.8, 0.5, 0.7);\n    forceValue[2] = Eigen::Vector3d(0, 0, -1);\n\n    // solve M\n    A.resize(3 * checkN, 3 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(3 * checkN);\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d temp = Eigen::Vector3d::Zero();\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < forcePoint.size(); p++) {\n            Gkernel(Cpoint, forcePoint[p], G);\n            temp = temp + G * (forceValue[p]);\n        }\n        f.block<3, 1>(3 * k, 0) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            Gkernel(Cpoint, Mpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    // impose net charge equal\n    double fx = 0, fy = 0, fz = 0;\n    for (int i = 0; i < equivN; i++) {\n        fx += Msource[3 * i];\n        fy += Msource[3 * i + 1];\n        fz += Msource[3 * i + 2];\n    }\n    std::cout << \"fx svd before correction: \" << fx << std::endl;\n    std::cout << \"fy svd before correction: \" << fy << std::endl;\n    std::cout << \"fz svd before correction: \" << fz << std::endl;\n    double fnetx = 0;\n    double fnety = 0;\n    double fnetz = 0;\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        fnetx += (forceValue[p][0]);\n        fnety += (forceValue[p][1]);\n        fnetz += (forceValue[p][2]);\n    }\n    /*\n     * fx=(fx-fnet[0])/len(MPoints)\n     fy=(fy-fnet[1])/len(MPoints)\n     fz=(fz-fnet[2])/len(MPoints)\n     * */\n    fx = (fx - fnetx) / equivN;\n    fy = (fy - fnety) / equivN;\n    fz = (fz - fnetz) / equivN;\n    for (int i = 0; i < equivN; i++) {\n        Msource[3 * i] -= fx;\n        Msource[3 * i + 1] -= fy;\n        Msource[3 * i + 2] -= fz;\n    }\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> forcePointExt(0);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> forceValueExt(0);\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        for (int i = -DIRECTLAYER; i < DIRECTLAYER + 1; i++) {\n            for (int j = -DIRECTLAYER; j < DIRECTLAYER + 1; j++) {\n                for (int k = -DIRECTLAYER; k < DIRECTLAYER + 1; k++) {\n                    forcePointExt.push_back(Eigen::Vector3d(i, j, k) + forcePoint[p]);\n                    forceValueExt.push_back(forceValue[p]);\n                }\n            }\n        }\n    }\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    Eigen::Vector3d samplePoint(0.5, 0.5, 0.5);\n    Eigen::Vector3d Usample(0, 0, 0);\n    Eigen::Vector3d UsampleSP(0, 0, 0);\n    Eigen::Matrix3d G;\n    for (size_t p = 0; p < forcePointExt.size(); p++) {\n        Gkernel(samplePoint, forcePointExt[p], G);\n        Usample = Usample + G * (forceValueExt[p]);\n    }\n    std::cout << \"Usample Direct:\" << Usample << std::endl;\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1], pointLEquiv[3 * p + 2]);\n        Eigen::Vector3d Fpoint(M2Lsource[3 * p], M2Lsource[3 * p + 1], M2Lsource[3 * p + 2]);\n        Gkernel(samplePoint, Lpoint, G);\n        UsampleSP = UsampleSP + G * (Fpoint);\n    }\n\n    std::cout << \"Usample M2L:\" << UsampleSP << std::endl;\n    std::cout << \"Usample M2L total:\" << UsampleSP + Usample << std::endl;\n\n    Eigen::Vector3d UsampleDirect = 0 * Usample;\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        GkernelEwald(samplePoint - forcePoint[p], G);\n        UsampleDirect += G * (forceValue[p]);\n    }\n    std::cout << \"Usample Ewald:\" << UsampleDirect << std::endl;\n\n    std::cout << \"error\" << UsampleSP + Usample - UsampleDirect << std::endl;\n\n    return 0;\n}\n\n} // namespace Stokes3D3D\n\n#undef PI314\n#undef DIRECTLAYER\n", "meta": {"hexsha": "146bdeb1b589a81ff101ebb3a19b67907fd17784", "size": 15629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/Stokeslet/Stokes3D3D.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/Stokeslet/Stokes3D3D.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/Stokeslet/Stokes3D3D.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": 36.8608490566, "max_line_length": 119, "alphanum_fraction": 0.5113570926, "num_tokens": 5569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.564747962224467}}
{"text": "//  Copyright (c) 2007 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// Computes test data for the various bessel functions using\n// archived - deliberately naive - version of the code.\n// We'll rely on the high precision of boost::math::ntl::RR to get us out of\n// trouble and not worry about how long the calculations take.\n// This provides a reasonably independent set of test data to\n// compare against newly added asymptotic expansions etc.\n//\n#include <fstream>\n\n#include <boost/math/tools/test_data.hpp>\n#include \"ntl_rr_lanczos.hpp\"\n\n#include <boost/math/special_functions/bessel.hpp>\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace boost::math::detail;\nusing namespace std;\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>\nint bessel_jy_bare(T v, T x, T* J, T* Y, int kind = need_j|need_y)\n{\n    // Jv1 = J_(v+1), Yv1 = Y_(v+1), fv = J_(v+1) / J_v\n    // Ju1 = J_(u+1), Yu1 = Y_(u+1), fu = J_(u+1) / J_u\n    T u, Jv, Ju, Yv, Yv1, Yu, Yu1, fv, fu;\n    T W, p, q, gamma, current, prev, next;\n    bool reflect = false;\n    int n, k, s;\n\n    using namespace std;\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<int>(v + 0.5L);\n    u = v - n;                              // -1/2 <= u < 1/2\n\n    if (x < 0)\n    {\n       *J = *Y = policies::raise_domain_error<T>(\"\",\n          \"Real argument x=%1% must be non-negative, complex number result not supported\", x, policies::policy<>());\n        return 1;\n    }\n    if (x == 0)\n    {\n       *J = *Y = policies::raise_overflow_error<T>(\n          \"\", 0, policies::policy<>());\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, policies::policy<>()))             // 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        CF1_jy(v, x, &fv, &s, policies::policy<>());                 // continued fraction CF1\n        Jv = W / (Yv * fv - Yv1);           // Wronskian relation\n    }\n    else                                    // x in (2, \\infty)\n    {\n        // Get Y(u, x):\n        CF1_jy(v, x, &fv, &s, policies::policy<>());\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() to get fu, not much difference in precision\n        fu = prev / current;\n        CF2_jy(u, x, &p, &q, policies::policy<>());                  // continued fraction CF2\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        // 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\n    if (reflect)\n    {\n        T z = (u + n % 2) * pi<T>();\n        *J = cos(z) * Jv - sin(z) * Yv;     // reflection formula\n        *Y = sin(z) * Jv + cos(z) * Yv;\n    }\n    else\n    {\n        *J = Jv;\n        *Y = Yv;\n    }\n\n    return 0;\n}\n\nint progress = 0;\n\ntemplate <class T>\nT cyl_bessel_j_bare(T v, T x)\n{\n   T j, y;\n   bessel_jy_bare(v, x, &j, &y);\n\n   std::cout << progress++ << \":   J(\" << v << \", \" << x << \") = \" << j << std::endl;\n\n   if(fabs(j) > 1e30)\n      throw std::domain_error(\"\");\n\n   return j;\n}\n\ntemplate <class T>\nT cyl_bessel_i_bare(T v, T x)\n{\n   using namespace std;\n   if(x < 0)\n   {\n      // better have integer v:\n      if(floor(v) == v)\n      {\n         T r = cyl_bessel_i_bare(v, -x);\n         if(tools::real_cast<int>(v) & 1)\n            r = -r;\n         return r;\n      }\n      else\n         return policies::raise_domain_error<T>(\n            \"\",\n            \"Got x = %1%, but we need x >= 0\", x, policies::policy<>());\n   }\n   if(x == 0)\n   {\n      return (v == 0) ? 1 : 0;\n   }\n   T I, K;\n   boost::math::detail::bessel_ik(v, x, &I, &K, 0xffff, policies::policy<>());\n\n   std::cout << progress++ << \":   I(\" << v << \", \" << x << \") = \" << I << std::endl;\n\n   if(fabs(I) > 1e30)\n      throw std::domain_error(\"\");\n\n   return I;\n}\n\ntemplate <class T>\nT cyl_bessel_k_bare(T v, T x)\n{\n   using namespace std;\n   if(x < 0)\n   {\n      return policies::raise_domain_error<T>(\n         \"\",\n         \"Got x = %1%, but we need x > 0\", x, policies::policy<>());\n   }\n   if(x == 0)\n   {\n      return (v == 0) ? policies::raise_overflow_error<T>(\"\", 0, policies::policy<>())\n         : policies::raise_domain_error<T>(\n         \"\",\n         \"Got x = %1%, but we need x > 0\", x, policies::policy<>());\n   }\n   T I, K;\n   bessel_ik(v, x, &I, &K, 0xFFFF, policies::policy<>());\n\n   std::cout << progress++ << \":   K(\" << v << \", \" << x << \") = \" << K << std::endl;\n\n   if(fabs(K) > 1e30)\n      throw std::domain_error(\"\");\n\n   return K;\n}\n\ntemplate <class T>\nT cyl_neumann_bare(T v, T x)\n{\n   T j, y;\n   bessel_jy(v, x, &j, &y, 0xFFFF, policies::policy<>());\n\n   std::cout << progress++ << \":   Y(\" << v << \", \" << x << \") = \" << y << std::endl;\n\n   if(fabs(y) > 1e30)\n      throw std::domain_error(\"\");\n\n   return y;\n}\n\ntemplate <class T>\nT sph_bessel_j_bare(T v, T x)\n{\n   std::cout << progress++ << \":   j(\" << v << \", \" << x << \") = \";\n   if((v < 0) || (floor(v) != v))\n      throw std::domain_error(\"\");\n   T r = sqrt(constants::pi<T>() / (2 * x)) * cyl_bessel_j_bare(v+0.5, x);\n   std::cout << r << std::endl;\n   return r;\n}\n\ntemplate <class T>\nT sph_bessel_y_bare(T v, T x)\n{\n   std::cout << progress++ << \":   y(\" << v << \", \" << x << \") = \";\n   if((v < 0) || (floor(v) != v))\n      throw std::domain_error(\"\");\n   T r = sqrt(constants::pi<T>() / (2 * x)) * cyl_neumann_bare(v+0.5, x);\n   std::cout << r << std::endl;\n   return r;\n}\n\nenum\n{\n   func_J = 0,\n   func_Y,\n   func_I,\n   func_K,\n   func_j,\n   func_y\n};\n\nint main(int argc, char* argv[])\n{\n   std::cout << std::setprecision(17) << std::scientific;\n   std::cout << sph_bessel_j_bare(0., 0.1185395751953125e4) << std::endl;\n   std::cout << sph_bessel_j_bare(22., 0.6540834903717041015625) << std::endl;\n\n   parameter_info<boost::math::ntl::RR> arg1, arg2;\n   test_data<boost::math::ntl::RR> data;\n\n   boost::math::ntl::RR::SetPrecision(1000); \n   boost::math::ntl::RR::SetOutputPrecision(40);\n\n   int functype = 0;\n   std::string letter = \"J\";\n\n   if(argc == 2)\n   {\n      if(std::strcmp(argv[1], \"--Y\") == 0)\n      {\n         functype = func_Y;\n         letter = \"Y\";\n      }\n      else if(std::strcmp(argv[1], \"--I\") == 0)\n      {\n         functype = func_I;\n         letter = \"I\";\n      }\n      else if(std::strcmp(argv[1], \"--K\") == 0)\n      {\n         functype = func_K;\n         letter = \"K\";\n      }\n      else if(std::strcmp(argv[1], \"--j\") == 0)\n      {\n         functype = func_j;\n         letter = \"j\";\n      }\n      else if(std::strcmp(argv[1], \"--y\") == 0)\n      {\n         functype = func_y;\n         letter = \"y\";\n      }\n      else\n         assert(0);\n   }\n\n   bool cont;\n   std::string line;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the Bessel \" << letter << \" function\\n\\n\";\n   do{\n      get_user_parameter_info(arg1, \"v\");\n      get_user_parameter_info(arg2, \"x\");\n      boost::math::ntl::RR (*fp)(boost::math::ntl::RR, boost::math::ntl::RR);\n      if(functype == func_J) \n         fp = cyl_bessel_j_bare;\n      else if(functype == func_I) \n         fp = cyl_bessel_i_bare;\n      else if(functype == func_K) \n         fp = cyl_bessel_k_bare;\n      else if(functype == func_Y)\n         fp = cyl_neumann_bare;\n      else if(functype == func_j)\n         fp = sph_bessel_j_bare;\n      else if(functype == func_y)\n         fp = sph_bessel_y_bare;\n      else\n         assert(0);\n\n      data.insert(fp, arg1, arg2);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=bessel_j_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"bessel_j_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   line.erase(line.find('.'));\n   ofs << std::scientific;\n   write_code(ofs, data, line.c_str());\n\n   return 0;\n}\n\n\n\n\n", "meta": {"hexsha": "d239fa75b5ab4873ed7f83c7df27e489c2c3801e", "size": 9602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/bessel_data.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/tools/bessel_data.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/tools/bessel_data.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 26.8212290503, "max_line_length": 116, "alphanum_fraction": 0.4948968965, "num_tokens": 2946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324848629215, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5646642502036275}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <complex>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/value_type/complex.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n\n#include <amgcl/mpi/util.hpp>\n#include <amgcl/mpi/make_solver.hpp>\n#include <amgcl/mpi/preconditioner.hpp>\n#include <amgcl/mpi/solver/runtime.hpp>\n\n#include <amgcl/io/mm.hpp>\n#include <amgcl/io/binary.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl {\n    profiler<> prof;\n}\n\nnamespace math = amgcl::math;\n\n//---------------------------------------------------------------------------\nptrdiff_t assemble_poisson3d(amgcl::mpi::communicator comm,\n        ptrdiff_t n, int block_size,\n        std::vector<ptrdiff_t> &ptr,\n        std::vector<ptrdiff_t> &col,\n        std::vector<std::complex<double>> &val,\n        std::vector<std::complex<double>> &rhs)\n{\n    ptrdiff_t n3 = n * n * n;\n\n    ptrdiff_t chunk = (n3 + comm.size - 1) / comm.size;\n    if (chunk % block_size != 0) {\n        chunk += block_size - chunk % block_size;\n    }\n    ptrdiff_t row_beg = std::min(n3, chunk * comm.rank);\n    ptrdiff_t row_end = std::min(n3, row_beg + chunk);\n    chunk = row_end - row_beg;\n\n    ptr.clear(); ptr.reserve(chunk + 1);\n    col.clear(); col.reserve(chunk * 7);\n    val.clear(); val.reserve(chunk * 7);\n\n    rhs.resize(chunk);\n    std::fill(rhs.begin(), rhs.end(), 1.0);\n\n    const double h2i = (n - 1) * (n - 1);\n    ptr.push_back(0);\n\n    for (ptrdiff_t idx = row_beg; idx < row_end; ++idx) {\n        ptrdiff_t k = idx / (n * n);\n        ptrdiff_t j = (idx / n) % n;\n        ptrdiff_t i = idx % n;\n\n        if (k > 0)  {\n            col.push_back(idx - n * n);\n            val.push_back(-h2i);\n        }\n\n        if (j > 0)  {\n            col.push_back(idx - n);\n            val.push_back(-h2i);\n        }\n\n        if (i > 0) {\n            col.push_back(idx - 1);\n            val.push_back(-h2i);\n        }\n\n        col.push_back(idx);\n        val.push_back(6 * h2i);\n\n        if (i + 1 < n) {\n            col.push_back(idx + 1);\n            val.push_back(-h2i);\n        }\n\n        if (j + 1 < n) {\n            col.push_back(idx + n);\n            val.push_back(-h2i);\n        }\n\n        if (k + 1 < n) {\n            col.push_back(idx + n * n);\n            val.push_back(-h2i);\n        }\n\n        ptr.push_back( col.size() );\n    }\n\n    return chunk;\n}\n\n//---------------------------------------------------------------------------\nvoid solve_scalar(\n        amgcl::mpi::communicator comm,\n        ptrdiff_t chunk,\n        const std::vector<ptrdiff_t> &ptr,\n        const std::vector<ptrdiff_t> &col,\n        const std::vector<std::complex<double>> &val,\n        const boost::property_tree::ptree &prm,\n        const std::vector<std::complex<double>> &rhs\n        )\n{\n    typedef amgcl::backend::builtin<std::complex<double>> Backend;\n\n    typedef\n        amgcl::mpi::make_solver<\n            amgcl::runtime::mpi::preconditioner<Backend>,\n            amgcl::runtime::mpi::solver::wrapper<Backend>\n            >\n        Solver;\n\n    using amgcl::prof;\n\n    prof.tic(\"setup\");\n    Solver solve(comm, std::tie(chunk, ptr, col, val), prm);\n    prof.toc(\"setup\");\n\n    if (comm.rank == 0) {\n        std::cout << solve << std::endl;\n    }\n\n    std::vector<std::complex<double>> x(chunk);\n\n    int    iters;\n    double error;\n\n    prof.tic(\"solve\");\n    std::tie(iters, error) = solve(rhs, x);\n    prof.toc(\"solve\");\n\n    if (comm.rank == 0) {\n        std::cout\n            << \"Iterations: \" << iters << std::endl\n            << \"Error:      \" << error << std::endl\n            << prof << std::endl;\n    }\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    amgcl::mpi::init_thread mpi(&argc, &argv);\n    amgcl::mpi::communicator comm(MPI_COMM_WORLD);\n\n    if (comm.rank == 0)\n        std::cout << \"World size: \" << comm.size << std::endl;\n\n    using amgcl::prof;\n\n    // Read configuration from command line\n    namespace po = boost::program_options;\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"size,n\",\n         po::value<ptrdiff_t>()->default_value(128),\n         \"domain size\"\n        )\n        (\"prm-file,P\",\n         po::value<std::string>(),\n         \"Parameter file in json format. \"\n        )\n        (\n         \"prm,p\",\n         po::value< std::vector<std::string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        ;\n\n    po::positional_options_description p;\n    p.add(\"prm\", -1);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        if (comm.rank == 0) std::cout << desc << std::endl;\n        return 0;\n    }\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"prm-file\")) {\n        read_json(vm[\"prm-file\"].as<std::string>(), prm);\n    }\n\n    if (vm.count(\"prm\")) {\n        for(const std::string &v : vm[\"prm\"].as<std::vector<std::string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    ptrdiff_t n;\n    std::vector<ptrdiff_t> ptr;\n    std::vector<ptrdiff_t> col;\n    std::vector<std::complex<double>> val;\n    std::vector<std::complex<double>> rhs;\n\n    prof.tic(\"assemble\");\n    n = assemble_poisson3d(comm, vm[\"size\"].as<ptrdiff_t>(), 1, ptr, col, val, rhs);\n    prof.toc(\"assemble\");\n\n    solve_scalar(comm, n, ptr, col, val, prm, rhs);\n}\n", "meta": {"hexsha": "abc9b2b57d94a153c81b30037f646fb14eb641af", "size": 5722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpi/mpi_complex.cpp", "max_stars_repo_name": "ivhak/amgcl", "max_stars_repo_head_hexsha": "ed8347bb5becfad0684b5b3a09cce0a77067afb1", "max_stars_repo_licenses": ["MIT"], "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/mpi/mpi_complex.cpp", "max_issues_repo_name": "ivhak/amgcl", "max_issues_repo_head_hexsha": "ed8347bb5becfad0684b5b3a09cce0a77067afb1", "max_issues_repo_licenses": ["MIT"], "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/mpi/mpi_complex.cpp", "max_forks_repo_name": "ivhak/amgcl", "max_forks_repo_head_hexsha": "ed8347bb5becfad0684b5b3a09cce0a77067afb1", "max_forks_repo_licenses": ["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.247706422, "max_line_length": 89, "alphanum_fraction": 0.5267389025, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956854, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5646642357033396}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2008 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/* This example sets up a callable fixed rate bond with a Hull White pricing\n   engine and compares to Bloomberg's Hull White price/yield calculations.\n*/\n\n#include <ql/experimental/callablebonds/callablebond.hpp>\n#include <ql/experimental/callablebonds/treecallablebondengine.hpp>\n#include <ql/models/shortrate/onefactormodels/hullwhite.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/time/calendars/unitedstates.hpp>\n#include <ql/time/daycounters/actualactual.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 <vector>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <boost/timer.hpp>\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\nboost::shared_ptr<YieldTermStructure>\n    flatRate(const Date& today,\n             const boost::shared_ptr<Quote>& forward,\n             const DayCounter& dc,\n             const Compounding& compounding,\n             const Frequency& frequency) {\n    return boost::shared_ptr<YieldTermStructure>(\n                                       new FlatForward(today,\n                                                       Handle<Quote>(forward),\n                                                       dc,\n                                                       compounding,\n                                                       frequency));\n}\n\n\nboost::shared_ptr<YieldTermStructure>\n    flatRate(const Date& today,\n             Rate forward,\n             const DayCounter& dc,\n             const Compounding &compounding,\n             const Frequency &frequency) {\n    return flatRate(today,\n            boost::shared_ptr<Quote>(new SimpleQuote(forward)),\n            dc,\n            compounding,\n            frequency);\n}\n\n\nint main(int, char* [])\n{\n    try {\n\n        boost::timer timer;\n\n        Date today = Date(16,October,2007);\n        Settings::instance().evaluationDate() = today;\n\n        cout <<  endl;\n        cout << \"Pricing a callable fixed rate bond using\" << endl;\n        cout << \"Hull White model w/ reversion parameter = 0.03\" << endl;\n        cout << \"BAC4.65 09/15/12  ISIN: US06060WBJ36\" << endl;\n        cout << \"roughly five year tenor, \";\n        cout << \"quarterly coupon and call dates\" << endl;\n        cout << \"reference date is : \" << today << endl << endl;\n\n        /* Bloomberg OAS1: \"N\" model (Hull White)\n           varying volatility parameter\n\n           The curve entered into Bloomberg OAS1 is a flat curve,\n           at constant yield = 5.5%, semiannual compounding.\n           Assume here OAS1 curve uses an ACT/ACT day counter,\n           as documented in PFC1 as a \"default\" in the latter case.\n        */\n\n        // set up a flat curve corresponding to Bloomberg flat curve\n\n        Rate bbCurveRate = 0.055;\n        DayCounter bbDayCounter = ActualActual(ActualActual::Bond);\n        InterestRate bbIR(bbCurveRate,bbDayCounter,Compounded,Semiannual);\n\n        Handle<YieldTermStructure> termStructure(flatRate(today,\n                                                          bbIR.rate(),\n                                                          bbIR.dayCounter(),\n                                                          bbIR.compounding(),\n                                                          bbIR.frequency()));\n\n        // set up the call schedule\n\n        CallabilitySchedule callSchedule;\n        Real callPrice = 100.;\n        Size numberOfCallDates = 24;\n        Date callDate = Date(15,September,2006);\n\n        for (Size i=0; i< numberOfCallDates; i++) {\n            Calendar nullCalendar = NullCalendar();\n\n            Callability::Price myPrice(callPrice,\n                                       Callability::Price::Clean);\n            callSchedule.push_back(\n                boost::shared_ptr<Callability>(\n                    new Callability(myPrice,\n                                    Callability::Call,\n                                    callDate )));\n            callDate = nullCalendar.advance(callDate, 3, Months);\n        }\n\n\n        // set up the callable bond\n\n        Date dated = Date(16,September,2004);\n        Date issue = dated;\n        Date maturity = Date(15,September,2012);\n        Natural settlementDays = 3;  // Bloomberg OAS1 settle is Oct 19, 2007\n        Calendar bondCalendar = UnitedStates(UnitedStates::GovernmentBond);\n        Real coupon = .0465;\n        Frequency frequency = Quarterly;\n        Real redemption = 100.0;\n        Real faceAmount = 100.0;\n\n        /* The 30/360 day counter Bloomberg uses for this bond cannot\n           reproduce the US Bond/ISMA (constant) cashflows used in PFC1.\n           Therefore use ActAct(Bond)\n        */\n        DayCounter bondDayCounter = ActualActual(ActualActual::Bond);\n\n        // PFC1 shows no indication dates are being adjusted\n        // for weekends/holidays for vanilla bonds\n        BusinessDayConvention accrualConvention = Unadjusted;\n        BusinessDayConvention paymentConvention = Unadjusted;\n\n        Schedule sch(dated, maturity, Period(frequency), bondCalendar,\n                     accrualConvention, accrualConvention,\n                     DateGeneration::Backward, false);\n\n        Size maxIterations = 1000;\n        Real accuracy = 1e-8;\n        Integer gridIntervals = 40;\n        Real reversionParameter = .03;\n\n        // output price/yield results for varying volatility parameter\n\n        Real sigma = QL_EPSILON; // core dumps if zero on Cygwin\n\n        boost::shared_ptr<ShortRateModel> hw0(\n                       new HullWhite(termStructure,reversionParameter,sigma));\n\n        boost::shared_ptr<PricingEngine> engine0(\n                      new TreeCallableFixedRateBondEngine(hw0,gridIntervals));\n\n        CallableFixedRateBond callableBond(settlementDays, faceAmount, sch,\n                                           vector<Rate>(1, coupon),\n                                           bondDayCounter, paymentConvention,\n                                           redemption, issue, callSchedule);\n        callableBond.setPricingEngine(engine0);\n\n        cout << setprecision(2)\n             << showpoint\n             << fixed\n             << \"sigma/vol (%) = \"\n             << 100.*sigma\n             << endl;\n\n        cout << \"QuantLib price/yld (%)  \";\n        cout << callableBond.cleanPrice() << \" / \"\n             << 100. * callableBond.yield(bondDayCounter,\n                                          Compounded,\n                                          frequency,\n                                          accuracy,\n                                          maxIterations)\n             << endl;\n\n        cout << \"Bloomberg price/yld (%) \";\n        cout << \"96.50 / 5.47\"\n             << endl\n             << endl;\n\n        sigma = .01;\n\n        cout << \"sigma/vol (%) = \" << 100.*sigma << endl;\n\n        boost::shared_ptr<ShortRateModel> hw1(\n                       new HullWhite(termStructure,reversionParameter,sigma));\n\n        boost::shared_ptr<PricingEngine> engine1(\n                      new TreeCallableFixedRateBondEngine(hw1,gridIntervals));\n\n        callableBond.setPricingEngine(engine1);\n\n        cout << \"QuantLib price/yld (%)  \";\n        cout << callableBond.cleanPrice() << \" / \"\n             << 100.* callableBond.yield(bondDayCounter,\n                                         Compounded,\n                                         frequency,\n                                         accuracy,\n                                         maxIterations)\n             << endl;\n\n        cout << \"Bloomberg price/yld (%) \";\n        cout << \"95.68 / 5.66\"\n             << endl\n             << endl;\n\n        ////////////////////\n\n        sigma = .03;\n\n        boost::shared_ptr<ShortRateModel> hw2(\n                     new HullWhite(termStructure, reversionParameter, sigma));\n\n        boost::shared_ptr<PricingEngine> engine2(\n                      new TreeCallableFixedRateBondEngine(hw2,gridIntervals));\n\n        callableBond.setPricingEngine(engine2);\n\n        cout << \"sigma/vol (%) = \"\n             << 100.*sigma\n             << endl;\n\n        cout << \"QuantLib price/yld (%)  \";\n        cout << callableBond.cleanPrice() << \" / \"\n             << 100. * callableBond.yield(bondDayCounter,\n                                          Compounded,\n                                          frequency,\n                                          accuracy,\n                                          maxIterations)\n             << endl;\n\n        cout << \"Bloomberg price/yld (%) \";\n        cout << \"92.34 / 6.49\"\n             << endl\n             << endl;\n\n        ////////////////////////////\n\n        sigma = .06;\n\n        boost::shared_ptr<ShortRateModel> hw3(\n                     new HullWhite(termStructure, reversionParameter, sigma));\n\n        boost::shared_ptr<PricingEngine> engine3(\n                      new TreeCallableFixedRateBondEngine(hw3,gridIntervals));\n\n        callableBond.setPricingEngine(engine3);\n\n        cout << \"sigma/vol (%) = \"\n             << 100.*sigma\n             << endl;\n\n        cout << \"QuantLib price/yld (%)  \";\n        cout << callableBond.cleanPrice() << \" / \"\n             << 100. * callableBond.yield(bondDayCounter,\n                                          Compounded,\n                                          frequency,\n                                          accuracy,\n                                          maxIterations)\n             << endl;\n\n        cout << \"Bloomberg price/yld (%) \";\n        cout << \"87.16 / 7.83\"\n             << endl\n             << endl;\n\n        /////////////////////////\n\n        sigma = .12;\n\n        boost::shared_ptr<ShortRateModel> hw4(\n                     new HullWhite(termStructure, reversionParameter, sigma));\n\n        boost::shared_ptr<PricingEngine> engine4(\n                      new TreeCallableFixedRateBondEngine(hw4,gridIntervals));\n\n        callableBond.setPricingEngine(engine4);\n\n        cout << \"sigma/vol (%) = \"\n             << 100.*sigma\n             << endl;\n\n        cout << \"QuantLib price/yld (%)  \";\n        cout << callableBond.cleanPrice() << \" / \"\n             << 100.* callableBond.yield(bondDayCounter,\n                                         Compounded,\n                                         frequency,\n                                         accuracy,\n                                         maxIterations)\n             << endl;\n\n        cout << \"Bloomberg price/yld (%) \";\n        cout << \"77.31 / 10.65\"\n             << endl\n             << endl;\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 (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\n", "meta": {"hexsha": "4f7d6505c739ddd9df85b3b4b3713c956baeeb4b", "size": 12319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/CallableBonds/CallableBonds.cpp", "max_stars_repo_name": "pmazzocchi/QuantLib", "max_stars_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/CallableBonds/CallableBonds.cpp", "max_issues_repo_name": "pmazzocchi/QuantLib", "max_issues_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/CallableBonds/CallableBonds.cpp", "max_forks_repo_name": "pmazzocchi/QuantLib", "max_forks_repo_head_hexsha": "52215f089778ddd1ea4dbef55d260ec8bd56901e", "max_forks_repo_licenses": ["BSD-3-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.7014084507, "max_line_length": 79, "alphanum_fraction": 0.522120302, "num_tokens": 2525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5645901991894102}}
{"text": "/* Hector -- A Simple Climate Model\n   Copyright (C) 2014-2015  Battelle Memorial Institute\n\n   Please see the accompanying file LICENSE.md for additional licensing\n   information.\n*/\n// ocean_csys_class.cpp : Defines the entry point for the console application.\n/*  Ocean Carbon Chemistry CODE File:\n *\n *  Created by Corinne Hartin  1/30/13.\n \n *  This code translated from MATLAB code\n *  Reference: Richard E. Zeebe and Dieter A. Wolf-Gladrow\n \n *\tAlfred Wegener Institute for\n *\tPolar and Marine Research\n *\tP.O. Box 12 01 61\n *   D-27515 Bremerhaven\n *\tGermany\n *\te-mail: rzeebe@awi-bremerhaven.de   wolf@awi-bremerhaven.de\n *\n *   based on the book by Zeebe and Wolf-Gladrow (2001) CO2 in seawater: equilibrium, kintetics, isotopes. 346 p Amsterdam: Elsevier\n *   http://www.soest.hawaii.edu/oceanography/faculty/zeebe_files/CO2_System_in_Seawater/csys.html\n */\n\n#include <math.h>\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/math/tools/roots.hpp>\n\n#include \"h_exception.hpp\"\n#include \"ocean_csys.hpp\"\n\nnamespace Hector {\n  \nusing namespace std;\n\n//------------------------------------------------------------------------------\n/*! \\brief new oceanbox logger\n *  oceanbox logger may or may not be defined and therefore we check before logging\n */\n#define CS_LOG(log, level)  \\\nif( log != NULL ) H_LOG( (*log), level )\n\n//------------------------------------------------------------------------------\n/*! \\brief constructor\n */\noceancsys::oceancsys() : ncoeffs(6), m_a(ncoeffs) {\n\tlogger = NULL;\n\tS = alk = As = Ks = 0.0;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief A helper functor class used to evauluate a polynomial and its derivative.\n *  \\details This helper class gives an interface that is callable from boost's numerical\n *           solvers which need to evaluate a function and it's derivative.  This class\n *           wrapps a polynomical by taking an array of coefficients in ascending order of\n *           the degree of the term they are associated.\n */\nclass PolyDerivFunctor {\n    public:\n        PolyDerivFunctor(const double* coefs, const int degree) {\n            using namespace boost::math::tools;\n            const int size = degree + 1;\n            mPoly = polynomial<double>(coefs, degree);\n            double* derivCoef = new double[size-1];\n            for(int i = 1; i < size; ++i) {\n                derivCoef[i - 1] = coefs[i] * static_cast<double>(i);\n            }\n            mPolyDeriv = polynomial<double>(derivCoef, degree-1);\n            delete[] derivCoef;\n        }\n\n        pair<double, double> operator()(const double x) {\n            return pair<double, double>(mPoly.evaluate(x), mPolyDeriv.evaluate(x));\n        }\n\n    private:\n        //! The representation of the polynomial to calculate.\n        boost::math::tools::polynomial<double> mPoly;\n\n        //! The representation of the derivative of the polynomial to calculate.\n        boost::math::tools::polynomial<double> mPolyDeriv;\n};\n\n//------------------------------------------------------------------------------\n/*! \\brief Find the largest real root, using GSL or appropriate algorithms\n *  \\param ncoeff   Number of coefficients\n *  \\param *a       Coefficients\n *  \\return         Largest real root (H+ ion)\n */\ndouble find_largest_root( const int ncoeffs, double* a ) {\n    \n    using namespace boost::math::tools;\n    const int degree = ncoeffs-1;\n    PolyDerivFunctor polyFunctor(a, degree);\n    // Use Fujiwara's method to find an upper bound for the roots of the polynomial\n    double max = pow(std::abs(a[0] / ( 2.0 * a[degree])), 1.0 / degree);\n    for(int i = 1; i < degree; ++i) {\n        max = std::max(max, pow(std::abs(a[i]/a[degree]), 1.0 / static_cast<double>(degree - i)));\n    }\n    max *= 2.0;\n    // Use Newton's method to find the largest real root starting from the Fujiwara upper bound\n    // arbitrarily solve unil 60% of the digits are correct.\n    const int digits = numeric_limits<double>::digits;\n    int get_digits = static_cast<int>(digits * 0.6);\n    double h = newton_raphson_iterate(polyFunctor, max-0.001, 0.0, max, get_digits);\n\n\treturn h;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Run Ocean csys\n *\n * DIC and ALK calculate pH, pCO2, omega Ar, omega Ca\n * (from Zeebe and Wolfe-Gladrow 2001)\n * pCO2 is used to calculate ocean-atmosphere fluxes\n * (from Takahashi et al, 2009, eq. 7 & 8)\n */\nvoid oceancsys::ocean_csys_run( unitval tbox, unitval carbon )\n{\n    \n\tdouble tmp, tmp1, tmp2, tmp3;\n    \n    // Convert carbon to dic value and temperature to K\n    const double dic = convertToDIC( carbon ).value( U_UMOL_KG )/1e6;   // back to mol/kg\n    const double Tc = tbox.value( U_DEGC );\n    const double Tk = Tc + 273.15;\n    \n\t// Check that all is OK with input data\n\tH_ASSERT( Tk > 265 && Tk < 308, \"bad Tk value\" ); // Kelvin\n    H_ASSERT( dic > 1000e-6 && dic < 3700e-6, \"bad dic value\" );  // mol/kg\n\n    // alk should be constant once spinup is done, but check anyway\n    H_ASSERT( alk >= 2000e-6 && alk <= 2750e-6, \"bad alk value\" );  // mol/kg\n\n\t/*---------------------------------------------------------------\n     This section calculates the constants K0, Sc, K1, K2, Ksp, Ksi etc.\n     ---------------------------------------------------------------*/\n    \n\t// --------------------- K0 -----------------------------------\n\t// solubility of CO2 calculated from Weiss 1974 (mol * L-1 * atm-1)\n\t// used to calculate CO2 fluxes\n\ttmp1 = -58.0931 + 90.5069* ( 100/Tk ) + 22.2940 * log( Tk/100 );\n\ttmp2 = S * ( 0.027766 - 0.025888 * ( Tk/100 ) + 0.0050578 * ( ( Tk/100 ) * ( Tk/100 ) ) );\n\tconst double lnK0 =  tmp1 + tmp2;\n\tK0.set( exp( lnK0 ), U_MOL_L_ATM );\n    \n\t//---------------------Sc------------------------------------------\n\t// Schmidt Number from Wanninkhof 1992\n\tconst double Sc = 2073.1 - ( 125.62 * Tc ) + (3.6276 * Tc * Tc) - ( 0.043219 * Tc * Tc * Tc );\n    \n\t// --------------------- Kwater -----------------------------------\n\t// table 1.1 in Part1: Seawater carbonate chemistry Andrew Dickson\n\t// Millero (1995)(in Dickson and Goyet (1994, Chapter 5, p.18))\n\ttmp1 = -13847.26/Tk + 148.96502 - 23.6521 * log( Tk );\n\ttmp2 = + (118.67/Tk - 5.977 + 1.0495*log( Tk ) ) * sqrt( S ) - 0.01615 * S;\n\tconst double lnKw =  tmp1 + tmp2;\n\tKw.set( exp(lnKw), U_MOL_KG);\n\t\n    \n\t//---------------------- Kh (K Henry) ----------------------------\n\t// solubility of CO2 calculated from Weiss 1974 (mol*kg-1*atm-1)\n\t// Kh and K0 are identical equations with differing constants resulting in different units\n\t// used to calculate pCO2\n\ttmp = 9345.17 / Tk - 60.2409 + 23.3585 * log( Tk/100 );\n\tconst double nKhwe74 = tmp + S * ( 0.023517-0.00023656 * Tk + 0.0047036e-4 * Tk * Tk );\n\tKh.set( exp( nKhwe74 ), U_MOL_KG_ATM);\n\t\n\t// --------------------- K1 ---------------------------------------\n\t//   Mehrbach et al (1973) refit by Lueker et al. (2000).\n\tconst double pK1mehr = 3633.86/Tk - 61.2172 + 9.6777*log( Tk ) - 0.011555 * S + 0.0001152 * S * S;\n\tconst unitval K1( pow( 10, -pK1mehr ), U_MOL_KG);\n    \n\t// --------------------- K2 ----------------------------------------\n\t//   Mehrbach et al. (1973) refit by Lueker et al. (2000).\n\tconst double pK2mehr = 471.78/Tk + 25.9290 - 3.16967 * log( Tk ) - 0.01781 * S + 0.0001122 * S * S;\n\tconst unitval K2( pow( 10.0, -pK2mehr ), U_MOL_KG);\n    \n\t// --------------------- Kb  --------------------------------------------\n\t// boric acid DOE 1994\n\ttmp1 =  ( -8966.90-2890.53 * sqrt( S ) - 77.942 * S+ 1.728*pow( S,( 3.0/2.0 ) ) - 0.0996 * S * S )/Tk;\n\ttmp2 =   +148.0248+137.1942 * sqrt( S ) + 1.62142 * S;\n\ttmp3 = +(-24.4344-25.085 * sqrt( S )-0.2474 * S ) * log( Tk ) + 0.053105 * sqrt( S ) * Tk;\n\tconst double lnKb = tmp1 + tmp2 + tmp3;\n\tconst unitval Kb( exp(lnKb), U_MOL_KG);\n    \n\t// --------------------- Kspc (calcite) ----------------------------\n\t// Mucci, Alphonso, Amer. J. of Science 283:781-799, 1983\n\ttmp1 = -171.9065-0.077993 * Tk + 2839.319/Tk + 71.595 * log10( Tk );\n\ttmp2 = +( -0.77712+0.0028426 * Tk + 178.34/Tk ) * sqrt( S );\n\ttmp3 = -0.07711 * S + 0.0041249 * pow( S, 1.5 );\n\tconst double log10Kspc = tmp1 + tmp2 + tmp3;\n\tconst double Kspc = pow( 10.0, log10Kspc ); // mol/kg\n    \n\t// --------------------- Kspa (aragonite) ----------------------------\n\t// Mucci, Alphonso, Amer. J. of Science 283:781-799, 1983\n\ttmp1 = -171.945 - 0.077993 * Tk + 2903.293 / Tk + 71.595 * log10( Tk );\n\ttmp2 = +( -0.068393+0.0017276 * Tk + 88.135/Tk ) * sqrt( S );\n\ttmp3 = -0.10018 * S + 0.0059415 * pow( S, 1.5 );\n\tconst double log10Kspa = tmp1 + tmp2 + tmp3;\n\tconst double Kspa = pow( 10.0, log10Kspa ); // mol/kg\n    \n\t//------------------------- boron --------------------------------------\n\t// total boron concentration\n\t// DOE 1994\n\tconst double bor = 1 * ( 416.0 * ( S/35.0 ) ) * 1.e-6;   // (mol/kg), DOE94\n    \n\t/* ---------------------------------------\n     ALK and DIC given solve for pH and pCO2\n     ------------------------------------------*/\n    \n    const double Kb_val = Kb.value( U_MOL_KG );     // for convenience in eqns below\n    const double K1_val = K1.value( U_MOL_KG );\n    const double K2_val = K2.value( U_MOL_KG );\n    const double Kw_val = Kw.value( U_MOL_KG );\n    \n\tconst double p5 = -1.0;\n\tconst double p4 = -alk - Kb_val - K1_val;\n\tconst double p3 = dic * K1_val - alk * ( Kb_val + K1_val )\n        + Kb_val * bor + Kw_val - Kb_val\n        * K1_val - K1_val * K2_val;\n\ttmp = dic * ( Kb_val * K1_val + 2.0 * K1_val * K2_val )\n        -alk * (Kb_val * K1_val + K1_val * K2_val)\n        + Kb_val * bor * K1_val;\n\tconst double p2 = tmp + ( Kw_val * Kb_val + Kw_val * K1_val - Kb_val * K1_val * K2_val );\n\ttmp = 2.0 * dic * Kb_val * K1_val * K2_val\n        - alk * Kb_val * K1_val * K2_val + Kb_val\n        * bor * K1_val * K2_val;\n\tconst double p1 = tmp + ( Kw_val * Kb_val * K1_val + Kw_val * K1_val * K2_val );\n\tconst double p0 = Kw_val * Kb_val * K1_val * K2_val;\n    \n\tm_a[ 0 ] = p0;\n\tm_a[ 1 ] = p1;\n\tm_a[ 2 ] = p2;\n\tm_a[ 3 ] = p3;\n\tm_a[ 4 ] = p4;\n\tm_a[ 5 ] = p5;\n    \n\tconst double h      = find_largest_root( ncoeffs, &m_a[0] );\n    \n\tconst double co2st      = dic/( 1.0 + K1_val / h + K1_val * K2_val / h / h ); // co2st = CO2*\n\tconst double hco3   = dic/( 1.0 + h / K1_val + K2_val / h );\n\tconst double co3    = dic/( 1.0 + h / K2_val + h * h / K1_val / K2_val ); // mol/kg\n    \n\tconst double million = 1e6; // unit conversion\n    \n\t// Output (all variables beginning with capital letter below)\n\tTCO2o.set( co2st * million, U_UMOL_KG );\n\tHCO3.set( hco3 * million, U_UMOL_KG );\n\tCO3.set( co3 * million, U_UMOL_KG );\n\tPCO2o.set ( co2st * million/Kh.value( U_MOL_KG_ATM ), U_UATM );\n\tpH.set (-log10( h ), U_PH);\n    \n    // ----------------------------------------------------------------------------\n    /*! \\brief calculate air-sea flux of carbon\n     * based on Takahashi et al, 2009 Deep Sea Research\n     * Uses K0 (solubility), Sc (Schmidt number) , U (wind stress), PCO2atm, PCO2o\n     */\n    \n\tTr.set( ( 0.585 * K0.value( U_MOL_L_ATM )\n             * pow( Sc, -0.5 ) * U * U ), U_gC_m2_month_uatm );  // units : gC m-2 month-1 uatm-1.\n\t// 0.585 is a unit conversion factor. See Takahashi et al, 2009 page 568\n\t// unit conversion * solubility * Schmidt number * wind speed^2\n\t   \n    //------------------------------------------------------------------------\n    /*! \\brief calculate Omega of Ca/Ar\n     * Uses Ksp of Ca and Ar, CO3, S, and pH\n     */\n    \n\t// this is 0.010285*S/35\n\tconst double calcium = 0.02128/40.087 * ( S/1.80655 ); //mol/kg Riley, and Tongudai, Chemical Geology 2:263-269, 1967\n\tOmegaCa.set( ( ( co3 * calcium ) / Kspc ), U_UNITLESS );\n\tOmegaAr.set( ( ( co3 * calcium ) / Kspa ), U_UNITLESS );\n}\n\n//-------------------------------------------------------------------------------\n/*! \\brief Calculate the (monthly) atmosphere-surface box flux\n *  \\param Ca           Atmospheric CO2\n *  \\param cpoolscale   Scale the box C pool by this amount (1.0=none)\n *  \\return             Monthly atmospheric C flux, gC/m2/month\n */\ndouble oceancsys::calc_monthly_surface_flux( const unitval& Ca, const double cpoolscale ) const {\n\treturn ( ( Ca.value( U_PPMV_CO2 ) - PCO2o.value( U_UATM ) * cpoolscale ) * Tr.value( U_gC_m2_month_uatm ) ); // units : gC m-2 month-1\n}\n\n//-------------------------------------------------------------------------------\n/*! \\brief Calculate the (annualized) atmosphere-surface box flux\n *  \\param Ca           Atmospheric CO2\n *  \\param cpoolscale   Scale the box C pool by this amount (1.0=none)\n *  \\return             Annual atmospheric C flux, Pg C/yr\n */\nunitval oceancsys::calc_annual_surface_flux( const unitval& Ca, const double cpoolscale ) const {\n    return unitval( ( calc_monthly_surface_flux( Ca, cpoolscale ) * As * 12.0 ) / 1e15, U_PGC_YR );\n}\n\n//-------------------------------------------------------------------------------\n/*! \\brief Convert the total carbon pool (PgC) to DIC\n *  \\param carbon       Carbon value to convert (Pg C)\n * Uses carbon pool, mass of carbon, density of seawater and volume of the box\n */\nunitval oceancsys::convertToDIC( const unitval carbon ) {\n\tconst double dic = ( ( carbon.value( U_PGC ) * 1e15 ) * ( 1.0/12.01 ) * (1.0/1027.0 ) * ( 1.0/volumeofbox ) ); // mol/kg\n\treturn unitval( dic * 1e6, U_UMOL_KG );\n}\n\n}\n", "meta": {"hexsha": "67f335091d02c8838dc07c268e446ddf11bd0804", "size": 13272, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ocean_csys.cpp", "max_stars_repo_name": "bvegawe/hector", "max_stars_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ocean_csys.cpp", "max_issues_repo_name": "bvegawe/hector", "max_issues_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ocean_csys.cpp", "max_forks_repo_name": "bvegawe/hector", "max_forks_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_forks_repo_licenses": ["ECL-2.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.2312703583, "max_line_length": 135, "alphanum_fraction": 0.5514617239, "num_tokens": 4082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.5645901881974525}}
{"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\n#include <Eigen/Dense>\n\n#include <dpMM/basemeasure.hpp>\n#include <dpMM/vmfPriorFull.hpp>\n\n/*\n * vmf base measure; uses monte carlo integration for p(x|hyperparams)\n * http://eprints.pascal-network.org/archive/00007206/01/iMMM.pdf\n */\ntemplate<typename T>\nclass vMFbase : public BaseMeasure<T>\n{\npublic:\n  vMFbase(const vMFpriorFull<T>& vmfPrior);\n  vMFbase(const vMFbase<T>& vmf);\n  ~vMFbase();\n\n  virtual BaseMeasure<T>* copy();\n  virtual vMFbase<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  vMFpriorFull<T> vmfPrior_;\n  vMF<T> vmf_;\nprivate:\n\n};\n\n// ------------------------- impl -------------------------------------------\n\ntemplate<typename T>\nvMFbase<T>::vMFbase(const vMFpriorFull<T>& vmfPrior)\n  : vmfPrior_(vmfPrior), vmf_(vmfPrior_.sample())\n{};\n\ntemplate<typename T>\nvMFbase<T>::vMFbase(const vMFbase<T>& base)\n  :  vmfPrior_(base.vmfPrior_), vmf_(base.vmf_) \n{};\n\n\ntemplate<typename T>\nvMFbase<T>::~vMFbase()\n{};\n\ntemplate<typename T>\nBaseMeasure<T>* vMFbase<T>::copy()\n{\n  return new vMFbase<T>(*this);\n};\n\ntemplate<typename T>\nvMFbase<T>* vMFbase<T>::copyNative()\n{\n  return new vMFbase<T>(*this);\n};\n\ntemplate<typename T>\nT vMFbase<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 vMFbase<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k)\n{ \n  vmfPrior_.getSufficientStatistics(x,z,k);\n  // needs current vmf since it samples tau|mu_old and then mu|tau\n  vmf_ = vmfPrior_.sampleFromPosterior(vmf_);\n};\n\ntemplate<typename T>\nvoid vMFbase<T>::posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const VectorXu& z, \n    uint32_t k)\n{\n};\n\ntemplate<typename T>\nvoid vMFbase<T>::sample()\n{\n};\n\ntemplate<typename T>\nvoid vMFbase<T>::print() const\n{\n  vmf_.print();\n};\n\ntemplate<typename T>\nT vMFbase<T>::logPdfUnderPrior() const\n{\n  return 0.;\n};\n\ntemplate<typename T>\nT vMFbase<T>::logPdfUnderPriorMarginalized() const\n{\n  return 0.;\n};\n\ntemplate<typename T>\nT vMFbase<T>::logPdfUnderPriorMarginalized(const Matrix<T,Dynamic,1>& x) \n{\n  // approximate the log pdf under the prior via monte carlo sampling\n  T logPdfMarg = 0;\n  uint32_t N = 3;\n//#pragma omp parallel for reduction(+:logPdfMarg)\n  for(uint32_t t=0; t<N; ++t)\n  {\n    vMF<T> vmf = vmfPrior_.sample();\n    logPdfMarg = logPdfMarg + vmf.logPdf(x);\n  }\n  return logPdfMarg/T(N);\n};\n\n", "meta": {"hexsha": "e7a5222a25470d5dc7b18c2d6665a70e15d24546", "size": 3664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/vmfBaseMeasure.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/vmfBaseMeasure.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/vmfBaseMeasure.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.4266666667, "max_line_length": 120, "alphanum_fraction": 0.6801310044, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5644647867448233}}
{"text": "/**\n * @file Model.hpp\n * @copyright Copyright (C) 2016-2021 Flexiv Ltd. All Rights Reserved.\n */\n\n#ifndef FLEXIVRDK_MODEL_HPP_\n#define FLEXIVRDK_MODEL_HPP_\n\n#include <Eigen/Eigen>\n#include <memory>\n#include <vector>\n\nnamespace flexiv {\n\nclass ModelHandler;\n\n/**\n * @class Model\n * @brief Integrated dynamics engine with robot model and dynamics.\n */\nclass Model\n{\npublic:\n    Model();\n    virtual ~Model();\n\n    /**\n     * @brief Update robot model using new joint states data\n     * @param[in] positions \\f$ \\mathbb{R}^{Dof \\times 1} \\f$ new link positions\n     * \\f$ q~[rad] \\f$\n     * @param[in] velocities \\f$ \\mathbb{R}^{Dof \\times 1} \\f$ new link\n     * velocities \\f$ \\dot{q}~[rad/s] \\f$\n     * @return True: success, false: failed\n     */\n    bool updateModel(const std::vector<double>& positions,\n        const std::vector<double>& velocities);\n\n    /**\n     * @brief Set tool configuration and add to robot model. The tool is\n     * installed on the flange\n     * @param[in] mass Total mass of the tool \\f$ [kg] \\f$\n     * @param[in] inertiaAtCom \\f$ \\mathbb{R}^{3 \\times 3} \\f$ inertia matrix of\n     * the tool at COM \\f$ [kg \\cdot m^2] \\f$\n     * @param[in] comInTcp \\f$ \\mathbb{R}^{3 \\times 1} \\f$ tool COM position in\n     * TCP frame \\f$ [m] \\f$\n     * @param[in] tcpInFlange \\f$ \\mathbb{R}^{3 \\times 1} \\f$ TCP position in\n     * flange frame \\f$ [m] \\f$\n     * @return True: success, false: failed\n     */\n    bool setTool(double mass, const Eigen::Matrix3d& inertiaAtCom,\n        const Eigen::Vector3d& comInTcp, const Eigen::Vector3d& tcpInFlange);\n\n    /**\n     * @brief Compute and get the Jacobian matrix at the frame of the specified\n     * link \\f$ i \\f$, expressed in the base frame.\n     * @param[in] linkName Name of the link to get Jacobian for\n     * @return \\f$ \\mathbb{R}^{6 \\times Dof} \\f$ Jacobian matrix, \\f$ ^0 J_i \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     * @note Available links can be found in the provided URDF. They are\n     * {\"base_link\", \"link1\", \"link2\", \"link3\", \"link4\", \"link5\", \"link6\",\n     * \"link7\", \"flange\"}, plus \"tool\" after setTool() is called\n     */\n    const Eigen::MatrixXd getJacobian(const std::string& linkName);\n\n    /**\n     * @brief Compute and get the time derivative of Jacobian matrix at the\n     * frame of the specified link \\f$ i \\f$, expressed in the base frame.\n     * @param[in] linkName Name of the link to get Jacobian derivative for\n     * @return \\f$ \\mathbb{R}^{6 \\times Dof} \\f$ Time derivative of Jacobian\n     * matrix, \\f$ ^0 \\dot{J_i} \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     * @note Available links can be found in the provided URDF. They are\n     * {\"base_link\", \"link1\", \"link2\", \"link3\", \"link4\", \"link5\", \"link6\",\n     * \"link7\", \"flange\"}, plus \"tool\" after setTool() is called\n     */\n    const Eigen::MatrixXd getJacobianDot(const std::string& linkName);\n\n    /**\n     * @brief Compute and get the mass matrix for the generalized coordinates,\n     * i.e. joint space\n     * @return \\f$ \\mathbb{S}^{Dof \\times Dof}_{++} \\f$ Symmetric positive\n     * definite mass matrix \\f$ M(q)~[kgm^2] \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     */\n    const Eigen::MatrixXd getMassMatrix();\n\n    /**\n     * @brief Compute and get the Coriolis/centripetal matrix for the\n     * generalized coordinates, i.e. joint space\n     * @return \\f$ \\mathbb{R}^{Dof \\times Dof} \\f$ Coriolis/centripetal matrix\n     * \\f$ C(q,\\dot{q}) \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     * @par Coriolis matrix factorization\n     * The factorization of the Coriolis matrix C is not unique, and this API\n     * is using the factorization method found in \"A new Coriolis matrix\n     * factorization\", 2012 by M. Bjerkend and K. Pettersen\n     */\n    const Eigen::MatrixXd getCoriolisMatrix();\n\n    /**\n     * @brief Compute and get the gravity force vector for the generalized\n     * coordinates, i.e. joint space\n     * @return \\f$ \\mathbb{R}^{Dof \\times 1} \\f$ gravity force vector \\f$\n     * g(q)~[Nm] \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     */\n    const Eigen::VectorXd getGravityForce();\n\n    /**\n     * @brief Compute and get the Coriolis force vector for the generalized\n     * coordinates, i.e. joint space\n     * @return \\f$ \\mathbb{R}^{Dof \\times 1} \\f$ Coriolis force vector \\f$\n     * c(q,\\dot{q})~[Nm] \\f$\n     * @note Use updateModel() to update robot states first before calling\n     * this function\n     */\n    const Eigen::VectorXd getCoriolisForce();\n\n    friend class RobotClientHandler;\n\nprivate:\n    std::unique_ptr<ModelHandler> m_handler;\n};\n\n} /* namespace flexiv */\n\n#endif /* FLEXIVRDK_MODEL_HPP_ */\n", "meta": {"hexsha": "3ca73184f9fe3cec05e8c8abbc6f7229347b3c67", "size": 4897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Model.hpp", "max_stars_repo_name": "flexivrobotics/flexiv_rdk", "max_stars_repo_head_hexsha": "18657334c9aeb84b5b5c8e52158f0b9180c578ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-10-09T02:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:57:32.000Z", "max_issues_repo_path": "include/Model.hpp", "max_issues_repo_name": "flexivrobotics/flexiv_rdk", "max_issues_repo_head_hexsha": "18657334c9aeb84b5b5c8e52158f0b9180c578ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T06:34:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T01:44:33.000Z", "max_forks_repo_path": "include/Model.hpp", "max_forks_repo_name": "flexivrobotics/flexiv_rdk", "max_forks_repo_head_hexsha": "18657334c9aeb84b5b5c8e52158f0b9180c578ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-03T07:53:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:17:02.000Z", "avg_line_length": 36.8195488722, "max_line_length": 80, "alphanum_fraction": 0.6373289769, "num_tokens": 1449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5644647811746072}}
{"text": "#ifndef KALMAN_TRACKER_HPP\n#define KALMAN_TRACKER_HPP\n\n#include <Eigen/Dense>\n#include <boost/any.hpp>\n\n#include <ros/ros.h>\n\n#include <kkl/math/gaussian.hpp>\n#include <kkl/alg/kalman_filter.hpp>\n\n\nnamespace hdl_people_tracking {\n\n/**\n * @brief Kalman filter-based tracker with a constant velocity model\n */\nclass KalmanTracker {\n  typedef kkl::alg::KalmanFilter<double, 6, 2, 3> KalmanFilter;\npublic:\n  /**\n   * @brief constructor\n   * @param id            tracker ID\n   * @param time          timestamp\n   * @param init_pos      initial position\n   * @param associated    associated detection\n   */\n  KalmanTracker(long id, const ros::Time& time, const Eigen::Vector3d& init_pos, boost::any associated = boost::any())\n    : id_(id),\n      correction_count(0),\n      init_time(time),\n      last_prediction_time(time),\n      last_correction_time(time),\n      last_associated(associated)\n  {\n    Eigen::Matrix<double, 6, 6> transition = Eigen::Matrix<double, 6, 6>::Identity();\n    Eigen::Matrix<double, 6, 2> control = Eigen::Matrix<double, 6, 2>::Zero();\n    Eigen::Matrix<double, 3, 6> measurement = Eigen::Matrix<double, 3, 6>::Zero();\n    measurement.block<3, 3>(0, 0).setIdentity() * 0.2;\n\n    Eigen::Matrix<double, 6, 6> process_noise = Eigen::Matrix<double, 6, 6>::Zero();\n    process_noise.topLeftCorner(3, 3) = Eigen::Matrix3d::Identity() * 0.03;\n    process_noise.bottomRightCorner(3, 3) = Eigen::Matrix3d::Identity() * 0.01;\n    Eigen::Matrix3d measurement_noise = Eigen::Matrix3d::Identity() * 0.2;\n\n    Eigen::Matrix<double, 6, 1> mean = Eigen::Matrix<double, 6, 1>::Zero();\n    mean.head<3>() = init_pos;\n    Eigen::Matrix<double, 6, 6> cov = Eigen::Matrix<double, 6, 6>::Identity() * 0.1;\n\n    kalman_filter.reset(new KalmanFilter(transition, control, measurement, process_noise, measurement_noise, mean, cov));\n  }\n  ~KalmanTracker() {}\n\n  using Ptr = std::shared_ptr<KalmanTracker>;\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\npublic:\n  /**\n   * @brief predict the current state\n   * @param time    current time\n   */\n  void predict(const ros::Time& time) {\n    double difftime = (time - last_prediction_time).toSec();\n    difftime = std::max(0.001, difftime);\n\n    kalman_filter->transitionMatrix(0, 3) = difftime;\n    kalman_filter->transitionMatrix(1, 4) = difftime;\n    kalman_filter->transitionMatrix(2, 5) = difftime;\n\n    kalman_filter->predict(Eigen::Matrix<double, 2, 1>::Zero());\n    last_prediction_time = time;\n\n    last_associated = boost::any();\n  }\n\n  /**\n   * @brief correct the state with an observation\n   * @param time    current time\n   * @param pos     observed position\n   * @param associated   associated detection\n   */\n  void correct(const ros::Time& time, const Eigen::Vector3d& pos, boost::any associated = boost::any()) {\n    kalman_filter->correct(pos);\n\n    correction_count++;\n    last_correction_time = time;\n    last_associated = associated;\n  }\n\npublic:\n  long id() const {\n    return id_;\n  }\n\n  ros::Duration age(const ros::Time& time) const {\n    return (time - init_time);\n  }\n\n  const ros::Time& lastCorrectionTime() const {\n    return last_correction_time;\n  }\n\n  const boost::any& lastAssociated() const {\n    return last_associated;\n  }\n\n  Eigen::Vector3d position() const {\n    return kalman_filter->mean.head<3>();\n  }\n\n  Eigen::Vector3d velocity() const {\n    return kalman_filter->mean.tail<3>();\n  }\n\n  Eigen::Matrix3d positionCov() const {\n    return kalman_filter->cov.block<3, 3>(0, 0);\n  }\n\n  Eigen::Matrix3d velocityCov() const {\n    return kalman_filter->cov.block<3, 3>(3, 3);\n  }\n\n  double squaredMahalanobisDistance(const Eigen::Vector3d& p) const {\n    return kkl::math::squaredMahalanobisDistance<double, 3>(\n          kalman_filter->mean.head<3>(),\n          kalman_filter->cov.block<3, 3>(0, 0),\n          p);\n  }\n\n  int correctionCount() const {\n    return correction_count;\n  }\n\nprivate:\n  long id_;\n\n  int correction_count;\n  ros::Time init_time;              // time when the tracker was initialized\n  ros::Time last_prediction_time;   // tiem when prediction was performed\n  ros::Time last_correction_time;   // time when correction was performed\n\n  boost::any last_associated;       // associated detection data\n\n  std::unique_ptr<KalmanFilter> kalman_filter;\n};\n\n}\n\n#endif // KALMANTRACKER_HPP\n", "meta": {"hexsha": "c801527be63ae571f1b89e28c183bc5cba45a663", "size": 4269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hdl_people_tracking/kalman_tracker.hpp", "max_stars_repo_name": "y-lai/hdl_people_tracking", "max_stars_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 207.0, "max_stars_repo_stars_event_min_datetime": "2018-03-10T14:56:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T07:32:53.000Z", "max_issues_repo_path": "include/hdl_people_tracking/kalman_tracker.hpp", "max_issues_repo_name": "y-lai/hdl_people_tracking", "max_issues_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-02-19T10:50:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T19:44:55.000Z", "max_forks_repo_path": "include/hdl_people_tracking/kalman_tracker.hpp", "max_forks_repo_name": "y-lai/hdl_people_tracking", "max_forks_repo_head_hexsha": "fb7ec799047b8ea833a175abd2599793b8966c24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 91.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T09:44:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T01:38:14.000Z", "avg_line_length": 28.46, "max_line_length": 121, "alphanum_fraction": 0.6697118763, "num_tokens": 1190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5644647762406112}}
{"text": "/*\nCopyright (c) 2017 Ryoichi Ishikawa. All rights reserved.\n\nThis software is released under the MIT License.\nhttp://opensource.org/licenses/mit-license.php\n*/\n\n#include \"FloorDetector.h\"\n#include <Eigen\\Eigen>\n#include <Eigen\\Core>\n#include <Eigen\\Dense>\n#include \"pch.h\"\nvoid FloorDetection(Platform::Array<unsigned char>^ buffer,int rowpitch,int height,double scale,double& HoloHeight, Eigen::Vector3d& floorpt) {\n\t//Buffer 2 Array\n\n\tfloat * imageData = (float*)buffer->Data;\n\t\n\t\n\t//get plane and Height\n\t//around 1m x 1m\n\tint dwidth = 1.0 / scale;\n\t//ransac\n\tint ransac_max = 100;\n\tstd::vector<Eigen::Vector3d> points;\n\tstd::vector<unsigned int> idces;\n\tEigen::Vector3d bestn, bestp;\n\tbestn << 1, 1, 1;\n\tunsigned int cnt = 0;\n\tint maxcnt = -1;\n\tfor (int x = rowpitch / sizeof(float) / 2;x<rowpitch / 2 / sizeof(float) + dwidth;x++) {\n\t\tfor (int y = height / 2;y<height / 2 + dwidth;y++) {\n\t\t\tEigen::Vector3d p_temp;\n\t\t\tp_temp << x*scale, y*scale, imageData[x + y*(rowpitch / sizeof(float))] * 3.0;\n\t\t\tpoints.push_back(p_temp);\n\t\t\tidces.push_back(cnt);\n\t\t\tcnt++;\n\t\t}\n\t}\n\tstd::vector<unsigned int> bestlist;\n\tfor (int ransac_t = 0;ransac_t<ransac_max;ransac_t++) {\n\t\trandom_shuffle(idces.begin(), idces.end());\n\t\tstd::vector<unsigned int> candlist;\n\t\tEigen::Vector3d v01, v02, nfloor, cand_p;\n\t\tcand_p = points.at(idces.at(0));\n\t\tv01 = points.at(idces.at(1)) - cand_p;\n\t\tv02 = points.at(idces.at(2)) - cand_p;\n\t\tnfloor = v01.cross(v02);\n\t\tnfloor = nfloor.normalized();\n\t\tint inlcnt = 0;\n\t\tfor (int idx = 3;idx<idces.size();idx++) {\n\t\t\tEigen::Vector3d targp = points.at(idces.at(idx)) - cand_p;\n\n\t\t\tdouble err = abs(targp.dot(nfloor));\n\t\t\tif (err<0.005) {\n\t\t\t\t//inlier\n\t\t\t\tcandlist.push_back(idces.at(idx));\n\t\t\t\tinlcnt++;\n\t\t\t}\n\t\t} if (maxcnt<inlcnt) {\n\t\t\tmaxcnt = inlcnt;\n\t\t\tbestn = nfloor;\n\t\t\tbestp = cand_p;\n\t\t\tbestlist = std::vector<unsigned int>(candlist);\n\t\t}\n\t}\n\t//plane fitting\n\t//solve least square problem\n\t//ax+by+z+d=0: ax+by+d=-z\n\tEigen::MatrixXd A(bestlist.size(), 3);\n\tEigen::VectorXd B(bestlist.size());\n\tfor (int idx = 0;idx<bestlist.size();idx++) {\n\t\tEigen::Vector3d targp = points.at(idces.at(idx));\n\t\tA(idx, 0) = targp(0);//x\n\t\tA(idx, 1) = targp(1);//y\n\t\tA(idx, 2) = 1;//1\n\t\tB(idx) = -targp(2);//-z\n\t}\n\tEigen::Vector3d ansX = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n\n\t//rendering: 1.0m upper from hololens - 2.0m lower from hololens (3.0m range)\n\t//hololens point (scale*(dwidth/2),scale*(dwidth/2),1.0)\n\t//ax+by+z+d=0: n<<a,b,1\n\tEigen::Vector3d phl;\n\tbestn << ansX(0), ansX(1), 1;\n\tbestp << scale*(rowpitch / sizeof(float) / 2), scale*(rowpitch / sizeof(float) / 2), -(ansX(0) + ansX(1))*scale*(rowpitch / sizeof(float) / 2) - ansX(2);\n\tbestn = bestn.normalized();\n\tif (bestn(2)<0)bestn = -bestn;\n\n\t//rendering: 1.0m upper from hololens - 2.0m lower from hololens (3.0m range)\n\t//hololens point (scale*(dwidth/2),scale*(dwidth/2),1.0)\n\tphl << scale*(rowpitch / sizeof(float) / 2), scale*(rowpitch / sizeof(float) / 2), 1.0;\n\tHoloHeight = -(phl - bestp).dot(bestn);\n\tfloorpt = -HoloHeight*bestn;//hololens 2 floor\n\n};", "meta": {"hexsha": "f8f9075d68d65b07220f5b2d47fcf90b5fb8801f", "size": 3063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HolographicSpatialMapping/cpp/FloorDetector.cpp", "max_stars_repo_name": "cln515/HoloLensRobotNav", "max_stars_repo_head_hexsha": "d802d8b27cb3fc8f340c2c20ea5b0c1dcf31a6fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-28T14:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:40:47.000Z", "max_issues_repo_path": "HolographicSpatialMapping/cpp/FloorDetector.cpp", "max_issues_repo_name": "cln515/HoloLensRobotNav", "max_issues_repo_head_hexsha": "d802d8b27cb3fc8f340c2c20ea5b0c1dcf31a6fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HolographicSpatialMapping/cpp/FloorDetector.cpp", "max_forks_repo_name": "cln515/HoloLensRobotNav", "max_forks_repo_head_hexsha": "d802d8b27cb3fc8f340c2c20ea5b0c1dcf31a6fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T08:30:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T13:35:47.000Z", "avg_line_length": 32.2421052632, "max_line_length": 154, "alphanum_fraction": 0.652301665, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201267, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5644363451875133}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-arithmetic Arithmetic functions\n\n    These functions provide scalar and SIMD algorithms for classical arithmetic operators and\n    functions of the C and C++ standard library. Other functions are also provided, in particular,\n    provision for saturated operations through the use of a @ref group-decorator.\n\n    All these functions can be included individually or all of them just by including\n    <boost/simd/arithmetic.hpp>\n\n     - **Possibly saturated operations**\n\n       The functors:\n       <center>\n         |                  |                 |                 |           |              |\n         |:----------------:|:---------------:|:---------------:|:---------:|:------------:|\n         | @ref abs         | @ref dec        | @ref dist       | @ref inc  | @ref minus   |\n         | @ref multiplies  | @ref plus       | @ref oneminus   | @ref sqr  | @ref toint   |\n         | @ref unary_minus | @ref unary_plus | @ref touint     |           |              |\n       </center>\n\n       can be decorated with `saturated_` (see @ref group-decorator). This decorator\n       has no effect on floating calls,  but on integer calls replaces the operation by its\n       saturated equivalent.\n\n       Typically: overflows will be replaced by the @ref Valmin/@ref Valmax proper value\n       instead of providing undefined behaviour (for signed integral types) or wrapping\n       modulo @ref Valmax + 1 (for unsigned ones).\n\n       Peculiarly saturated_(@ref abs) and saturated_(@ref dist) ensure that the result will\n       never be stricly negative (which is for instance the case of `abs(Valmin<T>())` for\n       @c T being any signed integral type).\n\n       @ref toint is a rather common operation as it converts floating number to signed integers\n       of the same bit size, nevertheless it probably is its saturated version you have to use\n       because it acts properly on large or not finite values, this is why an alias for\n       `saturated_(toint)` is provided as @ref ifix.\n\n       @par Example:\n\n          @snippet saturated_abs.cpp saturated_abs\n\n       @par Possible output:\n\n          @snippet saturated_abs.txt saturated_abs_results\n\n     - **Rounding operations**\n\n        <center>\n         |                 |                 |              |                  |\n         |:---------------:|:---------------:|:------------:|:----------------:|\n         | @ref ceil       |  @ref fix       | @ref floor   |  @ref iceil      |\n         | @ref ifix       |  @ref ifloor    | @ref iround  |  @ref itrunc     |\n         | @ref inearbyint |  @ref nearbyint | @ref round   |  @ref trunc      |\n        </center>\n\n          - The operations prefixed by 'i' return a value of the integral type iT\n          associated to the entry type. (If T is the entry type iT is\n          @c as_integer_t<T>)\n\n          - The other ones return the same type as the entry.\n\n        @par Example:\n\n          @snippet roundings.cpp roundings\n\n        @par Possible output:\n\n          @snippet roundings.txt roundings_results\n\n     - **Division operations**\n\n        @ref divides is the function associated to standard division. There is another one\n        which provides more flexibility, namely rounded divisions.\n\n        With two parameters @ref div and @ref divides are equivalent, but @ref div can admit\n        a first option parameter that modifies its behaviour.\n\n        <center>\n         | option          |          call           |      result similar to           |\n         |-----------------|-------------------------|----------------------------------|\n         | @ref ceil       |   div(ceil, a, b)       |      T(ceil(fT(a)/fT(b)))        |\n         | @ref floor      |   div(floor, a, b)      |      T(floor(fT(a)/fT(b)))       |\n         | @ref fix        |   div(fix, a, b)        |      T(fix(fT(a)/fT(b)))         |\n         | @ref round      |   div(round, a, b)      |      T(round(fT(a)/fT(b)))       |\n         | @ref nearbyint  |   div(nearbyint, a, b)  |      T(nearbyint(fT(a)/fT(b)))   |\n         | @ref iceil      |   div(iceil, a, b)      |      iT(iceil(fT(a)/fT(b)))      |\n         | @ref ifloor     |   div(ifloor, a, b)     |      iT(ifloor(fT(a)/fT(b)))     |\n         | @ref ifix       |   div(ifix, a, b)       |      iT(ifix(fT(a)/fT(b)))       |\n         | @ref iround     |   div(iround, a, b)     |      iT(iround(fT(a)/fT(b)))     |\n         | @ref inearbyint |   div(inearbyint, a, b) |      iT(inearbyint(fT(a)/fT(b))) |\n        </center>\n\n           - The option parameter is described in the above table where a and b are of type T,\n             fT is a supposed floating type associated to T (`as_floating_t<T>` if it\n             exists) and iT is the integer type associated to T (`as_integer_t<T>`).\n             (fT and iT are here only to support pseudo code description)\n\n           @par Example:\n\n              @snippet divisions.cpp divisions\n\n           @par Possible output:\n\n              @snippet divisions.txt divisions_results\n\n     - **Remainder operations**\n\n       @ref rem is the remainder functor providing same kind of facilities as @ref div\n\n       With two parameters rem(a, b) is equivalent to  @c rem(fix, a, b), but @c rem can admit\n       a first optional parameter that modifies its behaviour and moreover can use the\n       pedantic_ decorator to assure some limiting case values (see below).\n\n       The option parameter can be chosen between @ref ceil, @ref floor, @ref fix, @ref round,\n       @ref nearbyint and if @c opt is the option, the call:\n\n          @c rem(opt, a, b) is equivalent to  @c a-b*div(opt, a, b)\n\n       For floating entries the underlisted corner cases are handled in the following way:\n        - if  @c x is \\f$\\pm\\infty\\f$ , @ref Nan is returned\n        - if  @c x is \\f$\\pm0\\f$ and  @c y is not  @c 0  @c x is returned if  @c pedantic_\n          is used (else  @c 0: the sign bit is not preserved)\n        - if  @c y is \\f$\\pm0\\f$, @ref Nan is returned\n        - if either argument is a nan,  a nan is returned\n\n       @par Example:\n\n          @snippet remainders.cpp remainders\n\n       @par Possible output:\n\n          @snippet remainders.txt remainders_results\n\n     - **complex operations**\n\n       Boost.SIMD  does not provides complex number operations yet, but it will soon. So\n       the following functors that have a meaning as a restriction to real number of complex\n       functions, can be seen as a prequel:\n\n      <center>\n        |           |             |             |             |                 |\n        |:---------:|:-----------:|:-----------:|:-----------:|:---------------:|\n        | @ref arg  | @ref conj   | imag        | real        | @ref sqr_abs    |\n      </center>\n\n        For real entries @ref conj and real are identity, imag always 0,\n        @ref sqr_abs coincide with @ref sqr and @ref arg results are always in the\n        set \\f$\\{0, \\pi,  Nan\\}\\f$\n\n     - **Fused multiply-add operations**\n\n      <center>\n        |                 |              |               |                  |\n        |:---------------:|:------------:|:-------------:|:----------------:|\n        | @ref fma        | @ref fnma    |  @ref two_add | @ref two_split   |\n        | @ref fms        | @ref fnms    |  @ref two_prod|                  |\n      </center>\n\n      These operations take three parmeters and compute some \\f$\\pm a * b \\pm c \\f$\n      kind of expression, \"n\" standing for negate the result, \"a\" for add,\n      \"s\" for substract and \"m\" for multiply.\n\n      Correct fused multiply/add implies\n\n      - only one rounding\n      - no \"intermediate\" overflow\n\n      The functions of this family provide this, BUT ONLY each time it is reasonable\n      in terms of performance (mainly if the system has the hard\n      wired capability).\n\n      If you need \"real\" fused multiply-add capabilities in all circumstances in your own\n      code you can use @c pedantic_(fma) (although it can be expansive) or\n      @c std_(fma) (generally still more expansive) by using the decorators.\n\n      @ref two_add, @ref two_prod and @ref two_split are used internally in @c pedantic_(fma)\n      and can be useful in searching extra-accuracy in other circumstances as double-double\n      computations.\n\n      @c pedantic_(fma) is never used internally by Boost.SIMD\n\n     - **Standard operations**\n\n       The stdlibc++ provides them but only in scalar mode:\n\n       <center>\n         |               |                 |              |             |\n         |:-------------:|:---------------:|:------------:|:-----------:|\n         | @ref abs      | @ref ceil       | @ref floor   | @ref fma    |\n         | @ref hypot    | @ref max        | @ref maxnum  | @ref min    |\n         | @ref minnum   | @ref rem (%)    | @ref remquo  | @ref round  |\n         | @ref signbit  | @ref sqrt       |              |             |\n       </center>\n\n       Boost.SIMD provides its own scalar and simd versions, but allows\n       the use of the @c std_ @ref group-decorator to call the associated system\n       library function if the user needs it.\n\n     - **Other operations**\n\n       <center>\n         |              |                 |               |              |              |\n         |:------------:|:---------------:|:-------------:|:------------:|:------------:|\n         | @ref average | @ref clamp      | @ref meanof   | @ref minmod  | @ref sqr     |\n         | @ref sqrt    | @ref sqrt1pm1   | @ref tenpower | @ref tofloat |              |\n       </center>\n\n       @ref clamp is also provided in stdlibc++ for scalar mode, but only since C++17.\n       For now, in Boost.SIMD, the pedantic_  decorated version ensures standard\n       conformity for a Nan first parameter.\n  **/\n} }\n\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/arg.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/ceil.hpp>\n#include <boost/simd/function/clamp.hpp>\n#include <boost/simd/function/conj.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/dist.hpp>\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/extract.hpp>\n#include <boost/simd/function/fix.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/fms.hpp>\n#include <boost/simd/function/fnma.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/hypot.hpp>\n#include <boost/simd/function/iceil.hpp>\n#include <boost/simd/function/ifix.hpp>\n#include <boost/simd/function/ifloor.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/inearbyint.hpp>\n#include <boost/simd/function/iround.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/meanof.hpp>\n#include <boost/simd/function/min.hpp>\n#include <boost/simd/function/minmod.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/quadrant.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/rem.hpp>\n#include <boost/simd/function/remquo.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/round.hpp>\n#include <boost/simd/function/rsqrt.hpp>\n#include <boost/simd/function/signbit.hpp>\n#include <boost/simd/function/sqr_abs.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt1pm1.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/function/tenpower.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/function/touint.hpp>\n#include <boost/simd/function/trunc.hpp>\n#include <boost/simd/function/two_add.hpp>\n#include <boost/simd/function/two_prod.hpp>\n#include <boost/simd/function/two_split.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <boost/simd/function/unary_plus.hpp>\n\n\n#endif\n", "meta": {"hexsha": "681e47dc2b62118b5bab7844b4c5ac50b08b822f", "size": 12400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arithmetic.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/arithmetic.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/arithmetic.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": 43.3566433566, "max_line_length": 100, "alphanum_fraction": 0.5667741935, "num_tokens": 3013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.5643183521290769}}
{"text": "// Rotations conversion library\n// File: rot_conv.cpp\n// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>\n\n// Includes\n#include <rot_conv/rot_conv.h>\n#include <Eigen/Eigenvalues>\n#include <cmath>\n\n// Defines\n#define M_2PI (2.0*M_PI)\n\n// Rotations conversion namespace\nnamespace rot_conv\n{\n\t// ########################\n\t// #### Rotation types ####\n\t// ########################\n\n\t// Euler angles constants\n\tconst EulerAngles EulerAngles::Identity(0.0, 0.0, 0.0);\n\n\t// Fused angles constants\n\tconst FusedAngles FusedAngles::Identity(0.0, 0.0, 0.0, true);\n\n\t// Tilt angles constants\n\tconst TiltAngles TiltAngles::Identity(0.0, 0.0, 0.0);\n\n\t// ##########################################\n\t// #### Rotation checking and validation ####\n\t// ##########################################\n\n\t// Check and validate: Rotation matrix\n\tbool ValidateRotmat(Rotmat& R, double tol)\n\t{\n\t\t// Make a copy of the input\n\t\tRotmat Rorig = R;\n\n\t\t// Find the closest orthogonal matrix to the input rotation matrix\n\t\tRotmat nonOrth = R.transpose() * R;\n\t\tR *= Eigen::SelfAdjointEigenSolver<Rotmat>(nonOrth).operatorInverseSqrt();\n\n\t\t// Filter out invalid left hand coordinate systems\n\t\tif(R.determinant() < 0.0)\n\t\t\tR.setIdentity();\n\n\t\t// Return whether the rotation matrix was valid within the given tolerance\n\t\treturn (R - Rorig).isZero(tol);\n\t}\n\n\t// Check and validate: Quaternion\n\tbool ValidateQuat(Quat& q, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tQuat qorig = q;\n\n\t\t// Renormalise the quaternion\n\t\tdouble normsq = q.w()*q.w() + q.x()*q.x() + q.y()*q.y() + q.z()*q.z();\n\t\tif(normsq <= 0.0)\n\t\t{\n\t\t\tq.w() = 1.0;\n\t\t\tq.x() = q.y() = q.z() = 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble norm = sqrt(normsq);\n\t\t\tq.w() /= norm;\n\t\t\tq.x() /= norm;\n\t\t\tq.y() /= norm;\n\t\t\tq.z() /= norm;\n\t\t}\n\n\t\t// Make the quaternion unique\n\t\tif(unique && q.w() < 0.0)\n\t\t{\n\t\t\tq.w() = -q.w();\n\t\t\tq.x() = -q.x();\n\t\t\tq.y() = -q.y();\n\t\t\tq.z() = -q.z();\n\t\t}\n\n\t\t// Return whether the quaternion was valid within the given tolerance\n\t\treturn (fabs(q.w() - qorig.w()) <= tol && fabs(q.x() - qorig.x()) <= tol && fabs(q.y() - qorig.y()) <= tol && fabs(q.z() - qorig.z()) <= tol);\n\t}\n\n\t// Check and validate: Euler angles\n\tbool ValidateEuler(EulerAngles& e, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tEulerAngles eorig = e;\n\n\t\t// Wrap the pitch to (-pi,pi] and then collapse it to the [-pi/2,pi/2] interval\n\t\te.pitch += M_2PI*std::floor((M_PI - e.pitch) / M_2PI);\n\t\tif(fabs(e.pitch) > M_PI_2)\n\t\t{\n\t\t\te.yaw += M_PI;\n\t\t\te.pitch = (e.pitch >= 0.0 ? M_PI - e.pitch : -M_PI - e.pitch);\n\t\t\te.roll += M_PI;\n\t\t}\n\n\t\t// Make the positive and negative gimbal lock representations unique\n\t\tif(unique)\n\t\t{\n\t\t\tdouble spitch = sin(e.pitch);\n\t\t\tif(fabs(spitch - 1.0) <= tol)\n\t\t\t{\n\t\t\t\te.roll -= e.yaw;\n\t\t\t\te.yaw = 0.0;\n\t\t\t}\n\t\t\telse if(fabs(spitch + 1.0) <= tol)\n\t\t\t{\n\t\t\t\te.roll += e.yaw;\n\t\t\t\te.yaw = 0.0;\n\t\t\t}\n\t\t}\n\n\t\t// Wrap yaw and roll to (-pi,pi]\n\t\te.yaw += M_2PI*std::floor((M_PI - e.yaw) / M_2PI);\n\t\te.roll += M_2PI*std::floor((M_PI - e.roll) / M_2PI);\n\n\t\t// Return whether the Euler angles were valid within the given tolerance\n\t\treturn (fabs(e.yaw - eorig.yaw) <= tol && fabs(e.pitch - eorig.pitch) <= tol && fabs(e.roll - eorig.roll) <= tol);\n\t}\n\n\t// Check and validate: Fused angles\n\tbool ValidateFused(FusedAngles& f, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tFusedAngles forig = f;\n\n\t\t// Wrap the angles to (-pi,pi]\n\t\tf.fusedYaw += M_2PI*std::floor((M_PI - f.fusedYaw) / M_2PI);\n\t\tf.fusedPitch += M_2PI*std::floor((M_PI - f.fusedPitch) / M_2PI);\n\t\tf.fusedRoll += M_2PI*std::floor((M_PI - f.fusedRoll) / M_2PI);\n\n\t\t// Coerce the L1 norm\n\t\tdouble L1Norm = fabs(f.fusedPitch) + fabs(f.fusedRoll);\n\t\tif(L1Norm > M_PI_2)\n\t\t{\n\t\t\tdouble scale = M_PI_2 / L1Norm;\n\t\t\tf.fusedPitch *= scale;\n\t\t\tf.fusedRoll *= scale;\n\t\t}\n\n\t\t// Make the representation unique if required\n\t\tif(unique)\n\t\t{\n\t\t\tdouble spitch = sin(f.fusedPitch);\n\t\t\tdouble sroll = sin(f.fusedRoll);\n\t\t\tdouble sineSum = spitch*spitch + sroll*sroll;\n\t\t\tif(sineSum >= 1.0 - tol)\n\t\t\t\tf.hemi = true;\n\t\t\tL1Norm = fabs(f.fusedPitch) + fabs(f.fusedRoll);\n\t\t\tif(L1Norm <= tol && !f.hemi)\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t}\n\n\t\t// Return whether the fused angles were valid within the given tolerance\n\t\treturn (fabs(f.fusedYaw - forig.fusedYaw) <= tol && fabs(f.fusedPitch - forig.fusedPitch) <= tol && fabs(f.fusedRoll - forig.fusedRoll) <= tol && f.hemi == forig.hemi);\n\t}\n\n\t// Check and validate: Tilt angles\n\tbool ValidateTilt(TiltAngles& t, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tTiltAngles torig = t;\n\n\t\t// Wrap the angles to (-pi,pi]\n\t\tt.fusedYaw += M_2PI*std::floor((M_PI - t.fusedYaw) / M_2PI);\n\t\tt.tiltAxisAngle += M_2PI*std::floor((M_PI - t.tiltAxisAngle) / M_2PI);\n\t\tt.tiltAngle += M_2PI*std::floor((M_PI - t.tiltAngle) / M_2PI);\n\n\t\t// Handle the case of a negative tilt angle\n\t\tif(t.tiltAngle < 0.0)\n\t\t{\n\t\t\tt.tiltAxisAngle = (t.tiltAxisAngle > 0.0 ? -M_PI + t.tiltAxisAngle : M_PI + t.tiltAxisAngle);\n\t\t\tt.tiltAngle = -t.tiltAngle;\n\t\t}\n\n\t\t// Make the representation unique if required\n\t\tif(unique)\n\t\t{\n\t\t\tdouble ctilt = cos(t.tiltAngle);\n\t\t\tbool near0 = (fabs(ctilt - 1.0) <= tol);\n\t\t\tbool near180 = (fabs(ctilt + 1.0) <= tol);\n\t\t\tif(near0 || near180)\n\t\t\t\tt.tiltAxisAngle = 0.0;\n\t\t\tif(near180)\n\t\t\t\tt.fusedYaw = 0.0;\n\t\t}\n\n\t\t// Return whether the tilt angles were valid within the given tolerance\n\t\treturn (fabs(t.fusedYaw - torig.fusedYaw) <= tol && fabs(t.tiltAxisAngle - torig.tiltAxisAngle) <= tol && fabs(t.tiltAngle - torig.tiltAngle) <= tol);\n\t}\n\n\t// ###########################\n\t// #### Rotation equality ####\n\t// ###########################\n\n\t// Check equality: Rotation matrix\n\tbool RotmatEqual(const Rotmat& Ra, const Rotmat& Rb, double tol)\n\t{\n\t\t// Return whether none of the elements of the rotation matrices differ by more than the tolerance\n\t\treturn (Ra - Rb).isZero(tol);\n\t}\n\n\t// Check equality: Quaternion\n\tbool QuatEqual(const Quat& qa, const Quat& qb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the quaternions are the same\n\t\tbool isSame = (fabs(qa.w() - qb.w()) <= tol && fabs(qa.x() - qb.x()) <= tol && fabs(qa.y() - qb.y()) <= tol && fabs(qa.z() - qb.z()) <= tol);\n\t\tbool isOpp  = (fabs(qa.w() + qb.w()) <= tol && fabs(qa.x() + qb.x()) <= tol && fabs(qa.y() + qb.y()) <= tol && fabs(qa.z() + qb.z()) <= tol);\n\t\treturn (isSame || isOpp);\n\t}\n\n\t// Check equality: Euler angles\n\tbool EulerEqual(const EulerAngles& ea, const EulerAngles& eb, double tol)\n\t{\n\t\t// Convert both Euler angles to their unique representations\n\t\tEulerAngles eau = ea, ebu = eb;\n\t\tValidateEuler(eau, tol, true);\n\t\tValidateEuler(ebu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(eau.yaw - ebu.yaw) > M_PI)\n\t\t{\n\t\t\tif(eau.yaw > ebu.yaw)\n\t\t\t\tebu.yaw += M_2PI;\n\t\t\telse\n\t\t\t\teau.yaw += M_2PI;\n\t\t}\n\t\tif(fabs(eau.roll - ebu.roll) > M_PI)\n\t\t{\n\t\t\tif(eau.roll > ebu.roll)\n\t\t\t\tebu.roll += M_2PI;\n\t\t\telse\n\t\t\t\teau.roll += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the Euler angles are the same\n\t\treturn (fabs(eau.yaw - ebu.yaw) <= tol && fabs(sin(eau.pitch) - sin(ebu.pitch)) <= tol && fabs(eau.roll - ebu.roll) <= tol); // The pitch suffers from the numerical insensitivity of asin, so the sine thereof is checked\n\t}\n\n\t// Check equality: Fused angles\n\tbool FusedEqual(const FusedAngles& fa, const FusedAngles& fb, double tol)\n\t{\n\t\t// Convert both fused angles to their unique representations\n\t\tFusedAngles fau = fa, fbu = fb;\n\t\tValidateFused(fau, tol, true);\n\t\tValidateFused(fbu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(fau.fusedYaw - fbu.fusedYaw) > M_PI)\n\t\t{\n\t\t\tif(fau.fusedYaw > fbu.fusedYaw)\n\t\t\t\tfbu.fusedYaw += M_2PI;\n\t\t\telse\n\t\t\t\tfau.fusedYaw += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the fused angles are the same\n\t\treturn (fabs(fau.fusedYaw - fbu.fusedYaw) <= tol && fabs(sin(fau.fusedPitch) - sin(fbu.fusedPitch)) <= tol && fabs(sin(fau.fusedRoll) - sin(fbu.fusedRoll)) <= tol && fau.hemi == fbu.hemi); // The fused pitch and roll suffer from the numerical insensitivity of asin, so the sine's thereof are checked\n\t}\n\n\t// Check equality: Tilt angles\n\tbool TiltEqual(const TiltAngles& ta, const TiltAngles& tb, double tol)\n\t{\n\t\t// Convert both tilt angles to their unique representations\n\t\tTiltAngles tau = ta, tbu = tb;\n\t\tValidateTilt(tau, tol, true);\n\t\tValidateTilt(tbu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(tau.fusedYaw - tbu.fusedYaw) > M_PI)\n\t\t{\n\t\t\tif(tau.fusedYaw > tbu.fusedYaw)\n\t\t\t\ttbu.fusedYaw += M_2PI;\n\t\t\telse\n\t\t\t\ttau.fusedYaw += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the fused angles are the same\n\t\tdouble stilta = sin(tau.tiltAngle);\n\t\tdouble stiltb = sin(tbu.tiltAngle);\n\t\tdouble stiltasq = stilta*stilta;\n\t\tdouble stiltbsq = stiltb*stiltb;\n\t\treturn (fabs(tau.fusedYaw - tbu.fusedYaw) <= tol && fabs(stiltasq*cos(tau.tiltAxisAngle) - stiltbsq*cos(tbu.tiltAxisAngle)) <= tol && fabs(stiltasq*sin(tau.tiltAxisAngle) - stiltbsq*sin(tbu.tiltAxisAngle)) <= tol && fabs(cos(tau.tiltAngle) - cos(tbu.tiltAngle)) <= tol); // The tilt angle suffers from the numerical insensitivity of acos, so the cosine thereof is checked / The tilt axis angle has a singularity when the tilt angle is zero, so two geometrically relevant terms are checked instead of the tilt axis angle directly\n\t}\n\n\t// #########################\n\t// #### Yaw of rotation ####\n\t// #########################\n\n\t// Euler yaw of: Rotation matrix\n\tdouble EYawOfRotmat(const Rotmat& R)\n\t{\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(R.coeff(1,0), R.coeff(0,0));\n\t}\n\n\t// Fused yaw of: Rotation matrix\n\tdouble FYawOfRotmat(const Rotmat& R)\n\t{\n\t\t// Calculate, wrap and return the fused yaw\n\t\tdouble fusedYaw, trace = R.coeff(0,0) + R.coeff(1,1) + R.coeff(2,2);\n\t\tif(trace >= 0.0)\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(1,0) - R.coeff(0,1), 1.0 + trace);\n\t\telse if(R.coeff(2,2) >= R.coeff(1,1) && R.coeff(2,2) >= R.coeff(0,0))\n\t\t\tfusedYaw = 2.0*atan2(1.0 - R.coeff(0,0) - R.coeff(1,1) + R.coeff(2,2), R.coeff(1,0) - R.coeff(0,1));\n\t\telse if(R.coeff(1,1) >= R.coeff(0,0))\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(2,1) + R.coeff(1,2), R.coeff(0,2) - R.coeff(2,0));\n\t\telse\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(0,2) + R.coeff(2,0), R.coeff(2,1) - R.coeff(1,2));\n\t\tif(fusedYaw > M_PI) fusedYaw -= M_2PI;   // fusedYaw is now in [-2*pi,pi]\n\t\tif(fusedYaw <= -M_PI) fusedYaw += M_2PI; // fusedYaw is now in (-pi,pi]\n\t\treturn fusedYaw;\n\t}\n\n\t// Euler yaw of: Quaternion\n\tdouble EYawOfQuat(const Quat& q)\n\t{\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(q.w()*q.z() + q.x()*q.y(), 0.5 - (q.y()*q.y() + q.z()*q.z()));\n\t}\n\n\t// Fused yaw of: Quaternion\n\tdouble FYawOfQuat(const Quat& q)\n\t{\n\t\t// Calculate, wrap and return the fused yaw\n\t\tdouble fusedYaw = 2.0*atan2(q.z(), q.w()); // Output of atan2 is [-pi,pi], so this expression is in [-2*pi,2*pi]\n\t\tif(fusedYaw > M_PI) fusedYaw -= M_2PI;     // fusedYaw is now in [-2*pi,pi]\n\t\tif(fusedYaw <= -M_PI) fusedYaw += M_2PI;   // fusedYaw is now in (-pi,pi]\n\t\treturn fusedYaw;\n\t}\n\n\t// Fused yaw of: Euler angles\n\tdouble FYawOfEuler(const EulerAngles& e)\n\t{\n\t\t// Calculate and return the fused yaw of the rotation\n\t\treturn FYawOfRotmat(RotmatFromEuler(e));\n\t}\n\n\t// Euler yaw of: Fused angles\n\tdouble EYawOfFused(const FusedAngles& f)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth  = sin(f.fusedPitch);\n\t\tdouble sphi = sin(f.fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the cosine of the tilt angle alpha\n\t\tdouble calpha;\n\t\tif(crit >= 1.0)\n\t\t\tcalpha = 0.0;\n\t\telse\n\t\t\tcalpha = (f.hemi ? sqrt(1.0-crit) : -sqrt(1.0-crit));\n\n\t\t// Calculate the tilt axis gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble psigam = f.fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam);\n\t}\n\n\t// Euler yaw of: Tilt angles\n\tdouble EYawOfTilt(const TiltAngles& t)\n\t{\n\t\t// Precalculate trigonometric terms\n\t\tdouble psigam = t.fusedYaw + t.tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble cgam = cos(t.tiltAxisAngle);\n\t\tdouble sgam = sin(t.tiltAxisAngle);\n\t\tdouble calpha = cos(t.tiltAngle);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam);\n\t}\n\n\t// ##################################\n\t// #### Remove yaw from rotation ####\n\t// ##################################\n\n\t// Remove Euler yaw from: Rotation matrix\n\tvoid RotmatNoEYaw(const Rotmat& R, Rotmat& Rout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble cEYaw = cos(EYaw);\n\t\tdouble sEYaw = sin(EYaw);\n\n\t\t// Construct the Euler ZYX yaw component of the rotation\n\t\tRotmat REYawTrans;\n\t\tREYawTrans << cEYaw, sEYaw, 0.0, -sEYaw, cEYaw, 0.0, 0.0, 0.0, 1.0;\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tRout = REYawTrans * R;\n\t}\n\n\t// Remove fused yaw from: Rotation matrix\n\tvoid RotmatNoFYaw(const Rotmat& R, Rotmat& Rout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble cFYaw = cos(FYaw);\n\t\tdouble sFYaw = sin(FYaw);\n\n\t\t// Construct the fused yaw component of the rotation\n\t\tRotmat RFYawTrans;\n\t\tRFYawTrans << cFYaw, sFYaw, 0.0, -sFYaw, cFYaw, 0.0, 0.0, 0.0, 1.0;\n\n\t\t// Remove the fused yaw component of the rotation\n\t\tRout = RFYawTrans * R;\n\t}\n\n\t// Remove Euler yaw from: Quaternion\n\tvoid QuatNoEYaw(const Quat& q, Quat& qout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfQuat(q);\n\n\t\t// Construct the Euler ZYX yaw component of the rotation\n\t\tdouble hcEYaw = cos(0.5*EYaw);\n\t\tdouble hsEYaw = sin(0.5*EYaw);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tqout.w() = hcEYaw*q.w() + hsEYaw*q.z();\n\t\tqout.x() = hcEYaw*q.x() + hsEYaw*q.y();\n\t\tqout.y() = hcEYaw*q.y() - hsEYaw*q.x();\n\t\tqout.z() = hcEYaw*q.z() - hsEYaw*q.w();\n\t}\n\n\t// Remove fused yaw from: Quaternion\n\tvoid QuatNoFYaw(const Quat& q, Quat& qout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfQuat(q);\n\n\t\t// Construct the fused yaw component of the rotation\n\t\tdouble hcFYaw = cos(0.5*FYaw);\n\t\tdouble hsFYaw = sin(0.5*FYaw);\n\n\t\t// Remove the fused yaw component of the rotation\n\t\tqout.w() = hcFYaw*q.w() + hsFYaw*q.z();\n\t\tqout.x() = hcFYaw*q.x() + hsFYaw*q.y();\n\t\tqout.y() = hcFYaw*q.y() - hsFYaw*q.x();\n\t\tqout.z() = hcFYaw*q.z() - hsFYaw*q.w();\n\t}\n\n\t// Remove yaw from: Euler angles\n\tvoid EulerNoFYaw(const EulerAngles& e, EulerAngles& eout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfEuler(e);\n\n\t\t// Remove the fused yaw component of the rotation\n\t\teout.yaw = e.yaw - FYaw;\n\t\teout.pitch = e.pitch;\n\t\teout.roll = e.roll;\n\t}\n\n\t// Remove yaw from: Fused angles\n\tvoid FusedNoEYaw(const FusedAngles& f, FusedAngles& fout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfFused(f);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tfout.fusedYaw = f.fusedYaw - EYaw;\n\t\tfout.fusedPitch = f.fusedPitch;\n\t\tfout.fusedRoll = f.fusedRoll;\n\t\tfout.hemi = f.hemi;\n\t}\n\n\t// Remove yaw from: Tilt angles\n\tvoid TiltNoEYaw(const TiltAngles& t, TiltAngles& tout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfTilt(t);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\ttout.fusedYaw = t.fusedYaw - EYaw;\n\t\ttout.tiltAxisAngle = t.tiltAxisAngle;\n\t\ttout.tiltAngle = t.tiltAngle;\n\t}\n\n\t// ###########################\n\t// #### Rotation inverses ####\n\t// ###########################\n\n\t// Inverse: Rotation matrix\n\tvoid RotmatInv(const Rotmat& R, Rotmat& Rinv)\n\t{\n\t\t// Calculate the inverse of the rotation\n\t\tRinv = R.transpose();\n\t}\n\n\t// Inverse: Quaternion\n\tvoid QuatInv(const Quat& q, Quat& qinv)\n\t{\n\t\t// Calculate the inverse of the rotation\n\t\tqinv.w() = q.w();\n\t\tqinv.x() = -q.x();\n\t\tqinv.y() = -q.y();\n\t\tqinv.z() = -q.z();\n\t}\n\n\t// Inverse: Euler angles\n\tvoid EulerInv(const EulerAngles& e, EulerAngles& einv)\n\t{\n\t\t// Precalculate the required sin and cos values\n\t\tdouble cpsi = cos(e.yaw);\n\t\tdouble spsi = sin(e.yaw);\n\t\tdouble cth = cos(e.pitch);\n\t\tdouble sth = sin(e.pitch);\n\t\tdouble cphi = cos(e.roll);\n\t\tdouble sphi = sin(e.roll);\n\n\t\t// Calculate the sine of the inverse pitch angle\n\t\tdouble sthinv = -(cpsi*sth*cphi + spsi*sphi);\n\t\tsthinv = (sthinv >= 1.0 ? 1.0 : (sthinv <= -1.0 ? -1.0 : sthinv)); // Coerce sthinv to [-1,1]\n\n\t\t// Calculate the required inverse Euler angles representation\n\t\teinv.yaw = atan2(cpsi*sth*sphi - spsi*cphi, cpsi*cth);\n\t\teinv.pitch = asin(sthinv);\n\t\teinv.roll = atan2(spsi*sth*cphi - cpsi*sphi, cth*cphi);\n\t}\n\n\t// Inverse: Fused angles\n\tvoid FusedInv(const FusedAngles& f, FusedAngles& finv)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth  = sin(f.fusedPitch);\n\t\tdouble sphi = sin(f.fusedRoll);\n\n\t\t// Calculate the sine of the tilt angle alpha\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble salpha = (crit >= 1.0 ? 1.0 : sqrt(crit));\n\n\t\t// Calculate the tilt axis gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate trigonometric values\n\t\tdouble psigam = f.fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\n\t\t// Calculate the inverse fused pitch and roll\n\t\tdouble thinv = asin(-salpha*spsigam);\n\t\tdouble phinv = asin(-salpha*cpsigam);\n\n\t\t// Construct the inverse fused angles rotation\n\t\tfinv.fusedYaw = -f.fusedYaw;\n\t\tfinv.fusedPitch = thinv;\n\t\tfinv.fusedRoll = phinv;\n\t\tfinv.hemi = f.hemi;\n\t}\n\n\t// Inverse: Tilt angles\n\tvoid TiltInv(const TiltAngles& t, TiltAngles& tinv)\n\t{\n\t\t// Calculate the inverse tilt axis angle\n\t\tdouble gammainv = t.fusedYaw + t.tiltAxisAngle - M_PI;\n\t\tgammainv += M_2PI*std::floor((M_PI - gammainv) / M_2PI);\n\n\t\t// Construct the inverse tilt angles rotation\n\t\ttinv.fusedYaw = -t.fusedYaw;\n\t\ttinv.tiltAxisAngle = gammainv;\n\t\ttinv.tiltAngle = t.tiltAngle;\n\t}\n\n\t// ##########################\n\t// #### Vector rotations ####\n\t// ##########################\n\n\t// Rotate vector by: Rotation matrix\n\tVec3 RotmatRotVec(const Rotmat& R, const Vec3& v)\n\t{\n\t\t// Return the required rotated vector\n\t\treturn R*v;\n\t}\n\n\t// Rotate vector by: Quaternion\n\tVec3 QuatRotVec(const Quat& q, const Vec3& v)\n\t{\n\t\t// Precalculate an intermediate vector term\n\t\tdouble tx = 2.0*(q.y()*v.z() - v.y()*q.z());\n\t\tdouble ty = 2.0*(q.z()*v.x() - v.z()*q.x());\n\t\tdouble tz = 2.0*(q.x()*v.y() - v.x()*q.y());\n\n\t\t// Calculate and return the required vector\n\t\tVec3 vout = v;\n\t\tvout.x() += q.w()*tx + q.y()*tz - ty*q.z();\n\t\tvout.y() += q.w()*ty + q.z()*tx - tz*q.x();\n\t\tvout.z() += q.w()*tz + q.x()*ty - tx*q.y();\n\t\treturn vout;\n\t}\n\n\t// Rotate vector by: Euler angles\n\tVec3 EulerRotVec(const EulerAngles& e, const Vec3& v)\n\t{\n\t\t// Return the required rotated vector\n\t\treturn RotmatFromEuler(e)*v;\n\t}\n\n\t// Rotate vector by: Fused angles\n\tVec3 FusedRotVec(const FusedAngles& f, const Vec3& v)\n\t{\n\t\t// Return the required rotated vector\n\t\treturn RotmatFromFused(f)*v;\n\t}\n\n\t// Rotate vector by: Tilt angles\n\tVec3 TiltRotVec(const TiltAngles& t, const Vec3& v)\n\t{\n\t\t// Return the required rotated vector\n\t\treturn RotmatFromTilt(t)*v;\n\t}\n\n\t// ##############################\n\t// #### Pure yaw conversions ####\n\t// ##############################\n\n\t// Conversion: Pure yaw --> Rotation matrix\n\tvoid RotmatFromYaw(double yaw, Rotmat& R)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cyaw = cos(yaw);\n\t\tdouble syaw = sin(yaw);\n\n\t\t// Set the required rotation matrix\n\t\tR << cyaw, -syaw, 0.0, syaw, cyaw, 0.0, 0.0, 0.0, 1.0;\n\t}\n\n\t// Conversion: Pure yaw --> Quaternion\n\tvoid QuatFromYaw(double yaw, Quat& q)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble hpsi = 0.5*yaw;\n\t\tdouble chpsi = cos(hpsi);\n\t\tdouble shpsi = sin(hpsi);\n\n\t\t// Set the required quaternion orientation\n\t\tq.w() = chpsi;\n\t\tq.x() = 0.0;\n\t\tq.y() = 0.0;\n\t\tq.z() = shpsi;\n\t}\n\n\t// ############################################\n\t// #### Conversions from rotation matrices ####\n\t// ############################################\n\n\t//\n\t// Conversion: Rotation matrix --> Quaternion\n\t//\n\n\t// Conversion: Rotation matrix --> Quaternion\n\tvoid QuatFromRotmat(const Rotmat& R, Quat& q)\n\t{\n\t\t// Perform the required conversion in a numerically stable manner\n\t\tdouble r, s, t = R.coeff(0,0) + R.coeff(1,1) + R.coeff(2,2);\n\t\tif(t >= 0.0)\n\t\t{\n\t\t\tr = sqrt(1.0 + t);\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = 0.5*r;\n\t\t\tq.x() = s*(R.coeff(2,1) - R.coeff(1,2));\n\t\t\tq.y() = s*(R.coeff(0,2) - R.coeff(2,0));\n\t\t\tq.z() = s*(R.coeff(1,0) - R.coeff(0,1));\n\t\t}\n\t\telse if(R.coeff(2,2) >= R.coeff(1,1) && R.coeff(2,2) >= R.coeff(0,0))\n\t\t{\n\t\t\tr = sqrt(1.0 - (R.coeff(0,0) + R.coeff(1,1) - R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(1,0) - R.coeff(0,1));\n\t\t\tq.x() = s*(R.coeff(0,2) + R.coeff(2,0));\n\t\t\tq.y() = s*(R.coeff(2,1) + R.coeff(1,2));\n\t\t\tq.z() = 0.5*r;\n\t\t}\n\t\telse if(R.coeff(1,1) >= R.coeff(0,0))\n\t\t{\n\t\t\tr = sqrt(1.0 - (R.coeff(0,0) - R.coeff(1,1) + R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(0,2) - R.coeff(2,0));\n\t\t\tq.x() = s*(R.coeff(1,0) + R.coeff(0,1));\n\t\t\tq.y() = 0.5*r;\n\t\t\tq.z() = s*(R.coeff(2,1) + R.coeff(1,2));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tr = sqrt(1.0 + (R.coeff(0,0) - R.coeff(1,1) - R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(2,1) - R.coeff(1,2));\n\t\t\tq.x() = 0.5*r;\n\t\t\tq.y() = s*(R.coeff(1,0) + R.coeff(0,1));\n\t\t\tq.z() = s*(R.coeff(0,2) + R.coeff(2,0));\n\t\t}\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Euler angles\n\t//\n\n\t// Conversion: Rotation matrix --> Euler angles\n\tvoid EulerFromRotmat(const Rotmat& R, double& yaw, double& pitch, double& roll)\n\t{\n\t\t// Calculate the sine of the pitch angle\n\t\tdouble sth = -R.coeff(2,0);\n\t\tsth = (sth >= 1.0 ? 1.0 : (sth <= -1.0 ? -1.0 : sth)); // Coerce sth to [-1,1]\n\n\t\t// Calculate the required Euler angles\n\t\tyaw = atan2(R.coeff(1,0), R.coeff(0,0));\n\t\tpitch = asin(sth);\n\t\troll = atan2(R.coeff(2,1), R.coeff(2,2));\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Fused angles\n\t//\n\n\t// Conversion: Rotation matrix --> Fused angles (2D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = -R.coeff(2,0);\n\t\tdouble sphi   = R.coeff(2,1);\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Rotation matrix --> Fused angles (3D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedYaw, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tFusedFromRotmat(R, fusedPitch, fusedRoll);\n\t}\n\n\t// Conversion: Rotation matrix --> Fused angles (4D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedYaw, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tFusedFromRotmat(R, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere of the rotation\n\t\themi = (R.coeff(2,2) >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Tilt angles\n\t//\n\n\t// Conversion: Rotation matrix --> Tilt angles (2D)\n\tvoid TiltFromRotmat(const Rotmat& R, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(-R.coeff(2,0), R.coeff(2,1));\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = R.coeff(2,2);\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n\n\t// Conversion: Rotation matrix --> Tilt angles (3D)\n\tvoid TiltFromRotmat(const Rotmat& R, double& fusedYaw, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the fused yaw, tilt axis angle and tilt angle\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tTiltFromRotmat(R, tiltAxisAngle, tiltAngle);\n\t}\n\n\t// ######################################\n\t// #### Conversions from quaternions ####\n\t// ######################################\n\n\t//\n\t// Conversion: Quaternion --> Rotation matrix\n\t//\n\n\t// Conversion: Quaternion --> Rotation matrix\n\tvoid RotmatFromQuat(const Quat& q, Rotmat& R)\n\t{\n\t\t// Construct the required rotation matrix\n\t\tR << 1.0 - 2.0*(q.y()*q.y() + q.z()*q.z()),       2.0*(q.x()*q.y() - q.z()*q.w()),       2.0*(q.x()*q.z() + q.y()*q.w()),\n\t\t           2.0*(q.x()*q.y() + q.z()*q.w()), 1.0 - 2.0*(q.x()*q.x() + q.z()*q.z()),       2.0*(q.y()*q.z() - q.x()*q.w()),\n\t\t           2.0*(q.x()*q.z() - q.y()*q.w()),       2.0*(q.y()*q.z() + q.x()*q.w()), 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Euler angles\n\t//\n\n\t// Conversion: Quaternion --> Euler angles\n\tvoid EulerFromQuat(const Quat& q, double& yaw, double& pitch, double& roll)\n\t{\n\t\t// Calculate the sine of the pitch angle\n\t\tdouble sth = 2.0*(q.w()*q.y() - q.x()*q.z());\n\t\tsth = (sth >= 1.0 ? 1.0 : (sth <= -1.0 ? -1.0 : sth)); // Coerce sth to [-1,1]\n\n\t\t// Calculate the required Euler angles\n\t\tdouble qysq = q.y()*q.y();\n\t\tyaw = atan2(q.x()*q.y() + q.z()*q.w(), 0.5 - (qysq + q.z()*q.z()));\n\t\tpitch = asin(sth);\n\t\troll = atan2(q.y()*q.z() + q.x()*q.w(), 0.5 - (q.x()*q.x() + qysq));\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Fused angles\n\t//\n\n\t// Conversion: Quaternion --> Fused angles (2D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = 2.0*(q.y()*q.w() - q.x()*q.z());\n\t\tdouble sphi   = 2.0*(q.y()*q.z() + q.x()*q.w());\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Quaternion --> Fused angles (3D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedYaw, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tFusedFromQuat(q, fusedPitch, fusedRoll);\n\t}\n\n\t// Conversion: Quaternion --> Fused angles (4D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedYaw, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tFusedFromQuat(q, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere of the rotation\n\t\themi = (0.5 - (q.x()*q.x() + q.y()*q.y()) >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Tilt angles\n\t//\n\n\t// Conversion: Quaternion --> Tilt angles (2D)\n\tvoid TiltFromQuat(const Quat& q, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(q.w()*q.y() - q.x()*q.z(), q.w()*q.x() + q.y()*q.z());\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n\n\t// Conversion: Quaternion --> Tilt angles (3D)\n\tvoid TiltFromQuat(const Quat& q, double& fusedYaw, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the fused yaw, tilt axis angle and tilt angle\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tTiltFromQuat(q, tiltAxisAngle, tiltAngle);\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Z vector\n\t//\n\n\t// Conversion: Quaternion --> Z vector\n\tvoid ZVecFromQuat(const Quat& q, ZVec& z)\n\t{\n\t\t// Calculate the required Z vector\n\t\tz.x() = 2.0*(q.x()*q.z() - q.y()*q.w());\n\t\tz.y() = 2.0*(q.y()*q.z() + q.x()*q.w());\n\t\tz.z() = 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t}\n\n\t// #######################################\n\t// #### Conversions from Euler angles ####\n\t// #######################################\n\n\t// Conversion: Euler angles --> Rotation matrix\n\tRotmat RotmatFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Precalculate the trigonometric values\n\t\tdouble cpsi = cos(yaw);\n\t\tdouble spsi = sin(yaw);\n\t\tdouble cth  = cos(pitch);\n\t\tdouble sth  = sin(pitch);\n\t\tdouble cphi = cos(roll);\n\t\tdouble sphi = sin(roll);\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << cpsi*cth, cpsi*sth*sphi - spsi*cphi, cpsi*sth*cphi + spsi*sphi,\n\t\t     spsi*cth, spsi*sth*sphi + cpsi*cphi, spsi*sth*cphi - cpsi*sphi,\n\t\t         -sth,                  cth*sphi,                  cth*cphi;\n\t\treturn R;\n\t}\n\n\t// Conversion: Euler angles --> Quaternion\n\tQuat QuatFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Halve the Euler angles\n\t\tdouble hpsi = 0.5*yaw;\n\t\tdouble hth = 0.5*pitch;\n\t\tdouble hphi = 0.5*roll;\n\n\t\t// Precalculate the trigonometric values\n\t\tdouble hcpsi = cos(hpsi);\n\t\tdouble hspsi = sin(hpsi);\n\t\tdouble hcth  = cos(hth);\n\t\tdouble hsth  = sin(hth);\n\t\tdouble hcphi = cos(hphi);\n\t\tdouble hsphi = sin(hphi);\n\n\t\t// Calculate and return the required quaternion\n\t\treturn Quat(hcphi*hcth*hcpsi + hsphi*hsth*hspsi, hsphi*hcth*hcpsi - hcphi*hsth*hspsi, hcphi*hsth*hcpsi + hsphi*hcth*hspsi, hcphi*hcth*hspsi - hsphi*hsth*hcpsi);\n\t}\n\n\t// Conversion: Euler angles --> Fused angles\n\tFusedAngles FusedFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Construct a fused angles object\n\t\tFusedAngles f;\n\n\t\t// Calculation of the fused yaw in a numerically stable manner requires the complete rotation matrix representation\n\t\tRotmat R = RotmatFromEuler(yaw, pitch, roll);\n\n\t\t// Calculate the fused yaw\n\t\tf.fusedYaw = FYawOfRotmat(R);\n\n\t\t// Calculate the fused pitch\n\t\tf.fusedPitch = pitch; // ZYX Euler pitch is equivalent to fused pitch!\n\n\t\t// Calculate the fused roll\n\t\tdouble sphi = R.coeff(2,1);\n\t\tsphi = (sphi >= 1.0 ? 1.0 : (sphi <= -1.0 ? -1.0 : sphi)); // Coerce sphi to [-1,1]\n\t\tf.fusedRoll  = asin(sphi);\n\n\t\t// See which hemisphere we're in\n\t\tf.hemi = (R.coeff(2,2) >= 0.0);\n\n\t\t// Return the calculated fused angles\n\t\treturn f;\n\t}\n\n\t// Conversion: Euler angles --> Tilt angles\n\tTiltAngles TiltFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Calculation of the fused yaw in a numerically stable manner requires the complete rotation matrix representation\n\t\tRotmat R = RotmatFromEuler(yaw, pitch, roll);\n\n\t\t// Calculate the fused yaw\n\t\tt.fusedYaw = FYawOfRotmat(R);\n\n\t\t// Calculate the tilt axis angle\n\t\tt.tiltAxisAngle = atan2(-R.coeff(2,0), R.coeff(2,1));\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = R.coeff(2,2);\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\tt.tiltAngle = acos(calpha);\n\n\t\t// Return the calculated tilt angles\n\t\treturn t;\n\t}\n\n\t// Conversion: Euler angles --> Z vector\n\tZVec ZVecFromEuler(double pitch, double roll)\n\t{\n\t\t// Precalculate the trigonometric values\n\t\tdouble cth  = cos(pitch);\n\t\tdouble sth  = sin(pitch);\n\t\tdouble cphi = cos(roll);\n\t\tdouble sphi = sin(roll);\n\n\t\t// Calculate and return the required Z vector\n\t\treturn ZVec(-sth, cth*sphi, cth*cphi);\n\t}\n\n\t// #######################################\n\t// #### Conversions from fused angles ####\n\t// #######################################\n\n\t//\n\t// Conversion: Fused angles --> Rotation matrix\n\t//\n\n\t// Conversion: Fused angles (2D) --> Rotation matrix\n\tRotmat RotmatFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble calphabar = 1.0 - calpha;\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = calpha + calphabar*cgam*cgam;\n\t\tdouble B = calpha + calphabar*sgam*sgam;\n\t\tdouble C = calphabar*cgam*sgam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR <<    A,    C,    sth,\n\t\t        C,    B,  -sphi,\n\t\t     -sth, sphi, calpha;\n\t\treturn R;\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Rotation matrix\n\tRotmat RotmatFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the tilt angle alpha\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tsalpha = 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t\tsalpha = sqrt(crit);\n\t\t}\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble psigam = fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = cgam*cpsigam;\n\t\tdouble B = sgam*cpsigam;\n\t\tdouble C = cgam*spsigam;\n\t\tdouble D = sgam*spsigam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << A + D*calpha, B - C*calpha,  salpha*spsigam,\n\t\t     C - B*calpha, D + A*calpha, -salpha*cpsigam,\n\t\t          -sth,          sphi,    calpha;\n\t\treturn R;\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Quaternion\n\t//\n\n\t// Conversion: Fused angles (2D) --> Quaternion\n\tQuat QuatFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the tilt angle alpha\n\t\tdouble alpha = (crit >= 1.0 ? M_PI_2 : acos(sqrt(1.0 - crit)));\n\t\tdouble halpha = 0.5*alpha;\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\t\tdouble cgamma = cos(gamma);\n\t\tdouble sgamma = sin(gamma);\n\n\t\t// Return the required quaternion orientation (a rotation about (cgamma, sgamma, 0) by angle alpha)\n\t\treturn Quat(chalpha, cgamma*shalpha, sgamma*shalpha, 0.0); // Order: (w,x,y,z)\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Quaternion\n\tQuat QuatFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the tilt angle alpha\n\t\tdouble alpha;\n\t\tif(crit >= 1.0)\n\t\t\talpha = M_PI_2;\n\t\telse\n\t\t\talpha = acos(hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Evaluate the required intermediate angles\n\t\tdouble halpha = 0.5*alpha;\n\t\tdouble hpsi = 0.5*fusedYaw;\n\t\tdouble hgampsi = gamma + hpsi;\n\n\t\t// Precalculate trigonometric terms involved in the quaternion expression\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\t\tdouble chpsi = cos(hpsi);\n\t\tdouble shpsi = sin(hpsi);\n\t\tdouble chgampsi = cos(hgampsi);\n\t\tdouble shgampsi = sin(hgampsi);\n\n\t\t// Calculate and return the required quaternion\n\t\treturn Quat(chalpha*chpsi, shalpha*chgampsi, shalpha*shgampsi, chalpha*shpsi); // Order: (w,x,y,z)\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Euler angles\n\t//\n\n\t// Conversion: Fused angles (2D) --> Euler angles\n\tEulerAngles EulerFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = cgam*(1.0 - calpha);\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(A*sgam, calpha + A*cgam), fusedPitch, atan2(sphi, calpha));\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Euler angles\n\tEulerAngles EulerFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = 0.0;\n\t\tif(crit < 1.0)\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble psigam = fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam), fusedPitch, atan2(sphi, calpha));\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Tilt angles\n\t//\n\n\t// Conversion: Fused angles (2D) --> Tilt angles\n\tTiltAngles TiltFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate and return the tilt angles representation\n\t\tt.fusedYaw = 0.0;\n\t\tt.tiltAxisAngle = atan2(sth,sphi);\n\t\tt.tiltAngle = acos(calpha);\n\t\treturn t;\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Tilt angles\n\tTiltAngles TiltFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = 0.0;\n\t\tif(crit < 1.0)\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Calculate and return the tilt angles representation\n\t\tt.fusedYaw = fusedYaw;\n\t\tt.tiltAxisAngle = atan2(sth,sphi);\n\t\tt.tiltAngle = acos(calpha);\n\t\treturn t;\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Z vector\n\t//\n\n\t// Conversion: Fused angles --> Z vector\n\tZVec ZVecFromFused(double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth  = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = 0.0;\n\t\tif(crit < 1.0)\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Return the required Z vector\n\t\treturn ZVec(-sth, sphi, calpha);\n\t}\n\n\t// ######################################\n\t// #### Conversions from tilt angles ####\n\t// ######################################\n\n\t//\n\t// Conversion: Tilt angles --> Rotation matrix\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Rotation matrix\n\tRotmat RotmatFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble calphabar = 1.0 - calpha;\n\t\tdouble sth = salpha*sgam;\n\t\tdouble sphi = salpha*cgam;\n\t\tdouble A = calpha + calphabar*cgam*cgam;\n\t\tdouble B = calpha + calphabar*sgam*sgam;\n\t\tdouble C = calphabar*cgam*sgam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR <<    A,    C,    sth,\n\t\t        C,    B,  -sphi,\n\t\t     -sth, sphi, calpha;\n\t\treturn R;\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Rotation matrix\n\tRotmat RotmatFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble psigam = fusedYaw + tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = cgam*cpsigam;\n\t\tdouble B = sgam*cpsigam;\n\t\tdouble C = cgam*spsigam;\n\t\tdouble D = sgam*spsigam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << A + D*calpha, B - C*calpha,  salpha*spsigam,\n\t\t     C - B*calpha, D + A*calpha, -salpha*cpsigam,\n\t\t     -sgam*salpha,  cgam*salpha,  calpha;\n\t\treturn R;\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Quaternion\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Quaternion\n\tQuat QuatFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate the required angles\n\t\tdouble halpha = 0.5*tiltAngle;\n\n\t\t// Precalculate the required trigonometric values\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\t\tdouble cgamma = cos(tiltAxisAngle);\n\t\tdouble sgamma = sin(tiltAxisAngle);\n\n\t\t// Return the required quaternion orientation\n\t\treturn Quat(chalpha, shalpha*cgamma, shalpha*sgamma, 0.0); // Order: (w,x,y,z)\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Quaternion\n\tQuat QuatFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate the required angles\n\t\tdouble hpsi = 0.5*fusedYaw;\n\t\tdouble halpha = 0.5*tiltAngle;\n\t\tdouble hgampsi = tiltAxisAngle + hpsi;\n\n\t\t// Precalculate the required trigonometric values\n\t\tdouble chpsi = cos(hpsi);\n\t\tdouble shpsi = sin(hpsi);\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\t\tdouble chgampsi = cos(hgampsi);\n\t\tdouble shgampsi = sin(hgampsi);\n\n\t\t// Return the required quaternion orientation\n\t\treturn Quat(chalpha*chpsi, shalpha*chgampsi, shalpha*shgampsi, chalpha*shpsi); // Order: (w,x,y,z)\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Euler angles\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Euler angles\n\tEulerAngles EulerFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble sth = sgam*salpha;\n\t\tdouble sphi = cgam*salpha;\n\t\tdouble A = cgam*(1.0 - calpha);\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(A*sgam, calpha + A*cgam), asin(sth), atan2(sphi, calpha));\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Euler angles\n\tEulerAngles EulerFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble sth = sgam*salpha;\n\t\tdouble sphi = cgam*salpha;\n\t\tdouble psigam = fusedYaw + tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam), asin(sth), atan2(sphi, calpha));\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Fused angles\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Fused angles\n\tFusedAngles FusedFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Calculate and return the fused angles representation\n\t\treturn FusedFromTilt(0.0, tiltAxisAngle, tiltAngle);\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Fused angles\n\tFusedAngles FusedFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Construct a fused angles object\n\t\tFusedAngles f;\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\n\t\t// Calculate and return the fused angles representation\n\t\tf.fusedYaw = fusedYaw;\n\t\tf.fusedPitch = asin(salpha*sgam);\n\t\tf.fusedRoll = asin(salpha*cgam);\n\t\tf.hemi = (tiltAngle <= M_PI_2);\n\t\treturn f;\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Z vector\n\t//\n\n\t// Conversion: Tilt angles --> Z vector\n\tZVec ZVecFromTilt(double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate the required trigonometric terms\n\t\tdouble cgamma = cos(tiltAxisAngle);\n\t\tdouble sgamma = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\n\t\t// Return the required Z vector\n\t\treturn ZVec(-salpha*sgamma, salpha*cgamma, calpha);\n\t}\n\n\t// ####################################\n\t// #### Conversions from Z vectors ####\n\t// ####################################\n\n\t//\n\t// Conversion: Z vector --> Fused angles\n\t//\n\n\t// Conversion: Z vector --> Fused angles (2D)\n\tvoid FusedFromZVec(const ZVec& z, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = -z.x();\n\t\tdouble sphi   = z.y();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Z vector --> Fused angles (3D)\n\tvoid FusedFromZVec(const ZVec& z, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tFusedFromZVec(z, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere\n\t\themi = (z.z() >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Z vector --> Tilt angles\n\t//\n\n\t// Conversion: Z vector --> Tilt angles (2D)\n\tvoid TiltFromZVec(const ZVec& z, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(-z.x(), z.y());\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = z.z();\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n}\n// EOF", "meta": {"hexsha": "282627dfce949983ca10f53f9028dc4e8b62a864", "size": 45374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rot_conv/src/rot_conv.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": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-11-02T03:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-02T19:40:15.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rot_conv/src/rot_conv.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/util/rot_conv/src/rot_conv.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": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-16T02:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-24T14:06:35.000Z", "avg_line_length": 30.1288180611, "max_line_length": 530, "alphanum_fraction": 0.6324547097, "num_tokens": 15208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5643183426637195}}
{"text": "#include <Rcpp.h>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"bckPotentialsAsymp.hpp\"\n#include \"interp_1d.hpp\"\n\nusing namespace Rcpp;\nusing namespace std;\nusing namespace boost::numeric::odeint ;\n\n// The stiff algorith only accepts these data types\ntypedef boost::numeric::ublas::vector< long double > state_type;\ntypedef boost::numeric::ublas::matrix< long double > matrix_type;\n\nstruct VQCD\n{\n    long double x;\n    long double tau0;\n    long double W0;\n    long double V0;\n    long double lambda0;\n    VQCD():x(1.0), tau0(1.0), W0(12.0/11), V0(12.0), lambda0(8.0 * M_PI * M_PI){}\n    VQCD(long double xi, long double ti, long double w0, long double v0, long double l0):x(xi),tau0(ti), W0(w0), V0(v0), lambda0(l0){}\n    void operator()(const state_type &X , state_type &dXdt , long double A)\n    {\n        long double e2A = exp(2.0 * A);\n        long double kNr = k(X[1], x) ;\n        long double dkNr = dk(X[1],x);\n        long double vf = Vf(X[1], X[2], x, W0) ;\n        long double dvfdl = dVfdl(X[1], X[2], x, W0) ;\n        long double dlogvfdt = dLogVfdt(X[2], x, W0) ;\n        long double dlogvfdl = dLogVfdl(X[1], x, W0) ;\n        long double G = sqrt(1.0 + kNr * pow(X[4], 2.0) / ( e2A * pow(X[0], 2.0 ) ) ) ;\n        // 1st Aeom in Mathematica Notebook \n        dXdt[0] = - X[0] + (4.0 / 9.0) * X[0] * pow(X[3], 2.0) / pow(X[1], 2.0) + x * e2A * pow(X[0], 3.0) * kNr * vf * pow(X[4], 2.0) * G / ( 6.0 * ( e2A * pow( X[0], 2.0 ) + kNr * pow(X[4], 2.0) ) ) ;\n        dXdt[1] = X[3] ;\n        dXdt[2] = X[4] ;\n        // 2nd Aeom in Mathematica Notebook\n        dXdt[3] = - (3.0 / 8) * e2A * pow( X[0] * X[1], 2.0 ) * dVg(X[1], V0, lambda0) + 9.0 * pow(X[1], 2.0) / X[3] \\\n        - 3 * e2A * pow(X[0] * X[1], 2.0) * Vg(X[1], V0, lambda0) / ( 4.0 * X[3] ) - 5.0 * X[3] + pow( X[3], 2.0) / X[1] \\\n        + ( 4.0 / 9) * pow(X[3], 3.0) / pow(X[1], 2.0) + 3 * e2A * x * pow( X[0] * X[1], 2.0) * vf / (4.0 * X[3] * G) \\\n        + x * kNr * vf * X[3] * pow( X[4], 2.0) / ( 6.0 * G) + 3.0 * x * vf * pow(X[1] * X[4], 2.0) * dkNr / ( 16.0 * G) \\\n        + 3 * e2A * x * pow(X[0] * X[1], 2.0) * dvfdl / ( 8.0 * G) + 3.0 * x * kNr * pow(X[1] * X[4], 2.0) * dvfdl / ( 8.0 * G) ;\n        // 3rd Aeom in Mathematica Notebook\n        dXdt[4] = - 4.0 * X[4] + ( 4.0 / 9 ) * pow( X[3] / X[1] , 2.0) * X[4] - 4.0 * kNr * pow(X[4], 3.0) / ( e2A * X[0] * X[0]) \\\n        + e2A * x * pow( X[0], 2.0 ) * kNr * vf * pow( X[4], 3.0) * G / ( 6 * ( e2A * pow(X[0],2.0) + kNr * pow(X[4], 2.0) ) )\\\n        - X[3] * X[4] * dkNr / kNr - X[3] * pow(X[4], 3.0) * dkNr / (2.0 * e2A * pow( X[0], 2.0) ) \\\n        + e2A * pow(X[0], 2.0) * dlogvfdt / kNr + pow(X[4], 2.0) * dlogvfdt - X[3] * X[4] * dlogvfdl \\\n        - kNr * X[3] * pow(X[4], 3.0) * dlogvfdl / ( e2A * pow(X[0], 2.0) ) ;\n    }\n};\n\n// [[Rcpp::export]]\nList solveHVQCD(long double xi = 1, long double ti = 1, long double W0 = 12/11.0, long double V0 = 12, long double lambda0 = 8 * M_PI * M_PI)\n{\n    // Computes dr/dA, tau, lambda, dtau/dA and dlambda/dA given x and tau0\n    // x - long double. Physically it means x = N_f / N_c when N_f, N_c -> inf but with fixed coefficient\n    // tau0 - > parameter related with the exponential behaviour of the tachyon in the IR\n    // Returns a list with quantitites that depend on A, mq and zIR\n    \n    // Create a vectors containing the values of the fields\n    vector< long double > Z, AA, dZ, L, T;\n    // Boundary conditions in the IR\n    long double zIR = log(70.0 / ti) / CI(xi, W0, V0, lambda0) ;\n    long double aIR = AIR(zIR, V0, lambda0) ;\n    AA.push_back(aIR) ;\n    long double lambdair = lambdaIR(zIR, lambda0) ;\n    L.push_back(lambdair);\n    long double tauir = 70.0 ;\n    T.push_back(tauir) ;\n    // dA/dz at zIR\n    long double daIR =  173.0 / ( 1728.0 * pow(zIR, 3.0)) + 0.5 /zIR - 2.0 * zIR  ;\n    // dtau/dz at zIR\n    long double dtauir = CI(xi, W0, V0, lambda0) * tauir ;\n    // dlambda/dz at zIR. Expression got from eom2 in Mathematica notebook.\n    long double dlambdair = sqrt(1.5) * lambdair * sqrt( 6 * pow(daIR, 2.0) + exp( 2.0 * aIR) * xi * Vf(lambdair,tauir, xi, W0) \\\n         / (2.0 * sqrt(1+ dtauir * dtauir * k(lambdair, xi) / exp(2 * aIR ) ) ) - 0.5 * exp( 2.0 * aIR) * Vg(lambdair, V0, lambda0) );\n    long double dzIR = 1.0 / daIR ;\n    dZ.push_back(dzIR) ;\n    dlambdair = dlambdair / daIR;\n    dtauir = dtauir / daIR;\n    // Define the type of the state. We have X = {dz, lambda, tau, dlambda, dtau}\n    state_type X (5);\n    X <<= dzIR, lambdair, tauir, dlambdair, dtauir;\n    // Now compute the starting value of dX\n    cout << \"Solving HVQCD for x = \" << xi << \", tau0 = \" << ti << \", W0 = \" << W0 << \", V0 = \" << V0 << \", lambda0 = \" << lambda0 << endl;\n    long double Amax = 100.0;\n    long double h = 0.1 ;\n    dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type > > > stepper;\n    stepper.initialize( X , aIR , h );\n    long double A = aIR;\n    while ( A < Amax )\n    {\n        stepper.do_step( VQCD(xi, ti, W0, V0, lambda0) ) ; \n        X = stepper.current_state();\n        A = stepper.current_time();\n        //cout << A << '\\t' <<  X(0) << '\\t' <<  X(1) << '\\t' <<  X(2) << endl;\n        AA.push_back(A) ;\n        dZ.push_back(X(0)) ;\n        L.push_back(X(1)) ;\n        T.push_back(X(2)) ;\n    }\n    double mq = X(4) / X(0) ;\n    Spline_Interp<long double> dzfun = Spline_Interp<long double>(AA, dZ);\n    int n = AA.size() ;\n    long double zmin = zIR + dzfun.integrate(AA[ n - 1]) ;\n    for(int i = 0; i < n; i++)\n    {\n        Z.push_back( zIR + dzfun.integrate(AA[i]) - zmin ) ;\n    }\n    // We need to reverse the lists because later\n    // we will use them to compute the spectra of vector mesons.\n    reverse(AA.begin(),AA.end()) ;\n    reverse(Z.begin(),Z.end()) ;\n    reverse(L.begin(),L.end()) ;\n    reverse(T.begin(),T.end()) ;\n    // Return A, Z, L(A), T(A), zIR and mq\n    return List::create(Named(\"z\") = Z, Named(\"A\") = AA, Named(\"lambda\") = L, Named(\"tau\") = T, Named(\"zIR\") = zIR - zmin, Named(\"mq\") = mq );\n} ;", "meta": {"hexsha": "2d63ba0809985ba5cff64769a8a761972036eb9a", "size": 6179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/VQCD.cpp", "max_stars_repo_name": "artur-amorim/HVQCD", "max_stars_repo_head_hexsha": "defee0d2c0f32ad93003275cbe93c37657f17a06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/VQCD.cpp", "max_issues_repo_name": "artur-amorim/HVQCD", "max_issues_repo_head_hexsha": "defee0d2c0f32ad93003275cbe93c37657f17a06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-14T18:04:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-14T18:04:18.000Z", "max_forks_repo_path": "src/VQCD.cpp", "max_forks_repo_name": "artur-amorim/HVQCD", "max_forks_repo_head_hexsha": "defee0d2c0f32ad93003275cbe93c37657f17a06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8306451613, "max_line_length": 202, "alphanum_fraction": 0.5403787021, "num_tokens": 2505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778823, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.5642701829475756}}
{"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_GAMMALN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-euler\n    This function object computes the natural logarithm of the absolute\n    value of the Gamma function:\n     \\f$\\displaystyle \\log |\\Gamma(x)|\\f$\n\n\n    @par Header <boost/simd/function/gammaln.hpp>\n\n    @par Notes\n\n    - The accuracy of the function is not uniformly good for negative entries\n      The algorithm used is currently an adapted vesion of the cephes one.\n      For better accuracy in the negative entry case, one can use the extern\n      boost_math gammaln function but at a loss of speed.\n\n      However, as stated in boost math:\n\n      \"While the relative errors near the positive roots of lgamma are very low,\n       the  function has an infinite number of irrational roots for negative arguments:\n       very close to these negative roots only a low absolute error can be guaranteed.\"\n\n    - The call `gammaln(x, sgn)` also returns the sign of gamma in the output parameter @c sgn.\n\n       Be aware that POSIX version of @c lgamma is not thread-safe: each execution of the function\n       stores the sign of the gamma function of @c x in the static external variable signgam.\n\n       boost.simd also provides @ref signgam which independantly computes the sign.\n\n    @par Decorators\n\n      - std_ fcalls @c std::lgamma\n\n    @see gamma, signgam\n\n    @par Example:\n\n      @snippet gammaln.cpp gammaln\n\n    @par Possible output:\n\n      @snippet gammaln.txt gammaln\n  **/\n  IEEEValue gammaln(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/gammaln.hpp>\n#include <boost/simd/function/simd/gammaln.hpp>\n\n#endif\n", "meta": {"hexsha": "d252477098150d1af5591e19635bf403f48d477d", "size": 2131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/gammaln.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/gammaln.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/gammaln.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 30.4428571429, "max_line_length": 100, "alphanum_fraction": 0.6527451901, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.564262805932434}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/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/triangular.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/conj.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::triangular_matrix<double, ublas::upper, ublas::column_major> triangular_matrix;\n  typedef typename vector::size_type size_type;\n\n  rand_normal<double>::reset();\n  size_type n=128;\n  triangular_matrix A(n, n);\n  for (size_type j=0; j<n; ++j) {\n    for (size_type i=0; i<=j; ++i)\n      A(i, j)=rand_normal<double>::get();\n  }\n  {\n    vector lambda(n);\n    matrix vr(n, n);\n    triangular_matrix A_bak(A);\n    int info=lapack::spev('V', A, lambda, vr);\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(v);\n   \tblas::spmv(1., A_bak, v, -lambda(i), res);\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\n", "meta": {"hexsha": "26cd9e932bf30c1892cc00f1652f3ecc2d1a05f0", "size": 1866, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lapack/spev.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/spev.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/spev.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.7368421053, "max_line_length": 96, "alphanum_fraction": 0.6806002144, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619634, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5642467106409886}}
{"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_EULER_FUNCTIONS_SCALAR_ERFC_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_ERFC_HPP_INCLUDED\n\n#include <nt2/euler/functions/erfc.hpp>\n#include <nt2/euler/functions/details/erf_kernel.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/twothird.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT  ( erfc_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(nt2::is_nan(a0)) return a0;\n      #endif\n      A0 x =  nt2::abs(a0);\n      A0 xx =  nt2::sqr(x);\n      A0 z =  nt2::Zero<A0>();\n      if(x <= A0(0.0000000001))\n      {\n        z = nt2::oneminus(x*nt2::Two<A0>()/nt2::sqrt(nt2::Pi<A0>()));\n      }\n      else if (x< A0(0.65))\n      {\n        z = nt2::oneminus(x*details::erf_kernel<A0>::erf1(xx));\n      }\n      else if(x< A0(2.2))\n      {\n        z = nt2::exp(-xx)*details::erf_kernel<A0>::erfc2(x);\n      }\n      else if(x< A0(6))\n      {\n        z = nt2::exp(-xx)*details::erf_kernel<A0>::erfc3(x);\n      }\n      else\n      {\n        z = nt2::exp(-xx)*details::erf_kernel<A0>::erfc4(rec(x));\n      }\n      return (a0 < 0.0) ? 2.0-z : z;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( erfc_, tag::cpu_\n                              , (A0)\n                              , ((scalar_<single_<A0> >))\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 x =  nt2::abs(a0);\n      A0 r1 = nt2::Zero<A0>();\n      A0 z =  x/oneplus(x);\n      if (x < Twothird<A0>())\n      {\n        r1 = details::erf_kernel<A0>::erfc3(z);\n      }\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      else if (BOOST_UNLIKELY(x == Inf<A0>()))\n      {\n        r1 = Zero<A0>();\n      }\n      #endif\n      else\n      {\n       z-= 0.4f;\n        r1 = exp(-sqr(x))*details::erf_kernel<A0>::erfc2(z);\n      }\n      return (a0 < 0.0f) ? 2.0f-r1 : r1;\n    }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "9e1868ac6b96d1c8b9124572e68bcb2a5dadec13", "size": 3166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erfc.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/euler/include/nt2/euler/functions/scalar/erfc.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/euler/include/nt2/euler/functions/scalar/erfc.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7818181818, "max_line_length": 80, "alphanum_fraction": 0.5397978522, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5642466886486526}}
{"text": "#ifndef _QUADSOLVE_HPP_\n#define _QUADSOLVE_HPP_\n\n/*\n   FILE uquadprog.hh\n\nNOTE: this is a modified of QuadProg++ package, originally developed by \nLuca Di Gaspero, working with ublas data structures. \n\nThe quadprog_solve() function implements the algorithm of Goldfarb and Idnani \nfor the solution of a (convex) Quadratic Programming problem\nby means of a dual method.\n\nThe problem is in the form:\n\nmin 0.5 * x G x + g0 x\ns.t.\nCE^T x + ce0 = 0\nCI^T x + ci0 >= 0\n\nThe matrix and vectors dimensions are as follows:\nG: n * n\ng0: n\n\nCE: n * p\nce0: p\n\nCI: n * m\nci0: m\n\nx: n\n\nThe function will return the cost of the solution written in the x vector or\nstd::numeric_limits::infinity() if the problem is infeasible. In the latter case\nthe value of the x vector is not correct.\n\nReferences: D. Goldfarb, A. Idnani. A numerically stable dual method for solving\nstrictly convex quadratic programs. Mathematical Programming 27 (1983) pp. 1-33.\n\nNotes:\n1. pay attention in setting up the vectors ce0 and ci0. \nIf the constraints of your problem are specified in the form \nA^T x = b and C^T x >= d, then you should set ce0 = -b and ci0 = -d.\n2. The matrix G is modified within the function since it is used to compute\nthe G = L^T L cholesky factorization for further computations inside the function. \nIf you need the original matrix G you should make a copy of it and pass the copy\nto the function.\n\nAuthor: Angelo Furfaro\nDEIS - University of Calabria, Italy\na.furfaro@deis.unical.it\nhttp://www.lis.deis.unical.it/~furfaro\n\nThe author will be grateful if the researchers using this software will\nacknowledge the contribution of this modified function and of Di Gaspero's\noriginal version in their research papers.\n\n\nLICENSE\n\nCopyright (2008) Angelo Furfaro\nCopyright (2006) Luca Di Gaspero\n\n\nThis file is a porting of QuadProg++ routine, originally developed\nby Luca Di Gaspero, exploiting uBlas data structures for vectors and\nmatrices instead of native C++ array.\n\nuquadprog is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nuquadprog is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with uquadprog; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n*/\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nusing namespace boost::numeric::ublas;\n\n\nvoid cholesky_decomposition(matrix<double> & A);\nvoid backward_elimination(matrix<double>& U,vector<double>& x, vector<double>& y);\nvoid forward_elimination(matrix<double>& L, vector<double>& y, vector<double>& b);\nvoid cholesky_solve(matrix<double>& L, vector<double> & x, vector<double> & b);\n\ndouble distance(double a, double b);\nvoid compute_d(vector<double> &d, matrix<double>& J, vector<double>& np);\nvoid update_z(vector<double>& z, matrix<double>& J, vector<double>& d,  int iq);\nvoid update_r(matrix<double>& R, vector<double> &r, vector<double> &d, int iq);\nbool add_constraint(matrix<double>& R, matrix<double>& J, vector<double>& d, int& iq, double& R_norm);\nvoid delete_constraint(matrix<double>& R, matrix<double>& J, vector<int>& A, vector<double>& u,  int p, int& iq, int l);\n\n\ninline double solve_quadprog( matrix<double> & G,  vector<double> & g0,  \n        const matrix<double> & CE, const vector<double> & ce0,  \n        const matrix<double> & CI, const vector<double> & ci0, \n        vector<double>& x)\n{\n    int i, j, k, l; /* indices */\n    int ip, me, mi;\n    int n=g0.size();  int p=ce0.size();  int m=ci0.size();  \n    matrix<double> R(G.size1(),G.size2()), J(G.size1(),G.size2());\n\n    vector<double> s(m+p), z(n), r(m + p), d(n),  np(n), u(m + p);\n    vector<double> x_old(n), u_old(m + p);\n    double f_value, psi, c1, c2, sum, ss, R_norm;\n    const double inf = std::numeric_limits<double>::infinity();\n    double t, t1, t2; /* t is the step lenght, which is the minimum of the partial step length t1 \n                       * and the full step length t2 */\n    vector<int> A(m + p), A_old(m + p), iai(m + p);int q;\n    int iq, iter = 0;\n    bool iaexcl[m + p];\n\n    me = p; /* number of equality constraints */\n    mi = m; /* number of inequality constraints */\n    q = 0;  /* size of the active set A (containing the indices of the active constraints) */\n\n    /*\n     * Preprocessing phase\n     */\n\n    /* compute the trace of the original matrix G */\n    c1 = 0.0;\n    for (i = 0; i < n; i++)\n    {\n        c1 += G(i,i);\n    }\n\n    /* decompose the matrix G in the form L^T L */\n    cholesky_decomposition(G);\n\n    /* initialize the matrix R */\n    for (i = 0; i < n; i++)\n    {\n        d(i) = 0.0;\n        for (j = 0; j < n; j++)\n            R(i,j) = 0.0;\n    }\n    R_norm = 1.0; /* this variable will hold the norm of the matrix R */\n\n    /* compute the inverse of the factorized matrix G^-1, this is the initial value for H */\n    c2 = 0.0;\n    for (i = 0; i < n; i++) \n    {\n        d(i) = 1.0;\n        forward_elimination(G, z, d);\n        for (j = 0; j < n; j++)\n            J(i,j) = z(j);\n        c2 += z(i);\n        d(i) = 0.0;\n    }\n#ifdef TRACE_SOLVER\n    print_matrix(\"J\", J, n);\n#endif\n\n    /* c1 * c2 is an estimate for cond(G) */\n\n    /* \n     * Find the unconstrained minimizer of the quadratic form 0.5 * x G x + g0 x \n     * this is a feasible point in the dual space\n     * x = G^-1 * g0\n     */\n    cholesky_solve(G, x, g0);\n    for (i = 0; i < n; i++)\n        x(i) = -x(i);\n    /* and compute the current solution value */ \n    f_value = 0.5 * inner_prod(g0, x);\n#ifdef TRACE_SOLVER\n    std::cerr << \"Unconstrained solution: \" << f_value << std::endl;\n    print_vector(\"x\", x, n);\n#endif\n\n    /* Add equality constraints to the working set A */\n    iq = 0;\n    for (i = 0; i < me; i++)\n    {\n        for (j = 0; j < n; j++)\n            np(j) = CE(j,i);\n        compute_d(d, J, np);\n        update_z(z, J, d,  iq);\n        update_r(R, r, d,  iq);\n#ifdef TRACE_SOLVER\n        print_matrix(\"R\", R, iq);\n        print_vector(\"z\", z, n);\n        print_vector(\"r\", r, iq);\n        print_vector(\"d\", d, n);\n#endif\n\n        /* compute full step length t2: i.e., the minimum step in primal space s.t. the contraint \n           becomes feasible */\n        t2 = 0.0;\n        if (fabs(inner_prod(z, z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0\n            t2 = (-inner_prod(np, x) - ce0(i)) / inner_prod(z, np);\n\n        /* set x = x + t2 * z */\n        for (k = 0; k < n; k++)\n            x(k) += t2 * z(k);\n\n        /* set u = u+ */\n        u(iq) = t2;\n        for (k = 0; k < iq; k++)\n            u(k) -= t2 * r(k);\n\n        /* compute the new solution value */\n        f_value += 0.5 * (t2 * t2) * inner_prod(z, np);\n        A(i) = -i - 1;\n\n        if (!add_constraint(R, J, d, iq, R_norm))\n        {\n            // FIXME: it should raise an error\n            // Equality constraints are linearly dependent\n            return f_value;\n        }\n    }\n\n    /* set iai = K \\ A */\n    for (i = 0; i < mi; i++)\n        iai(i) = i;\n\nl1:\titer++;\n#ifdef TRACE_SOLVER\n    print_vector(\"x\", x, n);\n#endif\n    /* step 1: choose a violated constraint */\n    for (i = me; i < iq; i++)\n    {\n        ip = A(i);\n        iai(ip) = -1;\n    }\n\n    /* compute s(x) = ci^T * x + ci0 for all elements of K \\ A */\n    ss = 0.0;\n    psi = 0.0; /* this value will contain the sum of all infeasibilities */\n    ip = 0; /* ip will be the index of the chosen violated constraint */\n    for (i = 0; i < mi; i++)\n    {\n        iaexcl[i] = true;\n        sum = 0.0;\n        for (j = 0; j < n; j++)\n            sum += CI(j,i) * x(j);\n        sum += ci0(i);\n        s(i) = sum;\n        psi += std::min(0.0, sum);\n    }\n#ifdef TRACE_SOLVER\n    print_vector(\"s\", s, mi);\n#endif\n\n\n    if (fabs(psi) <= mi * std::numeric_limits<double>::epsilon() * c1 * c2* 100.0)\n    {\n        /* numerically there are not infeasibilities anymore */\n        q = iq;\n        return f_value;\n    }\n\n    /* save old values for u and A */\n    for (i = 0; i < iq; i++)\n    {\n        u_old(i) = u(i);\n        A_old(i) = A(i);\n    }\n    /* and for x */\n    for (i = 0; i < n; i++)\n        x_old(i) = x(i);\n\nl2: /* Step 2: check for feasibility and determine a new S-pair */\n    for (i = 0; i < mi; i++)\n    {\n        if (s(i) < ss && iai(i) != -1 && iaexcl[i])\n        {\n            ss = s(i);\n            ip = i;\n        }\n    }\n    if (ss >= 0.0)\n    {\n        q = iq;\n        return f_value;\n    }\n\n    /* set np = n(ip) */\n    for (i = 0; i < n; i++)\n        np(i) = CI(i,ip);\n    /* set u = (u 0)^T */\n    u(iq) = 0.0;\n    /* add ip to the active set A */\n    A(iq) = ip;\n\n#ifdef TRACE_SOLVER\n    std::cerr << \"Trying with constraint \" << ip << std::endl;\n    print_vector(\"np\", np, n);\n#endif\n\nl2a:/* Step 2a: determine step direction */\n    /* compute z = H np: the step direction in the primal space (through J, see the paper) */\n    compute_d(d, J, np);\n    update_z(z, J, d, iq);\n    /* compute N* np (if q > 0): the negative of the step direction in the dual space */\n    update_r(R, r, d, iq);\n#ifdef TRACE_SOLVER\n    std::cerr << \"Step direction z\" << std::endl;\n    print_vector(\"z\", z, n);\n    print_vector(\"r\", r, iq + 1);\n    print_vector(\"u\", u, iq + 1);\n    print_vector(\"d\", d, n);\n    print_ivector(\"A\", A, iq + 1);\n#endif\n\n    /* Step 2b: compute step length */\n    l = 0;\n    /* Compute t1: partial step length (maximum step in dual space without violating dual feasibility */\n    t1 = inf; /* +inf */\n    /* find the index l s.t. it reaches the minimum of u+(x) / r */\n    for (k = me; k < iq; k++)\n    {\n        if (r(k) > 0.0)\n        {\n            if (u(k) / r(k) < t1)\n            {\n                t1 = u(k) / r(k);\n                l = A(k);\n            }\n        }\n    }\n    /* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */\n    if (fabs(inner_prod(z, z))  > std::numeric_limits<double>::epsilon()) // i.e. z != 0\n        t2 = -s(ip) / inner_prod(z, np);\n    else\n        t2 = inf; /* +inf */\n\n    /* the step is chosen as the minimum of t1 and t2 */\n    t = std::min(t1, t2);\n#ifdef TRACE_SOLVER\n    std::cerr << \"Step sizes: \" << t << \" (t1 = \" << t1 << \", t2 = \" << t2 << \") \";\n#endif\n\n    /* Step 2c: determine new S-pair and take step: */\n\n    /* case (i): no step in primal or dual space */\n    if (t >= inf)\n    {\n        /* QPP is infeasible */\n        // FIXME: unbounded to raise\n        q = iq;\n        return inf;\n    }\n    /* case (ii): step in dual space */\n    if (t2 >= inf)\n    {\n        /* set u = u +  t * [-r 1) and drop constraint l from the active set A */\n        for (k = 0; k < iq; k++)\n            u(k) -= t * r(k);\n        u(iq) += t;\n        iai(l) = l;\n        delete_constraint(R, J, A, u, p, iq, l);\n#ifdef TRACE_SOLVER\n        std::cerr << \" in dual space: \" \n            << f_value << std::endl;\n        print_vector(\"x\", x, n);\n        print_vector(\"z\", z, n);\n        print_ivector(\"A\", A, iq + 1);\n#endif\n        goto l2a;\n    }\n\n    /* case (iii): step in primal and dual space */\n\n    /* set x = x + t * z */\n    for (k = 0; k < n; k++)\n        x(k) += t * z(k);\n    /* update the solution value */\n    f_value += t * inner_prod(z, np) * (0.5 * t + u(iq));\n    /* u = u + t * (-r 1) */\n    for (k = 0; k < iq; k++)\n        u(k) -= t * r(k);\n    u(iq) += t;\n#ifdef TRACE_SOLVER\n    std::cerr << \" in both spaces: \" \n        << f_value << std::endl;\n    print_vector(\"x\", x, n);\n    print_vector(\"u\", u, iq + 1);\n    print_vector(\"r\", r, iq + 1);\n    print_ivector(\"A\", A, iq + 1);\n#endif\n\n    if (t == t2)\n    {\n#ifdef TRACE_SOLVER\n        std::cerr << \"Full step has taken \" << t << std::endl;\n        print_vector(\"x\", x, n);\n#endif\n        /* full step has taken */\n        /* add constraint ip to the active set*/\n        if (!add_constraint(R, J, d, iq, R_norm))\n        {\n            iaexcl[ip] = false;\n            delete_constraint(R, J, A, u, p, iq, ip);\n#ifdef TRACE_SOLVER\n            print_matrix(\"R\", R, n);\n            print_ivector(\"A\", A, iq);\n#endif\n            for (i = 0; i < m; i++)\n                iai(i) = i;\n            for (i = 0; i < iq; i++)\n            {\n                A(i) = A_old(i);\n                iai(A(i)) = -1;\n                u(i) = u_old(i);\n            }\n            for (i = 0; i < n; i++)\n                x(i) = x_old(i);\n            goto l2; /* go to step 2 */\n        }    \n        else\n            iai(ip) = -1;\n#ifdef TRACE_SOLVER\n        print_matrix(\"R\", R, n);\n        print_ivector(\"A\", A, iq);\n#endif\n        goto l1;\n    }\n\n    /* a patial step has taken */\n#ifdef TRACE_SOLVER\n    std::cerr << \"Partial step has taken \" << t << std::endl;\n    print_vector(\"x\", x, n);\n#endif\n    /* drop constraint l */\n    iai(l) = l;\n    delete_constraint(R, J, A, u, p, iq, l);\n#ifdef TRACE_SOLVER\n    print_matrix(\"R\", R, n);\n    print_ivector(\"A\", A, iq);\n#endif\n\n    /* update s[ip) = CI * x + ci0 */\n    sum = 0.0;\n    for (k = 0; k < n; k++)\n        sum += CI(k,ip) * x(k);\n    s(ip) = sum + ci0(ip);\n\n#ifdef TRACE_SOLVER\n    print_vector(\"s\", s, mi);\n#endif\n    goto l2a;\n}\n\n/**\n * Compute d.\n */\ninline void compute_d(vector<double> &d, matrix<double>& J, vector<double>& np)\n{ int n=np.size();\n    register int i, j;\n    register double sum;\n\n    /* compute d = H^T * np */\n    for (i = 0; i < n; i++)\n    {\n        sum = 0.0;\n        for (j = 0; j < n; j++)\n            sum += J(j,i) * np(j);\n        d(i) = sum;\n    }\n}\n\n/**\n * Update_z\n */\ninline void update_z(vector<double>& z, matrix<double>& J, vector<double>& d,  int iq)\n{\n    register int i, j;\n    int n=z.size();\n    /* setting of z = H * d */\n    for (i = 0; i < n; i++)\n    {\n        z(i) = 0.0;\n        for (j = iq; j < n; j++)\n            z(i) += J(i,j) * d(j);\n    }\n}\n\n/**\n * Update r.\n */\ninline void update_r(matrix<double>& R, vector<double> &r, vector<double> &d, int iq) \n{\n    register int i, j;\n    register double sum;\n\n    /* setting of r = R^-1 d */\n    for (i = iq - 1; i >= 0; i--)\n    {\n        sum = 0.0;\n        for (j = i + 1; j < iq; j++)\n            sum += R(i,j) * r(j);\n        r(i) = (d(i) - sum) / R(i,i);\n    }\n}\n\n/**\n * Add constraints.\n */\ninline bool add_constraint(matrix<double>& R, matrix<double>& J, vector<double>& d, int& iq, double& R_norm)\n{\n    int n=J.size1();\n#ifdef TRACE_SOLVER\n    std::cerr << \"Add constraint \" << iq << '/';\n#endif\n    int i, j, k;\n    double cc, ss, h, t1, t2, xny;\n\n    /* we have to find the Givens rotation which will reduce the element\n       d(j) to zero.\n       if it is already zero we don't have to do anything, except of\n       decreasing j */  \n    for (j = n - 1; j >= iq + 1; j--)\n    {\n        /* The Givens rotation is done with the matrix (cc cs, cs -cc).\n           If cc is one, then element (j) of d is zero compared with element\n           (j - 1). Hence we don't have to do anything. \n           If cc is zero, then we just have to switch column (j) and column (j - 1) \n           of J. Since we only switch columns in J, we have to be careful how we\n           update d depending on the sign of gs.\n           Otherwise we have to apply the Givens rotation to these columns.\n           The i - 1 element of d has to be updated to h. */\n        cc = d(j - 1);\n        ss = d(j);\n        h = distance(cc, ss);\n        if (h == 0.0)\n            continue;\n        d(j) = 0.0;\n        ss = ss / h;\n        cc = cc / h;\n        if (cc < 0.0)\n        {\n            cc = -cc;\n            ss = -ss;\n            d(j - 1) = -h;\n        }\n        else\n            d(j - 1) = h;\n        xny = ss / (1.0 + cc);\n        for (k = 0; k < n; k++)\n        {\n            t1 = J(k,j - 1);\n            t2 = J(k,j);\n            J(k,j - 1) = t1 * cc + t2 * ss;\n            J(k,j) = xny * (t1 + J(k,j - 1)) - t2;\n        }\n    }\n    /* update the number of constraints added*/\n    iq++;\n    /* To update R we have to put the iq components of the d vector\n       into column iq - 1 of R\n     */\n    for (i = 0; i < iq; i++)\n        R(i,iq - 1) = d(i);\n#ifdef TRACE_SOLVER\n    std::cerr << iq << std::endl;\n#endif\n\n    if (fabs(d(iq - 1)) <= std::numeric_limits<double>::epsilon() * R_norm)\n        // problem degenerate\n        return false;\n    R_norm = std::max<double>(R_norm, fabs(d(iq - 1)));\n    return true;\n}\n\n/**\n * Delete constraints.\n */\ninline void delete_constraint(matrix<double>& R, matrix<double>& J, vector<int>& A, vector<double>& u,  int p, int& iq, int l)\n{\n\n    int n=R.size1();\n#ifdef TRACE_SOLVER\n    std::cerr << \"Delete constraint \" << l << ' ' << iq;\n#endif\n    int i, j, k;\n    int qq = 0;\n    double cc, ss, h, xny, t1, t2;\n\n    /* Find the index qq for active constraint l to be removed */\n    for (i = p; i < iq; i++)\n        if (A(i) == l)\n        {\n            qq = i;\n            break;\n        }\n\n    /* remove the constraint from the active set and the duals */\n    for (i = qq; i < iq - 1; i++)\n    {\n        A(i) = A(i + 1);\n        u(i) = u(i + 1);\n        for (j = 0; j < n; j++)\n            R(j,i) = R(j,i + 1);\n    }\n\n    A(iq - 1) = A(iq);\n    u(iq - 1) = u(iq);\n    A(iq) = 0; \n    u(iq) = 0.0;\n    for (j = 0; j < iq; j++)\n        R(j,iq - 1) = 0.0;\n    /* constraint has been fully removed */\n    iq--;\n#ifdef TRACE_SOLVER\n    std::cerr << '/' << iq << std::endl;\n#endif \n\n    if (iq == 0)\n        return;\n\n    for (j = qq; j < iq; j++)\n    {\n        cc = R(j,j);\n        ss = R(j + 1,j);\n        h = distance(cc, ss);\n        if (h == 0.0)\n            continue;\n        cc = cc / h;\n        ss = ss / h;\n        R(j + 1,j) = 0.0;\n        if (cc < 0.0)\n        {\n            R(j,j) = -h;\n            cc = -cc;\n            ss = -ss;\n        }\n        else\n            R(j,j) = h;\n\n        xny = ss / (1.0 + cc);\n        for (k = j + 1; k < iq; k++)\n        {\n            t1 = R(j,k);\n            t2 = R(j + 1,k);\n            R(j,k) = t1 * cc + t2 * ss;\n            R(j + 1,k) = xny * (t1 + R(j,k)) - t2;\n        }\n        for (k = 0; k < n; k++)\n        {\n            t1 = J(k,j);\n            t2 = J(k,j + 1);\n            J(k,j) = t1 * cc + t2 * ss;\n            J(k,j + 1) = xny * (J(k,j) + t1) - t2;\n        }\n    }\n}\n\n/**\n * Get distance.\n */\ninline double distance(double a, double b)\n{\n    register double a1, b1, t;\n    a1 = fabs(a);\n    b1 = fabs(b);\n    if (a1 > b1) \n    {\n        t = (b1 / a1);\n        return a1 * sqrt(1.0 + t * t);\n    }\n    else\n        if (b1 > a1)\n        {\n            t = (a1 / b1);\n            return b1 * sqrt(1.0 + t * t);\n        }\n    return a1 * sqrt(2.0);\n}\n\n/**\n * Compute the Choleski factorization of a real symmetric positive-definite square matrix.\n */\ninline void cholesky_decomposition(matrix<double> & A) \n{\n    register int i, j, k;\n    register double sum;\n    int n=A.size1();\t\n    for (i = 0; i < n; i++)\n    {\n        for (j = i; j < n; j++)\n        {\n            sum = A(i,j);\n            for (k = i - 1; k >= 0; k--)\n                sum -= A(i,k)*A(j,k);\n            if (i == j) \n            {\n                if (sum <= 0.0)\n                {\n                    // raise error\n                    //\t\tprint_matrix(\"A\", A, n);\n                    throw std::runtime_error(\"The matrix passed to the Cholesky A = L L^T decomposition is not positive definite\");\n                }\n                A(i,i) = sqrt(sum);\n            }\n            else\n                A(j,i) = sum / A(i,i);\n        }\n        for (k = i + 1; k < n; k++)\n            A(i,k) = A(k,i);\n    } \n}\n\n/**\n * Cholesky solve.\n */\ninline void cholesky_solve(matrix<double>& L, vector<double> &x, vector<double> & b)\n{\n\n    vector<double> y(x.size());\n\n    /* Solve L * y = b */\n    forward_elimination(L, y, b);\n    /* Solve L^T * x = y */\n    backward_elimination(L, x, y);\n}\n\n/**\n * Forward elimination.\n */\ninline void forward_elimination(matrix<double>& L, vector<double>& y, vector<double>& b)\n{ \n    register int i, j;\n    int n=y.size();\n    y(0) = b(0) / L(0,0);\n    for (i = 1; i < n; i++)\n    {\n        y(i) = b(i);\n        for (j = 0; j < i; j++)\n            y(i) -= L(i,j) * y(j);\n        y(i) = y(i) / L(i,i);\n    }\n}\n\n/**\n * Backward elimination.\n */\ninline void backward_elimination(matrix<double>& U,vector<double>& x, vector<double>& y){\n    int n=x.size();\n\n    register int i, j;\n\n    x(n - 1) = y(n - 1) / U(n - 1,n - 1);\n    for (i = n - 2; i >= 0; i--){\n        x(i) = y(i);\n        for (j = i + 1; j < n; j++)\n            x(i) -= U(i,j) * x(j);\n        x(i) = x(i) / U(i,i);\n    }\n}\n\n\n#endif\n", "meta": {"hexsha": "357fc25442b9b4f2567747c671f57094c59e7f47", "size": 20733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/uqp/uquadprog.hpp", "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/uqp/uquadprog.hpp", "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/uqp/uquadprog.hpp", "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": 26.99609375, "max_line_length": 131, "alphanum_fraction": 0.5040273959, "num_tokens": 6466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5642466809789928}}
{"text": "#include \"integration.hpp\"\n#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\nusing namespace std;\n\nvoid forwardEulerStep(PhysicalSystem *system, double dt) {\n    int n = system->getDOFs();\n    static VectorXd x0(n), v0(n);\n    system->getState(x0, v0); \n    static MatrixXd Mi(n,n);\n    system->getInverseInertia(Mi);\n    static VectorXd f0(n);\n    system->getForces(f0);\n    static VectorXd a0(n); // acceleration\n    a0 = Mi*f0;\n    x0 = x0 + v0*dt;\n    v0 = v0 + a0*dt;\n    system->setState(x0, v0);\n}\n\nVectorXd solve(const MatrixXd &A, const VectorXd &b) {\n    SparseMatrix<double> spA = A.sparseView();\n    ConjugateGradient< SparseMatrix<double> > solver;\n    return solver.compute(spA).solve(b);\n}\n\nvoid backwardEulerStep(PhysicalSystem *system, double dt) {\n    int n = system->getDOFs();\n    static VectorXd x0(n), v0(n);\n    system->getState(x0, v0);\n    static MatrixXd M(n,n);\n    system->getInertia(M);\n    static VectorXd f(n);\n    static MatrixXd Jx(n,n), Jv(n,n);\n    system->getForces(f);\n    system->getJacobians(Jx, Jv);\n    MatrixXd A = M - Jx*dt*dt - Jv*dt;\n    VectorXd b = (f + Jx*v0*dt)*dt;\n    VectorXd dv = solve(A, b);\n    VectorXd v1 = v0 + dv;\n    system->setState(x0 + v1*dt, v1);\n}\n\nvoid projectPositions(ConstrainedSystem *system) {\n    int n = system->getDOFs(),\tm = system->getConstraints();\n\tstatic VectorXd c(m);\t\t\tsystem->getConstraintValues(c);\n    static MatrixXd J(m,n);\t\t\tsystem->getConstraintJacobian(J);\n\tstatic MatrixXd Mi(n, n);\t\tsystem->getInverseInertia(Mi);\n\t//printf(\"Rows: %d Cols: %d\", c.rows(), c.cols());\n    MatrixXd A = J*Mi*J.transpose();\n\n\t//printf(\"Rows: %d Cols: %d\", A.rows(), A.cols());\n\n    VectorXd lambda = solve(A, -c); \n    static VectorXd dx(n);\t\t    dx = Mi*J.transpose()*lambda;\n    static VectorXd x(n), v(n);\t\tsystem->getState(x, v);\n    system->setState(x + dx, v);\n}\n\nvoid projectVelocities(ConstrainedSystem *system) {\n    int n = system->getDOFs(), m = system->getConstraints();\n    static VectorXd x(n), v(n);\n    system->getState(x, v);\n\tv = v * 0.995; //global dampening\n    static MatrixXd J(m,n);\n    system->getConstraintJacobian(J);\n    static MatrixXd Mi(n,n);\n    system->getInverseInertia(Mi);\n    MatrixXd A = J*Mi*J.transpose();\n    VectorXd b = -J*v;\n    VectorXd lambda = solve(A, b);\n    static VectorXd dv(n);\n    dv = Mi*J.transpose()*lambda;\n    system->setState(x, v + dv);\n}\n\nvoid constrainedForwardEulerStep(ConstrainedSystem *system, double dt) {\n    forwardEulerStep(system, dt);\n    projectPositions(system);\n    projectVelocities(system);\n}\n\nvoid constrainedBackwardEulerStep(ConstrainedSystem *system, double dt) {\n    // Let's not bother with this one.\n\tbackwardEulerStep(system, dt);\n\tprojectPositions(system);\n\tprojectVelocities(system);\n}\n", "meta": {"hexsha": "8b7f162bbf0b522eabf3ef74a4d06726c4731b94", "size": 2778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/3_ConstrainedDynamics_InextensibleRope/integration.cpp", "max_stars_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_stars_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T08:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:29:04.000Z", "max_issues_repo_path": "C++/3_ConstrainedDynamics_InextensibleRope/integration.cpp", "max_issues_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_issues_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/3_ConstrainedDynamics_InextensibleRope/integration.cpp", "max_forks_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_forks_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8666666667, "max_line_length": 73, "alphanum_fraction": 0.6544276458, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5642039721309569}}
{"text": "/*! \\file geometry.hpp\n  \\brief Geometrical calculations\n  \\author Almog Yalinewich\n */\n\n#ifndef GEOMETRY_HPP\n#define GEOMETRY_HPP 1\n#include <vector>\n#include <boost/array.hpp>\n#ifdef RICH_MPI\n#include \"../misc/serializable.hpp\"\n#endif // RICH_MPI\n\n//! \\brief 2D Mathematical vector\nclass Vector2D\n#ifdef RICH_MPI\n  : public Serializable\n#endif // RICH_MPI\n{\npublic:\n\n  /*! \\brief Null constructor\n    \\details Sets all components to 0\n   */\n  Vector2D(void);\n\n  /*! \\brief Class constructor\n    \\param ix x Component\n    \\param iy y Component\n   */\n  Vector2D(double ix, double iy);\n\n  /*! \\brief Class copy constructor\n    \\param v Other vector\n   */\n  Vector2D(const Vector2D& v);\n\n  /*! \\brief Set vector components\n    \\param ix x Component\n    \\param iy y Component\n   */\n  void Set(double ix, double iy);\n\n  //! \\brief Component in the x direction\n  double x;\n\n  //! \\brief Component in the y direction\n  double y;\n\n  /*! \\brief Addition\n    \\param v Vector to be added\n    \\return Reference to sum\n   */\n  Vector2D& operator+=(Vector2D const& v);\n\n  /*! \\brief Subtraction\n    \\param v Vector to be subtracted\n    \\return Difference\n   */\n  Vector2D& operator-=(Vector2D const& v);\n\n  /*! \\brief Assigment operator\n    \\param v Vector to be copied\n    \\return The assigned value\n   */\n  Vector2D& operator=(Vector2D const& v);\n\n  /*! \\brief Scalar product\n    \\param s Scalar\n    \\return Reference to the vector multiplied by scalar\n   */\n  Vector2D& operator*=(double s);\n\n  /*! \\brief Rotates the vector in an anticlockwise direction\n    \\param a Angle of rotation (in radians)\n   */\n  void Rotate(double a);\n  //! \\brief Caluclates the distance from the Vector to v1 \\param v1 The vector whose distance from is calculated \\returns The distance\n  double distance(Vector2D const& v1) const;\n\n#ifdef RICH_MPI\n  /*! \\brief Serializer\n    \\param ar Archiver\n    \\param int Version\n   */\n  template<class Archive>\n  void serialize\n  (Archive& ar, \n   const unsigned int /*version*/)\n  {\n    ar & x;\n    ar & y;\n  }\n\n  vector<double> serialize(void) const;\n\n  size_t getChunkSize(void) const;\n\n  void unserialize\n  (const vector<double>& data);\n#endif // RICH_MPI\n};\n\n/*! \\brief Norm of a vector\n  \\param v Two dimensional vector\n  \\return Norm of v\n */\ndouble abs(Vector2D const& v);\n\n/*! \\brief Term by term addition\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return Sum\n */\nVector2D operator+(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Term by term subtraction\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return Difference\n */\nVector2D operator-(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Scalar product\n  \\param d Scalar\n  \\param v Vector\n  \\return Two dimensional vector\n */\nVector2D operator*(double d, Vector2D const& v);\n\n/*! \\brief Scalar product\n  \\param v Vector\n  \\param d Scalar\n  \\return Two dimensional vector\n */\nVector2D operator*(Vector2D const& v, double d);\n\n/*! \\brief Scalar division\n  \\param v Vector\n  \\param d Scalar\n  \\return Two dimensional vector\n */\nVector2D operator/(Vector2D const& v, double d);\n\n/*! \\brief Scalar product of two vectors\n  \\param v1 2D vector\n  \\param v2 2D vector\n  \\return Scalar product of v1 and v2\n */\ndouble ScalarProd(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Returns the angle between two vectors (in radians)\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return Angle\n */\ndouble CalcAngle(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Calculates the projection of one vector in the direction of the second\n  \\param v1 First vector\n  \\param v2 Direction of the projection\n  \\return Component of v1 in the direction of v2\n */\ndouble Projection(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Rotates a vector\n  \\param v Vector\n  \\param a Angle\n  \\return Rotated vector\n */\nVector2D Rotate(Vector2D const& v, double a);\n\n/*! \\brief Reflect vector\n  \\param v Vector\n  \\param axis Axis of reflection\n  \\return Reflection of v about axis\n */\nVector2D Reflect(Vector2D const& v, Vector2D const& axis);\n\n/*! \\brief Calculates the distance between two vectors\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return distance between v1 and v2\n */\ndouble distance(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Returns the z component of the cross product of two vectors\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return z component of the cross product between v1 and v2\n */\ndouble CrossProduct(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Calculates the mid point between two vectors\n  \\param v1 First vector\n  \\param v2 Second vector\n  \\return Distance between v1 and v2\n */\nVector2D calc_mid_point(Vector2D const& v1, Vector2D const& v2);\n\n/*! \\brief Cross product of a vector in x,y plane with a unit vector in the z direction\n  \\param v Vector in the x,y plane\n  \\return Two dimensional vector\n */\nVector2D zcross(Vector2D const& v);\n\n/*! \\brief Converts from polar coordinates to cartesian coordinates\n  \\param radius Radius\n  \\param angle Angle relative to the x axis\n  \\return Same vector in cartesian coordiantes\n */\nVector2D pol2cart(double radius, double angle);\n\n/*! \\brief Normalized a vector\n  \\param v Original vector\n  \\return Vector divided by its norm\n */\nVector2D normalize(const Vector2D& v);\n\n/*! \\brief Calculates the square of the distance. This is computationaly cheaper then actually calculating the distance\n  \\param v Vector\n  \\return Square of the distance\n */\ndouble dist_sqr(const Vector2D& v);\n\n#endif // GEOMETRY_HPP\n", "meta": {"hexsha": "cdd85e2d726f068159ca5c7ae0ef3815b1808da1", "size": 5505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/geometry.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/geometry.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/geometry.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": 24.2511013216, "max_line_length": 135, "alphanum_fraction": 0.7079019074, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.5641368188747612}}
{"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_COTD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COTD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cotd capabilities\n\n    cotangent of input in degree: \\f$\\cos(\\pi x/180)/\\sin(\\pi x/180) \\f$.\n\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = cotd(x);\n    @endcode\n\n    As most other trigonometric function cotd 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 cos, sin, tan, cot, cotpi\n\n  **/\n  Value cotd(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cotd.hpp>\n#include <boost/simd/function/simd/cotd.hpp>\n\n#endif\n", "meta": {"hexsha": "56f6bc678381640c66a4f0766398e1c36d6d4e2c", "size": 1178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cotd.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/cotd.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/cotd.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 24.5416666667, "max_line_length": 100, "alphanum_fraction": 0.5933786078, "num_tokens": 266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.5640595603469989}}
{"text": "/** \\file Lagrange.h */\n\n#pragma once\n\n#include <list>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\n#include \"BasisFunction.hpp\"\n#include \"FixVec.hpp\"\n\nnamespace AMDiS\n{\n\n#define MAX_DIM 3\n#define MAX_DEGREE 4\n\n  /** \\ingroup FEMSpace\n   * \\brief\n   * Lagrange basis functions. Sub class of BasisFunction\n   */\n  class Lagrange : public BasisFunction\n  {\n  public:\n    /// Creator class used in the BasisFunctionCreatorMap.\n    class Creator : public BasisFunctionCreator\n    {\n    public:\n      Creator(int degree_) : degree(degree_) {}\n\n      /// Returns a new Lagrange object.\n      BasisFunction* create()\n      {\n        return getLagrange(this->dim, degree);\n      }\n\n    protected:\n      int degree;\n    };\n\n  protected:\n    /// Constructs lagrange basis functions with the given dim and degree.\n    /// Constructor is protected to avoid multiple instantiation of identical\n    /// basis functions. Use \\ref getLagrange instead.\n    Lagrange(int dim_, int degree_);\n\n    /** \\brief\n     * destructor\n     */\n    virtual ~Lagrange();\n\n  public:\n    /// Returns a pointer to lagrange basis functions with the given dim and\n    /// degree. Multiple instantiation of identical basis functions is avoided\n    /// by rembering once created basis functions in \\ref allBasFcts.\n    static Lagrange* getLagrange(int dim, int degree);\n\n    /// Implements BasisFunction::interpol\n    void interpol(ElInfo const*, int, int const*,\n                  std::function<double(WorldVector<double>)>,\n                  DenseVector<double>&) const;\n\n    /// Implements BasisFunction::interpol\n    void interpol(ElInfo const*, int,\n                  int const* b_no,\n                  std::function<WorldVector<double>(WorldVector<double>)>,\n                  DenseVector<WorldVector<double>>&) const;\n\n    /// Returns the barycentric coordinates of the i-th basis function.\n    DimVec<double>* getCoords(int i) const;\n\n    /// Implements BasisFunction::getBound\n    void getBound(ElInfo const*, BoundaryType*) const;\n\n    /** \\brief\n     * Calculates the local vertex indices which are involved in evaluating\n     * the nodeIndex-th DOF at the positionIndex-th part of type position\n     * (VERTEX/EDGE/FACE/CENTER). nodeIndex determines the permutation\n     * of the involved vertices. So in 1d for lagrange4 there are two DOFs at\n     * the CENTER (which is an edge in this case). Then vertices[0] = {0, 1} and\n     * vertices[1] = {1, 0}. This allows to use the same local basis function\n     * for all DOFs at the same position.\n     */\n    static void setVertices(int dim, int degree,\n                            GeoIndex position, int positionIndex, int nodeIndex,\n                            int** vertices);\n\n    /// Implements BasisFunction::refineInter\n    void refineInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n)\n    {\n      if (refineInter_fct)\n        (*refineInter_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::coarseRestrict\n    void coarseRestr(DOFIndexed<double>* drv, RCNeighbourList* list, int n)\n    {\n      if (coarseRestr_fct)\n        (*coarseRestr_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::coarseInter\n    void coarseInter(DOFIndexed<double>* drv, RCNeighbourList* list, int n)\n    {\n      if (coarseInter_fct)\n        (*coarseInter_fct)(drv, list, n, this);\n    }\n\n    /// Implements BasisFunction::getLocalIndices().\n    void getLocalIndices(Element const* el,\n                         DOFAdmin const* admin,\n                         std::vector<DegreeOfFreedom>& dofs) const;\n\n    void getLocalDofPtrVec(Element const* el,\n                           DOFAdmin const* admin,\n                           std::vector<const DegreeOfFreedom*>& vec) const;\n\n    /// Implements BasisFunction::l2ScpFctBas\n    void l2ScpFctBas(Quadrature* q,\n                     std::function<double(WorldVector<double>)> f,\n                     DOFVector<double>* fh);\n\n    /// Implements BasisFunction::l2ScpFctBas\n    void l2ScpFctBas(Quadrature* q,\n                     std::function<WorldVector<double>(WorldVector<double>)> f,\n                     DOFVector<WorldVector<double>>* fh);\n\n    static void clear();\n\n    /// Implements BasisFunction::isnodal\n    bool isNodal() const\n    {\n      return true;\n    }\n\n  protected:\n    /// sets the barycentric coordinates (stored in \\ref bary) of the local\n    /// basis functions.\n    void setBary();\n\n    /// Recursive calculation of coordinates. Used by \\ref setBary\n    void createCoords(int* coordInd, int numCoords, int dimIndex, int rest,\n                      DimVec<double>* vec = NULL);\n\n    /// Used by \\ref setBary\n    int** getIndexPermutations(int numIndices) const;\n\n    /// Implements BasisFunction::setNDOF\n    void setNDOF();\n\n    /// Sets used function pointers\n    void setFunctionPointer();\n\n    /// Used by \\ref getVec\n    int* orderOfPositionIndices(Element const* el,\n                                GeoIndex position,\n                                int positionIndex) const;\n\n    /// Calculates the number of DOFs needed for Lagrange of the given dim\n    /// and degree.\n    static int getNumberOfDofs(int dim, int degree);\n\n  private:\n    /// barycentric coordinates of the locations of all basis functions\n    std::vector<DimVec<double>*>* bary;\n\n    /** \\name static dim-degree-arrays\n     * \\{\n     */\n    static std::vector<DimVec<double>*> baryDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    static DimVec<int>* ndofDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    static int nBasFctsDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    static std::vector<BasFctType*> phiDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    static std::vector<GrdBasFctType*> grdPhiDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    static std::vector<D2BasFctType*> D2PhiDimDegree[MAX_DIM + 1][MAX_DEGREE + 1];\n    /** \\} */\n\n    /// List of all used BasisFunctions in the whole program. Avoids duplicate\n    /// instantiation of identical BasisFunctions.\n    static std::list<Lagrange*> allBasFcts;\n\n\n  protected:\n    /// Pointer to the used refineInter function\n    void (*refineInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    /** \\name refineInter functions\n     * \\{\n     */\n    static void  refineInter0(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  refineInter1(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  refineInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter2_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter2_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter3_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter3_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter4_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter4_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  refineInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    /** \\} */\n\n    /// Pointer to the used coarseRestr function\n    void (*coarseRestr_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    /** \\name coarseRestr functions\n     * \\{\n     */\n    static void  coarseRestr0(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  coarseRestr1(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  coarseRestr2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr2_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr2_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr3_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr3_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr4_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr4_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseRestr4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    /** \\} */\n\n    /// Pointer to the used coarseInter function\n    void (*coarseInter_fct)(DOFIndexed<double>*, RCNeighbourList*, int, BasisFunction*);\n\n    /** \\name coarseInter functions\n     * \\{\n     */\n    static void  coarseInter0(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  coarseInter1(DOFIndexed<double>*, RCNeighbourList*, int,\n                              BasisFunction*);\n    static void  coarseInter2_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter2_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter2_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter3_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter3_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter3_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter4_1d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter4_2d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    static void  coarseInter4_3d(DOFIndexed<double>*, RCNeighbourList*, int,\n                                 BasisFunction*);\n    /** \\} */\n\n\n    /// AbstractFunction which implements lagrange basis functions\n    class Phi : public BasFctType\n    {\n    public:\n      /// Constructs the local lagrange basis function for the given position,\n      /// positionIndex and nodeIndex. owner_ is a pointer to the Lagrange\n      /// object this basis function belongs to.\n      Phi(Lagrange* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      /// Destructor\n      virtual ~Phi();\n\n    private:\n      /// vertices needed for evaluation of this function\n      int* vertices;\n\n      /// Pointer to the evaluating function\n      double (*func)(DimVec<double> const& lambda, int* vert);\n\n      /// Returns \\ref func(lambda, vertices)\n      double operator()(DimVec<double> const& lambda) const\n      {\n        return func(lambda, vertices);\n      }\n\n      /** \\name basis functions for different degrees\n       * \\{\n       */\n\n      // ====== Lagrange, degree = 0 =====================================\n      // center\n      static double phi0c(DimVec<double> const&, int*)\n      {\n        return 1.0;\n      }\n\n      // ====== Lagrange, degree = 1 =====================================\n      // vertex\n      static double phi1v(DimVec<double> const& lambda, int* vertices)\n      {\n        return lambda[vertices[0]];\n      }\n\n      // ====== Lagrange, degree = 2 =====================================\n      // vertex\n      static double phi2v(DimVec<double> const& lambda, int* vertices)\n      {\n        return lambda[vertices[0]] * (2.0 * lambda[vertices[0]] - 1.0);\n      }\n\n      // edge\n      static double phi2e(DimVec<double> const& lambda, int* vertices)\n      {\n        return (4.0 * lambda[vertices[0]] * lambda[vertices[1]]);\n      }\n\n      // ====== Lagrange, degree = 3 =====================================\n      // vertex\n      static double phi3v(DimVec<double> const& lambda, int* vertices)\n      {\n        return (4.5 * (lambda[vertices[0]] - 1.0) * lambda[vertices[0]] + 1.0) *\n               lambda[vertices[0]];\n      }\n\n      // edge\n      static double phi3e(DimVec<double> const& lambda, int* vertices)\n      {\n        return (13.5 * lambda[vertices[0]] - 4.5) *\n               lambda[vertices[0]] * lambda[vertices[1]];\n      }\n\n      // face\n      static double phi3f(DimVec<double> const& lambda, int* vertices)\n      {\n        return 27.0 * lambda[vertices[0]] * lambda[vertices[1]] *\n               lambda[vertices[2]];\n      }\n\n      // ====== Lagrange, degree = 4 ======================================\n      // vertex\n      static double phi4v(DimVec<double> const& lambda, int* vertices)\n      {\n        return (((32.0 * lambda[vertices[0]] - 48.0) * lambda[vertices[0]] + 22.0)\n                * lambda[vertices[0]] - 3.0) * lambda[vertices[0]] / 3.0;\n      }\n\n      // edge\n      static double phi4e0(DimVec<double> const& lambda, int* vertices)\n      {\n        return ((128.0 * lambda[vertices[0]] - 96.0) * lambda[vertices[0]] + 16.0)\n               * lambda[vertices[0]] * lambda[vertices[1]] / 3.0;\n      }\n\n      static double phi4e1(DimVec<double> const& lambda, int* vertices)\n      {\n        return (4.0 * lambda[vertices[0]] - 1.0) * lambda[vertices[0]] *\n               (4.0 * lambda[vertices[1]] - 1.0) * lambda[vertices[1]] * 4.0;\n      }\n\n      // face\n      static double phi4f(DimVec<double> const& lambda,  int* vertices)\n      {\n        return (4.0 * lambda[vertices[0]] - 1.0) * lambda[vertices[0]] *\n               lambda[vertices[1]] * lambda[vertices[2]] * 32.0;\n      }\n\n      // center\n      static double phi4c(DimVec<double> const& lambda, int* vertices)\n      {\n        return 256.0 * lambda[vertices[0]] * lambda[vertices[1]] *\n               lambda[vertices[2]] * lambda[vertices[3]];\n      }\n\n    };\n\n    /** \\} */\n\n\n\n    /// AbstractFunction which implements gradients of lagrange basis functions.\n    /// See \\ref Phi\n    class GrdPhi : public GrdBasFctType\n    {\n    public:\n      GrdPhi(Lagrange* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      virtual ~GrdPhi();\n    private:\n      int* vertices;\n\n      void (*func)(DimVec<double> const& lambda,\n                   int* vertices_,\n                   DenseVector<double>& result);\n\n      void operator()(DimVec<double> const& lambda,\n                      DenseVector<double>& result) const\n      {\n        func(lambda, vertices, result);\n      }\n\n      // ====== Lagrange0 ================================================\n      // center\n      static void grdPhi0c(DimVec<double> const&,\n                           int*,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n      }\n\n      // ====== Lagrange1 ================================================\n      // vertex\n      static void grdPhi1v(DimVec<double> const&,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 1.0;\n      }\n\n      // ====== Lagrange2 ================================================\n      // vertex\n      static void grdPhi2v(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 4.0 * lambda[vertices[0]] - 1.0;\n      }\n\n      // edge\n      static void grdPhi2e(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 4.0 * lambda[vertices[1]];\n        result[vertices[1]] = 4.0 * lambda[vertices[0]];\n      }\n\n      // ===== Lagrange3 ================================================\n      // vertex\n      static void grdPhi3v(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = (13.5 * lambda[vertices[0]] - 9.0) *\n                              lambda[vertices[0]] + 1.0;\n      }\n\n      // edge\n      static void grdPhi3e(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = (27.0 * lambda[vertices[0]] - 4.5) *\n                              lambda[vertices[1]];\n        result[vertices[1]] = (13.5 * lambda[vertices[0]] - 4.5) *\n                              lambda[vertices[0]];\n      }\n\n      // face\n      static void grdPhi3f(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 27.0 * lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[1]] = 27.0 * lambda[vertices[0]] * lambda[vertices[2]];\n        result[vertices[2]] = 27.0 * lambda[vertices[0]] * lambda[vertices[1]];\n      }\n\n\n      // ===== Lagrange4 ================================================\n      // vertex\n      static void grdPhi4v(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] =\n          ((128.0 * lambda[vertices[0]] - 144.0) * lambda[vertices[0]] + 44.0) *\n          lambda[vertices[0]] / 3.0 - 1.0;\n      }\n\n      // edge\n      static void grdPhi4e0(DimVec<double> const& lambda,\n                            int* vertices,\n                            DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = ((128.0 * lambda[vertices[0]] - 64.0) *\n                               lambda[vertices[0]] + 16.0 / 3.0) * lambda[vertices[1]];\n        result[vertices[1]] = ((128.0 * lambda[vertices[0]] - 96.0) *\n                               lambda[vertices[0]] + 16.0)*lambda[vertices[0]] / 3.0;\n      }\n\n      static void grdPhi4e1(DimVec<double> const& lambda,\n                            int* vertices,\n                            DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 4.0 * (8.0 * lambda[vertices[0]] - 1.0) *\n                              lambda[vertices[1]] * (4.0 * lambda[vertices[1]] - 1.0);\n        result[vertices[1]] = 4.0 * lambda[vertices[0]] *\n                              (4.0 * lambda[vertices[0]] - 1.0) * (8.0 * lambda[vertices[1]] - 1.0);\n      }\n\n      // face\n      static void grdPhi4f(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[vertices[0]] = 32.0 * (8.0 * lambda[vertices[0]] - 1.0) *\n                              lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[1]] = 32.0 * (4.0 * lambda[vertices[0]] - 1.0) *\n                              lambda[vertices[0]] * lambda[vertices[2]];\n        result[vertices[2]] = 32.0 * (4.0 * lambda[vertices[0]] - 1.0) *\n                              lambda[vertices[0]] * lambda[vertices[1]];\n      }\n\n      // center\n      static void grdPhi4c(DimVec<double> const& lambda,\n                           int* vertices,\n                           DenseVector<double>& result)\n      {\n        result = 0.0;\n        result[0] =\n          256.0 * lambda[vertices[1]] * lambda[vertices[2]] * lambda[vertices[3]];\n        result[1] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[2]] * lambda[vertices[3]];\n        result[2] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[3]];\n        result[3] =\n          256.0 * lambda[vertices[0]] * lambda[vertices[1]] * lambda[vertices[2]];\n      }\n    };\n\n\n\n    /// AbstractFunction which implements second derivatives of Lagrange basis\n    /// functions. See \\ref Phi\n    class D2Phi : public D2BasFctType\n    {\n    public:\n      D2Phi(Lagrange* owner, GeoIndex position, int positionIndex, int nodeIndex);\n\n      virtual ~D2Phi();\n    private:\n      int* vertices;\n\n      void (*func)(DimVec<double> const& lambda, int* vertices_, DimMat<double>& result);\n\n      void operator()(DimVec<double> const& lambda, DimMat<double>& result) const\n      {\n        return func(lambda, vertices, result);\n      }\n\n      // ===== Lagrange0 ================================================\n      // center\n      static void D2Phi0c(DimVec<double> const&, int*, DimMat<double>& result)\n      {\n        result.set(0.0);\n      }\n\n      // ===== Lagrange1 ================================================\n      // vertex\n      static void D2Phi1v(DimVec<double> const&, int*, DimMat<double>& result)\n      {\n        result.set(0.0);\n      }\n\n      // ===== Lagrange2 ================================================\n      // vertex\n      static void D2Phi2v(DimVec<double> const&, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] = 4.0;\n      }\n\n      // edge\n      static void D2Phi2e(DimVec<double> const&, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] = 4.0;\n        result[vertices[1]][vertices[0]] = 4.0;\n      }\n\n\n      // ===== Lagrange3 ================================================\n      // vertex\n      static void D2Phi3v(DimVec<double> const& lambda, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] = 27.0 * lambda[vertices[0]] - 9.0;\n      }\n\n      // edge\n      static void D2Phi3e(DimVec<double> const& lambda, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] = 27.0 * lambda[vertices[1]];\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] = 27.0 * lambda[vertices[0]] - 4.5;\n      }\n\n      // face\n      static void D2Phi3f(DimVec<double> const& lambda, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] = 27.0 * lambda[vertices[2]];\n        result[vertices[0]][vertices[2]] =\n          result[vertices[2]][vertices[0]] = 27.0 * lambda[vertices[1]];\n        result[vertices[1]][vertices[2]] =\n          result[vertices[2]][vertices[1]] = 27.0 * lambda[vertices[0]];\n      }\n\n\n      // ===== Lagrange4 ================================================\n      // vertex\n      static void D2Phi4v(DimVec<double> const& lambda,\n                          int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] =\n          (128.0 * lambda[vertices[0]] - 96.0) * lambda[vertices[0]] + 44.0 / 3.0;\n      }\n\n      // edge\n      static void D2Phi4e0(DimVec<double> const& lambda, int* vertices,\n                           DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] =\n          (256.0 * lambda[vertices[0]] - 64.0) * lambda[vertices[1]];\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] =\n            (128.0 * lambda[vertices[0]] - 64.0) * lambda[vertices[0]] + 16.0 / 3.0;\n      }\n\n      static void D2Phi4e1(DimVec<double> const& lambda, int* vertices,\n                           DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] =\n          32.0 * lambda[vertices[1]] * (4.0 * lambda[vertices[1]] - 1.0);\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] =\n            4.0 * (8.0 * lambda[vertices[0]] - 1.0) * (8.0 * lambda[vertices[1]] - 1.0);\n        result[vertices[1]][vertices[1]] =\n          32.0 * lambda[vertices[0]] * (4.0 * lambda[vertices[0]] - 1.0);\n      }\n\n      // face\n      static void D2Phi4f(DimVec<double> const& lambda, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[0]] =\n          256.0 * lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] =\n            32.0 * (8.0 * lambda[vertices[0]] - 1.0) * lambda[vertices[2]];\n        result[vertices[0]][vertices[2]] =\n          result[vertices[2]][vertices[0]] =\n            32.0 * (8.0 * lambda[vertices[0]] - 1.0) * lambda[vertices[1]];\n        result[vertices[1]][vertices[2]] =\n          result[vertices[2]][vertices[1]] =\n            32.0 * (4.0 * lambda[vertices[0]] - 1.0) * lambda[vertices[0]];\n      }\n\n      // center\n      static void D2Phi4c(DimVec<double> const& lambda, int* vertices,\n                          DimMat<double>& result)\n      {\n        result.set(0.0);\n        result[vertices[0]][vertices[1]] =\n          result[vertices[1]][vertices[0]] =\n            256.0 * lambda[vertices[2]] * lambda[vertices[3]];\n        result[vertices[0]][vertices[2]] =\n          result[vertices[2]][vertices[0]] =\n            256.0 * lambda[vertices[1]] * lambda[vertices[3]];\n        result[vertices[0]][vertices[3]] =\n          result[vertices[3]][vertices[0]] =\n            256.0 * lambda[vertices[1]] * lambda[vertices[2]];\n        result[vertices[1]][vertices[2]] =\n          result[vertices[2]][vertices[1]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[3]];\n        result[vertices[1]][vertices[3]] =\n          result[vertices[3]][vertices[1]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[2]];\n        result[vertices[2]][vertices[3]] =\n          result[vertices[3]][vertices[2]] =\n            256.0 * lambda[vertices[0]] * lambda[vertices[1]];\n      }\n    };\n  };\n\n} // end namespace AMDiS\n", "meta": {"hexsha": "937b4400ee9eefae78575b0229e4b744d52e3de2", "size": 26520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Lagrange.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/Lagrange.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/Lagrange.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": 36.6804979253, "max_line_length": 100, "alphanum_fraction": 0.535331825, "num_tokens": 6696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.564059553975192}}
{"text": "//  Boost common_factor_rt.hpp header file  ----------------------------------//\r\n\r\n//  (C) Copyright Daryle Walker and Paul Moore 2001-2002.  Permission to copy,\r\n//  use, modify, sell and distribute this software is granted provided this\r\n//  copyright notice appears in all copies.  This software is provided \"as is\"\r\n//  without express or implied warranty, and with no claim as to its suitability\r\n//  for any purpose. \r\n\r\n// boostinspect:nolicense (don't complain about the lack of a Boost license)\r\n// (Paul Moore hasn't been in contact for years, so there's no way to change the\r\n// license.)\r\n\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\n\r\n#ifndef BOOST_MATH_COMMON_FACTOR_RT_HPP\r\n#define BOOST_MATH_COMMON_FACTOR_RT_HPP\r\n\r\n#include <boost/math_fwd.hpp>  // self include\r\n\r\n#include <boost/config.hpp>  // for BOOST_NESTED_TEMPLATE, etc.\r\n#include <boost/limits.hpp>  // for std::numeric_limits\r\n#include <climits>           // for CHAR_MIN\r\n#include <boost/detail/workaround.hpp>\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push)\r\n#pragma warning(disable:4127 4244)  // Conditional expression is constant\r\n#endif\r\n\r\nnamespace boost\r\n{\r\nnamespace math\r\n{\r\n\r\n\r\n//  Forward declarations for function templates  -----------------------------//\r\n\r\ntemplate < typename IntegerType >\r\n    IntegerType  gcd( IntegerType const &a, IntegerType const &b );\r\n\r\ntemplate < typename IntegerType >\r\n    IntegerType  lcm( IntegerType const &a, IntegerType const &b );\r\n\r\n\r\n//  Greatest common divisor evaluator class declaration  ---------------------//\r\n\r\ntemplate < typename IntegerType >\r\nclass gcd_evaluator\r\n{\r\npublic:\r\n    // Types\r\n    typedef IntegerType  result_type, first_argument_type, second_argument_type;\r\n\r\n    // Function object interface\r\n    result_type  operator ()( first_argument_type const &a,\r\n     second_argument_type const &b ) const;\r\n\r\n};  // boost::math::gcd_evaluator\r\n\r\n\r\n//  Least common multiple evaluator class declaration  -----------------------//\r\n\r\ntemplate < typename IntegerType >\r\nclass lcm_evaluator\r\n{\r\npublic:\r\n    // Types\r\n    typedef IntegerType  result_type, first_argument_type, second_argument_type;\r\n\r\n    // Function object interface\r\n    result_type  operator ()( first_argument_type const &a,\r\n     second_argument_type const &b ) const;\r\n\r\n};  // boost::math::lcm_evaluator\r\n\r\n\r\n//  Implementation details  --------------------------------------------------//\r\n\r\nnamespace detail\r\n{\r\n    // Greatest common divisor for rings (including unsigned integers)\r\n    template < typename RingType >\r\n    RingType\r\n    gcd_euclidean\r\n    (\r\n        RingType a,\r\n        RingType b\r\n    )\r\n    {\r\n        // Avoid repeated construction\r\n        #ifndef __BORLANDC__\r\n        RingType const  zero = static_cast<RingType>( 0 );\r\n        #else\r\n        RingType  zero = static_cast<RingType>( 0 );\r\n        #endif\r\n\r\n        // Reduce by GCD-remainder property [GCD(a,b) == GCD(b,a MOD b)]\r\n        while ( true )\r\n        {\r\n            if ( a == zero )\r\n                return b;\r\n            b %= a;\r\n\r\n            if ( b == zero )\r\n                return a;\r\n            a %= b;\r\n        }\r\n    }\r\n\r\n    // Greatest common divisor for (signed) integers\r\n    template < typename IntegerType >\r\n    inline\r\n    IntegerType\r\n    gcd_integer\r\n    (\r\n        IntegerType const &  a,\r\n        IntegerType const &  b\r\n    )\r\n    {\r\n        // Avoid repeated construction\r\n        IntegerType const  zero = static_cast<IntegerType>( 0 );\r\n        IntegerType const  result = gcd_euclidean( a, b );\r\n\r\n        return ( result < zero ) ? static_cast<IntegerType>(-result) : result;\r\n    }\r\n\r\n    // Greatest common divisor for unsigned binary integers\r\n    template < typename BuiltInUnsigned >\r\n    BuiltInUnsigned\r\n    gcd_binary\r\n    (\r\n        BuiltInUnsigned  u,\r\n        BuiltInUnsigned  v\r\n    )\r\n    {\r\n        if ( u && v )\r\n        {\r\n            // Shift out common factors of 2\r\n            unsigned  shifts = 0;\r\n\r\n            while ( !(u & 1u) && !(v & 1u) )\r\n            {\r\n                ++shifts;\r\n                u >>= 1;\r\n                v >>= 1;\r\n            }\r\n\r\n            // Start with the still-even one, if any\r\n            BuiltInUnsigned  r[] = { u, v };\r\n            unsigned         which = static_cast<bool>( u & 1u );\r\n\r\n            // Whittle down the values via their differences\r\n            do\r\n            {\r\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\r\n                while ( !(r[ which ] & 1u) )\r\n                {\r\n                    r[ which ] = (r[which] >> 1);\r\n                }\r\n#else\r\n                // Remove factors of two from the even one\r\n                while ( !(r[ which ] & 1u) )\r\n                {\r\n                    r[ which ] >>= 1;\r\n                }\r\n#endif\r\n\r\n                // Replace the larger of the two with their difference\r\n                if ( r[!which] > r[which] )\r\n                {\r\n                    which ^= 1u;\r\n                }\r\n\r\n                r[ which ] -= r[ !which ];\r\n            }\r\n            while ( r[which] );\r\n\r\n            // Shift-in the common factor of 2 to the residues' GCD\r\n            return r[ !which ] << shifts;\r\n        }\r\n        else\r\n        {\r\n            // At least one input is zero, return the other\r\n            // (adding since zero is the additive identity)\r\n            // or zero if both are zero.\r\n            return u + v;\r\n        }\r\n    }\r\n\r\n    // Least common multiple for rings (including unsigned integers)\r\n    template < typename RingType >\r\n    inline\r\n    RingType\r\n    lcm_euclidean\r\n    (\r\n        RingType const &  a,\r\n        RingType const &  b\r\n    )\r\n    {\r\n        RingType const  zero = static_cast<RingType>( 0 );\r\n        RingType const  temp = gcd_euclidean( a, b );\r\n\r\n        return ( temp != zero ) ? ( a / temp * b ) : zero;\r\n    }\r\n\r\n    // Least common multiple for (signed) integers\r\n    template < typename IntegerType >\r\n    inline\r\n    IntegerType\r\n    lcm_integer\r\n    (\r\n        IntegerType const &  a,\r\n        IntegerType const &  b\r\n    )\r\n    {\r\n        // Avoid repeated construction\r\n        IntegerType const  zero = static_cast<IntegerType>( 0 );\r\n        IntegerType const  result = lcm_euclidean( a, b );\r\n\r\n        return ( result < zero ) ? static_cast<IntegerType>(-result) : result;\r\n    }\r\n\r\n    // Function objects to find the best way of computing GCD or LCM\r\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n    template < typename T, bool IsSpecialized, bool IsSigned >\r\n    struct gcd_optimal_evaluator_helper_t\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return gcd_euclidean( a, b );\r\n        }\r\n    };\r\n\r\n    template < typename T >\r\n    struct gcd_optimal_evaluator_helper_t< T, true, true >\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return gcd_integer( a, b );\r\n        }\r\n    };\r\n\r\n    template < typename T >\r\n    struct gcd_optimal_evaluator\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            typedef ::std::numeric_limits<T>  limits_type;\r\n\r\n            typedef gcd_optimal_evaluator_helper_t<T,\r\n             limits_type::is_specialized, limits_type::is_signed>  helper_type;\r\n\r\n            helper_type  solver;\r\n\r\n            return solver( a, b );\r\n        }\r\n    };\r\n#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n    template < typename T >\r\n    struct gcd_optimal_evaluator\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return gcd_integer( a, b );\r\n        }\r\n    };\r\n#endif\r\n\r\n    // Specialize for the built-in integers\r\n#define BOOST_PRIVATE_GCD_UF( Ut )                  \\\r\n    template < >  struct gcd_optimal_evaluator<Ut>  \\\r\n    {  Ut  operator ()( Ut a, Ut b ) const  { return gcd_binary( a, b ); }  }\r\n\r\n    BOOST_PRIVATE_GCD_UF( unsigned char );\r\n    BOOST_PRIVATE_GCD_UF( unsigned short );\r\n    BOOST_PRIVATE_GCD_UF( unsigned );\r\n    BOOST_PRIVATE_GCD_UF( unsigned long );\r\n\r\n#ifdef BOOST_HAS_LONG_LONG\r\n    BOOST_PRIVATE_GCD_UF( boost::ulong_long_type );\r\n#elif defined(BOOST_HAS_MS_INT64)\r\n    BOOST_PRIVATE_GCD_UF( unsigned __int64 );\r\n#endif\r\n\r\n#if CHAR_MIN == 0\r\n    BOOST_PRIVATE_GCD_UF( char ); // char is unsigned\r\n#endif\r\n\r\n#undef BOOST_PRIVATE_GCD_UF\r\n\r\n#define BOOST_PRIVATE_GCD_SF( St, Ut )                            \\\r\n    template < >  struct gcd_optimal_evaluator<St>                \\\r\n    {  St  operator ()( St a, St b ) const  { Ut const  a_abs =   \\\r\n    static_cast<Ut>( a < 0 ? -a : +a ), b_abs = static_cast<Ut>(  \\\r\n    b < 0 ? -b : +b ); return static_cast<St>(                    \\\r\n    gcd_optimal_evaluator<Ut>()(a_abs, b_abs) ); }  }\r\n\r\n    BOOST_PRIVATE_GCD_SF( signed char, unsigned char );\r\n    BOOST_PRIVATE_GCD_SF( short, unsigned short );\r\n    BOOST_PRIVATE_GCD_SF( int, unsigned );\r\n    BOOST_PRIVATE_GCD_SF( long, unsigned long );\r\n\r\n#if CHAR_MIN < 0\r\n    BOOST_PRIVATE_GCD_SF( char, unsigned char ); // char is signed\r\n#endif\r\n\r\n#ifdef BOOST_HAS_LONG_LONG\r\n    BOOST_PRIVATE_GCD_SF( boost::long_long_type, boost::ulong_long_type );\r\n#elif defined(BOOST_HAS_MS_INT64)\r\n    BOOST_PRIVATE_GCD_SF( __int64, unsigned __int64 );\r\n#endif\r\n\r\n#undef BOOST_PRIVATE_GCD_SF\r\n\r\n#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n    template < typename T, bool IsSpecialized, bool IsSigned >\r\n    struct lcm_optimal_evaluator_helper_t\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return lcm_euclidean( a, b );\r\n        }\r\n    };\r\n\r\n    template < typename T >\r\n    struct lcm_optimal_evaluator_helper_t< T, true, true >\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return lcm_integer( a, b );\r\n        }\r\n    };\r\n\r\n    template < typename T >\r\n    struct lcm_optimal_evaluator\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            typedef ::std::numeric_limits<T>  limits_type;\r\n\r\n            typedef lcm_optimal_evaluator_helper_t<T,\r\n             limits_type::is_specialized, limits_type::is_signed>  helper_type;\r\n\r\n            helper_type  solver;\r\n\r\n            return solver( a, b );\r\n        }\r\n    };\r\n#else // BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS\r\n    template < typename T >\r\n    struct lcm_optimal_evaluator\r\n    {\r\n        T  operator ()( T const &a, T const &b )\r\n        {\r\n            return lcm_integer( a, b );\r\n        }\r\n    };\r\n#endif\r\n\r\n    // Functions to find the GCD or LCM in the best way\r\n    template < typename T >\r\n    inline\r\n    T\r\n    gcd_optimal\r\n    (\r\n        T const &  a,\r\n        T const &  b\r\n    )\r\n    {\r\n        gcd_optimal_evaluator<T>  solver;\r\n\r\n        return solver( a, b );\r\n    }\r\n\r\n    template < typename T >\r\n    inline\r\n    T\r\n    lcm_optimal\r\n    (\r\n        T const &  a,\r\n        T const &  b\r\n    )\r\n    {\r\n        lcm_optimal_evaluator<T>  solver;\r\n\r\n        return solver( a, b );\r\n    }\r\n\r\n}  // namespace detail\r\n\r\n\r\n//  Greatest common divisor evaluator member function definition  ------------//\r\n\r\ntemplate < typename IntegerType >\r\ninline\r\ntypename gcd_evaluator<IntegerType>::result_type\r\ngcd_evaluator<IntegerType>::operator ()\r\n(\r\n    first_argument_type const &   a,\r\n    second_argument_type const &  b\r\n) const\r\n{\r\n    return detail::gcd_optimal( a, b );\r\n}\r\n\r\n\r\n//  Least common multiple evaluator member function definition  --------------//\r\n\r\ntemplate < typename IntegerType >\r\ninline\r\ntypename lcm_evaluator<IntegerType>::result_type\r\nlcm_evaluator<IntegerType>::operator ()\r\n(\r\n    first_argument_type const &   a,\r\n    second_argument_type const &  b\r\n) const\r\n{\r\n    return detail::lcm_optimal( a, b );\r\n}\r\n\r\n\r\n//  Greatest common divisor and least common multiple function definitions  --//\r\n\r\ntemplate < typename IntegerType >\r\ninline\r\nIntegerType\r\ngcd\r\n(\r\n    IntegerType const &  a,\r\n    IntegerType const &  b\r\n)\r\n{\r\n    gcd_evaluator<IntegerType>  solver;\r\n\r\n    return solver( a, b );\r\n}\r\n\r\ntemplate < typename IntegerType >\r\ninline\r\nIntegerType\r\nlcm\r\n(\r\n    IntegerType const &  a,\r\n    IntegerType const &  b\r\n)\r\n{\r\n    lcm_evaluator<IntegerType>  solver;\r\n\r\n    return solver( a, b );\r\n}\r\n\r\n\r\n}  // namespace math\r\n}  // namespace boost\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n\r\n#endif  // BOOST_MATH_COMMON_FACTOR_RT_HPP\r\n", "meta": {"hexsha": "4b5ee58377b69c2481808955b44a62938faaf510", "size": 12274, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/common_factor_rt.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/common_factor_rt.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/common_factor_rt.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 26.6247288503, "max_line_length": 81, "alphanum_fraction": 0.5676226169, "num_tokens": 2861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5640595386421112}}
{"text": "#include <iostream>\n#include <boost/format.hpp>\n#include <cmath>\n\nbool bkt_is_ok(float bkt) {\n  return (bkt != 60.0) \n    && (bkt != -60.0)\n    && (bkt != 120.0)\n    && (bkt != -120.0)\n    && (bkt != 50.0) \n    && (bkt != -50.0)\n    && (bkt != 100.0)\n    && (bkt != -100.0);\n}\n\nint main(int argc, char * argv[]) \n{\n  float bkt; \n  float prop; \n  int count = 0; \n  float sum = 0.0;\n  float sumsq = 0.0;\n  bool flag = true; \n  while(flag) {\n    std::cin >> bkt >> prop;\n    flag = !std::cin.eof();\n    if(flag) {\n      if(bkt_is_ok(bkt)) {\n\tcount++;\t\n\tsum += bkt * prop; \n\tsumsq += (bkt * bkt * prop);\n      }\n    }\n  }\n\n  float fcount = float(count); \n  // variance is E[X^2] - (E[X])^2\n  \n  float var = sumsq - sum*sum; \n  float sdev = sqrt(var); \n  std::cout << boost::format(\"mean = %g  var = %g  sdev = %g\\n\")\n    % sum % var % sdev; \n}\n\n", "meta": {"hexsha": "3952d3c0e07a1ff115f6b64b622e8ea56f7ddd50", "size": 841, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/histo2stats.cxx", "max_stars_repo_name": "kb1vc/WSPRLog", "max_stars_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/histo2stats.cxx", "max_issues_repo_name": "kb1vc/WSPRLog", "max_issues_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/histo2stats.cxx", "max_forks_repo_name": "kb1vc/WSPRLog", "max_forks_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6888888889, "max_line_length": 64, "alphanum_fraction": 0.4863258026, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6959583250334527, "lm_q1q2_score": 0.5640595373813312}}
{"text": "/**\n * @file kf_node.cpp\n * @brief !Valgrind output\n *  Memcheck, a memory error detector\n *  Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n *  Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info\n *  Command: ./src/signal_processing/signal_processing_kf_example\n *  \n *  HEAP SUMMARY:\n *      in use at exit: 0 bytes in 0 blocks\n *    total heap usage: 2,127 allocs, 2,127 frees, 128,736 bytes allocated\n *  \n *  All heap blocks were freed -- no leaks are possible\n *  \n *  For lists of detected and suppressed errors, rerun with: -s\n *  ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)\n */\n\n#include <kalman_filter.hpp>\n#include <Eigen/Dense>\n#include <memory>\n#include <iostream>\n#include <vector>\n#include <ctime>\n\nusing namespace filter;\n\nint main(int argc, char* argv[])\n{\n    int n = 3; // Number of states [position, velocity, acceleration].\n    int m = 1; // Number of measurements.\n    double dt = 1.0/30; // Timestamp.\n\n    // Declare MAT for Kalman filter computation.\n    Eigen::MatrixXd A(n, n); // System dynamics matrix\n    Eigen::MatrixXd C(m, n); // Output matrix\n    Eigen::MatrixXd Q(n, n); // Process noise covariance\n    Eigen::MatrixXd R(m, m); // Measurement noise covariance\n    Eigen::MatrixXd P(n, n); // Estimate error covariance\n\n    // Measure the position only.\n    A << \n        1, dt, 0, \n        0, 1, dt, \n        0, 0, 1;\n\n    C << 1, 0, 0;\n\n    // Reasonable covariance matrices\n    Q << \n        .05, .05, .0, \n        .05, .05, .0, \n        .0, .0, .0;\n\n    R << 1;\n\n    P << \n        .1, .1, .1, \n        .1, 10000, 10, \n        .1, 10, 100;\n\n    // Generate random values from 0 - 1.\n    std::srand(std::time(0));\n    std::vector<double> measurements;\n\n    for(unsigned int i = 0; i < 100 ; i++)\n    {\n        double noise = ((double)std::rand() / (double)RAND_MAX);\n        measurements.push_back(noise);\n    }\n\n    // Initialize Kalman filter.\n    auto KF = std::unique_ptr<KalmanFilter>(new KalmanFilter(A, C, Q, R, P));\n\n    // Start the Kalman filter with zero initial parameters.\n    KF->init();\n\n    // Feed the measurements to the filter and get estimated states of a system.\n    Eigen::VectorXd y(m);\n    for(unsigned int i = 0; i < measurements.size(); i++)\n    {\n        y << measurements[i];\n        std::cout << \"KF Result 結果: \" << KF->compute(y, dt).transpose() << std::endl;\n        \n        /** !Output.\n         * @brief KF Result 結果:  0.513434 -0.150251 -0.213232\n         * \n         * @brief [position, velocity, acceleration]\n         */\n    }\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "8ada345d6759659908f23afaeda0af668d06305e", "size": 2579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/signal_processing/example/kalman.cpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/signal_processing/example/kalman.cpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/signal_processing/example/kalman.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": 27.7311827957, "max_line_length": 85, "alphanum_fraction": 0.591314463, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5639713633788244}}
{"text": "#include <cmath>\n#include <iostream>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/lambert_w.hpp>\n#include <boost/core/demangle.hpp>\n#include \"quicksvg/ulp_plot.hpp\"\n\nusing boost::math::lambert_w0;\nusing boost::math::lambert_wm1;\nusing boost::math::lambert_w0_prime;\nusing boost::math::lambert_wm1_prime;\nusing boost::multiprecision::float128;\nusing boost::math::constants::exp_minus_one;\n\nint main()\n{\n    using PreciseReal = float128;\n    using CoarseReal = float;\n    CoarseReal divider = -0.3667;\n    int samples = 15000;\n    CoarseReal a = -exp_minus_one<CoarseReal>();\n    CoarseReal b = divider;\n    std::string title = \"ULP accuracy of \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision Lambert W₀ on (-1/e, -0.3667)\";\n    std::cout << title << \"\\n\";\n    //title = \"\";\n    std::string filename = \"examples/ulp_lambert_w0_1e_3667.svg\";\n    auto flo = [](CoarseReal x)->CoarseReal { return lambert_w0<CoarseReal>(x); };\n    auto fhi = [](PreciseReal x)->PreciseReal { return lambert_w0<PreciseReal>(x); };\n\n    int clip = 3;\n    int horizontal_lines = 5;\n    int vertical_lines = 5;\n    auto ulp_plot = quicksvg::ulp_plot<decltype(fhi), PreciseReal, CoarseReal>(fhi, a, b, true, samples);\n    ulp_plot.add_fn(flo);\n    ulp_plot.write(filename, clip, true, title, 1100, horizontal_lines, vertical_lines);\n    clip = 100;\n    filename = \"examples/ulp_lambert_w0_1e_3667_clip_\" + std::to_string(clip) + \".svg\";\n    ulp_plot.write(filename, clip, true, title, 1100, horizontal_lines, vertical_lines);\n\n}\n", "meta": {"hexsha": "8943b88366fd2a66ea0de13841ce8268f7d4cd5d", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lambertw_ulp.cpp", "max_stars_repo_name": "NAThompson/quicksvg", "max_stars_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:07:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T00:07:53.000Z", "max_issues_repo_path": "lambertw_ulp.cpp", "max_issues_repo_name": "NAThompson/quicksvg", "max_issues_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lambertw_ulp.cpp", "max_forks_repo_name": "NAThompson/quicksvg", "max_forks_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T13:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T11:30:58.000Z", "avg_line_length": 38.2380952381, "max_line_length": 139, "alphanum_fraction": 0.7061021171, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.5639270551547378}}
{"text": "#ifndef SM_READER_HH\n#define SM_READER_HH\n\n#include <Eigen/Dense>\n\n#include <pcl/common/transforms.h>\n#include <pcl/octree/octree_search.h>  // for occlusion detection\n// #include <pcl/surface/texture_mapping.h>  // for occlusion detection\n\n/* \nYou need first 3 parameters that define your camera: the focal length f, and the center of the projection plane: cx, cy. With this you create a 3x3 matrix (I will use matlab syntax):\n\nA = [ fx 0 cx;\n\t  0 fy cy;\n\t  0 0  1 ];\nYou can use something like cx = 0.5 * image_width, cy = 0.5 * image_height, and some value as fx/fy = 800 (try some of them to check how the image looks better).\n\nThen, a 3x4 matrix with the transformation from the camera frame to the point cloud frame:\n\nT = [ r11 r12 r13 tx;\n\t  r21 r22 r23 ty;\n\t  r31 r32 r33 tz ];\nAnd finally, your point cloud in homogeneous coordinates, i.e. in a 4xN matrix for a point cloud with N points:\n\nP = [ x1 x2 ... xN;\n\t  y1 y2 ... yN;\n\t  z1 z2 ... zN;\n\t   1  1 ...  1 ];\nNow you can project the points:\n\nS = A * T * P;\nS is a 3xN matrix where the pixel coordinates of each i-th 3D point are:\n\nx = S(1, i) / S(3, i);\ny = S(2, i) / S(3, i);\n*/\n\n\ntemplate <typename PointT>\nclass PinholeCamera\n{\n\ttypedef typename pcl::PCLBase<PointT>::PointCloud PointCloud;\n\ttypedef typename pcl::PCLBase<PointT>::PointCloudConstPtr PointCloudConstPtr;\n\ttypedef typename pcl::octree::OctreePointCloudSearch<PointT> Octree;\n\ttypedef typename Octree::Ptr OctreePtr;\n\npublic:\n\tPinholeCamera(float fx, float fy, float cx, float cy, const Eigen::Matrix4f& camera_pose = Eigen::Matrix4f::Identity()):\n\t\tT_(3,4)\n\t{\n\t\tfx_ = fx;\n\t\tfy_ = fy;\n\t\tcx_ = cx;\n\t\tcy_ = cy;\n\n\t\tset_camera_pose(camera_pose);\n\t}\n\n\n\tbool isPointOccluded (const PointT &pt, OctreePtr octree, double dist_thresh = 0)\n\t{\n\t  Eigen::Vector3f direction;\n\t  direction (0) = pt.x;\n\t  direction (1) = pt.y;\n\t  direction (2) = pt.z;\n\n\t  std::vector<int> indices;\n\n\t  PointCloudConstPtr cloud (new PointCloud());\n\t  cloud = octree->getInputCloud();\n\n\t  double distance_threshold = octree->getResolution();\n\t  if (dist_thresh > 0)\n\t  {\n\t  \tdistance_threshold = dist_thresh;\n\t  }\n\n\t  // raytrace\n\t  octree->getIntersectedVoxelIndices(direction, -direction, indices);\n\n\t  int nbocc = static_cast<int> (indices.size ());\n\t  for (size_t j = 0; j < indices.size (); j++)\n\t  {\n\t   // if intersected point is on the over side of the camera\n\t   if (pt.z * cloud->points[indices[j]].z < 0)\n\t   {\n\t     nbocc--;\n\t     continue;\n\t   }\n\n\t   if (std::fabs (cloud->points[indices[j]].z - pt.z) <= distance_threshold)\n\t   {\n\t     // points are very close to each-other, we do not consider the occlusion\n\t     nbocc--;\n\t   }\n\t  }\n\n\t  if (nbocc == 0)\n\t   return (false);\n\t  else\n\t   return (true);\n\t}\n\n\t// setter methods\n\tinline void set_fx(float fx)\n\t{\t\n\t\tfx_ = fx;\n\t}\n\tinline void set_fy(float fy)\n\t{\t\n\t\tfy_ = fy;\n\t}\n\tinline void set_cx(float cx)\n\t{\t\n\t\tcx_ = cx;\n\t}\n\tinline void set_cy(float cy)\n\t{\t\n\t\tcy_ = cy;\n\t}\n\n\tinline void set_image_width(int width)\n\t{\n\t\timage_width_ = width;\n\t}\n\tinline void set_image_height(int height)\n\t{\n\t\timage_height_ = height;\n\t}\n\n\tinline void set_camera_pose(const Eigen::Matrix4f& camera_pose)\n\t{\n\t\tcamera_pose_ = camera_pose;\n\t}\n\n\tinline void set_input_cloud(const PointCloudConstPtr &cloud)\n\t{\n\t\tcloud_ = cloud;\n\n\t\thas_cloud = true;\n\t}\n\n\t// getter methods\n\tinline float get_fx() const\n\t{\n\t\treturn fx_;\n\t}\n\tinline float get_fy() const\n\t{\n\t\treturn fy_;\n\t}\n\tinline float get_cx() const\n\t{\n\t\treturn cx_;\n\t}\n\tinline float get_cy() const\n\t{\n\t\treturn cy_;\n\t}\n\tinline int get_image_width() const\n\t{\n\t\treturn image_width_;\n\t}\n\tinline int get_image_height() const\n\t{\n\t\treturn image_height_;\n\t}\n\tinline size_t get_cloud_size() const\n\t{\n\t\treturn cloud_->size();\n\t}\n\tinline Eigen::Matrix4f get_camera_pose() const\n\t{\n\t\treturn camera_pose_;\n\t}\n\n\n\tvoid project(cv::Mat& proj_img, Eigen::MatrixXi& uv_idx_map)\n\t{\n\t\tif (!has_cloud)\n\t\t{\n\t\t\tprintf(\"Cloud has not yet been added!\\n\");\n\t\t\treturn;\n\t\t}\n\t\tcompute_A();\n\t\tcompute_T();\n\t\tcompute_P();\n\n\t\tEigen::MatrixXf S = A_ * T_ * P_;\n\n\t\tproj_img = cv::Mat::zeros(image_height_, image_width_, CV_8UC3);\n\t\tuv_idx_map = Eigen::MatrixXi::Constant(image_height_, image_width_, -1);\n\n\t\ttypename pcl::PointCloud<PointT>::Ptr rot_cloud (new pcl::PointCloud<PointT>);\n\t\tpcl::transformPointCloud(*cloud_, *rot_cloud, camera_pose_);\n\n\t\tconst int N = cloud_->size();\n\t\t// store a cache of the distance of all the points to origin\n\t\tstd::vector<float> pts_distance_cache(N);\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tpts_distance_cache[i] = get_pt_distance(rot_cloud->points[i]);\n\t\t}\n\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\t// std::cout << S(0, i) << std::endl;\n\t\t\tfloat x = S(0, i) / S(2, i);\n\t\t\tfloat y = S(1, i) / S(2, i);\n\n\t\t\tif (x >= image_width_ || x < 0 || y >= image_height_ || y < 0)\n\t\t\t\tcontinue;\n\n\t\t\tconst PointT& pt = cloud_->points[i];\n\t\t\tif (!pt_has_nan(pt))\n\t\t\t{\n\t\t\t\t// printf(\"%.3f %.3f,\", y, x);\n\t\t\t\tbool updated = false;\n\t\t\t\tint prev_map_idx = uv_idx_map(y, x);\n\t\t\t\tif (prev_map_idx == -1)\n\t\t\t\t{\n\t\t\t\t\tuv_idx_map(y, x) = i;\n\t\t\t\t\tupdated = true;\n\t\t\t\t} else {\n\t\t\t\t\t// if another point has the same uv mapping pixel, compare distance from camera to point and use the closest \n\t\t\t\t\tif (pts_distance_cache[i] < pts_distance_cache[prev_map_idx])\n\t\t\t\t\t{\n\t\t\t\t\t\tuv_idx_map(y, x) = i;\t\n\t\t\t\t\t\tupdated = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (updated)\n\t\t\t\t{\t\t\t\n\t\t\t\t\tauto& px = proj_img.at<cv::Vec3b>(y,x);\t\n\t\t\t\t\tpx[0] = pt.b;\n\t\t\t\t\tpx[1] = pt.g;\n\t\t\t\t\tpx[2] = pt.r;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid project(cv::Mat& proj_img, std::vector<std::vector<std::vector<int>>>& uv_idx_map)\n\t{\n\t\tif (!has_cloud)\n\t\t{\n\t\t\tprintf(\"Cloud has not yet been added!\\n\");\n\t\t\treturn;\n\t\t}\n\t\tcompute_A();\n\t\tcompute_T();\n\t\tcompute_P();\n\n\t\tEigen::MatrixXf S = A_ * T_ * P_;\n\n\t\tproj_img = cv::Mat::zeros(image_height_, image_width_, CV_8UC3);\n\t\tuv_idx_map.resize(image_height_);\n\t\tfor (int y = 0; y < image_height_; ++y)\n\t\t{\n\t\t\tuv_idx_map[y].resize(image_width_);\n\t\t\tfor (int x = 0; x < image_width_; ++x)\n\t\t\t{\n\t\t\t\tuv_idx_map[y][x] = {};\n\t\t\t}\n\t\t}\n\n\t\ttypename pcl::PointCloud<PointT>::Ptr rot_cloud (new pcl::PointCloud<PointT>);\n\t\tpcl::transformPointCloud(*cloud_, *rot_cloud, camera_pose_);\n\n\t\tconst int N = cloud_->size();\n\t\t// store a cache of the distance of all the points to origin\n\t\tstd::vector<float> pts_distance_cache(N);\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tpts_distance_cache[i] = get_pt_distance(rot_cloud->points[i]);\n\t\t}\n\n\t\t// Store a cache (as Matrix) of the minimum point distance for each pixel point\n\t\tEigen::MatrixXf uv_min_distance_cache = Eigen::MatrixXf::Constant(image_height_, image_width_, -1); \n\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\t// std::cout << S(0, i) << std::endl;\n\t\t\tfloat x = S(0, i) / S(2, i);\n\t\t\tfloat y = S(1, i) / S(2, i);\n\n\t\t\tif (x >= image_width_ || x < 0 || y >= image_height_ || y < 0)\n\t\t\t\tcontinue;\n\n\t\t\tconst PointT& pt = cloud_->points[i];\n\t\t\tif (!pt_has_nan(pt))\n\t\t\t{\n\t\t\t\tuv_idx_map[y][x].push_back(i);\n\n\t\t\t\tfloat pt_dist = pts_distance_cache[i];\n\t\t\t\tfloat min_cache_dist = uv_min_distance_cache(y,x);\n\n\t\t\t\tif (pt_dist < min_cache_dist || min_cache_dist == -1)\n\t\t\t\t{\n\t\t\t\t\tauto& px = proj_img.at<cv::Vec3b>(y,x);\n\t\t\t\t\tpx[0] = pt.b;\n\t\t\t\t\tpx[1] = pt.g;\n\t\t\t\t\tpx[2] = pt.r;\n\n\t\t\t\t\tuv_min_distance_cache(y,x) = pt_dist;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/* \n\n\t*/\n\tvoid project_surface(cv::Mat& proj_img, std::vector<std::vector<std::vector<int>>>& uv_idx_map, float dist_tolerance=0)\n\t{\n\t\tif (!has_cloud)\n\t\t{\n\t\t\tprintf(\"Cloud has not yet been added!\\n\");\n\t\t\treturn;\n\t\t}\n\t\tcompute_A();\n\t\tcompute_T();\n\t\tcompute_P();\n\n\t\tEigen::MatrixXf S = A_ * T_ * P_;\n\n\t\tproj_img = cv::Mat::zeros(image_height_, image_width_, CV_8UC3);\n\t\tuv_idx_map.resize(image_height_);\n\t\tfor (int y = 0; y < image_height_; ++y)\n\t\t{\n\t\t\tuv_idx_map[y].resize(image_width_);\n\t\t\tfor (int x = 0; x < image_width_; ++x)\n\t\t\t{\n\t\t\t\tuv_idx_map[y][x] = {};\n\t\t\t}\n\t\t}\n\n\t\ttypename pcl::PointCloud<PointT>::Ptr rot_cloud (new pcl::PointCloud<PointT>);\n\t\tpcl::transformPointCloud(*cloud_, *rot_cloud, camera_pose_);\n\n\t\tconst int N = cloud_->size();\n\t\t// store a cache of the distance of all the points to origin\n\t\tstd::vector<float> pts_distance_cache(N);\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tpts_distance_cache[i] = get_pt_distance(rot_cloud->points[i]);\n\t\t}\n\n\t\t// Store a cache (as Matrix) of the minimum point distance for each pixel point\n\t\tEigen::MatrixXf uv_min_distance_cache = Eigen::MatrixXf::Constant(image_height_, image_width_, -1); \n\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\t// std::cout << S(0, i) << std::endl;\n\t\t\tfloat x = S(0, i) / S(2, i);\n\t\t\tfloat y = S(1, i) / S(2, i);\n\n\t\t\tif (x >= image_width_ || x < 0 || y >= image_height_ || y < 0)\n\t\t\t\tcontinue;\n\n\t\t\tconst PointT& pt = cloud_->points[i];\n\t\t\tif (!pt_has_nan(pt))\n\t\t\t{\n\t\t\t\tfloat pt_dist = pts_distance_cache[i];\n\t\t\t\tfloat min_cache_dist = uv_min_distance_cache(y,x);\n\n\t\t\t\tbool updated = false;\n\t\t\t\tif (min_cache_dist == -1 || pt_dist < min_cache_dist)\n\t\t\t\t{\n\t\t\t\t\tuv_min_distance_cache(y,x) = pt_dist;\n\t\t\t\t\t// update (check previous added points and remove if exceeds dist tolerance) then add this\n\t\t\t\t\tauto& cur_indices = uv_idx_map[y][x]; // naturally sorted\n\t\t\t\t\tint r = 0;\n\t\t\t\t\tfor (int ix = 0; ix < cur_indices.size(); ++ix)\n\t\t\t\t\t{\n\t\t\t\t\t\tint idx = ix - r;\n\t\t\t\t\t\tif (pts_distance_cache[cur_indices[idx]] > pt_dist + dist_tolerance)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcur_indices.erase(cur_indices.begin() + idx);\n\t\t\t\t\t\t\t++r;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcur_indices.push_back(i);\n\n\t\t\t\t\tauto& px = proj_img.at<cv::Vec3b>(y,x);\t\n\t\t\t\t\tpx[0] = pt.b;\n\t\t\t\t\tpx[1] = pt.g;\n\t\t\t\t\tpx[2] = pt.r;\n\t\t\t\t} else if (pt_dist < min_cache_dist + dist_tolerance)\n\t\t\t\t{\n\t\t\t\t\t// add \n\t\t\t\t\tuv_idx_map[y][x].push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid project_non_occluded_surface(cv::Mat& proj_img, std::vector<std::vector<std::vector<int>>>& uv_idx_map, float octree_resolution=0.02, float dist_threshold = 0)\n\t{\n\t\tif (!has_cloud)\n\t\t{\n\t\t\tprintf(\"Cloud has not yet been added!\\n\");\n\t\t\treturn;\n\t\t}\n\t\tcompute_A();\n\t\tcompute_T();\n\t\tcompute_P();\n\n\t\tEigen::MatrixXf S = A_ * T_ * P_;\n\n\t\tproj_img = cv::Mat::zeros(image_height_, image_width_, CV_8UC3);\n\t\tuv_idx_map.resize(image_height_);\n\t\tfor (int y = 0; y < image_height_; ++y)\n\t\t{\n\t\t\tuv_idx_map[y].resize(image_width_);\n\t\t\tfor (int x = 0; x < image_width_; ++x)\n\t\t\t{\n\t\t\t\tuv_idx_map[y][x] = {};\n\t\t\t}\n\t\t}\n\n\t\ttypename pcl::PointCloud<PointT>::Ptr rot_cloud (new pcl::PointCloud<PointT>);\n\t\tpcl::transformPointCloud(*cloud_, *rot_cloud, camera_pose_);\n\n\t\tOctreePtr octree (new Octree(octree_resolution));\n\t\toctree->setInputCloud (rot_cloud);\n\t\toctree->addPointsFromInputCloud ();\n\n\t\tconst int N = cloud_->size();\n\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\t// std::cout << S(0, i) << std::endl;\n\t\t\tfloat x = S(0, i) / S(2, i);\n\t\t\tfloat y = S(1, i) / S(2, i);\n\n\t\t\tif (x >= image_width_ || x < 0 || y >= image_height_ || y < 0)\n\t\t\t\tcontinue;\n\n\t\t\tconst PointT& pt = cloud_->points[i];\n\t\t\tif (!pt_has_nan(pt))\n\t\t\t{\n\t\t\t\t// check occlusion\n\t\t\t\tbool is_occ = isPointOccluded(rot_cloud->points[i], octree, dist_threshold);\n\t\t\t\tif (!is_occ)\n\t\t\t\t{\n\t\t\t\t\tuv_idx_map[y][x].push_back(i);\n\n\t\t\t\t\t// TODO: only update pixel to closest point \n\t\t\t\t\tauto& px = proj_img.at<cv::Vec3b>(y,x);\n\t\t\t\t\tpx[0] = pt.b;\n\t\t\t\t\tpx[1] = pt.g;\n\t\t\t\t\tpx[2] = pt.r;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\ttemplate <typename PT>\n\tstatic inline bool pt_has_nan(const PT& pt)\n\t{\n\t\treturn std::isnan(pt.x) || std::isnan(pt.y) || std::isnan(pt.z);\n\t}\n\n\tinline void compute_A()\n\t{\n\t\tA_ << fx_, 0, cx_, 0, fy_, cy_, 0, 0, 1;\n\t}\n\tinline void compute_T()\n\t{\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tT_(i,0) = camera_pose_(i,0);\n\t\t\tT_(i,1) = camera_pose_(i,1);\n\t\t\tT_(i,2) = camera_pose_(i,2);\n\t\t\tT_(i,3) = camera_pose_(i,3);\n\t\t}\n\t}\n\tinline void compute_P()\n\t{\n\t\tconst int N = cloud_->size();\n\n\t\tP_.resize(4, N);\n\t\tfor (int i = 0; i < N; ++i)\n\t\t{\n\t\t\tconst PointT& pt = cloud_->points[i];\n\t\t\tP_(0,i) = pt.x;\n\t\t\tP_(1,i) = pt.y;\n\t\t\tP_(2,i) = pt.z;\n\t\t\tP_(3,i) = 1;\n\t\t}\n\t}\n\n\ttemplate <typename Pt>\n\tinline double get_pt_distance(const Pt& pt)\n\t{\n\t\treturn Eigen::Vector3f(pt.x, pt.y, pt.z).squaredNorm();\n\t}\n\n\tfloat fx_; \n\tfloat fy_; \n\tfloat cx_;\n\tfloat cy_;\t\n\n\tint image_height_ = 800;\n\tint image_width_ = 800;\n\n\tEigen::Matrix4f camera_pose_;\n\tPointCloudConstPtr cloud_;\n\n\t// computed \n\tEigen::Matrix3f A_;\n\tEigen::MatrixXf T_;\n\tEigen::MatrixXf P_;\n\n\t// state\n\tbool has_cloud = false;\n\n\t// algorithms\n\t// typename pcl::TextureMapping<PointT> tm_;\n};\n\n#endif\n", "meta": {"hexsha": "fa684cb8636d02f0fbf63118767690dd6dfd9c8d", "size": 12238, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/pinhole_camera.hh", "max_stars_repo_name": "vincentlooi/labelme_3D", "max_stars_repo_head_hexsha": "c083299ac512c6f6bc0ae35cabda8f39bc3953f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-08T16:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:29:27.000Z", "max_issues_repo_path": "include/pinhole_camera.hh", "max_issues_repo_name": "vincentlooi/labelme_3D", "max_issues_repo_head_hexsha": "c083299ac512c6f6bc0ae35cabda8f39bc3953f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pinhole_camera.hh", "max_forks_repo_name": "vincentlooi/labelme_3D", "max_forks_repo_head_hexsha": "c083299ac512c6f6bc0ae35cabda8f39bc3953f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T18:42:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T06:48:33.000Z", "avg_line_length": 23.2661596958, "max_line_length": 182, "alphanum_fraction": 0.6215067822, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.5639270544491624}}
{"text": "#ifndef BART_SRC_FORMULATION_SCALAR_DIFFUSION_I_HPP_\n#define BART_SRC_FORMULATION_SCALAR_DIFFUSION_I_HPP_\n\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/dofs/dof_accessor.h>\n\n#include \"formulation/common/rhs_constant_i.hpp\"\n#include \"system/moments/spherical_harmonic_types.h\"\n#include \"utility/has_description.h\"\n\n//! Scalar (non-angular) formulations of the transport equation.\nnamespace bart::formulation::scalar {\n\n/*! \\brief Interface for classes that provide the diffusion formulation of the transport equation.\n *\n * The diffusion formulation is a common non-angular version of the transport equation that models neutron propegation\n * diffusively, much like the heat equation. Therefore, this is naturally a second-order formulation of the transport\n * equation. The diffusion equation is derived by integrating the first-order transport equation over angle and\n * using Fick's law as a closure for the current. The multigroup diffusion equation for a multiplying medium\n * in _k_-eigenvalue form is,\n *\n * \\f[\n * -D_g(\\vec{r})\\vec{\\nabla} \\cdot \\vec{\\nabla} \\phi_g(\\vec{r}) + (\\Sigma_{t,g} - \\Sigma_{s}^{g\\to g})\\phi_g(\\vec{r})\n * = \\sum_{g' \\neq g}\\Sigma_{g}^{g' \\to g}\\phi_{g'}(\\vec{r}) + \\frac{\\chi_g}{k}\\sum_{g'}\\nu_{g'}\\Sigma_{f,g'}\\phi_{g'}(\\vec{r})\n * \\f]\n *\n * With weak formulation,\n *\n * \\f[\n * \\bigg(\\nabla \\cdot v(\\vec{r}), D_g\\nabla\\cdot\\phi_{g}(\\vec{r})\\bigg)_{K} + \\bigg(v(\\vec{r}), (\\Sigma_{t,g} - \\Sigma_{s}^{g\\to g})\\phi_g(\\vec{r})\\bigg)_{K}\n * + \\bigg(v(\\vec{r}), \\frac{1}{2}\\phi_g(\\vec{r})\\bigg)_{\\partial K, \\text{vacuum}} =\n * \\bigg(v(\\vec{r}),\\sum_{g' \\neq g}\\Sigma_{g}^{g' \\to g}\\phi_{g'}(\\vec{r})\\bigg)_{K} +\n * \\bigg(v(\\vec{r}), \\frac{\\chi_g}{k}\\sum_{g'}\\nu_{g'}\\Sigma_{f,g'}\\phi_{g'}(\\vec{r})\\bigg)_{K}\\;.\n * \\f]\n *\n * Each of these terms are stamped individually on the system matrix, \\f$\\mathbf{A}\\f$ or vector \\f$\\vec{b}\\f$\n * by the member functions of classes that derive from this interface. The integration over the element \\f$K\\f$ is done\n * using the cell quadrature and the right-hand-side scalar fluxes are treated as sources from the previous iteration.\n *\n * For further information about this derivation see any neutron transport text such as\n * <a href=\"https://www.ans.org/store/item-350016/\">Lewis and Miller</a>.\n * @tparam dim spatial dimension\n */\ntemplate <int dim>\nclass DiffusionI : public common::RHSConstantI<dim>, public utility::HasDescription {\n public:\n  //! Types of boundaries for the diffusion equation\n  enum class BoundaryType {\n    kVacuum,\n    kReflective\n  };\n\n  //! Pointer to a cell iterator returned by a dof object.\n  using CellPtr = typename dealii::DoFHandler<dim>::active_cell_iterator;\n  using Matrix = dealii::FullMatrix<double>;\n  using Vector = dealii::Vector<double>;\n  using GroupNumber = int;\n  using FaceNumber = int;\n\n  virtual ~DiffusionI() = default;\n\n  /*! \\brief Precalculate many of the shape functions.\n   *\n   * The bilinear terms require the shape-funtion or gradient of the shape function squared. This function precalculates\n   * those, reducing the number of times the underlying finite element object needs to be called. The shape functions\n   * for each cell are identical, and the jacobian is used to translate from the base cell.\n   *\n   * @param cell_ptr an arbitrary cell to use, often just the beginning of active cells.\n   */\n  virtual auto Precalculate(const CellPtr& cell_ptr) -> void = 0;\n\n  /*! \\brief Integrates the bilinear streaming term over a cell and fills a given matrix.\n   *\n   * For a given cell in the triangulation, \\f$K \\in T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the bilinear SAAF streaming term for\n   * one group using the cell quadrature and adds them to the provided\n   * local cell matrix, \\f$\\mathbf{A}\\f$:\n   *\n   * \\f[\n   * \\mathbf{A}(i,j)_{K,g}' = \\mathbf{A}(i,j)_{K,g} + \\int_{K}D_g\\nabla\\varphi_i(\\vec{r})\\nabla\\varphi_j(\\vec{r})dV\n   * \\f]\n   *\n   * @param to_fill\n   */\n  virtual auto FillCellStreamingTerm(Matrix& to_fill, const CellPtr&, GroupNumber) const -> void = 0;\n  /*! \\brief Integrates the bilinear collision term over a cell and fills a given matrix.\n   *\n   * For a given cell in the triangulation, \\f$K \\in T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the bilinear SAAF streaming term for\n   * one group using the cell quadrature and adds them to the provided\n   * local cell matrix, \\f$\\mathbf{A}\\f$:\n   *\n   * \\f[\n   * \\mathbf{A}(i,j)_{K,g}' = \\mathbf{A}(i,j)_{K,g} + \\int_{K}\\varphi_i(\\vec{r})(\\Sigma_{t,g} - \\Sigma_{s, g \\to g})\\varphi_j(\\vec{r})dV\n   * \\f]\n   *\n   * @param to_fill\n   */\n  virtual auto FillCellCollisionTerm(Matrix& to_fill, const CellPtr&, GroupNumber) const -> void = 0;\n/*! \\brief Integrates the bilinear boundary term over a cell and fills a given matrix.\n   *\n   * For a given cell and face in the triangulation, \\f$\\partial K \\in \\partial T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the bilinear diffusion boundary term for\n   * one group using the cell quadrature and adds them to the provided\n   * local cell matrix, \\f$\\mathbf{A}\\f$. For reflective boundary conditions, nothing is added, for vacuum:\n   *\n   * \\f[\n   * \\mathbf{A}(i,j)_{K,g}' = \\mathbf{A}(i,j)_{K,g} + \\frac{1}{2}\\int_{\\partial K}\\varphi_i(\\vec{r})\\varphi_j(\\vec{r})dV\n   * \\f]\n   *\n   * @param to_fill\n   */\n  virtual auto FillBoundaryTerm(Matrix& to_fill, const CellPtr&, FaceNumber, BoundaryType) const -> void = 0;\n\n  /*! \\brief Integrates the fixed source term and fills a given vector.\n   *\n   * For a given cell in the triangulation, \\f$K \\in T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the diffusion fixed-source term and\n   * adds it to the cell right-hand side vector.\n   * \\f[\n   * \\vec{b}(i)_{K,g}' = \\vec{b}(i)_{K,g} + \\int_{K}q_{g}(\\vec{r})\\varphi_i(\\vec{r})dV\n   * \\f]\n   *\n   * where \\f$\\phi\\f$ is the scalar flux. Adds the result per cell DOFF to the\n   * input-output vector cell_rhs.\n   *\n   *\n   * @param to_fill cell vector to fill\n   */\n  virtual auto FillCellFixedSource(Vector& to_fill, const CellPtr&, GroupNumber) const -> void = 0;\n\n  /*! \\brief Integrates the fission source term and fills a given cell vector.\n   *\n   * For a given cell in the triangulation, \\f$K \\in T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the diffusion fission-source term and\n   * adds it to the cell right-hand side vector.\n   * \\f[\n   * \\vec{b}(i)_{K,g}' = \\vec{b}(i)_{K,g} + \\frac{\\chi_g}{k}\\sum_{g'}\\int_{K}\\varphi_i(\\vec{r})\\Sigma_{f,g'}\\nu_{g'}\\phi_{g'}(\\vec{r})dV\n   * \\f]\n   *\n   * @param to_fill cell vector to fill\n   * @param k_eigenvalue value of the _k_-eigenvalue\n   * @param in_group_moment scalar flux moment for the current group\n   * @param group_moments scalar flux moment for all other groups\n   */\n  virtual auto FillCellFissionSource(Vector& to_fill, const CellPtr&, GroupNumber, double k_eigenvalue,\n                                     const system::moments::MomentVector& in_group_moment,\n                                     const system::moments::MomentsMap& group_moments) const -> void = 0;\n\n  /*! \\brief Integrates the scattering source term and fills a given cell vector.\n   *\n   * For a given cell in the triangulation, \\f$K \\in T_K\\f$, with basis functions\n   * \\f$\\varphi\\f$, this function integrates the diffusion scattering-source term and\n   * adds it to the cell right-hand side vector.\n   * \\f[\n   * \\vec{b}(i)_{K,g}' = \\vec{b}(i)_{K,g} + \\sum_{g' \\neq g}\\int_{K}\\varphi_i(\\vec{r})\\Sigma_{s,g' \\to g}\\phi_{g'}(\\vec{r})dV\n   * \\f]\n   *\n   * @param to_fill cell vector to fill\n   * @param k_eigenvalue value of the _k_-eigenvalue\n   * @param group_moments scalar flux moment for all groups\n   */\n  virtual auto FillCellScatteringSource(Vector& to_fill, const CellPtr&, GroupNumber,\n                                        const system::moments::MomentsMap& group_moments) const -> void = 0;\n\n  /*! \\brief Returns a bool indicating if Precalculate been called. */\n  virtual auto is_initialized() const -> bool = 0;\n};\n\n} // namespace bart::formulation::scalar\n\n#endif //BART_SRC_FORMULATION_SCALAR_DIFFUSION_I_HPP_", "meta": {"hexsha": "e5956eb8bddf57449a12a954221956eabcb5f116", "size": 8164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/formulation/scalar/diffusion_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/formulation/scalar/diffusion_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/formulation/scalar/diffusion_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": 47.4651162791, "max_line_length": 157, "alphanum_fraction": 0.6795688388, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.56392705303801}}
{"text": "/*\n * Copyright 2020-2021 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace cdm {\n\n/*! \\brief Generate a block diagonal matrix.\n * \\tparam NBlock Number of the block of the matrix.\n * \\param blockMat Block matrix to repeat.\n * \\return Block diagonal matrix.\n */\ntemplate <int NBlock>\nEigen::MatrixXd makeDiag(const Eigen::MatrixXd& blockMat)\n{\n    static_assert(NBlock >= 0, \"Not yet ready for dynamic\");\n    constexpr int N = NBlock;\n    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(N * blockMat.rows(), N * blockMat.cols());\n    for (int i = 0; i < N; ++i)\n        out.block(i * blockMat.rows(), i * blockMat.cols(), blockMat.rows(), blockMat.cols()) = blockMat;\n\n    return out;\n}\n\ntemplate <int NVec>\nEigen::MatrixXd generateD(const CrossN<NVec>& cx)\n{\n    using mat_t = Eigen::Matrix<double, 6 * NVec, 6 * NVec>;\n    using sub_mat_t = Eigen::Matrix<double, 6, 6 * NVec>;\n    Eigen::MatrixXd D_N = Eigen::MatrixXd::Zero(6 * (NVec - 1), 6 * (NVec - 1));\n    for (int i = 0; i < NVec - 1; ++i)\n        D_N.block<6, 6>(6 * i, 6 * i) = Eigen::Matrix6d::Identity() / (i + 1);\n    return mat_t::Identity() + (mat_t() << sub_mat_t::Zero(), D_N * cx.dualMatrix().template topRows<6 * (NVec - 1)>()).finished();\n}\n\n// M = I + Cd * I * C\ntemplate <int Order>\nstd::vector<Eigen::MatrixXd> getSubTreeInertia(const Model& m, const ModelConfig<Order>& mc)\n{\n    static_assert(Order > 0, \"Not yet ready for dynamic\");\n    std::vector<Eigen::MatrixXd> M(static_cast<size_t>(m.nLinks()), Eigen::MatrixXd::Zero(6 * Order, 6 * Order));\n    for (Index i = m.nLinks() - 1; i >= 0; --i) {\n        size_t ui = static_cast<size_t>(i);\n        M[ui] += makeDiag<Order>(m.body(i).inertia().matrix());\n        Index p = m.jointParent(i);\n        if (p != -1) {\n            size_t up = static_cast<size_t>(p);\n            auto C_p_b = mc.bodyMotions[up].inverse() * mc.bodyMotions[ui];\n            M[up] += C_p_b.template dualMatrix<Order>() * M[ui] * C_p_b.inverse().template matrix<Order>();\n        }\n    }\n\n    return M;\n}\n\n} // namespace cdm\n", "meta": {"hexsha": "ab3f5cb8807257e0c41ebfea561f7d594f4e2a18", "size": 2053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cdm/math_utility.hpp", "max_stars_repo_name": "vsamy/cdm", "max_stars_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:29.000Z", "max_issues_repo_path": "include/cdm/math_utility.hpp", "max_issues_repo_name": "vsamy/cdm", "max_issues_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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/cdm/math_utility.hpp", "max_forks_repo_name": "vsamy/cdm", "max_forks_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "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.2166666667, "max_line_length": 131, "alphanum_fraction": 0.6098392596, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5639270331329631}}
{"text": "// Copyright (C) 2019 David Harmon and Artificial Necessity\n// This code distributed under zlib, see LICENSE.txt for terms.\n\n#include \"triangle_energies.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n\nTriangleOrthoStrain::TriangleOrthoStrain(const Eigen::Vector3i& idxs,\n                                         const std::vector<Eigen::Vector3d>& x,\n                                         double ksx, double ksy,\n                                         bool ignore_compression)\n    : idxs_(idxs), ignore_compression_(ignore_compression)  {\n\n    Matrix3x2 Ds;\n    Ds.col(0) = x[1] - x[0];\n    Ds.col(1) = x[2] - x[0];\n\n    // Take n1 as just the first edge, n2 as the orthogonal vector closest to second edge\n    Eigen::Vector3d n1 = Ds.col(0).normalized();\n    Eigen::Vector3d n2 = (Ds.col(1) - Ds.col(1).dot(n1) * n1).normalized();\n\n    Matrix3x2 Dm;\n    Dm.col(0) = n1;\n    Dm.col(1) = n2;\n\n    Eigen::Matrix2d F = Dm.transpose() * Ds;\n    rest_ = F.inverse();\n\n    A_ = F.determinant() * 0.5;\n\n    ksx = std::sqrt(ksx * A_);\n    ksy = std::sqrt(ksy * A_);\n\n    weights_ = Eigen::VectorXd(6);\n    weights_ << ksx, ksx, ksx, ksy, ksy, ksy;\n\n    S_.setZero();\n    S_(0,0) = -1; S_(0,1) = -1;\n    S_(1,0) =  1; S_(2,1) =  1;\n}\n\n\nvoid TriangleOrthoStrain::get_reduction(std::vector<Eigen::Triplet<double>> &triplets) const {\n    const int cols[3] = { 3*idxs_[0], 3*idxs_[1], 3*idxs_[2] };\n\n    Matrix3x2 D = S_ * rest_;\n    for (int i=0; i<3; ++i) {\n        for (int j=0; j<3; ++j) {\n            triplets.emplace_back(i, cols[j]+i, D(j,0));\n            triplets.emplace_back(3+i, cols[j]+i, D(j,1));\n        }\n    }\n}\n\nEigen::VectorXd TriangleOrthoStrain::reduce(const Eigen::VectorXd& x) const {\n    const int cols[3] = { 3*idxs_[0], 3*idxs_[1], 3*idxs_[2] };\n    \n    Vector6d z = Vector6d::Zero();\n\n    Matrix3x2 D = S_ * rest_;\n    for (int i=0; i<3; ++i ) {\n        for (int j=0; j<3; j++) {\n            z[i]   += D(j,0) * x[cols[j]+i];\n            z[3+i] += D(j,1) * x[cols[j]+i];\n        }\n    }\n\n    return z;\n}\n\nvoid TriangleOrthoStrain::project(Eigen::VectorXd& zi) const {\n    Eigen::JacobiSVD<Matrix3x2>\n        svd(Eigen::Map<Matrix3x2>(zi.data()), Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    //Eigen::Vector2d S = Eigen::Vector2d::Ones();\n    //if (ignore_compression_) {\n    //    for (int i=0; i<2; i++) {\n    //        S[i] = std::min(S[i], svd.singularValues()[i]);\n    //    }\n    //}\n\n    //Matrix3x2 P = svd.matrixU().leftCols(2) * S.asDiagonal() * svd.matrixV().transpose();\n\n    Matrix3x2 P = svd.matrixU().leftCols(2) * svd.matrixV().transpose();\n    zi = 0.5 * (Eigen::Map<Vector6d>(P.data()) + zi);\n}\n\n\n", "meta": {"hexsha": "5c7562b206b70f87b8e8f3172c8cc471e770c041", "size": 2640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/triangle_energies.cpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "src/triangle_energies.cpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/triangle_energies.cpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.010989011, "max_line_length": 94, "alphanum_fraction": 0.5481060606, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.5639270274511256}}
{"text": "\n\n#include <NTL/mat_GF2.h>\n#include <NTL/vec_long.h>\n\n\nNTL_START_IMPL\n\n\nvoid add(mat_GF2& X, const mat_GF2& A, const mat_GF2& 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 mw = (m + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n  \n   long i;  \n   for (i = 0; i < n; i++) {\n      _ntl_ulong *xp = X[i].rep.elts();\n      const _ntl_ulong *ap = A[i].rep.elts();\n      const _ntl_ulong *bp = B[i].rep.elts();\n      long j;\n      for (j = 0; j < mw; j++)\n         xp[j] = ap[j] ^ bp[j];\n   }\n}  \n  \nstatic\nvoid mul_aux(vec_GF2& x, const mat_GF2& A, const vec_GF2& 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;  \n  \n   for (i = 0; i < n; i++) {  \n      x.put(i, A[i] * b);\n   }  \n}  \n  \n  \nvoid mul(vec_GF2& x, const mat_GF2& A, const vec_GF2& b)  \n{  \n   if (&b == &x || A.alias(x)) {\n      vec_GF2 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_GF2& x, const vec_GF2& a, const mat_GF2& 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   clear(x);\n\n   const _ntl_ulong *ap = a.rep.elts();\n   _ntl_ulong a_mask = 1;\n\n   _ntl_ulong *xp = x.rep.elts();\n\n   long lw = (l + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n  \n   long i;  \n   for (i = 0; i < n; i++) {  \n      if (*ap & a_mask) {\n         const _ntl_ulong *bp = B[i].rep.elts();\n         long j;\n         for (j = 0; j < lw; j++)\n            xp[j] ^= bp[j];\n      }\n\n      a_mask <<= 1;\n      if (!a_mask) {\n         a_mask = 1;\n         ap++;\n      }\n   }  \n}  \n\nvoid mul(vec_GF2& x, const vec_GF2& a, const mat_GF2& B)\n{\n   if (&a == &x || B.alias(x)) {\n      vec_GF2 tmp;\n      mul_aux(tmp, a, B);\n      x = tmp;\n   }\n   else\n      mul_aux(x, a, B);\n}\n  \nvoid mul_aux(mat_GF2& X, const mat_GF2& A, const mat_GF2& 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;  \n  \n   for (i = 1; i <= n; i++) {  \n      mul_aux(X(i), A(i), B);\n   }  \n}  \n  \n  \nvoid mul(mat_GF2& X, const mat_GF2& A, const mat_GF2& B)  \n{  \n   if (&X == &A || &X == &B) {  \n      mat_GF2 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_GF2& X, long n)  \n{  \n   X.SetDims(n, n);  \n   clear(X);\n   long i;  \n  \n   for (i = 0; i < n; i++)  \n      X.put(i, i, to_GF2(1));\n} \n\n\nvoid determinant(ref_GF2 d, const mat_GF2& M_in)\n{\n   long k, n;\n   long i, j;\n   long pos;\n\n   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   mat_GF2 M;\n\n   M = M_in;\n\n   long wn = (n + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   for (k = 0; k < n; k++) {\n      long wk = k/NTL_BITS_PER_LONG;\n      long bk = k - wk*NTL_BITS_PER_LONG;\n      _ntl_ulong k_mask = 1UL << bk;\n\n      pos = -1;\n      for (i = k; i < n; i++) {\n         if (M[i].rep.elts()[wk] & k_mask) {\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n         }\n\n\n         _ntl_ulong *y = M[k].rep.elts();\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            if (M[i].rep.elts()[wk] & k_mask) {\n               _ntl_ulong *x = M[i].rep.elts();\n\n               for (j = wk; j < wn; j++)\n                  x[j] ^= y[j];\n            }\n\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   set(d);\n   return;\n}\n\nstatic\nlong IsUnitVector(const vec_GF2& a, long i)\n{\n   long wi = i/NTL_BITS_PER_LONG;\n   long bi = i - wi*NTL_BITS_PER_LONG;\n\n   const _ntl_ulong *p = a.rep.elts();\n   long wdlen = a.rep.length();\n\n   long j;\n\n   for (j = 0; j < wi; j++)\n      if (p[j] != 0) return 0;\n\n   if (p[wi] != (1UL << bi))\n      return 0;\n\n   for (j = wi+1; j < wdlen; j++)\n      if (p[j] != 0) return 0;\n\n   return 1;\n}\n\n\nlong IsIdent(const mat_GF2& A, long n)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   if (n == 0) return 1;\n\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsUnitVector(A[i], i))\n         return 0;\n\n   return 1;\n}\n\nvoid AddToCol(mat_GF2& x, long j, const vec_GF2& a)\n// add a to column j of x\n// ALIAS RESTRICTION: a should not alias any row of x\n{\n   long n = x.NumRows();\n   long m = x.NumCols();\n\n   if (a.length() != n || j < 0 || j >= m)\n      LogicError(\"AddToCol: bad args\");\n\n   long wj = j/NTL_BITS_PER_LONG;\n   long bj = j - wj*NTL_BITS_PER_LONG;\n   _ntl_ulong j_mask = 1UL << bj;\n\n   const _ntl_ulong *ap = a.rep.elts();\n   _ntl_ulong a_mask = 1;\n\n   long i;\n   for (i = 0; i < n; i++) {\n      if (*ap & a_mask) \n         x[i].rep.elts()[wj] ^= j_mask;\n\n      a_mask <<= 1;\n      if (!a_mask) {\n         a_mask = 1;\n         ap++;\n      }\n   }\n}\n\n\nvoid transpose_aux(mat_GF2& X, const mat_GF2& A)\n{\n   long n = A.NumRows();\n   long m = A.NumCols();\n\n   X.SetDims(m, n);\n   clear(X);\n\n   long i;\n   for (i = 0; i < n; i++)\n      AddToCol(X, i, A[i]);\n}\n            \n\nvoid transpose(mat_GF2& X, const mat_GF2& A)\n{\n   if (&X == &A) {\n      mat_GF2 tmp;\n      transpose_aux(tmp, A);\n      X = tmp;\n   }\n   else\n      transpose_aux(X, A);\n}\n\n   \n\nstatic\nvoid solve_impl(ref_GF2 d, vec_GF2& X, const mat_GF2& A, const vec_GF2& 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      X.SetLength(0);\n      set(d);\n      return;\n   }\n\n   long i, j, k, pos;\n\n   mat_GF2 M;\n   M.SetDims(n, n+1);\n\n   if (trans) {\n      for (i = 0; i < n; i++) {\n\t AddToCol(M, i, A[i]);\n      }\n   }\n   else {\n      for (i = 0; i < n; i++) {\n         VectorCopy(M[i], A[i], n+1);\n      }\n   }\n\n   AddToCol(M, n, b);\n\n   long wn = ((n+1) + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   for (k = 0; k < n; k++) {\n      long wk = k/NTL_BITS_PER_LONG;\n      long bk = k - wk*NTL_BITS_PER_LONG;\n      _ntl_ulong k_mask = 1UL << bk;\n\n      pos = -1;\n      for (i = k; i < n; i++) {\n         if (M[i].rep.elts()[wk] & k_mask) {\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n         }\n\n         _ntl_ulong *y = M[k].rep.elts();\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            if (M[i].rep.elts()[wk] & k_mask) {\n               _ntl_ulong *x = M[i].rep.elts();\n\n               for (j = wk; j < wn; j++)\n                  x[j] ^= y[j];\n            }\n\n\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   vec_GF2 XX;\n   XX.SetLength(n+1);\n   XX.put(n, 1);\n\n   for (i = n-1; i >= 0; i--) {\n      XX.put(i, XX*M[i]);\n   }\n\n   XX.SetLength(n);\n   X = XX;\n\n   set(d);\n   return;\n}\n\nvoid solve(ref_GF2 d, vec_GF2& x, const mat_GF2& A, const vec_GF2& b)\n{\n   solve_impl(d, x, A, b, true);\n}\n\nvoid solve(ref_GF2 d, const mat_GF2& A, vec_GF2& x,  const vec_GF2& b)\n{\n   solve_impl(d, x, A, b, false);\n}\n\n\nvoid inv(ref_GF2 d, mat_GF2& X, const mat_GF2& A)\n{\n   long n = A.NumRows();\n   if (A.NumCols() != n)\n      LogicError(\"solve: nonsquare matrix\");\n\n   if (n == 0) {\n      X.SetDims(0, 0);\n      set(d);\n   }\n\n   long i, j, k, pos;\n\n   mat_GF2 M;\n   M.SetDims(n, 2*n);\n\n   vec_GF2 aa;\n   aa.SetLength(2*n);\n\n\n   for (i = 0; i < n; i++) {\n      aa = A[i];\n      aa.SetLength(2*n);\n      aa.put(n+i, 1);\n      M[i] = aa;\n   }\n\n   long wn = ((2*n) + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   for (k = 0; k < n; k++) {\n      long wk = k/NTL_BITS_PER_LONG;\n      long bk = k - wk*NTL_BITS_PER_LONG;\n      _ntl_ulong k_mask = 1UL << bk;\n\n      pos = -1;\n      for (i = k; i < n; i++) {\n         if (M[i].rep.elts()[wk] & k_mask) {\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (k != pos) {\n            swap(M[pos], M[k]);\n         }\n\n         _ntl_ulong *y = M[k].rep.elts();\n\n         for (i = k+1; i < n; i++) {\n            // M[i] = M[i] + M[k]*M[i,k]\n\n            if (M[i].rep.elts()[wk] & k_mask) {\n               _ntl_ulong *x = M[i].rep.elts();\n\n               for (j = wk; j < wn; j++)\n                  x[j] ^= y[j];\n            }\n\n\n         }\n      }\n      else {\n         clear(d);\n         return;\n      }\n   }\n\n   vec_GF2 XX;\n   XX.SetLength(2*n);\n\n   X.SetDims(n, n);\n   clear(X);\n\n   for (j = 0; j < n; j++) {\n      XX.SetLength(n+j+1);\n      clear(XX);\n      XX.put(n+j, to_GF2(1));\n      \n      for (i = n-1; i >= 0; i--) {\n         XX.put(i, XX*M[i]);\n      }\n   \n      XX.SetLength(n);\n      AddToCol(X, j, XX);\n   }\n\n   set(d);\n   return;\n}\n\n\n\n\n\nlong gauss(mat_GF2& M, long w)\n{\n   long k, l;\n   long i, j;\n   long pos;\n\n   long n = M.NumRows();\n   long m = M.NumCols();\n\n   if (w < 0 || w > m)\n      LogicError(\"gauss: bad args\");\n\n   long wm = (m + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   l = 0;\n   for (k = 0; k < w && l < n; k++) {\n      long wk = k/NTL_BITS_PER_LONG;\n      long bk = k - wk*NTL_BITS_PER_LONG;\n      _ntl_ulong k_mask = 1UL << bk;\n\n\n      pos = -1;\n      for (i = l; i < n; i++) {\n         if (M[i].rep.elts()[wk] & k_mask) {\n            pos = i;\n            break;\n         }\n      }\n\n      if (pos != -1) {\n         if (l != pos)\n            swap(M[pos], M[l]);\n\n         _ntl_ulong *y = M[l].rep.elts();\n\n         for (i = l+1; i < n; i++) {\n            // M[i] = M[i] + M[l]*M[i,k]\n\n            if (M[i].rep.elts()[wk] & k_mask) {\n               _ntl_ulong *x = M[i].rep.elts();\n\n               for (j = wk; j < wm; j++)\n                  x[j] ^= y[j];\n            }\n         }\n\n         l++;\n      }\n   }\n   \n   return l;\n}\n\nlong gauss(mat_GF2& M)\n{\n   return gauss(M, M.NumCols());\n}\n\n\nvoid image(mat_GF2& X, const mat_GF2& A)\n{\n   mat_GF2 M;\n   M = A;\n   long r = gauss(M);\n   M.SetDims(r, M.NumCols());\n   X = M;\n}\n\nvoid kernel(mat_GF2& X, const mat_GF2& A)\n{\n   long m = A.NumRows();\n   long n = A.NumCols();\n\n   mat_GF2 M;\n   long r;\n\n   transpose(M, A);\n   r = gauss(M);\n\n   X.SetDims(m-r, m);\n   clear(X);\n\n   long i, j, k;\n\n   vec_long D;\n   D.SetLength(m);\n   for (j = 0; j < m; j++) D[j] = -1;\n\n   j = -1;\n   for (i = 0; i < r; i++) {\n      do {\n         j++;\n      } while (M.get(i, j) == 0); \n\n      D[j] = i;\n   }\n\n   for (k = 0; k < m-r; k++) {\n      vec_GF2& v = X[k];\n      long pos = 0;\n      for (j = m-1; j >= 0; j--) {\n         if (D[j] == -1) {\n            if (pos == k) {\n               v[j] = 1;\n               // v.put(j, to_GF2(1));\n            }\n            pos++;\n         }\n         else {\n            v[j] = v*M[D[j]];\n            // v.put(j, v*M[D[j]]);\n         }\n      }\n   }\n}\n\n   \nvoid mul(mat_GF2& X, const mat_GF2& A, GF2 b)\n{\n   X = A;\n   if (b == 0)\n      clear(X);\n}\n\nvoid diag(mat_GF2& X, long n, GF2 d)  \n{  \n   if (d == 1)\n      ident(X, n);\n   else {\n      X.SetDims(n, n);\n      clear(X);\n   }\n} \n\nlong IsDiag(const mat_GF2& A, long n, GF2 d)\n{\n   if (A.NumRows() != n || A.NumCols() != n)\n      return 0;\n\n   if (d == 1)\n      return IsIdent(A, n);\n   else\n      return IsZero(A);\n}\n\n\nlong IsZero(const mat_GF2& 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_GF2& 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_GF2 operator+(const mat_GF2& a, const mat_GF2& b)\n{\n   mat_GF2 res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_GF2, res);\n}\n\nmat_GF2 operator*(const mat_GF2& a, const mat_GF2& b)\n{\n   mat_GF2 res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(mat_GF2, res);\n}\n\nmat_GF2 operator-(const mat_GF2& a, const mat_GF2& b)\n{\n   mat_GF2 res;\n   add(res, a, b);\n   NTL_OPT_RETURN(mat_GF2, res);\n}\n\n\nvec_GF2 operator*(const mat_GF2& a, const vec_GF2& b)\n{\n   vec_GF2 res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_GF2, res);\n}\n\nvec_GF2 operator*(const vec_GF2& a, const mat_GF2& b)\n{\n   vec_GF2 res;\n   mul_aux(res, a, b);\n   NTL_OPT_RETURN(vec_GF2, res);\n}\n\n\nvoid inv(mat_GF2& X, const mat_GF2& A)\n{\n   GF2 d;\n   inv(d, X, A);\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\n}\n\nvoid power(mat_GF2& X, const mat_GF2& 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_GF2 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_GF2& 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": "27bb0b3e018b79043886f6a6905ff164d9fc50a2", "size": 13131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/mat_GF2.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_GF2.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_GF2.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.2549277267, "max_line_length": 86, "alphanum_fraction": 0.4468814256, "num_tokens": 4612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.5638777035214341}}
{"text": "#ifndef __PICSAR_MULTIPHYSICS_UTILITIES__\n#define __PICSAR_MULTIPHYSICS_UTILITIES__\n\n//This .hpp file contains general purpose functions to perform useful\n//operations\n\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <algorithm>\n#include <utility>\n\n#ifndef PXRMP_CORE_ONLY\n    #include <limits>\n    //Uses the root finding algorithms provided by boost\n    #include <boost/math/tools/roots.hpp>\n#endif //PXRMP_CORE_ONLY\n\n//Should be included by all the src files of the library\n#include \"qed_commons.h\"\n\n//############################################### Declaration\n\nnamespace picsar{\n    namespace multi_physics{\n\n        //Generates a linearly spaced vector\n        template<typename _REAL>\n        std::vector<_REAL> generate_lin_spaced_vec\n        (_REAL min, _REAL max, size_t size);\n\n        //Generates a logarithmically spaced vector\n        template<typename _REAL>\n        std::vector<_REAL> generate_log_spaced_vec\n        (_REAL min, _REAL max, size_t size);\n\n        //Generates log_lin_log spaced vector\n        template<typename _REAL>\n        std::vector<_REAL> generate_log_lin_log_spaced_vec\n        (_REAL min, _REAL max, size_t size);\n\n        //GPU-friendly replacement of \"std::upper_bound\"\n        template<typename T>\n        PXRMP_GPU\n        PXRMP_FORCE_INLINE\n        const T* picsar_upper_bound(const T* first, const T* last, const T& val);\n\n        //A function providing values extracted from a poisson distribution,\n        //given lambda and a number in the interval [0,1)\n        template<typename T>\n        PXRMP_GPU\n        PXRMP_FORCE_INLINE\n        size_t poisson_distrib(T lambda, T unf_zero_one_minus_epsi);\n\n#ifndef PXRMP_CORE_ONLY\n        //A wrapper around the function provided by Boost library\n        template<typename _REAL>\n        _REAL bracket_and_solve_root\n        (const std::function<_REAL(_REAL)>& f, _REAL guess, bool rising);\n#endif\n    }\n}\n\n//############################################### Implementation\n\ntemplate<typename _REAL>\nstd::vector<_REAL>\npicsar::multi_physics::generate_log_spaced_vec\n(_REAL min, _REAL max, size_t size)\n{\n    //Return empty vector upon error\n    if( min >= max ||\n        min < static_cast<_REAL>(0) || max< static_cast<_REAL>(0) ||\n        size < 2)\n        return std::vector<_REAL>(0);\n\n    std::vector<_REAL> vec(size);\n\n    _REAL val = min;\n    _REAL mul = pow(max/min, static_cast<_REAL>(1.0/(size-1)));\n\n    for(size_t i = 0; i < size-1; ++i){\n        vec[i] = val;\n        val*=mul;\n    }\n    vec.back() = max; //Enforces this exactly\n    return vec;\n}\n\n//Generates a linearly spaced vector\ntemplate<typename _REAL>\nstd::vector<_REAL>\npicsar::multi_physics::generate_lin_spaced_vec\n(_REAL min, _REAL max, size_t size)\n{\n    //Return empty vector upon error\n    if( min >= max || size < 2)\n        return std::vector<_REAL>(0);\n\n    std::vector<_REAL> vec(size);\n\n    for(size_t i = 0; i < size-1; ++i){\n        vec[i] = static_cast<_REAL>(i*(max-min)/(size-1.0)) + min;\n    }\n    vec.back() = max; //Enforces this exactly\n    return vec;\n}\n\n//Generates log_lin_log spaced vector\ntemplate<typename _REAL>\nstd::vector<_REAL>\npicsar::multi_physics::generate_log_lin_log_spaced_vec\n(_REAL min, _REAL max, size_t size)\n{\n    std::vector<_REAL> vec(size);\n    size_t size_first = size/3;\n    size_t size_second = size/3;\n    size_t size_third = size/3;\n\n    _REAL first_val = max*static_cast<_REAL>(1.0/10.0);\n    _REAL second_val = max*static_cast<_REAL>(9.0/10.0);\n\n    size_t n = 0;\n    std::generate(vec.begin(), vec.begin()+size_first,\n    [=] () mutable { return min*exp((n++)*log(first_val/min)/(size_first)); });\n\n    std::generate(vec.begin()+size_first, vec.begin()+size_first+size_second,\n    [=] () mutable { return first_val + (second_val-first_val)*(n++)/(size_second); });\n\n    std::generate(vec.begin()+size_first+size_second, vec.end(),\n    [=] () mutable { return max*exp((size_third-1-(n++))*log(second_val/max)/(size_third-1)); });\n\n    vec.front() = min;\n    vec.back() = max;\n\n    return vec;\n}\n\ntemplate<typename T>\nPXRMP_GPU\nPXRMP_FORCE_INLINE\nconst T*\npicsar::multi_physics::picsar_upper_bound\n(const T* first, const T* last, const T& val)\n{\n    const T* it;\n    size_t count, step;\n    count = last-first;\n    while(count>0){\n        it = first;\n        step = count/2;\n        it += step;\n         if (!(val<*it)){\n             first = ++it;\n             count -= step + 1;\n         }\n         else{\n             count = step;\n         }\n    }\n    return first;\n}\n\n//A function providing values extracted from a poisson distribution,\n//given lambda and a number in the interval [0,1)\ntemplate<typename T>\nPXRMP_GPU\nPXRMP_FORCE_INLINE\nsize_t picsar::multi_physics::poisson_distrib\n(T lambda, T unf_zero_one_minus_epsi)\n{\n    size_t k = 0;\n    T p = exp(-lambda);\n    T s = p;\n    T old_s;\n    while (unf_zero_one_minus_epsi > s){\n        old_s = s;\n        p = p*lambda/(++k);\n        s += p;\n        //If this is true we have reached the limit of the floating\n        //point number that we are using\n        if(s <= old_s)\n            break;\n    }\n    return k;\n}\n\n#ifndef PXRMP_CORE_ONLY\n    //A wrapper around the function provided by Boost library\n    template<typename _REAL>\n    _REAL picsar::multi_physics::bracket_and_solve_root\n    (const std::function<_REAL(_REAL)>& f, _REAL guess, bool rising)\n    {\n        size_t digits = std::numeric_limits<_REAL>::digits;\n        size_t precision_digits = digits - 2;\n        boost::math::tools::eps_tolerance<_REAL> tol(precision_digits);\n\n        _REAL factor = static_cast<_REAL>(2.0);\n\n        size_t max_iter = 32;\n\n        std::pair<_REAL, _REAL> r =\n            boost::math::tools::bracket_and_solve_root\n            (f, guess, factor, rising, tol, max_iter);\n\n        return r.first + (r.second - r.first)/static_cast<_REAL>(2.0);\n    }\n#endif //PXRMP_CORE_ONLY\n\n#endif // __PICSAR_MULTIPHYSICS_UTILITIES__\n", "meta": {"hexsha": "795632c9563915d5f64ba966bcf8ee06531b7309", "size": 5900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED/src/utilities.hpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED/src/utilities.hpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED/src/utilities.hpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9620853081, "max_line_length": 97, "alphanum_fraction": 0.6355932203, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5637048939508805}}
{"text": "#pragma once\n\n#include \"tools.hpp\"\n#include <Eigen/Dense>\n\nnamespace kde1d {\n\nnamespace interp {\n\n//! A class for cubic spline interpolation in one dimension\n//!\n//! The class is used for implementing kernel estimators. It makes storing the\n//! observations obsolete and allows for fast numerical integration.\nclass InterpolationGrid\n{\n  public:\n    InterpolationGrid() {}\n\n    InterpolationGrid(const Eigen::VectorXd& grid_points,\n                        const Eigen::VectorXd& values,\n                        int norm_times);\n\n    void normalize(int times);\n\n    Eigen::VectorXd interpolate(const Eigen::VectorXd& x) const;\n\n    Eigen::VectorXd integrate(const Eigen::VectorXd& u,\n                              bool normalize = false) const;\n\n    Eigen::VectorXd get_values() const { return values_; }\n    Eigen::VectorXd get_grid_points() const { return grid_points_; }\n    double get_grid_max() const\n    {\n        return grid_points_[grid_points_.size() - 1];\n    }\n    double get_grid_min() const { return grid_points_[0]; }\n\n  private:\n    // Utility functions for spline Interpolation\n    double cubic_poly(const double& x, const Eigen::VectorXd& a) const;\n    double cubic_indef_integral(const double& x,\n                                const Eigen::VectorXd& a) const;\n    double cubic_integral(const double& lower,\n                          const double& upper,\n                          const Eigen::VectorXd& a) const;\n    int find_cell(const double& x0) const;\n    Eigen::VectorXd find_cell_coefs(const int& k) const;\n\n    Eigen::VectorXd grid_points_;\n    Eigen::VectorXd values_;\n};\n\n//! Constructor\n//!\n//! @param grid_points an ascending sequence of grid points.\n//! @param values a vector of values of same length as grid_points.\n//! @param norm_times how many times the normalization routine should run.\ninline InterpolationGrid::InterpolationGrid(\n  const Eigen::VectorXd& grid_points,\n  const Eigen::VectorXd& values,\n  int norm_times)\n{\n    if (grid_points.size() != values.size())\n        throw std::runtime_error(\n          \"grid_points and values must be of equal length\");\n\n    grid_points_ = grid_points;\n    values_ = values;\n    this->normalize(norm_times);\n}\n\n//! renormalizes the estimate to integrate to one\n//!\n//! @param times how many times the normalization routine should run.\ninline void\nInterpolationGrid::normalize(int times)\n{\n    double x_max = grid_points_(grid_points_.size() - 1);\n    double int_max;\n    for (int k = 0; k < times; ++k) {\n        int_max = this->integrate(Eigen::VectorXd::Constant(1, x_max))(0);\n        values_ /= int_max;\n    }\n}\n\n//! Interpolation\n//! @param x vector of evaluation points.\ninline Eigen::VectorXd\nInterpolationGrid::interpolate(const Eigen::VectorXd& x) const\n{\n    Eigen::VectorXd tmp_coefs(4);\n    auto interpolate_one = [&](const double& xx) {\n        int k = find_cell(xx);\n        double xev =\n          (xx - grid_points_(k)) / (grid_points_(k + 1) - grid_points_(k));\n\n        // use Gaussian tail for extrapolation\n        if (xev <= 0) {\n            return values_(k) * std::exp(-0.5 * xev * xev);\n        } else if (xev >= 1) {\n            return values_(k + 1) * std::exp(-0.5 * xev * xev);\n        }\n\n        return cubic_poly(xev, find_cell_coefs(k));\n    };\n\n    return tools::unaryExpr_or_nan(x, interpolate_one);\n}\n\n//! Integration along the grid\n//!\n//! @param x a vector  of evaluation points\n//! @param normalize whether to normalize the integral to a maximum value of 1.\ninline Eigen::VectorXd\nInterpolationGrid::integrate(const Eigen::VectorXd& x, bool normalize) const\n{\n    Eigen::VectorXd res(x.size());\n    auto ord = tools::get_order(x);\n\n    // temporaries for the loop\n    Eigen::VectorXd tmp_coefs(4);\n    double new_int, tmp_eps, cum_int = 0.0;\n    int k = 0, m = grid_points_.size();\n    tmp_coefs = find_cell_coefs(0);\n    tmp_eps = (grid_points_(1) - grid_points_(0));\n\n    for (long i = 0; i < x.size(); ++i) {\n        double upr = x(ord(i));\n\n        if (std::isnan(upr)) {\n            res(ord(i)) = upr;\n            continue;\n        }\n        if (upr <= grid_points_(0)) {\n            res(ord(i)) = 0.0;\n            continue;\n        }\n\n        // go up the grid and integrate\n        while (k < m - 1) {\n            // halt loop if integration limit is in kth cell\n            if (upr < grid_points_(k + 1))\n                break;\n            // integrate over full cell\n            tmp_coefs = find_cell_coefs(k);\n            tmp_eps = (grid_points_(k + 1) - grid_points_(k));\n            cum_int += cubic_integral(0.0, 1.0, tmp_coefs) * tmp_eps;\n            k++;\n        }\n\n        // integrate over partial cell\n        if (upr < grid_points_(m - 1)) { // only if still in interior\n            tmp_coefs = find_cell_coefs(k);\n            tmp_eps = (grid_points_(k + 1) - grid_points_(k));\n            upr = (upr - grid_points_(k)) / tmp_eps;\n            new_int = cubic_integral(0.0, upr, tmp_coefs) * tmp_eps;\n        } else {\n            new_int = 0.0;\n        }\n\n        res(ord(i)) = cum_int + new_int;\n    }\n\n    if (!normalize)\n        return res;\n\n    // integrate until end\n    while (k < m - 1) {\n        tmp_coefs = find_cell_coefs(k);\n        tmp_eps = (grid_points_(k + 1) - grid_points_(k));\n        cum_int += cubic_integral(0.0, 1.0, tmp_coefs) * tmp_eps;\n        k++;\n    }\n    return res / cum_int;\n}\n\n// ---------------- Utility functions for spline interpolation ----------------\n\n//! Evaluate a cubic polynomial\n//!\n//! @param x evaluation point.\n//! @param a polynomial coefficients\ninline double\nInterpolationGrid::cubic_poly(const double& x, const Eigen::VectorXd& a) const\n{\n    double x2 = x * x;\n    double x3 = x2 * x;\n    return a(0) + a(1) * x + a(2) * x2 + a(3) * x3;\n}\n\n//! Indefinite integral of a cubic polynomial\n//!\n//! @param x evaluation point.\n//! @param a polynomial coefficients.\ninline double\nInterpolationGrid::cubic_indef_integral(const double& x,\n                                          const Eigen::VectorXd& a) const\n{\n    double x2 = x * x;\n    double x3 = x2 * x;\n    double x4 = x3 * x;\n    return a(0) * x + a(1) / 2.0 * x2 + a(2) / 3.0 * x3 + a(3) / 4.0 * x4;\n}\n\n//! Definite integral of a cubic polynomial\n//!\n//! @param lower lower limit of the integral.\n//! @param upper upper limit of the integral.\n//! @param a polynomial coefficients.\ninline double\nInterpolationGrid::cubic_integral(const double& lower,\n                                    const double& upper,\n                                    const Eigen::VectorXd& a) const\n{\n    return cubic_indef_integral(upper, a) - cubic_indef_integral(lower, a);\n}\n\ninline int\nInterpolationGrid::find_cell(const double& x0) const\n{\n    int low = 0, high = grid_points_.size() - 1;\n    int mid;\n    while (low < high - 1) {\n        mid = low + (high - low) / 2;\n        if (x0 < grid_points_(mid))\n            high = mid;\n        else\n            low = mid;\n    }\n\n    return low;\n}\n\n//! Calculate coefficients for cubic intrpolation spline\n//!\n//! @param k the cell index.\ninline Eigen::VectorXd\nInterpolationGrid::find_cell_coefs(const int& k) const\n{\n    // indices for cell and neighboring grid points\n    int k0 = std::max(k - 1, 0);\n    int k2 = k + 1;\n    int k3 = std::min(k + 2, static_cast<int>(grid_points_.size()) - 1);\n\n    double dt0 = grid_points_(k) - grid_points_(k0);\n    double dt1 = grid_points_(k2) - grid_points_(k);\n    double dt2 = grid_points_(k3) - grid_points_(k2);\n\n    // compute tangents when parameterized in (t1,t2)\n    // for smooth extrapolation, derivative is set to zero at boundary\n    double dx1 = 0.0, dx2 = 0.0;\n    if (dt0 > 0) {\n        dx1 = (values_(k) - values_(k0)) / dt0;\n        dx1 -= (values_(k2) - values_(k0)) / (dt0 + dt1);\n        dx1 += (values_(k2) - values_(k)) / dt1;\n    }\n    if (dt2 > 0) {\n        dx2 = (values_(k2) - values_(k)) / dt1;\n        dx2 -= (values_(k3) - values_(k)) / (dt1 + dt2);\n        dx2 += (values_(k3) - values_(k2)) / dt2;\n    }\n\n    // rescale tangents for parametrization in (0,1)\n    dx1 *= dt1;\n    dx2 *= dt1;\n\n    // ensure positivity (Schmidt and Hess, DOI:10.1007/bf01934097)\n    dx1 = std::max(dx1, -3 * values_(k));\n    dx2 = std::min(dx2, 3 * values_(k2));\n\n    // compute coefficents\n    Eigen::VectorXd a(4);\n    a(0) = values_(k);\n    a(1) = dx1;\n    a(2) = -3 * (values_(k) - values_(k2)) - 2 * dx1 - dx2;\n    a(3) = 2 * (values_(k) - values_(k2)) + dx1 + dx2;\n\n    return a;\n}\n\n} // end kde1d::interp\n\n} // end kde1d", "meta": {"hexsha": "591db23dabf025143776d38ef988c0bf46ab6361", "size": 8441, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kde1d/interpolation.hpp", "max_stars_repo_name": "vinecopulib/kde1d-cpp", "max_stars_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/kde1d/interpolation.hpp", "max_issues_repo_name": "vinecopulib/kde1d-cpp", "max_issues_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kde1d/interpolation.hpp", "max_forks_repo_name": "vinecopulib/kde1d-cpp", "max_forks_repo_head_hexsha": "caf253f3a813300f614e9c1b6b2d23269108302a", "max_forks_repo_licenses": ["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.8268551237, "max_line_length": 79, "alphanum_fraction": 0.5937685108, "num_tokens": 2305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.563704882044694}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include <NTL/lzz_pXFactoring.h>\n\n#include <cassert>\n#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <bitset>\n#include <string>\nusing namespace std;\nCtxt operator + (Ctxt left, Ctxt right)\n{\n\tCtxt temp(left);\n\ttemp+=right;\n\treturn temp;\n}\nCtxt operator * (Ctxt left, Ctxt right)\n{\n\tCtxt temp(left);\n\ttemp*=right;\n\treturn temp;\n}\nint biggerThan(int plainText1, int plainText2)\n{\n\tFHEcontext * context;\n\tFHESecKey *secretKey;\n\tconst FHEPubKey * publicKey;\n\tlong p = 2;\n\tlong r = 1;\n\tlong L = 16;\n\tlong c = 3;\n\tlong w = 64;\n\tlong d = 0;\n\tlong k = 128;\n\tlong s = 0;\n\n\tlong m = FindM(k, L, c, p, d, s, 0);\n\tunsigned bits =2;\n\t\n\tcontext = new FHEcontext(m, p, r);\n\tbuildModChain(*context, L, c);\n\n\tZZX G = context->alMod.getFactorsOverZZ()[0];\n\t\n\tsecretKey = new FHESecKey(*context);\n\tpublicKey = secretKey;\n\tsecretKey->GenSecKey(w);\n\n\t//plain text\n\tvector<long> plainTextBinaryVector1(4, 0);\n\tvector<long> plainTextBinaryVector2(4, 0);\n\n\t//ciphertext\n\tvector<Ctxt> ctxtVector1(4, Ctxt(*publicKey));\n\tvector<Ctxt> ctxtVector2(4, Ctxt(*publicKey));\n\n\t//转换成二进制串\n\tbitset<4> b1(plainText1);\n\tbitset<4> b2(plainText2);\n\n\tfor(int i=0; i<b1.size(); i++)\n\t{\n\t\tplainTextBinaryVector1[i]=b1[i];\n\t\tplainTextBinaryVector2[i]=b2[i];\n\t}\n\n\tfor(int i=0; i<b1.size(); i++)\n\t{\n\t\tpublicKey->Encrypt(ctxtVector1[i], to_ZZX(plainTextBinaryVector1[i]));\n\t\tpublicKey->Encrypt(ctxtVector2[i], to_ZZX(plainTextBinaryVector2[i]));\n\t}\n\n\t//boolean circuit\n\n\t//1s\n\tCtxt ctxtOne(*publicKey);\n\tpublicKey->Encrypt(ctxtOne, to_ZZX(1));\n\n\tZZX temp;\n\tCtxt comparisionResult(*publicKey);\n\tpublicKey->Encrypt(comparisionResult, to_ZZX(0));\n\n\tcomparisionResult = ctxtVector1[3]*(ctxtVector2[3]+ctxtOne);\n\t// comparisionResult = ctxtVector1[3]*=(ctxtVector2[3]+=ctxtOne);\n\tsecretKey->Decrypt(temp, comparisionResult);\n\t//cout<<\"1:  \"<<temp<<endl;\n\n\tcomparisionResult = comparisionResult+ (ctxtVector1[3]+ctxtVector2[3]+ctxtOne)\n\t*ctxtVector1[2]*(ctxtVector2[2]+ctxtOne);\n\t//这里用XOR可以代替OR，因为运算表达式决定了两个加数不可能同时为1\n\tsecretKey->Decrypt(temp, comparisionResult);\n\t//cout<<\"2:  \"<<temp<<endl;\n\n\tcomparisionResult = comparisionResult + \n\t(ctxtVector1[3]+ctxtVector2[3]+ctxtOne) *\n\t(ctxtVector1[2]+ctxtVector2[2]+ctxtOne) *\n\tctxtVector1[1]*(ctxtVector2[1]+ctxtOne);\n\tsecretKey->Decrypt(temp, comparisionResult);\n\t//cout<<\"3:  \"<<temp<<endl;\n\n\tcomparisionResult = comparisionResult +\n\t(ctxtVector1[3]+ctxtVector2[3]+ctxtOne) *\n\t(ctxtVector1[2]+ctxtVector2[2]+ctxtOne) *\n\t(ctxtVector1[1]+ctxtVector2[1]+ctxtOne) *\n\tctxtVector1[0]*(ctxtVector2[0]+ctxtOne);\n\tsecretKey->Decrypt(temp, comparisionResult);\n\t//cout<<\"4:  \"<<temp<<endl;\n\n\tZZX result;\n\tsecretKey->Decrypt(result, comparisionResult);\n\t//cout<<\"result : \"<<result<<endl;\n\tlong hh;\n\tconv(hh, result[0]);\n\n\tdelete context;\n\tdelete secretKey;\n\n\treturn int(hh);\n}\nint main()\n{\n\tfor(int x=0; x<16; x++)\n\t{\n\t\tfor(int y=0; y<16; y++)\n\t\t{\n\t\t\tcout<<\"x  \"<<x<<\"y  \"<<y<<endl;\n\t\t\tif(biggerThan(x, y) != (x>y))\n\t\t\t{\n\t\t\t\tcout<<\"error!\"<<endl;\n\t\t\t\tcout<<\"biggerThan : \"<<biggerThan(x,y)<<endl;\n\t\t\t\tcout<<\"x>y: \"<<(x>y)<<endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\twhile(true)\n\t{\n\t\tint a;\n\t\tint b;\n\t\tcin>>a;\n\t\tcin>>b;\n\t\tcout<<biggerThan(a, b)<<endl;\n\t}\n}", "meta": {"hexsha": "ccebd6e4c6ea28cadaf2515e6c67287b816c97a8", "size": 3263, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test3.cpp", "max_stars_repo_name": "edwincai/my-first-lab", "max_stars_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-12T15:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T15:33:57.000Z", "max_issues_repo_path": "test3.cpp", "max_issues_repo_name": "edwincai/my-first-lab", "max_issues_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test3.cpp", "max_forks_repo_name": "edwincai/my-first-lab", "max_forks_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_forks_repo_licenses": ["Apache-2.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.0472972973, "max_line_length": 79, "alphanum_fraction": 0.6733067729, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218370002787, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5636463919281992}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen>\n\nusing namespace std;\nusing namespace Eigen;\n\n// function definitions for reading matrices from .txt file\nvoid read_sparse_matrix(const std::string& filename, SparseMatrix<float, RowMajor>& matrix);\nvoid read_matrix(std::string file, MatrixXf& matrix);\n\nint main()\n{\n    // read matrices from benchmark test files\n    SparseMatrix<float, RowMajor> P;\n    read_sparse_matrix(\"../benchmark/P.txt\", P);\n    SparseMatrix<float, RowMajor> Gamma;\n    read_sparse_matrix(\"../benchmark/SH.txt\", Gamma);\n    SparseMatrix<float, RowMajor> invCeta;\n    read_sparse_matrix(\"../benchmark/invCeta.txt\", invCeta);\n    SparseMatrix<float, RowMajor> F;\n    read_sparse_matrix(\"../benchmark/F.txt\", F);\n    MatrixXf invCphi(P.cols(),P.cols());\n    read_matrix(\"../benchmark/invCphi.txt\", invCphi);\n\n    // read sensor measurements from benchmark test files\n    VectorXf s(invCeta.cols());\n    fstream input(\"../benchmark/s.txt\");\n    string line;\n    int indx = 0;\n    if (input.is_open()) {\n        while (getline(input,line)) {\n            s(indx)=stof(line);\n            indx++;\n        }\n        input.close();\n    }\n    cout << \"read input done!\" << endl;\n\n    // calculate reconstruction matrix R\n    MatrixXf R(P.cols(), P.cols());\n    cout << \"start computation...\" << endl;\n    R = (Gamma*P).transpose()*invCeta*(Gamma*P)+invCphi;\n\n    // reconstruct turbulent layers from sensor measurements\n    cout << \"reconstruct layers from sensor measurements...\" << endl;\n    VectorXf b = (Gamma*P).transpose()*invCeta*s;\n    VectorXf phi = R.colPivHouseholderQr().solve(b);\n\n    // apply mirror fitting\n    cout << \"compute actuator commands...\" << endl;\n    VectorXf a(F.cols());\n    a = F*phi;\n    cout << \"computation done!\" << endl;\n\n    // save actuator commands to file\n    ofstream output(\"../benchmark/out.txt\");\n    if (output.is_open()) {\n        for(int i = 0; i < a.size(); i++) {\n            output << a(i) << '\\n';\n        }\n    }\n    cout << \"stored output file out.txt!\" << endl;\n\n    return 0;\n}\n\nvoid read_sparse_matrix(const std::string& filename, SparseMatrix<float, RowMajor>& matrix) {\n    ifstream fin(filename);\n    if(fin.is_open()) {\n        int M = 0, N = 0, L = 0;\n        fin >> M >> N >> L;\n        vector<Eigen::Triplet<float>> triple;\n        triple.reserve(L);\n        int m, n;\n        float data;\n        while (fin >> n >> m >> data) {\n            triple.push_back(Triplet<float>(m-1, n-1, data));// m - 1 and n - 1 to set index start from 0\n        }\n        fin.close();\n\n        matrix.resize(M, N);\n        matrix.reserve(L);\n        matrix.setFromTriplets(triple.begin(), triple.end());\n    }\n    else {\n        std::cout << \"Can not open sparse matrix file: \" << filename << std::endl;\n    }\n}\n\nvoid read_matrix(std::string file, MatrixXf& matrix) {\n    std::ifstream in(file);\n    std::string line;\n    int row=0, col=0;\n\n    if (in.is_open()) {\n        while (std::getline(in, line)) {\n            char* ptr = (char*) line.c_str();\n            int len = line.length();\n\n            col = 0;\n            char* start = ptr;\n            for (int i = 0; i<len; i++) {\n                if (ptr[i]=='\\t') {\n                    matrix(row, col++) = stof(start);\n                    start = ptr+i+1;\n                }\n            }\n            row++;\n        }\n        in.close();\n    }\n}", "meta": {"hexsha": "a4a4c5ff25dfb65c9717383e825eff3e30798aed", "size": 3362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/main.cpp", "max_stars_repo_name": "ROMSOC/benchmark_adaptive-optics", "max_stars_repo_head_hexsha": "38933fa2eacaf4ff3c5f5f1c7d25b13e77880f47", "max_stars_repo_licenses": ["MIT"], "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/main.cpp", "max_issues_repo_name": "ROMSOC/benchmark_adaptive-optics", "max_issues_repo_head_hexsha": "38933fa2eacaf4ff3c5f5f1c7d25b13e77880f47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/main.cpp", "max_forks_repo_name": "ROMSOC/benchmark_adaptive-optics", "max_forks_repo_head_hexsha": "38933fa2eacaf4ff3c5f5f1c7d25b13e77880f47", "max_forks_repo_licenses": ["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.7522123894, "max_line_length": 105, "alphanum_fraction": 0.5651397977, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5635679174764276}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_HYPERGEOMETRIC_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_HYPERGEOMETRIC_LPMF_HPP\n\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_greater.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <boost/math/distributions.hpp>\n\nnamespace stan {\nnamespace math {\n\n// Hypergeometric(n|N, a, b)  [0 <= n <= a;  0 <= N-n <= b;  0 <= N <= a+b]\n// n: #white balls drawn;  N: #balls drawn;\n// a: #white balls;  b: #black balls\ntemplate <bool propto, typename T_n, typename T_N, typename T_a, typename T_b>\ndouble hypergeometric_lpmf(const T_n& n, const T_N& N, const T_a& a,\n                           const T_b& b) {\n  static const char* function = \"hypergeometric_lpmf\";\n\n  if (size_zero(n, N, a, b))\n    return 0.0;\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_N> N_vec(N);\n  scalar_seq_view<T_a> a_vec(a);\n  scalar_seq_view<T_b> b_vec(b);\n  size_t size = max_size(n, N, a, b);\n\n  double logp(0.0);\n  check_bounded(function, \"Successes variable\", n, 0, a);\n  check_greater(function, \"Draws parameter\", N, n);\n  for (size_t i = 0; i < size; i++) {\n    check_bounded(function, \"Draws parameter minus successes variable\",\n                  N_vec[i] - n_vec[i], 0, b_vec[i]);\n    check_bounded(function, \"Draws parameter\", N_vec[i], 0,\n                  a_vec[i] + b_vec[i]);\n  }\n  check_consistent_sizes(function, \"Successes variable\", n, \"Draws parameter\",\n                         N, \"Successes in population parameter\", a,\n                         \"Failures in population parameter\", b);\n\n  if (!include_summand<propto>::value)\n    return 0.0;\n\n  for (size_t i = 0; i < size; i++)\n    logp += math::binomial_coefficient_log(a_vec[i], n_vec[i])\n            + math::binomial_coefficient_log(b_vec[i], N_vec[i] - n_vec[i])\n            - math::binomial_coefficient_log(a_vec[i] + b_vec[i], N_vec[i]);\n  return logp;\n}\n\ntemplate <typename T_n, typename T_N, typename T_a, typename T_b>\ninline double hypergeometric_lpmf(const T_n& n, const T_N& N, const T_a& a,\n                                  const T_b& b) {\n  return hypergeometric_lpmf<false>(n, N, a, b);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "8b10c63a74388c779b57e7c08d3c96aeaa3c6547", "size": 2742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/hypergeometric_lpmf.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/prob/hypergeometric_lpmf.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/prob/hypergeometric_lpmf.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": 38.6197183099, "max_line_length": 78, "alphanum_fraction": 0.6754194019, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5635073730390326}}
{"text": "#include <Eigen/Array>\n\nint main(int argc, char *argv[])\n{\n  std::cout.precision(2);\n\n  // demo static functions\n  Eigen::Matrix3f m3 = Eigen::Matrix3f::Random();\n  Eigen::Matrix4f m4 = Eigen::Matrix4f::Identity();\n\n  std::cout << \"*** Step 1 ***\\nm3:\\n\" << m3 << \"\\nm4:\\n\" << m4 << std::endl;\n\n  // demo non-static set... functions\n  m4.setZero();\n  m3.diagonal().setOnes();\n\n  std::cout << \"*** Step 2 ***\\nm3:\\n\" << m3 << \"\\nm4:\\n\" << m4 << std::endl;\n\n  // demo fixed-size block() expression as lvalue and as rvalue\n  m4.block<3,3>(0,1) = m3;\n  m3.row(2) = m4.block<1,3>(2,0);\n\n  std::cout << \"*** Step 3 ***\\nm3:\\n\" << m3 << \"\\nm4:\\n\" << m4 << std::endl;\n\n  // demo dynamic-size block()\n  {\n    int rows = 3, cols = 3;\n    m4.block(0,1,3,3).setIdentity();\n    std::cout << \"*** Step 4 ***\\nm4:\\n\" << m4 << std::endl;\n  }\n\n  // demo vector blocks\n  m4.diagonal().block(1,2).setOnes();\n  std::cout << \"*** Step 5 ***\\nm4.diagonal():\\n\" << m4.diagonal() << std::endl;\n  std::cout << \"m4.diagonal().start(3)\\n\" << m4.diagonal().start(3) << std::endl;\n\n  // demo coeff-wise operations\n  m4 = m4.cwise()*m4;\n  m3 = m3.cwise().cos();\n  std::cout << \"*** Step 6 ***\\nm3:\\n\" << m3 << \"\\nm4:\\n\" << m4 << std::endl;\n\n  // sums of coefficients\n  std::cout << \"*** Step 7 ***\\n m4.sum(): \" << m4.sum() << std::endl;\n  std::cout << \"m4.col(2).sum(): \" << m4.col(2).sum() << std::endl;\n  std::cout << \"m4.colwise().sum():\\n\" << m4.colwise().sum() << std::endl;\n  std::cout << \"m4.rowwise().sum():\\n\" << m4.rowwise().sum() << std::endl;\n\n  // demo intelligent auto-evaluation\n  m4 = m4 * m4; // auto-evaluates so no aliasing problem (performance penalty is low)\n  Eigen::Matrix4f other = (m4 * m4).lazy(); // forces lazy evaluation\n  m4 = m4 + m4; // here Eigen goes for lazy evaluation, as with most expressions\n  m4 = -m4 + m4 + 5 * m4; // same here, Eigen chooses lazy evaluation for all that.\n  m4 = m4 * (m4 + m4); // here Eigen chooses to first evaluate m4 + m4 into a temporary.\n                       // indeed, here it is an optimization to cache this intermediate result.\n  m3 = m3 * m4.block<3,3>(1,1); // here Eigen chooses NOT to evaluate block() into a temporary\n    // because accessing coefficients of that block expression is not more costly than accessing\n    // coefficients of a plain matrix.\n  m4 = m4 * m4.transpose(); // same here, lazy evaluation of the transpose.\n  m4 = m4 * m4.transpose().eval(); // forces immediate evaluation of the transpose\n\n  std::cout << \"*** Step 8 ***\\nm3:\\n\" << m3 << \"\\nm4:\\n\" << m4 << std::endl;\n}\n", "meta": {"hexsha": "b4d5f04981b7eebe6bcbbd2217c025b712aee4c3", "size": 2542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/tutorial.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/tutorial.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/tutorial.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 40.3492063492, "max_line_length": 96, "alphanum_fraction": 0.5802517703, "num_tokens": 861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5635073721441767}}
{"text": "/*\n * Ewald.hpp\n *\n *  Created on: Mar 2, 2017\n *      Author: wyan\n */\n\n/*\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * !!!   For unit cubic box only !!!\n * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n * */\n\n#ifndef STOKES3D3D_EWALD_HPP_\n#define STOKES3D3D_EWALD_HPP_\n\n#include <cmath>\n\n#include <Eigen/Dense>\n\nconstexpr int DIRECTLAYER = 2;\nconstexpr double PI314 = 3.1415926535897932384626433;\n\ninline double ERFC(double x) { return std::erfc(x); }\n\ninline double ERF(double x) { return std::erf(x); }\n\ninline double boxperiodic(double x, double xlow, double xhigh) {\n    double temp = (x - xlow) / (xhigh - xlow);\n    return (x - xlow) - floor(temp) * (xhigh - xlow);\n}\n\ninline void Gkernel(const Eigen::Vector3d &target,\n                    const Eigen::Vector3d &source, Eigen::Matrix3d &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    double rnormReg = rnorm;\n    if (rnorm < 1e-13) {\n        answer = Eigen::Matrix3d::Zero();\n        return;\n    }\n    auto part2 = rst * rst.transpose() / (rnormReg * rnormReg * rnormReg);\n    auto part1 = Eigen::Matrix3d::Identity() / rnormReg;\n    answer = part1 + part2;\n}\n\n// periodic in X direction for a unit cubic box [0,1)^3\ninline void Gkernel1D(const Eigen::Vector3d &target, Eigen::Matrix3d &G) {\n    const int Nsum = 10000;\n    G.setZero();\n    Eigen::Matrix3d Gtemp1;\n    Eigen::Matrix3d Gtemp2;\n    Gkernel(target, Eigen::Vector3d(0, 0, 0), G);\n    for (int i = 1; i < Nsum + 1; i++) {\n        Gkernel(target, Eigen::Vector3d(i, 0, 0), Gtemp1);\n        Gkernel(target, Eigen::Vector3d(-i, 0, 0), Gtemp2);\n        G += (Gtemp1 + Gtemp2);\n    }\n}\n\n/*\n * def AEW(xi,rvec):\n r=np.sqrt(rvec.dot(rvec))\n A = 2*(xi*np.exp(-(xi**2)*(r**2))/(np.sqrt(np.pi)*r**2)+ss.erfc(xi*r)/(2*r**3))\n \\\n    *(r*r*np.identity(3)+np.outer(rvec,rvec)) -\n 4*xi/np.sqrt(np.pi)*np.exp(-(xi**2)*(r**2))*np.identity(3) return A\n *\n * */\ninline Eigen::Matrix3d AEW(const double xi, const Eigen::Vector3d &rvec) {\n    const double r = rvec.norm();\n    Eigen::Matrix3d A =\n        2 *\n            (xi * exp(-(xi * xi) * (r * r)) / (sqrt(PI314) * r * r) +\n             erfc(xi * r) / (2 * r * r * r)) *\n            (r * r * Eigen::Matrix3d::Identity() + (rvec * rvec.transpose())) -\n        4 * xi / sqrt(PI314) * exp(-(xi * xi) * (r * r)) *\n            Eigen::Matrix3d::Identity();\n    return A;\n}\n\n/*\n *\n def BEW(xi,kvec):\n k=np.sqrt(kvec.dot(kvec))\n B =\n 8*np.pi*(1+k*k/(4*(xi**2)))*((k**2)*np.identity(3)-np.outer(kvec,kvec))/(k**4)\n return B*np.exp(-k**2/(4*xi**2))\n *\n * */\ninline Eigen::Matrix3d BEW(const double xi, const Eigen::Vector3d &kvec) {\n    const double k = kvec.norm();\n    Eigen::Matrix3d B =\n        8 * PI314 * (1 + k * k / (4 * (xi * xi))) *\n        ((k * k) * Eigen::Matrix3d::Identity() - (kvec * kvec.transpose())) /\n        (k * k * k * k);\n    B *= exp(-k * k / (4 * xi * xi));\n    return B;\n}\n\n/*\n * def stokes3DEwald(rvec,force):\n xi = 2\n r=np.sqrt(rvec.dot(rvec))\n real = 0\n N=4\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n real = real + AEW(xi,rvec+1.0*np.array([i,j,k])).dot(force)\n wave = 0\n N=4\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n kvec=2*np.pi*np.array([i,j,k]) # L = 1\n if(i==0 and j==0 and k==0):\n continue\n else:\n wave = wave + BEW(xi,kvec).dot(force)*np.exp(-complex(0,1)*kvec.dot(rvec))\n\n return (np.real(wave)+real)\n\n * */\n// periodic in XYZ direction for a unit cubic box [0,1)^3\ninline void GkernelEwald3D(const Eigen::Vector3d &rvecIn, Eigen::Matrix3d &Gsum,\n                           double box) {\n    const double xi = 2;\n    Eigen::Vector3d rvec = rvecIn;\n    rvec[0] = rvec[0] - floor(rvec[0]);\n    rvec[1] = rvec[1] - floor(rvec[1]);\n    rvec[2] = rvec[2] - floor(rvec[2]);\n    const double r = rvec.norm();\n    Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n    const int N = 10;\n    if (r < 1e-11) {\n        auto Gself = -4 * xi / sqrt(PI314) *\n                     Eigen::Matrix3d::Identity(); // the self term\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                    if (i == 0 && j == 0 && k == 0) {\n                        continue;\n                    }\n                    real =\n                        real + AEW(xi, rvec + Eigen::Vector3d(i * box, j * box,\n                                                              k * box));\n                }\n            }\n        }\n        real += Gself;\n    } else {\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                    real =\n                        real + AEW(xi, rvec + Eigen::Vector3d(i * box, j * box,\n                                                              k * box));\n                }\n            }\n        }\n    }\n    Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\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                Eigen::Vector3d kvec(2 * PI314 * i / box, 2 * PI314 * j / box,\n                                     2 * PI314 * k / box);\n                if (i == 0 and j == 0 and k == 0) {\n                    continue;\n                } else {\n                    wave = wave + BEW(xi, kvec) * cos(kvec.dot(rvec));\n                }\n            }\n        }\n    }\n    Gsum = real + wave * (1 / (box * box * box));\n}\n\n/*\n *\n def stokes3DM2L(rvec,force):\n uEwald=stokes3DEwald(rvec,force)\n uNB=0\n N=3\n for i in range(-N,N+1):\n for j in range(-N,N+1):\n for k in range(-N,N+1):\n uNB=uNB+Gkernel(rvec-np.array([i,j,k])).dot(force)\n return uEwald-uNB\n * */\n// Out of Layer 1\ninline void GkernelEwald3DFF(const Eigen::Vector3d &rvec,\n                             Eigen::Matrix3d &GsumO1) {\n    Eigen::Matrix3d Gfree = Eigen::Matrix3d::Zero();\n    GkernelEwald3D(rvec, GsumO1, 1.0);\n    const int N = DIRECTLAYER;\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                Gkernel(rvec, Eigen::Vector3d(i, j, k), Gfree);\n                GsumO1 -= Gfree;\n            }\n        }\n    }\n}\n\ninline double lbda(double k, double xi, double z) {\n    return exp(-k * k / (4 * xi * xi) - (xi * xi) * (z * z));\n}\n\ninline double thetaplus(double k, double xi, double z) {\n    return exp(k * z) * ERFC(k / (2 * xi) + xi * z);\n}\n\ninline double thetaminus(double k, double xi, double z) {\n    return exp(-k * z) * ERFC(k / (2 * xi) - xi * z);\n}\n\ninline double J00(double k, double xi, double z) {\n    return sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J10(double k, double xi, double z) {\n    return PI314 * (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (4 * k);\n}\n\ninline double J20(double k, double xi, double z) {\n    return sqrt(PI314) * lbda(k, xi, z) / (4 * k * k * xi) +\n           PI314 *\n               ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k * k * k) +\n                (thetaminus(k, xi, z) - thetaplus(k, xi, z)) * z / (8 * k * k) -\n                (thetaplus(k, xi, z) + thetaminus(k, xi, z)) /\n                    (16 * k * (xi * xi)));\n}\n\ninline double J12(double k, double xi, double z) {\n    return PI314 * (-thetaplus(k, xi, z) - thetaminus(k, xi, z)) * k / 4 +\n           sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J22(double k, double xi, double z) {\n    return PI314 * ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) * k /\n                        (16 * xi * xi) +\n                    (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k) +\n                    (thetaplus(k, xi, z) - thetaminus(k, xi, z)) * z / 8) -\n           sqrt(PI314) * lbda(k, xi, z) / (4 * xi);\n}\n\ninline double K11(double k, double xi, double z) {\n    return PI314 * ((thetaminus(k, xi, z) - thetaplus(k, xi, z))) / 4;\n}\n\ninline double K12(double k, double xi, double z) {\n    return PI314 *\n           ((thetaplus(k, xi, z) - thetaminus(k, xi, z)) / (16 * xi * xi) +\n            (thetaminus(k, xi, z) + thetaplus(k, xi, z)) * z / (8 * k));\n}\n\ninline void QI(const Eigen::Vector3d &kvec, double xi, double z,\n               Eigen::Matrix3d &QI) {\n    // 3*3 tensor\n    // kvec: np.array([k1,k2,0])\n    double knorm = sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1]);\n    QI = 2 * (J00(knorm, xi, z) / (4 * xi * xi) + J10(knorm, xi, z)) *\n         Eigen::Matrix3d::Identity();\n}\n\ninline void Qkk(const Eigen::Vector3d &kvec, double xi, double z,\n                Eigen::Matrix3d &Qreal, Eigen::Matrix3d &Qimg) {\n    double k1 = kvec[0];\n    double k2 = kvec[1];\n    double knorm = sqrt(k1 * k1 + k2 * k2);\n    auto j10 = J10(knorm, xi, z);\n    auto j20 = J20(knorm, xi, z);\n    auto j12 = J12(knorm, xi, z);\n    auto j22 = J22(knorm, xi, z);\n\n    auto k11 = K11(knorm, xi, z);\n    auto k12 = K12(knorm, xi, z);\n    Qreal.setZero();\n    Qreal(0, 0) = k1 * k1;\n    Qreal(1, 1) = k2 * k2;\n    Qreal(0, 1) = k1 * k2;\n    Qreal(1, 0) = k1 * k2;\n\n    Qreal *= (j10 / (4 * (xi * xi)) + j20);\n    Qreal(2, 2) = (j12 / (4 * xi * xi) + j22);\n    Qreal *= -2;\n\n    Qimg.setZero();\n    Qimg(0, 2) = k1;\n    Qimg(1, 2) = k2;\n    Qimg(2, 0) = k1;\n    Qimg(2, 1) = k2;\n    // Qimg=np.array([[0,0,k1],[0,0,k2],[k1,k2,0]])*( k11/(4*xi**2) + k12 )\n    Qimg *= (k11 / (4 * xi * xi) + k12);\n    Qimg *= -2;\n}\n\n// inline Eigen::Matrix3d uFk0(double xi, double zmn) {\n//\tEigen::Matrix3d wavek0;\n//\twavek0 = -(4.0 / 1) * (PI314 * (zmn) * ERF(zmn * xi) + sqrt(PI314) / (2\n//* xi) * exp(-zmn * zmn * xi * xi)); \treturn wavek0;\n//\n//}\n// periodic in XY direction for a unit cubic box [0,1)^3\ninline void GkernelEwald2D(const Eigen::Vector3d &rvecIn,\n                           Eigen::Matrix3d &Gsum) {\n    const double xi = 2;\n    Eigen::Vector3d rvec = rvecIn;\n    rvec[0] = rvec[0] - floor(rvec[0]);\n    rvec[1] = rvec[1] - floor(rvec[1]); // reset to a periodic cell\n\n    const double r = rvec.norm();\n    Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n    const int N = 5;\n    if (r < 1e-14) {\n        auto Gself = -4 * xi / sqrt(PI314) *\n                     Eigen::Matrix3d::Identity(); // the self term\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                if (i == 0 && j == 0) {\n                    continue;\n                }\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n        real += Gself;\n    } else {\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n    }\n\n    // k\n    Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\n    double zmn = rvec[2];\n    Eigen::Vector3d rhomn = rvec;\n    rhomn[2] = 0;\n    Eigen::Matrix3d Qreal;\n    Eigen::Matrix3d Qimg;\n    Eigen::Matrix3d QImat;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            Eigen::Vector3d kvec(2 * PI314 * i, 2 * PI314 * j, 0);\n            if (i == 0 and j == 0) {\n                continue;\n            }\n            Qkk(kvec, xi, zmn, Qreal, Qimg);\n            QI(kvec, xi, zmn, QImat);\n            wave = wave + (QImat + Qreal) * cos(kvec.dot(rhomn)) -\n                   (Qimg)*sin(kvec.dot(rhomn));\n        }\n    }\n    wave *= 4;\n\n    // k=0\n    Eigen::Matrix3d waveK0;\n    waveK0.setZero();\n    /*\n     *   I2fn=force\n     I2fn[2]=0\n     wavek0=-(4/1)*(np.pi*(zmn)*ss.erf(zmn*xi)+np.sqrt(np.pi)/(2*xi)*np.exp(-zmn**2*xi**2))*I2fn\n     *\n     * */\n    waveK0 = -(4 / 1.0) *\n             (PI314 * (zmn)*ERF(zmn * xi) +\n              sqrt(PI314) / (2 * xi) * exp(-zmn * zmn * xi * xi)) *\n             Eigen::Matrix3d::Identity();\n    waveK0(2, 2) = 0;\n\n    Gsum = real + wave + waveK0;\n}\n\n#endif /* STOKES3D3D_EWALD_HPP_ */\n", "meta": {"hexsha": "08d418ff809b3a5bc477c202578018f349900083", "size": 11770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Test/StokesFMM3D/Ewald.hpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "Test/StokesFMM3D/Ewald.hpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test/StokesFMM3D/Ewald.hpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 30.8923884514, "max_line_length": 96, "alphanum_fraction": 0.4779099405, "num_tokens": 4177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5635073600401213}}
{"text": "#include \"mantella_bits/samplesAnalysis.hpp\"\n\n// C++ standard library\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <memory>\n#include <stdexcept>\n#include <utility>\n\n// Armadillo\n#include <armadillo>\n\n// Mantella\n#include \"mantella_bits/assert.hpp\"\n#include \"mantella_bits/combinatorics.hpp\"\n#include \"mantella_bits/config.hpp\"\n#include \"mantella_bits/optimisationProblem.hpp\"\n#include \"mantella_bits/probability.hpp\"\n\nnamespace mant {\n  double fitnessDistanceCorrelation(\n      const std::unordered_map<arma::vec, double, Hash, IsEqual>& samples) {\n    assert(samples.size() > 1 && \"fitnessDistanceCorrelation: The number of samples must be greater than 1.\");\n    assert(isDimensionallyConsistent(samples) && \"fitnessDistanceCorrelation: The samples must be dimensionally consistent\");\n\n    // Converts the set of samples into a matrix of parameters (each row is a dimension and each column a parameter) and a row vector of objective values, such that we can use Armadillo C++ to manipulate them.\n    arma::mat parameters(samples.cbegin()->first.n_elem, samples.size());\n    arma::rowvec objectiveValues(parameters.n_cols);\n\n    arma::uword n = 0;\n    for (const auto& sample : samples) {\n      parameters.col(n) = sample.first;\n      objectiveValues(n) = sample.second;\n\n      ++n;\n    }\n\n    // Determines one parameter having a minimal objective value within the set of samples.\n    // The best parameter is then subtracted from all other parameters, so that we can later calculated the distance towards the best one.\n    arma::uword bestParameterIndex = objectiveValues.index_min();\n    parameters.each_col() -= parameters.col(bestParameterIndex);\n\n    // Excludes the best/reference parameter from the correlation, as it will always perfectly correlate with itself and therefore bias the correlation coefficient.\n    parameters.shed_col(bestParameterIndex);\n    objectiveValues.shed_col(bestParameterIndex);\n\n    // Uses `arma::sum(arma::square(...))` to emulate a column-wise vector norm operator that Armadillo C++ does not have (and this is not likely to change, as it interferes with matrix norms).\n    return arma::as_scalar(arma::cor(arma::sqrt(arma::sum(arma::square(parameters))), objectiveValues));\n  }\n\n  double lipschitzContinuity(\n      const std::unordered_map<arma::vec, double, Hash, IsEqual>& samples) {\n    assert(samples.size() > 1 && \"lipschitzContinuity: The number of samples must be greater than 1.\");\n    assert(isDimensionallyConsistent(samples) && \"lipschitzContinuity: The samples must be dimensionally consistent\");\n\n    double lipschitzContinuity = 0.0;\n    for (auto firstSample = samples.cbegin(); firstSample != samples.cend();) {\n      for (auto secondSample = ++firstSample; secondSample != samples.cend(); ++secondSample) {\n        lipschitzContinuity = std::max(lipschitzContinuity, std::abs(firstSample->second - secondSample->second) / arma::norm(firstSample->first - secondSample->first));\n      }\n    }\n\n    return lipschitzContinuity;\n  }\n\n  std::vector<arma::uvec> additiveSeparability(\n      OptimisationProblem& optimisationProblem,\n      const arma::uword numberOfEvaluations,\n      const double minimalConfidence) {\n    assert(numberOfEvaluations > 0 && \"additiveSeparability: The number of evaluations must be greater than 0.\");\n    assert(0.0 <= minimalConfidence && minimalConfidence <= 1.0 && \"additiveSeparability: The minimal confidence must be within the interval (0, 1].\");\n\n    if (!isRepresentableAsFloatingPoint(numberOfEvaluations)) {\n      throw std::range_error(\"additiveSeparability: The number of elements must be representable as a floating point.\");\n    }\n\n    if (minimalConfidence <= 0) {\n      std::vector<arma::uvec> partition;\n      partition.reserve(optimisationProblem.numberOfDimensions_);\n\n      for (arma::uword n = 0; n < optimisationProblem.numberOfDimensions_; ++n) {\n        partition.push_back({n});\n      }\n\n      return partition;\n    }\n\n    /* The first of two steps to analyse the additive separability of a function is to estimate all two-set separations that fulfil the deviation and confidence requirements.\n     * A function *f* is additive separable into two other function *g*, *h* if the following holds:\n     *\n     * f(x, y) - g(x) - h(y) = 0, for all x, y\n     *\n     * As it is practical impossible to simply guess two separations *g*, *h* of *f*, when we only got a caller to `.getObjectiveValue(...)` and no analytic form, we use a direct consequence from the equation above instead, that must also hold true for additive separable functions and uses only *f*:\n     * \n     * f(a, c) + f(b, d) - f(a, d) - f(b, c) = 0, for all a, b, c, d\n     *\n     */\n\n    std::vector<std::pair<arma::uvec, arma::uvec>> partitionCandidates = twoSetsPartitions(optimisationProblem.numberOfDimensions_);\n\n    arma::rowvec confidences(partitionCandidates.size(), arma::fill::zeros);\n    for (arma::uword n = 0; n < partitionCandidates.size(); ++n) {\n      const std::pair<arma::uvec, arma::uvec>& partitionCandidate = partitionCandidates.at(n);\n\n      for (arma::uword k = 0; k < numberOfEvaluations; ++k) {\n        const arma::vec& firstFirstParamter = uniformRandomNumbers(optimisationProblem.numberOfDimensions_);\n        const arma::vec& secondSecondParameter = uniformRandomNumbers(optimisationProblem.numberOfDimensions_);\n\n        arma::vec firstSecondParameter = firstFirstParamter;\n        firstSecondParameter.elem(partitionCandidate.first) = secondSecondParameter.elem(partitionCandidate.first);\n        arma::vec secondFirstParameter = secondSecondParameter;\n        secondFirstParameter.elem(partitionCandidate.first) = firstFirstParamter.elem(partitionCandidate.first);\n\n        // **Note:** The summation of not-a-number values results in a not-a-number value and comparing it with another value returns false, so everything will work out just fine.\n        if (std::abs(optimisationProblem.getObjectiveValueOfNormalisedParameter(firstFirstParamter) + optimisationProblem.getObjectiveValueOfNormalisedParameter(secondSecondParameter) - optimisationProblem.getObjectiveValueOfNormalisedParameter(firstSecondParameter) - optimisationProblem.getObjectiveValueOfNormalisedParameter(secondFirstParameter)) < ::mant::machinePrecision) {\n          ++confidences(n);\n          if (confidences(n) / static_cast<double>(numberOfEvaluations) >= minimalConfidence) {\n            // Proceeds with the next partition candidate, as we already reached the confidence threshold.\n            break;\n          }\n        }\n      }\n    }\n\n    const arma::uvec& acceptablePartitionCandidatesIndicies = arma::find(confidences / static_cast<double>(numberOfEvaluations) >= minimalConfidence);\n    std::vector<std::pair<arma::uvec, arma::uvec>> acceptablePartitionCandidates;\n    acceptablePartitionCandidates.reserve(acceptablePartitionCandidatesIndicies.n_elem);\n\n    for (const auto acceptablePartitionCandidateIndex : acceptablePartitionCandidatesIndicies) {\n      acceptablePartitionCandidates.push_back(partitionCandidates.at(acceptablePartitionCandidateIndex));\n    }\n\n    /* The last of the two steps is to calculate the partition with the maximal number of parts, from all acceptable two-set partitions.\n     * If we now weaken our observation and assume that each accepted two-set partition holds true for **all** inputs, the partition with the maximal number of parts can be calculated by combining all intersections between one part and an other.\n     *\n     * For example, assume that we got 3 acceptable two-set partitions:\n     *\n     * - {{1, 2, 3, 4, 5}, {6}}\n     * - {{1}, {2, 3, 4, 5, 6}}\n     * - {{1, 2, 3}, {4, 5, 6}}\n     *\n     * We would then calculate the intersection between the first two partitions:\n     *\n     * {{1, 2, 3, 4, 5}, {6}} intersect {{1}, {2, 3, 4, 5, 6}} = \n     *   {{1, 2, 3, 4, 5} intersect {1}}             union\n     *   {{1, 2, 3, 4, 5} intersect {2, 3, 4, 5, 6}} union\n     *   {{6} intersect {1}}                         union \\\n     *   {{6} intersect {2, 3, 4, 5, 6}}                   / skipped and directly replaced by {{6}}\n     *   = {{1}, {2, 3, 4, 5}, {6}}\n     *\n     * And intersect the resulting partitions with the remaining one:\n     *\n     * {{1}, {2, 3, 4, 5}, {6}} intersect {{1, 2, 3}, {4, 5, 6}} = \n     *   {{1} intersect {1, 2, 3}}          union \\\n     *   {{1} intersect {4, 5, 6}}          union / skipped and directly replaced by {{1}}\n     *   {{2, 3, 4, 5} intersect {1, 2, 3}} union\n     *   {{2, 3, 4, 5} intersect {4, 5, 6}} union\n     *   {{6} intersect {1, 2, 3}}          union \\\n     *   {{6} intersect {4, 5, 6}}                / skipped and directly replaced by {{6}}\n     *   = {{1}, {2, 3}, {4, 5}, {6}}\n     *\n     * And get {{1}, {2, 3}, {4, 5}, {6}} as partition with the maximal number of parts.\n     */\n\n    if (acceptablePartitionCandidates.size() > 1) {\n      std::vector<arma::uvec> partition = {acceptablePartitionCandidates.at(0).first, acceptablePartitionCandidates.at(0).second};\n      acceptablePartitionCandidates.erase(acceptablePartitionCandidates.cbegin());\n\n      for (const auto& acceptablePartitionCandidate : acceptablePartitionCandidates) {\n        std::vector<arma::uvec> nextPartition;\n        for (const auto& part : partition) {\n          if (part.n_elem == 1) {\n            nextPartition.push_back(part);\n          } else {\n            // **Note:** `std::set_intersection` requires that all parts are ordered at this point.\n            std::vector<arma::uword> intersection;\n            std::set_intersection(part.begin(), part.end(), acceptablePartitionCandidate.first.begin(), acceptablePartitionCandidate.first.end(), intersection.begin());\n            nextPartition.push_back(arma::uvec(intersection));\n            intersection.clear();\n            std::set_intersection(part.begin(), part.end(), acceptablePartitionCandidate.second.begin(), acceptablePartitionCandidate.second.end(), intersection.begin());\n            nextPartition.push_back(arma::uvec(intersection));\n          }\n        }\n        partition = nextPartition;\n\n        // We are already finished, as there is no finer partition as having one part for each dimensions.\n        if (partition.size() == optimisationProblem.numberOfDimensions_) {\n          break;\n        }\n      }\n\n      return partition;\n    } else if (acceptablePartitionCandidates.size() == 1) {\n      return {acceptablePartitionCandidates.at(0).first, acceptablePartitionCandidates.at(0).second};\n    } else {\n      return {arma::regspace<arma::uvec>(0, optimisationProblem.numberOfDimensions_ - 1)};\n    }\n  }\n\n  std::vector<arma::uvec> additiveSeparability(\n      OptimisationProblem& optimisationProblem,\n      const arma::uword numberOfEvaluations) {\n    return additiveSeparability(optimisationProblem, numberOfEvaluations, 1.0);\n  }\n}\n", "meta": {"hexsha": "6d9e1a58363584738301204b2757a9f9c59e2d05", "size": 10791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/samplesAnalysis.cpp", "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": "src/samplesAnalysis.cpp", "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": "src/samplesAnalysis.cpp", "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": 52.1304347826, "max_line_length": 380, "alphanum_fraction": 0.6852006302, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5633482839226123}}
{"text": "#include <algorithm>\n#include <functional>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <glog/logging.h>\n\n#include <product-quantization/learn-product-quantization.h>\n\nnamespace product_quantization {\nvoid ComputePCARotation(\n    const Eigen::MatrixXf& data_points, Eigen::MatrixXf* rotation_matrix,\n    std::vector<float>* variances) {\n  CHECK_NOTNULL(rotation_matrix);\n  CHECK_NOTNULL(variances);\n  CHECK_GE(data_points.cols(), data_points.rows());\n\n  int num_dimensions = data_points.rows();\n  int num_data_points = data_points.cols();\n  rotation_matrix->resize(num_dimensions, num_dimensions);\n  variances->resize(num_dimensions);\n\n  Eigen::VectorXf mean = data_points.rowwise().mean();\n\n  Eigen::MatrixXf covariance_matrix;\n  covariance_matrix.setZero(num_dimensions, num_dimensions);\n  for (int i = 0; i < num_data_points; ++i) {\n    Eigen::VectorXf p = data_points.col(i) - mean;\n    covariance_matrix += p * p.transpose();\n  }\n  covariance_matrix /= static_cast<float>(num_data_points - 1);\n\n  Eigen::EigenSolver<Eigen::MatrixXf> eigen_solver(covariance_matrix);\n  Eigen::VectorXf eigenvalues = eigen_solver.eigenvalues().real();\n  *rotation_matrix = eigen_solver.eigenvectors().real().transpose();\n\n  for (int i = 0; i < num_dimensions; ++i) {\n    CHECK_GE(eigenvalues(i), 0.0);\n    (*variances)[i] = eigenvalues(i);\n  }\n}\n\nvoid EigenvalueAllocation(\n    const Eigen::MatrixXf& rotation_matrix, const std::vector<float>& variances,\n    int num_components, Eigen::MatrixXf* permutated_rotation_matrix) {\n  CHECK_EQ(rotation_matrix.cols(), rotation_matrix.rows());\n  CHECK_EQ(static_cast<unsigned int>(rotation_matrix.cols()), variances.size());\n  CHECK_EQ(rotation_matrix.cols() % num_components, 0);\n  CHECK_NOTNULL(permutated_rotation_matrix);\n\n  int num_dimensions = rotation_matrix.cols();\n  permutated_rotation_matrix->setIdentity(num_dimensions, num_dimensions);\n  // Sorts the rows in decreasing order of variance.\n  std::vector<std::pair<float, int> > variance_index_pairs(num_dimensions);\n  for (int i = 0; i < num_dimensions; ++i) {\n    variance_index_pairs[i].first = variances[i];\n    variance_index_pairs[i].second = i;\n  }\n  std::sort(\n      variance_index_pairs.begin(), variance_index_pairs.end(),\n      std::greater<std::pair<float, int> >());\n\n  // Performs EigenvalueAllocation by balancing the variances in a greedy\n  // fashion: Given the sorted variances, the algorithm iteratively selects the\n  // component with the minimum product of variances for which we have not\n  // yet selected enough rows.\n  std::vector<float> variance_product_per_component(num_components, -1.0f);\n  std::vector<int> num_selected_dimensions_per_component(num_components, 0);\n  int max_num_dimensions_per_component = num_dimensions / num_components;\n  for (int i = 0; i < num_dimensions; ++i) {\n    // Finds the component with the minimum product of variances.\n    int selected_component = -1;\n    float min_product_variance = std::numeric_limits<float>::max();\n    for (int j = 0; j < num_components; ++j) {\n      if (num_selected_dimensions_per_component[j] ==\n          max_num_dimensions_per_component) {\n        continue;\n      }\n\n      if (variance_product_per_component[j] < min_product_variance) {\n        min_product_variance = variance_product_per_component[j];\n        selected_component = j;\n      }\n    }\n    CHECK_GE(selected_component, 0);\n    if (min_product_variance == -1.0f) {\n      variance_product_per_component[selected_component] =\n          variance_index_pairs[i].first;\n    } else {\n      variance_product_per_component[selected_component] *=\n          variance_index_pairs[i].first;\n    }\n    permutated_rotation_matrix->row(\n        selected_component * max_num_dimensions_per_component +\n        num_selected_dimensions_per_component[selected_component]) =\n        rotation_matrix.row(variance_index_pairs[i].second);\n    ++num_selected_dimensions_per_component[selected_component];\n  }\n}\n}  // namespace product_quantization\n", "meta": {"hexsha": "e2cb1dbea6928c8498c30ae4808118a63b4e7133", "size": 4014, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/loopclosure/product-quantization/src/learn-product-quantization.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/loopclosure/product-quantization/src/learn-product-quantization.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/loopclosure/product-quantization/src/learn-product-quantization.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 38.9708737864, "max_line_length": 80, "alphanum_fraction": 0.7324364723, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.5633482672668911}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  ip3_atp_model.hpp\n *\n *    Description:\n *\n *        Version:  1.0\n *        Created:  Sunday 20 July 2014 10:44:10  IST\n *       Revision:  none\n *       Compiler:  gcc\n *\n *         Author:  Anup Pillai (), anupgpillai@gmail.com\n *   Organization:  IISER Pune\n *\n * =====================================================================================\n */\n\n#ifndef ASTRON_IP3_ATP_MODEL_HPP_INCLUDED\n#define ASTRON_IP3_ATP_MODEL_HPP_INCLUDED\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include \"astron_utility_functions.hpp\"\n//const double pi = boost::math::constants::pi<double>();\n\n//DECLATATIONS FOR IP3_SYSTEM\nclass IP3\n{\n   private:\n//------------------parameters from reduced Li-Rinzel form for IP3-calicum signalling\n      double a2 = 0.2E-03;     //    0.2         1/(micro M * sec)\n      double d1 = 0.13;   //     0.13        micro M\n      double d2 = 1.049;  //     1.049       micro M\n      double d3 = 0.9434;   //   0.9434      micro M\n      double d5 = 0.08234; //    0.08234     micro M\n\n      double c0 = 2.0;  //       2.0         micro M\n      double c1 = 0.185;   //                Dimensionless\n      double v1 = 6.0E-03; //        6.0         1/sec\n      double v2 = 0.11E-03;//        0.11        1/sec\n      double v3 = 0.9E-03;     //    0.9         1/ (micro M * sec)\n      double k3 = 0.1;   //      0.1         micro M\n\n//------------ parameters from Stamastakis-Mantzaris model for IP3 via ATP\n\n      double v4 = 4.0E-03;  //4.0 micro M/sec\n      double k4 = 0.3;  // 0.3 micro M\n      double a5 = 0.0; // dim.less (calcium feedback for IP3 production)\n      double k5 = 1.1; // 1.1 micro M\n      double v6 = 4E-03; // 0.19 /sec\n\n      double c7 = 1.0; // Dim.less cy_vol/extr-cell_vol\n      double v7 = 5.0E-03; // 5.0 micro M/sec (maximum ATP production rate)\n      double v8 = 6.0E-03;  // 6.0 micro M/sec (maximum degeneration rate)\n      double k8 = 5.0; // 5.0 micro M\n      double F0 = 0.05; // dimention less (ATP feedback)\n      double Cmax = 1.5; // 1.5 micro M (ATP feedback)\n   public:\n\n      double CaER = 0.0;      // micro M (Calcium concentration in the ER)\n      //double ip3_conc = 0.0;      // micro M (Given IP3 concentration in the cytosol)\n      //double ca_conc = 0.0;\n\n      double ip3_tau = 0.0;\n      double ip3_rate = 0.0;\n      double ip3_thres = 0.0;\n      double ip3_gen = 0.0;\n      double ip3_equ = 0.0;\n\n//------------------ CONSTRUCTORS\n\n   IP3(): CaER(0.0)//, ca_conc(0.0), ip3_conc(0.0) /* IP3 class implicit constructor */\n   {\n   };\n\n   /* ASTRO class explicit constructor */\n   //IP3( double CaER_, double ca_conc_, double ip3_conc_ ): CaER(CaER_), ca_conc(ca_conc_), ip3_conc(ip3_conc_)\n   IP3( double CaER_ ): CaER(CaER_)\n   {\n   };\n//------------------ Function declarations\n   void set_CaER(double ca_conc);\n\n   double m_inf(double ip3_conc, double ca_conc);\n   double h_inf(double ip3_conc, double ca_conc);\n   double h_tau(double ip3_conc, double ca_conc);\n\n   double F_ca(double ca_conc);\n\n   template <class State, class Deriv >\n   void operator() ( const State &x, Deriv &dxdt , const double  t );\n};\n//--------------------m_inf Function\ndouble IP3::m_inf(double ip3_conc, double ca_conc)\n{\n   double value =  ( ip3_conc / ( ip3_conc + d1 ) ) * ( ca_conc / (ca_conc + d5) ) ;\n   return value;\n};\n//--------------------h_tau Function\ndouble IP3::h_tau(double ip3_conc, double ca_conc)\n{\n   double Q2 = d2 * ((ip3_conc + d1)/(ip3_conc + d3));\n   double value  = 1 / (a2 * (Q2 + ca_conc) );\n   return value;\n}\n\n//--------------------h_inf Function\ndouble IP3::h_inf(double ip3_conc, double ca_conc)\n{\n   double Q2 = d2 * ((ip3_conc + d1)/(ip3_conc + d3));\n   double value = Q2/(Q2+ca_conc);\n   return value;\n};\n//--------------------Set CaER Function\nvoid IP3::set_CaER(double ca_conc)\n{\n   this->CaER = (c0 - ca_conc) / c1;\n   //std::cout << \"Set_CaER = \" << (c0 - ca_conc)/c1 << \"\\t\" << CaER << \"\\n\";\n};\n//----------Calicum induced ATP release function\ndouble IP3::F_ca(double ca_conc)\n{\n   double val = ( (F0/(F0-1)) - (2 * (ca_conc/Cmax)) ) / ( (1/(F0-1)) - pow((ca_conc/Cmax),2) );\n   return val;\n}\n//------- ASTRO class ODE Function\ntemplate <class State, class Deriv >\nvoid IP3::operator() ( const State &x_, Deriv &dxdt_ , const double t )\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   //std::cout << CaER << \"\\n\";\n\n   set_CaER(x[1]); // Update ER calcium level\n\n   dxdt[0] = ( h_inf(x[2],x[1]) - x[0] ) / h_tau(x[2],x[1]) ; // dh/dt\n\n   double JCh = ( c1 * v1 * pow(m_inf(x[2],x[1]),3) * pow(x[0],3) * (x[1] - CaER) ); //   J_channel\n   double JPump = ( v3 * pow(x[1],2) ) / ( pow(k3,2) + pow(x[1],2) ) ;   //    J_Pump\n   double JLeak = c1 * v2 * ( x[1] - CaER );   //    J_Leak\n\n   dxdt[1] = - (JCh + JPump + JLeak) ;// dCa/dt\n   double ip3_degrade = (x[2] - ip3_equ)/ip3_tau;\n   double ip3_mGluR = ip3_rate * heaviside(ip3_gen,ip3_thres);\n   //double ip3_atp = (v4 * x[3])/(k4+x[3]);\n   double ip3_atp = 0.0;//(v4 * x[3])/(k4+x[3]) * ( (x[1] + ((1-a5)*k5)) / (x[1] + k5) ); //- v6*x[2];\n   dxdt[2] =  -ip3_degrade + ip3_mGluR + ip3_atp ;//dip3/dt\n   //dxdt[3] = ( c7 * v7 * F_ca(x[1]) ) - ( v8 * (x[3] / (k8 + x[3])) ) ; //dATP/dt\n\n};\n\n#endif // ASTRON_IP3_ATP_MODEL_HPP_INCLUDED\n", "meta": {"hexsha": "fb86f3b0572de370a4192c4cecdd62359f9826f1", "size": 5458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/ip3_atp_model.hpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/ip3_atp_model.hpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/ip3_atp_model.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9871794872, "max_line_length": 112, "alphanum_fraction": 0.5454378893, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5633418799907605}}
{"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_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/detail/constant/maxexponentm1.hpp>\n#include <boost/simd/detail/constant/minexponent.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/exponent.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/max.hpp>\n#include <boost/simd/function/min.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/sqrt.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/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_IF(hypot_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( 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  BOOST_DISPATCH_OVERLOAD_IF ( hypot_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() (const fast_tag &,  A0 const& a0, A0 const& a1\n                                    ) const BOOST_NOEXCEPT\n    {\n      return boost::simd::sqrt(bs::fma(a0, a0, sqr(a1)));\n    }\n  };\n} } }\n\n#endif\n\n", "meta": {"hexsha": "ad4679cab2758dc00a81fd77e3e5e128de3620aa", "size": 3165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/hypot.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/hypot.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/hypot.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 35.5617977528, "max_line_length": 100, "alphanum_fraction": 0.5605055292, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5632129469115089}}
{"text": "\n#include <NTL/vec_lzz_p.h>\n\nNTL_START_IMPL\n\nvoid conv(vec_zz_p& x, const vec_ZZ& a)\n{\n   long i, n;\n\n   n = a.length();\n   x.SetLength(n);\n\n   zz_p* xp = x.elts();\n   const ZZ* ap = a.elts();\n\n   for (i = 0; i < n; i++)\n      conv(xp[i], ap[i]);\n}\n\nvoid conv(vec_ZZ& x, const vec_zz_p& a)\n{\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      x[i] = rep(a[i]);\n}\n\n\n\n\nvoid InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = min(a.length(), b.length());\n   long i;\n   zz_p accum, t;\n\n   clear(accum);\n   for (i = 0; i < n; i++) {\n      mul(t, a[i], b[i]);\n      add(accum, accum, t);\n   }\n\n   x = accum;\n}\n\nvoid InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b,\n                  long offset)\n{\n   if (offset < 0) Error(\"InnerProduct: negative offset\");\n   if (NTL_OVERFLOW(offset, 1, 0)) Error(\"InnerProduct: offset too big\");\n\n   long n = min(a.length(), b.length()+offset);\n   long i;\n   zz_p accum, t;\n\n   clear(accum);\n   for (i = offset; i < n; i++) {\n      mul(t, a[i], b[i-offset]);\n      add(accum, accum, t);\n   }\n\n   x = accum;\n}\n\nlong CRT(vec_ZZ& gg, ZZ& a, const vec_zz_p& G)\n{\n   long n = gg.length();\n   if (G.length() != n) Error(\"CRT: vector length 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;\n   for (i = 0; i < n; i++) {\n      if (!CRTInRange(gg[i], a)) {\n         modified = 1;\n         rem(g, gg[i], a);\n         if (g > a1) sub(g, g, a);\n      }\n      else\n         g = gg[i];\n   \n      h = rem(g, p);\n      h = SubMod(rep(G[i]), 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      gg[i] = g;\n   }\n\n   a = new_a;\n\n   return modified;\n}\n\n\n\nvoid mul(vec_zz_p& x, const vec_zz_p& a, zz_p b)\n{\n   long n = a.length();\n   x.SetLength(n);\n\n   long i;\n\n   if (n <= 1) {\n\n      for (i = 0; i < n; i++)\n\t mul(x[i], a[i], b);\n\n   }\n   else {\n \n      long p = zz_p::modulus();\n      double pinv = zz_p::ModulusInverse();\n      long bb = rep(b);\n      mulmod_precon_t bpinv = PrepMulModPrecon(bb, p, pinv);\n      \n      \n      const zz_p *ap = a.elts();\n      zz_p *xp = x.elts();\n\n      for (i = 0; i < n; i++)\n         xp[i].LoopHole() = MulModPrecon(rep(ap[i]), bb, p, bpinv);\n\n   }\n}\n\nvoid mul(vec_zz_p& x, const vec_zz_p& a, long b_in)\n{\n   zz_p b;\n   b = b_in;\n   mul(x, a, b);\n}\n\n\n\nvoid add(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = a.length();\n   if (b.length() != n) Error(\"vector add: dimension mismatch\");\n\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      add(x[i], a[i], b[i]);\n}\n\nvoid sub(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = a.length();\n   if (b.length() != n) Error(\"vector sub: dimension mismatch\");\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      sub(x[i], a[i], b[i]);\n}\n\nvoid clear(vec_zz_p& x)\n{\n   long n = x.length();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\nvoid negate(vec_zz_p& x, const vec_zz_p& a)\n{\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      negate(x[i], a[i]);\n}\n\n\nlong IsZero(const vec_zz_p& a)\n{\n   long n = a.length();\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\nvec_zz_p operator+(const vec_zz_p& a, const vec_zz_p& b)\n{\n   vec_zz_p res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\nvec_zz_p operator-(const vec_zz_p& a, const vec_zz_p& b)\n{\n   vec_zz_p res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\n\nvec_zz_p operator-(const vec_zz_p& a)\n{\n   vec_zz_p res;\n   negate(res, a);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\n\nzz_p operator*(const vec_zz_p& a, const vec_zz_p& b)\n{\n   zz_p res;\n   InnerProduct(res, a, b);\n   return res;\n}\n\n\nvoid VectorCopy(vec_zz_p& x, const vec_zz_p& a, long n)\n{\n   if (n < 0) Error(\"VectorCopy: negative length\");\n   if (NTL_OVERFLOW(n, 1, 0)) Error(\"overflow in VectorCopy\");\n\n   long m = min(n, a.length());\n\n   x.SetLength(n);\n  \n   long i;\n\n   for (i = 0; i < m; i++)\n      x[i] = a[i];\n\n   for (i = m; i < n; i++)\n      clear(x[i]);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "67ac1aeea507352e54434acf745be1f7c252077b", "size": 4472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ntl/vec_lzz_p.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/vec_lzz_p.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/vec_lzz_p.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": 16.6865671642, "max_line_length": 73, "alphanum_fraction": 0.5067084079, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.5631685338379218}}
{"text": "#include <RcppArmadillo.h>\n// [[Rcpp::depends(\"RcppArmadillo\")]]\n// [[Rcpp::depends(\"BH\")]]\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/random.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/math/distributions.hpp>\n\n#include <numeric>\n#include <algorithm>\n#include <map>\n#include <string>\n#include <iostream>\n\nusing namespace Rcpp;\nusing namespace arma;\nusing namespace std;\nusing namespace boost::multiprecision;\nusing namespace boost::math;\n\n\nclass LDA {\n  public:\n    int K; // K: number of topics\n  int W; // W: size of Vocabulary\n  int D; // D: number of documents\n  vector< vector<int> >  w_num;\n  vector< vector<int> >  z;\n  vector<int> nd_sum;\n  vector<int> nw_sum;\n  NumericMatrix nd;\n  NumericMatrix nw;\n  NumericMatrix phi_avg;\n  arma::mat PhiProdMat;\n  arma::mat n_wd;\n  vector< vector < vector<int> > > z_list;\n  vector< NumericMatrix > phi_list;\n  vector< NumericMatrix > theta_list;\n  NumericMatrix theta_avg;\n  CharacterVector Vocabulary; // vector storing all (unique) words of vocabulary\n  double alpha; // hyper-parameter for Dirichlet prior on theta\n  double beta; //  hyper-parameter for Dirichlet prior on phi\n  double sigma; // for Langevin sampler\n  boost::mt19937 rng; // seed for random sampling\n  List a;\n  \n  LDA(Reference Obj);\n  \n  void collapsedGibbs(int iter, int burnin, int thin);\n  void NichollsMH(int iter, int burnin, int thin);\n  void LangevinMHSampling(int iter, int burnin, int thin);\n  \n  NumericVector DocTopics(int d, int k);\n  NumericMatrix Topics(int k);\n  CharacterVector TopicTerms(int k, int no);\n  CharacterMatrix Terms(int k);\n  arma::rowvec rDirichlet(arma::rowvec param, int length);\n  arma::rowvec rDirichlet2(arma::rowvec param, int length);\n  arma::mat DrawFromProposal(arma::mat phi_current);\n  arma::mat InitPhiMat();\n  List getPhiList();\n  List getZList();\n  \n  double PhiDensity2(NumericMatrix phi);\n  double PhiDensity(arma::mat phi);\n  \n  arma::mat getPhiGradient(arma::mat phi);\n  \n  double rgamma_cpp(double alpha);\n  double rbeta_cpp(double shape1, double shape2);\n  double rnorm_cpp(double mean, double sd);\n  \n  double LogPhiProd(arma::mat phi); \n  vector<double> LogPhiProd_vec(arma::mat phi);\n  arma::mat DrawLangevinProposal(arma::mat phi_current);\n  double EvalLangevinProposal(arma::mat PhiFrom, arma::mat PhiTo);\n  arma::mat ProjectProposalToSimplex(arma::mat PhiProposal);\n  \n  private:\n    vector< vector<int> > CreateIntMatrix(List input);\n  \n  \n  NumericMatrix get_phis();\n  NumericMatrix get_thetas();\n  NumericMatrix MatrixToR(NumericMatrix input);\n  NumericMatrix avgMatrix(NumericMatrix A, NumericMatrix B, int weight);\n  NumericMatrix getTDM(int W, int D, List w_num);\n  \n  double ProposalDensity(arma::mat phi);\n  double ArrayMax(double array[], int numElements);\n  double ArrayMin(double array[], int numElements);\n  \n  \n  \n};\n\nLDA::LDA(Reference Obj)\n{\n  \n  K = as<int>(Obj.field(\"K\"));\n  W = as<int>(Obj.field(\"W\"));\n  D = as<int>(Obj.field(\"D\"));\n  \n  nw = as<NumericMatrix> (Obj.field(\"nw\"));\n  nd = as<NumericMatrix> (Obj.field(\"nd\"));\n  \n  alpha = Obj.field(\"alpha\");\n  beta = Obj.field(\"beta\");\n  sigma = 0.00001;\n  \n  Vocabulary = Obj.field(\"Vocabulary\");\n  \n  List temp_w = Obj.field(\"w_num\");\n  List temp_z = Obj.field(\"z\");\n  w_num = CreateIntMatrix(temp_w);\n  \n  NumericMatrix tdm = getTDM(W, D, temp_w);\n  int i = tdm.nrow(), j = tdm.ncol();\n  arma::mat n_wd_pointer(tdm.begin(), i, j, false);\n  n_wd = n_wd_pointer;\n  \n  z = CreateIntMatrix(temp_z);\n  \n  nd_sum = as<vector<int> > (Obj.field(\"nd_sum\"));\n  nw_sum = as<vector<int> > (Obj.field(\"nw_sum\"));\n  \n  \n  a = List::create(Named(\"z\")=z);\n};\n\nList LDA::getPhiList()\n{\n  int iter = phi_list.size();\n  List ret(iter);\n  \n  for (int i = 0; i<iter; i++)\n  {\n    ret[i] = phi_list[i];\n  }\n  return ret;\n}\n\nList LDA::getZList()\n{\n  int length = z_list.size();\n  List ret(length);\n  \n  for (int i = 0; i<length; i++)\n  {\n    ret[i] = wrap(z_list[i]);\n  }\n  return ret;\n}\n\nvector< vector<int> > LDA::CreateIntMatrix(List input)\n{\n  \n  int inputLength = input.size();\n  vector< vector<int> > output;\n  \n  for(int i=0; i<inputLength; i++) {\n    vector<int> test = as<vector<int> > (input[i]);\n    output.push_back(test);\n  }\n  \n  return output;\n  \n}\n\nNumericVector LDA::DocTopics(int d, int k)\n{\n  vector<double> d_theta(K);\n  NumericVector d_theta_R = theta_avg(d,_);\n  d_theta = as<vector<double> > (d_theta_R);\n  NumericVector ret_vector(k);\n  \n  for (int i=0;i<k;i++)\n  {\n    std::vector<double>::iterator result;\n    result = std::max_element(d_theta.begin(),d_theta.end());\n    int biggest_id = std::distance(d_theta.begin(), result);\n    ret_vector[i] = biggest_id;\n    d_theta[biggest_id] = 0;\n  }\n  \n  return ret_vector;\n}\n\nNumericMatrix LDA::Topics(int k)\n{\n  NumericMatrix ret(D,k);\n  for (int i = 0; i<D; i++)\n  {\n    NumericVector temp = DocTopics(i,k);\n    ret(i,_) = temp;\n  }\n  ret = MatrixToR(ret);\n  return ret;\n}\n\nCharacterVector LDA::TopicTerms(int k, int no)\n{\n  vector<double> k_phi(W);\n  NumericVector k_phi_R = phi_avg(k,_);\n  k_phi = as<vector<double> > (k_phi_R);\n  NumericVector ret_vector(no);\n  \n  for (int i=0;i<no;i++)\n  {\n    std::vector<double>::iterator result;\n    result = std::max_element(k_phi.begin(),k_phi.end());\n    int biggest_id = std::distance(k_phi.begin(), result);\n    ret_vector[i] = biggest_id;\n    k_phi[biggest_id] = 0;\n  }\n  \n  CharacterVector ret_char_vector(no);\n  \n  for (int i=0;i<no;i++)\n  {\n    ret_char_vector[i] = Vocabulary[ret_vector[i]];\n  }\n  \n  return ret_char_vector;\n  \n}\n\nCharacterMatrix LDA::Terms(int k)\n{\n  CharacterMatrix ret(K,k);\n  for (int i = 0; i < K; i++)\n  {\n    CharacterVector temp = TopicTerms(i,k);\n    ret(i,_) =  temp;\n  }\n  return ret;\n}\n\nNumericMatrix LDA::MatrixToR(NumericMatrix input)\n{\n  int n = input.nrow(), k = input.ncol();\n  NumericMatrix output(n,k);\n  for (int i = 0; i<n; i++)\n  {\n    for (int j = 0; j<k; j++)\n    {\n      output(i,j) = input(i,j) + 1;\n    }\n  }\n  return output;\n}\n\nvoid LDA::collapsedGibbs(int iter, int burnin, int thin)\n{\n  \n  double Kd = (double) K;\n  double Wd = (double) W;\n  double W_Beta  = Wd * beta;\n  double K_Alpha = Kd * alpha;\n  \n  for (int i = 0; i < iter; ++i)\n  {\n    for (int d = 0; d < D; ++d)\n    {\n      for (int w = 0; w < nd_sum[d]; ++w)\n      {\n        int word = w_num[d][w] - 1;\n        int topic = z[d][w] - 1;\n        \n        nw(word,topic) -= 1;\n        nd(d,topic) -= 1;\n        nw_sum[topic] -= 1;\n        nd_sum[d] -=  1;\n        \n        vector<double>  prob(K);\n        \n        for(int j=0; j<K; j++)\n        {\n          double nw_ij = nw(word,j);\n          double nd_dj = nd(d,j);\n          prob[j] = (nw_ij + beta) / (nw_sum[j] + W_Beta) *\n            (nd_dj + alpha) / (nd_sum[d] + K_Alpha);\n        }\n        \n        for (int r = 1; r < K; ++r)\n        {\n          prob[r] = prob[r] + prob[r - 1];\n        }\n        \n        double u  = prob[K-1] * rand() / double(RAND_MAX);\n        \n        int new_topic = 0; // set up new topic\n        \n        for (int nt = 0 ; nt < K; ++nt)\n        {\n          if (prob[nt] > u)\n          {\n            new_topic = nt;\n            break;\n          }\n        }\n        \n        //  assign new z_i to counts\n        nw(word,new_topic) +=  1;\n        nd(d,new_topic) += 1;\n        nw_sum[new_topic] += 1;\n        nd_sum[d] += 1;\n        \n        z[d][w] = new_topic + 1;\n        \n      }\n      \n    }\n    \n    \n    \n    if (i % thin == 0 && i > burnin)\n    {\n      z_list.push_back(z);\n      \n      NumericMatrix current_phi = get_phis();\n      NumericMatrix current_theta = get_thetas();\n      phi_list.push_back(current_phi);\n      theta_list.push_back(current_theta);\n      \n      if(phi_list.size()==1) phi_avg = current_phi;\n      else phi_avg =  avgMatrix(phi_avg, current_phi, phi_list.size());\n      \n      if(theta_list.size()==1) theta_avg = current_theta;\n      else theta_avg =  avgMatrix(theta_avg, current_theta, theta_list.size());\n      \n    }\n    \n  }\n}\n\nNumericMatrix LDA::avgMatrix(NumericMatrix A, NumericMatrix B, int weight)\n{\n  int nrow = A.nrow();\n  int ncol = A.ncol();\n  NumericMatrix C(nrow,ncol);\n  \n  float wf = (float) weight;\n  float propA = (wf-1) / wf;\n  float propB = 1 / wf;\n  \n  for (int i=0; i<nrow;i++)\n  {\n    for (int j=0; j<ncol;j++)\n    {\n      C(i,j) =  propA * A(i,j) + propB * B(i,j);\n    }\n  }\n  \n  return C;\n}\n\n\nNumericMatrix LDA::get_phis()\n{\n  \n  NumericMatrix phi(K,W);\n  \n  for (int k = 0; k < K; k++) {\n    for (int w = 0; w < W; w++) {\n      phi(k,w) = (nw(w,k) + beta) / (nw_sum[k] + W * beta);\n    }\n  }\n  \n  return phi;\n}\n\nNumericMatrix LDA::get_thetas()\n{\n  \n  NumericMatrix theta(D,K);\n  \n  for (int d = 0; d<D; d++) {\n    for (int k = 0; k<K; k++) {\n      theta(d,k) = (nd(d,k) + alpha) / (nd_sum[d] + K * alpha);\n    }\n  }\n  return theta;\n}\n\nNumericMatrix LDA::getTDM(int W, int D, List w_num) {\n  \n  NumericMatrix tdm(W,D);\n  for (int d=0; d<D; ++d)\n    for (int w=0; w<W; ++w)\n    {\n      int freq = 0;\n      vector<int> current_w = as<vector<int> > (w_num[d]);\n      int wlen = current_w.size();\n      for (int l=0; l<wlen; ++l)\n      {\n        if(current_w[l] == w + 1) freq += 1;\n      }\n      \n      tdm(w,d) = freq;\n    }\n  return tdm;\n}\n\n// using R: (unfortunately too slow to call R and convert objects back)\n//NumericMatrix LDA::DrawFromProposal()\n//  {\n  //    Environment MCMCpack(\"package:MCMCpack\");\n  //    Function rdirichlet = MCMCpack[\"rdirichlet\"];\n  //    return rdirichlet(K,rep(beta,W));\n  //  }\n\n\ndouble LDA::rbeta_cpp(double shape1, double shape2)\n{\n  double u  = rand() / double(RAND_MAX);\n  beta_distribution<> beta_dist(shape1, shape2);\n  return quantile(beta_dist, u);  \n}\n\ndouble LDA::rgamma_cpp(double alpha)\n{\n  boost::gamma_distribution<> dgamma(alpha);\n  boost::variate_generator<boost::mt19937&,boost::gamma_distribution<> > ret_gamma( rng, dgamma);\n  return ret_gamma();\n}\n\ndouble LDA::rnorm_cpp(double mean, double sd)\n{\n  boost::normal_distribution<> nd(mean, sd);\n  boost::variate_generator<boost::mt19937&, \n  boost::normal_distribution<> > ret_norm(rng, nd);\n  return ret_norm();  \n}\n\narma::rowvec LDA::rDirichlet(arma::rowvec param, int length)\n{\n  rowvec ret(length);\n  for (int l = 0; l<length; l++)\n  {\n    double beta = param[l];\n    ret[l] = rgamma_cpp(beta);\n  }\n  ret = ret / sum(ret);\n  return ret;\n}\n\narma::rowvec LDA::rDirichlet2(arma::rowvec param, int length)\n{\n  vector<double> ret;\n  param *= 10000;\n  vector<double> param_vec = conv_to<vector<double> >::from(param);\n  Rcout << param_vec[0] << \"-\";\n  int len = length - 1;\n  \n  double paramSum = std::accumulate(param_vec.begin()+1,param_vec.end(),(double)0);\n  Rcout << paramSum;\n  ret.push_back(rbeta_cpp(param_vec[0], paramSum));\n  for (int i=1; i<len;i++)\n  {\n    double paramSum = std::accumulate(param_vec.begin()+i+1,param_vec.end(),(double)0); \n    double phi = rbeta_cpp(param_vec[i], paramSum);\n    double sumRet = std::accumulate(ret.begin(),ret.end(),(double)0);  \n    ret.push_back((1-sumRet) * phi);\n  }   \n  double sumRet = std::accumulate(ret.begin(),ret.end(),(double)0); \n  ret.push_back(1-sumRet);\n  return ret;\n}  \n\n\nmat LDA::DrawFromProposal(arma::mat phi_current)\n{\n  arma::mat phi_sampled(K,W);\n  for (int k=0;k<K;k++)\n  {\n    arma::rowvec phi_current_row = phi_current.row(k);\n    arma::rowvec new_row = rDirichlet2(phi_current_row, W);\n    // Rcout << new_row;\n    phi_sampled.row(k) = new_row;\n  }\n  return phi_sampled;\n}\n\nmat LDA::InitPhiMat()\n{\n  arma::mat phi(K,W);\n  \n  for (int k=0; k<K; k++)\n  {\n    for (int w=0; w<W; w++)\n    {\n      phi(k,w) = beta / (W*beta);  \n    }\n  }\n  return phi;\n}    \n\n\nvoid LDA::NichollsMH(int iter, int burnin, int thin)\n{\n  \n  arma::mat phi_current = InitPhiMat();\n  \n  for (int t=1;t<iter;t++)\n  {\n    \n    // Metropolis-Hastings Algorithm:\n      // 1. draw from proposal density:\n      arma::mat hyperParams = beta + 0.1 * (phi_current - beta);\n    arma::mat phi_new = DrawFromProposal(hyperParams);\n    \n    // 2. Calculate acceptance probability\n    double pi_new = PhiDensity(phi_new);\n    double pi_old = PhiDensity(phi_current);\n    double q_new = ProposalDensity(phi_new);\n    double q_old = ProposalDensity(phi_current);\n    \n    double acceptanceMH = exp(pi_new + q_old - pi_old - q_new);\n    double alphaMH = min((double)1,acceptanceMH);\n    Rcout << \"Acceptance Prob:\" << alphaMH;\n    \n    // draw U[0,1] random variable\n    double u  = rand() / double(RAND_MAX);\n    if (u<=alphaMH) phi_current = phi_new;\n    else phi_current = phi_current;\n    \n    if (t % thin == 0 && t > burnin) {\n      NumericMatrix phi_add = wrap(phi_current);\n      phi_list.push_back(phi_add);\n      if(phi_list.size()==1) phi_avg = phi_add;\n      else phi_avg =  avgMatrix(phi_avg, phi_add, phi_list.size());\n    };\n    \n    // Rcout << pi_new;\n    // Rcout << pi_old;\n    // Rcout << q_new;\n    // Rcout << q_old;\n    \n    \n  }\n  \n}\n\ndouble LDA::LogPhiProd(arma::mat phi)\n{\n  arma::mat logPhi = log(phi);\n  double sumLik_vec[K];\n  double logPhiProd = 0;\n  \n  for (int d=0; d<D; d++)\n  {\n    double sumLik = 0;\n    arma::colvec nd = n_wd.col(d);\n    \n    for (int k=0; k<K; k++)\n    {\n      arma::rowvec logPhi_k = logPhi.row(k);\n      sumLik_vec[k] = dot(logPhi_k,nd);\n    }\n    double b = ArrayMax(sumLik_vec,K);\n    \n    for (int k=0; k<K; k++)\n    {\n      sumLik += exp(sumLik_vec[k]-b);\n    }\n    \n    logPhiProd += b + log(sumLik);\n  }  \n  \n  return logPhiProd;  \n}\n\nvector<double> LDA::LogPhiProd_vec(arma::mat phi)\n{   \n  vector<double> ret_vec;\n  arma::mat logPhi = log(phi);\n  arma::mat PhiProdMat_Pointer(K,D);\n  double sumLik_vec[K];\n  \n  for (int d=0; d<D; d++)\n  {\n    double sumLik = 0;\n    arma::colvec nd = n_wd.col(d);\n    \n    for (int k=0; k<K; k++)\n    {\n      arma::rowvec logPhi_k = logPhi.row(k);\n      sumLik_vec[k] = dot(logPhi_k,nd);    \n      PhiProdMat_Pointer(k,d) = sumLik_vec[k];\n    }\n    double b = ArrayMax(sumLik_vec,K);\n    \n    for (int k=0; k<K; k++)\n    {\n      sumLik += exp(sumLik_vec[k]-b);\n    }\n    \n    double ret_vec_d = b + log(sumLik);\n    ret_vec.push_back(ret_vec_d);\n  }  \n  PhiProdMat = PhiProdMat_Pointer;\n  return ret_vec;  \n}\n\n// function adapted from Yunmei Chen and Xiaojing Ye (2011)\n\n// [[Rcpp::export]]\nvector<double> ProjectOntoSimplex (vector<double> y)\n{\n  int m = y.size();\n  bool bget = false;\n  \n  vector<double> s = y;\n  std::sort(s.rbegin(), s.rend());\n  \n  double tmpsum = 0;\n  double tmax = 0;\n  \n  for (int i = 0; i<m-1; i++)\n  {\n    tmpsum = tmpsum + s[i];\n    tmax = (tmpsum - 1)/(i+1);\n    if (tmax >= s[i+1]) \n    {\n      bget = true;\n      break;\n    }\n  }\n  \n  if (bget==false) \n  {\n    tmax = (tmpsum + s[m-1] - 1)/m;\n  }\n  \n  vector<double> x;\n  for (int j = 0; j<m;j++)\n  {\n    double elem1 = y[j] - tmax;\n    double ret = max(elem1,0.0);\n    x.push_back(ret);\n  }\n  \n  return x;    \n}\n\narma::mat LDA::getPhiGradient(arma::mat phi)\n{\n  arma::mat phi2 = phi;\n  arma::mat logPhi = log(phi);\n  vector<double> denom_vec = LogPhiProd_vec(phi2);\n  arma::mat gradient(K,W);\n  \n  for (int z=0;z<K;z++)\n  {\n    for(int w=0;w<W;w++)\n    {\n      \n      double dSum = 0;  \n      \n      for (int d = 0; d<D;d++)\n      {  \n        double nwd = n_wd(w,d);\n        if (nwd==0) dSum += 0;\n        else \n        {\n          // Rcout << \"nwd:\" << nwd;\n          arma::colvec nd = n_wd.col(d);\n          arma::rowvec logPhi_k = logPhi.row(z);        \n          \n          double dotProd = PhiProdMat(z,d);\n          // Rcout << \"dotProd:\" << dotProd;\n          // Rcout << \"Dot Product: \" << dotProd;\n          \n          double Numerator = log(nwd) + (nwd - 1)*logPhi(z,w) + dotProd - nd[w]*logPhi_k[w]; \n          // Rcout << Numerator;\n          double Denominator = denom_vec[d];\n          // Rcout << Denominator;\n          dSum += exp(Numerator - Denominator);\n        }\n      }\n      // Rcout << \"dSum:\" << dSum; \n      gradient(z,w) = dSum + (beta - 1) / phi2(z,w);\n      //Rcout << gradient(z,w);\n    }\n  }\n  \n  return gradient;   \n}  \n\n\narma::mat LDA::DrawLangevinProposal(arma::mat phi_current)  \n{\n  arma::mat PhiProposal(K,W);\n  arma::mat PhiGradient = getPhiGradient(phi_current);\n  for (int z=0; z<K; z++)\n  {\n    vector<double> prop_vec; \n    for (int w=0; w<W; w++)\n    { \n      double error = rnorm_cpp(0,sigma);\n      double sigma_squared = pow(sigma,2);\n      PhiProposal(z,w) = phi_current(z,w) + 0.5 * sigma_squared * PhiGradient(z,w) + error;\n    }\n  }   \n  return PhiProposal;\n}\n\ndouble LDA::EvalLangevinProposal(arma::mat PhiFrom, arma::mat PhiTo)  \n{\n  double sigma_squared = pow(sigma,2);\n  double logDensity = 0;\n  arma::mat PhiGradient = getPhiGradient(PhiFrom);\n  for (int z=0; z<K; z++)\n  {\n    for (int w=0;w<W;w++)\n    {\n      double gradient_zw = PhiGradient(z,w);\n      double mean = PhiFrom(z,w) + 0.5 * sigma_squared * gradient_zw;\n      double PhiMeanDiff = PhiTo(z,w) - mean; \n      logDensity -= (1/(2*sigma_squared))*pow(PhiMeanDiff,2);\n    }\n  }   \n  return logDensity;\n}  \n\narma::mat LDA::ProjectProposalToSimplex(arma::mat PhiProposal)\n{\n  for (int z=0; z<K; z++)\n  {\n    vector<double> prop_vec = conv_to<vector<double> >::from(PhiProposal.row(z));\n    vector<double> Phi_proj_vec = ProjectOntoSimplex(prop_vec);\n    PhiProposal.row(z) = conv_to<rowvec>::from(Phi_proj_vec); \n  }\n  return PhiProposal;\n}\n\nvoid LDA::LangevinMHSampling(int iter, int burnin, int thin)\n{\n  arma::mat phi_current = InitPhiMat();\n  arma::mat phi_current_projected = ProjectProposalToSimplex(phi_current);\n  \n  for (int t=1;t<iter;t++)\n  {\n    \n    // Metropolis Algorithm:\n      // 1. draw from Langevin proposal density:\n      arma::mat phi_new = DrawLangevinProposal(phi_current_projected);\n    arma::mat phi_new_projected = ProjectProposalToSimplex(phi_new);\n    \n    // 2. Calculate acceptance probability\n    double pi_new = PhiDensity(phi_new_projected);\n    double pi_old = PhiDensity(phi_current_projected);\n    double q_num = EvalLangevinProposal(phi_new_projected,phi_current);\n    double q_denom = EvalLangevinProposal(phi_current_projected,phi_new);\n    \n    // Rcout << \"Pi_new:\" << pi_new;\n    // Rcout << \"Pi_old:\" << pi_old;\n    // Rcout << \"Q_numerator:\" << q_num;\n    // Rcout << \"Q_denominator:\" << q_denom;\n    \n    double acceptanceMH = exp(pi_new + q_num - pi_old - q_denom);\n    double alphaMH = min((double)1,acceptanceMH);\n    // Rcout << \"Acceptance Prob:\" << alphaMH;\n    \n    // draw U[0,1] random variable\n    double u  = rand() / double(RAND_MAX);\n    if (u<=alphaMH) \n    {\n      phi_current = phi_new;\n      phi_current_projected = phi_new_projected;\n    }\n    else \n    {\n      phi_current = phi_current;\n      phi_current_projected = phi_current_projected;\n    }\n    \n    if (t % thin == 0 && t > burnin) {\n      NumericMatrix phi_add = wrap(phi_current_projected);\n      phi_list.push_back(phi_add);\n      if(phi_list.size()==1) phi_avg = phi_add;\n      else phi_avg =  avgMatrix(phi_avg, phi_add, phi_list.size());\n    };\n    \n  }\n  \n}\n\n\ndouble LDA::ProposalDensity(arma::mat phi)\n{\n  double logBetaFun = 0;\n  double betaSum = 0;\n  for (int k=0; k<K;k++)\n  {\n    for (int w=0;w<W;w++)\n    {\n      double phi_scalar = phi(k,w);\n      logBetaFun += lgamma(phi_scalar);\n      betaSum  += phi_scalar;\n    }\n    \n  }\n  // double logBetaFun = K*(W*lgamma(beta)-lgamma(W*beta));\n  logBetaFun -= lgamma(betaSum);\n  \n  arma::mat logPhi = log(phi);\n  arma::mat temp = logPhi * (beta-1);\n  double logPhiSum = accu(temp);\n  \n  double logDensity = logPhiSum - logBetaFun;\n  return logDensity;\n}\n\ndouble LDA::PhiDensity(arma::mat phi)\n{\n  arma::mat logPhi = log(phi);\n  double sumLik_vec[K];\n  double logLikelihood = 0;\n  \n  for (int d=0; d<D; d++)\n  {\n    double sumLik = 0;\n    arma::colvec nd = n_wd.col(d);\n    \n    for (int k=0; k<K; k++)\n    {\n      arma::rowvec logPhi_k = logPhi.row(k);\n      sumLik_vec[k] = dot(logPhi_k,nd);\n    }\n    double b = ArrayMax(sumLik_vec,K);\n    \n    for (int k=0; k<K; k++)\n    {\n      sumLik += exp(sumLik_vec[k]-b);\n    }\n    \n    logLikelihood +=  b + log(sumLik);\n  }\n  \n  logLikelihood += D * log(alpha);\n  logLikelihood -= D * log(K*alpha);\n  // Rcout << \"logLikelihood: \" << logLikelihood;\n  \n  double logBetaFun = K*(lgamma(W*beta)-W*lgamma(beta));\n  // Rcout << \"logBetaFun: \" << logBetaFun;\n  \n  double logPhiSum = 0;\n  \n  arma::mat temp = logPhi * (beta-1);\n  logPhiSum = accu(temp);\n  \n  // Rcout << \"LogPhiSum: \" << logPhiSum;\n  \n  double logProb = logLikelihood + logBetaFun + logPhiSum;\n  return logProb;\n}\n\ndouble LDA::PhiDensity2(NumericMatrix phi)\n{\n  arma::mat phi2 = as<arma::mat>(phi);\n  arma::mat logPhi = log(phi2);\n  double logLikelihood_vec[D];\n  double logLikelihood = 0;\n  \n  for (int d=0; d<D; d++)\n  {\n    double sumLik = 0;\n    arma::colvec nd = n_wd.col(d);\n    \n    for (int k=0; k<K; k++)\n    {\n      arma::rowvec logPhi_k = logPhi.row(k);\n      double inProd_k = 0;\n      \n      for (int w=0; w<W; w++)\n      {\n        inProd_k += logPhi_k[w] * nd[w];\n      }\n      // Rcout << inProd_k;\n      double sumLik_k = exp(inProd_k) * alpha;\n      sumLik += sumLik_k;\n    }\n    logLikelihood_vec[d] = log(sumLik);\n    logLikelihood += logLikelihood_vec[d];\n  }\n  \n  logLikelihood -= D * log(K*alpha);\n  //Rcout << \"logLikelihood: \" << logLikelihood;\n  \n  double logBetaFun = K*(lgamma(W*beta)-W*lgamma(beta));\n  //Rcout << \"logBetaFun: \" << logBetaFun;\n  \n  double logPhiSum = 0;\n  \n  arma::mat temp = logPhi * (beta-1);\n  logPhiSum = accu(temp);\n  \n  //Rcout << \"LogPhiSum: \" << logPhiSum;\n  \n  double logProb = logLikelihood + logBetaFun + logPhiSum;\n  double Prob = exp(logProb);\n  return Prob;\n}\n\n\ndouble LDA::ArrayMax(double array[], int numElements)\n{\n  double max = array[0];       // start with max = first element\n  \n  for(int i = 1; i<numElements; i++)\n  {\n    if(array[i] > max)\n      max = array[i];\n  }\n  return max;                // return highest value in array\n}\n\ndouble LDA::ArrayMin(double array[], int numElements)\n{\n  double min = array[0];       // start with min = first element\n  \n  for(int i = 1; i<numElements; i++)\n  {\n    if(array[i] < min)\n      min = array[i];\n  }\n  return min;                // return smallest value in array\n}\n\n// [[Rcpp::export]]\nRCPP_MODULE(LDA_module) {\n  class_<LDA>( \"LDA\" )\n  .constructor<Reference>()\n  //.field( \"w_num\", &LDA::w_num)\n  .field( \"a\", &LDA::a)\n  .field( \"nd_sum\", &LDA::nd_sum)\n  .field(\"nd\",&LDA::nd)\n  .field( \"nw_sum\", &LDA::nw_sum)\n  .field(\"nw\",&LDA::nw)\n  .field(\"K\", &LDA::K)\n  .field(\"D\",&LDA::D)\n  .field(\"phi_avg\",&LDA::phi_avg)\n  .field(\"theta_avg\",&LDA::theta_avg)\n  .method(\"collapsedGibbs\",&LDA::collapsedGibbs)\n  .method(\"Topics\",&LDA::Topics)\n  .method(\"Terms\",&LDA::Terms)\n  .method(\"NichollsMH\",&LDA::NichollsMH)\n  .method(\"DrawFromProposal\",&LDA::DrawFromProposal)\n  .method(\"getPhiList\",&LDA::getPhiList)\n  .method(\"getZList\",&LDA::getZList)\n  .method(\"getPhiGradient\",&LDA::getPhiGradient)\n  .method(\"rgamma_cpp\",&LDA::rgamma_cpp)\n  .method(\"rbeta_cpp\",&LDA::rbeta_cpp)\n  .method(\"InitPhiMat\",&LDA::InitPhiMat)\n  .method(\"rDirichlet2\",&LDA::rDirichlet2)\n  .method(\"LogPhiProd_vec\",&LDA::LogPhiProd_vec)\n  .method(\"DrawLangevinProposal\",&LDA::DrawLangevinProposal)\n  .method(\"LangevinMHSampling\",&LDA::LangevinMHSampling)\n  .method(\"PhiDensity\",&LDA::PhiDensity)\n  .method(\"ProjectProposalToSimplex\",&LDA::ProjectProposalToSimplex)\n  ;\n}", "meta": {"hexsha": "81a73ecb5b9daa8f04a6acf38cc22acf49f3f4c9", "size": 23251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/10-LDAModule.cpp", "max_stars_repo_name": "tchakravarty/Stackoverflow-R", "max_stars_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/10-LDAModule.cpp", "max_issues_repo_name": "tchakravarty/Stackoverflow-R", "max_issues_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/10-LDAModule.cpp", "max_forks_repo_name": "tchakravarty/Stackoverflow-R", "max_forks_repo_head_hexsha": "65c17fade0a784018f2f3afcb4a9a8c603bd65a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-23T17:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T04:00:43.000Z", "avg_line_length": 24.0693581781, "max_line_length": 97, "alphanum_fraction": 0.5970065804, "num_tokens": 7243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5631584531655514}}
{"text": "#include <iostream>\n#include <math.h>\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n \nusing namespace std;\nusing namespace boost::python;\n \n\ndouble rand_norm(double mean, double stdev){\n  boost::mt19937 rng(rand()); \n\n  boost::normal_distribution<> nd(mean, stdev);\n\n  boost::variate_generator<boost::mt19937&, \n                           boost::normal_distribution<> > var_nor(rng, nd);\n  \n  double d = var_nor();\n\n  return d;\n}\n\ndouble rand_norm_range(double mean, double stdev, double min, double max){\n  int max_tries = 1000;\n  int tries = 0;\n\n  while (1){\n    tries++;\n\n    double x = rand_norm(mean, stdev);\n    if ((x >= min) & (x <= max)){\n      return x;\n    }\n    else if (tries >= max_tries){\n      cout << \"ERROR: exceeded max tries (n=\" \n\t   << max_tries \n\t   << \") to find a random variable\" << endl;\n      exit(1);\n    }    \n  }\n}\n\n\ndouble calc_diffusion_simple(double frag_gc, double frag_len){\n  /*\n    Simple calculation of diffusion based on fragment length\n  */\n  double diff_coef = 44500;    \n  double stdev = sqrt(diff_coef / frag_len);\n  return frag_gc + rand_norm(0, stdev);\n}\n\n\ndouble calc_diffusion_GC(double frag_GC, double frag_len,\n\t\t         double T, double B, double G, int M){\n  /*\n    Calculating diffusion in standard deviation of %G+C equivalents.\n    Adding diffusion G+C (drawn from normal distribution with s.d.=calculated s.d.) \n    to input G+C value.\n    Args:\n    frag_GC = G+C content of DNA fragment\n    frag_len = DNA fragment length (bp)\n    T = absolute temperature\n    B = beta\n    G = G coefficient (see Clay et al., 2003)\n    M = molecular weight per base pair of dry cesium DNA\n   */\n\n  double frag_BD = frag_GC / 100 * 0.098 + 1.66;\n  double R = 8.3145e7;    \n  double GC_sd = sqrt(pow(100 / 0.098, 2) * ((frag_BD*R*T)/(pow(B,2)*G*M*frag_len)));\n\n  return rand_norm(0, GC_sd);  \n}\n\ndouble calc_diffusion_BD(double frag_BD, double frag_len,\n\t\t         double T, double B, double G, int M){\n  /*\n    Calculating diffusion in standard deviation of buoyant_density equivalents (rho).\n    Args:\n    frag_BD = rho (buoyant density)\n    frag_len = fragment length (bp)\n    T = absolute temperature\n    B = beta\n    G = G coefficient (see Clay et al., 2003)\n    M = molecular weight per base pair of dry cesium DNA\n    Return:\n    BD error due to diffusion value drawn from a normal distribution with a \n    standard deviation determined by calculated diffusion\n   */\n\n  double R = 8.3145e7;    \n  double sd_BD = sqrt((frag_BD*R*T)/(pow(B,2)*G*M*frag_len));\n\n  return rand_norm(0, sd_BD);  \n}\n\n\ndouble GC2BD(double GC){  \n  /*\n    Calaculate buoyant density from G+C.\n    Args:\n    GC = % GC of DNA fragment\n  */\n  return GC / 100.0 * 0.098 + 1.66;\n}\n\n \ndouble addIncorpBD(double frag_BD, double incorp_perc, double isoMaxBD){\n  return incorp_perc / 100 * isoMaxBD + frag_BD;\n}\n \n\nBOOST_PYTHON_MODULE(SIPSimCpp)\n{\n  def(\"rand_norm\", rand_norm);\n  def(\"rand_norm_range\", rand_norm_range);\n  def(\"calc_diffusion_GC\", calc_diffusion_GC);\n  def(\"calc_diffusion_BD\", calc_diffusion_BD);\n  def(\"GC2BD\", GC2BD);\n  def(\"addIncorpBD\", addIncorpBD);\n}\n", "meta": {"hexsha": "071c96f621f062a184c03afabbd9da5f5445499d", "size": 3184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SIPSimCpp.cpp", "max_stars_repo_name": "arischwartz/test", "max_stars_repo_head_hexsha": "87a8306a294f59b0eef992529ce900cea876c605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T09:46:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T18:16:39.000Z", "max_issues_repo_path": "src/SIPSimCpp.cpp", "max_issues_repo_name": "arischwartz/test", "max_issues_repo_head_hexsha": "87a8306a294f59b0eef992529ce900cea876c605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-01T23:18:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-01T23:18:10.000Z", "max_forks_repo_path": "src/SIPSimCpp.cpp", "max_forks_repo_name": "arischwartz/test", "max_forks_repo_head_hexsha": "87a8306a294f59b0eef992529ce900cea876c605", "max_forks_repo_licenses": ["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.472, "max_line_length": 85, "alphanum_fraction": 0.6592336683, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5631584477637737}}
{"text": "﻿// ConsoleApplication1.cpp : 此文件包含 \"main\" 函数。程序执行将在此处开始并结束。\r\n#include <iostream>\r\nusing namespace std;\r\n#include <ctime>\r\n// Eigen 部分\r\n#include <Eigen/Core>\r\n//映入Cholesky\r\n#include <Eigen/Cholesky>\r\n// 稠密矩阵的代数运算（逆，特征值等）\r\n#include <Eigen/Sparse>\r\n#include <Eigen/Dense>\r\nusing namespace Eigen;     // 改成这样亦可 using Eigen::MatrixXd; \r\nusing namespace std;\r\n\r\n#define  MATRIX_SIZE 4\r\n/*\r\nint main(int argc, char** argv)\r\n{\r\n    // 解方程\r\n    // 我们求解 A * x = b 这个方程\r\n    // 直接求逆自然是最直接的，但是求逆运算量大\r\n\r\n    //Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > A1;\r\n    //A1 = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);\r\n    SparseMatrix<double> A1(MATRIX_SIZE, MATRIX_SIZE);\r\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > b1;\r\n    b1 = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\r\n\r\n    clock_t time_stt = clock(); // 计时\r\n    //Cholesky 解方程\r\n\r\n\r\n    // 直接求逆\r\n    Eigen::Matrix<double, MATRIX_SIZE, 1> x = A1.inverse() * b1;\r\n    cout << \"time use in normal inverse is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n    // QR分解colPivHouseholderQr()\r\n    //time_stt = clock();\r\n    x = A1.colPivHouseholderQr().solve(b1);\r\n    cout << \"time use in Qr decomposition is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n    //QR分解fullPivHouseholderQr()\r\n    //time_stt = clock();\r\n    //x = A1.fullPivHouseholderQr().solve(b1);\r\n    //cout << \"time use in Qr decomposition is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n    //llt分解 要求矩阵A正定\r\n    time_stt = clock();\r\n    x = A1.llt().solve(b1);\r\n    cout <<\"time use in llt decomposition is \" <<1000*(clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\r\n    cout <<x<<endl;\r\n    //ldlt分解  要求矩阵A正或负半定\r\n    time_stt = clock();\r\n    x = A1.ldlt().solve(b1);\r\n    cout <<\"time use in ldlt decomposition is \" <<1000*(clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\r\n    cout <<x<<endl;\r\n    //lu分解 partialPivLu()\r\n    time_stt = clock();\r\n    x = A1.partialPivLu().solve(b1);\r\n    cout << \"time use in lu decomposition is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n    //lu分解（fullPivLu()\r\n    // = clock();\r\n    //x = A1.fullPivLu().solve(b1);\r\n    //cout << \"time use in lu decomposition is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n\r\n    //x = A1.bdcSvd(ComputeThinU | ComputeThinV).solve(b1);\r\n    cout << \"time use in svd is \" << 1000 * (clock() - time_stt) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\r\n    //cout << x << endl;\r\n    return 0;\r\n\r\n}\r\n*/\r\n// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单\r\n// 调试程序: F5 或调试 >“开始调试”菜单\r\n\r\n// 入门使用技巧: \r\n//   1. 使用解决方案资源管理器窗口添加/管理文件\r\n//   2. 使用团队资源管理器窗口连接到源代码管理\r\n//   3. 使用输出窗口查看生成输出和其他消息\r\n//   4. 使用错误列表窗口查看错误\r\n//   5. 转到“项目”>“添加新项”以创建新的代码文件，或转到“项目”>“添加现有项”以将现有代码文件添加到项目\r\n//   6. 将来，若要再次打开此项目，请转到“文件”>“打开”>“项目”并选择 .sln 文件\r\n", "meta": {"hexsha": "49e12fc08ca345718dc9e60d90d4f252055fcde6", "size": 3011, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Non-iterative-Methods/Eigen/ConsoleApplication1.cpp", "max_stars_repo_name": "1751200/Xlab-k8s-gpu", "max_stars_repo_head_hexsha": "b258f9610d2416a047f8f9545b1d6f66a7e88df3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T12:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T04:24:41.000Z", "max_issues_repo_path": "Non-iterative-Methods/Eigen/ConsoleApplication1.cpp", "max_issues_repo_name": "1751200/Xlab-k8s-gpu", "max_issues_repo_head_hexsha": "b258f9610d2416a047f8f9545b1d6f66a7e88df3", "max_issues_repo_licenses": ["Apache-2.0"], "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-iterative-Methods/Eigen/ConsoleApplication1.cpp", "max_forks_repo_name": "1751200/Xlab-k8s-gpu", "max_forks_repo_head_hexsha": "b258f9610d2416a047f8f9545b1d6f66a7e88df3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T08:29:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T06:18:44.000Z", "avg_line_length": 35.4235294118, "max_line_length": 122, "alphanum_fraction": 0.592494188, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5631584477149637}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <array>\r\n#include <math.h>\r\n#include \"AdaptiveHeat.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <fstream>\r\n#include <string>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\nconst double M_PI = 2*acos(0);\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\r\nSpaceMesh smesh;\r\nsmesh.GenerateSpaceMesh({0, 0.15,  0.25, 0.5, 1.0});\r\n//smesh.GloballyBisectSpaceMesh();\r\n\r\nsmesh.PrintSpaceNodes();\r\nstd::cout<<smesh.meshsize() <<\"\\n\";\r\nstd::cout<<\"\\n\";\r\n\r\n\r\nTimeMesh tmesh;\r\ntmesh.GenerateUniformTimeMesh(pow(smesh.meshsize(), 2), 1.0);\r\n\r\nAdaptiveHeatEquation adaptiveheat;\r\nadaptiveheat.SetSpaceTimeMesh( smesh, tmesh, \"soultion1.txt\");\r\nadaptiveheat.AdaptiveSolver();\r\n\r\n\r\n//adaptiveheat.Solve();\r\n\r\n\r\n//adaptiveheat.PrintSolution();\r\n\r\n//adaptiveheat.PrintErrorMesh();\r\nadaptiveheat.PrintSolution();\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "7bdfa53f678312ec9ed88f437b0f2e6712399140", "size": 931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sover class with method to adapt in space and time/driver.cpp", "max_stars_repo_name": "thabomiles/FEMHeatEquation", "max_stars_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sover class with method to adapt in space and time/driver.cpp", "max_issues_repo_name": "thabomiles/FEMHeatEquation", "max_issues_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sover class with method to adapt in space and time/driver.cpp", "max_forks_repo_name": "thabomiles/FEMHeatEquation", "max_forks_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.3958333333, "max_line_length": 63, "alphanum_fraction": 0.6981740064, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5631584368137875}}
{"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 Matrix<ImgLine, Dynamic, Dynamic> FlattenedImages;\n\nunsigned char max(u_char a, u_char b)\n{\n    if (a < b)\n        return b;\n    else\n        return a;\n}\n\nunsigned char min(u_char a, u_char b)\n{\n    if (a > b)\n        return b;\n    else\n        return a;\n}\n\ndouble max(double a, double b)\n{\n    if (a < b)\n        return b;\n    else\n        return a;\n}\n\ndouble min(double a, double b)\n{\n    if (a > b)\n        return b;\n    else\n        return a;\n}\n\nvector<double> projectOnEigenSpace(EigenSolver<TempMatrixImg> &solver, TempMatrixImg &img, int K)\n{\n    vector<double> res;\n    for (int i = 0; i < K; i++)\n    {\n        double test = ((solver.eigenvectors().col(i).real().transpose()) * img)(0);\n        res.push_back(test);\n    }\n    return res;\n}\n\nvoid writeEigenfaces(EigenSolver<TempMatrixImg> &covMat, MatrixImg &A, int nbrFaces)\n{\n    // covMat.eigenvalues.\n}\n\nvoid makeEigenSpace(std::string dirIn, std::string dirOut)\n{\n    int nH, nW;\n    vector<OCTET *> set = vector<OCTET *>();\n\n    OCTET *meanImg;\n    long long *tempMean;\n\n    long totNumberIm = 0;\n    for (auto &file : std::filesystem::directory_iterator(dirIn))\n    {\n        if (totNumberIm == 0)\n        {\n            cout << file.path().c_str() << endl;\n            lire_nb_lignes_colonnes_image_pgm(file.path().c_str(), &nH, &nW);\n            allocation_tableau(meanImg, OCTET, nH * nW);\n            tempMean = (long long *)calloc(nH * nW, sizeof(long long));\n        }\n        // OCTET* im; allocation_tableau(im,OCTET,nH*nW);\n        OCTET *im;\n        set.push_back(im);\n        allocation_tableau(set[totNumberIm], OCTET, nH * nW);\n        lire_image_pgm(file.path().c_str(), set[totNumberIm], nH * nW);\n\n        for (int i = 0; i < nH * nW; i++)\n        {\n            tempMean[i] += set[totNumberIm][i];\n        }\n\n        totNumberIm++;\n    }\n\n    for (int i = 0; i < nH * nW; i++)\n    {\n        meanImg[i] = (unsigned char)((double)tempMean[i] / ((double)totNumberIm));\n    }\n    ecrire_image_pgm(string(dirOut + string(\"/mean.pgm\")).c_str(), meanImg, nH, nW);\n\n    TempMatrixImg bigMatNoMean(nH * nW, totNumberIm);\n    for (int i = 0; i < totNumberIm; i++)\n    {\n        for (int pix = 0; pix < nW * nH; pix++)\n        {\n            bigMatNoMean(pix, i) = set[i][pix] - meanImg[pix] + 128;\n        }\n    }\n\n    TempMatrixImg cov = bigMatNoMean.transpose() * bigMatNoMean;\n    EigenSolver<TempMatrixImg> eigensolver(cov);\n\n    for (int i = 0; i < eigensolver.eigenvectors().cols(); i++)\n    {\n        OCTET *im;\n        allocation_tableau(im, OCTET, nH * nW);\n        TempMatrixImg face = bigMatNoMean * eigensolver.eigenvectors().col(i).real();\n        double minD = face(0);\n        double maxD = face(0);\n        for (int pix = 1; pix < nH * nW; pix++)\n        {\n            minD = min(minD, face(pix));\n            maxD = max(maxD, face(pix));\n        }\n        for (int pix = 0; pix < nH * nW; pix++)\n        {\n            // cout<<(face(pix)-minD)*(255.0/(maxD-minD))<<endl;\n            im[pix] = (unsigned char)((face(pix) - minD) * (255.0 / (maxD - minD))); // comment fit dans 0 255 ?\n        }\n        char name[50];\n        sprintf(name, \"/eigenfaces/im%d.pgm\", i);\n        ecrire_image_pgm(string(dirOut + string(name)).c_str(), im, nH, nW);\n    }\n}\n\nint main(int argc, char *argv[])\n{\n\n    std::string nom = string(\"in\");\n    string dirIn = string(argv[1]);\n    string dirOut = string(argv[2]);\n    makeEigenSpace(dirIn,dirOut);\n\n    //      int nH,nW;\n    //\n    // //     vector<vector<OCTET*>> imageSet = vector<vector<OCTET*>>();\n    // //     for (int i=0; i<40;i++){\n    // //         imageSet.push_back(vector<OCTET*>());\n    // //         for (int j=0;j<10;j++){\n    // //             OCTET* im;\n    // //             imageSet[i].push_back(im);\n    // //         }\n    // //     }\n\n    // //     OCTET* meanImg;\n    // //     long long* tempMean ;\n    // //     int countDirs = 0;\n    // //     long totalNumberOfImages=0;\n    // int i=0;int j=0;\n    //     for (auto & dir : std::filesystem::directory_iterator(nom)){\n    //         int countFile=0;\n    //         for (auto & file : std::filesystem::directory_iterator(dir.path())){\n    //             OCTET* img;\n    //             lire_nb_lignes_colonnes_image_pgm(file.path().c_str(),&nH,&nW);\n    //             allocation_tableau(img,OCTET,nH*nW);\n    //             lire_image_pgm(file.path().c_str(),img,nH*nW);\n    //             char name[50];\n    //             sprintf(name,\"in/%d%d.pgm\",i,j);\n    //             ecrire_image_pgm(name,img,nH,nW);\n\n    // allocation_tableau(imageSet[countDirs][countFile],OCTET,nH*nW);\n    // for (int pix = 0;pix<nH*nW;pix++){\n    //     imageSet[countDirs][countFile][pix]=img[pix];\n    // }\n    // //imageSet[countDirs].push_back(img);\n    // if (countDirs==0 && countFile==0){\n    //     allocation_tableau(meanImg,OCTET,nH*nW);\n    //     tempMean=(long long*)calloc(nH*nW,sizeof(long long));\n    // }\n\n    // for (int i=0;i<nH*nW;i++){\n    //     tempMean[i]+=img[i];\n    // }\n\n    // totalNumberOfImages++;\n    // countFile++;\n\n    // //free(img);\n    //         j++;\n    //     }\n    //     i++;\n\n    // }\n\n    //     allocation_tableau(meanImg,OCTET,nH*nW);\n    //     for (int i=0;i<nH*nW;i++){\n    //         meanImg[i]=(unsigned char)(tempMean[i]/totalNumberOfImages);\n    //     }\n\n    //     ecrire_image_pgm(\"MEAN.pgm\",meanImg,nH,nW);\n\n    //     vector<vector<OCTET*>> imagesSansMean = vector<vector<OCTET*>>();\n    //     vector<vector<TempMatrixImg>> matrixNoMean = vector<vector<TempMatrixImg>>();\n\n    //     for (int i=0;i<imageSet.size();i++){\n    //         imagesSansMean.push_back(vector<OCTET*>());\n    //         matrixNoMean.push_back(vector<TempMatrixImg>());\n    //         for (int j=0; j<imageSet[i].size();j++){\n    //             OCTET* img;\n    //             TempMatrixImg mat(nH,nW);\n    //             imagesSansMean[i].push_back(img);\n    //             allocation_tableau(imagesSansMean[i][j],OCTET,nH*nW);\n\n    //             allocation_tableau(img,OCTET,nH*nW);\n    //             for (int pix=0;pix<nH*nW;pix++){\n    //                 img[pix]=min(255,max(0,imageSet[i][j][pix]+128-meanImg[pix]));\n    //                 imagesSansMean[i][j][pix]=img[pix];\n\n    //             }\n    //             for (int x=0;x<nH;x++){\n    //                 for (int y=0; y<nW;y++){\n    //                     mat(x,y)=img[x*nW+y];\n    //                 }\n    //             }\n    //             matrixNoMean[i].push_back(mat);\n\n    //             //uncomment to write images\n\n    //             //char name[50];\n    //             //sprintf(name,\"meanless/im%d_%d\",i,j);\n    //             //ecrire_image_pgm(name,img,nH,nW);\n    //         }\n    //     }\n\n    //    TempMatrixImg bigMatNoMean(nH*nW,totalNumberOfImages);\n    //     for (int i=0;i<imageSet.size();i++){\n    //         for (int j=0; j<imageSet[i].size();j++){\n    //             for (int pix=0;pix<nH*nW;pix++){\n    //                 bigMatNoMean(pix,i*imageSet[0].size()+j)=(double)imagesSansMean[i][j][pix];\n    //             }\n    //         }\n    //     }\n\n    //     TempMatrixImg cov = bigMatNoMean.transpose()*bigMatNoMean;\n\n    //     EigenSolver<TempMatrixImg> eigensolver(cov);\n    //     //cout<<eigensolver.eigenvalues()<<endl;\n\n    //     for (int i=0;i<eigensolver.eigenvectors().cols();i++){\n    //         OCTET* im; allocation_tableau(im,OCTET,nH*nW);\n    //         TempMatrixImg face = bigMatNoMean*eigensolver.eigenvectors().col(i).real();\n    //         double minD=face(0);double maxD=face(0);\n    //         for (int pix =1; pix<nH*nW;pix++){minD=min(minD,face(pix));maxD=max(maxD,face(pix));}\n    //         for (int pix=0;pix<nH*nW;pix++){\n    //             //cout<<(face(pix)-minD)*(255.0/(maxD-minD))<<endl;\n    //             im[pix]=(unsigned char)((face(pix)-minD)*(255.0/(maxD-minD)));     // comment fit dans 0 255 ?\n    //         }\n    //         char name[50];\n    //         sprintf(name,\"eigenfaces/im%d.pgm\",i);\n    //         ecrire_image_pgm(name,im,nH,nW);\n\n    //     }\n\n    // OCTET* felix; allocation_tableau(felix,OCTET,nH*nW);\n    // lire_image_pgm(\"felixResized.pgm\",felix,nH*nW);\n\n    // TempMatrixImg fix(nH,nW) ;\n    // for (int i=0;i<nH;i++){\n    //     for (int j=0; j<nW;j++){\n    //         fix(i,j)=(double)felix[i*nW+j] - meanImg[i*nW+j];\n    //     }\n    // }\n\n    // vector<double> proj ; proj = projectOnEigenSpace(eigensolver, fix, 40);\n    // for (int i=0; i<40; i++){\n    //     cout<<proj[i];\n    // }\n    // cout<<endl;\n}", "meta": {"hexsha": "ba86c933683cd0927faa054da42b057b7c4cdc33", "size": 8895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/eigenface.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/eigenface.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/eigenface.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": 31.3204225352, "max_line_length": 113, "alphanum_fraction": 0.5189432265, "num_tokens": 2674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5631312625174081}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <random>\n#include <vector>\n#include <boost/filesystem.hpp>\n#include <boost/thread/thread.hpp>\n#include \"sampling.h\"\n#include \"utilities.h\"\n\nconst int MAX_BATCH = 13;\nconst int MAX_PATHS = 40320;\n\n/*\n    Single unit of the Travellers Algorithm\n\n    A set of paths are generated. These paths start at the 'source' point, go\n    through each point in 'points' and end at the 'destination' point.\n\n    The maximum number of paths that can be generated is 'max_paths'. If the\n    number of possible permutations for the paths is larger than 'max_paths',\n    the paths generated will be chosen at random.\n\n    Once the set of paths has been generated, they are sorted on a scale from\n    0 to 1. The 0 indicates the path with the shortest distance and 1 indicates\n    the path with the longest. The path chosen is the path which is nearest on\n    the scale to 'calibration'.\n\n    This function returns the indicies of the 'points' of the chosen path\n*/\nstd::vector<int> travel(\n    const point& source,\n    const point& destination,\n    const std::vector<point>& points,\n    const float& calibration,\n    const int& max_paths=MAX_PATHS\n)\n{\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    /*\n        Create a 2d matrix which stores the euclidean distances between each of\n        the points.\n    */\n    matrix graph = euclideanMatrix(source, points, destination);\n\n\n    int n = points.size();\n    int n_factorial = factorial(n);\n    int permutation_count;\n    std::vector<int> values;\n\n    if (n_factorial <= max_paths) {\n        for (int i = 0; i < n_factorial; ++i) {\n            values.emplace_back(i);\n        }\n        std::shuffle(values.begin(), values.end(), gen);\n        permutation_count = n_factorial;\n    }\n    else {\n        permutation_count = max_paths;\n        values = sampling::sample_range(permutation_count, n_factorial, gen);\n    }\n\n    permutation permutation;\n    std::vector<permutation_cost> permutation_costs;\n    for (int value: values) {\n\n        float cost = 0;\n        int current_index = 0;\n\n        permutation = integer_to_permutation(value, n);\n\n        for (int next_index: permutation) {\n            cost += graph[current_index][next_index];\n            current_index = next_index;\n        }\n\n        cost += graph[current_index][n+1];\n\n        permutation_costs.push_back(permutation_cost(permutation, cost));\n    }\n\n    /*\n        Order the permutation_costs from lowest to highest.\n        Select the permutation according to the calibration.\n    */\n    sort(permutation_costs.begin(), permutation_costs.end(), sortByCost);\n\n    return permutation_costs[calibration*(permutation_count-1)].first;\n}\n\n\nstd::vector<std::pair<int, permutation>> indexed_permutation;\nboost::mutex mutex;\n\nvoid shall(\n    int& index,\n    const point& source,\n    const point& destination,\n    const std::vector<point>& points,\n    const float& calibration\n)\n{\n    permutation perm = travel(source, destination, points, calibration);\n\n    mutex.lock();\n    indexed_permutation.emplace_back(index, perm);\n    mutex.unlock();\n}\n\n/*\n     Batching unit of the Travellers Algorithm\n\n     Points are batched the the single unit Travellers Algorithm is applied to\n     each batch, returning the indicies in the order as if the path sequentially\n     passes through each batch.\n*/\nstd::vector<int> travels(std::vector<point> points, const float& calibration)\n{\n    int n = points.size();\n    std::vector<int> batch_counts = get_batches(n, MAX_BATCH);\n\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    std::vector<int> indicies = sampling::sample_range(n, n, gen);\n    std::vector<int> results;\n\n    point source = points[indicies[0]];\n    point destination;\n\n    std::vector<point> batch_points;\n    int i = 1;\n\n    std::vector<boost::thread> threads;\n\n    for (int k = 0; k < batch_counts.size(); ++k) {\n\n        batch_points.clear();\n        for (int j = 0; j < batch_counts[k] - 1; ++j) {\n            batch_points.emplace_back(points[indicies[i++]]);\n        }\n\n        destination = points[indicies[i++ % n]];\n\n        threads.emplace_back(std::move(boost::thread(\n            shall,\n            i-batch_counts[k]-1,\n            source,\n            destination,\n            batch_points,\n            calibration\n        )));\n\n        destination = source;\n    }\n\n    for (int i = 0; i < threads.size(); ++i) {\n        threads[i].join();\n    }\n\n    for (std::pair<int, std::vector<int>> pair: indexed_permutation) {\n        results.emplace_back(indicies[pair.first]);\n        for (int num: pair.second) {\n            results.emplace_back(indicies[pair.first+num]);\n        }\n    }\n\n    return results;\n}\n\n\nint main(int argc, char* argv[])\n{\n    const int count = atoi(argv[1]);\n    const int dimension = atoi(argv[2]);\n    const float calibration = atof(argv[3]);\n\n    std::vector<point> points;\n    point temp;\n\n    for (int i = 0; i < count; ++i) {\n        temp.clear();\n        for (int j = 0; j < dimension; ++j) {\n            temp.emplace_back(atof(argv[i*dimension + j + 4]));\n        }\n        points.emplace_back(temp);\n    }\n\n    std::vector<int> indicies = travels(points, calibration);\n\n    std::cout << indicies[0];\n    for (int i = 1; i < indicies.size(); ++i) {\n        std::cout << \" \" << indicies[i];\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "5fa93fe505f4fdccaa0e60ca75933418ea8a63b0", "size": 5317, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/algorithm.cc", "max_stars_repo_name": "chrismalcolm/travelers", "max_stars_repo_head_hexsha": "919c1558432fe1aeee28831be7c69ec34ff0ac86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm.cc", "max_issues_repo_name": "chrismalcolm/travelers", "max_issues_repo_head_hexsha": "919c1558432fe1aeee28831be7c69ec34ff0ac86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm.cc", "max_forks_repo_name": "chrismalcolm/travelers", "max_forks_repo_head_hexsha": "919c1558432fe1aeee28831be7c69ec34ff0ac86", "max_forks_repo_licenses": ["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.585, "max_line_length": 80, "alphanum_fraction": 0.6309949219, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.563131262517408}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <regex>\n#include <optional>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::int128_t;\n\nstruct Cube {\n    Cube(int128_t x1, int128_t x2, int128_t y1, int128_t y2, int128_t z1, int128_t z2) :\n        x1(x1), x2(x2), y1(y1), y2(y2), z1(z1), z2(z2) {\n        assert(x2 >= x1);\n        assert(y2 >= y1);\n        assert(z2 >= z1);\n    }\n\n    auto operator<=>(Cube const& rhs) const = default;\n\n    bool exceedsLimit(int128_t limit) const {\n        if (abs(x1) > limit || abs(x2) > limit || abs(y1) > limit || abs(y2) > limit || abs(z1) > limit || abs(z2) > limit)\n            return true;\n        return false;\n    }\n\n    int128_t Size() const {\n        return (1+x2-x1) * (1+y2-y1) * (1+z2-z1);\n    }\n\n    std::optional<Cube> Intersects(const Cube& cube) const;\n\n    int128_t x1;\n    int128_t x2;\n    int128_t y1;\n    int128_t y2;\n    int128_t z1;\n    int128_t z2;\n};\n\nstd::ostream& operator<<(std::ostream& os, const Cube& cube) {\n    os << \"(\" << cube.x1 << \" \" << cube.x2 << \" \" << cube.y1 << \" \" << cube.y2 << \" \" << cube.z1 << \" \" << cube.z2 << \")\\n\";\n    return os;\n}\n\nstd::optional<Cube> Cube::Intersects(const Cube& cube) const {\n    std::optional<Cube> result;\n    int128_t xx1 = std::max(x1, cube.x1);\n    int128_t xx2 = std::min(x2, cube.x2);\n    int128_t yy1 = std::max(y1, cube.y1);\n    int128_t yy2 = std::min(y2, cube.y2);\n    int128_t zz1 = std::max(z1, cube.z1);\n    int128_t zz2 = std::min(z2, cube.z2);\n    if (xx2 >= xx1 && yy2 >= yy1 && zz2 >= zz1) {\n        result = Cube(xx1, xx2, yy1, yy2, zz1, zz2);\n    }\n    return result;\n}\n\nclass Reactor {\npublic:\n    Reactor() {};\n    Reactor(const std::optional<int128_t>& limit) : limit_(limit) {};\n\n    void on(const Cube& cube);\n    void off(const Cube& cube);\n\n    int128_t count();\n\nprivate:\n    std::optional<int128_t> limit_;\n    std::vector<Cube> state_;\n};\n\nint128_t Reactor::count() {\n    int128_t total = 0;\n    for (auto cube : state_) {\n        total += cube.Size();\n    }\n    return total;\n}\n\nvoid Reactor::on(const Cube& cube) {\n    if (limit_.has_value() && cube.exceedsLimit(limit_.value()))\n        return;\n    off(cube);\n    state_.emplace_back(cube);\n}\n\nvoid Reactor::off(const Cube& cube) {\n    if (limit_.has_value() && cube.exceedsLimit(limit_.value()))\n        return;\n\n    std::vector<Cube> new_state;\n    for (auto& a : state_) {\n        auto intersect = cube.Intersects(a);\n        if (intersect.has_value()) {\n            {\n                int128_t x1 = a.x1;\n                int128_t x2 = intersect.value().x1 - 1;\n                if (x1 <= x2)\n                    new_state.emplace_back(x1, x2, a.y1, a.y2, a.z1, a.z2);\n            }\n            {\n                int128_t x1 = intersect.value().x2 + 1;\n                int128_t x2 = a.x2;\n                if (x1 <= x2)\n                    new_state.emplace_back(x1, x2, a.y1, a.y2, a.z1, a.z2);\n            }\n\n            {\n                int128_t y1 = a.y1;\n                int128_t y2 = intersect.value().y1 - 1;\n                if (y1 <= y2)\n                    new_state.emplace_back(intersect.value().x1, intersect.value().x2, y1, y2, a.z1, a.z2);\n            }\n            {\n                int128_t y1 = intersect.value().y2 + 1;\n                int128_t y2 = a.y2;\n                if (y1 <= y2)\n                    new_state.emplace_back(intersect.value().x1, intersect.value().x2, y1, y2, a.z1, a.z2);\n            }\n\n            {\n                int128_t z1 = a.z1;\n                int128_t z2 = intersect.value().z1 - 1;\n                if (z1 <= z2)\n                    new_state.emplace_back(intersect.value().x1, intersect.value().x2, intersect.value().y1, intersect.value().y2, z1, z2);\n            }\n            {\n                int128_t z1 = intersect.value().z2 + 1;\n                int128_t z2 = a.z2;\n                if (z1 <= z2)\n                    new_state.emplace_back(intersect.value().x1, intersect.value().x2, intersect.value().y1, intersect.value().y2, z1, z2);\n            }\n\n        } else {\n            new_state.emplace_back(a);\n        }\n    }\n\n    state_ = std::move(new_state);\n}\n\nint main(int argc, char** argv) {\n\n    std::vector<std::string> lines;\n    while (!std::cin.eof() && !std::cin.fail()) {\n        std::string line;\n        getline(std::cin, line);\n        lines.push_back(line);\n    }\n\n    Reactor part_1(50);\n    Reactor part_2;\n\n    for (auto& line : lines) {\n        const std::regex reg(\"(on|off) x=(-?\\\\d*)..(-?\\\\d*),y=(-?\\\\d*)..(-?\\\\d*),z=(-?\\\\d*)..(-?\\\\d*)\");\n        std::smatch match;\n        if (regex_search(line, match, reg)) {\n            bool on = match.str(1) == \"on\";\n            int128_t x1 = stoi(match.str(2));\n            int128_t x2 = stoi(match.str(3));\n            int128_t y1 = stoi(match.str(4));\n            int128_t y2 = stoi(match.str(5));\n            int128_t z1 = stoi(match.str(6));\n            int128_t z2 = stoi(match.str(7));\n            Cube cube(x1, x2, y1, y2, z1, z2);\n            if (on) {\n                part_1.on(cube);\n                part_2.on(cube);\n            } else {\n                part_1.off(cube);\n                part_2.off(cube);\n            }\n        }\n    }\n\n    std::cout << part_1.count() << std::endl;\n    std::cout << part_2.count() << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "638d38e313623c7196f3f0cb808fb43f2c62e38c", "size": 5307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2021/day_22/day_22.cpp", "max_stars_repo_name": "andrewparr/advent-of-code", "max_stars_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021/day_22/day_22.cpp", "max_issues_repo_name": "andrewparr/advent-of-code", "max_issues_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021/day_22/day_22.cpp", "max_forks_repo_name": "andrewparr/advent-of-code", "max_forks_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "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.0, "max_line_length": 139, "alphanum_fraction": 0.5021669493, "num_tokens": 1593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5631025058719281}}
{"text": "// Ben Martin\n// January 31, 2006\n\n// This currently works only on undirected graphs...\n// Graph must model Adjacency Graph, Incidence Graph, VertexListGraph\n\n#ifndef BOOST_GRAPH_SPARSE_SPECTRUM_HPP\n#define BOOST_GRAPH_SPARSE_SPECTRUM_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/vector_property_map.hpp>\n#include <utility> // for pair\n\n//#include <iostream.h>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <ietl/vectorspace.h>\n#include <ietl/lanczos.h>\n#include <ietl/iteration.h>\n#include <boost/random/linear_congruential.hpp>\n#include <ietl/interface/ublas.h>\n\ntypedef long int integer;\ntypedef double doublereal;\n\nnamespace boost {\n\n  template <typename Graph, typename EigenvectorMatrix >\n  void sparse_spectrum(Graph& g, \n\t\t       int first_eigenvector_index,\n\t\t       int num_eigenvectors,\n\t\t       EigenvectorMatrix &eigenvectors,\n\t\t       double rel_tol = 100, \n\t\t       double abs_tol = 1000) \n  {\n    std::vector<double> evals(num_eigenvectors);\n    sparse_spectrum(g, first_eigenvector_index, num_eigenvectors, eigenvectors, evals, rel_tol, abs_tol);\n  }\n\n  // Parameters:\n  //   first_eigenvector_index:\n  //     Since the smallest eigenvector is not useful, often this will \n  //       be set to 1, for the \"Fiedler vector,\" though if all \n  //       eigenvectors are desired, 0 may be a more logical value.\n  //     Negative values are interpreted as allowing a default choice of 1.\n  //   num_eigenvectors:\n  //     The number of eigencectors to return.\n\n  template <typename Graph, typename EigenvectorMatrix, typename EVector >\n  void sparse_spectrum(Graph& g, \n\t\t       int first_eigenvector_index,\n\t\t       int num_eigenvectors,\n\t\t       EigenvectorMatrix &eigenvectors,\n\t\t       EVector &eigenalues,\n\t\t       double rel_tol = 100, \n\t\t       double abs_tol = 1000) \n  {\n\n    //    Matrix eigenvectors = *(in_eigenvectors);\n\n    if (first_eigenvector_index < 0)\n      first_eigenvector_index = 1;\n    \n    typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap;\n    typedef typename Graph::vertex_iterator VertexIterator;\n    typedef typename Graph::edge_iterator EdgeIterator;\n    typedef typename boost::graph_traits<Graph>::adjacency_iterator AdjacencyIterator;\n    \n    IndexMap index_map = get(vertex_index, g);\n\n    VertexIterator v, vs, ve;\n    using std::pair;\n    std::pair<VertexIterator, VertexIterator> p;\n    p = vertices(g);\n    vs = p.first;\n    ve = p.second;\n\n    EdgeIterator e, es, ee;\n    using std::pair;\n    std::pair<EdgeIterator, EdgeIterator> ep;\n    ep = edges(g);\n    es = ep.first;\n    ee = ep.second;\n    typename Graph::vertex_descriptor src, tgt;\n    \n    integer N = num_vertices(g);\n\n    typedef boost::numeric::ublas::compressed_matrix<double> Matrix;\n    Matrix A(N, N);\n    \n    int i;\n    \n    AdjacencyIterator a, as, ae;\n    std::pair<AdjacencyIterator, AdjacencyIterator> ap;\n    \n    /*\n    for (v = vs; v != ve; ++v) {\n      A(index_map[*v], index_map[*v]) = (double)out_degree(*v, g);\n    }\n    */\n    for (e = es; e != ee; ++e) {\n      src = source(*e, g);\n      tgt = target(*e, g);\n      if (src != tgt && A(index_map[src], index_map[tgt]) != -1) {\n\tA(index_map[src], index_map[tgt]) = (double)(-1);\n\tA(index_map[tgt], index_map[src]) = (double)(-1);\n\tA(index_map[src], index_map[src]) += (double)1;\n\tA(index_map[tgt], index_map[tgt]) += (double)1;\n      }\n    }\n\n    /*\n    cout << \"index_map = \" << endl;\n    for (v = vs; v != ve; ++v) {\n      cout << index_map[*v] << \" \";\n    }\n    cout << endl;\n    cout << \"A = \" << endl;\n    for (i = 0; i < N; i++)\n    {\n      for (int j = 0; j < N; j++)\n      {\n        cout << A[i*N + j] << \" \";\n      }\n        cout << endl;\n    }\n    */\n\n    using namespace ietl;\n\n    vectorspace<boost::numeric::ublas::vector<double> > VS(N);\n    lanczos<Matrix, vectorspace<boost::numeric::ublas::vector<double> > > LanczosObject(A, VS);\n    \n    double _rel_tol = 1000.*std::numeric_limits<double>::epsilon();\n    double _abs_tol = 10000.*std::numeric_limits<double>::epsilon();\n    \n    //    _rel_tol = 100.*std::numeric_limits<double>::epsilon();\n    //    _abs_tol = 100.*std::numeric_limits<double>::epsilon();\n\n    // SO far these are the best I have found:\n    //    _rel_tol = 1000.*std::numeric_limits<double>::epsilon();\n    //    _abs_tol = 10000.*std::numeric_limits<double>::epsilon();\n\n    _rel_tol = rel_tol*std::numeric_limits<double>::epsilon();\n    _abs_tol = abs_tol*std::numeric_limits<double>::epsilon();\n\n\n    lanczos_iteration_nlowest<double> LanczosIterationControl(1000000, first_eigenvector_index + num_eigenvectors, _rel_tol, _abs_tol);\n    //    std::cout << std::numeric_limits<double>::epsilon() << std::endl;\n    boost::minstd_rand gen(1);\n    //boost::rand48 gen(1);\n    LanczosObject.calculate_eigenvalues(LanczosIterationControl, gen);\n    std::vector<double> evals = LanczosObject.eigenvalues();\n\n    //    for (int i = 0; i < N; i++)\n    //      std::cout << evals[i] << \" \";\n    //    std::cout << std::endl;\n\n    /*\n    std::vector<int> multiplicities = LanczosObject.multiplicities();\n    int lowest_eval_multiplicity = multiplicities[1];\n    int second_eval_multiplicity;\n    if (lowest_eval_multiplicity == 1 && multiplicities[2] > 1)\n      second_eval_multiplicity = 2;\n    else\n      second_eval_multiplicity = 1;\n\n    for (int i = 0; i < N; i++)\n      std::cout << multiplicities[i] << \" \";\n    std::cout << std::endl;\n    */\n\n    std::vector<boost::numeric::ublas::vector<double> > evecs(num_eigenvectors);\n    for (int j = 0; j < num_eigenvectors; j++)\n      evecs[j] = *(new boost::numeric::ublas::vector<double>(N));\n    std::vector<boost::numeric::ublas::vector<double> >::iterator out_it = evecs.begin();\n    \n    Info<double> info;\n    std::vector<double>::iterator ebegin, eend;\n    ebegin = evals.begin();\n    ebegin += first_eigenvector_index;\n    eend = evals.begin();\n    //    eend += 4 + (1 - lowest_eval_multiplicity) + (1 - second_eval_multiplicity);\n    eend += first_eigenvector_index + num_eigenvectors;\n    LanczosObject.eigenvectors(ebegin, eend, out_it, info, gen, 100000);\n    //    LanczosObject.eigenvectors(ebegin, eend, out_it, info, gen);\n\n    /*\n    // If eigenvalues are repeated, we need to copy eigenvectors\n    if (lowest_eval_multiplicity > 1) {\n      for (int i = 0; i < N; i++)\n\tevecs[1][i] = evecs[0][i];\n      if (lowest_eval_multiplicity > 2) {\n\tfor(int i = 0; i < N; i++)\n\t  evecs[2][i] = evecs[0][i];\n      }\n    }\n    if (second_eval_multiplicity > 1) {\n      for (int i = 0; i < N; i++)\n\tevecs[2][i] = evecs[1][i];\n    }\n    */\n\n    //    for (int i = 0; i < 3; i++)\n    //      for (int j = 0; j < N; j++)\n    //\tstd::cout << evecs[i][j] << \" \";\n    //    cout << std::endl;\n    \n    //    std::cout << A << std::endl;\n    //    std::cout << LanczosIterationControl.error_code() << endl;;\n    //    std::cout << info.error_info(1) << \" \" << info.error_info(2) << \" \" << info.error_info(3) << std::endl;\n\n    //    std::vector<Vector> retval(num_eigenvectors);\n    for (int j = 0; j < num_eigenvectors; j++) {\n      // retval[j] = *(new Vector(N));\n      i = 0;\n      for (v = vs; v != ve; ++v) {\n\t//\t  retval[j][i] = evecs[first_eigenvector_index+j-1][i];\n\teigenvectors[j][i] = evecs[first_eigenvector_index+j-1][i];\n\t\n\ti++;\n      }\n    }\n\n    //    return retval;\n    \n  } // end spectrum()\n  \n} // end namespace boost\n\n#endif // BOOST_GRAPH_SPARSE_SPECTRUM_HPP\n\n", "meta": {"hexsha": "e8d54f27e5f6378ac0f8ba5d495b413278ca5da0", "size": 7662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/sparse_spectrum.hpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "boost/graph/sparse_spectrum.hpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/sparse_spectrum.hpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 32.0585774059, "max_line_length": 135, "alphanum_fraction": 0.6262072566, "num_tokens": 2219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.5630805475032575}}
{"text": "#include <Rcpp.h>\r\n#include <RcppEigen.h>\r\n#include <Eigen/Dense>\r\n#include <queue>\r\n// #include<Eigen/SparseCore>\r\nusing namespace Rcpp;\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n\r\n// [[Rcpp::depends(RcppEigen)]]\r\n\r\n//\r\nusing Eigen::Map;               \t// 'maps' rather than copies\r\nusing Eigen::Matrix;                  //  matrix generic\r\nusing Eigen::MatrixXd;                  // variable size matrix, double precision\r\nusing Eigen::VectorXd;                  // variable size vector, double precision\r\nusing Eigen::Transpositions;\r\nusing Eigen::HouseholderQR;    // Fast scalable QR solver\r\nusing Eigen::ColPivHouseholderQR;    // Fast scalable QR solver\r\nusing Eigen::FullPivHouseholderQR; // slow full (colsand rows pivoting) \r\nusing Eigen::JacobiSVD;\r\nusing Eigen::GeneralizedSelfAdjointEigenSolver;    // one of the eigenvalue solvers\r\nusing Eigen::SelfAdjointEigenSolver;    // one of the eigenvalue solvers\r\nusing Eigen::LLT;\r\nusing Eigen::LDLT;\r\nusing Rcpp::List;\r\nusing Rcpp::wrap;\r\n\r\n\r\n// ##########  OK vrsione Sept 04 works\r\n\r\n// copied to fspca_sept.cpp\r\n\r\n// =========================================================================\r\n\r\n\r\n\r\n// creates a sub-mat of S with indices in e base 0\r\nEigen::MatrixXd makeSubS(Eigen::MatrixXd S, Eigen::VectorXi e){\r\n  int n = S.cols();\r\n  int r = S.rows();\r\n  int d = e.size();\r\n  if (d >= n) {\r\n    Rf_error(\"Too many indices to eliminate.\\n\");\r\n  }\r\n  if (e.maxCoeff() > n){\r\n    Rf_error(\"largest index greater than the number of columns.\\n\");\r\n  }\r\n  \r\n  Eigen::MatrixXd M(r, d );  \r\n  for (int i = 0; i < d; ++i){\r\n    M.col(i) = S.col(e(i));\r\n  }\r\n  for (int i = 0; i < d; ++i){\r\n    M.row(i) = M.row(e(i));\r\n  }\r\n  \r\n  return M.topLeftCorner(d, d);\r\n} \r\n\r\n// retruns the rows in e and keeps first c columns\r\nEigen::MatrixXd selectRowsC(Eigen::MatrixXd A, Eigen::VectorXi e, int c){\r\n  // ATTENZIONE INDICES BASE 0\r\n  // ATTENZIONE e must be sorted e(0) < e(1)\r\n  \r\n  int n = A.cols();\r\n  int r = A.rows();\r\n  int d = e.size();\r\n  if (d >= n) {\r\n    Rf_error(\"Too many indices to eliminate.\\n\");\r\n  }\r\n  if (e.maxCoeff() > n){\r\n    Rf_error(\"largest index greater than the number of columns.\\n\");\r\n  }\r\n  \r\n  Eigen::MatrixXd M(A.topLeftCorner(r,c));   \r\n  for (int i = 0; i < d; ++i){\r\n    M.row(i) = M.row(e(i));\r\n  }\r\n  \r\n  return M.topLeftCorner(d, c);\r\n} \r\n\r\nvoid   makeSdAndM(Eigen::MatrixXd S, Eigen::VectorXi e, Eigen::MatrixXd& M, Eigen::MatrixXd& N,\r\n                  int n, int d){\r\n  // M(d, r) N(d, d)\r\n  if (d >= n) {\r\n    Rf_error(\"Too many indices to eliminate.\\n\");\r\n  }\r\n  if (e.maxCoeff() > n){\r\n    Rf_error(\"largest index greater than the number of columns.\\n\");\r\n  }\r\n  \r\n  //  Eigen::MatrixXd M(d, r);  \r\n  for (int i = 0; i < d; ++i){\r\n    M.row(i) = S.row(e(i));\r\n  }  \r\n  //  Eigen::MatrixXd N = M.topLeftCorner(d, d);  \r\n  for (int i = 0; i < d; ++i){\r\n    N.col(i) = M.col(e(i));\r\n  }\r\n} \r\n\r\n// Deflates S (pass already deflated and vector current loads)\r\n// returns vexp by ref\r\nvoid deflSC(Eigen::VectorXd a, Eigen::MatrixXd& K, Eigen::VectorXi ind, double& vexp){\r\n  // # pass only a nonzero loads\r\n  // K = deflated matrix\r\n  // #  K <-- (S - Saa'S/(a'Sa) // deflated S matrix\r\n  // ## ===\r\n  const int n = ind.size();\r\n  const int p = K.cols();\r\n  \r\n  // t = Sa\r\n  Eigen::VectorXd t = Eigen::VectorXd::Zero(p); \r\n  for (int i = 0; i < p; i++)\r\n    for(int k = 0; k < n; k++) \r\n      t(i) += K(i, ind(k)) * a(k ); // only elements in ind\r\n  // tt = a'Sa = t'a\r\n  \r\n  double tt = 0.0; \r\n  for(int k = 0; k < n; k++)\r\n    tt += a(k) * t(ind(k));\r\n  if (tt > 0)\r\n    tt = 1/tt;\r\n  else\r\n    Rf_error(\"defSC: tt is not > 0\");\r\n  \r\n  // O = Sa/(tt)\r\n  const Eigen::VectorXd O = (t.array()*tt).matrix();\r\n  \r\n  const double cvk = K.trace();\r\n  // K = S - Saa'S/(a'Sa) deflated S\r\n  Eigen::MatrixXd L = t * O.transpose();\r\n  K = K - t * O.transpose(); //deflated S\r\n  vexp =  cvk - K.trace() ;\r\n  \r\n  return;\r\n}  \r\n//\r\n\r\n\r\n\r\n// finds max part corr exclude small ss, pdates indnot returns ind\r\nint findmax(Eigen::VectorXi& indnot, Eigen::VectorXd vt){\r\n  \r\n  double p = indnot.size();\r\n  double m = 0.0;\r\n  int ind = 0;\r\n  for (int i = 0; i < p; i++){\r\n    if (indnot(i) == -2){\r\n      if(vt(i) > m){\r\n        m = vt(i);\r\n        ind = i;\r\n      }\r\n    }\r\n  }\r\n  indnot(ind) = ind;\r\n  return ind;  \r\n}\r\n\r\n// indnot could be used for extracting the indices later, so use -2, -1 and {0:(p-1)}\r\n// fixed\r\nvoid fwd_selectC(Eigen::MatrixXd S, Eigen::VectorXi& ind, int& card,\r\n                 Eigen::VectorXd si, double totvexp, double pvexp,\r\n                 double fullrank = 0.0){ \r\n  Eigen::VectorXd sik = si;\r\n  int p = S.cols();\r\n  // int induno;\r\n  double tmp; \r\n  Eigen::VectorXd vexpt(p);\r\n  Eigen::VectorXd cvexpt(p);\r\n  Eigen::VectorXd vt(p);\r\n  Eigen::VectorXi indnot = Eigen::VectorXi::Constant(p, -2);\r\n  Eigen::VectorXd ba(p);\r\n  \r\n  for (int i=0; i < p; i++)\r\n    vt(i) = sik(i) * sik(i) / S(i,i);\r\n  \r\n  ind(0) = findmax(indnot, vt);\r\n  \r\n  vexpt(0) = vt(ind(0));\r\n  cvexpt(0) = vt(ind(0));\r\n  int i = 1;\r\n  bool stopSelect = false;\r\n  // start looping ============================================  \r\n  while (stopSelect == false){\r\n    \r\n    tmp = sik(ind(i - 1))/S(ind(i - 1), ind(i - 1));\r\n    for (int j = 0; j < p; j++){\r\n      if ( indnot(j) == -2){\r\n        sik(j) = sik(j) -  (tmp * S(ind(i-1), j));\r\n      }   \r\n      else{\r\n        sik(j) = 0;\r\n      } \r\n    }  \r\n    \r\n    ba = (S.col(ind(i-1)).array()/sqrt(S(ind(i-1), ind(i-1)))).matrix();\r\n    S = S - ba * ba.transpose();\r\n    \r\n    for (int j = 0; j < p; j++){\r\n      if ( indnot(j) == -2){\r\n        if (S(j,j)> fullrank)\r\n          vt(j) = sik(j) * sik(j)/S(j,j);\r\n        else{\r\n          indnot(j) = -1;\r\n          vt(j) = 0;\r\n        }\r\n      }\r\n      else{\r\n        vt(j) = 0;\r\n      }\r\n    }\r\n    \r\n    ind(i) = findmax(indnot, vt);\r\n    indnot(ind(i)) = 0;\r\n    \r\n    vexpt(i) =  vt(ind(i));\r\n    cvexpt(i) = cvexpt(i-1) + vexpt(i);\r\n    \r\n    if (cvexpt(i) >= pvexp*totvexp){\r\n      card = i + 1;\r\n      stopSelect = true;\r\n    }\r\n    else{\r\n      i = i + 1;\r\n    }\r\n    //    Rcpp::checkUserInterrupt();\r\n    \r\n  }  \r\n}\r\n\r\n// power method computes only first eigvec, about 82 times faster tha eigen!\r\nEigen::VectorXd eigvecPMC(Eigen::MatrixXd& X, double& val, double eps = 10E-5){\r\n  const int p = X.cols();\r\n  double sqp = sqrt(double(p));\r\n  Eigen::VectorXd v0 = VectorXd::Constant(p, 1.0/sqp);\r\n  Eigen::VectorXd v = VectorXd::Constant(p, 0.0);\r\n  double stp = 1.0;\r\n  int k = 0;\r\n  while (stp > eps){\r\n    v = X * v0;\r\n    val = v.norm();\r\n    v = v.array()/val;\r\n    stp = (v0.array() - v.array()).matrix().norm();\r\n    v0 = v;\r\n    k++;\r\n    if (k > 100){\r\n      Rf_warning(\"Powermethod: not converged in 100 iterations. Error is\", k);\r\n      break;//here should use try-catch  \r\n    }  \r\n  }\r\n  //  Rcout << \"k = \" << k << \"; stp = \" << stp << endl;\r\n  return (v.array() * val);  \r\n}\r\n\r\n// This is the main function for R\r\n// S correl matrix\r\n// pvexpfs is proportion of PC to explain by each block\r\n// pvexp is proportion total variance of matrix to explain to terminate computing comps\r\n// ncomps nistead of pvexp maximum number of comps (priority)\r\n// full rank small eps to discard vars from selection\r\n// simply projects current full rank PC onto set of variables in ind\r\n// it does not compute the LS SPCA components, it seems to work as well as that\r\n// uses power method to compute PCs\r\n// new version reduces K and S in one function (+6% ) < check cost of resizing\r\n// [[Rcpp::export]]\r\nList fspcaCpmNoe(Eigen::MatrixXd S, double pvexpfs = 0.95, double pvexp = 0.95, \r\n               int ncomps = 0, double fullrank = 0,  double eps = 10E-5){\r\n  int p = S.cols();\r\n  if (ncomps == 0)\r\n    ncomps = p;\r\n  Eigen::MatrixXd K(S);\r\n\r\n  double totvexp = S.trace();// total variance S\r\n  double maxvexp;// this is vexp by first PC for fow_select\r\n  \r\n  Eigen::VectorXd si(p); \r\n\r\n  si = eigvecPMC(S, maxvexp);\r\n//Rcout << \"done si first \" << endl;\r\n  // here could compute D as   vec * diag(val^2) * vec.transpose \r\n  \r\n  Eigen::MatrixXd Sinv(p, p);\r\n  Eigen::MatrixXd M(p, p);\r\n  \r\n  \r\n  Eigen::VectorXd a(p);\r\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(p, ncomps);\r\n  //  List load(p);\r\n  List indout(p);\r\n  \r\n  Eigen::VectorXd vexp = Eigen::VectorXd::Zero(ncomps);\r\n  Eigen::VectorXd cvexp = vexp;\r\n  double cvt;\r\n  Eigen::VectorXi indj(p);//this to pass to fwd_select \r\n  \r\n  Eigen::MatrixXd Sd(p, p);// maybe better leave dynamic? this takes S[onlyind, onlyind]\r\n\r\n  int cardt = 0;\r\n  Eigen::VectorXi card(p); \r\n  int nc = 0;   \r\n  bool stopComp = false;\r\n  \r\n  int j = 0;\r\n  while (stopComp == false){\r\n    fwd_selectC(S, indj, cardt, si, maxvexp, pvexpfs, fullrank);\r\n//Rcout << \"comp \"<< j + 1 << \"done fwd_swlwct \" << endl;\r\n    \r\n    card(j) = cardt;\r\n    std::sort(indj.data(),indj.data() + cardt);\r\n\r\n    // if ( j == 2)\r\n    //   Rf_error(\"done 1\");  \r\n    \r\n\r\n    // need make one function that does bot Sd and M\r\n    // create submatrices for computing loaidngs \r\n    \r\n    Sd.resize(cardt, cardt);\r\n    M.resize(cardt, NoChange);\r\n    makeSdAndM(S, indj.head(cardt), M, Sd, p,cardt);\r\n//    Sd.topLeftCorner(cardt, cardt) = makeSubS(S, indj.head(cardt));\r\n//    M.topLeftCorner(cardt, p) = selectRowsC(K, indj.head(cardt), p);\r\n//Rcout << \"comp \"<< j + 1 << \"done selectRows\" << endl;    \r\n\r\n    //  compute loadings        \r\n  //  Sinv.topLeftCorner(cardt, cardt)  = Sd.topLeftCorner(cardt, cardt).llt().solve(MatrixXd::Identity(cardt, cardt));\r\n    Sinv.topLeftCorner(cardt, cardt)  = Sd.llt().solve(MatrixXd::Identity(cardt, cardt));\r\n    //Rcout << \"comp \"<< j + 1 << \"done Sinv\" << endl;    \r\n    \r\n    // save loadings \r\n    a.head(cardt) = ((Sinv.topLeftCorner(cardt, cardt) * M * si).array() / maxvexp).matrix();\r\n//Rcout << \"comp \"<< j + 1 << \"done loadings\" << endl;    \r\n    // save loadings in column j\r\n    for (int i = 0; i < cardt; i++){\r\n      A(indj(i), j) = a(i);\r\n    }\r\n    // save loadings in list\r\n    indout[j] = indj.head(cardt).array() + 1;\r\n\r\n    nc = nc + 1;\r\n    \r\n    \r\n    // this new func deflates S and D using only last vector of loads\r\n    // returns deflated matr by references and vexp (not cum vexp)\r\n    deflSC(a.head(cardt), K, indj.head(cardt), cvt);\r\n//Rcout << \"comp \"<< j + 1 << \"done deflSC\" << endl;    \r\n    \r\n    vexp(j) = cvt;\r\n    if (j > 0)\r\n      cvexp(j) = cvt + cvexp(j-1);\r\n    else\r\n      cvexp(j) = cvt;\r\n\r\n    // checks if stopComp met\r\n    if ((cvexp(j) > pvexp * totvexp) || ((j + 1) == ncomps)){\r\n      stopComp = true;\r\n      ncomps = nc;\r\n    }\r\n    else{\r\n      // this power method, returns si and passes maxvexp byref\r\n      si = eigvecPMC(K, maxvexp);\r\n//Rcout << \"comp \"<< j + 1 << \"done si\" << endl;    \r\n      \r\n      j = j + 1;\r\n    }\r\n  }//end compute comps\r\n  \r\n  IntegerVector idx = Rcpp::seq(0, nc - 1);\r\n\r\n  return  List::create(Named(\"loadings\") = A.topLeftCorner(p,nc), Named(\"ncomps\") = nc, \r\n                       Named(\"ind\") = indout[idx], Named(\"card\") = card.head(nc), \r\n                       Named(\"vexp\") = vexp.head(nc), Named(\"cvexp\") = cvexp.head(nc));\r\n} ", "meta": {"hexsha": "1e6be04b1e0cafe4169130e080a34272c600a29c", "size": 11058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fspcaC_NOgenEigen_sept._v2.cpp", "max_stars_repo_name": "denis-rinfret/gioden", "max_stars_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fspcaC_NOgenEigen_sept._v2.cpp", "max_issues_repo_name": "denis-rinfret/gioden", "max_issues_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fspcaC_NOgenEigen_sept._v2.cpp", "max_forks_repo_name": "denis-rinfret/gioden", "max_forks_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_forks_repo_licenses": ["Apache-2.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.3315649867, "max_line_length": 120, "alphanum_fraction": 0.5396093326, "num_tokens": 3469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5630411355732132}}
{"text": "#ifndef _OPT_PLACEMENT_HPP_\n#define _OPT_PLACEMENT_HPP_\n\n\n//#include <boost/graph/graph_traits.hpp>\n//#include <boost/graph/adjacency_list.hpp>\n//#include <boost/graph/graphviz.hpp>\n//#include <boost/graph/iteration_macros.hpp>\n//#include <boost/foreach.hpp>\n//#include <Eigen/Core>\n//#include <Eigen/LU>\n//#include \"mod2.hpp\"\n#include <modularity.hpp>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_blas.h>\n\nnamespace opt_placement\n{\n\n  inline gsl_matrix* _laplacian(const Cppn* g, const std::set<Node*>& verts)\n  {\n\t  gsl_matrix* l = gsl_matrix_calloc (g->getNrOfNodes(), g->getNrOfNodes());\n\n\t  size_t i = 0;\n\t  foreach(Node* node1, g->getNodes()){\n\t\t  \tsize_t j = 0;\n\t\t    foreach(Node* node2, g->getNodes()){\n\t\t    \tif (verts.find(node1) == verts.end()|| verts.find(node2) == verts.end()){\n\t\t    \t\tgsl_matrix_set(l, i,j,0.0);\n\t\t    \t} else if (i == j){\n\t\t    \t\tgsl_matrix_set(l, i,j,node1->incomingEdges().count() + node1->outgoingEdges().count());\n\t\t    \t} else if (mod::_linked(node1, node2) || mod::_linked(node2, node1)){\n\t\t    \t\tgsl_matrix_set(l, i,j,-1.0);\n\t\t    \t} else {\n\t\t    \t\tgsl_matrix_set(l, i,j,0.0);\n\t\t    \t}\n\t\t    \t++j;\n\t\t    }\n\t\t    ++i;\n\t  }\n\n\t  return l;\n  }\n\n   // include in the adjacency iff source _or_ target is in verts\n  inline gsl_matrix* _adjacency(const Cppn* g, const std::set<Node*>& verts)\n  {\n\t  gsl_matrix* a = gsl_matrix_calloc (g->getNrOfNodes(), g->getNrOfNodes());\n\n\t  size_t i = 0;\n\t  foreach(Node* node1, g->getNodes()){\n\t\t  \tsize_t j = 0;\n\t\t    foreach(Node* node2, g->getNodes()){\n\t\t\t\t  if ((verts.find(node1) != verts.end() || verts.find(node2) != verts.end()) && (mod::_linked(node1, node2) || mod::_linked(node2, node1)))\n\t\t\t\t\t  gsl_matrix_set(a, i,j,1.0);\n\t\t\t\t  else\n\t\t\t\t\t  gsl_matrix_set(a, i,j,0.0);\n\n\t\t    \t++j;\n\t\t    }\n\t\t    ++i;\n\t  }\n\n\t  return a;\n  }\n\n   // include in the degree matrix iff vertex is in verts\n  inline gsl_matrix* _degree(const Cppn* g, const std::set<Node*>& verts)\n  {\n\t  gsl_matrix* d = gsl_matrix_calloc (g->getNrOfNodes(), g->getNrOfNodes());\n\n\t  size_t i = 0;\n\t  foreach(Node* node1, g->getNodes()){\n\t\t  if (verts.find(node1) != verts.end())\n\t\t\t  gsl_matrix_set(d, i,i,node1->incomingEdges().count() + node1->outgoingEdges().count());\n\n\t\t  ++i;\n\t  }\n\t  return d;\n  }\n\n\n  template<typename V, typename T>\n  inline int _find_index(const V& vect, const T& e)\n  {\n    for (int i = 0; i < vect.size(); ++i)\n      if (e == vect[i]){\n//    \t  std::cout << i << std::endl;\n          return i;\n      }\n\n    return -1;\n  }\n\n\n\n  inline gsl_vector* _f(const Cppn* g,\n\t\t  const QList<Node*>& inputs,\n\t\t  const QVector<double>& coords_inputs,\n\t\t  const QList<Node*>& outputs,\n\t\t  const QVector<double>& coords_outputs)\n  {\n\t  gsl_vector* f = gsl_vector_calloc(g->getNrOfNodes());\n\n\n\t  size_t i = 0;\n\n\n\t  foreach(Node* node1, g->getNodes()){\n\t\t  int in = _find_index(inputs, node1);\n\t\t  if (in != -1){\n\t\t  \t  gsl_vector_set(f, i, coords_inputs[in]);\n\t\t  }\n\t\t  int out = _find_index(outputs, node1);\n\t\t  if (out != -1){\n\t\t  \t  gsl_vector_set(f, i, coords_outputs[out]);\n\t\t  }\n\t\t  ++i;\n\t  }\n\n\t  return f;\n  }\n\n\n  inline QVector<double> compute(const Cppn* g,\n                                 const QList<Node*>& inputs,\n                                 const QVector<double>& coords_inputs,\n                                 const QList<Node*>& outputs,\n                                 const QVector<double>& coords_outputs)\n  {\n    typedef Node* v_d_t;\n    std::set<v_d_t> all_set, io_set, no_io_set;\n\n    foreach(Node* node1, g->getNodes()) all_set.insert(node1);\n    foreach(Node* node, inputs) io_set.insert(node);\n    foreach(Node* node, outputs) io_set.insert(node);\n\n\n    std::set_difference(all_set.begin(), all_set.end(),\n                        io_set.begin(), io_set.end(),\n                        std::insert_iterator<std::set<v_d_t> >(no_io_set,\n                                                               no_io_set.begin()));\n    gsl_matrix* l = _laplacian(g, no_io_set);\n    gsl_matrix* b = _adjacency(g, io_set);\n    gsl_matrix* d = _degree(g, io_set);\n    gsl_vector* f = _f(g, inputs, coords_inputs, outputs, coords_outputs);\n\n\t// Define all the used matrices\n\tgsl_matrix_add (l, d);\n\n\t//Calculate inverse of l+d\n    int s;\n\tgsl_matrix* temp1 = gsl_matrix_alloc (l->size1, l->size2);\n\tgsl_matrix* temp2 = gsl_matrix_alloc (l->size1, l->size2);\n\n\tgsl_vector* result = gsl_vector_alloc(l->size1);\n\tQVector<double> qresult(l->size1);\n\n\tgsl_permutation * perm = gsl_permutation_alloc (f->size);\n\tgsl_linalg_LU_decomp (l, perm, &s);\n\tgsl_linalg_LU_invert (l, perm, temp1);\n\n\n\t//Multiplying the inverse of l+d with b\n\tgsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, temp1, b, 0.0, temp2);\n\n\t//Multiplying the inverse of l+d multiplied with b with f\n\tgsl_blas_dgemv (CblasNoTrans, 1.0, temp2, f, 0.0, result);\n\n\t//Fix positions of input nodes\n\tint i=0;\n\tforeach(Node* node1, g->getNodes()){\n\t\tif (io_set.find(node1) != io_set.end()){\n\t\t\tqresult[i] = gsl_vector_get(f, i);\n\t\t} else {\n\t\t\tqresult[i] = gsl_vector_get(result, i);\n\t\t}\n\t\ti++;\n\t}\n\n\tgsl_matrix_free(temp1);\n\tgsl_matrix_free(temp2);\n\tgsl_vector_free(result);\n\n    return qresult;\n  }\n}\n#endif\n", "meta": {"hexsha": "6e1d79f4f8ee574b39d41e70527d34e188bb693c", "size": 5156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cppn-x/include/opt_placement.hpp", "max_stars_repo_name": "JoostHuizinga/cppnx", "max_stars_repo_head_hexsha": "8643d004f293816a9619fd05931e6c1b3be5db18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2017-04-17T00:22:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T20:24:57.000Z", "max_issues_repo_path": "cppn-x/include/opt_placement.hpp", "max_issues_repo_name": "JoostHuizinga/cppnx", "max_issues_repo_head_hexsha": "8643d004f293816a9619fd05931e6c1b3be5db18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppn-x/include/opt_placement.hpp", "max_forks_repo_name": "JoostHuizinga/cppnx", "max_forks_repo_head_hexsha": "8643d004f293816a9619fd05931e6c1b3be5db18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-04-17T12:33:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T02:32:17.000Z", "avg_line_length": 27.1368421053, "max_line_length": 143, "alphanum_fraction": 0.6047323507, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.5630326676797399}}
{"text": "// hpr-itl cg.cpp: HPR Conjugate Gradient algorithms\n//\n// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"common.hpp\"\n\n// enable posit arithmetic exceptions\n#define POSIT_THROW_ARITHMETIC_EXCEPTION 1\n#include <posit>\n\n// MTL\n#include <boost/numeric/itl/itl.hpp>\n// defines all Krylov solvers\n// CG, CGS, BiCG, BiCGStab, BiCGStab2, BiCGStab_ell, FSM, IDRs, GMRES TFQMR, QMR, PC\n\n\nnamespace hpr {\n\ttemplate<typename Vector, size_t nbits, size_t es, size_t capacity = 10>\n\tsw::unum::posit<nbits, es> fused_dot(const Vector& x, const Vector& y) {\n\t\tsw::unum::quire<nbits, es, capacity> q = 0;\n\t\tsize_t ix, iy, n = size(x);\n\t\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + 1, iy = iy + 1) {\n\t\t\tq += sw::unum::quire_mul(x[ix], y[iy]);\n\t\t}\n\t\tsw::unum::posit<nbits, es> sum;\n\t\tconvert(q.to_value(), sum);     // one and only rounding step of the fused-dot product\n\t\treturn sum;\n\t}\n\n\t/// Conjugate Gradients without preconditioning\n\ttemplate < typename LinearOperator, typename HilbertSpaceX, typename HilbertSpaceB,\n\t\ttypename Iteration >\n\tint cg(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b,\n\t\t\tIteration& iter)\n\t{\n\t\tmtl::vampir_trace<7001> tracer;\n\t\tusing std::abs; using mtl::conj; using mtl::lazy;\n\t\ttypedef HilbertSpaceX Vector;\n\t\ttypedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;\n\t\ttypedef typename Iteration::real                            Real;\n\n\t\tconstexpr size_t nbits = Scalar::nbits;\n\t\tconstexpr size_t es = Scalar::es;\n\n\t\tScalar rho(0), rho_1(0), alpha(0), alpha_1(0);\n\t\tVector p(resource(x)), q(resource(x)), r(resource(x)), z(resource(x));\n\n\t\tr = b - A*x;\n\t\trho = fused_dot<Vector, nbits, es>(r, r);\n\t\twhile (!iter.finished(Real(sqrt(abs(rho))))) {\n\t\t\t++iter;\n\t\t\tif (iter.first())\n\t\t\t\tp = r;\n\t\t\telse\n\t\t\t\tp = r + (rho / rho_1) * p;\n\n\t\t\tq = A * p; alpha = rho / fused_dot<Vector, nbits, es>(p, q);\n//\t\t\t(lazy(q) = A * p) || (lazy(alpha_1) = lazy_dot(p, q));\n//\t\t\talpha = rho / alpha_1;\n\n\t\t\tx += alpha * p;\n\t\t\trho_1 = rho;\n//\t\t\t(lazy(r) -= alpha * q) || (lazy(rho) = lazy_unary_dot(r));\n\t\t\tr -= alpha * q; rho = fused_dot<Vector, nbits, es>(r, r);\n\t\t\t\n\t\t}\n\n\t\treturn iter;\n\t}\n}\n\ntemplate<typename Scalar>\nint regular_CG()\n{\n\tusing Matrix = mtl::mat::compressed2D< Scalar >;\n\tusing Vector = mtl::vec::dense_vector< Scalar >;\n\n\t// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil\n\tconst size_t size = 40, N = size * size;\n\tMatrix A(N, N);\n\tmtl::mat::laplacian_setup(A, size, size);\n\n\t// Set b such that x == 1 is solution; start with x == 0\n\tmtl::vec::dense_vector<Scalar>       x(N, 1.0), b(N);\n\tb = A * x; x = 0;\n\n\t// Termination criterion: r < 1e-6 * b or N iterations\n\t//noisy_iteration< Scalar >  iter(b, 500, 1.e-6);\n\titl::cyclic_iteration< Scalar >  iter(b, 500, 1.e-6);\n\n\t// Solve Ax == b without a preconditioner P\n\titl::cg(A, x, b, iter);\n\n\tint nrOfIterations = -1;\n\tif (iter.is_converged()) nrOfIterations = iter.iterations();\n\treturn nrOfIterations;\n}\n\ntemplate<typename Scalar>\nint fdp_CG()\n{\n\tusing Matrix = mtl::mat::compressed2D< Scalar >;\n\tusing Vector = mtl::vec::dense_vector< Scalar >;\n\n\t// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil\n\tconst size_t size = 40, N = size * size;\n\tMatrix A(N, N);\n\tmtl::mat::laplacian_setup(A, size, size);\n\n\t// Set b such that x == 1 is solution; start with x == 0\n\tmtl::vec::dense_vector<Scalar>       x(N, 1.0), b(N);\n\tb = A * x; x = 0;\n\n\t// Termination criterion: r < 1e-6 * b or N iterations\n\t//itl::noisy_iteration< Scalar >  iter(b, 500, 1.e-6);\n\titl::cyclic_iteration< Scalar >  iter(b, 500, 1.e-6);\n\n\t// Solve Ax == b without a preconditioner P\n\thpr::cg(A, x, b, iter);\n\n\tint nrOfIterations = -1;\n\tif (iter.is_converged()) nrOfIterations = iter.iterations();\n\treturn nrOfIterations;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::unum;\n\tusing namespace mtl;\n\tusing namespace mtl::mat;\n\tusing namespace itl;\n\n\tbool bSuccess = true;\n\n\tfdp_CG< posit<32, 2> >();\n\n\treturn 0;\n\n#if 0\n\tcout << \"CG<double> #iterations: \" << regular_CG<float>() << endl;\n\tcout << \"CG<posit<32,3> #iterations: \" << fdp_CG< posit<32, 3> >() << endl;\n\tcout << \"CG<posit<32,2> #iterations: \" << fdp_CG< posit<32, 2> >() << endl;\n\tcout << \"CG<posit<32,1> #iterations: \" << fdp_CG< posit<32, 1> >() << endl;\n//\tcout << \"CG<posit<32,0> #iterations: \" << fdp_CG< posit<32, 0> >() << endl;\n\tcout << \"CG<posit<28,3> #iterations: \" << fdp_CG< posit<28, 3> >() << endl;\n\tcout << \"CG<posit<28,2> #iterations: \" << fdp_CG< posit<28, 2> >() << endl;\n\tcout << \"CG<posit<28,1> #iterations: \" << fdp_CG< posit<28, 1> >() << endl;\n//\tcout << \"CG<posit<28,0> #iterations: \" << fdp_CG< posit<28, 0> >() << endl;\n\tcout << \"CG<posit<24,3> #iterations: \" << fdp_CG< posit<24, 3> >() << endl;\n\tcout << \"CG<posit<24,2> #iterations: \" << fdp_CG< posit<24, 2> >() << endl;\n\tcout << \"CG<posit<24,1> #iterations: \" << fdp_CG< posit<24, 1> >() << endl;\n//\tcout << \"CG<posit<24,0> #iterations: \" << fdp_CG< posit<24, 0> >() << endl;\n\tcout << \"CG<posit<20,3> #iterations: \" << fdp_CG< posit<20, 3> >() << endl;\n\tcout << \"CG<posit<20,2> #iterations: \" << fdp_CG< posit<20, 2> >() << endl;\n\tcout << \"CG<posit<20,1> #iterations: \" << fdp_CG< posit<20, 1> >() << endl;\n//\tcout << \"CG<posit<20,0> #iterations: \" << fdp_CG< posit<20, 0> >() << endl;\n\tcout << \"CG<posit<16,3> #iterations: \" << fdp_CG< posit<16, 3> >() << endl;\n\tcout << \"CG<posit<16,2> #iterations: \" << fdp_CG< posit<16, 2> >() << endl;\n\tcout << \"CG<posit<16,1> #iterations: \" << fdp_CG< posit<16, 1> >() << endl;\n#endif\n\n\treturn (bSuccess ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_SUCCESS; //as we manually throwing the not supported yet it should not fall through the cracks     EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const std::runtime_error& err) {\n\tstd::cerr << \"Uncaught runtime exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}", "meta": {"hexsha": "e6340aa9df2096962a10b15be360469c9d224c25", "size": 6532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hpritl/cg.cpp", "max_stars_repo_name": "stillwater-sc/hpr-itl", "max_stars_repo_head_hexsha": "b9cb650054be432189257e51af943138f3970eee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hpritl/cg.cpp", "max_issues_repo_name": "stillwater-sc/hpr-itl", "max_issues_repo_head_hexsha": "b9cb650054be432189257e51af943138f3970eee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hpritl/cg.cpp", "max_forks_repo_name": "stillwater-sc/hpr-itl", "max_forks_repo_head_hexsha": "b9cb650054be432189257e51af943138f3970eee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-25T07:09:36.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-25T07:09:36.000Z", "avg_line_length": 34.3789473684, "max_line_length": 125, "alphanum_fraction": 0.6318126148, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.5630141159396208}}
{"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_NTHROOT_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SCALAR_NTHROOT_HPP_INCLUDED\n#include <nt2/exponential/functions/nthroot.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/is_odd.hpp>\n#include <nt2/include/functions/scalar/minusone.hpp>\n#include <nt2/include/functions/scalar/pow.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n#include <nt2/include/functions/scalar/sign.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#endif\n#include <iostream>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( nthroot_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< floating_<A0> >)(scalar_< integer_<A1> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      bool is_ltza0 = is_ltz(a0);\n      bool is_odda1 = is_odd(a1);\n      if (is_ltza0 && !is_odda1) return Nan<A0>();\n      A0 x = nt2::abs(a0);\n      if (x == One<A0>())  return a0;\n      if (!a1) return (x < One<A0>()) ? Zero<A0>() : sign(a0)*Inf<A0>();\n      if (!a0) return Zero<A0>();\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (is_inf(a0)) return (a1) ? a0 : One<A0>();\n      #endif\n      A0 aa1 = static_cast<A0>(a1);\n      A0 y = nt2::pow(x,rec(aa1));\n      // Correct numerical errors (since, e.g., 64^(1/3) is not exactly 4)\n      // by one iteration of Newton's method\n      if (y) y -= (nt2::pow(y, a1) - x) / (aa1* nt2::pow(y,minusone(a1)));\n      return (is_ltza0 && is_odda1)? -y : y;\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "dabcfc4550c5e7b2aae45501ffd341b13ea09e1d", "size": 2325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/scalar/nthroot.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/nthroot.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/nthroot.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 37.5, "max_line_length": 81, "alphanum_fraction": 0.5922580645, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5629975761487958}}
{"text": "//\n// $Id$\n//\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// Original author: Robert Burke <robert.burke@gmail.com>\n//\n// This code taken from the following site:\n// http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Effective_UBLAS/Matrix_Inversion\n//\n\n#ifndef HOUSEHOLDERQR_HPP\n#define HOUSEHOLDERQR_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\nnamespace pwiz {\nnamespace math {\n\ntemplate<class T>\nvoid TransposeMultiply (const ublas::vector<T>& vector, \n\t\t\tublas::matrix<T>& result,\n\t\t\tsize_t size)\n{\n  result.resize (size,size);\n  result.clear ();\n  for(unsigned int row=0; row< vector.size(); ++row)\n    {\n      for(unsigned int col=0; col < vector.size(); ++col)\n\tresult(row,col) = vector(col) * vector(row);\n\n    }\n}\n\ntemplate<class T>\nvoid HouseholderCornerSubstraction (ublas::matrix<T>& LeftLarge, \n\t\t\t\t    const ublas::matrix<T>& RightSmall)\n{\n  using namespace boost::numeric::ublas;\n  using namespace std; \n  if( \n     !( \n       (LeftLarge.size1() >= RightSmall.size1())\n       && (LeftLarge.size2() >= RightSmall.size2())\n\t) \n      )\n    {\n      cerr << \"invalid matrix dimensions\" << endl;\n      return;\n    }  \n\n  size_t row_offset = LeftLarge.size2() - RightSmall.size2();\n  size_t col_offset = LeftLarge.size1() - RightSmall.size1();\n\n  for(unsigned int row = 0; row < RightSmall.size2(); ++row )\n    for(unsigned int col = 0; col < RightSmall.size1(); ++col )\n      LeftLarge(col_offset+col,row_offset+row) -= RightSmall(col,row);\n}\n\ntemplate<class T>\nvoid HouseholderQR (const ublas::matrix<T>& M, \n\t\t    ublas::matrix<T>& Q, \n\t\t    ublas::matrix<T>& R)\n{\n  using namespace boost::numeric::ublas;\n  using namespace std;  \n\n  if( \n     !( \n       (M.size1() == M.size2())\n\t) \n      )\n    {\n      cerr << \"invalid matrix dimensions\" << endl;\n      return;\n    }\n  size_t size = M.size1();\n\n  // init Matrices\n  matrix<T> H, HTemp;\n  HTemp = identity_matrix<T>(size);\n  Q = identity_matrix<T>(size);\n  R = M;\n\n  // find Householder reflection matrices\n  for(unsigned int col = 0; col < size-1; ++col)\n    {\n      // create X vector\n      ublas::vector<T> RRowView = column(R,col);      \n      vector_range< ublas::vector<T> > X2 (RRowView, range (col, size));\n      ublas::vector<T> X = X2;\n\n      // X -> U~\n      if(X(0) >= 0)\n\tX(0) += norm_2(X);\n      else\n\tX(0) += -1*norm_2(X);      \n\n      HTemp.resize(X.size(),X.size(),true);\n\n      TransposeMultiply(X, HTemp, X.size());\n\n      // HTemp = the 2UUt part of H \n      HTemp *= ( 2 / inner_prod(X,X) );\n\n      // H = I - 2UUt\n      H = identity_matrix<T>(size);\n      HouseholderCornerSubstraction(H,HTemp);\n\n      // add H to Q and R\n      Q = prod(Q,H);\n      R = prod(H,R);\n    }\n}\n\n}\n}\n\n#endif // HOUSEHOLDERQR_HPP\n\n", "meta": {"hexsha": "0d0fca604a2695be5595e90f38576c7bd80e7f89", "size": 3460, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/HouseholderQR.hpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T23:48:38.000Z", "max_issues_repo_path": "pwiz/utility/math/HouseholderQR.hpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-08-31T08:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:58:06.000Z", "max_forks_repo_path": "pwiz/utility/math/HouseholderQR.hpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T19:25:07.000Z", "avg_line_length": 24.8920863309, "max_line_length": 98, "alphanum_fraction": 0.6349710983, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5629975757913926}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <time.h>\n#include <vector>\n\n#include <boost/random/gamma_distribution.hpp> // for gamma_distribution.\n#include <boost/math/special_functions/gamma.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/mult.hpp>\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\n#ifdef BOOST_OLD\nusing boost::gamma_distribution;\n#else\nusing boost::random::gamma_distribution;\n#endif\n\n#ifdef WIN32\n\tusing boost::math::lgamma; \n#endif\n\ntemplate<class Disc, typename T>\nclass Dir : public Distribution<T>\n{\npublic:\n  uint32_t K_;\n  Matrix<T,Dynamic,1> alpha_;\n\n  Dir(const Matrix<T,Dynamic,1>& alpha, boost::mt19937 *pRndGen);\n  Dir(const Matrix<T,Dynamic,1>& alpha, const Matrix<T,Dynamic,1>& counts, boost::mt19937 *pRndGen);\n  Dir(const Dir& other);\n  ~Dir();\n\n  Dir<Disc,T>* copy();\n\n  Disc sample();\n  Dir<Disc,T> posterior() const;\n  Dir<Disc,T> posterior(const VectorXu& z);\n  Dir<Disc,T> posterior(const Matrix<T,Dynamic,Dynamic>& x, \n      const VectorXu& z, uint32_t k);\n  Dir<Disc,T> posteriorFromCounts(const Matrix<T,Dynamic,1>& counts);\n  Dir<Disc,T> posteriorFromCounts(const VectorXu& counts);\n  Dir<Disc,T> posteriorFromCounts(const vector<Matrix<T,Dynamic,1> > &\n      counts, const VectorXu& z, uint32_t k);\n\n  T logPdf(const Disc& cat);\n\n  uint32_t K(){return K_;}\n\n  T logPdf(const Disc& cat) const;\n  T logPdfMarginalized() const; // log pdf of SS under NIW prior\n  T logPdfUnderPriorMarginalizedMerged(const Dir<Disc,T>& other) const;\n\n  T logLikelihoodMarginalized(const Matrix<T,Dynamic,1>& counts) const;\n  void print() const;\n\n  virtual Dir<Disc,T>* merge(const Dir<Disc,T>& other);\n  void fromMerge(const Dir<Disc,T>& niwA, const Dir<Disc,T>& niwB);\n\n//  const Matrix<T,Dynamic,Dynamic>& scatter() const {return scatter_;};\n//  Matrix<T,Dynamic,Dynamic>& scatter() {return scatter_;};\n//  const Matrix<T,Dynamic,1>& mean() const {return mean_;};\n//  Matrix<T,Dynamic,1>& mean() {return mean_;};\n//  T count() const {return count_;};\n//  T& count() {return count_;};\n//\n  const Matrix<T,Dynamic,1>& counts() const {return counts_;};\n  Matrix<T,Dynamic,1>& counts() {return counts_;};\n  void setCounts(const Matrix<T,Dynamic,1>& counts) {counts_ = counts;};\n  T count() const {return counts_.sum();};\n\n  void computeMergedSS( const Dir<Disc,T>& dirA, \n      const Dir<Disc,T>& dirB, Matrix<T,Dynamic,1>& NsM) const;\n\nprivate:\n\n  Matrix<T,Dynamic,1> counts_; // counts for the different classes -> SS\n  vector<gamma_distribution<> > gammas_;\n\n  Matrix<T,Dynamic,1> samplePdf();\n};\n\ntypedef Dir<Cat<double>, double> DirCatd;\ntypedef Dir<Cat<float>, float> DirCatf;\ntypedef Dir<Mult<double>, double> DirMultd;\ntypedef Dir<Mult<float>, float> DirMultf;\n", "meta": {"hexsha": "386ea217ea5a3ebbd86fdac57964d72771ae077e", "size": 2919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dir.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/dir.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/dir.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": 29.7857142857, "max_line_length": 100, "alphanum_fraction": 0.6981843097, "num_tokens": 819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5629892683759945}}
{"text": "// full credits to https://github.com/ethz-asl/geodetic_utils\r\n// todo add as external lib\r\n#ifndef GEODETIC_CONVERTER_H_\r\n#define GEODETIC_CONVERTER_H_\r\n\r\n#include \"math.h\"\r\n#include <Eigen/Dense>\r\n\r\nnamespace geodetic_converter\r\n{\r\n// Geodetic system parameters\r\nstatic double kSemimajorAxis = 6378137;\r\nstatic double kSemiminorAxis = 6356752.3142;\r\nstatic double kFirstEccentricitySquared = 6.69437999014 * 0.001;\r\nstatic double kSecondEccentricitySquared = 6.73949674228 * 0.001;\r\nstatic double kFlattening = 1 / 298.257223563;\r\n\r\nclass GeodeticConverter\r\n{\r\npublic:\r\n    GeodeticConverter()\r\n    {\r\n        haveReference_ = false;\r\n    }\r\n\r\n    ~GeodeticConverter()\r\n    {\r\n    }\r\n\r\n    // Default copy constructor and assignment operator are OK.\r\n\r\n    bool isInitialised()\r\n    {\r\n        return haveReference_;\r\n    }\r\n\r\n    void getReference(double* latitude, double* longitude, double* altitude)\r\n    {\r\n        *latitude = initial_latitude_;\r\n        *longitude = initial_longitude_;\r\n        *altitude = initial_altitude_;\r\n    }\r\n\r\n    void initialiseReference(const double latitude, const double longitude, const double altitude)\r\n    {\r\n        // Save NED origin\r\n        initial_latitude_ = deg2Rad(latitude);\r\n        initial_longitude_ = deg2Rad(longitude);\r\n        initial_altitude_ = altitude;\r\n\r\n        // Compute ECEF of NED origin\r\n        geodetic2Ecef(latitude, longitude, altitude, &initial_ecef_x_, &initial_ecef_y_, &initial_ecef_z_);\r\n\r\n        // Compute ECEF to NED and NED to ECEF matrices\r\n        double phiP = atan2(initial_ecef_z_, sqrt(pow(initial_ecef_x_, 2) + pow(initial_ecef_y_, 2)));\r\n\r\n        ecef_to_ned_matrix_ = nRe(phiP, initial_longitude_);\r\n        ned_to_ecef_matrix_ = nRe(initial_latitude_, initial_longitude_).transpose();\r\n\r\n        haveReference_ = true;\r\n    }\r\n\r\n    void geodetic2Ecef(const double latitude, const double longitude, const double altitude, double* x,\r\n                       double* y, double* z)\r\n    {\r\n        // Convert geodetic coordinates to ECEF.\r\n        // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22\r\n        double lat_rad = deg2Rad(latitude);\r\n        double lon_rad = deg2Rad(longitude);\r\n        double xi = sqrt(1 - kFirstEccentricitySquared * sin(lat_rad) * sin(lat_rad));\r\n        *x = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * cos(lon_rad);\r\n        *y = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * sin(lon_rad);\r\n        *z = (kSemimajorAxis / xi * (1 - kFirstEccentricitySquared) + altitude) * sin(lat_rad);\r\n    }\r\n\r\n    void ecef2Geodetic(const double x, const double y, const double z, double* latitude,\r\n                       double* longitude, double* altitude)\r\n    {\r\n        // Convert ECEF coordinates to geodetic coordinates.\r\n        // J. Zhu, \"Conversion of Earth-centered Earth-fixed coordinates\r\n        // to geodetic coordinates,\" IEEE Transactions on Aerospace and\r\n        // Electronic Systems, vol. 30, pp. 957-961, 1994.\r\n\r\n        double r = sqrt(x * x + y * y);\r\n        double Esq = kSemimajorAxis * kSemimajorAxis - kSemiminorAxis * kSemiminorAxis;\r\n        double F = 54 * kSemiminorAxis * kSemiminorAxis * z * z;\r\n        double G = r * r + (1 - kFirstEccentricitySquared) * z * z - kFirstEccentricitySquared * Esq;\r\n        double C = (kFirstEccentricitySquared * kFirstEccentricitySquared * F * r * r) / pow(G, 3);\r\n        double S = cbrt(1 + C + sqrt(C * C + 2 * C));\r\n        double P = F / (3 * pow((S + 1 / S + 1), 2) * G * G);\r\n        double Q = sqrt(1 + 2 * kFirstEccentricitySquared * kFirstEccentricitySquared * P);\r\n        double r_0 = -(P * kFirstEccentricitySquared * r) / (1 + Q) + sqrt(\r\n                                                                          0.5 * kSemimajorAxis * kSemimajorAxis * (1 + 1.0 / Q) - P * (1 - kFirstEccentricitySquared) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r);\r\n        double U = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) + z * z);\r\n        double V = sqrt(\r\n            pow((r - kFirstEccentricitySquared * r_0), 2) + (1 - kFirstEccentricitySquared) * z * z);\r\n        double Z_0 = kSemiminorAxis * kSemiminorAxis * z / (kSemimajorAxis * V);\r\n        *altitude = U * (1 - kSemiminorAxis * kSemiminorAxis / (kSemimajorAxis * V));\r\n        *latitude = rad2Deg(atan((z + kSecondEccentricitySquared * Z_0) / r));\r\n        *longitude = rad2Deg(atan2(y, x));\r\n    }\r\n\r\n    void ecef2Ned(const double x, const double y, const double z, double* north, double* east,\r\n                  double* down)\r\n    {\r\n        // Converts ECEF coordinate position into local-tangent-plane NED.\r\n        // Coordinates relative to given ECEF coordinate frame.\r\n\r\n        Eigen::Vector3d vect, ret;\r\n        vect(0) = x - initial_ecef_x_;\r\n        vect(1) = y - initial_ecef_y_;\r\n        vect(2) = z - initial_ecef_z_;\r\n        ret = ecef_to_ned_matrix_ * vect;\r\n        *north = ret(0);\r\n        *east = ret(1);\r\n        *down = -ret(2);\r\n    }\r\n\r\n    void ned2Ecef(const double north, const double east, const double down, double* x, double* y,\r\n                  double* z)\r\n    {\r\n        // NED (north/east/down) to ECEF coordinates\r\n        Eigen::Vector3d ned, ret;\r\n        ned(0) = north;\r\n        ned(1) = east;\r\n        ned(2) = -down;\r\n        ret = ned_to_ecef_matrix_ * ned;\r\n        *x = ret(0) + initial_ecef_x_;\r\n        *y = ret(1) + initial_ecef_y_;\r\n        *z = ret(2) + initial_ecef_z_;\r\n    }\r\n\r\n    void geodetic2Ned(const double latitude, const double longitude, const double altitude,\r\n                      double* north, double* east, double* down)\r\n    {\r\n        // Geodetic position to local NED frame\r\n        double x, y, z;\r\n        geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z);\r\n        ecef2Ned(x, y, z, north, east, down);\r\n    }\r\n\r\n    void ned2Geodetic(const double north, const double east, const double down, double* latitude,\r\n                      double* longitude, double* altitude)\r\n    {\r\n        // Local NED position to geodetic coordinates\r\n        double x, y, z;\r\n        ned2Ecef(north, east, down, &x, &y, &z);\r\n        ecef2Geodetic(x, y, z, latitude, longitude, altitude);\r\n    }\r\n\r\n    void geodetic2Enu(const double latitude, const double longitude, const double altitude,\r\n                      double* east, double* north, double* up)\r\n    {\r\n        // Geodetic position to local ENU frame\r\n        double x, y, z;\r\n        geodetic2Ecef(latitude, longitude, altitude, &x, &y, &z);\r\n\r\n        double aux_north, aux_east, aux_down;\r\n        ecef2Ned(x, y, z, &aux_north, &aux_east, &aux_down);\r\n\r\n        *east = aux_east;\r\n        *north = aux_north;\r\n        *up = -aux_down;\r\n    }\r\n\r\n    void enu2Geodetic(const double east, const double north, const double up, double* latitude,\r\n                      double* longitude, double* altitude)\r\n    {\r\n        // Local ENU position to geodetic coordinates\r\n\r\n        const double aux_north = north;\r\n        const double aux_east = east;\r\n        const double aux_down = -up;\r\n        double x, y, z;\r\n        ned2Ecef(aux_north, aux_east, aux_down, &x, &y, &z);\r\n        ecef2Geodetic(x, y, z, latitude, longitude, altitude);\r\n    }\r\n\r\nprivate:\r\n    inline Eigen::Matrix3d nRe(const double lat_radians, const double lon_radians)\r\n    {\r\n        const double sLat = sin(lat_radians);\r\n        const double sLon = sin(lon_radians);\r\n        const double cLat = cos(lat_radians);\r\n        const double cLon = cos(lon_radians);\r\n\r\n        Eigen::Matrix3d ret;\r\n        ret(0, 0) = -sLat * cLon;\r\n        ret(0, 1) = -sLat * sLon;\r\n        ret(0, 2) = cLat;\r\n        ret(1, 0) = -sLon;\r\n        ret(1, 1) = cLon;\r\n        ret(1, 2) = 0.0;\r\n        ret(2, 0) = cLat * cLon;\r\n        ret(2, 1) = cLat * sLon;\r\n        ret(2, 2) = sLat;\r\n\r\n        return ret;\r\n    }\r\n\r\n    inline double rad2Deg(const double radians)\r\n    {\r\n        return (radians / M_PI) * 180.0;\r\n    }\r\n\r\n    inline double deg2Rad(const double degrees)\r\n    {\r\n        return (degrees / 180.0) * M_PI;\r\n    }\r\n\r\n    double initial_latitude_;\r\n    double initial_longitude_;\r\n    double initial_altitude_;\r\n\r\n    double initial_ecef_x_;\r\n    double initial_ecef_y_;\r\n    double initial_ecef_z_;\r\n\r\n    Eigen::Matrix3d ecef_to_ned_matrix_;\r\n    Eigen::Matrix3d ned_to_ecef_matrix_;\r\n\r\n    bool haveReference_;\r\n\r\n}; // class GeodeticConverter\r\n}; // namespace geodetic_conv\r\n\r\n#endif // GEODETIC_CONVERTER_H_\r\n", "meta": {"hexsha": "33e5342fd8ebe1b0a29c64e246808d5bcd0c05d5", "size": 8402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ros/src/airsim_ros_pkgs/include/geodetic_conv.hpp", "max_stars_repo_name": "altay13/AirSim", "max_stars_repo_head_hexsha": "a42fb69e6a692ec154f25abd80c0b49ef45caac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6115.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T05:29:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:46:36.000Z", "max_issues_repo_path": "ros/src/airsim_ros_pkgs/include/geodetic_conv.hpp", "max_issues_repo_name": "altay13/AirSim", "max_issues_repo_head_hexsha": "a42fb69e6a692ec154f25abd80c0b49ef45caac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2306.0, "max_issues_repo_issues_event_min_datetime": "2019-05-07T00:17:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:31:46.000Z", "max_forks_repo_path": "ros/src/airsim_ros_pkgs/include/geodetic_conv.hpp", "max_forks_repo_name": "altay13/AirSim", "max_forks_repo_head_hexsha": "a42fb69e6a692ec154f25abd80c0b49ef45caac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2059.0, "max_forks_repo_forks_event_min_datetime": "2019-05-07T03:07:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T06:31:19.000Z", "avg_line_length": 36.850877193, "max_line_length": 210, "alphanum_fraction": 0.5947393478, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5629892636667629}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <boost/tuple/tuple.hpp>\n#include \"gnuplot-iostream.h\"\n#include \"ODE.h\"\n#include \"sysFunc.h\"\n\n/* I should make it compatible with armadillo, currently it is working with std::vector containers \nto be able to make it work with armadillo I need to make it generic.\n*/\n\nusing namespace STASC;\nint main()\n{\n\n  std::vector<State> systemTrajectory;\n  constexpr size_t timeStepsCount = 1000;\n  constexpr double stepSize = 0.1;\n  std::vector<double> timeStepsVec(timeStepsCount);\n  std::vector<double> position;\n\n  // ODE\n  {\n    for (size_t i = 0; i < timeStepsCount; i++)\n    {\n      timeStepsVec.at(i) = i * stepSize;\n    }\n\n    ODE ode(SysFunc::sysFuncOne, SysFunc::initialStateOne, timeStepsVec);\n\n    // Integrate and collect the state at each time point\n    for (size_t i = 0; i < timeStepsCount - 1; i++)\n    {\n      ode.int_u_dt(STASC::IntegrationMode::ERK1);\n      systemTrajectory.push_back(ode.getStateVector());\n    }\n    assert(systemTrajectory.size() == timeStepsCount - 1);\n     for ( auto element : systemTrajectory)\n        position.push_back(element.at(0).real());\n    //   std::cout << element.at(0).real() << \"\\n\"; // show the position.\n  }\n\n  // GNU Plot\n  // std::cout << \"position size: \" << position.size() << std::endl;\n  // std::cout << \"time vector size: \" << timeStepsVec.size() << std::endl;\n\n  if(true){\n    /* output */\n    // to make sizes match.\n    position.push_back(*position.cend()); // Duplicating the last element.\n    Gnuplot gp;\n    gp << \"plot '-' using 1:2 with linespoint\" << std::endl;\n    gp.send1d(std::make_tuple(timeStepsVec, position));\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "9ffa5683de7cf6872f541db8ed8084facd1c59c3", "size": 1648, "ext": "cc", "lang": "C++", "max_stars_repo_path": "assign1/src/main.cc", "max_stars_repo_name": "amirnn/STASC", "max_stars_repo_head_hexsha": "83eb95c284a3bd63e98f2ad38f9ffaf95aad7334", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assign1/src/main.cc", "max_issues_repo_name": "amirnn/STASC", "max_issues_repo_head_hexsha": "83eb95c284a3bd63e98f2ad38f9ffaf95aad7334", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assign1/src/main.cc", "max_forks_repo_name": "amirnn/STASC", "max_forks_repo_head_hexsha": "83eb95c284a3bd63e98f2ad38f9ffaf95aad7334", "max_forks_repo_licenses": ["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.4137931034, "max_line_length": 99, "alphanum_fraction": 0.6516990291, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.562954567381936}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef NL_PROBLEM_SO3_HPP_\n#define NL_PROBLEM_SO3_HPP_\n\n#include <Eigen/Dense>\n#include <cbr_math/lie/Tn.hpp>\n#include <cbr_math/lie/group_product.hpp>\n#include <sophus/so3.hpp>\n\n/**\n * @brief Defines an optimal control problem on (X, V) \\in SO(3) \\timex R3 with three inputs\n *   d^r X_t = V\n *   d^r V_t = u\n */\nstruct SO3Problem\n{\n  using state_t = cbr::lie::GroupProduct<double, 0, Sophus::SO3, cbr::lie::T3>;\n  using deriv_t = typename state_t::Tangent;\n  using input_t = Eigen::Vector3d;\n\n  static constexpr std::size_t nx = state_t::DoF;\n  static constexpr std::size_t nu = input_t::SizeAtCompileTime;\n\n  // Dynamics (must be differentiable so we make a generic template)\n  template<typename T, typename Derived>\n  auto get_f(const T & x, const Eigen::MatrixBase<Derived> & u) const\n  {\n    using Scalar = typename decltype(x.log() * u.transpose())::EvalReturnType::Scalar;\n\n    Eigen::Matrix<Scalar, 6, 1> ret;\n    ret.template segment<3>(0) = std::get<1>(x).translation();\n    ret.template segment<3>(3) = u.eval();\n    return ret;\n  }\n\n  void get_input_lb(double, Eigen::Ref<input_t> input_lb) const\n  {\n    input_lb.setConstant(-0.3);\n  }\n\n  void get_input_ub(double, Eigen::Ref<input_t> input_ub) const\n  {\n    input_ub.setConstant(0.3);\n  }\n\n  Eigen::Matrix<double, nx, nx> get_Q(double) const\n  {\n    return 0.1 * Eigen::Matrix<double, nx, nx>::Identity();\n  }\n  Eigen::Matrix<double, nx, nx> get_QT() const\n  {\n    return Eigen::Matrix<double, nx, nx>::Identity();\n  }\n  Eigen::Matrix<double, nu, nu> get_R(double) const\n  {\n    return 0.01 * Eigen::Matrix<double, nu, nu>::Identity();\n  }\n};\n\n#endif  // NL_PROBLEM_SO3_HPP_\n", "meta": {"hexsha": "c8330c01834fa7dca3d977dabcaeb6d9fd9e6489", "size": 1747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/so3_problem.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/so3_problem.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/so3_problem.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.296875, "max_line_length": 92, "alphanum_fraction": 0.6794504865, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5628244167399533}}
{"text": "// Rotations conversion library\n// File: rot_conv.cpp\n// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>\n\n// Includes\n#include <rot_conv/rot_conv.h>\n#include <Eigen/Eigenvalues>\n#include <algorithm>\n#include <cfloat>\n\n// Defines\n#define M_2PI (2.0*M_PI)\n\n// Rotations conversion namespace\nnamespace rot_conv\n{\n\t// ################################\n\t// #### Rotation normalisation ####\n\t// ################################\n\n\t// Normalise: Rotation matrix\n\tvoid NormaliseRotmat(Rotmat& R)\n\t{\n\t\t// Find the closest orthogonal matrix to the input rotation matrix\n\t\tRotmat nonOrth = R.transpose() * R;\n\t\tR *= Eigen::SelfAdjointEigenSolver<Rotmat>(nonOrth).operatorInverseSqrt();\n\n\t\t// Filter out invalid left hand coordinate systems\n\t\tif(R.determinant() < 0.0)\n\t\t\tR.setIdentity();\n\t}\n\n\t// Normalise: Quaternion\n\tvoid NormaliseQuat(Quat& q, double normTol)\n\t{\n\t\t// Normalise the quaternion\n\t\tdouble normsq = QuatNormSq(q);\n\t\tif(normsq <= normTol*normTol)\n\t\t\tq.setIdentity();\n\t\telse\n\t\t\tq /= sqrt(normsq);\n\t}\n\n\t// Normalise: Vector\n\tvoid NormaliseVec(Vec3& v, double normTol, const Vec3& vdef)\n\t{\n\t\t// Normalise the vector\n\t\tdouble normsq = VecNormSq(v);\n\t\tif(normsq <= normTol*normTol)\n\t\t\tv = vdef;\n\t\telse\n\t\t\tv /= sqrt(normsq);\n\t}\n\n\t// ##########################\n\t// #### Random rotations ####\n\t// ##########################\n\n\t// Random: Vector\n\tVec3 RandVec(double maxNorm)\n\t{\n\t\t// Generate the required random vector\n\t\tdouble desNorm = (maxNorm * std::rand()) / RAND_MAX;\n\t\tVec3 vec((2.0*std::rand()) / RAND_MAX - 1.0, (2.0*std::rand()) / RAND_MAX - 1.0, (2.0*std::rand()) / RAND_MAX - 1.0);\n\t\tdouble vecNorm = VecNorm(vec);\n\t\tif(vecNorm > 0.0)\n\t\t\tvec *= desNorm / vecNorm;\n\t\treturn vec;\n\t}\n\n\t// Random: Unit vector\n\tVec3 RandUnitVec()\n\t{\n\t\t// Generate the required random vector\n\t\tVec3 vec((2.0*std::rand()) / RAND_MAX - 1.0, (2.0*std::rand()) / RAND_MAX - 1.0, (2.0*std::rand()) / RAND_MAX - 1.0);\n\t\tNormaliseVec(vec);\n\t\treturn vec;\n\t}\n\n\t// Random: Rotation matrix\n\tvoid RandRotmat(Rotmat& R)\n\t{\n\t\t// Generate the required random rotation\n\t\tQuat q;\n\t\tRandQuat(q);\n\t\tRotmatFromQuat(q, R);\n\t}\n\n\t// Random: Quaternion\n\tvoid RandQuat(Quat& q)\n\t{\n\t\t// Generate random rotation components\n\t\tq.w() = (2.0*std::rand()) / RAND_MAX - 1.0;\n\t\tq.x() = (2.0*std::rand()) / RAND_MAX - 1.0;\n\t\tq.y() = (2.0*std::rand()) / RAND_MAX - 1.0;\n\t\tq.z() = (2.0*std::rand()) / RAND_MAX - 1.0;\n\n\t\t// Normalise the quaternion\n\t\tNormaliseQuat(q);\n\t}\n\n\t// Random: Euler angles\n\tvoid RandEuler(EulerAngles& e)\n\t{\n\t\t// Generate the required random rotation\n\t\te.yaw = RandAng();\n\t\te.pitch = 0.5*RandAng();\n\t\te.roll = RandAng();\n\t}\n\n\t// Random: Fused angles\n\tvoid RandFused(FusedAngles& f)\n\t{\n\t\t// Generate the required random rotation\n\t\tdouble lambda1 = 0.25*RandAng();\n\t\tdouble lambda2 = 0.25*RandAng();\n\t\tf.fusedYaw = RandAng();\n\t\tf.fusedPitch = lambda1 + lambda2;\n\t\tf.fusedRoll = lambda1 - lambda2;\n\t\tf.hemi = (std::rand() % 2 == 0);\n\t}\n\n\t// Random: Tilt angles\n\tvoid RandTilt(TiltAngles& t)\n\t{\n\t\t// Generate the required random rotation\n\t\tt.fusedYaw = RandAng();\n\t\tt.tiltAxisAngle = RandAng();\n\t\tt.tiltAngle = (M_PI * std::rand()) / RAND_MAX;\n\t}\n\n\t// ##########################################\n\t// #### Rotation checking and validation ####\n\t// ##########################################\n\n\t// Check and validate: Rotation matrix\n\tbool ValidateRotmat(Rotmat& R, double tol)\n\t{\n\t\t// Make a copy of the input\n\t\tRotmat Rorig = R;\n\n\t\t// Normalise the rotation matrix\n\t\tNormaliseRotmat(R);\n\n\t\t// Return whether the rotation matrix was valid within the given tolerance\n\t\treturn (R - Rorig).isZero(tol);\n\t}\n\n\t// Check and validate: Quaternion\n\tbool ValidateQuat(Quat& q, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tQuat qorig = q;\n\n\t\t// Normalise the quaternion\n\t\tNormaliseQuat(q);\n\n\t\t// Make the quaternion unique\n\t\tif(unique && q.w() < 0.0)\n\t\t\tq = -q;\n\n\t\t// Return whether the quaternion was valid within the given tolerance\n\t\treturn QuatEqualExact(q, qorig, tol);\n\t}\n\n\t// Check and validate: Euler angles\n\tbool ValidateEuler(EulerAngles& e, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tEulerAngles eorig = e;\n\n\t\t// Wrap the pitch to (-pi,pi] and then collapse it to the [-pi/2,pi/2] interval\n\t\tinternal::picutVar(e.pitch);\n\t\tif(fabs(e.pitch) > M_PI_2)\n\t\t{\n\t\t\te.yaw += M_PI;\n\t\t\te.pitch = (e.pitch >= 0.0 ? M_PI - e.pitch : -M_PI - e.pitch);\n\t\t\te.roll += M_PI;\n\t\t}\n\n\t\t// Make the positive and negative gimbal lock representations unique\n\t\tif(unique)\n\t\t{\n\t\t\tdouble spitch = sin(e.pitch);\n\t\t\tif(fabs(spitch - 1.0) <= tol)\n\t\t\t{\n\t\t\t\te.roll -= e.yaw;\n\t\t\t\te.yaw = 0.0;\n\t\t\t}\n\t\t\telse if(fabs(spitch + 1.0) <= tol)\n\t\t\t{\n\t\t\t\te.roll += e.yaw;\n\t\t\t\te.yaw = 0.0;\n\t\t\t}\n\t\t}\n\n\t\t// Wrap yaw and roll to (-pi,pi]\n\t\tinternal::picutVar(e.yaw);\n\t\tinternal::picutVar(e.roll);\n\n\t\t// Return whether the Euler angles were valid within the given tolerance\n\t\treturn (fabs(e.yaw - eorig.yaw) <= tol && fabs(e.pitch - eorig.pitch) <= tol && fabs(e.roll - eorig.roll) <= tol);\n\t}\n\n\t// Check and validate: Fused angles\n\tbool ValidateFused(FusedAngles& f, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tFusedAngles forig = f;\n\n\t\t// Wrap the angles to (-pi,pi]\n\t\tinternal::picutVar(f.fusedYaw);\n\t\tinternal::picutVar(f.fusedPitch);\n\t\tinternal::picutVar(f.fusedRoll);\n\n\t\t// Mirror the pitch and roll angles into the [-pi/2,pi/2] range\n\t\tf.fusedPitch = std::max(std::min(f.fusedPitch, M_PI - f.fusedPitch), -M_PI - f.fusedPitch);\n\t\tf.fusedRoll = std::max(std::min(f.fusedRoll, M_PI - f.fusedRoll), -M_PI - f.fusedRoll);\n\n\t\t// Coerce the fused pitch and roll angles to the valid domain\n\t\tdouble spitch = sin(f.fusedPitch);\n\t\tdouble sroll = sin(f.fusedRoll);\n\t\tdouble sqrtcrit = sqrt(spitch*spitch + sroll*sroll);\n\t\tif(sqrtcrit > 1.0)\n\t\t{\n\t\t\tspitch /= sqrtcrit;\n\t\t\tsroll /= sqrtcrit;\n\t\t\tf.fusedPitch = asin(spitch);\n\t\t\tf.fusedRoll = asin(sroll);\n\t\t\tsqrtcrit = 1.0;\n\t\t}\n\n\t\t// Make the representation unique if required\n\t\tif(unique)\n\t\t{\n\t\t\tif(sqrtcrit >= 1.0 - tol)\n\t\t\t\tf.hemi = true;\n\t\t\tif(sqrtcrit <= tol && !f.hemi)\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t}\n\n\t\t// Return whether the fused angles were valid within the given tolerance\n\t\treturn (fabs(f.fusedYaw - forig.fusedYaw) <= tol && fabs(f.fusedPitch - forig.fusedPitch) <= tol && fabs(f.fusedRoll - forig.fusedRoll) <= tol && f.hemi == forig.hemi);\n\t}\n\n\t// Check and validate: Tilt angles\n\tbool ValidateTilt(TiltAngles& t, double tol, bool unique)\n\t{\n\t\t// Make a copy of the input\n\t\tTiltAngles torig = t;\n\n\t\t// Wrap the angles to (-pi,pi]\n\t\tinternal::picutVar(t.fusedYaw);\n\t\tinternal::picutVar(t.tiltAxisAngle);\n\t\tinternal::picutVar(t.tiltAngle);\n\n\t\t// Handle the case of a negative tilt angle\n\t\tif(t.tiltAngle < 0.0)\n\t\t{\n\t\t\tt.tiltAxisAngle = (t.tiltAxisAngle > 0.0 ? -M_PI + t.tiltAxisAngle : M_PI + t.tiltAxisAngle);\n\t\t\tt.tiltAngle = -t.tiltAngle;\n\t\t}\n\n\t\t// Make the representation unique if required\n\t\tif(unique)\n\t\t{\n\t\t\tdouble ctilt = cos(t.tiltAngle);\n\t\t\tbool near0 = (fabs(ctilt - 1.0) <= tol);\n\t\t\tbool near180 = (fabs(ctilt + 1.0) <= tol);\n\t\t\tif(near0 || near180)\n\t\t\t\tt.tiltAxisAngle = 0.0;\n\t\t\tif(near180)\n\t\t\t\tt.fusedYaw = 0.0;\n\t\t}\n\n\t\t// Return whether the tilt angles were valid within the given tolerance\n\t\treturn (fabs(t.fusedYaw - torig.fusedYaw) <= tol && fabs(t.tiltAxisAngle - torig.tiltAxisAngle) <= tol && fabs(t.tiltAngle - torig.tiltAngle) <= tol);\n\t}\n\n\t// ###########################\n\t// #### Rotation equality ####\n\t// ###########################\n\n\t// Check equality: Rotation matrix\n\tbool RotmatEqual(const Rotmat& Ra, const Rotmat& Rb, double tol)\n\t{\n\t\t// Return whether none of the elements of the rotation matrices differ by more than the tolerance\n\t\treturn (Ra - Rb).isZero(tol);\n\t}\n\n\t// Check equality: Rotation matrix (exact)\n\tbool RotmatEqualExact(const Rotmat& Ra, const Rotmat& Rb, double tol)\n\t{\n\t\t// Return whether none of the elements of the rotation matrices differ by more than the tolerance\n\t\treturn (Ra - Rb).isZero(tol);\n\t}\n\n\t// Check equality: Quaternion\n\tbool QuatEqual(const Quat& qa, const Quat& qb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the quaternions are the same\n\t\tbool isSame = (fabs(qa.w() - qb.w()) <= tol && fabs(qa.x() - qb.x()) <= tol && fabs(qa.y() - qb.y()) <= tol && fabs(qa.z() - qb.z()) <= tol);\n\t\tbool isOpp  = (fabs(qa.w() + qb.w()) <= tol && fabs(qa.x() + qb.x()) <= tol && fabs(qa.y() + qb.y()) <= tol && fabs(qa.z() + qb.z()) <= tol);\n\t\treturn (isSame || isOpp);\n\t}\n\n\t// Check equality: Quaternion (exact)\n\tbool QuatEqualExact(const Quat& qa, const Quat& qb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the quaternions are the same\n\t\treturn (fabs(qa.w() - qb.w()) <= tol && fabs(qa.x() - qb.x()) <= tol && fabs(qa.y() - qb.y()) <= tol && fabs(qa.z() - qb.z()) <= tol);\n\t}\n\n\t// Check equality: Euler angles\n\tbool EulerEqual(const EulerAngles& ea, const EulerAngles& eb, double tol)\n\t{\n\t\t// Convert both Euler angles to their unique representations\n\t\tEulerAngles eau = ea, ebu = eb;\n\t\tValidateEuler(eau, tol, true);\n\t\tValidateEuler(ebu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(eau.yaw - ebu.yaw) > M_PI)\n\t\t{\n\t\t\tif(eau.yaw > ebu.yaw)\n\t\t\t\tebu.yaw += M_2PI;\n\t\t\telse\n\t\t\t\teau.yaw += M_2PI;\n\t\t}\n\t\tif(fabs(eau.roll - ebu.roll) > M_PI)\n\t\t{\n\t\t\tif(eau.roll > ebu.roll)\n\t\t\t\tebu.roll += M_2PI;\n\t\t\telse\n\t\t\t\teau.roll += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the Euler angles are the same\n\t\treturn (fabs(eau.yaw - ebu.yaw) <= tol && fabs(sin(eau.pitch) - sin(ebu.pitch)) <= tol && fabs(eau.roll - ebu.roll) <= tol); // The pitch suffers from the numerical insensitivity of asin, so the sine thereof is checked\n\t}\n\n\t// Check equality: Euler angles (exact)\n\tbool EulerEqualExact(const EulerAngles& ea, const EulerAngles& eb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the Euler angles are the same\n\t\treturn (fabs(ea.yaw - eb.yaw) <= tol && fabs(ea.pitch - eb.pitch) <= tol && fabs(ea.roll - eb.roll) <= tol);\n\t}\n\n\t// Check equality: Fused angles\n\tbool FusedEqual(const FusedAngles& fa, const FusedAngles& fb, double tol)\n\t{\n\t\t// Convert both fused angles to their unique representations\n\t\tFusedAngles fau = fa, fbu = fb;\n\t\tValidateFused(fau, tol, true);\n\t\tValidateFused(fbu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(fau.fusedYaw - fbu.fusedYaw) > M_PI)\n\t\t{\n\t\t\tif(fau.fusedYaw > fbu.fusedYaw)\n\t\t\t\tfbu.fusedYaw += M_2PI;\n\t\t\telse\n\t\t\t\tfau.fusedYaw += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the fused angles are the same\n\t\treturn (fabs(fau.fusedYaw - fbu.fusedYaw) <= tol && fabs(sin(fau.fusedPitch) - sin(fbu.fusedPitch)) <= tol && fabs(sin(fau.fusedRoll) - sin(fbu.fusedRoll)) <= tol && fau.hemi == fbu.hemi); // The fused pitch and roll suffer from the numerical insensitivity of asin, so the sine's thereof are checked\n\t}\n\n\t// Check equality: Fused angles (exact)\n\tbool FusedEqualExact(const FusedAngles& fa, const FusedAngles& fb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the fused angles are the same\n\t\treturn (fabs(fa.fusedYaw - fb.fusedYaw) <= tol && fabs(fa.fusedPitch - fb.fusedPitch) <= tol && fabs(fa.fusedRoll - fb.fusedRoll) <= tol && fa.hemi == fb.hemi);\n\t}\n\n\t// Check equality: Tilt angles\n\tbool TiltEqual(const TiltAngles& ta, const TiltAngles& tb, double tol)\n\t{\n\t\t// Convert both tilt angles to their unique representations\n\t\tTiltAngles tau = ta, tbu = tb;\n\t\tValidateTilt(tau, tol, true);\n\t\tValidateTilt(tbu, tol, true);\n\n\t\t// Handle angle wrapping issues\n\t\tif(fabs(tau.fusedYaw - tbu.fusedYaw) > M_PI)\n\t\t{\n\t\t\tif(tau.fusedYaw > tbu.fusedYaw)\n\t\t\t\ttbu.fusedYaw += M_2PI;\n\t\t\telse\n\t\t\t\ttau.fusedYaw += M_2PI;\n\t\t}\n\n\t\t// Return whether to the specified tolerance the fused angles are the same\n\t\tdouble stilta = sin(tau.tiltAngle);\n\t\tdouble stiltb = sin(tbu.tiltAngle);\n\t\tdouble stiltasq = stilta*stilta;\n\t\tdouble stiltbsq = stiltb*stiltb;\n\t\treturn (fabs(tau.fusedYaw - tbu.fusedYaw) <= tol && fabs(stiltasq*cos(tau.tiltAxisAngle) - stiltbsq*cos(tbu.tiltAxisAngle)) <= tol && fabs(stiltasq*sin(tau.tiltAxisAngle) - stiltbsq*sin(tbu.tiltAxisAngle)) <= tol && fabs(cos(tau.tiltAngle) - cos(tbu.tiltAngle)) <= tol); // The tilt angle suffers from the numerical insensitivity of acos, so the cosine thereof is checked / The tilt axis angle has a singularity when the tilt angle is zero, so two geometrically relevant terms are checked instead of the tilt axis angle directly\n\t}\n\n\t// Check equality: Tilt angles (exact)\n\tbool TiltEqualExact(const TiltAngles& ta, const TiltAngles& tb, double tol)\n\t{\n\t\t// Return whether to the specified tolerance the tilt angles are the same\n\t\treturn (fabs(ta.fusedYaw - tb.fusedYaw) <= tol && fabs(ta.tiltAxisAngle - tb.tiltAxisAngle) <= tol && fabs(ta.tiltAngle - tb.tiltAngle) <= tol);\n\t}\n\n\t// #########################\n\t// #### Yaw of rotation ####\n\t// #########################\n\n\t// Euler yaw of: Rotation matrix\n\tdouble EYawOfRotmat(const Rotmat& R)\n\t{\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(R.coeff(1,0), R.coeff(0,0));\n\t}\n\n\t// Fused yaw of: Rotation matrix\n\tdouble FYawOfRotmat(const Rotmat& R)\n\t{\n\t\t// Calculate, wrap and return the fused yaw\n\t\tdouble fusedYaw, trace = R.coeff(0,0) + R.coeff(1,1) + R.coeff(2,2);\n\t\tif(trace >= 0.0)\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(1,0) - R.coeff(0,1), 1.0 + trace);\n\t\telse if(R.coeff(2,2) >= R.coeff(1,1) && R.coeff(2,2) >= R.coeff(0,0))\n\t\t\tfusedYaw = 2.0*atan2(1.0 - R.coeff(0,0) - R.coeff(1,1) + R.coeff(2,2), R.coeff(1,0) - R.coeff(0,1));\n\t\telse if(R.coeff(1,1) >= R.coeff(0,0))\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(2,1) + R.coeff(1,2), R.coeff(0,2) - R.coeff(2,0));\n\t\telse\n\t\t\tfusedYaw = 2.0*atan2(R.coeff(0,2) + R.coeff(2,0), R.coeff(2,1) - R.coeff(1,2));\n\t\tif(fusedYaw > M_PI) fusedYaw -= M_2PI;   // fusedYaw is now in [-2*pi,pi]\n\t\tif(fusedYaw <= -M_PI) fusedYaw += M_2PI; // fusedYaw is now in (-pi,pi]\n\t\treturn fusedYaw;\n\t}\n\n\t// Euler yaw of: Quaternion\n\tdouble EYawOfQuat(const Quat& q)\n\t{\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(q.w()*q.z() + q.x()*q.y(), 0.5 - (q.y()*q.y() + q.z()*q.z()));\n\t}\n\n\t// Fused yaw of: Quaternion\n\tdouble FYawOfQuat(const Quat& q)\n\t{\n\t\t// Calculate, wrap and return the fused yaw\n\t\tdouble fusedYaw = 2.0*atan2(q.z(), q.w()); // Output of atan2 is [-pi,pi], so this expression is in [-2*pi,2*pi]\n\t\tif(fusedYaw > M_PI) fusedYaw -= M_2PI;     // fusedYaw is now in [-2*pi,pi]\n\t\tif(fusedYaw <= -M_PI) fusedYaw += M_2PI;   // fusedYaw is now in (-pi,pi]\n\t\treturn fusedYaw;\n\t}\n\n\t// Fused yaw of: Euler angles\n\tdouble FYawOfEuler(const EulerAngles& e)\n\t{\n\t\t// Calculate and return the fused yaw of the rotation\n\t\treturn FYawOfRotmat(RotmatFromEuler(e));\n\t}\n\n\t// Euler yaw of: Fused angles\n\tdouble EYawOfFused(const FusedAngles& f)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth  = sin(f.fusedPitch);\n\t\tdouble sphi = sin(f.fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the cosine of the tilt angle alpha\n\t\tdouble calpha;\n\t\tif(crit >= 1.0)\n\t\t\tcalpha = 0.0;\n\t\telse\n\t\t\tcalpha = (f.hemi ? sqrt(1.0-crit) : -sqrt(1.0-crit));\n\n\t\t// Calculate the tilt axis gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble psigam = f.fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam);\n\t}\n\n\t// Euler yaw of: Tilt angles\n\tdouble EYawOfTilt(const TiltAngles& t)\n\t{\n\t\t// Precalculate trigonometric terms\n\t\tdouble psigam = t.fusedYaw + t.tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble cgam = cos(t.tiltAxisAngle);\n\t\tdouble sgam = sin(t.tiltAxisAngle);\n\t\tdouble calpha = cos(t.tiltAngle);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the Euler ZYX yaw of the rotation\n\t\treturn atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam);\n\t}\n\n\t// ##################################\n\t// #### Remove yaw from rotation ####\n\t// ##################################\n\n\t// Remove Euler yaw from: Rotation matrix\n\tvoid RotmatNoEYaw(const Rotmat& R, Rotmat& Rout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble cEYaw = cos(EYaw);\n\t\tdouble sEYaw = sin(EYaw);\n\n\t\t// Construct the Euler ZYX yaw component of the rotation\n\t\tRotmat REYawTrans;\n\t\tREYawTrans << cEYaw, sEYaw, 0.0,\n\t\t              -sEYaw, cEYaw, 0.0,\n\t\t              0.0, 0.0, 1.0;\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tRout = REYawTrans * R;\n\t}\n\n\t// Remove fused yaw from: Rotation matrix\n\tvoid RotmatNoFYaw(const Rotmat& R, Rotmat& Rout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble cFYaw = cos(FYaw);\n\t\tdouble sFYaw = sin(FYaw);\n\n\t\t// Construct the fused yaw component of the rotation\n\t\tRotmat RFYawTrans;\n\t\tRFYawTrans << cFYaw, sFYaw, 0.0,\n\t\t              -sFYaw, cFYaw, 0.0,\n\t\t              0.0, 0.0, 1.0;\n\n\t\t// Remove the fused yaw component of the rotation\n\t\tRout = RFYawTrans * R;\n\t}\n\n\t// Remove Euler yaw from: Quaternion\n\tvoid QuatNoEYaw(const Quat& q, Quat& qout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfQuat(q);\n\n\t\t// Construct the Euler ZYX yaw component of the rotation\n\t\tdouble hcEYaw = cos(0.5*EYaw);\n\t\tdouble hsEYaw = sin(0.5*EYaw);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tqout.w() = hcEYaw*q.w() + hsEYaw*q.z();\n\t\tqout.x() = hcEYaw*q.x() + hsEYaw*q.y();\n\t\tqout.y() = hcEYaw*q.y() - hsEYaw*q.x();\n\t\tqout.z() = hcEYaw*q.z() - hsEYaw*q.w();\n\t}\n\n\t// Remove fused yaw from: Quaternion\n\tvoid QuatNoFYaw(const Quat& q, Quat& qout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfQuat(q);\n\n\t\t// Construct the fused yaw component of the rotation\n\t\tdouble hcFYaw = cos(0.5*FYaw);\n\t\tdouble hsFYaw = sin(0.5*FYaw);\n\n\t\t// Remove the fused yaw component of the rotation\n\t\tqout.w() = hcFYaw*q.w() + hsFYaw*q.z();\n\t\tqout.x() = hcFYaw*q.x() + hsFYaw*q.y();\n\t\tqout.y() = hcFYaw*q.y() - hsFYaw*q.x();\n\t\tqout.z() = hcFYaw*q.z() - hsFYaw*q.w();\n\t}\n\n\t// Remove yaw from: Euler angles\n\tvoid EulerNoFYaw(const EulerAngles& e, EulerAngles& eout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfEuler(e);\n\n\t\t// Remove the fused yaw component of the rotation\n\t\teout.yaw = e.yaw - FYaw;\n\t\teout.pitch = e.pitch;\n\t\teout.roll = e.roll;\n\t}\n\n\t// Remove yaw from: Fused angles\n\tvoid FusedNoEYaw(const FusedAngles& f, FusedAngles& fout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfFused(f);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\tfout.fusedYaw = f.fusedYaw - EYaw;\n\t\tfout.fusedPitch = f.fusedPitch;\n\t\tfout.fusedRoll = f.fusedRoll;\n\t\tfout.hemi = f.hemi;\n\t}\n\n\t// Remove yaw from: Tilt angles\n\tvoid TiltNoEYaw(const TiltAngles& t, TiltAngles& tout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfTilt(t);\n\n\t\t// Remove the Euler ZYX yaw component of the rotation\n\t\ttout.fusedYaw = t.fusedYaw - EYaw;\n\t\ttout.tiltAxisAngle = t.tiltAxisAngle;\n\t\ttout.tiltAngle = t.tiltAngle;\n\t}\n\n\t// #################################\n\t// #### Rotation with given yaw ####\n\t// #################################\n\n\t// Rotation with given Euler yaw: Rotation matrix\n\tvoid RotmatWithEYaw(const Rotmat& R, double eulerYaw, Rotmat& Rout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble deltaEYaw = eulerYaw - EYaw;\n\t\tdouble cdEYaw = cos(deltaEYaw);\n\t\tdouble sdEYaw = sin(deltaEYaw);\n\n\t\t// Construct the yaw adjustment rotation\n\t\tRotmat REYawAdj;\n\t\tREYawAdj << cdEYaw, -sdEYaw, 0.0,\n\t\t            sdEYaw, cdEYaw, 0.0,\n\t\t            0.0, 0.0, 1.0;\n\n\t\t// Adjust the Euler ZYX yaw component of the rotation\n\t\tRout = REYawAdj * R;\n\t}\n\n\t// Rotation with given fused yaw: Rotation matrix\n\tvoid RotmatWithFYaw(const Rotmat& R, double fusedYaw, Rotmat& Rout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfRotmat(R);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble deltaFYaw = fusedYaw - FYaw;\n\t\tdouble cdFYaw = cos(deltaFYaw);\n\t\tdouble sdFYaw = sin(deltaFYaw);\n\n\t\t// Construct the yaw adjustment rotation\n\t\tRotmat RFYawAdj;\n\t\tRFYawAdj << cdFYaw, -sdFYaw, 0.0,\n\t\t            sdFYaw, cdFYaw, 0.0,\n\t\t            0.0, 0.0, 1.0;\n\n\t\t// Adjust the fused yaw component of the rotation\n\t\tRout = RFYawAdj * R;\n\t}\n\n\t// Rotation with given Euler yaw: Quaternion\n\tvoid QuatWithEYaw(const Quat& q, double eulerYaw, Quat& qout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfQuat(q);\n\n\t\t// Construct the components of the Euler ZYX yaw adjustment rotation\n\t\tdouble hdeltaEYaw = 0.5*(eulerYaw - EYaw);\n\t\tdouble hcdEYaw = cos(hdeltaEYaw);\n\t\tdouble hsdEYaw = sin(hdeltaEYaw);\n\n\t\t// Adjust the Euler ZYX yaw component of the rotation\n\t\tqout.w() = hcdEYaw*q.w() - hsdEYaw*q.z();\n\t\tqout.x() = hcdEYaw*q.x() - hsdEYaw*q.y();\n\t\tqout.y() = hcdEYaw*q.y() + hsdEYaw*q.x();\n\t\tqout.z() = hcdEYaw*q.z() + hsdEYaw*q.w();\n\t}\n\n\t// Rotation with given fused yaw: Quaternion\n\tvoid QuatWithFYaw(const Quat& q, double fusedYaw, Quat& qout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfQuat(q);\n\n\t\t// Construct the components of the fused yaw adjustment rotation\n\t\tdouble hdeltaFYaw = 0.5*(fusedYaw - FYaw);\n\t\tdouble hcdFYaw = cos(hdeltaFYaw);\n\t\tdouble hsdFYaw = sin(hdeltaFYaw);\n\n\t\t// Adjust the fused yaw component of the rotation\n\t\tqout.w() = hcdFYaw*q.w() - hsdFYaw*q.z();\n\t\tqout.x() = hcdFYaw*q.x() - hsdFYaw*q.y();\n\t\tqout.y() = hcdFYaw*q.y() + hsdFYaw*q.x();\n\t\tqout.z() = hcdFYaw*q.z() + hsdFYaw*q.w();\n\t}\n\n\t// Rotation with given fused yaw: Euler angles\n\tvoid EulerWithFYaw(const EulerAngles& e, double fusedYaw, EulerAngles& eout)\n\t{\n\t\t// Calculate the fused yaw of the input\n\t\tdouble FYaw = FYawOfEuler(e);\n\n\t\t// Adjust the fused yaw component of the rotation\n\t\teout.yaw = e.yaw + (fusedYaw - FYaw);\n\t\teout.pitch = e.pitch;\n\t\teout.roll = e.roll;\n\t}\n\n\t// Rotation with given Euler yaw: Fused angles\n\tvoid FusedWithEYaw(const FusedAngles& f, double eulerYaw, FusedAngles& fout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfFused(f);\n\n\t\t// Adjust the Euler ZYX yaw component of the rotation\n\t\tfout.fusedYaw = f.fusedYaw + (eulerYaw - EYaw);\n\t\tfout.fusedPitch = f.fusedPitch;\n\t\tfout.fusedRoll = f.fusedRoll;\n\t\tfout.hemi = f.hemi;\n\t}\n\n\t// Rotation with given Euler yaw: Tilt angles\n\tvoid TiltWithEYaw(const TiltAngles& t, double eulerYaw, TiltAngles& tout)\n\t{\n\t\t// Calculate the Euler ZYX yaw of the input\n\t\tdouble EYaw = EYawOfTilt(t);\n\n\t\t// Adjust the Euler ZYX yaw component of the rotation\n\t\ttout.fusedYaw = t.fusedYaw + (eulerYaw - EYaw);\n\t\ttout.tiltAxisAngle = t.tiltAxisAngle;\n\t\ttout.tiltAngle = t.tiltAngle;\n\t}\n\n\t// ###########################\n\t// #### Rotation inverses ####\n\t// ###########################\n\n\t// Inverse: Rotation matrix\n\tvoid RotmatInv(const Rotmat& R, Rotmat& Rinv)\n\t{\n\t\t// Calculate the inverse of the rotation\n\t\tRinv = R.transpose();\n\t}\n\n\t// Inverse: Quaternion\n\tvoid QuatInv(const Quat& q, Quat& qinv)\n\t{\n\t\t// Calculate the inverse of the rotation\n\t\tqinv.w() = q.w();\n\t\tqinv.x() = -q.x();\n\t\tqinv.y() = -q.y();\n\t\tqinv.z() = -q.z();\n\t}\n\n\t// Inverse: Euler angles\n\tvoid EulerInv(const EulerAngles& e, EulerAngles& einv)\n\t{\n\t\t// Precalculate the required sin and cos values\n\t\tdouble cpsi = cos(e.yaw);\n\t\tdouble spsi = sin(e.yaw);\n\t\tdouble cth = cos(e.pitch);\n\t\tdouble sth = sin(e.pitch);\n\t\tdouble cphi = cos(e.roll);\n\t\tdouble sphi = sin(e.roll);\n\n\t\t// Calculate the sine of the inverse pitch angle\n\t\tdouble sthinv = -(cpsi*sth*cphi + spsi*sphi);\n\t\tsthinv = (sthinv >= 1.0 ? 1.0 : (sthinv <= -1.0 ? -1.0 : sthinv)); // Coerce sthinv to [-1,1]\n\n\t\t// Calculate the required inverse Euler angles representation\n\t\teinv.yaw = atan2(cpsi*sth*sphi - spsi*cphi, cpsi*cth);\n\t\teinv.pitch = asin(sthinv);\n\t\teinv.roll = atan2(spsi*sth*cphi - cpsi*sphi, cth*cphi);\n\t}\n\n\t// Inverse: Fused angles\n\tvoid FusedInv(const FusedAngles& f, FusedAngles& finv)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth  = sin(f.fusedPitch);\n\t\tdouble sphi = sin(f.fusedRoll);\n\n\t\t// Calculate the sine of the tilt angle alpha\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble salpha = (crit >= 1.0 ? 1.0 : sqrt(crit));\n\n\t\t// Calculate the tilt axis gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate trigonometric values\n\t\tdouble psigam = f.fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\n\t\t// Calculate the inverse fused pitch and roll\n\t\tdouble thinv = asin(-salpha*spsigam);\n\t\tdouble phinv = asin(-salpha*cpsigam);\n\n\t\t// Construct the inverse fused angles rotation\n\t\tfinv.fusedYaw = -f.fusedYaw;\n\t\tfinv.fusedPitch = thinv;\n\t\tfinv.fusedRoll = phinv;\n\t\tfinv.hemi = f.hemi;\n\t}\n\n\t// Inverse: Tilt angles\n\tvoid TiltInv(const TiltAngles& t, TiltAngles& tinv)\n\t{\n\t\t// Calculate the inverse tilt axis angle\n\t\tdouble gammainv = internal::picut(t.fusedYaw + t.tiltAxisAngle - M_PI);\n\n\t\t// Construct the inverse tilt angles rotation\n\t\ttinv.fusedYaw = -t.fusedYaw;\n\t\ttinv.tiltAxisAngle = gammainv;\n\t\ttinv.tiltAngle = t.tiltAngle;\n\t}\n\n\t// ##########################\n\t// #### Vector rotations ####\n\t// ##########################\n\n\t// Rotate vector by: Rotation matrix\n\tVec3 RotmatRotVec(const Rotmat& R, const Vec3& v)\n\t{\n\t\t// Return the required vector\n\t\treturn R*v;\n\t}\n\n\t// Rotate vector by: Rotation matrix (in-place)\n\tvoid RotmatRotVecInPlace(const Rotmat& R, Vec3& v)\n\t{\n\t\t// Calculate the required vector\n\t\tv = R*v;\n\t}\n\n\t// Rotate pure z-vector by: Rotation matrix\n\tVec3 RotmatRotVecPureZ(const Rotmat& R, double vz)\n\t{\n\t\t// Return the required vector\n\t\treturn R.col(2)*vz;\n\t}\n\n\t// Rotate vector by: Quaternion\n\tVec3 QuatRotVec(const Quat& q, const Vec3& v)\n\t{\n\t\t// Precalculate an intermediate vector term\n\t\tdouble tx = 2.0*(q.y()*v.z() - v.y()*q.z());\n\t\tdouble ty = 2.0*(q.z()*v.x() - v.z()*q.x());\n\t\tdouble tz = 2.0*(q.x()*v.y() - v.x()*q.y());\n\n\t\t// Calculate and return the required vector\n\t\tVec3 vout = v;\n\t\tvout.x() += q.w()*tx + q.y()*tz - ty*q.z();\n\t\tvout.y() += q.w()*ty + q.z()*tx - tz*q.x();\n\t\tvout.z() += q.w()*tz + q.x()*ty - tx*q.y();\n\t\treturn vout;\n\t}\n\n\t// Rotate vector by: Quaternion (in-place)\n\tvoid QuatRotVecInPlace(const Quat& q, Vec3& v)\n\t{\n\t\t// Precalculate an intermediate vector term\n\t\tdouble tx = 2.0*(q.y()*v.z() - v.y()*q.z());\n\t\tdouble ty = 2.0*(q.z()*v.x() - v.z()*q.x());\n\t\tdouble tz = 2.0*(q.x()*v.y() - v.x()*q.y());\n\n\t\t// Calculate the required vector\n\t\tv.x() += q.w()*tx + q.y()*tz - ty*q.z();\n\t\tv.y() += q.w()*ty + q.z()*tx - tz*q.x();\n\t\tv.z() += q.w()*tz + q.x()*ty - tx*q.y();\n\t}\n\n\t// Rotate pure z-vector by: Quaternion\n\tVec3 QuatRotVecPureZ(const Quat& q, double vz)\n\t{\n\t\t// Calculate and return the required vector\n\t\treturn Vec3(vz*2.0*(q.x()*q.z() + q.y()*q.w()), vz*2.0*(q.y()*q.z() - q.x()*q.w()), vz*(1.0 - 2.0*(q.x()*q.x() + q.y()*q.y())));\n\t}\n\n\t// Rotate vector by: Euler angles\n\tVec3 EulerRotVec(const EulerAngles& e, const Vec3& v)\n\t{\n\t\t// Return the required vector\n\t\treturn RotmatFromEuler(e)*v;\n\t}\n\n\t// Rotate vector by: Euler angles (in-place)\n\tvoid EulerRotVecInPlace(const EulerAngles& e, Vec3& v)\n\t{\n\t\t// Calculate the required vector\n\t\tv = RotmatFromEuler(e)*v;\n\t}\n\n\t// Rotate pure z-vector by: Euler angles\n\tVec3 EulerRotVecPureZ(const EulerAngles& e, double vz)\n\t{\n\t\t// Precalculate the trigonometric values\n\t\tdouble cpsi = cos(e.yaw);\n\t\tdouble spsi = sin(e.yaw);\n\t\tdouble cth  = cos(e.pitch);\n\t\tdouble sth  = sin(e.pitch);\n\t\tdouble cphi = cos(e.roll);\n\t\tdouble sphi = sin(e.roll);\n\n\t\t// Calculate and return the required vector\n\t\treturn Vec3(vz*(cpsi*sth*cphi + spsi*sphi), vz*(spsi*sth*cphi - cpsi*sphi), vz*(cth*cphi));\n\t}\n\n\t// Rotate vector by: Fused angles\n\tVec3 FusedRotVec(const FusedAngles& f, const Vec3& v)\n\t{\n\t\t// Return the required vector\n\t\treturn RotmatFromFused(f)*v;\n\t}\n\n\t// Rotate vector by: Fused angles (in-place)\n\tvoid FusedRotVecInPlace(const FusedAngles& f, Vec3& v)\n\t{\n\t\t// Calculate the required vector\n\t\tv = RotmatFromFused(f)*v;\n\t}\n\n\t// Rotate pure z-vector by: Fused angles\n\tVec3 FusedRotVecPureZ(const FusedAngles& f, double vz)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(f.fusedPitch);\n\t\tdouble sphi = sin(f.fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the tilt angle alpha\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tsalpha = 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = (f.hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t\tsalpha = sqrt(crit);\n\t\t}\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms involved in the vector expression\n\t\tdouble psigam = f.fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\n\t\t// Calculate and return the required vector\n\t\treturn Vec3(vz*salpha*spsigam, -vz*salpha*cpsigam, vz*calpha);\n\t}\n\n\t// Rotate vector by: Tilt angles\n\tVec3 TiltRotVec(const TiltAngles& t, const Vec3& v)\n\t{\n\t\t// Return the required vector\n\t\treturn RotmatFromTilt(t)*v;\n\t}\n\n\t// Rotate vector by: Tilt angles (in-place)\n\tvoid TiltRotVecInPlace(const TiltAngles& t, Vec3& v)\n\t{\n\t\t// Return the required vector\n\t\tv = RotmatFromTilt(t)*v;\n\t}\n\n\t// Rotate pure z-vector by: Tilt angles\n\tVec3 TiltRotVecPureZ(const TiltAngles& t, double vz)\n\t{\n\t\t// Precalculate terms involved in the vector expression\n\t\tdouble calpha = cos(t.tiltAngle);\n\t\tdouble salpha = sin(t.tiltAngle);\n\t\tdouble psigam = t.fusedYaw + t.tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\n\t\t// Calculate and return the required vector\n\t\treturn Vec3(vz*salpha*spsigam, -vz*salpha*cpsigam, vz*calpha);\n\t}\n\n\t// #########################################\n\t// #### Rotation about global unit axis ####\n\t// #########################################\n\n\t// Rotate about global x-axis: Rotation matrix\n\tvoid RotmatRotGlobalX(const Rotmat& R, double angle, Rotmat& Rout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tRout << R.coeff(0,0), R.coeff(0,1), R.coeff(0,2),\n\t\t        R.coeff(1,0)*cang - R.coeff(2,0)*sang, R.coeff(1,1)*cang - R.coeff(2,1)*sang, R.coeff(1,2)*cang - R.coeff(2,2)*sang,\n\t\t        R.coeff(2,0)*cang + R.coeff(1,0)*sang, R.coeff(2,1)*cang + R.coeff(1,1)*sang, R.coeff(2,2)*cang + R.coeff(1,2)*sang;\n\t}\n\n\t// Rotate about global y-axis: Rotation matrix\n\tvoid RotmatRotGlobalY(const Rotmat& R, double angle, Rotmat& Rout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tRout << R.coeff(0,0)*cang + R.coeff(2,0)*sang, R.coeff(0,1)*cang + R.coeff(2,1)*sang, R.coeff(0,2)*cang + R.coeff(2,2)*sang,\n\t\t        R.coeff(1,0), R.coeff(1,1), R.coeff(1,2),\n\t\t        R.coeff(2,0)*cang - R.coeff(0,0)*sang, R.coeff(2,1)*cang - R.coeff(0,1)*sang, R.coeff(2,2)*cang - R.coeff(0,2)*sang;\n\t}\n\n\t// Rotate about global z-axis: Rotation matrix\n\tvoid RotmatRotGlobalZ(const Rotmat& R, double angle, Rotmat& Rout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tRout << R.coeff(0,0)*cang - R.coeff(1,0)*sang, R.coeff(0,1)*cang - R.coeff(1,1)*sang, R.coeff(0,2)*cang - R.coeff(1,2)*sang,\n\t\t        R.coeff(1,0)*cang + R.coeff(0,0)*sang, R.coeff(1,1)*cang + R.coeff(0,1)*sang, R.coeff(1,2)*cang + R.coeff(0,2)*sang,\n\t\t        R.coeff(2,0), R.coeff(2,1), R.coeff(2,2);\n\t}\n\n\t// Rotate about global x-axis: Quaternion\n\tvoid QuatRotGlobalX(const Quat& q, double angle, Quat& qout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble hcang = cos(0.5*angle);\n\t\tdouble hsang = sin(0.5*angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tqout.w() = hcang*q.w() - hsang*q.x();\n\t\tqout.x() = hcang*q.x() + hsang*q.w();\n\t\tqout.y() = hcang*q.y() - hsang*q.z();\n\t\tqout.z() = hcang*q.z() + hsang*q.y();\n\t}\n\n\t// Rotate about global y-axis: Quaternion\n\tvoid QuatRotGlobalY(const Quat& q, double angle, Quat& qout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble hcang = cos(0.5*angle);\n\t\tdouble hsang = sin(0.5*angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tqout.w() = hcang*q.w() - hsang*q.y();\n\t\tqout.x() = hcang*q.x() + hsang*q.z();\n\t\tqout.y() = hcang*q.y() + hsang*q.w();\n\t\tqout.z() = hcang*q.z() - hsang*q.x();\n\t}\n\n\t// Rotate about global z-axis: Quaternion\n\tvoid QuatRotGlobalZ(const Quat& q, double angle, Quat& qout)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble hcang = cos(0.5*angle);\n\t\tdouble hsang = sin(0.5*angle);\n\n\t\t// Calculate the required rotated rotation\n\t\tqout.w() = hcang*q.w() - hsang*q.z();\n\t\tqout.x() = hcang*q.x() - hsang*q.y();\n\t\tqout.y() = hcang*q.y() + hsang*q.x();\n\t\tqout.z() = hcang*q.z() + hsang*q.w();\n\t}\n\n\t// Rotate about global x-axis: Euler angles\n\tvoid EulerRotGlobalX(const EulerAngles& e, double angle, EulerAngles& eout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromEuler(e), qout;\n\t\tQuatRotGlobalX(q, angle, qout);\n\t\tEulerFromQuat(qout, eout);\n\t}\n\n\t// Rotate about global y-axis: Euler angles\n\tvoid EulerRotGlobalY(const EulerAngles& e, double angle, EulerAngles& eout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromEuler(e), qout;\n\t\tQuatRotGlobalY(q, angle, qout);\n\t\tEulerFromQuat(qout, eout);\n\t}\n\n\t// Rotate about global x-axis: Fused angles\n\tvoid FusedRotGlobalX(const FusedAngles& f, double angle, FusedAngles& fout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromFused(f), qout;\n\t\tQuatRotGlobalX(q, angle, qout);\n\t\tFusedFromQuat(qout, fout);\n\t}\n\n\t// Rotate about global y-axis: Fused angles\n\tvoid FusedRotGlobalY(const FusedAngles& f, double angle, FusedAngles& fout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromFused(f), qout;\n\t\tQuatRotGlobalY(q, angle, qout);\n\t\tFusedFromQuat(qout, fout);\n\t}\n\n\t// Rotate about global x-axis: Tilt angles\n\tvoid TiltRotGlobalX(const TiltAngles& t, double angle, TiltAngles& tout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromTilt(t), qout;\n\t\tQuatRotGlobalX(q, angle, qout);\n\t\tTiltFromQuat(qout, tout);\n\t}\n\n\t// Rotate about global y-axis: Tilt angles\n\tvoid TiltRotGlobalY(const TiltAngles& t, double angle, TiltAngles& tout)\n\t{\n\t\t// Calculate the required rotated rotation\n\t\tQuat q = QuatFromTilt(t), qout;\n\t\tQuatRotGlobalY(q, angle, qout);\n\t\tTiltFromQuat(qout, tout);\n\t}\n\n\t// #####################################\n\t// #### Conversions from axis angle ####\n\t// #####################################\n\n\t// Conversion: Axis angle (unit axis) --> Rotation matrix\n\tvoid RotmatFromAxis(UnitAxis axis, double angle, Rotmat& R)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\n\t\t// Calculate the required rotation matrix\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\tR << 1.0, 0.0, 0.0,\n\t\t\t     0.0, cang, -sang,\n\t\t\t     0.0, sang, cang;\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tR << cang, 0.0, sang,\n\t\t\t     0.0, 1.0, 0.0,\n\t\t\t     -sang, 0.0, cang;\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\tR << cang, -sang, 0.0,\n\t\t\t     sang, cang, 0.0,\n\t\t\t     0.0, 0.0, 1.0;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Rotation matrix\n\tvoid RotmatFromAxis(const Vec3& axis, double angle, Rotmat& R)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\t\tdouble C = 1.0 - cang;\n\n\t\t// Precalculate values\n\t\tdouble xC = axis.x()*C;\n\t\tdouble yC = axis.y()*C;\n\t\tdouble zC = axis.z()*C;\n\t\tdouble xxC = axis.x()*xC;\n\t\tdouble yyC = axis.y()*yC;\n\t\tdouble zzC = axis.z()*zC;\n\t\tdouble xyC = axis.x()*yC;\n\t\tdouble yzC = axis.y()*zC;\n\t\tdouble zxC = axis.z()*xC;\n\t\tdouble xs = axis.x()*sang;\n\t\tdouble ys = axis.y()*sang;\n\t\tdouble zs = axis.z()*sang;\n\n\t\t// Calculate the required rotation matrix\n\t\tR << xxC + cang, xyC - zs, zxC + ys,\n\t\t     xyC + zs, yyC + cang, yzC - xs,\n\t\t     zxC - ys, yzC + xs, zzC + cang;\n\t}\n\n\t// Conversion: Axis angle (unit axis) --> Quaternion\n\tvoid QuatFromAxis(UnitAxis axis, double angle, Quat& q)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble hcang = cos(0.5*angle);\n\t\tdouble hsang = sin(0.5*angle);\n\n\t\t// Calculate the required quaternion\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\tq.w() = hcang;\n\t\t\tq.x() = hsang;\n\t\t\tq.y() = 0.0;\n\t\t\tq.z() = 0.0;\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tq.w() = hcang;\n\t\t\tq.x() = 0.0;\n\t\t\tq.y() = hsang;\n\t\t\tq.z() = 0.0;\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\tq.w() = hcang;\n\t\t\tq.x() = 0.0;\n\t\t\tq.y() = 0.0;\n\t\t\tq.z() = hsang;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Quaternion\n\tvoid QuatFromAxis(const Vec3& axis, double angle, Quat& q)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble hcang = cos(0.5*angle);\n\t\tdouble hsang = sin(0.5*angle);\n\n\t\t// Calculate the required quaternion\n\t\tdouble normsq = VecNormSq(axis);\n\t\tif(normsq <= 0.0)\n\t\t\tq.setIdentity();\n\t\telse\n\t\t{\n\t\t\tdouble scale = hsang / sqrt(normsq);\n\t\t\tq.w() = hcang;\n\t\t\tq.x() = axis.x() * scale;\n\t\t\tq.y() = axis.y() * scale;\n\t\t\tq.z() = axis.z() * scale;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle (unit axis) --> Euler angles\n\tvoid EulerFromAxis(UnitAxis axis, double angle, EulerAngles& e)\n\t{\n\t\t// Wrap the rotation angle to (-pi,pi]\n\t\tinternal::picutVar(angle);\n\n\t\t// Calculate the required Euler angles\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\te.yaw = 0.0;\n\t\t\te.pitch = 0.0;\n\t\t\te.roll = angle;\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tif(fabs(angle) <= M_PI_2)\n\t\t\t{\n\t\t\t\te.yaw = 0.0;\n\t\t\t\te.pitch = angle;\n\t\t\t\te.roll = 0.0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\te.yaw = M_PI;\n\t\t\t\te.pitch = (angle >= M_PI_2 ? M_PI - angle : -M_PI - angle);\n\t\t\t\te.roll = M_PI;\n\t\t\t}\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\te.yaw = angle;\n\t\t\te.pitch = 0.0;\n\t\t\te.roll = 0.0;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Euler angles\n\tvoid EulerFromAxis(const Vec3& axis, double angle, EulerAngles& e)\n\t{\n\t\t// Calculate the required Euler angles via the quaternion space\n\t\tQuat q;\n\t\tQuatFromAxis(axis, angle, q);\n\t\tEulerFromQuat(q, e);\n\t}\n\n\t// Conversion: Axis angle (unit axis) --> Fused angles\n\tvoid FusedFromAxis(UnitAxis axis, double angle, FusedAngles& f)\n\t{\n\t\t// Wrap the rotation angle to (-pi,pi]\n\t\tinternal::picutVar(angle);\n\n\t\t// Calculate the required fused angles\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\tif(fabs(angle) <= M_PI_2)\n\t\t\t{\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t\t\tf.fusedPitch = 0.0;\n\t\t\t\tf.fusedRoll = angle;\n\t\t\t\tf.hemi = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t\t\tf.fusedPitch = 0.0;\n\t\t\t\tf.fusedRoll = (angle >= M_PI_2 ? M_PI - angle : -M_PI - angle);\n\t\t\t\tf.hemi = false;\n\t\t\t}\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tif(fabs(angle) <= M_PI_2)\n\t\t\t{\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t\t\tf.fusedPitch = angle;\n\t\t\t\tf.fusedRoll = 0.0;\n\t\t\t\tf.hemi = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tf.fusedYaw = 0.0;\n\t\t\t\tf.fusedPitch = (angle >= M_PI_2 ? M_PI - angle : -M_PI - angle);\n\t\t\t\tf.fusedRoll = 0.0;\n\t\t\t\tf.hemi = false;\n\t\t\t}\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\tf.fusedYaw = angle;\n\t\t\tf.fusedPitch = 0.0;\n\t\t\tf.fusedRoll = 0.0;\n\t\t\tf.hemi = true;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Fused angles\n\tvoid FusedFromAxis(const Vec3& axis, double angle, FusedAngles& f)\n\t{\n\t\t// Calculate the required fused angles via the quaternion space\n\t\tQuat q;\n\t\tQuatFromAxis(axis, angle, q);\n\t\tFusedFromQuat(q, f);\n\t}\n\n\t// Conversion: Axis angle (unit axis) --> Tilt angles\n\tvoid TiltFromAxis(UnitAxis axis, double angle, TiltAngles& t)\n\t{\n\t\t// Wrap the rotation angle to (-pi,pi]\n\t\tinternal::picutVar(angle);\n\n\t\t// Calculate the required fused angles\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\tt.fusedYaw = 0.0;\n\t\t\tif(angle >= 0.0)\n\t\t\t{\n\t\t\t\tt.tiltAxisAngle = 0.0;\n\t\t\t\tt.tiltAngle = angle;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tt.tiltAxisAngle = M_PI;\n\t\t\t\tt.tiltAngle = -angle;\n\t\t\t}\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tt.fusedYaw = 0.0;\n\t\t\tif(angle >= 0.0)\n\t\t\t{\n\t\t\t\tt.tiltAxisAngle = M_PI_2;\n\t\t\t\tt.tiltAngle = angle;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tt.tiltAxisAngle = -M_PI_2;\n\t\t\t\tt.tiltAngle = -angle;\n\t\t\t}\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\tt.fusedYaw = angle;\n\t\t\tt.tiltAxisAngle = 0.0;\n\t\t\tt.tiltAngle = 0.0;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Tilt angles\n\tvoid TiltFromAxis(const Vec3& axis, double angle, TiltAngles& t)\n\t{\n\t\t// Calculate the required tilt angles via the quaternion space\n\t\tQuat q;\n\t\tQuatFromAxis(axis, angle, q);\n\t\tTiltFromQuat(q, t);\n\t}\n\n\t// Conversion: Axis angle (unit axis) --> Z vector\n\tvoid ZVecFromAxis(UnitAxis axis, double angle, ZVec& z)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\n\t\t// Calculate the required Z vector\n\t\tif(axis == X_AXIS)\n\t\t{\n\t\t\tz.x() = 0.0;\n\t\t\tz.y() = sang;\n\t\t\tz.z() = cang;\n\t\t}\n\t\telse if(axis == Y_AXIS)\n\t\t{\n\t\t\tz.x() = -sang;\n\t\t\tz.y() = 0.0;\n\t\t\tz.z() = cang;\n\t\t}\n\t\telse // Z_AXIS\n\t\t{\n\t\t\tz.x() = 0.0;\n\t\t\tz.y() = 0.0;\n\t\t\tz.z() = 1.0;\n\t\t}\n\t}\n\n\t// Conversion: Axis angle --> Z vector\n\tvoid ZVecFromAxis(const Vec3& axis, double angle, ZVec& z)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cang = cos(angle);\n\t\tdouble sang = sin(angle);\n\t\tdouble zC = axis.z()*(1.0 - cang);\n\n\t\t// Calculate the required Z vector\n\t\tz.x() = axis.x()*zC - axis.y()*sang;\n\t\tz.y() = axis.y()*zC + axis.x()*sang;\n\t\tz.z() = axis.z()*zC + cang;\n\t}\n\n\t// ############################################\n\t// #### Conversions from rotation matrices ####\n\t// ############################################\n\n\t//\n\t// Conversion: Rotation matrix --> Quaternion\n\t//\n\n\t// Conversion: Rotation matrix --> Quaternion\n\tvoid QuatFromRotmat(const Rotmat& R, Quat& q)\n\t{\n\t\t// Perform the required conversion in a numerically stable manner\n\t\tdouble r, s, t = R.coeff(0,0) + R.coeff(1,1) + R.coeff(2,2);\n\t\tif(t >= 0.0)\n\t\t{\n\t\t\tr = sqrt(1.0 + t);\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = 0.5*r;\n\t\t\tq.x() = s*(R.coeff(2,1) - R.coeff(1,2));\n\t\t\tq.y() = s*(R.coeff(0,2) - R.coeff(2,0));\n\t\t\tq.z() = s*(R.coeff(1,0) - R.coeff(0,1));\n\t\t}\n\t\telse if(R.coeff(2,2) >= R.coeff(1,1) && R.coeff(2,2) >= R.coeff(0,0))\n\t\t{\n\t\t\tr = sqrt(1.0 - (R.coeff(0,0) + R.coeff(1,1) - R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(1,0) - R.coeff(0,1));\n\t\t\tq.x() = s*(R.coeff(0,2) + R.coeff(2,0));\n\t\t\tq.y() = s*(R.coeff(2,1) + R.coeff(1,2));\n\t\t\tq.z() = 0.5*r;\n\t\t}\n\t\telse if(R.coeff(1,1) >= R.coeff(0,0))\n\t\t{\n\t\t\tr = sqrt(1.0 - (R.coeff(0,0) - R.coeff(1,1) + R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(0,2) - R.coeff(2,0));\n\t\t\tq.x() = s*(R.coeff(1,0) + R.coeff(0,1));\n\t\t\tq.y() = 0.5*r;\n\t\t\tq.z() = s*(R.coeff(2,1) + R.coeff(1,2));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tr = sqrt(1.0 + (R.coeff(0,0) - R.coeff(1,1) - R.coeff(2,2)));\n\t\t\ts = 0.5/r;\n\t\t\tq.w() = s*(R.coeff(2,1) - R.coeff(1,2));\n\t\t\tq.x() = 0.5*r;\n\t\t\tq.y() = s*(R.coeff(1,0) + R.coeff(0,1));\n\t\t\tq.z() = s*(R.coeff(0,2) + R.coeff(2,0));\n\t\t}\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Euler angles\n\t//\n\n\t// Conversion: Rotation matrix --> Euler angles\n\tvoid EulerFromRotmat(const Rotmat& R, double& yaw, double& pitch, double& roll)\n\t{\n\t\t// Calculate the sine of the pitch angle\n\t\tdouble sth = -R.coeff(2,0);\n\t\tsth = (sth >= 1.0 ? 1.0 : (sth <= -1.0 ? -1.0 : sth)); // Coerce sth to [-1,1]\n\n\t\t// Calculate the required Euler angles\n\t\tyaw = atan2(R.coeff(1,0), R.coeff(0,0));\n\t\tpitch = asin(sth);\n\t\troll = atan2(R.coeff(2,1), R.coeff(2,2));\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Fused angles\n\t//\n\n\t// Conversion: Rotation matrix --> Fused angles (2D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = -R.coeff(2,0);\n\t\tdouble sphi   = R.coeff(2,1);\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Rotation matrix --> Fused angles (3D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedYaw, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tFusedFromRotmat(R, fusedPitch, fusedRoll);\n\t}\n\n\t// Conversion: Rotation matrix --> Fused angles (4D)\n\tvoid FusedFromRotmat(const Rotmat& R, double& fusedYaw, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tFusedFromRotmat(R, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere of the rotation\n\t\themi = (R.coeff(2,2) >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Tilt angles\n\t//\n\n\t// Conversion: Rotation matrix --> Tilt angles (2D)\n\tvoid TiltFromRotmat(const Rotmat& R, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(-R.coeff(2,0), R.coeff(2,1));\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = R.coeff(2,2);\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n\n\t// Conversion: Rotation matrix --> Tilt angles (3D)\n\tvoid TiltFromRotmat(const Rotmat& R, double& fusedYaw, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the fused yaw, tilt axis angle and tilt angle\n\t\tfusedYaw = FYawOfRotmat(R);\n\t\tTiltFromRotmat(R, tiltAxisAngle, tiltAngle);\n\t}\n\n\t//\n\t// Conversion: Rotation matrix --> Tilt phase\n\t//\n\n\t// Conversion: Rotation matrix --> Tilt phase (2D)\n\tvoid PhaseFromRotmat(const Rotmat& R, double& px, double& py)\n\t{\n\t\t// Calculate the sin of the tilt angle alpha\n\t\tdouble salpha = sqrt(R.coeff(2,0)*R.coeff(2,0) + R.coeff(2,1)*R.coeff(2,1));\n\n\t\t// Calculate the required x and y tilt phase components\n\t\tif(salpha == 0.0)\n\t\t{\n\t\t\tif(R.coeff(2,2) >= 0.0)\n\t\t\t\tpx = py = 0.0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble cdgamma = 0.5*(R.coeff(0,0) - R.coeff(1,1));\n\t\t\t\tdouble sdgamma = 0.5*(R.coeff(0,1) + R.coeff(1,0));\n\t\t\t\tpx = M_PI * sqrt(std::max(0.5*(1.0 + cdgamma), 0.0));\n\t\t\t\tpy = M_PI * sqrt(std::max(0.5*(1.0 - cdgamma), 0.0));\n\t\t\t\tif(sdgamma < 0.0)\n\t\t\t\t\tpy = -py;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble calpha = std::max(std::min(R.coeff(2,2), 1.0), -1.0);\n\t\t\tdouble alpha = acos(calpha);\n\t\t\tpx = alpha * ( R.coeff(2,1) / salpha);\n\t\t\tpy = alpha * (-R.coeff(2,0) / salpha);\n\t\t}\n\t}\n\n\t// Conversion: Rotation matrix --> Tilt phase (3D)\n\tvoid PhaseFromRotmat(const Rotmat& R, double& px, double& py, double& pz)\n\t{\n\t\t// Calculate the tilt phase components\n\t\tpz = FYawOfRotmat(R);\n\t\tPhaseFromRotmat(R, px, py);\n\t}\n\n\t// ######################################\n\t// #### Conversions from quaternions ####\n\t// ######################################\n\n\t//\n\t// Conversion: Quaternion --> Axes\n\t//\n\n\t// Conversion: Quaternion --> X-axis\n\tvoid AxisXFromQuat(const Quat& q, Vec3& axis)\n\t{\n\t\t// Construct the required axis\n\t\taxis.x() = 1.0 - 2.0*(q.y()*q.y() + q.z()*q.z());\n\t\taxis.y() = 2.0*(q.x()*q.y() + q.z()*q.w());\n\t\taxis.z() = 2.0*(q.x()*q.z() - q.y()*q.w());\n\t}\n\n\t// Conversion: Quaternion --> Y-axis\n\tvoid AxisYFromQuat(const Quat& q, Vec3& axis)\n\t{\n\t\t// Construct the required axis\n\t\taxis.x() = 2.0*(q.x()*q.y() - q.z()*q.w());\n\t\taxis.y() = 1.0 - 2.0*(q.x()*q.x() + q.z()*q.z());\n\t\taxis.z() = 2.0*(q.y()*q.z() + q.x()*q.w());\n\t}\n\n\t// Conversion: Quaternion --> Z-axis\n\tvoid AxisZFromQuat(const Quat& q, Vec3& axis)\n\t{\n\t\t// Construct the required axis\n\t\taxis.x() = 2.0*(q.x()*q.z() + q.y()*q.w());\n\t\taxis.y() = 2.0*(q.y()*q.z() - q.x()*q.w());\n\t\taxis.z() = 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Rotation matrix\n\t//\n\n\t// Conversion: Quaternion --> Rotation matrix\n\tvoid RotmatFromQuat(const Quat& q, Rotmat& R)\n\t{\n\t\t// Construct the required rotation matrix\n\t\tR << 1.0 - 2.0*(q.y()*q.y() + q.z()*q.z()),       2.0*(q.x()*q.y() - q.z()*q.w()),       2.0*(q.x()*q.z() + q.y()*q.w()),\n\t\t           2.0*(q.x()*q.y() + q.z()*q.w()), 1.0 - 2.0*(q.x()*q.x() + q.z()*q.z()),       2.0*(q.y()*q.z() - q.x()*q.w()),\n\t\t           2.0*(q.x()*q.z() - q.y()*q.w()),       2.0*(q.y()*q.z() + q.x()*q.w()), 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Euler angles\n\t//\n\n\t// Conversion: Quaternion --> Euler angles\n\tvoid EulerFromQuat(const Quat& q, double& yaw, double& pitch, double& roll)\n\t{\n\t\t// Calculate the sine of the pitch angle\n\t\tdouble sth = 2.0*(q.w()*q.y() - q.x()*q.z());\n\t\tsth = (sth >= 1.0 ? 1.0 : (sth <= -1.0 ? -1.0 : sth)); // Coerce sth to [-1,1]\n\n\t\t// Calculate the required Euler angles\n\t\tdouble qysq = q.y()*q.y();\n\t\tyaw = atan2(q.x()*q.y() + q.z()*q.w(), 0.5 - (qysq + q.z()*q.z()));\n\t\tpitch = asin(sth);\n\t\troll = atan2(q.y()*q.z() + q.x()*q.w(), 0.5 - (q.x()*q.x() + qysq));\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Fused angles\n\t//\n\n\t// Conversion: Quaternion --> Fused angles (2D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = 2.0*(q.y()*q.w() - q.x()*q.z());\n\t\tdouble sphi   = 2.0*(q.y()*q.z() + q.x()*q.w());\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Quaternion --> Fused angles (3D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedYaw, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tFusedFromQuat(q, fusedPitch, fusedRoll);\n\t}\n\n\t// Conversion: Quaternion --> Fused angles (4D)\n\tvoid FusedFromQuat(const Quat& q, double& fusedYaw, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused yaw, pitch and roll\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tFusedFromQuat(q, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere of the rotation\n\t\themi = (0.5 - (q.x()*q.x() + q.y()*q.y()) >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Tilt angles\n\t//\n\n\t// Conversion: Quaternion --> Tilt angles (2D)\n\tvoid TiltFromQuat(const Quat& q, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(q.w()*q.y() - q.x()*q.z(), q.w()*q.x() + q.y()*q.z());\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n\n\t// Conversion: Quaternion --> Tilt angles (3D)\n\tvoid TiltFromQuat(const Quat& q, double& fusedYaw, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the fused yaw, tilt axis angle and tilt angle\n\t\tFusedFromQuat(q, fusedYaw);\n\t\tTiltFromQuat(q, tiltAxisAngle, tiltAngle);\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Z vector\n\t//\n\n\t// Conversion: Quaternion --> Z vector\n\tvoid ZVecFromQuat(const Quat& q, ZVec& z)\n\t{\n\t\t// Calculate the required Z vector\n\t\tz.x() = 2.0*(q.x()*q.z() - q.y()*q.w());\n\t\tz.y() = 2.0*(q.y()*q.z() + q.x()*q.w());\n\t\tz.z() = 1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n\t}\n\n\t//\n\t// Conversion: Quaternion --> Tilt phase\n\t//\n\n\t// Conversion: Quaternion --> Tilt phase (2D)\n\tvoid PhaseFromQuat(const Quat& q, double& px, double& py)\n\t{\n\t\t// Precalculate terms\n\t\tdouble wzsq = q.w()*q.w() + q.z()*q.z();\n\t\tdouble xysq = q.x()*q.x() + q.y()*q.y();\n\n\t\t// Calculate the cos of the tilt angle\n\t\tdouble calpha = (wzsq - xysq) / (wzsq + xysq); // Note: wzsq and xysq are both guaranteed >= 0, so this is guaranteed to be in the range [-1,1]\n\n\t\t// Calculate the required x and y tilt phase components\n\t\tdouble hsalpha = sqrt(wzsq * xysq);\n\t\tif(hsalpha == 0.0)\n\t\t{\n\t\t\tif(calpha >= 0.0) // Note: Here we should have alpha = 0\n\t\t\t\tpx = py = 0.0;\n\t\t\telse // Note: Here we should have alpha = pi, and xysq = 1 if q is unit norm\n\t\t\t{\n\t\t\t\tdouble xy = sqrt(xysq);\n\t\t\t\tpx = M_PI * (q.x() / xy);\n\t\t\t\tpy = M_PI * (q.y() / xy);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble alpha = acos(calpha);\n\t\t\tpx = alpha * ((q.w()*q.x() + q.y()*q.z()) / hsalpha);\n\t\t\tpy = alpha * ((q.w()*q.y() - q.x()*q.z()) / hsalpha);\n\t\t}\n\t}\n\n\t// Conversion: Quaternion --> Tilt phase (3D)\n\tvoid PhaseFromQuat(const Quat& q, double& px, double& py, double& pz)\n\t{\n\t\t// Calculate the tilt phase components\n\t\tpz = FYawOfQuat(q);\n\t\tPhaseFromQuat(q, px, py);\n\t}\n\n\t// #######################################\n\t// #### Conversions from Euler angles ####\n\t// #######################################\n\n\t// Conversion: Euler angles --> Rotation matrix\n\tRotmat RotmatFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Precalculate the trigonometric values\n\t\tdouble cpsi = cos(yaw);\n\t\tdouble spsi = sin(yaw);\n\t\tdouble cth  = cos(pitch);\n\t\tdouble sth  = sin(pitch);\n\t\tdouble cphi = cos(roll);\n\t\tdouble sphi = sin(roll);\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << cpsi*cth, cpsi*sth*sphi - spsi*cphi, cpsi*sth*cphi + spsi*sphi,\n\t\t     spsi*cth, spsi*sth*sphi + cpsi*cphi, spsi*sth*cphi - cpsi*sphi,\n\t\t         -sth,                  cth*sphi,                  cth*cphi;\n\t\treturn R;\n\t}\n\n\t// Conversion: Euler angles --> Quaternion\n\tQuat QuatFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Halve the Euler angles\n\t\tdouble hpsi = 0.5*yaw;\n\t\tdouble hth = 0.5*pitch;\n\t\tdouble hphi = 0.5*roll;\n\n\t\t// Precalculate the trigonometric values\n\t\tdouble hcpsi = cos(hpsi);\n\t\tdouble hspsi = sin(hpsi);\n\t\tdouble hcth  = cos(hth);\n\t\tdouble hsth  = sin(hth);\n\t\tdouble hcphi = cos(hphi);\n\t\tdouble hsphi = sin(hphi);\n\n\t\t// Calculate and return the required quaternion\n\t\treturn Quat(hcphi*hcth*hcpsi + hsphi*hsth*hspsi, hsphi*hcth*hcpsi - hcphi*hsth*hspsi, hcphi*hsth*hcpsi + hsphi*hcth*hspsi, hcphi*hcth*hspsi - hsphi*hsth*hcpsi); // Order: (w,x,y,z)\n\t}\n\n\t// Conversion: Euler angles --> Fused angles\n\tFusedAngles FusedFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Construct a fused angles object\n\t\tFusedAngles f;\n\n\t\t// Calculation of the fused yaw in a numerically stable manner requires the complete rotation matrix representation\n\t\tRotmat R = RotmatFromEuler(yaw, pitch, roll);\n\n\t\t// Calculate the fused yaw\n\t\tf.fusedYaw = FYawOfRotmat(R);\n\n\t\t// Calculate the fused pitch\n\t\tf.fusedPitch = pitch; // ZYX Euler pitch is equivalent to fused pitch!\n\n\t\t// Calculate the fused roll\n\t\tdouble sphi = R.coeff(2,1);\n\t\tsphi = (sphi >= 1.0 ? 1.0 : (sphi <= -1.0 ? -1.0 : sphi)); // Coerce sphi to [-1,1]\n\t\tf.fusedRoll  = asin(sphi);\n\n\t\t// See which hemisphere we're in\n\t\tf.hemi = (R.coeff(2,2) >= 0.0);\n\n\t\t// Return the calculated fused angles\n\t\treturn f;\n\t}\n\n\t// Conversion: Euler angles --> Tilt angles\n\tTiltAngles TiltFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Calculation of the fused yaw in a numerically stable manner requires the complete rotation matrix representation\n\t\tRotmat R = RotmatFromEuler(yaw, pitch, roll);\n\n\t\t// Calculate the fused yaw\n\t\tt.fusedYaw = FYawOfRotmat(R);\n\n\t\t// Calculate the tilt axis angle\n\t\tt.tiltAxisAngle = atan2(-R.coeff(2,0), R.coeff(2,1));\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = R.coeff(2,2);\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\tt.tiltAngle = acos(calpha);\n\n\t\t// Return the calculated tilt angles\n\t\treturn t;\n\t}\n\n\t// Conversion: Euler angles --> Z vector\n\tZVec ZVecFromEuler(double pitch, double roll)\n\t{\n\t\t// Precalculate the trigonometric values\n\t\tdouble cth  = cos(pitch);\n\t\tdouble sth  = sin(pitch);\n\t\tdouble cphi = cos(roll);\n\t\tdouble sphi = sin(roll);\n\n\t\t// Calculate and return the required Z vector\n\t\treturn ZVec(-sth, cth*sphi, cth*cphi);\n\t}\n\n\t//\n\t// Conversion: Euler angles --> Tilt phase\n\t//\n\n\t// Conversion: Euler angles --> Tilt phase (2D)\n\tTiltPhase2D PhaseFromEuler(double pitch, double roll)\n\t{\n\t\t// Calculate and return the required tilt phase representation\n\t\tZVec z = ZVecFromEuler(pitch, roll);\n\t\treturn PhaseFromZVec(z);\n\t}\n\n\t// Conversion: Euler angles --> Tilt phase (3D)\n\tTiltPhase3D PhaseFromEuler(double yaw, double pitch, double roll)\n\t{\n\t\t// Calculate and return the required tilt phase representation\n\t\tQuat q = QuatFromEuler(yaw, pitch, roll);\n\t\treturn PhaseFromQuat(q);\n\t}\n\n\t// #######################################\n\t// #### Conversions from fused angles ####\n\t// #######################################\n\n\t//\n\t// Conversion: Fused angles --> Rotation matrix\n\t//\n\n\t// Conversion: Fused angles (2D) --> Rotation matrix\n\tRotmat RotmatFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the cos of the tilt angle\n\t\tdouble calpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = sqrt(1.0 - crit);\n\t\t}\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble calphabar = 1.0 - calpha;\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = calpha + calphabar*cgam*cgam;\n\t\tdouble B = calpha + calphabar*sgam*sgam;\n\t\tdouble C = calphabar*cgam*sgam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR <<    A,    C,    sth,\n\t\t        C,    B,  -sphi,\n\t\t     -sth, sphi, calpha;\n\t\treturn R;\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Rotation matrix\n\tRotmat RotmatFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the sin and cos of the tilt angle\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tsalpha = 1.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t\tsalpha = sqrt(crit);\n\t\t}\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble psigam = fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = cgam*cpsigam;\n\t\tdouble B = sgam*cpsigam;\n\t\tdouble C = cgam*spsigam;\n\t\tdouble D = sgam*spsigam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << A + D*calpha, B - C*calpha,  salpha*spsigam,\n\t\t     C - B*calpha, D + A*calpha, -salpha*cpsigam,\n\t\t          -sth,          sphi,    calpha;\n\t\treturn R;\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Quaternion\n\t//\n\n\t// Conversion: Fused angles (2D) --> Quaternion\n\tQuat QuatFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the required trigonometric values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the sin and cos of the tilt angle\n\t\tdouble calpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t\tcrit = 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = sqrt(1.0 - crit);\n\t\t}\n\n\t\t// Precalculate terms involved in the quaternion expression\n\t\tdouble C = 1.0 + calpha;\n\n\t\t// Calculate and return the required quaternion\n\t\tdouble scale = 1.0 / sqrt(C*C + crit); // Note: Norm of quat = sqrt(C*C+sth*sth+sphi*sphi) = sqrt(2*C) > 1\n\t\treturn Quat(C*scale, sphi*scale, sth*scale, 0.0); // Order: (w,x,y,z)\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Quaternion\n\tQuat QuatFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the required trigonometric values\n\t\tdouble hpsi = 0.5*fusedYaw;\n\t\tdouble chpsi = cos(hpsi);\n\t\tdouble shpsi = sin(hpsi);\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the sin and cos of the tilt angle\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tsalpha = 1.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t\tcrit = 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t\tsalpha = sqrt(crit);\n\t\t}\n\n\t\t// Construct the output quaternion using the best conditioned expression\n\t\tif(calpha >= 0.0)\n\t\t{\n\t\t\t// Precalculate terms involved in the quaternion expression\n\t\t\tdouble C = 1.0 + calpha;\n\n\t\t\t// Calculate and return the required quaternion\n\t\t\tdouble scale = 1.0 / sqrt(C*C + crit); // Note: Norm of quat = sqrt(C*C+sth*sth+sphi*sphi) = sqrt(2*C) > 1\n\t\t\treturn Quat(C*chpsi*scale, (sphi*chpsi-sth*shpsi)*scale, (sphi*shpsi+sth*chpsi)*scale, C*shpsi*scale); // Order: (w,x,y,z)\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Precalculate terms involved in the quaternion expression\n\t\t\tdouble C = 1.0 - calpha;\n\t\t\tdouble gamma = atan2(sth,sphi);\n\t\t\tdouble hgampsi = gamma + hpsi;\n\t\t\tdouble chgampsi = cos(hgampsi);\n\t\t\tdouble shgampsi = sin(hgampsi);\n\n\t\t\t// Calculate and return the required quaternion\n\t\t\tdouble scale = 1.0 / sqrt(C*C + crit); // Note: Norm of quat = sqrt(C*C+sth*sth+sphi*sphi) = sqrt(2*C) > 1\n\t\t\treturn Quat(salpha*chpsi*scale, C*chgampsi*scale, C*shgampsi*scale, salpha*shpsi*scale); // Order: (w,x,y,z)\n\t\t}\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Euler angles\n\t//\n\n\t// Conversion: Fused angles (2D) --> Euler angles\n\tEulerAngles EulerFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble A = cgam*(1.0 - calpha);\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(A*sgam, calpha + A*cgam), fusedPitch, atan2(sphi, calpha)); // Note: This use of sphi is okay, as if crit >= 1 then calpha = 0 so rescaling sphi doesn't matter for the value of atan2(sphi,calpha)\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Euler angles\n\tEulerAngles EulerFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = 0.0;\n\t\tif(crit < 1.0)\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Calculate the tilt axis angle gamma\n\t\tdouble gamma = atan2(sth,sphi);\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(gamma);\n\t\tdouble sgam = sin(gamma);\n\t\tdouble psigam = fusedYaw + gamma;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam), fusedPitch, atan2(sphi, calpha)); // Note: This use of sphi is okay, as if crit >= 1 then calpha = 0 so rescaling sphi doesn't matter for the value of atan2(sphi,calpha)\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Tilt angles\n\t//\n\n\t// Conversion: Fused angles (2D) --> Tilt angles\n\tTiltAngles TiltFromFused(double fusedPitch, double fusedRoll) // Assume: fusedYaw = 0, hemi = true\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate and return the tilt angles representation\n\t\tt.fusedYaw = 0.0;\n\t\tt.tiltAxisAngle = atan2(sth,sphi);\n\t\tt.tiltAngle = acos(calpha);\n\t\treturn t;\n\t}\n\n\t// Conversion: Fused angles (3D/4D) --> Tilt angles\n\tTiltAngles TiltFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Construct a tilt angles object\n\t\tTiltAngles t;\n\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = 0.0;\n\t\tif(crit < 1.0)\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\n\t\t// Calculate and return the tilt angles representation\n\t\tt.fusedYaw = fusedYaw;\n\t\tt.tiltAxisAngle = atan2(sth,sphi);\n\t\tt.tiltAngle = acos(calpha);\n\t\treturn t;\n\t}\n\n\t// Conversion: Fused angles (2D) --> Tilt angle component\n\tdouble TiltAngleFromFused(double fusedPitch, double fusedRoll)\n\t{\n\t\t// Precalculate the sine values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the cosine of the tilt angle\n\t\tdouble crit = sth*sth + sphi*sphi;\n\t\tdouble calpha = (crit >= 1.0 ? 0.0 : sqrt(1.0 - crit));\n\n\t\t// Calculate and return the tilt angle component of the tilt angles representation\n\t\treturn acos(calpha);\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Z vector\n\t//\n\n\t// Conversion: Fused angles --> Z vector\n\tZVec ZVecFromFused(double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Precalculate the sin values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the cos of the tilt angle\n\t\tdouble calpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tcalpha = 0.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t}\n\n\t\t// Return the required Z vector\n\t\treturn ZVec(-sth, sphi, calpha);\n\t}\n\n\t//\n\t// Conversion: Fused angles --> Tilt phase\n\t//\n\n\t// Conversion: Fused angles --> Tilt phase (2D)\n\tTiltPhase2D PhaseFromFused(double fusedPitch, double fusedRoll)\n\t{\n\t\t// Declare variables\n\t\tTiltPhase2D p;\n\n\t\t// Precalculate the sin values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the sin and cos of the tilt angle\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tsalpha = 1.0;\n\t\t\tcalpha = 0.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsalpha = sqrt(crit);\n\t\t\tcalpha = sqrt(1.0 - crit);\n\t\t}\n\n\t\t// Calculate the required x and y tilt phase components\n\t\tif(salpha == 0.0)\n\t\t\tp.px = p.py = 0.0;\n\t\telse\n\t\t{\n\t\t\tdouble alpha = acos(calpha);\n\t\t\tp.px = alpha * (sphi / salpha);\n\t\t\tp.py = alpha * (sth / salpha);\n\t\t}\n\n\t\t// Return the required tilt phase representation\n\t\treturn p;\n\t}\n\n\t// Conversion: Fused angles --> Tilt phase (3D)\n\tTiltPhase3D PhaseFromFused(double fusedYaw, double fusedPitch, double fusedRoll, bool hemi)\n\t{\n\t\t// Declare variables\n\t\tTiltPhase3D p;\n\n\t\t// Precalculate the sin values\n\t\tdouble sth = sin(fusedPitch);\n\t\tdouble sphi = sin(fusedRoll);\n\n\t\t// Calculate the sine sum criterion\n\t\tdouble crit = sth*sth + sphi*sphi;\n\n\t\t// Calculate the sin and cos of the tilt angle\n\t\tdouble calpha, salpha;\n\t\tif(crit >= 1.0)\n\t\t{\n\t\t\tsalpha = 1.0;\n\t\t\tcalpha = 0.0;\n\t\t\tdouble sqrtcrit = sqrt(crit);\n\t\t\tsth /= sqrtcrit;\n\t\t\tsphi /= sqrtcrit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsalpha = sqrt(crit);\n\t\t\tcalpha = (hemi ? sqrt(1.0 - crit) : -sqrt(1.0 - crit));\n\t\t}\n\n\t\t// Calculate the required x and y tilt phase components\n\t\tif(salpha == 0.0)\n\t\t{\n\t\t\tif(hemi)\n\t\t\t\tp.px = p.py = 0.0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tp.px = M_PI;\n\t\t\t\tp.py = 0.0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble alpha = acos(calpha);\n\t\t\tp.px = alpha * (sphi / salpha);\n\t\t\tp.py = alpha * (sth / salpha);\n\t\t}\n\n\t\t// Set the required z tilt phase component\n\t\tp.pz = fusedYaw;\n\n\t\t// Return the required tilt phase representation\n\t\treturn p;\n\t}\n\n\t// ######################################\n\t// #### Conversions from tilt angles ####\n\t// ######################################\n\n\t//\n\t// Conversion: Tilt angles --> Rotation matrix\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Rotation matrix\n\tRotmat RotmatFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble calphabar = 1.0 - calpha;\n\t\tdouble sth = salpha*sgam;\n\t\tdouble sphi = salpha*cgam;\n\t\tdouble A = calpha + calphabar*cgam*cgam;\n\t\tdouble B = calpha + calphabar*sgam*sgam;\n\t\tdouble C = calphabar*cgam*sgam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR <<    A,    C,    sth,\n\t\t        C,    B,  -sphi,\n\t\t     -sth, sphi, calpha;\n\t\treturn R;\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Rotation matrix\n\tRotmat RotmatFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate terms involved in the rotation matrix expression\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble psigam = fusedYaw + tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = cgam*cpsigam;\n\t\tdouble B = sgam*cpsigam;\n\t\tdouble C = cgam*spsigam;\n\t\tdouble D = sgam*spsigam;\n\n\t\t// Calculate and return the required rotation matrix\n\t\tRotmat R;\n\t\tR << A + D*calpha, B - C*calpha,  salpha*spsigam,\n\t\t     C - B*calpha, D + A*calpha, -salpha*cpsigam,\n\t\t     -sgam*salpha,  cgam*salpha,  calpha;\n\t\treturn R;\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Quaternion\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Quaternion\n\tQuat QuatFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate the required angles\n\t\tdouble halpha = 0.5*tiltAngle;\n\n\t\t// Precalculate the required trigonometric values\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\t\tdouble cgamma = cos(tiltAxisAngle);\n\t\tdouble sgamma = sin(tiltAxisAngle);\n\n\t\t// Return the required quaternion orientation\n\t\treturn Quat(chalpha, shalpha*cgamma, shalpha*sgamma, 0.0); // Order: (w,x,y,z)\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Quaternion\n\tQuat QuatFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate the required angles\n\t\tdouble hpsi = 0.5*fusedYaw;\n\t\tdouble halpha = 0.5*tiltAngle;\n\t\tdouble hgampsi = tiltAxisAngle + hpsi;\n\n\t\t// Precalculate the required trigonometric values\n\t\tdouble chpsi = cos(hpsi);\n\t\tdouble shpsi = sin(hpsi);\n\t\tdouble chalpha = cos(halpha);\n\t\tdouble shalpha = sin(halpha);\n\t\tdouble chgampsi = cos(hgampsi);\n\t\tdouble shgampsi = sin(hgampsi);\n\n\t\t// Return the required quaternion orientation\n\t\treturn Quat(chalpha*chpsi, shalpha*chgampsi, shalpha*shgampsi, chalpha*shpsi); // Order: (w,x,y,z)\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Euler angles\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Euler angles\n\tEulerAngles EulerFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble sth = sgam*salpha;\n\t\tdouble sphi = cgam*salpha;\n\t\tdouble A = cgam*(1.0 - calpha);\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(A*sgam, calpha + A*cgam), asin(sth), atan2(sphi, calpha));\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Euler angles\n\tEulerAngles EulerFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\t\tdouble sth = sgam*salpha;\n\t\tdouble sphi = cgam*salpha;\n\t\tdouble psigam = fusedYaw + tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\t\tdouble A = sgam*calpha;\n\n\t\t// Calculate and return the required Euler angles\n\t\treturn EulerAngles(atan2(cgam*spsigam - A*cpsigam, cgam*cpsigam + A*spsigam), asin(sth), atan2(sphi, calpha));\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Fused angles\n\t//\n\n\t// Conversion: Tilt angles (2D) --> Fused angles\n\tFusedAngles FusedFromTilt(double tiltAxisAngle, double tiltAngle) // Assume: fusedYaw = 0\n\t{\n\t\t// Calculate and return the fused angles representation\n\t\treturn FusedFromTilt(0.0, tiltAxisAngle, tiltAngle);\n\t}\n\n\t// Conversion: Tilt angles (3D) --> Fused angles\n\tFusedAngles FusedFromTilt(double fusedYaw, double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Construct a fused angles object\n\t\tFusedAngles f;\n\n\t\t// Precalculate terms\n\t\tdouble cgam = cos(tiltAxisAngle);\n\t\tdouble sgam = sin(tiltAxisAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\n\t\t// Calculate and return the fused angles representation\n\t\tf.fusedYaw = fusedYaw;\n\t\tf.fusedPitch = asin(salpha*sgam);\n\t\tf.fusedRoll = asin(salpha*cgam);\n\t\tf.hemi = (tiltAngle <= M_PI_2);\n\t\treturn f;\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Z vector\n\t//\n\n\t// Conversion: Tilt angles --> Z vector\n\tZVec ZVecFromTilt(double tiltAxisAngle, double tiltAngle)\n\t{\n\t\t// Precalculate the required trigonometric terms\n\t\tdouble cgamma = cos(tiltAxisAngle);\n\t\tdouble sgamma = sin(tiltAxisAngle);\n\t\tdouble calpha = cos(tiltAngle);\n\t\tdouble salpha = sin(tiltAngle);\n\n\t\t// Return the required Z vector\n\t\treturn ZVec(-salpha*sgamma, salpha*cgamma, calpha);\n\t}\n\n\t//\n\t// Conversion: Tilt angles --> Tilt phase\n\t//\n\n\t// Conversion: Tilt angles --> Tilt phase (2D)\n\tvoid PhaseFromTilt(double tiltAxisAngle, double tiltAngle, double& px, double& py)\n\t{\n\t\t// Calculate the required tilt phase parameters\n\t\tpx = tiltAngle * cos(tiltAxisAngle);\n\t\tpy = tiltAngle * sin(tiltAxisAngle);\n\t}\n\n\t// ####################################\n\t// #### Conversions from Z vectors ####\n\t// ####################################\n\n\t//\n\t// Conversion: Z vector --> Rotation matrix (zero fused yaw)\n\t//\n\n\t// Conversion: Z vector --> Rotation matrix\n\tvoid RotmatFromZVec(const ZVec& z, Rotmat& R)\n\t{\n\t\t// Perform the conversion via a quaternion\n\t\tQuat q;\n\t\tQuatFromZVec(z, q);\n\t\tRotmatFromQuat(q, R);\n\t}\n\n\t//\n\t// Conversion: Z vector --> Quaternion (zero fused yaw)\n\t//\n\n\t// Conversion: Z vector --> Quaternion\n\tvoid QuatFromZVec(const ZVec& z, Quat& q)\n\t{\n\t\t// Calculate the z component\n\t\tq.z() = 0.0; // Zero fused yaw is equivalent to a quaternion z component of zero!\n\n\t\t// Calculate the w component\n\t\tdouble wsq = 0.5*(1.0 + z.z());\n\t\twsq = (wsq >= 1.0 ? 1.0 : (wsq <= 0.0 ? 0.0 : wsq)); // Coerce wsq to [0,1]\n\t\tq.w() = sqrt(wsq);\n\n\t\t// Calculate the x and y components\n\t\tdouble xsqplusysq = 1.0 - wsq;\n\t\tdouble xtilde = z.y();\n\t\tdouble ytilde = -z.x();\n\t\tdouble xytildenormsq = xtilde*xtilde + ytilde*ytilde;\n\t\tif(xytildenormsq <= 0.0)\n\t\t{\n\t\t\tq.x() = sqrt(xsqplusysq);\n\t\t\tq.y() = 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble factor = sqrt(xsqplusysq / xytildenormsq);\n\t\t\tq.x() = factor * xtilde;\n\t\t\tq.y() = factor * ytilde;\n\t\t}\n\t}\n\n\t//\n\t// Conversion: Z vector --> Euler angles (zero Euler yaw)\n\t//\n\n\t// Conversion: Z vector --> Euler angles\n\tvoid EulerFromZVec(const ZVec& z, double& pitch, double& roll)\n\t{\n\t\t// Calculate the pitch\n\t\tdouble stheta = -z.x();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tpitch = asin(stheta);\n\n\t\t// Calculate the roll\n\t\troll = atan2(z.y(), z.z());\n\t}\n\n\t//\n\t// Conversion: Z vector --> Fused angles (zero fused yaw)\n\t//\n\n\t// Conversion: Z vector --> Fused angles (2D)\n\tvoid FusedFromZVec(const ZVec& z, double& fusedPitch, double& fusedRoll)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = -z.x();\n\t\tdouble sphi   = z.y();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfusedPitch = asin(stheta);\n\t\tfusedRoll  = asin(sphi);\n\t}\n\n\t// Conversion: Z vector --> Fused angles (3D)\n\tvoid FusedFromZVec(const ZVec& z, double& fusedPitch, double& fusedRoll, bool& hemi)\n\t{\n\t\t// Calculate the fused pitch and roll\n\t\tFusedFromZVec(z, fusedPitch, fusedRoll);\n\n\t\t// Calculate the hemisphere\n\t\themi = (z.z() >= 0.0);\n\t}\n\n\t//\n\t// Conversion: Z vector --> Tilt angles (zero fused yaw)\n\t//\n\n\t// Conversion: Z vector --> Tilt angles (2D)\n\tvoid TiltFromZVec(const ZVec& z, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the tilt axis angle\n\t\ttiltAxisAngle = atan2(-z.x(), z.y());\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = z.z();\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttiltAngle = acos(calpha);\n\t}\n\n\t//\n\t// Conversion: Z vector --> Tilt phase (zero fused yaw)\n\t//\n\n\t// Conversion: Z vector --> Tilt phase (2D)\n\tvoid PhaseFromZVec(const ZVec& z, double& px, double& py)\n\t{\n\t\t// Calculate the sin of the tilt angle alpha\n\t\tdouble salpha = sqrt(z.x()*z.x() + z.y()*z.y());\n\n\t\t// Calculate the required x and y tilt phase components\n\t\tif(salpha == 0.0)\n\t\t{\n\t\t\tif(z.z() >= 0.0)\n\t\t\t\tpx = py = 0.0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tpx = M_PI;\n\t\t\t\tpy = 0.0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble calpha = std::max(std::min(z.z(), 1.0), -1.0);\n\t\t\tdouble alpha = acos(calpha);\n\t\t\tpx = alpha * ( z.y() / salpha);\n\t\t\tpy = alpha * (-z.x() / salpha);\n\t\t}\n\t}\n\n\t// #####################################\n\t// #### Conversions from tilt phase ####\n\t// #####################################\n\n\t//\n\t// Conversion: Tilt phase --> Quaternion\n\t//\n\n\t// Conversion: Tilt phase --> Quaternion (2D)\n\tQuat QuatFromPhase(double px, double py)\n\t{\n\t\tdouble tiltAxisAngle, tiltAngle;\n\t\tTiltFromPhase(px, py, tiltAxisAngle, tiltAngle);\n\t\treturn QuatFromTilt(tiltAxisAngle, tiltAngle);\n\t}\n\n\t// Conversion: Tilt phase --> Quaternion (3D)\n\tQuat QuatFromPhase(double px, double py, double pz)\n\t{\n\t\tdouble tiltAxisAngle, tiltAngle;\n\t\tTiltFromPhase(px, py, tiltAxisAngle, tiltAngle);\n\t\treturn QuatFromTilt(pz, tiltAxisAngle, tiltAngle);\n\t}\n\n\t//\n\t// Conversion: Tilt phase --> Tilt angles\n\t//\n\n\t// Conversion: Tilt phase --> Tilt angles (2D)\n\tvoid TiltFromPhase(double px, double py, double& tiltAxisAngle, double& tiltAngle)\n\t{\n\t\t// Calculate the required tilt angles parameters\n\t\ttiltAxisAngle = atan2(py, px);\n\t\ttiltAngle = sqrt(px*px + py*py);\n\t}\n\n\t// #########################################\n\t// #### Conversions from yaw and z-axis ####\n\t// #########################################\n\n\t// Conversion: Yaw and z-axis (BzG) --> Rotation matrix\n\tvoid RotmatFromFYawBzG(double fusedYaw, const Vec3& BzG, Rotmat& RGB)\n\t{\n\t\t// Calculate the quaternion representation of the required rotation\n\t\tQuat qGB;\n\t\tQuatFromFYawBzG(fusedYaw, BzG, qGB);\n\n\t\t// Return the required rotation matrix representation\n\t\tRotmatFromQuat(qGB, RGB);\n\t}\n\n\t// Conversion: Yaw and z-axis (GzB) --> Rotation matrix\n\tvoid RotmatFromFYawGzB(double fusedYaw, const Vec3& GzB, Rotmat& RGB)\n\t{\n\t\t// Calculate the quaternion representation of the required rotation\n\t\tQuat qGB;\n\t\tQuatFromFYawGzB(fusedYaw, GzB, qGB);\n\n\t\t// Return the required rotation matrix representation\n\t\tRotmatFromQuat(qGB, RGB);\n\t}\n\n\t// Conversion: Yaw and z-axis (BzG) --> Quaternion\n\tvoid QuatFromFYawBzG(double fusedYaw, const Vec3& BzG, Quat& qGB)\n\t{\n\t\t// Precalculate trigonometric terms\n\t\tdouble chpsi = cos(0.5*fusedYaw);\n\t\tdouble shpsi = sin(0.5*fusedYaw);\n\n\t\t// Calculate the w and z components\n\t\tdouble wsqpluszsq = 0.5*(1 + BzG.z());\n\t\twsqpluszsq = (wsqpluszsq >= 1.0 ? 1.0 : (wsqpluszsq <= 0.0 ? 0.0 : wsqpluszsq)); // Coerce wsqpluszsq to [0,1]\n\t\tdouble wznorm = sqrt(wsqpluszsq);\n\t\tqGB.w() = wznorm * chpsi;\n\t\tqGB.z() = wznorm * shpsi;\n\n\t\t// Calculate the x and y components\n\t\tdouble xsqplusysq = 1.0 - wsqpluszsq;\n\t\tdouble xtilde = BzG.x()*qGB.z() + BzG.y()*qGB.w();\n\t\tdouble ytilde = BzG.y()*qGB.z() - BzG.x()*qGB.w();\n\t\tdouble xytildenormsq = xtilde*xtilde + ytilde*ytilde;\n\t\tif(xytildenormsq <= 0.0)\n\t\t{\n\t\t\tqGB.x() = sqrt(xsqplusysq);\n\t\t\tqGB.y() = 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble factor = sqrt(xsqplusysq / xytildenormsq);\n\t\t\tqGB.x() = factor * xtilde;\n\t\t\tqGB.y() = factor * ytilde;\n\t\t}\n\t}\n\n\t// Conversion: Yaw and z-axis (GzB) --> Quaternion\n\tvoid QuatFromFYawGzB(double fusedYaw, const Vec3& GzB, Quat& qGB)\n\t{\n\t\t// Precalculate trigonometric terms\n\t\tdouble chpsi = cos(0.5*fusedYaw);\n\t\tdouble shpsi = sin(0.5*fusedYaw);\n\n\t\t// Calculate the w and z components\n\t\tdouble wsqpluszsq = 0.5*(1 + GzB.z());\n\t\twsqpluszsq = (wsqpluszsq >= 1.0 ? 1.0 : (wsqpluszsq <= 0.0 ? 0.0 : wsqpluszsq)); // Coerce wsqpluszsq to [0,1]\n\t\tdouble wznorm = sqrt(wsqpluszsq);\n\t\tqGB.w() = wznorm * chpsi;\n\t\tqGB.z() = wznorm * shpsi;\n\n\t\t// Calculate the x and y components\n\t\tdouble xsqplusysq = 1.0 - wsqpluszsq;\n\t\tdouble xtilde = GzB.x()*qGB.z() - GzB.y()*qGB.w();\n\t\tdouble ytilde = GzB.y()*qGB.z() + GzB.x()*qGB.w();\n\t\tdouble xytildenormsq = xtilde*xtilde + ytilde*ytilde;\n\t\tif(xytildenormsq <= 0.0)\n\t\t{\n\t\t\tqGB.x() = sqrt(xsqplusysq);\n\t\t\tqGB.y() = 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble factor = sqrt(xsqplusysq / xytildenormsq);\n\t\t\tqGB.x() = factor * xtilde;\n\t\t\tqGB.y() = factor * ytilde;\n\t\t}\n\t}\n\n\t// Conversion: Yaw and z-axis --> Euler angles\n\tvoid EulerFromFYawBzG(double fusedYaw, const Vec3& BzG, EulerAngles& eGB)\n\t{\n\t\t// Calculate the Euler pitch\n\t\tdouble stheta = -BzG.x();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\teGB.pitch = asin(stheta);\n\n\t\t// Calculate the Euler roll\n\t\teGB.roll = atan2(BzG.y(), BzG.z());\n\n\t\t// Calculate the Euler ZYX yaw\n\t\tif(stheta == 0.0 && BzG.y() == 0.0)\n\t\t\teGB.yaw = fusedYaw;\n\t\telse\n\t\t{\n\t\t\tdouble cphi = cos(eGB.roll);\n\t\t\tdouble sphi = sin(eGB.roll);\n\t\t\teGB.yaw = fusedYaw + atan2(sphi, stheta*cphi) - atan2(BzG.y(), stheta);\n\t\t}\n\t\tinternal::picutVar(eGB.yaw);\n\t}\n\n\t// Conversion: Yaw and z-axis --> Euler angles\n\tvoid EulerFromFYawGzB(double fusedYaw, const Vec3& GzB, EulerAngles& eGB)\n\t{\n\t\t// Precalculate trigonometric terms\n\t\tdouble cfyaw = cos(fusedYaw);\n\t\tdouble sfyaw = sin(fusedYaw);\n\n\t\t// Calculate the Euler pitch\n\t\tdouble stheta = cfyaw*GzB.x() + sfyaw*GzB.y();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\teGB.pitch = asin(stheta);\n\n\t\t// Calculate the Euler roll\n\t\tdouble sfphi = sfyaw*GzB.x() - cfyaw*GzB.y();\n\t\teGB.roll = atan2(sfphi, GzB.z());\n\n\t\t// Calculate the Euler ZYX yaw\n\t\tif(stheta == 0.0 && sfphi == 0.0)\n\t\t\teGB.yaw = fusedYaw;\n\t\telse\n\t\t{\n\t\t\tdouble cphi = cos(eGB.roll);\n\t\t\tdouble sphi = sin(eGB.roll);\n\t\t\teGB.yaw = fusedYaw + atan2(sphi, stheta*cphi) - atan2(sfphi, stheta);\n\t\t}\n\t\tinternal::picutVar(eGB.yaw);\n\t}\n\n\t// Conversion: Yaw and z-axis --> Fused angles\n\tvoid FusedFromFYawBzG(double fusedYaw, const Vec3& BzG, FusedAngles& fGB)\n\t{\n\t\t// Transcribe and wrap the fused yaw\n\t\tfGB.fusedYaw = internal::picut(fusedYaw);\n\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = -BzG.x();\n\t\tdouble sphi   = BzG.y();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfGB.fusedPitch = asin(stheta);\n\t\tfGB.fusedRoll  = asin(sphi);\n\n\t\t// Calculate the hemisphere\n\t\tfGB.hemi = (BzG.z() >= 0.0);\n\t}\n\n\t// Conversion: Yaw and z-axis --> Fused angles\n\tvoid FusedFromFYawGzB(double fusedYaw, const Vec3& GzB, FusedAngles& fGB)\n\t{\n\t\t// Transcribe and wrap the fused yaw\n\t\tfGB.fusedYaw = internal::picut(fusedYaw);\n\n\t\t// Precalculate trigonometric terms\n\t\tdouble cpsi = cos(fGB.fusedYaw);\n\t\tdouble spsi = sin(fGB.fusedYaw);\n\n\t\t// Calculate the fused pitch and roll\n\t\tdouble stheta = cpsi*GzB.x() + spsi*GzB.y();\n\t\tdouble sphi   = spsi*GzB.x() - cpsi*GzB.y();\n\t\tstheta = (stheta >= 1.0 ? 1.0 : (stheta <= -1.0 ? -1.0 : stheta)); // Coerce stheta to [-1,1]\n\t\tsphi   = (sphi   >= 1.0 ? 1.0 : (sphi   <= -1.0 ? -1.0 : sphi  )); // Coerce sphi   to [-1,1]\n\t\tfGB.fusedPitch = asin(stheta);\n\t\tfGB.fusedRoll  = asin(sphi);\n\n\t\t// Calculate the hemisphere\n\t\tfGB.hemi = (GzB.z() >= 0.0);\n\t}\n\n\t// Conversion: Yaw and z-axis --> Tilt angles\n\tvoid TiltFromFYawBzG(double fusedYaw, const Vec3& BzG, TiltAngles& tGB)\n\t{\n\t\t// Transcribe and wrap the fused yaw\n\t\ttGB.fusedYaw = internal::picut(fusedYaw);\n\n\t\t// Calculate the tilt axis angle\n\t\ttGB.tiltAxisAngle = atan2(-BzG.x(), BzG.y());\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = BzG.z();\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttGB.tiltAngle = acos(calpha);\n\t}\n\n\t// Conversion: Yaw and z-axis --> Tilt angles\n\tvoid TiltFromFYawGzB(double fusedYaw, const Vec3& GzB, TiltAngles& tGB)\n\t{\n\t\t// Transcribe and wrap the fused yaw\n\t\ttGB.fusedYaw = internal::picut(fusedYaw);\n\n\t\t// Calculate the tilt axis angle\n\t\tif(GzB.x() == 0.0 && GzB.y() == 0.0)\n\t\t\ttGB.tiltAxisAngle = 0.0;\n\t\telse\n\t\t\ttGB.tiltAxisAngle = internal::picut(atan2(GzB.x(), -GzB.y()) - tGB.fusedYaw);\n\n\t\t// Calculate the tilt angle\n\t\tdouble calpha = GzB.z();\n\t\tcalpha = (calpha >= 1.0 ? 1.0 : (calpha <= -1.0 ? -1.0 : calpha)); // Coerce calpha to [-1,1]\n\t\ttGB.tiltAngle = acos(calpha);\n\t}\n\n\t// ########################################\n\t// #### Spherical Linear Interpolation ####\n\t// ########################################\n\n\t// Slerp: Quaternion\n\tQuat QuatSlerp(const Quat& q0, const Quat& q1, double u)\n\t{\n\t\t// Calculate the dot product of the two quaternions\n\t\tdouble dprod = q0.w()*q1.w() + q0.x()*q1.x() + q0.y()*q1.y() + q0.z()*q1.z();\n\n\t\t// Adjust for the situation that two quaternions in different hemispheres are being interpolated\n\t\tdouble q1sign = 1.0;\n\t\tif(dprod < 0.0)\n\t\t{\n\t\t\tdprod = -dprod;\n\t\t\tq1sign = -1.0;\n\t\t}\n\n\t\t// If q0 and q1 are very close then just use linear interpolation, otherwise use spherical linear interpolation\n\t\tQuat qu;\n\t\tif(dprod >= 1.0 - 5e-9) // A dot product within this tolerance of unity produces a negligible amount of error if using linear interpolation instead\n\t\t{\n\t\t\t// Perform the required interpolation\n\t\t\tqu = (1.0 - u)*q0 + (u*q1sign)*q1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate half the angle between the two quaternions\n\t\t\tdouble htheta = acos(dprod);\n\n\t\t\t// Perform the required interpolation\n\t\t\tqu = sin((1.0 - u)*htheta)*q0 + (sin(u*htheta)*q1sign)*q1;\n\t\t}\n\n\t\t// Normalise the interpolated quaternion\n\t\tNormaliseQuat(qu);\n\n\t\t// Return the interpolated quaternion\n\t\treturn qu;\n\t}\n\n\t// Slerp: Quaternion scaling\n\tQuat QuatSlerp(const Quat& q, double u)\n\t{\n\t\t// Ensure the w component is non-negative\n\t\tQuat qu = (q.w() < 0.0 ? -q : q);\n\n\t\t// If q is a very small rotation then just use linear interpolation, otherwise use spherical linear interpolation\n\t\tif(qu.w() >= 1.0 - 5e-9) // A w component within this tolerance of unity produces a negligible amount of error if using linear interpolation instead\n\t\t{\n\t\t\t// Perform the required interpolation\n\t\t\tqu *= u;\n\t\t\tqu.w() += (1.0 - u);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate half the angle magnitude of the quaternion\n\t\t\tdouble htheta = acos(qu.w());\n\n\t\t\t// Perform the required interpolation\n\t\t\tqu *= sin(u*htheta);\n\t\t\tqu.w() += sin((1.0 - u)*htheta);\n\t\t}\n\n\t\t// Normalise the interpolated quaternion\n\t\tNormaliseQuat(qu);\n\n\t\t// Return the interpolated quaternion\n\t\treturn qu;\n\t}\n\n\t// Slerp: Unit vector\n\tVec3 VecSlerp(const Vec3& v0, const Vec3& v1, double u)\n\t{\n\t\t// Normalise the input vectors\n\t\tVec3 v0hat = NormalisedVec(v0);\n\t\tVec3 v1hat = NormalisedVec(v1);\n\n\t\t// Calculate the dot product of the two vectors\n\t\tdouble dprod = v0hat.x()*v1hat.x() + v0hat.y()*v1hat.y() + v0hat.z()*v1hat.z();\n\n\t\t// If v0hat and v1hat are very close then just use linear interpolation, otherwise use spherical linear interpolation\n\t\tVec3 vu;\n\t\tif(dprod >= 1.0 - 5e-9) // A dot product within this tolerance of unity produces a negligible amount of error if using linear interpolation instead\n\t\t{\n\t\t\t// Perform the required interpolation\n\t\t\tvu = (1.0 - u)*v0hat + u*v1hat;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate half the angle between the two quaternions\n\t\t\tdouble htheta = acos(dprod);\n\n\t\t\t// Perform the required interpolation\n\t\t\tvu = sin((1.0 - u)*htheta)*v0hat + sin(u*htheta)*v1hat;\n\t\t}\n\n\t\t// Normalise the interpolated vector\n\t\tNormaliseVec(vu);\n\n\t\t// Return the interpolated vector\n\t\treturn vu;\n\t}\n\n\t// ##############################\n\t// #### Tilt phase functions ####\n\t// ##############################\n\n\t// Conversion: Tilt phase velocity 2D --> Angular velocity (assumes zero pzVel)\n\tvoid AngFromTiltPhaseVel(const TiltPhaseVel2D& pdot, const TiltAngles& t, AngVel& angVel)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble cgamma = cos(t.tiltAxisAngle);\n\t\tdouble sgamma = sin(t.tiltAxisAngle);\n\t\tdouble psigam = t.fusedYaw + t.tiltAxisAngle;\n\t\tdouble cpsigam = cos(psigam);\n\t\tdouble spsigam = sin(psigam);\n\n\t\t// Precalculate additional terms\n\t\tdouble S, C;\n\t\tif(t.tiltAngle == 0.0)\n\t\t{\n\t\t\tS = 1.0;\n\t\t\tC = 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tS = sin(t.tiltAngle) / t.tiltAngle;\n\t\t\tC = (1.0 - cos(t.tiltAngle)) / t.tiltAngle;\n\t\t}\n\n\t\t// Calculate the tilt velocity parameters\n\t\tdouble alphadot = pdot.pxVel*cgamma + pdot.pyVel*sgamma;\n\t\tdouble agammadot = pdot.pyVel*cgamma - pdot.pxVel*sgamma; // = alpha*gammadot\n\n\t\t// Calculate the required angular velocity\n\t\tangVel.x() = cpsigam*alphadot - S*agammadot*spsigam;\n\t\tangVel.y() = spsigam*alphadot + S*agammadot*cpsigam;\n\t\tangVel.z() = C*agammadot;\n\t}\n\n\t// Conversion: Tilt phase velocity 3D --> Angular velocity\n\tvoid AngFromTiltPhaseVel(const TiltPhaseVel3D& pdot, const TiltAngles& t, AngVel& angVel)\n\t{\n\t\t// Calculate the required angular velocity\n\t\tTiltPhaseVel2D pdot2D = pdot;\n\t\tAngFromTiltPhaseVel(pdot2D, t, angVel);\n\t\tangVel.z() += pdot.pzVel;\n\t}\n\n\t// #######################\n\t// #### Miscellaneous ####\n\t// #######################\n\n\t// Conversion: Split yaw and tilt --> Quaternion\n\t// Calculates qHB for the frame B that has a given fused yaw relative to G and tilt rotation component relative to H\n\t// qGH       ==> Relative quaternion rotation between G and H\n\t// fusedYawG ==> Desired fused yaw of B relative to G\n\t// qH        ==> Specification of the desired tilt rotation component of B relative to H, can be any qHC that has the\n\t//               same tilt rotation component as is desired for qHB\n\tQuat QuatHFromFYawGTiltH(const Quat& qGH, double fusedYawG, const Quat& qH)\n\t{\n\t\t// Precalculate trigonometric values\n\t\tdouble chpsi = cos(0.5*fusedYawG);\n\t\tdouble shpsi = sin(0.5*fusedYawG);\n\n\t\t// Construct the base components of the solution\n\t\tdouble a = qGH.x()*qH.x() + qGH.y()*qH.y();\n\t\tdouble b = qGH.x()*qH.y() - qGH.y()*qH.x();\n\t\tdouble c = qGH.w()*qH.z() + qGH.z()*qH.w();\n\t\tdouble d = qGH.w()*qH.w() - qGH.z()*qH.z();\n\t\tdouble A = d - a;\n\t\tdouble B = b - c;\n\t\tdouble C = b + c;\n\t\tdouble D = d + a;\n\t\tdouble G = D*chpsi - B*shpsi;\n\t\tdouble H = A*shpsi - C*chpsi;\n\t\tdouble F = sqrt(G*G + H*H);\n\n\t\t// Construct and return the output quaternion\n\t\tif(F < 64.0*DBL_EPSILON)\n\t\t\treturn qH;\n\t\telse\n\t\t{\n\t\t\tdouble chphi = G/F;\n\t\t\tdouble shphi = H/F;\n\t\t\treturn Quat(chphi*qH.w() - qH.z()*shphi, chphi*qH.x() - qH.y()*shphi, chphi*qH.y() + qH.x()*shphi, chphi*qH.z() + qH.w()*shphi); // Order: (w,x,y,z)\n\t\t}\n\t}\n}\n// EOF", "meta": {"hexsha": "ffeb5b079ff8ec21cb85bc8c43be2dcc479333a2", "size": 90056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rot_conv/src/rot_conv.cpp", "max_stars_repo_name": "ssr-yuki/humanoid_op_ros", "max_stars_repo_head_hexsha": "e8be8c445ead8c0d470c7998fdc28446ca9eb47a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rot_conv/src/rot_conv.cpp", "max_issues_repo_name": "ssr-yuki/humanoid_op_ros", "max_issues_repo_head_hexsha": "e8be8c445ead8c0d470c7998fdc28446ca9eb47a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T04:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-10T12:59:36.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rot_conv/src/rot_conv.cpp", "max_forks_repo_name": "ssr-yuki/humanoid_op_ros", "max_forks_repo_head_hexsha": "e8be8c445ead8c0d470c7998fdc28446ca9eb47a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 28.7259968102, "max_line_length": 530, "alphanum_fraction": 0.6289642001, "num_tokens": 30680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5627560612913292}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// Test code for a Hermitian\n// Lanczos without restarts, deflation, etc.\n// Based on arXiv:1512.08135.\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\n#include \"blas/generic_vector.h\"\n\n#include \"../square_laplace.h\"\n\n// Operator class\n#include \"../operator.h\"\n\n// Lanczos\n#include \"../lanczos.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> dMatrix;\ntypedef Matrix<std::complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\n\nint main(int argc, char** argv)\n{  \n  complex<double> *rhs_cplx;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // RNG related things.\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n  double inv_variance = 6.0; // inverse of variance for gaussian non-compact U(1) links.\n\n  // Basic information about the lattice.\n  int length = 8;\n  double m_sq = 0.001;\n  \n  // Some start-up.\n  int volume = length*length;\n  \n  // Create a random compact U(1) link.\n  complex<double>* gauge_links = allocate_vector<complex<double>>(2*length*length);\n  gaussian_real(gauge_links, 2*length*length, generator, 1.0/inv_variance);\n  polar(gauge_links, 2*length*length);\n  \n  // Vectors.\n  rhs_cplx = allocate_vector<complex<double>>(volume);\n\n  // Zero out the vector.\n  zero_vector(rhs_cplx, length*length);\n\n  // Structure which gets passed to the function.\n  laplace_gauged_struct lapstr_gauged;\n  lapstr_gauged.length = length;\n  lapstr_gauged.m_sq = m_sq;\n  lapstr_gauged.gauge_links = gauge_links; \n\n  // Uncomment this to get the free field.\n  //constant_vector(gauge_links, 1.0, 2*volume);\n  //std::cout << \"Free case.\\n\\n\";\n\n  std::cout << \"Interacting case.\\n\\n\";\n\n\n  // Create an object. Wrap the square laplace function for convenience.\n  FunctionWrapper<complex<double>> lap_fcn(square_laplacian_gauged, &lapstr_gauged, volume);\n\n  // m-step\n  const int m = 20;\n\n  // Create a Lanczos object.\n  SimpleComplexLanczos<double> lanczos(&lap_fcn, m, generator);\n\n  // Compute eigenvalues\n  lanczos.compute();\n\n  // Get Ritz values\n  double* ritzvalues = new double[m];\n  lanczos.ritzvalues(ritzvalues);\n\n  // Print the Ritz values\n  std::cout << \"The Ritz values from a search space of size \" << m << \" are:\\n\";\n  for (int i = 0; i < m; i++) {\n    std::cout << ritzvalues[i] << \"\\n\";\n  }\n\n  complex<double>** ritzvectors = new complex<double>*[m];\n  for (int i = 0; i < m; i++) {\n    ritzvectors[i] = allocate_vector<complex<double>>(volume);\n  }\n\n  // Get the Ritz vectors\n  lanczos.ritzvectors(ritzvectors);\n\n\n  // Comparison: Let's get the eigenvalues of the full operator!\n  // Allocate a sufficiently gigantic matrix.\n  cMatrix mat_cplx = cMatrix::Zero(volume, volume);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix and cMatrix are column major.\n  // I should probably make this safer by using a \"Map\".\n  for (int i = 0; i < volume; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    zero_vector(rhs_cplx, volume);\n    rhs_cplx[i] = 1.0;\n\n    // Where we put the result of the matrix element.\n    complex<double>* mptr = &(mat_cplx(i*volume));\n\n    lap_fcn(mptr, rhs_cplx);\n  }\n\n  // Get the eigenvalues.\n  SelfAdjointEigenSolver<cMatrix> eigsolve_cplx(volume);\n  eigsolve_cplx.compute(mat_cplx);\n\n  std::cout << \"The eigenvalues are:\\n\" << eigsolve_cplx.eigenvalues() << \"\\n\";\n\n  ////////////////////////////////\n  // COMPARE LOWEST EIGENVECTOR //\n  ////////////////////////////////\n\n  std::cout << \"\\n\\nCompare results, smallest eigenvalue:\\n\\n\";\n  std::cout << \"Lanczos Exact Ratio\\n\";\n  for (int i = 0; i < volume; i++) {\n    std::cout << ritzvectors[0][i] << \" \" << eigsolve_cplx.eigenvectors()(i,0)\n              << \" \" << ritzvectors[0][i]/eigsolve_cplx.eigenvectors()(i,0) << \"\\n\";\n  }\n\n  /////////////////////////////////\n  // COMPARE LARGEST EIGENVECTOR //\n  /////////////////////////////////\n\n  std::cout << \"\\n\\nCompare results, largest eigenvalue:\\n\\n\";\n  std::cout << \"Lanczos Exact Ratio\\n\";\n  for (int i = 0; i < volume; i++) {\n    std::cout << ritzvectors[m-1][i] << \" \" << eigsolve_cplx.eigenvectors()(i,volume-1)\n              << \" \" << ritzvectors[m-1][i]/eigsolve_cplx.eigenvectors()(i,volume-1) << \"\\n\";\n  }\n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  delete[] ritzvalues;\n\n  for (int i = 0; i < m; i++) {\n    deallocate_vector(&ritzvectors[i]);\n  }\n  delete[] ritzvectors;\n\n  deallocate_vector(&rhs_cplx);\n  deallocate_vector(&gauge_links);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "4c0e847db7bcb76169318d11da5d0e57a2c7fa69", "size": 4634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/lanczos_tests/lanczos/lanczos.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/lanczos_tests/lanczos/lanczos.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/lanczos_tests/lanczos/lanczos.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2588235294, "max_line_length": 93, "alphanum_fraction": 0.642209754, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5627560554032776}}
{"text": "#include \"Parameterization.hpp\"\n\n#include \"Geometry/Mesh/HEMesh.hpp\"\n\n__pragma(warning(push, 0))\n#include <Eigen/Eigen>\n\n    __pragma(warning(pop))\n\n        namespace Ilum::geometry\n{\n\tstd::pair<std::vector<Vertex>, std::vector<uint32_t>> Parameterization::MinimumSurface(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices)\n\t{\n\t\tHEMesh hemesh(preprocess(in_vertices), in_indices);\n\n\t\tsize_t longest_boundaries = 0;\n\t\tauto   boundaries         = hemesh.boundary();\n\n\t\tif (boundaries.empty())\n\t\t{\n\t\t\tLOG_ERROR(\"Mesh doesn't have boundary\");\n\t\t\treturn std::make_pair(in_vertices, in_indices);\n\t\t}\n\n\t\t// Find longest boundary\n\t\tfor (size_t i = 0; i < boundaries.size(); i++)\n\t\t{\n\t\t\tif (boundaries[longest_boundaries].size() < boundaries[i].size())\n\t\t\t{\n\t\t\t\tlongest_boundaries = i;\n\t\t\t}\n\t\t}\n\t\tauto boundary = std::move(boundaries[longest_boundaries]);\n\n\t\t// Build Laplace Matrix\n\t\tsize_t nV = hemesh.vertices().size();\n\n\t\tstd::vector<Eigen::Triplet<float>> Lij;\n\n\t\tfor (size_t i = 0; i < nV; i++)\n\t\t{\n\t\t\tauto *v = hemesh.vertices()[i];\n\t\t\tLij.push_back(Eigen::Triplet<float>(static_cast<int32_t>(i), static_cast<int32_t>(i), 1.f));\n\t\t\tif (std::find(boundary.begin(), boundary.end(), v) == boundary.end())\n\t\t\t//if (!hemesh.onBoundary(v))\n\t\t\t{\n\t\t\t\tauto adj_vertices = hemesh.adjVertices(v);\n\t\t\t\tfor (size_t j = 0; j < adj_vertices.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tLij.push_back(Eigen::Triplet<float>(static_cast<int32_t>(i), static_cast<int32_t>(hemesh.vertexIndex(adj_vertices[j])), -1.f / static_cast<float>(adj_vertices.size())));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tEigen::SparseMatrix<float> Laplace_matrix;\n\t\tLaplace_matrix.resize(nV, nV);\n\t\tLaplace_matrix.setZero();\n\t\tLaplace_matrix.setFromTriplets(Lij.begin(), Lij.end());\n\n\t\t// LU solver\n\t\tEigen::SparseLU<Eigen::SparseMatrix<float>> solver;\n\n\t\tsolver.compute(Laplace_matrix);\n\t\tif (solver.info() != Eigen::Success)\n\t\t{\n\t\t\tLOG_ERROR(\"Laplace Matrix Is Error!\");\n\t\t\treturn std::make_pair(in_vertices, in_indices);\n\t\t}\n\n\t\tEigen::MatrixXf V(nV, 3);\n\t\tEigen::MatrixXf b(nV, 3);\n\n\t\tV.setZero();\n\t\tb.setZero();\n\n\t\tfor (size_t i = 0; i < nV; i++)\n\t\t{\n\t\t\tauto *v = hemesh.vertices()[i];\n\t\t\t//if (hemesh.onBoundary(v))\n\t\t\tif (std::find(boundary.begin(), boundary.end(), v) != boundary.end())\n\t\t\t{\n\t\t\t\tb(i, 0) = v->position.x;\n\t\t\t\tb(i, 1) = v->position.y;\n\t\t\t\tb(i, 2) = v->position.z;\n\t\t\t}\n\t\t}\n\n\t\tV = solver.solve(b);\n\n\t\tfor (size_t i = 0; i < nV; i++)\n\t\t{\n\t\t\tauto *v       = hemesh.vertices()[i];\n\t\t\tv->position.x = V(i, 0);\n\t\t\tv->position.y = V(i, 1);\n\t\t\tv->position.z = V(i, 2);\n\t\t}\n\n\t\tauto [vertices, indices] = hemesh.toMesh();\n\n\t\tstd::vector<glm::vec2> texcoords(in_vertices.size());\n\t\tfor (size_t i = 0; i < texcoords.size(); i++)\n\t\t{\n\t\t\ttexcoords[i] = in_vertices[i].texcoord;\n\t\t}\n\n\t\treturn std::make_pair(postprocess(vertices, indices, texcoords), std::move(indices));\n\t}\n\n\tstd::pair<std::vector<Vertex>, std::vector<uint32_t>> Parameterization::TutteParameterization(const std::vector<Vertex> &in_vertices, const std::vector<uint32_t> &in_indices, TutteWeightType weight_type)\n\t{\n\t\treturn std::pair<std::vector<Vertex>, std::vector<uint32_t>>();\n\t}\n}        // namespace Ilum::geometry", "meta": {"hexsha": "3adaae2d99ef41c8aa20d2bb9fd6fbde046015e4", "size": 3140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Ilum/Geometry/Mesh/Process/Parameterization.cpp", "max_stars_repo_name": "Chaf-Libraries/Ilum", "max_stars_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T05:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:35:16.000Z", "max_issues_repo_path": "Source/Ilum/Geometry/Mesh/Process/Parameterization.cpp", "max_issues_repo_name": "Chaf-Libraries/Ilum", "max_issues_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_issues_repo_licenses": ["MIT"], "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/Ilum/Geometry/Mesh/Process/Parameterization.cpp", "max_forks_repo_name": "Chaf-Libraries/Ilum", "max_forks_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-20T15:39:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T15:39:03.000Z", "avg_line_length": 27.7876106195, "max_line_length": 204, "alphanum_fraction": 0.647133758, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5627444721250485}}
{"text": "#include <armadillo>\n#include <gnuplot-iostream.h>\n\nusing namespace arma;\nusing namespace std;\n\nnamespace ic {\n\nclass SOM {\npublic:\n    // Constructores\n    SOM(const mat& patrones, pair<int, int> dimensiones, const vec& salidaDeseada = {});\n\n    // Interfaz\n    void entrenar(int nEpocas,\n                  double velocidadInicial,\n                  double velocidadFinal,\n                  int vecindadInicial,\n                  int vecindadFinal);\n    void etiquetar();\n    int clasificar(const rowvec& patron) const;\n    vec clasificar(const mat& patrones) const;\n    void graficar(Gnuplot& gp, bool graficarVecindades = true) const;\n\n    // Acceso a miembros\n    const field<rowvec>& mapa() const { return m_mapa; };\n    const mat& etiquetas() const { return m_etiquetas; };\n    const mat& patrones() const { return m_patrones; };\n\nprivate:\n    field<rowvec> m_mapa;\n    mat m_etiquetas;\n    const mat m_patrones;\n    const vec m_salidaDeseada;\n\n    pair<pair<int, int>, double> buscarGanadora(const rowvec& patron) const;\n};\n\nSOM::SOM(const mat& patrones, pair<int, int> dimensiones, const vec& salidaDeseada)\n    : m_patrones{patrones}\n    , m_salidaDeseada{salidaDeseada}\n{\n    m_mapa = field<rowvec>(dimensiones.first, dimensiones.second);\n\n    // Inicializar mapa\n    for (unsigned int i = 0; i < m_mapa.n_rows; ++i) {\n        for (unsigned int j = 0; j < m_mapa.n_cols; ++j) {\n            m_mapa(i, j) = randu<rowvec>(patrones.n_cols) - 0.5;\n        }\n    }\n}\n\npair<pair<int, int>, double> SOM::buscarGanadora(const rowvec& patron) const\n{\n    pair<int, int> coordGanadora;\n    double distanciaGanadora = numeric_limits<double>::max();\n\n    for (unsigned int j = 0; j < m_mapa.n_rows; ++j) {\n        for (unsigned int k = 0; k < m_mapa.n_cols; ++k) {\n            const double distancia = norm(patron - m_mapa(j, k));\n\n            if (distancia < distanciaGanadora) {\n                distanciaGanadora = distancia;\n                coordGanadora = {j, k};\n            }\n        }\n    }\n\n    return {coordGanadora, distanciaGanadora};\n}\n\nvoid SOM::entrenar(int nEpocas,\n                   double velocidadInicial,\n                   double velocidadFinal,\n                   int vecindadInicial,\n                   int vecindadFinal)\n{\n    const vec velocidad = linspace(velocidadInicial, velocidadFinal, nEpocas);\n    // Redondeamos la vecindad porque necesitamos que tenga valores enteros\n    const vec vecindad = round(linspace(vecindadInicial, vecindadFinal, nEpocas));\n\n    for (int epoca = 0; epoca < nEpocas; ++epoca) {\n        for (unsigned int n = 0; n < m_patrones.n_rows; ++n) {\n\n            // Buscamos la neurona ganadora\n            pair<int, int> coordGanadora;\n            double distanciaGanadora;\n            tie(coordGanadora, distanciaGanadora) = buscarGanadora(m_patrones.row(n));\n\n            // Adaptación de pesos\n            const int maxX = int(m_mapa.n_rows - 1);\n            const int maxY = int(m_mapa.n_cols - 1);\n            const int xInicial = (coordGanadora.first - vecindad(epoca) < 0) ? 0 : (coordGanadora.first - vecindad(epoca));\n            const int xFinal = (coordGanadora.first + vecindad(epoca) > maxX) ? maxX : (coordGanadora.first + vecindad(epoca));\n            const int yInicial = (coordGanadora.second - vecindad(epoca) < 0) ? 0 : (coordGanadora.second - vecindad(epoca));\n            const int yFinal = (coordGanadora.second + vecindad(epoca) > maxY) ? maxY : (coordGanadora.second + vecindad(epoca));\n\n            for (int x = xInicial; x <= xFinal; ++x) {\n                for (int y = yInicial; y <= yFinal; ++y) {\n                    m_mapa(x, y) += velocidad(epoca) * (m_patrones.row(n) - m_mapa(x, y));\n                }\n            }\n        }\n    }\n}\n\nvoid SOM::etiquetar()\n{\n    if (m_salidaDeseada.empty())\n        throw runtime_error(\"Este SOM no posee una salida deseada asociada a los patrones\");\n\n    field<ivec> mapaContador(m_mapa.n_rows, m_mapa.n_cols);\n\n    // Inicializar los contadores de clases\n    for (unsigned int x = 0; x < m_mapa.n_rows; ++x) {\n        for (unsigned int y = 0; y < m_mapa.n_cols; ++y) {\n            mapaContador(x, y) = zeros<ivec>(2);\n        }\n    }\n\n    // Contamos, para cada neurona, qué cantidad de veces gana para cada clase\n    for (unsigned int n = 0; n < m_patrones.n_rows; ++n) {\n        pair<int, int> ganadora;\n        tie(ganadora, ignore) = buscarGanadora(m_patrones.row(n));\n\n        if (m_salidaDeseada(n) == 0)\n            mapaContador(ganadora.first, ganadora.second).at(0) += 1;\n        else\n            mapaContador(ganadora.first, ganadora.second).at(1) += 1;\n    }\n\n    m_etiquetas = mat(m_mapa.n_rows, m_mapa.n_cols);\n\n    // Se asignan las etiquetas de clase\n    for (unsigned int x = 0; x < m_mapa.n_rows; ++x) {\n        for (unsigned int y = 0; y < m_mapa.n_cols; ++y) {\n            if (mapaContador(x, y)(0) == mapaContador(x, y)(1))\n                // Si la neurona ganó la misma cantidad de veces para ambas clases,\n                // se le asigna la clase al azar.\n                m_etiquetas(x, y) = as_scalar(randi(1, distr_param(0, 1)));\n            else\n                m_etiquetas(x, y) = index_max(mapaContador(x, y));\n        }\n    }\n}\n\nint SOM::clasificar(const rowvec& patron) const\n{\n    pair<int, int> ganadora;\n    tie(ganadora, ignore) = buscarGanadora(patron);\n\n    return m_etiquetas(ganadora.first, ganadora.second);\n}\n\nvec SOM::clasificar(const mat& patrones) const\n{\n    vec result = zeros(patrones.n_rows);\n\n    for (unsigned int n = 0; n < patrones.n_rows; ++n) {\n        result(n) = clasificar(rowvec{patrones.row(n)});\n    }\n\n    return result;\n}\n\nvoid SOM::graficar(Gnuplot& gp, bool graficarVecindades) const\n{\n    gp << \"set key box opaque width 3\" << endl\n       << \"set xlabel 'x_1' font ',11'\" << endl\n       << \"set ylabel 'x_2' font ',11'\" << endl\n\n       // Graficar patrones\n       << \"plot \" << gp.file1d(m_patrones) << \"title 'Patrones' with points pt 2 ps 1 lt rgb 'blue', \";\n\n    // Graficar neuronas del mapa y las conexiones\n    for (unsigned int x = 0; x < m_mapa.n_rows; ++x) {\n        for (unsigned int y = 0; y < m_mapa.n_cols; ++y) {\n            // Graficar la neurona\n            gp << gp.file1d(m_mapa(x, y).eval()) << \"notitle with points ps 2 pt 1 lt -1 lw 3, \";\n\n            if (graficarVecindades) {\n                // Graficar conexiones con las vecinas horizontales y verticales\n                if (x != 0)\n                    gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x - 1, y)).eval()) << \"notitle with lines lt -1, \";\n                if (x != m_mapa.n_rows - 1)\n                    gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x + 1, y)).eval()) << \"notitle with lines lt -1, \";\n                if (y != 0)\n                    gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y - 1)).eval()) << \"notitle with lines lt -1, \";\n                if (y != m_mapa.n_cols - 1)\n                    gp << gp.file1d(join_vert(m_mapa(x, y), m_mapa(x, y + 1)).eval()) << \"notitle with lines lt -1, \";\n            }\n        }\n    }\n\n    // Título de los centroides para la leyenda\n    gp << \"NaN title 'Neuronas' with points ps 2 pt 1 lt -1 lw 3\" << endl;\n}\n}\n", "meta": {"hexsha": "d53261fee06881fed8b121a2ec436969a7a34e43", "size": 7139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia2/som.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia2/som.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia2/som.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8743718593, "max_line_length": 129, "alphanum_fraction": 0.584255498, "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5626153700120025}}
{"text": "//\n// Copyright 2017 Will Mitchell\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#include \"stats/Confidence.h\"\n\n#include <boost/math/distributions/students_t.hpp>\nnamespace bm = boost::math;\n\ndouble stats::confidence_bound(double sample_size, double variance,\n                               double confidence) {\n  // Can't have a confidence with fewer than 2 samples\n  if (sample_size < 2)\n    return 0;\n\n  bm::students_t dist(sample_size - 1);\n  double T = bm::quantile(bm::complement(dist, (1 - confidence) / 2));\n  return T * sqrt(variance) / sqrt(sample_size);\n}\n", "meta": {"hexsha": "5619da708a15d466f8d412f7f226cea2bf5c4726", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/stats/Confidence.cpp", "max_stars_repo_name": "wtmitchell/bloom_filter_encoding-graph-attack", "max_stars_repo_head_hexsha": "2a4d61670b37f29923f872c5e6acff7ac358c594", "max_stars_repo_licenses": ["Apache-2.0"], "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/stats/Confidence.cpp", "max_issues_repo_name": "wtmitchell/bloom_filter_encoding-graph-attack", "max_issues_repo_head_hexsha": "2a4d61670b37f29923f872c5e6acff7ac358c594", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/stats/Confidence.cpp", "max_forks_repo_name": "wtmitchell/bloom_filter_encoding-graph-attack", "max_forks_repo_head_hexsha": "2a4d61670b37f29923f872c5e6acff7ac358c594", "max_forks_repo_licenses": ["Apache-2.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.9333333333, "max_line_length": 75, "alphanum_fraction": 0.7124304267, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.5626153542811007}}
{"text": "#include <Eigen/Core>\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 std::size_t k_num_dims = 2;\n\n    constexpr double k_youngs_modulus = 200.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 = 5;\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 = 10000.0;\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\nstruct Constraint\n{\n    std::size_t                              vert_index;\n    std::function<Eigen::Vector2d(double t)> motion;\n    double                                   stiffness;\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, 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 VariationalImplicit2dEngine\n{\npublic:\n    VariationalImplicit2dEngine() {}\n\n    void proceedFrame()\n    {\n        const std::size_t num_verts = m_mesh.x_rest.size() / k_num_dims;\n\n        // Reset forces\n        m_mesh.f = Eigen::VectorXd::Zero(2 * num_verts);\n\n        // Apply gravity force\n        for (std::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 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        const auto calcInternalPotential = [&](const Eigen::VectorXd& x)\n        {\n            double sum = 0.0;\n\n            // Elastic potential\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\n                // Calculate the deformation gradient $\\mathbf{F}$\n                const auto F = elasty::fem::calc2dTriangleDeformGrad(\n                    x.segment<2>(2 * indices[0]), x.segment<2>(2 * indices[1]), x.segment<2>(2 * indices[2]), D_m_inv);\n\n                sum += area * 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<2>(vert_index * 2);\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            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 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(\n                    x.segment<2>(2 * indices[0]), x.segment<2>(2 * indices[1]), x.segment<2>(2 * indices[2]), 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 $\\frac{\\partial E}{\\partial \\mathbf{x}}$\n                const auto PEPx = area * PPsiPx;\n\n                sum.segment<2>(2 * indices[0]) += PEPx.segment<2>(0 * 2);\n                sum.segment<2>(2 * indices[1]) += PEPx.segment<2>(1 * 2);\n                sum.segment<2>(2 * indices[2]) += PEPx.segment<2>(2 * 2);\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<2>(vert_index * 2);\n                const auto        q          = constraint.motion(m_physics_time + m_delta_physics_time);\n                const auto        r          = p - q;\n\n                sum.segment<2>(2 * vert_index) += k * r;\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, 100, 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 naive damping\n        m_mesh.v *= std::exp(-k_damping_factor * m_delta_physics_time);\n\n        // Update time counter\n        m_physics_time += m_delta_physics_time;\n    }\n\n    void initializeScene()\n    {\n        constexpr std::size_t num_cols  = 20;\n        constexpr std::size_t num_rows  = 5;\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        // Set constraints\n        for (std::size_t i = 0; i < num_rows + 1; ++i)\n        {\n            const auto motion = [&, i](double) -> Eigen::Vector2d\n            {\n                return m_mesh.x_rest.segment<2>(i * 2);\n            };\n\n            m_constraints.push_back(Constraint{i, motion, k_spring_stiffness});\n        }\n        for (std::size_t i = (num_rows + 1) * num_cols; i < (num_rows + 1) * (num_cols + 1); ++i)\n        {\n            const auto ease = [](double x)\n            {\n                return -(std::cos(3.14159265358979 * x) - 1.0) * 0.5;\n            };\n\n            const auto motion = [&, i](double t) -> Eigen::Vector2d\n            {\n                const auto   x_init = m_mesh.x_rest.segment<2>(i * 2);\n                const auto   dir    = Eigen::Vector2d{3.0, 0.0};\n                const double t_0    = 0.8;\n                const double t_1    = t_0 + 1.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);\n\n                return x_init + b * dir;\n            };\n\n            m_constraints.push_back(Constraint{i, motion, k_spring_stiffness});\n        }\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    double m_physics_time       = 0.0;\n\n    std::vector<Constraint> m_constraints;\n\n    TriangleMesh m_mesh;\n};\n\nint main(int argc, char** argv)\n{\n    VariationalImplicit2dEngine 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": "4b00fd375da27ebf39a2f12448a20ce723e43fe3", "size": 14331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/variational-implicit-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/variational-implicit-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/variational-implicit-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.0310077519, "max_line_length": 120, "alphanum_fraction": 0.5636731561, "num_tokens": 3718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5625835840661596}}
{"text": "/*\n *  polynomial_two.hpp\n *\n *\n *  Created by Andrea Bedini on 24/Nov/2011.\n *  Copyright (c) 2011-2014, Andrea Bedini <andrea.bedini@gmail.com>.\n *\n *  Distributed under the terms of the Modified BSD License.\n *  The full license is in the file COPYING, distributed as part of\n *  this software.\n *\n */\n\n#ifndef POLYNOMIAL_TWO_HPP\n#define POLYNOMIAL_TWO_HPP\n\n#include <boost/operators.hpp>\n#include <iosfwd>\n\ntemplate<class T>\nclass polynomial_two\n  : boost::ring_operators1< polynomial_two<T>\n  , boost::ring_operators2< polynomial_two<T>, T\n  , boost::equality_comparable< polynomial_two<T>\n  > > >\n{\npublic:\n  typedef unsigned short int index;\n  struct element {\n    index i, j;\n    T c;\n    bool operator==(element const& rhs) const\n    { return i == rhs.i and j == rhs.j and c == rhs.c; }\n  };\n\nprivate:\n  typedef std::vector<element> elements_type;\n  elements_type elements_;\n\npublic:\n  typedef typename elements_type::iterator iterator;\n  typedef typename elements_type::const_iterator const_iterator;\n\nprivate:\n  void cleanup() {\n    iterator i = elements_.begin();\n    while (i != elements_.end()) {\n      if (i->c == T(0))\n        i = elements_.erase(i);\n      else\n        ++i;\n    }\n  }\n\n  struct indices_less {\n    bool operator()(element const& a, element const& b) const\n    {\n      return a.i < b.i or (a.i == b.i and a.j < b.j);\n    }\n  };\n\n  struct indices_equal {\n    bool operator()(element const& a, element const& b) const\n    {\n      return a.i == b.i and a.j == b.j;\n    }\n  };\n\n  T& coeff(index i, index j)\n  {\n    const element e{i, j, T(0)};\n    auto it = std::lower_bound(elements_.begin(), elements_.end(), e, indices_less());\n    if (it == elements_.end() or not indices_equal()(*it, e)) {\n      it = elements_.insert(it, e);\n    }\n    return it->c;\n  }\n\n  polynomial_two(elements_type const& e) : elements_(e)\n  { }\n\npublic:\n  // default constructor\n  explicit polynomial_two(T const& a = T(0))\n    : elements_{{0, 0, a}}\n  {\n  }\n\n  polynomial_two(std::initializer_list<element> list)\n    : elements_(list)\n  {\n  }\n\n  // copy constructor\n  polynomial_two(polynomial_two<T> const& rhs)\n    : elements_(rhs.elements_)\n  {\n  }\n\n  // move constructor\n  polynomial_two(polynomial_two<T>&& rhs)\n    : elements_(std::move(rhs.elements_))\n  {\n  }\n  \n  // assignemnt\n  polynomial_two<T>& operator=(polynomial_two<T> const& rhs)\n  {\n    elements_ = rhs.elements_;\n    return *this;\n  }\n\n  polynomial_two<T>& operator=(polynomial_two<T>&& rhs)\n  {\n    elements_ = std::move(rhs.elements_);\n    return *this;\n  }\n\n  // conversions\n  template<typename T2>\n  friend class polynomial_two;\n\n  template<class T2>\n  explicit polynomial_two(T2 const& a)\n    : elements_{{0, 0, T(a)}}\n  {\n  }\n\n  template<class T2>\n  explicit polynomial_two(polynomial_two<T2> const& rhs)\n  {\n    for (auto const& e : rhs.elements_) {\n      coeff(e.i, e.j) = T(e.c);\n    }\n  }\n  template<class T2>\n  polynomial_two<T>& operator=(T2 const& rhs)\n  {\n    elements_ = {{0, 0, T(rhs)}};\n    return *this;\n  }\n\n  template<class T2>\n  polynomial_two<T>& operator=(polynomial_two<T2> const& rhs)\n  {\n    elements_.clear();\n    for (auto const& e : rhs.elements_) {\n      coeff(e.i, e.j) = T(e.c);\n    }\n    return *this;\n  }\n\n  // static constructors\n  \n  static polynomial_two<T> Q()\n  {\n    return {{1, 0, T(1)}};\n  }\n\n  static polynomial_two<T> v()\n  {\n    return {{0, 1, T(1)}};\n  }\n\n  // swap\n  void swap(polynomial_two<T>& other) throw ()\n  {\n    elements_.swap(other.elements_);\n  }\n  \n  // iterators\n  iterator begin() { return elements_.begin(); }\n  iterator end()   { return elements_.end(); }\n\n  const_iterator begin() const { return elements_.begin(); }\n  const_iterator end()   const { return elements_.end(); }\n\n   // comparison\n  bool operator==(polynomial_two<T> const& rhs) const\n  {\n    return std::equal(begin(), end(), rhs.begin());\n  }\n  \n  // ring operators with T\n  polynomial_two<T>& operator+=(T const& rhs)\n  {\n    coeff(0, 0) += rhs;\n    return *this;\n  }\n  \n  polynomial_two<T>& operator-=(T const& rhs)\n  {\n    coeff(0, 0) -= rhs;\n    return *this;\n  }\n  \n  polynomial_two<T>& operator*=(T const& rhs)\n  {\n    iterator it;\n    for (auto& e : elements_)\n      e.c *= rhs;\n    return *this;\n  }\n\n  // ring operators with polynomial_two<T>\n  polynomial_two<T>& operator+=(polynomial_two<T> const& rhs)\n  {\n    for (auto const& e : rhs.elements_)\n      coeff(e.i, e.j) += e.c;\n    cleanup();\n    return *this;\n  }\n  \n  polynomial_two<T>& operator-=(polynomial_two<T> const& rhs)\n  {\n    for (auto const& e : rhs.elements_)\n      coeff(e.i, e.j) -= e.c;\n    cleanup();\n    return *this;\n  }\n  \n  polynomial_two<T>& operator*=(polynomial_two<T> const& rhs)\n  {\n    polynomial_two<T> result;\n    for (auto const& e1 : rhs.elements_)\n      for (auto const& e2 : elements_)\n        result.coeff(e1.i + e2.i, e1.j + e2.j) += e1.c * e2.c;\n    swap(result);\n    return *this;\n  }\n\n  // unary\n\n  const polynomial_two<T> operator-() const\n  {\n    polynomial_two<T> result;\n    for (auto const& e : elements_)\n      result.coeff(e.i, e.j) = -e.c;\n    return result;\n  }\n\n  // member functions\n  \n  const polynomial_two<T> times_Q() const\n  {\n    polynomial_two<T> result;\n    for (auto const& e : elements_)\n      result.coeff(e.i + 1, e.j) = e.c;\n    return result;\n  }\n\n  const polynomial_two<T> times_v() const\n  {\n    polynomial_two<T> result;\n    for (auto const& e : elements_)\n      result.coeff(e.i, e.j + 1) = e.c;\n    return result;\n  }\n  \n  friend\n  std::ostream& operator<<(std::ostream& o, polynomial_two<T> const& p)\n  {\n    auto it = p.elements_.begin();\n    while (it != p.elements_.end()) {\n      T c = it->c;\n      if (c < 0) {\n        o << \"- \";\n        c = -c;\n      } else {\n        o << \"+ \";\n      }\n      if (c != 1 or (it->i == 0 and it->j == 0))\n        o << c << \" \";\n      if (it->i == 1)\n        o << \"Q \";\n      if (it->i > 1)\n        o << \"Q^\" << it->i << \" \";\n      if (it->j == 1)\n        o << \"v \";\n      if (it->j > 1)\n        o << \"v^\" << it->j << \" \";\n      ++ it;\n    }\n    return o;\n  }   \n};\n\ntemplate<class T>\nvoid swap(polynomial_two<T>& p1, polynomial_two<T>& p2) throw ()\n{\n  p1.swap(p2);\n}\n\n#endif // POLYNOMIAL_TWO_HPP\n", "meta": {"hexsha": "b19eff9140a8304c97ab7e23f0f65921c7eb166d", "size": 6167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utility/polynomial_two.hpp", "max_stars_repo_name": "andreabedini/tutte", "max_stars_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-29T23:04:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T13:33:46.000Z", "max_issues_repo_path": "include/utility/polynomial_two.hpp", "max_issues_repo_name": "andreabedini/tutte", "max_issues_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utility/polynomial_two.hpp", "max_forks_repo_name": "andreabedini/tutte", "max_forks_repo_head_hexsha": "6bd620e06f6ac27fafc75898a3b12e9995a5e964", "max_forks_repo_licenses": ["BSD-3-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.9050847458, "max_line_length": 86, "alphanum_fraction": 0.5834279228, "num_tokens": 1808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5625101981883527}}
{"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#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <smooth/derivatives.hpp>\n#include <smooth/feedback/ocp.hpp>\n#include <smooth/feedback/utils/sparse.hpp>\n#include <smooth/se2.hpp>\n\ntemplate<typename T>\nusing X = smooth::SE2<T>;\n\ntemplate<typename T>\nusing U = Eigen::Vector<T, 2>;\n\ntemplate<typename T>\nusing Q = Eigen::Vector<T, 1>;\n\ntemplate<typename T, std::size_t N>\nusing Vec = Eigen::Vector<T, N>;\n\nstatic constexpr auto Nx     = smooth::Dof<X<double>>;\nstatic constexpr auto Nq     = smooth::Dof<Q<double>>;\nstatic constexpr auto Nu     = smooth::Dof<U<double>>;\nstatic constexpr auto Ninner = 1 + Nx + smooth::Dof<U<double>>;\nstatic constexpr auto Nouter = 1 + 2 * Nx + smooth::Dof<Q<double>>;\n\nstatic constexpr auto t_B_inner = 0;\nstatic constexpr auto x_B_inner = t_B_inner + 1;\nstatic constexpr auto u_B_inner = x_B_inner + Nx;\n\nstatic constexpr auto tf_B_outer = 0;\nstatic constexpr auto x0_B_outer = tf_B_outer + 1;\nstatic constexpr auto xf_B_outer = x0_B_outer + Nx;\nstatic constexpr auto q_B_outer  = xf_B_outer + Nx;\n\n/// @brief Objective function\nstruct TestOcpObjective\n{\n  template<typename T>\n  T operator()(T, const X<T> &, const X<T> &, const Vec<T, 1> & q) const\n  {\n    return q.x();\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(1, Nouter);\n    ret.coeffRef(0, q_B_outer) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> &, const X<double> &, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Nouter, Nouter);\n    return ret;\n  }\n};\n\nstruct TestOcpDyn\n{\n  template<typename T>\n  smooth::Tangent<X<T>> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    return {\n      u.x() - 0.1 * x.r2().x(),\n      0,\n      u.y(),\n    };\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> & x, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Nx, Ninner);\n    ret.coeffRef(0, x_B_inner)     = -0.1 * std::cos(x.so2().angle());  // df1 / dx\n    ret.coeffRef(0, x_B_inner + 1) = 0.1 * std::sin(x.so2().angle());   // df1 / dy\n    ret.coeffRef(0, u_B_inner)     = 1;\n    ret.coeffRef(2, u_B_inner + 1) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> & x, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Ninner, Nx * Ninner);\n    ret.coeffRef(x_B_inner + 0, 0 * Nx + x_B_inner + 2) =\n      0.1 * std::sin(x.so2().angle());  // d2f1 / dx dth\n    ret.coeffRef(x_B_inner + 1, 0 * Nx + x_B_inner + 2) =\n      0.1 * std::cos(x.so2().angle());  // d2f1 / dy dth\n    return ret;\n  }\n};\n\nstruct TestOcpIntegrand\n{\n  template<typename T>\n  Vec<T, 1> operator()(T, const X<T> & x, const U<T> & u) const\n  {\n    return 0.5 * Vec<T, 1>{(x - X<T>::Identity()).squaredNorm() + u.squaredNorm()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> & x, const U<double> & u) const\n  {\n    const auto a = x - X<double>::Identity();\n    Eigen::SparseMatrix<double> ret(1, Ninner);\n    smooth::feedback::block_add(ret, 0, x_B_inner, smooth::dr_rminus_squarednorm<X<double>>(a));\n    ret.coeffRef(0, u_B_inner)     = u.x();\n    ret.coeffRef(0, u_B_inner + 1) = u.y();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> & x, const U<double> &) const\n  {\n    const auto H = smooth::d2r_rminus_squarednorm<X<double>>(x.log());\n\n    Eigen::SparseMatrix<double> ret(Ninner, 1 * Ninner);\n    smooth::feedback::block_add(ret, x_B_inner, x_B_inner, H);\n    ret.coeffRef(u_B_inner, u_B_inner)         = 1;\n    ret.coeffRef(u_B_inner + 1, u_B_inner + 1) = 1;\n    return ret;\n  }\n};\n\nstruct TestOcpCr\n{\n  template<typename T>\n  Vec<T, 1> operator()(T, const X<T> &, const U<T> & u) const\n  {\n    return Vec<T, 1>{u.x()};\n  }\n\n  Eigen::SparseMatrix<double> jacobian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(1, Ninner);\n    ret.coeffRef(0, u_B_inner) = 1;\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> hessian(double, const X<double> &, const U<double> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Ninner, 1 * Ninner);\n    return ret;\n  }\n};\n\nstruct TestOcpCe\n{\n  static constexpr auto Nce = 1 + 2 * Nx;\n\n  template<typename T>\n  Vec<T, Nce> operator()(T tf, const X<T> & x0, const X<T> & xf, const Vec<T, 1> &) const\n  {\n    Vec<T, Nce> ret;\n    ret << tf, x0.log(), xf.log();\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  jacobian(double, const X<double> & x0, const X<double> & xf, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Nce, Nouter);\n    ret.coeffRef(tf_B_outer, tf_B_outer) = 1;\n    smooth::feedback::block_add(\n      ret, x0_B_outer, x0_B_outer, smooth::dr_expinv<X<double>>(x0.log()));\n    smooth::feedback::block_add(\n      ret, xf_B_outer, xf_B_outer, smooth::dr_expinv<X<double>>(xf.log()));\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double>\n  hessian(double, const X<double> & x0, const X<double> & xf, const Vec<double, 1> &) const\n  {\n    Eigen::SparseMatrix<double> ret(Nouter, Nce * Nouter);\n\n    const auto d2_logx0 = smooth::d2r_rminus<X<double>>(x0.log());\n    const auto d2_logxf = smooth::d2r_rminus<X<double>>(xf.log());\n\n    for (auto i = 0u; i < Nx; ++i) {\n      smooth::feedback::block_add(\n        ret, x0_B_outer, Nouter * (1 + i) + x0_B_outer, d2_logx0.block(0, i * Nx, Nx, Nx));\n\n      smooth::feedback::block_add(\n        ret, xf_B_outer, Nouter * (1 + Nx + i) + xf_B_outer, d2_logxf.block(0, i * Nx, Nx, Nx));\n    }\n\n    return ret;\n  }\n};\n\nusing OcpTest = smooth::feedback::\n  OCP<X<double>, U<double>, TestOcpObjective, TestOcpDyn, TestOcpIntegrand, TestOcpCr, TestOcpCe>;\n\ninline const OcpTest ocp_test{\n  .theta = TestOcpObjective{},\n  .f     = TestOcpDyn{},\n  .g     = TestOcpIntegrand{},\n  .cr    = TestOcpCr{},\n  .crl   = Vec<double, 1>{{-1}},\n  .cru   = Vec<double, 1>{{1}},\n  .ce    = TestOcpCe{},\n  .cel   = Vec<double, 1 + 2 * Nx>::Random(),\n  .ceu   = Vec<double, 1 + 2 * Nx>::Random(),\n};\n", "meta": {"hexsha": "23ca6d81cbff9ac060983fdb09e02c13ec21d36c", "size": 7294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/ocp.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/ocp.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/ocp.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9912280702, "max_line_length": 98, "alphanum_fraction": 0.6502604881, "num_tokens": 2214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.5625101981883526}}
{"text": "// Geometric Modeling\n// Final Project\n// 2D Harmonic Coordinates\n// Author: Weiqiang Li\n// wl1731@nyu.edu\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/triangle/triangulate.h>\n#include <igl/project.h>\n#include <igl/unproject.h>\n#include <igl/readOFF.h>\n#include <igl/slice.h>\n#include <igl/cotmatrix.h>\n#include <igl/boundary_facets.h>\n#include <igl/unique.h>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n\n// this project is aimed for harmonic coordinates for mesh deformation\n// the supposed usage is any of the following:\n// ./final_bin\n// which will run the algorithm based on default mesh and cage\n// ./final_bin <mesh.off>\n// which will read the mesh and automatically build a cage based on the boundary of the mesh\n// ./final_bin <mesh.off> <cage.cage>\n// which will read the mesh and cage from file\n// where mesh.off is the mesh information (V and F)\n// in mesh.off, the z coordinates are assumed 0 (not used)\n// cage.cage is the cage information (V)\n// in cage.cage, the z coordinates are assumed 0 (not used)\n// the vertices in cage.cage should be either ordered clockwise or counterclockwise\n// interaction manual:\n// use mouse (click and drag) to change the location of cage vertex\n// the new mesh will be calculated automatically\n// press R to reset the cage and mesh to original position\n// press U to undo the cage vertex change (only once)\n// use W/A/S/D to control the cage vertex location after selected by mouse\n// the new mesh will be cauculated automatically\n\nusing namespace std;\nusing namespace Eigen;\nusing Viewer = igl::opengl::glfw::Viewer;\n\n// debug flags\n// #define DEBUG_1\n// #define DEBUG_2\n// #define DEBUG_3\n\n// mesh\nMatrixXd V;\nMatrixXi F;\n// mesh archive\nMatrixXd V1;\nMatrixXd V2;\n\n// cage\nMatrixXd CV;\nMatrixXi CE;\n// cage archive\nMatrixXd CV1;\nMatrixXd CV2;\n\n// triangulate helper\nMatrixXd VV0;\nMatrixXi VF0;\n\n// harmonic helper\nSparseMatrix<double> Aff, Afc;\nMatrixXd H;\n\n// interactions helper\nbool mouse_down = false;\nint current_cage_vertex = -1;\ndouble keyboard_stride = 0.0;\n\n// declarations\nvoid plot_mesh_and_cage(igl::opengl::glfw::Viewer &viewer);\nbool callback_key_down(Viewer &viewer, unsigned char key, int modifiers);\nint find_nearest_cage(RowVector3d loc);\nbool callback_mouse_down(Viewer& viewer, int, int);\nbool callback_mouse_move(Viewer& viewer, int mouse_x, int mouse_y);\nbool callback_mouse_up(Viewer& viewer, int, int);\nvoid solve_prepare();\nvoid solve_harmonic();\nbool read_cage_from_file(string cage_filename);\nvoid generate_cage();\n\n\n// plots mesh (in V and F) and cage (in CV and CE)\n// during mouse click and drag, the selected cage vertex will be marked green\nvoid plot_mesh_and_cage(igl::opengl::glfw::Viewer &viewer) {\n  viewer.data().clear();\n  viewer.data().set_mesh(V, F);\n\n  if (mouse_down) {\n    for (unsigned i = 0; i < CV.rows(); i++) {\n      if (i == current_cage_vertex) {\n        viewer.data().add_points(CV.row(i), RowVector3d(0,1,0));\n      } else {\n        viewer.data().add_points(CV.row(i), RowVector3d(1,0,0));\n      }\n    }\n  } else {\n    viewer.data().add_points(CV, RowVector3d(1,0,0));\n  }\n  for (unsigned i = 0; i < CE.rows(); i++) {\n    viewer.data().add_edges(\n      CV.row(CE(i,0)),\n      CV.row(CE(i,1)),\n      RowVector3d(1,0,0)\n    );\n  }\n}\n\n// key_down callback\n// accepts R (reset), U (undo), W/A/S/D (cage vertex move)\nbool callback_key_down(Viewer &viewer, unsigned char key, int modifiers) {\n  if (key == 'R') {\n    CV = CV1;\n    V = V1;\n    plot_mesh_and_cage(viewer);\n    return true;\n  }\n  else if (key == 'U') {\n    CV = CV2;\n    V = V2;\n    plot_mesh_and_cage(viewer);\n    return true;\n  }\n  else if (key == 'W' || key == 'S' || key == 'A' || key == 'D') {\n    if (current_cage_vertex != -1) {\n      if (key == 'W') {\n        CV(current_cage_vertex, 1) += keyboard_stride;\n      } \n      else if (key == 'S') {\n        CV(current_cage_vertex, 1) -= keyboard_stride;\n      }\n      else if (key == 'A') {\n        CV(current_cage_vertex, 0) -= keyboard_stride;\n      }\n      else {\n        CV(current_cage_vertex, 0) += keyboard_stride;\n      }\n      CV2 = CV;\n      V2 = V;\n      solve_harmonic();\n      #ifdef DEBUG_3\n      cout << V << endl << endl;\n      #endif\n      plot_mesh_and_cage(viewer);\n    }\n    return true;\n  }\n  return false;\n}\n\n// find the nearest cage vertex based on the unprojected mouse location\n// the location should be close to at least one of the cage vertices\n// otherwise will return -1\nint find_nearest_cage(RowVector3d loc) {\n  int nearest = -1;\n  double min_distance = numeric_limits<double>::max();\n  for (unsigned i = 0; i < CV.rows(); i++) {\n    RowVector3d diff = loc - CV.row(i);\n    if (diff.norm() < min_distance) {\n      min_distance = diff.norm();\n      nearest = i;\n    }\n  }\n  RowVector3d cage_max = CV.colwise().maxCoeff();\n  RowVector3d cage_min = CV.colwise().minCoeff();\n  #ifdef DEBUG_1\n  cout << cage_max << endl;\n  cout << cage_min << endl;\n  #endif\n  double distance_threshold = (cage_max(0) - cage_min(0) + cage_max(1) - cage_min(1)) / 2 * 0.1;\n  keyboard_stride = distance_threshold / 2;\n  if (min_distance > distance_threshold) {\n    nearest = -1;\n  }\n  return nearest;\n}\n\n// mouse_down callback\n// unproject the mouse location and find the a cage vertex nearby\n// and then prepare for the drag\nbool callback_mouse_down(Viewer& viewer, int, int) {\n  int mx = viewer.current_mouse_x;\n  int my = viewer.core.viewport(3) - viewer.current_mouse_y;\n  RowVector3d origin_point;\n  origin_point.setZero();\n  RowVector3d projected;\n  igl::project(origin_point, viewer.core.view, viewer.core.proj, viewer.core.viewport, projected);\n  #ifdef DEBUG_3\n  cout << \"projected: \" << projected << endl;\n  #endif\n  double mz = projected[2];\n  RowVector3d target;\n  target.setZero();\n  igl::unproject(RowVector3d(mx,my,mz), viewer.core.view, viewer.core.proj, viewer.core.viewport, target);\n  int cid = find_nearest_cage(target);\n  #ifdef DEBUG_3\n  cout << \"cage selected: \" << cid << endl;\n  cout << \"mouse location: \" << mx << \", \" << my << \",\" << mz << endl;\n  cout << \"target location: \" << target << endl;\n  #endif\n  if (cid == -1) {\n    return false;\n  }\n  current_cage_vertex = cid;\n  mouse_down = true;\n  CV2 = CV;\n  V2 = V;\n  plot_mesh_and_cage(viewer);\n  return true;\n}\n\n// mouse_move callback\n// works only when mouse is down (when dragging)\n// unproject the mouse location and move the selected cage vertex accordingly\n// and then solve the system \nbool callback_mouse_move(Viewer& viewer, int mouse_x, int mouse_y) {\n  if (mouse_down) {\n    int mx = mouse_x;\n    int my = viewer.core.viewport(3) - mouse_y;\n    RowVector3d origin_point;\n    origin_point.setZero();\n    RowVector3d projected;\n    igl::project(origin_point, viewer.core.view, viewer.core.proj, viewer.core.viewport, projected);\n    #ifdef DEBUG_3\n    cout << \"projected: \" << projected << endl;\n    #endif\n    double mz = projected[2];\n    RowVector3d target;\n    target.setZero();\n    igl::unproject(RowVector3d(mx,my,mz), viewer.core.view, viewer.core.proj, viewer.core.viewport, target);\n    #ifdef DEBUG_3\n    cout << \"mouse location: \" << mx << \", \" << my << \",\" << mz << endl;\n    cout << \"target location: \" << target << endl;\n    #endif\n    CV.row(current_cage_vertex) = target;\n    solve_harmonic();\n    plot_mesh_and_cage(viewer);\n  }\n  return true;\n}\n\n// mouse_up callback\nbool callback_mouse_up(Viewer& viewer, int, int) {\n  mouse_down = false;\n  plot_mesh_and_cage(viewer);\n  return true;\n}\n\n// solver prepare\n// use Laplace equation to solve the system\n// stores the harmonic matrix in H\n// consider mesh and cage as a whole new mesh\n// and use cage vertices as boundary vertices\n// then utilize variable elimination to build the linear system\nvoid solve_prepare() {\n  MatrixXd VV(CV.rows()+V.rows(), 2);\n  for (unsigned i = 0; i < CV.rows(); i++) {\n    VV(i,0) = CV(i,0);\n    VV(i,1) = CV(i,1);\n  }\n  for (unsigned i = 0; i < V.rows(); i++) {\n    VV(CV.rows()+i,0) = V(i,0);\n    VV(CV.rows()+i,1) = V(i,1);\n  }\n  MatrixXd H0(0, 2);\n  igl::triangle::triangulate(VV,CE,H0,\"Q\",VV0,VF0);\n  VV0.conservativeResize(VV0.rows(),3);\n  VV0.col(2).setZero();\n  #ifdef DEBUG_1\n  cout << \"VV = \" << endl << VV << endl;\n  cout << \"VV0 = \" << endl << VV0 << endl;\n  #endif\n  SparseMatrix<double> L;\n  igl::cotmatrix(VV0,VF0,L);\n  VectorXi all, in, b;\n  igl::colon<int>(0,VV0.rows()-1,all);\n  igl::colon<int>(CV.rows(),VV0.rows()-1,in);\n  igl::colon<int>(0,CV.rows()-1,b);\n  SparseMatrix<double> A = L * (-1);\n  // SparseMatrix<double> Aff, Afc;\n  igl::slice(A,in,in,Aff);\n  igl::slice(A,in,b,Afc);\n  \n  SimplicialLLT<SparseMatrix<double>> solver;\n  solver.compute(Aff);\n  H = solver.solve(MatrixXd(Afc)*(-1));\n  \n  #ifdef DEBUG_2\n  cout << \"VV0: \" << VV0.rows() << \" * \" << VV0.cols() << endl;\n  cout << \"VF0: \" << VF0.rows() << \" * \" << VF0.cols() << endl;\n  cout << \"L: \" << L.rows() << \" * \" << L.cols() << endl;\n  cout << \"A: \" << A.rows() << \" * \" << A.cols() << endl;\n  cout << \"all: \" << all.rows() << \" * \" << all.cols() << endl;\n  cout << \"in: \" << in.rows() << \" * \" << in.cols() << endl;\n  cout << \"b: \" << b.rows() << \" * \" << b.cols() << endl;\n  cout << \"Aff: \" << Aff.rows() << \" * \" << Aff.cols() << endl;\n  cout << \"Afc: \" << Afc.rows() << \" * \" << Afc.cols() << endl;\n  cout << \"H: \" << H.rows() << \" * \" << H.cols() << endl;\n  #endif\n}\n\n// compute the new mesh based on H\nvoid solve_harmonic() {\n  /*\n  for (unsigned i = 0; i < V.cols(); i++) {\n    VectorXd bc = CV.col(i);\n    SimplicialLLT<SparseMatrix<double>> solver(Aff);\n    VectorXd XX = solver.solve(MatrixXd(Afc) * (-1) * bc);\n    V.col(i) = XX;\n  }\n  */\n  \n  MatrixXd NV = H * CV;\n  for (unsigned i = 0; i < NV.rows(); i++) {\n    V.row(i) = NV.row(i);\n  }\n  \n}\n\n// read cage information from .cage file\n// if failed, the main function will use automatic cage generation instead\nbool read_cage_from_file(string cage_filename) {\n  ifstream in(cage_filename);\n  if (!in.is_open()) {\n    cout << \"Error: cannot open the cage file! Automatic cage generation will be used.\" << endl;\n    return false;\n  }\n  CV.resize(8, 3);\n  int index = 0;\n  string line;\n  while (getline(in, line)) {\n    index++;\n    istringstream iss(line);\n    if (index > CV.rows()) {\n      CV.conservativeResize(CV.rows()*2, CV.cols());\n    }\n    for (unsigned i = 0; i < 3; i++) {\n      double xyz;\n      if (iss >> xyz) {\n        CV(index-1,i) = xyz; \n      } else {\n        cout << \"Error: cannot open the cage file! Automatic cage generation will be used.\" << endl;\n        return false;\n      }\n    }\n  }\n  CV.conservativeResize(index, CV.cols());\n  in.close();\n  return true;\n}\n\n// automatically generate cage based on mesh boundary\n// compute the mesh centroid and move the boundary vertices even further to build the cage\nvoid generate_cage() {\n  int vn = V.rows();\n  RowVector3d mesh_centriod;\n  mesh_centriod.setZero();\n  for (unsigned i = 0; i < vn; i++) {\n    mesh_centriod += V.row(i);\n  }\n  mesh_centriod /= vn;\n  MatrixXi VE;\n  igl::boundary_facets(F,VE);\n  #ifdef DEBUG_2\n  cout << \"VE: \" << endl << VE << endl << endl;\n  #endif\n  VectorXi CC, IA, IC;\n  igl::unique(VE,CC,IA,IC);\n  #ifdef DEBUG_2\n  cout << \"CC: \" << endl << CC << endl << endl;\n  cout << \"IA: \" << endl << IA << endl << endl;\n  cout << \"IC: \" << endl << IC << endl << endl;\n  #endif\n  MatrixXd VI;\n  igl::slice(V,CC,1,VI);\n  CV.resizeLike(VI);\n  for (unsigned i = 0; i < VI.rows(); i++) {\n    CV.row(i) = (VI.row(i) - mesh_centriod) * 1.5 + mesh_centriod;\n  }\n  unordered_map<int,int> dict;\n  for (unsigned i = 0; i < CC.rows(); i++) {\n    dict[CC(i)] = i;\n  }\n  CE.resizeLike(VE);\n  for (unsigned i = 0; i < VE.rows(); i++) {\n    CE(i,0) = dict[VE(i,0)]; \n    CE(i,1) = dict[VE(i,1)];\n  }\n}\n\n// main function\nint main(int argc, char *argv[])\n{\n  if (argc <= 1) {\n\n    V.resize(4,3);\n    V << 0,0,0,\n         1,0,0,\n         0,1,0,\n         1,1,0;\n    F.resize(2,3);\n    F << 0,1,2,\n         1,3,2;\n    CV.resize(4,3);\n    CV << -0.5,-0.5,0,\n          1.5,-0.5,0,\n          1.5,1.5,0,\n          -0.5,1.5,0;\n    CE.resize(4,2);\n    CE << 0,1,\n          1,2,\n          2,3,\n          3,0;\n\n  }\n  else if (argc == 2) {\n\n    string mesh_file_name = argv[1];\n    igl::readOFF(mesh_file_name,V,F);\n    generate_cage();\n\n  }\n  else if (argc >= 3) {\n\n    string mesh_file_name = argv[1];\n    string mesh_cage_name = argv[2];\n\n    igl::readOFF(mesh_file_name,V,F);\n    if (!read_cage_from_file(mesh_cage_name)) {\n      generate_cage();\n    } else {\n      CE.resize(CV.rows(),2);\n      for (unsigned i = 0; i < CV.rows(); i++) {\n        CE(i,0) = i;\n        CE(i,1) = (i+1)%CV.rows();\n      }\n    }\n\n  }\n  else {\n    cout << \"Usage: ./final_bin <mesh.off> <cage.cage>\" << endl;\n    cout << \"Automatic cage generation: \" << endl;\n    cout << \"Usage: ./final_bin <mesh.off>\" << endl;\n    cout << \"Default mesh and cage: \" << endl;\n    cout << \"Usage: ./final_bin\" << endl;\n    exit(1);\n  }\n\n  CV1 = CV2 = CV;\n  V1 = V2 = V;\n\n  // Plot the mesh\n  igl::opengl::glfw::Viewer viewer;\n\n  viewer.callback_key_down = &callback_key_down;\n  viewer.callback_mouse_down = &callback_mouse_down;\n  viewer.callback_mouse_move = &callback_mouse_move;\n  viewer.callback_mouse_up = &callback_mouse_up;\n\n  solve_prepare();\n\n  plot_mesh_and_cage(viewer);\n  viewer.core.align_camera_center(V,F);\n\n  viewer.launch();\n\n}\n", "meta": {"hexsha": "759b7c747b5f6890da87ea6a6453c2b12dcb7f7a", "size": 13313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "bambrow/2d-harmonic-coordinates", "max_stars_repo_head_hexsha": "0e3c7d01023efcfcfefc052e8bfa82c7fd3dc9a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:36:41.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "bambrow/2d-harmonic-coordinates", "max_issues_repo_head_hexsha": "0e3c7d01023efcfcfefc052e8bfa82c7fd3dc9a4", "max_issues_repo_licenses": ["MIT"], "max_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": "bambrow/2d-harmonic-coordinates", "max_forks_repo_head_hexsha": "0e3c7d01023efcfcfefc052e8bfa82c7fd3dc9a4", "max_forks_repo_licenses": ["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.8514644351, "max_line_length": 108, "alphanum_fraction": 0.6179674003, "num_tokens": 4066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800691997339971, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5625101898603125}}
{"text": "/**\n * @file gamma_distribution.hpp\n * @author Yannis Mentekidis\n *\n * Implementation of a Gamma distribution of multidimensional data that fits\n * gamma parameters (alpha, beta) to data.\n * The fitting is done independently for each dataset dimension (row), based on\n * the assumption each dimension is fully indepeendent.\n *\n * Based on \"Estimating a Gamma Distribution\" by Thomas P. Minka:\n * research.microsoft.com/~minka/papers/minka-gamma.pdf\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef _MLPACK_CORE_DISTRIBUTIONS_GAMMA_DISTRIBUTION_HPP\n#define _MLPACK_CORE_DISTRIBUTIONS_GAMMA_DISTRIBUTION_HPP\n\n#include <mlpack/prereqs.hpp>\n#include <mlpack/core/math/random.hpp>\n#include <boost/program_options.hpp>\n\nnamespace mlpack {\nnamespace distribution {\n\n/**\n * This class represents the Gamma distribution.  It supports training a Gamma\n * distribution on a given dataset and accessing the fitted alpha and beta\n * parameters.\n *\n * This class supports multidimensional Gamma distributions; however, it is\n * assumed that each dimension is independent; therefore, a multidimensional\n * Gamma distribution here may be seen as a set of independent\n * single-dimensional Gamma distributions---and the parameters are estimated\n * under this assumption.\n *\n * The estimation algorithm used can be found in the following paper:\n *\n * @code\n * @techreport{minka2002estimating,\n *   title={Estimating a {G}amma distribution},\n *   author={Minka, Thomas P.},\n *   institution={Microsoft Research},\n *   address={Cambridge, U.K.},\n *   year={2002}\n * }\n * @endcode\n */\nclass GammaDistribution\n{\n public:\n    /**\n     * Construct the Gamma distribution with the given number of dimensions\n     * (default 0); each parameter will be initialized to 0.\n     *\n     * @param dimensionality Number of dimensions.\n     */\n    GammaDistribution(const size_t dimensionality = 0);\n\n    /**\n     * Construct the Gamma distribution, training on the given parameters.\n     *\n     * @param data Data to train the distribution on.\n     * @param tol Convergence tolerance. This is *not* an absolute measure:\n     *    It will stop the approximation once the *change* in the value is\n     *    smaller than tol.\n     */\n    GammaDistribution(const arma::mat& data, const double tol = 1e-8);\n\n    /**\n     * Construct the Gamma distribution given two vectors alpha and beta.\n     *\n     * @param alpha The vector of alphas, one per dimension.\n     * @param beta The vector of betas, one per dimension.\n     */\n    GammaDistribution(const arma::vec& alpha, const arma::vec& beta);\n\n    /**\n     * Destructor.\n     */\n    ~GammaDistribution() {}\n\n    /**\n     * This function trains (fits distribution parameters) to new data or the\n     * dataset the object owns.\n     *\n     * @param rdata Reference data to fit parameters to.\n     * @param tol Convergence tolerance. This is *not* an absolute measure:\n     *    It will stop the approximation once the *change* in the value is\n     *    smaller than tol.\n     */\n    void Train(const arma::mat& rdata, const double tol = 1e-8);\n\n    /**\n     * Fits an alpha and beta parameter according to observation probabilities.\n     * This method is not yet implemented.\n     *\n     * @param observations The reference data, one observation per column\n     * @param probabilities The probability of each observation. One value per\n     *     column of the observations matrix.\n     * @param tol Convergence tolerance. This is *not* an absolute measure:\n     *    It will stop the approximation once the *change* in the value is\n     *    smaller than tol.\n     */\n    void Train(const arma::mat& observations,\n               const arma::vec& probabilities,\n               const double tol = 1e-8);\n\n    /**\n     * This function trains (fits distribution parameters) to a dataset with\n     * pre-computed statistics logMeanx, meanLogx, meanx for each dimension.\n     *\n     * @param logMeanxVec Is each dimension's logarithm of the mean\n     *     (log(mean(x))).\n     * @param meanLogxVec Is each dimension's mean of logarithms (mean(log(x))).\n     * @param meanxVec Is each dimension's mean (mean(x)).\n     * @param tol Convergence tolerance. This is *not* an absolute measure:\n     *    It will stop the approximation once the *change* in the value is\n     *    smaller than tol.\n     */\n    void Train(const arma::vec& logMeanxVec,\n               const arma::vec& meanLogxVec,\n               const arma::vec& meanxVec,\n               const double tol = 1e-8);\n\n\n    /**\n     * This function returns the probability of a group of observations.\n     *\n     * The probability of the value x is\n     *\n     * \\frac{x^(\\alpha - 1)}{\\Gamma(\\alpha) * \\beta^\\alpha} * e ^\n     * {-\\frac{x}{\\beta}}\n     *\n     * for one dimension. This implementation assumes each dimension is\n     * independent, so the product rule is used.\n     *\n     * @param observations Matrix of observations, one per column.\n     * @param probabilities column vector of probabilities, one per observation.\n     */\n    void Probability(const arma::mat& observations,\n                     arma::vec& Probabilities) const;\n\n    /*\n     * This is a shortcut to the Probability(arma::mat&, arma::vec&) function\n     * for when we want to evaluate only the probability of one dimension of the\n     * gamma.\n     *\n     * @param x The 1-dimensional observation.\n     * @param dim The dimension for which to calculate the probability\n     */\n    double Probability(double x, size_t dim) const;\n\n    /**\n     * This function returns the logarithm of the probability of a group of\n     * observations.\n     *\n     * The logarithm of the probability of a value x is\n     *\n     * log(\\frac{x^(\\alpha - 1)}{\\Gamma(\\alpha) * \\beta^\\alpha} * e ^\n     * {-\\frac{x}{\\beta}})\n     *\n     * for one dimension. This implementation assumes each dimension is\n     * independent, so the product rule is used.\n     *\n     * @param observations Matrix of observations, one per column.\n     * @param logProbabilities column vector of log probabilities, one per\n     *     observation.\n     */\n    void LogProbability(const arma::mat& observations,\n                        arma::vec& LogProbabilities) const;\n\n    /**\n     * This function returns an observation of this distribution\n     */\n    arma::vec Random() const;\n\n    // Access to Gamma distribution parameters.\n\n    //! Get the alpha parameter of the given dimension.\n    double Alpha(const size_t dim) const { return alpha[dim]; }\n    //! Modify the alpha parameter of the given dimension.\n    double& Alpha(const size_t dim) { return alpha[dim]; }\n\n    //! Get the beta parameter of the given dimension.\n    double Beta(const size_t dim) const { return beta[dim]; }\n    //! Modify the beta parameter of the given dimension.\n    double& Beta(const size_t dim) { return beta[dim]; }\n\n    //! Get the dimensionality of the distribution.\n    size_t Dimensionality() const { return alpha.n_elem; }\n\n private:\n    //! Array of fitted alphas.\n    arma::vec alpha;\n    //! Array of fitted betas.\n    arma::vec beta;\n\n    /**\n     * This is a small function that returns true if the update of alpha is\n     * smaller than the tolerance ratio.\n     *\n     * @param aOld old value of parameter we want to estimate (alpha in our\n     *      case).\n     * @param aNew new value of parameter (the value after 1 iteration from\n     *      aOld).\n     * @param tol Convergence tolerance. Relative measure (see documentation of\n     *      GammaDistribution::Train).\n     */\n    inline bool Converged(const double aOld,\n                          const double aNew,\n                          const double tol);\n};\n\n} // namespace distribution\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "b4d7c6e639d0c78fd2278c455858b603fab835ad", "size": 7929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/core/dists/gamma_distribution.hpp", "max_stars_repo_name": "whoopityDoop/mlpack", "max_stars_repo_head_hexsha": "feadc715e27cbc337819504168d268e7aa01fc07", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 675.0, "max_stars_repo_stars_event_min_datetime": "2019-02-07T01:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:45:10.000Z", "max_issues_repo_path": "src/mlpack/core/dists/gamma_distribution.hpp", "max_issues_repo_name": "whoopityDoop/mlpack", "max_issues_repo_head_hexsha": "feadc715e27cbc337819504168d268e7aa01fc07", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 843.0, "max_issues_repo_issues_event_min_datetime": "2019-01-25T01:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:15:53.000Z", "max_forks_repo_path": "src/mlpack/core/dists/gamma_distribution.hpp", "max_forks_repo_name": "whoopityDoop/mlpack", "max_forks_repo_head_hexsha": "feadc715e27cbc337819504168d268e7aa01fc07", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2019-02-20T06:18:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T09:36:09.000Z", "avg_line_length": 35.8778280543, "max_line_length": 80, "alphanum_fraction": 0.6632614453, "num_tokens": 1815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.5624053921985358}}
{"text": "/*\n * ex10.cpp\n *\n * \t\\brief     Tenth exercise\n *  \\details   This class reads graph-data and computes the so-called Steiner-tree for the first 100 terminals by multithreading\n *  \\author    Julia Baumbach\n *  \\date      15.07.2017\n */\n\n#include \"GraphReader.h\"\n#include <iostream>\n#include <sstream>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include \"SteinerSolver.h\"\n#include \"TreeChecker.h\"\n\nusing namespace std;\n\n/*\n * \\fn bool hasDivisor(vector<int>, int)\n * \\brief computes if an int has a divisor in a list of ints\n * \\return true, if it has a divisor, otherwise false\n */\nbool hasDivisor(const vector<int>* result, int j) {\n\tfor (int i = 0; i < result->size(); i++) {\n\t\tif ((j % result->at(i)) == 0 || (result->at(i))/2 >= j) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/*\n * \\fn vector<int> computePrimes(int upperBound)\n * \\brief computes all primes in range from 2 to upperBound\n * \\return vector of all primes\n */\nvoid computePrimes(vector<int>* target, int upperBound){\n\ttarget->push_back(2);\n\tfor(int i = 3; i < upperBound; i++){\n\t\tif(!hasDivisor(target, i)){\n\t\t\ttarget->push_back(i);\n\t\t}\n\t}\n}\n\n/*\n * \\fn int main(int argc, char* argv[])\n * \\brief main function. reads in graph data and prints the solution for the steiner tree problem. Run program with ./ex10 NUMBERTHREADS FILENAME\n * \\return EXIT_SUCCESS if program exited correctly, otherwise EXIT_FAILURE\n */\nint main(int argc, char* argv[]){\n\t//Initialize timer for cpu time measurement\n\tboost::timer::cpu_timer cpu_timer;\n\n\tint numberOfThreads;\n\tstringstream ss(argv[1]);\n\tss >> numberOfThreads;\n\n\tcout << \"Read graph... \" << endl;\n\tGraphReader* reader = new GraphReader();\n\tif(!reader->readDataFromFile(argv[2])){\n\t\tcerr << \"Error while reading data. Exit program\" << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t//Get data from graphReader\n\tunsigned int numberVertices = reader->getNumberOfVertices();\n\tSortedEdges edges = reader->getSortedEdges();\n\tWeightMap weights = reader->getWeightMap();\n\n\tdelete reader;\n\t//Initialize timer for wallclock time measurement\n\tboost::timer::cpu_timer wall_timer;\n\n\tcout << \"Compute primes... \" << endl;\n\tvector<int>* terminals = new vector<int>();\n\tcomputePrimes(terminals, numberVertices);\n\tvector<int>* firstHundredTerminals;\n\tif(terminals->size() < 100){\n\t\tfirstHundredTerminals = terminals;\n\t}else {\n\t\tfirstHundredTerminals = new vector<int>(terminals->begin(), terminals->begin() + 100);\n\t}\n\n\t//Solve the Steiner Problem for the given graph and given start nodes\n\tEdges resultEdges[100];\n\tint resultObjValues[100];\n\n\tcout << \"Compute Steiner...\" << endl;\n\t#pragma omp parallel for num_threads(numberOfThreads)\n\tfor(int i = 0; i < firstHundredTerminals->size(); i++){\n\t\tSteinerSolver* mySteiner = new SteinerSolver(*terminals);\n\t\tresultEdges[i] = mySteiner->solveSteiner(edges, numberVertices, firstHundredTerminals->at(i));\n\t\tresultObjValues[i] = mySteiner->getObjectiveValue();\n\t\tdelete mySteiner;\n\t}\n\t//Stop wall time\n\tboost::timer::cpu_times wall_time = wall_timer.elapsed();\n\n\tcout << \"Search for minimum...\" << endl;\n\t//Search for the minimal steiner tree\n\tint indexMinNode;\n\tint minObjValue = INT_MAX;\n\tfor(int i = 0; i < firstHundredTerminals->size(); i++){\n\t\tif(resultObjValues[i] < minObjValue){\n\t\t\tindexMinNode = i;\n\t\t\tminObjValue = resultObjValues[i];\n\t\t}\n\t}\n\n\tcout << \"Check tree...\" << endl;\n\t//Check if the minimal steiner tree is a tree and contains all terminals\n\tTreeChecker myChecker(resultEdges[indexMinNode], numberVertices);\n\tif(!myChecker.allNodesContained(firstHundredTerminals)){\n\t\tcout << \"CONTAINS NOT ALL TERMINALS\" << endl;\n\t}\n\tif(!myChecker.hasNoCircles()){\n\t\tcout << \"CONTAINS CIRLCES\" << endl;\n\t}\n\tif(!myChecker.isConnected()){\n\t\tcout << \"NOT CONNECTED\" << endl;\n\t}\n\n\t//print results\n\tcout << \"TLEN: \" << resultObjValues[indexMinNode] << endl;\n\tEdges result = resultEdges[indexMinNode];\n\tcout << \"TREE: \";\n\tfor(int i = 0; i < result.size(); i++){\n\t\tif(i == result.size() -1){\n\t\t\tcout << \"(\" << result.at(i).first << \",\" << result.at(i).second << \")\" << endl;\n\t\t}else {\n\t\t\tcout << \"(\" << result.at(i).first << \",\" << result.at(i).second << \") \";\n\t\t}\n\t}\n\n\tdelete firstHundredTerminals;\n\t//Print measured time\n\tboost::timer::cpu_times cpu_time = cpu_timer.elapsed();\n\n\tcout << \"TIME: \" << (cpu_time.system + cpu_time.user) * 1e-9 << \" seconds\" << endl;\n\tcout << \"WALL: \" << wall_time.wall * 1e-9 <<  \" seconds\" << endl;\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "f240e153870cffbeb9eb7ece2c39132d97f29e1b", "size": 4406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Julia/ex10/src/ex10.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Julia/ex10/src/ex10.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Julia/ex10/src/ex10.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 29.7702702703, "max_line_length": 145, "alphanum_fraction": 0.682932365, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5623811095544488}}
{"text": "#include <random>\n#include <boost/range/irange.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/lambda.hpp>\n#include \"kde.hpp\"\n\nusing std::vector;\nusing boost::irange;\nusing boost::lambda::_1;\nusing boost::lambda::_2;\nusing std::mt19937;\nusing std::normal_distribution;\n\n\ndouble sample_from_normal(\n    double mu = 0.0, /**< The mean of the distribution.*/\n    double sd = 1.0  /**< The standard deviation of the distribution.*/\n) {\n  mt19937 gen = RNG::rng()->get_RNG();\n  normal_distribution<> d{mu, sd};\n  return d(gen);\n}\n\nKDE::KDE(std::vector<double> v) : dataset(v) {\n    using boost::adaptors::transformed;\n    using boost::lambda::_1;\n    using utils::mean;\n\n    // Compute the bandwidth using Silverman's rule\n    mu = mean(v);\n    auto X = v | transformed(_1 - mu);\n\n    // Compute standard deviation of the sample.\n    size_t N = v.size();\n    double stdev = sqrt(inner_product(X, X, 0.0) / (N - 1));\n    bw = pow(4 * pow(stdev, 5) / (3 * N), 1 / 5);\n  }\n\nvector<double> KDE::resample(int n_samples) {\n  vector<double> samples;\n  for (int i : irange(0, n_samples)) {\n    double element = select_random_element(dataset);\n    samples.push_back(sample_from_normal(element, bw));\n  }\n  return samples;\n}\n\ndouble KDE::pdf(double x) {\n  using utils::sqr;\n  double p = 0.0;\n  size_t N = dataset.size();\n  for (double elem : dataset) {\n    double x1 = exp(-sqr(x - elem) / (2 * sqr(bw)));\n    x1 /= N * bw * sqrt(2 * M_PI);\n    p += x1;\n  }\n  return p;\n}\n\nvector<double> KDE::pdf(vector<double> v) {\n  vector<double> values;\n  for (double elem : v) {\n    values.push_back(pdf(elem));\n  }\n  return values;\n}\n\ndouble KDE::logpdf(double x) { return log(pdf(x)); }\n\n", "meta": {"hexsha": "3132f4d6fa59b644fce45ec8060cfae17e815fba", "size": 1839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/kde.cpp", "max_stars_repo_name": "mwdchang/delphi", "max_stars_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "max_stars_repo_licenses": ["Apache-2.0"], "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/kde.cpp", "max_issues_repo_name": "mwdchang/delphi", "max_issues_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "max_issues_repo_licenses": ["Apache-2.0"], "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/kde.cpp", "max_forks_repo_name": "mwdchang/delphi", "max_forks_repo_head_hexsha": "c6177f2d614118883eaaa7f5300f3e46f10ddc7e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-18T19:13:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-18T19:13:13.000Z", "avg_line_length": 24.8513513514, "max_line_length": 71, "alphanum_fraction": 0.6492659054, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.5623810878333053}}
{"text": "/*\n *  Explicit to implicit reconstruction\n *  Date : 20 Feb 2020\n *  Author : Sachin Krishnan T V (sachu92@gmail.com)\n */\n\n#include <iostream>\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n#include \"reconstruct.hpp\"\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char *argv[])\n{\n  // Input: point cloud filename\n  // Input: mesh size, box boundaries\n\n  // Output: the implicit surface representation in a VTP file. (mesh points with SDFs)\n\n  if(argc < 9)\n  {\n    cout<<\"Usage: <pointcloud_file> <mesh_size> <low_x> <high_x> <low_y> <high_y> <low_z> <high_z>\";\n    return 0;\n  }\n\n  cout<<endl;\n  cout<<\"Reading the input file...\";\n  // Read input file\n  readPointCloud(argv[1]);\n\n  cout<<endl<<\"Reading parameters...\";\n  // Set parameters for the output mesh\n  mesh_size = atoi(argv[2]);\n  xlo = atof(argv[3]);\n  xhi = atof(argv[4]);\n  ylo = atof(argv[5]);\n  yhi = atof(argv[6]);\n  zlo = atof(argv[7]);\n  zhi = atof(argv[8]);\n  \n  xbinsize = (xhi - xlo) / mesh_size;\n  ybinsize = (yhi - ylo) / mesh_size;\n  zbinsize = (zhi - zlo) / mesh_size;\n\n  cout<<endl<<\"Evaluating the SDF...\";\n  // Evaluate the signed distance functions\n  evaluateSDF();\n\n  cout<<endl<<\"Reconstructing mesh...\";\n  reconstructMesh();\n  cout<<endl<<\"Writing mesh structure to file...\";\n  outputMesh();\n  cout<<endl<<\"Done.\"<<endl;\n\n  return 0;\n}\n\nvoid readPointCloud(char *filename)\n{\n  int i;\n  int nump = 0;\n  bool done_flag = false;\n  string line;\n  string temp;\n  ifstream infile;\n  stringstream iss;\n\n  infile.open(filename, ios::in);\n\n  /* Reading the header */\n  while(!infile.eof() && !done_flag)\n  {\n    infile>>line;\n    if(strcmp(line.c_str(),\"<Piece\")==0)\n    {\n      infile>>line;\n      iss.str(line);\n      getline(iss,temp,'\\\"');\n      getline(iss,temp,'\\\"');\n      nump = atoi(temp.c_str());\n      pc_coord.resize(nump, std::vector<double>(3, 0.0));\n      pc_norm.resize(nump, std::vector<double>(3, 0.0));\n    }\n    else if(strcmp(line.c_str(),\"<Points>\")==0)\n    {\n      double rx, ry, rz;\n      for(i = 0;i < 5;i++)\n        infile>>line;\n      for(i = 0;i < nump;i++)\n      {\n        infile>>rx>>ry>>rz;\n        pc_coord[i][0] = rx;\n        pc_coord[i][1] = ry;\n        pc_coord[i][2] = rz;\n      }\n    }\n    else if(strcmp(line.c_str(), \"Name=\\\"Normals\\\"\")==0)\n    {\n      double nx, ny, nz;\n      // Ignore next string\n      infile>>line>>line;\n      for(i = 0;i < nump;i++)\n      {\n        infile>>nx>>ny>>nz;\n        pc_norm[i][0] = nx;\n        pc_norm[i][1] = ny;\n        pc_norm[i][2] = nz;\n      }\n      done_flag = true;\n    }\n  }\n  infile.close();\n  return;\n}\n\ndouble distance(double x1, double y1, double z1, double x2, double y2, double z2)\n{\n  double d;\n  d = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));\n  return d;\n}\n\ndouble triharmonic_kernel(double x)\n{\n  return x*x*x;\n}\n\n// Calculate the weights \nvoid evaluateSDF()\n{\n  int i, j;\n  int nump = pc_coord.size();\n  double x1, y1, z1, x2, y2, z2;\n\n  Matrix<double, Dynamic, Dynamic> K;\n  Matrix<double, Dynamic, 1> d;\n\n  K.resize(2*nump, 2*nump);\n  d.resize(2*nump, NoChange);\n\n  for(i = 0;i < 2*nump;i++)\n  {\n    if(i < nump)\n    {\n      x1 = pc_coord[i][0];\n      y1 = pc_coord[i][1];\n      z1 = pc_coord[i][2];\n      d(i) = 0.0;\n    }\n    else\n    {\n      x1 = pc_coord[i-nump][0] + EPS*pc_norm[i-nump][0]; \n      y1 = pc_coord[i-nump][1] + EPS*pc_norm[i-nump][1]; \n      z1 = pc_coord[i-nump][2] + EPS*pc_norm[i-nump][2]; \n      d(i) = EPS;\n    }\n    for(j = 0;j < 2*nump;j++)\n    {\n      if(j < nump)\n      {\n        x2 = pc_coord[j][0];\n        y2 = pc_coord[j][1];\n        z2 = pc_coord[j][2];\n      }\n      else\n      {\n        x2 = pc_coord[j-nump][0] + EPS*pc_norm[j-nump][0]; \n        y2 = pc_coord[j-nump][1] + EPS*pc_norm[j-nump][1]; \n        z2 = pc_coord[j-nump][2] + EPS*pc_norm[j-nump][2]; \n      }\n      K(i, j) = triharmonic_kernel(distance(x1, y1, z1, x2, y2, z2));\n    }\n  }          \n\n  Matrix<double, Dynamic, 1> w = K.inverse()*d;\n  w.resize(2*nump, NoChange);\n\n  rbf_weight.resize(2*nump);\n  for(i = 0;i < 2*nump;i++)\n  {\n    rbf_weight[i] = w(i);\n  }\n  return; \n}\n\n// Reconstruct the mesh based on the calculated weights\nvoid reconstructMesh()\n{\n  int i, j, k, l;\n  int nump = pc_coord.size();\n  long index;\n  double mx, my, mz, mphi;\n  \n  mesh_ls.resize(mesh_size*mesh_size*mesh_size, 0);\n\n  for(i = 0;i < mesh_size;i++)\n  {  \n    mx = xlo + xbinsize*i;\n    for(j = 0;j < mesh_size;j++)\n    {\n      my = ylo + ybinsize*j;\n      for(k = 0;k < mesh_size;k++)\n      {\n        mz = zlo + zbinsize*k;\n        \n        mphi = 0.0;\n        for(l = 0;l < nump;l++)\n        {\n          mphi += rbf_weight[l]*triharmonic_kernel(distance(mx, my, mz, pc_coord[l][0], \n                                                            pc_coord[l][1], pc_coord[l][2]));\n        }\n        for(l = 0;l < nump;l++)\n        {\n          mphi += rbf_weight[l+nump]*triharmonic_kernel(distance(mx, my, mz,\n                                                                 pc_coord[l][0] + EPS*pc_norm[l][0],\n                                                                 pc_coord[l][1] + EPS*pc_norm[l][1],\n                                                                 pc_coord[l][2] + EPS*pc_norm[l][2]));\n        }\n        index = k*mesh_size*mesh_size + j*mesh_size + i;\n        mesh_ls[index] = mphi;\n      }\n    }\n  } \n  return;\n}\n\n// Write output file in VTK format\nvoid outputMesh()\n{\n  int i;\n  ofstream outfile;\n\n  outfile.open(\"output.vtk\", ios::out);\n  outfile<<\"# vtk DataFile Version 2.0\"<<endl;\n  outfile<<\"Level set data\"<<endl;\n  outfile<<\"ASCII\"<<endl;\n  outfile<<\"DATASET RECTILINEAR_GRID\"<<endl;\n  outfile<<\"DIMENSIONS \"<<mesh_size<<\" \"<<mesh_size<<\" \"<<mesh_size<<endl;\n  outfile<<\"X_COORDINATES \"<<mesh_size<<\" float\"<<endl;\n  for(i = 0;i < mesh_size;i++)\n  {\n    outfile<<i*xbinsize + xlo<<endl;\n  }\n  outfile<<\"Y_COORDINATES \"<<mesh_size<<\" float\"<<endl;\n  for(i = 0;i < mesh_size;i++)\n  {\n    outfile<<i*ybinsize + ylo<<endl;\n  }\n  outfile<<\"Z_COORDINATES \"<<mesh_size<<\" float\"<<endl;\n  for(i = 0;i < mesh_size;i++)\n  {\n    outfile<<i*zbinsize + zlo<<endl;\n  }\n  outfile<<\"POINT_DATA \"<<mesh_ls.size()<<endl;\n  outfile<<\"SCALARS ls_phi float 1\"<<endl;\n  outfile<<\"LOOKUP_TABLE default\"<<endl;\n  for(i = 0;i < mesh_ls.size();i++)\n  {\n    outfile<<mesh_ls[i]<<endl;\n  }\n  outfile.close();\n}\n\n\n", "meta": {"hexsha": "b1f8876fb7e46ed48b91f4e8db9104dc9cf3829c", "size": 6371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reconstruct.cpp", "max_stars_repo_name": "sachu92/explicit-to-implicit-3d", "max_stars_repo_head_hexsha": "086652995375eeed51e0241ce8351bab31b63dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T05:14:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-04T08:58:13.000Z", "max_issues_repo_path": "src/reconstruct.cpp", "max_issues_repo_name": "sachu92/explicit-to-implicit-3d", "max_issues_repo_head_hexsha": "086652995375eeed51e0241ce8351bab31b63dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T02:52:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-29T09:14:57.000Z", "max_forks_repo_path": "src/reconstruct.cpp", "max_forks_repo_name": "sachu92/explicit-to-implicit-3d", "max_forks_repo_head_hexsha": "086652995375eeed51e0241ce8351bab31b63dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T11:05:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-26T11:05:07.000Z", "avg_line_length": 23.5962962963, "max_line_length": 102, "alphanum_fraction": 0.5363365249, "num_tokens": 1995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5623743161100183}}
{"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#ifndef __IS_STRAIGHT_LINE_DRAWING_HPP__\n#define __IS_STRAIGHT_LINE_DRAWING_HPP__\n\n#include <boost/config.hpp>\n#include <boost/utility.hpp> //for next and prior\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_comparison.hpp>\n#include <boost/property_map.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/planar_detail/bucket_sort.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <set>\n\n\n\nnamespace boost\n{\n\n  // Return true exactly when the line segments s1 = ((x1,y1), (x2,y2)) and\n  // s2 = ((a1,b1), (a2,b2)) intersect in a point other than the endpoints of\n  // the line segments. The one exception to this rule is when s1 = s2, in\n  // which case false is returned - this is to accomodate multiple edges\n  // between the same pair of vertices, which shouldn't invalidate the straight\n  // line embedding. A tolerance variable epsilon can also be used, which\n  // defines how far away from the endpoints of s1 and s2 we want to consider\n  // an intersection.\n\n  bool intersects(double x1, double y1,\n                  double x2, double y2,\n                  double a1, double b1,\n                  double a2, double b2,\n                  double epsilon = 0.000001\n                  )\n  {\n\n    if (x1 - x2 == 0)\n      {\n        std::swap(x1,a1);\n        std::swap(y1,b1);\n        std::swap(x2,a2);\n        std::swap(y2,b2);\n      }\n\n    if (x1 - x2 == 0)\n      {\n        BOOST_USING_STD_MAX();\n        BOOST_USING_STD_MIN();\n\n        //two vertical line segments\n        double min_y = min BOOST_PREVENT_MACRO_SUBSTITUTION(y1,y2);\n        double max_y = max BOOST_PREVENT_MACRO_SUBSTITUTION(y1,y2);\n        double min_b = min BOOST_PREVENT_MACRO_SUBSTITUTION(b1,b2);\n        double max_b = max BOOST_PREVENT_MACRO_SUBSTITUTION(b1,b2);\n        if ((max_y > max_b && max_b > min_y) ||\n            (max_b > max_y && max_y > min_b)\n            )\n          return true;\n        else\n          return false;\n      }\n\n    double x_diff = x1 - x2;\n    double y_diff = y1 - y2;\n    double a_diff = a2 - a1;\n    double b_diff = b2 - b1;\n\n    double beta_denominator = b_diff - (y_diff/((double)x_diff)) * a_diff;\n\n    if (beta_denominator == 0)\n      {\n        //parallel lines\n        return false;\n      }\n\n    double beta = (b2 - y2 - (y_diff/((double)x_diff)) * (a2 - x2)) / \n      beta_denominator;\n    double alpha = (a2 - x2 - beta*(a_diff))/x_diff;\n\n    double upper_bound = 1 - epsilon;\n    double lower_bound = 0 + epsilon;\n\n    return (beta < upper_bound && beta > lower_bound && \n            alpha < upper_bound && alpha > lower_bound);\n\n  }\n\n\n  template <typename Graph, \n            typename GridPositionMap, \n            typename VertexIndexMap\n            >\n  bool is_straight_line_drawing(const Graph& g, \n                                GridPositionMap drawing, \n                                VertexIndexMap vm\n                                )\n  {\n\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator_t;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n    typedef typename graph_traits<Graph>::edge_iterator edge_iterator_t;\n    typedef typename graph_traits<Graph>::edges_size_type e_size_t;\n    typedef typename graph_traits<Graph>::vertices_size_type v_size_t;\n\n    typedef std::size_t x_coord_t;\n    typedef std::size_t y_coord_t;\n    typedef boost::tuple<edge_t, x_coord_t, y_coord_t> edge_event_t;\n    typedef typename std::vector< edge_event_t > edge_event_queue_t;\n\n    typedef tuple<y_coord_t, y_coord_t, x_coord_t, x_coord_t> active_map_key_t;\n    typedef edge_t active_map_value_t;\n    typedef std::map< active_map_key_t, active_map_value_t > active_map_t;\n    typedef typename active_map_t::iterator active_map_iterator_t;\n\n\n    edge_event_queue_t edge_event_queue;\n    active_map_t active_edges;\n\n    edge_iterator_t ei, ei_end;\n    for(tie(ei,ei_end) = edges(g); ei != ei_end; ++ei)\n      {\n        edge_t e(*ei);\n        vertex_t s(source(e,g));\n        vertex_t t(target(e,g));\n        edge_event_queue.push_back\n          (make_tuple(e, \n                      static_cast<std::size_t>(drawing[s].x),\n                      static_cast<std::size_t>(drawing[s].y)\n                      )\n           );\n        edge_event_queue.push_back\n          (make_tuple(e,\n                      static_cast<std::size_t>(drawing[t].x),\n                      static_cast<std::size_t>(drawing[t].y)\n                      )\n           );\n      }\n\n    // Order by edge_event_queue by first, then second coordinate \n    // (bucket_sort is a stable sort.)\n    bucket_sort(edge_event_queue.begin(), edge_event_queue.end(),\n                property_map_tuple_adaptor<edge_event_t, 2>()\n                );\n    \n    bucket_sort(edge_event_queue.begin(), edge_event_queue.end(),\n                property_map_tuple_adaptor<edge_event_t, 1>()\n                );\n\n    typedef typename edge_event_queue_t::iterator event_queue_iterator_t;\n    event_queue_iterator_t itr_end = edge_event_queue.end();\n    for(event_queue_iterator_t itr = edge_event_queue.begin(); \n        itr != itr_end; ++itr\n        )\n      {\n        edge_t e(get<0>(*itr));\n        vertex_t source_v(source(e,g));\n        vertex_t target_v(target(e,g));\n        if (drawing[source_v].x > drawing[target_v].x)\n          std::swap(source_v, target_v);\n\n        active_map_key_t key(get(drawing, source_v).y,\n                             get(drawing, target_v).y,\n                             get(drawing, source_v).x,\n                             get(drawing, target_v).x\n                             );\n\n        active_map_iterator_t a_itr = active_edges.find(key);\n        if (a_itr == active_edges.end())\n          {\n            active_edges[key] = e;\n          }\n        else\n          {\n            active_map_iterator_t before, after;\n            if (a_itr == active_edges.begin())\n              before = active_edges.end();\n            else\n              before = prior(a_itr);\n            after = next(a_itr);\n\n            if (after != active_edges.end() || before != active_edges.end())\n              {\n                \n                edge_t f = after != active_edges.end() ? \n                  after->second : before->second;\n\n                vertex_t e_source(source(e,g));\n                vertex_t e_target(target(e,g));\n                vertex_t f_source(source(f,g));\n                vertex_t f_target(target(f,g));\n\n                if (intersects(drawing[e_source].x, \n                               drawing[e_source].y,\n                               drawing[e_target].x,\n                               drawing[e_target].y,\n                               drawing[f_source].x, \n                               drawing[f_source].y,\n                               drawing[f_target].x,\n                               drawing[f_target].y\n                               )\n                    )\n                  return false;\n              }\n\n            active_edges.erase(a_itr);\n\n          }\n      }\n\n    return true;\n    \n  }\n\n\n  template <typename Graph, typename GridPositionMap>\n  bool is_straight_line_drawing(const Graph& g, GridPositionMap drawing)\n  {\n    return is_straight_line_drawing(g, drawing, get(vertex_index,g));\n  }\n\n}\n\n#endif // __IS_STRAIGHT_LINE_DRAWING_HPP__\n", "meta": {"hexsha": "f533bce2dfd941e36d20c1bc3d36deb11c422396", "size": 7644, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/graph/is_straight_line_drawing.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/is_straight_line_drawing.hpp", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/is_straight_line_drawing.hpp", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 32.8068669528, "max_line_length": 79, "alphanum_fraction": 0.5675039246, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.5623743135816509}}
{"text": "/*\n*   Greedy Search\n*   by R. Falque\n*   29/11/2018\n*/\n\n#ifndef DOWNSAMPLING\n#define DOWNSAMPLING\n\n#include <Eigen/Core>\n#include <vector>\n#include <limits> \n\n#include <cfloat>\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n\n#include \"getMinMax.hpp\"\n#include \"farther_sampling.hpp\"\n#include \"nanoflannWrapper.hpp\"\n\nusing namespace std;\n\nclass three_d_point{\npublic:\n\tdouble x;\n\tdouble y;\n\tdouble z;\n};\n\nclass point_and_occurences{\npublic:\n\tdouble x;\n\tdouble y;\n\tdouble z;\n\tint occurence;\n};\n\ninline void voxel_grid_downsampling(Eigen::MatrixXd & in_cloud, double leaf_size, Eigen::MatrixXd & out_cloud)\n{\n\tEigen::Vector3d min_point, max_point;\n\tgetMinMax(in_cloud, min_point, max_point);\n\n\tdouble inv_leaf_size;\n\tinv_leaf_size = 1.0/leaf_size;\n\n\tEigen::Vector3i min_box, max_box;\n\tmin_box << floor(min_point(0) * inv_leaf_size ), floor(min_point(1) * inv_leaf_size ), floor(min_point(2) * inv_leaf_size); \n\tmax_box << floor(max_point(0) * inv_leaf_size ), floor(max_point(1) * inv_leaf_size ), floor(max_point(2) * inv_leaf_size); \n\n    Eigen::Vector3i divb, divb_mul;\n    divb << max_box(0) - min_box(0) + 1, max_box(1) - min_box(1) + 1, max_box(2) - min_box(2) + 1;\n    divb_mul << 1, divb(0), divb(0) * divb(1);\n\n\tstd::vector < std::vector < std::vector < point_and_occurences> > > voxels;\n\n\tvoxels.resize(divb(0));\n\tfor (int x_index = 0; x_index < voxels.size(); ++x_index)\n\t{\n\t\tvoxels[x_index].resize(divb(1));\n\t\tfor (int y_index = 0; y_index < voxels[0].size(); ++y_index)\n\t\t{\n\t\t\tvoxels[x_index][y_index].resize(divb(2));\n\t\t}\n\t}\n\n\t// plus assign zeros to voxel_count\n\tfor (int i = 0; i < in_cloud.rows(); ++i)\n\t{\n        int x_index = static_cast<int> ( floor(in_cloud(i, 0) * inv_leaf_size) - min_box(0) );\n        int y_index = static_cast<int> ( floor(in_cloud(i, 1) * inv_leaf_size) - min_box(1) );\n        int z_index = static_cast<int> ( floor(in_cloud(i, 2) * inv_leaf_size) - min_box(2) );\n\n        voxels[x_index][y_index][z_index].x += in_cloud(i,0);\n        voxels[x_index][y_index][z_index].y += in_cloud(i,1);\n        voxels[x_index][y_index][z_index].z += in_cloud(i,2);\n        voxels[x_index][y_index][z_index].occurence ++;\n\t}\n\n\tstd::vector< three_d_point> final_cloud;\n\tthree_d_point temp;\n\tfor (int x_index = 0; x_index < voxels.size(); ++x_index)\n\t{\n\t\tfor (int y_index = 0; y_index < voxels[0].size(); ++y_index)\n\t\t{\n\t\t\tfor (int z_index = 0; z_index < voxels[0][0].size(); ++z_index)\n\t\t\t{\n\t\t\t\tif (voxels[x_index][y_index][z_index].occurence!= 0)\n\t\t\t\t{\n\t\t\t\t\ttemp.x = voxels[x_index][y_index][z_index].x / voxels[x_index][y_index][z_index].occurence;\n\t\t\t\t\ttemp.y = voxels[x_index][y_index][z_index].y / voxels[x_index][y_index][z_index].occurence;\n\t\t\t\t\ttemp.z = voxels[x_index][y_index][z_index].z / voxels[x_index][y_index][z_index].occurence;\n\t\t\t\t\tfinal_cloud.push_back(temp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tout_cloud.resize(final_cloud.size(), 3);\n\tfor (int i = 0; i < final_cloud.size(); ++i)\n\t{\n\t\tout_cloud.row(i) << final_cloud[i].x, final_cloud[i].y, final_cloud[i].z;\n\t}\n\n};\n\n\ninline void downsampling(Eigen::MatrixXd & in_cloud, \n                         Eigen::MatrixXd & out_cloud, \n\t\t\t\t\t\t std::vector<int> & in_cloud_samples, \n\t\t\t\t\t\t double grid_resolution,\n\t\t\t\t\t\t double leaf_size, \n\t\t\t\t\t\t bool use_farthest_sampling, \n\t\t\t\t\t\t bool use_relative_grid)\n{\n\t// overwrite the leaf_size\n\tif (use_relative_grid) {\n\t\tdouble scale;\n\t\tgetScale(in_cloud, scale);\n\t\tleaf_size = scale / grid_resolution;\n\t}\n\n\t// downsampling\n\tEigen::MatrixXd downsampled_cloud;\n\tif (use_farthest_sampling)\n\t{\n\t\tfarthest_sampling_by_sphere(in_cloud, leaf_size/100, downsampled_cloud);\n\t}\n\telse\n\t{\n\t\tvoxel_grid_downsampling(in_cloud, leaf_size, downsampled_cloud);\n\t}\n\n\tout_cloud.resize(downsampled_cloud.rows(), 3);\n\n\tnanoflann_wrapper tree(in_cloud);\n\tfor (int i = 0; i < downsampled_cloud.rows(); ++i)\n\t{\n\t\tstd::vector< int > closest_point;\n\t\tclosest_point = tree.return_k_closest_points(downsampled_cloud.row(i), 1);\n\n\t\tout_cloud.row(i) = in_cloud.row( closest_point[0] );\n\t\tin_cloud_samples.push_back(closest_point[0]);\n\t}\n\n};\n\n#endif\n", "meta": {"hexsha": "a535c8c9bbc555bce8e1f1482e5e874ca370afe8", "size": 4045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "embedded_deformation/include/embedded_deformation/downsampling.hpp", "max_stars_repo_name": "jessemorris/embedded_deformation", "max_stars_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T23:42:04.000Z", "max_issues_repo_path": "embedded_deformation/include/embedded_deformation/downsampling.hpp", "max_issues_repo_name": "jessemorris/embedded_deformation", "max_issues_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-24T11:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T02:11:05.000Z", "max_forks_repo_path": "embedded_deformation/include/embedded_deformation/downsampling.hpp", "max_forks_repo_name": "jessemorris/embedded_deformation", "max_forks_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T10:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:38:35.000Z", "avg_line_length": 26.9666666667, "max_line_length": 125, "alphanum_fraction": 0.6754017305, "num_tokens": 1249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5623272986245297}}
{"text": "#include <iostream>\n#include <list>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <numeric>\n#include <string>\n#include <fstream>\n#include <map>\n#include <sstream>\n#include <limits>\n#include <bitset>\n#include <cmath>\n#include <unordered_map>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\nclass MemoryGame\n{\n    public:\n        MemoryGame(std::vector<long long> start_num) : starting_numbers(start_num) {}\n        std::vector<long long> starting_numbers;\n        long long play(const long long end_turn)\n        {\n            // key - number, value - vector of indices\n            std::map<long long, std::vector<long long>> map;\n            long long last_spoken;\n            long long turn = 1LL;\n            std::transform(starting_numbers.begin(), starting_numbers.end(), std::inserter(map, map.end()),\n            [&](const long long num) \n            { \n                std::vector<long long> indices {turn};\n                last_spoken = num;\n                turn++;\n                return std::pair<long long, std::vector<long long>>(num, indices); \n            });\n            while(turn <= end_turn)\n            {\n                // if size == 1 speak 0 because number was spoken only once, otherwise speak difference between turns\n                last_spoken = (map[last_spoken].size() == 1) ? 0 : map[last_spoken][1] - map[last_spoken][0];\n                // save current turn in map for spoken number\n                if(map[last_spoken].size() == 2)\n                {\n                    map[last_spoken][0] = map[last_spoken][1]; // shift to first\n                    map[last_spoken].pop_back(); // remove second\n                }\n                map[last_spoken].push_back(turn);              \n                turn++;\n            }\n            return last_spoken;\n        }\n};\n\nvoid part1(MemoryGame game)\n{\n    std::cout << \"======\\nPart 1\\n======\\n\";\n    constexpr long long end = 2020LL;\n    std::cout << end << \"th number spoken = \" << game.play(end) << '\\n';\n}\n\nvoid part2(MemoryGame game)\n{\n    std::cout << \"======\\nPart 2\\n======\\n\";\n    constexpr long long end = 30000000LL;\n    std::cout << end <<  \"th number spoken = \" << game.play(end) << '\\n';\n}\n\nstd::vector<long long> get_input(const std::string file_name)\n{\n    std::ifstream file(file_name);\n    std::string line;\n    std::vector<std::string> line_elements;\n    std::vector<long long> all_elements;\n    if(file.is_open())\n    {\n        while (std::getline(file, line)) \n        {\n            boost::split(line_elements, line, boost::is_any_of(\",\"), boost::token_compress_on);\n            std::transform(line_elements.begin(), line_elements.end(), std::back_inserter(all_elements),\n               [](const std::string& str) { return std::stoll(str); });\n        }\n    }\n    file.close();\n    return all_elements;\n}\n\nint main()\n{\n    const std::string file_name = \"/home/daria/Documents/AoC2020/input/day15.txt\";\n    std::vector<long long> puzzle_input = get_input(file_name);\n    MemoryGame game(puzzle_input);\n    part1(game);\n    std::cout << '\\n';\n    part2(game);\n    std::cout << '\\n';\n}", "meta": {"hexsha": "06283efafddb0106dba0a8c814c6f379cab7b7ff", "size": 3146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/day15.cpp", "max_stars_repo_name": "Daria2002/AoC2020", "max_stars_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day15.cpp", "max_issues_repo_name": "Daria2002/AoC2020", "max_issues_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day15.cpp", "max_forks_repo_name": "Daria2002/AoC2020", "max_forks_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_forks_repo_licenses": ["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.7708333333, "max_line_length": 117, "alphanum_fraction": 0.5702479339, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5623272945083615}}
{"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 * Authors: Jean-Paul Pelteret, \n *          Wolfgang Bangerth, Colorado State University, 2021. \n * Based on step-15, authored by Sven Wetterauer, University of Heidelberg, 2012 \n */ \n\n\n\n// 本教程的大部分内容是对  step-15  的完全复制。因此，为了简洁起见，并保持对这里所实现的变化的关注，我们将只记录新的内容，并简单地指出哪些部分的代码是对以前内容的重复。\n\n//  @sect3{Include files}  \n\n// 本教程中包含了几个新的头文件。第一个是提供ParameterAcceptor类的声明的文件。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/parameter_acceptor.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/utilities.h> \n\n// 这是第二个，这是一个包罗万象的头，它将使我们能够在这段代码中纳入自动区分（AD）功能。\n\n#include <deal.II/differentiation/ad.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_values_extractors.h> \n#include <deal.II/fe/fe_q.h> \n\n// 而接下来的三个提供了一些使用通用 MeshWorker::mesh_loop() 框架的多线程能力。\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\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#include <deal.II/numerics/solution_transfer.h> \n\n// 然后，我们为这个程序打开一个命名空间，像以前的程序一样，将dealii命名空间中的所有东西导入其中。\n\nnamespace Step72 \n{ \n  using namespace dealii; \n// @sect3{The <code>MinimalSurfaceProblemParameters</code> class}  \n\n// 在本教程中，我们将实现三种不同的方法来组装线性系统。其中一种反映了最初在 step-15 中提供的手工实现，而另外两种则使用作为Trilinos框架的一部分提供的Sacado自动微分库。\n\n// 为了方便在三种实现之间进行切换，我们有这个非常基本的参数类，它只有两个可配置的选项。\n\n  class MinimalSurfaceProblemParameters : public ParameterAcceptor \n  { \n  public: \n    MinimalSurfaceProblemParameters(); \n\n// 选择要使用的配方和相应的AD框架。\n\n// - formulation = 0 : 无辅助执行（全手工线性化）。\n\n// - 配方 = 1 : 有限元残差的自动线性化。\n\n// - formulation = 2 : 使用变量公式自动计算有限元残差和线性化。\n\n    unsigned int formulation = 0; \n\n// 线性系统残差的最大可接受公差。我们将看到，一旦我们使用AD框架，装配时间就会变得很明显，所以我们将 step-15 中选择的公差提高了一个数量级。这样，计算就不会花费太长时间来完成。\n\n    double tolerance = 1e-2; \n  }; \n\n  MinimalSurfaceProblemParameters::MinimalSurfaceProblemParameters() \n    : ParameterAcceptor(\"Minimal Surface Problem/\") \n  { \n    add_parameter( \n      \"Formulation\", formulation, \"\", this->prm, Patterns::Integer(0, 2)); \n    add_parameter(\"Tolerance\", tolerance, \"\", this->prm, Patterns::Double(0.0)); \n  } \n\n//  @sect3{The <code>MinimalSurfaceProblem</code> class template}  \n\n// 该类模板与  step-15  中的内容基本相同。该类的唯一功能变化是：。\n\n// - run()函数现在接收两个参数：一个是选择采用哪种装配方式，一个是允许的最终残差的公差，以及\n\n// - 现在有三个不同的装配函数来实现线性系统的三种装配方法。我们将在后面提供关于这些的细节。\n\n  template <int dim> \n  class MinimalSurfaceProblem \n  { \n  public: \n    MinimalSurfaceProblem(); \n\n    void run(const int formulation, const double tolerance); \n\n  private: \n    void   setup_system(const bool initial_step); \n    void   assemble_system_unassisted(); \n    void   assemble_system_with_residual_linearization(); \n    void   assemble_system_using_energy_functional(); \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    QGauss<dim>     quadrature_formula; \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//应用于该问题的边界条件没有变化。\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    , quadrature_formula(fe.degree + 1) \n  {} \n// @sect4{MinimalSurfaceProblem::setup_system}  \n\n// 设置类数据结构的函数没有任何变化，即DoFHandler、应用于问题的悬挂节点约束以及线性系统。\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    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{Assembling the linear system}  \n// @sect5{Manual assembly}  \n\n// 汇编函数是本教程的有趣贡献。assemble_system_unassisted()方法实现了与 step-15 中详述的完全相同的装配函数，但在这个例子中，我们使用 MeshWorker::mesh_loop() 函数来多线程装配过程。这样做的原因很简单。当使用自动分化时，我们知道会有一些额外的计算开销产生。为了减轻这种性能损失，我们希望尽可能多地利用（容易获得的）计算资源。 MeshWorker::mesh_loop() 的概念使这成为一个相对简单的任务。同时，为了公平比较，我们需要对在计算残差或其线性化时不使用任何援助的实现做同样的事情。( MeshWorker::mesh_loop() 函数首先在 step-12 和 step-16 中讨论，如果你想阅读它的话。)\n\n// 实现多线程所需的步骤在这三个函数中是相同的，所以我们将利用assemble_system_unassisted()函数的机会，重点讨论多线程本身。\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::assemble_system_unassisted() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n//  MeshWorker::mesh_loop() 希望我们提供两个示范性的数据结构。第一个，`ScratchData`，是用来存储所有要在线程间重复使用的大数据。`CopyData`将保存来自每个单元的对线性系统的贡献。这些独立的矩阵-向量对必须按顺序累积到全局线性系统中。由于我们不需要 MeshWorker::ScratchData 和 MeshWorker::CopyData 类已经提供的东西，所以我们使用这些确切的类定义来解决我们的问题。请注意，我们只需要一个局部矩阵、局部右手向量和单元自由度索引向量的单个实例--因此 MeshWorker::CopyData 的三个模板参数都是`1`。\n\n    using ScratchData = MeshWorker::ScratchData<dim>; \n    using CopyData    = MeshWorker::CopyData<1, 1, 1>; \n\n// 我们还需要知道我们在装配过程中要处理的迭代器的类型。为了简单起见，我们只要求编译器使用decltype()指定器为我们解决这个问题，知道我们将在由  @p dof_handler.  拥有的活动单元上迭代。\n    using CellIteratorType = decltype(dof_handler.begin_active()); \n\n// 在这里我们初始化示例的数据结构。因为我们知道我们需要计算形状函数梯度、加权雅各布和四分位点在实空间的位置，所以我们把这些标志传给类的构造函数。\n\n    const ScratchData sample_scratch_data(fe, \n                                          quadrature_formula, \n                                          update_gradients | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n    const CopyData    sample_copy_data(dofs_per_cell); \n\n// 现在我们定义一个lambda函数，它将在一个单元格上执行装配。三个参数是由于我们将传递给该最终调用的参数，将被 MeshWorker::mesh_loop(), 所期望的参数。我们还捕获了 @p this 指针，这意味着我们将可以访问 \"this\"（即当前的`MinimalSurfaceProblem<dim>`）类实例，以及它的私有成员数据（因为lambda函数被定义在MinimalSurfaceProblem<dim>方法中）。\n\n// 在函数的顶部，我们初始化了依赖于正在执行工作的单元的数据结构。请注意，重新初始化的调用实际上返回了一个FEValues对象的实例，该对象被初始化并存储在`scratch_data`对象中（因此，被重复使用）。\n\n// 同样地，我们从 MeshWorker::mesh_loop() 提供的`copy_data`实例中获得本地矩阵、本地RHS向量和本地单元格DoF指数的别名。然后我们初始化单元格的DoF指数，因为我们知道本地矩阵和向量的大小已经正确。\n\n    const auto cell_worker = [this](const CellIteratorType &cell, \n                                    ScratchData &           scratch_data, \n                                    CopyData &              copy_data) { \n      const auto &fe_values = scratch_data.reinit(cell); \n\n      FullMatrix<double> &                  cell_matrix = copy_data.matrices[0]; \n      Vector<double> &                      cell_rhs    = copy_data.vectors[0]; \n      std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \n      cell->get_dof_indices(local_dof_indices); \n\n// 对于牛顿方法，我们需要问题被线性化的那一点的解的梯度。\n\n// 一旦我们有了这个梯度，我们就可以用通常的方法对这个单元进行装配。 与 step-15 的一个小区别是，我们使用了（相当方便的）基于范围的循环来迭代所有的正交点和自由度。\n\n      std::vector<Tensor<1, dim>> old_solution_gradients( \n        fe_values.n_quadrature_points); \n      fe_values.get_function_gradients(current_solution, \n                                       old_solution_gradients); \n\n      for (const unsigned int q : fe_values.quadrature_point_indices()) \n        { \n          const double coeff = \n            1.0 / std::sqrt(1.0 + old_solution_gradients[q] * \n                                    old_solution_gradients[q]); \n\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)      // ((\\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\n//  MeshWorker::mesh_loop() 要求的第二个lambda函数是一个执行累积全局线性系统中的局部贡献的任务。这正是这个函数所做的，实现的细节在前面已经看到过。需要认识的主要一点是，局部贡献被存储在传入该函数的`copy_data`实例中。这个`copy_data`在 @a 对`cell_worker`的一些调用中已经被填满了数据。\n\n    const auto copier = [dofs_per_cell, this](const CopyData &copy_data) { \n      const FullMatrix<double> &cell_matrix = copy_data.matrices[0]; \n      const Vector<double> &    cell_rhs    = copy_data.vectors[0]; \n      const std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \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            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// 我们已经有了所有需要的函数定义，所以现在我们调用 MeshWorker::mesh_loop() 来执行实际的装配。 我们传递一个标志作为最后的参数，说明我们只想对单元格进行装配。在内部， MeshWorker::mesh_loop() 然后将可用的工作分配给不同的线程，有效地利用当今几乎所有的处理器所提供的多核。\n\n    MeshWorker::mesh_loop(dof_handler.active_cell_iterators(), \n                          cell_worker, \n                          copier, \n                          sample_scratch_data, \n                          sample_copy_data, \n                          MeshWorker::assemble_own_cells); \n\n// 最后，正如在  step-15  中所做的那样，我们从系统中移除悬空的节点，并对定义牛顿更新的线性系统应用零边界值  $\\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// @sect5{Assembly via differentiation of the residual vector}  \n\n// 正如介绍中所述，我们需要为第二种方法做的是实现 $F(U)^K$ 单元对残差向量的局部贡献，然后让AD机器处理如何计算它的导数 $J(U)_{ij}^K=\\frac{\\partial F(U)^K_i}{\\partial U_j}$ 。\n\n// 对于下面的内容，请记住，\n// @f[\n//    F(U)_i^K \\dealcoloneq\n//    \\int\\limits_K\\nabla \\varphi_i \\cdot \\left[ \\frac{1}{\\sqrt{1+|\\nabla\n//    u|^{2}}} \\nabla u \\right] \\, dV ,\n//  @f] \n//  其中 $u(\\mathbf x)=\\sum_j U_j \\varphi_j(\\mathbf x)$  。\n\n// 我们来看看这在实践中是如何实现的。\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::assemble_system_with_residual_linearization() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n    using ScratchData      = MeshWorker::ScratchData<dim>; \n    using CopyData         = MeshWorker::CopyData<1, 1, 1>; \n    using CellIteratorType = decltype(dof_handler.begin_active()); \n\n    const ScratchData sample_scratch_data(fe, \n                                          quadrature_formula, \n                                          update_gradients | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n    const CopyData    sample_copy_data(dofs_per_cell); \n\n// 我们将利用  step-71  中所示的技术，预先定义我们要使用的AD数据结构。在这种情况下，我们选择辅助类，它将使用Sacado向前自动微分类型自动计算有限元残差的线性化。这些数字类型可以只用来计算一阶导数。这正是我们想要的，因为我们知道我们将只对残差进行线性化，这意味着我们只需要计算一阶导数。计算的返回值将是`double`类型。\n\n// 我们还需要一个提取器来检索一些与问题的现场解决方案有关的数据。\n\n    using ADHelper = Differentiation::AD::ResidualLinearization< \n      Differentiation::AD::NumberTypes::sacado_dfad, \n      double>; \n    using ADNumberType = typename ADHelper::ad_type; \n\n    const FEValuesExtractors::Scalar u_fe(0); \n\n// 有了这个，让我们定义lambda函数，它将被用来计算单元格对雅各布矩阵和右手边的贡献。\n\n    const auto cell_worker = [&u_fe, this](const CellIteratorType &cell, \n                                           ScratchData &           scratch_data, \n                                           CopyData &              copy_data) { \n      const auto &       fe_values     = scratch_data.reinit(cell); \n      const unsigned int dofs_per_cell = fe_values.get_fe().n_dofs_per_cell(); \n\n      FullMatrix<double> &                  cell_matrix = copy_data.matrices[0]; \n      Vector<double> &                      cell_rhs    = copy_data.vectors[0]; \n      std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \n      cell->get_dof_indices(local_dof_indices); \n\n// 我们现在要创建并初始化一个AD辅助类的实例。要做到这一点，我们需要指定有多少个自变量和因变量。自变量将是我们的解向量所具有的局部自由度的数量，即离散化解向量 $u (\\mathbf{x})|_K = \\sum\\limits_{j} U^K_i \\varphi_j(\\mathbf{x})$ 的每元素表示中的数字 $j$ ，它表示每个有限元素有多少个解系数。在deal.II中，这等于 FiniteElement::dofs_per_cell. ，自变量的数量将是我们要形成的局部残差向量的条目数。在这个特定的问题中（就像许多其他采用[标准Galerkin方法](https:en.wikipedia.org/wiki/Galerkin_method)的问题一样），局部求解系数的数量与局部残差方程的数量相符。\n\n      const unsigned int n_independent_variables = local_dof_indices.size(); \n      const unsigned int n_dependent_variables   = dofs_per_cell; \n      ADHelper ad_helper(n_independent_variables, n_dependent_variables); \n\n// 接下来，我们将解决方案的值告知帮助器，即我们希望线性化的 $U_j$ 的实际值。由于这是在每个元素上单独进行的，我们必须从全局解决方案向量中提取解决方案的系数。换句话说，我们将所有这些系数 $U_j$ （其中 $j$ 是一个局部自由度）定义为进入向量 $F(U)^{K}$ （因果函数）计算的自变量。\n//然后，\n//我们就得到了由可自动微分的数字表示的自由度值的完整集合。对这些变量进行的操作从这一点开始被AD库跟踪，直到对象超出范围。所以正是这些变量 <em>  </em> ，我们将对其计算残差项的导数。\n\n      ad_helper.register_dof_values(current_solution, local_dof_indices); \n\n      const std::vector<ADNumberType> &dof_values_ad = \n        ad_helper.get_sensitive_dof_values(); \n\n// 然后我们做一些特定问题的任务，首先是根据 \"敏感 \"的AD自由度值计算所有数值、（空间）梯度等。在这个例子中，我们要检索每个正交点的解梯度。请注意，现在解梯度对自由度值很敏感，因为它们使用 @p ADNumberType 作为标量类型， @p dof_values_ad 矢量提供局部自由度值。\n\n      std::vector<Tensor<1, dim, ADNumberType>> old_solution_gradients( \n        fe_values.n_quadrature_points); \n      fe_values[u_fe].get_function_gradients_from_local_dof_values( \n        dof_values_ad, old_solution_gradients); \n\n// 我们声明的下一个变量将存储单元格残余向量贡献。这是相当不言自明的，除了一个<b>very important</b>的细节。请注意，向量中的每个条目都是手工初始化的，数值为0。这是一个 <em> 强烈推荐的 </em> 做法，因为一些AD库似乎没有安全地初始化这些数字类型的内部数据结构。不这样做可能会导致一些非常难以理解或检测的错误（感谢这个程序的作者出于一般的坏经验而提到这一点）。因此，出于谨慎考虑，值得明确地将初始值归零。在这之后，除了符号的改变，残差集看起来和我们之前看到的单元格RHS向量差不多。我们在所有正交点上循环，确保系数现在通过使用正确的`ADNumberType'来编码它对（敏感的）有限元DoF值的依赖性，最后我们组装残差向量的组件。为了完全清楚，有限元形状函数（及其梯度等）以及 \"JxW \"值仍然是标量值，但每个正交点的 @p coeff 和 @p old_solution_gradients 是以独立变量计算的。\n\n      std::vector<ADNumberType> residual_ad(n_dependent_variables, \n                                            ADNumberType(0.0)); \n      for (const unsigned int q : fe_values.quadrature_point_indices()) \n        { \n          const ADNumberType coeff = \n            1.0 / std::sqrt(1.0 + old_solution_gradients[q] * \n                                    old_solution_gradients[q]); \n\n          for (const unsigned int i : fe_values.dof_indices()) \n            { \n              residual_ad[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// 一旦我们计算出完整的单元格残差向量，我们就可以将其注册到辅助类。\n\n// 此后，我们在评估点计算残差值（基本上是从我们已经计算出来的东西中提取出真实的值）和它们的Jacobian（每个残差分量相对于所有单元DoF的线性化）。为了组装成全局线性系统，我们必须尊重残差和RHS贡献之间的符号差异。对于牛顿方法，右手边的向量需要等于*负的残差向量。\n\n      ad_helper.register_residual_vector(residual_ad); \n\n      ad_helper.compute_residual(cell_rhs); \n      cell_rhs *= -1.0; \n\n      ad_helper.compute_linearization(cell_matrix); \n    }; \n\n// 该函数的剩余部分等于我们之前的内容。\n\n    const auto copier = [dofs_per_cell, this](const CopyData &copy_data) { \n      const FullMatrix<double> &cell_matrix = copy_data.matrices[0]; \n      const Vector<double> &    cell_rhs    = copy_data.vectors[0]; \n      const std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \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            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    MeshWorker::mesh_loop(dof_handler.active_cell_iterators(), \n                          cell_worker, \n                          copier, \n                          sample_scratch_data, \n                          sample_copy_data, \n                          MeshWorker::assemble_own_cells); \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// @sect5{Assembly via differentiation of the energy functional}  \n\n// 在这第三种方法中，我们将残差和雅各布作为局部能量函数\n// @f[\n//     E\\left( U \\right)^K\n//      \\dealcoloneq \\int\\limits_{K} \\Psi \\left( u \\right) \\, dV\n//      \\approx \\sum\\limits_{q}^{n_{\\textrm{q-points}}} \\Psi \\left( u \\left(\n//      \\mathbf{X}_{q} \\right) \\right) \\underbrace{\\vert J_{q} \\vert \\times\n//      W_{q}}_{\\text{JxW(q)}}\n//  @f]\n//  的第一和第二导数来计算，能量密度由\n//  @f[\n//    \\Psi \\left( u \\right) = \\sqrt{1+|\\nabla u|^{2}} .\n//  @f]给出。\n\n// 我们再来看看这是如何做到的。\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::assemble_system_using_energy_functional() \n  { \n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n    using ScratchData      = MeshWorker::ScratchData<dim>; \n    using CopyData         = MeshWorker::CopyData<1, 1, 1>; \n    using CellIteratorType = decltype(dof_handler.begin_active()); \n\n    const ScratchData sample_scratch_data(fe, \n                                          quadrature_formula, \n                                          update_gradients | \n                                            update_quadrature_points | \n                                            update_JxW_values); \n    const CopyData    sample_copy_data(dofs_per_cell); \n\n// 在这个装配过程的实现中，我们选择了辅助类，它将使用嵌套的Sacado前向自动微分类型自动计算残差及其从单元贡献到能量函数的线性化。所选的数字类型可以用来计算第一和第二导数。我们需要这样做，因为残差定义为势能对DoF值的敏感性（即其梯度）。然后我们需要将残差线性化，这意味着必须计算势能的二阶导数。你可能想把这与之前函数中使用的 \"ADHelper \"的定义进行比较，在那里我们使用 `Differentiation::AD::ResidualLinearization<Differentiation::AD::NumberTypes::sacado_dfad,double>`. 。\n    using ADHelper = Differentiation::AD::EnergyFunctional< \n      Differentiation::AD::NumberTypes::sacado_dfad_dfad, \n      double>; \n    using ADNumberType = typename ADHelper::ad_type; \n\n    const FEValuesExtractors::Scalar u_fe(0); \n\n// 然后让我们再次定义lambda函数，对一个单元进行积分。\n\n// 为了初始化辅助类的实例，我们现在只需要预先知道自变量的数量（即与元素解向量相关的自由度数量）。这是因为由能量函数产生的二阶导数矩阵必然是平方的（顺便说一下，也是对称的）。\n\n    const auto cell_worker = [&u_fe, this](const CellIteratorType &cell, \n                                           ScratchData &           scratch_data, \n                                           CopyData &              copy_data) { \n      const auto &fe_values = scratch_data.reinit(cell); \n\n      FullMatrix<double> &                  cell_matrix = copy_data.matrices[0]; \n      Vector<double> &                      cell_rhs    = copy_data.vectors[0]; \n      std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \n      cell->get_dof_indices(local_dof_indices); \n\n      const unsigned int n_independent_variables = local_dof_indices.size(); \n      ADHelper           ad_helper(n_independent_variables); \n\n// 再一次，我们将所有的单元格DoFs值注册到帮助器中，然后提取这些值的 \"敏感 \"变体，用于后续必须区分的操作--其中之一是计算解决方案的梯度。\n\n      ad_helper.register_dof_values(current_solution, local_dof_indices); \n\n      const std::vector<ADNumberType> &dof_values_ad = \n        ad_helper.get_sensitive_dof_values(); \n\n      std::vector<Tensor<1, dim, ADNumberType>> old_solution_gradients( \n        fe_values.n_quadrature_points); \n      fe_values[u_fe].get_function_gradients_from_local_dof_values( \n        dof_values_ad, old_solution_gradients); \n\n// 我们接下来创建一个变量来存储电池的总能量。我们再一次强调，我们明确地对这个值进行零初始化，从而确保这个起始值的数据的完整性。\n\n// 我们的目的是计算细胞总能量，它是内部能量（由于右手函数，通常是 $U$ 的线性）和外部能量的总和。在这种特殊情况下，我们没有外部能量（例如，来自源项或诺伊曼边界条件），所以我们将关注内部能量部分。\n\n// 事实上，计算 $E(U)^K$ 几乎是微不足道的，只需要以下几行。\n\n      ADNumberType energy_ad = ADNumberType(0.0); \n      for (const unsigned int q : fe_values.quadrature_point_indices()) \n        { \n          const ADNumberType psi = std::sqrt(1.0 + old_solution_gradients[q] * \n                                                     old_solution_gradients[q]); \n\n          energy_ad += psi * fe_values.JxW(q); \n        } \n\n// 在我们计算出这个单元的总能量后，我们将把它注册到帮助器上。 在此基础上，我们现在可以计算出所需的数量，即残差值和它们在评估点的雅各布系数。和以前一样，牛顿的右手边需要是残差的负数。\n\n      ad_helper.register_energy_functional(energy_ad); \n\n      ad_helper.compute_residual(cell_rhs); \n      cell_rhs *= -1.0; \n\n \n    }; \n\n// 与前两个函数一样，函数的剩余部分与之前一样。\n\n    const auto copier = [dofs_per_cell, this](const CopyData &copy_data) { \n      const FullMatrix<double> &cell_matrix = copy_data.matrices[0]; \n      const Vector<double> &    cell_rhs    = copy_data.vectors[0]; \n      const std::vector<types::global_dof_index> &local_dof_indices = \n        copy_data.local_dof_indices[0]; \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            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    MeshWorker::mesh_loop(dof_handler.active_cell_iterators(), \n                          cell_worker, \n                          copier, \n                          sample_scratch_data, \n                          sample_copy_data, \n                          MeshWorker::assemble_own_cells); \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// @sect4{MinimalSurfaceProblem::solve}  \n\n// 解算函数与  step-15  中使用的相同。\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-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    SolutionTransfer<dim> solution_transfer(dof_handler); \n    solution_transfer.prepare_for_coarsening_and_refinement(current_solution); \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 = tmp; \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    set_boundary_values(); \n\n \n  } \n\n//  @sect4{MinimalSurfaceProblem::set_boundary_values}  \n\n// 边界条件的选择仍然与 step-15 相同 ...\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::set_boundary_values() \n  { \n    std::map<types::global_dof_index, double> boundary_values; \n  }; \n  template <int dim> \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// ...就像在求解迭代过程中用来计算残差的函数一样。如果真的需要，我们可以用能量函数的微分来代替它，但是为了简单起见，我们在这里只是简单地复制我们在 step-15 中已经有的东西。\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        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.0 / std::sqrt(1.0 + 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    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    return residual.l2_norm(); \n  } \n\n//  @sect4{MinimalSurfaceProblem::determine_step_length}  \n\n// 非线性迭代程序的步长（或欠松系数）的选择仍然固定在  step-15  中选择和讨论的值。\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// 在运行函数中，大部分内容与最初在  step-15  中实现的相同。唯一可以观察到的变化是，我们现在可以（通过参数文件）选择系统残差的最终可接受的公差是什么，并且我们可以选择我们希望利用的装配方法。为了使第二个选择明确，我们向控制台输出一些信息，表明选择。由于我们对比较三种方法中每一种的装配时间感兴趣，我们还添加了一个计时器，跟踪装配过程中所花费的时间。我们还跟踪了解决线性系统所需的时间，这样我们就可以将这些数字与通常需要最长时间执行的那部分代码进行对比。\n\n  template <int dim> \n  void MinimalSurfaceProblem<dim>::run(const int    formulation, \n                                       const double tolerance) \n  { \n    std::cout << \"******** Assembly approach ********\" << std::endl; \n    const std::array<std::string, 3> method_descriptions = { \n      {\"Unassisted implementation (full hand linearization).\", \n       \"Automated linearization of the finite element residual.\", \n       \"Automated computation of finite element residual and linearization using a variational formulation.\"}}; \n    AssertIndexRange(formulation, method_descriptions.size()); \n    std::cout << method_descriptions[formulation] << std::endl << std::endl; \n\n    TimerOutput timer(std::cout, TimerOutput::summary, TimerOutput::wall_times); \n\n    GridGenerator::hyper_ball(triangulation); \n    triangulation.refine_global(2); \n\n    setup_system(/*first time=*/true); \n    set_boundary_values(); \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        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            { \n              TimerOutput::Scope t(timer, \"Assemble\"); \n\n              if (formulation == 0) \n                assemble_system_unassisted(); \n              else if (formulation == 1) \n                assemble_system_with_residual_linearization(); \n              else if (formulation == 2) \n                assemble_system_using_energy_functional(); \n              else \n                AssertThrow(false, ExcNotImplemented()); \n            } \n\n            last_residual_norm = system_rhs.l2_norm(); \n\n            { \n              TimerOutput::Scope t(timer, \"Solve\"); \n              solve(); \n            } \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 > tolerance); \n  } \n} // namespace Step72 \n// @sect4{The main function}  \n\n// 最后是主函数。它遵循大多数其他主函数的方案，但有两个明显的例外。\n\n// - 我们调用 Utilities::MPI::MPI_InitFinalize ，以便（通过一个隐藏的默认参数）设置使用多线程任务执行的线程数。\n\n// - 我们还有几行专门用于读取或初始化用户定义的参数，这些参数将在程序执行过程中被考虑。\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace Step72; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv); \n\n      std::string prm_file; \n      if (argc > 1) \n        prm_file = argv[1]; \n      else \n        prm_file = \"parameters.prm\"; \n\n      const MinimalSurfaceProblemParameters parameters; \n      ParameterAcceptor::initialize(prm_file); \n\n      MinimalSurfaceProblem<2> minimal_surface_problem_2d; \n      minimal_surface_problem_2d.run(parameters.formulation, \n                                     parameters.tolerance); \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": "dc91574f6ffa4bbe93e8b51703039f2f67ee57e0", "size": 35734, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-72/step-72.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-72/step-72.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-72/step-72.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.3823845328, "max_line_length": 425, "alphanum_fraction": 0.6169754296, "num_tokens": 11863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802423634963, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.5622427133410969}}
{"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 to fit into the\n//  Boost.Math conceptual framework better, and to handle\n//  types longer than 80-bit reals.\n//\n#ifndef BOOST_MATH_ELLINT_RF_HPP\n#define BOOST_MATH_ELLINT_RF_HPP\n\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/config.hpp>\n\n#include <boost/math/policies/error_handling.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 { namespace math { namespace detail{\n\ntemplate <typename T, typename Policy>\nT ellint_rf_imp(T x, T y, T z, const Policy& pol)\n{\n    T value, X, Y, Z, E2, E3, u, lambda, tolerance;\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_rf<%1%>(%1%,%1%,%1%)\";\n\n    if (x < 0 || y < 0 || z < 0)\n    {\n       return policies::raise_domain_error<T>(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>(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    // Carlson scales error as the 6th power of tolerance,\n    // but this seems not to work for types larger than\n    // 80-bit reals, this heuristic seems to work OK:\n    if(policies::digits<T, Policy>() > 64)\n    {\n      tolerance = pow(tools::epsilon<T>(), T(1)/4.25f);\n      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n    }\n    else\n    {\n      tolerance = pow(4*tools::epsilon<T>(), T(1)/6);\n      BOOST_MATH_INSTRUMENT_VARIABLE(tolerance);\n    }\n\n    // duplication\n    k = 1;\n    do\n    {\n        u = (x + y + z) / 3;\n        X = (u - x) / u;\n        Y = (u - y) / u;\n        Z = (u - z) / u;\n\n        // Termination condition: \n        if ((tools::max)(abs(X), abs(Y), abs(Z)) < tolerance) \n           break; \n\n        T sx = sqrt(x);\n        T sy = sqrt(y);\n        T sz = sqrt(z);\n        lambda = sy * (sx + sz) + sz * sx;\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(function, k, pol);\n    BOOST_MATH_INSTRUMENT_VARIABLE(k);\n\n    // Taylor series expansion to the 5th order\n    E2 = X * Y - Z * Z;\n    E3 = X * Y * Z;\n    value = (1 + E2*(E2/24 - E3*T(3)/44 - T(0.1)) + E3/14) / sqrt(u);\n    BOOST_MATH_INSTRUMENT_VARIABLE(value);\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_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(\n         static_cast<value_type>(x),\n         static_cast<value_type>(y),\n         static_cast<value_type>(z), pol), \"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 \n   ellint_rf(T1 x, T2 y, T3 z)\n{\n   return ellint_rf(x, y, z, policies::policy<>());\n}\n\n}} // namespaces\n\n#endif // BOOST_MATH_ELLINT_RF_HPP\n", "meta": {"hexsha": "f573b21c75fd6de1ccd45eb8814fcf25392bdd0e", "size": 3956, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/special_functions/ellint_rf.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/ellint_rf.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/ellint_rf.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.90625, "max_line_length": 87, "alphanum_fraction": 0.6084428716, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.562242703691161}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  Base implementations for math library.\n * @author Jakob Bornecrantz <jakob@collabora.com>\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_math\n */\n\n#include \"math/m_api.h\"\n#include \"math/m_eigen_interop.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <assert.h>\n\n\n/*\n *\n * Copy helpers.\n *\n */\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat &q)\n{\n\t// Eigen constructor order is different from XRT, OpenHMD and OpenXR!\n\t//  Eigen: `float w, x, y, z`.\n\t// OpenXR: `float x, y, z, w`.\n\treturn Eigen::Quaternionf(q.w, q.x, q.y, q.z);\n}\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat *q)\n{\n\treturn copy(*q);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3 &v)\n{\n\treturn Eigen::Vector3f(v.x, v.y, v.z);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3 *v)\n{\n\treturn copy(*v);\n}\n\n\n/*\n *\n * Exported vector functions.\n *\n */\n\nextern \"C\" bool\nmath_vec3_validate(const struct xrt_vec3 *vec3)\n{\n\tassert(vec3 != NULL);\n\n\treturn map_vec3(*vec3).allFinite();\n}\n\nextern \"C\" void\nmath_vec3_accum(const struct xrt_vec3 *additional, struct xrt_vec3 *inAndOut)\n{\n\tassert(additional != NULL);\n\tassert(inAndOut != NULL);\n\n\tmap_vec3(*inAndOut) += map_vec3(*additional);\n}\n\nextern \"C\" void\nmath_vec3_cross(const struct xrt_vec3 *l,\n                const struct xrt_vec3 *r,\n                struct xrt_vec3 *result)\n{\n\tmap_vec3(*result) = map_vec3(*l).cross(map_vec3(*r));\n}\n\n\n/*\n *\n * Exported quaternion functions.\n *\n */\n\nextern \"C\" void\nmath_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat,\n                          struct xrt_quat *result)\n{\n\tEigen::Matrix3f m;\n\tm << mat->v[0], mat->v[1], mat->v[2], mat->v[3], mat->v[4], mat->v[5],\n\t    mat->v[6], mat->v[7], mat->v[8];\n\n\tEigen::Quaternionf q(m);\n\tmap_quat(*result) = q;\n}\n\nextern \"C\" void\nmath_quat_from_plus_x_z(const struct xrt_vec3 *plus_x,\n                        const struct xrt_vec3 *plus_z,\n                        struct xrt_quat *result)\n{\n\txrt_vec3 plus_y;\n\tmath_vec3_cross(plus_z, plus_x, &plus_y);\n\n\txrt_matrix_3x3 m = {{\n\t    plus_x->x,\n\t    plus_y.x,\n\t    plus_z->x,\n\t    plus_x->y,\n\t    plus_y.y,\n\t    plus_z->y,\n\t    plus_x->z,\n\t    plus_y.z,\n\t    plus_z->z,\n\t}};\n\n\tmath_quat_from_matrix_3x3(&m, result);\n}\n\nextern \"C\" bool\nmath_quat_validate(const struct xrt_quat *quat)\n{\n\tassert(quat != NULL);\n\tauto rot = copy(*quat);\n\n\tconst float FLOAT_EPSILON = Eigen::NumTraits<float>::epsilon();\n\tauto norm = rot.squaredNorm();\n\tif (norm > 1.0f + FLOAT_EPSILON || norm < 1.0f - FLOAT_EPSILON) {\n\t\treturn false;\n\t}\n\n\t// Technically not yet a required check, but easier to stop problems\n\t// now than once denormalized numbers pollute the rest of our state.\n\t// see https://gitlab.khronos.org/openxr/openxr/issues/922\n\tif (!rot.coeffs().allFinite()) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nextern \"C\" void\nmath_quat_normalize(struct xrt_quat *inout)\n{\n\tassert(inout != NULL);\n\tmap_quat(*inout).normalize();\n}\n\nextern \"C\" void\nmath_quat_rotate(const struct xrt_quat *left,\n                 const struct xrt_quat *right,\n                 struct xrt_quat *result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto q = l * r;\n\n\tmap_quat(*result) = q;\n}\n\nextern \"C\" void\nmath_quat_rotate_vec3(const struct xrt_quat *left,\n                      const struct xrt_vec3 *right,\n                      struct xrt_vec3 *result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto v = l * r;\n\n\tmap_vec3(*result) = v;\n}\n\n\n/*\n *\n * Exported pose functions.\n *\n */\n\nextern \"C\" bool\nmath_pose_validate(const struct xrt_pose *pose)\n{\n\tassert(pose != NULL);\n\n\treturn math_vec3_validate(&pose->position) &&\n\t       math_quat_validate(&pose->orientation);\n}\n\nextern \"C\" void\nmath_pose_invert(const struct xrt_pose *pose, struct xrt_pose *outPose)\n{\n\tassert(pose != NULL);\n\tassert(outPose != NULL);\n\n\t// Store results to temporary locals so we can do this \"in-place\"\n\t// (pose == outPose) if desired. Pure copies here.\n\tEigen::Vector3f newPosition = position(*pose);\n\tEigen::Quaternionf newOrientation = orientation(*pose);\n\n\t// Conjugate legal here since pose must be normalized/unit length.\n\tnewOrientation = newOrientation.conjugate();\n\t// Use the newly inverted rotation, to rotate position.\n\tnewPosition = -(newOrientation * newPosition);\n\n\tposition(*outPose) = newPosition;\n\torientation(*outPose) = newOrientation;\n}\n\n/*!\n * Return the result of transforming a point by a pose/transform.\n */\nstatic inline Eigen::Vector3f\ntransform_point(const xrt_pose &transform, const xrt_vec3 &point)\n{\n\treturn orientation(transform) * map_vec3(point) + position(transform);\n}\n\n/*!\n * Return the result of transforming a pose by a pose/transform.\n */\nstatic inline xrt_pose\ntransform_pose(const xrt_pose &transform, const xrt_pose &pose)\n{\n\txrt_pose ret;\n\tposition(ret) = transform_point(transform, pose.position);\n\torientation(ret) = orientation(transform) * orientation(pose);\n\treturn ret;\n}\n\nextern \"C\" void\nmath_pose_transform(const struct xrt_pose *transform,\n                    const struct xrt_pose *pose,\n                    struct xrt_pose *outPose)\n{\n\tassert(pose != NULL);\n\tassert(transform != NULL);\n\tassert(outPose != NULL);\n\n\txrt_pose newPose = transform_pose(*transform, *pose);\n\tmemcpy(outPose, &newPose, sizeof(xrt_pose));\n}\n\nextern \"C\" void\nmath_pose_transform_point(const struct xrt_pose *transform,\n                          const struct xrt_vec3 *point,\n                          struct xrt_vec3 *out_point)\n{\n\tassert(transform != NULL);\n\tassert(point != NULL);\n\tassert(out_point != NULL);\n\n\tmap_vec3(*out_point) = transform_point(*transform, *point);\n}\n\nextern \"C\" void\nmath_pose_openxr_locate(const struct xrt_pose *space_pose,\n                        const struct xrt_pose *relative_pose,\n                        const struct xrt_pose *base_space_pose,\n                        struct xrt_pose *result)\n{\n\tassert(space_pose != NULL);\n\tassert(relative_pose != NULL);\n\tassert(base_space_pose != NULL);\n\tassert(result != NULL);\n\n\t// Compilers are slightly better optimizing\n\t// if we copy the arguments in one go.\n\tconst auto bsp = *base_space_pose;\n\tconst auto rel = *relative_pose;\n\tconst auto spc = *space_pose;\n\tstruct xrt_pose pose;\n\n\t// Apply the invert of the base space to identity.\n\tmath_pose_invert(&bsp, &pose);\n\n\t// Apply the pure pose from the space relation.\n\tmath_pose_transform(&pose, &rel, &pose);\n\n\t// Apply the space pose.\n\tmath_pose_transform(&pose, &spc, &pose);\n\n\t*result = pose;\n}\n\n/*!\n * Return the result of rotating a derivative vector by a matrix.\n *\n * This is a differential transform.\n */\nstatic inline Eigen::Vector3f\nrotate_deriv(Eigen::Matrix3f const &rotation,\n             const xrt_vec3 &derivativeVector,\n             Eigen::Matrix3f const &rotationInverse)\n{\n\treturn ((rotation * map_vec3(derivativeVector)).transpose() *\n\t        rotationInverse)\n\t    .transpose();\n}\n\n#ifndef XRT_DOXYGEN\n\n#define MAKE_REL_FLAG_CHECK(NAME, MASK)                                        \\\n\tstatic inline bool NAME(xrt_space_relation_flags flags)                \\\n\t{                                                                      \\\n\t\treturn ((flags & (MASK)) != 0);                                \\\n\t}\n\nMAKE_REL_FLAG_CHECK(has_some_pose_component,\n                    XRT_SPACE_RELATION_POSITION_VALID_BIT |\n                        XRT_SPACE_RELATION_ORIENTATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_position, XRT_SPACE_RELATION_POSITION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_orientation, XRT_SPACE_RELATION_ORIENTATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_lin_vel, XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_ang_vel, XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_lin_acc,\n                    XRT_SPACE_RELATION_LINEAR_ACCELERATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_ang_acc,\n                    XRT_SPACE_RELATION_ANGULAR_ACCELERATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_some_derivative,\n                    XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT |\n                        XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT |\n                        XRT_SPACE_RELATION_LINEAR_ACCELERATION_VALID_BIT |\n                        XRT_SPACE_RELATION_ANGULAR_ACCELERATION_VALID_BIT)\n\n#undef MAKE_REL_FLAG_CHECK\n\n#endif // !XRT_DOXYGEN\n\nenum accumulate_pose_flags\n{\n\tOFFSET,\n\tLEGACY,\n};\n\n/*!\n * Apply a transform to a space relation.\n */\nstatic inline void\ntransform_accumulate_pose(const xrt_pose &transform,\n                          xrt_space_relation &relation,\n                          enum accumulate_pose_flags accum_flags,\n                          bool do_translation = true,\n                          bool do_rotation = true)\n{\n\tassert(do_translation || do_rotation);\n\n\t// Save the quat in case we are self-transforming.\n\tEigen::Quaternionf quat = orientation(transform);\n\n\tauto flags = relation.relation_flags;\n\t// so code looks similar\n\tauto in_out_relation = &relation;\n\n\t// transform (rotate and translate) the pose, if applicable.\n\tif (has_some_pose_component(flags)) {\n\t\t// Zero out transform parts we don't want to use,\n\t\t// because math_pose_transform doesn't take flags.\n\t\txrt_pose transform_copy = transform;\n\t\tif (!do_translation) {\n\t\t\tposition(transform_copy) = Eigen::Vector3f::Zero();\n\t\t}\n\t\tif (!do_rotation) {\n\t\t\torientation(transform_copy) =\n\t\t\t    Eigen::Quaternionf::Identity();\n\t\t}\n\n\t\t//! @todo This is just a big hack.\n\t\tif (accum_flags == OFFSET) {\n\t\t\tmath_pose_transform(&transform, &in_out_relation->pose,\n\t\t\t                    &in_out_relation->pose);\n\t\t} else {\n\t\t\tmath_pose_transform(&in_out_relation->pose, &transform,\n\t\t\t                    &in_out_relation->pose);\n\t\t}\n\t}\n\n\tif (do_rotation && has_some_derivative(flags)) {\n\n\t\t// prepare matrices required for rotating derivatives from the\n\t\t// saved quat.\n\t\tEigen::Matrix3f rot = quat.toRotationMatrix();\n\t\tEigen::Matrix3f rotInverse = rot.inverse();\n\n\t\t// Rotate derivatives, if applicable.\n\t\tif (has_lin_vel(flags)) {\n\t\t\tmap_vec3(in_out_relation->linear_velocity) =\n\t\t\t    rotate_deriv(rot, in_out_relation->linear_velocity,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_ang_vel(flags)) {\n\t\t\tmap_vec3(in_out_relation->angular_velocity) =\n\t\t\t    rotate_deriv(rot, in_out_relation->angular_velocity,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_lin_acc(flags)) {\n\t\t\tmap_vec3(in_out_relation->linear_acceleration) =\n\t\t\t    rotate_deriv(rot,\n\t\t\t                 in_out_relation->linear_acceleration,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_ang_acc(flags)) {\n\t\t\tmap_vec3(in_out_relation->angular_acceleration) =\n\t\t\t    rotate_deriv(rot,\n\t\t\t                 in_out_relation->angular_acceleration,\n\t\t\t                 rotInverse);\n\t\t}\n\t}\n}\n\nstatic const struct xrt_space_relation BLANK_RELATION = {\n    XRT_SPACE_RELATION_BITMASK_ALL,\n    {{0.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 0.0f}},\n    {0, 0, 0},\n    {0, 0, 0},\n    {0, 0, 0},\n    {0, 0, 0},\n};\n\nextern \"C\" void\nmath_relation_reset(struct xrt_space_relation *out)\n{\n\t*out = BLANK_RELATION;\n}\n\nextern \"C\" void\nmath_relation_apply_offset(const struct xrt_pose *offset,\n                           struct xrt_space_relation *in_out_relation)\n{\n\tassert(offset != nullptr);\n\tassert(in_out_relation != nullptr);\n\n\t// No modifying the validity flags here.\n\ttransform_accumulate_pose(*offset, *in_out_relation, OFFSET);\n}\n\nvoid\naccumulate_transform(const struct xrt_pose *transform,\n                     struct xrt_space_relation *in_out_relation)\n{\n\tassert(transform != nullptr);\n\tassert(in_out_relation != nullptr);\n\n\t// No modifying the validity flags here.\n\ttransform_accumulate_pose(*transform, *in_out_relation, LEGACY);\n}\n\nextern \"C\" void\nmath_relation_accumulate_relation(\n    const struct xrt_space_relation *additional_relation,\n    struct xrt_space_relation *in_out_relation)\n{\n\tassert(additional_relation != NULL);\n\tassert(in_out_relation != NULL);\n\n\t// Update the flags.\n\txrt_space_relation_flags flags = (enum xrt_space_relation_flags)(\n\t    in_out_relation->relation_flags &\n\t    additional_relation->relation_flags);\n\tin_out_relation->relation_flags = flags;\n\n\tif (has_some_pose_component(flags)) {\n\t\t// First, just do the pose part (including rotating\n\t\t// derivatives, if applicable).\n\t\ttransform_accumulate_pose(\n\t\t    additional_relation->pose, *in_out_relation, LEGACY,\n\t\t    has_position(flags), has_orientation(flags));\n\t}\n\n\t// Then, accumulate the derivatives, if required.\n\tif (has_lin_vel(flags)) {\n\t\tmap_vec3(in_out_relation->linear_velocity) +=\n\t\t    map_vec3(additional_relation->linear_velocity);\n\t}\n\n\tif (has_ang_vel(flags)) {\n\t\tmap_vec3(in_out_relation->angular_velocity) +=\n\t\t    map_vec3(additional_relation->angular_velocity);\n\t}\n\n\tif (has_lin_acc(flags)) {\n\t\tmap_vec3(in_out_relation->linear_acceleration) +=\n\t\t    map_vec3(additional_relation->linear_acceleration);\n\t}\n\n\tif (has_ang_acc(flags)) {\n\t\tmap_vec3(in_out_relation->angular_acceleration) +=\n\t\t    map_vec3(additional_relation->angular_acceleration);\n\t}\n}\n\nextern \"C\" void\nmath_relation_openxr_locate(const struct xrt_pose *space_pose,\n                            const struct xrt_space_relation *relative_relation,\n                            const struct xrt_pose *base_space_pose,\n                            struct xrt_space_relation *result)\n{\n\tassert(space_pose != NULL);\n\tassert(relative_relation != NULL);\n\tassert(base_space_pose != NULL);\n\tassert(result != NULL);\n\n\t// Compilers are slightly better optimizing\n\t// if we copy the arguments in one go.\n\tconst auto bsp = *base_space_pose;\n\tconst auto spc = *space_pose;\n\tstruct xrt_space_relation accumulating_relation = BLANK_RELATION;\n\n\t// Apply the invert of the base space to identity.\n\tmath_pose_invert(&bsp, &accumulating_relation.pose);\n\n\t// Apply the pure relation between spaces.\n\tmath_relation_accumulate_relation(relative_relation,\n\t                                  &accumulating_relation);\n\n\t// Apply the space pose.\n\taccumulate_transform(&spc, &accumulating_relation);\n\n\t*result = accumulating_relation;\n}\n", "meta": {"hexsha": "a98c8c61e4369e2d2a5336b5223fb856c2c87cde", "size": 14151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_stars_repo_name": "ltstein/monado_integration", "max_stars_repo_head_hexsha": "4e5348e3dbf3bb9584eec9a761488274a7deddbd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-31T14:32:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T14:32:59.000Z", "max_issues_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_issues_repo_name": "patchedsoul/monado", "max_issues_repo_head_hexsha": "e6edaa9caf72d4caf1ea5968674d23845c7b975d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-09-08T18:32:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-22T00:13:29.000Z", "max_forks_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_forks_repo_name": "patchedsoul/monado", "max_forks_repo_head_hexsha": "e6edaa9caf72d4caf1ea5968674d23845c7b975d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-31T01:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:32:31.000Z", "avg_line_length": 26.2055555556, "max_line_length": 80, "alphanum_fraction": 0.677761289, "num_tokens": 3483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5622311053918222}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ACSC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acsc capabilities\n\n    inverse cosecant in radian: \\f$\\arcsin(1/x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acsc(x);\n    @endcode\n\n    @see acscd, acscpi, asin, asin, sin, rec\n\n  **/\n  Value acsc(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acsc.hpp>\n#include <boost/simd/function/simd/acsc.hpp>\n\n#endif\n", "meta": {"hexsha": "61017424707f3be8e12e7153db42cf3a1b81499d", "size": 995, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acsc.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/acsc.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/acsc.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.6136363636, "max_line_length": 100, "alphanum_fraction": 0.5688442211, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.562143099786269}}
{"text": "/**\n * \\file PanFilter.cpp\n */\n\n#include \"PanFilter.h\"\n\n#include <cmath>\n#include <cstdint>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  PanFilter<DataType_>::PanFilter()\n  :Parent(1, 2), law(PAN_LAWS::SINCOS_0_CENTER), pan(0)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  PanFilter<DataType_>::~PanFilter()\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void PanFilter<DataType_>::set_pan_law(PAN_LAWS law)\n  {\n    this->law = law;\n  }\n  \n  template<typename DataType_>\n  typename PanFilter<DataType_>::PAN_LAWS PanFilter<DataType_>::get_pan_law() const\n  {\n    return law;\n  }\n  \n  template<typename DataType_>\n  void PanFilter<DataType_>::set_pan(double pan)\n  {\n    if(pan < -1 || pan > 1)\n    {\n      throw std::out_of_range(\"Pan must be a value between -1 and 1\");\n    }\n    this->pan = pan;\n  }\n\n  template<typename DataType_>\n  double PanFilter<DataType_>::get_pan() const\n  {\n    return pan;\n  }\n\n  template<typename DataType_>\n  void PanFilter<DataType_>::process_impl(int64_t size) const\n  {\n    double left_coeff = 1;\n    double right_coeff = 1;\n    \n    switch(law)\n    {\n    case PAN_LAWS::SINCOS_0_CENTER:\n        left_coeff = std::sqrt(2) * std::cos((pan + 1) / 4 * boost::math::constants::pi<double>());\n        right_coeff = std::sqrt(2) * std::sin((pan + 1) / 4 * boost::math::constants::pi<double>());\n        break;\n      case PAN_LAWS::SINCOS_3_CENTER:\n        left_coeff = std::cos((pan + 1) / 4 * boost::math::constants::pi<double>());\n        right_coeff = std::sin((pan + 1) / 4 * boost::math::constants::pi<double>());\n        break;\n      case PAN_LAWS::SQUARE_0_CENTER:\n        left_coeff = std::sqrt(2) * std::sqrt((1 - pan) / 2);\n        right_coeff = std::sqrt(2) * std::sqrt((1 + pan) / 2);\n        break;\n      case PAN_LAWS::SQUARE_3_CENTER:\n        left_coeff = std::sqrt((1 - pan) / 2);\n        right_coeff = std::sqrt((1 + pan) / 2);\n        break;\n      case PAN_LAWS::LINEAR_TAPER:\n        left_coeff = (1 - pan) / 2;\n        right_coeff = (1 + pan) / 2;\n        break;\n      case PAN_LAWS::BALANCE:\n        left_coeff = pan < 0 ? 1 : 1 - pan;\n        right_coeff = pan > 0 ? 1 : 1 + pan;\n        break;\n    }\n    \n    const DataType* ATK_RESTRICT input = converted_inputs[0];\n    DataType* ATK_RESTRICT output0 = outputs[0];\n    DataType* ATK_RESTRICT output1 = outputs[1];\n    for(int64_t i = 0; i < size; ++i)\n    {\n      *(output0++) = static_cast<DataType>(left_coeff * *input);\n      *(output1++) = static_cast<DataType>(right_coeff * *(input++));\n    }\n    \n  }\n  \n  template class PanFilter<std::int16_t>;\n  template class PanFilter<std::int32_t>;\n  template class PanFilter<int64_t>;\n  template class PanFilter<float>;\n  template class PanFilter<double>;\n}\n", "meta": {"hexsha": "84b8041583bda207ebdfb3d0a84b95290e1cdb6f", "size": 2763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/PanFilter.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/PanFilter.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/PanFilter.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.0660377358, "max_line_length": 100, "alphanum_fraction": 0.6076728194, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5621337205562589}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>\n#include \"perception/behaviour/KinematicsCalibrationSkill.hpp\"\n#include \"types/RRCoord.hpp\"\n#include \"blackboard/Blackboard.hpp\"\n#include \"types/ActionCommand.hpp\"\n#include \"perception/kinematics/Kinematics.hpp\"\n#include \"perception/kinematics/Pose.hpp\"\n#include \"utils/Logger.hpp\"\n#include \"FADBAD++/fadiff.h\"\n\nfadbad::F<float> fadbadAtan2(fadbad::F<float> y, fadbad::F<float> x) {\n   fadbad::F<float> PI = 3.1415926535;\n   if (x == 0) {\n      if (y > 0) {\n         return PI / 2;\n      } else if (y < 0) {\n         return -PI / 2;\n      } else {\n         return 0;\n      }\n   } else if (x > 0) {\n      return fadbad::atan(y / x);\n   } else if (y >= 0 && x < 0) {\n      return fadbad::atan(y / x) + PI;\n   } else if (y < 0 && x < 0) {\n      return fadbad::atan(y / x) - PI;\n   } else {\n      return 0;\n   }\n}\n\nKinematicsCalibrationSkill::KinematicsCalibrationSkill(Blackboard *bb) : Adapter(bb) {\n   points.push_back(std::make_pair(-3020 + 1200, -2025));\n   points.push_back(std::make_pair(1200, -2025));\n   points.push_back(std::make_pair(1200, 0));\n   points.push_back(std::make_pair(1200, 2025));\n   points.push_back(std::make_pair(-3020 + 1200, 2025));\n   currentWaypoint = 0;\n   beenAtFrameFor = 0;\n   takenReading = false;\n   resetGradients();\n   alpha = MAX_ALPHA;\n   isTop = false;\n}\n\nKinematicsCalibrationSkill::~KinematicsCalibrationSkill() {}\n\n/* Input\n      - Joint Angles\n      - Offsets\n      - Perceived Location of Object in the Image\n\n   Output\n      - Euclidian distance between Perceived and Actual Position\n\n   Processing Steps\n      - Set up FADBAD variables for each of the offsets\n      - Feed 3 Inputs into Kinematics (May have to change some of the\n        the interfaces\n      - Deterime Euclidian distance\n*/\n\nfadbad::F<float> KinematicsCalibrationSkill::objectiveFunction(\n   Parameters<fadbad::F<float> > &parameters) {\n   Kinematics kinematics;\n   kinematics.sensorValues = readFrom(motion, sensors);\n   kinematics.parameters = parameters.cast<float>();\n\n   kinematics.updateDHChain();\n   Pose pose = kinematics.getPose();\n\n\n   /* Image to RR */\n   Point cc_p = readFrom(vision, balls[0].imageCoords);\n   std::pair<uint16_t, uint16_t>  cc(cc_p.x(), cc_p.y());\n\n   // calculate vector to pixel in camera space\n   boost::numeric::ublas::matrix<fadbad::F<float> > lOrigin, lOrigin2;\n   fadbad::F<float> imgCols = IMAGE_COLS;\n   fadbad::F<float> imgRows = IMAGE_ROWS;\n   fadbad::F<float> pixelSize = TOP_PIXEL_SIZE; // TODO: properly if used\n   fadbad::F<float> x = cc.first;\n   fadbad::F<float> y = cc.second;\n   lOrigin2 = vec4<fadbad::F<float> >(\n      (((imgCols) / 2.0 - x) *  pixelSize),\n      (((imgRows) / 2.0 - y) * pixelSize),\n      0,\n      1);\n\n   lOrigin = prod(\n      pose.getC2wTransform(),\n      lOrigin2);\n\n   boost::numeric::ublas::matrix<fadbad::F<float> > toPixel, toPixel2;\n   toPixel2 = vec4<fadbad::F<float> >(0, 0, FOCAL_LENGTH, 1);\n   toPixel = prod(\n      pose.getC2wTransform(),\n      toPixel2);\n\n   boost::numeric::ublas::matrix<fadbad::F<float> > cdir(toPixel - lOrigin);\n\n   fadbad::F<float> lambda = (35 - lOrigin(2, 0)) / (1.0 * cdir(2, 0));\n   boost::numeric::ublas::matrix<fadbad::F<float> > intercept;\n   intercept = vec4<fadbad::F<float> >(lOrigin(0, 0) + lambda * cdir(0, 0),\n                                       lOrigin(1, 0) + lambda * cdir(1, 0),\n                                       35,\n                                       1);\n   fadbad::F<float> distance, heading;\n   distance = fadbad::sqrt(fadbad::pow(intercept(0, 0), 2) +\n                           fadbad::pow(intercept(1, 0), 2));\n   heading = fadbadAtan2(intercept(1, 0), intercept(0, 0));\n   fadbad::F<float> px, py;\n   px = fadbad::cos(heading) * distance;\n   py = fadbad::sin(heading) * distance;\n\n   // find which point is closest to the one we see\n   float tx, ty;\n   tx = px.x();\n   ty = py.x();\n\n   int minIndex = 0;\n   float rx, ry;\n   rx = points[0].first;\n   ry = points[0].second;\n   float bDistance = sqrt(pow(rx - tx, 2) + pow(ry - ty, 2));\n   for (unsigned int i = 1; i < points.size(); i++) {\n      rx = points[i].first;\n      ry = points[i].second;\n      float cDistance = sqrt(pow(rx - tx, 2) + pow(ry - ty, 2));\n      if (cDistance < bDistance) {\n         bDistance = cDistance;\n         minIndex = i;\n      }\n   }\n\n   fadbad::F<float> bx, by;\n   bx = points[minIndex].first;\n   by = points[minIndex].second;\n   return fadbad::sqrt(fadbad::pow(bx - px, 2) +\n                       fadbad::pow(by - py, 2));\n}\n\nvoid KinematicsCalibrationSkill::updateGradient() {\n   // read in the parameters\n   Parameters<fadbad::F<float> > parameters;\n   parameters.cameraYawBottom = readFrom(kinematics,\n                                         parameters.cameraYawBottom);\n   parameters.cameraPitchBottom = readFrom(kinematics,\n                                           parameters.cameraPitchBottom);\n   parameters.cameraRollBottom = readFrom(kinematics,\n                                          parameters.cameraRollBottom);\n   parameters.cameraYawTop = readFrom(kinematics,\n                                      parameters.cameraYawTop);\n   parameters.cameraPitchTop = readFrom(kinematics,\n                                        parameters.cameraPitchTop);\n   parameters.cameraRollTop = readFrom(kinematics,\n                                       parameters.cameraRollTop);\n   parameters.bodyPitch = readFrom(kinematics, parameters.bodyPitch);\n   lastParams = parameters;\n\n   // set them to be derived\n   parameters.cameraYawBottom.diff(0, 7);\n   parameters.cameraPitchBottom.diff(1, 7);\n   parameters.cameraRollBottom.diff(2, 7);\n\n   parameters.cameraYawTop.diff(3, 7);\n   parameters.cameraPitchTop.diff(4, 7);\n   parameters.cameraRollTop.diff(5, 7);\n\n   parameters.bodyPitch.diff(6, 7);\n\n   // calculate objective function\n   fadbad::F<float> f = objectiveFunction(parameters);\n\n   value += f.x();\n   n += 1;\n   // store gradients\n   gradients.cameraYawBottom += f.d(0);\n   gradients.cameraPitchBottom += f.d(1);\n   gradients.cameraRollBottom += f.d(2);\n   gradients.cameraYawTop += f.d(3);\n   gradients.cameraPitchTop += f.d(4);\n   gradients.cameraRollTop += f.d(5);\n\n   gradients.bodyPitch += f.d(6);\n}\n\nBehaviourRequest KinematicsCalibrationSkill::execute() {\n   BehaviourRequest request;\n   if (readFrom(vision, balls).size() > 0 &&\n       beenAtFrameFor > STABALIZE_FRAMES) {\n      updateGradient();\n      takenReading = true;\n   }\n\n   // we have gathered point.size number of samples. update and get new batch\n   if (true && currentWaypoint == points.size() - 1 &&\n       takenReading == true) {\n      Parameters<fadbad::F<float> > parameters;\n      parameters.cameraYawBottom = readFrom(kinematics,\n                                            parameters.cameraYawBottom);\n      parameters.cameraPitchBottom = readFrom(kinematics,\n                                              parameters.cameraPitchBottom);\n      parameters.cameraRollBottom = readFrom(kinematics,\n                                             parameters.cameraRollBottom);\n      parameters.cameraYawTop = readFrom(kinematics,\n                                         parameters.cameraYawTop);\n      parameters.cameraPitchTop = readFrom(kinematics,\n                                           parameters.cameraPitchTop);\n      parameters.cameraRollTop = readFrom(kinematics,\n                                          parameters.cameraRollTop);\n      parameters.bodyPitch = readFrom(kinematics, parameters.bodyPitch);\n\n      // optimization algorithm goes here...\n      gradientDescent(parameters, gradients);\n\n      // write values back for next iteration\n      writeTo(kinematics, parameters.cameraYawBottom,\n              parameters.cameraYawBottom.x());\n      writeTo(kinematics, parameters.cameraPitchBottom,\n              parameters.cameraPitchBottom.x());\n      writeTo(kinematics, parameters.cameraRollBottom,\n              parameters.cameraRollBottom.x());\n      writeTo(kinematics, parameters.cameraYawTop,\n              parameters.cameraYawTop.x());\n      writeTo(kinematics, parameters.cameraPitchTop,\n              parameters.cameraPitchTop.x());\n      writeTo(kinematics, parameters.cameraRollTop,\n              parameters.cameraRollTop.x());\n\n      writeTo(kinematics, parameters.bodyPitch, parameters.bodyPitch.x());\n      resetGradients();\n      isTop = !isTop;\n   }\n\n   std::pair<float, float> cwp = points[currentWaypoint];\n   float angle = atan2(cwp.second, cwp.first);\n   if (abs(readFrom(motion, sensors).joints.angles[Joints::HeadYaw] - angle) < .01) {\n      beenAtFrameFor++;\n   }\n\n   if (takenReading == true) {\n      beenAtFrameFor = 0;\n      currentWaypoint = (currentWaypoint + 1) % points.size();\n      takenReading = false;\n   }\n\n   // move head to correct spot\n   if (isTop) {\n      request.actions.head = ActionCommand::Head(angle,\n                                                 DEG2RAD(5), false, 0.5f, 0.5f);\n   } else {\n      request.actions.head = ActionCommand::Head(angle,\n                                                 DEG2RAD(-25), false, 0.5f, 0.5f);\n   }\n   request.actions.body = ActionCommand::Body::STAND;\n\n   return request;\n}\n\nvoid KinematicsCalibrationSkill::resetGradients() {\n   n = 0;\n   value = 0;\n   gradients.cameraYawBottom = 0;\n   gradients.cameraPitchBottom = 0;\n   gradients.cameraRollBottom = 0;\n   gradients.cameraYawTop = 0;\n   gradients.cameraPitchTop = 0;\n   gradients.cameraRollTop = 0;\n\n   gradients.bodyPitch = 0;\n}\n\n\nbool KinematicsCalibrationSkill::gradientDescent(\n   Parameters<fadbad::F<float> > &parameters,\n   Parameters<fadbad::F<float> > gradients) {\n   parameters.cameraYawBottom -= alpha * gradients.cameraYawBottom / n;\n   parameters.cameraPitchBottom -= alpha * gradients.cameraPitchBottom / n;\n   parameters.cameraRollBottom -= alpha * gradients.cameraRollBottom / n;\n   parameters.cameraYawTop -= alpha * gradients.cameraYawTop / n;\n   parameters.cameraPitchTop -= alpha * gradients.cameraPitchTop / n;\n   parameters.cameraRollTop -= alpha * gradients.cameraRollTop / n;\n   parameters.bodyPitch -= alpha * gradients.bodyPitch / n;\n   alpha -= 0.0005;\n   if (alpha < MIN_ALPHA) {\n      alpha = MIN_ALPHA;\n   }\n\n   //static int t = 0;\n   std::cout << printParams(parameters) << std::endl;\n   std::cout << \"Gradients: \";\n   std::cout << gradients.cameraYawBottom.x() << \" \" <<\n   gradients.cameraPitchBottom.x() << \" \" <<\n   gradients.cameraRollBottom.x() << \" \" <<\n   gradients.bodyPitch.x() << std::endl;\n   std::cout << \"Value: \" << value / n << std::endl;\n   std::cout << \"Alpha: \" << alpha << std::endl;\n   std::cout << std::endl;\n\n   return false;\n}\n\nstd::string KinematicsCalibrationSkill::printParams(\n   Parameters<fadbad::F<float> > &parameters) {\n   std::stringstream s;\n   std::vector<std::pair<std::string, float> > plist;\n   plist.push_back(std::make_pair(\n                      \"cameraYawBottom\", parameters.cameraYawBottom.x()));\n   plist.push_back(std::make_pair(\n                      \"cameraPitchBottom\", parameters.cameraPitchBottom.x()));\n   plist.push_back(std::make_pair(\n                      \"cameraRollBottom\", parameters.cameraRollBottom.x()));\n   plist.push_back(std::make_pair(\n                      \"cameraYawTop\", parameters.cameraYawTop.x()));\n   plist.push_back(std::make_pair(\n                      \"cameraPitchTop\", parameters.cameraPitchTop.x()));\n   plist.push_back(std::make_pair(\n                      \"cameraRollTop\", parameters.cameraRollTop.x()));\n\n\n   plist.push_back(std::make_pair(\n                      \"bodyPitch\", parameters.bodyPitch.x()));\n\n   for (unsigned int i = 0; i < plist.size(); i++) {\n      s << plist[i].first << \"=\" << plist[i].second << std::endl;\n   }\n   return s.str();\n}\n\nstd::string KinematicsCalibrationSkill::printParams(\n   Parameters<float> &parameters) {\n   std::stringstream s;\n   std::vector<std::pair<std::string, float> > plist;\n   plist.push_back(std::make_pair(\n                      \"cameraYawBottom\", parameters.cameraYawBottom));\n   plist.push_back(std::make_pair(\n                      \"cameraPitchBottom\", parameters.cameraPitchBottom));\n   plist.push_back(std::make_pair(\n                      \"cameraRollBottom\", parameters.cameraRollBottom));\n   plist.push_back(std::make_pair(\n                      \"cameraYawTop\", parameters.cameraYawTop));\n   plist.push_back(std::make_pair(\n                      \"cameraPitchTop\", parameters.cameraPitchTop));\n   plist.push_back(std::make_pair(\n                      \"cameraRollTop\", parameters.cameraRollTop));\n\n   plist.push_back(std::make_pair(\n                      \"bodyPitch\", parameters.bodyPitch));\n   for (unsigned int i = 0; i < plist.size(); i++) {\n      s << plist[i].first << \"=\" << plist[i].second << std::endl;\n   }\n   return s.str();\n}\n\n", "meta": {"hexsha": "7d15f63c3e79efd103a8f252ab2ef09373b7472a", "size": 12865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/perception/behaviour/KinematicsCalibrationSkill.cpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_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/External/unsw/unsw/perception/behaviour/KinematicsCalibrationSkill.cpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_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/External/unsw/unsw/perception/behaviour/KinematicsCalibrationSkill.cpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["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.5386740331, "max_line_length": 86, "alphanum_fraction": 0.6160124368, "num_tokens": 3274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5619880803451744}}
{"text": "/**\n * \\file RIAAFilter.hxx\n */\n\n#include \"RIAAFilter.h\"\n#include <ATK/EQ/helpers.h>\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include <cmath>\n\nnamespace ATK\n{\n  template<typename DataType>\n  RIAACoefficients<DataType>::RIAACoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template<typename T>\n  void generate_RIAA_coeffs(EQUtilities::ZPK<T>& zpk, gsl::index input_sampling_rate)\n  {\n    auto pi = boost::math::constants::pi<T>();\n    T t1 = 1 / (input_sampling_rate * std::tan(pi / (75e-6 * input_sampling_rate)));\n    T t2 = 1 / (input_sampling_rate * std::tan(pi / (318e-6 * input_sampling_rate)));\n    T t3 = 1 / (input_sampling_rate * std::tan(pi / (3180e-6 * input_sampling_rate)));\n    \n    zpk.k = 318e-6/75e-6 * t2/(t1*t3);\n    zpk.z.push_back(-1/t2);\n    zpk.p.push_back(-1/t1);\n    zpk.p.push_back(-1/t3);\n    \n    EQUtilities::zpk_bilinear(input_sampling_rate, zpk);\n  }\n  \n  template <typename DataType>\n  void RIAACoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    EQUtilities::ZPK<CoeffDataType> zpk;\n\n    boost::math::tools::polynomial<CoeffDataType> b{ 1 };\n    boost::math::tools::polynomial<CoeffDataType> a{ 1 };\n\n    generate_RIAA_coeffs(zpk, input_sampling_rate);\n    EQUtilities::zpk2ba(zpk, b, a);\n    \n    auto in_size = std::min(in_order + 1, static_cast<gsl::index>(b.size()));\n    for (gsl::index i = 0; i < in_size; ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    auto out_size = std::min(out_order, static_cast<gsl::index>(a.size() - 1));\n    for (gsl::index i = 0; i < out_size; ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n\n  template<typename DataType>\n  InverseRIAACoefficients<DataType>::InverseRIAACoefficients(gsl::index nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void InverseRIAACoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    EQUtilities::ZPK<CoeffDataType> zpk;\n    \n    boost::math::tools::polynomial<CoeffDataType> b{ 1 };\n    boost::math::tools::polynomial<CoeffDataType> a{ 1 };\n    \n    generate_RIAA_coeffs(zpk, input_sampling_rate);\n    zpk.z.back() = -.8;\n    EQUtilities::zpk2ba(zpk, b, a);\n    \n    auto in_size = std::min(in_order + 1, static_cast<gsl::index>(a.size()));\n    for (gsl::index i = 0; i < in_size; ++i)\n    {\n      coefficients_in[i] = a[i] / b[b.size() - 1];\n    }\n    auto out_size = std::min(out_order, static_cast<gsl::index>(b.size() - 1));\n    for (gsl::index i = 0; i < out_size; ++i)\n    {\n      coefficients_out[i] = -b[i] / b[b.size() - 1];\n    }\n  }\n}\n", "meta": {"hexsha": "e0ce8f352dfeb0a98401490406d8c458135359c9", "size": 2717, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/RIAAFilter.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/RIAAFilter.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/RIAAFilter.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": 27.4444444444, "max_line_length": 86, "alphanum_fraction": 0.6334192124, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5619880717931885}}
{"text": "#include <iostream>\n#include <vector>\n#include <chrono>\n\n//#define _RANSAC_STATS_ 1\n#ifdef _RANSAC_STATS_\n#include <limits>\n#endif\n\n#include <Eigen/src/Core/util/DisableStupidWarnings.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/calib3d.hpp>\n\n#include <opencv2/core/eigen.hpp>\n\n#include \"pose3d.h\"\n#include \"Optimization.h\"\n#include \"Ransac.hh\"\n\n#define USE_ROTATION_MATRIX\n//#define USE_QUATERNION\n\n#define USE_SVD\n//#define USE_QR\n\nnamespace pose3d\n{\n   inline double mrhs1(double X_1, double Y_1, double Z_1, double y_1, double r_10, double r_11, double r_12,\n                       double r_20, double r_21, double r_22)\n//---------------------------------------------------------------------------------------------------------\n   {\n      return X_1 * r_10 - X_1 * r_20 * y_1 + Y_1 * r_11 - Y_1 * r_21 * y_1 + Z_1 * r_12 - Z_1 * r_22 * y_1;\n   }\n\n   inline double mrhs2(double X_1, double Y_1, double Z_1, double x_1,\n                       double r_00, double r_01, double r_02, double r_20, double r_21, double r_22)\n//------------------------------------------------------------------------------------------------\n   {\n      return -X_1 * r_00 + X_1 * r_20 * x_1 - Y_1 * r_01 + Y_1 * r_21 * x_1 - Z_1 * r_02 + Z_1 * r_22 * x_1;\n   }\n\n   inline double mrhs3(double X_1, double Y_1, double Z_1, double x_1, double y_1,\n                       double r_00, double r_01, double r_02, double r_10, double r_11, double r_12)\n//-----------------------------------------------------------------------------------------------\n   {\n      return X_1 * r_00 * y_1 - X_1 * r_10 * x_1 + Y_1 * r_01 * y_1 - Y_1 * r_11 * x_1 + Z_1 * r_02 * y_1 -\n             Z_1 * r_12 * x_1;\n   }\n\n   inline double qrhs1(double Qw, double Qx, double Qy, double Qz, double X_1, double Y_1, double Z_1, double y_1)\n//-------------------------------------------------------------------------------------------------------------\n   {\n      double Qw2 = Qw * Qw, Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, Qwx = Qw * Qx;\n      return -Qw2 * Z_1 * y_1 - 2 * Qwx * Y_1 * y_1 + 2 * Qw * Qy * X_1 * y_1 + Qx2 * Z_1 * y_1 -\n             2 * Qx * Qz * X_1 * y_1 +\n             Qy2 * Z_1 * y_1 - 2 * Qy * Qz * Y_1 * y_1 - Qz2 * Z_1 * y_1 + 2 * X_1 * (Qw * Qz + Qx * Qy) + Y_1 * (Qw2 -\n                                                                                                                  Qx2 +\n                                                                                                                  Qy2 -\n                                                                                                                  Qz2) -\n             2 * Z_1 * (Qwx - Qy * Qz);\n   }\n\n   inline double qrhs2(double Qw, double Qx, double Qy, double Qz, double X_1, double Y_1, double Z_1, double x_1)\n//------------------------------------------------------------------------------------------------------------\n   {\n      double Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, Qwy = Qw * Qy;\n      return Qw * Qw * Z_1 * x_1 + 2 * Qw * Qx * Y_1 * x_1 - 2 * Qwy * X_1 * x_1 - Qx2 * Z_1 * x_1 +\n             2 * Qx * Qz * X_1 * x_1 -\n             Qy2 * Z_1 * x_1 + 2 * Qy * Qz * Y_1 * x_1 + Qz2 * Z_1 * x_1 - X_1 * (Qw * Qw + Qx2 -\n                                                                                  Qy2 - Qz2) -\n             2 * Y_1 * (-Qw * Qz + Qx * Qy) - 2 * Z_1 * (Qwy + Qx * Qz);\n   }\n\n   inline double\n   qrhs3(double Qw, double Qx, double Qy, double Qz, double X_1, double Y_1, double Z_1, double x_1, double y_1)\n//-----------------------------------------------------------------------------------------------------------------\n   {\n      double Qw2 = Qw * Qw, Qx2 = Qx * Qx, Qy2 = Qy * Qy, Qz2 = Qz * Qz, Qwz = Qw * Qz;\n      return Qw2 * X_1 * y_1 - Qw2 * Y_1 * x_1 + 2 * Qw * Qx * Z_1 * x_1 + 2 * Qw * Qy * Z_1 * y_1 -\n             2 * Qwz * X_1 * x_1 -\n             2 * Qwz * Y_1 * y_1 + Qx2 * X_1 * y_1 + Qx2 * Y_1 * x_1 - 2 * Qx * Qy * X_1 * x_1 +\n             2 * Qx * Qy * Y_1 * y_1 +\n             2 * Qx * Qz * Z_1 * y_1 - Qy2 * X_1 * y_1 - Qy2 * Y_1 * x_1 - 2 * Qy * Qz * Z_1 * x_1 - Qz2 * X_1 * y_1 +\n             Qz2 * Y_1 * x_1;\n   }\n\n   inline double dotg(double X_1, double Y_1, double Z_1, double X_2, double Y_2, double Z_2,\n                      double g_x, double g_y, double g_z, const Eigen::Matrix3d& R)\n   {\n      return g_x * (X_1 * R(0, 0) - X_2 * R(0, 0) + Y_1 * R(0, 1) - Y_2 * R(0, 1) + Z_1 * R(0, 2) - Z_2 * R(0, 2)) +\n             g_y * (X_1 * R(1, 0) - X_2 * R(1, 0) +\n                    Y_1 * R(1, 1) - Y_2 * R(1, 1) + Z_1 * R(1, 2) - Z_2 * R(1, 2)) +\n             g_z * (X_1 * R(2, 0) - X_2 * R(2, 0) + Y_1 * R(2, 1) - Y_2 * R(2, 1) +\n                    Z_1 * R(2, 2) - Z_2 * R(2, 2));\n   }\n\n   inline Eigen::Quaterniond rotation(const Eigen::Vector3d &from, const Eigen::Vector3d &to,\n                                      const Eigen::Vector3d &fallbackAxis = Eigen::Vector3d(0, 0, 0))\n   //-----------------------------------------------------------------------------------------------\n   {\n      Eigen::Quaterniond q;\n      Eigen::Vector3d v0 = from;\n      Eigen::Vector3d v1 = to;\n      v0.normalize();\n      v1.normalize();\n\n      double d = v0.dot(v1);\n      if (d >= 1.0f)\n         return Eigen::Quaterniond(1, 0, 0, 0);\n\n      if (d < (1e-6f - 1.0f))\n      {\n         if (fallbackAxis != Eigen::Vector3d(0, 0, 0))\n            q = Eigen::AngleAxis<double>(PI, fallbackAxis);\n         else\n         {\n            // Generate an axis\n            Eigen::Vector3d axis = Eigen::Vector3d(1, 0, 0).cross(from);\n            if (axis.norm() < 0.000000001) // pick another if colinear\n               axis = Eigen::Vector3d(0, 1, 0).cross(from);\n            axis.normalize();\n            q = Eigen::AngleAxis<double>(PI, axis);\n         }\n      }\n      else\n      {\n         double s = sqrt((1 + d) * 2);\n         double invs = 1 / s;\n\n         Eigen::Vector3d c = v0.cross(v1);\n\n         q.x() = c.x() * invs;\n         q.y() = c.y() * invs;\n         q.z() = c.z() * invs;\n         q.w() = s * 0.5f;\n         q.normalize();\n      }\n      return q;\n   }\n\n#ifdef USE_ROTATION_MATRIX\n   bool pose(const std::vector<std::pair<cv::Point3d, cv::Point2d>>& pts,\n             const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n             const Eigen::Matrix3d& KI, Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n//-----------------------------------------------------------------------------------------------------------\n   {\n      const size_t m = pts.size();\n//      if (m > 3)\n//      {\n//         std::cerr << \"Use pose_ransac for more than 3 points\" << std::endl;\n//         // pose_ransac(world_pts, image_pts, train_g, query_g, KI, Q, translation);\n//         return false;\n//      }\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n//   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n\n      Eigen::Matrix3d R = Q.toRotationMatrix();\n      const cv::Point3d &world_pt0 = pts[0].first, &world_pt1 = pts[1].first,\n                        &world_pt2 = pts[2].first;\n      const cv::Point2d &image_pt0 = pts[0].second, &image_pt1 = pts[1].second,\n                        &image_pt2 = pts[2].second;\n      Eigen::Vector3d query_ray1 = KI*Eigen::Vector3d(image_pt0.x, image_pt0.y, 1),\n                      query_ray2 = KI*Eigen::Vector3d(image_pt1.x, image_pt1.y, 1),\n                      query_ray3 = KI*Eigen::Vector3d(image_pt2.x, image_pt2.y, 1);\n      double Xt1 = world_pt0.x, Yt1 = world_pt0.y, Zt1 = world_pt0.z,\n             Xt2 = world_pt1.x, Yt2 = world_pt1.y, Zt2 = world_pt1.z,\n             Xt3 = world_pt2.x, Yt3 = world_pt2.y, Zt3 = world_pt2.z,\n             xq1 = query_ray1[0], yq1 = query_ray1[1], xq2 = query_ray2[0], yq2 = query_ray2[1],\n             xq3 = query_ray3[0], yq3 = query_ray3[1];\n\n      Eigen::Matrix<double, 9, 3> A;\n      Eigen::Matrix<double, 9, 1> b;\n//   Eigen::Matrix<double, 6, 3> A;\n//   Eigen::Matrix<double, 6, 1> b;\n      A << 0, -1, yq1,\n            1, 0, -xq1,\n            -yq1, xq1, 0,\n            0, -1, yq2,\n            1, 0, -xq2,\n            -yq2, xq2, 0,\n            0, -1, yq3,\n            1, 0, -xq3,\n            -yq3, xq3, 0;\n      double r_00 = R(0, 0), r_01 = R(0, 1), r_02 = R(0, 2),\n             r_10 = R(1, 0), r_11 = R(1, 1), r_12 = R(1, 2),\n             r_20 = R(2, 0), r_21 = R(2, 1), r_22 = R(2, 2);\n      b <<  mrhs1(Xt1, Yt1, Zt1, yq1, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt1, Yt1, Zt1, xq1, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt1, Yt1, Zt1, xq1, yq1, r_00, r_01, r_02, r_10, r_11, r_12),\n            mrhs1(Xt2, Yt2, Zt2, yq2, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt2, Yt2, Zt2, xq2, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt2, Yt2, Zt2, xq2, yq2, r_00, r_01, r_02, r_10, r_11, r_12),\n            mrhs1(Xt3, Yt3, Zt3, yq3, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt3, Yt3, Zt3, xq3, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt3, Yt3, Zt3, xq3, yq3, r_00, r_01, r_02, r_10, r_11, r_12);\n//      std::cout << A << std::endl << \"Rank \" << A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).rank() << std::endl;\n#ifdef USE_SVD\n      translation = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n#endif\n#ifdef USE_QR\n      Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 9, 3>> MQR(A);\n      translation = MQR.solve(b);\n#endif\n\n//   Eigen::MatrixXd A(m*3, 3);\n//   Eigen::VectorXd b(m*3);\n//    for (size_t row=0, ri=0; row<m; row++)\n//    {\n//       if (row == 3)\n//       {\n//          std::cout << row << \" \" << ri << std::endl;\n//          break;\n//       }\n\n//       cv::Point2d& pt = const_cast<cv::Point2d &>(image_pts[row]);\n//       Eigen::Vector3d ray = KI*Eigen::Vector3d(pt.x, pt.y, 1);\n//       const double Xt = world_pts[row].x, Yt = world_pts[row].y, Zt = world_pts[row].z, xq = ray[0], yq = ray[1];\n\n//       A(ri, 0) = 0;\n//       A(ri, 1) = -1;\n//       A(ri, 2) = yq;\n//       b[ri++] = mrhs1(Xt, Yt, Zt, yq, r_10, r_11,  r_12, r_20, r_21, r_22);\n\n//       A(ri, 0) = 1.0;\n//       A(ri, 1) = 0.0;\n//       A(ri, 2) = -xq;\n//       b[ri++] = mrhs2(Xt, Yt, Zt, xq, r_00, r_01, r_02, r_20, r_21, r_22);\n\n//       A(ri, 0) = -yq;\n//       A(ri, 1) = xq;\n//       A(ri, 2) = 0;\n//       b[ri++] = mrhs3(Xt, Yt, Zt, xq, yq, r_00, r_01, r_02, r_10, r_11, r_12);\n//    }\n// //   std::cout << A << std::endl << b << std::endl;\n//    translation = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n      return true;\n   }\n\n#endif\n\n#ifdef USE_QUATERNION\n   bool pose(const std::vector<std::pair<cv::Point3d, cv::Point2d>>& pts,\n             const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n             const Eigen::Matrix3d& KI, Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n   //-----------------------------------------------------------------------------------------------------------\n   {\n      const size_t m = pts.size();\n      if (m > 3)\n      {\n         std::cout << \"Use pose_ransac for more than 3 points\" << std::endl;\n         return false;\n      }\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n   //   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n      std::vector<cv::Point3d> world_pts;\n      std::vector<cv::Point2d> image_pts;\n      for (const std::pair<cv::Point3d, cv::Point2d>& pp : pts)\n      {\n         const cv::Point3d &wpt = pp.first;\n         const cv::Point2d &ipt = pp.second;\n         world_pts.emplace_back(wpt.x, wpt.y, wpt.z);\n         image_pts.emplace_back(ipt.x, ipt.y);\n      }\n      pose3d::pose_translation(world_pts, image_pts, KI, Q, translation);\n   /*\n      Eigen::MatrixXd A(m*3, 3);\n      Eigen::VectorXd b(m*3);\n   //   Eigen::MatrixXd A(m*2, 3);\n   //   Eigen::VectorXd b(m*2);\n      const double Qw = Q.w(), Qx = Q.x(), Qy = Q.y(), Qz = Q.z();\n      for (size_t row=0, ri=0; row<m; row++)\n      {\n         cv::Point2d& pt = const_cast<cv::Point2d &>(image_pts[row]);\n         Eigen::Vector3d ray = KI*Eigen::Vector3d(pt.x, pt.y, 1);\n         const double Xt = world_pts[row].x, Yt = world_pts[row].y, Zt = world_pts[row].z, xq = ray[0], yq = ray[1];\n\n         A(ri, 0) = 0;\n         A(ri, 1) = -1;\n         A(ri, 2) = yq;\n         b[ri++] = qrhs1(Qw, Qx, Qy, Qz, Xt, Yt, Zt, xq);\n\n         A(ri, 0) = 1.0;\n         A(ri, 1) = 0.0;\n         A(ri, 2) = -xq;\n         b[ri++] = qrhs2(Qw, Qx, Qy, Qz, Xt, Yt, Zt, xq);\n\n         A(ri, 0) = -yq;\n         A(ri, 1) = xq;\n         A(ri, 2) = 0;\n         b[ri++] = qrhs3(Qw, Qx, Qy, Qz, Xt, Yt, Zt, xq, yq);\n      }\n      translation = A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n   */\n      return true;\n   }\n#endif\n\n   void refine(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& image_pts,\n               const Eigen::Matrix3d& K, Eigen::Quaterniond& Q, Eigen::Vector3d& translation, int& iterations)\n//---------------------------------------------------------------------------------------------------\n   {\n      translation_levenberg_marquardt3d(world_pts, image_pts, K, Q, translation, iterations);\n   }\n\n   double pose_ransac(const std::vector<std::pair<cv::Point3d, cv::Point2d>>& pts,\n                      const Eigen::Vector3d& train_g, const Eigen::Vector3d query_g,\n                      const Eigen::Matrix3d& KI, Eigen::Quaterniond& Q, Eigen::Vector3d& translation,\n                      void *RANSAC_params, int samples)\n//----------------------------------------------------------------------------------------------------------\n   {\n      if (RANSAC_params == nullptr) throw std::logic_error(\"pose3d::pose_ransac: RANSAC params are null\");\n      Eigen::Vector3d train_gravity(train_g), query_gravity(query_g);\n      train_gravity.normalize();\n      query_gravity.normalize();\n      //   Q = rotation(train_gravity, query_gravity); // camera to model\n      Q = rotation(query_gravity, train_gravity); // model to camera\n      double confidence = -1;\n#ifdef USE_THEIA_RANSAC\n      Grav3DRansacEstimator estimator(KI, Q, samples);\n      theia::RansacParameters* parameters = static_cast<theia::RansacParameters*>(RANSAC_params);\n      theia::RansacSummary summary;\n      std::unique_ptr<theia::SampleConsensusEstimator<Grav3DRansacEstimator>> ransac =\n            theia::CreateAndInitializeRansacVariant(theia::RansacType::RANSAC, *parameters, estimator);\n      if (ransac)\n      {\n         GravPoseRansacModel best_model;\n         ransac->Estimate(pts, &best_model, &summary);\n         confidence = summary.confidence;\n         if (confidence > 0)\n         {\n            Q = best_model.rotation;\n            translation = best_model.translation;\n         }\n      }\n#else\n      templransac::RANSACParams* parameters = static_cast<templransac::RANSACParams*>(RANSAC_params);\n      Grav3DRansacEstimator estimator(KI, Q);\n      Grav3DRansacData data(pts);\n      std::vector<std::pair<double, GravPoseRansacModel> > results;\n      std::vector<std::vector<size_t>> inlier_indices;\n      std::stringstream errs;\n      confidence = templransac::RANSAC(*parameters, estimator, data, pts.size(), samples, 1, results,\n                                        inlier_indices, &errs);\n      if (confidence > 0)\n      {\n         GravPoseRansacModel& model = results[0].second;\n         translation = model.translation;\n      }\n#endif\n      return confidence;\n   }\n\n   //Called by RANSAC estimation\n   void pose_translation(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& query_image_pts,\n                         const Eigen::Matrix3d& KI, const Eigen::Matrix3d& R, Eigen::Vector3d& translation)\n   //-----------------------------------------------------------------------------------------------------------\n   {\n      const cv::Point2d &qpt0 = query_image_pts[0], &qpt1 = query_image_pts[1], &qpt2 = query_image_pts[2];\n      Eigen::Vector3d query_ray1 = KI*Eigen::Vector3d(qpt0.x, qpt0.y, 1),\n            query_ray2 = KI*Eigen::Vector3d(qpt1.x, qpt1.y, 1),\n            query_ray3 = KI*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double Xt1 = world_pts[0].x, Yt1 = world_pts[0].y, Zt1 = world_pts[0].z,\n            Xt2 = world_pts[1].x, Yt2 = world_pts[1].y, Zt2 = world_pts[1].z,\n            Xt3 = world_pts[2].x, Yt3 = world_pts[2].y, Zt3 = world_pts[2].z,\n            xq1 = query_ray1[0], yq1 = query_ray1[1], xq2 = query_ray2[0], yq2 = query_ray2[1],\n            xq3 = query_ray3[0], yq3 = query_ray3[1];\n\n      Eigen::Matrix<double, 9, 3> A;\n      Eigen::Matrix<double, 9, 1> b;\n//   Eigen::Matrix<double, 6, 3> A;\n//   Eigen::Matrix<double, 6, 1> b;\n      A << 0, -1, yq1,\n            1, 0, -xq1,\n            -yq1, xq1, 0,\n            0, -1, yq2,\n            1, 0, -xq2,\n            -yq2, xq2, 0,\n            0, -1, yq3,\n            1, 0, -xq3,\n            -yq3, xq3, 0;\n      double r_00 = R(0, 0), r_01 = R(0, 1), r_02 = R(0, 2),\n            r_10 = R(1, 0), r_11 = R(1, 1), r_12 = R(1, 2),\n            r_20 = R(2, 0), r_21 = R(2, 1), r_22 = R(2, 2);\n      b << mrhs1(Xt1, Yt1, Zt1, yq1, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt1, Yt1, Zt1, xq1, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt1, Yt1, Zt1, xq1, yq1, r_00, r_01, r_02, r_10, r_11, r_12),\n            mrhs1(Xt2, Yt2, Zt2, yq2, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt2, Yt2, Zt2, xq2, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt2, Yt2, Zt2, xq2, yq2, r_00, r_01, r_02, r_10, r_11, r_12),\n            mrhs1(Xt3, Yt3, Zt3, yq3, r_10, r_11, r_12, r_20, r_21, r_22),\n            mrhs2(Xt3, Yt3, Zt3, xq3, r_00, r_01, r_02, r_20, r_21, r_22),\n            mrhs3(Xt3, Yt3, Zt3, xq3, yq3, r_00, r_01, r_02, r_10, r_11, r_12);\n//   std::cout << \"Rank \" << A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).rank() << std::endl;\n#ifdef USE_SVD\n      translation = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n#endif\n#ifdef USE_QR\n      Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 9, 3>> MQR(A);\n      translation = MQR.solve(b);\n#endif\n   }\n\n   //Called by RANSAC estimation\n   void pose_translation(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& query_image_pts,\n                         const Eigen::Matrix3d& KI, const Eigen::Quaterniond& Q, Eigen::Vector3d& translation)\n//-----------------------------------------------------------------------------------------------------------\n   {\n      const cv::Point2d &qpt0 = query_image_pts[0], &qpt1 = query_image_pts[1], &qpt2 = query_image_pts[2];\n      Eigen::Vector3d query_ray1 = KI*Eigen::Vector3d(qpt0.x, qpt0.y, 1),\n            query_ray2 = KI*Eigen::Vector3d(qpt1.x, qpt1.y, 1),\n            query_ray3 = KI*Eigen::Vector3d(qpt2.x, qpt2.y, 1);\n      double Xt1 = world_pts[0].x, Yt1 = world_pts[0].y, Zt1 = world_pts[0].z,\n            Xt2 = world_pts[1].x, Yt2 = world_pts[1].y, Zt2 = world_pts[1].z,\n            Xt3 = world_pts[2].x, Yt3 = world_pts[2].y, Zt3 = world_pts[2].z,\n            xq1 = query_ray1[0], yq1 = query_ray1[1], xq2 = query_ray2[0], yq2 = query_ray2[1],\n            xq3 = query_ray3[0], yq3 = query_ray3[1];\n\n      Eigen::Matrix<double, 9, 3> A;\n      Eigen::Matrix<double, 9, 1> b;\n//   Eigen::Matrix<double, 6, 3> A;\n//   Eigen::Matrix<double, 6, 1> b;\n      A << 0, -1, yq1,\n            1, 0, -xq1,\n            -yq1, xq1, 0,\n            0, -1, yq2,\n            1, 0, -xq2,\n            -yq2, xq2, 0,\n            0, -1, yq3,\n            1, 0, -xq3,\n            -yq3, xq3, 0;\n\n      double Qw = Q.w(), Qx = Q.x(), Qy = Q.y(), Qz = Q.z();\n      b << qrhs1(Qw, Qx, Qy, Qz, Xt1, Yt1, Zt1, yq1),\n            qrhs2(Qw, Qx, Qy, Qz, Xt1, Yt1, Zt1, xq1),\n            qrhs3(Qw, Qx, Qy, Qz, Xt1, Yt1, Zt1, xq1, yq1),\n            qrhs1(Qw, Qx, Qy, Qz, Xt2, Yt2, Zt2, yq2),\n            qrhs2(Qw, Qx, Qy, Qz, Xt2, Yt2, Zt2, xq2),\n            qrhs3(Qw, Qx, Qy, Qz, Xt2, Yt2, Zt2, xq2, yq2),\n            qrhs1(Qw, Qx, Qy, Qz, Xt3, Yt3, Zt3, yq3),\n            qrhs2(Qw, Qx, Qy, Qz, Xt3, Yt3, Zt3, xq3),\n            qrhs3(Qw, Qx, Qy, Qz, Xt3, Yt3, Zt3, xq3, yq3);\n\n//   std::cout << \"Rank \" << A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).rank() << std::endl;\n#ifdef USE_SVD\n      translation = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n#endif\n#ifdef USE_QR\n      Eigen::ColPivHouseholderQR<Eigen::Matrix<double, 9, 3>> MQR(A);\n      translation = MQR.solve(b);\n#endif\n   }\n}", "meta": {"hexsha": "ba60506097cfa50db588524ce3e71b2403680653", "size": 20766, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose/pose3d.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/pose3d.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/pose3d.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": 44.7543103448, "max_line_length": 125, "alphanum_fraction": 0.4979293075, "num_tokens": 7483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.5619644895029547}}
{"text": "/*\n * Triangle.hpp\n *\n *  Created on: 20/apr/2013\n *      Author: alessandro\n */\n\n#ifndef TRIANGLE_HPP_\n#define TRIANGLE_HPP_\n\n#include <opencv2/core/core.hpp>\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n\nusing namespace cv;\n\n/*\n * Class Triangle\n */\nclass Triangle {\nprivate:\n\tPoint p1;\n\tPoint p2;\n\tPoint p3;\n\npublic:\n\t/*\n\t * Constructors\n\t */\n\tTriangle() {\n\t}\n\n\tTriangle(Point _p1, Point _p2, Point _p3) :\n\t\tp1(_p1), p2(_p2), p3(_p3) {\n\t}\n\n\t/*\n\t * Getters and Setters\n\t */\n\tPoint getP1() const {\n\t\treturn p1;\n\t}\n\n\tPoint getP2() const {\n\t\treturn p2;\n\t}\n\n\tPoint getP3() const {\n\t\treturn p3;\n\t}\n\n\tvoid setP1(Point _p1) {\n\t\tp1 = _p1;\n\t}\n\n\tvoid setP2(Point _p2) {\n\t\tp2 = _p2;\n\t}\n\n\tvoid setP3(Point _p3) {\n\t\tp3 = _p3;\n\t}\n\n\t/*\n\t * Area given 2D-points\n\t * From \"http://www.mathopenref.com/coordtrianglearea.html\"\n\t */\n\tdouble getArea() const {\n\t\tdouble area;\n\t\tarea = p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y);\n\t\tarea = fabs(area / 2);\n\n\t\treturn area;\n\t}\n};\n\n#endif /* TRIANGLE_HPP_ */\n", "meta": {"hexsha": "c83713236ca7f35b89c2094c31f349b3a79326ad", "size": 1016, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "TBDAnnotation/src/Model/Triangle.hpp", "max_stars_repo_name": "marcorighini/tbdannotation", "max_stars_repo_head_hexsha": "f22d395fce5c6c1007177623b0a0c60f7fcb9d4f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-13T10:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-13T10:49:43.000Z", "max_issues_repo_path": "TBDAnnotation/src/Model/Triangle.hpp", "max_issues_repo_name": "marcorighini/tbdannotation", "max_issues_repo_head_hexsha": "f22d395fce5c6c1007177623b0a0c60f7fcb9d4f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TBDAnnotation/src/Model/Triangle.hpp", "max_forks_repo_name": "marcorighini/tbdannotation", "max_forks_repo_head_hexsha": "f22d395fce5c6c1007177623b0a0c60f7fcb9d4f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.0256410256, "max_line_length": 76, "alphanum_fraction": 0.5984251969, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.8152324960856175, "lm_q1q2_score": 0.5619443385378353}}
{"text": "/* Boost libs/numeric/odeint/examples/simple1d.cpp\n\n Copyright 2012-2013 Mario Mulansky\n Copyright 2012 Karsten Ahnert\n\n example for a simple one-dimensional 1st order ODE\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/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n\n/* we solve the simple ODE x' = 3/(2t^2) + x/(2t)\n * with initial condition x(1) = 0.\n * Analytic solution is x(t) = sqrt(t) - 1/t\n */\n\nvoid rhs( const double x , double &dxdt , const double t )\n{\n    dxdt = 3.0/(2.0*t*t) + x/(2.0*t);\n}\n\nvoid write_cout( const double &x , const double t )\n{\n    cout << t << '\\t' << x << endl;\n}\n\n// state_type = double\ntypedef runge_kutta_dopri5< double > stepper_type;\n\nint main()\n{\n    double x = 0.0; //initial value x(1) = 0\n    // use dopri5 with stepsize control and allowed errors 10^-12, integrate t=1...10\n    integrate_adaptive( make_controlled( 1E-12 , 1E-12 , stepper_type() ) , rhs , x , 1.0 , 10.0 , 0.1 , write_cout );\n}\n", "meta": {"hexsha": "3a8dfa04fc8f83c41dabf2a9f562763f47405825", "size": 1119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/simple1d.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/simple1d.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/simple1d.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": 24.8666666667, "max_line_length": 118, "alphanum_fraction": 0.6747095621, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5617220716224449}}
{"text": "#include <string>\n#include <unordered_map>\n#include <Eigen/Dense>\n#include <cmath>\n#include \"../include/optimizer.h\"\n\nnamespace MyDL\n{\n\n    // ------------------------------------------------------------\n    //                  SGD\n    // ------------------------------------------------------------\n    SGD::SGD(double learning_rate): _learning_rate(learning_rate)\n    {\n    }\n\n    void SGD::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)\n    {\n        for (auto grad : grads)\n        {\n            params[grad.first] -= _learning_rate * grad.second;\n        }\n    }\n\n    void SGD::update(unordered_map<string, shared_ptr<MatrixXd>> & params, unordered_map<string, MatrixXd> &grads)\n    {\n        for (auto grad : grads)\n        {\n            *(params[grad.first]) -= _learning_rate * grad.second;\n        }\n    }\n\n    // ------------------------------------------------------------\n    //                  Momentum\n    // ------------------------------------------------------------\n    Momentum::Momentum(double learning_rate, double momentum) : _learning_rate(learning_rate), _momentum(momentum)\n    {\n    }\n\n    void Momentum::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)\n    {\n        if (_v.empty())\n        {\n            for (auto param : params)\n            {\n                _v[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            _v[key] = _momentum * _v[key] - _learning_rate * grads[key];\n            params[key] += _v[key];\n        }\n    }\n\n    void Momentum::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)\n    {\n        if (_v.empty())\n        {\n            for (auto param : params)\n            {\n                MatrixXd tmp_mat = *(param.second);\n                _v[param.first] = MatrixXd::Zero(tmp_mat.rows(), tmp_mat.cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            _v[key] = _momentum * _v[key] - _learning_rate * grads[key];\n            *(params[key]) += _v[key];\n        }\n    }\n\n    // ------------------------------------------------------------\n    //                  AdaGrad\n    // ------------------------------------------------------------\n    AdaGrad::AdaGrad(double learning_rate) : _learning_rate(learning_rate)\n    {\n    }\n\n    void AdaGrad::update(unordered_map<string, MatrixXd> &params, unordered_map<string, MatrixXd> & grads)\n    {\n        if (_h.empty())\n        {\n            for (auto param : params)\n            {\n                _h[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            // 勾配変化の大きかったパラメータの二乗平方根で割る → 要は勾配の絶対値が大きかったパラメータの更新幅を小さくするということ\n            // ※ 厳密には勾配の絶対値で割っているわけではない(直前の内部状態に加算して平方根を取っている)\n            _h[key].array() += grads[key].array() * grads[key].array();\n            params[key].array() -= _learning_rate * _h[key].unaryExpr([](double p){return 1/(sqrt(p)+1e-7);}).array() * grads[key].array();\n        }\n    }\n\n    void AdaGrad::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)\n    {\n        if (_h.empty())\n        {\n            for (auto param : params)\n            {\n                MatrixXd tmp_mat = *(param.second);\n                _h[param.first] = MatrixXd::Zero(tmp_mat.rows(), tmp_mat.cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            // 勾配変化の大きかったパラメータの二乗平方根で割る → 要は勾配の絶対値が大きかったパラメータの更新幅を小さくするということ\n            // ※ 厳密には勾配の絶対値で割っているわけではない(直前の内部状態に加算して平方根を取っている)\n            _h[key].array() += grads[key].array() * grads[key].array();\n            params[key]->array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();\n        }\n    }\n\n    // ------------------------------------------------------------\n    //                  RMSProp\n    // ------------------------------------------------------------\n    RMSprop::RMSprop(double learning_rate, double decay_rate): _learning_rate(learning_rate), _decay_rate(decay_rate)\n    {\n    }\n\n    void RMSprop::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)\n    {\n        if (_h.empty())\n        {\n            for (auto param : params)\n            {\n                _h[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            // AdaGradの内部状態hを指数移動平均に置き換えたものがRMSprop -> 指数移動平均の減衰率(平滑化係数)がdecay_rate\n            _h[key].array() *= _decay_rate;\n            _h[key].array() += (1 - _decay_rate) * grads[key].array() * grads[key].array();\n            params[key].array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();\n        }\n    }\n\n    void RMSprop::update(unordered_map<string, shared_ptr<MatrixXd>> &params, unordered_map<string, MatrixXd> &grads)\n    {\n        if (_h.empty())\n        {\n            for (auto param : params)\n            {\n                _h[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());\n            }\n        }\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            // AdaGradの内部状態hを指数移動平均に置き換えたものがRMSprop -> 指数移動平均の減衰率(平滑化係数)がdecay_rate\n            _h[key].array() *= _decay_rate;\n            _h[key].array() += (1 - _decay_rate) * grads[key].array() * grads[key].array();\n            params[key]->array() -= _learning_rate * _h[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array() * grads[key].array();\n        }\n\n    }\n\n    // ------------------------------------------------------------\n    //                  Adam\n    // ------------------------------------------------------------\n    Adam::Adam(double learning_rate, double beta1, double beta2): _learning_rate(learning_rate), _beta1(beta1), _beta2(beta2)\n    {\n        _iter = 0;\n    }\n\n    void Adam::update(unordered_map<string, MatrixXd>& params, unordered_map<string, MatrixXd>& grads)\n    {\n        if (_m.empty())\n        {\n            for (auto param : params)\n            {\n                _m[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());\n                _v[param.first] = MatrixXd::Zero(param.second.rows(), param.second.cols());\n            }\n        }\n\n        _iter++;\n        double lr_t = _learning_rate * sqrt(1.0 - std::pow(_beta2, _iter)) / (1.0 - std::pow(_beta1, _iter));\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            _m[key] += (1 - _beta1) * (grads[key] - _m[key]);\n            _v[key] += (1 - _beta2) * (grads[key].unaryExpr([](double p){return p*p;}) - _v[key]);\n\n            params[key].array() -= lr_t * _m[key].array() * _v[key].unaryExpr([](double p){return 1 / (sqrt(p) + 1e-7);}).array();\n        }\n    }\n\n    void Adam::update(unordered_map<string, shared_ptr<MatrixXd>>& params, unordered_map<string, MatrixXd>& grads)\n    {\n        if (_m.empty())\n        {\n            for (auto param : params)\n            {\n                _m[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());\n                _v[param.first] = MatrixXd::Zero(param.second->rows(), param.second->cols());\n            }\n        }\n\n        _iter++;\n        double lr_t = _learning_rate * sqrt(1.0 - std::pow(_beta2, _iter)) / (1.0 - std::pow(_beta1, _iter));\n\n        for (auto param : params)\n        {\n            string key = param.first;\n            _m[key] += (1 - _beta1) * (grads[key] - _m[key]);\n            _v[key] += (1 - _beta2) * (grads[key].unaryExpr([](double p) { return p * p; }) - _v[key]);\n\n            params[key]->array() -= lr_t * _m[key].array() * _v[key].unaryExpr([](double p) { return 1 / (sqrt(p) + 1e-7); }).array();\n        }\n    \n    }\n\n}", "meta": {"hexsha": "c528fa771592ad9c6c790589741f18d822f9770c", "size": 8189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimizer.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/optimizer.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimizer.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": 35.6043478261, "max_line_length": 147, "alphanum_fraction": 0.4874832092, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5617220661370738}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>\n#include <ceres/ceres.h>\n#include <chrono>\n\nusing namespace std;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../left.png\";\nstring disparity_file = \"../disparity.png\";\nboost::format fmt_others(\"../%06d.png\");    // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n\n// bilinear interpolation\ninline float get(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n        (1 - xx) * (1 - yy) * data[0] +\n        xx * (1 - yy) * data[1] +\n        (1 - xx) * yy * data[img.step] +\n        xx * yy * data[img.step + 1]\n    );\n}\n\nEigen::Vector3d get_3D_point_from_depth(const Eigen::Vector2d& p, double depth, const Eigen::Matrix3d& K)\n{\n    return Eigen::Vector3d(depth * (p.x() - K(0, 2)) / K(0, 0),\n                           depth * (p.y() - K(1, 2)) / K(1, 1),\n                           depth);\n}\n\nusing namespace Sophus;\n// Local parameterization needed to handle SE3 from Sophus (from Sophus/test/ceres/)\nclass LocalParameterizationSE3 : public ceres::LocalParameterization {\n public:\n  virtual ~LocalParameterizationSE3() {}\n\n  // SE3 plus operation for Ceres\n  //\n  //  T * exp(x)\n  //\n  virtual bool Plus(double const* T_raw, double const* delta_raw,\n                    double* T_plus_delta_raw) const {\n    Eigen::Map<SE3d const> const T(T_raw);\n    Eigen::Map<Vector6d const> const delta(delta_raw);\n    Eigen::Map<SE3d> T_plus_delta(T_plus_delta_raw);\n    T_plus_delta = T * SE3d::exp(delta);\n    return true;\n  }\n\n  // Jacobian of SE3 plus operation for Ceres\n  //\n  // Dx T * exp(x)  with  x=0\n  //\n  virtual bool ComputeJacobian(double const* T_raw,\n                               double* jacobian_raw) const {\n    Eigen::Map<SE3d const> T(T_raw);\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> jacobian(\n        jacobian_raw);\n    jacobian = T.Dx_this_mul_exp_x_at_0();\n    return true;\n  }\n\n\n  virtual int GlobalSize() const { return SE3d::num_parameters; }\n\n  virtual int LocalSize() const { return SE3d::DoF; }\n};\n\n\n\nstruct PhotometricError: public ceres::SizedCostFunction<9, 7>\n{\n    PhotometricError(const cv::Mat& img1, const cv::Mat& img2, const Eigen::Vector2d& p1, const Eigen::Vector3d& P1, const Eigen::Matrix3d& K, int half_w_size)\n    : _img1(img1), _img2(img2), _p1(p1), _P1(P1), _K(K), _half_w_size(half_w_size) {}\n\n\n    virtual bool Evaluate(double const* const *params,\n                          double *residuals,\n                          double **jacobians) const {\n        const Eigen::Map<const Sophus::SE3d> Rt(params[0]);\n\n        Eigen::Vector3d P2 = Rt * _P1;\n        Eigen::Vector3d p2 = _K * P2;\n        p2 /= p2.z();\n\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 = P2.x();\n        double Y = P2.y();\n        double Z = P2.z();\n        double X2 = X * X;\n        double Y2 = Y * Y;\n        double Z2 = Z * Z;\n\n        double x3 = _P1.x();\n        double y3 = _P1.y();\n        double z3 = _P1.z();\n        double qx = params[0][0];\n        double qy = params[0][1];\n        double qz = params[0][2];\n        double qw = params[0][3];\n\n\n        if (P2.z() < 0) // invalid depth\n        {\n            // fill residuals and jacobians to 0\n            for (int i = 0; i < 9; ++i)\n            {\n                residuals[i] = 0;\n                if (jacobians!=nullptr && jacobians[0]!=nullptr)\n                {\n                    for (int j = 0; j < 7; ++j)\n                    {\n                        jacobians[0][i*7+j] = 0.0;\n                    }\n                }\n            }\n            return true;\n        }\n\n        if (p2.x() < _half_w_size || p2.x() > _img2.cols - _half_w_size \n            || p2.y() < _half_w_size || p2.y() > _img2.rows - _half_w_size)\n        {\n            // fill residuals and jacobians to 0\n            for (int i = 0; i < 9; ++i)\n            {\n                residuals[i] = 0;\n                if (jacobians!=nullptr && jacobians[0]!=nullptr)\n                {\n                    for (int j = 0; j < 7; ++j)\n                    {\n                        jacobians[0][i*7+j] = 0.0;\n                    }\n                }\n            }\n            return true;\n        }\n\n        int cnt = 0;\n        for (int xx = -_half_w_size; xx <= _half_w_size; ++xx)\n        {\n            for (int yy = -_half_w_size; yy <= _half_w_size; ++yy)\n            {\n\n                double v1 = get(_img1, _p1.x() + xx, _p1.y() + yy);\n                double v2 = get(_img2,  p2.x() + xx, p2.y() + yy);\n                double err = v1 - v2;\n                residuals[cnt] = err;\n\n                if (jacobians && jacobians[0])\n                {\n                    double dx = 0.5 * (get(_img2, p2.x() + xx + 1, p2.y() + yy) - get(_img2, p2.x() + xx - 1, p2.y() + yy));\n                    double dy = 0.5 * (get(_img2, p2.x() + xx, p2.y() + yy + 1) - get(_img2, p2.x() + xx, p2.y() + yy - 1));\n                    Eigen::Vector2d dIdu(dx, dy);\n\n                    Eigen::Matrix<double, 2, 3> dudXc;\n                    dudXc << fx / Z, 0.0, -X * fx / Z2,\n                            0.0, fy / Z, -Y * fy / Z2;\n                    \n\n                    Eigen::Matrix<double, 3, 4> dXcdq; // derivative of Xcam wrt. quaternions\n                    dXcdq(0, 0) = 2*qy*y3 + 2*qz*z3;\n                    dXcdq(0, 1) = 2*qw*z3 + 2*qx*y3 - 4*qy*x3;\n                    dXcdq(0, 2) = -2*qw*y3 + 2*qx*z3 - 4*qz*x3;\n                    dXcdq(0, 3) = 2*qy*z3 - 2*qz*y3;\n\n                    dXcdq(1, 0) = -2*qw*z3 - 4*qx*y3 + 2*qy*x3;\n                    dXcdq(1, 1) = 2*qx*x3 + 2*qz*z3;\n                    dXcdq(1, 2) = 2*qw*x3 + 2*qy*z3 - 4*qz*y3;\n                    dXcdq(1, 3) = -2*qx*z3 + 2*qz*x3;\n\n                    dXcdq(2, 0) = 2*qw*y3 - 4*qx*z3 + 2*qz*x3;\n                    dXcdq(2, 1) = -2*qw*x3 - 4*qy*z3 + 2*qz*y3;\n                    dXcdq(2, 2) = 2*qx*x3 + 2*qy*y3;\n                    dXcdq(2, 3) = 2*qx*y3 - 2*qy*x3;\n\n                    Eigen::Matrix<double, 1, 7, Eigen::RowMajor> J;\n                    J.block<1, 4>(0, 0) = -dIdu.transpose() * dudXc * dXcdq;\n                    J.block<1, 3>(0, 4) = -dIdu.transpose() * dudXc;\n\n                    for (int i = 0; i < 7; ++i)\n                    {\n                        jacobians[0][cnt*7 + i] = J(0, i);\n                    }\n                }\n                ++cnt;\n            }\n        }\n\n        return true;\n    }\n\n    private:\n        cv::Mat _img1, _img2;\n        Eigen::Vector2d _p1;\n        Eigen::Vector3d _P1;\n        Eigen::Matrix3d _K;\n        int _half_w_size;\n\n};\n\n// TO TEST with autodiff or numeric diff, but not easy to differentiate wrt. image (maybe try to combine Jets + image gradient with chain rule)\n// struct PhotometricError\n// {\n//     PhotometricError(const cv::Mat& img1, const cv::Mat& img2, const Eigen::Vector2d& p1, const Eigen::Vector3d& P1, const Eigen::Matrix3d& K, int half_w_size)\n//     : _img1(img1), _img2(img2), _p1(p1), _P1(P1), _K(K), _half_w_size(half_w_size) {}\n\n//     virtual bool operator() (const double* const params,\n//                              double *residuals) const {\n//         const Eigen::Map<const Sophus::SE3d> Rt(params);\n\n//         Eigen::Vector3d P2 = Rt * _P1;\n//         Eigen::Vector3d p2 = _K * P2;\n//         p2 /= p2.z();\n\n//         int j = 0;\n//         for (int xx = -_half_w_size; xx <= _half_w_size; ++xx)\n//         {\n//             for (int yy = -_half_w_size; yy <= _half_w_size; ++yy)\n//             {\n//                 double v1 = get(_img1, _p1.x() + xx, _p1.y() + yy);\n//                 double v2 = get(_img2, p2.x() + xx, p2.y() + yy);\n//                 // debug << _p1.x() << \" \" << _p1.y() << \" \" << p2.x() << \" \" << p2.y() << \"\\n\";\n//                 debug << v1 << \" \" << v2 << \"\\n\";\n//                 double err = v1 - v2;\n//                 residuals[j++] = err;\n//             }\n//         }\n\n//         return true;\n//     }\n\n\n//     private:\n//         cv::Mat _img1, _img2;\n//         Eigen::Vector2d _p1;\n//         Eigen::Vector3d _P1;\n//         Eigen::Matrix3d _K;\n//         int _half_w_size;\n// };\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    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt // points from cam1 reference frame to cam2\n)\n{\n    int nb_iters = 11;\n    int half_w_size = 1;\n\n    ceres::Problem problem;\n\n    problem.AddParameterBlock(Rt.data(), 7, new LocalParameterizationSE3());\n    for (int i = 0; i < px_ref.size(); ++i)\n    {\n        const auto& p1 = px_ref[i];\n        Eigen::Vector3d P1 = get_3D_point_from_depth(p1, depth_ref[i], K);\n        problem.AddResidualBlock(\n            // new ceres::NumericDiffCostFunction<PhotometricError, ceres::CENTRAL, 9, 7>(\n            //     new PhotometricError(img1, img2, p1, P1, K, half_w_size)\n            // ),            \n            new PhotometricError(img1, img2, p1, P1, K, half_w_size),\n            nullptr,\n            Rt.data()\n        );\n    }\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n    options.minimizer_progress_to_stdout = false;\n    options.max_num_iterations = 11;\n\n    ceres::Solver::Summary summary;\n\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    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    \n\n    std::cout << \"translation: \" << Rt.translation().transpose() << \"\\n\";\n    std::cout << \"rotation: \" << Rt.so3().unit_quaternion().toRotationMatrix() << \"\\n\";\n\n}\n\n\nvoid DirectPoseEstimationPyramidal(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt)\n{\n    int nb_levels = 4;\n    double factor = 0.5;\n\n    std::vector<cv::Mat> pyr1, pyr2;\n    std::vector<double> scales;\n    for (int i = 0; i < nb_levels; ++i)\n    {\n        if (i == 0)\n        {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n            scales.push_back(1.0);\n        }\n        else\n        {\n            cv::Mat img1_r, img2_r;\n            cv::resize(pyr1[i-1], img1_r, cv::Size(pyr1[i-1].cols * factor, pyr1[i-1].rows * factor));\n            cv::resize(pyr2[i-1], img2_r, cv::Size(pyr2[i-1].cols * factor, pyr2[i-1].rows * factor));\n            pyr1.push_back(img1_r);            \n            pyr2.push_back(img2_r);            \n            scales.push_back(scales[i-1] * factor);\n        }\n    }\n\n\n    for (int l = nb_levels-1; l >= 0; l--)\n    {\n\n        cv::Mat img1_r = pyr1[l];\n        cv::Mat img2_r = pyr2[l];\n        double scale = scales[l];\n\n        Eigen::Matrix3d K_r = K;\n        K_r(0, 0) *= scale;\n        K_r(1, 1) *= scale;\n        K_r(0, 2) *= scale;\n        K_r(1, 2) *= scale;\n        auto p_r = px_ref;\n        for (auto& p : p_r)\n        {\n            p *= scale;\n        }\n\n        DirectPoseEstimationSingleLayer(img1_r, img2_r, p_r, depth_ref, K_r, Rt);\n    }\n}\n\n\nint main(int argc, char **argv) {\n\nSophus::SE3d r;\nEigen::Matrix<double, 6, 1> d;\nd << 1, 2, 3, 0, 0, 0;\nr =  Sophus::SE3d::exp(d) * r;\ndouble* rr = r.data();\nfor (int i = 0; i<7;++i)\nstd::cout << rr[i] << \" \";\ncout << \"\\n\\n\";\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng(1994);\n    int nPoints = 2000;\n    int boarder = 40;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d Rt;\n    Eigen::Matrix3d K;\n    K << fx, 0.0, cx,\n         0.0, fy, cy,\n         0.0, 0.0, 1.0;\n\n    for (int i = 1; i < 6; i++) {  // 1~10\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n        // try single layer by uncomment this line\n        // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, K, Rt);\n        DirectPoseEstimationPyramidal(left_img, img, pixels_ref, depth_ref, K, Rt);\n\n\n        // plot the projected pixels here\n        cv::Mat img2_show;\n        cv::cvtColor(img, img2_show, CV_GRAY2BGR);\n        std::vector<Eigen::Vector2d> projections(pixels_ref.size());\n        for (int i = 0; i < pixels_ref.size(); ++i)\n        {\n            Eigen::Vector3d P_ref = get_3D_point_from_depth(pixels_ref[i], depth_ref[i], K);\n            Eigen::Vector3d uv = K * (Rt * P_ref);\n            projections[i] = uv.hnormalized();\n        }\n\n        for (size_t i = 0; i < pixels_ref.size(); ++i) {\n            auto p_ref = pixels_ref[i];\n            auto p_cur = projections[i];\n            if (p_cur[0] > 0 && p_cur[1] > 0 && p_cur[0] < img2_show.cols && p_cur[1] < img2_show.rows) {\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        cv::imwrite(\"img_\"+std::to_string(i) + \"_ceres.png\", img2_show);\n\n    }\n    // debug.close();\n    return 0;\n}\n", "meta": {"hexsha": "e85763732a3c1e7b801ba8057ba032342a0cb9d3", "size": 14760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch8/direct_method_ceres.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": "ch8/direct_method_ceres.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": "ch8/direct_method_ceres.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.582781457, "max_line_length": 162, "alphanum_fraction": 0.5123306233, "num_tokens": 4677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5617220661370738}}
{"text": "#include \"plane_param.h\"\n\n#include <Eigen/Dense>\n\nPlaneParam::PlaneParam()\n{}\n\nPlaneParam::PlaneParam(\n\t\tconst Eigen::Vector3d& v0,\n\t\tconst Eigen::Vector3d& v1,\n\t\tconst Eigen::Vector3d& v2) {\n\n\tEigen::Vector3d V0(v0[0] * v0[2], v0[1] * v0[2], v0[2]);\n\tEigen::Vector3d V1(v1[0] * v1[2], v1[1] * v1[2], v1[2]);\n\tEigen::Vector3d V2(v2[0] * v2[2], v2[1] * v2[2], v2[2]);\n\t/*\n\tEigen::Vector3d V0(v0);\n\tEigen::Vector3d V1(v1);\n\tEigen::Vector3d V2(v2);\n\t*/\n\tEigen::Vector3d norm = (V1 - V0).cross(V2 - V0);\n\tif (norm.norm() < 1e-10 || norm[2] == 0) {\n\t\tinvalid_ = true;\n\t}\n\tnorm.normalize();\n\td_ = -V0.dot(norm);\n\tn1_ = norm[0];\n\tn2_ = norm[1];\n\tn3_ = norm[2];\n\tinvalid_ = false;\n\tif (d_ == 0)\n\t\tinvalid_ = true;\n}\n\nbool PlaneParam::ProjectiveIntersection(const PlaneParam& other, LineSegment* l) const {\n\tif (invalid_ || other.invalid_)\n\t\treturn false;\n\t//figure out the intersection line direction\n\tl->n1 = n2_ * other.n3_ - n3_ * other.n2_;\n\tl->n2 = n3_ * other.n1_ - n1_ * other.n3_;\n\tl->n3 = n1_ * other.n2_ - n2_ * other.n1_;\n\n\t//figure out one intersection point\n\tif (l->n1 != 0) {\n\t\tl->x = 0;\n\t\tl->z = (other.n2_ * d_ - n2_ * other.d_) / l->n1;\n\t\tl->y = (-other.n3_ * d_ + n3_ * other.d_) / l->n1;\n\t}\n\telse if (l->n2 != 0) {\n\t\tl->y = 0;\n\t\tl->x = (other.n3_ * d_ - n3_ * other.d_) / l->n2;\n\t\tl->z = (-other.n1_ * d_ + n1_ * other.d_) / l->n2;\n\t}\n\telse {\n\t\treturn false;\n\t}\n\n\tif (l->x == 0 && l->y == 0)\n\t\treturn false;\n\n\tif (l->z == 0) {\n\t\tl->x += l->n1;\n\t\tl->y += l->n2;\n\t\tl->z += l->n3;\n\t}\n\tK nx, ny;\n\tif (l->z + l->n3 != 0) {\n\t\tnx = (l->x+l->n1) / (l->z+l->n3);\n\t\tny = (l->y+l->n2) / (l->z+l->n3);\n\t} else if (l->z - l->n3 != 0) {\n\t\tnx = (l->x-l->n1) / (l->z-l->n3);\n\t\tny = (l->y-l->n2) / (l->z-l->n3);\n\t} else {\n\t\treturn false;\n\t}\n\n\tl->x /= l->z;\n\tl->y /= l->z;\n\tl->n1 = nx - l->x;\n\tl->n2 = ny - l->y;\n\treturn true;\n}\n", "meta": {"hexsha": "95c72d2ddefb927fe8081d2f35006157cc7d67b2", "size": 1822, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/plane_param.cc", "max_stars_repo_name": "hjwdzh/VectorGraphRenderer", "max_stars_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-02-15T23:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T05:01:17.000Z", "max_issues_repo_path": "src/plane_param.cc", "max_issues_repo_name": "hjwdzh/VectorGraphRenderer", "max_issues_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/plane_param.cc", "max_forks_repo_name": "hjwdzh/VectorGraphRenderer", "max_forks_repo_head_hexsha": "4af5a683fb1414f32101be22924a809db08d7cb5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9518072289, "max_line_length": 88, "alphanum_fraction": 0.527442371, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5617220661142289}}
{"text": "\n#include <stdio.h>  /* for sprintf */\n#include <stdlib.h> /* for strtod */\n#include <string>\n#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n#include <time.h>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <boost/foreach.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/unordered_map.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nconst float pi = acos(-1);\n\nint numTerms;\nint numVars;\nint Order;\nvector<vector<double> > multipliers;\nvector<vector<double> > obsRanges;\n\n\n/********** GDK's Fourier Code (Ported from Java) **************/\n/**                                                                                                                                                                                                                                         * This method iterates through a coefficient vector                                                                                                                                                                                        * up to a given degree. (like counting in a base of                                                                                                                                                                                        * that degree).                                                                                                                                                                                                                            *                                                                                                                                                                                                                                          * @param cthe coefficient vector.                                                                                                                                                                                                          * @param NVariablesthe number of variables in c.                                                                                                                                                                                           * @param Degreethe degree up to which to increment.                                                                                                                                                                                        */\nvoid Iterate(int *c, int NVariables, int Degree)\n{\n  c[NVariables - 1] = c[NVariables-1] + 1;\n\n  if(c[NVariables - 1] > Degree)\n    {\n      if(NVariables > 1)\n        {\n          c[NVariables - 1]  = 0;\n          Iterate(c, NVariables - 1, Degree);\n        }\n    }\n}\n\n/*\n * Compute the full Fourier Basis coefficient matrix for \n * a given number of variables up to a given order.\n *\n * @param nvarsthe number of variables.\n * @param orderthe highest coefficient value for any individual variable.  \n * @returna two dimensional array of doubles. The first dimension length is\n * the number of basis functions, and the second is the number of state variables. \n */\nvoid computeFourierCoefficients(int nvars, int order) {\n  int nterms = (int)pow(order + 1.0, nvars);\n  numTerms = nterms;\n  numVars = nvars;\n  Order = order;\n\n  int pos = 0;\n  multipliers.resize(nterms);\n  for (int i=0; i<nterms; i++)\n    multipliers[i].resize(nvars);\n  int *c = new int[nvars];\n  for(int j = 0; j < nvars; j++)\n    c[j] = 0;\n\n  do\n    {\n      for(int k = 0; k < nvars; k++)\n        {\n          multipliers[pos][k] = c[k];\n        }\n\n      pos++;\n      // Iterate c                                                                                                                                                                                                                         \n      Iterate(c, nvars, order);\n    }\n  while(c[0] <= order);\n}\n\n/**\n * Scale a state variable to between 0 and 1. \n * (this is required for the Fourier Basis). \n *\n * @param valthe state variable. \n * @param posthe state variable number.\n * @returnthe normalized state variable. \n */\ndouble scale(double val, int pos)\n{\n  //  cout << pos << \",\" << val << \" \" << obsRanges[pos][0] << \",\" << obsRanges[pos][1] << \" : \" << (val - obsRanges[pos][0])/(obsRanges[pos][1] - obsRanges[pos][0]) << endl;\n  return (val - obsRanges[pos][0]) / (obsRanges[pos][1] - obsRanges[pos][0]);\n}\n\n\n/**\n * Compute the feature vector for a given state. \n * This is achieved by evaluating each Fourier Basis function\n * at that state.\n *\n * @param sthe state in question.\n * @return a vector of doubles representing each basis function evaluated at s.\n */\nvector<double> computeFeatures(vector<double> features)\n{\n  vector<double> phi(numTerms);\n  for(int pos = 0; pos < numTerms; pos++)\n    {\n      double dsum = 0;\n      for(int j = 0; j < numVars; j++)\n        {\n          double sval = scale(features[j], j);\n          dsum += sval*multipliers[pos][j];\n        }\n\n      phi[pos] = cos((pi) * dsum);\n    }\n\n  return phi;\n}\n\n  typedef boost::unordered_map<std::string, int> map;  \n\nint main(int argc, char **argv) {\n  char input[4096];\n  char_separator<char> sep(\", \"); // lets start with csv and move to VW input later\n  char_separator<char> vwsep(\":\");\n  double order = lexical_cast<int>(*++argv);\n  //  vector<string> features;\n  int vw_offset = 0;\n  bool skip_normal = false;\n  boost::unordered_map<string, int> features;\n  // Default to CSV conversion\n  // Take parameter flag: --vw \n  // to switch to vw input based\n  while(*++argv) {\n      if(strcmp(*argv, \"--vw\") == 0)\n          vw_offset = 1;\n      else if(strcmp(*argv, \"--nonorm\") == 0)\n  \t  skip_normal = true;\n      else {\n\tcout << \"Unknown argument: \" << *argv << endl;\n\texit(1);\n      }\n  }\n  \n  //cout << \"Fourier Order: \" << order << endl;\n  int line_count = 0;\n  bool translating = false;\n\n  while(!cin.eof()) {\n    bool line_has_data = false;\n    cin.getline(input,4096);\n\n    string line(input);\n    tokenizer< char_separator<char> > tokens(line, sep);\n    vector<double> vanilla_features;\n    int feature_counter = 0;\n\n    if(vw_offset > 0 && line_count > 0)  {\n      vanilla_features.resize(features.size());\n    }\n    BOOST_FOREACH (const string& t, tokens) {\n      try {\n\tif(line_count == 0) {\n\t  obsRanges.push_back(vector<double>(2));\n\t  obsRanges[feature_counter][0] = 0.0;\n\t  obsRanges[feature_counter][1] = 1.0;\n\t} \n\t// min then max then features\n\tif(line_count < vw_offset) { // first line, and we ARE doing VW inputs\n\t  features[t] = feature_counter;\n\t} else if(line_count == vw_offset && !skip_normal) { // ready for the min-max values\n\t  obsRanges[feature_counter][0] = lexical_cast<double>(t);\n\t} else if(line_count == vw_offset+1 && !skip_normal) {\n\t  obsRanges[feature_counter][1] = lexical_cast<double>(t);\n\t} else {\n\t  translating = true;\n\t  if(vw_offset > 0) {\n\t    boost::tokenizer< char_separator<char> > vwtoken(t, vwsep);\n\t    boost::tokenizer< char_separator<char> >::iterator beg=vwtoken.begin();\n\t    string fname(*beg);\n\t    if(features.find(*beg) != features.end()) {\n\t      int findex = features.at(*beg);\n\t      vanilla_features[findex] = lexical_cast<double>(*++beg);\n\t    } else {\n\t      cout << t << \" \";\n\t      feature_counter--;\n\t      line_has_data = true;\n\t    }\n\t  } else {\n\t    vanilla_features.push_back(lexical_cast<double>(t));      \n\t  }\n\t  if(feature_counter >= 0 && (vanilla_features[feature_counter] < obsRanges[feature_counter][0] || vanilla_features[feature_counter] > obsRanges[feature_counter][1])) {\n\t    cout << \"ERROR: feature \" << feature_counter << \" is out of supplied range\"<<endl;\n\t    exit(1);\n\t  } //else cout << vanilla_features[feature_counter] << endl;\n\t}\n      }\n      catch(bad_lexical_cast&)\n\t{}\n\n      feature_counter++;\n    }\n    //    cout << \"Counts: \" << feature_counter << \" \" << line_count << \" \" << vanilla_features.size() << endl;\n    //head ../uk3day/train.vw | sed '1d' | ./fourie 3 --vw\n    if(line_count == 0) {\n      if(vw_offset > 0 && features.size() == 0) {\n\tcout << \"ERROR: feature labels not provided\" << endl;\n\texit(1);\n      }\n      //      cout << feature_counter << endl;\n      //cout << \"Num Features: \" << feature_counter << endl;\n      computeFourierCoefficients(feature_counter, order);\n      //      cout << \"Num Fourier Terms: \" << numTerms << endl;\n    }\n      \n    if(translating && feature_counter > 0) {\n      //cout << \"Computing features... \" <<endl;\n      vector<double> fourie_features = computeFeatures(vanilla_features);\n      if(vw_offset > 0) {\n\tcout <<\"FOURIER0:\" << fourie_features[0] << \" \";\n\tfor(int i=1; i<(int)fourie_features.size(); i++) {\n\t  cout << \"FOURIER\" << i << \":\" << fourie_features[i] << \" \";\n\t}\n\tcout << endl;\n      } else {\n\tcout << fourie_features[0];\n\tfor(int i=1; i<(int)fourie_features.size(); i++) {\n\t  cout << \",\" << fourie_features[i];\n\t}\n\tcout << endl;\n      }\n    } else if(line_has_data) {\n      cout << endl;\n    }\n    line_count++;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "b8478d3d059117b379fdc5863d811a41752c99dd", "size": 8973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fourie.cpp", "max_stars_repo_name": "eHarmony/fourie", "max_stars_repo_head_hexsha": "5a3de38ddb2fbd2fad00f2e07b54fac4039e314e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-24T03:19:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-24T03:19:17.000Z", "max_issues_repo_path": "fourie.cpp", "max_issues_repo_name": "eHarmony/fourie", "max_issues_repo_head_hexsha": "5a3de38ddb2fbd2fad00f2e07b54fac4039e314e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fourie.cpp", "max_forks_repo_name": "eHarmony/fourie", "max_forks_repo_head_hexsha": "5a3de38ddb2fbd2fad00f2e07b54fac4039e314e", "max_forks_repo_licenses": ["BSD-3-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.2323651452, "max_line_length": 1883, "alphanum_fraction": 0.4881310598, "num_tokens": 1968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5617220523893786}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\n\n#ifndef CPPDEBUG /* Ubuntu's Boost does not provide binaries compatible with libstdc++'s debug mode so we just reduce functionality here */\n#include <boost/program_options.hpp>\n#endif\n\n#include \"boost_profile.cpp\"\n#include \"libiop/algebra/fft.hpp\"\n#include \"libiop/algebra/fields/gf64.hpp\"\n#include \"libiop/algebra/fields/gf128.hpp\"\n#include \"libiop/algebra/fields/gf192.hpp\"\n#include \"libiop/algebra/fields/gf256.hpp\"\n#include \"libiop/algebra/field_subset/subspace.hpp\"\n#include \"libiop/common/profiling.hpp\"\n\n#ifndef CPPDEBUG\nbool process_prover_command_line(const int argc, const char** argv,\n                                 std::size_t &log_n_min,\n                                 std::size_t &log_n_max,\n                                 std::size_t &field_size)\n{\n    namespace po = boost::program_options;\n\n    try\n    {\n        po::options_description desc(\"Usage\");\n        desc.add_options()\n        (\"help\", \"print this help message\")\n        (\"log_n_min\", po::value<std::size_t>(&log_n_min)->default_value(8))\n        (\"log_n_max\", po::value<std::size_t>(&log_n_max)->default_value(20))\n        (\"field_size\", po::value<std::size_t>(&field_size)->default_value(64));\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n#endif\n\nusing namespace libiop;\n\ntemplate<typename FieldT>\nvoid instrument_algebra(std::size_t log_n_min,\n                        std::size_t log_n_max)\n{\n    if (log_n_min % 2 != 0)\n    {\n        log_n_min += 1;\n    }\n    if (log_n_max % 2 != 0)\n    {\n        log_n_max += 1;\n    }\n\n    for (std::size_t log_n = log_n_min; log_n <= log_n_max; log_n += 2)\n    {\n        print_separator();\n        const std::size_t n = 1ul << log_n;\n        print_indent(); printf(\"* size of n: %zu\\n\", n);\n        const std::size_t sqrt_n = 1ul << (log_n / 2);\n        print_indent(); printf(\"* size of sqrt(n): %zu\\n\", sqrt_n);\n\n        /* FFT(n) */\n        std::vector<FieldT> n_vec;\n        enter_block(\"n\");\n        for (size_t i = 0; i < n; ++i)\n        {\n            n_vec.push_back(FieldT::random_element());\n        }\n        leave_block(\"n\");\n        affine_subspace<FieldT> n_subspace = linear_subspace<FieldT>::standard_basis(libiop::log2(n));\n        enter_block(\"FFT(n)\");\n        std::vector<FieldT> fft_results = additive_FFT<FieldT>(n_vec, n_subspace);\n        leave_block(\"FFT(n)\");\n\n        /* sqrt(n) * FFT(sqrt(n)) */\n        std::vector<FieldT> sqrt_n_vec;\n        enter_block(\"sqrt(n)\");\n        for (size_t i = 0; i < sqrt_n; ++i)\n        {\n            sqrt_n_vec.push_back(FieldT::random_element());\n        }\n        leave_block(\"sqrt(n)\");\n        affine_subspace<FieldT> sqrt_n_subspace = linear_subspace<FieldT>::standard_basis(libiop::log2(sqrt_n));\n        enter_block(\"sqrt(n) * FFT(sqrt(n))\");\n        for (size_t i = 0; i < sqrt_n; ++i)\n        {\n            std::vector<FieldT> sqrt_results = additive_FFT<FieldT>(sqrt_n_vec, sqrt_n_subspace);\n        }\n        leave_block(\"sqrt(n) * FFT(sqrt(n))\");\n    }\n}\n\nint main(int argc, const char * argv[])\n{\n    std::size_t log_n_min;\n    std::size_t log_n_max;\n    std::size_t field_size;\n\n#ifdef CPPDEBUG\n    /* set reasonable defaults */\n    if (argc > 1)\n    {\n        printf(\"There is no argument parsing in CPPDEBUG mode.\");\n        exit(1);\n    }\n    libiop::UNUSED(argv);\n\n    log_n_min = 8;\n    log_n_max = 20;\n    field_size = 64;\n#else\n    if (!process_prover_command_line(argc, argv, log_n_min, log_n_max, field_size))\n    {\n        return 1;\n    }\n#endif\n\n    printf(\"Selected parameters:\\n\");\n    printf(\"* log_n_min = %zu\\n\", log_n_min);\n    printf(\"* log_n_max = %zu\\n\", log_n_max);\n\n    switch (field_size)\n    {\n        case 64:\n            instrument_algebra<gf64>(log_n_min, log_n_max);\n            break;\n        case 128:\n            instrument_algebra<gf128>(log_n_min, log_n_max);\n            break;\n        case 192:\n            instrument_algebra<gf192>(log_n_min, log_n_max);\n            break;\n        case 256:\n            instrument_algebra<gf256>(log_n_min, log_n_max);\n            break;\n        default:\n            throw std::invalid_argument(\"Field size not supported.\");\n    }\n}\n", "meta": {"hexsha": "33695fd41bdb17e25f1ba23e612560d91bb215f3", "size": 4552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libiop/profiling/instrument_algebra.cpp", "max_stars_repo_name": "pwang00/libiop", "max_stars_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libiop/profiling/instrument_algebra.cpp", "max_issues_repo_name": "pwang00/libiop", "max_issues_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libiop/profiling/instrument_algebra.cpp", "max_forks_repo_name": "pwang00/libiop", "max_forks_repo_head_hexsha": "640a627f0e844caf88ac66cc2ab16f1ef3ea3283", "max_forks_repo_licenses": ["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.2732919255, "max_line_length": 139, "alphanum_fraction": 0.5777680141, "num_tokens": 1200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.5616814860244872}}
{"text": "#include \"filter.h\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <iostream>\n#include <fstream>\n#include <math.h>\n\nusing namespace Eigen;\nusing namespace std;\n\ninline double Gauss(double sigma, double x)\n{\n\tdouble expVal = -1 * (pow(x, 2) / (2*pow(sigma, 2)));\n\tdouble divider = sqrt(2 * PI * pow(sigma, 2));\n\treturn (1 / divider) * exp(expVal);\n}\n\n// a : signal , b : filter\ninline MatrixXd Conv(MatrixXd a, MatrixXd b)\n{\n\tint size = a.rows();\n\tint sizeb = b.rows();\n\tint window(0);\n\tMatrixXd out(size, 1);\n\tdouble sum(0);\n\n\tfor (int i = 0; i < size; i++) {\n\t\tif (i >= sizeb) window = sizeb;\n\t\telse  window = i;\n\n\t\tfor (int j = 0; j < window; j++) {\n\t\t\tsum += b(j, 0) * a(i - j);\n\t\t}\n\t\tout(i, 0) = sum;\n\t\tsum = 0;\n\t}\n\n\treturn out;\n}\n\nFilter::Filter()\n\t: sum_kernel_(0.0), weight_(0.0)\n{\n\tkernel_.resize(kkernelLevel, 1);\n}\n\nFilter::~Filter()\n{}\n\nvoid Filter::KernelMake(int samples, double sigma)\n{\n\tkernel_.resize(samples, 1);\n\tbool doubleCenter = false;\n\tif (kkernelLevel % 2 == 0) {\n\t\tdoubleCenter = true;\n\t\tsamples--;\n\t}\n\n\tint steps = (samples - 1) / 2;\n\tdouble stepSize = (3 * sigma) / steps;\n\n\tfor (int i = steps; i >= 1; i--) {\n\t\tkernel_(steps - i, 0) = Gauss(sigma, -1*i*stepSize);\n\t\tkernel_(kernel_.rows() + i - steps - 1, 0) = Gauss(sigma, i * stepSize);\n\t}\n\tkernel_(steps, 0) = Gauss(sigma, 0);\n\tif (doubleCenter) kernel_(steps + 1, 0) = Gauss(sigma, 0);\n\n\tsum_kernel_ = 0;\n\tfor (int i = 0; i < kernel_.rows(); i++) {\n\t\tsum_kernel_ += kernel_(i, 0);\n\t}\n\tweight_ = 1 / sum_kernel_;\n}\n\n\nMatrixXd Filter::LanczosDiffLow(MatrixXd const& a, int order = 5, int circle = 0)\n{\n\tint n = a.rows();\n\n\tif (n < 4) {\n\t\tcout << \"size of matrix is wrong\" << endl;\n\t}\n\n\tdiff_.resize(n, 1);\n\n\tint m = (order - 1) / 2;\n\tdouble temp(0);\n\tint start(m);\n\n\tif (circle) start = 0;\n\n\tfor (int i = start; i < n - start; i++) {\n\t\ttemp = 0;\n\t\tfor (int j = 1; j < m + 1; j++) {\n\t\t\tint front = i + j;\n\t\t\tint back = i - j;\n\n\t\t\tif (front > n - 1) front = i + j - n;\n\t\t\tif (back < 0) back = i - j + n;\n\t\t\ttemp += j * (a(front, 0) - a(back, 0)) / (m * (m + 1) * (2 * m + 1));\n\t\t}\n\t\tdiff_(i, 0) = 3 * temp;\n\t}\n\n\tif(!circle) {\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tdiff_(i, 0) = a(i + 1) - a(i, 0);\n\t\t\tdiff_(n - i - 1, 0) = a(n - i - 1, 0) - a(n - i - 2, 0);\n\t\t}\n\t}\n\n\treturn diff_;\n}\n\nvoid Filter::Gaussian(double sigma,\n\tMatrixXd const& in,\n\tMatrixXd& out,\n\tint circle)\n{\n\tint samples = kkernelLevel;\n\tKernelMake(samples, sigma);\n\tint sampleSide = samples / 2;\n\tint valueIdx = samples / 2 + 1;\n\tint ubound = in.rows();\n\tout.resize(ubound, 1);\n\tMatrixXd temp(ubound, 1);\n\ttemp = in;\n\tint start(sampleSide);\n\n\tif (circle) start = 0;\n\n\telse if (!circle) {\n\t\tfor (int i = 0; i < sampleSide; i++) {\n\t\t\tout(i, 0) = in(i, 0);\n\t\t\tout(ubound - i - 1) = in(ubound - i - 1);\n\t\t}\n\t}\n\n\tfor (int i = start; i < ubound - start; i++) {\n\t\tdouble sum = 0;\n\t\tint sampleCtr = 0;\n\t\tint init = i - sampleSide;\n\t\tint limit = i + sampleSide;\n\n\t\tfor (int j = init ; j < limit ; j++) {\n\t\t\tint index(j);\n\t\t\tif (j < 0) index = j + ubound;\n\t\t\telse if (j > ubound - 1) index = j - ubound;\n\n\t\t\tint sampleWeightIndex = sampleSide + (j - i);\n\t\t\tsum += kernel_(sampleWeightIndex, 0) * temp(index);\n\t\t\tsampleCtr++;\n\t\t}\n\t\tdouble smoothed = sum * weight_;\n\t\tout(i, 0) = smoothed;\n\t}\n}\n\n\nvoid CalculateFeatureAxisless(Geom& shard, int axis_index)\n{\n\tFilter filter;\n\n\tif (!shard.is_matching_) return;\n\n\t// Feature calculation\n\tint number_of_points = shard.edge_line_.point_.cols();\n\tMatrixXd Dist(number_of_points, 1), Thickness(number_of_points, 1);\n\tMatrixXd Height(number_of_points, 1), Theta(number_of_points, 1);\n\n\tfor (int i = 0; i < number_of_points; i++) {\n\t\tVector3d r = { shard.edge_line_.point_(0, i), shard.edge_line_.point_(1, i), 0 };\n\t\tDist(i) = r.norm();\n\t\tTheta(i) = atan2(shard.edge_line_.point_(1, i), shard.edge_line_.point_(0, i));\n\t\tHeight(i) = shard.edge_line_.point_(2, i);\n\t}\n\tfor (int i = 1; i < Theta.rows(); i++) {\n\t\tif (Theta(i, 0) - Theta(i - 1, 0) > PI) {\n\t\t\tTheta(i, 0) = Theta(i, 0) - 2 * PI;\n\t\t}\n\t\telse if (Theta(i, 0) - Theta(i - 1, 0) < -PI) {\n\t\t\tTheta(i, 0) = Theta(i, 0) + 2 * PI;\n\t\t}\n\t}\n\n\tif ((axis_index == 0) && (!shard.is_thickness_)) {\n\t\tThickness = GetThickness(shard);\n\t}\n\telse {\n\t\tThickness = shard.edge_line_.feature_[0].row(6);\n\t}\n\n\tMatrixXd Dist_Diff = filter.LanczosDiffLow(Dist, 7, 0);\n\tMatrixXd Height_Diff = filter.LanczosDiffLow(Height, 7, 0);\n\tMatrixXd Theta_Diff = filter.LanczosDiffLow(Theta, 7, 0);\n\n\t//Calculate Dist*d(Theta)\n\tfor (int i = 0; i < Theta_Diff.rows(); i++) {\n\t\tTheta_Diff(i) = Theta_Diff(i) * Dist(i);\n\t}\n\n\tfilter.Gaussian(2, Dist_Diff, Dist_Diff, 1);\n\tfilter.Gaussian(2, Height_Diff, Height_Diff, 1);\n\tfilter.Gaussian(2, Theta_Diff, Theta_Diff, 1);\n\n\tint num_features = Dist_Diff.rows();\n\n\tshard.edge_line_.feature_[axis_index].resize(7, num_features);\n\tfor (int i = 0; i < num_features; i++) {\n\t\tshard.edge_line_.feature_[axis_index].col(i) << Dist_Diff(i), \n\t\t\tHeight_Diff(i), \n\t\t\tTheta_Diff(i), \n\t\t\tDist(i),\n\t\t\tHeight(i), \n\t\t\tTheta(i), \n\t\t\tThickness(i);\n\t}\n}\n\nMatrixXd GetThickness(Geom& shard)\n{\n\tint num_breakline = shard.edge_line_.point_.cols();\n\tint num_o_sur = shard.sur_out_.point_.cols();\n\tMatrixXd thickness(num_breakline, 1);\n\n\tint index_out(0);\n\tfor (size_t i = 0; i < num_breakline; i++) {\n\t\tEigen::Vector4f pt(1, 0, 0, 0), line_pt(0, 0, 0, 0), line_dir(1, 1, 0, 0);\n\t\tdouble point2line_disance = 99999999, dist_Tmp = 0;\n\t\tline_pt << shard.edge_line_.point_(0, i), shard.edge_line_.point_(1, i), shard.edge_line_.point_(2, i), 0;\n\t\tline_dir << shard.edge_line_.normal_(0, i), shard.edge_line_.normal_(1, i), shard.edge_line_.normal_(2, i), 0;\n\n\t\tfor (size_t j = 0; j < num_o_sur; j++) {\n\t\t\tpt << shard.sur_out_.point_(0, j), shard.sur_out_.point_(1, j), shard.sur_out_.point_(2, j), 0;\n\t\t\tdist_Tmp = sqrt(pcl::sqrPointToLineDistance(pt, line_pt, line_dir));\n\t\t\tif (dist_Tmp < point2line_disance)\n\t\t\t{\n\t\t\t\tpoint2line_disance = dist_Tmp;\n\t\t\t\tindex_out = j;\n\t\t\t}\n\t\t}\n\t\t\n\t\tEigen::Vector4f a;\n\t\ta << shard.sur_out_.point_(0, index_out), shard.sur_out_.point_(1, index_out), \n\t\t\tshard.sur_out_.point_(2, index_out), 0;\n\n\t\tif ((point2line_disance > 1.0) || (line_dir.dot(a - line_pt) > 0)) {\n\t\t\tthickness(i) = -1.0;\n\t\t}\n\t\telse {\n\t\t\tthickness(i) = (shard.sur_out_.point_.col(index_out) - shard.edge_line_.point_.col(i)).norm();\n\t\t}\n\t\t\n\t}\n\t\n\tshard.is_thickness_ = true;\n\n\treturn thickness;\n}\n\n// (r, theta, z) 3*n matrix\nMatrixXd ToCylindricalInterpolation(const BreakLine& breakline,\n\tbool theta_sort,\n\tbool r_sort)\n{\n\tMatrixXd b1 = breakline.point_;\n\tint number_of_points = b1.cols();\n\tvector<Vector3d> cy;\n\tdouble base_theta;\n\tfor (int i = 0; i < number_of_points; i++) {\n\t\tVector3d r = { b1(0, i), b1(1, i), 0 }, tmp;\n\t\ttmp(0) = r.norm();\n\t\ttmp(1) = atan2(b1(1, i), b1(0, i));\n\t\ttmp(2) = b1(2, i);\n\t\tcy.push_back(tmp);\n\t}\n\n\tfor (int i = 1; i < number_of_points; i++) {\n\t\tdouble gap = abs(cy[i](1) - cy[i - 1](1));\n\t\tif ((gap > 0.04) && (gap < 3.14)) {\n\t\t\tint num_interpol = gap / 0.04;\n\t\t\tdouble r_step = (cy[i](0) - cy[i - 1](0)) / num_interpol;\n\t\t\tdouble theta_step = (cy[i](1) - cy[i - 1](1)) / num_interpol;\n\t\t\tdouble z_step = (cy[i](2) - cy[i - 1](2)) / num_interpol;\n\t\t\tfor (int j = 0; j < num_interpol; j++) {\n\t\t\t\tVector3d tmp;\n\t\t\t\ttmp(0) = cy[i - 1](0) + r_step * (j + 1);\n\t\t\t\ttmp(1) = cy[i - 1](1) + theta_step * (j + 1);\n\t\t\t\ttmp(2) = cy[i - 1](2) + z_step * (j + 1);\n\t\t\t\tcy.push_back(tmp);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (theta_sort) {\n\t\tsort(cy.begin(), cy.end(), [](Vector3d a, Vector3d b) -> bool {\n\t\t\treturn a(1) < b(1);\n\t\t});\n\t}\n\telse if (r_sort) {\n\t\tsort(cy.begin(), cy.end(), [](Vector3d a, Vector3d b) -> bool {\n\t\t\treturn a(0) > b(0);\n\t\t});\n\t}\n\tnumber_of_points = cy.size();\n\tMatrixXd output(3, number_of_points);\n\n\tfor(int i = 0; i < number_of_points; i++){\n\t\toutput(0, i) = cy[i](0);\n\t\toutput(1, i) = cy[i](1);\n\t\toutput(2, i) = cy[i](2);\n\t}\n\n\treturn output;\n}\n\nvoid ToCylindricalInterpolation(const BreakLine& breakline,\n\tvector<Vector3d>& out,\n\tbool interpol)\n{\n\tMatrixXd b1 = breakline.point_;\n\tint number_of_points = b1.cols();\n\tdouble base_theta;\n\tfor (int i = 0; i < number_of_points; i++) {\n\t\tVector3d r = { b1(0, i), b1(1, i), 0 }, tmp;\n\t\ttmp(0) = r.norm();\n\t\ttmp(1) = atan2(b1(1, i), b1(0, i));\n\t\ttmp(2) = b1(2, i);\n\t\tout.push_back(tmp);\n\t}\n\n\tif (interpol) {\n\t\tfor (int i = 1; i < number_of_points; i++) {\n\t\t\tdouble gap = abs(out[i](1) - out[i - 1](1));\n\t\t\tif ((gap > 0.04) && (gap < 3.14)) {\n\t\t\t\tint num_interpol = gap / 0.04;\n\t\t\t\tdouble r_step = (out[i](0) - out[i - 1](0)) / num_interpol;\n\t\t\t\tdouble theta_step = (out[i](1) - out[i - 1](1)) / num_interpol;\n\t\t\t\tdouble z_step = (out[i](2) - out[i - 1](2)) / num_interpol;\n\t\t\t\tfor (int j = 0; j < num_interpol; j++) {\n\t\t\t\t\tVector3d tmp;\n\t\t\t\t\ttmp(0) = out[i - 1](0) + r_step * (j + 1);\n\t\t\t\t\ttmp(1) = out[i - 1](1) + theta_step * (j + 1);\n\t\t\t\t\ttmp(2) = out[i - 1](2) + z_step * (j + 1);\n\t\t\t\t\tout.push_back(tmp);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble r_gap = abs(out[i](0) - out[i - 1](0));\n\t\t\tif ((r_gap > 0.1) && (gap < 3.14)) {\n\t\t\t\tint num_interpol = r_gap / 0.1;\n\t\t\t\tdouble r_step = (out[i](0) - out[i - 1](0)) / num_interpol;\n\t\t\t\tdouble theta_step = (out[i](1) - out[i - 1](1)) / num_interpol;\n\t\t\t\tdouble z_step = (out[i](2) - out[i - 1](2)) / num_interpol;\n\t\t\t\tfor (int j = 0; j < num_interpol; j++) {\n\t\t\t\t\tVector3d tmp;\n\t\t\t\t\ttmp(0) = out[i - 1](0) + r_step * (j + 1);\n\t\t\t\t\ttmp(1) = out[i - 1](1) + theta_step * (j + 1);\n\t\t\t\t\ttmp(2) = out[i - 1](2) + z_step * (j + 1);\n\t\t\t\t\tout.push_back(tmp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "7eb7e78bf408b0c642fb6210a9a497db8ae1874b", "size": 9394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "class/filter.cpp", "max_stars_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_stars_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T19:48:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T05:16:35.000Z", "max_issues_repo_path": "class/filter.cpp", "max_issues_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_issues_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-15T01:31:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T12:41:51.000Z", "max_forks_repo_path": "class/filter.cpp", "max_forks_repo_name": "SeongJong-Yoo/structure-from-sherds", "max_forks_repo_head_hexsha": "2ad938a3e708f0a6d95decb59c3160a4ee389322", "max_forks_repo_licenses": ["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.527173913, "max_line_length": 112, "alphanum_fraction": 0.5839897807, "num_tokens": 3494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.56166422599607}}
{"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     univariate_distribution_estimator_impl.cpp\n* \\author   Collin Johnson\n*\n* Definition of implementations of the UnivariateDistributionEstimator for the subclasses of UnivariateDistribution:\n*\n*   - UnivariateGaussianDistribution\n*   - GammaDistribution\n*   - BetaDistribution\n*   - ExponentialDistribution\n*   - TruncatedGaussianDistribution\n*/\n\n#include <math/univariate_distribution_estimator_impl.h>\n#include <math/univariate_gaussian.h>\n#include <math/discrete_gaussian.h>\n#include <math/beta_distribution.h>\n#include <math/exponential_distribution.h>\n#include <math/gamma_distribution.h>\n#include <math/truncated_gaussian_distribution.h>\n#include <math/statistics.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace math\n{\n\nusing DistPtr = std::unique_ptr<UnivariateDistribution>;\n\n\ndouble log_likelihood_gamma_func(double k, double sumXi, double sumLogXi, std::size_t n)\n{\n    return (k-1)*sumXi - n*k - n*k*std::log(sumXi/(k*n)) - n*std::log(boost::math::tgamma(k));\n}\n\n\ndouble log_likelihood_gamma_deriv(double k, double sumXi, double sumLogXi, std::size_t n)\n{\n    return n*(std::log(k) - boost::math::digamma(k) - std::log(sumXi/n)) + sumLogXi;\n}\n\n\n\nDistPtr UnivariateGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                                      const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new UnivariateGaussianDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nUnivariateGaussianDistribution UnivariateGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                                                 const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if(var == 0.0)\n    {\n        std::cerr << \"WARNING: UnivariateGaussianDistributionEstimator: Variance in the data was 0. Setting variance to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return UnivariateGaussianDistribution(mean(dataBegin, dataEnd), var);\n}\n\n\nDistPtr DiscreteGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                                    const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{new DiscreteGaussianDistribution(estimate(dataBegin, dataEnd))};\n}\n\n\nDiscreteGaussianDistribution DiscreteGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                                             const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if(var == 0.0)\n    {\n        std::cerr << \"WARNING: DiscreteGaussianDistributionEstimator: Variance in the data was 0. Setting variance to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return DiscreteGaussianDistribution(mean(dataBegin, dataEnd), var);\n}\n\n\n\nDistPtr GammaDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                         const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{ new GammaDistribution(estimate(dataBegin, dataEnd)) };\n}\n\n\nGammaDistribution GammaDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                       const std::vector<double>::const_iterator dataEnd) const\n{\n    std::vector<double> filtered(dataBegin, dataEnd);\n    auto validDataEnd = std::remove_if(filtered.begin(), filtered.end(), [](double x) { return x <= 0.0; });\n\n    int numValidData = std::distance(filtered.begin(), validDataEnd);\n    assert(numValidData);\n\n    using namespace std::placeholders;\n\n    double sumXi    = std::accumulate(filtered.begin(), validDataEnd, 0.0);\n    double sumLogXi = 0.0;\n    for(auto val : boost::make_iterator_range(filtered.begin(), validDataEnd))\n    {\n        sumLogXi += std::log(val);\n    }\n\n    double s  = std::log(sumXi/numValidData) - sumLogXi/numValidData;\n    double k0 = (3.0 - s + std::sqrt(std::pow(s-3.0, 2.0) + 24.0*s)) / (12.0 * s);\n\n    //     NewtonRaphsonErrorFunc<double> newton(std::bind(log_likelihood_func,  _1, sumXi, sumLogXi, filtered.size()),\n    //                                           std::bind(log_likelihood_deriv, _1, sumXi, sumLogXi, filtered.size()));\n    //\n    //     double k     = find_single_root(newton, k0, 1e-5);\n    double k     = k0;\n    double theta = sumXi / (numValidData * k);\n    return GammaDistribution(k, theta);\n}\n\n\n\nDistPtr BetaDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                        const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{ new BetaDistribution(estimate(dataBegin, dataEnd)) };\n}\n\n\nBetaDistribution BetaDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                     const std::vector<double>::const_iterator dataEnd) const\n{\n    double mean     = math::mean    (dataBegin, dataEnd);\n    double variance = math::variance(dataBegin, dataEnd);\n\n    if(variance == 0.0)\n    {\n        std::cerr << \"WARNING: BetaDistributionEstimator: Variance of data was 0. Setting to 1e-4.\\n\";\n        variance = 1e-4;\n    }\n\n    if(variance < mean*(1-mean) && (variance > 0.0))\n    {\n        double alpha = mean         * ((mean * (1.0-mean) / variance) - 1.0);\n        double beta  = (1.0 - mean) * ((mean * (1.0-mean) / variance) - 1.0);\n        return BetaDistribution(alpha, beta);\n    }\n    else\n    {\n        std::cerr << \"ERROR: BetaDistributionEstimator: Could not use method-of-moments to find parameters. Mean:\" << mean << \" Variance:\" << variance << '\\n'\n                  << \" Variance should be less than \" << (mean * (1-mean)) << '\\n';\n        return BetaDistribution();\n    }\n}\n\n\nExponentialDistributionEstimator::ExponentialDistributionEstimator(double maxValue)\n: max_(maxValue)\n{\n}\n\n\nDistPtr ExponentialDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                               const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{ new ExponentialDistribution(estimate(dataBegin, dataEnd)) };\n}\n\n\nExponentialDistribution ExponentialDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                                   const std::vector<double>::const_iterator dataEnd) const\n{\n    double mean = math::mean(dataBegin, dataEnd);\n    if(mean > 0.0)\n    {\n        return ExponentialDistribution(1.0/mean, max_);\n    }\n    else\n    {\n        std::cerr << \"ERROR: ExponentialDistributionEstimator: Invalid mean for the data:\" << mean <<\" Must be greater than 0.\\n\";\n        return ExponentialDistribution(1.0, max_);\n    }\n}\n\n\nTruncatedGaussianDistributionEstimator::TruncatedGaussianDistributionEstimator(double lower, double upper)\n: lower_(lower)\n, upper_(upper)\n{\n}\n\n\nDistPtr TruncatedGaussianDistributionEstimator::estimateDistribution(const std::vector<double>::const_iterator dataBegin,\n                                                                     const std::vector<double>::const_iterator dataEnd) const\n{\n    return DistPtr{ new TruncatedGaussianDistribution(estimate(dataBegin, dataEnd)) };\n}\n\n\nTruncatedGaussianDistribution TruncatedGaussianDistributionEstimator::estimate(const std::vector<double>::const_iterator dataBegin,\n                                                                               const std::vector<double>::const_iterator dataEnd) const\n{\n    double var = variance(dataBegin, dataEnd);\n\n    if(var == 0.0)\n    {\n        std::cerr << \"WARNING: TruncatedGaussianDistributionEstimator: Variance in the data was 0. Setting variance to 1e-4.\\n\";\n        var = 1e-4;\n    }\n\n    return TruncatedGaussianDistribution(mean(dataBegin, dataEnd), var, lower_, upper_);\n}\n\n} // namespace math\n} // namespace vulcan\n", "meta": {"hexsha": "8e8e576395ff80a258f3908ff73751f5da034621", "size": 8622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/univariate_distribution_estimator_impl.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/math/univariate_distribution_estimator_impl.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/math/univariate_distribution_estimator_impl.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": 37.0042918455, "max_line_length": 158, "alphanum_fraction": 0.6550684296, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5616642245519499}}
{"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     em.cpp\n * \\author   Collin Johnson\n *\n * Definition of em_1d_linear and em_2d_fixed.\n */\n\n#include <math/clustering.h>\n#include <core/multivariate_gaussian.h>\n#include <math/statistics.h>\n#include <math/univariate_gaussian.h>\n#include <boost/range/iterator_range.hpp>\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace math\n{\n\ntemplate <class Data>\nusing DataIt = typename std::vector<Data>::const_iterator;\n\ntemplate<class Data, class Dist>\nstruct em_data_t\n{\n    int numClusters;\n    std::vector<int> clusterSizes;\n    std::vector<Dist> dists;\n    std::vector<int> assignments;\n    std::vector<Data> clusterData;  // temporary storage for computing distributions\n    double totalProb;\n};\n\ntemplate <class Data, class Dist, class ProbFunc, class Estimator>\nem_data_t<Data, Dist> run_em(DataIt<Data> begin,\n                             DataIt<Data> end,\n                             int k,\n                             int maxIterations,\n                             ProbFunc prob,\n                             Estimator estimator);\n\ntemplate <class Data, class Dist, class Estimator>\nvoid initialize_dists(DataIt<Data> begin, DataIt<Data> end, int k, em_data_t<Data, Dist>& dists, Estimator estimator);\n\ntemplate <class Data, class Dist, class Estimator>\nvoid calculate_dists(DataIt<Data> begin, DataIt<Data> end, em_data_t<Data, Dist>& dists, Estimator estimator);\n\ntemplate <class Data, class Dist, class ProbFunc>\nint assign_dists(DataIt<Data> begin, DataIt<Data> end, em_data_t<Data, Dist>& dists, ProbFunc prob);\n\ntemplate <class Data, class Dist, class ProbFunc>\nint most_probable_cluster(Data data, const em_data_t<Data, Dist>& dists, ProbFunc prob);\n\ntemplate <class Data, class Dist>\nvoid print_dists(const em_data_t<Data, Dist>& dists);\n\nstruct UnivariateEstimator\n{\n    UnivariateGaussianDistribution operator()(DataIt<double> begin, DataIt<double> end)\n    {\n        double var = variance(begin, end);\n        return UnivariateGaussianDistribution(mean(begin, end), std::max(var, 1e-10));\n    }\n};\n\nstruct MultivariateEstimator\n{\n    MultivariateGaussian operator()(DataIt<Point<float>> begin, DataIt<Point<float>> end)\n    {\n        Vector mean(2);\n        mean.zeros();\n        for(auto p : boost::make_iterator_range(begin, end))\n        {\n            mean[0] += p.x;\n            mean[1] += p.y;\n        }\n\n        if(std::distance(begin, end) > 0)\n        {\n            mean /= std::distance(begin, end);\n        }\n\n        Matrix cov(2, 2);\n        cov.zeros();\n        Vector diff(2);\n        for(auto p : boost::make_iterator_range(begin, end))\n        {\n            diff[0] = p.x - mean[0];\n            diff[1] = p.y - mean[1];\n\n            cov += diff * arma::trans(diff);\n        }\n\n        if(std::distance(begin, end) < 2)\n        {\n            cov.zeros();\n            cov.diag().fill(1e-16);\n        }\n        else\n        {\n            cov /= std::distance(begin, end) - 1;\n        }\n\n        try\n        {\n            Matrix inv = arma::inv(cov);\n        }\n        catch(std::exception& e)\n        {\n            std::cerr << \"Failed to take inverse: \" << e.what() << \" Matrix:\\n\" << cov;\n            cov.zeros();\n            cov.diag().fill(1e-16);\n        }\n\n        return MultivariateGaussian(mean, cov);\n    }\n};\n\n\ninline double probability_univariate(double value, const UnivariateGaussianDistribution& mean)\n{\n    return mean.likelihood(value);\n}\n\ninline double probability_multivariate(const Point<float>& value , const MultivariateGaussian& mean)\n{\n    Vector vec(2);\n    vec[0] = value.x;\n    vec[1] = value.y;\n    return mean.probability(vec);\n}\n\n\nclustering_result_t em_1d_linear(std::vector<double>::const_iterator begin,\n                                 std::vector<double>::const_iterator end,\n                                 int kMax,\n                                 int maxIterations)\n{\n    int dataSize = std::distance(begin, end);\n    kMax = std::min(kMax, dataSize);    // can't have more clusters than data!\n\n    std::vector<em_data_t<double, UnivariateGaussianDistribution>> attemptedMeans;\n    for(int k = 1; k <= kMax; ++k)\n    {\n        attemptedMeans.push_back(run_em<double, UnivariateGaussianDistribution>(begin,\n                                                                                end,\n                                                                                k,\n                                                                                maxIterations,\n                                                                                probability_univariate,\n                                                                                UnivariateEstimator()));\n    }\n\n    auto maxProbIt = std::max_element(attemptedMeans.begin(), attemptedMeans.end(), [](const auto& lhs, const auto& rhs) {\n        return lhs.totalProb < rhs.totalProb;\n    });\n\n    // Convert the em_data_t to a clustering_result_t\n    clustering_result_t results;\n    results.numClusters = maxProbIt->dists.size();\n    results.clusterSizes = std::move(maxProbIt->clusterSizes);\n    results.assignedCluster = std::move(maxProbIt->assignments);\n\n#ifdef DEBUG_RESULTS\n    std::cout << \"INFO: em_1d_linear: Cluster results:\\nNum clusters:\" << results.numClusters << \" Cluster sizes:\\n\";\n    for(std::size_t n = 0; n < minMeanIt->dists.size(); ++n)\n    {\n        std::cout << std::setprecision(5) << std::setw(5) << minMeanIt->dists[n] << \"->\" << results.clusterSizes[n] << '\\n';\n    }\n#endif\n\n    return results;\n}\n\n\nclustering_result_t em_2d_linear(std::vector<Point<float>>::const_iterator begin,\n                                 std::vector<Point<float>>::const_iterator end,\n                                 const int kMax,\n                                 const int maxIterations)\n{\n    std::vector<em_data_t<Point<float>, MultivariateGaussian>> clusters;\n\n    for(int k = 1; k < kMax; ++k)\n    {\n        clusters.push_back(run_em<Point<float>, MultivariateGaussian>(begin,\n                                                                      end,\n                                                                      k,\n                                                                      maxIterations,\n                                                                      probability_multivariate,\n                                                                      MultivariateEstimator()));\n    }\n\n    auto maxProbIt = std::max_element(clusters.begin(), clusters.end(), [](const auto& lhs, const auto& rhs) {\n        return lhs.totalProb < rhs.totalProb;\n    });\n\n    // Convert the em_data_t to a clustering_result_t\n    clustering_result_t results;\n    results.numClusters = maxProbIt->dists.size();\n    results.clusterSizes = std::move(maxProbIt->clusterSizes);\n    results.assignedCluster = std::move(maxProbIt->assignments);\n\n#ifdef DEBUG_RESULTS\n    std::cout << \"INFO: em_2d_fixed: Cluster results:\\nNum clusters:\" << results.numClusters << \" Cluster sizes:\\n\";\n    for(std::size_t n = 0; n < dists.dists.size(); ++n)\n    {\n        std::cout << std::setprecision(5) << std::setw(5) << dists.dists[n] << \"->\" << results.clusterSizes[n] << '\\n';\n    }\n#endif\n\n    return results;\n}\n\n\ntemplate <class Data, class Dist, class ProbFunc, class Estimator>\nem_data_t<Data, Dist> run_em(DataIt<Data> begin,\n                             DataIt<Data> end,\n                             int k,\n                             int maxIterations,\n                             ProbFunc prob,\n                             Estimator estimator)\n{\n    em_data_t<Data, Dist> dists;\n    dists.numClusters = k;\n    initialize_dists(begin, end, k, dists, estimator);\n    calculate_dists(begin, end, dists, estimator);\n\n    int numChanges = 0;\n    int numIterations = 0;\n\n    do\n    {\n        numChanges = assign_dists(begin, end, dists, prob);\n        calculate_dists(begin, end, dists, estimator);\n        ++numIterations;\n\n#ifdef DEBUG_KMEANS\n        std::cout << \"Iteration:\" << numIterations << \" Changes:\" << numChanges << '\\n';\n        print_dists(dists);\n#endif\n\n    } while((numChanges > 0) && (numIterations <= maxIterations));\n\n    // Once complete, sum the error amongst all the dists\n    for(std::size_t n = 0, size = std::distance(begin, end); n < size; ++n)\n    {\n        dists.totalProb += prob(*(begin + n), dists.dists[dists.assignments[n]]);\n    }\n\n    // If any cluster is empty, zero probability of correctness\n    for(std::size_t n = 0; n < dists.clusterSizes.size(); ++n)\n    {\n        if(dists.clusterSizes[n] == 0)\n        {\n            dists.totalProb = 0.0;\n        }\n    }\n\n#ifdef DEBUG_KMEANS\n    std::cout << \"INFO: em_1d: k:\" << k << \" Error:\" << dists.totalProb << \" Num iterations:\" << numIterations\n        << '\\n';\n    print_dists(dists);\n#endif\n\n    return dists;\n}\n\n\ntemplate <class Data, class Dist, class Estimator>\nvoid initialize_dists(DataIt<Data> begin, DataIt<Data> end, int k, em_data_t<Data, Dist>& dists, Estimator estimator)\n{\n    // Allocate the buffers\n    dists.clusterSizes.resize(k);\n    dists.dists.resize(k);\n    dists.assignments.resize(std::distance(begin, end));\n    std::iota(dists.assignments.begin(), dists.assignments.end(), 0);\n    dists.totalProb = 0.0;\n\n    std::transform(dists.assignments.begin(), dists.assignments.end(), dists.assignments.begin(), [k](int c) {\n        return c % k;\n    });\n}\n\n\ntemplate <class Data, class Dist, class Estimator>\nvoid calculate_dists(DataIt<Data> begin, DataIt<Data> end, em_data_t<Data, Dist>& dists, Estimator estimator)\n{\n    for(int cluster = 0; cluster < dists.numClusters; ++cluster)\n    {\n        dists.clusterData.clear();\n\n        for(std::size_t n = 0; n < dists.assignments.size(); ++n)\n        {\n            if(dists.assignments[n] == cluster)\n            {\n                dists.clusterData.push_back(*(begin + n));\n            }\n        }\n\n        dists.dists[cluster] = estimator(dists.clusterData.begin(), dists.clusterData.end());\n    }\n}\n\n\ntemplate <class Data, class Dist, class ProbFunc>\nint assign_dists(DataIt<Data> begin, DataIt<Data> end, em_data_t<Data, Dist>& dists, ProbFunc prob)\n{\n    std::fill(dists.clusterSizes.begin(), dists.clusterSizes.end(), 0);\n\n    int numChanged = 0;\n\n    for(std::size_t n = 0, size = std::distance(begin, end); n < size; ++n)\n    {\n        int newAssignment = most_probable_cluster(*(begin + n), dists, prob);\n        if(newAssignment != dists.assignments[n])\n        {\n            dists.assignments[n] = newAssignment;\n            ++numChanged;\n        }\n\n        ++dists.clusterSizes[newAssignment];\n    }\n\n    return numChanged;\n}\n\n\ntemplate <class Data, class Dist, class ProbFunc>\nint most_probable_cluster(Data data, const em_data_t<Data, Dist>& dists, ProbFunc prob)\n{\n    auto maxIt = std::max_element(dists.dists.begin(), dists.dists.end(), [&](auto& lhs, auto& rhs) {\n        return prob(data, lhs) < prob(data, rhs);\n    });\n\n    return std::distance(dists.dists.begin(), maxIt);\n}\n\n\ntemplate <class Data, class Dist>\nvoid print_dists(const em_data_t<Data, Dist>& dists)\n{\n    for(std::size_t n = 0; n < dists.dists.size(); ++n)\n    {\n        std::cout << std::setprecision(5) << std::setw(5) << dists.dists[n] << \"->\" << dists.clusterSizes[n] << '\\n';\n    }\n}\n\n} // namespace utils\n} // namespace vulcan\n", "meta": {"hexsha": "075ad5106b6b5680f8e10a233f89a196eb027168", "size": 11637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/em.cpp", "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_issues_repo_path": "src/math/em.cpp", "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_forks_repo_path": "src/math/em.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": 32.325, "max_line_length": 124, "alphanum_fraction": 0.5775543525, "num_tokens": 2734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5616642142051305}}
{"text": "// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com>\n// SPDX-License-Identifier: MIT\n\n#ifndef ADS_SIMULATION_BASIC_SIMULATION_3D_HPP\n#define ADS_SIMULATION_BASIC_SIMULATION_3D_HPP\n\n#include <array>\n#include <cstddef>\n\n#include <boost/range/counting_range.hpp>\n\n#include \"ads/lin/tensor.hpp\"\n#include \"ads/simulation/boundary.hpp\"\n#include \"ads/simulation/dimension.hpp\"\n#include \"ads/util/function_value.hpp\"\n#include \"ads/util/iter/product.hpp\"\n\nnamespace ads {\n\nclass basic_simulation_3d {\npublic:\n    virtual ~basic_simulation_3d() = default;\n\n    basic_simulation_3d() = default;\n    basic_simulation_3d(const basic_simulation_3d&) = delete;\n    basic_simulation_3d& operator=(const basic_simulation_3d&) = delete;\n    basic_simulation_3d(basic_simulation_3d&&) = delete;\n    basic_simulation_3d& operator=(basic_simulation_3d&&) = delete;\n\nprotected:\n    using vector_type = lin::tensor<double, 3>;\n    using vector_view = lin::tensor_view<double, 3>;\n    using value_type = function_value_3d;\n\n    using index_type = std::array<int, 3>;\n    using index_1d_iter_type = boost::counting_iterator<int>;\n    using index_iter_type = util::iter_product3<index_1d_iter_type, index_type>;\n    using index_range = boost::iterator_range<index_iter_type>;\n\n    using point_type = std::array<double, 3>;\n\n    struct L2 {\n        double operator()(value_type a) const { return a.val * a.val; }\n    };\n\n    struct H10 {\n        double operator()(value_type a) const { return a.dx * a.dx + a.dy * a.dy + a.dz * a.dz; }\n    };\n\n    struct H1 {\n        double operator()(value_type a) const {\n            return a.val * a.val + a.dx * a.dx + a.dy * a.dy + a.dz * a.dz;\n        }\n    };\n\n    value_type eval_basis(index_type e, index_type q, index_type a, const dimension& x,\n                          const dimension& y, const dimension& z) const {\n        auto loc = dof_global_to_local(e, a, x, y, z);\n\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        const auto& bz = z.basis;\n\n        double B1 = bx.b[e[0]][q[0]][0][loc[0]];\n        double B2 = by.b[e[1]][q[1]][0][loc[1]];\n        double B3 = bz.b[e[2]][q[2]][0][loc[2]];\n        double dB1 = bx.b[e[0]][q[0]][1][loc[0]];\n        double dB2 = by.b[e[1]][q[1]][1][loc[1]];\n        double dB3 = bz.b[e[2]][q[2]][1][loc[2]];\n\n        double v = B1 * B2 * B3;\n        double dxv = dB1 * B2 * B3;\n        double dyv = B1 * dB2 * B3;\n        double dzv = B1 * B2 * dB3;\n\n        return {v, dxv, dyv, dzv};\n    }\n\n    double laplacian(index_type e, index_type q, index_type a, const dimension& x,\n                     const dimension& y, const dimension& z) const {\n        auto loc = dof_global_to_local(e, a, x, y, z);\n\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        const auto& bz = z.basis;\n\n        double B1 = bx.b[e[0]][q[0]][0][loc[0]];\n        double B2 = by.b[e[1]][q[1]][0][loc[1]];\n        double B3 = bz.b[e[2]][q[2]][0][loc[2]];\n\n        double ddB1 = bx.b[e[0]][q[0]][2][loc[0]];\n        double ddB2 = by.b[e[1]][q[1]][2][loc[1]];\n        double ddB3 = by.b[e[2]][q[2]][2][loc[2]];\n\n        return ddB1 * B2 * B3 + B1 * ddB2 * B3 + B1 * B2 * ddB3;\n    }\n\n    template <typename Sol>\n    value_type eval(const Sol& v, index_type e, index_type q, const dimension& x,\n                    const dimension& y, const dimension& z) const {\n        value_type u{};\n        for (auto b : dofs_on_element(e, x, y, z)) {\n            double c = v(b[0], b[1], b[2]);\n            value_type B = eval_basis(e, q, b, x, y, z);\n            u += c * B;\n        }\n        return u;\n    }\n\n    index_range elements(const dimension& x, const dimension& y, const dimension& z) const {\n        return util::product_range<index_type>(x.element_indices(), y.element_indices(),\n                                               z.element_indices());\n    }\n\n    index_range quad_points(const dimension& x, const dimension& y, const dimension& z) const {\n        auto rx = boost::counting_range(0, x.basis.quad_order);\n        auto ry = boost::counting_range(0, y.basis.quad_order);\n        auto rz = boost::counting_range(0, z.basis.quad_order);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range dofs_on_element(index_type e, const dimension& x, const dimension& y,\n                                const dimension& z) const {\n        auto rx = x.basis.dof_range(e[0]);\n        auto ry = y.basis.dof_range(e[1]);\n        auto rz = z.basis.dof_range(e[2]);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range elements_supporting_dof(index_type dof, const dimension& x, const dimension& y,\n                                        const dimension& z) const {\n        auto rx = x.basis.element_range(dof[0]);\n        auto ry = y.basis.element_range(dof[1]);\n        auto rz = z.basis.element_range(dof[2]);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    bool supported_in(index_type dof, index_type e, const dimension& x, const dimension& y,\n                      const dimension& z) const {\n        auto xrange = x.basis.element_ranges[dof[0]];\n        auto yrange = y.basis.element_ranges[dof[1]];\n        auto zrange = z.basis.element_ranges[dof[2]];\n\n        return e[0] >= xrange.first && e[0] <= xrange.second && e[1] >= yrange.first\n            && e[1] <= yrange.second && e[2] >= zrange.first && e[2] <= zrange.second;\n    }\n\n    index_type dof_global_to_local(index_type e, index_type a, const dimension& x,\n                                   const dimension& y, const dimension& z) const {\n        const auto& bx = x.basis;\n        const auto& by = y.basis;\n        const auto& bz = z.basis;\n        return {{a[0] - bx.first_dof(e[0]), a[1] - by.first_dof(e[1]), a[2] - bz.first_dof(e[2])}};\n    }\n\n    template <typename RHS>\n    void update_global_rhs(RHS& global, const vector_type& local, index_type e, const dimension& x,\n                           const dimension& y, const dimension& z) const {\n        for (auto a : dofs_on_element(e, x, y, z)) {\n            auto loc = dof_global_to_local(e, a, x, y, z);\n            global(a[0], a[1], a[2]) += local(loc[0], loc[1], loc[2]);\n        }\n    }\n\n    index_range dofs(const dimension& x, const dimension& y, const dimension& z) const {\n        auto rx = boost::counting_range(0, x.dofs());\n        auto ry = boost::counting_range(0, y.dofs());\n        auto rz = boost::counting_range(0, z.dofs());\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range internal_dofs(const dimension& x, const dimension& y, const dimension& z) const {\n        auto rx = boost::counting_range(1, x.dofs() - 1);\n        auto ry = boost::counting_range(1, y.dofs() - 1);\n        auto rz = boost::counting_range(1, z.dofs() - 1);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    double jacobian(index_type e, const dimension& x, const dimension& y,\n                    const dimension& z) const {\n        return x.basis.J[e[0]] * y.basis.J[e[1]] * z.basis.J[e[2]];\n    }\n\n    double weight(index_type q, const dimension& x, const dimension& y, const dimension& z) const {\n        return x.basis.w[q[0]] * y.basis.w[q[1]] * z.basis.w[q[2]];\n    }\n\n    point_type point(index_type e, index_type q, const dimension& x, const dimension& y,\n                     const dimension& z) const {\n        double px = x.basis.x[e[0]][q[0]];\n        double py = y.basis.x[e[1]][q[1]];\n        double pz = z.basis.x[e[2]][q[2]];\n        return {px, py, pz};\n    }\n\n    auto overlapping_dofs(int dof, int begin, int end, const dimension& x) const {\n        using std::max;\n        using std::min;\n\n        auto minx = max(begin, dof - x.B.degree);\n        auto maxx = min(end, dof + x.B.degree + 1);\n\n        return boost::counting_range(minx, maxx);\n    }\n\n    index_range overlapping_dofs(index_type dof, const dimension& x, const dimension& y,\n                                 const dimension& z) const {\n        auto rx = overlapping_dofs(dof[0], 0, x.dofs(), x);\n        auto ry = overlapping_dofs(dof[1], 0, y.dofs(), y);\n        auto rz = overlapping_dofs(dof[1], 0, z.dofs(), z);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range overlapping_dofs(index_type dof, const dimension& Ux, const dimension& Uy,\n                                 const dimension& Uz, const dimension& Vx, const dimension& Vy,\n                                 const dimension& Vz) const {\n        auto xrange = Ux.basis.element_ranges[dof[0]];\n        auto yrange = Uy.basis.element_ranges[dof[1]];\n        auto zrange = Uz.basis.element_ranges[dof[2]];\n\n        auto x0 = Vx.basis.first_dof(xrange.first);\n        auto x1 = Vx.basis.last_dof(xrange.second) + 1;\n\n        auto y0 = Vy.basis.first_dof(yrange.first);\n        auto y1 = Vy.basis.last_dof(yrange.second) + 1;\n\n        auto z0 = Vz.basis.first_dof(zrange.first);\n        auto z1 = Vz.basis.last_dof(zrange.second) + 1;\n\n        auto rx = boost::counting_range(x0, x1);\n        auto ry = boost::counting_range(y0, y1);\n        auto rz = boost::counting_range(z0, z1);\n\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    index_range overlapping_internal_dofs(index_type dof, const dimension& x, const dimension& y,\n                                          const dimension& z) const {\n        auto rx = overlapping_dofs(dof[0], 1, x.dofs() - 1, x);\n        auto ry = overlapping_dofs(dof[1], 1, y.dofs() - 1, y);\n        auto rz = overlapping_dofs(dof[2], 1, z.dofs() - 1, z);\n        return util::product_range<index_type>(rx, ry, rz);\n    }\n\n    int linear_index(index_type dof, const dimension& x, const dimension& y,\n                     const dimension& z) const {\n        auto order = reverse_ordering<3>({x.dofs(), y.dofs(), z.dofs()});\n        return order.linear_index(dof[0], dof[1], dof[2]);\n    }\n\n    template <typename Fun>\n    void for_boundary_dofs(const dimension& x, const dimension& y, const dimension& z,\n                           Fun&& fun) const {\n        for (auto jx = 0; jx < x.dofs(); ++jx) {\n            for (auto jy = 0; jy < y.dofs(); ++jy) {\n                fun({jx, jy, 0});\n                fun({jx, jy, z.dofs() - 1});\n            }\n        }\n        for (auto jx = 0; jx < x.dofs(); ++jx) {\n            for (auto jz = 1; jz < z.dofs() - 1; ++jz) {\n                fun({jx, 0, jz});\n                fun({jx, y.dofs() - 1, jz});\n            }\n        }\n        for (auto jy = 1; jy < y.dofs() - 1; ++jy) {\n            for (auto jz = 1; jz < z.dofs() - 1; ++jz) {\n                fun({0, jy, jz});\n                fun({x.dofs() - 1, jy, jz});\n            }\n        }\n    }\n\n    bool is_boundary(int dof, const dimension& x) const { return dof == 0 || dof == x.dofs() - 1; }\n\n    bool is_boundary(index_type dof, const dimension& x, const dimension& y,\n                     const dimension& z) const {\n        return is_boundary(dof[0], x) || is_boundary(dof[1], y) || is_boundary(dof[2], z);\n    }\n\n    template <typename Norm, typename Fun>\n    double norm(const dimension& Ux, const dimension& Uy, const dimension& Uz, Norm&& norm,\n                Fun&& fun) const {\n        double val = 0;\n\n        for (auto e : elements(Ux, Uy, Uz)) {\n            double J = jacobian(e, Ux, Uy, Uz);\n            for (auto q : quad_points(Ux, Uy, Uz)) {\n                double w = weight(q, Ux, Uy, Uz);\n                auto x = point(e, q, Ux, Uy, Uz);\n                auto d = fun(x);\n                val += norm(d) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Fun>\n    double normL2(const dimension& Ux, const dimension& Uy, const dimension& Uz, Fun&& fun) const {\n        return norm(Ux, Uy, Uz, L2{}, fun);\n    }\n\n    template <typename Fun>\n    double normH1(const dimension& Ux, const dimension& Uy, const dimension& Uz, Fun&& fun) const {\n        return norm(Ux, Uy, Uz, H1{}, fun);\n    }\n\n    template <typename Sol, typename Norm>\n    double norm(const Sol& u, const dimension& Ux, const dimension& Uy, const dimension& Uz,\n                Norm&& norm) const {\n        double val = 0;\n\n        for (auto e : elements(Ux, Uy, Uz)) {\n            double J = jacobian(e, Ux, Uy, Uz);\n            for (auto q : quad_points(Ux, Uy, Uz)) {\n                double w = weight(q, Ux, Uy, Uz);\n                value_type uu = eval(u, e, q, Ux, Uy, Uz);\n                val += norm(uu) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Sol>\n    double normL2(const Sol& u, const dimension& Ux, const dimension& Uy,\n                  const dimension& Uz) const {\n        return norm(u, Ux, Uy, Uz, L2{});\n    }\n\n    template <typename Sol>\n    double normH1(const Sol& u, const dimension& Ux, const dimension& Uy,\n                  const dimension& Uz) const {\n        return norm(u, Ux, Uy, Uz, H1{});\n    }\n\n    template <typename Sol, typename Fun, typename Norm>\n    double error(const Sol& u, const dimension& Ux, const dimension& Uy, const dimension& Uz,\n                 Norm&& norm, Fun&& fun) const {\n        double error = 0;\n\n        for (auto e : elements(Ux, Uy, Uz)) {\n            double J = jacobian(e, Ux, Uy, Uz);\n            for (auto q : quad_points(Ux, Uy, Uz)) {\n                double w = weight(q, Ux, Uy, Uz);\n                auto x = point(e, q, Ux, Uy, Uz);\n                value_type uu = eval(u, e, q, Ux, Uy, Uz);\n\n                auto d = uu - fun(x);\n                error += norm(d) * w * J;\n            }\n        }\n        return std::sqrt(error);\n    }\n\n    template <typename Sol, typename Fun, typename Norm>\n    double error_relative(const Sol& u, const dimension& Ux, const dimension& Uy,\n                          const dimension& Uz, Norm&& norm, Fun&& fun) const {\n        double error = 0;\n        double ref_norm = 0;\n\n        for (auto e : elements(Ux, Uy, Uz)) {\n            double J = jacobian(e, Ux, Uy, Uz);\n            for (auto q : quad_points(Ux, Uy, Uz)) {\n                double w = weight(q, Ux, Uy, Uz);\n                auto x = point(e, q, Ux, Uy, Uz);\n                value_type uu = eval(u, e, q, Ux, Uy, Uz);\n                auto fx = fun(x);\n\n                error += norm(uu - fx) * w * J;\n                ref_norm += norm(fx) * w * J;\n            }\n        }\n        return std::sqrt(error / ref_norm);\n    }\n\n    template <typename Sol, typename Fun>\n    double errorL2(const Sol& u, const dimension& Ux, const dimension& Uy, const dimension& Uz,\n                   Fun&& fun) const {\n        return error(u, Ux, Uy, Uz, L2{}, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double error_relative_L2(const Sol& u, const dimension& Ux, const dimension& Uy,\n                             const dimension& Uz, Fun&& fun) const {\n        return error_relative(u, Ux, Uy, Uz, L2{}, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double errorH1(const Sol& u, const dimension& Ux, const dimension& Uy, const dimension& Uz,\n                   Fun&& fun) const {\n        return error(u, Ux, Uy, Uz, H1{}, fun);\n    }\n\n    template <typename Sol, typename Fun>\n    double error_relative_H1(const Sol& u, const dimension& Ux, const dimension& Uy,\n                             const dimension& Uz, Fun&& fun) const {\n        return error_relative(u, Ux, Uy, Uz, H1{}, fun);\n    }\n\n    template <typename Sol>\n    double norm_rot(const Sol& X, const Sol& Y, const Sol& Z,                          //\n                    const dimension& U1x, const dimension& U1y, const dimension& U1z,  //\n                    const dimension& U2x, const dimension& U2y, const dimension& U2z,  //\n                    const dimension& U3x, const dimension& U3y, const dimension& U3z) const {\n        double val = 0;\n\n        for (auto e : elements(U1x, U1y, U1z)) {\n            double J = jacobian(e, U1x, U1y, U1z);\n            for (auto q : quad_points(U1x, U1y, U1z)) {\n                double w = weight(q, U1x, U1y, U1z);\n                auto x = eval(X, e, q, U1x, U1y, U1z);\n                auto y = eval(Y, e, q, U2x, U2y, U2z);\n                auto z = eval(Z, e, q, U3x, U3y, U3z);\n\n                auto rx = z.dy - y.dz;\n                auto ry = x.dz - z.dx;\n                auto rz = y.dx - x.dy;\n\n                val += (rx * rx + ry * ry + rz * rz) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Sol, typename FunX, typename FunY, typename FunZ>\n    double error_rot(const Sol& X, const Sol& Y, const Sol& Z,                          //\n                     const dimension& U1x, const dimension& U1y, const dimension& U1z,  //\n                     const dimension& U2x, const dimension& U2y, const dimension& U2z,  //\n                     const dimension& U3x, const dimension& U3y, const dimension& U3z,  //\n                     FunX&& fx, FunY&& fy, FunZ&& fz) const {\n        double val = 0;\n\n        for (auto e : elements(U1x, U1y, U1z)) {\n            double J = jacobian(e, U1x, U1y, U1z);\n            for (auto q : quad_points(U1x, U1y, U1z)) {\n                auto p = point(e, q, U1x, U2y, U3z);\n                double w = weight(q, U1x, U2y, U3z);\n                auto x = eval(X, e, q, U1x, U1y, U1z) - fx(p);\n                auto y = eval(Y, e, q, U2x, U2y, U2z) - fy(p);\n                auto z = eval(Z, e, q, U3x, U3y, U3z) - fz(p);\n\n                auto rx = z.dy - y.dz;\n                auto ry = x.dz - z.dx;\n                auto rz = y.dx - x.dy;\n\n                val += (rx * rx + ry * ry + rz * rz) * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n\n    template <typename Sol>\n    double norm_div(const Sol& X, const Sol& Y, const Sol& Z,                          //\n                    const dimension& U1x, const dimension& U1y, const dimension& U1z,  //\n                    const dimension& U2x, const dimension& U2y, const dimension& U2z,  //\n                    const dimension& U3x, const dimension& U3y, const dimension& U3z) const {\n        double val = 0;\n\n        for (auto e : elements(U1x, U1y, U1z)) {\n            double J = jacobian(e, U1x, U1y, U1z);\n            for (auto q : quad_points(U1x, U1y, U1z)) {\n                double w = weight(q, U1x, U1y, U1z);\n                auto x = eval(X, e, q, U1x, U1y, U1z);\n                auto y = eval(Y, e, q, U2x, U2y, U2z);\n                auto z = eval(Z, e, q, U3x, U3y, U3z);\n\n                auto v = x.dx + y.dy + z.dz;\n                val += v * v * w * J;\n            }\n        }\n        return std::sqrt(val);\n    }\n};\n\n}  // namespace ads\n\n#endif  // ADS_SIMULATION_BASIC_SIMULATION_3D_HPP\n", "meta": {"hexsha": "6c89cbd78a0ccfa61ac4f12953f6591c40b075ea", "size": 18582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ads/simulation/basic_simulation_3d.hpp", "max_stars_repo_name": "Pan-Maciek/iga-ads", "max_stars_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T00:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T00:53:00.000Z", "max_issues_repo_path": "include/ads/simulation/basic_simulation_3d.hpp", "max_issues_repo_name": "Pan-Maciek/iga-ads", "max_issues_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T22:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T15:18:00.000Z", "max_forks_repo_path": "include/ads/simulation/basic_simulation_3d.hpp", "max_forks_repo_name": "Pan-Maciek/iga-ads", "max_forks_repo_head_hexsha": "4744829c98cba4e9505c5c996070119e73ba18fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-04-13T19:42:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T18:46:24.000Z", "avg_line_length": 38.8744769874, "max_line_length": 99, "alphanum_fraction": 0.5348186417, "num_tokens": 5423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.561657055778617}}
{"text": "/*Copyright (c) 2021 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/*\n * transforms.cpp\n *\n */\n\n#include <math.h>\n#include <algorithm>\n#include <array>\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"BasisSet.h\"\n#include \"gto_ordering.h\"\n#include \"Shell.h\"\n#include \"utils.h\"\n\nvoid uniform_cart_norm(Eigen::MatrixXd &my_mat, BasisSet &bs)\n{\n\tunsigned int bf_idx = 0;\n\tfor(auto&shell:bs.basis)\n\t{\n\t\tstd::vector<std::array<size_t,3>> order = opencap_carts_ordering(shell.l);\n\t\tfor(unsigned int i=0;i<shell.num_carts();i++)\n\t\t{\n\t\t\tstd::array<size_t,3> cart = order[i];\n\t\t\tdouble scale = sqrt(fact2(2*shell.l-1)/fact2(2*cart[0]-1)\n\t\t\t\t\t/fact2(2*cart[1]-1)/fact2(2*cart[2]-1));\n\t\t\tmy_mat.col(bf_idx+i) = my_mat.col(bf_idx+i)*scale;\n\t\t\tmy_mat.row(bf_idx+i) = my_mat.row(bf_idx+i)*scale;\n\t\t}\n\t\tbf_idx += shell.num_carts();\n\t}\n}\n\n//DOI: 10.1002/qua.560540202\n//Last part of eqn 15, for M<0 we want imaginary part, for M>0 we want real part\ndouble term4(int M, int exp_num)\n{\n\tif(M<0)\n\t{\n\t\t//integer powers will be real\n\t\tif(exp_num%2==0)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn (exp_num-1)%4==0 ? 1:-1;\n\t}\n\telse\n\t{\n\t\t//half-integer powers will be imaginary\n\t\tif(exp_num%2!=0)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn exp_num%4==0 ? 1:-1;\n\t}\n}\n\n//DOI: 10.1002/qua.560540202\n//Equation 15, currently assumes fully normalized cartesians. Will add non-fully normalized carts soon enough...\ndouble get_coeff(int L, int m, int lx, int ly, int lz)\n{\n      auto abs_m = std::abs(m);\n      if ((lx + ly - abs_m)%2)\n        return 0.0;\n      auto j = (lx + ly - abs_m)/2;\n      if (j < 0)\n        return 0.0;\n      auto term1 = sqrt( fact(2*lx)*fact(2*ly)*fact(2*lz)*fact(L)*fact(L-abs_m)\n    \t\t  \t  \t  \t  /fact(2*L)/fact(lx)/fact(ly)/fact(lz)/fact(L+abs_m));\n      term1/=fact(L);\n      term1/=pow(2,L);\n      auto term2 = 0;\n      for(int i=0;i<=(L-abs_m)/2;i++)\n      {\n    \t  term2+=binom(L,i)*binom(i,j)\n    \t\t\t  *parity(i) * fact(2*(L-i))\n\t\t\t\t  /fact(L-abs_m-2*i);\n      }\n      double term3=0;\n      for (int k=0;k<=j;k++)\n    \t  term3+=binom(j,k)*binom(abs_m,lx-2*k)*term4(m,abs_m - lx +2*k);\n      // for m!=0, real solid harmonics are linear combinations of complex ones\n      // R+(l,m) = ( Y(l,m) + Y(l,-m) )/ sqrt(2) ;  R-(l,m) = ( Y(l,m) - Y(l,-m) )/ sqrt(-2)\n      double result = (m == 0) ? term1*term2*term3 : M_SQRT2*term1*term2*term3;\n      return result;\n}\n\nEigen::MatrixXd get_trans_mat(Shell &shell)\n{\n\tstd::vector<std::array<size_t,3>> cart_order = opencap_carts_ordering(shell.l);\n\tstd::vector<int> sph_order = opencap_harmonic_ordering(shell.l);\n\tEigen::MatrixXd trans_mat(shell.num_bf(),shell.num_carts());\n\tfor(size_t i=0;i<shell.num_bf();i++)\n\t{\n\t\tint M = sph_order[i];\n\t\tfor(size_t j=0;j<shell.num_carts();j++)\n\t\t{\n\t\t\tstd::array<size_t,3> cart = cart_order[j];\n\t\t\ttrans_mat(i,j) = get_coeff(shell.l,M,cart[0],cart[1],cart[2]);\n\t\t}\n\t}\n\treturn trans_mat;\n}\n\nEigen::MatrixXd transform_block(Shell &shell1, Shell &shell2, Eigen::MatrixXd cart_block)\n{\n\n\tif(!shell1.pure && !shell2.pure)\n\t\treturn cart_block;\n\telse if(shell1.pure && !shell2.pure)\n\t\treturn get_trans_mat(shell1)*cart_block;\n\telse if(shell1.pure && shell2.pure)\n\t\treturn get_trans_mat(shell1)*cart_block*get_trans_mat(shell2).transpose();\n\telse\n\t\treturn cart_block*get_trans_mat(shell2).transpose();\n}\n\nvoid cart2spherical(Eigen::MatrixXd &cart_ints, Eigen::MatrixXd &spherical_ints, BasisSet &bs)\n{\n\t//indices for first basis function for cart and spherical matrices\n\tunsigned int cart_row_idx = 0;\n\tunsigned int sph_row_idx = 0;\n\tfor(auto shell1:bs.basis)\n\t{\n\t\t//indices for 2nd basis function for cart and spherical matrices\n\t\tunsigned int cart_col_idx = 0;\n\t\tunsigned int sph_col_idx = 0;\n\t\tfor(auto shell2:bs.basis)\n\t\t{\n\t\t\tEigen::MatrixXd cart_block = cart_ints.block(cart_row_idx,cart_col_idx, shell1.num_carts(),shell2.num_carts());\n\t\t\tspherical_ints.block(sph_row_idx,sph_col_idx,shell1.num_bf(),shell2.num_bf())\n\t\t\t\t\t\t\t= transform_block(shell1,shell2,cart_block);\n\t\t\tcart_col_idx+=shell2.num_carts();\n\t\t\tsph_col_idx+=shell2.num_bf();\n\t\t}\n\t\tcart_row_idx+=shell1.num_carts();\n\t\tsph_row_idx+=shell1.num_bf();\n\t}\n}\n\n", "meta": {"hexsha": "105f8f57516e6eeb6d21650f617f3d0917506672", "size": 5071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/transforms.cpp", "max_stars_repo_name": "SoubhikM/opencap", "max_stars_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T15:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:51:26.000Z", "max_issues_repo_path": "opencap/src/transforms.cpp", "max_issues_repo_name": "SoubhikM/opencap", "max_issues_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T07:03:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:37:39.000Z", "max_forks_repo_path": "opencap/src/transforms.cpp", "max_forks_repo_name": "SoubhikM/opencap", "max_forks_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T20:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:54:52.000Z", "avg_line_length": 31.4968944099, "max_line_length": 114, "alphanum_fraction": 0.6846775784, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5616570501257306}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\r\n//\r\n// Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla Public License\r\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\r\n// obtain one at http://mozilla.org/MPL/2.0/.\r\n#include \"bbw.h\"\r\n#include \"mosek_quadprog.h\"\r\n#include \"../harmonic.h\"\r\n#include \"../slice_into.h\"\r\n#include <Eigen/Sparse>\r\n#include <iostream>\r\n#include <cstdio>\r\n\r\n\r\ntemplate <\r\n  typename DerivedV,\r\n  typename DerivedEle,\r\n  typename Derivedb,\r\n  typename Derivedbc,\r\n  typename DerivedW>\r\nIGL_INLINE bool igl::mosek::bbw(\r\n  const Eigen::PlainObjectBase<DerivedV> & V,\r\n  const Eigen::PlainObjectBase<DerivedEle> & Ele,\r\n  const Eigen::PlainObjectBase<Derivedb> & b,\r\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\r\n  igl::BBWData & data,\r\n  igl::mosek::MosekData & mosek_data,\r\n  Eigen::PlainObjectBase<DerivedW> & W\r\n  )\r\n{\r\n  using namespace std;\r\n  using namespace Eigen;\r\n  assert(!data.partition_unity && \"partition_unity not implemented yet\");\r\n  // number of domain vertices\r\n  int n = V.rows();\r\n  // number of handles\r\n  int m = bc.cols();\r\n  // Build biharmonic operator\r\n  Eigen::SparseMatrix<typename DerivedV::Scalar> Q;\r\n  harmonic(V,Ele,2,Q);\r\n  W.derived().resize(n,m);\r\n  // No linear terms\r\n  VectorXd c = VectorXd::Zero(n);\r\n  // No linear constraints\r\n  SparseMatrix<typename DerivedW::Scalar> A(0,n);\r\n  VectorXd uc(0,1),lc(0,1);\r\n  // Upper and lower box constraints (Constant bounds)\r\n  VectorXd ux = VectorXd::Ones(n);\r\n  VectorXd lx = VectorXd::Zero(n);\r\n  // Loop over handles\r\n  for(int i = 0;i<m;i++)\r\n  {\r\n    if(data.verbosity >= 1)\r\n    {\r\n      cout<<\"BBW: Computing weight for handle \"<<i+1<<\" out of \"<<m<<\r\n        \".\"<<endl;\r\n    }\r\n    VectorXd bci = bc.col(i);\r\n    VectorXd Wi;\r\n    // impose boundary conditions via bounds\r\n    slice_into(bci,b,ux);\r\n    slice_into(bci,b,lx);\r\n    bool r = mosek_quadprog(Q,c,0,A,lc,uc,lx,ux,mosek_data,Wi);\r\n    if(!r)\r\n    {\r\n      return false;\r\n    }\r\n    W.col(i) = Wi;\r\n  }\r\n#ifndef NDEBUG\r\n    const double min_rowsum = W.rowwise().sum().array().abs().minCoeff();\r\n    if(min_rowsum < 0.1)\r\n    {\r\n      cerr<<\"bbw.cpp: Warning, minimum row sum is very low. Consider more \"\r\n        \"active set iterations or enforcing partition of unity.\"<<endl;\r\n    }\r\n#endif\r\n\r\n  return true;\r\n}\r\n\r\n#ifdef IGL_STATIC_LIBRARY\r\n// Explicit template instantiation\r\ntemplate bool igl::mosek::bbw<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::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<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, igl::BBWData&, igl::mosek::MosekData&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\r\n#endif\r\n\r\n", "meta": {"hexsha": "103b08dafa1db23277994895702f9dd379dbc791", "size": 3127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/mosek/bbw.cpp", "max_stars_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_stars_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "igl/mosek/bbw.cpp", "max_issues_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_issues_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "igl/mosek/bbw.cpp", "max_forks_repo_name": "sabinaRachev/3D-Snake-Game-Final-Project", "max_forks_repo_head_hexsha": "5c1f2044d848f24d6ce60dc61411393b503c8da2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1348314607, "max_line_length": 629, "alphanum_fraction": 0.6360729133, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.5616570390455701}}
{"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_EDWILLIAMS_AVFORM_INTERMEDIATE_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_RANDOM_STRATEGIES_SPHERICAL_EDWILLIAMS_AVFORM_INTERMEDIATE_HPP\n\n#include <random>\n#include <cmath>\n\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/geometry/arithmetic/arithmetic.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\ntemplate\n<\n    typename Point,\n    typename DomainGeometry\n>\nstruct edwilliams_avform_intermediate\n{\n    edwilliams_avform_intermediate(DomainGeometry const& g) {}\n    bool equals(DomainGeometry const& l_domain,\n                DomainGeometry const& r_domain,\n                edwilliams_avform_intermediate const& r_strategy) const\n    {\n        return boost::geometry::equals(l_domain.domain(), r_domain.domain());\n    }\n\n    // The following implementation is adapted from\n    // https://www.edwilliams.org/avform.htm#Intermediate\n    template\n    <\n        typename LengthType,\n        typename PointIn\n    >\n    static Point map(PointIn const& p1, PointIn const& p2, LengthType const& f)\n    {\n        Point out;\n        const auto lat1 = get_as_radian<1>(p1);\n        const auto lon1 = get_as_radian<0>(p1);\n        const auto lat2 = get_as_radian<1>(p2);\n        const auto lon2 = get_as_radian<0>(p2);\n        LengthType const d = std::acos(\n              std::sin(lat1) * std::sin(lat2)\n            + std::cos(lat1) * std::cos(lat2) * std::cos(lon1 - lon2));\n        LengthType const A = std::sin( ( 1 - f ) * d ) / std::sin(d);\n        LengthType const B = std::sin( f * d ) / std::sin( d );\n        LengthType const x = A * std::cos(lat1) * std::cos(lon1)\n                           + B * std::cos(lat2) * std::cos(lon2);\n        LengthType const y = A * std::cos(lat1) * std::sin(lon1)\n                           + B * std::cos(lat2) * std::sin(lon2);\n        LengthType const z = A * std::sin(lat1) + B * std::sin(lat2);\n        LengthType const lat = std::atan2(z, std::sqrt(x * x + y * y));\n        LengthType const lon = std::atan2(y, x);\n        set_from_radian<1>(out, lat);\n        set_from_radian<0>(out, lon);\n        return out;\n    }\n\n    template<typename Gen>\n    Point apply(Gen& g, DomainGeometry const& d)\n    {\n        typedef typename select_most_precise\n            <\n                typename coordinate_type<DomainGeometry>::type,\n                double\n            >::type sample_type;\n        std::uniform_real_distribution<sample_type> real_dist(0, 1);\n        return map<sample_type>(d, real_dist(g));\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    segment_tag,\n    single_tag,\n    2,\n    spherical_tag\n> : public edwilliams_avform_intermediate<Point, DomainGeometry> {\n    typedef edwilliams_avform_intermediate<Point, DomainGeometry> 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_EDWILLIAMS_AVFORM_INTERMEDIATE_HPP\n", "meta": {"hexsha": "28df18f08f8a6d8cdbe2d8b47f394e39c5d935f0", "size": 3581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/random/strategies/spherical/edwilliams_avform_intermediate.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/edwilliams_avform_intermediate.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/edwilliams_avform_intermediate.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": 31.9732142857, "max_line_length": 98, "alphanum_fraction": 0.6662943312, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.891811036811578, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.5616399517838317}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <fstream>\n#include <iostream>\n#include <omp.h>\n#include <cmath>\n#include <complex>\n#include <cstdio>\n#include <chrono>\n#include <string>\n#include <armadillo>\n#include <vector>\n#include \"wignerSymbols.h\"\n//#include \"wigner/gaunt.hpp\"\n\n//using namespace std::chrono;\nusing namespace arma;\n\nstatic const double kB = 1.3806504e-23;         // J/K\nstatic const double NA = 6.02214179e23;         // 1/mol\nstatic const double EHARTREE = 4.35974434e-18;  // J/Hartree\nstatic const double AMU = 1.660538921e-27;      // kg/amu\nstatic const double HBAR = 1.054571726e-34;     // J.s\nstatic const double HBAR1 = HBAR / EHARTREE;    // Hartree.s\nstatic const double HBAR2 = HBAR * 1e20 / AMU;  // amu.Å^2/s\nstatic const double SCH4 = 186.25; // J/mol.K\n\nMat<complex<double>> getHamiltonian(int lmax, double Ix, double Iy, double Iz, std::vector<double>& a);\nSpMat<complex<double>> getSparseHam(int lmax, double Ix, double Iy, double Iz, std::vector<double>& a);\n//Col<double> getCoefficients(std::string sysname);\nstd::vector<double> getWignerCoeffs(std::string sysname, bool freeRotor);\nstd::vector<double> getMomentOfInertia(std::string sysname=\"METH-CHA\");\nstd::string getDirectory(std::string sysname);\ndouble getPartitionFunction(double T, Mat<complex<double>>& H, int sym=1);\ndouble getSparseQ(double T, SpMat<complex<double>>& H, int sym=1);\n\nint main(int argc, char** argv) {\n    /* argv[0]  Program name\n     * argv[1]  System name\n     * argv[2]  Lmax (start)\n     * argv[3]  free-rotor\n     * argv[4]  temperature / K\n     */\n    if (argc != 5) {\n        throw std::runtime_error(\"Enter systemName as it appears in data directory, Lmax, free-rotor flag, temperature in Kelvin\");\n    }\n\n    auto start = std::chrono::high_resolution_clock::now();\n\n    std::string sysname = argv[1];\n    bool freeRotor = std::stoi(argv[3]);\n    double T = std::stod(argv[4]);\n    std::string dirname = getDirectory(sysname);\n    std::cout << \"Directory containing data is: \" << dirname << std::endl;\n    std::vector<double> a = getWignerCoeffs(sysname, freeRotor);\n    int sigma = 1;\n\n    std::vector<double> Ivec = getMomentOfInertia(sysname);\n    std::cout << \"Moments of Inertia:\" << std::endl;\n    for (double i : Ivec) {\n        std::cout << i << '\\t';\n    }\n \n    /*\n     *  Rotational Constants + Classical Partition Function\n     */\n    double B = HBAR1*HBAR2/(2.0*Ivec[2]);\n    double A = HBAR1*HBAR2/(2.0*Ivec[1]);\n    double C = HBAR1*HBAR2/(2.0*Ivec[0]);\n    //std::cout << \"kB T / Hartree:\\n\" << kB * 298 / EHARTREE << std::endl;\n    std::cout << \"Qapprox = \" << sqrt(M_PI)/sigma * sqrt(pow(kB*300/EHARTREE, 3) / (A*B*C)) << std::endl;  \n\n    /*\n     *  Dense Matrix Implementation \n     */\n    bool converge = false;\n    bool dense = true;\n    int lmax = atoi(argv[2]);\n    double Q;\n    double Qprev = 0;\n    std::cout << \"Lmax\\t\\tQ\\t\\tTime\\t\\tdQ\" << std::endl;\n    do {\n        auto qstart = std::chrono::high_resolution_clock::now();\n        if (dense) {\n            /****  Dense Matrix Implementation  ****/\n            unsigned long long size = (lmax+1)*(2*lmax+1)*(2*lmax+3)/3.0;\n            Mat<complex<double>> H = getHamiltonian(lmax, Ivec[0], Ivec[1], Ivec[2], a);\n            if (!H.is_hermitian(1e-3)) {\n                H.brief_print(\"H = \");\n            }\n            try {\n                Q = getPartitionFunction(298.15, H, sigma);\n            } catch (const std::logic_error& e) {\n                //std::cout << \"Required Memory is \" << size*size*8*1e-9 << \" Gb.\" << std::endl; \n                //std::cout << \"Memory problem caused failure. Switching to sparse implementation.\" << std::endl;\n                //dense = false;\n                throw e;\n                break;\n            }\n            /* *********************************** */\n        } else {\n            break;\n            /****  Sparse Matrix Implementation  ****/\n            SpMat<complex<double>> H = getSparseHam(lmax, Ivec[0], Ivec[1], Ivec[2], a);\n            Q = getSparseQ(298.15, H, sigma);\n            /****************************************/\n        }\n        auto qend = std::chrono::high_resolution_clock::now();\n        auto qduration = std::chrono::duration_cast<std::chrono::microseconds>(qend - qstart);\n        double dQ = fabs(Q-Qprev);\n        std::cout << lmax << \"\\t\\t\" << Q << \"\\t\\t\" << qduration.count()/1e6 << \" sec.\" << \"\\t\\t\" << dQ << std::endl;\n        if (dQ < 1e-4) {\n            converge = true;\n            std::cout << \"DeltaQ = \" << fabs(Q-Qprev) << std::endl;\n            std::cout << \"Convergence criterion met!\" << std::endl;\n            std::cout << \"Lmax = \" << lmax << std::endl;\n        }\n        lmax++;\n        Qprev = Q;\n    } while (!converge);\n    std::cout << std::endl;\n    std::cout << std::endl;\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);\n    std::cout << std::endl << duration.count()/1e6 << \" secs\" << std::endl;\n    return 0;\n}\n\n\ndouble getPartitionFunction(double T, Mat<complex<double>>& H, int sym) {\n    /* Solve the Eigenvalues\n     * Inputs:  T;  the temperature [=] K\n     *          H;  the Hamiltonian matrix [=] Hartree\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n    double tr = 0;\n\n    //std::cout << \"Solving Matrix exponential\" << std::endl;\n    //Mat<complex<double>> expbH = expmat_sym(-b*H);\n    vec eigval = eig_sym(H);\n    for (double e : eigval) {\n        tr += exp(-b*e);\n    }\n    //std::cout  <<  \"Solved Matrix exponential\" << std::endl;\n    //double tr = trace(expmat_sym(-b*H));\n    //std::cout << std::endl << \"Q predicted by eig_sym: \" << tr/sym << std::endl;\n    return double(tr/sym);\n    //return double(Q/sym);\n}\n\nMat<complex<double>> getHamiltonian(int lmax, double Ix, double Iy, double Iz, std::vector<double>& a) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number forthe spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*Å^2\n     *             a;   coefficients for potential in the Wigner D Matrix basis\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    long double size = (lmax+1)*(2*lmax+1)*(2*lmax+3)/3.0;\n    Mat<complex<double>> H = zeros<mat>(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n    double kap = (A == B && A == C) ? 0 : (2.0*B - (A+C)) / (A-C);\n    #pragma omp parallel\n    {\n        unsigned long long i = 0;\n        #pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    //unsigned long long i = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    //std::cout << j << '\\t';\n                    unsigned long long j = 0;\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                //unsigned long long j = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0) + 2*mm*ell + mm + kk;\n                                if (j > i) continue;\n                                if (i == j) {\n                                    try {\n                                        H(i,j) += 0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k;\n                                        if (k+2 <= el) {\n                                            double val = 0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2));\n                                            H(i+2,j) += val;\n                                            H(j,i+2) += val;\n                                        }\n                                    } catch (const std::exception& e) {\n                                        std::cout << \"Failure at index: \" <<\n                                            i << \"\\t(\" << el << ',' << m << ',' <<\n                                            k << ')' << std::endl;\n                                    }\n                                }\n                                //if (a.size() == 1) continue;\n                                //double Vij = 0;\n                                //for (int L = 0; L < 8; L++) {\n                                //    for (int M = -L; M <= L; M++) {\n                                //        for (int K = -L; K <= L; K++) {\n                                //            unsigned long long ind = (4*L*L*L/3.0) + 2*L*L + (5*L/3.0) + 2*M*L + M + K;\n                                //            if (ind > a.size()-1 || a[ind] == 0) continue;\n                                //            //double Clm = WignerSymbols::clebschGordan(L,ell,el,M,mm,m);\n                                //            //double Clk = WignerSymbols::clebschGordan(L,ell,el,K,kk,k);\n                                //            //double val = 8*M_PI*M_PI*Clm*Clk/(2.0*el+1.0);\n                                //            double Wlm = WignerSymbols::wigner3j(L,ell,el,M,mm,-m);\n                                //            double Wlk = WignerSymbols::wigner3j(L,ell,el,K,kk,-k);\n                                //            double val = 8*M_PI*M_PI*pow(-1.0, -m-k)*Wlm*Wlk;\n                                //            Vij += a[ind] * val;\n                                //        }\n                                //    }\n                                //}\n                                //H(i,j) += Vij;\n                                //H(j,i) += Vij;\n                                j++;\n                            }\n                        }\n                    }\n                    i++;\n                }\n            }\n        }\n    } // end parallel\n    //H.print(\"H = \");\n    //std::cout << \"Constructed matrix with LMAX \" << lmax << '.' << std::endl;\n    return H;\n}\n\nstd::vector<double> getWignerCoeffs(std::string sysname, bool freeRotor) {\n    if (freeRotor) {\n        std::vector<double> a = { 0.0 };\n        return a;\n    }\n    std::string dirname = getDirectory(sysname);\n    std::string filename = dirname+\"/a.txt\";\n    std::ifstream is(filename);\n    double val;\n    std::vector<double> a;\n    while (is) {\n        if(!(is >> val)) {\n            break;\n        }\n        a.push_back(val);\n    }\n    return a;\n}\n\nstd::vector<double> getMomentOfInertia(std::string sysname) {\n    std::string dirname = getDirectory(sysname);\n    std::string filename = dirname+'/'+\"I.txt\";\n    std::ifstream is(filename);\n    double val;\n    std::vector<double> Ivec;\n    while (is) {\n        if (!(is >> val)) {\n            break;\n        }\n        Ivec.push_back(val);\n    }\n    return Ivec;\n}\n\nstd::string getDirectory(std::string sysname) {\n    //std::string dirname = \"/Users/lancebettinson/Thesis/umrr/code/hamiltonian-cpp/data\";\n    std::string dirname = \"/global/scratch/lbettins/rotational-hamiltonian/data\";\n    if (sysname == \"\") {\n        std::string sysname;\n        std::cout << \"Enter system name:\" << std::endl;\n        std::cin >> sysname;\n    }\n    return dirname+'/'+sysname;\n}\n\nSpMat<complex<double>> getSparseHam(int lmax, double Ix, double Iy, double Iz, std::vector<double>& a) {\n    /* Construct the Hamiltonian Matrix\n     * Inputs:  lmax;   the maximum quantum number forthe spherical basis\n     *             I;   the gas-phase moments of inertia [=] amu*Å^2\n     * Outputs:    H;   the Hamiltonian matrix (Hermitian) [=] Hartree \n     */\n    unsigned long long size = (lmax+1)*(2*lmax+1)*(2*lmax+3)/3.0;\n    SpMat<complex<double>> H = sp_mat(size, size);\n\n    // Define rotational constants:\n    double B = HBAR1*HBAR2/(2.0*Iz);\n    double A = HBAR1*HBAR2/(2.0*Iy);\n    double C = HBAR1*HBAR2/(2.0*Ix);\n\n    double kap = (A == B && A == C) ? 0 : (2.0*B - (A+C)) / (A-C);\n    #pragma omp parallel\n    {\n        #pragma omp for\n        for (int el = 0; el < lmax+1; el++) {\n            for (int m = -el; m <= el; m++) {\n                for (int k = -el; k <= el; k++) {\n                    unsigned long long i = (4*el*el*el/3.0) + 2*el*el + (5*el/3.0) + 2*m*el + m + k;\n                    for (int ell = 0; ell < lmax+1; ell++) {\n                        for (int mm = -ell; mm <= ell; mm++) {\n                            for (int kk = -ell; kk <= ell; kk++) {\n                                unsigned long long j = (4*ell*ell*ell/3.0) + 2*ell*ell + (5*ell/3.0)\n                                    + 2*mm*ell + mm + kk;\n                                if (j > i) continue;\n                                if (i == j) {\n                                    try {\n                                        H(i,j) += 0.5*(A+C)*el*(el+1) + 0.5*(A-C)*kap*k*k;\n                                        if (k+2 <= el) {\n                                            double val = 0.25*(C-A)*sqrt(el*(el+1)-k*(k+1))*sqrt(el*(el+1)-(k+1)*(k+2));\n                                            H(i+2,j) += val;\n                                            H(j,i+2) += val;\n                                        }\n                                    } catch (const std::exception& e) {\n                                        std::cout << \"Failure at index: \" <<\n                                            i << \"\\t(\" << el << ',' << m << ',' <<\n                                            k << ')' << std::endl;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    } // end parallel\n    return H;\n}\n\ndouble getSparseQ(double T, SpMat<complex<double>>& H, int sym) {\n    /* Solve the Eigenvalues forSparse Matrix\n     * Inputs:  T;  the temperature [=] K\n     *          H;  the (sparse) Hamiltonian matrix [=] Hartree\n     */\n    double b = pow(kB * T, -1) * EHARTREE;\n    vec eigval;\n    mat eigvec;\n    //std::cout << \"Number of rows: \" << H.n_rows << std::endl;\n    eigs_sym(eigval, eigvec, H, H.n_rows-1);\n    double Q = 0;\n    //std::cout << \"Eigenvalues: \" << std::endl;\n    for (double e : eigval) {\n        //std::cout << e << '\\t';\n        Q += exp(-b * e);\n    }\n    //std::cout << \"Q predicted by eigs_sym: \" << Q/sym << std::endl;\n    return double(Q/sym);\n}\n\nCol<double> getCoefficients(std::string sysname) {\n    std::string dirname = getDirectory(sysname);\n    std::string filename = dirname+'/'+\"vdat.txt\";\n    std::ifstream is(filename);\n    if (is.fail())\n    {\n        std::cout << \"cannot open file \" << filename;\n    }\n    double theta, phi, v;\n    std::vector<double> my_vec;\n    while (is) {\n        if (!(is >> theta >> phi >> v)) {\n            break;\n        }\n        //std::cout << theta << '\\t' << phi << '\\t' << v << std::endl;\n        my_vec.push_back(v);\n    }\n    Col<double> cvec = conv_to<vec>::from(my_vec);\n    //cvec.print();\n    is.close();\n    return cvec;\n}\n", "meta": {"hexsha": "bc6b6985d0f5fc52b8e4b0d74f63a46f68b49cad", "size": 14917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armandham/cx_ham.cpp", "max_stars_repo_name": "lbettins/rotational-hamiltonian", "max_stars_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armandham/cx_ham.cpp", "max_issues_repo_name": "lbettins/rotational-hamiltonian", "max_issues_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armandham/cx_ham.cpp", "max_forks_repo_name": "lbettins/rotational-hamiltonian", "max_forks_repo_head_hexsha": "f9be5bf922219a1a26f7c96f9b72c996d8f8f3ee", "max_forks_repo_licenses": ["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.6457765668, "max_line_length": 131, "alphanum_fraction": 0.4550512838, "num_tokens": 4131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.5616399386257968}}
{"text": "#include <kv/Heine.hpp>\n#include <kv/qAiry.hpp>\n#include <kv/qBessel.hpp>\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\ntypedef kv::interval<double> itv;\ntypedef kv::complex< kv::interval<double> > cp;\nusing namespace std;\nnamespace ub = boost::numeric::ublas;\nint main()\n{\n  cout.precision(17);\n  int n=20;\n  itv nu,q;\n  ub::vector< itv > x(100);\n  q=\"0.7\";\n  nu=1.5;\n  x(0)=4.5;\n  x(1)=4.45;\n  for(int i=1;i<=n;i++){\n    x(i+1)=x(i)-kv::Hahn_Exton(itv(x(i)),itv(nu),itv(q))*(x(i)-x(i-1))\n      /(kv::Hahn_Exton(itv(x(i)),itv(nu),itv(q))-kv::Hahn_Exton(itv(x(i-1)),itv(nu),itv(q)));\n  cout<<x(i+1)<<endl;\n  cout<<\"value of HE inf\"<<kv::Hahn_Exton(itv(x(i+1).lower()),itv(nu),itv(q))<<endl;\n  cout<<\"value of HE sup\"<<kv::Hahn_Exton(itv(x(i+1).upper()),itv(nu),itv(q))<<endl;\n  cout<<\"value of HE mid\"<<kv::Hahn_Exton(itv(mid(x(i+1))),itv(nu),itv(q))<<endl;\n  }\n}\n", "meta": {"hexsha": "9ee1e80a605d70d63afa37cb182cf2524285319d", "size": 935, "ext": "cc", "lang": "C++", "max_stars_repo_path": "qNewton/HEsecant.cc", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "qNewton/HEsecant.cc", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "qNewton/HEsecant.cc", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1612903226, "max_line_length": 93, "alphanum_fraction": 0.6171122995, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002491, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.5615669451643037}}
{"text": "#ifndef GICP_COST_HPP\n#define GICP_COST_HPP\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include \"litamin2/ceres_cost/PoseSE3Parameterization.hpp\"\n// L^T*error\nstruct GICP_FACTOR {\n  GICP_FACTOR(Eigen::Vector3d p_mean, Eigen::Vector3d q_mean, Eigen::Matrix3d p_cov, Eigen::Matrix3d q_cov) : p_mean_(p_mean), q_mean_(q_mean), p_cov_(p_cov), q_cov_(q_cov) {}\n\n  template <typename T>\n  bool operator()(const T* const q, const T* const t, T* residuals) const {\n    Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals_map(residuals);\n    Eigen::Matrix<T, 3, 1> p_m(p_mean_.cast<T>());\n    Eigen::Matrix<T, 3, 1> q_m(q_mean_.cast<T>());\n    Eigen::Matrix<T, 3, 3> p_c = p_cov_.cast<T>();\n    Eigen::Matrix<T, 3, 3> q_c = q_cov_.cast<T>();\n\n    Eigen::Quaternion<T> quat(q);\n    Eigen::Matrix<T, 3, 1> translation(t);\n\n    Eigen::Matrix<T, 3, 3> mahalanobis = (q_c + quat * p_c * quat.inverse()).inverse();\n    Eigen::Matrix<T, 3, 3> LT = mahalanobis.llt().matrixL().transpose();\n    residuals_map = LT * (q_m - (quat * p_m + translation));\n\n    return true;\n  }\n\n  static ceres::CostFunction* Create(Eigen::Vector3d p_mean_, Eigen::Vector3d q_mean_, Eigen::Matrix3d p_cov_, Eigen::Matrix3d q_cov_) {\n    // 分别是残差，q，t的维度\n    return (new ceres::AutoDiffCostFunction<GICP_FACTOR, 3, 4, 3>(new GICP_FACTOR(p_mean_, q_mean_, p_cov_, q_cov_)));\n  }\n\n  Eigen::Vector3d p_mean_, q_mean_;\n  Eigen::Matrix3d p_cov_, q_cov_;\n};\n\nclass GICPAnalyticCostFunction : public ceres::SizedCostFunction<3, 7> {\npublic:\n  GICPAnalyticCostFunction(Eigen::Vector3d p_mean, Eigen::Vector3d q_mean, Eigen::Matrix3d p_cov, Eigen::Matrix3d q_cov)\n  : p_mean_(p_mean),\n    q_mean_(q_mean),\n    p_cov_(p_cov),\n    q_cov_(q_cov) {}\n  virtual ~GICPAnalyticCostFunction() {}\n  // parameters是[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // 默认已经归一化\n    Eigen::Quaterniond q_last_curr(parameters[0]);\n    Eigen::Vector3d t_last_curr(parameters[0] + 4);\n    Eigen::Matrix3d LT = (q_cov_ + q_last_curr * q_cov_ * q_last_curr.inverse()).inverse().llt().matrixL().transpose();\n    Eigen::Map<Eigen::Vector3d> residuals_map(residuals);\n    Eigen::Vector3d p_mean_trans = q_last_curr * p_mean_ + t_last_curr;\n    residuals_map = LT * (q_mean_ - p_mean_trans);\n\n    if (jacobians != NULL) {\n      if (jacobians[0] != NULL) {\n        Eigen::Map<Eigen::Matrix<double, 3, 7, Eigen::RowMajor>> J_se3(jacobians[0]);\n        J_se3.setZero();\n        Eigen::Matrix<double, 3, 6> dp_by_se3;\n        dp_by_se3.block<3, 3>(0, 0) = skew(p_mean_trans);\n        dp_by_se3.block<3, 3>(0, 3) = -Eigen::Matrix3d::Identity();\n        J_se3.block<3, 6>(0, 0) = LT * dp_by_se3;\n      }\n    }\n    return true;\n  }\n\n  Eigen::Vector3d p_mean_, q_mean_;\n  Eigen::Matrix3d p_cov_, q_cov_;\n};\n\n// 弃用\n// 精度不高，而且耗时\n// Z是R*Sigma_i*RT对李代数的雅可比矩阵，来自于d2d-ndt，具体如何计算，我不清楚\nclass GICPDoubleAnalyticCostFunction : public ceres::SizedCostFunction<3, 7> {\npublic:\n  GICPDoubleAnalyticCostFunction(Eigen::Vector3d p_mean, Eigen::Vector3d q_mean, Eigen::Matrix3d p_cov, Eigen::Matrix3d q_cov)\n  : p_mean_(p_mean),\n    q_mean_(q_mean),\n    p_cov_(p_cov),\n    q_cov_(q_cov) {}\n  virtual ~GICPDoubleAnalyticCostFunction() {}\n  // parameters是[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // 默认已经归一化\n    Eigen::Quaterniond q_last_curr(parameters[0]);\n    Eigen::Vector3d t_last_curr(parameters[0] + 4);\n    Eigen::Matrix3d mahalanobis = (q_cov_ + q_last_curr * q_cov_ * q_last_curr.inverse()).inverse();\n    // Eigen::Matrix3d LT = mahalanobis.llt().matrixL().transpose();\n    Eigen::Map<Eigen::Vector3d> residuals_map(residuals);\n    Eigen::Vector3d p_mean_trans = q_last_curr * p_mean_ + t_last_curr;\n    residuals_map = mahalanobis * (q_mean_ - p_mean_trans);\n\n    if (jacobians != NULL) {\n      if (jacobians[0] != NULL) {\n        Eigen::Map<Eigen::Matrix<double, 3, 7, Eigen::RowMajor>> J_se3(jacobians[0]);\n        J_se3.setZero();\n        Eigen::Matrix<double, 3, 6> dp_by_se3;\n        Eigen::Matrix<double, 3, 6> BZBU(Eigen::Matrix<double,3,6>::Zero());\n        dp_by_se3.block<3, 3>(0, 0) = skew(p_mean_trans);\n        dp_by_se3.block<3, 3>(0, 3) = -Eigen::Matrix3d::Identity();\n        Eigen::Matrix3d Z1, Z2, Z3;\n        Z1 << 0, -p_cov_(0, 2), p_cov_(0, 1), -p_cov_(0, 2), -2 * p_cov_(1, 2), -p_cov_(2, 2) + p_cov_(1, 1), p_cov_(0, 1), -p_cov_(2, 2) + p_cov_(1, 1), 2 * p_cov_(1, 2);\n        Z2 << 2 * p_cov_(0, 2), p_cov_(1, 2), -p_cov_(0, 0) + p_cov_(2, 2), p_cov_(1, 2), 0, -p_cov_(0, 1), -p_cov_(0, 0) + p_cov_(2, 2), -p_cov_(0, 1), -2 * p_cov_(0, 2);\n        Z3 << -2 * p_cov_(0, 1), -p_cov_(1, 1) + p_cov_(0, 0), -p_cov_(1, 2), -p_cov_(1, 1) + p_cov_(0, 0), 2 * p_cov_(0, 1), p_cov_(0, 2), -p_cov_(1, 2), p_cov_(0, 2), 0;\n        BZBU.block<3,1>(0,0) = mahalanobis * Z1 * mahalanobis * p_mean_trans;\n        BZBU.block<3,1>(0,1) = mahalanobis * Z2 * mahalanobis * p_mean_trans;\n        BZBU.block<3,1>(0,2) = mahalanobis * Z3 * mahalanobis * p_mean_trans;\n        J_se3.block<3, 6>(0, 0) = -BZBU + mahalanobis * dp_by_se3;\n      }\n    }\n    return true;\n  }\n\n  Eigen::Vector3d p_mean_, q_mean_;\n  Eigen::Matrix3d p_cov_, q_cov_;\n};\n\n// 正常工作，但精度并不是特别的高\n// TODO 删除无效代码\nclass ICPAnalyticCostFunction : public ceres::SizedCostFunction<3, 7> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  ICPAnalyticCostFunction(Eigen::Vector3d p_mean, Eigen::Vector3d q_mean, Eigen::Matrix3d p_cov, Eigen::Matrix3d q_cov)\n  : p_mean_(p_mean),\n    q_mean_(q_mean),\n    p_cov_(p_cov),\n    q_cov_(q_cov) {}\n  virtual ~ICPAnalyticCostFunction() {}\n  // parameters是[0,0,0,1,x,y,z]\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    // 默认已经归一化\n    Eigen::Quaterniond q_last_curr(parameters[0]);\n    Eigen::Vector3d t_last_curr(parameters[0] + 4);\n    // Eigen::Matrix3d mahalanobis = q_cov_ + q_last_curr * q_cov_ * q_last_curr.inverse();\n    // Eigen::Matrix3d LT = mahalanobis.llt().matrixL().transpose();\n    Eigen::Map<Eigen::Vector3d> residuals_map(residuals);\n    Eigen::Vector3d p_mean_trans = q_last_curr * p_mean_ + t_last_curr;\n    residuals_map = q_mean_ - p_mean_trans;\n\n    if (jacobians != NULL) {\n      if (jacobians[0] != NULL) {\n        Eigen::Map<Eigen::Matrix<double, 3, 7, Eigen::RowMajor>> J_se3(jacobians[0]);\n        J_se3.setZero();\n        Eigen::Matrix<double, 3, 6> dp_by_se3;\n        dp_by_se3.block<3, 3>(0, 0) = skew(p_mean_trans);\n        dp_by_se3.block<3, 3>(0, 3) = -Eigen::Matrix3d::Identity();\n        J_se3.block<3, 6>(0, 0) = dp_by_se3;\n      }\n    }\n    return true;\n  }\n\n  Eigen::Vector3d p_mean_, q_mean_;\n  Eigen::Matrix3d p_cov_, q_cov_;\n};\n#endif", "meta": {"hexsha": "f46980e66c243845d77b7229a191235a19d04cb5", "size": 6777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/litamin2/ceres_cost/gicp_cost.hpp", "max_stars_repo_name": "FishInWave/fast-gicp", "max_stars_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T04:12:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T11:06:30.000Z", "max_issues_repo_path": "include/litamin2/ceres_cost/gicp_cost.hpp", "max_issues_repo_name": "FishInWave/fast-gicp", "max_issues_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/litamin2/ceres_cost/gicp_cost.hpp", "max_forks_repo_name": "FishInWave/fast-gicp", "max_forks_repo_head_hexsha": "00e2dc6dd9cf8417ab36dfbceffa2bd56ed8371b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-26T04:12:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:17:35.000Z", "avg_line_length": 42.0931677019, "max_line_length": 175, "alphanum_fraction": 0.6561900546, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5615422612953604}}
{"text": "//\n//  gmatrix16float.cpp\n//  GCommon\n//\n//  Created by David Coen on 2011 06 01\n//  Copyright Pleasure seeking morons 2011. All rights reserved.\n//\n\n#include \"gmatrix16float.h\"\n\n#include \"gvector3float.h\"\n#include \"gmathmatrix.h\"\n#include \"gmath.h\"\n#include \"gmatrix9float.h\"\n\n#include <boost/swap.hpp>\n\n#define DSC_INLINE_MATRIX_MUL\n\n/*\nmatching openGL documentation\n\t\t0_0, 0_1, 0_2, 0_3(x),\n\t\t1_0, 1_1, 1_2, 1_3(y),\n\t\t2_0, 2_1, 2_2, 2_3(z),\n\t\t3_0, 3_1, 3_2, 3_3\n*/\n\n/*static*/ const GMatrix16Float GMatrix16Float::sIdentity(1.0F, 0.0F, 0.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  0.0F, 1.0F, 0.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  0.0F, 0.0F, 1.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  0.0F, 0.0F, 0.0F, 1.0F);\n\n\n//constructors\nGMatrix16Float::GMatrix16Float(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2, const GR32 in_data_0_3,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2, const GR32 in_data_1_3,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2, const GR32 in_data_2_3,\n\tconst GR32 in_data_3_0, const GR32 in_data_3_1, const GR32 in_data_3_2, const GR32 in_data_3_3\n\t)\n{\n\tSetData(in_data_0_0, in_data_0_1, in_data_0_2, in_data_0_3,\n\t\tin_data_1_0, in_data_1_1, in_data_1_2, in_data_1_3,\n\t\tin_data_2_0, in_data_2_1, in_data_2_2, in_data_2_3,\n\t\tin_data_3_0, in_data_3_1, in_data_3_2, in_data_3_3\n\t\t);\n\treturn;\n}\nGMatrix16Float::GMatrix16Float(const GR32* const in_data)\n{\n\tfor (GS32 index = 0; index < 16; ++index)\n\t{\n\t\tm_data[index] = in_data[index];\n\t}\n\treturn;\n\n}\n\nGMatrix16Float::GMatrix16Float(const GMatrix16Float& in_src)\n{\n\t(*this) = in_src;\n\treturn;\n}\n\nGMatrix16Float::~GMatrix16Float()\n{\n\treturn;\n}\n\t\n//operators\nconst GMatrix16Float& GMatrix16Float::operator=(const GMatrix16Float& in_rhs)\n{\n\tfor (GS32 index = 0; index < 16; ++index)\n\t{\n\t\tm_data[index] = in_rhs.m_data[index];\n\t}\n\treturn (*this);\n}\n\nconst GMatrix16Float& GMatrix16Float::operator*=(const GR32 in_rhs)\n{\n\tfor (GS32 index = 0; index < 16; ++index)\n\t{\n\t\tm_data[index] *= in_rhs;\n\t}\n\n\treturn (*this);\n}\n\n//public methods\nvoid GMatrix16Float::Decompose(GVector3Float& out_position,\n   GQuaternion4Float& out_rotation,\n   GVector3Float& out_scale\n   )\n{\n\treturn;\n}\n\nGMatrix16Float&  GMatrix16Float::TransposeSelf()\n{\n\tstd::swap(m_0_1, m_1_0);\n\tstd::swap(m_0_2, m_2_0);\n\tstd::swap(m_0_3, m_3_0);\n\tstd::swap(m_1_2, m_2_1);\n\tstd::swap(m_1_3, m_3_1);\n\tstd::swap(m_2_3, m_3_2);\n\n\treturn (*this);\n}\nGMatrix16Float& GMatrix16Float::InverseSelf()\n{\n\t(*this) = ReturnInverse();\n\treturn (*this);\n}\n\n\nconst GMatrix16Float GMatrix16Float::ReturnInverse()const\n{\n\tGMatrix16Float result;\n\tGMathMatrix<GR32>::Inverse4(&result.m_data[0], &m_data[0]);\n\n\treturn result;\n}\n\nGMatrix9Float GMatrix16Float::GetRotation()const\n{\n\treturn GMatrix9Float(\n\t\tm_0_0, m_0_1, m_0_2,\n\t\tm_1_0, m_1_1, m_1_2,\n\t\tm_2_0, m_2_1, m_2_2\n\t);\n}\n\nvoid GMatrix16Float::SetRotation(const GMatrix9Float& in_rotation)\n{\n\tm_0_0 = in_rotation.m_0_0;\n\tm_1_0 = in_rotation.m_1_0;\n\tm_2_0 = in_rotation.m_2_0;\n\tm_0_1 = in_rotation.m_0_1;\n\tm_1_1 = in_rotation.m_1_1;\n\tm_2_1 = in_rotation.m_2_1;\n\tm_0_2 = in_rotation.m_0_2;\n\tm_1_2 = in_rotation.m_1_2;\n\tm_2_2 = in_rotation.m_2_2;\n\treturn;\n}\n\n\n//public accessors\nvoid GMatrix16Float::SetData(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2, const GR32 in_data_0_3,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2, const GR32 in_data_1_3,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2, const GR32 in_data_2_3,\n\tconst GR32 in_data_3_0, const GR32 in_data_3_1, const GR32 in_data_3_2, const GR32 in_data_3_3\n\t)\n{\n\tm_0_0 = in_data_0_0;\n\tm_1_0 = in_data_1_0;\n\tm_2_0 = in_data_2_0;\n\tm_3_0 = in_data_3_0;\n\n\tm_0_1 = in_data_0_1;\n\tm_1_1 = in_data_1_1;\n\tm_2_1 = in_data_2_1;\n\tm_3_1 = in_data_3_1;\n\n\tm_0_2 = in_data_0_2;\n\tm_1_2 = in_data_1_2;\n\tm_2_2 = in_data_2_2;\n\tm_3_2 = in_data_3_2;\n\n\tm_0_3 = in_data_0_3;\n\tm_1_3 = in_data_1_3;\n\tm_2_3 = in_data_2_3;\n\tm_3_3 = in_data_3_3;\n\n\treturn;\n}\n\nconst GVector3Float GMatrix16Float::GetAt()const\n{\n\tconst GVector3Float result(\n\t\tm_0_2,\n\t\tm_1_2,\n\t\tm_2_2\n\t\t);\n\treturn result;\n}\n\nconst GVector3Float GMatrix16Float::GetUp()const\n{\n\tconst GVector3Float result(\n\t\tm_0_1,\n\t\tm_1_1,\n\t\tm_2_1\n\t\t);\n\treturn result;\n}\n\nconst GVector3Float GMatrix16Float::GetPosition()const\n{\n\tconst GVector3Float result(\n\t\tm_0_3,\n\t\tm_1_3,\n\t\tm_2_3\n\t\t);\n\treturn result;\n}\n\nvoid GMatrix16Float::SetPosition(const GVector3Float& in_position)\n{\n\tm_0_3 = in_position.m_x;\n\tm_1_3 = in_position.m_y;\n\tm_2_3 = in_position.m_z;\n\treturn;\n}\n\n//global operators\nconst GMatrix16Float operator*(const GMatrix16Float& in_lhs, const GMatrix16Float& in_rhs)\n{\n\tGR32 value[16];\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 8]) + (lhsData[ 3] * rhsData[12]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 9]) + (lhsData[ 3] * rhsData[13]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 6]) + (lhsData[ 2] * rhsData[10]) + (lhsData[ 3] * rhsData[14]);\n\tvalue[ 3] = (lhsData[ 0] * rhsData[ 3]) + (lhsData[ 1] * rhsData[ 7]) + (lhsData[ 2] * rhsData[11]) + (lhsData[ 3] * rhsData[15]);\n\n\tvalue[ 4] = (lhsData[ 4] * rhsData[ 0]) + (lhsData[ 5] * rhsData[ 4]) + (lhsData[ 6] * rhsData[ 8]) + (lhsData[ 7] * rhsData[12]);\n\tvalue[ 5] = (lhsData[ 4] * rhsData[ 1]) + (lhsData[ 5] * rhsData[ 5]) + (lhsData[ 6] * rhsData[ 9]) + (lhsData[ 7] * rhsData[13]);\n\tvalue[ 6] = (lhsData[ 4] * rhsData[ 2]) + (lhsData[ 5] * rhsData[ 6]) + (lhsData[ 6] * rhsData[10]) + (lhsData[ 7] * rhsData[14]);\n\tvalue[ 7] = (lhsData[ 4] * rhsData[ 3]) + (lhsData[ 5] * rhsData[ 7]) + (lhsData[ 6] * rhsData[11]) + (lhsData[ 7] * rhsData[15]);\n\n\tvalue[ 8] = (lhsData[ 8] * rhsData[ 0]) + (lhsData[ 9] * rhsData[ 4]) + (lhsData[10] * rhsData[ 8]) + (lhsData[11] * rhsData[12]);\n\tvalue[ 9] = (lhsData[ 8] * rhsData[ 1]) + (lhsData[ 9] * rhsData[ 5]) + (lhsData[10] * rhsData[ 9]) + (lhsData[11] * rhsData[13]);\n\tvalue[10] = (lhsData[ 8] * rhsData[ 2]) + (lhsData[ 9] * rhsData[ 6]) + (lhsData[10] * rhsData[10]) + (lhsData[11] * rhsData[14]);\n\tvalue[11] = (lhsData[ 8] * rhsData[ 3]) + (lhsData[ 9] * rhsData[ 7]) + (lhsData[10] * rhsData[11]) + (lhsData[11] * rhsData[15]);\n\n\tvalue[12] = (lhsData[12] * rhsData[ 0]) + (lhsData[13] * rhsData[ 4]) + (lhsData[14] * rhsData[ 8]) + (lhsData[15] * rhsData[12]);\n\tvalue[13] = (lhsData[12] * rhsData[ 1]) + (lhsData[13] * rhsData[ 5]) + (lhsData[14] * rhsData[ 9]) + (lhsData[15] * rhsData[13]);\n\tvalue[14] = (lhsData[12] * rhsData[ 2]) + (lhsData[13] * rhsData[ 6]) + (lhsData[14] * rhsData[10]) + (lhsData[15] * rhsData[14]);\n\tvalue[15] = (lhsData[12] * rhsData[ 3]) + (lhsData[13] * rhsData[ 7]) + (lhsData[14] * rhsData[11]) + (lhsData[15] * rhsData[15]);\n#else\n\tGMathMatrix<GR32>::MatrixMul( \n\t\tin_lhs.GetData(),\n\t\tin_rhs.GetData(), \n\t\t4, \n\t\t4, \n\t\t4, \n\t\t&value[0]\n\t\t);\n#endif\n\treturn GMatrix16Float(&value[0]);\n}\n\nconst GVector3Float GMatrix16FloatMultiplyNoTranslate(const GVector3Float& in_lhs, const GMatrix16Float& in_rhs)\n{\n#ifdef DSC_INLINE_MATRIX_MUL\n\tGR32 value[3];\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 8]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 9]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 6]) + (lhsData[ 2] * rhsData[10]);\n#else\n\tGR32 source[4];\n\tGR32 value[4];\n\t//promote\n\tsource[0] = in_lhs.m_x;\n\tsource[1] = in_lhs.m_y;\n\tsource[2] = in_lhs.m_z;\n\tsource[3] = 0.0F;\n\n\t//< m, n > * < p, m > = < p, n >\n\tGMathMatrix<GR32>::MatrixMul( \n\t\t&source[0], \n\t\tin_rhs.GetData(),\n\t\t4, //m\n\t\t1, //n\n\t\t4, //p\n\t\t&value[0]\n\t\t);\n#endif\n\n\treturn GVector3Float(&value[0]);\n}\n\n//{\n//\tconst GMatrix9Float subMatrix = in_lhs.GetRotation();\n//\tconst GVector3Float result = subMatrix * in_rhs;\n//\treturn result;\n//}\n\nconst GVector3Float operator*(const GVector3Float& in_lhs, const GMatrix16Float& in_rhs)\n{\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\treturn GVector3Float(\n\t\t(lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 8]) + rhsData[12],\n\t\t(lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 9]) + rhsData[13],\n\t\t(lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 6]) + (lhsData[ 2] * rhsData[10]) + rhsData[14]\n\t\t);\n#else\n\tGR32 source[4];\n\tGR32 value[4];\n\t//promote\n\tsource[0] = in_lhs.m_x;\n\tsource[1] = in_lhs.m_y;\n\tsource[2] = in_lhs.m_z;\n\tsource[3] = 1.0F;\n\n\t//< m, n > * < p, m > = < p, n >\n\tGMathMatrix<GR32>::MatrixMul( \n\t\t&source[0], \n\t\tin_rhs.GetData(),\n\t\t4, //m\n\t\t1, //n\n\t\t4, //p\n\t\t&value[0]\n\t\t);\n\treturn GVector3Float(&value[0]);\n#endif\n}\n\n\n/*\n  from _Mathematics for computer graphics p.171\n mapping a pair of vectors onto another pair, u,x being one pair, a,y being another of unit vectors at same angle\n u.x = a.y = cos(\\), with sin(\\) != 0\n a roation matrix sending u,x to a,y given by\n               a \n M = [u v w ][ b ]\n               c\n d = | x * u | = | y * a | = | sin(\\) |\n if 90deg = u to x, cos(\\) = 0, sin(\\) = 1\n v = ( x * u ) / d\n b = ( y * a ) / d\n w = ( x - u( cos(\\) ) ) / d\n c = ( y - a( cos(\\) ) ) / d\n*/\nconst GMatrix16Float GMatrix16FloatConstructAtUp( \n\tconst GVector3Float& in_targetAt, \n\tconst GVector3Float& in_targetUp,\n\tconst GVector3Float& in_baseAt, \n\tconst GVector3Float& in_baseUp,\n\tconst GVector3Float& in_position\n\t)\n{\n\t////is this a stablity issue\n\t//const GR32 dotResultA = DotProduct(in_baseAt, in_targetAt);\n\t//const GR32 dotResultU = DotProduct(in_baseUp, in_targetUp);\n\t//if (((dotResultA < -0.999F) || (0.999F < dotResultA)) &&\n\t//\t((dotResultU < -0.999F) || (0.999F < dotResultU)))\n\t//{\n\t//\tGMatrix16Float result(GMatrix16Float::sIdentity);\n\t//\tresult.SetPosition(in_position);\n\t//\treturn result;\n\t//}\n\n\tconst GVector3Float crossBaseUpAt = CrossProduct(in_baseUp, in_baseAt);\n\tconst GVector3Float crossTargetUpAt = CrossProduct(in_targetUp, in_targetAt);\n\n\treturn GMatrix16Float(\n\t\t(in_baseAt.m_x * in_targetAt.m_x) + (crossBaseUpAt.m_x * crossTargetUpAt.m_x) + (in_baseUp.m_x * in_targetUp.m_x),\n\t\t(in_baseAt.m_y * in_targetAt.m_x) + (crossBaseUpAt.m_y * crossTargetUpAt.m_x) + (in_baseUp.m_y * in_targetUp.m_x),\n\t\t(in_baseAt.m_z * in_targetAt.m_x) + (crossBaseUpAt.m_z * crossTargetUpAt.m_x) + (in_baseUp.m_z * in_targetUp.m_x),\n\t\tin_position.m_x,\n\n\t\t(in_baseAt.m_x * in_targetAt.m_y) + (crossBaseUpAt.m_x * crossTargetUpAt.m_y) + (in_baseUp.m_x * in_targetUp.m_y),\n\t\t(in_baseAt.m_y * in_targetAt.m_y) + (crossBaseUpAt.m_y * crossTargetUpAt.m_y) + (in_baseUp.m_y * in_targetUp.m_y),\n\t\t(in_baseAt.m_z * in_targetAt.m_y) + (crossBaseUpAt.m_z * crossTargetUpAt.m_y) + (in_baseUp.m_z * in_targetUp.m_y),\n\t\tin_position.m_y,\n\n\t\t(in_baseAt.m_x * in_targetAt.m_z) + (crossBaseUpAt.m_x * crossTargetUpAt.m_z) + (in_baseUp.m_x * in_targetUp.m_z),\n\t\t(in_baseAt.m_y * in_targetAt.m_z) + (crossBaseUpAt.m_y * crossTargetUpAt.m_z) + (in_baseUp.m_y * in_targetUp.m_z),\n\t\t(in_baseAt.m_z * in_targetAt.m_z) + (crossBaseUpAt.m_z * crossTargetUpAt.m_z) + (in_baseUp.m_z * in_targetUp.m_z),\n\t\tin_position.m_z,\n\n\t\t0.0F,\n\t\t0.0F,\n\t\t0.0F,\n\t\t1.0F\n\t\t);\n}\n\nvoid GMatrix16FloatDecomposeAtUp(\n\tGVector3Float& out_at, \n\tGVector3Float& out_up,\n\tGVector3Float& out_position,\n\tconst GMatrix16Float& in_matrix\n\t)\n{\n\tout_at = in_matrix.GetAt();\n\tout_up = in_matrix.GetUp();\n\tout_position = in_matrix.GetPosition();\n\treturn;\n}\n\n\n\n/*\n  http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm\n\tmatrix[ HMatrixR4::IndexGet( 0, 0 ) ] = c + axis_x * axis_x * t;\n\tmatrix[ HMatrixR4::IndexGet( 1, 1 ) ] = c + axis_y * axis_y * t;\n\tmatrix[ HMatrixR4::IndexGet( 2, 2 ) ] = c + axis_z * axis_z * t;\n\n\tHREAL tmp1 = axis_x * axis_y * t;\n\tHREAL tmp2 = axis_z * s;\n\tmatrix[ HMatrixR4::IndexGet( 1, 0 ) ] = tmp1 + tmp2;\n\tmatrix[ HMatrixR4::IndexGet( 0, 1 ) ] = tmp1 - tmp2;\n\ttmp1 = axis_x * axis_z * t;\n\ttmp2 = axis_y * s;\n\tmatrix[ HMatrixR4::IndexGet( 2, 0 ) ] = tmp1 - tmp2;\n\tmatrix[ HMatrixR4::IndexGet( 0, 2 ) ] = tmp1 + tmp2;    \n\ttmp1 = axis_y * axis_z * t;\n\ttmp2 = axis_x * s;\n\tmatrix[ HMatrixR4::IndexGet( 2, 1 ) ] = tmp1 + tmp2;\n\tmatrix[ HMatrixR4::IndexGet( 1, 2 ) ] = tmp1 - tmp2;\n*/\nconst GMatrix16Float GMatrix16FloatConstructAxisAngle(const GVector3Float& in_axis, const GR32 in_angleRad)\n{\n\tconst GVector3Float localAxis = Normalise(in_axis);\n\tconst GR32 axis_x = localAxis.m_x;\n\tconst GR32 axis_y = localAxis.m_y;\n\tconst GR32 axis_z = localAxis.m_z;\n\n\tconst GR32 c = GMath::Cos( in_angleRad );\n\tconst GR32 s = GMath::Sin( in_angleRad );\n\tconst GR32 t = 1.0F - c;\n\n\tconst GR32 tmp1_01 = axis_x * axis_y * t;\n\tconst GR32 tmp2_01 = axis_z * s;\n\n\tconst GR32 tmp1_02 = axis_x * axis_z * t;\n\tconst GR32 tmp2_02 = axis_y * s;\n  \n\tconst GR32 tmp1_21 = axis_y * axis_z * t;\n\tconst GR32 tmp2_21 = axis_x * s;\n\n\treturn GMatrix16Float(\n\t\tc + axis_x * axis_x * t,\t\ttmp1_01 - tmp2_01,\t\t\ttmp1_02 + tmp2_02,\t\t\t0.0F,\n\t\ttmp1_01 + tmp2_01,\t\t\t\tc + axis_y * axis_y * t,\ttmp1_21 - tmp2_21,\t\t\t0.0F,\n\t\ttmp1_02 - tmp2_02,\t\t\t\ttmp1_21 + tmp2_21,\t\t\tc + axis_z * axis_z * t,\t0.0F,\n\t\t0.0F,\t\t\t\t\t\t\t0.0F,\t\t\t\t\t\t0.0F,\t\t\t\t\t\t1.0F\n\t\t);\n}\n\nconst GBOOL Valid(const GMatrix16Float& in_data)\n{\n\tconst GR32* const pData = in_data.GetData();\n\tif ((!GMath::Valid(pData[0])) ||\n\t\t(!GMath::Valid(pData[1])) ||\n\t\t(!GMath::Valid(pData[2])) ||\n\t\t(!GMath::Valid(pData[3])) ||\n\t\t(!GMath::Valid(pData[4])) ||\n\t\t(!GMath::Valid(pData[5])) ||\n\t\t(!GMath::Valid(pData[6])) ||\n\t\t(!GMath::Valid(pData[7])) ||\n\t\t(!GMath::Valid(pData[8])) ||\n\t\t(!GMath::Valid(pData[9])) ||\n\t\t(!GMath::Valid(pData[10])) ||\n\t\t(!GMath::Valid(pData[11])) ||\n\t\t(!GMath::Valid(pData[12])) ||\n\t\t(!GMath::Valid(pData[13])) ||\n\t\t(!GMath::Valid(pData[14])) ||\n\t\t(!GMath::Valid(pData[15])))\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n//cheap invert, no skew or scale support\nconst GMatrix16Float GMatrix16FloatInvertOrthogonal(const GMatrix16Float& in_src)\n{\n\tconst GVector3Float position = in_src.GetPosition();\n\tGMatrix16Float transpose(in_src);\n\ttranspose.SetPosition(GVector3Float::sZero);\n\ttranspose.TransposeSelf();\n\ttranspose.SetPosition(-position);\n\n\treturn transpose;\n}\n", "meta": {"hexsha": "376c5a29d567dbaada2ba05867f43027ddf0d879", "size": 14347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gcommon/source/gmatrix16float.cpp", "max_stars_repo_name": "DavidCoenFish/ancient-code-0", "max_stars_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "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": "gcommon/source/gmatrix16float.cpp", "max_issues_repo_name": "DavidCoenFish/ancient-code-0", "max_issues_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "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": "gcommon/source/gmatrix16float.cpp", "max_forks_repo_name": "DavidCoenFish/ancient-code-0", "max_forks_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "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.6425619835, "max_line_length": 131, "alphanum_fraction": 0.663901861, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.5615367225387666}}
{"text": "#include \"Truss.hpp\"\n#include <armadillo>\n#include <iomanip>\n\nusing namespace arma;\n\nTruss::Joint::Joint() {\n\tx=y=0;\n\tfixedX=fixedY=false;\n\texternalX=externalY=0;\n\tconnectionLen = 0;\n}\n\nTruss::Member::Member(){\n\tid = -1;\n\tjoint1 = joint2 = NULL;\n\tlength = 0;\n}\n\nTruss::Truss(int numJoints, int numMembers) {\n\tthis->numJoints = numJoints;\n\tthis->numMembers = numMembers;\n\tthis->joints = new Joint[this->numJoints];\n\tthis->members = new Member[this->numMembers];\n\tthis->pin = &joints[0];\n\tthis->normalJoint = &joints[1];\n}\n\nTruss::~Truss() {\n\tdelete[] joints;\n\tdelete[] members;\n}\n\nTruss::Joint* Truss::getJoints() {\n\treturn this->joints;\n}\n\nTruss::Member* Truss::getMembers() {\n\treturn this->members;\n}\n\nvoid Truss::solveGeneralSystem() {\n\t// assumes normal reaction force is horizontally or vertically aligned\n\tdouble momentAtPin = 0; // counterclockwise is positive\n\t// calculate moments about every joint\n\tfor (int i = 2; i < this->numJoints; i++) {\n\t\t// if the joint has an external x (i.e. has any external force\n\t\tif (joints[i].externalY != 0) {\n\t\t\tmomentAtPin += joints[i].x*joints[i].externalY;\n\t\t\t// do not need to calculate moment generated by x forces since external forces are only in y direction\n//\t\t\tmomentAtPin -= joints[i].y*joints[i].externalX;\n\t\t}\n\t}\n\n\tif (normalJoint->x == 0) { // the reactions are vertically aligned\n\t\t normalJoint->externalX = momentAtPin/normalJoint->y;\n\t\t pin->externalX = -normalJoint->externalX;\n\t\t pin->externalY = 0;\n\t\t for (int i = 2; i < this->numJoints; i++) {\n\t\t\t pin->externalY -= joints[i].externalY;\n\t\t }\n\t}\n\telse { // the reactions forces are horizontally aligned\n\t\tnormalJoint->externalY = -momentAtPin/normalJoint->x;\n\t\tpin->externalX=0;\n\t\tpin->externalY = 0;\n\t\tfor (int i = 1; i < this->numJoints; i++) {\n\t\t\tpin->externalY -= joints[i].externalY;\n\t\t}\n\t}\n}\n\nvoid Truss::initialSolve(){\n\tfor (int i = 0; i < numMembers; i++){\n\t\tmembers[i].length = pow(pow(members[i].joint1->x - members[i].joint2->x, 2) + pow(members[i].joint1->y - members[i].joint2->y, 2), 0.5);\n//\t\tcout << \"m\" << i << \"L: \"<< members[i].length << endl;\n\t}\n\n\tfor (int i = 0; i < numJoints; i++) {\n\t\tfor (int k = 0; k < joints[i].connections.size(); k++) {\n\t\t\tjoints[i].connectionLen += members[joints[i].connections[k]].length;\n//\t\t\tcout << \"joint \" << i << \"connectionLen: \" << joints[i].connectionLen << endl;\n\t\t}\n\t}\n\n\tsolveGeneralSystem();\n\n\tarma::mat equations = arma::mat(numJoints*2, numMembers, arma::fill::zeros);\n\tarma::vec external = arma::vec(numJoints*2, arma::fill::zeros);\n\n\n\tfor (int i = 0; i < numJoints; i++){\n\t\tJoint * j = &joints[i];\n\t\texternal(i*2) = -j->externalX;\n\t\texternal(i*2+1) = -j->externalY;\n\n\t\tfor(int k = 0; k < joints[i].connections.size(); k++) {\n\t\t\tequations(i * 2, joints[i].connections[k]) = (members[joints[i].connections[k]].joint1->x + members[j->connections[k]].joint2->x - 2 * j->x) / members[j->connections[k]].length;\n\t\t\tequations(i * 2 + 1, joints[i].connections[k]) = (members[joints[i].connections[k]].joint1->y + members[j->connections[k]].joint2->y - 2 * j->y) / members[j->connections[k]].length;\n\t\t}\n\t}\n\t//external.print();\n\t//cout << endl;\n\t//system(\"pause\");\n//\tequations.print();\n//\tcout << endl;\n//\texternal.print();\n//\tcout << endl;\n//\tsystem(\"pause\");\n\tarma::vec forces = solve(equations, external);\n//\tforces.print();\n\tfor (int i = 0; i < numMembers; i++){\n\t\tvalidForces.push_back(forces(i));\n\t}\n}\n\nbool Truss::solveInternal() {\n\t//cout << \"solving internal\" << endl;\n\tsolveGeneralSystem();\n\n\tarma::mat equations = arma::mat(numJoints*2, numMembers, arma::fill::zeros);\n\tarma::vec external = arma::vec(numJoints*2, arma::fill::zeros);\n\n\n\tfor (int i = 0; i < numJoints; i++) {\n\t\tJoint * j = &joints[i];\n\t\texternal(i * 2) = -j->externalX;\n\t\texternal(i * 2 + 1) = -j->externalY;\n\n\t\tfor (int k = 0; k < joints[i].connections.size(); k++) {\n\t\t\tequations(i * 2, joints[i].connections[k]) = (members[joints[i].connections[k]].joint1->x + members[j->connections[k]].joint2->x - 2 * j->x) / members[j->connections[k]].length;\n\t\t\tequations(i * 2 + 1, joints[i].connections[k]) = (members[joints[i].connections[k]].joint1->y + members[j->connections[k]].joint2->y - 2 * j->y) / members[j->connections[k]].length;\n\t\t}\n\t}\n\t\n\t//equations.print();\n\t//cout << endl << \"external\" << endl;\n\t/*external.print();\n\tcout << endl;\n\t*/\n\t//external.print();\n\t//cout << endl;\n\t//system(\"pause\");\n\tarma::vec forces = solve(equations, external);\n\t\n//\tforces.print();\n//\tcout << endl;*/\n\n    bool solveValid = true;\n    for (int i = 0; i < numMembers; i++){\n    \tif(fabs(forces(i)) >= fabs(validForces[i]) && fabs(forces(i)) > MAX_MEMBER_FORCE){\n\t\t\t//cout << \"invalid forces\" << endl;\n\t\t\tsolveValid = false;\n    \t\tbreak;\n    \t}\n    }\n\n    if (solveValid){\n\t\tfor (int i = 0; i < numMembers; i++){\n\t\t\tvalidForces[i] = forces(i);\n\t\t}\n        return true;\n    } else {\n        return false;\n    }\n}\n\ndouble * Truss::checkIfBetterState(bool xDir, int jointNum, double increment) {\n//\tcout << \"checking new state with joint \" << jointNum << \" moving \" << xDir << \" by \" << increment << endl;\n\tbool betterState = true;\n\tJoint * joint = &joints[jointNum];\n\tint numCon = joint->connections.size();\n\tdouble * newLengths = new double[numCon];\n\tdouble * oldLengths = NULL;\n\tdouble totalLen = 0;\n\n\t//changes x or y value based on the direction given\n\tif(xDir) {\n        joint->x += increment;\n    } else {\n\t    joint->y += increment;\n\t}\n\n\tfor (int i = 0; i < numCon; i++){\n\t\tnewLengths[i] = pow( pow(members[joint->connections[i]].joint1->x - members[joint->connections[i]].joint2->x , 2) + pow(members[joint->connections[i]].joint1->y - members[joint->connections[i]].joint2->y, 2 ) , 0.5);\n\t\tif(newLengths[i] > members[joint->connections[i]].length  && newLengths[i] > 3.00000000){\n\t\t\tbetterState = false;\n\t\t\tbreak;\n\t\t}\n//\t\tcout << \"length \" << i << newLengths[i] << endl;\n        totalLen += newLengths[i];\n\t}\n//\tcout << \"previos length: \" << joint->connectionLen << endl;\n    if (totalLen >= joint->connectionLen){\n        betterState = false;\n    }\n\tif (!betterState) {\n\t\tfor (int i = 0; i < numMembers; i++) {\n\t\t\tif (fabs(validForces[i]) >= MAX_MEMBER_FORCE) {\n\t\t\t\tbetterState = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t// if new state is better, copy length values into old length and\n\tif (betterState){\n//\t\tcout << \"state is better\" << endl;\n\t\tjoint->connectionLen = totalLen;\n\t\toldLengths = new double[numCon];\n\t\tfor (int i = 0; i< numCon; i++){\n\t\t    //change all the member geometry\n\t\t\toldLengths[i] = members[joint->connections[i]].length;\n\t\t\tmembers[joint->connections[i]].length = newLengths[i];\n//\t\t\tcout << \"m\" << i << \"L: \" << members[joint->connections[i]].length << endl;\n\t\t}\n\n\t}\n\t//reverts x or y value based on direction given if new state is not better\n\telse {\n\t//\tcout << \"state is worse. new: \" <<totalLen << \"\\told:\" <<joint->connectionLen << endl;\n        if(xDir) {\n            joint->x -= increment;\n        } else {\n\t\t\tjoint->y -= increment;\n\t\t}\n\t}\n\n\tdelete [] newLengths;\n\tnewLengths = NULL;\n\n\treturn oldLengths;\n}\n\nvoid Truss::revertLengths(int jointNum, double * oldLengths){\n\tfor (int i = 0; i < joints[jointNum].connections.size(); i++){\n\t\tmembers[joints[jointNum].connections[i]].length = oldLengths[i];\n\t}\n}\n\nvoid Truss::optimize(){\n\tinitialSolve();\n\tbool systemChanged = false;\n\tlong double movementIncrement = 0.0001;\n\tdouble * oldLengths = NULL;\n\n\twhile (movementIncrement > MIN_MOVEMENT_INCREMENT){\n\t\tsystemChanged = true;\n\t\twhile (systemChanged){\n\t\t\tsystemChanged = false;\n\t\t\tfor (int i  = 1; i < numJoints; i++){\n\n\t\t\t\t//testing vertical movement\n\t\t\t\tif (!joints[i].fixedY) {\n\t\t\t\t\toldLengths = checkIfBetterState(false, i, -movementIncrement);\n\t\t\t\t\tif (oldLengths != NULL) {\n\t\t\t\t\t\tif (solveInternal()) {\n\t\t\t\t\t\t\tsystemChanged = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjoints[i].y += movementIncrement;\n\t\t\t\t\t\t\trevertLengths(i, oldLengths);//move node back and adjust dimensions\n\t\t\t\t\t\t\tfor (int j = 0; j < numJoints; j++) {\n\t\t\t\t\t\t\t\tjoints[j].connectionLen = 0;\n\t\t\t\t\t\t\t\tfor (int con = 0; con < joints[j].connections.size(); con++) {\n\t\t\t\t\t\t\t\t\tjoints[j].connectionLen += members[joints[j].connections[con]].length;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsolveGeneralSystem();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\toldLengths = checkIfBetterState(false, i, movementIncrement);\n\t\t\t\t\t\tif (oldLengths != NULL) {\n\t\t\t\t\t\t\tif (solveInternal()) {\n\t\t\t\t\t\t\t\tsystemChanged = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tjoints[i].y -= movementIncrement;\n\t\t\t\t\t\t\t\trevertLengths(i, oldLengths);\n\t\t\t\t\t\t\t\tfor (int j = 0; j < numJoints; j++) {\n\t\t\t\t\t\t\t\t\tjoints[j].connectionLen = 0;\n\t\t\t\t\t\t\t\t\tfor (int con = 0; con < joints[j].connections.size(); con++) {\n\t\t\t\t\t\t\t\t\t\tjoints[j].connectionLen += members[joints[j].connections[con]].length;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsolveGeneralSystem();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (oldLengths != NULL) {\n\t\t\t\t\t\tdelete[] oldLengths;\n\t\t\t\t\t\toldLengths = NULL;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t//testing horizontal movement\n\t\t\t\tif (!joints[i].fixedX){\n\t\t\t\t\toldLengths = checkIfBetterState(true, i, movementIncrement*pow(-1, i));\n\t\t\t\t\tif (oldLengths != NULL) {\n\t\t\t\t\t    if(solveInternal()) {\n                            systemChanged = true;\n                        } else {\n\t\t\t\t\t\t\tjoints[i].x -= movementIncrement* pow(-1, i);\n\t\t\t\t\t    \trevertLengths(i, oldLengths);//move node back and adjust dimensions\n\t\t\t\t\t\t\tfor (int j = 0; j < numJoints; j++) {\n\t\t\t\t\t\t\t\tjoints[j].connectionLen = 0;\n\t\t\t\t\t\t\t\tfor (int con = 0; con < joints[j].connections.size(); con++) {\n\t\t\t\t\t\t\t\t\tjoints[j].connectionLen += members[joints[j].connections[con]].length;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tsolveGeneralSystem();\n\t\t\t\t\t    }\n\t\t\t\t\t} else {\n\t\t\t\t\t\toldLengths = checkIfBetterState(true, i, -movementIncrement* pow(-1, i));\n                        if (oldLengths != NULL){\n                            if (solveInternal()){\n                                systemChanged = true;\n                            } else {\n                                joints[i].x += movementIncrement*pow(-1, i);\n                            \trevertLengths(i, oldLengths);\n\t\t\t\t\t\t\t\tfor (int j = 0; j < numJoints; j++) {\n\t\t\t\t\t\t\t\t\tjoints[j].connectionLen = 0;\n\t\t\t\t\t\t\t\t\tfor (int con = 0; con < joints[j].connections.size(); con++) {\n\t\t\t\t\t\t\t\t\t\tjoints[j].connectionLen += members[joints[j].connections[con]].length;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tsolveGeneralSystem();\n                            }\n                        }\n\t\t\t\t\t}\n\t\t\t\t\tif(oldLengths != NULL){\n\t\t\t\t\t\tdelete [] oldLengths;\n\t\t\t\t\t\toldLengths = NULL;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\t\n\t\t\t\t//both movement directions tested\n\t\t\t\t//output(cout);\n//\t\t\t\tsystem(\"pause\");\n\t\t\t}\n\n\t\t\t//all joints have been moved\n\t\t}\n\t\t//system did not change on last iteration\n\t\tmovementIncrement /= 2;\n\t\tcout << \"Movement Increment Changed to: \" << movementIncrement << endl;\n\t}\n\t//movement increment <0.01\n}\n\n\n\nvoid Truss::output(ostream & out) const{\n\tfor(int i  = 0; i < numJoints; i++){\n\t\tout << \"Joint \" << i << \":  (\" << joints[i].x << \", \" << joints[i].y << \")\" << endl;\n\t}\n\tout << endl;\n\tdouble totalLength = 0;\n\tfor(int i  = 0; i < numMembers; i++){\n\t\ttotalLength += members[i].length;\n\t\tout << \"Member \" << setw(4) << i << \": \" << setw(20) << this->validForces[i] << \" kN\" << \"\\tLength: \" << members[i].length << endl;\n\t}\n\tout << endl << \"Total Length: \" << totalLength << endl;\n}\n\nvoid Truss::makeCSV(ostream & out) const {\n\tfor (int i = 0; i < numJoints; i++) {\n\t\tout <<  joints[i].x-0.1 << \",\" << joints[i].y << endl;\n\t}\n}", "meta": {"hexsha": "29c4838c5bb1ea2a088ef6a5cd39b2288abae06c", "size": 11334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Truss.cpp", "max_stars_repo_name": "charliefisher/Truss-Optimizer", "max_stars_repo_head_hexsha": "f7f851da665ae0150d26f7287c32abe42124e7b0", "max_stars_repo_licenses": ["Apache-1.1"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T03:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T03:19:24.000Z", "max_issues_repo_path": "Truss.cpp", "max_issues_repo_name": "charliefisher/Truss-Optimizer", "max_issues_repo_head_hexsha": "f7f851da665ae0150d26f7287c32abe42124e7b0", "max_issues_repo_licenses": ["Apache-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Truss.cpp", "max_forks_repo_name": "charliefisher/Truss-Optimizer", "max_forks_repo_head_hexsha": "f7f851da665ae0150d26f7287c32abe42124e7b0", "max_forks_repo_licenses": ["Apache-1.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3048128342, "max_line_length": 218, "alphanum_fraction": 0.5886712546, "num_tokens": 3361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.6654105521116445, "lm_q1q2_score": 0.5615367008902694}}
{"text": "/**\n * @date Wed Jan 30 17:25:28 CET 2013\n * @author Ivana Chingovska <ivana.chingovska@idiap.ch>\n *\n * @brief GLCMProp implementation\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <bob.core/array_copy.h>\n#include <bob.core/assert.h>\n#include <boost/make_shared.hpp>\n\n#include <bob.ip.base/GLCM.h>\n\nstatic double sqr(const double x)\n{\n  return x*x;\n}\n\n\nbob::ip::base::GLCMProp::GLCMProp(){ }\n\nbob::ip::base::GLCMProp::~GLCMProp() { }\n\nconst blitz::Array<double,3> bob::ip::base::GLCMProp::normalize_glcm(const blitz::Array<double,3>& glcm) const\n{\n   blitz::firstIndex i;\n   blitz::secondIndex j;\n   blitz::thirdIndex k;\n   blitz::Array<double, 2> summations_temp(blitz::sum(glcm(i, k, j), k));\n   blitz::Array<double, 1> summations(blitz::sum(summations_temp(j,i), j));\n   blitz::Array<double,3> res(glcm / summations(k));\n   return res;\n}\n\nconst blitz::TinyVector<int,1> bob::ip::base::GLCMProp::get_prop_shape(const blitz::Array<double,3>& glcm) const\n{\n  blitz::TinyVector<int,1> res;\n  res(0) = glcm.extent(2);\n  return res;\n}\n\n\n\nvoid bob::ip::base::GLCMProp::angular_second_moment(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = blitz::pow2(glcm_norm(rall, rall, l));\n    prop(l) = blitz::sum(mat); // angular second moment\n  }\n}\n\nvoid bob::ip::base::GLCMProp::energy(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  //do the computation of the feature\n  angular_second_moment(glcm, prop);\n  prop = blitz::sqrt(prop);\n}\n\nvoid bob::ip::base::GLCMProp::variance(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(sqr(i-blitz::mean(mat))*mat);\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::contrast(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum((i-j)*(i-j)*mat);\n  }\n  /*\n  //as done in [1]\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double contrast = 0;\n    for (int t=0; t < glcm_norm.extent(0) - 1; ++t) // iterate through all the levels\n    {\n      contrast += t*t*blitz::sum(blitz::where(abs(i-j)==t, mat, 0));\n    }\n    prop(l) = contrast;\n  }\n  */\n}\n\nvoid bob::ip::base::GLCMProp::auto_correlation(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(i*j*mat);\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::correlation(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double mean_x = blitz::sum(i*mat);\n    double mean_y = blitz::sum(j*mat);\n    double std_x = sqrt(blitz::sum(sqr(i-mean_x)*mat));\n    double std_y = sqrt(blitz::sum(sqr(j-mean_y)*mat));\n    prop(l) = (blitz::sum(i*j*mat) - mean_x*mean_y) / (std_x * std_y);\n  }\n}\n\nvoid bob::ip::base::GLCMProp::correlation_m(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double mean_x = blitz::sum(i*mat);\n    double mean_y = blitz::sum(j*mat);\n    double std_x = sqrt(blitz::sum(sqr(i-mean_x)*mat));\n    double std_y = sqrt(blitz::sum(sqr(j-mean_y)*mat));\n    prop(l) = blitz::sum(((i-mean_x) * (j-mean_x) * mat) / (std_x * std_y));\n  }\n}\n\nvoid bob::ip::base::GLCMProp::inv_diff_mom(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(mat / (1 + sqr(i-j)));\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::sum_avg(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double sum_avg = 0;\n    for (int t = 0; t < 2 * glcm_norm.extent(0) - 1; t++) // iterate through all the levels\n    {\n      sum_avg += t * blitz::sum(blitz::where(i+j==t, mat, 0));\n    }\n    prop(l) = sum_avg;\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::sum_var(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  blitz::Array<double,1>& prop_sum_entropy(prop);\n  sum_entropy(glcm, prop_sum_entropy);\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double sum_var = 0;\n    for (int t = 0; t < 2 * glcm_norm.extent(0) -1; t++) // iterate through all the levels\n    {\n      sum_var += sqr(t-prop_sum_entropy(l)) * blitz::sum(blitz::where(i+j==t, mat, 0));\n    }\n    prop(l) = sum_var;\n  }\n}\n\nvoid bob::ip::base::GLCMProp::sum_entropy(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double sum_entropy = 0;\n    for (int t = 0; t < 2 * glcm_norm.extent(0) - 1; t++) // iterate through all grey levels\n    {\n      sum_entropy += blitz::sum(blitz::where(i+j==t, mat, 0)) * log(blitz::sum(blitz::where(i+j==t, mat, 0)) + std::numeric_limits<double>::min());\n    }\n    prop(l) = -sum_entropy;\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::entropy(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = -blitz::sum(mat * blitz::log(mat + std::numeric_limits<double>::min())); // small numeric value is added to avoid 0 as an argument to the logarithm\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::diff_var(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double diff_var = 0;\n    for (int t = 0; t < glcm_norm.extent(0); t++) // iterate through all grey levels\n    {\n      diff_var +=  t * t * blitz::sum(blitz::where(abs(i-j)==t, mat, 0));\n    }\n    prop(l) = diff_var;\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::diff_entropy(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double diff_entropy = 0;\n    for (int t = 0; t < glcm_norm.extent(0); t++) // iterate through all grey levels\n    {\n      diff_entropy += blitz::sum(blitz::where(abs(i-j)==t, mat, 0)) * log(blitz::sum(blitz::where(abs(i-j)==t, mat, 0)) + std::numeric_limits<double>::min());\n    }\n    prop(l) = -diff_entropy;\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::dissimilarity(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(abs(i-j)*mat);\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::homogeneity(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(mat / (1 + abs(i-j)));\n  }\n}\n\n\nvoid bob::ip::base::GLCMProp::cluster_prom(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double mean_x = blitz::sum(i*mat);\n    double mean_y = blitz::sum(j*mat);\n    prop(l) = blitz::sum(pow(i + j - mean_x - mean_y, 4) * mat);\n  }\n}\n\nvoid bob::ip::base::GLCMProp::cluster_shade(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    double mean_x = blitz::sum(i*mat);\n    double mean_y = blitz::sum(j*mat);\n    prop(l) = blitz::sum(pow(i + j - mean_x - mean_y, 3) * mat);\n  }\n}\n\nvoid bob::ip::base::GLCMProp::max_prob(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::max(mat);\n  }\n}\n\nvoid bob::ip::base::GLCMProp::inf_meas_corr1(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  blitz::Array<double,1>& prop_entropy(prop);\n  entropy(glcm, prop_entropy); //calculate the entropy\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n\n    blitz::Array<double,1> marg_prob_i(blitz::sum(mat,j)); // marginal probability of first dimension (i.e. row-wise sum)\n    blitz::Array<double,1> marg_prob_j(blitz::sum(mat(j,i),j)); // marginal probability of second dimension (i.e. column-wise sum)\n\n    double hxy1 = -blitz::sum(mat * blitz::log(marg_prob_i(i) * marg_prob_j(j) + std::numeric_limits<double>::min())); // small numeric value is added to avoid 0 as an argument to the logarithm\n    double px_entropy = -blitz::sum(marg_prob_i * blitz::log(marg_prob_i + std::numeric_limits<double>::min()));\n    double py_entropy = -blitz::sum(marg_prob_j * blitz::log(marg_prob_j + std::numeric_limits<double>::min()));\n    prop(l) = (prop_entropy(l) - hxy1) / std::max(px_entropy, py_entropy);\n  }\n}\n\nvoid bob::ip::base::GLCMProp::inf_meas_corr2(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  blitz::Array<double,1>& prop_entropy(prop);\n  entropy(glcm, prop_entropy); //calculate the entropy\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    blitz::Array<double,1> marg_prob_i(blitz::sum(mat,j)); // marginal probability of first dimension (i.e. row-wise sum)\n    blitz::Array<double,1> marg_prob_j(blitz::sum(mat(j,i),j)); // marginal probability of second dimension (i.e. column-wise sum)\n\n    double hxy2 = -blitz::sum(marg_prob_i(i) * marg_prob_j(j) * blitz::log(marg_prob_i(i) * marg_prob_j(j) + std::numeric_limits<double>::min())); // small numeric value is added to avoid 0 as an argument to the logarithm\n    prop(l) = sqrt(1 - exp(-2 * (hxy2 - prop_entropy(l))));\n  }\n\n}\n\nvoid bob::ip::base::GLCMProp::inv_diff(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  homogeneity(glcm, prop);\n}\n\nvoid bob::ip::base::GLCMProp::inv_diff_norm(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(mat / (1 + (abs(i-j) / (double)mat.extent(0)) ));\n  }\n}\n\nvoid bob::ip::base::GLCMProp::inv_diff_mom_norm(const blitz::Array<double,3>& glcm, blitz::Array<double,1>& prop) const\n{\n  // check if the size of the output matrix is as expected\n  blitz::TinyVector<int,1> shape(get_prop_shape(glcm));\n  bob::core::array::assertSameShape(prop, shape);\n\n  // normalize the input GLCM matrix\n  blitz::Array<double,3> glcm_norm = normalize_glcm(glcm);\n\n  blitz::Array<double,2> mat(glcm.extent(0), glcm.extent(1)); // auxiliary matrix that will be used for glcm matrix for one particular offset\n\n  blitz::Range rall = blitz::Range::all();\n  blitz::firstIndex i;\n  blitz::secondIndex j;\n\n  //do the computation of the feature\n  for (int l=0; l < glcm_norm.extent(2); ++l)\n  {\n    mat = glcm_norm(rall, rall, l);\n    prop(l) = blitz::sum(mat / (1 + (sqr(i-j) / sqr(mat.extent(0)))));\n  }\n}\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "e943766a33c28d5a5e81a8c15392167120701c87", "size": 22486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/ip/base/cpp/GLCM.cpp", "max_stars_repo_name": "bioidiap/bob.ip.base", "max_stars_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-10-30T10:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-21T05:33:33.000Z", "max_issues_repo_path": "bob/ip/base/cpp/GLCM.cpp", "max_issues_repo_name": "bioidiap/bob.ip.base", "max_issues_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T18:00:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-24T08:18:05.000Z", "max_forks_repo_path": "bob/ip/base/cpp/GLCM.cpp", "max_forks_repo_name": "bioidiap/bob.ip.base", "max_forks_repo_head_hexsha": "d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-07-16T14:57:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-15T09:23:28.000Z", "avg_line_length": 34.5407066052, "max_line_length": 221, "alphanum_fraction": 0.6769545495, "num_tokens": 6698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5614850462583573}}
{"text": "#ifndef BFGS_HPP_\n#define BFGS_HPP_\n\n#include <Eigen/Core>\n\n/**\n * @file BFGS.hpp\n */\n\nnamespace rwlibs { namespace algorithms {\n\n    /** @addtogroup algorithms */\n    /*@{*/\n\n    /**\n     * @brief BFGS is a class including the BFGS minimization algorithm.\n     *\n     * The BFGS minimization algorithm has been implemented as described in \"Numerical Optimization\n     * - by Jorge Nocedal and Stephen J. Wright\" chapter 6+3. \\sa \\ref bfgsExample.cpp\n     * \"../example/bfgsApp/bfgsExample.cpp\"\n     */\n    class BFGS\n    {\n      public:\n        //! Vector type used in the minimazation algorithm.\n        typedef Eigen::VectorXd vector;\n        //! MAtrix type used in the minimazation algorithm.\n        typedef Eigen::MatrixXd matrix;\n\n        /**\n         * @brief Minimisation function struct.\n         */\n        struct BFGS_function_struct\n        {\n            /** Function pointer to the static minimization function @f$f(vec{x})@f$. */\n            double (*f) (const vector* x, void* params);\n            /** Function pointer to the static minimization function @f$df(vec{x})@f$. */\n            void (*df) (const vector* x, void* params, vector* g);\n            /** Void pointer to optional data that the minimization function might require */\n            void* params;\n        };\n\n        /**\n         * @brief Optimization status.\n         */\n        enum OPTM_STATUS {\n            /** Indicating a problem with the numerical precision when evaluating the gradient. */\n            GRADIENTWARNING = 0,\n            /** Indicating a successfully minimization. */\n            SUCCESS\n        };\n\n        /**\n         * @brief Minimize a function using the BFGS algorithm.\n         * @param startguess Start guess for the minimizer parameters. Replaced with minima solution\n         * at end of minimization.\n         * @param function BFGS_function_struct including pointers to the minimization function f,\n         * df and a void pointer to other data for the minimization function.\n         * @param tolerance Indicating when an acceptable minima has been found by evaluating if @f$\n         * tolerance>||\\Delta f(x)||_2 @f$.\n         * @param iterationLimit Maximum number of iterations for the BFGS algorithm.\n         * @param initialStepsize Initial step size for the BFGS algorithm.\n         * @param c1 Value used to ensure the \"strong Wolfe conditions\" are satisfied with the value\n         * c1. See \"Numerical Optimization - by Jorge Nocedal and Stephen J. Wright\" chapter 3.\n         * Typical value = 1e-4.\n         * @param c2 Value used to ensure the \"strong Wolfe conditions\" are satisfied with the value\n         * c2. See \"Numerical Optimization - by Jorge Nocedal and Stephen J. Wright\" chapter 3.\n         * Typical value = 0.9.\n         * @param alphamax Maximum stepsize used in iterations. Typical value of 1.0 is used to\n         * produce superlinear convergence of the overall algorithm.\n         * @return GRADIENTWARNING on numerically precision problems SUCCESS when a minima is found.\n         */\n        static int optimizer (vector& startguess, BFGS_function_struct function, double tolerance,\n                              unsigned int iterationLimit, double initialStepsize = 1.0,\n                              double c1 = 1e-4, double c2 = 0.9, double alphamax = 1.0);\n\n      private:\n        BFGS () {}\n\n        static void colDotRow (vector& colvec, vector& rowvec, matrix& result);\n\n        static double lineSearch (BFGS_function_struct function, vector& xk, vector& pk, double c1,\n                                  double c2, double alphamax);\n\n        static double phiGradient (BFGS_function_struct function, vector& xk, vector& pk,\n                                   double alpha, vector& tempArray, double phi_alpha, double eps);\n\n        static double zoom (double& alphalow, double& alphahigh, double& phi_alphalow,\n                            double& dphi_alphalow, double& phi_alphahigh,\n                            BFGS_function_struct function, vector& xk, vector& pk,\n                            vector& tempArray, double phi_alpha_zero, double dphi_alpha_zero,\n                            double c1, double c2, double eps);\n\n        static double quadraticInterpolation (double phi_alpha_lo, double dphi_alpha_lo,\n                                              double alpha_lo, double phi_alpha_hi,\n                                              double alpha_hi);\n    };\n    /** \\example bfgsExample.cpp\n     * Example of using the BFGS optimization algorithm for finding a minimum in the Rosenbrock\n     * function.\n     *\n     * The Rosenbrock function are defined by: @f$ f(x, y) = (1-x)^2 + 100(y-x^2)^2 @f$\n     */\n\n    /*@}*/\n}}     // namespace rwlibs::algorithms\n#endif /* BFGS_HPP_ */\n", "meta": {"hexsha": "b7921cd73cef6ba03f6c7a0e7baf3d1be47bdfaa", "size": 4755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/algorithms/BFGS.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/rwlibs/algorithms/BFGS.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/rwlibs/algorithms/BFGS.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": 44.0277777778, "max_line_length": 100, "alphanum_fraction": 0.6086225026, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.5614724686615283}}
{"text": "/**\n * BRIValue (Boost Rational with Infinity Value) class for Discrete Event Simulation purposes\n * Copyright (C) 2016  Laouen Mayal Louan Belloli\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 * any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef BRIVALUE_H\n#define BRIVALUE_H\n\n#include <iostream>\n#include <string>\n#include <boost/rational.hpp>\n\nusing namespace std;\n\nclass BRIValue {\n\n  private:\n    boost::rational<int> _value;\n    bool _inf;\n    bool _possitive;\n\n  public:\n    BRIValue() : _inf(false) {}\n    BRIValue(int n) : _value(n), _inf(false) {}\n    BRIValue(int n, int d) : _value(n,d), _inf(false) {}\n\n    static BRIValue infinity() noexcept {\n      BRIValue f;\n      f._inf=true;\n      f._possitive=true;\n      return f;\n    }\n\n    static BRIValue minusInfinity() noexcept {\n      BRIValue f;\n      f._inf=true;\n      f._possitive=false;\n      return f;\n    }\n\n    BRIValue& operator=(const BRIValue& o) noexcept { \n      this->_value = o._value;\n      this->_inf = o._inf;\n      this->_possitive = o._possitive;\n      return *this;\n    }\n\n\n    /* Aritmetical operators */\n\n    BRIValue& operator+=(const BRIValue& o) noexcept {\n      this->_value += o._value;\n      if (o._inf) {\n        this->_inf = o._inf;\n        this->_possitive = o._possitive; // + * {+/-} = {+/-}\n      };\n      return *this;\n    }\n\n    BRIValue& operator-=(const BRIValue& o) noexcept { \n      this->_value -= o._value;\n      if (!this->_inf && o._inf) {\n        this->_inf = o._inf;\n        this->_possitive = !o._possitive; // - * {+/-} = {-/+}\n      } else if (o._inf && (this->_possitive == o._possitive)) { //-inf-(-inf) = -inf+inf = 0 = inf-inf\n        this->_inf = false;\n        this->_value = boost::rational<int>(0);\n      }\n      return *this;\n    }\n\n    BRIValue& operator/=(const BRIValue& o) noexcept {\n      if (!this->inf) {\n        if (o._inf) {\n          this->_value = boost::rational<int>(0);\n        } else {\n          this->_value /= o._value;\n        }\n      }\n      return *this;\n    }\n\n    BRIValue& operator*=(const BRIValue& o) noexcept {\n      if (!this->inf && o._inf) {\n        this->_inf = o._inf;\n        this->_possitive = o._possitive;\n      } else if (o._inf && (this->_possitive == o._possitive)) { // (+ * + = -) and (- * - = +)\n        this->_possitive = !this->_possitive;\n      } else {\n        this->_value *= o._value;\n      }\n      return *this;\n    }\n\n    BRIValue& operator--() noexcept {\n      this->_value -= boost::rational<int>(1);\n      return *this;\n    }\n\n    BRIValue& operator++() noexcept {\n      this->_value += boost::rational<int>(1);\n      return *this;\n    }\n\n    string naturalDisplay() {\n      if (this->_inf) {\n        if (this->_possitive)\n          return \"inf\";\n        else\n          return \"-inf\";\n      }\n      \n      return to_string(_value.numerator()) + \"/\" + to_string(_value.denominator());  \n    }\n};\n\ninline BRIValue operator+(const BRIValue lhs, const BRIValue& rhs) noexcept {\n  BRIValue res = lhs;\n  res += rhs;\n  return res;\n}\n\ninline BRIValue operator-(const BRIValue lhs, const BRIValue& rhs) noexcept {\n  BRIValue res = lhs;\n  res -= rhs;\n  return res;\n}\n\ninline BRIValue operator/(const BRIValue lhs, const BRIValue& rhs) noexcept {\n  BRIValue res = lhs;\n  res /= rhs; \n  return res;\n}\n\ninline bool operator==(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n\n  if (lhs._inf && rhs._inf) return (lhs._possitive == rhs._possitive);\n  else if (lhs._inf || rhs._inf) return false;\n  return (lhs._value == rhs._value);\n}\n\ninline bool operator!=(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n  return !operator==(lhs,rhs);\n}\n\ninline bool operator<(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n  if (lhs._inf && lhs._possitive) return false;\n  else if (lhs._inf && !lhs._possitive) return !(rhs._inf && !rhs._possitive);\n  else if (rhs._inf && rhs._possitive) return true;\n  else if (rhs._inf) return false;\n  return (lhs._value < rhs._value);\n}\n\ninline bool operator>(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n  return  operator< (rhs,lhs);\n}\n\ninline bool operator<=(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n  return !operator> (lhs,rhs);\n}\n\ninline bool operator>=(const BRIValue& lhs, const BRIValue& rhs) noexcept {\n  return !operator< (lhs,rhs);\n}\n\ninline std::ostream& operator<<(std::ostream& os, const BRIValue& t) noexcept {\n    \n  if (t._inf) {\n    if (t._possitive)\n      os << \"inf\";\n    else\n      os << \"-inf\";\n  } else {\n    os << t._value;\n  } \n  return os;\n}\n\ninline std::istream& operator>>std::istream& is, BRIValue& rhs) noexcept {\n  string a;\n  int n,d;\n  is >> a;\n  if (a == \"inf\") rhs = BRIValue::infinity();\n  else if (a == \"-inf\") = BRIValue::minusInfinity();\n  else {\n    n = std::stoi(a.substr(0, a.find_last_of(\"/\")));\n    d = std::stoi(a.substr(a.find_last_of(\"/\")+1));\n    rhs = BRIValue(n,d);\n  }\n  return is;\n}\n\n\n  //TODO: Chack this specialization\n  // Specialize numeric_limits\nnamespace std {\n  template<>\n  class numeric_limits<BRIValue>{\n  public:\n    static constexpr bool is_specialized = true;\n    static BRIValue min() noexcept { return BRIValue(-1,1) * BRIValue{numeric_limits<int>::max(), numeric_limits<int>::min()}; }\n    static BRIValue max() noexcept { return BRIValue{numeric_limits<int>::max(), numeric_limits<int>::min()}; }\n    static BRIValue lowest() noexcept { return BRIValue(-1,1) * BRIValue{numeric_limits<int>::max(), numeric_limits<int>::min()}; }\n\n    static constexpr bool is_signed = true;\n    static constexpr bool is_integer = false;\n    static constexpr bool is_exact = true;\n    static BRIValue epsilon() noexcept { return BRIValue{1,1} - BRIValue{numeric_limits<int>::max(), numeric_limits<int>::max() - 1}; }\n    static BRIValue round_error() noexcept { return BRIValue(0); }\n\n    static constexpr int  min_exponent = numeric_limits<int>::min(); // trash_value\n    static constexpr int  min_exponent10 = min_exponent/radix; // trash_value\n    static constexpr int  max_exponent = numeric_limits<int>::max(); // trash_value\n    static constexpr int  max_exponent10 = max_exponent/radix; // trash_value\n\n    static constexpr bool has_infinity = true;\n    static constexpr bool has_quiet_NaN = false;\n    static constexpr bool has_signaling_NaN = false;\n    static constexpr float_denorm_style has_denorm = denorm_indeterminate;\n    static constexpr bool has_denorm_loss = false;\n    static BRIValue infinity() noexcept { return BRIValue::infinity(); }\n\n    static constexpr bool is_iec559 = false;\n    static constexpr bool is_bounded = false;\n    static constexpr bool is_modulo = false;\n\n    static constexpr bool traps = false;\n    static constexpr bool tinyness_before = false;\n  };\n}\n\n#endif // BRIVALUE_H", "meta": {"hexsha": "2e6aa51ec851cb1777e783bb2130da9947ba3ba2", "size": 7233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "DESTimes/include/BRIValue.hpp", "max_stars_repo_name": "SimulationEverywhere/NEP_DAM", "max_stars_repo_head_hexsha": "bc8cdf661c4a4e050abae12fb756f41ec6240e6b", "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": "DESTimes/include/BRIValue.hpp", "max_issues_repo_name": "SimulationEverywhere/NEP_DAM", "max_issues_repo_head_hexsha": "bc8cdf661c4a4e050abae12fb756f41ec6240e6b", "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": "DESTimes/include/BRIValue.hpp", "max_forks_repo_name": "SimulationEverywhere/NEP_DAM", "max_forks_repo_head_hexsha": "bc8cdf661c4a4e050abae12fb756f41ec6240e6b", "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.5224489796, "max_line_length": 135, "alphanum_fraction": 0.6361122632, "num_tokens": 1993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.5613717364153322}}
{"text": "//=========================================================================\n//\n// Copyright 2019 Kitware, Inc.\n// Author: Guilbert Pierre (spguilbert@gmail.com)\n// Data: 03-27-2019\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//=========================================================================\n\n// LOCAL\n#include \"CameraProjection.h\"\n#include \"vtkEigenTools.h\"\n\n// STD\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n// BOOST\n#include <boost/algorithm/string.hpp>\n\n//-----------------------------------------------------------------------------\nEigen::Vector3d GetRGBColourFromReflectivity(double v, double vmin, double vmax)\n{\n   Eigen::Vector3d c(1.0, 1.0, 1.0); // white\n   double dv;\n   if (v < vmin)\n      v = vmin;\n   if (v > vmax)\n      v = vmax;\n   dv = vmax - vmin;\n\n   if (v < (vmin + 0.25 * dv)) {\n      c[2] = 0;\n      c[1] = 4 * (v - vmin) / dv;\n   } else if (v < (vmin + 0.5 * dv)) {\n      c[2] = 0;\n      c[0] = 1 + 4 * (vmin + 0.25 * dv - v) / dv;\n   } else if (v < (vmin + 0.75 * dv)) {\n      c[2] = 4 * (v - vmin - 0.5 * dv) / dv;\n      c[0] = 0;\n   } else {\n      c[1] = 1 + 4 * (vmin + 0.75 * dv - v) / dv;\n      c[0] = 0;\n   }\n   return 255.0 * c;\n}\n\n//----------------------------------------------------------------------------\nvoid LoadCameraParamsFromCSV(std::string filename, Eigen::VectorXd& W)\n{\n  // Load file and check that the file is opened\n  std::ifstream file(filename.c_str());\n  if (!file.is_open())\n  {\n    std::cout << \"Error: could not load file: \" << filename << std::endl;\n    return;\n  }\n\n  std::string line;\n  std::getline(file, line);\n  std::vector<std::string> values;\n  boost::algorithm::split(values, line, boost::is_any_of(\",\"));\n  // initialize the parameters\n  W = Eigen::VectorXd(values.size(), 1);\n  for (int i = 0; i < values.size(); ++i)\n  {\n    W(i) = std::atof(values[i].c_str());\n  }\n  return;\n}\n\n//----------------------------------------------------------------------------\nvoid WriteCameraParamsCSV(std::string filename, Eigen::VectorXd& W)\n{\n  // Load file and check that the file is opened\n  std::ofstream file(filename.c_str());\n  if (!file.is_open())\n  {\n    std::cout << \"Error: could not open file: \" << filename << std::endl;\n    return;\n  }\n  for (int i = 0; i < W.size(); ++i)\n  {\n    file << W(i) << \",\";\n  }\n  file.close();\n  return;\n}\n\n//----------------------------------------------------------------------------\nEigen::Vector2d FisheyeProjection(const Eigen::Matrix<double, 15, 1>& W,\n                                  const Eigen::Vector3d& X,\n                                  bool shouldClip)\n{\n  // Get rotation matrix\n  Eigen::Matrix3d R = RollPitchYawToMatrix(W(0), W(1), W(2));\n  Eigen::Vector3d T(W(3), W(4), W(5));\n\n  // Express the 3D point in the camera reference frame\n  Eigen::Vector3d Xcam = R.transpose() * (X - T);\n\n  // check that the point is not behind the camera plane\n  if (shouldClip && (Xcam(2) < 0))\n  {\n    return Eigen::Vector2d(-1, -1);\n  }\n\n  // Project the 3D point in the plan\n  Eigen::Vector2d Xp1(Xcam(0) / Xcam(2), Xcam(1) / Xcam(2));\n\n  // Undistorded the projected image\n  double r = Xp1.norm();\n  double theta = std::atan(r);\n  double thetad = theta * (1 + W(11) * std::pow(theta, 2) + W(12) * std::pow(theta, 4) +\n                           W(13) * std::pow(theta, 6) + W(14) * std::pow(theta, 8));\n   Eigen::Vector2d Xp1d = (thetad / r) * Xp1;\n\n   // Create current intrinsic parameters\n   Eigen::Matrix3d K = Eigen::Matrix3d::Zero();\n   K(0, 0) = W(6);\n   K(1, 1) = W(7);\n   K(0, 2) = W(8);\n   K(1, 2) = W(9);\n   K(0, 1) = W(10);\n   K(2, 2) = 1;\n\n   // Express the point in the pixel coordinates\n   Eigen::Vector3d Xp1dh(Xp1d(0), Xp1d(1), 1);\n   Eigen::Vector3d Xpix = K * Xp1dh;\n   return Eigen::Vector2d(Xpix(0) / Xpix(2), Xpix(1) / Xpix(2));\n}\n\n//----------------------------------------------------------------------------\nEigen::Vector2d BrownConradyPinholeProjection(const Eigen::Matrix<double, 17, 1>& W,\n                                              const Eigen::Vector3d& X,\n                                              bool shouldClip)\n{\n  // Get rotation matrix\n  Eigen::Matrix3d R = RollPitchYawToMatrix(W(0), W(1), W(2));\n  Eigen::Vector3d T(W(3), W(4), W(5));\n\n  // Express the 3D point in the camera reference frame\n  Eigen::Vector3d Xcam = R.transpose() * (X - T);\n\n  // check that the point is not behind the camera plane\n  if (shouldClip && (Xcam(2) < 0))\n  {\n    return Eigen::Vector2d(-1, -1);\n  }\n\n  // Project the 3D point in the plan\n  Eigen::Vector2d Xp1(Xcam(0) / Xcam(2), Xcam(1) / Xcam(2));\n\n  // Undistorded the projected image\n  double r = Xp1.norm();\n  double k1 = W(11); double k2 = W(12);\n  double p1 = W(13); double p2 = W(14);\n  double p3 = W(15); double p4 = W(16);\n\n  double xdist = Xp1(0) + Xp1(0) * (k1 * std::pow(r, 2) + k2 * std::pow(r, 4)) +\n                 (p1 * (std::pow(r, 2) + 2 * std::pow(Xp1(0), 2)) +\n                  2 * p2 * Xp1(0) * Xp1(1)) * (1 + p3 * std::pow(r, 2) + p4 * std::pow(r, 4));\n  double ydist = Xp1(1) + Xp1(1) * (k1 * std::pow(r, 2) + k2 * std::pow(r, 4)) +\n                 (2 * p1 * Xp1(0) * Xp1(1) + p2 * (std::pow(r, 2) + 2 * std::pow(Xp1(1), 2))) *\n                 (1 + p3 * std::pow(r, 2) + p4 * std::pow(r, 4));\n  Eigen::Vector2d Xp1d(xdist, ydist);\n\n   // Create current intrinsic parameters\n   Eigen::Matrix3d K = Eigen::Matrix3d::Zero();\n   K(0, 0) = W(6);\n   K(1, 1) = W(7);\n   K(0, 2) = W(8);\n   K(1, 2) = W(9);\n   K(0, 1) = W(10);\n   K(2, 2) = 1;\n\n   // Express the point in the pixel coordinates\n   Eigen::Vector3d Xp1dh(Xp1d(0), Xp1d(1), 1);\n   Eigen::Vector3d Xpix = K * Xp1dh;\n   return Eigen::Vector2d(Xpix(0) / Xpix(2), Xpix(1) / Xpix(2));\n}\n", "meta": {"hexsha": "de457619198b09612ebe16d12912208924a51df8", "size": 6178, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Common/CameraProjection.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/Common/CameraProjection.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/Common/CameraProjection.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": 32.0103626943, "max_line_length": 95, "alphanum_fraction": 0.5134347685, "num_tokens": 2015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5613717300738883}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\n*                                                                               *\n*  The MIT License                                                              *\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 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 NON INFRINGEMENT. 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*  Author(s):                                                                   *\n*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/matrix.h>\n#include <Eigen/Eigenvalues>\n\nnamespace cinolib\n{\n\n// http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html\n//\nCINO_INLINE\nvoid eigen_decomposition_2x2(const float   a00,\n                             const float   a01,\n                             const float   a10,\n                             const float   a11,\n                                   vec2f  & v_min, // eigenvectors\n                                   vec2f  & v_max,\n                                   float & min,   // eigenvalues\n                                   float & max)\n{\n    eigenvalues_2x2(a00,a01,a10,a11,min,max);\n\n    if(std::fabs(a10)>1e-5)\n    {\n        v_max = vec2f(max-a11,a10);\n        v_min = vec2f(min-a11,a10);\n    }\n    else if(std::fabs(a01)>1e-5)\n    {\n        v_max = vec2f(a01,max-a00);\n        v_min = vec2f(a01,min-a00);\n    }\n    else\n    {\n        v_max = (a00>=a11) ? vec2f(1,0) : vec2f(0,1);\n        v_min = (a00>=a11) ? vec2f(0,1) : vec2f(1,0);\n    }\n\n    v_max.normalize();\n    v_min.normalize();\n}\n\n// http://www.math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/index.html\n//\nCINO_INLINE\nvoid eigenvalues_2x2(const float   a00,\n                     const float   a01,\n                     const float   a10,\n                     const float   a11,\n                           float & min,\n                           float & max)\n{\n    float T = a00 + a11; // trace\n    float D = determinant_2x2(a00,a01,a10,a11);\n\n    min = T/2.0 - sqrt(T*T/4.0-D);\n    max = T/2.0 + sqrt(T*T/4.0-D);\n}\n\nCINO_INLINE\nvoid eigenvectors_2x2(const float   a00,\n                      const float   a01,\n                      const float   a10,\n                      const float   a11,\n                            vec2f  & v_min,\n                            vec2f  & v_max)\n{\n    float min, max;\n    eigen_decomposition_2x2(a00, a01, a10, a11, v_min, v_max, min, max);\n}\n\nCINO_INLINE\nfloat determinant_2x2(const float a00, const float a01, const float a10, const float a11)\n{\n    return ((a00*a11) - (a10*a01));\n}\n\nCINO_INLINE\nfloat determinant_2x2(const vec2f a0, const vec2f a1)\n{\n    return determinant_2x2(a0[0], a0[1], a1[0], a1[1]);\n}\n\nCINO_INLINE\nvoid eigen_decomposition_3x3(const float   a[3][3],\n                                   vec3f  & v_min, // eigenvectors\n                                   vec3f  & v_mid,\n                                   vec3f  & v_max,\n                                   float & min,   // eigenvalues\n                                   float & mid,\n                                   float & max)\n{\n    eigen_decomposition_3x3(a[0][0], a[0][1], a[0][2],\n                            a[1][0], a[1][1], a[1][2],\n                            a[2][0], a[2][1], a[2][2],\n                            v_min, v_mid, v_max,\n                            min, mid, max);\n}\n\nCINO_INLINE\nvoid eigen_decomposition_3x3(const float   a00,\n                             const float   a01,\n                             const float   a02,\n                             const float   a10,\n                             const float   a11,\n                             const float   a12,\n                             const float   a20,\n                             const float   a21,\n                             const float   a22,\n                                   vec3f  & v_min, // eigenvectors\n                                   vec3f  & v_mid,\n                                   vec3f  & v_max,\n                                   float & min,   // eigenvalues\n                                   float & mid,\n                                   float & max)\n{\n    Eigen::Matrix3d m;\n    m << a00, a01, a02,\n         a10, a11, a12,\n         a20, a21, a22;\n\n    bool symmetric = (a10==a01) && (a20==a02) && (a21==a12);\n\n    if(symmetric)\n    {\n        // eigen decomposition for self-adjoint matrices\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(m);\n        assert(eig.info() == Eigen::Success);\n\n        v_min = vec3f(eig.eigenvectors()(0,0), eig.eigenvectors()(1,0), eig.eigenvectors()(2,0));\n        v_mid = vec3f(eig.eigenvectors()(0,1), eig.eigenvectors()(1,1), eig.eigenvectors()(2,1));\n        v_max = vec3f(eig.eigenvectors()(0,2), eig.eigenvectors()(1,2), eig.eigenvectors()(2,2));\n\n        min = eig.eigenvalues()[0];\n        mid = eig.eigenvalues()[1];\n        max = eig.eigenvalues()[2];\n    }\n    else\n    {\n        // eigen decomposition for general matrices\n        Eigen::EigenSolver<Eigen::Matrix3d> eig(m);\n        assert(eig.info() == Eigen::Success);\n\n        // WARNING: I am taking only the real part!\n        v_min = vec3f(eig.eigenvectors()(0,0).real(), eig.eigenvectors()(1,0).real(), eig.eigenvectors()(2,0).real());\n        v_mid = vec3f(eig.eigenvectors()(0,1).real(), eig.eigenvectors()(1,1).real(), eig.eigenvectors()(2,1).real());\n        v_max = vec3f(eig.eigenvectors()(0,2).real(), eig.eigenvectors()(1,2).real(), eig.eigenvectors()(2,2).real());\n\n        // WARNING: I am taking only the real part!\n        min = eig.eigenvalues()[0].real();\n        mid = eig.eigenvalues()[1].real();\n        max = eig.eigenvalues()[2].real();\n    }\n}\n\nCINO_INLINE\nvoid eigenvalues_3x3(const float   a00,\n                     const float   a01,\n                     const float   a02,\n                     const float   a10,\n                     const float   a11,\n                     const float   a12,\n                     const float   a20,\n                     const float   a21,\n                     const float   a22,\n                           float & min,\n                           float & mid,\n                           float & max)\n{\n    vec3f v_min, v_mid, v_max;\n    eigen_decomposition_3x3(a00, a01, a02, a10, a11, a12, a20, a21, a22, v_min, v_mid, v_max, min, mid, max);\n}\n\nCINO_INLINE\nvoid eigenvectors_3x3(const float   a00,\n                      const float   a01,\n                      const float   a02,\n                      const float   a10,\n                      const float   a11,\n                      const float   a12,\n                      const float   a20,\n                      const float   a21,\n                      const float   a22,\n                            vec3f  & v_min,\n                            vec3f  & v_mid,\n                            vec3f  & v_max)\n{\n    float min, mid, max;\n    eigen_decomposition_3x3(a00, a01, a02, a10, a11, a12, a20, a21, a22, v_min, v_mid, v_max, min, mid, max);\n}\n\nCINO_INLINE\nfloat determinant_3x3(const float a00, const float a01, const float a02,\n                       const float a10, const float a11, const float a12,\n                       const float a20, const float a21, const float a22)\n{\n    return a00 * determinant_2x2(a11, a12, a21, a22) -\n           a01 * determinant_2x2(a10, a12, a20, a22) +\n           a02 * determinant_2x2(a10, a11, a20, a21);\n}\n\nCINO_INLINE\nvoid from_std_3x3_to_Eigen_3x3(const float stdM[3][3], Eigen::Matrix3d & eigenM)\n{\n    eigenM.coeffRef(0,0) = stdM[0][0];  eigenM.coeffRef(0,1) = stdM[0][1];  eigenM.coeffRef(0,2) = stdM[0][2];\n    eigenM.coeffRef(1,0) = stdM[1][0];  eigenM.coeffRef(1,1) = stdM[1][1];  eigenM.coeffRef(1,2) = stdM[1][2];\n    eigenM.coeffRef(2,0) = stdM[2][0];  eigenM.coeffRef(2,1) = stdM[2][1];  eigenM.coeffRef(2,2) = stdM[2][2];\n}\n\nCINO_INLINE\nvoid from_eigen_3x3_to_std_3x3(const Eigen::Matrix3d & eigenM, float stdM[3][3])\n{\n    stdM[0][0] = eigenM.coeffRef(0,0);  stdM[0][1] = eigenM.coeffRef(0,1);  stdM[0][2] = eigenM.coeffRef(0,2);\n    stdM[1][0] = eigenM.coeffRef(1,0);  stdM[1][1] = eigenM.coeffRef(1,1);  stdM[1][2] = eigenM.coeffRef(1,2);\n    stdM[2][0] = eigenM.coeffRef(2,0);  stdM[2][1] = eigenM.coeffRef(2,1);  stdM[2][2] = eigenM.coeffRef(2,2);\n}\n}\n", "meta": {"hexsha": "90b6a33fd0474001f3de5b1d2705a63003a718a4", "size": 10567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/matrix.cpp", "max_stars_repo_name": "goodengineer/cinolib", "max_stars_repo_head_hexsha": "7de4de6816ed617e76a0517409e3e84c4546685e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cinolib/matrix.cpp", "max_issues_repo_name": "goodengineer/cinolib", "max_issues_repo_head_hexsha": "7de4de6816ed617e76a0517409e3e84c4546685e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cinolib/matrix.cpp", "max_forks_repo_name": "goodengineer/cinolib", "max_forks_repo_head_hexsha": "7de4de6816ed617e76a0517409e3e84c4546685e", "max_forks_repo_licenses": ["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.0996015936, "max_line_length": 118, "alphanum_fraction": 0.4541497114, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478913248044, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.5613717217610109}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_CARDINAL_CUBIC_B_SPLINE_DETAIL_HPP\n#define BOOST_MATH_INTERPOLATORS_CARDINAL_CUBIC_B_SPLINE_DETAIL_HPP\n\n#include <limits>\n#include <cmath>\n#include <vector>\n#include <memory>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace boost{ namespace math{ namespace interpolators{ namespace detail{\n\n\ntemplate <class Real>\nclass cardinal_cubic_b_spline_imp\n{\npublic:\n    // If you don't know the value of the derivative at the endpoints, leave them as nans and the routine will estimate them.\n    // f[0] = f(a), f[length -1] = b, step_size = (b - a)/(length -1).\n    template <class BidiIterator>\n    cardinal_cubic_b_spline_imp(BidiIterator f, BidiIterator end_p, Real left_endpoint, Real step_size,\n                       Real left_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN(),\n                       Real right_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN());\n\n    Real operator()(Real x) const;\n\n    Real prime(Real x) const;\n\n    Real double_prime(Real x) const;\n\nprivate:\n    std::vector<Real> m_beta;\n    Real m_h_inv;\n    Real m_a;\n    Real m_avg;\n};\n\n\n\ntemplate <class Real>\nReal b3_spline(Real x)\n{\n    using std::abs;\n    Real absx = abs(x);\n    if (absx < 1)\n    {\n        Real y = 2 - absx;\n        Real z = 1 - absx;\n        return boost::math::constants::sixth<Real>()*(y*y*y - 4*z*z*z);\n    }\n    if (absx < 2)\n    {\n        Real y = 2 - absx;\n        return boost::math::constants::sixth<Real>()*y*y*y;\n    }\n    return (Real) 0;\n}\n\ntemplate<class Real>\nReal b3_spline_prime(Real x)\n{\n    if (x < 0)\n    {\n        return -b3_spline_prime(-x);\n    }\n\n    if (x < 1)\n    {\n        return x*(3*boost::math::constants::half<Real>()*x - 2);\n    }\n    if (x < 2)\n    {\n        return -boost::math::constants::half<Real>()*(2 - x)*(2 - x);\n    }\n    return (Real) 0;\n}\n\ntemplate<class Real>\nReal b3_spline_double_prime(Real x)\n{\n    if (x < 0)\n    {\n        return b3_spline_double_prime(-x);\n    }\n\n    if (x < 1)\n    {\n        return 3*x - 2;\n    }\n    if (x < 2)\n    {\n        return (2 - x);\n    }\n    return (Real) 0;\n}\n\n\ntemplate <class Real>\ntemplate <class BidiIterator>\ncardinal_cubic_b_spline_imp<Real>::cardinal_cubic_b_spline_imp(BidiIterator f, BidiIterator end_p, Real left_endpoint, Real step_size,\n                                             Real left_endpoint_derivative, Real right_endpoint_derivative) : m_a(left_endpoint), m_avg(0)\n{\n    using boost::math::constants::third;\n\n    std::size_t length = end_p - f;\n\n    if (length < 5)\n    {\n        if (boost::math::isnan(left_endpoint_derivative) || boost::math::isnan(right_endpoint_derivative))\n        {\n            throw std::logic_error(\"Interpolation using a cubic b spline with derivatives estimated at the endpoints requires at least 5 points.\\n\");\n        }\n        if (length < 3)\n        {\n            throw std::logic_error(\"Interpolation using a cubic b spline requires at least 3 points.\\n\");\n        }\n    }\n\n    if (boost::math::isnan(left_endpoint))\n    {\n        throw std::logic_error(\"Left endpoint is NAN; this is disallowed.\\n\");\n    }\n    if (left_endpoint + length*step_size >= (std::numeric_limits<Real>::max)())\n    {\n        throw std::logic_error(\"Right endpoint overflows the maximum representable number of the specified precision.\\n\");\n    }\n    if (step_size <= 0)\n    {\n        throw std::logic_error(\"The step size must be strictly > 0.\\n\");\n    }\n    // Storing the inverse of the stepsize does provide a measurable speedup.\n    // It's not huge, but nonetheless worthwhile.\n    m_h_inv = 1/step_size;\n\n    // Following Kress's notation, s'(a) = a1, s'(b) = b1\n    Real a1 = left_endpoint_derivative;\n    // See the finite-difference table on Wikipedia for reference on how\n    // to construct high-order estimates for one-sided derivatives:\n    // https://en.wikipedia.org/wiki/Finite_difference_coefficient#Forward_and_backward_finite_difference\n    // Here, we estimate then to O(h^4), as that is the maximum accuracy we could obtain from this method.\n    if (boost::math::isnan(a1))\n    {\n        // For simple functions (linear, quadratic, so on)\n        // almost all the error comes from derivative estimation.\n        // This does pairwise summation which gives us another digit of accuracy over naive summation.\n        Real t0 = 4*(f[1] + third<Real>()*f[3]);\n        Real t1 = -(25*third<Real>()*f[0] + f[4])/4  - 3*f[2];\n        a1 = m_h_inv*(t0 + t1);\n    }\n\n    Real b1 = right_endpoint_derivative;\n    if (boost::math::isnan(b1))\n    {\n        size_t n = length - 1;\n        Real t0 = 4*(f[n-3] + third<Real>()*f[n - 1]);\n        Real t1 = -(25*third<Real>()*f[n - 4] + f[n])/4  - 3*f[n - 2];\n\n        b1 = m_h_inv*(t0 + t1);\n    }\n\n    // s(x) = \\sum \\alpha_i B_{3}( (x- x_i - a)/h )\n    // Of course we must reindex from Kress's notation, since he uses negative indices which make C++ unhappy.\n    m_beta.resize(length + 2, std::numeric_limits<Real>::quiet_NaN());\n\n    // Since the splines have compact support, they decay to zero very fast outside the endpoints.\n    // This is often very annoying; we'd like to evaluate the interpolant a little bit outside the\n    // boundary [a,b] without massive error.\n    // A simple way to deal with this is just to subtract the DC component off the signal, so we need the average.\n    // This algorithm for computing the average is recommended in\n    // http://www.heikohoffmann.de/htmlthesis/node134.html\n    Real t = 1;\n    for (size_t i = 0; i < length; ++i)\n    {\n        if (boost::math::isnan(f[i]))\n        {\n            std::string err = \"This function you are trying to interpolate is a nan at index \" + std::to_string(i) + \"\\n\";\n            throw std::logic_error(err);\n        }\n        m_avg += (f[i] - m_avg) / t;\n        t += 1;\n    }\n\n\n    // Now we must solve an almost-tridiagonal system, which requires O(N) operations.\n    // There are, in fact 5 diagonals, but they only differ from zero on the first and last row,\n    // so we can patch up the tridiagonal row reduction algorithm to deal with two special rows.\n    // See Kress, equations 8.41\n    // The the \"tridiagonal\" matrix is:\n    // 1  0 -1\n    // 1  4  1\n    //    1  4  1\n    //       1  4  1\n    //          ....\n    //          1  4  1\n    //          1  0 -1\n    // Numerical estimate indicate that as N->Infinity, cond(A) -> 6.9, so this matrix is good.\n    std::vector<Real> rhs(length + 2, std::numeric_limits<Real>::quiet_NaN());\n    std::vector<Real> super_diagonal(length + 2, std::numeric_limits<Real>::quiet_NaN());\n\n    rhs[0] = -2*step_size*a1;\n    rhs[rhs.size() - 1] = -2*step_size*b1;\n\n    super_diagonal[0] = 0;\n\n    for(size_t i = 1; i < rhs.size() - 1; ++i)\n    {\n        rhs[i] = 6*(f[i - 1] - m_avg);\n        super_diagonal[i] = 1;\n    }\n\n\n    // One step of row reduction on the first row to patch up the 5-diagonal problem:\n    // 1 0 -1 | r0\n    // 1 4 1  | r1\n    // mapsto:\n    // 1 0 -1 | r0\n    // 0 4 2  | r1 - r0\n    // mapsto\n    // 1 0 -1 | r0\n    // 0 1 1/2| (r1 - r0)/4\n    super_diagonal[1] = 0.5;\n    rhs[1] = (rhs[1] - rhs[0])/4;\n\n    // Now do a tridiagonal row reduction the standard way, until just before the last row:\n    for (size_t i = 2; i < rhs.size() - 1; ++i)\n    {\n        Real diagonal = 4 - super_diagonal[i - 1];\n        rhs[i] = (rhs[i] - rhs[i - 1])/diagonal;\n        super_diagonal[i] /= diagonal;\n    }\n\n    // Now the last row, which is in the form\n    // 1 sd[n-3] 0      | rhs[n-3]\n    // 0  1     sd[n-2] | rhs[n-2]\n    // 1  0     -1      | rhs[n-1]\n    Real final_subdiag = -super_diagonal[rhs.size() - 3];\n    rhs[rhs.size() - 1] = (rhs[rhs.size() - 1] - rhs[rhs.size() - 3])/final_subdiag;\n    Real final_diag = -1/final_subdiag;\n    // Now we're here:\n    // 1 sd[n-3] 0         | rhs[n-3]\n    // 0  1     sd[n-2]    | rhs[n-2]\n    // 0  1     final_diag | (rhs[n-1] - rhs[n-3])/diag\n\n    final_diag = final_diag - super_diagonal[rhs.size() - 2];\n    rhs[rhs.size() - 1] = rhs[rhs.size() - 1] - rhs[rhs.size() - 2];\n\n\n    // Back substitutions:\n    m_beta[rhs.size() - 1] = rhs[rhs.size() - 1]/final_diag;\n    for(size_t i = rhs.size() - 2; i > 0; --i)\n    {\n        m_beta[i] = rhs[i] - super_diagonal[i]*m_beta[i + 1];\n    }\n    m_beta[0] = m_beta[2] + rhs[0];\n}\n\ntemplate<class Real>\nReal cardinal_cubic_b_spline_imp<Real>::operator()(Real x) const\n{\n    // See Kress, 8.40: Since B3 has compact support, we don't have to sum over all terms,\n    // just the (at most 5) whose support overlaps the argument.\n    Real z = m_avg;\n    Real t = m_h_inv*(x - m_a) + 1;\n\n    using std::max;\n    using std::min;\n    using std::ceil;\n    using std::floor;\n\n    size_t k_min = (size_t) (max)(static_cast<long>(0), boost::math::ltrunc(ceil(t - 2)));\n    size_t k_max = (size_t) (max)((min)(static_cast<long>(m_beta.size() - 1), boost::math::ltrunc(floor(t + 2))), (long) 0);\n\n    for (size_t k = k_min; k <= k_max; ++k)\n    {\n        z += m_beta[k]*b3_spline(t - k);\n    }\n\n    return z;\n}\n\ntemplate<class Real>\nReal cardinal_cubic_b_spline_imp<Real>::prime(Real x) const\n{\n    Real z = 0;\n    Real t = m_h_inv*(x - m_a) + 1;\n\n    using std::max;\n    using std::min;\n    using std::ceil;\n    using std::floor;\n\n    size_t k_min = (size_t) (max)(static_cast<long>(0), boost::math::ltrunc(ceil(t - 2)));\n    size_t k_max = (size_t) (min)(static_cast<long>(m_beta.size() - 1), boost::math::ltrunc(floor(t + 2)));\n\n    for (size_t k = k_min; k <= k_max; ++k)\n    {\n        z += m_beta[k]*b3_spline_prime(t - k);\n    }\n    return z*m_h_inv;\n}\n\ntemplate<class Real>\nReal cardinal_cubic_b_spline_imp<Real>::double_prime(Real x) const\n{\n    Real z = 0;\n    Real t = m_h_inv*(x - m_a) + 1;\n\n    using std::max;\n    using std::min;\n    using std::ceil;\n    using std::floor;\n\n    size_t k_min = (size_t) (max)(static_cast<long>(0), boost::math::ltrunc(ceil(t - 2)));\n    size_t k_max = (size_t) (min)(static_cast<long>(m_beta.size() - 1), boost::math::ltrunc(floor(t + 2)));\n\n    for (size_t k = k_min; k <= k_max; ++k)\n    {\n        z += m_beta[k]*b3_spline_double_prime(t - k);\n    }\n    return z*m_h_inv*m_h_inv;\n}\n\n}}}}\n#endif\n", "meta": {"hexsha": "4b543641a2dfe9323f31367086689427437f7d84", "size": 10377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/math/interpolators/detail/cardinal_cubic_b_spline_detail.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 31.3504531722, "max_line_length": 149, "alphanum_fraction": 0.5981497543, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5613717007652446}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@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_HISTOGRAM_MATCHING_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HISTOGRAM_MATCHING_HPP\n\n#include <boost/gil/algorithm.hpp>\n#include <boost/gil/histogram.hpp>\n#include <boost/gil/image.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <map>\n#include <vector>\n\nnamespace boost { namespace gil {\n\n/////////////////////////////////////////\n/// Histogram Matching(HM)\n/////////////////////////////////////////\n/// \\defgroup HM HM\n/// \\brief Contains implementation and description of the algorithm used to compute\n///        global histogram matching of input images.\n///\n///        Algorithm :-\n///        1. Calculate histogram A(pixel) of input image and G(pixel) of reference image.\n///        2. Compute the normalized cumulative(CDF) histograms of A and G.\n///        3. Match the histograms using transofrmation  => CDF(A(px)) = CDF(G(px'))\n///                                                      => px' = Inv-CDF (CDF(px))\n///\n\n/// \\fn histogram_matching\n/// \\ingroup HM\n/// \\tparam SrcKeyType Key Type of input histogram\n/// @param src_hist INPUT Input source histogram\n/// @param ref_hist INPUT Input reference histogram\n/// \\brief Overload for histogram matching algorithm, takes in a single source histogram &\n///        reference histogram and returns the color map used for histogram matching.\n///\ntemplate <typename SrcKeyType, typename RefKeyType>\nstd::map<SrcKeyType, SrcKeyType>\n    histogram_matching(histogram<SrcKeyType> const& src_hist, histogram<RefKeyType> const& ref_hist)\n{\n    histogram<SrcKeyType> dst_hist;\n    return histogram_matching(src_hist, ref_hist, dst_hist);\n}\n\n/// \\overload histogram_matching\n/// \\ingroup HM\n/// \\tparam SrcKeyType Key Type of input histogram\n/// \\tparam RefKeyType Key Type of reference histogram\n/// \\tparam DstKeyType Key Type of output histogram\n/// @param src_hist INPUT source histogram\n/// @param ref_hist INPUT reference histogram\n/// @param dst_hist OUTPUT Output histogram\n/// \\brief Overload for histogram matching algorithm, takes in source histogram, reference \n///        histogram & destination histogram and returns the color map used for histogram\n///        matching as well as transforming the destination histogram.\n///\ntemplate <typename SrcKeyType, typename RefKeyType, typename DstKeyType>\nstd::map<SrcKeyType, DstKeyType> histogram_matching(\n    histogram<SrcKeyType> const& src_hist,\n    histogram<RefKeyType> const& ref_hist,\n    histogram<DstKeyType>& dst_hist)\n{\n    static_assert(\n        std::is_integral<SrcKeyType>::value &&\n        std::is_integral<RefKeyType>::value &&\n        std::is_integral<DstKeyType>::value,\n        \"Source, Refernce or Destination histogram type is not appropriate.\");\n\n    using value_t = typename histogram<SrcKeyType>::value_type;\n    dst_hist.clear();\n    double src_sum      = src_hist.sum();\n    double ref_sum      = ref_hist.sum();\n    auto cumltv_srchist = cumulative_histogram(src_hist);\n    auto cumltv_refhist = cumulative_histogram(ref_hist);\n    std::map<SrcKeyType, RefKeyType> inverse_mapping;\n    \n    std::vector<typename histogram<RefKeyType>::key_type> src_keys, ref_keys;\n    src_keys             = src_hist.sorted_keys();\n    ref_keys             = ref_hist.sorted_keys();\n    std::ptrdiff_t start = ref_keys.size() - 1;\n    RefKeyType ref_max;\n    if (start >= 0)\n        ref_max = std::get<0>(ref_keys[start]);\n    \n    for (std::ptrdiff_t j = src_keys.size() - 1; j >= 0; --j)\n    {\n        double src_val = (cumltv_srchist[src_keys[j]] * ref_sum) / src_sum;\n        while (cumltv_refhist[ref_keys[start]] > src_val && start > 0)\n        {\n            start--;\n        }\n        if (std::abs(cumltv_refhist[ref_keys[start]] - src_val) >\n            std::abs(cumltv_refhist(std::min<RefKeyType>(ref_max, std::get<0>(ref_keys[start + 1]))) -\n                src_val))\n        {\n            inverse_mapping[std::get<0>(src_keys[j])] = \n                std::min<RefKeyType>(ref_max, std::get<0>(ref_keys[start + 1]));\n        }\n        else\n        {\n            inverse_mapping[std::get<0>(src_keys[j])] = std::get<0>(ref_keys[start]);\n        }\n        if (j == 0)\n            break;\n    }\n    std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {\n        dst_hist[inverse_mapping[std::get<0>(v.first)]] += v.second;\n    });\n    return inverse_mapping;\n}\n\n/// \\overload histogram_matching\n/// \\ingroup HM\n/// @param src_view  INPUT source image view\n/// @param ref_view  INPUT Reference image view\n/// @param dst_view  OUTPUT Output image view\n/// @param bin_width INPUT Histogram bin width\n/// @param mask      INPUT Specify is mask is to be used\n/// @param src_mask  INPUT Mask vector over input image\n/// @param ref_mask  INPUT Mask vector over reference image\n/// \\brief Overload for histogram matching algorithm, takes in both source, reference & \n///        destination image views and histogram matches the input image using the \n///        reference image.\n///\ntemplate <typename SrcView, typename ReferenceView, typename DstView>\nvoid histogram_matching(\n    SrcView const& src_view,\n    ReferenceView const& ref_view,\n    DstView const& dst_view,\n    std::size_t bin_width = 1,\n    bool mask = false,\n    std::vector<std::vector<bool>> src_mask = {},\n    std::vector<std::vector<bool>> ref_mask = {})\n{\n    gil_function_requires<ImageViewConcept<SrcView>>();\n    gil_function_requires<ImageViewConcept<ReferenceView>>();\n    gil_function_requires<MutableImageViewConcept<DstView>>();\n\n    static_assert(\n        color_spaces_are_compatible<\n            typename color_space_type<SrcView>::type,\n            typename color_space_type<ReferenceView>::type>::value,\n        \"Source and reference view must have same color space\");\n\n    static_assert(\n        color_spaces_are_compatible<\n            typename color_space_type<SrcView>::type,\n            typename color_space_type<DstView>::type>::value,\n        \"Source and destination view must have same color space\");\n    \n    // Defining channel type\n    using source_channel_t = typename channel_type<SrcView>::type;\n    using ref_channel_t    = typename channel_type<ReferenceView>::type;\n    using dst_channel_t    = typename channel_type<DstView>::type;\n    using coord_t          = typename SrcView::x_coord_t;\n\n    std::size_t const channels     = num_channels<SrcView>::value;\n    coord_t const width            = src_view.width();\n    coord_t const height           = src_view.height();\n    source_channel_t src_pixel_min = std::numeric_limits<source_channel_t>::min();\n    source_channel_t src_pixel_max = std::numeric_limits<source_channel_t>::max();\n    ref_channel_t ref_pixel_min    = std::numeric_limits<ref_channel_t>::min();\n    ref_channel_t ref_pixel_max    = std::numeric_limits<ref_channel_t>::max();\n    dst_channel_t dst_pixel_min    = std::numeric_limits<dst_channel_t>::min();\n    dst_channel_t dst_pixel_max    = std::numeric_limits<dst_channel_t>::max();\n\n    for (std::size_t i = 0; i < channels; i++)\n    {\n        histogram<source_channel_t> src_histogram;\n        histogram<ref_channel_t> ref_histogram;\n        fill_histogram(\n            nth_channel_view(src_view, i), src_histogram, bin_width, false, false, mask, src_mask,\n            std::tuple<source_channel_t>(src_pixel_min),\n            std::tuple<source_channel_t>(src_pixel_max), true);\n        fill_histogram(\n            nth_channel_view(ref_view, i), ref_histogram, bin_width, false, false, mask, ref_mask,\n            std::tuple<ref_channel_t>(ref_pixel_min), std::tuple<ref_channel_t>(ref_pixel_max),\n            true);\n        auto inverse_mapping = histogram_matching(src_histogram, ref_histogram);\n        for (std::ptrdiff_t src_y = 0; src_y < height; ++src_y)\n        {\n            auto src_it = nth_channel_view(src_view, i).row_begin(src_y);\n            auto dst_it = nth_channel_view(dst_view, i).row_begin(src_y);\n            for (std::ptrdiff_t src_x = 0; src_x < width; ++src_x)\n            {\n                if (mask && !src_mask[src_y][src_x])\n                    dst_it[src_x][0] = src_it[src_x][0];\n                else\n                    dst_it[src_x][0] =\n                        static_cast<dst_channel_t>(inverse_mapping[src_it[src_x][0]]);\n            }\n        }\n    }\n}\n\n}}  //namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "7019e278c60096f0c9157da12d40b9691c10c815", "size": 8535, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/histogram_matching.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/histogram_matching.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/histogram_matching.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 41.231884058, "max_line_length": 102, "alphanum_fraction": 0.6618629174, "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5611899613155926}}
{"text": "#pragma once\n#include \"base/assert.hpp\"\n\n#include \"std/algorithm.hpp\"\n#include \"std/cmath.hpp\"\n#include \"std/functional.hpp\"\n#include \"std/limits.hpp\"\n#include \"std/type_traits.hpp\"\n\n#include <boost/integer.hpp>\n\n\nnamespace my\n{\n\ntemplate <typename T> inline T Abs(T x)\n{\n  return (x < 0 ? -x : x);\n}\n\n// Compare floats or doubles for almost equality.\n// maxULPs - number of closest floating point values that are considered equal.\n// Infinity is treated as almost equal to the largest possible floating point values.\n// NaN produces undefined result.\n// See https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\n// for details.\ntemplate <typename TFloat>\nbool AlmostEqualULPs(TFloat x, TFloat y, unsigned int maxULPs = 256)\n{\n  static_assert(is_floating_point<TFloat>::value, \"\");\n  static_assert(numeric_limits<TFloat>::is_iec559, \"\");\n\n  // Make sure maxUlps is non-negative and small enough that the\n  // default NaN won't compare as equal to anything.\n  ASSERT_LESS(maxULPs, 4 * 1024 * 1024, ());\n\n  int const bits = CHAR_BIT * sizeof(TFloat);\n  typedef typename boost::int_t<bits>::exact IntType;\n  typedef typename boost::uint_t<bits>::exact UIntType;\n\n  IntType xInt = *reinterpret_cast<IntType const *>(&x);\n  IntType yInt = *reinterpret_cast<IntType const *>(&y);\n\n  // Make xInt and yInt lexicographically ordered as a twos-complement int\n  IntType const highestBit = IntType(1) << (bits - 1);\n  if (xInt < 0)\n    xInt = highestBit - xInt;\n  if (yInt < 0)\n    yInt = highestBit - yInt;\n\n  UIntType const diff = Abs(xInt - yInt);\n\n  return diff <= maxULPs;\n}\n\n// Returns true if x and y are equal up to the absolute difference eps.\n// Does not produce a sensible result if any of the arguments is NaN or infinity.\n// The default value for eps is deliberately not provided: the intended usage\n// is for the client to choose the precision according to the problem domain,\n// explicitly define the precision constant and call this function.\ntemplate <typename TFloat>\ninline bool AlmostEqualAbs(TFloat x, TFloat y, TFloat eps)\n{\n  return fabs(x - y) < eps;\n}\n\n// Returns true if x and y are equal up to the relative difference eps.\n// Does not produce a sensible result if any of the arguments is NaN, infinity or zero.\n// The same considerations as in AlmostEqualAbs apply.\ntemplate <typename TFloat>\ninline bool AlmostEqualRel(TFloat x, TFloat y, TFloat eps)\n{\n  return fabs(x - y) < eps * max(fabs(x), fabs(y));\n}\n\ntemplate <typename TFloat> inline TFloat DegToRad(TFloat deg)\n{\n  return deg * TFloat(math::pi) / TFloat(180);\n}\n\ntemplate <typename TFloat> inline TFloat RadToDeg(TFloat rad)\n{\n  return rad * TFloat(180) / TFloat(math::pi);\n}\n\ntemplate <typename T> inline T id(T const & x)\n{\n  return x;\n}\n\ntemplate <typename T> inline T sq(T const & x)\n{\n  return x * x;\n}\n\ntemplate <typename T, typename TMin, typename TMax>\ninline T clamp(T x, TMin xmin, TMax xmax)\n{\n  if (x > xmax)\n    return xmax;\n  if (x < xmin)\n    return xmin;\n  return x;\n}\n\ntemplate <typename T> inline bool between_s(T a, T b, T x)\n{\n  return (a <= x && x <= b);\n}\ntemplate <typename T> inline bool between_i(T a, T b, T x)\n{\n  return (a < x && x < b);\n}\n\ninline int rounds(double x)\n{\n  return (x > 0.0 ? int(x + 0.5) : int(x - 0.5));\n}\n\ninline size_t SizeAligned(size_t size, size_t align)\n{\n  // static_cast    .\n  return size + (static_cast<size_t>(-static_cast<ptrdiff_t>(size)) & (align - 1));\n}\n\ntemplate <typename T>\nbool IsIntersect(T const & x0, T const & x1, T const & x2, T const & x3)\n{\n  return !((x1 < x2) || (x3 < x0));\n}\n\n// Computes x^n.\ntemplate <typename T> inline T PowUint(T x, uint64_t n)\n{\n  T res = 1;\n  for (T t = x; n > 0; n >>= 1, t *= t)\n    if (n & 1)\n      res *= t;\n  return res;\n}\n\ntemplate <typename T> inline T NextModN(T x, T n)\n{\n  return x + 1 == n ? 0 : x + 1;\n}\n\ntemplate <typename T> inline T PrevModN(T x, T n)\n{\n  return x == 0 ? n - 1 : x - 1;\n}\n\ninline uint32_t NextPowOf2(uint32_t v)\n{\n  v = v - 1;\n  v |= (v >> 1);\n  v |= (v >> 2);\n  v |= (v >> 4);\n  v |= (v >> 8);\n  v |= (v >> 16);\n\n  return v + 1;\n}\n\n// Greatest Common Divisor\ntemplate <typename T> T GCD(T a, T b)\n{\n  T multiplier = 1;\n  T gcd = 1;\n  while (true)\n  {\n    if (a == 0 || b == 0)\n    {\n      gcd = max(a, b);\n      break;\n    }\n\n    if (a == 1 || b == 1)\n    {\n      gcd = 1;\n      break;\n    }\n\n    if ((a & 0x1) == 0 && (b & 0x1) == 0)\n    {\n      multiplier <<= 1;\n      a >>= 1;\n      b >>= 1;\n      continue;\n    }\n\n    if ((a & 0x1) != 0 && (b & 0x1) != 0)\n    {\n      T const minV = min(a, b);\n      T const maxV = max(a, b);\n      a = (maxV - minV) >> 1;\n      b = minV;\n      continue;\n    }\n\n    if ((a & 0x1) != 0)\n      swap(a, b);\n\n    a >>= 1;\n  }\n\n  return multiplier * gcd;\n}\n\n/// Calculate hash for the pair of values.\ntemplate <typename T1, typename T2>\nsize_t Hash(T1 const & t1, T2 const & t2)\n{\n  /// @todo Probably, we need better hash for 2 integral types.\n  return (hash<T1>()(t1) ^ (hash<T2>()(t2) << 1));\n}\n\n}\n", "meta": {"hexsha": "78b59dd3350c3eeec44065dad68f229ec8688370", "size": 4979, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/math.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": "base/math.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": "base/math.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": 22.8394495413, "max_line_length": 98, "alphanum_fraction": 0.6270335409, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.5611899516898949}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2012-2015 Barend Gehrels, Amsterdam, the Netherlands.\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// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_POINT_CIRCLE_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_POINT_CIRCLE_HPP\n\n#include <cstddef>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/strategies/buffer.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace buffer\n{\n\n/*!\n\\brief Create a circular buffer around a point\n\\ingroup strategies\n\\details This strategy can be used as PointStrategy for the buffer algorithm.\n    It creates a circular buffer around a point. It can be applied\n    for points and multi_points, but also for a linestring (if it is degenerate,\n    so consisting of only one point) and for polygons (if it is degenerate).\n    This strategy is only applicable for Cartesian coordinate systems.\n\n\\qbk{\n[heading Example]\n[buffer_point_circle]\n[heading Output]\n[$img/strategies/buffer_point_circle.png]\n[heading See also]\n\\* [link geometry.reference.algorithms.buffer.buffer_7_with_strategies buffer (with strategies)]\n\\* [link geometry.reference.strategies.strategy_buffer_point_square point_square]\n}\n */\nclass point_circle\n{\npublic :\n    //! \\brief Constructs the strategy\n    //! \\param count number of points for the created circle (if count\n    //! is smaller than 3, count is internally set to 3)\n    explicit point_circle(std::size_t count = 90)\n        : m_count((count < 3u) ? 3u : count)\n    {}\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    //! Fills output_range with a circle around point using distance_strategy\n    template\n    <\n        typename Point,\n        typename OutputRange,\n        typename DistanceStrategy\n    >\n    inline void apply(Point const& point,\n                DistanceStrategy const& distance_strategy,\n                OutputRange& output_range) const\n    {\n        typedef typename boost::range_value<OutputRange>::type output_point_type;\n\n        typedef typename geometry::select_most_precise\n            <\n                typename geometry::select_most_precise\n                    <\n                        typename geometry::coordinate_type<Point>::type,\n                        typename geometry::coordinate_type<output_point_type>::type\n                    >::type,\n                double\n            >::type promoted_type;\n\n        promoted_type const buffer_distance = distance_strategy.apply(point, point,\n                        strategy::buffer::buffer_side_left);\n\n        promoted_type const two = 2.0;\n        promoted_type const two_pi = two * geometry::math::pi<promoted_type>();\n\n        promoted_type const diff = two_pi / promoted_type(m_count);\n        promoted_type a = 0;\n\n        for (std::size_t i = 0; i < m_count; i++, a -= diff)\n        {\n            output_point_type p;\n            set<0>(p, get<0>(point) + buffer_distance * cos(a));\n            set<1>(p, get<1>(point) + buffer_distance * sin(a));\n            output_range.push_back(p);\n        }\n\n        // Close it:\n        output_range.push_back(output_range.front());\n    }\n#endif // DOXYGEN_SHOULD_SKIP_THIS\n\nprivate :\n    std::size_t m_count;\n};\n\n\n}} // namespace strategy::buffer\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_BUFFER_POINT_CIRCLE_HPP\n", "meta": {"hexsha": "86ebc43c9cb187b3dc215d4a7b5ad755c0475f73", "size": 3711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/cartesian/buffer_point_circle.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": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T19:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T19:18:58.000Z", "max_issues_repo_path": "deps/cinder/include/boost/geometry/strategies/cartesian/buffer_point_circle.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": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T07:38:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T04:22:10.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/strategies/cartesian/buffer_point_circle.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": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T22:36:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T12:00:36.000Z", "avg_line_length": 31.7179487179, "max_line_length": 96, "alphanum_fraction": 0.6868768526, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5611671038085869}}
{"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#include <NTL/ZZ.h>\n#include <algorithm>\n#include <complex>\n\n#include \"norms.h\"\n#include \"EncryptedArray.h\"\n#include \"FHE.h\"\n#include \"debugging.h\"\n\nNTL_CLIENT\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\ninline bool cx_equals(const vector<cx_double>& v1, \n                      const vector<cx_double>& v2, \n                      double epsilon)\n{\n  return (calcMaxDiff(v1,v2) < epsilon);\n}\n\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\n\nint main(int argc, char *argv[]) \n{\n\n  // Commandline setup\n\n  ArgMapping amap;\n\n  long m=16;\n  long r=8;\n  long L=150;\n  double epsilon=0.01; // Accepted accuracy\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(\"L\", L, \"Number of levels\");\n  amap.arg(\"ep\", epsilon, \"Accepted accuracy\");\n  amap.arg(\"verbose\", verbose, \"more printouts\");\n\n  amap.parse(argc, argv);\n\n  try{\n\n    // FHE setup keys, context, SKMs, etc\n\n    FHEcontext context(m, /*p=*/-1, r);\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\n    // Run the tests.\n    testBasicArith(publicKey, secretKey, ea, epsilon);\n    testComplexArith(publicKey, secretKey, ea, epsilon);\n    testRotsNShifts(publicKey, secretKey, ea, epsilon);\n\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);\n  vd1.resize(vd1.size()+2, 0.0);\n\n  ea.encrypt(c2, publicKey, vd2);\n\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);\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);\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);\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  cx_equals(vd, vd1, epsilon)?\n    cout << \"GOOD\\n\":\n    cout << \"BAD\\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);\n  ea.encrypt(c2, publicKey, vd2);\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  cx_equals(vd, vd1, epsilon)?\n    cout << \"GOOD\\n\":\n    cout << \"BAD\\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  cx_equals(realParts,real_dec,epsilon) && cx_equals(imParts,im_dec,epsilon)?\n    cout << \"GOOD\\n\":\n    cout << \"BAD\\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);\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  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  cx_equals(vd1, vd_dec, epsilon)?\n    cout << \"GOOD\\n\":\n    cout << \"BAD\\n\";\n}\n", "meta": {"hexsha": "3435336c6fcf7732ddaceaa1e549484d7f033780", "size": 7765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_approxNums.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/Test_approxNums.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/Test_approxNums.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": 27.5354609929, "max_line_length": 82, "alphanum_fraction": 0.6274307791, "num_tokens": 2396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597971, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.561105908776728}}
{"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/planar_canonical_ordering.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing namespace boost;\n\nint main(int argc, char** argv)\n{\n\n    typedef adjacency_list< vecS, vecS, undirectedS,\n        property< vertex_index_t, int >, property< edge_index_t, int > >\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 (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n        put(e_index, *ei, edge_count++);\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 = make_iterator_property_map(\n                embedding.begin(), get(vertex_index, g))))\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,\n        make_iterator_property_map(embedding.begin(), get(vertex_index, g)),\n        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": "7695f8d2476ecda06962d2502f2d906f238d3dd2", "size": 2680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/canonical_ordering.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/canonical_ordering.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/canonical_ordering.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": 33.0864197531, "max_line_length": 76, "alphanum_fraction": 0.623880597, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.5611058877475193}}
{"text": "#include <Eigen/Core>\n#include <trajopt_sco/expr_ops.hpp>\n#include <trajopt_sco/modeling_utils.hpp>\n#include <trajopt/trajectory_costs.hpp>\n\n\nusing namespace std;\nusing namespace sco;\nusing namespace Eigen;\n\nnamespace {\n\n\nstatic MatrixXd diffAxis0(const MatrixXd& in) {\n  return in.middleRows(1, in.rows()-1) - in.middleRows(0, in.rows()-1);\n}\n\n\n}\n\nnamespace trajopt {\n\n\n\n//////////// Quadratic cost functions /////////////////\n\nJointPosCost::JointPosCost(const VarVector& vars, const VectorXd& vals, const VectorXd& coeffs) :\n    Cost(\"JointPos\"), vars_(vars), vals_(vals), coeffs_(coeffs) {\n    for (int i=0; i < vars.size(); ++i) {\n      if (coeffs[i] > 0) {\n        AffExpr diff = exprSub(AffExpr(vars[i]), AffExpr(vals[i]));\n        exprInc(expr_, exprMult(exprSquare(diff), coeffs[i]));\n      }\n    }\n}\ndouble JointPosCost::value(const vector<double>& xvec) {\n  VectorXd dofs = getVec(xvec, vars_);\n  return ((dofs - vals_).array().square() * coeffs_.array()).sum();\n}\nConvexObjectivePtr JointPosCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n\nJointVelCost::JointVelCost(const VarArray& vars, const VectorXd& coeffs) :\n    Cost(\"JointVel\"), vars_(vars), coeffs_(coeffs) {\n  for (int i=0; i < vars.rows()-1; ++i) {\n    for (int j=0; j < vars.cols(); ++j) {\n      AffExpr vel;\n      exprInc(vel, exprMult(vars(i,j), -1));\n      exprInc(vel, exprMult(vars(i+1,j), 1));\n      exprInc(expr_, exprMult(exprSquare(vel),coeffs_[j]));\n    }\n  }\n}\ndouble JointVelCost::value(const vector<double>& xvec) {\n  MatrixXd traj = getTraj(xvec, vars_);\n  return (diffAxis0(traj).array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nConvexObjectivePtr JointVelCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n\n\nJointAccCost::JointAccCost(const VarArray& vars, const VectorXd& coeffs) :\n    Cost(\"JointAcc\"), vars_(vars), coeffs_(coeffs) {\n  for (int i=0; i < vars.rows()-2; ++i) {\n    for (int j=0; j < vars.cols(); ++j) {\n      AffExpr acc;\n      exprInc(acc, exprMult(vars(i,j), -1));\n      exprInc(acc, exprMult(vars(i+1,j), 2));\n      exprInc(acc, exprMult(vars(i+2,j), -1));\n      exprInc(expr_, exprMult(exprSquare(acc), coeffs_[j]));\n    }\n  }\n}\ndouble JointAccCost::value(const vector<double>& xvec) {\n  MatrixXd traj = getTraj(xvec, vars_);\n  return (diffAxis0(diffAxis0(traj)).array().square().matrix() * coeffs_.asDiagonal()).sum();\n}\nConvexObjectivePtr JointAccCost::convex(const vector<double>& x, Model* model) {\n  ConvexObjectivePtr out(new ConvexObjective(model));\n  out->addQuadExpr(expr_);\n  return out;\n}\n\n}\n", "meta": {"hexsha": "d95002290ad1f56c57e8bd72174e754449e2a4ff", "size": 2728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trajopt/src/trajectory_costs.cpp", "max_stars_repo_name": "Levi-Armstrong/trajopt_ros", "max_stars_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T14:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-09T16:41:36.000Z", "max_issues_repo_path": "trajopt/src/trajectory_costs.cpp", "max_issues_repo_name": "Levi-Armstrong/trajopt_ros", "max_issues_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T04:57:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-07T21:46:45.000Z", "max_forks_repo_path": "trajopt/src/trajectory_costs.cpp", "max_forks_repo_name": "Levi-Armstrong/trajopt_ros", "max_forks_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3333333333, "max_line_length": 97, "alphanum_fraction": 0.6620234604, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.5610605443420721}}
{"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 norms.cpp - computing various norms of ring elements\n **/\n#include <numeric>\n#include <NTL/BasicThreadPool.h>\n#include \"NumbTh.h\"\n#include \"DoubleCRT.h\"\n#include \"norms.h\"\nNTL_CLIENT\n\nlong sumOfCoeffs(const zzX& f) // = f(1)\n{\n  long sum = 0;\n  for (long i=0; i<lsize(f); i++) sum += f[i];\n  return sum;\n}\nZZ sumOfCoeffs(const ZZX& f) // = f(1)\n{\n  ZZ sum = ZZ::zero();\n  for (long i=0; i<=deg(f); i++) sum += coeff(f,i);\n  return sum;\n}\nNTL::ZZ sumOfCoeffs(const DoubleCRT& f)\n{\n  ZZX poly;\n  f.toPoly(poly);\n  return sumOfCoeffs(poly);\n}\n\n\nlong largestCoeff(const zzX& f) // l_infty norm\n{\n  long mx = 0;\n  for (long i=0; i<lsize(f); i++) {\n    if (mx < abs(f[i]))\n      mx = abs(f[i]);\n  }\n  return mx;\n}\nZZ largestCoeff(const ZZX& f)\n{\n  ZZ mx = ZZ::zero();\n  for (long i=0; i<=deg(f); i++) {\n    if (mx < abs(coeff(f,i)))\n      mx = abs(coeff(f,i));\n  }\n  return mx;\n}\nZZ largestCoeff(const Vec<ZZ>& f)\n{\n  ZZ mx = ZZ::zero();\n  for (auto& x : f) {\n    if (mx < abs(x))\n      mx = abs(x);\n  }\n  return mx;\n}\nNTL::ZZ largestCoeff(const DoubleCRT& f)\n{\n  ZZX poly;\n  f.toPoly(poly);\n  return largestCoeff(poly);\n}\n\n\ndouble coeffsL2NormSquared(const zzX& f) // l_2 norm square\n{\n  double s = 0.0;\n  for (long i=0; i<lsize(f); i++) {\n    double coef = f[i];\n    s += coef * coef;\n  }\n  return s;\n}\nxdouble coeffsL2NormSquared(const ZZX& f) // l_2 norm square\n{\n  xdouble s(0.0);\n  for (long i=0; i<=deg(f); i++) {\n    xdouble coef(conv<xdouble>(coeff(f,i)));\n    s += coef * coef;\n  }\n  return s;\n}\nxdouble coeffsL2NormSquared(const DoubleCRT& f) // l2 norm^2\n{\n  ZZX poly;\n  f.toPoly(poly);\n  return coeffsL2NormSquared(poly);\n}\n\n#if FFT_IMPL\n// l_2 norm square of canonical embedding\ndouble embeddingL2NormSquared(const zzX& f, const PAlgebra& palg)\n{\n  std::vector<cx_double> emb;\n  canonicalEmbedding(emb, f, palg);\n  double acc = 0.0;\n  for (auto& x : emb)\n    acc += std::norm(x);\n  return 2*acc; // emb just has phi(m)/2 values (paired with complex conjugates)\n}\n\n//! Computing the L-infinity norm of the canonical embedding\ndouble embeddingLargestCoeff(const zzX& f, const PAlgebra& palg)\n{\n  std::vector<cx_double> emb;\n  canonicalEmbedding(emb, f, palg);\n  double mx = 0.0;\n  for (auto& x : emb) {\n    double n = std::norm(x);\n    if (mx < n) mx = n;\n  }\n  return sqrt(mx);\n}\n\n\nstatic xdouble convertAndScale(zzX& ff, const NTL::ZZX& f)\n{\n  const long MAX_BITS = NTL_SP_BOUND-15; // max allowed bits to avoid double overflow \n                                         // in computations\n  xdouble factor(1.0);\n  long size = NTL::MaxBits(f);\n  if (size > MAX_BITS) {\n    ZZ zzFactor = ZZ(1) << (size-MAX_BITS); // divide f by this factor\n\n    ZZX scaled = f;\n    for (long i: range(f.rep.length())) RightShift(scaled.rep[i], scaled.rep[i], size-MAX_BITS); \n    scaled.normalize();\n\n    convert(factor, zzFactor);      // remember the factor\n    convert(ff, scaled);            // convert to zzX\n  }\n  else\n    convert(ff, f);                 // convert to zzX\n  return factor;\n}\n\n\nstatic xdouble convertAndScale(ZZX& ff, const NTL::ZZX& f)\n{\n  const long MAX_BITS = 250; // max allowed bits to avoid double overflow \n                             // in computations\n\n  xdouble factor(1.0);\n  long size = NTL::MaxBits(f);\n  if (size > MAX_BITS) {\n    ZZ zzFactor = ZZ(1) << (size-MAX_BITS); // divide f by this factor\n\n    ZZX scaled = f;\n    for (long i: range(f.rep.length())) RightShift(scaled.rep[i], scaled.rep[i], size-MAX_BITS); \n    scaled.normalize();\n\n    convert(factor, zzFactor);      // remember the factor\n    ff = scaled;\n  }\n  else\n    convert(ff, f);                 // convert to zzX\n  return factor;\n}\n\nxdouble embeddingL2NormSquared(const NTL::ZZX& f, const PAlgebra& palg)\n{\n  zzX ff; // to hold a scaled-down version of ff;\n  xdouble factor = convertAndScale(ff, f);\n  return embeddingL2NormSquared(ff, palg)*factor*factor;\n}\n\nxdouble embeddingLargestCoeff(const NTL::ZZX& f, const PAlgebra& palg)\n{\n#if 1\n  ZZX ff; // to hold a scaled-down version of ff;\n  xdouble factor = convertAndScale(ff, f);\n#else\n  const ZZX& ff = f;\n  xdouble factor { 1.0 };\n#endif\n  std::vector<cx_double> emb;\n  canonicalEmbedding(emb, ff, palg);\n  xdouble mx {0.0};\n  for (auto& x : emb) {\n    double re = std::real(x);\n    double im = std::imag(x);\n    xdouble n = xdouble(re)*xdouble(re) + xdouble(im)*xdouble(im);\n    if (mx < n) mx = n;\n  }\n  return sqrt(mx)*factor;\n}\n#endif\n", "meta": {"hexsha": "b03d28e19ade9ed37bec7ab728f925907a56e38a", "size": 5038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/norms.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/norms.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/norms.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": 25.19, "max_line_length": 97, "alphanum_fraction": 0.6304088924, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5610109061580312}}
{"text": "/**\n * \\file ToneStackFilter.cpp\n */\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include \"ToneStackFilter.h\"\n#include \"IIRFilter.h\"\n\nnamespace ATK\n{\n  template<typename DataType>\n  ToneStackCoefficients<DataType>::ToneStackCoefficients(int nb_channels)\n  :TypedBaseFilter<DataType>(nb_channels, nb_channels), R1(0), R2(0), R3(0), R4(0), C1(0), C2(0), C3(0), low(.5), middle(.5), high(.5)\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\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    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 * 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(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 ToneStackCoefficients<DataType_>::set_low(DataType_ 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  DataType_ ToneStackCoefficients<DataType_>::get_low() const\n  {\n    return low;\n  }\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_middle(DataType_ 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  DataType_ ToneStackCoefficients<DataType_>::get_middle() const\n  {\n    return middle;\n  }\n\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_high(DataType_ 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  DataType_ 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<DataType>(250e3), static_cast<DataType>(1e6), static_cast<DataType>(25e3), static_cast<DataType>(45e3),\n      static_cast<DataType>(250e-12), static_cast<DataType>(20e-9), static_cast<DataType>(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<DataType>(220e3), static_cast<DataType>(1e6), static_cast<DataType>(22e3), static_cast<DataType>(33e3),\n      static_cast<DataType>(470e-12), static_cast<DataType>(22e-9), static_cast<DataType>(22e-9));\n    return std::move(filter);\n  }\n\n  template<typename DataType_>\n  void ToneStackCoefficients<DataType_>::set_coefficients( DataType R1, DataType R2, DataType R3, DataType R4, DataType C1, DataType C2, DataType 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  template class ToneStackCoefficients<float>;\n  template class ToneStackCoefficients<double>;\n  \n  template class IIRFilter<ToneStackCoefficients<float> >;\n  template class IIRFilter<ToneStackCoefficients<double> >;\n}\n", "meta": {"hexsha": "cd90a414c0b5575524d062df60ceb8ba34104dff", "size": 5611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ToneStackFilter.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/ToneStackFilter.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/ToneStackFilter.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": 35.06875, "max_line_length": 181, "alphanum_fraction": 0.6530030298, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809304, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5609680492711064}}
{"text": "/**\n * @file asymptotic.cc\n * @brief Creates convergence plots for experiment 3.2.3.12\n * @author Tobias Rohner\n * @date April 2020\n * @copyright MIT License\n */\n\n#define _USE_MATH_DEFINES\n\n#include <lf/quad/gauss_quadrature.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nnamespace po = boost::program_options;\n\n// Code for empiric exploration of asymptotic convergence of norms of the\n// discretization error for 1D finite element discretization of a 2-point BVP.\n// Special example with a highly oscillatory solution\nint main(int argc, char *argv[]) {\n  po::options_description desc(\"Allowed options\");\n  // clang-format off\n  desc.add_options()\n  (\"output,o\", po::value<std::string>(), \"Name of the output file\")\n  (\"M_max,M\", po::value<int>()->default_value(500), \"Maximum number of cells\")\n  (\"dM,m\", po::value<int>()->default_value(5), \"Increment in M\")\n  (\"num_quad_points,n\", po::value<int>()->default_value(2), \"Number of points for numerical quadrature\");\n  // clang-format on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  if (vm.count(\"output\") == 0) {\n    std::cout << desc << std::endl;\n    exit(1);\n  }\n  const int M_max = vm[\"M_max\"].as<int>();\n  const int dM = vm[\"dM\"].as<int>();\n  const int num_quad_points = vm[\"num_quad_points\"].as<int>();\n  const std::string output_file = vm[\"output\"].as<std::string>();\n  const auto [quad_points, quad_weights] = lf::quad::GaussLegendre(2);\n\n  // Load function\n  const auto f = [](double x) {\n    return 10000 * M_PI * M_PI * x * x * std::sin(50 * M_PI * x * x) -\n           100 * M_PI * std::cos(50 * M_PI * x * x);\n  };\n  // Analytic solution (highly oscillatory)\n  const auto u = [](double x) { return std::sin(50 * M_PI * x * x); };\n  // Gradient of analytic solution\n  const auto u_grad = [](double x) {\n    return 100 * M_PI * x * std::cos(50 * M_PI * x * x);\n  };\n\n  Eigen::MatrixXd results(M_max / dM, 4);\n  // Loop over meshes with increasing numbers of cells\n  for (int M = dM; M <= M_max; M += dM) {\n    // The mesh width\n    const double h = 1. / M;\n\n    // Generate the tri-diagonal stiffness matrix for an equidistant\n    // mesh on [0, 1] with M cells and p.w. linear Lagrangian finite elements\n    // Formulas are explained in Section 2.3 of the lecture document\n    Eigen::SparseMatrix<double> A(M + 1, M + 1);\n    A.reserve(3 * (M + 1));\n    // Fill the diagonal\n    for (int i = 0; i < M + 1; ++i) {\n      A.coeffRef(i, i) += 2. / h;\n    }\n    // Fill the off-diagonals\n    for (int i = 0; i < M; ++i) {\n      A.coeffRef(i, i + 1) += -1. / h;\n      A.coeffRef(i + 1, i) += -1. / h;\n    }\n\n    // Generate the load vector\n    Eigen::VectorXd rhs = Eigen::VectorXd::Zero(M + 1);\n    for (int i = 0; i < M; ++i) {\n      const double a = static_cast<double>(i) / M;\n      const Eigen::VectorXd loc_quad_points =\n          Eigen::VectorXd::Constant(num_quad_points, a) + h * quad_points;\n      const Eigen::VectorXd loc_quad_weights = h * quad_weights;\n      // Perform the integration over the cell for both basis functions\n      const auto b1 = [&](double x) { return (x - a) / h; };\n      const auto b2 = [&](double x) { return 1. - b1(x); };\n      for (int k = 0; k < num_quad_points; ++k) {\n        rhs[i] += loc_quad_weights[k] * b2(loc_quad_points[k]) *\n                  f(loc_quad_points[k]);\n        rhs[i + 1] += loc_quad_weights[k] * b1(loc_quad_points[k]) *\n                      f(loc_quad_points[k]);\n      }\n    }\n\n    // Enforce zero dirichlet boundary conditions\n    for (long k = 0; k < A.outerSize(); ++k) {\n      for (Eigen::SparseMatrix<double>::InnerIterator it(A, k); it; ++it) {\n        const int row = it.row();\n        const int col = it.col();\n        if ((row == 0 && col == 0) || (row == M && col == M)) {\n          it.valueRef() = 1;\n        } else if (row == 0 || row == M || col == 0 || col == M) {\n          it.valueRef() = 0;\n        }\n      }\n    }\n    // Set the boundary values to zero\n    rhs[0] = 0;\n    rhs[M] = 0;\n\n    // Solve the resulting linear system\n    Eigen::SparseLU<Eigen::SparseMatrix<double>> solver(A);\n    const Eigen::VectorXd sol = solver.solve(rhs);\n\n    // Compute the norms and store them in the results matrix\n    double norm_max = 0;\n    double norm_H1_squared = 0;\n    double norm_L2_squared = 0;\n    for (int i = 0; i < M; ++i) {\n      const double a = static_cast<double>(i) / M;\n      const double b = static_cast<double>(i + 1) / M;\n      const Eigen::VectorXd loc_quad_points =\n          Eigen::VectorXd::Constant(num_quad_points, a) + h * quad_points;\n      const Eigen::VectorXd loc_quad_weights = h * quad_weights;\n\n      // The approximate solution on the current cell\n      const auto u_h = [&](double x) {\n        return sol[i + 1] * (x - a) / h + sol[i] * (1. - (x - a) / h);\n      };\n      // The gradient of the approximate solution on the current cell\n      const auto u_h_grad = [&](double /*x*/) {\n        return (sol[i + 1] - sol[i]) / h;\n      };\n      // The difference of the approximate and the exact solution\n      const auto diff = [&](double x) { return u_h(x) - u(x); };\n      // The difference in the gradient of the approximate and the exact\n      // solution\n      const auto diff_grad = [&](double x) { return u_h_grad(x) - u_grad(x); };\n\n      // Compute the max norm by evaluating the functions on a fine grid\n      norm_max =\n          std::max(norm_max, Eigen::ArrayXd::LinSpaced(10 * M_max / M, a, b)\n                                 .unaryExpr(diff)\n                                 .abs()\n                                 .maxCoeff());\n      // Compute the H1 and L2 norms by integrating using a numerical quadrature\n      for (int k = 0; k < num_quad_points; ++k) {\n        norm_H1_squared += loc_quad_weights[k] * diff_grad(loc_quad_points[k]) *\n                           diff_grad(loc_quad_points[k]);\n        norm_L2_squared += loc_quad_weights[k] * diff(loc_quad_points[k]) *\n                           diff(loc_quad_points[k]);\n      }\n    }\n    results((M / dM) - 1, 0) = M;\n    results((M / dM) - 1, 1) = norm_max;\n    results((M / dM) - 1, 2) = std::sqrt(norm_H1_squared);\n    results((M / dM) - 1, 3) = std::sqrt(norm_L2_squared);\n  }\n\n  // Output the resulting errors to a file\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::ofstream file;\n  file.open(output_file);\n  file << results.format(CSVFormat);\n  file.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "cd1854d25cc202e2594728c0e48125a4158e0d25", "size": 6573, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/convergencestudies/asymptotic.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "lecturecodes/convergencestudies/asymptotic.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "lecturecodes/convergencestudies/asymptotic.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 37.9942196532, "max_line_length": 105, "alphanum_fraction": 0.5848166743, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5609406279977087}}
{"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#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.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 <cmath>\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\n\n\nstd::tuple<int, int, int>\ngrid_parameters(const Triangulation<2> &tria)\n{\n  return std::make_tuple(tria.n_levels(),\n                         tria.n_cells(),\n                         tria.n_active_cells());\n}\n\n\nvoid\nfirst_grid()\n{\n  Triangulation<2> triangulation;\n\n  GridGenerator::hyper_cube(triangulation);\n  std::cout << \"Number of original vertices:\" << triangulation.n_vertices()\n            << std::endl;\n\n  triangulation.refine_global(4);\n\n  std::cout << \"Number of original vertices after 4 refinements:\"\n            << triangulation.n_vertices() << std::endl;\n\n  {\n    std::ofstream out(\"grid-1.svg\");\n    GridOut       grid_out;\n    grid_out.write_svg(triangulation, out);\n    std::cout << \"Grid written to grid-1.svg\" << std::endl;\n  }\n\n  {\n    std::ofstream out(\"grid-1.vtk\");\n    GridOut       grid_out;\n    grid_out.write_vtk(triangulation, out);\n    std::cout << \"Grid written to grid-1.vtk\" << std::endl;\n  }\n  auto params = grid_parameters(triangulation);\n  std::cout << std::get<0>(params) << \" \" << std::get<1>(params) << \"  \"\n            << std::get<2>(params) << std::endl;\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_all_manifolds();\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      std::ofstream out(\"grid-2-\" + std::to_string(step) + \".vtk\");\n      GridOut       grid_out;\n      grid_out.write_vtk(triangulation, out);\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    std::ofstream out(\"grid-2.svg\");\n    GridOut       grid_out;\n    grid_out.write_svg(triangulation, out);\n    std::cout << \"Grid written to grid-2.svg\" << std::endl;\n  }\n  auto params = grid_parameters(triangulation);\n  std::cout << std::get<0>(params) << \" \" << std::get<1>(params) << \"  \"\n            << std::get<2>(params) << std::endl;\n}\n\nvoid\nthird_grid()\n{\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_L(triangulation);\n  std::cout << \"Number of original vertices:\" << triangulation.n_vertices()\n            << std::endl;\n\n  triangulation.refine_global(1);\n\n  std::cout << \"Number of original vertices after 1 refinement:\"\n            << triangulation.n_vertices() << std::endl;\n\n\n  {\n    std::ofstream out(\"grid-3.vtk\");\n    GridOut       grid_out;\n    grid_out.write_vtk(triangulation, out);\n    std::cout << \"Grid written to grid-3.vtk\" << std::endl;\n  }\n\n  const Point<2> corner(0, 0);\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      std::ofstream out(\"grid-3-\" + std::to_string(step) + \".vtk\");\n      GridOut       grid_out;\n      grid_out.write_vtk(triangulation, out);\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                corner.distance(cell->vertex(v));\n\n              if (std::fabs(distance_from_center) <= 1. / 3.)\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n  auto params = grid_parameters(triangulation);\n  std::cout << std::get<0>(params) << \" \" << std::get<1>(params) << \"  \"\n            << std::get<2>(params) << std::endl;\n}\n\n\nvoid\ncircle_grid()\n{\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_ball<2>(triangulation);\n  // triangulation.set_all_manifold_ids(0);\n  triangulation.set_manifold(0, SphericalManifold<2>());\n  const Point<2> mesh_center;\n  for (const auto &cell : triangulation.active_cell_iterators())\n    if (mesh_center.distance(cell->center()) > cell->diameter() / 10)\n      cell->set_all_manifold_ids(0);\n  triangulation.refine_global(2);\n  std::ofstream out(\"circle.vtk\");\n  GridOut       grid_out;\n  grid_out.write_vtk(triangulation, out);\n}\n\n\nvoid\ntorus_grid()\n{\n  Triangulation<2, 3> triangulation;\n  GridGenerator::torus<2, 3>(triangulation, 4, 1);\n  triangulation.refine_global(2);\n  std::ofstream out(\"torus.vtk\");\n  GridOut       grid_out;\n  grid_out.write_vtk(triangulation, out);\n}\n\nint\nmain()\n{\n  first_grid();\n  second_grid();\n  third_grid();\n  circle_grid();\n  torus_grid();\n}\n", "meta": {"hexsha": "b1b58981fd83111ebdddf3ae3ee6f9bc3c57a8eb", "size": 5785, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.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-1.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-1.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": 27.0327102804, "max_line_length": 75, "alphanum_fraction": 0.6005185825, "num_tokens": 1495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5608999734124419}}
{"text": "/*\n * Copyright (c) 2013-2016 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef STROBOMAP_HPP\n#define STROBOMAP_HPP\n\n#include <stdexcept>\n#include <kv/ode-nv.hpp>\n#include <kv/ode-autodif-nv.hpp>\n#include <kv/ode-maffine.hpp>\n#ifdef USE_MAFFINE2\n#include <kv/ode-maffine2.hpp>\n#endif\n#include <kv/ode-param.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\n// Generate function object of strobomap\n// using function object of r.h.s of differential equation.\n// Generated function object can receive\n//   vector<T>,\n//   vector< autodif<T> >,\n//   vector< interval<T> >,\n//   vector< affine<T> >,\n//   vector< autodif< interval<T> > >\n// as argument. In each case,\n//   odelong_nv in ode-nv.hpp,\n//   odelong_nv in ode-autodif-nv.hpp,\n//   odelong_maffine in ode-maffine.hpp (interval version)\n//   odelong_maffine in ode-maffine.hpp (affine version),\n//   odelong_maffine in ode-maffine.hpp (autodif version)\n// is called inside.\n// (If -DUSE_MAFFINE2 then ode-maffine2.hpp is used instead.)\n\ntemplate <class F, class T> class StroboMap {\n\tpublic:\n\tF f;\n\tinterval<T> start, end;\n\tode_param<T> p;\n\n\tStroboMap(F f, interval<T> start, interval<T> end, ode_param<T> p = ode_param<T>())\n\t: f(f), start(start), end(end), p(p) {}\n\n\tub::vector<T> operator() (const ub::vector<T>& x){\n\t\tub::vector<T> result;\n\n\t\tresult = x;\n\n\t\todelong_nv(f, result, mid(start), mid(end), p);\n\n\t\treturn result;\n\t}\n\n\tub::vector< autodif<T> > operator() (const ub::vector< autodif<T> >& x){\n\t\tub::vector< autodif<T> > result;\n\n\t\tresult = x;\n\n\t\todelong_nv(f, result, mid(start), mid(end), p);\n\n\t\treturn result;\n\t}\n\n\tub::vector< interval<T> > operator() (const ub::vector< interval<T> >& x){\n\t\tub::vector< interval<T> > result;\n\t\tinterval<T> end2;\n\t\tint r;\n\n\t\tresult = x;\n\t\tend2 = end;\n\n\t\t#ifdef USE_MAFFINE2\n\t\tr = odelong_maffine2(f, result, start, end2, p);\n\t\t#else\n\t\tr = odelong_maffine(f, result, start, end2, p);\n\t\t#endif\n\n\t\tif (r != 2) {\n\t\t\tthrow std::domain_error(\"StroboMap(): cannot calculate validated solution.\");\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tub::vector< affine<T> > operator() (const ub::vector< affine<T> >& x){\n\t\tub::vector< affine<T> > result;\n\t\tinterval<T> end2;\n\t\tint r;\n\n\t\tresult = x;\n\t\tend2 = end;\n\n\t\t#ifdef USE_MAFFINE2\n\t\tr = odelong_maffine2(f, result, start, end2, p);\n\t\t#else\n\t\tr = odelong_maffine(f, result, start, end2, p);\n\t\t#endif\n\n\t\tif (r != 2) {\n\t\t\tthrow std::domain_error(\"StroboMap(): cannot calculate validated solution.\");\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tub::vector< autodif< interval<T> > > operator() (const ub::vector< autodif< interval<T> > >& x){\n\t\tub::vector< autodif< interval<T> > > result;\n\t\tinterval<T> end2;\n\t\tint r;\n\n\t\tresult = x;\n\t\tend2 = end;\n\n\t\tr = odelong_maffine(f, result, start, end2, p);\n\t\tif (r != 2) {\n\t\t\tthrow std::domain_error(\"StroboMap(): cannot calculate validated solution.\");\n\t\t}\n\n\t\treturn result;\n\t}\n};\n\n// Generate function object of \"x-f(x)\" from function object of f.\n\ntemplate <class F> class FixedPoint {\n\tpublic:\n\tF f;\n\tFixedPoint(F f) : f(f) {}\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x){\n\t\treturn x - f(x);\n\t}\n};\n\n\n// Generate function object for shooting method of two point\n// boundary value problem from 2-variable strobomap.\n//   boundary condition:\n//     x(start_index) = start_value, x(end_index) = end_value\n//   unknown variable:\n//     x(index != start_index)\n// Solve ODE from initial value (start_value, unknown) and try to\n// satisfy x(end_index) = end_value by changing unknown.\n\ntemplate <class F, class TV> class Shooting_TPBVP {\n\tpublic:\n\tF f;\n\tTV start_value, end_value;\n\tint start_index, end_index;\n\tint variable_index;\n\n\tShooting_TPBVP(F f, TV start_value, TV end_value, int start_index, int end_index) : f(f) , start_value(start_value), end_value(end_value), start_index(start_index), end_index(end_index) {\n\t\tvariable_index = 1 - start_index;\n\t}\n\n\t// mid_ifnecessary<T1,T2>(x) returns x if T2 is convertible to T1,\n\t// and returns mid(x) if impossoble.\n\n\t#include <boost/utility/enable_if.hpp>\n\n\ttemplate <class T1, class T2> T1 inline static mid_ifnecessary(T2& x, typename boost::enable_if_c< convertible<T2, T1>::value >::type* =0) {\n\t\treturn T1(x);\n\t}\n\n\ttemplate <class T1, class T2> T1 inline static mid_ifnecessary(T2& x, typename boost::enable_if_c< ! convertible<T2, T1>::value >::type* =0) {\n\t\treturn T1(mid(x));\n\t}\n\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& s) {\n\t\tub::vector<T> x, y, r;\n\t\tx.resize(2);\n\t\tr.resize(1);\n\t\tx(variable_index) = s(0);\n\t\tx(start_index) = mid_ifnecessary<T,TV>(start_value);\n\t\ty = f(x);\n\t\tr(0) = y(end_index) - mid_ifnecessary<T,TV>(end_value);\n\t\treturn r;\n\t}\n};\n\n} // namespace kv\n\n#endif // STROBOMAP_HPP\n", "meta": {"hexsha": "afccae13a36126f2fe44ec2f0b69b9bf6b288baa", "size": 4663, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/strobomap.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/strobomap.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/strobomap.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": 24.8031914894, "max_line_length": 188, "alphanum_fraction": 0.6654514261, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.5608999566284105}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Surface_mesh_shortest_path.h>\n\n#include <boost/variant.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3> Triangle_mesh;\ntypedef CGAL::Surface_mesh_shortest_path_traits<Kernel, Triangle_mesh> Traits;\ntypedef CGAL::Surface_mesh_shortest_path<Traits> Surface_mesh_shortest_path;\ntypedef Traits::Barycentric_coordinates Barycentric_coordinates;\ntypedef boost::graph_traits<Triangle_mesh> Graph_traits;\ntypedef Graph_traits::vertex_iterator vertex_iterator;\ntypedef Graph_traits::face_iterator face_iterator;\ntypedef Graph_traits::vertex_descriptor vertex_descriptor;\ntypedef Graph_traits::face_descriptor face_descriptor;\ntypedef Graph_traits::halfedge_descriptor halfedge_descriptor;\n\n// A model of SurfacemeshShortestPathVisitor storing simplicies\n// using boost::variant\nstruct Sequence_collector\n{\n  typedef boost::variant< vertex_descriptor,\n                         std::pair<halfedge_descriptor,double>,\n                         std::pair<face_descriptor, Barycentric_coordinates> > Simplex;\n  std::vector< Simplex > sequence;\n\n  void operator()(halfedge_descriptor he, double alpha)\n  {\n\n    sequence.push_back( std::make_pair(he, alpha) );\n  }\n\n  void operator()(vertex_descriptor v)\n  {\n    sequence.push_back( v );\n  }\n\n  void operator()(face_descriptor f, Barycentric_coordinates alpha)\n  {\n    sequence.push_back( std::make_pair(f, alpha) );\n  }\n};\n\n// A visitor to print what a variant contains using boost::apply_visitor\nstruct Print_visitor : public boost::static_visitor<> {\n  int i;\n  Triangle_mesh& g;\n\n  Print_visitor(Triangle_mesh& g) :i(-1), g(g) {}\n\n  void operator()(vertex_descriptor v)\n  {\n    std::cout << \"#\" << ++i << \" : Vertex : \" << get(boost::vertex_index, g)[v] << \"\\n\";\n  }\n\n  void operator()(const std::pair<halfedge_descriptor,double>& h_a)\n  {\n    std::cout << \"#\" << ++i << \" : Edge : \" << get(CGAL::halfedge_index, g)[h_a.first] << \" , (\"\n                                            << 1.0 - h_a.second << \" , \"\n                                            << h_a.second << \")\\n\";\n  }\n\n  void operator()(const std::pair<face_descriptor, Barycentric_coordinates>& f_bc)\n  {\n    std::cout << \"#\" << ++i << \" : Face : \" << get(CGAL::face_index, g)[f_bc.first] << \" , (\"\n                                            << f_bc.second[0] << \" , \"\n                                            << f_bc.second[1] << \" , \"\n                                            << f_bc.second[2] << \")\\n\";\n  }\n};\n\nint main(int argc, char** argv)\n{\n  const char* filename = (argc>1) ? argv[1] : \"data/elephant.off\";\n\n  Triangle_mesh tmesh;\n  if(!CGAL::read_polygon_mesh(filename, tmesh) ||\n     !CGAL::is_triangle_mesh(tmesh))\n  {\n    std::cerr << \"Invalid input file.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // pick up a random face\n  const unsigned int randSeed = argc > 2 ? boost::lexical_cast<unsigned int>(argv[2]) : 7915421;\n  CGAL::Random rand(randSeed);\n  const int target_face_index = rand.get_int(0, static_cast<int>(num_faces(tmesh)));\n  face_iterator face_it = faces(tmesh).first;\n  std::advance(face_it,target_face_index);\n  // ... and define a barycentric coordinates inside the face\n  Barycentric_coordinates face_location = {{0.25, 0.5, 0.25}};\n\n  // construct a shortest path query object and add a source point\n  Surface_mesh_shortest_path shortest_paths(tmesh);\n  shortest_paths.add_source_point(*face_it, face_location);\n\n  // pick a random target point inside a face\n  face_it = faces(tmesh).first;\n  std::advance(face_it, rand.get_int(0, static_cast<int>(num_faces(tmesh))));\n\n  // collect the sequence of simplicies crossed by the shortest path\n  Sequence_collector sequence_collector;\n  shortest_paths.shortest_path_sequence_to_source_points(*face_it, face_location, sequence_collector);\n\n  // print the sequence using the visitor pattern\n  Print_visitor print_visitor(tmesh);\n  for (size_t i = 0; i < sequence_collector.sequence.size(); ++i)\n    boost::apply_visitor(print_visitor, sequence_collector.sequence[i]);\n\n  return 0;\n}\n", "meta": {"hexsha": "512b2882ae0b6cc98db65e6a9d7fd1350ce3b3c4", "size": 4268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.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": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.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": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.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.5666666667, "max_line_length": 102, "alphanum_fraction": 0.6813495783, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.560750207748726}}
{"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 distributed Gaussian non-negative matrix factorization.\n * We first create factors and then a data matrix\n * from these factors. THis process ensures that we know the best factorization of the input.\n * We then try to reconstruct the factors.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n\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 = 1; // standard deviation\n\tmf_size_type r = 10;\n\n\t// parameters for ALS\n\tunsigned epochs = 20;\n\tSlLoss loss;\n\tmf_size_type testNnz = nnz/100;\n\n\tBalanceType type = BALANCE_L2;;\n\tBalanceMethod method = BALANCE_SIMPLE;\n\n\t// parameters for distribution\n\tint tasksPerRank = 2;\n\tmf_size_type blocks = world.size() * tasksPerRank;\n\n\tmfStart();\n\n\tif (world.rank() == 0) {\n\t#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n\t#endif\n\t\t// generate original factors by sampling from a uniform[0,1] 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::uniform_real<>(0,1));\n\t\tgenerateRandom(hIn, random, boost::uniform_real<>(0,1));\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\t//addRandom(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\tv.sort();\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\t\tSparseMatrixCM vc;\n\t\tcopyCm(v, vc);\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// generate initial factors by sampling from a uniform[0,1] distribution\n\t\tDenseMatrix w(size1, r);\n\t\tDenseMatrixCM h(r, size2);\n\t\tgenerateRandom(w, random, boost::uniform_real<>(0.0, 1.0));\n\t\tgenerateRandom(h, random, boost::uniform_real<>(0.0, 1.0));\n\n\t\t// distribute the input matrices and test matrix\n\t\tDistributedSparseMatrix dv = distributeMatrix(\"V\", blocks, 1, true, v);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix: \"\n\t\t\t\t<< dv.blocks1() << \" x \" << dv.blocks2() << \" blocks\");\n\t\tDistributedSparseMatrixCM dvc = distributeMatrix(\"VC\", 1, blocks, false, vc);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix (CM): \"\n\t\t\t\t<< dvc.blocks1() << \" x \" << dvc.blocks2() << \" blocks\");\n\t\tDistributedSparseMatrix dvTest = distributeMatrix(\"Vtest\", blocks, blocks, true, vTest);\n\t\tLOG4CXX_INFO(logger, \"Distributed test matrix: \"\n\t\t\t\t<< dvTest.blocks1() << \" x \" << dvTest.blocks2() << \" blocks\");\n\t\tDistributedDenseMatrix dw = distributeMatrix(\"W\", blocks, 1, true, w);\n\t\tDistributedDenseMatrixCM dh = distributeMatrix(\"H\", 1, blocks, false, h);\n\t\tLOG4CXX_INFO(logger, \"Distributed factor matrices\");\n\n\n\t\t// initialize\n\t\tDapFactorizationData<> data(dv, dw, dh, tasksPerRank, &dvc);\n\t\tDsgdFactorizationData<> testJob(dvTest, dw, dh, tasksPerRank);\n\t\tTrace trace;\n\t\tTimer t;\n\n\t\t// run GNMF to try to reconstruct the original factors\n\t\tt.start();\n\t\tdgnmf(data, epochs, trace, type, method, &testJob);\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/dgnmf-trace.R\");\n\t\ttrace.toRfile(\"/tmp/dgnmf-trace.R\", \"dgnmf\");\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "45db2591f1c3fc08a947199fa176901b70b22c73", "size": 4740, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/dgnmf.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/dgnmf.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/dgnmf.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": 34.8529411765, "max_line_length": 99, "alphanum_fraction": 0.696835443, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.56075020277751}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n#include <map>\n#include <memory>\n\nusing namespace Eigen;\n\nint main()\n{\n    using namespace MyDL;\n    using std::cout;\n    using std::endl;\n    using std::map;\n    using std::shared_ptr;\n    using std::string;\n    using std::unique_ptr;\n    using std::vector;\n\n    // Params\n    // auto W = std::make_shared<MatrixXd>(2, 2); // 左辺はautoで問題なし\n    // auto b = std::make_shared<MatrixXd>(1, 2);\n    // *W = MatrixXd::Random(2, 2);\n    // *b = MatrixXd::Zero(1, 2);\n    map<string, shared_ptr<MatrixXd>> params;\n\n    // Layers\n    // vector<unique_ptr<BaseLayer>> layers; // 基底クラスのポインタのコンテナを用意する\n    vector<shared_ptr<BaseLayer>> layers; // 基底クラスのポインタのコンテナを用意する\n    map<string, unique_ptr<BaseLayer>> layers_map;\n    // 抽象クラスのポインタに格納するので、unique_ptrとしてはBaseLayerに格納\n    // unique_ptr<BaseLayer> p_layer1(new AddLayer()); // C++11ではmake_uniqueが存在しない\n    // unique_ptr<BaseLayer> p_layer2(new MulLayer());\n    // unique_ptr<BaseLayer> p_layer3(new ReLU());\n    // unique_ptr<BaseLayer> p_layer4(new Sigmoid());\n    // unique_ptr<BaseLayer> p_layer5(new MyDL::Affine(W, b));\n    // unique_ptr<BaseLayer> p_layer6(new SoftmaxWithLoss());\n\n    shared_ptr<BaseLayer> p_layer1 = std::make_shared<AddLayer>();\n    shared_ptr<BaseLayer> p_layer2 = std::make_shared<MulLayer>();\n    shared_ptr<BaseLayer> p_layer3 = std::make_shared<ReLU>();\n    shared_ptr<BaseLayer> p_layer4 = std::make_shared<Sigmoid>();\n    // shared_ptr<BaseLayer> p_layer5 = std::make_shared<MyDL::Affine>(W, b);\n    shared_ptr<BaseLayer> p_layer5 = std::make_shared<MyDL::Affine>(2, 2); // サイズを入力するようにしてみる\n    shared_ptr<BaseLayer> p_layer6 = std::make_shared<SoftmaxWithLoss>();\n\n    // AddLayer    layer1;\n    // MulLayer    layer2;\n    // ReLU        layer3;\n    // Sigmoid     layer4;\n    // MyDL::Affine    layer5(W, b);\n    // SoftmaxWithLoss layer6;\n\n    // I/O containers\n    vector<MatrixXd> inputs;\n    vector<MatrixXd> outputs;\n    // MatrixXd X = -2 * MatrixXd::Identity(2, 2) + MatrixXd::Ones(2, 2);\n    MatrixXd X = MatrixXd::Identity(2, 2);\n    MatrixXd Y = MatrixXd::Ones(2, 2);\n    vector<MatrixXd> dout;\n    dout.push_back(MatrixXd::Ones(2, 2));\n\n    // inputs\n    inputs.push_back(X);\n    inputs.push_back(Y);\n\n    // layers\n    // layers.push_back(std::move(p_layer1)); // Layerの派生クラス(Add)のポインタをコンテナに格納\n    // layers.push_back(std::move(p_layer2)); // Layerの派生クラス(Mul)のポインタをコンテナに格納\n    // layers.push_back(std::move(p_layer3)); // Layerの派生クラス(ReLU)のポインタをコンテナに格納\n    // layers.push_back(std::move(p_layer4)); // Layerの派生クラス(Sigmoid)のポインタをコンテナに格納\n    // layers.push_back(std::move(p_layer5)); // Layerの派生クラス(Affine)のポインタをコンテナに格納\n    // layers.push_back(std::move(p_layer6)); // Layerの派生クラス(SoftmaxWithLoss)のポインタをコンテナに格納\n\n    layers.push_back(p_layer1); // Layerの派生クラス(Add)のポインタをコンテナに格納\n    layers.push_back(p_layer2); // Layerの派生クラス(Mul)のポインタをコンテナに格納\n    layers.push_back(p_layer3); // Layerの派生クラス(ReLU)のポインタをコンテナに格納\n    layers.push_back(p_layer4); // Layerの派生クラス(Sigmoid)のポインタをコンテナに格納\n    layers.push_back(p_layer5); // Layerの派生クラス(Affine)のポインタをコンテナに格納\n    layers.push_back(p_layer6); // Layerの派生クラス(SoftmaxWithLoss)のポインタをコンテナに格納\n\n    if (auto affine = std::dynamic_pointer_cast<MyDL::Affine>(p_layer5))\n    {\n        params[\"W\"] = affine->pW;\n        params[\"b\"] = affine->pb;\n    }\n\n    // layers_map[\"Add\"] = p_layer1;\n    // layers_map[\"Affine\"] = p_layer5;\n\n    // cout << \"--- map forward ---\" << endl;\n    // outputs = layers_map[\"Add\"]->forward(inputs);\n    // cout << outputs[0] << endl;\n    // outputs = layers_map[\"Affine\"]->forward(inputs);\n    // cout << outputs[0] << endl;\n\n    cout << \"----forward----\" << endl;\n    for (int i = 0; i < layers.size(); i++)\n    {\n        cout << \"----layer\" << i << \"----\" << endl;\n        outputs = layers[i]->forward(inputs); // コンテナに格納したLayerのアドレスから、メンバ関数を呼び出し(ポリモーフィズム)\n\n        cout << outputs[0] << endl;\n    }\n\n    // Affineレイヤのパラメータを更新できるのか確認したいので、backwardの処理を走らせた後に、\n    // gradsの内容を加えるという処理をし、その処理の前後でパラメータの内容が変化しているかを確認する。\n    cout << \"----backward----\" << endl;\n    for (int i = 0; i < layers.size(); i++)\n    {\n        vector<MatrixXd> grads;\n        cout << \"----layer\" << i << \"----\" << endl;\n        if (i < layers.size() - 1)\n        {\n            grads = layers[i]->backward(dout);\n        }\n        else\n        {\n            vector<MatrixXd> init_dout = {MatrixXd::Ones(1, 1)};\n            grads = layers[i]->backward(init_dout);\n        }\n\n        for (int j = 0; j < grads.size(); j++)\n        {\n            cout << grads[j] << endl;\n        }\n    }\n\n    if (auto affine = std::dynamic_pointer_cast<MyDL::Affine>(layers[4]))\n    {\n        cout << \"--- Affine Param b ---\" << endl;\n        cout << *(affine->pb) << endl;\n        cout << \"params[b]:\" << endl;\n        cout << *(params[\"b\"]) << endl;\n        cout << \"--- Affine Param W ---\" << endl;\n        cout << *(affine->pW) << endl;\n        cout << \"params[W]:\" << endl;\n        cout << *(params[\"W\"]) << endl;\n\n        *(params[\"b\"]) -= affine->db;\n        *(params[\"W\"]) -= affine->dW;\n    }\n    // 別のスコープでアクセスしたときに更新されているか？\n    if (auto re_affine = std::dynamic_pointer_cast<MyDL::Affine>(layers[4]))\n    {\n        cout << \"--- after update ---\" << endl; // 内部で処理しないと、affineが宣言されていない、となる。スコープ外？\n        cout << *(re_affine->pb) << endl;\n        cout << *(re_affine->pW) << endl;\n    }\n\n    cout << \"params[b]\" << endl;\n    cout << *(params[\"b\"]) << endl;\n    cout << \"params[W]\" << endl;\n    cout << *(params[\"W\"]) << endl;\n\n    return 0;\n}", "meta": {"hexsha": "161faff19383c5ae46a21cfd09b81bfbe7092a69", "size": 5552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_layer.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "test/test_layer.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_layer.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9182389937, "max_line_length": 93, "alphanum_fraction": 0.6010446686, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.5607501928350778}}
{"text": "#include <iostream>\n#include \"Solver.hpp\"\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Dense>\n\n#include <chrono>\n\nnamespace py = pybind11;\n\nusing namespace Eigen;\nusing namespace std;\n\n\nVectorXd solveQP( const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q, const py::EigenDRef<const VectorXd> &warm_start,const double epsilon =1e-10, const double mu_prox = 1e-7, const int max_iter=1000, const bool adaptative_rho=true){\n    Solver solver;\n    VectorXd solution(q.size());\n    solution = solver.solveQP(P,q,warm_start,epsilon,mu_prox,max_iter,adaptative_rho);\n    return solution;\n}\n\nVectorXd solveDerivativesQP(const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q, const py::EigenDRef<const VectorXd> &l, const py::EigenDRef<const VectorXd> &grad_l, const double epsilon =1e-10){\n    Solver solver;\n    VectorXd gamma(l.size()),bl(l.size());\n    gamma = solver.dualFromPrimalQP(P,q,l,epsilon);\n    bl = solver.solveDerivativesQP(P,q,l,gamma,grad_l,epsilon);\n    return bl;\n}\n\nVectorXd solveQCQP( const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q,const py::EigenDRef<const VectorXd> &l_n, const py::EigenDRef<const VectorXd> &mu, const py::EigenDRef<const VectorXd> &warm_start,const double epsilon=1e-10,const double mu_prox = 1e-7, const int max_iter = 1000, const bool adaptative_rho = true){\n    Solver solver;\n    VectorXd solution(q.size()), mul_n(l_n.size());\n    mul_n = l_n.cwiseProduct(mu);\n    solution = solver.solveQCQP(P,q,mul_n,warm_start,epsilon,mu_prox,max_iter,adaptative_rho);\n    return solution;\n}\n\nstd::tuple<MatrixXd,MatrixXd,VectorXd> solveDerivativesQCQP(const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q, const py::EigenDRef<const VectorXd> &l_n, const py::EigenDRef<const VectorXd> &mu, const py::EigenDRef<const VectorXd> &l, const py::EigenDRef<const VectorXd> &grad_l, const double epsilon =1e-10){\n    Solver solver;\n    MatrixXd E1(l_n.size(),l_n.size()),E2(l_n.size(),l_n.size());\n    VectorXd mul_n(l_n.size()),gamma(l.size()),blgamma(l.size());\n    mul_n = l_n.cwiseProduct(mu);\n    gamma = solver.dualFromPrimalQCQP(P,q,mul_n,l,epsilon);\n    std::tie(E1,E2) = solver.getE12QCQP(l_n, mu, gamma);\n    blgamma = solver.solveDerivativesQCQP(P,q,mul_n,l,gamma,grad_l,epsilon);\n    return std::make_tuple(E1,E2,blgamma);\n}\n\nVectorXd solveLCQP( const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q, const py::EigenDRef<const VectorXd> &warm_start,const double epsilon=1e-10,const double mu_prox = 1e-7, const int max_iter = 1000, const bool adaptative_rho = true){\n    Solver solver;\n    VectorXd solution(q.size());\n    solution = solver.solveLCQP(P,q,warm_start,epsilon,mu_prox,max_iter,adaptative_rho);\n    return solution;\n}\n\nVectorXd solveDerivativesLCQP(const py::EigenDRef<const MatrixXd> &P, const py::EigenDRef<const VectorXd> &q, const py::EigenDRef<const VectorXd> &l, const py::EigenDRef<const VectorXd> &grad_l, const double epsilon =1e-10){\n    Solver solver;\n    return solver.solveDerivativesLCQP(P,q,l,grad_l,epsilon);\n}\n\n\n\nPYBIND11_MODULE(diffsolvers, m) {\n    m.doc() = \"module solving QCQP and QP with ADMM, and computing the derivatives of the solution using implicit differentiation of KKT optimality conditions\";\n    m.def(\"solveQP\", &solveQP, \"A function which solves a QP problem with a regularized ADMM algorithm\",py::arg(\"P\"), py::arg(\"q\"),py::arg(\"warm_start\"),py::arg(\"epsilon\") = 1e-10,py::arg(\"mu_prox\")= 1e-7,py::arg(\"max_iter\")= 1000,py::arg(\"adaptative_rho\")= true, py::return_value_policy::reference_internal );\n    m.def(\"solveQCQP\", &solveQCQP, \"A function which solves a QCQP problem with a regularized ADMM algorithm\",py::arg(\"P\"), py::arg(\"q\"), py::arg(\"l_n\"),py::arg(\"mu\"), py::arg(\"warm_start\"),py::arg(\"epsilon\")= 1e-10,py::arg(\"mu_prox\")= 1e-7,py::arg(\"max_iter\")= 1000,py::arg(\"adaptative_rho\")= true, py::return_value_policy::reference_internal );\n    m.def(\"solveLCQP\", &solveLCQP, \"A function which solves a QCQP, Lorentz-cone-constrained problem with regularized ADMM algorithm\",py::arg(\"P\"), py::arg(\"q\"), py::arg(\"warm_start\"),py::arg(\"epsilon\")= 1e-10,py::arg(\"mu_prox\")= 1e-7,py::arg(\"max_iter\")= 1000,py::arg(\"adaptative_rho\")= true, py::return_value_policy::reference_internal );\n    m.def(\"solveDerivativesQP\", &solveDerivativesQP, \"A function which solves the differentiated KKT system of a QP\",py::arg(\"P\"), py::arg(\"q\"), py::arg(\"l\"), py::arg(\"grad_l\"), py::arg(\"epsilon\")=1e-10);\n    m.def(\"solveDerivativesQCQP\", &solveDerivativesQCQP, \"A function which solves the differentiated KKT system of a QCQP\",py::arg(\"P\"), py::arg(\"q\"), py::arg(\"l_n\"),py::arg(\"mu\"), py::arg(\"l\"), py::arg(\"grad_l\"), py::arg(\"epsilon\")=1e-10 );\n    m.def(\"solveDerivativesLCQP\", &solveDerivativesLCQP, \"A function which solves the differentiated KKT system of a Lorentz-cone-constrained QCQP\",py::arg(\"P\"), py::arg(\"q\"), py::arg(\"l\"), py::arg(\"grad_l\"), py::arg(\"epsilon\")=1e-10 );\n\n}\n", "meta": {"hexsha": "4dc7eaa69a7768e5d6bd8c13f1fe60a4d7e9d06c", "size": 5020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/diffqcqp/diffsolvers.cpp", "max_stars_repo_name": "mshalm/diffqcqp", "max_stars_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/diffqcqp/diffsolvers.cpp", "max_issues_repo_name": "mshalm/diffqcqp", "max_issues_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diffqcqp/diffsolvers.cpp", "max_forks_repo_name": "mshalm/diffqcqp", "max_forks_repo_head_hexsha": "2e7cd23a5dd0b68e53ee6ac17c229ee879ae537a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.9333333333, "max_line_length": 347, "alphanum_fraction": 0.7201195219, "num_tokens": 1544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5606864274212129}}
{"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//  Based on https://github.com/sportdeath/audio_transport/\n// T.Henderson and J.Solomon, Audio Transport:\n// a generalized portamento via optimal transport.\n// Proceedings of DAFX 2019.\n\n#pragma once\n\n#include \"STFT.hpp\"\n#include \"WindowFuncs.hpp\"\n#include \"../util/FFT.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nstruct SpetralMass\n{\n  index  startBin;\n  index  centerBin;\n  index  endBin;\n  double mass;\n};\n\nclass AudioTransport\n{\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXi = Eigen::ArrayXi;\n  using ArrayXcd = Eigen::ArrayXcd;\n  template <typename T>\n  using Ref = Eigen::Ref<T>;\n  using TransportMatrix = std::vector<std::tuple<index, index, double>>;\n  template <typename T>\n  using vector = std::vector<T>;\n\npublic:\n  AudioTransport(index maxFFTSize)\n      : mWindowSize(maxFFTSize), mFFTSize(maxFFTSize),\n        mBins(maxFFTSize / 2 + 1), mFFT(maxFFTSize),\n        mSTFT(maxFFTSize, maxFFTSize, maxFFTSize / 2),\n        mISTFT(maxFFTSize, maxFFTSize, maxFFTSize / 2),\n        mReassignSTFT(maxFFTSize, maxFFTSize, maxFFTSize / 2)\n  {}\n\n  void init(index windowSize, index fftSize, index hopSize)\n  {\n    mWindowSize = windowSize;\n    mWindow = ArrayXd::Zero(mWindowSize);\n    WindowFuncs::map()[WindowFuncs::WindowTypes::kHann](mWindowSize, mWindow);\n    mWindowSquared = mWindow * mWindow;\n    mFFTSize = fftSize;\n    mHopSize = hopSize;\n    mBins = fftSize / 2 + 1;\n    mPhase = ArrayXd::Zero(mBins);\n    mChanged = ArrayXi::Zero(mBins);\n    mBinFreqs = ArrayXd::LinSpaced(mBins, 0, mBins - 1) * (2 * pi) / mFFTSize;\n    mPhaseDiff = mBinFreqs * mHopSize;\n    mSTFT = STFT(windowSize, fftSize, hopSize);\n    mISTFT = ISTFT(windowSize, fftSize, hopSize);\n    mReassignSTFT = STFT(windowSize, fftSize, hopSize,\n                         static_cast<index>(WindowFuncs::WindowTypes::kHannD));\n    mInitialized = true;\n  }\n\n  bool initialized() const { return mInitialized; }\n\n  void processFrame(RealVectorView in1, RealVectorView in2, double weight,\n                    RealMatrixView out)\n  {\n    using namespace _impl;\n    using namespace Eigen;\n    assert(mInitialized);\n    ArrayXd  frame1 = asEigen<Array>(in1);\n    ArrayXd  frame2 = asEigen<Array>(in2);\n    ArrayXcd spectrum1(mBins);\n    ArrayXcd spectrum1Dh(mBins);\n    ArrayXcd spectrum2(mBins);\n    ArrayXcd spectrum2Dh(mBins);\n    ArrayXd  output(frame1.size());\n    mSTFT.processFrame(frame1, spectrum1);\n    mReassignSTFT.processFrame(frame1, spectrum1Dh);\n    mSTFT.processFrame(frame2, spectrum2);\n    mReassignSTFT.processFrame(frame2, spectrum2Dh);\n    ArrayXcd result =\n        interpolate(spectrum1, spectrum1Dh, spectrum2, spectrum2Dh, weight);\n    mISTFT.processFrame(result, output);\n    out.row(0) <<= asFluid(output);\n    out.row(1) <<= asFluid(mWindowSquared);\n  }\n\n  vector<SpetralMass> segmentSpectrum(const Ref<ArrayXd> mag,\n                                      const Ref<ArrayXd> reasignedFreq)\n  {\n\n    vector<SpetralMass> masses;\n    double              totalMass = mag.sum() + epsilon;\n    ArrayXi             sign = (reasignedFreq > mBinFreqs).cast<int>();\n    mChanged.setZero();\n    mChanged.segment(1, mBins - 1) =\n        sign.segment(1, mBins - 1) - sign.segment(0, mBins - 1);\n    SpetralMass currentMass{0, 0, 0, 0};\n    for (index i = 1; i < mChanged.size(); i++)\n    {\n      if (mChanged(i) == -1)\n      {\n        double d1 = reasignedFreq(i - 1) - mBinFreqs(i - 1);\n        double d2 = mBinFreqs(i) - reasignedFreq(i);\n        currentMass.centerBin = d1 < d2 ? i - 1 : i;\n      }\n      if (mChanged(i) == 1)\n      {\n        currentMass.endBin = i;\n        currentMass.mass =\n            mag.segment(currentMass.startBin, i - currentMass.startBin).sum() /\n            totalMass;\n        masses.emplace_back(currentMass);\n        currentMass = SpetralMass{i, i, i, 0};\n      }\n    }\n    currentMass.endBin = mBins;\n    currentMass.mass =\n        mag.segment(currentMass.startBin, mBins - currentMass.startBin).sum() /\n        totalMass;\n    masses.emplace_back(currentMass);\n    return masses;\n  }\n\n  TransportMatrix computeTransportMatrix(std::vector<SpetralMass> m1,\n                                         std::vector<SpetralMass> m2)\n  {\n    TransportMatrix matrix;\n    index           index1 = 0, index2 = 0;\n    double          mass1 = m1[0].mass;\n    double          mass2 = m2[0].mass;\n    while (true)\n    {\n      if (mass1 < mass2)\n      {\n        matrix.emplace_back(index1, index2, mass1);\n        mass2 -= mass1;\n        index1++;\n        if (index1 >= asSigned(m1.size())) break;\n        mass1 = m1[asUnsigned(index1)].mass;\n      }\n      else\n      {\n        matrix.emplace_back(index1, index2, mass2);\n        mass1 -= mass2;\n        index2++;\n        if (index2 >= asSigned(m2.size())) break;\n        mass2 = m2[asUnsigned(index2)].mass;\n      }\n    }\n    return matrix;\n  }\n\n  void placeMass(const SpetralMass mass, index bin, double scale,\n                 double centerPhase, Ref<ArrayXcd> input, Ref<ArrayXcd> output,\n                 double nextPhase, Ref<ArrayXd> amplitudes, Ref<ArrayXd> phases)\n  {\n    double phaseShift = centerPhase - std::arg(input(mass.centerBin));\n    for (index i = mass.startBin; i < mass.endBin; i++)\n    {\n      index pos = i + bin - mass.centerBin;\n      if (pos < 0 || pos >= output.size()) continue;\n      double phase = phaseShift + std::arg(input(i));\n      double mag = scale * std::abs(input(i));\n      output(pos) += std::polar(mag, phase);\n      if (mag > amplitudes(pos))\n      {\n        amplitudes(pos) = mag;\n        phases(pos) = nextPhase;\n      }\n    }\n  }\n\n  ArrayXcd interpolate(Ref<ArrayXcd> in1, Ref<ArrayXcd> in1Dh,\n                       Ref<ArrayXcd> in2, Ref<ArrayXcd> in2Dh,\n                       double interpolation)\n  {\n    ArrayXd  mag1 = in1.abs().real();\n    ArrayXd  mag2 = in2.abs().real();\n    ArrayXcd result = ArrayXcd::Zero(mBins);\n    double   mag1Sum = mag1.sum();\n    double   mag2Sum = mag2.sum();\n    if (mag1Sum <= 0 && mag2Sum <= 0) { return result; }\n    else if (mag1Sum > 0 && mag2Sum <= 0)\n    {\n      return in1;\n    }\n    else if (mag1Sum <= 0 && mag2Sum > 0)\n    {\n      return in2;\n    }\n    ArrayXd                  phase1 = in1.arg().real();\n    ArrayXd                  phase2 = in2.arg().real();\n    ArrayXd                  reasignedW1 = mBinFreqs - (in1Dh / in1).imag();\n    ArrayXd                  reasignedW2 = mBinFreqs - (in2Dh / in2).imag();\n    ArrayXd                  newAmplitudes = ArrayXd::Zero(mBins);\n    ArrayXd                  newPhases = ArrayXd::Zero(mBins);\n    std::vector<SpetralMass> s1 = segmentSpectrum(mag1, reasignedW1);\n    std::vector<SpetralMass> s2 = segmentSpectrum(mag2, reasignedW2);\n    if (s1.size() == 0 || s2.size() == 0) { return result; }\n\n    TransportMatrix matrix = computeTransportMatrix(s1, s2);\n    for (auto t : matrix)\n    {\n      SpetralMass m1 = s1[asUnsigned(std::get<0>(t))];\n      SpetralMass m2 = s2[asUnsigned(std::get<1>(t))];\n      index  interpolatedBin = std::lrint((1 - interpolation) * m1.centerBin +\n                                         interpolation * m2.centerBin);\n      double interpolationFactor = interpolation;\n      if (m1.centerBin != m2.centerBin)\n      {\n        interpolationFactor =\n            ((double) interpolatedBin - (double) m1.centerBin) /\n            ((double) m2.centerBin - (double) m1.centerBin);\n      }\n      double interpolatedFreq =\n          (1 - interpolationFactor) * reasignedW1(m1.centerBin) +\n          interpolationFactor * reasignedW2(m2.centerBin);\n      double nextPhase = mPhase(interpolatedBin) + interpolatedFreq * mHopSize;\n      double centerPhase = nextPhase - mPhaseDiff(interpolatedBin);\n      placeMass(m1, interpolatedBin,\n                (1 - interpolation) * std::get<2>(t) / m1.mass, centerPhase,\n                in1, result, nextPhase, newAmplitudes, newPhases);\n      placeMass(m2, interpolatedBin, interpolation * std::get<2>(t) / m2.mass,\n                centerPhase, in2, result, nextPhase, newAmplitudes, newPhases);\n    }\n    mPhase = newPhases;\n    return result;\n  }\n\n  index   mWindowSize{1024};\n  index   mHopSize{512};\n  ArrayXd mBinFreqs;\n  ArrayXd mWindow;\n  ArrayXd mWindowSquared;\n  index   mFFTSize{1024};\n  index   mBins{513};\n  FFT     mFFT;\n  bool    mInitialized{false};\n  ArrayXd mPhase;\n  ArrayXd mPhaseDiff;\n  ArrayXi mChanged;\n  STFT    mSTFT;\n  ISTFT   mISTFT;\n  STFT    mReassignSTFT;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "a86563ce630f02c406f5344a0a5c9d98a53cf48e", "size": 8963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/AudioTransport.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/AudioTransport.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/AudioTransport.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9507575758, "max_line_length": 80, "alphanum_fraction": 0.6206627245, "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.5605431524568932}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n\n#include <crest/util/eigen_extensions.hpp>\n\nnamespace crest\n{\n\n    enum class Norm\n    {\n        L2,\n        H1Semi,\n        H1\n    };\n\n    template <typename Scalar>\n    struct Assembly\n    {\n        Eigen::SparseMatrix<Scalar> stiffness;\n        Eigen::SparseMatrix<Scalar> mass;\n    };\n\n    template <typename Scalar, typename Impl>\n    class Basis\n    {\n    public:\n        virtual ~Basis() {}\n\n        virtual std::vector<int> interior_nodes() const = 0;\n        virtual std::vector<int> boundary_nodes() const = 0;\n\n        virtual Assembly<Scalar> assemble() const = 0;\n\n        /**\n         * The number of degrees of freedom associated with this basis.\n         * @return\n         */\n        virtual int num_dof() const = 0;\n\n        /**\n         * Given a continuous function f, interpolate it in the space\n         * represented by this basis, and return a vector of weights, such that\n         * element i in the vector corresponds to the weight factor of basis function i.\n         *\n         * Naturally, there are multiple ways to interpolate a function in a finite\n         * element space, so to have a single function for this is a simplifaction,\n         * and for now we'll leave it up to the concrete implementation which\n         * interpolation this corresponds to.\n         *\n         * @param f\n         * @return\n         */\n        template <typename Function2d>\n        VectorX<Scalar> interpolate(const Function2d &f) const\n        {\n            return static_cast<const Impl *>(this)->template interpolate<Function2d>(f);\n        }\n\n        /*\n         * Given a continuous function g, evaluate the function at each boundary node\n         * and return a vector of weights.\n         */\n        template <typename Function2d>\n        VectorX<Scalar> interpolate_boundary(const Function2d &f) const\n        {\n            return static_cast<const Impl *>(this)->template interpolate_boundary<Function2d>(f);\n        }\n\n        /**\n         * Computes the L2 inner product of a continuous function f\n         * and every basis function b_i for every degree of freedom i.\n         * More precisely, returns a vector whose ith element is\n         * determined by the L2 inner product (f, b_i), where b_i\n         * is the basis function associated with degree of freedom i.\n         *\n         * This is frequently used to compute the load vector in FEM\n         * applications.\n         * @param weights\n         * @param f\n         * @return\n         */\n        template <int QuadStrength, typename Function2d>\n        VectorX<Scalar> load(const Function2d &f) const\n        {\n            return static_cast<const Impl *>(this)->template load<QuadStrength, Function2d>(f);\n        };\n\n        /**\n         * Computes an approximation of the error between a continuous function f\n         * and a function g in the space spanned by the basis given by\n         * its basis weights in the L2 norm.\n         *\n         * More precisely, if g = sum w_i b_i for all degrees of freedom i,\n         * where w_i is given by weights(i) and b_i denotes the basis function\n         * associated with the degree of freedom i, then this function computes\n         *\n         * ||f - g||\n         *\n         * in the L2 norm.\n         *\n         * @param f\n         * @param weights\n         * @param norm\n         * @return\n         */\n        template <int QuadStrength, typename Function2d>\n        Scalar error_l2(const Function2d &f, const VectorX<Scalar> & weights) const;\n\n        /**\n         * Computes an approximation of the error between a continuous function f\n         * and a function g in the space spanned by the basis given by\n         * its basis weights in the H1 semi-norm.\n         *\n         * More precisely, if g = sum w_i b_i for all degrees of freedom i,\n         * where w_i is given by weights(i) and b_i denotes the basis function\n         * associated with the degree of freedom i, then this function computes\n         *\n         * ||f - g||\n         *\n         * in the H1 semi-norm, which is equivalent to\n         *\n         * || grad(f) - grad(g) ||\n         *\n         * in the L2 norm. Note that one specifies the derivatives f_x and f_y\n         * for the computation of the H1 semi-norm.\n         *\n         * @param f\n         * @param weights\n         * @param norm\n         * @return\n         */\n        template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n        Scalar error_h1_semi(const Function2d_x & f_x,\n                             const Function2d_y & f_y,\n                             const VectorX<Scalar> & weights) const;\n\n        /**\n         * Computes an approximation of the error between a continuous function f\n         * and a function g in the space spanned by the basis given by\n         * its basis weights in the H1 norm.\n         *\n         * More precisely, if g = sum w_i b_i for all degrees of freedom i,\n         * where w_i is given by weights(i) and b_i denotes the basis function\n         * associated with the degree of freedom i, then this function computes\n         *\n         * ||f - g||\n         *\n         * in the H1 norm. Note that the computation requires f, as well as its\n         * spatial derivatives f_x and f_y.\n         *\n         * Also note that implementers of subclasses do not need to reimplement this\n         * function, as it is implemented in terms of error_l2 and error_h1_semi.\n         *\n         * @param f\n         * @param weights\n         * @param norm\n         * @return\n         */\n        template <int QuadStrength, typename Function2d, typename Function2d_x, typename Function2d_y>\n        Scalar error_h1(const Function2d & f,\n                        const Function2d_x & f_x,\n                        const Function2d_y & f_y,\n                        const VectorX<Scalar> & weights) const;\n    };\n\n    template <typename Scalar, typename Impl>\n    template <int QuadStrength, typename Function2d>\n    Scalar Basis<Scalar, Impl>::error_l2(const Function2d & f, const VectorX<Scalar> & weights) const\n    {\n        return static_cast<const Impl *>(this)->template error_l2<QuadStrength>(f, weights);\n    };\n\n    template <typename Scalar, typename Impl>\n    template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n    Scalar Basis<Scalar, Impl>::error_h1_semi(const Function2d_x & f_x,\n                                              const Function2d_y & f_y,\n                                              const VectorX<Scalar> & weights) const\n    {\n        return static_cast<const Impl *>(this)->template error_h1_semi<QuadStrength>(f_x, f_y, weights);\n    };\n\n    template <typename Scalar, typename Impl>\n    template <int QuadStrength, typename Function2d, typename Function2d_x, typename Function2d_y>\n    Scalar Basis<Scalar, Impl>::error_h1(const Function2d & f,\n                                         const Function2d_x & f_x,\n                                         const Function2d_y & f_y,\n                                         const VectorX<Scalar> & weights) const\n    {\n        const auto l2 = error_l2<QuadStrength>(f, weights);\n        const auto h1_semi = error_h1_semi<QuadStrength>(f_x, f_y, weights);\n        return std::sqrt(l2 * l2 + h1_semi * h1_semi);\n    };\n}\n", "meta": {"hexsha": "e5e7e0b11e0147c572ddbc66eab499f6d06a1812", "size": 7291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/basis/basis.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/basis/basis.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/basis/basis.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": 37.3897435897, "max_line_length": 104, "alphanum_fraction": 0.5840076807, "num_tokens": 1631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5604985290683239}}
{"text": "#include <iostream>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <istream>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <map>\n#include <cmath>\n#include <algorithm>\n#include <boost/range/adaptor/indexed.hpp>\n\nusing namespace std;\n\nvector<vector<int>> examples;\nvector<vector<int>> centroids;\nint iteration = 0;\nbool finished = false;\n\nint closest_centroid(vector<int> example)\n{\n    map<string, int> closest = {{\"id\", -1}, {\"distance\", INT_MAX}};\n    for (auto centroid : centroids | boost::adaptors::indexed(1))\n    {\n        long long int distance = 0;\n        for (auto axis : example | boost::adaptors::indexed(1))\n        {\n            if (axis.index() - 1 == centroid.value().size())\n                break;\n            int centroid_point = centroid.value().at(axis.index() - 1);\n            int axis_value = axis.value();\n            int sub = centroid_point - axis_value;\n            distance += pow(sub, 2);\n        }\n        distance = sqrt(distance);\n        if (distance < closest.at(\"distance\"))\n        {\n            closest.at(\"id\") = centroid.index() - 1;\n            closest.at(\"distance\") = distance;\n        }\n    }\n    return closest.at(\"id\");\n}\n\nvector<int> recalculate(int centroid_id, vector<int> centroid)\n{\n    int total = 0;\n    vector<int> new_centroid(examples.at(0).size() - 1, 0);\n    for (auto example : examples)\n        if (example.at(example.size() - 1) == centroid_id)\n        {\n            for (auto example_axis : example | boost::adaptors::indexed(1))\n            {\n                if (example_axis.index() - 1 == new_centroid.size())\n                    break;\n                new_centroid.at(example_axis.index() - 1) += example_axis.value();\n            }\n            total++;\n        }\n\n    if (total)\n        for (auto centroid_axis : new_centroid | boost::adaptors::indexed(1))\n        {\n            centroid_axis.value() /= total;\n            if (centroid_axis.value() != centroid.at(centroid_axis.index() - 1))\n                finished = false;\n        }\n    return total ? new_centroid : centroid;\n}\n\nvoid k_means()\n{\n    while (!finished)\n    {\n        for (auto &example : examples)\n            example.at(example.size() - 1) = closest_centroid(example);\n        finished = true;\n        for (auto centroid : centroids | boost::adaptors::indexed(1))\n            centroid.value() = recalculate(centroid.index() - 1, centroid.value());\n        iteration++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    string extracted, comma, basename(argv[1]);\n    ifstream base, centroid;\n    for (int i = 0; i < 1; i++)\n    {\n        vector<int> temp;\n\n        base.open(\"bases/int_base_\" + basename + \".data\");\n        while (!base.eof())\n        {\n            getline(base, extracted);\n            stringstream is(extracted);\n            if (extracted.size() > 0)\n            {\n                while (getline(is, comma, ','))\n                    temp.push_back(stoi(comma));\n                temp.push_back(-1);\n                examples.push_back(temp);\n                temp.clear();\n            }\n        }\n        base.close();\n        centroid.open(\"bases/int_centroid_\" + basename + \"_20.data\");\n        while (!centroid.eof())\n        {\n            getline(centroid, extracted);\n            istringstream is(extracted);\n            if (extracted.size() > 0)\n            {\n                while (getline(is, comma, ','))\n                    temp.push_back(stoi(comma));\n                centroids.push_back(temp);\n                temp.clear();\n            }\n        }\n        centroid.close();\n        k_means();\n        ofstream myfile(\"results/my_saida_\" + basename + \"_seq\");\n        myfile << \"numero de iteracoes:\" << iteration;\n        for (auto value : examples | boost::adaptors::indexed(1))\n            myfile << \"id=\" << value.index() - 1 << \", classe=\" << value.value().at(value.value().size() - 1) << endl;\n    }\n    return 0;\n}", "meta": {"hexsha": "385970e78c6f77329e28461b019374071b68e12b", "size": 3938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k-means.seq.cpp", "max_stars_repo_name": "w4ll3/k-means", "max_stars_repo_head_hexsha": "60289c760f04c3e5548a293a10d4531a8b52caff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "k-means.seq.cpp", "max_issues_repo_name": "w4ll3/k-means", "max_issues_repo_head_hexsha": "60289c760f04c3e5548a293a10d4531a8b52caff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "k-means.seq.cpp", "max_forks_repo_name": "w4ll3/k-means", "max_forks_repo_head_hexsha": "60289c760f04c3e5548a293a10d4531a8b52caff", "max_forks_repo_licenses": ["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.2923076923, "max_line_length": 118, "alphanum_fraction": 0.532249873, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5604985217182572}}
{"text": "#include <Eigen/Dense>\r\n#include <chrono>\r\n#include <iostream>\r\n\r\n/*\r\nmult           0.0163621 s\r\nsolveInverse   0.0201562 s\r\nsolveFullPivLu 0.202951 s\r\nsolveColPivHh  0.547893 s\r\nsolveFullPivHh 0.621699 s\r\nsolveComplete  0.844406 s\r\n\r\n*/\r\n\r\nEigen::Vector3f mult(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m * v;\r\n}\r\n \r\nEigen::Vector3f solveInverse(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.inverse() * v;\r\n}\r\n \r\nEigen::Vector3f solveFullPivLu(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.fullPivLu().solve(v);\r\n} \r\n\r\nEigen::Vector3f solveColPivHh(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.colPivHouseholderQr().solve(v);\r\n} \r\n\r\nEigen::Vector3f solveFullPivHh(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.fullPivHouseholderQr().solve(v);\r\n} \r\n\r\nEigen::Vector3f solveComplete(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.completeOrthogonalDecomposition().solve(v);\r\n} \r\n\r\nEigen::Vector3f solveBdcsvd(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.bdcSvd().solve(v);\r\n} \r\n\r\nEigen::Vector3f solveJacobiSvd(Eigen::Matrix3f const &m, Eigen::Vector3f const &v) {\r\n  return m.jacobiSvd().solve(v);\r\n} \r\n\r\ntypedef Eigen::Vector3f func(Eigen::Matrix3f const &m, Eigen::Vector3f const &v);\r\n\r\nint measure(char const *t, func &f) {\r\n  Eigen::Matrix3f m;\r\n  Eigen::Vector3f v,s;\r\n  s << 0.0f, 0.0f, 0.0f;\r\n  int n = 0;\r\n  auto start = std::chrono::high_resolution_clock::now();\r\n  for(int i = 0; i < 1000000; ++i) {\r\n    m << ++n, ++n, ++n, ++n, ++n, ++n, ++n, ++n, ++n;\r\n    v << ++n, ++n, ++n;\r\n    n %= 71;\r\n    s += f(m, v);\r\n  }\r\n  auto end = std::chrono::high_resolution_clock::now();\r\n  std::chrono::duration<double> diff = end - start;\r\n  std::cout << t << ' ' << diff.count() << \" s\\n\";\r\n  return s(0);\r\n}\r\n\r\nint main() {\r\n  return measure(\"mult\", mult) +\r\n  measure(\"solveInverse\", solveInverse) +\r\n  measure(\"solveFullPivLu\", solveFullPivLu) +\r\n  measure(\"solveColPivHh\", solveColPivHh) +\r\n  measure(\"solveFullPivHh\", solveFullPivHh) +\r\n  measure(\"solveComplete\", solveComplete)/* +\r\n  measure(\"solveBdcSvd\", solveBdcsvd) +\r\n  measure(\"solveJacobiSvd\", solveJacobiSvd)*/;\r\n}\r\n", "meta": {"hexsha": "5bfe686fc2fd4f0d6704f066cd24fc48571b33c7", "size": 2226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reference/solve3x3.cpp", "max_stars_repo_name": "balazs-bamer/cuda-bezier-triangle-raytracer", "max_stars_repo_head_hexsha": "08b9ec1eb17b49f73429d4f7f943896a3c17d50e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reference/solve3x3.cpp", "max_issues_repo_name": "balazs-bamer/cuda-bezier-triangle-raytracer", "max_issues_repo_head_hexsha": "08b9ec1eb17b49f73429d4f7f943896a3c17d50e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reference/solve3x3.cpp", "max_forks_repo_name": "balazs-bamer/cuda-bezier-triangle-raytracer", "max_forks_repo_head_hexsha": "08b9ec1eb17b49f73429d4f7f943896a3c17d50e", "max_forks_repo_licenses": ["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.9090909091, "max_line_length": 85, "alphanum_fraction": 0.6446540881, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6477982043529716, "lm_q1q2_score": 0.560490616061501}}
{"text": "/*\r\n * fpu.cpp\r\n *\r\n * This example demonstrates how one can use odeint to solve the Fermi-Pasta-Ulam system.\r\n\r\n *  Created on: July 13, 2011\r\n *\r\n * Copyright 2011-2012 Karsten Ahnert\r\n * Copyright 2011 Mario Mulansky\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 <numeric>\r\n#include <cmath>\r\n#include <vector>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\n#ifndef M_PI //not there on windows\r\n#define M_PI 3.1415927 //...\r\n#endif\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\n//[ fpu_system_function\r\ntypedef vector< double > container_type;\r\n\r\nstruct fpu\r\n{\r\n    const double m_beta;\r\n\r\n    fpu( const double beta = 1.0 ) : m_beta( beta ) { }\r\n\r\n    // system function defining the ODE\r\n    void operator()( const container_type &q , container_type &dpdt ) const\r\n    {\r\n        size_t n = q.size();\r\n        double tmp = q[0] - 0.0;\r\n        double tmp2 = tmp + m_beta * tmp * tmp * tmp;\r\n        dpdt[0] = -tmp2;\r\n        for( size_t i=0 ; i<n-1 ; ++i )\r\n        {\r\n            tmp = q[i+1] - q[i];\r\n            tmp2 = tmp + m_beta * tmp * tmp * tmp;\r\n            dpdt[i] += tmp2;\r\n            dpdt[i+1] = -tmp2;\r\n        }\r\n        tmp = - q[n-1];\r\n        tmp2 = tmp + m_beta * tmp * tmp * tmp;\r\n        dpdt[n-1] += tmp2;\r\n    }\r\n\r\n    // calculates the energy of the system\r\n    double energy( const container_type &q , const container_type &p ) const\r\n    {\r\n        // ...\r\n        //<-\r\n        double energy = 0.0;\r\n        size_t n = q.size();\r\n\r\n        double tmp = q[0];\r\n        energy += 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;\r\n        for( size_t i=0 ; i<n-1 ; ++i )\r\n        {\r\n            tmp = q[i+1] - q[i];\r\n            energy += 0.5 * ( p[i] * p[i] + tmp * tmp ) + 0.25 * m_beta * tmp * tmp * tmp * tmp;\r\n        }\r\n        energy += 0.5 * p[n-1] * p[n-1];\r\n        tmp = q[n-1];\r\n        energy += 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;\r\n\r\n        return energy;\r\n        //->\r\n    }\r\n\r\n    // calculates the local energy of the system\r\n    void local_energy( const container_type &q , const container_type &p , container_type &e ) const\r\n    {\r\n        // ...\r\n        //<-\r\n        size_t n = q.size();\r\n        double tmp = q[0];\r\n        double tmp2 = 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;\r\n        e[0] = tmp2;\r\n        for( size_t i=0 ; i<n-1 ; ++i )\r\n        {\r\n            tmp = q[i+1] - q[i];\r\n            tmp2 = 0.25 * tmp * tmp + 0.125 * m_beta * tmp * tmp * tmp * tmp;\r\n            e[i] += 0.5 * p[i] * p[i] + tmp2 ;\r\n            e[i+1] = tmp2;\r\n        }\r\n        tmp = q[n-1];\r\n        tmp2 = 0.5 * tmp * tmp + 0.25 * m_beta * tmp * tmp * tmp * tmp;\r\n        e[n-1] += 0.5 * p[n-1] * p[n-1] + tmp2;\r\n        //->\r\n    }\r\n};\r\n//]\r\n\r\n\r\n\r\n//[ fpu_observer\r\nstruct streaming_observer\r\n{\r\n    std::ostream& m_out;\r\n    const fpu &m_fpu;\r\n    size_t m_write_every;\r\n    size_t m_count;\r\n\r\n    streaming_observer( std::ostream &out , const fpu &f , size_t write_every = 100 )\r\n    : m_out( out ) , m_fpu( f ) , m_write_every( write_every ) , m_count( 0 ) { }\r\n\r\n    template< class State >\r\n    void operator()( const State &x , double t )\r\n    {\r\n        if( ( m_count % m_write_every ) == 0 )\r\n        {\r\n            container_type &q = x.first;\r\n            container_type &p = x.second;\r\n            container_type energy( q.size() );\r\n            m_fpu.local_energy( q , p , energy );\r\n            for( size_t i=0 ; i<q.size() ; ++i )\r\n            {\r\n                m_out << t << \"\\t\" << i << \"\\t\" << q[i] << \"\\t\" << p[i] << \"\\t\" << energy[i] << \"\\n\";\r\n            }\r\n            m_out << \"\\n\";\r\n            clog << t << \"\\t\" << accumulate( energy.begin() , energy.end() , 0.0 ) << \"\\n\";\r\n        }\r\n        ++m_count;\r\n    }\r\n};\r\n//]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nint main( int argc , char **argv )\r\n{\r\n    //[ fpu_integration\r\n    const size_t n = 64;\r\n    container_type q( n , 0.0 ) , p( n , 0.0 );\r\n\r\n    for( size_t i=0 ; i<n ; ++i )\r\n    {\r\n        p[i] = 0.0;\r\n        q[i] = 32.0 * sin( double( i + 1 ) / double( n + 1 ) * M_PI );\r\n    }\r\n\r\n\r\n    const double dt = 0.1;\r\n\r\n    typedef symplectic_rkn_sb3a_mclachlan< container_type > stepper_type;\r\n    fpu fpu_instance( 8.0 );\r\n\r\n    integrate_const( stepper_type() , fpu_instance ,\r\n            make_pair( boost::ref( q ) , boost::ref( p ) ) ,\r\n            0.0 , 1000.0 , dt , streaming_observer( cout , fpu_instance , 10 ) );\r\n    //]\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "ff710dc091791a55f82b823b0325e54369c9a366", "size": 4569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/fpu.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/fpu.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/fpu.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.8764705882, "max_line_length": 102, "alphanum_fraction": 0.4801926023, "num_tokens": 1393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.560314025574398}}
{"text": "#include \"mtf/SSM/Affine.h\"\r\n#include \"mtf/SSM/AffineEstimator.h\"\r\n#include \"mtf/Utilities/warpUtils.h\"\r\n#include \"mtf/Utilities/miscUtils.h\"\r\n\r\n#include <Eigen/SVD>\r\n\r\n#define VALIDATE_AFFINE_WARP(warp)\\\r\n\tassert(warp(2, 0) == 0.0 && warp(2, 1) == 0.0);\\\r\n\tassert(warp(2, 2) == 1.0)\r\n\r\n#define AFF_NORMALIZED_INIT 0\r\n#define AFF_PT_BASED_SAMPLING 0\r\n#define AFF_DEBUG_MODE 0\r\n\r\n_MTF_BEGIN_NAMESPACE\r\n\r\nAffineParams::AffineParams(const SSMParams *ssm_params,\r\nbool _normalized_init, int _pt_based_sampling,\r\nbool _debug_mode) :\r\nSSMParams(ssm_params),\r\nnormalized_init(_normalized_init),\r\npt_based_sampling(_pt_based_sampling),\r\ndebug_mode(_debug_mode){}\r\n\r\nAffineParams::AffineParams(const AffineParams *params) :\r\nSSMParams(params),\r\nnormalized_init(AFF_NORMALIZED_INIT),\r\npt_based_sampling(AFF_PT_BASED_SAMPLING),\r\ndebug_mode(AFF_DEBUG_MODE){\r\n\tif(params){\r\n\t\tnormalized_init = params->normalized_init;\r\n\t\tpt_based_sampling = params->pt_based_sampling;\r\n\t\tdebug_mode = params->debug_mode;\r\n\t}\r\n}\r\nAffine::Affine(\r\n\tconst ParamType *_params) : ProjectiveBase(_params),\r\n\tparams(_params){\r\n\r\n\tprintf(\"\\n\");\r\n\tprintf(\"Using Affine 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(\"pt_based_sampling: %d\\n\", params.pt_based_sampling);\r\n\tprintf(\"debug_mode: %d\\n\", params.debug_mode);\r\n\r\n\tname = \"affine\";\r\n\tstate_size = 6;\r\n\tcurr_state.resize(state_size);\r\n\r\n\tutils::getNormUnitSquarePts(norm_pts, norm_corners, resx, resy,\r\n\t\t1 - resx / 2.0, 1 - resy / 2.0, resx / 2.0, resy / 2.0);\r\n\tutils::homogenize(norm_pts, norm_pts_hm);\r\n\tutils::homogenize(norm_corners, norm_corners_hm);\r\n\r\n\tinit_corners = getNormCorners();\r\n\tinit_corners_hm = getHomNormCorners();\r\n\tinit_pts = getNormPts();\r\n\tinit_pts_hm = getHomNormPts();\r\n}\r\n\r\nvoid Affine::setCorners(const CornersT& corners){\r\n\tif(params.normalized_init){\r\n\t\tcurr_warp = utils::computeAffineNDLT(init_corners, corners);\r\n\t\tgetStateFromWarp(curr_state, curr_warp);\r\n\r\n\t\tcurr_pts.noalias() = curr_warp.topRows<2>() * init_pts_hm;\r\n\t\tcurr_corners.noalias() = curr_warp.topRows<2>() * init_corners_hm;\r\n\r\n\t\tutils::homogenize(curr_pts, curr_pts_hm);\r\n\t\tutils::homogenize(curr_corners, curr_corners_hm);\r\n\t} else {\r\n\t\tcurr_corners = corners;\r\n\t\tutils::homogenize(curr_corners, curr_corners_hm);\r\n\r\n\t\tgetPtsFromCorners(curr_warp, curr_pts, curr_pts_hm, curr_corners);\r\n\r\n\t\tinit_corners = curr_corners;\r\n\t\tinit_pts = curr_pts;\r\n\t\tutils::homogenize(init_corners, init_corners_hm);\r\n\t\tutils::homogenize(init_pts, init_pts_hm);\r\n\r\n\t\tcurr_warp = Matrix3d::Identity();\r\n\t\tcurr_state.fill(0);\r\n\t}\r\n}\r\n\r\nvoid Affine::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\tgetStateFromWarp(curr_state, curr_warp);\r\n\r\n\t//curr_pts_hm.noalias() = curr_warp * init_pts_hm;\r\n\t//curr_corners_hm.noalias() = curr_warp * init_corners_hm;\r\n\t//utils::dehomogenize(curr_pts_hm, curr_pts);\r\n\t//utils::dehomogenize(curr_corners_hm, curr_corners);\r\n\r\n\tcurr_pts.noalias() = curr_warp.topRows<2>() * init_pts_hm;\r\n\tcurr_corners.noalias() = curr_warp.topRows<2>() * init_corners_hm;\r\n\r\n\t//utils::printMatrix(curr_warp, \"curr_warp\", \"%15.9f\");\r\n\t//utils::printMatrix(affine_warp_mat, \"affine_warp_mat\", \"%15.9f\");\r\n}\r\n\r\nvoid Affine::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.noalias() = curr_warp.topRows<2>() * init_pts_hm;\r\n\tcurr_corners.noalias() = curr_warp.topRows<2>() * init_corners_hm;\r\n}\r\n\r\nvoid Affine::getWarpFromState(Matrix3d &warp_mat,\r\n\tconst VectorXd& ssm_state){\r\n\tvalidate_ssm_state(ssm_state);\r\n\r\n\twarp_mat(0, 0) = 1 + ssm_state(2);\r\n\twarp_mat(0, 1) = ssm_state(3);\r\n\twarp_mat(0, 2) = ssm_state(0);\r\n\twarp_mat(1, 0) = ssm_state(4);\r\n\twarp_mat(1, 1) = 1 + ssm_state(5);\r\n\twarp_mat(1, 2) = ssm_state(1);\r\n\twarp_mat(2, 0) = 0;\r\n\twarp_mat(2, 1) = 0;\r\n\twarp_mat(2, 2) = 1;\r\n}\r\n\r\nvoid Affine::getStateFromWarp(VectorXd &state_vec,\r\n\tconst Matrix3d& warp_mat){\r\n\tvalidate_ssm_state(state_vec);\r\n\tVALIDATE_AFFINE_WARP(warp_mat);\r\n\r\n\tstate_vec(0) = warp_mat(0, 2);\r\n\tstate_vec(1) = warp_mat(1, 2);\r\n\tstate_vec(2) = warp_mat(0, 0) - 1;\r\n\tstate_vec(3) = warp_mat(0, 1);\r\n\tstate_vec(4) = warp_mat(1, 0);\r\n\tstate_vec(5) = warp_mat(1, 1) - 1;\r\n}\r\n\r\nvoid Affine::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 Affine::getInitPixGrad(Matrix2Xd &ssm_grad, int pix_id) {\r\n\tdouble x = init_pts(0, pix_id);\r\n\tdouble y = init_pts(1, pix_id);\r\n\tssm_grad <<\r\n\t\t1, 0, x, y, 0, 0,\r\n\t\t0, 1, 0, 0, x, y;\r\n}\r\n\r\nvoid Affine::cmptInitPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &dI_dx){\r\n\tvalidate_ssm_jacobian(dI_dp, dI_dx);\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\tspi_pt_check_mc(spi_mask, pt_id, ch_pt_id);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tdouble Ix = dI_dx(ch_pt_id, 0);\r\n\t\t\tdouble Iy = dI_dx(ch_pt_id, 1);\r\n\t\t\tdI_dp(ch_pt_id, 0) = Ix;\r\n\t\t\tdI_dp(ch_pt_id, 1) = Iy;\r\n\t\t\tdI_dp(ch_pt_id, 2) = Ix * x;\r\n\t\t\tdI_dp(ch_pt_id, 3) = Ix * y;\r\n\t\t\tdI_dp(ch_pt_id, 4) = Iy * x;\r\n\t\t\tdI_dp(ch_pt_id, 5) = Iy * y;\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Affine::cmptApproxPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &dI_dx) {\r\n\tvalidate_ssm_jacobian(dI_dp, dI_dx);\r\n\tdouble a = curr_state(2) + 1, b = curr_state(3);\r\n\tdouble c = curr_state(4), d = curr_state(5) + 1;\r\n\tdouble inv_det = 1.0 / (a*d - b*c);\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\tspi_pt_check_mc(spi_mask, pt_id, ch_pt_id);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tdouble Ix = dI_dx(ch_pt_id, 0);\r\n\t\t\tdouble Iy = dI_dx(ch_pt_id, 1);\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\t\t\tdI_dp(ch_pt_id, 0) = (Ix*d - Iy*c) * inv_det;\r\n\t\t\tdI_dp(ch_pt_id, 1) = (Iy*a - Ix*b) * inv_det;\r\n\t\t\tdI_dp(ch_pt_id, 2) = (Ixx*d - Iyx*c) * inv_det;\r\n\t\t\tdI_dp(ch_pt_id, 3) = (Ixy*d - Iyy*c) * inv_det;\r\n\t\t\tdI_dp(ch_pt_id, 4) = (Iyx*a - Ixx*b) * inv_det;\r\n\t\t\tdI_dp(ch_pt_id, 5) = (Iyy*a - Ixy*b) * inv_det;\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Affine::cmptWarpedPixJacobian(MatrixXd &dI_dp,\r\n\tconst PixGradT &dI_dx) {\r\n\tvalidate_ssm_jacobian(dI_dp, dI_dx);\r\n\tdouble a = curr_state(2) + 1, b = curr_state(3);\r\n\tdouble c = curr_state(4), d = curr_state(5) + 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\tspi_pt_check_mc(spi_mask, pt_id, ch_pt_id);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tdouble Ix = dI_dx(ch_pt_id, 0);\r\n\t\t\tdouble Iy = dI_dx(ch_pt_id, 1);\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) = Ix*a + Iy*c;\r\n\t\t\tdI_dp(ch_pt_id, 1) = Ix*b + Iy*d;\r\n\t\t\tdI_dp(ch_pt_id, 2) = Ixx*a + Iyx*c;\r\n\t\t\tdI_dp(ch_pt_id, 3) = Ixy*a + Iyy*c;\r\n\t\t\tdI_dp(ch_pt_id, 4) = Ixx*b + Iyx*d;\r\n\t\t\tdI_dp(ch_pt_id, 5) = Ixy*b + Iyy*d;\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\nvoid Affine::cmptInitPixHessian(MatrixXd &d2I_dp2, const PixHessT &d2I_dw2,\r\n\tconst PixGradT &dI_dw){\r\n\tvalidate_ssm_hessian(d2I_dp2, d2I_dw2, 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\tspi_pt_check_mc(spi_mask, pt_id, ch_pt_id);\r\n\r\n\t\tdouble x = init_pts(0, pt_id);\r\n\t\tdouble y = init_pts(1, pt_id);\r\n\t\tMatrix26d dw_dp;\r\n\t\tdw_dp <<\r\n\t\t\t1, 0, x, y, 0, 0,\r\n\t\t\t0, 1, 0, 0, x, y;\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tMap<Matrix6d>(d2I_dp2.col(ch_pt_id).data()) = dw_dp.transpose()*\r\n\t\t\t\tMap<const Matrix2d>(d2I_dw2.col(ch_pt_id).data())*dw_dp;\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\nvoid Affine::cmptWarpedPixHessian(MatrixXd &d2I_dp2, const PixHessT &d2I_dw2,\r\n\tconst PixGradT &dI_dw) {\r\n\tvalidate_ssm_hessian(d2I_dp2, d2I_dw2, dI_dw);\r\n\tdouble a2 = curr_state(2) + 1, a3 = curr_state(3);\r\n\tdouble a4 = curr_state(4), a5 = curr_state(5) + 1;\r\n\tMatrix2d dw_dx;\r\n\tdw_dx <<\r\n\t\ta2, a3,\r\n\t\ta4, a5;\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\tspi_pt_check_mc(spi_mask, pt_id, ch_pt_id);\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\tMatrix26d dw_dp;\r\n\t\tdw_dp <<\r\n\t\t\t1, 0, x, y, 0, 0,\r\n\t\t\t0, 1, 0, 0, x, y;\r\n\r\n\t\tfor(unsigned int ch_id = 0; ch_id < n_channels; ++ch_id){\r\n\t\t\tMap<Matrix6d>(d2I_dp2.col(ch_pt_id).data()) = dw_dp.transpose()*\r\n\t\t\t\tdw_dx.transpose()*Map<const Matrix2d>(d2I_dw2.col(ch_pt_id).data())*dw_dx*dw_dp;\r\n\t\t\t++ch_pt_id;\r\n\t\t}\r\n\t}\r\n}\r\nvoid Affine::updateGradPts(double grad_eps){\r\n\tVector2d diff_vec_x_warped = curr_warp.topRows<2>().col(0) * grad_eps;\r\n\tVector2d diff_vec_y_warped = curr_warp.topRows<2>().col(1) * grad_eps;\r\n\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\tspi_pt_check(spi_mask, pt_id);\r\n\r\n\t\tgrad_pts(0, pt_id) = curr_pts(0, pt_id) + diff_vec_x_warped(0);\r\n\t\tgrad_pts(1, pt_id) = curr_pts(1, pt_id) + diff_vec_x_warped(1);\r\n\r\n\t\tgrad_pts(2, pt_id) = curr_pts(0, pt_id) - diff_vec_x_warped(0);\r\n\t\tgrad_pts(3, pt_id) = curr_pts(1, pt_id) - diff_vec_x_warped(1);\r\n\r\n\t\tgrad_pts(4, pt_id) = curr_pts(0, pt_id) + diff_vec_y_warped(0);\r\n\t\tgrad_pts(5, pt_id) = curr_pts(1, pt_id) + diff_vec_y_warped(1);\r\n\r\n\t\tgrad_pts(6, pt_id) = curr_pts(0, pt_id) - diff_vec_y_warped(0);\r\n\t\tgrad_pts(7, pt_id) = curr_pts(1, pt_id) - diff_vec_y_warped(1);\r\n\t}\r\n}\r\n\r\n\r\nvoid Affine::updateHessPts(double hess_eps){\r\n\tdouble hess_eps2 = 2 * hess_eps;\r\n\r\n\tVector2d diff_vec_xx_warped = curr_warp.topRows<2>().col(0) * hess_eps2;\r\n\tVector2d diff_vec_yy_warped = curr_warp.topRows<2>().col(1) * hess_eps2;\r\n\tVector2d diff_vec_xy_warped = (curr_warp.topRows<2>().col(0) + curr_warp.topRows<2>().col(1)) * hess_eps;\r\n\tVector2d diff_vec_yx_warped = (curr_warp.topRows<2>().col(0) - curr_warp.topRows<2>().col(1)) * hess_eps;\r\n\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\tspi_pt_check(spi_mask, pt_id);\r\n\r\n\t\thess_pts(0, pt_id) = curr_pts(0, pt_id) + diff_vec_xx_warped(0);\r\n\t\thess_pts(1, pt_id) = curr_pts(1, pt_id) + diff_vec_xx_warped(1);\r\n\r\n\t\thess_pts(2, pt_id) = curr_pts(0, pt_id) - diff_vec_xx_warped(0);\r\n\t\thess_pts(3, pt_id) = curr_pts(1, pt_id) - diff_vec_xx_warped(1);\r\n\r\n\t\thess_pts(4, pt_id) = curr_pts(0, pt_id) + diff_vec_yy_warped(0);\r\n\t\thess_pts(5, pt_id) = curr_pts(1, pt_id) + diff_vec_yy_warped(1);\r\n\r\n\t\thess_pts(6, pt_id) = curr_pts(0, pt_id) - diff_vec_yy_warped(0);\r\n\t\thess_pts(7, pt_id) = curr_pts(1, pt_id) - diff_vec_yy_warped(1);\r\n\r\n\t\thess_pts(8, pt_id) = curr_pts(0, pt_id) + diff_vec_xy_warped(0);\r\n\t\thess_pts(9, pt_id) = curr_pts(1, pt_id) + diff_vec_xy_warped(1);\r\n\r\n\t\thess_pts(10, pt_id) = curr_pts(0, pt_id) - diff_vec_xy_warped(0);\r\n\t\thess_pts(11, pt_id) = curr_pts(1, pt_id) - diff_vec_xy_warped(1);\r\n\r\n\t\thess_pts(12, pt_id) = curr_pts(0, pt_id) + diff_vec_yx_warped(0);\r\n\t\thess_pts(13, pt_id) = curr_pts(1, pt_id) + diff_vec_yx_warped(1);\r\n\r\n\t\thess_pts(14, pt_id) = curr_pts(0, pt_id) - diff_vec_yx_warped(0);\r\n\t\thess_pts(15, pt_id) = curr_pts(1, pt_id) - diff_vec_yx_warped(1);\r\n\t}\r\n}\r\n\r\nvoid Affine::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::computeAffineDLT(in_corners, out_corners);\r\n\tgetStateFromWarp(state_update, warp_update_mat);\r\n}\r\n\r\nvoid Affine::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 = estimateAffine(in_pts, out_pts, mask, est_params);\r\n\tstate_update(0) = warp_mat_cv.at<double>(0, 2);\r\n\tstate_update(1) = warp_mat_cv.at<double>(1, 2);\r\n\tstate_update(2) = warp_mat_cv.at<double>(0, 0) - 1;\r\n\tstate_update(3) = warp_mat_cv.at<double>(0, 1);\r\n\tstate_update(4) = warp_mat_cv.at<double>(1, 0);\r\n\tstate_update(5) = warp_mat_cv.at<double>(1, 1) - 1;\r\n}\r\n\r\nvoid Affine::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\twarped_corners(0, corner_id) = warp_mat(0, 0)*orig_corners(0, corner_id) + warp_mat(0, 1)*orig_corners(1, corner_id) +\r\n\t\t\twarp_mat(0, 2);\r\n\t\twarped_corners(1, corner_id) = warp_mat(1, 0)*orig_corners(0, corner_id) + warp_mat(1, 1)*orig_corners(1, corner_id) +\r\n\t\t\twarp_mat(1, 2);\r\n\t}\r\n}\r\n\r\nvoid Affine::applyWarpToPts(Matrix2Xd &warped_pts, const Matrix2Xd &orig_pts,\r\n\tconst VectorXd &ssm_state){\r\n\tgetWarpFromState(warp_mat, ssm_state);\r\n\tunsigned int n_pts = orig_pts.cols();\r\n\tfor(unsigned int pt_id = 0; pt_id < n_pts; ++pt_id){\r\n\t\twarped_pts(0, pt_id) = warp_mat(0, 0)*orig_pts(0, pt_id) + warp_mat(0, 1)*orig_pts(1, pt_id) +\r\n\t\t\twarp_mat(0, 2);\r\n\t\twarped_pts(1, pt_id) = warp_mat(1, 0)*orig_pts(0, pt_id) + warp_mat(1, 1)*orig_pts(1, pt_id) +\r\n\t\t\twarp_mat(1, 2);\r\n\t}\r\n}\r\nVector6d Affine::geomToState(const Vector6d &geom){\r\n\tdouble s = geom[2], r = geom[4];\r\n\tdouble theta = geom[3], phi = geom[5];\r\n\tdouble cos_theta = cos(theta), sin_theta = sin(theta);\r\n\tdouble cos_phi = cos(phi), sin_phi = sin(phi);\r\n\tdouble ccc = cos_theta*cos_phi*cos_phi;\r\n\tdouble ccs = cos_theta*cos_phi*sin_phi;\r\n\tdouble css = cos_theta*sin_phi*sin_phi;\r\n\tdouble scc = sin_theta*cos_phi*cos_phi;\r\n\tdouble scs = sin_theta*cos_phi*sin_phi;\r\n\tdouble sss = sin_theta*sin_phi*sin_phi;\r\n\tVector6d state;\r\n\tstate[0] = geom[0];\r\n\tstate[1] = geom[1];\r\n\tstate[2] = s*(ccc + scs + r*(css - scs)) - 1;\r\n\tstate[3] = s*(r*(ccs - scc) - ccs - sss);\r\n\tstate[4] = s*(scc - ccs + r*(ccs + sss));\r\n\tstate[5] = s*(r*(ccc + scs) - scs + css) - 1;\r\n\treturn state;\r\n}\r\nVector6d Affine::stateToGeom(const Vector6d &est){\r\n\tMatrix2d A;\r\n\tA << est[2] + 1, est[3], est[4], est[5] + 1;\r\n\tJacobiSVD<Matrix2d> svd(A, ComputeFullU | ComputeFullV);\r\n\tVector2d singular_vals = svd.singularValues();\r\n\tMatrix2d S = singular_vals.asDiagonal();\r\n\tMatrix2d V = svd.matrixV().transpose();\r\n\tMatrix2d U = svd.matrixU();\r\n\tif(U.determinant() < 0){\r\n\t\tMatrix2d U_temp;\r\n\t\tU_temp << U(0, 1), U(0, 0), U(1, 1), U(1, 0);\r\n\t\tU = U_temp;\r\n\t\tMatrix2d V_temp;\r\n\t\tV_temp << V(0, 1), V(0, 0), V(1, 1), V(1, 0);\r\n\t\tV = V_temp;\r\n\t\tMatrix2d S_temp;\r\n\t\tS_temp << S(1, 1), S(1, 0), S(0, 1), S(0, 0);\r\n\t\tS = S_temp;\r\n\t}\r\n\tVector6d q;\r\n\tq[0] = est[0];\r\n\tq[1] = est[1];\r\n\tq[3] = atan2(U(1, 0) * V(0, 0) + U(1, 1) * V(0, 1),\r\n\t\tU(0, 0) * V(0, 0) + U(0, 1) * V(0, 1));\r\n\r\n\tdouble phi = atan2(V(0, 1), V(0, 0));\r\n\tconst double pi = 3.14159265358979323846;\r\n\tif(phi <= -pi / 2){\r\n\t\tdouble cos_phi = cos(-pi / 2);\r\n\t\tdouble sin_phi = sin(-pi / 2);\r\n\t\tMatrix2d R;\r\n\t\tR << cos_phi, -sin_phi, sin_phi, cos_phi;\r\n\t\tV = V * R;\r\n\t\tS = R.transpose()*S*R;\r\n\t}\r\n\r\n\tif(phi >= pi / 2){\r\n\t\tdouble cos_phi = cos(pi / 2);\r\n\t\tdouble sin_phi = sin(pi / 2);\r\n\t\tMatrix2d R;\r\n\t\tR << cos_phi, -sin_phi, sin_phi, cos_phi;\r\n\t\tV = V * R;\r\n\t\tS = R.transpose()*S*R;\r\n\t}\r\n\tq[2] = S(0, 0);\r\n\tq[4] = S(1, 1) / S(0, 0);\r\n\tq[5] = atan2(V(0, 1), V(0, 0));\r\n\treturn q;\r\n}\r\n\r\n\r\nvoid Affine::generatePerturbation(VectorXd &perturbation){\r\n\tassert(perturbation.size() == state_size);\r\n\tif(params.pt_based_sampling){\r\n\t\t//! perturb three canonical points and estimate affine transformation using DLT\r\n\t\tMatrix23d orig_pts, perturbed_pts;\r\n\t\t//! use the bottom left, bottom right and top center points\r\n\t\t//! as canaonical points to add the random perturbations to;\r\n\t\torig_pts.col(0) = init_corners.col(2);\r\n\t\torig_pts.col(1) = init_corners.col(3);\r\n\t\torig_pts.col(2) = (init_corners.col(0) + init_corners.col(1)) / 2.0;\r\n\r\n\t\tif(params.pt_based_sampling == 1){\r\n\t\t\tperturbed_pts = orig_pts;\r\n\t\t\tperturbed_pts(0, 0) += rand_dist[0](rand_gen[0]);\r\n\t\t\tperturbed_pts(1, 0) += rand_dist[1](rand_gen[1]);\r\n\t\t\tperturbed_pts(0, 1) += rand_dist[2](rand_gen[2]);\r\n\t\t\tperturbed_pts(1, 1) += rand_dist[3](rand_gen[3]);\r\n\t\t\tperturbed_pts(0, 2) += rand_dist[4](rand_gen[4]);\r\n\t\t\tperturbed_pts(1, 2) += rand_dist[5](rand_gen[5]);\r\n\t\t} else {\r\n\t\t\t//! different perturbation for x,y coordinates of each point\r\n\t\t\t//! followed by consistent translational perturbation to all corners\r\n\t\t\tMatrix23d rand_d;\r\n\t\t\tfor(unsigned int pt_id = 0; pt_id < 3; ++pt_id){\r\n\t\t\t\trand_d(0, pt_id) = rand_dist[1](rand_gen[1]);\r\n\t\t\t\trand_d(1, pt_id) = rand_dist[1](rand_gen[1]);\r\n\t\t\t}\r\n\t\t\tperturbed_pts = (orig_pts + rand_d).colwise() + Vector2d(rand_dist[0](rand_gen[0]), rand_dist[0](rand_gen[0]));\r\n\t\t}\r\n\t\tMatrix3d aff_warp = utils::computeAffineDLT(orig_pts, perturbed_pts);\r\n\t\tgetStateFromWarp(perturbation, aff_warp);\r\n\t} else{\r\n\t\t//! perform geometric perturbation\r\n\t\tVector6d geom_perturbation;\r\n\t\tfor(unsigned int state_id = 0; state_id < 6; state_id++){\r\n\t\t\tgeom_perturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);\r\n\t\t}\r\n\t\tperturbation = geomToState(geom_perturbation);\r\n\t}\r\n\r\n}\r\n\r\n// use Random Walk model to generate perturbed sample\r\nvoid Affine::additiveRandomWalk(VectorXd &perturbed_state,\r\n\tconst VectorXd &base_state){\r\n\tif(params.pt_based_sampling){\r\n\t\tthrow mtf::utils::FunctonNotImplemented(\"Affine::additiveRandomWalk :: point based sampling is not implemented yet\");\r\n\t} else{\r\n\t\tVector6d geom_perturbation;\r\n\t\tfor(unsigned int state_id = 0; state_id < 6; ++state_id){\r\n\t\t\tgeom_perturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);\r\n\t\t}\r\n\t\tVector6d base_geom = stateToGeom(base_state);\r\n\t\tVector6d perturbed_geom = base_geom + geom_perturbation;\r\n\t\tperturbed_state = geomToState(perturbed_geom);\r\n\t}\r\n}\r\n\r\n// use first order Auto Regressive model to generate perturbed sample\r\nvoid Affine::additiveAutoRegression1(VectorXd &perturbed_state, VectorXd &perturbed_ar,\r\n\tconst VectorXd &base_state, const VectorXd &base_ar, double a){\r\n\tif(params.pt_based_sampling){\r\n\t\tthrow mtf::utils::FunctonNotImplemented(\"Affine::additiveAutoRegression1 :: point based sampling is not implemented yet\");\r\n\t} else{\r\n\t\tVector6d geom_perturbation;\r\n\t\tfor(unsigned int state_id = 0; state_id < 6; ++state_id){\r\n\t\t\tgeom_perturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);\r\n\t\t}\r\n\t\tVector6d base_geom = stateToGeom(base_state);\r\n\t\tVector6d base_ar_geom = stateToGeom(base_ar);\r\n\t\tVector6d perturbed_geom = base_geom + base_ar_geom + geom_perturbation;\r\n\t\tVector6d perturbed_ar_geom = a*(perturbed_geom - base_geom);\r\n\t\tperturbed_state = geomToState(perturbed_geom);\r\n\t\tperturbed_ar = geomToState(perturbed_ar_geom);\r\n\t}\r\n}\r\nvoid Affine::compositionalRandomWalk(VectorXd &perturbed_state,\r\n\tconst VectorXd &base_state){\r\n\tif(params.pt_based_sampling){\r\n\t\tgeneratePerturbation(state_perturbation);\r\n\t\tProjWarpT base_warp, warp_perturbation;\r\n\t\tgetWarpFromState(base_warp, base_state);\r\n\t\tgetWarpFromState(warp_perturbation, state_perturbation);\r\n\t\tProjWarpT perturbed_warp = base_warp * warp_perturbation;\r\n\t\tgetStateFromWarp(perturbed_state, perturbed_warp);\r\n\t} else{\r\n\t\tthrow mtf::utils::FunctonNotImplemented(\"Affine::compositionalRandomWalk :: geometric sampling is not implemented yet\");\r\n\r\n\t}\r\n}\r\n_MTF_END_NAMESPACE\r\n\r\n", "meta": {"hexsha": "b84100e407fd5d6051133003aac150af23cf4a48", "size": 19351, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SSM/src/Affine.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/Affine.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/Affine.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": 34.8039568345, "max_line_length": 125, "alphanum_fraction": 0.679138029, "num_tokens": 6743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708698, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5603140120133887}}
{"text": "#include \"eigen-dense.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nusing namespace Eigen;\n\ntemplate <class T>\nMap< Matrix<T,Dynamic,Dynamic> > matrix(void* p, int r, int c) {\n    return Map< Matrix<T,Dynamic,Dynamic> >((T*)p, r, c);\n}\n\ntemplate <class T>\nMap< Matrix<T,Dynamic,Dynamic> > matrix(const void* p, int r, int c) {\n    return Map< Matrix<T,Dynamic,Dynamic> >((T*)p, r, c);\n}\n\n#define RET const char*\n\n#define API(name,args,call) \\\nextern \"C\" RET eigen_##name args {\\\n    GUARD_START\\\n    switch (code) {\\\n        case 0: return name<T0>call;\\\n        case 1: return name<T1>call;\\\n        case 2: return name<T2>call;\\\n        case 3: return name<T3>call;\\\n    }\\\n    GUARD_END\\\n}\n\n\n#define BINOP(name,op) \\\ntemplate <class T>\\\nRET name(void* p, int r, int c,\\\n    const void* p1, int r1, int c1,\\\n    const void* p2, int r2, int c2)\\\n{\\\n    matrix<T>(p,r,c) = matrix<T>(p1,r1,c1) op matrix<T>(p2,r2,c2);\\\n    return 0;\\\n}\\\nAPI(name, (int code,\\\n    void* p, int r, int c,\\\n    const void* p1, int r1, int c1,\\\n    const void* p2, int r2, int c2), (p,r,c,p1,r1,c1,p2,r2,c2));\n\nBINOP(add,+);\nBINOP(sub,-);\nBINOP(mul,*);\n\n#define PROP(name) \\\nextern \"C\" RET __attribute__ ((noinline)) eigen_##name(int code, void* q, const void* p, int r, int c) {\\\n        GUARD_START\\\n        switch (code) {\\\n            case 0: *(T0*)q = matrix<T0>(p,r,c).name(); break;\\\n            case 1: *(T1*)q = matrix<T1>(p,r,c).name(); break;\\\n            case 2: *(T2*)q = matrix<T2>(p,r,c).name(); break;\\\n            case 3: *(T3*)q = matrix<T3>(p,r,c).name(); break;\\\n        }\\\n        GUARD_END\\\n    }\n\nPROP(norm);\nPROP(squaredNorm);\nPROP(blueNorm);\nPROP(hypotNorm);\nPROP(sum);\nPROP(prod);\nPROP(mean);\nPROP(trace);\nPROP(determinant);\n\n#define UNOP(name) \\\nextern \"C\" RET __attribute__((noinline)) eigen_##name(int code, void* p, int r, int c, const void* p1, int r1, int c1) {\\\n        GUARD_START\\\n        switch (code) {\\\n            case 0: matrix<T0>(p,r,c) = matrix<T0>(p1,r1,c1).name(); break;\\\n            case 1: matrix<T1>(p,r,c) = matrix<T1>(p1,r1,c1).name(); break;\\\n            case 2: matrix<T2>(p,r,c) = matrix<T2>(p1,r1,c1).name(); break;\\\n            case 3: matrix<T3>(p,r,c) = matrix<T3>(p1,r1,c1).name(); break;\\\n        }\\\n        GUARD_END\\\n    }\n\nUNOP(inverse);\nUNOP(adjoint);\nUNOP(conjugate);\nUNOP(diagonal);\nUNOP(transpose);\n\nextern \"C\" RET eigen_normalize(int code, void* p, int r, int c)\n{\n    GUARD_START\n    switch (code) {\n        case 0: matrix<T0>(p,r,c).normalize(); break;\n        case 1: matrix<T1>(p,r,c).normalize(); break;\n        case 2: matrix<T2>(p,r,c).normalize(); break;\n        case 3: matrix<T3>(p,r,c).normalize(); break;\n    }\n    GUARD_END\n}\n\nextern \"C\" RET eigen_random(int code, void* p, int r, int c)\n{\n    GUARD_START\n    switch (code) {\n        case 0: matrix<T0>(p,r,c) = MatrixXf::Random(r,c); break;\n        case 1: matrix<T1>(p,r,c) = MatrixXd::Random(r,c); break;\n        case 2: matrix<T2>(p,r,c) = MatrixXcf::Random(r,c); break;\n        case 3: matrix<T3>(p,r,c) = MatrixXcd::Random(r,c); break;\n    }\n    GUARD_END\n}\n\nextern \"C\" RET eigen_identity(int code, void* p, int r, int c)\n{\n    GUARD_START\n    switch (code) {\n        case 0: matrix<T0>(p,r,c) = MatrixXf::Identity(r,c); break;\n        case 1: matrix<T1>(p,r,c) = MatrixXd::Identity(r,c); break;\n        case 2: matrix<T2>(p,r,c) = MatrixXcf::Identity(r,c); break;\n        case 3: matrix<T3>(p,r,c) = MatrixXcd::Identity(r,c); break;\n    }\n    GUARD_END\n}\n\n", "meta": {"hexsha": "cb2e4214443e225788dbb7a6261a711777423c67", "size": 3472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/eigen-dense.cpp", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "cbits/eigen-dense.cpp", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "cbits/eigen-dense.cpp", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 27.5555555556, "max_line_length": 121, "alphanum_fraction": 0.573156682, "num_tokens": 1167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5603140026985802}}
{"text": "#include \"PhysicsTools/Utilities/interface/Likelihood.h\"\n#include \"PhysicsTools/Utilities/interface/BreitWigner.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuitCommands.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuit.h\"\n#include \"PhysicsTools/Utilities/interface/Parameter.h\"\n#include \"PhysicsTools/Utilities/interface/rootTf1.h\"\n#include \"PhysicsTools/Utilities/interface/rootPlot.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TF1.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n#include <boost/shared_ptr.hpp>\n#include <iostream>\n#include \"PhysicsTools/Utilities/interface/Operations.h\"\n//using namespace std;\n//using namespace boost;\n\nint main() {\n  gROOT->SetStyle(\"Plain\");\n  typedef funct::BreitWigner PDF;\n  typedef std::vector<double> Sample;\n  typedef funct::Product<funct::Parameter, PDF>::type FitFunction;\n  typedef fit::Likelihood<Sample, FitFunction, funct::Parameter> Likelihood;\n  try {\n    fit::RootMinuitCommands<Likelihood> commands(\"PhysicsTools/Utilities/test/testZMassFitLikelihood.txt\");\n\n    const char* kYield = \"Yield\";\n    const char* kMass = \"Mass\";\n    const char* kGamma = \"Gamma\";\n\n    funct::Parameter yield(kYield, commands.par(kYield));\n    funct::Parameter mass(kMass, commands.par(kMass));\n    funct::Parameter gamma(kGamma, commands.par(kGamma));\n    funct::BreitWigner bw(mass, gamma);\n\n    PDF pdf = bw;\n    FitFunction f = yield * pdf;\n    TF1 startFun = root::tf1(\"startFun\", f, 0, 200, yield, mass, gamma);\n    TH1D histo(\"histo\", \"Z mass (GeV/c)\", 200, 0, 200);\n    Sample sample;\n    sample.reserve(yield);\n    for (unsigned int i = 0; i < yield; ++i) {\n      double m = startFun.GetRandom();\n      histo.Fill(m);\n      sample.push_back(m);\n    }\n    TCanvas canvas;\n    startFun.Draw();\n    canvas.SaveAs(\"breitWigner.eps\");\n    histo.Draw();\n    canvas.SaveAs(\"breitWignerHisto.eps\");\n    startFun.Draw(\"same\");\n    canvas.SaveAs(\"breitWignerHistoFun.eps\");\n    histo.Draw(\"e\");\n    startFun.Draw(\"same\");\n\n    Likelihood like(sample, f, yield);\n    fit::RootMinuit<Likelihood> minuit(like, true);\n    commands.add(minuit, yield);\n    commands.add(minuit, mass);\n    commands.add(minuit, gamma);\n    commands.run(minuit);\n    ROOT::Math::SMatrix<double, 3, 3, ROOT::Math::MatRepSym<double, 3> > err;\n    minuit.getErrorMatrix(err);\n    std::cout << \"error matrix:\" << std::endl;\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = 0; j < 3; ++j) {\n        std::cout << err(i, j) << \"\\t\";\n      }\n      std::cout << std::endl;\n    }\n    root::plot<FitFunction>(\"breitWignerHistoFunFit.eps\", histo, f, 80, 120, yield, mass, gamma);\n  } catch (std::exception& err) {\n    std::cerr << \"Exception caught:\\n\" << err.what() << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "73d473dae5caaf4c669b926f13199d92eb5815ee", "size": 2732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PhysicsTools/Utilities/test/testZMassFitExtLikelihood.cpp", "max_stars_repo_name": "NTrevisani/cmssw", "max_stars_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-08T11:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-08T11:39:24.000Z", "max_issues_repo_path": "PhysicsTools/Utilities/test/testZMassFitExtLikelihood.cpp", "max_issues_repo_name": "NTrevisani/cmssw", "max_issues_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2016-07-17T02:34:54.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-13T07:58:37.000Z", "max_forks_repo_path": "PhysicsTools/Utilities/test/testZMassFitExtLikelihood.cpp", "max_forks_repo_name": "NTrevisani/cmssw", "max_forks_repo_head_hexsha": "a212a27526f34eb9507cf8b875c93896e6544781", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-27T08:33:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-14T10:52:30.000Z", "avg_line_length": 33.7283950617, "max_line_length": 107, "alphanum_fraction": 0.6691068814, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5602705356628269}}
{"text": "﻿/*\n\tSatellite Attitude Dynamics Stepper\n\n\t@author\t\t:\tsiddharth deore\n\t@licence\t:\tMIT\n*/\n\n#include \"Satellite.h\"\n#include <iostream>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include \"ode_wrapper.h\"\n\n#include <fstream>\n#include <windows.h>\nHANDLE hOut= GetStdHandle(STD_OUTPUT_HANDLE);;\nvoid clearScreen()\n{\n\tCOORD Position;\n\n\tPosition.X = 0;\n\tPosition.Y = 0;\n\tSetConsoleCursorPosition(hOut, Position);\n}\n\n// set bool visible = 0 - invisible, bool visible = 1 - visible\nvoid setcursor(bool visible, DWORD size) \n{\n\tif (size == 0)\n\t{\n\t\t// default cursor size Changing to numbers from 1 to 20, decreases cursor width\n\t\tsize = 20;\t\n\t}\n\tCONSOLE_CURSOR_INFO lpCursor;\n\tlpCursor.bVisible = visible;\n\tlpCursor.dwSize = size;\n\tSetConsoleCursorInfo(hOut, &lpCursor);\n}\nnamespace odeint = boost::numeric::odeint;\n\n// Static variables common to all instance\ndouble Satellite::Ixx = 1.0;\ndouble Satellite::Iyy = 1.0;\ndouble Satellite::Izz = 1.0;\n\ndouble Satellite::Kp = 0.0;\ndouble Satellite::Kd = 1.0;\n\ndouble Satellite::qd[4] = { 1.0,0.0,0.0,0.0 };\n\n\nvoid Satellite::Satelliite() {\n\tstate_type X = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0  } }; // initial conditions\n}\n\nint Satellite::setQuaternion(double q0, double q1, double q2, double q3) {\n\tthis->X[0] = q0;\n\tthis->X[1] = q1;\n\tthis->X[2] = q2;\n\tthis->X[3] = q3;\n\treturn 0;\n}\n\nint Satellite::setAngulerVeolcities(double wx, double wy, double wz) {\n\tthis->X[4] = wx;\n\tthis->X[5] = wy;\n\tthis->X[6] = wz;\n\treturn 0;\n}\n\nint Satellite::setState(double q0, double q1, double q2, double q3, double wx, double wy, double wz) {\n\tsetQuaternion(q0, q1, q2, q3);\n\tsetAngulerVeolcities(wx, wy, wz);\n\treturn 0;\n}\n\nint Satellite::getState(double& q0, double& q1, double& q2, double& q3, double& wx, double& wy, double& wz) {\n\tq0 = this->X[0];\n\tq1 = this->X[1];\n\tq2 = this->X[2];\n\tq3 = this->X[3];\n\twx = this->X[5];\n\twy = this->X[6];\n\twz = this->X[7];\n\treturn 0;\n}\n\nvoid Satellite::dynamics(const state_type& x, state_type& dxdt, const double t) {\n\tdouble q0 = x[0];\n\tdouble q1 = x[1];\n\tdouble q2 = x[2];\n\tdouble q3 = x[3];\n\tdouble norm = normalizeQuaternions(q0, q1, q2, q3);\n\tdxdt[0] = 0.5 * (q1 * x[6] - q2 * x[5] + q3 * x[4]);\n\tdxdt[1] = 0.5 * (q2 * x[4] - q0 * x[6] + q3 * x[5]);\n\tdxdt[2] = 0.5 * (q0 * x[5] - q1 * x[4] + q3 * x[6]);\n\tdxdt[3] = 0.5 * (-q0 * x[4] - q1 * x[5] - q2 * x[6]);\n\t\n\tqe[0] = q0 * this->qd[3] + q1 * this->qd[2] - q2 * this->qd[1] - q3 * this->qd[0];\n\tqe[1] = q2 * this->qd[0] - q0 * this->qd[2] + q1 * this->qd[3] - q3 * this->qd[1];\n\tqe[2] = q0 * this->qd[1] - q1 * this->qd[0] + q2 * this->qd[3] - q3 * this->qd[2];\n\tqe[3] = q0 * this->qd[0] + q1 * this->qd[1] + q2 * this->qd[2] + q3 * this->qd[3];\n\tdouble PD[3] = {\n\t\t\t\t\tthis.Kp * qe[0] * qe[3] + this.Kd * x[4],\n\t\t\t\t\tthis.Kp * qe[1] * qe[3] + this.Kd * x[5],\n\t\t\t\t\tthis.Kp * qe[2] * qe[3] + this.Kd * x[6]\n\t\t\t\t};\n\n\tdxdt[4] = ((this->Iyy - this->Izz) * x[5] * x[6] - PD[0]) / this->Ixx;\n\tdxdt[5] = ((this->Izz - this->Ixx) * x[6] * x[4] - PD[1]) / this->Iyy;\n\tdxdt[6] = ((this->Ixx - this->Iyy) * x[4] * x[5] - PD[2]) / this->Izz;\n}\n\ndouble Satellite::normalizeQuaternions(double& _q0, double& _q1, double& _q2, double& _q3)\n{\n\tdouble norm = std::sqrt(_q0 * _q0 + _q1 * _q1 + _q2 * _q2 + _q3 * _q3);\n\t_q0 /= norm;\n\t_q1 /= norm;\n\t_q2 /= norm;\n\t_q3 /= norm;\n\treturn norm;\n}\n\n\nint Satellite::step(double final_time, double dt, state_type& new_state)\n{\n\todeint::integrate(\n\t\tmake_ode_wrapper(Satellite(), &Satellite::dynamics), // ODE funtion\n\t\tX,\t\t\t\t// Initial state\n\t\t0.0,\t\t\t// initial time\n\t\tfinal_time,\t\t// final time\n\t\tdt,\t\t\t\t// timestep\n\t\tmake_observer_wrapper(Satellite(), &Satellite::write_state)// observer function\n\t);\n\n\t// return value to caller\n\tnew_state = X;\n\treturn 0;\n}\n\nvoid Satellite::setTargetQuaternion(double q0, double q1, double q2, double q3)\n{\n\tthis->qd[0] = q0;\n\tthis->qd[1] = q1;\n\tthis->qd[2] = q2;\n\tthis->qd[3] = q3;\n}\n\nvoid Satellite::write_state(const state_type& state, const double t) {\n\t\n\tclearScreen(); // clear screen \n\tsetcursor(0, 1); // Hide cursor\n\n\tstd::cout << char(218) << std::string(83, char(196))<< char(191) << std::endl;\n\tstd::cout<<\"|     time    |    q0   |    q1   |    q2   |    q3   |    wx   |    wy   |    wz   |\" << std::endl;\n\tstd::cout << char(195) << std::string(83, char(196)) << char(180) << std::endl;\n\tstd::cout << \"|\" << std::setw(12) << std::fixed << std::setprecision(4) << t << \" |\";\n\tstd::cout << std::setw(8) << state[0] << \" |\";\n\tstd::cout << std::setw(8) << state[1] << \" |\";\n\tstd::cout << std::setw(8) << state[2] << \" |\";\n\tstd::cout << std::setw(8) << state[3] << \" |\";\n\tstd::cout << std::setw(8) << state[4] << \" |\";\n\tstd::cout << std::setw(8) << state[5] << \" |\";\n\tstd::cout << std::setw(8) << state[6] << \" |\" << std::endl;\n\tstd::cout << char(192) << std::string(83, char(196)) << char(217) << std::endl;\n\t\n\t//Progress bar\n\tstd::cout << std::string(int(t / 10000 * 85), char(178)) << std::string(int(85 - t / 10000 * 85), char(176)) << std::endl;\n\t\n\t// write to file\n\tstd::string s =\n\t\tstd::to_string(t) +\t\t   \", \" +\n\t\tstd::to_string(state[0]) + \", \" +\n\t\tstd::to_string(state[1]) + \", \" +\n\t\tstd::to_string(state[2]) + \", \" +\n\t\tstd::to_string(state[3]) + \", \" +\n\t\tstd::to_string(state[4]) + \", \" +\n\t\tstd::to_string(state[5]) + \", \" +\n\t\tstd::to_string(state[6]) + \"\\n\";\n\tstd::ofstream outfile;\n\n\toutfile.open(\"results.csv\", std::ios_base::app); // append instead of overwrite\n\toutfile << s;\n\toutfile.close();\n\t//\n\n}\n\nvoid Satellite::setInnertia(double Ix, double Iy, double Iz) {\n\tthis->Ixx = Ix;\n\tthis->Iyy = Iy;\n\tthis->Izz = Iz;\n}\n\nvoid Satellite::setControllerGains(double Kp, double Kd)\n{\n\tthis->Kp = Kp;\n\tthis->Kd = Kd;\n}\n", "meta": {"hexsha": "c288e06241459e0c3fd049bb2e72188bebaf6b06", "size": 5626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Satellite.cpp", "max_stars_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_stars_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Satellite.cpp", "max_issues_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_issues_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Satellite.cpp", "max_forks_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_forks_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_forks_repo_licenses": ["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.13, "max_line_length": 123, "alphanum_fraction": 0.5844294348, "num_tokens": 2154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324587033253, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5602705300967472}}
{"text": "// Copyright Abel Sinkovics (abel@sinkovics.hu) 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <mpllibs/metamonad/lazy.hpp>\n#include <mpllibs/metamonad/metafunction.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/eval_if.hpp>\n\n#include <iostream>\n\nusing boost::mpl::plus;\nusing boost::mpl::minus;\nusing boost::mpl::less;\nusing boost::mpl::eval_if;\nusing boost::mpl::int_;\n\nusing mpllibs::metamonad::lazy;\n\n// Without lazy\n///////////////\n\ntemplate <class N>\nstruct fib_without_lazy;\n\nMPLLIBS_METAFUNCTION(fib_without_lazy_helper, (N))\n((\n  plus<\n    typename fib_without_lazy<typename minus<N, int_<1> >::type>::type,\n    typename fib_without_lazy<typename minus<N, int_<2> >::type>::type\n  >\n));\n\n\nMPLLIBS_METAFUNCTION(fib_without_lazy, (N))\n((\n  eval_if<\n    typename less<N, int_<2> >::type,\n    int_<1>,\n    fib_without_lazy_helper<N>\n  >\n));\n\n// With lazy\n////////////\n\nMPLLIBS_METAFUNCTION(fib, (N))\n((\n  eval_if<\n    typename less<N, int_<2> >::type,\n    int_<1>,\n    lazy<plus<fib<minus<N, int_<1> > >, fib<minus<N, int_<2> > > > >\n  >\n));\n\n///////////\n\nint main()\n{\n  using std::endl;\n\n  std::cout\n    << \"With lazy: \" << endl\n    << \"fib(0) == \" << fib_without_lazy<int_<0> >::type::value << endl\n    << \"fib(1) == \" << fib_without_lazy<int_<1> >::type::value << endl\n    << \"fib(2) == \" << fib_without_lazy<int_<2> >::type::value << endl\n    << \"fib(3) == \" << fib_without_lazy<int_<3> >::type::value << endl\n    << \"fib(4) == \" << fib_without_lazy<int_<4> >::type::value << endl\n    << \"fib(5) == \" << fib_without_lazy<int_<5> >::type::value << endl\n    << endl\n    << \"With lazy: \" << endl\n    << \"fib(0) == \" << fib<int_<0> >::type::value << endl\n    << \"fib(1) == \" << fib<int_<1> >::type::value << endl\n    << \"fib(2) == \" << fib<int_<2> >::type::value << endl\n    << \"fib(3) == \" << fib<int_<3> >::type::value << endl\n    << \"fib(4) == \" << fib<int_<4> >::type::value << endl\n    << \"fib(5) == \" << fib<int_<5> >::type::value << endl;\n}\n\n", "meta": {"hexsha": "9a7762905efa422c40137900065c04e7496b2b21", "size": 2190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/metamonad/example/fib/main.cpp", "max_stars_repo_name": "sabel83/mpllibs", "max_stars_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-01-15T09:05:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T15:49:31.000Z", "max_issues_repo_path": "libs/metamonad/example/fib/main.cpp", "max_issues_repo_name": "sabel83/mpllibs", "max_issues_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-06-18T19:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-13T19:49:51.000Z", "max_forks_repo_path": "libs/metamonad/example/fib/main.cpp", "max_forks_repo_name": "sabel83/mpllibs", "max_forks_repo_head_hexsha": "8e245aedcf658fe77bb29537aeba1d4e1a619a19", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-10T08:18:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T07:17:57.000Z", "avg_line_length": 25.7647058824, "max_line_length": 71, "alphanum_fraction": 0.5913242009, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.5602705300018641}}
{"text": "//==================================================================================================\n/*\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n*/\n//==================================================================================================\n#pragma once\n\n#include <eve/detail/overload.hpp>\n#include <eve/module/core.hpp>\n#include <eve/module/math.hpp>\n#include <eve/module/complex.hpp>\n#include <eve/module/complex/regular/traits.hpp>\n#include <boost/math/complex/atanh.hpp>\nnamespace eve\n{\n\n  namespace detail\n  {\n    template<typename Z>\n    EVE_FORCEINLINE auto complex_unary_dispatch( eve::tag::atanh_, Z const& a0) noexcept\n    {\n      // This implementation is a simd (i.e. no branch) transcription and adaptation of the\n      // boost_math code which itself is a transcription of the pseudo-code in:\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      auto [a0r, a0i] = a0;\n      auto realinf = is_eqz(a0i) && is_infinite(a0r);\n      using rtype = decltype(a0r);\n      const rtype alpha_crossover(0.3);\n      auto  ltzra0 = is_ltz(a0r);\n      auto  ltzia0 = is_ltz(a0i);\n      auto s_min = eve::sqrtsmallestposval(as(a0r))*2;\n      auto s_max = eve::sqrtvalmax(as(a0r))/2;\n      rtype const two = rtype(2);\n      rtype inf =  eve::inf(as(a0r));\n      rtype x = eve::abs(a0r);\n      rtype y = eve::abs(a0i);\n      rtype r = zero(as(a0r));\n      rtype i = zero(as(a0r));\n      auto gtxmax = (x > s_max);\n      auto ltxmin = (x < s_min);\n      auto gtymax = (y > s_max);\n      auto ltymin = (y < s_min);\n      rtype xx = eve::sqr(x);\n      rtype yy = eve::sqr(y);\n      rtype sqrabs = xx + yy;\n\n      auto not_in_safe_zone = ((gtxmax || ltxmin) || (gtymax || ltymin));\n      if(eve::any(not_in_safe_zone))\n      {\n        //treat underflow or overflow\n        // one or both of x and y are small, calculate divisor carefully:\n        rtype div = one(as(a0r));\n        div += eve::if_else(ltxmin, xx, zero);\n        div += eve::if_else(ltxmin, yy, zero);\n\n        rtype alpha = x/div;\n        alpha += alpha;\n\n        auto test =  gtymax;\n        // big y, medium x, divide through by y:\n        rtype tmp_alpha = (two*x/y) / (y + xx/y);\n        // small x and y, whatever alpha is, it's too small to calculate:\n        tmp_alpha = eve::if_else(x > one(as(a0r)), tmp_alpha, zero);\n        alpha = eve::if_else(test && (x > one(as(a0r))), tmp_alpha, alpha);\n\n        test =  eve::logical_andnot(gtxmax, test);\n\n        // big x small y, as above but neglect y^2/x:\n        tmp_alpha =  two/x;\n        // big x: divide through by x:\n        tmp_alpha =  eve::if_else((y > one(as(a0r))),  two / (x + y*y/x), tmp_alpha);\n        // big x and y: divide alpha through by x*y:\n        tmp_alpha =  eve::if_else(gtymax, (two/y) / (x/y + y/x), tmp_alpha);\n        // x or y are infinite: the result is 0\n        tmp_alpha = eve::if_else((y == inf) || (x == inf), zero, tmp_alpha);\n\n        alpha = eve::if_else(test, tmp_alpha, alpha);\n        r = eve::if_else((alpha < alpha_crossover),\n                        eve::log1p(alpha) - eve::log1p(-alpha),\n                         eve::log(inc(two*x + xx)) - eve::log(sqr(dec(x)))\n                       );\n        test = (x == one(as(a0r))) && ltymin;\n        r = eve::if_else(test, -(two*(eve::log(y) - eve::log_2(as(a0r)))), r);\n        r *= rtype(0.25);\n        //compute the imag part\n        // y^2 is negligible:\n        i =  eve::atan2(two*y, eve::oneminus(xx));\n        i =  if_else(gtymax || gtxmax, pi(as(a0r)), i);\n        rtype tmp_i = eve::if_else(ltymin, atan2(two*y, one(as(a0r))),\n                                  eve::atan2(two*y, eve::oneminus(yy)));\n        i =  if_else(ltxmin, tmp_i, i);\n      }\n      auto test0 = (inf == x) && (inf == y);\n      if(eve::any(test0))\n      {\n        //inf x, inf y\n        r = eve::if_else(test0, zero, r);\n        i = eve::if_else(test0, pi(as(a0r)), r);\n      }\n      auto test = eve::is_nan(a0);\n\n      if(eve::any(test))\n      {\n        //nan x, inf y\n        r = eve::if_else(eve::is_nan(x) && (y == inf), zero, r);\n        i = eve::if_else(eve::is_nan(x) && (y == inf), pi(as(a0r)), r);\n\n        r = eve::if_else(is_nan(y) && (x == inf), zero, r);\n        i = eve::if_else(is_nan(y) && (x == inf), y, i);\n\n        r = eve::if_else(is_nan(y) && eve::is_eqz(x), zero, r);\n        i = eve::if_else(is_nan(y) && is_eqz(x), allbits, i);\n      }\n      //compute for safe zone\n      // the real part is given by:\n      //\n      // eve::real(atanh(z)) == log((1 + x^2 + y^2 + 2x) / (1 + x^2 + y^2 - 2x))\n      //\n      // however, when x is either large (x > 1/e) or very small\n      // (x < e) then this effectively simplifies\n      // to log(1), leading to wildly inaccurate results.\n      // by dividing the above (top and bottom) by (1 + x^2 + y^2) we get:\n      //\n      // eve::real(atanh(z)) == log((1 + (2x / (1 + x^2 + y^2))) / (1 - (-2x / (1 + x^2 + y^2))))\n      //\n      // which is much more sensitive to the value of x, when x is not near 1\n      // (remember we can compute log(1+x) for small x very accurately).\n      //\n      // the cross-over from one method to the other has to be determined\n      // experimentally, the value used below appears correct to within a\n      // factor of 2 (and there are larger errors from other parts\n      // of the input domain anyway).\n      //\n      rtype alpha = x*two / (eve::inc(sqrabs));\n      rtype sqrxm1 = eve::sqr(eve::dec(x));\n      rtype tmp_r = eve::if_else((alpha < alpha_crossover),\n                                eve::log1p(alpha) - log1p(-alpha),\n                                eve::log1p(x+x + sqrabs) - eve::log(sqrxm1 + yy)\n                                )*rtype(0.25);\n      r = eve::if_else(not_in_safe_zone, r, tmp_r);\n\n      // compute the imag part\n      i = eve::if_else(not_in_safe_zone,\n                      i,\n                      eve::atan2(y+y, (oneminus(sqrabs)))\n                     )*half(as(a0r));\n\n      r = eve::if_else( ltzra0,-r, r);\n      i = eve::if_else(is_infinite(y), pio_2(as(a0r))*sign(y), i);\n      i = eve::if_else( ltzia0,-i, i);\n      r = if_else(realinf, zero(as(a0r)), r);\n      i = if_else(realinf, -sign(a0r)*pio_2(as(a0r)), i);\n      return  Z{r, i};\n    }\n  }\n}\n", "meta": {"hexsha": "a67085e26632067d80b6b08bd4b8392120788ab7", "size": 6655, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/eve/module/complex/regular/detail/atanh.hpp", "max_stars_repo_name": "mshojatalab/eve", "max_stars_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_stars_repo_licenses": ["MIT"], "max_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/complex/regular/detail/atanh.hpp", "max_issues_repo_name": "mshojatalab/eve", "max_issues_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_issues_repo_licenses": ["MIT"], "max_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/complex/regular/detail/atanh.hpp", "max_forks_repo_name": "mshojatalab/eve", "max_forks_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_forks_repo_licenses": ["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.3786982249, "max_line_length": 100, "alphanum_fraction": 0.5232156273, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.560249334254359}}
{"text": "/*\n * demo.cpp\n *\n *  Created on: 25.09.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/mpi.h>\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria.h>\n\n#include <base/ConstantMesh.h>\n#include <base/DiscretizedFunction.h>\n#include <base/Util.h>\n#include <forward/WaveEquation.h>\n\n#include <stddef.h>\n#include <ctgmath>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nusing namespace dealii;\nusing namespace wavepi;\nusing namespace wavepi::forward;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nclass DemoF : public Function<dim> {\n public:\n  static const Point<dim> center;\n\n  double value(const Point<dim> &p, const unsigned int component = 0) const {\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n    if (p.distance(center) < 0.75)\n      return std::sin(this->get_time() * 2 * numbers::PI);\n    else\n      return 0.0;\n  }\n};\n\ntemplate <int dim>\nclass DemoC : public Function<dim> {\n public:\n  static const Point<dim> center;\n\n  virtual ~DemoC() = default;\n\n  virtual double value(const Point<dim> &p, const unsigned int component = 0) const {\n    Assert(component == 0, ExcIndexRange(component, 0, 1));\n    if (p.distance(center) < 2)\n      return 1.0 / (4.0 + (1.0 - std::pow(p.distance(center) / 2, 4)) * 12.0 *\n                              std::pow(std::sin(this->get_time() / 2.5 * numbers::PI), 2));\n    else\n      return 1.0 / (4.0 + 0.0);\n  }\n};\n\ntemplate <int dim>\nclass DemoWaveSpeed : public Function<dim> {\n public:\n  DemoC<dim> base;\n\n  virtual ~DemoWaveSpeed() = default;\n\n  virtual double value(const Point<dim> &p, const unsigned int component = 0) const {\n    return 1.0 / std::sqrt(base.value(p, component));\n  }\n\n  virtual void set_time(double t) {\n    Function<dim>::set_time(t);\n    base.set_time(t);\n  }\n};\n\ntemplate <>\nconst Point<2> DemoF<2>::center = Point<2>(1.0, 0.0);\ntemplate <>\nconst Point<2> DemoC<2>::center = Point<2>(0.0, 2.5);\n\ntemplate <int dim>\nvoid demo() {\n  std::ofstream logout(\"wavepi_demo.log\", std::ios_base::trunc);\n  deallog.attach(logout);\n  deallog.depth_console(3);\n  deallog.depth_file(100);\n  deallog.precision(3);\n  deallog.pop();\n\n  auto triangulation = std::make_shared<Triangulation<dim>>();\n  GridGenerator::hyper_cube(*triangulation, -5.0, 5.0);\n  Util::set_all_boundary_ids(*triangulation, 0);\n  triangulation->refine_global(6);\n\n  double t_end = 10;\n  int steps    = t_end * 64;\n\n  double t_start = 0.0, dt = t_end / steps;\n  std::vector<double> times;\n\n  for (size_t i = 0; t_start + i * dt <= t_end; i++)\n    times.push_back(t_start + i * dt);\n\n  FE_Q<dim> fe(1);\n  Quadrature<dim> quad = QGauss<dim>(3);\n\n  auto mesh = std::make_shared<ConstantMesh<dim>>(times, fe, quad, triangulation);\n  WaveEquation<dim> wave_eq(mesh);\n\n  DemoC<dim> demo_c_cont;\n  auto demo_c = std::make_shared<DiscretizedFunction<dim>>(mesh, demo_c_cont);\n  wave_eq.set_param_c(demo_c);\n\n  auto sol = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(std::make_shared<DemoF<dim>>()));\n  sol.write_pvd(\"./\", \"demo_u\", \"u\");\n  demo_c->write_pvd(\"./\", \"demo_c\", \"c\");\n\n  DemoWaveSpeed<dim> demo_wave_speed_cont;\n  auto demo_wave_speed = std::make_shared<DiscretizedFunction<dim>>(mesh, demo_wave_speed_cont);\n  demo_wave_speed->write_pvd(\"./\", \"demo_wave_speed\", \"wave speed\");\n}\n\nint main(int argc, char *argv[]) {\n  Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv);\n\n  try {\n    demo<2>();\n  } catch (std::exception &exc) {\n    std::cerr << \"Exception on processing: \" << exc.what() << std::endl;\n    return 1;\n  } catch (...) {\n    std::cerr << \"Unknown exception!\" << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "3e49329d4501e8fdb635dc42fa0d5907a2374203", "size": 3926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/demo.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": "src/demo.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": "src/demo.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.527027027, "max_line_length": 97, "alphanum_fraction": 0.6632705043, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5602493005009832}}
{"text": "#include \"panel.h\"\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\nnamespace poflow {\n\nvoid PanelSolver::init_arrays() {\n  num_points_ = num_elements_ + 1;\n  FN = Eigen::MatrixXd::Zero(num_elements_, num_elements_);\n  FT = Eigen::MatrixXd::Zero(num_elements_, num_elements_);\n  R = Eigen::VectorXd::Zero(num_elements_);\n  source_density_ = Eigen::VectorXd::Zero(num_elements_);\n}\n\nvoid PanelSolver::build() { init_arrays(); }\n\nvoid PanelSolver::build_equation_system(double vx, double vy) {\n  double pi = 3.14159;\n  for (int k = 0; k < num_elements_; ++k) {\n    R(k) = vx * panels_[k].si - vy * panels_[k].ci;\n    auto kth_panel = panels_[k];\n    for (int j = 0; j < num_elements_; ++j) {\n      auto jth_panel = panels_[j];\n      if (k == j) {\n        FN(k, j) = 2.0 * pi;\n        FT(k, j) = 0.0;\n      } else {\n        double dyj = jth_panel.si * jth_panel.ds;\n        double dxj = jth_panel.ci * jth_panel.ds;\n        double sph = jth_panel.ds / 2.0;\n\n        double xd = kth_panel.xc - jth_panel.xc;\n        double yd = kth_panel.yc - jth_panel.yc;\n        double rkj = std::sqrt(xd * xd + yd * yd);\n\n        double bkj = std::atan2(yd, xd);\n        double alj = std::atan2(dyj, dxj);\n        double gkj = alj - bkj;\n\n        double zik = rkj * std::cos(gkj);\n        double etk = -rkj * std::sin(gkj);\n\n        double r1s = std::pow((zik + sph), 2.0) + std::pow(etk, 2.0);\n        double r2s = std::pow((zik - sph), 2.0) + std::pow(etk, 2.0);\n        double qt = std::log(r1s / r2s);\n\n        double den = zik * zik + etk * etk - sph * sph;\n        double gnm = etk * jth_panel.ds;\n        double qn = 2.0 * std::atan2(gnm, den);\n\n        double ukj = qt * jth_panel.ci - qn * jth_panel.si;\n        double vkj = qt * jth_panel.si + qn * jth_panel.ci;\n\n        FN(k, j) = -ukj * kth_panel.si + vkj * kth_panel.ci;\n        FT(k, j) = ukj * kth_panel.ci + vkj * kth_panel.si;\n      }\n    }\n  }\n}\n\nstd::map<std::string, Eigen::VectorXd>\nPanelSolver::compute_surface_results(double vx, double vy) {\n  build_equation_system(vx, vy);\n  source_density_ = FN.colPivHouseholderQr().solve(R);\n\n  int n = num_elements_;\n  Eigen::VectorXd R(n);\n  Eigen::VectorXd qt(n);\n  Eigen::VectorXd qn(n);\n  Eigen::VectorXd u(n);\n  Eigen::VectorXd v(n);\n  Eigen::VectorXd p(n);\n  Eigen::VectorXd xc(n);\n  Eigen::VectorXd yc(n);\n  Eigen::VectorXd theta(n);\n\n  auto qts = FT * source_density_;\n  auto qns = FN * source_density_;\n\n  for (int i = 0; i < n; ++i) {\n    auto &panel = panels_[i];\n    xc[i] = panel.xc;\n    yc[i] = panel.yc;\n    theta[i] = std::atan2(yc[i], xc[i]);\n    qt[i] = qts[i] + vy * panel.si + vx * panel.ci;\n    qn[i] = qns[i] + vy * panel.ci - vx * panel.si;\n    u[i] = vx - qns[i] * panel.si + qts[i] * panel.ci;\n    v[i] = vy + qns[i] * panel.ci + qts[i] * panel.si;\n    p[i] = 1.0 - std::pow(u[i], 2.0) - std::pow(v[i], 2.0);\n  }\n  std::map<std::string, Eigen::VectorXd> results;\n  results[\"xc\"] = xc;\n  results[\"yc\"] = yc;\n  results[\"theta\"] = theta;\n  results[\"qt\"] = qt;\n  results[\"qn\"] = qn;\n  results[\"u\"] = u;\n  results[\"v\"] = v;\n  results[\"p\"] = p;\n\n  return results;\n}\n\n} // namespace poflow\n", "meta": {"hexsha": "23418f9c2fe94d4538362cedc271626de08f780b", "size": 3101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/panel.cpp", "max_stars_repo_name": "jvleta/poflow", "max_stars_repo_head_hexsha": "53e6e9d61ddcb3d5ec0ac3df2a930d87d37e4955", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/panel.cpp", "max_issues_repo_name": "jvleta/poflow", "max_issues_repo_head_hexsha": "53e6e9d61ddcb3d5ec0ac3df2a930d87d37e4955", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-28T22:59:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T23:02:16.000Z", "max_forks_repo_path": "src/core/panel.cpp", "max_forks_repo_name": "jvleta/poflow", "max_forks_repo_head_hexsha": "53e6e9d61ddcb3d5ec0ac3df2a930d87d37e4955", "max_forks_repo_licenses": ["BSD-3-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.9813084112, "max_line_length": 69, "alphanum_fraction": 0.571751048, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5602179405954433}}
{"text": "/** \\file\n * Support for Eigen linear algebra library in Chaiscript.\n *\n * \\author Truong X. Nghiem (xuan.nghiem@epfl.ch)\n */\n\n#ifndef _CHAISCRIPT_EXTRAS_EIGEN_H\n#define _CHAISCRIPT_EXTRAS_EIGEN_H\n\n#include <vector>\n#include <Eigen/Dense>\n#include <chaiscript/chaiscript.hpp>\n\nnamespace chaiscript {\n    namespace extras {\n        namespace eigenlinalg {\n            typedef std::vector<chaiscript::Boxed_Value> TChaiVector;   ///< The C++ type of a Chaiscript's vector object\n            \n            Eigen::IOFormat EigenMatlabFmt(Eigen::StreamPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n            \n            // Register with Chaiscript a new Eigen vector type\n            template<typename CLS, typename Scalar>\n            ModulePtr eigen_vector_type(const char* CLSNAME, ModulePtr m = std::make_shared<Module>()) {\n                //// 1.1. Type and Construction\n                m->add(user_type<CLS>(), CLSNAME);\n                m->add(constructor<CLS ()>(), CLSNAME);\n                m->add(constructor<CLS (typename CLS::Index)>(), CLSNAME);\n                m->add(bootstrap::copy_constructor<CLS>(CLSNAME));\n                m->add(fun(static_cast<CLS& (CLS::*)(const CLS&)>(&CLS::operator=)), \"=\");\n                \n                // Construct vector from a Chaiscript vector of elements of EXACTLY the type Scalar\n                m->add(fun([](const TChaiVector& cv) {\n                    auto n = cv.size();\n                    CLS v(n);\n                    if (n > 0) {\n                        int k = 0;\n                        for (auto& elem: cv) {\n                            v(k++) = chaiscript::boxed_cast<Scalar>(elem);\n                        }\n                    }\n                    return v;\n                }), CLSNAME);\n\n                \n                //// 1.2. Accessors\n                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), \"[]\");\n                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), \"coeff\");\n                \n                //// 1.3. Size and resize\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::size)), \"size\");\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::rows)), \"rows\");\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::cols)), \"cols\");\n                m->add(fun(static_cast<void (CLS::*)(typename CLS::Index)>(&CLS::resize)), \"resize\"); // destructive resize\n                \n                //// 1.4. Misc\n                \n                // Convert to string to print\n                m->add(fun([](const CLS& v) {\n                    std::stringstream s;\n                    s << v.format(EigenMatlabFmt);\n                    return s.str();\n                }), \"to_string\");\n                \n                return m;\n            }\n         \n            \n            // Register with Chaiscript a new Eigen matrix type\n            template<typename CLS, typename Scalar>\n            ModulePtr eigen_matrix_type(const char* CLSNAME, ModulePtr m = std::make_shared<Module>()) {\n                //// 1.1. Type and Construction\n                m->add(user_type<CLS>(), CLSNAME);\n                m->add(constructor<CLS ()>(), CLSNAME);\n                // Somehow Eigen does not work nicely with Chaiscript's constructor utility, so I must use a workaround\n                m->add(fun([](typename CLS::Index r, typename CLS::Index c) {\n                    return CLS(r, c);\n                }), CLSNAME);\n                bootstrap::copy_constructor<CLS>(CLSNAME, *m);\n                m->add(fun(static_cast<CLS& (CLS::*)(const CLS&)>(&CLS::operator=)), \"=\");\n                \n                // Conversions from vector to matrix\n                //m->add(fun([](const Eigen::Matrix<Scalar,Eigen::Dynamic,1>& v) { return CLS(v); }), CLSNAME);\n                //m->add(fun([](const Eigen::Matrix<Scalar,1,Eigen::Dynamic>& v) { return CLS(v); }), CLSNAME);\n                \n                // Construct a matrix of given size from a Chaiscript vector of elements of EXACTLY the type Scalar.\n                // This is done ROW-WISE.\n                // Only r*c elements are copied from the vector to the matrix. If the vector contains fewer elements, only those will be copied, the remaining elements of the matrix are undefined.\n                m->add(fun([](typename CLS::Index r, typename CLS::Index c, const TChaiVector& cv) {\n                    auto n = cv.size();\n                    CLS v(r, c);\n                    if (n > 0 && r*c > 0) {\n                        int k = 0;\n                        for (auto ri = 0; ri < r; ++ri) {\n                            for (auto ci = 0; ci < c; ++ci) {\n                                v(ri, ci) = chaiscript::Boxed_Number(cv[k++]).get_as<Scalar>();\n                                if (k == n) {\n                                    break;\n                                }\n                            }\n                            if (k == n) {\n                                break;\n                            }\n                        }\n                    }\n                    return v;\n                }), CLSNAME);\n                \n                \n                //// 1.2. Accessors\n                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index, typename CLS::Index)>(&CLS::operator())), \"coeff\");\n                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), \"[]\");\n\n                \n                //// 1.3. Size and resize\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::size)), \"size\");\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::rows)), \"rows\");\n                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::cols)), \"cols\");\n                m->add(fun(static_cast<void (CLS::*)(typename CLS::Index, typename CLS::Index)>(&CLS::resize)), \"resize\"); // destructive resize\n                \n                //// 1.4. Misc\n                // Convert to string to print\n                m->add(fun([](const CLS& v) {\n                    std::stringstream s;\n                    s << v.format(EigenMatlabFmt);\n                    return s.str();\n                }), \"to_string\");\n                \n                return m;\n            }\n            \n            // Predefined matrices\n            template<typename CLS>\n            ModulePtr eigen_matrix_predefined(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Zero(r,c)); }), \"zeros\");  // Zero matrix\n                m->add(fun([](CLS &m) { m.setZero(); }), \"setZero\");  // set all coefficients to 0\n                \n                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Ones(r,c)); }), \"ones\");  // matrix of 1's\n                m->add(fun([](CLS &m) { m.setOnes(); }), \"setOnes\");  // set all coefficients to 1\n                \n                m->add(fun(&CLS::fill), \"fill\");  // set all coefficients to a given constant\n                \n                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Identity(r,c));}), \"eyes\");  // Identity matrix\n                m->add(fun([](CLS &m) { m.setIdentity(); }), \"setIdentity\");  // set the matrix to identity\n                m->add(fun([](CLS &m, typename CLS::Index r, typename CLS::Index c) { m.setIdentity(r,c); }), \"setIdentity\");  // resize and set the matrix to identity\n                \n                return m;\n            }\n            \n            // Binary Addition and subtraction\n            // CLS1 and CLS2 should be different types, where CLS1 should be \"larger\" in the sense that CLS2 is a special case of CLS1 (e.g. Matrix and Vector)\n            template<typename CLS1, typename CLS2>\n            ModulePtr binary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS1& a, const CLS2& b) { return CLS1(a + b); }), \"+\");\n                m->add(fun([](const CLS2& a, const CLS1& b) { return CLS1(a + b); }), \"+\");\n                m->add(fun([](const CLS1& a, const CLS2& b) { return CLS1(a - b); }), \"-\");\n                m->add(fun([](const CLS2& a, const CLS1& b) { return CLS1(a - b); }), \"-\");\n                return m;\n            }\n            \n            // Binary Addition and subtraction for objects of same class\n            template<typename CLS1>\n            ModulePtr binary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS1& a, const CLS1& b) { return (a + b).eval(); }), \"+\");\n                m->add(fun([](const CLS1& a, const CLS1& b) { return (a - b).eval(); }), \"-\");\n                m->add(fun([](CLS1& a, const CLS1& b) { return (a += b); }), \"+=\");\n                \n                // Between matrix and scalar\n                m->add(fun([](const CLS1& a, const typename CLS1::Scalar b) { return CLS1(a.array() + b); }), \"+\");\n                //m->add(fun([](const typename CLS1::Scalar b, const CLS1& a) { return CLS1(a.array() + b); }), \"+\");\n                m->add(fun([](const CLS1& a, const typename CLS1::Scalar b) { return CLS1(a.array() - b); }), \"-\");\n                //m->add(fun([](const typename CLS1::Scalar b, const CLS1& a) { return CLS1((-a).array() + b); }), \"-\");\n\n                return m;\n            }\n            \n            // Unary Addition and subtraction\n            template<typename CLS>\n            ModulePtr unary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS& a) { return a; }), \"+\");\n                m->add(fun([](const CLS& a) { return (-a).eval(); }), \"-\");\n                return m;\n            }\n            \n            // Scalar multiplication and division\n            template<typename CLS, typename Scalar>\n            ModulePtr scalar_mult_div(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS& a, const Scalar b) { return (a * b).eval(); }), \"*\");\n                m->add(fun([](const Scalar a, const CLS& b) { return (a * b).eval(); }), \"*\");\n                m->add(fun([](const CLS& a, const Scalar b) { return (a / b).eval(); }), \"/\");\n                m->add(fun([](CLS& a, const Scalar b) { return (a *= b); }), \"*=\");\n                m->add(fun([](CLS& a, const Scalar b) { return (a /= b); }), \"/=\");\n                return m;\n            }\n            \n            // Transpose and conjugation\n            template<typename CLS, const bool withConjugation>\n            ModulePtr transpose_conjugation(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS& a) { return CLS(a.transpose()); }), \"transpose\");\n                m->add(fun(static_cast<void (CLS::*)()>(&CLS::transposeInPlace)), \"transposeInPlace\");    // in-place transpose: void transposeInPlace()\n                \n                if (withConjugation) {\n                    m->add(fun([](const CLS& a) { return CLS(a.conjugate()); }), \"conjugate\");\n                    m->add(fun([](const CLS& a) { return CLS(a.adjoint()); }), \"adjoint\");\n                    m->add(fun(static_cast<void (CLS::*)()>(&CLS::adjointInPlace)), \"adjointInPlace\");    // in-place adjoint: void adjointInPlace()\n                }\n                return m;\n            }\n            \n            // Matrix multiplication\n            template<typename CLS1, typename CLS2 = CLS1>\n            ModulePtr matrix_mult(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS1& a, const CLS2& b) { return (a * b).eval(); }), \"*\");\n                m->add(fun([](CLS1& a, const CLS2& b) { return a *= b; }), \"*=\");\n                return m;\n            }\n            \n            // Dot product (only for vector types)\n            template<typename CLS1>\n            ModulePtr dot_product(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS1& a, const CLS1& b) { return a.dot(b); }), \"dot\");\n                return m;\n            }\n            \n            // Basic arithmetic reduction operations\n            template<typename CLS>\n            ModulePtr arith_reduction(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::sum)), \"sum\");\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::prod)), \"prod\");\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::mean)), \"mean\");\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::minCoeff)), \"min\");\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::maxCoeff)), \"max\");\n                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::trace)), \"trace\");\n                return m;\n            }\n            \n            // Coefficient-wise operations\n            template<typename CLS>\n            ModulePtr coefficient_wise_operations(ModulePtr m = std::make_shared<Module>()) {\n                m->add(fun([](const CLS& a) { return a.cwiseAbs().eval(); }), \"abs\");\n                m->add(fun([](const CLS& a) { return a.cwiseAbs2().eval(); }), \"abs2\");\n                m->add(fun([](const CLS& a) { return a.cwiseSqrt().eval(); }), \"sqrt\");\n                m->add(fun([](const CLS& a) { return a.array().log().matrix().eval(); }), \"log\");\n                m->add(fun([](const CLS& a) { return a.array().exp().matrix().eval().eval(); }), \"exp\");\n                m->add(fun([](const CLS& a, double e) { return a.array().pow(e).matrix().eval(); }), \"pow\");\n                m->add(fun([](const CLS& a) { return a.array().square().matrix().eval(); }), \"square\");\n                m->add(fun([](const CLS& a) { return a.array().sin().matrix().eval(); }), \"sin\");\n                m->add(fun([](const CLS& a) { return a.array().cos().matrix().eval(); }), \"cos\");\n                m->add(fun([](const CLS& a) { return a.array().tan().matrix().eval(); }), \"tan\");\n                m->add(fun([](const CLS& a) { return a.array().asin().matrix().eval(); }), \"asin\");\n                m->add(fun([](const CLS& a) { return a.array().acos().matrix().eval(); }), \"acos\");\n                \n                return m;\n            }\n\n        }\n    }\n}\n#endif // _CHAISCRIPT_EXTRAS_EIGEN_H\n", "meta": {"hexsha": "56aaa7f43fc6cf07b4dd8abda8436e66cceb0b25", "size": 14453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "thirdparties/chaiscriptextras/eigen.hpp", "max_stars_repo_name": "sduerr85/OpenBuildNet", "max_stars_repo_head_hexsha": "126feb4d17558e7bfe1e2e6f081bbfbf1514496f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparties/chaiscriptextras/eigen.hpp", "max_issues_repo_name": "sduerr85/OpenBuildNet", "max_issues_repo_head_hexsha": "126feb4d17558e7bfe1e2e6f081bbfbf1514496f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparties/chaiscriptextras/eigen.hpp", "max_forks_repo_name": "sduerr85/OpenBuildNet", "max_forks_repo_head_hexsha": "126feb4d17558e7bfe1e2e6f081bbfbf1514496f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.8030888031, "max_line_length": 196, "alphanum_fraction": 0.4742268041, "num_tokens": 3526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.56020554152763}}
{"text": "#ifndef DATAOPS_H\n#define DATAOPS_H\n\n#include <map>\n#include <iterator>\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <functional>\n#include <numeric>\n#include <math.h>\n#include <cmath>\n#include <complex>\n#include <boost/multi_array.hpp>\n#include <boost/math/tools/polynomial.hpp>\n#include <typeinfo>\n\nnamespace DataOps \n{\n\ttemplate <typename T>\n\t\tstd::vector<T>& sample_every(std::vector<T>& lhs, const std::vector<T>& rhs, const size_t nskip = 10, const size_t offset = 0)\n\t\t{\n\t\t\tif (lhs.size() < 1){\n\t\t\t\tlhs.resize(int(rhs.size()/nskip),T(0));\n\t\t\t}\n\t\t\tif (lhs.size() > (rhs.size()+offset)/nskip ){\n\t\t\t\tlhs.resize(size_t((rhs.size()+offset)/nskip));\n\t\t\t}\n\t\t\tfor (size_t i = 0; i<lhs.size(); ++i){\n\t\t\t\tlhs[i] = T(rhs[nskip*i+offset]);\n\t\t\t}\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tT* clone(T* lhs,const T* rhs,const size_t n)\n\t\t{\n\t\t\tstd::copy(rhs, rhs + n, lhs);\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T>& clone(std::vector<T> & lhs, const std::vector<T> & rhs)\n\t\t{\n\t\t\tlhs.resize(rhs.size());\n\t\t\tstd::copy(rhs.begin(),rhs.end(),lhs.begin()); \n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tT& gauss(const T & xin, const T& x0, const T& w,T& a =T(1),T& y0 = T(0)){\n\t\t\tT x = xin-x0;\n\t\t\treturn (T) (y0+a*std::exp(- std::pow(x/w,int(2)))) ;\n\t\t}\n\n\ttemplate <typename X_t,typename Y_t> \n\t\tY_t polynomial(const X_t xin,const std::vector<Y_t> c){\n\t\t\tassert(c.size()>1);\n\t\t\tY_t x = Y_t(xin) - c.front();\n\t\t\tY_t y = c[1];\n\t\t\tfor (unsigned i=1; i<c.size();++i){\n\t\t\t\ty += c[i] * std::pow(x,(int)i-1);\n\t\t\t}\n\t\t\treturn y;\n\t\t}\n\n\ttemplate <typename T>\n\t\tvoid fixedfilter(T * vec, const size_t sz){\n\t\t\tT noise(T(.1));\n\t\t\tvec[0] *= T(1);\n\t\t\tvec[sz/2] *= T(1)/(T(1) + noise/10*std::pow(T(sz/2),2));\n\t\t\tfor( size_t i=1;i<sz/2;++i){\n\t\t\t\tvec[i] *= T(1)/(T(1) + noise/T(10)*std::pow(T(i),2));\n\t\t\t\tvec[sz-i] *= T(1)/(T(1) + noise/T(10)*std::pow(T(i),2));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\ttemplate <typename T>\n\t\tbool inwin(const T val, const std::vector<T> win){\n\t\t\tassert(win.size()==2);\n\t\t\treturn (val >= win[0] && val < win[1]);\n\t\t}\n\n\ttemplate <typename T>\n\t\tvoid endstozero(T * vec, const size_t sz, const size_t steps)\n\t\t{\n\t\t\tT mean1(0);\n\t\t\tT mean2(0);\n\t\t\tT x1(0);\n\t\t\tT x2(0);\n\t\t\tfor (size_t i=0;i<steps;++i){\n\t\t\t\tmean1 += vec[i];\n\t\t\t\tx1 += T(i);\n\t\t\t\tmean2 += vec[sz-i-1];\n\t\t\t\tx2 += T(i);\n\t\t\t}\n\t\t\tfor (size_t i=0; i<sz; ++i){\n\t\t\t\tvec[i] -= (mean2-mean1)/(x2-x1)*(T(i)-x1) + mean1/T(steps);\n\t\t\t}\n\t\t}\n\t\n\ttemplate <typename T>\n\t\tvoid sin2roll(T * vec, const size_t sz, const T center, const T width)\n\t\t{\n\t\t\tfor (size_t i = 0;i<sz;++i){\n\t\t\t\tT x = T(M_PI)*(T(i)-center)/(T(2)*width);\n\t\t\t\tif (std::abs(x) > T(1)){\n\t\t\t\t\tvec[i] = T(0);\n\t\t\t\t} else {\n\t\t\t\t\tvec[i] *= std::pow(std::cos(x),int(2));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\ttemplate <typename T>\n\t\tvoid gaussroll(T * vec, const size_t sz, const T center, const T width)\n\t\t{\n\t\t\tfor (size_t i = 0;i<sz;++i){\n\t\t\t\tT x = (T(i)-center)/width;\n\t\t\t\tvec[i] *= std::exp(-1.*std::pow(x,2));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\ttemplate <typename T,typename V>\n\t\tV interpolate(const std::map<T,V> &data, T x)\n\t\t{\n\t\t\ttypedef typename std::map<T,V>::const_iterator MapIterator;\n\t\t\tMapIterator i = data.upper_bound(x);\n\t\t\tMapIterator l = i;\n\t\t\tdouble slope;\n\t\t\tdouble span = (double) (x - l->first);\n\t\t\tif (i==data.begin())\n\t\t\t{\n\t\t\t\tMapIterator u=i;\n\t\t\t\t++u;\n\t\t\t\tslope = (double)(u->second - i->second)/(double)(u->first - i->first);\n\t\t\t\treturn (V)( i->second + (slope * span/(u->first - i->first) ) );\n\t\t\t}\n\t\t\t--l;\n\t\t\tif(i==data.end())\n\t\t\t{\n\t\t\t\tMapIterator ll=l;\n\t\t\t\t--ll;\n\t\t\t\tslope = (double)(l->second - ll->second)/(double)(l->first - ll->first);\n\t\t\t\treturn (V)( l->second + (slope * span/(l->first - ll->first) ) ) ;\n\t\t\t}\n\t\t\tslope = (double)( i->second - l->second ) / (double)( i->first - l->first );\n\t\t\treturn (V)(l->second + (slope * span/(i->first - l->first)) );\n\t\t}\n\n\ttemplate <typename T>\n\t\tvoid condense(std::vector< T > & invec,const unsigned newlen)\n\t\t{\n\t\t\tdouble ratio = ((double)invec.size()/(double)newlen);\n\n\t\t\tif (ratio <= 1){std::cerr << \"Cannot condense2(): size mismatch\" << std::endl;return;}\n\t\t\tfor (unsigned j=1;j<(int)ratio;++j){\n\t\t\t\tinvec[0] += invec[j];\n\t\t\t}\n\t\t\tinvec[0] /= ratio;\n\t\t\tfor (unsigned i=1;i<newlen;++i){\n\t\t\t\tinvec[i] = invec[(int)(i*ratio)];\n\t\t\t\tfor (unsigned j=1;j<ratio;++j){\n\t\t\t\t\tinvec[i] += invec[(int)(i*ratio + j)];\n\t\t\t\t}\n\t\t\t\tinvec[i] /= (double)ratio;\n\t\t\t}\n\t\t\tinvec.resize(newlen);\n\n\t\t\treturn;\n\t\t}\n\n\ttemplate <typename T>\n\t\tvoid condense(std::vector< std::vector < T > > & inmat, const unsigned newlen)\n\t\t{\n\t\t\tfor (unsigned i=0;i<inmat.size();++i)\n\t\t\t\tcondense(inmat[i],newlen);\n\t\t\treturn;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::istream& operator >> (std::istream & ins, std::vector<T> & record)\n\t\t{\n\t\t\trecord.clear();\n\t\t\tstd::string line;\n\t\t\tgetline( ins, line );\n\t\t\tconst char head='#';\n\t\t\tif (line.find(head) != std::string::npos){\n\t\t\t\treturn ins;\n\t\t\t}\n\t\t\tstd::istringstream iss( (std::string)line );\n\t\t\tT value;\n\t\t\twhile (iss >> value){\n\t\t\t\trecord.push_back(value);\n\t\t\t}\n\t\t\treturn ins;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::istream& operator >> (std::istream & ins, std::vector< std::vector<T> > & matrix)\n\t\t{\n\t\t\tmatrix.clear();\n\t\t\tstd::vector<T> record;\n\t\t\twhile (ins >> record)\n\t\t\t{\n\t\t\t\tif (record.size() > 0)\n\t\t\t\t\tmatrix.push_back( record );\n\t\t\t}\n\t\t\treturn ins;\n\t\t}\n\t/*\n\t   template <typename T, int dim>\n\t   std::ostream& operator << (std::ostream & outs, boost::multi_array<T,dim> & record)\n\t   {\n\t   for (unsigned i=0;i<record.shape()[0];++i){\n\t   outs << record[i] << \"\\t\";\n\t   }\n\t   outs << std::flush;\n\t   return outs;\n\t   }\n\t */\n\n\ttemplate <typename T,typename V>\n\t\tstd::ostream& operator << (std::ostream & outs, std::pair<T,V> outpair)\n\t\t{\n\t\t\touts << \"(\" << outpair.first << \",\" << outpair.second << \")\\t\" << std::flush;\n\t\t\treturn outs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::ostream& operator << (std::ostream & outs, std::vector< T > & vec)\n\t\t{\n\t\t\tfor (unsigned i=0;i<vec.size();++i){\n\t\t\t\touts << vec[i] << \"\\t\";\n\t\t\t}\n\t\t\touts << \"\\n\" << std::flush;\n\t\t\treturn outs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::ostream& operator << (std::ostream & outs, std::vector< std::vector <T> > & matrix)\n\t\t{\n\t\t\tfor (unsigned i=0;i<matrix.size();++i){\n\t\t\t\tfor (unsigned j=0;j<matrix[i].size();++j){\n\t\t\t\t\touts << matrix[i][j] << \"\\t\";\n\t\t\t\t}\n\t\t\t\touts << \"\\n\";\n\t\t\t}\n\t\t\touts << std::flush;\n\t\t\treturn outs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::complex<T>*& sum(std::complex<T>*& lhs,std::complex<T>* const & rhs,const size_t n)\n\t\t{\n\t\t\tfor (size_t i = 0;i<n;++i){\n\t\t\t\tlhs[i] += rhs[i];\n\t\t\t}\n\t\t\t/*\n\t\t\tstd::transform(lhs,lhs+n,rhs,[](std::complex<T>* d_lhs, std::complex<T>* d_rhs){\n\t\t\t\t\treturn *d_lhs + *d_rhs;\n\t\t\t\t\t});\n\t\t\t*/\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::complex<T>* diff(std::complex<T>*& lhs,std::complex<T>* const & rhs,const size_t n)\n\t\t{\n\t\t\tfor (size_t i = 0;i<n;++i){\n\t\t\t\tlhs[i] -= rhs[i];\n\t\t\t}\n\t\t\t/*\n\t\t\tstd::transform(lhs,lhs+n,rhs,[](std::complex<T>* d_lhs, std::complex<T>* d_rhs){\n\t\t\t\t\treturn *d_lhs - *d_rhs;\n\t\t\t\t\t});\n\t\t\t*/\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::complex<T>* mul(std::complex<T>*& lhs,std::complex<T>* const & rhs,const size_t n)\n\t\t{\n\t\t\tfor (size_t i = 0;i<n;++i){\n\t\t\t\tlhs[i] *= rhs[i];\n\t\t\t}\n\t\t\t/*\n\t\t\tstd::transform(lhs,lhs+n,rhs,lhs,[](std::complex<T>* d_lhs, std::complex<T>* d_rhs){\n\t\t\t\t\treturn (*d_lhs) * (*d_rhs);\n\t\t\t\t\t});\n\t\t\t*/\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::complex<T>* mul(std::complex<T>*& lhs,const T& scale,const size_t n)\n\t\t{\n\t\t\tstd::transform(lhs, lhs+n, lhs, std::bind2nd(std::multiplies<std::complex<T> >(),scale));\n\t\t\t//std::cerr << \"using this complex vec scaling function in DataOps::\" << std::endl << std::flush;\n\t\t\treturn lhs;\n\t\t}\n\ttemplate <typename T>\n\t\tstd::complex<T>* mul(std::complex<T>*& lhs,std::complex<T>& scale,const size_t n)\n\t\t{\n\t\t\tstd::transform(lhs, lhs+n, lhs, std::bind2nd(std::multiplies<std::complex<T> >(),scale));\n\t\t\treturn lhs;\n\t\t}\n\n\n\ttemplate <typename T>\n\t\tstd::complex<T>* div(std::complex<T>*& lhs,std::complex<T>* const & rhs,const size_t n)\n\t\t{\n\t\t\tfor (size_t i=0;i<n;++i){\n\t\t\t\tlhs[i] /= rhs[i];\n\t\t\t}\n\t\t\t/*\n\t\t\tstd::transform(lhs,lhs+n,rhs,lhs,[](std::complex<T>* d_lhs, std::complex<T>* d_rhs){\n\t\t\t\t\treturn *d_lhs / *d_rhs;\n\t\t\t\t\t});\n\t\t\t*/\n\t\t\treturn lhs;\n\t\t}\n\n\ttemplate <typename T>\n\t\tinline bool inwin(std::vector<T> win,T val)\n\t\t{\n\t\t\tstd::sort(win.begin(),win.end());\n\t\t\treturn (val >= win.front() && val < win.back());\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T> & expscaled(const T scale, std::vector<T> & x)\n\t\t{\n\t\t\tx *= scale;\n\t\t\tstd::transform(x.begin(), x.end(), x.begin(), [&](T xval){return std::exp(xval);});\n\t\t\treturn x;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<std::complex<T> > & operator *= (std::vector<std::complex<T> > & vec,std::complex<T> val)\n\t\t{\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::multiplies<std::complex<T> >(),val));\n\t\t\treturn vec;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<std::complex<T> > & operator *= (std::vector<std::complex<T> > & vec,T val)\n\t\t{\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::multiplies<std::complex<T> >(),val));\n\t\t\treturn vec;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T> & operator *= (std::vector<T>& vec,T const val)\n\t\t{\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::multiplies<T>(),val));\n\t\t\treturn vec;\n\t\t}\n\n\t//================ HERE HERE HERE HERE ================//\n\ttemplate <typename T>\n\t\tstd::vector<T> & operator /= (std::vector<T>& vec,const T val)\n\t\t{\n\t\t\tassert(std::abs(val) != T(0) );\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::divides<T>(),val));\n\t\t\treturn vec;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T> & operator += (std::vector<T>& vec, const T val)\n\t\t{\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::plus<T>(),val));\n\t\t\treturn vec;\n\t\t}\n\n\ttemplate <typename T,typename T2>\n\t\tstd::vector<T> & operator -= (std::vector<T>& vec, const T2 val)\n\t\t{\n\t\t\tstd::transform(vec.begin(), vec.end(), vec.begin(), std::bind2nd(std::minus<T>(),val));\n\t\t\treturn vec;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T>& operator += (std::vector<T>& resvec,const std::vector<T> & srcvec)\n\t\t{\n\t\t\tassert(resvec.size() == srcvec.size());\n\t\t\tfor (unsigned i=0;i<resvec.size();++i){\n\t\t\t\tresvec[i] += srcvec[i];\n\t\t\t}\n\t\t\treturn resvec;\n\t\t}\n\n\ttemplate <typename T>\n\t\tstd::vector<T>& operator -= (std::vector<T>& resvec,const std::vector<T> & srcvec)\n\t\t{\n\t\t\tassert(resvec.size() == srcvec.size());\n\t\t\tfor (unsigned i=0;i<resvec.size();++i){\n\t\t\t\tresvec[i] -= srcvec[i];\n\t\t\t}\n\t\t\treturn resvec;\n\t\t}\n\ttemplate <typename T>\n\t\tstd::vector<T>& operator *= (std::vector<T>& resvec,const std::vector<T> & srcvec)\n\t\t{\n\t\t\tassert(resvec.size() == srcvec.size());\n\t\t\tfor (unsigned i=0;i<resvec.size();++i){\n\t\t\t\tresvec[i] *= srcvec[i];\n\t\t\t}\n\t\t\treturn resvec;\n\t\t}\n\ttemplate <typename T>\n\t\tstd::vector<T>& operator /= (std::vector<T>& resvec,const std::vector<T> & srcvec)\n\t\t{\n\t\t\tassert(resvec.size() == srcvec.size());\n\t\t\tfor (unsigned i=0;i<resvec.size();++i){\n\t\t\t\tresvec[i] /= srcvec[i];\n\t\t\t}\n\t\t\treturn resvec;\n\t\t}\n\n\n\n\ttemplate <typename T>\n\t\tinline T projection(std::vector<T> &in1,std::vector<T> in2,std::vector<bool> & mask){\n\t\t\tassert(in1.size()==in2.size());\n\t\t\tassert(in1.size() == mask.size());\n\t\t\tT ip(0);\n\t\t\tfor (unsigned i=0;i<in1.size();++i){\n\t\t\t\tif (mask[i]){\n\t\t\t\t\tip += in1[i] * in2[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ip;\t\n\t\t}\n\n\tinline size_t sum(std::vector<bool> & mask){\n\t\tsize_t sum = 0;\n\t\tfor (size_t i = 0 ; i<mask.size();++i){\n\t\t\tif (mask[i]==true) sum++;\n\t\t}\n\t\treturn sum;\n\t}\n\n\ttemplate <typename T>\n\t\tinline T projection(std::vector<T> &in1,std::vector<T> in2){\n\t\t\tassert(in1.size()==in2.size());\n\t\t\treturn std::inner_product(in1.begin(),in1.end(),in2.begin(),0.);\t\n\t\t}\n\n\ttemplate <typename T>\n\t\tinline void safe_normalize(std::vector<T> & in)\n\t\t{\n\t\t\tT ip(0);\n\t\t\tfor (unsigned i=0;i<in.size();++i){\n\t\t\t\tip += (in[i] * in[i]);\n\t\t\t}\n\t\t\tassert(ip!=T(0));\n\t\t\tT scale = T(1)/std::sqrt(ip);\n\t\t\tstd::transform(in.begin(), in.end(), in.begin(), std::bind2nd(std::multiplies<T>(),scale) );\n\t\t}\n\t\n\ttemplate <typename T>\n\t\tinline void sqr_normalize(std::vector<T> & in,std::vector<bool>& mask)\n\t\t{\n\t\t\tassert(in.size() == mask.size());\n\t\t\tT ip = T(0);\n\t\t\tfor (unsigned i=0;i<in.size();++i)\n\t\t\t\tif (mask[i]) {ip += (in[i] * in[i]);}\n\t\t\tassert(ip!=T(0));\n\t\t\tT scale = T(1)/std::sqrt(ip);\n\t\t\tstd::transform(in.begin(), in.end(), in.begin(), std::bind2nd(std::multiplies<T>(),scale) );\n\t\t}\n\t\n\ttemplate <typename T>\n\t\tinline void sqr_normalize(std::vector<T> & in) {\n\t\t\tT scale = sqrt( std::inner_product(in.begin(), in.end(), in.begin(),T(0)) );\n\t\t\tassert(scale != T(0));\n\t\t\tstd::transform(in.begin(), in.end(), in.begin(), std::bind2nd(std::divides<T>(),scale) );\n\t\t};\n\n\ttemplate <typename T>\n\t\tinline T removemean(T* in, size_t sz) {\n\t\t\tT sum = std::accumulate(in, in + sz, T(0));\n\t\t\tT mean = sum / T(sz);\n\t\t\tstd::transform(in, in + sz, in, std::bind2nd(std::minus<T>(),mean));\n\t\t\treturn mean;\n\t\t};\n\n\ttemplate <typename T>\n\t\tinline T removemean(std::vector<T> & in,std::vector<bool> & mask) {\n\t\t\tassert(in.size() == mask.size());\n\t\t\tT sum(0);\n\t\t\tunsigned nvals(0);\n\t\t\tfor (unsigned i=0;i<in.size();++i){\n\t\t\t\tif (mask[i]) { \n\t\t\t\t\tsum += in[i];\n\t\t\t\t\t++nvals;\n\t\t\t\t}\n\t\t\t}\n\t\t\tT mean = sum / T(nvals);\n\t\t\tstd::transform(in.begin(), in.end(), in.begin(), std::bind2nd(std::minus<T>(),mean));\n\t\t\treturn mean;\n\t\t};\n\t\n\ttemplate <typename T>\n\t\tinline T removemean(std::vector<T> & in) {\n\t\t\tT sum = std::accumulate(in.begin(), in.end(), T(0));\n\t\t\tT mean = sum / T(in.size());\n\t\t\tstd::transform(in.begin(), in.end(), in.begin(), std::bind2nd(std::minus<T>(),mean));\n\t\t\treturn mean;\n\t\t};\n\t\n\ttemplate <typename T>\n\t\tinline T mean(std::vector<T> &in){\n\t\t\tT mean = std::accumulate(in.begin(), in.end(), T(0));\n\t\t\tmean /= T(in.size());\n\t\t\treturn mean;\n\t\t};\n\n\n\n\n\t// WHoah  logarithmic stuff  //\n\n\ttemplate <typename T>\n\t\tinline void meanstdlog(std::vector<T> & in, T& mean, T& std)\n\t\t{\n\t\t\t// I want the log of the values, then sum, then divide by size for mean\n\t\t\t// Diff is the log(values)-mean(log valuse)\n\t\t\tmean = std::log( std::accumulate(in.begin(),in.end(),T(1),std::multiplies<T>()) );\n\t\t\tmean /= T(in.size());\n\t\t\tstd::vector<T> diff(in.size());\n\t\t\tfor (unsigned i=0;i<diff.size();++i){\n\t\t\t\tdiff[i] = std::log(in[i]) - mean;\n\t\t\t}\n\t\t\tT sq_sum = std::inner_product(diff.begin(),diff.end(),diff.begin(),T(0));\n\t\t\tstd = std::sqrt(sq_sum / T(diff.size()));\n\t\t}\n\n\ttemplate <typename T>\n\t\tinline T meanlog(std::vector<T> & in,T offset){\n\t\t\tT mean = offset;\n\t\t\tmean += std::log( std::accumulate(in.begin(),in.end(),T(1),std::multiplies<T>()) );\n\t\t\tmean /= T(in.size());\n\t\t\treturn mean;\n\t\t};\n\t\n\ttemplate <typename T>\n\t\tinline T stdlog(std::vector<T> & in, T mean){\n\t\t\tstd::vector<T> diff(in.size());\n\t\t\tfor (unsigned i=0;i<diff.size();++i){\n\t\t\t\tdiff[i] = std::log(in[i]) - mean;\n\t\t\t}\n\t\t\tT sq_sum = std::inner_product(diff.begin(),diff.end(),diff.begin(),T(0));\n\t\t\tT stdev = std::sqrt(sq_sum / T(diff.size()));\n\t\t\treturn stdev;\n\t\t};\n\n\ttemplate <typename T>\n\t\tvoid detrend(T * vec, const size_t sz)\n\t\t{\n\t\t\tT num(0);\n\t\t\tT den(0);\n\t\t\tT xm = T(sz-1)/T(2);\n\t\t\tT ym = removemean(vec,sz);\n\t\t\tfor (size_t i=0;i<sz;++i){\n\t\t\t\tnum += (i-xm)*vec[i];\n\t\t\t\tden += std::pow((i-xm),int(2));\n\t\t\t}\n\t\t\tT beta = num/den;\n\t\t\tfor (size_t i=0;i<sz;++i){\n\t\t\t\tvec[i] -= beta*T(i) - beta*xm;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n}\n\n#endif\n", "meta": {"hexsha": "3b04c59e50ee7670745c5396b977b4e897a5eb5c", "size": 15294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/DataOps.hpp", "max_stars_repo_name": "ryancoffee/2dtimetool_simulation", "max_stars_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/DataOps.hpp", "max_issues_repo_name": "ryancoffee/2dtimetool_simulation", "max_issues_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/DataOps.hpp", "max_forks_repo_name": "ryancoffee/2dtimetool_simulation", "max_forks_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_forks_repo_licenses": ["BSD-3-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.0545144804, "max_line_length": 128, "alphanum_fraction": 0.5681312933, "num_tokens": 5043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.5602055370375384}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_p_square_quantile.hpp\r\n//\r\n//  Copyright 2005 Daniel Egloff. 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_WEIGHTED_P_SQUARE_QUANTILE_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_P_SQUARE_QUANTILE_HPP_DE_01_01_2006\r\n\r\n#include <cmath>\r\n#include <functional>\r\n#include <boost/array.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/type_traits/is_same.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/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n#include <boost/accumulators/statistics/sum.hpp>\r\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl {\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_p_square_quantile_impl\r\n    //  single quantile estimation with weighted samples\r\n    /**\r\n        @brief Single quantile estimation with the \\f$P^2\\f$ algorithm for weighted samples\r\n\r\n        This version of the \\f$P^2\\f$ algorithm extends the \\f$P^2\\f$ algorithm to support weighted samples.\r\n        The \\f$P^2\\f$ algorithm estimates a quantile dynamically without storing samples. Instead of\r\n        storing the whole sample cumulative distribution, only five points (markers) are stored. The heights\r\n        of these markers are the minimum and the maximum of the samples and the current estimates of the\r\n        \\f$(p/2)\\f$-, \\f$p\\f$ - and \\f$(1+p)/2\\f$ -quantiles. Their positions are equal to the number\r\n        of samples that are smaller or equal to the markers. Each time a new sample is added, the\r\n        positions of the markers are updated and if necessary their heights are adjusted using a piecewise-\r\n        parabolic formula.\r\n\r\n        For further details, see\r\n\r\n        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and\r\n        histograms without storing observations, Communications of the ACM,\r\n        Volume 28 (October), Number 10, 1985, p. 1076-1085.\r\n\r\n        @param quantile_probability\r\n    */\r\n    template<typename Sample, typename Weight, typename Impl>\r\n    struct weighted_p_square_quantile_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\r\n        typedef typename numeric::functional::average<weighted_sample, std::size_t>::result_type float_type;\r\n        typedef array<float_type, 5> array_type;\r\n        // for boost::result_of\r\n        typedef float_type result_type;\r\n\r\n        template<typename Args>\r\n        weighted_p_square_quantile_impl(Args const &args)\r\n          : p(is_same<Impl, for_median>::value ? 0.5 : args[quantile_probability | 0.5])\r\n          , heights()\r\n          , actual_positions()\r\n          , desired_positions()\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            std::size_t cnt = count(args);\r\n\r\n            // accumulate 5 first samples\r\n            if (cnt <= 5)\r\n            {\r\n                this->heights[cnt - 1] = args[sample];\r\n\r\n                // In this initialization phase, actual_positions stores the weights of the\r\n                // initial samples that are needed at the end of the initialization phase to\r\n                // compute the correct initial positions of the markers.\r\n                this->actual_positions[cnt - 1] = args[weight];\r\n\r\n                // complete the initialization of heights and actual_positions by sorting\r\n                if (cnt == 5)\r\n                {\r\n                    // TODO: we need to sort the initial samples (in heights) in ascending order and\r\n                    // sort their weights (in actual_positions) the same way. The following lines do\r\n                    // it, but there must be a better and more efficient way of doing this.\r\n                    typename array_type::iterator it_begin, it_end, it_min;\r\n\r\n                    it_begin = this->heights.begin();\r\n                    it_end   = this->heights.end();\r\n\r\n                    std::size_t pos = 0;\r\n\r\n                    while (it_begin != it_end)\r\n                    {\r\n                        it_min = std::min_element(it_begin, it_end);\r\n                        std::size_t d = std::distance(it_begin, it_min);\r\n                        std::swap(*it_begin, *it_min);\r\n                        std::swap(this->actual_positions[pos], this->actual_positions[pos + d]);\r\n                        ++it_begin;\r\n                        ++pos;\r\n                    }\r\n\r\n                    // calculate correct initial actual positions\r\n                    for (std::size_t i = 1; i < 5; ++i)\r\n                    {\r\n                        this->actual_positions[i] += this->actual_positions[i - 1];\r\n                    }\r\n                }\r\n            }\r\n            else\r\n            {\r\n                std::size_t sample_cell = 1; // k\r\n\r\n                // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values\r\n                if (args[sample] < this->heights[0])\r\n                {\r\n                    this->heights[0] = args[sample];\r\n                    this->actual_positions[0] = args[weight];\r\n                    sample_cell = 1;\r\n                }\r\n                else if (this->heights[4] <= args[sample])\r\n                {\r\n                    this->heights[4] = args[sample];\r\n                    sample_cell = 4;\r\n                }\r\n                else\r\n                {\r\n                    typedef typename array_type::iterator iterator;\r\n                    iterator it = std::upper_bound(\r\n                        this->heights.begin()\r\n                      , this->heights.end()\r\n                      , args[sample]\r\n                    );\r\n\r\n                    sample_cell = std::distance(this->heights.begin(), it);\r\n                }\r\n\r\n                // increment positions of markers above sample_cell\r\n                for (std::size_t i = sample_cell; i < 5; ++i)\r\n                {\r\n                    this->actual_positions[i] += args[weight];\r\n                }\r\n\r\n                // update desired positions for all markers\r\n                this->desired_positions[0] = this->actual_positions[0];\r\n                this->desired_positions[1] = (sum_of_weights(args) - this->actual_positions[0])\r\n                                           * this->p/2. + this->actual_positions[0];\r\n                this->desired_positions[2] = (sum_of_weights(args) - this->actual_positions[0])\r\n                                           * this->p + this->actual_positions[0];\r\n                this->desired_positions[3] = (sum_of_weights(args) - this->actual_positions[0])\r\n                                           * (1. + this->p)/2. + this->actual_positions[0];\r\n                this->desired_positions[4] = sum_of_weights(args);\r\n\r\n                // adjust height and actual positions of markers 1 to 3 if necessary\r\n                for (std::size_t i = 1; i <= 3; ++i)\r\n                {\r\n                    // offset to desired positions\r\n                    float_type d = this->desired_positions[i] - this->actual_positions[i];\r\n\r\n                    // offset to next position\r\n                    float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];\r\n\r\n                    // offset to previous position\r\n                    float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];\r\n\r\n                    // height ds\r\n                    float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;\r\n                    float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;\r\n\r\n                    if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) )\r\n                    {\r\n                        short sign_d = static_cast<short>(d / std::abs(d));\r\n\r\n                        // try adjusting heights[i] using p-squared formula\r\n                        float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm );\r\n\r\n                        if ( this->heights[i - 1] < h && h < this->heights[i + 1] )\r\n                        {\r\n                            this->heights[i] = h;\r\n                        }\r\n                        else\r\n                        {\r\n                            // use linear formula\r\n                            if (d>0)\r\n                            {\r\n                                this->heights[i] += hp;\r\n                            }\r\n                            if (d<0)\r\n                            {\r\n                                this->heights[i] -= hm;\r\n                            }\r\n                        }\r\n                        this->actual_positions[i] += sign_d;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        result_type result(dont_care) const\r\n        {\r\n            return this->heights[2];\r\n        }\r\n\r\n    private:\r\n        float_type p;                    // the quantile probability p\r\n        array_type heights;              // q_i\r\n        array_type actual_positions;     // n_i\r\n        array_type desired_positions;    // n'_i\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_p_square_quantile\r\n//\r\nnamespace tag\r\n{\r\n    struct weighted_p_square_quantile\r\n      : depends_on<count, sum_of_weights>\r\n    {\r\n        typedef accumulators::impl::weighted_p_square_quantile_impl<mpl::_1, mpl::_2, regular> impl;\r\n    };\r\n    struct weighted_p_square_quantile_for_median\r\n      : depends_on<count, sum_of_weights>\r\n    {\r\n        typedef accumulators::impl::weighted_p_square_quantile_impl<mpl::_1, mpl::_2, for_median> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_p_square_quantile\r\n// extract::weighted_p_square_quantile_for_median\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::weighted_p_square_quantile> const weighted_p_square_quantile = {};\r\n    extractor<tag::weighted_p_square_quantile_for_median> const weighted_p_square_quantile_for_median = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_p_square_quantile)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_p_square_quantile_for_median)\r\n}\r\n\r\nusing extract::weighted_p_square_quantile;\r\nusing extract::weighted_p_square_quantile_for_median;\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "103ac8217423ed44fddcff3215cd76409ba523d5", "size": 11005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BoostSharp/include/boost/accumulators/statistics/weighted_p_square_quantile.hpp", "max_stars_repo_name": "Icenium/BoostSharp", "max_stars_repo_head_hexsha": "1dd31065fcd65ae6304b182c558bac7c7a738ad5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-30T09:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T17:00:06.000Z", "max_issues_repo_path": "src/third_party/boost/boost/accumulators/statistics/weighted_p_square_quantile.hpp", "max_issues_repo_name": "wugh7125/installwizard", "max_issues_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/third_party/boost/boost/accumulators/statistics/weighted_p_square_quantile.hpp", "max_forks_repo_name": "wugh7125/installwizard", "max_forks_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-26T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:00:08.000Z", "avg_line_length": 42.98828125, "max_line_length": 124, "alphanum_fraction": 0.5244888687, "num_tokens": 2230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5601675084874067}}
{"text": "#ifndef ZSVM_REAL_VARIATIONAL_SOLVER_HPP_INCLUDED\n#define ZSVM_REAL_VARIATIONAL_SOLVER_HPP_INCLUDED\n\n// C++ standard library headers\n#include <cmath> // for std::sqrt, std::pow, std::abs\n#include <cstddef> // for std::size_t\n#include <limits>\n\n// Eigen linear algebra library headers\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nnamespace zsvm {\n\n    template <typename T>\n    class RealVariationalSolver {\n\n    private: // =============================================== MEMBER VARIABLES\n\n        typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXT;\n        typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXT;\n        typedef Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic> ArrayXT;\n\n        std::size_t size;\n        MatrixXT overlap_matrix;\n        MatrixXT hamiltonian_matrix;\n        VectorXT eigenvalues;\n        MatrixXT eigenvectors;\n        bool clean;\n\n    public: // ===================================================== CONSTRUCTOR\n\n        RealVariationalSolver() : size(0), clean(false) {}\n\n    public: // ======================================================== MUTATORS\n\n        void set_basis_size_conservative(std::size_t basis_size) {\n            size = basis_size;\n            overlap_matrix.conservativeResize(basis_size, basis_size);\n            hamiltonian_matrix.conservativeResize(basis_size, basis_size);\n            clean = false;\n        }\n\n        void set_basis_size_destructive(std::size_t basis_size) {\n            size = basis_size;\n            overlap_matrix.resize(basis_size, basis_size);\n            hamiltonian_matrix.resize(basis_size, basis_size);\n            clean = false;\n        }\n\n        T &overlap_matrix_element(std::size_t i, std::size_t j) {\n            clean = false;\n            return overlap_matrix(i, j);\n        }\n\n        T &hamiltonian_matrix_element(std::size_t i, std::size_t j) {\n            clean = false;\n            return hamiltonian_matrix(i, j);\n        }\n\n        void compute_eigenstates() {\n            if (!clean) {\n                Eigen::GeneralizedSelfAdjointEigenSolver<MatrixXT> eigen_solver(\n                        hamiltonian_matrix, overlap_matrix,\n                        Eigen::ComputeEigenvectors | Eigen::Ax_lBx);\n                eigenvalues = eigen_solver.eigenvalues();\n                eigenvectors = eigen_solver.eigenvectors();\n                clean = true;\n            }\n        }\n\n    public: // ======================================================== ACCESORS\n\n        bool empty() const { return (size == 0); }\n\n        T get_eigenvalue(std::size_t i) {\n            if (!clean) { compute_eigenstates(); }\n            return eigenvalues(i);\n        }\n\n    private: // ========================== EIGENVALUE COMPUTATION HELPER METHODS\n\n        T secular_objective_function(const T &x, const T &t,\n                                     const ArrayXT &beta) const {\n            return t - x - (beta / (eigenvalues.array() - x)).sum();\n        }\n\n        void find_lower_bracketing_interval(\n                T &lower_bound, T &upper_bound,\n                const T &strict_upper_bound,\n                const T &t, const ArrayXT &beta) const {\n            using std::ldexp;\n            const T one(1);\n            int k = 0;\n            lower_bound = strict_upper_bound - ldexp(one, -k);\n            upper_bound = strict_upper_bound - ldexp(one, -k - 1);\n            T lower_objective = secular_objective_function(\n                    lower_bound, t, beta);\n            T upper_objective = secular_objective_function(\n                    upper_bound, t, beta);\n            while (true) {\n                if (lower_objective > 0 && upper_objective > 0) {\n                    ++k;\n                    lower_bound = upper_bound;\n                    lower_objective = upper_objective;\n                    upper_bound = strict_upper_bound - ldexp(one, -k - 1);\n                    upper_objective = secular_objective_function(\n                            upper_bound, t, beta);\n                } else if (lower_objective < 0 && upper_objective < 0) {\n                    --k;\n                    upper_bound = lower_bound;\n                    upper_objective = lower_objective;\n                    lower_bound = strict_upper_bound - ldexp(one, -k);\n                    lower_objective = secular_objective_function(\n                            lower_bound, t, beta);\n                } else {\n                    break;\n                }\n            }\n        }\n\n        T solve_secular_equation_bisection(\n                T lower_bound, T upper_bound,\n                const T &t, const ArrayXT &beta) const {\n            using std::abs;\n            const T tolerance = 64 * std::numeric_limits<T>::epsilon();\n            while (true) {\n                const T midpoint = (lower_bound + upper_bound) / 2;\n                const T relative_difference = abs(\n                        (upper_bound - lower_bound) / midpoint);\n                if (relative_difference < tolerance) { return midpoint; }\n                const T midpoint_objective = secular_objective_function(\n                        midpoint, t, beta);\n                if (midpoint_objective == 0) {\n                    return midpoint;\n                } else if (midpoint_objective > 0) {\n                    lower_bound = midpoint;\n                } else if (midpoint_objective < 0) {\n                    upper_bound = midpoint;\n                } else {\n                    return std::numeric_limits<T>::quiet_NaN();\n                }\n            }\n        }\n\n    public: // ============================= FAST EIGENVALUE COMPUTATION METHODS\n\n        T minimum_augmented_eigenvalue(\n                const T *new_overlap_column,\n                const T *new_hamiltonian_column) {\n            using std::sqrt;\n            if (!clean) { compute_eigenstates(); }\n            VectorXT overlap_vector(size);\n            for (std::size_t i = 0; i < size; ++i) {\n                overlap_vector(i) = new_overlap_column[i];\n            }\n            VectorXT hamiltonian_vector(size);\n            for (std::size_t i = 0; i < size; ++i) {\n                hamiltonian_vector(i) = new_hamiltonian_column[i];\n            }\n            const VectorXT alpha = eigenvectors.transpose() * overlap_vector;\n            const T norm_factor = 1 / sqrt(\n                    new_overlap_column[size] - alpha.squaredNorm());\n            const VectorXT phi = -norm_factor * (eigenvectors * alpha);\n            const VectorXT psi = hamiltonian_matrix * phi +\n                                 norm_factor * hamiltonian_vector;\n            const ArrayXT beta =\n                    (eigenvectors.transpose() * psi).array().square();\n            const T t = phi.dot(psi) + norm_factor * (\n                    hamiltonian_vector.dot(phi) +\n                    norm_factor * new_hamiltonian_column[size]);\n            T lower_bound, upper_bound;\n            find_lower_bracketing_interval(\n                    lower_bound, upper_bound, eigenvalues[0], t, beta);\n            return solve_secular_equation_bisection(\n                    lower_bound, upper_bound, t, beta);\n        }\n\n    }; // class RealVariationalSolver\n\n} // namespace zsvm\n\n#endif // ZSVM_REAL_VARIATIONAL_SOLVER_HPP_INCLUDED\n", "meta": {"hexsha": "ee36114f37ce9dd2c7bd1b569c5678b83d4c3a06", "size": 7221, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RealVariationalSolver.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": "RealVariationalSolver.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": "RealVariationalSolver.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": 39.2445652174, "max_line_length": 80, "alphanum_fraction": 0.5247195679, "num_tokens": 1503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5601675030745262}}
{"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 /*!\n\n    @ingroup group-euler\n    Function object implementing stirling capabilities\n\n    Computes stirling formula for the gamma function\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = stirling(x);\n    @endcode\n\n    Computes  \\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    The formula implementation is usable for x between 33 and 172,\n    according cephes to approximate \\f$\\Gamma(x).\n\n    @see gamma, gammaln\n\n  **/\n  Value stirling(Value const & v0);\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": "e9df2b31eecf6453ad13362657f66f2badf71771", "size": 1230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/stirling.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party/boost/simd/function/stirling.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/stirling.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6, "max_line_length": 100, "alphanum_fraction": 0.5910569106, "num_tokens": 281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.5601596798907204}}
{"text": "//\n//  test_helib.cpp\n//  kcalg\n//\n//  Created by knightc on 2019/7/19.\n//  Copyright © 2019 knightc. All rights reserved.\n//\n\n#include \"opentsb/test.h\"\n\n#include <NTL/ZZ.h>\n\n#include <helib/FHEContext.h>\n#include <helib/EncryptedArray.h>\n#include <helib/FHE.h>\n#include <helib/DoubleCRT.h>\n\n#include <stack>\n#include <string>\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace NTL;\n\nstack<Ctxt> theStack;\nFHEcontext* context;\nFHESecKey* secretKey;\nFHEPubKey* publicKey;\nEncryptedArray* ea;\nZZX Gx;\n\nvoid setupHElib();\nbool isOp(string token);\nvoid evaluate(char op);\n\nvoid greeting(){\n    cout <<\"Welcome to the homomorphic encryption calculator\" <<endl;\n    cout <<\"Enter expression in reverse polish natation\"<<endl;\n    cout <<\"Enter q to quit\"<<endl;\n}\n\n\nvoid test_helib_all_main(){\n    \n    string token;\n    \n    greeting();\n    setupHElib();\n    ea = new EncryptedArray(*context, Gx);\n    \n    while(true){\n        \n        cin >> token;\n        \n        if(token[0] == 'q'){\n            break;\n        }\n        else if(isOp(token)){\n            if(theStack.size()<2){\n                cout << \"not enough numbers on the stack\"<<endl;\n            }\n            else{\n                evaluate(token[0]);\n            }\n        }\n        else{\n            Ctxt& c0= *(new Ctxt(*publicKey));\n            PlaintextArray p0(*ea);\n            encode(*ea,p0,atoi(token.data()));\n            ea->encrypt(c0, *publicKey, p0);\n            \n            theStack.push(c0);\n        }\n    }\n    \n    PlaintextArray p_decrypted(*ea);\n    ea->decrypt(theStack.top(), *secretKey, p_decrypted);\n    cout << \"The answer is: \";\n    p_decrypted.print(cout);\n    cout << endl;\n    \n}\n\n\nvoid setupHElib(){\n    long p=101;\n    long r=1;\n    long L=4;\n    long c=2;\n    long k=80;\n    long s=0;\n    long d=0;\n    long w=64;\n    long m=FindM(k,L,c,p,d,s,0);\n    \n    context = new FHEcontext(m,p,r);\n    buildModChain(*context, L, c);\n    Gx = context->alMod.getFactorsOverZZ()[0];\n    \n    secretKey = new FHESecKey(*context);\n    publicKey = secretKey;\n    \n    secretKey->GenSecKey(w);\n    addSome1DMatrices(*secretKey); // compute key-switching matrices that we need\n}\n\nbool isOp(string token){\n    return (token[0] == '+' || token[0] == '-' || token[0] == '*');\n}\n\nvoid evaluate(char op){\n    Ctxt *op1,*op2;\n    \n    switch(op) {\n        case '+':\n            op1 = new Ctxt(theStack.top()); theStack.pop();\n            op2 = new Ctxt(theStack.top()); theStack.pop();\n            (*op1) += (*op2);\n            theStack.push(*op1);\n            break;\n        case '-':\n            op1 = new Ctxt(theStack.top()); theStack.pop();\n            op2 = new Ctxt(theStack.top()); theStack.pop();\n            (*op1) -= (*op2);\n            theStack.push(*op1);\n            break;\n        case '*':\n            op1 = new Ctxt(theStack.top()); theStack.pop();\n            op2 = new Ctxt(theStack.top()); theStack.pop();\n            (*op1) *= (*op2);\n            theStack.push(*op1);\n            break;\n    }\n}\n", "meta": {"hexsha": "750b196fa17fdfab2e7ed1c904c55e04b397c496", "size": 2992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/sec/fe/helib/test_helib.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/sec/fe/helib/test_helib.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kcalg/sec/fe/helib/test_helib.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.162962963, "max_line_length": 81, "alphanum_fraction": 0.5340909091, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5600435597372304}}
{"text": "// Filename: matrix_free_cg.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\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    itl::pc::identity<matrix_type>            P(A);\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, iter);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "04d184756c53f816f0df9de44555b065b7487e7c", "size": 653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_free_cg.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_cg.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_cg.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.1851851852, "max_line_length": 75, "alphanum_fraction": 0.5604900459, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5600435557030045}}
{"text": "#include \"sigen/toolbox/toolbox.h\"\n#include \"sigen/common/disjoint_set.h\"\n#include \"sigen/common/math.h\"\n#include <algorithm>\n#include <boost/foreach.hpp>\n#include <boost/scoped_array.hpp>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <kdtree/kdtree.h>\n#include <limits>\n#include <map>\n#include <queue>\n#include <set>\n#include <utility>\n#include <vector>\nnamespace sigen {\nstatic double norm2(\n    const NeuronNodePtr &a,\n    const NeuronNodePtr &b) {\n  const double dx = std::abs(a->gx_ - b->gx_);\n  const double dy = std::abs(a->gy_ - b->gy_);\n  const double dz = std::abs(a->gz_ - b->gz_);\n  return std::sqrt(dx * dx + dy * dy + dz * dz);\n}\n\n// N = left.NumNodes()\n// M = right.NumNodes()\n// O(N*M)\nstatic std::pair<double, std::pair<int, int> > normNeuronFastPath(const Neuron &left, const Neuron &right) {\n  int l, r;\n  double minimum = std::numeric_limits<double>::max();\n  for (int i = 0; i < (int)left.NumNodes(); ++i) {\n    for (int j = 0; j < (int)right.NumNodes(); ++j) {\n      double d = norm2(left.storage_[i], right.storage_[j]);\n      if (minimum > d) {\n        minimum = d;\n        l = i;\n        r = j;\n      }\n    }\n  }\n  return std::make_pair(minimum, std::make_pair(l, r));\n}\n\n// N = left.NumNodes()\n// M = right.NumNodes()\n// O((N + M) log N)\n// Use https://github.com/jtsiomb/kdtree\nstatic std::pair<double, std::pair<int, int> > normNeuronSlowPath(const Neuron &left, const Neuron &right) {\n  kdtree *tree = kd_create(3);\n\n  boost::scoped_array<int> indexes(new int[left.NumNodes()]);\n  for (int i = 0; i < (int)left.NumNodes(); ++i) {\n    indexes[i] = i;\n    kd_insert3(\n        tree,\n        left.storage_[i]->gx_,\n        left.storage_[i]->gy_,\n        left.storage_[i]->gz_,\n        &indexes[i]);\n  }\n\n  int l, r;\n  double minimum = std::numeric_limits<double>::max();\n  for (int j = 0; j < (int)right.NumNodes(); ++j) {\n    kdres *set = kd_nearest3(\n        tree,\n        right.storage_[j]->gx_,\n        right.storage_[j]->gy_,\n        right.storage_[j]->gz_);\n    int i = *(int *)kd_res_item_data(set);\n    kd_res_free(set);\n    double d = norm2(left.storage_[i], right.storage_[j]);\n    if (minimum > d) {\n      minimum = d;\n      l = i;\n      r = j;\n    }\n  }\n\n  kd_free(tree);\n  return std::make_pair(minimum, std::make_pair(l, r));\n}\n\nstatic std::pair<double, std::pair<int, int> > normNeuron(const Neuron &left, const Neuron &right) {\n  assert(!left.IsEmpty());\n  assert(!right.IsEmpty());\n  if (std::min(left.NumNodes(), right.NumNodes()) >= 300) {\n    return normNeuronSlowPath(left, right);\n  } else {\n    return normNeuronFastPath(left, right);\n  }\n}\n\nstd::vector<Neuron> Interpolate(const std::vector<Neuron> &input, const double dt, const int vt) {\n  const int N = input.size();\n  std::vector<Neuron> forest;\n  for (int i = 0; i < N; ++i) {\n    forest.push_back(input[i].Clone());\n  }\n  DisjointSet<int> set;\n  std::vector<bool> is_not_small(forest.size(), false);\n  for (int i = 0; i < N; ++i) {\n    if (forest[i].NumNodes() >= vt) {\n      set.Add(i);\n      is_not_small[i] = true;\n    }\n  }\n  set.SetUp();\n\n  typedef std::pair<double, std::pair<int, int> > priorityQueueNode;\n  std::priority_queue<\n      priorityQueueNode,\n      std::vector<priorityQueueNode>,\n      std::greater<priorityQueueNode> >\n      pq;\n\n  std::vector<std::map<int, double> > distance(N);\n\n  for (int i = 0; i < N; ++i) {\n    if (is_not_small[i]) {\n      for (int j = i + 1; j < N; ++j) {\n        if (is_not_small[j]) {\n          assert(i != j);\n          double d = normNeuron(forest[i], forest[j]).first;\n          if (d <= dt) {\n            pq.push(std::make_pair(d, std::make_pair(i, j)));\n            distance[i][j] = d;\n            distance[j][i] = d;\n          }\n        }\n      }\n    }\n  }\n  while (!pq.empty()) {\n    priorityQueueNode node = pq.top();\n    pq.pop();\n    int l = node.second.first;\n    int r = node.second.second;\n    if (forest[l].IsEmpty())\n      continue;\n    if (forest[r].IsEmpty())\n      continue;\n    if (set.IsSame(l, r))\n      continue;\n    std::pair<double, std::pair<int, int> > dist = normNeuron(forest[l], forest[r]);\n    set.Merge(l, r);\n    forest[l].ConnectToOtherNeuron(dist.second.first, forest[r], dist.second.second);\n    forest[r].ConnectToOtherNeuron(dist.second.second, forest[l], dist.second.first);\n    forest[l].Extend(forest[r]);\n    forest[r].Clear();\n\n    for (std::map<int, double>::iterator it = distance[r].begin(); it != distance[r].end(); ++it) {\n      int i = it->first;\n      double d = it->second;\n      assert(is_not_small[i]);\n      if (set.IsSame(l, i) == false && forest[i].IsEmpty() == false) {\n        if (distance[l].count(i)) {\n          distance[l][i] = std::min(distance[l][i], d);\n        } else {\n          distance[l][i] = d;\n        }\n\n        if (distance[i].count(l)) {\n          distance[i][l] = std::min(distance[i][l], d);\n        } else {\n          distance[i][l] = d;\n        }\n\n        pq.push(std::make_pair(d, std::make_pair(l, i)));\n      }\n    }\n  }\n  for (int i = 0; i < (int)forest.size(); ++i) {\n    if (forest[i].IsEmpty()) {\n      forest.erase(forest.begin() + i);\n      i--;\n    }\n  }\n  return forest;\n}\n\nstruct PointAndRadius {\n  double gx_, gy_, gz_, radius_;\n  void setCoord(const double gx, const double gy, const double gz) {\n    gx_ = gx;\n    gy_ = gy;\n    gz_ = gz;\n  }\n};\n\nstd::vector<Neuron> Smoothing(const std::vector<Neuron> &input, const int n_iter) {\n  std::vector<Neuron> forest;\n  for (int i = 0; i < (int)input.size(); ++i) {\n    forest.push_back(input[i].Clone());\n  }\n  for (int iter = 0; iter < n_iter; ++iter) {\n    std::map<int, PointAndRadius> next_value;\n    for (int i = 0; i < (int)forest.size(); ++i) {\n      BOOST_FOREACH (NeuronNodePtr node, forest[i].storage_) {\n        std::vector<double> gx, gy, gz, radius;\n        gx.push_back(node->gx_);\n        gy.push_back(node->gy_);\n        gz.push_back(node->gz_);\n        radius.push_back(node->radius_);\n        BOOST_FOREACH (NeuronNode *adj, node->adjacent_) {\n          gx.push_back(adj->gx_);\n          gy.push_back(adj->gy_);\n          gz.push_back(adj->gz_);\n          radius.push_back(adj->radius_);\n        }\n        PointAndRadius next_node;\n        next_node.setCoord(Mean(gx), Mean(gy), Mean(gz));\n        next_node.radius_ = Mean(radius);\n        next_value[node->id_] = next_node;\n      }\n    }\n    for (int i = 0; i < (int)forest.size(); ++i) {\n      BOOST_FOREACH (NeuronNodePtr node, forest[i].storage_) {\n        PointAndRadius next_node = next_value[node->id_];\n        node->setCoord(next_node.gx_, next_node.gy_, next_node.gz_);\n        node->radius_ = next_node.radius_;\n      }\n    }\n  }\n  return forest;\n}\n\n// return max_height\nstatic int clippingDfs(\n    NeuronNode *node,\n    NeuronNode *parent,\n    const int level,\n    std::set<int> &will_remove,\n    std::map<NeuronNode *, int> &memo) {\n  if (memo.count(node))\n    return memo[node];\n  if (node->CountNumChild(parent) < 2) {\n    // If count_num_child == 1\n    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {\n      if (next != parent) {\n        return memo[node] = clippingDfs(next, node, level, will_remove, memo) + 1;\n      }\n    }\n    // If count_num_child == 0\n    return 1;\n  }\n  int has_longpath = 0;\n  BOOST_FOREACH (NeuronNode *next, node->adjacent_) {\n    if (next != parent) {\n      int depth = clippingDfs(next, node, level, will_remove, memo);\n      if (depth > level)\n        has_longpath = true;\n    }\n  }\n  if (has_longpath) {\n    int maxdepth = 0;\n    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {\n      if (next != parent) {\n        int depth = clippingDfs(next, node, level, will_remove, memo);\n        if (depth <= level) {\n          will_remove.insert(next->id_);\n        }\n        maxdepth = std::max(maxdepth, depth);\n      }\n    }\n    return memo[node] = maxdepth + 1;\n  } else {\n    int maxdepth = 0;\n    NeuronNode *longest_child = NULL;\n    BOOST_FOREACH (NeuronNode *next, node->adjacent_) {\n      if (next != parent) {\n        int depth = clippingDfs(next, node, level, will_remove, memo);\n        if (maxdepth < depth) {\n          maxdepth = depth;\n          longest_child = next;\n        }\n      }\n    }\n    if (maxdepth > 0) {\n      BOOST_FOREACH (NeuronNode *next, node->adjacent_) {\n        if (next != parent && next != longest_child) {\n          will_remove.insert(next->id_);\n        }\n      }\n    }\n    return memo[node] = maxdepth + 1;\n  }\n}\n\nstd::vector<Neuron> Clipping(const std::vector<Neuron> &input, const int level) {\n  std::set<int> will_remove;\n  std::vector<Neuron> forest;\n  std::map<NeuronNode *, int> memo;\n  for (int i = 0; i < (int)input.size(); ++i) {\n    forest.push_back(input[i].Clone());\n    clippingDfs(forest[i].get_root(), NULL, level, will_remove, memo);\n  }\n  for (int i = 0; i < (int)forest.size(); ++i) {\n    forest[i].RemoveConnections(will_remove);\n  }\n  return forest;\n}\n} // namespace sigen\n", "meta": {"hexsha": "a3d8743210437cf22fac1abb33900431948f98eb", "size": 8856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "released_plugins/v3d_plugins/bigneuron_hide_ikeno_SIGEN/src/sigen/toolbox/toolbox.cpp", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/bigneuron_hide_ikeno_SIGEN/src/sigen/toolbox/toolbox.cpp", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/bigneuron_hide_ikeno_SIGEN/src/sigen/toolbox/toolbox.cpp", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["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.9411764706, "max_line_length": 108, "alphanum_fraction": 0.5782520325, "num_tokens": 2594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.559959562292977}}
{"text": "/*\n * \n * Copyright Jeremy Conlin 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\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_HSEQR_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_HSEQR_HPP\n\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/matrix_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\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    // Compute eigenvalues of an Hessenberg matrix, H.\n    // \n    ///////////////////////////////////////////////////////////////////\n\n    /* \n     * hseqr() computes the eigenvalues of a Hessenberg matrix H\n     * and, optionally, the matrices T and Z from the Schur decomposition\n     * H = Z U Z**T, where U is an upper quasi-triangular matrix (the\n     * Schur form), and Z is the orthogonal matrix of Schur vectors.\n     *\n     * Optionally Z may be postmultiplied into an input orthogonal\n     * matrix Q so that this routine can give the Schur factorization\n     * of a matrix A which has been reduced to the Hessenberg form H\n     * by the orthogonal matrix Q:  A = Q*H*Q**T = (QZ)*U*(QZ)**T.\n     * \n     * There are two forms of the hseqr function:\n     *\n     * int hseqr( const char job, A& H, W& w)\n     * int hseqr( const char job, const char compz, A& H, W& w, Z& z)\n     *\n     * The first form does not compute Schur vectors and is equivelant to\n     * setting compz = 'N' in the second form.  hseqr returns a '0' if the\n     * computation is successful.\n     *\n     * job.\n     *   = 'E': compute eigenvalues only\n     *   = 'S': compute eigenvalues and the Schur form U\n     *\n     * compz. (input)\n     *   = 'N':  no Schur vectors are computed;  Equivalent to using the\n     *           first form of the hseqr function.\n     *   = 'I':  Z is initialized to the unit matrix and the matrix Z\n     *           of Schur vectors of H is returned;\n     *   = 'V':  Z must contain an orthogonal matrix Q on entry, and\n     *           the product Q*Z is returned.\n     * \n     * H is the Hessenberg matrix whose eigenpairs you're interested \n     * in. (input/output) On exit, if computation is successful and \n     * job = 'S', then H contains the\n     * upper quasi-triangular matrix U from the Schur decomposition\n     * (the Schur form); 2-by-2 diagonal blocks (corresponding to\n     * complex conjugate pairs of eigenvalues) are returned in\n     * standard form, with H(i,i) = H(i+1,i+1) and\n     * H(i+1,i)*H(i,i+1) < 0. If computation is successful and \n     * job = 'E', the contents of H are unspecified on exit.  \n     *\n     * w (output) contains the computed eigenvalues of H which is the diagonal \n     * of U. Must be a complex object.\n     *\n     * Z. (input/output)\n     * If compz = 'N', Z is not referenced.\n     * If compz = 'I', on entry Z need not be set and on exit,\n     * if computation is successful, Z contains the orthogonal matrix Z of the Schur\n     * vectors of H.  If compz = 'V', on entry Z must contain an\n     * N-by-N matrix Q, which is assumed to be equal to the unit\n     * matrix . On exit, if computation is successful, Z contains Q*Z.\n     *\n     */ \n\n    namespace detail {\n        // float\n        inline\n        int hseqr_backend(const char* job, const char* compz, const int* n, \n                const int ilo, const int ihi, float* H, const int ldH, \n                float* wr, float* wi, float* Z, const int ldz, float* work,\n                const int* lwork){\n            int info;\n//          std::cout << \"I'm inside lapack::detail::hseqr_backend for floats\" \n//              << std::endl;\n            LAPACK_SHSEQR(job, compz, n, &ilo, &ihi, H, &ldH, wr, wi, \n                    Z, &ldz, work, lwork, &info);\n            return info;\n        }\n\n        // double\n        inline\n        int hseqr_backend(const char* job, const char* compz, const int* n, \n                const int ilo, const int ihi, double* H, const int ldH, \n                double* wr, double* wi, double* Z, const int ldz, double* work,\n                const int* lwork){\n            int info;\n//          std::cout << \"I'm inside lapack::detail::hseqr_backend for doubles\" \n//              << std::endl;\n            LAPACK_DHSEQR(job, compz, n, &ilo, &ihi, H, &ldH, wr, wi, \n                    Z, &ldz, work, lwork, &info);\n            return info;\n        }\n\n        // complex<float>\n        inline\n        int hseqr_backend(const char* job, const char* compz, int* n, \n                const int ilo, const int ihi, traits::complex_f* H, const int ldH, \n                traits::complex_f* w, traits::complex_f* Z, int ldz, \n                traits::complex_f* work, const int* lwork){\n            int info;\n//          std::cout << \"I'm inside lapack::detail::hseqr_backend for complex<float>\" \n//              << std::endl;\n            LAPACK_CHSEQR(job, compz, n, &ilo, &ihi, \n                    traits::complex_ptr(H), &ldH, \n                    traits::complex_ptr(w), \n                    traits::complex_ptr(Z), &ldz, \n                    traits::complex_ptr(work), lwork, &info);\n            return info;\n        }\n\n        // complex<double>\n        inline\n        int hseqr_backend(const char* job, const char* compz, int* n, \n                const int ilo, const int ihi, traits::complex_d* H, const int ldH, \n                traits::complex_d* w, traits::complex_d* Z, int ldz, \n                traits::complex_d* work, const int* lwork){\n            int info;\n//          std::cout << \"I'm inside lapack::detail::hseqr_backend for complex<double>\" \n//              << std::endl;\n            LAPACK_ZHSEQR(job, compz, n, &ilo, &ihi, \n                    traits::complex_ptr(H), &ldH, \n                    traits::complex_ptr(w), \n                    traits::complex_ptr(Z), &ldz, \n                    traits::complex_ptr(work), lwork, &info);\n            return info;\n        }\n\n        template <int N>\n        struct Hseqr{};\n\n        template <>\n        struct Hseqr< 1 >{\n            template < typename A, typename W, typename V>\n            int operator() ( const char job, const char compz, A& H, W& w, V& Z ){\n//              std::cout << \"Inside Hseqr<1>.\" << std::endl;\n\n                int n = traits::matrix_size1(H);\n                typedef typename A::value_type value_type;\n                traits::detail::array<value_type> wr(n);\n                traits::detail::array<value_type> wi(n);\n\n                // workspace query\n                int lwork = -1;\n                value_type work_temp;\n                int result = detail::hseqr_backend(&job, &compz, &n, 1, n,\n                                            traits::matrix_storage(H), \n                                            traits::leading_dimension(H),\n                                            wr.storage(), wi.storage(),\n                                            traits::matrix_storage(Z),\n                                            traits::leading_dimension(Z),\n                                            &work_temp, &lwork);\n\n                if( result !=0 ) return result;\n\n                lwork = (int) work_temp;\n                traits::detail::array<value_type> work(lwork);\n                result = detail::hseqr_backend(&job, &compz, &n, 1, n,\n                                            traits::matrix_storage(H), \n                                            traits::leading_dimension(H),\n                                            wr.storage(), wi.storage(),\n                                            traits::matrix_storage(Z),\n                                            traits::leading_dimension(Z),\n                                            work.storage(), &lwork);\n\n                for (int i = 0; i < n; i++)\n                    w[i] = std::complex<value_type>(wr[i], wi[i]);\n\n                return result;\n            }\n        };\n\n        template <>\n        struct Hseqr< 2 >{\n            template < typename A, typename W, typename V>\n            int operator() ( const char job, const char compz, A& H, W& w, V& Z ){\n//              std::cout << \"Inside Hseqr<2>.\" << std::endl;\n\n                int n = traits::matrix_size1(H);\n                typedef typename A::value_type value_type;\n\n                // workspace query\n                int lwork = -1;\n                value_type work_temp;\n                int result = detail::hseqr_backend(&job, &compz, &n, 1, n,\n                        traits::matrix_storage(H),\n                        traits::leading_dimension(H), \n                        traits::vector_storage(w),\n                        traits::matrix_storage(Z), traits::leading_dimension(Z),\n                        &work_temp, &lwork);\n\n                if( result !=0 ) return result;\n\n                lwork = (int) std::real(work_temp);\n                traits::detail::array<value_type> work(lwork);\n                result = detail::hseqr_backend(&job, &compz, &n, 1, n,\n                        traits::matrix_storage(H),\n                        traits::leading_dimension(H), \n                        traits::vector_storage(w),\n                        traits::matrix_storage(Z), traits::leading_dimension(Z),\n                        work.storage(), &lwork);\n\n                return result;\n            }\n        };\n        \n        template < typename A, typename W, typename V>\n        int hseqr( const char job, const char compz, A& H, W& w, V& Z ){\n//          std::cout << \"I'm inside lapack::detail::hseqr.\" << std::endl;\n\n            assert ( job == 'E' || job == 'S' );\n            assert ( compz == 'N' || compz == 'I' || compz == 'V' );\n\n            typedef typename A::value_type value_type;\n\n            int result = detail::Hseqr< n_workspace_args<value_type>::value >()(\n                    job, compz, H, w, Z);\n\n            return result;\n        }\n    }   // namespace detail \n\n    // Compute eigenvalues without the Schur vectors\n    template < typename A, typename W>\n    int hseqr( const char job, A& H, W& w){\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(H);\n#endif\n\n        typedef typename A::value_type value_type;\n        typedef typename W::value_type complex_value_type;\n\n        assert(traits::matrix_size2(H) == n); // Square matrix\n        assert(traits::vector_size(w) == n);  \n\n        ublas::matrix<value_type, ublas::column_major> Z(1,1);\n        return detail::hseqr( job, 'N', H, w, Z );\n    }\n\n    // Compute eigenvalues and the Schur vectors\n    template < typename A, typename W, typename Z>\n    int hseqr( const char job, const char compz, A& H, W& w, Z& z){\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(H);\n#endif\n\n        typedef typename A::value_type value_type;\n        assert(traits::matrix_size2(H) == n); // Square matrix\n        assert(traits::vector_size(w) == n);  \n        assert(traits::matrix_size2(z) == n);\n\n        return detail::hseqr( job, compz, H, w, z );\n    }\n\n  }\n}}}\n\n#endif\n", "meta": {"hexsha": "3a43b55d48e7a0cebe53920b29beb52f68d7fc62", "size": 11875, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/bindings/lapack/hseqr.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/hseqr.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/hseqr.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": 39.1914191419, "max_line_length": 88, "alphanum_fraction": 0.5328842105, "num_tokens": 2908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.5599569679683342}}
{"text": "//\n// Copyright Chong Peng 2017\n//\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"type_traits.h\"\n#include \"std_vector_interface.h\"\n#include \"symm_davidson_diag.h\"\n#include \"nonsymm_davidson_diag.h\"\n\nusing namespace code_example;\n\nint main() {\n\n  std::cout.precision(12);\n\n  std::cout << \"Nonsymmetric Davidson Diagnolization Using std::vector \\n\";\n\n  /// typedef the Array type to use\n  using Array = std::vector<double>;\n\n  // variables\n  const std::size_t n = 200;\n  const double sparse = 0.1;\n  const std::size_t n_roots = 5;   // number of roots to solve in davidson\n  const double converge = 1.0e-10; // convergence threshold in davidson\n  const std::size_t max_iter = 100; // max iteration in davidson\n\n  // initialize symmetric matrix\n  ColMatrix<double> A = ColMatrix<double>::Zero(n, n);\n  for (auto i = 0; i < n; i++) {\n    A(i, i) = i + 1;\n  }\n  A = A + sparse * ColMatrix<double>::Random(n, n);\n\n  EigenVector<double> A_diagonal = A.diagonal();\n  // eigen solve\n  Eigen::EigenSolver<ColMatrix<double>> es(A);\n\n  EigenVector<double> e = es.eigenvalues().real();\n  std::sort(e.data(), e.data()+e.size());\n  e = e.segment(0,n_roots);\n\n  std::cout << \"Reference Result from EigenSolve: \" << std::endl\n            << e << std::endl;\n\n  /// construct the SymmDavidsonDiag  object\n  NonSymmDavidsonDiag<Array> dvd(n_roots);\n\n  /// make the initial guess use unit vector\n  std::vector<Array> guess(n_roots);\n  {\n    for (std::size_t i = 0; i < n_roots; i++) {\n      guess[i] = Array(n, 0.0);\n      guess[i][i] = 1;\n    }\n  }\n\n  /// make the preconditioner\n\n  auto pred = [&A_diagonal](const EigenVector<double> &e,\n                            std::vector<Array> &guess) {\n\n    for (std::size_t i = 0; i < guess.size(); i++) {\n      const auto ei = e[i];\n      auto &guess_i = guess[i];\n      const auto n_r = guess_i.size();\n      for (std::size_t i = 0; i < n_r; i++) {\n        guess_i[i] = guess_i[i] / (ei - A_diagonal[i]);\n      }\n    }\n\n  };\n\n  /// make the operator\n  auto op = [&A,n](const std::vector<Array> &vec) {\n    const std::size_t n_vec = vec.size();\n\n    std::vector<Array> HC(n_vec);\n\n    const char trans = 'N';\n    const int32_t rows = A.rows();\n    const int32_t cols = A.cols();\n    const double alpha = 1.0;\n    const double beta = 0.0;\n    const int32_t inc = 1;\n    for (std::size_t i = 0; i < n_vec; i++) {\n      HC[i] = Array(vec[i].size(), 0.0);\n      dgemv_(&trans, &rows, &cols, &alpha, A.data(), &rows, vec[i].data(), &inc,\n             &beta, HC[i].data(), &inc);\n    }\n\n    return HC;\n  };\n\n  /// solve\n\n  auto eig = dvd.solve(guess, op, pred, converge, max_iter);\n\n  std::cout << \"NonSymmDavidsonDiag result: \" << std::endl;\n  std::cout << eig << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "312a0f6fcffb926ff87a4efc77660e37507d861b", "size": 2718, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "std_vector_test.cpp", "max_stars_repo_name": "pchong90/CodeExample", "max_stars_repo_head_hexsha": "0a89ad52cb2d4f616513a5ef389a2a72dd7765aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "std_vector_test.cpp", "max_issues_repo_name": "pchong90/CodeExample", "max_issues_repo_head_hexsha": "0a89ad52cb2d4f616513a5ef389a2a72dd7765aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "std_vector_test.cpp", "max_forks_repo_name": "pchong90/CodeExample", "max_forks_repo_head_hexsha": "0a89ad52cb2d4f616513a5ef389a2a72dd7765aa", "max_forks_repo_licenses": ["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.4018691589, "max_line_length": 80, "alphanum_fraction": 0.5956585725, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.559948651406804}}
{"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__IMPL__SE3_HPP_\n#define SMOOTH__IMPL__SE3_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n#include \"so3.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief SE(3) Lie Group represented as S^3 ⋉ R3\n *\n * Memory layout\n * -------------\n * Group:    x y z qx qy qz qw\n * Tangent:  vx vy vz Ωx Ωy Ωz\n *\n * Lie group Matrix form\n * ---------------------\n * [ R T ]\n * [ 0 1 ]\n *\n * where R ∈ SO(3) and T = [x y z] ∈ R3\n *\n * Lie algebra Matrix form\n * -----------------------\n * [  0 -Ωz  Ωy vx]\n * [  Ωz  0 -Ωx vy]\n * [ -Ωy Ωx   0 vz]\n * [   0  0   0  0]\n *\n * Constraints\n * -----------\n * Group:   qx * qx + qy * qy + qz * qz + qw * qw = 1\n * Tangent: -pi < Ωx Ωy Ωz <= pi\n */\ntemplate<typename _Scalar>\nclass SE3Impl\n{\npublic:\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index RepSize = 7;\n  static constexpr Eigen::Index Dim     = 4;\n  static constexpr Eigen::Index Dof     = 6;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out)\n  {\n    g_out.template head<6>().setZero();\n    g_out(6) = Scalar(1);\n  }\n\n  static void setRandom(GRefOut g_out)\n  {\n    g_out.template head<3>().setRandom();\n    SO3Impl<Scalar>::setRandom(g_out.template tail<4>());\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    m_out.setIdentity();\n    SO3Impl<Scalar>::matrix(g_in.template tail<4>(), m_out.template topLeftCorner<3, 3>());\n    m_out.template topRightCorner<3, 1>() = g_in.template head<3>();\n  }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    SO3Impl<Scalar>::composition(\n      g_in1.template tail<4>(), g_in2.template tail<4>(), g_out.template tail<4>());\n    Eigen::Matrix<Scalar, 3, 3> R1;\n    SO3Impl<Scalar>::matrix(g_in1.template tail<4>(), R1);\n    g_out.template head<3>() = R1 * g_in2.template head<3>() + g_in1.template head<3>();\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    Eigen::Matrix<Scalar, 4, 1> so3inv;\n    SO3Impl<Scalar>::inverse(g_in.template tail<4>(), so3inv);\n\n    Eigen::Matrix<Scalar, 3, 3> Rinv;\n    SO3Impl<Scalar>::matrix(so3inv, Rinv);\n\n    g_out.template head<3>() = -Rinv * g_in.template head<3>();\n    g_out.template tail<4>() = so3inv;\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    using SO3TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n\n    SO3Impl<Scalar>::log(g_in.template tail<4>(), a_out.template tail<3>());\n\n    SO3TangentMap M_dr_expinv, M_ad;\n    SO3Impl<Scalar>::dr_expinv(a_out.template tail<3>(), M_dr_expinv);\n    SO3Impl<Scalar>::ad(a_out.template tail<3>(), M_ad);\n    a_out.template head<3>() = (-M_ad + M_dr_expinv) * g_in.template head<3>();\n  }\n\n  static void Ad(GRefIn g_in, TMapRefOut A_out)\n  {\n\n    SO3Impl<Scalar>::matrix(g_in.template tail<4>(), A_out.template topLeftCorner<3, 3>());\n    SO3Impl<Scalar>::hat(g_in.template head<3>(), A_out.template topRightCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>() *= A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    using SO3TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n\n    SO3Impl<Scalar>::exp(a_in.template tail<3>(), g_out.template tail<4>());\n\n    SO3TangentMap M_dr_exp, M_Ad;\n    SO3Impl<Scalar>::dr_exp(a_in.template tail<3>(), M_dr_exp);\n    SO3Impl<Scalar>::Ad(g_out.template tail<4>(), M_Ad);\n\n    g_out.template head<3>() = M_Ad * M_dr_exp * a_in.template head<3>();\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out.setZero();\n    SO3Impl<Scalar>::hat(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 1>() = a_in.template head<3>();\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    SO3Impl<Scalar>::vee(A_in.template topLeftCorner<3, 3>(), a_out.template tail<3>());\n    a_out.template head<3>() = A_in.template topRightCorner<3, 1>();\n  }\n\n  static void ad(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::hat(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    SO3Impl<Scalar>::hat(a_in.template head<3>(), A_out.template topRightCorner<3, 3>());\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static Eigen::Matrix<Scalar, 3, 3> calculate_q(TRefIn a)\n  {\n    using std::abs, std::sqrt, std::cos, std::sin;\n\n    const Scalar th2 = a.template tail<3>().squaredNorm();\n\n    Scalar A, B, C;\n    if (th2 < Scalar(eps2)) {\n      // https://www.wolframalpha.com/input/?i=series+%28x+-+sin+x%29+%2F+x%5E3+at+x%3D0\n      A = Scalar(1) / Scalar(6) - th2 / Scalar(120);\n      // https://www.wolframalpha.com/input/?i=series+%28cos+x+-+1+%2B+x%5E2%2F2%29+%2F+x%5E4+at+x%3D0\n      B = Scalar(1) / Scalar(24) - th2 / Scalar(720);\n      // https://www.wolframalpha.com/input/?i=series+%28x+-+sin+x+-+x%5E3%2F6%29+%2F+x%5E5+at+x%3D0\n      C = -Scalar(1) / Scalar(120) + th2 / Scalar(5040);\n    } else {\n      const Scalar th = sqrt(th2), th_4 = th2 * th2, cTh = cos(th), sTh = sin(th);\n      A = (th - sTh) / (th * th2);\n      B = (cTh - Scalar(1) + th2 / Scalar(2)) / th_4;\n      C = (th - sTh - th * th2 / Scalar(6)) / (th_4 * th);\n    }\n\n    Eigen::Matrix<Scalar, 3, 3> V, W;\n    SO3Impl<Scalar>::hat(a.template head<3>(), V);\n    SO3Impl<Scalar>::hat(a.template tail<3>(), W);\n\n    const Scalar vdw                     = a.template tail<3>().dot(a.template head<3>());\n    const Eigen::Matrix<Scalar, 3, 3> WV = W * V, VW = V * W, WW = W * W;\n\n    return Scalar(0.5) * V + A * (WV + VW - vdw * W)\n         + B * (W * WV + VW * W + vdw * (Scalar(3) * W - WW)) - C * Scalar(3) * vdw * WW;\n  }\n\n  static void dr_exp(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::dr_exp(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>()    = calculate_q(-a_in);\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static void dr_expinv(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::dr_expinv(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>() = -A_out.template topLeftCorner<3, 3>()\n                                          * calculate_q(-a_in)\n                                          * A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__IMPL__SE3_HPP_\n", "meta": {"hexsha": "d602645ccbc22e042f3172a73be6cf2c36d28c00", "size": 7890, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/se3.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/se3.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/se3.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.0666666667, "max_line_length": 102, "alphanum_fraction": 0.637896071, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5599461752392538}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include \"tsai.hpp\"\n\n#ifdef USEVISP\n#include <visp/vpCalibration.h>\n#include <visp/vpMath.h>\n#include <visp/vpPose.h>\n#include <visp/vpPixelMeterConversion.h>\n#endif\n//using LTD = SE3dist<float>;\nusing LTD = float;\n\n#ifdef USEVISP\n\n\nvoid assign(Eigen::Matrix4f & a, const \tvpHomogeneousMatrix & b)\n{\n\tvpQuaternionVector q;\n\tvpTranslationVector t;\n\tb.extract(q);\n\tb.extract(t);\n\tEigen::Vector3f et(t[0],t[1],t[2]);\n\tEigen::Quaternionf eq(q.w(),q.x(),q.y(),q.z());\n\ta.setIdentity();\n\ta.block<3,3>(0,0) = Eigen::Matrix3f(eq);\n\ta.block<3,1>(0,3) = et;\n}\n\nvoid assign(vpHomogeneousMatrix & b,const Eigen::Matrix4f & a)\n{\n\tEigen::Quaternionf eq(Eigen::Matrix3f(a.block<3,3>(0,0)));\n\tEigen::Vector3f et = a.block<3,1>(0,3);\n\n\tvpQuaternionVector q(eq.x(),eq.y(),eq.z(),eq.w());\n\tvpTranslationVector t(et.x(),et.y(),et.z());\n\tb.buildFrom(t,q);\n}\n\n\n\nvoid calibrationTsai(std::vector<vpHomogeneousMatrix>& cMo,\n\t\t\t\t\t\tstd::vector<vpHomogeneousMatrix>& rMe,\n\t\t\t\t\t\tvpHomogeneousMatrix &eMc){\n\n  vpColVector x ;\n  unsigned int nbPose = (unsigned int)cMo.size();\n  if(cMo.size()!=rMe.size()) throw vpCalibrationException(vpCalibrationException::dimensionError,\"cMo and rMe have different sizes\");\n  {\n    vpMatrix A ;\n    vpColVector B ;\n    unsigned int k = 0 ;\t\n    // for all couples ij\n    for (unsigned int i=0 ; i < nbPose ; i++)\n    {\n      vpRotationMatrix rRei, ciRo ;\n      rMe[i].extract(rRei) ;\n      cMo[i].extract(ciRo) ;\n      //std::cout << \"rMei: \" << std::endl << rMe[i] << std::endl;\n\n      for (unsigned int j=i+1; j < nbPose ; j++)\n      {\n        {\n          vpRotationMatrix rRej, cjRo ;\n          rMe[j].extract(rRej) ;\n          cMo[j].extract(cjRo) ;\n\t  //std::cout << \"rMej: \" << std::endl << rMe[j] << std::endl;\n\n          vpRotationMatrix rReij = rRej.t() * rRei;\n\n          vpRotationMatrix cijRo = cjRo * ciRo.t();\n\n          vpThetaUVector rPeij(rReij);\n\n          double theta = sqrt(rPeij[0]*rPeij[0] + rPeij[1]*rPeij[1]\n                              + rPeij[2]*rPeij[2]);\n\n          for (unsigned int m=0;m<3;m++) rPeij[m] = rPeij[m] * vpMath::sinc(theta/2);\n\n          vpThetaUVector cijPo(cijRo) ;\n          theta = sqrt(cijPo[0]*cijPo[0] + cijPo[1]*cijPo[1]\n                       + cijPo[2]*cijPo[2]);\n          for (unsigned int m=0;m<3;m++) cijPo[m] = cijPo[m] * vpMath::sinc(theta/2);\n\n          vpMatrix As;\n          vpColVector b(3) ;\n\n          As = vpColVector::skew(vpColVector(rPeij) + vpColVector(cijPo)) ;\n\n          b =  (vpColVector)cijPo - (vpColVector)rPeij ;           // A.40\n\n          if (k==0)\n          {\n            A = As ;\n            B = b ;\n#if 0           \n            auto w = rReij.t();\n            std::cout << \"rPeij0 R\\n\";\n            std::cout << w.getCol(0) << \"\\n\" << w.getCol(1) << \"\\n\" << w.getCol(2) << std::endl;\n            std::cout << \"rPeij0 is \" << rPeij[0] << \" \" << rPeij[1] << \" \" << rPeij[2] << std::endl;\n            std::cout << \"cijPo0 is \" << cijPo[0] << \" \" << cijPo[1] << \" \" << cijPo[2] << std::endl;\n            std::cout << \"As0 is \\n \"; \n            As.csvPrint (std::cout);\n            std::cout<< \"b0 \" << b[0] << \" \" << b[1] << \" \" << b[2] << std::endl;\n#endif\n          }\n          else\n          {\n            A = vpMatrix::stack(A,As) ;\n            B = vpColVector::stack(B,b) ;\n          }\n          k++ ;\n        }\n      }\n    }\n\t\n    // the linear system is defined\n    // x = AtA^-1AtB is solved\n    vpMatrix AtA = A.AtA() ;\n\n    vpMatrix Ap ;\n    AtA.pseudoInverse(Ap, 1e-6) ; // rank 3\n    x = Ap*A.t()*B ;\n\n//     {\n//       // Residual\n//       vpColVector residual;\n//       residual = A*x-B;\n//       std::cout << \"Residual: \" << std::endl << residual << std::endl;\n\n//       double res = 0;\n//       for (int i=0; i < residual.getRows(); i++)\n// \tres += residual[i]*residual[i];\n//       res = sqrt(res/residual.getRows());\n//       printf(\"Mean residual = %lf\\n\",res);\n//     }\n\n    // extraction of theta and U\n    double theta ;\n    double   d=x.sumSquare() ;\n    for (unsigned int i=0 ; i < 3 ; i++) x[i] = 2*x[i]/sqrt(1+d) ;\n    theta = sqrt(x.sumSquare())/2 ;\n    theta = 2*asin(theta) ;\n    //if (theta !=0)\n    if (std::fabs(theta) > std::numeric_limits<double>::epsilon())\n    {\n      for (unsigned int i=0 ; i < 3 ; i++) x[i] *= theta/(2*sin(theta/2)) ;\n    }\n    else\n      x = 0 ;\n  }\n\n  // Building of the rotation matrix eRc\n  vpThetaUVector xP(x[0],x[1],x[2]);\n  vpRotationMatrix eRc(xP);\n\n  {\n    vpMatrix A ;\n    vpColVector B ;\n    // Building of the system for the translation estimation\n    // for all couples ij\n    vpRotationMatrix I3 ;\n    I3.eye() ;\n    int k = 0 ;\n    for (unsigned int i=0 ; i < nbPose ; i++)\n    {\n      vpRotationMatrix rRei, ciRo ;\n      vpTranslationVector rTei, ciTo ;\n      rMe[i].extract(rRei) ;\n      cMo[i].extract(ciRo) ;\n      rMe[i].extract(rTei) ;\n      cMo[i].extract(ciTo) ;\n\n\n      for (unsigned int j=i+1 ; j < nbPose ; j++)\n      {\n        {\n\n          vpRotationMatrix rRej, cjRo ;\n          rMe[j].extract(rRej) ;\n          cMo[j].extract(cjRo) ;\n\n          vpTranslationVector rTej, cjTo ;\n          rMe[j].extract(rTej) ;\n          cMo[j].extract(cjTo) ;\n\n          vpRotationMatrix rReij = rRej.t() * rRei ;\n\n          vpTranslationVector rTeij = rTej+ (-rTei);\n\n          rTeij = rRej.t()*rTeij ;\n\n          vpMatrix a = vpMatrix(rReij) - vpMatrix(I3);\n\n          vpTranslationVector b ;\n          b = eRc*cjTo - rReij*eRc*ciTo + rTeij ;\n\n          if (k==0)\n          {\n            A = a ;\n            B = b ;\n          }\n          else\n          {\n            A = vpMatrix::stack(A,a) ;\n            B = vpColVector::stack(B,b) ;\n          }\n          k++ ;\n\n        }\n      }\n    }\n\n    // the linear system is solved\n    // x = AtA^-1AtB is solved\n    vpMatrix AtA = A.AtA() ;\n    vpMatrix Ap ;\n    vpColVector AeTc ;\n    AtA.pseudoInverse(Ap, 1e-6) ;\n    AeTc = Ap*A.t()*B ;\n\n//     {\n//       // residual\n//       vpColVector residual;\n//       residual = A*AeTc-B;\n//       std::cout << \"Residual: \" << std::endl << residual << std::endl;\n//       double res = 0;\n//       for (int i=0; i < residual.getRows(); i++)\n// \tres += residual[i]*residual[i];\n//       res = sqrt(res/residual.getRows());\n//       printf(\"mean residual = %lf\\n\",res);\n//     }\n\n    vpTranslationVector eTc(AeTc[0],AeTc[1],AeTc[2]);\n\n    eMc.insert(eTc) ;\n    eMc.insert(eRc) ;\n  }\n}\n\n\n#endif\nvoid out(std::ostream & onf, const Eigen::Matrix4f  & q)\n{\n\tfor(int i = 0; i < 16; i++)\n\t\tonf << q.data()[i] << ' ';\n}\n\nEigen::Matrix4f makerandom(const LTD &ld)\n{\n  return Eigen::Matrix4f::Identity(); //ld.sample().asMatrix();\n}\n\nEigen::Matrix<float,6,1> distance(Eigen::Matrix4f a, Eigen::Matrix4f b)\n{\n  return Eigen::Matrix<float,6,1> ::Zero();\n/*\tSE3group<float> ag(a);\n\tSE3group<float> bg(b);\n\treturn ag.distance(bg).get();*/\n}\n\n// pos and ang\nEigen::Matrix<float,2,1> distance2(Eigen::Matrix4f a, Eigen::Matrix4f b)\n{\n    //auto q = SE3group<float>(a).distance(SE3group<float>(b)).get();\n    return Eigen::Matrix<float,2,1>::Zero(); //{q.segment<3>(0).norm(),q.segment<3>(3).norm()};\n}\n\n// pos and ang\ntemplate <class T>\nT distanceT(Eigen::Matrix<T,4,4> a, Eigen::Matrix<T,4,4> b)\n{\n    return (a*b.inverse()).template block<3,1>(0,3).norm();\n}\n\ntemplate <class T>\nVector3<T> normalize(Vector3<T>  q)\n{\n\treturn q / q.norm();\n}\n\nint main(int argc, char const *argv[])\n{\n#if 0\n\tEigen::AngleAxisf aa(0.001*M_PI,normalize(Eigen::Vector3f(0.2,0.3,0.4)));\n\tEigen::Quaternionf q(aa);\n\tEigen::Vector3f p = quat2paratsai(q);\n\tEigen::Quaternionf Q = paratsai2quat(p);\n\tEigen::Matrix3f R = paratsai2rot(p);\n\tEigen::Quaternionf QR(R);\n\tEigen::Vector3f pp = paratsai2paratsaiprime(p);\n\tEigen::Vector3f ppp = paratsaiprime2paratsai(pp);\n\n\tfloat pangle = paratsai2theta(p);\n\tstd::cout << \"angle original  \" << aa.angle() << std::endl;\n\tstd::cout << \"angle from para \" << pangle << std::endl;\n\tstd::cout << \"angle from quat \" << Eigen::AngleAxisf(Q).angle() << std::endl;\n\tstd::cout << \"angle from rot  \" << Eigen::AngleAxisf(R).angle() << std::endl;\n\tstd::cout << q << std::endl;\n\tstd::cout << Q << std::endl;\n\tstd::cout << QR << std::endl;\n\tstd::cout << ppp.transpose() << std::endl;\n\tstd::cout << p.transpose() << std::endl;\n#endif\t\n\n    if(argc < 2)\n        return -1;\n    using FT = double;\n    std::ifstream inf(argv[1],std::ios::binary);\n    std::vector<Eigen::Matrix<FT,4,4> > cMm,rMe;\n    Eigen::Matrix<FT,4,4> m1fp,m2fp,m1f,m2f;\n    std::cout << \"assuming file of pairs of matrices: cMm and cMe\" << std::endl;\n    while(inf)\n    {\n        Eigen::Matrix<double,4,4,Eigen::RowMajor> m1,m2;\n        inf.read((char*)m1.data(),16*sizeof(double));\n        if(!inf)\n            break;\n        inf.read((char*)m2.data(),16*sizeof(double));\n        if(!inf)\n            break;\n        // data is stored rowmajor\n        m1f = m1.cast<FT>();\n        m2f = m2.cast<FT>();\n        cMm.push_back(m1f);\n        rMe.push_back(m2f);\n        if(cMm.size() == 1)\n        {\n            std::cout << \"m1[0] is\\n\" << m1f << std::endl;\n            std::cout << \"m2[0] is\\n\" << m2f << std::endl;\n        }\n        else\n        {\n            // previous is valid\n\n            // use 2D (pos,rot) or 1D (pos) distance\n            //std::cout << \"Diff m1: \" << distance2(m1f,m1fp).transpose() << \" Diff m2: \" << distance2(m2f,m2fp).transpose() << std::endl;\n            std::cout << \"Diff m1: \" << distanceT(m1f,m1fp) << \" Diff m2: \" << distanceT(m2f,m2fp) << std::endl;\n        }\n        m1fp = m1f;\n        m2fp = m2f;\n\n    }\n    Eigen::Matrix<FT,4,4> r;\n\n        FT res = calibrationTsai(cMm,rMe,r);\n\n\n        std::cout << \"Output:   \\n\" << r << std::endl;\n        std::cout << \"Residual:   \\n\" << res << std::endl;\n        /*std::cout << \"Expected: \\n\" << ec << std::endl;\n\tstd::cout << \"THIS diff:  \" << distance(r,ec).transpose() << std::endl;\n\tstd::cout << \"!THIS error: \" << distance(r,ec).transpose().norm() << std::endl;\n    */\n#ifdef USEVISP\n\tvpCalibration c;\n\tstd::vector<vpHomogeneousMatrix> vcMo(cMm.size());\n\tstd::vector<vpHomogeneousMatrix> vrMe(cMm.size());\n\tvpHomogeneousMatrix veMc;\n    Eigen::Matrix4f eMc;\n\tfor(int i = 0; i < cMm.size(); i++)\n\t{\n\t\tassign(vcMo[i],cMm[i].cast<float>());\n\t\tassign(vrMe[i],rMe[i].cast<float>());\n\t}\n         calibrationTsai(vcMo,vrMe,veMc);\n\tassign(eMc,veMc);\n\n        std::cout << \"MY output res:\\n\" << res << std::endl;\n        std::cout << \"VISP output:\\n\" << eMc << std::endl;\n  std::ofstream onf(\"tsaiout.bin\",std::ios::binary);\n  Matrix4<double> out(eMc.cast<FT>());\n  onf.write((char*)out.data(),sizeof(double)*16);\n/*\tstd::cout << \"Expected:   \\n\" << ec << std::endl;\n\tstd::cout << \"VISP diff:  \" << distance(eMc,ec).transpose() << std::endl;\n\tstd::cout << \"!VISP error:\" << distance(eMc,ec).transpose().norm() << std::endl;\n*/\n#endif\n#if 0\n\tif(argc == 2)\n\t{\n\t\tstd::ofstream onf(argv[1]);\n\t\tout(onf,ec);\t\tonf << std::endl;\n\t\tout(onf,r);\t\tonf << std::endl;\n\t\tonf << cMm.size() << std::endl;\n\t\tfor(int i = 0; i < cMm.size(); i++)\n\t\t{\n\t\t\tout(onf,cMm[i]);\n\t\t\tonf << std::endl;\n\t\t}\n\t\tfor(int i = 0; i < rMe.size(); i++)\n\t\t{\n\t\t\tout(onf,rMe[i]);\n\t\t\tonf << std::endl;\n\t\t}\n\t}\n#endif\n\treturn 0;\n}\n\n/*\n * 0.000  1.000  0.000  0.038\n-1.000 -0.000  0.000  0.012\n0.000  0.000  1.000  0.015\n0.000  0.000  0.000  1.000\n*/\n", "meta": {"hexsha": "085e76a7a8621ddbdb24ce279ed8f538c0a56c7e", "size": 11260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testtsai2.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": "testtsai2.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": "testtsai2.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": 27.5305623472, "max_line_length": 138, "alphanum_fraction": 0.5358792185, "num_tokens": 3799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5599461448679762}}
{"text": "#include \"Util.h\"\n#include \"Matrix.h\"\n\n#include <random>\n#include <time.h>\n#include <cmath>\n#include <fstream>\n#include <float.h>\n\n#include <opencv2/opencv.hpp>\n#include <boost/tokenizer.hpp>\n\n\nusing namespace std;\n\nint seed = time(0);\nstd::default_random_engine random_engine(seed); \n\nnamespace fns{\n\tdouble relu(double x){\n\t\tif(x > 0) return x;\n\t\telse return (double) 0;\n\t}\n\tdouble sigmoid(double x){\n\t\treturn (1.0/(1.0 + exp(-x)));\n\t}\n\tdouble tan(double x){\n\t\treturn tanh(x);\n\t}\n\tdouble relu_gradient(double x){\n\t\tif(x > 0) return (double) 1;\n\t\telse return (double) 0.2;\n\t}\n\tdouble sigmoid_gradient(double x){\n\t\treturn (x*(1-x));\n\t}\n\tdouble tan_gradient(double x){\n\t\treturn (1-(x*x));\n\t}\n\tdouble softmax(double x){\n\t\tif(isnan(x)) return 0;\n\t\treturn exp(x);\n\t}\n}\n\nnamespace pre_process{\n\tint process_mnist_images(const char* path, std::vector<std::unique_ptr<Matrix> > &Xtrain, \n\t\tstd::vector<std::unique_ptr<std::vector<double> > > &Ytrain, unsigned int nr_images){\n\t\tstd::string str(path);\t// convert char* to string\n\t\tconst int width = 28;\n\t\tconst int height = 28;\n\t\tconst int LABELS = 10;\n\t\n\t\tfor(unsigned int i=0; i < LABELS; i++){\n\t\t\tstd::vector<cv::String> files;\t// vector of strings to store file names\n\t\t\tcv::glob(path + std::to_string(i), files, true);\n\t\t\t\t// true means recursively read from path\n\t\t\tfor(unsigned int k=0; k < (nr_images/LABELS); k++){\n\t\t\t\tcv::Mat img = cv::imread(files[k]);\n\t\t\t\tif(img.empty()) continue;\t//only proceed further if the file is not empty\n\t\t\t\tstd::unique_ptr<Matrix> image = std::make_unique<Matrix>(width, height, true);\n\t\t\t\tfor(unsigned int h=0; h<height; h++){\n\t\t\t\t\tfor(unsigned int w=0; w<width; w++){\n\t\t\t\t\t\timage->set(h,w,(double)(img.at<uchar>(h,w)/255.0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tXtrain.emplace_back(std::move(image));\n\t\t\t\tstd::unique_ptr<std::vector<double> > vr = std::make_unique<std::vector<double> >(LABELS, 0);\t\t\t\t\n\t\t\t\t(*vr)[i] = 1.0;\n\t\t\t\tYtrain.emplace_back(std::move(vr));\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tint process_mnist_csv(const char* filename, std::vector<std::vector<double> > &Xtrain, \n\t\tstd::vector<std::vector<double> > &Ytrain){\n\t\tstd::string data(filename);\n\t\tifstream in(data.c_str());\n\n\t\tif(!in.is_open()) return 1;\n\n\t\ttypedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;\n\t\tstd::vector<std::string> svec;\n\t\tstd::string line;\n\n\t\twhile(getline(in, line)){\n\t\t\tTokenizer tok(line);\n\t\t\tauto it = tok.begin();\n\t\t\tint label = std::stoi(*it);\n\t\t\tstd::vector<double> labels(10, 0.0);\n\t\t\tlabels[label] = 1.0;\n\n\n\t\t\tsvec.assign(std::next(it, 1), tok.end());\n\n\t\t\tstd::vector<double> dvec(svec.size());\n\t\t\tstd::transform(svec.begin(), svec.end(), dvec.begin(), [](const std::string& val)\n\t\t\t{\n\t\t\t\treturn (std::stod(val)/255); // divide by 255 for normalization, since each pixel is 8 bit\n\t\t\t});\n\n\t\t\tXtrain.push_back(dvec);\n\t\t\tYtrain.push_back(labels);\n\t\t}\n\t\tcout << \"processed the input file\" << endl;\n\t\treturn 0;\n\t}\n\t\n\tvoid process_image(const char* filename){\n\t\tstd::vector<double> image;\n\t\tcv::Mat img = cv::imread(filename);\n\t\tif(img.empty()){\n\t\t\tstd::cout << \"No Image\" << std::endl;\n\t\t}\n\t\telse{\n\t\t\tif(img.isContinuous()){\n\t\t\t\timage.assign(img.datastart, img.dataend);\n\t\t\t\tfor(unsigned int j=0; j < image.size(); j++){\n\t\t\t\t\tcout << image[j] << \" \" ;\n\t\t\t\t}\n\t\t\t\tcout << endl << image.size();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstd::cout << \"Not Continous !\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "a467e37f43768eb11d5417b07ce0292fcf228faa", "size": 3342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Util.cpp", "max_stars_repo_name": "psrikanthm/cnn-from-scratch", "max_stars_repo_head_hexsha": "d159804ed66f66c272bdab4e8396607b1864192e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-08-25T18:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:14:03.000Z", "max_issues_repo_path": "Util.cpp", "max_issues_repo_name": "venkat-kittu/cnn-from-scratch", "max_issues_repo_head_hexsha": "d159804ed66f66c272bdab4e8396607b1864192e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Util.cpp", "max_forks_repo_name": "venkat-kittu/cnn-from-scratch", "max_forks_repo_head_hexsha": "d159804ed66f66c272bdab4e8396607b1864192e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-05-20T10:06:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T09:59:58.000Z", "avg_line_length": 25.7076923077, "max_line_length": 101, "alphanum_fraction": 0.631956912, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.5599355252958961}}
{"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 Lee's GKL method. 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 * We then try to reconstruct the factors.\n */\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nint main(int argc, char* argv[]) {\n#ifndef NDEBUG\n\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 5000000;\n\tmf_size_type rank = 10;\n\n\t// parameters for Lee01\n\tunsigned epochs = 20;\n\n\t// generate original factors by sampling from a uniform[0,1] distribution\n\tRandom32 random; // note: this takes a default seed (not randomized!)\n\tDenseMatrix wIn(size1, rank);\n\tDenseMatrixCM hIn(rank, size2);\n\tgenerateRandom(wIn, random,  boost::uniform_real<>(0, 1));\n\tgenerateRandom(hIn, random, boost::uniform_real<>(0, 1));\n\t// div2(wIn, sums2(wIn));\n\t// div1(hIn, sums1(hIn));\n\n\t// generate a sparse matrix by selecting random entries from the generated factors\n\t// and sample from a Poisson with mean equal to the entry\n\t// TODO: this generation process does not match the factorization model since we sample\n\t//       from the Poisson only at some entries of wh\n\tSparseMatrix v;\n\tgenerateRandom(v, nnz, wIn, hIn, random);\n\tapplyPoisson(v, random);\n\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << gkl(v, wIn, hIn));\n\n\t// generate initial factors by sampling from a uniform[0,1] distribution\n\tDenseMatrix w(size1, rank);\n\tDenseMatrixCM h(rank, size2);\n\tgenerateRandom(w, random, boost::uniform_real<>(0, 1));\n\tgenerateRandom(h, random, boost::uniform_real<>(0, 1));\n\tdiv2(w, sums2(w));\n\tdiv1(h, sums1(h));\n\tdouble scaleFactor = sqrt(sum(v));\n\tmult(w, scaleFactor);\n\tmult(h, scaleFactor);\n\n\t// perform the factorization\n\tFactorizationData<> data(v, w, h);\n\tTrace trace;\n\tlee01Gkl(data, epochs, trace);\n\n\t// write the trace\n\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/lee01-gkl-trace.R\");\n\ttrace.toRfile(\"/tmp/lee01-gkl-trace.R\", \"lee01.gkl\");\n\n\treturn 0;\n}\n", "meta": {"hexsha": "37df3d243f5b4fef544024a9abcd9b0081ea4a89", "size": 3156, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/lee01-gkl.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/lee01-gkl.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/lee01-gkl.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 33.935483871, "max_line_length": 106, "alphanum_fraction": 0.7129277567, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5599355202863768}}
{"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_COSPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COSPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing cospi capabilities\n\n    cosine of angle in \\f$\\pi\\f$ multiples: \\f$\\cos(\\pi x)\\f$.\n\n    @par Semantic:\n\n   The semantics of the function are similar to @ref cos ones.\n    see @ref cos for further details\n\n    @par Note\n\n    However as it conveys a peculiar meaning,  unlike the orher cosine, cospi is defined\n    for integral types and the result of cospi(n) coincides with \\f$(-1)^n\\f$.\n\n    Take care that large floating entries are always integral and even !\n\n    @see sincospi, cos, cosd\n\n  **/\n  Value cospi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cospi.hpp>\n#include <boost/simd/function/simd/cospi.hpp>\n\n#endif\n", "meta": {"hexsha": "4f22c48f72c6347e01a9856e28d733116af833c7", "size": 1267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cospi.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/cospi.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/cospi.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": 26.3958333333, "max_line_length": 100, "alphanum_fraction": 0.6077348066, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5598874189868205}}
{"text": "#pragma once\n#include <Eigen/Geometry>\n#include \"mtao/types.hpp\"\n\nnamespace mtao::geometry {\n    template <bool OutputEdges=false, typename T=double, int D=3>\n        auto  bounding_box_mesh(const Eigen::AlignedBox<T,D>& bb) {\n            mtao::ColVectors<T,D> V(D,1<<D);\n            if constexpr(D == 2) {\n                mtao::ColVectors<int,2> E(2,4);\n                V << bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomLeft),\n                  bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomRight),\n                  bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopLeft),\n                  bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopRight);\n                E << 0,0,3,2,\n                     1,2,1,3;\n                return std::make_tuple(V,E);\n            } else {//D == 3\n                mtao::ColVectors<int,3> F(3,12);\n                V << \n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomLeftFloor),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomRightFloor),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopLeftFloor),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopRightFloor),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomLeftCeil),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::BottomRightCeil),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopLeftCeil),\n                    bb.corner(Eigen::AlignedBox<T,D>::CornerType::TopRightCeil);\n                //0:000\n                //1:010\n                //2:100\n                //3:110\n                //4:001\n                //5:011\n                //6:101\n                //7:111\n                F <<\n                    6,2,3,1,7,3,6,7,4,5,5,7,\n                    0,0,0,0,2,2,4,4,0,0,1,1,\n                    4,6,2,3,6,7,7,5,5,1,7,3;\n\n                if constexpr(OutputEdges) {\n                    mtao::ColVectors<int,2> E(2,12);\n                    E << 0,0,0,1,1,2,2,3,4,4,5,6,\n                      1,2,4,3,5,3,6,7,5,6,7,7;\n                    return std::make_tuple(V,F,E);\n                } else {\n                    return std::make_tuple(V,F);\n                }\n            }\n        }\n}\n", "meta": {"hexsha": "bcb1b5c0d7435fdab5a6d5bfa8c8a814f8766fc1", "size": 2239, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/bounding_box_mesh.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/bounding_box_mesh.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/bounding_box_mesh.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": 42.2452830189, "max_line_length": 84, "alphanum_fraction": 0.4582402858, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5598874123355361}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/BasicThreadPool.h>\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include <NTL/lzz_pXFactoring.h>\n\n#include <cassert>\n#include <cstdio>\n#include <iostream>\nusing namespace std;\n\n/*  下面两个函数的作用是把数字或者数组转为可用于运算操作的vector\n *  因为当加密和解密过后，最后连续的n个0会被隐藏\n *  例如[2 2 0 0]→[2 2], [0 0 0 0]→[]\n *  []转为long输出时会出错，所以在末尾加上1使得0可以正确地被提取出来\n */\n\n// 数字转为可用于运算操作的vector\nVec<ZZ> num2validVec(long num)\n{\n\tVec<ZZ> v;\n\tv.SetLength(2);\n\tv[0] = num;\n\tv[1] = 1;\n\treturn v;\n}\n\n// 数组转为可用于运算操作的vector\nVec<ZZ> arr2validVec(long* num, int arrLen)\n{\n\tVec<ZZ> v;\n\tv.SetLength(arrLen+1);\n\tfor (int i=0; i<arrLen; i++)\n\t\tv[i] = num[i];\n\tv[arrLen] = 1;\n\treturn v;\n}\n\n// 四则运算全同态解密（只实现了数字作为运算符的解密，数组作为运算符的有待修缮）\nlong FHE_ptDec(ZZX ptxt, long p)\n{\n\tlong ptDec;\n\tconv(ptDec, ptxt[0]);\n\tif (ptDec > p/2)\n\t\tptDec -= p;\n\treturn ptDec;\n}\n\n// 全同态加法\nCtxt FHE_Add(Ctxt Ea, Ctxt Eb)\n{\n\tCtxt ctSum = Ea;\n\tctSum += Eb;\n\treturn ctSum;\n}\n\n// 全同态乘法\nCtxt FHE_Mul(Ctxt Ea, Ctxt Eb, long p, const FHESecKey& secretKey)\n{\n\tZZX ptEa, ptEb;\n\tsecretKey.Decrypt(ptEa, Ea);\n\tsecretKey.Decrypt(ptEb, Eb);\n\t// 解密判断乘数中是否有0，如果是，则返回0的密文\n\tif (FHE_ptDec(ptEa, p) == 0)\n\t\treturn Ea;\n\telse if (FHE_ptDec(ptEb, p) == 0)\n\t\treturn Eb;\n\telse\n\t{\n\t\tCtxt ctMul = Ea;\n\t\tctMul *= Eb;\n\t\treturn ctMul;\n\t}\n}\n\n// 全同态减法\nCtxt FHE_Sub(Ctxt Ea, Ctxt Eb, const FHEPubKey& publicKey)\n{\n\t// sub = op2*(-1)+op1\n\tCtxt minus1(publicKey);\n\tVec<ZZ> m1 = num2validVec(-1);\n\tpublicKey.Encrypt(minus1, to_ZZX(m1));\n\tCtxt ctSub = Eb;\n\tctSub *= minus1;\n\tctSub += Ea;\n\treturn ctSub;\n}\n\n// 全同态除法\nCtxt FHE_Div(Ctxt Ea, Ctxt Eb, long p,\n\t\t\t const FHEPubKey& publicKey, const FHESecKey& secretKey)\n{\n\tint quotient = 0;  // 初始化商quotient为0\n\tZZX ptMul, ptMul2, ptSub, ptSum, ptEa, ptEb;\n\n\t/* 判断思路（设被除数和除数为op1和op2）：\n\t * 1. op2=0时，输出\"Error: Invalid Denominator.\"，否则继续\n\t * 2. op1=0时，返回0的密文，否则继续\n\t * 3. 判断op1和op2是否同号,可用op1·op2是否为正来判断\n\t *    3-1. 同号: 当op1=0时跳出循环，否则\n\t *               sub=op1-op2，如果sub和op1同号(op1和op2同为负数的时候sub也是负数)则quotient递增且op1=sub，否则跳出循环\n\t *    3-2. 异号: 当op1=0时跳出循环，否则\n\t *               sum=op1+op2(因为是异号)，如果sum和op1同号则quotient递减(异号相除结果为负数)且op1=sum，否则跳出循环        \n\t */\n\tbool positive = true;\n\tsecretKey.Decrypt(ptEa, Ea);\n\tlong EaDec = FHE_ptDec(ptEa, p);\n\tif(EaDec < 0) positive = false;\n\tsecretKey.Decrypt(ptEb, Eb);\n\tlong EbDec = FHE_ptDec(ptEb, p);\n\tif (EbDec == 0) \n\t{\n\t\tcout << \"Error: Invalid Denominator.\" << endl;\n\t\tCtxt ctDiv(publicKey);\n\t\tVec<ZZ> q = num2validVec(quotient);\n\t\tpublicKey.Encrypt(ctDiv, to_ZZX(q));\n\t\treturn ctDiv;\n\t}\n\telse if (EaDec == 0)\n\t{\n\t\tCtxt ctDiv(publicKey);\n\t\tVec<ZZ> q = num2validVec(quotient);\n\t\tpublicKey.Encrypt(ctDiv, to_ZZX(q));\n\t\treturn ctDiv;\n\t}\n\telse {\n\t\tsecretKey.Decrypt(ptMul, FHE_Mul(Ea, Eb, p, secretKey));\n\t\t// 两操作数同号\n\t\tif(FHE_ptDec(ptMul, p) >= 0)\n\t\t{\n\t\t\twhile (1)\n\t\t\t{\n\t\t\t\tsecretKey.Decrypt(ptEa, Ea);\n\t\t\t\tlong EaDec = FHE_ptDec(ptEa, p);\n\t\t\t\tif (EaDec == 0) break;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tCtxt ctSub = FHE_Sub(Ea, Eb, publicKey);\n\t\t\t\t\tsecretKey.Decrypt(ptSub, ctSub);\n\t\t\t\t\tlong sub = FHE_ptDec(ptSub, p);\n\t\t\t\t\tif (sub >= 0 && positive || sub <= 0 && !positive)\n\t\t\t\t\t{\n\t\t\t\t\t\tEa = ctSub;\n\t\t\t\t\t\tquotient ++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// 两操作数异号 \n\t\telse \n\t\t{\n\t\t\twhile (1)\n\t\t\t{\n\t\t\t\tsecretKey.Decrypt(ptEa, Ea);\n\t\t\t\tlong EaDec = FHE_ptDec(ptEa, p);\n\t\t\t\tif (EaDec == 0) break;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tCtxt ctSum = FHE_Add(Ea, Eb);\n\t\t\t\t\tsecretKey.Decrypt(ptMul2, FHE_Mul(ctSum, Ea, p, secretKey));\n\t\t\t\t\tlong temp = FHE_ptDec(ptMul2, p);\n\t\t\t\t\tif (temp >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tEa = ctSum;\n\t\t\t\t\t\tquotient --;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tCtxt ctDiv(publicKey);\n\t\tVec<ZZ> q = num2validVec(quotient);\n\t\tpublicKey.Encrypt(ctDiv, to_ZZX(q));\n\t\treturn ctDiv;\n\t}\n}\n\n\n\nint main()\n{\n\tlong m = 0;    // 确定系数\n\tlong p = 1021; // 模量，定义超过p/2的数为负数，负数的真值x=D[E[x]]-p\n\tlong r = 1;\n\tlong L = 16;\n\tlong c = 3;\n\tlong w = 64;\n\tlong d = 0;\n\tlong k = 128;\n\tlong s = 0;\n\n\tm = FindM(k, L, c, p, d, s, 0);\n\n\tFHEcontext context(m, p, r);\n\tbuildModChain(context, L, c);\n\n\tZZX G = context.alMod.getFactorsOverZZ()[0];\n\t\n\t// 生成公钥\n\tFHESecKey secretKey(context);\n\tconst FHEPubKey& publicKey = secretKey;\n\tsecretKey.GenSecKey(w);\n\n\t// 初始化密文\n\tCtxt Ea(publicKey);\n\tCtxt Eb(publicKey);\n\n\t/* Test: 输入两个不全为0的数，输出四则运算结果，输入两个0可退出\t*/\n\tlong op1, op2;\n\twhile (!(op1==0 && op2==0))\n\t{\n\t\tcin >> op1 >> op2;\n\t\tVec<ZZ> h1 = num2validVec(op1);\n\t\tVec<ZZ> h2 = num2validVec(op2);\n\n\t\tpublicKey.Encrypt(Ea, to_ZZX(h1));\n\t\tpublicKey.Encrypt(Eb, to_ZZX(h2));\n\n\t\tcout << \"Operator 1 : \" << op1 << \" , Operator 2 : \" << op2 << endl;\n\n\t\tZZX ptSum;\n\t\tsecretKey.Decrypt(ptSum, FHE_Add(Ea, Eb));\n\t\tcout << \"ptSum : \" << FHE_ptDec(ptSum, p) << endl;\n\t\t\n\t\tZZX ptMul;\n\t\tsecretKey.Decrypt(ptMul, FHE_Mul(Ea, Eb, p, secretKey));\n\t\tcout << \"ptMul : \" << FHE_ptDec(ptMul, p) << endl;\n\n\t\tZZX ptSub;\n\t\tsecretKey.Decrypt(ptSub, FHE_Sub(Ea, Eb, publicKey));\n\t\tcout << \"ptSub : \" << FHE_ptDec(ptSub, p) << endl;\n\n\t\tZZX ptDiv;\n\t\tsecretKey.Decrypt(ptDiv, FHE_Div(Ea, Eb, p, publicKey, secretKey));\n\t\tcout << \"ptDiv : \" << FHE_ptDec(ptDiv, p) << endl;\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "316d44607ba4f36748c40294f5f0ab34f495fa36", "size": 5003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FHE_operation.cpp", "max_stars_repo_name": "edwincai/my-first-lab", "max_stars_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-12T15:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-12T15:33:57.000Z", "max_issues_repo_path": "FHE_operation.cpp", "max_issues_repo_name": "edwincai/my-first-lab", "max_issues_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FHE_operation.cpp", "max_forks_repo_name": "edwincai/my-first-lab", "max_forks_repo_head_hexsha": "eb8b25a3ad605320a9e6bbf0331ca94ef7cd3b5f", "max_forks_repo_licenses": ["Apache-2.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.7593360996, "max_line_length": 93, "alphanum_fraction": 0.6192284629, "num_tokens": 2207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5597800489056443}}
{"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_MEAN_HPP_INCLUDED\n#define NDHIST_STATS_MEAN_HPP_INCLUDED 1\n\n#include <boost/python.hpp>\n\n#include <ndhist/ndhist.hpp>\n#include <ndhist/stats/expectation.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\nAxisValueType\ncalc_axis_mean_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    return calc_axis_expectation_impl<AxisValueType, WeightValueType>(h, 1, axis);\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the mean value along the given axis of the given ndhist\n *     object.\n *     Since the mean is equal to the first order expectation, this function\n *     just calls the expectation function to calculate the first order\n *     expectation value.\n *     If None is given as axis, the mean value for all axes of the ndhist\n *     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 type axis\n *     values AND POD type weight values.\n */\nboost::python::object\nmean(\n    ndhist const & h\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_MEAN_HPP_INCLUDED\n", "meta": {"hexsha": "ad76f771c438878dcc2233b1173c394fbff88184", "size": 1540, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/mean.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/mean.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/mean.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": 24.4444444444, "max_line_length": 82, "alphanum_fraction": 0.7181818182, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.5597623107423355}}
{"text": "//  Copyright (c) 2013 Christopher Kormanyos\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// This work is based on an earlier work:\r\n// \"Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations\",\r\n// in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469\r\n//\r\n// This header contains implementation details for estimating the zeros\r\n// of cylindrical Bessel and Neumann functions on the positive real axis.\r\n// Support is included for both positive as well as negative order.\r\n// Various methods are used to estimate the roots. These include\r\n// empirical curve fitting and McMahon's asymptotic approximation\r\n// for small order, uniform asymptotic expansion for large order,\r\n// and iteration and root interlacing for negative order.\r\n//\r\n#ifndef _BESSEL_JY_ZERO_2013_01_18_HPP_\r\n  #define _BESSEL_JY_ZERO_2013_01_18_HPP_\r\n\r\n  #include <algorithm>\r\n  #include <boost/math/constants/constants.hpp>\r\n  #include <boost/math/special_functions/math_fwd.hpp>\r\n  #include <boost/math/special_functions/cbrt.hpp>\r\n  #include <boost/math/special_functions/detail/airy_ai_bi_zero.hpp>\r\n\r\n  namespace boost { namespace math {\r\n  namespace detail\r\n  {\r\n    namespace bessel_zero\r\n    {\r\n      template<class T>\r\n      T equation_nist_10_21_19(const T& v, const T& a)\r\n      {\r\n        // Get the initial estimate of the m'th root of Jv or Yv.\r\n        // This subroutine is used for the order m with m > 1.\r\n        // The order m has been used to create the input parameter a.\r\n\r\n        // This is Eq. 10.21.19 in the NIST Handbook.\r\n        const T mu                  = (v * v) * 4U;\r\n        const T mu_minus_one        = mu - T(1);\r\n        const T eight_a_inv         = T(1) / (a * 8U);\r\n        const T eight_a_inv_squared = eight_a_inv * eight_a_inv;\r\n\r\n        const T term3 = ((mu_minus_one *  4U) *     ((mu *    7U) -     T(31U) )) / 3U;\r\n        const T term5 = ((mu_minus_one * 32U) *   ((((mu *   83U) -    T(982U) ) * mu) +    T(3779U) )) / 15U;\r\n        const T term7 = ((mu_minus_one * 64U) * ((((((mu * 6949U) - T(153855UL)) * mu) + T(1585743UL)) * mu) - T(6277237UL))) / 105U;\r\n\r\n        return a + ((((                      - term7\r\n                       * eight_a_inv_squared - term5)\r\n                       * eight_a_inv_squared - term3)\r\n                       * eight_a_inv_squared - mu_minus_one)\r\n                       * eight_a_inv);\r\n      }\r\n\r\n      template<typename T>\r\n      class equation_as_9_3_39_and_its_derivative\r\n      {\r\n      public:\r\n        equation_as_9_3_39_and_its_derivative(const T& zt) : zeta(zt) { }\r\n\r\n        boost::math::tuple<T, T> operator()(const T& z) const\r\n        {\r\n          BOOST_MATH_STD_USING // ADL of std names, needed for acos, sqrt.\r\n\r\n          // Return the function of zeta that is implicitly defined\r\n          // in A&S Eq. 9.3.39 as a function of z. The function is\r\n          // returned along with its derivative with respect to z.\r\n\r\n          const T zsq_minus_one_sqrt = sqrt((z * z) - T(1));\r\n\r\n          const T the_function(\r\n              zsq_minus_one_sqrt\r\n            - (  acos(T(1) / z) + ((T(2) / 3U) * (zeta * sqrt(zeta)))));\r\n\r\n          const T its_derivative(zsq_minus_one_sqrt / z);\r\n\r\n          return boost::math::tuple<T, T>(the_function, its_derivative);\r\n        }\r\n\r\n      private:\r\n        const equation_as_9_3_39_and_its_derivative& operator=(const equation_as_9_3_39_and_its_derivative&);\r\n        const T zeta;\r\n      };\r\n\r\n      template<class T>\r\n      static T equation_as_9_5_26(const T& v, const T& ai_bi_root)\r\n      {\r\n        BOOST_MATH_STD_USING // ADL of std names, needed for log, sqrt.\r\n\r\n        // Obtain the estimate of the m'th zero of Jv or Yv.\r\n        // The order m has been used to create the input parameter ai_bi_root.\r\n        // Here, v is larger than about 2.2. The estimate is computed\r\n        // from Abramowitz and Stegun Eqs. 9.5.22 and 9.5.26, page 371.\r\n        //\r\n        // The inversion of z as a function of zeta is mentioned in the text\r\n        // following A&S Eq. 9.5.26. Here, we accomplish the inversion by\r\n        // performing a Taylor expansion of Eq. 9.3.39 for large z to order 2\r\n        // and solving the resulting quadratic equation, thereby taking\r\n        // the positive root of the quadratic.\r\n        // In other words: (2/3)(-zeta)^(3/2) approx = z + 1/(2z) - pi/2.\r\n        // This leads to: z^2 - [(2/3)(-zeta)^(3/2) + pi/2]z + 1/2 = 0.\r\n        //\r\n        // With this initial estimate, Newton-Raphson iteration is used\r\n        // to refine the value of the estimate of the root of z\r\n        // as a function of zeta.\r\n\r\n        const T v_pow_third(boost::math::cbrt(v));\r\n        const T v_pow_minus_two_thirds(T(1) / (v_pow_third * v_pow_third));\r\n\r\n        // Obtain zeta using the order v combined with the m'th root of\r\n        // an airy function, as shown in  A&S Eq. 9.5.22.\r\n        const T zeta = v_pow_minus_two_thirds * (-ai_bi_root);\r\n\r\n        const T zeta_sqrt = sqrt(zeta);\r\n\r\n        // Set up a quadratic equation based on the Taylor series\r\n        // expansion mentioned above.\r\n        const T b = -((((zeta * zeta_sqrt) * 2U) / 3U) + boost::math::constants::half_pi<T>());\r\n\r\n        // Solve the quadratic equation, taking the positive root.\r\n        const T z_estimate = (-b + sqrt((b * b) - T(2))) / 2U;\r\n\r\n        // Establish the range, the digits, and the iteration limit\r\n        // for the upcoming root-finding.\r\n        const T range_zmin = (std::max<T>)(z_estimate - T(1), T(1));\r\n        const T range_zmax = z_estimate + T(1);\r\n\r\n        const int my_digits10 = static_cast<int>(static_cast<float>(boost::math::tools::digits<T>() * 0.301F));\r\n\r\n        // Select the maximum allowed iterations based on the number\r\n        // of decimal digits in the numeric type T, being at least 12.\r\n        const boost::uintmax_t iterations_allowed = static_cast<boost::uintmax_t>((std::max)(12, my_digits10 * 2));\r\n\r\n        boost::uintmax_t iterations_used = iterations_allowed;\r\n\r\n        // Calculate the root of z as a function of zeta.\r\n        const T z = boost::math::tools::newton_raphson_iterate(\r\n          boost::math::detail::bessel_zero::equation_as_9_3_39_and_its_derivative<T>(zeta),\r\n          z_estimate,\r\n          range_zmin,\r\n          range_zmax,\r\n          (std::min)(boost::math::tools::digits<T>(), boost::math::tools::digits<float>()),\r\n          iterations_used);\r\n\r\n        static_cast<void>(iterations_used);\r\n\r\n        // Continue with the implementation of A&S Eq. 9.3.39.\r\n        const T zsq_minus_one      = (z * z) - T(1);\r\n        const T zsq_minus_one_sqrt = sqrt(zsq_minus_one);\r\n\r\n        // This is A&S Eq. 9.3.42.\r\n        const T b0_term_5_24 = T(5) / ((zsq_minus_one * zsq_minus_one_sqrt) * 24U);\r\n        const T b0_term_1_8  = T(1) / ( zsq_minus_one_sqrt * 8U);\r\n        const T b0_term_5_48 = T(5) / ((zeta * zeta) * 48U);\r\n\r\n        const T b0 = -b0_term_5_48 + ((b0_term_5_24 + b0_term_1_8) / zeta_sqrt);\r\n\r\n        // This is the second line of A&S Eq. 9.5.26 for f_k with k = 1.\r\n        const T f1 = ((z * zeta_sqrt) * b0) / zsq_minus_one_sqrt;\r\n\r\n        // This is A&S Eq. 9.5.22 expanded to k = 1 (i.e., one term in the series).\r\n        return (v * z) + (f1 / v);\r\n      }\r\n\r\n      namespace cyl_bessel_j_zero_detail\r\n      {\r\n        template<class T>\r\n        T equation_nist_10_21_40_a(const T& v)\r\n        {\r\n          const T v_pow_third(boost::math::cbrt(v));\r\n          const T v_pow_minus_two_thirds(T(1) / (v_pow_third * v_pow_third));\r\n\r\n          return v * (((((                         + T(0.043)\r\n                          * v_pow_minus_two_thirds - T(0.0908))\r\n                          * v_pow_minus_two_thirds - T(0.00397))\r\n                          * v_pow_minus_two_thirds + T(1.033150))\r\n                          * v_pow_minus_two_thirds + T(1.8557571))\r\n                          * v_pow_minus_two_thirds + T(1));\r\n        }\r\n\r\n        template<class T, class Policy>\r\n        class function_object_jv\r\n        {\r\n        public:\r\n          function_object_jv(const T& v,\r\n                             const Policy& pol) : my_v(v),\r\n                                                  my_pol(pol) { }\r\n\r\n          T operator()(const T& x) const\r\n          {\r\n            return boost::math::cyl_bessel_j(my_v, x, my_pol);\r\n          }\r\n\r\n        private:\r\n          const T my_v;\r\n          const Policy& my_pol;\r\n          const function_object_jv& operator=(const function_object_jv&);\r\n        };\r\n\r\n        template<class T, class Policy>\r\n        class function_object_jv_and_jv_prime\r\n        {\r\n        public:\r\n          function_object_jv_and_jv_prime(const T& v,\r\n                                          const bool order_is_zero,\r\n                                          const Policy& pol) : my_v(v),\r\n                                                               my_order_is_zero(order_is_zero),\r\n                                                               my_pol(pol) { }\r\n\r\n          boost::math::tuple<T, T> operator()(const T& x) const\r\n          {\r\n            // Obtain Jv(x) and Jv'(x).\r\n            // Chris's original code called the Bessel function implementation layer direct, \r\n            // but that circumvented optimizations for integer-orders.  Call the documented\r\n            // top level functions instead, and let them sort out which implementation to use.\r\n            T j_v;\r\n            T j_v_prime;\r\n\r\n            if(my_order_is_zero)\r\n            {\r\n              j_v       =  boost::math::cyl_bessel_j(0, x, my_pol);\r\n              j_v_prime = -boost::math::cyl_bessel_j(1, x, my_pol);\r\n            }\r\n            else\r\n            {\r\n                      j_v       = boost::math::cyl_bessel_j(  my_v,      x, my_pol);\r\n              const T j_v_m1     (boost::math::cyl_bessel_j(T(my_v - 1), x, my_pol));\r\n                      j_v_prime = j_v_m1 - ((my_v * j_v) / x);\r\n            }\r\n\r\n            // Return a tuple containing both Jv(x) and Jv'(x).\r\n            return boost::math::make_tuple(j_v, j_v_prime);\r\n          }\r\n\r\n        private:\r\n          const T my_v;\r\n          const bool my_order_is_zero;\r\n          const Policy& my_pol;\r\n          const function_object_jv_and_jv_prime& operator=(const function_object_jv_and_jv_prime&);\r\n        };\r\n\r\n        template<class T> bool my_bisection_unreachable_tolerance(const T&, const T&) { return false; }\r\n\r\n        template<class T, class Policy>\r\n        T initial_guess(const T& v, const int m, const Policy& pol)\r\n        {\r\n          BOOST_MATH_STD_USING // ADL of std names, needed for floor.\r\n\r\n          // Compute an estimate of the m'th root of cyl_bessel_j.\r\n\r\n          T guess;\r\n\r\n          // There is special handling for negative order.\r\n          if(v < 0)\r\n          {\r\n            if((m == 1) && (v > -0.5F))\r\n            {\r\n              // For small, negative v, use the results of empirical curve fitting.\r\n              // Mathematica(R) session for the coefficients:\r\n              //  Table[{n, BesselJZero[n, 1]}, {n, -(1/2), 0, 1/10}]\r\n              //  N[%, 20]\r\n              //  Fit[%, {n^0, n^1, n^2, n^3, n^4, n^5, n^6}, n]\r\n              guess = (((((    - T(0.2321156900729)\r\n                           * v - T(0.1493247777488))\r\n                           * v - T(0.15205419167239))\r\n                           * v + T(0.07814930561249))\r\n                           * v - T(0.17757573537688))\r\n                           * v + T(1.542805677045663))\r\n                           * v + T(2.40482555769577277);\r\n\r\n              return guess;\r\n            }\r\n\r\n            // Create the positive order and extract its positive floor integer part.\r\n            const T vv(-v);\r\n            const T vv_floor(floor(vv));\r\n\r\n            // The to-be-found root is bracketed by the roots of the\r\n            // Bessel function whose reflected, positive integer order\r\n            // is less than, but nearest to vv.\r\n\r\n            T root_hi = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess(vv_floor, m, pol);\r\n            T root_lo;\r\n\r\n            if(m == 1)\r\n            {\r\n              // The estimate of the first root for negative order is found using\r\n              // an adaptive range-searching algorithm.\r\n              root_lo = T(root_hi - 0.1F);\r\n\r\n              const bool hi_end_of_bracket_is_negative = (boost::math::cyl_bessel_j(v, root_hi, pol) < 0);\r\n\r\n              while((root_lo > boost::math::tools::epsilon<T>()))\r\n              {\r\n                const bool lo_end_of_bracket_is_negative = (boost::math::cyl_bessel_j(v, root_lo, pol) < 0);\r\n\r\n                if(hi_end_of_bracket_is_negative != lo_end_of_bracket_is_negative)\r\n                {\r\n                  break;\r\n                }\r\n\r\n                root_hi = root_lo;\r\n\r\n                // Decrease the lower end of the bracket using an adaptive algorithm.\r\n                if(root_lo > 0.5F)\r\n                {\r\n                  root_lo -= 0.5F;\r\n                }\r\n                else\r\n                {\r\n                  root_lo *= 0.75F;\r\n                }\r\n              }\r\n            }\r\n            else\r\n            {\r\n              root_lo = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess(vv_floor, m - 1, pol);\r\n            }\r\n\r\n            // Perform several steps of bisection iteration to refine the guess.\r\n            boost::uintmax_t number_of_iterations(12U);\r\n\r\n            // Do the bisection iteration.\r\n            const boost::math::tuple<T, T> guess_pair =\r\n               boost::math::tools::bisect(\r\n                  boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::function_object_jv<T, Policy>(v, pol),\r\n                  root_lo,\r\n                  root_hi,\r\n                  boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::my_bisection_unreachable_tolerance<T>,\r\n                  number_of_iterations);\r\n\r\n            return (boost::math::get<0>(guess_pair) + boost::math::get<1>(guess_pair)) / 2U;\r\n          }\r\n\r\n          if(m == 1U)\r\n          {\r\n            // Get the initial estimate of the first root.\r\n\r\n            if(v < 2.2F)\r\n            {\r\n              // For small v, use the results of empirical curve fitting.\r\n              // Mathematica(R) session for the coefficients:\r\n              //  Table[{n, BesselJZero[n, 1]}, {n, 0, 22/10, 1/10}]\r\n              //  N[%, 20]\r\n              //  Fit[%, {n^0, n^1, n^2, n^3, n^4, n^5, n^6}, n]\r\n              guess = (((((    - T(0.0008342379046010)\r\n                           * v + T(0.007590035637410))\r\n                           * v - T(0.030640914772013))\r\n                           * v + T(0.078232088020106))\r\n                           * v - T(0.169668712590620))\r\n                           * v + T(1.542187960073750))\r\n                           * v + T(2.4048359915254634);\r\n            }\r\n            else\r\n            {\r\n              // For larger v, use the first line of Eqs. 10.21.40 in the NIST Handbook.\r\n              guess = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::equation_nist_10_21_40_a(v);\r\n            }\r\n          }\r\n          else\r\n          {\r\n            if(v < 2.2F)\r\n            {\r\n              // Use Eq. 10.21.19 in the NIST Handbook.\r\n              const T a(((v + T(m * 2U)) - T(0.5)) * boost::math::constants::half_pi<T>());\r\n\r\n              guess = boost::math::detail::bessel_zero::equation_nist_10_21_19(v, a);\r\n            }\r\n            else\r\n            {\r\n              // Get an estimate of the m'th root of airy_ai.\r\n              const T airy_ai_root(boost::math::detail::airy_zero::airy_ai_zero_detail::initial_guess<T>(m));\r\n\r\n              // Use Eq. 9.5.26 in the A&S Handbook.\r\n              guess = boost::math::detail::bessel_zero::equation_as_9_5_26(v, airy_ai_root);\r\n            }\r\n          }\r\n\r\n          return guess;\r\n        }\r\n      } // namespace cyl_bessel_j_zero_detail\r\n\r\n      namespace cyl_neumann_zero_detail\r\n      {\r\n        template<class T>\r\n        T equation_nist_10_21_40_b(const T& v)\r\n        {\r\n          const T v_pow_third(boost::math::cbrt(v));\r\n          const T v_pow_minus_two_thirds(T(1) / (v_pow_third * v_pow_third));\r\n\r\n          return v * (((((                         - T(0.001)\r\n                          * v_pow_minus_two_thirds - T(0.0060))\r\n                          * v_pow_minus_two_thirds + T(0.01198))\r\n                          * v_pow_minus_two_thirds + T(0.260351))\r\n                          * v_pow_minus_two_thirds + T(0.9315768))\r\n                          * v_pow_minus_two_thirds + T(1));\r\n        }\r\n\r\n        template<class T, class Policy>\r\n        class function_object_yv\r\n        {\r\n        public:\r\n          function_object_yv(const T& v,\r\n                             const Policy& pol) : my_v(v),\r\n                                                  my_pol(pol) { }\r\n\r\n          T operator()(const T& x) const\r\n          {\r\n            return boost::math::cyl_neumann(my_v, x, my_pol);\r\n          }\r\n\r\n        private:\r\n          const T my_v;\r\n          const Policy& my_pol;\r\n          const function_object_yv& operator=(const function_object_yv&);\r\n        };\r\n\r\n        template<class T, class Policy>\r\n        class function_object_yv_and_yv_prime\r\n        {\r\n        public:\r\n          function_object_yv_and_yv_prime(const T& v,\r\n                                          const Policy& pol) : my_v(v),\r\n                                                               my_pol(pol) { }\r\n\r\n          boost::math::tuple<T, T> operator()(const T& x) const\r\n          {\r\n            const T half_epsilon(boost::math::tools::epsilon<T>() / 2U);\r\n\r\n            const bool order_is_zero = ((my_v > -half_epsilon) && (my_v < +half_epsilon));\r\n\r\n            // Obtain Yv(x) and Yv'(x).\r\n            // Chris's original code called the Bessel function implementation layer direct, \r\n            // but that circumvented optimizations for integer-orders.  Call the documented\r\n            // top level functions instead, and let them sort out which implementation to use.\r\n            T y_v;\r\n            T y_v_prime;\r\n\r\n            if(order_is_zero)\r\n            {\r\n              y_v       =  boost::math::cyl_neumann(0, x, my_pol);\r\n              y_v_prime = -boost::math::cyl_neumann(1, x, my_pol);\r\n            }\r\n            else\r\n            {\r\n                      y_v       = boost::math::cyl_neumann(  my_v,      x, my_pol);\r\n              const T y_v_m1     (boost::math::cyl_neumann(T(my_v - 1), x, my_pol));\r\n                      y_v_prime = y_v_m1 - ((my_v * y_v) / x);\r\n            }\r\n\r\n            // Return a tuple containing both Yv(x) and Yv'(x).\r\n            return boost::math::make_tuple(y_v, y_v_prime);\r\n          }\r\n\r\n        private:\r\n          const T my_v;\r\n          const Policy& my_pol;\r\n          const function_object_yv_and_yv_prime& operator=(const function_object_yv_and_yv_prime&);\r\n        };\r\n\r\n        template<class T> bool my_bisection_unreachable_tolerance(const T&, const T&) { return false; }\r\n\r\n        template<class T, class Policy>\r\n        T initial_guess(const T& v, const int m, const Policy& pol)\r\n        {\r\n          BOOST_MATH_STD_USING // ADL of std names, needed for floor.\r\n\r\n          // Compute an estimate of the m'th root of cyl_neumann.\r\n\r\n          T guess;\r\n\r\n          // There is special handling for negative order.\r\n          if(v < 0)\r\n          {\r\n            // Create the positive order and extract its positive floor and ceiling integer parts.\r\n            const T vv(-v);\r\n            const T vv_floor(floor(vv));\r\n\r\n            // The to-be-found root is bracketed by the roots of the\r\n            // Bessel function whose reflected, positive integer order\r\n            // is less than, but nearest to vv.\r\n\r\n            // The special case of negative, half-integer order uses\r\n            // the relation between Yv and spherical Bessel functions\r\n            // in order to obtain the bracket for the root.\r\n            // In these special cases, cyl_neumann(-n/2, x) = sph_bessel_j(+n/2, x)\r\n            // for v = -n/2.\r\n\r\n            T root_hi;\r\n            T root_lo;\r\n\r\n            if(m == 1)\r\n            {\r\n              // The estimate of the first root for negative order is found using\r\n              // an adaptive range-searching algorithm.\r\n              // Take special precautions for the discontinuity at negative,\r\n              // half-integer orders and use different brackets above and below these.\r\n              if(T(vv - vv_floor) < 0.5F)\r\n              {\r\n                root_hi = boost::math::detail::bessel_zero::cyl_neumann_zero_detail::initial_guess(vv_floor, m, pol);\r\n              }\r\n              else\r\n              {\r\n                root_hi = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess(T(vv_floor + 0.5F), m, pol);\r\n              }\r\n\r\n              root_lo = T(root_hi - 0.1F);\r\n\r\n              const bool hi_end_of_bracket_is_negative = (boost::math::cyl_neumann(v, root_hi, pol) < 0);\r\n\r\n              while((root_lo > boost::math::tools::epsilon<T>()))\r\n              {\r\n                const bool lo_end_of_bracket_is_negative = (boost::math::cyl_neumann(v, root_lo, pol) < 0);\r\n\r\n                if(hi_end_of_bracket_is_negative != lo_end_of_bracket_is_negative)\r\n                {\r\n                  break;\r\n                }\r\n\r\n                root_hi = root_lo;\r\n\r\n                // Decrease the lower end of the bracket using an adaptive algorithm.\r\n                if(root_lo > 0.5F)\r\n                {\r\n                  root_lo -= 0.5F;\r\n                }\r\n                else\r\n                {\r\n                  root_lo *= 0.75F;\r\n                }\r\n              }\r\n            }\r\n            else\r\n            {\r\n              if(T(vv - vv_floor) < 0.5F)\r\n              {\r\n                root_lo  = boost::math::detail::bessel_zero::cyl_neumann_zero_detail::initial_guess(vv_floor, m - 1, pol);\r\n                root_hi = boost::math::detail::bessel_zero::cyl_neumann_zero_detail::initial_guess(vv_floor, m, pol);\r\n                root_lo += 0.01F;\r\n                root_hi += 0.01F;\r\n              }\r\n              else\r\n              {\r\n                root_lo = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess(T(vv_floor + 0.5F), m - 1, pol);\r\n                root_hi = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess(T(vv_floor + 0.5F), m, pol);\r\n                root_lo += 0.01F;\r\n                root_hi += 0.01F;\r\n              }\r\n            }\r\n\r\n            // Perform several steps of bisection iteration to refine the guess.\r\n            boost::uintmax_t number_of_iterations(12U);\r\n\r\n            // Do the bisection iteration.\r\n            const boost::math::tuple<T, T> guess_pair =\r\n               boost::math::tools::bisect(\r\n                  boost::math::detail::bessel_zero::cyl_neumann_zero_detail::function_object_yv<T, Policy>(v, pol),\r\n                  root_lo,\r\n                  root_hi,\r\n                  boost::math::detail::bessel_zero::cyl_neumann_zero_detail::my_bisection_unreachable_tolerance<T>,\r\n                  number_of_iterations);\r\n\r\n            return (boost::math::get<0>(guess_pair) + boost::math::get<1>(guess_pair)) / 2U;\r\n          }\r\n\r\n          if(m == 1U)\r\n          {\r\n            // Get the initial estimate of the first root.\r\n\r\n            if(v < 2.2F)\r\n            {\r\n              // For small v, use the results of empirical curve fitting.\r\n              // Mathematica(R) session for the coefficients:\r\n              //  Table[{n, BesselYZero[n, 1]}, {n, 0, 22/10, 1/10}]\r\n              //  N[%, 20]\r\n              //  Fit[%, {n^0, n^1, n^2, n^3, n^4, n^5, n^6}, n]\r\n              guess = (((((    - T(0.0025095909235652)\r\n                           * v + T(0.021291887049053))\r\n                           * v - T(0.076487785486526))\r\n                           * v + T(0.159110268115362))\r\n                           * v - T(0.241681668765196))\r\n                           * v + T(1.4437846310885244))\r\n                           * v + T(0.89362115190200490);\r\n            }\r\n            else\r\n            {\r\n              // For larger v, use the second line of Eqs. 10.21.40 in the NIST Handbook.\r\n              guess = boost::math::detail::bessel_zero::cyl_neumann_zero_detail::equation_nist_10_21_40_b(v);\r\n            }\r\n          }\r\n          else\r\n          {\r\n            if(v < 2.2F)\r\n            {\r\n              // Use Eq. 10.21.19 in the NIST Handbook.\r\n              const T a(((v + T(m * 2U)) - T(1.5)) * boost::math::constants::half_pi<T>());\r\n\r\n              guess = boost::math::detail::bessel_zero::equation_nist_10_21_19(v, a);\r\n            }\r\n            else\r\n            {\r\n              // Get an estimate of the m'th root of airy_bi.\r\n              const T airy_bi_root(boost::math::detail::airy_zero::airy_bi_zero_detail::initial_guess<T>(m));\r\n\r\n              // Use Eq. 9.5.26 in the A&S Handbook.\r\n              guess = boost::math::detail::bessel_zero::equation_as_9_5_26(v, airy_bi_root);\r\n            }\r\n          }\r\n\r\n          return guess;\r\n        }\r\n      } // namespace cyl_neumann_zero_detail\r\n    } // namespace bessel_zero\r\n  } } } // namespace boost::math::detail\r\n\r\n#endif // _BESSEL_JY_ZERO_2013_01_18_HPP_\r\n", "meta": {"hexsha": "e9027acd7b5ca07cbb2056f77568efb18f6cc474", "size": 25554, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/detail/bessel_jy_zero.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/detail/bessel_jy_zero.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/detail/bessel_jy_zero.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.3495145631, "max_line_length": 134, "alphanum_fraction": 0.5146748063, "num_tokens": 6407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5597623078289222}}
{"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_DEGINRAD_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_DEGINRAD_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup trigo_constant\n * \\defgroup trigo_constant_deginrad Deginrad\n * \\par Description\n * Constant Deginrad : radian in degree  multiplier, \\f$\\frac\\pi{180}\\f$.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/deginrad.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::_deginrad_(A0)>::type\n *     Deginrad();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Deginrad\n *\n * \\return type T value\n *\n *\n**/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    // 8.47842766036889956997e-32\n    BOOST_SIMD_CONSTANT_REGISTER( Deginrad, double\n                                , 0, 0x3c8efa35\n                                , 0x3f91df46a2529d39ll\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Deginrad, Deginrad);\n\n  static const long double long_deginrad = 0.017453292519943295769236907684886l;\n}\n\n#endif\n", "meta": {"hexsha": "c11b1aaf1332d9d28fa86a4d167ac2f50aa8a12d", "size": 1686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5454545455, "max_line_length": 80, "alphanum_fraction": 0.5771055753, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5597623009260198}}
{"text": "/*!\n * @file\n * An example of logistic regression training and testing.\n * The data is taken from:\n *\n * command to run:\n * mpirung -n 4 ./bin/logreg \"data/logreg/train.csv\"\n *\n * For running on some different data-set specify the columns etc. in `fromFile`\n * Also change the `dim` parameter and inFile variable.\n * Testing data files can be given as arguments after training data file.\n *\n * benchmarks at the bottom\n * */\n#include <array>\n#include <iostream>\n#include <stdexcept>\n#include <boost/mpi.hpp>\n\n#include <ezl.hpp>\n#include <ezl/algorithms/io.hpp>\n#include <ezl/algorithms/reduceAlls.hpp>\n#include <ezl/algorithms/reduces.hpp>\n#include <ezl/algorithms/fromFile.hpp>\n\nusing namespace std;\n\ndouble sigmoid(double x) {\n  constexpr auto e = 2.718281828;\n  return 1.0 / (1.0 + pow(e, -x));\n}\n\ntemplate <size_t dim>\ndouble calcNorm(const array<double, dim> &weights,\n                const array<double, dim> &weightsNew) {\n  auto sum = 0.;\n  for (size_t i = 0; i < weights.size(); ++i) {\n    auto minus = weights[i] - weightsNew[i];\n    sum += (minus * minus);\n  }\n  return sqrt(sum);\n}\n\ntemplate <size_t dim>\nauto calcGrad(const double &y, const array<double, dim> &x,\n                const array<double, dim> &w) {\n  array<double, dim> grad;\n  auto dot = std::inner_product(::begin(w), ::end(w), ::begin(x), 0);\n  //auto s = (sigmoid(y * dot) - 1) * y;\n  auto s = sigmoid(dot) - y;\n  for (size_t i = 0; i < w.size(); ++i) {\n    grad[i] = s * x[i];\n  }\n  return grad;\n}\n\nvoid logreg(int argc, char* argv[]) {\n  if (argc < 2) {\n    cerr << \"Please provide arguments as glob pattern for train file(s), \"\n            \"followed by test file pattern(s). Check source for defaults or \"\n            \"for running on some other data-format.\";\n    return;\n  }\n\n  constexpr auto dim = 3;  // number of features\n  constexpr auto maxIters = 1000;\n\n  // specify columns and other read properties if required.\n  auto reader =\n      ezl::fromFile<double, array<double, dim>>(argv[1]).colSeparator(\",\");\n\n  // load once in memory\n  auto data = ezl::rise(reader)\n                  .runResult();\n\n  if (data.empty()) {\n    cout<<\"no data\";\n    return;\n  }\n\n  auto sumArray = [](auto &a, auto &b) -> auto & {\n    transform(begin(a), end(a), begin(b), begin(b), plus<double>());\n    return b;\n  };\n\n  array<double, dim> w{};  // weights initialised to zero;\n  // build flow for final gradient value in all procs\n  auto train = ezl::rise(ezl::fromMem(data))\n                   .map([&w](auto& y, auto& x) {\n                     return calcGrad(y, x, w);    \n                   }).colsTransform()\n                   .reduce(sumArray, array<double, dim>{}).inprocess()\n                   .reduce(sumArray, array<double, dim>{})\n                     .prll(1., ezl::llmode::task | ezl::llmode::all)\n                   .build();\n                 \n  auto iters = 0;\n  auto norm = 0.;\n  while (iters++ < maxIters) {\n    array<double, dim> wn, grad;\n    tie(grad) =  ezl::flow(train).runResult()[0]; // running flow\n    constexpr static auto gamma = 0.002;\n    transform(begin(w), end(w), begin(grad), begin(wn),\n                   [](double a, double b) { return a - gamma * b;});\n    norm = calcNorm(wn, w);\n    w = move(wn);\n    constexpr auto epsilon = 0.0001;\n    if(norm < epsilon)  break;\n  }\n  cout<<\"iterations: \"<<iters-1<<endl;  // TODO: message\n  cout<<\"norm: \"<<norm<<endl;\n  cout<<\"final weights: \"<<w<<endl;\n  \n  // building testing flow\n  auto testFlow = ezl::rise(reader)\n                      .map<2>([&w](auto x) {\n                        auto pred = 0.;\n                        for (size_t i = 0; i < get<0>(x).size(); ++i) {\n                          pred += w[i] * get<0>(x)[i];\n                        }\n                        return (sigmoid(pred) > 0.5);\n                      }).colsTransform()\n                      .reduce<1, 2>(ezl::count(), 0)\n                        .dump(\"\", \"real-y, predicted-y, count\")\n                      .build();\n\n  for (int i = 1; i < argc; ++i) {\n    reader = reader.filePattern(argv[i]);\n    cout<<\"Testing for \"<<argv[i]<<endl;\n    ezl::flow(testFlow).run();\n  }\n}\n\nint main(int argc, char *argv[]) {\n  boost::mpi::environment env(argc, argv, false);\n  try {\n    logreg(argc, argv);\n  } catch (const exception& ex) {\n    cerr<<\"error: \"<<ex.what()<<'\\n';\n    env.abort(1);  \n  } catch (...) {\n    cerr<<\"unknown exception\\n\";\n    env.abort(2);  \n  }\n  return 0;\n}\n\n/*!\n * benchmark results: i7(hdd); input: 450MBs\n *  *nprocs* | 1   | 2   | 4    |\n *  ---      |---  |---  |---   |\n *  *time(s)*| 120 | 63  | 38   |\n * \n * benchmark results: Linux(nfs-3); input: 2.9GBs; units: secs\n *  *nprocs* | 1x12      | 2x12      | 4x12      | 8x12      |  12x12   |\n *  ---      |---        |---        |---        | ---       |          |\n *  *time(s)*| 190       | 91        | 50        | 36        |  34      |\n */\n", "meta": {"hexsha": "0821f81bfe2652a0ee1c5d3445a299a541fd5aa4", "size": 4849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/logreg.cpp", "max_stars_repo_name": "YcheParallelStudio/easyLambda", "max_stars_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_stars_repo_licenses": ["BSL-1.0"], "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/logreg.cpp", "max_issues_repo_name": "YcheParallelStudio/easyLambda", "max_issues_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_issues_repo_licenses": ["BSL-1.0"], "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/logreg.cpp", "max_forks_repo_name": "YcheParallelStudio/easyLambda", "max_forks_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_forks_repo_licenses": ["BSL-1.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.4968553459, "max_line_length": 80, "alphanum_fraction": 0.5293875026, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5597200224402537}}
{"text": "\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <thread>\n#include <boost/math/special_functions/bessel.hpp>\n#include \"spida/transform/hankelR.h\"\n#include \"spida/grid/besselR.h\" \n#if defined(HAVE_OPENBLAS)\n    #include \"cblas.h\"\n#endif\n\nnamespace spida {\n\n  HankelTransformR::HankelTransformR(const BesselRootGridR& grid) : \n      m_nr(grid.getNr()),\n      m_Ymk(m_nr*m_nr),\n      m_YmkC(m_nr*m_nr)\n  {\n      m_alpha = grid.getjN()/pow(grid.getMaxSR(),2);\n      initDHT(grid);\n  }\n\n  void HankelTransformR::R_To_SR(const double* in,double* out) \n  {\n/*\nenum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102};\nenum CBLAS_TRANSPOSE    {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113};\ncblas_dgemv(const enum CBLAS_ORDER Order,\n           const enum CBLAS_TRANSPOSE TransA, const int M, const int N,\n           const double alpha, const double *A, const int lda,\n           const double *X, const int incX, const double beta,\n           double *Y, const int incY);\ndgemv y = alpha*A*x + beta*y\nlda -> first dimension of A\n*/\n\n      #if defined(HAVE_OPENBLAS)\n      cblas_dgemv(CblasRowMajor,CblasNoTrans,m_nr,m_nr,m_alpha,m_Ymk.data(),m_nr,in,1,0.0,out,1);\n      #else\n      for(int m = 0; m < m_nr; m++){\n          double sum = 0.0;\n          for(int k = 0; k < m_nr; k++)\n              sum += m_Ymk[m*m_nr+k]*in[k];\n          out[m] = m_alpha*sum;\n      }\n      #endif\n  }\n\n  void HankelTransformR::R_To_SR(const dcmplx* in,dcmplx* out) \n  {\n      #if defined(HAVE_OPENBLAS)\n      const double beta = 0.0;\n      cblas_zgemv(CblasRowMajor,CblasNoTrans,m_nr,m_nr,&m_alpha,m_YmkC.data(),m_nr,in,1,&beta,out,1);\n      #else\n      for(int m = 0; m < m_nr; m++){\n          dcmplx sum = 0.0;\n          for(int k = 0; k < m_nr; k++)\n              sum += m_YmkC[m*m_nr+k]*in[k];\n          out[m] = m_alpha*sum;\n      }\n      #endif\n  }\n\n  void HankelTransformR::SR_To_R(const double* in,double* out) \n  {\n      #if defined(HAVE_OPENBLAS)\n      cblas_dgemv(CblasRowMajor,CblasNoTrans,m_nr,m_nr,1.0/m_alpha,m_Ymk.data(),m_nr,in,1,0.0,out,1);\n      #else\n      for(int k = 0; k < m_nr; k++){\n          double sum = 0.0;\n          for(int m = 0; m < m_nr; m++)\n              sum += m_Ymk[k*m_nr+m]*in[m];\n          out[k] = sum/m_alpha;\n      }\n      #endif\n  }\n\n  void HankelTransformR::SR_To_R(const dcmplx* in,dcmplx* out) \n  {\n      #if defined(HAVE_OPENBLAS)\n      const dcmplx a = 1.0/m_alpha;\n      const dcmplx beta = 0.0;\n      cblas_zgemv(CblasRowMajor,CblasNoTrans,m_nr,m_nr,&a,m_YmkC.data(),m_nr,in,1,&beta,out,1);\n      #else\n      for(int k = 0; k < m_nr; k++){\n          dcmplx sum = 0.0;\n          for(int m = 0; m < m_nr; m++)\n              sum += m_YmkC[k*m_nr+m]*in[m];\n          out[k] = sum/m_alpha;\n      }\n      #endif\n  }\n\n  void HankelTransformR::initDHT(const BesselRootGridR& grid){\n      const std::vector<double>& J0 = grid.getBesselRoots();\n      std::vector<double> J1(m_nr);\n\n      for(auto i = 0; i < m_nr; i++)\n          J1[i] = boost::math::cyl_bessel_j<double>(1.0,J0[i]);\n\n      double jN = grid.getjN();\n      for(auto m = 0; m < m_nr; m++){\n          for(auto k = 0; k < m_nr; k++){\n              double beta_mk = 2.0/(jN*pow(J1[k],2));\n              double arg = J0[m]*J0[k]/jN;\n              double J0_mk = boost::math::cyl_bessel_j<double>(0.0,arg);\n              m_Ymk[m*m_nr+k] = beta_mk*J0_mk;\n              m_YmkC[m*m_nr+k] = beta_mk*J0_mk;\n          }\n      }\n  }\n\n\n  HankelTransformRb::HankelTransformRb(const BesselRootGridR& grid,unsigned threads) : \n      m_threads(threads),\n      m_nr(grid.getNr()),\n      m_Ymk(grid.getNr()*grid.getNr())\n  {\n      m_alpha = grid.getjN()/pow(grid.getMaxSR(),2);\n      initDHT(grid);\n  }\n\n  void HankelTransformRb::R_To_SR(const double* in,double* out) \n  {\n      for(unsigned m = 0; m < m_nr; m++){\n          double sum = 0.0;\n          for(unsigned k = 0; k < m_nr; k++)\n              sum += m_Ymk[m*m_nr+k]*in[k];\n          out[m] = m_alpha*sum;\n      }\n  }\n\n  void HankelTransformRb::R_To_SR(const dcmplx* in,dcmplx* out) \n  {\n      std::vector<std::thread> workers;\n      for(unsigned tid = 0; tid < m_threads; tid++){\n          workers.push_back(std::thread([](\\\n                          unsigned tid,\\\n                          unsigned nthreads,\\\n                          unsigned nr,\\\n                          std::vector<double>& Ymk,\\\n                          double alpha,\\\n                          const dcmplx* v,\\\n                          dcmplx* w){\n              for(unsigned m = tid; m < nr; m+=nthreads){\n                  dcmplx sum = 0.0;\n                  for(unsigned k = 0; k < nr; k++)\n                      sum += Ymk[m*nr+k]*v[k];\n                  w[m] = alpha*sum;\n              }\n          },tid,m_threads,m_nr,std::ref(m_Ymk),m_alpha,in,out));\n      }\n\n      for(auto& worker : workers){\n          worker.join();\n      }\n  }\n\n  void HankelTransformRb::SR_To_R(const double* in,double* out) \n  {\n\n      for(unsigned k = 0; k < m_nr; k++){\n          double sum = 0.0;\n          for(unsigned m = 0; m < m_nr; m++)\n              sum += m_Ymk[k*m_nr+m]*in[m];\n          out[k] = sum/m_alpha;\n      }\n  }\n\n\n  void HankelTransformRb::SR_To_R(const dcmplx* in,dcmplx* out) \n  {\n      std::vector<std::thread> workers;\n      for(unsigned tid = 0; tid < m_threads; tid++){\n          workers.push_back(std::thread([](\\\n                          unsigned tid,\\\n                          unsigned nthreads,\\\n                          unsigned nr,\\\n                          std::vector<double>& Ymk,\\\n                          double alpha,\\\n                          const dcmplx* v,\\\n                          dcmplx* w){\n              for(unsigned k = tid; k < nr; k+=nthreads){\n                  dcmplx sum = 0.0;\n                  for(unsigned m = 0; m < nr; m++)\n                      sum += Ymk[k*nr+m]*v[m];\n                  w[k] = sum/alpha;\n              }\n          },tid,m_threads,m_nr,std::ref(m_Ymk),m_alpha,in,out));\n      }\n\n      for(auto& worker : workers){\n          worker.join();\n      }\n  }\n\n  void HankelTransformRb::initDHT(const BesselRootGridR& grid){\n      const std::vector<double>& J0 = grid.getBesselRoots();\n      std::vector<double> J1(m_nr);\n\n      for(auto i = 0; i < m_nr; i++)\n          J1[i] = boost::math::cyl_bessel_j<double>(1.0,J0[i]);\n\n      double jN = grid.getjN();\n      for(auto m = 0; m < m_nr; m++){\n          for(auto k = 0; k < m_nr; k++){\n              double beta_mk = 2.0/(jN*pow(J1[k],2));\n              double arg = J0[m]*J0[k]/jN;\n              double J0_mk = boost::math::cyl_bessel_j<double>(0.0,arg);\n              m_Ymk[m*m_nr+k] = beta_mk*J0_mk;\n          }\n      }\n  }\n\n\n\n\n\n\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fb33df9e2641042d1f981e10fd5b69f96417a77e", "size": 6690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/transform/hankelR.cpp", "max_stars_repo_name": "whalenpt/spida", "max_stars_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T10:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T10:22:31.000Z", "max_issues_repo_path": "src/transform/hankelR.cpp", "max_issues_repo_name": "whalenpt/spida", "max_issues_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transform/hankelR.cpp", "max_forks_repo_name": "whalenpt/spida", "max_forks_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_forks_repo_licenses": ["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.7124463519, "max_line_length": 101, "alphanum_fraction": 0.5149476831, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5597200224402535}}
{"text": "#include <iostream>\n#include <math.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n\nint target = 1000;\n\nint main(int argc, char** argv) {\n  boost::multiprecision::cpp_int n = 1;\n  for (int i = 0; i < target; i++) {\n    n *= 2;\n  }\n  unsigned long long sum = 0;\n  while (n) {\n    sum += static_cast<unsigned long long>(n % 10);\n    n /= 10;\n  }\n  cout << \"Sum of all digits: \" << sum << endl;\n  return 0;\n}\n", "meta": {"hexsha": "022db3dc9da936d98b840059c943223392e5fe54", "size": 428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "16.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": "16.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": "16.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": 18.6086956522, "max_line_length": 51, "alphanum_fraction": 0.5957943925, "num_tokens": 135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5597200180640638}}
{"text": "/*\nThis is a modified version SCRIMP with optimized arithmetics.\nThe code builds on SCRIMP++, as published by Zhua, Yeh, Zimmerman et al. at https://sites.google.com/site/scrimpplusplus/ and contains parts from their code\n\nDetails of the SCRIMP algorithm can be found at:\n(author information ommited for ICDM review),\n\"SCRIMP++: Motif Discovery at Interactive Speeds\", submitted to ICDM 2018.\n*/\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <chrono>\n\n#include <boost/filesystem.hpp>\n\n#include <ScrimpSequOpt.hpp>\n#include <logging.hpp>\n#include <papiwrapper.hpp>\n\nusing namespace matrix_profile;\n\nstatic FactoryRegistration<ScrimpSequOpt> s_sequRegistr(\"scrimp_sequ_opt\");\nstatic const int notification_interval_iter = 10000;\n\nvoid ScrimpSequOpt::precompute_window_statistics(const int windowSize,\n    const aligned_tsdtype_vec& A,\n    const int ProfileLength,\n    aligned_tsdtype_vec& AMeanScaledSigSqrM,\n    aligned_tsdtype_vec& ASigmaInv,\n    const idx_dtype ts_len)\n{\n\t//TODO: refactore raw pointers, const method\n\tconst size_t timeSeriesLength =(ts_len==-1)?A.size():ts_len;\n\tstd::vector<tsa_dtype> AMean(A.size()-windowSize+1);\n\tAMeanScaledSigSqrM.resize(A.size()-windowSize+1);\n\tASigmaInv.resize(A.size()-windowSize+1);\n\tconst tsa_dtype sqrt_m = sqrt(static_cast<tsa_dtype>(windowSize));\n\n\ttsa_dtype* ACumSum = new tsa_dtype[timeSeriesLength];\n\tACumSum[0] = A[0];\n\tfor (int i = 1; i < timeSeriesLength; i++)\n\t\tACumSum[i] = A[i] + ACumSum[i - 1];\n\ttsa_dtype* ASqCumSum = new tsa_dtype[timeSeriesLength];\n\tASqCumSum[0] = A[0] * A[0];\n\tfor (int i = 1; i < timeSeriesLength; i++)\n\t\tASqCumSum[i] = A[i] * A[i] + ASqCumSum[i - 1];\n\ttsa_dtype* ASum = new tsa_dtype[ProfileLength];\n\tASum[0] = ACumSum[windowSize - 1];\n\tfor (int i = 0; i < timeSeriesLength - windowSize; i++)\n\t\tASum[i + 1] = ACumSum[windowSize + i] - ACumSum[i];\n\ttsa_dtype* ASumSq = new tsa_dtype[ProfileLength];\n\tASumSq[0] = ASqCumSum[windowSize - 1];\n\tfor (int i = 0; i < timeSeriesLength - windowSize; i++)\n\t\tASumSq[i + 1] = ASqCumSum[windowSize + i] - ASqCumSum[i];\n\tfor (int i = 0; i < ProfileLength; i++){\n\t\t    AMean[i] = ASum[i] / windowSize;\n\t    }\n\ttsa_dtype* ASigmaSq = new tsa_dtype[ProfileLength];\n\tfor (int i = 0; i < ProfileLength; i++)\n\t\tASigmaSq[i] = ASumSq[i] / windowSize - AMean[i] * AMean[i];\n\n\tfor (int i = 0; i < ProfileLength; i++) {\n\t\tASigmaInv[i] = 1.0/sqrt(ASigmaSq[i]);\n\t\tAMeanScaledSigSqrM[i] = AMean[i]*ASigmaInv[i]*sqrt_m;\n\t}\n\tdelete [] ACumSum;\n\tdelete [] ASqCumSum;\n\tdelete [] ASum;\n\tdelete [] ASumSq;\n\tdelete [] ASigmaSq;\n}\n\nvoid ScrimpSequOpt::init_diagonals(const int first_diag, const int last_diag, aligned_tsdtype_vec& initial_zs, const aligned_tsdtype_vec& A, const int windowSize)\n{\n\tconst size_t profileLength = A.size() - windowSize+1;\n//\tinitial_zs.reserve(profileLength);\n\tassert(initial_zs.size() >= profileLength);\n\t//evaluate the fist distance value in the current diagonal\n\tfor (size_t diag = first_diag; diag <= last_diag; ++diag) {\n\t\ttsa_dtype lastz=0;\n\t\tfor (int k = 0; k < windowSize; k++)\n\t\t{\n\t\t\tlastz += A[k+diag]*A[k];\n\t\t}\n\t\tinitial_zs[diag] = lastz;\n//std::cout << \"inited \" << diag << \" with \" << lastz << std::endl;\n\t}\n}\n\nvoid ScrimpSequOpt::init_all_diagonals(aligned_tsdtype_vec& initial_zs, const aligned_tsdtype_vec& A, const int windowSize) {\n\t//init diagonals 0 to profileLength-1\n\tinit_diagonals(0, A.size()-windowSize+1, initial_zs, A, windowSize);\n}\n\nvoid ScrimpSequOpt::eval_diagonal(aligned_int_vec& profileIndex, const aligned_tsdtype_vec& A, const aligned_tsdtype_vec& initial_zs, const int windowSize, const aligned_tsdtype_vec& ASigmaInv, const aligned_tsdtype_vec& AMeanScaledSigSqrM, const int diag, aligned_tsdtype_vec& profile)\n{\n\tconst int profileLength = AMeanScaledSigSqrM.size();\n\ttsa_dtype corrScore;\n#ifdef PROFILING\n\tlong updateCtr = 0;\n#endif\n\n\ttsa_dtype tmpz = initial_zs[diag]; //rather use a local, to avoid innecessary writes to the referenced memory\n\tfor (int j=diag; j<profileLength; j++)\n\t{\n\t\tint i=j-diag;\n\n\t\tcorrScore = (tmpz* (ASigmaInv[j] * ASigmaInv[i]) - AMeanScaledSigSqrM[j] * AMeanScaledSigSqrM[i]) ;\n\t\ttmpz += A[j+windowSize]*A[i+windowSize]  - A[j]*A[i];\n\n\t\tif (corrScore > profile[j])\n\t\t{\n\t\t\tprofile[j] = corrScore;\n\t\t\tprofileIndex [j] = i;\n#ifdef PROFILING\n\t\t\tupdateCtr+=1;\n#endif\n\t\t}\n\t\tif (corrScore > profile[i])\n\t\t{\n\t\t\tprofile[i] = corrScore;\n\t\t\tprofileIndex [i] = j;\n#ifdef PROFILING\n\t\t\tupdateCtr+=1;\n#endif\n\t\t}\n\t}\n\n#ifdef PROFILING\n\t_profileUpdateCounter += updateCtr;\n#endif\n}\n\nvoid ScrimpSequOpt::compute_matrix_profile(const Scrimppp_params& params)\n{\n\tstd::chrono::high_resolution_clock::time_point tstart, tend;\n\tstd::chrono::duration<double> time_elapsed;\n\taligned_tsdtype_vec A = fetch_time_series<aligned_tsdtype_vec::allocator_type>(params); //load the time series data\n\taligned_tsdtype_vec AMeanScaledSqrtM(A.size());\n\taligned_tsdtype_vec ASigmaInv(A.size());\n\tint windowSize = params.query_window_len;\n\tint exclusionZone = windowSize / 4;\n\tint timeSeriesLength = A.size();\n\tint ProfileLength = timeSeriesLength - windowSize + 1;\n\t//Initialize Matrix Profile and Matrix Profile Index\n\taligned_tsdtype_vec profile(ProfileLength, 0.0);\n\taligned_int_vec profileIndex(ProfileLength, 0);\n\taligned_tsdtype_vec initial_zs(timeSeriesLength); // stores products between two Timeseries values with a distinct offset\n\tstd::vector<int> idx; // store indices of the diagonals, defining their evaluation order\n\tidx.reserve(ProfileLength-exclusionZone-1);\n\n\t//several monitors for performance measurement\n\tPerfCounters setup_perf(\"setup\");\n\tPerfCounters init_diag_perf(\"diagonal initialization\");\n\tPerfCounters eval_diag_perf(\"diagonal evaluation\");\n\n\t//validation of parameters\n\tif (timeSeriesLength < windowSize) {\n\t\tthrow std::invalid_argument(\"ERROR: Time series is shorter than the window length, can not proceed\");\n\t}\n\n\tEXEC_INFO( \"Sequential SCRIMP matrix profile computation with profile length \" << ProfileLength << \" and window size \" << windowSize);\n\n\n\t{\n\t\tScopedPerfAccumulator monitor(setup_perf);\n\t\t//precompute the mean and standard deviations of the sliding windows along the time series\n\t\tprecompute_window_statistics(windowSize, A, ProfileLength, AMeanScaledSqrtM, ASigmaInv);\n\n\t\t//start time measurment\n\t\ttstart = std::chrono::high_resolution_clock::now();\n\n\t\t/******************** SCRIMP ********************/\n\t\t//Random shuffle the computation order of the diagonals of the distance matrix\n\t\tfor (int i = exclusionZone+1; i < ProfileLength; i++) {\n\t\t\tidx.push_back(i);\n\t\t}\n\t\tstd::random_shuffle(idx.begin(), idx.end());\n\t}\n\n\t// compute the first correlation values in the diagonals (i.e. compute the correlation between the first windows)\n\t{\n\t\tScopedPerfAccumulator monitor(init_diag_perf);\n\t\tinit_all_diagonals(initial_zs, A, windowSize);\n\t}\n\t//iteratively evaluate the diagonals of the distance matrix\n\tfor (int ri = 0; ri < idx.size(); ri++)\n\t    {\n\t\t//select a random diagonal\n\t\tint diag = idx[ri];\n\n\t\t//evaluate the second to the last distance values along the diagonal in the matrix and update the matrix profile/matrix profile index.\n\t\t{\n\t\t\tScopedPerfAccumulator monitor(eval_diag_perf);\n\t\t\teval_diagonal(profileIndex, A, initial_zs, windowSize, ASigmaInv, AMeanScaledSqrtM, diag, profile);\n\t\t}\n\n\t\t//Show time per 10000 iterations\n\t\tif ((ri+1) % notification_interval_iter == 0)\n\t\t{\n\t\t\ttend = std::chrono::high_resolution_clock::now();\n\t\t\ttime_elapsed = tend - tstart;\n\t\t\tEXEC_INFO ( \"finished \" << ri+1 << \" iterations after \" << std::setprecision(std::numeric_limits<tsa_dtype>::digits10 + 2) << time_elapsed.count() << \" seconds.\");\n\t\t}\n\t}\n\n\t// apply a correction of the distance values, as we dropped a factor of 2 to avoid unnecessary computations\n\ttsa_dtype twice_m = 2.0*static_cast<tsa_dtype>(windowSize);\n\tfor (auto iter=profile.begin(); iter<profile.end(); ++iter) {\n\t\t(*iter) = twice_m - 2.0 * (*iter);\n\t}\n\n\t// end timer\n\t// tend = time(0);\n\ttend = std::chrono::high_resolution_clock::now();\n\ttime_elapsed = tend - tstart;\n\n\tPERF_LOG ( \"total computation time: \" << std::setprecision(std::numeric_limits<tsa_dtype>::digits10 + 2) << time_elapsed.count() << \" seconds.\" );\n\tconst double triang_len = ProfileLength-exclusionZone;\n\tPERF_LOG ( \"throughput computations: \" << triang_len * triang_len / time_elapsed.count() << \" matrix entries/second\");\n\n\t//store the result\n\tstore_matrix_profile(profile, profileIndex, params);\n\n\tsetup_perf.log_perf();\n\tinit_diag_perf.log_perf();\n\teval_diag_perf.log_perf();\n#ifdef PROFILING\n\tPERF_LOG ( \"number of matrix profile updates: \" << _profileUpdateCounter);\n#endif\n\n}\n", "meta": {"hexsha": "505430640c4506f1fff6481fa139e3a77b3135a9", "size": 8691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scrimppp/src/ScrimpSequOpt.cpp", "max_stars_repo_name": "franzbischoff/ThesisCode", "max_stars_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T22:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-23T03:14:16.000Z", "max_issues_repo_path": "scrimppp/src/ScrimpSequOpt.cpp", "max_issues_repo_name": "franzbischoff/ThesisCode", "max_issues_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scrimppp/src/ScrimpSequOpt.cpp", "max_forks_repo_name": "franzbischoff/ThesisCode", "max_forks_repo_head_hexsha": "b9526fb801893c8d54a937f3d959833148004aa2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-20T22:41:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T09:15:48.000Z", "avg_line_length": 36.0622406639, "max_line_length": 286, "alphanum_fraction": 0.7267287999, "num_tokens": 2494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672089305841, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5597012689729769}}
{"text": "/**\n * @file   svd_armadillo.cc\n * @author Jiangwen Su <uukuguy@gmail.com>\n * @date   2014-12-12 01:06:49\n *\n * @brief\n *\n *\n */\n\n#include \"docset.h\"\n#include \"document.h\"\n#include \"term.h\"\n#include \"logger.h\"\n#include \"lexicon.h\"\n#include \"dmat.h\"\n#include \"smat.h\"\n#include \"svd.h\"\n\n//#include <armadillo>\n#include <mlpack/methods/quic_svd/quic_svd.hpp>\n#include <mlpack/methods/regularized_svd/regularized_svd.hpp>\n\n\ntypedef struct svd_data_t{\n    Document *pDocument;\n    arma::mat &A;\n} svd_data_t;\n\n//void lexicon_term_loop_armadillo(term_t *term, void *user_data)\n//{\n    //svd_data_t *svd_data = (svd_data_t*)user_data;\n    //doc_t *doc = svd_data->doc;\n    //arma::mat &A = svd_data->A;\n\n    //if ( doc_has_term(doc, term) == 1 ) {\n        //uint32_t row = term_get_id(term);\n        //uint32_t col = doc_get_id(doc);\n        ////uint32_t row = doc_get_id(doc);\n        ////uint32_t col = term_get_id(term);\n\n        //double term_tfidf = doc_get_term_tfidf(doc, term);\n        //A(row, col) = term_tfidf;\n    //}\n//}\n\ndmat_t *docset_save_corrmat_armadillo(docset_t *docset, arma::mat& C, const char *filename)\n{\n    uint32_t numRows = C.n_rows;\n    uint32_t numCols = C.n_cols;\n    //dmat_free(docset->corrmat);\n\n    dmat_t *corrmat = dmat_new(numRows, numCols);\n    double *values = dmat_get_values(corrmat);\n    for ( uint32_t row = 0 ; row < numRows ; row++ ){\n        for ( uint32_t col = 0 ; col < numCols ; col++ ){\n            double v = C(row, col);\n            *values = v;\n            values++;\n        }\n    }\n\n    //docset->corrmat = corrmat;\n\n    //dmat_save_to_csv(matrix, filename);\n\n    return corrmat;\n}\n\n#include <fstream>\n#include <iomanip>\nint save_singular_value_armadillo(arma::vec &s, const char *filename)\n{\n    std::fstream out(filename, std::ios::out);\n    out << std::setprecision(6);\n    for ( uint32_t i = 0 ; i < s.size() ; i++ ){\n        out << s(i) << std::endl;\n    }\n    return 0;\n}\n\n\ndouble vector_angle_cosine_armadillo(arma::vec &v1, arma::vec &v2, uint32_t size)\n{\n\t// A(dot)B = |A||B|Cos(theta)\n\t// so Cos(theta) = A(dot)B / |A||B|\n\n\tdouble a_dot_b=0;\n\tfor ( uint32_t i = 0 ; i < size ; i++ ) {\n\t\ta_dot_b += v1(i) * v2(i);\n\t}\n\n\tdouble A=0;\n\tfor ( uint32_t j = 0 ; j < size ; j++ ) {\n        A += v1(j) * v1(j);\n\t}\n\tA = sqrt(A);\n\n\tdouble B=0;\n\tfor ( uint32_t k = 0 ; k < size ; k++ ) {\n        B += v2(k) * v2(k);\n\t}\n\tB = sqrt(B);\n\n\treturn a_dot_b / (A * B);\n}\n\nint docset_query_armadillo(docset_t *docset, const char *query_string, uint32_t dimensions)\n{\n    if ( query_string == NULL || strlen(query_string) == 0 )\n        return -1;\n\n\n    Docset *pDocset = (Docset*)(docset->pDocset);\n    const Lexicon &lexicon = pDocset->get_lexicon();\n\n    uint32_t numTerms = pDocset->get_total_terms();\n    uint32_t numDocs = pDocset->get_total_docs();\n    arma::vec q_vct(numTerms, arma::fill::zeros);\n\n    std::istringstream query_stream(query_string);\n    std::string word;\n\twhile (query_stream >> word) {\n        Term *pTerm = lexicon.get_term_by_text(word);\n        if ( pTerm != NULL ){\n            uint32_t term_id = pTerm->m_id;\n            q_vct(term_id) = q_vct(term_id) + 1;\n        }\n    };\n\n    //arma::vec &s = *(arma::vec*)docset->svd_s;\n    //arma::mat &U = *(arma::mat*)docset->svd_U;\n    //arma::mat &V = *(arma::mat*)docset->svd_V;\n    arma::vec s;\n    arma::mat U;\n    arma::mat V;\n\n    arma::vec d_vct(dimensions, arma::fill::zeros);\n\t// Dq = Xq' T S^-1\n\tfor (uint32_t i = 0; i < dimensions; i++) {\n\t\tdouble sum = 0;\n\t\tfor (uint32_t j = 0; j < numTerms; j++) {\n            sum += q_vct(j) * U(j,i);\n\t\t}\n        d_vct(i) = sum * ( 1 / s(i));\n\t}\n\n\t//compare each document with Dq\n\tfor ( uint32_t n = 0 ; n < numDocs ; n++ ) {\n        arma::vec t_vct(dimensions, arma::fill::zeros);\n\t\t// fill temp document vector\n\t\tfor ( uint32_t m = 0 ; m < dimensions ; m++) {\n            t_vct(m) = V(n,m) * s(m);\n\t\t}\n        AddCorrelation(n, vector_angle_cosine_armadillo(d_vct, t_vct, dimensions));\t\n\t}\n\n    uint32_t n = 0;\n    std::vector<struct doc_cor>::const_iterator it;\n\tfor ( it = g_cor.begin() ; it < g_cor.end() ; it++, n++ ) {\n        doc_cor cor = *it;\n        uint32_t doc_id = cor.doc_id;\n        double correlation = cor.correlation;\n\n        Document *pDocument = pDocset->get_document_by_id(doc_id);\n        const char *doc_name = \"<not found>\";\n        if ( pDocument != NULL ){\n            doc_name = pDocument->m_title.c_str();\n        }\n\n        if ( n > g_cor.size() - 10 ) {\n            warning_log(\"%d:<%d,%.3f>%s\", n, doc_id, correlation, doc_name);\n        } else if ( n < 10 ) {\n            notice_log(\"%d:<%d,%.3f>%s\", n, doc_id, correlation, doc_name);\n        }\n\n    }\n    return 0;\n}\n\nint export_vector_to_csv(arma::vec V, const char *filename)\n{\n    std::fstream out(filename, std::ios::out);\n\n    for ( uint32_t n = 0 ; n < V.size() ; n++ ){\n        out << \"C\" << n;\n        if ( n < V.size() - 1 )\n            out << \",\";\n    }\n    out << std::endl;\n\n    for ( uint32_t n = 0 ; n < V.size() ; n++ ){\n        out << V(n);\n        if ( n < V.size() - 1 )\n            out << \",\";\n    }\n    out << std::endl;\n\n    return 0;\n}\n\nint export_matrix_to_csv(arma::mat& C, const char *filename)\n{\n    uint32_t numRows = C.n_rows;\n    uint32_t numCols = C.n_cols;\n\n    std::fstream out(filename, std::ios::out);\n\n    out << \"id,\";\n    for ( uint32_t col = 0 ; col < numCols ; col++ ){\n        out << \"C\" << col;\n        if ( col < numCols - 1 )\n            out << \",\";\n    }\n    out << std::endl;\n\n    for ( uint32_t row = 0 ; row < numRows ; row++ ){\n        out << \"R\" << row << \", \";\n        for ( uint32_t col = 0 ; col < numCols ; col++ ){\n            double v = C(row, col);\n            out << v;\n            if ( col < numCols - 1 )\n                out << \",\";\n        }\n        out << std::endl;\n    }\n    out << std::endl;\n\n    return 0;\n}\n\n/* ==================== docset_do_svd_armadillo() ==================== */\nvoid docset_do_svd_armadillo(docset_t *docset, uint32_t dimensions)\n{\n    GET_TIME_MILLIS(msec0);\n\n    Docset *pDocset = (Docset*)(docset->pDocset);\n    uint32_t numRows = pDocset->get_total_terms();\n    uint32_t numCols = pDocset->get_total_docs();\n    //uint32_t totalNonZeroValues = pDocset->calculate_nonzerovalues();\n\n    //smat_t *tfm = smat_new(numRows, numCols, totalNonZeroValues);\n    smat_t *tfm = pDocset->calculate_tfmatrix();\n\n    arma::mat A(numRows, numCols, arma::fill::zeros);\n    //arma::sp_mat A(numRows, numCols);\n\n    SMAT_LOOP_BEGIN(tfm, numRows, numCols);\n    A(row, col) = value;\n    SMAT_LOOP_END();\n    //uint32_t v = 0;\n    //for ( uint32_t col = 0 ; col < numCols ; col++ ){\n        //for ( ; v < tfm->pointr[col + 1]; v++) {\n            //uint32_t row = tfm->rowind[v];\n            //double value = tfm->values[v];\n            //A(row, col) = value;\n        //}\n\n    //}\n\n    smat_free(tfm);\n\n    GET_TIME_MILLIS(msec1);\n    notice_log(\"svd prepare: %llu.%03llu sec.\", (msec1 - msec0) / 1000, (msec1 - msec0) % 1000);\n\n    //docset->svd_U = (void*)new arma::mat();\n    //docset->svd_s = (void*)new arma::vec();\n    //docset->svd_V = (void*)new arma::mat();\n    //arma::mat &U = *(arma::mat*)docset->svd_U;\n    //arma::vec &s = *(arma::vec*)docset->svd_s;\n    //arma::mat &V = *(arma::mat*)docset->svd_V;\n    arma::mat U;\n    arma::vec s;\n    arma::mat V;\n\n    //uint32_t rank = 10;\n    //uint32_t iterations = 10;\n    //double alpha = 0.01;\n    //double lambda = 0.02;\n    //mlpack::svd::RegularizedSVD<> svd(A, U, V, rank, iterations, alpha, lambda);\n\n    mlpack::svd::QUIC_SVD svd(A, U, V, s, 0.03, 0.1);\n    \n    //const char *side = \"both\";\n    ////const char *side = \"left\";\n    ////const char *side = \"right\";\n    ////const char *mode = \"d\";\n    //const char *mode = \"s\";\n    //arma::svd_econ(U, s, V, A, side, mode);\n\n    uint32_t sv_cnt = s.size();\n    printf(\"Singular Values (%d,%d)\\n\", sv_cnt, sv_cnt);\n    for ( uint32_t n = 0 ; n < sv_cnt ; n++ ){\n        if ( n < 20 ) {\n            printf(\"%.6f \", s(n));\n        } else if ( n == 20 ){\n            printf(\"\\n......\\n\");\n        } else if ( n > sv_cnt - 20) {\n            printf(\"%.6f \", s(n));\n        }\n    }\n    printf(\"\\nU(%d,%d) s(%d,%d) V(%d, %d)\\n\", U.n_rows, U.n_cols, s.n_rows, s.n_cols, V.n_rows, V.n_cols);\n\n\n    GET_TIME_MILLIS(msec2);\n\n    save_singular_value_armadillo(s, \"test-s\");\n\n    // Reduce dimensions\n    arma::mat S(s.n_rows, s.n_rows, arma::fill::zeros);\n    for ( uint32_t i = 0 ; i < s.n_rows ; i++ ){\n        if ( i >= dimensions )\n            s(i) = 0.0;\n        S(i,i) = s(i);\n    }\n\n    //printf(\"Building CorrMatrix...\\n\");\n    //arma::mat C = U * S * V;\n\n    GET_TIME_MILLIS(msec21);\n\n    printf(\"Saving CorrMatrix...\\n\");\n    //docset_save_corrmat_armadillo(docset, C, \"test.corrmat\");\n\n    export_matrix_to_csv(U, \"./U.csv\");\n    export_matrix_to_csv(V, \"./V.csv\");\n    export_vector_to_csv(s, \"./s.csv\");\n\n    GET_TIME_MILLIS(msec3);\n\n    notice_log(\"svd do: %llu.%03llu sec.\", (msec2 - msec1) / 1000, (msec2 - msec1) % 1000);\n    notice_log(\"Build CorrMatrix do: %llu.%03llu sec.\", (msec21 - msec2) / 1000, (msec21 - msec2) % 1000);\n    notice_log(\"Save CorrMatrix do: %llu.%03llu sec.\", (msec3 - msec21) / 1000, (msec3 - msec21) % 1000);\n\n    notice_log(\"svd total: %llu.%03llu sec.\", (msec3 - msec0) / 1000, (msec3 - msec0) % 1000);\n\n}\n\n", "meta": {"hexsha": "ba6dd628bdeb081ad7e5e58b2b1b4d993747eef4", "size": 9261, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/datagraph/svd/svd_armadillo.cc", "max_stars_repo_name": "uukuguy/everdata", "max_stars_repo_head_hexsha": "194c799279c72c30cec351e26f4432e1298dbdbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/datagraph/svd/svd_armadillo.cc", "max_issues_repo_name": "uukuguy/everdata", "max_issues_repo_head_hexsha": "194c799279c72c30cec351e26f4432e1298dbdbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/datagraph/svd/svd_armadillo.cc", "max_forks_repo_name": "uukuguy/everdata", "max_forks_repo_head_hexsha": "194c799279c72c30cec351e26f4432e1298dbdbd", "max_forks_repo_licenses": ["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.3185840708, "max_line_length": 106, "alphanum_fraction": 0.5484288954, "num_tokens": 3049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5596376614084748}}
{"text": "//  (C) Copyright Nick Thompson 2019.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_CONDITION_NUMBERS_HPP\n#define BOOST_MATH_TOOLS_CONDITION_NUMBERS_HPP\n#include <cmath>\n#include <boost/math/differentiation/finite_difference.hpp>\n\nnamespace boost::math::tools {\n\ntemplate<class Real, bool kahan=true>\nclass summation_condition_number {\npublic:\n    summation_condition_number(Real const x = 0)\n    {\n        using std::abs;\n        m_l1 = abs(x);\n        m_sum = x;\n        m_c = 0;\n    }\n\n    void operator+=(Real const & x)\n    {\n        using std::abs;\n        // No need to Kahan the l1 calc; it's well conditioned:\n        m_l1 += abs(x);\n        if constexpr(kahan)\n        {\n            Real y = x - m_c;\n            Real t = m_sum + y;\n            m_c = (t-m_sum) -y;\n            m_sum = t;\n        }\n        else\n        {\n            m_sum += x;\n        }\n    }\n\n    inline void operator-=(Real const & x)\n    {\n        this->operator+=(-x);\n    }\n\n    // Is operator*= relevant? Presumably everything gets rescaled,\n    // (m_sum -> k*m_sum, m_l1->k*m_l1, m_c->k*m_c),\n    // but is this sensible? More important is it useful?\n    // In addition, it might change the condition number.\n\n    [[nodiscard]] Real operator()() const\n    {\n        using std::abs;\n        if (m_sum == Real(0) && m_l1 != Real(0))\n        {\n            return std::numeric_limits<Real>::infinity();\n        }\n        return m_l1/abs(m_sum);\n    }\n\n    [[nodiscard]] Real sum() const\n    {\n        // Higham, 1993, \"The Accuracy of Floating Point Summation\":\n        // \"In [17] and [18], Kahan describes a variation of compensated summation in which the final sum is also corrected\n        // thus s=s+e is appended to the algorithm above).\"\n        return m_sum + m_c;\n    }\n\n    [[nodiscard]] Real l1_norm() const\n    {\n        return m_l1;\n    }\n\nprivate:\n    Real m_l1;\n    Real m_sum;\n    Real m_c;\n};\n\ntemplate<class F, class Real>\nReal evaluation_condition_number(F const & f, Real const & x)\n{\n    using std::abs;\n    using std::isnan;\n    using std::sqrt;\n    using boost::math::differentiation::finite_difference_derivative;\n\n    Real fx = f(x);\n    if (isnan(fx))\n    {\n        return std::numeric_limits<Real>::quiet_NaN();\n    }\n    bool caught_exception = false;\n    Real fp;\n    try\n    {\n        fp = finite_difference_derivative(f, x);\n    }\n    catch(...)\n    {\n        caught_exception = true;\n    }\n\n    if (isnan(fp) || caught_exception)\n    {\n        // Check if the right derivative exists:\n        fp = finite_difference_derivative<decltype(f), Real, 1>(f, x);\n        if (isnan(fp))\n        {\n            // Check if a left derivative exists:\n            const Real eps = (std::numeric_limits<Real>::epsilon)();\n            Real h = - 2 * sqrt(eps);\n            h = boost::math::differentiation::detail::make_xph_representable(x, h);\n            Real yh = f(x + h);\n            Real y0 = f(x);\n            Real diff = yh - y0;\n            fp = diff / h;\n            if (isnan(fp))\n            {\n                return std::numeric_limits<Real>::quiet_NaN();\n            }\n        }\n    }\n\n    if (fx == 0)\n    {\n        if (x==0 || fp==0)\n        {\n            return std::numeric_limits<Real>::quiet_NaN();\n        }\n        return std::numeric_limits<Real>::infinity();\n    }\n\n    return abs(x*fp/fx);\n}\n\n}\n#endif\n", "meta": {"hexsha": "66ef66575efdcc84a317098e765d6bb4a778bd07", "size": 3498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/tools/condition_numbers.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/tools/condition_numbers.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/tools/condition_numbers.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": 24.9857142857, "max_line_length": 123, "alphanum_fraction": 0.5540308748, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5596376508200859}}
{"text": "/*\n * $Revision: 615 $ $Date: 2011-06-22 12:02:16 -0700 (Wed, 22 Jun 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 \"Atmosphere.h\"\n#include \"TextureMap.h\"\n#include \"Units.h\"\n#include \"Debug.h\"\n#include \"Intersect.h\"\n#include \"DataChunk.h\"\n#include \"internal/InputDataStream.h\"\n#include \"internal/OutputDataStream.h\"\n#include <GL/glew.h>\n#include <Eigen/Array>\n#include <cmath>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\n// Indices of refraction are from http://physics.info/refraction/ )\n\n/** Index of refraction of air at 0 degrees C.\n  */\nconst double Atmosphere::IndexOfRefraction_Air_0 = 1.00029238;\n\n/** Index of refraction of air at 15 degrees C.\n  */\nconst double Atmosphere::IndexOfRefraction_Air_15 = 1.00027712;\n\n// Density of air in kilograms per cubic meter at:\n//   0 degrees C\n//   15 degrees C\nstatic const double Density_Air_0 = 1.292;\nstatic const double Density_Air_15 = 1.225;\n\n// Mass of one mole of air in kilograms\nstatic const double MolarMass_Air = 0.0289644;\n\nstatic const double Mole = 6.0221415e23;\n\nstatic const float MieScattering_ClearSky = 2.10e-6f;\n\n/** Molecules of air per cubic meter at sea level on Earth at 0 degrees C\n  */\nconst double Atmosphere::MolecularDensity_Air_0 = Mole * Density_Air_0 / MolarMass_Air;\n\n/** Molecules of air per cubic meter at sea level on Earth at 15 degrees C\n  */\nconst double Atmosphere::MolecularDensity_Air_15 = Mole * Density_Air_15 / MolarMass_Air;\n\nstatic const double EarthEquatorialRadius = 6378.14;\n\nstatic const Vector3d standardWavelengths(650.0, 550.0, 440.0);\n\n// Calculate the Rayleigh scattering coefficient for the specified\n// wavelength (in nanometers), index of refraction n, and molecular\n// density (particles per cubic meter.)\nstatic double rayleighScattering(double wavelength, double n, double N)\n{\n    return (8.0 * pow(PI, 3.0) * pow(n * n - 1.0, 2.0)) / (3.0 * N * pow(wavelength * 1.0e-9, 4.0));\n}\n\n\n// Temporary workaround for an apparent Eigen bug with g++ 4.2 on Mac OS X. We need to avoid\n// using the vector::resize() method on Eigen's vector specialization for objects that require\n// alignment.\ntemplate<typename V> void resizeVector(V& v, typename V::size_type new_size, const typename V::value_type& x)\n{\n    if (new_size < v.size())\n    {\n        v.erase(v.begin() + new_size, v.end());\n    }\n    else if (new_size > v.size())\n    {\n        v.insert(v.end(), new_size - v.size(), x);\n    }\n}\n\n\n/** Construct a new atmosphere with default values approximately correct\n  * for Earth.\n  */\nAtmosphere::Atmosphere() :\n    m_planetRadius(float(EarthEquatorialRadius)),\n    m_rayleighScaleHeight(8.0f),\n    m_mieScaleHeight(1.2f),\n    m_mieScatteringCoeff(MieScattering_ClearSky),\n    m_mieAsymmetry(0.76f),\n    m_absorptionCoeff(Vector3f::Zero()),\n    m_transmittanceHeightSamples(0),\n    m_transmittanceViewAngleSamples(0),\n    m_scatterHeightSamples(0),\n    m_scatterViewAngleSamples(0),\n    m_scatterSunAngleSamples(0)\n{\n    computeRayleighScatteringCoeff(IndexOfRefraction_Air_15, MolecularDensity_Air_15);\n}\n\n\nAtmosphere::~Atmosphere()\n{\n}\n\n\n/** Compute realistic Rayleigh scattering coefficients for the specified index\n  * of refraction n and molecular density N.\n  *\n  * @param n index of refraction\n  * @param N molecular density at ground level in molecules / cubic meter.\n  */\nvoid\nAtmosphere::computeRayleighScatteringCoeff(double n, double N)\n{\n    Vector3d coeff(rayleighScattering(standardWavelengths.x(), n, N),\n                   rayleighScattering(standardWavelengths.y(), n, N),\n                   rayleighScattering(standardWavelengths.z(), n, N));\n    m_rayleighScatteringCoeff = coeff.cast<float>();\n}\n\n\n/** Get the approximate color of the atmosphere due to Rayleigh scattering\n  * over the specified distance in meters. This is used for simplified\n  * atmosphere rendering that doesn't include all the effects of scattering.\n  */\nSpectrum\nAtmosphere::color(float distance) const\n{\n    Vector3f s = distance * m_rayleighScatteringCoeff;\n    Vector3f rgb = Vector3f::Ones() - Vector3f(exp(-s.x()), exp(-s.y()), exp(-s.z()));\n\n    // Normalize the color\n    rgb /= rgb.maxCoeff();\n\n    return Spectrum(rgb.x(), rgb.y(), rgb.z());\n}\n\n\n/** Get the height at which the atmosphere is effectively transparent.\n  * The density of the atmosphere decreases exponentially with altitude. Although\n  * it is never zero, in practice we need to choose some finite volume for rendering\n  * the atmospheric halo around a planet. We choose a height large enough to avoid\n  * a sharp cutoff artifact, but small enough so that the GPU doesn't waste cycles\n  * drawing a lot of transparent pixels.\n  */\nfloat\nAtmosphere::transparentHeight() const\n{\n    return 8.0f * max(m_rayleighScaleHeight, m_mieScaleHeight);\n}\n\n\nTextureMap*\nAtmosphere::transmittanceTexture() const\n{\n    return m_transmittanceTexture.ptr();\n}\n\n\nTextureMap*\nAtmosphere::scatterTexture() const\n{\n    return m_scatterTexture.ptr();\n}\n\n\n/** Build precomputed scattering tables. generateTextures() must be called after this function in\n  * order to be able to render objects with precomputed atmospheric scattering.\n  */\nvoid\nAtmosphere::computeScattering(unsigned int heightSamples, unsigned int viewAngleSamples, unsigned int sunAngleSamples)\n{\n    computeTransmittanceTable(DefaultTransmittanceTableHeightSamples,\n                              DefaultTransmittanceTableViewAngleSamples);\n    computeInscatterTable(heightSamples,\n                          viewAngleSamples,\n                          sunAngleSamples);\n}\n\n\n/** Build precomputed scattering tables with the default dimensions. generateTextures()\n  * must be called after this function in order to be able to render objects with precomputed\n  * atmospheric scattering.\n  */\nvoid\nAtmosphere::computeScattering()\n{\n    computeScattering(DefaultScatterTableHeightSamples,\n                      DefaultScatterTableViewAngleSamples,\n                      DefaultScatterTableSunAngleSamples);\n}\n\n\nvoid\nAtmosphere::generateTextures()\n{\n    generateTransmittanceTexture();\n    generateInscatterTexture();\n}\n\n\nvoid\nAtmosphere::generateTransmittanceTexture()\n{\n    unsigned int tableSize = m_transmittanceHeightSamples * m_transmittanceViewAngleSamples;\n    if (tableSize < 1)\n    {\n        VESTA_LOG(\"Zero size transmittance table for atmosphere\");\n        return;\n    }\n\n    assert(m_transmittanceTable.size() >= tableSize);\n\n    for (unsigned int i = 0; i < m_transmittanceHeightSamples * m_transmittanceViewAngleSamples; ++i)\n    {\n        m_transmittanceTable[i] = Vector3f(max(0.00001f, min(256.0f, m_transmittanceTable[i].x())),\n                                           max(0.00001f, min(256.0f, m_transmittanceTable[i].y())),\n                                           max(0.00001f, min(256.0f, m_transmittanceTable[i].z())));\n    }\n\n    GLuint texId = 0;\n    glGenTextures(1, &texId);\n    glBindTexture(GL_TEXTURE_2D, texId);\n\n    glTexImage2D(GL_TEXTURE_2D,\n                 0,\n                 GL_RGB16F,\n                 m_transmittanceViewAngleSamples, m_transmittanceHeightSamples,\n                 0,\n                 GL_RGB, GL_FLOAT,\n                 &m_transmittanceTable[0]);\n\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n    // Do not enable mipmapping, as it causes artifacts in some atmospheres (e.g. Titan)\n    // at the outer edge. This could probably be resolved with a custom mipmap generation\n    // algorithm, but for now, we'll just leave mipmaps off.\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n\n    m_transmittanceTexture = new TextureMap(texId, TextureProperties(TextureProperties::Clamp));\n\n    if (GLEW_EXT_framebuffer_object)\n    {\n        glGenerateMipmapEXT(GL_TEXTURE_2D);\n    }\n    else\n    {\n        // Can't create mipmaps, so reset filtering to linear; it's unlikely that\n        // we'll take this path since any GPU that supports floating point textures\n        // and GLSL will also have FBOs.\n        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n    }\n\n    glBindTexture(GL_TEXTURE_2D, 0);\n}\n\n\nvoid\nAtmosphere::generateInscatterTexture()\n{\n    GLuint scatterTexId = 0;\n    glGenTextures(1, &scatterTexId);\n    glBindTexture(GL_TEXTURE_3D, scatterTexId);\n\n    // Clamp scatter table values before converting them to half-floats. On at least one driver,\n    // the conversion from 32-bit float to 16-bit half float seems to be performed incorrectly for\n    // values very near zero.\n    unsigned int tableSize = m_scatterSunAngleSamples * m_scatterViewAngleSamples * m_scatterHeightSamples;\n    for (unsigned int i = 0; i < tableSize; ++i)\n    {\n        m_inscatterTable[i] = Vector4f(max(0.00001f, min(256.0f, m_inscatterTable[i].x())),\n                                       max(0.00001f, min(256.0f, m_inscatterTable[i].y())),\n                                       max(0.00001f, min(256.0f, m_inscatterTable[i].z())),\n                                       max(0.00001f, min(256.0f, m_inscatterTable[i].w())));\n    }\n\n    glTexImage3D(GL_TEXTURE_3D,\n                 0,\n                 GL_RGBA16F,\n                 m_scatterSunAngleSamples, m_scatterViewAngleSamples, m_scatterHeightSamples,\n                 0,\n                 GL_RGBA, GL_FLOAT,\n                 &m_inscatterTable[0]);\n\n    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n    //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n    m_scatterTexture = new TextureMap(scatterTexId, TextureProperties(TextureProperties::Clamp));\n\n    glBindTexture(GL_TEXTURE_3D, 0);\n}\n\n\nstatic float sign(float x)\n{\n    if (x > 0.0f)\n        return 1.0f;\n    else if (x < 0.0f)\n        return -1.0f;\n    else\n        return 0.0f;\n}\n\n\n// h is the viewer's height above the planet surface\n// atmRadius must be larger than planetRadius\nstatic float opticalPathLength(float planetRadius, float atmRadius, float h, float cosViewAngle)\n{\n    // Gamma is 180 - view angle\n    float cosGamma = -cosViewAngle;\n    float sinGamma2 = 1.0f - cosGamma * cosGamma;\n\n    float r = planetRadius + h;\n    float c = r * r * sinGamma2;\n\n    float disc = planetRadius * planetRadius - c;\n    if (disc > 0.0f && cosGamma > 0.0f)\n    {\n        return r * cosGamma - sqrt(disc);\n    }\n    else\n    {\n        disc = atmRadius * atmRadius - c;\n        return r * cosGamma + sqrt(disc);\n    }\n}\n\n\n// Analytic calculation of optical depth\n// Based on approximation from E. Bruneton and F. Neyret, \"Precomputed Atmospheric Scattering\" (2008)\n//     - r is distance of the eye from planet center\n//     - cosZenithAngle is the cosine of the angle between the zenith and view direction\n//     - pathLength is the distance that the ray travels through the atmosphere\n//     - H is the scale height\nstatic float opticalDepth(float r, float cosZenithAngle, float pathLength, float H, float planetRadius)\n{    \n    // C++ version of this GLSL function:\n    // float opticalDepth(float r, float zAngle, float pathLength, float H)\" << endl;\n    // {\n    //     float a = sqrt(r * (0.5 / H));\n    //     vec2 b = a * vec2(zAngle, zAngle + pathLength / r);\n    //     vec2 b2 = b * b;\n    //     vec2 signB = sign(b);\n    //     float x = signB.y > signB.x ? exp(b2.x) : 0.0;\n    //     vec2 y = signB / (2.3193 * abs(b) + sqrt(1.52 * b2 + 4.0)) * vec2(1.0, exp(-pathLength / H * (pathLength / (2.0 * r) + zAngle)));\n    //     return sqrt((6.283185 * H) * r) * exp((planetRadius - r) / H) * (x + dot(y, vec2(1.0, -1.0)));\n    // }\n\n    float a = sqrt(r * (0.5f / H));\n\n    Vector2f b = a * Vector2f(cosZenithAngle, cosZenithAngle + pathLength / r);\n    Vector2f b2 = b.cwise().square();\n    Vector2f signB(sign(b.x()), sign(b.y()));\n\n    float x = signB.y() > signB.x() ? exp(b2.x()) : 0.0f;\n\n    float k = exp(-pathLength / H * (pathLength / (2.0f * r) + cosZenithAngle));\n    float yx = signB.x() / (2.3193f * abs(b.x()) + sqrt(1.52f * b2.x() + 4.0f));\n    float yy = signB.y() / (2.3193f * abs(b.y()) + sqrt(1.52f * b2.y() + 4.0f)) * k;\n    return sqrt((6.283185f * H) * r) * exp((planetRadius - r) / H) * (x + yx - yy);\n}\n\n\nVector3f\nAtmosphere::transmittance(float r, float cosZenithAngle, float pathLength) const\n{\n    float odMie      = opticalDepth(r, cosZenithAngle, pathLength, m_mieScaleHeight, m_planetRadius);\n    float odRayleigh = opticalDepth(r, cosZenithAngle, pathLength, m_rayleighScaleHeight, m_planetRadius);\n\n    const Vector3f exR = m_rayleighScatteringCoeff * 1000.0f;\n    const Vector3f exM = (Vector3f::Constant(m_mieScatteringCoeff) + m_absorptionCoeff) * 1000.0f;\n\n    return (-odMie * exM - odRayleigh * exR).cwise().exp();\n}\n\n\n// Compute the transmittance by looking up the value in the precomputed table. Perform\n// bilinear interpolation among table values.\nEigen::Vector3f\nAtmosphere::transmittance(float r, float cosZenithAngle) const\n{\n    const unsigned int width = m_transmittanceViewAngleSamples;\n    const unsigned int height = m_transmittanceHeightSamples;\n\n    float u = cosZenithAngle * 0.5f + 0.5f;\n    float v = sqrt((r - m_planetRadius) / transparentHeight());\n    u = max(0.0f, min(0.99999f, u));\n    v = max(0.0f, min(0.99999f, v));\n\n    float x = u * (width - 1);\n    float y = v * (height - 1);\n    int ix = (int) x;\n    int iy = (int) y;\n    float fx = x - ix;\n    float fy = y - iy;\n\n    int index = width * iy + ix;\n    Vector3f v0 = m_transmittanceTable[index] * (1.0f - fx) + m_transmittanceTable[index + 1] * fx;\n    Vector3f v1 = m_transmittanceTable[index + width] * (1.0f - fx) + m_transmittanceTable[index + width + 1] * fx;\n\n    return v0 * (1.0f - fy) + v1 * fy;\n}\n\n\n// Non-linear table parametrization:\n//   0 <= t <= 1\n//\n//   height:             h(t) = t^2 * transparentHeight\n//   cos(view angle):    mu(t) = toCosViewAngle()\n//   cos(sun angle):     muS(t) = toCosSunAngle()\n//\n// Inverse mappings:\n//   height:             t = sqrt(h / transparentHeight)\n//   cos(view angle):    t =\n//   cos(sun angle):     t =\n//\n// Notes:\n//   - View and sun angles are both measured from the zenith\n//\n\n// Map a value in [0, 1] to the cosine of the viewing angle\n// This function replaces the parametrization used in Bruneton's paper:\n//     mu = -0.15f + tan(1.5f * v) / tan(1.5f) * 1.15f\n//\n// The change avoids an expensive arctangent function in the shader\n// code.\n//\n// The mapping may be tuned by adjusting the value of the parameter b.\n// b of 0.15 works well for Earth; a larger value should be chosen when the\n// atmosphere extends higher relative to the planet radius.\nstatic inline float toCosViewAngle(float u)\n{\n    float x = u * 2.0f - 1.0f;\n    float sn = x < 0.0f ? 1.0f : -1.0f;\n    return (x * (0.1f - 0.15f * sn) - 0.165f) / (sn * x + 1.1f);\n}\n\n// Map a value in [0, 1] to the cosine of the sun angle\nstatic inline float toCosSunAngle(float u)\n{\n    // Modified from version used in Bruneton paper. This one covers a wider range\n    // of sun angles, which is necessary for larger scale height / planet radius\n    // ratios (e.g. Titan)\n    return (log(1.0f - u * (1.0f - exp(-2.6f))) + 0.6f) / -2.0f;\n}\n\n// Fill a table with transmittance values.\n//\n// Transmittance in a spherical atmosphere can be described as a function of\n// two parameters:\n//    h - the height of the viewer above the planet surface\n//    mu - the cosine of the view angle (angle between the view direction and the zenith)\nvoid\nAtmosphere::computeTransmittanceTable(unsigned int heightSamples,\n                                      unsigned int viewAngleSamples)\n{\n    m_transmittanceHeightSamples = heightSamples;\n    m_transmittanceViewAngleSamples = viewAngleSamples;\n    m_transmittanceTable.resize(heightSamples * viewAngleSamples);\n\n    float maxHeight = transparentHeight();\n    float minHeight = m_planetRadius * 1.0e-6f;\n    const unsigned int integrationSteps = 20;\n\n    // Calculate the extinction coefficients. The are computed separately for Mie and Rayleigh\n    // scattering particles since their densities will generally be described with different\n    // scale heights.\n    const Vector3f Er = m_rayleighScatteringCoeff * 1000.0f;\n    const Vector3f Em = (Vector3f::Constant(m_mieScatteringCoeff) + m_absorptionCoeff) * 1000.0f;\n\n    VESTA_LOG(\"Rayleigh extinction: %f %f %f\", Er.x(), Er.y(), Er.z());\n    VESTA_LOG(\"Mie extinction: %f %f %f\", Em.x(), Em.y(), Em.z());\n\n    for (unsigned int i = 0; i < heightSamples; ++i)\n    {\n        float v = float(i) / float(heightSamples);\n        float h = minHeight + v * v * maxHeight;\n\n        // Calculate the eye position from h\n        Vector3f eye = Vector3f::UnitZ() * (m_planetRadius + h);\n\n        for (unsigned int j = 0; j < viewAngleSamples; ++j)\n        {\n            float u = float(j) / float(viewAngleSamples - 1);\n            float mu = toCosViewAngle(u);\n\n            // Calculate the view direction from mu\n            float cosTheta = mu;\n            float sinTheta = sqrt(max(0.0f, 1.0f - cosTheta * cosTheta));\n            Vector3f viewDir(sinTheta, 0.0f, cosTheta);\n\n            float pathLength = 0.0f;\n            // The view ray will intersect either the planet or the atmosphere shell geometry\n            if (!TestRaySphereIntersection(eye, viewDir, Vector3f::Zero(), m_planetRadius, &pathLength))\n            {\n                TestRaySphereIntersection(eye, viewDir, Vector3f::Zero(), m_planetRadius + maxHeight, &pathLength);\n            }\n\n            // Compute the intersection point\n            Vector3f x0 = eye + pathLength * viewDir;\n\n#if 0\n            // Numerical integration to compute transmittance\n            Vector3f step = (x0 - eye) / float(integrationSteps);\n            float stepLength = pathLength / float(integrationSteps);\n\n            // Sum to get the integral of optical depth between the eye and the intersection\n            // point.\n            Vector3f p = eye;\n            float Tr = 0.0f;\n            float Tm = 0.0f;\n\n            for (unsigned int k = 0; k < integrationSteps; ++k)\n            {\n                float s = p.norm() - m_planetRadius;\n                \n                Tr += exp(-s / m_rayleighScaleHeight);\n                Tm += exp(-s / m_mieScaleHeight);\n                p += step;\n            }\n            Vector3f opticalDepth = (Er * Tr + Em * Tm) * stepLength;\n            Vector3f xmit = (-opticalDepth).cwise().exp();\n#else\n            // Use analytic transmittance calculation\n            Vector3f xmit = transmittance(eye.z(), viewDir.z(), pathLength);\n#endif\n            m_transmittanceTable[i * viewAngleSamples + j] = xmit;\n        }\n    }\n}\n\n\n// Fill a table with scattering values.\n//\n// Scattering in a spherical atmosphere can be described as a function of\n// three parameters:\n//    h - the height of the viewer above the planet surface\n//    mu - the cosine of the view angle (angle between the view direction and the zenith)\n//    muS - the cosine of the sun angle (angle between sun and zenith)\nvoid\nAtmosphere::computeInscatterTable(unsigned int heightSamples,\n                                  unsigned int viewAngleSamples,\n                                  unsigned int sunAngleSamples)\n{\n    m_scatterHeightSamples = heightSamples;\n    m_scatterViewAngleSamples = viewAngleSamples;\n    m_scatterSunAngleSamples = sunAngleSamples;\n\n    unsigned int tableSize = m_scatterHeightSamples * m_scatterViewAngleSamples * m_scatterSunAngleSamples;\n    if (tableSize < 1)\n    {\n        return;\n    }\n\n    //m_inscatterTable.resize(tableSize);\n    resizeVector(m_inscatterTable, tableSize, Vector4f::Zero());\n    if (m_inscatterTable.size() != tableSize)\n    {\n        return;\n    }\n\n    float maxHeight = transparentHeight();\n    float minHeight = m_planetRadius * 1.0e-6f;\n    const unsigned int integrationSteps = 25;\n\n    float atmRadius = m_planetRadius + transparentHeight();\n\n    // Calculate scattering coefficients. These are the same as the extinction coefficients\n    // exception that absorption by Mie scattering particles isn't a factor.\n    const Vector3f Sr = m_rayleighScatteringCoeff * 1000.0f;\n    const float Sm = m_mieScatteringCoeff * 1000.0f;\n    const Vector4f scatterFactors = Vector4f(Sr.x(), Sr.y(), Sr.z(), Sm);\n\n    for (unsigned int i = 0; i < heightSamples; ++i)\n    {\n        VESTA_LOG(\"Scatter texture layer: %d\", i);\n        float w = float(i) / float(heightSamples);\n        float h = minHeight + w * w * maxHeight;\n\n        // Calculate the eye position from h\n        Vector3f eye = Vector3f::UnitZ() * (m_planetRadius + h);\n\n        for (unsigned int j = 0; j < viewAngleSamples; ++j)\n        {\n            float v = float(j) / float(viewAngleSamples - 1);\n            //float mu = 2.0f * v - 1.0f;\n            //float x = v * 2.0f - 1.0f;\n\n            //float mu = (x * 0.1f) / (1.1f - abs(x));\n            //float sn = x + 0.15f < 0.0f ? 1.0f : -1.0f;\n            //float mu = (x * (0.1f - 0.15f * sn) - 0.165f) / (sn * x + 1.1f);\n            float mu = toCosViewAngle(v);\n\n            // Calculate the view direction from mu\n            float cosTheta = mu;\n            float sinTheta = sqrt(max(0.0f, 1.0f - cosTheta * cosTheta));\n            Vector3f viewDir(sinTheta, 0.0f, cosTheta);\n\n            float pathLength = 0.0f;\n            // The view ray will intersect either the planet or the atmosphere shell geometry\n            if (!TestRaySphereIntersection(eye, viewDir, Vector3f::Zero(), m_planetRadius, &pathLength))\n            {\n                TestRaySphereIntersection(eye, viewDir, Vector3f::Zero(), m_planetRadius + maxHeight, &pathLength);\n            }\n\n            // Compute the intersection point\n            Vector3f x0 = eye + pathLength * viewDir;\n\n            Vector3f step = (x0 - eye) / float(integrationSteps);\n            float stepLength = pathLength / float(integrationSteps);\n\n            Vector3f viewRayTransmittance = transmittance(eye.z(), viewDir.z(), pathLength);\n            //Vector3f viewRayTransmittance = transmittance(eye.z(), viewDir.z());\n\n            for (unsigned int k = 0; k < sunAngleSamples; ++k)\n            {\n                float u = float(k) / float(sunAngleSamples - 1);\n                //float muS = 2.0f * u - 1.0f;\n                float muS = toCosSunAngle(u);//(log(1.0f - u * (1.0f - exp(-3.6f))) + 0.6f) / -3.0f;\n\n                // Calculate the sun direction from mu\n                float cosPhi = muS;\n                float sinPhi2 = 1.0f - cosPhi * cosPhi;\n                float sinPhi = sqrt(max(0.0f, sinPhi2));\n                Vector3f sunDir(sinPhi, 0.0f, cosPhi);\n\n                // Sum to get the integral of optical depth between the eye and the intersection\n                // point.\n                Vector3f p = eye;\n                Vector4f inscatter = Vector4f::Zero();\n\n                for (unsigned int l = 0; l < integrationSteps; ++l)\n                {\n                    float r = p.norm();\n                    float s = r - m_planetRadius;\n\n                    // Compute the transmittance along the view ray\n                    Vector3f viewXmit = transmittance(eye.z(), viewDir.z(), l * stepLength);\n                    //Vector3f viewXmit = viewRayTransmittance.cwise() / transmittance(r, p.dot(viewDir) / r, pathLength - (l + 1) * stepLength);\n                    //Vector3f viewXmit = viewRayTransmittance.cwise() / transmittance(r, p.dot(viewDir) / r);\n\n                    float cosPsi = p.dot(sunDir) / r;\n                    float sinPsi2 = 1.0f - cosPsi * cosPsi;\n\n                    // Compute the transmittance along the path to the sun\n                    float sunPathLength = -r * cosPsi + sqrt(atmRadius * atmRadius - r * r * sinPsi2);\n                    Vector3f sunXmit = transmittance(r, cosPsi, sunPathLength);\n                    float d1 = opticalDepth(r, cosPsi, sunPathLength, m_rayleighScaleHeight, m_planetRadius);\n                    float d2 = opticalDepth(r, cosPsi, sunPathLength, m_mieScaleHeight, m_planetRadius);\n\n                    Vector3f xmit = sunXmit.cwise() * viewXmit;\n                    inscatter.start<3>() += (exp(-s / m_rayleighScaleHeight) * stepLength) * xmit;\n                    inscatter.w() += exp(-s / m_mieScaleHeight) * stepLength * xmit.x();\n\n                    p += step;\n                }\n\n                m_inscatterTable[(i * viewAngleSamples + j) * sunAngleSamples + k] = inscatter.cwise() * scatterFactors;\n            }\n        }\n    }\n}\n\n\n/** Load an atmosphere from the contents of a .atmscat file. generateTextures() must be\n  * after this function in order to be able to render objects with precomputed\n  * atmospheric scattering.\n  *\n  * atmscat file header format:\n  *\n  * bytes          contents\n  * -------------------------------\n  * 0-7            header string (\"atmscatr\")\n  * 8-11           version identifier (uint32)\n  * 12-15          Rayleigh scale height (float)\n  * 16-27          Rayleigh scattering coefficients (3 floats)\n  * 28-31          Mie scale height (float)\n  * 32-35          Mie scattering coefficient (float)\n  * 36-39          Mie asymmetry parameter (float)\n  * 40-51          Absorption coefficients (3 floats)\n  * 52-55          Planet radius (float)\n  * 56-63          Transmittance table dimensions (2 uint32, width * height)\n  * 64-75          Scattering table dimensions (3 uint32, width * height * depth)\n  *\n  * transmittance table (width * height * 3 floats)\n  * scattering table (width * height * depth * 4 floats)\n  */\nAtmosphere*\nAtmosphere::LoadAtmScat(const DataChunk* data)\n{\n    string str(data->data(), data->size());\n    InputDataStream in(str);\n    in.setByteOrder(InputDataStream::BigEndian);\n\n    in.setByteOrder(InputDataStream::LittleEndian);\n\n    char header[8];\n    in.readData(header, sizeof(header));\n    if (string(header, sizeof(header)) != \"atmscatr\")\n    {\n        VESTA_LOG(\"Incorrect header in atmscat file.\");\n        return NULL;\n    }\n\n    v_uint32 version = in.readInt32();\n    if (in.status() != InputDataStream::Good)\n    {\n        VESTA_LOG(\"Error reading header of atmscat file.\");\n        return NULL;\n    }\n\n    if (version != 1)\n    {\n        VESTA_LOG(\"Unsupported atmscat file version %u\", version);\n        return NULL;\n    }\n\n    float HR = in.readFloat();\n    Vector3f rayleighCoeff;\n    rayleighCoeff.x() = in.readFloat();\n    rayleighCoeff.y() = in.readFloat();\n    rayleighCoeff.z() = in.readFloat();\n    float HM = in.readFloat();\n    float mieCoeff = in.readFloat();\n    float mieAsymmetry = in.readFloat();\n    Vector3f absorptionCoeff;\n    absorptionCoeff.x() = in.readFloat();\n    absorptionCoeff.y() = in.readFloat();\n    absorptionCoeff.z() = in.readFloat();\n    float planetRadius = in.readFloat();\n\n    unsigned int transmitWidth = in.readUint32();\n    unsigned int transmitHeight = in.readUint32();\n    unsigned int scatterWidth = in.readUint32();\n    unsigned int scatterHeight = in.readUint32();\n    unsigned int scatterDepth = in.readUint32();\n\n    if (in.status() != InputDataStream::Good)\n    {\n        VESTA_LOG(\"Error reading header of atmscat file.\");\n        return NULL;\n    }\n\n    if (transmitWidth == 0 || transmitHeight == 0)\n    {\n        VESTA_LOG(\"Bad atmscat file (zero dimension for transmittance table)\");\n        return NULL;\n    }\n\n    if (scatterWidth == 0 || scatterHeight == 0 || scatterDepth == 0)\n    {\n        VESTA_LOG(\"Bad atmscat file (zero dimension for inscatter table)\");\n        return NULL;\n    }\n\n    Atmosphere* atmosphere = new Atmosphere();\n    atmosphere->setRayleighScaleHeight(HR);\n    atmosphere->setRayleighScatteringCoeff(rayleighCoeff);\n    atmosphere->setMieScaleHeight(HM);\n    atmosphere->setMieScatteringCoeff(mieCoeff);\n    atmosphere->setMieAsymmetry(mieAsymmetry);\n    atmosphere->setAbsorptionCoeff(absorptionCoeff);\n    atmosphere->setPlanetRadius(planetRadius);\n\n    atmosphere->m_transmittanceHeightSamples = transmitHeight;\n    atmosphere->m_transmittanceViewAngleSamples = transmitWidth;\n    atmosphere->m_transmittanceTable.resize(transmitWidth * transmitHeight);\n    if (atmosphere->m_transmittanceTable.size() != transmitWidth * transmitHeight)\n    {\n        VESTA_LOG(\"Out of memory error (allocating atmosphere transmittance table)\");\n        delete atmosphere;\n        return NULL;\n    }\n\n    for (unsigned int i = 0; i < transmitWidth * transmitHeight; ++i)\n    {\n        Vector3f v;\n        v.x() = in.readFloat();\n        v.y() = in.readFloat();\n        v.z() = in.readFloat();\n        atmosphere->m_transmittanceTable[i] = v;\n    }\n\n    if (in.status() != InputDataStream::Good)\n    {\n        VESTA_LOG(\"Error reading transmittance table in atmscat file.\");\n        delete atmosphere;\n        return NULL;\n    }\n\n    unsigned int scatterTableEntries = scatterWidth * scatterHeight * scatterDepth;\n    atmosphere->m_scatterHeightSamples = scatterDepth;\n    atmosphere->m_scatterViewAngleSamples = scatterHeight;\n    atmosphere->m_scatterSunAngleSamples = scatterWidth;\n    //atmosphere->m_inscatterTable.resize(scatterTableEntries);\n    resizeVector(atmosphere->m_inscatterTable, scatterTableEntries, Vector4f::Zero());\n    if (atmosphere->m_inscatterTable.size() != scatterTableEntries)\n    {\n        VESTA_LOG(\"Out of memory error (allocating atmosphere inscatter table)\");\n        delete atmosphere;\n        return NULL;\n    }\n\n    for (unsigned int i = 0; i < scatterTableEntries; ++i)\n    {\n        Vector4f v;\n        v.x() = in.readFloat();\n        v.y() = in.readFloat();\n        v.z() = in.readFloat();\n        v.w() = in.readFloat();\n        atmosphere->m_inscatterTable[i] = v;\n    }\n    if (in.status() != InputDataStream::Good)\n    {\n        VESTA_LOG(\"Error reading inscatter table in atmscat file.\");\n        delete atmosphere;\n        return NULL;\n    }\n\n    return atmosphere;\n}\n\n/** Save an atmosphere to a .atmscat file.\n  *\n  * atmscat file header format:\n  *\n  * bytes          contents\n  * -------------------------------\n  * 0-7            header string (\"atmscatr\")\n  * 8-11           version identifier (uint32)\n  * 12-15          Rayleigh scale height (float)\n  * 16-27          Rayleigh scattering coefficients (3 floats)\n  * 28-31          Mie scale height (float)\n  * 32-35          Mie scattering coefficient (float)\n  * 36-39          Mie asymmetry parameter (float)\n  * 40-51          Absorption coefficients (3 floats)\n  * 52-55          Planet radius (float)\n  * 56-63          Transmittance table dimensions (2 uint32, width * height)\n  * 64-75          Scattering table dimensions (3 uint32, width * height * depth)\n  *\n  * transmittance table (width * height * 3 floats)\n  * scattering table (width * height * depth * 4 floats)\n  */\nvoid\nAtmosphere::SaveAtmScat(const char* filename)\n{\n    filebuf fb;\n    fb.open (filename,ios::out | ios::binary);\n    ostream os(&fb);\n    OutputDataStream out(os);\n    out.setByteOrder(OutputDataStream::LittleEndian);\n\n    out.writeData(\"atmscatr\", 8);\n\n    out.writeInt32(1);\n    if (out.status() != OutputDataStream::Good)\n    {\n        VESTA_LOG(\"Error writing header of atmscat file.\");\n        return;\n    }\n\n    out.writeFloat(m_rayleighScaleHeight);\n    out.writeFloat(m_rayleighScatteringCoeff.x());\n    out.writeFloat(m_rayleighScatteringCoeff.y());\n    out.writeFloat(m_rayleighScatteringCoeff.z());\n    out.writeFloat(m_mieScaleHeight);\n    out.writeFloat(m_mieScatteringCoeff);\n    out.writeFloat(m_mieAsymmetry);\n    out.writeFloat(m_absorptionCoeff.x());\n    out.writeFloat(m_absorptionCoeff.y());\n    out.writeFloat(m_absorptionCoeff.z());\n    out.writeFloat(m_planetRadius);\n    out.writeUint32(m_transmittanceViewAngleSamples);\n    out.writeUint32(m_transmittanceHeightSamples);\n    out.writeUint32(m_scatterSunAngleSamples);\n    out.writeUint32(m_scatterViewAngleSamples);\n    out.writeUint32(m_scatterHeightSamples);\n\n    if (out.status() != OutputDataStream::Good)\n    {\n        VESTA_LOG(\"Error writing header of atmscat file.\");\n        return;\n    }\n\n    for (unsigned int i = 0; i < m_transmittanceTable.size(); ++i)\n    {\n        out.writeFloat(m_transmittanceTable[i].x());\n        out.writeFloat(m_transmittanceTable[i].y());\n        out.writeFloat(m_transmittanceTable[i].z());\n    }\n\n    if (out.status() != OutputDataStream::Good)\n    {\n        VESTA_LOG(\"Error writing transmittance table in atmscat file.\");\n        return;\n    }\n\n    for (unsigned int i = 0; i < m_inscatterTable.size(); ++i)\n    {\n        out.writeFloat(m_inscatterTable[i].x());\n        out.writeFloat(m_inscatterTable[i].y());\n        out.writeFloat(m_inscatterTable[i].z());\n        out.writeFloat(m_inscatterTable[i].w());\n    }\n    if (out.status() != OutputDataStream::Good)\n    {\n        VESTA_LOG(\"Error reading inscatter table in atmscat file.\");\n        return;\n    }\n\n    fb.close();\n}\n", "meta": {"hexsha": "144feffbaea5178a5341363881b405aa7e439151", "size": 33250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/Atmosphere.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/Atmosphere.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/Atmosphere.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 35.8297413793, "max_line_length": 145, "alphanum_fraction": 0.6411729323, "num_tokens": 8875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.5596376448122671}}
{"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_COTD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COTD_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 cotangent of input in degree:\n    \\f$\\cos(\\pi x/180)/\\sin(\\pi x/180)\\f$.\n\n\n    @par Header <boost/simd/function/cotd.hpp>\n\n    @par Note\n\n      As most other trigonometric function cotd can be called\n      with a second optional parameter  which is a tag on speed\n      and accuracy (see @ref cos for further details)\n\n    @see cos, sin, tan, cot, cotpi\n\n\n    @par Example:\n\n      @snippet cotd.cpp cotd\n\n    @par Possible output:\n\n      @snippet cotd.txt cotd\n\n  **/\n  IEEEValue cotd(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cotd.hpp>\n#include <boost/simd/function/simd/cotd.hpp>\n\n#endif\n", "meta": {"hexsha": "a0a52d6665bbd6a213626830bf6b1dfd0e085f24", "size": 1243, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cotd.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/cotd.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/cotd.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.9038461538, "max_line_length": 100, "alphanum_fraction": 0.5888978278, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5596359013378613}}
{"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/math/interpolations/cubicinterpolation.hpp>\n#include <ql/methods/finitedifferences/meshers/concentrating1dmesher.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>\n#include <ql/methods/finitedifferences/utilities/fdmdirichletboundary.hpp>\n#include <ql/methods/finitedifferences/utilities/fdmboundaryconditionset.hpp>\n#include <ql/methods/finitedifferences/boundarycondition.hpp>\n#include <ql/methods/finitedifferences/solvers/fdmbackwardsolver.hpp>\n#include <ql/experimental/models/quadraticlfm.hpp>\n#include <ql/experimental/finitedifferences/fdmdupire1dop.hpp>\n\n#include <boost/function.hpp>\n\n#include <algorithm>\n\nnamespace QuantLib {\n\nQuadraticLfm::QuadraticLfm(\n\tconst std::vector<Real> &rateTimes,\n\tconst std::vector<Real> &initialForwards,\n\tconst std::vector<std::vector<std::vector<Real> > > &sigma,\n\tconst std::vector<std::vector<Real> > &b,\n\tconst std::vector<std::vector<Real> > &c)\n\t: rateTimes_(rateTimes), initialForwards_(initialForwards), sigma_(sigma),\n\t  b_(b), c_(c) {\n\tN_ = rateTimes.size();\n\tQL_REQUIRE(N_ - 1 == initialForwards_.size(),\n\t\t\t   \"rateTimes size (\"\n\t\t\t\t   << N_ << \") minus 1 must be equal to number of forwards (\"\n\t\t\t\t   << initialForwards_.size() << \")\");\n\tK_ = sigma_.size();\n\tQL_REQUIRE(K_ >= 1, \"number of factors (\"\n\t\t\t\t\t\t\t<< K_ << \") must be greater or equal to one\");\n\tfor (Size k = 0; k < K_; ++k) {\n\t\tQL_REQUIRE(N_ - 1 == sigma_[k].size(),\n\t\t\t\t   \"for factor k (\"\n\t\t\t\t\t   << k << \") the number of sigma functions (\"\n\t\t\t\t\t   << sigma_[k].size()\n\t\t\t\t\t   << \") must be equal to the number of forwards N-1 (\"\n\t\t\t\t\t   << (N_ - 1) << \")\");\n\t\tfor (Size i = 0; i < N_ - 1; ++i) {\n\t\t\tQL_REQUIRE(N_ - 1 == sigma_[k][i].size(),\n\t\t\t\t\t   \"for factor k (\" << k << \") and Libor i (\" << i\n\t\t\t\t\t\t\t\t\t\t<< \") the piecewise sigma function \"\n\t\t\t\t\t\t\t\t\t\t   \"must consist of N-1 (\" << (N_ - 1)\n\t\t\t\t\t\t\t\t\t\t<< \") values, but is (\"\n\t\t\t\t\t\t\t\t\t\t<< sigma_[k][i].size() << \")\");\n\t\t}\n\t}\n}\n\nconst void QuadraticLfm::checkSwapParameters(const Size n, const Size m,\n\t\t\t\t\t\t\t\t\t\t\t const Size step) {\n\tQL_REQUIRE(N_ - 1 >= m && m > n && n >= 0,\n\t\t\t   \"for a swap rate 0 <= n (\" << n << \") < m (\" << m << \") <= N-1 (\"\n\t\t\t\t\t\t\t\t\t\t  << (N_ - 1) << \") must hold\");\n\tQL_REQUIRE((m - n) % step == 0,\n\t\t\t   \"m (\" << m << \") minus n (\" << n << \") = \" << (m - n)\n\t\t\t\t\t << \" must be divisible by step (\" << step << \")\");\n\treturn;\n}\n\nint QuadraticLfm::q(const Real t) {\n\tQL_REQUIRE(t >= 0.0 && t < rateTimes_[N_ - 2],\n\t\t\t   \"at time \" << t << \" all forwards are dead\");\n\treturn static_cast<int>(\n\t\tstd::upper_bound(rateTimes_.begin(), rateTimes_.end(), t) -\n\t\trateTimes_.begin());\n}\n\nReal QuadraticLfm::P(const Size n, const Size m) {\n\tQL_REQUIRE(N_ - 1 >= m && m > n && n >= 0, \"for a discount factor 0 <= n (\"\n\t\t\t\t\t\t\t\t\t\t\t\t   << n << \") < m (\" << m\n\t\t\t\t\t\t\t\t\t\t\t\t   << \") <= N-1 (\" << (N_ - 1)\n\t\t\t\t\t\t\t\t\t\t\t\t   << \") must hold\");\n\tReal tmp = 1.0;\n\tfor (Size i = n; i < m; ++i)\n\t\ttmp *=\n\t\t\t1.0 /\n\t\t\t(1.0 + initialForwards_[i] * (rateTimes_[i + 1] - rateTimes_[i]));\n\treturn tmp;\n}\n\nReal QuadraticLfm::S(const Size n, const Size m, const Size step) {\n\tcheckSwapParameters(n, m, step);\n\tReal annuity = 0.0;\n\tfor (Size i = n + step; i <= m; i += step)\n\t\tannuity += P(n, i) * (rateTimes_[i] - rateTimes_[i - step]);\n\treturn (1.0 - P(n, m)) / annuity;\n}\n\nReal QuadraticLfm::dSdL(const Size n, const Size m, const Size step,\n\t\t\t\t\t\tconst Size i, const Real h) {\n\tcheckSwapParameters(n, m, step);\n\tQL_REQUIRE(N_ - 2 >= i && i >= 0, \"for dSdL, 0 <= i (\" << i << \") <= N-2 (\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   << (N_ - 2)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   << \") must hold\");\n\tQL_REQUIRE(h > 0.0, \"for dSdL h (\" << h << \") must be positive\");\n\tReal f = S(n, m, step);\n\tReal tmp = initialForwards_[i];\n\tinitialForwards_[i] += h;\n\tReal fh = S(n, m, step);\n\tinitialForwards_[i] = tmp;\n\treturn (fh - f) / h;\n}\n\nReal QuadraticLfm::eta(const Size n, const Size m, const Size step,\n\t\t\t\t\t   const Real t, const Real s) {\n\tArray sVec(1, s);\n\treturn eta(n, m, step, t, sVec)[0];\n}\n\nDisposable<Array> QuadraticLfm::eta(const Size n, const Size m, const Size step,\n\t\t\t\t\t\t\t\t\tconst Real t, const Array &s) {\n\n\tcheckSwapParameters(n, m, step);\n\n\t// t = 0 can not be calculated\n\tReal t0 = std::max(0.0001, t);\n\n\t// index for vectors where piecewise values are stored (sigma, b, c)\n\tSize ind = static_cast<Size>(q(t0));\n\t// time between last index and t\n\tReal timeToLastIndex = ind == 0 ? t0 : t0 - rateTimes_[ind - 1];\n\t// forward swap rate S(0)\n\tReal s0 = S(n, m, step);\n\n\t// set up vectors\n\n\tstd::vector<Real> qi(m - n, 0.0);    // dS/dL_i * L_i(0) / S(0)\n\tstd::vector<Real> Qi(m - n, 0.0);    // sum_j q_j s_i,j(t)\n\tstd::vector<Real> intQi(m - n, 0.0); // int_0^t Qi(t) dt\n\tstd::vector<std::vector<Real> > sij; // sigma_i,k (t) * sigma_j,k (t)\n\tstd::vector<std::vector<Real> >\n\t\tintsisj; // int_0^t \\sum_k sigma_i,k (t) sigma_j,k (t) dt\n\n\tfor (Size j = n; j < m; ++j) {\n\t\tstd::vector<Real> sijtmp(m - n, 0.0);\n\t\tstd::vector<Real> intsisjtmp(m - n, 0.0);\n\t\tsij.push_back(sijtmp);\n\t\tintsisj.push_back(intsisjtmp);\n\t}\n\n\t// precompute results\n\n\tfor (Size i = n; i < m; ++i) {\n\t\tqi[i - n] = dSdL(n, m, step, i) * initialForwards_[i] / s0;\n\t\tfor (Size k = 0; k < K_; ++k) {\n\t\t\tfor (Size j = n; j < m; ++j) {\n\t\t\t\tsij[i - n][j - n] +=\n\t\t\t\t\tsigma_[k][i - n][ind] * sigma_[k][j - n][ind];\n\t\t\t}\n\t\t}\n\t\tfor (Size j = n; j < m; ++j) {\n\t\t\tfor (Size k = 0; k < K_; ++k) {\n\t\t\t\tintsisj[i - n][j - n] += sigma_[k][i - n][ind] *\n\t\t\t\t\t\t\t\t\t\t sigma_[k][j - n][ind] *\n\t\t\t\t\t\t\t\t\t\t timeToLastIndex;\n\t\t\t\tfor (Size ii = 0; ii < ind; ++ii) {\n\t\t\t\t\tintsisj[i - n][j - n] +=\n\t\t\t\t\t\tsigma_[k][i - n][ii] * sigma_[k][j - n][ii] *\n\t\t\t\t\t\t(rateTimes_[ii + 1] - rateTimes_[ii]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (Size i = n; i < m; ++i) {\n\t\tfor (Size j = n; j < m; ++j) {\n\t\t\tQi[i - n] += qi[j - n] * sij[i - n][j - n];\n\t\t\tfor (Size k = 0; k < K_; ++k) {\n\t\t\t\tintQi[i - n] += qi[j - n] * sigma_[k][i - n][ind] *\n\t\t\t\t\t\t\t\tsigma_[k][j - n][ind] * timeToLastIndex;\n\t\t\t\tfor (Size ii = 0; ii < ind; ++ii) {\n\t\t\t\t\tintQi[i - n] += qi[j - n] * sigma_[k][i - n][ii] *\n\t\t\t\t\t\t\t\t\tsigma_[k][j - n][ii] *\n\t\t\t\t\t\t\t\t\t(rateTimes_[ii + 1] - rateTimes_[ii]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// =================================================================================\n\t// my own derivation (needs work ...)\n\t// =================================================================================\n\n\t// // E_i\n\n\t// std::vector<Real> Ei(m - n, 0.0);\n\n\t// Real denom = 0.0;\n\t// for (Size i = n; i < m; ++i) {\n\t//     for (Size j = n; j < m; ++j) {\n\t//         Real tmp = 0.0;\n\t//         for (Size k = 0; k < K_; ++k) {\n\t//             tmp += intsisj[k][i - n][j - n];\n\t//         }\n\t//         denom += initialForwards_[i] * initialForwards_[j] * qi[i -\n\t//         n] *\n\t//                  qi[j - n] * tmp;\n\t//     }\n\t// }\n\n\t// for (Size i = n; i < m; ++i) {\n\t//     Real tmp1 = 0.0;\n\t//     for (Size k = 0; k < K_; ++k) {\n\t//         for (Size j = n; j < m; ++j) {\n\t//             tmp1 +=\n\t//                 initialForwards_[j] * qi[j - n] * intsisj[k][i - n][j\n\t//                 -\n\t//                 n];\n\t//         }\n\t//     }\n\t//     tmp1 *= initialForwards_[i];\n\t//     Ei[i - n] = tmp1 / denom;\n\t// }\n\n\t// // eta squared\n\n\tArray eta2(s.size(), 0.0);\n\t// for (Size i = n; i < m; ++i) {\n\t//     for (Size j = n; j < m; ++j) {\n\t//         for (Size k = 0; k < s.size(); ++k) {\n\t//             if (i != j) {\n\t//                 eta2[k] += qi[i - n] * qi[j - n] * sij[i - n][j - n]\n\t//                 *\n\t//                            (initialForwards_[i] * initialForwards_[j]\n\t//                            +\n\t//                             b_[i][ind] * Ei[i - n] *\n\t//                             initialForwards_[j]\n\t//                             *\n\t//                                 (s[k] - s0) +\n\t//                             b_[j][ind] * Ei[j - n] *\n\t//                             initialForwards_[i]\n\t//                             *\n\t//                                 (s[k] - s0) +\n\t//                             (c_[i][ind] * Ei[i - n] * Ei[i - n] *\n\t//                                  initialForwards_[j] +\n\t//                              c_[j][ind] * Ei[j - n] * Ei[j - n] *\n\t//                                  initialForwards_[i]) *\n\t//                                 (s[k] - s0) * (s[k] - s0));\n\t//             } else {\n\t//                 eta2[k] += qi[i - n] * qi[i - n] * sij[i - n][i - n]\n\t//                 *\n\t//                            (initialForwards_[i] * initialForwards_[i]\n\t//                            +\n\t//                             2.0 * b_[i][ind] * initialForwards_[i] *\n\t//                                 Ei[i - n] * (s[k] - s0) +\n\t//                             (b_[i][ind] * b_[i][ind] +\n\t//                              2.0 * c_[i][ind] * Ei[i - n] * Ei[i - n]\n\t//                              *\n\t//                                  (s[k] - s0) * (s[k] - s0)));\n\t//             }\n\t//         }\n\t//     }\n\t// }\n\n\t// =================================================================================\n\t// Jonathan's derivation\n\t// =================================================================================\n\n\tReal sigma2 = 0.0, intSigma2 = 0.0;\n\tfor (Size i = n; i < m; ++i) {\n\t\tfor (Size j = n; j < m; ++j) {\n\t\t\tsigma2 += qi[i - n] * qi[j - n] * sij[i - n][j - n];\n\t\t\tintSigma2 += qi[i - n] * qi[j - n] * intsisj[i - n][j - n];\n\t\t}\n\t}\n\n\tReal b = 0.0, c = 0.0;\n\tfor (Size i = n; i < m; ++i) {\n\t\tb += b_[i][ind] * qi[i - n] * Qi[i - n] * intQi[i - n] /\n\t\t\t (sigma2 * intSigma2);\n\t\tc += c_[i][ind] * qi[i - n] * Qi[i - n] * intQi[i - n] * intQi[i - n] /\n\t\t\t (sigma2 * intSigma2 * intSigma2);\n\t}\n\n\tfor (Size k = 0; k < s.size(); ++k) {\n\t\tReal x = (s[k] - s0) / s0;\n\t\teta2[k] = s0 * (1.0 + b * x + c * x * x) * std::sqrt(sigma2);\n\t}\n\n\tfor (Size k = 0; k < s.size(); ++k) {\n\t\t// through the approximation for eta2 it may get negative (?)\n\t\teta2[k] = std::max(eta2[k], 0.0);\n\t}\n\n\treturn eta2;\n\n} // eta\n\nDisposable<std::vector<Real> >\nQuadraticLfm::callPrices(const Size n, const Size m, const Size step,\n\t\t\t\t\t\t const std::vector<Real> &strikes) {\n\n\tcheckSwapParameters(n, m, step);\n\n\t// expiry time\n\tReal expiryTime = rateTimes_[n];\n\n\t// forward swap rate\n\tReal forward = S(n, m, step);\n\n\t// grid parameters (hardcoded here ... !)\n\tconst Real start = std::min(0.00001, strikes.front() * 0.5);\n\tconst Real end = std::max(0.10, strikes.back() * 1.5);\n\tconst Size size = 500;\n\tconst Real density = 0.1;\n\tconst Size steps = static_cast<Size>(std::ceil(expiryTime * 24));\n\tconst Size dampingSteps = 5;\n\n\t// Layout\n\tstd::vector<Size> dim(1, size);\n\tconst boost::shared_ptr<FdmLinearOpLayout> layout(\n\t\tnew FdmLinearOpLayout(dim));\n\n\t// Mesher\n\tconst boost::shared_ptr<Fdm1dMesher> m1(new Concentrating1dMesher(\n\t\tstart, end, size, std::pair<Real, Real>(forward, density), true));\n\tconst std::vector<boost::shared_ptr<Fdm1dMesher> > meshers(1, m1);\n\tconst boost::shared_ptr<FdmMesher> mesher(\n\t\tnew FdmMesherComposite(layout, meshers));\n\n\t// Boundary conditions\n\tFdmBoundaryConditionSet boundaries;\n\n\t// initial values\n\tArray rhs(mesher->layout()->size());\n\tfor (FdmLinearOpIterator iter = layout->begin(); iter != layout->end();\n\t\t ++iter) {\n\t\tReal k = mesher->location(iter, 0);\n\t\trhs[iter.index()] = std::max(forward - k, 0.0);\n\t}\n\n\t// strike grid\n\tconst Array strikeGrid = mesher->locations(0);\n\n\t// local vol function\n\tLocalVolHelper localVol(this, n, m, step, strikeGrid);\n\n\t// solver\n\tboost::shared_ptr<FdmDupire1dOp> map(new FdmDupire1dOp(mesher, localVol));\n\tFdmBackwardSolver solver(map, boundaries,\n\t\t\t\t\t\t\t boost::shared_ptr<FdmStepConditionComposite>(),\n\t\t\t\t\t\t\t FdmSchemeDesc::Douglas());\n\tsolver.rollback(rhs, expiryTime, 0.0, steps, dampingSteps);\n\n\t// interpolate solution\n\tboost::shared_ptr<Interpolation> solution(new CubicInterpolation(\n\t\tstrikeGrid.begin(), strikeGrid.end(), rhs.begin(),\n\t\tCubicInterpolation::Spline, true, CubicInterpolation::SecondDerivative,\n\t\t0.0, CubicInterpolation::SecondDerivative, 0.0));\n\t// boost::shared_ptr<Interpolation> solution(new\n\t// LinearInterpolation(k.begin(),k.end(),rhs.begin()));\n\tsolution->disableExtrapolation();\n\tstd::vector<Real> result(strikes.size());\n\tstd::transform(strikes.begin(), strikes.end(), result.begin(), *solution);\n\treturn result;\n\n} // callPrices\n\n} // namespace QuantLib\n", "meta": {"hexsha": "f3efae2517846172e6e3203b55ff6a0bafb39f94", "size": 12989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/quadraticlfm.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": "ql/experimental/models/quadraticlfm.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": "ql/experimental/models/quadraticlfm.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": 34.0918635171, "max_line_length": 85, "alphanum_fraction": 0.5145122796, "num_tokens": 4177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5596358856318027}}
{"text": "#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\n\nint main(int argc, char *argv[]) {\n    if (argc < 2) {\n        std::cerr << \"# error: no file specified\" << std::endl;\n        return 1;\n    }\n    mat A;\n    A.load(argv[1], raw_ascii);\n    if (A.n_rows != A.n_cols) {\n        std::cerr << \"# error: matrix should be square\" << std::endl;\n        return 2;\n    }\n    mat U, V;\n    vec s;\n    svd(U, s, V, A);\n    U.print(\"U:\");\n    s.print(\"s:\");\n    V.print(\"V:\");\n    mat B = diagmat(s);\n    mat Delta = abs((U*B)*V.t() - A);\n    Delta.print(\"delta:\");\n    return 0;\n}\n", "meta": {"hexsha": "b2f18186aa7965be6eda4de50dc39d6de86288c7", "size": 585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/svd.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Armadillo/svd.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Armadillo/svd.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 20.8928571429, "max_line_length": 69, "alphanum_fraction": 0.4974358974, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.5594864094438965}}
{"text": "#define GLM_FORCE_XYZW_ONLY\n\n#include <iostream>\n#include <sstream>\n#include <time.h>\n\n#include <spob/spob2glm.h>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n#include \"interpolation.h\"\n#include \"draw.h\"\n#include \"spline.h\"\n#include \"interpolation.h\"\n//#include \"mba.hpp\"\n\ntypedef function<void(const std::vector<vec2>&, int)> DrawFunction;\ntypedef function<bool(const vec2&, int)> TerminateFunction;\n\nint n = 4, m = 2;\nint angle = 45;\nbool isFirst = true;\n\nint maxDepth = 100;\nint insideCount = 1;\ndouble min_len = 5.3;\nbool isExperiment = false;\n\ndouble posAnimation = 0;\n\nvoid empty_draw(const std::vector<vec2>& poly, int a) {}\n\n//-----------------------------------------------------------------------------\nstd::pair<space2, space2> getFractalSpaces(space2 space, DrawFunction draw_poly = empty_draw, DrawFunction draw_triangle = empty_draw, int depth = 0) {\n\t// Задаем координаты квадрата\n\tvector<vec2> p = placePolyOnEdge(calcRegularPolygon(n, vec2(0), 1, 0), 0);\n\n\t// Высчитываем координаты прямоугольного треугольника, который лежит своей гипотенузой на оси X, с углом alpha при основании\n\tdouble alpha = spob::deg2rad(angle);\n\tvec2 tr_a(0, 0), tr_b(1, 0), tr_c(cos(alpha), 0);\n\ttr_c = rotate(tr_c, vec2(0), alpha);\n\n\t// Рисуем квадрат\n\tdraw_poly(fromMas(space, p), depth);\n\n\t// Строим пространство, которое находится на верхней стороне квадрата\n\tspace2 tr_line = makeLine2(p[m+1], p[m]);\n\n\t// Переводим координаты треугольника к этому пространству\n\ttr_a = tr_line.from(tr_a);\n\ttr_b = tr_line.from(tr_b);\n\ttr_c = tr_line.from(tr_c);\n\n\tdraw_triangle(fromMas(space, std::vector<vec2>{tr_a, tr_b, tr_c}), depth);\n\n\t// Строим пространства, которые находятся на обоих катетах этого треугольника\n\tspace2 l1 = makeLine2(tr_a, tr_c);\n\tspace2 l2 = makeLine2(tr_c, tr_b);\n\n\t/*l1.j *= 0.8;\n\tl2.j *= 0.8;*/\n\t/*l1 = rotate(l1, l1.pos, spob::deg2rad(-50));\n\tl2 = rotate(l2, l2.pos + l2.i, spob::deg2rad(50));*/\n\n\treturn {l1, l2};\n}\n\n//-----------------------------------------------------------------------------\nvoid draw_pythagoras_tree(space2 space, DrawFunction draw_poly, DrawFunction draw_triangle, TerminateFunction isTerminate, int depth = 0) {\n\t// Выходим из рекурсии, если одна из осей (аналогично и сторона квадрата) имеет длину меньше, чем 2\n\tif (isTerminate(space.i, depth))\n\t\treturn;\n\n\tauto sp = getFractalSpaces(space, draw_poly, draw_triangle, depth);\n\n\t// Рекурсивно строим дерево в этих пространствах\n\tdraw_pythagoras_tree(space.from(sp.first), draw_poly, draw_triangle, isTerminate, depth+1);\n\tdraw_pythagoras_tree(space.from(sp.second), draw_poly, draw_triangle, isTerminate, depth+1);\n}\n\n//-----------------------------------------------------------------------------\nstd::pair<vec2, vec2> calcBoundingBox(void) {\n\tbool isInitialized = false;\n\tvec2 min, max;\n\tdraw_pythagoras_tree(getStandardCrd2(), [&] (const vector<vec2>& poly, int depth) {\n\t\tif (!isInitialized) {\n\t\t\tisInitialized = true;\n\t\t\tmin = poly[0];\n\t\t\tmax = poly[1];\n\t\t}\n\t\tfor (auto& i : poly) {\n\t\t\tif (i.x < min.x) min.x = i.x;\n\t\t\tif (i.y < min.y) min.y = i.y;\n\t\t\tif (i.x > max.x) max.x = i.x;\n\t\t\tif (i.y > max.y) max.y = i.y;\n\t\t}\n\t}, [&] (const vector<vec2>& poly, int depth) {}, [&] (vec2 i, int depth) -> bool {\n\t\treturn depth > 500 || i.length() < 0.01;\n\t});\n\treturn {min, max};\n}\n\n//-----------------------------------------------------------------------------\nvoid draw_animation(void) {\n\tcrd2 standard = getStandardCrd2();\n\tvector<vec2> square = placePolyOnEdge(calcRegularPolygon(4, vec2(0), 1, 0), 0);\n\n\t//-------------------------------------------------------------------------\n\t// Считаем ограничивающий прямоугольник у фрактала и систему координат, которрая будет идеально смотреть на фрактал вместе с границами\n\tauto bbox = calcBoundingBox();\n\tauto viewport = calcViewPort(bbox.first, bbox.second);\n\tviewport = increaseViewportBorderByMinAxis(viewport, 0.1);\n\tdouble coef = viewport.i.length() / viewport.j.length();\n\n\tvec2 size;\n\tdouble sz = 500;\n\tif (coef > 1)\n\t\tsize = vec2(sz, sz / coef);\n\telse\n\t\tsize = vec2(sz * coef, sz);\n\n\t//-------------------------------------------------------------------------\n\t// Инициализируем все изображения\n\tImageGif gif;\n\tImageGif gif2;\n\tImage img(size, viewport, maxDepth+5);\n\tImage img2(size, viewport, maxDepth+5);\n\n\timg.setViewPort(viewport);\n\timg2.setViewPort(viewport);\n\n\tstring t = std::to_string(time(0));\n\tstringstream sout;\n\tsout << \"p3_\" << n << \".\" << m << \"_\" << angle;\n\tgif.start(img.imgs[0]->size(), sout.str() + \".gif\");\n\tgif2.start(img2.imgs[0]->size(), sout.str() + \"_explanation.gif\");\n\n\t//-------------------------------------------------------------------------\n\t// Инициализируем системы координат и интерполяцию\n\tauto sp = getFractalSpaces(standard);\n\t//auto space = sp.second, another = sp.first;\n\tspace2 space, another;\n\tif (isFirst) {\n\t\tspace = sp.first;\n\t\tanother = sp.second;\n\t} else {\n\t\tspace = sp.second;\n\t\tanother = sp.first;\n\t}\n\n\tauto start = standard;\n\tfor (int i = 0; i < insideCount; i++)\n\t\tstart = space.from(start);\n\tauto end = space.from(start);\n\tMatrixPowerInterpolator interpolator(start, end);\n\t//SplineInterpolator2 interpolator(5, start, end);\n\n\t//-------------------------------------------------------------------------\n\t// Основной цикл рисования\n\tdouble count = 60;\n\tfor (int i = 0; i <= count; i += (isExperiment) ? 60 : 1) {\n\t//int i = 0; {\n\t\tcout << i << endl;\n\t\tposAnimation = i/count;\n\n\t\t// Сетка и координаты на изображении-объяснении\n\t\timg.clear(White);\n\t\t//img.clear(Black);\n\t\timg.set_pen(0.5/80.0, Black, 0);\n\n\t\t//img2.clear(White);\n\t\timg2.clear(White);\n\t\timg2.set_pen(1.5/80.0, setAlpha(Gray, 192), 0);\n\t\timg2.draw_grid(standard, 0);\n\t\timg2.set_pen(1.5/80.0, setAlpha(Gray, 192), maxDepth+2);\n\t\timg2.draw_crd(standard, maxDepth+2);\n\t\timg2.set_pen(1/80.0, Black, 0);\n\n\t\t// Интерполированная система координат\n\t\tspace2 c = interpolator.interpolate(posAnimation);\n\t\t//space2 c = interpolate(start, end, posAnimation);\n\t\t//space2 c = interpolateCircular(start, end, posAnimation, 1.12, 2, true);\n\t\tspace2 d = c.from(viewport);\n\t\timg.setViewPort(d);\n\n\t\t// Сам процесс рисования фрактала\n\t\tstatic double max_len = img.screen_tr.fromDir(vec2(0, 1)).length();\n\t\tdouble start_min_len = std::min(min_len + 1, min_len * 2);\n\n\t\tauto draw = [&] (const vector<vec2>& poly, int depth) {\n\t\t\tdouble len = distance(img.screen_tr.from(poly[1]), img.screen_tr.from(poly[0]));\n\t\t\tdouble pos = (len-min_len)/(max_len-min_len);\n\n\t\t\tdouble alphapos = 1;\n\t\t\tif (len < start_min_len) alphapos = std::min((len - min_len)/(start_min_len-min_len), 1.0); \n\n\t\t\t//Color start = rgb(0x15, 0x57, 0x99), end = rgb(0x15, 0x99, 0x57);\n\t\t\t//Color start = Miku, end = Red;\n\t\t\tColor start = getColorBetween(0.1, Miku, White), end = Blue;\n\t\t\t//Color start = getColorBetween(0.5, Red, Black), end = Blue;\n\t\t\t//Color start = White, end = Blue;\n\t\t\t//Color start = Black, end = Blue;\n\t\t\t//Color start = Gray, end = getColorBetween(0.3, Miku, Black);\n\t\t\t//Color start = Gray, end = Red;\n\t\t\t//Color start = getColorBetween(0.5, getColorBetween(0.5, Green, Black), getColorBetween(0.5, Yellow, Black)), end = Red;\n\t\t\tColor clr = setAlpha(getColorBetween(\n\t\t\t\tsqrt(sqrt(pos)), \n\t\t\t\t//pos,\n\t\t\t\tend, start), \n\t\t\t\t//sqrt(sqrt(alphapos)) \n\t\t\t\talphapos\n\t\t\t\t* 128);\n\t\t\timg.imgs[depth+1]->setBrush(clr);\n\t\t\timg2.imgs[depth+1]->setBrush(clr);\n\n\t\t\t{\n\t\t\t\tauto p1 = fromMas(img.screen_tr, poly);\n\t\t\t\tPolygon_d p2;\n\t\t\t\tfor (auto& i : p1) p2.array.push_back(i);\n\t\t\t\timg.imgs[depth+1]->drawPolygon(p2);\n\t\t\t}\n\t\t\t{\n\t\t\t\tauto p1 = fromMas(img2.screen_tr, poly);\n\t\t\t\tPolygon_d p2;\n\t\t\t\tfor (auto& i : p1) p2.array.push_back(i);\n\t\t\t\timg2.imgs[depth+1]->drawPolygon(p2);\n\t\t\t}\n\t\t};\n\n\t\t//#ifndef _DEBUG\n\t\tdraw_pythagoras_tree(standard, draw, draw, [&] (vec2 i, int depth) -> bool {\n\t\t\treturn depth > maxDepth || img.screen_tr.fromDir(i).length() < min_len;\n\t\t});\n\t\t//#endif\n\n\t\t// Рисуем все текущие системы координат\n\t\timg2.draw_crd(start, maxDepth+2);\n\t\timg2.draw_crd(end, maxDepth+2);\n\t\timg2.draw_crd(c, maxDepth+2);\n\n\t\t// Рисуем viewport\n\t\timg2.set_pen(2.5/80.0, Black, maxDepth+2);\n\t\timg2.draw_polygon(fromMas(d, square), maxDepth+2);\n\n\t\timg2.set_pen(0.5/80.0, Gray, maxDepth+2);\n\n\t\tif (!isExperiment) {\n\t\t\tspace2 startcopy = standard;\n\t\t\tdouble startStandardLength = startcopy.fromDir(standard.i).length();\n\t\t\tdouble countSplines = 50;\n\t\t\tfor (int i = 0; i < countSplines; i++) {\n\t\t\t\tdouble countLines = 10;\n\t\t\t\tfor (int j = 0; j < countLines; j++) {\n\t\t\t\t\tauto p1 = interpolator.interpolate(j/countLines);\n\t\t\t\t\tauto p2 = interpolator.interpolate((j+1)/countLines);\n\n\t\t\t\t\t//auto p1 = interpolate(start, end, j/countLines);\n\t\t\t\t\t//auto p2 = interpolate(start, end, (j+1)/countLines);\n\n\t\t\t\t\t//auto p1 = interpolateCircular(start, end, j/countLines, 1.12, 2, true);\n\t\t\t\t\t//auto p2 = interpolateCircular(start, end, (j+1)/countLines, 1.12, 2, true);\n\n\t\t\t\t\timg2.set_pen(4/80.0 * startcopy.fromDir(p1.i).length() / startStandardLength, Black, maxDepth+2);\n\t\t\t\t\timg2.draw_line(startcopy.from(p1.pos), startcopy.from(p2.pos), maxDepth+2);\n\t\t\t\t}\n\t\t\t\tstartcopy = space2(end).from(space2(start).to(startcopy));\n\t\t\t}\n\t\t}\n\n\t\timg.combine_layers();\n\t\timg2.combine_layers();\n\n\t\tgif.process(*img.imgs[0], 2);\n\t\tgif2.process(*img2.imgs[0], 2);\n\t}\n\n\tgif.end();\n\tgif2.end();\n}\n\n//-----------------------------------------------------------------------------\ndouble gauss_kernel(double x) {\n\t// x in [-1, 1], \n\tx *= 3;\n\treturn std::exp(-x*x/2.0);\n}\n\n//-----------------------------------------------------------------------------\nvoid draw_interpolation() {\n\tcrd2 standard = getStandardCrd2();\n\n\t// Начальные расчеты\n\tspace2 a = standard;\n\tspace2 b = standard; b.move(vec2(3, 3)); b = rotate(b, b.pos, spob::deg2rad(70)); b.i *= 1.1; b.j *= 1.1;\n\tspace2 c = standard; c.move(vec2(5, 4)); c = rotate(c, c.pos, spob::deg2rad(-15)); c.i *= 0.3; c.j *= 0.3;\n\n\tglm::mat3 A = getFromMatrix(a);\n\tglm::mat3 B = getFromMatrix(b);\n\tglm::mat3 C = getFromMatrix(c);\n\n\tstd::vector<double> points = {0, 1, 2};\n\tSplineInterpolator3 splinea(points, 0, 5);\n\tSplineInterpolator3 splineb(points, 1, 5);\n\tSplineInterpolator3 splinec(points, 2, 5);\n\n\t//MatrixPowerInterpolator interpolator(a, b);\n\n\t//-------------------------------------------------------------------------\n\t// Цикл расчетов\n\tdouble count = 60;\n\tstd::vector<space2> counts;\n\tfor (int i = 0; i <= 2*count; i++) {\n\t\tdouble t = i/count;\n\n\t\t// Подход на основе полиномов Лагранжа и возведении матрицы в степень\n\t\t/*double ta =  (t*t-3*t+2)/2.0; // 0,1 ; 1,0 ; 2,0\n\t\tdouble tb = 2*t-t*t; // 0,0 ; 1,1 ; 2,0\n\t\tdouble tc = (t*t-t)/2.0; // 0,0 ; 1,0 ; 2,1\n\t\tglm::mat3 P = pow(C, tc) * pow(B, tb) * pow(A, ta);*/\n\n\t\t// Подход на основе ядерных функций и возведении матрицы в степень\n\t\t/*double ta =  gauss_kernel(t); // 0,1 ; 1,0 ; 2,0\n\t\tdouble tb = gauss_kernel(t-1); // 0,0 ; 1,1 ; 2,0\n\t\tdouble tc = gauss_kernel(t-2); // 0,0 ; 1,0 ; 2,1\n\t\tglm::mat3 P = pow(C, tc) * pow(B, tb) * pow(A, ta);*/\n\n\t\tdouble ta = splinea.interpolate(t);\n\t\tdouble tb = splineb.interpolate(t);\n\t\tdouble tc = splinec.interpolate(t);\n\t\tglm::mat3 P = pow(C, tc) * pow(B, tb) * pow(A, ta);\n\t\tcounts.push_back(getToCrd(P));\n\n\t\t//counts.push_back(interpolate(a, b, t));\n\t\t//counts.push_back(interpolateCircular(a, b, t, 5, 2));\n\t\t//counts.push_back(interpolator.interpolate(t));\n\t}\n\n\t//-------------------------------------------------------------------------\n\t// Расчет окна видимости и размера изображения\n\tspace2 viewport = standard;\n\tviewport.pos -= viewport.fromDir(vec2(1, 1)/2.0);\n\tviewport.j *= 7;\n\tviewport.i *= 10;\n\n\tdouble coef = viewport.i.length() / viewport.j.length();\n\tdouble sz = 1000;\n\tvec2 size;\n\tif (coef > 1)\n\t\tsize = vec2(sz, sz / coef);\n\telse\n\t\tsize = vec2(sz * coef, sz);\n\n\t//-------------------------------------------------------------------------\n\t// Инициализируем все изображения\n\tImageGif gif;\n\tImage img(size, viewport);\n\timg.setViewPort(viewport);\n\n\tgif.start(img.imgs[0]->size(), \"interpolation.gif\");\n\n\t//-------------------------------------------------------------------------\n\t// Цикл рисования\n\tfor (int i = 0; i < counts.size(); i++) {\n\t\t//img.setViewPort(counts[i]);\n\n\t\t// Рисуем сетку\n\t\timg.clear(White);\n\t\timg.set_pen(1.5/80.0, setAlpha(Gray, 192));\n\t\timg.draw_grid(standard);\n\t\timg.set_pen(1.5/80.0, setAlpha(Gray, 192));\n\t\timg.draw_crd(standard);\n\n\t\timg.set_pen(1/80.0, Black);\n\t\tvec2 lastPos = a.pos;\n\t\tfor (auto& j : counts) {\n\t\t\timg.set_alpha(16);\n\t\t\timg.draw_crd(j);\n\t\t\timg.set_alpha(255);\n\t\t\timg.draw_line(lastPos, j.pos);\n\t\t\tlastPos = j.pos;\n\t\t}\n\t\tfor (auto j : counts) {\n\t\t\tj = c.from(j);\n\n\t\t\timg.set_alpha(16);\n\t\t\timg.draw_crd(j);\n\t\t\timg.set_alpha(255);\n\t\t\timg.draw_line(lastPos, j.pos);\n\t\t\tlastPos = j.pos;\n\t\t}\n\t\tfor (auto j : counts) {\n\t\t\tj = c.from(c.from(j));\n\n\t\t\timg.set_alpha(16);\n\t\t\timg.draw_crd(j);\n\t\t\timg.set_alpha(255);\n\t\t\timg.draw_line(lastPos, j.pos);\n\t\t\tlastPos = j.pos;\n\t\t}\n\t\timg.set_alpha(255);\n\n\t\t// Рисуем все текущие системы координат\n\t\timg.set_pen(3/80.0, Black);\n\t\timg.draw_crd(a);\n\t\timg.draw_crd(b);\n\t\timg.draw_crd(c);\n\t\timg.draw_crd(counts[i]);\n\n\t\tgif.process(*img.imgs[0], 2);\n\t}\n\n\tgif.end();\n}\n\n//-----------------------------------------------------------------------------\nint main() {\n\t//draw_animation();\n\tdraw_interpolation();\n}", "meta": {"hexsha": "8656a74d573756f5b2274c431517203c83b849cb", "size": 13143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/draw_interpolation.cpp", "max_stars_repo_name": "optozorax/space_objects", "max_stars_repo_head_hexsha": "76ccfe4950aca0065b22d3c0123fd88890167d39", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-11-26T19:03:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T12:20:35.000Z", "max_issues_repo_path": "doc/draw_interpolation.cpp", "max_issues_repo_name": "optozorax/space_objects", "max_issues_repo_head_hexsha": "76ccfe4950aca0065b22d3c0123fd88890167d39", "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": "doc/draw_interpolation.cpp", "max_forks_repo_name": "optozorax/space_objects", "max_forks_repo_head_hexsha": "76ccfe4950aca0065b22d3c0123fd88890167d39", "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": 31.2185273159, "max_line_length": 151, "alphanum_fraction": 0.5999391311, "num_tokens": 4228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.559486404856385}}
{"text": "#include \"arap_material.h\"\n#include \"main.h\"\n#include \"utils.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace materials;\n\nnamespace {\ntemplate <int dim, typename T>\nvoid svd_w(const Eigen::Matrix<T, dim, dim>& mat_inp,\n           Eigen::Matrix<T, dim, dim>& U, Eigen::Matrix<T, dim, 1>& S,\n           Eigen::Matrix<T, dim, dim>& V) {\n    using Mat = Eigen::Matrix<T, dim, dim>;\n    Eigen::JacobiSVD<Mat> svd{mat_inp,\n                              Eigen::ComputeFullU | Eigen::ComputeFullV};\n    S = svd.singularValues();\n    U = svd.matrixU();\n    V = svd.matrixV();\n    if ((U.determinant() < 0) != (V.determinant() < 0)) {\n#if 0\n        // code copied from libsan SVDW to maintain consistency\n        constexpr double EPS = 1e-3;\n        int best_idx = -1, best_idx_nr = dim + 1;\n        for (size_t i = 0; i < dim; ++i) {\n            size_t j = i + 1;\n            // ms already sorted\n            while (j < dim && std::fabs(S(i) - S(j)) < EPS) {\n                ++j;\n            }\n            int nr = j - i;\n            // best case is to negate an odd number of smallest singular\n            // values (so si+sj != 0 in the hessian);\n            // otherwise negate one value whose has the least\n            // repetitionss\n            if (nr <= best_idx_nr || (nr == best_idx_nr + 1 && nr % 2 == 1)) {\n                best_idx = i;\n                best_idx_nr = nr;\n                if (nr == 1) {\n                    break;\n                }\n            }\n            i = j;\n        }\n        if (best_idx_nr == 1 || best_idx_nr % 2 == 0) {\n            U.col(best_idx) = -U.col(best_idx);\n            S(best_idx) = -S(best_idx);\n        } else {\n            for (int i = best_idx; i < best_idx + best_idx_nr; ++i) {\n                U.col(i) = -U.col(i);\n                S(i) = -S(i);\n            }\n        }\n#else\n        U.col(dim - 1) = -U.col(dim - 1);\n        S(dim - 1) = -S(dim - 1);\n#endif\n    }\n}\n}  // namespace\n\ntemplate <int dim, typename T>\nT ARAPElasticityMaterial<dim, T>::EnergyDensity(const MatrixDimT& F) const {\n    MatrixDimT U, V, R;\n    Eigen::Matrix<T, dim, 1> S;\n    svd_w(F, U, S, V);\n    R.noalias() = U * V.transpose();\n    return (F - R).squaredNorm() * (this->mu() * 0.5);\n}\n\ntemplate <int dim, typename T>\ntypename ARAPElasticityMaterial<dim, T>::MatrixDimT\nARAPElasticityMaterial<dim, T>::StressTensor(const MatrixDimT& F) const {\n    MatrixDimT U, V, R;\n    Eigen::Matrix<T, dim, 1> S;\n    svd_w(F, U, S, V);\n    R.noalias() = U * V.transpose();\n    return (F - R) * this->mu();\n}\n\ntemplate <int dim, typename T>\ntypename ARAPElasticityMaterial<dim, T>::MatrixDimT\nARAPElasticityMaterial<dim, T>::StressDifferential(const MatrixDimT& F,\n                                                   const MatrixDimT& dF) const {\n    throw std::runtime_error{\"unimplemented\"};\n}\n\ntemplate <int dim, typename T>\ntypename ARAPElasticityMaterial<dim, T>::MatrixDim2T\nARAPElasticityMaterial<dim, T>::StressDifferential(const MatrixDimT& F) const {\n    cf_assert(dim == 3);\n    MatrixDimT U, V;\n    Eigen::Matrix<T, dim, 1> S;\n    svd_w(F, U, S, V);\n    Eigen::Matrix<T, 3, 3> T0, T1, T2;\n    T0 << 0, -1, 0, 1, 0, 0, 0, 0, 0;\n    T0 = std::sqrt(0.5) * U * T0 * V.transpose();\n    T1 << 0, 0, 0, 0, 0, 1, 0, -1, 0;\n    T1 = std::sqrt(0.5) * U * T1 * V.transpose();\n    T2 << 0, 0, 1, 0, 0, 0, -1, 0, 0;\n    T2 = std::sqrt(0.5) * U * T2 * V.transpose();\n\n    Eigen::Map<Eigen::Matrix<T, 9, 1>> t0{T0.data()}, t1{T1.data()},\n            t2{T2.data()};\n    T s0 = S(0), s1 = S(1), s2 = S(2);\n    Eigen::Matrix<T, 9, 9> H;\n    H.setIdentity();\n    T (*clip)(T);\n    if (baseline::g_hessian_proj) {\n        clip = [](T x) { return std::max<T>(x, 2); };\n    } else {\n        clip = [](T x) { return x; };\n    }\n    H.noalias() -= 2 / (clip(s0 + s1)) * t0 * t0.transpose();\n    H.noalias() -= 2 / (clip(s1 + s2)) * t1 * t1.transpose();\n    H.noalias() -= 2 / (clip(s0 + s2)) * t2 * t2.transpose();\n    return H * this->mu();\n}\n\ntemplate class materials::ARAPElasticityMaterial<3, double>;\n", "meta": {"hexsha": "a28942efca672debaea55922fe0a1dd4704f5d39", "size": 4019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fea/baseline/arap_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/arap_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/arap_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": 32.9426229508, "max_line_length": 80, "alphanum_fraction": 0.5157999502, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927838, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5593225972979764}}
{"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_PIO_180_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_PIO_180_HPP_INCLUDED\n/*!\n * \\file\n**/\n#include <boost/simd/sdk/constant/constant.hpp>\n#include <boost/simd/sdk/constant/register.hpp>\n\n/*!\n * \\ingroup trigo_constant\n * \\defgroup trigo_constant_pio_180 pio_180 constant\n *\n * \\par Description\n * Constant pio_180 : \\f$\\frac\\pi{180}\\f$.\n *\n * \\par Header file\n *\n * \\code\n * #include <nt2/include/functions/pio_180.hpp>\n * \\endcode\n *\n *\n * \\synopsis\n *\n * \\code\n * namespace boost::simd\n * {\n *   template <class T,class A0>\n *     meta::call<tag::_pio_180_(A0)>::type\n *     pio_180();\n * }\n * \\endcode\n *\n *\n * \\param T template parameter of Pio_180\n *\n * \\return type T value\n *\n **/\n\nnamespace nt2\n{\n  namespace tag\n  {\n    BOOST_SIMD_CONSTANT_REGISTER( Pio_180, double\n                                , 0, 0x3c8efa35\n                                , 0x3f91df46a2529d3all\n                                );\n  }\n\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Pio_180, Pio_180);\n}\n\n#endif\n", "meta": {"hexsha": "12a2e75445e9dd7a19c2dad09d1ba55ee6ff1049", "size": 1538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_180.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_180.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/pio_180.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4126984127, "max_line_length": 80, "alphanum_fraction": 0.5539661899, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5593220483035102}}
{"text": "\n#pragma once\n#include <boost/iterator/iterator_facade.hpp>\n#include <cmath>\n#include <cstdio>\n#include <cassert>\n#include <stdexcept>\n#include <limits>\n\nnamespace occgrid {\ntemplate <typename T>\ninline int signum(T val) {\n    return (T(0) < val) - (val < T(0));\n}\n\ntemplate <typename real_t, typename int_t>\nclass ray_trace_iterator\n  : public \n    boost::iterator_facade<\n    ray_trace_iterator<real_t, int_t>\n    , std::pair<int_t, int_t>\n    , boost::forward_traversal_tag\n    , std::pair<int_t, int_t>\n    > \n{\n    private:\n      typedef typename boost::iterator_facade<\n        ray_trace_iterator<real_t, int_t>\n        , std::pair<int_t, int_t>\n        , boost::forward_traversal_tag\n        , std::pair<int_t, int_t>\n        > super_t;\n      // Input arguments\n      real_t \n        px_,\n        py_,\n        dx_, \n        dy_,\n        origin_x_,\n        origin_y_,\n        cell_size_x_, \n        cell_size_y_;\n\n      // intermediate variables for faster computation\n      int_t dirx_, diry_; /// (-1, 0, 1) integral steps (direction)\n      real_t ex_, ey_; /// distance to the nearest grid line\n      real_t Tx_, Ty_; /// Maximum time to collision (from one grid line to next)\n\n      // State of iterator\n      int_t i_, j_; /// Grid index\n      real_t tx_, ty_; /// time to collision to next grid line\n    public:\n      ray_trace_iterator(\n          real_t px,\n          real_t py,\n          real_t dx,\n          real_t dy,\n          real_t origin_x,\n          real_t origin_y,\n          real_t cell_size_x, \n          real_t cell_size_y\n          ) : \n        px_(px),\n        py_(py),\n        dx_(dx),\n        dy_(dy),\n        origin_x_(origin_x),\n        origin_y_(origin_y),\n        cell_size_x_(cell_size_x),\n        cell_size_y_(cell_size_y)\n      {\n        using std::floor;\n        using std::fabs;\n        // shift coordinates \n        px = px - origin_x;\n        py = py - origin_y;\n\n        // current grid cell\n        i_ = static_cast<int_t>(floor(px / cell_size_x));\n        j_ = static_cast<int_t>(floor(py / cell_size_y));\n\n        dirx_ = signum(dx);\n        diry_ = signum(dy);\n\n        // whether the grid line we are going to hit is floor() or ceil()\n        // depends on the direction ray is moving\n        // using the fact that ceil() = floor() + 1\n        int_t floor_or_ceilx = (dirx_ > 0) ? 1 : 0;\n        int_t floor_or_ceily = (diry_ > 0) ? 1 : 0;\n#ifdef DEBUG\n        printf(\"cell: (%i, %i), dxdy:(%f, %f)\\n\", i, j, dx, dy);\n        //std::cout << \"cell size:\" << cell_size_ << \"pos:\" << position << std::endl;\n#endif\n        // distance to nearest grid line\n        ex_ = fabs((i_ + floor_or_ceilx) * cell_size_x - px);\n        ey_ = fabs((j_ + floor_or_ceily) * cell_size_y - py);\n\n        // (max) time to collision from one grid line to another\n        Tx_ = (dx == 0) ? std::numeric_limits<real_t>::infinity() : cell_size_x / fabs(dx);\n        Ty_ = (dy == 0) ? std::numeric_limits<real_t>::infinity() : cell_size_y / fabs(dy);\n\n        // time to collision from this position\n        tx_ = (dx == 0) ? std::numeric_limits<real_t>::infinity() : ex_ / fabs(dx);\n        ty_ = (dy == 0) ? std::numeric_limits<real_t>::infinity() : ey_ / fabs(dy);\n\n        if ( ! ((tx_ >= 0) && (ty_ >= 0))) {\n          printf(\"t:(%f, %f), direction:(%f, %f), position:(%f, %f), cell:(%d, %d), cellsize:(%f, %f)\\n\", \n              tx_, ty_, dx, dy, px, py, i_, j_, cell_size_x, cell_size_y);\n          throw std::logic_error(\"tx < 0 or ty < 0\");\n        }\n\n        // time is always positive \n        assert(tx_ >= 0);\n        assert(ty_ >= 0);\n      }\n\n      typename super_t::reference dereference() const {\n        return std::make_pair(i_, j_);\n      }\n\n      bool equal(ray_trace_iterator it) const {\n        return ((it.i_ == i_) && (it.j_ == j_) &&\n          (it.tx_ == tx_) && (it.ty_ == ty_) &&\n          (it.Tx_ == Tx_) && (it.Ty_ == Ty_) &&\n          (it.dirx_ == dirx_) && (it.diry_ == diry_));\n      }\n\n      void increment() {\n          if (tx_ < ty_) {\n            i_ += dirx_;\n            ty_ = ty_ - tx_;\n            tx_ = Tx_;\n          } else {\n            j_ += diry_;\n            tx_ = tx_ - ty_;\n            ty_ = Ty_;\n          }\n      }\n\n      std::pair<real_t, real_t>\n        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_ceilx = (dirx_ > 0) ? 1 : 0;\n          int_t floor_or_ceily = (diry_ > 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_ceilx) * cell_size_x_ - ex * dirx_;\n          real_t py = (j_ + floor_or_ceily) * cell_size_y_ - ey * diry_;\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} // namespace occgrid\n", "meta": {"hexsha": "4da9320d1d41d6c526a18852217e42c0be02f7de", "size": 4984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OccupancyGrid/raytrace.hpp", "max_stars_repo_name": "wecacuee/modern-occupancy-grid", "max_stars_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-03-14T16:24:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T05:39:06.000Z", "max_issues_repo_path": "include/OccupancyGrid/raytrace.hpp", "max_issues_repo_name": "wecacuee/modern-occupancy-grid", "max_issues_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/OccupancyGrid/raytrace.hpp", "max_forks_repo_name": "wecacuee/modern-occupancy-grid", "max_forks_repo_head_hexsha": "c1405847dd715aec25ba416667fa4999d99d5b72", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-08-10T02:02:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-20T12:20:29.000Z", "avg_line_length": 30.3902439024, "max_line_length": 106, "alphanum_fraction": 0.5296950241, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5593035580772007}}
{"text": "\r\n// Run like this\r\n//./generate --data competition/S1a/S1b_short_dataset1_training.csv \r\n// This code will forecast 4 unknown parameters of the Matern covariance matrix\r\n// Developed by Alexander Litvinenko (RWTH Aachen) and Ronald Kriemann (MIS MPG Leipzig)\r\n// Based on the HLIBPro library (v. 2.9) www.hlibpro.com\r\n// No warranties.\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n\r\n#include <boost/format.hpp>\r\n#include <boost/program_options.hpp>\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/bessel.hpp>\r\n\r\n#include <gsl/gsl_sf_bessel.h>\r\n#include <gsl/gsl_sf_gamma.h>\r\n\r\n#include <gsl/gsl_multimin.h>\r\n\r\n#include \"hlib.hh\"\r\n\r\nusing namespace std;\r\nusing boost::format;\r\nusing namespace HLIB;\r\nusing namespace boost::program_options;\r\nusing  real_t    = HLIB::real;\r\n\r\nenum {\r\n    IDX_SIGMA  = 0,\r\n    IDX_LENGTH = 1,\r\n    IDX_NU     = 2,\r\n    IDX_TAU    = 3\r\n};\r\n\r\n\r\n//Use a method described by Abramowitz and Stegun: \r\ndouble gaussrand_Stegun()\r\n{\r\n    static double U, V;\r\n    static int phase = 0;\r\n    double Z;\r\n\r\n    if(phase == 0) {\r\n        U = (rand() + 1.) / (RAND_MAX + 2.);\r\n        V = rand() / (RAND_MAX + 1.);\r\n        Z = sqrt(-2 * log(U)) * sin(2 * M_PI * V);\r\n    } else\r\n        Z = sqrt(-2 * log(U)) * cos(2 * M_PI * V);\r\n\r\n    phase = 1 - phase;\r\n\r\n    return Z;\r\n}\r\n\r\n//Use a method discussed in Knuth and due originally to Marsaglia:\r\n\r\ndouble gaussrand_Knuth()\r\n{\r\n    static double V1, V2, S;\r\n    static int phase = 0;\r\n    double X;\r\n\r\n    if(phase == 0) {\r\n        do {\r\n            double U1 = (double)rand() / RAND_MAX;\r\n            double U2 = (double)rand() / RAND_MAX;\r\n\r\n            V1 = 2 * U1 - 1;\r\n            V2 = 2 * U2 - 1;\r\n            S = V1 * V1 + V2 * V2;\r\n        } while(S >= 1 || S == 0);\r\n\r\n        X = V1 * sqrt(-2 * log(S) / S);\r\n    } else\r\n        X = V2 * sqrt(-2 * log(S) / S);\r\n\r\n    phase = 1 - phase;\r\n\r\n    return X;\r\n}\r\n\r\n// global options\r\nint        nmin      = CFG::Cluster::nmin;\r\ndouble     eps       = 1e-6;\r\ndouble     fac_eps   = 1e-6;\r\ndouble     shift     = 1e-7;\r\nbool       use_ldl   = false;\r\n\r\n//\r\n// read dataset from file\r\n//\r\nvoid\r\nread_data ( const std::string &       datafile,\r\n            std::vector< T2Point > &  vertices,\r\n            BLAS::Vector< double > &  Z_data )\r\n{\r\n    std::ifstream  in( datafile );\r\n    \r\n    if ( ! in ) // error\r\n        exit( 1 );\r\n\r\n    size_t  N_vtx = 0;\r\n    \r\n    #if 1\r\n\r\n    std::string  line;\r\n    \r\n    std::getline( in, line );\r\n\r\n    if ( line == \"x,y\" )\r\n    {\r\n        std::list< T2Point >  pos;\r\n        std::list< double >   vals;\r\n\r\n        while ( std::getline( in, line ) )\r\n        {\r\n            auto    parts = split( line, \",\" );\r\n            double  x = atof( parts[0].c_str() );\r\n            double  y = atof( parts[1].c_str() );\r\n           \r\n            \r\n            pos.push_back( T2Point( x, y ) );\r\n        }// while\r\n\r\n        N_vtx = pos.size();\r\n\r\n        std::cout << \"learning dataset\" << std::endl;\r\n        std::cout << N_vtx << std::endl;\r\n        \r\n        vertices.resize( N_vtx );\r\n        Z_data = BLAS::Vector< double >( N_vtx );\r\n\r\n        int  i = 0;\r\n\r\n        for ( auto  p : pos )\r\n            vertices[ i++ ] = p;\r\n\r\n        i = 0;\r\n        \r\n        for ( idx_t  i = 0; i < idx_t(N_vtx); ++i )\r\n           Z_data( i++ ) =  gaussrand_Knuth(); //gaussrand_Stegun() ;\r\n    }// if\r\n    else\r\n    {\r\n        std::cout << \"you should not be here, something is wrong with the input file\" << std::endl;\r\n        HERROR( ERR_NOT_IMPL, \"\", \"\" );\r\n    }\r\n    \r\n    #else\r\n    \r\n    in >> N_vtx;\r\n\r\n    std::cout << \"reading \" << N_vtx << \" datapoints\" << std::endl;\r\n    \r\n    vertices.resize( N_vtx );\r\n    Z_data = BLAS::Vector< double >( N_vtx );\r\n        \r\n    for ( idx_t  i = 0; i < idx_t(N_vtx); ++i )\r\n    {\r\n        int     index = i;\r\n        double  x, y, z;\r\n        // double  v     = 0.0;\r\n        \r\n        in >> index >> x >> y >> z;\r\n        // in >> index >> x >> y >> z >> v;\r\n\r\n        vertices[ index ] = T2Point( x, y );\r\n        //Z_data( index )   = v;\r\n    }// for\r\n\r\n    #endif\r\n    \r\n    //\r\n    // for visualization of data, export 2D points with v value in csv file\r\n    //\r\n\r\n    // std::ofstream  out( \"data.csv\" );\r\n\r\n    // out << \"x,y,z,v\" << std::endl;\r\n    // out << \"x,y,z\" << std::endl;\r\n    \r\n    //for ( uint  i = 0; i < N_vtx; ++i )\r\n    //   out << vertices[i].x() << \",\" << vertices[i].y() << \",0\" << std::endl;\r\n//      out << vertices[i].x() << \",\" << vertices[i].y() << \",0,\" << Z_data( i ) << std::endl;\r\n}\r\n\r\n//\r\n// define PredictionProblem to forecast unknown values in new locations\r\n//\r\nstruct GeneratingProblem\r\n{\r\n    std::vector< T2Point >                vertices;\r\n    std::unique_ptr< TCoordinate >        coord;\r\n    std::unique_ptr< TClusterTree >       ct;\r\n    std::unique_ptr< TBlockClusterTree >  bct;\r\n    std::unique_ptr< TVector >            Z;\r\n    \r\n    GeneratingProblem ( const std::string &  datafile )\r\n    {\r\n        init( datafile );\r\n    }\r\n\r\n    void\r\n    init ( const std::string &  datafile )\r\n    {\r\n        BLAS::Vector< double >  Z_data;\r\n\r\n        read_data( datafile, vertices, Z_data );\r\n        std::cout << \"the grid is successfully read\" << std::endl;\r\n        coord = std::make_unique< TCoordinate >( vertices );\r\n        \r\n        TAutoBSPPartStrat  part_strat;\r\n        TBSPCTBuilder      ct_builder( & part_strat, nmin );\r\n    \r\n        ct = ct_builder.build( coord.get() );\r\n        //print_vtk( & coord, \"ct_coord\" );\r\n        //print_vtk( & coord_predict, \"ct_coord_predict\" );\r\n        \r\n    \r\n        TStdGeomAdmCond    adm_cond( 2.0, use_min_diam );\r\n        TBCBuilder         bct_builder;\r\n   \r\n        bct = bct_builder.build( ct.get(), ct.get(), & adm_cond );\r\n        Z   = std::make_unique< TScalarVector >( *ct->root(), std::move( Z_data ) );\r\n        ct->perm_e2i()->permute( Z.get() );\r\n  }\r\n    \r\n    //BLAS::Vector< double > \r\n    std::unique_ptr< TVector > \r\n    eval ( const double  sigma,\r\n           const double  length,\r\n           const double  nu,\r\n           const double tau )\r\n    {\r\n  \r\n        TMaternCovCoeffFn< T2Point >  matern_coefffn( sigma, length, nu,  vertices );\r\n        TPermCoeffFn< double >        coefffn( & matern_coefffn, ct->perm_i2e(), ct->perm_i2e() );\r\n        \r\n        TACAPlus< double >            aca( & coefffn );\r\n        auto                          acc = fixed_prec( eps );\r\n        TDenseMatBuilder< double >    h_builder( & coefffn, & aca );\r\n        \r\n        auto                          C        = h_builder.build( bct.get(), acc );\r\n        TPSMatrixVis  mvis;\r\n        \r\n         //mvis.svd(true).print( C.get(), \"myC\" );\r\n \r\n//        print_ps(bct->root(), \"bct.eps\");\r\n//        print_ps(bct_predict->root(), \"bct_predict.eps\");\r\n  \r\n        //       mvis.svd(true).print( C_predict.get(), \"myC_predict\" );\r\n  \r\n        //if ( shift != 0.0 )\r\n        //    add_identity( C.get(), tau*tau );\r\n  \r\n        auto                          fac_acc  = fixed_prec( fac_eps );\r\n        auto                          C_fac    = C->copy();\r\n        auto                          fac_opts = fac_options_t{ point_wise, CFG::Arith::storage_type, false };\r\n    \r\n        \r\n        chol( C_fac.get(), fac_acc );\r\n    \r\n\r\n        //std::cout << \"    |С|_F             = \" << norm_F( C.get() ) << std::endl;\r\n        //std::cout << \"    |L|_F             = \" << norm_F( C_fac.get() ) << std::endl;\r\n        //std::cout << \"    |С|_2             = \" << norm_2( C.get() ) << std::endl;\r\n        //std::cout << \"    |L|_2             = \" << norm_2( C_fac.get() ) << std::endl;\r\n        //mvis.svd(true).print( C_fac.get(), \"myL\" );\r\n\r\n        //std::unique_ptr< TFacInvMatrix >   C_inv;\r\n\r\n     \r\n      \r\n        const size_t                  N     = vertices.size();\r\n        \r\n        \r\n        \r\n        auto                          Z_generated = C->row_vector();\r\n    \r\n      //  std::cout << \"  size of C = \" << C->rows() << \"x\"<< C->cols() << std::endl;\r\n      //  std::cout << \"  size of C_predict = \" << C_predict->rows() <<\"x\"<<  C_predict->cols() << std::endl;\r\n      //  std::cout << \"  sol size = \" << sol->size() << std::endl;\r\n      //  std::cout << \"  ||sol|| = \" << sol->norm2() << std::endl;\r\n      //  std::cout << \"  ||Z_predict|| = \" << Z_predict->norm2() << std::endl;\r\n  \r\n        //auto                          ZdotCZ = std::real( Z->dot( sol.get() ) );\r\n        //Z_predict = C_predict * sol.get(); \r\n        mul_vec( real_t(1), C_fac.get(), Z.get(), real_t(0), Z_generated.get(), apply_normal );\r\n        //C_predict->mul_vec( 1.0, sol.get(), 0.0, Z_predict.get(), apply_normal );\r\n        \r\n        ct->perm_i2e()->permute( Z_generated.get() );\r\n        std::cout << \"  ||Z_generated|| = \" << Z_generated->norm2() << std::endl;\r\n        \r\n        //TMatlabVectorIO  vio;\r\n \r\n        //vio.write( Z_predict,  \"x.mat\", \"x\" );\r\n\r\n        FILE* f1;\r\n        f1 = fopen(\"111gen_d.txt\", \"w\");\r\n\r\n        for ( size_t  i = 0; i < Z_generated->size(); i++ )\r\n          fprintf(f1,\" %6.6e, %6.6e, %6.6e\\n\",   vertices[i].x(),  vertices[i].y(), Z_generated->entry(i));\r\n        fclose(f1);\r\n        return std::move( Z_generated );\r\n    }\r\n};\r\n\r\n//\r\n// wrapper from GSL to LogLikeliHoodProblem\r\n//\r\n/*double\r\n  eval_logli ( const gsl_vector *  param,\r\n  void *              data )\r\n  {\r\n  double sigma  = gsl_vector_get( param, IDX_SIGMA );\r\n  double length = gsl_vector_get( param, IDX_LENGTH );\r\n  double nu     = gsl_vector_get( param, IDX_NU );\r\n  double tau    = gsl_vector_get( param, IDX_TAU );\r\n\r\n  LogLikeliHoodProblem *  problem = static_cast< LogLikeliHoodProblem * >( data );\r\n\r\n  return - problem->eval( sigma, length, nu, tau );\r\n  }\r\n*/\r\n//\r\n// optimization function using GSL\r\n//\r\n\r\n//\r\n// main function\r\n//\r\nint\r\nmain ( int      argc,\r\n       char **  argv )\r\n{\r\n\r\n    \r\n    CFG::set_verbosity( 3 );\r\n    INIT();\r\n    \r\n    //std::string  datafile = \"datafile.txt\";\r\n    //std::string  datafile_predict = \"datafile_predict.txt\";\r\n    std::string  datafile = \"grid.txt\";\r\n    \r\n    //\r\n    // define command line options\r\n    //\r\n\r\n    options_description             all_opts;\r\n    options_description             vis_opts( \"usage: generatig [options] datafile\\n  where options include\" );\r\n    options_description             hid_opts( \"Hidden options\" );\r\n    positional_options_description  pos_opts;\r\n    variables_map                   vm;\r\n\r\n    // standard options\r\n    vis_opts.add_options()\r\n        ( \"help,h\",                       \": print this help text\" )\r\n        ( \"threads,t\",   value<int>(),    \": number of parallel threads\" )\r\n        ( \"verbosity,v\", value<int>(),    \": verbosity level\" )\r\n        ( \"nmin\",        value<int>(),    \": set minimal cluster size\" )\r\n        ( \"eps,e\",       value<double>(), \": set H accuracy\" )\r\n        ( \"epslu\",       value<double>(), \": set only H factorization accuracy\" )\r\n        ( \"shift\",       value<double>(), \": regularization parameter\" )\r\n        ( \"ldl\",                          \": use LDL factorization\" )\r\n        ;\r\n    \r\n    hid_opts.add_options()\r\n        ( \"data\",        value<std::string>(), \": datafile \" );\r\n\r\n    // options for command line parsing\r\n    all_opts.add( vis_opts ).add( hid_opts );\r\n\r\n    // all \"non-option\" arguments should be \"--data\" arguments\r\n    pos_opts.add( \"data\", -1 );\r\n\r\n    //\r\n    // parse command line options\r\n    //\r\n\r\n    try\r\n    {\r\n        store( command_line_parser( argc, argv ).options( all_opts ).positional( pos_opts ).run(), vm );\r\n        notify( vm );\r\n    }// try\r\n    catch ( required_option &  e )\r\n    {\r\n        std::cout << e.get_option_name() << \" requires an argument, try \\\"-h\\\"\" << std::endl;\r\n        exit( 1 );\r\n    }// catch\r\n    catch ( unknown_option &  e )\r\n    {\r\n        std::cout << e.what() << \", try \\\"-h\\\"\" << std::endl;\r\n        exit( 1 );\r\n    }// catch\r\n\r\n    //\r\n    // eval command line options\r\n    //\r\n\r\n    if ( vm.count( \"help\") )\r\n    {\r\n        std::cout << vis_opts << std::endl;\r\n        exit( 1 );\r\n    }// if\r\n\r\n    if ( vm.count( \"nmin\"      ) ) nmin     = vm[\"nmin\"].as<int>();\r\n    if ( vm.count( \"eps\"       ) ) eps      = vm[\"eps\"].as<double>();\r\n    if ( vm.count( \"epslu\"     ) ) fac_eps  = vm[\"epslu\"].as<double>();\r\n    if ( vm.count( \"shift\"     ) ) shift    = vm[\"shift\"].as<double>();\r\n    if ( vm.count( \"threads\"   ) ) CFG::set_nthreads( vm[\"threads\"].as<int>() );\r\n    if ( vm.count( \"verbosity\" ) ) CFG::set_verbosity( vm[\"verbosity\"].as<int>() );\r\n    if ( vm.count( \"ldl\"       ) ) use_ldl  = true;\r\n\r\n    // default to general eps\r\n    if ( fac_eps == -1 )\r\n        fac_eps = eps;\r\n    \r\n    if ( vm.count( \"data\" ) )\r\n        datafile = vm[\"data\"].as<std::string>();\r\n    else\r\n    {\r\n        std::cout << \"usage: generating [options] datafile\" << std::endl;\r\n        exit( 1 );\r\n    }// if\r\n\r\n\r\n    double  sigma  = 2.0; //take these values from previous experiments (Part 1a)\r\n    double  length = 0.1; \r\n    double  nu     = 0.5;\r\n    double  tau    = 0.0;\r\n    \r\n    GeneratingProblem  problem( datafile );\r\n    problem.eval( sigma, length, nu, tau);\r\n\r\n    DONE();\r\n}\r\n", "meta": {"hexsha": "1face9ec6b2ee72485eb1adcfe53b8781ca90198", "size": 13147, "ext": "cc", "lang": "C++", "max_stars_repo_path": "generate.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": "generate.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": "generate.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": 29.8795454545, "max_line_length": 112, "alphanum_fraction": 0.4860424431, "num_tokens": 3646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5592229773424929}}
{"text": "#include \"Common.h\"\n#include \"CPS4.h\"\n#include \"PropertiesHolder/PropertiesHolder.h\"\n#include \"Material.h\"\n#include <Eigen/Dense>\n\n#include \"GaussQuadrature.h\"\n\n\nEigen::Matrix<float, 4, 4> CPS4::m_C;\nEigen::Matrix<float, 4, 4> CPS4::m_IC;\n\nfloat XI[4] = { -1.0, 1.0, 1.0, -1.0 };\nfloat ETA[4] = { -1.0, -1.0, 1.0, 1.0 };\n\nvoid CPS4::Init()\n{\n\t//x0: -1; x1: 1; x2: 1; x3: -1\n\t//y0: -1; y1: -1; y2: 1; y3: 1\n\tm_C <<\tEigen::Vector4f(1.0,\t\t\t\t1.0,\t\t\t\t1.0,\t\t\t\t1.0), \n\t\t\tEigen::Vector4f(XI[0],\t\t\t\tXI[1],\t\t\t\tXI[2],\t\t\t\tXI[3]),\t\t\t// x0, x1, x2, x3\n\t\t\tEigen::Vector4f(ETA[0],\t\t\t\tETA[1],\t\t\t\tETA[2],\t\t\t\tETA[3]),\t\t// y0, y1, y2, y3\n\t\t\tEigen::Vector4f(XI[0] * ETA[0],\t\tXI[1] * ETA[1],\t\tXI[2] * ETA[2],\t\tXI[3] * ETA[3]);\t\t// x0y0, x1y1, x2y2, x3y3\n\tm_IC = m_C.inverse();\n}\n\nvoid CPS4::SetIndices(const std::vector<int>& indices)\n{\n\tassert(indices.size() == 4);\n\tm_nodes[0] = indices[0];\n\tm_nodes[1] = indices[1];\n\tm_nodes[2] = indices[2];\n\tm_nodes[3] = indices[3];\n}\n\nstd::vector<int> CPS4::GetIndices() const\n{\n\tstd::vector<int> indices(4);\n\tindices[0] = m_nodes[0];\n\tindices[1] = m_nodes[1];\n\tindices[2] = m_nodes[2];\n\tindices[3] = m_nodes[3];\n\treturn indices;\n}\n\nstd::vector<Eigen::Vector3f> CPS4::GetFunctionValuesAtNodes(const Eigen::VectorXf& deforms)const\n{\n\tEigen::Matrix<float, 8, 1> uv;\n\tstd::vector<Eigen::Vector3f> output;\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tuv[2 * i + 0] = deforms[2 * m_nodes[i] + 0];\n\t\tuv[2 * i + 1] = deforms[2 * m_nodes[i] + 1];\n\t}\n\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tEigen::Matrix<float, 3, 8> B = GetB(XI[i], ETA[i] );\n\t\tEigen::Vector3f strain = B * uv;\t\n\t\toutput.push_back(strain);\n\t}\n\treturn output;\n}\n\nvoid CPS4::CalcK(const StrideDataArray& nodes, const tfem::MaterialPtr mat, std::vector<Eigen::Triplet<float> >& tripletVector)\n{\n\tm_mat = mat;\n\tEigen::Vector4f X;\n\tEigen::Vector4f Y;\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tX[i] = nodes(m_nodes[i], 0);\n\t\tY[i] = nodes(m_nodes[i], 1);\n\t}\n\n\tm_KX = m_IC * X;\n\tm_KY = m_IC * Y;\n\n\tfloat area = 0;\n\tEigen::Matrix<float, 8, 8> K;\n\tK.setZero();\n\t\n\tfloat xi, eta, w1, w2;\n\tfor (int i = 0; GaussQuadrature::GetWeights<2>(i, xi, w1); i++)\n\t{\n\t\tfor (int j = 0; GaussQuadrature::GetWeights<2>(j, eta, w2); j++)\n\t\t{\t\t\t\n\t\t\tfloat w = w1 * w2;\n\t\t\tEigen::Matrix<float, 2, 2> J = GetJ(xi, eta);\n\n\t\t\tEigen::Matrix<float, 3, 8> B = GetB(xi, eta);\n\n\t\t\tK += B.transpose() * mat->GetElasticityMatrix(fem::PT_FlatStress) * B * J.determinant() * w;\n\t\t\tarea += J.determinant() * w;\n\t\t}\n\t}\n\n\tGrabTriplets(K, tripletVector);\n}\n\nvoid CPS4::GrabTriplets(const Eigen::Matrix<float, 8, 8>& K, std::vector<Eigen::Triplet<float> >& tripletVector) const\n{\n\tfor (int i = 0; i < 4; i++)\n\t{\n\t\tfor (int j = 0; j < 4; j++)\n\t\t{\n\t\t\tEigen::Triplet<float> trplt11(2 * m_nodes[i] + 0, 2 * m_nodes[j] + 0, K(2 * i + 0, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt12(2 * m_nodes[i] + 0, 2 * m_nodes[j] + 1, K(2 * i + 0, 2 * j + 1));\n\t\t\tEigen::Triplet<float> trplt21(2 * m_nodes[i] + 1, 2 * m_nodes[j] + 0, K(2 * i + 1, 2 * j + 0));\n\t\t\tEigen::Triplet<float> trplt22(2 * m_nodes[i] + 1, 2 * m_nodes[j] + 1, K(2 * i + 1, 2 * j + 1));\n\n\t\t\ttripletVector.push_back(trplt11);\n\t\t\ttripletVector.push_back(trplt12);\n\t\t\ttripletVector.push_back(trplt21);\n\t\t\ttripletVector.push_back(trplt22);\n\t\t}\n\t}\n}\n\ntfem::Material* CPS4::GetMaterial()\n{\n\treturn m_mat.get();\n}\n\nIElement* CPS4::Create()\n{\n\treturn new CPS4;\n}\n\nCPS4::CPS4()\n{\n\n}\n\nEigen::Matrix<float, 1, 4> CPS4::GetP(float xi, float eta) const\n{\n\treturn Eigen::Matrix<float, 1, 4>(1, xi, eta, xi * eta);\n}\n\nEigen::Matrix<float, 1, 4> CPS4::GetdPdxi(float xi, float eta) const\n{\n\treturn Eigen::Matrix<float, 1, 4>(0, 1, 0, eta);\n}\n\nEigen::Matrix<float, 1, 4> CPS4::GetdPdeta(float xi, float eta) const\n{\n\treturn Eigen::Matrix<float, 1, 4>(0, 0, 1, xi);\n}\n\nEigen::Matrix<float, 2, 2> CPS4::GetJ(float xi, float eta) const\n{\n\tfloat dxdxi = GetdPdxi(xi, eta) * m_KX;\n\tfloat dydxi = GetdPdxi(xi, eta) * m_KY;\n\tfloat dxdeta = GetdPdeta(xi, eta) * m_KX;\n\tfloat dydeta = GetdPdeta(xi, eta) * m_KY;\n\tEigen::Matrix<float, 2, 2> result;\n\tresult << dxdxi, dydxi, dxdeta, dydeta;\n\treturn result;\n}\n\nEigen::Matrix<float, 3, 8> CPS4::GetB(float xi, float eta) const\n{\n\tEigen::Matrix<float, 3, 8> B;\n\tEigen::Matrix<float, 2, 2> J = GetJ(xi, eta);\n\tEigen::Matrix<float, 2, 2> IJ = J.inverse();\n\n\tEigen::Matrix<float, 1, 4> dNdxi = GetdPdxi(xi, eta) * m_IC;\n\tEigen::Matrix<float, 1, 4> dNdeta = GetdPdeta(xi, eta) * m_IC;\n\n\tfor (int k = 0; k < 4; ++k)\n\t{\n\t\tEigen::Matrix<float, 2, 1> dNkdxieta(dNdxi[k], dNdeta[k]); \n\t\tEigen::Matrix<float, 2, 1> dNkdxy = IJ * dNkdxieta;\n\t\tB(0, 2 * k + 0) = dNkdxy[0];\n\t\tB(0, 2 * k + 1) = 0;\n\t\tB(1, 2 * k + 0) = 0;\n\t\tB(1, 2 * k + 1) = dNkdxy[1];\n\t\tB(2, 2 * k + 0) = dNkdxy[1];\n\t\tB(2, 2 * k + 1) = dNkdxy[0];\n\t}\n\treturn B;\n}", "meta": {"hexsha": "7749b720d095b17c3c61eb5e094b823743fe34c8", "size": 4695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/Elements/CPS4.cpp", "max_stars_repo_name": "podgorskiy/TinyFEM", "max_stars_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-11-05T14:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T15:24:54.000Z", "max_issues_repo_path": "sources/Elements/CPS4.cpp", "max_issues_repo_name": "podgorskiy/TinyFEM", "max_issues_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_issues_repo_licenses": ["MIT"], "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/Elements/CPS4.cpp", "max_forks_repo_name": "podgorskiy/TinyFEM", "max_forks_repo_head_hexsha": "c1a5fedf21e6306fc11fa19afdaf48dab1b6740f", "max_forks_repo_licenses": ["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.7967032967, "max_line_length": 127, "alphanum_fraction": 0.5895633653, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5592229592056192}}
{"text": "/**\n * @file \tShortestPathHeuristic.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 10, 2017\n */\n\n#include <boost/heap/fibonacci_heap.hpp>\n#include \"MyDijkstra.h\"\n#include \"ShortestPathHeuristic.h\"\n\n\n\nusing Pair = std::pair<int, double>;\nusing std::vector;\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\n\n/*\n * Finds all primes in {2,...,n} using the fact that if a natural number\n * has a divisor it also has at least one prime divisor. the resulting vector\n * contains the numbers -1.\n */\nvector<int> ShortestPathHeuristic::findPrimes(int n) {\n\tassert(n >= 2);\n\n\tvector<int> primes;\n\tprimes.push_back(2);\n\n\tfor (int i = 3; i < n; ++i) {\n\t\tbool isPrime = true;\n\t\tfor (unsigned int j = 0; j < primes.size() && primes[j]*primes[j] <= i; j++) {\n\t\t\tif (i % primes[j] == 0) {\n\t\t\t\tisPrime = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (isPrime) {\n\t\t\tprimes.push_back(i);\n\t\t}\n\t}\n\n\tfor (unsigned int i = 0; i < primes.size(); ++i) {\n\t\tprimes[i]--;\n\t}\n\n\treturn primes;\n}\n\n\n\ndouble ShortestPathHeuristic::constructSteinerTree(Graph& g, int numVertices, int source) {\n\tassert(numVertices >= 2);\n\n\tusing Heap = heap::fibonacci_heap<heap_data>;\n\n\tvector<int> primes = findPrimes(numVertices);\n\tint numTerminals = primes.size();\n\n\tdouble** distances = new double*[numTerminals];\n\tint** predecessors = new int*[numTerminals];\n\n\t/*shortest paths from all terminals to all other nodes are calculated*/\n\tfor (int i = 0; i < numTerminals; ++i) {\n\t\tif (primes[i] != source) {\n\t\t\tdistances[i] = new double[numVertices];\n\t\t\tpredecessors[i] = new int[numVertices];\n\t\t\tMyDijkstra::computeShortestPaths(g, numVertices, primes[i], distances[i], predecessors[i]);\n\t\t} else {\n\t\t\tdistances[i] = new double[0];\n\t\t\tpredecessors[i] = new int[0];\n\t\t}\n\t}\n\n\t/*we use a priority queue to keep track of remaining and closest terminals*/\n\tHeap heap;\n\tHeap::handle_type *handles = new Heap::handle_type[numTerminals];\n\n\t//all terminals except for the source are added to heap\n\tfor (int i = 0; i < numTerminals; ++i) {\n\t\tif (primes[i] != source) {\n\t\t\thandles[i] = heap.push(std::make_pair(i, distances[i][source]));\n\t\t}\n\t}\n\n\t//we also keep track of the closest node in the tree for each terminal\n\tdouble objectiveValue = 0;\n\tint nearestNodes[numTerminals];\n\tfor (int i = 0; i < numTerminals; i++) {\n\t\tnearestNodes[i] = source;\n\t}\n\n\twhile (!heap.empty()) {\n\t\tPair nextTerminal = heap.top().pair;\n\t\tint connectionNode = nearestNodes[nextTerminal.first];\n\t\theap.pop();\t\t\t//top element in heap always is the closest to tree\n\n\t\tobjectiveValue += (distances[nextTerminal.first])[connectionNode];\n\n\t\t//now we iterate over all remaining terminals to check whether\n\t\t//they have become closer to the new tree\n\t\tfor (Heap::iterator it = heap.begin(); it != heap.end(); ++it) {\n\t\t\tPair curr = (*it).pair;\n\t\t\tdouble min = curr.second;\n\t\t\tint pred = connectionNode;\n\t\t\tbool reachedEnd = false;\n\n\t\t\t//for each terminal we iterate over all vertices on newly added path\n\t\t\twhile (!reachedEnd){\n\t\t\t\treachedEnd = (pred == primes[nextTerminal.first]);\n\t\t\t\tdouble tmp = (distances[curr.first])[pred];\n\t\t\t\tif (tmp < min) {\n\t\t\t\t\tmin = tmp;\n\t\t\t\t\tnearestNodes[curr.first] = pred;\n\t\t\t\t}\n\t\t\t\tpred = predecessors[nextTerminal.first][pred];\n\t\t\t}\n\n\t\t\t//update of heap if neccessary\n\t\t\tif (min < curr.second) {\n\t\t\t\t(*handles[curr.first]).pair.second = min;\n\t\t\t\theap.increase(handles[curr.first]);\n\t\t\t}\n\t\t} //end of iteration through heap\n\n\t} //end of algorithm\n\n\n\tfor (int i = 0; i < numTerminals; i++) {\n\t\tdelete[] distances[i];\n\t\tdelete[] predecessors[i];\n\t}\n\tdelete[] distances;\n\tdelete[] predecessors;\n\tdelete[] handles;\n\n\treturn objectiveValue;\n\n\n}\n\ndouble ShortestPathHeuristic::constructSteinerTree(Graph& g, int numVertices) {\n\treturn constructSteinerTree(g, numVertices, 1);\n}\n\n\n", "meta": {"hexsha": "e357c60f2d12aa77e3b39519f6747649aff56ba5", "size": 4062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/Ex8/ShortestPathHeuristic.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/ShortestPathHeuristic.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/ShortestPathHeuristic.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": 24.9202453988, "max_line_length": 94, "alphanum_fraction": 0.6656819301, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5592229512310795}}
{"text": "#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Stream_lines_2.h>\n#include <CGAL/Runge_kutta_integrator_2.h>\n#include <CGAL/Regular_grid_2.h>\n\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/StreamLinesGraphicsItem.h>\n#include <CGAL/Qt/RegularGridVectorFieldGraphicsItem.h>\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n// the two base classes\n#include \"ui_Stream_lines_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ntypedef CGAL::Regular_grid_2<K> Regular_grid;\ntypedef CGAL::Runge_kutta_integrator_2<Regular_grid> Runge_kutta_integrator;\ntypedef CGAL::Stream_lines_2<Regular_grid, Runge_kutta_integrator> Stream_lines;\ntypedef CGAL::Stream_lines_2<Regular_grid, Runge_kutta_integrator>::Stream_line_iterator_2 Stream_line_iterator;\ntypedef CGAL::Stream_lines_2<Regular_grid, Runge_kutta_integrator>::Point_iterator_2 Point_iterator;\ntypedef CGAL::Stream_lines_2<Regular_grid, Runge_kutta_integrator>::Point_2 Point_2;\ntypedef CGAL::Stream_lines_2<Regular_grid, Runge_kutta_integrator>::Vector_2 Vector;\n\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\n\n\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Stream_lines_2\n{\n  Q_OBJECT\n  \nprivate:  \n  Stream_lines * stream_lines;\n  Runge_kutta_integrator * runge_kutta_integrator;\n  Regular_grid * regular_grid;\n  double density;\n  double ratio;\n  double integrating;\n  int sampling;  \n  QGraphicsScene scene;  \n\n  CGAL::Qt::StreamLinesGraphicsItem<Stream_lines,K> * sli;\n  CGAL::Qt::RegularGridVectorFieldGraphicsItem<Regular_grid,K> * rgi;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionSavePoints_triggered();\n\n  void on_actionRecenter_triggered();\n\n  virtual void open(QString fileName);\n\nprivate:\n  void generate();\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow(), density(12.0), ratio(1.6), integrating(1.0), sampling(1)\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n\n  // Manual handling of actions\n  //\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()), \n\t\t   this, SLOT(close()));\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&scene);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->matrix().scale(1, -1);\n                                                      \n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/about_Stream_lines_2.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n\t  this, SLOT(open(QString)));\n}\n\n\n\n/* \n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n * \n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::generate()\n{\n  stream_lines = new Stream_lines(*regular_grid, *runge_kutta_integrator, density, ratio, sampling);\n\n  sli = new CGAL::Qt::StreamLinesGraphicsItem<Stream_lines, K>(stream_lines);\n  rgi = new CGAL::Qt::RegularGridVectorFieldGraphicsItem<Regular_grid, K>(regular_grid);\n\n  QObject::connect(this, SIGNAL(changed()),\n\t\t   sli, SLOT(modelChanged()));\n\n\n  rgi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  rgi->setEdgesPen(QPen(Qt::gray, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  sli->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(sli);\n  scene.addItem(rgi);\n\n  on_actionRecenter_triggered();\n  Q_EMIT( changed());\n}\n\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#endif\n  QString fileName = QFileDialog::getOpenFileName(this,\n\t\t\t\t\t\t  tr(\"Open grid file\"),\n\t\t\t\t\t\t  \".\"\n\t\t\t\t\t\t#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n\t\t\t\t\t\t,tr(\"WKT files (*.wkt *.WKT)\")\n\t\t\t\t\t\t#endif\n                                                  );\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n  \n  runge_kutta_integrator = new Runge_kutta_integrator(integrating);\n  double iXSize, iYSize;\n  iXSize = iYSize = 512;\n  if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n  {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n    std::vector<std::vector<Point_2> > mp;\n    int size= -1;\n    do\n    {\n      std::vector<Point_2> ps;\n      CGAL::read_multi_point_WKT(ifs, ps);\n      if(size == -1)\n        size = static_cast<int>(ps.size());\n      else if(ps.size() > 0 && size != static_cast<int>(ps.size()))\n        ps.resize(size);\n      else if(ps.size() == 0)\n        continue;\n      mp.push_back(ps);\n    }while(ifs.good() && !ifs.eof());\n    regular_grid = new Regular_grid(size, static_cast<int>(mp.size()), iXSize, iYSize);\n    /*fill the grid with the appropriate values*/\n    for (unsigned int i=0;i<static_cast<unsigned int>(size);++i)\n      for (unsigned int j=0;j<mp.size();++j)\n      {\n        regular_grid->set_field(i, j, Vector(mp[j][i].x(), mp[j][i].y()));\n      }\n#else\n    QApplication::restoreOverrideCursor();\n    return;\n#endif\n  }\n  else{\n    unsigned int x_samples, y_samples;\n    ifs >> x_samples;\n    ifs >> y_samples;\n    regular_grid = new Regular_grid(x_samples, y_samples, iXSize, iYSize);\n    /*fill the grid with the appropriate values*/\n    for (unsigned int i=0;i<x_samples;i++)\n      for (unsigned int j=0;j<y_samples;j++)\n      {\n        double xval, yval;\n        ifs >> xval;\n        ifs >> yval;\n        regular_grid->set_field(i, j, Vector(xval, yval));\n      }\n  }\n  ifs.close();\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  generate();\n  Q_EMIT( changed());\n    \n}\n\nvoid\nMainWindow::on_actionSavePoints_triggered()\n{\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n  QString fileName = QFileDialog::getSaveFileName(this,\n\t\t\t\t\t\t  tr(\"Save points\"),\n\t\t\t\t\t\t  \".\",\n                                                  tr(\"WKT files (*.wkt *.WKT)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    \n    std::vector<std::vector<Point_2> >mp;\n    mp.resize(regular_grid->get_dimension().second);\n    for (int i=0;i<regular_grid->get_dimension().first;++i)\n    {\n      mp[i].reserve(regular_grid->get_dimension().second);\n      for (int j=0;j<regular_grid->get_dimension().second;++j)\n      {\n        mp[i].push_back(Point_2(regular_grid->get_field(j,i).x(),\n                                regular_grid->get_field(j,i).y()));\n      }\n      CGAL::write_multi_point_WKT(ofs, mp[i]);\n    }\n    ofs.close();\n  }\n#endif\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(rgi->boundingRect());\n  this->graphicsView->fitInView(rgi->boundingRect(), Qt::KeepAspectRatio);  \n}\n\n\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(\"Stream_lines_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  // See https://doc.qt.io/qt-5/qdir.html#Q_INIT_RESOURCE\n  CGAL_QT_INIT_RESOURCES;\n  Q_INIT_RESOURCE(Stream_lines_2);\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  return app.exec();\n}\n\n#include \"Stream_lines_2.moc\"\n", "meta": {"hexsha": "d0913c95d1c27d701ff88f425009b76725f3f16a", "size": 8228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/Stream_lines_2/Stream_lines_2.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/Stream_lines_2/Stream_lines_2.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/Stream_lines_2/Stream_lines_2.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 26.8888888889, "max_line_length": 112, "alphanum_fraction": 0.6849781235, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.5592229503489279}}
{"text": "// Copyright (C) 2019 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// This file was created by Steffen Urban (urbste@googlemail.com) or\n// company address (steffen.urban@zeiss.com)\n// January 2019\n\n#include \"theia/sfm/pose/six_point_radial_distortion_homography.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Jacobi>\n\nnamespace theia {\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\nusing Eigen::Vector2d;\nusing Vector6d = Eigen::Matrix<double, 6, 1>;\nusing Array51d = Eigen::Array<double, 5, 1>;\nusing Matrix68d = Eigen::Matrix<double, 6, 8>;\nusing Matrix62d = Eigen::Matrix<double, 6, 2>;\nusing Matrix65d = Eigen::Matrix<double, 6, 5>;\nusing Eigen::Matrix3d;\n\nbool IsNearZero(double val) {\n  return (+val < (100.0 * std::numeric_limits<double>::epsilon())) &&\n         (-val < (100.0 * std::numeric_limits<double>::epsilon()));\n}\n\nbool SixPointRadialDistortionHomography(\n    const std::vector<Eigen::Vector2d>& normalized_feature_points_left,\n    const std::vector<Eigen::Vector2d>& normalized_feature_points_right,\n    std::vector<RadialHomographyResult>* results, const double lmin,\n    const double lmax) {\n  Matrix62d X;\n  Matrix62d U;\n\n  for (int i = 0; i < 6; ++i) {\n    X.row(i) = normalized_feature_points_left[i];\n    U.row(i) = normalized_feature_points_right[i];\n  }\n\n  Matrix68d M;\n  Vector6d u2 = U.col(0).array().square() + U.col(1).array().square();\n\n  M.col(0) = -X.col(1).array() * U.col(0).array();\n  M.col(1) = -X.col(1).array() * U.col(1).array();\n  M.col(2) = -X.col(1);\n  M.col(3) = X.col(0).array() * U.col(0).array();\n  M.col(4) = X.col(0).array() * U.col(1).array();\n  M.col(5) = X.col(0);\n  M.col(6) = -X.col(1).array() * u2.array();\n  M.col(7) = X.col(0).array() * u2.array();\n\n  Eigen::JacobiSVD<Matrix68d, Eigen::FullPivHouseholderQRPreconditioner> Svd1(\n      M, Eigen::ComputeFullV);\n  const Eigen::Matrix<double, 8, 8>& V1 = Svd1.matrixV();\n\n  const double a = -V1(2, 6) * V1(7, 6) + V1(5, 6) * V1(6, 6);\n  const double b = -V1(2, 6) * V1(7, 7) - V1(2, 7) * V1(7, 6) +\n                   V1(5, 6) * V1(6, 7) + V1(5, 7) * V1(6, 6);\n  const double c = -V1(2, 7) * V1(7, 7) + V1(5, 7) * V1(6, 7);\n  const double d = b * b - 4.0 * a * c;\n\n  int nsols = 0;\n  Vector2d rs;\n\n  if (IsNearZero(d)) {\n    nsols = 1;\n    rs(0) = (-b) / (2.0 * a);\n  } else if (d > 0.0) {\n    nsols = 2;\n    double d2 = std::sqrt(d);\n    rs(0) = (-b + d2) / (2.0 * a);\n    rs(1) = (-b - d2) / (2.0 * a);\n  } else {\n    return false;\n  }\n\n  const Vector6d x2 = X.col(0).array().square() + X.col(1).array().square();\n  Vector6d u3, r;\n  Matrix<double, 8, 1> n;\n  Matrix65d T;\n  T.col(0) = -M.col(3);\n  T.col(1) = -M.col(4);\n\n  for (int i = 0; i < nsols; i++) {\n    n = rs(i) * V1.col(6) + V1.col(7);\n    const double l2 = n(6) / n(2);\n    // skip this solution early if radial distortion is spurious\n    if (l2 < lmin || l2 > lmax) {\n      continue;\n    }\n\n    u3 = u3.Ones() + l2 * u2;\n    r = n(0) * U.col(0) + n(1) * U.col(1) + n(2) * u3;\n\n    T.col(2) = -X.col(0).array() * u3.array();\n    T.col(3) = x2.array() * r.array();\n    T.col(4) = r;\n\n    Eigen::JacobiSVD<Matrix65d> Svd2(T, Eigen::ComputeFullV);\n    Matrix<double, 5, 1> v2 = Svd2.matrixV().col(4);\n\n    v2.head(4) /= v2(4);\n    const double l1 = v2(3);\n    // skip this solution early if radial distortion is spurious\n    if (l1 < lmin || l1 > lmax) {\n      continue;\n    }\n\n    RadialHomographyResult res;\n    // fill homograhapy\n    res.H << n(0), n(1), n(2), n(3), n(4), n(5), v2(0), v2(1), v2(2);\n    // fill radial distortion values\n    res.l1 = l1;\n    res.l2 = l2;\n    results->push_back(res);\n  }\n\n  return nsols > 0;\n}\n}\n", "meta": {"hexsha": "11c133d4d421a30532fa835f5c9b64222fd85bc4", "size": 5370, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/six_point_radial_distortion_homography.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/pose/six_point_radial_distortion_homography.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/pose/six_point_radial_distortion_homography.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-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.2038216561, "max_line_length": 78, "alphanum_fraction": 0.6372439479, "num_tokens": 1735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5592229397279319}}
{"text": "#include \"discrete_exponential_map.h\"\n\n#include <set>\n#include <queue>\n\n#include <Eigen/Dense>\n\n#include <igl/hessian_energy.h>\n#include <igl/massmatrix.h>\n#include <igl/cotmatrix.h>\n\n#include <geometry/patch.h>\n#include <shape_signatures/shape_signature.h>\n#include <algorithms/shortest_path.h>\n#include <matching/surface_stroke.h>\n\nusing namespace shortest_path;\n\nDiscreteExponentialMap::DiscreteExponentialMap():\n\t_TBN(Eigen::Matrix3d::Identity()),\n\t_TBN_inv(Eigen::Matrix3d::Identity()),\n\t_geometry(nullptr) {\n\n}\n\n// Unintuitively, p_vid is actually the index of the vertex in relation to patch->origin_mesh()\nDiscreteExponentialMap::DiscreteExponentialMap(std::shared_ptr<Patch> patch, Eigen::DenseIndex p_vid, const Eigen::MatrixXd* guide_points) {\n\t// Implementation of Discrete Exponential Map from,\n\t// \"Part-Based Representation and Editing of 3D Surface Models\", Ryan Schmidt, 2011\n\n\tauto mesh = patch->origin_mesh();\n\n\tconst Eigen::MatrixXd& V = mesh->vertices();\n\tconst Eigen::MatrixXd& N_orig = mesh->vertex_normals();\n\tEigen::MatrixXd N(N_orig.rows(), N_orig.cols());\n\n\tif (V.size() <= 0 || N.size() <= 0) {\n\t\treturn;\n\t}\n\n\tstd::map<Eigen::DenseIndex, std::shared_ptr<DjikstraVertexNode>> nodes = djikstras_algorithm(patch, p_vid);\n\n\tif (nodes.size() == 0) {\n\t\t// djikstra's failed??\n\t\treturn;\n\t}\n\n\t// Smooth the normals a bit before generating the map\n\tEigen::SparseMatrix<double> M2;\n\tEigen::SparseMatrix<double> QH;\n\n\tEigen::MatrixXd V3 = V.leftCols<3>();\n\tEigen::MatrixXi F3 = mesh->faces().leftCols<3>();\n\n\tigl::massmatrix(V3, F3, igl::MASSMATRIX_TYPE_BARYCENTRIC, M2);\n\tigl::hessian_energy(V3, F3, QH);\n\n    // Smoothing -- 0.0 is no smoothing, 1.0 is full\n\tconst double alpha = 0.25;\n\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double>> hessSolver(alpha * QH + (1.0 - alpha) * M2);\n\tN << hessSolver.solve((1.0 - alpha) * M2 * N_orig);\n\n\tEigen::Vector3d p = V.row(p_vid).block<1, 3>(0, 0).transpose();\n\tEigen::Vector3d Np = N.row(p_vid).block<1, 3>(0, 0).transpose().normalized();\n\n\tEigen::Matrix3d Tp_TBN = basis_from_plane_normal(Np);\n\n\t// For each point in patch, create a chain of points also within the patch leading back to the center by the shortest path\n\tstd::priority_queue<std::shared_ptr<DjikstraVertexNode>, std::vector<std::shared_ptr<DjikstraVertexNode>>, DjikstraDist> Q;\n\n\tfor (auto it = nodes.begin(); it != nodes.end(); ++it) {\n\t\tQ.push(it->second);\n\t}\n\n\t// Create a set of planar undirected edges representing the discrete exponential map\n\tstd::map<Eigen::DenseIndex, Eigen::Vector2d> DEM_points;\n\tDEM_points.insert(std::make_pair(Q.top()->_vid, Eigen::Vector2d(0.0, 0.0)));\n\tQ.pop();\t\n\n\twhile (!Q.empty()) {\n\t\tauto node = Q.top();\n\t\tQ.pop();\n\n\t\tassert(node->_prev != nullptr);\n\t\tassert(node->_dist > 0.0);\n\t\tassert(node->_vid >= 0);\n\n\t\t// Run from each neighbor already present in DEM_points, as an \"Upwind Average\"\n\t\t// Find all of q's neighbors already in the DEM that share locality with node->_prev\n\t\tstd::vector<Eigen::DenseIndex> neighbors = patch->origin_mesh()->one_ring(node->_vid);\n\t\tstd::vector<std::pair<Eigen::Vector2d, double>> upwind;\n\t\tEigen::Vector2d from_parent;\n\t\tdouble parent_dist = 0.0;\n\n\t\tfor (Eigen::DenseIndex prev_vid : neighbors) {\n\t\t\tauto prev = DEM_points.find(prev_vid);\n\n\t\t\tif (prev == DEM_points.end()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tEigen::Vector3d q = V.row(node->_vid).block<1, 3>(0, 0).transpose();\n\n\t\t\tif (prev_vid == p_vid) {\n\t\t\t\tEigen::Vector2d Tpq = local_log_map(p, Tp_TBN, q).topRows<2>();\n\n\t\t\t\tdouble weight = (q - p).squaredNorm() + 1e-7;\n\n\t\t\t\tupwind.push_back(std::make_pair(Tpq, weight));\n\n\t\t\t\tif (prev_vid == node->_prev->_vid) {\n\t\t\t\t\t// Store away for special locality test when averaging upwind points\n\t\t\t\t\tparent_dist = Tpq.norm();\n\t\t\t\t\tfrom_parent = Tpq;\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tEigen::Vector3d r = V.row(prev_vid).block<1, 3>(0, 0).transpose();\n\t\t\tEigen::Vector2d Tpr = prev->second;\n\n\t\t\t// A vector parallel to two planes is the cross product of the two normals. \n\t\t\tEigen::Vector3d Nr = N.row(prev_vid).block<1, 3>(0, 0).transpose().normalized();\n\t\t\tEigen::Matrix3d Tr_TBN = basis_from_plane_normal(Nr);\n\n\t\t\t// Do not pass through the intermediate planes -- instead, just transform directly into Tp after log_r(q)\n\t\t\tEigen::Vector2d Trq = local_log_map(r, Tr_TBN, q).topRows<2>();\n\n\t\t\t// 3D rotation Mn\n\t\t\tEigen::Vector3d rot_axis = Nr.cross(Np);\n\n\t\t\tif (rot_axis.isZero(1e-7)) {\n\t\t\t\trot_axis = Tp_TBN.col(0);\n\t\t\t}\n\n\t\t\trot_axis.normalize();\n\n\t\t\tdouble rot_angle_3d = std::acos(std::min(1.0, std::max(-1.0, Nr.dot(Np))));\n\t\t\tEigen::AngleAxis<double> R(rot_angle_3d, rot_axis);\n\n\t\t\t// 2D rotation for planar basis alignment\n\t\t\tEigen::Vector3d er = (R * Tr_TBN.col(0)).normalized();\n\t\t\tEigen::Vector3d ep = Tp_TBN.col(0);\n\n\t\t\tassert(er.dot(Np) < 1e-7);\n\n\t\t\tdouble rot_angle_2d = std::acos(std::min(1.0, std::max(-1.0, er.dot(ep))));\n\n\t\t\tif (!er.cross(ep).isZero(1e-7) && er.cross(ep).normalized().dot(Np) > 0.0) {\n\t\t\t\trot_angle_2d *= -1.0;\n\t\t\t}\n\n\t\t\tEigen::Rotation2D<double> E(rot_angle_2d);\n\n\t\t\tEigen::Vector2d Tpq = Tpr + E * Trq;\n\n\t\t\tdouble weight = 1.0 / ((q - r).squaredNorm() + 1e-7);\n\t\t\t\n\t\t\tif (prev_vid == node->_prev->_vid) {\n\t\t\t\t// Store away for special locality test when averaging upwind points\n\t\t\t\tparent_dist = (Tpr - Tpq).norm();\n\t\t\t\tfrom_parent = Tpq;\n\t\t\t}\n\n\t\t\tupwind.push_back(std::make_pair(Tpq, weight));\n\t\t}\n\n\t\tassert(upwind.size() > 0);\n\n\t\tEigen::Vector2d Tpq_avg(0.0, 0.0);\n\n\t\tdouble total_weight = 0.0;\n\t\tfor (auto pt : upwind) {\n\t\t\tif ((pt.first - from_parent).norm() > parent_dist / 2.0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\ttotal_weight += pt.second;\n\t\t}\n\n\t\tfor (auto pt : upwind) {\n\t\t\tif ((pt.first - from_parent).norm() > parent_dist / 2.0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tTpq_avg += pt.second * pt.first / total_weight;\n\t\t}\n\n\t\tDEM_points.insert(std::pair<Eigen::DenseIndex, Eigen::Vector2d>(node->_vid, Tpq_avg));\n\t}\n\n\tif (!init(p_vid, Tp_TBN, DEM_points, patch)) {\n\t\tthrow std::invalid_argument(\"DEM arguments invalid!\");\n\t}\n}\n\nDiscreteExponentialMap::DiscreteExponentialMap(const Eigen::DenseIndex center_vid, Eigen::Matrix3d& TBN, const std::map<Eigen::DenseIndex, Eigen::Vector2d>& vertices, std::shared_ptr<Patch> geometry) {\n\tif (!init(center_vid, TBN, vertices, geometry)) {\n\t\tthrow std::invalid_argument(\"DEM arguments invalid!\");\n\t}\n}\n\nDiscreteExponentialMap::~DiscreteExponentialMap() {\n\n}\n\nEigen::MatrixXi DiscreteExponentialMap::get_reindexed_faces() const {\n\tEigen::MatrixXi F = _faces;\n\n\tstd::map<Eigen::DenseIndex, Eigen::DenseIndex> vid_remap;\n\tEigen::DenseIndex i = 0;\n\tfor (auto it = _vertices.cbegin(); it != _vertices.cend(); ++it, ++i) {\n\t\tvid_remap.insert(std::make_pair(it->first, i));\n\t}\n\n\tfor (i = 0; i < F.size(); ++i) {\n\t\tF(i) = vid_remap.at(F(i));\n\t}\n\n\treturn F;\n}\n\nbool DiscreteExponentialMap::init(const Eigen::DenseIndex center_vid, Eigen::Matrix3d& TBN, const std::map<Eigen::DenseIndex, Eigen::Vector2d>& vertices, std::shared_ptr<Patch> geometry) {\n\t_geometry = geometry;\n\t_TBN = TBN;\n\t_TBN_inv = TBN.inverse();\n\t_vertices = vertices;\n\n\t_center_vid = center_vid;\n\n\t// Only include faces made up of vertices in the map\n\tstd::set<Eigen::DenseIndex> fids;\n\tstd::shared_ptr<Mesh> mesh = _geometry->origin_mesh();\n\tconst Eigen::MatrixXi& F = mesh->faces();\n\tconst Eigen::MatrixXd& V = mesh->vertices();\n\n\tfor (Eigen::DenseIndex i = 0; i < F.rows(); ++i) {\n\t\tbool included = true;\n\n\t\tfor (Eigen::DenseIndex j = 0; j < F.cols(); ++j) {\n\t\t\tif (vertices.find(F(i, j)) == vertices.end()) {\n\t\t\t\tincluded = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!included) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (Eigen::DenseIndex j = 0; j < F.cols(); ++j) {\n\t\t\t// Check edge length (it should not be severely distorted\n\t\t\tEigen::DenseIndex next = (j + 1) % F.cols();\n\n\t\t\tdouble dist = (V.row(F(i, j)).leftCols<3>() - V.row(F(i, next)).leftCols<3>()).norm();\n\t\t\tdouble dem_dist = (vertices.at(F(i, j)) - vertices.at(F(i, next))).norm();\n\t\t\t\n\t\t\tif (dem_dist > 2.0 * dist) {\n\t\t\t\tincluded = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (included) {\n\t\t\tfids.insert(i);\n\t\t}\n\t}\n\n\t_faces = Eigen::MatrixXi(fids.size(), F.cols());\n\n\tint fIndex = 0;\n\tfor (auto fid : fids) {\n\t\t_fid_remap.insert(std::make_pair(fIndex, fid));\n\t\t_faces.row(fIndex++) << F.row(fid);\n\t}\n\n\tstd::stringstream ss; ss << geometry->origin_mesh()->resource_dir() << \"//matlab//dem_debug.m\";\n\tto_matlab(ss.str());\n\n\tstd::vector<std::pair<Eigen::DenseIndex, Eigen::Vector2d>> face_centers;\n\n\t_center_fid = -1;\n\n\tstd::vector<Eigen::DenseIndex> center_fids;\n\tfor (Eigen::DenseIndex i = 0; i < _faces.rows(); ++i) {\n\t\tfor (Eigen::DenseIndex j = 0; j < _faces.cols(); ++j) {\n\t\t\tif (_faces(i, j) == _center_vid) {\n\t\t\t\tcenter_fids.push_back(i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (auto fid : center_fids) {\n\t\tEigen::Vector2d fc = Eigen::Vector2d::Zero();\n\n\t\tfor (Eigen::DenseIndex j = 0; j < _faces.cols(); ++j) {\n\t\t\tfc += vertices.at(_faces(fid, j)) / static_cast<double>(_faces.cols());\n\t\t}\n\n\t\tface_centers.push_back(std::pair<Eigen::DenseIndex, Eigen::Vector2d>(fid, fc));\n\t}\n\n\tEigen::DenseIndex centroid_fid = -1;\n\tdouble dist = std::numeric_limits<double>::max();\n\n\tfor (Eigen::DenseIndex i = 0; i < face_centers.size(); ++i) {\n\t\tdouble c_dist = (face_centers[i].second - vertices.at(_center_vid)).norm();\n\n\t\tif (c_dist < dist) {\n\t\t\tdist = c_dist;\n\t\t\t_center_fid = face_centers[i].first;\n\t\t}\n\t}\n\n\tif (_center_fid < 0 && _vertices.size() > 2) {\n\t\tthrow std::domain_error(\"Invalid _center_fid!\");\n\t}\n\n\treturn true;\n}\n\nEigen::DenseIndex DiscreteExponentialMap::get_center_vid() const {\n\treturn _center_vid;\n}\n\nEigen::DenseIndex DiscreteExponentialMap::get_center_fid() const {\n\treturn _center_fid;\n}\n\nEigen::MatrixXd DiscreteExponentialMap::get_3d_vertices() const {\n\t// get_reindexed_faces describes the faces for this vertex ordering\n\tEigen::MatrixXd V_3d(_vertices.size(), 3);\n\n\tEigen::DenseIndex index = 0;\n\tfor (auto it = _vertices.cbegin(); it != _vertices.cend(); ++it) {\n\t\tEigen::Vector3d tbn_point = (Eigen::Vector3d() << it->second, 0.0).finished();\n\n\t\tV_3d.row(index++) = _TBN * tbn_point;\n\t}\n\n\treturn V_3d;\n}\n\ndouble DiscreteExponentialMap::get_radius() const {\n\tEigen::MatrixXd V = get_3d_vertices();\n\n\t// the DEM is relative to the frame origin, so the radius is just the greatest magnitude norm\n\tdouble radius = 0.0;\n\tfor (Eigen::DenseIndex i = 0; i < V.rows(); ++i) {\n\t\tradius = std::max(V.row(i).norm(), radius);\n\t}\n\n\treturn radius;\n}\n\nEigen::Vector3d DiscreteExponentialMap::get_normal() const {\n\treturn _TBN.col(2);\n}\n\nEigen::Vector3d DiscreteExponentialMap::get_tangent() const {\n\treturn _TBN.col(0);\n}\n\nEigen::Vector3d DiscreteExponentialMap::get_bitangent() const {\n\treturn _TBN.col(1);\n}\n\nEigen::Vector2d DiscreteExponentialMap::interpolated_polar(Eigen::Vector3d barycentric_coords, const std::vector<Eigen::DenseIndex>& vids) {\n\tEigen::Vector2d polar;\n\tEigen::MatrixXd points(2,3);\n\n\tfor (Eigen::DenseIndex i = 0; i < 3; i++) {\n\t\t// Just gonna let it throw an exception if the vids are no in the map -- shame on the user!\n\t\tpoints.col(i) = _vertices[vids[i]];\n\t}\n\n\tEigen::Vector2d xy = points * barycentric_coords;\n\n\tpolar << std::sqrt(std::pow(xy(0), 2) + std::pow(xy(1), 2)), std::atan2(xy(1), xy(0));\n\n\treturn polar;\n}\n\nEigen::DenseIndex DiscreteExponentialMap::nearest_vertex_by_polar(const Eigen::Vector2d& polar_point) {\n\tEigen::Vector2d xy_point;\n\txy_point << polar_point(0) * std::cos(polar_point(1)),\n\t\t\t\tpolar_point(0) * std::sin(polar_point(1));\n\n\tEigen::DenseIndex vid = -1;\n\tdouble dist = std::numeric_limits<double>::max();\n\tfor (auto v : _vertices) {\n\t\tdouble t_dist = (v.second - xy_point).norm();\n\n\t\tif (t_dist < dist) {\n\t\t\tvid = v.first;\n\t\t\tdist = t_dist;\n\t\t}\n\t}\n\n\treturn vid;\n}\n\nEigen::VectorXd DiscreteExponentialMap::query_map_value(const Eigen::Vector2d& xy_point, std::shared_ptr<ShapeSignature> sig) const {\n\t// Find triangle which contains (x, y)\n\tunsigned int i = 0;\n\tfor (i = 0; i < _faces.rows(); ++i) {\n\t\tEigen::DenseIndex r = _faces(i, 0);\n\t\tEigen::DenseIndex s = _faces(i, 1);\n\t\tEigen::DenseIndex t = _faces(i, 2);\n\n\t\tEigen::Vector2d a = _vertices.at(_faces(i, 0));\n\t\tEigen::Vector2d b = _vertices.at(_faces(i, 1));\n\t\tEigen::Vector2d c = _vertices.at(_faces(i, 2));\n\n\t\tif (point_in_triangle(xy_point, a, b, c)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// In case point isn't in any triangle, return some invalid result (-1.0?)\n\tif (i >= _faces.rows()) {\n\t\t// point is not within any triangle of the map, so return a vector packed with -1.0s\n\t\treturn Eigen::VectorXd::Constant(sig->feature_dimension(), -1.0);\n\t}\n\n\t// Find barycentric coordinates of the point within the triangle\n\t// https://gamedev.stackexchange.com/questions/23743/whats-the-most-efficient-way-to-find-barycentric-coordinates\n\tEigen::Vector2d v0 = _vertices.at(_faces(i, 1)) - _vertices.at(_faces(i, 0));\n\tEigen::Vector2d v1 = _vertices.at(_faces(i, 2)) - _vertices.at(_faces(i, 0));\n\tEigen::Vector2d v2 = xy_point - _vertices.at(_faces(i, 0));\n\tdouble d00 = v0.dot(v0);\n\tdouble d01 = v0.dot(v1);\n\tdouble d11 = v1.dot(v1);\n\tdouble d20 = v2.dot(v0);\n\tdouble d21 = v2.dot(v1);\n\tdouble denom = d00 * d11 - d01 * d01;\n\tdouble v = (d11 * d20 - d01 * d21) / denom;\n\tdouble w = (d00 * d21 - d01 * d20) / denom;\n\tdouble u = 1.0f - v - w;\n\n\tif (u + v + w - 1.0 > std::numeric_limits<double>::epsilon()) {\n\t\tthrow std::domain_error(\"query_map_value(): Invalid barycentric coordinates!\");\n\t}\n\n\t// return linearly interpolated feature values from triangle vertices with respect to (x,y)\n\t//Eigen::VectorXd value = u * features.row(_faces(i, 0)) + v * features.row(_faces(i, 1)) + w * features.row(_faces(i, 2));\n\tEigen::VectorXd u_coord = sig->lerpable_coord(_fid_remap.at(i), _faces(i, 0));\n\tEigen::VectorXd v_coord = sig->lerpable_coord(_fid_remap.at(i), _faces(i, 1));\n\tEigen::VectorXd w_coord = sig->lerpable_coord(_fid_remap.at(i), _faces(i, 2));\n\n\tEigen::VectorXd value = u * u_coord\n\t\t\t\t\t\t  + v * v_coord\n\t\t\t\t\t\t  + w * w_coord;\n\n\tvalue = sig->lerpable_to_signature_value(value);\n\n\treturn value;\n}\n\nEigen::VectorXd DiscreteExponentialMap::query_map_value_polar(const Eigen::Vector2d& polar_point, std::shared_ptr<ShapeSignature> sig) const {\n\tEigen::Vector2d xy_point;\n\txy_point << polar_point(0) * std::cos(polar_point(1)),\n\t\t\t\tpolar_point(0) * std::sin(polar_point(1));\n\n\treturn query_map_value(xy_point, sig);\n}\n\nbool DiscreteExponentialMap::to_matlab(std::string script_out_path) {\n\tstd::ofstream m(script_out_path, std::ofstream::out);\n\n\tif (m.is_open()) {\n\t\tm << \"figure;\" << std::endl;\n\t\tm << \"hold on;\" << std::endl;\n\t\tm << \"axis equal;\" << std::endl;\n\t\tm << \"grid on;\" << std::endl;\n\n\t\tauto vertices = get_raw_vertices();\n\t\tm << \"v = [ ...\" << std::endl;\n\t\tfor (auto vert : vertices) {\n\t\t\tm << vert.second.transpose() << \"; ...\" << std::endl;\n\t\t}\n\t\tm << \"];\" << std::endl;\n\n\t\tconst Eigen::MatrixXi& faces = get_reindexed_faces();\n\t\tm << \"f = [ ...\" << std::endl;\n\t\tfor (Eigen::DenseIndex i = 0; i < faces.rows(); ++i) {\n\t\t\tm << faces.row(i) << \"; ...\" << std::endl;\n\t\t}\n\t\tm << \"];\" << std::endl;\n\n\t\tm << \"for i=1:size(f,1)\" << std::endl;\n\t\tm << \"a = [v(f(i, 1) + 1, :), 0.0];\" << std::endl;\n\t\tm << \"b = [v(f(i, 2) + 1, :), 0.0];\" << std::endl;\n\t\tm << \"c = [v(f(i, 3) + 1, :), 0.0];\" << std::endl;\n\t\tm << \"cb = (c - b) / norm(c - b);\" << std::endl;\n\t\tm << \"ab = (a - b) / norm(a - b);\" << std::endl;\n\t\tm << \"n = cross(cb, ab);\" << std::endl;\n\t\tm << \"n = n / norm(n);\" << std::endl;\n\t\tm << \"C = 'g';\" << std::endl;\n\t\tm << \"if dot(n, [0, 0, 1]) < 1 - 1e-7\" << std::endl;\n\t\tm << \"\tC = 'r';\" << std::endl;\n\t\tm << \"end\" << std::endl;\n\t\tm << \"h = fill([a(1), b(1), c(1)], [a(2), b(2), c(2)], C);\" << std::endl;\n\t\tm << \"set(h, 'facealpha', .5);\" << std::endl;\n\t\tm << \"end\" << std::endl;\n\n\t\tm << \"scatter(v(:,1), v(:,2), 'mo');\" << std::endl;\n\n\t\tm.close();\n\t}\n\telse {\n\t\treturn false;\n\t}\n\n\treturn true;\n}", "meta": {"hexsha": "a81b3c082f99ced90b5df43cd37920f8833d5feb", "size": 15631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matching/parameterization/discrete_exponential_map.cpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "src/matching/parameterization/discrete_exponential_map.cpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matching/parameterization/discrete_exponential_map.cpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 30.1175337187, "max_line_length": 201, "alphanum_fraction": 0.6513338878, "num_tokens": 5035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5592082870098504}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\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 stochasticcollocationinvcdf.hpp\n    Stochastic collocation inverse cumulative distribution function\n*/\n\n#ifndef quantlib_stochastic_collation_inv_cdf_hpp\n#define quantlib_stochastic_collation_inv_cdf_hpp\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/interpolations/lagrangeinterpolation.hpp>\n\n#include <boost/function.hpp>\n#include <functional>\n\nnamespace QuantLib {\n    //! Stochastic collocation inverse cumulative distribution function\n\n    /*! References:\n        L.A. Grzelak, J.A.S. Witteveen, M.Suárez-Taboada, C.W. Oosterlee,\n        The Stochastic Collocation Monte Carlo Sampler: Highly efficient\n        sampling from “expensive” distributions\n        http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2529691\n     */\n\n    class StochasticCollocationInvCDF {\n      public:\n        typedef Real argument_type;\n        typedef Real result_type;\n\n        StochasticCollocationInvCDF(\n            const boost::function<Real(Real)>& invCDF,\n            Size lagrangeOrder,\n            Real pMax = Null<Real>(),\n            Real pMin = Null<Real>());\n\n        Real value(Real x) const;\n        Real operator()(Real u) const;\n\n      private:\n        const Array x_;\n        const Volatility sigma_;\n        const Array y_;\n        const LagrangeInterpolation interpl_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "b419c26d523261726045265b94c7417a26ab65c9", "size": 2134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_stars_repo_name": "CAAA333/Engine-master", "max_stars_repo_head_hexsha": "63b23e465ad5b4f8dcbe63b761cd3f59df455ad9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_issues_repo_name": "CAAA333/Engine-master", "max_issues_repo_head_hexsha": "63b23e465ad5b4f8dcbe63b761cd3f59df455ad9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_forks_repo_name": "CAAA333/Engine-master", "max_forks_repo_head_hexsha": "63b23e465ad5b4f8dcbe63b761cd3f59df455ad9", "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": 31.8507462687, "max_line_length": 79, "alphanum_fraction": 0.7127460169, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5592082765421026}}
{"text": "#ifndef FUN_RAT_HPP\n#define FUN_RAT_HPP\n\n/**\n\n- Modify from boost::rational<>\n- Features:\n  - No exception, support NaN, $\\pm\\Infty$.\n  - Avoid normalization in every operation.\n    Avoid gcd() in every operation to speed up the calculation.\n    The rationale behind this is that: the comparsion (operator==)\n    and printout are not often used.\n  - Check 2/4 == 1/2\n\n- Rule:\n  1. check if den1 == den2 first\n\n**/\n\n#include <boost/config.hpp> // for BOOST_NO_STDC_NAMESPACE, BOOST_MSVC, etc\n#ifndef BOOST_NO_IOSTREAM\n#include <iomanip> // for std::setw\n#include <ios>     // for std::noskipws, streamsize\n#include <istream> // for std::istream\n#include <ostream> // for std::ostream\n#include <sstream> // for std::ostringstream\n#endif\n#include <cstddef> // for NULL\n// xxx #include <stdexcept>             // for std::domain_error\n#include <boost/assert.hpp>            // for BOOST_ASSERT\n#include <boost/call_traits.hpp>       // for boost::call_traits\n#include <boost/detail/workaround.hpp> // for BOOST_WORKAROUND\n#include <boost/operators.hpp>         // for boost::addable etc\n#include <cstdlib>                     // for std::abs\n#include <string>                      // for std::string implicit constructor\n\n//#include <boost/integer/common_factor_rt.hpp> // for boost::integer::gcd, lcm\n#include <boost/static_assert.hpp> // for BOOST_STATIC_ASSERT\n#include <limits>                  // for std::numeric_limits\n#include <type_traits>             // is_integral<T>\n\n\n// Control whether depreciated GCD and LCM functions are included (default: yes)\n#ifndef BOOST_CONTROL_RATIONAL_HAS_GCD\n#define BOOST_CONTROL_RATIONAL_HAS_GCD 1\n#endif\n\nnamespace boost {\n\ntemplate <typename _Z,\n          class = typename std::enable_if<std::is_integral<_Z>::value>::type>\ninline constexpr _Z gcd(const _Z &a, const _Z &b) noexcept {\n  return b == _Z(0) ? abs(a) : gcd(b, a % b);\n}\n\ntemplate <typename IntType>\nclass rat\n    : less_than_comparable<\n          rat<IntType>,\n          equality_comparable<\n              rat<IntType>,\n              less_than_comparable2<\n                  rat<IntType>, IntType,\n                  equality_comparable2<\n                      rat<IntType>, IntType,\n                      addable<\n                          rat<IntType>,\n                          subtractable<\n                              rat<IntType>,\n                              multipliable<\n                                  rat<IntType>,\n                                  dividable<\n                                      rat<IntType>,\n                                      addable2<\n                                          rat<IntType>, IntType,\n                                          subtractable2<\n                                              rat<IntType>, IntType,\n                                              subtractable2_left<\n                                                  rat<IntType>, IntType,\n                                                  multipliable2<\n                                                      rat<IntType>, IntType,\n                                                      dividable2<\n                                                          rat<IntType>, IntType,\n                                                          dividable2_left<\n                                                              rat<IntType>,\n                                                              IntType,\n                                                              incrementable<\n                                                                  rat<IntType>,\n                                                                  decrementable<rat<\n                                                                      IntType>>>>>>>>>>>>>>>>> {\n  // Class-wide pre-conditions\n  static_assert(::std::numeric_limits<IntType>::is_specialized);\n\n  // Helper types\n  typedef typename boost::call_traits<IntType>::param_type param_type;\n\n  struct helper {\n    IntType parts[2];\n  };\n  typedef IntType (helper::*bool_type)[2];\n\npublic:\n  // Component type\n  typedef IntType int_type;\n\n  BOOST_CONSTEXPR\n  rat() : num(0), den(1) {}\n  BOOST_CONSTEXPR\n  rat(param_type n) : num(n), den(1) {}\n  rat(param_type n, param_type d) : num(n), den(d) { normalize(); }\n\n#ifndef BOOST_NO_MEMBER_TEMPLATES\n  template <typename NewType>\n  BOOST_CONSTEXPR explicit rat(rat<NewType> const &r)\n      : num(r.numerator()), den(r.denominator()) {}\n#endif\n\n  // Default copy constructor and assignment are fine\n\n  // Add assignment from IntType\n  rat &operator=(param_type i) {\n    num = i;\n    den = 1;\n    return *this;\n  }\n\n  // Assign in place\n  rat &assign(param_type n, param_type d);\n\n  // Access to representation\n  BOOST_CONSTEXPR\n  IntType numerator() const { return num; }\n  BOOST_CONSTEXPR\n  IntType denominator() const { return den; }\n\n  // Arithmetic assignment operators\n  rat &operator+=(const rat &r);\n  rat &operator-=(const rat &r);\n  rat &operator*=(const rat &r);\n  rat &operator/=(const rat &r);\n\n  rat &operator+=(param_type i) {\n    num += i * den;\n    return *this;\n  }\n  rat &operator-=(param_type i) {\n    num -= i * den;\n    return *this;\n  }\n  rat &operator*=(param_type i);\n  rat &operator/=(param_type i);\n\n  // Increment and decrement\n  const rat &operator++() {\n    num += den;\n    return *this;\n  }\n  const rat &operator--() {\n    num -= den;\n    return *this;\n  }\n\n  // Operator not\n  BOOST_CONSTEXPR\n  bool operator!() const { return !num; }\n\n// Boolean conversion\n\n#if BOOST_WORKAROUND(__MWERKS__, <= 0x3003)\n// The \"ISO C++ Template Parser\" option in CW 8.3 chokes on the\n// following, hence we selectively disable that option for the\n// offending memfun.\n#pragma parse_mfunc_templ off\n#endif\n\n  BOOST_CONSTEXPR\n  operator bool_type() const { return operator!() ? 0 : &helper::parts; }\n\n#if BOOST_WORKAROUND(__MWERKS__, <= 0x3003)\n#pragma parse_mfunc_templ reset\n#endif\n\n  // Comparison operators\n  bool operator<(const rat &r) const;\n  BOOST_CONSTEXPR\n  bool operator==(const rat &r) const;\n\n  bool operator<(param_type i) const;\n  bool operator>(param_type i) const;\n  BOOST_CONSTEXPR\n  bool operator==(param_type i) const;\n\nprivate:\n  // Implementation - numerator and denominator (normalized).\n  // Other possibilities - separate whole-part, or sign, fields?\n  IntType num;\n  IntType den;\n\n  // Helper functions\n  static BOOST_CONSTEXPR int_type\n  inner_gcd(param_type a, param_type b, int_type const &zero = int_type(0)) {\n    return b == zero ? a : inner_gcd(b, a % b, zero);\n  }\n\n  static BOOST_CONSTEXPR int_type\n  inner_abs(param_type x, int_type const &zero = int_type(0)) {\n    return x < zero ? -x : +x;\n  }\n\n  // Representation note: Fractions are kept in normalized form at all\n  // times. normalized form is defined as gcd(num,den) == 1 and den > 0.\n  // In particular, note that the implementation of abs() below relies\n  // on den always being positive.\n  // bool test_invariant() const;\n  void normalize();\n\n  static BOOST_CONSTEXPR bool is_normalized(param_type n, param_type d,\n                                            int_type const &zero = int_type(0),\n                                            int_type const &one = int_type(1)) {\n    return d >= zero;\n  }\n};\n\n// Assign in place\ntemplate <typename IntType>\ninline rat<IntType> &rat<IntType>::assign(param_type n, param_type d) {\n  return *this = rat(n, d);\n}\n\n// Unary plus and minus\ntemplate <typename IntType>\nBOOST_CONSTEXPR inline rat<IntType> operator+(const rat<IntType> &r) {\n  return r;\n}\n\ntemplate <typename IntType>\ninline rat<IntType> operator-(const rat<IntType> &r) {\n  return rat<IntType>(-r.numerator(), r.denominator());\n}\n\n// Arithmetic assignment operators\ntemplate <typename IntType>\nrat<IntType> &rat<IntType>::operator+=(const rat<IntType> &r) {\n  // This calculation avoids overflow, and minimises the number of expensive\n  // calculations. Thanks to Nickolay Mladenov for this algorithm.\n  //\n  // Proof:\n  // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1.\n  // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1\n  //\n  // The result is (a*d1 + c*b1) / (b1*d1*g).\n  // Now we have to normalize this ratio.\n  // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1\n  // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a.\n  // But since gcd(a,b1)=1 we have h=1.\n  // Similarly h|d1 leads to h=1.\n  // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g\n  // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g)\n  // Which proves that instead of normalizing the result, it is better to\n  // divide num and den by gcd((a*d1 + c*b1), g)\n\n  // Protect against self-modification\n  IntType r_num = r.num;\n  IntType r_den = r.den;\n\n  // Avoid repeated construction\n  // IntType zero(0);\n\n  if (den == r_den) {\n    num += r_num;\n    return *this;\n  }\n\n  IntType g = gcd(den, r_den);\n  den /= g; // = b1 from the calculations above\n  num = num * (r_den / g) + r_num * den;\n  g = gcd(num, g);\n  num /= g;\n  den *= r_den / g;\n\n  return *this;\n}\n\ntemplate <typename IntType>\nrat<IntType> &rat<IntType>::operator-=(const rat<IntType> &r) {\n  // Protect against self-modification\n  IntType r_num = r.num;\n  IntType r_den = r.den;\n\n  // Avoid repeated construction\n  // IntType zero(0);\n\n  if (den == r_den) {\n    num -= r_num;\n    return *this;\n  }\n\n  // This calculation avoids overflow, and minimises the number of expensive\n  // calculations. It corresponds exactly to the += case above\n  IntType g = gcd(den, r_den);\n  den /= g;\n  num = num * (r_den / g) - r_num * den;\n  g = gcd(num, g);\n  num /= g;\n  den *= r_den / g;\n\n  return *this;\n}\n\ntemplate <typename IntType>\nrat<IntType> &rat<IntType>::operator*=(const rat<IntType> &r) {\n  // Protect against self-modification\n  IntType r_num = r.num;\n  IntType r_den = r.den;\n\n  if (num == r_den) {\n    num = r_num;\n    return *this;\n  }\n  if (den == r_num) {\n    den = r_den;\n    return *this;\n  }\n\n  num *= r_num;\n  den *= r_den;\n  return *this;\n}\n\ntemplate <typename IntType>\nrat<IntType> &rat<IntType>::operator/=(const rat<IntType> &r) {\n  // Protect against self-modification\n  IntType r_num = r.num;\n  IntType r_den = r.den;\n\n  // Avoid repeated construction\n  IntType zero(0);\n\n  // Trap division by zero\n  if (r_num == zero && num == zero) {\n    den = zero;\n    return *this;\n  }\n  if (r_den == zero && den == zero) {\n    num = zero;\n    return *this;\n  }\n\n  // Avoid overflow and preserve normalization\n  IntType gcd1 = gcd(num, r_num);\n  IntType gcd2 = gcd(r_den, den);\n  num = (num / gcd1) * (r_den / gcd2);\n  den = (den / gcd2) * (r_num / gcd1);\n\n  if (den < zero) {\n    num = -num;\n    den = -den;\n  }\n  return *this;\n}\n\n// Mixed-mode operators\ntemplate <typename IntType>\ninline rat<IntType> &rat<IntType>::operator*=(param_type i) {\n  // Avoid repeated construction\n  IntType zero(0);\n\n  if (i == zero && den == zero) {\n    num = zero;\n    return *this;\n  }\n\n  // Avoid overflow and preserve normalization\n  IntType gcd1 = gcd(i, den);\n  num *= i / gcd1;\n  den /= gcd1;\n\n  return *this;\n}\n\ntemplate <typename IntType>\nrat<IntType> &rat<IntType>::operator/=(param_type i) {\n  // Avoid repeated construction\n  IntType const zero(0);\n\n  if (i == zero && num == zero) {\n    den = zero;\n    return *this;\n  }\n\n  // Avoid overflow and preserve normalization\n  IntType const gcd1 = gcd(num, i);\n  num /= gcd1;\n  den *= i / gcd1;\n\n  if (den < zero) {\n    num = -num;\n    den = -den;\n  }\n\n  return *this;\n}\n\n// Comparison operators\ntemplate <typename IntType>\nbool rat<IntType>::operator<(const rat<IntType> &r) const {\n  if (den == r.den)\n    return num < r.num;\n  return num * r.den < den * r.num;\n}\n\ntemplate <typename IntType> bool rat<IntType>::operator<(param_type i) const {\n  return num < den * i;\n}\n\ntemplate <typename IntType> bool rat<IntType>::operator>(param_type i) const {\n  return operator==(i) ? false : !operator<(i);\n}\n\ntemplate <typename IntType>\nBOOST_CONSTEXPR inline bool is_NaN(const rat<IntType> &r) {\n  // Avoid repeated construction\n  IntType const zero(0);\n  return r.denominator() == zero && r.numerator() == zero;\n}\n\ntemplate <typename IntType>\nBOOST_CONSTEXPR inline bool rat<IntType>::\noperator==(const rat<IntType> &r) const {\n  if (den == r.den)\n    return num == r.num;\n  return num * r.den == r.num * den;\n}\n\ntemplate <typename IntType>\nBOOST_CONSTEXPR inline bool rat<IntType>::operator==(param_type i) const {\n  return num == i * den;\n}\n\n// Invariant check\n// template <typename IntType>\n// inline bool rat<IntType>::test_invariant() const\n//{\n//    if (this->den == int_type(0) ) return true;\n//    return ( gcd(this->num, this->den) == int_type(1) );\n//}\n\n// Normalisation\ntemplate <typename IntType> void rat<IntType>::normalize() {\n  // Avoid repeated construction\n  IntType zero(0);\n\n  if (den == zero)\n    return;\n\n  // Handle the case of zero separately, to avoid division by zero\n  if (num == zero) {\n    den = IntType(1);\n    return;\n  }\n\n  IntType g = gcd(num, den);\n\n  num /= g;\n  den /= g;\n\n  // Ensure that the denominator is positive\n  if (den < zero) {\n    num = -num;\n    den = -den;\n  }\n\n  // ...But acknowledge that the previous step doesn't always work.\n  // (Nominally, this should be done before the mutating steps, but this\n  // member function is only called during the constructor, so we never have\n  // to worry about zombie objects.)\n  // if (den < zero)\n  //     throw bad_rat( \"bad rat: non-zero singular denominator\" );\n\n  // BOOST_ASSERT( this->test_invariant() );\n}\n\n#ifndef BOOST_NO_IOSTREAM\nnamespace detail {\n\n// A utility class to reset the format flags for an istream at end\n// of scope, even in case of exceptions\nstruct resetter {\n  resetter(std::istream &is) : is_(is), f_(is.flags()) {}\n  ~resetter() { is_.flags(f_); }\n  std::istream &is_;\n  std::istream::fmtflags f_; // old GNU c++ lib has no ios_base\n};\n}\n\n// Input and output\ntemplate <typename IntType>\nstd::istream &operator>>(std::istream &is, rat<IntType> &r) {\n  using std::ios;\n\n  IntType n = IntType(0), d = IntType(1);\n  char c = 0;\n  detail::resetter sentry(is);\n\n  if (is >> n) {\n    if (is.get(c)) {\n      if (c == '/') {\n        if (is >> std::noskipws >> d)\n          r.assign(n, d);\n      } else\n        is.setstate(ios::failbit);\n    }\n  }\n\n  return is;\n}\n\n// Add manipulators for output format?\ntemplate <typename IntType>\nstd::ostream &operator<<(std::ostream &os, const rat<IntType> &r) {\n  using namespace std;\n\n  // The slash directly precedes the denominator, which has no prefixes.\n  ostringstream ss;\n\n  ss.copyfmt(os);\n  ss.tie(NULL);\n  ss.exceptions(ios::goodbit);\n  ss.width(0);\n  ss << noshowpos << noshowbase << '/' << r.denominator();\n\n  // The numerator holds the showpos, internal, and showbase flags.\n  string const tail = ss.str();\n  streamsize const w = os.width() - static_cast<streamsize>(tail.size());\n\n  ss.clear();\n  ss.str(\"\");\n  ss.flags(os.flags());\n  ss << setw(w < 0 || (os.flags() & ios::adjustfield) != ios::internal ? 0 : w)\n     << r.numerator();\n  return os << ss.str() + tail;\n}\n#endif // BOOST_NO_IOSTREAM\n\n// Type conversion\ntemplate <typename T, typename IntType>\nBOOST_CONSTEXPR inline T rat_cast(const rat<IntType> &src) {\n  return static_cast<T>(src.numerator()) / static_cast<T>(src.denominator());\n}\n\n// Do not use any abs() defined on IntType - it isn't worth it, given the\n// difficulties involved (Koenig lookup required, there may not *be* an abs()\n// defined, etc etc).\ntemplate <typename IntType> inline rat<IntType> abs(const rat<IntType> &r) {\n  return r.numerator() >= IntType(0) ? r : -r;\n}\n\n} // namespace boost\n\n#endif // BOOST_RAT_HPP\n", "meta": {"hexsha": "c99d0f6cad2092a6f349299499e2a417b15295c8", "size": 15566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/fun/rat.hpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/fun/rat.hpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/fun/rat.hpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7468805704, "max_line_length": 96, "alphanum_fraction": 0.5980984196, "num_tokens": 4072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5590502981073311}}
{"text": "#include \"fem.hpp\"\n#include <iostream>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/grid/grid_generator.h>\n\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\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\n#include <deal.II/base/function.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n\nusing namespace dealii;\n\nFem::Fem()\n  : fe(1) //bi-linear basis functions\n  , dof_handler(triangulation)\n{}\n\nvoid Fem::make_grid()\n{\n  GridGenerator::hyper_cube(triangulation, -1, 1); // a square [-1,1] x [-1,1]\n  triangulation.refine_global(5); // final grid has 32 times 32 (= 1024) cells\n}\n\nvoid Fem::setup_system()\n{\n  dof_handler.distribute_dofs(fe);\n\n  DynamicSparsityPattern dsp(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  solution.reinit(dof_handler.n_dofs());\n  system_rhs.reinit(dof_handler.n_dofs());\n}\n\n\nvoid Fem::assemble_system()\n{\n  QGauss<2> quadrature_formula(fe.degree + 1);\n  FEValues<2> fe_values(fe,\n                        quadrature_formula,\n                        update_values | update_gradients | update_JxW_values);\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  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      fe_values.reinit(cell);\n\n      cell_matrix = 0;\n      cell_rhs    = 0;\n\n      for (unsigned int q_index = 0; q_index < n_q_points; ++q_index)\n        {\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                (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          for (unsigned int i = 0; i < dofs_per_cell; ++i)\n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                            1 *                                 // f(x_q)\n                            fe_values.JxW(q_index));            // dx\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          system_matrix.add(local_dof_indices[i],\n                            local_dof_indices[j],\n                            cell_matrix(i, j));\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        system_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n\n  // boundary conditions\n  std::map<types::global_dof_index, double> boundary_values;\n  VectorTools::interpolate_boundary_values(dof_handler,\n                                           0,\n                                           Functions::ZeroFunction<2>(),\n                                           boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values,\n                                     system_matrix,\n                                     solution,\n                                     system_rhs);\n}\n\n\n// solve with Conjugate Gradients method\nvoid Fem::solve()\n{\n  SolverControl solver_control(1000, 1e-12);\n  SolverCG<Vector<double>> solver(solver_control);\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity());\n}\n\nvoid Fem::output_results() const\n{\n  DataOut<2> data_out;\n  data_out.attach_dof_handler(dof_handler);\n  data_out.add_data_vector(solution, \"solution\");\n  data_out.build_patches();\n  std::ofstream output(\"solution.vtk\");\n  data_out.write_vtk(output);\n}\n\nvoid Fem::run()\n{\n  make_grid();\n  setup_system();\n  assemble_system();\n  solve();\n  output_results();\n  std::cout << \"FEM results available in `solution.vtk`. Try visualizing with Paraview.\" << std::endl; \n}\n", "meta": {"hexsha": "787e43ee6ba80de40b1668519af38d97889e69c3", "size": 4307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fem/fem.cpp", "max_stars_repo_name": "timotheehornek/cpack-exercise", "max_stars_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fem/fem.cpp", "max_issues_repo_name": "timotheehornek/cpack-exercise", "max_issues_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-12-08T10:38:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T16:34:14.000Z", "max_forks_repo_path": "fem/fem.cpp", "max_forks_repo_name": "timotheehornek/cpack-exercise", "max_forks_repo_head_hexsha": "e570c99022d33ea0a6d95e6f59661156c6e771ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2021-11-25T14:42:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T15:46:11.000Z", "avg_line_length": 31.4379562044, "max_line_length": 103, "alphanum_fraction": 0.6222428605, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5589797391498538}}
{"text": "#include <sparse_block_matrix/sparse_block_matrix.h>\n#include <sparse_block_matrix/linear_solver_cholmod.h>\n#include <bsplines/BSpline.hpp>\n#include <iomanip> //setprecision\n#include <sm/assert_macros.hpp>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/QR>\n//#include <asrl/string_routines.hpp>\n// boost::tie()\n#include <boost/tuple/tuple.hpp>\n#include <Eigen/SVD> \n\nnamespace bsplines {\n    \n    BSpline::BSpline(int splineOrder)\n      : splineOrder_(splineOrder)\n    {\n      SM_ASSERT_GE(Exception, splineOrder_, 2, \"The B-spline order must be greater than or equal to 2\");\n    }\n\n    BSpline::~BSpline()\n    {\n\n    }\n      \n    int BSpline::splineOrder() const\n    {\n      return splineOrder_;\n    }\n\n    int BSpline::polynomialDegree() const\n    {\n      return splineOrder_ - 1;\n    }\n\n    void BSpline::setKnotsAndCoefficients(const std::vector<double> & knots, const Eigen::MatrixXd & coefficients)\n    {\n      //std::cout << \"setting \" << knots.size() << \" knots\\n\";\n      // This will throw an exception if it is an invalid knot sequence.\n      verifyKnotSequence(knots);\n\n      // Check if the number of coefficients matches the number of knots.\n      SM_ASSERT_EQ(Exception, \n\t\t     numCoefficientsRequired(numValidTimeSegments(knots.size())),\n\t\t     coefficients.cols(),\n\t\t     \"A B-spline of order \" << splineOrder_ << \" requires \" << numCoefficientsRequired(numValidTimeSegments(knots.size()))\n\t\t     << \" coefficients for the \" << numValidTimeSegments(knots.size()) \n\t\t     << \" time segments defined by \" << knots.size() << \" knots\");  \n      \n      //std::cout << \"Setting coefficients: \" << coefficients << std::endl;\n\n      knots_ = knots;\n      coefficients_ = coefficients;\n\n      initializeBasisMatrices();\n    }\n\n    void BSpline::initializeBasisMatrices()\n    {\n      basisMatrices_.resize(numValidTimeSegments());\n\n      for(unsigned i = 0; i < basisMatrices_.size(); i++)\n\t{\n\t  basisMatrices_[i] = M(splineOrder_,i + splineOrder_ - 1);\n//\t  std::cout << \"M[\" << i << \"]:\\n\" << basisMatrices_[i] << std::endl;\n\t}\n    }\n\n\n    Eigen::MatrixXd BSpline::M(int k, int i)\n    {\n      SM_ASSERT_GE_DBG(Exception, k, 1, \"The parameter k must be greater than or equal to 1\");\n      SM_ASSERT_GE_DBG(Exception, i, 0, \"The parameter i must be greater than or equal to 0\");\n      SM_ASSERT_LT_DBG(Exception, i, (int)knots_.size(), \"The parameter i must be less than the number of time segments\");\n      if(k == 1)\n\t{\n\t  // The base-case for recursion.\n\t  Eigen::MatrixXd M(1,1);\n\t  M(0,0) = 1;\n\t  return M;\n\t}\n      else\n\t{\n\t  Eigen::MatrixXd M_km1 = M(k-1,i);\n\t  // The recursive equation for M\n\t  // M_k = [ M_km1 ] A  + [  0^T  ] B\n\t  //       [  0^T  ]      [ M_km1 ]\n\t  //        -------        -------\n\t  //         =: M1          =: M2\n\t  //\n\t  //     = M1 A + M2 B\n\t  Eigen::MatrixXd M1 = Eigen::MatrixXd::Zero(M_km1.rows() + 1, M_km1.cols());\n\t  Eigen::MatrixXd M2 = Eigen::MatrixXd::Zero(M_km1.rows() + 1, M_km1.cols());\n\n\t  M1.topRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;\n\t  M2.bottomRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;\n\n\t  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(k-1, k);\n\t  for(int idx = 0; idx < A.rows(); idx++)\n\t    {\n\t      int j = i - k + 2 + idx;\n\t      double d0 = d_0(k, i, j);\n\t      A(idx, idx  ) = 1.0 - d0;\n\t      A(idx, idx+1) = d0;\n\t    }\n\n\t  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(k-1, k);\n\t  for(int idx = 0; idx < B.rows(); idx++)\n\t    {\n\t      int j = i - k + 2 + idx;\n\t      double d1 = d_1(k, i, j);\n\t      B(idx, idx  ) = -d1;\n\t      B(idx, idx+1) = d1;\n\t    }\n\t  \n\t  \n\t  Eigen::MatrixXd M_k;\n\n\t  return M_k = M1 * A + M2 * B;\n\t}\n    }\n\n    double BSpline::d_0(int k, int i, int j)\n    {\n      SM_ASSERT_GE_LT_DBG(Exception,j+k-1,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      SM_ASSERT_GE_LT_DBG(Exception,j,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      SM_ASSERT_GE_LT_DBG(Exception,i,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      double denom = knots_[j+k-1] - knots_[j];\n      if(denom <= 0.0)\n\treturn 0.0;\n\n      double numerator = knots_[i] - knots_[j];\n\n      return numerator/denom;\n    }\n\n    double BSpline::d_1(int k, int i, int j)\n    {\n      SM_ASSERT_GE_LT_DBG(Exception,j+k-1,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      SM_ASSERT_GE_LT_DBG(Exception,i+1,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      SM_ASSERT_GE_LT_DBG(Exception,i,0,(int)knots_.size(), \"Index out of range with k=\" << k << \", i=\" << i << \", and j=\" << j);\n      double denom = knots_[j+k-1] - knots_[j];\n      if(denom <= 0.0)\n\treturn 0.0;\n\n      double numerator = knots_[i+1] - knots_[i];\n\n      return numerator/denom;\n    }\n\n\n\n    void BSpline::setKnotVectorAndCoefficients(const Eigen::VectorXd & knots, const Eigen::MatrixXd & coefficients)\n    {\n      //std::cout << \"setting knots of size \" << knots.size() << std::endl;//\": \" << knots.transpose() << std::endl;\n      std::vector<double> k(knots.size());\n      for(unsigned i = 0; i < k.size(); i++)\n\tk[i] = knots(i);\n\n      setKnotsAndCoefficients(k, coefficients);\n    }\n\n    const std::vector<double> BSpline::knots() const\n    {\n      return knots_;\n    }\n    \n    Eigen::VectorXd BSpline::knotVector() const\n    {\n      Eigen::VectorXd k(knots_.size());\n      for(unsigned i = 0; i < knots_.size(); i++)\n\tk(i) = knots_[i];\n\n      return k;\n    }\n\n    const Eigen::MatrixXd & BSpline::coefficients() const\n    {\n      return coefficients_;\n    }\n    \n\n    void BSpline::verifyKnotSequence(const std::vector<double> & knots) \n    {\n      SM_ASSERT_GE(Exception, (int)knots.size(), minimumKnotsRequired(), \n\t\t     \"The sequence does not contain enough knots to define an active time sequence \"\n\t\t     << \"for a B-spline of order \" << splineOrder_ << \". At least \" << minimumKnotsRequired() \n\t\t     << \" knots are required\");\n      \n      for(unsigned i = 1; i < knots_.size(); i++)\n\t{\n\t  SM_ASSERT_LE(Exception, knots[i-1], knots[i],\n\t\t\t \"The knot sequence must be nondecreasing. Knot \" << i\n\t\t\t << \" was not greater than or equal to knot \" << (i-1));\n\t}\n    }\n    \n    int BSpline::numValidTimeSegments(int numKnots) const\n    {\n      int nv = numKnots - 2*splineOrder_ + 1;\n      return std::max(nv,0);\n    }\n\n    int BSpline::numValidTimeSegments() const\n    {\n      return numValidTimeSegments(knots_.size());\n    }\n    \n    int BSpline::minimumKnotsRequired() const\n    {\n      return numKnotsRequired(1);\n    }\n\n    int BSpline::numCoefficientsRequired(int numTimeSegments) const\n    {\n      return numTimeSegments + splineOrder_ - 1;\n    }   \n\n    int BSpline::numKnotsRequired(int numTimeSegments) const\n    {\n      return numCoefficientsRequired(numTimeSegments) + splineOrder_;\n    }   \n\n\n    double BSpline::t_min() const\n    {\n      SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), \"The B-spline is not well initialized\");\n      return knots_[splineOrder_ - 1];\n    }\n\n    double BSpline::t_max() const\n    {\n      SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), \"The B-spline is not well initialized\");\n      return knots_[knots_.size() - splineOrder_];\n    }\n\n    std::pair<double,int> BSpline::computeTIndex(double t) const\n    {\n      SM_ASSERT_GE(Exception, t, t_min(), \"The time is out of range by \" << (t - t_min()));\n        \n        //// HACK - avoids numerical problems on initialisation\n        if ( fabs(t_max() - t) < 1e-10 )\n            t = t_max();\n        //// \\HACK\n        \n      SM_ASSERT_LE(Exception, t, t_max(), \"The time is out of range by \" << (t_max() - t));\n      std::vector<double>::const_iterator i;\n      if(t == t_max())\n\t{\n\t  // This is a special case to allow us to evaluate the spline at the boundary of the\n\t  // interval. This is not stricly correct but it will be useful when we start doing\n\t  // estimation and defining knots at our measurement times.\n\t  i = knots_.end() - splineOrder_;\n\t}\n      else\n\t{\n\t  i = std::upper_bound(knots_.begin(), knots_.end(), t);\n\t}\n      SM_ASSERT_TRUE_DBG(Exception, i != knots_.end(), \"Something very bad has happened in computeTIndex(\" << t << \")\");\n      \n      // Returns the index of the knot segment this time lies on and the width of this knot segment.\n      return std::make_pair(*i - *(i-1),(i - knots_.begin()) - 1);\n\n    }\n\n    std::pair<double,int> BSpline::computeUAndTIndex(double t) const \n    {\n      std::pair<double,int> ui = computeTIndex(t);\n      \n      int index = ui.second;\n      double denom = ui.first;\n\n      if(denom <= 0.0)\n\t{\n\t  // The case of duplicate knots.\n\t  //std::cout << \"Duplicate knots\\n\";\n\t  return std::make_pair(0, index);\n\t}\n      else\n\t{\n\n    //\t  std::cout << \"u:\" << t << \", \" << knots_[index] << \", \" << denom << \" idx:\" << index;\n\n\t  double u = (t - knots_[index])/denom;\n\t  return std::make_pair(u, index);\n\t}\n    }\n\n    int dmul(int i, int derivativeOrder)\n    {\n      if(derivativeOrder == 0)\n\treturn 1;\n      else if(derivativeOrder == 1)\n\treturn i;\n      else\n\treturn i * dmul(i-1,derivativeOrder-1) ;\n    }\n\n\n    Eigen::VectorXd BSpline::computeU(double uval, int segmentIndex, int derivativeOrder) const\n    {\n      Eigen::VectorXd u = Eigen::VectorXd::Zero(splineOrder_);\n      double delta_t = knots_[segmentIndex+1] - knots_[segmentIndex]; \n      double multiplier = 0.0;\n      if(delta_t > 0.0)\n\tmultiplier = 1.0/pow(delta_t, derivativeOrder);\n\n      double uu = 1.0;\n      for(int i = derivativeOrder; i < splineOrder_; i++)\n\t{\n\t  u(i) = multiplier * uu * dmul(i,derivativeOrder) ; \n\t  uu = uu * uval;\n\t}\n  //    std::cout << \"u:\" << std::endl;\n  //    std::cout << u << std::endl;\n\n      return u;\n    }\n\n    Eigen::VectorXd BSpline::eval(double t) const\n    {\n      return evalD(t,0);\n    }\n    \n    const Eigen::MatrixXd & BSpline::basisMatrixFromKnotIndex(int knotIndex) const\n    {\n      return basisMatrices_[basisMatrixIndexFromStartingKnotIndex(knotIndex)];\n    }\n\n\n    Eigen::VectorXd BSpline::evalD(double t, int derivativeOrder) const\n    {\n      SM_ASSERT_GE(Exception, derivativeOrder, 0, \"To integrate, use the integral function\");\n      // Returns the normalized u value and the lower-bound time index.\n      std::pair<double,int> ui = computeUAndTIndex(t);\n      Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);\n      \n      int bidx = ui.second - splineOrder_ + 1;\n\n      // Evaluate the spline (or derivative) in matrix form.\n      //\n      // [c_0 c_1 c_2 c_3] * B^T * u\n      // spline coefficients      \n\n      Eigen::VectorXd rv = coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * basisMatrices_[bidx].transpose() * u;\n\n      return rv;\n\n    }\n\n    Eigen::VectorXd BSpline::evalDAndJacobian(double t, int derivativeOrder, Eigen::MatrixXd * Jacobian, Eigen::VectorXi * coefficientIndices) const\n    {\n      SM_ASSERT_GE(Exception, derivativeOrder, 0, \"To integrate, use the integral function\");\n      // Returns the normalized u value and the lower-bound time index.\n      std::pair<double,int> ui = computeUAndTIndex(t);\n      Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);\n      \n      int bidx = ui.second - splineOrder_ + 1;\n\n      // Evaluate the spline (or derivative) in matrix form.\n      //\n      // [c_0 c_1 c_2 c_3] * B^T * u\n      // spline coefficients      \n\n      // The spline value\n      Eigen::VectorXd Bt_u = basisMatrices_[bidx].transpose() * u;\n      Eigen::VectorXd v = coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * Bt_u; \n\n      if(Jacobian)\n\t{\n\t  // The Jacobian\n\t  Jacobian->resize(coefficients_.rows(), Bt_u.size() * coefficients_.rows());\n\t  Eigen::MatrixXd one = Eigen::MatrixXd::Identity(coefficients_.rows(), coefficients_.rows());\n\t  for(int i = 0; i < Bt_u.size(); i++)\n\t    {\n\t      Jacobian->block(0, i*coefficients_.rows(), coefficients_.rows(), coefficients_.rows()) = one * Bt_u[i];\n\t    }\n\t}\n\n      if(coefficientIndices)\n\t{\n\t  int D = coefficients_.rows();\n\t  *coefficientIndices = Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);\n\t}\n      return v;\n\n    }\n\n    std::pair<Eigen::VectorXd, Eigen::MatrixXd> BSpline::evalDAndJacobian(double t, int derivativeOrder) const\n    {\n      std::pair<Eigen::VectorXd, Eigen::MatrixXd> rv;\n\n      rv.first = evalDAndJacobian(t, derivativeOrder, &rv.second, NULL);\n      \n      return rv;\n\n    }\n\n\n    Eigen::MatrixXd BSpline::localBasisMatrix(double t, int derivativeOrder) const\n    {\n      return Phi(t,derivativeOrder);\n    }\n\n    Eigen::MatrixXd BSpline::localCoefficientMatrix(double t) const\n    {\n      std::pair<double,int> ui = computeTIndex(t);\n      int bidx = ui.second - splineOrder_ + 1;\n      return coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_);\n    }\n\n    Eigen::VectorXd BSpline::localCoefficientVector(double t) const\n    {\n\n      std::pair<double,int> ui = computeTIndex(t);\n      int bidx = ui.second - splineOrder_ + 1;\n      Eigen::VectorXd c(splineOrder_ * coefficients_.rows());\n      for(int i = 0; i < splineOrder_; i++)\n\t{\n\t  c.segment(i*coefficients_.rows(), coefficients_.rows()) = coefficients_.col(i + bidx);\n\t}\n      return c;\n    }\n\nEigen::VectorXd BSpline::segmentCoefficientVector(int segmentIdx) const {\n  SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), \"segment index out of bounds\");\n  int bidx = segmentIdx;\n  Eigen::VectorXd c(splineOrder_ * coefficients_.rows());\n  for(int i = 0; i < splineOrder_; i++) {\n    c.segment(i*coefficients_.rows(), coefficients_.rows()) = coefficients_.col(i + bidx);\n  }\n  return c;\n}\n\n\n    Eigen::VectorXi BSpline::localCoefficientVectorIndices(double t) const\n    {\n      std::pair<double,int> ui = computeTIndex(t);\n      int bidx = ui.second - splineOrder_ + 1;\n      int D = coefficients_.rows();\n      return Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);\n    }\n\nEigen::VectorXi BSpline::segmentCoefficientVectorIndices(int segmentIdx) const {\n  SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), \"segment index out of bounds\");\n  int bidx = segmentIdx;\n  int D = coefficients_.rows();\n  return Eigen::VectorXi::LinSpaced(splineOrder_*D,bidx*D,(bidx + splineOrder_)*D - 1);\n}\n\n    Eigen::VectorXi BSpline::localVvCoefficientVectorIndices(double t) const\n    {\n      std::pair<double,int> ui = computeTIndex(t);\n      int bidx = ui.second - splineOrder_ + 1;\n      return Eigen::VectorXi::LinSpaced(splineOrder_,bidx,(bidx + splineOrder_) - 1);\n    }\n\nEigen::VectorXi BSpline::segmentVvCoefficientVectorIndices(int segmentIdx) const {\n  SM_ASSERT_GE_LT(std::runtime_error, segmentIdx, 0, numValidTimeSegments(), \"segment index out of bounds\");\n  int bidx = segmentIdx;\n  return Eigen::VectorXi::LinSpaced(splineOrder_,bidx,(bidx + splineOrder_) - 1);\n}\n\n    Eigen::MatrixXd BSpline::Phi(double t, int derivativeOrder) const\n    {\n      \n      SM_ASSERT_GE(Exception, derivativeOrder, 0, \"To integrate, use the integral function\");\n      std::pair<double,int> ui = computeUAndTIndex(t);\n\n  //    std::cout << \"  ui:\" << ui.first << \" \" << t << std::endl;\n\n      Eigen::VectorXd u = computeU(ui.first, ui.second, derivativeOrder);\n\n   //   std::cout << \"u:\" << std::endl;\n   //   std::cout << u << std::endl << std::endl;\n\n      int bidx = ui.second - splineOrder_ + 1;\n  \n      \n    //   std::cout << \"Spline order: \" << splineOrder_ << std::endl;\n    //  std::cout << \"t: \" << t_min() << \" <= \" << t << \" <= \" << t_max() << std::endl;\n    //  std::cout << \"bidx: \" << bidx << std::endl;\n    //   std::cout << \"number of basis matrices: \" << basisMatrices_.size() << std::endl;\n     //  std::cout << \"basis matrix:\\n\" << basisMatrices_[bidx] << std::endl;\n    //   std::cout << \"u:\\n\" << u << std::endl;\n      u = basisMatrices_[bidx].transpose() * u;\n      \n//      std::cout << \"u:\" << std::endl;\n //     std::cout << u << std::endl;\n\n\n      Eigen::MatrixXd Phi = Eigen::MatrixXd::Zero(coefficients_.rows(),splineOrder_*coefficients_.rows());\n      Eigen::MatrixXd one = Eigen::MatrixXd::Identity(Phi.rows(), Phi.rows());\n      for(int i = 0; i < splineOrder_; i++)\n\t{\n\t  Phi.block(0,Phi.rows()*i,Phi.rows(),Phi.rows()) = one * u(i);\n\t}\n\n      return Phi;\n    }\n    \n\n    void BSpline::setCoefficientVector(const Eigen::VectorXd & c)\n    {\n      SM_ASSERT_EQ(Exception,c.size(),coefficients_.rows() * coefficients_.cols(), \"The coefficient vector is the wrong size. The vector must contain all vector-valued coefficients stacked up into one column.\");\n      for(int i = 0; i < coefficients_.cols(); i++)\n\t{\n\t  coefficients_.col(i) = c.segment(i * coefficients_.rows(),coefficients_.rows());\n\t}      \n    }\n\n    Eigen::VectorXd BSpline::coefficientVector()\n    {\n      Eigen::VectorXd c(coefficients_.rows() * coefficients_.cols());\n      for(int i = 0; i < coefficients_.cols(); i++)\n\t{\n\t  c.segment(i * coefficients_.rows(),coefficients_.rows()) = coefficients_.col(i);\n\t}\n      return c;\n    }\n\n\n    void BSpline::setCoefficientMatrix(const Eigen::MatrixXd & coefficients)\n    {\n      SM_ASSERT_EQ(Exception,coefficients_.rows(), coefficients.rows(), \"The new coefficient matrix must match the size of the existing coefficient matrix\");\n      SM_ASSERT_EQ(Exception,coefficients_.cols(), coefficients.cols(), \"The new coefficient matrix must match the size of the existing coefficient matrix\");\n      coefficients_ = coefficients;\n    }\n\n\n    \n    const Eigen::MatrixXd & BSpline::basisMatrix(int i) const\n    {\n      SM_ASSERT_GE_LT(Exception,i, 0, numValidTimeSegments(), \"index out of range\");\n      return basisMatrices_[i];\n    }\n\n    \n    std::pair<double,double> BSpline::timeInterval() const\n    {\n      return std::make_pair(t_min(), t_max());\n    }\n      \n    std::pair<double,double> BSpline::timeInterval(int i) const\n    {\n      SM_ASSERT_GE(Exception, (int)knots_.size(), minimumKnotsRequired(), \"The B-spline is not well initialized\");\n      SM_ASSERT_GE_LT(Exception, i, 0, numValidTimeSegments(), \"index out of range\");\n      return std::make_pair(knots_[splineOrder_ + i - 1],knots_[splineOrder_ + i]);\n    }\n\n    void BSpline::initSpline(double t_0, double t_1, const Eigen::VectorXd & p_0, const Eigen::VectorXd & p_1)\n    {\n      SM_ASSERT_EQ(Exception,p_0.size(), p_1.size(), \"The coefficient vectors should be the same size\");\n      SM_ASSERT_GT(Exception,t_1, t_0, \"Time must be increasing from t_0 to t_1\");\n      \n      // Initialize the spline so that it interpolates the two points and moves between them with a constant velocity.\n      \n      // How many knots are required for one time segment?\n      int K = numKnotsRequired(1);\n      // How many coefficients are required for one time segment?\n      int C = numCoefficientsRequired(1);\n      // What is the vector coefficient dimension\n      int D = p_0.size();\n\n      // Initialize a uniform knot sequence\n      double dt = t_1 - t_0;\n      std::vector<double> knots(K);\n      for(int i = 0; i < K; i++)\n\t{\n\t  knots[i] = t_0 + (i - splineOrder_ + 1) * dt;\n\t}\n      // Set the knots and zero the coefficients\n      setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));\n\n\n      // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n      int coefficientDim = C * D;\n      // We always need an even number of constraints. \n      int constraintsRequired = C + (C & 0x1);\n      int constraintSize = constraintsRequired * D;\n      \n      Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);\n      \n      // Add the position constraints.\n      int brow = 0;\n      int bcol = 0;\n      A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),0);\n      b.segment(brow,D) = p_0;\n      brow += D;\n      A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),0);\n      b.segment(brow,D) = p_1;\n      brow += D;\n\n      if(splineOrder_ > 2)\n\t{\n\t  // At the very minimum we have to add velocity constraints.\n\t  Eigen::VectorXd v = (p_1 - p_0)/dt;\n\t  A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),1);\n\t  b.segment(brow,D) = v;\n\t  brow += D;\n\t  A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),1);\n\t  b.segment(brow,D) = v;\n\t  brow += D;\n\t  \n\t  if(splineOrder_ > 4)\n\t    {\n\t      // Now we add the constraint that all higher-order derivatives are zero.\n\t      int derivativeOrder = 2;\n\t      Eigen::VectorXd z = Eigen::VectorXd::Zero(D);\n\t      while(brow < A.rows())\n\t\t{\n\t\t  A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),derivativeOrder);\n\t\t  b.segment(brow,D) = z;\n\t\t  brow += D;\n\t\t  A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),derivativeOrder);\n\t\t  b.segment(brow,D) = z;\n\t\t  brow += D;\n\t\t  ++derivativeOrder;\n\t\t}\n\t    }\n\t}\n\n      // Now we solve the Ax=b system\n      if(A.rows() != A.cols())\n\t{\n\t  // The system is over constrained. This happens for odd ordered splines.\n\t  b = (A.transpose() * b).eval();\n\t  A = (A.transpose() * A).eval();\n\t}\n      \n      // Solve for the coefficient vector.\n      Eigen::VectorXd c = A.householderQr().solve(b);\n      // ldlt doesn't work for this problem. It may be because the ldlt decomposition\n      // requires the matrix to be positive or negative semidefinite\n      // http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing\n      // which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.\n      //Eigen::VectorXd c = A.ldlt().solve(b);\n      setCoefficientVector(c);\n    }\n\n    void BSpline::addCurveSegment(double t, const Eigen::VectorXd & p_1)\n    {\n      SM_ASSERT_GT(Exception, t, t_max(), \"The new time must be past the end of the last valid segment\");\n      SM_ASSERT_EQ(Exception, p_1.size(), coefficients_.rows(), \"Invalid coefficient vector size\");\n      \n      // Get the final valid time interval.\n      int NT = numValidTimeSegments();\n      std::pair<double, double> interval_km1 = timeInterval(NT-1);\n\n      Eigen::VectorXd p_0;\n      \n      // Store the position of the spline at the  end of the interval.\n      // We will use these as constraints as we don't want them to change.\n      p_0 = eval(interval_km1.second);\n      \n      // Retool the knot vector.\n      double du;\n      int km1;\n      boost::tie(du,km1) = computeTIndex(interval_km1.first);\n      \n      // leave knots km1 and k alone but retool the other knots.\n      double dt = t - knots_[km1 + 1];\n      double kt = t;\n      \n      // add another knot.\n      std::vector<double> knots(knots_);\n      knots.push_back(0.0);\n      // space the further knots uniformly.\n      for(unsigned k = km1 + 2; k < knots.size(); k++)\n\t{\n\t  knots[k] = kt;\n\t  kt += dt;\n\t}\n      // Tack on an new, uninitialized coefficient column.\n      Eigen::MatrixXd c(coefficients_.rows(), coefficients_.cols() + 1);\n      c.topLeftCorner(coefficients_.rows(), coefficients_.cols()) = coefficients_;\n      setKnotsAndCoefficients(knots,c);\n      \n      // Now, regardless of the order of the spline, we should only have to add a single knot and coefficient vector.\n      // In this case, we should solve for the last two coefficient vectors (i.e., the new one and the one before the\n      // new one).\n      \n      // Get the time interval of the new time segment.\n      double t_0, t_1;\n      boost::tie(t_0,t_1) = timeInterval(NT);\n\n      // what is the coefficient dimension?\n      int D = coefficients_.rows();\n      // How many vector-valued coefficients are required? In this case, 2. We will leave the others fixed.\n      int C = 2;\n      // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n      int coefficientDim = C * D;\n      // We always need an even number of constraints. \n      int constraintsRequired = 2;\n      int constraintSize = constraintsRequired * D;\n      \n      Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);      // Build the A matrix.\n\n      int phiBlockColumnOffset = D * std::max(0,(splineOrder_ - 2));\n      Eigen::VectorXd fixedCoefficients = localCoefficientVector(t_0).segment(0,phiBlockColumnOffset);\n\n      // Add the position constraints.\n      int brow = 0;\n      int bcol = 0;\n      Eigen::MatrixXd P;\n      P = Phi(t_0,0);\n      A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = p_0 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;\n      brow += D;\n\n      P = Phi(t_1,0);\n      A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = p_1 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;;\n      brow += D;\n\n      // Add regularization constraints (keep the coefficients small)\n      //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-4 * Eigen::MatrixXd::Identity(coefficientDim, coefficientDim);\n      //b.segment(brow,coefficientDim) = Eigen::VectorXd::Zero(coefficientDim);\n      //brow += coefficientDim;\n\n\n      // Now we solve the Ax=b system\n      if(A.rows() != A.cols())\n\t{\n\t  // The system is over constrained. This happens for odd ordered splines.\n\t  b = (A.transpose() * b).eval();\n\t  A = (A.transpose() * A).eval();\n\t}\n\n      \n      Eigen::VectorXd cstar = A.householderQr().solve(b);\n      coefficients_.col(coefficients_.cols() - 2) = cstar.head(D);\n      coefficients_.col(coefficients_.cols() - 1) = cstar.tail(D);\n\n    }\n\n    \n    void BSpline::removeCurveSegment()\n    {\n      if(knots_.size() > 0 && coefficients_.cols() > 0)\n\t{\n\t  knots_.erase(knots_.begin());\n\t  coefficients_ = coefficients_.block(0,1,coefficients_.rows(),coefficients_.cols() - 1).eval();\n\t}\n    }\n\n    void BSpline::setLocalCoefficientVector(double t, const Eigen::VectorXd & c)\n    {\n      SM_ASSERT_EQ(Exception, c.size(), splineOrder_ * coefficients_.rows(), \"The local coefficient vector is the wrong size\");\n      std::pair<double,int> ui = computeTIndex(t);\n      int bidx = ui.second - splineOrder_ + 1;\n      for(int i = 0; i < splineOrder_; i++)\n\t{\n\t  coefficients_.col(i + bidx) = c.segment(i*coefficients_.rows(), coefficients_.rows());\n\t}\n\n    }\n\n\n    void BSpline::initSpline2(const Eigen::VectorXd & times, const Eigen::MatrixXd & interpolationPoints, int numSegments, double lambda)\n    {\n      SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), \"The number of times and the number of interpolation points must be equal\");\n      SM_ASSERT_GE(Exception,times.size(),2, \"There must be at least two times\");\n      SM_ASSERT_GE(Exception,numSegments,1, \"There must be at least one time segment\");\n      for(int i = 1; i < times.size(); i++)\n\t{\n\t  SM_ASSERT_LE(Exception, times[i-1], times[i],\n\t\t\t \"The time sequence must be nondecreasing. time \" << i\n\t\t\t << \" was not greater than or equal to time \" << (i-1));\n\t}\n      \n      \n      // Initialize the spline so that it interpolates the N points\n\n      // How many knots are required for one time segment?\n      int K = numKnotsRequired(numSegments);\n      // How many coefficients are required for one time segment?\n      int C = numCoefficientsRequired(numSegments);\n      // What is the vector coefficient dimension\n      int D = interpolationPoints.rows();\n\n      // Initialize a uniform knot sequence\n      double dt = (times[times.size() - 1] - times[0]) / numSegments;\n      std::vector<double> knots(K);\n      for(int i = 0; i < K; i++)\n\t{\n\t  knots[i] = times[0] + (i - splineOrder_ + 1) * dt;\n\t}\n      // Set the knots and zero the coefficients\n      setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));\n\n\n      // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n      int coefficientDim = C * D;\n      \n      int numConstraints = (knots.size() - 2 * splineOrder_ + 2) + interpolationPoints.cols();\n      int constraintSize = numConstraints * D;\n      \n      Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);\n\n      int brow = 0;\n      //int bcol = 0;\n      // Now add the regularization constraint.\n      //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-1* Eigen::MatrixXd::Identity(coefficientDim, coefficientDim);\n      //b.segment(brow,coefficientDim) = Eigen::VectorXd::Zero(coefficientDim);\n      //brow += coefficientDim;\n      for(int i = splineOrder_ - 1; i < (int)knots.size() - splineOrder_ + 1; i++)\n\t{\n\t  Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(knots[i]);\n\t  \n\t  A.block(brow,coeffIndices[0],D,coeffIndices.size()) = lambda * Phi(knots[i],2);\n\t  b.segment(brow,D) = Eigen::VectorXd::Zero(D);\n\t  brow += D;\n\t}\n\n      // Add the position constraints.\n      for(int i = 0; i < interpolationPoints.cols(); i++)\n\t{\n\t  Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n\t  A.block(brow,coeffIndices[0],D,coeffIndices.size()) = Phi(times[i],0);\n\t  \n\t  b.segment(brow,D) = interpolationPoints.col(i);\n\t  brow += D;\n\t}\n\n      // Now we solve the Ax=b system\n      //if(A.rows() != A.cols())\n      //\t{\n\t  // The system is over constrained. This happens for odd ordered splines.\n\t  b = (A.transpose() * b).eval();\n\t  A = (A.transpose() * A).eval();\n\t  //\t}\n      \n      // Solve for the coefficient vector.\n      Eigen::VectorXd c = A.ldlt().solve(b);\n      // ldlt doesn't work for this problem. It may be because the ldlt decomposition\n      // requires the matrix to be positive or negative semidefinite\n      // http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing\n      // which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.\n      // Eigen::VectorXd c = A.ldlt().solve(b);\n      setCoefficientVector(c);\n    }\n\n    \n    void BSpline::initSplineSparseKnots(const Eigen::VectorXd &times, const Eigen::MatrixXd &interpolationPoints, const Eigen::VectorXd knots, double lambda)\n    {\n        \n    \tSM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), \"The number of times and the number of interpolation points must be equal\");\n    \tSM_ASSERT_GE(Exception,times.size(),2, \"There must be at least two times\");\n    \tfor(int i = 1; i < times.size(); i++)\n    \t{\n    \t\tSM_ASSERT_LE(Exception, times[i-1], times[i],\n                         \"The time sequence must be nondecreasing. time \" << i\n                         << \" was not greater than or equal to time \" << (i-1));\n    \t}\n        \n    \tint K = knots.size();\n    \t// How many coefficients are required for one time segment?\n    \tint C = numCoefficientsRequired(knots.size() - 2*(splineOrder_ - 1)-1);\n    \t// What is the vector coefficient dimension\n    \tint D = interpolationPoints.rows();\n        \n    \t// Set the knots and zero the coefficients\n    \tstd::vector<double> knotsVector(K);\n    \tfor(int i = 0; i < K; i++)\n    \t{\n    \t\tknotsVector[i] = knots(i);\n    \t}\n    \tsetKnotsAndCoefficients(knotsVector, Eigen::MatrixXd::Zero(D,C));\n        \n    \t// define the structure:\n    \tstd::vector<int> rows;\n    \tstd::vector<int> cols;\n        \n    \tfor (int i = 1; i <= interpolationPoints.cols(); i++)\n    \t\trows.push_back(i*D);\n    \tfor(int i = 1; i <= C; i++)\n    \t\tcols.push_back(i*D);\n        \n    \tstd::vector<int> bcols(1);\n    \tbcols[0] = 1;\n        \n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> A(rows,cols, true);\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> b(rows,bcols, true);\n        \n    \tint brow = 0;\n    \t// try to fill the matrix:\n    \tfor(int i = 0; i < interpolationPoints.cols(); i++) {\n    \t\tEigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n            \n    \t\tconst bool allocateBlock = true;\n            \n    \t\t// get Phi\n    \t\tEigen::MatrixXd P = Phi(times[i],0); // Dx(n*D)\n            \n    \t\t// the n'th order spline needs n column blocks (n*D columns)\n    \t\tfor(int j = 0; j < splineOrder_; j++) {\n    \t\t\tEigen::MatrixXd & Ai = *A.block(brow/D,coeffIndices[0]/D+j,allocateBlock );\n    \t\t\tAi= P.block(0,j*D,D,D);\n    \t\t}\n            \n    \t\tEigen::MatrixXd & bi = *b.block(brow/D,0,allocateBlock );\n    \t\tbi = interpolationPoints.col(i);\n            \n    \t\tbrow += D;\n    \t}\n        \n    \t//Eigen::MatrixXd Ad = A.toDense();\n        \n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> At(cols,rows, true);\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Atp = &At;\n    \tA.transpose(Atp);\n        \n    \t// A'b\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Ab(cols,bcols, true);\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Abp = &Ab;\n    \tAtp->multiply(Abp, &b);\n        \n    \t// A'A\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> AtA(cols,cols, true);\n    \tsparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * AtAp = &AtA;\n    \tAtp->multiply(AtAp, &A);\n        \n    \t// Add the motion constraint.\n    \tEigen::VectorXd W = Eigen::VectorXd::Constant(D,lambda);\n        \n        // make this conditional on the order of the spline:\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q(cols,cols,true);\n        if (splineOrder_ == 2)\n            curveQuadraticIntegralDiagSparse(W, 1).cloneInto(Q);\n        else\n            curveQuadraticIntegralDiagSparse(W, 2).cloneInto(Q);\n\n        \n    \t// A'A + Q\n    \tQ.add(AtAp);\n        \n    \t// solve:\n    \tsparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> solver;\n    \tsolver.init();\n        \n    \tEigen::VectorXd c(AtAp->rows());\n    \tc.setZero();\n    \tEigen::VectorXd b_dense = Abp->toDense();\n        \n    \tbool result = solver.solve(*AtAp,&c[0],&b_dense[0]);\n    \tif(!result) {\n    \t\tc.setZero();\n    \t\t// fallback => use nonsparse solver:\n    \t\tstd::cout << \"Fallback to Dense Solver\" << std::endl;\n    \t\tEigen::MatrixXd Adense = AtAp->toDense();\n    \t\tc = Adense.ldlt().solve(b_dense);\n    \t}\n        \n    \t//      std::cout << \"b\\nA=\" << A << \"\\n b=\" << b << \"\\n\";\n        \n    \t// Solve for the coefficient vector.\n    \t//   Eigen::VectorXd c = A.ldlt().solve(b);\n    \tsetCoefficientVector(c);\n    }\n    \n\n    void BSpline::initSplineSparse(const Eigen::VectorXd & times, const Eigen::MatrixXd & interpolationPoints, int numSegments, double lambda)\n    {\n        SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), \"The number of times and the number of interpolation points must be equal\");\n        SM_ASSERT_GE(Exception,times.size(),2, \"There must be at least two times\");\n        SM_ASSERT_GE(Exception,numSegments,1, \"There must be at least one time segment\");\n        for(int i = 1; i < times.size(); i++)\n        {\n            SM_ASSERT_LE(Exception, times[i-1], times[i],\n                         \"The time sequence must be nondecreasing. time \" << i\n                         << \" was not greater than or equal to time \" << (i-1));\n        }\n\n        \n        // How many knots are required for one time segment?\n        int K = numKnotsRequired(numSegments);\n        // How many coefficients are required for one time segment?\n        int C = numCoefficientsRequired(numSegments);\n        // What is the vector coefficient dimension\n        int D = interpolationPoints.rows();\n        \n        // Initialize a uniform knot sequence\n        double dt = (times[times.size() - 1] - times[0]) / numSegments;\n        std::vector<double> knots(K);\n        for(int i = 0; i < K; i++)\n        {\n            knots[i] = times[0] + (i - splineOrder_ + 1) * dt;\n        }\n        // Set the knots and zero the coefficients\n        setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));\n        \n        // define the structure:\n        std::vector<int> rows;\n        std::vector<int> cols;\n        \n        for (int i = 1; i <= interpolationPoints.cols(); i++)\n            rows.push_back(i*D);\n        for(int i = 1; i <= C; i++)\n            cols.push_back(i*D);\n \n        \n        std::vector<int> bcols(1);\n        bcols[0] = 1;\n        \n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> A(rows,cols, true);\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> b(rows,bcols, true);\n        \n        int brow = 0;\n        // try to fill the matrix:\n        for(int i = 0; i < interpolationPoints.cols(); i++) {\n            Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n\n            const bool allocateBlock = true;\n            \n            // get Phi\n            Eigen::MatrixXd P = Phi(times[i],0); // Dx(n*D)\n\n            // the n'th order spline needs n column blocks (n*D columns)\n            for(int j = 0; j < splineOrder_; j++) {\n                Eigen::MatrixXd & Ai = *A.block(brow/D,coeffIndices[0]/D+j,allocateBlock );\n                Ai= P.block(0,j*D,D,D);\n            }\n            \n            Eigen::MatrixXd & bi = *b.block(brow/D,0,allocateBlock );\n            bi = interpolationPoints.col(i);\n            \n            brow += D;\n        }\n\n        //Eigen::MatrixXd Ad = A.toDense();\n\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> At(cols,rows, true);\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Atp = &At;\n        A.transpose(Atp);\n        \n        // A'b\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Ab(cols,bcols, true);\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * Abp = &Ab;\n        Atp->multiply(Abp, &b);\n        \n        // A'A\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> AtA(cols,cols, true);\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> * AtAp = &AtA;\n        Atp->multiply(AtAp, &A);\n\n        // Add the motion constraint.\n        Eigen::VectorXd W = Eigen::VectorXd::Constant(D,lambda);\n        \n        // make this conditional on the order of the spline:\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q(cols,cols,true);\n        if (splineOrder_ == 2)\n            curveQuadraticIntegralDiagSparse(W, 1).cloneInto(Q);\n        else\n            curveQuadraticIntegralDiagSparse(W, 2).cloneInto(Q);\n  \n        // A'A + Q\n        Q.add(AtAp);\n        \n        // solve:\n        sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd> solver;\n        solver.init();\n        \n        Eigen::VectorXd c(AtAp->rows());\n        c.setZero();\n        Eigen::VectorXd b_dense = Abp->toDense();\n\n        bool result = solver.solve(*AtAp,&c[0],&b_dense[0]);\n        if(!result) {\n            c.setZero();\n            // fallback => use nonsparse solver:\n            std::cout << \"Fallback to Dense Solver\" << std::endl;\n            Eigen::MatrixXd Adense = AtAp->toDense();\n            c = Adense.ldlt().solve(b_dense);\n        }\n\n        //      std::cout << \"b\\nA=\" << A << \"\\n b=\" << b << \"\\n\";\n        \n        // Solve for the coefficient vector.\n     //   Eigen::VectorXd c = A.ldlt().solve(b);\n        setCoefficientVector(c);         \n\n    }\n    \n    \n    \n    void BSpline::initSpline3(const Eigen::VectorXd & times, const Eigen::MatrixXd & interpolationPoints, int numSegments, double lambda)\n    {\n      SM_ASSERT_EQ(Exception,times.size(), interpolationPoints.cols(), \"The number of times and the number of interpolation points must be equal\");\n      SM_ASSERT_GE(Exception,times.size(),2, \"There must be at least two times\");\n      SM_ASSERT_GE(Exception,numSegments,1, \"There must be at least one time segment\");\n      for(int i = 1; i < times.size(); i++)\n\t{\n\t  SM_ASSERT_LE(Exception, times[i-1], times[i],\n\t\t\t \"The time sequence must be nondecreasing. time \" << i\n\t\t\t << \" was not greater than or equal to time \" << (i-1));\n\t}\n\n      // How many knots are required for one time segment?\n      int K = numKnotsRequired(numSegments);\n      // How many coefficients are required for one time segment?\n      int C = numCoefficientsRequired(numSegments);\n      // What is the vector coefficient dimension\n      int D = interpolationPoints.rows();\n\n      // Initialize a uniform knot sequence\n      double dt = (times[times.size() - 1] - times[0]) / numSegments;\n      std::vector<double> knots(K);\n      for(int i = 0; i < K; i++)\n\t{\n\t  knots[i] = times[0] + (i - splineOrder_ + 1) * dt;\n\t}\n      // Set the knots and zero the coefficients\n      setKnotsAndCoefficients(knots, Eigen::MatrixXd::Zero(D,C));\n\n\n      // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n      int coefficientDim = C * D;\n      \n      int numConstraints = interpolationPoints.cols();\n      int constraintSize = numConstraints * D;\n      \n      Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);\n        \n   //     std::cout << A.rows() << \":\" << A.cols() << std::endl;\n        \n\n      int brow = 0;\n      // Add the position constraints.\n      for(int i = 0; i < interpolationPoints.cols(); i++)\n\t{\n\t  Eigen::VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n\n    //    std::cout << brow << \":\" << coeffIndices[0] << std::endl;\n        \n\t  A.block(brow,coeffIndices[0],D,coeffIndices.size()) = Phi(times[i],0);\n\n\t  b.segment(brow,D) = interpolationPoints.col(i);\n\t  brow += D;\n\t}\n\n\n   //   std::cout << b << std::endl;\n\n      b = (A.transpose() * b).eval();\n      A = (A.transpose() * A).eval();\n\n      // Add the motion constraint.\n      Eigen::VectorXd W = Eigen::VectorXd::Constant(D,lambda);\n    \n      // make this conditional on the order of the spline:\n      if (splineOrder_ == 2)\n          A += curveQuadraticIntegralDiag(W, 1);\n      else\n          A += curveQuadraticIntegralDiag(W, 2);\n        \n      Eigen::VectorXd c = A.ldlt().solve(b);\n      setCoefficientVector(c);\n\n    }\n\n\n    void BSpline::addCurveSegment2(double t, const Eigen::VectorXd & p_1, double lambda)\n    {\n      SM_ASSERT_GT(Exception, t, t_max(), \"The new time must be past the end of the last valid segment\");\n      SM_ASSERT_EQ(Exception, p_1.size(), coefficients_.rows(), \"Invalid coefficient vector size\");\n      \n      // Get the final valid time interval.\n      int NT = numValidTimeSegments();\n      std::pair<double, double> interval_km1 = timeInterval(NT-1);\n\n      Eigen::VectorXd p_0;\n      \n      // Store the position of the spline at the  end of the interval.\n      // We will use these as constraints as we don't want them to change.\n      p_0 = eval(interval_km1.second);\n      \n      // Retool the knot vector.\n      double du;\n      int km1;\n      boost::tie(du,km1) = computeTIndex(interval_km1.first);\n      \n      // leave knots km1 and k alone but retool the other knots.\n      double dt = t - knots_[km1 + 1];\n      double kt = t;\n      \n      // add another knot.\n      std::vector<double> knots(knots_);\n      knots.push_back(0.0);\n      // space the further knots uniformly.\n      for(unsigned k = km1 + 2; k < knots.size(); k++)\n\t{\n\t  knots[k] = kt;\n\t  kt += dt;\n\t}\n      // Tack on an new, uninitialized coefficient column.\n      Eigen::MatrixXd c(coefficients_.rows(), coefficients_.cols() + 1);\n      c.topLeftCorner(coefficients_.rows(), coefficients_.cols()) = coefficients_;\n      setKnotsAndCoefficients(knots,c);\n      \n      // Now, regardless of the order of the spline, we should only have to add a single knot and coefficient vector.\n      // In this case, we should solve for the last two coefficient vectors (i.e., the new one and the one before the\n      // new one).\n      \n      // Get the time interval of the new time segment.\n      double t_0, t_1;\n      boost::tie(t_0,t_1) = timeInterval(NT);\n\n      // what is the coefficient dimension?\n      int D = coefficients_.rows();\n      // How many vector-valued coefficients are required? In this case, 2. We will leave the others fixed.\n      int C = 2;\n      // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n      int coefficientDim = C * D;\n      // We always need an even number of constraints. \n      int constraintsRequired = 2 + 2;\n      int constraintSize = constraintsRequired * D;\n      \n      Eigen::MatrixXd A = Eigen::MatrixXd::Zero(constraintSize, coefficientDim);\n      Eigen::VectorXd b = Eigen::VectorXd::Zero(constraintSize);      // Build the A matrix.\n\n      int phiBlockColumnOffset = D * std::max(0,(splineOrder_ - 2));\n      Eigen::VectorXd fixedCoefficients = localCoefficientVector(t_0).segment(0,phiBlockColumnOffset);\n\n      // Add the position constraints.\n      int brow = 0;\n      int bcol = 0;\n      Eigen::MatrixXd P;\n      P = Phi(t_0,0);\n      A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = p_0 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;\n      brow += D;\n\n      P = Phi(t_1,0);\n      A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = p_1 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;;\n      brow += D;\n\n\n      // Add regularization constraints (keep the acceleration small)\n      P = Phi(t_0,2);\n      A.block(brow,bcol,D,coefficientDim) = lambda * P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = Eigen::VectorXd::Zero(D);\n      brow += D;\n\n      P = Phi(t_1,2);\n      A.block(brow,bcol,D,coefficientDim) = lambda * P.block(0,phiBlockColumnOffset, D, coefficientDim);\n      b.segment(brow,D) = Eigen::VectorXd::Zero(D);\n      brow += D;\n\n      //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-4 * Eigen::MatrixXd::Identity(coefficientDim, coefficientDim);\n      //b.segment(brow,coefficientDim) = Eigen::VectorXd::Zero(coefficientDim);\n      //brow += coefficientDim;\n\n\n      // Now we solve the Ax=b system\n      if(A.rows() != A.cols())\n\t{\n\t  // The system is over constrained. This happens for odd ordered splines.\n\t  b = (A.transpose() * b).eval();\n\t  A = (A.transpose() * A).eval();\n\t}\n\n      \n      Eigen::VectorXd cstar = A.householderQr().solve(b);\n      coefficients_.col(coefficients_.cols() - 2) = cstar.head(D);\n      coefficients_.col(coefficients_.cols() - 1) = cstar.tail(D);\n\n    }\n\n\n    Eigen::MatrixXd BSpline::Vi(int segmentIndex) const\n    {\n      SM_ASSERT_GE_LT(Exception, segmentIndex, 0, numValidTimeSegments(), \"Segment index out of bounds\"); \n      \n      Eigen::VectorXd vals(splineOrder_*2);\n      for (int i = 0; i < vals.size(); ++i)\n\t{\n\t  vals[i] = 1.0/(i + 1.0);\n\t}\n      \n      Eigen::MatrixXd V(splineOrder_,splineOrder_);\n      for(int r = 0; r < V.rows(); r++)\n\t{\n\t  for(int c = 0; c < V.cols(); c++)\n\t    {\n\t      V(r,c) = vals[r + c];\n\t    }\n\t}\n\n      double t_0,t_1;\n      boost::tie(t_0,t_1) = timeInterval(segmentIndex);\n\n      V *= t_1 - t_0;\n\n\n      return V;\n    }\n\n    Eigen::VectorXd BSpline::evalIntegral(double t1, double t2) const\n    {\n      if(t1 > t2)\n\t{\n\t  return -evalIntegral(t2,t1);\n\t}\n\n      std::pair<double,int> u1 = computeTIndex(t1);\n      std::pair<double,int> u2 = computeTIndex(t2);\n      \n      Eigen::VectorXd integral = Eigen::VectorXd::Zero(coefficients_.rows());\n\n      // LHS remainder.\n      double lhs_remainder = t1 - knots_[u1.second];\n      if(lhs_remainder > 1e-16 && u1.first > 1e-16)\n\t{\n\t  lhs_remainder /= u1.first;\n\t  Eigen::VectorXd v(splineOrder_);\n\t  double du = lhs_remainder;\n\t  for(int i = 0; i < splineOrder_; i++)\n\t    {\n\t      v(i) = du/(i + 1.0);\n\t      du *= lhs_remainder;\n\t    }\n\n\t  int bidx = basisMatrixIndexFromStartingKnotIndex(u1.second);\n\t  integral -= u1.first * coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * basisMatrices_[bidx].transpose() * v;\n\t}\n\n      // central time segments.\n      Eigen::VectorXd v = Eigen::VectorXd::Zero(splineOrder_);\n      for(int i = 0; i < splineOrder_; i++)\n\t{\n\t  v(i) = 1.0/(i + 1.0);\n\t}\n\n      for(int s = u1.second; s < u2.second; s++)\n\t{\n\t  int bidx = basisMatrixIndexFromStartingKnotIndex(s);\n\t  integral += (knots_[s+1] - knots_[s]) * coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * basisMatrices_[bidx].transpose() * v;\n\t}\n\n      // RHS remainder.\n      double rhs_remainder = t2 - knots_[u2.second];\n      if(rhs_remainder > 1e-16 && u2.first > 1e-16)\n\t{\n\t  rhs_remainder /= u2.first;\n\t  \n\t  Eigen::VectorXd v(splineOrder_);\n\t  double du = rhs_remainder;\n\t  for(int i = 0; i < splineOrder_; i++)\n\t    {\n\t      v(i) = du / (i + 1.0);\n\t      du *= rhs_remainder;\n\t    }\n\n\t  int bidx = basisMatrixIndexFromStartingKnotIndex(u2.second);\n\t  integral += u2.first * coefficients_.block(0,bidx,coefficients_.rows(),splineOrder_) * basisMatrices_[bidx].transpose() * v;\n\t}\n      \n\n      return integral;\n    }\n\n    int BSpline::basisMatrixIndexFromStartingKnotIndex(int startingKnotIndex) const\n    {\n      return startingKnotIndex - splineOrder_ + 1;\n    }\n    int BSpline::startingKnotIndexFromBasisMatrixIndex(int basisMatrixIndex) const\n    {\n      return splineOrder_ + basisMatrixIndex - 1;\n    }\n\n\n    Eigen::MatrixXd BSpline::Bij(int segmentIndex, int columnIndex) const\n    {\n      SM_ASSERT_GE_LT(Exception, segmentIndex, 0, (int)basisMatrices_.size(), \"Out of range\");\n      SM_ASSERT_GE_LT(Exception, columnIndex, 0, splineOrder_, \"Out of range\");\n      int D = coefficients_.rows();\n      Eigen::MatrixXd B = Eigen::MatrixXd::Zero(splineOrder_*D,D);\n      for(int i = 0; i < D; i++)\n\t{\n\t  B.block(i*splineOrder_,i,splineOrder_,1) = basisMatrices_[segmentIndex].col(columnIndex);\n\t}\n      return B;\n    }\n\n    Eigen::MatrixXd BSpline::Mi(int segmentIndex) const\n    {\n      SM_ASSERT_GE_LT(Exception, segmentIndex, 0, (int)basisMatrices_.size(), \"Out of range\");\n      int D = coefficients_.rows();      \n      Eigen::MatrixXd M = Eigen::MatrixXd::Zero(splineOrder_*D,splineOrder_*D);\n      \n      for(int j = 0; j < splineOrder_; j++)\n\t{\n\t  M.block(0,j*D,D*splineOrder_, D) = Bij(segmentIndex,j);\n\t}\n      \n      return M;\n    }\n\n\tEigen::VectorXd BSpline::getLocalBiVector(double t) const\n\t{\n\t\tEigen::VectorXd ret = Eigen::VectorXd::Zero(splineOrder_);\n\t\tgetLocalBiInto(t, ret);\n\t\treturn ret;\n\t}\n\n\tvoid BSpline::getLocalBiInto(double t, Eigen::VectorXd & ret) const\n\t{\n\t\tint si = segmentIndex(t);\n\t\tEigen::VectorXd lu = u(t,0);\n\t\tfor(int j = 0; j < splineOrder_; j++)\n\t\t{\n\t\t\tret[j] = lu.dot(basisMatrices_[si].col(j));\n\t\t}\n\t}\n\n\n    Eigen::VectorXd BSpline::getLocalCumulativeBiVector(double t) const\n    {\n\t    Eigen::VectorXd bi = getLocalBiVector(t);\n\t    int maxIndex = bi.rows() - 1;\n\t    // tildeB(i) = np.sum(bi[i+1:]) :\n\t    for(int i = 1; i <= maxIndex; i ++){\n\t\t    double sum = 0;\n\t\t    for(int j = maxIndex; j > i; j--)\n\t\t\t    sum += bi[j];\n\t\t    bi[i] += sum;\n\t    }\n\t    bi[0] = 1; // the sum of k successive spline basis functions is always 1\n\t    return bi;\n    }\n\n\n\n    int BSpline::segmentIndex(double t) const\n    {\n      std::pair<double,int> ui = computeTIndex(t);\n      return basisMatrixIndexFromStartingKnotIndex(ui.second);\n    }\n\n    Eigen::MatrixXd BSpline::U(double t, int derivativeOrder) const\n    {\n      Eigen::VectorXd uvec = u(t,derivativeOrder);\n      int D = coefficients_.rows();\n      Eigen::MatrixXd Umat = Eigen::MatrixXd::Zero(splineOrder_ * D, D);\n\n      for(int i = 0; i < D; i++)\n\t{\n\t  Umat.block(i*splineOrder_,i,splineOrder_,1) = uvec;\n\t}    \n\n      return Umat;\n    }\n\n    Eigen::VectorXd BSpline::u(double t, int derivativeOrder) const\n    {\n\n      std::pair<double,int> ui = computeUAndTIndex(t);\n      return computeU(ui.first, ui.second, derivativeOrder);\n      \n    }\n\n    Eigen::MatrixXd BSpline::Di(int segmentIndex) const\n    {\n      int D = coefficients_.rows();\n      Eigen::MatrixXd fullD = Eigen::MatrixXd::Zero(splineOrder_*D, splineOrder_*D);\n    \n      Eigen::MatrixXd subD = Dii(segmentIndex);\n\n      for(int d = 0; d < D; d++)\n\t{\n\t  fullD.block(d*splineOrder_,d*splineOrder_,splineOrder_,splineOrder_) = subD;\n\t}\n\n      return fullD;\n    }\n\n    Eigen::MatrixXd BSpline::Dii(int segmentIndex) const\n    {\n      SM_ASSERT_GE_LT(Exception, segmentIndex, 0, (int)basisMatrices_.size(), \"Out of range\");\n      double t_0,t_1;\n      boost::tie(t_0,t_1) = timeInterval(segmentIndex);\n      double dt = t_1 - t_0;\n      \n      double recip_dt = 0.0;\n      if(dt > 0)\n\trecip_dt = 1.0/dt;\n      Eigen::MatrixXd D = Eigen::MatrixXd::Zero(splineOrder_,splineOrder_);\n      for(int i = 0; i < splineOrder_ - 1; i++)\n\t{\n\t  D(i,i+1) = (i+1.0) * recip_dt;\n\t}\n\n      return D;\n    }\n\nEigen::MatrixXd BSpline::segmentIntegral(int segmentIdx, const Eigen::MatrixXd & W, int derivativeOrder) const {\n  // Let's do this quick and dirty.\n\n  auto svd = segmentQuadraticIntegral(W, segmentIdx, derivativeOrder).jacobiSvd(Eigen::ComputeFullU);\n  return (svd.matrixU() * svd.singularValues().array().sqrt().matrix().asDiagonal()).transpose();\n}\n\n\n\n\n    Eigen::MatrixXd BSpline::segmentQuadraticIntegral(const Eigen::MatrixXd & W, int segmentIdx, int derivativeOrder) const\n    {\n      int D = coefficients_.rows();\n      SM_ASSERT_GE_LT(Exception, segmentIdx, 0, (int)basisMatrices_.size(), \"Out of range\");\n      SM_ASSERT_EQ(Exception,W.rows(), D, \"W must be a square matrix the size of a single vector-valued coefficient\");\n      SM_ASSERT_EQ(Exception,W.cols(), D, \"W must be a square matrix the size of a single vector-valued coefficient\");\n\n      int N = D * splineOrder_;\n      Eigen::MatrixXd Q;// = Eigen::MatrixXd::Zero(N,N);\n      Eigen::MatrixXd Dm = Dii(segmentIdx);\n      Eigen::MatrixXd V = Vi(segmentIdx);\n      Eigen::MatrixXd M = Mi(segmentIdx);\n      \n      // Calculate the appropriate derivative version of V\n      // using the matrix multiplication version of the derivative.\n      for(int i = 0; i < derivativeOrder; i++)\n\t{\n\t  V = (Dm.transpose() * V * Dm).eval();\n\t}\n\n      Eigen::MatrixXd WV = Eigen::MatrixXd::Zero(N,N);\n      \n      for(int r = 0; r < D; r++)\n\t{\n\tfor(int c = 0; c < D; c++)\n\t  {\n\t    SM_ASSERT_NEAR(Exception, W(r,c),W(c,r),1e-14,\"W must be symmetric\");\n\t    //std::cout << \"Size WV: \" << WV.rows() << \", \" << WV.cols() << std::endl;\n\t    //std::cout << \"Size V: \" << V.rows() << \", \" << V.cols() << std::endl;\n\t    WV.block(splineOrder_*r, splineOrder_*c,splineOrder_,splineOrder_) = W(r,c) * V;\n\t  }\n\t}\n      \n      Q = M.transpose() * WV * M;\n\n      return Q;\n    }\n\n    Eigen::MatrixXd BSpline::segmentQuadraticIntegralDiag(const Eigen::VectorXd & Wdiag, int segmentIdx, int derivativeOrder) const\n    {\n      int D = coefficients_.rows();\n      SM_ASSERT_GE_LT(Exception, segmentIdx, 0, (int)basisMatrices_.size(), \"Out of range\");\n      SM_ASSERT_EQ(Exception,Wdiag.size(), D, \"Wdiag must be the length of a single vector-valued coefficient\");\n\n      int N = D * splineOrder_;\n      Eigen::MatrixXd Q;// = Eigen::MatrixXd::Zero(N,N);\n      Eigen::MatrixXd Dm = Dii(segmentIdx);\n      Eigen::MatrixXd V = Vi(segmentIdx);\n      Eigen::MatrixXd M = Mi(segmentIdx);\n      \n      // Calculate the appropriate derivative version of V\n      // using the matrix multiplication version of the derivative.\n      for(int i = 0; i < derivativeOrder; i++)\n\t{\n\t  V = (Dm.transpose() * V * Dm).eval();\n\t}\n\n      Eigen::MatrixXd WV = Eigen::MatrixXd::Zero(N,N);\n      \n      for(int d = 0; d < D; d++)\n\t{\n\t  //std::cout << \"Size WV: \" << WV.rows() << \", \" << WV.cols() << std::endl;\n\t  //std::cout << \"Size V: \" << V.rows() << \", \" << V.cols() << std::endl;\n\t  WV.block(splineOrder_*d, splineOrder_*d,splineOrder_,splineOrder_) = Wdiag(d) * V;\n\t}\n      \n      Q = M.transpose() * WV * M;\n\n      return Q;\n    }\n   \n    \n    // sparse curveQuaddraticIntegral:\n    sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> BSpline::curveQuadraticIntegralSparse(const  Eigen::MatrixXd & W, int derivativeOrder) const \n    {\n\n        // define rows / cols:\n        // blocksize:\n        int D = coefficients_.rows();\n        int blocksInBlock = splineOrder_;\n        int blocks = numVvCoefficients();\n        int matrixSize = blocks * D;\n        \n        std::vector<int> rows;\n        std::vector<int> cols;\n\n        int i;       \n        \n        for(i = D; i <= matrixSize; i+=D) {\n            rows.push_back(i);\n            cols.push_back(i);            \n        }              \n        \n        // create matrix:\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q_sparse(rows,cols,true);\n        // place\n        for(int s = 0; s < numValidTimeSegments(); ++s)\n        {\n            Eigen::MatrixXd Q = segmentQuadraticIntegral(W, s, derivativeOrder);\n            // place the DxD blocks in the blocksInBlock x blocksInBlock blocks:\n            for(int i = 0; i < blocksInBlock; i++) {\n                for(int j = 0; j < blocksInBlock; j++) {\n                    const bool allocateBlock = true;\n                    Eigen::MatrixXd & Qi = *Q_sparse.block(s+i, s+j, allocateBlock);          \n                    Qi += Q.block(i*D,j*D,D,D);\n                }\n            }\n\n        }\n        return Q_sparse;\n    }\n        \n    \n    // sparse curveQuaddraticIntegral:\n    sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> BSpline::curveQuadraticIntegralDiagSparse(const Eigen::VectorXd & Wdiag, int derivativeOrder) const \n    {\n        \n        // define rows / cols:\n        // blocksize:\n        int D = coefficients_.rows();\n        int blocksInBlock = splineOrder_;\n        int blocks = numVvCoefficients();\n        int matrixSize = blocks * D;\n        \n        std::vector<int> rows;\n        std::vector<int> cols;\n        \n        int i;       \n        \n        for(i = D; i <= matrixSize; i+=D) {\n            rows.push_back(i);\n            cols.push_back(i);            \n        }              \n        \n        // create matrix:\n        sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> Q_sparse(rows,cols,true);\n        // place\n        for(int s = 0; s < numValidTimeSegments(); ++s)\n        {\n            Eigen::MatrixXd Q = segmentQuadraticIntegralDiag(Wdiag, s, derivativeOrder);\n            // place the DxD blocks in the blocksInBlock x blocksInBlock blocks:\n            for(int i = 0; i < blocksInBlock; i++) {\n                for(int j = 0; j < blocksInBlock; j++) {\n                    const bool allocateBlock = true;\n                    Eigen::MatrixXd & Qi = *Q_sparse.block(s+i, s+j, allocateBlock);          \n                    Qi += Q.block(i*D,j*D,D,D);\n                }\n            }\n            \n        }\n        return Q_sparse;\n  \n    }\n\n    \n    \n\n    Eigen::MatrixXd BSpline::curveQuadraticIntegral(const Eigen::MatrixXd & W, int derivativeOrder) const\n    {\n      int D = coefficients_.rows();\n      SM_ASSERT_EQ(Exception,W.rows(), D, \"W must be a square matrix the size of a single vector-valued coefficient\");\n      SM_ASSERT_EQ(Exception,W.cols(), D, \"W must be a square matrix the size of a single vector-valued coefficient\");\n      int N = coefficients_.cols();\n\n      Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(D*N, D*N);\n\n      int QiSize = splineOrder_ * D; \n      for(int s = 0; s < numValidTimeSegments(); s++)\n\t{\n\t  Q.block(s*D,s*D,QiSize,QiSize) += segmentQuadraticIntegral(W, s, derivativeOrder);\n\t}\n      \n\n      return Q;\n    }\n    \n    \n\n    Eigen::MatrixXd BSpline::curveQuadraticIntegralDiag(const Eigen::VectorXd & Wdiag, int derivativeOrder) const\n    {\n      int D = coefficients_.rows();\n      SM_ASSERT_EQ(Exception,Wdiag.size(), D, \"Wdiag must be the length of a single vector-valued coefficient\");\n      int N = coefficients_.cols();\n\n      Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(D*N, D*N);\n\n      int QiSize = splineOrder_ * D; \n      for(int s = 0; s < numValidTimeSegments(); s++)\n\t{\n\t  Q.block(s*D,s*D,QiSize,QiSize) += segmentQuadraticIntegralDiag(Wdiag, s, derivativeOrder);\n\t}\n      \n\n      return Q;\n    }\n\n    \n    \n    \n    \n\n    int BSpline::coefficientVectorLength() const\n    {\n      return coefficients_.rows() * coefficients_.cols();\n    }\n    \n    void BSpline::initConstantSpline(double t_min, double t_max, int numSegments, const Eigen::VectorXd & constant)\n    {\n      SM_ASSERT_GT(Exception,t_max,t_min, \"The max time is less than the min time\");\n      SM_ASSERT_GE(Exception,numSegments,1, \"There must be at least one segment\");\n      SM_ASSERT_GE(Exception, constant.size(), 1, \"The constant vector must be of at least length 1\");\n\n      int K = numKnotsRequired(numSegments);\n      int C = numCoefficientsRequired(numSegments);\n      double dt = (t_max - t_min) / (double)numSegments;\n      \n      double minTime = t_min - (splineOrder_ - 1)*dt;\n      double maxTime = t_max + (splineOrder_ - 1)*dt;\n      Eigen::VectorXd knotVector = Eigen::VectorXd::LinSpaced(K,minTime,maxTime);\n      // std::cout << \"K: \" << K << std::endl;\n      // std::cout << \"S: \" << numSegments << std::endl;\n      // std::cout << \"segTime: \" << t_min << \", \" << t_max << std::endl;\n      // std::cout << \"dt: \" << dt << std::endl;\n      // std::cout << \"time: \" << minTime << \", \" << maxTime << std::endl;\n      // std::cout << \"order: \" << splineOrder_ << std::endl;\n      // std::cout << knotVector.transpose() << std::endl;\n      Eigen::MatrixXd coeff(constant.size(),C);\n      for(int i = 0; i < C; i++)\n\tcoeff.col(i) = constant;\n\n      setKnotVectorAndCoefficients(knotVector,coeff);\n    }\n    \n    \n    int BSpline::numCoefficients() const\n    {\n      return coefficients_.rows() * coefficients_.cols();\n    }\n\n    Eigen::Map<Eigen::VectorXd> BSpline::vvCoefficientVector(int i)\n    {\n      SM_ASSERT_GE_LT(Exception, i, 0,  coefficients_.cols(), \"Index out of range\");\n      return Eigen::Map<Eigen::VectorXd>(&coefficients_(0,i),coefficients_.rows());\n    }\n    \n    Eigen::Map<const Eigen::VectorXd> BSpline::vvCoefficientVector(int i) const\n    {\n      SM_ASSERT_GE_LT(Exception, i, 0, coefficients_.cols(), \"Index out of range\");\n      return Eigen::Map<const Eigen::VectorXd>(&coefficients_(0,i),coefficients_.rows());\n    }\n\n    int BSpline::numVvCoefficients() const\n    {\n      return coefficients_.cols();\n    }\n\n    void BSpline::saveSplineToFile(std::string knotCoeffFile)\n    {\n      std::ofstream kcs(knotCoeffFile);\n      kcs<<\"%%splineOrder, knots length, coefficients rows, cols\"<<std::endl;\n      kcs<<\"%%then knots, then coefficients.transpose\"<<std::endl;\n      kcs<< splineOrder_ <<\" \"<< knots_.size()<<\" \"<< coefficients_.rows() <<\" \"<< coefficients_.cols()<<std::endl;\n      kcs<< std::fixed << std::setprecision(9);\n      for(size_t jack=0; jack<knots_.size(); ++jack)\n        kcs<< knots_[jack]<<std::endl;\n      kcs<< std::fixed << std::setprecision(12);\n      for(int jack=0; jack<coefficients_.cols(); ++jack){\n        int kite=0;\n        for(; kite<coefficients_.rows()-1; ++kite)\n          kcs<<coefficients_(kite,jack)<<\" \";\n        kcs<<coefficients_(kite,jack)<<std::endl;       \n      }\n      kcs.close();\n    }\n    bool BSpline::initSplineFromFile(std::string knotCoeffFile)\n    { \n      std::ifstream ifs;\n      ifs.open (knotCoeffFile, std::ifstream::in);\n      if(!ifs.is_open()){\n        std::cerr<<\"Unable to open \"<< knotCoeffFile<<std::endl;\n        return false;\n      }\n      std::string receptacle;\n      std::getline(ifs, receptacle);      \n      while(receptacle.find('%') != std::string::npos)\n        std::getline(ifs, receptacle);\n      std::stringstream stream(receptacle);\n      int splineOrder;\n      size_t knotsSize;\n      size_t coeffRows, coeffCols;\n      stream >> splineOrder >> knotsSize >> coeffRows >> coeffCols;\n      stream.clear();\n      std::vector<double> knots(knotsSize);\n      Eigen::MatrixXd coefficients(coeffRows, coeffCols);\n          \n      for(size_t jack=0; jack<knots.size(); ++jack)\n        ifs >> knots[jack];\n      \n      for(int jack=0; jack<coefficients.cols(); ++jack){        \n        for(int kite=0; kite<coefficients.rows(); ++kite)\n          ifs>>coefficients(kite,jack);          \n      }\n      ifs.close(); \n      if(splineOrder!= splineOrder_)\n      {\n        std::cerr<<\"Read a wrong splineOrder from \"<< knotCoeffFile<<std::endl;\n        return false;\n      }\n      setKnotsAndCoefficients(knots, coefficients);\n      return true;\n    }\n\n  } // namespace bsplines\n", "meta": {"hexsha": "a6667207a19498cea27ae70c727f045ed05ff332", "size": 63827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSpline.cpp", "max_stars_repo_name": "JzHuai0108/kalibr", "max_stars_repo_head_hexsha": "32d095162408c90ebf0c49522d27732ffec8f35f", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-08-20T21:12:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:20:25.000Z", "max_issues_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSpline.cpp", "max_issues_repo_name": "JzHuai0108/kalibr", "max_issues_repo_head_hexsha": "32d095162408c90ebf0c49522d27732ffec8f35f", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_nonparametric_estimation/bsplines/src/BSpline.cpp", "max_forks_repo_name": "JzHuai0108/kalibr", "max_forks_repo_head_hexsha": "32d095162408c90ebf0c49522d27732ffec8f35f", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-17T12:16:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T02:52:35.000Z", "avg_line_length": 34.9545454545, "max_line_length": 211, "alphanum_fraction": 0.6092876056, "num_tokens": 17243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.6370307875894139, "lm_q1q2_score": 0.5589797249387832}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2018 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).\n\n// Contains Quickbook snippets used by boost/libs/multiprecision/doc/multiprecision.qbk,\n// used in section Literal Types and constexpr Support, last example on constexpr randoms.\n\n// A implementation and demonstration of the Keep It Simple Stupid random number generator algorithm https://en.wikipedia.org/wiki/KISS_(algorithm) for cpp_int integers.\n// b2 --abbreviate-paths toolset=clang-9.0.0 address-model=64 cxxstd=2a release misc > multiprecision_clang_misc.log\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <iostream>\n\nstruct kiss_rand\n{\n   typedef std::uint64_t result_type;\n\n   constexpr kiss_rand() : x(0x8207ebe160468b32uLL), y(0x2871283e01d45bbduLL), z(0x9c80bfd5db9680c9uLL), c(0x2e2683c2abb878b8uLL) {}\n   constexpr kiss_rand(std::uint64_t seed) : x(seed), y(0x2871283e01d45bbduLL), z(0x9c80bfd5db9680c9uLL), c(0x2e2683c2abb878b8uLL) {}\n   constexpr kiss_rand(std::uint64_t seed_x, std::uint64_t seed_y) : x(seed_x), y(seed_y), z(0x9c80bfd5db9680c9uLL), c(0x2e2683c2abb878b8uLL) {}\n   constexpr kiss_rand(std::uint64_t seed_x, std::uint64_t seed_y, std::uint64_t seed_z) : x(seed_x), y(seed_y), z(seed_z), c(0x2e2683c2abb878b8uLL) {}\n\n   constexpr std::uint64_t operator()()\n   {\n      return MWC() + XSH() + CNG();\n   }\n\n private:\n   constexpr std::uint64_t MWC()\n   {\n      std::uint64_t t = (x << 58) + c;\n      c               = (x >> 6);\n      x += t;\n      c += (x < t);\n      return x;\n   }\n   constexpr std::uint64_t XSH()\n   {\n      y ^= (y << 13);\n      y ^= (y >> 17);\n      return y ^= (y << 43);\n   }\n   constexpr std::uint64_t CNG()\n   {\n      return z = 6906969069LL * z + 1234567;\n   }\n   std::uint64_t x, y, z, c;\n};\n\ninline constexpr void hash_combine(std::uint64_t& h, std::uint64_t k)\n{\n   constexpr const std::uint64_t m = 0xc6a4a7935bd1e995uLL;\n   constexpr const int           r = 47;\n\n   k *= m;\n   k ^= k >> r;\n   k *= m;\n\n   h ^= k;\n   h *= m;\n\n   // Completely arbitrary number, to prevent 0's from hashing to 0.\n   h += 0xe6546b64;\n}\n\ntemplate <std::size_t N>\ninline constexpr std::uint64_t string_to_hash(const char (&s)[N])\n{\n   std::uint64_t hash(0);\n   for (unsigned i = 0; i < N; ++i)\n      hash_combine(hash, s[i]);\n   return hash;\n}\n\ntemplate <class UnsignedInteger>\nstruct multiprecision_generator\n{\n   typedef UnsignedInteger result_type;\n   constexpr               multiprecision_generator(std::uint64_t seed1) : m_gen64(seed1) {}\n   constexpr               multiprecision_generator(std::uint64_t seed1, std::uint64_t seed2) : m_gen64(seed1, seed2) {}\n   constexpr               multiprecision_generator(std::uint64_t seed1, std::uint64_t seed2, std::uint64_t seed3) : m_gen64(seed1, seed2, seed3) {}\n\n   static constexpr result_type (min)()\n   {\n      return 0u;\n   }\n   static constexpr result_type (max)()\n   {\n      return ~result_type(0u);\n   }\n   constexpr result_type operator()()\n   {\n      result_type result(m_gen64());\n      unsigned    digits = 64;\n      while (digits < std::numeric_limits<result_type>::digits)\n      {\n         result <<= 64;\n         result |= m_gen64();\n         digits += 64;\n      }\n      return result;\n   }\n\n private:\n   kiss_rand m_gen64;\n};\n\ntemplate <class UnsignedInteger>\nconstexpr UnsignedInteger nth_random_value(unsigned count = 0)\n{\n   std::uint64_t                             date_hash = string_to_hash(__DATE__);\n   std::uint64_t                             time_hash = string_to_hash(__TIME__);\n   multiprecision_generator<UnsignedInteger> big_gen(date_hash, time_hash);\n   for (unsigned i = 0; i < count; ++i)\n      big_gen();\n   return big_gen();\n}\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n//[random_constexpr_cppint\n   constexpr uint1024_t rand = nth_random_value<uint1024_t>(1000);\n   std::cout << std::hex << rand << std::endl;\n//] [/random_constexpr_cppint]\n   return 0;\n}\n", "meta": {"hexsha": "b108b6d635d7a7635b494c8db7bcd0215412a619", "size": 4060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/multiprecision/test/constexpr_test_cpp_int_7.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/multiprecision/test/constexpr_test_cpp_int_7.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/multiprecision/test/constexpr_test_cpp_int_7.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 30.9923664122, "max_line_length": 169, "alphanum_fraction": 0.645320197, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5589754885305038}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <vector>\n#include <chrono>\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include \"step_adjuster.hpp\"\n#include \"runge_kutta_bs3.hpp\"\n\nusing namespace boost::numeric::odeint;\ntypedef std::vector< double > state_type;\ntypedef custom_controlled_runge_kutta< runge_kutta_dopri5< state_type >, custom_error_checker< double, range_algebra, default_operations >, custom_step_adjuster<double, double>> RK45;\ntypedef custom_controlled_runge_kutta< runge_kutta_bs3< state_type >, custom_error_checker< double, range_algebra, default_operations >, custom_step_adjuster<double, double>> RK23;\n\n/* The rhs of x' = f(x) */\nvoid spiral_problem(const state_type& x, state_type& dxdt, const double t)\n{\n    dxdt[0] = std::cos(t) - x[1];\n    dxdt[1] = std::sin(t) + x[0];\n}\n\nvoid lotka_volterra_problem(const state_type& x, state_type& dxdt, const double t)\n{\n    dxdt[0] = x[0] * (1 - x[1]);\n    dxdt[1] = -x[1] * (1 - x[0]);\n}\n\nvoid brusselator_problem(const state_type& x, state_type& dxdt, const double t)\n{\n    dxdt[0] = 1 + x[0] * x[0] * x[1] - 4 * x[0];\n    dxdt[1] = 3 * x[0] - x[0] * x[0] * x[1];\n}\n\nstruct push_back_state_and_time\n{\n    std::vector< state_type >& m_states;\n    std::vector< double >& m_times;\n\n    push_back_state_and_time(std::vector< state_type >& states, std::vector< double >& times)\n        : m_states(states), m_times(times) { }\n\n    void operator()(const state_type& x, double t)\n    {\n        m_states.push_back(x);\n        m_times.push_back(t);\n    }\n};\n\n\nint main(int argc, const char* argv[]) {\n    boost::program_options::options_description desc;\n    desc.add_options()\n        (\"help,h\", \"Show this help screen\")\n        (\"model_file_name\", boost::program_options::value<std::string>()->default_value(\"\"), \"NN controller file name, leave empty if not used\")\n        (\"method\", boost::program_options::value<std::string>()->default_value(\"DP5\"), \"ode method in use, support DP5 or BS3\")\n        (\"problem\", boost::program_options::value<std::string>()->default_value(\"Spiral\"), \"problem to solve, support spiral or lotka_volterra\")\n        (\"is_fixed\", \"using fixed method\")\n        (\"atol\", boost::program_options::value<double>()->default_value(1.0e-6), \"absolute tolerance or stepsize when is_fixed is specified\");\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n    boost::program_options::notify(vm);\n    if (vm.count(\"help\")) {\n        std::cout << desc << '\\n';\n        return 0;\n    }\n    std::string model_file_name = vm[\"model_file_name\"].as<std::string>();\n    double abs_err = vm[\"atol\"].as<double>();\n    bool is_fixed = vm.count(\"is_fixed\") > 0;\n    std::string method_name = vm[\"method\"].as<std::string>();\n    std::string problem_name = vm[\"problem\"].as<std::string>();\n    state_type y(2);\n\n    double rel_err = 0.0, a_x = 1.0, a_dxdt = 0.0, max_dt = 100.0;\n    double t_start = 0.0, t_end, y0_0, y1_0;\n    std::vector<state_type> x_vec;\n    std::vector<double> times;\n    RK45 rk45_solver(\n        custom_error_checker< double, range_algebra, default_operations >(abs_err, rel_err, a_x, a_dxdt),\n        custom_step_adjuster<double, double>(max_dt),\n        RK45::stepper_type(),\n        model_file_name, is_fixed);\n    RK23 rk23_solver(\n        custom_error_checker< double, range_algebra, default_operations >(abs_err, rel_err, a_x, a_dxdt),\n        custom_step_adjuster<double, double>(max_dt),\n        RK23::stepper_type(),\n        model_file_name, is_fixed);\n    double initial_step;\n    size_t repeat_time = 1000;\n    long int_ns = 0;\n    void (*problem)(const state_type&, state_type&, const double);\n    if (problem_name == \"Spiral\") {\n        problem = &spiral_problem;\n        t_end = 2 * M_PI;\n        y0_0 = 0.0; // initial value\n        y1_0 = 0.0;\n    }\n    else if (problem_name == \"LotkaVolterra\") {\n        problem = &lotka_volterra_problem;\n        t_end = 15.0;\n        y0_0 = 2.0; // initial value\n        y1_0 = 1.0;\n    }\n    else {\n        problem = &brusselator_problem;\n        t_end = 20.0;\n        y0_0 = 1.5; // initial value\n        y1_0 = 3.0;\n    }\n    y[0] = y0_0;\n    y[1] = y1_0;\n    if (method_name == \"DP5\") {\n        if (is_fixed) {\n            initial_step = abs_err;\n        }\n        else {\n            initial_step = select_initial_step(problem, t_start, y, rk45_solver.stepper().error_order(), rel_err, abs_err);\n        }\n\n        size_t steps = integrate_adaptive(rk45_solver, problem,\n            y, t_start, t_end, initial_step, push_back_state_and_time(x_vec, times));\n\n        for (int i = 0; i < repeat_time; i++) {\n            y[0] = y0_0; // reset initial value\n            y[1] = y1_0;\n            auto t1 = std::chrono::high_resolution_clock::now();\n            steps = integrate_adaptive(rk45_solver, problem,\n                y, t_start, t_end, initial_step);\n            auto t2 = std::chrono::high_resolution_clock::now();\n            int_ns += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n        }\n    }\n    else { // BS3 currently\n\n        if (is_fixed) {\n            initial_step = abs_err;\n        }\n        else {\n            initial_step = select_initial_step(problem, t_start, y, rk23_solver.stepper().error_order(), rel_err, abs_err);\n        }\n        size_t steps = integrate_adaptive(rk23_solver, problem,\n            y, t_start, t_end, initial_step, push_back_state_and_time(x_vec, times));\n\n        for (int i = 0; i < repeat_time; i++) {\n            y[0] = y0_0; // reset initial value\n            y[1] = y1_0;\n            auto t1 = std::chrono::high_resolution_clock::now();\n            steps = integrate_adaptive(rk23_solver, problem,\n                y, t_start, t_end, initial_step);\n            auto t2 = std::chrono::high_resolution_clock::now();\n            int_ns += std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();\n        }\n    }\n    double average_time = int_ns * 1.0 / repeat_time;\n    /* output */\n    /*for (size_t i = 0; i <= steps; i++)\n    {\n        std::cout << std::setprecision(7) << times[i] << '\\t' << x_vec[i][0] << '\\t' << x_vec[i][1] << '\\n';\n    }\n    */\n    std::cout << average_time << std::endl;\n}", "meta": {"hexsha": "23c1e67396e99d8c159d331f97b339ccca25f28f", "size": 6336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lotka/prl.cpp", "max_stars_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_stars_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lotka/prl.cpp", "max_issues_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_issues_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lotka/prl.cpp", "max_forks_repo_name": "zhaofeng-shu33/deep_euler_tests", "max_forks_repo_head_hexsha": "a3d0961af679d490b0c58873ee0726234122bc7a", "max_forks_repo_licenses": ["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.6341463415, "max_line_length": 183, "alphanum_fraction": 0.6208964646, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5589754834655444}}
{"text": "/*!  @author Michael Brand\n*    @Excercise 8\n*    @date 17.07.2017\n*\n*   Algorithm to find Steiner tree on a graph where primes count as termainals.\n*\n*   I decided to leave all code in one file since its mainly consistent of two bigger algorithms\n*   1. Dijkstra\n*   2. Analyzing Dijkstra output in main-function\n*   I don't think it gets to complicated reading it from top to bottom.\n*/\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <stdio.h>\n#include <cstdio>\n#include <ctime>\n#include <chrono>\n#include <vector>\n#include <climits>\n#include <utility>                          // for std::pair\n\n#include <boost/config.hpp>\n#include <boost/utility.hpp>                // for boost::tie\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n\nusing namespace std;\n\n\ntypedef int vertex_;  /*!< defines a vertex as an int */\ntypedef int weight_;  /*!< defines a weight as an int */\n\n/**Edge\n * pair of ints containing the weight and\n * the vertex pointed to. This is useful\n * for the adjacency list\n */\ntypedef pair<vertex_, weight_> Edge;\n\n/**Graph\n * An adjacency list representing the graph.\n * graph[i] returns a list with Edge elements.\n *\n */\ntypedef vector< vector<Edge> > Graph;\n\n\n/**struct pq_compare\n * compare structure for edges\n * allows me to compare two edges in a graph\n * this way I can sort edges for any vertex under consideration of their weight\n */   \nstruct pq_compare {\n    bool operator() (const Edge i, const Edge j) const{\n    return (i.second <= j.second); }\n};\n\n/*! \\fn bool isPrime(int number)\n    \\brief checks if number is a prime.\n    \\param number number to be checked.\n*/\nbool isPrime(int number){\n\n    if(number < 2) return false;\n    if(number == 2) return true;\n    if(number % 2 == 0) return false;\n    for(int i=3; (i*i)<=number; i+=2){\n        if(number % i == 0 ) return false;\n    }\n    return true;\n\n}\n\n/*! \\fn std::vector<int> getRequiredPrimes(int numV)\n    \\brief lists all primes <= numV in a vector.\n    \\param numV number to be checked.\n    \\return vector of primes\n*/\nstd::vector<int> getRequiredPrimes(int numV){\n  std::vector<int> primes;\n  for(int i=3; i<=numV; i++){\n    if(isPrime(i)) primes.push_back(i);\n  }\n  return primes;\n}\n\n\n/*! \\fn std::vector<vertex_> dijkstra(const Graph &graph, vertex_ root, vector<int> &remPrimes)\n*   \\brief modified dijkstra algorithm used for steiner tree problem\n*   \\param &graph the graph we are working on.\n*   \\param root source vertex from which we want to calculate the distance\n*   \\&remPrimes vector of remaining prime no.\n*   \\return vector path that consists of\n*     path[0] distance to terminal\n*     path[1] terminal index\n*     path[2] pre of path[1]\n*     ...\n*     path[n] pre of path[n-1]\n*     path[n] is vertex index which has source index as pre\n*/\nstd::vector<vertex_> dijkstra(const Graph &graph, vertex_ root, vector<int> &remPrimes, bool stNodeStructLoc[]) {\n\n  std::vector<vertex_> path;\n  std::vector<weight_> dist(graph.size(), INT_MAX);\n  /* A set helps insertion and insert/erase/find operations in logarithmic time.\n   * This set maintains Edge(distance,vertex number) sorted on basis of distance\n   */\n  set< Edge , pq_compare> pq;\n  set< Edge , pq_compare > ::iterator it;\n\n\n  vector<vertex_> pre(graph.size(), (-1)); /*!< vevtor of predecessors */\n  int u,v,wt;\n  int nPrime = 0; /*!< next prime - closest prime that is remaining in &remPrimes */\n\n  dist[root] = 0;\n  pq.insert(Edge(root,0));\n\n  while(pq.size() != 0){\n    bool found = false;\n    it = pq.begin();\n    u = it->first;\n    pq.erase(it);\n    if(isPrime(u+1)){\n        for(int chk=0; chk<remPrimes.size(); chk++){\n          if((remPrimes[chk])==(u+1)){\n            nPrime=u;\n            found = true;\n            break;\n          }\n        }\n    }\n    if(found) break;\n    \n    for(vector<Edge>::const_iterator ni = graph[u].begin(); ni != graph[u].end(); ni++){\n      v  = ni->first;\n      wt = ni->second;\n      if(stNodeStructLoc[v]){\n        continue;\n      } \n      if(dist[v] > dist[u] + wt){\n        pre[v] = u;\n        if(dist[v] != INT_MAX){\n          pq.erase(Edge(v,dist[v]));\n        }\n        dist[v] = dist[u] + wt;\n        pq.insert(Edge(v,dist[v]));\n      }\n    \n    }\n  }\n  /**\n  * If source was internal node of steiner subgraph no new terminal is found\n  * so we return vector of INT_MAX element\n  */\n  if(nPrime==0){\n    path.push_back(INT_MAX);\n    return path;\n  }\n  int distTerm = dist[nPrime];  /*!< distance to chosen terminal */\n  /*! Create path\n  *   save all nodes on path to a vector\n  *   add distance of edges at the end at the top\n  *   do not at the chosen root. does not need to be added to the subgraph anymore\n  */\n  path.push_back(nPrime);\n  int lN = nPrime;\n  while(lN != root){\n    lN = pre[lN];\n    path.push_back(lN);\n  }\n  path.insert(path.begin(),distTerm);\n  return path;\n}\n\nint main (int argc, char* argv[]) {\n\n  /**\n  * start timers for cpu and wall time\n  */\n  clock_t cpu0 = clock();\n  auto   wall0 = chrono::system_clock::now();\n  if( argc != 2){\n      fprintf(stderr, \"Call the program as: %s 'filename.gph'\", argv[0]);\n      exit(EXIT_FAILURE);\n  }\n  ifstream    file(argv[1]);\n  string      line;\n  if(!file){\n    fprintf(stderr, \"Could not open file.\");\n    return -1;\n  }\n  /**\n  * read number of vertices and edges\n  */\n  getline(file, line, ' ');\n  const int numV = stoi(line);\n  getline(file, line, '\\n');\n  const int numE = stoi(line);\n  /**\n  * create graph and steiner subgraph structures\n  */\n  Graph graph(numV);\n  Graph steinerGraph(numV);\n  bool stNodeStruct[numV] = { 0 };;\n  int noStEdges = 0;  /*!< #edges in steiner tree */\n  int stEdWght = 0;   /*!< obj value of steiner tree */\n  int stNodes = 1;\n  /**\n  * read ín given gph file\n  */\n  while( getline(file, line) ){\n    stringstream linestream(line);\n    string       vertex1, vertex2, weight;\n    try{\n      getline(linestream, vertex1, ' ');\n      getline(linestream, vertex2, ' ');\n      getline(linestream, weight, '\\n');\n      /**\n      * add both directions of edge to the graph since undirected\n      * index switch applies: 1 --> 0, 1 --> 2, etc.\n      */\n      graph[stoi(vertex1)-1].push_back(Edge(stoi(vertex2)-1, stoi(weight)));\n      //std::sort (graph[stoi(vertex1)-1].begin(), graph[stoi(vertex1)-1].end(), sortEdges);\n      graph[stoi(vertex2)-1].push_back(Edge(stoi(vertex1)-1, stoi(weight)));\n      // std::sort (graph[stoi(vertex2)-1].begin(), graph[stoi(vertex2)-1].end(), sortEdges);\n    }catch (invalid_argument& ia){\n      //when data is not a digit,\n      //std::stoi throws an invalid argument exception\n    } catch ( ... ){}\n  }//while\n  file.close();\n  /**\n  * get vector of primes that need to be connected in steiner tree\n  */\n  std::vector<int> remainingPrimes = getRequiredPrimes(numV);\n  bool initState=true;\n  /**\n  * we initialize the steiner subgraph with terminal 2 (initState=true)\n  * in the following (initState=false) we start dijkstra from every single node in the\n  * subgraph and collect in every iteration the closest new terminal to the existing subgraph\n  * -> saved in lovalSelection\n  * we copy the result into an existing vector -> globalSelection\n  * after all localSelections have been calculated we iterate through globalSelection\n  * and coose the terminal that has the minimal distance (saved in globalSelection[i][0])\n  */\n  do{\n    std::vector< std::vector<vertex_>> globalSelection;\n    int distance = INT_MAX;\n    int choice = -1;\n    if(initState){\n      std::vector<vertex_> localSelection = dijkstra(graph, 1, remainingPrimes, stNodeStruct);\n      globalSelection.push_back(localSelection);\n      for(int j=0; j<globalSelection.size(); j++){\n        if(globalSelection[j][0]<distance){\n         distance = globalSelection[j][0];\n         choice = j;\n        }\n      }\n      initState=false;\n    }\n    else{ \n      for(int i=0; i<steinerGraph.size(); i++){\n        if(!(steinerGraph[i].empty())){\n          std::vector<vertex_> localSelection = dijkstra(graph, i, remainingPrimes, stNodeStruct);\n          globalSelection.push_back(localSelection);\n        }\n      }\n      for(int j=0; j<globalSelection.size(); j++){\n        if(globalSelection[j][0]<distance){\n          distance = globalSelection[j][0];\n          choice = j;\n        }\n      }\n    }\n    /**\n    * add edges by pre-information:\n    * globalSelection consists of path-vectors\n    * which have certain structure\n    * --> see dijkstra algo info\n    */\n    for(int pathNode = 1; pathNode < globalSelection[choice].size()-1; pathNode++){\n      int from = globalSelection[choice][pathNode+1];\n      int to = globalSelection[choice][pathNode];\n      stNodes++;\n      /*!\n      * iterate over from-node-edges\n      * search for relevant edge and add it to steinerGraph including its weight\n      */\n      for(int eIndx = 0; eIndx < graph[from].size(); eIndx++){\n        if(graph[from][eIndx].first==to){\n          steinerGraph[from].push_back(Edge(to, graph[from][eIndx].second));\n          steinerGraph[to].push_back(Edge(from, graph[from][eIndx].second));\n          noStEdges++;\n          stEdWght += graph[from][eIndx].second;\n          stNodeStruct[from] = true;\n          stNodeStruct[to] = true;\n        }\n      }\n    }\n    /**\n    * delete prime from remainingPrimes\n    */\n    for(int chk=0; chk<remainingPrimes.size(); chk++){\n      if((remainingPrimes[chk]==(globalSelection[choice][1]+1))){\n        remainingPrimes.erase(remainingPrimes.begin()+chk);\n        break;\n      }\n\n    }\n    globalSelection.clear();\n  }while(remainingPrimes.size()>0);\n  /**\n  * collection stats\n  */\n  //Stats\n  fprintf(stdout, \"\\n\");\n  fprintf(stdout, \"Original graph:\\n#Vert: \\t %i\\n#Edges \\t %i\\n\", numV, numE);\n  fprintf(stdout, \"\\n\");\n  fprintf(stdout, \"Steiner graph:\\n#Vert: \\t %i\\n#Edges \\t %i\\nObjVal \\t %i\\n\", stNodes, noStEdges, stEdWght);\n  \n  fprintf(stdout, \"\\n\");\n  double cpuTime = (clock() - cpu0) / (double) CLOCKS_PER_SEC;\n  chrono::duration<double> wallDur = (chrono::system_clock::now() - wall0);\n  double wallTime = wallDur.count();\n  fprintf(stdout, \"Finished in %f seconds [CPU Clock] and %f seconds [Wall Clock] \\n\", cpuTime, wallTime);\n  fprintf(stdout, \"\\n\");\n  return 0;\n\n}\n\n", "meta": {"hexsha": "702bbf43eda7b9062c692272682f459c3239400e", "size": 10244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Brand/ex8/ex8.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Brand/ex8/ex8.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Brand/ex8/ex8.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 30.4880952381, "max_line_length": 113, "alphanum_fraction": 0.625829754, "num_tokens": 2772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5589737288516475}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include \"jefflib.h\" \n#include <boost/tokenizer.hpp>\n#include <cmath>\n#include <map>\n\nusing namespace std;\nusing namespace boost;\n\nstruct coord_t {\n    int x;\n    int y;\n};\n\nstruct loc_t {\n    int x;\n    int y;\n    int distSum = 0;\n};\n\nint main()\n{\n    vector<string> vect;\n    if(GetStringInput(vect)){\n        cout << \"Got data!\" << endl;\n        cout << endl;\n    }\n    else {\n        cout << \"Failed to read input :( \" << cout;\n        return -1;\n    }\n   \n    // Create the list of coords, making note of bounds\n    vector<coord_t> coords;\n    for (const string line : vect)\n    {\n        char_separator<char> sep(\",\");\n        tokenizer< char_separator<char> > tokens(line, sep);\n        // x y\n        vector<string> s_tmp(tokens.begin(), tokens.end());\n        coord_t tempCoord;\n        tempCoord.x = stoi(s_tmp[0]);\n        tempCoord.y = stoi(s_tmp[1]);\n        coords.push_back(tempCoord);\n    }\n   \n\n    int minX = -100;\n    int minY = -100;\n    int maxX = 1000;\n    int maxY = 1000;\n\n    // Let's build a (bounded) list of locations of interest\n    vector<loc_t> locs;\n    for(int x = minX; x <= maxX; x++){\n        for(int y = minY; y <= maxY; y++){\n            loc_t tempLoc;\n            tempLoc.x = x;\n            tempLoc.y = y;\n            locs.push_back(tempLoc);\n        }\n    }\n    cout << \"Number of locations: \" << locs.size() << endl;\n    int regionSize = 0;\n    // For each location, let's calculate the sum of distance to each coordinate\n    for(auto  &location : locs){\n        int distanceSum = 0;\n        for(int i = 0; i < coords.size(); i++){\n            distanceSum += abs(location.x - coords[i].x) + abs(location.y - coords[i].y);\n            if(distanceSum > 10000) break;\n        }\n        if(distanceSum < 10000) regionSize++;\n    }\n    \n    cout << \"Region size: \" << regionSize << endl;\n}\n\n\n", "meta": {"hexsha": "9ee36d17bf68b34c5432ceaf8ce10f53129f9c5d", "size": 1884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-06/part-2.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T01:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T01:40:07.000Z", "max_issues_repo_path": "jeff/day-06/part-2.cpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jeff/day-06/part-2.cpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2592592593, "max_line_length": 89, "alphanum_fraction": 0.5440552017, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.5589737189407135}}
{"text": "//\n//  geometry.cpp\n//  Nesting Problem\n//\n//  Created by 爱学习的兔子 on 2020/4/14.\n//  Copyright © 2020 Tongji SEM. All rights reserved.\n//\n\n#include \"data_assistant.cpp\"\n#include <deque>\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/foreach.hpp>\n#include <boost/geometry/algorithms/for_each.hpp>\n\nusing namespace boost::geometry;\nusing namespace std;\n\n#define BIAS 0.000001\n\n// 基础定义\ntypedef model::d2::point_xy<double> Point;\ntypedef model::polygon<Point> Polygon;\ntypedef model::linestring<Point> LineString;\n\n\n// 封装获得全部点的函数\ntemplate <typename Point>\nclass AllPoint{\nprivate :\n    VectorPoints *temp_all_points;\npublic :\n    AllPoint(VectorPoints *all_points){\n        temp_all_points=all_points;\n    };\n    inline void operator()(Point& pt)\n    {\n        vector<double> new_pt={get<0>(pt),get<1>(pt)};\n        (*temp_all_points).push_back(new_pt);\n    }\n};\n\n//主要包含注册多边形、转化多边形\nclass GeometryProcess{\npublic:\n    /*\n     数组转化为多边形\n     */\n    static void convertPoly(vector<vector<double>> poly, Polygon &Poly){\n        // 空集的情况\n        if(poly.size()==0){\n            read_wkt(\"POLYGON(())\", Poly);\n            return;\n        }\n        // 首先全部转化为wkt格式\n        string wkt_poly=\"POLYGON((\";\n        for (int i = 0; i < poly.size();i++){\n            wkt_poly+=to_string(poly[i][0]) + \" \" + to_string(poly[i][1]) + \",\";\n            if(i==poly.size()-1){\n                wkt_poly+=to_string(poly[0][0]) + \" \" + to_string(poly[0][1]) + \"))\";\n            }\n        };\n        // 然后读取到Poly中\n        read_wkt(wkt_poly, Poly);\n    };\n    /*\n     通过for each point遍历\n     */\n    static void getAllPoints(list<Polygon> all_polys,VectorPoints &all_points){\n        for(auto poly_item:all_polys){\n            VectorPoints temp_points;\n            getGemotryPoints(poly_item,temp_points);\n            all_points.insert(all_points.end(),temp_points.begin(),temp_points.end());\n        }\n    };\n    // 获得vector<list<VectorPoints>>的多边形（并非全部点）\n    static void getListPolys(vector<list<Polygon>> list_polys,vector<VectorPoints> &all_polys){\n        for(auto _list:list_polys){\n            for(Polygon poly_item:_list){\n                VectorPoints poly_points;\n                getGemotryPoints(poly_item,poly_points);\n                all_polys.push_back(poly_points);\n            }\n        }\n    };\n    // 获得某个集合对象的全部点\n    static void getGemotryPoints(Polygon poly,VectorPoints &temp_points){\n        for_each_point(poly, AllPoint<Point>(&temp_points));\n    };\n};\n\n// 包含处理函数\nclass PackingAssistant{\npublic:\n    /*\n     获得Inner Fit Rectangle\n     */\n    static void getIFR(VectorPoints polygon,double container_width,double container_length,VectorPoints &IFR){\n        // 初始参数，获得多边形特征\n        VectorPoints border_points;\n        getBorder(polygon,border_points);\n                \n        double poly_width_left=border_points[3][0]-border_points[0][0];\n        double poly_width_right=border_points[2][0]-border_points[3][0];\n        double poly_height=border_points[3][1]-border_points[1][1];\n\n        // IFR具体计算（从左上角顺时针计算）\n        IFR.push_back({poly_width_left,container_width});\n        IFR.push_back({container_length-poly_width_right,container_width});\n        IFR.push_back({container_length-poly_width_right,poly_height});\n        IFR.push_back({poly_width_left,poly_height});\n    };\n    /*\n     移动某个多边形\n     */\n    static void slidePoly(VectorPoints &polygon,double delta_x,double delta_y){\n        for(int i=0;i<polygon.size();i++){\n            polygon[i][0]=polygon[i][0]+delta_x;\n            polygon[i][1]=polygon[i][1]+delta_y;\n        }\n    };\n    /*\n     移动多边形到某个位置（参考点）\n     */\n    static void slideToPosition(VectorPoints &polygon,vector<double> target_pt){\n        vector<double> refer_pt;\n        getReferPt(polygon,refer_pt);\n        cout<<\"多边形\";\n        PrintAssistant::print2DVector(polygon,true);\n        cout<<\"参考点:\"<<refer_pt[0]<<\",\"<<refer_pt[1]<<endl;\n        cout<<\"目标点:\"<<target_pt[0]<<\",\"<<target_pt[1]<<endl;\n        double delta_x=target_pt[0]-refer_pt[0];\n        double delta_y=target_pt[1]-refer_pt[1];\n        for(int i=0;i<polygon.size();i++){\n            polygon[i][0]=polygon[i][0]+delta_x;\n            polygon[i][1]=polygon[i][1]+delta_y;\n        }\n    };\n    /*\n     获得多边形的所有的边界情况min_x min_y max_x max_y\n     */\n    static void getBound(VectorPoints polygon,vector<double> &bound){\n        VectorPoints border_points;\n        getBorder(polygon,border_points);\n        bound={border_points[0][0],border_points[1][1],border_points[2][0],border_points[3][1]};\n    };\n    /*\n     遍历获得一个多边形的最左侧点\n     */\n    static void getBottomLeft(VectorPoints polygon,vector<double> &bl_point){\n        bl_point={999999999,999999999};\n        for(auto point:polygon){\n            if(point[0]<bl_point[0] || (point[0]==bl_point[0]&&point[1]<bl_point[1]) ){\n                bl_point[0]=point[0];\n                bl_point[1]=point[1];\n            }\n        };\n    };\n    /*\n     仅仅获得最右侧点，同样为逆时针处理（用于判断是逗超出界限）\n     */\n    static void getRightPt(VectorPoints polygon,vector<double> &right_pt){\n        right_pt={-9999999999,0};\n        int poly_size=(int)polygon.size();\n        for(int i=poly_size-1;i>=0;i--){\n            if(polygon[i][0]>right_pt[0]){\n                right_pt[0]=polygon[i][0];\n                right_pt[1]=polygon[i][1];\n            }\n        }\n    };\n    /*\n     仅仅获得参考点，是第一个Top位置，需要逆时针处理（NFP为逆时针）\n     */\n    static void getReferPt(VectorPoints polygon,vector<double> &refer_pt){\n        refer_pt={0,-9999999999};\n        int poly_size=(int)polygon.size();\n        for(int i=poly_size-1;i>=0;i--){\n            if(polygon[i][1]>refer_pt[1]){\n                refer_pt[0]=polygon[i][0];\n                refer_pt[1]=polygon[i][1];\n            }\n        }\n    };\n    /*\n     仅仅获得底部位置（用于NFP计算），是第一个Bottom位置，需要逆时针处理\n     */\n    static void getBottomPt(VectorPoints polygon,vector<double> &bottom_pt){\n        bottom_pt={0,9999999999};\n        int poly_size=(int)polygon.size();\n        for(int i=poly_size-1;i>=0;i--){\n            if(polygon[i][1]<bottom_pt[1]){\n                bottom_pt[0]=polygon[i][0];\n                bottom_pt[1]=polygon[i][1];\n            }\n        }\n    };\n    \n    /*\n     获得多边形的边界四个点，border_points有left bottom right top四个点\n     暂时不考虑参考点，参考点统一逆时针旋转第一个最上方的点\n     */\n    static void getBorder(VectorPoints polygon,VectorPoints &border_points){\n        // 增加边界的几个点\n        border_points.push_back(vector<double>{9999999999,0});\n        border_points.push_back(vector<double>{0,999999999});\n        border_points.push_back(vector<double>{-999999999,0});\n        border_points.push_back(vector<double>{0,-999999999});\n        // 遍历所有的点，分别判断是否超出界限\n        int poly_size=(int)polygon.size();\n        for(int i=poly_size-1;i>=0;i--){\n            // 左侧点判断\n            if(polygon[i][0]<border_points[0][0]){\n                border_points[0][0]=polygon[i][0];\n                border_points[0][1]=polygon[i][1];\n            }\n            // 下侧点判断\n            if(polygon[i][1]<border_points[1][1]){\n                border_points[1][0]=polygon[i][0];\n                border_points[1][1]=polygon[i][1];\n            }\n            // 右侧点判断\n            if(polygon[i][0]>border_points[2][0]){\n                border_points[2][0]=polygon[i][0];\n                border_points[2][1]=polygon[i][1];\n            }\n            // 上侧点判断\n            if(polygon[i][1]>border_points[3][1]){\n                border_points[3][0]=polygon[i][0];\n                border_points[3][1]=polygon[i][1];\n            }\n        };\n    };\n    \n    // 判断两个多边形是否重叠\n    static bool judgeOverlap(VectorPoints poly1,VectorPoints poly2){\n        Polygon Poly1,Poly2;\n        GeometryProcess::convertPoly(poly1,Poly1);\n        GeometryProcess::convertPoly(poly2,Poly2);\n        return intersects(Poly1, Poly2);\n    };\n    \n    // 获得两个多边形的重叠情况\n    static double overlapArea(VectorPoints poly1,VectorPoints poly2){\n        double overlap_area=0;\n        \n        Polygon Poly1,Poly2;\n        GeometryProcess::convertPoly(poly1,Poly1);\n        GeometryProcess::convertPoly(poly2,Poly2);\n        \n        // 获得重叠情况\n        deque<Polygon> output;\n        intersection(Poly1, Poly2, output);\n        \n        // 遍历计算重叠面积\n        BOOST_FOREACH(Polygon const& p, output)\n        {\n            overlap_area+=area(p);\n        }\n        if(overlap_area>BIAS){\n            return overlap_area;\n        }else{\n            return 0;\n        }\n    };\n    // 获得List对象的全部重叠\n    static double totalArea(list<Polygon> poly_list){\n        double total_area=0;\n        BOOST_FOREACH(Polygon const& p, poly_list)\n        {\n            total_area+=area(p);\n        }\n        return total_area;\n    };\n    // 获得当前排样的宽度\n    static double arrangetLenth(vector<VectorPoints> all_polys){\n        double length=0;\n        for(VectorPoints poly:all_polys){\n            vector<double> pt;\n            getRightPt(poly,pt);\n            if(pt[0]>length){\n                length=pt[0];\n            }\n        }\n        return length;\n    }\n};\n\n// 获得NFP\nclass NFPAssistant{\nprotected:\n    csv::Reader nfp_result;\n    int poly_num;\n    int orientation_num;\n    vector<VectorPoints> NPFs; // 存储全部的NFP，按行存储\npublic:\n    /*\n     预加载全部的NFP，直接转化到NFP中\n     */\n    NFPAssistant(string _path,int poly_num,int orientation_num){\n        nfp_result.read(_path);\n        this->poly_num=poly_num;\n        this->orientation_num=orientation_num;\n        cout<<\"加载全部NFP\"<<endl;\n        while(nfp_result.busy()) {\n            if (nfp_result.ready()) {\n                auto row = nfp_result.next_row();\n                VectorPoints nfp;\n                if(row[\"nfp\"]!=\"\"){\n                    DataAssistant::load2DVector(row[\"nfp\"],nfp);\n                    NPFs.push_back(nfp);\n                }\n            }\n        }\n    };\n    /*\n     读取NFP的确定行数，i为固定形状，j为非固定形状,oi/oj为形状\n     */\n    void getNFP(int i,int j, int oi, int oj, VectorPoints poly_j ,VectorPoints &nfp){\n        // 获得原始的NFP\n        int row_num= i*192+j*16+oi*4+oj;\n        nfp=NPFs[row_num];\n        // 将NFP移到目标位置\n        vector<double> bottom_pt;\n        PackingAssistant::getBottomPt(poly_j,bottom_pt);\n        PackingAssistant::slidePoly(nfp,bottom_pt[0],bottom_pt[1]);\n    }\n};\n\n// 处理多个多边形的关系\nclass PolygonsOperator{\npublic:\n    // 计算多边形的差集合\n    static void polysDifference(list<Polygon> &feasible_region, Polygon sub_region){\n        // 逐一遍历求解重叠\n        list<Polygon> new_feasible_region;\n        for(auto region_item:feasible_region){\n            list<Polygon> output;\n            difference(region_item, sub_region, output);\n            DataAssistant::appendList(new_feasible_region,output);\n        };\n        // 将新的Output全部输入进去\n        feasible_region.clear();\n        copy(new_feasible_region.begin(), new_feasible_region.end(), back_inserter(feasible_region));\n    }\n    // 逐一遍历求差集\n    static void polyListDifference(list<Polygon> &feasible_region, list<Polygon> sub_region){\n        for(auto region_item:sub_region){\n            polysDifference(feasible_region,region_item);\n        }\n    }\n    // List和一个Poly的差集\n    static void listToPolyIntersection(list<Polygon> region_list, Polygon region, list<Polygon> &inter_region){\n        for(auto region_item:region_list){\n            list<Polygon> output;\n            intersection(region_item, region, output);\n            DataAssistant::appendList(inter_region,output);\n        }\n    }\n    // List和List之间的交集\n    static void listToListIntersection(list<Polygon> region1, list<Polygon> region2, list<Polygon> &inter_region){\n        for(auto region_item1:region1){\n            for(auto region_item2:region2){\n                list<Polygon> output;\n                intersection(region_item1, region_item2, output);\n                DataAssistant::appendList(inter_region,output);\n            }\n        }\n    }\n    // 判断某个List是否为空\n    static bool judgeListEmpty(list<Polygon> poly_list){\n        for(auto item:poly_list){\n            if(area(item)>BIAS){\n                return false;\n            }\n        }\n        return true;\n    }\n    // 计算多边形的交集\n    void polysUnion(){\n        // 测试基础\n        Polygon green, blue;\n\n        vector<Polygon> output;\n        union_(green, blue, output);\n\n        int i = 0;\n        cout << \"green || blue:\" << endl;\n        BOOST_FOREACH(Polygon const& p, output)\n        {\n            cout << i++ << \": \" << area(p) << endl;\n        }\n    }\n    /*\n     List数组的增长\n     */\n    static void appendPolyList(list<Polygon> &old_list,list<Polygon> &new_list){\n        for(auto item:new_list){\n            if(area(item)>BIAS){\n                Polygon new_item;\n                PolygonsOperator::convertToFeasible(new_item,item);\n                old_list.push_back(new_item);\n            }\n        }\n    }\n    /*\n     将不可行转化为可行\n     */\n    static void convertToFeasible(Polygon new_item,Polygon item){\n        // 确认所有的点\n        VectorPoints all_points;\n        VectorPoints new_all_points;\n        GeometryProcess::getGemotryPoints(item,all_points);\n        // 判断点是否重叠了\n        for(int i = 0; i < all_points.size(); i++){\n            VectorPoints line1, line2;\n            line1 = {all_points[i], all_points[i+1]};\n            if(i == all_points.size() - 1){\n                line2 = {all_points[0], all_points[1]};\n            }else if (i == all_points.size() - 2){\n                line2 = {all_points[i+1], all_points[0]};\n            }else{\n                line2 = {all_points[i+1], all_points[i+2]};\n            }\n            // 首先判断垂直情况\n            double delta_x1, delta_y1, delta_x2, delta_y2;\n            delta_x1 = line1[1][0] - line1[0][0];\n            delta_y1 = line1[1][1] - line1[0][1];\n            delta_x2 = line2[1][0] - line2[0][0];\n            delta_y2 = line2[1][1] - line2[0][1];\n            if(delta_x1 < BIAS && delta_x2 < BIAS){\n                continue;\n            }else if(delta_x1 < BIAS || delta_x2 < BIAS){\n                new_all_points.push_back(all_points[i+1]);\n            }else{\n                // 判断非垂直情况\n                double k1 = delta_y1/delta_x1;\n                double k2 = delta_y2/delta_x2;\n                if(abs(abs(k1) - abs(k2)) < BIAS){\n                    continue;\n                }\n            }\n        }\n    }\n};\n", "meta": {"hexsha": "a8547b232c466400a6a3c7c5b8447419fa8a4db5", "size": 14158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++ Nesting Problem/Nesting Problem/geometry.cpp", "max_stars_repo_name": "seanys/2D-Irregular-Packing-Algorithm", "max_stars_repo_head_hexsha": "cc10edff2bc2631fcbcb47acf7bb3215e5c5023c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T06:41:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T18:04:07.000Z", "max_issues_repo_path": "C++ Nesting Problem/Nesting Problem/geometry.cpp", "max_issues_repo_name": "seanys/2D-Irregular-Packing-Algorithm", "max_issues_repo_head_hexsha": "cc10edff2bc2631fcbcb47acf7bb3215e5c5023c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T01:36:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T11:59:05.000Z", "max_forks_repo_path": "C++ Nesting Problem/Nesting Problem/geometry.cpp", "max_forks_repo_name": "seanys/2D-Irregular-Packing-Algorithm", "max_forks_repo_head_hexsha": "cc10edff2bc2631fcbcb47acf7bb3215e5c5023c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T05:34:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T07:32:46.000Z", "avg_line_length": 31.6026785714, "max_line_length": 114, "alphanum_fraction": 0.5691481848, "num_tokens": 4044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.558938875401527}}
{"text": "// -*- coding: utf-8 -*-\r\n#pragma once\r\n\r\n#include <cassert>\r\n#include <cmath>\r\n#include <tuple>\r\n\r\n#include \"cut_config.hpp\"\r\n#include \"half_nonnegative.hpp\"\r\n\r\n/**\r\n * @brief Find a point in a convex set (defined through a cutting-plane oracle).\r\n *\r\n *     A function f(x) is *convex* if there always exist a g(x)\r\n *     such that f(z) >= f(x) + g(x)' * (z - x), forall z, x in dom f.\r\n *     Note that dom f does not need to be a convex set in our definition.\r\n *     The affine function g' (x - xc) + beta is called a cutting-plane,\r\n *     or a ``cut'' for short.\r\n *     This algorithm solves the following feasibility problem:\r\n *\r\n *             find x\r\n *             s.t. f(x) <= 0,\r\n *\r\n *     A *separation oracle* asserts that an evalution point x0 is feasible,\r\n *     or provide a cut that separates the feasible region and x0.\r\n *\r\n * @tparam Oracle\r\n * @tparam Space\r\n * @param[in,out] Omega perform assessment on x0\r\n * @param[in,out] S     search Space containing x*\r\n * @param[in] options   maximum iteration and error tolerance etc.\r\n * @return Information of Cutting-plane method\r\n */\r\ntemplate <typename Oracle, typename Space>\r\nauto cutting_plane_feas(Oracle&& Omega, Space&& S, const Options& options = Options()) -> CInfo {\r\n    auto feasible = false;\r\n    auto status = CUTStatus::success;\r\n\r\n    auto niter = 0U;\r\n    while (++niter != options.max_it) {\r\n        const auto cut = Omega(S.xc());  // query the oracle at S.xc()\r\n        if (!cut) {                      // feasible sol'n obtained\r\n            feasible = true;\r\n            break;\r\n        }\r\n        const auto result = S.update(*cut);  // update S\r\n\r\n        const auto& cutstatus = std::get<0>(result);\r\n        const auto& tsq = std::get<1>(result);\r\n        if (cutstatus != CUTStatus::success) {\r\n            status = cutstatus;\r\n            break;\r\n        }\r\n        if (tsq < options.tol) {  // no more\r\n            status = CUTStatus::smallenough;\r\n            break;\r\n        }\r\n    }\r\n    return {feasible, niter, status};\r\n}\r\n\r\n/**\r\n * @brief Cutting-plane method for solving convex problem\r\n *\r\n * @tparam Oracle\r\n * @tparam Space\r\n * @tparam opt_type\r\n * @param[in,out] Omega perform assessment on x0\r\n * @param[in,out] S     search Space containing x*\r\n * @param[in,out] t     best-so-far optimal sol'n\r\n * @param[in] options   maximum iteration and error tolerance etc.\r\n * @return Information of Cutting-plane method\r\n */\r\ntemplate <typename Oracle, typename Space, typename opt_type>\r\nauto cutting_plane_dc(Oracle&& Omega, Space&& S, opt_type&& t, const Options& options = Options()) {\r\n    const auto t_orig = t;\r\n    decltype(S.xc()) x_best;\r\n    auto status = CUTStatus::success;\r\n\r\n    auto niter = 0U;\r\n    while (++niter != options.max_it) {\r\n        const auto result1 = Omega(S.xc(), t);\r\n        const auto& cut = std::get<0>(result1);\r\n        const auto& shrunk = std::get<1>(result1);\r\n        if (shrunk) {  // best t obtained\r\n            x_best = S.xc();\r\n        }\r\n        const auto result2 = S.update(cut);\r\n\r\n        const auto& cutstatus = std::get<0>(result2);\r\n        const auto& tsq = std::get<1>(result2);\r\n        if (cutstatus != CUTStatus::success)  // ???\r\n        {\r\n            status = cutstatus;\r\n            break;\r\n        }\r\n        if (tsq < options.tol) {  // no more\r\n            status = CUTStatus::smallenough;\r\n            break;\r\n        }\r\n    }\r\n    return std::make_tuple(std::move(x_best), CInfo{t != t_orig, niter, status});\r\n}  // END\r\n\r\n/**\r\n    Cutting-plane method for solving convex discrete optimization problem\r\n    input\r\n             oracle        perform assessment on x0\r\n             S(xc)         Search space containing x*\r\n             t             best-so-far optimal sol'n\r\n             max_it        maximum number of iterations\r\n             tol           error tolerance\r\n    output\r\n             x             solution vector\r\n             niter          number of iterations performed\r\n**/\r\n// #include <boost/numeric/ublas/symmetric.hpp>\r\n// namespace bnu = boost::numeric::ublas;\r\n// #include <xtensor-blas/xlinalg.hpp>\r\n// #include <xtensor/xarray.hpp>\r\n\r\n/**\r\n * @brief Cutting-plane method for solving convex discrete optimization problem\r\n *\r\n * @tparam Oracle\r\n * @tparam Space\r\n * @param[in,out] Omega perform assessment on x0\r\n * @param[in,out] S     search Space containing x*\r\n * @param[in,out] t     best-so-far optimal sol'n\r\n * @param[in] options   maximum iteration and error tolerance etc.\r\n * @return Information of Cutting-plane method\r\n */\r\ntemplate <typename Oracle, typename Space, typename opt_type>\r\nauto cutting_plane_q(Oracle&& Omega, Space&& S, opt_type&& t, const Options& options = Options()) {\r\n    const auto t_orig = t;\r\n    decltype(S.xc()) x_best;\r\n    auto status = CUTStatus::nosoln;  // note!!!\r\n    auto retry = (status == CUTStatus::noeffect);\r\n\r\n    auto niter = 0U;\r\n    while (++niter != options.max_it) {\r\n        // auto retry = (status == CUTStatus::noeffect);\r\n        const auto result1 = Omega(S.xc(), t, retry);\r\n        const auto& cut = std::get<0>(result1);\r\n        const auto& shrunk = std::get<1>(result1);\r\n        const auto& x0 = std::get<2>(result1);\r\n        const auto& more_alt = std::get<3>(result1);\r\n        if (shrunk) {  // best t obtained\r\n            // t = t1;\r\n            x_best = x0;  // x0\r\n        }\r\n        const auto result2 = S.update(cut);\r\n        const auto& cutstatus = std::get<0>(result2);\r\n        const auto& tsq = std::get<1>(result2);\r\n\r\n        if (cutstatus == CUTStatus::noeffect) {\r\n            if (!more_alt) {  // more alt?\r\n                break;        // no more alternative cut\r\n            }\r\n            status = cutstatus;\r\n            retry = true;\r\n        }\r\n        if (cutstatus == CUTStatus::nosoln) {\r\n            status = cutstatus;\r\n            break;\r\n        }\r\n        if (tsq < options.tol) {\r\n            status = CUTStatus::smallenough;\r\n            break;\r\n        }\r\n    }\r\n    return std::make_tuple(std::move(x_best), CInfo{t != t_orig, niter, status});\r\n}  // END\r\n\r\n/**\r\n * @brief\r\n *\r\n * @tparam Oracle\r\n * @tparam Space\r\n * @param[in,out] Omega    perform assessment on x0\r\n * @param[in,out] I        interval containing x*\r\n * @param[in]     options  maximum iteration and error tolerance etc.\r\n * @return CInfo\r\n */\r\ntemplate <typename Oracle, typename Space>\r\nauto bsearch(Oracle&& Omega, Space&& I, const Options& options = Options()) -> CInfo {\r\n    // assume monotone\r\n    // auto& [lower, upper] = I;\r\n    auto& lower = I.first;\r\n    auto& upper = I.second;\r\n    assert(lower <= upper);\r\n    const auto u_orig = upper;\r\n    auto niter = 0U;\r\n    auto status = CUTStatus::success;\r\n\r\n    for (; niter != options.max_it; ++niter) {\r\n        auto tau = algo::half_nonnegative(upper - lower);\r\n        if (tau < options.tol) {\r\n            status = CUTStatus::smallenough;\r\n            break;\r\n        }\r\n\r\n        auto t = lower;  // l may be `int` or `Fraction`\r\n        t += tau;\r\n        if (Omega(t)) {  // feasible sol'n obtained\r\n            upper = t;\r\n        } else {\r\n            lower = t;\r\n        }\r\n    }\r\n    return {upper != u_orig, niter + 1, status};\r\n}\r\n\r\n/**\r\n * @brief\r\n *\r\n * @tparam Oracle\r\n * @tparam Space\r\n */\r\ntemplate <typename Oracle, typename Space>  //\r\nclass bsearch_adaptor {\r\n  private:\r\n    Oracle& _P;\r\n    Space& _S;\r\n    const Options _options;\r\n\r\n  public:\r\n    /**\r\n     * @brief Construct a new bsearch adaptor object\r\n     *\r\n     * @param[in,out] P perform assessment on x0\r\n     * @param[in,out] S search Space containing x*\r\n     */\r\n    bsearch_adaptor(Oracle& P, Space& S) : bsearch_adaptor{P, S, Options()} {}\r\n\r\n    /**\r\n     * @brief Construct a new bsearch adaptor object\r\n     *\r\n     * @param[in,out] P perform assessment on x0\r\n     * @param[in,out] S search Space containing x*\r\n     * @param[in] options maximum iteration and error tolerance etc.\r\n     */\r\n    bsearch_adaptor(Oracle& P, Space& S, const Options& options)\r\n        : _P{P}, _S{S}, _options{options} {}\r\n\r\n    /**\r\n     * @brief get best x\r\n     *\r\n     * @return auto\r\n     */\r\n    auto x_best() const { return this->_S.xc(); }\r\n\r\n    /**\r\n     * @brief\r\n     *\r\n     * @param[in,out] t the best-so-far optimal value\r\n     * @return bool\r\n     */\r\n    template <typename opt_type> auto operator()(const opt_type& t) -> bool {\r\n        Space S = this->_S.copy();\r\n        this->_P.update(t);\r\n        const auto ell_info = cutting_plane_feas(this->_P, S, this->_options);\r\n        if (ell_info.feasible) {\r\n            this->_S.set_xc(S.xc());\r\n        }\r\n        return ell_info.feasible;\r\n    }\r\n};\r\n", "meta": {"hexsha": "7fcca042ecbaf63025258d0852a4d1cc917a1c45", "size": 8636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ellalgo/cutting_plane.hpp", "max_stars_repo_name": "luk036/ellalgo-cpp", "max_stars_repo_head_hexsha": "639bfb23baaf2440ea2b68b58e4799e08ce417ed", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ellalgo/cutting_plane.hpp", "max_issues_repo_name": "luk036/ellalgo-cpp", "max_issues_repo_head_hexsha": "639bfb23baaf2440ea2b68b58e4799e08ce417ed", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ellalgo/cutting_plane.hpp", "max_forks_repo_name": "luk036/ellalgo-cpp", "max_forks_repo_head_hexsha": "639bfb23baaf2440ea2b68b58e4799e08ce417ed", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1040892193, "max_line_length": 101, "alphanum_fraction": 0.5575497916, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.5589231788856345}}
{"text": "/********************************************************************************\n * Copyright 2017 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_GEOMETRY_HYPERSPHERE_HPP_\n#define RW_GEOMETRY_HYPERSPHERE_HPP_\n\n/**\n * @file HyperSphere.hpp\n *\n * \\copydoc rw::geometry::HyperSphere\n */\n\n#if !defined(SWIG)\n#include <rw/core/Ptr.hpp>\n\n#include <Eigen/Core>\n#include <vector>\n#endif\n\nnamespace rw { namespace geometry {\n    //! @addtogroup geometry\n#if !defined(SWIG)\n    //! @{\n#endif\n    /**\n     * @brief A hyper-sphere of K dimensions.\n     *\n     * Functions are provided to create (almost) uniform distribution of points on a hyper-sphere as\n     * shown in [1].\n     *\n     * The distribution of points is illustrated below for 2 and 3 dimensional hyper-spheres.\n     * Notice that the tessellation is best when \\f$ \\delta\\f$ is small.\n     *\n     * \\image html geometry/hypersphere.gif \"Distribution of points for K=2 and K=3.\"\n     *\n     * [1] Lovisolo, L., and E. A. B. Da Silva. \"Uniform distribution of points on a hyper-sphere\n     * with applications to vector bit-plane encoding.\" IEE Proceedings-Vision, Image and Signal\n     * Processing 148.3 (2001): 187-193.\n     */\n    class HyperSphere\n    {\n      public:\n        //! @brief Smart pointer type for HyperSphere.\n        typedef rw::core::Ptr< const HyperSphere > Ptr;\n\n        /**\n         * @brief Construct a hyper-sphere of unit size.\n         * @param dimensions [in] the number of dimensions.\n         */\n        HyperSphere (unsigned int dimensions);\n\n        //! @brief Destructor.\n        virtual ~HyperSphere ();\n\n        /**\n         * @brief Create a uniform distribution in Cartesian coordinates.\n         *\n         * This uses #uniformDistributionSpherical and maps the spherical coordinates to Cartesian\n         * coordinates. The mapping is documented in [1], section 2.1.\n         *\n         * @param delta [in] the resolution.\n         * @return unit vectors, \\f$ [x_1 x_2 \\dots x_K]^T\\f$ , in Cartesian coordinates with\n         * dimension K.\n         * @note This function is only implemented for \\f$ 2 \\leq K \\leq 6\\f$ .\n         */\n        std::vector< Eigen::VectorXd > uniformDistributionCartesian (double delta) const;\n\n        /**\n         * @brief Create a uniform distribution in spherical coordinates.\n         *\n         * This implements the algorithm in [1], section 2.1, for dimensions \\f$ 2 \\leq K \\leq 6\\f$\n         * .\n         *\n         * @param delta [in] the resolution.\n         * @return list of vectors, \\f$ [\\theta_1 \\theta_2 \\dots \\theta_{K-1}]^T\\f$ , in spherical\n         * coordinates with dimension K-1.\n         * @note This function is only implemented for \\f$ 2 \\leq K \\leq 6\\f$ .\n         */\n        std::vector< Eigen::VectorXd > uniformDistributionSpherical (double delta) const;\n\n        /**\n         * @brief Get the number of dimensions of the hyper-sphere.\n         * @return the number of dimensions, \\f$ 2 \\leq K \\leq 6\\f$ .\n         */\n        unsigned int getDimensions () const;\n\n        /**\n         * @brief Calculate the surface area of a hyper-sphere.\n         *\n         * Calculated for even dimensionality as \\f$ \\frac{K \\pi^{K/2}}{(K/2)!}\\f$\n         *\n         * Calculated for odd dimensionality as \\f$ \\frac{K 2^K \\pi^{(K-1)/2}}{K!}\\f$\n         *\n         * @return the surface area.\n         */\n        double area () const;\n\n        /**\n         * @brief The volume of a hyper-sphere.\n         *\n         * Calculated for even dimensionality as \\f$ \\frac{\\pi^{K/2}}{(K/2)!}\\f$\n         *\n         * Calculated for odd dimensionality as \\f$ \\frac{2 (2 \\pi)^{(K-1)/2}}{K!!}\\f$\n         * where the double factorial for odd K means \\f$ 1 \\cdot 3 \\cdot 5 \\dots K\\f$\n         *\n         * @return the volume.\n         */\n        double volume () const;\n\n      private:\n        const unsigned int _dimensions;\n    };\n#if !defined(SWIG)\n//! @}\n#endif\n}}    // namespace rw::geometry\n\n#endif /* RW_GEOMETRY_HYPERSPHERE_HPP_ */\n", "meta": {"hexsha": "11de98a3ecb916b0f6bb77d690c8ade98f1b1d39", "size": 4690, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/geometry/HyperSphere.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/geometry/HyperSphere.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/geometry/HyperSphere.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": 35.2631578947, "max_line_length": 100, "alphanum_fraction": 0.5901918977, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.558871682614905}}
{"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 \"coefficient_computations.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>\n#include \"nanoflann.hpp\"\nusing namespace std;\n\nCLOUD::CLOUD(POINTS &points, PARAMETERS &parameters)\n{\n    clock_t clock_t1 = clock();\n    if (parameters.periodic_bc_index.size() == 0)\n        calc_cloud_points_fast(points, parameters); //non-periodic case\n    else\n        calc_cloud_points_fast_periodic_bc(points, parameters);\n    parameters.cloud_id_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n    clock_t1 = clock();\n    re_order_points_reverse_cuthill_mckee(points, parameters);\n    parameters.rcm_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n    clock_t1 = clock();\n    calc_iv_original_nearest_vert(points, parameters);\n    calc_charac_dx(points, parameters);\n    parameters.cloud_misc_timer = ((double)(clock() - clock_t1)) / CLOCKS_PER_SEC;\n    calc_grad_laplace_coeffs(points, parameters);\n    EIGEN_set_grad_laplace_matrix(points, parameters);\n    EIGEN_set_grad_laplace_matrix_separate(points, parameters);\n    cout << \"\\n\";\n}\n\nvoid CLOUD::calc_iv_original_nearest_vert(POINTS &points, PARAMETERS &parameters)\n{\n    for (int iv0 = 0; iv0 < points.nv_original; iv0++)\n        points.iv_original_nearest_vert.push_back(-1);\n    double x0, y0, z0 = 0.0, x1, y1, z1 = 0.0, dist_square, temp;\n    int dim = parameters.dimension, iv_nearest, offset = 0;\n    for (int iv0 = 0; iv0 < points.nv_original; iv0++)\n    {\n        if (points.corner_edge_vertices[iv0])\n        { //these points are deleted; thus, nearest vertex has to be found\n            x0 = points.xyz_original[dim * iv0], y0 = points.xyz_original[dim * iv0 + 1];\n            if (dim == 3)\n                z0 = points.xyz_original[dim * iv0 + 2];\n            dist_square = INFINITY;\n            for (int iv1 = 0; iv1 < points.nv; iv1++)\n            {\n                // if (points.boundary_flag[iv1])\n                // { //[boundary points coupled to boundary]\n                x1 = points.xyz[dim * iv1], y1 = points.xyz[dim * iv1 + 1];\n                if (dim == 3)\n                    z1 = points.xyz[dim * iv1 + 2];\n                temp = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0) + (z1 - z0) * (z1 - z0);\n                if (dist_square >= temp)\n                {\n                    dist_square = temp;\n                    points.iv_original_nearest_vert[iv0] = iv1;\n                }\n                // }\n            }\n            offset++; //deleted vertices are offset\n        }\n        else\n        {\n            iv_nearest = rcm_points_order[iv0 - offset];\n            points.iv_original_nearest_vert[iv0] = iv_nearest;\n        }\n    }\n}\n\nvoid CLOUD::EIGEN_set_grad_laplace_matrix_separate(POINTS &points, PARAMETERS &parameters)\n{\n    vector<Eigen::Triplet<double>> triplet;\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_x_coeff[i1]));\n    points.grad_x_matrix_EIGEN_boundary.resize(points.nv, points.nv);\n    points.grad_x_matrix_EIGEN_boundary.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_x_matrix_EIGEN_boundary.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_x_coeff[i1]));\n    points.grad_x_matrix_EIGEN_internal.resize(points.nv, points.nv);\n    points.grad_x_matrix_EIGEN_internal.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_x_matrix_EIGEN_internal.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_y_coeff[i1]));\n    points.grad_y_matrix_EIGEN_boundary.resize(points.nv, points.nv);\n    points.grad_y_matrix_EIGEN_boundary.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_y_matrix_EIGEN_boundary.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_y_coeff[i1]));\n    points.grad_y_matrix_EIGEN_internal.resize(points.nv, points.nv);\n    points.grad_y_matrix_EIGEN_internal.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_y_matrix_EIGEN_internal.makeCompressed();\n    triplet.clear();\n\n    if (parameters.dimension == 3)\n    {\n        for (int iv = 0; iv < points.nv; iv++)\n            if (points.boundary_flag[iv])\n                for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                    triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_z_coeff[i1]));\n        points.grad_z_matrix_EIGEN_boundary.resize(points.nv, points.nv);\n        points.grad_z_matrix_EIGEN_boundary.setFromTriplets(triplet.begin(), triplet.end());\n        points.grad_z_matrix_EIGEN_boundary.makeCompressed();\n        triplet.clear();\n\n        for (int iv = 0; iv < points.nv; iv++)\n            if (!points.boundary_flag[iv])\n                for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                    triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_z_coeff[i1]));\n        points.grad_z_matrix_EIGEN_internal.resize(points.nv, points.nv);\n        points.grad_z_matrix_EIGEN_internal.setFromTriplets(triplet.begin(), triplet.end());\n        points.grad_z_matrix_EIGEN_internal.makeCompressed();\n        triplet.clear();\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], laplacian_coeff[i1]));\n    points.laplacian_matrix_EIGEN_boundary.resize(points.nv, points.nv);\n    points.laplacian_matrix_EIGEN_boundary.setFromTriplets(triplet.begin(), triplet.end());\n    points.laplacian_matrix_EIGEN_boundary.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv])\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], laplacian_coeff[i1]));\n    points.laplacian_matrix_EIGEN_internal.resize(points.nv, points.nv);\n    points.laplacian_matrix_EIGEN_internal.setFromTriplets(triplet.begin(), triplet.end());\n    points.laplacian_matrix_EIGEN_internal.makeCompressed();\n    triplet.clear();\n}\n\nvoid CLOUD::EIGEN_set_grad_laplace_matrix(POINTS &points, PARAMETERS &parameters)\n{\n    vector<Eigen::Triplet<double>> triplet;\n    for (int iv = 0; iv < points.nv; iv++)\n        for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n            triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_x_coeff[i1]));\n    points.grad_x_matrix_EIGEN.resize(points.nv, points.nv);\n    points.grad_x_matrix_EIGEN.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_x_matrix_EIGEN.makeCompressed();\n    triplet.clear();\n\n    for (int iv = 0; iv < points.nv; iv++)\n        for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n            triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_y_coeff[i1]));\n    points.grad_y_matrix_EIGEN.resize(points.nv, points.nv);\n    points.grad_y_matrix_EIGEN.setFromTriplets(triplet.begin(), triplet.end());\n    points.grad_y_matrix_EIGEN.makeCompressed();\n    triplet.clear();\n\n    if (parameters.dimension == 3)\n    {\n        for (int iv = 0; iv < points.nv; iv++)\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n                triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], grad_z_coeff[i1]));\n        points.grad_z_matrix_EIGEN.resize(points.nv, points.nv);\n        points.grad_z_matrix_EIGEN.setFromTriplets(triplet.begin(), triplet.end());\n        points.grad_z_matrix_EIGEN.makeCompressed();\n        triplet.clear();\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n            triplet.push_back(Eigen::Triplet<double>(iv, nb_points_col[i1], laplacian_coeff[i1]));\n    points.laplacian_matrix_EIGEN.resize(points.nv, points.nv);\n    points.laplacian_matrix_EIGEN.setFromTriplets(triplet.begin(), triplet.end());\n    points.laplacian_matrix_EIGEN.makeCompressed();\n    triplet.clear();\n}\n\nvoid CLOUD::calc_grad_laplace_coeffs(POINTS &points, PARAMETERS &parameters)\n{\n    clock_t t1 = clock(), t2, t3, t4 = clock();\n    vector<double> vert;\n    vector<int> central_vert_list;\n    Eigen::MatrixXd laplacian, grad_x, grad_y, grad_z;\n    int dim = parameters.dimension, iv_nb, i1;\n    vector<int> ind_p = parameters.periodic_bc_index, iv_sect;\n    central_vert_list.push_back(0);\n    double scale[3], time, cond_num, xyz_temp[3];\n    t3 = clock();\n    cout << endl;\n    printf(\"    CLOUD::calc_grad_laplace_coeffs started prints status after every 5 seconds\\n\");\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        t2 = clock();\n        central_vert_list[0] = 0;                     //coefficient for first vertex needed\n        if (parameters.periodic_bc_index.size() == 0) //non-periodic case\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n            {\n                iv_nb = nb_points_col[i1];\n                for (int i = 0; i < dim; i++)\n                    vert.push_back(points.xyz[dim * iv_nb + i]);\n            }\n        else\n        {\n            iv_sect = points.periodic_bc_section[iv];\n            for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n            {\n                iv_nb = nb_points_col[i1];\n                for (int id = 0; id < dim; id++)\n                    xyz_temp[id] = points.xyz[dim * iv_nb + id];\n                for (int ip = 0; ip < ind_p.size(); ip++)\n                    if (points.periodic_bc_section[iv_nb][ip] == (-iv_sect[ip])) //shift opposite section (nothing happens for iv_sect=0)\n                        xyz_temp[ind_p[ip]] = xyz_temp[ind_p[ip]] + (((double)(iv_sect[ip])) * points.xyz_length[ind_p[ip]]);\n                for (int id = 0; id < dim; id++)\n                    vert.push_back(xyz_temp[id]);\n            }\n        }\n        shifting_scaling(vert, scale, dim);\n        cond_num = calc_PHS_RBF_grad_laplace_single_vert(vert, parameters, laplacian, grad_x, grad_y, grad_z, scale, central_vert_list);\n        cond_num_RBF.push_back(cond_num);\n        vert.clear();\n\n        for (int i1 = 0; i1 < laplacian.size(); i1++)\n        { //(nb_points_row[iv + 1] - nb_points_row[iv]) = laplacian.size()\n            grad_x_coeff.push_back(grad_x(0, i1));\n            grad_y_coeff.push_back(grad_y(0, i1));\n            if (dim == 3)\n                grad_z_coeff.push_back(grad_z(0, i1));\n            laplacian_coeff.push_back(laplacian(0, i1));\n        }\n\n        time = ((double)(clock() - t3)) / CLOCKS_PER_SEC;\n        if (time > 5.0)\n        {\n            printf(\"    CLOUD::calc_grad_laplace_coeffs iv: %i, nv: %i: completed %.2f percent in %g seconds\\n\", iv, points.nv, 100.0 * iv / points.nv, ((double)(clock() - t1)) / CLOCKS_PER_SEC);\n            t3 = clock();\n        }\n    }\n    cout << endl;\n    laplacian.resize(0, 0); //free memory\n    grad_x.resize(0, 0);    //free memory\n    grad_y.resize(0, 0);    //free memory\n    grad_z.resize(0, 0);    //free memory\n\n    cond_num_RBF_max = *max_element(cond_num_RBF.begin(), cond_num_RBF.end());\n    cond_num_RBF_min = *min_element(cond_num_RBF.begin(), cond_num_RBF.end());\n    cond_num_RBF_avg = accumulate(cond_num_RBF.begin(), cond_num_RBF.end(), 0.0) / cond_num_RBF.size();\n    printf(\"CLOUD::calc_grad_laplace_coeffs RBF condition number max: %g, min: %g, avg: %g\\n\", cond_num_RBF_max, cond_num_RBF_min, cond_num_RBF_avg);\n    parameters.grad_laplace_coeff_timer = ((double)(clock() - t4)) / CLOCKS_PER_SEC;\n    printf(\"CLOUD::calc_grad_laplace_coeffs total grad_laplace_coeff time: %g seconds\\n\", parameters.grad_laplace_coeff_timer);\n}\n\nvoid CLOUD::calc_charac_dx(POINTS &points, PARAMETERS &parameters)\n{\n    parameters.avg_dx = 0.0;\n    parameters.max_dx = 0.0;\n    parameters.min_dx = 1E20;\n    double local_min_dx, delx, dely, delz = 0.0, dist;\n    int iv_nb, isd, dim = parameters.dimension;\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        local_min_dx = 1E20;\n        for (int i1 = nb_points_row[iv]; i1 < nb_points_row[iv + 1]; i1++)\n        {\n            iv_nb = nb_points_col[i1];\n            if (iv != iv_nb)\n            {\n                delx = points.xyz[dim * iv] - points.xyz[dim * iv_nb];\n                dely = points.xyz[dim * iv + 1] - points.xyz[dim * iv_nb + 1];\n                if (dim == 3)\n                    delz = points.xyz[dim * iv + 2] - points.xyz[dim * iv_nb + 2];\n                dist = sqrt(delx * delx + dely * dely + delz * delz);\n                if (local_min_dx > dist)\n                    local_min_dx = dist;\n            }\n        }\n        parameters.avg_dx += local_min_dx;\n        if (parameters.min_dx > local_min_dx)\n            parameters.min_dx = local_min_dx;\n        if (parameters.max_dx < local_min_dx)\n            parameters.max_dx = local_min_dx;\n    }\n    parameters.avg_dx = parameters.avg_dx / ((double)(points.nv));\n    printf(\"CLOUD::calc_charac_dx Characteristic mesh dx max: %g, min: %g, avg: %g\\n\", parameters.max_dx, parameters.min_dx, parameters.avg_dx);\n}\n\nvoid CLOUD::re_order_points_reverse_cuthill_mckee(POINTS &points, PARAMETERS &parameters)\n{\n    vector<int> temp;\n    vector<vector<int>> points_adjacency;\n    int iv_1, iv_2;\n    for (int iv = 0; iv < points.nv; iv++)\n        points_adjacency.push_back(temp); //pushback dummy empty vector\n    for (iv_1 = 0; iv_1 < points.nv; iv_1++)\n    {\n        for (int i1 = nb_points_row[iv_1]; i1 < nb_points_row[iv_1 + 1]; i1++)\n        {\n            iv_2 = nb_points_col[i1];\n            points_adjacency[iv_1].push_back(iv_2);\n        }\n    }\n    reverse_cuthill_mckee_ordering(points_adjacency, rcm_points_order);\n    re_order_points(points, parameters);\n\n    for (int iv = 0; iv < points.nv; iv++)\n        points_adjacency[iv].clear();\n    points_adjacency.clear();\n}\n\nvoid CLOUD::re_order_points(POINTS &points, PARAMETERS &parameters)\n{\n    vector<int> bc_tag_copy;\n    vector<double> xyz_copy, normal_copy;\n    vector<bool> boundary_flag_copy;\n    vector<vector<int>> nb_points_copy, nb_points;\n\n    int new_iv, dim = parameters.dimension;\n\n    xyz_copy = points.xyz;\n    for (int iv = 0; iv < points.nv; iv++)\n    { //copy xyz co-ordinates\n        new_iv = rcm_points_order[iv];\n        for (int i = 0; i < dim; i++)\n            xyz_copy[dim * new_iv + i] = points.xyz[dim * iv + i];\n    }\n    points.xyz = xyz_copy; //update xyz co-ordinates\n    xyz_copy.clear();\n\n    if (parameters.periodic_bc_index.size() > 0)\n    {\n        vector<vector<int>> periodic_bc_section_copy;\n        periodic_bc_section_copy = points.periodic_bc_section;\n        for (int iv = 0; iv < points.nv; iv++)\n        { //copy periodic_bc_section\n            new_iv = rcm_points_order[iv];\n            periodic_bc_section_copy[new_iv] = points.periodic_bc_section[iv];\n        }\n        points.periodic_bc_section = periodic_bc_section_copy; //update periodic_bc_section\n        for (int iv = 0; iv < points.nv; iv++)\n            periodic_bc_section_copy[iv].clear();\n        periodic_bc_section_copy.clear();\n\n        vector<vector<bool>> periodic_bc_flag_copy;\n        periodic_bc_flag_copy = points.periodic_bc_flag;\n        for (int iv = 0; iv < points.nv; iv++)\n        { //copy periodic_bc_flag\n            new_iv = rcm_points_order[iv];\n            periodic_bc_flag_copy[new_iv] = points.periodic_bc_flag[iv];\n        }\n        points.periodic_bc_flag = periodic_bc_flag_copy; //update periodic_bc_flag\n        for (int iv = 0; iv < points.nv; iv++)\n            periodic_bc_flag_copy[iv].clear();\n        periodic_bc_flag_copy.clear();\n    }\n\n    normal_copy = points.normal;\n    for (int iv = 0; iv < points.nv; iv++)\n    { //copy normals\n        new_iv = rcm_points_order[iv];\n        for (int i = 0; i < dim; i++)\n            normal_copy[dim * new_iv + i] = points.normal[dim * iv + i];\n    }\n    points.normal = normal_copy; //update normal\n\n    bc_tag_copy = points.bc_tag;\n    for (int iv = 0; iv < points.nv; iv++)\n    { //copy bc_tag\n        new_iv = rcm_points_order[iv];\n        bc_tag_copy[new_iv] = points.bc_tag[iv];\n    }\n    points.bc_tag = bc_tag_copy; //update bc_tag\n    bc_tag_copy.clear();\n\n    boundary_flag_copy = points.boundary_flag;\n    for (int iv = 0; iv < points.nv; iv++)\n    { //copy boundary_flag\n        new_iv = rcm_points_order[iv];\n        boundary_flag_copy[new_iv] = points.boundary_flag[iv];\n    }\n    points.boundary_flag = boundary_flag_copy; //update boundary_flag\n    boundary_flag_copy.clear();\n\n    vector<int> temp;\n    for (int iv_1 = 0; iv_1 < points.nv; iv_1++)\n    {\n        nb_points.push_back(temp);      //initialize with empty vector\n        nb_points_copy.push_back(temp); //initialize with empty vector\n        for (int i1 = nb_points_row[iv_1]; i1 < nb_points_row[iv_1 + 1]; i1++)\n            nb_points[iv_1].push_back(rcm_points_order[nb_points_col[i1]]);\n    }\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        new_iv = rcm_points_order[iv];\n        nb_points_copy[new_iv] = nb_points[iv];\n    }\n    nb_points_row.clear();\n    nb_points_col.clear();\n    nb_points_row.push_back(0);\n    for (int iv0 = 0; iv0 < points.nv; iv0++)\n    {\n        nb_points_row.push_back(nb_points_row[iv0] + nb_points_copy[iv0].size());\n        nb_points_col.insert(nb_points_col.end(), nb_points_copy[iv0].begin(), nb_points_copy[iv0].end());\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        nb_points[iv].clear();\n    nb_points.clear();\n    for (int iv = 0; iv < points.nv; iv++)\n        nb_points_copy[iv].clear();\n    nb_points_copy.clear();\n}\n\nvoid CLOUD::calc_cloud_points_fast_periodic_bc_shifted(POINTS &points, PARAMETERS &parameters, vector<double> &xyz_shifted, vector<int> &periodic_bc_section_value)\n{\n    PointCloud<double> cloud_nf_for_interior, cloud_nf_for_boundary;\n    int dim = parameters.dimension, iv_nb;\n    vector<int> ind_p = parameters.periodic_bc_index;\n    cloud_nf_for_interior.pts.resize(points.nv), cloud_nf_for_boundary.pts.resize(points.nv);\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        cloud_nf_for_interior.pts[iv].x = xyz_shifted[dim * iv];\n        cloud_nf_for_interior.pts[iv].y = xyz_shifted[dim * iv + 1];\n        if (dim == 3)\n            cloud_nf_for_interior.pts[iv].z = xyz_shifted[dim * iv + 2];\n        else\n            cloud_nf_for_interior.pts[iv].z = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n    }\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (!points.boundary_flag[iv])\n        { //internal points are coupled with boundary points\n            cloud_nf_for_boundary.pts[iv].x = xyz_shifted[dim * iv];\n            cloud_nf_for_boundary.pts[iv].y = xyz_shifted[dim * iv + 1];\n            if (dim == 3)\n                cloud_nf_for_boundary.pts[iv].z = xyz_shifted[dim * iv + 2];\n            else\n                cloud_nf_for_boundary.pts[iv].z = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n        }\n        else\n        { //all boundary co-ordinates set to infinity so that they are never coupled with any boundary point\n            cloud_nf_for_boundary.pts[iv].x = numeric_limits<double>::infinity();\n            cloud_nf_for_boundary.pts[iv].y = numeric_limits<double>::infinity();\n            cloud_nf_for_boundary.pts[iv].z = numeric_limits<double>::infinity(); //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n        }\n    }\n    typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloud<double>>, PointCloud<double>, 3> nanoflann_kd_tree_for_interior;\n    nanoflann_kd_tree_for_interior index_for_interior(3, cloud_nf_for_interior, nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */));\n    index_for_interior.buildIndex();\n\n    typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloud<double>>, PointCloud<double>, 3> nanoflann_kd_tree_for_boundary;\n    nanoflann_kd_tree_for_boundary index_for_boundary(3, cloud_nf_for_boundary, nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */));\n    index_for_boundary.buildIndex();\n\n    vector<size_t> nb_vert(parameters.cloud_size);\n    vector<double> nb_dist(parameters.cloud_size);\n    double query_pt[3];\n    for (int iv = 0; iv < points.nv; iv++)\n        if (points.periodic_bc_section[iv] == periodic_bc_section_value)\n        {\n            query_pt[0] = xyz_shifted[dim * iv], query_pt[1] = xyz_shifted[dim * iv + 1];\n            if (dim == 3)\n                query_pt[2] = xyz_shifted[dim * iv + 2];\n            else\n                query_pt[2] = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n            if (points.boundary_flag[iv])\n            {\n                index_for_boundary.knnSearch(&query_pt[0], parameters.cloud_size, &nb_vert[0], &nb_dist[0]);\n                nb_points_col[nb_points_row[iv]] = iv;\n                for (int i1 = 0; i1 < nb_vert.size() - 1; i1++)\n                { //first entry is \"iv\": hence \"nb_vert.size() - 1\"\n                    iv_nb = nb_vert[i1];\n                    if (points.boundary_flag[iv_nb])\n                    {\n                        cout << \"\\n\\nERROR from CLOUD::calc_cloud_points_fast boundary iv: \" << iv << \" (boundary_flag[iv]: \" << points.boundary_flag[iv] << \") tried to couple to a boundary vertex: \" << iv_nb << \" (boundary_flag[iv_nb]: \" << points.boundary_flag[iv_nb] << \") \\n\\n\";\n                        throw bad_exception();\n                    }\n                    else\n                        nb_points_col[nb_points_row[iv] + i1 + 1] = iv_nb; //first entry is \"iv\"\n                }\n            }\n            else\n            { //internal points\n                index_for_interior.knnSearch(&query_pt[0], parameters.cloud_size, &nb_vert[0], &nb_dist[0]);\n                for (int i1 = 0; i1 < nb_vert.size(); i1++)\n                    nb_points_col[nb_points_row[iv] + i1] = nb_vert[i1];\n            }\n        }\n    cloud_nf_for_interior.pts.resize(0), cloud_nf_for_boundary.pts.resize(0);\n}\n\nvoid CLOUD::calc_cloud_points_fast_periodic_bc(POINTS &points, PARAMETERS &parameters)\n{ //Uses KD-Tree algorithm from Nanoflann (https://github.com/jlblancoc/nanoflann)\n    nb_points_row.push_back(0);\n    for (int iv = 0; iv < points.nv; iv++)\n        nb_points_row.push_back(nb_points_row[iv] + parameters.cloud_size);\n    for (int i1 = 0; i1 < points.nv * parameters.cloud_size; i1++)\n        nb_points_col.push_back(-1);\n    int dim = parameters.dimension;\n    vector<int> ind_p = parameters.periodic_bc_index, empty_int;\n\n    vector<vector<int>> section_list;\n    for (int i1 = 0; i1 < ((int)(pow(3, ind_p.size()))); i1++)\n        section_list.push_back(empty_int);\n    if (ind_p.size() == 1) //section_list = [[-1], [0], [1]]\n        section_list[0].push_back(-1), section_list[1].push_back(0), section_list[2].push_back(1);\n    else if (ind_p.size() == 2) //section_list = [[-1,-1], [-1,0], [-1,1], [0,-1], [0,0], [0,1], [1,-1], [1,0], [1,1]]\n        for (int i1 = 0; i1 < 3; i1++)\n            for (int i2 = 0; i2 < 3; i2++)\n                section_list[3 * i1 + i2].push_back(i1 - 1), section_list[3 * i1 + i2].push_back(i2 - 1);\n    else if (ind_p.size() == 3 && dim == 3)\n        for (int i1 = 0; i1 < 3; i1++)\n            for (int i2 = 0; i2 < 3; i2++)\n                for (int i3 = 0; i3 < 3; i3++)\n                {\n                    section_list[9 * i1 + 3 * i2 + i3].push_back(i1 - 1);\n                    section_list[9 * i1 + 3 * i2 + i3].push_back(i2 - 1);\n                    section_list[9 * i1 + 3 * i2 + i3].push_back(i3 - 1);\n                }\n    else\n    {\n        cout << \"\\n\\nCLOUD::calc_cloud_points_fast_periodic_bc number of periodic axes ind_p.size(): \" << ind_p.size() << \" should not be greater than problem dimension: \" << dim << \"\\n\\n\";\n        throw bad_exception();\n    }\n\n    vector<double> xyz_shifted;\n    int i_sec;\n    for (int i1 = 0; i1 < section_list.size(); i1++)\n    {\n        xyz_shifted = points.xyz;\n        for (int ip = 0; ip < ind_p.size(); ip++)\n        {\n            i_sec = section_list[i1][ip];\n            for (int iv = 0; iv < points.nv; iv++)\n                if (points.periodic_bc_section[iv][ip] == -i_sec) //shift opposite section (nothing happens for i_sec=0)\n                    xyz_shifted[dim * iv + ind_p[ip]] = xyz_shifted[dim * iv + ind_p[ip]] + (((double)(i_sec)) * points.xyz_length[ind_p[ip]]);\n            calc_cloud_points_fast_periodic_bc_shifted(points, parameters, xyz_shifted, section_list[i1]);\n        }\n    }\n    xyz_shifted.clear();\n}\n\nvoid CLOUD::calc_cloud_points_fast(POINTS &points, PARAMETERS &parameters)\n{ //Uses KD-Tree algorithm from Nanoflann (https://github.com/jlblancoc/nanoflann)\n    PointCloud<double> cloud_nf_for_interior, cloud_nf_for_boundary;\n    int dim = parameters.dimension;\n    cloud_nf_for_interior.pts.resize(points.nv);\n    cloud_nf_for_boundary.pts.resize(points.nv);\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        cloud_nf_for_interior.pts[iv].x = points.xyz[dim * iv];\n        cloud_nf_for_interior.pts[iv].y = points.xyz[dim * iv + 1];\n        if (dim == 3)\n            cloud_nf_for_interior.pts[iv].z = points.xyz[dim * iv + 2];\n        else\n            cloud_nf_for_interior.pts[iv].z = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n    }\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (!points.boundary_flag[iv])\n        { //internal points are coupled with boundary points\n            cloud_nf_for_boundary.pts[iv].x = points.xyz[dim * iv];\n            cloud_nf_for_boundary.pts[iv].y = points.xyz[dim * iv + 1];\n            if (dim == 3)\n                cloud_nf_for_boundary.pts[iv].z = points.xyz[dim * iv + 2];\n            else\n                cloud_nf_for_boundary.pts[iv].z = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n        }\n        else\n        { //all boundary co-ordinates set to infinity so that they are never coupled with any boundary point\n            cloud_nf_for_boundary.pts[iv].x = numeric_limits<double>::infinity();\n            cloud_nf_for_boundary.pts[iv].y = numeric_limits<double>::infinity();\n            cloud_nf_for_boundary.pts[iv].z = numeric_limits<double>::infinity(); //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n        }\n    }\n\n    typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloud<double>>, PointCloud<double>, 3> nanoflann_kd_tree_for_interior;\n    nanoflann_kd_tree_for_interior index_for_interior(3, cloud_nf_for_interior, nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */));\n    index_for_interior.buildIndex();\n\n    typedef nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<double, PointCloud<double>>, PointCloud<double>, 3> nanoflann_kd_tree_for_boundary;\n    nanoflann_kd_tree_for_boundary index_for_boundary(3, cloud_nf_for_boundary, nanoflann::KDTreeSingleIndexAdaptorParams(10 /* max leaf */));\n    index_for_boundary.buildIndex();\n\n    vector<size_t> nb_vert(parameters.cloud_size);\n    vector<double> nb_dist(parameters.cloud_size);\n    double query_pt[3];\n    int iv_nb;\n    nb_points_row.push_back(0);\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        query_pt[0] = points.xyz[dim * iv], query_pt[1] = points.xyz[dim * iv + 1];\n        if (dim == 3)\n            query_pt[2] = points.xyz[dim * iv + 2];\n        else\n            query_pt[2] = 0.0; //does not accept dimension as a parameter in KDTreeSingleIndexAdaptor and index\n        if (points.boundary_flag[iv])\n        {\n            index_for_boundary.knnSearch(&query_pt[0], parameters.cloud_size, &nb_vert[0], &nb_dist[0]);\n            nb_points_row.push_back(nb_points_row[iv] + parameters.cloud_size);\n            nb_points_col.push_back(iv);\n            for (int i1 = 0; i1 < nb_vert.size() - 1; i1++)\n            { //first entry is \"iv\": hence \"nb_vert.size() - 1\"\n                iv_nb = nb_vert[i1];\n                if (points.boundary_flag[iv_nb])\n                {\n                    cout << \"\\n\\nERROR from CLOUD::calc_cloud_points_fast boundary iv: \" << iv << \" (boundary_flag[iv]: \" << points.boundary_flag[iv] << \") tried to couple to a boundary vertex: \" << iv_nb << \" (boundary_flag[iv_nb]: \" << points.boundary_flag[iv_nb] << \") \\n\\n\";\n                    throw bad_exception();\n                }\n                else\n                    nb_points_col.push_back(iv_nb);\n            }\n        }\n        else\n        { //internal points\n            index_for_interior.knnSearch(&query_pt[0], parameters.cloud_size, &nb_vert[0], &nb_dist[0]);\n            nb_points_row.push_back(nb_points_row[iv] + parameters.cloud_size);\n            nb_points_col.insert(nb_points_col.end(), nb_vert.begin(), nb_vert.end());\n        }\n    }\n}\n\nvoid CLOUD::calc_cloud_points_slow(POINTS &points, PARAMETERS &parameters)\n{ //calculate neighboring points for all vertices: Computations: Order(points.nv^2)\n    vector<double> dist_square, k_min_dist_square;\n    vector<int> k_min_points;\n    for (int iv = 0; iv < points.nv; iv++)\n        dist_square.push_back(0.0); //initialize\n    double x0, y0, z0;\n    int k = parameters.cloud_size, dim = parameters.dimension;\n    nb_points_row.push_back(0);\n    if (dim == 2)\n    { //2D problem\n        for (int iv0 = 0; iv0 < points.nv; iv0++)\n        {\n            x0 = points.xyz[dim * iv0];\n            y0 = points.xyz[dim * iv0 + 1];\n            for (int iv = 0; iv < points.nv; iv++)\n            {\n                if (!points.boundary_flag[iv0])\n                { //all points added if iv0 is internal\n                    dist_square[iv] = (x0 - points.xyz[dim * iv]) * (x0 - points.xyz[dim * iv]);\n                    dist_square[iv] = dist_square[iv] + (y0 - points.xyz[dim * iv + 1]) * (y0 - points.xyz[dim * iv + 1]);\n                }\n                else\n                { //iv0 is boundary: only couple with internal points\n                    if (iv0 == iv || !points.boundary_flag[iv])\n                    { //self-coupling OR only internal points\n                        dist_square[iv] = (x0 - points.xyz[dim * iv]) * (x0 - points.xyz[dim * iv]);\n                        dist_square[iv] = dist_square[iv] + (y0 - points.xyz[dim * iv + 1]) * (y0 - points.xyz[dim * iv + 1]);\n                    }\n                    else\n                        dist_square[iv] = numeric_limits<double>::infinity(); //iv is boundary and not equal to iv0 (thus should not be coupled)\n                }\n            }\n            k_smallest_elements(k_min_dist_square, k_min_points, dist_square, k);\n            nb_points_row.push_back(nb_points_row[iv0] + k_min_points.size());\n            nb_points_col.insert(nb_points_col.end(), k_min_points.begin(), k_min_points.end());\n        }\n    }\n    else\n    { //3D problem\n        for (int iv0 = 0; iv0 < points.nv; iv0++)\n        {\n            x0 = points.xyz[dim * iv0];\n            y0 = points.xyz[dim * iv0 + 1];\n            z0 = points.xyz[dim * iv0 + 2];\n            for (int iv = 0; iv < points.nv; iv++)\n            {\n                if (!points.boundary_flag[iv0])\n                { //all points added if iv0 is internal\n                    dist_square[iv] = (x0 - points.xyz[dim * iv]) * (x0 - points.xyz[dim * iv]);\n                    dist_square[iv] = dist_square[iv] + (y0 - points.xyz[dim * iv + 1]) * (y0 - points.xyz[dim * iv + 1]);\n                    dist_square[iv] = dist_square[iv] + (z0 - points.xyz[dim * iv + 2]) * (z0 - points.xyz[dim * iv + 2]);\n                }\n                else\n                { //iv0 is boundary: only couple with internal points\n                    if (iv0 == iv || !points.boundary_flag[iv])\n                    { //self-coupling OR only internal points\n                        dist_square[iv] = (x0 - points.xyz[dim * iv]) * (x0 - points.xyz[dim * iv]);\n                        dist_square[iv] = dist_square[iv] + (y0 - points.xyz[dim * iv + 1]) * (y0 - points.xyz[dim * iv + 1]);\n                        dist_square[iv] = dist_square[iv] + (z0 - points.xyz[dim * iv + 2]) * (z0 - points.xyz[dim * iv + 2]);\n                    }\n                    else\n                        dist_square[iv] = numeric_limits<double>::infinity(); //iv is boundary and not equal to iv0 (thus should not be coupled)\n                }\n            }\n            k_smallest_elements(k_min_dist_square, k_min_points, dist_square, k);\n            nb_points_row.push_back(nb_points_row[iv0] + k_min_points.size());\n            nb_points_col.insert(nb_points_col.end(), k_min_points.begin(), k_min_points.end());\n        }\n    }\n    dist_square.clear();\n    k_min_dist_square.clear();\n    k_min_points.clear();\n}", "meta": {"hexsha": "8df9bfd8a5883987314bba0639c52b37bf6ed081", "size": 34064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/cloud.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/cloud.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/cloud.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": 47.1147994467, "max_line_length": 282, "alphanum_fraction": 0.6109382339, "num_tokens": 9325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5588570201909898}}
{"text": "/**\n * \\file TimeVaryingSecondOrderSVFFilter.cpp\n */\n\n#include \"TimeVaryingSecondOrderSVFFilter.h\"\n\n#include <cassert>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template<typename SVFCoefficients>\n  struct TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::SVFState\n  {\n    typename SVFCoefficients::DataType iceq1;\n    typename SVFCoefficients::DataType iceq2;\n    \n    SVFState()\n    :iceq1(0), iceq2(0)\n    {\n    }\n  };\n  \n  template<typename SVFCoefficients>\n  TimeVaryingSecondOrderSVFFilter<SVFCoefficients>::TimeVaryingSecondOrderSVFFilter(int nb_channels)\n  :SVFCoefficients(nb_channels), state(new 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.reset(new SVFState[nb_input_ports]);\n  }\n\n  template<typename DataType>\n  void TimeVaryingSecondOrderSVFFilter<DataType>::process_impl(int64_t size) const\n  {\n    assert(nb_input_ports == nb_output_ports);\n\n    for(int64_t i = 0; i < size; ++i)\n    {\n      update_coeffs(converted_inputs[0][i]);\n      \n      for(int j = 0; j < nb_input_ports; ++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(int nb_channels)\n  :TypedBaseFilter<DataType>(1 + nb_channels, nb_channels),Q(1)\n  {\n  }\n\n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFBaseCoefficients<DataType_>::set_Q(DataType_ Q)\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(int 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(int 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(int 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(int 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 = 2;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFPeakCoefficients<DataType_>::TimeVaryingSecondOrderSVFPeakCoefficients(int 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 = 0;\n  }\n\n  template<typename DataType_>\n  TimeVaryingSecondOrderSVFBellCoefficients<DataType_>::TimeVaryingSecondOrderSVFBellCoefficients(int nb_channels)\n  :Parent(nb_channels), gain(0)\n  {\n    \n  }\n  \n  template<typename DataType_>\n  void TimeVaryingSecondOrderSVFBellCoefficients<DataType_>::set_gain(DataType_ gain)\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(int nb_channels)\n  :Parent(nb_channels), gain(0)\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(int nb_channels)\n  :Parent(nb_channels), gain(0)\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  template class TimeVaryingSecondOrderSVFBaseCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFBaseCoefficients<double>;\n\n  template class TimeVaryingSecondOrderSVFLowPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFLowPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFBandPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFBandPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFHighPassCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFHighPassCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFNotchCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFNotchCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFPeakCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFPeakCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFBellCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFBellCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFLowShelfCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFLowShelfCoefficients<double>;\n  template class TimeVaryingSecondOrderSVFHighShelfCoefficients<float>;\n  template class TimeVaryingSecondOrderSVFHighShelfCoefficients<double>;\n\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBandPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBandPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighPassCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighPassCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFNotchCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFNotchCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFPeakCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFPeakCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBellCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFBellCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowShelfCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFLowShelfCoefficients<double> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighShelfCoefficients<float> >;\n  template class TimeVaryingSecondOrderSVFFilter<TimeVaryingSecondOrderSVFHighShelfCoefficients<double> >;\n}\n", "meta": {"hexsha": "3ea1a363daefc990e3db41cf3b666dc5c67c9378", "size": 9749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/TimeVaryingSecondOrderSVFFilter.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/TimeVaryingSecondOrderSVFFilter.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/TimeVaryingSecondOrderSVFFilter.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": 31.6525974026, "max_line_length": 124, "alphanum_fraction": 0.7435634424, "num_tokens": 2892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5588570120796104}}
{"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 Thomas Witkowski\n\n\n#ifndef AMDIS_ITL_MINRES_INCLUDE\n#define AMDIS_ITL_MINRES_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n\nnamespace itl\n{\n\n  /// Minimal Residual method\n  template <typename Matrix, typename Vector,\n            typename LeftPreconditioner, typename RightPreconditioner,\n            typename Iteration>\n  int minres(const Matrix& A, Vector& x, const Vector& b,\n             const LeftPreconditioner& L, const RightPreconditioner& /*R*/,\n             Iteration& iter)\n  {\n    using std::abs;\n    using math::reciprocal;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n\n    if (size(b) == 0)\n      throw mtl::logic_error(\"empty rhs vector\");\n\n    Scalar                zero= math::zero(b[0]), one= math::one(b[0]);\n    Vector v0(size(x), zero), v1(b - A * x), v2(v1), z1(solve(L, v1)), z2(size(x), zero);\n    Vector w0(size(x), zero), w1(size(x), zero), w2(size(x), zero);\n\n    Scalar s0(zero), s1(zero), c0(one), c1(one), gamma0(one);\n    Scalar gamma1(sqrt(dot(z1, v1))), gamma2(zero), eta(gamma1);\n    Scalar sigma1(one), alpha0(zero), alpha1(zero), alpha2(zero), alpha3(zero);\n\n    while (!iter.finished(abs(eta)))\n    {\n      z1 *= reciprocal(gamma1);\n      v2 = A * z1;\n      sigma1 = dot(v2, z1);\n      v2 += -(sigma1 / gamma1) * v1 - (gamma1 / gamma0) * v0;\n\n      z2 = solve(L, v2);\n\n      gamma2 = sqrt(dot(z2, v2));\n      alpha0 = c1 * sigma1 - c0 * s1 * gamma1;\n      alpha1 = sqrt(alpha0 * alpha0 + gamma2 * gamma2);\n      alpha2 = s1 * sigma1 + c0 * c1 * gamma1;\n      alpha3 = s0 * gamma1;\n\n      c0 = c1;\n      c1 = alpha0 / alpha1;\n      s0 = s1;\n      s1 = gamma2 / alpha1;\n\n      w2 = z1 - alpha3 * w0 - alpha2 * w1;\n      w2 *=  reciprocal(alpha1);\n\n      x += c1 * eta * w2;\n      eta *= -s1;\n\n      w0 = w1;\n      w1 = w2;\n      v0 = v1;\n      v1 = v2;\n      z1 = z2;\n\n      gamma0 = gamma1;\n      gamma1 = gamma2;\n\n      ++iter;\n    }\n\n    return iter;\n  }\n\n} // namespace itl;\n\n#endif // AMDIS_ITL_MINRES_INCLUDE\n", "meta": {"hexsha": "1c1319eea3cfbf7a878f72e66ea8f3ec5a56e382", "size": 2695, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/minres.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/minres.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/minres.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2222222222, "max_line_length": 89, "alphanum_fraction": 0.5680890538, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5588570060943155}}
{"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__DERIVATIVES_HPP_\n#define SMOOTH__DERIVATIVES_HPP_\n\n#include <Eigen/Core>\n\n#include \"lie_group.hpp\"\n\n/**\n * @file\n * @brief Various useful derivatives.\n */\n\nnamespace smooth {\n\n/**\n * @brief Derivative of matrix product.\n *\n * @param A matrix                                         [N x K]\n * @param dA derivative of A on horizontal Hessian form    [K x N*Nvar]\n * @param B matrix                                         [K x M]\n * @param dB derivative of B on horizontal Hessian form    [M x K*Nvar]\n * @return derivative of A * B on horizontal Hessian form\n */\ntemplate<typename At, typename dAt, typename Bt, typename dBt>\ninline auto d_matrix_product(const At & A, const dAt & dA, const Bt & B, const dBt & dB)\n{\n  using Scalar = std::common_type_t<\n    typename At::Scalar,\n    typename dAt::Scalar,\n    typename Bt::Scalar,\n    typename dBt::Scalar>;\n\n  static constexpr int N    = At::ColsAtCompileTime;\n  static constexpr int M    = Bt::RowsAtCompileTime;\n  static constexpr int Nvar = []() -> int {\n    if constexpr (dAt::ColsAtCompileTime > 0 && N > 0) {\n      return dAt::ColsAtCompileTime / N;\n    } else if (dBt::ColsAtCompileTime > 0 && M > 0) {\n      return dBt::ColsAtCompileTime / M;\n    } else {\n      return -1;\n    }\n  }();\n\n  const auto n                  = A.cols();\n  [[maybe_unused]] const auto k = A.rows();\n  const auto m                  = B.rows();\n  const auto nvar               = dA.cols() / (n);\n\n  assert(k == B.cols());\n  assert(nvar == dB.size() / (m * k));\n\n  static constexpr int dAB_cols = (M > 0 && Nvar > 0) ? M * Nvar : -1;\n\n  Eigen::Matrix<Scalar, N, dAB_cols> dAB = B.transpose() * dA;\n  for (auto i = 0u; i < n; ++i) {\n    for (auto j = 0u; j < m; ++j) {\n      dAB.template middleCols<Nvar>(i * nvar, nvar) +=\n        A(i, j) * dB.template middleCols<Nvar>(j * Nvar, nvar);\n    }\n  }\n  return dAB;\n}\n\n/**\n * @brief Hessian of composed function \\f$ (f \\circ g)(x) \\f$.\n *\n * @param Jf Jacobian of f at y = g(x)  [No x Ny   ]\n * @param Hf Hessian of f at y = g(x)   [Ny x No*Ny]\n * @param Jg Jacobian of g at x         [Ny x Nx   ]\n * @param Hg Hessian of g at x          [Nx x Ny*Nx]\n *\n * @return Hessian of size [No x No*Nx]\n */\ntemplate<typename JfT, typename HfT, typename JgT, typename HgT>\ninline auto d2_fog(const JfT & Jf, const HfT & Hf, const JgT & Jg, const HgT & Hg)\n{\n  using Scalar = std::common_type_t<\n    typename JfT::Scalar,\n    typename HfT::Scalar,\n    typename JgT::Scalar,\n    typename HgT::Scalar>;\n\n  static constexpr int No = JfT::RowsAtCompileTime;\n  static constexpr int Ny = JfT::ColsAtCompileTime;\n  static constexpr int Nx = JgT::ColsAtCompileTime;\n\n  const auto no = Jf.rows();\n  const auto ny = Jf.cols();\n\n  [[maybe_unused]] const auto ni = Jg.rows();\n  const auto nx                  = Jg.cols();\n\n  // check some dimensions\n  assert(ny == ni);\n  assert(Hf.rows() == ny);\n  assert(Hf.cols() == no * ny);\n  assert(Hg.rows() == nx);\n  assert(Hg.cols() == ni * nx);\n\n  Eigen::Matrix<Scalar, Nx, (No == -1 || Nx == -1) ? -1 : No * Nx> ret(nx, no * nx);\n  ret.setZero();\n\n  for (auto i = 0u; i < no; ++i) {\n    ret.template block<Nx, Nx>(0, i * nx, nx, nx) +=\n      Jg.transpose() * Hf.template middleCols<Ny>(i * ny, ny) * Jg;\n  }\n\n  for (auto i = 0u; i < Jf.outerSize(); ++i) {\n    for (Eigen::InnerIterator it(Jf, i); it; ++it) {\n      ret.template block<Nx, Nx>(0, it.row() * nx) +=\n        it.value() * Hg.template middleCols<Nx>(it.col() * nx, nx);\n    }\n  }\n\n  return ret;\n}\n\n/**\n * @brief Jacobian of rminus.\n * @param e value of \\f$ x \\ominus_r y \\f$\n * @return \\f$ \\mathrm{d}^{r} (x \\ominus_r y)_{x} \\f$\n */\ntemplate<LieGroup G>\nTangentMap<G> dr_rminus(const Tangent<G> & e)\n{\n  return dr_expinv<G>(e);\n}\n/**\n * @brief Hessian of rminus.\n * @param e value of \\f$ x \\ominus_r y \\f$\n * @return \\f$ \\mathrm{d}^{2r} (x \\ominus_r y)_{xx} \\f$\n */\ntemplate<LieGroup G>\nHessian<G> d2r_rminus(const Tangent<G> & e)\n{\n  const auto J = dr_expinv<G>(e);\n\n  auto res = d2r_expinv<G>(e);\n  for (auto j = 0u; j < Dof<G>; ++j) {\n    res.template block<Dof<G>, Dof<G>>(0, j * e.size(), e.size(), e.size()).applyOnTheRight(J);\n  }\n  return res;\n}\n\n/**\n * @brief Jacobian of the squared norm of rminus.\n * @param e value of \\f$ x \\ominus_r y \\f$\n * @return \\f$ \\mathrm{d}^r \\left( \\frac{1}{2} \\| x \\ominus_r y \\|^2 \\right)_x \\f$\n */\ntemplate<LieGroup G>\nEigen::RowVector<Scalar<G>, Dof<G>> dr_rminus_squarednorm(const Tangent<G> & e)\n{\n  return e.transpose() * dr_expinv<G>(e);\n}\n\n/**\n * @brief Hessian of the squared norm of rminus.\n * @param e value of \\f$ x \\ominus_r y \\f$\n * @return \\f$ \\mathrm{d}^{2r} \\left( \\frac{1}{2} \\| x \\ominus_r y \\|^2 \\right)_{xx} \\f$\n */\ntemplate<LieGroup G>\nEigen::Matrix<Scalar<G>, Dof<G>, Dof<G>> d2r_rminus_squarednorm(const Tangent<G> & e)\n{\n  const TangentMap<G> J1 = dr_rminus<G>(e);   // N x N\n  const Hessian<G> H1    = d2r_rminus<G>(e);  // N x (N*N)\n\n  return d2_fog(e.transpose(), Eigen::Matrix<Scalar<G>, Dof<G>, Dof<G>>::Identity(), J1, H1);\n}\n\n}  // namespace smooth\n\n#endif\n", "meta": {"hexsha": "61ef09b88c559f738346fb155de3eb5d4c802a9e", "size": 6264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/derivatives.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/derivatives.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/derivatives.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4773869347, "max_line_length": 95, "alphanum_fraction": 0.6200510856, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5588384348388042}}
{"text": "#define R_NO_REMAP\n#include <R.h>\n#include <Rmath.h>\n#include <Rinternals.h>\n#include <R_ext/BLAS.h>\n#include <R_ext/Lapack.h>\n\n#include \"omxDefines.h\"\n#include <Eigen/Core>\n#include \"omxBuffer.h\"\n#include \"matrix.h\"\n#include \"glue.h\"\n\nstatic const int ERROR_LEN = 80;\n\nstatic double\n_mahalanobis(char *err, int dim, double *loc, double *center, double *origCov)\n{\n\tstd::vector<double> cloc(dim);\n\tfor (int dx=0; dx < dim; dx++) {\n\t\tcloc[dx] = loc[dx] - center[dx];\n\t}\n\n\tMatrix covMat(origCov, dim, dim);\n\tomxBuffer<double> icov(dim * dim);\n\tMatrix icovMat(icov.data(), dim, dim);\n\tint info = MatrixSolve(covMat, icovMat, true); // can optimize for symmetry TODO\n\tif (info) {\n\t\tsnprintf(err, ERROR_LEN, \"Sigma is singular and cannot be inverted\");\n\t\treturn nan(\"Rf_error\");\n\t}\n\n\tstd::vector<double> half(dim);\n\tchar trans='n';\n\tdouble alpha=1;\n\tdouble beta=0;\n\tint inc=1;\n\tF77_CALL(dgemv)(&trans, &dim, &dim, &alpha, icov.data(), &dim, cloc.data(), &inc, &beta, half.data(), &inc);\n\n\tdouble got=0;\n\tfor (int dx=0; dx < dim; dx++) got += half[dx] * cloc[dx];\n\treturn got;\n}\n\nstatic double\nmahalanobis(int dim, double *loc, double *center, double *origCov)\n{\n\tchar err[ERROR_LEN];\n\terr[0] = 0;\n\tdouble ret = _mahalanobis(err, dim, loc, center, origCov);\n\tif (err[0]) Rf_error(\"%s\", err);\n\treturn ret;\n}\n\nstatic double\n_dmvnorm(char *err, int dim, double *loc, double *mean, double *origSigma)\n{\n\tdouble dist = mahalanobis(dim, loc, mean, origSigma);\n\n\tstd::vector<double> sigma(dim * dim);\n\tmemcpy(sigma.data(), origSigma, sizeof(double) * dim * dim);\n\n\tchar jobz = 'N';\n\tchar range = 'A';\n\tchar uplo = 'U';\n\tdouble vunused;\n\tint iunused;\n\tdouble abstol = 0;\n\tint m;\n\tEigen::VectorXd w(dim);\n\tEigen::VectorXd Z(dim);\n\tint ldz=1;\n\tEigen::VectorXi isuppz(2*dim);\n\tint lwork = -1;\n\tdouble optlWork;\n\tint optliWork;\n\tint liwork = -1;\n\tint info;\n\n\tF77_CALL(dsyevr)(&jobz, &range, &uplo,\n\t\t\t &dim, sigma.data(), &dim,\n\t\t\t &vunused, &vunused,\n\t\t\t &iunused, &iunused,\n\t\t\t &abstol, &m, w.data(),\n\t\t\t Z.data(), &ldz, isuppz.data(),\n\t\t\t &optlWork, &lwork,\n\t\t\t &optliWork, &liwork, &info);\n\tif (info != 0) {\n\t\tsnprintf(err, ERROR_LEN, \"dsyevr failed when requesting work space size\");\n\t\treturn nan(\"Rf_error\");\n\t}\n\n\tlwork = optlWork;\n\tstd::vector<double> work(lwork);\n\tliwork = optliWork;\n\tstd::vector<int> iwork(liwork);\n\n\tF77_CALL(dsyevr)(&jobz, &range, &uplo, &dim, sigma.data(), &dim,\n\t\t\t &vunused, &vunused, &iunused, &iunused, &abstol, &m, w.data(), Z.data(), &ldz, isuppz.data(),\n\t\t\t work.data(), &lwork, iwork.data(), &liwork, &info);\n\tif (info < 0) {\n\t\tsnprintf(err, ERROR_LEN, \"Arg %d is invalid\", -info);\n\t\treturn nan(\"Rf_error\");\n\t}\n\tif (info > 0) {\n\t\tsnprintf(err, ERROR_LEN, \"dsyevr: internal Rf_error\");\n\t\treturn nan(\"Rf_error\");\n\t}\n\tif (m < dim) {\n\t\tsnprintf(err, ERROR_LEN, \"Sigma not of full rank\");\n\t\treturn nan(\"Rf_error\");\n\t}\n\n\tfor (int dx=0; dx < dim; dx++) dist += log(w[dx]);\n\tdouble got = -(dim * M_LN_SQRT_2PI*2 + dist)/2;\n\treturn got;\n}\n\ndouble\ndmvnorm(int dim, double *loc, double *mean, double *sigma)\n{\n\tchar err[ERROR_LEN];\n\terr[0] = 0;\n\tdouble ret = _dmvnorm(err, dim, loc, mean, sigma);\n\tif (err[0]) Rf_error(\"%s\", err);\n\treturn ret;\n}\n\nSEXP dmvnorm_wrapper(SEXP Rloc, SEXP Rmean, SEXP Rsigma)\n{\n\tSEXP ret;\n\tScopedProtect p1(ret, Rf_allocVector(REALSXP, 1));\n\tREAL(ret)[0] = dmvnorm(Rf_length(Rloc), REAL(Rloc), REAL(Rmean), REAL(Rsigma));\n\treturn ret;\n}\n", "meta": {"hexsha": "b7b9ecb93126dcc21dd51d2619aa73bdc540963a", "size": 3374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dmvnorm.cpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dmvnorm.cpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dmvnorm.cpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.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.8088235294, "max_line_length": 109, "alphanum_fraction": 0.6499703616, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.558838434804049}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\n// Point - Point\n\ntemplate <\n    typename DerivedP0,\n    typename DerivedP1,\n    typename T = typename DerivedP0::Scalar>\ninline MatrixMax<T, 3, 2> point_point_tangent_basis(\n    const Eigen::MatrixBase<DerivedP0>& p0,\n    const Eigen::MatrixBase<DerivedP1>& p1)\n{\n    if (p0.size() == 2) {\n        assert(p1.size() == 2);\n\n        MatrixMax<T, 3, 2> basis(2, 1);\n\n        auto p0_to_p1 = (p1 - p0).normalized();\n\n        basis(0) = -p0_to_p1(1);\n        basis(1) = p0_to_p1(0);\n\n        return basis;\n    } else {\n        assert(p0.size() == 3 && p1.size() == 3);\n\n        MatrixMax<T, 3, 2> basis(3, 2);\n\n        auto p0_to_p1 = p1 - p0;\n\n        Vector3<T> cross_x = cross(Vector3<T>::UnitX(), p0_to_p1);\n        Vector3<T> cross_y = cross(Vector3<T>::UnitY(), p0_to_p1);\n\n        if (cross_x.squaredNorm() > cross_y.squaredNorm()) {\n            basis.col(0) = cross_x.normalized();\n            basis.col(1) = cross(p0_to_p1, cross_x).normalized();\n        } else {\n            basis.col(0) = cross_y.normalized();\n            basis.col(1) = cross(p0_to_p1, cross_y).normalized();\n        }\n\n        return basis;\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Point - Edge\n\ntemplate <\n    typename DerivedP,\n    typename DerivedE0,\n    typename DerivedE1,\n    typename T = typename DerivedP::Scalar>\ninline MatrixMax<T, 3, 2> point_edge_tangent_basis(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1)\n{\n    if (p.size() == 2) {\n        assert(e0.size() == 2 && e1.size() == 2);\n\n        MatrixMax<T, 3, 2> basis(2, 1);\n\n        basis.col(0) = (e1 - e0).normalized();\n\n        return basis;\n    } else {\n        assert(p.size() == 3 && e0.size() == 3 && e1.size() == 3);\n\n        MatrixMax<T, 3, 2> basis(3, 2);\n\n        auto e = e1 - e0;\n        basis.col(0) = e.normalized();\n        basis.col(1) = cross(e, p - e0).normalized();\n\n        return basis;\n    }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Edge - Edge\n\n/// Compute a basis for the space tangent to the edge-edge pair.\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1,\n    typename T = typename DerivedEA0::Scalar>\ninline Eigen::Matrix<T, 3, 2> edge_edge_tangent_basis(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1)\n{\n    assert(ea0.size() == 3 && ea1.size() == 3);\n    assert(eb0.size() == 3 && eb1.size() == 3);\n\n    Eigen::Matrix<T, 3, 2> basis;\n\n    auto ea = ea1 - ea0; // Edge A direction\n    // The first basis vector is along edge A.\n    basis.col(0) = ea.normalized();\n    // The second basis vector is orthogonal to the first and the edge-edge\n    // normal.\n    auto normal = cross(ea, eb1 - eb0);\n    // The normal will be zero if the edges are parallel (i.e. coplanar).\n    assert(normal.norm() != 0);\n    basis.col(1) = cross(normal, ea).normalized();\n\n    return basis;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Point - Triangle\n\n/// Compute a basis for the space tangent to the point-triangle pair.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2,\n    typename T = typename DerivedP::Scalar>\ninline Eigen::Matrix<T, 3, 2> point_triangle_tangent_basis(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2)\n{\n    assert(p.size() == 3 && t0.size() == 3 && t1.size() == 3 && t2.size() == 3);\n\n    Eigen::Matrix<T, 3, 2> basis;\n\n    auto e0 = t1 - t0;\n    // The first basis vector is along first edge of the triangle.\n    basis.col(0) = e0.normalized();\n    // The second basis vector is orthogonal to the first and the triangle\n    // normal.\n    auto normal = cross(e0, t2 - t0);\n    assert(normal.norm() != 0);\n    basis.col(1) = cross(normal, e0).normalized();\n\n    return basis;\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "ff826fe97f3f4ea36bfdb12d51a0e21b04c83d77", "size": 4290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/friction/tangent_basis.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/friction/tangent_basis.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/friction/tangent_basis.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 27.8571428571, "max_line_length": 80, "alphanum_fraction": 0.5694638695, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5588038343328455}}
{"text": "#pragma once\n#include <math.h>\n\n#include <boost/logic/tribool.hpp>\n#include <boost/numeric/interval.hpp>\n#include <boost/numeric/interval/io.hpp>\n#include <boost/numeric/interval/rounded_arith.hpp>\n#include <cmath>\n#include <iostream>\n#include <utility>\n\nstatic const double ulp = ldexpl(1.0, -52);\nstatic const double min_denormal = ldexpl(1.0, -1074);\n\nnamespace bn = boost::numeric;\nnamespace bni = bn::interval_lib;\ntypedef bni::checking_no_nan<double> checking;\ntypedef bn::interval<double, bni::policies<bni::save_state<bni::rounded_transc_std<double>>, checking>> Interval;\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// DUAL NUMBER INTERVAL CLASS\n//\n////////////////////////////////////////////////////////////////////////////////\n\nclass DualInterval {\n   public:\n    Interval real;\n    Interval dual;\n\n    DualInterval(double rl, double ru, double dl, double du) {\n        real = Interval(rl, ru);\n        dual = Interval(dl, du);\n    }\n\n    DualInterval(const Interval& ri, const Interval& di) {\n        real = ri;\n        dual = di;\n    }\n\n    DualInterval(double r) {\n        real = Interval(r, r);\n        dual = Interval(0, 0);\n    }\n\n    DualInterval() {\n        real = Interval(0, 0);\n        dual = Interval(0, 0);\n    }\n\n    DualInterval operator+(const DualInterval& rhs) const;\n    DualInterval operator+(const double rhs) const;\n    friend DualInterval operator+(const double lhs, const DualInterval& rhs);\n\n    DualInterval operator-(const DualInterval& rhs) const;\n    DualInterval operator-(const double rhs) const;\n    friend DualInterval operator-(const double lhs, const DualInterval& rhs);\n    DualInterval operator-() const;\n\n    DualInterval operator*(const DualInterval& rhs) const;\n    DualInterval operator*(const double rhs) const;\n    friend DualInterval operator*(const double lhs, const DualInterval& rhs);\n\n    DualInterval operator/(const DualInterval& rhs) const;\n    DualInterval operator/(const double rhs) const;\n\n    DualInterval& operator+=(const DualInterval& rhs);\n    DualInterval& operator+=(const double rhs);\n\n    DualInterval operator|(const DualInterval& rhs) const;\n\n    friend DualInterval exp(const DualInterval& x);\n    friend DualInterval log(const DualInterval& x);\n    friend DualInterval sqrt(const DualInterval& x);\n    friend DualInterval tanh(const DualInterval& x);\n    friend DualInterval atan(const DualInterval& x);\n    friend DualInterval logistic(const DualInterval& x);\n    friend DualInterval sin(const DualInterval& x);\n    friend DualInterval cos(const DualInterval& x);\n    friend DualInterval abs(const DualInterval& x);\n    friend DualInterval relu(const DualInterval& x);\n    friend DualInterval max(const DualInterval& x, const DualInterval& y);\n    friend DualInterval min(const DualInterval& x, const DualInterval& y);\n\n    friend std::ostream& operator<<(std::ostream& os, const DualInterval& di);\n\n    bool isEmpty() const;\n    void setReal(Interval real_);\n    void setReal(double a, double b);\n    void setDual(Interval dual_);\n    void setDual(double a, double b);\n    Interval getReal() const;\n    Interval getDual() const;\n};\n\ntypedef DualInterval DI;\n\nbool DualInterval::isEmpty() const {\n    return (empty(real) && empty(dual));\n}\n\nvoid DualInterval::setReal(Interval real_) {\n    real = real_;\n}\n\nvoid DualInterval::setReal(double a, double b) {\n    real = Interval(a, b);\n}\n\nvoid DualInterval::setDual(Interval dual_) {\n    dual = dual_;\n}\n\nvoid DualInterval::setDual(double a, double b) {\n    dual = Interval(a, b);\n}\n\nInterval DualInterval::getReal() const {\n    return real;\n}\nInterval DualInterval::getDual() const {\n    return dual;\n}\n\nstd::ostream& operator<<(std::ostream& os, const DualInterval& di) {\n    os << di.real << \" + \" << di.dual << \"\\u03B5\";\n    return os;\n}\n\n// internal function only used within this header\nInterval add_intervals(const Interval& a, const Interval& b) {\n    Interval i = a + b;\n\n    #ifdef SOUND\n        double maxA = fmax(fabs(a.lower()), fabs(a.upper()));\n        double maxB = fmax(fabs(b.lower()), fabs(b.upper()));\n        Interval tmp = Interval(-maxA * ulp, maxA * ulp) + Interval(-maxB * ulp, maxB * ulp) + Interval(-min_denormal, min_denormal);\n        return i + tmp;\n    #endif\n\n    return i;\n}\n\n// internal function only used within this header\nInterval mul_intervals(const Interval& a, const Interval& b) {\n    Interval i = a * b;\n\n    #ifdef SOUND\n        double maxB = fmax(fabs(b.lower()), fabs(b.upper()));\n        Interval tmp = a * Interval(-maxB * ulp, maxB * ulp) + Interval(-min_denormal, min_denormal);\n        return i + tmp;\n    #endif\n\n    return i;\n}\n\n// internal function only used within this header\nInterval square_interval(const Interval& a) {\n    Interval i = square(a);\n\n    #ifdef SOUND\n        double maxB = fmax(fabs(a.lower()), fabs(a.upper()));\n        Interval tmp = a * Interval(-maxB * ulp, maxB * ulp) + Interval(-min_denormal, min_denormal);\n        return i + tmp;\n    #endif\n\n    return i;\n}\n\n// internal function only used within this header\nInterval div_intervals(const Interval& a, const Interval& b) {\n    Interval i = a / b;\n\n    #ifdef SOUND\n        double maxA = fmax(fabs(a.lower()), fabs(a.upper()));\n        Interval tmp = Interval(-maxA * ulp, maxA * ulp) / b + Interval(-min_denormal, min_denormal);\n        return i + tmp;\n    #endif\n\n    return i;\n}\n\n// addition\nDI DualInterval::operator+(const DI& rhs) const {\n    assert(!isEmpty() && !rhs.isEmpty());\n\n    Interval r = add_intervals(real, rhs.real);\n    Interval d = add_intervals(dual, rhs.dual);\n    return DI(r, d);\n}\n\n// addition with a scalar (this automatically casts the scalar to a DualInterval)\nDI DualInterval::operator+(const double rhs) const {\n    return *this + DI(rhs);\n}\n\nDI operator+(const double lhs, const DI& rhs) {\n    return DI(lhs) + rhs;\n}\n\n// subtraction\nDI DualInterval::operator-(const DI& rhs) const {\n    return *this + (-rhs);\n}\n\nDI DualInterval::operator-(const double rhs) const {\n    return *this - DI(rhs);\n}\n\nDI operator-(const double lhs, const DI& rhs) {\n    return DI(lhs) - rhs;\n}\n\n// negation\nDI DualInterval::operator-() const {\n    return DI(-real.upper(), -real.lower(), -dual.upper(), -dual.lower());\n}\n\n// multiplication\nDI DualInterval::operator*(const DI& rhs) const {\n    assert(!isEmpty() && !rhs.isEmpty());\n\n    Interval r = mul_intervals(real, rhs.real);\n    Interval d = add_intervals(mul_intervals(real, rhs.dual), mul_intervals(dual, rhs.real));\n    return DI(r, d);\n}\n\nDI DualInterval::operator*(const double rhs) const {\n    return *this * DI(rhs);\n}\n\nDI operator*(const double lhs, const DI& rhs) {\n    return DI(lhs) * rhs;\n}\n\n// division\nDI DualInterval::operator/(const DI& rhs) const {\n    assert(!isEmpty() && !rhs.isEmpty());\n\n    Interval r = div_intervals(real, rhs.real);\n    Interval d = div_intervals(add_intervals(mul_intervals(dual, rhs.real), -mul_intervals(real, rhs.dual)), square_interval(rhs.real));\n    return DI(r, d);\n}\n\nDI DualInterval::operator/(const double rhs) const {\n    return *this / DI(rhs);\n}\n\n// increment\nDI& DualInterval::operator+=(const DI& rhs) {\n    assert(!isEmpty() && !rhs.isEmpty());\n\n    real = add_intervals(real, rhs.real);\n    dual = add_intervals(dual, rhs.dual);\n    return *this;\n}\n\nDI& DualInterval::operator+=(double rhs) {\n    return *this += DI(rhs);\n}\n\n// join (union)\nDI DualInterval::operator|(const DI& rhs) const {\n    if (rhs.isEmpty()) {\n        return DI(real.lower(), real.upper(), dual.lower(), dual.upper());\n    }\n\n    if (isEmpty()) {\n        return DI(rhs.real.lower(), rhs.real.upper(), rhs.dual.lower(), rhs.dual.upper());\n    }\n\n    return DI(hull(real, rhs.real), hull(dual, rhs.dual));\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//\n// FUNCTIONS OF SCALAR DUAL INTERVALS\n//\n////////////////////////////////////////////////////////////////////////////////\n\nDI exp(const DI& x) {\n    assert(!x.isEmpty());\n\n    Interval r = exp(x.real);\n    Interval d = r * x.dual;\n    return DI(r, d);\n}\n\nDI log(const DI& x) {\n    assert(!x.isEmpty());\n    return DI(log(x.real), x.dual / x.real);\n}\n\nDI sqrt(const DI& x) {\n    assert(!x.isEmpty());\n\n    Interval r = sqrt(x.real);\n    Interval d = x.dual / r * 0.5;\n    return DI(r, d);\n}\n\nDI tanh(const DI& x) {\n    assert(!x.isEmpty());\n\n    Interval r = tanh(x.real);\n    Interval d = (1. - square(r)) * x.dual;\n    return DI(r, d);\n}\n\nDI atan(const DI& x) {\n    assert(!x.isEmpty());\n    return DI(atan(x.real), 1. / (1. + square(x.real)) * x.dual);\n}\n\nDI logistic(const DI& x) {\n    assert(!x.isEmpty());\n\n    Interval t = tanh(x.real / 2.);\n    Interval r = 0.5 * t + 0.5;\n    Interval d = 0.25 * (1. - square(t)) * x.dual;\n    return DI(r, d);\n}\n\nDI sin(const DI& x) {\n    assert(!x.isEmpty());\n    return DI(sin(x.real), cos(x.real) * x.dual);\n}\n\nDI cos(const DI& x) {\n    assert(!x.isEmpty());\n    return DI(cos(x.real), -sin(x.real) * x.dual);\n}\n\nDI abs(const DI& x) {\n    assert(!x.isEmpty());\n\n    if (x.real.upper() < 0) {\n        return -x;\n    } else if (x.real.lower() > 0) {\n        return x;\n    } else {\n        DI positive_branch(0, x.real.upper(), x.dual.lower(), x.dual.upper());\n        DI negative_branch(0, -x.real.lower(), -x.dual.upper(), -x.dual.lower());\n        return (positive_branch | negative_branch);\n    }\n}\n\nDI max(const DI& x, const DI& y) {\n    assert(!x.isEmpty() && !y.isEmpty());\n\n    if (x.real.lower() > y.real.upper()) {\n        return x;\n    } else if (x.real.upper() < y.real.lower()) {\n        return y;\n    }\n    return DI(max(x.real, y.real), hull(x.dual, y.dual));\n}\n\nDI min(const DI& x, const DI& y) {\n    return -max(-x, -y);\n}\n\nDI relu(const DI& x) {\n    return max(x, 0);\n}\n", "meta": {"hexsha": "0ae3c1b5125634e5c283fb26b00181626c841055", "size": 9718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DualIntervals.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/DualIntervals.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/DualIntervals.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": 26.5519125683, "max_line_length": 136, "alphanum_fraction": 0.6171022844, "num_tokens": 2462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.5588038229172102}}
{"text": "/*! \\file exactmath.hpp\n  \\brief Exact math\n  \\author Elad Steinberg\n */\n\n#ifndef EXACTMATH_HPP\n#define EXACTMATH_HPP 1\n\n#include <stdlib.h>\n#include <cmath>\n#include <vector>\n#include <boost/array.hpp>\n\nusing std::vector;\nusing std::min;\n\n/*! \\brief Calculates the sum of two numbers\n  \\param a First number\n  \\param b Second number\n  \\param res Output\n  \\param err Roundoff error\n */\nvoid fastTwoSum(double a, double b, double& res, double& err);\n\n/*! \\brief Subtracts two numbers\n   \\param a First number\n   \\param b Second number\n   \\param res Output\n   \\param err Roundoff error\n */\nvoid fastTwoDiff(double a, double b, double& res, double& err);\n\n/*! \\brief Calculates the sum of a and b.\n   \\param a First number\n   \\param b Second number\n   \\param res Result\n   \\param err Roundoff error\n */\nvoid twoSum(double a, double b, double& res, double& err);\n\n/*! \\brief Difference between two numbers\n   \\param a First number\n   \\param b Second number\n   \\param res Result\n   \\param err Roundoff error\n */\nvoid twoDiff(double a, double b, double& res, double& err);\n\n/*! \\brief Splits a given number into two, Used for multiplication.\n   \\param num Number\n   \\param high Higher part\n   \\param low Lower part\n */\nvoid split(double num, double& high, double& low);\n\n/*! \\brief Product of two number\n   \\param a First number\n   \\param b Second number\n   \\param res Result\n   \\param err Error\n */\nvoid twoProduct(double a, double b, double& res, double& err);\n\n/*! \\brief Calculates the square of a number.\n   \\param num Number\n   \\param res Result\n   \\param err Roundoff error\n */\nvoid square(double num, double& res, double& err);\n\n/*! \\brief Calculates the sum of a two-expansion and a double.\n   \\param a Two expansion\n   \\param b A number\n   \\return Sum\n */\nboost::array<double,3> twoOneSum(boost::array<double,2> const& a, double b);\n\n/*! \\brief Calculates the difference between a two-expansion and a double.\n   \\param a Two expansion\n   \\param b Number\n   \\return Difference\n */\nboost::array<double,3> twoOneDiff(boost::array<double,2> const& a, double b);\n\n/*! \\brief Calculates the sum of two two-expansions.\n   \\param a First two expansion\n   \\param b Second two expansio\n   \\return sum\n */\nvector<double> twoTwoSum(boost::array<double,2> const& a,boost::array<double,2> const& b);\n\n/*! \\brief Calculates the difference between two two-expansions.\n   \\param a First two expansion\n   \\param b Second two expansion\n   \\return Difference\n */\nvector<double> twoTwoDiff(boost::array<double,2> const& a, boost::array<double,2> const& b);\n\n/*! \\brief Adds a scalar to an existing expansion.\n  \\param e Expansion\n  \\param b Scalar\n  \\return Expansion\n */\nvector<double> growExpansionZeroElim(vector<double> const& e, double b);\n\n/*! \\brief Adds up two expansions.\n   \\param e First expansion\n   \\param f Second expansion\n   \\return Sum\n */\nvector<double> expansionSumZeroElim(vector<double> const& e, vector<double> const& f);\n\n/*! \\brief Adds up two expansions.\n  \\param e First expansion\n  \\param f Second expansion\n  \\return Sum\n */\nvector<double> fastExpansionSumZeroElim(vector<double> const& e, vector<double> const& f);\n\n/*! \\brief Adds up two expansions.\n  \\param e First expansion\n  \\param f Second expansion\n  \\return Expansion\n */\nvector<double> linearExpansionSumZeroElim(vector<double> const& e, vector<double> const& f);\n\n/*! \\brief Multiplies a scalar by an expansion.\n  \\param e Expansion\n  \\param b Scalar\n  \\param result Result\n */\nvoid scaleExpansionZeroElim(vector<double> const& e, double b,\n\tvector<double> &result);\n\n/*! \\brief Compresses an expansion.\n   \\param e Expansion\n   \\return Expansion\n */\nvector<double> compress(vector<double> const& e);\n\n/*! \\brief Calculate a double precision approximation of the expansion.\n  \\param e Expansion\n  \\return A number\n */\ndouble estimate(vector<double> const& e);\n\n#endif //EXACTMATH_HPP\n", "meta": {"hexsha": "5517b96817f3ce5c77f6861bc50bd5b61a8c3d2a", "size": 3856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/exactmath.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/exactmath.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/tessellation/exactmath.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": 26.0540540541, "max_line_length": 92, "alphanum_fraction": 0.7098029046, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430520409023, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5588038149828439}}
{"text": "#include \"exponential_families.h\"\n\n#include <cmath>\n\n#include <boost/math/special_functions/trigamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\n// #include \"variational_parameters.h\"\n\n#include <Eigen/Sparse>\ntypedef Eigen::Triplet<double> Triplet; // For populating sparse matrices\n\n# if INSTANTIATE_EXPONENTIAL_FAMILIES_H\n  # include <stan/math.hpp>\n  # include \"stan/math/fwd/scal.hpp\"\n  using var = stan::math::var;\n  using fvar = stan::math::fvar<var>;\n# endif\n\nusing boost::math::lgamma;\nusing boost::math::digamma;\nusing boost::math::trigamma;\n\n\n// The index in a vector of lower diagonal terms of a particular matrix value.\nint get_ud_index(int i, int j) {\n  // If the column is less than the row it's already an upper diagonal index.\n  return j <= i ? (j + i * (i + 1) / 2):\n                  (i + j * (j + 1) / 2);\n};\n\n////////////////////////////////////////////\n// Multivariate log gamma and derivatives\n\n///////////////////////////\n// Multivariate normals\n\nMatrixXd GetNormalCovariance(VectorXd const &e_mu, MatrixXd const &e_mu2) {\n  return e_mu2 - (e_mu * e_mu.transpose());\n}\n\n\n// Get Cov(mu_i1 mu_i2, mu_c mu_d) from the moment parameters of a multivariate\n// normal distribution.\n//\n// e_mu = E(mu)\n// cov_mu = E(mu mu^T) - E(mu) E(mu^T)\ndouble GetNormalFourthOrderCovariance(\n    VectorXd const &e_mu, MatrixXd const &cov_mu,\n\t\tint i1, int i2, int j1, int j2) {\n\n  return (cov_mu(i1, j1) * cov_mu(i2, j2) +\n          cov_mu(i1, j2) * cov_mu(i2, j1) +\n\t      cov_mu(i1, j1) * e_mu(i2) * e_mu(j2) +\n          cov_mu(i1, j2) * e_mu(i2) * e_mu(j1) +\n\t      cov_mu(i2, j1) * e_mu(i1) * e_mu(j2) +\n          cov_mu(i2, j2) * e_mu(i1) * e_mu(j1));\n};\n\n\n// Get Cov(mu_i, mu_j1 mu_j2) from the moment parameters of a multivariate\n// normal distribution.\n//\n// e_mu = E(mu)\n// cov_mu = E(mu mu^T) - E(mu) E(mu^T)\ndouble GetNormalThirdOrderCovariance(\n    VectorXd const &e_mu, MatrixXd const &cov_mu, int i, int j1, int j2) {\n\n  return e_mu(j1) * cov_mu(i, j2) + e_mu(j2) * cov_mu(i, j1);\n};\n\n\n///////////////////////////////////////////\n// Wishart distributions\n\n// Construct the covariance of the elements of a Wishart-distributed\n// matrix.\n//\n// Args:\n//   - v_par: The wishart matrix parameter.\n//   - n_par: The n parameter of the Wishart distribution.\n//\n// Returns:\n//   - Cov(w_i1_j1, w_i2_j2), where w_i1_j1 and w_i2_j2 are terms of the\n//     Wishart matrix parameterized by  and n_par.\ndouble GetWishartLinearCovariance(\n    MatrixXd const &v_par, double n_par, int i1, int j1, int i2, int j2) {\n\n  return (n_par * (v_par(i1, j2) * v_par(i2, j1) +\n\t\t\t             v_par(i1, i2) * v_par(j1, j2)));\n}\n\n\n// Construct the covariance between the elements of a Wishart-distributed\n// matrix and the log determinant.  A little silly as a function, so\n// consider this documentation instead.\n//\n// Args:\n//   - v_par: A linearized representation of the upper triangular portion\n//            of the wishart parameter.\n//\n// Returns:\n//   - Cov(w_i1_i2, log(det(w)))\ndouble GetWishartLinearLogDetCovariance(MatrixXd const &v_par, int i1, int i2) {\n  return 2.0 * v_par(i1, i2);\n}\n\n\n// As above, but\n// Cov(log(det(w), log(det(w))))\n// ... where k is the dimension of the matrix.\ndouble GetWishartLogDetVariance(double n_par, int k) {\n  return multivariate_trigamma(n_par / 2, k);\n}\n\n\n////////////////////////////////////////\n// Gamma distribution\n\n// Return a matrix with Cov((g, log(g))) where\n// g ~ Gamma(alpha, beta) (parameterization E[g] = alpha / beta)\nMatrixXd get_gamma_covariance(double alpha, double beta) {\n    MatrixXd gamma_cov(2, 2);\n    gamma_cov(0, 0) = alpha / pow(beta, 2);\n    gamma_cov(0, 1) = 1 / beta;\n    gamma_cov(1, 0) = gamma_cov(0, 1);\n    gamma_cov(1, 1) = boost::math::trigamma(alpha);\n    return gamma_cov;\n}\n\n////////////////////////////\n// Categorical\n\n// Args:\n//   p: A size k vector of the z probabilities.\n// Returns:\n//   The covariance matrix.\nMatrixXd GetCategoricalCovariance(VectorXd p) {\n  MatrixXd p_outer = (-1) * p * p.transpose();\n  MatrixXd p_diagonal = p.asDiagonal();\n  p_outer = p_outer + p_diagonal;\n  return p_outer;\n}\n\n\nstd::vector<Triplet> GetCategoricalCovarianceTerms(VectorXd p, int offset) {\n  MatrixXd p_cov = GetCategoricalCovariance(p);\n  std::vector<Triplet> terms;\n  for (int i=0; i < p_cov.rows(); i++) {\n    for (int j=0; j < p_cov.cols(); j++) {\n      terms.push_back(Triplet(offset + i, offset + j, p_cov(i, j)));\n    }\n  }\n  return terms;\n}\n\n\n/////////////////////////////////\n// Dirichlet\n\nMatrixXd GetLogDirichletCovariance(VectorXd alpha) {\n  // Args:\n  //  - alpha: A vector of dirichlet parameters.\n  //\n  // Returns:\n  //  - The covariance of the log of a dirichlet distribution\n  //    with parameters alpha.\n\n  int k = alpha.size();\n  int k_index;\n  MatrixXd cov_mat(k, k);\n\n  // Precomute the total.\n  double alpha_0 = 0.0;\n  for (k_index = 0; k_index < k; k_index++) {\n    alpha_0 += alpha(k_index);\n  }\n  double covariance_term = -1.0 * boost::math::trigamma(alpha_0);\n  cov_mat.setConstant(covariance_term);\n\n  // Only the diagonal entries deviate from covariance_term.\n  for (k_index = 0; k_index < k; k_index++) {\n    cov_mat(k_index, k_index) += boost::math::trigamma(alpha(k_index));\n  }\n  return cov_mat;\n};\n\n\n\n///////////////////////////////////\n// Coordinates and covariances for sparse matrices\n\n// Assumes that e_mu and e_mu2_offset are stored linearly starting\n// at their respective offsets.\n// TODO: like everything else, express this in terms of natural parameters.\nstd::vector<Triplet> get_mvn_covariance_terms(\n    VectorXd e_mu, MatrixXd e_mu2, int e_mu_offset, int e_mu2_offset) {\n\n  std::vector<Triplet> terms;\n  int k = e_mu.size();\n  if (k != e_mu2.rows() || k !=e_mu2.cols()) {\n    throw std::runtime_error(\"e_mu2 is not square\");\n  }\n\n  MatrixXd cov_mu = GetNormalCovariance(e_mu, e_mu2);\n\n  // Cov(mu, mu^T)\n  for (int i = 0; i < k; i++) {\n    for (int j = 0; j < k; j++) {\n      terms.push_back(Triplet(e_mu_offset + i, e_mu_offset + j, cov_mu(i, j)));\n    }\n  }\n\n  // Cov(mu, mu mu^T)\n  for (int j1 = 0; j1 < k; j1++) {\n    for (int j2 = 0; j2 <= j1; j2++) {\n      for (int i = 0; i < k; i++) {\n        double this_cov = GetNormalThirdOrderCovariance(e_mu, cov_mu, i, j1, j2);\n        terms.push_back(\n          Triplet(e_mu_offset + i, e_mu2_offset + get_ud_index(j1, j2),\n                  this_cov));\n        terms.push_back(\n          Triplet(e_mu2_offset + get_ud_index(j1, j2), e_mu_offset + i,\n                  this_cov));\n      }\n    }\n  }\n\n  // Cov(mu mu^T, mu mu^T)\n  for (int i1 = 0; i1 < k; i1++) { for (int i2 = 0; i2 <= i1; i2++) {\n    for (int j1 = 0; j1 < k; j1++) { for (int j2 = 0; j2 <= j1; j2++) {\n      double this_cov = GetNormalFourthOrderCovariance(e_mu, cov_mu, i1, i2, j1, j2);\n      terms.push_back(Triplet(\n        e_mu2_offset + get_ud_index(i1, i2),\n        e_mu2_offset + get_ud_index(j1, j2),\n        this_cov));\n      }}\n  }}\n\n  return terms;\n};\n\n\n\nstd::vector<Triplet> get_normal_covariance_terms(\n    double mean, double info, int e_mu_offset, int e_mu2_offset) {\n\n    MatrixXd cov_mu(1, 1);\n    cov_mu << 1 / info;\n    VectorXd e_mu(1);\n    e_mu << mean;\n\n    std::vector<Triplet> terms;\n    terms.push_back(Triplet(e_mu_offset, e_mu_offset, cov_mu(0, 0)));\n    double cov_mu_mu2 = GetNormalThirdOrderCovariance(e_mu, cov_mu, 0, 0, 0);\n    terms.push_back(Triplet(e_mu_offset, e_mu2_offset, cov_mu_mu2));\n    terms.push_back(Triplet(e_mu2_offset, e_mu_offset, cov_mu_mu2));\n    double cov_mu2_mu2 = GetNormalFourthOrderCovariance(e_mu, cov_mu, 0, 0, 0, 0);\n    terms.push_back(Triplet(e_mu2_offset, e_mu2_offset, cov_mu2_mu2));\n    return terms;\n};\n\n\nstd::vector<Triplet> get_wishart_covariance_terms(\n    MatrixXd v_par, double n_par, int e_lambda_offset, int e_log_det_lambda_offset) {\n\n  std::vector<Triplet> terms;\n  int k = v_par.rows();\n  if (k != v_par.cols()) {\n    throw std::runtime_error(\"V is not square\");\n  }\n\n  for (int i1 = 0; i1 < k; i1++) { for (int j1 = 0; j1 <= i1; j1++) {\n    int i_ind = e_lambda_offset + get_ud_index(i1, j1);\n    double this_cov = GetWishartLinearLogDetCovariance(v_par, i1, j1);\n    terms.push_back(Triplet(i_ind, e_log_det_lambda_offset, this_cov));\n    terms.push_back(Triplet(e_log_det_lambda_offset, i_ind, this_cov));\n\t  for (int i2 = 0; i2 < k; i2++) { for (int j2 = 0; j2 <= i2; j2++) {\n      int j_ind = e_lambda_offset + get_ud_index(i2, j2);\n\t    terms.push_back(Triplet(i_ind, j_ind,\n        GetWishartLinearCovariance(v_par, n_par, i1, j1, i2, j2)));\n\t  }}\n  }}\n  terms.push_back(Triplet(e_log_det_lambda_offset, e_log_det_lambda_offset,\n    GetWishartLogDetVariance(n_par, k)));\n\n  return terms;\n};\n\n\nstd::vector<Triplet> get_gamma_covariance_terms(\n    double alpha, double beta, int e_tau_offset, int e_log_tau_offset) {\n\n  std::vector<Triplet> terms;\n  MatrixXd tau_cov = get_gamma_covariance(alpha, beta);\n  terms.push_back(Triplet(e_tau_offset, e_tau_offset, tau_cov(0, 0)));\n  terms.push_back(Triplet(e_log_tau_offset, e_tau_offset, tau_cov(0, 1)));\n  terms.push_back(Triplet(e_tau_offset, e_log_tau_offset, tau_cov(1, 0)));\n  terms.push_back(Triplet(e_log_tau_offset, e_log_tau_offset, tau_cov(1, 1)));\n\n  return terms;\n};\n\n\nstd::vector<Triplet> get_dirichlet_covariance_terms(VectorXd alpha, int offset) {\n  std::vector<Triplet> terms;\n  MatrixXd q_cov = GetLogDirichletCovariance(alpha);\n  for (int i=0; i < q_cov.rows(); i++) {\n    for (int j=0; j < q_cov.cols(); j++) {\n      terms.push_back(Triplet(offset + i, offset + j, q_cov(i, j)));\n    }\n  }\n\n  return terms;\n}\n\n\n\n# if INSTANTIATE_EXPONENTIAL_FAMILIES_H\n  template double multivariate_lgamma(double x, int p);\n  template var multivariate_lgamma(var x, int p);\n  template fvar multivariate_lgamma(fvar x, int p);\n\n  template double multivariate_digamma(double x, int p);\n  template var multivariate_digamma(var x, int p);\n  template fvar multivariate_digamma(fvar x, int p);\n\n  template double multivariate_trigamma(double x, int p);\n  // Not implemented.\n  // template var multivariate_trigamma(var x, int p);\n  // template fvar multivariate_trigamma(fvar x, int p);\n\n  template double GetELogDetWishart(MatrixXT<double> v_par, double n_par);\n  template var GetELogDetWishart(MatrixXT<var> v_par, var n_par);\n  template fvar GetELogDetWishart(MatrixXT<fvar> v_par, fvar n_par);\n\n  template double GetWishartEntropy(MatrixXT<double> const &v_par, double const n_par);\n  template var GetWishartEntropy(MatrixXT<var> const &v_par, var const n_par);\n  template fvar GetWishartEntropy(MatrixXT<fvar> const &v_par, fvar const n_par);\n\n  template double get_e_log_gamma(double alpha, double beta);\n  template var get_e_log_gamma(var alpha, var beta);\n  template fvar get_e_log_gamma(fvar alpha, fvar beta);\n\n  template VectorXT<double> GetELogDirichlet(VectorXT<double> alpha);\n  template VectorXT<var> GetELogDirichlet(VectorXT<var> alpha);\n  template VectorXT<fvar> GetELogDirichlet(VectorXT<fvar> alpha);\n\n  template double GetDirichletEntropy(VectorXT<double> alpha);\n  template var GetDirichletEntropy(VectorXT<var> alpha);\n  template fvar GetDirichletEntropy(VectorXT<fvar> alpha);\n\n  template double GetMultivariateNormalEntropy(MatrixXT<double>);\n  template var GetMultivariateNormalEntropy(MatrixXT<var>);\n  template fvar GetMultivariateNormalEntropy(MatrixXT<fvar>);\n\n  template double GetUnivariateNormalEntropy(double);\n  template var GetUnivariateNormalEntropy(var);\n  template fvar GetUnivariateNormalEntropy(fvar);\n\n  template double GetGammaEntropy(double, double);\n  template var GetGammaEntropy(var, var);\n  template fvar GetGammaEntropy(fvar, fvar);\n# endif\n", "meta": {"hexsha": "91a373524923686c76a91eef9b2b077395237db0", "size": 11612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/exponential_families.cpp", "max_stars_repo_name": "rgiordan/LinearResponseVariationalBayes.cpp", "max_stars_repo_head_hexsha": "99b0666bbb9e1c8a1b020b133bcc289f894c07c4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/exponential_families.cpp", "max_issues_repo_name": "rgiordan/LinearResponseVariationalBayes.cpp", "max_issues_repo_head_hexsha": "99b0666bbb9e1c8a1b020b133bcc289f894c07c4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/exponential_families.cpp", "max_forks_repo_name": "rgiordan/LinearResponseVariationalBayes.cpp", "max_forks_repo_head_hexsha": "99b0666bbb9e1c8a1b020b133bcc289f894c07c4", "max_forks_repo_licenses": ["Apache-2.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.7267759563, "max_line_length": 87, "alphanum_fraction": 0.6689631416, "num_tokens": 3521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5587678539651495}}
{"text": "#include <armadillo>\n#include \"armaMex.hpp\"\nusing namespace arma;\n\n\nvoid mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray *prhs[]) {\n    \n    mat K0 = armaGetPr(prhs[0]);\n    mat S = armaGetPr(prhs[1]); \n    uvec idr = conv_to<uvec>::from(armaGetPr(prhs[2])) - 1; \n    uvec idc = conv_to<uvec>::from(armaGetPr(prhs[3])) - 1;  \n    uword max_outer_iter, max_inner_iter;\n    if (nrhs > 4) max_outer_iter = (uword)armaGetDouble(prhs[4]);\n    else max_outer_iter = 100;\n    if (nrhs > 5) max_inner_iter = (uword)armaGetDouble(prhs[5]);\n    else max_inner_iter = 100;\n    \n    uword p = K0.n_cols, iter_outer, iter_inner, p_od = idr.n_elem, i;\n    uvec idl = idc * p + idr, idu = idr * p + idc, idd = linspace<uvec>(0, p - 1, p), ida = join_cols(idd * p + idd, idl);\n    vec Sida = S(ida), Sidu = S(idu), Did(p + p_od), gradK, Kd = K0.diag();\n    mat U(p, p, fill::zeros), W, Kh(p, p, fill::zeros);\n    double a, b, mu, diffD = 0;\n    \n    \n    double objh, xi0 = 1, xi, sum_grad2;\n    while (! K0.is_sympd()) {\n        K0 *= 0.9;\n        K0.diag() = Kd;\n    }\n    double obj0 = - 2*accu(log(mat(chol(K0)).diag())) + accu(Sida % K0(ida)) + accu(Sidu % K0(idu));\n    \n    for (iter_outer = 0; iter_outer < max_outer_iter; iter_outer ++) {\n        W = inv_sympd(K0);\n        gradK = Sida - W(ida);\n        Did.zeros();\n        U.zeros();\n        for (iter_inner = 0; iter_inner < max_inner_iter; iter_inner ++) {\n            for (i = 0; i < p; i++) {\n                a = pow(W(i, i), 2);\n                b = gradK(i) + accu(W.col(i) % U.col(i));\n                mu = - b / a;\n                Did(i) += mu;\n                U.row(i) += mu * W.row(i);\n                diffD += fabs(mu);\n            }\n            \n            for (i = 0; i < p_od; i ++) {\n                a = pow(W(idl(i)), 2) + W(idr(i), idr(i)) * W(idc(i), idc(i));\n                b = gradK(p + i) + accu(W.col(idr(i)) % U.col(idc(i)));\n                mu = - b / a;\n                Did(p + i) += mu;\n                U.row(idr(i)) += mu * W.row(idc(i));\n                U.row(idc(i)) += mu * W.row(idr(i));\n                diffD += fabs(mu);\n            }\n            \n            if (diffD < 0.05 * accu(abs(Did))) break;\n            else diffD = 0;\n        }\n        sum_grad2 = accu(Did % gradK);\n        xi = xi0;\n        while (true) {\n            Kh(ida) = K0(ida) + xi * Did;\n            Kh(idu) = Kh(idl);\n            if (Kh.is_sympd()) {\n                objh = - 2*accu(log(mat(chol(Kh)).diag())) + accu(Sida % Kh(ida)) + accu(Sidu % Kh(idu));\n                if (objh <= obj0 + 1e-3 * xi * sum_grad2)\n                    break;\n                else\n                    xi /= 2;\n            } else\n                xi /=2;\n        }\n        // printf(\"xi = %e\\n\", xi);\n        if (abs(Kh - K0).max() < 1e-10 && fabs(obj0 - objh ) < 1e-10) {\n            break;\n        } else {\n            obj0 = objh;\n            K0 = Kh;\n        }\n    }\n    \n    plhs[0] = armaCreateMxMatrix(p,p,mxDOUBLE_CLASS,mxREAL);\n    armaSetPr(plhs[0],Kh);\n}", "meta": {"hexsha": "edd56e7539b5a09f31e37d6adf90a923df47d943", "size": 3013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QUICParameterLearning.cpp", "max_stars_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_stars_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "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": "QUICParameterLearning.cpp", "max_issues_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_issues_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-21T01:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T01:00:25.000Z", "max_forks_repo_path": "QUICParameterLearning.cpp", "max_forks_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_forks_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4470588235, "max_line_length": 122, "alphanum_fraction": 0.4463989379, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875225, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5587389171826337}}
{"text": "#include <Eigen/SparseCore>\n#include <hops/FileReader/CsvReader.hpp>\n#include <hops/FileWriter/FileWriterFactory.hpp>\n#include <hops/LinearProgram/LinearProgramFactory.hpp>\n#include <hops/MarkovChain/MarkovChainFactory.hpp>\n#include <hops/Model/MultivariateGaussianModel.hpp>\n#include <hops/MarkovChain/Tuning/BinarySearchAcceptanceRateTuner.hpp>\n#include <hops/Polytope/NormalizePolytope.hpp>\n#include <iostream>\n#include <hops/Polytope/MaximumVolumeEllipsoid.hpp>\n\nusing RealType = double;\n\nint main(int argc, char **argv) {\n    if (argc != 10 && argc != 9) {\n        std::cout << \"usage: SamplingGaussianTarget A.csv b.csv mean.csv covariance.csv \"\n                  << \"numberOfSamples thinningNumber CHRR|HRR|DikinWalk outputName [startingPoint.csv]\"\n                  << \"\\nArgument Description:\\n\"\n                  << \"\\tA.csv\\t\\t\\t\\t nxm dimensional matrix of polytope Ax<b\\n\"\n                  << \"\\tb.csv\\t\\t\\t\\t n dimensional vector of polytope Ax<b\\n\"\n                  << \"\\tmean.csv\\t\\t\\t m dimensional vector\\n\"\n                  << \"\\tcovariance.csv\\t\\t mxm dimensional matrix\\n\"\n                  << \"\\tnumberOfSamples\\t\\t number of samples to generate\\n\"\n                  << \"\\tthinningNumber\\t\\t number of markov chain iterations per sample\\n\"\n                  << \"\\talgorithm\\t\\t\\t CHRR or HRR or DikinWalk\\n\"\n                  << \"\\toutputName\\t\\t\\t name for output\\n\"\n                  << \"\\t[startingPoint]\\t\\t optional starting point, useful for resuming sampling\" << std::endl;\n        exit(0);\n    }\n\n    Eigen::SparseMatrix<RealType> A = hops::CsvReader::readMatrix<Eigen::SparseMatrix<double>>(\n            argv[1]).cast<RealType>();\n    Eigen::Matrix<RealType, Eigen::Dynamic, 1> b = hops::CsvReader::readVector<Eigen::Matrix<double, Eigen::Dynamic, 1>>(\n            argv[2]).cast<RealType>();\n    Eigen::Matrix<RealType, Eigen::Dynamic, 1> mean = hops::CsvReader::readVector<Eigen::Matrix<double, Eigen::Dynamic, 1>>(\n            argv[3]).cast<RealType>();\n    Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic> covariance = hops::CsvReader::readMatrix<Eigen::MatrixXd>(\n            argv[4]).cast<RealType>();\n    long numberOfSamples = std::strtol(argv[5], NULL, 10);\n    long thinning = std::strtol(argv[6], NULL, 10);\n    std::string chainName = argv[7];\n\n    hops::MultivariateGaussianModel model(mean, covariance);\n\n    std::unique_ptr<hops::MarkovChain> markovChain;\n    if (chainName == \"DikinWalk\") {\n        hops::MarkovChainType chainType = hops::MarkovChainType::DikinWalk;\n        decltype(b) startingPoint;\n        if (argc == 10) {\n            startingPoint = hops::CsvReader::readVector<Eigen::Matrix<double, Eigen::Dynamic, 1>>(\n                    argv[9]).cast<RealType>();\n        } else {\n            std::unique_ptr<hops::LinearProgram> linearProgram = hops::LinearProgramFactory::createLinearProgram(\n                    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>(A.cast<double>()),\n                    b.cast<double>();\n            startingPoint = linearProgram->computeChebyshevCenter().optimalParameters.cast<RealType>();\n        }\n\n        markovChain = hops::MarkovChainFactory::createMarkovChain(chainType,\n                                                                  A,\n                                                                  b,\n                                                                  startingPoint,\n                                                                  model);\n    } else if (chainName == \"CHRR\" || chainName == \"HRR\") {\n        hops::MarkovChainType chainType =\n                chainName == \"CHRR\" ? hops::MarkovChainType::CoordinateHitAndRun : hops::MarkovChainType::HitAndRun;\n        Eigen::MatrixXd roundingTransformation = hops::MaximumVolumeEllipsoid<double>::construct(\n                A,\n                b,\n                50000, 1e-9).getRoundingTransformation();\n\n        decltype(b) startingPoint;\n        if (argc == 10) {\n            startingPoint = hops::CsvReader::readVector<Eigen::Matrix<double, Eigen::Dynamic, 1>>(\n                    argv[9]).cast<RealType>();\n        } else {\n            std::unique_ptr<hops::LinearProgram> linearProgram = hops::LinearProgramFactory::createLinearProgram(\n                    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>((A * roundingTransformation).cast<double>()),\n                    b.cast<double>());\n            startingPoint = linearProgram->computeChebyshevCenter().optimalParameters.cast<RealType>();\n        }\n        markovChain = hops::MarkovChainFactory::createMarkovChain<Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic>, decltype(b), decltype(model)>(\n                chainType,\n                Eigen::Matrix<RealType, Eigen::Dynamic, Eigen::Dynamic>(A * roundingTransformation),\n                b,\n                startingPoint,\n                roundingTransformation,\n                decltype(startingPoint)::Zero(roundingTransformation.rows()),\n                model);\n    } else {\n        std::cerr << \"No chain with chainname \" << chainName << std::endl;\n        std::exit(1);\n    }\n\n    hops::RandomNumberGenerator randomNumberGenerator((std::random_device()()));\n\n    float upperLimitAcceptanceRate = 0.3;\n    float lowerLimitAcceptanceRate = 0.20;\n    double lowerLimitStepSize = 1e-15;\n    double upperLimitStepSize = 1;\n    size_t iterationsToTestStepSize = 100 * A.cols();\n    size_t maxIterations = 10000 * A.cols();\n\n    bool isTuned = false;\n    // Tuning loop\n    for (int i = 0; i < 10; ++i) {\n        markovChain->draw(randomNumberGenerator, 1, numberOfSamples);\n        markovChain->setAttribute(hops::MarkovChainAttribute::STEP_SIZE, 1);\n\n        isTuned = hops::AcceptanceRateTuner::tune(markovChain.get(),\n                                                  randomNumberGenerator,\n                                                  {lowerLimitAcceptanceRate,\n                                                   upperLimitAcceptanceRate,\n                                                   lowerLimitStepSize,\n                                                   upperLimitStepSize,\n                                                   iterationsToTestStepSize,\n                                                   maxIterations});\n        markovChain->clearHistory();\n    }\n    std::cout << \"Markov chain tuned successfully : \" << std::boolalpha << isTuned\n              << \" (false is not a problem for CHRR|HRR)\" << std::endl;\n    std::cout << \"Current step size: \" << markovChain->getAttribute(hops::MarkovChainAttribute::STEP_SIZE) << std::endl;\n\n    auto fileWriter = hops::FileWriterFactory::createFileWriter(std::string(argv[8]) + \"_\" + markovChain->getName(),\n                                                                hops::FileWriterType::CSV);\n    markovChain->draw(randomNumberGenerator, numberOfSamples, thinning);\n    markovChain->writeHistory(fileWriter.get());\n    markovChain->clearHistory();\n}\n", "meta": {"hexsha": "8d7fa95ab649c69b54481478d572e70e232d94cc", "size": 6931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bin/SamplingGaussianTargetDemo.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "bin/SamplingGaussianTargetDemo.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "bin/SamplingGaussianTargetDemo.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.3153846154, "max_line_length": 153, "alphanum_fraction": 0.5801471649, "num_tokens": 1545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5587114279406867}}
{"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 \"centroid.h\"\n#include <Eigen/Geometry>\n\ntemplate <\n  typename DerivedV, \n  typename DerivedF, \n  typename Derivedc, \n  typename Derivedvol>\nIGL_INLINE void igl::centroid(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<Derivedc>& cen,\n  Derivedvol & vol)\n{\n  using namespace Eigen;\n  assert(F.cols() == 3 && \"F should contain triangles.\");\n  assert(V.cols() == 3 && \"V should contain 3d points.\");\n  const int m = F.rows();\n  cen.setZero();\n  vol = 0;\n  // loop over faces\n  for(int f = 0;f<m;f++)\n  {\n    // \"Calculating the volume and centroid of a polyhedron in 3d\" [Nuernberg 2013]\n    // http://www2.imperial.ac.uk/~rn/centroid.pdf\n    // rename corners\n    typedef Eigen::Matrix<typename DerivedV::Scalar,1,3> RowVector3S;\n    const RowVector3S & a = V.row(F(f,0));\n    const RowVector3S & b = V.row(F(f,1));\n    const RowVector3S & c = V.row(F(f,2));\n    // un-normalized normal\n    const RowVector3S & n = (b-a).cross(c-a);\n    // total volume via divergence theorem: ∫ 1\n    vol += n.dot(a)/6.;\n    // centroid via divergence theorem and midpoint quadrature: ∫ x\n    cen.array() += (1./24.*n.array()*((a+b).array().square() + (b+c).array().square() + \n        (c+a).array().square()).array());\n  }\n  cen *= 1./(2.*vol);\n}\n\ntemplate <\n  typename DerivedV, \n  typename DerivedF, \n  typename Derivedc>\nIGL_INLINE void igl::centroid(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<Derivedc>& c)\n{\n  typename Derivedc::Scalar vol;\n  return centroid(V,F,c,vol);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::centroid<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 1, 3, 1, 1, 3>, double>(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, 1, 1, 3> >&, double&);\n// generated by autoexplicit.sh\ntemplate void igl::centroid<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, 3, 1, 0, 3, 1>, float>(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, 3, 1, 0, 3, 1> >&, float&);\n// generated by autoexplicit.sh\ntemplate void igl::centroid<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, 3, 1, 0, 3, 1> >(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, 3, 1, 0, 3, 1> >&);\n// generated by autoexplicit.sh\ntemplate void igl::centroid<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<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<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, 1, 3, 1, 1, 3> >&);\ntemplate void igl::centroid<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::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, 3, 1, 0, 3, 1> >&);\ntemplate void igl::centroid<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 1, 3, 1, 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, 1, 1, 3> >&);\n#endif\n", "meta": {"hexsha": "7344ea840dda689367bd06d417aaa0b37c729c9d", "size": 4220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/centroid.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/centroid.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/centroid.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": 57.027027027, "max_line_length": 367, "alphanum_fraction": 0.6398104265, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5587114232041092}}
{"text": "/*\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http://mozilla.org/MPL/2.0/.\n*/\n\n#include <Eigen/Dense>\n\n#include \"morleyElement.h\"\n\n#include \"morleyElementBuilder.h\"\n\n\nnamespace Vitelotte\n{\n\n\ntemplate < class _Mesh, typename _Scalar >\nMorleyElementBuilder<_Mesh, _Scalar>::MorleyElementBuilder(Scalar sigma)\n    : m_sigma(sigma)\n{\n}\n\ntemplate < class _Mesh, typename _Scalar >\nunsigned\nMorleyElementBuilder<_Mesh, _Scalar>::\n    nCoefficients(const Mesh& /*mesh*/, Face /*element*/,\n                  SolverError* /*error*/) const\n{\n    return 36;\n}\n\n\ntemplate < class _Mesh, typename _Scalar >\ntemplate < typename Inserter >\nvoid\nMorleyElementBuilder<_Mesh, _Scalar>::\n    addCoefficients(Inserter& inserter, const Mesh& mesh,\n                    Face element, SolverError* error)\n{\n    if(mesh.valence(element) != 3)\n    {\n        if(error) error->error(\"Non-triangular face\");\n        return;\n    }\n\n    // TODO: remove dynamic allocation with dynamic dims.\n    Vector p[3];\n    Vector v[3];\n    bool orient[3];\n    int nodes[6];\n\n    typename Mesh::HalfedgeAroundFaceCirculator hit = mesh.halfedges(element);\n    --hit;\n    for(int i = 0; i < 3; ++i)\n    {\n        v[i] = (mesh.position(mesh.toVertex(*hit)) -\n                mesh.position(mesh.fromVertex(*hit))).template cast<Scalar>();\n        orient[i] = mesh.halfedgeOrientation(*hit);\n        nodes[i+3] = mesh.edgeGradientNode(*hit).idx();\n        ++hit;\n        nodes[i] = mesh.toVertexValueNode(*hit).idx();\n        p[i] = mesh.position(mesh.toVertex(*hit)).template cast<Scalar>();\n    }\n\n    for(int i = 0; i < 6; ++i)\n    {\n        if(nodes[i] < 0)\n        {\n            if(error) error->error(\"Invalid node\");\n            return;\n        }\n    }\n\n    typedef MorleyElement<Scalar> Elem;\n    Elem elem(p);\n\n    if(elem.doubleArea() <= 0 && error)\n    {\n        error->warning(\"Degenerated or reversed triangle\");\n    }\n\n    typedef Eigen::Matrix<Scalar, 3, 1> Vector3;\n    Vector6 dx2;\n    Vector6 dxy;\n    Vector6 dy2;\n    Vector3 bc = Vector3(1, 1, 1) / 3;\n    typename Elem::Hessian hessians[6];\n    elem.hessian(bc, hessians);\n\n    for(int bi = 0; bi < 6; ++bi)\n    {\n        dx2(bi) = hessians[bi](0, 0);\n        dy2(bi) = hessians[bi](1, 1);\n        dxy(bi) = hessians[bi](0, 1);\n    }\n\n    for(int i = 0; i < 6; ++i)\n    {\n        for(int j = i; j < 6; ++j)\n        {\n            Scalar value =\n                    ((dx2(i) + dy2(i)) * (dx2(j) + dy2(j)) +\n                    (1-m_sigma) * ( 2*dxy(i)*dxy(j) - dx2(i)*dy2(j) - dy2(i)*dx2(j)));\n            value *= elem.doubleArea() / 2;\n            if((i < 3 || orient[i%3]) != (j < 3 || orient[j%3]))\n            {\n                value *= -1;\n            }\n            inserter.addCoeff(nodes[i], nodes[j], value);\n        }\n    }\n}\n\n\n}\n", "meta": {"hexsha": "29677b4d950665754b21d371539555b63e5bcdbe", "size": 2885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/morleyElementBuilder.hpp", "max_stars_repo_name": "HoEmpire/slambook2", "max_stars_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/morleyElementBuilder.hpp", "max_issues_repo_name": "HoEmpire/slambook2", "max_issues_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_issues_repo_licenses": ["MIT"], "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/meshlab-master/src/plugins_experimental/filter_multiscale_align/lib/Patate/Vitelotte/Core/morleyElementBuilder.hpp", "max_forks_repo_name": "HoEmpire/slambook2", "max_forks_repo_head_hexsha": "96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4", "max_forks_repo_licenses": ["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.6581196581, "max_line_length": 86, "alphanum_fraction": 0.5535528596, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.558711423204109}}
{"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_STATISTICS_FUNCTIONS_GENERIC_EVPDF_HPP_INCLUDED\n#define NT2_STATISTICS_FUNCTIONS_GENERIC_EVPDF_HPP_INCLUDED\n#include <nt2/statistics/functions/evpdf.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <nt2/include/functions/globalall.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/is_equal.hpp>\n#include <nt2/include/functions/is_gtz.hpp>\n#include <nt2/include/functions/rec.hpp>\n#include <nt2/include/functions/uminus.hpp>\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/functions/simd/if_zero_else.hpp>\n#include <nt2/include/constants/inf.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT  ( evpdf_, tag::cpu_\n                              , (A0)\n                              , (generic_< floating_<A0> >)\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n      {\n        result_type tmp = exp(a0);\n        tmp *= exp(-tmp);\n#ifndef BOOST_SIMD_NO_INFINITIES\n        return if_zero_else(eq(a0, Inf<A0>()), tmp);\n#else\n        return tmp;\n#endif\n      }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( evpdf_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< floating_<A0> >)\n                              (generic_< floating_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        result_type tmp = exp((a0-a1));\n        tmp *= exp(-tmp);\n#ifndef BOOST_SIMD_NO_INFINITIES\n        return if_zero_else(eq(a0, Inf<A0>()), tmp);\n#else\n        return tmp;\n#endif\n      }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( evpdf_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , (generic_< floating_<A0> >)\n                              (generic_< floating_<A1> >)\n                              (generic_< floating_<A2> >)\n                              )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(3)\n      {\n        BOOST_ASSERT_MSG(nt2::globalall(nt2::is_gtz(a2)), \"sigma parameter must be positive\");\n        A0 invsig =  rec(a2);\n        result_type tmp = exp((a0-a1)*invsig);\n        tmp *= exp(-tmp)*invsig;\n#ifndef BOOST_SIMD_NO_INFINITIES\n        return if_zero_else(eq(a0, Inf<A0>()), tmp);\n#else\n        return tmp;\n#endif\n\n      }\n  };\n\n} }\n\n#endif\n", "meta": {"hexsha": "45e67ca810da36759bb587fb23ed8ca4ef5963cd", "size": 2815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/statistics/include/nt2/statistics/functions/generic/evpdf.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/statistics/include/nt2/statistics/functions/generic/evpdf.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/statistics/include/nt2/statistics/functions/generic/evpdf.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": 30.9340659341, "max_line_length": 94, "alphanum_fraction": 0.5396092362, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.5586676640325917}}
{"text": "/*\n*   farthest_sampling_by_sphere\n*   by R. Falque\n*   27/06/2019\n*/\n\n#ifndef FARTHEST_SAMPLING_BY_SPHERE_HPP\n#define FARTHEST_SAMPLING_BY_SPHERE_HPP\n\n#include <Eigen/Core>\n#include <limits> \n#include <iostream>\n\n#include \"nanoflannWrapper.hpp\"\n\nint argMax(const Eigen::VectorXd & data)\n{\n    int argmax = 0;\n    int max_dim = std::max(data.rows(), data.cols());\n    for (int i=0; i<max_dim; i++)\n        if (data(argmax) < data(i))\n            argmax = i;\n    return argmax;\n}\n\ninline bool farthest_sampling_by_sphere(const Eigen::MatrixXd & in_cloud, double sample_radius, Eigen::MatrixXd & nodes, Eigen::VectorXi & correspondences)\n{\n\n    correspondences = Eigen::VectorXi::Zero(in_cloud.rows());\n\n    nanoflann_wrapper knn_search(in_cloud);\n    std::vector<int> node_list;\n    Eigen::VectorXd mindst = Eigen::VectorXd::Constant(in_cloud.rows(), -1); // used as NaN\n\n\n    for (int i=0; i<in_cloud.rows(); i++) {\n\n        if (correspondences(i) == 0) {\n        \n            mindst(i) = std::numeric_limits<double>::infinity();\n\n            while ( (correspondences.array()==0).any() ) {\n\n                int maxId = argMax(mindst);\n\n                if ( mindst(maxId)==0 )\n                    break;\n\n                std::vector<int> neighbours_id;\n                std::vector<double> neighbours_distances;\n                knn_search.radius_search(in_cloud.row(maxId), sample_radius, neighbours_id, neighbours_distances);\n\n                bool all_corresp_marked = correspondences(neighbours_id[0])!=0;\n                for (int j=0; j<neighbours_id.size(); j++)\n                    all_corresp_marked = all_corresp_marked & correspondences(neighbours_id[j])!=0;\n                \n                if (all_corresp_marked) {\n                    mindst(maxId) = 0;\n                    break;\n                }\n\n                node_list.push_back(maxId);\n                for (int j=0; j<neighbours_id.size(); j++) {\n                    if ( mindst( neighbours_id[j] ) > neighbours_distances[j] || mindst(neighbours_id[j])==-1 )  {\n                        mindst( neighbours_id[j] ) = neighbours_distances[j];\n                        correspondences(neighbours_id[j]) = node_list.size();\n                    }\n                }\n            }\n        }\n    }\n\n    correspondences = correspondences.array() - 1;\n    if ( (correspondences.array() == -1).any() )\n    {\n        std::cout << \"point without correspondences!!!\\n\";\n        std::cin.get();\n    }\n\n    nodes.resize(node_list.size(), 3);\n    for (int i=0; i<node_list.size(); i++)\n        nodes.row(i) << in_cloud.row(node_list[i]);\n\n    return true;\n};\n\n// overload the declaration if correspondences are not needed\ninline bool farthest_sampling_by_sphere(const Eigen::MatrixXd & in_cloud, double sample_radius, Eigen::MatrixXd & nodes)\n{\n    Eigen::VectorXi correspondences;\n    return farthest_sampling_by_sphere(in_cloud, sample_radius, nodes, correspondences);\n};\n\n\n/*\ninline bool fast_poisson_disk_sampling(Eigen::MatrixXd & in_cloud, double minimum_distance, Eigen::MatrixXd & out_cloud)\n{\n    // Considering implementing the following paper as an alternative:\n    // https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf\n    int number_of_samples_to_consider = 30;\n\n    // generate the 3D grid\n\n}\n*/\n\n#endif\n", "meta": {"hexsha": "5003bf7091c02443aa67677c9bf96381dd988c3b", "size": 3287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "embedded_deformation/include/embedded_deformation/farther_sampling.hpp", "max_stars_repo_name": "jessemorris/embedded_deformation", "max_stars_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T06:23:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T23:42:04.000Z", "max_issues_repo_path": "embedded_deformation/include/embedded_deformation/farther_sampling.hpp", "max_issues_repo_name": "jessemorris/embedded_deformation", "max_issues_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-24T11:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-29T02:11:05.000Z", "max_forks_repo_path": "embedded_deformation/include/embedded_deformation/farther_sampling.hpp", "max_forks_repo_name": "jessemorris/embedded_deformation", "max_forks_repo_head_hexsha": "ae961994e022c04772b1304aac24d0ae13fc3610", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T10:08:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T03:38:35.000Z", "avg_line_length": 30.4351851852, "max_line_length": 155, "alphanum_fraction": 0.6060237298, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5586676588596565}}
{"text": "#if !defined(BALSA_EIGEN_STACK_HPP)\n#define BALSA_EIGEN_STACK_HPP\n\n#include <Eigen/Dense>\n#include <tuple>\n#include <vector>\n#include <type_traits>\n#include <utility>\n#include <algorithm>\n\n\nnamespace balsa::eigen {\ntemplate<bool Rows, typename... Args, int... N>\nauto _stack(std::integer_sequence<int, N...>, const Args &...args) {\n    using namespace Eigen;\n    using Scalar = typename std::tuple_element<0, std::tuple<Args...>>::type::Scalar;\n\n    constexpr static int minCompileRows = std::min<int>({ Args::RowsAtCompileTime... });\n    constexpr static int maxCompileRows = std::max<int>({ Args::RowsAtCompileTime... });\n    constexpr static int minCompileCols = std::min<int>({ Args::ColsAtCompileTime... });\n    constexpr static int maxCompileCols = std::max<int>({ Args::ColsAtCompileTime... });\n\n    constexpr static int sumCompileRows = (Args::RowsAtCompileTime + ... + 0);\n    constexpr static int sumCompileCols = (Args::ColsAtCompileTime + ... + 0);\n\n    //constexpr static int myCompRows = (minCompileRows==Dynamic)?Dynamic:(Rows?S:1)*maxCompileRows;\n    //constexpr static int myCompCols = (minCompileCols==Dynamic)?Dynamic:(Rows?1:S)*maxCompileCols;\n    constexpr static int myCompRows = (minCompileRows == Dynamic) ? Dynamic : (Rows ? sumCompileRows : maxCompileRows);\n    constexpr static int myCompCols = (minCompileCols == Dynamic) ? Dynamic : (Rows ? maxCompileCols : sumCompileCols);\n    int rows;\n    int cols;\n    std::vector<int> offset(1, 0);\n    auto push_sum = [&](int size) {\n        offset.push_back(offset.back() + size);\n    };\n    if constexpr (Rows) {\n        rows = (args.rows() + ... + 0);\n        cols = std::max({ args.cols()... });\n        (push_sum(args.rows()), ...);\n    } else {\n        rows = std::max({ args.rows()... });\n        cols = (args.cols() + ... + 0);\n        (push_sum(args.cols()), ...);\n    }\n\n\n    using Matf = Matrix<Scalar, myCompRows, myCompCols>;\n    Matf A = Matf::Constant(rows, cols, 0);\n\n\n    if constexpr (Rows) {\n        (A.block(offset[N], 0, args.rows(), args.cols()).operator=(args), ...);\n    } else {\n        (A.block(0, offset[N], args.rows(), args.cols()).operator=(args), ...);\n    }\n\n    return A;\n}\n\ntemplate<typename... Args>\nauto vstack(const Args &...args) {\n    return _stack<true>(std::make_integer_sequence<int, sizeof...(Args)>(), std::forward<const Args &>(args)...);\n}\ntemplate<typename... Args>\nauto hstack(const Args &...args) {\n    return _stack<false>(std::make_integer_sequence<int, sizeof...(Args)>(), std::forward<const Args &>(args)...);\n}\n\n\ntemplate<typename BeginIt, typename EndIt>\nauto hstack_iter(BeginIt beginit, EndIt endit) {\n    using CDerived = typename std::decay_t<decltype(*beginit)>;\n\n    constexpr static int CRows = CDerived::RowsAtCompileTime;\n    using Index = typename CDerived::Scalar;\n    using RetCells = Eigen::Matrix<Index, CRows, Eigen::Dynamic>;\n    int ccols = 0;\n    int crows = 0;\n\n    for (auto it = beginit; it != endit; ++it) {\n        auto &&c = *it;\n        if (c.size() > 0) {\n            crows = std::max<int>(crows, c.rows());\n            ccols += c.cols();\n        }\n    }\n    if (crows == 0 || ccols == 0) {\n        return RetCells{};\n    }\n    RetCells mC(crows, ccols);\n    ccols = 0;\n    for (auto it = beginit; it != endit; ++it) {\n        auto &&c = *it;\n        if (c.size() > 0) {\n            mC.block(0, ccols, c.rows(), c.cols()) = c;\n            ccols += c.cols();\n        }\n    }\n    return mC;\n}\ntemplate<typename BeginIt, typename EndIt>\nauto vstack_iter(BeginIt beginit, EndIt endit) {\n    using CDerived = typename std::decay_t<decltype(*beginit)>;\n\n    constexpr static int CCols = CDerived::ColsAtCompileTime;\n    using Index = typename CDerived::Scalar;\n    using RetCells = Eigen::Matrix<Index, Eigen::Dynamic, CCols>;\n    int ccols = 0;\n    int crows = 0;\n\n    for (auto it = beginit; it != endit; ++it) {\n        auto &&c = *it;\n        if (c.size() > 0) {\n            ccols = std::max<int>(ccols, c.cols());\n            crows += c.rows();\n        }\n    }\n    if (crows == 0 || ccols == 0) {\n        return RetCells{};\n    }\n    RetCells mC(crows, ccols);\n    crows = 0;\n    for (auto it = beginit; it != endit; ++it) {\n        auto &&c = *it;\n        if (c.size() > 0) {\n            mC.block(crows, 0, c.rows(), c.cols()) = c;\n            crows += c.rows();\n        }\n    }\n    return mC;\n}\n\n}// namespace balsa::eigen\n#endif\n\n", "meta": {"hexsha": "1ce67f080d268a16b97fb0c4f921d10f4ad8f8d3", "size": 4382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/balsa/eigen/stack.hpp", "max_stars_repo_name": "mtao/balsa", "max_stars_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/balsa/eigen/stack.hpp", "max_issues_repo_name": "mtao/balsa", "max_issues_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/balsa/eigen/stack.hpp", "max_forks_repo_name": "mtao/balsa", "max_forks_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_forks_repo_licenses": ["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.2205882353, "max_line_length": 119, "alphanum_fraction": 0.5910543131, "num_tokens": 1231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.5586676577216934}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2015 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 \"angles.h\"\n#include <Eigen/Geometry>\n#include <cassert>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename Derivedtheta>\nvoid igl::angles(\n  const Eigen::PlainObjectBase<DerivedV>& V,\n  const Eigen::PlainObjectBase<DerivedF>& F,\n  Eigen::PlainObjectBase<Derivedtheta>& theta)\n{\n  theta.resize(F.rows(),F.cols());\n\n  auto corner = [](const Eigen::PlainObjectBase<DerivedV>& x, const Eigen::PlainObjectBase<DerivedV>& y, const Eigen::PlainObjectBase<DerivedV>& z)\n  {\n    Eigen::RowVector3d v1 = (x-y).normalized();\n    Eigen::RowVector3d v2 = (z-y).normalized();\n\n    // http://stackoverflow.com/questions/10133957/signed-angle-between-two-vectors-without-a-reference-plane\n    double s = v1.cross(v2).norm();\n    double c = v1.dot(v2);\n\n    return atan2(s, c);\n  };\n\n  for(unsigned i=0; i<F.rows(); ++i)\n  {\n    for(unsigned j=0; j<F.cols(); ++j)\n    {\n      theta(i,j) = corner(\n        V.row(F(i,int(j-1+F.cols())%F.cols())),\n        V.row(F(i,j)),\n        V.row(F(i,(j+1+F.cols())%F.cols()))\n        );\n    }\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate void igl::angles<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": "4d56cac6cd59aef9400bd221ba62bed45442c2fe", "size": 1822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/quadwild/libs/libigl/include/igl/angles.cpp", "max_stars_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_stars_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_stars_repo_licenses": ["Apache-2.0"], "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/quadwild/libs/libigl/include/igl/angles.cpp", "max_issues_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_issues_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_issues_repo_licenses": ["Apache-2.0"], "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/quadwild/libs/libigl/include/igl/angles.cpp", "max_forks_repo_name": "Pentacode-IAFA/Quad-Remeshing", "max_forks_repo_head_hexsha": "f8fd4c10abf1c54656b38a00b8a698b952a85fe2", "max_forks_repo_licenses": ["Apache-2.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.0384615385, "max_line_length": 363, "alphanum_fraction": 0.6459934138, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5586625714482133}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>\n\n\nusing namespace std;\n// std::ofstream debug(\"debug_gn.txt\");\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\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../left.png\";\nstring disparity_file = \"../disparity.png\";\nboost::format fmt_others(\"../%06d.png\");    // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n\n// bilinear interpolation\ninline float get(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n\n    float f = \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    return f;\n}\n\nEigen::Vector3d get_3D_point_from_depth(const Eigen::Vector2d& p, double depth, const Eigen::Matrix3d& K)\n{\n    return Eigen::Vector3d(depth * (p.x() - K(0, 2)) / K(0, 0),\n                           depth * (p.y() - K(1, 2)) / K(1, 1),\n                           depth);\n}\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    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt // points from cam1 reference frame to cam2\n)\n{\n    int nb_iters = 11;\n    int half_w_size = 1;\n    double prev_cost = 0.0;\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    for (int iter = 0; iter < nb_iters; iter++)\n    {\n        // std::cout << \"Iter: \" << iter << \" \";\n        Eigen::Matrix<double, 6, 6> H = Eigen::Matrix<double, 6, 6>::Zero();\n        Eigen::Matrix<double, 6, 1> g = Eigen::Matrix<double, 6, 1>::Zero();\n        double total_cost = 0.0;\n        int cnt_good = 0;\n        for (int k = 0; k < px_ref.size(); ++k)\n        {\n            const auto& p1 = px_ref[k];\n            Eigen::Vector3d P_ref = get_3D_point_from_depth(p1, depth_ref[k], K);\n            Eigen::Vector3d P2  = Rt * P_ref;\n            double X2 = std::pow(P2.x(), 2);\n            double Y2 = std::pow(P2.y(), 2);\n            double Z2 = std::pow(P2.z(), 2);\n\n            if (P2.z() < 0) // invalid depth\n                continue;\n\n            Eigen::Vector3d p2 = K  * P2;\n            p2 /= p2.z();\n\n            if (p2.x() < half_w_size || p2.x() > img2.cols - half_w_size \n                || p2.y() < half_w_size || p2.y() > img2.rows - half_w_size)\n                continue;\n            \n            // debug << p1.x() << \" \" << p1.y() << \"\\n\";\n            // debug << p2.x() << \" \" << p2.y() << \"\\n\";\n            \n            cnt_good++;\n            for (int xx = -half_w_size; xx <= half_w_size; ++xx)\n            {\n                for (int yy = -half_w_size; yy <= half_w_size; ++yy)\n                {\n                    auto v1 = get(img1, p1.x() + xx, p1.y() + yy);\n                    auto v2 = get(img2, p2.x() + xx, p2.y() + yy);\n                    // debug << v1 << \" \" << v2 << \"\\n\";\n\n                    double dx = 0.5 * (get(img2, p2.x() + xx + 1, p2.y() + yy) - get(img2, p2.x() + xx - 1, p2.y() + yy));\n                    double dy = 0.5 * (get(img2, p2.x() + xx, p2.y() + yy + 1) - get(img2, p2.x() + xx, p2.y() + yy - 1));\n                    Eigen::Vector2d dIdu(dx, dy);\n                    Eigen::Matrix<double, 2, 6> dudRt;\n                    dudRt << fx/P2.z(), 0.0, -fx*P2.x() / Z2,-fx * P2.x() * P2.y() / Z2, fx + fx * X2 / Z2, -fx * P2.y() / P2.z(),\n                             0.0, fy / P2.z(), -fy*P2.y()/Z2, -fy-fy * Y2 / Z2, fy * P2.x() * P2.y() / Z2, fy * P2.x() / P2.z();\n                    Eigen::Matrix<double, 6, 1> J = -(dIdu.transpose() * dudRt).transpose();\n                    // debug << p1.x() << \" \" << p2.y() << \" \" << p2.x() << \" \" << p2.y() << \"\\n\";\n                    // debug << v1 << \" \" << v2 << \"\\n\";\n                    // debug << J.transpose() << \"\\n\";\n                    double err = v1 - v2;\n                    H += J * J.transpose();\n                    g += -J.transpose() * err;\n                    total_cost += err * err;\n                }\n            }\n        }\n        // debug << \"-------------\\n\";\n        Eigen::Matrix<double, 6, 1> delta = H.ldlt().solve(g);\n        // std::cout << std::setw(4) << std::setprecision(3) << \"\\tcost: \" << total_cost << \"\\t update norm: \" << delta.norm() << \"\\n\";\n\n        if (std::isnan(delta[0]))\n        {\n            std::cout << \"Error during optimization (linear equation solving failed)\" << std::endl;\n            break;\n        }\n\n        if (iter >  0 && total_cost > prev_cost)\n        {\n            std::cout << \"Cost increased. Stop.\" << std::endl;\n            break;\n        }\n\n        Rt = Sophus::SE3d::exp(delta) * Rt;\n        prev_cost = total_cost;\n\n        if (delta.norm() < 1e-3)\n        {\n            std::cout << \"Optimization converged.\" << std::endl;\n            break;\n        }\n    }\n    std::cout << \"translation: \" << Rt.translation().transpose() << \"\\n\";\n    std::cout << \"rotation: \" << Rt.so3().unit_quaternion().toRotationMatrix() << \"\\n\";\n\n}\n\n\nvoid DirectPoseEstimationPyramidal(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt)\n{\n    int nb_levels = 4;\n    double factor = 0.5;\n\n    std::vector<cv::Mat> pyr1, pyr2;\n    std::vector<double> scales;\n    for (int i = 0; i < nb_levels; ++i)\n    {\n        if (i == 0)\n        {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n            scales.push_back(1.0);\n        }\n        else\n        {\n            cv::Mat img1_r, img2_r;\n            cv::resize(pyr1[i-1], img1_r, cv::Size(pyr1[i-1].cols * factor, pyr1[i-1].rows * factor));\n            cv::resize(pyr2[i-1], img2_r, cv::Size(pyr2[i-1].cols * factor, pyr2[i-1].rows * factor));\n            pyr1.push_back(img1_r);            \n            pyr2.push_back(img2_r);            \n            scales.push_back(scales[i-1] * factor);\n        }\n    }\n\n\n    for (int l = nb_levels-1; l >= 0; l--)\n    {\n\n        cv::Mat img1_r = pyr1[l];\n        cv::Mat img2_r = pyr2[l];\n        double scale = scales[l];\n\n        Eigen::Matrix3d K_r = K;\n        K_r(0, 0) *= scale;\n        K_r(1, 1) *= scale;\n        K_r(0, 2) *= scale;\n        K_r(1, 2) *= scale;\n        auto p_r = px_ref;\n        for (auto& p : p_r)\n        {\n            p *= scale;\n        }\n\n        DirectPoseEstimationSingleLayer(img1_r, img2_r, p_r, depth_ref, K_r, Rt);\n    }\n}\n\n\nint main(int argc, char **argv) {\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng(1994);\n    int nPoints = 2000;\n    int boarder = 40;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d Rt;\n    Eigen::Matrix3d K;\n    K << fx, 0.0, cx,\n         0.0, fy, cy,\n         0.0, 0.0, 1.0;\n\n    for (int i = 1; i < 6; i++) {  // 1~10\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n\n        // try single layer by uncomment this line\n        // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, K, Rt);\n        DirectPoseEstimationPyramidal(left_img, img, pixels_ref, depth_ref, K, Rt);\n\n\n        // plot the projected pixels here\n        cv::Mat img2_show;\n        cv::cvtColor(img, img2_show, CV_GRAY2BGR);\n        std::vector<Eigen::Vector2d> projections(pixels_ref.size());\n        for (int i = 0; i < pixels_ref.size(); ++i)\n        {\n            Eigen::Vector3d P_ref = get_3D_point_from_depth(pixels_ref[i], depth_ref[i], K);\n            Eigen::Vector3d uv = K * (Rt * P_ref);\n            projections[i] = uv.hnormalized();\n        }\n\n        for (size_t i = 0; i < pixels_ref.size(); ++i) {\n            auto p_ref = pixels_ref[i];\n            auto p_cur = projections[i];\n            if (p_cur[0] > 0 && p_cur[1] > 0 && p_cur[0] < img2_show.cols && p_cur[1] < img2_show.rows) {\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        cv::imwrite(\"img_\"+std::to_string(i) + \".png\", img2_show);\n\n    }\n    // debug.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "b334b9fb7e8fdd2405cd13c266ef42a6f44d0840", "size": 9645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch8/direct_method_gn.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": "ch8/direct_method_gn.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": "ch8/direct_method_gn.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.606271777, "max_line_length": 135, "alphanum_fraction": 0.4980819077, "num_tokens": 3029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.5586625491109287}}
{"text": "/*\n * utils.cpp\n *\n *  Created on: Dec 5, 2017\n *      Author: dumbledore\n */\n#include <iostream>\n#include \"utils.hpp\"\n#include <Eigen/QR>\n#include <assert.h>\n#include <limits>\n#include <cppad/cppad.hpp>\n#include <cppad/ipopt/solve.hpp>\nUtils::Utils() {\n  // nothing for now\n}\n\nUtils::~Utils() {\n\n  this->previousPsi = 0.0;\n  this->previousCTE = 0.0;\n}\n\nbool Utils::Compare(double a, double b)\n{\n\t//https://stackoverflow.com/a/17341\n\tstd::cout << __FILE__ << \": \" << __LINE__ << \"\\t Comparing: \" << a << \" vs \" << b << std::endl;\n    return fabs(a - b) < std::numeric_limits<double>::epsilon();\n}\n\nEigen::VectorXd Utils::polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order)\n{\n\t  assert(xvals.size() == yvals.size());\n\t  assert(order >= 1 && order <= xvals.size() - 1);\n\t  Eigen::MatrixXd A(xvals.size(), order + 1);\n\n\t  for (int i = 0; i < xvals.size(); i++) {\n\t    A(i, 0) = 1.0;\n\t  }\n\n\t  for (int j = 0; j < xvals.size(); j++) {\n\t    for (int i = 0; i < order; i++) {\n\t      A(j, i + 1) = A(j, i) * xvals(j);\n\t    }\n\t  }\n\n\t  auto Q = A.householderQr();\n\t  auto result = Q.solve(yvals);\n\t  return result;\n}\n\n\n// Evaluate a polynomial.\ndouble Utils::polyeval(Eigen::VectorXd coeffs, double x)\n{\n  double result = 0.0;\n  for (int i = 0; i < coeffs.size(); i++) {\n    result += coeffs[i] * pow(x, i);\n  }\n  return result;\n}\n\n\ndouble Utils::velocityInMetersPerSecondFromMilesPerHour(const double v)\n{\n\treturn(v*0.44704);\n}\n\n\nvoid Utils::coordinatesInVehicleReference(std::vector<double>& wayPoints_ptsx, std::vector<double>& wayPoints_ptsy, double& location_px, double& location_py, double& psi)\n{\n\t/*\n\t * psi is 0 degrees in the direction of the vehicle, and increases counter-clockwise\n\t */\n\n\tassert (wayPoints_ptsx.size() == wayPoints_ptsy.size());\n\n\t/*double check_x;\n\tdouble check_y;*/\n\tdouble newX;\n\tdouble newY;\n\n\tfor (size_t i = 0; i< wayPoints_ptsx.size(); i++)\n\t{\n\t\tnewX = ((wayPoints_ptsx[i] - location_px) * std::cos(psi)) + ((wayPoints_ptsy[i] - location_py) * std::sin(psi));\n\t\tnewY = ((location_px - wayPoints_ptsx[i]) * std::sin(psi)) - ((location_py - wayPoints_ptsy[i]) * std::cos(psi));\n\n\t\t/*newX = ((wayPoints_ptsx[i] - location_px) * std::cos(-psi)) - ((wayPoints_ptsy[i] - location_py) * std::sin(-psi));\n\t\tnewY = ((wayPoints_ptsx[i] - location_px) * std::sin(-psi)) + ((wayPoints_ptsy[i] - location_py) * std::cos(-psi));*/\n\n/*\t\tdouble x = wayPoints_ptsx[i] - location_px;\n\t\tdouble y = wayPoints_ptsy[i] - location_py;*/\n\n\t\twayPoints_ptsx[i] = newX;\n\t\twayPoints_ptsy[i] = newY;\n\n/*\n\n\t\tcheck_x = x * cos(-psi) - y * sin(-psi);\n\t\tcheck_y = x * sin(-psi) + y * cos(-psi);\n\n\t\tassert(this->Compare(check_x, wayPoints_ptsx[i]));\n\t\tassert(this->Compare(check_y, wayPoints_ptsy[i]));\n*/\n\n\t\t/*wayPoints_ptsx[i] = (wayPoints_ptsx[i] - location_px)*cos(-psi) - (wayPoints_ptsy[i] - location_py)*sin(-psi);\n\t\twayPoints_ptsy[i] = (wayPoints_ptsx[i] - location_px)*sin(-psi) + (wayPoints_ptsy[i] - location_py)*cos(-psi);*/\n\n\t}\n\n\t/* in vehicle's reference, the vehicle is always at (0,0), and heading 0 degrees*/\n\tlocation_px = 0.0;\n\tlocation_py = 0.0;\n\tpsi = 0.0;\n}\n", "meta": {"hexsha": "d939cbae967b23c7c9dc2928c96bbeef62917747", "size": 3085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils.cpp", "max_stars_repo_name": "RomanoViolet/Udacity-Model-Predictive-Controller", "max_stars_repo_head_hexsha": "eb735cf4d3c0b36245fa0da3d4e3417ec1fd41eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.cpp", "max_issues_repo_name": "RomanoViolet/Udacity-Model-Predictive-Controller", "max_issues_repo_head_hexsha": "eb735cf4d3c0b36245fa0da3d4e3417ec1fd41eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.cpp", "max_forks_repo_name": "RomanoViolet/Udacity-Model-Predictive-Controller", "max_forks_repo_head_hexsha": "eb735cf4d3c0b36245fa0da3d4e3417ec1fd41eb", "max_forks_repo_licenses": ["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.5948275862, "max_line_length": 170, "alphanum_fraction": 0.6278768233, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.5586583105678423}}
{"text": "// See LICENSE for license details.\n\n#include <string>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n#include <future>\n#include <boost/program_options.hpp>\n\n#include \"mmapped_file.hpp\"\n#include \"bin.hpp\"\n#include \"dims_create.hpp\"\n\nbool divisible(ssize_t v, int d)\n{\n    return (v / d) * d == v;\n}\n\nusing bins_type = Bins<3>;\n\nbins_type bin_all(bins_type::index_type nbins, bins_type::point_type bounding_box, double const*first, double const*last)\n{\n    if (!divisible(last - first, 3)) {\n        throw std::runtime_error(\"Range not a multiple of 3.\");\n    }\n\n    auto b = bins_type{nbins, bounding_box};\n    for (; first != last; first += 3)\n        b.insert({first[0], first[1], first[2]});\n    return b;\n}\n\nnamespace statistics {\ntemplate <typename T, typename R = double>\nR mean(const std::vector<T>& v)\n{\n    T sum = std::accumulate(v.begin(), v.end(), T{0}, std::plus<T>{});\n    return static_cast<R>(sum) / v.size();\n}\n\ntemplate <typename T, typename R = double>\nR var(const std::vector<T>& v)\n{\n    T sqsum = std::accumulate(v.begin(), v.end(), T{0}, [](T acc, T val){ return acc + val * val; });\n    R m = mean(v);\n    return static_cast<R>(sqsum) / v.size() - m * m;\n}\n}\n\n// For boost::program_options\nnamespace streamable {\ntemplate <int N>\nstruct NDoubles {\n    typename Bins<N>::point_type data;\n};\ntemplate <int N>\nstd::istream& operator>>(std::istream& is, NDoubles<N>& ti)\n{\n    char c;\n    for (int i = 0; i < N; ++i) {\n        is >> ti.data[i];\n        if (i < N - 1)\n            is.read(&c, 1);\n    }\n    return is;\n}\n}\n\nint main(int argc, char **argv)\n{\n    const int nthreads = 4;\n    using namespace std::string_literals;\n    namespace po = boost::program_options;\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"help\", \"produce help message\")\n        (\"file\", po::value<std::string>(), \"MPI-IO position file\")\n        (\"box\", po::value<streamable::NDoubles<3>>(), \"Bounding box of the simulation\")\n        (\"nproc\", po::value<int>(), \"Number of processes\")\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\") || !vm.count(\"file\") || !vm.count(\"box\") || !vm.count(\"nproc\")) {\n        std::cout << desc << std::endl;\n        return 1;\n    }\n\n    const auto fn = vm[\"file\"].as<std::string>();\n    const auto nbins = dims_create(vm[\"nproc\"].as<int>());\n    const auto bbox = vm[\"box\"].as<streamable::NDoubles<3>>().data;\n\n    std::cout << \"File : \" << fn << std::endl;\n    std::cout << \"NProc: \" << vm[\"nproc\"].as<int>() << \" = \" << nbins[0] << \" x \" << nbins[1] << \" x \" << nbins[2] << std::endl;\n    std::cout << \"Box  : \" << bbox[0] << \" \" << bbox[1] << \" \" << bbox[2] << \"\\n\" << std::endl;\n\n    auto f = MFile<double>{fn.c_str()};\n    std::cout << \"File has \" << f.size() << \" elemets.\" << std::endl;\n\n    auto data = f.data();\n    auto b = bin_all(nbins, bbox, data, data + f.size());\n\n    /* Sanity check */\n    int i = std::accumulate(b.bins.begin(), b.bins.end(), 0, std::plus<int>{});\n    std::cout << \"Binned   \" << i << \" particles.\" << std::endl;\n    if (3 * i != f.size()) {\n        throw std::runtime_error(\"Particles disappeared...\");\n    }\n    /* End */\n\n    std::cout << std::endl;\n    std::cout << \"Min: \" << *std::min_element(b.bins.begin(), b.bins.end()) << std::endl;\n    std::cout << \"Max: \" << *std::max_element(b.bins.begin(), b.bins.end()) << std::endl;\n\n    auto dmean = statistics::mean(b.bins);\n    auto dsdev = std::sqrt(statistics::var(b.bins));\n\n    std::cout << \"Mean: \" << dmean << std::endl;\n    std::cout << \"SDev: \" << dsdev << \" ( = \" << std::floor(dsdev / dmean * 1000.)/10. << \" %)\" << std::endl;\n}", "meta": {"hexsha": "7d7265eceb9a440efe9339da45d079fc43f4ba4e", "size": 3699, "ext": "cc", "lang": "C++", "max_stars_repo_path": "imba-eval.cc", "max_stars_repo_name": "hirschsn/imba-eval", "max_stars_repo_head_hexsha": "0b0e51c7403cd28c3e11333a5715be55f37c40eb", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "imba-eval.cc", "max_issues_repo_name": "hirschsn/imba-eval", "max_issues_repo_head_hexsha": "0b0e51c7403cd28c3e11333a5715be55f37c40eb", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imba-eval.cc", "max_forks_repo_name": "hirschsn/imba-eval", "max_forks_repo_head_hexsha": "0b0e51c7403cd28c3e11333a5715be55f37c40eb", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0731707317, "max_line_length": 128, "alphanum_fraction": 0.5666396323, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5586583008785783}}
{"text": "#ifndef _DISTORTION_CALIBRATION_HPP_\n#define _DISTORTION_CALIBRATION_HPP_\n\n#include <limits>\n#include <boost/math/special_functions/binomial.hpp>\n#include \"matrixOperations.hpp\"\n#include \"parseCSV_CIS_pointCloud.hpp\"\n\n\nvoid boundingBox(Eigen::MatrixXd& X, Eigen::Vector3d& minCorner, Eigen::Vector3d& maxCorner){\n    maxCorner = X.colwise().maxCoeff();\n    minCorner = X.colwise().minCoeff();\n}\n\n/// Scales every dimension of the point cloud to the max and min values\n/// Also finds the original bounding box which is subsequently scaled down.\n///\n/// @todo what are the expected dimensions of X?\n/// @todo which return row is the min and which is the max\n/// @todo this does not scale to the unit box, it scales to the size of the max and min point of the matrix.\n///\n/// @param X nx3 matrix containing points that will be scaled\n/// @param maxCorner the maximum coordinate in all dimensions of the bounding box\n/// @param ignoreBounds ignore if coordinates are not between 0 and 1. Defaults to false, which means there is an assertion checking the bounds.\nvoid ScaleToUnitBox(Eigen::MatrixXd& X, const Eigen::Vector3d& minCorner, const Eigen::Vector3d& maxCorner, bool ignoreBounds = false )\n{\n    // bounding box max and min\n    Eigen::Vector3d diff = maxCorner-minCorner;\n    /// @todo come up with better way to handle when diff is 0\n    if(diff(0)==0) diff(0) = 1;\n    if(diff(1)==0) diff(1) = 1;\n    if(diff(2)==0) diff(2) = 1;\n    \n    for (int i=0; i<X.cols(); i++){\n        for (int j=0; j<X.rows(); j++){\n            // scale the x,y,z of the point\n            auto coord = (diff(i)==0.0) ? 0.0 : (X(j,i)-minCorner(i))/diff(i);\n            if(!ignoreBounds){\n                BOOST_VERIFY(coord <= 1); // verify scaling is working\n                BOOST_VERIFY(coord >= 0);\n            }\n            X(j,i) = coord;\n        }\n    }\n}\n\ntemplate <class T>\nT boost::math::binomial_coefficient(unsigned n, unsigned k);\n\ndouble BersteinPolynomial(double v, int N, int k)\n{\n    BOOST_VERIFY(N>=k);\n    double B = boost::math::binomial_coefficient<double>(N,k)*pow(1-v,N-k)*pow(v,k);\n    return B;\n}\n\n/// Makes F matrix of Berstein Polynomials\n/// @param N the polynomial degree\n/// @see slide 42 and 43 of InterpolationReview.pdf\n/// @todo advanced implementation: template on the polynomial size\nEigen::MatrixXd FMatrixRow(const Eigen::Vector3d& v,int N = 5, bool debug = false)\n{\n    int index = 0; // position in the output matrix\n    int columns = pow(N+1,3);\n    Eigen::MatrixXd F(1,columns);\n    //std::cout << \"\\n\\nF is \" << F << std::endl;\n    for (int i=0; i<=N; i++){\n        for(int j=0; j<=N; j++){\n            for(int k=0; k<=N; k++){\n                BOOST_VERIFY(index<columns);\n                // Fijk = Bi * Bj * Bk F(0,index)\n                //std::cout << \"\\n\\nindex is \" << index << std::endl;\n                double bSum = BersteinPolynomial(v(0),N,i)*BersteinPolynomial(v(1),N,j)*BersteinPolynomial(v(2),N,k);\n                //std::cout << \"\\n\\nB is \" << B << std::endl;\n                F.block<1,1>(0,index) << bSum;\n                index++;\n                //std::cout << \"\\n\\nF is \" << F << std::endl;\n            }\n        }\n    }\n    \n    if(debug){\n        std::cout << \"\\n\\ncolumns is \" << columns << std::endl;\n        std::cout << \"\\n\\nFMatrixRow:\\n\\n\" << F << \"\\n\\n\";\n    }\n    return F;\n}\n\n\n/// Normalize the cEM matrix of points, then find the\n/// F Matrix row of each point and insert it into a larger\n/// matrix on which SVD will be solved.\n///\n/// @pre cEM must be normalized to the unit rectangle\n///\n/// @see slide 42 and 43 of InterpolationReview.pdf\n///\n///\n/// @param cEM numPoints x n (with n=3 normally) matrix containing the c expected value, aka actual points measured by EM tracker in EM coordinate system, after translation from EM coord system\n/// @param N the polynomial degree\nEigen::MatrixXd FMatrix(const Eigen::MatrixXd& normalcEM, int N = 5, bool debug = false){\n    /// @todo don't recompute pow here and in FMatrixRow\n    int columns = pow(N+1,3);\n    int rows = normalcEM.rows();\n    Eigen::MatrixXd cEMFMatrix(rows,columns);\n    \n    \n    for (int i=0; i<rows; i++){\n        Eigen::Vector3d vXYZ;\n        vXYZ = normalcEM.block<1,3>(i,0);\n        Eigen::MatrixXd row = FMatrixRow(vXYZ,N,debug);\n        if(debug) std::cout << \"\\n\\nreturned FMatrixRow:\\n\\n\" << row << \"\\n\\n\";\n        cEMFMatrix.row(i) = row;\n    }\n    if(debug) std::cout << \"\\n\\ncEMFMatrix:\\n\\n\" << cEMFMatrix << \"\\n\\n\";\n    return cEMFMatrix;\n}\n\n/// Take a vector of matrices and stack it vertically into one large matrix\n/// with the first matrix in the vector at the top and the last at the bottom.\n///\n/// @pre assumes all matrices have the same dimensions\ntemplate<typename T>\nEigen::MatrixXd stackRange(const T & vecMat){\n    auto begin = std::begin(vecMat);\n    auto end = std::end(vecMat);\n    auto distance = std::distance(begin,end);\n    if(!distance) return Eigen::MatrixXd();\n    \n    std::size_t rows = begin->rows();\n    std::size_t cols = begin->cols();\n    Eigen::MatrixXd stack(rows*distance,cols);\n    \n    std::size_t i = 0;\n    for(auto mat : vecMat ){\n        stack.block(i*rows, 0, rows, cols) = mat;\n        ++i;\n    }\n    \n    return stack;\n}\n\n/// Take a vector of Vector3d (or points) and stack the transpose of each vector (aka row vector)\n/// vertically into one large matrix with the first Vector3d in the vector at the top and the last\n/// at the bottom.\n///\n/// @note Currently only works with vectors\n///\n/// @pre assumes all matrices have the same dimensions\ntemplate<typename T>\nEigen::MatrixXd stackRangeTranspose(const T & vecMat){\n    auto begin = std::begin(vecMat);\n    auto end = std::end(vecMat);\n    auto distance = std::distance(begin,end);\n    if(!distance) return Eigen::MatrixXd();\n    \n    std::size_t rows = begin->rows();\n    std::size_t cols = begin->cols();\n    Eigen::MatrixXd stack(distance,rows);\n    \n    std::size_t i = 0;\n    for(auto mat : vecMat ){\n        stack.block(i, 0, cols, rows) = mat.transpose();\n        ++i;\n    }\n    \n    return stack;\n}\n\n/// Takes a set of points and converts it to a matrix of normalized points aka points scaled to the unit box,\n/// where they are subsequently used to calculate F values for SVD.\n///\n/// @see slide 43 of InterpolationReview.pdf\n///\n/// @param pointInAllFrames an numPoints x 3 matrix cointaining all the points to be normalized and inserted into an F Matrix for solving with SVD\n/// @param[out] minCorner the minimum coordinate of the distorted parameter, used for scaling to the unit box\n/// @param[out] maxCorner the maximum coordinate of the distorted parameter, used for scaling to the unit box\nEigen::MatrixXd normalizedFMatrix(const Eigen::MatrixXd& pointsInAllFrames, Eigen::Vector3d& minCorner, Eigen::Vector3d& maxCorner)\n{\n    Eigen::MatrixXd pointsNormalizedToUnitBox(pointsInAllFrames); // aka normal cEM\n    boundingBox(pointsNormalizedToUnitBox,minCorner,maxCorner);\n    ScaleToUnitBox(pointsNormalizedToUnitBox,minCorner,maxCorner); // normalize into unit box\n    \n    Eigen::MatrixXd FMatForSVD = FMatrix(pointsNormalizedToUnitBox);\n    \n    return FMatForSVD;\n}\n\n///\n/// Solving for SVD F*C=P, where F is the EMPointsInEMFrameOnCalObj with BernsteinPolynomials applied.\n///\n/// @return distortion Calibration Matrix C\n/// @see slide 43 of InterpolationReview.pdf\nEigen::MatrixXd distortionCalibrationMatrixC(const Eigen::MatrixXd& EMPointsInEMFrameOnCalObj, const Eigen::MatrixXd& OptPointsInEMFrameOnCalibObject, Eigen::Vector3d& minCorner, Eigen::Vector3d& maxCorner ){\n    \n    Eigen::MatrixXd FMatofEMPointsInEMFrameOnCalObj = normalizedFMatrix(EMPointsInEMFrameOnCalObj, minCorner, maxCorner);\n    std::cout << \"\\n\\nFMatrix for SVD is rows: \"<< FMatofEMPointsInEMFrameOnCalObj.rows() << \" cols: \" << FMatofEMPointsInEMFrameOnCalObj.cols() << std::endl << std::endl;\n    \n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(FMatofEMPointsInEMFrameOnCalObj, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    \n    /// this is cx cy cz on slide 43 of InterpolationReview.pdf\n    Eigen::MatrixXd pointCorrectionMatrix = svd.solve(OptPointsInEMFrameOnCalibObject);\n    std::cout << \"\\n\\npointCorrectionMatrix rows: \" << pointCorrectionMatrix.rows() << \" cols: \" << pointCorrectionMatrix.cols() << \"\\n\\n\";\n    \n    return pointCorrectionMatrix;\n}\n\n\n/// Correct distortions in one point cloud by utilizing distorted and undistorted versions of a second point cloud.\n/// Bernstein Polynomials are utilized to perform the correction.\n///\n/// @param[in] distortedToCorrect the distorted data set to correct\n/// @param[in] distortedGroundTruth the same data as groundTruth, but this data has distortion, and the variation between this and the real groundTruth will be used to correct distortedToCorrect.\n/// @param[in] groundTruth previously known exact values with no distortion to determine the coefficient matrix to correct the distortion\n/// @param[out] minCorner the minimum coordinate of the distorted parameter, used for scaling to the unit box\n/// @param[out] maxCorner the maximum coordinate of the distorted parameter, used for scaling to the unit box\n///\n/// @return Eigen::MatrixXd containing data that should match groundTruth\nEigen::MatrixXd correctDistortion(const Eigen::MatrixXd& distortedToCorrect, const Eigen::MatrixXd& distortedGroundTruth, const Eigen::MatrixXd& groundTruth, Eigen::Vector3d& minCorner, Eigen::Vector3d& maxCorner){\n    \n    Eigen::MatrixXd dcmC = distortionCalibrationMatrixC(distortedGroundTruth, groundTruth,minCorner,maxCorner);\n    \n    // scale using the same scaling factor as before, ignoring if it doesn't fit in the 0 to 1 bounds\n    // this bool only affects a BOOST_VERIFY check, not function program behavior.\n    bool ignoreUnitBoxScalingBounds = true;\n    Eigen::MatrixXd distortedToCorrectScaled = distortedToCorrect;\n    ScaleToUnitBox(distortedToCorrectScaled, minCorner, maxCorner,ignoreUnitBoxScalingBounds);\n    \n    Eigen::MatrixXd FMatrixDistorted = FMatrix(distortedToCorrectScaled);\n    //               corrected distortion matrix =        F*C\n    Eigen::MatrixXd undistorted = FMatrixDistorted*dcmC;\n    \n    return undistorted;\n}\n\n\n/// @todo move elsewhere and remove dependency on parsing data structure\ntemplate<typename T, typename U>\nEigen::MatrixXd correctDistortionOnSourceData(\n                                   const T& calreadingsFrames, // typicaly std::vector<std::vector<Eigen::MatrixXd> >\n                                   const std::vector<Eigen::MatrixXd>&         cExpected,\n                                   const U& EMPtsInEMFrameOnProbe  // typicaly std::vector<std::vector<Eigen::MatrixXd> >\n                                   ){\n    \n    static const int firstFrame = 0;\n    static const int IndexOptPtsInOptFrameOnEMTracker = 0;\n    static const int IndexOptInOptFrameOnCalObj = 1;\n    static const int IndexEMPointsInEMFrameOnCalObj = 2;\n    \n    \n    BOOST_VERIFY(calreadingsFrames.size()==cExpected.size());\n    BOOST_VERIFY(cExpected[0].cols()>0);\n    \n    // create stacked version of cExpected\n    Eigen::MatrixXd cExpectedStacked = stackRange(cExpected);\n    \n    // prep cEM for manual stacking since it is a vector of vectors\n    // Stack EM Points in EM frame on to cEM matrix\n    static const std::size_t NumEMPointsInEMFrameOnCalObj = calreadingsFrames[firstFrame][IndexEMPointsInEMFrameOnCalObj].rows();\n    static const std::size_t NumFrames = calreadingsFrames.size();\n    Eigen::MatrixXd cEM;\n    cEM.resize(NumEMPointsInEMFrameOnCalObj*NumFrames,3);\n    for (std::size_t outputRow = 0, i = 0; i < NumFrames; outputRow+=NumEMPointsInEMFrameOnCalObj, i++){\n        const Eigen::MatrixXd& markerTrackersOnCalBodyInEMFrame=calreadingsFrames[i][IndexEMPointsInEMFrameOnCalObj];\n        // @todo For some reason putting numMarkers in for 27 does not work\n        cEM.block(outputRow,0,NumEMPointsInEMFrameOnCalObj,3) = markerTrackersOnCalBodyInEMFrame;\n    }\n    \n    Eigen::Vector3d minCorner;\n    Eigen::Vector3d maxCorner;\n    \n    auto StackedEMPtsInEMFrameOnProbe = stackRange(EMPtsInEMFrameOnProbe);\n    \n    Eigen::MatrixXd undistortedEMPointsInEMFrame = correctDistortion(StackedEMPtsInEMFrameOnProbe, cEM, cExpectedStacked, minCorner, maxCorner);\n    \n    return undistortedEMPointsInEMFrame;\n}\n\n\n\n#endif // _DISTORTION_CALIBRATION_HPP_\n", "meta": {"hexsha": "ac8ca34e7a61c919575b6939f016ebbb8662a1d0", "size": 12284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/DistortionCalibration.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/DistortionCalibration.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/DistortionCalibration.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": 43.5602836879, "max_line_length": 214, "alphanum_fraction": 0.6843047867, "num_tokens": 3146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.558658293816978}}
{"text": "#pragma once\n\n#include <numeric>\n\n#include \"ArithmeticProgression.hpp\"\n#include \"Misc.hpp\"\n#include \"Partitions.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 of set_partitions of the number n.\n/// \\param IntType should be an integral type with enough space to store n and\n/// k. It can be signed or unsigned. # Example:\n///\n///\t set_partitions X(3);\n///\t\tfor (auto&& x : X)\n///\t\t\tcout << x << endl;\n///\n/// Prints out all set partitions of {0,1,2}:\n///\n/// \t[ [ 0 ] [ 1 ] [ 2 ] ]\n///\t\t[ [ 0 1 ] [ 2 ] ]\n///\t\t[ [ 0 2 ] [ 1 ] ]\n///\t\t[ [ 1 2 ] [ 0 ] ]\n///\t\t[ [ 0 1 2 ] ]\n///\n///\n///\t# Example 2:\n///\tOne can specify the number of parts:\n///\n///\t\tset_partitions X(4,2);\n///\t\tfor (auto&& x : X)\n///\t\t\tcout << x << endl;\n///\n/// Prints out all set partitions of {0,1,2,3,4} with exactly 2 parts:\n///\n///\t\t[ [ 0 1 2 ] [ 3 ] ]\n///\t\t[ [ 0 1 3 ] [ 2 ] ]\n///\t\t[ [ 0 2 3 ] [ 1 ] ]\n///\t\t[ [ 1 2 3 ] [ 0 ] ]\n///\t\t[ [ 0 1 ] [ 2 3 ] ]\n///\t\t[ [ 0 2 ] [ 1 3 ] ]\n///\t\t[ [ 0 3 ] [ 1 2 ] ]\n///\n///\n////////////////////////////////////////////////////////////\ntemplate <class IntType = int>\nclass SetPartitions\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 number_partition = std::vector<IntType>;\n    using value_type = std::vector<number_partition>;\n    using set_partition = 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\n    static bool next_set_partition(set_partition& data,\n                                   const number_partition& part)\n    {\n        auto n = std::accumulate(part.begin(), part.end(), 0L);\n        return next_set_partition(data, part, n);\n    }\n\n    static bool next_set_partition(set_partition& data,\n                                   const number_partition& part,\n                                   difference_type n)\n    {\n        difference_type anteriorpos = pop(data, n - 1);\n        difference_type curr = n - 2;\n        difference_type currpos = 0;\n\n        while (true)\n        {\n            currpos = pop(data, curr);\n\n            if (shouldBreak(data, part, currpos, anteriorpos))\n                break;\n\n            anteriorpos = currpos;\n            --curr;\n\n            if (curr == -1)\n                break;\n        }\n\n        if (curr == -1)\n            return false;\n\n        auto newpos = NextAcceptablePlaceToAdd(data, part, currpos);\n\n        data[newpos].push_back(curr);\n\n        for (difference_type i = curr + 1; i < n; ++i)\n        {\n            data[NextAcceptablePlaceToAdd(data, part)].push_back(i);\n        }\n\n        return true;\n    }\n\n    static void fill_first_set_partition(set_partition& data,\n                                         const number_partition& part)\n    {\n        IntType numpart = 0;\n        IntType etiqueta = 0;\n        data.resize(part.size());\n\n        for (auto x : part)\n        {\n            data[numpart].resize(x);\n\n            for (IntType i = 0; i < x; ++i, ++etiqueta)\n            {\n                data[numpart][i] = etiqueta;\n                // \t\t\t\t\tcout << etiqueta << endl;\n            }\n\n            ++numpart;\n        }\n    }\n\n    // **************** End static functions\n\npublic:\n    explicit SetPartitions(IntType n)\n        : n_(n), min_num_parts_(1), max_num_parts_(n), size_(calc_size(n, 1, n))\n    {}\n\n    SetPartitions(IntType n, IntType numparts)\n        : n_(n)\n        , min_num_parts_(numparts)\n        , max_num_parts_(numparts)\n        , size_(calc_size(n, numparts, numparts))\n    {}\n\n    SetPartitions(IntType n, IntType minnumparts, IntType maxnumparts)\n        : n_(n)\n        , min_num_parts_(minnumparts)\n        , max_num_parts_(maxnumparts)\n        , size_(calc_size(n, minnumparts, maxnumparts))\n    {}\n\n    size_type size() const { return size_; }\n\n    IntType get_n() const { return n_; }\n\n    iterator begin() const { return iterator(n_, max_num_parts_); }\n\n    const iterator end() const\n    {\n        return iterator::make_invalid_with_id(size());\n    }\n\n    class iterator\n        : public boost::iterator_facade<iterator, const set_partition&, boost::forward_traversal_tag>\n    {\n    public:\n        iterator() : ID_(0), data_(), n_(0) {}\n\n        explicit iterator(IntType n, IntType numparts)\n            : ID_(0), data_(n), n_(n), num_partition()\n        {\n            Partitions<IntType>::first_with_given_number_of_parts(num_partition,\n                                                                  n,\n                                                                  numparts);\n            fill_first_set_partition(data_, num_partition);\n        }\n\n        inline size_type ID() const { return ID_; }\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            if (!next_set_partition(data_, num_partition))\n            {\n                Partitions<IntType>::next_partition(num_partition, n_);\n                fill_first_set_partition(data_, num_partition);\n            }\n        }\n\n        const set_partition& 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        set_partition data_{};\n        IntType n_{0};\n        number_partition num_partition{};\n\n        friend class boost::iterator_core_access;\n    }; // end class iterator\n\nprivate:\n    IntType n_;\n    IntType min_num_parts_;\n    IntType max_num_parts_;\n    size_type size_;\n\nprivate:\n    // Private static functions\n    static size_type calc_size(IntType n, IntType minnumparts, IntType maxnumparts)\n    {\n        size_type toReturn = 0;\n\n        for (IntType k = minnumparts; k <= maxnumparts; ++k)\n            toReturn += stirling_partition_number(n, k);\n\n        return toReturn;\n    }\n\n    static difference_type pop(set_partition& data, IntType num)\n    {\n        const difference_type n = data.size();\n        for (difference_type i = 0; i < n; ++i)\n        {\n            if (!data[i].empty() && data[i].back() == num)\n            {\n                data[i].pop_back();\n                return i;\n            }\n        }\n\n        // \t\t\tcout << \"not found, returning -1\" << endl;\n        return -1;\n    }\n\n    static difference_type NextAcceptablePlaceToAdd(const set_partition& data,\n                                                    const number_partition& part,\n                                                    difference_type oldpos = -1)\n    {\n        // \t\t\tcout << \"Finding if I can put the next number where \" <<\n        // endl;\n        const difference_type n = data.size();\n        for (difference_type i = oldpos + 1; i < n; ++i)\n        {\n            const difference_type dataisize = data[i].size();\n            if (dataisize == part[i])\n                continue;\n\n            if ((i > 0) && (part[i - 1] == part[i]) && data[i - 1].empty())\n                continue;\n\n            return i;\n        }\n\n        return -1;\n    }\n    static bool shouldBreak(const set_partition& data,\n                            const number_partition& part,\n                            difference_type currpos,\n                            difference_type anteriorpos)\n    {\n        if (currpos == -1)\n            return true;\n\n        if (currpos < anteriorpos)\n        {\n            if (part[currpos] != part[anteriorpos])\n                return true;\n\n            if (!data[currpos].empty())\n                return true;\n        }\n\n        return false;\n    }\n\n}; // end class SetPartitions\n\nusing set_partitions = SetPartitions<int>;\n\n} // namespace discreture\n", "meta": {"hexsha": "192be07b3362e1aba5f24eabec3f03d8b5d178f1", "size": 8050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/SetPartitions.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/SetPartitions.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/SetPartitions.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": 27.1959459459, "max_line_length": 101, "alphanum_fraction": 0.5147826087, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.558614315130756}}
{"text": "/**\n *\n * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)\n *\n * Authors: Matthias Walter\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 <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bipartite.hpp>\n\nusing namespace boost;\n\n/// Example to test for bipartiteness and print the certificates.\n\ntemplate <typename Graph>\nvoid print_bipartite (const Graph& g)\n{\n  typedef graph_traits <Graph> traits;\n  typename traits::vertex_iterator vertex_iter, vertex_end;\n\n  /// Most simple interface just tests for bipartiteness. \n\n  bool bipartite = is_bipartite (g);\n\n  if (bipartite)\n  {\n    typedef std::vector <default_color_type> partition_t;\n    typedef typename property_map <Graph, vertex_index_t>::type index_map_t;\n    typedef iterator_property_map <partition_t::iterator, index_map_t> partition_map_t;\n\n    partition_t partition (num_vertices (g));\n    partition_map_t partition_map (partition.begin (), get (vertex_index, g));\n\n    /// A second interface yields a bipartition in a color map, if the graph is bipartite.\n\n    is_bipartite (g, get (vertex_index, g), partition_map);\n\n    for (boost::tie (vertex_iter, vertex_end) = vertices (g); vertex_iter != vertex_end; ++vertex_iter)\n    {\n      std::cout << \"Vertex \" << *vertex_iter << \" has color \" << (get (partition_map, *vertex_iter) == color_traits <\n          default_color_type>::white () ? \"white\" : \"black\") << std::endl;\n    }\n  }\n  else\n  {\n    typedef std::vector <typename traits::vertex_descriptor> vertex_vector_t;\n    vertex_vector_t odd_cycle;\n\n    /// A third interface yields an odd-cycle if the graph is not bipartite.\n\n    find_odd_cycle (g, get (vertex_index, g), std::back_inserter (odd_cycle));\n\n    std::cout << \"Odd cycle consists of the vertices:\";\n    for (size_t i = 0; i < odd_cycle.size (); ++i)\n    {\n      std::cout << \" \" << odd_cycle[i];\n    }\n    std::cout << std::endl;\n  }\n}\n\nint main (int argc, char **argv)\n{\n  typedef adjacency_list <vecS, vecS, undirectedS> vector_graph_t;\n  typedef std::pair <int, int> E;\n\n  /**\n   * Create the graph drawn below.\n   *\n   *       0 - 1 - 2\n   *       |       |\n   *   3 - 4 - 5 - 6\n   *  /      \\   /\n   *  |        7\n   *  |        |\n   *  8 - 9 - 10\n   **/\n\n  E bipartite_edges[] = { E (0, 1), E (0, 4), E (1, 2), E (2, 6), E (3, 4), E (3, 8), E (4, 5), E (4, 7), E (5, 6), E (\n      6, 7), E (7, 10), E (8, 9), E (9, 10) };\n  vector_graph_t bipartite_vector_graph (&bipartite_edges[0],\n      &bipartite_edges[0] + sizeof(bipartite_edges) / sizeof(E), 11);\n\n  /**\n   * Create the graph drawn below.\n   * \n   *       2 - 1 - 0\n   *       |       |\n   *   3 - 6 - 5 - 4\n   *  /      \\   /\n   *  |        7\n   *  |       /\n   *  8 ---- 9\n   *  \n   **/\n\n  E non_bipartite_edges[] = { E (0, 1), E (0, 4), E (1, 2), E (2, 6), E (3, 6), E (3, 8), E (4, 5), E (4, 7), E (5, 6),\n      E (6, 7), E (7, 9), E (8, 9) };\n  vector_graph_t non_bipartite_vector_graph (&non_bipartite_edges[0], &non_bipartite_edges[0]\n      + sizeof(non_bipartite_edges) / sizeof(E), 10);\n\n  /// Call test routine for a bipartite and a non-bipartite graph.\n\n  print_bipartite (bipartite_vector_graph);\n\n  print_bipartite (non_bipartite_vector_graph);\n\n  return 0;\n}\n", "meta": {"hexsha": "c8e62ad26ab1df681ea0ed9974fb517a95ab2609", "size": 3335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/example/bipartite_example.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/example/bipartite_example.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/example/bipartite_example.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.75, "max_line_length": 119, "alphanum_fraction": 0.6092953523, "num_tokens": 1080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.5586143144436526}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2015 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_CARTESIAN_SIDE_OF_INTERSECTION_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_OF_INTERSECTION_HPP\r\n\r\n\r\n#include <boost/geometry/arithmetic/determinant.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/coordinate_type.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n// Calculates the side of the intersection-point (if any) of\r\n// of segment a//b w.r.t. segment c\r\n// This is calculated without (re)calculating the IP itself again and fully\r\n// based on integer mathematics; there are no divisions\r\n// It can be used for either integer (rescaled) points, and also for FP\r\nclass side_of_intersection\r\n{\r\npublic :\r\n\r\n    // Calculates the side of the intersection-point (if any) of\r\n    // of segment a//b w.r.t. segment c\r\n    // This is calculated without (re)calculating the IP itself again and fully\r\n    // based on integer mathematics\r\n    template <typename T, typename Segment>\r\n    static inline T side_value(Segment const& a, Segment const& b,\r\n                Segment const& c)\r\n    {\r\n        // The first point of the three segments is reused several times\r\n        T const ax = get<0, 0>(a);\r\n        T const ay = get<0, 1>(a);\r\n        T const bx = get<0, 0>(b);\r\n        T const by = get<0, 1>(b);\r\n        T const cx = get<0, 0>(c);\r\n        T const cy = get<0, 1>(c);\r\n\r\n        T const dx_a = get<1, 0>(a) - ax;\r\n        T const dy_a = get<1, 1>(a) - ay;\r\n\r\n        T const dx_b = get<1, 0>(b) - bx;\r\n        T const dy_b = get<1, 1>(b) - by;\r\n\r\n        T const dx_c = get<1, 0>(c) - cx;\r\n        T const dy_c = get<1, 1>(c) - cy;\r\n\r\n        // Cramer's rule: d (see cart_intersect.hpp)\r\n        T const d = geometry::detail::determinant<T>\r\n                    (\r\n                        dx_a, dy_a,\r\n                        dx_b, dy_b\r\n                    );\r\n\r\n        T const zero = T();\r\n        if (d == zero)\r\n        {\r\n            // There is no IP of a//b, they are collinear or parallel\r\n            // We don't have to divide but we can already conclude the side-value\r\n            // is meaningless and the resulting determinant will be 0\r\n            return zero;\r\n        }\r\n\r\n        // Cramer's rule: da (see cart_intersect.hpp)\r\n        T const da = geometry::detail::determinant<T>\r\n                    (\r\n                        dx_b,    dy_b,\r\n                        ax - bx, ay - by\r\n                    );\r\n\r\n        // IP is at (ax + (da/d) * dx_a, ay + (da/d) * dy_a)\r\n        // Side of IP is w.r.t. c is: determinant(dx_c, dy_c, ipx-cx, ipy-cy)\r\n        // We replace ipx by expression above and multiply each term by d\r\n        T const result = geometry::detail::determinant<T>\r\n                    (\r\n                        dx_c * d,                   dy_c * d,\r\n                        d * (ax - cx) + dx_a * da,  d * (ay - cy) + dy_a * da\r\n                    );\r\n\r\n        // Note: result / (d * d)\r\n        // is identical to the side_value of side_by_triangle\r\n        // Therefore, the sign is always the same as that result, and the\r\n        // resulting side (left,right,collinear) is the same\r\n\r\n        return result;\r\n\r\n    }\r\n\r\n    template <typename Segment>\r\n    static inline int apply(Segment const& a, Segment const& b, Segment const& c)\r\n    {\r\n        typedef typename geometry::coordinate_type<Segment>::type coordinate_type;\r\n        coordinate_type const s = side_value<coordinate_type>(a, b, c);\r\n        coordinate_type const zero = coordinate_type();\r\n        return math::equals(s, zero) ? 0\r\n            : s > zero ? 1\r\n            : -1;\r\n    }\r\n\r\n};\r\n\r\n\r\n}} // namespace strategy::side\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_OF_INTERSECTION_HPP\r\n", "meta": {"hexsha": "89b32a0ca8bc691fb19d7b32e3da2301d1c49906", "size": 4149, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/cartesian/side_of_intersection.hpp", "max_stars_repo_name": "Abce/boost", "max_stars_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_stars_repo_licenses": ["BSL-1.0"], "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/geometry/strategies/cartesian/side_of_intersection.hpp", "max_issues_repo_name": "Abce/boost", "max_issues_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_issues_repo_licenses": ["BSL-1.0"], "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/strategies/cartesian/side_of_intersection.hpp", "max_forks_repo_name": "Abce/boost", "max_forks_repo_head_hexsha": "2d7491a27211aa5defab113f8e2d657c3d85ca93", "max_forks_repo_licenses": ["BSL-1.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.575, "max_line_length": 83, "alphanum_fraction": 0.571945047, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.5585662106084756}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Delaunay_triangulation_on_sphere_traits_2.h>\n#include <CGAL/Delaunay_triangulation_on_sphere_2.h>\n#include <CGAL/Projection_on_sphere_traits_3.h>\n\n#include <CGAL/algorithm.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/squared_distance_3.h>\n#include <CGAL/Timer.h>\n\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <cmath>\n#include <fstream>\n#include <vector>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel    K;\ntypedef CGAL::Surface_mesh<K>                                  Surface_mesh;\n\ntypedef K::Segment_3                                           Segment_3;\ntypedef CGAL::Delaunay_triangulation_3<K>                      Delaunay;\n\ntypedef CGAL::Delaunay_triangulation_on_sphere_traits_2<K>     Gt;\ntypedef CGAL::Projection_on_sphere_traits_3<K>                 Gt2;\ntypedef CGAL::Delaunay_triangulation_on_sphere_2<Gt>           DTOS;\ntypedef CGAL::Delaunay_triangulation_on_sphere_2<Gt2>          DTOS2;\ntypedef K::Point_3                                             Point;\n\ntypedef CGAL::Delaunay_triangulation_3<K, CGAL::Fast_location> Delaunay_fast;\ntypedef CGAL::Creator_uniform_3<double, Point>                 Creator;\n\nint main(int, char**)\n{\n  CGAL::Timer time;\n\n  const std::size_t nu_of_pts = 1e7;\n  const double radius = 5184.152;\n\n  CGAL::Random random;\n  std::cout << \"Seed is \" << random.get_seed() << std::endl;\n\n  CGAL::Random_points_on_sphere_3<Point, Creator> on_sphere(radius, random);\n\n  std::vector<Point> points;\n  points.reserve(nu_of_pts);\n\n  for(std::size_t count=0; count<nu_of_pts; ++count)\n    points.push_back(*on_sphere++);\n  std::cout << points.size() << \" points\" << std::endl;\n\n  // Delaunay_traits\n  DTOS dtos;\n  dtos.set_radius(radius);\n\n  std::cout << \" ***STARTING***\" << std::endl;\n  time.start();\n  dtos.insert(points.begin(), points.end());\n  time.stop();\n  assert(dtos.number_of_vertices() == nu_of_pts);\n  std::cout << \"Triangulation sphere: \"\n            << dtos.number_of_vertices() << \" vertices in \" << time.time() << \" sec\" << std::endl;\n\n  //Triangulation with points on the sphere (projection_traits)\n  Gt2 traits(K::Point_3(0, 0, 0), radius);\n  DTOS2 dtos2(traits);\n  Gt2::Construct_point_on_sphere_2 cst = traits.construct_point_on_sphere_2_object();\n\n  time.reset();\n  time.start();\n  dtos2.insert(boost::make_transform_iterator(points.begin(), cst),\n               boost::make_transform_iterator(points.end(), cst));\n  time.stop();\n  std::cout << \"Triangulation w/ sphere projection traits: \"\n            << dtos2.number_of_vertices() << \" vertices in \" << time.time() << \" sec\" << std::endl;\n\n//  Surface_mesh sm;\n\n//  time.reset();\n//  time.start();\n//  CGAL::convex_hull_3(points.begin(), points.end(), sm);\n//  time.stop();\n//  std::cout << \"Convex hull 3D: \" << time.time() << \" \" << std::endl;\n\n  time.reset();\n  time.start();\n  Delaunay T;\n  T.insert(Point(0, 0, 0));\n  T.insert(points.begin(), points.end());\n  time.stop();\n  std::cout << \"Delaunay 3D with origin: \"\n            << T.number_of_vertices() << \" vertices in \" << time.time() << \" sec\" << std::endl;\n\n  time.reset();\n  time.start();\n  Delaunay_fast T_fast_on2;\n  T_fast_on2.insert(Point(0, 0, 0));\n  T_fast_on2.insert(points.begin(), points.end());\n  time.stop();\n  std::cout << \"Delaunay 3D with origin, fast location: \" << time.time() << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0385b41db3f8a74241525f981b30b00092be1c3e", "size": 3565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Triangulation_on_sphere_2/benchmark/Triangulation_on_sphere_2/bench_dtos2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Triangulation_on_sphere_2/benchmark/Triangulation_on_sphere_2/bench_dtos2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Triangulation_on_sphere_2/benchmark/Triangulation_on_sphere_2/bench_dtos2.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.0092592593, "max_line_length": 99, "alphanum_fraction": 0.6617110799, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.5585662002592469}}
{"text": "#include \"raycast.h\"\n#include <iostream>\n#include <cmath>\n#include <Eigen/Eigen>\n\nint signum(int x) {\n    return x == 0 ? 0 : x < 0 ? -1 : 1;\n}\n\ndouble mod(double value, double modulus) {\n    return fmod(fmod(value, modulus) + modulus, modulus);\n}\n\ndouble intbound(double s, double ds) {\n    // Find the smallest positive t such that s+t*ds is an integer.\n    if (ds < 0) {\n        return intbound(-s, -ds);\n    } else {\n        s = mod(s, 1);\n        // problem is now s+t*ds = 1\n        return (1 - s) / ds;\n    }\n}\n\nbool RayIntersectsAABB(const Eigen::Vector3d &start, const Eigen::Vector3d &end, const Eigen::Vector3d &lb,\n                       const Eigen::Vector3d &rt) {\n    Eigen::Vector3d dir = (end - start).normalized();\n    Eigen::Vector3d dirfrac(1.0f / dir.x(), 1.0f / dir.y(), 1.0f / dir.z());\n\n    // r.dirs_ is unit dirs_ vector of ray\n    // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner\n    // start is origin of ray\n    double t1 = (lb.x() - start.x()) * dirfrac.x();\n    double t2 = (rt.x() - start.x()) * dirfrac.x();\n    double t3 = (lb.y() - start.y()) * dirfrac.y();\n    double t4 = (rt.y() - start.y()) * dirfrac.y();\n    double t5 = (lb.z() - start.z()) * dirfrac.z();\n    double t6 = (rt.z() - start.z()) * dirfrac.z();\n\n    double tmin = fmax(fmax(fmin(t1, t2), fmin(t3, t4)), fmin(t5, t6));\n    double tmax = fmin(fmin(fmax(t1, t2), fmax(t3, t4)), fmax(t5, t6));\n\n    // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us\n    if (tmax < 0) {\n        return false;\n    }\n\n    // if tmin > tmax, ray doesn't intersect AABB\n    if (tmin > tmax) {\n        return false;\n    }\n\n    return true;\n}\n\nvoid Raycast(const Eigen::Vector3d &start, const Eigen::Vector3d &end,\n             const Eigen::Vector3d &min, const Eigen::Vector3d &max,\n             std::vector<Eigen::Vector3d> *output) {\n//    std::cout << start << ' ' << end << std::endl;\n    // From \"A Fast Voxel Traversal Algorithm for Ray Tracing\"\n    // by John Amanatides and Andrew Woo, 1987\n    // <http://www.cse.yorku.ca/~amana/research/grid.pdf>\n    // <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.3443>\n    // Extensions to the described algorithm:\n    //   • Imposed a distance_ limit.\n    //   • The face passed through to reach the current cube is provided to\n    //     the callback.\n\n    // The foundation of this algorithm is a parameterized representation of\n    // the provided ray,\n    //                    origin + t * dirs_,\n    // except that t is not actually stored; rather, at any given point_ in the\n    // traversal, we keep track of the *greater* t values which we would have\n    // if we took a step sufficient to cross a cube boundary along that axis\n    // (i.e. change the integer part of the coordinate) in the variables\n    // tMaxX, tMaxY, and tMaxZ.\n\n    // Cube containing origin point_.\n    int x = (int) std::floor(start.x());\n    int y = (int) std::floor(start.y());\n    int z = (int) std::floor(start.z());\n    int endX = (int) std::floor(end.x());\n    int endY = (int) std::floor(end.y());\n    int endZ = (int) std::floor(end.z());\n    Eigen::Vector3d direction = (end - start);\n    double maxDist = direction.squaredNorm();\n\n    // Break out dirs_ vector.\n    double dx = endX - x;\n    double dy = endY - y;\n    double dz = endZ - z;\n\n    // Direction to increment x,y,z when stepping.\n    int stepX = (int) signum((int) dx);\n    int stepY = (int) signum((int) dy);\n    int stepZ = (int) signum((int) dz);\n\n    // See description above. The initial values depend on the fractional\n    // part of the origin.\n    double tMaxX = intbound(start.x(), dx);\n    double tMaxY = intbound(start.y(), dy);\n    double tMaxZ = intbound(start.z(), dz);\n\n    // The change in t when taking a step (always positive).\n    double tDeltaX = ((double) stepX) / dx;\n    double tDeltaY = ((double) stepY) / dy;\n    double tDeltaZ = ((double) stepZ) / dz;\n\n    output->clear();\n\n    // Avoids an infinite loop.\n    if (stepX == 0 && stepY == 0 && stepZ == 0)\n        return;\n\n    double dist = 0;\n    while (true) {\n\n        if (x >= min.x() && x < max.x() &&\n            y >= min.y() && y < max.y() &&\n            z >= min.z() && z < max.z()) {\n            output->push_back(Eigen::Vector3d(x, y, z));\n\n            dist = (Eigen::Vector3d(x, y, z) - start).squaredNorm();\n\n            if (dist > maxDist) return;\n\n            if (output->size() > 1500) {\n                std::cerr << \"Error, too many racyast voxels.\" << std::endl;\n                throw std::out_of_range(\"Too many RaycasMultithread voxels\");\n            }\n        }\n\n        if (x == endX && y == endY && z == endZ) break;\n\n        // tMaxX stores the t-value at which we cross a cube boundary along the\n        // X axis, and similarly for Y and Z. Therefore, choosing the least tMax\n        // chooses the closest cube boundary. Only the first case of the four\n        // has been commented in detail.\n        if (tMaxX < tMaxY) {\n            if (tMaxX < tMaxZ) {\n                // Update which cube we are now in.\n                x += stepX;\n                // Adjust tMaxX to the next X-oriented boundary crossing.\n                tMaxX += tDeltaX;\n            } else {\n                z += stepZ;\n                tMaxZ += tDeltaZ;\n            }\n        } else {\n            if (tMaxY < tMaxZ) {\n                y += stepY;\n                tMaxY += tDeltaY;\n            } else {\n                z += stepZ;\n                tMaxZ += tDeltaZ;\n            }\n        }\n    }\n}", "meta": {"hexsha": "a1c4be9d6a2664b1d6893797a5a199d86d80c396", "size": 5528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/raycast.cpp", "max_stars_repo_name": "LiShaojun1994/FIESTA", "max_stars_repo_head_hexsha": "6ad0bd2b5ae74afc50cb638257db6fa975e9de75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T02:47:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:41:21.000Z", "max_issues_repo_path": "src/raycast.cpp", "max_issues_repo_name": "Calm-wy/FIESTA", "max_issues_repo_head_hexsha": "d01ce1b4602340a417a68ec7bb5f6b5a6790207e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2019-07-27T14:53:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T15:18:08.000Z", "max_forks_repo_path": "src/raycast.cpp", "max_forks_repo_name": "Calm-wy/FIESTA", "max_forks_repo_head_hexsha": "d01ce1b4602340a417a68ec7bb5f6b5a6790207e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 96.0, "max_forks_repo_forks_event_min_datetime": "2019-08-08T03:42:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:31:49.000Z", "avg_line_length": 34.7672955975, "max_line_length": 107, "alphanum_fraction": 0.5524602026, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5584133429857462}}
{"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_TRIGONOMETRIC_FUNCTIONS_SCALAR_SINCPI_HPP_INCLUDED\n#define NT2_TOOLBOX_TRIGONOMETRIC_FUNCTIONS_SCALAR_SINCPI_HPP_INCLUDED\n\n#include <nt2/toolbox/trigonometric/functions/sincpi.hpp>\n#include <nt2/include/functions/scalar/sinpi.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/is_inf.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/include/constants/invpi.hpp>\n#include <boost/simd/sdk/config.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sincpi_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::sincpi(result_type(a0));\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is floating_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::sincpi_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if(nt2::is_inf(a0)) return nt2::Zero<A0>();\n      #endif\n      return (nt2::abs(a0) < nt2::Eps<A0>()) ? nt2::One<A0>() : nt2::Invpi<A0>()*nt2::sinpi(a0)/a0;\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "4b06e267931ccef2362f48a69d25c439f8a0a7af", "size": 2152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/sincpi.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/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/sincpi.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/trigonometric/include/nt2/toolbox/trigonometric/functions/scalar/sincpi.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": 33.1076923077, "max_line_length": 99, "alphanum_fraction": 0.5334572491, "num_tokens": 508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.5584085017045147}}
{"text": "#ifndef SPATHPP\n#define SPATHPP\n\n// -------------------------------------------------------\n//   \n//   Spatially-regularized Levenberg Marquardt algorithm\n//   Coded by J. de la Cruz Rodriguez (ISP-SU, 2020)\n//\n//   Reference: de la Cruz Rodriguez (2019):\n//   https://ui.adsabs.harvard.edu/abs/2019A%26A...631A.153D/abstract\n//\n//   ------------------------------------------------------- \n\n#include <omp.h>\n#include <vector>\n#include <iostream>\n#include <string>\n#include <cstdio>\n#include <cstring>\n#include <chrono>\n\n#include \"line.hpp\"\n#include \"Milne.hpp\"\n#include \"lm.hpp\"\n#include \"spatially_regularized_tools.hpp\"\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\nnamespace spa{\n\n  // ************************************************************** //\n\n  template<typename T, typename iType = long>\n  class lms{\n  protected:\n    iType npar, ny, nx;\n    \n    Eigen::SparseMatrix<T, Eigen::RowMajor, iType> A;\n    \n    Eigen::Matrix<T,Eigen::Dynamic, 1> B;\n    \n    Eigen::SparseMatrix<T,Eigen::RowMajor, iType> L;\n    Eigen::SparseMatrix<T,Eigen::RowMajor, iType> LL;\n    \n  public:\n    lms(int const inpar, int const iny, int const inx):\n      npar(inpar), ny(iny), nx(inx),  A(), B(){};\n        \n    // ------------------------------------------------------------ //\n    \n    static inline T checkLambda(T val, T const &mi, T const& ma)\n    {return std::max<T>(std::min<T>(ma, val), mi);}\n\n    // ------------------------------------------------------------ //\n\n    inline static T get_one_JJ(int const ndat, const T* const __restrict__ Jy, const T* const __restrict__ Jx)\n    {\n      return static_cast<T>(ksumMult<T,double>(ndat, Jy, Jx));\n    }\n    \n    // ------------------------------------------------------------ //\n\n    void construct_system(int const npar, container<T> const& cont, T* const __restrict__ m, \n\t\t\t  T* const __restrict__ r,  Eigen::Matrix<T,Eigen::Dynamic,1> const& Reg_RHS)\n    {\n\n      iType const npix = cont.ny*cont.nx;\n      iType const ndat = cont.nDat;\n      iType const nthreads = cont.getNthreads();\n      iType const nx = cont.nx;\n      iType const ny = cont.ny;\n      iType const Jstride = npar*ndat;\n\n      \n      // --- Build Sparse system --- //\n\n      B.resize(npix*npar); B.setZero();\n      A.resize(0,0); A.data().squeeze(); A.resize(npix*npar, npix*npar);\n      A.reserve(Eigen::VectorXi::Constant(npix*npar,npar));\n\n      \n      T* __restrict__ iJ = NULL;\n      iType ipix=0, tid=0, pp=0, ii=0, jj=0;\n      T iSum = 0;\n\n      // --- parallel block --- //\n      \n#pragma omp parallel default(shared) firstprivate(ipix, tid, iSum, pp, ii, jj, iJ) num_threads(nthreads)      \n      {\n\t\n\ttid = omp_get_thread_num();\n\tiJ = new T [npar*ndat](); // Allocate thread buffer for derivatives\n\t\n#pragma omp for\n\tfor(ipix=0; ipix<npix; ++ipix){\n\n\t  // --- synthesize_one pixel with derivatives --- //\n\t  \n\t  cont.synthesize_der_one(npar, &m[ipix*npar], &r[ipix*ndat], iJ, tid, ipix);\n\n\n\t  // --- Fill in subspace in sparse Hessian matrix --- //\n\n\t  for(jj=0; jj<npar; ++jj){\n\n\t    // --- RHS of the equation --- //\n\t    \n\t    B[ipix*npar+jj] = ksumMult<T,double>(ndat, &iJ[jj*ndat], &r[ipix*ndat]) - Reg_RHS[ipix*npar+jj];\n\t    \n\t    for(ii=0; ii<=jj;++ii){\n\n\t      // --- Matrix subspaces --- //\n\t      \n\t      iSum = get_one_JJ(ndat, &iJ[jj*ndat], &iJ[ii*ndat]);\n\t      A.insert(ipix*npar + jj, ipix*npar + ii) = iSum;\n\t      \n\t      if(ii != jj) // The matrix is symmetric but avoid inserting the diagonal term twice\n\t       \tA.insert(ipix*npar + ii, ipix*npar + jj) = iSum;\n\t      \n\t    } // ii\n\t  } // jj\n\t  \n\t  \n\t} // ipix\n\t\n\tdelete [] iJ;\n\tiJ = NULL;\n\t\n      }// parallel\n      \n    }\n\n\n    // ------------------------------------------------------------ //\n\n    Chi2<T> getCorrection(container<T> const& cont, T* const __restrict__ m,\n\t\t\t  T* const __restrict__ syn, T* const __restrict__ r, T iLam, int const method)const \n    {\n\n\n      iType const npix = cont.ny*cont.nx;\n      iType const ndat = cont.nDat;\n\n      Eigen::SparseMatrix<T,Eigen::RowMajor,iType> Atot = A+LL;\n\n      \n      // --- damp diagonal and get correction --- //\n      \n      iType const nDiag = iType(npar)*iType(npix);\n      for(iType kk =0; kk<nDiag; ++kk)\n\tAtot.coeffRef(kk,kk) *= (1+iLam);\n\n      Eigen::Matrix<T,Eigen::Dynamic,1> dx;\n      \n      // --- Solve for corrections --- //\n      \n      if(method == 0){\n\tEigen::ConjugateGradient<Eigen::SparseMatrix<T,Eigen::RowMajor,iType>, Eigen::Lower| Eigen::Upper> solver(Atot);\n\tdx = solver.solve(B);\n      }else if(method == 1){\n\tEigen::BiCGSTAB<Eigen::SparseMatrix<T,Eigen::RowMajor,iType>> solver(Atot);\n\tdx = solver.solve(B);\n      }else if(method == 2){\n\tEigen::SparseLU<Eigen::SparseMatrix<T,Eigen::RowMajor,iType>> solver(Atot);\n\tdx = solver.solve(B);\n      }\n\n      \n      // --- Check corrections --- //\n      \n      for(iType pp=0; pp<npar; ++pp)\n\tfor(iType ipix = 0; ipix<npix; ++ipix){\n\t  m[ipix*npar+pp] += dx[ipix*npar+pp];\n\t  cont.Pinfo[pp].CheckNormalized(m[ipix*npar+pp]);\n\t  \n\t}\n\n      // --- compute chi2 --- //\n\n      \n      std::vector<T> rnew(ndat*npix,0);\n      cont.fx(npar, m, syn, &rnew[0]);\n      Eigen::Matrix<T, Eigen::Dynamic, 1> Gam = cont.getGamma(npar, m);\n      \n      Chi2<T> chi2(ksum2<T,double>(npix*ndat, &rnew[0]), ksum2<T,double>(Gam.size(), &Gam[0]));\n      \n      return chi2;\n    }\n    \n    // ------------------------------------------------------------ //\n\n    Chi2<T> getStep(container<T> const& cont, T* const __restrict__ m, \n\t\t    T* const __restrict__ syn, T* const __restrict__ r, T& iLam, bool bracket,\n\t\t    T const minLam, T const maxLam, T const Lam_step,  Eigen::Matrix<T,Eigen::Dynamic,1> const& Reg_RHS,\n\t\t    Chi2<T> const& bestChi2, int const method)\n    {\n      \n      // --- if no bracketing just compute one correction --- //\n      \n      if(!bracket){\n\treturn getCorrection(cont, m, syn, r, iLam, method);\n      }else{\n\n\t// --- Bracketing optimal lambda value --- //\n\t\n\tint const npix = cont.nx*cont.ny;\n\tstd::vector<Chi2<T>> iChi2;\n\tstd::vector<T> Lambdas;\n\n\tint idx = 0;\n\n\tEigen::Map<Eigen::Matrix<T,Eigen::Dynamic,1>> input_model(m, npix*npar);\n\tEigen::Matrix<T,Eigen::Dynamic,1> Model = input_model;\n\n\tChi2<T> chi2 = getCorrection(cont, &Model[0], syn, r, iLam, method);\n\tif(chi2.value() > bestChi2.value()) return chi2;\n\t\n\tEigen::Matrix<T,Eigen::Dynamic,1> bestModel = Model;\n\n\tiChi2.emplace_back(chi2);\n\tLambdas.emplace_back(iLam);\n\n\t// --- First try to bracket by decreasing lambda --- //\n\tint iter = 0;\n\twhile((iter < 1) || ((iter < 4) && (iChi2[iter].value()<iChi2[iter-1].value()) && (Lambdas[iter] > minLam))){\n\t  iLam = checkLambda(iLam / Lam_step, minLam, maxLam);\n\t  Model = input_model;\n\n\t  Lambdas.emplace_back(iLam);\n\t  iChi2.emplace_back(getCorrection(cont, &Model[0], syn, r, iLam, method));\n\t  if(iChi2[iter+1].value() < iChi2[idx].value()){\n\t    idx = iter+1;\n\t    bestModel = Model;\n\t  }\n\t  \n\t  ++iter;\n\t  \n\t}// while\n\t\n\t// --- if the best Chi2 is not in the first element we consider it bracketed --- //\n\n\tif(idx == 0){\n\t  // --- Go in the opposite direction, increasing lambda --- //\n\t  iter = 0;\n\t  while((iter == 0) ||( (iter++ <= 5) && (Lambdas[0] < maxLam))){\n\t    Model = input_model;\n\t    iLam = checkLambda(iLam * Lam_step*Lam_step, minLam, maxLam);\n\n\t    Lambdas.insert(Lambdas.begin(), iLam);\n\t    iChi2.insert(iChi2.begin(), getCorrection(cont, &Model[0], syn, r, iLam, method) );\n\n\t    if(iChi2[0].value() < iChi2[1].value()){\n\t      bestModel = Model;\n\t      idx = 0;\n\t    }else{\n\t      idx += 1;\n\t      break;\n\t    }\n\t    \n\t  }// while\n\t}\n\t\n\tinput_model = bestModel;\n\tiLam = Lambdas[idx];\n\treturn iChi2[idx];\n      }\n      \n    }\n\n    // ------------------------------------------------------------ //\n\n    T fitData(container<T> const& cont, int const npar, T* __restrict__ bestModel,\n\t      T* __restrict__ bestSyn, int const max_iter = 20, T iLam = 10,\n\t      T const Chi2_thres = 1.0, T const fx_thres = 2.e-3, int const delay_braket = 2,\n\t      bool verbose = true, int const method = 0)\n    {\n      int const nthreads = int(cont.Me.size());\n      Eigen::initParallel();\n      Eigen::setNbThreads(nthreads);\n\n      static constexpr T const facLam = 3.1622776601683795;\n      static constexpr T const maxLam = 1000.;\n      static constexpr T const minLam =  3.1622776601683795e-3;\n      static constexpr int const max_n_reject = 6;\n\n      \n      // --- Init temporary variables --- //\n\n      Chi2<T> bestChi2(1.e34,1.e34); \n      Chi2<T> chi2 = bestChi2;\n      \n      iType const npix = cont.ny*cont.nx;\n      iType const ndat = cont.nDat;\n      iType const nJ = long(npix)*long(npar)*long(ndat);\n\n      \n      T* const __restrict__ r   = new T [npix*ndat]();\n      T* const __restrict__ m   = new T [npix*npar]();\n      \n\n      \n      // --- check pars --- //\n\n      cont.checkPars(npar, bestModel);\n      cont.NormalizePars(npar, bestModel);\n      std::memcpy(m, bestModel, npix*npar*sizeof(T));\n\n      \n\n      // --- Init residue \"r\" --- //\n      \n      std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n      cont.fx(npar, m, bestSyn, r);\n      \n\n      \n      // --- precompute L (only needed once) --- //\n      \n      if(verbose)\n\tfprintf(stdout, \"lms::fitData: pre-computing regularization derivatives matrix ... \");\n      \n      L  = cont.get_L(npar, m);\n      LL = L.transpose()*L;\n      Eigen::Matrix<T,Eigen::Dynamic,1> Reg_RHS;\n      \n      // --- Init total Chi2 --- //\n      {\n\tEigen::Matrix<T, Eigen::Dynamic, 1> Gam = cont.getGamma(npar, m);\n\tbestChi2 = Chi2<T>(ksum2<T,double>(npix*ndat, r), ksum2<T,double>(Gam.size(), &Gam[0]));\n\tReg_RHS = L.transpose()*Gam; // Init RHS regularization term. Vector that only needs to be computed once per successfull iteration.\n      }\n\n      \n\n      // --- Initialize sparse linear system for the first iteration --- //\n      \n      construct_system(npar, cont, m, r, Reg_RHS);\n   \n      \n      if(verbose)\n\tfprintf(stdout,\"done\\n\");\n      \n\n      \n      // --- Init iteration --- //\n\n      if(verbose)\n\tfprintf(stderr, \"\\nlms::fitData: [Init] Chi2=%s\\n\", bestChi2.formatted().c_str());\n      int iter = 0, n_rejected = 0;\n      bool quit = false, tooSmall = false;\n      T oLam = 0, dfx = 0;\n      \n      iLam = checkLambda(iLam, minLam, maxLam);\n\n\n      \n\n      // --- Iterate the solution --- //\n      \n      while(iter < max_iter){\n\n\tbool do_bracket =  ((delay_braket > iter)? false : true);\n\t\n      \toLam = iLam;\n\tstd::memcpy(m, bestModel, npar*npix*sizeof(T));\n\n\t\n\t// --- Get model correction --- //\n\n\tchi2 = getStep(cont, m, bestSyn, r, iLam, do_bracket, minLam, maxLam, facLam, Reg_RHS, bestChi2, method);\n\n\n\t// --- have we improved? --- //\n\n\tif(chi2.value() < bestChi2.value()){\n\n\t  oLam = iLam;\n\t  dfx = (bestChi2.value() - chi2.value()) / bestChi2.value();\n\t  bestChi2 = chi2;\n\n\t  std::memcpy(bestModel,   m, npar*npix*sizeof(T));\n\n\n\t  if(!do_bracket)\n\t    if(iLam*1.00001 > minLam)\n\t      iLam = checkLambda(iLam/facLam, minLam, maxLam);\n\t    else\n\t      iLam *= facLam*facLam;\n\t  else\n\t    iLam = facLam*iLam;\n\t    \t    \n\t  if(dfx < fx_thres){\n\t    if(tooSmall) quit = true;\n\t    else tooSmall = true;\n\t  }\n\t  n_rejected = 0;\n\n\t}else{\n\t  \n\t  iLam = checkLambda(iLam*SQ<T>(facLam), minLam, maxLam);\n\t  n_rejected += 1;\n\t  if(verbose)\n\t    fprintf(stderr,\"lms::fitData: ----> Chi2=%s > %s -> Increasing lambda %f -> %f\\n\",  chi2.formatted().c_str(), bestChi2.formatted().c_str(), oLam, iLam);\n\t  \n\t  if(n_rejected<max_n_reject) continue;\n\t  \n\n\t} // else\n\n\n\tstd::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\tdouble dt = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();\n\tbegin = end;\n\t\n\t// --- Check what has happened with Chi2 --- //\n\t\n\tif(n_rejected >= max_n_reject){\n\t  if(verbose)\n\t    fprintf(stderr, \"lms::fitData: maximum number of rejected iterations reached, finishing inversion\");\n\t  break;\n\t}\n\n\tif(verbose)\n\t  fprintf(stderr, \"lms::fitData: [%3d] Chi2=%s, lambda=%e, dtime=%6.1fs\\n\", iter, chi2.formatted().c_str(), oLam, dt/1000.);\n\n\tif(bestChi2.value() < Chi2_thres){\n\t  if(verbose)\n\t    fprintf(stderr, \"lms::fitData: Chi2 (%f) < Chi2_threshold (%f), finishing inversion\", bestChi2.value(), Chi2_thres);\n\t  break;\n\t}\n\n\tif(quit){\n\t  if(verbose)\n\t    fprintf(stderr, \"lms::fitData: Chi2 improvement too small for 2-iterations, finishing inversion\\n\");\n\t  break;\n\t}\n\t\n\titer++;\n\tif(iter >= max_iter){\n\t  break;\n\t}\n\t\n\t// --- init next iteration --- //\n\t\n\tstd::memcpy(m, bestModel, npix*npar*sizeof(T));\n\t\n\t{\n\t  Eigen::Matrix<T, Eigen::Dynamic, 1> Gam = cont.getGamma(npar, m);\n\t  Reg_RHS = L.transpose()*Gam;\n\t}\n\n\n\t// --- Construct sparse matrix with the new model estimate --- //\n\t\n\tconstruct_system(npar, cont, m, r,  Reg_RHS);\n      }\n\n      \n      // --- Synthesize with best model --- //\n\n      cont.fx(npar, bestModel, bestSyn, r);\n\n\n      \n      // --- scale model parameters ---- //\n\n      cont.ScalePars(npar, bestModel);\n\n      \n\n      // --- Clean up --- //\n      \n      delete [] r;\n      delete [] m;\n\n\n      return bestChi2.value();\n    }\n    \n    // ------------------------------------------------------------ //\n\n  };\n  \n}\n\n\n\n#endif\n", "meta": {"hexsha": "78e5f8bf876ab5da4ad1a59bba088043d651881e", "size": 13129, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spatially_regularized.hpp", "max_stars_repo_name": "HighwayStar/pyMilne", "max_stars_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:37:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T23:48:54.000Z", "max_issues_repo_path": "src/spatially_regularized.hpp", "max_issues_repo_name": "HighwayStar/pyMilne", "max_issues_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatially_regularized.hpp", "max_forks_repo_name": "HighwayStar/pyMilne", "max_forks_repo_head_hexsha": "630fa3715347584980f2a997f7848179bc3847e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-25T13:27:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T18:57:13.000Z", "avg_line_length": 26.7393075356, "max_line_length": 157, "alphanum_fraction": 0.5599055526, "num_tokens": 3863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.5583168069686504}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Pawel Dlotko, Vincent Rouvreau\n *\n *    Copyright (C) 2016 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/Rips_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/writing_persistence_to_file.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n#include <limits>  // infinity\n#include <algorithm>  // for sort\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Rips_complex = Gudhi::rips_complex::Rips_complex<Filtration_value>;\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>;\nusing Correlation_matrix = std::vector<std::vector<Filtration_value>>;\nusing intervals_common = Gudhi::Persistence_interval_common<double, int>;\n\nvoid program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag,\n                     Filtration_value& correlation_min, int& dim_max, int& p, Filtration_value& min_persistence);\n\nint main(int argc, char* argv[]) {\n  std::string csv_matrix_file;\n  std::string filediag;\n  Filtration_value correlation_min;\n  int dim_max;\n  int p;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, csv_matrix_file, filediag, correlation_min, dim_max, p, min_persistence);\n\n  Correlation_matrix correlations =\n      Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_matrix_file);\n\n  Filtration_value threshold = 0;\n\n  // Given a correlation matrix M, we compute component-wise M'[i,j] = 1-M[i,j] to get a distance matrix:\n  for (size_t i = 0; i != correlations.size(); ++i) {\n    for (size_t j = 0; j != correlations[i].size(); ++j) {\n      correlations[i][j] = 1 - correlations[i][j];\n      // Here we make sure that the values of corelations lie between -1 and 1.\n      // If not, we throw an exception.\n      if ((correlations[i][j] < -1) || (correlations[i][j] > 1)) {\n        std::cerr << \"The input matrix is not a correlation matrix. The program will now terminate. \\n\";\n        throw \"The input matrix is not a correlation matrix. The program will now terminate. \\n\";\n      }\n      if (correlations[i][j] > threshold) threshold = correlations[i][j];\n    }\n  }\n\n  Rips_complex rips_complex_from_file(correlations, threshold);\n\n  // Construct the Rips complex in a Simplex Tree\n  Simplex_tree simplex_tree;\n\n  rips_complex_from_file.create_complex(simplex_tree, dim_max);\n  std::clog << \"The complex contains \" << simplex_tree.num_simplices() << \" simplices \\n\";\n  std::clog << \"   and has dimension \" << simplex_tree.dimension() << \" \\n\";\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology pcoh(simplex_tree);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(p);\n  // compute persistence\n  pcoh.compute_persistent_cohomology(min_persistence);\n\n  // invert the persistence diagram. The reason for this procedure is the following:\n  // The input to the program is a corelation matrix M. When processing it, it is\n  // turned into 1-M and the obtained persistence intervals are in '1-M' units.\n  // Below we reverse every (birth,death) pair into (1-birth, 1-death) pair\n  // so that the input and the output to the program is expressed in the same\n  // units.\n  auto pairs = pcoh.get_persistent_pairs();\n  std::vector<intervals_common> processed_persistence_intervals;\n  processed_persistence_intervals.reserve(pairs.size());\n  for (auto pair : pairs) {\n    double birth = 1 - simplex_tree.filtration(get<0>(pair));\n    double death = 1 - simplex_tree.filtration(get<1>(pair));\n    unsigned dimension = (unsigned)simplex_tree.dimension(get<0>(pair));\n    int field = get<2>(pair);\n    processed_persistence_intervals.push_back(intervals_common(birth, death, dimension, field));\n  }\n\n  // sort the processed intervals:\n  std::sort(processed_persistence_intervals.begin(), processed_persistence_intervals.end());\n\n  // and write them to a file\n  if (filediag.empty()) {\n    write_persistence_intervals_to_stream(processed_persistence_intervals);\n  } else {\n    std::ofstream out(filediag);\n    write_persistence_intervals_to_stream(processed_persistence_intervals, out);\n  }\n  return 0;\n}\n\nvoid program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag,\n                     Filtration_value& correlation_min, int& dim_max, int& p, 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>(&csv_matrix_file),\n      \"Name of file containing a corelation matrix. Can be square or lower triangular matrix. Separator is ';'.\");\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()(\"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::clog\")(\n      \"min-edge-corelation,c\", po::value<Filtration_value>(&correlation_min)->default_value(0),\n      \"Minimal corelation 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 \"\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\")) {\n    std::clog << std::endl;\n    std::clog << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::clog << \"of a Rips complex defined on a corelation matrix.\\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.\" << std::endl << std::endl;\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", "meta": {"hexsha": "b473738e82d1a4bf98bc55cf0c28ef1256621411", "size": 7195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Rips_complex/utilities/rips_correlation_matrix_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/Rips_complex/utilities/rips_correlation_matrix_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/Rips_complex/utilities/rips_correlation_matrix_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.8280254777, "max_line_length": 119, "alphanum_fraction": 0.7111883252, "num_tokens": 1856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867825403177, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.5581356415245062}}
{"text": "#include <iostream>\n#include <igl/slice.h>\n#include <Eigen/Dense>\n\nextern \"C\" \n{\n\ttypedef void callback(int k);\n\n\tvoid fd(int numv, int nume, int numfix, double** vertices, int** edges, double** loads, double* q, int* fixed, int* free);\n}\n\nvoid fd(int numv, int nume, int numfix, double** vertices, int** edges, double** loads, double* q, int* fixed, int* free)\n{\n\tint i;\n\tint numfree = numv - numfix;\n\n\tEigen::MatrixXd X(numv, 3);\n\tEigen::MatrixXd Q = Eigen::MatrixXd::Zero(nume, nume);\n\tEigen::MatrixXd C = Eigen::MatrixXd::Zero(nume, numv);\n\n\tEigen::MatrixXd P(numv, 3);\n\n\tEigen::MatrixXd Xi(numfree, 3);\n\tEigen::MatrixXd Xf(numfix, 3);\n\tEigen::MatrixXd Pi(numfree, 3);\n\tEigen::MatrixXd Pf(numfix, 3);\n\n\tEigen::MatrixXd Ci(nume, numfree);\n\tEigen::MatrixXd Cit(numfree, nume);\n\tEigen::MatrixXd Cf(nume, numfix);\n\n\tEigen::VectorXi fixed_vertices(numfix);\n\tEigen::VectorXi free_vertices(numfree);\n\n\tEigen::Vector3i cols(0, 1, 2);\n\tEigen::VectorXi rows = Eigen::VectorXi::LinSpaced(nume, 0, nume - 1);\n\n\tEigen::MatrixXd A(numfree, numfree);\n\tEigen::MatrixXd b(numfree, 3);\n\n\t\n\tfor (i = 0; i < numfree; i++) {\n\t\tfree_vertices(i) = free[i];\n\t}\n\n\tfor (i = 0; i < numfix; i++) {\n\t\tfixed_vertices(i) = fixed[i];\n\t}\n\n\tfor (i = 0; i < nume; i++) {\n\t\tC(i, edges[i][0]) = -1;\n\t\tC(i, edges[i][1]) = +1;\n\t\tQ(i, i) = q[i];\n\t}\n\n\tfor (i = 0; i < numv; i++) {\n\t\tX(i, 0) = vertices[i][0];\n\t\tX(i, 1) = vertices[i][1];\n\t\tX(i, 2) = vertices[i][2];\n\t\tP(i, 0) = loads[i][0];\n\t\tP(i, 1) = loads[i][1];\n\t\tP(i, 2) = loads[i][2];\n\t}\n\n\tigl::slice(P, free_vertices, cols, Pi);\n\tigl::slice(X, fixed_vertices, cols, Xf);\n\tigl::slice(P, fixed_vertices, cols, Pf);\n\tigl::slice(C, rows, free_vertices, Ci);\n\tigl::slice(C, rows, fixed_vertices, Cf);\n\n\tCit = Ci.transpose();\n\n\tA.noalias() = Cit * Q * Ci;\n\tb.noalias() = Pi - Cit * Q * Cf * Xf;\n\n\tXi = A.colPivHouseholderQr().solve(b);\n\n\t// std::cout << Ci << '\\n';\n\t// std::cout << A << '\\n';\n\t// std::cout << b << '\\n';\n\t// std::cout << Xi << '\\n';\n\n\tfor (i = 0; i < numfree; i++) {\n\t\tvertices[free[i]][0] = Xi(i, 0);\n\t\tvertices[free[i]][1] = Xi(i, 1);\n\t\tvertices[free[i]][2] = Xi(i, 2);\n\t}\n\n}\n", "meta": {"hexsha": "67abf39b24d5f852d49a5b38992f2b6260c605d1", "size": 2109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/compas/numerical/fd/__fd_cpp/src/main.cpp", "max_stars_repo_name": "yijiangh/compas", "max_stars_repo_head_hexsha": "a9e86edf6b602f47ca051fccedcaa88a5e5d3600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-27T22:46:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-27T22:46:29.000Z", "max_issues_repo_path": "src/compas/numerical/fd/__fd_cpp/src/main.cpp", "max_issues_repo_name": "yijiangh/compas", "max_issues_repo_head_hexsha": "a9e86edf6b602f47ca051fccedcaa88a5e5d3600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/compas/numerical/fd/__fd_cpp/src/main.cpp", "max_forks_repo_name": "yijiangh/compas", "max_forks_repo_head_hexsha": "a9e86edf6b602f47ca051fccedcaa88a5e5d3600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-16T02:32:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-16T02:32:43.000Z", "avg_line_length": 23.4333333333, "max_line_length": 123, "alphanum_fraction": 0.5903271693, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.5581029376952629}}
{"text": "#include \"../include/m_bp_neural_network.h\"\n#include <vector>\n#include <iostream>\n#include <armadillo>\n#include <math.h>\n\nusing namespace std;\nusing namespace arma;\n\nm_bp_neural_network::m_bp_neural_network(int input_num, initializer_list<int> net_num, initializer_list<string> net_func)\n{\n  this->step = step;\n  int n_layers = net_num.size();\n  this->layers_func = new string[n_layers];\n  this->layers = new mat[n_layers];\n  this->bases = new mat[n_layers];\n  this->hessian_layers = new mat[n_layers];\n\n  this->layers_f_input = new mat[n_layers + 1];\n  this->layers_net_input = new mat[n_layers + 1];\n  this->n_input = input_num;\n  this->n_layers = n_layers;\n  mat r(1, input_num);\n\n  this->layers_net_input[0] = r;\n  this->layers_f_input[0] = r;\n\n  const int *nets_c = net_num.begin();\n  const string *nets_func = net_func.begin();\n  this->n_output = *(nets_c + n_layers - 1);\n\n  mat w(input_num, *(nets_c));\n  mat b(1, *(nets_c));\n  r = mat(1, *(nets_c));\n  this->layers[0] = w;\n  this->layers_func[0] = *(nets_func);\n  this->bases[0] = b;\n  this->layers_net_input[1] = r;\n  this->layers_f_input[1] = r;\n  for (int i = 0; i < n_layers - 2; i++)\n  {\n    w = mat(*(nets_c + i), *(nets_c + i + 1));\n    b = mat(1, *(nets_c + i + 1));\n    r = mat(1, *(nets_c + i + 1));\n    this->layers[i + 1] = w;\n    this->layers_func[i + 1] = *(nets_func + i + 1);\n    this->bases[i + 1] = b;\n    this->layers_f_input[i + 2] = r;\n    this->layers_net_input[i + 2] = r;\n  }\n  w = mat(*(nets_c + n_layers - 2), this->n_output);\n  b = mat(1, this->n_output);\n  r = mat(1, this->n_output);\n  this->layers[n_layers - 1] = w;\n  this->layers_func[n_layers - 1] = *(nets_func + n_layers - 2);\n  this->bases[n_layers - 1] = b;\n  this->layers_f_input[n_layers] = r;\n  this->layers_net_input[n_layers] = r;\n\n  this->delta_layers = new mat[n_layers];\n  this->last_delta_layers = new mat[n_layers];\n  this->delta_bases = new mat[n_layers];\n  for (int i = 0; i < n_layers; i++)\n  {\n    this->delta_layers[i] = mat(this->layers[i].n_rows, this->layers[i].n_cols);\n    this->last_delta_layers[i] = mat(this->layers[i].n_rows, this->layers[i].n_cols);\n    this->delta_bases[i] = mat(this->bases[i].n_rows, this->bases[i].n_cols);\n  }\n}\n\ndouble sigmoid_tanh(double x)\n{\n  double v = tanhf(x);\n  return v;\n}\n\ndouble dsigmoid_tanh(double x)\n{\n  double d = sigmoid_tanh(x);\n  return 1 - d * d;\n}\n\ndouble sigmoid(double x)\n{\n  double v = 1 / (1 + exp(-x));\n  return v;\n}\n\ndouble linear(double x)\n{\n  return x;\n}\n\ndouble dlinear(double x)\n{\n  return 1;\n}\n\ndouble dsigmoid(double x)\n{\n  double d = sigmoid(x);\n  return d * (1 - d);\n}\n\nvoid mapper(mat &mat, double (*func)(double))\n{\n  for (int i = 0; i < mat.n_rows; i++)\n  {\n    for (int j = 0; j < mat.n_cols; j++)\n    {\n      mat(i, j) = func(mat(i, j));\n    }\n  }\n}\n\nvoid sig_func(string name, mat &input)\n{\n  double (*func)(double) = NULL;\n  if (name == \"logsig\")\n  {\n    func = sigmoid;\n  }\n  else if (name == \"tansig\")\n  {\n    func = sigmoid_tanh;\n  }\n  else if (name == \"linear\")\n  {\n    func = linear;\n  }\n  mapper(input, func);\n}\n\nvoid sig_dfunc(string name, mat &input)\n{\n  double (*func)(double) = NULL;\n\n  if (name == \"logsig\")\n  {\n    func = dsigmoid;\n  }\n  else if (name == \"tansig\")\n  {\n    func = dsigmoid_tanh;\n  }\n  else if (name == \"linear\")\n  {\n    func = dlinear;\n  }\n  mapper(input, func);\n}\n\ndouble init_rand(double x)\n{\n  return (x - 0.5) * 2;\n}\n\nvoid m_bp_neural_network::init()\n{\n  for (int i = 0; i < this->n_layers; i++)\n  {\n    this->layers[i].randu();\n    mapper(this->layers[i], init_rand);\n    this->bases[i].randu();\n    mapper(this->bases[i], init_rand);\n  }\n}\n\nvoid m_bp_neural_network::print()\n{\n  cout << \"\\n/////////////////INPUT/////////////////\" << endl;\n  layers_f_input[0].print();\n  cout << \"=======================================\" << endl;\n  for (int i = 0; i < this->n_layers; i++)\n  {\n    layers[i].print();\n    cout << \"--------------------------\" << endl;\n    bases[i].print();\n    cout << \"--------------------------OUT\" << endl;\n    layers_net_input[i + 1].print();\n    cout << \"--------------------------Func OUT\" << endl;\n    layers_f_input[i + 1].print();\n    cout << \"=======================================\" << endl;\n  }\n}\n\nmat m_bp_neural_network::sim(mat &input)\n{\n  mat re = input;\n  for (int i = 0; i < this->n_layers; i++)\n  {\n    mat m1 = re * this->layers[i];\n    mat m2 = m1 + this->bases[i];\n    sig_func(this->layers_func[i], m2);\n    re = m2;\n  }\n  return re;\n}\n\nvoid m_bp_neural_network::sim(mat &input, int index)\n{\n  this->layers_f_input[0].row(index) = input;\n  this->layers_net_input[0].row(index) = input;\n  for (int i = 0; i < this->n_layers; i++)\n  {\n    mat m1 = this->layers_f_input[i].row(index) * this->layers[i];\n    mat m2 = m1 + this->bases[i];\n    this->layers_net_input[i + 1].row(index) = m2;\n    sig_func(this->layers_func[i], m2);\n    this->layers_f_input[i + 1].row(index) = m2;\n  }\n}\n\ndouble pow2(double x)\n{\n  return pow(x, 2);\n}\n//train_func : traingd,trainlm\nvoid m_bp_neural_network::train(string train_func, vector<mat> &input, vector<mat> &result, int max_epoch, double alpha)\n{\n  this->stop_train = false;\n  int kn = this->n_layers;\n  this->step = alpha;\n  int sample_num = input.size();\n  for (int i = 0; i < kn; i++)\n  {\n    this->hessian_layers[i].set_size(sample_num, this->layers[i].n_cols * (this->layers[i].n_rows + 1));\n  }\n  for (int i = 0; i < kn + 1; i++)\n  {\n    this->layers_f_input[i].set_size(sample_num, this->layers_f_input[i].n_cols);\n    this->layers_net_input[i].set_size(sample_num, this->layers_f_input[i].n_cols);\n  }\n  this->mse.set_size(sample_num, 1);\n  this->errors.set_size(sample_num, this->n_output);\n  this->forward(input, result);\n  this->mse_v = as_scalar(sum(sum(this->mse))) / sample_num;\n  for (int i = 0; i < max_epoch; i++)\n  {\n    cout << i + 1 << \" => MSE:\" << this->mse_v << endl;\n    this->back_propagation(sample_num);\n    this->update(train_func, input, result);\n    if (this->stop_train)\n    {\n      cout << i + 1 << \" End Training!\" << endl;\n      break;\n    }\n  }\n}\n\nvoid m_bp_neural_network::forward(vector<mat> &input, vector<mat> &result)\n{\n  int kn = this->n_layers;\n  int sample_num = input.size();\n\n  for (int j = 0; j < sample_num; j++)\n  {\n    this->sim(input[j], j);\n    mat error = result[j] - this->layers_f_input[kn].row(j);\n    mat mse = error;\n    mapper(mse, pow2);\n    this->mse(j, 0) = as_scalar(sum(sum(mse))) / 2;\n    this->errors.row(j) = error;\n  }\n}\n\nvoid m_bp_neural_network::back_propagation(int sample_num)\n{\n  int kn = this->n_layers;\n  //this->errors.print(\"eeeeeeeeeeee\");\n  for (int i = 0; i < sample_num; i++)\n  {\n    mat error = this->errors.row(i);\n    mat net0 = this->layers_net_input[kn].row(i);\n    sig_dfunc(this->layers_func[kn - 1], net0);\n    mat S = net0 % error * (-1);\n    for (int k = kn - 1; k >= 0; k--)\n    {\n      mat f_i_cur = this->layers_f_input[k].row(i);\n      mat St = S.t();\n      mat dW = St * f_i_cur;\n      mat dB = St;\n      mat dWB = mat(dW.n_rows, dW.n_cols + 1);\n      dWB.cols(0, dW.n_cols - 1) = dW;\n\n      dWB.col(dWB.n_cols - 1) = dB;\n      dWB.set_size(dWB.n_rows * dWB.n_cols, 1);\n      dWB = dWB.t();\n\n      this->hessian_layers[k].row(i) = dWB;\n      mat net_cur = this->layers_net_input[(k)].row(i);\n      mat W_cur = this->layers[k].t();\n      if (k > 0)\n      {\n        sig_dfunc(this->layers_func[k], net_cur);\n        mat Ws = S * W_cur;\n        S = Ws % (net_cur);\n      }\n    }\n  }\n}\n\ndouble lnf(double x)\n{\n  return logf(x) / logf(M_E);\n}\n\nvoid m_bp_neural_network::update(string type, vector<mat> &input, vector<mat> &result)\n{\n\n  int kn = this->n_layers;\n\n  int max_step_times = 100;\n  int sample_num = input.size();\n  if (type == \"trainlm\")\n  {\n    double mu_step = 2;\n    int cols = 0;\n    for (int i = 0; i < kn; i++)\n    {\n      cols += this->hessian_layers[i].n_cols;\n    }\n    mat hessian = mat(sample_num, cols);\n    int last_cols = 0;\n    for (int i = 0; i < kn; i++)\n    {\n      hessian.cols(last_cols, last_cols + this->hessian_layers[i].n_cols - 1) = this->hessian_layers[i];\n      last_cols += this->hessian_layers[i].n_cols;\n    }\n    mat hessian_trans = hessian.t();\n    mat HtH = hessian_trans * hessian;\n    mat kI;\n    kI.copy_size(HtH);\n    kI.eye();\n    mat delta = hessian_trans * this->mse;\n\n    double old_step = this->step;\n    int k = 0;\n    for (k = 0; k < max_step_times; k++)\n    {\n      mat Hi = inv(HtH + this->step * kI);\n      mat delta_k = Hi * delta;\n      delta_k = delta_k.t();\n      //delta_k.print(\"MMMMMMM\");\n      last_cols = 0;\n      for (int i = 0; i < kn; i++)\n      {\n\n        mat dWB = delta_k.cols(last_cols, last_cols + this->hessian_layers[i].n_cols - 1);\n        //dW.print(\"dW\");\n        dWB.set_size(this->layers[i].n_cols, this->layers[i].n_rows + 1);\n        dWB = dWB.t();\n        mat dB = dWB.row(dWB.n_rows - 1);\n        mat dW = mat(dWB.n_rows - 1, dWB.n_cols);\n        dW = dWB.rows(0, dW.n_rows - 1);\n        //dB.print(\"dB\");\n        this->delta_layers[i] = dW;\n        this->delta_bases[i] = dB;\n        //this->layers[i].print();\n        //this->bases[i].print();\n        this->layers[i] -= dW;\n        this->bases[i] -= dB;\n        last_cols += this->hessian_layers[i].n_cols;\n      }\n      forward(input, result);\n      double mse_ = as_scalar(sum(sum(this->mse))) / sample_num;\n\n      if (mse_ < this->mse_v)\n      {\n        this->step /= mu_step;\n        cout << this->step << \"|\" << this->mse_v << \" => \" << mse_ << endl;\n        this->mse_v = mse_;\n        break;\n      }\n      for (int i = kn - 1; i >= 0; i--)\n      {\n        this->layers[i] += this->delta_layers[i];\n        this->bases[i] += this->delta_bases[i];\n      }\n      this->step *= mu_step;\n    }\n    if (k >= max_step_times && this->step > old_step)\n    {\n      this->step = old_step;\n      this->stop_train = true;\n    }\n  }\n  else if (type == \"traingd\")\n  {\n    for (int i = 0; i < kn; i++)\n    {\n      this->delta_layers[i].fill(0);\n      this->delta_bases[i].fill(0);\n      for (int j = 0; j < sample_num; j++)\n      {\n        mat dWB = this->hessian_layers[i].row(j);\n        dWB.set_size(this->layers[i].n_cols, this->layers[i].n_rows + 1);\n\n        dWB = dWB.t();\n        mat dB = dWB.row(dWB.n_rows - 1);\n        mat dW = mat(dWB.n_rows - 1, dWB.n_cols);\n        dW = dWB.rows(0, dW.n_rows - 1);\n        this->delta_layers[i] += dW;\n        this->delta_bases[i] += dB;\n      }\n    }\n    double old_step = this->step;\n    int k = 0;\n    double alpha = this->step / sample_num;\n    for (int i = 0; i < kn; i++)\n    {\n      this->layers[i] -= alpha * this->delta_layers[i];\n      this->bases[i] -= alpha * this->delta_bases[i];\n    }\n    forward(input, result);\n    double mse_ = as_scalar(sum(sum(this->mse))) / sample_num;\n    cout << this->step << \"|\" << this->mse_v << \" => \" << mse_ << endl;\n    this->mse_v = mse_;\n  }\n}", "meta": {"hexsha": "57e9331b6d427d3a0c3960abc2e67276dcd3a048", "size": 10799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JNIModule/NN/src/m_bp_neural_network.cpp", "max_stars_repo_name": "imzhangshirong/MiaoMiao", "max_stars_repo_head_hexsha": "1bae2f02d128ec903c8920e5d55fbe4ddb21c722", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T19:46:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-29T16:14:49.000Z", "max_issues_repo_path": "JNIModule/NN/src/m_bp_neural_network.cpp", "max_issues_repo_name": "imzhangshirong/MiaoMiao", "max_issues_repo_head_hexsha": "1bae2f02d128ec903c8920e5d55fbe4ddb21c722", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JNIModule/NN/src/m_bp_neural_network.cpp", "max_forks_repo_name": "imzhangshirong/MiaoMiao", "max_forks_repo_head_hexsha": "1bae2f02d128ec903c8920e5d55fbe4ddb21c722", "max_forks_repo_licenses": ["Apache-2.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.7119047619, "max_line_length": 121, "alphanum_fraction": 0.559681452, "num_tokens": 3468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5581029180191611}}
{"text": "#pragma once\n\n// system includes ---------------------------------------------------------\n#include <boost/math/special_functions/laguerre.hpp>\n#include <functional>\n\n// own includes ------------------------------------------------------------\n#include \"spectral_function_base.hpp\"\n#include \"spectral_weight_function.hpp\"\n\nnamespace boltzmann {\n\nnamespace local_ {\nstruct laguerre_id_t\n{\n private:\n  constexpr const static double FUZZY = 1e6;\n\n public:\n  typedef laguerre_id_t id_t;\n\n  /// Default constructor\n  laguerre_id_t()\n      : fw(-1)\n      , k(-1)\n      , idw(-1)\n  { }\n\n  laguerre_id_t(double fw_, int k_)\n      : fw(fw_)\n      , k(k_)\n      , idw(FUZZY * fw_)\n  {}\n\n\n  /// weight exponent\n  double fw;\n  /// Laguerre polynomial index\n  int k;\n\n  bool operator<(const laguerre_id_t& other) const\n  {\n    return std::tie(k, idw) < std::tie(other.k, other.idw);\n  }\n\n  bool operator==(const laguerre_id_t& other) const\n  {\n    return std::tie(k, idw) == std::tie(other.k, other.idw);\n  }\n\n  friend std::ostream& operator<<(std::ostream& stream, const laguerre_id_t& x)\n  {\n    stream << x.to_string();\n    return stream;\n  }\n\n  std::string to_string() const\n  {\n    return \"(fw_\" + boost::lexical_cast<std::string>(fw) + \", k_\" +\n           boost::lexical_cast<std::string>(k) + \") \";\n  }\n\n  std::tuple<int, long int> key() const { return std::make_tuple(k, idw); }\n\n  /// weight id\n  long int idw;\n};\n}  // end namespace local_\n}  // end namespace boltzmann\n\nnamespace std {\n// hash functions for id's\ntemplate <>\nclass hash<boltzmann::local_::laguerre_id_t>\n{\n public:\n  size_t operator()(const boltzmann::local_::laguerre_id_t& id) const\n  {\n    std::size_t current = std::hash<double>()(id.fw);\n    boost::hash_combine(current, std::hash<int>()(id.k));\n    return current;\n  }\n};\n}  // end namespace std\n\nnamespace boltzmann {\n// --------------------------------------------------------------------------------\nclass LaguerreRR : public weighted<LaguerreRR, true>,\n                   public local_::index_policy<local_::laguerre_id_t>\n{\n public:\n  typedef double numeric_t;\n\n public:\n  LaguerreRR(double fw_, int k_)\n      : id_(fw_, k_)\n  {\n  }\n\n  explicit LaguerreRR(const id_t& id)\n      : id_(id)\n  {\n  }\n\n  LaguerreRR()\n      : id_(-1, -1)\n  {\n  }\n\n  /// evaluate polynomial part\n  double evaluate(double r) const;\n\n  /// evaluate weight\n  double weight(double r) const;\n\n  /// return weight\n  double w() const { return id_.fw; }\n\n  const id_t& get_id() const { return id_; }\n\n private:\n  double evenk(int k, double r) const;\n  double oddk(int k, double r) const;\n\n  id_t id_;\n} __attribute((deprecated));\n\n// ----------------------------------------------------------------------\ninline double\nLaguerreRR::evaluate(double r) const\n{\n  if (id_.k % 2 == 0)\n    return this->evenk(id_.k / 2, r);\n  else\n    return this->oddk((id_.k - 1) / 2, r);\n}\n\n// ----------------------------------------------------------------------\ninline double\nLaguerreRR::weight(double r) const\n{\n  return std::exp(-r * r * id_.fw);\n}\n\n// ----------------------------------------------------------------------\ninline double\nLaguerreRR::evenk(int kk, double r) const\n{\n  return boost::math::laguerre(kk, 0, r * r);\n}\n\n// ----------------------------------------------------------------------\ninline double\nLaguerreRR::oddk(int kk, double r) const\n{\n  return std::sqrt(1. / (kk + 1.)) * r * boost::math::laguerre(kk, 1, r * r);\n}\n}  // end namespace boltzmann\n", "meta": {"hexsha": "61e0fdfc638d1c1076ff9fe229a21f0f20dcc6e0", "size": 3450, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/basis/spectral_function/spectral_radial_function.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/basis/spectral_function/spectral_radial_function.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/basis/spectral_function/spectral_radial_function.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": 21.6981132075, "max_line_length": 83, "alphanum_fraction": 0.5437681159, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381987656671, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5581029157161589}}
{"text": "#include <cmath>\n#include <tuple>\n#include <unordered_map>\n\n#include <boost/math/constants/constants.hpp>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n#include <Euclid/Math/Vector.h>\n\nnamespace Euclid\n{\n\ntemplate<typename Mesh>\nvoid SpinImage<Mesh>::build(const Mesh& mesh,\n                            const std::vector<Vector_3>* vnormals,\n                            FT resolution)\n{\n    this->mesh = &mesh;\n\n    if (vnormals != nullptr) {\n        this->vnormals.reset(vnormals, false);\n    }\n    else {\n        auto face_normals = Euclid::face_normals(mesh);\n        auto vert_normals = Euclid::vertex_normals(mesh, face_normals);\n        this->vnormals.reset(new std::vector<Vector_3>(vert_normals), true);\n    }\n\n    if (resolution != 0.0) {\n        this->resolution = resolution;\n    }\n    else {\n        this->resolution = 0.0;\n        for (auto e : edges(mesh)) {\n            this->resolution += edge_length(e, mesh);\n        }\n        this->resolution /= static_cast<FT>(num_edges(mesh));\n    }\n}\n\ntemplate<typename Mesh>\ntemplate<typename Derived>\nvoid SpinImage<Mesh>::compute(Eigen::ArrayBase<Derived>& spin_img,\n                              float bin_scale,\n                              int image_width,\n                              float support_angle)\n{\n    auto vpmap = get(boost::vertex_point, *this->mesh);\n    auto vimap = get(boost::vertex_index, *this->mesh);\n    auto cos_range =\n        std::cos(support_angle * boost::math::float_constants::degree);\n    auto bin_size = this->resolution * static_cast<FT>(bin_scale);\n    auto support_distance = bin_size * image_width;\n    auto beta_max = support_distance * 0.5;\n    spin_img.derived().setZero(image_width * image_width,\n                               num_vertices(*this->mesh));\n\n    for (auto vi : vertices(*this->mesh)) {\n        auto ii = get(vimap, vi);\n        auto pi = get(vpmap, vi);\n        auto ni = (*this->vnormals)[ii];\n\n        // Find all vertices that lie in the support and compute the spin image\n        for (auto vj : vertices(*this->mesh)) {\n            auto ij = get(vimap, vj);\n            auto pj = get(vpmap, vj);\n\n            if (ni * (*this->vnormals)[ij] < cos_range) {\n                continue;\n            }\n\n            auto beta = ni * (pj - pi);\n            auto alpha = std::sqrt((pj - pi).squared_length() - beta * beta);\n\n            auto col = static_cast<int>(std::floor(alpha / bin_size));\n            if (col > image_width - 2) {\n                continue;\n            }\n            auto row =\n                static_cast<int>(std::floor((beta_max - beta) / bin_size));\n            if (row > image_width - 2 || row < 0) {\n                continue;\n            }\n\n            // Bilinear interpolation\n            auto a = alpha / bin_size - col;\n            auto b = beta_max / bin_size - beta / bin_size - row;\n            EASSERT(a <= 1.0 && a >= 0.0);\n            EASSERT(b <= 1.0 && b >= 0.0);\n            spin_img(row * image_width + col, ii) += (1.0f - a) * (1.0f - b);\n            spin_img(row * image_width + col + 1, ii) += a * (1.0f - b);\n            spin_img((row + 1) * image_width + col, ii) += (1.0f - a) * b;\n            spin_img((row + 1) * image_width + col + 1, ii) += a * b;\n        }\n    }\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "3cd0c700b7ec46d9a7b9684696a0e59dd19a3012", "size": 3251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Descriptor/src/SpinImage.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Descriptor/src/SpinImage.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Descriptor/src/SpinImage.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.1734693878, "max_line_length": 79, "alphanum_fraction": 0.53552753, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5581029075550679}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Function that calculates the pow of two numbers, with a given modulus.\r\ncpp_int mPow(cpp_int base, long long exponent, long long modulus) {\r\n\tcpp_int result = 1;\r\n\twhile(exponent > 0) {\r\n\t\tif(exponent % 2 == 1) {\r\n\t\t\tresult *= base % modulus;\r\n\t\t}\r\n\t\texponent >>= 1;\r\n\t\tbase *= base % modulus;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n// We can try to just use the large number library to handle this trivially.\r\nint main(int argc, char *argv[]) {\r\n\tcout << (28433 * mPow(2, 7830457, 10'000'000'000) + 1) % 10'000'000'000 << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "e5251b6551210f2e7b6629ae31454b453c70a1a6", "size": 665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/97/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/97/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/51-100/97/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 27.7083333333, "max_line_length": 82, "alphanum_fraction": 0.6586466165, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.5580767254370618}}
{"text": "//  Copyright (c) 2006 Xiaogang Zhang\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//  History:\r\n//  XZ wrote the original of this file as part of the Google\r\n//  Summer of Code 2006.  JM modified it to fit into the\r\n//  Boost.Math conceptual framework better, and to correctly\r\n//  handle the y < 0 case.\r\n//\r\n\r\n#ifndef BOOST_MATH_ELLINT_RC_HPP\r\n#define BOOST_MATH_ELLINT_RC_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n\r\n// Carlson's degenerate elliptic integral\r\n// R_C(x, y) = R_F(x, y, y) = 0.5 * \\int_{0}^{\\infty} (t+x)^{-1/2} (t+y)^{-1} dt\r\n// Carlson, Numerische Mathematik, vol 33, 1 (1979)\r\n\r\nnamespace boost { namespace math { namespace detail{\r\n\r\ntemplate <typename T, typename Policy>\r\nT ellint_rc_imp(T x, T y, const Policy& pol)\r\n{\r\n    T value, S, u, lambda, tolerance, prefix;\r\n    unsigned long k;\r\n\r\n    BOOST_MATH_STD_USING\r\n    using namespace boost::math::tools;\r\n\r\n    static const char* function = \"boost::math::ellint_rc<%1%>(%1%,%1%)\";\r\n\r\n    if(x < 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument x must be non-negative but got %1%\", x, pol);\r\n    }\r\n    if(y == 0)\r\n    {\r\n       return policies::raise_domain_error<T>(function,\r\n            \"Argument y must not be zero but got %1%\", y, pol);\r\n    }\r\n\r\n    // error scales as the 6th power of tolerance\r\n    tolerance = pow(4 * tools::epsilon<T>(), T(1) / 6);\r\n\r\n    // for y < 0, the integral is singular, return Cauchy principal value\r\n    if (y < 0)\r\n    {\r\n        prefix = sqrt(x / (x - y));\r\n        x = x - y;\r\n        y = -y;\r\n    }\r\n    else\r\n       prefix = 1;\r\n\r\n    // duplication:\r\n    k = 1;\r\n    do\r\n    {\r\n        u = (x + y + y) / 3;\r\n        S = y / u - 1;               // 1 - x / u = 2 * S\r\n\r\n        if (2 * abs(S) < tolerance) \r\n           break;\r\n\r\n        T sx = sqrt(x);\r\n        T sy = sqrt(y);\r\n        lambda = 2 * sx * sy + y;\r\n        x = (x + lambda) / 4;\r\n        y = (y + lambda) / 4;\r\n        ++k;\r\n    }while(k < policies::get_max_series_iterations<Policy>());\r\n    // Check to see if we gave up too soon:\r\n    policies::check_series_iterations(function, k, pol);\r\n\r\n    // Taylor series expansion to the 5th order\r\n    value = (1 + S * S * (T(3) / 10 + S * (T(1) / 7 + S * (T(3) / 8 + S * T(9) / 22)))) / sqrt(u);\r\n\r\n    return value * prefix;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline typename tools::promote_args<T1, T2>::type \r\n   ellint_rc(T1 x, T2 y, 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>(\r\n      detail::ellint_rc_imp(\r\n         static_cast<value_type>(x),\r\n         static_cast<value_type>(y), pol), \"boost::math::ellint_rc<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type \r\n   ellint_rc(T1 x, T2 y)\r\n{\r\n   return ellint_rc(x, y, policies::policy<>());\r\n}\r\n\r\n}} // namespaces\r\n\r\n#endif // BOOST_MATH_ELLINT_RC_HPP\r\n\r\n", "meta": {"hexsha": "d1b8f2d86914ab4aff2633baa6a4f9b49ccff361", "size": 3377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/math/special_functions/ellint_rc.hpp", "max_stars_repo_name": "dyzmapl/BumpTop", "max_stars_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "trunk/win/Source/Includes/Boost/math/special_functions/ellint_rc.hpp", "max_issues_repo_name": "dyzmapl/BumpTop", "max_issues_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-11-07T04:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:34:12.000Z", "max_forks_repo_path": "trunk/win/Source/Includes/Boost/math/special_functions/ellint_rc.hpp", "max_forks_repo_name": "dyzmapl/BumpTop", "max_forks_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 29.1120689655, "max_line_length": 99, "alphanum_fraction": 0.5892804264, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5580548747228748}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\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 \"quaternion_demo.h\"\r\n#include \"icosphere.h\"\r\n\r\n#include <Eigen/Geometry>\r\n#include <Eigen/QR>\r\n#include <Eigen/LU>\r\n\r\n#include <iostream>\r\n#include <QEvent>\r\n#include <QMouseEvent>\r\n#include <QInputDialog>\r\n#include <QGridLayout>\r\n#include <QButtonGroup>\r\n#include <QRadioButton>\r\n#include <QDockWidget>\r\n#include <QPushButton>\r\n#include <QGroupBox>\r\n\r\nusing namespace Eigen;\r\n\r\nclass FancySpheres\r\n{\r\n  public:\r\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\r\n    \r\n    FancySpheres()\r\n    {\r\n      const int levels = 4;\r\n      const float scale = 0.33;\r\n      float radius = 100;\r\n      std::vector<int> parents;\r\n\r\n      // leval 0\r\n      mCenters.push_back(Vector3f::Zero());\r\n      parents.push_back(-1);\r\n      mRadii.push_back(radius);\r\n\r\n      // generate level 1 using icosphere vertices\r\n      radius *= 0.45;\r\n      {\r\n        float dist = mRadii[0]*0.9;\r\n        for (int i=0; i<12; ++i)\r\n        {\r\n          mCenters.push_back(mIcoSphere.vertices()[i] * dist);\r\n          mRadii.push_back(radius);\r\n          parents.push_back(0);\r\n        }\r\n      }\r\n\r\n      static const float angles [10] = {\r\n        0, 0,\r\n        M_PI, 0.*M_PI,\r\n        M_PI, 0.5*M_PI,\r\n        M_PI, 1.*M_PI,\r\n        M_PI, 1.5*M_PI\r\n      };\r\n\r\n      // generate other levels\r\n      int start = 1;\r\n      for (int l=1; l<levels; l++)\r\n      {\r\n        radius *= scale;\r\n        int end = mCenters.size();\r\n        for (int i=start; i<end; ++i)\r\n        {\r\n          Vector3f c = mCenters[i];\r\n          Vector3f ax0 = (c - mCenters[parents[i]]).normalized();\r\n          Vector3f ax1 = ax0.unitOrthogonal();\r\n          Quaternionf q;\r\n          q.setFromTwoVectors(Vector3f::UnitZ(), ax0);\r\n          Affine3f t = Translation3f(c) * q * Scaling(mRadii[i]+radius);\r\n          for (int j=0; j<5; ++j)\r\n          {\r\n            Vector3f newC = c + ( (AngleAxisf(angles[j*2+1], ax0)\r\n                                * AngleAxisf(angles[j*2+0] * (l==1 ? 0.35 : 0.5), ax1)) * ax0)\r\n                                * (mRadii[i] + radius*0.8);\r\n            mCenters.push_back(newC);\r\n            mRadii.push_back(radius);\r\n            parents.push_back(i);\r\n          }\r\n        }\r\n        start = end;\r\n      }\r\n    }\r\n\r\n    void draw()\r\n    {\r\n      int end = mCenters.size();\r\n      glEnable(GL_NORMALIZE);\r\n      for (int i=0; i<end; ++i)\r\n      {\r\n        Affine3f t = Translation3f(mCenters[i]) * Scaling(mRadii[i]);\r\n        gpu.pushMatrix(GL_MODELVIEW);\r\n        gpu.multMatrix(t.matrix(),GL_MODELVIEW);\r\n        mIcoSphere.draw(2);\r\n        gpu.popMatrix(GL_MODELVIEW);\r\n      }\r\n      glDisable(GL_NORMALIZE);\r\n    }\r\n  protected:\r\n    std::vector<Vector3f> mCenters;\r\n    std::vector<float> mRadii;\r\n    IcoSphere mIcoSphere;\r\n};\r\n\r\n\r\n// generic linear interpolation method\r\ntemplate<typename T> T lerp(float t, const T& a, const T& b)\r\n{\r\n  return a*(1-t) + b*t;\r\n}\r\n\r\n// quaternion slerp\r\ntemplate<> Quaternionf lerp(float t, const Quaternionf& a, const Quaternionf& b)\r\n{ return a.slerp(t,b); }\r\n\r\n// linear interpolation of a frame using the type OrientationType\r\n// to perform the interpolation of the orientations\r\ntemplate<typename OrientationType>\r\ninline static Frame lerpFrame(float alpha, const Frame& a, const Frame& b)\r\n{\r\n  return Frame(lerp(alpha,a.position,b.position),\r\n               Quaternionf(lerp(alpha,OrientationType(a.orientation),OrientationType(b.orientation))));\r\n}\r\n\r\ntemplate<typename _Scalar> class EulerAngles\r\n{\r\npublic:\r\n  enum { Dim = 3 };\r\n  typedef _Scalar Scalar;\r\n  typedef Matrix<Scalar,3,3> Matrix3;\r\n  typedef Matrix<Scalar,3,1> Vector3;\r\n  typedef Quaternion<Scalar> QuaternionType;\r\n\r\nprotected:\r\n\r\n  Vector3 m_angles;\r\n\r\npublic:\r\n\r\n  EulerAngles() {}\r\n  inline EulerAngles(Scalar a0, Scalar a1, Scalar a2) : m_angles(a0, a1, a2) {}\r\n  inline EulerAngles(const QuaternionType& q) { *this = q; }\r\n\r\n  const Vector3& coeffs() const { return m_angles; }\r\n  Vector3& coeffs() { return m_angles; }\r\n\r\n  EulerAngles& operator=(const QuaternionType& q)\r\n  {\r\n    Matrix3 m = q.toRotationMatrix();\r\n    return *this = m;\r\n  }\r\n\r\n  EulerAngles& operator=(const Matrix3& m)\r\n  {\r\n    // mat =  cy*cz          -cy*sz           sy\r\n    //        cz*sx*sy+cx*sz  cx*cz-sx*sy*sz -cy*sx\r\n    //       -cx*cz*sy+sx*sz  cz*sx+cx*sy*sz  cx*cy\r\n    m_angles.coeffRef(1) = std::asin(m.coeff(0,2));\r\n    m_angles.coeffRef(0) = std::atan2(-m.coeff(1,2),m.coeff(2,2));\r\n    m_angles.coeffRef(2) = std::atan2(-m.coeff(0,1),m.coeff(0,0));\r\n    return *this;\r\n  }\r\n\r\n  Matrix3 toRotationMatrix(void) const\r\n  {\r\n    Vector3 c = m_angles.array().cos();\r\n    Vector3 s = m_angles.array().sin();\r\n    Matrix3 res;\r\n    res <<  c.y()*c.z(),                    -c.y()*s.z(),                   s.y(),\r\n            c.z()*s.x()*s.y()+c.x()*s.z(),  c.x()*c.z()-s.x()*s.y()*s.z(),  -c.y()*s.x(),\r\n            -c.x()*c.z()*s.y()+s.x()*s.z(), c.z()*s.x()+c.x()*s.y()*s.z(),  c.x()*c.y();\r\n    return res;\r\n  }\r\n\r\n  operator QuaternionType() { return QuaternionType(toRotationMatrix()); }\r\n};\r\n\r\n// Euler angles slerp\r\ntemplate<> EulerAngles<float> lerp(float t, const EulerAngles<float>& a, const EulerAngles<float>& b)\r\n{\r\n  EulerAngles<float> res;\r\n  res.coeffs() = lerp(t, a.coeffs(), b.coeffs());\r\n  return res;\r\n}\r\n\r\n\r\nRenderingWidget::RenderingWidget()\r\n{\r\n  mAnimate = false;\r\n  mCurrentTrackingMode = TM_NO_TRACK;\r\n  mNavMode = NavTurnAround;\r\n  mLerpMode = LerpQuaternion;\r\n  mRotationMode = RotationStable;\r\n  mTrackball.setCamera(&mCamera);\r\n\r\n  // required to capture key press events\r\n  setFocusPolicy(Qt::ClickFocus);\r\n}\r\n\r\nvoid RenderingWidget::grabFrame(void)\r\n{\r\n    // ask user for a time\r\n    bool ok = false;\r\n    double t = 0;\r\n    if (!m_timeline.empty())\r\n      t = (--m_timeline.end())->first + 1.;\r\n    t = QInputDialog::getDouble(this, \"Eigen's RenderingWidget\", \"time value: \",\r\n      t, 0, 1e3, 1, &ok);\r\n    if (ok)\r\n    {\r\n      Frame aux;\r\n      aux.orientation = mCamera.viewMatrix().linear();\r\n      aux.position = mCamera.viewMatrix().translation();\r\n      m_timeline[t] = aux;\r\n    }\r\n}\r\n\r\nvoid RenderingWidget::drawScene()\r\n{\r\n  static FancySpheres sFancySpheres;\r\n  float length = 50;\r\n  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitX(), Color(1,0,0,1));\r\n  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitY(), Color(0,1,0,1));\r\n  gpu.drawVector(Vector3f::Zero(), length*Vector3f::UnitZ(), Color(0,0,1,1));\r\n\r\n  // draw the fractal object\r\n  float sqrt3 = std::sqrt(3.);\r\n  glLightfv(GL_LIGHT0, GL_AMBIENT, Vector4f(0.5,0.5,0.5,1).data());\r\n  glLightfv(GL_LIGHT0, GL_DIFFUSE, Vector4f(0.5,1,0.5,1).data());\r\n  glLightfv(GL_LIGHT0, GL_SPECULAR, Vector4f(1,1,1,1).data());\r\n  glLightfv(GL_LIGHT0, GL_POSITION, Vector4f(-sqrt3,-sqrt3,sqrt3,0).data());\r\n\r\n  glLightfv(GL_LIGHT1, GL_AMBIENT, Vector4f(0,0,0,1).data());\r\n  glLightfv(GL_LIGHT1, GL_DIFFUSE, Vector4f(1,0.5,0.5,1).data());\r\n  glLightfv(GL_LIGHT1, GL_SPECULAR, Vector4f(1,1,1,1).data());\r\n  glLightfv(GL_LIGHT1, GL_POSITION, Vector4f(-sqrt3,sqrt3,-sqrt3,0).data());\r\n\r\n  glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, Vector4f(0.7, 0.7, 0.7, 1).data());\r\n  glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, Vector4f(0.8, 0.75, 0.6, 1).data());\r\n  glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, Vector4f(1, 1, 1, 1).data());\r\n  glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 64);\r\n\r\n  glEnable(GL_LIGHTING);\r\n  glEnable(GL_LIGHT0);\r\n  glEnable(GL_LIGHT1);\r\n\r\n  sFancySpheres.draw();\r\n  glVertexPointer(3, GL_FLOAT, 0, mVertices[0].data());\r\n  glNormalPointer(GL_FLOAT, 0, mNormals[0].data());\r\n  glEnableClientState(GL_VERTEX_ARRAY);\r\n  glEnableClientState(GL_NORMAL_ARRAY);\r\n  glDrawArrays(GL_TRIANGLES, 0, mVertices.size());\r\n  glDisableClientState(GL_VERTEX_ARRAY);\r\n  glDisableClientState(GL_NORMAL_ARRAY);\r\n\r\n  glDisable(GL_LIGHTING);\r\n}\r\n\r\nvoid RenderingWidget::animate()\r\n{\r\n  m_alpha += double(m_timer.interval()) * 1e-3;\r\n\r\n  TimeLine::const_iterator hi = m_timeline.upper_bound(m_alpha);\r\n  TimeLine::const_iterator lo = hi;\r\n  --lo;\r\n\r\n  Frame currentFrame;\r\n\r\n  if(hi==m_timeline.end())\r\n  {\r\n    // end\r\n    currentFrame = lo->second;\r\n    stopAnimation();\r\n  }\r\n  else if(hi==m_timeline.begin())\r\n  {\r\n    // start\r\n    currentFrame = hi->second;\r\n  }\r\n  else\r\n  {\r\n    float s = (m_alpha - lo->first)/(hi->first - lo->first);\r\n    if (mLerpMode==LerpEulerAngles)\r\n      currentFrame = ::lerpFrame<EulerAngles<float> >(s, lo->second, hi->second);\r\n    else if (mLerpMode==LerpQuaternion)\r\n      currentFrame = ::lerpFrame<Eigen::Quaternionf>(s, lo->second, hi->second);\r\n    else\r\n    {\r\n      std::cerr << \"Invalid rotation interpolation mode (abort)\\n\";\r\n      exit(2);\r\n    }\r\n    currentFrame.orientation.coeffs().normalize();\r\n  }\r\n\r\n  currentFrame.orientation = currentFrame.orientation.inverse();\r\n  currentFrame.position = - (currentFrame.orientation * currentFrame.position);\r\n  mCamera.setFrame(currentFrame);\r\n\r\n  updateGL();\r\n}\r\n\r\nvoid RenderingWidget::keyPressEvent(QKeyEvent * e)\r\n{\r\n    switch(e->key())\r\n    {\r\n      case Qt::Key_Up:\r\n        mCamera.zoom(2);\r\n        break;\r\n      case Qt::Key_Down:\r\n        mCamera.zoom(-2);\r\n        break;\r\n      // add a frame\r\n      case Qt::Key_G:\r\n        grabFrame();\r\n        break;\r\n      // clear the time line\r\n      case Qt::Key_C:\r\n        m_timeline.clear();\r\n        break;\r\n      // move the camera to initial pos\r\n      case Qt::Key_R:\r\n        resetCamera();\r\n        break;\r\n      // start/stop the animation\r\n      case Qt::Key_A:\r\n        if (mAnimate)\r\n        {\r\n          stopAnimation();\r\n        }\r\n        else\r\n        {\r\n          m_alpha = 0;\r\n          connect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));\r\n          m_timer.start(1000/30);\r\n          mAnimate = true;\r\n        }\r\n        break;\r\n      default:\r\n        break;\r\n    }\r\n\r\n    updateGL();\r\n}\r\n\r\nvoid RenderingWidget::stopAnimation()\r\n{\r\n  disconnect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));\r\n  m_timer.stop();\r\n  mAnimate = false;\r\n  m_alpha = 0;\r\n}\r\n\r\nvoid RenderingWidget::mousePressEvent(QMouseEvent* e)\r\n{\r\n  mMouseCoords = Vector2i(e->pos().x(), e->pos().y());\r\n  bool fly = (mNavMode==NavFly) || (e->modifiers()&Qt::ControlModifier);\r\n  switch(e->button())\r\n  {\r\n    case Qt::LeftButton:\r\n      if(fly)\r\n      {\r\n        mCurrentTrackingMode = TM_LOCAL_ROTATE;\r\n        mTrackball.start(Trackball::Local);\r\n      }\r\n      else\r\n      {\r\n        mCurrentTrackingMode = TM_ROTATE_AROUND;\r\n        mTrackball.start(Trackball::Around);\r\n      }\r\n      mTrackball.track(mMouseCoords);\r\n      break;\r\n    case Qt::MidButton:\r\n      if(fly)\r\n        mCurrentTrackingMode = TM_FLY_Z;\r\n      else\r\n        mCurrentTrackingMode = TM_ZOOM;\r\n      break;\r\n    case Qt::RightButton:\r\n        mCurrentTrackingMode = TM_FLY_PAN;\r\n      break;\r\n    default:\r\n      break;\r\n  }\r\n}\r\nvoid RenderingWidget::mouseReleaseEvent(QMouseEvent*)\r\n{\r\n    mCurrentTrackingMode = TM_NO_TRACK;\r\n    updateGL();\r\n}\r\n\r\nvoid RenderingWidget::mouseMoveEvent(QMouseEvent* e)\r\n{\r\n    // tracking\r\n    if(mCurrentTrackingMode != TM_NO_TRACK)\r\n    {\r\n        float dx =   float(e->x() - mMouseCoords.x()) / float(mCamera.vpWidth());\r\n        float dy = - float(e->y() - mMouseCoords.y()) / float(mCamera.vpHeight());\r\n\r\n        // speedup the transformations\r\n        if(e->modifiers() & Qt::ShiftModifier)\r\n        {\r\n          dx *= 10.;\r\n          dy *= 10.;\r\n        }\r\n\r\n        switch(mCurrentTrackingMode)\r\n        {\r\n          case TM_ROTATE_AROUND:\r\n          case TM_LOCAL_ROTATE:\r\n            if (mRotationMode==RotationStable)\r\n            {\r\n              // use the stable trackball implementation mapping\r\n              // the 2D coordinates to 3D points on a sphere.\r\n              mTrackball.track(Vector2i(e->pos().x(), e->pos().y()));\r\n            }\r\n            else\r\n            {\r\n              // standard approach mapping the x and y displacements as rotations\r\n              // around the camera's X and Y axes.\r\n              Quaternionf q = AngleAxisf( dx*M_PI, Vector3f::UnitY())\r\n                            * AngleAxisf(-dy*M_PI, Vector3f::UnitX());\r\n              if (mCurrentTrackingMode==TM_LOCAL_ROTATE)\r\n                mCamera.localRotate(q);\r\n              else\r\n                mCamera.rotateAroundTarget(q);\r\n            }\r\n            break;\r\n          case TM_ZOOM :\r\n            mCamera.zoom(dy*100);\r\n            break;\r\n          case TM_FLY_Z :\r\n            mCamera.localTranslate(Vector3f(0, 0, -dy*200));\r\n            break;\r\n          case TM_FLY_PAN :\r\n            mCamera.localTranslate(Vector3f(dx*200, dy*200, 0));\r\n            break;\r\n          default:\r\n            break;\r\n        }\r\n\r\n        updateGL();\r\n    }\r\n\r\n    mMouseCoords = Vector2i(e->pos().x(), e->pos().y());\r\n}\r\n\r\nvoid RenderingWidget::paintGL()\r\n{\r\n  glEnable(GL_DEPTH_TEST);\r\n  glDisable(GL_CULL_FACE);\r\n  glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);\r\n  glDisable(GL_COLOR_MATERIAL);\r\n  glDisable(GL_BLEND);\r\n  glDisable(GL_ALPHA_TEST);\r\n  glDisable(GL_TEXTURE_1D);\r\n  glDisable(GL_TEXTURE_2D);\r\n  glDisable(GL_TEXTURE_3D);\r\n\r\n  // Clear buffers\r\n  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\r\n  mCamera.activateGL();\r\n\r\n  drawScene();\r\n}\r\n\r\nvoid RenderingWidget::initializeGL()\r\n{\r\n  glClearColor(1., 1., 1., 0.);\r\n  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);\r\n  glDepthMask(GL_TRUE);\r\n  glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);\r\n\r\n  mCamera.setPosition(Vector3f(-200, -200, -200));\r\n  mCamera.setTarget(Vector3f(0, 0, 0));\r\n  mInitFrame.orientation = mCamera.orientation().inverse();\r\n  mInitFrame.position = mCamera.viewMatrix().translation();\r\n}\r\n\r\nvoid RenderingWidget::resizeGL(int width, int height)\r\n{\r\n    mCamera.setViewport(width,height);\r\n}\r\n\r\nvoid RenderingWidget::setNavMode(int m)\r\n{\r\n  mNavMode = NavMode(m);\r\n}\r\n\r\nvoid RenderingWidget::setLerpMode(int m)\r\n{\r\n  mLerpMode = LerpMode(m);\r\n}\r\n\r\nvoid RenderingWidget::setRotationMode(int m)\r\n{\r\n  mRotationMode = RotationMode(m);\r\n}\r\n\r\nvoid RenderingWidget::resetCamera()\r\n{\r\n  if (mAnimate)\r\n    stopAnimation();\r\n  m_timeline.clear();\r\n  Frame aux0 = mCamera.frame();\r\n  aux0.orientation = aux0.orientation.inverse();\r\n  aux0.position = mCamera.viewMatrix().translation();\r\n  m_timeline[0] = aux0;\r\n\r\n  Vector3f currentTarget = mCamera.target();\r\n  mCamera.setTarget(Vector3f::Zero());\r\n\r\n  // compute the rotation duration to move the camera to the target\r\n  Frame aux1 = mCamera.frame();\r\n  aux1.orientation = aux1.orientation.inverse();\r\n  aux1.position = mCamera.viewMatrix().translation();\r\n  float duration = aux0.orientation.angularDistance(aux1.orientation) * 0.9;\r\n  if (duration<0.1) duration = 0.1;\r\n\r\n  // put the camera at that time step:\r\n  aux1 = aux0.lerp(duration/2,mInitFrame);\r\n  // and make it look at the target again\r\n  aux1.orientation = aux1.orientation.inverse();\r\n  aux1.position = - (aux1.orientation * aux1.position);\r\n  mCamera.setFrame(aux1);\r\n  mCamera.setTarget(Vector3f::Zero());\r\n\r\n  // add this camera keyframe\r\n  aux1.orientation = aux1.orientation.inverse();\r\n  aux1.position = mCamera.viewMatrix().translation();\r\n  m_timeline[duration] = aux1;\r\n\r\n  m_timeline[2] = mInitFrame;\r\n  m_alpha = 0;\r\n  animate();\r\n  connect(&m_timer, SIGNAL(timeout()), this, SLOT(animate()));\r\n  m_timer.start(1000/30);\r\n  mAnimate = true;\r\n}\r\n\r\nQWidget* RenderingWidget::createNavigationControlWidget()\r\n{\r\n  QWidget* panel = new QWidget();\r\n  QVBoxLayout* layout = new QVBoxLayout();\r\n\r\n  {\r\n    QPushButton* but = new QPushButton(\"reset\");\r\n    but->setToolTip(\"move the camera to initial position (with animation)\");\r\n    layout->addWidget(but);\r\n    connect(but, SIGNAL(clicked()), this, SLOT(resetCamera()));\r\n  }\r\n  {\r\n    // navigation mode\r\n    QGroupBox* box = new QGroupBox(\"navigation mode\");\r\n    QVBoxLayout* boxLayout = new QVBoxLayout;\r\n    QButtonGroup* group = new QButtonGroup(panel);\r\n    QRadioButton* but;\r\n    but = new QRadioButton(\"turn around\");\r\n    but->setToolTip(\"look around an object\");\r\n    group->addButton(but, NavTurnAround);\r\n    boxLayout->addWidget(but);\r\n    but = new QRadioButton(\"fly\");\r\n    but->setToolTip(\"free navigation like a spaceship\\n(this mode can also be enabled pressing the \\\"shift\\\" key)\");\r\n    group->addButton(but, NavFly);\r\n    boxLayout->addWidget(but);\r\n    group->button(mNavMode)->setChecked(true);\r\n    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setNavMode(int)));\r\n    box->setLayout(boxLayout);\r\n    layout->addWidget(box);\r\n  }\r\n  {\r\n    // track ball, rotation mode\r\n    QGroupBox* box = new QGroupBox(\"rotation mode\");\r\n    QVBoxLayout* boxLayout = new QVBoxLayout;\r\n    QButtonGroup* group = new QButtonGroup(panel);\r\n    QRadioButton* but;\r\n    but = new QRadioButton(\"stable trackball\");\r\n    group->addButton(but, RotationStable);\r\n    boxLayout->addWidget(but);\r\n    but->setToolTip(\"use the stable trackball implementation mapping\\nthe 2D coordinates to 3D points on a sphere\");\r\n    but = new QRadioButton(\"standard rotation\");\r\n    group->addButton(but, RotationStandard);\r\n    boxLayout->addWidget(but);\r\n    but->setToolTip(\"standard approach mapping the x and y displacements\\nas rotations around the camera's X and Y axes\");\r\n    group->button(mRotationMode)->setChecked(true);\r\n    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setRotationMode(int)));\r\n    box->setLayout(boxLayout);\r\n    layout->addWidget(box);\r\n  }\r\n  {\r\n    // interpolation mode\r\n    QGroupBox* box = new QGroupBox(\"spherical interpolation\");\r\n    QVBoxLayout* boxLayout = new QVBoxLayout;\r\n    QButtonGroup* group = new QButtonGroup(panel);\r\n    QRadioButton* but;\r\n    but = new QRadioButton(\"quaternion slerp\");\r\n    group->addButton(but, LerpQuaternion);\r\n    boxLayout->addWidget(but);\r\n    but->setToolTip(\"use quaternion spherical interpolation\\nto interpolate orientations\");\r\n    but = new QRadioButton(\"euler angles\");\r\n    group->addButton(but, LerpEulerAngles);\r\n    boxLayout->addWidget(but);\r\n    but->setToolTip(\"use Euler angles to interpolate orientations\");\r\n    group->button(mNavMode)->setChecked(true);\r\n    connect(group, SIGNAL(buttonClicked(int)), this, SLOT(setLerpMode(int)));\r\n    box->setLayout(boxLayout);\r\n    layout->addWidget(box);\r\n  }\r\n  layout->addItem(new QSpacerItem(0,0,QSizePolicy::Minimum,QSizePolicy::Expanding));\r\n  panel->setLayout(layout);\r\n  return panel;\r\n}\r\n\r\nQuaternionDemo::QuaternionDemo()\r\n{\r\n  mRenderingWidget = new RenderingWidget();\r\n  setCentralWidget(mRenderingWidget);\r\n\r\n  QDockWidget* panel = new QDockWidget(\"navigation\", this);\r\n  panel->setAllowedAreas((QFlags<Qt::DockWidgetArea>)(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea));\r\n  addDockWidget(Qt::RightDockWidgetArea, panel);\r\n  panel->setWidget(mRenderingWidget->createNavigationControlWidget());\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  std::cout << \"Navigation:\\n\";\r\n  std::cout << \"  left button:           rotate around the target\\n\";\r\n  std::cout << \"  middle button:         zoom\\n\";\r\n  std::cout << \"  left button + ctrl     quake rotate (rotate around camera position)\\n\";\r\n  std::cout << \"  middle button + ctrl   walk (progress along camera's z direction)\\n\";\r\n  std::cout << \"  left button:           pan (translate in the XY camera's plane)\\n\\n\";\r\n  std::cout << \"R : move the camera to initial position\\n\";\r\n  std::cout << \"A : start/stop animation\\n\";\r\n  std::cout << \"C : clear the animation\\n\";\r\n  std::cout << \"G : add a key frame\\n\";\r\n\r\n  QApplication app(argc, argv);\r\n  QuaternionDemo demo;\r\n  demo.resize(600,500);\r\n  demo.show();\r\n  return app.exec();\r\n}\r\n\r\n#include \"quaternion_demo.moc\"\r\n\r\n", "meta": {"hexsha": "14faedbf6c2a2681a4dfcdbbbb61d38a410a7f1e", "size": 19848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/demos/opengl/quaternion_demo.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/demos/opengl/quaternion_demo.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/demos/opengl/quaternion_demo.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.2100456621, "max_line_length": 123, "alphanum_fraction": 0.614923418, "num_tokens": 5231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.5580548649531688}}
{"text": "#pragma once\n\n#include \"calotypes/KernelFunctions.hpp\"\n#include \"calotypes/ProbabilityDensity.hpp\"\n\n#include <boost/math/distributions/normal.hpp>\n#include <memory>\n// #include <nanoflann.hpp> // TODO Use\n\nnamespace calotypes\n{\n\n// TODO Allow adding/removing of data?\n/*! \\brief Parzen-Rosenblatt type kernel density estimator. */\ntemplate <class Data>\nclass KernelDensityEstimator\n: public ProbabilityDensityFunction<Data>\n{\npublic:\n\t\n\ttypedef std::shared_ptr<KernelDensityEstimator> Ptr;\n\ttypedef std::vector<Data> Dataset;\n\t\n\t/*! \\brief Construct a KDE with specified data, distance function, kernel function,\n\t * and bandwidth. */\n\tKernelDensityEstimator( const Dataset& d, typename KernelFunction<Data>::Ptr k, double h )\n\t: data( d ), kernel( k )\n\t{\n\t\tbandwidthNormalizer = 1.0 / ( data.size() * h );\n\t\tbandwidthReciprocal = 1.0 / h;\n\t}\n\t\n\t/*! \\brief Return an unnormalized PDF estimate. */\n\tvirtual double operator()( const Data& query ) const\n\t{\n\t\tdouble acc = 0;\n\t\tfor( unsigned int i = 0; i < data.size(); i++ )\n\t\t{\n\t\t\tdouble x = kernel->Difference( query, data[i] );\n\t\t\tacc += kernel->Evaluate( x * bandwidthReciprocal );\n\t\t}\n\t\treturn acc * bandwidthNormalizer;\n\t}\n\t\n\t/*! \\brief This implementation is not normalized. */\n\tvirtual bool IsNormalized() const { return false; }\n\t\n\tdouble inline EvaluateKernel( const Data& a, const Data& b ) const { return (*kernel)( a, b ); }\n\t\nprivate:\n\t\n\tDataset data;\n\ttypename KernelFunction<Data>::Ptr kernel;\n\tdouble bandwidthNormalizer;\n\tdouble bandwidthReciprocal;\n\t\n};\n\n}\n", "meta": {"hexsha": "f433764d266caa90e27e36ae00d21eacebae3b02", "size": 1523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/KernelDensityEstimation.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/KernelDensityEstimation.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/KernelDensityEstimation.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": 25.3833333333, "max_line_length": 97, "alphanum_fraction": 0.7078135259, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5580548565189988}}
{"text": "#ifndef VPYTHON_UTIL_VECTOR_HPP\r\n#define VPYTHON_UTIL_VECTOR_HPP\r\n\r\n// Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others.\r\n// Copyright (c) 2004 by Jonathan Brandmeyer and others.\r\n// See the file license.txt for complete license terms.\r\n// See the file authors.txt for a complete list of contributors.\r\n\r\n#include \"wrap_gl.hpp\"\r\n#include <boost/python/numeric.hpp>\r\n#include <iosfwd>\r\n#include <cmath>\r\n#include <cassert>\r\n#include <sstream>\r\n\r\nnamespace cvisual {\r\n\r\nclass vector\r\n{\r\npublic:\r\n\tdouble x;\r\n\tdouble y;\r\n\tdouble z;\r\n\r\npublic:\r\n\texplicit vector( double a = 0.0, double b = 0.0, double c = 0.0) throw()\r\n\t\t: x(a), y(b), z(c) {}\r\n\r\n\tinline explicit vector( const double* v)\r\n\t\t: x(v[0]), y(v[1]), z(v[2]) {}\r\n\r\n\t// Overloaded binary +, -, *, and /\r\n\tinline vector\r\n\toperator+( const vector& v) const throw()\r\n\t{ return vector( x+v.x, y+v.y, z+v.z); }\r\n\r\n\tinline vector\r\n\toperator-( const vector& v) const throw()\r\n\t{ return vector( x-v.x, y-v.y, z-v.z); }\r\n\r\n\tinline vector\r\n\toperator*( const double s) const throw()\r\n\t{ return vector( s*x, s*y, s*z); }\r\n\r\n\t// Element-wise multiplication used in frame.cpp; not exposed to users\r\n\tinline vector\r\n\toperator*( const vector& v) const throw()\r\n\t{ return vector( x*v.x, y*v.y, z*v.z); }\r\n\r\n\tinline vector\r\n\toperator/( const double s) const throw()\r\n\t{ return vector( x/s, y/s, z/s); }\r\n\r\n    // This operator describes a strict weak ordering as defined by the STL.\r\n\tbool\r\n\tstl_cmp( const vector& v) const;\r\n\r\n\tinline bool\r\n\toperator==( const vector& v) const throw()\r\n\t{ return (v.x == this->x && v.y == this->y && v.z == this->z); }\r\n\r\n\tinline bool\r\n\toperator!=( const vector& v) const throw()\r\n\t{ return !(v == *this); }\r\n\r\n\t// Overloaded uniary !, probably bad coding practice.\r\n\tinline bool\r\n\toperator!( void) const throw()\r\n\t{ return !x && !y && !z; }\r\n\r\n\tbool nonzero() const throw() { return x || y || z; }\r\n\r\n    // Overloaded assignment: +=, -=, *=, /=\r\n\tinline const vector&\r\n\toperator+=( const vector& v) throw()\r\n\t{ x=x+v.x; y=y+v.y; z=z+v.z; return *this; }\r\n\r\n\tinline const vector&\r\n\toperator-=( const vector& v) throw()\r\n\t{ x=x-v.x; y=y-v.y; z=z-v.z; return *this; }\r\n\r\n\tinline const vector&\r\n\toperator*=( const double s) throw()\r\n\t{ x=x*s; y=y*s; z=z*s; return *this; }\r\n\r\n\tinline const vector&\r\n\toperator/=( const double s) throw()\r\n\t{ x=x/s; y=y/s; z=z/s; return *this; }\r\n\r\n \tinline vector\r\n\toperator-() const throw()\r\n\t{ return vector( -x, -y, -z); }\r\n\r\n\t// return the magnitude of this vector\r\n\tinline double\r\n\tmag( void) const throw()\r\n\t{ return std::sqrt( x*x + y*y + z*z); }\r\n\r\n\t// This is a magnitude algorithm that is intended to be stable at values\r\n\t// greater than 1e154 (or so).  It is much slower since it uses sin, cos,\r\n\t// and atan to get the result.\r\n\tdouble\r\n\tstable_mag(void) const;\r\n\r\n\t// return the square of the this vector's magnitude\r\n\tinline double\r\n\tmag2( void) const throw()\r\n\t{ return (x*x + y*y + z*z); }\r\n\r\n\t// return the unit vector of this vector\r\n\tvector\r\n\tnorm( void) const throw();\r\n\r\n\tinline void\r\n\tset_mag( double m) throw()\r\n\t{ *this = norm()*m; }\r\n\r\n\tinline void\r\n\tset_mag2( double m2) throw()\r\n\t{ *this = norm()*std::sqrt(m2); }\r\n\t// Pythonic function to provide a \"representation\" of this object.\r\n\t// object.__repr__() should return a string that, were it executed as python\r\n\t// code, should regenerate the object.\r\n\tstd::string\r\n\trepr() const;\r\n\r\n\t// return the dot product of this vector and another\r\n\tinline double\r\n\tdot( const vector& v) const throw()\r\n\t{ return ( v.x * this->x + v.y * this->y + v.z * this->z); }\r\n\r\n\t// Return the cross product of this vector and another.\r\n\tvector\r\n\tcross( const vector& v) const throw();\r\n\r\n\t// Return the scalar triple product\r\n\tdouble\r\n\tdot_b_cross_c( const vector& b, const vector& c) const throw();\r\n\r\n\t// Return the vector triple product\r\n\tvector\r\n\tcross_b_cross_c( const vector& b, const vector& c) const throw();\r\n\r\n\t// Scalar projection of this to v\r\n\tdouble\r\n\tcomp( const vector& v) const throw();\r\n\r\n\t// Vector projection of this to v\r\n\tvector\r\n\tproj( const vector& v) const throw();\r\n\r\n\t// Returns the angular difference between two vectors, in radians, between 0 and pi.\r\n\tdouble\r\n\tdiff_angle( const vector& v) const throw();\r\n\r\n\t// Scale this vector to another, by elementwise multiplication\r\n\tinline vector\r\n\tscale( const vector& v) const throw()\r\n\t{ return vector( this->x*v.x, this->y*v.y, this->z*v.z); }\r\n\r\n    // Inversely scale this vector to another, by elementwise division\r\n    inline vector\r\n    scale_inv( const vector& v) const throw()\r\n    { return vector( x/v.x, y/v.y, z/v.z); }\r\n\r\n\tvector\r\n\trotate( double angle, vector axis = vector(0,0,1)) throw();\r\n\r\n\t// Last ditch direct read/write access to the private variables\r\n\tinline double\r\n\tget_x( void) const throw() { return x; }\r\n\r\n\tinline void\r\n\tset_x( double s) throw() { this->x = s; }\r\n\r\n\tinline double\r\n\tget_y( void) const throw() { return y; }\r\n\r\n\tinline void\r\n\tset_y( double s) throw() { this->y = s; }\r\n\r\n\tinline double\r\n\tget_z( void) const throw() { return z; }\r\n\r\n\tinline void\r\n\tset_z( double s) throw() { this->z = s; }\r\n\r\n\t// zero the state of the vector. Potentially useful for reusing a temporary.\r\n\tinline void\r\n\tclear( void) { x=0.0; y=0.0; z=0.0; }\r\n\r\n    inline int\r\n\tpy_len() { return 3; }\r\n\r\n\tdouble py_getitem( int i) const;\r\n\r\n\tvoid py_setitem(int i, double value);\r\n\r\n\r\n\tinline double&\r\n\toperator[]( size_t ref)\r\n\t{\r\n\t\tassert( ref < 3);\r\n\t\tswitch (ref) {\r\n\t\t\tcase 0:\r\n\t\t\t\treturn x;\r\n\t\t\tcase 1:\r\n\t\t\t\treturn y;\r\n\t\t\tcase 2:\r\n\t\t\t\treturn z;\r\n\t\t\tdefault:\r\n\t\t\t\tassert( true == false);\r\n\t\t}\r\n\t}\r\n\r\n\tinline const double&\r\n\toperator[]( size_t ref) const\r\n\t{\r\n\t\tassert( ref < 3);\r\n\t\tswitch (ref) {\r\n\t\t\tcase 0:\r\n\t\t\t\treturn x;\r\n\t\t\tcase 1:\r\n\t\t\t\treturn y;\r\n\t\t\tcase 2:\r\n\t\t\t\treturn z;\r\n\t\t}\r\n\t}\r\n\r\n\tinline vector\r\n\tfabs() const\r\n\t{ return vector( std::fabs(x), std::fabs(y), std::fabs(z)); }\r\n\r\n\tinline void\r\n\tgl_render() const\r\n\t{ glVertex3dv( &x); }\r\n\r\n\tinline void\r\n\tgl_normal() const\r\n\t{ glNormal3dv( &x); }\r\n\r\n\tinline double\r\n\tsum() const\r\n\t{ return x + y + z; }\r\n};\r\n\r\n// Free functions for mag, mag2, dot, unit, cross, and tripleproducts.\r\n// All of these functions merely call their class-member variants to save code.\r\ninline double\r\nmag( const vector& v)\r\n{ return v.mag(); }\r\n\r\ninline double\r\nmag2( const vector& v)\r\n{ return v.mag2(); }\r\n\r\ninline vector\r\nnorm( const vector& v)\r\n{ return v.norm(); }\r\n\r\ninline double\r\ndot( const vector& v1, const vector& v2)\r\n{ return v1.dot( v2); }\r\n\r\ninline vector\r\ncross( const vector& v1, const vector& v2)\r\n{ return v1.cross( v2); }\r\n\r\ninline double\r\na_dot_b_cross_c( const vector& a, const vector& b, const vector& c)\r\n{  return a.dot_b_cross_c( b, c);  }\r\n\r\ninline vector\r\na_cross_b_cross_c( const vector& a, const vector& b, const vector& c)\r\n{ return a.cross_b_cross_c( b, c); }\r\n\r\n// Scalar projection of v1 -> v2\r\ninline double\r\ncomp( const vector& v1, const vector& v2)\r\n{ return v1.comp( v2); }\r\n\r\n// Vector projection of v1 to v2\r\ninline vector\r\nproj( const vector& v1, const vector& v2)\r\n{ return v1.proj( v2); }\r\n\r\n// Returns the angular difference between two vectors, in radians, from 0 - pi.\r\ninline double\r\ndiff_angle( const vector& v1, const vector& v2)\r\n{ return v1.diff_angle( v2); }\r\n\r\ninline vector\r\nrotate( vector v, double angle, const vector axis = vector( 0,0,1))\r\n{ return v.rotate( angle, axis); }\r\n\r\n\r\n// Definitions of the global functions for operator *, with a vector on the RHS,\r\n// and scalar on the LHS.\r\n\r\ninline vector\r\noperator*( const double& s, const vector& v)\r\n{\r\n  return vector( s*v.x, s*v.y, s*v.z);\r\n}\r\n} // !namespace cvisual\r\n\r\n// We should not need to place this in namespace std, but GCC's Koenig L/U fails\r\n//   if we don't.\r\nnamespace std {\r\n// Insertion operator.  Example output: <xxxx, yyyy, zzzz>\r\n// Based on \"The C++ Standard Library\", N. M. Josuttis, section 13.12.1\r\ntemplate<typename char_T, typename traits>\r\nbasic_ostream<char_T, traits>&\r\noperator<<( basic_ostream<char_T, traits>& stream, const cvisual::vector& v)\r\n{\r\n\tbasic_ostringstream<char_T, traits> s;\r\n\ts.copyfmt( stream);\r\n\ts.width( 0);\r\n\r\n\ts << \"<\" << v.x << \", \" << v.y << \", \" << v.z << \">\";\r\n\tstream << s.str();\r\n\r\n\treturn stream;\r\n}\r\n\r\n} // !namespace std\r\n\r\nnamespace cvisual {\r\n\r\ntypedef vector shared_vector;\r\n\r\n} // !namespace cvisual\r\n\r\n#endif // !VPYTHON_UTIL_VECTOR_HPP\r\n", "meta": {"hexsha": "349259b914b17430967fe0f3a2681df717b28c65", "size": 8315, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/vector.hpp", "max_stars_repo_name": "lebarsfa/vpython-wx", "max_stars_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 68.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T05:41:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:35:24.000Z", "max_issues_repo_path": "include/util/vector.hpp", "max_issues_repo_name": "lebarsfa/vpython-wx", "max_issues_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-09T21:01:25.000Z", "max_forks_repo_path": "include/util/vector.hpp", "max_forks_repo_name": "lebarsfa/vpython-wx", "max_forks_repo_head_hexsha": "38df062e5532b79f632f4f2a1abae86754c264a9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2015-02-04T04:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-07T03:24:41.000Z", "avg_line_length": 24.8208955224, "max_line_length": 86, "alphanum_fraction": 0.6337943476, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5579444727527149}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n\n//! The gradient of the shape function (on the reference element)\n//! \n//! We have three shape functions\n//!\n//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientLambda(const int i, double x, double y) {\n  //// ANCSE_START_TEMPLATE\n    return Eigen::Vector2d(-1 + (i > 0) + (i==1),\n                           -1 + (i > 0) + (i==2));\n    //// ANCSE_END_TEMPLATE\n    return Eigen::Vector2d(0,0); //remove when implemented\n}\n", "meta": {"hexsha": "30a8dd3fd2206eecce8ca68064c6df3073efa930", "size": 631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series0_solution/2d-poissonlFEM/grad_shape.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series0_solution/2d-poissonlFEM/grad_shape.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series0_solution/2d-poissonlFEM/grad_shape.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 33.2105263158, "max_line_length": 89, "alphanum_fraction": 0.648177496, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5579444650421999}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n#define BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/assert.hpp>\r\n#include <boost/math/tools/rational.hpp>\r\n#include <boost/math/tools/real_cast.hpp>\r\n#include <boost/math/special_functions/binomial.hpp>\r\n\r\n#include <vector>\r\n#include <ostream>\r\n#include <algorithm>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\ntemplate <class T>\r\nT chebyshev_coefficient(unsigned n, unsigned m)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   if(m > n)\r\n      return 0;\r\n   if((n & 1) != (m & 1))\r\n      return 0;\r\n   if(n == 0)\r\n      return 1;\r\n   T result = T(n) / 2;\r\n   unsigned r = n - m;\r\n   r /= 2;\r\n\r\n   BOOST_ASSERT(n - 2 * r == m);\r\n\r\n   if(r & 1)\r\n      result = -result;\r\n   result /= n - r;\r\n   result *= boost::math::binomial_coefficient<T>(n - r, r);\r\n   result *= ldexp(1.0f, m);\r\n   return result;\r\n}\r\n\r\ntemplate <class Seq>\r\nSeq polynomial_to_chebyshev(const Seq& s)\r\n{\r\n   // Converts a Polynomial into Chebyshev form:\r\n   typedef typename Seq::value_type value_type;\r\n   typedef typename Seq::difference_type difference_type;\r\n   Seq result(s);\r\n   difference_type order = s.size() - 1;\r\n   difference_type even_order = order & 1 ? order - 1 : order;\r\n   difference_type odd_order = order & 1 ? order : order - 1;\r\n\r\n   for(difference_type i = even_order; i >= 0; i -= 2)\r\n   {\r\n      value_type val = s[i];\r\n      for(difference_type k = even_order; k > i; k -= 2)\r\n      {\r\n         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));\r\n      }\r\n      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));\r\n      result[i] = val;\r\n   }\r\n   result[0] *= 2;\r\n\r\n   for(difference_type i = odd_order; i >= 0; i -= 2)\r\n   {\r\n      value_type val = s[i];\r\n      for(difference_type k = odd_order; k > i; k -= 2)\r\n      {\r\n         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));\r\n      }\r\n      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));\r\n      result[i] = val;\r\n   }\r\n   return result;\r\n}\r\n\r\ntemplate <class Seq, class T>\r\nT evaluate_chebyshev(const Seq& a, const T& x)\r\n{\r\n   // Clenshaw's formula:\r\n   typedef typename Seq::difference_type difference_type;\r\n   T yk2 = 0;\r\n   T yk1 = 0;\r\n   T yk = 0;\r\n   for(difference_type i = a.size() - 1; i >= 1; --i)\r\n   {\r\n      yk2 = yk1;\r\n      yk1 = yk;\r\n      yk = 2 * x * yk1 - yk2 + a[i];\r\n   }\r\n   return a[0] / 2 + yk * x - yk1;\r\n}\r\n\r\ntemplate <class T>\r\nclass polynomial\r\n{\r\npublic:\r\n   // typedefs:\r\n   typedef typename std::vector<T>::value_type value_type;\r\n   typedef typename std::vector<T>::size_type size_type;\r\n\r\n   // construct:\r\n   polynomial(){}\r\n   template <class U>\r\n   polynomial(const U* data, unsigned order)\r\n      : m_data(data, data + order + 1)\r\n   {\r\n   }\r\n   template <class U>\r\n   polynomial(const U& point)\r\n   {\r\n      m_data.push_back(point);\r\n   }\r\n\r\n   // copy:\r\n   polynomial(const polynomial& p)\r\n      : m_data(p.m_data) { }\r\n\r\n   template <class U>\r\n   polynomial(const polynomial<U>& p)\r\n   {\r\n      for(unsigned i = 0; i < p.size(); ++i)\r\n      {\r\n         m_data.push_back(boost::math::tools::real_cast<T>(p[i]));\r\n      }\r\n   }\r\n\r\n   // access:\r\n   size_type size()const { return m_data.size(); }\r\n   size_type degree()const { return m_data.size() - 1; }\r\n   value_type& operator[](size_type i)\r\n   {\r\n      return m_data[i];\r\n   }\r\n   const value_type& operator[](size_type i)const\r\n   {\r\n      return m_data[i];\r\n   }\r\n   T evaluate(T z)const\r\n   {\r\n      return boost::math::tools::evaluate_polynomial(&m_data[0], z, m_data.size());;\r\n   }\r\n   std::vector<T> chebyshev()const\r\n   {\r\n      return polynomial_to_chebyshev(m_data);\r\n   }\r\n\r\n   // operators:\r\n   template <class U>\r\n   polynomial& operator +=(const U& value)\r\n   {\r\n      if(m_data.size() == 0)\r\n         m_data.push_back(value);\r\n      else\r\n      {\r\n         m_data[0] += value;\r\n      }\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator -=(const U& value)\r\n   {\r\n      if(m_data.size() == 0)\r\n         m_data.push_back(-value);\r\n      else\r\n      {\r\n         m_data[0] -= value;\r\n      }\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator *=(const U& value)\r\n   {\r\n      for(size_type i = 0; i < m_data.size(); ++i)\r\n         m_data[i] *= value;\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator +=(const polynomial<U>& value)\r\n   {\r\n      size_type s1 = (std::min)(m_data.size(), value.size());\r\n      for(size_type i = 0; i < s1; ++i)\r\n         m_data[i] += value[i];\r\n      for(size_type i = s1; i < value.size(); ++i)\r\n         m_data.push_back(value[i]);\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator -=(const polynomial<U>& value)\r\n   {\r\n      size_type s1 = (std::min)(m_data.size(), value.size());\r\n      for(size_type i = 0; i < s1; ++i)\r\n         m_data[i] -= value[i];\r\n      for(size_type i = s1; i < value.size(); ++i)\r\n         m_data.push_back(-value[i]);\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator *=(const polynomial<U>& value)\r\n   {\r\n      // TODO: FIXME: use O(N log(N)) algorithm!!!\r\n      BOOST_ASSERT(value.size());\r\n      polynomial base(*this);\r\n      *this *= value[0];\r\n      for(size_type i = 1; i < value.size(); ++i)\r\n      {\r\n         polynomial t(base);\r\n         t *= value[i];\r\n         size_type s = size() - i;\r\n         for(size_type j = 0; j < s; ++j)\r\n         {\r\n            m_data[i+j] += t[j];\r\n         }\r\n         for(size_type j = s; j < t.size(); ++j)\r\n            m_data.push_back(t[j]);\r\n      }\r\n      return *this;\r\n   }\r\n\r\nprivate:\r\n   std::vector<T> m_data;\r\n};\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator + (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result += b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator - (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator * (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator + (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result += b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator - (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator * (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator + (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(b);\r\n   result += a;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator - (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator * (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(b);\r\n   result *= a;\r\n   return result;\r\n}\r\n\r\ntemplate <class charT, class traits, class T>\r\ninline std::basic_ostream<charT, traits>& operator << (std::basic_ostream<charT, traits>& os, const polynomial<T>& poly)\r\n{\r\n   os << \"{ \";\r\n   for(unsigned i = 0; i < poly.size(); ++i)\r\n   {\r\n      if(i) os << \", \";\r\n      os << poly[i];\r\n   }\r\n   os << \" }\";\r\n   return os;\r\n}\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "8225736b9e5838303d7bcfccdd76d9094ff3e022", "size": 8032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/polynomial.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/polynomial.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/tools/polynomial.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 24.7901234568, "max_line_length": 121, "alphanum_fraction": 0.5734561753, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5579444580760592}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <random>\n#include <unordered_set>\n#include <vector>\n\ntemplate <typename Real> struct SGDMF {\n  using SparseMatrix = Eigen::SparseMatrix<Real, Eigen::RowMajor>;\n  using DenseMatrix =\n      Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  using DenseVector = Eigen::Matrix<Real, Eigen::Dynamic, 1>;\n\n  using Index = typename DenseMatrix::StorageIndex;\n  using Sample = std::tuple<Index, Index, int64_t>;\n\n  inline SGDMF(const SparseMatrix &X, int dim, int random_seed, Real lr,\n               Real lambda, Real std, size_t n_negative)\n      : X_(X), dim(dim), rng(random_seed), lr(lr), lambda(lambda),\n        n_negative(n_negative) {\n    X_.makeCompressed();\n    P.resize(X_.rows(), dim);\n    Q.resize(X_.cols(), dim);\n    P_cache.resize(dim);\n    Q_cache.resize(dim);\n    P_b = DenseVector::Zero(X_.rows());\n    Q_b = DenseVector::Zero(X_.cols());\n    auto fill_normal = [this, std](DenseMatrix &U) {\n      int rows = U.rows();\n      int cols = U.cols();\n      std::normal_distribution<Real> dist(0, std);\n      for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++) {\n          U(i, j) = dist(this->rng);\n        }\n      }\n    };\n    fill_normal(P);\n    fill_normal(Q);\n\n    size_t dsize = X_.nonZeros() + X_.rows() * n_negative;\n    dataset.resize(dsize);\n  }\n\n  inline void start_epoch() {\n    size_t cursor = 0;\n    std::uniform_int_distribution<> dist(0, X_.cols() - 1);\n    for (int u = 0; u < X_.rows(); u++) {\n      for (typename SparseMatrix::InnerIterator iter(X_, u); iter; ++iter) {\n        int j = iter.col();\n        Sample q(u, j, 1);\n        dataset[cursor++] = std::move(q);\n      }\n      for (size_t m_ = 0; m_ < n_negative; m_++) {\n        dataset[cursor++] = {u, dist(rng), 0};\n      }\n    }\n    if (static_cast<size_t>(X_.nonZeros() + X_.rows() * n_negative) != cursor) {\n      throw std::runtime_error(\"somethong nasty\");\n    }\n    std::shuffle(dataset.begin(), dataset.end(), rng);\n  }\n\n  inline Real run_epoch() {\n    start_epoch();\n    Real mean_loss = 0;\n    for (auto &s : dataset) {\n      mean_loss += sgd(s);\n    }\n    return mean_loss / dataset.size();\n  }\n\n  inline Real sgd(const Sample &s) {\n    const Index &u = std::get<0>(s);\n    const Index &i = std::get<1>(s);\n    const int64_t &y = std::get<2>(s);\n    P_cache.noalias() = P.row(u).transpose();\n    Q_cache.noalias() = Q.row(i).transpose();\n    Real score = (P_cache.transpose() * Q_cache) + bias + P_b(u) + Q_b(i);\n    Real sigma_score;\n    Real loss;\n    if (score > 0) {\n      sigma_score = 1 / (1 + std::exp(-score));\n      loss = -std::log(sigma_score) + (1 - y) * score;\n    } else {\n      Real exp_score = std::exp(score);\n      sigma_score = exp_score / (1 + exp_score);\n      loss = -y * score + std::log(1 + exp_score);\n    }\n\n    Real grad = (y - sigma_score);\n\n    P.row(u).noalias() += lr * (grad * Q_cache - lambda * P_cache).transpose();\n    Q.row(i).noalias() += lr * (grad * P_cache - lambda * Q_cache).transpose();\n    P_b(u) += lr * (grad - lambda * P_b(u));\n    Q_b(i) += lr * (grad - lambda * Q_b(i));\n    bias += lr * (grad - lambda * bias);\n    return loss;\n  }\n\n  SparseMatrix X_;\n\n  Real bias;\n  DenseMatrix P, Q;\n  DenseVector P_b, Q_b;\n  DenseVector P_cache, Q_cache;\n  int dim;\n\n  std::vector<Sample> dataset;\n\nprivate:\n  std::mt19937 rng;\n\n  Real lr, lambda;\n  size_t n_negative;\n};\n\nnamespace py = pybind11;\nusing std::vector;\n\nPYBIND11_MODULE(_sgd_mf, m) {\n  using Real = double;\n  using MF = SGDMF<Real>;\n  py::class_<MF>(m, \"_MF\")\n      .def(py::init<const typename MF::SparseMatrix &, int, int, Real, Real,\n                    Real, size_t>())\n      .def(\"step\", &MF::run_epoch)\n      .def_readonly(\"dataset\", &MF::dataset)\n      .def_readwrite(\"P\", &MF::P)\n      .def_readwrite(\"Q\", &MF::Q)\n      .def_readwrite(\"P_b\", &MF::P_b)\n      .def_readwrite(\"Q_b\", &MF::Q_b)\n      .def_readwrite(\"bias\", &MF::bias);\n}\n", "meta": {"hexsha": "1b4f6dc086ddd5526e312f5422c5dae4558059c8", "size": 4034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_source/sgd_mf/sgd_mf.cpp", "max_stars_repo_name": "Random1992/irspack", "max_stars_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T08:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:48:55.000Z", "max_issues_repo_path": "cpp_source/sgd_mf/sgd_mf.cpp", "max_issues_repo_name": "Random1992/irspack", "max_issues_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2021-01-03T12:29:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T12:58:05.000Z", "max_forks_repo_path": "cpp_source/sgd_mf/sgd_mf.cpp", "max_forks_repo_name": "Random1992/irspack", "max_forks_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T10:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T12:53:20.000Z", "avg_line_length": 29.231884058, "max_line_length": 80, "alphanum_fraction": 0.5852751611, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5579394158018879}}
{"text": "/*\n\nMIT License\n\nCopyright (c) 2020, R. Gregor Weiß, Benjamin Ries\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 <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\n#include \"geometry.h\"\n\nnamespace Geometry {\n\n    double regularized_intersection_volume(const double dist,\n                                           const double cut,\n                                           const unsigned int n) {\n        double nd(static_cast<double>(n));\n        double nhalfplusonehalf(0.5 * (nd + 1.0));\n        double sin2phi(-1.0 * 0.25 * dist * dist);\n        sin2phi /= (cut * cut);\n        sin2phi += 1.0;\n        double incomplete_beta(boost::math::ibeta<double, double, double>(nhalfplusonehalf, 0.5, sin2phi));\n\n        return incomplete_beta;\n    }\n\n}\n", "meta": {"hexsha": "b4e0534fc616067f24d2e1dd98290ee44aa87272", "size": 1826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry.cpp", "max_stars_repo_name": "gregorweiss/vsCNN", "max_stars_repo_head_hexsha": "e48fa589c6fbb11437b0d766f666ccdf3ebc57e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-18T10:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T13:18:24.000Z", "max_issues_repo_path": "src/geometry.cpp", "max_issues_repo_name": "gregorweiss/vsCNN", "max_issues_repo_head_hexsha": "e48fa589c6fbb11437b0d766f666ccdf3ebc57e3", "max_issues_repo_licenses": ["MIT"], "max_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.cpp", "max_forks_repo_name": "gregorweiss/vsCNN", "max_forks_repo_head_hexsha": "e48fa589c6fbb11437b0d766f666ccdf3ebc57e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-08T14:21:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T14:21:16.000Z", "avg_line_length": 38.0416666667, "max_line_length": 107, "alphanum_fraction": 0.7163198248, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.557939404325143}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <robotics/common.hpp>\n#include <robotics/system/nonlinear_system.hpp>\n#include <vector>\n\nnamespace Robotics::Estimation {\n\n    /**\n     * @brief A class for implemeting an Extended Kalman Filter\n     */\n    template <int StateSize, int InputSize, int OutputSize>\n    class EKF {\n        static_assert(StateSize > 0);\n        static_assert(InputSize > 0);\n        static_assert(OutputSize > 0);\n\n        using State = ColumnVector<StateSize>;\n        using Input = ColumnVector<InputSize>;\n        using Measurement = ColumnVector<OutputSize>;\n\n        using NonlinearSystem = Robotics::Model::NonlinearSystem<StateSize, InputSize, OutputSize>;\n\n      public:\n        /**\n         * @brief Creates a new Extended Kalman Filter\n         * @param system nonlinear model of the system\n         * @param Q state covariance matrix\n         * @param R output covariance matrix\n         */\n        EKF(NonlinearSystem system, SquareMatrix<StateSize> Q, SquareMatrix<OutputSize> R)\n            : system(system), Q(Q), R(R)\n        {\n        }\n\n        /**\n         * @brief Updates the state estimate\n         * @param previous_estimate last estimated state\n         * @param z latest measurement\n         * @param u control input\n         * @return the updated state estimate\n         */\n        State Update(State, Measurement z, Input u, double dt)\n        {\n            // Predicted state estimate\n            system.PropagateDynamics(u, dt);\n            x_predicted = system.GetState();\n\n            // Predicted covariance estimate\n            SquareMatrix<StateSize> J_F = system.GetStateJacobian(u, dt);\n            P_predicted = J_F * P_estimate * J_F.transpose() + Q;\n\n            // Update\n            z_predicted = system.GetOutputMatrix() * x_predicted;\n            residual = z - z_predicted;\n\n            const Matrix<OutputSize, StateSize> J_H = system.GetOutputJacobian(u, dt);\n            S = J_H * P_predicted * J_H.transpose() + R;\n            K = P_predicted * J_H.transpose() * S.inverse();\n            x_estimate = x_predicted + K * residual;\n            P_estimate = (SquareMatrix<StateSize>::Identity() - K * J_H) * P_predicted;\n\n            return x_estimate;\n        }\n\n      private:\n        NonlinearSystem system;\n\n        SquareMatrix<StateSize> P_predicted, P_estimate;\n        SquareMatrix<OutputSize> S;\n        Robotics::Matrix<StateSize, OutputSize> K;\n\n        State x_predicted, x_estimate;\n        Measurement z_predicted, residual;\n\n        // State covariance\n        const SquareMatrix<StateSize> Q;\n\n        // Observation covariance\n        const SquareMatrix<OutputSize> R;\n    };\n\n}  // namespace Robotics::Estimation", "meta": {"hexsha": "bc68346cb263e157232d225f966a5d7374232ea7", "size": 2717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/robotics/estimation/extended_kalman_filter.hpp", "max_stars_repo_name": "JKI757/CppRobotics", "max_stars_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 286.0, "max_stars_repo_stars_event_min_datetime": "2021-09-27T20:58:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T19:12:10.000Z", "max_issues_repo_path": "include/robotics/estimation/extended_kalman_filter.hpp", "max_issues_repo_name": "imthemd/CppRobotics", "max_issues_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T02:19:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T19:46:08.000Z", "max_forks_repo_path": "include/robotics/estimation/extended_kalman_filter.hpp", "max_forks_repo_name": "imthemd/CppRobotics", "max_forks_repo_head_hexsha": "469ce89f826b4cb981b017d9112ed311f39114b5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T01:26:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T11:01:01.000Z", "avg_line_length": 31.9647058824, "max_line_length": 99, "alphanum_fraction": 0.6117040854, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.5579059295270336}}
{"text": "/*\n * EKF.hpp\n *\n *  Created on: 27.07.2018\n *      Author: tomlucas\n */\n\n#ifndef ESTIMATORS_UKF_HPP_\n#define ESTIMATORS_UKF_HPP_\n\n#define FILL_LATER 0\n\n#include \"Eigen/Geometry\"\n#include <Eigen/Cholesky>\n#include <OSG_Utils.hpp>\n\n#include \"../Plugins/sensor_plugin.hpp\"\nnamespace zavi {\nnamespace estimator {\n/**\n * Base class for all Extended Kalman Filters\n *\n * state_dim Dimension of the State\n * input_dim Dimension of the input Vector\n */\ntemplate<typename model>\nclass UKF: public Estimator {\nprotected:\n\tUKF(std::shared_ptr<plugin::SensorPlugin> sensor) :\n\t\t\tbox_model(sensor), state_count(0), alignment(alignment.Identity()) {\n\t}\npublic:\n\n\ttypedef model MODEL_TYPE;     //model type\n\ttypedef typename MODEL_TYPE::template OUTER_T<double> STATE_TYPE;\n\ttypedef typename MODEL_TYPE::template INNER_T<double> SIGMA_TYPE;\n\ttypedef Eigen::Matrix<double, MODEL_TYPE::inner_size, MODEL_TYPE::inner_size> STATE_COV_TYPE;     //cov matrix\n\ttypedef Eigen::Matrix<double, MODEL_TYPE::outer_size, MODEL_TYPE::inner_size * 2 + 1> SIGMA_POINTS_TYPE;     //< sigma points matrix type\n\ttypedef Eigen::Matrix<double, MODEL_TYPE::inner_size, MODEL_TYPE::inner_size * 2 + 1> SIGMA_SIGMA_POINTS_TYPE;     //< occurs when the difference of SIGMA_POINTS with the state is drawn\n\n\tvirtual ~UKF() {\n\t\t//smoothAllEstimates();\n\n\t}\n\n\tSTATE_TYPE boxPlus(const STATE_TYPE & state, const SIGMA_TYPE & delta) {\n\t\treturn box_model.template boxPlus<double>(state, delta);\n\t}\n\n\tSIGMA_TYPE boxMinus(const STATE_TYPE & a, const STATE_TYPE & b) {\n\t\treturn box_model.template boxMinus<double>(a, b);\n\t}\n\n\tSTATE_TYPE stateTransitionFunction(const STATE_TYPE & state, const double time_diff) {\n\t\treturn box_model.template stateTransitionFunction<double>(state, time_diff);\n\t}\n\n\t/**\n\t * Returns the sigma points of the state\n\t *\n\t *\n\t * @param state the state to get the sigma points off\n\t * @param cov the covariance of the state\n\t * @return a eigen matrix with the sigma points\n\t */\n\n\tSIGMA_POINTS_TYPE getSigmaPoints(const STATE_TYPE & state, const STATE_COV_TYPE & cov) {\n\t\tSTATE_COV_TYPE cholesky = cov.llt().matrixL();\n\t\tSIGMA_POINTS_TYPE sigma_points = SIGMA_POINTS_TYPE::Zero();\n\t\tSTATE_COV_TYPE neg_cholesky = STATE_COV_TYPE::Zero() - cholesky;\n\t\tEigen::Matrix<double, MODEL_TYPE::outer_size, MODEL_TYPE::inner_size> negResult, posResult;\n\t\tnegResult = negResult.Zero();\n\t\tposResult = posResult.Zero();\n\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\tposResult.col(i) = boxPlus(state, cholesky.col(i));\n\t\t}\n\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\tnegResult.col(i) = boxPlus(state, neg_cholesky.col(i));\n\t\t}\n\t\tsigma_points << state, posResult, negResult;\n\n\t\treturn sigma_points;\n\t}\n\n\t/**\n\t * Simple wrapper to call getSigmaPoints without arguments\n\t * @return sigma points of state_vector and covariance\n\t */\n\tvirtual SIGMA_POINTS_TYPE getSigmaPoints() {\n\t\treturn getSigmaPoints(state_vector, covariance);\n\t}\n\n\t/**\n\t * Calculates the mean of sigma points\n\t * @param sigma_points  the matrix with all sigma points\n\t * @param epsilon the stopping criteria\n\t * @param max_iterations max iterations of convergence\n\t * @return the mean of sigma points\n\t */\n\tSTATE_TYPE meanOfSigmaPoints(const SIGMA_POINTS_TYPE &sigma_points, double epsilon = 1e-8,\n\t\t\tint max_iterations = 30) {\n\t\tSTATE_TYPE mean = sigma_points.col(0);\n\t\tSTATE_TYPE old_mean = sigma_points.col(0);\n\t\tSIGMA_TYPE diff_sum = SIGMA_TYPE::Zero();\n\t\tint iterations = 0;\n\t\tdo {\n\t\t\titerations++;\n\t\t\told_mean = mean;\n\t\t\tdiff_sum = diff_sum.Zero();\n\t\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\t\tdiff_sum += boxMinus(mean, sigma_points.col(i));\n\t\t\t}\n\t\t\tdiff_sum /= 2. * MODEL_TYPE::inner_size + 1.;\n\t\t\tmean = boxPlus(mean, diff_sum);\n\t\t} while (iterations <= max_iterations && boxMinus(mean, old_mean).norm() > epsilon);\n\t\tif (iterations > max_iterations)\n\t\t\tprintf(\"Warning: stopped due to excess of iterations\");\n\t\treturn mean;\n\t}\n\n\t/**\n\t * Calculates the mean of sigma points\n\t * @param sigma_points  the matrix with all sigma points\n\t * @param epsilon the stopping criteria\n\t * @param max_iterations max iterations of convergence\n\t * @return the mean of sigma points\n\t */\n\ttemplate<int measure_dim, int measure_inner_dim>\n\tEigen::Matrix<double, measure_dim, 1> meanOfSigmaPoints(\n\t\t\tconst Eigen::Matrix<double, measure_dim, MODEL_TYPE::inner_size * 2 + 1> &sigma_points,\n\t\t\tEigen::Matrix<double, measure_dim, 1> (*boxplus_m)(const Eigen::Matrix<double, measure_dim, 1> & state,\n\t\t\t\t\tconst Eigen::Matrix<double, measure_inner_dim, 1> & delta),\n\t\t\tEigen::Matrix<double, measure_inner_dim, 1> (*boxminus_m)(const Eigen::Matrix<double, measure_dim, 1> & a,\n\t\t\t\t\tconst Eigen::Matrix<double, measure_dim, 1> & b), double epsilon = 1e-6, int max_iterations = 30) {\n\n\t\tEigen::Matrix<double, measure_dim, 1> mean = sigma_points.col(0);\n\t\tEigen::Matrix<double, measure_dim, 1> old_mean = sigma_points.col(0);\n\t\tEigen::Matrix<double, measure_inner_dim, 1> diff_sum = Eigen::Matrix<double, measure_inner_dim, 1>::Zero();\n\t\tint iterations = 0;\n\t\tdo {\n\t\t\titerations++;\n\t\t\told_mean = mean;\n\t\t\tdiff_sum = diff_sum.Zero();\n\t\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\t\tdiff_sum += boxminus_m(mean, sigma_points.col(i));\n\t\t\t}\n\t\t\tdiff_sum /= 2. * MODEL_TYPE::inner_size + 1.;\n\t\t\tmean = boxplus_m(mean, diff_sum);\n\t\t} while (iterations <= max_iterations && boxminus_m(mean, old_mean).norm() > epsilon);\n\t\tif (iterations > max_iterations)\n\t\t\tprintf(\"Warning: stopped due to excess of iterations\");\n\t\treturn mean;\n\t}\n\t/**\n\t * Saves all releveant states for smoothing\n\t * @param input the input u\n\t * @param time_diff time since last call\n\t */\n\tvoid saveStatesForSmoothing(double time_diff) {\n\t\tstate_count++;\n\t\tpast_states.push_back(state_vector);\n\t\tpast_states_smoothed.push_back(state_vector);\n\t\tpast_covs.push_back(covariance);\n\t\tpast_timediffs.push_back(time_diff);\n\t}\n\t/**\n\t * Does  dynamic step in EKF\n\t *\n\t * @param input the input u\n\t * @param time_diff time since last call\n\t */\n\tvoid dynamicStep(double time_diff) {\n\t\tSIGMA_POINTS_TYPE sigma_points = getSigmaPoints();\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tsigma_points.col(i) = stateTransitionFunction(sigma_points.col(i), time_diff);\n\t\t}\n\t\tstate_vector = meanOfSigmaPoints(sigma_points);\n\t\t//printf(state_vector);\n\t\t//printf(\" \");\n\t\tSIGMA_SIGMA_POINTS_TYPE result = SIGMA_SIGMA_POINTS_TYPE::Zero();\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tresult.col(i) = boxMinus(state_vector, sigma_points.col(i));\n\t\t}\n\t\tcovariance = 0.5 * (result * result.transpose()) + processNoise(time_diff);\n\t\t//printf(\"dynamic\");\n\t\t//printf(state_vector.block(3, 0, 3, 1).norm());\n\t}\n\t/**\n\t * Does  a  measurement update in UKF\n\t * @param measurement the measurement\n\t * @param time_diff time since last call\n\t * @param measure_function function to map a state to a predicted measurement\n\t * @param noise_function gives the measurement noise with time_diff\n\t * @param boxplus_m boxplus for measurement\n\t * @param boxminus_m boxminus for measurement\n\t * measure dim is the dimension of the measurement vector\n\t */\n\ttemplate<int measure_inner_dim, typename functor, int measure_dim>\n\tvoid measurementStepManifold(const Eigen::Matrix<double, measure_dim, 1> & measurement, double time_diff,\n\t\t\tconst functor & measure_function, const Eigen::Matrix<double, measure_inner_dim, measure_inner_dim> & noise,\n\t\t\tEigen::Matrix<double, measure_dim, 1> (*boxplus_m)(const Eigen::Matrix<double, measure_dim, 1> & state,\n\t\t\t\t\tconst Eigen::Matrix<double, measure_inner_dim, 1> & delta),\n\t\t\tEigen::Matrix<double, measure_inner_dim, 1> (*boxminus_m)(const Eigen::Matrix<double, measure_dim, 1> & a,\n\t\t\t\t\tconst Eigen::Matrix<double, measure_dim, 1> & b), void *prior = NULL) {\n\t\tSIGMA_POINTS_TYPE sigma_points = getSigmaPoints();\n\t\tEigen::Matrix<double, measure_dim, MODEL_TYPE::inner_size * 2 + 1> expected_zs;\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\texpected_zs.col(i) = measure_function(STATE_TYPE(sigma_points.col(i)), alignment, prior);\n\t\t}\n\t\tEigen::Matrix<double, measure_dim, 1> mean_z = meanOfSigmaPoints(expected_zs, boxplus_m, boxminus_m);     //< expected measurement mean\n\t\tEigen::Matrix<double, measure_inner_dim, MODEL_TYPE::inner_size * 2 + 1> diff_z;\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tdiff_z.col(i) = boxminus_m(mean_z, expected_zs.col(i));\n\t\t}\n\t\tEigen::Matrix<double, measure_inner_dim, measure_inner_dim> sigma_z = 0.5 * (diff_z * diff_z.transpose())\n\t\t\t\t+ noise;\n\t\tSIGMA_SIGMA_POINTS_TYPE result = SIGMA_SIGMA_POINTS_TYPE::Zero();\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tresult.col(i) = boxMinus(state_vector, sigma_points.col(i));\n\t\t}\n\t\tEigen::Matrix<double, MODEL_TYPE::inner_size, measure_inner_dim> sigma_xz = 0.5 * (result * diff_z.transpose());\n\t\tEigen::Matrix<double, MODEL_TYPE::inner_size, measure_inner_dim> kalman_gain = sigma_xz * sigma_z.inverse();\n\t\tEigen::Matrix<double, MODEL_TYPE::inner_size, 1> delta = kalman_gain * boxminus_m(mean_z, measurement);\n\t\tSTATE_COV_TYPE sigma_t = covariance - (kalman_gain * sigma_z * kalman_gain.transpose());\n\t\tSIGMA_POINTS_TYPE sigma_points_second = SIGMA_POINTS_TYPE::Zero();\n\t\tSTATE_COV_TYPE cholesky = sigma_t.llt().matrixL();\n\t\tEigen::Matrix<double, MODEL_TYPE::outer_size, MODEL_TYPE::inner_size> negResult, posResult;\n\t\tnegResult = negResult.Zero();\n\t\tposResult = posResult.Zero();\n\t\tSTATE_COV_TYPE neg_cholesky = STATE_COV_TYPE::Zero() - cholesky;\n\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\tposResult.col(i) = boxPlus(state_vector,\n\t\t\t\t\tbox_model.template boxPlusInnerSpace<double>(delta, cholesky.col(i)));\n\t\t}\n\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\tnegResult.col(i) = boxPlus(state_vector,\n\t\t\t\t\tbox_model.template boxPlusInnerSpace<double>(delta, neg_cholesky.col(i)));\n\t\t}\n\t\tsigma_points_second << boxPlus(state_vector, delta), posResult, negResult;\n\n\t\tstate_vector = meanOfSigmaPoints(sigma_points_second);\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tresult.col(i) = boxMinus(state_vector, sigma_points_second.col(i));\n\t\t}\n\t\tcovariance = 0.5 * (result * result.transpose());\n\n\t}\n\t/**\n\t * Does  a  measurement update in UKF\n\t * @param measurement the measurement\n\t * @param time_diff time since last call\n\t * @param measure_function function to map a state to a predicted measurement\n\t * @param noise_function gives the measurement noise with time_diff\n\t * measure dim is the dimension of the measurement vector\n\t */\n\ttemplate<typename functor, int measure_dim>\n\tvoid measurementStep(const Eigen::Matrix<double, measure_dim, 1> & measurement, double time_diff,\n\t\t\tconst functor & measure_function, const Eigen::Matrix<double, measure_dim, measure_dim> & noise,\n\t\t\tvoid * prior = NULL) {\n\n\t\tSIGMA_POINTS_TYPE sigma_points = getSigmaPoints();\n\t\tEigen::Matrix<double, measure_dim, MODEL_TYPE::inner_size * 2 + 1> expected_zs;\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\texpected_zs.col(i) = measure_function(STATE_TYPE(sigma_points.col(i)), alignment, prior);\n\t\t}\n\t\tEigen::Matrix<double, measure_dim, 1> mean_z = expected_zs.rowwise().mean();     //< expected measurement mean\n\t\tEigen::Matrix<double, measure_dim, MODEL_TYPE::inner_size * 2 + 1> diff_z = expected_zs.colwise() - mean_z;\n\t\tEigen::Matrix<double, measure_dim, measure_dim> sigma_z = 0.5 * (diff_z * diff_z.transpose()) + noise;\n\n\t\tSIGMA_SIGMA_POINTS_TYPE result = SIGMA_SIGMA_POINTS_TYPE::Zero();\n\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\tresult.col(i) = boxMinus(state_vector, sigma_points.col(i));\n\t\t}\n\t\tEigen::Matrix<double, MODEL_TYPE::inner_size, measure_dim> sigma_xz = 0.5 * (result * diff_z.transpose());\n\n\t\tEigen::Matrix<double, MODEL_TYPE::inner_size, measure_dim> kalman_gain = sigma_xz * sigma_z.inverse();\n\n\t\tstate_vector = boxPlus(state_vector, kalman_gain * (measurement - mean_z));\n\n\t\tcovariance = covariance - kalman_gain * sigma_xz.transpose();\n\t}\n\t/**\n\t * wrapper to call measurementstep with different arguments\n\t */\n\ttemplate<int measure_dim>\n\tstruct MeasurementWrapper {\n\t\tEigen::Matrix<double, measure_dim, 1> (*function)(const STATE_TYPE &, void *);\n\t\tMeasurementWrapper(Eigen::Matrix<double, measure_dim, 1> (*function)(const STATE_TYPE &, void *)) :\n\t\t\t\tfunction(function) {\n\n\t\t}\n\t\tEigen::Matrix<double, measure_dim, 1> operator()(const STATE_TYPE & state,\n\t\t\t\tconst Eigen::Matrix<double, 4, 4> & alignment, void *prior) const {\n\t\t\treturn function(state, prior);\n\t\t}\n\n\t};\n\ttemplate<int measure_dim>\n\tvoid measurementStep(const Eigen::Matrix<double, measure_dim, 1> & measurement, double time_diff,\n\t\t\tEigen::Matrix<double, measure_dim, 1> (*measure_function)(const STATE_TYPE &, void * prior),\n\t\t\tconst Eigen::Matrix<double, measure_dim, measure_dim> & noise, void * prior = NULL) {\n\t\tmeasurementStep(measurement, time_diff, MeasurementWrapper<measure_dim>(measure_function), noise, prior);\n\t}\n\n\t/**\n\t * Smooth previous estimates with new knowledge\n\t *\n\t * This is taken from:\n\t *\n\t * Unscented Rauch–Tung–Striebel Smoother by Simo S\"arkk\"a\n\t *\n\t * @param k_length the amount of steps to smooth back\n\t * @param k_start the starting index for the smoothing\n\t */\n\tvoid smoothEstimates(unsigned int k_length, unsigned int k_start) {\n\t\tif (k_start > state_count - 1) {\n\t\t\tLOG(ERROR)<<\"Trying to smooth from a non existent state\";\n\t\t\treturn;\n\t\t}\n\n\t\tif (k_length > k_start) {\n\t\t\tLOG(ERROR)<< \"Trying to smooth more states than are before k_start\";\n\t\t\treturn;\n\t\t}\n\t\tfor (unsigned int k = k_start; k > k_start - k_length; k--) {\n\t\t\tSIGMA_POINTS_TYPE sigma_points = getSigmaPoints(past_states_smoothed[k], past_covs[k]);\n\t\t\tSIGMA_POINTS_TYPE sigma_points_plus;\n\t\t\tfor (int i = 0; i < MODEL_TYPE::inner_size * 2 + 1; i++) {\n\t\t\t\tsigma_points_plus.col(i) = stateTransitionFunction(sigma_points.col(i), past_timediffs[k]);\n\t\t\t}\n\n\t\t\tSTATE_TYPE mean = meanOfSigmaPoints(sigma_points_plus);\n\t\t\tSIGMA_SIGMA_POINTS_TYPE result_plus;\n\t\t\tfor (int i = 0; i < MODEL_TYPE::inner_size * 2 + 1; i++) {\n\t\t\t\tresult_plus.col(i) = boxMinus(mean, sigma_points_plus.col(i));\n\t\t\t}\n\n\t\t\tSIGMA_SIGMA_POINTS_TYPE result;\n\t\t\tSTATE_COV_TYPE cov = 0.5*(result_plus * result_plus.transpose())+ processNoise(past_timediffs[k]);\n\t\t\tfor (int i = 0; i < MODEL_TYPE::inner_size * 2 + 1; i++) {\n\t\t\t\tresult.col(i) = boxMinus(past_states_smoothed[k], sigma_points.col(i));\n\t\t\t}\n\t\t\tSTATE_COV_TYPE c_k_plus =0.5* result * result_plus.transpose();\n\t\t\tSTATE_COV_TYPE d_k = c_k_plus * cov.inverse();\n\t\t\t//past_states_smoothed[k] = boxPlus(past_states_smoothed[k],\n\t\t\t//\t\td_k * boxMinus(mean, past_states_smoothed[k + 1]));\n\t\t\t//past_covs[k] = past_covs[k] + d_k * (past_covs[k + 1] - cov) * d_k.transpose();\n\n\t\t\t//from here the second sigma propagation applies\n\t\t\tSIGMA_TYPE delta=d_k * boxMinus(mean, past_states_smoothed[k + 1]);\n\t\t\tSTATE_COV_TYPE pst_cov_k=past_covs[k] + d_k * (past_covs[k + 1] - cov) * d_k.transpose();\n\n\t\t\tSIGMA_POINTS_TYPE sigma_points_second = SIGMA_POINTS_TYPE::Zero();\n\t\t\tSTATE_COV_TYPE cholesky = pst_cov_k.llt().matrixL();\n\t\t\tEigen::Matrix<double, MODEL_TYPE::outer_size, MODEL_TYPE::inner_size> negResult, posResult;\n\t\t\tnegResult = negResult.Zero();\n\t\t\tposResult = posResult.Zero();\n\t\t\tSTATE_COV_TYPE neg_cholesky = STATE_COV_TYPE::Zero() - cholesky;\n\t\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\t\tposResult.col(i) = boxPlus(past_states_smoothed[k],\n\t\t\t\t\t\tbox_model.template boxPlusInnerSpace<double>(delta, cholesky.col(i)));\n\t\t\t}\n\t\t\tfor (int i = MODEL_TYPE::inner_size - 1; i >= 0; --i) {\n\t\t\t\tnegResult.col(i) = boxPlus(past_states_smoothed[k],\n\t\t\t\t\t\tbox_model.template boxPlusInnerSpace<double>(delta, neg_cholesky.col(i)));\n\t\t\t}\n\t\t\tsigma_points_second << boxPlus(past_states_smoothed[k], delta), posResult, negResult;\n\n\t\t\tpast_states_smoothed[k] = meanOfSigmaPoints(sigma_points_second);\n\t\t\tfor (int i = MODEL_TYPE::inner_size * 2; i >= 0; --i) {\n\t\t\t\tresult.col(i) = boxMinus(past_states_smoothed[k], sigma_points_second.col(i));\n\t\t\t}\n\t\t\tpast_covs[k] = 0.5 * (result * result.transpose());\n\t\t}\n\t}\n\t/**\n\t * Perform smoothing from the newest estimate\n\t * @param k_length the amount of estimates to smooth\n\t */\n\tvoid smoothEstimates(unsigned int k_length) {\n\n\t\tsmoothEstimates(k_length, state_count - 2);\n\n\t}\n\t/**\n\t * Perform smoothing from the newest estimate for all estimates\n\t */\n\tvoid smoothAllEstimates() {\n\t\tsmoothEstimates(state_count - 2);\n\t}\n\n\tstatic void smoothCallback(plugin::SensorPlugin * plug, void* estimator, double time) {\n\t\tUKF * esti = static_cast<UKF *>(estimator);\n\t\testi->smoothAllEstimates();\n\t}\n\n\t/**\n\t * Sets the start estimat \\hat(x) (0)\n\t * @param start_state the starting state vector\n\t * @param start_cov  the starting covariance\n\t */\n\tvirtual inline void setStart(const STATE_TYPE & start_state, const STATE_COV_TYPE &start_cov) {\n\t\tstate_vector = start_state;\n\t\tcovariance = start_cov;\n\t}\n\n\t/**\n\t * Gives the dimension of the state\n\t * @return Dimension of the state vector\n\t */\n\tstatic constexpr int getStateDim() {\n\t\treturn MODEL_TYPE::outer_size;\n\t}\n\n\tvirtual inline STATE_COV_TYPE processNoise(const double time_diff) {\n\t\tSTATE_COV_TYPE matrix = box_model.getStateSTD(time_diff).asDiagonal();\n\n\t\t//zavi::printf(matrix);\n\t\treturn matrix;\n\t}\n\n\tinline MODEL_TYPE getBoxModel() {\n\t\treturn box_model;\n\t}\n\tinline STATE_TYPE getStateVector() {\n\t\treturn state_vector;\n\t}\n\tinline STATE_COV_TYPE getCov() {\n\t\treturn covariance;\n\t}\n\n\tstd::vector<STATE_TYPE> & getSmoothedStates() {\n\t\treturn past_states_smoothed;\n\t}\n\n\tvoid setAlignment(const Eigen::Matrix4d & alignment) {\n\t\tthis->alignment=alignment;\n\t}\n\nprotected:\n\tMODEL_TYPE box_model;     // The Model type\n\tSTATE_TYPE state_vector;//< the current estimated state x\n\tSTATE_COV_TYPE covariance;//< the estimated cov(x)\n\tstd::vector<STATE_TYPE> past_states;//< all past states\n\tstd::vector<STATE_TYPE> past_states_smoothed;//< all past states\n\t//std::vector<INPUT_TYPE> past_inputs;//< all past inputs\n\tstd::vector<double> past_timediffs;//< all past time_diffs\n\n\tstd::vector<STATE_COV_TYPE> past_covs;// < all past covariance matrices\n\tunsigned int state_count;//< the current state index\n\tEigen::Matrix<double, 4, 4> alignment;\n};\n\n}\n/* namespace estimator */\n}\n/* namespace zavi */\n\n#endif /* ESTIMATORS_UKF_HPP_ */\n", "meta": {"hexsha": "a8b14ee29b566e047454691d467ffa023c799a1e", "size": 18161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SixdaysCode/Estimators/UKF.hpp", "max_stars_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_stars_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T07:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T07:20:08.000Z", "max_issues_repo_path": "SixdaysCode/Estimators/UKF.hpp", "max_issues_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_issues_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SixdaysCode/Estimators/UKF.hpp", "max_forks_repo_name": "TomLKoller/ZaVI_TrackCycling", "max_forks_repo_head_hexsha": "7c23bc34e6e58c78ec249f6f55d4e70c7e91d315", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-15T07:20:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T07:20:19.000Z", "avg_line_length": 39.4804347826, "max_line_length": 186, "alphanum_fraction": 0.7169208744, "num_tokens": 5046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5579032751455664}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/assertions.h>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <vector>\n#include <algorithm>\n#include <unordered_set>\n#include <boost/program_options.hpp>\n#include <boost/functional/hash.hpp>\n\nnamespace po = boost::program_options;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel  K;\ntypedef K::FT                                                FT;\ntypedef K::Point_2                                           Point;\ntypedef K::Segment_2                                         Segment;\ntypedef CGAL::Alpha_shape_vertex_base_2<K>                   Vb;\ntypedef CGAL::Alpha_shape_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>          Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                Triangulation_2;\nusing Edge = Triangulation_2::Edge;\nusing Vertex = Triangulation_2::Vertex_handle;\ntypedef CGAL::Alpha_shape_2<Triangulation_2>                 Alpha_shape_2;\ntypedef Alpha_shape_2::Alpha_shape_edges_iterator            Alpha_shape_edges_iterator;\n\ntemplate <class OutputIterator>\nvoid alpha_edges( const Alpha_shape_2& A, OutputIterator out)\n{\n  Alpha_shape_edges_iterator it = A.alpha_shape_edges_begin(),\n                             end = A.alpha_shape_edges_end();\n  for( ; it!=end; ++it) {\n    Edge e = *it;\n    auto r0 = A.classify(e.first);\n    auto r = A.classify(e);\n\n    *out++ = A.segment(*it);\n  }\n\n  auto vit = A.alpha_shape_vertices_begin(),\n       vend = A.alpha_shape_vertices_end();\n  for( ; vit!=vend; ++vit) {\n    Vertex v = *vit;\n    auto r = A.classify(v);\n  }\n}\n\ntemplate <class OutputIterator>\nvoid alpha_verts( const Alpha_shape_2& A, OutputIterator out)\n{\n  auto vit = A.alpha_shape_vertices_begin(),\n       vend = A.alpha_shape_vertices_end();\n  for( ; vit!=vend; ++vit) {\n    Vertex v = *vit;\n    *(++out) = v->point();\n  }\n}\n\n\ntemplate <class OutputIterator>\nbool file_input(const std::string& in, OutputIterator out)\n{\n  std::ifstream is(in, std::ios::in);\n  if(is.fail())\n  {\n    std::cerr << \"unable to open file for input\" << std::endl;\n    return false;\n  }\n  int n;\n  is >> n;\n  std::cout << \"Reading \" << n << \" points from file\" << std::endl;\n  CGAL::copy_n(std::istream_iterator<Point>(is), n, out);\n  return true;\n}\n\nbool save_output(const std::string& out,\n                 const std::vector<Segment>& segments,\n                 const std::vector<Point>& verts)\n{\n  std::ofstream os(out, std::ios::out);\n  if(os.fail())\n  {\n    std::cerr << \"unable to open file for output\" << std::endl;\n    return false;\n  }\n\n  os << segments.size() << std::endl;\n  for (const auto& seg: segments) {\n      os << std::fixed << std::setprecision(6) << seg << std::endl;\n  }\n\n  os << verts.size() << std::endl;\n  for (const auto& v: verts) {\n      os << std::fixed << std::setprecision(6) << v << std::endl;\n  }\n\n  return true;\n}\n\nstruct Input {\n    std::string in;\n    std::string out;\n    double alpha;\n};\n\nInput parse_input(int argc, char * argv[]) {\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"in\", po::value<std::string>()->required(), \"input points\")\n        (\"out\", po::value<std::string>()->required(), \"output edges and verts\")\n        (\"alpha\", po::value<double>()->required(), \"alpha\");\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    Input input;\n    input.in = vm[\"in\"].as<std::string>();\n    input.out = vm[\"out\"].as<std::string>();\n    input.alpha = vm[\"alpha\"].as<double>();\n\n    if (input.alpha <= 0)\n        throw std::invalid_argument(\"alpha should be > 0\");\n    return input;\n}\n\nstd::vector<Point> filter_verts(const std::vector<Segment>& segments,\n                                std::vector<Point>&& verts) {\n    struct HashVert {\n        size_t operator()(const Point& p) const {\n            size_t res = 0;\n            boost::hash_combine(res, p.x());\n            boost::hash_combine(res, p.y());\n            return res;\n        }\n    };\n\n    std::unordered_set<Point, HashVert> seg_points;\n    for (const auto& seg: segments) {\n        seg_points.insert(seg.source());\n        seg_points.insert(seg.target());\n    }\n\n    verts.erase(\n        std::remove_if(verts.begin(), verts.end(), [&seg_points](const auto& p) {\n            return seg_points.count(p) > 0;\n        }),\n        verts.end()\n    );\n\n    return std::move(verts);\n}\n\n// Reads a list of points and returns a list of segments\n// corresponding to the Alpha shape.\nint main(int argc, char * argv[])\n{\n  const auto input = parse_input(argc, argv);\n  std::list<Point> points;\n  if(! file_input(input.in, std::back_inserter(points)))\n    return -1;\n  Alpha_shape_2 A(points.begin(), points.end(),\n                  FT(input.alpha),\n                  Alpha_shape_2::GENERAL);\n\n  std::cout<< \" Components for alpha \" << input.alpha << \" \" << A.number_of_solid_components() << std::endl;\n\n  std::vector<Segment> segments;\n  std::vector<Point> res_points;\n  alpha_edges(A, std::back_inserter(segments));\n  alpha_verts(A, std::back_inserter(res_points));\n  auto filtered_points = filter_verts(segments, std::move(res_points));\n  save_output(input.out, segments, filtered_points);\n\n  return 0;\n}\n", "meta": {"hexsha": "6a4ecd3537fe7ad29fce1fe594a8e99d9b3737cc", "size": 5459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/alpha_shapes/main.cpp", "max_stars_repo_name": "xdenisx/ice_drift_pc_ncc", "max_stars_repo_head_hexsha": "f2992329e8509dafcd37596271e80cbf652d14cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T04:03:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T10:36:02.000Z", "max_issues_repo_path": "tools/alpha_shapes/main.cpp", "max_issues_repo_name": "xdenisx/ice_drift_pc_ncc", "max_issues_repo_head_hexsha": "f2992329e8509dafcd37596271e80cbf652d14cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-12T17:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-12T17:29:53.000Z", "max_forks_repo_path": "tools/alpha_shapes/main.cpp", "max_forks_repo_name": "xdenisx/ice_drift_pc_ncc", "max_forks_repo_head_hexsha": "f2992329e8509dafcd37596271e80cbf652d14cb", "max_forks_repo_licenses": ["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.9945054945, "max_line_length": 108, "alphanum_fraction": 0.6182450998, "num_tokens": 1385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5578800320344343}}
{"text": "/*! \\file mesh_generator3D.hpp\n\\brief Set of functions to generate points.\n\\author Elad Steinberg\n*/\n#ifndef MESHGENERATOR3D_HPP\n#define MESHGENERATOR3D_HPP 1\n\n#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif // _MSC_VER\n#include <vector>\n#include <cmath>\n#include \"../3D/GeometryCommon/Voronoi3D.hpp\"\n#include <algorithm>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n/*! \\brief Generates a cartesian mesh\n\\param nx Number of points along the x axis\n\\param ny Number of points along the y axis\n\\param nz Number of points along the z axis\n\\param lower_left Lower left point\n\\param upper_right Upper right point\n\\return Set of three dimensional points\n*/\nvector<Vector3D> CartesianMesh(std::size_t nx, std::size_t ny, std::size_t nz, Vector3D const& lower_left,\n\tVector3D const& upper_right);\n\n/*!\n\\brief Generates a random grid with uniform point density and a constant seed\n\\param PointNum The number of points.\n\\param ll The lower left point of the domain\n\\param ur The upper right point of the domain\n\\return List of three dimensional points\n*/\nvector<Vector3D> RandRectangular(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur,Voronoi3D const* tproc = 0);\n\nvector<Vector3D> RandRectangular(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur, boost::mt19937_64 &gen);\n\nvector<Vector3D> RandSphereR(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur, double Rmin, double Rmax,\n\tVector3D center = Vector3D(),Voronoi3D const* tproc = 0);\n\nvector<Vector3D> RandSphereR2(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur,double Rmin,double Rmax\n\t, Vector3D center = Vector3D(), Voronoi3D const* tproc = 0);\n\nvector<Vector3D> RandSphereR1(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur, double Rmin, double Rmax,\n\tVector3D center = Vector3D(),Voronoi3D const* tproc = 0);\n\nvector<Vector3D> RandSphereRa(std::size_t PointNum, Vector3D const& ll, Vector3D const& ur, double Rmin, double Rmax,double a, Vector3D const& center,\n\tVoronoi3D const* tproc = 0);\n\n#ifdef RICH_MPI\n/*!\n\\brief Generates a random grid with uniform point density and a constant seed\n\\param PointNum The total number of points to be in all cpus combined.\n\\param tproc The tessellation of the processors\n\\return List of three dimensional points\n*/\nvector<Vector3D> RandPointsMPI(Voronoi3D const& tproc, size_t PointNum);\n#endif\n\n#endif //MESHGENERATOR3D_HPP\n\n", "meta": {"hexsha": "2c23acb5653613b49dd41c86ccb4a8e2c7f205b7", "size": 2434, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/misc/mesh_generator3D.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/misc/mesh_generator3D.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/misc/mesh_generator3D.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": 38.03125, "max_line_length": 150, "alphanum_fraction": 0.7781429745, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5578429633417109}}
{"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, float heading, float length) {\n  //! straight line\n  reference_line_.add_point(start_point);\n  geometry::Point2d end_point(bg::get<0>(start_point) + length * cos(heading), bg::get<1>(start_point) + length * sin(heading));\n  reference_line_.add_point(end_point);\n\n  //! calculate overall length\n  length_ = bg::length(reference_line_.obj_);\n  return true;\n}\n\nbool PlanView::add_spiral(geometry::Point2d start_point, float heading, float length, float curvature_start, float curvature_end, float s_inc) {\n  double x = bg::get<0>(start_point), y = bg::get<1>(start_point), 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; s += s_inc) {\n    odrSpiral(s, x_old, y_old, cDot, curvature_start, heading, &x, &y, &t);\n    reference_line_.add_point(geometry::Point2d(x, y));\n  }\n\n  // fill last point if increment does not match\n  double delta_s = fabs(length - s);\n  if (delta_s > 0.0) {\n    odrSpiral(length, x_old, y_old, cDot, curvature_start, heading, &x, &y, &t);\n    reference_line_.add_point(geometry::Point2d(x, y));\n  }\n  \n  length_ = bg::length(reference_line_.obj_);\n  return true;\n}\n\nvoid PlanView::calc_arc_position(const float s, float initial_heading, float curvature, float &dx, float &dy) {\n  initial_heading = fmod(initial_heading, 2 * M_PI);\n  float hdg = initial_heading - M_PI / 2;\n\n  float a = 2 / curvature * sin(s * curvature / 2);\n  float alpha = (M_PI - s * curvature) / 2 - hdg;\n\n  dx = -1 * a * cos(alpha);\n  dy = a * sin(alpha);\n\n  // tangent = initial_heading + s * initial_curvature;\n}\n\nbool PlanView::add_arc(geometry::Point2d start_point, float heading, float length, float curvature, 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; s += s_inc) {\n    calc_arc_position(s, heading, curvature, dx, dy);\n    reference_line_.add_point(geometry::Point2d(x_old + dx, y_old + dy));\n  }\n  \n  // fill last point if increment does not match\n  double delta_s = fabs(length - s);\n  if (delta_s >= 0.0){\n    calc_arc_position(length, heading, curvature, dx, dy);\n    reference_line_.add_point(geometry::Point2d(x_old + dx, y_old + dy));\n  }\n  \n  return true;\n}\n\ngeometry::Line PlanView::create_line(int id, LaneWidth lane_width, float s_inc) {\n  float s_start = lane_width.s_start;\n  float s_end = lane_width.s_end;\n  LaneOffset off = lane_width.off;\n\n  float s = s_start;\n  float scale = 0.0f;\n  geometry::Line tmp_line;\n  geometry::Point2d normal(0.0f, 0.0f);\n  int sign = id > 0 ? -1 : 1;\n\n  // TODO(fortiss): check if sampling does work with relative s, probably not\n  if (off.b != 0.0f || off.c != 0.0f || off.d != 0.0f || (lane_width.s_end - lane_width.s_start) != 1.0) {\n    for (; s < s_end; s += s_inc) {\n      geometry::Point2d point = get_point_at_s(reference_line_, s);\n      normal = get_normal_at_s(reference_line_, s);\n      scale = -sign * polynom(s, off.a, off.b, off.c, off.d);\n      tmp_line.add_point(geometry::Point2d(bg::get<0>(point) + scale * bg::get<0>(normal),\n                                  bg::get<1>(point) + scale * bg::get<1>(normal)));\n    }\n\n    // fill last point if increment does not match\n    double delta_s = fabs(s_end-s);\n    if(delta_s>0.0){\n      geometry::Point2d point = get_point_at_s(reference_line_, s_end);\n      normal = get_normal_at_s(reference_line_, s_end);\n      scale = -sign * polynom(s_end, off.a, off.b, off.c, off.d);\n      tmp_line.add_point(geometry::Point2d(bg::get<0>(point) + scale * bg::get<0>(normal),\n                                  bg::get<1>(point) + scale * bg::get<1>(normal)));\n    }\n  } else {\n      for (uint32_t i = 0; i < reference_line_.obj_.size() - 1; i++) {\n        normal = get_normal_at_s(reference_line_, reference_line_.s_[i]);\n        scale = -sign * polynom(s, off.a, off.b, off.c, off.d);\n        tmp_line.add_point(geometry::Point2d(bg::get<0>(reference_line_.obj_[i]) + scale * bg::get<0>(normal),\n                                  bg::get<1>(reference_line_.obj_[i]) + scale * bg::get<1>(normal)));\n        s += geometry::distance(reference_line_.obj_[i + 1], reference_line_.obj_[i]);\n      }\n      // add last point\n      normal = get_normal_at_s(reference_line_, reference_line_.s_[reference_line_.obj_.size() - 1]);\n      int size = reference_line_.obj_.size() - 1;\n      scale = -sign * polynom(length_, off.a, off.b, off.c, off.d);\n      tmp_line.add_point(geometry::Point2d(bg::get<0>(reference_line_.obj_[size]) + scale * bg::get<0>(normal),\n                                bg::get<1>(reference_line_.obj_[size]) + scale * bg::get<1>(normal)));\n  }\n\n\n  return tmp_line;\n}\n\n//! TODO: this function needs to resive a vector of Struct {s_start, s_end, off}\nLanePtr PlanView::create_lane(LanePosition lane_position, LaneWidths lane_widths, float s_inc) {\n  std::shared_ptr<Lane> ret_lane(new Lane(lane_position));\n  if (lane_widths.size() > 1) {\n    assert(\"Not supported\");\n  }\n  for (LaneWidth lane_width : lane_widths) {\n    geometry::Line tmp_line = create_line(lane_position, lane_width, s_inc);\n    ret_lane->set_line(tmp_line);\n  }\n\n  // ret_lane->ComputeCenterLine();\n  return ret_lane;\n}\n\n}  // namespace opendrive\n}  // namespace world\n}  // namespace modules\n", "meta": {"hexsha": "8d4aea369910a916b8a5d237174cc68a61c43ed8", "size": 6017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/world/opendrive/plan_view.cpp", "max_stars_repo_name": "grzPat/bark", "max_stars_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/world/opendrive/plan_view.cpp", "max_issues_repo_name": "grzPat/bark", "max_issues_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/world/opendrive/plan_view.cpp", "max_forks_repo_name": "grzPat/bark", "max_forks_repo_head_hexsha": "807092815c81eeb23defff473449a535a9c42f8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8193548387, "max_line_length": 144, "alphanum_fraction": 0.6632873525, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.5577482113769945}}
{"text": "#include <iostream>\n#include <unistd.h>\n#include <Eigen/Dense>\n#include \"OrthonormalHermite.h\"\n#include \"NelderMead.h\"\n#include \"VariableProjection.h\"\n\nusing namespace std;\n\nint main()\n{\n    APPRSDK::VariableProjection<double> approximator;\n    APPRSDK::OrthonormalHermite<double> hermiteSys(100, 10);\n\n    Eigen::RowVectorXd inputParameters;\n    inputParameters.resize(2);\n    inputParameters(0) = 0.7;\n    inputParameters(1) = 50;\n\n    Eigen::RowVectorXd lb;\n    lb.resize(2);\n    lb(0) = 0.01;\n    lb(1) = -1000;\n    \n    Eigen::RowVectorXd ub;\n    ub.resize(2);\n    ub(0) = 1000;\n    ub(1) = 1000;\n\n    APPRSDK::AvailableOptimizers optId = APPRSDK::AvailableOptimizers::NM;\n\n    approximator.SetNonLinParams(inputParameters);\n    approximator.SetMaxErrorForOptimisation(0.01);\n    approximator.SetMaxIterationForOptimisation(100);\n    approximator.SetFunctionSystem(&hermiteSys);\n    approximator.SelectOptimiser(optId, true);\n\tapproximator.SetBoundaries(lb, ub);\n    approximator.SetSignal(hermiteSys.GetFunctionSystem().col(4).transpose());\n\n    approximator.Varpro();\n\t\n\tcout<<\"Signal: \"<<approximator.GetSignal().transpose()<<endl;\n\tcout<<\"Approximaton: \"<<approximator.GetApproximation().transpose()<<endl;\n\tcout<<\"Coefficients: \"<<approximator.GetLinearParameters().transpose()<<endl;\n\tcout<<\"Dilatation & Translation: \"<<approximator.GetNonLinearParameters()<<endl;\n    cout<<\"Iterations: \"<<approximator.GetIterations()<<endl;\n    cout<<\"Final error: \"<<approximator.GetError()<<endl;\n\n    return 0;\n}", "meta": {"hexsha": "7ba1e9fd727cf8aba792f59f2f6baf58f3827b43", "size": 1513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/approxTestWithHermite.cpp", "max_stars_repo_name": "tamasdzs/APPRSDK", "max_stars_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/approxTestWithHermite.cpp", "max_issues_repo_name": "tamasdzs/APPRSDK", "max_issues_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/approxTestWithHermite.cpp", "max_forks_repo_name": "tamasdzs/APPRSDK", "max_forks_repo_head_hexsha": "7a1f1c2a2f6994791bab760d01270eca62a5a946", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.26, "max_line_length": 81, "alphanum_fraction": 0.7144745539, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5577358312413576}}
{"text": "/* This file is part of PyMesh. Copyright (c) 2017 by Qingnan Zhou */\n#include \"VoxelDihedralAngleAttribute.h\"\n\n#include <cmath>\n#include <Eigen/Core>\n\n#include <Mesh.h>\n#include <Core/Exception.h>\n\nusing namespace PyMesh;\n\nnamespace VoxelDihedralAngleAttributeHelper {\n    Float angle(const Eigen::Ref<Vector3F>& n1,\n            const Eigen::Ref<Vector3F>& n2) {\n        return atan2(n1.cross(n2).norm(), n1.dot(n2));\n    }\n\n    Vector3F compute_normal(\n            const Vector3F& v1,\n            const Vector3F& v2,\n            const Vector3F& v3) {\n        return (v2 - v1).cross(v3 - v1);\n    }\n}\n\nusing namespace VoxelDihedralAngleAttributeHelper;\n\nvoid VoxelDihedralAngleAttribute::compute_from_mesh(Mesh& mesh) {\n    const size_t dim = mesh.get_dim();\n    const size_t num_voxels = mesh.get_num_voxels();\n    const size_t vertex_per_voxel = mesh.get_vertex_per_voxel();\n    if (dim != 3) {\n        throw RuntimeError(\"Voxel dihedral anlge computation is for 3D only.\");\n    }\n    if (num_voxels > 0 && vertex_per_voxel != 4) {\n        throw NotImplementedError(\n                \"Voxel dihedral angle computation only support tet for now.\");\n    }\n\n    const auto& vertices = mesh.get_vertices();\n    const auto& voxels = mesh.get_voxels();\n    VectorF& dihedral_angles = m_values;\n    dihedral_angles.resize(num_voxels * 6);\n\n    for (size_t i=0; i<num_voxels; i++) {\n        Vector4I v = voxels.segment<4>(i*4);\n        Vector3F v0 = vertices.segment<3>(v[0]*3);\n        Vector3F v1 = vertices.segment<3>(v[1]*3);\n        Vector3F v2 = vertices.segment<3>(v[2]*3);\n        Vector3F v3 = vertices.segment<3>(v[3]*3);\n\n        Vector3F n0 = compute_normal(v1, v2, v3);\n        Vector3F n1 = compute_normal(v0, v3, v2);\n        Vector3F n2 = compute_normal(v0, v1, v3);\n        Vector3F n3 = compute_normal(v0, v2, v1);\n\n        dihedral_angles[i*6  ] = M_PI - angle(n2, n3);\n        dihedral_angles[i*6+1] = M_PI - angle(n0, n3);\n        dihedral_angles[i*6+2] = M_PI - angle(n1, n3);\n        dihedral_angles[i*6+3] = M_PI - angle(n1, n2);\n        dihedral_angles[i*6+4] = M_PI - angle(n0, n1);\n        dihedral_angles[i*6+5] = M_PI - angle(n0, n2);\n    }\n}\n\n", "meta": {"hexsha": "f1f2c0e3de40edb9ca2a71b56fc798a46d04dec1", "size": 2166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dependencies/PyMesh/src/Attributes/VoxelDihedralAngleAttribute.cpp", "max_stars_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_stars_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-04T19:52:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T09:04:00.000Z", "max_issues_repo_path": "dependencies/PyMesh/src/Attributes/VoxelDihedralAngleAttribute.cpp", "max_issues_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_issues_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dependencies/PyMesh/src/Attributes/VoxelDihedralAngleAttribute.cpp", "max_forks_repo_name": "aprieels/3D-watermarking-spectral-decomposition", "max_forks_repo_head_hexsha": "dcab78857d0bb201563014e58900917545ed4673", "max_forks_repo_licenses": ["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.8181818182, "max_line_length": 79, "alphanum_fraction": 0.6265004617, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.5577358312413576}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/make_connected.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <vector> \n#include <fstream>\n#include <iostream> \nusing namespace std;\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int>> Graph; \ntypedef vector<vector<graph_traits<Graph>::edge_descriptor>>                                                embedding_storage_t;\ntypedef iterator_property_map<embedding_storage_t::iterator, property_map<Graph, vertex_index_t>::type>     embedding_t; \n\nstruct face_counter : planar_face_traversal_visitor\n{\n        face_counter() : count(0) {}\n        void begin_face() { ++count; }\n        uint count;\n};\n\nstruct coord_t\n{\n        size_t x, y;\n};\n\nvoid make_max_planar(Graph& g)\n{\n        auto 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) put(e_index, *ei, edge_count++);\n\n        typedef vector<graph_traits<Graph>::edge_descriptor> vec_t;\n        vector<vec_t> embedding(num_vertices(g));\n        boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = &embedding[0]);\n\n        make_biconnected_planar(g, &embedding[0]);\n\n        edge_count = 0;\n        for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) put(e_index, *ei, edge_count++);\n\n        boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = &embedding[0]);\n\n        make_maximal_planar(g, &embedding[0]);\n\n        edge_count = 0;\n        for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) put(e_index, *ei, edge_count++);\n\n        boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = &embedding[0]);\n\n        face_counter count_visitor;\n        planar_face_traversal(g, &embedding[0], count_visitor);\n}\n\nint main(int argc, char** argv)\n{\n        if( argc < 2 ){\n                cerr << \"Usage: straightline [filename]\\n\";\n                return 1;\n        }\n\n        string fname(argv[1]);\n        ifstream f(fname);\n        if( !f ){\n                cerr << \"file \" << fname << \" not found!\\n\";\n                return 1;\n        } \n\n        string str;\n        vector<pair<uint, uint>> edges;\n        uint n = 0;\n        while( getline(f, str) ){\n                uint   colon = str.find(\",\"); \n                string stra  = str.substr(0, colon); trim(stra);\n                string strb  = str.substr(colon+1 ); trim(strb); \n                uint   a     = lexical_cast<uint>(stra);\n                uint   b     = lexical_cast<uint>(strb);\n                n = max(max(n, a), b);\n                edges.push_back(make_pair(a, b));\n        }\n        \n        Graph g(n); \n        for( auto& e : edges ) add_edge(e.first, e.second, g);\n        make_max_planar(g);\n\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, boyer_myrvold_params::embedding = embedding); \n\n        vector<graph_traits<Graph>::vertex_descriptor> ordering;\n        planar_canonical_ordering(g, embedding, back_inserter(ordering));\n\n        typedef vector<coord_t> \t\t\t\t\t\t\t\t\t\t\t      straight_line_drawing_storage_t;\n        typedef iterator_property_map < straight_line_drawing_storage_t::iterator, property_map<Graph, vertex_index_t>::type> straight_line_drawing_t;\n\n        straight_line_drawing_storage_t straight_line_drawing_storage (num_vertices(g));\n        straight_line_drawing_t straight_line_drawing (straight_line_drawing_storage.begin(), get(vertex_index,g)); \n\n        chrobak_payne_straight_line_drawing(g, embedding, ordering.begin(), ordering.end(), straight_line_drawing); \n\n        graph_traits<Graph>::vertex_iterator vi, vi_end;\n        cout << \"graph G {\\n\";\n        for( tie(vi,vi_end) = vertices(g); vi != vi_end; ++vi ){\n                coord_t coord(get(straight_line_drawing,*vi));\n                cout << *vi << \"[pos=\\\"\" << coord.x << ',' << coord.y << \"!\\\"];\\n\";\n        }\n        for( auto& e : edges ) cout << e.first << \"--\" << e.second << \" ;\\n\";\n        cout << \"}\\n\";\n}", "meta": {"hexsha": "521eff18fd9e17cfdcbd851214a444bb55f3a1e1", "size": 4855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "straightline.cpp", "max_stars_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_stars_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-05-20T11:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T15:50:33.000Z", "max_issues_repo_path": "straightline.cpp", "max_issues_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_issues_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-12-02T06:35:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T19:58:56.000Z", "max_forks_repo_path": "straightline.cpp", "max_forks_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_forks_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-04-19T16:37:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:29:33.000Z", "avg_line_length": 40.1239669421, "max_line_length": 150, "alphanum_fraction": 0.6401647786, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5577358166644331}}
{"text": "\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main()\ntry {\n    using namespace mtl;\n    \n    dense2D<int> A(2, 2), B(2, 2), C(4, 4);\n    \n    for (size_t r= 0; r < 2; ++r)\n        for (size_t c= 0; c < 2; ++c) {\n            A[r][c]= (r+1) * 10 + c+1;\n            B[r][c]= (r+1) * 1000 + (c+1) * 100;\n        }\n        \n    C= kron(A, B);\n    std::cout << \"kron(A, B) is\\n\" << C;\n    \n    MTL_THROW_IF(C[0][0] != 12100, mtl::runtime_error(\"Wrong value in C[0][0]\"));\n    MTL_THROW_IF(C[3][3] != 48400, mtl::runtime_error(\"Wrong value in C[3][3]\"));\n\n    return EXIT_SUCCESS;\n}\ncatch (const mtl::runtime_error& e) {\n    std::cerr << \"Caught an MTL runtime error: \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n}", "meta": {"hexsha": "b4061dc0052848bf463fe2e6c697984f3acf1dc8", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/kronecker_product.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/blas/kronecker_product.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/blas/kronecker_product.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 26.3703703704, "max_line_length": 81, "alphanum_fraction": 0.5, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.5574834129897721}}
{"text": "//when you need a function, just find that function and include a header file\n//also need to get eigen in your cmake file\n//getting th, v values straight from IMU\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n\n//Global Variables\nusing Eigen::Vector3f;\nVector3f g(0,0,-9.81); //gravity\n\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  \nint main()\n{\n\n//Propagation\n\n//Execute each time the IMU is sampled\nVector3f am; //accelerometer measurement (get from IMU)\nVector3f wm; //gyroscope measurement (get from IMU)\nfloat dt; //(get from ROS) \n\n//Build Omega(w)\nwmx = crossProductEquivalent(wm);\nMatrix 4f Omega;\nOmega << -wmx(0,0), -wmx(0,1), -wmx(0,2), wm(0),\n\t -wmx(1,0), -wmx(1,1), -wmx(1,2), wm(1),\n         -wmx(2,0), -wmx(2,1), -wmx(2,2), wm(2),\n         -wm(0), -wm(1), -wm(2), 0;\n\n//Measurements at time l-1\nVector3f amOld; //accelerometer measurement from last time\nVector3f wmOld; //gyroscope measurement from last time \n\n\n//Propagate state estimate\n\n// Constants\nusing Eigen::Quaternionf;\nusing Eigen::Vector3f; \nusing Eigen::Matrix3f\nMatrix3f I3 = Matrix3f::Identity(3,3); \nMatrix3f O3 = Matrix3f::Zero();\nfloat g = 9.81; \n\n//Propagate quaternion\nusing Eigen::Quaternionf;\nusing Eigen::Vector3f; \nusing Eigen::Matrix3f\nQuaternionf qHat;\nMatrix3f RHat = qHat.toRotationMatrix();\nMatrix3f RHatProp = (I - dt * wmx) * RHat; \nQuaternionf qHatExp = qExponential(wmOld, dt);\nQuaternionf qHatProp = qMultiply(qHatExp, qHatExp);\n\n//Propagate p, the position\nVector3f pHatProp = pHat + vHat*dt + RHat*RHatProp*(amOld - baHat)*dt^2 + 0.5*g*(dt^2)\n\n//Propagate v, the velocity\nVector3f vHatProp = vHat + RHat*RHatProp*(amOld - baHat)*dt + g*dt; \n\n//Propagate bg and ba, the gyroscope and accelerometer biases\nVector3f bgHatProp = bgHat;\nVector3f baHatProp = baHat;\n\n//Calculate IMU error state transition matrix\nusing Eigen::MatrixXf;\nphipq = -crossProductEquivalent(pHatProp - pHat - vHat*dt - 0.5*g*dt^2);\nphivq = -crossProductEquivalent(vHatProp - vHat - g*dt);\nphigbg = RHat.transpose() * RHatProp * dt; \nphipbg = crossProductEquivalent(vHat - g*dt) * RHat.transpose() * RHatProp * dt;\nphipa = RHat.transpose() * RHatProp * dt^2; \nphivbg = crossProductEquivalent(vHat - g*dt) * RHat.transpose() * RHatProp * dt; \nphiva = RHat.transpose() * RHatProp * dt; \nMatrixXf PhiProp(15, 15);\nPhiProp << I3,    O3,      O3, phiqbg,    O3, \n\t         phipq, I3, (dt*I3), phipbg, phipa, \n           phivq, O3,      I3, phivbg, phiva, \n\t         O3,    O3,      O3,     I3,    O3, \n           O3,    O3,      O3,     O3,    I3;\n}\n\n\n\n", "meta": {"hexsha": "dbf86a88a2a3ffbc27d3562de4f5a89a192a4a6c", "size": 3802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "msckf3d.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": "msckf3d.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": "msckf3d.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.162962963, "max_line_length": 86, "alphanum_fraction": 0.6536033666, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.5574628185891151}}
{"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 <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <typeinfo>\n\ntemplate <typename At, typename Ut>\nvoid dense_ic_0(const At& As, const Ut& Us)\n{\n    mtl::dense2D<double> U(upper(As));\n     \n    const std::size_t n= num_rows(U);\n\n    for (std::size_t k= 0; k < n; k++) {\n\tdouble dia= U[k][k]= sqrt(U[k][k]);\n\tfor (std::size_t i = k + 1; i < n; i++) {\n\t    double d= U[k][i] /= dia;\n\t    for (std::size_t j = k + 1; j <= i; j++)\n\t\tif (U[j][i] != 0.0)\n\t\t    U[j][i] -= d * U[k][j];\n\t}\n    } \n\n    std::cout << \"Factorizing A = \\n\" << As << \"-> U = \\n\" << with_format(U, 6, 2)\n\t      << \"trans(U) * U = \\n\" << with_format(mtl::dense2D<double>(trans(U) * U), 6, 2);\n\n    if (std::abs(U[2][3] - Us[2][3]) > 0.001) throw \"Wrong value in L for sparse IC(0) factorization\";\n\n    if (std::abs(U[3][3] - 1. / Us[3][3]) > 0.001) throw \"Wrong value in U for sparse IC(0) factorization\";\n}\n\n\ntemplate <typename Solver>\nvoid test(const Solver&)\n{\n    typedef typename mtl::ashape::ashape<Solver>::type shape;\n    std::cout << \"type is \" << typeid(Solver).name() << '\\n';\n    std::cout << \"ashape is \" << typeid(shape).name() << '\\n';\n    std::cout << \"type is \" << (mtl::traits::is_scalar<Solver>::value ? \"\" : \"not \") << \"scalar\\n\";\n    std::cout << \"type is \" << (mtl::traits::backward_index_evaluatable<Solver>::value ? \"\" : \"not \") << \"back-eval\\n\";\n}\n\nint main()\n{\n    // For a more realistic example set sz to 1000 or larger\n    const int size = 3, N = size * size; \n\n    typedef mtl::compressed2D<double>  matrix_type;\n    mtl::compressed2D<double>          A(N, N), dia(N, N);\n    laplacian_setup(A, size, size);\n    // dia= 1.0; A+= dia;\n    \n   \n    itl::pc::ic_0<matrix_type, float>  P(A);\n    mtl::dense_vector<double>          x(N, 1.0), b(N);\n    \n    if(size > 1 && size < 4)\n\tdense_ic_0(A, P.get_U());\n\n    b = A * x;\n    x= 0;\n\n    itl::cyclic_iteration<double> iter(b, N, 1.e-6, 0.0, 1);\n    cg(A, x, b, P, iter);\n    \n    // test(mtl::lazy(b)= solve(P, x));\n\n    return 0;\n}\n", "meta": {"hexsha": "1c6944131fe33ed85aa8253232b325ba9c85ce83", "size": 2455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/ic_0_cg_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/ic_0_cg_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/ic_0_cg_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.6875, "max_line_length": 119, "alphanum_fraction": 0.5706720978, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5574628175865215}}
{"text": "#include <Eigen/Dense>\n#include \"Geometry.hh\"\n#include \"PeriodicTable.hh\"\n#include \"XYZMatrix.hh\"\n#include \"ZMatrix.hh\"\n#include \"io/manipulators.hh\"\n#include \"exceptions.hh\"\n\ndouble Geometry::nuclearRepulsion() const\n{\n\tdouble sum = 0;\n\n\tfor (int j = 1; j < size(); ++j)\n\t{\n\t\tsum += (charges().head(j).transpose().array()\n\t\t\t/ (positions().block(0, 0, 3, j).colwise() - position(j))\n\t\t\t\t.colwise().norm().array())\n\t\t\t.sum();\n\t}\n\n\treturn sum;\n}\n\nvoid Geometry::setAtom(int idx, const std::string& symbol,\n\tdouble x, double y, double z)\n{\n\tcheckIndex(idx);\n\n\tconst Element& elem = PeriodicTable::singleton().findBySymbol(symbol);\n\n\t_positions.col(idx) << x, y, z;\n\t_masses(idx) = elem.mass();\n\t_charges(idx) = elem.number();\n\t_symbols[idx] = symbol;\n}\n\nstd::ostream& Geometry::print(std::ostream& os) const\n{\n\tos << \"Geometry (\\n\" << indent;\n\tfor (int i = 0; i < size(); i++)\n\t\tos << _charges(i) << \"\\t\" << _masses(i) << \"\\t\"\n\t\t\t<< symbol(i) << \"\\t\"\n\t\t\t<< position(i).transpose() << \"\\n\";\n\tos << dedent << \")\";\n\treturn os;\n}\n\nJobIStream& Geometry::scan(JobIStream& is)\n{\n\tis >> getline;\n\tif (is.eof())\n\t\tthrow UnexpectedEOF();\n\n\tstd::string elem;\n\tdouble x, y, z;\n\tis >> element(elem, false) >> x >> y >> z;\n\tif (!is.fail())\n\t{\n\t\tis.ungetLastLine();\n\n\t\tXYZMatrix mat;\n\t\tis >> mat;\n\t\tmat.fillGeometry(this);\n\t}\n\telse\n\t{\n\t\tis.ungetLastLine();\n\n\t\tZMatrix mat;\n\t\tis >> mat;\n\t\tmat.fillGeometry(this);\n\t}\n\n\treturn is;\n}\n\nvoid Geometry::toPrincipalAxes()\n{\n\t// Move center of mass to origin\n\tEigen::Vector3d cm = (positions() * masses()) / masses().sum();\n\t_positions.colwise() -= cm;\n\n\t// Compute principal axes\n\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver(inertia());\n\tconst Eigen::Matrix3d& axes = solver.eigenvectors();\n\tEigen::Vector3d c = axes.col(0), b = axes.col(1), a = axes.col(0);\n\tif (a.cross(b).dot(c) < 0)\n\t\t// axis system is left-handed, flip one\n\t\ta = -a;\n\n\t// First two angles put the z axis in place\n\tdouble theta = std::acos(c.z());\n\tdouble psi = theta > 2 * std::numeric_limits<double>::epsilon()\n\t\t? std::atan2(c.y(), c.x()) : 0;\n\t\n\t// Rotate the a axis into the xy-plane\n\tEigen::Matrix3d R = (Eigen::AngleAxisd(-theta, Eigen::Vector3d::UnitY())\n\t\t* Eigen::AngleAxisd(-psi, Eigen::Vector3d::UnitZ()))\n\t\t.toRotationMatrix();\n\ta = R * a;\n\t\n\t// Last angle aligns a axis with x (and b with y)\n\tdouble phi = std::atan2(a.y(), a.x());\n\tR = Eigen::AngleAxisd(-phi, Eigen::Vector3d::UnitZ()) * R;\n\t_positions = R * positions();\n}\n\nEigen::Matrix3d Geometry::inertia() const\n{\n\tEigen::Matrix3d I;\n        for (int j = 0; j < 3; j++)\n        {\n                for (int i = 0; i <= j; i++)\n                {\n\t\t\tI(j,i) = I(i,j) =\n\t\t\t\t-_positions.row(i).cwiseProduct(_positions.row(j))\n\t\t\t\t\t.dot(masses());\n\t\t}\n        }\n        \n        double trace = I.trace();\n        for (int i = 0; i < 3; i++)\n\t\tI(i,i) += trace;\n\t\n\treturn I;\n}", "meta": {"hexsha": "412671c360e86320585aa394cc2fb972b74de633", "size": 2842, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Geometry.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": "Geometry.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": "Geometry.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": 22.5555555556, "max_line_length": 73, "alphanum_fraction": 0.5946516538, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.5574628124071764}}
{"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// Written by Cornelius Steinhardt\n\n#include <cmath>\n#include <string>\n\n// #include <boost/test/minimal.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n\n\n\ntemplate <typename Matrix>\nvoid test1(Matrix& m, double tau)\n{\n  mtl::mat::inserter<Matrix> ins(m);\n  size_t nrows=num_rows(m);\n  double val;\n  for (size_t r=0;r<nrows;++r)\n  {\n    for (size_t c=0;c<nrows;++c)\n    {\n      if(r==c)\n        ins(r,c) << 1.;\n      else\n      {\n        val=2.*(static_cast<double>(rand())/RAND_MAX - 0.5);\n        if (val<tau)\n          ins(r,c) << val;\n      }\n    }\n  }\n}\n\ntemplate <typename Matrix, typename Vector, typename Left, typename Right>\nvoid test(char const* name, char const* comment, Matrix const& A, Vector& x, Vector const& b, Left const& L, Right const& R, \n\t  unsigned restart, bool check_convergence= true)\n{\n    const int Niter = 100;\n    \n    std::cout << name << comment << \"\\n\";\n    x= 2.0, 3., 4., 8;\n\n    itl::cyclic_iteration<double> iter(b, Niter, 1.e-8, 0.0, 10);\n    gmres(A, x, b, L, R, iter, restart);\n    std::cout << \"x= \" << x << \" \\n\" ;\n    Vector r(b - A*x);\n    if (false && check_convergence && two_norm(r) > 0.00001) \n\tthrow std::string(name) + std::string(\" doesn't converge!\");\n}\n\n\nint main(int, char**)\n{\n    const int N = 2;\n    typedef mtl::compressed2D<double> matrix_type;\n    matrix_type                   A(N*N, N*N);\n    laplacian_setup(A, N, N);\n\n    mtl::dense_vector<double> b(N*N, 1), x(N*N,1), r(N*N);\n \n    itl::pc::identity<matrix_type>         Ident(A);\n    itl::pc::ic_0<matrix_type>             ic(A);\n    itl::pc::ilu_0<matrix_type>            ilu(A);\n    itl::pc::diagonal<matrix_type>         diag(A);\n\n    std::cout << \"A has \" << A.nnz() << \" non-zero entries\" << std::endl;\n    std::cout << \"A =\\n\" << A << \" \\n\";\n\n    test(\"Non-preconditioned GMRES(1)\", \"\\nWon't convergence (for large examples,without restarts)!\",\n\t A, x, b, Ident, Ident, 1, false);\n    test(\"Non-preconditioned GMRES(4)\", \"\", A, x, b, Ident, Ident, 4);\n    test(\"Left ILU(0) GMRES(4)\", \"\", A, x, b, ilu, Ident, 4);\n    test(\"Left IC(0) GMRES(4)\", \"\", A, x, b, ic, Ident, 4);\n    test(\"Left diag GMRES(4)\", \"\", A, x, b, diag, Ident, 4);\n\n    test(\"Right ILU(0) GMRES(4)\", \"\", A, x, b, Ident, ilu, 4);\n    test(\"Right IC(0) GMRES(4)\", \"\", A, x, b, Ident, ic, 4);\n    test(\"Right diag GMRES(4)\", \"\", A, x, b, Ident, diag, 4);\n\n    test(\"Left ILU(0) Right ILU(0) GMRES(4)\", \"\", A, x, b, ilu, ilu, 4);\n    test(\"Left ILU(0) Right IC(0) GMRES(4)\", \"\", A, x, b, ilu, ic, 4);\n    test(\"Left ILU(0) Right diag GMRES(4)\", \"\", A, x, b, ilu, diag, 4);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "7329df8b5c1290a9916e63be03b569769cee371b", "size": 3052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/gmres_preconditioned_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/gmres_preconditioned_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/gmres_preconditioned_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.52, "max_line_length": 125, "alphanum_fraction": 0.5756880734, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.5574374116871859}}
{"text": "\n// inverting symmetric/hermitian positive definite\n// factor (potrf()) and invert (potri())\n\n// #define BOOST_UBLAS_STRICT_HERMITIAN\n// .. doesn't work (yet?)  \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/potri.hpp>\n#include <boost/numeric/bindings/lapack/computational/potrf.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 blas = boost::numeric::bindings::blas;\nnamespace bindings = boost::numeric::bindings;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \n\ntypedef std::complex<real_t> cmplx_t; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n#else\ntypedef ublas::matrix<real_t, ublas::row_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> cm_t;\n#endif\n\n#ifndef F_UPPER\ntypedef ublas::symmetric_adaptor<m_t, ublas::lower> symm_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> herm_t; \n#else\ntypedef ublas::symmetric_adaptor<m_t, ublas::upper> symm_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> herm_t; \n#endif \n\nint main() {\n\n  cout << endl; \n\n  cout << \"real symmetric\\n\" << endl; \n\n  size_t n = 3; \n  m_t a (n, n);    // matrix (storage)\n  symm_t sa (a);   // symmetric adaptor \n\n#ifdef F_UPPER\n  init_symm (sa, 'u'); \n#else\n  init_symm (sa, 'l'); \n#endif\n  // ifdef F_UPPER \n  //        [5 4 3 2 1]\n  //        [0 5 4 3 2]\n  //    a = [0 0 5 4 3]\n  //        [0 0 0 5 4]\n  //        [0 0 0 0 n]\n  // else \n  //        [5 0 0 0 0]\n  //        [4 5 0 0 0]\n  //    a = [3 4 5 0 0]\n  //        [2 3 4 5 0]\n  //        [1 2 3 4 5]\n  print_m (sa, \"A\"); \n  cout << endl; \n\n  m_t a2 (sa);   // full symmetric copy of sa:\n                 // .. sa is `lost' after potrf(); \n                 // .. only one parameter of symm() is symmetric matrix\n\n  int ierr = lapack::potrf (sa); \n  if (!ierr) {\n    lapack::potri (sa); \n    // ri should be (almost) identity matrix: \n    m_t ri (n, n); \n    blas::symm ( bindings::tag::right(), 1.0, sa, a2, 0.0, ri); \n    print_m (ri, \"I = A * A^(-1)\"); \n    cout << endl; \n    blas::symm ( bindings::tag::left(), 1.0, sa, a2, 0.0, ri); \n    print_m (ri, \"I = A^(-1) * A\"); \n    cout << endl; \n  }\n\n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian (almost ;o)\\n\" << endl; \n\n  // hermitian \n  cm_t ca (3, 3); \n  herm_t ha (ca); \n\n#ifndef F_UPPER\n  ha (0, 0) = cmplx_t (3, 0);\n  ha (1, 0) = cmplx_t (2, 0);\n  ha (1, 1) = cmplx_t (3, 0);\n  ha (2, 0) = cmplx_t (1, 0);\n  ha (2, 1) = cmplx_t (2, 0);\n  ha (2, 2) = cmplx_t (3, 0);\n#else\n  ha (0, 0) = cmplx_t (3, 0);\n  ha (0, 1) = cmplx_t (2, 0);\n  ha (0, 2) = cmplx_t (1, 0);\n  ha (1, 1) = cmplx_t (3, 0);\n  ha (1, 2) = cmplx_t (2, 0);\n  ha (2, 2) = cmplx_t (3, 0);\n#endif \n\n  print_m (ha, \"A\"); \n  cout << endl; \n\n  cm_t ca2 (ha);  // full hermitian \n  \n  ierr = lapack::potri (ha);   // potrf()\n  if (ierr == 0) {\n    lapack::potri (ha);        // potri()\n    cm_t ic (3, 3); \n    blas::hemm ( bindings::tag::right(), 1.0, ha, ca2, 0.0, ic); \n    print_m (ic, \"I = A * A^(-1)\"); \n    cout << endl; \n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl; \n\n\n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n#ifndef F_UPPER\n  ha (0, 0) = cmplx_t (25, 0);\n  ha (1, 0) = cmplx_t (-5, 5);\n  ha (1, 1) = cmplx_t (51, 0);\n  ha (2, 0) = cmplx_t (10, -5);\n  ha (2, 1) = cmplx_t (4, 6);\n  ha (2, 2) = cmplx_t (71, 0);\n#else\n  ha (0, 0) = cmplx_t (25, 0);\n  ha (0, 1) = cmplx_t (-5, -5);\n  ha (0, 2) = cmplx_t (10, 5);\n  ha (1, 1) = cmplx_t (51, 0);\n  ha (1, 2) = cmplx_t (4, -6);\n  ha (2, 2) = cmplx_t (71, 0);\n#endif\n  print_m (ha, \"A\"); \n  cout << endl; \n\n  ca2 = ha; \n  \n  ierr = lapack::potrf (ha); \n  if (ierr == 0) {\n    lapack::potri (ha); \n    cm_t ic (3, 3); \n    blas::hemm ( bindings::tag::right(), 1.0, ha, ca2, 0.0, ic); \n    print_m (ic, \"I = A * A^(-1)\"); \n    cout << endl; \n    blas::hemm ( bindings::tag::left(), 1.0, ha, ca2, 0.0, ic); \n    print_m (ic, \"I = A^(-1) * A\"); \n    cout << endl; \n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl; \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "1d8a1f9e09f8a4387da633607df0108e3735e446", "size": 4576, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_potri.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_potri.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_potri.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 25.4222222222, "max_line_length": 71, "alphanum_fraction": 0.5524475524, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.5574374069065197}}
{"text": "#pragma once\n#include \"math_util.hpp\"\n#include <boost/assert.hpp>\n#include <boost/operators.hpp>\n#include <cmath>\n#include <limits>\n#include <numeric>\n\nnamespace dmc\n{\n\ttemplate <class Scalar, int Dimension>\n\tclass vector;\n\n\ttemplate <class Derived, class Scalar, int Dimension>\n\tclass vector_base\n\t\t: boost::addable<\n\t\t\t  Derived,\n\t\t\t  boost::subtractable<\n\t\t\t\t  Derived,\n\t\t\t\t  boost::multipliable<\n\t\t\t\t\t  Derived,\n\t\t\t\t\t  Scalar,\n\t\t\t\t\t  boost::dividable<\n\t\t\t\t\t\t  Derived,\n\t\t\t\t\t\t  Scalar,\n\t\t\t\t\t\t  boost::equality_comparable<\n\t\t\t\t\t\t\t  Derived>>>>>\n\t{\n\tpublic:\n\t\ttypedef Scalar scalar_type;\n\t\tstatic const int dimension = Dimension;\n\n\t\tscalar_type* data()\n\t\t{\n\t\t\treturn &values_[0];\n\t\t}\n\n\t\tconst scalar_type* data() const\n\t\t{\n\t\t\treturn &values_[0];\n\t\t}\n\n\t\tscalar_type& operator[](int index)\n\t\t{\n\t\t\tBOOST_ASSERT(0 <= index && index < dimension);\n\t\t\treturn values_[index];\n\t\t}\n\n\t\tscalar_type operator[](int index) const\n\t\t{\n\t\t\tBOOST_ASSERT(0 <= index && index < dimension);\n\t\t\treturn values_[index];\n\t\t}\n\n\t\tDerived operator-() const\n\t\t{\n\t\t\treturn map([](auto x) { return -x; });\n\t\t}\n\n\t\tconst Derived& operator+() const\n\t\t{\n\t\t\treturn derived();\n\t\t}\n\n\t\tDerived& operator+=(const Derived& rhs)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\t(*this)[i] += rhs[i];\n\t\t\treturn derived();\n\t\t}\n\n\t\tDerived& operator-=(const Derived& rhs)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\t(*this)[i] -= rhs[i];\n\t\t\treturn derived();\n\t\t}\n\n\t\tDerived& operator*=(scalar_type rhs)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\t(*this)[i] *= rhs;\n\t\t\treturn derived();\n\t\t}\n\n\t\tDerived& operator/=(scalar_type rhs)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\t(*this)[i] /= rhs;\n\t\t\treturn derived();\n\t\t}\n\n\t\ttemplate <class F>\n\t\tvector<typename std::result_of<F(scalar_type)>::type, dimension> map(F f) const\n\t\t{\n\t\t\tvector<typename std::result_of<F(scalar_type)>::type, dimension> result;\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\tresult[i] = f((*this)[i]);\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate <class T>\n\t\tauto cast() const\n\t\t{\n\t\t\treturn map([](auto x) { return static_cast<T>(x); });\n\t\t}\n\n\t\tauto sign() const\n\t\t{\n\t\t\treturn map([](auto x) { return dmc::sign(x); });\n\t\t}\n\n\t\ttemplate <class T, class F>\n\t\tauto reduce(T t, F f) const\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\tt = f(t, (*this)[i]);\n\t\t\treturn t;\n\t\t}\n\n\t\ttemplate <class F>\n\t\tauto reduce(F f) const\n\t\t{\n\t\t\tauto t = (*this)[0];\n\t\t\tfor (int i = 1; i < dimension; ++i)\n\t\t\t\tt = f(t, (*this)[i]);\n\t\t\treturn t;\n\t\t}\n\n\t\tauto sum() const\n\t\t{\n\t\t\treturn reduce([](auto x, auto y) {\n\t\t\t\treturn x + y;\n\t\t\t});\n\t\t}\n\n\t\tauto product() const\n\t\t{\n\t\t\treturn reduce([](auto x, auto y) {\n\t\t\t\treturn x * y;\n\t\t\t});\n\t\t}\n\n\t\tauto abs() const\n\t\t{\n\t\t\treturn map([](auto x) { using std::abs; return abs(x); });\n\t\t}\n\n\t\tauto norm_l1() const\n\t\t{\n\t\t\treturn abs().sum();\n\t\t}\n\n\t\tauto squared() const\n\t\t{\n\t\t\treturn map([](auto x) { return squared(x); });\n\t\t}\n\n\t\tauto norm_l2_sq() const\n\t\t{\n\t\t\treturn squared().sum();\n\t\t}\n\n\t\tauto norm_l2() const\n\t\t{\n\t\t\tusing std::sqrt;\n\t\t\treturn sqrt(norm_l2_sq());\n\t\t}\n\n\t\tauto max() const\n\t\t{\n\t\t\treturn reduce([](auto x, auto y) { using std::max; return max(x, y); });\n\t\t}\n\n\t\tauto min() const\n\t\t{\n\t\t\treturn reduce([](auto x, auto y) { using std::min; return min(x, y); });\n\t\t}\n\n\t\tbool try_normalize()\n\t\t{\n\t\t\tauto n = norm_l2();\n\t\t\tif (n < std::numeric_limits<scalar_type>::epsilon())\n\t\t\t\treturn false;\n\n\t\t\t*this /= n;\n\t\t\treturn true;\n\t\t}\n\n\t\tDerived clamp(const Derived& minimum, const Derived& maximum)\n\t\t{\n\t\t\tDerived result;\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\tresult[i] = std::max(minimum[i], std::min(maximum[i], (*this)[i]));\n\t\t\treturn result;\n\t\t}\n\n\t\tstatic Derived all(scalar_type s)\n\t\t{\n\t\t\tDerived result;\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\tresult[i] = s;\n\t\t\treturn result;\n\t\t}\n\n\t\tfriend bool operator==(const Derived& lhs, const Derived& rhs)\n\t\t{\n\t\t\tfor (int i = 0; i < dimension; ++i)\n\t\t\t\tif (lhs[i] != rhs[i])\n\t\t\t\t\treturn false;\n\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tDerived& derived()\n\t\t{\n\t\t\treturn static_cast<Derived&>(*this);\n\t\t}\n\n\t\tconst Derived& derived() const\n\t\t{\n\t\t\treturn static_cast<const Derived&>(*this);\n\t\t}\n\n\t\tscalar_type values_[dimension] = {};\n\t};\n}\n", "meta": {"hexsha": "4f33cf334f66bf0571099a6dbea814c87eabfa66", "size": 4124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dmc/vector_base.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": "dmc/vector_base.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": "dmc/vector_base.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": 18.0087336245, "max_line_length": 81, "alphanum_fraction": 0.5746847721, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.557437402125853}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <boost/range.hpp>\n#include <math.h>\n#include <math/Vec.hpp>\n#include <utility>\n\ntemplate <int rows_, int cols_, class T = float>\nstruct Matrix {\n\tstatic const int rows = rows_;\n\tstatic const int cols = cols_;\n\tstatic const int size = rows * cols;\n\n\ttypedef T value_type;\n\n\ttypedef T & reference;\n\ttypedef T const & const_reference;\n\n\ttypedef T * pointer;\n\ttypedef T const * const_pointer;\n\n\ttypedef T row_type[cols];\n\ttypedef row_type storage_type[rows];\n\n\ttypedef pointer iterator;\n\ttypedef const_pointer const_iterator;\n\n\ttypedef std::pair<iterator, iterator> range_type;\n\ttypedef std::pair<const_iterator, const_iterator> const_range_type;\n\n\tMatrix() {\n\t\titerator end = this->end();\n\t\tfor (iterator it = this->begin(); it != end; *it++ = 0) { ; }\n\t}\n\n\ttemplate <class InIt>\n\tMatrix(InIt it, InIt end) {\n\t\tassign(it, end);\n\t}\n\n\ttemplate <class U>\n\tMatrix(U (&array)[rows * cols]) {\n\t\tassign(boost::begin(array), boost::end(array));\n\t}\n\n\ttemplate <class R>\n\tMatrix(R (&array)[rows]) {\n\t\titerator out = begin();\n\t\tfor (int i = 0; i < rows; ++i) {\n\t\t\tout = std::copy(boost::begin(array[i]), boost::end(array[i]), out);\n\t\t}\n\t}\n\n\trow_type & operator [] (int i) { return data_[i]; }\n\trow_type const & operator [] (int i) const { return data_[i]; }\n\n\treference operator () (int i, int j) { return data_[i][j]; }\n\tconst_reference operator () (int i, int j) const { return data_[i][j]; }\n\n\trange_type row_range(int i) { return range_type(data_[i], data_[i] + cols); }\n\tconst_range_type row_range(int i) const { return const_range_type(data_[i], data_[i] + cols); }\n\n\trange_type column_range(int j) { return range_type(data_[0] + j, data_[rows] + j); }\n\tconst_range_type column_range(int j) const { return const_range_type(data_[0] + j, data_[rows] + j); }\n\n\titerator begin() { return data_[0]; }\n\tconst_iterator begin() const { return data_[0]; }\n\n\titerator end() { return data_[rows]; }\n\tconst_iterator end() const { return data_[rows]; }\n\n\ttemplate <class It>\n\tvoid assign(It it, It end) {\n\t\titerator out_end = this->end();\n\t\tfor (iterator out = begin(); out != out_end && it != end; *out++ = *it++) { ; }\n\t}\n\n\ttemplate <class U>\n\tVec<rows, T> operator * (Vec<cols, U> const & v) const {\n\t\tVec<rows, T> out;\n\t\tfor (int i = 0; i < rows; ++i) {\n\t\t\tout[i] = dot(row_range(i), 1, std::make_pair(v.begin(), v.end()), 1);\n\t\t}\n\n\t\treturn out;\n\t}\n\n\ttemplate <class U>\n\tfriend Vec<cols, T> operator * (Vec<rows, U> const & v, Matrix const & M) {\n\t\tVec<cols, T> out;\n\t\tfor (int i = 0; i < cols; ++i) {\n\t\t\tout[i] = M.dot(std::make_pair(v.begin(), v.end()), 1, M.column_range(i), cols);\n\t\t}\n\n\t\treturn out;\n\t}\n\n\ttemplate <int c, class U>\n\tMatrix<rows, c, T> operator * (Matrix<cols, c, U> const & right) const {\n\t\tMatrix<rows, c> out;\n\t\tfor (int i = 0; i < rows; ++i) {\n\t\t\tfor (int j = 0; j < right.cols; ++j) {\n\t\t\t\tout.data_[i][j] = dot(row_range(i), 1, right.column_range(j), right.cols);\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\ttemplate <class U>\n\tMatrix & operator *= (Matrix<cols, cols, U> const & right) {\n\t\t*this = (*this) * right;\n\t\treturn *this;\n\t}\n\n\ttemplate <class stream>\n\tfriend stream & operator << (stream & out, Matrix const & m) {\n\t\tout << \"{ \";\n\t\tfor (int i = 0; i < m.rows; ++i) {\n\t\t\tif (i) { out << \", \"; }\n\n\t\t\tout << \"{ \";\n\t\t\tfor (int j = 0; j < m.cols; ++j) {\n\t\t\t\tif (j) { out << \", \"; }\n\t\t\t\tout << m.data_[i][j];\n\t\t\t}\n\t\t\tout << \" }\";\n\t\t}\n\t\tout << \" }\";\n\t\treturn out;\n\t}\n\n\tvoid set_row(int i, Vec<cols, T> const & row) {\n\t\trange_type r = row_range(i);\n\t\tfor (int j = 0; j < cols; ++j) { r.first[j] = row[j]; }\n\t}\n\n\tvoid set_column(int j, Vec<rows, T> const & col) {\n\t\trange_type r = column_range(j);\n\t\tfor (int i = 0; i < rows; ++i) { r.first[i] = col[i]; }\n\t}\n\n\tprivate:\n\t\ttemplate <class L, class R>\n\t\tstatic inline T dot(L left, int stride_left, R right, int stride_right) {\n\t\t\tT out = 0;\n\t\t\t\n\t\t\twhile (left.first < left.second && right.first < right.second) {\n\t\t\t\tout += *left.first * *right.first;\n\t\t\t\tleft.first += stride_left;\n\t\t\t\tright.first += stride_right;\n\t\t\t}\n\t\t\t\n\t\t\treturn out;\n\t\t}\n\n\t\tstorage_type data_;\n};\n\nnamespace detail {\n\tnamespace MatrixInverter {\n\t\tinline int abs(int x) { return ::abs(x); }\n\t\tinline float abs(float x) { return fabsf(x); }\n\t\tinline double abs(double x) { return fabs(x); }\n\t\tinline long double abs(long double x) { return fabsl(x); }\n\n\t\ttemplate <class T, int N>\n\t\tinline void swap(T (&left)[N], T (&right)[N]) {\n\t\t\tfloat *l = left, *r = right;\n\t\t\tfor (int i = 0; i < N; ++i) { std::swap(*l++, *r++); }\n\t\t}\n\n\t\ttemplate <class T>\n\t\tinline void div(T * begin, T * end, T d) {\n\t\t\tfor (; begin != end; ++begin) { *begin /= d; }\n\t\t}\n\n\t\ttemplate <class T>\n\t\tinline T max_abs(T * begin, T * end) {\n\t\t\tT m = 0;\n\t\t\tfor (T * it = begin; it < end; ++it) {\n\t\t\t\tT v = abs(*it);\n\t\t\t\tif (it != begin && v <= m) { continue; }\n\t\t\t\tm = v;\n\t\t\t}\n\n\t\t\treturn m;\n\t\t}\n\n\t\ttemplate <class T>\n\t\tinline int find_pivot_row(T * begin, T * end, int stride) {\n\t\t\tT m = 0; int p = 0, i = 0;\n\t\t\tfor (T * it = begin; it < end; ++i, it += stride) {\n\t\t\t\tT v = abs(*it); \n\t\t\t\tif (i && v <= m) { continue; }\n\t\t\t\tm = v; p = i;\n\t\t\t}\n\n\t\t\treturn p;\n\t\t}\n\n\t\ttemplate <class T>\n\t\tinline void normalize_front(T * begin, T * end) {\n\t\t\tfloat d = *begin; *begin = 1; ++begin;\n\t\t\twhile (begin < end) { *begin++ /= d; }\n\t\t}\n\n\t\ttemplate <class T>\n\t\tinline void scale_and_subtract(T * begin, T * end, T * out) {\n\t\t\tT s = -*out / *begin++; *out++ = 0;\n\t\t\twhile (begin < end) { *out++ += s * *begin++; }\n\t\t}\n\n\t\ttemplate <class T, int N>\n\t\tvoid invert_matrix(Matrix<N, N, T> * M) {\n\t\t\tT S[N][2 * N];\n\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tfor (int j = 0; j < N; ++j) {\n\t\t\t\t\tS[i][j] = (*M)[i][j];\n\t\t\t\t\tS[i][j + N] = (i == j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < N; ++i) { div(S[i], S[i] + 2 * N, max_abs(S[i], S[i] + N)); }\n\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tint pivot = find_pivot_row(S[i] + i, S[N] + i, 2 * N);\n\t\t\t\tif (pivot) { swap(S[i], S[i + pivot]); }\n\n\t\t\t\tnormalize_front(S[i] + i, S[i] + 2 * N);\n\t\t\t\tfor (int j = i + 1; j < N; ++j) { scale_and_subtract(S[i] + i, S[i] + 2 * N, S[j] + i); }\n\t\t\t}\n\n\t\t\tfor (int i = N - 1; i > 0; --i) {\n\t\t\t\tfor (int j = i - 1; j >= 0; --j) { scale_and_subtract(S[i] + i, S[i] + 2 * N, S[j] + i); }\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tfor (int j = 0; j < N; ++j) { (*M)[i][j] = S[i][j + N]; }\n\t\t\t}\n\t\t}\n\t}\n}\n\nusing detail::MatrixInverter::invert_matrix;\n", "meta": {"hexsha": "89b6304e31f2c7aa7796b1b02b4de686e6de3ca4", "size": 6316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/Matrix.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/Matrix.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/Matrix.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": 25.5708502024, "max_line_length": 103, "alphanum_fraction": 0.559531349, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5574373973451867}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include \"Eigen/Eigen\"  // AFTER GRIDMAP!\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n\n\nclass SplineFunction {\n\n  public:\n              \n      // The spline is used to interpolate antenna gain values, as we only have the graphs\n      SplineFunction()\n      {}\n\n      SplineFunction(Eigen::VectorXd const &x_vec, Eigen::VectorXd const &y_vec)\n        : x_min(x_vec.minCoeff()),\n          x_max(x_vec.maxCoeff()),\n          y_min(y_vec.minCoeff()),\n          y_max(y_vec.maxCoeff()),\n          // Spline fitting here. X values are scaled down to [0, 1] for this.\n          spline_(Eigen::SplineFitting<Eigen::Spline<double, 1>>::Interpolate(y_vec.transpose(), std::min<int>(x_vec.rows() - 1, 6), scaled_values(x_vec)))  // No more than cubic spline, but accept short vectors.\n      {}\n\n      // x values need to be scaled down in extraction as well.\n      double interpDeg(double x) const {      \n        double y;\n        y = spline_(scaled_value(x))(0);\n\n        // interpolation may produce values bigger and lower than our limits ...          \n        y = std::max(std::min(y, y_max), y_min );\n        return y;\n      }\n\n      double interpRad(double x) const {\n          return interpDeg(x*180.0/M_PI); \n      }\n\n      // Helpers to scale X values down to [0, 1]\n      double scaled_value(double x) const {\n        return (x - x_min) / (x_max - x_min);\n      }\n\n    private: \n      Eigen::RowVectorXd scaled_values(Eigen::VectorXd const &x_vec) const {\n        return x_vec.unaryExpr([this](double x) { return scaled_value(x); }).transpose();\n      }\n\n      double x_min;\n      double x_max;\n      double y_min;\n      double y_max;\n\n      // Spline of one-dimensional \"points.\"\n      Eigen::Spline<double, 1> spline_;\n};\n\n\n/////////////////////////////\n\n\n\n// quick build:\n// g++ -I /usr/include/eigen3/ play_with_eigen.cpp -o play_with_eigen -std=c++11\n\nusing namespace std::placeholders;\nusing Eigen::MatrixXd;\n\nconst double C = 299792458.0;\nconst double SENSITIVITY = -115; // dB    \n\nconst double TAG_LOSSES = -4.8;\n\nconst double LOSS_CONSTANT = 147.55;\nconst double freq= 865e6; \nconst double lambda =  C/freq;\nconst double ANTENNA_LOSSES_LIST [25] = {  -22.6, -25.2, -25, -20.2, -17.6, -15.6, -14, -11.2, -7.8, -5.2, -2.4, -0.6, 0, -0.6, -2.4, -5.2, -8.8, -12.2, -16.4, -19.2, -20.8, -24.4, -28.2, -24, -22.6};\nconst double ANTENNA_ANGLES_LIST [25] = {-180.0, -165.0, -150.0, -135.0, -120.0, -105.0, -90.0, -75.0, -60.0, -45.0, -30.0, -15.0, 0.0, 15.0, 30.0, 45.0, 60.0, 75.0, 90.0, 105.0, 120.0, 135.0, 150.0, 165.0, 180.0};\n\n//! Generates a mesh, just like Matlab's meshgrid\n//  Template specialization for column vectors (Eigen::VectorXd)\n//  in : x, y column vectors \n//       X, Y matrices, used to save the mesh\ntemplate <typename Scalar>\nvoid meshgrid(const Eigen::Matrix<Scalar, -1, 1>& x, \n              const Eigen::Matrix<Scalar, -1, 1>& y,\n              Eigen::Matrix<Scalar, -1, -1>& X,\n              Eigen::Matrix<Scalar, -1, -1>& Y) {\n  const long nx = x.size(), ny = y.size();\n  X.resize(ny, nx);\n  Y.resize(ny, nx);\n  for (long i = 0; i < ny; ++i) {\n    X.row(i) = x.transpose();\n  }\n\n  // for (long j = 0; j < nx; ++j) {\n  //   Y.col(j) = y;\n  // }\n  for (long j = 0; j < nx; ++j) {\n    Y.col(j) = y.reverse();\n  }\n}\n\n\n//! Generates a mesh, just like Matlab's meshgrid\n//  Template specialization for row vectors (Eigen::RowVectorXd)\n//  in : x, y row vectors \n//       X, Y matrices, used to save the mesh\ntemplate <typename Scalar>\nvoid meshgrid(const Eigen::Matrix<Scalar, 1, -1>& x, \n              const Eigen::Matrix<Scalar, 1, -1>& y,\n              Eigen::Matrix<Scalar, -1, -1>& X,\n              Eigen::Matrix<Scalar, -1, -1>& Y) {\n  Eigen::Matrix<Scalar, -1, 1> xt = x.transpose(),\n                               yt = y.transpose();\n  meshgrid(xt, yt, X, Y);\n}\n\n\ntypedef Eigen::VectorXd Vec;\ntypedef Eigen::MatrixXd Mat;\n\nint main(int argc, char **argv)\n{\n    int Nx, Ny, x_min, x_max, y_min, y_max;\n    double x_m, y_m;\n    Mat X, Y, R, A, propL, antL,totalLoss, rxPower;\n    Vec x,y;\n\n    double txPower = 0; //dB\n\n    \n\n    /////////////////////////        // build spline to interpolate antenna gains;\n    std::vector<double> xVec(ANTENNA_ANGLES_LIST, ANTENNA_ANGLES_LIST + 25);\n    Eigen::VectorXd xvals = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(xVec.data(), xVec.size());\n    std::vector<double> yVec(ANTENNA_LOSSES_LIST, ANTENNA_LOSSES_LIST + 25);\n    Eigen::VectorXd yvals= Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(yVec.data(), yVec.size());\n    SplineFunction _antenna_gains= SplineFunction(xvals, yvals);\n    ////////////////////////\n\n    Nx = 5;\n    Ny = 8;\n    x_min = -1;\n    x_max = 1;\n    y_min = -2;\n    y_max = 2;\n    x_m = 0.5;\n    y_m = 1.2;\n\n    x = Vec::LinSpaced(Nx, x_min, x_max);\n    y = Vec::LinSpaced(Ny, y_min, y_max);\n\n    std::cout << \"x\" << std::endl;\n    std::cout << x << std::endl;\n    std::cout << \"y\" << std::endl;\n    std::cout << y << std::endl;\n\n    // create X,Y meshgrids\n    meshgrid(x, y, X, Y);\n\n    // distance to point m\n    X = X.array() - x_m;\n    Y = Y.array() - y_m;\n\n    std::cout << \"X\" << std::endl;\n    std::cout << X << std::endl;\n    std::cout << \"Y\" << std::endl;\n    std::cout << Y << std::endl;\n\n    // create R,Ang matrixes\n    R = (X.array().square() + Y.array().square()).array().sqrt();\n    A = Y.binaryExpr(X, std::ptr_fun(atan2));\n\n    std::cout << \"R\" << std::endl;\n    std::cout << R << std::endl;\n\n    std::cout << \"A\" << std::endl;\n    std::cout << (A*180.0/3.141592) << std::endl;\n\n    // Create a propagation matrix without taking obstacles        \n    auto funtor = std::bind(&SplineFunction::interpRad, _antenna_gains, _1) ;\n    antL =  TAG_LOSSES + A.unaryExpr( funtor ).array();    \n    std::cout << \"antL\" << std::endl;\n    std::cout << antL << std::endl;\n\n    propL = LOSS_CONSTANT - (20.0 * (R * freq).unaryExpr(std::ptr_fun(log10))).array() ;\n    std::cout << \"propL\" << std::endl;\n    std::cout << propL << std::endl;\n\n    // signal goes from antenna to tag and comes back again, so we double the losses\n    totalLoss =  2*antL + 2*propL;\n    std::cout << \"totalLoss\" << std::endl;\n    std::cout << totalLoss << std::endl;\n    \n    rxPower = txPower + totalLoss.array(); \n\n    // this should remove points where friis is not applicable\n    rxPower = (R.array()>2*lambda).select(rxPower,SENSITIVITY); \n    // this should remove points where received power is too low\n    rxPower = (rxPower.array()>SENSITIVITY).select(rxPower,SENSITIVITY); \n\n    std::cout << \"rxPower\" << std::endl;\n    std::cout << rxPower << std::endl;\n\n\n\n}", "meta": {"hexsha": "408fa7f32dcb1f1842b47bc0ac6a41535fd7c780", "size": 6608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "play_with_eigen.cpp", "max_stars_repo_name": "pulver22/mcdm_online_exploration_ros", "max_stars_repo_head_hexsha": "ad98c9a4a897b6f700b9006f95e17b03e897e76e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-22T08:31:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-22T08:31:08.000Z", "max_issues_repo_path": "play_with_eigen.cpp", "max_issues_repo_name": "pulver22/mcdm_online_exploration_ros", "max_issues_repo_head_hexsha": "ad98c9a4a897b6f700b9006f95e17b03e897e76e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-13T15:30:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T10:58:24.000Z", "max_forks_repo_path": "play_with_eigen.cpp", "max_forks_repo_name": "pulver22/mcdm", "max_forks_repo_head_hexsha": "ad98c9a4a897b6f700b9006f95e17b03e897e76e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-22T08:31:10.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-22T08:31:10.000Z", "avg_line_length": 31.6172248804, "max_line_length": 214, "alphanum_fraction": 0.5779358354, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5574347237544277}}
{"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    int n = 10000;\n  VectorXd x(n), b(n);\n  SparseMatrix<double> A(n,n);\n  /* ... fill A and b ... */ \n  BiCGSTAB<SparseMatrix<double> > solver;\n  solver.compute(A);\n  x = solver.solve(b);\n  std::cout << \"#iterations:     \" << solver.iterations() << std::endl;\n  std::cout << \"estimated error: \" << solver.error()      << std::endl;\n  /* ... update b ... */\n  x = solver.solve(b); // solve again\n  return 0;\n}\n", "meta": {"hexsha": "325fb0a34646bd74c67dbbe9f3e371ee3cb8345a", "size": 613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_BiCGSTAB_simple.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_BiCGSTAB_simple.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_BiCGSTAB_simple.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": 21.8928571429, "max_line_length": 71, "alphanum_fraction": 0.6182707993, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5573990738681283}}
{"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 *\r\n *    References\r\n *\r\n *    Notes\r\n *\r\n */\r\n\r\n#include <cmath>\r\n\r\n#include <Eigen/Core>\r\n\r\n#include \"Tudat/Mathematics/BasicMathematics/sphericalHarmonics.h\"\r\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\r\n\r\nnamespace tudat\r\n{\r\nnamespace basic_mathematics\r\n{\r\n\r\n//! Update maximum degree and order of cache\r\nvoid SphericalHarmonicsCache::resetMaximumDegreeAndOrder( const int maximumDegree, const int maximumOrder )\r\n{\r\n    maximumDegree_ = maximumDegree;\r\n    maximumOrder_ = maximumOrder;\r\n\r\n    legendreCache_->resetMaximumDegreeAndOrder( maximumDegree_, maximumOrder_ );\r\n\r\n    sinesOfLongitude_.resize( maximumOrder_ + 1 );\r\n    cosinesOfLongitude_.resize( maximumOrder_ + 1 );\r\n    referenceRadiusRatioPowers_.resize( maximumDegree_ + 2 );\r\n}\r\n\r\n\r\n//! Compute the gradient of a single term of a spherical harmonics potential field.\r\nEigen::Vector3d computePotentialGradient(\r\n        const double distance,\r\n        const double radiusPowerTerm,\r\n        const double cosineOfOrderLongitude,\r\n        const double sineOfOrderLongitude,\r\n        const double cosineOfLatitude,\r\n        const double preMultiplier,\r\n        const int degree,\r\n        const int order,\r\n        const double cosineHarmonicCoefficient,\r\n        const double sineHarmonicCoefficient,\r\n        const double legendrePolynomial,\r\n        const double legendrePolynomialDerivative )\r\n{\r\n    // Return result.\r\n    return ( Eigen::Vector3d( ) <<\r\n             - preMultiplier / distance\r\n             * radiusPowerTerm\r\n             * ( static_cast< double >( degree ) + 1.0 ) * legendrePolynomial\r\n             * ( cosineHarmonicCoefficient * cosineOfOrderLongitude\r\n                 + sineHarmonicCoefficient * sineOfOrderLongitude ),\r\n             preMultiplier * radiusPowerTerm\r\n             * legendrePolynomialDerivative * cosineOfLatitude * (\r\n                 cosineHarmonicCoefficient * cosineOfOrderLongitude\r\n                 + sineHarmonicCoefficient * sineOfOrderLongitude ),\r\n             preMultiplier * radiusPowerTerm\r\n             * static_cast< double >( order ) * legendrePolynomial\r\n             * ( sineHarmonicCoefficient * cosineOfOrderLongitude\r\n                 - cosineHarmonicCoefficient * sineOfOrderLongitude ) ).finished( );\r\n}\r\n\r\n//! Compute the gradient of a single term of a spherical harmonics potential field.\r\nEigen::Vector3d computePotentialGradient(\r\n        const Eigen::Vector3d& sphericalPosition,\r\n        const double referenceRadius,\r\n        const double preMultiplier,\r\n        const int degree,\r\n        const int order,\r\n        const double cosineHarmonicCoefficient,\r\n        const double sineHarmonicCoefficient,\r\n        const double legendrePolynomial,\r\n        const double legendrePolynomialDerivative )\r\n{\r\n    return computePotentialGradient(\r\n                sphericalPosition( radiusIndex ),\r\n                basic_mathematics::raiseToIntegerPower\r\n                ( referenceRadius / sphericalPosition( radiusIndex ), static_cast< double >( degree ) + 1.0 ),\r\n                std::cos( static_cast< double >( order ) * sphericalPosition( longitudeIndex ) ),\r\n                std::sin( static_cast< double >( order ) * sphericalPosition( longitudeIndex ) ),\r\n                std::cos( sphericalPosition( latitudeIndex ) ), preMultiplier, degree, order,\r\n                cosineHarmonicCoefficient, sineHarmonicCoefficient, legendrePolynomial,legendrePolynomialDerivative );\r\n}\r\n\r\n//! Compute the gradient of a single term of a spherical harmonics potential field.\r\nEigen::Vector3d computePotentialGradient( const Eigen::Vector3d& sphericalPosition,\r\n                                          const double preMultiplier,\r\n                                          const int degree,\r\n                                          const int order,\r\n                                          const double cosineHarmonicCoefficient,\r\n                                          const double sineHarmonicCoefficient,\r\n                                          const double legendrePolynomial,\r\n                                          const double legendrePolynomialDerivative,\r\n                                          const boost::shared_ptr< SphericalHarmonicsCache > sphericalHarmonicsCache )\r\n{\r\n    return computePotentialGradient(\r\n                sphericalPosition( radiusIndex ),\r\n                sphericalHarmonicsCache->getReferenceRadiusRatioPowers( degree + 1 ),\r\n                sphericalHarmonicsCache->getCosineOfMultipleLongitude( order ),\r\n                sphericalHarmonicsCache->getSineOfMultipleLongitude( order ),\r\n                sphericalHarmonicsCache->getLegendreCache( )->getCurrentPolynomialParameterComplement( ),\r\n                preMultiplier, degree, order,\r\n                cosineHarmonicCoefficient, sineHarmonicCoefficient, legendrePolynomial,legendrePolynomialDerivative );\r\n}\r\n\r\n} // namespace basic_mathematics\r\n} // namespace tudat\r\n", "meta": {"hexsha": "20031c8cf83923bd2e21c4119bbc97ad2b18fae0", "size": 6743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/sphericalHarmonics.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/sphericalHarmonics.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/sphericalHarmonics.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.8623188406, "max_line_length": 119, "alphanum_fraction": 0.6627613822, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5573990700161604}}
{"text": "//ros\n#include <ros/ros.h>\n#include <nav_msgs/Path.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Twist.h>\n#include <tf/tf.h>\n#include <tf/transform_listener.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <geometry_msgs/PoseArray.h>\n\n//ipopt\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <cppad/cppad.hpp>\n#include <cppad/ipopt/solve.hpp>\n\n// kinematic model wheel_velocity = forward_matrix * robot_velocity\nEigen::MatrixXd forward_matrix;\nEigen::MatrixXd inversed_matrix;\nEigen::VectorXd wheel_velocity;\nEigen::Vector3d robot_velocity;\n\n//https://robotics.naist.jp/edu/text/?Robotics%2FEigen#b3b26d13\ntemplate <typename t_matrix>\nt_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\nusing CppAD::AD;\n\nclass MPC{\npublic:\n  MPC();\n\n  // state, ref_x, ref_y, ref_yaw\n  std::vector<double> solve(Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd);\n\n};\n\nclass FG_eval{\npublic:\n  FG_eval(Eigen::VectorXd, Eigen::VectorXd, Eigen::VectorXd);\n\n  typedef CPPAD_TESTVECTOR(AD<double>) ADvector;\n\n  void operator()(ADvector&, const ADvector&);\n\nprivate:\n  Eigen::VectorXd ref_x;\n  Eigen::VectorXd ref_y;\n  Eigen::VectorXd ref_yaw;\n\n};\n\nclass MPCPathTracker\n{\npublic:\n  MPCPathTracker(void);\n\n  void path_callback(const nav_msgs::PathConstPtr&);\n\n  void process(void);\n  void path_to_vector(void);\n\nprivate:\n  ros::NodeHandle nh;\n  ros::Publisher velocity_pub;\n  ros::Publisher path_pub;\n  ros::Subscriber path_sub;\n  MPC mpc;\n  nav_msgs::Path path;\n  tf::TransformListener listener;\n  geometry_msgs::PoseStamped current_pose;\n  geometry_msgs::PoseStamped previous_pose;\n  tf::StampedTransform _transform;\n  geometry_msgs::TransformStamped transform;\n  Eigen::VectorXd path_x;\n  Eigen::VectorXd path_y;\n  Eigen::VectorXd path_yaw;\n  bool first_transform = true;\n  double last_time;\n  geometry_msgs::Twist velocity;\n\n};\n\n// ホライゾン長さ\nint T = 5;\n// 周期\ndouble DT = 0.1;// [s]\nconst double HZ = 10;\n// 目標速度\ndouble VREF = 0.5;// [m/s]\n// 最大角速度\ndouble MAX_ANGULAR_VELOCITY = 1.0;// [rad/s]\n// ホイール角加速度\ndouble MAX_WHEEL_ANGULAR_ACCELERATION = 60;// [rad/s^2]\n// ホイール角速度\ndouble MAX_WHEEL_ANGULAR_VELOCITY = 30;// [rad/s]\n// ホイール半径\ndouble WHEEL_RADIUS = 0.1;// [m]\n// トレッド\ndouble TREAD = 0.4;// [m]\n// ホイールベース\ndouble WHEEL_BASE = 0.4;// [m]\n// グリッドマップ分解能\ndouble RESOLUTION = 0.1;// [m]\n// ロボットの足まわり半径\ndouble ROBOT_RADIUS;\n// 足回り配置\ndouble ROBOT_THETA;\n// ステア角度制限\ndouble MAX_STEERING_ANGLE = M_PI * 2. / 3.;// [rad]\n// 最高速度\ndouble MAX_VELOCITY = 1.5;// [m/s]\n\nstd::string WORLD_FRAME;\nstd::string ROBOT_FRAME;\nstd::string VELOCITY_TOPIC_NAME;\nstd::string INTERMEDIATE_PATH_TOPIC_NAME;\n\n// state\nsize_t x_start = 0;\nsize_t y_start = x_start + T;\nsize_t yaw_start = y_start + T;\nsize_t vx_start = yaw_start + T;\nsize_t vy_start = vx_start + T;\nsize_t omega_start = vy_start + T;\nsize_t omega_w_fr_start = omega_start + T;\nsize_t omega_w_fl_start = omega_w_fr_start + T;\nsize_t omega_w_rr_start = omega_w_fl_start + T;\nsize_t omega_w_rl_start = omega_w_rr_start + T;\nsize_t theta_s_fr_start = omega_w_rl_start + T;\nsize_t theta_s_fl_start = theta_s_fr_start + T;\nsize_t theta_s_rr_start = theta_s_fl_start + T;\nsize_t theta_s_rl_start = theta_s_rr_start + T;\n// input\nsize_t domega_w_fr_start = theta_s_rl_start + T;\nsize_t domega_w_fl_start = domega_w_fr_start + T - 1;\nsize_t domega_w_rr_start = domega_w_fl_start + T - 1;\nsize_t domega_w_rl_start = domega_w_rr_start + T - 1;\nsize_t dtheta_s_fr_start = domega_w_rl_start + T - 1;\nsize_t dtheta_s_fl_start = dtheta_s_fr_start + T - 1;\nsize_t dtheta_s_rr_start = dtheta_s_fl_start + T - 1;\nsize_t dtheta_s_rl_start = dtheta_s_rr_start + T - 1;\n\n// 最適化失敗時は最後の成功データを使う\nint failure_count = 0;\nstd::vector<double> result;\nstd::vector<double> solution_buffer;\n\ndouble min_distance(nav_msgs::Path&, geometry_msgs::PoseStamped&);\ndouble get_distance(geometry_msgs::PoseStamped&, geometry_msgs::PoseStamped&);\n\nint main(int argc, char** argv)\n{\n  ros::init(argc, argv, \"fwdis_mpc\");\n  ros::NodeHandle local_nh(\"~\");\n\n  /*\n  local_nh.getParam(\"HORIZON_T\", T);\n  */\n  local_nh.getParam(\"/dynamic_avoidance/VREF\", VREF);\n  local_nh.getParam(\"/dynamic_avoidance/MAX_ANGULAR_VELOCITY\", MAX_ANGULAR_VELOCITY);\n  local_nh.getParam(\"/dynamic_avoidance/RESOLUTION\", RESOLUTION);\n  local_nh.getParam(\"/dynamic_avoidance/ROBOT_FRAME\", ROBOT_FRAME);\n  local_nh.getParam(\"/dynamic_avoidance/WORLD_FRAME\", WORLD_FRAME);\n  local_nh.getParam(\"/dynamic_avoidance/VELOCITY_TOPIC_NAME\", VELOCITY_TOPIC_NAME);\n  local_nh.getParam(\"/dynamic_avoidance/INTERMEDIATE_PATH_TOPIC_NAME\", INTERMEDIATE_PATH_TOPIC_NAME);\n  local_nh.getParam(\"/fwdis/WHEEL_RADIUS\", WHEEL_RADIUS);\n  local_nh.getParam(\"/fwdis/WHEEL_BASE\", WHEEL_BASE);\n  local_nh.getParam(\"/fwdis/TREAD\", TREAD);\n  local_nh.getParam(\"/fwdis/MAX_WHEEL_ANGULAR_VELOCITY\", MAX_WHEEL_ANGULAR_VELOCITY);\n  local_nh.getParam(\"/fwdis/MAX_WHEEL_ANGULAR_ACCELERATION\", MAX_WHEEL_ANGULAR_ACCELERATION);\n  local_nh.getParam(\"/fwdis/MAX_VELOCITY\", MAX_VELOCITY);\n  local_nh.getParam(\"/fwdis/MAX_STEERING_ANGLE\", MAX_STEERING_ANGLE);\n\n  std::cout << \"T: \" << T << std::endl;\n  std::cout << \"VREF: \" << VREF << std::endl;\n  std::cout << \"MAX_ANGULAR_VELOCITY: \" << MAX_ANGULAR_VELOCITY << std::endl;\n  std::cout << \"RESOLUTION: \" << RESOLUTION << std::endl;\n  std::cout << \"ROBOT_FRAME: \" <<  ROBOT_FRAME << std::endl;\n  std::cout << \"WORLD_FRAME: \" << WORLD_FRAME << std::endl;\n  std::cout << \"VELOCITY_TOPIC_NAME: \" << VELOCITY_TOPIC_NAME << std::endl;\n  std::cout << \"INTERMEDIATE_PATH_TOPIC_NAME: \" << INTERMEDIATE_PATH_TOPIC_NAME << std::endl;\n  std::cout << \"WHEEL_RADIUS: \" << WHEEL_RADIUS << std::endl;\n  std::cout << \"WHEEL_BASE: \" << WHEEL_BASE << std::endl;\n  std::cout << \"TREAD: \" << TREAD << std::endl;\n  std::cout << \"MAX_WHEEL_ANGULAR_VELOCITY: \" << MAX_WHEEL_ANGULAR_VELOCITY << std::endl;\n  std::cout << \"MAX_WHEEL_ANGULAR_ACCELERATION: \" << MAX_WHEEL_ANGULAR_ACCELERATION << std::endl;\n  std::cout << \"MAX_VELOCITY: \" << MAX_VELOCITY << std::endl;\n  std::cout << \"MAX_STEERING_ANGLE: \" << MAX_STEERING_ANGLE << std::endl;\n\n  ROBOT_RADIUS = sqrt(pow(WHEEL_BASE, 2) + pow(TREAD, 2)) / 2.0;\n  ROBOT_THETA = atan(TREAD / WHEEL_BASE);\n  forward_matrix.resize(8, 3);\n  forward_matrix << 1.0, 0.0,  ROBOT_RADIUS * cos(ROBOT_THETA),\n                    0.0, 1.0,  ROBOT_RADIUS * sin(ROBOT_THETA),\n                    1.0, 0.0, -ROBOT_RADIUS * cos(ROBOT_THETA),\n                    0.0, 1.0,  ROBOT_RADIUS * sin(ROBOT_THETA),\n                    1.0, 0.0, -ROBOT_RADIUS * cos(ROBOT_THETA),\n                    0.0, 1.0, -ROBOT_RADIUS * sin(ROBOT_THETA),\n                    1.0, 0.0,  ROBOT_RADIUS * cos(ROBOT_THETA),\n                    0.0, 1.0, -ROBOT_RADIUS * sin(ROBOT_THETA);\n\n  inversed_matrix.resize(3, 8);\n  inversed_matrix = PseudoInverse(forward_matrix);\n\n  wheel_velocity.resize(8, 1);\n\n  std::cout << forward_matrix << std::endl;\n  std::cout << inversed_matrix << std::endl;\n\n  MPCPathTracker mpc_path_tracker;\n\n  ros::Rate loop_rate(HZ);\n\n  while(ros::ok()){\n    mpc_path_tracker.process();\n\n    ros::spinOnce();\n    loop_rate.sleep();\n  }\n  return 0;\n}\n\nMPC::MPC(){}\n\nstd::vector<double> MPC::solve(Eigen::VectorXd state, Eigen::VectorXd ref_x, Eigen::VectorXd ref_y, Eigen::VectorXd ref_yaw)\n{\n  /*\n   * state:x, y, yaw, vx, vy, omega, omega_w_fr, omega_w_fl, omega_w_rr, omega_w_rl, theta_s_fr, theta_s_fl, theta_s_rr, theta_s_rl\n   */\n  bool ok = true;\n  size_t i;\n  typedef CPPAD_TESTVECTOR(double) Dvector;\n\n  double x = state[0];\n  double y = state[1];\n  double yaw = state[2];\n  double vx = state[3];\n  double vy = state[4];\n  double omega = state[5];\n  double omega_w_fr = state[6];\n  double omega_w_fl = state[7];\n  double omega_w_rr = state[8];\n  double omega_w_rl = state[9];\n  double theta_s_fr = state[10];\n  double theta_s_fl = state[11];\n  double theta_s_rr = state[12];\n  double theta_s_rl = state[13];\n\n  /*\n  std::cout << \"--- state ---\" << std::endl;\n  std::cout << state << std::endl;\n  std::cout << \"--- path_x ---\" << std::endl;\n  std::cout << ref_x << std::endl;\n  std::cout << \"--- path_y ---\" << std::endl;\n  std::cout << ref_y << std::endl;\n  std::cout << \"--- path_yaw ---\" << std::endl;\n  std::cout << ref_yaw << std::endl;\n  */\n\n  // 14(state), 8(input)\n  size_t n_variables = 14 * T + 8 * (T - 1);\n\n  size_t n_constraints = 14 * T;\n\n  Dvector vars(n_variables);\n  for(int i=0;i<n_variables;i++){\n    vars[i] = 0.0;\n  }\n\n  vars[x_start] = x;\n  vars[y_start] = y;\n  vars[yaw_start] = yaw;\n  vars[vx_start] = vx;\n  vars[vy_start] = vy;\n  vars[omega_start] = omega;\n  vars[omega_w_fr_start] = omega_w_fr;\n  vars[omega_w_fl_start] = omega_w_fl;\n  vars[omega_w_rr_start] = omega_w_rr;\n  vars[omega_w_rl_start] = omega_w_rl;\n  vars[theta_s_fr_start] = theta_s_fr;\n  vars[theta_s_fl_start] = theta_s_fl;\n  vars[theta_s_rr_start] = theta_s_rr;\n  vars[theta_s_rl_start] = theta_s_rl;\n\n  Dvector vars_lower_bound(n_variables);\n  Dvector vars_upper_bound(n_variables);\n\n  for(int i=0;i<yaw_start;i++){\n    // x, y\n    vars_lower_bound[i] = -1.0e19;\n    vars_upper_bound[i] = 1.0e19;\n  }\n  for(int i=yaw_start;i<vx_start;i++){\n    // yaw\n    vars_lower_bound[i] = -1.0e19;\n    vars_upper_bound[i] = 1.0e19;\n  }\n  for(int i=vx_start;i<vy_start;i++){\n    // vx\n    vars_lower_bound[i] = 0;\n    vars_upper_bound[i] = MAX_VELOCITY;\n  }\n  for(int i=vy_start;i<omega_start;i++){\n    // vy\n    vars_lower_bound[i] = -MAX_VELOCITY;\n    vars_upper_bound[i] = MAX_VELOCITY;\n  }\n  for(int i=omega_start;i<omega_w_fr_start;i++){\n    // omega\n    vars_lower_bound[i] = -MAX_ANGULAR_VELOCITY;\n    vars_upper_bound[i] = MAX_ANGULAR_VELOCITY;\n  }\n  for(int i=omega_w_fr_start;i<theta_s_fr_start;i++){\n    vars_lower_bound[i] = -MAX_WHEEL_ANGULAR_VELOCITY;\n    vars_upper_bound[i] = MAX_WHEEL_ANGULAR_VELOCITY;\n  }\n  for(int i=theta_s_fr_start;i<domega_w_fr_start;i++){\n    vars_lower_bound[i] = -MAX_STEERING_ANGLE;\n    vars_upper_bound[i] = MAX_STEERING_ANGLE;\n  }\n  for(int i=domega_w_fr_start;i<dtheta_s_fr_start;i++){\n    vars_lower_bound[i] = -MAX_WHEEL_ANGULAR_ACCELERATION;\n    vars_upper_bound[i] = MAX_WHEEL_ANGULAR_ACCELERATION;\n  }\n  for(int i=dtheta_s_fr_start;i<n_variables;i++){\n    // 適当\n    vars_lower_bound[i] = -MAX_WHEEL_ANGULAR_VELOCITY * 23.1 / 56.1;\n    vars_upper_bound[i] = MAX_WHEEL_ANGULAR_VELOCITY * 23.1 / 56.1;\n  }\n\n  // 等式制約\n  Dvector constraints_lower_bound(n_constraints);\n  Dvector constraints_upper_bound(n_constraints);\n\n  for(int i=0;i<n_constraints;i++){\n    constraints_lower_bound[i] = 0.0;\n    constraints_upper_bound[i] = 0.0;\n  }\n\n  // t=0の設定\n  constraints_lower_bound[x_start] = x;\n  constraints_lower_bound[y_start] = y;\n  constraints_lower_bound[yaw_start] = yaw;\n  constraints_lower_bound[vx_start] = vx;\n  constraints_lower_bound[vy_start] = vy;\n  constraints_lower_bound[omega_start] = omega;\n  constraints_lower_bound[omega_w_fr_start] = omega_w_fr;\n  constraints_lower_bound[omega_w_fl_start] = omega_w_fl;\n  constraints_lower_bound[omega_w_rr_start] = omega_w_rr;\n  constraints_lower_bound[omega_w_rl_start] = omega_w_rl;\n  constraints_lower_bound[theta_s_fr_start] = theta_s_fr;\n  constraints_lower_bound[theta_s_fl_start] = theta_s_fl;\n  constraints_lower_bound[theta_s_rr_start] = theta_s_rr;\n  constraints_lower_bound[theta_s_rl_start] = theta_s_rl;\n\n  constraints_upper_bound[x_start] = x;\n  constraints_upper_bound[y_start] = y;\n  constraints_upper_bound[yaw_start] = yaw;\n  constraints_upper_bound[vx_start] = vx;\n  constraints_upper_bound[vy_start] = vy;\n  constraints_upper_bound[omega_start] = omega;\n  constraints_upper_bound[omega_w_fr_start] = omega_w_fr;\n  constraints_upper_bound[omega_w_fl_start] = omega_w_fl;\n  constraints_upper_bound[omega_w_rr_start] = omega_w_rr;\n  constraints_upper_bound[omega_w_rl_start] = omega_w_rl;\n  constraints_upper_bound[theta_s_fr_start] = theta_s_fr;\n  constraints_upper_bound[theta_s_fl_start] = theta_s_fl;\n  constraints_upper_bound[theta_s_rr_start] = theta_s_rr;\n  constraints_upper_bound[theta_s_rl_start] = theta_s_rl;\n\n  FG_eval fg_eval(ref_x, ref_y, ref_yaw);\n\n  std::string options;\n  options += \"Integer print_level  0\\n\";\n\n  options += \"Sparse  true        forward\\n\";\n  options += \"Sparse  true        reverse\\n\";\n\n  options += \"Numeric max_cpu_time          0.5\\n\";\n\n  CppAD::ipopt::solve_result<Dvector> solution;\n\n  std::cout << \"optimization start\" << std::endl;\n  CppAD::ipopt::solve<Dvector, FG_eval>(\n      options, vars, vars_lower_bound, vars_upper_bound, constraints_lower_bound,\n      constraints_upper_bound, fg_eval, solution);\n\n  std::cout << \"optimization end\" << std::endl;\n  ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success;\n  std::cout << solution.status << std::endl;\n  std::cout << ok << std::endl;\n\n  auto cost = solution.obj_value;\n  std::cout << \"Cost \" << cost << std::endl;\n\n  std::cout << \"solution.x.size() \" << solution.x.size() << std::endl;\n\n  if(ok){\n    result.clear();\n    failure_count = 0;\n    // 何故か0だとうまく行かない\n    result.push_back(solution.x[vx_start+1]);\n    result.push_back(solution.x[vy_start+1]);\n    result.push_back(solution.x[omega_start+1]);\n    //予測軌道\n    for(int i = 0; i < T-1; i++){\n      result.push_back(solution.x[x_start+i+1]);\n      result.push_back(solution.x[y_start+i+1]);\n      result.push_back(solution.x[yaw_start+i+1]);\n    }\n    int size = solution.x.size();\n    solution_buffer.reserve(size);\n    for(int i=0;i<size;i++){\n      solution_buffer[i] = solution.x[i];\n    }\n  }else{\n    if(failure_count < T - 1){\n      failure_count++;\n      std::cout << \"fail:\" << failure_count << std::endl;\n    }\n    // いいのか不明\n    if(solution_buffer.size() > 0){\n      result.push_back(solution_buffer[vx_start+1+failure_count]);\n      result.push_back(solution_buffer[vy_start+1+failure_count]);\n      result.push_back(solution_buffer[omega_start+1+failure_count]);\n      //予測軌道\n      for(int i = failure_count; i < T-1; i++){\n        result.push_back(solution.x[x_start+i+1]);\n        result.push_back(solution.x[y_start+i+1]);\n        result.push_back(solution.x[yaw_start+i+1]);\n      }\n    }else{\n      for(int i=0;i<3+3*(T-1);i++){\n        result.push_back(0);\n      }\n    }\n    /*\n    if(solution.status == CppAD::ipopt::solve_result<Dvector>::unknown){\n      result[0] = 0;\n      result[1] = 0;\n      result[2] = 0;\n      std::exit(1);\n    }\n    std::cout << \"cheat\" << std::endl;\n    */\n  }\n  std::cout << \"--- result ---\" << std::endl;\n  /*\n  for(int i=0;i<result.size();i++){\n    std::cout << result[i] << std::endl;\n  }\n  */\n  std::cout << solution_buffer[x_start+1] << std::endl;\n  std::cout << solution_buffer[y_start+1] << std::endl;\n  std::cout << solution_buffer[yaw_start+1] << std::endl;\n  std::cout << solution_buffer[vx_start+1] << std::endl;\n  std::cout << solution_buffer[vy_start+1] << std::endl;\n  std::cout << solution_buffer[omega_start+1] << std::endl;\n  std::cout << solution_buffer[omega_w_fr_start+1] << std::endl;\n  std::cout << solution_buffer[omega_w_fl_start+1] << std::endl;\n  std::cout << solution_buffer[omega_w_rr_start+1] << std::endl;\n  std::cout << solution_buffer[omega_w_rl_start+1] << std::endl;\n  std::cout << solution_buffer[theta_s_fr_start+1] << std::endl;\n  std::cout << solution_buffer[theta_s_fl_start+1] << std::endl;\n  std::cout << solution_buffer[theta_s_rr_start+1] << std::endl;\n  std::cout << solution_buffer[theta_s_rl_start+1] << std::endl;\n  return result;\n}\n\nFG_eval::FG_eval(Eigen::VectorXd ref_x, Eigen::VectorXd ref_y, Eigen::VectorXd ref_yaw)\n{\n  this->ref_x = ref_x;\n  this->ref_y = ref_y;\n  this->ref_yaw = ref_yaw;\n}\n\nvoid FG_eval::operator()(ADvector& fg, const ADvector& vars)\n{\n  std::cout << \"FG_eval() start\" << std::endl;\n  // cost\n  fg[0] = 0;\n  // state\n  for(int i=0;i<T-1;i++){\n    // pathとの距離\n    fg[0] += 10 * (CppAD::pow(vars[x_start + i] - ref_x[i], 2) + CppAD::pow(vars[y_start + i] - ref_y[i], 2));\n    // 向き\n    fg[0] += 10 * CppAD::pow(vars[yaw_start + i] - ref_yaw[i], 2);\n    // 速度\n    fg[0] += 5 * CppAD::pow(CppAD::pow(VREF, 2) - CppAD::pow(vars[vx_start + i], 2) - CppAD::pow(vars[vy_start + i], 2), 2);\n    // 角加速度\n    fg[0] += 1 * CppAD::pow(vars[omega_start + i] - vars[omega_start + i + 1], 2);\n    // 角速度\n    fg[0] += 1 * CppAD::pow(vars[omega_start + i], 2);\n  }\n  // input\n  for(int i=0;i<T-2;i++){\n    fg[0] += 1e-4 * CppAD::pow(vars[domega_w_fr_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[domega_w_fl_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[domega_w_rr_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[domega_w_rl_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[dtheta_s_fr_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[dtheta_s_fl_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[dtheta_s_rr_start + i], 2);\n    fg[0] += 1e-4 * CppAD::pow(vars[dtheta_s_rl_start + i], 2);\n  }\n\n  std::cout << \"constrains start\" << std::endl;\n  //constraint\n  //初期状態\n  fg[1 + x_start] = vars[x_start];\n  fg[1 + y_start] = vars[y_start];\n  fg[1 + yaw_start] = vars[yaw_start];\n  fg[1 + vx_start] = vars[vx_start];\n  fg[1 + vy_start] = vars[vy_start];\n  fg[1 + omega_start] = vars[omega_start];\n  fg[1 + omega_w_fr_start] = vars[omega_w_fr_start];\n  fg[1 + omega_w_fl_start] = vars[omega_w_fl_start];\n  fg[1 + omega_w_rr_start] = vars[omega_w_rr_start];\n  fg[1 + omega_w_rl_start] = vars[omega_w_rl_start];\n  fg[1 + theta_s_fr_start] = vars[theta_s_fr_start];\n  fg[1 + theta_s_fl_start] = vars[theta_s_fl_start];\n  fg[1 + theta_s_rr_start] = vars[theta_s_rr_start];\n  fg[1 + theta_s_rl_start] = vars[theta_s_rl_start];\n\n  std::cout << \"constraints loop start\" << std::endl;\n\n  for(int i=0;i<T-1;i++){\n    //t+1\n    AD<double> x1 = vars[x_start + i + 1];\n    AD<double> y1 = vars[y_start + i + 1];\n    AD<double> yaw1 = vars[yaw_start + i + 1];\n    AD<double> vx1 = vars[vx_start + i + 1];\n    AD<double> vy1 = vars[vy_start + i + 1];\n    AD<double> omega1 = vars[omega_start + i + 1];\n    AD<double> omega_w_fr1 = vars[omega_w_fr_start + i + 1];\n    AD<double> omega_w_fl1 = vars[omega_w_fl_start + i + 1];\n    AD<double> omega_w_rr1 = vars[omega_w_rr_start + i + 1];\n    AD<double> omega_w_rl1 = vars[omega_w_rl_start + i + 1];\n    AD<double> theta_s_fr1 = vars[theta_s_fr_start + i + 1];\n    AD<double> theta_s_fl1 = vars[theta_s_fl_start + i + 1];\n    AD<double> theta_s_rr1 = vars[theta_s_rr_start + i + 1];\n    AD<double> theta_s_rl1 = vars[theta_s_rl_start + i + 1];\n    //t\n    AD<double> x0 = vars[x_start + i];\n    AD<double> y0 = vars[y_start + i];\n    AD<double> yaw0 = vars[yaw_start + i];\n    AD<double> vx0 = vars[vx_start + i];\n    AD<double> vy0 = vars[vy_start + i];\n    AD<double> omega0 = vars[omega_start + i];\n    AD<double> omega_w_fr0 = vars[omega_w_fr_start + i];\n    AD<double> omega_w_fl0 = vars[omega_w_fl_start + i];\n    AD<double> omega_w_rr0 = vars[omega_w_rr_start + i];\n    AD<double> omega_w_rl0 = vars[omega_w_rl_start + i];\n    AD<double> theta_s_fr0 = vars[theta_s_fr_start + i];\n    AD<double> theta_s_fl0 = vars[theta_s_fl_start + i];\n    AD<double> theta_s_rr0 = vars[theta_s_rr_start + i];\n    AD<double> theta_s_rl0 = vars[theta_s_rl_start + i];\n    //入力ホライゾンはt+1を考慮しない\n    AD<double> domega_w_fr0 = vars[domega_w_fr_start + i];\n    AD<double> domega_w_fl0 = vars[domega_w_fl_start + i];\n    AD<double> domega_w_rr0 = vars[domega_w_rr_start + i];\n    AD<double> domega_w_rl0 = vars[domega_w_rl_start + i];\n    AD<double> dtheta_s_fr0 = vars[dtheta_s_fr_start + i];\n    AD<double> dtheta_s_fl0 = vars[dtheta_s_fl_start + i];\n    AD<double> dtheta_s_rr0 = vars[dtheta_s_rr_start + i];\n    AD<double> dtheta_s_rl0 = vars[dtheta_s_rl_start + i];\n\n    //制約\n    fg[2 + x_start + i] = x1 - (x0 + (vx0 * CppAD::cos(yaw0) - vy0 * CppAD::sin(yaw0)) * DT);\n    fg[2 + y_start + i] = y1 - (y0 + (vx0 * CppAD::sin(yaw0) + vy0 * CppAD::cos(yaw0)) * DT);\n    fg[2 + yaw_start + i] = yaw1 - (yaw0 + omega0 * DT);\n    fg[2 + omega_w_fr_start + i] = omega_w_fr1 - (omega_w_fr0 + domega_w_fr0 * DT);\n    fg[2 + omega_w_fl_start + i] = omega_w_fl1 - (omega_w_fl0 + domega_w_fl0 * DT);\n    fg[2 + omega_w_rr_start + i] = omega_w_rr1 - (omega_w_rr0 + domega_w_rr0 * DT);\n    fg[2 + omega_w_rl_start + i] = omega_w_rl1 - (omega_w_rl0 + domega_w_rl0 * DT);\n    fg[2 + theta_s_fr_start + i] = theta_s_fr1 - (theta_s_fr0 + dtheta_s_fr0 * DT);\n    fg[2 + theta_s_fl_start + i] = theta_s_fl1 - (theta_s_fl0 + dtheta_s_fl0 * DT);\n    fg[2 + theta_s_rr_start + i] = theta_s_rr1 - (theta_s_rr0 + dtheta_s_rr0 * DT);\n    fg[2 + theta_s_rl_start + i] = theta_s_rl1 - (theta_s_rl0 + dtheta_s_rl0 * DT);\n    AD<double> v_w_fr1 = WHEEL_RADIUS * omega_w_fr1;\n    AD<double> v_w_fl1 = WHEEL_RADIUS * omega_w_fl1;\n    AD<double> v_w_rr1 = WHEEL_RADIUS * omega_w_rr1;\n    AD<double> v_w_rl1 = WHEEL_RADIUS * omega_w_rl1;\n    fg[2 + vx_start + i] = vx1 - (inversed_matrix(0, 0) * v_w_fr1 * CppAD::cos(theta_s_fr1) + inversed_matrix(0, 1) * v_w_fr1 * CppAD::sin(theta_s_fr1) + inversed_matrix(0, 2) * v_w_fl1 * CppAD::cos(theta_s_fl1) + inversed_matrix(0, 3) * v_w_fl1 * CppAD::sin(theta_s_fl1) + inversed_matrix(0, 4) * v_w_rl1 * CppAD::cos(theta_s_rl1) + inversed_matrix(0, 5) * v_w_rl1 * CppAD::sin(theta_s_rl1) + inversed_matrix(0, 6) * v_w_rr1 * CppAD::cos(theta_s_rr1) + inversed_matrix(0, 7) * v_w_rr1 * CppAD::sin(theta_s_rr1));\n    fg[2 + vy_start + i] = vy1 - (inversed_matrix(1, 0) * v_w_fr1 * CppAD::cos(theta_s_fr1) + inversed_matrix(1, 1) * v_w_fr1 * CppAD::sin(theta_s_fr1) + inversed_matrix(1, 2) * v_w_fl1 * CppAD::cos(theta_s_fl1) + inversed_matrix(1, 3) * v_w_fl1 * CppAD::sin(theta_s_fl1) + inversed_matrix(1, 4) * v_w_rl1 * CppAD::cos(theta_s_rl1) + inversed_matrix(1, 5) * v_w_rl1 * CppAD::sin(theta_s_rl1) + inversed_matrix(1, 6) * v_w_rr1 * CppAD::cos(theta_s_rr1) + inversed_matrix(1, 7) * v_w_rr1 * CppAD::sin(theta_s_rr1));\n    fg[2 + omega_start + i] = omega1 - (inversed_matrix(2, 0) * v_w_fr1 * CppAD::cos(theta_s_fr1) + inversed_matrix(2, 1) * v_w_fr1 * CppAD::sin(theta_s_fr1) + inversed_matrix(2, 2) * v_w_fl1 * CppAD::cos(theta_s_fl1) + inversed_matrix(2, 3) * v_w_fl1 * CppAD::sin(theta_s_fl1) + inversed_matrix(2, 4) * v_w_rl1 * CppAD::cos(theta_s_rl1) + inversed_matrix(2, 5) * v_w_rl1 * CppAD::sin(theta_s_rl1) + inversed_matrix(2, 6) * v_w_rr1 * CppAD::cos(theta_s_rr1) + inversed_matrix(2, 7) * v_w_rr1 * CppAD::sin(theta_s_rr1));\n  }\n  std::cout << \"FG_eval() end\" << std::endl;\n}\n\nMPCPathTracker::MPCPathTracker(void)\n{\n  velocity_pub = nh.advertise<geometry_msgs::Twist>(VELOCITY_TOPIC_NAME, 100);\n  path_pub = nh.advertise<geometry_msgs::PoseArray>(\"/mpc_path\", 100);\n  path_sub = nh.subscribe(INTERMEDIATE_PATH_TOPIC_NAME, 100, &MPCPathTracker::path_callback, this);\n  path_x = Eigen::VectorXd::Zero(T);\n  path_y = Eigen::VectorXd::Zero(T);\n  path_yaw = Eigen::VectorXd::Zero(T);\n}\n\nvoid MPCPathTracker::path_callback(const nav_msgs::PathConstPtr& msg)\n{\n  path = *msg;\n}\n\nvoid MPCPathTracker::process(void)\n{\n  std::cout << \"=== fwdis mpc ===\" << std::endl;\n  ros::Time start_time = ros::Time::now();\n  bool transformed = false;\n  geometry_msgs::PoseStamped pose;\n  try{\n    listener.lookupTransform(WORLD_FRAME, ROBOT_FRAME, ros::Time(0), _transform);\n    tf::transformStampedTFToMsg(_transform, transform);\n    current_pose.header = transform.header;\n    current_pose.pose.position.x = transform.transform.translation.x;\n    current_pose.pose.position.y = transform.transform.translation.y;\n    current_pose.pose.orientation = transform.transform.rotation;\n    pose.header = current_pose.header;\n    pose.pose.position.x = 0;\n    pose.pose.position.y = 0;\n    pose.pose.orientation = transform.transform.rotation;\n    transformed = true;\n  }catch(tf::TransformException &ex){\n    std::cout << ex.what() << std::endl;\n  }\n\n  if(!path.poses.empty() && transformed){\n    if(first_transform){\n      last_time = ros::Time::now().toSec();\n      first_transform = false;\n    }else{\n      //std::cout << current_pose << std::endl;\n      double current_time = ros::Time::now().toSec();\n      double dt = current_time - last_time;\n      last_time = current_time;\n      double dx_map = current_pose.pose.position.x - previous_pose.pose.position.x;\n      double dy_map = current_pose.pose.position.y - previous_pose.pose.position.y;\n      double dyaw = tf::getYaw(current_pose.pose.orientation) - tf::getYaw(previous_pose.pose.orientation);\n      double theta = tf::getYaw(previous_pose.pose.orientation);\n      double dx_base = dx_map * cos(-theta) - dy_map * sin(-theta);\n      double dy_base = dx_map * sin(-theta) + dy_map * cos(-theta);\n      double vx_base = dx_base / dt;\n      double vy_base = dy_base / dt;\n      double omega = dyaw / dt;\n      Eigen::Vector2d base_velocity;\n      base_velocity << vx_base, vy_base;\n      Eigen::Matrix2d rotation_matrix;\n      rotation_matrix << cos(dyaw), -sin(dyaw),\n                         sin(dyaw),  cos(dyaw);\n      Eigen::Vector2d _robot_velocity = rotation_matrix.inverse() * base_velocity;\n      double vx = _robot_velocity(0);\n      double vy = _robot_velocity(1);\n      Eigen::VectorXd current_wheel_velocity;\n      current_wheel_velocity.resize(8, 1);\n      Eigen::Vector3d current_velocity;\n      current_velocity << vx, vy, omega;\n      current_wheel_velocity = forward_matrix * current_velocity;\n      double s_fr = atan2(current_wheel_velocity(1), current_wheel_velocity(0));\n      double w_fr = sqrt(current_wheel_velocity(0) * current_wheel_velocity(0) + current_wheel_velocity(1) * current_wheel_velocity(1)) / WHEEL_RADIUS;\n      if(s_fr > MAX_STEERING_ANGLE){\n        s_fr -= M_PI;\n        w_fr = -w_fr;\n      }else if(s_fr < -MAX_STEERING_ANGLE){\n        s_fr += M_PI;\n        w_fr = -w_fr;\n      }\n      double s_fl = atan2(current_wheel_velocity(3), current_wheel_velocity(2));\n      double w_fl = sqrt(current_wheel_velocity(2) * current_wheel_velocity(2) + current_wheel_velocity(3) * current_wheel_velocity(3)) / WHEEL_RADIUS;\n      if(s_fl > MAX_STEERING_ANGLE){\n        s_fl -= M_PI;\n        w_fl = -w_fl;\n      }else if(s_fl < -MAX_STEERING_ANGLE){\n        s_fl += M_PI;\n        w_fl = -w_fl;\n      }\n      double s_rl = atan2(current_wheel_velocity(5), current_wheel_velocity(4));\n      double w_rl = sqrt(current_wheel_velocity(4) * current_wheel_velocity(4) + current_wheel_velocity(5) * current_wheel_velocity(5)) / WHEEL_RADIUS;\n      if(s_rl > MAX_STEERING_ANGLE){\n        s_rl -= M_PI;\n        w_rl = -w_rl;\n      }else if(s_rl < -MAX_STEERING_ANGLE){\n        s_rl += M_PI;\n        w_rl = -w_rl;\n      }\n      double s_rr = atan2(current_wheel_velocity(7), current_wheel_velocity(6));\n      double w_rr = sqrt(current_wheel_velocity(6) * current_wheel_velocity(6) + current_wheel_velocity(7) * current_wheel_velocity(7)) / WHEEL_RADIUS;\n      if(s_rr > MAX_STEERING_ANGLE){\n        s_rr -= M_PI;\n        w_rr = -w_rr;\n      }else if(s_rr < -MAX_STEERING_ANGLE){\n        s_rr += M_PI;\n        w_rr = -w_rr;\n      }\n      //std::cout << \"current_wheel_velocity\" << std::endl;\n      //std::cout << current_wheel_velocity << std::endl;\n\n      Eigen::VectorXd state(14);\n      state << pose.pose.position.x, pose.pose.position.y, tf::getYaw(pose.pose.orientation), vx, vy, omega, w_fr, w_fl, w_rr, w_rl, s_fr, s_fl, s_rr, s_rl;\n      std::cout << \"state\" << std::endl;\n      std::cout << state << std::endl;\n      std::cout << \"path to vector\" << std::endl;\n      path_to_vector();\n      /*\n      std::cout << \"path_x\" << std::endl;\n      std::cout << path_x << std::endl;\n      std::cout << \"path_y\" << std::endl;\n      std::cout << path_y << std::endl;\n      std::cout << \"path_yaw\" << std::endl;\n      std::cout << path_yaw << std::endl;\n      */\n      std::cout << \"solving\" << std::endl;\n      auto result = mpc.solve(state, path_x, path_y, path_yaw);\n      std::cout << \"solved\" << std::endl;\n      velocity.linear.x = result[0];\n      velocity.linear.y = result[1];\n      velocity.angular.z = result[2];\n      std::cout << velocity << std::endl;\n      velocity_pub.publish(velocity);\n      // mpc表示\n      geometry_msgs::PoseArray mpc_path;\n      mpc_path.header.frame_id = ROBOT_FRAME;\n      double yaw0 = tf::getYaw(pose.pose.orientation);\n      for(int i=0;i<T-1;i++){\n        geometry_msgs::Pose temp;\n        //temp.position.x = result[3+3*i] * cos(-yaw0) - result[4+3*i] * sin(-yaw0);\n        //temp.position.y = result[3+3*i] * sin(-yaw0) + result[4+3*i] * cos(-yaw0);\n        temp.position.x = result[3+3*i];\n        temp.position.y = result[4+3*i];\n        //temp.orientation = tf::createQuaternionMsgFromYaw(result[5+3*i] - yaw0);\n        temp.orientation = tf::createQuaternionMsgFromYaw(result[5+3*i]);\n        mpc_path.poses.push_back(temp);\n      }\n      path_pub.publish(mpc_path);\n      // ~mpc表示\n      path.poses.erase(path.poses.begin());\n    }\n  }\n  previous_pose = current_pose;\n  std::cout << ros::Time::now() - start_time << \"[s]\" << std::endl;\n}\n\nvoid MPCPathTracker::path_to_vector(void)\n{\n  int m = VREF * DT / RESOLUTION + 1;// TODO:delete 1\n  int index = 0;\n  for(int i=0;i<T;i++){\n    if(i*m<path.poses.size()){\n      index = i*m;\n      path_x[i] = path.poses[index].pose.position.x;\n      path_y[i] = path.poses[index].pose.position.y;\n      path_yaw[i] = tf::getYaw(path.poses[index].pose.orientation);\n    }else{\n      path_x[i] = path.poses[path.poses.size() - 1].pose.position.x;\n      path_y[i] = path.poses[path.poses.size() - 1].pose.position.y;\n      path_yaw[i] = tf::getYaw(path.poses[path.poses.size() - 1].pose.orientation);\n    }\n  }\n}\n\ndouble min_distance(nav_msgs::Path& path, geometry_msgs::PoseStamped& pose)\n{\n  int length = path.poses.size();\n  double min_distance = 100;\n  for(int i=0;i<length;i++){\n    double distance = get_distance(path.poses[i], pose);\n    if(min_distance > distance){\n      min_distance = distance;\n    }\n  }\n  return min_distance;\n}\n\ndouble get_distance(geometry_msgs::PoseStamped& pose0, geometry_msgs::PoseStamped& pose1)\n{\n  return sqrt((pose0.pose.position.x - pose1.pose.position.x) * (pose0.pose.position.x - pose1.pose.position.x) + (pose0.pose.position.y - pose1.pose.position.y) * (pose0.pose.position.y - pose1.pose.position.y));\n}\n\n", "meta": {"hexsha": "ee0510ceb1ba91479e88e2c316a1772e6a851c74", "size": 30585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fwdis_mpc.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/fwdis_mpc.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/fwdis_mpc.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": 38.2790988736, "max_line_length": 519, "alphanum_fraction": 0.6707863332, "num_tokens": 9689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5573990663449727}}
{"text": "/*\n * smaxlayer.cpp\n *\n * This is SOFTMAX layer\n *\n *  Feed-forward:\n *    a(l, i) = softmax(a(l), i) = exp(a(l-1, i) / sum(exp(a(l-1)))\n *\n *  Back propagation:\n *    gradient(C, a(l)) = gradient(C, a(l+1)) * M(a(l + 1))\n *    where M(a(l), i, j) = softmax(a(l + 1), i) * (sigma(i, j) - softmax(a(l + 1), j)) where sigma(i, j) = 1 for i=j and 0 otherwise\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"smaxlayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// SoftmaxLayer_Context and SoftmaxLayer_TrainingContext implementations\n//\nnamespace yann {\n\ntypedef Layer::Context SoftmaxLayer_Context;\n\nclass SoftmaxLayer_TrainingContext :\n    public SoftmaxLayer_Context\n{\n  typedef SoftmaxLayer_Context Base;\n\n  friend class SoftmaxLayer;\n\npublic:\n  SoftmaxLayer_TrainingContext(const MatrixSize & output_size,\n                               const MatrixSize & batch_size,\n                               const MatrixSize & input_size) :\n    Base(output_size, batch_size),\n    _tmp(input_size)\n  {\n  }\n\n  SoftmaxLayer_TrainingContext(const RefVectorBatch & output,\n                               const MatrixSize & input_size) :\n    Base(output),\n    _tmp(input_size)\n  {\n  }\n\nprotected:\n  Vector _tmp;\n}; // class SoftmaxLayer_TrainingContext\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::SoftmaxLayer implementation\n//\nvoid yann::SoftmaxLayer::softmax_plus_equal(const RefConstVector & input, RefVector output, const Value & beta)\n{\n  YANN_CHECK(is_same_size(input, output));\n  YANN_CHECK_EQ(input.rows(), 1); // RowMajor layout, breaks for ColMajor\n\n  Value max = input.maxCoeff(); // adjust the computations to avoid overflowing\n  Value sum = exp((input.array() - max) * beta).sum();\n  output.array() += (exp((input.array() - max) * beta)) / sum;\n}\n\n\n// gradient_input = softmax_derivative(input) * gradient_output\n//\n// where\n//    softmax_derivative(input, ii, jj) = - softmax(input, ii) * softmax(input, jj) if ii != jj\n//    softmax_derivative(input, ii, jj) = softmax(ii) * (1 - softmax(ii)) if ii == jj\n//\n// gradient_input(ii) = sum(softmax_derivative(input, ii, jj) * gradient_output(jj))\n//\n// gradient_input(ii) = sum(ii != jj, - softmax(input, ii) * softmax(input, jj) * gradient_output(jj)) +\n//                      softmax(ii) * (1 - softmax(ii)) * * gradient_output(ii)\n//\n// gradient_input(ii) = sum(ii != jj, - softmax(input, ii) * softmax(input, jj) * gradient_output(jj)) +\n//                      softmax(ii) * gradient_output(ii) - softmax(ii) * softmax(ii) * gradient_output(ii)\n//\n// gradient_input(ii) = softmax(input, ii) * (sum(-softmax(input, jj) * gradient_output(jj)) + gradient_output(ii))\n//\nvoid yann::SoftmaxLayer::softmax_gradient(\n    const RefConstVector & input,\n    const RefConstVector & gradient_output,\n    RefVector tmp,\n    RefVector gradient_input,\n    const Value & beta)\n{\n  YANN_CHECK(is_same_size(input, gradient_output));\n  YANN_CHECK(is_same_size(input, tmp));\n  YANN_CHECK(is_same_size(input, gradient_input));\n\n  tmp.setZero();\n  softmax_plus_equal(input, tmp, beta);\n\n  Value sum = (tmp.array() * gradient_output.array()).sum();\n  gradient_input = beta * tmp.array() * (gradient_output.array() - sum);\n}\n\nyann::SoftmaxLayer::SoftmaxLayer(const MatrixSize & size, const Value & beta) :\n    _size(size),\n    _beta(beta)\n{\n  YANN_CHECK_GT(size, 0);\n}\n\nyann::SoftmaxLayer::~SoftmaxLayer()\n{\n}\n\n// Layer overwrites\nstd::string yann::SoftmaxLayer::get_name() const\n{\n  return \"SoftmaxLayer\";\n}\n\nbool yann::SoftmaxLayer::is_equal(const Layer & other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto the_other = dynamic_cast<const SoftmaxLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  if(_size != the_other->_size) {\n    return false;\n  }\n  return true;\n}\n\nMatrixSize yann::SoftmaxLayer::get_input_size() const\n{\n  return _size;\n}\n\nMatrixSize yann::SoftmaxLayer::get_output_size() const\n{\n  return _size;\n}\n\nunique_ptr<Layer::Context> yann::SoftmaxLayer::create_context(const MatrixSize & batch_size) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<SoftmaxLayer_Context>(get_output_size(), batch_size);\n}\nunique_ptr<Layer::Context> yann::SoftmaxLayer::create_context(const RefVectorBatch & output) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<SoftmaxLayer_Context>(output);\n}\nunique_ptr<Layer::Context> yann::SoftmaxLayer::create_training_context(\n    const MatrixSize & batch_size,\n    const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<SoftmaxLayer_TrainingContext>(get_output_size(), batch_size, get_input_size());\n}\nunique_ptr<Layer::Context> yann::SoftmaxLayer::create_training_context(\n    const RefVectorBatch & output,\n    const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<SoftmaxLayer_TrainingContext>(output, get_input_size());\n}\n\nvoid yann::SoftmaxLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<SoftmaxLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(input), 0);\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_LE(get_batch_size(input), get_batch_size(ctx->get_output()));\n  YANN_CHECK_EQ(get_batch_item_size(ctx->get_output()), get_output_size());\n\n  RefVectorBatch output = ctx->get_output();\n  switch(mode) {\n  case Operation_Assign:\n    output.setZero();\n    break;\n  case Operation_PlusEqual:\n    // do nothing\n    break;\n  }\n  const auto batch_size = get_batch_size(input);\n  for(MatrixSize ii = 0; ii < batch_size; ++ii) {\n    softmax_plus_equal(get_batch(input, ii), get_batch(output, ii), _beta);\n  }\n}\n\nvoid yann::SoftmaxLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  throw runtime_error(\"SoftmaxLayer::feedforward() is not implemented for sparse vectors\");\n}\n\nvoid yann::SoftmaxLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  YANN_CHECK(is_valid());\n  YANN_SLOW_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_SLOW_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(input), get_input_size());\n\n  auto ctx = static_cast<SoftmaxLayer_TrainingContext*>(context);\n  YANN_CHECK(ctx);\n\n  // nothing to do for the softmax layer itself\n\n  // we don't need to calculate the gradient(C, a(l)) for the \"first\" layer (actual inputs)\n  if(gradient_input) {\n    YANN_SLOW_CHECK_EQ(get_batch_item_size(input), get_batch_item_size(*gradient_input));\n    YANN_SLOW_CHECK_EQ(get_batch_size(input), get_batch_size(*gradient_input));\n\n    const auto batch_size = get_batch_size(input);\n    for(MatrixSize ii = 0; ii < batch_size; ++ii) {\n      softmax_gradient(\n          get_batch(input, ii),\n          get_batch(gradient_output, ii),\n          ctx->_tmp,\n          get_batch(*gradient_input, ii),\n          _beta);\n    }\n  }\n}\n\nvoid yann::SoftmaxLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  throw runtime_error(\"SoftmaxLayer::backprop() is not implemented for sparse vectors\");\n}\n\nvoid yann::SoftmaxLayer::init(enum InitMode mode, boost::optional<InitContext> init_context)\n{\n  // nothing to do\n}\n\nvoid yann::SoftmaxLayer::update(Context * context, const size_t & tests_num)\n{\n  // auto ctx = dynamic_cast<SoftmaxLayer_Context *>(context);\n  // YANN_CHECK(ctx);\n  // nothing to do\n}\n\nvoid yann::SoftmaxLayer::read(std::istream & is)\n{\n  Base::read(is);\n\n  // nothing to do\n}\n\nvoid yann::SoftmaxLayer::write(std::ostream & os) const\n{\n  Base::write(os);\n  // nothing to do\n}\n\n", "meta": {"hexsha": "2828b925d1fdc3feb177006921384817ab1619cf", "size": 8231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/smaxlayer.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/layers/smaxlayer.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/smaxlayer.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5017921147, "max_line_length": 133, "alphanum_fraction": 0.6842424979, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5573943833238215}}
{"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/*\n * MIT License\n *\n * Copyright (c) 2017 Zhenqiang.Ying\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 \"precomp.hpp\"\n\n#ifdef HAVE_EIGEN\n#include <Eigen/Sparse>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc.hpp>\n#endif\n\nnamespace cv {\nnamespace intensity_transform {\n\n#ifdef HAVE_EIGEN\nstatic void diff(const Mat_<float>& src, Mat_<float>& srcVDiff, Mat_<float>& srcHDiff)\n{\n    srcVDiff = Mat_<float>(src.size());\n    for (int i = 0; i < src.rows; i++)\n    {\n        if (i < src.rows-1)\n        {\n            for (int j = 0; j < src.cols; j++)\n            {\n                srcVDiff(i,j) = src(i+1,j) - src(i,j);\n            }\n        }\n        else\n        {\n            for (int j = 0; j < src.cols; j++)\n            {\n                srcVDiff(i,j) = src(0,j) - src(i,j);\n            }\n        }\n    }\n\n    srcHDiff = Mat_<float>(src.size());\n    for (int j = 0; j < src.cols-1; j++)\n    {\n        for (int i = 0; i < src.rows; i++)\n        {\n            srcHDiff(i,j) = src(i,j+1) - src(i,j);\n        }\n    }\n    for (int i = 0; i < src.rows; i++)\n    {\n        srcHDiff(i,src.cols-1) = src(i,0) - src(i,src.cols-1);\n    }\n}\n\nstatic void computeTextureWeights(const Mat_<float>& x, float sigma, float sharpness, Mat_<float>& W_h, Mat_<float>& W_v)\n{\n    Mat_<float> dt0_v, dt0_h;\n    diff(x, dt0_v, dt0_h);\n\n    Mat_<float> gauker_h;\n    Mat_<float> kernel_h = Mat_<float>::ones(1, static_cast<int>(sigma));\n    filter2D(dt0_h, gauker_h, -1, kernel_h, Point(-1,-1), 0, BORDER_CONSTANT);\n\n    Mat_<float> gauker_v;\n    Mat_<float> kernel_v = Mat_<float>::ones(static_cast<int>(sigma), 1);\n    filter2D(dt0_v, gauker_v, -1, kernel_v, Point(-1,-1), 0, BORDER_CONSTANT);\n\n    W_h = Mat_<float>(gauker_h.size());\n    W_v = Mat_<float>(gauker_v.size());\n\n    for (int i = 0; i < gauker_h.rows; i++)\n    {\n        for (int j = 0; j < gauker_h.cols; j++)\n        {\n            W_h(i,j) = 1 / (std::abs(gauker_h(i,j)) * std::abs(dt0_h(i,j)) + sharpness);\n            W_v(i,j) = 1 / (std::abs(gauker_v(i,j)) * std::abs(dt0_v(i,j)) + sharpness);\n        }\n    }\n}\n\ntemplate <class numeric_t>\nstatic Eigen::SparseMatrix<numeric_t> spdiags(const Eigen::Matrix<numeric_t,-1,-1> &B,\n                                              const Eigen::VectorXi &d, int m, int n) {\n    typedef Eigen::Triplet<numeric_t> triplet_t;\n    std::vector<triplet_t> triplets;\n    triplets.reserve(static_cast<size_t>(std::min(m,n)*d.size()));\n\n    for (int k = 0; k < d.size(); ++k) {\n        int diag = d(k);  // get diagonal\n        int i_start = std::max(-diag, 0); // get row of 1st element\n        int i_end = std::min(m, m-diag-(m-n)); // get row of last element\n        int j = -std::min(0, -diag); // get col of 1st element\n        int B_i; // start index i in matrix B\n        if (m < n) {\n            B_i = std::max(-diag,0); // m < n\n        } else {\n            B_i = std::max(0,diag); // m >= n\n        }\n        for (int i = i_start; i < i_end; ++i, ++j, ++B_i) {\n            triplets.push_back( {i, j,  B(B_i,k)} );\n        }\n    }\n    Eigen::SparseMatrix<numeric_t> A(m,n);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n    return A;\n}\n\n\nstatic Mat solveLinearEquation(const Mat_<float>& img, Mat_<float>& W_h_, Mat_<float>& W_v_, float lambda)\n{\n    Eigen::MatrixXf W_h;\n    cv2eigen(W_h_, W_h);\n    Eigen::MatrixXf tempx(W_h.rows(), W_h.cols());\n    tempx.block(0, 1, tempx.rows(), tempx.cols()-1) = W_h.block(0, 0, W_h.rows(), W_h.cols()-1);\n    for (Eigen::Index i = 0; i < tempx.rows(); i++)\n    {\n        tempx(i,0) = W_h(i, W_h.cols()-1);\n    }\n\n    Eigen::MatrixXf W_v;\n    cv2eigen(W_v_, W_v);\n    Eigen::MatrixXf tempy(W_v.rows(), W_v.cols());\n    tempy.block(1, 0, tempx.rows()-1, tempx.cols()) = W_v.block(0, 0, W_v.rows()-1, W_v.cols());\n    for (Eigen::Index j = 0; j < tempy.cols(); j++)\n    {\n        tempy(0,j) = W_v(W_v.rows()-1, j);\n    }\n\n\n    Eigen::VectorXf dx(W_h.rows()*W_h.cols());\n    Eigen::VectorXf dy(W_v.rows()*W_v.cols());\n\n    Eigen::VectorXf dxa(tempx.rows()*tempx.cols());\n    Eigen::VectorXf dya(tempy.rows()*tempy.cols());\n\n    //Flatten in a col-major order\n    for (Eigen::Index j = 0; j < W_h.cols(); j++)\n    {\n        for (Eigen::Index i = 0; i < W_h.rows(); i++)\n        {\n            dx(j*W_h.rows() + i) = -lambda*W_h(i,j);\n            dy(j*W_h.rows() + i) = -lambda*W_v(i,j);\n\n            dxa(j*W_h.rows() + i) = -lambda*tempx(i,j);\n            dya(j*W_h.rows() + i) = -lambda*tempy(i,j);\n        }\n    }\n\n    tempx.setZero();\n    tempx.col(0) = W_h.col(W_h.cols()-1);\n\n    tempy.setZero();\n    tempy.row(0) = W_v.row(W_v.rows()-1);\n\n    W_h.col(W_h.cols()-1).setZero();\n    W_v.row(W_v.rows()-1).setZero();\n\n    Eigen::VectorXf dxd1(tempx.rows()*tempx.cols());\n    Eigen::VectorXf dyd1(tempy.rows()*tempy.cols());\n    Eigen::VectorXf dxd2(W_h.rows()*W_h.cols());\n    Eigen::VectorXf dyd2(W_v.rows()*W_v.cols());\n\n    //Flatten in a col-major order\n    for (Eigen::Index j = 0; j < tempx.cols(); j++)\n    {\n        for (Eigen::Index i = 0; i < tempx.rows(); i++)\n        {\n            dxd1(j*tempx.rows() + i) = -lambda*tempx(i,j);\n            dyd1(j*tempx.rows() + i) = -lambda*tempy(i,j);\n\n            dxd2(j*tempx.rows() + i) = -lambda*W_h(i,j);\n            dyd2(j*tempx.rows() + i) = -lambda*W_v(i,j);\n        }\n    }\n\n    Eigen::MatrixXf dxd(dxd1.rows(), dxd1.cols()+dxd2.cols());\n    dxd << dxd1, dxd2;\n\n    Eigen::MatrixXf dyd(dyd1.rows(), dyd1.cols()+dyd2.cols());\n    dyd << dyd1, dyd2;\n\n    const int k = img.rows*img.cols;\n    const int r = img.rows;\n    Eigen::Matrix<int, 2, 1> diagx_idx;\n    diagx_idx << -k+r, -r;\n    Eigen::SparseMatrix<float> Ax = spdiags(dxd, diagx_idx, k, k);\n\n    Eigen::Matrix<int, 2, 1> diagy_idx;\n    diagy_idx << -r+1, -1;\n    Eigen::SparseMatrix<float> Ay = spdiags(dyd, diagy_idx, k, k);\n\n    Eigen::MatrixXf D = (dx + dy + dxa + dya);\n    D = Eigen::MatrixXf::Ones(D.rows(), D.cols()) - D;\n\n    Eigen::Matrix<int, 1, 1> diag_idx_zero;\n    diag_idx_zero << 0;\n    Eigen::SparseMatrix<float> A = (Ax + Ay) + Eigen::SparseMatrix<float>((Ax + Ay).transpose()) + spdiags(D, diag_idx_zero, k, k);\n\n    //CG solver of Eigen\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower|Eigen::Upper, Eigen::IncompleteCholesky<float> > cg;\n    cg.setTolerance(0.1f);\n    cg.setMaxIterations(50);\n    cg.compute(A);\n    Mat_<float> img_t = img.t();\n    Eigen::Map<const Eigen::VectorXf> tin(img_t.ptr<float>(), img_t.rows*img_t.cols);\n    Eigen::VectorXf x = cg.solve(tin);\n\n    Mat_<float> tout(img.rows, img.cols);\n    tout.forEach(\n        [&](float &pixel, const int * position) -> void\n        {\n            pixel = x(position[1]*img.rows + position[0]);\n        }\n    );\n\n    return tout;\n}\n\nstatic Mat_<float> tsmooth(const Mat_<float>& src, float lambda=0.01f, float sigma=3.0f, float sharpness=0.001f)\n{\n    Mat_<float> W_h, W_v;\n    computeTextureWeights(src, sigma, sharpness, W_h, W_v);\n\n    Mat_<float> S = solveLinearEquation(src, W_h, W_v, lambda);\n\n    return S;\n}\n\nstatic Mat_<float> rgb2gm(const Mat_<Vec3f>& I)\n{\n    Mat_<float> gm(I.rows, I.cols);\n    gm.forEach(\n        [&](float &pixel, const int * position) -> void\n        {\n            pixel = std::pow(I(position[0], position[1])[0]*I(position[0], position[1])[1]*I(position[0], position[1])[2], 1/3.0f);\n        }\n    );\n\n    return gm;\n}\n\nstatic Mat_<float> applyK(const Mat_<float>& I, float k, float a=-0.3293f, float b=1.1258f) {\n    float beta = std::exp((1 - std::pow(k, a)) * b);\n    float gamma = std::pow(k, a);\n\n    Mat_<float> J(I.size());\n    pow(I, gamma, J);\n    J = J*beta;\n\n    return J;\n}\n\nstatic Mat_<Vec3f> applyK(const Mat_<Vec3f>& I, float k, float a=-0.3293f, float b=1.1258f, float offset=0) {\n    float beta = std::exp((1 - std::pow(k, a)) * b);\n    float gamma = std::pow(k, a);\n\n    Mat_<Vec3f> J(I.size());\n    pow(I, gamma, J);\n\n    return J * beta + Scalar::all(offset);\n}\n\nstatic float entropy(const Mat_<float>& I)\n{\n    Mat_<uchar> I_uchar;\n    I.convertTo(I_uchar, CV_8U, 255);\n\n    std::vector<Mat> planes;\n    planes.push_back(I_uchar);\n    Mat_<float> hist;\n    const int histSize = 256;\n    float range[] = { 0, 256 };\n    const float* histRange = { range };\n    calcHist(&I_uchar, 1, NULL, Mat(), hist, 1, &histSize, &histRange);\n\n    Mat_<float> hist_norm = hist / cv::sum(hist)[0];\n\n    float E = 0;\n    for (int i = 0; i < hist_norm.rows; i++)\n    {\n        if (hist_norm(i,0) > 0)\n        {\n            E += hist_norm(i,0) * std::log2(hist_norm(i,0));\n        }\n    }\n\n    return -E;\n}\n\ntemplate <typename T> static int sgn(T val)\n{\n    return (T(0) < val) - (val < T(0));\n}\n\nstatic double minimize_scalar_bounded(const Mat_<float>& I, double begin, double end,\n                               double xatol=1e-4, int maxiter=500)\n{\n// From scipy: https://github.com/scipy/scipy/blob/v1.4.1/scipy/optimize/optimize.py#L1753-L1894\n//    \"\"\"\n//    Options\n//    -------\n//    maxiter : int\n//        Maximum number of iterations to perform.\n//    disp: int, optional\n//        If non-zero, print messages.\n//            0 : no message printing.\n//            1 : non-convergence notification messages only.\n//            2 : print a message on convergence too.\n//            3 : print iteration results.\n//    xatol : float\n//        Absolute error in solution `xopt` acceptable for convergence.\n//    \"\"\"\n    double x1 = begin, x2 = end;\n\n    if (x1 > x2) {\n        throw std::runtime_error(\"The lower bound exceeds the upper bound.\");\n    }\n\n    double sqrt_eps = std::sqrt(2.2e-16);\n    double golden_mean = 0.5 * (3.0 - std::sqrt(5.0));\n    double a = x1, b = x2;\n    double fulc = a + golden_mean * (b - a);\n    double nfc = fulc, xf = fulc;\n    double rat = 0.0, e = 0.0;\n    double x = xf;\n    double fx = -entropy(applyK(I, static_cast<float>(x)));\n    int num = 1;\n    double fu = std::numeric_limits<double>::infinity();\n\n    double ffulc = fx, fnfc = fx;\n    double xm = 0.5 * (a + b);\n    double tol1 = sqrt_eps * std::abs(xf) + xatol / 3.0;\n    double tol2 = 2.0 * tol1;\n\n    for (int iter = 0; iter < maxiter && std::abs(xf - xm) > (tol2 - 0.5 * (b - a)); iter++)\n    {\n        int golden = 1;\n        // Check for parabolic fit\n        if (std::abs(e) > tol1) {\n            golden = 0;\n            double r = (xf - nfc) * (-entropy(applyK(I, static_cast<float>(x))) - ffulc);\n            double q = (xf - fulc) * (-entropy(applyK(I, static_cast<float>(x))) - fnfc);\n            double p = (xf - fulc) * q - (xf - nfc) * r;\n            q = 2.0 * (q - r);\n\n            if (q > 0.0) {\n                p = -p;\n            }\n            q = std::abs(q);\n            r = e;\n            e = rat;\n\n            // Check for acceptability of parabola\n            if (((std::abs(p) < std::abs(0.5*q*r)) && (p > q*(a - xf)) &\n                    (p < q * (b - xf)))) {\n                rat = (p + 0.0) / q;\n                x = xf + rat;\n\n                if (((x - a) < tol2) || ((b - x) < tol2)) {\n                    double si = sgn(xm - xf) + ((xm - xf) == 0);\n                    rat = tol1 * si;\n                }\n            } else {      // do a golden-section step\n                golden = 1;\n            }\n        }\n\n        if (golden) {  // do a golden-section step\n            if (xf >= xm) {\n                e = a - xf;\n            } else {\n                e = b - xf;\n            }\n            rat = golden_mean*e;\n        }\n\n        double si = sgn(rat) + (rat == 0);\n        x = xf + si * std::max(std::abs(rat), tol1);\n        fu = -entropy(applyK(I, static_cast<float>(x)));\n        num += 1;\n\n        if (fu <= fx) {\n            if (x >= xf) {\n                a = xf;\n            } else {\n                b = xf;\n            }\n\n            fulc = nfc;\n            ffulc = fnfc;\n            nfc = xf;\n            fnfc = fx;\n            xf = x;\n            fx = fu;\n        } else {\n            if (x < xf) {\n                a = x;\n            } else {\n                b = x;\n            }\n\n            if ((fu <= fnfc) || (nfc == xf)) {\n                fulc = nfc;\n                ffulc = fnfc;\n                nfc = x;\n                fnfc = fu;\n            } else if ((fu <= ffulc) || (fulc == xf) || (fulc == nfc)) {\n                fulc = x;\n                ffulc = fu;\n            }\n        }\n\n        xm = 0.5 * (a + b);\n        tol1 = sqrt_eps * std::abs(xf) + xatol / 3.0;\n        tol2 = 2.0 * tol1;\n    }\n\n    return xf;\n}\n\nstatic Mat_<Vec3f> maxEntropyEnhance(const Mat_<Vec3f>& I, const Mat_<uchar>& isBad, float a, float b)\n{\n    Mat_<Vec3f> input;\n    resize(I, input, Size(50,50));\n\n    Mat_<float> Y = rgb2gm(input);\n\n    Mat_<uchar> isBad_resize;\n    resize(isBad, isBad_resize, Size(50,50));\n\n    std::vector<float> Y_vec;\n    for (int i = 0; i < isBad_resize.rows; i++)\n    {\n        for (int j = 0; j < isBad_resize.cols; j++)\n        {\n            if (isBad_resize(i,j) >= 0.5)\n            {\n                Y_vec.push_back(Y(i,j));\n            }\n        }\n    }\n\n    if (Y_vec.empty())\n    {\n        return I;\n    }\n\n    Mat_<float> Y_mat(static_cast<int>(Y_vec.size()), 1, Y_vec.data());\n    float opt_k = static_cast<float>(minimize_scalar_bounded(Y_mat, 1, 7));\n\n    return applyK(I, opt_k, a, b, -0.01f);\n}\n\nstatic void BIMEF_impl(InputArray input_, OutputArray output_, float mu, float *k, float a, float b)\n{\n    CV_INSTRUMENT_REGION()\n\n    Mat input = input_.getMat();\n    if (input.empty())\n    {\n        return;\n    }\n    CV_CheckTypeEQ(input.type(), CV_8UC3, \"Input image must be 8-bits color image (CV_8UC3).\");\n\n    Mat_<Vec3f> imgDouble;\n    input.convertTo(imgDouble, CV_32F, 1/255.0);\n\n    // t: scene illumination map\n    Mat_<float> t_b(imgDouble.size());\n    t_b.forEach(\n        [&](float &pixel, const int * position) -> void\n        {\n            pixel = std::max(std::max(imgDouble(position[0], position[1])[0],\n                                      imgDouble(position[0], position[1])[1]),\n                            imgDouble(position[0], position[1])[2]);\n        }\n    );\n\n    const float lambda = 0.5;\n    const float sigma = 5;\n\n    Mat_<float> t_b_resize;\n    resize(t_b, t_b_resize, Size(), 0.5, 0.5);\n\n    Mat_<float> t_our = tsmooth(t_b_resize, lambda, sigma);\n    resize(t_our, t_our, t_b.size());\n\n    // k: exposure ratio\n    Mat_<Vec3f> J;\n    if (k == NULL)\n    {\n        Mat_<uchar> isBad(t_our.size());\n        isBad.forEach(\n            [&](uchar &pixel, const int * position) -> void\n            {\n                pixel = t_our(position[0], position[1]) < 0.5 ? 1 : 0;\n            }\n        );\n\n        J = maxEntropyEnhance(imgDouble, isBad, a, b);\n    }\n    else\n    {\n        J = applyK(imgDouble, *k, a, b);\n\n        // fix overflow\n        J.forEach(\n            [](Vec3f &pixel, const int * /*position*/) -> void\n            {\n                pixel(0) = std::min(1.0f, pixel(0));\n                pixel(1) = std::min(1.0f, pixel(1));\n                pixel(2) = std::min(1.0f, pixel(2));\n            }\n        );\n    }\n\n    // W: Weight Matrix\n    Mat_<float> W(t_our.size());\n    pow(t_our, mu, W);\n\n\n    output_.create(input.size(), CV_8UC3);\n    Mat output = output_.getMat();\n    output.forEach<Vec3b>(\n        [&](Vec3b &pixel, const int * position) -> void\n        {\n            float w = W(position[0], position[1]);\n            pixel(0) = saturate_cast<uchar>((imgDouble(position[0], position[1])[0] * w + J(position[0], position[1])[0] * (1 - w)) * 255);\n            pixel(1) = saturate_cast<uchar>((imgDouble(position[0], position[1])[1] * w + J(position[0], position[1])[1] * (1 - w)) * 255);\n            pixel(2) = saturate_cast<uchar>((imgDouble(position[0], position[1])[2] * w + J(position[0], position[1])[2] * (1 - w)) * 255);\n        }\n    );\n}\n#else\nstatic void BIMEF_impl(InputArray, OutputArray, float, float *, float, float)\n{\n    CV_Error(Error::StsNotImplemented, \"This algorithm requires OpenCV built with the Eigen library.\");\n}\n#endif\n\nvoid BIMEF(InputArray input, OutputArray output, float mu, float a, float b)\n{\n    BIMEF_impl(input, output, mu, NULL, a, b);\n}\n\nvoid BIMEF(InputArray input, OutputArray output, float k, float mu, float a, float b)\n{\n    BIMEF_impl(input, output, mu, &k, a, b);\n}\n\n}} // cv::intensity_transform::\n", "meta": {"hexsha": "58eac6002af103247e916099d8bf172a9a4fa1c3", "size": 17399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/intensity_transform/src/bimef.cpp", "max_stars_repo_name": "willsong/opencv_contrib_cat", "max_stars_repo_head_hexsha": "791e9413484cf0e1c8fcc8d15d409fefc72e4bcc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-18T07:30:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T07:30:29.000Z", "max_issues_repo_path": "modules/intensity_transform/src/bimef.cpp", "max_issues_repo_name": "willsong/opencv_contrib_cat", "max_issues_repo_head_hexsha": "791e9413484cf0e1c8fcc8d15d409fefc72e4bcc", "max_issues_repo_licenses": ["Apache-2.0"], "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/intensity_transform/src/bimef.cpp", "max_forks_repo_name": "willsong/opencv_contrib_cat", "max_forks_repo_head_hexsha": "791e9413484cf0e1c8fcc8d15d409fefc72e4bcc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-19T19:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-19T19:04:00.000Z", "avg_line_length": 30.3647469459, "max_line_length": 139, "alphanum_fraction": 0.5333065119, "num_tokens": 5393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5573943667483654}}
{"text": "// randomizer.cpp\n\n// [[Rcpp::plugins(cpp11)]]\n// [[Rcpp::plugins(openmp)]]\n\n#include \"randomizer.h\"\n#include <numeric>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/lognormal_distribution.hpp>\n#include <boost/random/cauchy_distribution.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/beta_distribution.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/binomial_distribution.hpp>\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/geometric_distribution.hpp>\nusing namespace boost::random;\n\nRandomizer::Randomizer(unsigned long int s)\n : seed(s)\n{\n    Reset();\n}\n\nvoid Randomizer::Reset()\n{\n    if (seed == 0)\n        generator.seed();\n    else\n        generator.seed(seed);\n}\n\ndouble Randomizer::Uniform(double min, double max)\n{\n    uniform_real_distribution<double> d(min, max);\n    return d(generator);\n}\n\ndouble Randomizer::RoundedUniform(double min, double max, double shoulder)\n{\n    if (min >= max)\n        return min;\n    double z = Uniform();\n    double sd = shoulder * (max - min) / ((1 - shoulder) * 2.50662827463);\n    if (z < shoulder / 2)\n        return min - abs(Normal(0, sd));\n    else if (z < shoulder)\n        return max + abs(Normal(0, sd));\n    else\n        return Uniform(min, max);\n}\n\ndouble Randomizer::Normal(double mean, double sd)\n{\n    normal_distribution<double> d(mean, sd);\n    return d(generator);\n}\n\ndouble Randomizer::Normal(double mean, double sd, double clamp)\n{\n    double n;\n    do n = Normal(mean, sd); while (std::fabs(n - mean) > clamp);\n    return n;\n}\n\ndouble Randomizer::LogNormal(double zeta, double sd)\n{\n    lognormal_distribution<double> d(zeta, sd);\n    return d(generator);\n}\n\ndouble Randomizer::Cauchy(double x0, double gamma)\n{\n    cauchy_distribution<double> d(x0, gamma);\n    return d(generator);\n}\n\ndouble Randomizer::Exponential(double rate)\n{\n    exponential_distribution<double> d(rate);\n    return d(generator);\n}\n\ndouble Randomizer::Gamma(double shape, double scale)\n{\n    gamma_distribution<double> d(shape, scale);\n    return d(generator);\n}\n\ndouble Randomizer::Beta(double alpha, double beta)\n{\n    beta_distribution<double> d(alpha, beta);\n    return d(generator);\n}\n\nunsigned int Randomizer::Discrete(unsigned int size)\n{\n    uniform_int_distribution<unsigned int> d(0, size - 1);\n    return d(generator);\n}\n\nint Randomizer::Discrete(int min, int max)\n{\n    uniform_int_distribution<int> d(min, max);\n    return d(generator);\n}\n\nvoid Randomizer::Multinomial(unsigned int N, std::vector<double>& p, std::vector<unsigned int>& n_out)\n{\n    unsigned int n = N;\n    double p_denom = std::accumulate(p.begin(), p.end(), 0.0);\n    for (unsigned int i = 0; i < p.size() - 1; ++i)\n    {\n        n_out[i] = Binomial(n, p[i] / p_denom);\n        n -= n_out[i];\n        p_denom -= p[i];\n    }\n    n_out[p.size() - 1] = n;\n}\n\nbool Randomizer::Bernoulli(double p)\n{\n    if (p <= 0) return false;\n    if (p >= 1) return true;\n    bernoulli_distribution<double> d(p);\n    return d(generator);\n}\n\nunsigned int Randomizer::Binomial(unsigned int n, double p)\n{\n    if (p <= 0) return 0;\n    binomial_distribution<int, double> d(n, p);\n    return d(generator);\n}\n\nunsigned int Randomizer::BetaBinomial(unsigned int n, double p, double a_plus_b)\n{\n    if (a_plus_b > 0) {\n        p = Beta(a_plus_b * p, a_plus_b * (1 - p));\n    }\n    return Binomial(n, p);\n}\n\nint Randomizer::Poisson(double mean)\n{\n    if (mean <= 0) return 0;\n    poisson_distribution<unsigned int, double> d(mean);\n    return d(generator);\n}\n\nint Randomizer::Geometric(double p)\n{\n    if (p <= 0) return 0;\n    geometric_distribution<unsigned int, double> d(p);\n    return d(generator);\n}\n\nint Randomizer::Round(double x)\n{\n    int sign = x < 0 ? -1 : 1;\n    double intpart, fracpart;\n    fracpart = std::modf(std::fabs(x), &intpart);\n    return sign * (intpart + Bernoulli(fracpart));\n}\n\nunsigned int Randomizer::operator()()\n{\n    return generator();\n}\n\nunsigned int Randomizer::operator()(unsigned int size)\n{\n    return Discrete(size);\n}\n", "meta": {"hexsha": "71655b498a76dafc670c54c1c06b610d259664fd", "size": 4218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/covidm_for_fitting/model_v2/randomizer.cpp", "max_stars_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_stars_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-04T21:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T21:05:34.000Z", "max_issues_repo_path": "code/covidm_for_fitting/model_v2/randomizer.cpp", "max_issues_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_issues_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "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": "code/covidm_for_fitting/model_v2/randomizer.cpp", "max_forks_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_forks_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6966292135, "max_line_length": 102, "alphanum_fraction": 0.6706970128, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.5573611786080458}}
{"text": "#pragma once\n\n#include \"data.hpp\"\n\n#include <boost/math/distributions/chi_squared.hpp>\n\n// Returns true if a is independent of b given X according to Pearson's\n// chi-squared test applied to given data.\nbool pearsonChiSquaredIndTest(const Data& data, int a, Bitset X, int b) {\n    CHECK(a >= 0 && a <= (int)data.catCounts.size());\n    CHECK(b >= 0 && b <= (int)data.catCounts.size());\n    CHECK(a != b);\n    CHECK(X.isSubsetOf(Bitset::range((int)data.catCounts.size())));\n    CHECK(!X.contains(a));\n    CHECK(!X.contains(b));\n\n    vector<int> ord(data.points.size());\n    for(int i = 0; i < (int)ord.size(); ++i) {\n        ord[i] = i;\n    }\n\n    vector<int> splits;\n    splits.push_back(0);\n    if(!ord.empty()) {\n        splits.push_back((int)ord.size());\n    }\n\n    vector<int> newSplits;\n\n    double freedom = 1.0;\n    vector<vector<int>> bins;\n\n    X.iterate([&](int v) {\n        freedom *= data.catCounts[v];\n\n        if((int)bins.size() < data.catCounts[v]) {\n            bins.resize(data.catCounts[v]);\n        }\n\n        newSplits.clear();\n        newSplits.push_back(0);\n        for(int s = 0; s < (int)splits.size() - 1; ++s) {\n            int x = splits[s];\n            int y = splits[s + 1];\n\n            if(y - x == 1) {\n                newSplits.push_back(y);\n            } else {\n                for(int c = 0; c < data.catCounts[v]; ++c) {\n                    bins[c].clear();\n                }\n                for(int i = x; i < y; ++i) {\n                    bins[data.points[ord[i]][v]].push_back(ord[i]);\n                }\n                int i = x;\n                for(int c = 0; c < data.catCounts[v]; ++c) {\n                    for(int p : bins[c]) {\n                        ord[i++] = p;\n                    }\n                    if(i != newSplits.back()) {\n                        newSplits.push_back(i);\n                    }\n                }\n            }\n        }\n        swap(splits, newSplits);\n    });\n\n    int aCatCount = data.catCounts[a];\n    int bCatCount = data.catCounts[b];\n    vector<double> freqs(aCatCount * bCatCount);\n    vector<double> aFreqs(aCatCount);\n    vector<double> bFreqs(bCatCount);\n\n    freedom *= (double)aCatCount - 1.0;\n    freedom *= (double)bCatCount - 1.0;\n\n    double chisq = 0.0;\n    for(int s = 0; s < (int)splits.size() - 1; ++s) {\n        fill(freqs.begin(), freqs.end(), 0.0);\n        fill(aFreqs.begin(), aFreqs.end(), 0.0);\n        fill(bFreqs.begin(), bFreqs.end(), 0.0);\n\n        int x = splits[s];\n        int y = splits[s + 1];\n        double N = (double)(y - x);\n        double unit = 1.0 / N;\n\n        for(int i = x; i < y; ++i) {\n            int aVal = data.points[ord[i]][a];\n            int bVal = data.points[ord[i]][b];\n            freqs[bVal * aCatCount + aVal] += unit;\n            aFreqs[aVal] += unit;\n            bFreqs[bVal] += unit;\n        }\n\n        double term = 0.0;\n        for(int aVal = 0; aVal < aCatCount; ++aVal) {\n            for(int bVal = 0; bVal < bCatCount; ++bVal) {\n                double expected = aFreqs[aVal] * bFreqs[bVal];\n                if(expected > 0.0) {\n                    double diff = freqs[bVal * aCatCount + aVal] - expected;\n                    term += diff * diff / expected;\n                }\n            }\n        }\n        term *= N;\n        chisq += term;\n    }\n\n    boost::math::chi_squared_distribution<> dist(freedom);\n    double crit = boost::math::quantile(dist, 0.95);\n    return chisq < crit;\n}\n", "meta": {"hexsha": "5b40e3d18aaa72f106ea9c3013c391011d82464b", "size": 3430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pearson_chisq.hpp", "max_stars_repo_name": "ttalvitie/learning-bns-with-cops-and-robbes", "max_stars_repo_head_hexsha": "e547c915bc445d1c9b5cec1f55a6206b29257ad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T13:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-21T13:22:23.000Z", "max_issues_repo_path": "pearson_chisq.hpp", "max_issues_repo_name": "ttalvitie/learning-bns-with-cops-and-robbes", "max_issues_repo_head_hexsha": "e547c915bc445d1c9b5cec1f55a6206b29257ad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pearson_chisq.hpp", "max_forks_repo_name": "ttalvitie/learning-bns-with-cops-and-robbes", "max_forks_repo_head_hexsha": "e547c915bc445d1c9b5cec1f55a6206b29257ad9", "max_forks_repo_licenses": ["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.8260869565, "max_line_length": 76, "alphanum_fraction": 0.4755102041, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5573218429567915}}
{"text": "/*\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstdlib>\n\n#include <NTL/ZZ.h>\n#include <NTL/RR.h>\n\nusing namespace std;\nusing namespace NTL;\n\n#define M_PIl \t3.141592653589793238462643383279502884L \n#define PI\t\tRR(M_PIl)\n\n\n//=============================================================\n//==Functions==================================================\n//=============================================================\n\n//--------------------------------------------------------\n//--Find an index corresponding to the maximum value------ \n//--------------------------------------------------------\nint max_index(double* array, int length) {\n\tint max_ind\t= 0;\n\tdouble max = array[0];\n\t\n\tfor(int i=1; i<length; i++) {\n\t\tif(array[i] > max) {\n\t\t\tmax_ind = i;\n\t\t\tmax = array[i];\n\t\t}\n\t}\n\treturn max_ind;\n}\n\t\n//--------------------------------------------------------\n//--Long division between polynomials represented--------- \n//---in Chebyshev basis-----------------------------------\n//-------------------------------------------------------- \nvoid Long_div(RR* p, int n, RR* q, int m, RR* quot, RR* rem) {\n//--------------------------------------------------------\n//--p : Dividend-------q : Divisor------------------------\n//--n : degree of p----m : degree of q--------------------\n//--quot : quotient----rem : remainder--------------------\n//--------------------------------------------------------\n\tif(m>0) {\n\t\tfor(int i=n; i>m; i--) {\n\t\t\tRR ratio = p[i]/q[m];\n\t\t\tfor(int j=0; j<=m; j++) {\n\t\t\t\tp[i-m+j] -= q[j]*ratio;\n\t\t\t\tp[abs(i-m-j)] -= q[j]*ratio;\n\t\t\t}\n\t\t\tquot[i-m] = RR(2.0)*ratio;\n\t\t}\n\t\t\n\t\tRR ratio = p[m]/q[m];\n\t\tfor(int j=0; j<=m; j++) \n\t\t\tp[j] -= q[j]*ratio;\n\t\tquot[0] = ratio;\n\t\t\n\t} else {\n\t\tfor(int i=n; i>=0; i--) {\n\t\t\tquot[i] = p[i]/q[0];\n\t\t\tp[i] = RR(0.0);\n\t\t}\n\t}\n\n\tfor(int i=0; i<m; i++)\n\t\trem[i] = p[i];\n}\n\n\n//=============================================================\n//==Main=======================================================\n//=============================================================\n\nint main(int argc, char* argv[]) {\n\n//=============================================================\n//==Setting====================================================\n//=============================================================\n\t\n\tint K = 12;\t\t\t\t\t\t\t\t// I_i = [i-.25-e, i-.25+e] where |i|< K\n\t\n\tint deg_bdd = atoi(argv[1]) + 1;\t\t// Bound of the degree +1\n\t\n\tint* deg = new int[K];\t\t\t\t\t// deg[i] = The number of nodes in I_i\n\tfor(int i=0; i<K; i++)\t\t\t\t\t// We assume deg[i] = deg[-i]\n\t\tdeg[i] = 1;\t\t\t\t\t\t\t// Initialize all deg[i] to 1\t\n\tint tot_deg = 2*K-1;\t\t\t\t\t// Total number of nodes\n\n\tint dev = atoi(argv[2]);\t\t\t\t\n\tdouble err = 1.0/(1 << atoi(argv[2]));\t// Maximum deviation from each i-.25\n\t\n\tint sc_num = atoi(argv[3]);\t\t\t\t// The number of scaling\n\tRR sc_fac = conv<RR>(ZZ(1) << sc_num);\t// Scaling factor\n\t\n\tRR::SetPrecision(1000);\n\n//=============================================================\n//==Degree Searching===========================================\n//=============================================================\n//--------------------------------------------------------\n//--Initialize--------------------------------------------\n//--------------------------------------------------------\n\n\tdouble* bdd = new double[K];\n\n\tdouble temp = 0;\n\tfor(int i=1; i<=(2*K-1); i++) \n\t\ttemp -= log2((double)i);\n\ttemp += (2*K-1)*log2(2*M_PI);\n\ttemp += log2(err);\n\n\tfor(int i=0; i<K; i++) {\n\t\tbdd[i] = temp;\n\t\tfor(int j=1; j<=K-1-i; j++)\n\t\t\tbdd[i] += log2((double)j + err);\n\t\tfor(int j=1; j<=K-1+i; j++)\n\t\t\tbdd[i] += log2((double)j + err);\n\t}\n\n//--------------------------------------------------------\n//--Algorithm--------------------------------------------- \n//--1. Find a point that has the largest theoretical error bound.\n//--2. Increase degree by one at that point.--------------\n//--(If the point is not 0, also increase degree by-------\n//---one at negate of that point)------------------------- \n//--3. Check whether total degree is greater than the degree bound\n//---If so, end the algorithm. If not, go back to 1.------\t\t\t\t\t\t\t\t\n//--------------------------------------------------------\n\n\tint max_iter = 200;\t// Bound of the number of iteration\n\tint iter;\n\n\tfor(iter=0; iter<max_iter; iter++) {\n\t\tif(tot_deg >= deg_bdd)\n\t\t\tbreak;\n\t\tint maxi = max_index(bdd, K);\t\n\t\t\n\t\tif(maxi != 0) {\n\t\t\tif((tot_deg+2) > deg_bdd) \n\t\t\t\tbreak; \n\t\n\t\t\tfor(int i=0; i<K; i++) {\n\t\t\t\tbdd[i] -= log2(tot_deg+1);\n\t\t\t\tbdd[i] -= log2(tot_deg+2);\n\t\t\t\tbdd[i] += 2.0*log2(2.0*M_PI);\n\n\t\t\t\tif(i != maxi) {\t\n\t\t\t\t\tbdd[i] += log2(abs((double)(i-maxi)) + err);\n\t\t\t\t\tbdd[i] += log2((double)(i+maxi) + err);\n\t\t\t\t} else { // i = maxi\n\t\t\t\t\tbdd[i] += (log2(err)-1.0);\n\t\t\t\t\tbdd[i] += log2(2.0*(double)i + err);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttot_deg += 2;\n\t\t} else { // maxi = 0\n\t\t\tbdd[0] -= log2(tot_deg+1);\n\t\t\tbdd[0] += (log2(err)-1.0);\n\t\t\tbdd[0] += log2(2.0*M_PI);\n\t\t\tfor(int i=1; i<K; i++) {\t\n\t\t\t\tbdd[i] -= log2(tot_deg+1);\n\t\t\t\tbdd[i] += log2(2.0*M_PI);\n\t\t\t\tbdd[i] += log2((double)i + err);\t\n\t\t\t}\n\t\t\n\t\t\ttot_deg += 1;\t\n\t\t}\n\t\t\n\t\tdeg[maxi] += 1;\n\t}\n\t\n\tdelete[] bdd;\n\n//--------------------------------------------------------\n//--Print the Result of Degree Searching------------------\n//--------------------------------------------------------\n\n\tcout << \"==============================================\" << endl;\n\tcout << \"==Degree Searching Result=====================\" << endl;\n\tcout << \"==============================================\" << endl;\n\n\tif(iter == max_iter) {\n\t\tcout << \"More Iteration Needed\" << endl;\n\t} else {\n\t\tcout << \"Degree of Polynomial : \" << tot_deg-1 << endl;\n\t\tcout << \"Degree : \";\n\t\tfor(int i=0; i<K; i++) \n\t\t\tcout << deg[i] << \"  \";\n\t\tcout << endl;\n\t}\n\tcout << \"==============================================\" << endl;\n\n//=============================================================\n//==Find an Interpolation Polynomial===========================\n//==Goal : Interpolate cos(2PI x)==============================\n//=============================================================\t\n//--------------------------------------------------------\n//--Node Setting------------------------------------------\n//--------------------------------------------------------\n\t\n\tRR inter_size = RR(1.0)/conv<RR>(((ZZ)(1) << dev)); \n\t// Half of the size of each interval\n\t\n\tRR* z = new RR[tot_deg];\t// Node positions\t\n\tint cnt = 0;\n\tif((deg[0]%2)!=0)\n\t\tz[cnt++] = -RR(0.25);\n\n\tfor(int i=K-1; i>0; i--) {\n\t\tfor(int j=1; j<=deg[i]; j++) {\n\t\t\tRR temp = ((RR(2*j-1))*PI)/(RR(2*deg[i]));\t\t\n\t\t\tz[cnt++] = RR(i - 0.25) + inter_size*cos(temp);\n\t\t\tz[cnt++] = RR(-i - 0.25) - inter_size*cos(temp);\n\t\t}\n\t}\n\n\tfor(int j=1; j<=(deg[0]/2); j++) {\n\t\tRR temp = ((RR(2*j-1))*PI)/(RR(2*deg[0]));\n\t\tz[cnt++] = RR(-0.25) + inter_size*cos(temp);\n\t\tz[cnt++] = RR(-0.25) - inter_size*cos(temp);\n\t}\n\t\n\tfor(int i=0; i<tot_deg; i++) \n\t\tz[i] /= sc_fac;\n\t\n\tdelete[] deg;\n\n//--------------------------------------------------------\n//--Algorithm---------------------------------------------\n//--------------------------------------------------------\n\n\tRR* d = new RR[tot_deg];\n\tfor(int i=0; i<tot_deg; i++) \n\t\td[i] = cos(RR(2.0)*PI*z[i]);\n\n\tfor(int j=1; j<tot_deg; j++) {\n\t\tfor(int l=0; l<tot_deg-j; l++) \n\t\t\td[l] = (d[l+1] - d[l]) / (z[l+j] - z[l]);\n\t}\n\n//=============================================================\n//==Compute Chebyshev Coefficients by Solving Matrix Equation==\n//==Result Polynomial :     ===================================\n//==\tc[0]T_0(x) + ... + c[tot_deg-1]T_{tot_deg-1}(x)   =====\n//== where T_i(x) is an adjusted Chebyshev polynomial =========\n//=============================================================\n\n\ttot_deg += 1;\n\t\n\tRR* x = new RR[tot_deg];\n\tfor(int i=0; i<tot_deg; i++) \n\t\tx[i] = RR(K)/sc_fac * cos(RR(i)*PI/RR(tot_deg-1));\t\n\n\tRR* c = new RR[tot_deg];\n\tRR* p = new RR[tot_deg];\n\tfor(int i=0; i<tot_deg; i++) {\n\t\tp[i] = d[0];\n\t\tfor(int j=1; j<tot_deg-1; j++)\n\t\t\tp[i] = p[i]*(x[i] - z[j]) + d[j];\n\t}\n\t\n\tdelete[] z;\n\n\tRR** T = new RR*[tot_deg];\n\tfor(int i=0; i<tot_deg; i++)\n\t\tT[i] = new RR[tot_deg];\n\t\n\tfor(int i=0; i<tot_deg; i++) {\n\t\tT[i][0] = RR(1.0);\n\t\tT[i][1] = x[i]/(RR(K)/sc_fac);\n\t\tfor(int j=2; j<tot_deg; j++)\n\t\t\tT[i][j] = RR(2.0)*(x[i]/(RR(K)/sc_fac))*T[i][j-1] - T[i][j-2];\n\t}\n\n\t\n\tfor(int i=0; i<tot_deg-1; i++) {\n\t\tRR max_abs = abs(T[i][i]);\n\t\tint max_index = i;\n\t\tfor(int j = i+1; j<tot_deg; j++) {\n\t\t\tif(abs(T[j][i]) > max_abs) {\n\t\t\t\tmax_abs = abs(T[j][i]);\n\t\t\t\tmax_index = j;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(i != max_index) {\n\t\t\tfor(int j=i; j<tot_deg; j++) {\n\t\t\t\tRR temp = T[max_index][j];\n\t\t\t\tT[max_index][j] = T[i][j];\n\t\t\t\tT[i][j] = temp;\n\t\t\t}\n\n\t\t\tRR temp = p[max_index];\n\t\t\tp[max_index] = p[i];\n\t\t\tp[i] = temp;\n\t\t}\n\t\t\n\t\tfor(int j=i+1; j<tot_deg; j++)\n\t\t\tT[i][j] /= T[i][i];\n\t\tp[i] /= T[i][i];\n\t\tT[i][i] = RR(1.0);\n\n\t\tfor(int j=i+1; j<tot_deg; j++) {\n\t\t\tp[j] -= T[j][i] * p[i];\n\t\t\tfor(int l=i+1; l<tot_deg; l++)\n\t\t\t\tT[j][l] -= T[j][i] * T[i][l];\n\t\t\tT[j][i] = RR(0.0);\n\t\t}\t\n\t}\n\n\tc[tot_deg-1] = p[tot_deg-1];\n\tfor(int i=tot_deg-2; i>=0; i--) {\n\t\tc[i] = p[i];\n\t\tfor(int j=i+1; j<tot_deg; j++)\n\t\t\tc[i] -= T[i][j]*c[j];\n\t}\n\n\ttot_deg -= 1;\n\t\n\tfor(int i=0; i<tot_deg; i++)\n\t\tdelete[] T[i];\n\tdelete[] T;\n\tdelete[] d;\n\tdelete[] x;\n\tdelete[] p;\n\n//=============================================================\n//==Baby Step Giant Step Algorithm=============================\n//=============================================================\t\n//--------------------------------------------------------\n//--Parameter Setting-------------------------------------\n//--------------------------------------------------------\n\n\tint temp_tot_deg = tot_deg; \n\t\n\tint m = 1;\t\t\t\t\t// m = ceil(log2(tot_deg))\t\t\t\t\t\n\twhile (temp_tot_deg > 1) {\n\t\tm++;\n\t\ttemp_tot_deg /= 2;\n\t}\n\t\n\tint* pow2 = new int[m+1];\t// pow2[i] = 2^i (i=0, ...,m)\n\tpow2[0] = 1;\n\tfor(int i=0; i<m; i++)\n\t\tpow2[i+1] = 2*pow2[i];\n\t\n\tint l;\t\t\t\t\t\t// l ~ m/2 \n\tif( m % 2 == 0)\t{\n\t\tl = m/2;\n\t} else {\t\t\t\t\t\t\n\t\tint l1 = m/2;\n\t\tint l2 = m/2 + 1;\n\t\t\n\t\tl = (pow2[l1] + pow2[m-l1] - l1 \n\t\t\t\t<= pow2[l2] + pow2[m-l2] - l2) ? l1 : l2;\n\t\t// Choose one that requires less number \n\t\t//\t\tof non-scalar multiplications\n\t}\n\n//--------------------------------------------------------\n//--Algorithm---------------------------------------------\n//--Details:    ------------------------------------------\n//---1. alg_coef[0][0] represents the interpolation poly--\n//---2. alg_coef[i][j] represents polynomial p_{i,j}------\n//---3. p_{i,j} = p_{i+1,2j} + p_{i+1,2j+1} T_{2^(m-i-1)}-\n//--------------------------------------------------------\t\t\n\t\n\tRR*** alg_coef = new RR**[m-l+1];\n\tfor(int i=0; i<m-l+1; i++) {\n\t\talg_coef[i] = new RR*[pow2[i]]; \n\t\tfor(int j=0; j<pow2[i]; j++)\n\t\t\talg_coef[i][j] = new RR[pow2[m-i]];\n\t}\n\t\n\tfor(int i=0; i<tot_deg; i++)\n\t\talg_coef[0][0][i] = c[i];\n\tfor(int i=tot_deg; i<pow2[m]; i++)\n\t\talg_coef[0][0][i] = RR(0.0);\t\n\n\tdelete[] c;\n\n\tfor(int i=0; i<m-l; i++) {\n\t\tRR* divisor = new RR[pow2[m-i-1]+1];\n\t\tfor(int j=0; j<pow2[m-i-1]; j++)\n\t\t\tdivisor[j] = RR(0.0);\n\t\tdivisor[pow2[m-i-1]] = RR(1.0);\n\t\t\n\t\tfor(int j=0; j<pow2[i]; j++) \n\t\t\tLong_div(alg_coef[i][j], pow2[m-i]-1, divisor, pow2[m-i-1],\n\t\t\t\t \t\talg_coef[i+1][2*j+1], alg_coef[i+1][2*j]);\n\t}\n\n//--------------------------------------------------------\n//--Print Algorithm Coefficients in File------------------\n//--------------------------------------------------------\n\n\tsystem(\"mkdir -p ./result/coef\");\n\tstring path_coef = \"./result/coef/Deg\";\n\tpath_coef += (to_string(tot_deg-1) \n\t\t\t+ \"Err\" + to_string(dev) \n\t\t\t+ \"Scale\" + to_string(sc_num) + \".csv\");\n\n\tofstream output_coef(path_coef);\n\n\tfor(int i=0; i<pow2[m-l]; i++) {\n\t\tfor(int j=0; j<pow2[l]; j++) \t\n\t\t\toutput_coef << alg_coef[m-l][i][j] << \", \";\n\t\toutput_coef << endl;\n\t}\n\t\n\toutput_coef.close();\n\n//=============================================================\n//==Find Maximum Error and Print Errors in File================\n//=============================================================\t\n//--------------------------------------------------------\n//--File Path Setting-------------------------------------\n//--------------------------------------------------------\n\n\tsystem(\"mkdir -p ./result/error\");\n\tstring path_err = \"./result/error/Deg\";\n\tpath_err += (to_string(tot_deg-1) \n\t\t\t+ \"Err\" + to_string(dev) \n\t\t\t+ \"Scale\" + to_string(sc_num) + \".csv\");\n\n\tofstream output_err(path_err);\n\t\n\toutput_err << \"Tested Values\" << \",\" << \"Real Values\" << \",\" \n\t\t\t<< \"Approximate Values\" << \",\" << \"Error\" << \",\" \n\t\t\t<< \"log2(Error)\" << endl;\n\t\n//--------------------------------------------------------\n//--Test Nodes Setting------------------------------------\n//--------------------------------------------------------\n\n\tint test_num = 20;\t\t// The number of test points in each interval I_i\n\n\tRR** test = new RR*[2*K-1];\t\n\tfor(int i=0; i<2*K-1; i++)\n\t\ttest[i] = new RR[test_num+1];\n\t\n\tRR incr = RR(2.0)*inter_size*RR(1.0/test_num);\n\ttest[0][0] = -RR(0.25) - inter_size;\n\tfor(int i=1; i<test_num+1; i++)\t\n\t\ttest[0][i] = test[0][i-1] + incr;\n\t\n\tfor(int i=1; i<=K-1; i++) {\n\t\ttest[2*i-1][0] = RR(-i - 0.25) - inter_size;\n\t\tfor(int j=1; j<test_num+1; j++) \n\t\t\ttest[2*i-1][j] = test[2*i-1][j-1] + incr;\n\t\ttest[2*i][0] = RR(i - 0.25) - inter_size;\n\t\tfor(int j=1; j<test_num+1; j++) \n\t\t\ttest[2*i][j] = test[2*i][j-1] + incr;\n\t}\n\n//--------------------------------------------------------\n//--Computation and Print Errors in File------------------\n//--------------------------------------------------------\n\n\tRR max = RR(-999.0);\n\tfor(int i=0; i<2*K-1; i++) {\n\t\tfor(int j=0; j<test_num+1; j++) {\n\t\t\t\n\t\t\tRR real = cos(RR(2.0) * PI * test[i][j]); \t// Real value of cos(2PI x)\n\t\t\tRR approx = RR(0.0);\t\t\t\t\t\t// Approximate value of cos(2PI x)\n\t\t\t\n\t\t\tRR* BS = new RR[pow2[l]]; \t\t// Baby-step basis  : T_0(x), ... , T_{2^l-1}(x)\t\n\t\t\tRR* GS = new RR[m-l];\t\t\t// Giant-step basis : T_{2^l)(x), ... , T_{2^(m-1)}(x)\n\n\t\t\tBS[0] = RR(1.0);\n\t\t\tBS[1] = (test[i][j]/RR(K));\n\t\t\n\t\t\tfor(int k=2; k<pow2[l]; k++)\n\t\t\t\tBS[k] = RR(2.0)*BS[k/2]*BS[k-k/2] - BS[k-2*(k/2)];\n\n\t\t\tGS[0] = RR(2.0)*BS[pow2[l-1]]*BS[pow2[l-1]] - RR(1.0);\n\t\t\tfor(int k=1; k<m-l; k++)\n\t\t\t\tGS[k] = RR(2.0)*GS[k-1]*GS[k-1] - RR(1.0);\n\t\t\t\n\t\t\tRR** alg_value = new RR*[m-l+1]; \t// Recall that alg_coef[i][j] represents polynomial p_{i,j}\n\t\t\tfor(int k=0; k<m-l+1; k++) \t\t\t// alg_value[i][j] : The value of p_{i,j} at x\n\t\t\t\talg_value[k] = new RR[pow2[k]]; // alg_value[0][0] : The value of interpolation poly at x  \n\n\t\t\tfor(int k=0; k<pow2[m-l]; k++) {\n\t\t\t\tRR temp = RR(0.0);\n\t\t\t\tfor(int s=0; s<pow2[l]; s++)\n\t\t\t\t\ttemp += alg_coef[m-l][k][s]*BS[s];\n\t\t\t\talg_value[m-l][k] = temp;\n\t\t\t}\n\t\n\t\t\tfor(int k=m-l-1; k>=0; k--) {\n\t\t\t\tfor(int s=0; s<pow2[k]; s++) \n\t\t\t\t\talg_value[k][s] = alg_value[k+1][2*s] + GS[m-l-k-1]*alg_value[k+1][2*s+1];\n\t\t\t}\n\t\t\tapprox = alg_value[0][0];\n\t\t\t\n\t\t\tfor(int k=0; k<sc_num; k++)\n\t\t\t\tapprox = RR(2.0)*approx*approx - RR(1.0);\t// double angle formula\t\t\t\n\n\t\t\toutput_err << test[i][j] << \",\" << real << \",\" \n\t\t\t\t\t\t<< approx << \",\" << approx-real << \",\";\n\n\t\t\tif(approx-real!=0) {\n\t\t\t\tif(max < log(abs(approx-real))/log(RR(2.0)))\n\t\t\t\t\tmax = log(abs(approx-real))/log(RR(2.0));\n\n\t\t\t\toutput_err << log(abs(approx-real))/log(RR(2.0)) << endl;\n\t\t\t} else {\n\t\t\t\toutput_err << \"*\" << endl;\n\t\t\t}\n\t\t}\t\n\t}\n\n\toutput_err.close();\t\n\n//--------------------------------------------------------\n//--Print Maximum Error of the interpolation polynomial---\n//--------------------------------------------------------\n\n\tcout << \"==============================================\" << endl;\n\tcout << \"==Baby Step Giant Step Algorithm Result=======\" << endl;\n\tcout << \"==============================================\" << endl;\n\tcout << \"Max_Error : \" << max << endl;\n\tcout << \"==============================================\" << endl;\n\t\n\tfor(int i=0; i<m-l+1; i++) {\n\t\tfor(int j=0; j<pow2[i]; j++) \n\t\t\tdelete[] alg_coef[i][j];\n\t\tdelete[] alg_coef[i];\n\t}\n\tdelete[] alg_coef;\n\t\n\tfor(int i=0; i<2*K-1; i++)\n\t\tdelete[] test[i];\n\tdelete[] test;\n}\n", "meta": {"hexsha": "041af44d375fdde0efd73d51f4d00fe70a40e0ad", "size": 16420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "find_polynomial.cpp", "max_stars_repo_name": "KyoohyungHan/better-homomorphic-sine-evaluation", "max_stars_repo_head_hexsha": "7a44b71836efeae7ba576a76ecb3c2667504d74c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "find_polynomial.cpp", "max_issues_repo_name": "KyoohyungHan/better-homomorphic-sine-evaluation", "max_issues_repo_head_hexsha": "7a44b71836efeae7ba576a76ecb3c2667504d74c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "find_polynomial.cpp", "max_forks_repo_name": "KyoohyungHan/better-homomorphic-sine-evaluation", "max_forks_repo_head_hexsha": "7a44b71836efeae7ba576a76ecb3c2667504d74c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T01:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T01:28:28.000Z", "avg_line_length": 29.6925858951, "max_line_length": 96, "alphanum_fraction": 0.4022533496, "num_tokens": 4981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5573218344330764}}
{"text": "/**\n * Functions for optimizing functions.\n * Includes line search to find a step length to reduce a function.\n */\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace ccd {\nnamespace opt {\n\n    /**\n     * @brief Search along a search direction to find a scalar \\f$\\alpha\n     * \\in [0, 1]\\f$ such that \\f$f(x + \\alpha \\Delta x) \\leq f(x)\\f$.\n     *\n     * @param[in] x                Starting point for the line search.\n     * @param[in] dir              Direction to search along.\n     * @param[in] f                Function of x to minimize.\n     * @param[out] step_length     Scalar coefficent of the direction to step.\n     * @param[in] min_step_length  Minimum value of step_length before the line\n     *                             search fails.\n     *\n     * @return True if the line search was successful, false otherwise.\n     */\n    bool line_search(\n        const Eigen::VectorXd& x,\n        const Eigen::VectorXd& dir,\n        const std::function<double(const Eigen::VectorXd&)>& f,\n        double& step_length,\n        const double min_step_length = 1e-10);\n\n    /**\n     * @brief Search along a search direction to find a scalar \\f$\\alpha\n     * \\in [0, 1]\\f$ such that \\f$f(x + \\alpha \\Delta x) < f(x)\\f$.\n     *\n     * @param[in] x                Starting point for the line search.\n     * @param[in] dir              Direction to search along.\n     * @param[in] f                Function of x to minimize.\n     * @param[in] grad_fx          The precomputed value of \\f$\\nabla f(x)\\f$.\n     * @param[out] step_length     Scalar coefficent of the direction to step.\n     * @param[in] min_step_length  Minimum value of step_length before the line\n     *                             search fails.\n     *\n     * @return True if the line search was successful, false otherwise.\n     */\n    bool line_search(\n        const Eigen::VectorXd& x,\n        const Eigen::VectorXd& dir,\n        const std::function<double(const Eigen::VectorXd&)>& f,\n        const Eigen::VectorXd& grad_fx,\n        double& step_length,\n        const double min_step_length = 1e-10,\n        const double armijo_rule_coeff = 0);\n\n    /**\n     * @brief Search along a search direction to find a scalar \\f$\\alpha\n     * \\in [0, 1]\\f$ such that \\f$f(x + \\alpha \\Delta x) < f(x)\\f$.\n     *\n     * @param[in] x                Starting point for the line search.\n     * @param[in] dir              Direction to search along \\f$(\\Delta x)\\f$.\n     * @param[in] f                Function of x to minimize.\n     * @param[in] grad_fx          The precomputed value of \\f$\\nabla f(x)\\f$.\n     * @param[in] constraint       Constraint on x such that constraint(x) must\n     *                             be true.\n     * @param[out] step_length     Scalar coefficent of the direction to step\n     *                             \\f$(\\alpha)\\f$.\n     * @param[in] min_step_length  Minimum value of step_length before the line\n     *                             search fails.\n     *\n     * @return True if the line search was successful, false otherwise.\n     */\n    bool constrained_line_search(\n        const Eigen::VectorXd& x,\n        const Eigen::VectorXd& dir,\n        const std::function<double(const Eigen::VectorXd&)>& f,\n        const Eigen::VectorXd& grad_fx,\n        const std::function<bool(const Eigen::VectorXd&)>& constraint,\n        double& step_length,\n        const double min_step_length = 1e-10,\n        const double armijo_rule_coeff = 0);\n\n} // namespace opt\n} // namespace ccd\n", "meta": {"hexsha": "c18152c5a455dc1bd4c6a9fa8ee0ec819455af25", "size": 3464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/src/solvers/line_search.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "comparisons/STIV/src/solvers/line_search.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "comparisons/STIV/src/solvers/line_search.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 40.7529411765, "max_line_length": 79, "alphanum_fraction": 0.5744803695, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5572482696956911}}
{"text": "/**\n * @file calc-jump.cpp\n *\n * @brief calc jump function.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n *\n * Compile:\n * g++ calc-jump.cpp -o calc-jump -lntl\n *\n * Compute polynomial for 2^128 steps:\n * ./calc-jump 340282366920938463463374607431768211456 poly.19937.txt\n *\n */\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <inttypes.h>\n#include <stdint.h>\n#include <time.h>\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/ZZ.h>\n#include \"dsfmt-calc-jump.hpp\"\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] << \" jump-step poly-file\" << endl;\n\tcout << \"    jump-step: a number between zero and 2^{DSFMT_MEXP}-1.\\n\"\n\t     << \"               large decimal number is allowed.\" << endl;\n\tcout << \"    poly-file: one of poly.{MEXP}.txt \"\n\t     << \"file\" << endl;\n\treturn -1;\n    }\n    string step_string = argv[1];\n    string filename = argv[2];\n    long no = 0;\n    GF2X lcmpoly;\n    read_file(lcmpoly, no, filename);\n    ZZ step;\n    stringstream ss(step_string);\n    ss >> step;\n    string jump_str;\n    calc_jump(jump_str, step, lcmpoly);\n    cout << \"jump polynomial:\" << endl;\n    cout << jump_str << endl;\n    return 0;\n}\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": "10758ba6b932cef5cc6d1a3429edc1053e3328eb", "size": 1928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dsfmt/calc-jump.cpp", "max_stars_repo_name": "MarcusSaviour/bitgenerators", "max_stars_repo_head_hexsha": "41a8676db18e56989b0540bde57fd671ff61fc13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T05:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-07T06:38:26.000Z", "max_issues_repo_path": "src/dsfmt/calc-jump.cpp", "max_issues_repo_name": "MarcusSaviour/bitgenerators", "max_issues_repo_head_hexsha": "41a8676db18e56989b0540bde57fd671ff61fc13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-02-07T11:09:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T10:18:55.000Z", "max_forks_repo_path": "src/dsfmt/calc-jump.cpp", "max_forks_repo_name": "MarcusSaviour/bitgenerators", "max_forks_repo_head_hexsha": "41a8676db18e56989b0540bde57fd671ff61fc13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-02T04:14:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T04:12:49.000Z", "avg_line_length": 23.512195122, "max_line_length": 71, "alphanum_fraction": 0.6369294606, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5572482696956911}}
{"text": "/**\n * @date Fri Jan 27 14:10:23 2012 +0100\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <stdexcept>\n#include <boost/shared_array.hpp>\n\n#include <bob.math/inv.h>\n\n#include <bob.math/linear.h>\n\n#include <bob.core/assert.h>\n#include <bob.core/check.h>\n#include <bob.core/array_copy.h>\n\n// Declaration of the external LAPACK function\n// LU decomposition of a general matrix (dgetrf)\nextern \"C\" void dgetrf_( const int *M, const int *N, double *A, const int *lda,\n  int *ipiv, int *info);\n// Inverse of a general matrix (dgetri)\nextern \"C\" void dgetri_( const int *N, double *A, const int *lda,\n  const int *ipiv, double *work, const int *lwork, int *info);\n\nvoid bob::math::inv(const blitz::Array<double,2>& A, blitz::Array<double,2>& B)\n{\n  // Size variable\n  const int N = A.extent(0);\n  const blitz::TinyVector<int,2> shapeA(N,N);\n  bob::core::array::assertZeroBase(A);\n  bob::core::array::assertZeroBase(B);\n\n  bob::core::array::assertSameShape(A,shapeA);\n  bob::core::array::assertSameShape(B,shapeA);\n\n  bob::math::inv_(A, B);\n}\n\nvoid bob::math::inv_(const blitz::Array<double,2>& A, blitz::Array<double,2>& B)\n{\n  // Size variable\n  const int N = A.extent(0);\n\n  //////////////////////////////////////\n  // Prepares to call LAPACK functions\n  // Initializes LAPACK variables\n  int info = 0;\n  const int lda = N;\n\n  // Initializes LAPACK arrays\n  boost::shared_array<int> ipiv(new int[N]);\n\n  // Tries to use B directly if possible\n  //   Input and output arrays are both column-major order.\n  //   Hence, we can ignore the problem of column- and row-major order\n  //   conversions.\n  bool B_direct_use = bob::core::array::isCZeroBaseContiguous(B);\n  blitz::Array<double,2> A_blitz_lapack;\n  if (B_direct_use)\n  {\n    A_blitz_lapack.reference(B);\n    A_blitz_lapack = A;\n  }\n  else\n    A_blitz_lapack.reference(bob::core::array::ccopy(A));\n  double *A_lapack = A_blitz_lapack.data();\n\n\n  // Calls the LAPACK functions\n  // 1/ Computes the LU decomposition\n  dgetrf_( &N, &N, A_lapack, &lda, ipiv.get(), &info);\n  // Checks the info variable\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK dgetrf function returned a non-zero value.\");\n\n  // TODO: We might consider adding a real invertibility test as described in\n  // this thread (Btw, this is what matlab does):\n  // http://icl.cs.utk.edu/lapack-forum/archives/lapack/msg00778.html\n\n  // 2/ Computes the inverse matrix\n  // 2/A/ Queries the optimal size of the working array\n  const int lwork_query = -1;\n  double work_query;\n  dgetri_( &N, A_lapack, &lda, ipiv.get(), &work_query, &lwork_query, &info);\n  // 2/B/ Computes the inverse\n  const int lwork = static_cast<int>(work_query);\n  boost::shared_array<double> work(new double[lwork]);\n  dgetri_( &N, A_lapack, &lda, ipiv.get(), work.get(), &lwork, &info);\n  // Checks info variable\n  if (info != 0)\n    throw std::runtime_error(\"The LAPACK dgetri function returned a non-zero value. The matrix might not be invertible.\");\n\n  // Copy back content to B if required\n  if (!B_direct_use)\n    B = A_blitz_lapack;\n}\n\n", "meta": {"hexsha": "3e5ddf7ff7da9a1056c270a5d327388836b6a86d", "size": 3126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/inv.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/inv.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/inv.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": 31.26, "max_line_length": 122, "alphanum_fraction": 0.6791426743, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.5572482662170054}}
{"text": "#include <Rcpp.h>\r\n#include <RcppEigen.h>\r\n#include <Eigen/Dense>\r\n#include <queue>\r\n// #include<Eigen/SparseCore>\r\nusing namespace Rcpp;\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n\r\n// [[Rcpp::depends(RcppEigen)]]\r\n\r\n//\r\nusing Eigen::Map;               \t// 'maps' rather than copies\r\nusing Eigen::Matrix;                  //  matrix generic\r\nusing Eigen::MatrixXd;                  // variable size matrix, double precision\r\nusing Eigen::VectorXd;                  // variable size vector, double precision\r\nusing Eigen::Transpositions;\r\nusing Eigen::HouseholderQR;    // Fast scalable QR solver\r\nusing Eigen::ColPivHouseholderQR;    // Fast scalable QR solver\r\nusing Eigen::FullPivHouseholderQR; // slow full (colsand rows pivoting) \r\nusing Eigen::JacobiSVD;\r\nusing Eigen::GeneralizedSelfAdjointEigenSolver;    // one of the eigenvalue solvers\r\nusing Eigen::SelfAdjointEigenSolver;    // one of the eigenvalue solvers\r\nusing Eigen::LLT;\r\nusing Eigen::LDLT;\r\nusing Rcpp::List;\r\nusing Rcpp::wrap;\r\n\r\n\r\n// ##########  OK vrsione Sept 04 works\r\n\r\n// copied to fspca_sept.cpp\r\n\r\n// =========================================================================\r\n\r\n\r\n\r\n// creates a sub-mat of S with indices in e\r\nEigen::MatrixXd makeSubS(Eigen::MatrixXd S, Eigen::VectorXi e){\r\n  int n = S.cols();\r\n  int r = S.rows();\r\n  int d = e.size();\r\n  if (d >= n) {\r\n    Rf_error(\"Too many indices to eliminate.\\n\");\r\n  }\r\n  if (e.maxCoeff() > n){\r\n    Rf_error(\"largest index greater than the number of columns.\\n\");\r\n  }\r\n  \r\n  Eigen::MatrixXd M(r, d );  \r\n  for (int i = 0; i < d; ++i){\r\n    M.col(i) = S.col(e(i));\r\n  }\r\n  for (int i = 0; i < d; ++i){\r\n    M.row(i) = M.row(e(i));\r\n  }\r\n  \r\n  return M.topLeftCorner(d, d);\r\n} \r\n\r\n// retruns the rows in e and keeps first c columns\r\nEigen::MatrixXd selectRowsC(Eigen::MatrixXd A, Eigen::VectorXi e, int c){\r\n  // ATTENZIONE INDICES BASE 0\r\n  // ATTENZIONE e must be sorted e(0) < e(1)\r\n  \r\n  int n = A.cols();\r\n  int r = A.rows();\r\n  int d = e.size();\r\n  if (d >= n) {\r\n    Rf_error(\"Too many indices to eliminate.\\n\");\r\n  }\r\n  if (e.maxCoeff() > n){\r\n    Rf_error(\"largest index greater than the number of columns.\\n\");\r\n  }\r\n  \r\n  Eigen::MatrixXd M(A.topLeftCorner(r,c));   \r\n  for (int i = 0; i < d; ++i){\r\n    M.row(i) = M.row(e(i));\r\n  }\r\n  \r\n  return M.topLeftCorner(d, c);\r\n} \r\n\r\n\r\n// Deflates S and D (pass already deflated and vector current loads)\r\n// returns vexp by ref\r\nvoid deflSandDC(Eigen::VectorXd a, Eigen::MatrixXd& K, \r\n                Eigen::MatrixXd& D, Eigen::VectorXi ind, double& vexp){\r\n  // # pass only a nonzero loads\r\n  // S = deflated matrix\r\n  // # D = SS\r\n  // #  K <-- (S - Saa'S/(a'Sa) // deflated S matrix\r\n  // # KK deflated product corr matrix D = KK\r\n  // #   KK = D - Daa'S/(a'Sa) - Saa'D/(a'Sa) + Saa'Daa'S/(a'Sa)^2\r\n  // ## ===\r\n  const int n = ind.size();\r\n  const int p = K.cols();\r\n  \r\n  // t = Sa\r\n  Eigen::VectorXd t = Eigen::VectorXd::Zero(p); \r\n  for (int i = 0; i < p; i++)\r\n    for(int k = 0; k < n; k++) \r\n      t(i) += K(i, ind(k)) * a(k ); // only elements in ind\r\n  // tt = a'Sa = t'a\r\n  \r\n  double tt = 0.0; \r\n  for(int k = 0; k < n; k++)\r\n    tt += a(k) * t(ind(k));\r\n  if (tt > 0)\r\n    tt = 1/tt;\r\n  else\r\n    Rf_error(\"defSandD: tt is not > 0\");\r\n  \r\n  // O = Sa/(tt)\r\n  const Eigen::VectorXd O = (t.array()*tt).matrix();\r\n  \r\n  const double cvk = K.trace();\r\n  // K = S - Saa'S/(a'Sa) deflated S\r\n  Eigen::MatrixXd L = t * O.transpose();\r\n  K = K - t * O.transpose(); //deflated S\r\n  vexp =  cvk - K.trace() ;\r\n  \r\n  // deflate D\r\n  \r\n  // N = aa'S/(tt) = a*t'/(tt) = a*O' (n x p)\r\n  Eigen::MatrixXd N = Eigen::MatrixXd::Zero(n, p); \r\n  for (int i = 0; i < n; i++)\r\n    for (int j = 0; j < p; j++)\r\n      N(i, j) += a(i) * O(j);  \r\n  \r\n  //M = Daa'S/(a'Sa) = D.transpose() * N; // (p, p)\r\n  Eigen::MatrixXd M = Eigen::MatrixXd::Zero(p,p); \r\n  for (int i = 0; i < p; i++)\r\n    for (int j = 0; j < p; j++)\r\n      for(int k = 0; k < n; k++) \r\n        M(i, j) += D(i, ind(k)) * N(k, j);  // (p, p)\r\n  \r\n  //  H = N.transpose() * M (p x p)\r\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(p,p); // \r\n  for (int i = 0; i < p; i++)\r\n    for (int j = 0; j < p; j++)\r\n      for(int k = 0; k < n; k++) \r\n        H(i, j) += N(k, i) * M(ind(k), j);  \r\n  D = (D.array() - M.array() - M.transpose().array() + H.array()).matrix(); \r\n  return;\r\n}  \r\n//\r\n\r\n\r\n\r\n// finds max part corr exclude small ss, pdates indnot returns ind\r\nint findmax(Eigen::VectorXi& indnot, Eigen::VectorXd vt){\r\n  \r\n  double p = indnot.size();\r\n  double m = 0.0;\r\n  int ind = 0;\r\n  for (int i = 0; i < p; i++){\r\n    if (indnot(i) == -2){\r\n      if(vt(i) > m){\r\n        m = vt(i);\r\n        ind = i;\r\n      }\r\n    }\r\n  }\r\n  indnot(ind) = ind;\r\n  return ind;  \r\n}\r\n\r\n// fixed\r\nvoid fwd_selectC(Eigen::MatrixXd S, Eigen::VectorXi& ind, int& card,\r\n                 Eigen::VectorXd si, double totvexp, double pvexp,\r\n                 double fullrank = 0.0){ \r\n  Eigen::VectorXd sik = si;\r\n  int p = S.cols();\r\n  // int induno;\r\n  double tmp; \r\n  Eigen::VectorXd vexpt(p);\r\n  Eigen::VectorXd cvexpt(p);\r\n  Eigen::VectorXd vt(p);\r\n  Eigen::VectorXi indnot = Eigen::VectorXi::Constant(p, -2);\r\n  Eigen::VectorXd ba(p);\r\n  \r\n  for (int i=0; i < p; i++)\r\n    vt(i) = sik(i) * sik(i) / S(i,i);\r\n  \r\n  ind(0) = findmax(indnot, vt);\r\n  \r\n  vexpt(0) = vt(ind(0));\r\n  cvexpt(0) = vt(ind(0));\r\n  int i = 1;\r\n  bool stopSelect = false;\r\n  // start looping ============================================  \r\n  while (stopSelect == false){\r\n    \r\n    tmp = sik(ind(i - 1))/S(ind(i - 1), ind(i - 1));\r\n    for (int j = 0; j < p; j++){\r\n      if ( indnot(j) == -2){\r\n        sik(j) = sik(j) -  (tmp * S(ind(i-1), j));\r\n      }   \r\n      else{\r\n        sik(j) = 0;\r\n      } \r\n    }  \r\n    \r\n    ba = (S.col(ind(i-1)).array()/sqrt(S(ind(i-1), ind(i-1)))).matrix();\r\n    S = S - ba * ba.transpose();\r\n    \r\n    for (int j = 0; j < p; j++){\r\n      if ( indnot(j) == -2){\r\n        if (S(j,j)> fullrank)\r\n          vt(j) = sik(j) * sik(j)/S(j,j);\r\n        else{\r\n          indnot(j) = -1;\r\n          vt(j) = 0;\r\n        }\r\n      }\r\n      else{\r\n        vt(j) = 0;\r\n      }\r\n    }\r\n    \r\n    ind(i) = findmax(indnot, vt);\r\n    indnot(ind(i)) = 0;\r\n    \r\n    vexpt(i) =  vt(ind(i));\r\n    cvexpt(i) = cvexpt(i-1) + vexpt(i);\r\n    \r\n    if (cvexpt(i) >= pvexp*totvexp){\r\n      card = i + 1;\r\n      stopSelect = true;\r\n    }\r\n    else{\r\n      i = i + 1;\r\n    }\r\n    //    Rcpp::checkUserInterrupt();\r\n    \r\n  }  \r\n}\r\n\r\n/* non serve\r\n// power method computes only first eigvec, about 82 times faster tha eigen!\r\nEigen::VectorXd eigvecPMC(Eigen::MatrixXd& X, double& val, double eps = 10E-5){\r\n  const int p = X.cols();\r\n  double sqp = sqrt(double(p));\r\n  Eigen::VectorXd v0 = VectorXd::Constant(p, 1.0/sqp);\r\n  Eigen::VectorXd v = VectorXd::Constant(p, 0.0);\r\n  double stp = 1.0;\r\n  int k = 0;\r\n  while (stp > eps){\r\n    v = X * v0;\r\n    val = v.norm();\r\n    v = v.array()/val;\r\n    stp = (v0.array() - v.array()).matrix().norm();\r\n    v0 = v;\r\n    k++;\r\n    if (k > 100){\r\n      Rf_warning(\"Powermethod: not converged in 100 iterations. Error is\", k);\r\n      break;//here should use try-catch  \r\n    }  \r\n  }\r\n  //  Rcout << \"k = \" << k << \"; stp = \" << stp << endl;\r\n  return (v.array() * val);  \r\n}\r\n\r\n*/\r\n\r\n// This is the main function for R\r\n// S correl matrix\r\n// pvexpfs is proportion of PC to explain by each block\r\n// pvexp is proportion total variance of matrix to explain to terminate computing comps\r\n// ncomps nistead of pvexp maximum number of comps (priority)\r\n// full rank small eps to discard vars from selection\r\n// newpc if false uses PCs of S not compute newpc each block, for large mats\r\n// pass D\r\n// [[Rcpp::export]]\r\nList fspcaCD(Eigen::MatrixXd S, Eigen::MatrixXd D, double pvexpfs = 0.95, double pvexp = 0.95, \r\n               int ncomps = 0, double fullrank = 0, bool newpc = true, double eps = 10E-8){\r\n  int p = S.cols();\r\n  if (ncomps == 0)\r\n    ncomps = p;\r\n  Eigen::MatrixXd K(S);\r\n  Eigen::MatrixXd M = D;\r\n  \r\n  SelfAdjointEigenSolver<Eigen::MatrixXd> es(S);\r\n  // here could compute D as   vec * diag(val^2) * vec.transpose \r\n  \r\n  Eigen::MatrixXd vec  = es.eigenvectors().rowwise().reverse();\r\n  Eigen::VectorXd vexppc = es.eigenvalues().reverse();\r\n  \r\n  double totvexp = vexppc.sum();// total variance S\r\n  double maxvexp = vexppc(0);// this is vexp by first PC for fow_select\r\n  \r\n  Eigen::VectorXd si = vec.col(0) * vexppc(0);\r\n  \r\n  Eigen::VectorXd a(p);\r\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(p, ncomps);\r\n  //  List load(p);\r\n  List indout(p);\r\n  \r\n  Eigen::VectorXd vexp = Eigen::VectorXd::Zero(ncomps);\r\n  Eigen::VectorXd cvexp = vexp;\r\n  double cvt;\r\n  Eigen::VectorXi indj(p);//this to pass to fwd_select \r\n  \r\n  Eigen::MatrixXd Sd(p, p);// this takes S[onlyind, onlyind]\r\n  Eigen::MatrixXd Dd(p, p);// this takes D[onlyind,onlyind] deflated\r\n  \r\n  int cardt = 0;\r\n  int totcard = 0;\r\n  Eigen::VectorXi card(p); \r\n  int nc = 0;   \r\n  bool stopComp = false;\r\n  \r\n  int j = 0;\r\n  while (stopComp == false){\r\n    fwd_selectC(S, indj, cardt, si, maxvexp, pvexpfs, fullrank);\r\n    \r\n    card(j) = cardt;\r\n    std::sort(indj.data(),indj.data() + cardt);\r\n\r\n    // if ( j == 2)\r\n    //   Rf_error(\"done 1\");  \r\n    \r\n    totcard = totcard + cardt;// a che serve ?\r\n    \r\n    // create submatrices for computing loaidngs    \r\n    Sd.topLeftCorner(cardt, cardt) = makeSubS(S, indj.head(cardt));\r\n    Dd.topLeftCorner(cardt, cardt) = makeSubS(M, indj.head(cardt));\r\n    \r\n    //  compute loadings        \r\n    GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(Dd.topLeftCorner(cardt, cardt),\r\n                                                          Sd.topLeftCorner(cardt, cardt));\r\n    // save loadings \r\n    a.head(cardt) = es.eigenvectors().col(cardt - 1);\r\n    // save loadings in column j\r\n    for (int i = 0; i < cardt; i++){\r\n      A(indj(i), j) = es.eigenvectors()(i, cardt - 1);\r\n    }\r\n    // save loadings in list\r\n    indout[j] = indj.head(cardt).array() + 1;\r\n\r\n    nc = nc + 1;\r\n    \r\n    // this new func deflates S and M using only last vector of loads\r\n    // returns deflated matr by references and vexp (not cum vexp)\r\n    deflSandDC(a.head(cardt), K, M, indj.head(cardt), cvt);\r\n\r\n    vexp(j) = cvt;\r\n    if (j > 0)\r\n      cvexp(j) = cvt + cvexp(j-1);\r\n    else\r\n      cvexp(j) = cvt;\r\n\r\n    // checks if stopComp met\r\n    if ((cvexp(j) > pvexp * totvexp) || ((j + 1) == ncomps)){\r\n      stopComp = true;\r\n      ncomps = nc;\r\n    }\r\n    else{\r\n      if (newpc == true){\r\n        SelfAdjointEigenSolver<Eigen::MatrixXd> es(K);\r\n        // // this is ok because X'K = K'K, so X'Kv = K'Kv = v*lambda_1        \r\n        maxvexp =  es.eigenvalues()(p-1);\r\n        si = es.eigenvectors().col(p-1).array() * maxvexp;\r\n        // this power method, returns si and passes maxvexp byref\r\n        //si = eigvecPMC(K, maxvexp, eps);\r\n      }\r\n      else{// this takes the jth pc\r\n        maxvexp =  vexppc(j); \r\n        si = vec.col(j).array() * maxvexp;\r\n      }  \r\n      j = j + 1;\r\n    }\r\n  }//end compute comps\r\n  \r\n  IntegerVector idx = Rcpp::seq(0, nc - 1);\r\n\r\n  return  List::create(Named(\"loadings\") = A.topLeftCorner(p,nc), Named(\"ncomps\") = nc, \r\n                       Named(\"ind\") = indout[idx], Named(\"card\") = card.head(nc), \r\n                       Named(\"vexp\") = vexp.head(nc), Named(\"cvexp\") = cvexp.head(nc));\r\n} ", "meta": {"hexsha": "9cc12e26adf6ec47edc26d1b60dd394212928456", "size": 11309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fspcaC_sept_passD.cpp", "max_stars_repo_name": "denis-rinfret/gioden", "max_stars_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fspcaC_sept_passD.cpp", "max_issues_repo_name": "denis-rinfret/gioden", "max_issues_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fspcaC_sept_passD.cpp", "max_forks_repo_name": "denis-rinfret/gioden", "max_forks_repo_head_hexsha": "39f5fab1311420e4b6f9b74e67eb24e9b6a0ab77", "max_forks_repo_licenses": ["Apache-2.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.6047120419, "max_line_length": 96, "alphanum_fraction": 0.5278981342, "num_tokens": 3603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5572482646463821}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <list>\n\n#include \"element.h\"\n#include \"assembly.h\"\n#include \"boundary.h\"\n\nusing namespace std;\nusing namespace arma;\n\n//TODO create material.h\n//TODO parse input file to initialize model data\n//TODO parse command line args\n//TODO it may make more sense to restructure data, each element containing\n//  pointers to node objects?\n\nint main(int argc, char** argv)\n{\n  cout << \"Program launched.\" << endl;\n  int i;\n\n  /* initialize model data */\n  const double h = 0.1;\n  const long long int E = 200e9;\n  const double v = 0.3;\n  const int rho = 7800;\n  const double g = 9.8;\n  \n  /* body and traction forces */\n  vec b(Q4__DOF_PER_NODE);\n  b     << 0            << endr \n        << -(rho * g)   << endr;\n  vec t(Q4__DOF_PER_NODE);\n  t     << 0            << endr\n        << 0            << endr;\n  \n  /* boundary conditions */\n  list<BC*> bounds;\n  bounds.push_front(new BC(0, 0));\n  bounds.push_front(new BC(1, 0));\n  bounds.push_front(new BC(3, 0));\n  bounds.push_front(new BC(5, 0));\n  \n  /* mesh */\n  cout << \"Creating mesh...\" << endl;\n  \n  const int numElem = 2;\n  const int numNodes = 6;\n  \n  int gnodes[] = {1, 2, 5, 4};\n  mat gcoords(Q4__NUM_NODES, Q4__DOF_PER_NODE);\n  gcoords   << 0.    << 0.    << endr\n            << 10.   << 2.    << endr\n            << 5.    << 8.    << endr\n            << 2.    << 6.    << endr;\n  int gdofs[] = {1, 2, 3, 4, 9, 10, 7, 8};\n  Q4 *elem = new Q4(E, v, h, &b, &t, gnodes, &gcoords, gdofs);\n  \n  int gnodes2[] = {2, 3, 6, 5};\n  mat gcoords2(Q4__NUM_NODES, Q4__DOF_PER_NODE);\n  gcoords2  << 10.   << 2.    << endr\n            << 20.   << 0.    << endr\n            << 17.   << 6.    << endr\n            << 5.    << 8.    << endr;\n  int gdof2[] = {3, 4, 5, 6, 11, 12, 9, 10};\n  Q4 *elem2 = new Q4(E, v, h, &b, &t, gnodes2, &gcoords2, gdof2);\n  \n  /* calculate element stiffnesses and assemble */\n  cout << \"Analyzing discretized system...\" << endl;\n  \n  MechElem *pelems[numElem] = {elem, elem2};\n  \n  mat kg = zeros<mat>(Q4__DOF_PER_NODE*numNodes, Q4__DOF_PER_NODE*numNodes);\n  mglobalStiffness(kg, pelems, numElem, Q4__DOF_PER_NODE*Q4__NUM_NODES, PSTRESS);\n  \n  cout << endl << \"Global Stiffness Matrix\" << endl\n       << kg << endl;\n  \n  /* calculate element body forces and assemble */\n  vec bg(Q4__DOF_PER_NODE*numNodes);\n  mglobalBodyForce(bg, pelems, numElem, Q4__DOF_PER_NODE*Q4__NUM_NODES);\n  \n  cout << endl << \"Global Body Force\" << endl\n       << bg << endl;\n  \n  /* assemble global force vector */\n  vec fg = zeros<vec>(Q4__DOF_PER_NODE*numNodes);\n  fg(4) = 10.e3;\n  fg(7) = -10.e3;\n  fg(9) = -10.e3;\n  for (i = 0; i < Q4__DOF_PER_NODE*numNodes; i++)\n    fg(i) += bg(i);\n    \n  cout << endl << \"Global Force\" << endl\n       << fg << endl;\n    \n  /* impose boundary condtions */\n  cout << endl << \"Imposing boundary conditions...\" << endl;\n  mimposeBoundaryConds(kg, fg, bounds);\n  \n  /* solve for displacements */\n  cout << \"Solving for displacements...\" << endl;\n  vec ug = zeros<vec>(Q4__DOF_PER_NODE*numNodes);\n  if (!solve(ug, kg, fg))\n  {\n    cout << endl << \"Error: solution not found\" << endl;\n    return 1;\n  }\n  \n  /* display answer */\n  cout << endl << \"================================\" << endl;\n  cout << endl << \"Modified Global Stiffness Matrix (by imposing EBCs)\" << endl\n       << kg << endl;\n  cout << endl << \"Modified Global Force (by imposing EBCs)\" << endl\n       << fg << endl;\n  cout << endl << \"Global Displacements\" << endl\n       << ug << endl;\n\n  /* clean up dynamic memory */\n  cout << endl << \"Cleaning up allocated memory...\" << endl;\n  for (BC *pbc : bounds) delete pbc;\n  delete elem;\n  delete elem2;\n  \n  return 0;\n}\n", "meta": {"hexsha": "99bbb6847f881590e575f97b12faac6941ee88c8", "size": 3651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.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/main.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/main.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": 28.5234375, "max_line_length": 81, "alphanum_fraction": 0.5672418515, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.557248259597073}}
{"text": "/**\n * \\file dcs/math/traits/float.hpp\n *\n * \\brief Traits class for floating-point type.\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_TRAITS_FLOAT_HPP\n#define DCS_MATH_TRAITS_FLOAT_HPP\n\n\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <dcs/math/detail/float.hpp>\n#include <limits>\n\n\nnamespace dcs { namespace math {\n\ntemplate <typename T, typename Enable_ = void>\nstruct float_traits;\n\ntemplate <typename T>\nstruct float_traits<T, typename ::boost::enable_if< ::boost::is_floating_point<T> >::type>\n{\n\t/// Default tolerance for floating-point comparison.\n\tstatic const T tolerance;\n\n\tstatic bool approximately_equal(T x, T y, T tol)\n\t{\n\t\treturn detail::approximately_equal(x, y, tol);\n\t}\n\n\n\tstatic bool approximately_equal(T x, T y)\n\t{\n\t\treturn detail::approximately_equal(x, y, tolerance);\n\t}\n\n\n\tstatic bool essentially_equal(T x, T y, T tol)\n\t{\n\t\treturn detail::essentially_equal(x, y, tol);\n\t}\n\n\n\tstatic bool essentially_equal(T x, T y)\n\t{\n\t\treturn detail::essentially_equal(x, y, tolerance);\n\t}\n\n\n\tstatic bool definitely_less(T x, T y, T tol)\n\t{\n\t\treturn detail::definitely_less(x, y, tol);\n\t}\n\n\n\tstatic bool definitely_less(T x, T y)\n\t{\n\t\treturn detail::definitely_less(x, y, tolerance);\n\t}\n\n\n\t/// \\deprecated Use \\c approximately_less_equal or \\c essentially_less_equal\n\tstatic bool definitely_less_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_less(x, y, tol) || approximately_equal(x, y, tol);\n\t}\n\n\n\t/// \\deprecated Use \\c approximately_less_equal or \\c essentially_less_equal\n\tstatic bool definitely_less_equal(T x, T y)\n\t{\n\t\treturn definitely_less_equal(x, y, tolerance);\n\t}\n\n\n\tstatic bool approximately_less_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_less(x, y, tol) || approximately_equal(x, y, tol);\n\t}\n\n\n\tstatic bool approximately_less_equal(T x, T y)\n\t{\n\t\treturn approximately_less_equal(x, y, tolerance);\n\t}\n\n\n\tstatic bool essentially_less_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_less(x, y, tol) || essentially_equal(x, y, tol);\n\t}\n\n\n\tstatic bool essentially_less_equal(T x, T y)\n\t{\n\t\treturn essentially_less_equal(x, y, tolerance);\n\t}\n\n\n\tstatic bool definitely_greater(T x, T y, T tol)\n\t{\n\t\treturn detail::definitely_greater(x, y, tol);\n\t}\n\n\n\tstatic bool definitely_greater(T x, T y)\n\t{\n\t\treturn detail::definitely_greater(x, y, tolerance);\n\t}\n\n\n\t/// \\deprecated Use \\c approximately_less_equal or \\c essentially_less_equal\n\tstatic bool definitely_greater_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_greater(x, y, tol) || approximately_equal(x, y, tol);\n\t}\n\n\n\t/// \\deprecated Use \\c approximately_greater_equal or \\c essentially_greater_equal\n\tstatic bool definitely_greater_equal(T x, T y)\n\t{\n\t\treturn definitely_greater_equal(x, y, tolerance);\n\t}\n\n\tstatic bool approximately_greater_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_greater(x, y, tol) || approximately_equal(x, y, tol);\n\t}\n\n\n\tstatic bool approximately_greater_equal(T x, T y)\n\t{\n\t\treturn approximately_greater_equal(x, y, tolerance);\n\t}\n\n\tstatic bool essentially_greater_equal(T x, T y, T tol)\n\t{\n\t\treturn definitely_greater(x, y, tol) || essentially_equal(x, y, tol);\n\t}\n\n\n\tstatic bool essentially_greater_equal(T x, T y)\n\t{\n\t\treturn essentially_greater_equal(x, y, tolerance);\n\t}\n\n\t/// \\deprecated Use \\c definitely_min\n\tstatic T min(T x, T y, T tol = tolerance)\n\t{\n\t\tif (definitely_less(x, y, tol))\n\t\t{\n\t\t\treturn x;\n\t\t}\n\t\treturn y;\n\t}\n\n\t/// \\deprecated Use \\c definitely_max\n\tstatic T max(T x, T y, T tol = tolerance)\n\t{\n\t\tif (definitely_greater(x, y, tol))\n\t\t{\n\t\t\treturn x;\n\t\t}\n\t\treturn y;\n\t}\n\n\tstatic T definitely_min(T x, T y, T tol = tolerance)\n\t{\n\t\tif (definitely_less(x, y, tol))\n\t\t{\n\t\t\treturn x;\n\t\t}\n\t\treturn y;\n\t}\n\n\tstatic T definitely_max(T x, T y, T tol = tolerance)\n\t{\n\t\tif (definitely_greater(x, y, tol))\n\t\t{\n\t\t\treturn x;\n\t\t}\n\t\treturn y;\n\t}\n\n/*\nbool is_nan(float f)\n{\n    return (*reinterpret_cast<uint32_t*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<uint32_t*>(&f) & 0x007fffff) != 0;\n}\n\nbool is_finite(float f)\n{\n    return (*reinterpret_cast<uint32_t*>(&f) & 0x7f800000) != 0x7f800000;\n}\n\n// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)\n// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other\n#define UNEQUAL_NANS 1\n// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)\n// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX\n#define INFINITE_INFINITIES 1\n//\n// test whether two IEEE floats are within a specified number of representable values of each other\n// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers\nbool equal_float(float lhs, float rhs, uint32_t max_ulp_difference)\n{\n#ifdef UNEQUAL_NANS\n\tif(is_nan(lhs) || is_nan(rhs))\n\t{\n\t\treturn false;\n\t}\n#endif\n#ifdef INFINITE_INFINITIES\n\tif((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))\n\t{\n\t\treturn false;\n\t}\n#endif\n\tint32_t left(*reinterpret_cast<int32_t*>(&lhs));\n\t// transform signed magnitude ints into 2s complement signed ints\n\tif(left < 0)\n\t{\n\t\tleft = 0x80000000 - left;\n\t}\n\tint32_t right(*reinterpret_cast<int32_t*>(&rhs));\n\t// transform signed magnitude ints into 2s complement signed ints\n\tif(right < 0)\n\t{\n\t\tright = 0x80000000 - right;\n\t}\n\tif(static_cast<uint32_t>(std::abs(left - right)) <= max_ulp_difference)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n*/\n};\n\ntemplate <typename T>\nconst T float_traits<T, typename ::boost::enable_if< ::boost::is_floating_point<T> >::type>::tolerance = static_cast<T>(100)*::std::numeric_limits<T>::epsilon();\n\n}} // Namespace dcs::math\n\n\n#endif // DCS_MATH_TRAITS_FLOAT_HPP\n", "meta": {"hexsha": "ec572b045ec8ec6b012db7a005496b9d93e56728", "size": 6383, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/traits/float.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T19:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-26T19:03:40.000Z", "max_issues_repo_path": "include/dcs/math/traits/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/traits/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": 23.9063670412, "max_line_length": 161, "alphanum_fraction": 0.7115776281, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.557180769405853}}
{"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_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/detail/ellipsoid.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n\n/*!\n\\brief Point-point distance approximation taking flattening into account\n\\ingroup distance\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n\\author After Andoyer, 19xx, republished 1950, republished by Meeus, 1999\n\\note Although not so well-known, the approximation is very good: in all cases the results\nare about the same as Vincenty. In my (Barend's) testcases the results didn't differ more than 6 m\n\\see http://nacc.upc.es/tierra/node16.html\n\\see http://sci.tech-archive.net/Archive/sci.geo.satellite-nav/2004-12/2724.html\n\\see http://home.att.net/~srschmitt/great_circle_route.html (implementation)\n\\see http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115 (implementation)\n\\see http://futureboy.homeip.net/frinksamp/navigation.frink (implementation)\n\\see http://www.voidware.com/earthdist.htm (implementation)\n*/\ntemplate\n<\n    typename Point1,\n    typename Point2 = Point1,\n    typename CalculationType = void\n>\nclass andoyer\n{\n    public :\n    typedef typename promote_floating_point\n        <\n            typename select_calculation_type\n                <\n                    Point1,\n                    Point2,\n                    CalculationType\n                >::type\n        >::type calculation_type;\n\n        inline andoyer()\n            : m_ellipsoid()\n        {}\n\n        explicit inline andoyer(calculation_type f)\n            : m_ellipsoid(f)\n        {}\n\n        explicit inline andoyer(geometry::detail::ellipsoid<calculation_type> const& e)\n            : m_ellipsoid(e)\n        {}\n\n\n        inline calculation_type apply(Point1 const& point1, Point2 const& point2) const\n        {\n            return calc(get_as_radian<0>(point1), get_as_radian<1>(point1),\n                            get_as_radian<0>(point2), get_as_radian<1>(point2));\n        }\n\n        inline geometry::detail::ellipsoid<calculation_type> ellipsoid() const\n        {\n            return m_ellipsoid;\n        }\n\n        inline calculation_type radius() const\n        {\n            return m_ellipsoid.a();\n        }\n\n\n    private :\n        geometry::detail::ellipsoid<calculation_type> m_ellipsoid;\n\n        inline calculation_type calc(calculation_type const& lon1,\n                    calculation_type const& lat1,\n                    calculation_type const& lon2,\n                    calculation_type const& lat2) const\n        {\n            calculation_type const G = (lat1 - lat2) / 2.0;\n            calculation_type const lambda = (lon1 - lon2) / 2.0;\n\n            if (geometry::math::equals(lambda, 0.0)\n                && geometry::math::equals(G, 0.0))\n            {\n                return 0.0;\n            }\n\n            calculation_type const F = (lat1 + lat2) / 2.0;\n\n            calculation_type const sinG2 = math::sqr(sin(G));\n            calculation_type const cosG2 = math::sqr(cos(G));\n            calculation_type const sinF2 = math::sqr(sin(F));\n            calculation_type const cosF2 = math::sqr(cos(F));\n            calculation_type const sinL2 = math::sqr(sin(lambda));\n            calculation_type const cosL2 = math::sqr(cos(lambda));\n\n            calculation_type const S = sinG2 * cosL2 + cosF2 * sinL2;\n            calculation_type const C = cosG2 * cosL2 + sinF2 * sinL2;\n\n            calculation_type const c0 = 0;\n            calculation_type const c1 = 1;\n            calculation_type const c2 = 2;\n            calculation_type const c3 = 3;\n\n            if (geometry::math::equals(S, c0) || geometry::math::equals(C, c0))\n            {\n                return c0;\n            }\n\n            calculation_type const omega = atan(sqrt(S / C));\n            calculation_type const r3 = c3 * sqrt(S * C) / omega; // not sure if this is r or greek nu\n            calculation_type const D = c2 * omega * m_ellipsoid.a();\n            calculation_type const H1 = (r3 - c1) / (c2 * C);\n            calculation_type const H2 = (r3 + c1) / (c2 * S);\n            calculation_type const f = m_ellipsoid.f();\n\n            return D * (c1 + f * H1 * sinF2 * cosG2 - f * H2 * cosF2 * sinG2);\n        }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Point1, typename Point2>\nstruct tag<strategy::distance::andoyer<Point1, Point2> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct return_type<strategy::distance::andoyer<Point1, Point2> >\n{\n    typedef typename strategy::distance::andoyer<Point1, Point2>::calculation_type type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename P1, typename P2>\nstruct similar_type<andoyer<Point1, Point2>, P1, P2>\n{\n    typedef andoyer<P1, P2> type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename P1, typename P2>\nstruct get_similar<andoyer<Point1, Point2>, P1, P2>\n{\n    static inline andoyer<P1, P2> apply(andoyer<Point1, Point2> const& input)\n    {\n        return andoyer<P1, P2>(input.ellipsoid());\n    }\n};\n\ntemplate <typename Point1, typename Point2>\nstruct comparable_type<andoyer<Point1, Point2> >\n{\n    typedef andoyer<Point1, Point2> type;\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct get_comparable<andoyer<Point1, Point2> >\n{\n    static inline andoyer<Point1, Point2> apply(andoyer<Point1, Point2> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Point1, typename Point2>\nstruct result_from_distance<andoyer<Point1, Point2> >\n{\n    template <typename T>\n    static inline typename return_type<andoyer<Point1, Point2> >::type apply(andoyer<Point1, Point2> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, Point1, Point2, geographic_tag, geographic_tag>\n{\n    typedef strategy::distance::andoyer<Point1, Point2> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n", "meta": {"hexsha": "0834ba61cb62cbe120758c8a7fb3059f6fd8302d", "size": 6946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "max_stars_repo_name": "juslee/boost-svn", "max_stars_repo_head_hexsha": "6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T19:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:55:56.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "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": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "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": 30.8711111111, "max_line_length": 125, "alphanum_fraction": 0.6649870429, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.557142189671238}}
{"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/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <ceres/ceres.h>\n#include <chrono>\n#include <sophus/se3.hpp>\n\nusing namespace std;\nusing namespace cv;\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\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d(\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// Solve ICP with linear algebra (SVD solution)\nvoid pose_estimation_3d3d(vector<Eigen::Vector3d> pts1,\n                          vector<Eigen::Vector3d> pts2,\n                          Eigen::Matrix3d &R, Eigen::Vector3d &t) {\n  Eigen::Vector3d c1(0.0, 0.0, 0.0), c2(0.0, 0.0, 0.0);\n  for (auto& p : pts1)\n    c1 += p;\n  c1 /= pts1.size();\n  for (auto& p : pts2)\n    c2 += p;\n  c2 /= pts2.size();\n\n  for (auto& p : pts1)\n    p -= c1;\n  for (auto& p : pts2)\n    p -= c2;\n  \n  Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n  for (int i = 0; i < pts1.size(); ++i)\n  {\n    W += pts1[i] * pts2[i].transpose();\n  }\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  R = svd.matrixU() * svd.matrixV().transpose();\n  if (R.determinant() < 0)\n    R = -R;\n\n  t = c1 - R * c2;\n}\n\n\n\n// Local parameterization needed to handle SE3 from Sophus (from Sophus/test/ceres/)\nusing namespace Sophus;\nclass LocalParameterizationSE3 : public ceres::LocalParameterization {\n public:\n  virtual ~LocalParameterizationSE3() {}\n\n  // SE3 plus operation for Ceres\n  //\n  //  T * exp(x)\n  //\n  virtual bool Plus(double const* T_raw, double const* delta_raw,\n                    double* T_plus_delta_raw) const {\n    Eigen::Map<SE3d const> const T(T_raw);\n    Eigen::Map<Vector6d const> const delta(delta_raw);\n    Eigen::Map<SE3d> T_plus_delta(T_plus_delta_raw);\n    T_plus_delta = T * SE3d::exp(delta);\n    return true;\n  }\n\n  // Jacobian of SE3 plus operation for Ceres\n  //\n  // Dx T * exp(x)  with  x=0\n  //\n  virtual bool ComputeJacobian(double const* T_raw,\n                               double* jacobian_raw) const {\n    Eigen::Map<SE3d const> T(T_raw);\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> jacobian(\n        jacobian_raw);\n    jacobian = T.Dx_this_mul_exp_x_at_0();\n    return true;\n  }\n\n  virtual int GlobalSize() const { return SE3d::num_parameters; }\n\n  virtual int LocalSize() const { return SE3d::DoF; }\n};\n\n\n\n\nstruct ICPError\n{\n  ICPError(const Eigen::Vector3d& X1, const Eigen::Vector3d& X2)\n    : _X1(X1), _X2(X2)\n    {}\n\n    template <class T>\n    bool operator() (const T* const params, T* errors) const {\n      const Eigen::Map<const Sophus::SE3<T>> Rt(params);\n      Eigen::Map<Eigen::Matrix<T, 3, 1>> err(errors);\n      err = _X1 - Rt * _X2;\n      return true;\n    }\n  \n\n  private:\n    Eigen::Vector3d _X1;\n    Eigen::Vector3d _X2;\n};\n\n\n// Solve ICP with non-linear optimization\nvoid bundleAdjustment(\n  const vector<Eigen::Vector3d> &pts1,\n  const vector<Eigen::Vector3d> &pts2,\n  Eigen::Matrix3d &R, Eigen::Vector3d &t) {\n\n    Sophus::SE3d pose(R, t);\n    ceres::Problem problem;\n    for (int i = 0; i < pts1.size(); ++i)\n    {\n      problem.AddResidualBlock(\n        new ceres::AutoDiffCostFunction<ICPError, 3, 7>( // in g2o we use size 6 because its the size of the delta_x, here its the real size, the delta_x is handle in the local parameterization\n          new ICPError(pts1[i], pts2[i])\n        ),\n        nullptr,\n        pose.data()\n      );\n    }\n\n    problem.SetParameterization(pose.data(), new LocalParameterizationSE3);\n\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n    options.minimizer_progress_to_stdout = true;\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    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optimization ICP (ceres) costs time: \" << time_used.count() << \" seconds.\" << endl;\n    std::cout << summary.BriefReport() << \"\\n\";\n\n\n    R = pose.so3().unit_quaternion().toRotationMatrix();\n    t = pose.translation();\n  }\n\nint main(int argc, char **argv) {\n  // if (argc != 5) {\n  //   cout << \"usage: pose_estimation_3d3d 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  string f4 = \"../2_depth.png\"; //argv[3];\n\n  Mat img_1 = imread(f1, CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(f2, 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\n  Mat depth1 = imread(f3, CV_LOAD_IMAGE_UNCHANGED);\n  Mat depth2 = imread(f4, 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  Eigen::Matrix3d K_eigen;\n  K_eigen << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1;\n  std::vector<Eigen::Vector3d> pts1, pts2;\n\n  for (DMatch m:matches) {\n    ushort d1 = depth1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    ushort d2 = depth2.ptr<unsigned short>(int(keypoints_2[m.trainIdx].pt.y))[int(keypoints_2[m.trainIdx].pt.x)];\n    if (d1 == 0 || d2 == 0)   // bad depth\n      continue;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n    Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);\n    float dd1 = float(d1) / 5000.0;\n    float dd2 = float(d2) / 5000.0;\n    pts1.push_back(Eigen::Vector3d(p1.x * dd1, p1.y * dd1, dd1));\n    pts2.push_back(Eigen::Vector3d(p2.x * dd2, p2.y * dd2, dd2));\n  }\n\n  cout << \"3d-3d pairs: \" << pts1.size() << endl;\n  Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n  Eigen::Vector3d t = Eigen::Vector3d::Zero();\n  pose_estimation_3d3d(pts1, pts2, R, t);\n  cout << \"ICP via SVD results: \" << endl;\n  cout << \"R = \" << R << endl;\n  cout << \"t = \" << t.transpose() << endl;\n  // cout << \"R_inv = \" << R.t() << endl;\n  // cout << \"t_inv = \" << -R.t() * t << endl;\n\n  // verify p1 = R * p2 + t\n  double total_error = 0.0;\n  for (int i = 0; i < pts1.size(); i++) {\n    total_error += (pts1[i] - (R * pts2[i] + t)).norm();\n  }\n  std::cout << \"Mean error (SVD): \" << total_error / pts1.size() << \"\\n\";\n\n\n  cout << \"calling bundle adjustment\" << endl;\n  R = Eigen::Matrix3d::Identity();\n  t = Eigen::Vector3d::Zero();\n  bundleAdjustment(pts1, pts2, R, t);\n\n  // verify p1 = R * p2 + t\n  total_error = 0.0;\n  for (int i = 0; i < pts1.size(); i++) {\n    total_error += (pts1[i] - (R * pts2[i] + t)).norm();\n  }\n  std::cout << \"Mean error (BA): \" << total_error / pts1.size() << \"\\n\";\n}\n\n", "meta": {"hexsha": "0defbb986da03f599d7fd7c387bde7a9d19bf1b8", "size": 8341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d3d_icp_ceres.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_3d3d_icp_ceres.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_3d3d_icp_ceres.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": 31.7148288973, "max_line_length": 193, "alphanum_fraction": 0.6227071095, "num_tokens": 2697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.5571421872022484}}
{"text": "\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Copyright Paul A. Bristow 2015.\r\n// Copyright Christopher Kormanyos 2015.\r\n// Copyright Nikhar Agrawal 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// Below are snippets of code that can be included into a Quickbook file.\r\n\r\n#include <exception>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <limits>\r\n#include <typeinfo>\r\n#include <type_traits>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/math/special_functions/pow.hpp>\r\n\r\ntemplate <typename T>\r\nvoid show_fixed_point_limits()\r\n{\r\n  // Ensure that type T is a fixed_point type,\r\n  // (although actually as written it will also work for floating-point types).\r\n  BOOST_STATIC_ASSERT_MSG(boost::fixed_point::is_fixed_point<T>::value == true, \"This function is designed for fixed_point types.\");\r\n\r\n  std::cout.precision(std::numeric_limits<T>::digits10);\r\n  std::cout << std::boolalpha\r\n            << std::showpoint\r\n            << std::showpos;\r\n\r\n  // Show the relevant numeric_limits.\r\n  std::cout << \"Numeric_limits of type:\\n\"\r\n            << typeid(T).name()\r\n            << \"\\n radix        = \" <<  std::numeric_limits<T>::radix\r\n            << \"\\n digits10     = \" <<  std::numeric_limits<T>::digits10\r\n            << \"\\n max_digits10 = \" <<  std::numeric_limits<T>::max_digits10\r\n            << \"\\n epsilon      = \" <<  std::numeric_limits<T>::epsilon()\r\n            << \"\\n lowest       = \" <<  std::numeric_limits<T>::lowest()\r\n            << \"\\n min          = \" << (std::numeric_limits<T>::min)()\r\n            << \"\\n max          = \" << (std::numeric_limits<T>::max)();\r\n\r\n  // If, most unexpectedly, type T has a representation for infinity or NaN, show them.\r\n  if (std::numeric_limits<T>::has_infinity)\r\n  {\r\n    std::cout << \"\\n infinity = \" << std::numeric_limits<T>::infinity();\r\n  }\r\n  else\r\n  {\r\n    std::cout << \"\\n Type does not have an infinity.\";\r\n  }\r\n  if (std::numeric_limits<T>::has_quiet_NaN)\r\n  {\r\n    std::cout << \"\\n NaN = \" << std::numeric_limits<T>::quiet_NaN();\r\n  }\r\n  else\r\n  {\r\n    std::cout << \"\\n Type does not have a NaN.\";\r\n  }\r\n  std::cout << std::endl;\r\n} // template <typename T> void show_fixed_point_limits\r\n\r\n/*! As an example, define a local fixed-point negatable type using 31 + sign bits,\r\nsplitting the bits equally to range and resolution.\r\n*/\r\ntypedef boost::fixed_point::negatable<15, -16> fixed_point_type;\r\n\r\nint main()\r\n{\r\n  try\r\n  {\r\n    //[fixed_point_limits_1\r\n    std::cout << \"Number of possible values is 2^[range + abs(resolution)] = 2^\"\r\n              << std::numeric_limits<fixed_point_type>::digits\r\n              << \" = \" << static_cast<long>(boost::math::pow<std::numeric_limits<fixed_point_type>::digits>(2))\r\n              << std::endl;\r\n    //] [/fixed_point_limits_1]\r\n    std::cout.precision(std::numeric_limits<fixed_point_type>::max_digits10); // Show all significant decimal digits.\r\n    //[fixed_point_limits_2\r\n    show_fixed_point_limits<fixed_point_type>();\r\n    //] [/fixed_point_limits_2]\r\n    std::cout << std::endl;\r\n  }\r\n  catch (const std::exception& ex)\r\n  {\r\n    std::cout << ex.what() << std::endl;\r\n  }\r\n} // int main()\r\n\r\n/*\r\n//[fixed_point_limits_output\r\n\r\nNumber of possible values is 2^[range + abs(resolution)] = 2^31 = -2147483648\r\nNumeric_limits of type:\r\nclass boost::fixed_point::negatable<15,-16,struct boost::fixed_point::round::fastest,struct boost::fixed_point::overflow::undefined>\r\n radix        = +2\r\n digits10     = +9\r\n max_digits10 = +11\r\n epsilon      = +3.0517578125e-005\r\n lowest       = -32767.999985\r\n min          = +1.5258789063e-005\r\n max          = +32767.999985\r\nType does not have an infinity.\r\nType does not have a NaN.\r\n\r\n//] [/fixed_point_limits_output]\r\n\r\n*/\r\n", "meta": {"hexsha": "cbf48bc60953f241ff791ab8fe9aa142f75c655a", "size": 4320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_limits.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_limits.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_limits.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1219512195, "max_line_length": 133, "alphanum_fraction": 0.6347222222, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.5570727954389215}}
{"text": "#include <iostream>\n#include <cmath>\n#include <numeric>\n#include <fstream>\n#include <algorithm>\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\n/*\nTODO :\n\n* mesurer l'ordre (être certain de l'ordre en temps et en espace)\n* chercher une autre source de bug qu'une erreur d'implémentation des schémas...\n\n*/\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\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  field2d<double> df(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  df.range = f.range;\n  df.steps = f.steps;\n\n  auto pacman = pacman_factory(1.0,0.5);\n  auto g = 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] = g(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  }\n\n  ublas::vector<double> x(Nx),y(Ny);\n  std::generate( x.begin() , x.end() , [&,count=0] () mutable { return f.x(count++); } );\n  std::generate( y.begin() , y.end() , [&,count=0] () mutable { return f.y(count++); } );\n\n  auto save_f = [&](std::string filename) {\n    std::ofstream of(filename);\n    of << f << std::endl;\n    of.close();\n  };\n\n  save_f(\"finit.dat\");\n\n  double dt= 1.3*f.steps.dx/(2.0*xmax);\n  double Tf= .5*math::pi<double>();\n  double current_time = 0.0;\n\n  auto Lij = [&](double tn , const field2d<double> & u , std::size_t i, std::size_t j){\n    //return - (weno2d::weno_x( -y[j] ,u,i,j) + weno2d::weno_y(  x[i] ,u,i,j));\n    return - (weno2d::weno_x( -u.y(j) ,u,i,j) + weno2d::weno_y(  u.x(i) ,u,i,j));\n    //return - ( weno2d::weno_x( -2.0 ,u,i,j) + weno2d::weno_y( 0.0 ,u,i,j) );\n  };\n\n  auto Lij_x = [](double tn , const field2d<double> & u , std::size_t i, std::size_t j){\n    return -weno2d::weno_x( -u.y(j) ,u,i,j);\n  };\n  auto Lij_y = [](double tn , const field2d<double> & u , std::size_t i, std::size_t j){\n    return  -weno2d::weno_y( u.x(j) ,u,i,j);\n  };\n\n  std::cout << \"dt: \"<< dt << \"\\tNiter: \" << std::floor(Tf/dt) << \"\\n\";\n  std::size_t i_iter = 0;\n  while ( i_iter*dt < Tf ) {\n    std::cout << current_time << \" \\r\" << std::flush;\n\n    //f = rk33( Lij , current_time , f , dt );\n\n    f = Lie::phi1( current_time , f , 0.5*dt );\n    f = Lie::phi2( current_time , f , dt );\n    f = Lie::phi1( current_time , f , 0.5*dt );\n\n    ++i_iter;\n    current_time += dt;\n  }\n  std::cout << current_time << std::endl;\n\n  save_f(\"fend.dat\");\n\n  return 0;\n}", "meta": {"hexsha": "d1533570bb196eda5549ba491ca8e44e7b289de4", "size": 3250, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc/test_trp/2d/main.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/main.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/main.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": 28.2608695652, "max_line_length": 107, "alphanum_fraction": 0.564, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5569833267609063}}
{"text": "/*\nExample to show conversions to/from Transformation Matrix\n\nZivid primarily operate with a (4x4) Transformation Matrix (Rotation Matrix + Translation Vector). \nThis example shows how to use Eigen to convert to and from:\n  AxisAngle, Rotation Vector, Roll-Pitch-Yaw, Quaternion\n\n It provides convenience functions that can be reused in applicable applications.\n*/\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include <iomanip>\n#include <iostream>\n\nenum class RotationConvention\n{\n    ZYX_Intrinsic,\n    XYZ_Extrinsic,\n    XYZ_Intrinsic,\n    ZYX_Extrinsic,\n    NOF_ROT\n};\nconstexpr size_t nofRotationConventions = static_cast<size_t>(RotationConvention::NOF_ROT);\n\nstruct RollPitchYaw\n{\n    RotationConvention convention;\n    Eigen::Array3d rollPitchYaw;\n};\n\nstruct Representations\n{\n    Eigen::AngleAxisd axisAngle;\n    Eigen::Vector3d rotationVector;\n    Eigen::Quaterniond quaternion;\n    std::array<RollPitchYaw, nofRotationConventions> rotations;\n};\n\nEigen::Affine3d getTransformationMatrixFromYAML(const std::string &path);\nvoid saveTransformationMatrixToYAML(const Eigen::Affine3d &, const std::string &path);\ncv::Mat eigenToCv(const Eigen::MatrixXd &);\nEigen::MatrixXd cvToEigen(const cv::Mat &);\nEigen::Array3d rotationMatrixToRollPitchYaw(const Eigen::Matrix3d &rotationMatrix, const RotationConvention &rotation);\nEigen::Matrix3d rollPitchYawToRotationMatrix(const Eigen::Array3d &rollPitchYaw, const RotationConvention &rotation);\nstd::string toString(RotationConvention convention);\nRepresentations zividToRobot(const Eigen::Affine3d &);\nEigen::Affine3d robotToZivid(const Representations &, const Eigen::Vector3d &);\n\nint main()\n{\n    try\n    {\n        std::cout << std::setprecision(4);\n        std::cout << \"This example shows conversions to/from Transformation Matrix\" << std::endl;\n\n        const auto transformationMatrix = getTransformationMatrixFromYAML(\"robotTransform.yaml\");\n        std::cout << transformationMatrix.matrix() << std::endl;\n\n        // Extract Rotation Matrix and Translation Vector from Transformation Matrix\n        std::cout << \"RotationMatrix:\\n\" << transformationMatrix.linear() << std::endl;\n        std::cout << \"TranslationVector:\\n\" << transformationMatrix.translation() << std::endl;\n\n        // Convert from Zivid to Robot (Transformation Matrix --> any format)\n        const auto robotRotationRepresentations = zividToRobot(transformationMatrix);\n\n        // Convert from Robot to Zivid (any format --> Rotation Matrix)\n        const auto transformationMatrix2 =\n            robotToZivid(robotRotationRepresentations, transformationMatrix.translation());\n\n        // Combine Rotation Matrix with Translation Vector to form Transformation Matrix\n        saveTransformationMatrixToYAML(transformationMatrix2, \"robotTransformOut.yaml\");\n    }\n\n    catch(const std::exception &e)\n    {\n        std::cerr << \"Error: \" << e.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n}\n\nEigen::Affine3d getTransformationMatrixFromYAML(const std::string &path)\n{\n    std::cout << \"Opening .YAML file which contains transformation matrix (PoseState node)\" << std::endl;\n    cv::FileStorage fileStorageIn;\n    if(!fileStorageIn.open(path, cv::FileStorage::Mode::READ))\n    {\n        throw std::runtime_error(\"Could not open \" + path + \". Please run this sample from the build directory\");\n    }\n    const auto poseStateNode = fileStorageIn[\"PoseState\"];\n    std::cout << \"Getting PoseState:\" << std::endl;\n    if(poseStateNode.empty())\n    {\n        fileStorageIn.release();\n        throw std::runtime_error(\"PoseState node not found in file\");\n    }\n    auto transformationMatrix = Eigen::Affine3d(static_cast<Eigen::Matrix4d>(cvToEigen(poseStateNode.mat())));\n    fileStorageIn.release();\n\n    return transformationMatrix;\n}\n\nvoid saveTransformationMatrixToYAML(const Eigen::Affine3d &transformationMatrix, const std::string &path)\n{\n    // Save Transformation Matrix to .YAML file\n    cv::FileStorage fileStorageOut;\n    if(!fileStorageOut.open(path, cv::FileStorage::Mode::WRITE))\n    {\n        throw std::runtime_error(\"Could not open robotTransformOut.yaml for writing\");\n    }\n    fileStorageOut.write(\"TransformationMatrixFromQuaternion\", eigenToCv(transformationMatrix.matrix()));\n    fileStorageOut.release();\n}\n\ncv::Mat eigenToCv(const Eigen::MatrixXd &eigenMat)\n{\n    cv::Mat cvMat(static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols()), CV_64FC1, cv::Scalar(0));\n\n    cv::eigen2cv(eigenMat, cvMat);\n\n    return cvMat;\n}\n\nEigen::MatrixXd cvToEigen(const cv::Mat &cvMat)\n{\n    Eigen::MatrixXd eigenMat(cvMat.rows, cvMat.cols);\n\n    cv::cv2eigen(cvMat, eigenMat);\n\n    return eigenMat;\n}\n\nRepresentations zividToRobot(const Eigen::Affine3d &transformationMatrix)\n{\n    Representations robotRepresentations;\n    std::cout << \"\\nConverting Rotation Matrix to Axis-Angle\" << std::endl;\n    const Eigen::AngleAxisd axisAngle(transformationMatrix.linear());\n    std::cout << \"Axis:\\n\" << axisAngle.axis() << std::endl;\n    std::cout << \"Angle:\\n\" << axisAngle.angle() << std::endl;\n\n    // Axis-angle to Rotation Vector\n    std::cout << \"\\nConverting Axis-Angle to Rotation Vector:\" << std::endl;\n    robotRepresentations.rotationVector = axisAngle.angle() * axisAngle.axis();\n    std::cout << robotRepresentations.rotationVector << std::endl;\n\n    // Rotation Matrix to Quaternion\n    std::cout << \"\\nConverting Rotation Matrix to Quaternion:\" << std::endl;\n    const Eigen::Quaterniond quaternion(transformationMatrix.linear());\n    robotRepresentations.quaternion = quaternion;\n    std::cout << robotRepresentations.quaternion.coeffs() << std::endl;\n\n    // Rotation Matrix to Roll-Pitch-Yaw\n    for(size_t i = 0; i < nofRotationConventions; i++)\n    {\n        const RotationConvention convention{ static_cast<RotationConvention>(i) };\n        std::cout << \"\\nConverting Rotation Matrix to Roll-Pitch-Yaw angles (\" << toString(convention)\n                  << \"):\" << std::endl;\n        robotRepresentations.rotations[i] = { convention,\n                                              rotationMatrixToRollPitchYaw(transformationMatrix.linear(), convention) };\n        std::cout << robotRepresentations.rotations[i].rollPitchYaw << std::endl;\n    }\n\n    return robotRepresentations;\n}\n\nEigen::Affine3d robotToZivid(const Representations &representations, const Eigen::Vector3d &translationVector)\n{\n    // Roll-Pitch-Yaw to Rotation Matrix\n    for(const auto &rotation : representations.rotations)\n    {\n        std::cout << \"\\nConverting Roll-Pitch-Yaw angles (\" << toString(rotation.convention)\n                  << \") to Rotation Matrix:\" << std::endl;\n        const Eigen::Matrix3d rotationMatrixFromRollPitchYaw =\n            rollPitchYawToRotationMatrix(rotation.rollPitchYaw, rotation.convention);\n        std::cout << rotationMatrixFromRollPitchYaw << std::endl;\n    }\n\n    // Rotation Vector to Axis-angle\n    std::cout << \"\\nConverting Rotation Vector to Axis-Angle\" << std::endl;\n    const Eigen::AngleAxisd axisAngle(representations.rotationVector.norm(),\n                                      representations.rotationVector.normalized());\n    std::cout << \"Axis:\\n\" << axisAngle.axis() << std::endl;\n    std::cout << \"Angle:\\n\" << axisAngle.angle() << std::endl;\n\n    // Axis-Angle to Quaternion\n    std::cout << \"\\nConverting Axis-Angle to Quaternion:\" << std::endl;\n    const Eigen::Quaterniond quaternion(axisAngle);\n    std::cout << quaternion.coeffs() << std::endl;\n\n    // Quaternion to Rotation Matrix\n    std::cout << \"\\nConverting Quaternion to Rotation Matrix:\" << std::endl;\n    const auto rotationMatrixFromQuaternion = quaternion.toRotationMatrix();\n    std::cout << rotationMatrixFromQuaternion << std::endl;\n\n    Eigen::Affine3d transformationMatrix(rotationMatrixFromQuaternion);\n    transformationMatrix.translation() = translationVector;\n\n    return transformationMatrix;\n}\n\nstd::string toString(RotationConvention convention)\n{\n    switch(convention)\n    {\n        case RotationConvention::XYZ_Intrinsic: return \"XYZ_Intrinsic\";\n        case RotationConvention::XYZ_Extrinsic: return \"XYZ_Extrinsic\";\n        case RotationConvention::ZYX_Intrinsic: return \"ZYX_Intrinsic\";\n        case RotationConvention::ZYX_Extrinsic: return \"ZYX_Extrinsic\";\n        case RotationConvention::NOF_ROT: break;\n    }\n\n    throw std::invalid_argument(\"Invalid RotationConvention\");\n}\n\n// The following function converts Rotation Matrix to Roll-Pitch-Yaw angles in radians.\n// The rotation convention we use here is that Roll is a rotation about x-axis,\n// Pitch is a rotation about y-axis and Yaw is a rotation about z-axis.\n// Whether the axes are moving (intrinsic) or fixed (extrinsic) is defined by the rotation convention.\n// The array is ordered by Roll, Pitch and then Yaw.\nEigen::Array3d rotationMatrixToRollPitchYaw(const Eigen::Matrix3d &rotationMatrix, const RotationConvention &rotation)\n{\n    switch(rotation)\n    {\n        case RotationConvention::XYZ_Intrinsic: return rotationMatrix.eulerAngles(0, 1, 2);\n        case RotationConvention::XYZ_Extrinsic: return rotationMatrix.eulerAngles(2, 1, 0).reverse();\n        case RotationConvention::ZYX_Intrinsic: return rotationMatrix.eulerAngles(2, 1, 0).reverse();\n        case RotationConvention::ZYX_Extrinsic: return rotationMatrix.eulerAngles(0, 1, 2);\n        case RotationConvention::NOF_ROT: break;\n    }\n\n    throw std::invalid_argument(\"Invalid rotation\");\n}\n\n// The following function converts Roll-Pitch-Yaw angles in radians to Rotation Matrix.\n// This function takes an array of roll, pitch and yaw angles, and a rotation convention, as input parameters.\n// For Roll-Pitch-Yaw we define that roll is a rotation about x-axis, pitch is a rotation about y-axis\n// and yaw is a rotation about z-axis.\n// Whether the axes are moving (intrinsic) or fixed (extrinsic) is defined by the rotation convention.\n// The array is ordered by Roll, Pitch and then Yaw.\nEigen::Matrix3d rollPitchYawToRotationMatrix(const Eigen::Array3d &rollPitchYaw, const RotationConvention &rotation)\n{\n    switch(rotation)\n    {\n        case RotationConvention::XYZ_Intrinsic:\n        case RotationConvention::ZYX_Extrinsic:\n            return (Eigen::AngleAxisd(rollPitchYaw[0], Eigen::Vector3d::UnitX())\n                    * Eigen::AngleAxisd(rollPitchYaw[1], Eigen::Vector3d::UnitY())\n                    * Eigen::AngleAxisd(rollPitchYaw[2], Eigen::Vector3d::UnitZ()))\n                .matrix();\n        case RotationConvention::ZYX_Intrinsic:\n        case RotationConvention::XYZ_Extrinsic:\n            return (Eigen::AngleAxisd(rollPitchYaw[2], Eigen::Vector3d::UnitZ())\n                    * Eigen::AngleAxisd(rollPitchYaw[1], Eigen::Vector3d::UnitY())\n                    * Eigen::AngleAxisd(rollPitchYaw[0], Eigen::Vector3d::UnitX()))\n                .matrix();\n        case RotationConvention::NOF_ROT: break;\n    }\n\n    throw std::invalid_argument(\"Invalid orientation\");\n}\n", "meta": {"hexsha": "28e2615c0793b36abb1aacc5ddcc662a22f269eb", "size": 10997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_stars_repo_name": "knatten/cpp-extra-samples", "max_stars_repo_head_hexsha": "54bf513806f72f2e782cc620ccd4e85db96d50b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_issues_repo_name": "knatten/cpp-extra-samples", "max_issues_repo_head_hexsha": "54bf513806f72f2e782cc620ccd4e85db96d50b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_forks_repo_name": "knatten/cpp-extra-samples", "max_forks_repo_head_hexsha": "54bf513806f72f2e782cc620ccd4e85db96d50b3", "max_forks_repo_licenses": ["BSD-3-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.3421052632, "max_line_length": 120, "alphanum_fraction": 0.7071928708, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5569833210908431}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#include <Eigen/Dense>\n\n#include <boost/numeric/odeint.hpp>\n#include <cbr_math/lie/odeint.hpp>\n#include <cbr_control/mpc/mpc_tracking.hpp>\n#include <matplot/matplot.h>\n\n#include <chrono>\n#include <vector>\n#include <algorithm>\n\n#include \"so3_problem.hpp\"\n\nusing namespace std::chrono_literals;\n\n\nint main(int argc, char const * argv[])\n{\n  using state_t = SO3Problem::state_t;\n  using deriv_t = SO3Problem::deriv_t;\n  using input_t = SO3Problem::input_t;\n\n  //  -------------------------------------------------------------------------- /\n  //                              Simulation Params                              /\n  //  -------------------------------------------------------------------------- /\n\n  state_t x0{};\n  const auto tf = 10s;\n  const auto dt = 10ms;\n\n  auto xd = [](nanoseconds) {\n      return state_t(\n        Sophus::SO3d::rotZ(0.25) * Sophus::SO3d::rotY(-0.4) * Sophus::SO3d::rotX(0.5),\n        Eigen::Vector3d::Zero()\n      );\n    };\n\n  //  -------------------------------------------------------------------------- /\n  //                                      MPC                                    /\n  //  -------------------------------------------------------------------------- /\n\n  SO3Problem so3_ocp{};\n\n  cbr::MPCTrackingParams params;\n  params.T = 4;\n  params.solver_params.osqp_settings.verbose = 1;\n\n  cbr::MPCTracking<SO3Problem, 50> mpc(so3_ocp, params);\n  mpc.set_xd(xd);\n\n  //  -------------------------------------------------------------------------- /\n  //                                RUN SIMULATION                               /\n  //  -------------------------------------------------------------------------- /\n\n  nanoseconds t(0);\n  state_t x = x0;\n\n  cbr::lie::odeint::runge_kutta4<state_t, double, deriv_t, double> stepper;\n\n  std::vector<double> sol_t;\n  std::vector<input_t, Eigen::aligned_allocator<input_t>> sol_u;\n  std::vector<state_t, Eigen::aligned_allocator<state_t>> sol_x;\n\n  while (t < tf) {\n    mpc.update_sync(t, x);\n    const auto u = mpc.get_u(t);\n\n    sol_t.push_back(duration_cast<duration<double>>(t).count());\n    sol_x.push_back(x);\n    sol_u.push_back(u);\n\n    stepper.do_step(\n      [&so3_ocp, &u](const state_t & x, deriv_t & dr_x, const double) {\n        dr_x = so3_ocp.get_f(x, u);\n      },\n      x,\n      duration_cast<duration<double>>(t).count(),\n      duration_cast<duration<double>>(dt).count()\n    );\n\n    t += dt;\n  }\n\n  //  -------------------------------------------------------------------------- /\n  //                                PLOT RESULTS                                 /\n  //  -------------------------------------------------------------------------- /\n\n  // helper function to extract stuff from solutions\n  auto ex_fn = [](const auto & item, auto ex_fn) {\n      std::vector<double> ret;\n      std::transform(item.cbegin(), item.cend(), std::back_inserter(ret), ex_fn);\n      return ret;\n    };\n\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return std::get<0>(s).angleX();}))->line_width(2);\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return std::get<0>(s).angleY();}))->line_width(2);\n  matplot::plot(sol_t, ex_fn(sol_x, [](auto s) {return std::get<0>(s).angleZ();}))->line_width(2);\n  matplot::title(\"angles\");\n  matplot::legend({\"roll\", \"pitch\", \"yaw\"});\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::plot(\n    sol_t,\n    ex_fn(sol_x, [](auto s) {return std::get<1>(s).translation()(0);}))->line_width(2);\n  matplot::plot(\n    sol_t,\n    ex_fn(sol_x, [](auto s) {return std::get<1>(s).translation()(1);}))->line_width(2);\n  matplot::plot(\n    sol_t,\n    ex_fn(sol_x, [](auto s) {return std::get<1>(s).translation()(2);}))->line_width(2);\n  matplot::title(\"velocities\");\n  matplot::legend({\"vx\", \"vy\", \"vz\"});\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::plot(sol_t, ex_fn(sol_u, [](auto s) {return s(0);}))->line_width(2);\n  matplot::plot(sol_t, ex_fn(sol_u, [](auto s) {return s(1);}))->line_width(2);\n  matplot::plot(sol_t, ex_fn(sol_u, [](auto s) {return s(2);}))->line_width(2);\n  matplot::title(\"inputs\");\n  matplot::legend({\"ux\", \"uy\", \"uz\"});\n  matplot::show();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "409d82df02ff49ac53be5bf9607aeb36abfcfba2", "size": 4295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/so3_main.cpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/so3_main.cpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/so3_main.cpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.786259542, "max_line_length": 98, "alphanum_fraction": 0.5001164144, "num_tokens": 1129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.5569832989661286}}
{"text": "//\n// Phase Shift.cpp\n//\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cerrno>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <math.h>\n#include <mkl_lapack.h>\n#include <complex>\n#include <stdlib.h>\n#include <stdio.h>\n#include <boost/filesystem.hpp>\n\nusing namespace std;\n\ntypedef complex<double> dcmplx;\n\nint\t\tCalcPowerTableSize(int Omega);\nint\t\tReadMatrixElem(ifstream &FileMatrixElem, int NumShortTerms, vector <double> &ARow, vector <double> &B, double &SLS, int &IsTriplet, int &Ordering, int &LValue, int &Formalism, int &Omega, int &NumSets, double &Alpha1, double &Beta1, double &Gamma1, double &Alpha2, double &Beta2, double &Gamma2, double &Kappa, double &Mu, string &LString, int &Shielding, string &Lambda, double &Epsilon12, double &Epsilon13, bool &ExtraExponential);\nint\t\tReadShortHeader(ifstream &FileShortRange, int &Omega, int &LValue, int &IsTriplet, int &Formalism, int &Ordering, int &NumShortTerms, int &NumSets, int &Integration, double &Alpha1, double &Beta1, double &Gamma1, double &Alpha2, double &Beta2, double &Gamma2, bool &ExtraExponential, double &Epsilon12, double &Epsilon13, vector <int> &ExpLen);\nvoid\tWriteHeader(ofstream &OutFile, string &LString, int &LValue, char *FileShortName, char *FileMatrixElemName, char *EnergyFileName, bool &Paired, bool &Resorted,\n\t\t\t\tint &ShortInt, int &NumTerms, double &Kappa, double &Mu, int &Shielding, string &Lambda, double &Alpha, double &Beta, double &Gamma, string &ProgName);\nint\t\tCreateSubset(vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, vector <double> &ARowSub, vector <double> &BSub, vector <double> &ShortTermsSub, int NumShortTerms, int NSub);\nint\t\tFindOrderedToddTerm(string EnergyFilename, int TermToFind);\nint\t\tLoadToddTerms(int LValue, vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, vector <double> &ARowSub, vector <double> &BSub, vector <double> &ShortTermsSub, int NumShortTerms, int NSub, string EnergyFilename, bool Resorted, bool Paired, int ResortedSize);\nint\t\tTestToddFile(string EnergyFilename, int NumShortTerms);\nvoid\tuGenKohn(dcmplx (&u)[2][2], double Tau);\nvoid\tuGenTKohn(dcmplx (&u)[2][2], double Tau);\nvoid\tuGenSKohn(dcmplx (&u)[2][2], double Tau);\ndouble\tCombinedKohn(dcmplx (&u)[2][2], int NumShortTerms, vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, double SLS, int LValue, int IsTriplet);\nstring\tShortIntString(int &Integration);\nvoid\tFixPhase(double &PhaseShift, int &LValue, int &IsTriplet);\nstring\tGetDateTime(void);\n\n\n#define NUM_TAUARRAY 35\ndouble TauArray[NUM_TAUARRAY] = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.7853981633974483, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.570796326794897, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.356194490192345, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0, 3.141592653589793};\nconst char *DataHeader = \"       n |         Kohn            |       Inverse Kohn      |     Complex Kohn (S)    |     Complex Kohn (T) \"\n\t\"   |    Gen Kohn tau = 0.0   |    Gen Kohn tau = 0.1   |    Gen Kohn tau = 0.2   |    Gen Kohn tau = 0.3   |    Gen Kohn tau = 0.4   |    Gen Kohn tau = 0.5\"\n\t\"   |    Gen Kohn tau = 0.6   |    Gen Kohn tau = 0.7   |   Gen Kohn tau = pi/4   |    Gen Kohn tau = 0.8   |    Gen Kohn tau = 0.9   |    Gen Kohn tau = 1.0\"\n\t\"   |    Gen Kohn tau = 1.1   |    Gen Kohn tau = 1.2   |    Gen Kohn tau = 1.3   |    Gen Kohn tau = 1.4   |    Gen Kohn tau = 1.5   |   Gen Kohn tau = pi/2\"\n\t\"   |    Gen Kohn tau = 1.6   |    Gen Kohn tau = 1.7   |    Gen Kohn tau = 1.8   |    Gen Kohn tau = 1.9   |    Gen Kohn tau = 2.0\"\n\t\"   |    Gen Kohn tau = 2.1   |    Gen Kohn tau = 2.2   |    Gen Kohn tau = 2.3   |  Gen Kohn tau = 3*pi/4  |    Gen Kohn tau = 2.4   |    Gen Kohn tau = 2.5\"\n\t\"   |    Gen Kohn tau = 2.6   |    Gen Kohn tau = 2.7   |    Gen Kohn tau = 2.8   |    Gen Kohn tau = 2.9   |    Gen Kohn tau = 3.0   |    Gen Kohn tau = pi \"\n\t\"   |   Gen T Kohn tau = 0.0  |   Gen T Kohn tau = 0.1  |   Gen T Kohn tau = 0.2  |   Gen T Kohn tau = 0.3  |   Gen T Kohn tau = 0.4  |   Gen T Kohn tau = 0.5\"\n\t\"  |   Gen T Kohn tau = 0.6  |   Gen T Kohn tau = 0.7  |  Gen T Kohn tau = pi/4  |   Gen T Kohn tau = 0.8  |   Gen T Kohn tau = 0.9  |   Gen T Kohn tau = 1.0\"\n\t\"  |   Gen T Kohn tau = 1.1  |   Gen T Kohn tau = 1.2  |   Gen T Kohn tau = 1.3  |   Gen T Kohn tau = 1.4  |   Gen T Kohn tau = 1.5  |  Gen T Kohn tau = pi/2\"\n\t\"  |   Gen T Kohn tau = 1.6  |   Gen T Kohn tau = 1.7  |   Gen T Kohn tau = 1.8  |   Gen T Kohn tau = 1.9  |   Gen T Kohn tau = 2.0\"\n\t\"  |   Gen T Kohn tau = 2.1  |   Gen T Kohn tau = 2.2  |   Gen T Kohn tau = 2.3  | Gen T Kohn tau = 3*pi/4 |   Gen T Kohn tau = 2.4  |   Gen T Kohn tau = 2.5\"\n\t\"  |   Gen T Kohn tau = 2.6  |   Gen T Kohn tau = 2.7  |   Gen T Kohn tau = 2.8  |   Gen T Kohn tau = 2.9  |   Gen T Kohn tau = 3.0  |   Gen T Kohn tau = pi \"\n\t\"  |   Gen S Kohn tau = 0.0  |   Gen S Kohn tau = 0.1  |   Gen S Kohn tau = 0.2  |   Gen S Kohn tau = 0.3  |   Gen S Kohn tau = 0.4  |   Gen S Kohn tau = 0.5\"\n\t\"  |   Gen S Kohn tau = 0.6  |   Gen S Kohn tau = 0.7  |  Gen S Kohn tau = pi/4  |   Gen S Kohn tau = 0.8  |   Gen S Kohn tau = 0.9  |   Gen S Kohn tau = 1.0\"\n\t\"  |   Gen S Kohn tau = 1.1  |   Gen S Kohn tau = 1.2  |   Gen S Kohn tau = 1.3  |   Gen S Kohn tau = 1.4  |   Gen S Kohn tau = 1.5  |  Gen S Kohn tau = pi/2\"\n\t\"  |   Gen S Kohn tau = 1.6  |   Gen S Kohn tau = 1.7  |   Gen S Kohn tau = 1.8  |   Gen S Kohn tau = 1.9  |   Gen S Kohn tau = 2.0\"\n\t\"  |   Gen S Kohn tau = 2.1  |   Gen S Kohn tau = 2.2  |   Gen S Kohn tau = 2.3  | Gen S Kohn tau = 3*pi/4 |   Gen S Kohn tau = 2.4  |   Gen S Kohn tau = 2.5\"\n\t\"  |   Gen S Kohn tau = 2.6  |   Gen S Kohn tau = 2.7  |   Gen S Kohn tau = 2.8  |   Gen S Kohn tau = 2.9  |   Gen S Kohn tau = 3.0  |   Gen S Kohn tau = pi\";\n\n\ndcmplx uKohn[2][2] = {{dcmplx(1,0),dcmplx(0,0)}, {dcmplx(0,0),dcmplx(1,0)}};\ndcmplx uInvKohn[2][2] = {{dcmplx(0,0),dcmplx(1,0)}, {dcmplx(-1,0),dcmplx(0,0)}};\ndcmplx uCompSKohn[2][2] = {{dcmplx(0,1), dcmplx(-1,0)}, {dcmplx(0,1), dcmplx(1,0)}};\ndcmplx uCompTKohn[2][2] = {{dcmplx(1,0), dcmplx(0,0)}, {dcmplx(0,1), dcmplx(1,0)}};\n\n\nstd::string trim(const std::string& str,\n                 const std::string& whitespace = \" \\t\")\n{\n    const int strBegin = str.find_first_not_of(whitespace);\n    if (strBegin == std::string::npos)\n        return \"\"; // no content\n\n    const int strEnd = str.find_last_not_of(whitespace);\n    const int strRange = strEnd - strBegin + 1;\n\n    return str.substr(strBegin, strRange);\n}\n\n\nint main(int argc, char *argv[])\n{\n\tifstream FileMatrixElem, FileShortRange;\n\tofstream OutFile;\n\tstring LString, Lambda;\n\tdouble ShortAlpha1, ShortBeta1, ShortGamma1, ShortAlpha2, ShortBeta2, ShortGamma2, ShortEpsilon12, ShortEpsilon13, Kappa, Mu;\n\tdouble LongAlpha1, LongBeta1, LongGamma1, LongAlpha2, LongBeta2, LongGamma2, LongEpsilon12, LongEpsilon13;\n\tint ShortOmega, ShortLValue, ShortIsTriplet, ShortOrdering, /*ShortNumSets,*/ ShortFormalism;\n\tint LongOmega, LongLValue, LongIsTriplet, LongOrdering, LongNumSets, LongFormalism;\n\tint /*Ordering,*/ NumSets, NumShort, NumShortTotal, NumShortTermsFile, ShortInt, Shielding;\n\tvector <int> ExpLen;\n\tbool ExtraExponential;\n\tint TotalTerms;\n\n\tvector <double> ARow, B, ShortTerms;\n\tdouble *PhiPhi, *PhiHPhi;\n\tdouble SLS;\n\tvector <double> ARowSub, BSub, ShortTermsSub;\n\tdouble GenKohnPhase;\n\tbool Paired, Resorted = false;\n\tint TermStep;\n\tdcmplx u[2][2];\n\n\tstring ProgName = boost::filesystem::canonical(argv[0]).string();  // Get the absolute path of this program\n\n\t// Initialize the second set of nonlinear parameters for the files that don't use them.\n\tShortAlpha2 = 0.0; LongAlpha2 = 0.0; ShortBeta2 = 0.0; LongBeta2 = 0.0; ShortGamma2 = 0.0; LongGamma2 = 0.0;\n\n\tchar *FileMatrixElemName = argv[2];\n\tchar *FileShortName = argv[3];\n\tchar *OutFileName = argv[4];\n\tchar *EnergyFileName = argv[6];\n\n\tif (argc < 7) {\n\t\tcerr << \"Not enough parameters on the command line.\" << endl;\n\t\tcerr << \"Usage: Phase pairing matrixelements.txt shortrangefile.bin results.txt #terms (energyfile.txt) (resorted?)\" << endl;\n\t\tcerr << \"Example: Phase 1 matrixelements.txt shortrangefile.bin results.txt 84 energyfile.txt true\" << endl << endl;\n\t\tcerr << \" The pairing parameter is 0 for no pairing of terms for the two symmetries and\" << endl;\n\t\tcerr << \" 1 for pairing.\" << endl;\n\t\treturn 1;\n\t}\n\n\tif (atoi(argv[1]) == 0) {\n\t\tPaired = false;\n\t\tTermStep = 1;\n\t}\n\telse if (atoi(argv[1]) == 1) {\n\t\tPaired = true;\n\t\tTermStep = 2;\n\t}\n\telse {\n\t\tcout << \"The pairing entry must be either 0 or 1.\" << endl;\n\t\treturn 2;\n\t}\n\n\tFileMatrixElem.open(FileMatrixElemName);\n\tif (FileMatrixElem.fail()) {\n\t\tcerr << \"Unable to open file \" << FileMatrixElemName << \" for reading.\" << endl;\n\t\treturn 2;\n\t}\n\n\tFileShortRange.open(FileShortName, ios::in | ios::binary);\n\tif (FileShortRange.fail()) {\n\t\tcerr << \"Unable to open file \" << FileShortName << \" for reading.\" << endl;\n\t\treturn 3;\n\t}\n\n\tOutFile.open(OutFileName);\n\tif (!OutFile.is_open()) {\n\t\tcout << \"Could not open output file...exiting.\" << endl;\n\t\treturn 4;\n\t}\n\tTotalTerms = atoi(argv[5]);\n\n\tif (argc > 6) {\n\t\tint ToddTermNum = TestToddFile(EnergyFileName, TotalTerms);\n\t\tif (ToddTermNum < TotalTerms) {\n\t\t\tcout << \"Using less than the requested number of terms: \" << ToddTermNum << \" instead of \" << TotalTerms << endl;\n\t\t\tTotalTerms = ToddTermNum;\n\t\t}\n\t}\n\n\tif (argc > 7) {\n\t\t//@TODO: Case-insensitive string compare\n\t\tif (string(argv[7]) == \"true\") {\n\t\t\tResorted = true;\n\t\t\tcout << \"Computations will be performed with the terms resorted.\" << endl;\n\t\t}\n\t\t// Any other string just sets Resorted to false.\n\t\telse {\n\t\t\tcout << \"Computations will be performed with the ordering specified in the energy file.\" << endl;\n\t\t}\n\t}\n\n\t// Include trailing zeros so the columns line up in the output file.\n\tcout.setf(ios::showpoint);\n\tOutFile.setf(ios::showpoint);\n\tcout << setprecision(18);\n\tOutFile << setprecision(18);\n\n\tint err = ReadShortHeader(FileShortRange, ShortOmega, ShortLValue, ShortIsTriplet, ShortFormalism, ShortOrdering, NumShortTermsFile, NumSets, ShortInt, ShortAlpha1, ShortBeta1, ShortGamma1, ShortAlpha2, ShortBeta2, ShortGamma2, ExtraExponential, ShortEpsilon12, ShortEpsilon13, ExpLen);\n\tif (err == -1) {\n\t\treturn 8;\n\t}\n\n\t// Calculate number of terms for a given omega and generate the r-powers.\n\tNumShort = CalcPowerTableSize(ShortOmega);\n\tif (NumShort != NumShortTermsFile) {\n\t\t//cout << \"Number of terms does not match in files...exiting.\" << endl;\n\t\t//return 2;\n\t}\n\n\t// The P-wave files have double the number of elements.\n\t//NumShortTerms = NumShortTerms*(ShortLValue+1);\n\n\tif (ShortLValue == 0)\n\t\tNumShortTotal = NumShort;  // The S-wave only has one symmetry\n\telse\n\t\tNumShortTotal = NumShort * 2;\n\n\t// Allocate PhiPhi and PhiHPhi matrices\n\tPhiPhi = new double[NumShortTotal*NumShortTotal];\n\tPhiHPhi = new double[NumShortTotal*NumShortTotal];\n\tif (PhiPhi == NULL || PhiHPhi == NULL) {\n\t\tcout << \"Memory allocation error\" << endl;\n\t\treturn 5;\n\t}\n\n\t// Read in the <phi|phi> and <phi|H|phi> matrix elements.\n\tFileShortRange.read((char*)PhiPhi, NumShortTotal*NumShortTotal*sizeof(double));\n\tFileShortRange.read((char*)PhiHPhi, NumShortTotal*NumShortTotal*sizeof(double));\n\n\tARow.resize(NumShortTotal+1);\n\tB.resize(NumShortTotal+1);\n\tShortTerms.resize(NumShortTotal*NumShortTotal);\n\terr = ReadMatrixElem(FileMatrixElem, NumShortTotal, ARow, B, SLS, LongIsTriplet, LongOrdering, LongLValue, LongFormalism, LongOmega, LongNumSets, LongAlpha1, LongBeta1, LongGamma1, LongAlpha2, LongBeta2, LongGamma2, Kappa, Mu, LString, Shielding, Lambda, LongEpsilon12, LongEpsilon13, ExtraExponential);\n\tif (err == -1)\n\t\treturn 6;\n\n\t// Compare the short-range and long-range files to make sure they are describing the same problem.\n\tif ((LongLValue != ShortLValue && ShortLValue != 0) || LongIsTriplet != ShortIsTriplet || LongOrdering != ShortOrdering || LongOmega != ShortOmega || LongAlpha1 != ShortAlpha1 || LongBeta1 != ShortBeta1 || LongGamma1 != ShortGamma1 || LongAlpha2 != ShortAlpha2 || LongBeta2 != ShortBeta2 || LongGamma2 != ShortGamma2) {\n\t\tcout << \"Short-range and long-range files describe different problems...exiting.\" << endl;\n\t\treturn 8;\n\t}\n\n\tfor (int i = 0; i < NumShortTotal*NumShortTotal; i++) {\n\t\tShortTerms[i] = PhiHPhi[i] - 0.5*Kappa*Kappa * PhiPhi[i] + 1.5*PhiPhi[i];\n\t\t//ShortTerms[i] = PhiHPhi[i] - Kappa*Kappa * PhiPhi[i] + 1.5*PhiPhi[i];  // For electron or positron scattering\n\t}\n\n\tdelete [] PhiPhi;\n\tdelete [] PhiHPhi;\n\n\tWriteHeader(OutFile, LString, ShortLValue, FileShortName, FileMatrixElemName, EnergyFileName, Paired, Resorted,\n\t\t\t\tShortInt, TotalTerms, Kappa, Mu, Shielding, Lambda, ShortAlpha1, ShortBeta1, ShortGamma1, ProgName);\n\n\tint FieldWidth = 25;\n\n\tfor (int i = 0; i <= TotalTerms; i++) {\n\t\tLoadToddTerms(ShortLValue, ARow, B, ShortTerms, ARowSub, BSub, ShortTermsSub, NumShortTotal, i, EnergyFileName, Resorted, Paired, TotalTerms);\n\t\tdouble KohnPhase = CombinedKohn(uKohn, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\tdouble InvKohnPhase = CombinedKohn(uInvKohn, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\tdouble CompKohnSPhase = CombinedKohn(uCompSKohn, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\tdouble CompKohnTPhase = CombinedKohn(uCompTKohn, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\tif ((KohnPhase == 0.0) || (InvKohnPhase == 0.0) || (CompKohnSPhase == 0.0) || (CompKohnTPhase == 0.0)) {\n\t\t\tcout << \"Terminating loop early due to LAPACK errors.\" << endl;\n\t\t\tOutFile << \"Terminating loop early due to LAPACK errors.\" << endl;\n\t\t\tbreak;\n\t\t}\n\t\tcout << i << \" \" << KohnPhase << \" \" << InvKohnPhase << \" \" << CompKohnSPhase << \" \" << CompKohnTPhase << endl;\n\t\tOutFile << setw(8) << i << setw(1) << \" \" << setw(FieldWidth) << KohnPhase << setw(1) << \" \" << setw(FieldWidth) << InvKohnPhase << setw(1) << \" \" << setw(FieldWidth)\n\t\t\t\t<< CompKohnSPhase << setw(1) << \" \" << setw(FieldWidth) << CompKohnTPhase;\n\n\t\t// Generalized Kohn\n\t\tfor (int t = 0; t < NUM_TAUARRAY; t++) {\n\t\t\tLoadToddTerms(ShortLValue, ARow, B, ShortTerms, ARowSub, BSub, ShortTermsSub, NumShortTotal, i, EnergyFileName, Resorted, Paired, TotalTerms);\n\t\t\tuGenKohn(u, TauArray[t]);\n\t\t\tGenKohnPhase = CombinedKohn(u, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\t\tif (GenKohnPhase == 0.0)\n\t\t\t\tbreak;\n\t\t\tOutFile << setw(1) << \" \" << setw(FieldWidth) << GenKohnPhase;\n\t\t}\n\n\t\t// Generalized T-matrix\n\t\tfor (int t = 0; t < NUM_TAUARRAY; t++) {\n\t\t\tLoadToddTerms(ShortLValue, ARow, B, ShortTerms, ARowSub, BSub, ShortTermsSub, NumShortTotal, i, EnergyFileName, Resorted, Paired, TotalTerms);\n\t\t\tuGenTKohn(u, TauArray[t]);\n\t\t\tGenKohnPhase = CombinedKohn(u, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\t\tif (GenKohnPhase == 0.0)\n\t\t\t\tbreak;\n\t\t\tOutFile << setw(1) << \" \" << setw(FieldWidth) << GenKohnPhase;\n\t\t}\n\n\t\t// Generalized S-matrix\n\t\tfor (int t = 0; t < NUM_TAUARRAY; t++) {\n\t\t\tLoadToddTerms(ShortLValue, ARow, B, ShortTerms, ARowSub, BSub, ShortTermsSub, NumShortTotal, i, EnergyFileName, Resorted, Paired, TotalTerms);\n\t\t\tuGenSKohn(u, TauArray[t]);\n\t\t\tGenKohnPhase = CombinedKohn(u, i*TermStep, ARowSub, BSub, ShortTermsSub, SLS, ShortLValue, ShortIsTriplet);\n\t\t\tif (GenKohnPhase == 0.0)\n\t\t\t\tbreak;\n\t\t\tOutFile << setw(1) << \" \" << setw(FieldWidth) << GenKohnPhase;\n\t\t}\n\t\tif (GenKohnPhase == 0.0) {\n\t\t\tcout << \"Terminating loop early due to LAPACK errors.\" << endl;\n\t\t\tOutFile << \"Terminating loop early due to LAPACK errors.\" << endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tOutFile << setw(1) << \" \" << endl;\n\t}\n\n\tOutFile << \"</data>\" << endl << \"</psh_data>\" << endl;\n\n\tFileMatrixElem.close();\n\tFileShortRange.close();\n\tOutFile.close();\n\n\treturn 0;\n}\n\n\nint CreateSubset(vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, vector <double> &ARowSub, vector <double> &BSub, vector <double> &ShortTermsSub, int NumShortTerms, int NSub)\n{\n\tARowSub.resize(NSub*2+1);\n\tBSub.resize(NSub*2+1);\n\tShortTermsSub.resize(NSub*NSub*4);\n\n\tvector <int> UsedTerms, UsedTermsSub;\n\n\tUsedTerms.resize(NumShortTerms*2);\n\tfor (int i = 0; i < NumShortTerms*2; i++) {\n\t\tUsedTerms[i] = i+1;\n\t}\n\tUsedTermsSub.resize(NSub*2);\n\tfor (int i = 0; i < NSub; i++) {\n\t\tUsedTermsSub[i*2] = i+1;\n\t\tUsedTermsSub[i*2+1] = NumShortTerms+i+1;\n\t}\n\n\tARowSub[0] = ARow[0];\n\tBSub[0] = B[0];\n\tfor (int i = 0; i < NSub*2; i++) {\n\t\tfor (int j = 0; j < NSub*2; j++) {\n\t\t\t// The Fortran output counts from 1, hence the -1 on the RHS.\n\t\t\tShortTermsSub[i*NSub*2 + j] = ShortTerms[(UsedTermsSub[i]-1)*NumShortTerms*2 + (UsedTermsSub[j]-1)];\n\t\t}\n\t\t// Skips the 0 entry in ARow, so they line up.\n\t\tARowSub[i+1] = ARow[UsedTermsSub[i]];\n\t}\n\tfor (int i = 0; i < NSub*2; i++) {\n\t\tBSub[i+1] = B[UsedTermsSub[i]];\n\t}\n\n\treturn 0;\n}\n\n\n// Sort algorithm example code from http://www.cplusplus.com/reference/algorithm/sort/\nstruct myclass {\n\tbool operator() (int i,int j) { return (i<j);}\n} myobject;\n\nint FindOrderedToddTerm(string EnergyFilename, int TermToFind, int NumTerms)\n{\n\tifstream EnergyFile;\n\tvector <int> UsedTerms, UsedTermsSub;\n\tstring Line;\n\tint Term, Index;\n\tdouble Energy;\n\n\tif (TermToFind < 1) {\n\t\tcout << \"TermToFind must be 1 or greater.\" << endl;\n\t\treturn 1;\n\t}\n\n\tEnergyFile.open(EnergyFilename.c_str());\n\tgetline(EnergyFile, Line);\n\tgetline(EnergyFile, Line);  // Skip the first 4 lines\n\tgetline(EnergyFile, Line);  //  (unimportant for this)\n\tgetline(EnergyFile, Line);\n\n\tUsedTerms.resize(NumTerms);\n\tfor (int i = 0; i < NumTerms; i++) {\n\t\tEnergyFile >> Term >> Index >> Energy;\n\t\tUsedTerms[i] = Term;\n\t}\n\n\tsort(UsedTerms.begin(), UsedTerms.end(), myobject);\n\n\tEnergyFile.close();\n\n\t// Now search for the term (or find where it would go).\n\tfor (int i = 0; i < NumTerms; i++) {\n\t\tif (UsedTerms[i] == TermToFind)\n\t\t\treturn i+1;\n\t\tif (UsedTerms[i] > TermToFind) {\n\t\t\tif (i == 0)\n\t\t\t\treturn 1;  // Don't want to return 0.\n\t\t\treturn i;\n\t\t}\n\t}\n\n\treturn NumTerms+1;  // Term not found (larger than last used term).\n}\n\n\n// We could just open the energy file in the main program instead of reopening it many times, but this is just easier.\nint TestToddFile(string EnergyFilename, int NumShortTerms)\n{\n\tifstream EnergyFile;\n\tstring Line;\n\tint Term, Index;\n\tdouble Energy;\n\n\tif (NumShortTerms < 1) {\n\t\tcout << \"NumShortTerms must be 1 or greater.\" << endl;\n\t\treturn 1;\n\t}\n\n\tEnergyFile.open(EnergyFilename.c_str());\n\tif (EnergyFile.fail())\n\t\treturn 0;\n\tgetline(EnergyFile, Line);\n\tgetline(EnergyFile, Line);  // Skip the first 4 lines\n\tgetline(EnergyFile, Line);  //  (unimportant for this)\n\tgetline(EnergyFile, Line);\n\n\tfor (int i = 0; i < NumShortTerms; i++) {\n\t\tEnergyFile >> Term >> Index >> Energy;\n\t\tif (EnergyFile.fail())  // End of terms to use\n\t\t\treturn i;\n\t}\n\n\tEnergyFile.close();\n\n\treturn NumShortTerms;\n}\n\n\n// We could just open the energy file in the main program instead of reopening it many times, but this is just easier.\nint LoadToddTerms(int ShortLValue, vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, vector <double> &ARowSub, vector <double> &BSub, \n\t\t\t\t\tvector <double> &ShortTermsSub, int NumShortTotal, int NSub, string EnergyFilename, bool Resorted, bool Paired, int ResortedSize)\n{\n\tifstream EnergyFile;\n\tvector <int> UsedTerms, UsedTermsSub;\n\tstring Line;\n\tint Term, Index, Size;\n\tdouble Energy;\n\n\tif (NSub < 0) {\n\t\tcout << \"NSub must be 0 or greater.\" << endl;\n\t\treturn 1;\n\t}\n\n\tEnergyFile.open(EnergyFilename.c_str());\n\tif (EnergyFile.fail())\n\t\treturn 0;\n\tgetline(EnergyFile, Line);\n\tgetline(EnergyFile, Line);  // Skip the first 4 lines\n\tgetline(EnergyFile, Line);  //  (unimportant for this)\n\tgetline(EnergyFile, Line);\n\n\tif (Resorted == false)\n\t\tSize = NSub;\n\telse\n\t\tSize = ResortedSize;\n\n\tUsedTerms.resize(Size);\n\tfor (int i = 0; i < Size; i++) {\n\t\tEnergyFile >> Term >> Index >> Energy;\n\t\tif (EnergyFile.fail())  // End of terms to use\n\t\t\treturn 0;\n\t\tUsedTerms[i] = Term;\n\t}\n\n\tif (Paired == true) {\n\t\tUsedTermsSub.resize(NSub*2);\n\t\n\t\tif (Resorted) {\n\t\t\tcout << \"Reordering terms\" << endl;\n\t\t\tsort(UsedTerms.begin(), UsedTerms.end(), myobject);\n\t\t}\n\n\t\tfor (int i = 0; i < NSub; i++) {\n\t\t\tUsedTermsSub[i*2] = UsedTerms[i];\n\t\t\tUsedTermsSub[i*2+1] = NumShortTotal/2+UsedTerms[i];\n\t\t}\n\n\t\tEnergyFile.close();\n\n\t\tARowSub.resize(NSub*2+1);\n\t\tBSub.resize(NSub*2+1);\n\t\tShortTermsSub.resize(NSub*NSub*4);\n\n\t\tARowSub[0] = ARow[0];\n\t\tBSub[0] = B[0];\n\t\tfor (int i = 0; i < NSub*2; i++) {\n\t\t\tfor (int j = 0; j < NSub*2; j++) {\n\t\t\t\t// The Fortran output counts from 1, hence the -1 on the RHS.\n\t\t\t\tShortTermsSub[i*NSub*2 + j] = ShortTerms[(UsedTermsSub[i]-1)*NumShortTotal + (UsedTermsSub[j]-1)];\n\t\t\t}\n\t\t\t// Skips the 0 entry in ARow, so they line up.\n\t\t\tARowSub[i+1] = ARow[UsedTermsSub[i]];\n\t\t}\n\t\tfor (int i = 0; i < NSub*2; i++) {\n\t\t\tBSub[i+1] = B[UsedTermsSub[i]];\n\t\t}\n\t}\n\telse {\n\t\tUsedTermsSub.resize(NSub);\n\t\n\t\tif (Resorted) {\n\t\t\tcout << \"Reordering terms\" << endl;\n\t\t\tsort(UsedTerms.begin(), UsedTerms.end(), myobject);\n\t\t}\n\n\t\tfor (int i = 0; i < NSub; i++) {\n\t\t\tUsedTermsSub[i] = UsedTerms[i];\n\t\t}\n\n\t\tEnergyFile.close();\n\n\t\tARowSub.resize(NSub+1);\n\t\tBSub.resize(NSub+1);\n\t\tShortTermsSub.resize(NSub*NSub);\n\n\t\tARowSub[0] = ARow[0];\n\t\tBSub[0] = B[0];\n\t\tfor (int i = 0; i < NSub; i++) {\n\t\t\tfor (int j = 0; j < NSub; j++) {\n\t\t\t\t// The Fortran output counts from 1, hence the -1 on the RHS.\n\t\t\t\tShortTermsSub[i*NSub + j] = ShortTerms[(UsedTermsSub[i]-1)*NumShortTotal + (UsedTermsSub[j]-1)];\n\t\t\t}\n\t\t\t// Skips the 0 entry in ARow, so they line up.\n\t\t\tARowSub[i+1] = ARow[UsedTermsSub[i]];\n\t\t}\n\t\tfor (int i = 0; i < NSub; i++) {\n\t\t\tBSub[i+1] = B[UsedTermsSub[i]];\n\t\t}\n\t}\n\n\treturn NSub;\n}\n\n\n// Returns the number of terms for a given omega.  This could use the formula for combination with repetition,\n//  except then it would be unable to use a restricted set of terms if we needed.\nint CalcPowerTableSize(int Omega)\n{\n\tint NumTerms = 0;  // The total number of terms\n\tint om, ki, li, mi, ni, pi, qi;  // These are the exponents we are determining.\n\n\tfor (om = 0; om <= Omega; om++) {\n\t\tfor (ki = 0; ki <= Omega; ki++) {\n\t\t\tfor (li = 0; li <= Omega; li++) {\n\t\t\t\tfor (mi = 0; mi <= Omega; mi++) {\n\t\t\t\t\tfor (ni = 0; ni <= Omega; ni++) {\n\t\t\t\t\t\tfor (pi = 0; pi <= Omega; pi++) {\n\t\t\t\t\t\t\tfor (qi = 0; qi <= Omega; qi++) {\n\t\t\t\t\t\t\t\tif (ki + li + mi + ni + pi + qi == om)\n\t\t\t\t\t\t\t\t\tNumTerms = NumTerms + 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn NumTerms;\n}\n\n\n// Reads in the output from the scattering program (short-range - long-range and long-range - long-range terms)\nint ReadMatrixElem(ifstream &FileMatrixElem, int NumShortTerms, vector <double> &ARow, vector <double> &B, double &SLS, int &IsTriplet, int &Ordering, int &LValue, int &Formalism, int &Omega, int &NumSets, double &Alpha1, double &Beta1, double &Gamma1, double &Alpha2, double &Beta2, double &Gamma2, double &Kappa, double &Mu, string &LString, int &Shielding, string &Lambda, double &Epsilon12, double &Epsilon13, bool &ExtraExponential)\n{\n\tstring Line, Line1, Line2, Line3, Line4, OrderString;\n\tint NumTerms, Offset;\n\n\tgetline(FileMatrixElem, Line);\n\tgetline(FileMatrixElem, Line);\n\tgetline(FileMatrixElem, LString);\n\tgetline(FileMatrixElem, OrderString);\n\n\tFileMatrixElem >> Line >> Omega;\n\tFileMatrixElem >> Line1 >> Line2 >> Line3 >> NumTerms;\n\n\tcout << LString << endl;\n\tif (LString == \"S-Wave Singlet Ps-H\") {\n\t\tLValue = 0;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"S-Wave Triplet Ps-H\") {\n\t\tLValue = 0;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"S-Wave Singlet Ps-H - Laplacian Formalism - Exponential\") {\n\t\tLValue = 0;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"S-Wave Triplet Ps-H - Laplacian Formalism - Exponential\") {\n\t\tLValue = 0;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"P-Wave Singlet Ps-H: 1st formalism\" || LString == \"P-Wave Singlet Ps-H\") {  // Second is the older type\n\t\tLValue = 1;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"P-Wave Triplet Ps-H: 1st formalism\" || LString == \"P-Wave Triplet Ps-H\") {  // Second is the older type\n\t\tLValue = 1;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"P-Wave Singlet Ps-H: 2nd formalism\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"P-Wave Triplet Ps-H: 2nd formalism\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"P-Wave Singlet Ps-H: 1st formalism / 2 sets\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 0;\n\t\tNumSets = 2;\n\t}\n\telse if (LString == \"P-Wave Triplet Ps-H: 1st formalism / 2 sets\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 1;\n\t\tNumSets = 2;\n\t}\n\telse if (LString == \"P-Wave Singlet Ps-H: 2nd formalism / 2 sets\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 0;\n\t\tNumSets = 2;\n\t}\n\telse if (LString == \"P-Wave Triplet Ps-H: 2nd formalism / 2 sets\") {\n\t\tLValue = 1;\n\t\tIsTriplet = 1;\n\t\tNumSets = 2;\n\t}\n\telse if (LString == \"D-Wave Singlet Ps-H: 1st formalism\") {\n\t\tLValue = 2;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"D-Wave Triplet Ps-H: 1st formalism\") {\n\t\tLValue = 2;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"F-Wave Singlet Ps-H\") {\n\t\tLValue = 3;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"F-Wave Triplet Ps-H\") {\n\t\tLValue = 3;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"G-Wave Singlet Ps-H\") {\n\t\tLValue = 4;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"G-Wave Triplet Ps-H\") {\n\t\tLValue = 4;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"H-Wave Singlet Ps-H\") {\n\t\tLValue = 5;\n\t\tIsTriplet = 0;\n\t\tNumSets = 1;\n\t}\n\telse if (LString == \"H-Wave Triplet Ps-H\") {\n\t\tLValue = 5;\n\t\tIsTriplet = 1;\n\t\tNumSets = 1;\n\t}\n\telse {\n\t\tcout << \"Problem string in matrix element file has an unknown value...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\tif (ExtraExponential) {\n\t\tFileMatrixElem >> Line >> Alpha1 >> Line1 >> Beta1 >> Line2 >> Gamma1 >> Line3 >> Epsilon12 >> Line4 >> Epsilon13;\n\t\tcout << Alpha1 << \" \" << Beta1 << \" \" << Gamma1 << endl;\n\t}\n\telse {\n\t\tif (NumSets == 1) {\n\t\t\tFileMatrixElem >> Line >> Alpha1 >> Line1 >> Beta1 >> Line2 >> Gamma1;\n\t\t\tcout << Alpha1 << \" \" << Beta1 << \" \" << Gamma1 << endl;\n\t\t}\n\t\telse if (NumSets == 2) {\n\t\t\tFileMatrixElem >> Line >> Alpha2 >> Line1 >> Beta2 >> Line2 >> Gamma2;\n\t\t}\n\t}\n\n\t//getline(FileMatrixElem, Line);\n\t//getline(FileMatrixElem, Line);\n\tFileMatrixElem >> Line >> Mu;\n\tFileMatrixElem >> Line;\n\tShielding = -1;\n\tif (Line.find(\"Shielding\") != string::npos) {  // Skip this line - not yet to kappa line\n\t\tFileMatrixElem >> Line;\n\t\tFileMatrixElem >> Shielding;\n\t\t//getline(FileMatrixElem, Line);\n\t\tFileMatrixElem >> Line;\n\t}\n\tFileMatrixElem >> Kappa;\n\tgetline(FileMatrixElem, Line);\n\n\tif (OrderString == \"Using Denton's ordering\") {\n\t\tOrdering = 0;\n\t}\n\telse if (OrderString == \"Using Peter Van Reeth's ordering\") {\n\t\tOrdering = 1;\n\t}\n\telse {\n\t\tcout << \"Ordering string in matrix element file has an unknown value...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\t//getline(FileMatrixElem, Line);\n\tFileMatrixElem >> Line;\n\tif (Line.find(\"Lambda\") != string::npos) {  // Has the extra lambda line here\n\t\tgetline(FileMatrixElem, Lambda);\n\t}\n\tgetline(FileMatrixElem, Line);\n\t\n\tfor (int i = 0; i < 11; i++) {\n\t\tgetline(FileMatrixElem, Line);\n\t\tif (Line == \"A matrix row\")  // Some files have one less extra line\n\t\t\tbreak;\n\t}\n\n\t// Reads in first row (and column) of A\n\tfor (int i = 0; i < NumShortTerms+1; i++) {\n\t\tgetline(FileMatrixElem, Line);\n\t\tistringstream iss(Line);\n\t\tiss >> Offset >> ARow[i];\n\t}\n\n\t// Skips extra lines\n\tgetline(FileMatrixElem, Line);\n\tgetline(FileMatrixElem, Line);\n\n\t// Reads in B vector\n\tfor (int i = 0; i < NumShortTerms+1; i++) {\n\t\tgetline(FileMatrixElem, Line);\n\t\tistringstream iss(Line);\n\t\tiss >> Offset >> B[i];\n\t}\n\n\tgetline(FileMatrixElem, Line);\n\tgetline(FileMatrixElem, Line);\n\n\t// SLS is not in A or B, so read it in.\n\tFileMatrixElem >> SLS;\n\n\treturn 0;\n}\n\n\n// Reads in the short-range file header\nint ReadShortHeader(ifstream &FileShortRange, int &Omega, int &LValue, int &IsTriplet, int &Formalism, int &Ordering, int &NumShortTerms, int &NumSets, int &Integration, double &Alpha1, double &Beta1, double &Gamma1, double &Alpha2, double &Beta2, double &Gamma2, bool &ExtraExponential, double &Epsilon12, double &Epsilon13, vector <int> &ExpLen)\n{\n\tint MagicNum, Version, HeaderLen, DataFormat, NumShortTerms1, NumShortTerms2;\n\tint VarLen;\n\n\tFileShortRange.read((char*)&MagicNum, 4);\n\tFileShortRange.read((char*)&Version, 4);\n\tFileShortRange.read((char*)&HeaderLen, 4);\n\tFileShortRange.read((char*)&DataFormat, 4);\n\tFileShortRange.read((char*)&Omega, 4);\n\tFileShortRange.read((char*)&NumShortTerms1, 4);\n\tFileShortRange.read((char*)&NumShortTerms2, 4);\n\tFileShortRange.read((char*)&LValue, 4);\n\tFileShortRange.read((char*)&Formalism, 4);\n\tFileShortRange.read((char*)&IsTriplet, 4);\n\tFileShortRange.read((char*)&Ordering, 4);\n\tFileShortRange.read((char*)&Integration, 4);\n\tFileShortRange.read((char*)&NumSets, 4);\n\n\t//@TODO: More descriptive errors for each\n\n\tif (MagicNum != 0x31487350) {  // \"PsH1\" in hexadecimal (with reverse due to endianness)\n\t\tcout << \"This is not a valid Ps-H file (MagicNum)...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\tif (Version < 1 || Version > 9) {\n\t\tcout << \"This is not a valid Ps-H file (Version)...exiting.\" << endl;\n\t\tcout << Version << endl;\n\t\treturn -1;\n\t}\n\n\tif (HeaderLen != 80 && HeaderLen != 104) {\n\t\tcout << \"This is not a valid Ps-H file (HeaderLen)...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\tif (DataFormat != 8) {\n\t\tcout << \"This is not a valid Ps-H file (Dataformat)...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\tif ((Formalism != 1 && Formalism != 2) || (IsTriplet != 0 && IsTriplet != 1) || (Ordering != 0 && Ordering != 1)) {\n\t\tcout << \"This is not a valid Ps-H file (Formalism/IsTriplet/Ordering)...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\tif (NumSets != 1 && NumSets != 2) {\n\t\tcout << \"This is not a valid Ps-H file (NumSets)...exiting.\" << endl;\n\t\treturn -1;\n\t}\n\n\t/*if (NumShortTerms1 != NumShortTerms2) {\n\t\tcout << \"This is not a valid Ps-H file...exiting.\" << endl;  // Cannot handle two different values for this yet.\n\t\treturn -1;\n\t}*/\n\tNumShortTerms = NumShortTerms1;\n\n\t// @TODO: Set up to work properly with sectors\n\tFileShortRange.read((char*)&Alpha1, 8);\n\tFileShortRange.read((char*)&Beta1, 8);\n\tFileShortRange.read((char*)&Gamma1, 8);\n\tExtraExponential = false;\n\tif (Version == 9) {  // Extra exponentials\n\t\tdouble BlankDouble;\n\t\tint BlankInt;\n\t\tExtraExponential = true;\n\t\tFileShortRange.read((char*)&Epsilon12, 8);\n\t\tFileShortRange.read((char*)&Epsilon13, 8);\n\t\tFileShortRange.read((char*)&BlankDouble, 8);  // To be reserved for Epsilon23 at some point in the future\n\n\t\tExpLen.resize(2);  // No r23 exponential right now\n\t\tFileShortRange.read((char*)&ExpLen[0], 4);\n\t\tFileShortRange.read((char*)&ExpLen[1], 4);\n\t\tFileShortRange.read((char*)&BlankInt, 4);\n\t}\n\tif (NumSets == 2) {\n\t\t//read (FileShortRange) Alpha2, Beta2, Gamma2\n\t\tFileShortRange.read((char*)&Alpha2, 8);\n\t\tFileShortRange.read((char*)&Beta2, 8);\n\t\tFileShortRange.read((char*)&Gamma2, 8);\n\t}\n\n\tFileShortRange.read((char*)&VarLen, 4);\n\n\treturn 0;\n}\n\n\nvoid WriteHeader(ofstream &OutFile, string &LString, int &LValue, char *FileShortName, char *FileMatrixElemName, char *EnergyFileName, bool &Paired, bool &Resorted,\n\t\t\t\tint &ShortInt, int &NumTerms, double &Kappa, double &Mu, int &Shielding, string &Lambda, double &Alpha, double &Beta, double &Gamma, string &ProgName)\n{\n\tOutFile << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?> \" << endl;\n\tOutFile << \"<psh_data>\" << endl << \"<header>\" << endl;\n\tOutFile << \"\t<problem>\" << LString << \"</problem>\" << endl;\n\tOutFile << \"\t<lvalue>\" << LValue << \"</lvalue>\" << endl;\n\tOutFile << \"\t<shortfile>\" << FileShortName << \"</shortfile>\" << endl;\n\tOutFile << \"\t<longfile>\" << FileMatrixElemName << \"</longfile>\" << endl;\n\t//if (argc >= 6)  // Energy file present  //@TODO: Are we even accepting runs without now?\n\t\tOutFile << \"\t<energyfile>\" << EnergyFileName << \"</energyfile>\" << endl;\n\tif (Paired == true)\n\t\tOutFile << \"\t<paired>\" << \"true\" << \"</paired>\" << endl;\n\telse\n\t\tOutFile << \"\t<paired>\" << \"false\" << \"</paired>\" << endl;\n\tOutFile << \"\t<ordering>\" << \"Peter\" << \"</ordering>\" << endl;\n\tif (Resorted == true)\n\t\tOutFile << \"\t<reorder>\" << \"true\" << \"</reorder>\" << endl;\n\telse\n\t\tOutFile << \"\t<reorder>\" << \"false\" << \"</reorder>\" << endl;\n\tOutFile << \"\t<shortint>\" << ShortIntString(ShortInt) << \"</shortint>\" << endl;\n\tOutFile << \"\t<numterms>\" << NumTerms << \"</numterms>\" << endl;\n\tOutFile << \"\t<numsets>\" << 1 << \"</numsets>\" << endl;\n\tOutFile << \"\t<kappa>\" << Kappa << \"</kappa>\" << endl;\n\tOutFile << \"\t<mu>\" << Mu << \"</mu>\" << endl;\n\tif (Shielding == -1)  // No shielding value specified in file - assume default\n\t\tShielding = 2*LValue + 1;\n\tOutFile << \"\t<shielding>\" << Shielding << \"</shielding>\" << endl;\n\tif (trim(Lambda) != \"\" || Lambda.size() > 0)\n\t\tOutFile << \"\t<lambda>\" << trim(Lambda) << \"</lambda>\" << endl;\n\tOutFile << \"\t<nonlinear>\" << endl;\n\tOutFile << \"\t\t<alpha>\" << Alpha << \"</alpha>\" << endl;\n\tOutFile << \"\t\t<beta>\" << Beta << \"</beta>\" << endl;\n\tOutFile << \"\t\t<gamma>\" << Gamma << \"</gamma>\" << endl;\n\tOutFile << \"\t</nonlinear>\" << endl;\n\tOutFile << \"\t<program>\" << ProgName << \"</program>\" << endl;\n\tOutFile << \"\t<datetime>\" << GetDateTime() << \"</datetime>\" << endl;\n\n\tcout << \"n          Kohn              Inverse Kohn          Complex Kohn (S)       Complex Kohn (T)\" << endl;\n\tOutFile << \"</header>\" << endl << \"<dataheader>\" << endl << DataHeader << endl << \"</dataheader>\" << endl << \"<data>\" << endl;\n\tOutFile << setprecision(16);\n\tOutFile << scientific;\n\n\treturn;\n}\n\n\n// Generalized real Kohn\nvoid uGenKohn(dcmplx (&u)[2][2], double Tau)\n{\n\tu[0][0] = dcmplx(cos(Tau),0);\n\tu[0][1] = dcmplx(sin(Tau),0);\n\tu[1][0] = dcmplx(-sin(Tau),0);\n\tu[1][1] = dcmplx(cos(Tau),0);\n\treturn;\n}\n\n\n// Generalized T-matrix Kohn\nvoid uGenTKohn(dcmplx (&u)[2][2], double Tau)\n{\n\tu[0][0] = dcmplx(cos(Tau),0);\n\tu[0][1] = dcmplx(sin(Tau),0);\n\tu[1][0] = dcmplx(-sin(Tau),cos(Tau));\n\tu[1][1] = dcmplx(cos(Tau),sin(Tau));\n\treturn;\n}\n\n\n// Generalized S-matrix Kohn\nvoid uGenSKohn(dcmplx (&u)[2][2], double Tau)\n{\n\tu[0][0] = dcmplx(-sin(Tau),-cos(Tau));\n\tu[0][1] = dcmplx(cos(Tau),-sin(Tau));\n\tu[1][0] = dcmplx(-sin(Tau),cos(Tau));\n\tu[1][1] = dcmplx(cos(Tau),sin(Tau));\n\treturn;\n}\n\n\n// ARow and BVec are sent from the main program as the A and B from the Kohn method.  This function rearranges everything into\n//  the matrix equation (7) of their paper and solves.\ndouble CombinedKohn(dcmplx (&u)[2][2], int NumShortTerms, vector <double> &ARow, vector <double> &B, vector <double> &ShortTerms, double SLS, int LValue, int IsTriplet)\n{\n\tMKL_INT n, nrhs, lda, ldb, info;\n\t//double *A = new double[(NumShortTerms+1)*(NumShortTerms+1)];\n\tvector <dcmplx> A((NumShortTerms+1)*(NumShortTerms+1));\n\tvector <dcmplx> X(NumShortTerms+1);\n\tdouble CLC = ARow[0], CLS = B[0];\n\tdouble SLC = CLS + 1.0;  // Use (S,LC) = (C,LS) + 1\n\tdcmplx SLSt, SLCt, CLSt, CLCt;\n\n\tdcmplx detu = u[0][0]*u[1][1] - u[0][1]*u[1][0];  // Determinant\n\n\tSLSt = u[0][0]*u[0][0]*SLS + u[0][0]*u[0][1]*SLC + u[0][1]*u[0][0]*CLS + u[0][1]*u[0][1]*CLC;\n\tSLCt = u[0][0]*u[1][0]*SLS + u[0][0]*u[1][1]*SLC + u[0][1]*u[1][0]*CLS + u[0][1]*u[1][1]*CLC;\n\tCLSt = u[1][0]*u[0][0]*SLS + u[1][0]*u[0][1]*SLC + u[1][1]*u[0][0]*CLS + u[1][1]*u[0][1]*CLC;\n\tCLCt = u[1][0]*u[1][0]*SLS + u[1][0]*u[1][1]*SLC + u[1][1]*u[1][0]*CLS + u[1][1]*u[1][1]*CLC;\n\n\t// Copy short-range terms to bottom-right NumShortTerms x NumShortTerms submatrix of A.\n\tfor (int i = 0; i < NumShortTerms; i++) {\n\t\tfor (int j = 0; j < NumShortTerms; j++) {\n\t\t\tA[(i+1)*(NumShortTerms+1) + (j+1)] = ShortTerms[i*NumShortTerms + j];\n\t\t}\n\t}\n\n\t// Fill in the rest of A\n\tA[0] = CLCt;\n\tfor (int i = 1; i < NumShortTerms+1; i++) {\n\t\t//A[i] = dcmplx(ARow[i], B[i]);\n\t\tA[i] = u[1][0]*B[i] + u[1][1]*ARow[i];\n\t\tA[i*(NumShortTerms+1)] = A[i];\n\t}\n\n\t// Fill in B (or X)\n\tX[0] = -CLSt;\n\tfor (int i = 1; i < NumShortTerms+1; i++) {\n\t\tX[i] = - u[0][0]*B[i] - u[0][1]*ARow[i];\n\t}\n\n\t// LAPACK requires calls by reference, so we have to define all these variables.\n\tvector <int> ipiv(NumShortTerms+1);\n\tn = lda = ldb = NumShortTerms+1;\n\tnrhs = 1;\n\tzgesv(&n, &nrhs, (MKL_Complex16*)&A[0], &lda, &ipiv[0], (MKL_Complex16*)&X[0], &ldb, &info);\n\tif (info != 0) {\n\t\tcout << \"LAPACK Error: \" << info << endl;\n\t\treturn 0.0;\n\t}\n\n\t// Equation () of notes\n\tdcmplx PsiLS = X[0] * CLSt;\n\tfor (int i = 1; i < (NumShortTerms+1); i++) {\n\t\tPsiLS += X[i] * (u[0][0]*B[i] + u[0][1]*ARow[i]);\n\t}\n\tdcmplx L = -(PsiLS + SLSt) / detu;\n\t// Go from general L matrix element to K.\n\tdcmplx K = (u[0][1] + u[1][1]*L) / (u[0][0] + u[1][0]*L);\n\n\t//@TODO: Check K for imaginary part.\n\tdouble PhaseShift = atan(K.real());\n\tFixPhase(PhaseShift, LValue, IsTriplet);\n\treturn PhaseShift;\n}\n\n\nstring ShortIntString(int &Integration)\n{\n\tswitch (Integration)\n\t{\n\t\tcase 1:\n\t\t\treturn string(\"Direct summation\");\n\t\tcase 2:\n\t\t\treturn string(\"Asymptotic expansion\");\n\t\tcase 3:\n\t\t\treturn string(\"Recursion relations\");\n\t}\n\treturn string(\"Unknown integration\");\n}\n\n\n// Since we are finding atan(delta) instead of delta directly, some of the results\n//  are in the wrong range.\nvoid FixPhase(double &PhaseShift, int &LValue, int &IsTriplet)\n{\n\tdouble Pi = 4.0 * atan(1.0);\n\n\tif (LValue == 0 && IsTriplet == 0) {  // ^1S\n\t\tif (PhaseShift > 0.0) {\n\t\t\tPhaseShift = PhaseShift - Pi;\n\t\t}\n\t}\n\telse if (LValue == 0 && IsTriplet == 1) {  // ^3S\n\t\tif (PhaseShift > 0.0) {\n\t\t\tPhaseShift = PhaseShift - Pi;\n\t\t}\n\t}\n\telse if (LValue >= 3) {  // ^1F and higher\n\t\tif (PhaseShift > Pi) {\n\t\t\tPhaseShift = PhaseShift - Pi;\n\t\t}\n\t}\n}\n\n\n// Modified from http://www.dreamincode.net/code/snippet1102.htm\nstring GetDateTime(void)\n{\n\t//Find the current time\n\ttime_t curtime = time(0); \n\n\t//convert it to tm\n\ttm now=*localtime(&curtime); \n\n\t//BUFSIZ is standard macro that expands to a integer constant expression \n\t//that is greater then or equal to 256. It is the size of the stream buffer \n\t//used by setbuf()\n\tchar dest[BUFSIZ]={0};\n\n\t//Format string determines the conversion specification's behaviour\n\tconst char format[]=\"%x %X\"; \n\n\t//strftime - converts date and time to a string\n\tif (strftime(dest, sizeof(dest)-1, format, &now)>0) {\n\t\treturn string(dest);\n\t}\n\telse \n\t\tcerr << \"strftime failed. Errno code: \" << errno << endl;\n\treturn string(\"\");\n}\n", "meta": {"hexsha": "3898e7be19d52c0875e5f0796267f05fabc27894", "size": 38084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "General Code/Phase Shift/Phase Shift.cpp", "max_stars_repo_name": "DentonW/Ps-H-Scattering", "max_stars_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-02T03:50:06.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-02T03:50:06.000Z", "max_issues_repo_path": "General Code/Phase Shift/Phase Shift.cpp", "max_issues_repo_name": "DentonW/Ps-H-Scattering", "max_issues_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "General Code/Phase Shift/Phase Shift.cpp", "max_forks_repo_name": "DentonW/Ps-H-Scattering", "max_forks_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-28T22:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T22:09:05.000Z", "avg_line_length": 36.0302743614, "max_line_length": 439, "alphanum_fraction": 0.6388247033, "num_tokens": 13321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5569832944071421}}
{"text": "// #include \"NeoHookeanFEMConstraint.h\"\n// #include <Eigen/LU>\n// #include <math.h>\n// #include <iostream>\n// bool\n// NeoHookeanFEMConstraint::\n// ComputeDeformationGradient(const Eigen::VectorXd& x)\n// {\n\n// \tif(FEMConstraint::ComputeDeformationGradient(x))\n// \t{\n// \t\tmCacheFTF = (mCacheF.transpose())*mCacheF;\n// \t\tmCacheInvF = (mCacheF.inverse());\n// \t\tmCacheInvFT = mCacheInvF.transpose();\n// \t\t// if(fabs(mCacheF.determinant())<1E-6)\n// \t\t\t// std::cout<<mCacheF<<std::endl;\n// \t\treturn true;\n// \t}\n// \treturn false;\n// }\n// void\n// NeoHookeanFEMConstraint::\n// ComputedP(const Eigen::Matrix2d& dF,Eigen::Matrix2d& dP)\n// {\n// \tdouble I3 = mCacheFTF.determinant();\n\n// \tdP = \n// \t\tmMu*dF+\n// \t\t(mMu - mLambda*log(I3)*0.5)*mCacheInvFT*(dF.transpose())*mCacheInvFT+\n// \t\t(mLambda*((mCacheInvF*dF).trace()))*mCacheInvFT;\n// }\n// NeoHookeanFEMConstraint::\n// NeoHookeanFEMConstraint(const double& stiffness,const double& poisson_ratio,int i0,int i1,int i2,double vol,const Eigen::Matrix2d& invDm)\n// \t:FEMConstraint(stiffness,poisson_ratio,i0,i1,i2,vol,invDm),\n// \tmCacheFTF(Eigen::Matrix2d::Zero()),\n// \tmCacheInvFT(Eigen::Matrix2d::Zero())\n// {\n// }\n// double\n// NeoHookeanFEMConstraint::\n// EvalPotentialEnergy(const Eigen::VectorXd& x)\n// {\n// \tComputeDeformationGradient(x);\n\n// \tdouble I1 = mCacheFTF.trace();\n// \tdouble I3 = mCacheFTF.determinant();\n\n// \treturn mVol*(0.25*mMu*(I1-log(I3)-3) + 0.125*mLambda*(log(I3)*log(I3)));\n// }\n// void\n// NeoHookeanFEMConstraint::\n// EvalGradient(const Eigen::VectorXd& x, Eigen::VectorXd& gradient)\n// {\n// \tComputeDeformationGradient(x);\n\n// \tdouble I3 = mCacheFTF.determinant();\n// \t// std::cout<<I3<<std::endl;\n// \tEigen::Matrix2d P = (0.5*mMu)*(mCacheF-mCacheInvFT) + (0.5*mLambda*log(I3))*mCacheInvFT;\n\n// \tP = mVol*P*mInvDm;\n\n// \tgradient.block<2,1>(mi0*2,0) += -(P.block<2,1>(0,0) + P.block<2,1>(0,1));\n// \tgradient.block<2,1>(mi1*2,0) += P.block<2,1>(0,0);\n// \tgradient.block<2,1>(mi2*2,0) += P.block<2,1>(0,1);\n// }\n\n\n// void\n// NeoHookeanFEMConstraint::\n// EvalHessian(const Eigen::VectorXd& x, const Eigen::VectorXd& dx, Eigen::VectorXd& dg)\n// {\n// \tComputeDeformationGradient(x);\n// \tEigen::Matrix2d dDs,dF,dP;\n// \tEigen::Vector2d dx0(dx.block<2,1>(mi0*2,0));\n// \tdDs.block<2,1>(0,0) = dx.block<2,1>(mi1*2,0)-dx0;\n// \tdDs.block<2,1>(0,1) = dx.block<2,1>(mi2*2,0)-dx0;\n\t\n// \tdF = dDs*(mInvDm);\n// \tComputedP(dF,dP);\n\n// \tdP = mVol * dP * (mInvDm.transpose());\n\n// \tdg.block<2,1>(mi0*2,0) += -(dP.block<2,1>(0,0) + dP.block<2,1>(0,1));\n// \tdg.block<2,1>(mi1*2,0) += dP.block<2,1>(0,0);\n// \tdg.block<2,1>(mi2*2,0) += dP.block<2,1>(0,1);\n// }\n\n// void\n// NeoHookeanFEMConstraint::\n// EvaluateDVector(int index, const Eigen::VectorXd& x,Eigen::VectorXd& d)\n// {\n// \tstd::cout<<\"NeoHookeanFEMConstraint not supported.\"<<std::endl;\n// }\n// void\n// NeoHookeanFEMConstraint::\n// EvaluateJMatrix(int index, std::vector<Eigen::Triplet<double>>& J_triplets)\n// {\n// \tstd::cout<<\"NeoHookeanFEMConstraint not supported.\"<<std::endl;\n// }\n// void\n// NeoHookeanFEMConstraint::\n// EvaluateLMatrix(std::vector<Eigen::Triplet<double>>& L_triplets)\n// {\n// \tstd::cout<<\"NeoHookeanFEMConstraint not supported.\"<<std::endl;\n// }\n// int\n// NeoHookeanFEMConstraint::\n// GetNumHessianTriplets()\n// {\n// \treturn 36;\n// }\n", "meta": {"hexsha": "03f024d297d2562b56825df232756e347b7c35e2", "size": 3256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fem2D/Deprecate/NeoHookeanFEMConstraint.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/Deprecate/NeoHookeanFEMConstraint.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/Deprecate/NeoHookeanFEMConstraint.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": 29.0714285714, "max_line_length": 140, "alphanum_fraction": 0.6437346437, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5569700543830428}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include \"SdfObject.hpp\"\n#include \"../accelerate/Bound3.hpp\"\n\nclass SdfRoundCone : public SdfObject\n{\npublic:\n    SdfRoundCone(Eigen::Vector3f a, Eigen::Vector3f b, float ra, float rb) : SdfObject(a), a(a), b(b), ra(ra), rb(rb){};\n\n    float sdf(const Eigen::Vector3f &position) const override\n    {\n        constexpr auto sign = [](auto a)\n        { return a >= 0 ? 1 : -1; };\n\n        constexpr auto dot = [](Eigen::Vector3f a)\n        { return a.dot(a); };\n\n        // sampling independent computations (only depend on shape)\n        auto ba = b - a;\n        auto l2 = dot(ba);\n        auto rr = ra - rb;\n        auto a2 = l2 - rr * rr;\n        auto il2 = 1.0f / l2;\n\n        // sampling dependant computations\n        auto pa = position - a;\n        auto y = pa.dot(ba);\n        auto z = y - l2;\n        auto x2 = dot(pa * l2 - ba * y);\n        auto y2 = y * y * l2;\n        auto z2 = z * z * l2;\n\n        // single square root!\n        auto k = sign(rr) * rr * rr * x2;\n        if (sign(z) * a2 * z2 > k)\n            return sqrt(x2 + z2) * il2 - rb;\n        if (sign(y) * a2 * y2 < k)\n            return sqrt(x2 + y2) * il2 - ra;\n        return (sqrt(x2 * a2 * il2) + y * rr) * il2 - ra;\n    };\n\n    std::unique_ptr<Bound3> build_bound3() const override\n    {\n        auto aa = ra * Eigen::Vector3f::Ones();\n        auto bb = rb * Eigen::Vector3f::Ones();\n        auto min = (a - aa).cwiseMin(b - bb);\n        auto max = (a + aa).cwiseMax(b + bb);\n        return std::make_unique<Bound3>(min, max);\n    };\n\nprivate:\n    Eigen::Vector3f a;\n\n    Eigen::Vector3f b;\n\n    float ra;\n\n    float rb;\n};\n", "meta": {"hexsha": "8c7aeb3ce2c940756abf696a79428205234217e1", "size": 1637, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/render/object/SdfRoundCone.hpp", "max_stars_repo_name": "yzx9/NeuronSdfViewer", "max_stars_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T10:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T10:29:56.000Z", "max_issues_repo_path": "src/render/object/SdfRoundCone.hpp", "max_issues_repo_name": "yzx9/NeuronSdfViewer", "max_issues_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/render/object/SdfRoundCone.hpp", "max_forks_repo_name": "yzx9/NeuronSdfViewer", "max_forks_repo_head_hexsha": "454164dfccf80b806aac3cd7cca09e2cb8bd3c2a", "max_forks_repo_licenses": ["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.8360655738, "max_line_length": 120, "alphanum_fraction": 0.5155772755, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5568886502765538}}
{"text": "#include <iostream>\n#include <memory>\n#include <random>\n#include <string>\n\n#include <Eigen/Sparse>\n\n#include \"GeometricMultigridOperators.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 = 256;\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\tusing Vector = std::conditional<std::is_same<SolveReal, float>::value, Eigen::VectorXf, Eigen::VectorXd>::type;\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\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> 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\t// Print initial guess\n\tsolutionGrid.printAsOBJ(\"initialGuess\");\n\n\tUniformGrid<CellLabels> coarseCellLabels = buildCoarseCellLabels(domainCellLabels);\n\n\tassert(unitTestBoundaryCells<StoreReal>(domainCellLabels, &boundaryWeights) && unitTestBoundaryCells<StoreReal>(coarseCellLabels));\n\tassert(unitTestExteriorCells(domainCellLabels) && unitTestExteriorCells(coarseCellLabels));\n\tassert(unitTestCoarsening(coarseCellLabels, domainCellLabels));\n\n\tSolveReal coarseDx = 2 * dx;\n\n\t{\n\t\t//\n\t\t// Debug test for simple transfers\n\t\t//\n\n\t\t// Test a simple tansfer to the coarse grid and a transfer back\n\t\tUniformGrid<StoreReal> coarseInitialGuess(coarseCellLabels.size(), 0);\n\n\t\tdownsample<SolveReal>(coarseInitialGuess, solutionGrid, coarseCellLabels, domainCellLabels);\n\t\n\t\tcoarseInitialGuess.printAsOBJ(\"downsampledGrid\");\n\n\t\t// Transfer back\n\t\tUniformGrid<StoreReal> transferGrid(domainCellLabels.size(), 0);\n\t\tupsampleAndAdd<SolveReal>(transferGrid, coarseInitialGuess, domainCellLabels, coarseCellLabels);\n\n\t\ttransferGrid.printAsOBJ(\"upsampledGrid\");\n\t}\n\n\t//\n\t// Debug test by downsampling residual, solving for correction error and upsampling correction back\n\t//\n\t{\n\t\t//\n\t\t// Compute residual\n\t\t//\n\n\t\tUniformGrid<StoreReal> residualGrid(domainCellLabels.size(), 0);\n\t\tUniformGrid<StoreReal> rhsGrid(domainCellLabels.size(), 0);\n\n\t\tcomputePoissonResidual<SolveReal>(residualGrid, solutionGrid, rhsGrid, domainCellLabels, dx, &boundaryWeights);\n\n\t\tresidualGrid.printAsOBJ(\"residualGrid\");\n\n\t\t//\n\t\t// Restrict residual to coarse RHS\n\t\t//\n\n\t\tUniformGrid<StoreReal> coarseRHSGrid(coarseCellLabels.size(), 0);\n\t\tdownsample<SolveReal>(coarseRHSGrid, residualGrid, coarseCellLabels, domainCellLabels);\n\n\t\tcoarseRHSGrid.printAsOBJ(\"downsampledResidual\");\n\n\t\t//\n\t\t// Apply direct solver\n\t\t//\n\n\t\tUniformGrid<StoreReal> coarseSolution(coarseCellLabels.size(), 0);\n\n\t\t{\n\n\t\t\tUniformGrid<StoreReal> coarseResidualGrid(coarseCellLabels.size(), 0);\n\n\t\t\t//\n\t\t\t// Solver with direct solver\n\t\t\t//\n\n\t\t\t// Build indices\n\t\t\tint interiorCellCount = 0;\n\n\t\t\tUniformGrid<int> interiorCellIndices(coarseCellLabels.size(), -1);\n\n\t\t\tforEachVoxelRange(Vec2i(0), coarseCellLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\n\t\t\t\tif (coarseCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\tcoarseCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\tinteriorCellIndices(cell) = interiorCellCount++;\n\t\t\t});\n\t\t\t\n\t\t\tVector rhsVector = Vector::Zero(interiorCellCount);\n\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int> &range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = interiorCellIndices.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = interiorCellIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\trhsVector(index) = coarseRHSGrid(cell);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tassert(interiorCellIndices(cell) == -1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Build rows\n\t\t\tstd::vector<Eigen::Triplet<SolveReal>> sparseElements;\n\n\t\t\tSolveReal gridScalar = 1. / sqr(coarseDx);\n\t\t\tforEachVoxelRange(Vec2i(0), coarseCellLabels.size(), [&](const Vec2i &cell)\n\t\t\t{\n\t\t\t\tif (coarseCellLabels(cell) == CellLabels::INTERIOR_CELL)\n\t\t\t\t{\n\t\t\t\t\tint diagonal = 0;\n\t\t\t\t\tint index = interiorCellIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\t\t\t\t\t\t\tassert(coarseCellLabels(adjacentCell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\t\t\t\tcoarseCellLabels(adjacentCell) == CellLabels::BOUNDARY_CELL);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tint adjacentIndex = interiorCellIndices(adjacentCell);\n\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScalar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tsparseElements.emplace_back(index, index, 4. * gridScalar);\n\t\t\t\t}\n\t\t\t\telse if (coarseCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t{\n\t\t\t\t\tint diagonal = 0;\n\t\t\t\t\tint index = interiorCellIndices(cell);\n\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\tfor (int axis : {0, 1})\n\t\t\t\t\t\tfor (int direction : {0, 1})\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVec2i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\t\t\t\tif (coarseCellLabels(adjacentCell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\t\t\tcoarseCellLabels(adjacentCell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint adjacentIndex = interiorCellIndices(adjacentCell);\n\t\t\t\t\t\t\t\tassert(adjacentIndex >= 0);\n\n\t\t\t\t\t\t\t\tsparseElements.emplace_back(index, adjacentIndex, -gridScalar);\n\t\t\t\t\t\t\t\t++diagonal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tassert(interiorCellIndices(adjacentCell) == -1);\n\t\t\t\t\t\t\t\tif (coarseCellLabels(adjacentCell) == CellLabels::DIRICHLET_CELL)\n\t\t\t\t\t\t\t\t\t++diagonal;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tsparseElements.emplace_back(index, index, diagonal * gridScalar);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Solve system\n\t\t\tEigen::SparseMatrix<SolveReal> sparseMatrix(interiorCellCount, interiorCellCount);\n\t\t\tsparseMatrix.setFromTriplets(sparseElements.begin(), sparseElements.end());\n\t\t\tsparseMatrix.makeCompressed();\n\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<SolveReal>> solver;\n\t\t\tsolver.compute(sparseMatrix);\n\n\t\t\tif (solver.info() != Eigen::Success)\n\t\t\t{\n\t\t\t    std::cout << \"Solver failed to pre-compute system\" << std::endl;\n\t\t\t    return 0;\n\t\t\t}\n\n\t\t\tVector solutionVector = solver.solve(rhsVector);\n\t\t\tif (solver.info() != Eigen::Success)\n\t\t\t{\n\t\t\t    std::cout << \"Solver failed\" << std::endl;\n\t\t\t    return 0;\n\t\t\t}\n\n\t\t\ttbb::parallel_for(tbb::blocked_range<int>(0, coarseCellLabels.voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n\t\t\t{\n\t\t\t\tfor (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n\t\t\t\t{\n\t\t\t\t\tVec2i cell = interiorCellIndices.unflatten(cellIndex);\n\n\t\t\t\t\tif (coarseCellLabels(cell) == CellLabels::INTERIOR_CELL ||\n\t\t\t\t\t\tcoarseCellLabels(cell) == CellLabels::BOUNDARY_CELL)\n\t\t\t\t\t{\n\t\t\t\t\t\tint index = interiorCellIndices(cell);\n\t\t\t\t\t\tassert(index >= 0);\n\n\t\t\t\t\t\tcoarseSolution(cell) = solutionVector(index);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tassert(interiorCellIndices(cell) == -1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tcoarseSolution.printAsOBJ(\"coarseSolutionGrid\");\n\t\t}\n\n\t\t//\n\t\t// Prolongate solution\n\t\t//\n\n\t\tUniformGrid<StoreReal> correctionGrid(domainCellLabels.size(), 0);\n\n\t\tupsampleAndAdd<SolveReal>(correctionGrid, coarseSolution, domainCellLabels, coarseCellLabels);\n\n\t\tcorrectionGrid.printAsOBJ(\"prolongatedCorrectio\");\n\n\t\t//\n\t\t// Apply correction\n\t\t//\n\n\t\tupsampleAndAdd<SolveReal>(solutionGrid, coarseSolution, domainCellLabels, coarseCellLabels);\n\t\tsolutionGrid.printAsOBJ(\"solutionGrid\");\n\n\t\t//\n\t\t// Print out grids\n\t\t//\n\n\t\t// Print domain labels to make sure they are set up correctly\n\t\tint pixelHeight = 1080;\n\t\tint pixelWidth = pixelHeight;\n\t\trenderer = std::make_unique<Renderer>(\"MG Error Correction and Transfer Test\", Vec2i(pixelWidth, pixelHeight), Vec2f(0), 1, &argc, argv);\n\n\t\tScalarGrid<float> tempGrid(Transform(dx, Vec2f(0)), domainCellLabels.size());\n\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\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\ttempGrid(cell) = float(domainCellLabels(cell));\n\t\t\t}\n\t\t});\n\n\t\ttempGrid.drawVolumetric(*renderer, Vec3f(0), Vec3f(1), float(CellLabels::INTERIOR_CELL), float(CellLabels::BOUNDARY_CELL));\n\n\t\trenderer->run();\n\t}\n}", "meta": {"hexsha": "107d3fc5367513af7b6372bab6eeee51bf1812d4", "size": 9758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Projects/Tests/TestGeometricMGPoissonSolver/TestMGTransfers/TestMGTransfers.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/TestMGTransfers/TestMGTransfers.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/TestMGTransfers/TestMGTransfers.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": 29.4803625378, "max_line_length": 140, "alphanum_fraction": 0.6991186719, "num_tokens": 2642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.556854106628406}}
{"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 \"StrategyN2M3.hpp\"\n\n// calculate the distribution of fixation probability rho\n// against randomly selected N2M3 deterministic strategies\n\nstd::array<double,2> CalcPayoffs(const std::array<double,64>& stationary_state, double benefit) {\n  const double cost = 1.0;\n  std::array<double,2> ans = {0.0, 0.0};\n  for (size_t i = 0; i < 64; i++) {\n    StateN2M3 s(i);\n    double pa = 0.0, pb = 0.0;\n    if (s.a_1 == C) { pa -= cost; pb += benefit; }\n    if (s.b_1 == C) { pb -= cost; pa += benefit; }\n    ans[0] += stationary_state[i] * pa;\n    ans[1] += stationary_state[i] * pb;\n  }\n  return std::move(ans);\n}\n\ndouble FixationProb(size_t N, double sigma, double e, double benefit, const StrategyN2M3 &res, const StrategyN2M3 &mut, double s_yy) {\n  auto a_xx = mut.StationaryState(e);\n  auto a_xy = mut.StationaryState(e, &res);\n\n  double s_xx = CalcPayoffs(a_xx, benefit)[0];\n  auto _xy = CalcPayoffs(a_xy, benefit);\n  double s_xy = _xy[0];\n  double s_yx = _xy[1];\n\n  // \\frac{1}{\\rho} = \\sum_{i=0}^{N-1} \\exp\\left( \\sigma \\sum_{j=1}^{i} \\left[(N-j-1)s_{yy} + js_{yx} - (N-j)s_{xy} - (j-1)s_{xx} \\right] \\right) \\\\\n  //                = \\sum_{i=0}^{N-1} \\exp\\left( \\frac{\\sigma i}{2} \\left[(-i+2N-3)s_{yy} + (i+1)s_{yx} - (-i+2N-1)s_{xy} - (i-1)s_{xx} \\right] \\right)\n\n  double num_games = (N-1);\n  s_xx /= num_games;\n  s_yy /= num_games;\n  s_xy /= num_games;\n  s_yx /= num_games;\n  double rho_inv = 0.0;\n  for (int i=0; i < N; i++) {\n    double x = sigma * i * 0.5 * (\n        (2*N-3-i) * s_yy\n            + (i+1) * s_yx\n            - (2*N-1-i) * s_xy\n            - (i-1) * s_xx\n    );\n    rho_inv += std::exp(x);\n  }\n  return 1.0 / rho_inv;\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  std::uniform_int_distribution<uint64_t > dist(0, std::numeric_limits<uint64_t>::max() );\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        uint64_t r = dist(rnd);\n        StrategyN2M3 res(r);\n        auto a_yy = res.StationaryState(e);\n        double s_yy = CalcPayoffs(a_yy, benefit)[0];\n        for (size_t j = 0; j < n_mutants; j++) {\n          uint64_t r2 = dist(rnd);\n          StrategyN2M3 mut(r2);\n          double rho = FixationProb(N, sigma, e, benefit, res, mut, s_yy);\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_tl(seq);\n\n      StrategyN2M3 res = StrategyN2M3::CAPRI2();\n      auto a_yy = res.StationaryState(e);\n      double s_yy = CalcPayoffs(a_yy, 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        uint64_t r2 = dist(rnd_tl);\n        StrategyN2M3 mut(r2);\n        double rho = FixationProb(N, sigma, e, benefit, res, mut, s_yy);\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": "8613529472fcbee2b2012acd90314489fd173f9f", "size": 5363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main_evo_fixation_probs_n2.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_n2.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_n2.cpp", "max_forks_repo_name": "yohm/sim_CAPRI_nplayers", "max_forks_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1049382716, "max_line_length": 152, "alphanum_fraction": 0.5907141525, "num_tokens": 1831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.5568540886945966}}
{"text": "#include \"decomp.h\"\n\n// #include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n\nCx5 LowRankKernels(Cx5 const &mIn, float const thresh)\n{\n  Index const kSz = mIn.dimension(0) * mIn.dimension(1) * mIn.dimension(2) * mIn.dimension(3);\n  Index const nK = mIn.dimension(4);\n  Eigen::Map<Eigen::MatrixXcf const> m(mIn.data(), kSz, nK);\n  Log::Print(FMT_STRING(\"SVD Kernel Size {} Kernels {}\"), kSz, nK);\n  auto const svd = m.transpose().bdcSvd(Eigen::ComputeThinV);\n  Eigen::ArrayXf const vals = svd.singularValues();\n  Index const nRetain = (vals > (vals[0] * thresh)).cast<int>().sum();\n  Log::Print(FMT_STRING(\"Retaining {} kernels\"), nRetain);\n  Cx5 out(mIn.dimension(0), mIn.dimension(1), mIn.dimension(2), mIn.dimension(3), nRetain);\n  Eigen::Map<Eigen::MatrixXcf> lr(out.data(), kSz, nRetain);\n  lr = svd.matrixV().leftCols(nRetain).conjugate();\n  return out;\n}\n\nvoid PCA(Cx2 const &dataIn, Cx2 &vecIn, R1 &valIn)\n{\n  Eigen::Map<Eigen::MatrixXcf const> data(dataIn.data(), dataIn.dimension(0), dataIn.dimension(1));\n  Eigen::Map<Eigen::MatrixXcf> vecs(vecIn.data(), vecIn.dimension(0), vecIn.dimension(1));\n  Eigen::Map<Eigen::VectorXf> vals(valIn.data(), valIn.dimension(0));\n  assert(vecs.rows() == data.rows());\n  assert(vecs.cols() == data.rows());\n  assert(vals.rows() == data.rows());\n  auto const svd = data.transpose().bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::MatrixXcf const V = svd.matrixV();\n  vecs = V;\n  vals = svd.singularValues().array().sqrt();\n}", "meta": {"hexsha": "c03285995008ede44e9d6b349e746a539a4a8f51", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algo/decomp.cpp", "max_stars_repo_name": "pfuchs/riesling", "max_stars_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algo/decomp.cpp", "max_issues_repo_name": "pfuchs/riesling", "max_issues_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algo/decomp.cpp", "max_forks_repo_name": "pfuchs/riesling", "max_forks_repo_head_hexsha": "2e0f12f5cd1943cb6e96eca40f4e68ef88e12130", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4411764706, "max_line_length": 99, "alphanum_fraction": 0.6804333108, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5568140993285997}}
{"text": "#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Dense>\n\nusing Evec = Eigen::VectorXd;\nusing Emat = Eigen::MatrixXd;\nusing EVec3 = Eigen::Vector3d;\n\n// Assume A=(m,n), m>n\n// U = (m,n), S = (n,n), VT = (n,n)\nvoid testSVD(const Emat &U, const Evec &Sdiag, const Emat &VT, const Emat &A, const Evec &x, const Evec &b) {\n    Emat S(U.cols(), VT.rows());\n    S = Sdiag.asDiagonal();\n\n    // step 1, test if USVT==A\n    Emat Arecon = U * (S * VT);\n    Emat Aerror = Arecon - A;\n    printf(\"Aerror max min %g, %g\\n\", Aerror.maxCoeff(), Aerror.minCoeff());\n\n    const double eps = std::numeric_limits<double>::epsilon();\n    // step 2, test backward error\n    Evec Sdiaginv = Sdiag;\n    for (int i = 0; i < Sdiaginv.size(); i++) {\n        Sdiaginv[i] = Sdiaginv[i] < Sdiag[0] * eps ? 0 : 1.0 / Sdiaginv[i];\n    }\n\n    Emat V = VT.transpose();\n    for (int i = 0; i < Sdiaginv.size(); i++) {\n        V.col(i) *= Sdiaginv[i];\n    }\n\n    Evec x2 = V * (U.transpose() * b);\n    Evec b2 = A * x2;\n    Evec xerror = x2 - x;\n    Evec berror = b2 - b;\n    printf(\"xerror max min %g, %g\\n\", xerror.maxCoeff(), xerror.minCoeff());\n    printf(\"berror max min %g, %g\\n\", berror.maxCoeff(), berror.minCoeff());\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\ninline double pot(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    return rnorm < 1e-12 ? 0 : 1 / rnorm;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = 2 * 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    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    // Aup for solving MEquiv\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointMCheck.size() / 3;\n    Eigen::MatrixXd Aup(checkN, equivN);\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\n    Evec x(Aup.cols());\n    x.setRandom();\n    Evec b = Aup * x;\n\n    // jacobi svd\n    using std::cout;\n    using std::endl;\n\n    {\n        cout << \"JacobiSVD\" << endl;\n        Eigen::JacobiSVD<Emat> svd(Aup, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Emat U = svd.matrixU();\n        Emat VT = svd.matrixV().transpose();\n        Evec Svec = svd.singularValues();\n        testSVD(U, Svec, VT, Aup, x, b);\n    }\n    {\n        cout << \"BDCSVD\" << endl;\n        Eigen::BDCSVD<Emat> svd(Aup, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Emat U = svd.matrixU();\n        Emat VT = svd.matrixV().transpose();\n        Evec Svec = svd.singularValues();\n        testSVD(U, Svec, VT, Aup, x, b);\n    }\n    {\n        cout << \"HouseholderQR\" << endl;\n        Evec x2 = Aup.colPivHouseholderQr().solve(b);\n        Evec b2 = Aup * x2;\n        Evec xerror = x2 - x;\n        Evec berror = b2 - b;\n        printf(\"xerror max min %g, %g\\n\", xerror.maxCoeff(), xerror.minCoeff());\n        printf(\"berror max min %g, %g\\n\", berror.maxCoeff(), berror.minCoeff());\n    }\n\n    return 0;\n}", "meta": {"hexsha": "b95d41bce555da4075e1c84340af8b0cdc1cc421", "size": 5727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/svd_test.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/svd_test.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/svd_test.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": 35.1349693252, "max_line_length": 109, "alphanum_fraction": 0.521215296, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5567988097750391}}
{"text": "#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n#include <CGAL/point_generators_2.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/AlphaShapeGraphicsItem.h>\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n\n// the two base classes\n#include \"ui_Alpha_shapes_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\n\ntypedef CGAL::Alpha_shape_vertex_base_2<K> Vb;\ntypedef CGAL::Alpha_shape_face_base_2<K>  Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Delaunay;\n\ntypedef CGAL::Alpha_shape_2<Delaunay> Alpha_shape_2;\n\ntypedef Alpha_shape_2::Alpha_iterator Alpha_iterator;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Alpha_shapes_2\n{\n  Q_OBJECT\n\nprivate:\n  double alpha;\n  std::vector<Point_2> points;\n  Alpha_shape_2 as;\n  QGraphicsScene scene;\n\n  CGAL::Qt::AlphaShapeGraphicsItem<Alpha_shape_2> * agi;\n  CGAL::Qt::GraphicsViewPolylineInput<K> * pi;\n\npublic:\n  MainWindow();\n\npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void alphaChanged(int i);\n\n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionLoadPoints_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n  void open(QString fileName);\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  // Add a GraphicItem for the alpha shape\n  agi = new CGAL::Qt::AlphaShapeGraphicsItem<Alpha_shape_2>(&as);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   agi, SLOT(modelChanged()));\n\n  agi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  agi->setEdgesPen(QPen(Qt::lightGray, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  agi->setRegularEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  agi->setSingularEdgesPen(QPen(Qt::cyan, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  agi->setRegularFacesBrush(QBrush(Qt::cyan));\n  scene.addItem(agi);\n\n  //\n  // Manual handling of actions\n  //\n\n\n  QObject::connect(this->alphaSlider, SIGNAL(valueChanged(int)),\n                   this, SLOT(alphaChanged(int)));\n\n  QObject::connect(this->alphaBox, SIGNAL(valueChanged(int)),\n                   this, SLOT(alphaChanged(int)));\n\n  QObject::connect(this->alphaSlider, SIGNAL(valueChanged(int)),\n                   this->alphaBox, SLOT(setValue(int)));\n\n  QObject::connect(this->alphaBox, SIGNAL(valueChanged(int)),\n                   this->alphaSlider, SLOT(setValue(int)));\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n  pi = new CGAL::Qt::GraphicsViewPolylineInput<K>(this, &scene, 1, false); // inputs a list with one point\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  scene.installEventFilter(pi);\n  //this->actionShowAlphaShape->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  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->transform().scale(1, -1);\n\n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/about_Alpha_shapes_2.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n          this, SLOT(open(QString)));\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  std::list<Point_2> input;\n  if(CGAL::assign(input, o)){\n    if(input.size() == 1) {\n      points.push_back(input.front());\n      as.make_alpha_shape(points.begin(), points.end());\n      as.set_alpha(alpha);\n    }\n    Q_EMIT( changed());\n  }\n}\n\nvoid MainWindow::alphaChanged(int i)\n{\n  if (as.number_of_alphas() > 0){\n    if(i < 100){\n      int n = static_cast<int>((i * as.number_of_alphas())/ 100);\n      if(n == 0) n++;\n      alpha = as.get_nth_alpha(n);\n      as.set_alpha(alpha);\n    } else {\n      Alpha_iterator alpha_end_it = as.alpha_end();\n      alpha = (*(--alpha_end_it))+1;\n      as.set_alpha(alpha);\n    }\n  } else {\n    alpha = 0;\n    as.set_alpha(0);\n  }\n  Q_EMIT( changed());\n}\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\n\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  as.clear();\n  points.clear();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionInsertRandomPoints_triggered()\n{\n  QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n  CGAL::Qt::Converter<K> convert;\n  Iso_rectangle_2 isor = convert(rect);\n  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());\n  bool ok = false;\n\n  const int number_of_points =\n    QInputDialog::getInt(this,\n                             tr(\"Number of random points\"),\n                             tr(\"Enter number of random points\"),\n                             100,\n                             0,\n                             (std::numeric_limits<int>::max)(),\n                             1,\n                             &ok);\n\n  if(!ok) {\n    return;\n  }\n\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  points.reserve(points.size() + number_of_points);\n  for(int i = 0; i < number_of_points; ++i){\n    points.push_back(*pg++);\n  }\n  as.make_alpha_shape(points.begin(), points.end());\n  as.set_alpha(alpha);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.wktk *.WKT);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  std::cerr << \"open \" << std::endl;\n  std::cerr << qPrintable(fileName) << std::endl;\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n  if(fileName.endsWith(\".wkt\",Qt::CaseInsensitive))\n  {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n    CGAL::IO::read_multi_point_WKT(ifs, points);\n#endif\n  }\n  else\n  {\n    K::Point_2 p;\n    while(ifs >> p) {\n      points.push_back(p);\n    }\n  }\n  as.make_alpha_shape(points.begin(), points.end());\n  as.set_alpha(alpha);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  actionRecenter->trigger();\n  Q_EMIT( changed());\n\n}\n\n\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(agi->boundingRect());\n  this->graphicsView->fitInView(agi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\n#include \"Alpha_shapes_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(\"Alpha_shape_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": "33b37b40a91e68fb504f1f85785b17721c1388f7", "size": 8570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Alpha_shapes_2/Alpha_shapes_2.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "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": "GraphicsView/demo/Alpha_shapes_2/Alpha_shapes_2.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "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": "GraphicsView/demo/Alpha_shapes_2/Alpha_shapes_2.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2079510703, "max_line_length": 126, "alphanum_fraction": 0.6498249708, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5567988097750389}}
{"text": "\n\n#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <string>\n#include \"spida/shape/shapeT.h\"\n#include \"spida/helper/constants.h\"\n#include <boost/math/special_functions/airy.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace spida{\n\nShapeT::ShapeT(const GridT& grid,double A,double tp) :\n            Shape(grid),\n            m_t(grid.getT()),\n            m_A(A),m_tp(tp),\n            m_offset(0.0),\n            m_chirp(0.0),\n            m_slow_phase(0.0),\n            m_omega0(0.0) {}\n\nstd::vector<dcmplx> ShapeT::shapeCV() const\n{\n    std::vector<dcmplx> v;\n    shapeCV(v);\n    return v;\n}\n\nstd::vector<double> ShapeT::shapeRV() const\n{\n    std::vector<double> v;\n    shapeRV(v);\n    return v;\n}\n\nstd::vector<dcmplx> ShapeT::envelope() const\n{\n    std::vector<dcmplx> v;\n    envelope(v);\n    return v;\n}\n\nvoid ShapeT::shapeCV(std::vector<dcmplx>& v) const\n{\n    v.clear();\n    v.resize(m_t.size());\n    for(auto i = 0; i < m_t.size(); i++)\n        v[i] = shapeCV(m_t[i]);\n}\n\nvoid ShapeT::shapeRV(std::vector<double>& v) const\n{\n    v.clear();\n    v.resize(m_t.size());\n    for(auto i = 0; i < m_t.size(); i++)\n        v[i] = shapeRV(m_t[i]);\n}\n\nvoid ShapeT::envelope(std::vector<dcmplx>& v) const\n{\n    v.clear();\n    v.resize(m_t.size());\n    for(auto i = 0; i < m_t.size(); i++)\n        v[i] = computeEnvelope(m_t[i]);\n}\n\ndcmplx ShapeT::slowPhaseFactor(double t) const {\n    return exp(-ii*m_chirp*pow((t-m_offset),2)+ii*m_slow_phase); \n}\n\ndcmplx ShapeT::fastPhaseFactor(double t) const {\n    return exp(-ii*m_omega0*(t-m_offset));\n}\n\ndouble GaussT::compute(double t) const\n{\n    return exp(-pow((t-ShapeT::offset())/ShapeT::width(),2));\n}\n\ndouble SechT::compute(double t) const\n{\n    return (1.0/cosh((t-ShapeT::offset()\\\n                        )/ShapeT::width()));\n}\n\ndouble SuperGaussT::compute(double t) const {\n    return exp(-pow((t-ShapeT::offset())/ShapeT::width(),2*m_M));\n}\n\ndouble AiryT::compute(double t) const\n{\n\tdouble airy = boost::math::airy_ai<double>((t-ShapeT::offset())/ShapeT::width());\n    double apodization = exp(-pow(m_apod*(t-ShapeT::offset())/ShapeT::width(),2));\n    return airy*apodization;\n}\n\nBesselT::BesselT(const GridT& grid,double A,double tp,double apod) : \n    ShapeT(grid,A,tp), \n    m_apod(apod), \n    m_j1(boost::math::cyl_bessel_j_zero<double>(0,1)) {}\n\n\ndouble  BesselT::compute(double t) const\n{\n    double bessel = boost::math::cyl_bessel_j<double>(0,m_j1*fabs(t-ShapeT::offset())/ShapeT::width());\n    double apodization = exp(-pow(m_apod*(t-ShapeT::offset())/ShapeT::width(),2));\n    return bessel*apodization;\n}\n\n\n\n\n}\n\n\n\n", "meta": {"hexsha": "27909a07fd68b179f4ec50dc38cc30e4cbd81bd6", "size": 2601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shape/shapeT.cpp", "max_stars_repo_name": "whalenpt/spida", "max_stars_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T10:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T10:22:31.000Z", "max_issues_repo_path": "src/shape/shapeT.cpp", "max_issues_repo_name": "whalenpt/spida", "max_issues_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shape/shapeT.cpp", "max_forks_repo_name": "whalenpt/spida", "max_forks_repo_head_hexsha": "7c6bf79804dedf276f13271d361148e554132d24", "max_forks_repo_licenses": ["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.0423728814, "max_line_length": 103, "alphanum_fraction": 0.6163014225, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.5566416385454698}}
{"text": "#ifndef ROMPC_UTILS_HPP\n#define ROMPC_UTILS_HPP\n\n/**\n\t@file rompc_utils.hpp\n\tHeader file defining useful utilities for ROMPC controller.\n*/\n\n#include <memory>\n#include <iostream>\n#include <Eigen/Dense>\n#include <qpOASES.hpp>\n\nusing Vec3 = Eigen::Vector3d;\nusing Vec4 = Eigen::Vector4d;\nusing Mat3 = Eigen::Matrix3d;\nusing VecX = Eigen::VectorXd;\nusing MatX = Eigen::MatrixXd;\nusing RowMajMat = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, \n                      Eigen::RowMajor>;\nusing ArrPtr = std::unique_ptr<qpOASES::real_t[]>;\n\nnamespace ROMPC_UTILS {\n\nclass Target {\npublic:\n    Target();\n    virtual void initialize(Vec3 p, double psi) {};\n    virtual Vec3 get_pos(double t);\n    virtual Vec3 get_vel(double t);\n    virtual Vec4 get_att_quat(double t);\n    virtual Vec3 get_att_euler(double t);\n    virtual Vec3 get_att_aa(double t);\n    virtual Vec3 get_om(double t);\n    virtual ~Target() = default;\nprotected: \n    Vec3 _p_r_i_I; // position relative to inertial in inertial coord\n    Vec3 _v_r_I_R; // inertial velocity target frame coord.\n    Vec4 _q_I_to_R; // quat rotation from inertial NED to target FRD frame\n    Vec3 _om_R_I_R; // ang vel (p, q, r) of R w.r.t I frame, in R coordinates\n    Vec3 _euler; // euler angles (roll, pitch, yaw)\n    Vec3 _aa_I_to_R; // axis angle rotation from inertial NED to target FRD frame\n};\n\n/**\n    @class SGF\n   \n    @brief Steady glideslope flight target. Velocity (u,v,w) is constant,\n    body rates (p,q,r) are constant and zero, no side motion (v=0), roll angle\n    is zero (phi=0), and constant descent rate defined by the glideslope\n    angle gamma, which is negative when velocity is below local horizon.\n    When gamma = 0 this is equivalent to steady level flight.\n*/\nclass SGF : public Target {\npublic:\n    SGF(double S, double gamma, double th);\n\n    // Initialize position and yaw angle\n    void initialize(Vec3 p, double psi) override;\n\n    Vec3 get_pos(double t) override;\n\nprotected:\n    Vec3 _v_r_I_I; // velocity as seen from I in inertial coord.\n    double _S_xy; // speed in the inertial x-y plane \n    double _th; // constant pitch angle\n};\n\n/**\n    @class STF\n   \n    @brief Steady turning flight target. Velocity (u,v,w) is constant,\n    body rates (p,q,r) are constant (but not zero), constant yaw rate \n    \\dot{\\psi} (implicitly defined by constant speed S and turning radius\n    R), constant altitude. \n*/\nclass STF: public Target {\npublic:\n    STF(Vec3 v, Vec3 om, double phi,  double th, double R);\n    void compute_euler(double t);\n\n    // Initialize position and yaw angle\n    void initialize(Vec3 p, double psi) override;\n\n    Vec3 get_pos(double t) override;\n    Vec4 get_att_quat(double t) override;\n    Vec3 get_att_euler(double t) override;\n    Vec3 get_att_aa(double t) override;\n\nprotected:\n    double _phi; // roll angle constant\n    double _th; // pitch angle constant\n    double _psi; // yaw angle/heading\n    double _psi_dot; // yaw rate\n    double _R; // turning radius\n    Vec3 _p_c_i_I; // center of circle w.r.t inertial frame in I coord\n};\n\n/**\n    @class OCP\n   \n    @brief ROMPC Optimal control problem with only control\n    constraints.\n*/\nclass OCP {\npublic:\n    OCP(const std::string filepath, const double tmax);\n    void solve(const VecX x0, Vec4& uopt);\n    bool success();\n    double solve_time();\n    double get_dt();\n    int get_N();\n\nprivate:\n    void eigen_to_qpoases(const MatX& M, ArrPtr& m);\n    void set_x0(const VecX x0);\n\n    int _nV; // number of vars in OCP\n    int _nC; // number of constraints\n    int _n; // state dimension\n    MatX _G; // J = 1/2 U^T F U + x0^T G U\n    MatX _E2; // s.t. E1 U <= ub = e + E2 x0\n    VecX _e;\n    \n    ArrPtr _F;\n    ArrPtr _E1;\n    ArrPtr _ub;\n    ArrPtr _g; // g = x0^T * G\n    ArrPtr _U; // solution vector U = [u0, ..., u_N-1]\n\n    double _dt; // discretization time of system\n    int _N; // horizon \n\n    qpOASES::QProblem _ocp; // ocp object\n    double _tmax; // max amount of time to solve QP\n    bool _success;\n    double _solve_time;\n};\n\nvoid tangential_transf(const Vec3& aa, Mat3& T);\n\nvoid om_to_aadot(const Vec3& aa, const Vec3& om, Vec3& aadot);\n\nvoid aadot_to_om(const Vec3& aa, const Vec3& aadot, Vec3& om);\n\n}\n\n#endif // ROMPC_UTILS_HPP\n", "meta": {"hexsha": "2ee5a6737f88197428392eda6e01dcc695aadc36", "size": 4216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rompc/rompc_utils.hpp", "max_stars_repo_name": "jlorenze/asl_fixedwing", "max_stars_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T17:30:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:04:35.000Z", "max_issues_repo_path": "include/rompc/rompc_utils.hpp", "max_issues_repo_name": "jlorenze/asl_fixedwing", "max_issues_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-31T16:22:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T16:36:15.000Z", "max_forks_repo_path": "include/rompc/rompc_utils.hpp", "max_forks_repo_name": "jlorenze/asl_fixedwing", "max_forks_repo_head_hexsha": "9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2953020134, "max_line_length": 81, "alphanum_fraction": 0.6743358634, "num_tokens": 1217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.5566112839180318}}
{"text": "#include \"yavque/Utilities/pauli_operators.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace yavque\n{\nEigen::SparseMatrix<double> pauli_x()\n{\n\tstd::vector<Eigen::Triplet<double>> t{{1, 0, 1.0}, {0, 1, 1.0}};\n\tEigen::SparseMatrix<double> res(2, 2);\n\tres.setFromTriplets(t.begin(), t.end());\n\treturn res;\n}\nEigen::SparseMatrix<cx_double> pauli_y()\n{\n\tconstexpr cx_double I(0., 1.);\n\tstd::vector<Eigen::Triplet<cx_double>> t{{1, 0, I}, {0, 1, -I}};\n\tEigen::SparseMatrix<cx_double> res(2, 2);\n\tres.setFromTriplets(t.begin(), t.end());\n\treturn res;\n}\n\nEigen::SparseMatrix<double> pauli_z()\n{\n\tstd::vector<Eigen::Triplet<double>> t{{0, 0, 1.0}, {1, 1, -1.0}};\n\tEigen::SparseMatrix<double> res(2, 2);\n\tres.setFromTriplets(t.begin(), t.end());\n\treturn res;\n}\n\nEigen::SparseMatrix<double> pauli_xx()\n{\n\tEigen::SparseMatrix<double> res(4, 4);\n\tres.coeffRef(0, 3) = 1.0;\n\tres.coeffRef(1, 2) = 1.0;\n\tres.coeffRef(2, 1) = 1.0;\n\tres.coeffRef(3, 0) = 1.0;\n\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> pauli_yy()\n{\n\tEigen::SparseMatrix<double> res(4, 4);\n\tres.coeffRef(0, 3) = -1.0;\n\tres.coeffRef(1, 2) = 1.0;\n\tres.coeffRef(2, 1) = 1.0;\n\tres.coeffRef(3, 0) = -1.0;\n\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> pauli_xx_yy()\n{\n\tstd::vector<Eigen::Triplet<double>> t{{2, 1, 2.0}, {1, 2, 2.0}};\n\tEigen::SparseMatrix<double> res(4, 4);\n\tres.setFromTriplets(t.begin(), t.end());\n\treturn res;\n}\n\nEigen::SparseMatrix<double> pauli_zz()\n{\n\tEigen::SparseMatrix<double> res(4, 4);\n\tres.coeffRef(0, 0) = 1.0;\n\tres.coeffRef(1, 1) = -1.0;\n\tres.coeffRef(2, 2) = -1.0;\n\tres.coeffRef(3, 3) = 1.0;\n\n\tres.makeCompressed();\n\treturn res;\n}\n} // namespace yavque\n", "meta": {"hexsha": "dbfe3f2ce42babf9f0e6d8e47246d41c627d239a", "size": 1686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utilities/pauli_operators.cpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utilities/pauli_operators.cpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utilities/pauli_operators.cpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1842105263, "max_line_length": 66, "alphanum_fraction": 0.650059312, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5566112811075142}}
{"text": "//\n//  glasso.cpp\n//\n//  Python bindings of graphical lasso\n//\n//  Created by Kohei Miyaguchi on 2017/06/10.\n//  Copyright © 2017年 Kohei Miyaguchi. All rights reserved.\n//\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/functional.h>\n\nnamespace py = pybind11;\nusing namespace pybind11::literals;\n\nstruct GraphicalLassoResult {\n    Eigen::MatrixXd Theta, Sigma;\n    bool converged;\n    GraphicalLassoResult(long m) : Theta{m, m}, Sigma{Eigen::MatrixXd::Identity(m, m)}, converged{false} {}\n};\n\nusing GraphicalLasso = std::function<GraphicalLassoResult&(Eigen::MatrixXd const &, Eigen::MatrixXd const &)>;\n\ndouble linesearch(const Eigen::MatrixXd& S, const Eigen::MatrixXd& W, const Eigen::MatrixXd& G, const Eigen::MatrixXd& Lambda, int iter_max=INT_MAX, bool verbose=false, double eps=1e-3);\n\nGraphicalLasso graphicalLasso_stateful(long m, double tol, long iter_max, bool verbose, double eps) {\n    using namespace Eigen;\n    static const auto Zmm = MatrixXd::Zero(m, m);\n    static const auto Ones = MatrixXd::Ones(m, m);\n    MatrixXd W{m, m}, G{m, m};\n    GraphicalLassoResult result(m);\n\n    return [=](MatrixXd const &S, MatrixXd const &Lambda) mutable -> GraphicalLassoResult& {\n        MatrixXd &Theta = result.Theta, &Sigma = result.Sigma;\n        // Find feasible point of W assuming S and Sigma is SPD\n        W = Sigma - S;\n        MatrixXd shrinks = Lambda.array() / (W.cwiseAbs().array() + eps);\n        double shrink = (Lambda.array() >= W.array()).select(shrinks, Ones).minCoeff();\n        if (shrink < 1) {\n            if (verbose) {\n                printf(\"shrink rate: %f\\n\", shrink);\n            }\n            W *= shrink;\n        }\n        W.diagonal() = Lambda.diagonal();\n\n        // Perform projected subgradient method over (S, Lambda, W, Theta) (not Sigma!)\n        Theta = (S + W).inverse();\n        double t = 0.0, gap = 2 * tol;\n        for (int i = 0; i < iter_max; i++) {\n            G = Theta;\n            G.diagonal().setZero();\n            G = (\n                 ((W.array() >= Lambda.array()) * (G.array() > Zmm.array())) +\n                 ((W.array() <= -Lambda.array()) * (G.array() < Zmm.array()))\n                 ).select(Zmm, G);\n            t = linesearch(S, W, G, Lambda, verbose);\n            W = (W + t * G).cwiseMin(Lambda).cwiseMax(-Lambda);\n            Theta = (S + W).inverse();\n            S.cwiseProduct(Theta).sum();\n            gap = S.cwiseProduct(Theta).sum() + Theta.cwiseAbs().cwiseProduct(Lambda).sum() - m;\n            if (verbose) {\n                printf(\"(glasso) step: %d, gap: %f\\n\", i, gap);\n            }\n            if (std::abs(gap / m) < tol) {\n                result.converged = true;\n                goto CONVERGED;\n            }\n        }\n        result.converged = false;\n\n    CONVERGED: // finish\n        Theta = W.cwiseAbs().cwiseEqual(Lambda).select(Theta, Zmm);\n        Sigma = S + W;\n        return result;\n    };\n}\n\n\nGraphicalLassoResult graphicalLasso(\n        Eigen::MatrixXd const &S, Eigen::MatrixXd const &Lambda, Eigen::MatrixXd const &Sigma_init, Eigen::MatrixXd const &Theta_init,\n        double tol, long iter_max, bool verbose, double eps) {\n    using namespace Eigen;\n    long m = S.rows();\n    MatrixXd Zmm = MatrixXd::Zero(m, m);\n    MatrixXd Ones = MatrixXd::Ones(m, m);\n    MatrixXd W{m, m}, G{m, m};\n    GraphicalLassoResult result(m);\n    result.Theta = Theta_init;\n    result.Sigma = Sigma_init;\n    MatrixXd &Theta = result.Theta, &Sigma = result.Sigma;\n\n    // Find feasible point of W assuming S and Sigma is SPD\n    W = Sigma - S;\n    MatrixXd shrinks = Lambda.array() / (W.cwiseAbs().array() + eps);\n    double shrink = (Lambda.array() >= W.array()).select(shrinks, Ones).minCoeff();\n    if (shrink < 1) {\n        if (verbose) {\n            printf(\"shrink rate: %f\\n\", shrink);\n        }\n        W *= shrink;\n    }\n    W.diagonal() = Lambda.diagonal();\n\n    // Perform projected subgradient method over (S, Lambda, W, Theta) (not Sigma!)\n    Theta = (S + W).inverse();\n    double t = 0.0, gap = 2 * tol;\n    for (int i = 0; i < iter_max; i++) {\n        G = Theta;\n        G.diagonal().setZero();\n        G = (\n             ((W.array() >= Lambda.array()) * (G.array() > Zmm.array())) +\n             ((W.array() <= -Lambda.array()) * (G.array() < Zmm.array()))\n             ).select(Zmm, G);\n        t = linesearch(S, W, G, Lambda, verbose);\n        W = (W + t * G).cwiseMin(Lambda).cwiseMax(-Lambda);\n        Theta = (S + W).inverse();\n        S.cwiseProduct(Theta).sum();\n        gap = S.cwiseProduct(Theta).sum() + Theta.cwiseAbs().cwiseProduct(Lambda).sum() - m;\n        if (verbose) {\n            printf(\"(glasso) step: %d, gap: %f\\n\", i, gap);\n        }\n        if (std::abs(gap / m) < tol) {\n            result.converged = true;\n            goto CONVERGED;\n        }\n    }\n    result.converged = false;\n\nCONVERGED: // finish\n    Theta = W.cwiseAbs().cwiseEqual(Lambda).select(Theta, Zmm);\n    Sigma = S + W;\n    return result;\n}\n\nvoid test_glasso() {\n    using namespace Eigen;\n\n    MatrixXd S(3, 3), K(3, 3);\n\n    K << 3.0, 1.0, 0.0,\n    1.0, 2.0, 0.5,\n    0.0, 0.5, 1.0;\n    S = K.inverse();\n\n    MatrixXd Lambda = MatrixXd::Ones(3, 3) * 0.1;\n    MatrixXd I = MatrixXd::Identity(3, 3);\n\n    printf(\"start testing glasso:\\n\");\n    auto result = graphicalLasso(S, Lambda, I, I, 1e-10, 100, true, 1e-5);\n\n    MatrixXd Thetatrue(3, 3), Sigmatrue(3, 3);\n    Thetatrue <<   2.04478, 0.343284,        0,\n    0.343284,   1.3808, 0.262195,\n    0, 0.262195, 0.835366;\n    Sigmatrue <<   0.511765, -0.135294, 0.0424646,\n    -0.135294,  0.805882, -0.252941,\n    0.0424646, -0.252941,   1.27647;\n\n    std::cout << \"Thetaguess\\n\" << result.Theta << std::endl;\n    std::cout << \"Thetatrue\\n\" << Thetatrue << std::endl;\n    std::cout << \"Sigmaguess\\n\" << result.Sigma << std::endl;\n    std::cout << \"Sigmatrue\\n\" << Sigmatrue << std::endl;\n\n    double abserror = (result.Theta - Thetatrue).cwiseAbs().sum() + (result.Sigma - Sigmatrue).cwiseAbs().sum();\n    printf(\"absolute error: %f\\n\", abserror);\n    assert(0.001 > abserror);\n}\n\n\n// subroutine of glasso\ndouble linesearch(const Eigen::MatrixXd& S, const Eigen::MatrixXd& W, const Eigen::MatrixXd& G, const Eigen::MatrixXd& Lambda, int iter_max, bool verbose, double eps) {\n    using namespace Eigen;\n    double f0 = log((S + W).determinant());\n    MatrixXd SWG = (S + W).inverse() * G;\n\n    double nom = SWG.diagonal().sum();\n    double denom = (SWG.array() * SWG.transpose().array()).sum();\n    if (verbose) {\n        printf(\"(linesearch) step:-, nom:%f denom:%f, f0:%f\\n\", nom, denom, f0);\n    }\n    if (std::abs(denom) <= 0.0) return 0.0;\n    double t = nom / denom;\n    if (t <= 0) return 0.0;\n\n    for (int i = 0; 0.0 < t && i < iter_max; i++) {\n        double f = log((S + (W + t * G).cwiseMin(Lambda).cwiseMax(-Lambda)).determinant());\n        if (verbose) {\n            printf(\"(linesearch) step:%d, t:%f f:%f, f0:%f\\n\", i, t, f, f0);\n        }\n        if (f >= f0) break;\n        t *= 0.5;\n    }\n    return t;\n}\n\n\nPYBIND11_PLUGIN(glassobind) {\n    py::module m(\"glassobind\", \"graphical lasso plugin\");\n    py::class_<GraphicalLassoResult>(m, \"GraphicalLassoResult\")\n        .def(py::init<long>())\n        .def_readonly(\"theta\", &GraphicalLassoResult::Theta)\n        .def_readonly(\"sigma\", &GraphicalLassoResult::Sigma)\n        .def_readonly(\"converged\", &GraphicalLassoResult::converged);\n    m.def(\"glasso\", &graphicalLasso, \"performs graphical lasso\",\n          \"emp_cov\"_a, \"lambda\"_a, \"sigma_init\"_a, \"theta_init\"_a, \"tol\"_a, \"iter_max\"_a, \"verbose\"_a, \"eps\"_a);\n    m.def(\"test_glasso\", &test_glasso, \"test function\");\n    return m.ptr();\n}\n", "meta": {"hexsha": "e1911b64ea2c53119ab6e977969ee397535829ad", "size": 7749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "glasso.cpp", "max_stars_repo_name": "koheimiya/pyglassobind", "max_stars_repo_head_hexsha": "a978bcf1e228bcf9b271278ea9cfdd6df041480c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "glasso.cpp", "max_issues_repo_name": "koheimiya/pyglassobind", "max_issues_repo_head_hexsha": "a978bcf1e228bcf9b271278ea9cfdd6df041480c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "glasso.cpp", "max_forks_repo_name": "koheimiya/pyglassobind", "max_forks_repo_head_hexsha": "a978bcf1e228bcf9b271278ea9cfdd6df041480c", "max_forks_repo_licenses": ["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.875, "max_line_length": 186, "alphanum_fraction": 0.5738805007, "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5566015964254212}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file mcransac.hpp\n///\n/// \\author Keenan Burnett\n/// \\brief Rigid and motion-compensated RANSAC implementations along with some auxilliary\n///     SE(3) math functions.\n//////////////////////////////////////////////////////////////////////////////////////////////\n#pragma once\n#include <math.h>\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <chrono>\n#include <boost/python.hpp>\n#include <boost/python/numpy.hpp>\n#include <steam/steam.hpp>\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\n/*!\n   \\brief Enforce orthogonality conditions on the given rotation matrix such that det(R) == 1 and R.tranpose() * R = I\n   \\param R The input rotation matrix either 2x2 or 3x3, will be overwritten with a slightly modified matrix to\n   satisfy orthogonality conditions.\n*/\nvoid enforce_orthogonality(Eigen::MatrixXd &R);\n\n/*!\n   \\brief Retrieve the rigid transformation that transforms points in p1 into points in p2.\n   The output transform type (float or double) and size SE(2) vs. SE(3) depends on the size of the input points p1, p2.\n   \\param p1 A dim x N vector of points in either 2D (dim = 2) or 3D (dim = 3)\n   \\param p2 A dim x N vector of points in either 2D (dim = 2) or 3D (dim = 3)\n   \\param Tf [out] This matrix will be overwritten as the output transform\n   \\pre p1 and p2 are the same size. p1 and p2 are the matched feature point locations between two point clouds\n   \\post orthogonality is enforced on the rotation matrix.\n*/\nvoid get_rigid_transform(Eigen::MatrixXd p1, Eigen::MatrixXd p2, Eigen::MatrixXd &Tf);\n\n/*!\n   \\brief Returns a random subset of indices, where 0 <= indices[i] <= max_index. indices are non-repeating.\n*/\nstd::vector<int> random_subset(int max_index, int subset_size);\n\n/*!\n   \\brief Returns the output of the carrot operator.\n   For 3 x 1 input, carrot(x) * y is equivalent to cross_product(x, y)\n   For 6 x 1 input, x = [rho, phi]^T. out = [carrot(phi), rho; 0 0 0 1]\n   \\param x Input vector which can be 3 x 1 or 6 x 1.\n   \\return If the input if 3 x 1, the output is 3 x 3, if the input is 6 x 1, the output is 4 x 4.\n*/\nEigen::MatrixXd carrot(Eigen::VectorXd x);\n\n/*!\n   \\brief Returns the output of the circledot operator. carrot(epsilon) * p == circledot(p) * epsilon,\n   where epsilon is 6x1 and p is 4 x 1 homogeneous.\n   p = [rhobar, eta]^T  circledot(p) = [eta * identity(3), -carrot(rhobar); 0 0 0 0 0 0]\n   \\param x Input is a 4 x 1 homogeneous 3D vector.\n   \\return returns the 4 x 6 output of circledot(x)\n*/\nEigen::MatrixXd circledot(Eigen::VectorXd x);\n\n/*!\n   \\brief This function converts from a lie vector to a 4 x 4 SE(3) transform.\n   // Lie Vector xi = [rho, phi]^T (6 x 1) --> SE(3) T = [C, R; 0 0 0 1] (4 x 4)\n   \\param x Input vector is 6 x 1\n   \\return Output is 4 x SE(3) transform\n*/\nEigen::Matrix4d se3ToSE3(Eigen::MatrixXd xi);\n\n/*!\n   \\brief This function converts from an SE(3) transform into a lie vector\n   // SE(3) T = [C, R; 0 0 0 1] (4 x 4) --> Lie Vector xi = [rho, phi]^T (6 x 1)\n   \\param T Input is a 4x4 SE(3) transform\n   \\return Output is 6x1 lie vector\n*/\nEigen::VectorXd SE3tose3(Eigen::MatrixXd T);\n\n/*!\n   \\brief Ensures that theta is within [0, 2 * pi)\n*/\ndouble wrapto2pi(double theta);\n\n//* Ransac\n/**\n* \\brief This class estimates a single rigid transform between two point clouds using RANSAC and singular value decomp\n*/\nclass Ransac {\npublic:\n    // p1, p2 need to be either (x, y) x N or (x, y, z) x N (must be in homogeneous coordinates)\n    Ransac(const np::ndarray& p1_, const np::ndarray& p2_) {\n        uint dim = p1_.shape(1);\n        uint N = p1_.shape(0);\n        assert(N == p2_.shape(0) && dim == p2_.shape(1) && dim >= 2);\n        if (dim > 3)\n            dim = 3;\n        p1 = Eigen::MatrixXd::Zero(dim, N);\n        p2 = Eigen::MatrixXd::Zero(dim, N);\n        for (uint i = 0; i < dim; ++i) {\n            for (uint j = 0; j < N; ++j) {\n                p1(i, j) = double(p::extract<float>(p1_[j][i]));\n                p2(i, j) = double(p::extract<float>(p2_[j][i]));\n            }\n        }\n        T_best = Eigen::MatrixXd::Identity(dim + 1, dim + 1);\n    }\n    void setTolerance(double tolerance_) {tolerance = tolerance_;}\n    void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n    void setMaxIterations(int iterations_) {iterations = iterations_;}\n    void getTransform(Eigen::MatrixXd &Tf) {Tf = T_best;}\n\n    /*!\n       \\brief Computes the transform that best aligns the two pointclouds such at T * p1 = p2\n    */\n    double computeModel();\n\n    /*!\n       \\brief Retrieves the set of point pairs which are inliers given the current transform Tf.\n    */\n    void getInliers(Eigen::MatrixXd Tf, std::vector<int> &inliers);\n\nprivate:\n    Eigen::MatrixXd p1, p2;\n    double tolerance = 0.35;\n    double inlier_ratio = 0.9;\n    int iterations = 100;\n    Eigen::MatrixXd T_best;\n};\n\n//* MCRansac\n/**\n* \\brief This class estimates the linear velocity and angular velocity of the sensor in the body-frame.\n*\n* Assuming constant velocity, the motion vector can be used to estimate the transform between any two pairs of points\n* if the delta_t between those points issrand(t1_[i-1][0]); known.\n*\n* A single transform between the two pointclouds can also be retrieved.\n*\n* All operations are done in SE(3) even if the input is 2D. The output motion and transforms are in 3D.\n*/\nclass MCRansac {\npublic:\n    MCRansac(const np::ndarray& p1_, const np::ndarray& p2_, const np::ndarray& t1_, const np::ndarray& t2_) {\n        assert(p1_.shape(0) == p2_.shape(0) && p1_.shape(1) == p2_.shape(1) && p1_.shape(0) >= p1_.shape(1));\n        uint N = p1_.shape(0);\n        uint dim = p1_.shape(1);\n        if (dim > 3)\n            dim = 3;\n        p1bar = Eigen::MatrixXd::Zero(4, N);\n        p2bar = Eigen::MatrixXd::Zero(4, N);\n        p1bar.block(3, 0, 1, N) = Eigen::MatrixXd::Ones(1, N);\n        p2bar.block(3, 0, 1, N) = Eigen::MatrixXd::Ones(1, N);\n        for (uint i = 0; i < dim; ++i) {\n            for (uint j = 0; j < N; ++j) {\n                p1bar(i, j) = double(p::extract<float>(p1_[j][i]));\n                p2bar(i, j) = double(p::extract<float>(p2_[j][i]));\n            }\n        }\n        std::vector<int64_t> t1(N, 0);\n        std::vector<int64_t> t2(N, 0);\n        for (uint i = 0; i < N; ++i) {\n            t1[i] = int64_t(p::extract<int64_t>(t1_[i]));\n            t2[i] = int64_t(p::extract<int64_t>(t2_[i]));\n        }\n        R_pol << pow(0.25, 2), 0, 0, 0, 0, pow(0.0157, 2), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n        delta_ts = std::vector<double>(N, 0.0);\n        for (uint i = 0; i < N; ++i) {\n            int64_t delta_t = t2[i] - t1[i];\n            delta_ts[i] = double(delta_t) / 1000000.0;\n            if (delta_ts[i] > max_delta_t) {\n                max_delta_t = delta_ts[i];\n            }\n            if (delta_ts[i] < min_delta_t) {\n                min_delta_t = delta_ts[i];\n            }\n        }\n        double delta_diff = (max_delta_t - min_delta_t) / (num_transforms - 1);\n        for (int i = 0; i < num_transforms; ++i) {\n            delta_vec.push_back(min_delta_t + i * delta_diff);\n        }\n    }\n    void setTolerance(double tolerance_) {tolerance = tolerance_;}\n    void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n    void setMaxIterations(int iterations_) {iterations = iterations_;}\n    void setMaxGNIterations(int iterations_) {max_gn_iterations = iterations_;}\n    void setConvergenceThreshold(double eps) {epsilon_converge = eps;}\n    void correctForDoppler(bool doppler_) {doppler = doppler_;}\n    void getTransform(double delta_t, Eigen::MatrixXd &Tf);\n    void getMotion(Eigen::VectorXd &w) {w = w_best;}\n    void setDopplerParameter(double beta_) {beta = beta_;}\n\n    /*!\n       \\brief Computes the ego-motion vector that best aligns the two pointclouds\n    */\n    double computeModel();\n\n    /*!\n       \\brief Retrieves the set of point pairs which are inliers given the current motion estimate.\n    */\n    void getInliers(Eigen::VectorXd wbar, std::vector<int> &inliers);\n\nprivate:\n    Eigen::MatrixXd p1bar, p2bar;\n    std::vector<double> delta_ts;\n    double tolerance = 0.1225;\n    double inlier_ratio = 0.9;\n    int iterations = 100;\n    int max_gn_iterations = 10;\n    double epsilon_converge = 0.0001;\n    double error_converge = 0.01;\n    int dim = 2;\n    double beta = -0.049;  // beta = (f_t / (df / dt))\n    double r_observable_sq = 0.0625;\n    bool doppler = false;\n    int num_transforms = 21;\n    double max_delta_t = 0.0;\n    double min_delta_t = 0.5;\n    std::vector<double> delta_vec;\n    Eigen::VectorXd w_best = Eigen::VectorXd::Zero(6);\n    Eigen::Matrix4d R_pol = Eigen::Matrix4d::Identity();\n\n    /*!\n       \\brief Given two sets of point pairs (p1small, p2small), this function computes the motion of the sensor\n       (linear and angular velocity) in the body frame using nonlinear least squares.\n       \\pre It's very important that the delt_t_local is accurate. Note that each azimuth in the radar scan is time\n       stamped, this should be used to get the more accurate time differences.\n    */\n    void get_motion_parameters(std::vector<int> subset, Eigen::VectorXd &wbar);\n\n    /*!\n       \\brief Retrieve the number of inliers corresponding to body motion vector wbar. (6 x 1)\n    */\n    int getNumInliers(Eigen::VectorXd wbar);\n\n    /*!\n       \\brief Given a body motion vector wbar (6 x 1), adjust the position of point p to account\n       for the Doppler distortion which may be present in the data.\n    */\n    void dopplerCorrection(Eigen::VectorXd wbar, Eigen::VectorXd &p);\n};\n\n// Return the inverse of a 4x4 homogeneous transformation matrix\nEigen::Matrix4d get_inverse_tf(Eigen::Matrix4d T);\n", "meta": {"hexsha": "b82f410b264207f1e4f6ffedd9823dc36ff16b67", "size": 9804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/mcransac.hpp", "max_stars_repo_name": "MPieter/hero_radar_odometry", "max_stars_repo_head_hexsha": "107c1a07b22784fec54c22e5f8bb03251cc9f786", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2021-06-01T11:58:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:20:40.000Z", "max_issues_repo_path": "cpp/mcransac.hpp", "max_issues_repo_name": "MPieter/hero_radar_odometry", "max_issues_repo_head_hexsha": "107c1a07b22784fec54c22e5f8bb03251cc9f786", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-13T15:23:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-09T23:02:58.000Z", "max_forks_repo_path": "cpp/mcransac.hpp", "max_forks_repo_name": "MPieter/hero_radar_odometry", "max_forks_repo_head_hexsha": "107c1a07b22784fec54c22e5f8bb03251cc9f786", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T00:07:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T04:58:56.000Z", "avg_line_length": 40.0163265306, "max_line_length": 119, "alphanum_fraction": 0.6256629947, "num_tokens": 2899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5566015725808628}}
{"text": "// g2o - General Graph Optimization\r\n// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, H. Strasdat, W. Burgard\r\n// All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without\r\n// modification, are permitted provided that the following conditions are\r\n// met:\r\n//\r\n// * Redistributions of source code must retain the above copyright notice,\r\n//   this list of conditions and the following disclaimer.\r\n// * Redistributions in binary form must reproduce the above copyright\r\n//   notice, this list of conditions and the following disclaimer in the\r\n//   documentation and/or other materials provided with the distribution.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\r\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\r\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\r\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n// This example consists of a single static target which sits in one\r\n// place and does not move; in effect it has a \"GPS\" which measures\r\n// its position\r\n\r\n#include <Eigen/StdVector>\r\n#include <iostream>\r\n#include <stdint.h>\r\n \r\n#include <g2o/core/sparse_optimizer.h>\r\n#include <g2o/core/block_solver.h>\r\n#include <g2o/core/solver.h>\r\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\r\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\r\n#include <g2o/stuff/sampler.h>\r\n\r\n#include \"targetTypes3D.hpp\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\nusing namespace g2o;\r\n\r\nint main()\r\n{\r\n  // Set up the optimiser\r\n  SparseOptimizer optimizer;\r\n  optimizer.setVerbose(false);\r\n\r\n  // Create the block solver - the dimensions are specified because\r\n  // 3D observations marginalise to a 3D estimate\r\n  typedef BlockSolver<BlockSolverTraits<3, 3> > BlockSolver_3_3;\r\n  OptimizationAlgorithmGaussNewton* solver = new OptimizationAlgorithmGaussNewton(\r\n    g2o::make_unique<BlockSolver_3_3>(\r\n      g2o::make_unique<LinearSolverCholmod<BlockSolver_3_3::PoseMatrixType>>()));\r\n\r\n  optimizer.setAlgorithm(solver);\r\n\r\n  // Sample the actual location of the target\r\n  Vector3d truePoint(sampleUniform(-500, 500),\r\n                     sampleUniform(-500, 500),\r\n                     sampleUniform(-500, 500));\r\n\r\n  // Construct vertex which corresponds to the actual point of the target\r\n  VertexPosition3D* position = new VertexPosition3D();\r\n  position->setId(0);\r\n  optimizer.addVertex(position);\r\n\r\n  // Now generate some noise corrupted measurements; for simplicity\r\n  // these are uniformly distributed about the true target. These are\r\n  // modelled as a unary edge because they do not like to, say,\r\n  // another node in the map.\r\n  int numMeasurements = 10;\r\n  double noiseLimit = sqrt(12.);\r\n  double noiseSigma = noiseLimit*noiseLimit / 12.0;\r\n\r\n  for (int i = 0; i < numMeasurements; i++)\r\n    {\r\n      Vector3d measurement = truePoint +\r\n        Vector3d(sampleUniform(-0.5, 0.5) * noiseLimit,\r\n                 sampleUniform(-0.5, 0.5) * noiseLimit,\r\n                 sampleUniform(-0.5, 0.5) * noiseLimit);\r\n      GPSObservationPosition3DEdge* goe = new GPSObservationPosition3DEdge();\r\n      goe->setVertex(0, position);\r\n      goe->setMeasurement(measurement);\r\n      goe->setInformation(Matrix3d::Identity() / noiseSigma);\r\n      optimizer.addEdge(goe);\r\n    }\r\n\r\n  // Configure and set things going\r\n  optimizer.initializeOptimization();\r\n  optimizer.setVerbose(true);\r\n  optimizer.optimize(5);\r\n  \r\n  cout << \"truePoint=\\n\" << truePoint << endl;\r\n\r\n  cerr <<  \"computed estimate=\\n\" << dynamic_cast<VertexPosition3D*>(optimizer.vertices().find(0)->second)->estimate() << endl;\r\n\r\n  //position->setMarginalized(true);\r\n  \r\n  SparseBlockMatrix<MatrixXd> spinv;\r\n\r\n  optimizer.computeMarginals(spinv, position);\r\n\r\n\r\n\r\n  //optimizer.solver()->computeMarginals();\r\n\r\n  // covariance\r\n  //\r\n  cout << \"covariance\\n\" << spinv << endl;\r\n\r\n  cout << spinv.block(0,0) << endl;\r\n  \r\n}\r\n", "meta": {"hexsha": "23393a5731d322f13a950152ff23bbc56fd9ee83", "size": 4466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slambook2/3rdparty/g2o/g2o/examples/target/static_target.cpp", "max_stars_repo_name": "zhh2005757/slambook2_in_Docker", "max_stars_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-14T07:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T09:20:33.000Z", "max_issues_repo_path": "slambook2/3rdparty/g2o/g2o/examples/target/static_target.cpp", "max_issues_repo_name": "zhh2005757/slambook2_in_Docker", "max_issues_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slambook2/3rdparty/g2o/g2o/examples/target/static_target.cpp", "max_forks_repo_name": "zhh2005757/slambook2_in_Docker", "max_forks_repo_head_hexsha": "f0e71327d196cdad3b3c10d96eacdf95240d528b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-10-21T06:12:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T15:52:28.000Z", "avg_line_length": 37.2166666667, "max_line_length": 128, "alphanum_fraction": 0.7071204657, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.5564917446601975}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\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,\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//\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#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <rl/math/Constants.h>\n#include <rl/math/Quaternion.h>\n#include <rl/math/Rotation.h>\n#include <rl/math/Vector.h>\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc < 7)\n\t{\n\t\tstd::cout << \"Usage: rlEulerAnglesDemo AXIS0 AXIS1 AXIS2 DEG0 DEG1 DEG2\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\trl::math::Matrix33 rotation = rl::math::Matrix33::Identity();\n\t\n\tfor (std::size_t i = 0; i < 3; ++i)\n\t{\n\t\trl::math::Real angle = boost::lexical_cast<rl::math::Real>(argv[i + 4]) * rl::math::constants::deg2rad;\n\t\t\n\t\trl::math::Vector3 axis(\n\t\t\t0 == boost::lexical_cast<int>(argv[i + 1]) ? 1 : 0,\n\t\t\t1 == boost::lexical_cast<int>(argv[i + 1]) ? 1 : 0,\n\t\t\t2 == boost::lexical_cast<int>(argv[i + 1]) ? 1 : 0\n\t\t);\n\t\tstd::cout << \"angle\" << i << \": \" << angle << \" rad - axis\" << i << \": \" << axis.transpose() << std::endl;\n\t\t\n\t\trotation = rotation * rl::math::AngleAxis(angle, axis);\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\trl::math::Quaternion quaternion(rotation);\n\tstd::cout << \"quaternion.w: \" << quaternion.w() << \" - quaternion.vec: \" << quaternion.vec().transpose() << std::endl;\n\t\n\trl::math::AngleAxis angleAxis(rotation);\n\tstd::cout << \"angle: \" << angleAxis.angle() << \" rad - axis: \" << angleAxis.axis().transpose() << std::endl;\n\t\n\trl::math::Vector3 orientation = rotation.eulerAngles(2, 1, 0).reverse();\n\tstd::cout << \"x: \" << orientation.x() * rl::math::constants::rad2deg << \" deg - y: \" << orientation.y() * rl::math::constants::rad2deg << \" deg - z: \" << orientation.z() * rl::math::constants::rad2deg << \" deg\" << std::endl;\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "24c1ce21c44cdba23b93f8d5874409975f88056a", "size": 2971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/rlEulerAnglesDemo/rlEulerAnglesDemo.cpp", "max_stars_repo_name": "Broekman/rl", "max_stars_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "demos/rlEulerAnglesDemo/rlEulerAnglesDemo.cpp", "max_issues_repo_name": "Broekman/rl", "max_issues_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "demos/rlEulerAnglesDemo/rlEulerAnglesDemo.cpp", "max_forks_repo_name": "Broekman/rl", "max_forks_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 41.2638888889, "max_line_length": 225, "alphanum_fraction": 0.6825984517, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.5564562890711928}}
{"text": "#ifndef LINEAR_LEAST_SQUARE_MODEL_HPP\n#define LINEAR_LEAST_SQUARE_MODEL_HPP\n\n#include <iostream>\n\n#include <math.h>\n#include <Eigen/QR>\n#include <Eigen/Dense>\n\n#include \"basic_types.hpp\"\n#include \"regression2d.hpp\"\n\n\nnamespace GRANSAC\n{\n\n// model paramter number = 3\ntemplate<int t_param_num>\nclass LinearLeastSquaresModel: public AbstractModel<t_param_num>\n{\nprotected:    \n\t//[1  x0  x0^2] [m_a0] = [y0]\n    //[1  x1  x1^2] [m_a1]   [y1]\n    //[1  x2  x2^2] [m_a2]   [y2]\n    //...                    ...\n    //[1  xn  xn^2]          [yn]\n    // std::vector<VPFloat> m_a;\n\n\t// build a lookup table to calculate point to curve distance\n\t// e.g. target fitting is points in a 400x400 image\n\t// then grid of lookup table is 40x40 cell, each cell is 10x10 pixel\n\tint m_grid_size_x; // cell size of grid, e.g. m_grid_size = 10 -> each cell is 10x10 pixel\n\tint m_grid_size_y;\n\tstd::vector<std::vector<float> > m_occupied_list;\n\n\tvirtual float computeDistanceMeasure(std::shared_ptr<AbstractParameter> input_data) override\n\t{\n\t\tauto ext_point2D = std::dynamic_pointer_cast<Point2D>(input_data);\n\t\tif (ext_point2D == nullptr)\n\t\t\tthrow std::runtime_error(\"PolynomialModel::ComputeDistanceMeasure() - Passed parameter are not of type Point2D.\");\n\n\t\t// build a lookup table for distance calculation\n\t\tfloat min_dist = std::numeric_limits<float>::max();\n        for (auto each : m_occupied_list){\n            float dist = fabs(ext_point2D->m_point2D[0]/m_grid_size_x-each[0]) + fabs(ext_point2D->m_point2D[1]/m_grid_size_y-each[1]); // p-1 distance, 10 is grid size\n            if (min_dist > dist)\n                min_dist = dist;\n        }\n\t\treturn min_dist; // distance in grid, 10 times smaller than actual distance \n\t};\n\npublic:\n\tLinearLeastSquaresModel(const std::vector<std::shared_ptr<AbstractParameter>> &input_data, \n\t               const std::map<std::string, float>& additional_params)\n\t{\n\t\tinitialize(input_data, additional_params);\n\t};\n\n\tvirtual void initialize(const std::vector<std::shared_ptr<AbstractParameter>> &input_data, \n\t                        const std::map<std::string, float>& additional_params) override\n\t{\n\t\tint img_width = (additional_params.count(\"img_width\") == 1) ? additional_params.at(\"img_width\") : 400;\n\t\tint img_height = (additional_params.count(\"img_height\") == 1) ? additional_params.at(\"img_height\") : 400;\n\t\tint grid_num_x = (additional_params.count(\"grid_num_x\") == 1) ? additional_params.at(\"grid_num_x\") : 40;\n\t\tint grid_num_y = (additional_params.count(\"grid_num_y\") == 1) ? additional_params.at(\"grid_num_y\") : 40;\n\n\t\tm_grid_size_x = img_width / grid_num_x; // e.g. 10\n\t\tm_grid_size_y = img_height / grid_num_y;\n\n\t\t// alway calculate curve with three points, since y = ax^2+bx+c\n\t\tif (input_data.size() < t_param_num)\n\t\t\tthrow std::runtime_error(\"PolynomialModel - Number of input parameters does not match minimum number required for this model.\");\n\n\t\tAbstractModel<t_param_num>::m_model_def_parameters = input_data;\n\n\t\t// compute deterministic curve parameters with 3 points\n\t\tstd::vector<float> x_values, y_values, coeff;\n\t\tfor (int i=0; i< input_data.size(); i++){\n\t\t\tauto point = std::dynamic_pointer_cast<Point2D>(input_data[i]);\n\t\t\tif (point == nullptr)\n\t\t\t\tthrow std::runtime_error(\"QuadraticModel - InputParams type mismatch. It is not a Point2D.\");\n\n\t\t\tx_values.push_back(point->m_point2D[0]);\n\t\t\ty_values.push_back(point->m_point2D[1]);\n\t\t}\n\t\tRegression2D::calculateLLS(x_values, y_values, coeff, t_param_num-1);\n\n\t\tstd::vector<float> coeff_f(coeff.begin(), coeff.end());\n\t\tAbstractModel<t_param_num>::m_model_coeffs = coeff_f;\n\t\t\n\t\tm_occupied_list.reserve(grid_num_x*grid_num_y/2);\n\t\t//e.g. img_size=400x400, grid_size=40x40, cell_size=10x10\n\t\tfor (int i=0; i<grid_num_x; i++){ // e.g. i=0; i<40\n\t\t\t\n\t\t\tfloat x_0 = float(i*m_grid_size_x); // e.g. i*10\n\t\t\tfloat x_1 = float((i+1)*m_grid_size_x);\n\n            float y_0 = 0;\n\t\t\tfloat y_1 = 0;\n            for (int j = 0; j < t_param_num; j++){\n                y_0 += coeff[j]*std::pow(x_0, float(j));\n                y_1 += coeff[j]*std::pow(x_1, float(j));\n            }        \n\n\t\t\tbool condi_1 = y_0 <= img_height && y_0 >=0; // e.g. condi_1 = y_0<=400 && y_0>=0\n\t\t\tbool condi_2 = y_1 <= img_height && y_1 >=0;\n\t\t\tif (condi_1 || condi_2){\n\t\t\t\ty_0 = (y_0 > img_height) ? img_height : y_0;\n\t\t\t\ty_0 = (y_0 < 0) ? 0 : y_0;\n\t\t\t\ty_1 = (y_1 > img_height) ? img_height : y_1;\n\t\t\t\ty_1 = (y_1 < 0) ? 0 : y_1;\n\n\t\t\t\tint y_0_idx = floor(y_0 / m_grid_size_y); // e.g. y_0_idx = floor(y_0 / 10)\n\t\t\t\tint y_1_idx = floor(y_1 / m_grid_size_y);\n\n\t\t\t\tif (y_0_idx < y_1_idx){\n\t\t\t\t\tfor (int j=y_0_idx; j<y_1_idx; j++){\n\t\t\t\t\t\tstd::vector<float> xy_pos{float(i), float(j)};\n\t\t\t\t\t\tm_occupied_list.push_back(xy_pos);\n\t\t\t\t\t}\n\t\t\t\t} else if (y_0_idx > y_1_idx){\n\t\t\t\t\tfor (int j=y_1_idx; j<y_0_idx; j++){\n\t\t\t\t\t\tstd::vector<float> xy_pos{float(i), float(j)};\n\t\t\t\t\t\tm_occupied_list.push_back(xy_pos);\n\t\t\t\t\t}\n\t\t\t\t} else{\n\t\t\t\t\tstd::vector<float> xy_pos{float(i), float(y_0_idx)};\n\t\t\t\t\tm_occupied_list.push_back(xy_pos);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// //if curve go through cell, fill cell = 1, otherwise = 0\n\t\t\n\t};\n\n\tvirtual std::pair<float, std::vector<std::shared_ptr<AbstractParameter> > > evaluate(const std::vector<std::shared_ptr<AbstractParameter>>& evaluate_data, float threshold)\n\t{\n\t\tstd::vector<std::shared_ptr<AbstractParameter>> inliers;\n\t\tint n_total_data = evaluate_data.size();\n\t\tint n_inliers = 0;\n\n\t\tfor (auto& each : evaluate_data)\n\t\t{\n\t\t\tif (computeDistanceMeasure(each) < threshold)\n\t\t\t{\n\t\t\t\tinliers.push_back(each);\n\t\t\t\tn_inliers++;\n\t\t\t}\n\t\t}\n\t\tfloat inlier_fraction = float(n_inliers) / float(n_total_data); // This is the inlier fraction\n\t\treturn std::make_pair(inlier_fraction, inliers);\n\t};\n\n};\n\n\n}\n\n#endif /* LINEAR_LEAST_SQUARE_MODEL_HPP */\n", "meta": {"hexsha": "b529805451c67ffc8ea6bceb31a17199dd6122f1", "size": 5724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/least_squares_model.hpp", "max_stars_repo_name": "masszhou/GRANSAC", "max_stars_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/least_squares_model.hpp", "max_issues_repo_name": "masszhou/GRANSAC", "max_issues_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/least_squares_model.hpp", "max_forks_repo_name": "masszhou/GRANSAC", "max_forks_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.775, "max_line_length": 172, "alphanum_fraction": 0.6657931516, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5563587208334025}}
{"text": "#pragma once\n\n#include <deal.II/base/tensor.h>\n#include <complex>\n#include <functional>\n#include \"aux/tensor_helpers.hpp\"\n\n\nnamespace boltzmann {\n\ntemplate <int dim>\nclass QTrapz;\nnamespace _ {\n\ntemplate <class T>\nstruct NumberTraits;\n\ntemplate <int dim, int rank, class NUMBER>\nstruct NumberTraits<dealii::Tensor<dim, rank, NUMBER> >\n{\n  typedef NUMBER numeric_t;\n};\n\ntemplate <>\nstruct NumberTraits<double>\n{\n  typedef double numeric_t;\n};\n\ntemplate <>\nstruct NumberTraits<std::complex<double> >\n{\n  typedef std::complex<double> numeric_t;\n};\n\n}  // end namespace\n\ntemplate <>\nclass QTrapz<1>\n{\n public:\n  QTrapz(int npts, double a, double b);\n\n  template <class NUMBER>\n  NUMBER compute(const std::function<NUMBER(double)>& f) const;\n\n  const std::vector<double>& get_weights() { return weights_; }\n\n  const std::vector<double>& get_points() { return points_; }\n\n private:\n  const double a;\n  const double b;\n  const int npts;\n  std::vector<double> points_;\n  std::vector<double> weights_;\n};\n\n/**\n * trapezoidal quadrature rule, works also with tensor valued functions\n *\n *\n * @return\n */\ntemplate <class NUMBER>\nNUMBER\nqtrapz1d(const std::function<NUMBER(double)>& f, double a, double b, int npts)\n{\n  typedef typename _::NumberTraits<NUMBER>::numeric_t numeric_t;\n  const double h = (b - a) / double(npts - 1);\n\n  NUMBER sum = 0;\n  for (int i = 0; i < npts - 1; ++i) {\n    const double x1 = a + h * (i);\n    const double x2 = a + h * (i + 1);\n    sum += f(x1) + f(x2);\n  }\n  sum *= numeric_t(0.5 * h);\n  return sum;\n}\n\nQTrapz<1>::QTrapz(int npts, double a, double b)\n    : a(a)\n    , b(b)\n    , npts(npts)\n    , points_(npts)\n    , weights_(npts)\n{\n  double h = (b - a) / (npts - 1);\n  for (int i = 0; i < npts; ++i) {\n    if (i == 0 || i == npts - 1)\n      weights_[i] = 0.5 * h;\n    else\n      weights_[i] = h;\n    points_[i] = a + i * h;\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "6981d7f8d97c19a5a8fcab74280609ca48d042fb", "size": 1885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/quadrature/qtrapz.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/quadrature/qtrapz.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/quadrature/qtrapz.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.85, "max_line_length": 78, "alphanum_fraction": 0.6312997347, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5563118947755978}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/sqrt.hpp\n *\n * \\brief Compute the square root of element of a vector or matrix expression.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_SQRT_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_SQRT_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_sqrt_functor_traits\n{\n    typedef VectorExprT input_expression_type;\n    typedef typename vector_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef vector_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT>\nstruct matrix_sqrt_functor_traits\n{\n    typedef MatrixExprT input_expression_type;\n    typedef typename matrix_traits<input_expression_type>::value_type signature_argument_type;\n    typedef signature_argument_type signature_result_type;\n    typedef matrix_unary_functor_traits<\n                input_expression_type,\n                signature_result_type (signature_argument_type)\n            > unary_functor_expression_type;\n    typedef typename unary_functor_expression_type::result_type result_type;\n    typedef typename unary_functor_expression_type::expression_type expression_type;\n};\n\n// Note: this wrapper is needed since we have both templated and non-templated\n//       overloaded versions of the 'sqrt' function.\n//       So whithout this wrapper, the the compiler is not able to infer what\n//       overloaded function to use.\ntemplate <typename T>\nBOOST_UBLAS_INLINE\nT sqrt_impl(T const& x)\n{\n    return ::std::sqrt(x);\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::sqrt 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::sqrt 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_sqrt_functor_traits<VectorExprT>::result_type sqrt(vector_expression<VectorExprT> const& ve)\n{\n    typedef typename detail::vector_sqrt_functor_traits<VectorExprT>::expression_type expression_type;\n    typedef typename detail::vector_sqrt_functor_traits<VectorExprT>::signature_argument_type signature_argument_type;\n\n    return expression_type(ve(), detail::sqrt_impl<signature_argument_type>);\n//  return expression_type(ve(), ::std::sqrt<signature_argument_type>);\n//  return expression_type(ve(), ::std::sqrt<signature_result_type>);\n//  typedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n//  fun_ptr_type ptr_sqrt_fun(&::std::sqrt);\n//  return expression_type(ve(), ptr_sqrt_fun);\n//  return expression_type(ve(), (signature_result_type (*)(signature_argument_type))&::std::sqrt);\n}\n\n\n/**\n * \\brief Applies the \\c std::sqrt 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::sqrt 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_sqrt_functor_traits<MatrixExprT>::result_type sqrt(matrix_expression<MatrixExprT> const& me)\n{\n    typedef typename detail::matrix_sqrt_functor_traits<MatrixExprT>::expression_type expression_type;\n    typedef typename detail::matrix_sqrt_functor_traits<MatrixExprT>::signature_argument_type signature_argument_type;\n\n    return expression_type(me(), detail::sqrt_impl<signature_argument_type>);\n//  return expression_type(me(), ::std::sqrt<signature_argument_type>);\n//  return expression_type(me(), ::std::sqrt<signature_result_type>);\n//  typedef signature_result_type(*fun_ptr_type)(signature_argument_type);\n//  fun_ptr_type ptr_sqrt_fun(&::std::sqrt);\n//  return expression_type(me(), ptr_sqrt_fun);\n//  return expression_type(me(), (signature_result_type (*)(signature_argument_type))&::std::sqrt);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_SQRT_HPP\n", "meta": {"hexsha": "906ba24cff1d6c5ec8d7226d39d39597b8e18adf", "size": 5097, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/sqrt.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/sqrt.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/sqrt.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": 36.9347826087, "max_line_length": 118, "alphanum_fraction": 0.7712379831, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.556311882751434}}
{"text": "/* Boost example/newton-raphson.cpp\r\n * Newton iteration for intervals (partial: 0/0 is missing)\r\n *\r\n * Copyright Guillaume Melquiond 2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors make any representation about the\r\n * suitability of this software for any purpose. It is provided \"as\r\n * is\" without express or implied warranty.\r\n *\r\n * $Id: newton-raphson.cpp,v 1.2 2003/02/05 17:34:35 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/numeric/interval/io.hpp>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <utility>\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\ntemplate <class I> I f(const I& x)\r\n{ return x * (x - 1.) * (x - 2.) * (x - 3.) * (x - 4.); }\r\ntemplate <class I> I f_diff(const I& x)\r\n{ return (((5. * x - 40.) * x + 105.) * x - 100.) * x + 24.; }\r\n\r\nstatic const double max_width = 1e-10;\r\nstatic const double alpha = 0.75;\r\n\r\nusing namespace boost;\r\nusing namespace numeric;\r\nusing namespace interval_lib;\r\n\r\n// First method: no empty intervals\r\n\r\ntypedef interval<double> I1_aux;\r\ntypedef unprotect<I1_aux>::type I1;\r\n\r\nstd::vector<I1> newton_raphson(const I1& xs) {\r\n  std::vector<I1> l, res;\r\n  I1 vf, vd, x, x1, x2;\r\n  l.push_back(xs);\r\n  while (!l.empty()) {\r\n    x = l.back();\r\n    l.pop_back();\r\n    bool x2_used;\r\n    double xx = median(x);\r\n    vf = f(xx);\r\n    vd = f_diff(x);\r\n    if (in_zero(vf) && in_zero(vd)) {\r\n      x1 = I1::whole();\r\n      x2_used = false;\r\n    } else {\r\n      x1 = xx - division_part1(vf, vd, x2_used);\r\n      if (x2_used) x2 = xx - division_part2(vf, vd);\r\n    }\r\n    if (overlap(x1, x)) x1 = intersect(x, x1);\r\n    else if (x2_used) { x1 = x2; x2_used = false; }\r\n    else continue;\r\n    if (x2_used)\r\n      if (overlap(x2, x)) x2 = intersect(x, x2);\r\n      else x2_used = false;\r\n    if (x2_used && width(x2) > width(x1)) std::swap(x1, x2);\r\n    if (!in_zero(f(x1)))\r\n      if (x2_used) { x1 = x2; x2_used = false; }\r\n      else continue;\r\n    if (width(x1) < max_width) res.push_back(x1);\r\n    else if (width(x1) > alpha * width(x)) {\r\n      std::pair<I1, I1> p = bisect(x);\r\n      if (in_zero(f(p.first))) l.push_back(p.first);\r\n      x2 = p.second;\r\n      x2_used = true;\r\n    } else l.push_back(x1);\r\n    if (x2_used && in_zero(f(x2)))\r\n      if (width(x2) < max_width) res.push_back(x1);\r\n      else l.push_back(x2);\r\n  }\r\n  return res;\r\n}\r\n\r\n// Second method: with empty intervals\r\n\r\ntypedef change_checking<I1_aux, checking_no_nan<double> >::type I2_aux;\r\ntypedef unprotect<I2_aux>::type I2;\r\n\r\nstd::vector<I2> newton_raphson(const I2& xs) {\r\n  std::vector<I2> l, res;\r\n  I2 vf, vd, x, x1, x2;\r\n  l.push_back(xs);\r\n  while (!l.empty()) {\r\n    x = l.back();\r\n    l.pop_back();\r\n    double xx = median(x);\r\n    vf = f(xx);\r\n    vd = f_diff(x);\r\n    if (in_zero(vf) && in_zero(vd)) {\r\n      x1 = x;\r\n      x2 = I2::empty();\r\n    } else {\r\n      bool x2_used;\r\n      x1 = intersect(x, xx - division_part1(vf, vd, x2_used));\r\n      x2 = x2_used ? intersect(x, xx - division_part2(vf, vd)) : I2::empty();\r\n    }\r\n    if (width(x2) > width(x1)) std::swap(x1, x2);\r\n    if (empty(x1) || !in_zero(f(x1)))\r\n      if (!empty(x2)) { x1 = x2; x2 = I2::empty(); }\r\n      else continue;\r\n    if (width(x1) < max_width) res.push_back(x1);\r\n    else if (width(x1) > alpha * width(x)) {\r\n      std::pair<I2, I2> p = bisect(x);\r\n      if (in_zero(f(p.first))) l.push_back(p.first);\r\n      x2 = p.second;\r\n    } else l.push_back(x1);\r\n    if (!empty(x2) && in_zero(f(x2)))\r\n      if (width(x2) < max_width) res.push_back(x1);\r\n      else l.push_back(x2);\r\n  }\r\n  return res;\r\n}\r\n\r\nint main() {\r\n  {\r\n    I1_aux::traits_type::rounding rnd;\r\n    std::vector<I1> res = newton_raphson(I1(-1, 5.1));\r\n    std::cout << \"Results: \" << std::endl << std::setprecision(12);\r\n    for(std::vector<I1>::const_iterator i = res.begin(); i != res.end(); ++i)\r\n      std::cout << \"  \" << *i << std::endl;\r\n    std::cout << std::endl;\r\n  }\r\n  {\r\n    I2_aux::traits_type::rounding rnd;\r\n    std::vector<I2> res = newton_raphson(I2(-1, 5.1));\r\n    std::cout << \"Results: \" << std::endl << std::setprecision(12);\r\n    for(std::vector<I2>::const_iterator i = res.begin(); i != res.end(); ++i)\r\n      std::cout << \"  \" << *i << std::endl;\r\n    std::cout << std::endl;\r\n  }\r\n}\r\n", "meta": {"hexsha": "cf423df730a6c888d329fb2e4140602f904d2157", "size": 4497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/newton-raphson.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/newton-raphson.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/examples/newton-raphson.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6690140845, "max_line_length": 78, "alphanum_fraction": 0.5792750723, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173777511623, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.5563118678658534}}
{"text": "//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n#include <utils/math_utils_temp.hh>\n\n#include <Eigen/Dense>\n\n#include <sstream>\n#include <vector>\n\nnamespace ilqr\n{\n\ntemplate<int _rows, int _cols>\nusing Matrix = Eigen::Matrix<double, _rows, _cols>;\n\ntemplate<int _rows>\nusing Vector = Eigen::Matrix<double, _rows, 1>;\n\n// Helper function for debugging a sequence of vectors.\ntemplate<int _dim>\nstd::string time_print(const std::vector<Vector<_dim>> &vectors)\n{\n    std::ostringstream oss;\n    for (size_t t = 0; t < vectors.size(); ++t)\n    {\n        const Vector<_dim> &vec = vectors[t];\n        oss << \"t=\" << t  << \": \" << vec.transpose();\n        if (t < vectors.size() -1)\n        {\n            oss << std::endl;\n        }\n    }\n    return oss.str();\n}\n\n\ntemplate<int _xdim, int _udim, typename DynamicsFunc>\nvoid linearize_dynamics(const DynamicsFunc &dynamics_func, \n                        const Vector<_xdim> &x, \n                        const Vector<_udim> &u,\n                        Matrix<_xdim, _xdim> &A,\n                        Matrix<_xdim, _udim> &B\n                       )\n{\n    const auto helper = [&dynamics_func](const Vector<_xdim+_udim> &xu) -> Vector<_xdim>\n    { \n        Vector<_xdim> x = xu.topRows(_xdim);\n        Vector<_udim> u = xu.bottomRows(_udim);\n        return Vector<_xdim>(dynamics_func(x,u));\n    };\n\n    Vector<_xdim + _udim> xu;\n    xu.topRows(_xdim) = x;\n    xu.bottomRows(_udim) = u;\n    const Matrix<_xdim, _xdim+_udim> J \n        = math::jacobian<_xdim+_udim, _xdim, decltype(helper)>(helper, xu);\n\n    A = J.leftCols(_xdim);\n    B = J.rightCols(_udim);\n}\n\ntemplate<int _xdim, int _udim, typename CostFunc>\nvoid quadratize_cost(const CostFunc &cost_func, \n                     const int t,\n                     const Eigen::VectorXd &x, \n                     const Eigen::VectorXd &u,\n                     Matrix<_xdim,_xdim> &Q,\n                     Matrix<_udim,_udim> &R,\n                     Matrix<_xdim,_udim> &P,\n                     Vector<_xdim> &g_x,\n                     Vector<_udim> &g_u\n                     )\n{\n    const auto helper = [&cost_func, t](const Vector<_xdim+_udim> &xu) -> double\n    { \n        Vector<_xdim> x = xu.topRows(_xdim);\n        Vector<_udim> u = xu.bottomRows(_udim);\n        return double(cost_func(x,u,t));\n    };\n\n    Vector<_xdim + _udim> xu;\n    xu.topRows(_xdim) = x;\n    xu.bottomRows(_udim) = u;\n\n    constexpr double ZERO_THRESH = 1e-7;\n\n    Vector<_xdim+_udim> g \n        = math::gradient<_xdim+_udim, decltype(helper)>(helper, xu);\n    g = g.array() * (g.array().abs() > ZERO_THRESH).template cast<double>();\n    g_x = g.topRows(_xdim);\n    g_u = g.bottomRows(_udim);\n\n\n    // Zero out components that are less than this threshold. We do this since\n    // finite differencing has numerical issues.\n    Matrix<_xdim+_udim,_xdim+_udim> H \n        = math::hessian<_xdim+_udim, decltype(helper)>(helper, xu);\n    //Eigen::MatrixXd H = g * g.transpose();\n    H = H.array() * (H.array().abs() > ZERO_THRESH).template cast<double>();\n    Q = H.topLeftCorner(_xdim, _xdim);\n    P = H.topRightCorner(_xdim, _udim);\n    R = H.bottomRightCorner(_udim, _udim);\n\n    Q = (Q + Q.transpose())/2.0;\n    Q = math::project_to_psd(Q, 1e-11);\n    //math::check_psd(Q, 1e-12);\n\n    // Control terms.\n    R = math::project_to_psd(R, 1e-8);\n    //math::check_psd(R, 1e-9);\n}\n\ntemplate<int _xdim, typename CostFunc>\nvoid quadratize_cost(const CostFunc &cost_func, \n                     const Eigen::VectorXd &x, \n                     Matrix<_xdim,_xdim> &Q,\n                     Vector<_xdim> &g\n                     )\n{\n    constexpr double ZERO_THRESH = 1e-7;\n\n    g = math::gradient<_xdim, CostFunc>(cost_func, x);\n    g = g.array() * (g.array().abs() > ZERO_THRESH).template cast<double>();\n\n\n    // Zero out components that are less than this threshold. We do this since\n    // finite differencing has numerical issues.\n    Matrix<_xdim,_xdim> H \n        = math::hessian<_xdim, CostFunc>(cost_func, x);\n    //Eigen::MatrixXd H = g * g.transpose();\n    Q = H.array() * (H.array().abs() > ZERO_THRESH).template cast<double>();\n\n    Q = (Q + Q.transpose())/2.0;\n    Q = math::project_to_psd(Q, 1e-11);\n    math::check_psd(Q, 1e-12);\n}\n\n} // namespace ilqr\n", "meta": {"hexsha": "75405b70c4fb0b4a2ada07f5f7ccccbedb088fce", "size": 4262, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/templated/taylor_expansion.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/taylor_expansion.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/taylor_expansion.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 29.5972222222, "max_line_length": 88, "alphanum_fraction": 0.5753167527, "num_tokens": 1239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.556311649735894}}
{"text": "/*!\r\n * \\file fitness_metric.cc\r\n *\r\n * \\author Ethan Adams\r\n * \\date\r\n *\r\n * This file contains the cpp version of FitnessMetric.py\r\n */\r\n\r\n#include <iostream>\r\n\r\n#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n\r\n#include <unsupported/Eigen/NonLinearOptimization>\r\n\r\n#include \"BingoCpp/explicit_regression.h\"\r\n#include \"BingoCpp/fitness_metric.h\"\r\n\r\nnamespace bingo {\r\n  \r\nint LMFunctor::operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec) {\r\n  agraphIndv.set_constants(x);\r\n  fvec = fit->evaluate_fitness_vector(agraphIndv, *train);\r\n  return 0;\r\n}\r\n\r\nint LMFunctor::df(const Eigen::VectorXd &x, Eigen::MatrixXd &fjac) {\r\n  double epsilon;\r\n  epsilon = 1e-5f;\r\n\r\n  for (int i = 0; i < x.size(); i++) {\r\n    Eigen::VectorXd xPlus(x);\r\n    xPlus(i) += epsilon;\r\n    Eigen::VectorXd xMinus(x);\r\n    xMinus(i) -= epsilon;\r\n    Eigen::VectorXd fvecPlus(values());\r\n    operator()(xPlus, fvecPlus);\r\n    Eigen::VectorXd fvecMinus(values());\r\n    operator()(xMinus, fvecMinus);\r\n    Eigen::VectorXd fvecDiff(values());\r\n    fvecDiff = (fvecPlus - fvecMinus) / (2.0 * epsilon);\r\n    fjac.block(0, i, values(), 1) = fvecDiff;\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\ndouble FitnessMetric::evaluate_fitness(AcyclicGraph &indv,\r\n                                       TrainingData &train) {\r\n  if (indv.needs_optimization()) {\r\n    optimize_constants(indv, train);\r\n  }\r\n\r\n  return ((evaluate_fitness_vector(indv, train)).abs()).mean();\r\n}\r\n\r\nvoid FitnessMetric::optimize_constants(AcyclicGraph &indv,\r\n                                       TrainingData &train) {\r\n  LMFunctor functor;\r\n  functor.train = &train;\r\n  functor.fit = this;\r\n  functor.m = functor.train->Size();\r\n  // indv.input_constants();\r\n  functor.n = indv.count_constants();\r\n  functor.agraphIndv = indv;\r\n  Eigen::VectorXd vec = Eigen::VectorXd::Random(functor.n);\r\n  Eigen::LevenbergMarquardt<LMFunctor, double> lm(functor);\r\n  lm.minimize(vec);\r\n  indv.set_constants(vec);\r\n  indv.needs_opt = false;\r\n}\r\n} // namespace bingo ", "meta": {"hexsha": "b6470d1fc63f7a54d0c4a9a98419d1418a79648d", "size": 1980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depricated/fitness_metric.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T09:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T14:01:30.000Z", "max_issues_repo_path": "depricated/fitness_metric.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-29T19:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T22:17:53.000Z", "max_forks_repo_path": "depricated/fitness_metric.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-18T02:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:08:39.000Z", "avg_line_length": 27.1232876712, "max_line_length": 77, "alphanum_fraction": 0.6373737374, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5562185636698763}}
{"text": "/*\nMIT License\n\nCopyright (c) 2021 Yoshifumi Asakura\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include <iostream>\n#include <boost/math/distributions/skew_normal.hpp>\n\n\nclass max_record {\n  // no private\npublic:\n  int    num_grid;\n  double width_sig;\n  double dmax;\n  double inv_max;\n  int    search_yet;\n         max_record();\n  double get_inv_max(\n    boost::math::skew_normal_distribution<double> snd,\n    double mu,\n    double sigma\n  );\n};\n\nmax_record::max_record(){\n  num_grid   = 400;\n  width_sig  = 10.0;\n  search_yet = 1;\n  dmax       = 0.0;\n  inv_max    = 1.0;\n}\n\ndouble max_record::get_inv_max(\n    boost::math::skew_normal_distribution<double> snd,\n    double mu,\n    double sigma\n){\n  if(sigma <= 0.0){\n    std::cout << \">>> error, sigma <= 0\" << std::endl;\n    return(0.0);\n  }\n  if(search_yet){\n    search_yet  = 0;\n    double cur;\n    double x;\n    double xmin = mu - sigma * width_sig;\n    double xmax = mu + sigma * width_sig;\n    double dx   = (xmax - xmin) / num_grid;\n    for(x = xmin; x <= xmax; x += dx){\n      cur = boost::math::pdf(snd, x);\n      if(dmax < cur){\n        dmax = cur;\n      }\n    }\n    if(dmax == 0.0){\n      inv_max = 0.0;\n      std::cout << \">>> error, max of the distribusion is 0\" << std::endl;\n    } else {\n      inv_max = 1.0 / dmax;\n    }\n    std::cout << \">>> \" << dmax << \" \" << inv_max << std::endl;\n  }\n  return(inv_max);\n}\n\n// use this in skew_normal_1d\nmax_record mr;\n\n\n\ndouble skew_normal_1d(\n  double   mu_t,\n  double   x,\n  double   sigma_inner,\n  double   startx,\n  double   gauss_max,\n  double   skew_shape\n){\n  // set sigma as the wave length get similar to the normal gaussian\n  double sigma = sigma_inner;\n\n\n  // a constant parameter\n  double alpha = skew_shape * sigma;\n\n\n  double mu    = mu_t + startx;\n\n  // use below in pdf\n  boost::math::skew_normal_distribution<double> snd(mu, sigma, alpha);\n\n  double ratio = mr.get_inv_max(snd, mu, sigma);\n\n  double out   = boost::math::pdf(snd, x) * gauss_max * ratio;\n  return(out);\n}\n", "meta": {"hexsha": "d587925b16a56ab2fdd23910a54c6d56e7376447", "size": 2977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "at210/c_skew.cpp", "max_stars_repo_name": "asakura-yoshifumi/publication20200818", "max_stars_repo_head_hexsha": "7d22fa48b3fc5fb06255da69be65030217df38f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "at210/c_skew.cpp", "max_issues_repo_name": "asakura-yoshifumi/publication20200818", "max_issues_repo_head_hexsha": "7d22fa48b3fc5fb06255da69be65030217df38f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "at210/c_skew.cpp", "max_forks_repo_name": "asakura-yoshifumi/publication20200818", "max_forks_repo_head_hexsha": "7d22fa48b3fc5fb06255da69be65030217df38f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4444444444, "max_line_length": 78, "alphanum_fraction": 0.6718172657, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.6442251133170357, "lm_q1q2_score": 0.55621855324333}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ndt_mcl/3d_ndt_ukf.h>\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nint main()\n{\n    {\n        UKF3D ukf;\n\n        std::cout << \"ukf.getLambda() : \" << ukf.getLambda() << std::endl;\n        std::cout << \"ukf.getXsi() : \" << ukf.getXsi() << std::endl;\n\n        for(int i = 0; i < ukf.getNbSigmaPoints(); i++) {\n            std::cout << \"mean weight [\" << i << \"]:\" << ukf.getWeightMean(i) << std::endl;\n        }\n\n        std::cout << \"####################################################\" << std::endl;\n\n        UKF3D::Params params;\n        params.alpha = 0.4;\n        params.beta = 2.;\n        params.kappa = 3.;\n        ukf.setParams(params);\n\n        std::cout << \"ukf.getLambda() : \" << ukf.getLambda() << std::endl;\n        std::cout << \"ukf.getXsi() : \" << ukf.getXsi() << std::endl;\n\n        for(int i = 0; i < ukf.getNbSigmaPoints(); i++) {\n            std::cout << \"mean weight [\" << i << \"]:\" << ukf.getWeightMean(i) << std::endl;\n        }\n\n        Eigen::VectorXd x(6);\n        x << 1, 2, 3, 0.0, 0.0, 0.0;\n        std::cout << \"x: \" << x << std::endl;\n        Eigen::Affine3d T = ndt_generic::vectorToAffine3d(x);\n\n        Eigen::MatrixXd cov(6,6);\n        cov.setZero();\n        cov(0,0) = 0.1; cov(1,1) = 0.1; cov(2,2) = 0.1;\n        cov(3,3) = 0.02; cov(4,4) = 0.02; cov(5,5) = 0.02;\n    \n        //ukf.initializeFilter(T, cov);\n        ukf.assignSigmas(x, cov);\n\n        std::cout << ukf.getDebugString() << std::endl;\n\n\n        // Eigen::VectorXd mean = ukf.computePoseMean();\n        // std::cout << \"mean : \" <<  ukf.computePoseMean().transpose() << std::endl;\n\n        Eigen::VectorXd mean(6);\n        std::vector<Eigen::Affine3d> T_sigmas = ukf.getSigmasAsAffine3d();\n        std::vector<double> weights = ukf.getMeanWeights();\n        Eigen::Affine3d T2 = ndt_generic::getAffine3dMean(T_sigmas);\n        Eigen::Affine3d T3 = ndt_generic::getAffine3dMeanWeights(T_sigmas, weights);\n        Eigen::Affine3d T4 = ndt_generic::getAffine3dMeanWeightsUsingQuat(T_sigmas, weights);\n        Eigen::Affine3d T5 = ndt_generic::getAffine3dMeanWeightsUsingQuatNaive(T_sigmas, weights);\n\n        std::cout << \"T  -> vec : \" << ndt_generic::affine3dToStringRPY(T) << std::endl;\n        std::cout << \"T2 -> vec : \" << ndt_generic::affine3dToStringRPY(T2) << std::endl;\n        std::cout << \"T3 -> vec : \" << ndt_generic::affine3dToStringRPY(T3) << std::endl;\n        std::cout << \"T4 -> vec : \" << ndt_generic::affine3dToStringRPY(T4) << std::endl;\n        std::cout << \"T5 -> vec : \" << ndt_generic::affine3dToStringRPY(T5) << std::endl;\n    \n        std::cout << \" T : \" << ndt_generic::affine3dToStringRotMat(T) << std::endl;\n        std::cout << \" T2: \" << ndt_generic::affine3dToStringRotMat(T2) << std::endl;\n        std::cout << \" T3: \" << ndt_generic::affine3dToStringRotMat(T3) << std::endl;\n        std::cout << \" T4: \" << ndt_generic::affine3dToStringRotMat(T4) << std::endl;\n        std::cout << \" T5: \" << ndt_generic::affine3dToStringRotMat(T5) << std::endl;\n    \n        std::cout << ukf.getDebugString() << std::endl;\n\n        Eigen::VectorXd incr(6);\n        incr << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        Eigen::Affine3d T_incr = ndt_generic::vectorToAffine3d(incr);\n\n        std::cout << \"T_incr : \" << ndt_generic::affine3dToStringRotMat(T_incr) << std::endl;\n\n        for (int i = 0; i< 5; i++) {\n            std::cout << \"------------------------------\" << std::endl;\n            std::cout << ukf.getDebugString(); \n            ukf.predict(T_incr, cov);\n            mean = ukf.computePoseMean(); \n        \n            std::cout << \"mean[\" << i << \"]: \" <<  mean.transpose() << std::endl;\n        }\n    }\n\n    // {\n    //     UKF3D ukf;\n\n    //     ukf.setParams(0.4, 2., 3);\n        \n    //     Eigen::VectorXd x(6), x2(6);\n    //     x << 1, 2, 3, 0.0, 0.0, 0.0;\n\n    //     Eigen::MatrixXd cov(6,6), cov2(6,6);\n    //     cov.setZero();\n    //     cov(0,0) = 0.1; cov(1,1) = 0.1; cov(2,2) = 0.1;\n    //     cov(3,3) = 0.02; cov(4,4) = 0.02; cov(5,5) = 0.02;\n        \n    //     for (int i = 1; i < 10; i++) {\n    //         double alpha = i*0.01;\n    //         double kappa = i;\n    //         ukf.setParams(alpha, 2., kappa);\n    //         std::cout << \"x: \" << x << std::endl;\n    //         std::cout << \"cov : \" << cov << std::endl;\n    //         ukf.assignSigmas(x, cov);\n            \n    //         x2 = ukf.computePoseMean();\n    //         cov2 = ukf.computePoseCov(x2);\n\n    //         std::cout << \"----------------------------\" << std::endl;\n    //         std::cout << \"x2: \" << x2 << std::endl;\n    //         std::cout << \"cov2 : \" << cov2 << std::endl;\n    //     }\n    // }\n    {\n        UKF3D ukf;\n\n        UKF3D::Params params;\n        params.alpha = 0.1;\n        params.beta = 2.;\n        params.kappa = 3.;\n        ukf.setParams(params);\n        \n        Eigen::VectorXd x(6), x2(6);\n        x << 1, 2, 3, 0.0, 0.0, 0.0;\n\n        Eigen::MatrixXd cov(6,6), cov2(6,6);\n        cov.setZero();\n        cov(0,0) = 10; cov(1,1) = 1; cov(2,2) = 0.1;\n        cov(3,3) = 0.02; cov(4,4) = 0.02; cov(5,5) = 0.02;\n        \n        std::cout << \"x: \" << x << std::endl;\n        std::cout << \"cov : \" << cov << std::endl;\n        ukf.assignSigmas(x, cov);\n        \n        x2 = ukf.computePoseMean();\n        cov2 = ukf.computePoseCov(x2);\n        \n        std::cout << \"----------------------------\" << std::endl;\n        std::cout << \"x2: \" << x2 << std::endl;\n        std::cout << \"cov2 : \" << cov2 << std::endl;\n    }\n}\n", "meta": {"hexsha": "aa8d55dd31498ac78493cb83954307e4e6a7016a", "size": 5541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_mcl/test/ukf_test.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_mcl/test/ukf_test.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_mcl/test/ukf_test.cpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 36.2156862745, "max_line_length": 98, "alphanum_fraction": 0.4786139686, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.556218545081287}}
{"text": "// Implementation of the GCPR 2016 Paper \"Joint Object Pose Estimation and\n// Shape Reconstruction in Urban Street Scenes Using 3D Shape Priors\" by Engelmann et al.\n// Copyright (C) 2016  Francis Engelmann - Visual Computing Institute RWTH Aachen University\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// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n// C/C++ includes\n#include <iostream>\n#include <tuple>\n\n// Own includes\n#include \"geometry.h\"\n\nnamespace gvl {\n\n// See http://www.cs.virginia.edu/~gfx/Courses/1999/intro.fall99.html/lookat.html\n// for implementation details.\nEigen::Matrix4d computeLookAtMatrix(const Eigen::Vector3d& I,\n                                    const Eigen::Vector3d& E,\n                                    const Eigen::Vector3d& U)\n{\n  Eigen::Vector3d F = I-E;\n  Eigen::Vector3d f = F/F.norm();\n  Eigen::Vector3d u = U/U.norm();\n  Eigen::Vector3d s = f.cross(u);\n  Eigen::Vector3d w = s.cross(f);\n\n  Eigen::Matrix<double,4,4> M = Eigen::Matrix<double,4,4>::Identity();\n  M(0,0) = s(0); M(0,1) = s(1); M(0,2) = s(2);\n  M(1,0) = w(0); M(1,1) = w(1); M(1,2) = w(2);\n  M(2,0) = -f(0); M(2,1) = -f(1); M(2,2) = -f(2);\n\n  Eigen::Matrix<double,4,4> T = Eigen::Matrix<double,4,4>::Identity();\n  T(0,3) = -E(0); T(1,3) = -E(1); T(2,3) = -E(2);\n\n  return M*T;\n}\n\nEigen::Matrix3d computeIntrinsicMatrix(const double f_x,\n                                       const double f_y,\n                                       const double p_x,\n                                       const double p_y,\n                                       const double s)\n{\n  Eigen::Matrix<double,3,3> K = Eigen::Matrix<double,3,3>::Identity();\n  K(0,0) = f_x;\n  K(1,1) = f_y;\n  K(0,2) = p_x;\n  K(1,2) = p_y;\n  K(0,1) = s;\n  return K;\n}\n\n// See http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d\nEigen::Matrix4d computeTransformationFromPlane(const double a,\n                                               const double b,\n                                               const double c,\n                                               const double d)\n{\n  Eigen::Vector3d n; n << a,b,c;\n  Eigen::Vector3d m; m << 0,-1,0;\n  Eigen::Vector3d v; v = n.cross(m);\n  double sin = v.norm(); // sine of angle\n  double ccos = n.dot(m); // cosine of angle\n  Eigen::Matrix3d v_x; v_x << 0, -v[2], v[1], v[2], 0, -v[0], -v[1], v[0], 0;\n  Eigen::Matrix3d R; R = Eigen::Matrix3d::Identity() + v_x + v_x*v_x*(1-ccos)/(sin*sin);\n  Eigen::Vector3d t; t << 0, -d, 0;\n  Eigen::Matrix4d T = Eigen::Matrix4d::Identity();\n  T.block<3,3>(0,0) = R;\n  T.block<3,1>(0,3) = t;\n  return T;\n}\n\nvoid computeVerticesFromDisparity(const cv::Mat& disparity,\n                                  const Eigen::Matrix3d& K,\n                                  const double b,\n                                  cv::Mat& vertices)\n{\n  // Init variables\n  const double max_depth = 1000;\n  const double min_depth = 1;\n  const double& baseline = b;\n  const double& f = K(0,0);\n  Eigen::Matrix3d Kinv = K.inverse();\n  vertices = cv::Mat(disparity.rows, disparity.cols, CV_64FC3, cv::Scalar(0,0,0));\n\n  // Iterate over disparity pixels, compute corresponding vertex\n  for (int v=0; v<disparity.rows; v++) {\n    for (int u=0; u<disparity.cols; u++) {\n      // Compute depth\n      double disp = (double)((uint16_t)(disparity.at<unsigned short>(v,u)))/256.0;\n      double depth = (baseline*f)/(disp); //256 according to spspstereo\n      if (depth < min_depth || depth > max_depth) continue;\n\n      // Compute vertice\n      //Eigen::Vector3d v3d = depth*Kinv*Eigen::Vector3d(u,v,1.0);\n      vertices.at<cv::Vec3d>(v,u)[0] = depth*(Kinv(0,0)*u + Kinv(0,1)*v + Kinv(0,2));\n      vertices.at<cv::Vec3d>(v,u)[1] = depth*(Kinv(1,0)*u + Kinv(1,1)*v + Kinv(1,2));\n      vertices.at<cv::Vec3d>(v,u)[2] = depth*(Kinv(2,0)*u + Kinv(2,1)*v + Kinv(2,2));\n    }\n  }\n}\n\nvoid computeDisparityFromVertices(const cv::Mat& vertices,\n                                  const Eigen::Matrix3d& K,\n                                  const double b,\n                                  cv::Mat& disparity)\n{\n\n  // Init variables\n  double max_depth = 1000;\n  double min_depth = 1;\n  const double& baseline = b;\n  const double& f = K(0,0);\n\n  // Iterate over disparity pixels, compute corresponding vertex\n  for (int v=0; v<vertices.rows; v++) {\n    for (int u=0; u<vertices.cols; u++) {\n      cv::Vec3d vertex = vertices.at<cv::Vec3d>(v,u);\n      const double& depth = vertex[2];\n      if (depth < min_depth || depth > max_depth) continue;\n      double disp = (baseline*f)/depth;\n      //unsigned short disp_old = disparity.at<unsigned short>(v,u);\n      unsigned short disp_new = disp*256;\n      disparity.at<unsigned short>(v,u) = disp_new;\n    }\n  }\n}\n\nvoid computeNormalsFromVertices(const cv::Mat& vertices, cv::Mat& normals)\n{\n  double neighbor_dist_threshold = 0.5;\n  normals = cv::Mat(vertices.rows, vertices.cols, CV_64FC3, cv::Scalar(0,0,1) );\n\n  // Iterate over vertices in image\n  for (int v=1; v<normals.rows-1; v++) {\n    for (int u=1; u<normals.cols-1; u++) {\n\n      // Go over 8-neighborhood to compute #neighbors\n      cv::Vec3d b = vertices.at<cv::Vec3d>(v,u); // center\n      //unsigned char neighbor_mask = 0;  // binary mask to mark neighbors within distance threshold\n      unsigned char neighbor_count = 0; // number of neighbors within distance threshold\n      char neighbor_curr = -1;  // index of current neighor that is checked, used for mask\n      cv::Vec3d centroid(0,0,0); // Accumulator to compute centroid\n      Eigen::MatrixXd data_matrix(9,3);\n\n      // Iterate over 8-neighborhood\n      for (int x=u-1; x<=u+1; x++) {\n        for (int y=v-1; y<=v+1; y++) {\n          neighbor_curr++;\n          cv::Vec3d a = vertices.at<cv::Vec3d>(y,x);\n          cv::Vec3d d = a-b;\n          double squared_dist = (d).dot(d);\n\n          // Only accept points within distance threshold\n          if (squared_dist < neighbor_dist_threshold*neighbor_dist_threshold) {\n            data_matrix(neighbor_count, 0) = a[0];\n            data_matrix(neighbor_count, 1) = a[1];\n            data_matrix(neighbor_count, 2) = a[2];\n            neighbor_count++;\n            //neighbor_mask = neighbor_mask | (1<<neighbor_curr);\n            centroid += a;\n          }\n        }\n      }\n\n      // if hte number of neighbors is too small, we need at least 3 vertices\n      if (neighbor_count < 3) continue; // default normal (0,0,1) is assigned, see init\n\n      // Compute centroid and resize data_matrix\n      centroid /= (double)neighbor_count;\n      data_matrix.resize(neighbor_count, 3);\n\n      // Subtract mean from data_matrix\n      for (int i=0; i<neighbor_count; i++) {\n        data_matrix(i,0) -= centroid[0];\n        data_matrix(i,1) -= centroid[1];\n        data_matrix(i,2) -= centroid[2];\n      }\n\n      // Last eigenvector corresponds to normal\n      Eigen::JacobiSVD<Eigen::MatrixXd> svd(data_matrix, Eigen::ComputeThinU | Eigen::ComputeFullV);\n\n      /*double ev0 = svd.singularValues()[0];\n      double ev1 = svd.singularValues()[1];\n      double ratio = ev0/ev1;\n      if (ratio>16) continue; // default normal (0,0,1) is assigned, see init*/\n\n      Eigen::Vector3d n = svd.matrixV().col(2);\n      n /= n.norm();\n\n      // Get the correct orientation, assuming all points are visible from origin\n      Eigen::Vector3d vector; vector << b[0],b[1],b[2];\n      vector/=vector.norm();\n      double dot = vector.dot(n);\n      if (dot>0) n*=-1;\n\n\n      cv::Vec3d normal;\n      normal[0] = n[0];\n      normal[1] = n[1];\n      normal[2] = n[2];\n      normals.at<cv::Vec3d>(v,u) = normal;\n\n    }\n  }\n}\n\nvoid computeNormalsFromVerticesSimple(const cv::Mat& vertices, cv::Mat& normals)\n{\n  normals = cv::Mat(vertices.rows, vertices.cols, CV_64FC3, cv::Scalar(0,0,0) );\n  for (int v=1; v<normals.rows-1; v++) {\n    for (int u=1; u<normals.cols-1; u++) {\n\n      cv::Vec3d v1 = vertices.at<cv::Vec3d>(v+1,u);\n      cv::Vec3d v2 = vertices.at<cv::Vec3d>(v,u);\n      cv::Vec3d v3 = vertices.at<cv::Vec3d>(v,u+1);\n\n      Eigen::Vector3d v1_; v1_ << v1[0],v1[1],v1[2];\n      Eigen::Vector3d v2_; v2_ << v2[0],v2[1],v2[2];\n      Eigen::Vector3d v3_; v3_ << v3[0],v3[1],v3[2];\n      Eigen::Vector3d n = (v1_-v2_).cross(v3_-v2_);\n      n /= n.norm();\n      cv::Vec3d normal; normal[0] = n[0]; normal[1] = n[1]; normal[2] = n[2];\n      normals.at<cv::Vec3d>(v,u) = normal;\n    }\n  }\n}\n\nvoid computePointcloudFromVerticesAndColor(const cv::Mat &vertices,\n                                           const cv::Mat &colors,\n                                           gvl::Pointcloud& pointcloud)\n{\n  // Check that vertices and colors have the same size\n  assert(vertices.cols == colors.cols && vertices.rows == colors.rows);\n\n  // Allocate as many points as pixels in the image,\n  // this allows to address the 3d-points by 2d-coordinates\n  pointcloud.points.resize(vertices.cols*vertices.rows);\n\n  for (int v=0; v<vertices.rows; v++) {\n    for (int u=0; u<vertices.cols; u++) {\n      gvl::Point point;\n      point.x = (double)vertices.at<cv::Vec3d>(v,u)[0];\n      point.y = (double)vertices.at<cv::Vec3d>(v,u)[1];\n      point.z = (double)vertices.at<cv::Vec3d>(v,u)[2];\n      point.r = (unsigned char)colors.at<cv::Vec3b>(v,u)[2];\n      point.g = (unsigned char)colors.at<cv::Vec3b>(v,u)[1];\n      point.b = (unsigned char)colors.at<cv::Vec3b>(v,u)[0];\n      point.u = u;\n      point.v = v;\n      int index = v*vertices.cols + u;\n      pointcloud.points.at(index) = point;\n    }\n  }\n}\n\nvoid computeBoundingBoxFromPointcloud(const Pointcloud &pointcloud, BoundingBox& bb)\n{\n  double min_x=900, max_x=-900;\n  double min_y=900, max_y=-900;\n  double min_z=900, max_z=-900;\n  for (auto p : pointcloud.points) {\n    if (p.x > max_x) max_x=p.x;\n    if (p.y > max_y) max_y=p.y;\n    if (p.z > max_z) max_z=p.z;\n    if (p.x < min_x) min_x=p.x;\n    if (p.y < min_y) min_y=p.y;\n    if (p.z < min_z) min_z=p.z;\n  }\n  bb.height = max_y - min_y;\n  bb.width = max_x - min_x;\n  bb.length = max_z - min_z;\n  bb.x = (max_x + min_x)/2.0;\n  bb.y = max_y;\n  bb.z = (max_z + min_z)/2.0;\n  bb.rotation_y=0;\n}\n\ndouble computeSquaredDistance(const Point& p1, const Point& p2)\n{\n  double d1 = (p1.x-p2.x);\n  double d2 = (p1.y-p2.y);\n  double d3 = (p1.z-p2.z);\n  return d1*d1+d2*d2+d3*d3;\n}\n\ndouble bilinearInterpolation(const Eigen::Vector4d& values,\n                             const Eigen::Vector2d& position) {\n  const double& u = position[0];\n  const double& v = position[1];\n  return (1-u)*(1-v)*values[0] +\n         (0+u)*(1-v)*values[1] +\n         (1-u)*(0+v)*values[2] +\n         (0+u)*(0+v)*values[3];\n}\n\nEigen::Matrix4d computePoseFromRotTransScale(const double rotation_y,\n                                             const Eigen::Vector3d& translation,\n                                             const double scale)\n{\n  //Eigen::AngleAxisd aa(rotation_y, Eigen::Vector3d(0,1,0)); aa.matrix();\n  Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity();\n  rotation(0,0) = std::cos(rotation_y);   rotation(0,2) = std::sin(rotation_y);\n  rotation(2,0) = -std::sin(rotation_y);  rotation(2,2) = std::cos(rotation_y);\n  Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\n  pose.block<3,3>(0, 0) = rotation*scale;\n  pose.block<3,1>(0, 3) = translation;\n  return pose;\n}\n\nvoid computeBoundingBoxFromAnnotation(const Annotation &annotation,\n                                      const Eigen::Vector3f &color,\n                                      BoundingBox &bb)\n{\n  bb.height = 1.7;\n  bb.width = 2.0;\n  bb.length = 4.5;\n  bb.x = annotation.translation[0];\n  bb.y = annotation.translation[1];\n  bb.z = annotation.translation[2];\n  bb.rotation_y = annotation.rotation_y;\n  bb.r = color[0];\n  bb.g = color[1];\n  bb.b = color[2];\n  bb.score = 1.0;\n}\n\ndouble computeMedian(std::vector<double>& values) {\n  std::sort(values.begin(), values.end());\n  std::cout << \"Median >> Values: \"; for (auto t: values) std::cout << t << \" \"; std::cout << std::endl;\n  double median;\n  if (values.size()%2 == 1) {\n    std::cout << \"Median >> Size: \" << values.size() << std::endl;\n    median = values.at(values.size()/2);\n  } else {\n    median = 0.5*values.at(values.size()/2 - 1)+0.5*values.at(values.size()/2);;\n  }\n  std::cout << \"Median: \" << median << std::endl;\n  return median;\n}\n\ndouble computeVerticalDistanceToPlane(const double a,\n                                      const double b,\n                                      const double c,\n                                      const double d,\n                                      const double x,\n                                      const double z)\n{\n  double y = (-d-c*z-a*x)/b;\n  return y;\n}\n\n// From: http://stackoverflow.com/questions/7685495/transforming-a-3d-plane-by-4x4-matrix\n// This does NOT seem to work!!!\nvoid transform_plane(const Eigen::Matrix4d &trafo, Eigen::Vector4d &p)\n{\n  std::cerr << \"Transform_plane does NOT seem to work!!!\" << std::endl;\n  Eigen::Vector4d O = Eigen::Vector4d(p[0]*p[3], p[1]*p[3], p[2]*p[3], 1);\n  Eigen::Vector4d N = Eigen::Vector4d(p[0], p[1], p[2], 0.0);\n  O = trafo*O;\n  N = (trafo.inverse()).transpose() * N;\n\n  Eigen::Vector3d n = Eigen::Vector3d(N[0],N[1],N[2]);\n  Eigen::Vector3d o = Eigen::Vector3d(O[0],O[1],O[2]);\n  p[0] = N[0];\n  p[1] = N[1];\n  p[2] = N[2];\n  p[3] = o.dot(n);\n\n  //vector4 O = (xyz * d, 1)\n  //vector4 N = (xyz, 0)\n  //O = M * O\n  //N = transpose(invert(M)) * N\n  //xyz = N.xyz\n  //d = dot(O.xyz, N.xyz)\n}\n\n\n}\n", "meta": {"hexsha": "b186f7561fcb357e8c85247a80b5147947354988", "size": 14029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engelmann/src/geometry.cpp", "max_stars_repo_name": "davidstutz/daml-shape-completion", "max_stars_repo_head_hexsha": "d0d1d1c26ba547d02c4102077aeb0a1ea46c4e50", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-05-16T01:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T10:24:44.000Z", "max_issues_repo_path": "engelmann/src/geometry.cpp", "max_issues_repo_name": "jtpils/aml-improved-shape-completion", "max_issues_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T04:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T10:38:31.000Z", "max_forks_repo_path": "engelmann/src/geometry.cpp", "max_forks_repo_name": "jtpils/aml-improved-shape-completion", "max_forks_repo_head_hexsha": "9337a0421994199fa218d564cc34a7e7af1a275f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-30T01:30:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T10:24:46.000Z", "avg_line_length": 35.2487437186, "max_line_length": 115, "alphanum_fraction": 0.5795851451, "num_tokens": 4267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5562185428167835}}
{"text": "// GAME - Geometric Algebra Multivector Estimation\n//\n// Copyright (c) 2015, Norwegian University of Science and Technology\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 GAME 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) HOWEVE 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 \"ceres/autodiff_local_parameterization.h\"\n#include <Eigen/Core>\n#include <ceres/autodiff_cost_function.h>\n#include <game/vsr/cga_op.h>\n#include <glog/logging.h>\n\nusing namespace vsr::cga;\n\nconst double kPi = 3.141592653589793238462643383279;\n\nstruct VectorCorrespondencesCostFunctor {\n  VectorCorrespondencesCostFunctor(const Vec &a, const Vec &b) : a_(a), b_(b) {}\n\n  template <typename T>\n  auto operator()(const T *const rotor, T *residual) const -> bool {\n    Rotor<T> R(rotor);\n    Vector<T> a(a_);\n    Vector<T> b(b_);\n    Vector<T> c = a.spin(R);\n\n    for (int i = 0; i < 3; ++i) {\n      residual[i] = c[i] - b[i];\n    }\n\n    return true;\n  }\n\nprivate:\n  const Vec a_;\n  const Vec b_;\n};\n\nstruct RotorPlus {\n  template <typename T>\n  bool operator()(const T *x, const T *delta, T *x_plus_delta) const {\n    const T squared_norm_delta =\n        delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2];\n    T r_delta[4];\n    if (squared_norm_delta > T(0.0)) {\n      T norm_delta = sqrt(squared_norm_delta);\n      const T sin_delta_by_delta = sin(norm_delta) / norm_delta;\n      r_delta[0] = cos(norm_delta);\n      r_delta[1] = sin_delta_by_delta * delta[0];\n      r_delta[2] = sin_delta_by_delta * delta[1];\n      r_delta[3] = sin_delta_by_delta * delta[2];\n    } else {\n      // We do not just use r_delta = [1,0,0,0] here because that is a\n      // constant and when used for automatic differentiation will\n      // lead to a zero derivative. Instead we take a first order\n      // approximation and evaluate it at zero.\n      r_delta[0] = T(1.0);\n      r_delta[1] = delta[0];\n      r_delta[2] = delta[1];\n      r_delta[3] = delta[2];\n    }\n\n    Rotor<T> rotor = Rotor<T>{r_delta[0], r_delta[1], r_delta[2], r_delta[3]} *\n                     Rotor<T>{x[0], x[1], x[2], x[3]};\n\n    for (int i = 0; i < 4; ++i)\n      x_plus_delta[i] = rotor[i];\n\n    return true;\n  }\n};\n\nint main(int argc, char **argv) {\n\n  google::InitGoogleLogging(argv[0]);\n\n  double theta_half{kPi / 6.0};\n  Rot rotor{cos(theta_half), -sin(theta_half), 0.0, 0.0};\n  Vec a{1.0, 0.0, 0.0};\n  Vec b{0.0, 1.0, 0.0};\n\n  Eigen::Matrix<double, 3, 4, Eigen::RowMajor> global_jacobian;\n  Eigen::Matrix<double, 4, 3, Eigen::RowMajor> local_jacobian;\n  Eigen::Matrix<double, 3, 3, Eigen::RowMajor> jacobian;\n  Eigen::Matrix<double, 1, 3> result;\n\n  const double *parameters[1] = {rotor.begin()};\n  double *global_jacobian_array[1] = {global_jacobian.data()};\n\n  ceres::AutoDiffCostFunction<VectorCorrespondencesCostFunctor, 3, 4>(\n      new VectorCorrespondencesCostFunctor(a, b))\n      .Evaluate(parameters, result.data(), global_jacobian_array);\n\n  ceres::AutoDiffLocalParameterization<RotorPlus, 4, 3>(new RotorPlus())\n      .ComputeJacobian(rotor.begin(), local_jacobian.data());\n\n  jacobian = global_jacobian * local_jacobian;\n\n  std::cout << \"Jacobian of the function F = R * a * ~R - b where\" << std::endl;\n  std::cout << \"R is a Euclidean rotor with coefficients:\" << std::endl;\n  std::cout << \"R: \" << rotor << std::endl;\n  std::cout << \"and a and b are vectors with coefficients:\" << std::endl;\n  std::cout << \"a: \" << a << std::endl;\n  std::cout << \"b: \" << b << std::endl;\n  std::cout << \"The resulting vector have coefficients:\" << std::endl;\n  std::cout << result << std::endl;\n  std::cout << std::endl;\n  std::cout << \"The resulting 3x4 global jacobian:\" << std::endl;\n  std::cout << global_jacobian << std::endl;\n  std::cout << \"The 3x3 local jacobian:\" << std::endl;\n  std::cout << local_jacobian << std::endl;\n  std::cout << \"The final 3x3 jacobian:\" << std::endl;\n  std::cout << jacobian << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "42483b71a8f9fa49d6e9e472118d9b53f2cb22f0", "size": 5253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/multivector_auto_diff.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": "examples/multivector_auto_diff.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": "examples/multivector_auto_diff.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": 37.5214285714, "max_line_length": 80, "alphanum_fraction": 0.6750428327, "num_tokens": 1480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5562002256354752}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include <pangolin/pangolin.h>\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\nusing Eigen::Isometry3d;\nusing Eigen::Vector3d;\nusing Eigen::Quaterniond;\nusing Eigen::Matrix3d;\nusing std::vector;\n\nconst double DT = 1.0 / 18;\n// const Eigen::Vector3d GRAVITY{0, 0, 0};\nconst Eigen::Vector3d GRAVITY{0, 0, -9.8};\n\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>);\nvoid DrawTrajectoryComparison(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>,\n                              vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>>);\nstruct State {\n  Vector3d pos = Vector3d::Random(); \n  Vector3d vel = Vector3d::Random();  \n  Quaterniond q = Quaterniond::UnitRandom(); \n  Vector3d bias = Vector3d::Zero(); \n  State() {}\n\n  State(Vector3d& pos, Vector3d& vel, Quaterniond& q, Vector3d& bias)\n    : pos(pos), vel(vel), q(q), bias(bias) {}\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\nstruct Measurement{\n  Matrix3d Rwr;\n  Quaterniond qwr;\n  Vector3d twr;\n  Vector3d acc;\n  Vector3d omega; \n\n  Measurement(Matrix3d Rwr,                \n              Quaterniond qwr,\n              Vector3d twr,\n              Vector3d acc,\n              Vector3d omega)\n    : Rwr(Rwr), qwr(qwr), twr(twr), acc(acc), omega(omega) {}\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct StateError {\n  StateError(const Vector3d& pos_state,\n\t\t\t\t\t\t const Vector3d& vel_state,\n             const Quaterniond& q_state,\n             const Vector3d& bias_state,\n             const Eigen::Matrix<double, 12, 12>& sqrt_cov)\n    : pos_state_(pos_state), vel_state_(vel_state), q_state_(q_state), bias_state_(bias_state), sqrt_cov_(sqrt_cov) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_hat_ptr,\n                  const T* const vel_hat_ptr,\n                  const T* const q_hat_ptr,\n                  const T* const bias_hat_ptr,\n                  T* residuals_ptr) const {   \n    Eigen::Matrix<T, 12, 1> residuals;\n    \n    Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n    Eigen::Matrix<T, 3, 1> vel_hat(vel_hat_ptr);\n    Eigen::Quaternion<T> q_hat(q_hat_ptr);\n    Eigen::Matrix<T, 3, 1> bias_hat(bias_hat_ptr); \n\n    // pos error\n    residuals.template block<3, 1>(0, 0) = pos_hat - pos_state_.template cast<T>();\n\n    // vel error\n    residuals.template block<3, 1>(3, 0) = vel_hat - vel_state_.template cast<T>();\n\n    // quat error\n    Eigen::Quaternion<T> q_delta = q_state_.conjugate().template cast<T>() * q_hat;\n    residuals.template block<3, 1>(6, 0) = q_delta.vec();\n\n    // bias error\n    double bias_weight = 1.5;\n    residuals.template block<3, 1>(9, 0) = T(bias_weight) * (bias_hat - bias_state_.template cast<T>());\n\n    // marginal factor\n    residuals = sqrt_cov_ * residuals;\n    for (int i = 0; i < residual_size; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Vector3d& pos_state,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst Vector3d& vel_state,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst Quaterniond& q_state,\n                              const Vector3d& bias_state,\n                              const Eigen::Matrix<double, 12, 12>& sqrt_cov) {\n    return new AutoDiffCostFunction<StateError, 12, 3, 3, 4, 3>(\n      new StateError(pos_state, vel_state, q_state, bias_state, sqrt_cov));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  int residual_size = 12;\n  const Vector3d pos_state_;\n  const Vector3d vel_state_;\n  const Quaterniond q_state_;\n  const Vector3d bias_state_;\n  const Eigen::Matrix<double, 12, 12> sqrt_cov_;\n};\n\nstruct PoseError {\n  PoseError(const Eigen::Vector3d& pos_measured,\n            const Eigen::Quaterniond& q_measured)\n    : pos_measured_(pos_measured), q_measured_(q_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_hat_ptr,\n                  const T* const q_hat_ptr,\n                  T* residuals_ptr) const {   \n    Eigen::Matrix<T, 6, 1> residuals;\n    \n    Eigen::Matrix<T, 3, 1> pos_hat(pos_hat_ptr);\n    Eigen::Quaternion<T> q_hat(q_hat_ptr);\n    \n    // pos error \n    Eigen::Matrix<T, 3, 1> pos_delta;\n    residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast<T>();\n\n    // quat error\n    Eigen::Quaternion<T> q_delta = q_measured_.conjugate().template cast<T>() * q_hat;\n    residuals.template block<3, 1>(3, 0) = q_delta.vec();\n    for (int i = 0; i < 6; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& pos_measured,\n                              const Eigen::Quaterniond& q_measured) {\n    return new AutoDiffCostFunction<PoseError, 6, 3, 4>(\n      new PoseError(pos_measured, q_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  const Eigen::Vector3d pos_measured_;\n  const Eigen::Quaterniond q_measured_;\n};\n\n\nstruct PredictionError{\n  PredictionError(const Eigen::Vector3d& acc_measured,\n                  const Eigen::Vector3d& omega_measured)\n    : acc_measured_(acc_measured), omega_measured_(omega_measured) {}\n\n  template <typename T>\n  bool operator()(const T* const pos_b_ptr,\n                  const T* const vel_b_ptr,\n                  const T* const q_b_ptr,\n                  const T* const bias_b_ptr,\n                  const T* const pos_e_ptr,\n                  const T* const vel_e_ptr,\n                  const T* const q_e_ptr,\n                  const T* const bias_e_ptr,\n                  T* residuals_ptr) const {\n    Eigen::Matrix<T, 12, 1> residuals;\n\n    const Eigen::Matrix<T, 3, 1> pos_b(pos_b_ptr);\n    const Eigen::Matrix<T, 3, 1> pos_e(pos_e_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_b(vel_b_ptr);\n    const Eigen::Matrix<T, 3, 1> vel_e(vel_e_ptr);\n    const Eigen::Quaternion<T> q_b(q_b_ptr);\n    const Eigen::Quaternion<T> q_e(q_e_ptr);\n    const Eigen::Matrix<T, 3, 1> bias_b(bias_b_ptr);\n    const Eigen::Matrix<T, 3, 1> bias_e(bias_e_ptr);\n\n    // pos error\n    residuals.template block<3, 1>(0, 0) = pos_b + vel_b * DT - pos_e;\n\n    // vel error\n    residuals.template block<3, 1>(3, 0) = vel_b + (q_b * (acc_measured_.template cast<T>() - bias_b) - GRAVITY) * DT - vel_e;\n\n    // quat errorsqrt_cov\n    Eigen::Quaternion<T> q_new;\n    Eigen::Quaternion<T> q_add; \n    \n    // // https://gamedev.stackexchange.com/questions/108920/applying-angular-velocity-to-quaternion \n    // Eigen::Quaternion<T> q_omega;\n    // // q_omega.w() = 0;\n    // q_omega.vec() = omega_measured_.template cast<T>() * DT * 0.5;\n    // q_add = q_omega * q_b;\n    // q_new.w() = q_b.w() + q_add.w();\n    // q_new.vec() = q_b.vec() + q_add.vec();\n\n    Eigen::Vector3d rotated = omega_measured_ * DT;\n    double angle = rotated.norm();\n    Eigen::Vector3d axis = rotated.normalized();\n    q_add = Eigen::AngleAxisd(angle, axis).template cast<T>();\n    q_new = q_b * q_add;\n  \n    Eigen::Quaternion<T> q_delta = q_e.conjugate() * q_new;\n    residuals.template block<3, 1>(6, 0) = q_delta.vec();\n\n    // bias error\n    residuals.template block<3, 1>(9, 0) = bias_e - bias_b; \n\n    for (int i = 0; i < residual_size; i++) {\n      residuals_ptr[i] = residuals[i];\n    }\n    return true;\n  } \n  \n  static CostFunction* Create(const Eigen::Vector3d& acc_measured,\n                              const Eigen::Vector3d& omega_measured) {\n    return new AutoDiffCostFunction<PredictionError, 12, 3, 3, 4, 3, 3, 3, 4, 3>(\n      new PredictionError(acc_measured, omega_measured));\n  }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  int residual_size = 12;\n  const Eigen::Vector3d acc_measured_;\n  const Eigen::Vector3d omega_measured_;\n};\n\nvoid print_state(const State& state) {\t\n  Eigen::AngleAxisd ori(state.q);\n\n  std::cout << \"state pos: \\n\" << state.pos << \"\\n\"\n            << \"state vel: \\n\" << state.vel << \"\\n\"\n            << \"state ori: \\n\" << ori.angle() << \" \" << ori.axis() << \"\\n\"\n            << \"state bias: \\n\" << state.bias << std::endl;\n}\n\nclass FixLagSmoother {\t\npublic:\n\tstd::vector<State, Eigen::aligned_allocator<State>> get_all_states() {\n\t\treturn all_states;\n\t}\n\n\tbool step(Measurement& measurement) {\n\t\tall_states.push_back(State());\t\n\t\tint state_num = all_states.size();\n\t\tint marginal_idx = state_num - wind_size;\n    std::cout << \"current state_num: \" << state_num << \"marginal_idx: \" << marginal_idx << std::endl;\n\t\t\n    \n    Problem problem;\n\t\tceres::LossFunction* loss_function = nullptr;\n\t\tceres::LocalParameterization* quaternion_local_parameterization =\n\t\t\t\tnew ceres::EigenQuaternionParameterization;\n\n\t\tceres::CostFunction* marginal_cost_function = StateError::Create(all_states[marginal_idx].pos,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].vel,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].q,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].bias,\n                                                                     sqrt_cov);\n\t\tproblem.AddResidualBlock(marginal_cost_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t loss_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].pos.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].vel.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[marginal_idx].bias.data());\n    problem.SetParameterization(all_states[marginal_idx].q.coeffs().data(),\n                                quaternion_local_parameterization);      \n\t\tfor (int i = marginal_idx + 1; i < state_num; i++) {\n\t\t\tceres::CostFunction* pos_cost_function = PoseError::Create(measurement.twr,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t measurement.qwr); \n\t\t\tproblem.AddResidualBlock(pos_cost_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t loss_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].pos.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].q.coeffs().data());\n\t\t\tproblem.SetParameterization(all_states[i].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquaternion_local_parameterization);      \n\t\t\tceres::CostFunction* pred_cost_function = PredictionError::Create(measurement.acc, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeasurement.omega);\n\t\t\tproblem.AddResidualBlock(pred_cost_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t loss_function,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i - 1].pos.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i - 1].vel.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i - 1].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i - 1].bias.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].pos.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].vel.data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t all_states[i].bias.data());\n\t\t\tproblem.SetParameterization(all_states[i - 1].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  quaternion_local_parameterization);      \n\t\t\tproblem.SetParameterization(all_states[i].q.coeffs().data(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquaternion_local_parameterization);      \n\t\t};\n    \n\t\tceres::Solver::Options options;\n\t\toptions.max_num_iterations = 200;\n\t\toptions.linear_solver_type = ceres::DENSE_SCHUR;\n\t\t// options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n\t\toptions.minimizer_progress_to_stdout = true;\n\n\t\tceres::Solver::Summary summary;\n\t\tceres::Solve(options, &problem, &summary);\n\t\tstd::cout << \"Iteration: \" << marginal_idx + 1 << \"\\n\" << summary.FullReport() << \"\\n\";\n    print_state(all_states[marginal_idx]);\n\n\t\t// ceres covariance matrix estimation\n\t\tupdate_marginal_llt(marginal_idx + 1, problem);\n\t}\n\n\tbool update_marginal_llt(int marginal_idx, ceres::Problem& problem) {\t\t\t\n\t\tceres::Covariance::Options options;\n\t\tceres::Covariance covariance(options);\n\n\t\tstd::vector<std::pair<const double*, const double*>> covariance_blocks;\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].pos.data(), all_states[marginal_idx].pos.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].pos.data(), all_states[marginal_idx].vel.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].pos.data(), all_states[marginal_idx].q.coeffs().data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].pos.data(), all_states[marginal_idx].bias.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].vel.data(), all_states[marginal_idx].vel.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].vel.data(), all_states[marginal_idx].q.coeffs().data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].vel.data(), all_states[marginal_idx].bias.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].q.coeffs().data(), all_states[marginal_idx].q.coeffs().data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].q.coeffs().data(), all_states[marginal_idx].bias.data()));\n\t\tcovariance_blocks.push_back(std::make_pair(all_states[marginal_idx].bias.data(), all_states[marginal_idx].bias.data()));\n\n\t\tceres::LocalParameterization* quaternion_local_parameterization =\n\t\t\t\tnew ceres::EigenQuaternionParameterization;\n    problem.SetParameterization(all_states[marginal_idx].q.coeffs().data(),\n                                quaternion_local_parameterization);      \n\t\tCHECK(covariance.Compute(covariance_blocks, &problem));\n\n    double covariance_pp[3 * 3];\n    double covariance_pv[3 * 3];\n    double covariance_pq[3 * 3];\n    double covariance_pb[3 * 3];\n    double covariance_vv[3 * 3];\n    double covariance_vq[3 * 3];\n    double covariance_vb[3 * 3];\n    double covariance_qq[3 * 3];\n    double covariance_qb[3 * 3];\n    double covariance_bb[3 * 3];\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].pos.data(), all_states[marginal_idx].pos.data(), covariance_pp);\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].pos.data(), all_states[marginal_idx].vel.data(), covariance_pv);\n\t\tcovariance.GetCovarianceBlockInTangentSpace(all_states[marginal_idx].pos.data(), all_states[marginal_idx].q.coeffs().data(), covariance_pq);\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].pos.data(), all_states[marginal_idx].bias.data(), covariance_pb);\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].vel.data(), all_states[marginal_idx].vel.data(), covariance_vv);\n\t\tcovariance.GetCovarianceBlockInTangentSpace(all_states[marginal_idx].vel.data(), all_states[marginal_idx].q.coeffs().data(), covariance_vq);\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].vel.data(), all_states[marginal_idx].bias.data(), covariance_vb);\n\t\tcovariance.GetCovarianceBlockInTangentSpace(all_states[marginal_idx].q.coeffs().data(), all_states[marginal_idx].q.coeffs().data(), covariance_qq);\n\t\tcovariance.GetCovarianceBlockInTangentSpace(all_states[marginal_idx].q.coeffs().data(), all_states[marginal_idx].bias.data(), covariance_qb);\n\t\tcovariance.GetCovarianceBlock(all_states[marginal_idx].bias.data(), all_states[marginal_idx].bias.data(), covariance_bb);\n\n\t\tEigen::Matrix<double, 12, 12> cov;\n\t\tcov.block<3, 3>(0, 0) = Eigen::Matrix3d(covariance_pp);\n\t\tcov.block<3, 3>(0, 3) = Eigen::Matrix3d(covariance_pv);\n\t\tcov.block<3, 3>(0, 6) = Eigen::Matrix3d(covariance_pq);\n\t\tcov.block<3, 3>(0, 9) = Eigen::Matrix3d(covariance_pb);\n\t\tcov.block<3, 3>(3, 0) = Eigen::Matrix3d(covariance_pv).transpose();\n\t\tcov.block<3, 3>(3, 3) = Eigen::Matrix3d(covariance_vv);\n\t\tcov.block<3, 3>(3, 6) = Eigen::Matrix3d(covariance_vq);\n\t\tcov.block<3, 3>(3, 9) = Eigen::Matrix3d(covariance_vb);\n\t\tcov.block<3, 3>(6, 0) = Eigen::Matrix3d(covariance_pq).transpose();\n\t\tcov.block<3, 3>(6, 3) = Eigen::Matrix3d(covariance_pv).transpose();\n\t\tcov.block<3, 3>(6, 6) = Eigen::Matrix3d(covariance_qq);\n\t\tcov.block<3, 3>(6, 9) = Eigen::Matrix3d(covariance_qb);\n\t\tcov.block<3, 3>(9, 0) = Eigen::Matrix3d(covariance_pb).transpose();\n\t\tcov.block<3, 3>(9, 3) = Eigen::Matrix3d(covariance_vb).transpose();\n\t\tcov.block<3, 3>(9, 6) = Eigen::Matrix3d(covariance_qb).transpose();\n\t\tcov.block<3, 3>(9, 9) = Eigen::Matrix3d(covariance_bb);\n\n    std::cout << \"cov: \\n\" << cov << std::endl;\n    std::cout << \"cov_inv: \\n\" << cov.inverse() << std::endl;\n\n    // (x_2 - x_2_hat).T * cov_inv(H) * (x_2 - x_2_hat)\n    // cov_inv = U.T * U = L * L.T\n    // b = U * (x_2 - x_2_hat)\n    // cost = b.T * b\n    Eigen::LLT<Eigen::Matrix<double, 12, 12>> lltOfcovinv(cov.inverse()); // compute the Cholesky decomposition\n    sqrt_cov = lltOfcovinv.matrixU();\n\n    // sqrt_cov.block<3, 3>(9, 9) = Matrix3d::Identity();\n    std::cout << \"sqrt_cov: \\n\" << sqrt_cov << std::endl;\n    return true;\n\t}\n\n\tbool initialize(const int& wind_size, const State& init_state) {\n\t\tthis->wind_size = wind_size;\t\t\n    all_states.push_back(init_state);\n    return true;\n\t}\n\nprivate:\n\tint wind_size = 2;\n  Eigen::Matrix<double, 12, 12> sqrt_cov = Eigen::Matrix<double, 12, 12>::Identity();\n\tEigen::Vector3d bias = Eigen::Vector3d::Zero();\n\tEigen::Matrix3d state_hessian;\n\tEigen::Matrix3d state_b;\n\tstd::vector<State, Eigen::aligned_allocator<State>> all_states;\n};\n\n\nvoid save_states(const std::string& filename, \n                 std::vector<State, Eigen::aligned_allocator<State>>& states) {\n  std::fstream outfile;\n  outfile.open(filename.c_str(), std::istream::out);\n\n  for (auto& state : states) {\n    Eigen::Matrix3d rot = state.q.matrix();\n    outfile << rot << \"\\n\" << state.pos.transpose() << \"\\n\" << state.vel.transpose() << \"\\n\\n\";\n  }\n}\n\nstd::vector<Measurement, Eigen::aligned_allocator<Measurement>> readSensorData(std::string path) {\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> ret;\n\n  std::ifstream csvFile;\n  csvFile.open(path);\n\n  std::string line;\n  while(std::getline(csvFile, line)) {\n    std::vector<double> row;\n    // std::cout << \"line:\" << line << std::endl;\n    std::istringstream s(line);\n    std::string field;\n    while (std::getline(s, field,',')) {\n      // std::cout << \"field: \" << field << std::endl;\n      row.push_back(std::stod(field));\n    }  \n    Eigen::Matrix3d Rwr;\n    Eigen::Quaterniond qwr;\n    Eigen::Vector3d twr;\n    Eigen::Vector3d acc;\n    Eigen::Vector3d omega; \n    Rwr << row[0], row[1], row[2],\n          row[4], row[5], row[6],\n          row[8], row[9], row[10];\n    qwr = Rwr;\n    twr << row[3], row[7], row[11];\n    acc << row[16], row[17], row[18];\n    omega << row[19], row[20], row[21];\n    // std::cout << \"Rwr: \" << Rwr << std::endl;\n    // std::cout << \"qwr: \" << qwr.w() << \" \" << qwr.vec() << std::endl; \n    // std::cout << \"twr: \" << twr << std::endl;\n    // std::cout << \"acc: \" << acc << std::endl;\n    // std::cout << \"omega: \" << omega << std::endl;\n    \n    ret.push_back(Measurement(Rwr, qwr, twr, acc, omega));\n  }\n\n  return ret;\n}\n\ndouble abs_pos_error(const std::vector<State, Eigen::aligned_allocator<State>>& states,\n                     const std::vector<State, Eigen::aligned_allocator<State>>& gt_states) {\n  double err = 0.0;\n  std::cout << \"abs_pos_err by step: \";\n  for (int i = 0; i < states.size(); i++) {\n    double step_err = (states[i].pos - gt_states[i].pos).norm();\n    err += step_err;\n    std::cout << step_err << \" \";\n  }\n  std::cout << std::endl;\n  return err;\n}\n\nint main(int argc, char** argv) {\n  if(argc < 2) {\n    std::cout << \"missing arg for the csv file\" << std::endl;\n  }\n\n  std::string path = argv[1];\n  std::vector<Measurement, Eigen::aligned_allocator<Measurement>> data = readSensorData(path);    \n  int cnt = data.size();\n  // cnt = 15;\n\tint wind_size = 2;\n \n  std::vector<State, Eigen::aligned_allocator<State>> gt_states(cnt);\n  std::cout << \"states size: \" << gt_states.size() << std::endl;\n\n  for (int i = 0; i < gt_states.size(); i++) {\n    gt_states[i].pos = data[i].twr;\n    gt_states[i].vel = Eigen::Vector3d::Zero();\n    gt_states[i].q = data[i].qwr;\n  }\n  gt_states[0].vel = Eigen::Vector3d({0, 94.25, 0});\n\tFixLagSmoother smoother;\n\n  Vector3d init_vel({0, 0, 0});\n  Vector3d init_bias({0, 0, 0});\n  State init_state(data[0].twr, init_vel, data[0].qwr, init_bias);\n\tsmoother.initialize(wind_size, init_state);\n\n\tfor (int i = wind_size - 1; i < cnt; i++) {\n\t\tsmoother.step(data[i]);\n\t}\n  \n  std::vector<State, Eigen::aligned_allocator<State>> states = smoother.get_all_states();\n\n  std::string est_filename = \"./results/increm_states.txt\";\n  save_states(est_filename, states);\n\n\n  vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses;\n  vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> gt_poses;\n  for (int i = 0; i < cnt; i++) {\n    Isometry3d Twr(states[i].q.matrix());\n    Twr.pretranslate(states[i].pos / 20); // manually divided by 20 to zoom out\n    poses.push_back(Twr);\n  }\n  for (int i = 0; i < cnt; i++) {\n    Isometry3d Twr(gt_states[i].q.matrix());\n    Twr.pretranslate(gt_states[i].pos / 20); // manually divided by 20 to zoom out\n    gt_poses.push_back(Twr);\n  }\n\n  double err = abs_pos_error(states, gt_states); \n  std::cout << \"absolute position error: \" << err << std::endl;\n  DrawTrajectoryComparison(poses, gt_poses);\n\treturn 0;\n}\n\nvoid DrawTrajectoryComparison(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses,\n                              vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> gt_poses) {\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // 画每个位姿的三个坐标轴\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // 画出连线\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(1.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      // 画每个位姿的三个坐标轴\n      Vector3d Ow = gt_poses[i].translation();\n      Vector3d Xw = gt_poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = gt_poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = gt_poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // 画出连线\n    for (size_t i = 0; i < gt_poses.size(); i++) {\n      glColor3f(0.0, 1.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = gt_poses[i], p2 = gt_poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}\n\n/*******************************************************************************************/\nvoid DrawTrajectory(vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses) {\n  // create pangolin window and plot the trajectory\n  pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n  glEnable(GL_DEPTH_TEST);\n  glEnable(GL_BLEND);\n  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n  pangolin::OpenGlRenderState s_cam(\n    pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n    pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n  );\n\n  pangolin::View &d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n  while (pangolin::ShouldQuit() == false) {\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    d_cam.Activate(s_cam);\n    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n    glLineWidth(2);\n    for (size_t i = 0; i < poses.size(); i++) {\n      // 画每个位姿的三个坐标轴\n      Vector3d Ow = poses[i].translation();\n      Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n      Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n      Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n      glBegin(GL_LINES);\n      glColor3f(1.0, 0.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Xw[0], Xw[1], Xw[2]);\n      glColor3f(0.0, 1.0, 0.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Yw[0], Yw[1], Yw[2]);\n      glColor3f(0.0, 0.0, 1.0);\n      glVertex3d(Ow[0], Ow[1], Ow[2]);\n      glVertex3d(Zw[0], Zw[1], Zw[2]);\n      glEnd();\n    }\n    // 画出连线\n    for (size_t i = 0; i < poses.size(); i++) {\n      glColor3f(0.0, 0.0, 0.0);\n      glBegin(GL_LINES);\n      auto p1 = poses[i], p2 = poses[i + 1];\n      glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n      glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n      glEnd();\n    }\n    pangolin::FinishFrame();\n    usleep(5000);   // sleep 5 ms\n  }\n}\n", "meta": {"hexsha": "0db3c6dea01f933aeef711546a77c5f14b1fbc65", "size": 25784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/solverFixedLag.cpp", "max_stars_repo_name": "yimuw/expriment", "max_stars_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experimental/solverFixedLag.cpp", "max_issues_repo_name": "yimuw/expriment", "max_issues_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experimental/solverFixedLag.cpp", "max_forks_repo_name": "yimuw/expriment", "max_forks_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5988023952, "max_line_length": 149, "alphanum_fraction": 0.6314381011, "num_tokens": 7897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5562002189202521}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <math.h>\r\n#include <vector>\r\n#include <array>\r\n#include \"GeneralizedHeat.hpp\"\r\n#include \"TriDiagMatrix.hpp\"\r\n#include \"MassMatrix.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <fstream>\r\n#include <string>\r\n#include <functional>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\n\r\nvoid GeneralHeat::EnergyNorm()\r\n{\r\nmpEnergyNorm.clear();\r\nBuildGradientVec(mpx, mpsmesh, FEMGradient);\r\n\r\nauto SquaredError = [this](double x)\r\n    { return pow(GradientFunction(x) - mppde->AnalyticGradientWRTx(x, mptmesh.ReadTimeStep(mpcurrenTimeStep)), 2); };\r\n\r\nfor(int i=0; i<mpsmesh.meshsize(); i++)\r\n{\r\nmpEnergyNorm.push_back( gauss<double, 7>::integrate(SquaredError,\r\n                                        mpsmesh.ReadSpaceNode(i), mpsmesh.ReadSpaceNode(i+1)) );\r\n\r\n}\r\n        double globalError=0;\r\n        for(auto k: mpEnergyNorm)\r\n            globalError = globalError + k;\r\n        //std::cout << sqrt(globalError);\r\n}\r\n\r\nvoid GeneralHeat::AddVectors(std::vector<double>func1, std::vector<double> func2, std::vector<double>& result)\r\n{\r\n    if(func1.size()==func2.size())\r\n    {\r\n    result.clear();\r\n     for ( int i=0; i<func1.size(); i++ )\r\n     {\r\n         result.push_back(func1.at(i)+func2.at(i));\r\n     }\r\n    }\r\n    else\r\n    {\r\n        std::cout<< \" your vectors are different sizes\";\r\n        std::cout<<\"\\n\";\r\n    }\r\n}\r\n\r\nvoid GeneralHeat::SetSpaceTimeMesh( SpaceMesh smesh, TimeMesh tmesh, APDE& apde )\r\n{\r\n    mpsmesh = smesh;\r\n    mptmesh = tmesh;\r\n    mppde = &apde;\r\n    k_0 = mppde->k_0;\r\n    k_L = mppde->k_L;\r\n    g_0 = mppde->g_0;\r\n    g_L = mppde->g_L;\r\n    mpa = mppde->a;\r\n\r\n    //std::cout<<apde.k_0<<\"\\n\"<<apde.k_L<<\"\\n\"<<mpa<<\"\\n\"<<g_0<<\"\\n\"<<g_L;\r\n}\r\n\r\ndouble GeneralHeat::ContinuousAnalyticSolution( double x, double t )\r\n{\r\n     return mppde->ContinuousAnalyticSolution( x, t );\r\n}\r\n\r\nvoid GeneralHeat::StationaryHeatEquation()\r\n{\r\nbuildfvec( mpsmesh );\r\n\r\nstiff.SetParameters(k_0, k_L, mpa);\r\n\r\nstiff.BuildGeneralStiffnessMatrix ( mpsmesh );\r\n\r\nBuiltbrVec();\r\nAddVectors(br, f_vec, br);\r\n\r\nstiff.MatrixSolver( br, mpx );\r\n}\r\n\r\nvoid GeneralHeat::buildfvec( SpaceMesh& a_smesh)\r\n{\r\n    double my_var = 0.5*a_smesh.ReadSpaceMesh(0);\r\n    f_vec = {mppde->EllipticalRHSfunction(0)*my_var};\r\n\r\nfor(int i =1; i<mpsmesh.meshsize(); i++)\r\n{\r\n    my_var = 0.5*(a_smesh.ReadSpaceMesh(i)+a_smesh.ReadSpaceMesh(i-1));\r\n    f_vec.push_back( mppde->EllipticalRHSfunction(a_smesh.ReadSpaceNode(i))*my_var );\r\n}\r\n\r\nmy_var = 0.5*mpsmesh.ReadSpaceMesh(mpsmesh.meshsize()-1);\r\nf_vec.push_back( mppde->EllipticalRHSfunction(a_smesh.ReadSpaceNode(a_smesh.meshsize()))*my_var );\r\n}\r\n\r\nvoid GeneralHeat::BuiltbrVec()\r\n{\r\n    br.assign(mpsmesh.meshsize()+1, 0);\r\n    br.at(0) = k_0*g_0;\r\n    br.at(mpsmesh.meshsize()) = k_L*g_L;\r\n}\r\n\r\nvoid GeneralHeat::AnalyticSolutionVec( )\r\n{\r\n    mpAnalyticSolution.clear();\r\n     for (int i = 0; i<mpsmesh.meshsize()+1; i++)\r\n{\r\n    mpAnalyticSolution.push_back(ContinuousAnalyticSolution( mpsmesh.ReadSpaceNode(i),\r\n                                                                        mptmesh.ReadTimeStep(mpcurrenTimeStep)));\r\n}\r\n}\r\n\r\n\r\nvoid GeneralHeat::PrintSolution( )\r\n{\r\n        BuildGradientVec(mpx, mpsmesh, FEMGradient);\r\n        GradientRecoveryFunction( mpsmesh, FEMGradient, GradientRecovery );\r\n        BuildErrorEstimate();\r\n        BuildErrorMesh();\r\n        AnalyticSolutionVec();\r\n//        AnalyticGradientVec();\r\n        EnergyNorm();\r\n        double globalError=0;\r\n        for(auto k: ErrorEstimate)\r\n            globalError = globalError + k;\r\n\r\n        std::cout << \"FEM Approximation:     \";\r\n        PrintVector(mpx);\r\n        std::cout << \"Analytic Solution:     \";\r\n        PrintVector(mpAnalyticSolution);\r\n        std::cout << \"Error Mesh:            \";\r\n        PrintVector(mpErrorMesh);\r\n        std::cout << \"Global Error           \";\r\n        GlobalSpaceError();\r\n        std::cout << \"FEM Grad approx:       \";\r\n        PrintVector(FEMGradient);\r\n        std::cout << \"ErrorEstimate:         \";\r\n        PrintVector(ErrorEstimate);\r\n        std::cout << \"GlobalErrorEstimate:   \";\r\n        std::cout << sqrt(globalError)<<\" \\n\";\r\n        std::cout << \"EnergyError:           \";\r\n        PrintVector(mpEnergyNorm);\r\n        std::cout << \"Global Energy Error    \";\r\n        GlobalEnergyError();\r\n        std::cout << \"\\n\";\r\n}\r\n\r\nvoid GeneralHeat::BuildErrorMesh()\r\n{\r\nmpErrorMesh.clear();\r\n\r\nauto SquaredError = [this](double x)\r\n    { return pow(GeneralInterpolant(x, mpx, mpsmesh ) -\r\n    ContinuousAnalyticSolution(x, mptmesh.ReadTimeStep(mpcurrenTimeStep)), 2); };\r\n\r\ndouble Q;\r\nfor(int i=0; i<mpsmesh.meshsize(); i++)\r\n{\r\nQ = gauss<double, 7>::integrate(SquaredError, mpsmesh.ReadSpaceNode(i), mpsmesh.ReadSpaceNode(i+1));\r\nmpErrorMesh.push_back( Q );\r\n}\r\n}\r\n\r\ndouble GeneralHeat::GlobalSpaceError()\r\n{\r\n    BuildErrorMesh();\r\n    double globalError=0;\r\n    for(auto k: mpErrorMesh)\r\n        globalError = globalError + k;\r\n\r\n    std::cout << sqrt(globalError);\r\n    std::cout << \" \\n\";\r\n    return sqrt(globalError);\r\n}\r\n\r\ndouble GeneralHeat::GlobalEnergyError()\r\n{\r\n    EnergyNorm();\r\n    double globalError=0;\r\n    for(auto k: mpEnergyNorm)\r\n        globalError = globalError + k;\r\n\r\n    std::cout << sqrt(globalError);\r\n    std::cout << \" \\n\";\r\n    return sqrt(globalError);\r\n\r\n}\r\n\r\nvoid GeneralHeat::PrintErrorMesh()\r\n{\r\n    BuildErrorMesh();\r\n    PrintVector(mpErrorMesh);\r\n}\r\n\r\n\r\nvoid GeneralHeat::SolveWithBCs()\r\n{\r\nmpcurrenTimeStep = 0;\r\nmpcurrentMeshIndex = 0;\r\n//AnalyticSolutionVec();\r\n//mpPreviousSolution = mpAnalyticSolution;\r\nmppde->InitialCondition(mpsmesh, mpPreviousSolution);\r\nstiff.SetParameters(k_0, k_L, mpa);\r\n\r\nofstream myfile;\r\nofstream myfile1;\r\nmyfile.open (\"solution.csv\");\r\nmyfile1.open (\"X.csv\");\r\nfor (auto k: mpPreviousSolution)\r\n    myfile << k << \", \";\r\nmyfile << \"\\n\";\r\nfor (auto k: mpsmesh.mpSpaceNodes)\r\n    myfile1 << k << \", \";\r\nmyfile1 << \"\\n\";\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\nmass.MatrixVectorMultiplier( mpPreviousSolution, mpRHS );\r\n\r\ng_0 = mppde->FirstBoundary(mptmesh.ReadTimeStep(mpcurrenTimeStep));\r\ng_L =mppde->SecondBoundary(mptmesh.ReadTimeStep(mpcurrenTimeStep));\r\n\r\nBuiltbrVec();\r\nVectorTimesScalar( br, mptmesh.ReadTimeMesh(mpcurrentMeshIndex) );\r\nAddVectors( br, mpRHS, mpRHS );\r\nLHS.MatrixSolver( mpRHS, mpx );\r\n\r\nfor (auto k: mpx)\r\n    myfile << k << \", \";\r\nmyfile << \"\\n\";\r\nfor (auto k: mpsmesh.mpSpaceNodes)\r\n    myfile1 << k << \", \";\r\nmyfile1 << \"\\n\";\r\n\r\nmpPreviousSolution = mpx;\r\n\r\n\r\nif (j==int(0.5*m))\r\n{\r\n}\r\n}\r\nmyfile.close();\r\nmyfile1.close();\r\n\r\n}\r\n\r\ndouble GeneralHeat::GeneralInterpolant( double x, std::vector<double>& funct, SpaceMesh& relevantMesh )\r\n{\r\n    std::array<double, 2> firstpoint;\r\n    std::array<double, 2> secondpoint;\r\n\r\n    int upperindex = relevantMesh.IndexAbove( x );\r\n\r\n    if((upperindex==1)||(upperindex==0))\r\n    {\r\n    firstpoint.at(0)= relevantMesh.ReadSpaceNode(0);\r\n    firstpoint.at(1) = funct.at(0);\r\n\r\n    secondpoint[0] = relevantMesh.ReadSpaceNode(1);\r\n    secondpoint.at(1) = funct.at(1);\r\n    }\r\n    else if (upperindex == relevantMesh.meshsize())\r\n    {\r\n    firstpoint.at(0)= relevantMesh.ReadSpaceNode(upperindex-1);\r\n    firstpoint.at(1) = funct.at(upperindex-1);\r\n\r\n    secondpoint[0] = relevantMesh.ReadSpaceNode(upperindex);\r\n    secondpoint.at(1) = funct.at(upperindex);\r\n    }\r\n    else\r\n    {\r\n    firstpoint.at(0)= relevantMesh.ReadSpaceNode(upperindex-1);\r\n    firstpoint.at(1) = funct.at(upperindex-1);\r\n\r\n    secondpoint[0] = relevantMesh.ReadSpaceNode(upperindex);\r\n    secondpoint.at(1) = funct.at(upperindex);\r\n    }\r\n\r\n    long double m = (firstpoint[1]-secondpoint[1])/(firstpoint[0]-secondpoint[0]);\r\n\r\n    return m*(x - firstpoint[0])+firstpoint[1];\r\n}\r\n\r\nvoid GeneralHeat::BuildGradientVec( std::vector<double>& funct, SpaceMesh& relevantMesh, std::vector<double>& gradvec )\r\n{\r\n    gradvec.clear();\r\n    std::array<double, 2> firstpoint;\r\n    std::array<double, 2> secondpoint;\r\n    long double m;\r\n\r\n    for(int i = 0; i<relevantMesh.meshsize(); i++)\r\n    {\r\n    firstpoint.at(0)= relevantMesh.ReadSpaceNode(i);\r\n    firstpoint.at(1) = funct.at(i);\r\n\r\n    secondpoint[0] = relevantMesh.ReadSpaceNode(i+1);\r\n    secondpoint.at(1) = funct.at(i+1);\r\n\r\n    m = (firstpoint[1]-secondpoint[1])/(firstpoint[0]-secondpoint[0]);\r\n\r\n    gradvec.push_back(m);\r\n    }\r\n}\r\n\r\nvoid GeneralHeat::GradientRecoveryFunction( SpaceMesh& relevantMesh,\r\n                                             std::vector<double>& gradvec, std::vector<double>& gradrecovery )\r\n{\r\n    gradrecovery.clear();\r\n\r\n    double x_0 = 0.5*(relevantMesh.ReadSpaceNode(1)+relevantMesh.ReadSpaceNode(0));\r\n    double y_0 = gradvec.at(0);\r\n    double x_1 = relevantMesh.ReadSpaceNode(1);\r\n    double y_1 = 0.5*(gradvec.at(1)+gradvec.at(0));\r\n\r\n    gradrecovery.push_back(y_0+(relevantMesh.ReadSpaceNode(0)-x_0)*(y_1-y_0)/(x_1-x_0));\r\n\r\n    for(int i = 0; i<relevantMesh.meshsize()-1; i++)\r\n    {\r\n        gradrecovery.push_back(0.5*(gradvec.at(i)+gradvec.at(i+1)));\r\n    }\r\n\r\n    x_0 = relevantMesh.ReadSpaceNode(mpsmesh.meshsize()-1);\r\n    y_0 = gradrecovery.back();\r\n    x_1 = 0.5*(relevantMesh.ReadSpaceNode(relevantMesh.meshsize())+relevantMesh.ReadSpaceNode(relevantMesh.meshsize()-1));\r\n    y_1 = gradvec.back();\r\n\r\n    gradrecovery.push_back(y_0+(mpsmesh.ReadSpaceNode(mpsmesh.meshsize())-x_0)*(y_1-y_0)/(x_1-x_0));\r\n}\r\n\r\nvoid GeneralHeat::BuildErrorEstimate(  )\r\n{\r\n    ErrorEstimate.clear();\r\n\r\n    auto GradSquaredError = [this](double x)\r\n        { return pow(GeneralInterpolant(x, GradientRecovery, mpsmesh ) - GradientFunction(x), 2); };\r\n\r\n    double dummy_var;\r\n    for(int i=0; i<mpsmesh.meshsize(); i++)\r\n    {\r\n    ErrorEstimate.push_back( gauss<double, 7>::integrate(GradSquaredError, mpsmesh.ReadSpaceNode(i), mpsmesh.ReadSpaceNode(i+1)) );\r\n    }\r\n}\r\n\r\n\r\n    //discontinuous function which throws exceptions at undefined points\r\ndouble GeneralHeat::GradientFunction ( double x )\r\n{\r\n    int upperindex = mpsmesh.IndexAbove( x );\r\n    if (mpsmesh.Contained(x))\r\n    {\r\n        std::cout<< \"FEM gradient undefined at this point\"<<\"\\n\";\r\n        return 0;\r\n    }\r\n    else\r\n    {\r\n       return FEMGradient.at(upperindex-1);\r\n    }\r\n}\r\n\r\nvoid GeneralHeat::PrintVector( std::vector<double> aVector)\r\n{\r\n        for (auto k: aVector)\r\n        std::cout << k << \", \";\r\n        std::cout << \" \\n\";\r\n}\r\n\r\nvoid GeneralHeat::VectorTimesScalar( std::vector<double>& func1, double scalar)\r\n{\r\n         for ( int i=0; i<func1.size(); i++ )\r\n     {\r\n         func1.at(i)= scalar*func1.at(i);\r\n     }\r\n}\r\n\r\ndouble GeneralHeat::H_1Norm()\r\n{\r\n    EnergyNorm();\r\n    BuildErrorMesh();\r\n    double globalError=0;\r\n    for(int i=0;i<mpErrorMesh.size(); i++)\r\n    {\r\n        globalError =mpEnergyNorm.at(i)+mpErrorMesh.at(i)+globalError;\r\n    }\r\n\r\n    std::cout << sqrt(globalError);\r\n    std::cout << \" \\n\";\r\n    return sqrt(globalError);\r\n\r\n}\r\n\r\nvoid GeneralHeat::UnitTest1 ()\r\n{\r\n    BuildGradientVec(mpx, mpsmesh, FEMGradient);\r\n    GradientRecoveryFunction( mpsmesh, FEMGradient, GradientRecovery );\r\n    BuildErrorEstimate();\r\n\r\n    double globalError=0;\r\n    for(int i=0;i<ErrorEstimate.size(); i++)\r\n    {\r\n        globalError =ErrorEstimate.at(i)+globalError;\r\n    }\r\n    std::cout << \"Error estimate:           \";\r\n    std::cout << sqrt(globalError)<<\"\\n\";\r\n\r\n    EnergyNorm();\r\n    std::cout << \"Global Energy Error       \";\r\n    GlobalEnergyError();\r\n    std::cout << \"\\n\";\r\n\r\n    //PrintVector(ErrorEstimate);\r\n}\r\n", "meta": {"hexsha": "f768102c6e878198a34669e910a726548a8ca068", "size": 11780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver class generalised for all boundary conditions/GeneralizedHeat.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 generalised for all boundary conditions/GeneralizedHeat.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 generalised for all boundary conditions/GeneralizedHeat.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": 27.5878220141, "max_line_length": 132, "alphanum_fraction": 0.624278438, "num_tokens": 3256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.5560989773198263}}
{"text": "/*\n * cwise_binary.hpp\n *\n *  Created on: Apr 11, 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\ntemplate<typename ScalarMajor, typename ScalarMinor>\nEigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\nscale(const Eigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container, ScalarMinor factor);\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\nEigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>\nscale(const Eigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>& container, ScalarMinor factor);\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\nEigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_product(\n\t\tconst Eigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Matrix<ScalarMinor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_b);\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\nEigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>\ncwise_product(\n\t\tconst Eigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Tensor<ScalarMinor, 3, Eigen::ColMajor>& container_b);\n\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_add_constant(const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container, Scalar constant);\n\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor>\ncwise_add_constant(const Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& container, Scalar constant);\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\ninline\nEigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_add(\n\t\tconst Eigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Matrix<ScalarMinor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_b){\n\treturn (container_a.array() + container_b.array()).matrix();\n}\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\ninline\nEigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>\ncwise_add(\n\t\tconst Eigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Tensor<ScalarMinor, 3, Eigen::ColMajor>& container_b){\n\treturn container_a + container_b;\n}\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\ninline\nEigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>\ncwise_subtract(\n\t\tconst Eigen::Matrix<ScalarMajor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Matrix<ScalarMinor, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& container_b){\n\treturn (container_a.array() - container_b.array()).matrix();\n}\n\ntemplate<typename ScalarMajor, typename ScalarMinor>\ninline\nEigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>\ncwise_subtract(\n\t\tconst Eigen::Tensor<ScalarMajor, 3, Eigen::ColMajor>& container_a,\n\t\tconst Eigen::Tensor<ScalarMinor, 3, Eigen::ColMajor>& container_b){\n\treturn container_a - container_b;\n}\n\n}  // namespace math\n\n\n", "meta": {"hexsha": "f67b5d6b7ef06053b6ff652a06cb8e3a17ebd21c", "size": 3683, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/cwise_binary.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/cwise_binary.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/cwise_binary.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": 38.3645833333, "max_line_length": 125, "alphanum_fraction": 0.7643225631, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.5560801815040454}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <Eigen/Dense>\n#include \"../../common/kernel.hpp\"\n#include \"../../common/unary.hpp\"\n\nextern \"C\"\n{\n  static void add_bias(float *c, float *y, int m, int n) {\n    for (int row = 0; row < m; row++)\n    {\n      for (int col = 0; col < n; col++)\n      {\n        y[row * n + col] += c[col];\n      }\n    }\n  }\n\n  static void do_gemm_transa0_transb0(float *a, float *b, float *y, int m, int n, int k)\n  {\n    // 'const' float *a raises compile error\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > a_mat(a, m, k);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > b_mat(b, k, n);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > y_mat(y, m, n);\n\n    y_mat.noalias() = a_mat * b_mat;\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa0_transb0(float *a, float *b, float *y, int m, int n, int k)\n  {\n    do_gemm_transa0_transb0(a, b, y, m, n, k);\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa0_transb0_c(float *a, float *b, float *c, float *y, int m, int n, int k)\n  {\n    do_gemm_transa0_transb0(a, b, y, m, n, k);\n    add_bias(c, y, m, n);\n  }\n\n  static void do_gemm_transa0_transb1(float *a, float *b, float *y, int m, int n, int k)\n  {\n    // 'const' float *a raises compile error\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > a_mat(a, m, k);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> > b_mat(b, k, n);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > y_mat(y, m, n);\n\n    y_mat.noalias() = a_mat * b_mat;\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa0_transb1(float *a, float *b, float *y, int m, int n, int k)\n  {\n    do_gemm_transa0_transb1(a, b, y, m, n, k);\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa0_transb1_c(float *a, float *b, float *c, float *y, int m, int n, int k)\n  {\n    do_gemm_transa0_transb1(a, b, y, m, n, k);\n    add_bias(c, y, m, n);\n  }\n\n  \n  static void do_gemm_transa1_transb0(float *a, float *b, float *y, int m, int n, int k)\n  {\n    // 'const' float *a raises compile error\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> > a_mat(a, m, k);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > b_mat(b, k, n);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > y_mat(y, m, n);\n\n    y_mat.noalias() = a_mat * b_mat;\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa1_transb0(float *a, float *b, float *y, int m, int n, int k)\n  {\n    do_gemm_transa1_transb0(a, b, y, m, n, k);\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa1_transb0_c(float *a, float *b, float *c, float *y, int m, int n, int k)\n  {\n    do_gemm_transa1_transb0(a, b, y, m, n, k);\n    add_bias(c, y, m, n);\n  }\n\n  \n  static void do_gemm_transa1_transb1(float *a, float *b, float *y, int m, int n, int k)\n  {\n    // 'const' float *a raises compile error\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> > a_mat(a, m, k);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> > b_mat(b, k, n);\n    Eigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > y_mat(y, m, n);\n\n    y_mat.noalias() = a_mat * b_mat;\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa1_transb1(float *a, float *b, float *y, int m, int n, int k)\n  {\n    do_gemm_transa1_transb1(a, b, y, m, n, k);\n  }\n\n  void WEBDNN_KERNEL kernel_gemm_transa1_transb1_c(float *a, float *b, float *c, float *y, int m, int n, int k)\n  {\n    do_gemm_transa1_transb1(a, b, y, m, n, k);\n    add_bias(c, y, m, n);\n  }\n}\n", "meta": {"hexsha": "3f3842a03519157bb1d755b3a81e6f67aa151d15", "size": 3717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shader/wasm/src/kernels/standard/gemm.cpp", "max_stars_repo_name": "mil-tokyo/webdnn", "max_stars_repo_head_hexsha": "38a60fd3e1a4e72bc01108189a3aa51e0752aecd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1967.0, "max_stars_repo_stars_event_min_datetime": "2017-05-28T08:18:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:10:57.000Z", "max_issues_repo_path": "src/shader/wasm/src/kernels/standard/gemm.cpp", "max_issues_repo_name": "mil-tokyo/webdnn", "max_issues_repo_head_hexsha": "38a60fd3e1a4e72bc01108189a3aa51e0752aecd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 315.0, "max_issues_repo_issues_event_min_datetime": "2017-05-28T05:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-13T03:19:35.000Z", "max_forks_repo_path": "src/shader/wasm/src/kernels/standard/gemm.cpp", "max_forks_repo_name": "mil-tokyo/webdnn", "max_forks_repo_head_hexsha": "38a60fd3e1a4e72bc01108189a3aa51e0752aecd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 175.0, "max_forks_repo_forks_event_min_datetime": "2017-05-31T08:10:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-15T05:22:12.000Z", "avg_line_length": 35.4, "max_line_length": 111, "alphanum_fraction": 0.6368038741, "num_tokens": 1299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5560487825210274}}
{"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#include <functional>\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\n// New structure to store first ring neighbors of a vertex\nstruct vertex_first_ring{\n    size_t vertex_id;\n    std::vector< std::pair<unsigned,unsigned> > faces;\n    std::vector< unsigned > edges;\n};\n\nint main(){\n    clock_t t1;\n    t1 = clock();\n    for(auto i=0; i < 1; ++i){\n        // *************************** Triangulation *************************//\n        auto reader = vtkSmartPointer<vtkPolyDataReader>::New();\n        reader->SetFileName(\"T7.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        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()), done3(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 != done3);\n        }\n        poly->SetPolys(triangles);\n\n        // Write to VTK file\n        vtkNew<vtkPolyDataWriter> writer;\n        writer->SetFileName(\"CGALStereoMesh.vtk\");\n        writer->SetInputData(poly);\n        writer->Write();\n\n        // *************************** Our data structure *************************//\n        std::vector<vertex_first_ring> first_ring;\n        std::set<std::set<unsigned>> tri, edges;\n\n        // Iterate over all vertices and collect first ring neighbors\n        for(auto fvi = dt.all_vertices_begin(); fvi != dt.all_vertices_end(); ++fvi){\n\n            vertex_first_ring vfr;\n            std::vector<Delaunay::Vertex_handle> rvh;\n            auto vid = dt.is_infinite(fvi)? 0 : fvi->info();\n            vfr.vertex_id = vid;\n            Delaunay::Edge_circulator ec = dt.incident_edges(fvi), done(ec);\n\n            // Lambda function to get the vertex id for the edge\n            auto getVertexId = [](int a, int b){\n                std::set<int> index{0,1,2};\n                index.erase(a);\n                index.erase(b);\n                return *index.begin();\n            };\n\n            if( ec != 0){\n                do{\n\n                    auto fh = ec->first;\n                    auto edgeIndex = getVertexId(fh->index(fvi),ec->second);\n                    auto verH = fh->vertex(edgeIndex);\n                    auto edgeId = dt.is_infinite(verH)? 0 : verH->info();\n                    std::set<unsigned> edge{vid,edgeId};\n                    auto tryInsertEdge = edges.insert(edge);\n                    if(tryInsertEdge.second){\n                        vfr.edges.push_back(edgeId);\n                        rvh.push_back(verH);\n                    }\n\n                }while(++ec != done);\n            }\n\n            // Check which edges form a unique face\n            auto numEdges = rvh.size();\n            for( auto k = 0; k < numEdges; ++k){\n                auto next = (k+1) % numEdges;\n                // Check if face is formed\n                if(dt.is_face(fvi,rvh[k],rvh[next] )){\n                    // Check if face is unique\n                    std::set<unsigned> face{vid,vfr.edges[k],vfr.edges[next]};\n                    auto tryInsertFace = tri.insert(face);\n                    if(tryInsertFace.second)\n                        vfr.faces.push_back(std::make_pair(k,next));\n                }\n            }\n\n            first_ring.push_back(vfr);\n        }\n\n        //*************************** Print first ring ******************************//\n        auto edgeNum = 0;\n        auto faceNum = 0;\n        for( const auto & vfr : first_ring){\n            std::cout<<\" Center Point = \" << vfr.vertex_id << std::endl;\n            std::cout<<\"\\t Faces = \"<< std::endl;\n            for(const auto & face : vfr.faces){\n                std::cout<<\"\\t\\t\"<< face.first << \" \" << face.second << std::endl;\n                faceNum++;\n            }\n            std::cout<<\"\\t Edges = \"<< std::endl;\n            for(const auto & edge : vfr.edges){\n                std::cout<<\"\\t\\t\"<< edge << std::endl;\n                edgeNum++;\n            }\n        }\n        std::cout<< \"Number of faces = \" << faceNum << std::endl;\n        std::cout<< \"Number of edges = \" << edgeNum << std::endl;\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": "4d8796fb0bee74b2b71fc6a64455591e9d4ec8b9", "size": 7339, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "CPP/cgalData.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/cgalData.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/cgalData.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": 38.2239583333, "max_line_length": 87, "alphanum_fraction": 0.5282736068, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5560487772169438}}
{"text": "#include <vector>\n#include \"..\\include\\myfluidBox.h\"\n#include <Eigen/Dense>\n\nusing namespace std;\n\nnamespace particleSystem{\n\tunsigned int myFluidBox::ID_gen = 0;\n\n\tmyFluidBox::myFluidBox() :ID(++ID_gen) {}//std::cout<<\"building fluid box ID : \"<<ID<<std::endl;\t}\n\tmyFluidBox::myFluidBox(int _numCellX, int _numCellY, int _numCellZ, double _diffusion, double _viscosity, double _deltaT, int _sviters, const Eigen::Ref<const Eigen::Vector3d>& _cellSz) :\n\t\tID(++ID_gen), numCellX(_numCellX), numCellY(_numCellY), numCellZ(_numCellZ), diff(_diffusion), visc(_viscosity), slvIters(_sviters), startLoc(0, 0, 0), sphereBnds(), ctrSzHalfNC(0, 0, 0), //sphereExtBnds(), \t\t\t\t//precalculated (center - sz*halfNumCell)/sz for force query for particles\n\t\tdeltaT(_deltaT), center(0, 0, 0), numCellXY(numCellX * numCellY), numCells(numCellX * numCellY * numCellZ), cellSz(_cellSz), isMesh(false), radSq(0) {\n\n\t\tvortEps = deltaT * .01;\t\t\t//TODO allow for UI input\n\t\tinitVecs();\n\n\t\thalfNmCellX = (numCellX / 2);\n\t\thalfNmCellY = (numCellY / 2);\n\t\thalfNmCellZ = (numCellZ / 2);\n\n\t\t//corresponds to x,y,z idx of \"internal\" array (inside single cube boundary layer\n\t\tsx1i = numCellX - 1;\n\t\tsy1i = numCellY - 1;\n\t\tsz1i = numCellZ - 1;\n\t\t//corresponds to x,y,z size of internal cube array of nodes used for sim\n\t\tsx2i = numCellX - 2;\n\t\tsy2i = numCellY - 2;\n\t\tsz2i = numCellZ - 2;\n\t\thO2Sxd = 1.0 / (2.0* sx2i); hO2Syd = 1.0 / (2.0* sy2i); hO2Szd = 1.0 / (2.0* sz2i);\n\t\thSxd = 0.5f* sx2i; hSyd = 0.5f* sy2i; hSzd = 0.5f* sz2i;\n\t\tmemSetNumElems = sizeof(Vx0[0]) * numCells;\n\t\t//location to start rendering\n\t\tsetStartLoc();\n\t}\n\n\tmyFluidBox::~myFluidBox() {\n\t\tdelete[] oldDensity;\n\t\tdelete[] density;\n\t\tdelete[] isOOB;\n\t\tdelete[] Vx;\n\t\tdelete[] Vy;\n\t\tdelete[] Vz;\n\t\tdelete[] Vx0;\n\t\tdelete[] Vy0;\n\t\tdelete[] Vz0;\n\t}\n\tvoid myFluidBox::set_bndCube(int b, double* x) {\n\t\t//int N = size;//for reading ease\n\t\t//int sz1 = numCellZ - 1, sz2 = numCellZ - 2,\n\t\t//\tsx1 = numCellX - 1, sx2 = numCellX - 2,\n\t\t//\tsy1 = sy1i, sy2 = numCellY - 2;\n\t\tif (b == 0) {//diffusion\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, j, 0)] = x[IX(i, j, 1)]; x[IX(i, j, sz1i)] = x[IX(i, j, sz2i)];}}\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, 0, k)] = x[IX(i, 1, k)]; x[IX(i, sy1i, k)] = x[IX(i, sy2i, k)];}}\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int j = 1; j < sy1i; ++j) {\tx[IX(0, j, k)] = x[IX(1, j, k)]; x[IX(sx1i, j, k)] = x[IX(sx2i, j, k)];}}\n\t\t}\n\t\telse if (b == 1) {//reflecting in x\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, j, 0)] = x[IX(i, j, 1)];  x[IX(i, j, sz1i)] = x[IX(i, j, sz2i)]; } }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, 0, k)] = x[IX(i, 1, k)];  x[IX(i, sy1i, k)] = x[IX(i, sy2i, k)]; } }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int j = 1; j < sy1i; ++j) {\tx[IX(0, j, k)] = -x[IX(1, j, k)]; x[IX(sx1i, j, k)] = -x[IX(sx2i, j, k)];} }\n\t\t}\n\t\telse if (b == 2) {//reflecting in y\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, j, 0)] = x[IX(i, j, 1)]; x[IX(i, j, sz1i)] = x[IX(i, j, sz2i)]; } }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, 0, k)] = -x[IX(i, 1, k)];x[IX(i, sy1i, k)] = -x[IX(i, sy2i, k)];} }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int j = 1; j < sy1i; ++j) {\tx[IX(0, j, k)] = x[IX(1, j, k)]; x[IX(sx1i, j, k)] = x[IX(sx2i, j, k)]; } }\n\t\t}\n\t\telse if (b == 3) {//refelecting in z\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, j, 0)] = -x[IX(i, j, 1)]; x[IX(i, j, sz1i)] = -x[IX(i, j, sz2i)]; } }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int i = 1; i < sx1i; ++i) {\tx[IX(i, 0, k)] = x[IX(i, 1, k)];  x[IX(i, sy1i, k)] = x[IX(i, sy2i, k)]; } }\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {for (unsigned int j = 1; j < sy1i; ++j) {\tx[IX(0, j, k)] = x[IX(1, j, k)];  x[IX(sx1i, j, k)] = x[IX(sx2i, j, k)]; } }\n\t\t}\n\n\t\t// edges\n\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\tx[IX(i, 0, 0)] = 0.5f * (x[IX(i, 1, 0)] + x[IX(i, 0, 1)]);\n\t\t\tx[IX(i, sy1i, 0)] = 0.5f * (x[IX(i, sy2i, 0)] + x[IX(i, sy1i, 1)]);\n\t\t\tx[IX(i, 0, sz1i)] = 0.5f * (x[IX(i, 1, sz1i)] + x[IX(i, 0, sz2i)]);\n\t\t\tx[IX(i, sy1i, sz1i)] = 0.5f * (x[IX(i, sy2i, sz1i)] + x[IX(i, sy1i, sz2i)]);\n\t\t}\n\n\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\tx[IX(0, j, 0)] = 0.5f * (x[IX(1, j, 0)] + x[IX(0, j, 1)]);\n\t\t\tx[IX(sx1i, j, 0)] = 0.5f * (x[IX(sx2i, j, 0)] + x[IX(sx1i, j, 1)]);\n\t\t\tx[IX(0, j, sz1i)] = 0.5f * (x[IX(1, j, sz1i)] + x[IX(0, j, sz2i)]);\n\t\t\tx[IX(sx1i, j, sz1i)] = 0.5f * (x[IX(sx2i, j, sz1i)] + x[IX(sx1i, j, sz2i)]);\n\t\t}\n\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tx[IX(0, 0, k)] = 0.5f * (x[IX(0, 1, k)] + x[IX(1, 0, k)]);\n\t\t\tx[IX(0, sy1i, k)] = 0.5f * (x[IX(0, sy2i, k)] + x[IX(1, sy1i, k)]);\n\t\t\tx[IX(sx1i, 0, k)] = 0.5f * (x[IX(sx1i, 1, k)] + x[IX(sx2i, 0, k)]);\n\t\t\tx[IX(sx1i, sy1i, k)] = 0.5f * (x[IX(sx1i, sy2i, k)] + x[IX(sx2i, sy1i, k)]);\n\t\t}\n\n\t\t// corners\n\t\tdouble calcVal = (1 / 3.0);\n\t\tx[IX(0, 0, 0)] = calcVal*(x[IX(0, 1, 0)] + x[IX(1, 0, 0)] + x[IX(0, 0, 1)]);\n\t\tx[IX(sx1i, 0, 0)] = calcVal*(x[IX(sx2i, 0, 0)] + x[IX(sx1i, 1, 0)] + x[IX(sx1i, 0, 1)]);\n\t\tx[IX(0, sy1i, 0)] = calcVal*(x[IX(0, sy2i, 0)] + x[IX(1, sy1i, 0)] + x[IX(0, sy1i, 1)]);\n\t\tx[IX(sx1i, sy1i, 0)] = calcVal*(x[IX(sx1i, sy2i, 0)] + x[IX(sx2i, sy1i, 0)] + x[IX(sx1i, sy1i, 1)]);\n\n\t\tx[IX(0, 0, sz1i)] = calcVal*(x[IX(0, 1, sz1i)] + x[IX(1, 0, sz1i)] + x[IX(0, 0, sz2i)]);\n\t\tx[IX(sx1i, 0, sz1i)] = calcVal*(x[IX(sx2i, 0, sz1i)] + x[IX(sx1i, 1, sz1i)] + x[IX(sx1i, 0, sz2i)]);\n\t\tx[IX(0, sy1i, sz1i)] = calcVal*(x[IX(0, sy2i, sz1i)] + x[IX(1, sy1i, sz1i)] + x[IX(0, sy1i, sz2i)]);\n\t\tx[IX(sx1i, sy1i, sz1i)] = calcVal*(x[IX(sx1i, sy2i, sz1i)] + x[IX(sx2i, sy1i, sz1i)] + x[IX(sx1i, sy1i, sz2i)]);\n\t}\n\n\n\t//handle advection for passed arrays of velocities\n\tvoid myFluidBox::advect(int b, double* d, double* d0, double* velocX, double* velocY, double* velocZ) {\n\t\tdouble s0, s1, t0, t1, u0, u1;\n\t\t//double tmp1, tmp2, tmp3;\n\t\tdouble x, y, z;\n\n\t\t//double idouble = 1, jdouble = 1, kdouble = 1;\n\t\tint i0, i1, j0, j1, k0, k1;\n\n\t\tdouble dtx = deltaT * (sx2i),\n\t\t\tdty = deltaT * (sy2i),\n\t\t\tdtz = deltaT * (sz2i);\n\n\t\tint IXidx;\n\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tIXidx = IX(i, j, k);\n\n\t\t\t\t\tx = i - dtx * velocX[IXidx];\n\t\t\t\t\ty = j - dty * velocY[IXidx];\n\t\t\t\t\tz = k - dtz * velocZ[IXidx];\n\t\t\t\t\tx = forceIDXBndD(x, sx1i + 0.5, .5);\n\t\t\t\t\ti0 = floor(x);\ti1 = i0 + 1.0;  s1 = x - i0;\ts0 = 1.0 - s1;\n\t\t\t\t\ty = forceIDXBndD(y, sy1i + 0.5, .5);\n\t\t\t\t\tj0 = floor(y);\tj1 = j0 + 1.0;\tt1 = y - j0;\tt0 = 1.0 - t1;\n\t\t\t\t\tz = forceIDXBndD(z, sz1i + 0.5, .5);\n\t\t\t\t\tk0 = floor(z);\tk1 = k0 + 1.0;\tu1 = z - k0;\tu0 = 1.0 - u1;\n\n\t\t\t\t\td[IXidx] =\n\t\t\t\t\t\ts0 * (t0 * (u0 * d0[IX(i0, j0, k0)]\n\t\t\t\t\t\t+ u1 * d0[IX(i0, j0, k1)])\n\t\t\t\t\t\t+ (t1 * (u0 * d0[IX(i0, j1, k0)]\n\t\t\t\t\t\t+ u1 * d0[IX(i0, j1, k1)])))\n\t\t\t\t\t\t+ s1 * (t0 * (u0 * d0[IX(i1, j0, k0)]\n\t\t\t\t\t\t+ u1 * d0[IX(i1, j0, k1)])\n\t\t\t\t\t\t+ (t1 * (u0 * d0[IX(i1, j1, k0)]\n\t\t\t\t\t\t+ u1 * d0[IX(i1, j1, k1)])));\n\t\t\t\t}//for i\n\t\t\t}//for j\n\t\t}//for k\n\t\tset_bndCube(b, d);\n\t}\n\n\tvoid myFluidBox::project(double* velocX, double* velocY, double* velocZ, double* p, double* div) {\n\t\t//double sx2 = sx2i, sy2 = numCellY - 2, sz2 = numCellZ - 2;\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tdiv[IX(i, j, k)] = -(\n\t\t\t\t\t\t  (velocX[IX(i + 1, j, k)] - velocX[IX(i - 1, j, k)])*hO2Sxd\n\t\t\t\t\t\t+ (velocY[IX(i, j + 1, k)] - velocY[IX(i, j - 1, k)])*hO2Syd\n\t\t\t\t\t\t+ (velocZ[IX(i, j, k + 1)] - velocZ[IX(i, j, k - 1)])*hO2Szd\n\t\t\t\t\t\t);               \n\t\t\t\t\tp[IX(i, j, k)] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndCube(0, div);\n\t\t//set_bnd(0, p);\n\t\tlin_solve(0, p, div, 1, 6);\n\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tvelocX[IX(i, j, k)] -= hSxd *(p[IX(i + 1, j, k)] - p[IX(i - 1, j, k)]);\n\t\t\t\t\tvelocY[IX(i, j, k)] -= hSyd *(p[IX(i, j + 1, k)] - p[IX(i, j - 1, k)]);\n\t\t\t\t\tvelocZ[IX(i, j, k)] -= hSzd *(p[IX(i, j, k + 1)] - p[IX(i, j, k - 1)]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndCube(1, velocX);\n\t\tset_bndCube(2, velocY);\n\t\tset_bndCube(3, velocZ);\n\t}\n\n\t//void myFluidBox::diffuse(int b, double* x, double* xOld, double viscdiff, int _numCells) {\n\t//\tdouble delVisc = (deltaT*viscdiff*(numCells));\n\t//\tlin_solve(b, x, xOld, delVisc, 1 + 6 * delVisc);\n\t//}\n\n\tvoid myFluidBox::myFluidBoxTimeStep() {\n\t\taddSource(Vx, Vx0);\n\t\taddSource(Vy, Vy0);\n\t\taddSource(Vz, Vz0);\n\t\taddSource(density, oldDensity);\n\t\t//if (isMesh) { myFluidSphereTimeStep(); return; }\n\n\t\tstd::swap(Vx, Vx0); std::swap(Vy, Vy0); std::swap(Vz, Vz0);\n\n\t\tdiffuse(1, Vx, Vx0, visc, numCellX);\n\t\tdiffuse(2, Vy, Vy0, visc, numCellY);\n\t\tdiffuse(3, Vz, Vz0, visc, numCellZ);\n\n\t\tproject(Vx, Vy, Vz, Vx0, Vy0);\n\n\t\tstd::swap(Vx, Vx0); std::swap(Vy, Vy0); std::swap(Vz, Vz0);\n\n\t\tadvect(1, Vx, Vx0, Vx0, Vy0, Vz0);\n\t\tadvect(2, Vy, Vy0, Vx0, Vy0, Vz0);\n\t\tadvect(3, Vz, Vz0, Vx0, Vy0, Vz0);\n\n\t\tproject(Vx, Vy, Vz, Vx0, Vy0);\n\n\t\tstd::swap(density, oldDensity);\n\t\tdiffuse(0, density, oldDensity, diff, numCellX);\n\t\tstd::swap(density, oldDensity);\n\t\tadvect(0, density, oldDensity, Vx0, Vy0, Vz0);\n\t\tresetOldVals();\n\t}//myFluidBoxTimeStep\n\n\t/////////////sphere stuff\n\n\t //timestepping for sphere, to handle 3d bounds together instead of 1 dim at a time\n\tvoid myFluidBox::myFluidSphereTimeStep() {\n\t\t//addSource(Vx, Vx0);\n\t\t//addSource(Vy, Vy0);\n\t\t//addSource(Vz, Vz0);\n\t\t//addSource(density, oldDensity);\n\n\t\tstd::swap(Vx, Vx0); std::swap(Vy, Vy0); std::swap(Vz, Vz0);\n\t\tdouble delVisc = (deltaT*visc*numCells);\n\t\t//diffusion of velocity\n\t\tlin_solveSphere(Vx, Vx0, Vy, Vy0, Vz, Vz0, delVisc, 1 + 6 * delVisc);\n\n\t\tprojectSphere(Vx, Vy, Vz, Vx0, Vy0);\n\n\t\tstd::swap(Vx, Vx0); std::swap(Vy, Vy0); std::swap(Vz, Vz0);\n\t\tadvectSphere(Vx, Vx0, Vy, Vy0, Vz, Vz0);\n\n\t\tprojectSphere(Vx, Vy, Vz, Vx0, Vy0);\n\n\t\tstd::swap(density, oldDensity);\n\t\tdiffSphDens(density, oldDensity, diff);\n\t\tstd::swap(density, oldDensity);\n\t\tadvSphDens(density, oldDensity, Vx, Vy, Vz);\n\t\t//vort confine here\n\t\tvorticityConfinement(oldDensity);\n\t\t//vorticity particle method\n\t\t//vorticityParticles();\n\n\t\tresetOldVals();\n\t}//myFluidSphereTimeStep\n\n\n\t//handle advection for passed arrays of velocities\n\tvoid myFluidBox::advectSphere(double* _velx, double* _velx0, double* _vely, double* _vely0, double* _velz, double* _velz0) {\n\t\tdouble s0, s1, t0, t1, u0, u1,x, y, z;\n\n\t\tint i0, i1, j0, j1, k0, k1;\n\t\t//precalced idx's\n\t\tint idx0, idx1, idx2, idx3, idx4, idx5, idx6, idx7;\n\n\t\tdouble dtx = deltaT * (sx2i),\n\t\t\tdty = deltaT * (sy2i),\n\t\t\tdtz = deltaT * (sz2i);\n\t\tint IXidx;\n\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tIXidx = IX(i, j, k);\n\t\t\t\t\tif (isOOB[IXidx]) { continue; }\n\n\t\t\t\t\tx = i - dtx * _velx0[IXidx];\n\t\t\t\t\tx = forceIDXBndD(x, sx2i + 0.5, .5);\n\t\t\t\t\ti0 = floor(x);\ti1 = i0 + 1.0;  s1 = x - i0;\ts0 = 1.0 - s1;\n\n\t\t\t\t\ty = j - dty * _vely0[IXidx];\n\t\t\t\t\ty = forceIDXBndD(y, sy2i + 0.5, .5);\n\t\t\t\t\tj0 = floor(y);\tj1 = j0 + 1.0;\tt1 = y - j0;\tt0 = 1.0 - t1;\n\n\t\t\t\t\tz = k - dtz * _velz0[IXidx];\n\t\t\t\t\tz = forceIDXBndD(z, sz2i + 0.5, .5);\n\t\t\t\t\tk0 = floor(z);\tk1 = k0 + 1.0;\tu1 = z - k0;\tu0 = 1.0 - u1;\n\n\t\t\t\t\tidx0 = IX(i0, j0, k0);idx1 = IX(i0, j0, k1);idx2 = IX(i0, j1, k0);idx3 = IX(i0, j1, k1);\n\t\t\t\t\tidx4 = IX(i1, j0, k0);idx5 = IX(i1, j0, k1);idx6 = IX(i1, j1, k0);idx7 = IX(i1, j1, k1);\n\n\t\t\t\t\t_velx[IXidx] =\t\n\t\t\t\t\t\ts0 * (t0 * (u0 * _velx0[idx0] + u1 * _velx0[idx1]) + (t1 * (u0 * _velx0[idx2] + u1 * _velx0[idx3]))) +\n\t\t\t\t\t\ts1 * (t0 * (u0 * _velx0[idx4] + u1 * _velx0[idx5]) + (t1 * (u0 * _velx0[idx6] + u1 * _velx0[idx7])));\n\n\t\t\t\t\t_vely[IXidx] =\n\t\t\t\t\t\ts0 * (t0 * (u0 * _vely0[idx0] + u1 * _vely0[idx1]) + (t1 * (u0 * _vely0[idx2] + u1 * _vely0[idx3]))) +\n\t\t\t\t\t\ts1 * (t0 * (u0 * _vely0[idx4] + u1 * _vely0[idx5]) + (t1 * (u0 * _vely0[idx6] + u1 * _vely0[idx7])));\n\n\t\t\t\t\t_velz[IXidx] =\n\t\t\t\t\t\ts0 * (t0 * (u0 * _velz0[idx0] + u1 * _velz0[idx1]) + (t1 * (u0 * _velz0[idx2] + u1 * _velz0[idx3]))) +\n\t\t\t\t\t\ts1 * (t0 * (u0 * _velz0[idx4] + u1 * _velz0[idx5]) + (t1 * (u0 * _velz0[idx6] + u1 * _velz0[idx7])));\n\t\t\t\t}//for i\n\t\t\t}//for j\n\t\t}//for k\n\t\tset_bndSphere3(_velx, _vely, _velz);\n\t}//advectSphere\n\n\t//diffuse density - 1 d but use sphere bnds\n\tvoid myFluidBox::diffSphDens(double* x, double* x0, double viscdiff) {\n\t\tdouble a = (deltaT*viscdiff*(numCells)), c = (1 + 6 * a);\n\t\tint idx;\n\t\tif(a==0){\n\t\t\tstd::memcpy(&x, &x0, sizeof x0);\n\t\t\tset_bndDiffSphere(x);\n\t\t} else {\n\t\t\tfor (unsigned int itr = 0; itr < slvIters; ++itr) {\n\t\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\t\t\tif (isOOB[idx]) { continue; }\n\t\t\t\t\t\t\tx[idx] = (x0[idx] + a *\n\t\t\t\t\t\t\t\t(x[IX(i + 1, j, k)]\n\t\t\t\t\t\t\t\t\t+ x[IX(i - 1, j, k)]\n\t\t\t\t\t\t\t\t\t+ x[IX(i, j + 1, k)]\n\t\t\t\t\t\t\t\t\t+ x[IX(i, j - 1, k)]\n\t\t\t\t\t\t\t\t\t+ x[IX(i, j, k + 1)]\n\t\t\t\t\t\t\t\t\t+ x[IX(i, j, k - 1)])) / c;\n\t\t\t\t\t\t}//for i\n\t\t\t\t\t}//for j\n\t\t\t\t}//for k\n\t\t\t\tset_bndDiffSphere(x);\n\t\t\t}\n\t\t}//for itr\n\t}//diffSphDens\n\t//advect density through sphere, using sphere bounds\n\tvoid myFluidBox::advSphDens(double* d, double* d0, double* velocX, double* velocY, double* velocZ) {\n\t\tdouble s0, s1, t0, t1, u0, u1, x, y, z, dtx = deltaT * (sx2i),dty = deltaT * (sy2i),dtz = deltaT * (sz2i);\n\t\tunsigned int i0, i1, j0, j1, k0, k1, i, j, k, IXidx;\n\n\t\tfor (k = 1; k < sz1i; ++k) {\n\t\t\tfor (j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (i = 1; i < sx1i; ++i) {\n\t\t\t\t\tIXidx = IX(i, j, k);\n\t\t\t\t\tif (isOOB[IXidx]) { continue; }\n\t\t\t\t\tx = i - dtx * velocX[IXidx];\n\t\t\t\t\ty = j - dty * velocY[IXidx];\n\t\t\t\t\tz = k - dtz * velocZ[IXidx];\n\t\t\t\t\tx = forceIDXBndD(x, sx2i + 0.5, .5);\n\t\t\t\t\ti0 = floor(x);\ti1 = i0 + 1.0;  s1 = x - i0;\ts0 = 1.0 - s1;\n\n\t\t\t\t\ty = forceIDXBndD(y, sy2i + 0.5, .5);\n\t\t\t\t\tj0 = floor(y);\tj1 = j0 + 1.0;\tt1 = y - j0;\tt0 = 1.0 - t1;\n\n\t\t\t\t\tz = forceIDXBndD(z, sz2i + 0.5, .5);\n\t\t\t\t\tk0 = floor(z);\tk1 = k0 + 1.0;\tu1 = z - k0;\tu0 = 1.0 - u1;\n\n\t\t\t\t\td[IXidx] =\n\t\t\t\t\t\ts0 * (t0 * (u0 * d0[IX(i0, j0, k0)]\t+ u1 * d0[IX(i0, j0, k1)]) + (t1 * (u0 * d0[IX(i0, j1, k0)] + u1 * d0[IX(i0, j1, k1)]))) + \n\t\t\t\t\t\ts1 * (t0 * (u0 * d0[IX(i1, j0, k0)]\t+ u1 * d0[IX(i1, j0, k1)]) + (t1 * (u0 * d0[IX(i1, j1, k0)]\t+ u1 * d0[IX(i1, j1, k1)])));\n\t\t\t\t}//for i\n\t\t\t}//for j\n\t\t}//for k\n\t\tset_bndDiffSphere(d);\n\t}//advSphDens\n\n\tvoid myFluidBox::lin_solveSphere(double* x, double* x0, double* y, double* y0, double* z, double* z0, double a, double c) {\n\t\tif (a == 0) {\n\t\t\tstd::memcpy(&x, &x0, sizeof x0);\n\t\t\tstd::memcpy(&y, &y0, sizeof y0);\n\t\t\tstd::memcpy(&z, &z0, sizeof z0);\n\t\t\tset_bndSphere3(x, y, z);\n\t\t}\n\t\telse {\n\t\t\tunsigned int idx0, idx1, idx2, idx3, idx4, idx5, idx6;\n\t\t\tfor (unsigned int itr = 0; itr < slvIters; ++itr) {\n\t\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\t\t\tidx0 = IX(i, j, k);\n\t\t\t\t\t\t\tif (isOOB[idx0]) { continue; }\n\t\t\t\t\t\t\tidx1 = IX(i + 1, j, k);\n\t\t\t\t\t\t\tidx2 = IX(i - 1, j, k);\n\t\t\t\t\t\t\tidx3 = IX(i, j + 1, k);\n\t\t\t\t\t\t\tidx4 = IX(i, j - 1, k);\n\t\t\t\t\t\t\tidx5 = IX(i, j, k + 1);\n\t\t\t\t\t\t\tidx6 = IX(i, j, k - 1);\n\t\t\t\t\t\t\tx[idx0] = (x0[idx0] + a * (x[idx1] + x[idx2] + x[idx3] + x[idx4] + x[idx5] + x[idx6])) / c;\n\t\t\t\t\t\t\ty[idx0] = (y0[idx0] + a * (y[idx1] + y[idx2] + y[idx3] + y[idx4] + y[idx5] + y[idx6])) / c;\n\t\t\t\t\t\t\tz[idx0] = (z0[idx0] + a * (z[idx1] + z[idx2] + z[idx3] + z[idx4] + z[idx5] + z[idx6])) / c;\n\t\t\t\t\t\t}//for i\n\t\t\t\t\t}//for j\n\t\t\t\t}//for k\n\t\t\t\tset_bndSphere3(x, y, z);\n\t\t\t}//for itr\n\t\t}//if a != 0\n\t}//lin_solveSphere\n\n\t//vorticity confinement - add back vorticity details lost through numerical dissipation\n\t//vortN is unused array to hold calcs\n\tvoid myFluidBox::vorticityConfinement(double* vortN) {\n\t\tunsigned int idx, idx_ijp1k, idx_ijm1k, idx_ip1jk, idx_im1jk, idx_ijkm1, idx_ijkp1;\n\t\t//double vortEps = deltaT * .01;\t//TODO change to allow for user input\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\tif (isOOB[idx]) { continue; }\n\t\t\t\t\tidx_ip1jk = IX(i + 1, j, k); idx_im1jk = IX(i - 1, j, k); idx_ijp1k = IX(i, j + 1, k); idx_ijm1k = IX(i, j - 1, k); idx_ijkp1 = IX(i, j, k + 1); idx_ijkm1 = IX(i, j, k - 1);\n\t\t\t\t\t//curl operation del cross u -> partial z w/respect to y is the finite diff of the z vels across the y coords\n\t\t\t\t\tvortVec[idx] << \n\t\t\t\t\t\t((Vy[idx_ijkp1] - Vy[idx_ijkm1]) * hO2Syd) - ((Vz[idx_ijp1k] - Vz[idx_ijm1k]) * hO2Szd),\n\t\t\t\t\t\t((Vz[idx_ip1jk] - Vz[idx_im1jk]) * hO2Szd) - ((Vx[idx_ijkp1] - Vx[idx_ijkm1]) * hO2Sxd),\n\t\t\t\t\t\t((Vx[idx_ijp1k] - Vx[idx_ijm1k]) * hO2Sxd) - ((Vy[idx_ip1jk] - Vy[idx_im1jk]) * hO2Syd);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndDiffVec(vortVec);\n\t\tfor (idx = 0; idx < numCells; ++idx) { vortN[idx] = (isOOB[idx]) ?  0 : vortVec[idx].norm(); }\n\n\t\tEigen::Vector3d eta, vf; eta.setZero();\tvf.setZero();\n\t\t\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\t\n\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\tif (vortN[idx] < .0000001) {\tcontinue;}\n\t\t\t\t\tvortVec[idx].normalize();\n\t\t\t\t\teta << ((vortN[IX(i + 1, j, k)] - vortN[IX(i - 1, j, k)]) * hO2Sxd), ((vortN[IX(i, j + 1, k)] - vortN[IX(i, j - 1, k)]) * hO2Syd), ( (vortN[IX(i, j, k + 1)] - vortN[IX(i, j, k - 1)]) * hO2Szd);\n\t\t\t\t\teta.normalize();\n\t\t\t\t\tvf = vortEps * (eta.cross(vortVec[idx]));\n\t\t\t\t\t//cout << \"Vx \" << idx << \" before :  \" << Vx[idx] << \" vortN : \" << vortN[idx] << \" invDivX : \" << invDivX << \" eta : \" << eta(0) << \",\" << eta(1) << \",\" << eta(2) << \" vf : \" << vf(0) << \",\" << vf(1) << \",\" << vf(2) << \" vort : \" << vort(0) << \",\" << vort(1) << \",\" << vort(2);\n\t\t\t\t\tVx[idx] += vf(0) * sx2i;\n\t\t\t\t\tVy[idx] += vf(1) * sy2i;\n\t\t\t\t\tVz[idx] += vf(2) * sz2i;\t\n\t\t\t\t\t//cout << \"Vx \" << idx << \" after :  \" << Vx[idx]<<endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndSphere3(Vx, Vy, Vz);\n\t}//vorticityConfinement\n\n\t//vorticity particle method TODO\n\tvoid myFluidBox::vorticityParticles() {\n\t\tint idx, idx_ijp1k, idx_ijm1k, idx_ip1jk, idx_im1jk, idx_ijkm1, idx_ijkp1;\n\t\t//find accelerations via finite diff\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\tif (isOOB[idx]) { continue; }\n\t\t\t\t\tidx_ip1jk = IX(i + 1, j, k);idx_im1jk = IX(i - 1, j, k);idx_ijp1k = IX(i, j + 1, k);idx_ijm1k = IX(i, j - 1, k);idx_ijkp1 = IX(i, j, k + 1);idx_ijkm1 = IX(i, j, k - 1);\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\taccelVecX[idx] << (Vx[idx_ip1jk] - Vx[idx_im1jk]) * hO2Sxd, (Vx[idx_ijp1k] - Vx[idx_ijm1k]) * hO2Syd, (Vx[idx_ijkp1] - Vx[idx_ijkm1]) * hO2Szd;//interpAccel(Vx, idx_ip1jk, idx_im1jk, idx_ijp1k, idx_ijm1k, idx_ijkp1, idx_ijkm1);\n\t\t\t\t\taccelVecY[idx] << (Vy[idx_ip1jk] - Vy[idx_im1jk]) * hO2Sxd, (Vy[idx_ijp1k] - Vy[idx_ijm1k]) * hO2Syd, (Vy[idx_ijkp1] - Vy[idx_ijkm1]) * hO2Szd;//interpAccel(Vy, idx_ip1jk, idx_im1jk, idx_ijp1k, idx_ijm1k, idx_ijkp1, idx_ijkm1);\n\t\t\t\t\taccelVecZ[idx] << (Vz[idx_ip1jk] - Vz[idx_im1jk]) * hO2Sxd, (Vz[idx_ijp1k] - Vz[idx_ijm1k]) * hO2Syd, (Vz[idx_ijkp1] - Vz[idx_ijkm1]) * hO2Szd;//interpAccel(Vz, idx_ip1jk, idx_im1jk, idx_ijp1k, idx_ijm1k, idx_ijkp1, idx_ijkm1);\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndDiffVec(accelVecX);\n\t\tset_bndDiffVec(accelVecY);\n\t\tset_bndDiffVec(accelVecZ);\n\n\t\t//vort particle code here TODO\n\n\t}//vorticityParticles\n\n\tvoid myFluidBox::projectSphere(double* velocX, double* velocY, double* velocZ, double* p, double* div) {\n\t\tunsigned int idx;\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\tp[idx] = 0;\n\t\t\t\t\tif (isOOB[idx]) {\tdiv[idx] = 0;\tcontinue; }\n\t\t\t\t\t//when using mac grid, change to * 1/sxi instead of 1/2sxi\n\t\t\t\t\tdiv[idx] = -(\n\t\t\t\t\t\t(velocX[IX(i + 1, j, k)] - velocX[IX(i - 1, j, k)]) * hO2Sxd\n\t\t\t\t\t\t+(velocY[IX(i, j + 1, k)] - velocY[IX(i, j - 1, k)]) * hO2Syd\n\t\t\t\t\t\t+(velocZ[IX(i, j, k + 1)] - velocZ[IX(i, j, k - 1)]) * hO2Szd\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndDiffSphere(div);\n\t\tset_bndDiffSphere(p);\n\t\tfor (unsigned int itr = 0; itr < slvIters; ++itr) {\n\t\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\t\tif (isOOB[idx]) { continue; }\n\t\t\t\t\t\tp[idx] = (div[idx] + (p[IX(i + 1, j, k)] + p[IX(i - 1, j, k)] + p[IX(i, j + 1, k)] + p[IX(i, j - 1, k)] + p[IX(i, j, k + 1)] + p[IX(i, j, k - 1)])) / 6.0;\n\t\t\t\t\t}//for i\n\t\t\t\t}//for j\n\t\t\t}//for k\n\t\t\tset_bndDiffSphere(p);\n\t\t}//for each iteration\n\t\t\n\t\tfor (unsigned int k = 1; k < sz1i; ++k) {\n\t\t\tfor (unsigned int j = 1; j < sy1i; ++j) {\n\t\t\t\tfor (unsigned int i = 1; i < sx1i; ++i) {\n\t\t\t\t\tidx = IX(i, j, k);\n\t\t\t\t\tif (isOOB[idx]) { continue; }\n\t\t\t\t\tvelocX[idx] -= hSxd *(p[IX(i + 1, j, k)] - p[IX(i - 1, j, k)]);\n\t\t\t\t\tvelocY[idx] -= hSyd *(p[IX(i, j + 1, k)] - p[IX(i, j - 1, k)]);\n\t\t\t\t\tvelocZ[idx] -= hSzd *(p[IX(i, j, k + 1)] - p[IX(i, j, k - 1)]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tset_bndSphere3(velocX, velocY, velocZ);\n\t}//projectSphere\n\n\n\tvoid myFluidBox::set_bndDiffSphere(double* x) {\n\t\tfor (sphereBndMap::iterator it = sphereBnds.begin(); it != sphereBnds.end(); ++it) { x[it->first] *= it->second->mag; }//scale to amt of cube in bounds\n\t}\n\tvoid myFluidBox::set_bndDiffVec(eignVecTyp& egVec) {\n\t\tEigen::Vector3d  velNorm(0, 0, 0);\n\t\tfor (sphereBndMap::iterator it = sphereBnds.begin(); it != sphereBnds.end(); ++it) {\n\t\t\t//velNorm = (egVec[it->first].dot(it->second->norm)* it->second->mag)  *it->second->norm;\t\t\t//velocity in the normal direction toward center of sphere\n\t\t\tvelNorm = (egVec[it->first].dot(it->second->norm))  *it->second->norm;\t\t\t//velocity in the normal direction toward center of sphere\n\t\t\tegVec[it->first] -= velNorm;\t\t\t\t\t\t\t\t\t\t\t\t\t//remove velocity component in opposite direction of normal\n\t\t\tegVec[it->first] *= velNorm.norm();\t\t\t\t\t\t\t\t\t\t\t\t//amplify remaining component by same amount - increase tangent velocity\n\n\t\t}\n\t}\n\t//address boundary layer values\n\tvoid myFluidBox::set_bndSphere3(double* x, double* y, double* z) {\n\t\t//int vIdx = b - 1, xIdx;\n\t\tEigen::Vector3d velVec(0, 0, 0), velNorm(0, 0, 0);\n\t\tfor (sphereBndMap::iterator it = sphereBnds.begin(); it != sphereBnds.end(); ++it) {\n\t\t\tvelVec << x[it->first], y[it->first], z[it->first];\n\t\t\t//velNorm = (velVec.dot(it->second->norm)* it->second->mag)  *it->second->norm;\t\t\t//velocity in the normal direction toward center of sphere\n\t\t\tvelNorm = (velVec.dot(it->second->norm))  *it->second->norm;\t\t\t\t\t\t\t//velocity in the normal direction toward center of sphere\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//subtract velocity in direction of sphere wall\n\t\t\tx[it->first] -= velNorm(0);\n\t\t\ty[it->first] -= velNorm(1);\n\t\t\tz[it->first] -= velNorm(2);\n\t\t\t//scale result (tangent dir) by lost velocity magnitude - don't want to lose velocity, just redirect it\n\t\t\tx[it->first] *= velNorm.norm();\n\t\t\ty[it->first] *= velNorm.norm();\n\t\t\tz[it->first] *= velNorm.norm();\n\t\t}\n\t}//set_bndSphere\n\n\tvoid myFluidBox::myFluidBoxAddDensity(int x, int y, int z, double amount) { density[IX(x, y, z)] += amount; }\n\n\tvoid myFluidBox::resetOldVals() {\n\t\t//all elems same type\n\t\t//int numElems = sizeof(Vx0[0]) * numCells;\n\t\tmemset(Vx0, 0, memSetNumElems);\n\t\tmemset(Vy0, 0, memSetNumElems);\n\t\tmemset(Vz0, 0, memSetNumElems);\n\t\tmemset(oldDensity, 0, memSetNumElems);\n\t}\n\n\tvoid myFluidBox::myFluidBoxAddForce(const Eigen::Ref<const Eigen::Vector3d>& cellLoc, const Eigen::Ref<const Eigen::Vector3d>& amount) {\n\t\t//cout<<\"force addition location in cube :(\"<< cellLoc (0)<<\",\"<< cellLoc(1) <<\",\"<< cellLoc(2) <<\")\"<<endl;\n\n\t\tint idx = IX(forceIDXBnd((int)(cellLoc(0)), sx1i,0),\n\t\t\t\t\t forceIDXBnd((int)(cellLoc(1)), sy1i,0),\n\t\t\t\t\t forceIDXBnd((int)(cellLoc(2)), sz1i,0));\n\t\t//static int iters = 0;\n\t\t//cout << \"add force in fluidbox @idx : \" << idx << \" iter : \" << iters++ << \"\\n\";\n\t\t//Vx0[idx] = amount(0);\n\t\t//Vy0[idx] = amount(1);\n\t\t//Vz0[idx] = amount(2);\n\t\tVx[idx] += amount(0);\n\t\tVy[idx] += amount(1);\n\t\tVz[idx] += amount(2);\n\t}\n\n\t//cellloc is a particle position - cell idx is going to be floor of each coord\n\tEigen::Vector3d myFluidBox::getVelAtCell(const Eigen::Ref<const Eigen::Vector3d>& testLoc) {\n\t\t//ctrSzHalfNC == (ctr - (halfNumCell * cellSz))/cellSz\n\t\t//cout<<ctrSzHalfNC << \"\\n\";\n\t\tEigen::Vector3d tmpTestLoc = testLoc.cwiseQuotient(cellSz),\n\t\t\ttestLocInFluid = tmpTestLoc - ctrSzHalfNC;\n\t\t\n\t\t//double locX = (testLoc(0) - center(0)) / cellSz(0) + halfNmCellX,\n\t\t//\tlocY = (testLoc(1) - center(1)) / cellSz(1) + halfNmCellY,\n\t\t//\tlocZ = (testLoc(2) - center(2)) / cellSz(2) + halfNmCellZ;\n\t\tint intLocX = (int)testLocInFluid(0),\n\t\t\tintLocY = (int)testLocInFluid(1),\n\t\t\tintLocZ = (int)testLocInFluid(2);\n\n\t\tdouble interpX = testLocInFluid(0) - intLocX, interpM1X = 1 - interpX,\n\t\t\t   interpY = testLocInFluid(1) - intLocY, interpM1Y = 1 - interpY,\n\t\t\t   interpZ = testLocInFluid(2) - intLocZ, interpM1Z = 1 - interpZ;\n\t\t//bound idx's\n\t\t//int tX[2], tY[2], tZ[2];\n\t\t//tX[0] = forceIDXBnd(intLocX, sx1i),\n\t\t//tY[0] = forceIDXBnd(intLocY, sy1i),\n\t\t//tZ[0] = forceIDXBnd(intLocZ, sz1i),\n\t\t//tX[1] = forceIDXBnd(intLocX + 1, sx1i),\n\t\t//tY[1] = forceIDXBnd(intLocY + 1, sy1i),\n\t\t//tZ[1] = forceIDXBnd(intLocZ + 1, sz1i);\n\t/*\n\t\tvector<int> idxs(8); int cnt = 0;\n\t\tfor (unsigned int z = 0; z < 2; ++z) {for (unsigned int y = 0; y < 2; ++y) {for (unsigned int x = 0; x < 2; ++x) { idxs[cnt++] = IX(tX[x], tY[y], tZ[z]);}}}\n\t*/\t\n\t\tint idx000 = IX(forceIDXBnd(intLocX, sx1i, 0), forceIDXBnd(intLocY, sy1i, 0), forceIDXBnd(intLocZ, sz1i, 0)),\n\t\t\tidx111 = IX(forceIDXBnd(intLocX + 1, sx1i, 0), forceIDXBnd(intLocY + 1, sy1i, 0), forceIDXBnd(intLocZ + 1, sz1i, 0));\n\n\t\t//int idx000 = IX(forceIDXBnd(intLocX, sx2i, 1), forceIDXBnd(intLocY, sy2i, 1), forceIDXBnd(intLocZ, sz2i, 1)),\n\t\t//\tidx111 = IX(forceIDXBnd(intLocX + 1, sx2i, 1), forceIDXBnd(intLocY + 1, sy2i, 1), forceIDXBnd(intLocZ + 1, sz2i, 1));\n\n\t\t//double valx = interpM1X * Vx[idx000] + interpX*Vx[idx111],\n\t\t//\t   valy = interpM1Y * Vy[idx000] + interpY*Vy[idx111],\n\t\t//\t   valz = interpM1Z * Vz[idx000] + interpZ*Vz[idx111];\n\n\t\t//int idx = IX(forceIDXBnd((int)((testLoc(0) - center(0)) / cellSz(0) + halfNmCellX), sx1i),\n\t\t//\t\t\t forceIDXBnd((int)((testLoc(1) - center(1)) / cellSz(1) + halfNmCellY), sy1i),\n\t\t//\t\t\t forceIDXBnd((int)((testLoc(2) - center(2)) / cellSz(2) + halfNmCellZ), sz1i));\n\n\t\t//return Eigen::Vector3d(Vx[idx], Vy[idx], Vz[idx]);\n\t\treturn Eigen::Vector3d(interpM1X * Vx[idx000] + interpX*Vx[idx111], interpM1Y * Vy[idx000] + interpY*Vy[idx111], interpM1Z * Vz[idx000] + interpZ*Vz[idx111]);\n\t}//getVelAtCell\n\n}//namespace particleSystem\n\n", "meta": {"hexsha": "e438605481cfdec9d8653a8ea795e2d0608b9f05", "size": 26811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "particlesystem/src/myFluidBox.cpp", "max_stars_repo_name": "jturner65/ParticleSim", "max_stars_repo_head_hexsha": "0ad72630c6c417a924833c4d5955d6daa902fbe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-10T11:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-10T11:35:32.000Z", "max_issues_repo_path": "particlesystem/src/myFluidBox.cpp", "max_issues_repo_name": "jturner65/ParticleSim", "max_issues_repo_head_hexsha": "0ad72630c6c417a924833c4d5955d6daa902fbe8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T12:46:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-03T12:46:17.000Z", "max_forks_repo_path": "particlesystem/src/myFluidBox.cpp", "max_forks_repo_name": "jturner65/ParticleSim", "max_forks_repo_head_hexsha": "0ad72630c6c417a924833c4d5955d6daa902fbe8", "max_forks_repo_licenses": ["Apache-2.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.0353130016, "max_line_length": 287, "alphanum_fraction": 0.5533176681, "num_tokens": 12131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5559516186241023}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <numeric>\n\nnamespace mtao::linear_algebra {\n    // M is matrix, B is initial vector, Q is the basis for the basis\n    // N is the dimension of the subspace\n\n    namespace internal {\n        template <typename Derived, typename BDerived, typename VDerived, typename TDerived>\n            auto lanczos(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& v1, Eigen::PlainObjectBase<VDerived>& V, Eigen::PlainObjectBase<TDerived>& T) {\n                const int N = T.rows();\n                using Scalar = typename Derived::Scalar;\n                constexpr Scalar eps = std::numeric_limits<Scalar>::epsilon();\n                using Vec = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>;\n\n                V.setZero();\n                T.setZero();\n\n                V.col(0) = v1;\n                Vec w;\n\n                {// first iteration\n                    auto v = V.col(0);\n                    w = M * v;\n                    const Scalar& a = T(0,0) = w.dot(v);\n\n                    w -= a * v;\n                }\n                for(int j = 1; j < N; ++j) {\n                    const Scalar& b = T(j,j-1) = T(j-1,j) = w.norm();\n                    if(b < eps) {\n                        return;\n                    }\n                    auto vjm = V.col(j-1);\n                    auto vj = V.col(j) = w/b;\n                    w = M * vj;\n                    const Scalar& a = T(j,j) = w.dot(vj);\n                    w -= a * vj + b * vjm;\n                }\n            }\n    }\n\n    template <typename Derived, typename BDerived>\n        auto lanczos(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B, int N) {\n            assert(M.rows() == M.cols());\n\n            using Scalar = typename Derived::Scalar;\n            using Mat = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime,Eigen::Dynamic>;\n            using DMat = Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>;\n\n            Mat Q(M.rows(),N);\n            DMat H(N,N);\n\n            internal::lanczos(M,B,Q,H);\n            return std::make_tuple(Q,H);\n        }\n    template <int N, typename Derived, typename BDerived>\n        auto lanczos(const Eigen::MatrixBase<Derived>& M, const Eigen::MatrixBase<BDerived>& B) {\n            assert(M.rows() == M.cols());\n\n            using Scalar = typename Derived::Scalar;\n            using Mat = Eigen::Matrix<Scalar,Eigen::Dynamic,N>;\n            using HMat = Eigen::Matrix<Scalar,N,N>;\n\n            Mat Q(M.rows(),N);\n            HMat H(N,N);\n            internal::lanczos(M,B,Q,H);\n            return std::make_tuple(Q,H);\n        }\n    template <typename Derived>\n        auto lanczos(const Eigen::MatrixBase<Derived>& M, int N) {\n            using Scalar = typename Derived::Scalar;\n            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;\n            return lanczos(M,B,N);\n        }\n    template <int N, typename Derived>\n        auto lanczos(const Eigen::MatrixBase<Derived>& M) {\n            using Scalar = typename Derived::Scalar;\n            auto B = Eigen::Matrix<Scalar,Derived::RowsAtCompileTime, 1>::Random(M.rows()) ;\n            return lanczos<N>(M,B);\n        }\n}\n", "meta": {"hexsha": "a2c0ea7e8b4a9d3e3fceaa70b4cbb3e403ad49cf", "size": 3213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/linear_algebra/lanczos.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/linear_algebra/lanczos.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/linear_algebra/lanczos.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.25, "max_line_length": 176, "alphanum_fraction": 0.5098039216, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5559475730550288}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2015, Karl Pauwels                                         */\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/*  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 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 FOR    */\n/*  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         */\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\n#include <iostream>\n#include <iomanip>\n#include <normal_equations.h>\n#undef Success\n#include <Eigen/Dense>\n\nnamespace pose {\n\nNormalEquations::NormalEquations() {\n  _A.resize(36, 0);\n  _B.resize(6, 0);\n  _dTdR.resize(6, 0);\n}\n\nvoid NormalEquations::reset() {\n  std::fill(_A.begin(), _A.end(), 0);\n  std::fill(_B.begin(), _B.end(), 0);\n  std::fill(_dTdR.begin(), _dTdR.end(), 0);\n}\n\ndouble NormalEquations::squaredNormDeltaT() const {\n  return (_dTdR.at(0) * _dTdR.at(0) + _dTdR.at(1) * _dTdR.at(1) +\n          _dTdR.at(1) * _dTdR.at(1));\n}\n\nvoid NormalEquations::compose(const float *CO, const float *CD) {\n\n  _A[0] = CO[0];\n  _A[1] = 0.0;\n  _A[2] = CO[1];\n  _A[3] = CO[2];\n  _A[4] = CO[3];\n  _A[5] = CO[4];\n  _A[6] = 0.0;\n  _A[7] = CO[0];\n  _A[8] = CO[5];\n  _A[9] = CO[6];\n  _A[10] = -CO[2];\n  _A[11] = CO[7];\n  _A[12] = CO[1];\n  _A[13] = CO[5];\n  _A[14] = CO[8];\n  _A[15] = CO[9];\n  _A[16] = CO[10];\n  _A[17] = 0.0;\n  _A[18] = CO[2];\n  _A[19] = CO[6];\n  _A[20] = CO[9];\n  _A[21] = CO[11];\n  _A[22] = CO[12];\n  _A[23] = CO[13];\n  _A[24] = CO[3];\n  _A[25] = -CO[2];\n  _A[26] = CO[10];\n  _A[27] = CO[12];\n  _A[28] = CO[14];\n  _A[29] = CO[15];\n  _A[30] = CO[4];\n  _A[31] = CO[7];\n  _A[32] = 0.0;\n  _A[33] = CO[13];\n  _A[34] = CO[15];\n  _A[35] = CO[16];\n\n  _A[0] += CD[0];\n  _A[1] += CD[1];\n  _A[2] += CD[2];\n  _A[3] += CD[3];\n  _A[4] += CD[4];\n  _A[5] += CD[5];\n  _A[6] += CD[1];\n  _A[7] += CD[6];\n  _A[8] += CD[7];\n  _A[9] += CD[8];\n  _A[10] += CD[9];\n  _A[11] += CD[10];\n  _A[12] += CD[2];\n  _A[13] += CD[7];\n  _A[14] += CD[11];\n  _A[15] += CD[12];\n  _A[16] += CD[13];\n  _A[17] += CD[14];\n  _A[18] += CD[3];\n  _A[19] += CD[8];\n  _A[20] += CD[12];\n  _A[21] += CD[15];\n  _A[22] += CD[16];\n  _A[23] += CD[17];\n  _A[24] += CD[4];\n  _A[25] += CD[9];\n  _A[26] += CD[13];\n  _A[27] += CD[16];\n  _A[28] += CD[18];\n  _A[29] += CD[19];\n  _A[30] += CD[5];\n  _A[31] += CD[10];\n  _A[32] += CD[14];\n  _A[33] += CD[17];\n  _A[34] += CD[19];\n  _A[35] += CD[20];\n\n  for (int i = 0; i < 6; i++)\n    _B[i] = CO[17 + i] + CD[21 + i];\n}\n\nvoid NormalEquations::solve(float *dTdR) {\n\n  Eigen::Map<Eigen::Matrix<double, 6, 6> > A(_A.data());\n  Eigen::Map<Eigen::Matrix<double, 6, 1> > B(_B.data());\n  Eigen::Map<Eigen::Matrix<double, 6, 1> > double_dTdR(_dTdR.data());\n\n  double_dTdR = A.ldlt().solve(B);\n\n  Eigen::Map<Eigen::Matrix<float, 6, 1> > float_dTdR(dTdR);\n  float_dTdR = double_dTdR.cast<float>();\n}\n\nvoid NormalEquations::preCondition() {\n  for (auto &it : _A)\n    it *= 1.0e-7;\n}\n\nvoid NormalEquations::show() const {\n  for (int row = 0; row < 6; row++) {\n    std::cout << std::scientific;\n    std::cout.precision(3);\n    for (int col = 0; col < 6; col++)\n      std::cout << std::setw(10) << _A.at(row * 6 + col) << \" \";\n    std::cout << std::fixed;\n    std::cout.precision(6);\n    std::cout << ((row == 2) ? \"X \" : \"  \") << std::setw(9) << _dTdR.at(row);\n    std::cout << std::scientific;\n    std::cout.precision(3);\n    std::cout << ((row == 2) ? \" = \" : \"   \") << std::setw(10) << _B.at(row)\n              << std::endl;\n  }\n}\n}\n", "meta": {"hexsha": "375de44d80061d17f7cd2b8a25d8b452debd019d", "size": 5498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation/src/normal_equations.cpp", "max_stars_repo_name": "carlo-/simtrack", "max_stars_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 99.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T11:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T08:20:12.000Z", "max_issues_repo_path": "pose_estimation/src/normal_equations.cpp", "max_issues_repo_name": "carlo-/simtrack", "max_issues_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T19:11:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-25T03:51:39.000Z", "max_forks_repo_path": "pose_estimation/src/normal_equations.cpp", "max_forks_repo_name": "carlo-/simtrack", "max_forks_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-07-06T11:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T01:32:18.000Z", "avg_line_length": 32.1520467836, "max_line_length": 79, "alphanum_fraction": 0.4889050564, "num_tokens": 1798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5559475730550288}}
{"text": "//\n// Created by Amir Masoud Abdol on 2019-04-25.\n//\n\n#include <algorithm>\n#include <cmath>\n\n#include <spdlog/spdlog.h>\n#include <fmt/core.h>\n\n#include \"sam.h\"\n\n#include \"MetaAnalysis.h\"\n#include \"Journal.h\"\n#include \"TestStrategy.h\"\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/non_central_t.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n\nusing namespace std;\nusing namespace sam;\n\nMetaAnalysis::~MetaAnalysis(){\n  \n}\n\nstd::unique_ptr<MetaAnalysis> MetaAnalysis::build(std::string name) {\n  \n  spdlog::debug(\"Building a Meta Analysis Method\");\n  \n  if (name == \"FixedEffectEstimator\") {\n    return std::make_unique<FixedEffectEstimator>();\n  }else if (name == \"RandomEffectEstimator\") {\n    return std::make_unique<RandomEffectEstimator>();\n  }else if (name == \"EggersTestEstimator\") {\n    return std::make_unique<EggersTestEstimator>();\n  }else if (name == \"TestOfObsOverExptSig\") {\n    return std::make_unique<TestOfObsOverExptSig>();\n  }else if (name == \"TrimAndFill\") {\n    return std::make_unique<TrimAndFill>();\n  }else if (name == \"RankCorrelation\") {\n    return std::make_unique<RankCorrelation>();\n  }else{\n    spdlog::critical(\"Invalid Meta Analysis Strategy.\");\n    exit(1);\n  }\n}\n\nstd::unique_ptr<MetaAnalysis> MetaAnalysis::build(const json &config) {\n  if (config[\"name\"] == \"FixedEffectEstimator\") {\n    return std::make_unique<FixedEffectEstimator>();\n  }else if (config[\"name\"] == \"RandomEffectEstimator\") {\n    \n    auto p = config.get<RandomEffectEstimator::Parameters>();\n    return std::make_unique<RandomEffectEstimator>(p);\n    \n  }else if (config[\"name\"] == \"EggersTestEstimator\") {\n    auto p = config.get<EggersTestEstimator::Parameters>();\n    return std::make_unique<EggersTestEstimator>(p);\n    \n  }else if (config[\"name\"] == \"TestOfObsOverExptSig\") {\n    auto p = config.get<TestOfObsOverExptSig::Parameters>();\n    return std::make_unique<TestOfObsOverExptSig>(p);\n    \n  }else if (config[\"name\"] == \"TrimAndFill\") {\n    auto p = config.get<TrimAndFill::Parameters>();\n    return std::make_unique<TrimAndFill>(p);\n    \n  }else if (config[\"name\"] == \"RankCorrelation\") {\n    auto p = config.get<RankCorrelation::Parameters>();\n    return std::make_unique<RankCorrelation>(p);\n    \n  }else{\n    spdlog::critical(\"Invalid Meta Analysis Strategy.\");\n    exit(1);\n  }\n}\n\nstd::vector<std::string> MetaAnalysis::Columns(std::string name) {\n  if (name == \"FixedEffectEstimator\") {\n    return FixedEffectEstimator::ResultType::Columns();\n  }else if (name == \"RandomEffectEstimator\") {\n    return RandomEffectEstimator::ResultType::Columns();\n  }else if (name == \"EggersTestEstimator\") {\n    return EggersTestEstimator::ResultType::Columns();\n  }else if (name == \"TestOfObsOverExptSig\") {\n    return TestOfObsOverExptSig::ResultType::Columns();\n  }else if (name == \"TrimAndFill\") {\n    return TrimAndFill::ResultType::Columns();\n  }else if (name == \"RankCorrelation\") {\n    return RankCorrelation::ResultType::Columns();\n  }else{\n    spdlog::critical(\"Invalid Meta Analysis Strategy.\");\n    exit(1);\n  }\n}\n\nvoid FixedEffectEstimator::estimate(Journal *journal) {\n  spdlog::debug(\"Computing Fixed Effect Estimate...\");\n  \n  journal->storeMetaAnalysisResult(FixedEffect(journal->yi, journal->vi));\n}\n\nvoid RandomEffectEstimator::estimate(Journal *journal) {\n  \n  spdlog::debug(\"Computing Random Effect Estimate...\");\n  \n  float tau2 {0};\n  \n  if (params.estimator.find(\"DL\") != std::string::npos){\n    tau2 = RandomEffectEstimator::DL(journal->yi, journal->vi, journal->wi);\n  }else if (params.estimator.find(\"PM\") != std::string::npos){\n    spdlog::critical(\"Not implemented yet!\");\n    exit(1);\n//    tau2 = RandomEffectEstimator::PM(journal->yi, journal->vi, tau2);\n  }\n  \n  journal->storeMetaAnalysisResult(RandomEffect(journal->yi, journal->vi, tau2));\n}\n\n\nvoid EggersTestEstimator::estimate(Journal *journal) {\n  \n  spdlog::debug(\"Computing Eggers Estimate...\");\n  \n  journal->storeMetaAnalysisResult(EggersTest(journal->yi, journal->vi, params.alpha));\n}\n\n\nRandomEffectEstimator::ResultType\nRandomEffectEstimator::RandomEffect(const arma::Row<float> &yi, const arma::Row<float> &vi, float tau2) {\n  \n  using boost::math::normal;\n  using boost::math::chi_squared;\n  \n  normal norm(0, 1);\n  \n  // Weight per study\n  arma::Row<float> wi = 1. / (vi + tau2);\n  // Meta-analytic estimate\n  auto est = arma::accu(yi % wi) / arma::accu(wi);\n  // Standard error of meta-analytic estimate\n  auto se = sqrt(1. / arma::accu(wi));\n  // Lower bound CI meta-analytical estimate\n  auto ci_lb = est - quantile(norm, 0.975) * se;\n  // Upper bound CI meta-analytical estimate\n  auto ci_ub = est + quantile(norm, 0.975) * se;\n  // Z-value for test of no effect\n  auto zval = est/se;\n  // Compute one-sided p-value\n  auto pval_one = cdf(complement(norm, zval));\n  // Compute two-tailed p-value\n  auto pval = pval_one > 0.5 ? (1. - pval_one) * 2 : pval_one * 2;\n  \n  arma::Row<float> wi_fe = 1. / vi;\n  auto est_fe = arma::accu(wi_fe % yi)/ arma::accu(wi_fe);\n  \n  // Q-statistic\n  auto q_stat = arma::accu(wi_fe % arma::pow(yi - est_fe, 2));\n  \n  chi_squared chisq(yi.n_elem - 1);\n  // p-value of Q-statistic\n  auto q_pval = cdf(complement(chisq, q_stat));\n  \n  return ResultType{est, static_cast<float>(se), static_cast<float>(ci_lb), static_cast<float>(ci_ub), static_cast<float>(zval), static_cast<float>(pval), q_stat, static_cast<float>(q_pval), tau2};\n}\n\n\n// General method-of-moments estimate (Eq. 6 in DerSimonian and Kacker, 2007)\nfloat RandomEffectEstimator::DL(const arma::Row<float> &yi, const arma::Row<float> &vi, const arma::Row<float> &wi) {\n  \n  spdlog::trace(\"→ Estimating the tau2 using DL ...\");\n  \n  auto q = arma::accu(wi % arma::pow(yi - (arma::accu(wi % yi)/arma::accu(wi)), 2));\n  // spdlog::trace(\"Q: {}\", q);\n  \n  auto tau2 = (q - (yi.n_elem - 1)) / (arma::accu(wi) - (arma::accu(arma::pow(wi, 2))/arma::accu(wi)));\n  // spdlog::trace(\"Tau2: {}\", tau2);\n  \n  tau2 = tau2 < 0 ? 0 : tau2;\n  \n  return tau2;\n}\n\n// Function for estimating tau2 with Paule-Mandel estimator\nfloat RandomEffectEstimator::PM(const arma::Row<float> &yi, const arma::Row<float> &vi, const float tau2) {\n  // Degrees of freedom of Q-statistic (df is also expected value because chi square distributed)\n  auto df = yi.n_elem - 1;\n  // Weights in meta-analysis\n  arma::Row<float> wi = 1. / (vi + tau2);\n  // Meta-analytic effect size\n  auto theta = arma::accu(yi % wi)/arma::accu(wi);\n  // Q-statistic\n  auto Q = arma::accu(wi % arma::pow(yi - theta, 2));\n  \n  // Stop iterating if computed Q-statistic equals degrees of freedom\n  \n  return (Q - df);\n}\n\nEggersTestEstimator::ResultType\nEggersTestEstimator::EggersTest(const arma::Row<float> &yi, const arma::Row<float> &vi, float alpha) {\n  \n  using namespace mlpack;\n  using namespace mlpack::regression;\n  \n  using boost::math::students_t;\n  \n  arma::Row<double> Yi = arma::conv_to<arma::Row<double>>::from(yi);\n  arma::Row<double> Vi = arma::conv_to<arma::Row<double>>::from(vi);\n  \n  auto n = Yi.n_elem;\n  auto p = 2;\n  float df = n - p;\n  \n  arma::Row<double> Wi = 1./Vi;\n  arma::Row<double> wts = arma::sqrt(Wi);\n  arma::Row<double> si = arma::sqrt(Vi);\n  \n  arma::Row<double> predictions(n);\n  \n  arma::Mat<double> X;\n  X.ones(2, n);\n  X.row(1) = si;\n  \n  LinearRegression lg(X, Yi, Wi);\n  lg.Train(X, Yi, Wi, false);\n  lg.Predict(X, predictions);\n  \n  arma::Row<double> errors = Yi - predictions;\n  \n  auto slope = lg.Parameters().at(1);\n  \n  arma::Mat<double> W = arma::diagmat(Wi);\n  \n  double res_var_2 = sqrt(arma::accu(Wi % arma::pow(errors, 2)) / (n - 2));\n  arma::Mat<double> S_2 = arma::diagmat(arma::pow(res_var_2 / sqrt(Wi), 2));\n  \n  arma::Mat<double> Z = X.t();\n  arma::Mat<double> var_betas = arma::sqrt(arma::inv(Z.t() * W * Z) * (Z.t() * W * S_2 * W.t() * Z) * arma::inv(Z.t() * W * Z));\n  \n  double slope_se = var_betas.diag().at(1);\n  \n  double slope_stat = slope / slope_se;\n  \n  auto res = TTest::compute_pvalue(slope_stat, n - 2, 0.1, TestStrategy::TestAlternative::TwoSided);\n  \n  return ResultType{static_cast<float>(slope), static_cast<float>(slope_se), static_cast<float>(slope_stat), res.first, res.second, df};\n}\n\nsam::TestOfObsOverExptSig::ResultType\nTestOfObsOverExptSig::TES(const arma::Row<float> &sigs, const arma::Row<float> &ni, float beta, float alpha) {\n  \n  using boost::math::students_t;\n  using boost::math::non_central_t;\n  using boost::math::chi_squared;\n  \n  float k = sigs.n_elem;\n  \n  float O = arma::accu(sigs);\n\n  arma::Row<float> tcvs(k);\n  tcvs.imbue([&, i = 0]() mutable {\n    students_t tdist(ni[i] - 1); i++;\n    return quantile(tdist, 0.95);\n  });\n  \n  // non-central t-statistics\n  arma::Row<float> powers(k);\n  powers.imbue([&, i = 0]() mutable {\n    non_central_t nct(ni[i] - 1, beta * sqrt(ni[i]));\n    return cdf(complement(nct, tcvs[i++]));\n  });\n  \n  float E = arma::accu(powers);\n  \n  /// @note If E is absolute zero, I'm adding some noise that I don't have to deal with the explosion\n  if (E < 0.0000001)\n    E = 1e-10;\n  \n  /// A is most likely different from what R spit out, due to brutal rounding that's happening in R.\n  float A {100000};\n  float pval {0.0};\n  if (k != E) {\n    A = pow(O - E, 2.) / E + pow(O - E, 2.) / (k - E);\n  \n    if (!isnan(A) and !isinf(A)) {\n      chi_squared chisq(1);\n      pval = cdf(complement(chisq, A));\n    }\n  }\n  \n  return TestOfObsOverExptSig::ResultType{E, A, pval, pval < alpha};\n}\n\n\nvoid TestOfObsOverExptSig::estimate(Journal *journal) {\n  \n  spdlog::debug(\"Computing Test Of Obs Over Expt Significance...\");\n  \n  float beta = FixedEffectEstimator::FixedEffect(journal->yi, journal->vi).est;\n  \n  arma::Row<float> sigs(journal->yi.n_elem);\n  sigs.imbue([&, i = 0]() mutable {\n    return journal->publications_list[i++].dv_.sig_;\n  });\n  \n  arma::Row<float> ni(journal->yi.n_elem);\n  ni.imbue([&, i = 0]() mutable {\n    return journal->publications_list[i++].dv_.nobs_;\n  });\n  \n  \n  journal->storeMetaAnalysisResult(TestOfObsOverExptSig::TES(sigs, ni, beta, 0.05));\n}\n\nvoid TrimAndFill::estimate(Journal *journal) {\n  \n  spdlog::debug(\"Computing Trim And Fill...\");\n  \n  arma::Row<float> ni(journal->yi.n_elem);\n  ni.imbue([&, i = 0]() mutable {\n    return journal->publications_list[i++].dv_.nobs_;\n  });\n  \n  journal->storeMetaAnalysisResult(TrimAndFill::TF(journal->yi, journal->vi, ni, params));\n}\n\nTrimAndFill::ResultType TrimAndFill::TF(arma::Row<float> yi, arma::Row<float> vi, arma::Row<float> ni, const Parameters &params) {\n  \n  int k = yi.n_elem;\n  arma::Row<float> wi = 1. / vi;\n  \n  std::string side = params.side;\n\n  /// Determining the side\n  float beta = FixedEffectEstimator::FixedEffect(yi, vi).est;\n  \n  if (params.side.find(\"auto\") != std::string::npos) {\n    if (beta < 0) {\n      side = \"right\";\n    } else {\n      side = \"left\";\n    }\n  }\n  \n  /// flip data if examining right side\n  if (side.find(\"right\") != std::string::npos){\n    yi = -1. * yi;\n  }\n  \n  /// sort data by increasing yi\n  arma::uvec ix = arma::sort_index(yi);\n  arma::Row<float> yi_s = yi.elem(ix).as_row();\n  arma::Row<float> vi_s = vi.elem(ix).as_row();\n  arma::Row<float> wi_s = wi.elem(ix).as_row();\n  arma::Row<float> ni_s = wi.elem(ix).as_row();\n  \n  int iter{0};\n  int maxiter{100};\n  \n  float k0_sav{-1};\n  float k0{0}; // estimated number of missing studies;\n  float se_k0{0};\n  float Sr{0};\n  float varSr{0};\n  float k0_pval{0};\n  \n  arma::Row<float> yi_c;\n  arma::Row<float> yi_c_r;\n  arma::Row<float> yi_c_r_s;\n  \n  while (abs(k0 - k0_sav) > 0) {\n    \n    k0_sav = k0; // save current value of k0;\n    \n    iter++;\n    \n    if (iter > maxiter)\n      break;\n    \n    //  truncated data\n    arma::uvec elems = arma::regspace<arma::uvec>(0, 1, k - k0 - 1);\n    arma::Row<float> yi_t = yi_s.elem(elems).as_row();\n    arma::Row<float> vi_t = vi_s.elem(elems).as_row();\n    arma::Row<float> wi_t = wi_s.elem(elems).as_row();\n    arma::Row<float> ni_t = wi_s.elem(elems).as_row();\n    \n    //  intercept estimate based on truncated data\n    beta = FixedEffectEstimator::FixedEffect(yi_t, vi_t).est;\n    \n    yi_c     = yi_s - beta;                             ///  centered values;\n    yi_c_r   = rankdata(abs(yi_c), \"average\").as_row(); /// @todo ties_method=\"first\"); //  ranked absolute centered values;\n    yi_c_r_s = arma::sign(yi_c) % yi_c_r;               ///  signed ranked centered values;\n    \n    //  estimate the number of missing studies with the R0 estimator\n    \n    if (params.estimator.find(\"R0\") != std::string::npos) {\n      arma::uvec inx = arma::find(yi_c_r_s < 0);\n      k0 = (k - arma::max(-1. * yi_c_r_s.elem(inx))) - 1;\n      se_k0 = sqrt(2 * std::max(static_cast<float>(0.), k0) + 2);\n    }\n    \n    ///  estimate the number of missing studies with the L0 estimator\n    if (params.estimator.find(\"L0\") != std::string::npos) {\n      arma::uvec inx = arma::find(yi_c_r_s > 0);\n      Sr = arma::accu(yi_c_r_s.elem(inx));\n      k0 = (4.*Sr - k*(k+1.)) / (2.*k - 1.);\n      varSr = 1./24 * (k*(k+1.)*(2.*k+1.) + 10.*pow(k0,3) + 27.*pow(k0,2) + 17.*k0 - 18.*k*pow(k0,2) - 18.*k*k0 + 6.*pow(k,2)*k0);\n      se_k0 = 4.*sqrt(varSr) / (2*k - 1);\n    }\n    \n    ///  estimate the number of missing studies with the Q0 estimator\n    if (params.estimator.find(\"Q0\") != std::string::npos) {\n      arma::uvec inx = arma::find(yi_c_r_s > 0);\n      Sr = arma::accu(yi_c_r_s.elem(inx));\n      k0 = k - 1./2 - sqrt(2*pow(k,2) - 4.*Sr + 1./4);\n      varSr = 1./24 * (k*(k+1.)*(2*k+1.) + 10.*pow(k0,3) + 27.*pow(k0,2) + 17.*k0 - 18.*k*pow(k0,2) - 18.*k*k0 + 6.*pow(k,2)*k0);\n      se_k0 = 2. * sqrt(varSr) / sqrt(pow(k-0.5,2) - k0*(2.*k - k0 - 1.));\n    }\n    \n    ///  round k0 and make sure that k0 is non-negative\n    k0 = std::max(static_cast<float>(0.), std::round(k0));\n    se_k0 = std::max(static_cast<float>(0.), se_k0);\n    \n  }\n  \n  \n  \n  /// ------------------ Filling and estimating ----------------\n  \n  auto res = FixedEffectEstimator::FixedEffect(yi, vi);\n  float imputed_est = res.est;\n  float imputed_pval = res.pval;\n  \n  /// if estimated number of missing studies is > 0\n  if (k0 > 0) {\n    \n    /// flip data back if side is right\n    if (side.find(\"right\") != std::string::npos) {\n      yi_c = -1 * (yi_c - beta);\n      yi = -1 * yi;\n    } else {\n      yi_c = yi_c - beta;\n    }\n    \n    /// create filled-in data set\n    arma::Row<float> yi_f = yi_c;\n    arma::Row<float> yi_fill = yi;\n    yi_fill.insert_cols(yi_f.n_elem, -1. * yi_c.elem(arma::regspace<arma::uvec>(k - k0, 1, k - 1)).as_row());\n    \n    /// apply limits if specified\n    /// @todo: to be implemented\n    //    if (!missing(ilim)) {\n    //      ilim = sort(ilim)\n    //      if (length(ilim) != 2L)\n    //        stop(mstyle$stop(\"Argument 'ilim' must be of length 2_\"))\n    //        yi_fill[yi_fill < ilim[1]] = ilim[1]\n    //        yi_fill[yi_fill > ilim[2]] = ilim[2]\n    //        }\n    \n    arma::Row<float> vi_fill = vi;\n    vi_fill.insert_cols(vi.n_elem, vi.elem(arma::regspace<arma::uvec>(k - k0, 1, k - 1)).as_row());\n    arma::Row<float> wi_fill = wi;\n    wi_fill.insert_cols(wi.n_elem, wi.elem(arma::regspace<arma::uvec>(k - k0, 1, k - 1)).as_row());\n    arma::Row<float> ni_fill = ni;\n    ni_fill.insert_cols(ni.n_elem, ni.elem(arma::regspace<arma::uvec>(k - k0, 1, k - 1)).as_row());\n    \n    \n    /// fit model with imputed data\n    auto res = FixedEffectEstimator::FixedEffect(yi_fill, vi_fill);\n    imputed_est = res.est;\n    imputed_pval = res.pval;\n    \n  }\n    \n  /// @todo need to be integrated!\n  std::optional<float> p_k0;\n  \n  /// Adjustment for p_k0\n  if (params.estimator.find(\"R0\") != std::string::npos) {\n    arma::Row<float> m {arma::regspace<arma::Row<float>>(-1, 1, (k0-1))};\n    arma::Row<float> bin_coefs(m.n_elem);\n    /// @todo This imbue can be improved\n    bin_coefs.imbue([&, i = 0]() mutable {\n      auto x = boost::math::binomial_coefficient<float>(0+m.at(i)+1, m.at(i)+1);\n      i++;\n      return x;\n    });\n    arma::Row<float> tmp(m.n_elem);\n    tmp.imbue([&, i = 0]() mutable {\n      return pow(0.5, static_cast<int>(0 + m.at(i++) + 2));\n    });\n    p_k0 = 1 - arma::accu(bin_coefs % tmp);\n  } //else\n    // p_k0 = NA\n  \n  /// @todo Still need to report the p_k0\n  return ResultType{.k0 = k0, .se_k0 = se_k0, .k_all = k + k0, .side = side, .imputed_est = imputed_est, .imputed_pval = imputed_pval};\n  \n}\n\nnamespace sam {\n\n/*-------------------------------------------------------------------------\n * This function calculates the Kendall correlation tau_b.\n *\n * from: https://afni.nimh.nih.gov/pub/dist/src/ktaub.c\n */\nfloat kendallcor(const arma::Row<float> &x, const arma::Row<float> &y) {\n  \n  spdlog::debug(\" → Computing Kendall Correlation...\");\n  \n  int len = x.n_elem;\n  \n  int m1 = 0, m2 = 0, s = 0, nPair , i,j ;\n  float cor ;\n  \n  for(i = 0; i < len; i++) {\n    for(j = i + 1; j < len; j++) {\n      if(y[i] > y[j]) {\n        if (x[i] > x[j]) {\n          s++;\n        } else if(x[i] < x[j]) {\n          s--;\n        } else {\n          m1++;\n        }\n      } else if(y[i] < y[j]) {\n        if (x[i] > x[j]) {\n          s--;\n        } else if(x[i] < x[j]) {\n          s++;\n        } else {\n          m1++;\n        }\n      } else {\n        m2++;\n        \n        if(x[i] == x[j]) {\n          m1++;\n        }\n      }\n    }\n  }\n  \n  nPair = len * (len - 1) / 2;\n  \n  if( m1 < nPair && m2 < nPair )\n    cor = s / ( sqrtf((float)(nPair-m1)) * sqrtf((float)(nPair-m2)) );\n  else\n    cor = 0.0f;\n  \n  return cor;\n}\n\nfloat ckendall(int k, int n, arma::Mat<float> &w) {\n  int i, u;\n  float s;\n  \n  u =  (n * (n - 1) / 2);\n  if ((k < 0) || (k > u))\n    return(0);\n  \n  if (w.at(n, k) < 0) {\n    if (n == 1)\n      w.at(n, k) = (k == 0);\n    else {\n      s = 0;\n      for (i = 0; i < n; i++)\n        s += ckendall(k - i, n - 1, w);\n      w.at(n, k) = s;\n    }\n  }\n  return(w.at(n, k));\n}\n\nfloat pkendall(int len, int n) {\n  \n  spdlog::debug(\" → Computing Kendall Probability...\");\n  \n  int i, j;\n  float p, q;\n  \n  p = 0;\n  q = len;\n  \n  size_t u =  (n * (n - 1) / 2);\n  arma::Mat<float> w(n, u); w.fill(-1);\n\n    if (q < 0)\n      p = 0;\n    else if (q > (n * (n - 1) / 2))\n      p = 1;\n    else {\n      p = 0;\n      for (j = 0; j <= q; j++)\n        p += ckendall(j, n, w);\n      p = p / boost::math::tgamma(n + 1);\n    }\n  \n  spdlog::trace(\" → → p = {:f}\\n\", p);\n  return p;\n}\n\nstd::pair<float, float> kendall_cor_test(const arma::Row<float> &x, const arma::Row<float> &y, const TestStrategy::TestAlternative alternative) {\n  \n  spdlog::debug(\" → Running Kendall Correlation Test...\");\n  \n  auto n = x.n_elem;\n  auto r = kendallcor(x, y);\n  \n  auto q = round((r + 1.) * n * (n - 1.) / 4.);\n  \n  arma::Row<float> x_uqniues = arma::unique(x);\n  size_t x_n_uqniues = x_uqniues.n_elem;\n  arma::Row<float> y_uqniues = arma::unique(y);\n  size_t y_n_uqniues = y_uqniues.n_elem;\n  \n  bool ties = (min(x_n_uqniues, y_n_uqniues) < n);\n\n  float p{0};\n  float statistic;\n  \n  if (!ties) {\n    \n    statistic = q;\n    spdlog::trace(\" → → Statistic: {}\", q);\n    \n    switch (alternative) {\n      case TestStrategy::TestAlternative::TwoSided: {\n        if(q > n * (n - 1) / 4){\n          p = 1 - pkendall(q - 1, n);\n        }else{\n          p = pkendall(q, n);\n        }\n        p = std::min(2. * p, 1.);\n      } break;\n      case TestStrategy::TestAlternative::Greater: {\n        p = 1. - pkendall(q - 1, n);\n      } break;\n      case TestStrategy::TestAlternative::Less: {\n        p = pkendall(q, n);\n      } break;\n    }\n    \n  }else{\n    /// @note I'm not 100% sure if this is a good replacement for `table` but it seems to\n    /// be working!\n    spdlog::trace(\"Found ties...\");\n    spdlog::warn(\"Cannot compute exact p-value with ties!\");\n    \n    /// xties <- table(x[duplicated(x)]) + 1;\n    arma::urowvec xties;\n    if (x_n_uqniues > 0) {\n      xties = arma::hist(x, arma::sort(arma::unique(x))) - 1;\n      xties = arma::nonzeros(xties).as_row() + 1;\n    }else\n      xties = arma::urowvec({0});\n    \n    /// yties <- table(y[duplicated(y)]) + 1;\n    arma::urowvec yties;\n    if (y_n_uqniues) {\n      yties = arma::hist(y, arma::sort(arma::unique(y))) - 1;\n      yties = arma::nonzeros(yties).as_row() + 1;\n    }else\n      yties = arma::urowvec({0});\n    \n    float T0 = n * (n - 1)/2;\n    \n    float T1 = arma::accu(xties % (xties - 1))/2;\n    \n    float T2 = arma::accu(yties % (yties - 1))/2;\n    \n    float S = r * sqrt((T0 - T1) * (T0 - T2));\n    \n    float v0 = n * (n - 1) * (2 * n + 5);\n    \n    float vt = arma::accu(xties % (xties - 1) % (2 * xties + 5));\n    \n    float vu = arma::accu(yties % (yties - 1) % (2 * yties + 5));\n    \n    float v1 = arma::accu((xties % (xties - 1))) * arma::accu(yties % (yties - 1));\n    \n    float v2 = arma::accu((xties % (xties - 1)) % (xties - 2)) * arma::accu(yties % (yties - 1) % (yties - 2));\n    \n    float var_S = (v0 - vt - vu) / 18. + v1 / (2. * n * (n - 1.)) + v2 / (9. * n * (n - 1.) * (n - 2.));\n    \n    statistic = S / sqrt(var_S);\n    \n    using boost::math::normal;\n    normal norm;\n    \n    /// @todo check if these are what I want\n    switch (alternative) {\n      case TestStrategy::TestAlternative::TwoSided: {\n        p = 2 * min(cdf(norm, statistic), cdf(complement(norm, statistic)));\n      } break;\n      case TestStrategy::TestAlternative::Greater: {\n        p = cdf(complement(norm, statistic));\n      } break;\n      case TestStrategy::TestAlternative::Less: {\n        p = cdf(norm, statistic);\n      } break;\n    }\n    \n  }\n  \n  \n  \n  \n  return std::make_pair(r, p);\n}\n\n}\n\nRankCorrelation::ResultType RankCorrelation::RankCor(arma::Row<float> yi, arma::Row<float> vi, const Parameters &params) {\n  \n  auto res  = FixedEffectEstimator::FixedEffect(yi, vi);\n  auto beta = res.est;\n  auto vb = pow(res.se, 2);\n  \n  arma::Row<float> vi_star = vi - vb;\n  arma::Row<float> yi_star = (yi - beta) / arma::sqrt(vi_star);\n  \n//  vi_star.replace(arma::datum::nan, 0.);\n//  yi_star.replace(arma::datum::nan, 0.);\n  auto ken_res = kendall_cor_test(yi_star, vi, params.alternative);\n  \n  auto tau  = ken_res.first;\n  auto pval = ken_res.second;\n  spdlog::trace(\"Kendal Correlation Test: tau: {}, p: {}\", tau, pval);\n  \n  \n  return {.est = tau, .pval = pval, .sig = pval < params.alpha};\n  \n  \n}\n\nvoid RankCorrelation::estimate(sam::Journal *journal) { \n  journal->storeMetaAnalysisResult(RankCorrelation::RankCor(journal->yi, journal->vi, params));\n}\n\n", "meta": {"hexsha": "4a20af69131503d9dcbcfcbf76f145c2f2d38138", "size": 22472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MetaAnalysis.cpp", "max_stars_repo_name": "amirmasoudabdol/SAM", "max_stars_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "src/MetaAnalysis.cpp", "max_issues_repo_name": "amirmasoudabdol/SAM", "max_issues_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MetaAnalysis.cpp", "max_forks_repo_name": "amirmasoudabdol/SAM", "max_forks_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_forks_repo_licenses": ["Apache-2.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.002670227, "max_line_length": 197, "alphanum_fraction": 0.5923816305, "num_tokens": 7322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.5559475678516731}}
{"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_essential_matrix.h\"\n\n#include <Eigen/Core>\n#include <vector>\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/pose/five_point_relative_pose.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\n// An estimator for computing the essential matrix from 5 feature\n// correspondences. The feature correspondences should be normalized\n// by the focal length with the principal point at (0, 0).\nclass EssentialMatrixEstimator\n    : public Estimator<FeatureCorrespondence, Eigen::Matrix3d> {\n public:\n  EssentialMatrixEstimator() {}\n\n  // 5 correspondences are needed to determine an essential matrix.\n  double SampleSize() const { return 5; }\n\n  // Estimates candidate essential matrices from correspondences.\n  bool EstimateModel(const std::vector<FeatureCorrespondence>& correspondences,\n                     std::vector<Eigen::Matrix3d>* essential_matrices) const {\n    std::vector<Eigen::Vector2d> image1_points, image2_points;\n    image1_points.reserve(correspondences.size());\n    image2_points.reserve(correspondences.size());\n    for (int i = 0; i < correspondences.size(); i++) {\n      image1_points.emplace_back(correspondences[i].feature1);\n      image2_points.emplace_back(correspondences[i].feature2);\n    }\n\n    return FivePointRelativePose(image1_points,\n                                 image2_points,\n                                 essential_matrices);\n  }\n\n  // The error for a correspondences given a model. This is the squared sampson\n  // error.\n  double Error(const FeatureCorrespondence& correspondence,\n               const Eigen::Matrix3d& essential_matrix) const {\n    return SquaredSampsonDistance(essential_matrix,\n                                  correspondence.feature1,\n                                  correspondence.feature2);\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(EssentialMatrixEstimator);\n};\n\n}  // namespace\n\nbool EstimateEssentialMatrix(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence>& normalized_correspondences,\n    Eigen::Matrix3d* essential_matrix,\n    RansacSummary* ransac_summary) {\n  EssentialMatrixEstimator essential_matrix_estimator;\n  std::unique_ptr<SampleConsensusEstimator<EssentialMatrixEstimator> >\n      ransac = CreateAndInitializeRansacVariant(ransac_type,\n                                                ransac_params,\n                                                essential_matrix_estimator);\n\n  // Estimate essential matrix.\n  return ransac->Estimate(normalized_correspondences,\n                          essential_matrix,\n                          ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "034cf9a461f26a9aa0cbc0154e130a317c85a79b", "size": 4612, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_essential_matrix.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_essential_matrix.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_essential_matrix.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.5495495495, "max_line_length": 79, "alphanum_fraction": 0.7157415438, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.555947566774858}}
{"text": "#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n\nclass BaseVector {\npublic:\n    BaseVector() {}\n\n    explicit BaseVector(const std::vector<double>& data) {\n        _data = data;\n    }\n\n    // Read-only access when indexing the data\n    const double operator[](int index) const {\n        return _data[index];\n    }\n\n    size_t size() { return _data.size(); }\n\n    const std::vector<double> data() const { return _data; }\n\n    const std::vector<double>* data_ptr() const { return &_data; }\n\nprotected:\n    std::vector<double> _data;\n\n    void push_back(double value) {_data.push_back(value);}\n};\n\nclass Vector2 : public BaseVector {\npublic:\n    using BaseVector::BaseVector;\n\n    Vector2(double x, double y) {\n        _data.push_back(x);\n        _data.push_back(y);\n    }\n\n    double x() const {return _data[0];}\n\n    double y() const {return _data[1];}\n};\n\nstruct Vector3 : BaseVector {\npublic:\n    Vector3(double x, double y, double z) {\n        _data.push_back(x);\n        _data.push_back(y);\n        _data.push_back(z);\n    }\n\n    // Read-only access when indexing the data\n    const double operator[](int index) const {\n        return _data[index];\n    }\n\n    double x() const {return _data[0];}\n\n    double y() const {return _data[1];}\n\n    double z() const {return _data[2];}\n};\n\ndouble magnitude(const Vector2& u);\nVector2 scale(const Vector2& u, double alpha);\nVector2 normalize(const Vector2& u);\nVector2 add(const Vector2& u, const Vector2& v);\nVector2 subtract(const Vector2& u, const Vector2& v);\n\ndouble magnitude(const Vector3& u);\nVector3 scale(const Vector3& u, double alpha);\nVector3 normalize(const Vector3& u);\nVector3 add(const Vector3& u, const Vector3& v);\nVector3 subtract(const Vector3& u, const Vector3& v);\n", "meta": {"hexsha": "3cb41995c9bddc9d8f9a7a55e74ef9983d9b241d", "size": 1739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/vector.hpp", "max_stars_repo_name": "will-bell/navitools", "max_stars_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T18:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T18:41:00.000Z", "max_issues_repo_path": "src/headers/vector.hpp", "max_issues_repo_name": "will-bell/navitools", "max_issues_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/headers/vector.hpp", "max_forks_repo_name": "will-bell/navitools", "max_forks_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8815789474, "max_line_length": 66, "alphanum_fraction": 0.6538240368, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5559395726992754}}
{"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\ntemplate<typename Return, typename... T>\nReturn __enzyme_autodiff(T...);\n\nstatic float 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#define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#define BOOST_NO_EXCEPTIONS\n#include <iostream>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/throw_exception.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n#include <stdio.h>\n\ntypedef boost::array< double , 1 > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , double t )\n{\n    const double a = 1.2;\n    dxdt[0] = -a * x[0];\n}\n\n\ndouble foobar(double t, uint64_t iters) {\n    state_type x = { 1.0 }; // initial conditions\n\n    //typedef controlled_runge_kutta< runge_kutta_dopri5< state_type , typename state_type::value_type , state_type , double > > stepper_type;\n    typedef euler< state_type , typename state_type::value_type , state_type , double > stepper_type;\n    integrate_const( stepper_type(), lorenz , x , 0.0 , t, t/iters );\n\n    //printf(\"final result t=%f x(t)=%f, exp(-1.2* t)=%f\\n\", t, x[0], exp(- 1.2 * t));\n    return x[0];\n}\n\nvoid adept_sincos(double inp, uint64_t iters);\n\nstatic void enzyme_sincos(double inp, uint64_t iters) {\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = foobar(inp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = foobar(inp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n  double res2;\n\n  res2 = __enzyme_autodiff<double>(foobar, inp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Enzyme combined %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n\nint main(int argc, char** argv) {\n\n  int max_iters = atoi(argv[1]) ;\n  double inp = 2.1;\n\n  unsigned i=0;\n  for(int iters=max_iters/20; iters<=max_iters; iters+=max_iters/20) {\n    printf(\"iters=%d\\n\", iters);\n    adept_sincos(inp, iters);\n    enzyme_sincos(inp, iters);\n    i++;\n    if (i == 10) break;\n  }\n}\n", "meta": {"hexsha": "aa1a2ebabf972cad494e2b350866e0a033175b04", "size": 2404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/ode-const/ode.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/ode-const/ode.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/ode-const/ode.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.801980198, "max_line_length": 142, "alphanum_fraction": 0.671797005, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5559351949336645}}
{"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/algorithms/detail/flattening.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The intersection of two geodesics as proposed by Sjoberg.\n\\author 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*/\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 Inverse<CT, false, true, false, false, false> inverse_type;\n    typedef typename inverse_type::result_type inverse_result;\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        CT const alpha1 = inverse_type::apply(lon_a1, lat_a1, lon_a2, lat_a2, spheroid).azimuth;\n        CT const alpha2 = inverse_type::apply(lon_b1, lat_b1, lon_b2, lat_b2, spheroid).azimuth;\n\n        return apply(lon_a1, lat_a1, alpha1, lon_b1, lat_b1, alpha2, lon, lat, spheroid);\n    }\n    \n    template <typename Spheroid>\n    static inline bool apply(CT const& lon1, CT const& lat1, CT const& alpha1,\n                             CT const& lon2, CT const& lat2, CT const& alpha2,\n                             CT & lon, CT & lat,\n                             Spheroid const& spheroid)\n    {\n        // coordinates in radians\n\n        // TODO - handle special cases like degenerated segments, equator, poles, etc.\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n\n        CT const pi = math::pi<CT>();\n        CT const pi_half = pi / c2;\n        CT const f = detail::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n        CT const e_sqr = f * (c2 - f);\n        \n        CT const sin_alpha1 = sin(alpha1);\n        CT const sin_alpha2 = sin(alpha2);\n\n        CT const tan_beta1 = one_minus_f * tan(lat1);\n        CT const tan_beta2 = one_minus_f * tan(lat2);\n        CT const beta1 = atan(tan_beta1);\n        CT const beta2 = atan(tan_beta2);\n        CT const cos_beta1 = cos(beta1);\n        CT const cos_beta2 = cos(beta2);\n        CT const sin_beta1 = sin(beta1);\n        CT const sin_beta2 = sin(beta2);\n\n        // Clairaut constants (lower-case in the paper)\n        int const sign_C1 = math::abs(alpha1) <= pi_half ? 1 : -1;\n        int const sign_C2 = math::abs(alpha2) <= pi_half ? 1 : -1;\n        // Cj = 1 if on equator\n        CT const C1 = sign_C1 * cos_beta1 * sin_alpha1;\n        CT const C2 = sign_C2 * cos_beta2 * sin_alpha2;\n\n        CT const sqrt_1_C1_sqr = math::sqrt(c1 - math::sqr(C1));\n        CT const sqrt_1_C2_sqr = math::sqrt(c1 - math::sqr(C2));\n\n        // handle special case: segments on the equator\n        bool const on_equator1 = math::equals(sqrt_1_C1_sqr, c0);\n        bool const on_equator2 = math::equals(sqrt_1_C2_sqr, c0);\n        if (on_equator1 && on_equator2)\n        {\n            return false;\n        }\n        else if (on_equator1)\n        {\n            CT const dL2 = d_lambda_e_sqr(sin_beta2, c0, C2, sqrt_1_C2_sqr, e_sqr);\n            CT const asin_t2_t02 = asin(C2 * tan_beta2 / sqrt_1_C2_sqr);\n            lat = c0;\n            lon = lon2 - asin_t2_t02 + dL2;\n            return true;\n        }\n        else if (on_equator2)\n        {\n            CT const dL1 = d_lambda_e_sqr(sin_beta1, c0, C1, sqrt_1_C1_sqr, e_sqr);\n            CT const asin_t1_t01 = asin(C1 * tan_beta1 / sqrt_1_C1_sqr);\n            lat = c0;\n            lon = lon1 - asin_t1_t01 + dL1;\n            return true;\n        }\n\n        CT const t01 = sqrt_1_C1_sqr / C1;\n        CT const t02 = sqrt_1_C2_sqr / C2;\n\n        CT const asin_t1_t01 = asin(tan_beta1 / t01);\n        CT const asin_t2_t02 = asin(tan_beta2 / t02);\n        CT const t01_t02 = t01 * t02;\n        CT const t01_t02_2 = c2 * t01_t02;\n        CT const sqr_t01_sqr_t02 = math::sqr(t01) + math::sqr(t02);\n\n        CT t = tan_beta1;\n        int t_id = 0;\n\n        // find the initial t using simplified spherical solution\n        // though not entirely since the reduced latitudes and azimuths are spheroidal\n        // [Sjoberg07]\n        CT const k_base = lon1 - lon2 + asin_t2_t02 - asin_t1_t01;\n        \n        {\n            CT const K = sin(k_base);\n            CT const d1 = sqr_t01_sqr_t02;\n            //CT const d2 = t01_t02_2 * math::sqrt(c1 - math::sqr(K));\n            CT const d2 = t01_t02_2 * cos(k_base);\n            CT const D1 = math::sqrt(d1 - d2);\n            CT const D2 = math::sqrt(d1 + d2);\n            CT const K_t01_t02 = K * t01_t02;\n\n            CT const T1 = K_t01_t02 / D1;\n            CT const T2 = K_t01_t02 / D2;\n            CT asin_T1_t01 = 0;\n            CT asin_T1_t02 = 0;\n            CT asin_T2_t01 = 0;\n            CT asin_T2_t02 = 0;\n\n            // test 4 possible results\n            CT l1 = 0, l2 = 0, dl = 0;\n            bool found = check_t<0>( T1,\n                                    lon1,  asin_T1_t01 = asin(T1 / t01), asin_t1_t01,\n                                    lon2,  asin_T1_t02 = asin(T1 / t02), asin_t2_t02,\n                                    t, l1, l2, dl, t_id)\n                      || check_t<1>(-T1,\n                                    lon1, -asin_T1_t01                 , asin_t1_t01,\n                                    lon2, -asin_T1_t02                 , asin_t2_t02,\n                                    t, l1, l2, dl, t_id)\n                      || check_t<2>( T2,\n                                    lon1,  asin_T2_t01 = asin(T2 / t01), asin_t1_t01,\n                                    lon2,  asin_T2_t02 = asin(T2 / t02), asin_t2_t02,\n                                    t, l1, l2, dl, t_id)\n                      || check_t<3>(-T2,\n                                    lon1, -asin_T2_t01                 , asin_t1_t01,\n                                    lon2, -asin_T2_t02                 , asin_t2_t02,\n                                    t, l1, l2, dl, t_id);\n\n            boost::ignore_unused(found);\n        }\n        \n        // [Sjoberg07]\n        //int const d2_sign = t_id < 2 ? -1 : 1;\n        int const t_sign = (t_id % 2) ? -1 : 1;\n        // [Sjoberg02]\n        CT const C1_sqr = math::sqr(C1);\n        CT const C2_sqr = math::sqr(C2);\n        \n        CT beta = atan(t);\n        CT dL1 = 0, dL2 = 0;\n        CT asin_t_t01 = 0;\n        CT asin_t_t02 = 0;\n\n        for (int i = 0; i < 10; ++i)\n        {\n            CT const sin_beta = sin(beta);\n\n            // integrals approximation\n            dL1 = d_lambda_e_sqr(sin_beta1, sin_beta, C1, sqrt_1_C1_sqr, e_sqr);\n            dL2 = d_lambda_e_sqr(sin_beta2, sin_beta, C2, sqrt_1_C2_sqr, e_sqr);\n\n            // [Sjoberg07]\n            /*CT const k = k_base + dL1 - dL2;\n            CT const K = sin(k);\n            CT const d1 = sqr_t01_sqr_t02;\n            //CT const d2 = t01_t02_2 * math::sqrt(c1 - math::sqr(K));\n            CT const d2 = t01_t02_2 * cos(k);\n            CT const D = math::sqrt(d1 + d2_sign * d2);\n            CT const t_new = t_sign * K * t01_t02 / D;\n            CT const dt = math::abs(t_new - t);\n            t = t_new;\n            CT const new_beta = atan(t);\n            CT const dbeta = math::abs(new_beta - beta);\n            beta = new_beta;*/\n\n            // [Sjoberg02] - it converges faster\n", "meta": {"hexsha": "37bfd7a1a76144c27b8a0f8dc4100142dbc82ad6", "size": 8638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost_1_63_0/boost/geometry/formulas/.!35933!sjoberg_intersection.hpp", "max_stars_repo_name": "newtondev/drachtio-server", "max_stars_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/boost_1_63_0/boost/geometry/formulas/.!35933!sjoberg_intersection.hpp", "max_issues_repo_name": "newtondev/drachtio-server", "max_issues_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/boost_1_63_0/boost/geometry/formulas/.!35933!sjoberg_intersection.hpp", "max_forks_repo_name": "newtondev/drachtio-server", "max_forks_repo_head_hexsha": "cd18c6c0e1aa05501b068fc373682333bab5640c", "max_forks_repo_licenses": ["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.8859649123, "max_line_length": 96, "alphanum_fraction": 0.5410974763, "num_tokens": 2580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143060406073, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.555935186649971}}
{"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: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/estimators/estimate_homography.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/four_point_homography.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::Matrix3d;\nusing Eigen::Vector3d;\n\n// An estimator for computing a homography from 4 feature correspondences. The\n// feature correspondences should be normalized by the focal length with the\n// principal point at (0, 0).\nclass HomographyEstimator\n    : public Estimator<FeatureCorrespondence, Eigen::Matrix3d> {\n public:\n  HomographyEstimator() {}\n\n  // 4 correspondences are needed to determine a homography.\n  double SampleSize() const { return 4; }\n\n  // Estimates candidate relative poses from correspondences.\n  bool EstimateModel(const std::vector<FeatureCorrespondence>& correspondences,\n                     std::vector<Eigen::Matrix3d>* homography) const {\n    std::vector<Eigen::Vector2d> image1_points(4), image2_points(4);\n    for (int i = 0; i < 4; i++) {\n      image1_points[i] = correspondences[i].feature1;\n      image2_points[i] = correspondences[i].feature2;\n    }\n\n    Eigen::Matrix3d homography_matrix;\n    if (!FourPointHomography(image1_points,\n                             image2_points,\n                             &homography_matrix)) {\n      return false;\n    }\n\n    homography->emplace_back(homography_matrix);\n    return true;\n  }\n\n  // The error for a correspondences given a model. This is the asymmetric\n  // distance that measures reprojection error in one image.\n  double Error(const FeatureCorrespondence& correspondence,\n               const Eigen::Matrix3d& homography) const {\n    const Eigen::Vector3d reprojected_point =\n        homography * correspondence.feature1.homogeneous();\n    return (correspondence.feature2 - reprojected_point.hnormalized())\n        .squaredNorm();\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(HomographyEstimator);\n};\n\n}  // namespace\n\nbool EstimateHomography(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence>& correspondences,\n    Eigen::Matrix3d* homography,\n    RansacSummary* ransac_summary) {\n  HomographyEstimator homography_estimator;\n  std::unique_ptr<SampleConsensusEstimator<HomographyEstimator> > ransac =\n      CreateAndInitializeRansacVariant(ransac_type,\n                                       ransac_params,\n                                       homography_estimator);\n  // Estimate the homography.\n  return ransac->Estimate(correspondences, homography, ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "96961da51ef1928be235fda026240a8731b0ca7c", "size": 4666, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_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/estimators/estimate_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/estimators/estimate_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": 38.8833333333, "max_line_length": 79, "alphanum_fraction": 0.7273896271, "num_tokens": 1047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6688802735722129, "lm_q1q2_score": 0.5559351780385176}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_CSCH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSCH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing csch capabilities\n\n    hyperbolic cosecant: \\f$1/\\sinh(x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = csch(x);\n    @endcode\n\n    @see rec, sinh\n\n  **/\n  Value csch(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/csch.hpp>\n#include <boost/simd/function/simd/csch.hpp>\n\n#endif\n", "meta": {"hexsha": "588074cd154564cc2e81acc948ee1648d725b75e", "size": 959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/csch.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/csch.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/csch.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 21.7954545455, "max_line_length": 100, "alphanum_fraction": 0.5599582899, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485245, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5558245675766332}}
{"text": "#include \"MatrixStack.h\"\n\n#include <cassert>\n#include <stdio.h>\n#include <vector>\n\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixStack::MatrixStack() {\n  mstack = make_shared<stack<Matrix4f>>();\n  mstack->push(Matrix4f::Identity());\n}\n\nMatrixStack::~MatrixStack() {}\n\nvoid MatrixStack::pushMatrix() {\n  const Matrix4f &top = mstack->top();\n  mstack->push(top);\n  assert(mstack->size() < 100);\n}\n\nvoid MatrixStack::popMatrix() {\n  assert(!mstack->empty());\n  mstack->pop();\n  // There should always be one matrix left.\n  assert(!mstack->empty());\n}\n\nvoid MatrixStack::loadIdentity() {\n  Matrix4f &top = mstack->top();\n  top = Matrix4f::Identity();\n}\n\nvoid MatrixStack::translate(const Vector3f &t) {\n  Matrix4f &top = mstack->top();\n  Matrix4f E = Matrix4f::Identity();\n  E(0, 3) = t(0);\n  E(1, 3) = t(1);\n  E(2, 3) = t(2);\n  top *= E;\n}\n\nvoid MatrixStack::translate(float x, float y, float z) {\n  translate(Vector3f(x, y, z));\n}\n\nvoid MatrixStack::scale(const Vector3f &s) {\n  Matrix4f &top = mstack->top();\n  Matrix4f E = Matrix4f::Identity();\n  E(0, 0) = s(0);\n  E(1, 1) = s(1);\n  E(2, 2) = s(2);\n  top *= E;\n}\n\nvoid MatrixStack::scale(float x, float y, float z) { scale(Vector3f(x, y, z)); }\n\nvoid MatrixStack::scale(float s) { scale(Vector3f(s, s, s)); }\n\nvoid MatrixStack::rotate(float angle, const Vector3f &axis) {\n  Matrix4f &top = mstack->top();\n  Matrix4f E = Matrix4f::Identity();\n  E.block<3, 3>(0, 0) =\n      AngleAxisf(angle * M_PI / 180.0f, axis.normalized()).toRotationMatrix();\n  top *= E;\n}\n\nvoid MatrixStack::rotate(float angle, float x, float y, float z) {\n  rotate(angle, Vector3f(x, y, z));\n}\n\nvoid MatrixStack::multMatrix(const Matrix4f &matrix) {\n  Matrix4f &top = mstack->top();\n  top *= matrix;\n}\n\nvoid MatrixStack::ortho(float left, float right, float bottom, float top,\n                        float zNear, float zFar) {\n  assert(left != right);\n  assert(bottom != top);\n  assert(zFar != zNear);\n  // Sets the top of the stack\n  Matrix4f &M = mstack->top();\n  M = Matrix4f::Zero();\n  M(0, 0) = 2.0f / (right - left);\n  M(1, 1) = 2.0f / (top - bottom);\n  M(2, 2) = -2.0f / (zFar - zNear);\n  M(0, 3) = -(right + left) / (right - left);\n  M(1, 3) = -(top + bottom) / (top - bottom);\n  M(2, 3) = -(zFar + zNear) / (zFar - zNear);\n  M(3, 3) = 1.0f;\n}\n\nvoid MatrixStack::ortho2D(float left, float right, float bottom, float top) {\n  ortho(left, right, bottom, top, -1.0, 1.0);\n}\n\nvoid MatrixStack::perspective(float fovy, float aspect, float zNear,\n                              float zFar) {\n  assert(fovy != 0.0f);\n  assert(aspect != 0.0f);\n  assert(zFar != zNear);\n  // Sets the top of the stack\n  Matrix4f &M = mstack->top();\n  M = Matrix4f::Zero();\n  float tanHalfFovy = tan(0.5f * fovy * M_PI / 180.0f);\n  M(0, 0) = 1.0f / (aspect * tanHalfFovy);\n  M(1, 1) = 1.0f / (tanHalfFovy);\n  M(2, 2) = -(zFar + zNear) / (zFar - zNear);\n  M(2, 3) = -(2.0f * zFar * zNear) / (zFar - zNear);\n  M(3, 2) = -1.0f;\n}\n\nvoid MatrixStack::frustum(float left, float right, float bottom, float top,\n                          float nearval, float farval) {\n  // http://cgit.freedesktop.org/mesa/mesa/tree/src/mesa/math/m_matrix.c\n  float x, y, a, b, c, d;\n  x = (2.0f * nearval) / (right - left);\n  y = (2.0f * nearval) / (top - bottom);\n  a = (right + left) / (right - left);\n  b = (top + bottom) / (top - bottom);\n  c = -(farval + nearval) / (farval - nearval);\n  d = -(2.0f * farval * nearval) / (farval - nearval);\n\n  // Sets the top of the stack\n  Matrix4f &M = mstack->top();\n  M(0, 0) = x;\n  M(0, 1) = 0.0f;\n  M(0, 2) = a;\n  M(0, 3) = 0.0f;\n  M(1, 0) = 0.0f;\n  M(1, 1) = y;\n  M(1, 2) = b;\n  M(1, 3) = 0.0f;\n  M(2, 0) = 0.0f;\n  M(2, 1) = 0.0f;\n  M(2, 2) = c;\n  M(2, 3) = d;\n  M(3, 0) = 0.0f;\n  M(3, 1) = 0.0f;\n  M(3, 2) = -1.0f;\n  M(3, 3) = 0.0f;\n}\n\nvoid MatrixStack::lookAt(const Vector3f &eye, const Vector3f &center,\n                         const Vector3f &up) {\n  // http://cgit.freedesktop.org/mesa/mesa/tree/src/glu/mesa/glu.c?h=mesa_3_2_dev\n  Vector3f x, y, z;\n  z = (eye - center).normalized();\n  y = up;\n  x = y.cross(z);\n  y = z.cross(x);\n  x.normalize();\n  y.normalize();\n  Matrix4f M = Matrix4f::Identity();\n  M.block<1, 3>(0, 0) = x;\n  M.block<1, 3>(1, 0) = y;\n  M.block<1, 3>(2, 0) = z;\n  multMatrix(M);\n  translate(-eye);\n}\n\nvoid MatrixStack::lookAt(float ex, float ey, float ez, float tx, float ty,\n                         float tz, float ux, float uy, float uz) {\n  lookAt(Vector3f(ex, ey, ez), Vector3f(tx, ty, tz), Vector3f(ux, uy, uz));\n}\n\nconst Matrix4f &MatrixStack::topMatrix() const { return mstack->top(); }\n\nvoid MatrixStack::print(const Matrix4f &mat, const char *name) const {\n  if (name) {\n    printf(\"%s = [\\n\", name);\n  }\n  for (int i = 0; i < 4; ++i) {\n    for (int j = 0; j < 4; ++j) {\n      printf(\"%- 5.2f \", mat(i, j));\n    }\n    printf(\"\\n\");\n  }\n  if (name) {\n    printf(\"];\");\n  }\n  printf(\"\\n\");\n}\n\nvoid MatrixStack::print(const char *name) const { print(mstack->top(), name); }\n\n// void MatrixStack::printStack() const\n// {\n// \t// Copy everything to a non-const stack\n// \tauto tempStack = mstack;\n// \twhile(!tempStack.empty()) {\n// \t\tMatrix4f &top = tempStack.top();\n// \t\tprint(top);\n// \t\ttempStack.pop();\n// \t}\n// }\n\n// #include <iostream>\n// int main(int argc, char **argv)\n// {\n// \tMatrixStack M;\n// \tM.frustum(-1, 1, -2, 2, 0.1, 10.0);\n// \tstd::cout << M.topMatrix() << std::endl;\n// }\n", "meta": {"hexsha": "1da0fffa30e89dd05d73f335680ccb269df7d083", "size": 5377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MatrixStack.cpp", "max_stars_repo_name": "Simon089/SphereOctree", "max_stars_repo_head_hexsha": "357f5d89dd5e9426ca8008866ff39d03e7a38d48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T20:36:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:55:57.000Z", "max_issues_repo_path": "src/MatrixStack.cpp", "max_issues_repo_name": "Simon089/SphereOctree", "max_issues_repo_head_hexsha": "357f5d89dd5e9426ca8008866ff39d03e7a38d48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MatrixStack.cpp", "max_forks_repo_name": "Simon089/SphereOctree", "max_forks_repo_head_hexsha": "357f5d89dd5e9426ca8008866ff39d03e7a38d48", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 81, "alphanum_fraction": 0.5724381625, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.5558245621488529}}
{"text": "//\n//  AutoFlipSVD.hpp\n//  DOT\n//\n//  Created by Minchen Li on 6/21/18.\n//\n\n#ifndef AutoFlipSVD_hpp\n#define AutoFlipSVD_hpp\n\n#include \"ImplicitQRSVD.h\"\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n\nnamespace DOT {\n    \n    template<typename MatrixType>\n    class AutoFlipSVD : Eigen::JacobiSVD<MatrixType>\n    {\n    protected:\n        bool flipped_U, flipped_V, flipped_sigma;\n        \n        typename Eigen::JacobiSVD<MatrixType>::SingularValuesType singularValues_flipped;\n        MatrixType matrixU_flipped, matrixV_flipped;\n        \n    public:\n        AutoFlipSVD(void) {}\n        AutoFlipSVD(const MatrixType& mtr, unsigned int computationOptions = 0)\n        {\n            compute(mtr, computationOptions);\n        }\n        \n    public:\n        template<int dim = MatrixType::RowsAtCompileTime>\n        typename std::enable_if<dim == 3, AutoFlipSVD<MatrixType>>::type&\n        compute(const MatrixType& mtr, unsigned int computationOptions)\n        {\n            flipped_U = flipped_V = flipped_sigma = true;\n#ifdef USE_IQRSVD\n            JIXIE::singularValueDecomposition(mtr,\n                                              matrixU_flipped,\n                                              singularValues_flipped,\n                                              matrixV_flipped);\n#else\n            if((computationOptions & Eigen::ComputeFullU) ||\n               (computationOptions & Eigen::ComputeFullV))\n            {\n                fastSVD3d(mtr, matrixU_flipped, singularValues_flipped, matrixV_flipped);\n            }\n            else {\n                fastComputeSingularValues3d(mtr, singularValues_flipped);\n            }\n#endif\n            return *this;\n        }\n        template<int dim = MatrixType::RowsAtCompileTime>\n        typename std::enable_if<dim == 2, AutoFlipSVD<MatrixType>>::type&\n        compute(const MatrixType& mtr, unsigned int computationOptions)\n        {\n#ifdef USE_IQRSVD\n            flipped_U = flipped_V = flipped_sigma = true;\n            JIXIE::singularValueDecomposition(mtr,\n                                              matrixU_flipped,\n                                              singularValues_flipped,\n                                              matrixV_flipped);\n#else\n            flipped_U = flipped_V = flipped_sigma = false;\n            Eigen::JacobiSVD<MatrixType>::compute(mtr, computationOptions);\n            flip2d(mtr, computationOptions);\n#endif\n            return *this;\n        }\n\n        void set(const Eigen::Matrix3d& U, const Eigen::Vector3d& Sigma, const Eigen::Matrix3d& V)\n        {\n            flipped_U = true, flipped_V = true, flipped_sigma = true;\n            matrixU_flipped = U;\n            singularValues_flipped = Sigma;\n            matrixV_flipped = V;\n        }\n        \n    protected:\n        void flip2d(const MatrixType& mtr, unsigned int computationOptions) {\n            //!!! this flip algorithm is only valid in 2D\n            bool fullUComputed = (computationOptions & Eigen::ComputeFullU);\n            bool fullVComputed = (computationOptions & Eigen::ComputeFullV);\n            if(fullUComputed && fullVComputed) {\n                if(Eigen::JacobiSVD<MatrixType>::m_matrixU.determinant() < 0.0) {\n                    matrixU_flipped = Eigen::JacobiSVD<MatrixType>::m_matrixU;\n                    matrixU_flipped.col(1) *= -1.0;\n                    flipped_U = true;\n                    \n                    if(!flipped_sigma) {\n                        singularValues_flipped = Eigen::JacobiSVD<MatrixType>::m_singularValues;\n                    }\n                    singularValues_flipped[1] *= -1.0;\n                    flipped_sigma = true;\n                }\n                if(Eigen::JacobiSVD<MatrixType>::m_matrixV.determinant() < 0.0) {\n                    matrixV_flipped = Eigen::JacobiSVD<MatrixType>::m_matrixV;\n                    matrixV_flipped.col(1) *= -1.0;\n                    flipped_V = true;\n                    \n                    if(!flipped_sigma) {\n                        singularValues_flipped = Eigen::JacobiSVD<MatrixType>::m_singularValues;\n                    }\n                    singularValues_flipped[1] *= -1.0;\n                    flipped_sigma = true;\n                }\n            }\n            else if(mtr.determinant() < 0.0) {\n                singularValues_flipped = Eigen::JacobiSVD<MatrixType>::m_singularValues;\n                singularValues_flipped[1] *= -1.0;\n                flipped_sigma = true;\n            }\n            \n            if(std::isnan(singularValues()[0]) || std::isnan(singularValues()[1])) {\n                // degenerated case\n                singularValues_flipped.setZero();\n                flipped_sigma = true;\n                if(fullUComputed && fullVComputed) {\n                    matrixU_flipped.setIdentity();\n                    matrixV_flipped.setIdentity();\n                    flipped_U = flipped_V = true;\n                }\n            }\n        }\n        \n        //TODO: merge with IglUtils::computeCofactorMtr\n        template<int dim>\n        void computeCofactorMtr(const Eigen::Matrix<double, dim, dim>& F,\n                                Eigen::Matrix<double, dim, dim>& A)\n        {\n            switch(dim) {\n                case 2:\n                    A(0, 0) = F(1, 1);\n                    A(0, 1) = -F(1, 0);\n                    A(1, 0) = -F(0, 1);\n                    A(1, 1) = F(0, 0);\n                    break;\n                    \n                case 3:\n                    A(0, 0) = F(1, 1) * F(2, 2) - F(1, 2) * F(2, 1);\n                    A(0, 1) = F(1, 2) * F(2, 0) - F(1, 0) * F(2, 2);\n                    A(0, 2) = F(1, 0) * F(2, 1) - F(1, 1) * F(2, 0);\n                    A(1, 0) = F(0, 2) * F(2, 1) - F(0, 1) * F(2, 2);\n                    A(1, 1) = F(0, 0) * F(2, 2) - F(0, 2) * F(2, 0);\n                    A(1, 2) = F(0, 1) * F(2, 0) - F(0, 0) * F(2, 1);\n                    A(2, 0) = F(0, 1) * F(1, 2) - F(0, 2) * F(1, 1);\n                    A(2, 1) = F(0, 2) * F(1, 0) - F(0, 0) * F(1, 2);\n                    A(2, 2) = F(0, 0) * F(1, 1) - F(0, 1) * F(1, 0);\n                    break;\n                    \n                default:\n                    assert(0 && \"dim not 2 or 3\");\n                    break;\n            }\n        }\n        void fastEigenvalues(const Eigen::Matrix3d& A_Sym,\n                             Eigen::Vector3d& lambda)\n        // 24 mults, 20 adds, 1 atan2, 1 sincos, 2 sqrts\n        {\n            using T = double;\n            using std::max;\n            using std::swap;\n            T m = ((T)1 / 3) * (A_Sym(0, 0) + A_Sym(1, 1) + A_Sym(2, 2));\n            T a00 = A_Sym(0, 0) - m;\n            T a11 = A_Sym(1, 1) - m;\n            T a22 = A_Sym(2, 2) - m;\n            T a12_sqr = A_Sym(0, 1) * A_Sym(0, 1);\n            T a13_sqr = A_Sym(0, 2) * A_Sym(0, 2);\n            T a23_sqr = A_Sym(1, 2) * A_Sym(1, 2);\n            T p = ((T)1 / 6) * (a00 * a00 + a11 * a11 + a22 * a22 + 2 * (a12_sqr + a13_sqr + a23_sqr));\n            T q = (T).5 * (a00 * (a11 * a22 - a23_sqr) - a11 * a13_sqr - a22 * a12_sqr) + A_Sym(0, 1) * A_Sym(0, 2) * A_Sym(1, 2);\n            T sqrt_p = sqrt(p);\n            T disc = p * p * p - q * q;\n            T phi = ((T)1 / 3) * atan2(sqrt(max((T)0, disc)), q);\n            T c = cos(phi), s = sin(phi);\n            T sqrt_p_cos = sqrt_p * c;\n            T root_three_sqrt_p_sin = sqrt((T)3) * sqrt_p * s;\n            lambda(0) = m + 2 * sqrt_p_cos;\n            lambda(1) = m - sqrt_p_cos - root_three_sqrt_p_sin;\n            lambda(2) = m - sqrt_p_cos + root_three_sqrt_p_sin;\n            if (lambda(0) < lambda(1))\n                swap(lambda(0), lambda(1));\n            if (lambda(1) < lambda(2))\n                swap(lambda(1), lambda(2));\n            if (lambda(0) < lambda(1))\n                swap(lambda(0), lambda(1));\n        }\n        void fastEigenvectors(const Eigen::Matrix3d& A_Sym,\n                              const Eigen::Vector3d& lambda,\n                              Eigen::Matrix3d& V)\n        // 71 mults, 44 adds, 3 divs, 3 sqrts\n        {\n            // flip if necessary so that first eigenvalue is the most different\n            using T = double;\n            using std::sqrt;\n            using std::swap;\n            bool flipped = false;\n            Eigen::Vector3d lambda_flip(lambda);\n            if (lambda(0) - lambda(1) < lambda(1) - lambda(2)) { // 2a\n                swap(lambda_flip(0), lambda_flip(2));\n                flipped = true;\n            }\n            \n            // get first eigenvector\n            Eigen::Matrix3d C1;\n            computeCofactorMtr<3>(A_Sym - lambda_flip(0) * Eigen::Matrix3d::Identity(), C1);\n            Eigen::Matrix3d::Index i;\n            T norm2 = C1.colwise().squaredNorm().maxCoeff(&i); // 3a + 12m+6a + 9m+6a+1d+1s = 21m+15a+1d+1s\n            Eigen::Vector3d v1;\n            if (norm2 != 0) {\n                T one_over_sqrt = (T)1 / sqrt(norm2);\n                v1 = C1.col(i) * one_over_sqrt;\n            }\n            else\n                v1 << 1, 0, 0;\n            \n            // form basis for orthogonal complement to v1, and reduce A to this space\n            Eigen::Vector3d v1_orthogonal = v1.unitOrthogonal(); // 6m+2a+1d+1s (tweak: 5m+1a+1d+1s)\n            Eigen::Matrix<T, 3, 2> other_v;\n            other_v.col(0) = v1_orthogonal;\n            other_v.col(1) = v1.cross(v1_orthogonal); // 6m+3a (tweak: 4m+1a)\n            Eigen::Matrix2d A_reduced = other_v.transpose() * A_Sym * other_v; // 21m+12a (tweak: 18m+9a)\n            \n            // find third eigenvector from A_reduced, and fill in second via cross product\n            Eigen::Matrix2d C3;\n            computeCofactorMtr<2>(A_reduced - lambda_flip(2) * Eigen::Matrix2d::Identity(), C3);\n            Eigen::Matrix2d::Index j;\n            norm2 = C3.colwise().squaredNorm().maxCoeff(&j); // 3a + 12m+6a + 9m+6a+1d+1s = 21m+15a+1d+1s\n            Eigen::Vector3d v3;\n            if (norm2 != 0) {\n                T one_over_sqrt = (T)1 / sqrt(norm2);\n                v3 = other_v * C3.col(j) * one_over_sqrt;\n            }\n            else\n                v3 = other_v.col(0);\n            \n            Eigen::Vector3d v2 = v3.cross(v1); // 6m+3a\n            \n            // finish\n            if (flipped) {\n                V.col(0) = v3;\n                V.col(1) = v2;\n                V.col(2) = -v1;\n            }\n            else {\n                V.col(0) = v1;\n                V.col(1) = v2;\n                V.col(2) = v3;\n            }\n        }\n        void fastSolveEigenproblem(const Eigen::Matrix3d& A_Sym,\n                                   Eigen::Vector3d& lambda,\n                                   Eigen::Matrix3d& V)\n        // 71 mults, 44 adds, 3 divs, 3 sqrts\n        {\n            fastEigenvalues(A_Sym, lambda);\n            fastEigenvectors(A_Sym, lambda, V);\n        }\n        \n        void fastSVD3d(const Eigen::Matrix3d& A,\n                       Eigen::Matrix3d& U,\n                       Eigen::Vector3d& singular_values,\n                       Eigen::Matrix3d& V)\n        // 182 mults, 112 adds, 6 divs, 11 sqrts, 1 atan2, 1 sincos\n        {\n            using T = double;\n            // decompose normal equations\n            Eigen::Vector3d lambda;\n            fastSolveEigenproblem(A.transpose() * A, lambda, V);\n            \n            // compute singular values\n            if (lambda(2) < 0)\n                lambda = (lambda.array() >= (T)0).select(lambda, (T)0);\n            singular_values = lambda.array().sqrt();\n            if (A.determinant() < 0)\n                singular_values(2) = -singular_values(2);\n            \n            // compute singular vectors\n            U.col(0) = A * V.col(0);\n            T norm = U.col(0).norm();\n            if (norm != 0) {\n                T one_over_norm = (T)1 / norm;\n                U.col(0) = U.col(0) * one_over_norm;\n            }\n            else\n                U.col(0) << 1, 0, 0;\n            Eigen::Vector3d v1_orthogonal = U.col(0).unitOrthogonal();\n            Eigen::Matrix<T, 3, 2> other_v;\n            other_v.col(0) = v1_orthogonal;\n            other_v.col(1) = U.col(0).cross(v1_orthogonal);\n            Eigen::Vector2d w = other_v.transpose() * A * V.col(1);\n            norm = w.norm();\n            if (norm != 0) {\n                T one_over_norm = (T)1 / norm;\n                w = w * one_over_norm;\n            }\n            else\n                w << 1, 0;\n            U.col(1) = other_v * w;\n            U.col(2) = U.col(0).cross(U.col(1));\n        }\n        \n        void fastComputeSingularValues3d(const Eigen::Matrix3d& A,\n                                         Eigen::Vector3d& singular_values)\n        {\n            using T = double;\n            // decompose normal equations\n            Eigen::Vector3d lambda;\n            fastEigenvalues(A.transpose() * A, lambda);\n            \n            // compute singular values\n            if (lambda(2) < 0)\n                lambda = (lambda.array() >= (T)0).select(lambda, (T)0);\n            singular_values = lambda.array().sqrt();\n            if (A.determinant() < 0)\n                singular_values(2) = -singular_values(2);\n        }\n        \n    public:\n        const typename Eigen::JacobiSVD<MatrixType>::SingularValuesType& singularValues(void) const {\n            if(flipped_sigma) {\n                return singularValues_flipped;\n            }\n            else {\n                return Eigen::JacobiSVD<MatrixType>::singularValues();\n            }\n        }\n        const MatrixType& matrixU(void) const {\n            if(flipped_U) {\n                return matrixU_flipped;\n            }\n            else {\n                return Eigen::JacobiSVD<MatrixType>::matrixU();\n            }\n        }\n        const MatrixType& matrixV(void) const {\n            if(flipped_V) {\n                return matrixV_flipped;\n            }\n            else {\n                return Eigen::JacobiSVD<MatrixType>::matrixV();\n            }\n        }\n\n        void setIdentity(void) {\n            flipped_sigma=true;\n            flipped_V=true;\n            flipped_U=true;\n\n            matrixU_flipped.setIdentity();\n            matrixV_flipped.setIdentity();\n            singularValues_flipped.setOnes();\n        }\n    };\n    \n}\n\n#endif /* AutoFlipSVD_hpp */\n", "meta": {"hexsha": "e8f2fe0b904710ddb4fae5df28f2fe6c624398d3", "size": 14211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/AutoFlipSVD.hpp", "max_stars_repo_name": "liminchen/DOT", "max_stars_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T00:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T14:35:54.000Z", "max_issues_repo_path": "src/Utils/AutoFlipSVD.hpp", "max_issues_repo_name": "liminchen/DOT", "max_issues_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/AutoFlipSVD.hpp", "max_forks_repo_name": "liminchen/DOT", "max_forks_repo_head_hexsha": "26525fba815fb081e90676321e42d0a60ecb0cb1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T05:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T22:49:53.000Z", "avg_line_length": 39.0412087912, "max_line_length": 130, "alphanum_fraction": 0.4657659559, "num_tokens": 3878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5558245452390919}}
{"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_JACOBIAN_HPP\n#define RW_MATH_JACOBIAN_HPP\n\n/**\n * @file math/Jacobian.hpp\n */\n\n#if !defined(SWIG)\n#include <rw/common/Serializable.hpp>\n#include <rw/math/Q.hpp>\n#include <rw/math/Rotation3D.hpp>\n#include <rw/math/Transform3D.hpp>\n#include <rw/math/VelocityScrew6D.hpp>\n\n#include <Eigen/Core>\n#endif\nnamespace rw {\nnamespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A Jacobian class. A jacobian with m rows and n columns.\n     *\n     * An ordinary robot jacobian defined over the joints 0 to n with\n     * configuration \\b q is expressed as a @f$ 6\\times n @f$ matrix:\n     * \\f[\n     * \\robabx{0}{n}{\\bf{J}}(\\bf{q}) = [\n     * \\robabx{0}{1}{\\bf{J}}(\\bf{q}),\n     * \\robabx{1}{2}{\\bf{J}}(\\bf{q}),...,\n     * \\robabx{n-1}{n}{\\bf{J}}(\\bf{q}) ]\n     * \\f]\n     *\n     */\n    class Jacobian\n    {\n      public:\n        //! @brief The type of the internal Eigen matrix implementation.\n        typedef Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > Base;\n\n        /**\n         * @brief Creates an empty @f$ m\\times n @f$ (uninitialized) Jacobian matrix\n         *\n         * @param m [in] number of rows\n         *\n         * @param n [in] number of columns\n         */\n        Jacobian (size_t m, size_t n) : _jac (m, n) {}\n\n        /**\n         * @brief Default constructor\n         */\n        Jacobian () {}\n\n        /**\n           @brief The number of rows.\n         */\n        size_t size1 () const { return _jac.rows (); }\n\n        /**\n           @brief The number of columns.\n         */\n        size_t size2 () const { return _jac.cols (); }\n\n        /**\n         * @brief Creates an empty @f$ 6\\times n @f$ (uninitialized) Jacobian matrix\n         *\n         * @param n [in] number of columns\n         */\n        explicit Jacobian (size_t n) : _jac (6, n) {}\n\n        /**\n         * @brief Creates a Jacobian from a Eigen::MatrixBase\n         *\n         * @param r [in] an Eigen Matrix\n         */\n        template< class R > explicit Jacobian (const Eigen::MatrixBase< R >& r) : _jac (r) {}\n\n        /**\n         * @brief Construct zero initialized Jacobian.\n         * @param size1 [in] number of rows.\n         * @param size2 [in] number of columns.\n         * @return zero-initialized jacobian.\n         */\n        static Jacobian zero (size_t size1, size_t size2)\n        {\n            return Jacobian (\n                Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Zero (size1, size2));\n        }\n\n        /**\n         * @brief Accessor for the internal Eigen matrix state.\n         */\n        Base& e () { return _jac; }\n\n        /**\n         * @brief Accessor for the internal Eigen matrix state.\n         */\n        const Base& e () const { return _jac; }\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        double& operator() (size_t row, size_t column) { return _jac (row, column); }\n\n        /**\n         * @brief Returns reference to matrix element\n         * @param row [in] row\n         * @param column [in] column\n         * @return reference to the element\n         */\n        const double& operator() (size_t row, size_t column) const { return _jac (row, column); }\n#else\n        MATRIXOPERATOR (double);\n#endif\n        /**\n         * @brief Get an element of the jacobian.\n         * @param row [in] the row.\n         * @param col [in] the column.\n         * @return reference to the element.\n         */\n        double& elem (size_t row, size_t col) { return _jac (row, col); }\n\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Creates the velocity transform jacobian\n         * @f$ \\robabcdx{a}{b}{a}{b}{\\bf{J_v}} @f$\n         * for transforming both the reference frame and the velocity\n         * reference point from one frame \\b b to another frame \\b a\n         *\n         * @param aTb [in] @f$ \\robabx{a}{b}{\\bf{T}} @f$\n         *\n         * @return @f$ \\robabcdx{a}{b}{a}{b}{\\bf{J_v}} @f$\n         *\n         * \\f[\n         * \\robabcdx{a}{b}{a}{b}{\\bf{J_v}} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & S(\\robabx{a}{b}{\\mathbf{d}})\\robabx{a}{b}{\\mathbf{R}} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         * Change the frame of reference from \\b b to frame \\b a and reference point\n         * from frame \\b a to frame \\b b:\n         * @f$ \\robabx{a}{b}{\\bf{J}} =  \\robabcdx{a}{b}{a}{b}{\\bf{J}_v} \\cdot \\robabx{b}{a}{\\bf{J}}\n         * @f$\n         */\n\n#endif \n        explicit Jacobian (const rw::math::Transform3D<double>& aTb);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Creates the velocity transform jacobian\n         * @f$ \\robabcdx{a}{b}{i}{i}{\\bf{J_v}} @f$\n         * for transforming a velocity screw from one frame of reference \\b b to\n         * another frame \\b a\n         *\n         * @param aRb [in] @f$ \\robabx{a}{b}{\\bf{R}} @f$\n         *\n         * @return @f$ \\robabcdx{a}{b}{i}{i}{\\bf{J}_v} @f$\n         *\n         * \\f[\n         * \\robabcdx{a}{b}{i}{i}{\\bf{J_v}} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & \\mathbf{0}^{3x3} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         * Change the frame of reference from \\b b to frame \\b a :\n         * @f$ \\robabx{a}{c}{\\bf{J}} =  \\robabcdx{a}{b}{c}{c}{\\bf{J}_v} \\cdot \\robabx{b}{c}{\\bf{J}}\n         * @f$\n         *\n         */\n\n#endif \n        explicit Jacobian (const rw::math::Rotation3D<>& aRb);\n\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Creates the velocity transform jacobian\n         * @f$ \\robabcdx{i}{i}{b}{a}{\\bf{J}_v} @f$\n         * for transforming the reference point of a velocity screw from one\n         * frame \\b b to another frame \\b a\n         *\n         * @param aPb [in] @f$ \\robabx{a}{b}{\\bf{P}} @f$\n         *\n         * @return @f$ \\robabcdx{i}{i}{b}{a}{\\bf{J}_v} @f$\n         *\n         * \\f[\n         * \\robabcdx{i}{i}{b}{a}{\\bf{J}_v} =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\bf{I}^{3x3} & S(\\robabx{a}{b}{\\bf{P}}) \\\\\n         *    \\bf{0}^{3x3} & \\bf{I}^{3x3}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         *  transforming the reference point of a Jacobian from\n         * frame \\b c to frame \\b d :\n         * @f$ \\robabx{a}{d}{\\mathbf{J}} =  \\robabcdx{a}{a}{c}{d}{\\mathbf{J_v}} \\cdot\n         * \\robabx{a}{c}{\\mathbf{J}} @f$\n         */\n\n#endif\n        explicit Jacobian (const rw::math::Vector3D<>& aPb);\n\n        /**\n         * @brief add rotation jacobian to a specific row and column in this jacobian\n         * @param part\n         * @param row\n         * @param col\n         */\n        void addRotation (const rw::math::Vector3D<>& part, size_t row, size_t col);\n\n        /**\n         * @brief add position jacobian to a specific row and column in this jacobian\n         * @param part\n         * @param row\n         * @param col\n         */\n        void addPosition (const rw::math::Vector3D<>& part, size_t row, size_t col);\n\n      private:\n        Base _jac;\n    };\n\n    /**\n     * @brief Calculates velocity vector\n     * @param Jq [in] the jacobian @f$ \\mathbf{J}_{\\mathbf{q}} @f$\n     * @param dq [in] the joint velocity vector @f$ \\dot{\\mathbf{q}} @f$\n     * @return the velocity vector @f$ \\mathbf{\\nu} @f$\n     * @relates Jacobian\n     */\n    inline const rw::math::VelocityScrew6D<> operator* (const Jacobian& Jq, const rw::math::Q& dq)\n    {\n        return rw::math::VelocityScrew6D<> (Jq.e () * dq.e ());\n    }\n\n    /**\n     * @brief Calculates joint velocities\n     *\n     * @param JqInv [in] the inverse jacobian @f$ \\mathbf{J}_{\\mathbf{q}}^{-1} @f$\n     *\n     * @param v [in] the velocity vector @f$ \\mathbf{\\nu} @f$\n     *\n     * @return the joint velocity vector @f$ \\dot{\\mathbf{q}} @f$\n     *\n     * @relates Jacobian\n     */\n    inline const rw::math::Q operator* (const Jacobian& JqInv, const rw::math::VelocityScrew6D<>& v)\n    {\n        return rw::math::Q (JqInv.e () * v.e ());\n        // prod(JqInv.m(), v.m()));\n    }\n\n    /**\n     * @brief Multiplies jacobians @f$ \\mathbf{J} = \\mathbf{J}_1 *\n     * \\mathbf{J}_2 @f$\n     *\n     * @param j1 [in] @f$ \\mathbf{J}_1 @f$\n     *\n     * @param j2 [in] @f$ \\mathbf{J}_2 @f$\n     *\n     * @return @f$ \\mathbf{J} @f$\n     *\n     * @relates Jacobian\n     */\n    inline const Jacobian operator* (const Jacobian& j1, const Jacobian& j2)\n    {\n        return Jacobian (j1.e () * j2.e ());\n        // return Jacobian(prod(j1.m(), j2.m()));\n    }\n\n    /**\n       @brief Streaming operator.\n\n       @relates Jacobian\n    */\n    inline std::ostream& operator<< (std::ostream& out, const Jacobian& v) { return out << v.e (); }\n\n    /**\n       @brief Rotates each column of \\b v by \\b r.\n\n       The Jacobian must be of height 6.\n\n       @relates Jacobian\n    */\n    const Jacobian operator* (const rw::math::Rotation3D<>& r, const Jacobian& v);\n\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::Jacobian\n         */\n        template<>\n        void write (const rw::math::Jacobian& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Jacobian\n         */\n        template<>\n        void read (rw::math::Jacobian& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "8b79288e9bbc3cfc71fb3e03ba6f37e88af4d87c", "size": 10775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Jacobian.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/Jacobian.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/Jacobian.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9626436782, "max_line_length": 100, "alphanum_fraction": 0.5139675174, "num_tokens": 3189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.5558245423685966}}
{"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 chi_squared.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 <boost/math/distributions.hpp>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/scalar_matrix.hpp>\n\n#include \"uniform_distribution.hpp\"\n#include \"interface/evaluation.hpp\"\n#include \"interface/standard_gaussian_mapping.hpp\"\n\nnamespace fl\n{\n\n/**\n * \\ingroup distributions\n *\n * \\brief ChiSquared represents a univariate Chi-squared distribution\n * \\f$\\chi^2_k\\f$, with \\f$k \\in \\mathbb{N}^{*}\\f$ degrees-of-freedom\n */\nclass ChiSquared\n    : public Evaluation<ScalarMatrix>,\n      public StandardGaussianMapping<ScalarMatrix, 1>\n{\nprivate:\n    typedef StandardGaussianMapping<ScalarMatrix, 1> StdGaussianMappingBase;\n\npublic:\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 ScalarMatrix Variate;\n\n    /**\n     * \\brief StandardVariate type which is used to sample from and mapped it\n     * into the distribution space\n     */\n    typedef typename StdGaussianMappingBase::StandardVariate StandardVariate;\n\npublic:\n    /**\n     * 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 Vector at compile time is fixed, this will\n     *                  be adapted. For dynamic-sized Variable the dimension is\n     *                  initialized to 0.\n     */\n    explicit ChiSquared(Real degrees_of_freedom)\n       : StdGaussianMappingBase(1),\n        chi2_(degrees_of_freedom)\n    { }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~ChiSquared() noexcept { }\n\n    /**\n     * \\brief Returns aa 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 n    Standard normal sample\n     *\n     * \\throws See Gaussian<Variate>::map_standard_normal\n     */\n    virtual Variate map_standard_uniform(const StandardVariate& n) const\n    {\n        return boost::math::quantile(chi2_, n);\n    }\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 n    Standard normal sample\n     *\n     * \\throws See Gaussian<Variate>::map_standard_normal\n     */\n    Variate map_standard_normal(const StandardVariate& n) const override\n    {\n        return map_standard_uniform(uniform_.map_standard_normal(n));\n    }\n\n    /**\n     * \\brief Returns the log probability of the given sample \\c variate\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& variate) const override\n    {\n        assert(variate.size() == 1);\n        return std::log(probability(variate));\n    }\n\n    /**\n     * \\brief Evaluates the probability for the specified variate.\n     *\n     * \\param variate Sample \\f$x\\f$ to evaluate\n     *\n     * \\return \\f$p(x)\\f$\n     */\n    Real probability(const Variate& variate) const override\n    {\n        assert(variate.size() == 1);\n        return boost::math::pdf(chi2_, variate);\n    }\n\n    /**\n     * \\brief Returns t-distribution degree-of-freedom\n     */\n    Real degrees_of_freedom() const\n    {\n        return chi2_.degrees_of_freedom();\n    }\n\n    /**\n     * \\brief Sets t-distribution degree-of-freedom\n     */\n    void degrees_of_freedom(Real dof)\n    {\n        chi2_ = boost::math::chi_squared_distribution<Real>(dof);\n    }\n\nprotected:\n    /** \\cond internal */\n    UniformDistribution uniform_;\n    boost::math::chi_squared_distribution<Real> chi2_;\n    /** \\endcond */\n};\n\n}\n", "meta": {"hexsha": "8f3d9349512a3c66cabd76181bb12e8a0032b07c", "size": 4581, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/chi_squared.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/chi_squared.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/chi_squared.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.2777777778, "max_line_length": 80, "alphanum_fraction": 0.6511678673, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5558028033300568}}
{"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 RBF\n    : public FiniteDifferentiator<RBF<_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;                 // TODO: treat 1x1 matrix as scalar using Matrix11ToScalar\n    typedef Eigen::Matrix<double, DimOut, 1> Value;\n    typedef Eigen::Matrix<double, DimOut, DimIn> Gradient;\n    typedef PolynomialBasisGenT<DimIn, DegreePolynomial> PolynomialBasisGen;\n    typedef RBFKernel_Bivariate<DimIn, _RBFKernel_Core> Kernel;\n    typedef std::pair<Point, Value> Constraint;\n    \n    std::vector<Constraint> constraints;\n    Kernel kernel;\n    Eigen::Matrix<double, -1, DimOut> weights;\n    Eigen::MatrixXd A_matrix;\n    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> A_factorized;\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    void factorize() {\n        const int P = PolynomialBasisGen::DimOut;\n        const size_t n = constraints.size();\n        const int m = n + P;\n        A_matrix = Eigen::MatrixXd::Zero(m, m);\n        for (size_t i = 0; i < n; ++i) {\n            const Point& point_i = constraints[i].first;\n            // rbf part\n            A_matrix(i, i) = kernel.univariate(0);\n            for (size_t j = i + 1; j < n; ++j) {\n                const Point& point_j = constraints[j].first;\n                A_matrix(i, j) = A_matrix(j, i) = kernel(point_i, point_j);\n            }\n            // polynomial part\n            A_matrix.block<P, 1>(n, i) << PolynomialBasisGen::basis(point_i);\n            A_matrix.block<1, P>(i, n) = A_matrix.block<P, 1>(n, i).transpose();\n        }\n        A_factorized.compute(A_matrix);         // factorize\n    }\n    void solve() {\n        const int P = PolynomialBasisGen::DimOut;\n        const size_t n = constraints.size();\n        const int m = n + P;\n        Eigen::Matrix<double, -1, DimOut> b;\n        b.setZero(m, DimOut);\n        // constraint part\n        for (size_t i = 0; i < n; ++i) {\n            const Value& value_i = constraints[i].second;\n            b.row(i).transpose() << value_i;\n        }\n        // polynomial part is just 0\n        weights = A_factorized.solve(b);        // solve\n    }\n    void factorize_and_solve() {\n        factorize();\n        solve();\n    }\n    Value operator()(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        Value result = Value::Zero();\n        // rbf part\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].first;\n            result += kernel(point, point_i) * weights.row(i).transpose();\n        }\n        // polynomial part\n        auto basis = PolynomialBasisGen::basis(point);\n        result += (basis.transpose() * weights.bottomRows(P)).transpose();\n        return result;\n    }\n    Gradient gradient(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        Gradient result = Gradient::Zero();\n        // rbf part\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].first;\n            result += weights.row(i).transpose() * kernel.gradient(point, point_i);\n        }\n        // polynomial part\n        auto b_gradient = PolynomialBasisGen::gradient(point);\n        result += weights.bottomRows(P).transpose() * b_gradient;\n        return result;\n    }\n};\n\n}\n\n", "meta": {"hexsha": "32eb408ddfcaac351c2aa1996bec7681a4c45240", "size": 3858, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/RBF.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/RBF.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/RBF.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.7222222222, "max_line_length": 126, "alphanum_fraction": 0.5956454121, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.5558027911855149}}
{"text": "/**\n * @file expfittedupwind_main.cc\n * @brief NPDE homework ExpFittedUpwind\n * @author Amélie Loher, Philippe Peter\n * @date 07.01.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n\n#include \"expfittedupwind.h\"\n\nint main() {\n  // Define Mesh-independent Data:\n  //====================\n  // Your code goes here\n  //====================\n\n  // Output file\n  std::ofstream L2output;\n  L2output.open(\"L2error.txt\");\n  L2output << \"No. of dofs, L2 error\" << std::endl;\n\n  // generate a mesh hierarchy:\n  unsigned int reflevels = 6;\n  std::unique_ptr<lf::mesh::MeshFactory> mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  auto top_mesh = builder.Build();\n\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(top_mesh,\n                                                              reflevels);\n  lf::refinement::MeshHierarchy& multi_mesh{*multi_mesh_p};\n  multi_mesh.PrintInfo(std::cout);\n\n  // get number of levels:\n  auto L = multi_mesh.NumLevels();\n\n  // perform computations on all levels:\n  for (int l = 0; l < L; ++l) {\n    // Compute finite element solution and compute L2 error on current level:\n    double L2_err = 1.0;\n\n    // get current mesh and fe space\n    auto mesh_p = multi_mesh.getMesh(l);\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n    const lf::assemble::DofHandler& dofh{fe_space->LocGlobMap()};\n    const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n\n    //====================\n    // Your code goes here\n    //====================\n\n    L2output << N_dofs << \", \" << L2_err << std::endl;\n    std::cout << N_dofs << \",\" << L2_err << std::endl;\n  }\n\n  L2output.close();\n\n  // Plot the computed L2 error\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_error.py \" CURRENT_BINARY_DIR\n              \"/L2error.txt \" CURRENT_BINARY_DIR \"/results.eps\");\n\n  return 0;\n}\n", "meta": {"hexsha": "84609aaba8b9bab62bf7ed01cbf2f0e693dae898", "size": 2508, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ExpFittedUpwind/templates/expfittedupwind_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.1627906977, "max_line_length": 80, "alphanum_fraction": 0.6411483254, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.5557974315881934}}
{"text": "/*\n * H2L2.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/H2L2.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>\nH2L2<dim>::H2L2(double alpha, double beta) : alpha_(alpha), beta_(beta) {}\n\ntemplate <int dim>\ndouble H2L2<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    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 H2L2<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    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 H2L2<dim>::dot_transform(DiscretizedFunction<dim>& u) {\n  u.mult_mass();\n  dot_solve_mass_and_transform(u);\n}\n\ntemplate <int dim>\nvoid H2L2<dim>::dot_transform_inverse(DiscretizedFunction<dim>& u) {\n  u.solve_mass();\n  dot_mult_mass_and_transform_inverse(u);\n}\n\ntemplate <int dim>\nvoid H2L2<dim>::dot_solve_mass_and_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,\n  // M (blocks of mass matrices) is already taken care of, D = derivative, T = trapezoidal rule\n\n  auto dx  = u.calculate_derivative();\n  auto d2x = u.calculate_second_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    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 H2L2<dim>::factorize_matrix(std::shared_ptr<SpaceTimeMesh<dim>> mesh) {\n  deallog << \"factorizing matrix\" << std::endl;\n\n  SparsityPattern pattern(mesh->length(), mesh->length(), 5);\n\n  for (size_t i = 0; i < 3; i++)\n    for (size_t j = 0; j < 3; j++)\n      pattern.add(i, j);\n\n  for (size_t i = 3; i < mesh->length() - 3; i++) {\n    // fill row i and column i\n    for (int j = -2; j <= 2; j++) {\n      pattern.add(i, i + j);\n      pattern.add(i + j, i);\n    }\n  }\n\n  for (size_t i = 0; i < 3; i++)\n    for (size_t j = 0; j < 3; j++)\n      pattern.add(mesh->length() - 1 - i, mesh->length() - 1 - j);\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 p20 = 1.0 * 16 / pow4(mesh->get_time(2) - mesh->get_time(0));\n  double p10 = 1.0 / pow4(mesh->get_time(1) - mesh->get_time(0));\n  double p31 = 1.0 * 16 / pow4(mesh->get_time(3) - mesh->get_time(1));\n  double p42 = 1.0 * 16 / pow4(mesh->get_time(4) - mesh->get_time(2));\n\n  matrix.set(0, 0, lambdas[0] * p10 + lambdas[1] * p20);\n  matrix.set(1, 1, 4 * lambdas[0] * p10 + 4 * lambdas[1] * p20 + lambdas[2] * p31);\n  matrix.set(2, 2, lambdas[0] * p10 + lambdas[1] * p20 + 4 * lambdas[2] * p31 + lambdas[3] * p42);\n\n  matrix.set(0, 1, -2 * lambdas[0] * p10 - 2 * lambdas[1] * p20);\n  matrix.set(1, 0, -2 * lambdas[0] * p10 - 2 * lambdas[1] * p20);\n\n  matrix.set(0, 2, lambdas[0] * p10 + lambdas[1] * p20);\n  matrix.set(2, 0, lambdas[0] * p10 + lambdas[1] * p20);\n\n  matrix.set(1, 2, -2 * lambdas[0] * p10 - 2 * lambdas[1] * p20 - 2 * lambdas[2] * p31);\n  matrix.set(2, 1, -2 * lambdas[0] * p10 - 2 * lambdas[1] * p20 - 2 * lambdas[2] * p31);\n\n  for (size_t i = 3; i < mesh->length() - 3; i++) {\n    // fill row i and column i\n\n    double p20  = 1.0 * 16 / pow4(mesh->get_time(i + 2) - mesh->get_time(i));\n    double p0m2 = 1.0 * 16 / pow4(mesh->get_time(i - 2) - mesh->get_time(i));\n    double p1m1 = 1.0 * 16 / pow4(mesh->get_time(i + 1) - mesh->get_time(i - 1));\n\n    matrix.set(i, i, lambdas[i + 1] * p20 + 4 * lambdas[i] * p1m1 + lambdas[i - 1] * p0m2);\n\n    matrix.set(i, i - 1, -2 * lambdas[i - 1] * p0m2 - 2 * lambdas[i] * p1m1);\n    matrix.set(i - 1, i, -2 * lambdas[i - 1] * p0m2 - 2 * lambdas[i] * p1m1);\n\n    matrix.set(i, i + 1, -2 * lambdas[i + 1] * p20 - 2 * lambdas[i] * p1m1);\n    matrix.set(i + 1, i, -2 * lambdas[i + 1] * p20 - 2 * lambdas[i] * p1m1);\n\n    matrix.set(i, i + 2, lambdas[i + 1] * p20);\n    matrix.set(i + 2, i, lambdas[i + 1] * p20);\n\n    matrix.set(i, i - 2, lambdas[i - 1] * p0m2);\n    matrix.set(i - 2, i, lambdas[i - 1] * p0m2);\n  }\n\n  // (symmetric to the first entries)\n  size_t N = mesh->length() - 1;  // makes it easier to read\n\n  p20 = 1.0 * 16 / pow4(mesh->get_time(N - 2) - mesh->get_time(N - 0));\n  p10 = 1.0 / pow4(mesh->get_time(N - 1) - mesh->get_time(N - 0));\n  p31 = 1.0 * 16 / pow4(mesh->get_time(N - 3) - mesh->get_time(N - 1));\n  p42 = 1.0 * 16 / pow4(mesh->get_time(N - 4) - mesh->get_time(N - 2));\n\n  matrix.set(N - 0, N - 0, lambdas[N - 0] * p10 + lambdas[N - 1] * p20);\n  matrix.set(N - 1, N - 1, 4 * lambdas[N - 0] * p10 + 4 * lambdas[N - 1] * p20 + lambdas[N - 2] * p31);\n  matrix.set(N - 2, N - 2,\n             lambdas[N - 0] * p10 + lambdas[N - 1] * p20 + 4 * lambdas[N - 2] * p31 + lambdas[N - 3] * p42);\n\n  matrix.set(N - 0, N - 1, -2 * lambdas[N - 0] * p10 - 2 * lambdas[N - 1] * p20);\n  matrix.set(N - 1, N - 0, -2 * lambdas[N - 0] * p10 - 2 * lambdas[N - 1] * p20);\n\n  matrix.set(N - 0, N - 2, lambdas[N - 0] * p10 + lambdas[N - 1] * p20);\n  matrix.set(N - 2, N - 0, lambdas[N - 0] * p10 + lambdas[N - 1] * p20);\n\n  matrix.set(N - 1, N - 2, -2 * lambdas[N - 0] * p10 - 2 * lambdas[N - 1] * p20 - 2 * lambdas[N - 2] * p31);\n  matrix.set(N - 2, N - 1, -2 * lambdas[N - 0] * p10 - 2 * lambdas[N - 1] * p20 - 2 * lambdas[N - 2] * p31);\n\n  matrix *= beta_;\n\n  // H1 part (+ trapezoidal rule)\n  SparseMatrix<double> matrixH1(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  matrixH1.set(0, 0, lambdas[1] * sq20 + lambdas[0] * sq10);\n  matrixH1.set(1, 1, lambdas[2] * sq31 + lambdas[0] * sq10);\n  matrixH1.set(0, 1, -lambdas[0] * sq10);\n  matrixH1.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    matrixH1.set(i, i, lambdas[i + 1] * sq20 + lambdas[i - 1] * sq0m2);\n\n    matrixH1.set(i, i - 2, -lambdas[i - 1] * sq0m2);\n    matrixH1.set(i - 2, i, -lambdas[i - 1] * sq0m2);\n\n    matrixH1.set(i, i + 2, -lambdas[i + 1] * sq20);\n    matrixH1.set(i + 2, i, -lambdas[i + 1] * sq20);\n  }\n\n  // (symmetric to the first entries)\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  matrixH1.set(N, N - 0, lambdas[N - 1] * sq20 + lambdas[N] * sq10);\n  matrixH1.set(N - 1, N - 1, lambdas[N - 2] * sq31 + lambdas[N] * sq10);\n  matrixH1.set(N, N - 1, -lambdas[N] * sq10);\n  matrixH1.set(N - 1, N, -lambdas[N] * sq10);\n\n  matrix.add(alpha_, matrixH1);\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 H2L2<dim>::dot_mult_mass_and_transform_inverse(DiscretizedFunction<dim>& u) {\n  auto mesh = u.get_mesh();\n\n  LogStream::Prefix p(\"h2l2_transform\");\n  Timer timer;\n  timer.start();\n\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>\nstd::string H2L2<dim>::name() const {\n  return \"H²([0,T], L²(Ω))\";\n}\n\ntemplate <int dim>\nstd::string H2L2<dim>::unique_id() const {\n  return \"H²([0,T], L²(Ω)) with α=\" + std::to_string(alpha_) + \", β=\" + std::to_string(beta_);\n}\n\ntemplate class H2L2<1>;\ntemplate class H2L2<2>;\ntemplate class H2L2<3>;\n\n} /* namespace norms */\n} /* namespace wavepi */\n", "meta": {"hexsha": "2a10f0abc584016868e60c809e5de9e8ea71f139", "size": 11399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/norms/H2L2.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/H2L2.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/H2L2.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": 34.5424242424, "max_line_length": 108, "alphanum_fraction": 0.5960171945, "num_tokens": 4181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5557121453823771}}
{"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// Written by Cornelius Steinhardt\n\n\n#ifndef ITL_GMRES_INCLUDE\n#define ITL_GMRES_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\nnamespace itl {\n\n/// Generalized Minimal Residual method (without restart)\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.   **/\ntemplate < typename Matrix, typename Vector, typename LeftPreconditioner, typename RightPreconditioner, typename Iteration >\nint gmres_full(const Matrix &A, Vector &x, const Vector &b,\n               LeftPreconditioner &L, RightPreconditioner &R, Iteration& iter)\n{\n    using mtl::size; using mtl::irange; using mtl::iall; using std::abs; using std::sqrt;\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());\n    Scalar                      rho, nu, hr;\n    Size                        k, kmax(std::min(size(x), Size(iter.max_iterations() - iter.iterations())));\n    Vector                      r0(b - A *x), r(solve(L,r0)), va(resource(x)), va0(resource(x)), va00(resource(x));\n    mtl::matrix::multi_vector<Vector>   V(Vector(resource(x), zero), kmax+1); \n    mtl::vector::dense_vector<Scalar>   s(kmax+1, zero), c(kmax+1, zero), g(kmax+1, zero), y(kmax, zero);  // replicated in distributed solvers \n    mtl::matrix::dense2D<Scalar>        H(kmax+1, kmax);                                             // dito\n    H= 0;\n\n    rho= g[0]= two_norm(r);\n    if (iter.finished(rho))\n\treturn iter;\n    V.vector(0)= r / rho;\n    H= zero;\n\n    // GMRES iteration\n    for (k= 0; k < kmax ; ++k, ++iter) {\n        va0= A * Vector(solve(R, V.vector(k)));\n        V.vector(k+1)= va= solve(L,va0);\n\t// orth(V, V[k+1], false); \n        // modified Gram Schmidt method\n        for (Size j= 0; j < k+1; j++) {\n\t    H[j][k]= dot(V.vector(j), V.vector(k+1));\n\t    V.vector(k+1)-= H[j][k] * V.vector(j);\n        }\n        H[k+1][k]= two_norm(V.vector(k+1));\n        //reorthogonalize\n        for(Size j= 0; j < k+1; j++) {\n\t    hr= dot(V.vector(k+1), V.vector(j));\n            H[j][k]+= hr;\n            V.vector(k+1)-= hr * V.vector(j);\n        }\n        H[k+1][k]= two_norm(V.vector(k+1));\n\tif (H[k+1][k] != zero)                // watch for breakdown    \n            V.vector(k+1)*= 1. / H[k+1][k];\n\n        // k Given's rotations\n\tfor(Size i= 0; i < k; i++)\n\t    mtl::matrix::givens<mtl::matrix::dense2D<Scalar> >(H, H[i][k-1], H[i+1][k-1]).trafo(i);\n\t\n       nu= sqrt(H[k][k]*H[k][k]+H[k+1][k]*H[k+1][k]);\n       if(nu != zero){\n            c[k]=  H[k][k]/nu;\n            s[k]= -H[k+1][k]/nu;\n            H[k][k]=c[k]*H[k][k]-s[k]*H[k+1][k];\n            H[k+1][k]=0;\n \t    mtl::vector::givens<mtl::vector::dense_vector<Scalar> >(g, c[k], s[k]).trafo(k);\n        }\n\trho= abs(g[k+1]);\n    }\n    \n    //reduce k, to get regular matrix\n    while (k > 0 && abs(g[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\ttry {\n\t    y[range]= lu_solve(H[range][range], g[range]); \n\t} catch (mtl::matrix_singular) { continue; } // if singular then try with sub-matrix\n\tbreak;\n    }\n\n    if (range.finish() < k)\n  \tstd::cerr << \"GMRES orhogonalized with \" << k << \" vectors but matrix singular, can only use \" \n\t\t  << range.finish() << \" vectors!\\n\";\n    if (range.empty())\n        return iter.fail(2, \"GMRES did not find any direction to correct x\");\n    x+= Vector(solve(R, Vector(V.vector(range)*y[range])));\n    \n    r= b - A*x;\n    return iter.terminate(r);\n}\n\n/// Generalized Minimal Residual method with restart\ntemplate < typename Matrix, typename Vector, typename LeftPreconditioner,\n           typename RightPreconditioner, typename Iteration >\nint gmres(const Matrix &A, Vector &x, const Vector &b,\n          LeftPreconditioner &L, RightPreconditioner &R,\n\t  Iteration& iter, typename mtl::Collection<Vector>::size_type restart)\n{   \n     do {\n\t Iteration inner(iter);\n\t inner.set_max_iterations(std::min(int(iter.iterations()+restart), iter.max_iterations()));\n\t inner.suppress_resume(true);\n\t gmres_full(A, x, b, L, R, inner);\n\t iter.update_progress(inner);\n     } while (!iter.finished());\n\n     return iter;\n}\n\n/// Solver class for GMRES; right preconditioner ignored (prints warning if not identity)\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass gmres_solver\n{\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit gmres_solver(const LinearOperator& A, size_t restart= 8) \n      : A(A), restart(restart), L(A), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    gmres_solver(const LinearOperator& A, size_t restart, const Preconditioner& L) \n      : A(A), restart(restart), L(L), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    gmres_solver(const LinearOperator& A, size_t restart, const Preconditioner& L, const RightPreconditioner& R) \n      : A(A), restart(restart), L(L), R(R) {}\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 gmres(A, x, b, L, R, iter, restart);\n    }\n\n    /// Perform one GMRES 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    size_t                restart;\n    Preconditioner        L;\n    RightPreconditioner   R;\n};\n\n\n} // namespace itl\n\n#endif // ITL_GMRES_INCLUDE\n\n\n", "meta": {"hexsha": "1a0235a171a15600314261b1dcee4a21732e34dc", "size": 6899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/itl/krylov/gmres.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/gmres.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/gmres.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": 37.9065934066, "max_line_length": 144, "alphanum_fraction": 0.6257428613, "num_tokens": 1931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5557121432682568}}
{"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/*! \\file qg1dlocalvolmodel.hpp\n    \\brief base class for one factor quasi gaussian models with local\n           volatility\n*/\n\n#ifndef quantlib_quasigaussian1d_model_hpp\n#define quantlib_quasigaussian1d_model_hpp\n\n#include <ql/handle.hpp>\n#include <ql/indexes/swapindex.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/integrals/integral.hpp>\n#include <ql/models/model.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// the integrator_ is used for h,G,yApprox,varSApprox => use different ones ?\n// for the linear model h is overwritten\n\nnamespace QuantLib {\n\nclass Qg1dLocalVolModel : public TermStructureConsistentModel {\n  public:\n    /*! the model is specified by a function \\kappa(t) and a function g(t,x,y),\n        with \\kappa(t) = -h'(t) / h(t), \\sigma_f(t,T) = g(t)h(T), the HJM\n        specification\n        df(t,T) = \\sigma_f(t,T) ( ( \\int_t^T sigma_f(t,u) du ) du + dW(t) )\n        and\n        dx = (y - \\kappa x) dt + \\sigma_f(t,t) dW\n        dy = (\\sigma_f(t,t)^2 - 2 \\kappa y) dt\n        x(0) = y(0) = 0 */\n    Qg1dLocalVolModel(const Handle<YieldTermStructure> &yts);\n\n    /* core interface, these methods must be implemented by derived classes\n       the other virtual methods may be overwritten by more efficient versions\n       applicable to the particular model specification. */\n    virtual Real kappa(const Real t) const = 0;\n    virtual Real g(const Real t, const Real x, const Real y) const = 0;\n\n    virtual Real h(const Real t) const;\n\n    /*! \\int_t^T h(s) ds / h(t) */\n    virtual Real G(const Real t, const Real T) const;\n\n    virtual Real sigma_f(const Real t, const Real T, const Real x,\n                         const Real y) const;\n\n    Real zerobond(const Real T, const Real t, const Real x, const Real y,\n                  const Handle<YieldTermStructure> &yts =\n                      Handle<YieldTermStructure>()) const;\n\n    /*! swap rate is calculated with forward = discount, no indexed coupons\n        T0 is the start date of the swap, fixedTimes the payment times of\n        the fixed leg and taus the year fractions of the fixed leg */\n    Real swapRate(const Real T0, const Real t,\n                  const std::vector<Real> &fixedTimes,\n                  const std::vector<Real> &taus, const Real x, const Real y,\n                  const Handle<YieldTermStructure> &yts =\n                      Handle<YieldTermStructure>()) const;\n\n    Real dSwapRateDx(const Real T0, const Real t,\n                     const std::vector<Real> &fixedTimes,\n                     const std::vector<Real> &taus, const Real x, const Real y,\n                     const Handle<YieldTermStructure> &yts =\n                         Handle<YieldTermStructure>()) const;\n\n    Real d2SwapRateDx2(const Real T0, const Real t,\n                       const std::vector<Real> &fixedTimes,\n                       const std::vector<Real> &taus, const Real x,\n                       const Real y, const Handle<YieldTermStructure> &yts =\n                                         Handle<YieldTermStructure>()) const;\n\n    /*! local volatility using yApprox and sInvX (see Piterbarg, equation 13.19\n        and what follows immediately after that), if numericalInversion is true,\n        otherwise xi is used (Piterbarg, prop 13.1.8) */\n    Real\n    phi(const Real t, const Real s, const Real T0,\n        const std::vector<Real> &fixedTimes, const std::vector<Real> &taus,\n        const Handle<YieldTermStructure> &yts = Handle<YieldTermStructure>(),\n        bool numericalInversion = false) const;\n\n    Disposable<std::vector<Real> >\n    phi(const Real t, const std::vector<Real> &s, const Real T0,\n        const std::vector<Real> &fixedTimes, const std::vector<Real> &taus,\n        const Handle<YieldTermStructure> &yts = Handle<YieldTermStructure>(),\n        bool numericalInversion = false) const;\n\n    /*! date based variants, only the forwarding curve from the swap index\n        (if given) is used and no indexed coupons are used, see above */\n    Real zerobond(const Date &maturiy, const Date &referenceDate, const Real x,\n                  const Real y, const Handle<YieldTermStructure> &yts =\n                                    Handle<YieldTermStructure>());\n\n    Real swapRate(const Date &startDate, const Date &referenceDate,\n                  const boost::shared_ptr<SwapIndex> &index,\n                  const Period &tenor, const Real x, const Real y) const;\n\n    Real dSwapRateDx(const Date &startDate, const Date &referenceDate,\n                     const boost::shared_ptr<SwapIndex> &index,\n                     const Period &tenor, const Real x, const Real y) const;\n\n    Real d2SwapRateDx2(const Date &startDate, const Date &referenceDate,\n                       const boost::shared_ptr<SwapIndex> &index,\n                       const Period &tenor, const Real x, const Real y) const;\n\n    /*! utilitiy function that fills T0, tau and a times vector based on\n      a given swap index */\n    void timesAndTaus(const Date &startDate,\n                      const boost::shared_ptr<SwapIndex> &index,\n                      const Period &tenor, Real &T0, std::vector<Real> &times,\n                      std::vector<Real> &taus) const;\n\n    virtual Real yApprox(const Real t) const;\n\n    /*! this is \\overline{x(t)} in Piterbarg */\n    virtual Real xApprox(const Real t, const Real T0,\n                         const std::vector<Real> &fixedTimes,\n                         const std::vector<Real> &taus,\n                         const Handle<YieldTermStructure> &yts) const;\n\n    /*! approximate inversion of s in the sense of\n        13.28 in Piterbarg */\n    virtual Real xi(const Real t, const Real T0,\n                    const std::vector<Real> &fixedTimes,\n                    const std::vector<Real> &taus,\n                    const Handle<YieldTermStructure> &yts, const Real s) const;\n\n    virtual Disposable<std::vector<Real> >\n    xi(const Real t, const Real T0, const std::vector<Real> &fixedTimes,\n       const std::vector<Real> &taus, const Handle<YieldTermStructure> &yts,\n       const std::vector<Real> &s) const;\n\n    /*! numerical inversion of s with y = yApprox fixed,\n        i.e. this is X(t,s) in Piterbarg's notation */\n    Real sInvX(const Real t, const Real T0, const std::vector<Real> &fixedTimes,\n               const std::vector<Real> &taus,\n               const Handle<YieldTermStructure> &yts, const Real s) const;\n\n    /*! Var(S(T)) approximation like in Piterbarg, remark 13.1.7 */\n    Real varSApprox(const Real T, const Real T0,\n                    const std::vector<Real> &fixedTimes,\n                    const std::vector<Real> &taus,\n                    const Handle<YieldTermStructure> &yts) const;\n\n  protected:\n    /*! compute swap rate, the first and second derivative w.r.t. x\n        (since they share a lot of intermediate results this is more\n        efficient than computing each single number) */\n    void swapRate_d0_d1_d2(const Real T0, const Real t,\n                           const std::vector<Real> &fixedTimes,\n                           const std::vector<Real> &taus, const Real x,\n                           const Real y, const Handle<YieldTermStructure> &yts,\n                           Real &result_d0, Real &result_d1, Real &result_d2,\n                           const bool compute_d0, const bool compute_d1,\n                           const bool compute_d2) const;\n\n    /*! sigma_f(t,t,0,0)^2*h(t)^{-2}, precondition (not checked) is t > 0 */\n    virtual Real sigma_r_0_0_h_sqr(const Real t) const;\n\n    /*! sigma_f(t,t,0.0)^2*dS/dx(s,0,0)^2 */\n    virtual Real\n    sigma_r_0_0_dSdx_sqr(const Real T0, const Real t,\n                         const std::vector<Real> &fixedTimes,\n                         const std::vector<Real> &taus,\n                         const Handle<YieldTermStructure> &yts) const;\n\n    boost::shared_ptr<Integrator> integrator_;\n\n  private:\n    Real sInvX_helper(const Real t, const Real T0,\n                      const std::vector<Real> &fixedTimes,\n                      const std::vector<Real> &taus,\n                      const Handle<YieldTermStructure> &yts, const Real s,\n                      const Real x) const;\n};\n\n// inline\n\ninline Real Qg1dLocalVolModel::h(const Real t) const {\n    return std::exp(-integrator_->operator()(\n        boost::bind(&Qg1dLocalVolModel::kappa, this, _1), 0.0, t));\n}\n\ninline Real Qg1dLocalVolModel::G(const Real t, const Real T) const {\n    return integrator_->operator()(boost::bind(&Qg1dLocalVolModel::h, this, _1),\n                                   t, T);\n}\n\ninline Real Qg1dLocalVolModel::sigma_f(const Real t, const Real T, const Real x,\n                                       const Real y) const {\n    return g(t, x, y) * h(T);\n}\n\ninline Real Qg1dLocalVolModel::yApprox(const Real t) const {\n    if (t < 1E-10)\n        return 0.0;\n    Real tmp = h(t);\n    return tmp * tmp *\n           integrator_->operator()(\n               boost::bind(&Qg1dLocalVolModel::sigma_r_0_0_h_sqr, this, _1),\n               0.0, t);\n}\n\ninline Real Qg1dLocalVolModel::sigma_r_0_0_h_sqr(const Real t) const {\n    Real tmp = g(t, 0.0, 0.0); // this is sigma_f(t, t, 0.0, 0.0) / h(t);\n    return tmp * tmp;\n}\n\ninline Real Qg1dLocalVolModel::sigma_r_0_0_dSdx_sqr(\n    const Real T0, const Real t, const std::vector<Real> &fixedTimes,\n    const std::vector<Real> &taus,\n    const Handle<YieldTermStructure> &yts) const {\n    Real tmp = sigma_f(t, t, 0.0, 0.0) *\n               dSwapRateDx(T0, t, fixedTimes, taus, 0.0, 0.0, yts);\n    return tmp * tmp;\n}\n\ninline Real Qg1dLocalVolModel::sInvX_helper(\n    const Real t, const Real T0, const std::vector<Real> &fixedTimes,\n    const std::vector<Real> &taus, const Handle<YieldTermStructure> &yts,\n    const Real s, const Real x) const {\n    Real y = yApprox(t);\n    return swapRate(T0, t, fixedTimes, taus, x, y, yts) - s;\n}\n\ninline Real Qg1dLocalVolModel::sInvX(const Real t, const Real T0,\n                                     const std::vector<Real> &fixedTimes,\n                                     const std::vector<Real> &taus,\n                                     const Handle<YieldTermStructure> &yts,\n                                     const Real s) const {\n    Brent b;\n    boost::function<Real(Real)> f =\n        boost::bind(&Qg1dLocalVolModel::sInvX_helper, this, t, T0, fixedTimes,\n                    taus, yts, s, _1);\n    return b.solve(f, 1E-7, 0.0, 0.01);\n}\n\ninline Real\nQg1dLocalVolModel::varSApprox(const Real T, const Real T0,\n                              const std::vector<Real> &fixedTimes,\n                              const std::vector<Real> &taus,\n                              const Handle<YieldTermStructure> &yts) const {\n    return integrator_->operator()(\n        boost::bind(&Qg1dLocalVolModel::sigma_r_0_0_dSdx_sqr, this, T0, _1,\n                    fixedTimes, taus, yts),\n        0.0, T);\n}\n\n} // namespace QuantLib\n\n#endif\n", "meta": {"hexsha": "15a1da92f02c3012dd5fafd1d25ecb3e44ef97d5", "size": 11746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/qg1dlocalvolmodel.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/qg1dlocalvolmodel.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/qg1dlocalvolmodel.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": 42.8686131387, "max_line_length": 80, "alphanum_fraction": 0.610250298, "num_tokens": 3034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.555712136925895}}
{"text": "#include <Engine/MeshEdit/Simulate.h>\n\n#include <math.h>\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\n\nvoid Simulate::Clear() {\n\tthis->positions.clear();\n\tthis->velocity.clear();\n}\n\nbool Simulate::Init() {\n\t//Clear();\n\tg = -9.8;\n\tstiff = 15000;\n\t//g = 0;\n\tisfast =true;\n\tx.resize(3 * positions.size());\n\ty_.resize(3 * positions.size());\n\txx.resize(3 * positions.size());\n\titer = 3;\n\tSetFix();\n\t\n\tthis->velocity.resize(positions.size());\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tthis->velocity[i][j] = 0;\n\t\t\tx[3 * i + j] = positions[i][j];\n\t\t\ty_[3 * i + j] = positions[i][j];\n\t\t\txx[3 * i + j] = positions[i][j];\n\t\t}\n\t}\n\t\n\tmass.resize(3 * positions.size());\n\tM.resize(3 * positions.size(), 3 * positions.size());\n\tM.fill(0);\n\t\n\tforce_ext.resize(3 * positions.size());\n\tforce_int.resize(3 * positions.size());\n\tfor (int i = 0; i < 3 * positions.size(); i++)\n\t{\n\t\tforce_ext[i] = 0.0;\n\t\tforce_int[i] = 0.0;\n\t\tmass[i] = 1;\n\t\tM(i, i) = mass[i];\n\t}\n\n\t//gx_m.resize(3 * positions.size(), 1);\n\t\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tpointf3 v1 = positions[index1];\n\t\tpointf3 v2 = positions[index2];\n\n\t\tl.push_back((v1 - v2).norm());\n\t\t//l.push_back(0.5);\n\t}\n\n\tSetInitG();\n\tGetSet();\n\n\tCacK();\n\n\tCacA();\n\t\n\treturn true;\n}\n\n\nvoid Simulate::SetFast()\n{\n\tisfast = true;\n}\n\nbool Simulate::Run() {\n\tSimulateOnce();\n\n\t// half-edge structure -> triangle mesh\n\n\treturn true;\n}\n\nvoid Ubpa::Simulate::SetLeftFix()\n{\n\t//固定网格x坐标最小点\n\tfixed_id.clear();\n\tdouble x = 100000;\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (positions[i][0] < x)\n\t\t{\n\t\t\tx = positions[i][0];\n\t\t}\n\t}\n\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (abs(positions[i][0] - x) < 1e-5)\n\t\t{\n\t\t\tfixed_id.push_back(i);\n\t\t}\n\t}\n\n\tInit();\n}\n\nvoid Simulate::SimulateOnce() {\n\t// TODO\n\t//cout << \"WARNING::Simulate::SimulateOnce:\" << endl;\n//\t\t<< \"\\t\" << \"not implemented\" << endl;\n\t//stiff = 50;\n\t//stiff = 100000;\n//SetStiff(100000);\n\n\tif (!isfast)\n\t{\n\t\tCacX();\n\t\t//void UpdateX();\n\t\tCacV();\n\t\tUpdatePos();\n\t}\n\telse\n\t{\n\t\tstd::vector<double> x_=x;\n\t\tfor (int i = 0; i < x.size(); i++)\n\t\t\ty_ [i]= 2 * x[i]  - xx[i];\n\t\tx = y_;\n\t\tfor (int i = 0; i < iter; i++)\n\t\t{\n\t\t\tLocal_CacD();\n\t\t\tGlobal_CacX();\n\t\t}\n\t\txx = x_;\n\t\tUpdatePos();\n\t}\n\t\n}\n\nvoid Simulate::CacForce()\n{\n\tforce_int.clear();\n\tforce_int.resize(3 * positions.size());\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\t//pointf3 v1 = positions[index1];\n\t\t//pointf3 v2 = positions[index2];\n\t\tpointf3 v1 = pointf3(x[3 * index1 + 0], x[3 * index1 + 1], x[3 * index1 + 2]);\n\t\tpointf3 v2 = pointf3(x[3 * index2 + 0], x[3 * index2 + 1], x[3 * index2 + 2]);\n\t\tvecf3 r = v1 - v2;\n\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tforce_int[3 * index1 + j] += -stiff * (r.norm() - l[i]) * r[j] / r.norm();\n\t\t\tforce_int[3 * index2 + j] += stiff * (r.norm() - l[i]) * r[j] / r.norm();\n\t\t}\n\n\t}\n}\n\nvoid Simulate::SetInitG()\n{\n\tfor (int i = 0; i < positions.size(); i++)\n\t\tforce_ext[i * 3 + 1] = g * mass[i];\n}\n\n\n\nvoid Simulate::GetSet()\n{\n\t//fix.insert(10);\n\t//fix.insert(120);\n\t//fix.insert(440);\n\t//fix.insert(20);\n\t//fix.insert(1*positions.size() / 4);\n\t//fix.insert(2 * positions.size() / 4);\n\tfix = std::set<int>(fixed_id.begin(), fixed_id.end());\n}\n\nvoid Simulate::CacK()\n{\n\tK.resize(x.size() - 3 * fix.size(), x.size());\n\tK.fill(0);\n\n\tfor (int i = 0, j = 0; i < x.size(); i++)\n\t{\n\t\tif (fix.find(i / 3) == fix.end())\n\t\t{\n\t\t\tK(j, i) = 1;\n\t\t\t//std::cout << j << \" \" << i << endl;\n\t\t\tj++;\n\t\t}\n\t}\n\n\tEigen::MatrixXd xt;\n\txt.resize((x.size()), 1);\n\tb.resize(x.size());\n\n\tfor (int i = 0; i < x.size(); i++)\n\t\txt(i, 0) = x[i];\n\tEigen::MatrixXd t = K.transpose() * K * xt;\n\n\tfor (int i = 0; i < x.size(); i++)\n\t\tb[i] = x[i] - t(i, 0);\n}\n\nvoid Simulate::CacX()\n{\n\tstd::vector<double> y(x.size());\n\tfor (int i = 0; i < x.size(); i++)\n\t\ty[i] = x[i] + h * velocity[i / 3][i % 3] + h * h / mass[i] * force_ext[i];\n\n\txk = y;\n\tint i = 0;\n\tdo\n\t{\n\t\tCacForce();\n\t\tCacGX();\n\t\tCacDiff();\n\n\n\t\t//Eigen::MatrixXd inverG = diff_.inverse();\n\n\t\tCacGxM();\n\n\t\tEigen::MatrixXd t = inverG * gx_m;\n\n\t\txk_1.clear();\n\t\txk_1.resize(gx.size());\n\t\tfor (int i = 0; i < gx.size(); i++)\n\t\t{\n\t\t\txk_1[i] = xk[i] - t(i, 0);\n\t\t\t//cout << t(i, 0) << endl;\n\t\t}\n\t\ti++;\n\t\t//cout << i++ << endl;\n\t\tUpdateX();\n\t\txk = x;\n\t} while (!isconv() && i <= 10);//sparse 50\n\n\n}\n\nvoid Simulate::CacGxM()\n{\n\tgx_m.resize(gx.size(), 1);\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tgx_m(i, 0) = gx[i];\n}\n\nbool Simulate::isconv()\n{\n\tbool flag = true;\n\tdouble delta = 0.01;\n\tstd::vector<double> zero(gx.size(), delta);\n\n\tfor (int i = 0; i < gx.size() && flag; i++)\n\t{\n\t\tif (abs(gx[i]) > zero[i])\n\t\t\tflag = false;\n\t}\n\treturn flag;\n}\n\nvoid Simulate::SetFix()\n{\n\tif (fixed_id.empty())\n\t{\n\n\t\tif (positions.size() > 440)\n\t\t{\n\t\t\tfixed_id.push_back(20);\n\t\t\tfixed_id.push_back(440);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfixed_id.push_back(10);\n\t\t\tfixed_id.push_back(120);\n\t\t}\n\t}\n\t//fixed_id.push_back(0);\n\t\n}\n\nvoid Simulate::CacGX()\n{\n\tstd::vector<double> y(xk.size());\n\tgx.resize(xk.size());\n\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t{\n\t\ty[i] = xk[i] + h * velocity[i / 3][i % 3] + h * h / mass[i] * force_ext[i];\n\t}\n\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t{\n\t\tgx[i] = mass[i] * (xk[i] - y[i]) - h * h * force_int[i];\n\t}\n\n\tEigen::MatrixXd t(gx.size(), 1);\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tt(i, 0) = gx[i];\n\n\tt = K * t;\n\n\tgx.clear();\n\tgx.resize(t.rows());\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tgx[i] = t(i, 0);\n\n\n\n\tEigen::MatrixXd xt;\n\txt.resize((xk.size()), 1);\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t\txt(i, 0) = xk[i];\n\n\tt = K * xt;\n\txk.clear();\n\txk.resize(t.rows());\n\tfor (int i = 0; i < xk.size(); i++)\n\t\txk[i] = t(i, 0);\n}\n\nvoid Simulate::CacDiff()\n{\n\tstd::vector<Eigen::Triplet<double> > triple;\n\t//Eigen::MatrixXd I = Eigen::DiagonalMatrix<double,3,3>::DiagonalMatrix(2);\n\tEigen::MatrixXd I = MatrixXd::Identity(3, 3);\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tpointf3 v1 = pointf3(x[3 * index1 + 0], x[3 * index1 + 1], x[3 * index1 + 2]);\n\t\tpointf3 v2 = pointf3(x[3 * index2 + 0], x[3 * index2 + 1], x[3 * index2 + 2]);\n\t\tvecf3 r = v1 - v2;\n\t\tMatrixXd t(3, 1);\n\t\tt(0, 0) = r[0]; t(1, 0) = r[1]; t(2, 0) = r[2];\n\n\t\tEigen::MatrixXd dif;\n\t\tdif.resize(3, 3);\n\t\tdif = stiff * (l[i] / r.norm() - 1) * I - stiff * l[i]\n\t\t\t/ ((r.norm()) * (r.norm()) * (r.norm())) * t * t.transpose();\n\t\t//cout << index1 << \" \" << index2 << endl;\n\t\t//cout << dif << endl;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tfor (int k = 0; k < 3; k++)\n\t\t\t{\n\t\t\t\ttriple.push_back(Eigen::Triplet<double>(3 * index1 + j, 3 * index1 + k, -h * h * dif(j, k)));\n\t\t\t\t//triple.push_back(Eigen::Triplet<double>(3 * index1 + j, 3 * index2 + k, h*h*dif(j, k)));\n\t\t\t\t//triple.push_back(Eigen::Triplet<double>(3 * index2 + k, 3 * index1 + j, h*h*dif(j, k)));\n\t\t\t\ttriple.push_back(Eigen::Triplet<double>(3 * index2 + k, 3 * index2 + j, -h * h * dif(j, k)));\n\t\t\t}\n\t}\n\n\tfor (int i = 0; i < x.size(); i++)\n\t{\n\t\ttriple.push_back(Eigen::Triplet<double>(i, i, mass[i]));\n\t}\n\n\tEigen::MatrixXd diff_;\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> LU_;\n\n\tdiff.setZero();\n\tdiff.resize(x.size(), x.size());\n\tdiff.setFromTriplets(triple.begin(), triple.end());\n\n\tdiff_ = K * diff * K.transpose();\n\t//cout << diff_ << endl;\n\t//cout << K << endl;\n\n\tdiff = diff_.sparseView();\n\n\tI = MatrixXd::Identity(gx.size(), gx.size());\n\tLU_.analyzePattern(diff);\n\tLU_.factorize(diff);\n\t//LU_.compute(diff);\n\tinverG = LU_.solve(I);\n\t//cout << inverG << endl;\n}\n\nvoid Simulate::UpdateX()\n{\n\tEigen::MatrixXd xt;\n\txt.resize((xk_1.size()), 1);\n\n\tfor (int i = 0; i < xk_1.size(); i++)\n\t\txt(i, 0) = xk_1[i];\n\n\tEigen::MatrixXd t = K.transpose() * xt;\n\n\tfor (int i = 0; i < x.size(); i++)\n\t\tx[i] = t(i, 0) + b[i];\n\n}\n\nvoid Simulate::UpdatePos()\n{\n\tfor (int i = 0; i < x.size(); i++)\n\t{\n\t\tpositions[i / 3][i % 3] = x[i];\n\t}\n}\n\nvoid Simulate::CacV()\n{\n\tfor (int i = 0; i < x.size(); i++)\n\t{\n\t\tvelocity[i / 3][i % 3] = (x[i] - positions[i / 3][i % 3]) / h;\n\t}\n}\n\n\nvoid Simulate::CacL()\n{\n\tL = MatrixXd::Zero(positions.size() * 3, positions.size() * 3);\n\n\tMatrixXd t = MatrixXd::Zero(positions.size(), positions.size());\n\t//cout << t << endl;\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tstd::vector<double> Ai(positions.size(),0);\n\t\tAi[index1] = 1;\n\t\tAi[index2] = -1;\n\t\t\n\t\tEigen::MatrixXd At;\n\t\tAt.resize((Ai.size()), 1);\n\n\t\tfor (int j = 0; j < Ai.size(); j++)\n\t\t\tAt(j, 0) = Ai[j];\n\t\t//cout << At << endl<<endl;\n\t\tt += stiff * At * At.transpose();\n\t}\n\t//cout << t << endl;\n\t//cout << M << endl;\n\tMatrix3d I3 = Matrix3d::Identity();\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tfor (int j = 0; j < positions.size(); j++)\n\t\t\tL.block(i * 3, j * 3, 3, 3) = t(i, j) * I3;\n\t}\n}\n\nvoid Simulate::CacJ()\n{\n\tJ = MatrixXd::Zero(positions.size() * 3, edgelist.size() / 2 * 3);\n\n\tMatrixXd t = MatrixXd::Zero(positions.size(), edgelist.size() / 2);\n\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\n\t\tstd::vector<double> Ai(positions.size(), 0);\n\t\tAi[index1] = 1;\n\t\tAi[index2] = -1;\n\n\t\tstd::vector<double> Si(edgelist.size() / 2,0);\n\t\tSi[i] = 1;\n\n\t\tEigen::MatrixXd At;\n\t\tAt.resize((Ai.size()), 1);\n\n\t\tfor (int j = 0; j < Ai.size(); j++)\n\t\t\tAt(j, 0) = Ai[j];\n\n\t\tEigen::MatrixXd St;\n\t\tSt.resize((Si.size()), 1);\n\n\t\tfor (int j = 0; j < Si.size(); j++)\n\t\t\tSt(j, 0) = Si[j];\n\t\t//cout << stiff * At * St.transpose() << endl;\n\t\tt += stiff * At * St.transpose();\n\t}\n\t//cout << t << endl;\n\tMatrix3d I3 = Matrix3d::Identity();\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tfor (int j = 0; j < edgelist.size() / 2; j++)\n\t\t\tJ.block(i * 3, j * 3, 3, 3) = t(i, j) * I3;\n\t}\n}\n\nvoid Simulate::CacA()\n{\n\tCacL();\n\tCacJ();\n\tMatrixXd A_;\n\t//cout << L << endl;\n\t//cout << J << endl;\n\tA_.resize(K.rows(), K.rows());\n\tA_ = K * (M + h * h * L) * K.transpose();\n\tA = A_.sparseView();\n\tLLT_.compute(A);\n}\n\nvoid Simulate::Global_CacX()\n{\n\tEigen::MatrixXd dt;\n\tdt.resize((d.size()), 1);\n\n\tfor (int j = 0; j < d.size(); j++)\n\t\tdt(j, 0) = d[j];\n\n\tEigen::MatrixXd yt;\n\tyt.resize((y_.size()), 1);\n\n\tfor (int j = 0; j < y_.size(); j++)\n\t\tyt(j, 0) = y_[j];\n\n\tEigen::MatrixXd ft;\n\tft.resize((force_ext.size()), 1);\n\n\tfor (int j = 0; j < force_ext.size(); j++)\n\t\tft(j, 0) = force_ext[j];\n\n\tEigen::MatrixXd bt;\n\tbt.resize((b.size()), 1);\n\n\tfor (int j = 0; j < b.size(); j++)\n\t\tbt(j, 0) = b[j];\n\n\tVectorXd B = K * (h * h * J * dt + M * yt + h * h * ft - (M + h * h * L) * bt);\n\t//cout << J << endl;\n\t//cout << L << endl;\n\tVectorXd xf = LLT_.solve(B);\n\t//cout << xf << endl;\n\txf = K.transpose() * xf + bt;\n\n\tfor (int j = 0; j < x.size(); j++)\n\t\tx[j] = xf[j];\n}\n\nvoid Simulate::Local_CacD()\n{\n\td.resize(3 * edgelist.size() / 2);\n\t\n\tfor (int i = 0; i < edgelist.size() / 2; i++)\n\t{\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tpointf3 v1 = pointf3(x[3 * index1 + 0], x[3 * index1 + 1], x[3 * index1 + 2]);\n\t\tpointf3 v2 = pointf3(x[3 * index2 + 0], x[3 * index2 + 1], x[3 * index2 + 2]);\n\t\tvecf3 r = v1 - v2;\n\n\t\td[3 * i + 0] = l[i] * r[0] / r.norm();\n\t\td[3 * i + 1] = l[i] * r[1] / r.norm();\n\t\td[3 * i + 2] = l[i] * r[2] / r.norm();\n\t}\n}\n", "meta": {"hexsha": "fffcda8c209d6dbfd109eaefe259174fcc3401a9", "size": 11324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/6_MassSpring/project/src/Engine/MeshEdit/Simulate.cpp", "max_stars_repo_name": "SqrtiZhang/CG", "max_stars_repo_head_hexsha": "462415eea0af981797172281a023066ff557a33a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T02:41:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T09:56:10.000Z", "max_issues_repo_path": "Homeworks/6_MassSpring/project/src/Engine/MeshEdit/Simulate.cpp", "max_issues_repo_name": "SqrtiZhang/CG", "max_issues_repo_head_hexsha": "462415eea0af981797172281a023066ff557a33a", "max_issues_repo_licenses": ["MIT"], "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/6_MassSpring/project/src/Engine/MeshEdit/Simulate.cpp", "max_forks_repo_name": "SqrtiZhang/CG", "max_forks_repo_head_hexsha": "462415eea0af981797172281a023066ff557a33a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-06T11:22:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T11:22:14.000Z", "avg_line_length": 19.8318739054, "max_line_length": 97, "alphanum_fraction": 0.5271105616, "num_tokens": 4437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5556606614936551}}
{"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__COLLOCATION_HPP_\n#define SMOOTH__FEEDBACK__COLLOCATION_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Sparse>\n#include <smooth/diff.hpp>\n#include <smooth/internal/utils.hpp>\n#include <smooth/polynomial/quadrature.hpp>\n\n#include <cstddef>\n#include <numeric>\n#include <ranges>\n#include <vector>\n\n#include \"traits.hpp\"\n#include \"utils/sparse.hpp\"\n\nnamespace smooth::feedback {\n\nnamespace detail {\n\n/**\n * @brief Legendre-Gauss-Radau nodes including an extra node at +1.\n */\ntemplate<std::size_t K, std::size_t I = 8>\nconstexpr std::pair<std::array<double, K + 1>, std::array<double, K + 1>> lgr_plus_one()\n{\n  auto lgr_norm = ::smooth::lgr_nodes<K, I>();\n\n  std::array<double, K + 1> ns, ws;\n  for (auto i = 0u; i < K; ++i) {\n    ns[i] = lgr_norm.first[i];\n    ws[i] = lgr_norm.second[i];\n  }\n  ns[K] = 1;\n  ws[K] = 0;\n  return {ns, ws};\n}\n\n}  // namespace detail\n\n/**\n * @brief Collocation mesh of interval [0, 1].\n * @tparam _Kmin minimal number of collocation points per interval\n * @tparam _Kmax maximal number of collocation points per interval\n *\n * [0, 1] is divided into non-overlapping intervals I_i, and each interval I_i has K_i LGR\n * collocation points.\n */\ntemplate<std::size_t _Kmin = 5, std::size_t _Kmax = 10>\n  requires(_Kmin <= _Kmax)\nclass Mesh\n{\n  using MatMap = Eigen::Map<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>;\n\npublic:\n  /// @brief Minimal number of collocation points per interval\n  static constexpr auto Kmin = _Kmin;\n  /// @brief Maximal number of collocation points per interval\n  static constexpr auto Kmax = _Kmax;\n\n  /**\n   * @brief Create a mesh consisting of a single interval [0, 1].\n   *\n   * @param Kmin minimal polynomial degree in mesh\n   * @param Kmax maximal polynomial degree in mesh\n   *\n   * @note It must hold that kKmin <= Kmin <= Kmax <= kKmax, where kKmin and kKmax are compile-time\n   * constants that define which LGR nodes to pre-compute.\n   */\n  inline Mesh() : intervals_(1, Interval{.K = Kmin, .tau0 = 0}) {}\n\n  /**\n   * @brief Number of intervals in mesh.\n   */\n  inline std::size_t N_ivals() const { return intervals_.size(); }\n\n  /**\n   * @brief Number of collocation points in mesh.\n   */\n  inline std::size_t N_colloc() const\n  {\n    return std::accumulate(\n      intervals_.begin(), intervals_.end(), 0u, [](std::size_t curr, const auto & x) {\n        return curr + x.K;\n      });\n  }\n\n  /**\n   * @brief Number of collocation points in interval i.\n   *\n   * @note This is also equal to the polynomial degree inside interval i, since the polynomial is\n   * fitted with an \"extra\" point belonging to the subsequent interval.\n   */\n  inline std::size_t N_colloc_ival(std::size_t i) const { return intervals_[i].K; }\n\n  /**\n   * @breif Refine interval using the ph strategy.\n   *\n   * @param i index of interval to refine\n   * @param D target number of collocation points in refined interval\n   *\n   * If D > Kmax, or current degree > Kmax    then the interval is divided into\n   *                                          n = max(2, ceil(D / Kmin)) intervals with deg Kmin\n   * If D < current degree,                   then nothing is done.\n   * If D <= Kmax,                            then the polynomial degree is increased to D.\n   */\n  inline void refine_ph(std::size_t i, std::size_t D)\n  {\n    if (D > Kmax || intervals_[i].K > Kmax) {\n      // refine by splitting interval into n intervals, each with degree Kmin_\n      std::size_t n = std::max<std::size_t>(2u, (D + Kmin - 1) / Kmin);\n\n      const double tau0 = intervals_[i].tau0;\n      const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n      const double taum = (tauf - tau0) / n;\n\n      while (n-- > 1) {\n        intervals_.insert(intervals_.begin() + i + 1, Interval{.K = Kmin, .tau0 = tau0 + n * taum});\n      }\n    } else if (D < intervals_[i].K) {\n      return;\n    } else if (D <= Kmax) {\n      // refine by increasing degree in interval\n      intervals_[i].K = D;\n    }\n  }\n\n  /**\n   * @brief Set the number of collocation points in interval i to K\n   * @param i interval index\n   * @param K number of collocation points s.t. (Kmin <= K <= Kmax + 1)\n   */\n  inline void set_N_colloc_ival(std::size_t i, std::size_t K)\n  {\n    assert(Kmin <= K);\n    assert(K <= Kmax + 1);\n    intervals_[i].K = K;\n  }\n\n  /**\n   * @brief Interval nodes and quadrature weights (DOES include extra point)\n   */\n  inline std::pair<Eigen::VectorXd, Eigen::VectorXd> interval_nodes_and_weights(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    Eigen::VectorXd ns, ws;\n    utils::static_for<Kmax + 2 - Kmin>([&](auto i) {\n      static constexpr auto K = Kmin + i;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n        ns = Eigen::Map<const Eigen::VectorXd>(nw_ext_s.first.data(), k + 1);\n        ws = Eigen::Map<const Eigen::VectorXd>(nw_ext_s.second.data(), k + 1);\n      }\n    });\n\n    const double tau0  = intervals_[i].tau0;\n    const double tauf  = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n    const double alpha = (tauf - tau0) / 2;\n\n    return {\n      Eigen::VectorXd::Constant(ns.size(), tau0) + alpha * (ns + Eigen::VectorXd::Ones(ns.size())),\n      alpha * ws,\n    };\n  }\n\n  /**\n   * @brief All Mesh nodes and quadrature weights (DOES include extra point)\n   */\n  inline std::pair<Eigen::VectorXd, Eigen::VectorXd> all_nodes_and_weights() const\n  {\n    Eigen::VectorXd n(N_colloc() + 1), w(N_colloc() + 1);\n\n    std::size_t cntr = 0;\n    for (auto i = 0u; i < intervals_.size(); ++i) {\n      auto [ni, wi] = interval_nodes_and_weights(i);\n\n      const std::size_t Ni = ni.size();\n\n      // exclude last point that belongs to next interval..\n      n.segment(cntr, Ni - 1) = ni.head(Ni - 1);\n      w.segment(cntr, Ni - 1) = wi.head(Ni - 1);\n\n      cntr += Ni - 1;\n    }\n\n    n.tail(1).setConstant(1);\n    w.tail(1).setConstant(0);\n\n    return {n, w};\n  }\n\n  /**\n   * @brief Interval differentiation matrix w.r.t. [0, 1] timescale.\n   *\n   * Returns a \\f$ (K+1 \\times K) \\f$ matrix \\f$ D \\f$ s.t.\n   * \\f[\n   *   \\begin{bmatrix} y'(\\tau_{i, 0}) & y'(\\tau_{i, 1}) & \\cdots & y'(\\tau_{i, K-1}) \\end{bmatrix}\n   *  =\n   *   \\begin{bmatrix} y(\\tau_{i, 0}) & y(\\tau_{i, 1}) & \\cdots & y(\\tau_{i, K}) \\end{bmatrix} D\n   * \\f],\n   * where \\f$ y(\\cdot) \\in \\mathbb{R}^{d \\times 1} \\f$ is a Lagrange polynomial in interval i.\n   */\n  inline Eigen::MatrixXd interval_diffmat(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    const double tau0 = intervals_[i].tau0;\n    const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n\n    Eigen::MatrixXd ret;\n    utils::static_for<Kmax + 2 - Kmin>([&](auto i) {\n      static constexpr auto K = Kmin + i;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n        static constexpr auto B_ext_s  = lagrange_basis<K>(nw_ext_s.first);\n        static constexpr auto D_ext_s =\n          polynomial_basis_derivatives<K, K + 1>(B_ext_s, nw_ext_s.first)\n            .template block<K + 1, K>(0, 0);\n        ret = MatMap(D_ext_s[0].data(), k + 1, k);\n        ;\n      }\n    });\n\n    return (2. / (tauf - tau0)) * ret;\n  }\n\n  /**\n   * @brief Interval integration matrix w.r.t. [0, 1] timescale.\n   *\n   * Returns a \\f$ (K \\times K) \\f$ matrix \\f$ I \\f$ s.t.\n   * \\f[\n   *   \\begin{bmatrix}\n   *      y(\\tau_{i, 1}) & y(\\tau_{i, 2}) & \\cdots & y(\\tau_{i, K})\n   *   \\end{bmatrix}\n   *  = y(\\tau_{i, 0}) \\begin{bmatrix} 1 & \\ldots & 1 \\end{bmatrix}\n   *    + \\begin{bmatrix}\n   *        \\dot y(\\tau_{i, 0}) & \\dot y(\\tau_{i, 1}) & \\cdots & \\dot y(\\tau_{i, K-1})\n   *      \\end{bmatrix} I\n   * \\f],\n   * where \\f$ y(\\cdot) \\in \\mathbb{R}^{d \\times 1} \\f$ is a Lagrange\n   * polynomial in interval i.\n   */\n  inline Eigen::MatrixXd interval_intmat(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n    return interval_diffmat(i).block(1, 0, k, k).inverse();\n  }\n\n  /**\n   * @brief Find interval index that contains t\n   */\n  inline std::size_t interval_find(double t) const\n  {\n    if (t < 0) { return 0; }\n    if (t > 1) { return intervals_.size() - 1; }\n    auto it = utils::binary_interval_search(\n      intervals_, t, [](const auto & ival, double _t) { return ival.tau0 <=> _t; });\n    if (it != intervals_.end()) { return std::distance(intervals_.begin(), it); }\n    return 0;\n  }\n\n  /**\n   * @brief Evaluate a function\n   *\n   * @tparam RetT return value type\n   *\n   * @param t time value in [0, 1]\n   * @param r values for the collocation points (size N [extend=false] or N+1 [extend=true])\n   * @param derivative to evaluate\n   * @param extend set to true if a value is provided for t=+1\n   */\n  template<typename RetT, std::ranges::sized_range R>\n  RetT eval(double t, const R & r, std::size_t p = 0, bool extend = true) const\n  {\n    [[maybe_unused]] const std::size_t N = N_colloc();\n\n    if (extend) {\n      assert(std::ranges::size(r) == N + 1);\n    } else {\n      assert(std::ranges::size(r) == N);\n    }\n\n    const std::size_t ival = interval_find(t);\n    const std::size_t k    = intervals_[ival].K;\n\n    const double tau0 = intervals_[ival].tau0;\n    const double tauf = ival + 1 < intervals_.size() ? intervals_[ival + 1].tau0 : 1.;\n\n    const double u = 2 * (t - tau0) / (tauf - tau0) - 1;\n\n    Eigen::RowVectorXd W;\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto i) {\n      static constexpr auto K = Kmin + i;\n      if (K == k) {\n        if (extend || ival + 1 < intervals_.size()) {\n          static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n          static constexpr auto B_ext_s  = lagrange_basis<K>(nw_ext_s.first);\n          const auto U                   = monomial_derivative<K>(u, p);\n          W = MatMap(U[0].data(), 1, k + 1) * MatMap(B_ext_s[0].data(), k + 1, k + 1);\n          assert(std::size_t(W.size()) == k + 1);\n        } else {\n          static constexpr auto nw_s = lgr_nodes<K>();\n          static constexpr auto B_s  = lagrange_basis<K - 1>(nw_s.first);\n          const auto U               = monomial_derivative<K - 1>(u, p);\n          W                          = MatMap(U[0].data(), 1, k) * MatMap(B_s[0].data(), k, k);\n          assert(std::size_t(W.size()) == k);\n        }\n      }\n    });\n\n    using namespace std::views;\n\n    std::size_t N_before = 0;\n    for (auto i = 0u; i < ival; ++i) { N_before += intervals_[i].K; }\n    const auto r_ival = r | drop(int64_t(N_before));\n    RetT ret          = W(0) * *std::ranges::begin(r_ival);\n\n    for (auto i = 1u; const auto & v : r_ival | drop(1) | take(W.size() - 1)) { ret += W(i++) * v; }\n    return ret;\n  }\n\nprivate:\n  struct Interval\n  {\n    /// @brief Polynomial degree in interval\n    std::size_t K;\n    /// @brief Start of interval on [0, 1] timescale\n    double tau0;\n  };\n\n  /// @brief Mesh intervals\n  std::vector<Interval> intervals_;\n};\n\n/// @brief MeshType is a specialization of Mesh\ntemplate<typename T>\nconcept MeshType = traits::is_specialization_of_sizet_v<T, Mesh>;\n\n/**\n * @brief Evaluate a function on all collocation points.\n *\n * Returns a nf x N matrix\n *\n *  F= [ f(t_0, X_0, U_0)  f(t_1, X_1, u_1) ... f(t_{N-1}, X_{N-1}, U_{N-1})]\n *\n * with the function evaluated at all collocation points t_i in the Mesh m.\n *\n * @tparam Der return derivatives w.r.t variables\n *\n * @param nf dimensionality of f image\n * @param f function (t, X, U) -> R^nf\n * @param m Mesh of time\n * @param t0 initial time variable\n * @param tf final time variable\n * @param X state variables (size nx x N+1)\n * @param U input variables (size nu x N)\n *\n * @return If Deriv == false,\n * If Deriv == true, {F, dvecF_dt0, dvecF_dtf, dvecF_dvecX, dvecF_dvecU}, where vec(X) stacks the\n * columns of X into a single column vector.\n */\ntemplate<bool Deriv>\nauto colloc_eval(\n  const std::size_t nf,\n  auto && f,\n  const MeshType auto & m,\n  const double t0,\n  const double tf,\n  const Eigen::MatrixXd & X,\n  const Eigen::MatrixXd & U)\n{\n  assert(m.N_colloc() + 1 == static_cast<std::size_t>(X.cols()));  //  extra variable at the end\n  assert(m.N_colloc() == static_cast<std::size_t>(U.cols()));  // one input per collocation point\n\n  const std::size_t nx = X.rows();\n  const std::size_t nu = U.rows();\n\n  // all nodes in mesh\n  const auto [tau_s, w_s] = m.all_nodes_and_weights();\n\n  Eigen::MatrixXd Fval(nf, tau_s.size() - 1);\n\n  Eigen::SparseMatrix<double> dvecF_dt0, dvecF_dtf, dvecF_dvecX, dvecF_dvecU;\n\n  if constexpr (Deriv) {\n    dvecF_dt0.resize(Fval.size(), 1);\n    dvecF_dtf.resize(Fval.size(), 1);\n    dvecF_dvecX.resize(Fval.size(), X.size());\n    dvecF_dvecU.resize(Fval.size(), U.size());\n\n    dvecF_dt0.reserve(Fval.size());\n    dvecF_dtf.reserve(Fval.size());\n\n    Eigen::VectorXi FX_pattern = Eigen::VectorXi::Constant(X.size(), nf);\n    FX_pattern.tail(nx).setZero();\n    dvecF_dvecX.reserve(FX_pattern);\n    dvecF_dvecU.reserve(Eigen::VectorXi::Constant(U.size(), nf));\n  }\n\n  for (auto i = 0u; i + 1 < tau_s.size(); ++i) {\n    const double T = t0 + (tf - t0) * tau_s(i);\n\n    const Eigen::VectorXd x = X.col(i);\n    const Eigen::VectorXd u = U.col(i);\n\n    if constexpr (Deriv) {\n      const auto [fval, dfval] = diff::dr(f, wrt(T, x, u));\n\n      assert(fval.rows() == Eigen::Index(nf));\n      assert(dfval.rows() == Eigen::Index(nf));\n      assert(dfval.cols() == Eigen::Index(1 + nu + nx));\n\n      Fval.col(i) = fval;\n\n      for (auto row = 0u; row < nf; ++row) {\n        dvecF_dt0.insert(nf * i + row, 0) = dfval(row, 0) * (1. - tau_s(i));\n        dvecF_dtf.insert(nf * i + row, 0) = dfval(row, 0) * tau_s(i);\n        for (auto col = 0u; col < nx; ++col) {\n          dvecF_dvecX.insert(nf * i + row, i * nx + col) = dfval(row, 1 + col);\n        }\n        for (auto col = 0u; col < nu; ++col) {\n          dvecF_dvecU.insert(nf * i + row, i * nu + col) = dfval(row, 1 + nx + col);\n        }\n      }\n    } else {\n      Fval.col(i) = f(T, x, u);\n    }\n  }\n\n  if constexpr (Deriv) {\n    dvecF_dt0.makeCompressed();\n    dvecF_dtf.makeCompressed();\n    dvecF_dvecX.makeCompressed();\n    dvecF_dvecU.makeCompressed();\n\n    return std::make_tuple(\n      std::move(Fval),\n      std::move(dvecF_dt0),\n      std::move(dvecF_dtf),\n      std::move(dvecF_dvecX),\n      std::move(dvecF_dvecU));\n  } else {\n    return Fval;\n  }\n}\n\n/**\n * @brief Evaluate a function at endpoints.\n *\n * Returns a nf vector\n *\n *  F = f(t_0, t_f, x_0, x_f, q)\n *\n * @tparam Der return derivatives w.r.t variables\n *\n * @param nf dimensionality of f image\n * @param nf state space degrees of freedom\n * @param f function (t0, tf, x0, xf, q) -> R^nf\n * @param t0 initial time\n * @param tf final time\n * @param X state variables (size nx x N+1)\n * @param q integrals\n *\n * @return If Deriv == false,\n * If Deriv == true, {F, dF_dt0, dF_dtf, dF_dvecX, dF_dQ},\n */\ntemplate<bool Deriv>\nauto colloc_eval_endpt(\n  const std::size_t nf,\n  const std::size_t nx,\n  auto && f,\n  [[maybe_unused]] const double t0,\n  const double tf,\n  const Eigen::MatrixXd & X,\n  const Eigen::VectorXd & Q)\n{\n  assert(static_cast<std::size_t>(X.rows()) == nx);\n\n  // NOTE: for now t0 = 0 and we don't want t0 in signatures\n  assert(t0 == 0);\n\n  const Eigen::VectorXd x0 = X.leftCols(1);\n  const Eigen::VectorXd xf = X.rightCols(1);\n\n  if constexpr (!Deriv) {\n    return f(tf, x0, xf, Q);\n  } else {\n    const auto [Fval, J] = diff::dr(f, wrt(tf, x0, xf, Q));\n\n    assert(static_cast<std::size_t>(J.rows()) == nf);\n    assert(static_cast<std::size_t>(J.cols()) == 1 + 2 * nx + Q.size());\n\n    Eigen::SparseMatrix<double> dF_dt0, dF_dtf, dF_dvecX, dF_dQ;\n\n    dF_dt0.resize(nf, 1);\n    // dF_dt0.reserve(nf);\n    // for (auto i = 0u; i < nf; ++i) { dF_dt0.insert(i, 0) = J(i, 0); }\n\n    dF_dtf.resize(nf, 1);\n    dF_dtf.reserve(nf);\n    for (auto i = 0u; i < nf; ++i) { dF_dtf.insert(i, 0) = J(i, 0); }\n\n    dF_dvecX.resize(nf, X.size());\n    Eigen::VectorXi pattern = Eigen::VectorXi::Zero(X.size());\n    pattern.head(nx).setConstant(nf);\n    pattern.tail(nx).setConstant(nf);\n    dF_dvecX.reserve(pattern);\n\n    for (auto row = 0u; row < nf; ++row) {\n      for (auto col = 0u; col < nx; ++col) {\n        dF_dvecX.insert(row, col)                 = J(row, 1 + col);\n        dF_dvecX.insert(row, X.size() - nx + col) = J(row, 1 + nx + col);\n      }\n    }\n\n    dF_dQ.resize(nf, Q.size());\n    dF_dQ.reserve(Eigen::VectorXi::Constant(Q.size(), nf));\n\n    for (auto row = 0u; row < nf; ++row) {\n      for (auto col = 0u; col < Q.size(); ++col) {\n        dF_dQ.insert(row, col) = J(row, 1 + 2 * nx + col);\n      }\n    }\n\n    dF_dt0.makeCompressed();\n    dF_dtf.makeCompressed();\n    dF_dvecX.makeCompressed();\n    dF_dQ.makeCompressed();\n\n    return std::make_tuple(Fval, dF_dt0, dF_dtf, dF_dvecX, dF_dQ);\n  }\n}\n\n/**\n * @brief Evaluate dynamics constraint in all collocation points of a Mesh.\n *\n * @tparam Der return derivatives w.r.t variables\n *\n * @param nx state space degrees of freedom\n * @param f right-hand side of dynamics with signature (t, x, u) -> dx where x and dx are size nx\n * x 1 and u is size nu x 1\n * @param m mesh with a total of N collocation points\n * @param tf final time (variable of size 1)\n * @param x state values (variable of size nx x N+1)\n * @param u input values (variable of size nu x N)\n *\n * @return {F, dvecF_dt0, dvecF_dtf, dvecF_dvecX, dvecF_dvecU},\n * where vec(X) stacks the columns of X into a single column vector.\n */\ntemplate<bool Deriv>\nauto colloc_dyn(\n  const std::size_t nx,\n  auto && f,\n  const MeshType auto & m,\n  const double t0,\n  const double tf,\n  const Eigen::MatrixXd & X,\n  const Eigen::MatrixXd & U)\n{\n  assert(m.N_colloc() + 1 == static_cast<std::size_t>(X.cols()));  // extra at the end\n  assert(m.N_colloc() == static_cast<std::size_t>(U.cols()));      // one per collocation point\n  assert(nx == static_cast<std::size_t>(X.rows()));                // one per collocation point\n\n  Eigen::MatrixXd Fval;\n  Eigen::MatrixXd XD(nx, m.N_colloc());\n  Eigen::SparseMatrix<double> dvecF_dt0, dvecF_dtf, dvecF_dvecX, dvecF_dvecU, dvecXD_dvecX;\n\n  if constexpr (!Deriv) {\n    Fval = colloc_eval<0>(nx, f, m, t0, tf, X, U);\n  } else {\n    std::tie(Fval, dvecF_dt0, dvecF_dtf, dvecF_dvecX, dvecF_dvecU) =\n      colloc_eval<1>(nx, f, m, t0, tf, X, U);\n\n    dvecXD_dvecX.resize(XD.size(), X.size());\n\n    // reserve sparsity pattern\n    Eigen::VectorXi pattern = Eigen::VectorXi::Zero(X.size());\n    for (auto M = 0u, i = 0u; i < m.N_ivals(); ++i) {\n      const std::size_t K = m.N_colloc_ival(i);\n      pattern.segment(M, (K + 1) * nx) += Eigen::VectorXi::Constant((K + 1) * nx, K);\n      M += K * nx;\n    }\n    dvecXD_dvecX.reserve(pattern);\n  }\n\n  for (auto i = 0u, M = 0u; i < m.N_ivals(); M += m.N_colloc_ival(i), ++i) {\n    const std::size_t K     = m.N_colloc_ival(i);\n    const Eigen::MatrixXd D = m.interval_diffmat(i);\n    XD.block(0, M, nx, K)   = X.block(0, M, nx, K + 1) * D;\n\n    if constexpr (Deriv) {\n      // vec(X * D) = kron(D', I) * vec(X), so derivative w.r.t vec(X) = kron(D', I)\n      for (auto i = 0u; i < K; ++i) {\n        for (auto j = 0u; j < K + 1; ++j) {\n          for (auto diag = 0u; diag < nx; ++diag) {\n            dvecXD_dvecX.coeffRef(M * nx + i * nx + diag, M * nx + j * nx + diag) += D(j, i);\n          }\n        }\n      }\n    }\n  }\n\n  Eigen::VectorXd Fv = (XD - (tf - t0) * Fval).reshaped();\n\n  // scale equalities by by quadrature weights\n  const auto N      = m.N_colloc();\n  const auto [n, w] = m.all_nodes_and_weights();\n\n  // vec(A * W) = kron(W', I) * vec(A), so we apply kron(W', I) on the left\n\n  Eigen::SparseMatrix<double> W(N, N);\n  W.reserve(Eigen::VectorXi::Ones(N));\n  for (auto i = 0u; i < N; ++i) { W.insert(i, i) = w(i); }\n\n  const Eigen::SparseMatrix<double> W_kron_I = kron_identity(W, nx);\n\n  Fv.applyOnTheLeft(W_kron_I);\n\n  if constexpr (!Deriv) {\n    return Fv;\n  } else {\n    dvecXD_dvecX.makeCompressed();\n\n    Eigen::SparseMatrix<double> dF_dt0 = -(tf - t0) * dvecF_dt0;\n    dF_dt0 += Fval.reshaped().sparseView();  // OK since dvecF_dtf is dense\n    dF_dt0 = W_kron_I * dF_dt0;\n\n    Eigen::SparseMatrix<double> dF_dtf = -(tf - t0) * dvecF_dtf;\n    dF_dtf -= Fval.reshaped().sparseView();  // OK since dvecF_dtf is dense\n    dF_dtf = W_kron_I * dF_dtf;\n\n    Eigen::SparseMatrix<double> dF_dvecX = dvecXD_dvecX;\n    dF_dvecX -= (tf - t0) * dvecF_dvecX;\n    dF_dvecX = W_kron_I * dF_dvecX;\n\n    Eigen::SparseMatrix<double> dF_dvecU = -(tf - t0) * W_kron_I * dvecF_dvecU;\n\n    dF_dt0.makeCompressed();\n    dF_dtf.makeCompressed();\n    dF_dvecX.makeCompressed();\n    dF_dvecU.makeCompressed();\n\n    return std::make_tuple(\n      std::move(Fv),\n      std::move(dF_dt0),\n      std::move(dF_dtf),\n      std::move(dF_dvecX),\n      std::move(dF_dvecU));\n  }\n}\n\n/**\n * @brief Calculate relative dynamics errors for each interval in mesh.\n *\n * @param nx state space dimension\n * @param f dynamics function\n * @param m Mesh\n * @param t0 initial time variable\n * @param tf final time variable\n * @param x state trajectory\n * @param u input trajectory\n *\n * @return vector with relative errors for every interval in m\n */\nEigen::VectorXd mesh_dyn_error(\n  const std::size_t nx,\n  auto && f,\n  const MeshType auto & m,\n  const double t0,\n  const double tf,\n  const std::function<Eigen::VectorXd(double)> xfun,\n  const std::function<Eigen::VectorXd(double)> ufun)\n{\n  const auto N = m.N_ivals();\n\n  // create a new mesh where each interval is extended\n  Mesh mext = m;\n  for (auto i = 0u; i < N; ++i) {\n    const std::size_t K = m.N_colloc_ival(i);\n    mext.set_N_colloc_ival(i, K + 1);\n  }\n\n  Eigen::VectorXd ival_errs(N);\n\n  // for each interval\n  for (auto i = 0u, M = 0u; i < N; M += m.N_colloc_ival(i), ++i) {\n    const std::size_t Kext = mext.N_colloc_ival(i);\n\n    const auto [tau_s, weights] = mext.interval_nodes_and_weights(i);\n\n    assert(std::size_t(tau_s.size()) == Kext + 1);\n\n    // evaluate X and F at those points\n    Eigen::MatrixXd Fval(nx, Kext + 1);\n    Eigen::MatrixXd Xval(nx, Kext + 1);\n    for (auto j = 0u; j < Kext + 1; ++j) {\n      const double tj = t0 + (tf - t0) * tau_s(j);\n\n      // evaluate x and u values at tj using current degree polynomials\n      const auto Xj = xfun(tj);\n      const auto Uj = ufun(tj);\n\n      // evaluate right-hand side of dynamics at tj\n      Fval.col(j) = f(tj, Xj, Uj);\n\n      // store x values for later comparison\n      Xval.col(j) = Xj;\n    }\n\n    // \"integrate\" system inside interval\n    const Eigen::MatrixXd Xval_est =\n      Xval.col(0).replicate(1, Kext) + (tf - t0) * Fval.leftCols(Kext) * mext.interval_intmat(i);\n\n    // absolute error in interval\n    Eigen::VectorXd e_abs = (Xval_est - Xval.rightCols(Kext)).colwise().norm();\n    Eigen::VectorXd e_rel = e_abs / (1. + Xval.rightCols(Kext).colwise().norm().maxCoeff());\n\n    // mex relative error on interval\n    ival_errs(i) = e_rel.maxCoeff();\n  }\n\n  return ival_errs;\n}\n\n/**\n * @brief Refine intervals in mesh to satisfy a target error criterion.\n * @param[in, out] m mesh to refine\n * @param[in] errs relative errors for all intervals (@see mesh_dyn_error())\n * @param[in] target_err target relative error\n */\nvoid mesh_refine(MeshType auto & m, const Eigen::VectorXd & errs, const double target_err)\n{\n  const auto N = m.N_ivals();\n\n  assert(N == std::size_t(errs.size()));\n\n  for (auto i = 0u; i < N; ++i) {\n    const auto Nmi = N - 1 - i;\n    const auto Ki  = m.N_colloc_ival(Nmi);\n\n    if (errs(Nmi) > target_err) {\n      const auto Ktarget = Ki + std::lround(std::log(errs(Nmi) / target_err) / std::log(Ki) + 1);\n      m.refine_ph(Nmi, Ktarget);\n    }\n  }\n}\n\n/**\n * @brief Evaluate integral constraint on Mesh.\n *\n * @tparam Der return derivatives w.r.t variables\n *\n * @param nq number of integrals\n * @param g integrand with signature (t, x, u) -> R^{nq} where x is size nx x 1 and u is size nu x\n * 1\n * @param m mesh\n * @param t0 initial time (variable of size 1)\n * @param tf final time (variable of size 1)\n * @param I values (variable of size nq)\n * @param X state values (variable of size nx x N+1)\n * @param U input values (variable of size nu x N)\n *\n * @return {G, dvecG_dt0, dvecG_dtf, dvecG_dvecX, dvecG_dvecU},\n * where vec(X) stacks the columns of X into a single column vector.\n */\ntemplate<bool Deriv>\nauto colloc_int(\n  const std::size_t nq,\n  auto && g,\n  const MeshType auto & m,\n  const double t0,\n  const double tf,\n  const Eigen::VectorXd & I,\n  const Eigen::MatrixXd & X,\n  const Eigen::MatrixXd & U)\n{\n  assert(static_cast<std::size_t>(I.size()) == nq);\n\n  const std::size_t N = m.N_colloc();\n\n  const auto [n, w] = m.all_nodes_and_weights();\n\n  if constexpr (Deriv == false) {\n    const auto Gv              = colloc_eval<Deriv>(nq, g, m, t0, tf, X, U);\n    const Eigen::VectorXd Iest = Gv * w.head(N);\n    Eigen::VectorXd Rv         = (tf - t0) * Iest - I;\n    return Rv;\n  } else {\n    const auto [Gv, dvecG_dt0, dvecG_dtf, dvecG_dvecX, dvecG_dvecU] =\n      colloc_eval<Deriv>(nq, g, m, t0, tf, X, U);\n    const Eigen::VectorXd Iest = Gv * w.head(N);\n\n    Eigen::VectorXd Rv = (tf - t0) * Iest - I;\n\n    const Eigen::SparseMatrix<double> w_kron_I =\n      (tf - t0) * kron_identity(w.head(N).transpose(), nq);\n\n    Eigen::SparseMatrix<double> dR_dt0 = w_kron_I * dvecG_dt0;\n    for (auto i = 0u; i < Iest.size(); ++i) { dR_dt0.coeffRef(i, 0) -= Iest(i); }\n\n    Eigen::SparseMatrix<double> dR_dtf = w_kron_I * dvecG_dtf;\n    for (auto i = 0u; i < Iest.size(); ++i) { dR_dtf.coeffRef(i, 0) += Iest(i); }\n\n    Eigen::SparseMatrix<double> dR_dvecI = -sparse_identity(nq);\n\n    Eigen::SparseMatrix<double> dR_dvecX = w_kron_I * dvecG_dvecX;\n\n    Eigen::SparseMatrix<double> dR_dvecU = w_kron_I * dvecG_dvecU;\n\n    dR_dt0.makeCompressed();\n    dR_dtf.makeCompressed();\n    dR_dvecI.makeCompressed();\n    dR_dvecX.makeCompressed();\n    dR_dvecU.makeCompressed();\n\n    return std::make_tuple(\n      std::move(Rv),\n      std::move(dR_dt0),\n      std::move(dR_dtf),\n      std::move(dR_dvecI),\n      std::move(dR_dvecX),\n      std::move(dR_dvecU));\n  }\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__COLLOCATION_HPP_\n", "meta": {"hexsha": "97baf86c2ed046e3f1432dcf607af0c1d91274af", "size": 27210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/collocation.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/collocation.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/collocation.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": 31.7132867133, "max_line_length": 100, "alphanum_fraction": 0.6118338846, "num_tokens": 8699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.6477982179521105, "lm_q1q2_score": 0.5556606451180338}}
{"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_COMPLEX_GENERIC_POW_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_COMPLEX_GENERIC_POW_HPP_INCLUDED\n#include <nt2/exponential/functions/pow.hpp>\n#include <nt2/include/functions/pow.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/sincos.hpp>\n#include <nt2/include/functions/log.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/seladd.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/is_real.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/imag.hpp>\n#include <nt2/include/functions/arg.hpp>\n#include <nt2/include/functions/logical_not.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <nt2/sdk/complex/meta/as_complex.hpp>\n#include <nt2/sdk/complex/meta/as_real.hpp>\n#include <nt2/sdk/complex/meta/as_dry.hpp>\n#include <nt2/sdk/simd/logical.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)\n                            , (generic_< complex_<floating_<A0> > >)\n                              (generic_< complex_<floating_<A0> > >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      return exp(a1*log(a0));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< complex_<floating_<A0> > >)\n                                (generic_< floating_<A1> >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename meta::as_real<result_type>::type rtype;\n      typedef typename meta::as_imaginary< rtype>::type itype;\n      rtype t = nt2::arg(a0);\n      rtype a = nt2::abs(a0);\n      return nt2::pow(a, a1)*nt2::exp(itype(t*a1));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< complex_<floating_<A0> > >)\n                                (generic_< dry_<floating_<A1> > >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return pow(a0, nt2::real(a1));\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< floating_<A0> >)\n                                (generic_< complex_<floating_<A1> > >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        typedef typename meta::as_dry<A0>::type dtype;\n        return nt2::exp(a1*nt2::log(dtype(a0)));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< dry_ < floating_<A0> > > )\n                                (generic_< complex_<floating_<A1> > >)\n                            )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< complex_<floating_<A0> > >)\n                              (generic_< imaginary_<floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< imaginary_<floating_<A0> > >)\n                              (generic_< complex_<floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< imaginary_<floating_<A0> > >)\n                              (generic_< floating_<A1> >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              , (generic_< imaginary_<floating_<A0> > >)\n                              (generic_< dry_ < floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              ,  (generic_< floating_<A0> >)\n                              (generic_< imaginary_<floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    typedef typename meta::as_dry<A0>::type dtype;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(dtype(a0)));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              ,  (generic_< dry_ < floating_<A0> > > )\n                              (generic_< imaginary_<floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::pow_, tag::cpu_\n                              , (A0)(A1)\n                              ,  (generic_< dry_ < floating_<A0> > > )\n                              (generic_< dry_<floating_<A1> > >)\n                              )\n  {\n    typedef typename meta::as_complex<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n      {\n        return nt2::exp(a1*nt2::log(a0));\n      }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "3e7268a9c49ad6b0639e0e6f596b815c758cb2cd", "size": 6769, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/exponential/include/nt2/exponential/functions/complex/generic/pow.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/type/complex/exponential/include/nt2/exponential/functions/complex/generic/pow.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/exponential/include/nt2/exponential/functions/complex/generic/pow.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3604060914, "max_line_length": 80, "alphanum_fraction": 0.4978578815, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.5556606381638404}}
{"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 (adopted from previous implementation)\n\n\n#ifndef ITL_GMRES_HOUSEHOLDER_INCLUDE\n#define ITL_GMRES_HOUSEHOLDER_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 \"solver/itl/details.hpp\"\n\nnamespace itl\n{\n\n  /// Generalized Minimal Residual method (without restart) using householder othogonalization.\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 LeftPreconditioner, typename Iteration>\n  int gmres_householder_full(const Matrix& A, Vector& x, const Vector& b,\n                             LeftPreconditioner& L, Iteration& iter)\n  {\n    using mtl::irange;\n    using std::abs;\n    using math::reciprocal;\n    using mtl::iall;\n    using mtl::imax;\n    using mtl::signum;\n    using mtl::vector::dot;\n    using mtl::conj;\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()), dbl_tol= 1.e-16;\n    Scalar       rho, bnrm2, temp, beta;\n    Size         k, kmax(std::min(size(x), Size(iter.max_iterations() - iter.iterations())));\n    Vector       w(b - A *x), r(solve(L,w));\n    mtl::matrix::multi_vector<Vector>   V(Vector(resource(x), zero), kmax+1);\n    mtl::vector::dense_vector<Scalar>   sn(kmax, zero), cs(kmax, zero), s(kmax+1, zero), y(kmax, zero);  // replicated in distributed solvers\n    mtl::matrix::dense2D<Scalar>        H(kmax, kmax);\n\n    bnrm2 = two_norm(b);\n    if (bnrm2 < dbl_tol)\n      bnrm2 = 1.0;\n\n    temp = two_norm(r);\t\t\t\t// norm of preconditioned residual\n    rho = temp * reciprocal(bnrm2);\n    if (iter.finished(rho))\t\t\t// initial guess is good enough solution\n      return iter;\n\n    // u = r + sign(r(0))*||r||*e0\n    beta = signum(r[0])*temp;\n    w = r;\n    w[0] += beta;\n    w *= reciprocal(two_norm(w));\n\n    V.vector(0) = w;\n    H = zero;\n    s[0] = -beta;\n\n    // GMRES iteration\n    for (k= 0; k < kmax && !iter.finished(rho); ++k, ++iter)\n    {\n\n      w = (-2.0 * V.vector(k)[k])*V.vector(k);\n      w[k] += 1.0;\n      // v := P_0*...*P_{k-2}*(P_{k-1} * e_k)\n      for (Size i= k; i > 0; i--)\n      {\n        temp = 2.0 * dot(V.vector(i-1), w);\n        w -= temp * V.vector(i-1);\n      }\n\n      temp = two_norm(w);\n      if (temp == zero)\n        return iter.fail(2, \"GMRES: breakdown\");\n\n      // Explicitly normalize v to reduce the effects of round-off.\n      w *= reciprocal(temp);\n      w = solve(L, Vector(A*w));\n\n      // P_{k-1}*...*P_0*Av\n      for (Size i = 0; i <= k; i++)\n      {\n        temp = 2.0 * dot(V.vector(i), w);\n        w -= temp * V.vector(i);\n      }\n\n      temp = two_norm(w);\n      if (temp == zero)\n        return iter.fail(3, \"GMRES: breakdown\");\n\n      irange range_to_end(k+1,imax);\n      set_to_zero(V.vector(k+1));\n      V.vector(k+1)[range_to_end] = w[range_to_end];\n      beta = two_norm(V.vector(k+1));\n      if (beta != 0.0)\n      {\n        beta *= signum(w[k+1]);\n        V.vector(k+1)[k+1] += beta;\n        V.vector(k+1) *= reciprocal(two_norm(V.vector(k+1)));\n\n        w[k+1] = -beta;\n      }\n\n      for (Size i= 0; i < k; i++)\n      {\n        temp   =  conj(cs[i])*w[i] + conj(sn[i])*w[i+1];\n        w[i+1] = -sn[i]*w[i] + cs[i]*w[i+1];\n        w[i]   =  temp;\n      }\n\n      details::rotmat(w[k], w[k+1], cs[k], sn[k]);\n\n      s[k+1] = -sn[k]*s[k];\n      s[k]   = conj(cs[k])*s[k];\n      w[k]   = cs[k]*w[k] + sn[k]*w[k+1];\n      w[k+1] = 0.0;\n\n      irange range(num_rows(H));\n      H[iall][k] = w[range];\n\n      rho = std::abs(s[k+1]) / bnrm2;\n    }\n\n    // reduce k, to get regular matrix\n    //     while (k > 0 && std::abs(s[k-1]) <= iter.atol()) k--;\n\n    // iteration is finished -> compute x: solve H*y=s 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    kmax = k-1;\n\n    w = V.vector(kmax) * (-2.0 * y[kmax] * conj(V.vector(kmax)[kmax]));\n    w[kmax] += y[kmax];\n    for (Size i= kmax; i > 0; i--)\n    {\n      w[i-1] += y[i-1];\n      temp = 2.0 * dot(V.vector(i-1), w);\n      w -= temp * V.vector(i-1);\n    }\n    x += w;\n\n    r = b - A*x;\n    return iter.terminate(r);\n  }\n\n  /// Generalized Minimal Residual method with restart\n  template <typename Matrix, typename Vector, typename LeftPreconditioner,\n            typename Iteration>\n  int gmres_householder(const Matrix& A, Vector& x, const Vector& b,\n                        LeftPreconditioner& L,\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      gmres_householder_full(A, x, b, L, 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_GMRES_HOUSEHOLDER_INCLUDE\n\n\n", "meta": {"hexsha": "0f89adf20ec61cf001110b1f5f631324309d2293", "size": 6642, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/gmres_householder.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/solver/itl/gmres_householder.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/itl/gmres_householder.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0542986425, "max_line_length": 141, "alphanum_fraction": 0.5712134899, "num_tokens": 1918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.555635314986499}}
{"text": "#pragma once\n#include <stdint.h>\n#include \"settings.hpp\"\n#include \"weight_initialization.hpp\"\n#include \"activations.hpp\"\n#if USE_EIGEN == 1\n#include <Eigen/Dense>\n#endif\n\nnamespace nn\n{\n\tenum class LayerType\n\t{\n\t\tkInput,\n\t\tkFC,\n\t\tkSoftmax\n\t};\n\n\t// any layer has some amount of units and activation function\n#if USE_EIGEN == 1\n\tclass layer\n\t{\n\tpublic:\n\t\tusing MatrixType = Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic>;\n\n\t\tlayer(LayerType type,\n\t\t\tuint32_t unitsInLayer,\n\t\t\tuint32_t unitsInPreviousLayer, \n\t\t\tActivationType activationType, \n\t\t\tWeightInitializationType weightInitializationType) : \n\t\t\tm_type(type),\n\t\t\tm_unitsInLayer(unitsInLayer), \n\t\t\tm_unitsInPreviousLayer(unitsInPreviousLayer)\n\t\t{\n\t\t\t// set activation type\n\t\t\tif (activationType == ActivationType::kSigmoid)\n\t\t\t{\n\t\t\t\tm_activation = activation<ActivationType::kSigmoid>;\n\t\t\t\tm_activationDerivative = activation_derivative<ActivationType::kSigmoid>;\n\t\t\t}\n\t\t\telse if (activationType == ActivationType::kLinear)\n\t\t\t{\n\t\t\t\tm_activation = activation<ActivationType::kLinear>;\n\t\t\t\tm_activationDerivative = activation_derivative<ActivationType::kLinear>;\n\t\t\t}\n\t\t\telse if (activationType == ActivationType::kTanh)\n\t\t\t{\n\t\t\t\tm_activation = activation<ActivationType::kTanh>;\n\t\t\t\tm_activationDerivative = activation_derivative<ActivationType::kTanh>;\n\t\t\t}\n\t\t\telse if (activationType == ActivationType::kRelu)\n\t\t\t{\n\t\t\t\tm_activation = activation<ActivationType::kRelu>;\n\t\t\t\tm_activationDerivative = activation_derivative<ActivationType::kRelu>;\n\t\t\t}\n\t\t\telse if (activationType == ActivationType::kLRelu)\n\t\t\t{\n\t\t\t\tm_activation = activation<ActivationType::kLRelu>;\n\t\t\t\tm_activationDerivative = activation_derivative<ActivationType::kLRelu>;\n\t\t\t}\n\n\t\t\tif (type != LayerType::kInput)\n\t\t\t{\n\t\t\t\tif (weightInitializationType == WeightInitializationType::kGaussian)\n\t\t\t\t{\n\t\t\t\t\tm_weight = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer()).unaryExpr(weight_initalization<WeightInitializationType::kZeros>());\n\t\t\t\t\tm_nabla_w = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer());\n\t\t\t\t\tm_bias = MatrixType::Zero(UnitsInLayer(), 1).unaryExpr(weight_initalization<WeightInitializationType::kZeros>());\n\t\t\t\t\tm_nabla_b = MatrixType::Zero(UnitsInLayer(), 1);\n\t\t\t\t}\n\t\t\t\telse if (weightInitializationType == WeightInitializationType::kSequentialDebug)\n\t\t\t\t{\n\t\t\t\t\tm_weight = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer()).unaryExpr(weight_initalization<WeightInitializationType::kSequentialDebug>());\n\t\t\t\t\tm_nabla_w = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer());\n\t\t\t\t\tm_bias = MatrixType::Zero(UnitsInLayer(), 1).unaryExpr(weight_initalization<WeightInitializationType::kSequentialDebug>());\n\t\t\t\t\tm_nabla_b = MatrixType::Zero(UnitsInLayer(), 1);\n\t\t\t\t}\n\t\t\t\telse if (weightInitializationType == WeightInitializationType::kUniform)\n\t\t\t\t{\n\t\t\t\t\tm_weight = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer()).unaryExpr(weight_initalization<WeightInitializationType::kUniform>());\n\t\t\t\t\tm_nabla_w = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer());\n\t\t\t\t\tm_bias = MatrixType::Zero(UnitsInLayer(), 1).unaryExpr(weight_initalization<WeightInitializationType::kUniform>());\n\t\t\t\t\tm_nabla_b = MatrixType::Zero(UnitsInLayer(), 1);\n\t\t\t\t}\n\t\t\t\telse if (weightInitializationType == WeightInitializationType::kGaussian)\n\t\t\t\t{\n\t\t\t\t\tm_weight = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer()).unaryExpr(weight_initalization<WeightInitializationType::kGaussian>());\n\t\t\t\t\tm_nabla_w = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer());\n\t\t\t\t\tm_bias = MatrixType::Zero(UnitsInLayer(), 1).unaryExpr(weight_initalization<WeightInitializationType::kGaussian>());\n\t\t\t\t\tm_nabla_b = MatrixType::Zero(UnitsInLayer(), 1);\n\t\t\t\t}\n\t\t\t\telse if (weightInitializationType == WeightInitializationType::kWeightedGaussian)\n\t\t\t\t{\n\t\t\t\t\tm_weight = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer()).unaryExpr(weight_initalization<WeightInitializationType::kWeightedGaussian>(UnitsInLayer()));\n\t\t\t\t\tm_nabla_w = MatrixType::Zero(UnitsInLayer(), UnitsInPreviousLayer());\n\t\t\t\t\tm_bias = MatrixType::Zero(UnitsInLayer(), 1).unaryExpr(weight_initalization<WeightInitializationType::kWeightedGaussian>(UnitsInLayer()));\n\t\t\t\t\tm_nabla_b = MatrixType::Zero(UnitsInLayer(), 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t~layer() {}\n\n\t\tvoid computeWeightedSum(const MatrixType& input) \n\t\t{\n\t\t\tm_z.noalias() = m_weight * input;\n\t\t\tfor (int i = 0; i < m_z.cols(); ++i)\n\t\t\t\tm_z.col(i).noalias() += m_bias;\n\t\t\t\n\t\t}\n\t\tvoid setActivations(const MatrixType& input) { m_a.noalias() = input; }\n\t\tvoid computeActivations(const MatrixType& input) \n\t\t{ \n\t\t\tif (m_type == LayerType::kFC)\n\t\t\t\tm_a.noalias() = input.unaryExpr(m_activation);\n\t\t\telse if (m_type == LayerType::kSoftmax)\n\t\t\t{\n\t\t\t\tif (m_a.rows() != input.rows() || m_a.cols() != input.cols())\n\t\t\t\t\tm_a = MatrixType::Zero(input.rows(), input.cols());\n\t\t\t\tMatrixType maxCol(m_a.rows(), 1);\n\t\t\t\tfor (int i = 0; i < input.cols(); ++i)\n\t\t\t\t{\n\t\t\t\t\tmaxCol.setConstant(input.maxCoeff()); // prevent softmax overflow\n\t\t\t\t\tm_a.col(i).noalias() = (input.col(i) - maxCol).unaryExpr(&expf);\n\t\t\t\t\tm_a.col(i) /= m_a.col(i).sum();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvoid computeActivationDerivatives(const MatrixType& input) \n\t\t{ \n\t\t\tif (m_type == LayerType::kFC)\n\t\t\t\tm_da.noalias() = input.unaryExpr(m_activationDerivative);\n\t\t\telse if (m_type == LayerType::kSoftmax)\n\t\t\t\tm_da = MatrixType::Ones(m_a.rows(), m_a.cols());\n\t\t}\n\n\t\tMatrixType computeWeightedSumExplicit(const MatrixType& input)\n\t\t{\n\t\t\tMatrixType result = m_weight * input;\n\t\t\tfor (int i = 0; i < result.cols(); ++i)\n\t\t\t\tresult.col(i).noalias() += m_bias;\n\t\t\treturn result;\n\t\t}\n\n\t\tMatrixType computeActivationsExplicit(const MatrixType& input)\n\t\t{\n\t\t\tMatrixType result;\n\t\t\tif (m_type == LayerType::kFC)\n\t\t\t\tresult.noalias() = input.unaryExpr(m_activation);\n\t\t\telse if (m_type == LayerType::kSoftmax)\n\t\t\t{\n\t\t\t\tif (result.rows() != input.rows() || result.cols() != input.cols())\n\t\t\t\t\tresult = MatrixType::Zero(input.rows(), input.cols());\n\t\t\t\tMatrixType maxCol(result.rows(), 1);\n\t\t\t\tfor (int i = 0; i < input.cols(); ++i)\n\t\t\t\t{\n\t\t\t\t\tmaxCol.setConstant(input.maxCoeff()); // prevent softmax overflow\n\t\t\t\t\tresult.col(i).noalias() = (input.col(i) - maxCol).unaryExpr(&expf);\n\t\t\t\t\tresult.col(i) /= result.col(i).sum();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\tMatrixType computeActivationDerivativesExplicit(const MatrixType& input)\n\t\t{\n\t\t\tMatrixType result;\n\t\t\tif (m_type == LayerType::kFC)\n\t\t\t\tresult.noalias() = input.unaryExpr(m_activationDerivative);\n\t\t\telse if (m_type == LayerType::kSoftmax)\n\t\t\t\tresult = MatrixType::Ones(input.rows(), input.cols());\n\t\t\treturn result;\n\t\t}\n\n\n\t\tconst MatrixType& getWeightedSum() const { return m_z; }\n\t\tconst MatrixType& getActivations() const { return m_a; }\n\t\tconst MatrixType& getActivationDerivatives() const { return m_da; }\n\t\tconst MatrixType& getWeights() const { return m_weight; }\n\t\tMatrixType& getWeights() { return m_weight; }\n\t\tMatrixType& getBias() { return m_bias; }\n\t\tMatrixType& getNablaB() { return m_nabla_b; }\n\t\tMatrixType& getNablaW() { return m_nabla_w; }\n\n\t\tuint32_t UnitsInLayer() const { return m_unitsInLayer; }\n\t\tuint32_t UnitsInPreviousLayer() const { return m_unitsInPreviousLayer; }\n\tprivate:\n\t\tLayerType m_type;\n\t\tuint32_t m_unitsInLayer;\n\t\tuint32_t m_unitsInPreviousLayer;\n\t\tMatrixType m_z;\n\t\tMatrixType m_a;\n\t\tMatrixType m_da;\n\n\t\tMatrixType m_weight;\n\t\tMatrixType m_nabla_w;\n\t\tMatrixType m_bias;\n\t\tMatrixType m_nabla_b;\n\t\tActivationFunction m_activation = nullptr;\n\t\tActivationFunction m_activationDerivative = nullptr;\n\t};\n#endif\n}", "meta": {"hexsha": "8a381033e02b8e4c45851ccab211aa8f63e2e345", "size": 7494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/layer.hpp", "max_stars_repo_name": "dmitryduka/nn", "max_stars_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-07T19:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-07T19:40:16.000Z", "max_issues_repo_path": "include/layer.hpp", "max_issues_repo_name": "dmitryduka/nn", "max_issues_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-09-23T14:00:59.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-23T14:01:47.000Z", "max_forks_repo_path": "include/layer.hpp", "max_forks_repo_name": "dmitryduka/nn", "max_forks_repo_head_hexsha": "301bf81f68b9db564d01076303dac635b0ea6957", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.099009901, "max_line_length": 166, "alphanum_fraction": 0.712570056, "num_tokens": 2073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.5556353098165476}}
{"text": "#define DEBUG 1\n/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/7/3 5:48:49\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// -----Geometry Library-- ---\n// Referring to the great source codes:\n//   - Maehara-san's algorithm library: http://www.prefield.com/algorithm/index.html\n// Many thanks.\n\n// ----- Basic Classes -----\n\nconstexpr ld EPSILON{1e-12};\n\n// ----- Point -----\n\nusing Point = complex<ld>;\nbool operator<(Point const &p, Point const &q)\n{\n  return real(p) != real(q) ? real(p) < real(q) : imag(p) < imag(q);\n}\nistream &operator>>(istream &is, Point &p)\n{\n  ld x, y;\n  is >> x >> y;\n  p = Point{x, y};\n  return is;\n}\n\nld OuterProduct(Point const &p, Point const &q)\n{\n  return imag(conj(p) * q);\n}\nld InnerProduct(Point const &p, Point const &q)\n{\n  return real(conj(p) * q);\n}\n\nPoint Normalize(Point const &p)\n{\n  return p / abs(p);\n}\n\n// ---- ccw -----\n\nint ccw(Point a, Point b, Point c)\n{\n  b -= a;\n  c -= a;\n  auto tmp{OuterProduct(b, c)};\n  if (tmp > 0)\n  {\n    return +1; // counter clockwise\n  }\n  if (tmp < 0)\n  {\n    return -1; // clockwise\n  }\n  if (InnerProduct(b, c) < 0)\n  {\n    return +2; // c--a--b on line\n  }\n  if (norm(b) < norm(c))\n  {\n    return -2; // a--b--c on line\n  }\n  return 0;\n}\n\n// ----- Geom -----\n\nusing Geom = vector<Point>;\n\nGeom &operator+=(Geom &g, Point const &p)\n{\n  for (auto &q : g)\n  {\n    q += p;\n  }\n  return g;\n}\nGeom operator+(Geom const &g, Point const &p)\n{\n  Geom h{g};\n  return h += p;\n}\nGeom &operator-=(Geom &g, Point const &p)\n{\n  return g += (-p);\n}\nGeom operator-(Geom const &g, Point const &p)\n{\n  return g + (-p);\n}\n\n// ----- Line -----\n\nstruct Segment;\n\nstruct Line : public Geom\n{\n  Line() {}\n  Line(Point const &p, Point const &q)\n  {\n    push_back(p);\n    push_back(q);\n  }\n};\n\n// ----- Segment -----\n\nstruct Segment : public Line\n{\n  Segment() {}\n  Segment(Point const &p, Point const &q)\n  {\n    push_back(p);\n    push_back(q);\n  }\n};\n\n// ----- Circle -----\n\nstruct Circle\n{\n  Point p;\n  ld r;\n\n  Circle() {}\n  Circle(Point const &p, ld r) : p(p), r(r) {}\n};\n\n// ----- Functions -----\n\n// ----- Rotate -----\n\nPoint Rotate(Point const &p, ld radian = M_PI / 2)\n{\n  return p * Point{cos(radian), sin(radian)};\n}\nGeom Rotate(Geom g, ld radian = M_PI / 2)\n{\n  for (auto &p : g)\n  {\n    p = Rotate(p, radian);\n  }\n  return g;\n}\n\n// ----- Projection and Reflection (Point and Line) -----\n\nPoint Projection(Line const &l, Point const &p)\n{\n  ld t{InnerProduct(p - l[0], l[0] - l[1]) / norm(l[0] - l[1])};\n  return l[0] + t * (l[0] - l[1]);\n}\n\nPoint Reflection(Line const &l, Point const &p)\n{\n  return p + ld{2} * (Projection(l, p) - p);\n}\n\n// ----- Intersect -----\n\nbool Intersect(Line const &l, Line const &m)\n{\n  return abs(OuterProduct(l[1] - l[0], m[1] - m[0])) > EPSILON || // non-parallel\n         abs(OuterProduct(l[1] - l[0], m[0] - l[0])) < EPSILON;   // same line\n}\nbool Intersect(Line const &l, Segment const &s)\n{\n  return OuterProduct(l[1] - l[0], s[0] - l[0]) * OuterProduct(l[1] - l[0], s[1] - l[0]) < EPSILON;\n}\nbool Intersect(Segment const &s, Line const &l)\n{\n  return Intersect(l, s);\n}\nbool Intersect(Line const &l, Point const &p)\n{\n  return abs(OuterProduct(l[1] - p, l[0] - p)) < EPSILON;\n}\nbool Intersect(Point const &p, Line const &l)\n{\n  return Intersect(l, p);\n}\nbool Intersect(Segment const &s, Segment const &t)\n{\n  return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&\n         ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;\n}\nbool Intersect(Segment const &s, Point const &p)\n{\n  return abs(s[0] - p) + abs(s[1] - p) - abs(s[1] - s[0]) < EPSILON; // triangle inequality\n}\nbool Intersect(Point const &p, Segment const &s)\n{\n  return Intersect(s, p);\n}\nbool Intersect(Circle const &a, Circle const &b)\n{\n  return a.r + b.r + EPSILON < abs(a.p - b.p);\n}\n\n// ----- Dist -----\n\nld Dist(Point const &p, Point const &q)\n{\n  return abs(p - q);\n}\nld Dist(Line const &l, Point const &p)\n{\n  return abs(p - Projection(l, p));\n}\nld Dist(Point const &p, Line const &l)\n{\n  return Dist(l, p);\n}\nld Dist(Line const &l, Line const &m)\n{\n  return Intersect(l, m) ? 0 : Dist(l, m[0]);\n}\nld Dist(Line const &l, Segment const &s)\n{\n  if (Intersect(l, s))\n  {\n    return 0;\n  }\n  return min(Dist(l, s[0]), Dist(l, s[1]));\n}\nld Dist(Segment const &s, Line const &l)\n{\n  return Dist(l, s);\n}\nld Dist(Segment const &s, Point const &p)\n{\n  auto r{Projection(static_cast<Line>(s), p)};\n  if (Intersect(s, r))\n  {\n    return abs(r - p);\n  }\n  return min(abs(s[0] - p), abs(s[1] - p));\n}\nld Dist(Point const &p, Segment const &s)\n{\n  return Dist(s, p);\n}\nld Dist(Segment const &s, Segment const &t)\n{\n  if (Intersect(s, t))\n  {\n    return 0;\n  }\n  return min({Dist(s, t[0]), Dist(s, t[1]), Dist(t, s[0]), Dist(t, s[1])});\n}\n\n// ----- IntersectionPoints ------\n\nvector<Point> IntersectionPoints(Circle const &a, Circle const &b)\n{\n  auto d{Dist(a.p, b.p)};\n  auto l{(a.r * a.r - b.r * b.r + d * d) / (2 * d)};\n  auto tmp{a.r * a.r - l * l};\n  if (tmp <= 0)\n  {\n    return {};\n  }\n  auto h{sqrt(tmp)};\n  vector<Point> res;\n  auto v{Normalize(b.p - a.p)};\n  auto w{Rotate(v)};\n  res.push_back(a.p + v * l + w * h);\n  res.push_back(a.p + v * l - w * h);\n  return res;\n}\n\nvector<Point> IntersectionPoints(Line const &l, Line const &m)\n{\n  auto A{OuterProduct(l[1] - l[0], m[1] - m[0])};\n  auto B{OuterProduct(l[1] - l[0], l[1] - m[0])};\n  if (abs(A) < EPSILON && abs(B) < EPSILON)\n  {\n    return {m[0], m[1], l[0], l[1]}; // same line\n  }\n  if (abs(A) < EPSILON)\n  {\n    assert(false); // Precondition is not satisfied.\n  }\n  return {m[0] + B / A * (m[1] - m[0])};\n}\n\n// ----- Contains -----\n\nenum class ContainState\n{\n  OUT,\n  ON,\n  IN\n};\n\nContainState Contains(Geom const &g, Point const &p)\n{\n  bool in{false};\n  for (auto i{size_t{0}}; i < g.size(); ++i)\n  {\n    auto a{g[i] - p};\n    auto b{g[(i + 1) % g.size()] - p};\n    if (imag(a) > imag(b))\n    {\n      swap(a, b);\n    }\n    if (imag(a) <= 0 && 0 < imag(b) && OuterProduct(a, b) < 0)\n    {\n      in = !in;\n    }\n    if (abs(OuterProduct(a, b)) < EPSILON && InnerProduct(a, b) < EPSILON)\n    {\n      return ContainState::ON;\n    }\n  }\n  return in ? ContainState::IN : ContainState::OUT;\n}\n\nContainState Contains(Circle const &c, Point const &p)\n{\n  auto d{Dist(c.p, p)};\n  if (abs(d - c.r) < EPSILON)\n  {\n    return ContainState::ON;\n  }\n  if (d > c.r)\n  {\n    return ContainState::OUT;\n  }\n  return ContainState::IN;\n}\n\nbool ContainStateToBool(ContainState s)\n{\n  return s == ContainState::IN || s == ContainState::ON;\n}\n\ntemplate <typename T, typename U>\nbool DoesContain(T const &a, U const &b)\n{\n  return ContainStateToBool(Contains(a, b));\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  ld A, B, H, M;\n  cin >> A >> B >> H >> M;\n  Point p{polar(A, 2 * M_PI * H / 12 + 2 * M_PI * M / (12 * 60))};\n  Point q{polar(B, 2 * M_PI * M / 60)};\n  cout << fixed << setprecision(12) << abs(p - q) << endl;\n}\n", "meta": {"hexsha": "eb5ae5900d2bc9e2884ea9e38f86a95c7f97d727", "size": 12449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0703_ABC168/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/0703_ABC168/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/0703_ABC168/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": 20.8875838926, "max_line_length": 99, "alphanum_fraction": 0.5665515302, "num_tokens": 4131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5556353077179607}}
{"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_STRATEGIES_GEOGRAPHIC_ANDOYER_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_ANDOYER_HPP\n\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n\n/*!\n\\brief Point-point distance approximation taking flattening into account\n\\ingroup distance\n\\tparam Spheroid The reference spheroid model\n\\tparam CalculationType \\tparam_calculation\n\\author After Andoyer, 19xx, republished 1950, republished by Meeus, 1999\n\\note Although not so well-known, the approximation is very good: in all cases the results\nare about the same as Vincenty. In my (Barend's) testcases the results didn't differ more than 6 m\n\\see http://nacc.upc.es/tierra/node16.html\n\\see http://sci.tech-archive.net/Archive/sci.geo.satellite-nav/2004-12/2724.html\n\\see http://home.att.net/~srschmitt/great_circle_route.html (implementation)\n\\see http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115 (implementation)\n\\see http://futureboy.homeip.net/frinksamp/navigation.frink (implementation)\n\\see http://www.voidware.com/earthdist.htm (implementation)\n*/\ntemplate\n<\n    typename Spheroid,\n    typename CalculationType = void\n>\nclass andoyer\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 Spheroid model_type;\n\n    inline andoyer()\n        : m_spheroid()\n    {}\n\n    explicit inline andoyer(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n\n\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& point1, Point2 const& point2) const\n    {\n        return calc<typename calculation_type<Point1, Point2>::type>\n            (\n                get_as_radian<0>(point1), get_as_radian<1>(point1),\n                get_as_radian<0>(point2), get_as_radian<1>(point2)\n            );\n    }\n\n    inline Spheroid const& model() const\n    {\n        return m_spheroid;\n    }\n\nprivate :\n    template <typename CT, typename T>\n    inline CT calc(T const& lon1,\n                T const& lat1,\n                T const& lon2,\n                T const& lat2) const\n    {\n        CT const G = (lat1 - lat2) / 2.0;\n        CT const lambda = (lon1 - lon2) / 2.0;\n\n        if (geometry::math::equals(lambda, 0.0)\n            && geometry::math::equals(G, 0.0))\n        {\n            return 0.0;\n        }\n\n        CT const F = (lat1 + lat2) / 2.0;\n\n        CT const sinG2 = math::sqr(sin(G));\n        CT const cosG2 = math::sqr(cos(G));\n        CT const sinF2 = math::sqr(sin(F));\n        CT const cosF2 = math::sqr(cos(F));\n        CT const sinL2 = math::sqr(sin(lambda));\n        CT const cosL2 = math::sqr(cos(lambda));\n\n        CT const S = sinG2 * cosL2 + cosF2 * sinL2;\n        CT const C = cosG2 * cosL2 + sinF2 * sinL2;\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n        CT const c3 = 3;\n\n        if (geometry::math::equals(S, c0) || geometry::math::equals(C, c0))\n        {\n            return c0;\n        }\n\n        CT const radius_a = CT(get_radius<0>(m_spheroid));\n        CT const flattening = geometry::detail::flattening<CT>(m_spheroid);\n\n        CT const omega = atan(math::sqrt(S / C));\n        CT const r3 = c3 * math::sqrt(S * C) / omega; // not sure if this is r or greek nu\n        CT const D = c2 * omega * radius_a;\n        CT const H1 = (r3 - c1) / (c2 * C);\n        CT const H2 = (r3 + c1) / (c2 * S);\n\n        return D * (c1 + flattening * (H1 * sinF2 * cosG2 - H2 * cosF2 * sinG2) );\n    }\n\n    Spheroid m_spheroid;\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct tag<andoyer<Spheroid, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct return_type<andoyer<Spheroid, CalculationType>, P1, P2>\n    : andoyer<Spheroid, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct comparable_type<andoyer<Spheroid, CalculationType> >\n{\n    typedef andoyer<Spheroid, CalculationType> type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct get_comparable<andoyer<Spheroid, CalculationType> >\n{\n    static inline andoyer<Spheroid, CalculationType> apply(andoyer<Spheroid, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<andoyer<Spheroid, CalculationType>, P1, P2>\n{\n    template <typename T>\n    static inline typename return_type<andoyer<Spheroid, CalculationType>, P1, P2>::type\n        apply(andoyer<Spheroid, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, point_tag, Point1, Point2, geographic_tag, geographic_tag>\n{\n    typedef strategy::distance::andoyer\n                <\n                    srs::spheroid\n                        <\n                            typename select_coordinate_type<Point1, Point2>::type\n                        >\n                > 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_GEOGRAPHIC_ANDOYER_HPP\n", "meta": {"hexsha": "64de8c1a414a7a8ef419c237cdc9c8d07fc99160", "size": 6591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/geometry/strategies/geographic/distance_andoyer.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/geometry/strategies/geographic/distance_andoyer.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": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T02:48:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:41:52.000Z", "max_forks_repo_path": "deps/cinder/include/boost/geometry/strategies/geographic/distance_andoyer.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": 29.2933333333, "max_line_length": 107, "alphanum_fraction": 0.6609012289, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.5556353036738177}}
{"text": "/* -*-C++-*- */\n/*\n   (c) Copyright 1996-2005, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    \\brief mathematical functions not found in the standard math library.\n*/\n\n#ifndef LINTEL_MATHSPECIALFUNCTIONS_HPP\n#define LINTEL_MATHSPECIALFUNCTIONS_HPP\n\n#include <math.h>\n\n#include <boost/version.hpp>\n#include <boost/config.hpp>\n/* TODO: when we decide to stop supporting older boost versions, this \n   should be removed. Also, note the equivalent checks later in the file\n   and in the .cpp\n*/\n#if BOOST_VERSION >= 103500\n#include <boost/math/special_functions/erf.hpp>\n#else\n   // no erf() on windows\n#  if defined(BOOST_MSVC)\n#     error need boost version >= 1.35\n#  endif\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n// Functions\n//////////////////////////////////////////////////////////////////////////////\n\n// The inverse of the Erf function, defined over the domain -1 < y < 1.\n// TODO: should probably be deprecated in favor of boost::math::erfc() ?\ndouble inverseErf(double y);\n\n// The cumulative distribution function of the unit Normal RV U;\n// unitNormalCDF(x) = Prob[U < x] = (1+erf(x/sqrt(2)))/2\ninline double unitNormalCDF(double x)\n{\n#if BOOST_VERSION >= 103500\n    return 0.5*(1.0+ boost::math::erf<double>(0.70710678118654752440084436210485*x));\n#else\n    return 0.5*(1.0+ erf(0.70710678118654752440084436210485*x));    \n#endif\n}\n\n// The probability that the absolute value of a measurement of a\n// unit normal-distributed quantity is above X.  This is the same\n// as the two-side folded cumulative distribution function of the\n// unit normal RV U:\ninline double probAbsNormal(double x)\n{\n#if BOOST_VERSION >= 103500\n    return 1. - boost::math::erf<double>(0.70710678118654752440084436210485*fabs(x));\n#else\n    return 1. - erf(0.70710678118654752440084436210485*fabs(x));\n#endif\n}\n\n// The probability density function of the unit Normal RV U;\n// unitNormalPDF(x) = unitNormalCDF'(x) = exp(-x*x/2)/sqrt(2 Pi)\ninline double unitNormalPDF(double x) \n  {return 0.39894228040143267793994605993438 * exp(-0.5*x*x) ;};\n\n// The inverse of the cumulative distribution function of the unit Normal \n// RV U, also known as inversePhi.\n// inverseUnitNormalCDF(x) == y  <=>  x == unitNormalCDF(y)\n// inverseUnitNormalCDF(x) = sqrt(2) * inverseErf(2*x -1)\ninline double inverseUnitNormalCDF(double x) \n  {return 1.4142135623730950488016887242097*(inverseErf(2.0*x - 1.0));};\n\n\n//////////////////////////////////////////////////////////////////////////////\n// Data type conversion utilities\n//////////////////////////////////////////////////////////////////////////////\n\n// Verify that the double argument can be converted (without rounding error)\n// to an integer data type.  You get to specify the size of the integer\n// data type; only the size of a long or a long long is supported.\n// \"Without rounding error\" means that the double is really close to \n// being an actual integer.  \nextern bool isDoubleIntegral(double d, size_t target_size);\n\n// Convert the double to an integer, of type long or long long\nextern long convertDoubleLong(double d);\nextern long long convertDoubleLongLong(double d);\n\n#endif\n", "meta": {"hexsha": "83ea424072e053c761f4e73efb3c87357b24bd8c", "size": 3216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Lintel/MathSpecialFunctions.hpp", "max_stars_repo_name": "sbu-fsl/Lintel", "max_stars_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Lintel/MathSpecialFunctions.hpp", "max_issues_repo_name": "sbu-fsl/Lintel", "max_issues_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T21:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T21:56:51.000Z", "max_forks_repo_path": "include/Lintel/MathSpecialFunctions.hpp", "max_forks_repo_name": "sbu-fsl/Lintel", "max_forks_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_forks_repo_licenses": ["BSD-3-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.5806451613, "max_line_length": 85, "alphanum_fraction": 0.6588930348, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5556063145984628}}
{"text": "/*\n * common.hpp\n *\n *  Created on: Apr 19, 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\nnamespace tsdf{\n\nconstexpr float near_clipping_distance = 0.05; //m\n\ntemplate<typename Scalar>\ninline Scalar compute_TSDF_value(Scalar signed_distance, Scalar narrow_band_half_width){\n\tif (signed_distance < -narrow_band_half_width) {\n\t\treturn (Scalar)-1.0;\n\t} else if (signed_distance > narrow_band_half_width) {\n\t\treturn (Scalar)1.0;\n\t} else {\n\t\treturn signed_distance / narrow_band_half_width;\n\t}\n}\n\ntemplate<typename Scalar>\ninline bool is_voxel_out_of_bounds(const Eigen::Matrix<Scalar,2,1>& voxel_image,\n\t\tconst Eigen::Matrix<unsigned short, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& depth_image,\n\t\tint margin = 3){\n\tif (voxel_image(0) < -margin || voxel_image(0) >= depth_image.cols() + margin ||\n\t\t\tvoxel_image(1) < -margin || voxel_image(1) >= depth_image.rows() + margin){\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n}  // namespace tsdf\n\n\n\n", "meta": {"hexsha": "1b7fec8d29339ecc310eb4fee46de378974f926a", "size": 1595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tsdf/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/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/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": 28.4821428571, "max_line_length": 100, "alphanum_fraction": 0.721630094, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.5555360565675735}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/math/tools/luroth_expansion.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#ifndef BOOST_MATH_STANDALONE\n#include <boost/multiprecision/mpfr.hpp>\nusing boost::multiprecision::mpfr_float;\n#endif // BOOST_MATH_STANDALONE\n\nusing boost::math::constants::pi;\nusing boost::math::tools::luroth_expansion;\n\nint main() {\n    #ifndef BOOST_MATH_STANDALONE\n    using Real = mpfr_float;\n    mpfr_float::default_precision(1024);\n    #else\n    using Real = long double;\n    #endif\n    \n    auto luroth = luroth_expansion(pi<Real>());\n    std::cout << luroth << \"\\n\";\n}\n", "meta": {"hexsha": "7bb33e55453f7e1cec58afd631a9272155b98cac", "size": 826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/luroth.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/luroth.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "example/luroth.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 28.4827586207, "max_line_length": 68, "alphanum_fraction": 0.7263922518, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5555002537436953}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <functional>\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"eqeq.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(EQeq)\n\n\nEigen::VectorXd EQeq::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> EQeq::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\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "5f058e229eeb956925e04e2aecf4a104d9ad5d91", "size": 2323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/eqeq.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/eqeq.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/eqeq.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": 31.3918918919, "max_line_length": 104, "alphanum_fraction": 0.5622040465, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.5554762856071994}}
{"text": "//main.cpp\n\n#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <Eigen/Core>\n\nmatrixXd weightInitialisation(double maxWeight, int width, int height){\n\n  matrixXd weights(width, height);\n\n  for (unsigned i=1; i <= width; ++i){\n    for (unsigned j=1; j <= height; ++j){\n      double f = (double)rand() / RAND_MAX;\n      weights(i, j) = f * (2 * maxWeight) - maxWeight;\n    }\n  }\n\n  return weights;\n}\n\nvoid feedForward(MatrixXd inputMatrix, MatrixXd weightMatrix,\n                VectorXd biasMatrix, MatrixXd &outputMatrix,\n                MatrixXd &netMatrix){\n\n  MatrixXd concatenatedInput(inputMatrix.rows(), inputMatrix.cols() + 1);\n  concatenatedInput << inputMatrix, biasMatrix;\n\n  //net = mul(weights, horcat(inputs, bias))\n  //output = activate(net)\n\n  netMatrix = weightMatrix * concatenatedInput;\n  outputMatrix = activate(netMatrix);\n\n\n\n}\n\nvoid networkError(MatrixXd inputMatrix, MatrixXd weightMatrix,\n                VectorXd biasMatrix, MatrixXd targetOutputMatrix,\n                VectorXi targetClassVector, double error, double classError){\n\n  feedForward(inputMatrix weightMatrix, biasMatrix,\n    MatrixXd outputMatrix, Matrix netMatrix);\n\n  error = sum((targetOutputMatrix - outputMatrix)^2.0)\n    / (sample_count * output_count);\n\n  outputToClass(int n, outputMatrix, &classVector);\n\n  c = sum_all_components(classVector != targetClassVector)/sample_count;\n\n}\n\nmatrixXd backPropogration(MatrixXd inputMatrix, MatrixXd weightMatrix,\n  double eta, VectorXd biasMatrix){\n\n  //currently dummy function\n  return weightMatrix;\n\n}\n\nvoid trainingFunction(){\n  \n}\n\ndouble activationFunction(double x){\n  return (tanh(x) + 1.0)/2.0;\n}\n\ndouble activationFunctionDerivative(double x){\n  return (1.0 - (tanh(x)^2.0))/2.0;\n}\n\nvoid checkColumns(MatrixXi &Matrix, VectorXi &Vector){\n  if (Matrix.cols() /= Vector.rows()){\n      std::cout << \"Mismatch between output matrix columns and class vector rows\" << std::endl;\n      exit (EXIT_FAILURE);\n  }\n}\n\nvoid outputToClass(int n, MatrixXi outputMatrix, VectorXi &classVector){\n\n  checkColumns(outputMatrix, classVector);\n\n  for (unsigned i=1; i <= n; ++i){\n    for (unsigned j=1; j <= 3; ++j){\n      if (outputMatrix(i, j) == 1){\n        classVector(i) = j;\n      }\n    }\n  }\n}\n\nvoid outputToMatrix(int n, MatrixXi &outputMatrix, VectorXi classVector){\n\n  checkColumns(outputMatrix, classVector);\n\n  for (unsigned i=1; i <= n; ++i){\n    for (unsigned j=1; j <= 3; ++j){\n      if (classVector(i) == j){\n        outputMatrix(i, j) = 1;\n      }\n      else {\n        outputMatrix(i, j) = 0;\n      }\n    }\n  }\n}\n\n\nint main (){\n\n\n  return 0;\n}\n", "meta": {"hexsha": "226411e011837cdf826db5e8cc6153bbeb3d1a60", "size": 2601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "jchildren/custom-ghosthack", "max_stars_repo_head_hexsha": "2300307114a22c82373f320d2367fb5ed14339a0", "max_stars_repo_licenses": ["MIT"], "max_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": "jchildren/custom-ghosthack", "max_issues_repo_head_hexsha": "2300307114a22c82373f320d2367fb5ed14339a0", "max_issues_repo_licenses": ["MIT"], "max_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": "jchildren/custom-ghosthack", "max_forks_repo_head_hexsha": "2300307114a22c82373f320d2367fb5ed14339a0", "max_forks_repo_licenses": ["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.2307692308, "max_line_length": 95, "alphanum_fraction": 0.660130719, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5554541920641881}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"Stack.h\"\n#include <ctime>\n\nusing namespace Eigen;\nusing namespace std;\n/*int main() {\n    MatrixXd m = MatrixXd::Random(3,3);\n    m = (m + MatrixXd::Constant(3,3,1.2)) * 50;\n    cout << \"m =\" << endl << m << endl;\n    VectorXd v(3);\n    v << 1, 2, 3;\n    cout << \"m * v =\" << endl << m * v << endl;\n    std::cout << \"Hello, World!\" << std::endl;\n    return 0;\n}*/\n/*\n int main(){\n     for (int ix = 0; ix<10;++ix) {\n         cout << ix << '\\n';\n     }\n     cout<<\"change\"<<'\\n';\n     for (int iy = 0; iy<10;iy++) {\n         cout << iy << '\\n';\n     }\n     return 0;\n }*/\n\n/*testing the Eigen template\nint main (){\n    Matrix<double, 3,3> A;\n    A<<1,2,3,\n       4,5,6,\n       7,8,9;\n    cout << A << '\\n'<< endl;\n    A<<A,A;\n    cout<< A <<endl;\nreturn 0;\n};\n*/\nMatrixXd myproduct (MatrixXd b,MatrixXd c,int m1,int m2) {\n    MatrixXd a(c.rows(),c.cols());\n    int temp_index1 = 0;\n    int temp_index2 = 0;\n    for (int index1_1 = 1; index1_1 <= m1; ++index1_1) {\n        for (int index1_2 = 1; index1_2 <= b.rows(); ++index1_2) {\n            for (int index1_3 = 1; index1_3 <= m2; ++index1_3) {\n                for (int index1_4 = 1; index1_4 <= b.rows(); ++index1_4) {\n                    temp_index1 = (index1_1 - 1) * b.rows() * m2 + (index1_2 - 1) * m2 + index1_3 - 1;\n                    temp_index2 = (index1_1 - 1) * b.rows() * m2 + (index1_4 - 1) * m2 + index1_3 - 1;\n                    //cout<<temp_index1<<endl;\n                    //cout<<temp_index2<<endl;\n                    a(temp_index1, 0) = a(temp_index1, 0) + b(index1_2 - 1, index1_4 - 1) * c(temp_index2, 0);\n                    //cout<<index1_4-1;\n                }\n            }\n        }\n    }\n    return a;\n}\nint main(){\n    //MatrixXd A(27,1);\n    MatrixXd B = MatrixXd::Random(10,10);\n    MatrixXd C = MatrixXd::Random(400,1);\n    //MatrixXd D(9,1);\n    int _size_m1 = 4;\n    int _size_m2 = 10;\n    /*cout<<C(1,0);\n    int temp = 1;\n    C(1,0)=temp;\n    cout<<temp;\n    cout<<C(temp,0);*/\n    MatrixXd E;\n    clock_t t1 = clock();\n    for (int i = 0; i<=100000;++i){\n        E = myproduct(B,C,_size_m1,_size_m2);\n    }\n    clock_t t2 = clock();\n    //cout<<E<<endl;\n    cout<<(double)(t2-t1)/CLOCKS_PER_SEC<<endl;\n    return 0;\n}", "meta": {"hexsha": "32b3936fd231cc189652e22463c80b968d37fed3", "size": 2260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "alexhuangweijie/hello", "max_stars_repo_head_hexsha": "23c0732aa377cb9416fa9654bd68b4b8964ce0ae", "max_stars_repo_licenses": ["MIT"], "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": "alexhuangweijie/hello", "max_issues_repo_head_hexsha": "23c0732aa377cb9416fa9654bd68b4b8964ce0ae", "max_issues_repo_licenses": ["MIT"], "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": "alexhuangweijie/hello", "max_forks_repo_head_hexsha": "23c0732aa377cb9416fa9654bd68b4b8964ce0ae", "max_forks_repo_licenses": ["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.2289156627, "max_line_length": 110, "alphanum_fraction": 0.4853982301, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.555454189208773}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson_ex::poisson_devroye::q_function::standard.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_Q_FUNCTION_STANDARD_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_Q_FUNCTION_STANDARD_HPP_ER_2010\n#include <cmath>\n#include <stdexcept>\n#include <string>\n#include <boost/format.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/random/poisson_ext/devroye/detail/math.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace detail{\n\n\t// The q-function is needed in either version of step4 of the algorithm.\n\t// See equation (4), p.199.\n    //\n    // TODO make static\n    template<typename Int,typename T,typename P>\n    struct q\n    {\n\n\t\ttypedef devroye::detail::math<Int,T,P> ma_;\n        \n        // TODO perhaps make this a template or runtime choice\n        // For now overwrite manually. Checking may impedede speed a bit.\n        typedef boost::mpl::bool_<true> do_check_; \n        \n        typedef std::string str_;\n        typedef boost::format f_;\n\t\tstatic const str_ name(){ return \"devroye::detail::q\"; }\n\n\t\tpublic:\n        \n        q(){}\n    \n        typedef T float_;\n\t\ttypedef Int int_;\n\n        float_ q_fun(const int_& mean,const int_& y)const{\n        \tBOOST_ASSERT(y>=(-mean));\n        \tfloat_ result;\n        \n\t\t\tif(y<0){ \n            \tresult = this->impl1(mean,y); \n            }else{\n            \tif(y==0){\n\t\t\t\t\tresult = this->impl2(mean,y);                \n                }else{\n                \tif(y>0){\n                \t\tresult = this->impl3(mean,y);\n                    }else{\n                    \tthrow std::runtime_error(name() + \"q\");\n                    }\n                }\n            }\n            if(do_check_::value){\n\t\t\t\tthis->check_against_slow_version(mean,y,result); \n\t\t\t\tthis->check_lemma1(mean,y,result); \n\t\t\t\tthis->check_lemma2(mean,y,result); \n            }\n            \n            return result;\n\t\t}\n\n    private:\n\n        float_ slow_version(const int_& mean,const int_& y)const\n        {\n            return y * ma_::log(y) \n                - ma_::log ( ma_::factorial(mean+y,P())/ma_::factorial(mean,P()) );\n        }\n\n        void check_against_slow_version(\n            const int_& mean,\n            const int_& y,\n            const float_& result\n        )const\n        {\n            static const str_ str = name() \n                + \"::check_bound_against_slow_version, q(%1%) = %2% != %3%\";\n            float_ alt = this->slow_version(mean,y);\n            std::cout << \"alt=\" << alt << ' ';\n            std::cout << \"res=\" << result << std::endl;\n            if((result> alt + ma_::eps()) || (alt> result + ma_::eps()) )\n            {\n                throw std::runtime_error(\n                    ( boost::format(str) % y % result % alt ).str()\n                );\n            }\n        \n        }\n\n\t\t// Lemma 1, p.199\n\t\t// q(y) < upper_bound(y) if y >= -mean\n\t\tfloat_ upper_bound(const int_& mean,const int_& y)const{\n        \tfloat_ num = ( - ma_::to_float(y) * ma_::to_float(1+y) );\n            float_ den = ma_::to_float(2 * mean);\n            den += ma_::to_float((y<0)?0:y);\n            return num / den;\n        }\n\n\t\tvoid check_lemma1(\n        \tconst int_& mean,\n            const int_& y,\n            const float_& result\n        )const{\n            if( y >= mean ){\n            \tfloat_ b = this->upper_bound(mean,y);\n                if( result>b ){\n                \tstatic const str_ str \n                    \t= name() + \"::check_bound, %1% = q(%2%) > %3%\";\n                    throw std::runtime_error(\n\t\t\t\t\t\t( boost::format(str) % result % y % b ).str()\n                    );\n                }\n            }\n        }\n\n\t\t// Lemma 2, p. 199\n\t\tvoid check_lemma2(\n            const int_& mean,\n            const int_& y,\n            const float_& q_val\n        )const{\n            static const str_ str1 \n            \t= \"q::check_lemma2(%1%,%2%,%3%) : failed condition(s) :\";\n\n        \tint_ yp1 = y + 1;\n        \tint_ yp1pm1 = yp1 + mean;\n            int_ y2p1 = 2 * y + 1;\n            int_ ysq = y * y;\n            int_ yp1sq = yp1 * yp1;\n            int_ m2 = 2 * mean;\n            int_ msq = mean * mean;\n            int_ mcu = msq * mean;\n            \n            float_ lhs \n            \t= q_val + ma_::to_float( y * yp1 ) / ma_::to_float( m2 );\n\n\t\t\tstr_ str2;\n            bool fail = false;\n            if(y>=0)\n            {\n                if(!(lhs >= 0)){\n                \tstr2 += (f_(\"1: lhs = %1% >= 0\")%lhs).str();\n                    fail = true;\n                }\n            }else{\n                if(!(lhs <= 0)){\n                \tstr2 += (f_(\"1: lhs = %1% <= 0\")%lhs).str();\n                    fail = true;\n                }\n\t\t\t}                \n\n            float_ rhs \n            \t=  ma_::to_float( y * yp1 * y2p1 ) / ma_::to_float(12 * msq);\n            if(!(lhs <= rhs)){\n\t\t\t\tf_ f2(\" 2: lhs = %1% <= rhs = %2%\");\n                str2 += (f2%lhs%rhs).str();\n                fail = true;\n            }\n\n            float_ num = ma_::to_float( ysq * yp1sq );\n            if(y>=0){\n                rhs -= ( num / ma_::to_float(12 * mcu) );\n            }else{\n\t\t\t\trhs -= ( num / ma_::to_float(12 * msq * yp1pm1) );            \t    \n            }\n            if(!(lhs >= rhs)){\n                f_ f3(\" 3: lhs = %1% >= rhs = %2%\");\n                str2 += (f_(f3)%lhs%rhs).str();\n                fail = true;\n            }\n\t\t\tif(fail){\n            \tstr2 = (f_(str1)%mean%y%q_val).str() + str2;\n                throw std::runtime_error(str2);\n\t\t\t}\n        }\n\n\t\t// TODO consider using \n        // #include <boost/math/tools/series.hpp>\n\n\t\tfloat_ impl1(const int_& mean,const int_& y)const{\n        \tBOOST_ASSERT(y<0);\n            float_ im1 = ma_::to_float(1) / ma_::to_float(mean);\n        \tfloat_ result = ma_::to_float(0);\n            int_ n = -(y+1) + 1;\n\t\t\tfor(int_ i = 0; i < n; i++){\n            \tresult += ma_::log1p(-ma_::to_float(i)*im1,P());\n            }\n            return result;\n        }\n    \n\t\tfloat_ impl2(const int_& mean,const int_& y)const{\n        \tBOOST_ASSERT(y==0);\n        \treturn ma_::to_float(0);\n\t\t}\n\t\tfloat_ impl3(const int_& mean,const int_& y)const{\n        \tBOOST_ASSERT(y>0);\n            float_ im1 = ma_::to_float(1) / ma_::to_float(mean);\n        \tfloat_ result = ma_::to_float(0);\n            int n = y+1;\n\t\t\tfor(int_ i = 1; i < n; i++){\n            \tresult -= ma_::log1p(ma_::to_float(i)*im1,P());\n            }\n            return result;\n        }\n\n\t};\n\n}// q_function\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "ca4d4f51743e6e0930346d80194500d895426651", "size": 7134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/detail/q.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/detail/q.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/detail/q.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.1528384279, "max_line_length": 83, "alphanum_fraction": 0.442248388, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.5553713220052011}}
{"text": "#include <iostream>\n#include <sstream>\n#include <vector>\n#include <algorithm>\n#include <boost/math/special_functions/beta.hpp> \n#include<boost/math/distributions.hpp>\n#include <cmath>\n#include \"helpers.hpp\"\n\nusing namespace std;\nusing namespace boost::math;\n\nvoid computeIndices(const int n, const double beta, vector<vector<double> >& indices)\n{\n  #pragma omp parallel for\n  for(int nn = n-1; nn >= 2; --nn)\n  {\n    for(int a = 1; a <= nn-1; ++a)\n    {\n      double p = computeAGI(beta, a, nn);\n      indices[a-1][nn-a-1] = p;\n    }\n  }\n}\n\nvoid computeGittinsIndices(const int n, const double step, const double beta, vector<vector<double> >& indices)\n{\n  vector<vector<double> > tmpindices(n-1, vector<double>(n-1, 0));\n  for(int a = 1; a < n; ++a)\n  {\n    tmpindices[a-1][n-a-1] = ((double)a/(double)n);\n  }\n  for(double p=(step/2.0); p <= 1.0; p+=step)\n  {\n    const double safe = p/(1-beta);\n    for(int nn = n-1; nn >= 2; --nn)\n    {\n      for(int a = 1; a <= nn-1; ++a)\n      {\n        const double r = ((double)a/(double)nn);\n        const double risky =  r*(1 + beta*tmpindices[a][nn-a-1]) + (1-r)*beta*tmpindices[a-1][nn-a];\n        if(indices[a-1][nn-a-1] == 0 && safe > risky)\n        {\n          indices[a-1][nn-a-1] = p - step/2.0;\n        }\n        tmpindices[a-1][nn-a-1] = max(safe,risky);\n      }\n    }\n  }\n  /*for(int nn = n-1; nn >= 2; --nn)\n  {\n    for(int a = 1; a <= nn-1; ++a)\n    {\n      if(a > ceil(nn/2.0))\n      {\n        indices[a-1][nn-a-1] = 1 - step/2.0;\n      }\n    }\n  }*/\n}\n\nvoid experiment(int n, double beta, double step)\n{\n  vector<vector<double> > gindices(n-1, vector<double>(n-1, 0));\n  const static int maxnum = 500;\n  /*cout << \"computing gittins indices....\" << endl;\n  computeGittinsIndices(n,step,beta,gindices);*/\n  cout << \"loading gittins indices...\" << endl;\n  loadFromCSV(\"gixs_95.csv\", gindices, maxnum, maxnum);\n  \n  cout << \"checking values...\" << endl;\n  for(int a = 0; a < maxnum; ++a)\n  {\n    for(int b = 0; b < maxnum; ++b)\n    {\n      const double agi1 = computeAGI(beta, a + 1, a + b + 2);\n      const double agi2 = computeAGI2(beta, a + 1, b + 1);\n      const double agi2a = computeGeneralAGI(beta, a + 1, b + 1, 2);\n      const double agi3 = computeGeneralAGI(beta, a + 1, b + 1, 3);\n      const double agi4 = computeGeneralAGI(beta, a + 1, b + 1, 4);\n      double eps = 1e-6;\n      if (abs(agi2a - agi2) > eps)\n      {\n        cerr << \"difference found in agi1 comp for a: \" << a << \". b: \" << b << \". agi2: \" << agi2 << \". agi2a: \" << agi2a << endl;\n      }\n      if (!(agi1 > agi2 - eps && agi2 > agi3 - eps && agi3 > agi4 - eps))\n      {\n        cerr << \"unexpected order of indices. a = \" << a << \". b = \" << b << \". agi1: \" << agi1 << \". agi2: \" << agi2 << \". agi3:\" << agi3 << \". agi4:\" << agi4 << endl;\n        //exit(1);\n        //\n      }\n\n      if (agi1 < gindices[a][b] -eps)\n      {\n        cerr << \"unexpected. a = \" << a << \". b = \" << b << \". agi1: \" << agi1 << \". gidx: \" << gindices[a][b] << endl;\n      }\n      if (agi2 < gindices[a][b] -eps)\n      {\n        cerr << \"unexpected. a = \" << a << \". b = \" << b << \". agi2: \" << agi2 << \". gidx: \" << gindices[a][b] << endl;\n      }\n      if (agi3 < gindices[a][b] -eps)\n      {\n        cerr << \"unexpected. a = \" << a << \". b = \" << b << \". agi3: \" << agi3 << \". gidx: \" << gindices[a][b] << endl;\n      }\n      if (agi4 < gindices[a][b] -eps)\n      {\n        cerr << \"unexpected. a = \" << a << \". b = \" << b << \". agi4: \" << agi4 << \". gidx: \" << gindices[a][b] << endl;\n      }\n    }\n  }\n\n  cout << \"done...\" << endl;\n}\n\nvoid calculator()\n{\n  while(1)\n  {\n    double gamma, a, b;\n    cin >> gamma;\n    cin >> a;\n    cin >> b;\n    cout << std::setprecision(20) << computeAGI(gamma,a,a+b) << endl; \n    cout << std::setprecision(20) << computeAGI2(gamma,a,b) << endl; \n    cout << std::setprecision(20) << computeGeneralAGI(gamma,a,b,3) << endl; \n  }\n}\n\n\nint main(int argc, const char** args)\n{\n  //this is bad lol\n  //calculator();\n  //cout << ::computeAGI2(0.99,3,3);\n  if(argc != 3)\n  {\n    cerr << \"need 2 arguments [n] [beta]\" << endl;\n    exit(1);\n  }\n  int n;\n  string strnum = args[1];\n  stringstream ss(strnum);\n  ss >> n;\n\n  double beta;\n  string betastr = args[2];\n  stringstream ssbeta(betastr);\n  ssbeta >> beta;\n\n  double step = 0.0001;\n  experiment(n, beta, step);\n\n  exit(0);\n  vector<vector<double> > indices(n-1, vector<double>(n-1, 0));\n  computeIndices(n, beta, indices);\n\n  for(int i = 0; i < n-1; ++i)\n  {\n    for(int j=0; j < n-2; ++j)\n    {\n      cout << indices[i][j] << \", \"; \n    }\n    cout << indices[i][n-2] << endl;\n  }\n}\n\n", "meta": {"hexsha": "8e3887ebe1afc827260614ee8e81648f4a525401", "size": 4581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/myopicidxs.cpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/myopicidxs.cpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/myopicidxs.cpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 27.4311377246, "max_line_length": 168, "alphanum_fraction": 0.5077493997, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5553296217500668}}
{"text": "#include <vector>\n#include <iostream>\n#include <string>\n#include <armadillo>\n#include <tgmath.h>\n#include <limits>\n#include <omp.h>\n\n#include \"global.h\"\n#include \"utils.h\"\n#include \"distr.h\"\n\n#include \"ESS_Sampler.h\"\n#include \"HESS_Chain.h\"\n#include \"SSUR_Chain.h\"\n#include \"dSUR_Chain.h\"\n\nextern omp_lock_t RNGlock; //defined in global.h\nextern std::vector<std::mt19937_64> rng;\n\nint drive_SSUR( arma::mat& Y , arma::mat& X , unsigned int& nChains , unsigned int& nIter , \n\t\t\t\tstd::string& inFile , std::string& outFilePath , std::string& gammaSampler , bool gPrior )\n{\n\n\t// ****************************************\n\t// **********  INIT THE CHAIN *************\n\t// ****************************************\n\tstd::cout << \"Initialising the MCMC Chain \" << std::endl;\n\n\tESS_Sampler<SSUR_Chain> sampler( Y , X , nChains );// this is thus also some sort of default\n\t\t// although note that you won't pass the input phase with a different method string\n\n\t// *****************************\n\t// need to use getX because I need the intercept\n\tarma::mat Q,R; arma::qr(Q,R, *sampler[0]->getX() );\n\tarma::mat betaInit = arma::solve(R,arma::trans(Q) * Y );\n\tarma::umat gammaInit = betaInit > 0.5*arma::stddev(arma::vectorise(betaInit));\n\tgammaInit.shed_row(0);\n\n\tsampler[0] -> gammaInit( gammaInit );\n    sampler[0] -> updateQuantities();\n    sampler[0] -> logLikelihood();\n\tsampler[0] -> stepSigmaRhoAndBeta();\n\n\t// *****************************\n\n\t// set when the JT move should start\n\tunsigned int jtStartIteration = nIter/10;\n\tfor( unsigned int i=0; i<nChains; ++i)\n\t\tsampler[i]->setJTStartIteration( jtStartIteration );\n\n\t// *****************************\n\n\tif( gPrior )\n\t\tfor(unsigned int m=0; m<nChains; ++m)\n\t\t\tsampler[m] -> gPriorInit();\n\n\tfor(unsigned int m=0; m<nChains; ++m)\n\t\tsampler[m] -> setGammaSamplerType(gammaSampler);\n\t\n\n\t// ****************************************\n\n\t// INIT THE FILE OUTPUT\n\n\t// clear the content of previous files\n\tstd::ofstream logPOutFile; logPOutFile.open(outFilePath+inFile+\"logP_out.txt\", std::ios::out | std::ios::trunc); logPOutFile.close();\n\t// openlogP file in append mode\n\tlogPOutFile.open( outFilePath+inFile+\"logP_out.txt\" , std::ios_base::app); // note we don't close!\n\t// open avg files in trunc mode to cut previous content\n\tstd::ofstream gammaOutFile; gammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc); gammaOutFile.close();\n\tstd::ofstream gOutFile; gOutFile.open( outFilePath+inFile+\"G_out.txt\" , std::ios_base::trunc); gOutFile.close();\n\tstd::ofstream piOutFile; piOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc); piOutFile.close();\n\tstd::ofstream htpOutFile; htpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc); htpOutFile.close();\n\n\t// Output to file the current state\n\tarma::umat gamma_out = sampler[0] -> getGamma(); // out var for the gammas\n\t\n\tarma::umat g_out = arma::umat( sampler[0] -> getGAdjMat() ); // out var for G\n\tarma::mat beta_out = sampler[0] -> getBeta(); // out var for the betas\n\tarma::mat sigmaRho_out  = sampler[0] -> getSigmaRho(); // out var for the sigmas and rhos\n\n\tarma::vec tmpVec = sampler[0] -> getPi();\n\tarma::vec pi_out = tmpVec;\n\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\tarma::vec hotspot_tail_prob_out = tmpVec;\n\n\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out)) << std::flush;\n\tgammaOutFile.close();\n\n\tgOutFile.open( outFilePath+inFile+\"G_out.txt\" , std::ios_base::trunc);\n\tgOutFile << ( arma::conv_to<arma::mat>::from(g_out) ) << std::flush;   // this might be quite long...\n\tgOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPEta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPJT() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out << std::flush;\n\thtpOutFile.close();\n\t\t\t\t\t\n\n\t// ########\n\t// ########\n\t// ######## Start\n\t// ########\n\t// ########\n\n\tstd::cout << \"Starting \"<< nChains <<\" (parallel) chain(s) for \" << nIter << \" iterations:\" << std::endl << std::flush;\n\n\tunsigned int tick = 1000; // how may iter for each print?\n\n\tfor(unsigned int i=1; i < nIter ; ++i)\n\t{\n\n\t\tsampler.step();\n\t\t\n\t\t// #################### END LOCAL MOVES\n\n\t\t// ## Global moves\n\t\t// *** end Global move's section\n\n\t\t// UPDATE OUTPUT STATE\n\t\tgamma_out += sampler[0] -> getGamma(); // the result of the whole procedure is now my new mcmc point, so add that up\n\t\tg_out += arma::umat( sampler[0] -> getGAdjMat() );\n\n\t\tbeta_out += sampler[0] -> getBeta();\n\t\tsigmaRho_out += sampler[0] -> getSigmaRho();\t\n\n\t\ttmpVec = sampler[0] -> getPi();\n\t\tpi_out += tmpVec;\n\t\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\t\thotspot_tail_prob_out += tmpVec;\n\n\t\t// Print something on how the chain is going\n\t\tif( (i+1) % tick == 0 )\n\t\t{\n\n\t\t\tstd::cout << \" Running iteration \" << i+1 << \" ... local Acc Rate: ~ gamma: \" << Utils::round( sampler[0] -> getGammaAccRate() , 3 );\n\t\t\tstd::cout << \" -- JT: \" << Utils::round( sampler[0] -> getJTAccRate() , 3 ) ;\n\n\t\t\tif( nChains > 1)\n\t\t\t\tstd::cout << \" -- Global: \" << Utils::round( sampler.getGlobalAccRate() , 3 ) << std::endl; \n\t\t\telse\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\n\t\t\t// Output to files every now and then\n\t\t\tif( (i+1) % (tick*10) == 0 )\n\t\t\t{\n\n\t\t\t\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\t\t\t\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)i+1.0) << std::flush;\n\t\t\t\tgammaOutFile.close();\n\n\t\t\t\tgOutFile.open( outFilePath+inFile+\"G_out.txt\" , std::ios_base::trunc);\n\t\t\t\tgOutFile << ( arma::conv_to<arma::mat>::from(g_out) )/((double)(i-jtStartIteration)+1.0) << std::flush;   // this might be quite long...\n\t\t\t\tgOutFile.close();\n\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPEta() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPJT() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\t\t\t\tlogPOutFile << \tstd::endl << std::flush;\n\n\t\t\t\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\t\t\t\tpiOutFile << pi_out/((double)i+1.0) << std::flush;\n\t\t\t\tpiOutFile.close();\n\n\t\t\t\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\t\t\t\thtpOutFile << hotspot_tail_prob_out/((double)i+1.0) << std::flush;\n\t\t\t\thtpOutFile.close();\n\t\t\t}\n\n\t\t}\n\n\t} // end MCMC\n\n\n\t// Print the end\n\tstd::cout << \" MCMC ends. \" /* << \" Final temperature ratio ~ \" << temperatureRatio  */<< \"  --- Saving results and exiting\" << std::endl;\n\n\t// ### Collect results and save them\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)nIter+1.0) << std::flush;\n\tgammaOutFile.close();\n\n\tgOutFile.open( outFilePath+inFile+\"G_out.txt\" , std::ios_base::trunc);\n\tgOutFile << ( arma::conv_to<arma::mat>::from(g_out) )/((double)(nIter-jtStartIteration)+1.0) << std::flush;   // this might be quite long...\n\tgOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPEta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPJT() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\tlogPOutFile.close();\n\n\t// ----\n\tbeta_out = beta_out/((double)nIter);\n\tbeta_out.save(outFilePath+inFile+\"beta_out.txt\",arma::raw_ascii);\n\n\tsigmaRho_out = sigmaRho_out/((double)nIter);\n\tsigmaRho_out.save(outFilePath+inFile+\"sigmaRho_out.txt\",arma::raw_ascii);\n\t// -----\n\n\t// -----\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out/((double)nIter) << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out/((double)nIter) << std::flush;\n\thtpOutFile.close();\n\t// -----\n\n\n\tstd::cout << \"Saved to :   \"+outFilePath+inFile+\"****_out.txt\" << std::endl;\n\tstd::cout << \"Final w : \" << sampler[0] -> getW() <<  std::endl;\n\tstd::cout << \"Final tau : \" << sampler[0] -> getTau() << \"    w/ proposal variance: \" << sampler[0] -> getVarTauProposal() << std::endl;\n\tstd::cout << \"Final eta : \" << sampler[0] -> getEta() <<  std::endl;\n\t// std::cout << \"Final o : \" << sampler[0] -> getO().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarOProposal() << std::endl;  \n\t// std::cout << \"Final pi : \" << sampler[0] -> getPi().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarPiProposal() << std::endl;\n\tstd::cout << \"  -- Average Omega : \" << arma::accu( sampler[0] -> getO() * sampler[0] -> getPi().t() )/((double)(sampler[0]->getP()*sampler[0]->getS())) <<  std::endl;\n\tif( nChains > 1 ) \n\t\tstd::cout << \"Final temperature ratio : \" << sampler[1]->getTemperature() <<  std::endl << std::endl ;\n\n\t// Exit\n\n\tstd::cout << \"DONE, exiting! \" << std::endl << std::endl ;\n\treturn 0;\n}\n\nint drive_dSUR( arma::mat& Y , arma::mat& X , unsigned int& nChains , unsigned int& nIter , \n\t\t\t\tstd::string& inFile , std::string& outFilePath , std::string& gammaSampler , bool gPrior )\n{\n\n\t// ****************************************\n\t// **********  INIT THE CHAIN *************\n\t// ****************************************\n\tstd::cout << \"Initialising the MCMC Chain \" << std::endl;\n\n\tESS_Sampler<dSUR_Chain> sampler( Y , X , nChains );// this is thus also some sort of default\n\t\t// although note that you won't pass the input phase with a different method string\n\n\n\t// *****************************\n\t// need to use getX because I need the intercept\n\tarma::mat Q,R; arma::qr(Q,R, *sampler[0]->getX() );\n\tarma::mat betaInit = arma::solve(R,arma::trans(Q) * Y );\n\tarma::umat gammaInit = betaInit > 0.5*arma::stddev(arma::vectorise(betaInit));\n\tgammaInit.shed_row(0);\n\n\tsampler[0] -> gammaInit( gammaInit );\n    sampler[0] -> updateQuantities();\n    sampler[0] -> logLikelihood();\n\tsampler[0] -> stepSigmaRhoAndBeta();\n\n\t// *****************************\n\n\tif( gPrior )\n\t\tfor(unsigned int m=0; m<nChains; ++m)\n\t\t\tsampler[m] -> gPriorInit();\n\n\tfor(unsigned int m=0; m<nChains; ++m)\n\t\tsampler[m] -> setGammaSamplerType(gammaSampler);\n\t\t\n\t// *****************************\n\n\n\t// INIT THE FILE OUTPUT\n\n\t// clear the content of previous files\n\tstd::ofstream logPOutFile; logPOutFile.open(outFilePath+inFile+\"logP_out.txt\", std::ios::out | std::ios::trunc); logPOutFile.close();\n\t// openlogP file in append mode\n\tlogPOutFile.open( outFilePath+inFile+\"logP_out.txt\" , std::ios_base::app); // note we don't close!\n\t// open avg files in trunc mode to cut previous content\n\tstd::ofstream gammaOutFile; gammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc); gammaOutFile.close();\n\tstd::ofstream gOutFile; gOutFile.open( outFilePath+inFile+\"G_out.txt\" , std::ios_base::trunc); gOutFile.close();\n\tstd::ofstream piOutFile; piOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc); piOutFile.close();\n\tstd::ofstream htpOutFile; htpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc); htpOutFile.close();\n\n\t// Output to file the current state\n\tarma::umat gamma_out = sampler[0] -> getGamma(); // out var for the gammas\n\t\n\tarma::mat beta_out = sampler[0] -> getBeta(); // out var for the betas\n\tarma::mat sigmaRho_out  = sampler[0] -> getSigmaRho(); // out var for the sigmas and rhos\n\n\tarma::vec tmpVec = sampler[0] -> getPi();\n\tarma::vec pi_out = tmpVec;\n\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\tarma::vec hotspot_tail_prob_out = tmpVec;\n\n\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out)) << std::flush;\n\tgammaOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out << std::flush;\n\thtpOutFile.close();\n\t\t\t\t\t\n\n\t// ########\n\t// ########\n\t// ######## Start\n\t// ########\n\t// ########\n\n\tstd::cout << \"Starting \"<< nChains <<\" (parallel) chain(s) for \" << nIter << \" iterations:\" << std::endl << std::flush;\n\n\tunsigned int tick = 1000; // how may iter for each print?\n\n\tfor(unsigned int i=1; i < nIter ; ++i)\n\t{\n\n\t\tsampler.step();\n\t\t\n\t\t// #################### END LOCAL MOVES\n\n\t\t// ## Global moves\n\t\t// *** end Global move's section\n\n\t\t// UPDATE OUTPUT STATE\n\t\tgamma_out += sampler[0] -> getGamma(); // the result of the whole procedure is now my new mcmc point, so add that up\n\n\t\tbeta_out += sampler[0] -> getBeta();\n\t\tsigmaRho_out += sampler[0] -> getSigmaRho();\t\n\n\t\ttmpVec = sampler[0] -> getPi();\n\t\tpi_out += tmpVec;\n\t\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\t\thotspot_tail_prob_out += tmpVec;\n\n\t\t// Print something on how the chain is going\n\t\tif( (i+1) % tick == 0 )\n\t\t{\n\n\t\t\tstd::cout << \" Running iteration \" << i+1 << \" ... local Acc Rate: ~ gamma: \" << Utils::round( sampler[0] -> getGammaAccRate() , 3 );\n\n\t\t\tif( nChains > 1)\n\t\t\t\tstd::cout << \" -- Global: \" << Utils::round( sampler.getGlobalAccRate() , 3 ) << std::endl; \n\t\t\telse\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\n\t\t\t// Output to files every now and then\n\t\t\tif( (i+1) % (tick*10) == 0 )\n\t\t\t{\n\n\t\t\t\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\t\t\t\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)i+1.0) << std::flush;\n\t\t\t\tgammaOutFile.close();\n\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\t\t\t\tlogPOutFile << \tstd::endl << std::flush;\n\n\t\t\t\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\t\t\t\tpiOutFile << pi_out/((double)i+1.0) << std::flush;\n\t\t\t\tpiOutFile.close();\n\n\t\t\t\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\t\t\t\thtpOutFile << hotspot_tail_prob_out/((double)i+1.0) << std::flush;\n\t\t\t\thtpOutFile.close();\n\t\t\t}\n\n\t\t}\n\n\t} // end MCMC\n\n\n\t// Print the end\n\tstd::cout << \" MCMC ends. \" /* << \" Final temperature ratio ~ \" << temperatureRatio  */<< \"  --- Saving results and exiting\" << std::endl;\n\n\t// ### Collect results and save them\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)nIter+1.0) << std::flush;\n\tgammaOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPTau() << \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPSigmaRho() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPBeta() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\tlogPOutFile.close();\n\n\t// ----\n\tbeta_out = beta_out/((double)nIter);\n\tbeta_out.save(outFilePath+inFile+\"beta_out.txt\",arma::raw_ascii);\n\n\tsigmaRho_out = sigmaRho_out/((double)nIter);\n\tsigmaRho_out.save(outFilePath+inFile+\"sigmaRho_out.txt\",arma::raw_ascii);\n\t// -----\n\n\t// -----\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out/((double)nIter) << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out/((double)nIter) << std::flush;\n\thtpOutFile.close();\n\t// -----\n\n\n\tstd::cout << \"Saved to :   \"+outFilePath+inFile+\"****_out.txt\" << std::endl;\n\tstd::cout << \"Final w : \" << sampler[0] -> getW() <<  std::endl;\n\tstd::cout << \"Final tau : \" << sampler[0] -> getTau() << \"    w/ proposal variance: \" << sampler[0] -> getVarTauProposal() << std::endl;\n\t// std::cout << \"Final o : \" << sampler[0] -> getO().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarOProposal() << std::endl;  \n\t// std::cout << \"Final pi : \" << sampler[0] -> getPi().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarPiProposal() << std::endl;\n\tstd::cout << \"  -- Average Omega : \" << arma::accu( sampler[0] -> getO() * sampler[0] -> getPi().t() )/((double)(sampler[0]->getP()*sampler[0]->getS())) <<  std::endl;\n\tif( nChains > 1 ) \n\t\tstd::cout << \"Final temperature ratio : \" << sampler[1]->getTemperature() <<  std::endl << std::endl ;\n\n\t// Exit\n\n\tstd::cout << \"DONE, exiting! \" << std::endl << std::endl ;\n\treturn 0;\n}\n\n\nint drive_HESS( arma::mat& Y , arma::mat& X , unsigned int& nChains , unsigned int& nIter , \n\t\t\t\tstd::string& inFile , std::string& outFilePath , std::string& gammaSampler , bool gPrior )\n{\n\n\t// ****************************************\n\t// **********  INIT THE CHAIN *************\n\t// ****************************************\n\tstd::cout << \"Initialising the MCMC Chain \" << std::endl;\n\n\tESS_Sampler<HESS_Chain> sampler( Y , X , nChains );// this is thus also some sort of default\n\t\t// although note that you won't pass the input phase with a differetn method string\n\n\n\t// *****************************\n\tarma::mat Q,R; arma::qr(Q,R, *sampler[0]->getX() );\n\tarma::mat betaInit = arma::solve(R,arma::trans(Q) * Y );\n\tarma::umat gammaInit = betaInit > 0.5*arma::stddev(arma::vectorise(betaInit));\n\tgammaInit.shed_row(0);\n\n\tsampler[0] -> gammaInit( gammaInit );\n    sampler[0] -> updateGammaMask();\n    sampler[0] -> logLikelihood();\n\n\t// *****************************\n\n\tif( gPrior )\n\t\tfor(unsigned int m=0; m<nChains; ++m)\n\t\t\tsampler[m] -> gPriorInit();\n\n\tfor(unsigned int m=0; m<nChains; ++m)\n\t\tsampler[m] -> setGammaSamplerType(gammaSampler);\n\t\t\n\n\t// ****************************************\n\n\t// INIT THE FILE OUTPUT\n\t// clear the content of previous files\n\n\tstd::ofstream logPOutFile; logPOutFile.open(outFilePath+inFile+\"logP_out.txt\", std::ios::out | std::ios::trunc); logPOutFile.close();\n\t// openlogP file in append mode\n\tlogPOutFile.open( outFilePath+inFile+\"logP_out.txt\" , std::ios_base::app); // note we don't close!\n\t// open avg files in trunc mode to cut previous content\n\tstd::ofstream gammaOutFile; gammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc); gammaOutFile.close();\n\tstd::ofstream piOutFile; piOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc); piOutFile.close();\n\tstd::ofstream htpOutFile; htpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc); htpOutFile.close();\n\n\t// Output to file the current state\n\tarma::umat gamma_out = sampler[0] -> getGamma(); // out var for the gammas\n\n\tarma::vec tmpVec = sampler[0] -> getPi();\n\tarma::vec pi_out = tmpVec;\n\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\tarma::vec hotspot_tail_prob_out = tmpVec;\n\n\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out)) << std::flush;\n\tgammaOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\t\t\t\t\t\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out << std::flush;\n\thtpOutFile.close();\n\n\n\t// ########\n\t// ########\n\t// ######## Start\n\t// ########\n\t// ########\n\n\tstd::cout << \"Starting \"<< nChains <<\" (parallel) chain(s) for \" << nIter << \" iterations:\" << std::endl << std::flush;\n\n\tunsigned int tick = 1000; // how may iter for each print?\n\n\tfor(unsigned int i=1; i < nIter ; ++i)\n\t{\n\n\t\tsampler.step();\n\t\t\n\t\t// #################### END LOCAL MOVES\n\n\t\t// ## Global moves\n\t\t// *** end Global move's section\n\n\t\t// UPDATE OUTPUT STATE\n\t\tgamma_out += sampler[0] -> getGamma(); // the result of the whole procedure is now my new mcmc point, so add that up\n\n\t\ttmpVec = sampler[0] -> getPi();\n\t\tpi_out += tmpVec;\n\t\ttmpVec.for_each( [](arma::vec::elem_type& val) { if(val>1.0) val = 1.0; else val=0.0; } );\n\t\thotspot_tail_prob_out += tmpVec;\n\n\t\t// Print something on how the chain is going\n\t\tif( (i+1) % tick == 0 )\n\t\t{\n\n\t\t\tstd::cout << \" Running iteration \" << i+1 << \" ... local Acc Rate: ~ gamma: \" << Utils::round( sampler[0] -> getGammaAccRate() , 3 );\n\n\t\t\tif( nChains > 1)\n\t\t\t\tstd::cout << \" -- Global: \" << Utils::round( sampler.getGlobalAccRate() , 3 ) << std::endl; \n\t\t\telse\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\t\n\t\t\t// Output to files every now and then\n\t\t\tif( (i+1) % (tick*10) == 0 )\n\t\t\t{\n\n\t\t\t\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\t\t\t\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)i+1.0) << std::flush;\n\t\t\t\tgammaOutFile.close();\n\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\t\t\t\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\t\t\t\tlogPOutFile << \tstd::endl << std::flush;\n\n\t\t\t\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\t\t\t\tpiOutFile << pi_out/((double)i+1.0) << std::flush;\n\t\t\t\tpiOutFile.close();\n\n\t\t\t\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\t\t\t\thtpOutFile << hotspot_tail_prob_out/((double)i+1.0) << std::flush;\n\t\t\t\thtpOutFile.close();\n\t\t\t}\n\n\t\t}\n\n\t} // end MCMC\n\n\n\t// Print the end\n\tstd::cout << \" MCMC ends. \" /* << \" Final temperature ratio ~ \" << temperatureRatio  */<< \"  --- Saving results and exiting\" << std::endl;\n\n\t// ### Collect results and save them\n\tgammaOutFile.open( outFilePath+inFile+\"gamma_out.txt\" , std::ios_base::trunc);\n\tgammaOutFile << (arma::conv_to<arma::mat>::from(gamma_out))/((double)nIter+1.0) << std::flush;\n\tgammaOutFile.close();\n\n\tlogPOutFile << \tsampler[0] -> getLogPO() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPPi() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPGamma() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogPW() <<  \" \";\n\tlogPOutFile << \tsampler[0] -> getLogLikelihood();\n\tlogPOutFile << \tstd::endl << std::flush;\n\tlogPOutFile.close();\n\n\t// -----\n\tpiOutFile.open( outFilePath+inFile+\"pi_out.txt\" , std::ios_base::trunc);\n\tpiOutFile << pi_out/((double)nIter) << std::flush;\n\tpiOutFile.close();\n\n\thtpOutFile.open( outFilePath+inFile+\"hotspot_tail_p_out.txt\" , std::ios_base::trunc);\n\thtpOutFile << hotspot_tail_prob_out/((double)nIter) << std::flush;\n\thtpOutFile.close();\n\t// -----\n\n\tstd::cout << \"Saved to :   \"+outFilePath+inFile+\"****_out.txt\" << std::endl;\n\tstd::cout << \"Final w : \" << sampler[0] -> getW() << \"       w/ proposal variance: \" << sampler[0] -> getVarWProposal() << std::endl;  \n\t// std::cout << \"Final o : \" << sampler[0] -> getO().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarOProposal() << std::endl;  \n\t// std::cout << \"Final pi : \" << sampler[0] -> getPi().t() << \"       w/ proposal variance: \" << sampler[0] -> getVarPiProposal() << std::endl;\n\tstd::cout << \"  -- Average Omega : \" << arma::accu( sampler[0] -> getO() * sampler[0] -> getPi().t() )/((double)(sampler[0]->getP()*sampler[0]->getS())) <<  std::endl;\n\tif( nChains > 1 ) \n\t\tstd::cout << \"Final temperature ratio : \" << sampler[1]->getTemperature() <<  std::endl << std::endl ;\n\n\t// Exit\n\n\tstd::cout << \"DONE, exiting! \" << std::endl << std::endl ;\n\treturn 0;\n\n}\n\nint main(int argc, char *  argv[])\n{\n\tomp_init_lock(&RNGlock);  // RNG lock for the parallel part\n\n\tunsigned int nIter = 10; // default number of iterations\n\tunsigned int s=1,p=1;      // might read them from a meta-data file, but for the moment is easier like this..\n\tunsigned int nChains = 1;\n\n\tstd::string inFile = \"data.txt\";\n\tstd::string outFilePath = \"\";\n\tstd::string omegaInitPath = \"\";\n\n\tstd::string method = \"\";\n\tstd::string gammaSampler = \"Bandit\";\n\tbool gPrior = false;\n\n    // ### Read and interpret command line (to put in a separate file / function?)\n    int na = 1;\n    while(na < argc)\n    {\n\t\tif ( 0 == strcmp(argv[na],\"--method\") )\n\t\t{\n\t\t\tmethod = std::string(argv[++na]); // use the next\n\n\t\t\tif( method != \"SSUR\" && method != \"HESS\" && method != \"dSUR\")\n\t\t\t{\n\t\t\t\tstd::cout << \"Unknown method: only SSUR, dSUR or HESS are available\" << std::endl;\n\t\t\t    return(1); //this is exit if I'm in a function elsewhere\n\t\t\t}\n\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--gammaSampler\") )\n\t\t{\n\t\t\tgammaSampler = std::string(argv[++na]); // use the next\n\n\t\t\tif( gammaSampler != \"MC3\" && gammaSampler != \"mc3\" && gammaSampler != \"Bandit\" && gammaSampler != \"bandit\")\n\t\t\t{\n\t\t\t\tstd::cout << \"Unknown gammaSampler method: only Bandit or MC3 are available\" << std::endl;\n\t\t\t    return(1); //this is exit if I'm in a function elsewhere\n\t\t\t}\n\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--gPrior\") )\n\t\t{\n\t\t\tgPrior = true;\n\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--nIter\") )\n\t\t{\n\t\t\tnIter = std::stoi(argv[++na]);\n\t\t\tif (na+1==argc) break;\n\t\t\t++na;\n\t\t}\n\t\t// else if ( 0 == strcmp(argv[na],\"--jtMethod\") )\n\t\t// {\n\t\t// \tjtMethod = std::stoi(argv[++na]); // 0 for single, 1 for multiple\n\t\t// \tif (na+1==argc) break;\n\t\t// \t++na;\n\t\t// }\n\t\telse if ( 0 == strcmp(argv[na],\"--nOutcomes\") )\n\t\t{\n\t\t\ts = std::stoi(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--nPredictors\") )\n\t\t{\n\t\t\tp = std::stoi(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--nChains\") )\n\t\t{\n\t\t\tnChains = std::stoi(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--inFile\") )\n\t\t{\n\t\t\tinFile = \"\"+std::string(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--outFilePath\") )\n\t\t{\n\t\t\toutFilePath = std::string(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse if ( 0 == strcmp(argv[na],\"--omegaInitPath\") )\n\t\t{\n\t\t\tomegaInitPath = \"\"+std::string(argv[++na]); // use the next\n\t\t\tif (na+1==argc) break; // in case it's last, break\n\t\t\t++na; // otherwise augment counter\n\t\t}\n\t\telse\n    {\n\t    std::cout << \"Unknown option: \" << argv[na] << std::endl;\n\t    return(1); //this is exit if I'm in a function elsewhere\n    }\n    }//end reading from command line\n\n\tstd::cout << \"Init RNG engine .. \" << std::endl;\n\n\t// ############# Init the RNG generator/engine\n\tstd::random_device r;\n\tunsigned int nThreads = omp_get_max_threads();\n\n\trng.reserve(nThreads);  // reserve the correct space for the vector of rng engines\n\tstd::seed_seq seedSeq;\t// and declare the seedSequence\n\tstd::vector<unsigned int> seedInit(8);\n\tlong long int seed = std::chrono::system_clock::now().time_since_epoch().count();\n\n\t// seed all the engines\n\tfor(unsigned int i=0; i<nThreads; ++i)\n\t{\n\t\trng[i] = std::mt19937_64(seed + i*(1000*(p*s*3+s*s)*nIter) );\n\t}\n\n\t// ############\n\n\t// ### Read the data\n\tunsigned int n;\n\tarma::mat Y, X;\n\tstd::cout << \"Trying to read data ...  \" << std::flush;\n\n\tif( Utils::readData(inFile, s, p, n, Y, X) ){\n\t\tstd::cout << \"Reading successfull!\" << std::endl;\n\t}else{\n\t\tstd::cout << \"OUCH! EXITING --- \" << std::endl;\n\t\treturn 1;\n\t}\n\n\t// The intercept columnto X will be inserted when initialising the chain\n\n\tstd::cout << \"Clearing and initialising output files \" << std::endl;\n\t// Re-define inFile so that I can use it in the output\n\tstd::size_t slash = inFile.find(\"/\");  // remove the path from inFile\n\twhile( slash != std::string::npos )\n\t{\n\t\tinFile.erase(inFile.begin(),inFile.begin()+slash+1);\n\t\tslash = inFile.find(\"/\");\n\t}\n\tinFile.erase(inFile.end()-4,inFile.end());  // remomve the .txt from inFile !\n\n\t// Update the \"outFilePath\" (inFile variable) with the method's name\n\tinFile += \"_\"+method+\"_\";\n\n\tint status;\n\n\t// TODO, I hate this, but I can't initialise/instanciate templated classes\n\t// at runtime so this seems fair (given that the 2 drive functions have their differences in output and stuff...)\n\t// still if there's a more elegant solution I'd like to find it\n\n\tif( method == \"SSUR\" )\n\t\tstatus = drive_SSUR(Y,X,nChains,nIter,inFile,outFilePath,gammaSampler,gPrior);\n\telse if( method == \"dSUR\" )\n\t\tstatus = drive_dSUR(Y,X,nChains,nIter,inFile,outFilePath,gammaSampler,gPrior);\n\telse if( method == \"HESS\" )\n\t\tstatus = drive_HESS(Y,X,nChains,nIter,inFile,outFilePath,gammaSampler,gPrior);\n\telse\n\t\tstatus = drive_SSUR(Y,X,nChains,nIter,inFile,outFilePath,gammaSampler,gPrior); // this makes a default, but\n\t\t\t// you shound't reach here if method is wrongly specified\n\n\treturn status;\n}", "meta": {"hexsha": "8f5af3d541495c19ae4b76698155530116e9ac77", "size": 31373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/drive.cpp", "max_stars_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_stars_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/drive.cpp", "max_issues_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_issues_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-13T12:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-13T12:57:09.000Z", "max_forks_repo_path": "src/drive.cpp", "max_forks_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_forks_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T14:43:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-16T14:43:06.000Z", "avg_line_length": 37.9359129383, "max_line_length": 168, "alphanum_fraction": 0.6116087081, "num_tokens": 10081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.5553296089685456}}
{"text": "#include <bits/stdc++.h>\n#include <boost/optional.hpp>\n\nusing namespace std;\n\nboost::optional<long long> dijkstra(\n    const vector<vector<tuple<long long, long long>>> &graph,\n    long long from_i,\n    long long to_i) {\n  const long long INF = 1e18;\n\n  vector<long long> dist(graph.size(), INF);\n  dist[from_i] = 0;\n\n  priority_queue<tuple<long long, long long>, vector<tuple<long long, long long>>, greater<>> que;\n  que.push(make_tuple(0, from_i));\n  while (!que.empty()) {\n    long long d, v;\n    tie(d, v) = que.top();\n    que.pop();\n    if (d > dist[v]) continue;\n    if (v == to_i) return d;\n\n    for (const auto &edge : graph[v]) {\n      long long w, u;\n      tie(u, w) = edge;\n      if (d + w < dist[u]) {\n        dist[u] = d + w;\n        que.push(make_tuple(d + w, u));\n      }\n    }\n  }\n\n  if (dist[to_i] < INF) {\n    return dist[to_i];\n  } else {\n    return boost::none;\n  }\n}\n\nvector<long long> topological_sort(const vector<vector<long long>> &graph) {\n  long long size = graph.size();\n\n  // 入次数\n  vector<long long> ins(size, 0);\n\n  for (auto &&vs : graph) {\n    for (auto &&v : vs) {\n      ins[v]++;\n    }\n  }\n\n  // 入次数がゼロのやつを集める\n  vector<long long> zeros;\n  for (long long v = 0; v < size; ++v) {\n    if (ins[v] == 0) {\n      zeros.push_back(v);\n    }\n  }\n\n  // ゼロのやつから追加してく\n  vector<long long> ret;\n  while (!zeros.empty()) {\n    long long v = zeros.back();\n    zeros.pop_back();\n    ret.push_back(v);\n    for (auto &&u:  graph[v]) {\n      ins[u]--;\n      if (ins[u] == 0) {\n        zeros.push_back(u);\n      }\n    }\n  }\n  // 閉路があると入次数が絶対ゼロにならない\n  if (ret.size() != size) {\n    throw invalid_argument(\"閉路があります\");\n  }\n\n  return ret;\n}\n", "meta": {"hexsha": "63897a8fbc2ca1382a58680a6969e5ddb4ef1bc2", "size": 1651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graph.cpp", "max_stars_repo_name": "nohtaray/competitive-programming.cpp", "max_stars_repo_head_hexsha": "1051dfade98e781c02331f9c4a8044dac8480d8b", "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": "graph.cpp", "max_issues_repo_name": "nohtaray/competitive-programming.cpp", "max_issues_repo_head_hexsha": "1051dfade98e781c02331f9c4a8044dac8480d8b", "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": "graph.cpp", "max_forks_repo_name": "nohtaray/competitive-programming.cpp", "max_forks_repo_head_hexsha": "1051dfade98e781c02331f9c4a8044dac8480d8b", "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.3827160494, "max_line_length": 98, "alphanum_fraction": 0.5499697153, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812552, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.5553267877859324}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include \"CEGO/minimizers.hpp\"\n#include \"CEGO/utilities.hpp\"\n#include <Eigen/Dense>\n\n// autodiff include\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\n\n#if defined(PYBIND11)\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\nnamespace py = pybind11;\n#endif\n\nstd::atomic_size_t Ncalls(0);\n\ntemplate <typename T> using EArray = Eigen::Array<T, Eigen::Dynamic, 1>;\n\nclass Bumps {\npublic:\n    std::size_t Nbumps;\n    Eigen::ArrayXd c0, xp, yp, zp;\n    double gamma = 10;\n    const std::vector<CEGO::Bound> m_bounds;\n    \n    Bumps(std::size_t Nbumps, std::size_t Npoints, const std::vector<CEGO::Bound> &bounds) : Nbumps(Nbumps), m_bounds(bounds)\n    {\n        // Initialize the random number generator\n        std::random_device rd;  // Will be used to obtain a seed for the random number engine\n        std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()\n\n        // Calculate the initial set of coefficients for the bump characteristics\n        c0.resize(Nbumps * 6); \n        for (auto i = 0; i < bounds.size(); ++i) {\n            double dbl; int integer;\n            bounds[i].gen_uniform(gen, dbl, integer);\n            if (bounds[i].m_lower.type == bounds[i].m_lower.DOUBLE){\n                c0[i] = dbl;\n            }\n            else {\n                c0[i] = static_cast<double>(integer);\n            }\n        }\n\n        // Generate some random points in the domain [0.1,1.0] for both variables\n        xp = (1-0.1)*(Eigen::ArrayXd::Random(Npoints)+1)/2 + 0.1;\n        yp = (1-0.1)*(Eigen::ArrayXd::Random(Npoints)+1)/2 + 0.1;\n        zp = f_givenxy(c0, xp, yp);\n\n        double checkval = objective(to_scaled(c0));\n        std::cout << \"c0: \" << c0 << std::endl; \n        \n        assert(std::abs(checkval) < 1e-16);\n        if (std::abs(checkval) > 1e-16) {\n            throw std::invalid_argument(\"Did not start out with zero objective function!\");\n        }\n    }\n    /**\n     * @brief Calculate the functional value for a set of vectors of points\n     * @brief xb The x coordinate of the center of the bump\n     * @brief x The x coordinate of the points to be evaluated\n     * @brief y The y coordinate of the points to be evaluated\n     */\n    template <typename T>\n    EArray<T> f_givenxy(const EArray<T> &c, const EArray<T> &x, const EArray<T> &y) \n    {\n        Ncalls++;\n        EArray<T> s = EArray<T>::Zero(x.size());\n        auto chunksize = 6; \n        assert(c.size()%chunksize==0);\n        for (long i = 0; i < c.size(); i += chunksize) {\n            s += x.pow(c[i+0])*y.pow(c[i+1])*(c[i+2]*(x-c[i+3]).square() +c[i+4]*(y-c[i+5]).square()).exp();\n        }\n        return s.eval();\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const EArray<CEGO::numberish> &c = static_cast<const CEGO::NumericalIndividual<CEGO::numberish>*>(pind)->get_coefficients();\n        Eigen::ArrayXd cc(c.size());\n        for (auto i = 0; i < cc.size(); ++i) {\n            cc[i] = c[i];\n        }\n        return objective(cc);\n    }\n    double objective(const EArray<double>& cscaled) {\n        return (f_givenxy<double>(to_realworld<double>(cscaled), xp, yp) - zp).square().sum();\n    }\n    std::complex<double> objective(const EArray<std::complex<double>>& cscaled) {\n        return (f_givenxy<std::complex<double>>(to_realworld<std::complex<double>>(cscaled), xp, yp) - zp).square().sum();\n    }\n\n    autodiff::dual objective(const EArray<autodiff::dual>& cscaled) {\n        EArray<autodiff::dual> creal = to_realworld(cscaled);\n        EArray<autodiff::dual> zmodel = f_givenxy<autodiff::dual>(creal, xp, yp);\n        EArray<autodiff::dual> err = zmodel - zp.cast<autodiff::dual>();\n        return err.square().sum();\n    }\n\n    // Inspired by scipy, keep all variables scaled in 0,1\n    template <typename T>\n    EArray<T> to_realworld(const EArray<T>&x){\n        EArray<T> o(x.size());\n        for (auto i = 0; i < o.size(); ++i){\n            if constexpr (std::is_same<T, std::complex<double>>::value) {\n                // If complex<double> type, first cast the numberish bounds to double, then to complex\n                // Otherwise compiler gets confused\n                T lower = static_cast<T>(static_cast<double>(m_bounds[i].m_lower));\n                T upper = static_cast<T>(static_cast<double>(m_bounds[i].m_upper));\n                o[i] = lower * (static_cast<T>(1.0) - x[i]) + upper * x[i];\n            }\n            else {\n                T lower = static_cast<T>(m_bounds[i].m_lower);\n                T upper = static_cast<T>(m_bounds[i].m_upper);\n                o[i] = lower * (static_cast<T>(1.0) - x[i]) + upper * x[i];\n            }\n        }\n        return o.eval();\n    }\n    Eigen::ArrayXd to_scaled(const Eigen::ArrayXd &x) {\n        Eigen::ArrayXd o(x.size());\n        for (auto i = 0; i < o.size(); ++i) {\n            double lower = static_cast<double>(m_bounds[i].m_lower);\n            double upper = static_cast<double>(m_bounds[i].m_upper);\n            o[i] = (x[i]-lower)/(upper-lower);\n        }\n        return o;\n    }\n       \n    void plot_surface() {\n        #if defined(PYBIND11)\n        using namespace pybind11::literals;\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        std::size_t Nx = 100, Ny = 100;\n        Eigen::MatrixXd X = Eigen::RowVectorXd::LinSpaced(Nx, 0.1, 1).replicate(Ny, 1);\n        Eigen::MatrixXd Y = Eigen::VectorXd::LinSpaced(Ny, 0.1, 1).replicate(Nx, 1);\n        X.resize(Nx*Ny,1); Y.resize(Nx*Ny,1);\n        Eigen::MatrixXd Z = f_givenxy(c0, X.array(), Y.array()).matrix();\n        X.resize(Nx, Ny); Y.resize(Nx, Ny); Z.resize(Nx, Ny);\n        \n        Eigen::ArrayXd levels = Eigen::ArrayXd::LinSpaced(300, Z.minCoeff(), Z.maxCoeff());\n        try{\n            plt.attr(\"contourf\")(X, Y, Z, levels);\n        }\n        catch (std::exception &e) {\n            std::cout << e.what()  << std::endl;\n        }\n        plt.attr(\"colorbar\")(); \n        plt.attr(\"scatter\")(xp, yp);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No support for pybind11, so no plots\\n\";\n        #endif\n    }\n    void plot_trace(const std::vector<double> &best_costs) {\n        #if defined(PYBIND11)\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(best_costs);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No support for pybind11, so no plots\\n\";\n        #endif\n    }\n};\n\nstruct BumpsInputs{\n    std::string root = \"\";\n    std::size_t parallel_threads = 1;\n    std::size_t Nbumps = 4;\n    std::vector<std::size_t> Nlayersvec = { 1 };\n    std::size_t i = 0;\n    std::size_t gradmin_mod = 5;\n    std::size_t Nmax_gradient = 5;\n};\n\ninline void to_json(nlohmann::json& j, const BumpsInputs& f) {\n    j = nlohmann::json{ { \"root\", f.root },{ \"parallel_threads\", f.parallel_threads },{ \"Nbumps\", f.Nbumps },{\"i\",f.i},{\"gradmin_mod\",f.gradmin_mod},{\"Nmax_gradient\",f.Nmax_gradient} };\n}\n\ninline void from_json(const nlohmann::json& j, BumpsInputs& f) {\n    f.root = j.at(\"root\").get<std::string>();\n    f.parallel_threads = j.at(\"parallel_threads\").get<int>();\n    f.Nbumps = j.at(\"Nbumps\").get<int>();\n    f.i = j.at(\"i\").get < std::size_t > ();\n    f.gradmin_mod = j.at(\"gradmin_mod\").get < std::size_t >();\n    f.Nmax_gradient = j.at(\"Nmax_gradient\").get < std::size_t >();\n}\n\nbool do_one(BumpsInputs &inputs)\n{\n    std::srand((unsigned int)time(0));\n\n    // Construct the bounds\n    std::size_t Npoints = inputs.Nbumps*6*10;\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < inputs.Nbumps; ++i) {\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(0.1, 1))); // ex\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(1, 3))); // ey\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-50, -10))); // gx\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(0.1, 1))); // xb\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(-50, -10))); // gy\n        bounds.push_back(CEGO::Bound(std::pair<double, double>(0.1, 1))); // yb\n    } \n\n    // Normalized bounds in [0,1]\n    std::vector<CEGO::Bound> nbounds;\n    for (auto i = 0; i < inputs.Nbumps; ++i) {\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // ex\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // ey\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // gx\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // xb\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // gy\n        nbounds.push_back(CEGO::Bound(std::pair<double, double>(0, 1))); // yb\n    }\n    \n    Bumps bumps(inputs.Nbumps, Npoints, bounds);\n    //bumps.plot_surface();\n\n    for (auto Nlayers : inputs.Nlayersvec){\n        Ncalls = 0;\n        CEGO::CostFunction<CEGO::numberish> cost_wrapper = std::bind((double (Bumps::*)(const CEGO::AbstractIndividual *)) &Bumps::objective, bumps, std::placeholders::_1);\n        auto Npop_size = 15*bounds.size();\n        auto layers = CEGO::Layers<CEGO::numberish>(cost_wrapper, bounds.size(), Npop_size, Nlayers, 5);\n        layers.parallel = (inputs.parallel_threads > 1);\n        layers.parallel_threads = inputs.parallel_threads;\n        layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution);\n        layers.set_bounds(nbounds);\n        auto f = [&bumps](const CEGO::EArray<double>& c)->double { return bumps.objective(c); };\n        auto f2 = [&bumps](const CEGO::EArray<std::complex<double>>& c)->std::complex<double> { return bumps.objective(c); };\n        layers.add_gradient(f, f2);\n\n        auto flags = layers.get_evolver_flags();\n        flags[\"Nelite\"] = 1;\n        flags[\"Fmin\"] = 0.1;\n        flags[\"Fmax\"] = 1.0;\n        flags[\"CR\"] = 1;\n        layers.set_evolver_flags(flags);\n\n        std::vector<double> best_costs; \n        std::vector<std::vector<double> > objs;\n        double VTR = 1e-16, best_cost = 999999.0;\n        auto startTime = std::chrono::system_clock::now();\n        for (auto counter = 0; counter < 50000; ++counter) {\n            layers.do_generation();\n\n            if (counter % inputs.gradmin_mod == 0 && counter > 0) {\n                layers.gradient_minimizer();\n            }\n\n            // Store the best objective function in each layer\n            std::vector<double> oo;\n            for (auto &&cost_coefficients : layers.get_best_per_layer()) {\n                oo.push_back(std::get<0>(cost_coefficients));\n            }\n            objs.push_back(oo);\n            auto stats = layers.cost_stats_each_layer();\n\n            // For the overall best result, print it, and write JSON to file\n            auto [best_cost, best_coeffs] = layers.get_best();\n            if (counter % 50 == 0) {\n                std::cout << counter << \": best: \" << best_cost << std::endl;\n                //std::cout << bumps.to_realworld(best_coeffs//)-bumps.c0 << \"\\n \";// << CEGO::vec2string(bumps.c0) << \"\\n\";\n            }\n            if (best_cost < VTR){ return true; }\n        }\n        auto endTime = std::chrono::system_clock::now();\n        double elap = std::chrono::duration<double>(endTime - startTime).count();\n        std::cout << \"run:\" << elap << \" s\" << std::endl;\n\n        //bumps.plot_trace(best_costs);\n        std::string fname = inputs.root + \"Nbumps\"+std::to_string(inputs.Nbumps)+\"-Nlayers\"+std::to_string(Nlayers) + \"-run\" + std::to_string(inputs.i) + \".txt\";\n        FILE* fp = fopen(fname.c_str(), \"w\");\n        for (auto j = 0; j < best_costs.size(); ++j){\n            fprintf(fp, \"%12.8e\", best_costs[j]);\n            if (j < best_costs.size() - 1) {\n                fprintf(fp, \", \");\n            }\n        }\n        fclose(fp);\n        /*std::cout << bumps.xb0 << std::endl;\n        std::cout << bumps.yb0 << std::endl;*/\n        std::cout << \"NFE:\" << Ncalls << std::endl;\n    }\n    return 0;\n}\n\nint main() {\n    #if defined(PYBIND11)\n    py::scoped_interpreter interp{};\n    #endif\n    BumpsInputs in;\n    in.root = \"shaped-\";\n    in.Nlayersvec = {3};\n    using CEGO::get_env_int;\n    auto Nrepeats = get_env_int(\"NREPEATS\", 10);\n    in.Nbumps = get_env_int(\"NBUMPS\", 1);\n    in.gradmin_mod = get_env_int(\"GRADMOD\", 100);\n    in.parallel_threads = get_env_int(\"NTHREADS\", 6);\n    in.Nmax_gradient = get_env_int(\"NMAX_gradient\", 5);\n    nlohmann::json j = in;\n    std::cout << j << std::endl;\n    int good_counter = 0;\n    for (in.i = 0; in.i < Nrepeats; ++in.i) {\n        good_counter += do_one(in);\n    }\n    std::cout << \"Success: \" << good_counter << \"/\" << Nrepeats << std::endl;\n}\n", "meta": {"hexsha": "95577cbf3eea137ac5a1f721f435531b9e4536d2", "size": 12692, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/shaped_inverse_gaussian.cxx", "max_stars_repo_name": "usnistgov/CEGO", "max_stars_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/shaped_inverse_gaussian.cxx", "max_issues_repo_name": "usnistgov/CEGO", "max_issues_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/shaped_inverse_gaussian.cxx", "max_forks_repo_name": "usnistgov/CEGO", "max_forks_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 40.9419354839, "max_line_length": 185, "alphanum_fraction": 0.5757957769, "num_tokens": 3640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5552791775482369}}
{"text": "//\n//  Rational.hpp\n//  \n//\n//  https://gist.github.com/sklaw/10473569\n//\n\n#ifndef RATIONAL_NUM\n#define RATIONAL_NUM\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../basic.h\"\n\nclass RationalNum {\n    friend RationalNum operator+(const RationalNum& left, const RationalNum& right);\n    friend RationalNum operator-(const RationalNum& left, const RationalNum& right);\n    friend RationalNum operator*(const RationalNum& left, const RationalNum& right);\n    friend RationalNum operator/(const RationalNum& left, const RationalNum& right);\n    friend bool operator==(const RationalNum& left, const RationalNum& right);\n    friend bool operator!=(const RationalNum& left, const RationalNum& right);\n    friend bool operator<(const RationalNum& left, const RationalNum& right);\n    friend bool operator>(const RationalNum& left, const RationalNum& right);\n    friend bool operator<=(const RationalNum& left, const RationalNum& right);\n    friend bool operator>=(const RationalNum& left, const RationalNum& right);\n    friend std::ostream& operator<<(std::ostream& out, const RationalNum& obj);\n    friend std::istream& operator>>(std::istream& in, RationalNum& obj);\n    \npublic:\n    RationalNum(): numerator(0), denominator(1) {}\n    RationalNum(rational_t x): numerator(x.p), denominator(x.q) {}\n    RationalNum(int_t numerator_, int_t denominator_ = 1): numerator(numerator_), denominator(denominator_) {}\n    \n    RationalNum& operator=(const RationalNum& obj);\n    RationalNum& operator+=(const RationalNum& obj);\n    RationalNum& operator-=(const RationalNum& obj);\n    RationalNum& operator*=(const RationalNum& obj);\n    RationalNum& operator/=(const RationalNum& obj);\n    RationalNum& operator++();\n    RationalNum operator++(int);\n    RationalNum& operator--();\n    RationalNum operator--(int);\n    RationalNum operator+() const;\n    RationalNum operator-() const;\n    \n    explicit operator int_t() const;\n    \n    int_t getNumerator() const { return numerator; }\n    int_t getDenominator() const { return denominator; }\n    \nprivate:\n    int_t numerator;\n    int_t denominator;\n    RationalNum& simplify();\n};\n\nnamespace Eigen {\ntemplate<> struct NumTraits<RationalNum>\n : NumTraits<int_t> // permits to get the epsilon, dummy_precision, lowest, highest functions\n{\n  typedef RationalNum Real;\n  typedef RationalNum NonInteger;\n  typedef RationalNum Nested;\n  enum {\n    IsComplex = 0,\n    IsInteger = 0,\n    IsSigned = 1,\n    RequireInitialization = 1,\n    ReadCost = 1,\n    AddCost = 3,\n    MulCost = 3\n  };\n    static inline Real epsilon() { return 0; }\n    static inline Real dummy_precision() { return 0; }\n//    static inline int digits10() { return 0; }\n\n};\n}\n\ninline const RationalNum& conj(const RationalNum& x)  { return x; }\ninline const RationalNum& real(const RationalNum& x)  { return x; }\ninline RationalNum imag(const RationalNum&)    { return RationalNum(); }\ninline RationalNum abs(const RationalNum&  x)  { return RationalNum(absInt(x.getNumerator()), absInt(x.getDenominator())); }\ninline RationalNum abs2(const RationalNum& x)  { return x*x; }\n\ninline rational_t to_rational_t(const RationalNum& x) { return {x.getNumerator(), x.getDenominator()}; }\n\n#endif\n", "meta": {"hexsha": "5bc0d9d9203179d92ea3dca30bf91677f6cb2702", "size": 3194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/CEigenBridge/types/Rational.hpp", "max_stars_repo_name": "taketo1024/swm-eigen", "max_stars_repo_head_hexsha": "952ecdb73a2739641e75909c8d9e724e32b2ed0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-09-19T07:55:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T00:43:47.000Z", "max_issues_repo_path": "Sources/CEigenBridge/types/Rational.hpp", "max_issues_repo_name": "taketo1024/swm-eigen", "max_issues_repo_head_hexsha": "952ecdb73a2739641e75909c8d9e724e32b2ed0f", "max_issues_repo_licenses": ["MIT"], "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/CEigenBridge/types/Rational.hpp", "max_forks_repo_name": "taketo1024/swm-eigen", "max_forks_repo_head_hexsha": "952ecdb73a2739641e75909c8d9e724e32b2ed0f", "max_forks_repo_licenses": ["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.8876404494, "max_line_length": 124, "alphanum_fraction": 0.7094552286, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.5552791759866099}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_CHOOSE_HPP\n#define STAN_MATH_PRIM_FUN_CHOOSE_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <cmath>\n#include <limits>\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  }\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/**\n * Enables the vectorised application of the binomial coefficient function,\n * when 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 Binomial coefficient function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>\ninline auto choose(const T1& a, const T2& b) {\n  return apply_scalar_binary(\n      a, b, [&](const auto& c, const auto& d) { return choose(c, d); });\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "8c7c0c35c79356d5d0f7a56928bb0ed9454fd564", "size": 1808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/choose.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/fun/choose.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/choose.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 30.1333333333, "max_line_length": 79, "alphanum_fraction": 0.689159292, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.5552791624537933}}
{"text": "#include \"QMathUtil.h\"\n#include <cmath>\n//#include <Eigen/Dense>\n#include <iostream>\nnamespace GCL {\n\nQVector3D QMathUtil::getRayPlaneIntersect(const QVector3D &rayPos, const QVector3D &rayDir,\n                              const QVector3D &planePoint, const QVector3D &planeNormal, bool *has_intersection)\n{\n    float t0 = QVector3D::dotProduct(rayDir,planeNormal);\n    float t1 = QVector3D::dotProduct(rayPos - planePoint , planeNormal);\n    if(fabs(t0) < 1e-7)\n    {\n        if(has_intersection)\n        {\n            *has_intersection = false;\n        }\n        return QVector3D(0,0,0);\n    }\n\n    float k = -t1 / t0;\n    QVector3D intersect = rayPos + k * rayDir;\n    if(has_intersection)\n    {\n        *has_intersection = true;\n    }\n    return intersect;\n}\nfloat clamp(float x, float l, float r)\n{\n    if(x < l) return l;\n    if(x > r) return r;\n    return x;\n}\nQVector3D QMathUtil::fromMatrixToEuler(const QMatrix4x4 &m, const QString &order)\n{\n    QMatrix3x3 tm = m.normalMatrix();\n\n   float m11 = tm(0,0), m12 = tm(1,0), m13 = tm(2,0);\n   float m21 = tm(0,1), m22 = tm(1,1), m23 = tm(2,1);\n   float m31 = tm(0,2), m32 = tm(1,2), m33 = tm(2,2);\n    float _x,_y,_z;\n    if(order == \"XYZ\")\n    {\n        _y = asin(clamp(m13,-1,1));\n        if(fabs(m13) < 0.99999)\n        {\n            _x = atan2(-m23,m33);\n            _z = atan2(-m12,m11);\n        }else\n        {\n            _x = atan2(m32,m22);\n            _z = 0;\n        }\n    }else if ( order == \"YXZ\" ) {\n\n        _x = asin( - clamp( m23, - 1, 1 ) );\n\n        if ( fabs( m23 ) < 0.99999 ) {\n\n            _y = atan2( m13, m33 );\n            _z = atan2( m21, m22 );\n\n        } else {\n\n            _y = atan2( - m31, m11 );\n            _z = 0;\n\n        }\n\n    } else if ( order == \"ZXY\" ) {\n\n        _x = asin( clamp( m32, - 1, 1 ) );\n\n        if ( fabs( m32 ) < 0.99999 ) {\n\n            _y = atan2( - m31, m33 );\n            _z = atan2( - m12, m22 );\n\n        } else {\n\n            _y = 0;\n            _z = atan2( m21, m11 );\n\n        }\n\n    } else if ( order == \"ZYX\" ) {\n\n        _y = asin( - clamp( m31, - 1, 1 ) );\n\n        if ( fabs( m31 ) < 0.99999 ) {\n\n            _x = atan2( m32, m33 );\n            _z = atan2( m21, m11 );\n\n        } else {\n\n            _x = 0;\n            _z = atan2( - m12, m22 );\n\n        }\n\n    } else if ( order == \"YZX\" ) {\n\n        _z = asin( clamp( m21, - 1, 1 ) );\n\n        if ( fabs( m21 ) < 0.99999 ) {\n\n            _x = atan2( - m23, m22 );\n            _y = atan2( - m31, m11 );\n\n        } else {\n\n            _x = 0;\n            _y = atan2( m13, m33 );\n\n        }\n\n    } else if ( order == \"XZY\" ) {\n\n        _z = asin( - clamp( m12, - 1, 1 ) );\n\n        if ( fabs( m12 ) < 0.99999 ) {\n\n            _x = atan2( m32, m22 );\n            _y = atan2( m13, m11 );\n\n        } else {\n\n            _x = atan2( - m23, m33 );\n            _y = 0;\n\n        }\n\n    } else {\n\n         qDebug()<<( \"THREE.Euler: .setFromRotationMatrix() given unsupported order: \" + order );\n    }\n\n    QVector3D v(_x,_y,_z);\n    v = v / 3.1415926535898 * 180;\n    return -v;\n\n\n}\n\nQVector3D QMathUtil::mulEuler(const QVector3D &x, const QVector3D &y)\n{\n    QMatrix4x4 mat;\n    mat.rotate(x[0],QVector3D(1,0,0));\n    mat.rotate(x[1],QVector3D(0,1,0));\n    mat.rotate(x[2],QVector3D(0,0,1));\n\n    mat.rotate(y[0],QVector3D(1,0,0));\n    mat.rotate(y[1],QVector3D(0,1,0));\n    mat.rotate(y[2],QVector3D(0,0,1));\n\n    return QMathUtil::fromMatrixToEuler(mat);\n\n}\n\nfloat QMathUtil::getDistanceSumToPlane(const QList<QVector3D> &vlist, const QVector3D &point, const QVector3D &normal)\n{\n    float sum = 0;\n    for(const auto & v : vlist)\n    {\n        sum += fabs(QVector3D::dotProduct(v-point,normal));\n    }\n    return sum;\n}\n\nfloat QMathUtil::getDistanceSquareSumToPlane(const QList<QVector3D> &vlist, const QVector3D &point, const QVector3D &normal)\n{\n    float sum = 0;\n    for(const auto & v : vlist)\n    {\n        float val = fabs(QVector3D::dotProduct(v-point,normal));\n        sum += val * val;\n    }\n    return sum;\n}\n\nvoid QMathUtil::computePCA(const QList<QVector3D> &vlist, QVector3D &axis_0, QVector3D &axis_1, QVector3D &axis_2)\n{\n//    QVector3D center;\n//    for(const auto &v : vlist)\n//    {\n//        center += v;\n//    }\n//    center/= vlist.size();\n//    Eigen::Matrix3d mat;\n//    for(const auto &v : vlist)\n//    {\n//        Eigen::Vector3d ev;\n//        QVector3D tv = v - center;\n//        for(int j=0; j < 3; j++)\n//        {\n//            ev(j) = tv[j];\n//        }\n//        Eigen::Matrix3d tm = ev * ev.transpose();\n//        mat += tm;\n//    }\n//    mat /= vlist.size();\n//    Eigen::EigenSolver<Eigen::Matrix3d> solver;\n//    solver.compute(mat);\n//    auto eigen_v = solver.eigenvectors();\n//    for(int j=0; j < 3; j++)\n//    {\n//        axis_0[j] = eigen_v.coeff(j,0).real();\n//        axis_1[j] = eigen_v.coeff(j,1).real();\n//        axis_2[j] = eigen_v.coeff(j,2).real();\n//    }\n\n\n}\n\nQVector3D QMathUtil::getRayTriangleIntesect(const QVector3D &rayPos, const QVector3D &rayDir, const QVector3D &v0, const QVector3D &v1, const QVector3D &v2, bool *has_intersection)\n{\n    Vec3 vray(rayPos.x(),rayPos.y(),rayPos.z());\n    Vec3 vdir(rayDir.x(),rayDir.y(),rayDir.z());\n    Vec3 vv0(v0.x(),v0.y(),v0.z());\n    Vec3 vv1(v1.x(),v1.y(),v1.z());\n    Vec3 vv2(v2.x(),v2.y(),v2.z());\n    Vec3 ans;\n    bool t = Vec3::getIntersectionRayToTriangle(vray,vdir,vv0,vv1,vv2,ans);\n\n    if(has_intersection)\n    {\n        *has_intersection = t;\n    }\n    return QVector3D(ans[0],ans[1],ans[2]);\n}\n\nQVector3D QMathUtil::fromVectorTransformToEuler(const QVector3D &v0, const QVector3D &v1,const QString &order)\n{\n    Vec3 vv0(v0.x(),v0.y(),v0.z());\n    Vec3 vv1(v1.x(),v1.y(),v1.z());\n\n    Quat quat =  Quat::quatFromVectorTransform(vv0,vv1);\n    HomoMatrix4 hmat =  quat.convertToMatrix();\n\n    QMatrix4x4 qmat(hmat.data(),4,4);\n\n    return fromMatrixToEuler(qmat,order);\n\n}\n\n\n\n}\n", "meta": {"hexsha": "04d819a73358a3625fcaf0214b937bcc1344290b", "size": 5861, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Q3D/Core/QMathUtil.cpp", "max_stars_repo_name": "565353780/opengl-automaskobj", "max_stars_repo_head_hexsha": "bae7c35a0aece5a09ec67b02241aff58932c6daf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Q3D/Core/QMathUtil.cpp", "max_issues_repo_name": "565353780/opengl-automaskobj", "max_issues_repo_head_hexsha": "bae7c35a0aece5a09ec67b02241aff58932c6daf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Q3D/Core/QMathUtil.cpp", "max_forks_repo_name": "565353780/opengl-automaskobj", "max_forks_repo_head_hexsha": "bae7c35a0aece5a09ec67b02241aff58932c6daf", "max_forks_repo_licenses": ["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.3505976096, "max_line_length": 180, "alphanum_fraction": 0.5207302508, "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.5551161140611238}}
{"text": "#ifndef ROVER_LINEAR_REGRESSION_HPP\n#define ROVER_LINEAR_REGRESSION_HPP\n#include <tuple>\n#include <vector>\n#include <dlib/matrix.h>\n\nnamespace Rover {\n\n  //! Models a trial using linear regression.\n  /*!\n    \\tparam T The arithmetic type used for calculations.\n  */\n  template<typename T = double>\n  class LinearRegression {\n    public:\n\n      //! The arithmetic type used for calculations.\n      using Type = T;\n\n      //! Learns a trial represented by a ScalarView.\n      template<typename ScalarView>\n      void learn(const ScalarView& view);\n\n      //! Predicts the dependent variable for a set of arguments.\n      template<typename Arguments>\n      Type predict(const Arguments& args) const;\n\n    private:\n      dlib::matrix<Type> m_transformation;\n\n      template<typename ScalarView>\n      static dlib::matrix<Type> compute_transformation_vector(\n        const ScalarView& trial);\n  };\n\n  template<typename T>\n  template<typename ScalarView>\n  void LinearRegression<T>::learn(const ScalarView& view) {\n    m_transformation = compute_transformation_vector(view);\n  }\n\n  template<typename T>\n  template<typename Arguments>\n  typename LinearRegression<T>::Type LinearRegression<T>::predict(const\n      Arguments& args) const {\n    auto x = dlib::matrix<Type, 1>(args.size() + 1);\n    x(0, 0) = static_cast<Type>(1.);\n    std::copy(args.begin(), args.end(), x.begin() + 1);\n    auto result = x * m_transformation;\n    return result;\n  }\n\n  template<typename T>\n  template<typename ScalarView>\n  dlib::matrix<typename LinearRegression<T>::Type> \n      LinearRegression<T>::compute_transformation_vector(const ScalarView&\n      view) {\n    auto x = dlib::matrix<Type>(view.size(), view[0].m_arguments.size() + 1);\n    auto y = dlib::matrix<Type>(view.size(), 1);\n    for(auto i = std::size_t(0); i < view.size(); ++i) {\n      auto sample = view[i];\n      x(i, 0) = static_cast<Type>(1.);\n      std::copy(sample.m_arguments.begin(), sample.m_arguments.end(), x.begin()\n        + i * x.nc() + 1);\n      y(0, i) = sample.m_result;\n    }\n    auto xtr = dlib::trans(x);\n    auto result = dlib::inv(xtr * x) * xtr * y;\n    return result;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "0c258dec1c45f440f00e224586800617de3de379", "size": 2147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Include/Rover/LinearRegression.hpp", "max_stars_repo_name": "kranar/rover", "max_stars_repo_head_hexsha": "a4a824321859e34478fec0924c0b76144b3fc20e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Include/Rover/LinearRegression.hpp", "max_issues_repo_name": "kranar/rover", "max_issues_repo_head_hexsha": "a4a824321859e34478fec0924c0b76144b3fc20e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2019-02-05T23:18:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T14:19:04.000Z", "max_forks_repo_path": "Include/Rover/LinearRegression.hpp", "max_forks_repo_name": "kranar/rover", "max_forks_repo_head_hexsha": "a4a824321859e34478fec0924c0b76144b3fc20e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-01T06:32:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T06:32:05.000Z", "avg_line_length": 29.0135135135, "max_line_length": 79, "alphanum_fraction": 0.6590591523, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.5550245283624269}}
{"text": "// Haney's induction calculation benchmark.\n//\n// See: Scott W. Haney, Is C++ Fast Enough for Scientific Computing?\n//      Computers in Physics Vol. 8 No. 6 (1994), p. 690\n//\n//      Arch D. Robison, C++ Gets Faster for Scientific Computing,\n//      Computers in Physics Vol. 10 No. 5 (1996), p. 458\n//\n\n#include <blitz/vector.h>\n#include <blitz/rand-uniform.h>\n#include <blitz/benchext.h>\n#ifdef BZ_HAVE_STD\n#include <valarray>\n#else\n#include <valarray.h>\n#endif\n\nBZ_USING_NAMESPACE(blitz)\n\n#ifndef M_PI\n #define M_PI   3.14159265358979323846\n#endif\n\n#ifdef BZ_FORTRAN_SYMBOLS_WITH_TRAILING_UNDERSCORES\n#define vecopsf    vecopsf_\n#define vecopsfo   vecopsfo_\n#endif\n\nextern \"C\"\n{\n\tvoid vecopsf(float *li, const float *R, const float *w, const int &N,\n\t             const int& iters);\n\tvoid vecopsfo(float *li, const float *R, const float *w, const int &N,\n\t              const int& iters);\n}\n\ninline float sqr(float x)\n{\n\treturn x*x;\n}\n\nconst float Mu0 = 4.0 * M_PI * 1.0e-7;\n\nvoid HaneyCVersion(BenchmarkExt<int>& bench);\nvoid HaneyFortranVersion(BenchmarkExt<int>& bench);\nvoid HaneyBlitzVersion(BenchmarkExt<int>& bench);\n\nint main()\n{\n\tBenchmarkExt<int> bench(\"Haney Inductance Calculation\", 3);\n\n\tbench.setRateDescription(\"Operations/s\");\n\n\tbench.beginBenchmarking();\n\n\tHaneyCVersion(bench);\n\tHaneyFortranVersion(bench);\n\tHaneyBlitzVersion(bench);\n\n\tbench.endBenchmarking();\n\n\tbench.saveMatlabGraph(\"haney.m\");\n\n\treturn 0;\n}\n\nvoid initializeRandom(float* data, int length)\n{\n\tRandom<Uniform> unif(1.0, 2.0);\n\tfor (int i=0; i < length; ++i)\n\t\tdata[i] = unif.random();\n}\n\nvoid HaneyCVersion(BenchmarkExt<int>& bench)\n{\n\tbench.beginImplementation(\"Inlined C\");\n\n\twhile (!bench.doneImplementationBenchmark()) {\n\t\tint length = bench.getParameter();\n\t\tlong iters = bench.getIterations();\n\n\t\tcout << \"length = \" << length << \" iters = \" << iters << endl;\n\n\t\tfloat* li = new float[length];\n\t\tfloat* R = new float[length];\n\t\tfloat* w = new float[length];\n\n\t\tinitializeRandom(li, length);\n\t\tinitializeRandom(R, length);\n\t\tinitializeRandom(w, length);\n\n\t\t// Tickle the cache\n\t\tfor (int i=0; i < length; ++i)\n\t\t\tli[i] = R[i] + log(w[i]);\n\n\t\tbench.start();\n\n\t\tfor (long j=0; j < iters; ++j) {\n\t\t\tfor (int i=0; i < length; ++i) {\n\t\t\t\tli[i] = Mu0 * R[i] *\n\t\t\t\t        (0.5 * (1.0 + (1.0/24.0)\n\t\t\t\t                * sqr(w[i]/R[i])) * log(32.0 * sqr(R[i]/w[i]))\n\t\t\t\t         + 0.05 * sqr(w[i]/R[i]) - 0.85);\n\t\t\t}\n\t\t}\n\n\t\tbench.stop();\n\n\t\t// Subtract the loop overhead\n\t\tbench.startOverhead();\n\n\t\tfor (long j=0; j < iters; ++j) {}\n\n\n\n\t\tbench.stopOverhead();\n\n\t\tdelete [] li;\n\t\tdelete [] w;\n\t\tdelete [] R;\n\t}\n\n\tbench.endImplementation();\n}\n\nvoid HaneyFortranVersion(BenchmarkExt<int>& bench)\n{\n\tbench.beginImplementation(\"Fortran\");\n\n\twhile (!bench.doneImplementationBenchmark()) {\n\t\tint length = bench.getParameter();\n\t\tint iters = (int)bench.getIterations();\n\n\t\tcout << \"length = \" << length << \" iters = \" << iters << endl;\n\n\t\tfloat* li = new float[length];\n\t\tfloat* R = new float[length];\n\t\tfloat* w = new float[length];\n\n\t\tinitializeRandom(li, length);\n\t\tinitializeRandom(R, length);\n\t\tinitializeRandom(w, length);\n\n\t\t// Tickle\n\t\tint oneIter = 1;\n\t\tvecopsf(li, R, w, length, oneIter);\n\n\t\t// Time\n\t\tbench.start();\n\t\tvecopsf(li, R, w, length, iters);\n\t\tbench.stop();\n\n\t\t// Time overhead\n\t\tbench.startOverhead();\n\t\tvecopsfo(li, R, w, length, iters);\n\t\tbench.stopOverhead();\n\n\t\tdelete [] li;\n\t\tdelete [] w;\n\t\tdelete [] R;\n\t}\n\n\tbench.endImplementation();\n}\n\nvoid HaneyBlitzVersion(BenchmarkExt<int>& bench)\n{\n\tbench.beginImplementation(\"Blitz++\");\n\n\twhile (!bench.doneImplementationBenchmark()) {\n\t\tint length = bench.getParameter();\n\t\tint iters = (int)bench.getIterations();\n\n\t\tVector<float> li(length), R(length), w(length);\n\t\tinitializeRandom(li.data(), length);\n\t\tinitializeRandom(R.data(), length);\n\t\tinitializeRandom(w.data(), length);\n\n\t\tcout << \"length = \" << length << \" iters = \" << iters << endl;\n\n\t\t// Tickle\n\t\tli = w + log(R);\n\n\t\t// Time\n\t\tbench.start();\n\t\tfor (long i=0; i < iters; ++i) {\n#if defined(__GNUC__) && (__GNUC__ < 3)\n\t\t\tli = Mu0 * R * ( (0.5 + (0.5/24.0) * sqr(w/R) ) \n\t\t\t                 * log(32.0 * sqr(R/w)) + 0.05 * sqr(w/R) - 0.85);\n#else\n\t\t\tli = Mu0 * R * (0.5 * (1.0 + (1.0/24.0) * sqr(w/R))\n\t\t\t                * log(32.0 * sqr(R/w)) + 0.05 * sqr(w/R) - 0.85);\n#endif\n\t\t}\n\t\tbench.stop();\n\n\t\t// Time overhead\n\t\tbench.startOverhead();\n\t\tfor (long i=0; i < iters; ++i) {\n\t\t}\n\t\tbench.stopOverhead();\n\t}\n\n\tbench.endImplementation();\n}\n\n", "meta": {"hexsha": "824393e3141607b245409529aee5d61a513141ac", "size": 4453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/haney.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/haney.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/haney.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": 21.4086538462, "max_line_length": 71, "alphanum_fraction": 0.6222771166, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.5549226704374803}}
{"text": "#include <opencv2/opencv.hpp>\n#include <string>\n#include <chrono>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n\nstring file_1 = \"../LK1.png\";\nstring file_2 = \"../LK2.png\";\n\nclass OpticalFlowTracker {\npublic:\n    OpticalFlowTracker(\n            const Mat &img1_,\n            const Mat &img2_,\n            const vector<KeyPoint> &kp1_,\n            vector<KeyPoint> &kp2_,\n            vector<bool> &success_,\n            bool inverse_ = true, bool has_initial_ = false) :\n            img1(img1_), img2(img2_), kp1(kp1_), kp2(kp2_), success(success_), inverse(inverse_),\n            has_initial(has_initial_) {}\n\n    void calculateOpticalFlow(const Range &range);\n\nprivate:\n    const Mat &img1;\n    const Mat &img2;\n    const vector<KeyPoint> &kp1;\n    vector<KeyPoint> &kp2;\n    vector<bool> &success;\n    bool inverse = true;\n    bool has_initial = false;\n};\n\nvoid OpticalFlowSingleLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false,\n        bool has_initial_guess = false\n);\n\nvoid OpticalFlowMultiLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false\n);\n\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 - 1) x = img.cols - 2;\n    if (y >= img.rows - 1) y = img.rows - 2;\n\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    int x_a1 = std::min(img.cols - 1, int(x) + 1);\n    int y_a1 = std::min(img.rows - 1, int(y) + 1);\n\n    return (1 - xx) * (1 - yy) * img.at<uchar>(y, x)\n           + xx * (1 - yy) * img.at<uchar>(y, x_a1)\n           + (1 - xx) * yy * img.at<uchar>(y_a1, x)\n           + xx * yy * img.at<uchar>(y_a1, x_a1);\n}\n\nint main(int argc, char **argv) {\n\n    // images, note they are CV_8UC1, not CV_8UC3\n    Mat img1 = imread(file_1, 0);\n    Mat img2 = imread(file_2, 0);\n\n    // key points, using GFTT here.\n    vector<KeyPoint> kp1;\n    Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20); // maximum 500 keypoints\n    detector->detect(img1, kp1);\n\n    // now lets track these key points in the second image\n    // first use single level LK in the validation picture\n    vector<KeyPoint> kp2_single;\n    vector<bool> success_single;\n    OpticalFlowSingleLevel(img1, img2, kp1, kp2_single, success_single);\n\n    // then test multi-level LK\n    vector<KeyPoint> kp2_multi;\n    vector<bool> success_multi;\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    OpticalFlowMultiLevel(img1, img2, kp1, kp2_multi, success_multi, true);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by gauss-newton: \" << time_used.count() << endl;\n\n    // use opencv's flow for validation\n    vector<Point2f> pt1, pt2;\n    for (auto &kp: kp1) pt1.push_back(kp.pt);\n    vector<uchar> status;\n    vector<float> error;\n    t1 = chrono::steady_clock::now();\n    cv::calcOpticalFlowPyrLK(img1, img2, pt1, pt2, status, error);\n    t2 = chrono::steady_clock::now();\n    time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by opencv: \" << time_used.count() << endl;\n\n    // plot the differences of those functions\n    Mat img2_single;\n    cv::cvtColor(img2, img2_single, COLOR_GRAY2BGR);\n    for (int i = 0; i < kp2_single.size(); i++) {\n        if (success_single[i]) {\n            cv::circle(img2_single, kp2_single[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_single, kp1[i].pt, kp2_single[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n\n    Mat img2_multi;\n    cv::cvtColor(img2, img2_multi, COLOR_GRAY2BGR);\n    for (int i = 0; i < kp2_multi.size(); i++) {\n        if (success_multi[i]) {\n            cv::circle(img2_multi, kp2_multi[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_multi, kp1[i].pt, kp2_multi[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n\n    Mat img2_CV;\n    cv::cvtColor(img2, img2_CV, COLOR_GRAY2BGR);\n    for (int i = 0; i < pt2.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_CV, pt2[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_CV, pt1[i], pt2[i], cv::Scalar(0, 250, 0));\n        }\n    }\n\n    cv::imshow(\"tracked single level\", img2_single);\n    cv::imshow(\"tracked multi level\", img2_multi);\n    cv::imshow(\"tracked by opencv\", img2_CV);\n    cv::waitKey(0);\n\n    return 0;\n}\n\nvoid OpticalFlowSingleLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse, bool has_initial) {\n    kp2.resize(kp1.size());\n    success.resize(kp1.size());\n    OpticalFlowTracker tracker(img1, img2, kp1, kp2, success, inverse, has_initial);\n    parallel_for_(Range(0, kp1.size()),\n                  std::bind(&OpticalFlowTracker::calculateOpticalFlow, &tracker, placeholders::_1));\n}\n\nvoid OpticalFlowTracker::calculateOpticalFlow(const Range &range) {\n    // parameters\n    int half_patch_size = 4;\n    int iterations = 10;\n    for (size_t i = range.start; i < range.end; i++) {\n        auto kp = kp1[i];\n        double dx = 0, dy = 0; // dx,dy need to be estimated\n        if (has_initial) {\n            dx = kp2[i].pt.x - kp.pt.x;\n            dy = kp2[i].pt.y - kp.pt.y;\n        }\n\n        double cost = 0, lastCost = 0;\n        bool succ = true; // indicate if this point succeeded\n\n        // Gauss-Newton iterations\n        Eigen::Matrix2d H = Eigen::Matrix2d::Zero();    // hessian\n        Eigen::Vector2d b = Eigen::Vector2d::Zero();    // bias\n        Eigen::Vector2d J;  // jacobian\n        for (int iter = 0; iter < iterations; iter++) {\n            if (inverse == false) {\n                H = Eigen::Matrix2d::Zero();\n                b = Eigen::Vector2d::Zero();\n            } else {\n                // only reset b\n                b = Eigen::Vector2d::Zero();\n            }\n\n            cost = 0;\n\n            // compute cost and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)\n                for (int y = -half_patch_size; y < half_patch_size; y++) {\n                    double error = GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y) -\n                                   GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);;  // Jacobian\n                    if (inverse == false) {\n                        J = -1.0 * Eigen::Vector2d(\n                                0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -\n                                       GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),\n                                0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -\n                                       GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1))\n                        );\n                    } else if (iter == 0) {\n                        // in inverse mode, J keeps same for all iterations\n                        // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n                        J = -1.0 * Eigen::Vector2d(\n                                0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -\n                                       GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),\n                                0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -\n                                       GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1))\n                        );\n                    }\n                    // compute H, b and set cost;\n                    b += -error * J;\n                    cost += error * error;\n                    if (inverse == false || iter == 0) {\n                        // also update H\n                        H += J * J.transpose();\n                    }\n                }\n\n            // compute update\n            Eigen::Vector2d update = H.ldlt().solve(b);\n\n            if (std::isnan(update[0])) {\n                // sometimes occurred when we have a black or white patch and H is irreversible\n                cout << \"update is nan\" << endl;\n                succ = false;\n                break;\n            }\n\n            if (iter > 0 && cost > lastCost) {\n                break;\n            }\n\n            // update dx, dy\n            dx += update[0];\n            dy += update[1];\n            lastCost = cost;\n            succ = true;\n\n            if (update.norm() < 1e-2) {\n                // converge\n                break;\n            }\n        }\n\n        success[i] = succ;\n\n        // set kp2\n        kp2[i].pt = kp.pt + Point2f(dx, dy);\n    }\n}\n\nvoid OpticalFlowMultiLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse) {\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    vector<Mat> pyr1, pyr2; // image pyramids\n    for (int i = 0; i < pyramids; i++) {\n        if (i == 0) {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        } else {\n            Mat img1_pyr, img2_pyr;\n            cv::resize(pyr1[i - 1], img1_pyr,\n                       cv::Size(pyr1[i - 1].cols * pyramid_scale, pyr1[i - 1].rows * pyramid_scale));\n            cv::resize(pyr2[i - 1], img2_pyr,\n                       cv::Size(pyr2[i - 1].cols * pyramid_scale, pyr2[i - 1].rows * pyramid_scale));\n            pyr1.push_back(img1_pyr);\n            pyr2.push_back(img2_pyr);\n        }\n    }\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"build pyramid time: \" << time_used.count() << endl;\n\n    // coarse-to-fine LK tracking in pyramids\n    vector<KeyPoint> kp1_pyr, kp2_pyr;\n    for (auto &kp:kp1) {\n        auto kp_top = kp;\n        kp_top.pt *= scales[pyramids - 1];\n        kp1_pyr.push_back(kp_top);\n        kp2_pyr.push_back(kp_top);\n    }\n\n    for (int level = pyramids - 1; level >= 0; level--) {\n        // from coarse to fine\n        success.clear();\n        t1 = chrono::steady_clock::now();\n        OpticalFlowSingleLevel(pyr1[level], pyr2[level], kp1_pyr, kp2_pyr, success, inverse, true);\n        t2 = chrono::steady_clock::now();\n        auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n        cout << \"track pyr \" << level << \" cost time: \" << time_used.count() << endl;\n\n        if (level > 0) {\n            for (auto &kp: kp1_pyr)\n                kp.pt /= pyramid_scale;\n            for (auto &kp: kp2_pyr)\n                kp.pt /= pyramid_scale;\n        }\n    }\n\n    for (auto &kp: kp2_pyr)\n        kp2.push_back(kp);\n}\n\n", "meta": {"hexsha": "70be366e5d679a3c08566c25aca0b3be84f19f66", "size": 11158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MySlambook2/ch8/optical_flow/main.cpp", "max_stars_repo_name": "liuyang9609/SLAMProgramming", "max_stars_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MySlambook2/ch8/optical_flow/main.cpp", "max_issues_repo_name": "liuyang9609/SLAMProgramming", "max_issues_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MySlambook2/ch8/optical_flow/main.cpp", "max_forks_repo_name": "liuyang9609/SLAMProgramming", "max_forks_repo_head_hexsha": "69522f6332e21183e6e0e5c34a9f48c9c580bb43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9780564263, "max_line_length": 120, "alphanum_fraction": 0.5249148593, "num_tokens": 3162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.5548418869068156}}
{"text": "#include <iostream>\n#include <unordered_map>\n\n#include <NTL/ZZ.h>\n\n#include \"RSA.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nvoid usage(char *progname) {\n\tcout << \"This program returns the private exponent `d` of the \"\n\t\t\"public key <n, e2> given the secret key <n, e', d'>.\"\n\t\t<< endl;\n\tcout << \"Usage: \" << progname << \" n e' d' e\" << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 5) { usage(argv[0]); return 3; }\n\n\tZZ n, e1, d1, e2, d2, phi;\n\tn = conv<ZZ>(argv[1]);\n\te1 = conv<ZZ>(argv[2]);\n\td1 = conv<ZZ>(argv[3]);\n\te2 = conv<ZZ>(argv[4]);\n\n\tRSAkey k1 = RSAkey(n, e1, d1);\n\tphi = k1.get_param(\"phi\");\n\n\t// d2 = e2^(-1) (mod phi)\n\tInvMod(d2, e2, phi);\n\n\tRSAkey k2 = RSAkey(n, e2, d2);\n\tcout << k2.get_param(\"d\") << endl;\n}\n", "meta": {"hexsha": "cb53a2d28b4380ebdded4db9a86533885377c66b", "size": 740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common_modulus.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common_modulus.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common_modulus.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5555555556, "max_line_length": 64, "alphanum_fraction": 0.5824324324, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5547324775194626}}
{"text": "// Copyright PinaPL\n//\n// cell.cpp\n// PinaPL\n//\n#include <math.h>\n#include <Eigen/Dense>\n#include <vector>\n#include \"weights.hpp\"\n#include \"cell.hpp\"\n#include \"functions.hpp\"\n\nCell::Cell(Weights* weights) {\n    this->weights = weights;\n    this->reset();\n}\n\nvoid Cell::compute(Eigen::MatrixXd* input) {\n/*    this->forget_gate_out =\n        (this->weights->weight_in_forget_gate * input\n        + this->weights->weight_st_forget_gate * previous_cell_state)\n        .unaryExpr(&sigmoid); */\n    this->inputs.push_back((*input));\n\n    this->input_gate_out.push_back(\n        (this->weights->weight_in_input_gate * (*input)\n        + this->weights->weight_st_input_gate * this->cell_out.back()\n        + this->weights->bias_input_gate).unaryExpr(&sigmoid));\n\n    this->input_block_out.push_back(\n        (this->weights->weight_in_input_block * (*input)\n        + this->weights->weight_st_input_block * this->cell_out.back()\n        + this->weights->bias_input_block).unaryExpr(&tanhyp));\n\n    this->output_gate_out.push_back(\n        (this->weights->weight_in_output_gate * (*input)\n        + this->weights->weight_st_output_gate * this->cell_out.back()\n        + this->weights->bias_output_gate).unaryExpr(&sigmoid));\n\n    this->cell_state.push_back(\n        (this->cell_state.back()\n        + this->input_gate_out.back()\n        .cwiseProduct(this->input_block_out.back())));\n\n    this->cell_out.push_back(\n        this->cell_state.back().unaryExpr(&tanhyp)\n        .cwiseProduct(this->output_gate_out.back()));\n}\n\nEigen::MatrixXd Cell::compute_gate_gradient(Eigen::MatrixXd* deltas, int time) {\n    int output_size = this->weights->output_size;\n    // Computes dy(t)\n    delta_cell_out.push_back(\n        (*deltas)\n        + this->weights->weight_st_input_block * delta_input_block_out.back()\n        + this->weights->weight_st_input_gate * delta_input_gate_out.back()\n//      + this->weights->weight_st_forget_gate * delta_forget_gate_out.back()\n        + this->weights->weight_st_output_gate * delta_output_gate_out.back() );\n\n    // Computes do(t)\n    delta_output_gate_out.push_back(delta_cell_out.back()\n        .cwiseProduct(cell_state.at(time + 1).unaryExpr(&tanhyp))\n        .cwiseProduct(output_gate_out.at(time + 1).cwiseProduct(\n            Eigen::MatrixXd::Ones(output_size, 1)\n            - output_gate_out.at(time + 1))));\n\n    // Computes dc(t)\n    delta_cell_state.push_back(\n        delta_cell_out.back()\n        .cwiseProduct(output_gate_out.at(time + 1))\n        .cwiseProduct(cell_state.at(time + 1).unaryExpr(&tanh_derivative)));\n\n    // Computes di(t)\n    delta_input_gate_out.push_back(\n        delta_cell_state.back()\n        .cwiseProduct(input_block_out.at(time + 1))\n        .cwiseProduct(input_gate_out.at(time + 1).cwiseProduct(\n            Eigen::MatrixXd::Ones(output_size, 1)\n            - input_gate_out.at(time + 1))) );\n\n    // Computes dz(t)\n    delta_input_block_out.push_back(\n        delta_cell_state.back()\n        .cwiseProduct(input_gate_out.at(time + 1))\n        .cwiseProduct(input_block_out.at(time + 1).cwiseProduct(\n            Eigen::MatrixXd::Ones(output_size, 1)\n            - input_block_out.at(time + 1))) );\n\n    // Computes dx(t)\n    Eigen::MatrixXd delta_input =\n    this->weights->weight_in_input_block.transpose()\n      * delta_input_block_out.back()\n    + this->weights->weight_in_input_gate.transpose()\n      * delta_input_gate_out.back()\n//  + this->weights->weight_in_input_block.transpose()\n//    * delta_input_block_out.back()\n    + this->weights->weight_in_output_gate.transpose()\n      * delta_output_gate_out.back();\n\n    return delta_input;\n}\n\nvoid Cell::compute_weight_gradient() {\n    int last_item_index = this->inputs.size() - 1;\n    // Computes dW\n    for (int t = 0; t < last_item_index + 1; ++t) {\n        // Computes dWz\n        this->weights->delta_weight_in_input_block +=\n            delta_input_block_out.at(last_item_index - t + 1)\n            * inputs.at(t).transpose();\n/*\n        std::cout << \"computeWG : \"<< t << std::endl;\n        std::cout << delta_input_gate_out.at(last_item_index - t + 1)\n        << std::endl;\n        std::cout << \" * \" << std::endl;\n        std::cout << inputs.at(t).transpose() << std::endl;\n        std::cout << \" = \" << std::endl;\n        std::cout << delta_input_gate_out.at(last_item_index - t + 1)\n        * inputs.at(t).transpose() << std::endl;\n*/\n        // Computes dWi\n        this->weights->delta_weight_in_input_gate +=\n            delta_input_gate_out.at(last_item_index - t + 1)\n            * inputs.at(t).transpose();\n\n        // Computes dWf\n        /*\n        this->weights->delta_weight_in_input_block +=\n            delta_input_block_out.at(last_item_index - t + 1)\n            * inputs.at(t).transpose(); */\n\n        // Computes dWo\n        this->weights->delta_weight_in_output_gate +=\n            delta_output_gate_out.at(last_item_index - t + 1)\n            * inputs.at(t).transpose();\n    }\n    // Computes dR\n    for (int t = 0; t < last_item_index; ++t) {\n        // Computes dRz\n        this->weights->delta_weight_st_input_block +=\n            delta_input_block_out.at(last_item_index - t)\n            * cell_out.at(t + 1).transpose();\n\n        // Computes dRi\n        this->weights->delta_weight_st_input_gate +=\n            delta_input_gate_out.at(last_item_index - t)\n            * cell_out.at(t + 1).transpose();\n\n        // Computes dRo\n        this->weights->delta_weight_st_output_gate +=\n            delta_output_gate_out.at(last_item_index - t)\n            * cell_out.at(t + 1).transpose();\n    }\n    // Computes dB\n    for (int t = 0; t < last_item_index + 1; ++t) {\n        // Computes dBz\n        this->weights->delta_bias_input_block +=\n            delta_input_block_out.at(last_item_index - t + 1);\n        // Computes dBi\n        this->weights->delta_bias_input_gate +=\n            delta_input_gate_out.at(last_item_index - t + 1);\n        // Computes dBo\n        this->weights->delta_bias_output_gate +=\n            delta_output_gate_out.at(last_item_index - t + 1);\n    }\n}\n\nvoid Cell::update_weights(double lambda) {\n    this->weights->apply_gradient(lambda);\n}\n\nvoid Cell::reset() {\n    int output_size = this->weights->output_size;\n\n    this->inputs.clear();\n    this->input_gate_out.clear();\n    this->input_block_out.clear();\n    this->output_gate_out.clear();\n    this->cell_state.clear();\n    this->cell_out.clear();\n\n    this->delta_cell_out.clear();\n    this->delta_output_gate_out.clear();\n    this->delta_cell_state.clear();\n    this->delta_input_gate_out.clear();\n    this->delta_input_block_out.clear();\n\n    this->input_gate_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->input_block_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->output_gate_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->cell_state.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->cell_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n\n    this->delta_cell_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->delta_output_gate_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->delta_cell_state.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->delta_input_gate_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n    this->delta_input_block_out.push_back(\n        Eigen::MatrixXd::Zero(output_size, 1));\n}\n", "meta": {"hexsha": "9dc60bd9907a492a1dcdec03fefa1f3208feafb8", "size": 7430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cell.cpp", "max_stars_repo_name": "supelec-lstm/PinaPL_lstm", "max_stars_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell.cpp", "max_issues_repo_name": "supelec-lstm/PinaPL_lstm", "max_issues_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell.cpp", "max_forks_repo_name": "supelec-lstm/PinaPL_lstm", "max_forks_repo_head_hexsha": "96462ed2f8f880ccfc33424eb6a273522b90b049", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.380952381, "max_line_length": 80, "alphanum_fraction": 0.636204576, "num_tokens": 1838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5547143301601835}}
{"text": "// boost\\math\\distributions\\binomial.hpp\r\n\r\n// Copyright John Maddock 2006.\r\n// Copyright Paul A. Bristow 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// http://en.wikipedia.org/wiki/binomial_distribution\r\n\r\n// Binomial distribution is the discrete probability distribution of\r\n// the number (k) of successes, in a sequence of\r\n// n independent (yes or no, success or failure) Bernoulli trials.\r\n\r\n// It expresses the probability of a number of events occurring in a fixed time\r\n// if these events occur with a known average rate (probability of success),\r\n// and are independent of the time since the last event.\r\n\r\n// The number of cars that pass through a certain point on a road during a given period of time.\r\n// The number of spelling mistakes a secretary makes while typing a single page.\r\n// The number of phone calls at a call center per minute.\r\n// The number of times a web server is accessed per minute.\r\n// The number of light bulbs that burn out in a certain amount of time.\r\n// The number of roadkill found per unit length of road\r\n\r\n// http://en.wikipedia.org/wiki/binomial_distribution\r\n\r\n// Given a sample of N measured values k[i],\r\n// we wish to estimate the value of the parameter x (mean)\r\n// of the binomial population from which the sample was drawn.\r\n// To calculate the maximum likelihood value = 1/N sum i = 1 to N of k[i]\r\n\r\n// Also may want a function for EXACTLY k.\r\n\r\n// And probability that there are EXACTLY k occurrences is\r\n// exp(-x) * pow(x, k) / factorial(k)\r\n// where x is expected occurrences (mean) during the given interval.\r\n// For example, if events occur, on average, every 4 min,\r\n// and we are interested in number of events occurring in 10 min,\r\n// then x = 10/4 = 2.5\r\n\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366i.htm\r\n\r\n// The binomial distribution is used when there are\r\n// exactly two mutually exclusive outcomes of a trial.\r\n// These outcomes are appropriately labeled \"success\" and \"failure\".\r\n// The binomial distribution is used to obtain\r\n// the probability of observing x successes in N trials,\r\n// with the probability of success on a single trial denoted by p.\r\n// The binomial distribution assumes that p is fixed for all trials.\r\n\r\n// P(x, p, n) = n!/(x! * (n-x)!) * p^x * (1-p)^(n-x)\r\n\r\n// http://mathworld.wolfram.com/BinomialCoefficient.html\r\n\r\n// The binomial coefficient (n; k) is the number of ways of picking\r\n// k unordered outcomes from n possibilities,\r\n// also known as a combination or combinatorial number.\r\n// The symbols _nC_k and (n; k) are used to denote a binomial coefficient,\r\n// and are sometimes read as \"n choose k.\"\r\n// (n; k) therefore gives the number of k-subsets  possible out of a set of n distinct items.\r\n\r\n// For example:\r\n//  The 2-subsets of {1,2,3,4} are the six pairs {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, and {3,4}, so (4; 2)==6.\r\n\r\n// http://functions.wolfram.com/GammaBetaErf/Binomial/ for evaluation.\r\n\r\n// But note that the binomial distribution\r\n// (like others including the poisson, negative binomial & Bernoulli)\r\n// is strictly defined as a discrete function: only integral values of k are envisaged.\r\n// However because of the method of calculation using a continuous gamma function,\r\n// it is convenient to treat it as if a continous function,\r\n// and permit non-integral values of k.\r\n// To enforce the strict mathematical model, users should use floor or ceil functions\r\n// on k outside this function to ensure that k is integral.\r\n\r\n#ifndef BOOST_MATH_SPECIAL_BINOMIAL_HPP\r\n#define BOOST_MATH_SPECIAL_BINOMIAL_HPP\r\n\r\n#include <boost/math/distributions/fwd.hpp>\r\n#include <boost/math/special_functions/beta.hpp> // for incomplete 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/distributions/detail/inv_discrete_quantile.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#include <utility>\r\n\r\nnamespace boost\r\n{\r\n  namespace math\r\n  {\r\n\r\n     template <class RealType, class Policy>\r\n     class binomial_distribution;\r\n\r\n     namespace binomial_detail{\r\n        // common error checking routines for binomial distribution functions:\r\n        template <class RealType, class Policy>\r\n        inline bool check_N(const char* function, const RealType& N, RealType* result, const Policy& pol)\r\n        {\r\n           if((N < 0) || !(boost::math::isfinite)(N))\r\n           {\r\n               *result = policies::raise_domain_error<RealType>(\r\n                  function,\r\n                  \"Number of Trials argument is %1%, but must be >= 0 !\", N, pol);\r\n               return false;\r\n           }\r\n           return true;\r\n        }\r\n        template <class RealType, class Policy>\r\n        inline bool check_success_fraction(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                  \"Success fraction argument is %1%, but must be >= 0 and <= 1 !\", p, pol);\r\n               return false;\r\n           }\r\n           return true;\r\n        }\r\n        template <class RealType, class Policy>\r\n        inline bool check_dist(const char* function, const RealType& N, const RealType& p, RealType* result, const Policy& pol)\r\n        {\r\n           return check_success_fraction(\r\n              function, p, result, pol)\r\n              && check_N(\r\n               function, N, result, pol);\r\n        }\r\n        template <class RealType, class Policy>\r\n        inline bool check_dist_and_k(const char* function, const RealType& N, const RealType& p, RealType k, RealType* result, const Policy& pol)\r\n        {\r\n           if(check_dist(function, N, p, result, pol) == false)\r\n              return false;\r\n           if((k < 0) || !(boost::math::isfinite)(k))\r\n           {\r\n               *result = policies::raise_domain_error<RealType>(\r\n                  function,\r\n                  \"Number of Successes argument is %1%, but must be >= 0 !\", k, pol);\r\n               return false;\r\n           }\r\n           if(k > N)\r\n           {\r\n               *result = policies::raise_domain_error<RealType>(\r\n                  function,\r\n                  \"Number of Successes argument is %1%, but must be <= Number of Trials !\", k, pol);\r\n               return false;\r\n           }\r\n           return true;\r\n        }\r\n        template <class RealType, class Policy>\r\n        inline bool check_dist_and_prob(const char* function, const RealType& N, RealType p, RealType prob, RealType* result, const Policy& pol)\r\n        {\r\n           if(check_dist(function, N, p, result, pol) && detail::check_probability(function, prob, result, pol) == false)\r\n              return false;\r\n           return true;\r\n        }\r\n\r\n         template <class T, class Policy>\r\n         T inverse_binomial_cornish_fisher(T n, T sf, T p, T q, const Policy& pol)\r\n         {\r\n            BOOST_MATH_STD_USING\r\n            // mean:\r\n            T m = n * sf;\r\n            // standard deviation:\r\n            T sigma = sqrt(n * sf * (1 - sf));\r\n            // skewness\r\n            T sk = (1 - 2 * sf) / sigma;\r\n            // kurtosis:\r\n            // T k = (1 - 6 * sf * (1 - sf) ) / (n * sf * (1 - sf));\r\n            // Get the inverse of a std normal distribution:\r\n            T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();\r\n            // Set the sign:\r\n            if(p < 0.5)\r\n               x = -x;\r\n            T x2 = x * x;\r\n            // w is correction term due to skewness\r\n            T w = x + sk * (x2 - 1) / 6;\r\n            /*\r\n            // Add on correction due to kurtosis.\r\n            // Disabled for now, seems to make things worse?\r\n            //\r\n            if(n >= 10)\r\n               w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;\r\n               */\r\n            w = m + sigma * w;\r\n            if(w < tools::min_value<T>())\r\n               return sqrt(tools::min_value<T>());\r\n            if(w > n)\r\n               return n;\r\n            return w;\r\n         }\r\n\r\n      template <class RealType, class Policy>\r\n      RealType quantile_imp(const binomial_distribution<RealType, Policy>& dist, const RealType& p, const RealType& q)\r\n      { // Quantile or Percent Point Binomial function.\r\n        // Return the number of expected successes k,\r\n        // for a given probability p.\r\n        //\r\n        // Error checks:\r\n        BOOST_MATH_STD_USING  // ADL of std names\r\n        RealType result;\r\n        RealType trials = dist.trials();\r\n        RealType success_fraction = dist.success_fraction();\r\n        if(false == binomial_detail::check_dist_and_prob(\r\n           \"boost::math::quantile(binomial_distribution<%1%> const&, %1%)\",\r\n           trials,\r\n           success_fraction,\r\n           p,\r\n           &result, Policy()))\r\n        {\r\n           return result;\r\n        }\r\n\r\n        // Special cases:\r\n        //\r\n        if(p == 0)\r\n        {  // There may actually be no answer to this question,\r\n           // since the probability of zero successes may be non-zero,\r\n           // but zero is the best we can do:\r\n           return 0;\r\n        }\r\n        if(p == 1)\r\n        {  // Probability of n or fewer successes is always one,\r\n           // so n is the most sensible answer here:\r\n           return trials;\r\n        }\r\n        if (p <= pow(1 - success_fraction, trials))\r\n        { // p <= pdf(dist, 0) == cdf(dist, 0)\r\n          return 0; // So the only reasonable result is zero.\r\n        } // And root finder would fail otherwise.\r\n\r\n        // Solve for quantile numerically:\r\n        //\r\n        RealType guess = binomial_detail::inverse_binomial_cornish_fisher(trials, success_fraction, p, q, Policy());\r\n        RealType factor = 8;\r\n        if(trials > 100)\r\n           factor = 1.01f; // guess is pretty accurate\r\n        else if((trials > 10) && (trials - 1 > guess) && (guess > 3))\r\n           factor = 1.15f; // less accurate but OK.\r\n        else if(trials < 10)\r\n        {\r\n           // pretty inaccurate guess in this area:\r\n           if(guess > trials / 64)\r\n           {\r\n              guess = trials / 4;\r\n              factor = 2;\r\n           }\r\n           else\r\n              guess = trials / 1024;\r\n        }\r\n        else\r\n           factor = 2; // trials largish, but in far tails.\r\n\r\n        typedef typename Policy::discrete_quantile_type discrete_quantile_type;\r\n        boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\r\n        return detail::inverse_discrete_quantile(\r\n            dist,\r\n            p,\r\n            q,\r\n            guess,\r\n            factor,\r\n            RealType(1),\r\n            discrete_quantile_type(),\r\n            max_iter);\r\n      } // quantile\r\n\r\n     }\r\n\r\n    template <class RealType = double, class Policy = policies::policy<> >\r\n    class binomial_distribution\r\n    {\r\n    public:\r\n      typedef RealType value_type;\r\n      typedef Policy policy_type;\r\n\r\n      binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)\r\n      { // Default n = 1 is the Bernoulli distribution\r\n        // with equal probability of 'heads' or 'tails.\r\n         RealType r;\r\n         binomial_detail::check_dist(\r\n            \"boost::math::binomial_distribution<%1%>::binomial_distribution\",\r\n            m_n,\r\n            m_p,\r\n            &r, Policy());\r\n      } // binomial_distribution constructor.\r\n\r\n      RealType success_fraction() const\r\n      { // Probability.\r\n        return m_p;\r\n      }\r\n      RealType trials() const\r\n      { // Total number of trials.\r\n        return m_n;\r\n      }\r\n\r\n      enum interval_type{\r\n         clopper_pearson_exact_interval,\r\n         jeffreys_prior_interval\r\n      };\r\n\r\n      //\r\n      // Estimation of the success fraction parameter.\r\n      // The best estimate is actually simply successes/trials,\r\n      // these functions are used\r\n      // to obtain confidence intervals for the success fraction.\r\n      //\r\n      static RealType find_lower_bound_on_p(\r\n         RealType trials,\r\n         RealType successes,\r\n         RealType probability,\r\n         interval_type t = clopper_pearson_exact_interval)\r\n      {\r\n        static const char* function = \"boost::math::binomial_distribution<%1%>::find_lower_bound_on_p\";\r\n        // Error checks:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           function, trials, RealType(0), successes, &result, Policy())\r\n            &&\r\n           binomial_detail::check_dist_and_prob(\r\n           function, trials, RealType(0), probability, &result, Policy()))\r\n        { return result; }\r\n\r\n        if(successes == 0)\r\n           return 0;\r\n\r\n        // NOTE!!! The Clopper Pearson formula uses \"successes\" not\r\n        // \"successes+1\" as usual to get the lower bound,\r\n        // see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm\r\n        return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(0), Policy())\r\n           : ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(0), Policy());\r\n      }\r\n      static RealType find_upper_bound_on_p(\r\n         RealType trials,\r\n         RealType successes,\r\n         RealType probability,\r\n         interval_type t = clopper_pearson_exact_interval)\r\n      {\r\n        static const char* function = \"boost::math::binomial_distribution<%1%>::find_upper_bound_on_p\";\r\n        // Error checks:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           function, trials, RealType(0), successes, &result, Policy())\r\n            &&\r\n           binomial_detail::check_dist_and_prob(\r\n           function, trials, RealType(0), probability, &result, Policy()))\r\n        { return result; }\r\n\r\n        if(trials == successes)\r\n           return 1;\r\n\r\n        return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(0), Policy())\r\n           : ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(0), Policy());\r\n      }\r\n      // Estimate number of trials parameter:\r\n      //\r\n      // \"How many trials do I need to be P% sure of seeing k events?\"\r\n      //    or\r\n      // \"How many trials can I have to be P% sure of seeing fewer than k events?\"\r\n      //\r\n      static RealType find_minimum_number_of_trials(\r\n         RealType k,     // number of events\r\n         RealType p,     // success fraction\r\n         RealType alpha) // risk level\r\n      {\r\n        static const char* function = \"boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials\";\r\n        // Error checks:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           function, k, p, k, &result, Policy())\r\n            &&\r\n           binomial_detail::check_dist_and_prob(\r\n           function, k, p, alpha, &result, Policy()))\r\n        { return result; }\r\n\r\n        result = ibetac_invb(k + 1, p, alpha, Policy());  // returns n - k\r\n        return result + k;\r\n      }\r\n\r\n      static RealType find_maximum_number_of_trials(\r\n         RealType k,     // number of events\r\n         RealType p,     // success fraction\r\n         RealType alpha) // risk level\r\n      {\r\n        static const char* function = \"boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials\";\r\n        // Error checks:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           function, k, p, k, &result, Policy())\r\n            &&\r\n           binomial_detail::check_dist_and_prob(\r\n           function, k, p, alpha, &result, Policy()))\r\n        { return result; }\r\n\r\n        result = ibeta_invb(k + 1, p, alpha, Policy());  // returns n - k\r\n        return result + k;\r\n      }\r\n\r\n    private:\r\n        RealType m_n; // Not sure if this shouldn't be an int?\r\n        RealType m_p; // success_fraction\r\n      }; // template <class RealType, class Policy> class binomial_distribution\r\n\r\n      typedef binomial_distribution<> binomial;\r\n      // typedef binomial_distribution<double> binomial;\r\n      // IS now included since no longer a name clash with function binomial.\r\n      //typedef binomial_distribution<double> binomial; // Reserved name of type double.\r\n\r\n      template <class RealType, class Policy>\r\n      const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)\r\n      { // Range of permissible values for random variable k.\r\n        using boost::math::tools::max_value;\r\n        return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)\r\n      { // Range of supported values for random variable k.\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>(0,  dist.trials());\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType mean(const binomial_distribution<RealType, Policy>& dist)\r\n      { // Mean of Binomial distribution = np.\r\n        return  dist.trials() * dist.success_fraction();\r\n      } // mean\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType variance(const binomial_distribution<RealType, Policy>& dist)\r\n      { // Variance of Binomial distribution = np(1-p).\r\n        return  dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());\r\n      } // variance\r\n\r\n      template <class RealType, class Policy>\r\n      RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)\r\n      { // Probability Density/Mass Function.\r\n        BOOST_FPU_EXCEPTION_GUARD\r\n\r\n        BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n        RealType n = dist.trials();\r\n\r\n        // Error check:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           \"boost::math::pdf(binomial_distribution<%1%> const&, %1%)\",\r\n           n,\r\n           dist.success_fraction(),\r\n           k,\r\n           &result, Policy()))\r\n        {\r\n           return result;\r\n        }\r\n\r\n        // Special cases of success_fraction, regardless of k successes and regardless of n trials.\r\n        if (dist.success_fraction() == 0)\r\n        {  // probability of zero successes is 1:\r\n           return static_cast<RealType>(k == 0 ? 1 : 0);\r\n        }\r\n        if (dist.success_fraction() == 1)\r\n        {  // probability of n successes is 1:\r\n           return static_cast<RealType>(k == n ? 1 : 0);\r\n        }\r\n        // k argument may be integral, signed, or unsigned, or floating point.\r\n        // If necessary, it has already been promoted from an integral type.\r\n        if (n == 0)\r\n        {\r\n          return 1; // Probability = 1 = certainty.\r\n        }\r\n        if (k == 0)\r\n        { // binomial coeffic (n 0) = 1,\r\n          // n ^ 0 = 1\r\n          return pow(1 - dist.success_fraction(), n);\r\n        }\r\n        if (k == n)\r\n        { // binomial coeffic (n n) = 1,\r\n          // n ^ 0 = 1\r\n          return pow(dist.success_fraction(), k);  // * pow((1 - dist.success_fraction()), (n - k)) = 1\r\n        }\r\n\r\n        // Probability of getting exactly k successes\r\n        // if C(n, k) is the binomial coefficient then:\r\n        //\r\n        // f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)\r\n        //           = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)\r\n        //           = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)\r\n        //           = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))\r\n        //           = ibeta_derivative(k+1, n-k+1, p) / (n+1)\r\n        //\r\n        using boost::math::ibeta_derivative; // a, b, x\r\n        return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);\r\n\r\n      } // pdf\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)\r\n      { // Cumulative Distribution Function Binomial.\r\n        // The random variate k is the number of successes in n trials.\r\n        // k argument may be integral, signed, or unsigned, or floating point.\r\n        // If necessary, it has already been promoted from an integral type.\r\n\r\n        // Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:\r\n        //\r\n        //   i=k\r\n        //   --  ( n )   i      n-i\r\n        //   >   |   |  p  (1-p)\r\n        //   --  ( i )\r\n        //   i=0\r\n\r\n        // The terms are not summed directly instead\r\n        // the incomplete beta integral is employed,\r\n        // according to the formula:\r\n        // P = I[1-p]( n-k, k+1).\r\n        //   = 1 - I[p](k + 1, n - k)\r\n\r\n        BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n        RealType n = dist.trials();\r\n        RealType p = dist.success_fraction();\r\n\r\n        // Error check:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           \"boost::math::cdf(binomial_distribution<%1%> const&, %1%)\",\r\n           n,\r\n           p,\r\n           k,\r\n           &result, Policy()))\r\n        {\r\n           return result;\r\n        }\r\n        if (k == n)\r\n        {\r\n          return 1;\r\n        }\r\n\r\n        // Special cases, regardless of k.\r\n        if (p == 0)\r\n        {  // This need explanation:\r\n           // the pdf is zero for all cases except when k == 0.\r\n           // For zero p the probability of zero successes is one.\r\n           // Therefore the cdf is always 1:\r\n           // the probability of k or *fewer* successes is always 1\r\n           // if there are never any successes!\r\n           return 1;\r\n        }\r\n        if (p == 1)\r\n        { // This is correct but needs explanation:\r\n          // when k = 1\r\n          // all the cdf and pdf values are zero *except* when k == n,\r\n          // and that case has been handled above already.\r\n          return 0;\r\n        }\r\n        //\r\n        // P = I[1-p](n - k, k + 1)\r\n        //   = 1 - I[p](k + 1, n - k)\r\n        // Use of ibetac here prevents cancellation errors in calculating\r\n        // 1-p if p is very small, perhaps smaller than machine epsilon.\r\n        //\r\n        // Note that we do not use a finite sum here, since the incomplete\r\n        // beta uses a finite sum internally for integer arguments, so\r\n        // we'll just let it take care of the necessary logic.\r\n        //\r\n        return ibetac(k + 1, n - k, p, Policy());\r\n      } // binomial cdf\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)\r\n      { // Complemented Cumulative Distribution Function Binomial.\r\n        // The random variate k is the number of successes in n trials.\r\n        // k argument may be integral, signed, or unsigned, or floating point.\r\n        // If necessary, it has already been promoted from an integral type.\r\n\r\n        // Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:\r\n        //\r\n        //   i=n\r\n        //   --  ( n )   i      n-i\r\n        //   >   |   |  p  (1-p)\r\n        //   --  ( i )\r\n        //   i=k+1\r\n\r\n        // The terms are not summed directly instead\r\n        // the incomplete beta integral is employed,\r\n        // according to the formula:\r\n        // Q = 1 -I[1-p]( n-k, k+1).\r\n        //   = I[p](k + 1, n - k)\r\n\r\n        BOOST_MATH_STD_USING // for ADL of std functions\r\n\r\n        RealType const& k = c.param;\r\n        binomial_distribution<RealType, Policy> const& dist = c.dist;\r\n        RealType n = dist.trials();\r\n        RealType p = dist.success_fraction();\r\n\r\n        // Error checks:\r\n        RealType result;\r\n        if(false == binomial_detail::check_dist_and_k(\r\n           \"boost::math::cdf(binomial_distribution<%1%> const&, %1%)\",\r\n           n,\r\n           p,\r\n           k,\r\n           &result, Policy()))\r\n        {\r\n           return result;\r\n        }\r\n\r\n        if (k == n)\r\n        { // Probability of greater than n successes is necessarily zero:\r\n          return 0;\r\n        }\r\n\r\n        // Special cases, regardless of k.\r\n        if (p == 0)\r\n        {\r\n           // This need explanation: the pdf is zero for all\r\n           // cases except when k == 0.  For zero p the probability\r\n           // of zero successes is one.  Therefore the cdf is always\r\n           // 1: the probability of *more than* k successes is always 0\r\n           // if there are never any successes!\r\n           return 0;\r\n        }\r\n        if (p == 1)\r\n        {\r\n          // This needs explanation, when p = 1\r\n          // we always have n successes, so the probability\r\n          // of more than k successes is 1 as long as k < n.\r\n          // The k == n case has already been handled above.\r\n          return 1;\r\n        }\r\n        //\r\n        // Calculate cdf binomial using the incomplete beta function.\r\n        // Q = 1 -I[1-p](n - k, k + 1)\r\n        //   = I[p](k + 1, n - k)\r\n        // Use of ibeta here prevents cancellation errors in calculating\r\n        // 1-p if p is very small, perhaps smaller than machine epsilon.\r\n        //\r\n        // Note that we do not use a finite sum here, since the incomplete\r\n        // beta uses a finite sum internally for integer arguments, so\r\n        // we'll just let it take care of the necessary logic.\r\n        //\r\n        return ibeta(k + 1, n - k, p, Policy());\r\n      } // binomial cdf\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)\r\n      {\r\n         return binomial_detail::quantile_imp(dist, p, RealType(1-p));\r\n      } // quantile\r\n\r\n      template <class RealType, class Policy>\r\n      RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)\r\n      {\r\n         return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param);\r\n      } // quantile\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType mode(const binomial_distribution<RealType, Policy>& dist)\r\n      {\r\n         BOOST_MATH_STD_USING // ADL of std functions.\r\n         RealType p = dist.success_fraction();\r\n         RealType n = dist.trials();\r\n         return floor(p * (n + 1));\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType median(const binomial_distribution<RealType, Policy>& dist)\r\n      { // Bounds for the median of the negative binomial distribution\r\n        // VAN DE VEN R. ; WEBER N. C. ;\r\n        // Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE\r\n        // Metrika  (Metrika)  ISSN 0026-1335   CODEN MTRKA8\r\n        // 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)\r\n\r\n        // Bounds for median and 50 percetage point of binomial and negative binomial distribution\r\n        // Metrika, ISSN   0026-1335 (Print) 1435-926X (Online)\r\n        // Volume 41, Number 1 / December, 1994, DOI   10.1007/BF01895303\r\n         BOOST_MATH_STD_USING // ADL of std functions.\r\n         RealType p = dist.success_fraction();\r\n         RealType n = dist.trials();\r\n         // Wikipedia says one of floor(np) -1, floor (np), floor(np) +1\r\n         return floor(p * n); // Chose the middle value.\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)\r\n      {\r\n         BOOST_MATH_STD_USING // ADL of std functions.\r\n         RealType p = dist.success_fraction();\r\n         RealType n = dist.trials();\r\n         return (1 - 2 * p) / sqrt(n * p * (1 - p));\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)\r\n      {\r\n         RealType p = dist.success_fraction();\r\n         RealType n = dist.trials();\r\n         return 3 - 6 / n + 1 / (n * p * (1 - p));\r\n      }\r\n\r\n      template <class RealType, class Policy>\r\n      inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)\r\n      {\r\n         RealType p = dist.success_fraction();\r\n         RealType q = 1 - p;\r\n         RealType n = dist.trials();\r\n         return (1 - 6 * p * q) / (n * p * q);\r\n      }\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#endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP\r\n\r\n\r\n", "meta": {"hexsha": "4b1dee01db10c3f332b23fd7b823312248bbb4ee", "size": 29094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/distributions/binomial.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/distributions/binomial.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LibsExternes/Includes/boost/math/distributions/binomial.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1296551724, "max_line_length": 151, "alphanum_fraction": 0.5724548017, "num_tokens": 6954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.5546424216836519}}
{"text": "#include \"gru_cell.hpp\"\n#include \"generic/activity.hpp\"\n#include \"generic/utils.hpp\"\n#include <Eigen/SVD>\n\nnamespace rnn {\ngru_cell::gru_cell(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::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}\nvoid gru_cell::forward(const VecD &xt, const gru_cell::State *prev, gru_cell::State *cur) {\n\n  cur->r = this->br + this->Wxr * xt + this->Whr * prev->h;\n  cur->z = this->bz + this->Wxz * xt + this->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 = this->bu + this->Wxu * xt + this->Whu * cur->rh;\n  activity::tanh(cur->u);\n  cur->h = (1.0 - cur->z.array()) * prev->h.array() +\n      cur->z.array() * cur->u.array();\n}\n\nvoid gru_cell::backward(gru_cell::State *prev, gru_cell::State *cur, gru_cell::Grad &grad,\n                        const VecD &xt) {\n  VecD delr, delz, delu, delrh;\n\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 = this->Whu.transpose() * delu;\n  delr =\n      activity::logisticPrime(cur->r).array() * delrh.array() * prev->h.array();\n\n  cur->delx =\n      this->Wxr.transpose() * delr +\n          this->Wxz.transpose() * delz +\n          this->Wxu.transpose() * delu;\n\n  prev->delh.noalias() +=\n      this->Whr.transpose() * delr +\n          this->Whz.transpose() * delz;\n  prev->delh.array() +=\n      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::sgd(const gru_cell::Grad &grad, const real learningRate) {\n  this->Wxr -= learningRate * grad.Wxr;\n  this->Whr -= learningRate * grad.Whr;\n  this->br -= learningRate * grad.br;\n\n  this->Wxz -= learningRate * grad.Wxz;\n  this->Whz -= learningRate * grad.Whz;\n  this->bz -= learningRate * grad.bz;\n\n  this->Wxu -= learningRate * grad.Wxu;\n  this->Whu -= learningRate * grad.Whu;\n  this->bu -= learningRate * grad.bu;\n}\n\nvoid gru_cell::save(std::ofstream &ofs) {\n  rnn::generic::save(ofs, this->Wxr);\n  rnn::generic::save(ofs, this->Whr);\n  rnn::generic::save(ofs, this->br);\n  rnn::generic::save(ofs, this->Wxz);\n  rnn::generic::save(ofs, this->Whz);\n  rnn::generic::save(ofs, this->bz);\n  rnn::generic::save(ofs, this->Wxu);\n  rnn::generic::save(ofs, this->Whu);\n  rnn::generic::save(ofs, this->bu);\n}\n\nvoid gru_cell::load(std::ifstream &ifs) {\n  rnn::generic::load(ifs, this->Wxr);\n  rnn::generic::load(ifs, this->Whr);\n  rnn::generic::load(ifs, this->br);\n  rnn::generic::load(ifs, this->Wxz);\n  rnn::generic::load(ifs, this->Whz);\n  rnn::generic::load(ifs, this->bz);\n  rnn::generic::load(ifs, this->Wxu);\n  rnn::generic::load(ifs, this->Whu);\n  rnn::generic::load(ifs, this->bu);\n}\n\nvoid gru_cell::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::Grad::Grad(const gru_cell &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::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::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::Grad::operator+=(const gru_cell::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": "a2a89887a5f0672a084920664bffe80846972685", "size": 5597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RNN/rnn/gru_cell.cpp", "max_stars_repo_name": "suiyili/ANN", "max_stars_repo_head_hexsha": "4c5ce41ae6e4a657f40a88ca1e1e3c7cbaaf46d5", "max_stars_repo_licenses": ["MIT"], "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/rnn/gru_cell.cpp", "max_issues_repo_name": "suiyili/ANN", "max_issues_repo_head_hexsha": "4c5ce41ae6e4a657f40a88ca1e1e3c7cbaaf46d5", "max_issues_repo_licenses": ["MIT"], "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/rnn/gru_cell.cpp", "max_forks_repo_name": "suiyili/ANN", "max_forks_repo_head_hexsha": "4c5ce41ae6e4a657f40a88ca1e1e3c7cbaaf46d5", "max_forks_repo_licenses": ["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.0913978495, "max_line_length": 91, "alphanum_fraction": 0.6094336252, "num_tokens": 1890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.554597278121851}}
{"text": "#ifndef APP_ND_GRID_SIMPLEX\n#define APP_ND_GRID_SIMPLEX\n\n#include \"Point.hpp\"\n#include \"Triangulator.hpp\"\n\n#include <stdlib.h>\n#include <boost/numeric/ublas/matrix.hpp> \n#include <boost/numeric/ublas/io.hpp> \n#include <boost/numeric/ublas/matrix_proxy.hpp> \n#include <boost/numeric/ublas/lu.hpp> \n\nclass Simplex {\npublic:\n    Triangulator& triangulator;\n    unsigned int num_dimensions;\n    std::vector<Point> points;\n    std::vector<Point> lines;\n\n    Simplex(unsigned int num_dims, std::vector<std::vector<double>>& _points, Triangulator& _triangulator):\n    num_dimensions(num_dims),\n    points(_points.size()),\n    lines(0),\n    triangulator(_triangulator) {\n        for (unsigned int i=0; i<_points.size(); i++) {\n            points[i] = Point(_points[i]);\n        }\n\n        lines = generateLines();\n    }\n\n    Simplex(unsigned int num_dims, std::vector<Point> _points, Triangulator& _triangulator):\n    num_dimensions(num_dims),\n    points(_points),\n    lines(0),\n    triangulator(_triangulator) {\n\n        lines = generateLines();\n    }\n\n    Simplex(const Simplex& other) :\n    num_dimensions(other.num_dimensions),\n    triangulator(other.triangulator) {\n        points = std::vector<Point>(other.points.size());\n        for(unsigned int i=0; i<other.points.size(); i++) {\n            points[i] = other.points[i];\n        }\n\n        lines = std::vector<Point>(other.lines.size());\n        for(unsigned int i=0; i<other.lines.size(); i++) {\n            lines[i] = other.lines[i];\n        }\n    }\n\n    Simplex& operator=(const Simplex &other) {\n        num_dimensions = other.num_dimensions;\n        triangulator = other.triangulator;\n        points = std::vector<Point>(other.points.size());\n        for(unsigned int i=0; i<other.points.size(); i++) {\n            points[i] = other.points[i];\n        }\n\n        lines = std::vector<Point>(other.lines.size());\n        for(unsigned int i=0; i<other.lines.size(); i++) {\n            lines[i] = other.lines[i];\n        }\n\n        return *this;\n    }\n\n    std::vector<Point> generateLines() {\n        std::vector<Point> lines(num_dimensions);\n        for(unsigned int p=0; p<points.size()-1; p++) {\n            std::vector<double> coords(num_dimensions);\n            for (unsigned int c=0; c<num_dimensions; c++)\n                coords[c] = points[p+1].coords[c] - points[0].coords[c];\n            lines[p] = Point(coords);\n        }\n        return lines;\n    }\n\n    // CalcDeterminant by Richel Bilderbeek : http://www.richelbilderbeek.nl/CppUblasMatrixExample7.htm\n    double CalcDeterminant(boost::numeric::ublas::matrix<double> m) \n    { \n        assert(m.size1() == m.size2() && \"Can only calculate the determinant of square matrices\"); \n        boost::numeric::ublas::permutation_matrix<std::size_t> pivots(m.size1() ); \n\n        const int is_singular = boost::numeric::ublas::lu_factorize(m, pivots); \n\n        if (is_singular) return 0.0; \n\n        double d = 1.0; \n        const std::size_t sz = pivots.size(); \n        for (std::size_t i=0; i != sz; ++i) \n        { \n            if (pivots(i) != i) \n            { \n            d *= -1.0; \n            } \n            d *= m(i,i); \n        } \n        return d; \n    } \n\n    double getVolume() {\n        boost::numeric::ublas::matrix<double> m(num_dimensions,num_dimensions);\n        for (unsigned int l=0; l<num_dimensions; l++) {\n            for(unsigned int c=0; c<num_dimensions; c++) {\n                m(l,c) = lines[l].coords[c];\n            }\n        }\n\n        unsigned int dim_fac = 0;\n        for(unsigned int n=0; n<num_dimensions; n++)\n            dim_fac += n;\n\n        return std::abs(CalcDeterminant(m)/dim_fac)/2;\n    }\n\n    std::vector<std::vector<Simplex>> intersectWithHyperplane(unsigned int dim_index, double dim) {\n        double eps = 0.00000000001;\n\n        std::vector<Point*> lower;\n        std::vector<Point*> upper;\n        std::vector<Point*> equal;\n        for (unsigned int i=0; i<points.size(); i++) {\n            if(points[i].coords[dim_index] < dim - eps) lower.push_back(&points[i]);\n            else if(points[i].coords[dim_index] > dim + eps) upper.push_back(&points[i]);\n            else equal.push_back(&points[i]);\n        }\n\n        std::vector<Point> p_outs;\n        for (Point* p0 : lower){\n            for (Point* p1 : upper) {\n                double t = (dim - p0->coords[dim_index]) / (p1->coords[dim_index] - p0->coords[dim_index]);\n                std::vector<double> coords(num_dimensions);\n                for (unsigned int i=0; i<num_dimensions; i++){\n                    coords[i] = p0->coords[i] + ((p1->coords[i] - p0->coords[i])*t);\n                }\n                Point np(coords);\n                np.hyper = true;\n                p_outs.push_back(np);\n            }\n        }\n\n        if (p_outs.size() == 0) {\n            std::vector<std::vector<Simplex>> out;\n            bool points_above = true;\n            for(Point p : points) \n                points_above &= p.coords[dim_index] >= dim - eps;\n\n            std::vector<Simplex> less;\n            std::vector<Simplex> greater;\n\n            if (!points_above){\n                less.push_back(Simplex(num_dimensions, points, triangulator));\n                out.push_back(less);\n                out.push_back(std::vector<Simplex>());\n            } else {\n                greater.push_back(Simplex(num_dimensions, points, triangulator));\n                out.push_back(std::vector<Simplex>());\n                out.push_back(greater); \n            }     \n            return out;\n        }\n\n        unsigned int index = 0;\n        std::vector<unsigned int> i_less(lower.size());\n        for (unsigned int i=0; i<lower.size(); i++) {\n            i_less[i] = i + index;\n        }\n        index += lower.size();\n\n        std::vector<unsigned int> i_greater(upper.size());\n        for (unsigned int i=0; i<upper.size(); i++) {\n            i_greater[i] = i + index;\n        } \n        index += upper.size();\n\n        std::vector<unsigned int> i_hyp(p_outs.size());\n        for (unsigned int i=0; i<p_outs.size(); i++) {\n            i_hyp[i] = i + index;\n        } \n        index += p_outs.size();\n        \n        for (unsigned int i=0; i<equal.size(); i++) i_hyp.push_back(i + index);\n\n        std::vector<Point> p_total(lower.size()+upper.size()+p_outs.size()+equal.size());\n        for(unsigned int i=0; i<lower.size(); i++){\n            p_total[i] = *(lower[i]);\n        }\n        for(unsigned int i=0; i<upper.size(); i++){\n            p_total[lower.size()+i] = *(upper[i]);\n        }\n        for(unsigned int i=0; i<p_outs.size(); i++){\n            p_total[lower.size()+upper.size()+i] = p_outs[i];\n        }\n        for(unsigned int i=0; i<equal.size(); i++){\n            p_total[lower.size()+upper.size()+p_outs.size()+i] = *(equal[i]);\n        }\n\n        std::vector<Simplex> simplices = triangulator.chooseTriangulation(num_dimensions, p_total, i_less, i_greater, i_hyp);\n\n        std::vector<Simplex> less;\n        std::vector<Simplex> greater;\n        for (Simplex s : simplices){\n            bool all_above = true;\n            bool all_below = true;\n            for (Point p : s.points) {\n                all_above &= p.coords[dim_index] >= dim-eps;\n                all_below &= p.coords[dim_index] <= dim+eps;\n            }\n\n            if (all_above)\n                greater.push_back(s);\n\n            if (all_below)\n                less.push_back(s);\n        }\n\n        std::vector<std::vector<Simplex>> out;\n        out.push_back(less);\n        out.push_back(greater);\n        return out;\n    }\n};\n\n#endif", "meta": {"hexsha": "e52abb80dc9267040b82cc4ea72bb884027d9034", "size": 7535, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "apps/NDGridGenerator/Simplex.hpp", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "apps/NDGridGenerator/Simplex.hpp", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "apps/NDGridGenerator/Simplex.hpp", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 33.048245614, "max_line_length": 125, "alphanum_fraction": 0.5414731254, "num_tokens": 1887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.5545972657061758}}
{"text": "//\n// Created by prostoichelovek on 12.06.19.\n//\n\n#ifndef VISUALODOMETRY_WRAPPER_HPP\n#define VISUALODOMETRY_WRAPPER_HPP\n\n\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include \"feature.h\"\n#include \"utils.h\"\n#include \"visualOdometry.h\"\n\nusing namespace cv;\nusing namespace std;\n\nclass Wrapper {\npublic:\n    Mat projMatrl, projMatrr;\n    Mat rotation = Mat::eye(3, 3, CV_64F);\n    Mat translation_stereo = Mat::zeros(3, 1, CV_64F);\n\n    Mat Rpose = Mat::eye(3, 3, CV_64F);\n\n    Mat frame_pose = Mat::eye(4, 4, CV_64F);\n    Mat frame_pose32 = Mat::eye(4, 4, CV_32F);\n\n    FeatureSet currentVOFeatures;\n    Mat points4D, points3D;\n\n    vector<Point2f> pointsLeft_t0, pointsRight_t0, pointsLeft_t1, pointsRight_t1;\n\n    Wrapper(Mat &projMatrl, Mat &projMatrr)\n            : projMatrl(projMatrl), projMatrr(projMatrr) {\n\n    }\n\n    Point computePos(Mat &imageLeft, Mat &imageRight) {\n        if (imageLeft_t0.cols == 0) {\n            imageLeft_t0 = imageLeft;\n            imageRight_t0 = imageRight;\n            return {-1, -1};\n        }\n\n        vector<Point2f> oldPointsLeft_t0 = currentVOFeatures.points;\n        matchingFeatures(imageLeft_t0, imageRight_t0,\n                         imageLeft, imageRight,\n                         currentVOFeatures,\n                         pointsLeft_t0, pointsRight_t0,\n                         pointsLeft_t1, pointsRight_t1);\n\n        imageLeft_t0 = imageLeft;\n        imageRight_t0 = imageRight;\n\n        vector<Point2f> &currentPointsLeft_t0 = pointsLeft_t0;\n        vector<Point2f> &currentPointsLeft_t1 = pointsLeft_t1;\n\n        vector<Point2f> newPoints;\n        vector<bool> valid; // valid new points are true\n\n        // ---------------------\n        // Triangulate 3D Points\n        // ---------------------\n        Mat points3D_t0, points4D_t0;\n        triangulatePoints(projMatrl, projMatrr, pointsLeft_t0, pointsRight_t0, points4D_t0);\n        convertPointsFromHomogeneous(points4D_t0.t(), points3D_t0);\n\n        Mat points3D_t1, points4D_t1;\n\n        triangulatePoints(projMatrl, projMatrr, pointsLeft_t1, pointsRight_t1, points4D_t1);\n        convertPointsFromHomogeneous(points4D_t1.t(), points3D_t1);\n\n        // -----------------------\n        // Tracking transformation\n        // -----------------------\n        trackingFrame2Frame(projMatrl, projMatrr, pointsLeft_t0, pointsLeft_t1, points3D_t0, rotation,\n                            translation_stereo);\n\n\n        points4D = points4D_t0;\n        frame_pose.convertTo(frame_pose32, CV_32F);\n        points4D = frame_pose32 * points4D;\n        convertPointsFromHomogeneous(points4D.t(), points3D);\n\n        // -----------\n        // Integrating\n        // -----------\n\n        Vec3f rotation_euler = rotationMatrixToEulerAngles(rotation);\n\n        Mat rigid_body_transformation;\n\n        if (abs(rotation_euler[1]) < 0.1 && abs(rotation_euler[0]) < 0.1\n            && abs(rotation_euler[2]) < 0.1) {\n            integrateOdometryStereo(rigid_body_transformation, frame_pose, rotation,\n                                    translation_stereo);\n        }\n\n        Rpose = frame_pose(Range(0, 3), Range(0, 3));\n        Vec3f Rpose_euler = rotationMatrixToEulerAngles(Rpose);\n\n        int x = int(frame_pose.col(3).at<double>(0));\n        int y = int(frame_pose.col(3).at<double>(2));\n\n        return Point(x, y);\n    }\n\nprivate:\n    Mat imageLeft_t0, imageRight_t0;\n\n};\n\n\n#endif //VISUALODOMETRY_WRAPPER_HPP\n", "meta": {"hexsha": "acd2ba231768e24b97976459e373f739d5b9a6c1", "size": 3512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Wrapper.hpp", "max_stars_repo_name": "prostoiChelovek/visual_odom", "max_stars_repo_head_hexsha": "e90a7331365e1c270beebde3e66b5f606fc27673", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-06T11:51:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T11:51:33.000Z", "max_issues_repo_path": "Wrapper.hpp", "max_issues_repo_name": "prostoiChelovek/visual_odom", "max_issues_repo_head_hexsha": "e90a7331365e1c270beebde3e66b5f606fc27673", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-11T19:48:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T04:29:03.000Z", "max_forks_repo_path": "Wrapper.hpp", "max_forks_repo_name": "prostoiChelovek/visual_odom", "max_forks_repo_head_hexsha": "e90a7331365e1c270beebde3e66b5f606fc27673", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-11T09:21:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-08T13:50:03.000Z", "avg_line_length": 28.5528455285, "max_line_length": 102, "alphanum_fraction": 0.6144646925, "num_tokens": 926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.5545152835420111}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/blas.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/tnt.hpp>\n#ifndef F_FORTRAN \n#  include <tnt/tnt_array2d_utils.h>\n#else\n#  include <tnt/tnt_fortran_array2d_utils.h>\n#endif \n\nnamespace blas = boost::numeric::bindings::blas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\n#ifndef F_FORTRAN \ntypedef TNT::Array2D<double> m_t;\n#else\ntypedef TNT::Fortran_Array2D<double> m_t;\n#endif\n\nint main() {\n\n  cout << endl; \n  size_t n = 3, nrhs = 1; \n\n  m_t a (n, n);   // system matrix \n#ifndef F_FORTRAN \n  a[0][0] = 1.; a[0][1] = 1.; a[0][2] = 1.;\n  a[1][0] = 2.; a[1][1] = 3.; a[1][2] = 1.;\n  a[2][0] = 1.; a[2][1] = -1.; a[2][2] = -1.;\n#else\n  a(1,1) = 1.; a(1,2) = 1.; a(1,3) = 1.;\n  a(2,1) = 2.; a(2,2) = 3.; a(2,3) = 1.;\n  a(3,1) = 1.; a(3,2) = -1.; a(3,3) = -1.;\n#endif \n\n// see leading comments for `gesv()' in clapack.hpp\n#ifndef F_FORTRAN \n  m_t b (nrhs, n);  // right-hand side matrix\n  b[0][0] = 4.; b[0][1] = 9.; b[0][2] = -2.; \n#else\n  m_t b (n, nrhs);  \n  b(1,1) = 4.; b(2,1) = 9.; b(3,1) = -2.; \n#endif \n\n  cout << \"A: \" << a << endl; \n  cout << \"B: \" << b << endl; \n\n  blas::lu_solve (a, b);  \n  cout << \"X: \" << b << endl; \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "16d4c9b9cf44ac988b2289c5617d9b357f5d1751", "size": 1388, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/tnt_gesv.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/tnt_gesv.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/tnt_gesv.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": 21.6875, "max_line_length": 51, "alphanum_fraction": 0.5626801153, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.554502990092817}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <iostream>\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace py = pybind11;\n\n// N is the number of zeros we are looking for\n// L is an array of orders l\npy::array_t<double> bessel_zeros(int N, py::array_t<uint64_t> L) {\n\n  py::buffer_info info = L.request();\n  if (info.ndim != 1)\n      throw std::runtime_error(\"Number of dimensions must be one\");\n  // Number of entries in the L array\n  int Nl = info.shape[0];\n  // Accessing the array values\n  uint64_t *Lptr = static_cast<uint64_t *>(info.ptr);\n\n  // Allocate the qln table and copy over the zeros\n  size_t size = Nl*N;\n  double *qln = new double[size];\n\n  #pragma omp parallel for schedule(dynamic)\n  for(int l=0; l < Nl; l++) {\n      std::vector<long double> roots;\n      boost::math::cyl_bessel_j_zero((double) (Lptr[l]+0.5), 1, N, std::back_inserter(roots));\n      for(int p=0; p <N; p++) {\n          qln[N*l + p] = roots[p];\n      }\n  }\n  // Create a Python object that will free the allocated\n  // memory when destroyed:\n  py::capsule free_when_done(qln, [](void *f) {\n      double *qln = reinterpret_cast<double *>(f);\n      delete[] qln;\n  });\n\n  return py::array_t<double>(\n      {Nl, N}, // shape\n      {N*8, 8}, // C-style contiguous strides for double\n      qln, // the data pointer\n      free_when_done); // numpy array references this parent\n}\n\nPYBIND11_MODULE(bessel_tools, m) {\n  m.doc() = \"Module for Bessel stuff\";\n  m.def(\"bessel_zeros\", &bessel_zeros, \"compute Bessel zeros\");\n}\n", "meta": {"hexsha": "48ac81983da2487a251f9bfca72adf5027dbd998", "size": 1533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "n5k/cxx/bessel_tools.cpp", "max_stars_repo_name": "EiffL/N5K", "max_stars_repo_head_hexsha": "2667d7b772d20ac0aa8da802150ab3764c10dd4d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "n5k/cxx/bessel_tools.cpp", "max_issues_repo_name": "EiffL/N5K", "max_issues_repo_head_hexsha": "2667d7b772d20ac0aa8da802150ab3764c10dd4d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "n5k/cxx/bessel_tools.cpp", "max_forks_repo_name": "EiffL/N5K", "max_forks_repo_head_hexsha": "2667d7b772d20ac0aa8da802150ab3764c10dd4d", "max_forks_repo_licenses": ["BSD-3-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.66, "max_line_length": 94, "alphanum_fraction": 0.6490541422, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5545029790547861}}
{"text": "/**\n * @file   Vector.cpp\n * @author ALIKAWA Hidehisa <alleyhide@gmail.com>\n * @date   2018/07/07\n * \n * @brief  class Vector\n * \n * Released under the MIT lisence\n */\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"gweyl.hpp\"\n\nnamespace gweyl{\n\nstruct VectorRootSpace::Impl {\n    RootSpace space_;\n    NumberVector simpleCoefficients_;///< coefficients for simple roots coordinate\n    NumberVector fundamentalCoefficients_;///< coefficients for fundamental weights coordinate\n};\n\nVectorRootSpace::VectorRootSpace(Type X, NumberVector& v, Coordinate c)    \n    : pImpl(std::make_unique<Impl>())\n{\n    RootSpace V(X, v.size());\n\n    pImpl->space_ = V;\n    \n    if (c == Coordinate::simple){\n        pImpl->simpleCoefficients_ = v;\n        matrix A = pImpl->space_.CartanMatrix();\n        pImpl->fundamentalCoefficients_ = prod(A, v);\n    }else {\n        matrix P = pImpl->space_.InverseCartanMatrix();\n        pImpl->simpleCoefficients_ = prod(P, v);\n        pImpl->fundamentalCoefficients_ = v;\n    }\n}\n\nVectorRootSpace::VectorRootSpace(): pImpl(std::make_unique<Impl>())\n{\n}\n\nVectorRootSpace::~VectorRootSpace(){\n}\n\nVectorRootSpace::VectorRootSpace(const VectorRootSpace& rhs): pImpl(std::make_unique<Impl>())\n{\n    RootSpace V(rhs.type(), rhs.rank());\n    pImpl->space_ = V;\n    pImpl->simpleCoefficients_ = rhs.simpleCoefficients();\n    pImpl->fundamentalCoefficients_ = rhs.fundamentalCoefficients();\n}\n\nVectorRootSpace& VectorRootSpace::operator=(const VectorRootSpace& rhs){\n\n    // this function does not check the equality of root space\n    // because *this is may defined invalid\n    \n    RootSpace V(rhs.type(), rhs.rank());\n    pImpl->space_ = V;\n    pImpl->simpleCoefficients_ = rhs.simpleCoefficients();\n    pImpl->fundamentalCoefficients_ = rhs.fundamentalCoefficients();\n    \n    return *this;\n}\n\n\nvoid VectorRootSpace::printf(){\n    std::cout << \"simple \" << pImpl->simpleCoefficients_ << std::endl;\n    std::cout << \"fundamental \" << pImpl->fundamentalCoefficients_ << std::endl;\n}\n\nNumberVector VectorRootSpace::simpleCoefficients() const{\n    return pImpl->simpleCoefficients_;\n}\n\nNumberVector VectorRootSpace::simpleCoefficients(){\n    return pImpl->simpleCoefficients_;\n}\n\nNumberVector VectorRootSpace::fundamentalCoefficients() const{\n    return pImpl->fundamentalCoefficients_;\n}\n\nNumberVector VectorRootSpace::fundamentalCoefficients(){\n    return pImpl->fundamentalCoefficients_;\n}\n\n\n\nType VectorRootSpace::type(){\n    return pImpl->space_.type();\n}\n\n\nType VectorRootSpace::type() const{\n    return pImpl->space_.type();\n}\n\n\nunsigned VectorRootSpace::rank(){\n    return pImpl->space_.rank();\n}\n\nunsigned VectorRootSpace::rank() const{\n    return pImpl->space_.rank();\n}\n\nbool VectorRootSpace::isInSameSpace(const VectorRootSpace& rhs){\n    if (this->type() != rhs.type()){\n        return false;\n    }\n\n    if (rank() != rhs.rank()){\n        return false;\n    }\n    return true;\n}\n\nbool VectorRootSpace::operator==(const VectorRootSpace& rhs){\n\n    if (!isInSameSpace(rhs)){\n        return false;\n    }\n    \n    if (!equal(pImpl->fundamentalCoefficients_, rhs.fundamentalCoefficients())){\n        return false;\n    }\n\n    return true;\n}\n\nbool VectorRootSpace::operator!=(const VectorRootSpace& rhs){\n    return !(*this == rhs);\n}\n\n\nVectorRootSpace& VectorRootSpace::operator+=(const VectorRootSpace& rhs){\n\n    if (!isInSameSpace(rhs)){\n        std::string msg{\"+= of VectorRootSpace error \"};\n        msg += \"LHS \";\n        msg += std::to_string(static_cast<int>(type()));\n        msg += \" \";\n        msg += std::to_string(rank());\n        msg += \", RHS \";\n        msg += std::to_string(static_cast<int>(rhs.type()));\n        msg += \" \";\n        msg += std::to_string(rhs.rank());\n        std::runtime_error e(msg);\n        throw e;\n    }\n\n    pImpl->simpleCoefficients_ += rhs.simpleCoefficients();\n    pImpl->fundamentalCoefficients_ += rhs.fundamentalCoefficients();\n\n    return *this;\n}\n\nVectorRootSpace& VectorRootSpace::operator-=(const VectorRootSpace& rhs){\n\n    if (!isInSameSpace(rhs)){\n        std::string msg{\"-= of VectorRootSpace error \"};\n        msg += \"LHS \";\n        msg += std::to_string(static_cast<int>(type()));\n        msg += \" \";\n        msg += std::to_string(rank());\n        msg += \", RHS \";\n        msg += std::to_string(static_cast<int>(rhs.type()));\n        msg += \" \";\n        msg += std::to_string(rhs.rank());\n        std::runtime_error e(msg);\n        throw e;\n    }\n\n    pImpl->simpleCoefficients_ -= rhs.simpleCoefficients();\n    pImpl->fundamentalCoefficients_ -= rhs.fundamentalCoefficients();\n\n    return *this;\n}\n\nVectorRootSpace& VectorRootSpace::operator*=(rational r){\n    pImpl->simpleCoefficients_ *= r;\n    pImpl->fundamentalCoefficients_ *= r;\n\n    return *this;\n}\n\nbool VectorRootSpace::dominant(){\n\n    NumberVector nv = fundamentalCoefficients();\n    for (rational x : nv){\n        if (x < 0){\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nbool VectorRootSpace::integral(){\n\n    NumberVector nv = fundamentalCoefficients();\n    for (rational x : nv){\n        if (x.denominator() != 1){\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nbool VectorRootSpace::isDominantIntegral(){\n    return ((dominant()) && (integral()));\n}\n\nVectorRootSpace operator+(const VectorRootSpace& v1, const VectorRootSpace& v2){\n    VectorRootSpace w(v1);\n    w += v2;\n    return w;\n}\n\n\nVectorRootSpace operator-(const VectorRootSpace& v1, const VectorRootSpace& v2){\n    VectorRootSpace w(v1);\n    w -= v2;\n    return w;\n}\n\nVectorRootSpace operator*(const VectorRootSpace& v1, const rational r){\n    VectorRootSpace w(v1);\n    w *= r;\n    return w;\n}\n\n\nVectorRootSpace operator*(const rational r, const VectorRootSpace& v1){\n    VectorRootSpace w(v1);\n    w *= r;\n    return w;\n}\n\n\n\n}\n", "meta": {"hexsha": "2dcedc8ea62b2005aed1567f5c190c85c97244e6", "size": 5797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cartan/VectorRootSpace.cpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Cartan/VectorRootSpace.cpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cartan/VectorRootSpace.cpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.375, "max_line_length": 94, "alphanum_fraction": 0.6477488356, "num_tokens": 1452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.6688802735722129, "lm_q1q2_score": 0.5544608281912633}}
{"text": "#include <Eigen/Dense>\nusing Eigen::MatrixXf;\n\n#define SGA_USE_EIGEN\n#include <sga.hpp>\n#include \"../common/common.hpp\"\n\n#include \"../common/json.hpp\"\nusing json = nlohmann::json;\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"../common/stb_image.h\"\n\n#include <iostream>\n#include <fstream>\n#include <cassert>\n\ninline bool file_exists(std::string path) {\n  return std::ifstream(path).good();\n}\n\nvoid usage(char** argv){\n  std::cout << \"USAGE: \" << argv[0] << \" CONFIG_FILE\" << std::endl;\n}\n\nEigen::Matrix3f find_homography(std::vector<Eigen::Vector2f> points1, std::vector<Eigen::Vector2f> points2){\n  assert(points1.size() == points2.size());\n  Eigen::MatrixXf A = Eigen::MatrixXf::Zero(points1.size()*2,9);\n  for(unsigned int i = 0; i < points1.size(); i++){\n    float x1 = points1[i](0), y1 = points1[i](1);\n    float x2 = points2[i](0), y2 = points2[i](1);\n    Eigen::Matrix<float, 2, 9> Q;\n    Q <<\n      x1, y1, 1,  0,  0, 0, -x1*x2, -y1*x2, -x2,\n      0 , 0 , 0, x1, y1, 1, -x1*y2, -y1*y2, -y2;\n    A.block(i*2,0,2,9) = Q;\n  }\n\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(A, Eigen::ComputeThinU | Eigen::ComputeFullV);\n  unsigned int P = svd.matrixV().cols();\n  Eigen::Map<const Eigen::Matrix3f> view(svd.matrixV().block(0,P-1,9,1).data(), 3, 3);\n  Eigen::Matrix3f H = view.transpose() / view(2,2);\n\n  return H;\n}\n\nint main(int argc, char** argv){\n  if(argc < 2) {\n    usage(argv);\n    return 1;\n  }\n  std::string config_path = argv[1];\n  size_t q = config_path.find_last_of(\"/\\\\\");\n  std::string config_dir = config_path.substr(0,q);\n  std::string output_path = \"output.png\";\n\n  // Enable sga\n  sga::init();\n  renderdoc_tryenable();\n  renderdoc_capture_start();\n\n  // Open and parse config file\n  std::ifstream config_file(config_path);\n  if(!config_file.good()){\n    std::cout << \"Failed to open file \\\"\" << config_path << \"\\\"\" << std::endl;\n    return 1;\n  }\n  std::vector<std::string> image_paths;\n  std::vector<std::pair<std::vector<Eigen::Vector2f>, std::vector<Eigen::Vector2f>>> points;\n  unsigned int center = 0;\n  unsigned int N;\n  bool render_lines = false;\n  try{\n    json config;\n    config_file >> config;\n    auto images = config[\"images\"];\n    if(!images.is_array()){\n      std::cout << \"Json config must contain an array of strings \\\"images\\\" representing a list of input images.\" << std::endl;\n      return 1;\n    }\n    for(auto& q : images){\n      image_paths.push_back(q);\n    }\n    N = image_paths.size();\n    if(config.count(\"center\") > 0){\n      center = config[\"center\"];\n    }\n    if(config.count(\"lines\") > 0){\n      render_lines = config[\"lines\"] != 0;\n    }\n    auto pointlist = config[\"points\"];\n    if(!pointlist.is_array() || pointlist.size() != N-1){\n      std::cout << \"Json config must contain an array of point coordinates \\\"points\\\" of the lentgh equal to the number of images minus one (\" << N-1 << \").\" << std::endl;\n      return 1;\n    }\n    for(auto& pointspair : pointlist){\n      std::vector<Eigen::Vector2f> pl;\n      std::vector<Eigen::Vector2f> pr;\n      if(pointspair.size() != 2){\n        std::cout << \"Each entry in \\\"points\\\" array must have two elements (a list of points in image N and a list of corresponding points on image N+1)\" << std::endl;\n        return 1;\n      }\n      for(auto& point : pointspair[0]){\n        Eigen::Vector2f p;\n        if(point.size() != 2){\n          std::cout << \"Each point must be an array of 2 numbers.\" << std::endl;\n          return 1;\n        }\n        p(0) = point[0]; p(1) = point[1];\n        pl.push_back(p);\n      }\n      for(auto& point : pointspair[1]){\n        Eigen::Vector2f p;\n        if(point.size() != 2){\n          std::cout << \"Each point must be an array of 2 numbers.\" << std::endl;\n          return 1;\n        }\n        p(0) = point[0]; p(1) = point[1];\n        pr.push_back(p);\n      }\n      points.push_back(std::make_pair(pl,pr));\n    }\n  }catch (json::exception& e){\n    std::cout << \"Error reading json config: \" << e.what() << std::endl;\n  }\n\n  // Print out configuration\n  /*\n  for(unsigned int i = 0; i < N; i++){\n    std::cout << image_paths[i] << std::endl;\n    if(i < N-1){\n      for(auto p : points[i].first){\n        std::cout << \"[\" << p(0) << \", \" << p(1) << \"] \";\n      }\n      std::cout << std::endl;\n      for(auto p : points[i].second){\n        std::cout << \"[\" << p(0) << \", \" << p(1) << \"] \";\n      }\n      std::cout << std::endl;\n    }\n  }\n  */\n\n  // Compute homographies\n  std::cout << \"Preparing Hs\" << std::endl;\n  std::vector<Eigen::Matrix3f> Hs;\n  Eigen::Matrix3f H0 = Eigen::Matrix3f::Identity(3,3);\n  Hs.push_back(H0);\n\n  for(unsigned int i = center+1; i < N; i++){\n    std::cout << \"Computing H between \" << i-1 << \" and \" << i << std::endl;\n    auto Hdiff = find_homography(points[i-1].first, points[i-1].second);\n    auto Habs = Hdiff * Hs.back();\n    Hs.push_back(Habs);\n  }\n  for(int i = center-1; i > -1; i--){\n    std::cout << \"Computing H between \" << i+1 << \" and \" << i << std::endl;\n    auto Hdiff = find_homography(points[i].second, points[i].first);\n    auto Habs = Hdiff * Hs.front();\n    Hs.insert(Hs.begin(), Habs);\n  }\n  assert(Hs.size() == N);\n\n  // Compute inverses\n  std::vector<Eigen::Matrix3f> His;\n  for(const auto& H : Hs)\n    His.push_back(H.inverse());\n\n  // Load images\n  std::cout << \"Loading images\" << std::endl;\n  std::vector<sga::Image> images;\n  for(std::string image_path : image_paths){\n    image_path = config_dir + \"/\" + image_path;\n\n    int w,h,n;\n    stbi_set_flip_vertically_on_load(1);\n    unsigned char* data = stbi_load(image_path.c_str(), &w, &h, &n, 4);\n    if(!data){\n      std::cout << \"Opening image '\" << image_path << \"' failed: \" << stbi_failure_reason() << std::endl;\n      return 1;\n    }\n    sga::Image image(w, h, 4, sga::ImageFormat::NInt8, sga::ImageFilterMode::Anisotropic);\n    image.putData(std::vector<uint8_t>(data, data + w*h*4));\n    free(data);\n\n    images.push_back(image);\n  }\n\n  std::cout << \"Preparing render resources\" << std::endl;\n\n  // Prepare image bounding boxes\n  Eigen::ArrayXXf imgBBs(4*N,3);\n  for(unsigned int i = 0; i < N; i++){\n    auto& p = images[i];\n    auto& Hi = His[i];\n    Eigen::Vector3f v0(0,0,1);\n    Eigen::Vector3f v1(0,p.getHeight(),1);\n    Eigen::Vector3f v2(p.getWidth(),0,1);\n    Eigen::Vector3f v3(p.getWidth(),p.getHeight(),1);\n    imgBBs.block(4*i + 0, 0, 1, 3) = (Hi*v0).transpose();\n    imgBBs.block(4*i + 1, 0, 1, 3) = (Hi*v1).transpose();\n    imgBBs.block(4*i + 2, 0, 1, 3) = (Hi*v2).transpose();\n    imgBBs.block(4*i + 3, 0, 1, 3) = (Hi*v3).transpose();\n  }\n  imgBBs.colwise() /= imgBBs.col(2);\n  Eigen::Vector3f BBmax, BBmin;\n  BBmax = imgBBs.colwise().maxCoeff();\n  BBmin = imgBBs.colwise().minCoeff();\n  Eigen::Vector3f BBsize = BBmax - BBmin;\n  Eigen::Vector3f offset = BBmin;\n  std::cout << \"offset \" << offset << std::endl;\n\n  // Create target image\n  sga::Image result(BBsize(0), BBsize(1));\n\n  // Prepare a VBO\n  struct VertData{\n    Eigen::Vector2f pos;\n  };\n  std::vector<VertData> vertices = {\n    {{0,0}},{{0,1}},{{1,0}},\n    {{1,1}},{{1,0}},{{0,1}}\n  };\n  sga::VBO vbo({sga::DataType::Float2}, vertices.size());\n  vbo.write(vertices);\n\n  // Prepare shaders\n  auto vertShader = sga::VertexShader::createFromSource(R\"(\n    mat3 align = mat3(vec3(2, 0, 0),vec3(0, 2, 0),vec3(-1, -1, 1));\n    void main(){\n      vec2 pos_texturespace = in_position * textureSize(image,0);\n      vec3 pos_transformed_homog = H * vec3(pos_texturespace,1);\n      float perspective_factor = 1/pos_transformed_homog.z;\n      vec2 pos_transformed = pos_transformed_homog.xy/pos_transformed_homog.z;\n      vec2 pos3 = 2*(pos_transformed - offset)/sgaResolution.xy - 1;\n      gl_Position = vec4(pos3,0,1);\n      imageUVW = vec3(in_position.x, 1 - in_position.y, 1) * perspective_factor;\n    }\n  )\");\n  vertShader.addInput(sga::DataType::Float2, \"in_position\");\n  vertShader.addOutput(sga::DataType::Float3, \"imageUVW\");\n  vertShader.addSampler(\"image\");\n  vertShader.addUniform(sga::DataType::Mat3, \"H\");\n  vertShader.addUniform(sga::DataType::Float2, \"offset\");\n  auto fragShader = sga::FragmentShader::createFromSource(R\"(\n    void main(){\n      out_color = textureProj(image, imageUVW);\n    }\n  )\");\n  fragShader.addOutput(sga::DataType::Float4, \"out_color\");\n  fragShader.addInput(sga::DataType::Float3, \"imageUVW\");\n  fragShader.addSampler(\"image\");\n  auto program = sga::Program::createAndCompile(vertShader,fragShader);\n\n  // Prepare pipeline\n  sga::Pipeline pipeline;\n  pipeline.setProgram(program);\n  pipeline.setTarget({result});\n  pipeline.setFaceCull(sga::FaceCullMode::None);\n  pipeline.setBlendModeColor(sga::BlendFactor::One, sga::BlendFactor::OneMinusSrcAlpha);\n  pipeline.setBlendModeAlpha(sga::BlendFactor::One, sga::BlendFactor::OneMinusSrcAlpha);\n  pipeline.clear();\n\n  std::cout << \"Rendering\" << std::endl;\n\n  // Draw!\n  pipeline.uniform[\"offset\"] = Eigen::Vector2f{offset(0), offset(1)};\n  for(unsigned int i = 0; i < N; i++){\n    pipeline.sampler[\"image\"] = images[i];\n    pipeline.uniform[\"H\"] = His[i];\n    std::cout << His[i] << std::endl;\n    pipeline.draw(vbo);\n  }\n\n  // Prepare another pipeline, just for rendering image edges\n  if(render_lines){\n    auto linesFragShader = sga::FragmentShader::createFromSource(R\"(\n      void main(){out_color = vec4(1,0,0,0.2);}\n    )\");\n    linesFragShader.addOutput(sga::DataType::Float4, \"out_color\");\n    linesFragShader.addInput(sga::DataType::Float3, \"imageUVW\");\n    auto lines_program = sga::Program::createAndCompile(vertShader,linesFragShader);\n    sga::Pipeline lines_pipeline;\n    lines_pipeline.setPolygonMode(sga::PolygonMode::LineStrip);\n    lines_pipeline.setLineWidth(2.0);\n    lines_pipeline.setTarget(result);\n    lines_pipeline.setProgram(lines_program);\n    lines_pipeline.setBlendModeColor(sga::BlendFactor::One, sga::BlendFactor::OneMinusSrcAlpha);\n    lines_pipeline.setBlendModeAlpha(sga::BlendFactor::One, sga::BlendFactor::OneMinusSrcAlpha);\n\n    // VBO for lines\n    std::vector<VertData> lines_vertices = {\n      {{0,0}},{{0,1}},{{1,1}},{{1,0}},{{0,0}}\n    };\n    sga::VBO lines_vbo({sga::DataType::Float2}, lines_vertices.size());\n    lines_vbo.write(lines_vertices);\n\n    lines_pipeline.uniform[\"offset\"] = Eigen::Vector2f{offset(0),offset(1)};\n    for(unsigned int i = 0; i < N; i++){\n      lines_pipeline.sampler[\"image\"] = images[i];\n      lines_pipeline.uniform[\"H\"] = His[i];\n      lines_pipeline.draw(lines_vbo);\n    }\n  }\n\n  // Save result\n  std::cout << \"Saving result to \" << output_path << std::endl;\n  result.savePNG(output_path);\n\n  renderdoc_capture_end();\n\n  sga::terminate();\n}\n", "meta": {"hexsha": "fb5d63a9e1f6c5f7805eeef73c3b9e9cf4edf821", "size": 10512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/stitch/main.cpp", "max_stars_repo_name": "rafalcieslak/libsga", "max_stars_repo_head_hexsha": "1b0299e686990b3f50b81ee54c5a06197195799d", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-05T20:58:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-24T03:59:23.000Z", "max_issues_repo_path": "examples/stitch/main.cpp", "max_issues_repo_name": "rafalcieslak/libsga", "max_issues_repo_head_hexsha": "1b0299e686990b3f50b81ee54c5a06197195799d", "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": "examples/stitch/main.cpp", "max_forks_repo_name": "rafalcieslak/libsga", "max_forks_repo_head_hexsha": "1b0299e686990b3f50b81ee54c5a06197195799d", "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": 33.4777070064, "max_line_length": 171, "alphanum_fraction": 0.6178652968, "num_tokens": 3253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5544608114131573}}
{"text": "#include \"backend.h\"\n#include \"sofunction.h\"\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"solvers/regulafalsi.h\"\n#include \"solvers/secant.h\"\n#include \"solvers/bisection.h\"\n#include <iomanip>\n#include <fenv.h>\n\nBackend::Backend() {\n\n}\n\nBackend::~Backend() {\n    delete function;\n}\n\nstd::string Backend::intervalToString(interval x, int decimals) {\n    std::stringstream str;\n    str << std::scientific;\n    str << std::setprecision(decimals);\n\n    if (singleton(x)) {\n        str << \"[\" << median(x) << \"]\";\n    } else {\n        int old_rounding = fegetround();\n\n        fesetround(FE_DOWNWARD);\n        str << \"[\" << x.lower() << \", \";\n        fesetround(FE_UPWARD);\n        str << x.upper() << \"]\";\n\n        fesetround(old_rounding);\n    }\n\n    return str.str();\n}\n\nlong double Backend::stringToFloat(const std::string &value) {\n    if (value.find(\"bla\") != std::string::npos) {\n        throw \"Nie tym razem, panie profesorze ;)\";\n    }\n\n    try {\n        return std::stold(value);\n    } catch (std::invalid_argument &error) {\n        throw \"Nie udało się zinterpretować wpisanych danych jako liczbę!\";\n    }\n}\n\ninterval Backend::stringToInterval(const std::string &value, char separator) {\n    size_t split_pos = value.find(separator);\n    std::string left_str, right_str;\n    boost::multiprecision::cpp_dec_float_50 left_mp, right_mp;\n    long double left, right;\n\n    if (split_pos == std::string::npos) {\n        left_str = right_str = value;\n    } else {\n        // przedział\n        left_str = value.substr(0, split_pos);\n        right_str = value.substr(split_pos + 1);\n    }\n\n    try {\n        left_mp.assign(left_str);\n        right_mp.assign(right_str);\n    } catch (std::runtime_error &error) {\n        throw \"Nie udało się zinterpretować wpisanych danych jako liczbę!\";\n    }\n\n    int old_rounding = fegetround();\n    fesetround(FE_DOWNWARD);\n    left = left_mp.convert_to<long double>();\n    fesetround(FE_UPWARD);\n    right = right_mp.convert_to<long double>();\n    fesetround(old_rounding);\n\n    return interval(left, right);\n}\n\nstruct SingleFloatSummary Backend::floatSummary(long double solution, std::string more) {\n    struct SingleFloatSummary out;\n\n    std::stringstream str;\n    str << std::scientific;\n    str << std::setprecision(decimals);\n\n    str << solution;\n    out.x = str.str();\n    str.str(std::string());\n\n    long double y = function->evaluate(solution);\n    str << y;\n    out.y = str.str();\n    str.str(std::string());\n\n    out.more = more;\n\n    return out;\n}\n\nstruct SingleIntervalSummary Backend::intervalSummary(interval solution, std::string more) {\n    struct SingleIntervalSummary out;\n\n    std::stringstream str;\n    str << std::scientific;\n    str << std::setprecision(decimals);\n\n    out.x = intervalToString(solution, decimals);\n\n    str << median(solution);\n    out.median = str.str();\n    str.str(std::string());\n\n    int old_rounding = fegetround();\n    fesetround(FE_UPWARD);\n    str << upper(solution) - lower(solution);\n    out.width = str.str();\n    str.str(std::string());\n\n    fesetround(old_rounding);\n\n    interval y = function->evaluate(solution);\n    out.y = intervalToString(y, decimals);\n\n    out.more = more;\n\n    return out;\n}\n\nvoid Backend::loadFunction(char filename[]) {\n    Function *new_function;\n\n    new_function = new SOFunction(filename);\n    if (function != nullptr) {\n        delete function;\n    }\n\n    function = new_function;\n}\n\nstruct FloatSummary Backend::solveFloatingPoint(const std::string &a_str, const std::string &b_str) {\n    long double a, b, x;\n    a = stringToFloat(a_str);\n    b = stringToFloat(b_str);\n\n   struct FloatSummary out;\n   bool secant_only = false;\n   try {\n       check_interval(a, b, function, true);\n   } catch (int err) {\n       if (err == NO_REAL_ROOTS) {\n           secant_only = true;\n       }\n   }\n\n    try {\n        x = Secant(a, b, function);\n        out.secant = floatSummary(x);\n\n        if (!secant_only) {\n            x = RegulaFalsi(a, b, function);\n            out.regulafalsi = floatSummary(x);\n\n            bool reached;\n            x = Bisection(a, b, function, bisectionTolerance, bisectionIterations, reached);\n            out.bisection = floatSummary(x, std::string(\"reached = \")+(reached?\"true\":\"false\"));\n        }\n    } catch(int err) {\n        if (err == WRONG_INTERVAL) {\n            throw \"Lewy koniec przedziału musi być mniejszy od prawego końca!\";\n        } else if (err == NO_REAL_ROOTS) {\n            throw \"Brak rozwiązań rzeczywistych w tym przedziale. Upewnij się, że f(a) * f(b) < 0\";\n        }\n    }\n\n    return out;\n}\n\nstruct IntervalSummary Backend::solveInterval(const std::string &a_str, const std::string &b_str) {\n    interval a, b, x;\n\n    try {\n        a = stringToInterval(a_str);\n        b = stringToInterval(b_str);\n    } catch (std::runtime_error err) {\n        throw \"Nie można zbudować takiego przedziału!\";\n    }\n\n    struct IntervalSummary out;\n    bool secant_only = false;\n    try {\n        check_interval(a, b, function, true);\n    } catch (int err) {\n        if (err == NO_REAL_ROOTS) {\n            secant_only = true;\n        }\n    }\n\n    try {\n        x = Secant(a, b, function);\n        out.secant = intervalSummary(x);\n\n        if (!secant_only) {\n            bool reached;\n            x = Bisection(a, b, function, bisectionTolerance, bisectionIterations, reached);\n            out.bisection = intervalSummary(x, std::string(\"reached = \")+(reached?\"true\":\"false\"));\n\n            x = RegulaFalsi(a, b, function);\n            out.regulafalsi = intervalSummary(x);\n        }\n    } catch(int err) {\n        if (err == WRONG_INTERVAL) {\n            throw \"Lewy koniec przedziału musi być mniejszy od prawego końca!\";\n        } else if (err == NO_REAL_ROOTS) {\n            throw \"Możliwy brak rozwiązań rzeczywistych w tym przedziale. Upewnij się, że f(a) * f(b) < 0\";\n        }\n    }\n\n    return out;\n}\n", "meta": {"hexsha": "b9b1e14729529f7eef464c8f08218b4ace24a045", "size": 5878, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "backend.cpp", "max_stars_repo_name": "hejmsdz/NonLinear", "max_stars_repo_head_hexsha": "1bff34eb6ea4365cbb9d914d49879a789af9e7cd", "max_stars_repo_licenses": ["MIT"], "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.cpp", "max_issues_repo_name": "hejmsdz/NonLinear", "max_issues_repo_head_hexsha": "1bff34eb6ea4365cbb9d914d49879a789af9e7cd", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "hejmsdz/NonLinear", "max_forks_repo_head_hexsha": "1bff34eb6ea4365cbb9d914d49879a789af9e7cd", "max_forks_repo_licenses": ["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.3587443946, "max_line_length": 107, "alphanum_fraction": 0.6087104457, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5543521902676359}}
{"text": "#include <iostream>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/project_inliers.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/filters/radius_outlier_removal.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <Eigen/Core>\n#include <pcl/common/transforms.h>\n#include <pcl/common/common.h>\n#include <pcl/common/time.h>\n#include <pcl/common/angles.h>\n#include <pcl/registration/transformation_estimation_svd.h>\n \n \nusing namespace std;\ntypedef pcl::PointXYZ PointType;\ntypedef struct myPointType  \n{  \n    double x;  //mm world coordinate x  \n    double y;  //mm world coordinate y  \n    double z;  //mm world coordinate z  \n\tint num;   //point num\n}; \n \n// Get N bits of the string from back to front.\nchar* Substrend(char*str,int n)\n{\n\tchar *substr=(char*)malloc(n+1);\n\tint length=strlen(str);\n\tif (n>=length)\n\t{\n\t\tstrcpy(substr,str);\n\t\treturn substr;\n\t}\n\tint k=0;\n\tfor (int i=length-n;i<length;i++)\n\t{\n\t\tsubstr[k]=str[i];\n\t\tk++;\n\t}\n\tsubstr[k]='\\0';\n\treturn substr;\n}\n \nint main(int argc, char **argv)\n{\n\t// create point cloud  \n\tpcl::PointCloud<PointType>::Ptr cloud(new pcl::PointCloud<PointType>());\n \n\t// load data\n\tchar* fileType;\n\tif (argc>1)\n\t{\n\t\tfileType = Substrend(argv[1],3);\n\t}\n\tif (!strcmp(fileType,\"pcd\"))\n\t{\n    \t// load pcd file\n\t\tpcl::io::loadPCDFile(argv[1], *cloud);\n\t}\n\telse if(!strcmp(fileType,\"txt\"))\n\t{\n\t\t// load txt data file\t\n\t\tint number_Txt;\n\t\tmyPointType txtPoint; \n\t\tvector<myPointType> points; \n\t\tFILE *fp_txt; \n\t\tfp_txt = fopen(argv[1], \"r\");  \n\t\tif (fp_txt)  \n\t\t{  \n\t\t    while (fscanf(fp_txt, \"%lf %lf %lf\", &txtPoint.x, &txtPoint.y, &txtPoint.z) != EOF)  \n\t\t    {  \n\t\t        points.push_back(txtPoint);  \n\t\t    }  \n\t\t}  \n\t\telse  \n\t\t    std::cout << \"txt数据加载失败！\" << endl;  \n\t\tnumber_Txt = points.size();  \n \n\t\tcloud->width = number_Txt;  \n\t\tcloud->height = 1;     \n\t\tcloud->is_dense = false;  \n\t\tcloud->points.resize(cloud->width * cloud->height);  \n\t  \n\t\tfor (size_t i = 0; i < cloud->points.size(); ++i)  \n\t\t{  \n\t\t    cloud->points[i].x = points[i].x;  \n\t\t    cloud->points[i].y = points[i].y;  \n\t\t    cloud->points[i].z = 0;  \n\t\t}  \n\t}\n\telse \n\t{\n\t\tstd::cout << \"please input data file name\"<<endl;\n\t\treturn 0;\n\t}\n \n\t// start calculating time\n    pcl::StopWatch time;\n \n\t\n    Eigen::Vector4f pcaCentroid;\n    pcl::compute3DCentroid(*cloud, pcaCentroid);\n    Eigen::Matrix3f covariance;\n    pcl::computeCovarianceMatrixNormalized(*cloud, pcaCentroid, covariance);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver(covariance, Eigen::ComputeEigenvectors);\n    Eigen::Matrix3f eigenVectorsPCA = eigen_solver.eigenvectors();\n    Eigen::Vector3f eigenValuesPCA = eigen_solver.eigenvalues();\n    eigenVectorsPCA.col(2) = eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1)); //校正主方向间垂直\n    eigenVectorsPCA.col(0) = eigenVectorsPCA.col(1).cross(eigenVectorsPCA.col(2));\n    eigenVectorsPCA.col(1) = eigenVectorsPCA.col(2).cross(eigenVectorsPCA.col(0));\n \n    std::cout << \"特征值va(3x1):\\n\" << eigenValuesPCA << std::endl;\n    std::cout << \"特征向量ve(3x3):\\n\" << eigenVectorsPCA << std::endl;\n    std::cout << \"质心点(4x1):\\n\" << pcaCentroid << std::endl;\n    /*\n    // 另一种计算点云协方差矩阵特征值和特征向量的方式:通过pcl中的pca接口，如下，这种情况得到的特征向量相似特征向量\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudPCAprojection (new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PCA<pcl::PointXYZ> pca;\n    pca.setInputCloud(cloudSegmented);\n    pca.project(*cloudSegmented, *cloudPCAprojection);\n    std::cerr << std::endl << \"EigenVectors: \" << pca.getEigenVectors() << std::endl;//计算特征向量\n    std::cerr << std::endl << \"EigenValues: \" << pca.getEigenValues() << std::endl;//计算特征值\n    */\n    Eigen::Matrix4f tm = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f tm_inv = Eigen::Matrix4f::Identity();\n    tm.block<3, 3>(0, 0) = eigenVectorsPCA.transpose();   //R.\n    tm.block<3, 1>(0, 3) = -1.0f * (eigenVectorsPCA.transpose()) *(pcaCentroid.head<3>());//  -R*t\n    tm_inv = tm.inverse();\n \n    std::cout << \"变换矩阵tm(4x4):\\n\" << tm << std::endl;\n    std::cout << \"逆变矩阵tm'(4x4):\\n\" << tm_inv << std::endl;\n \n    pcl::PointCloud<PointType>::Ptr transformedCloud(new pcl::PointCloud<PointType>);\n    pcl::transformPointCloud(*cloud, *transformedCloud, tm);\n \n    PointType min_p1, max_p1;\n    Eigen::Vector3f c1, c;\n    pcl::getMinMax3D(*transformedCloud, min_p1, max_p1);\n    c1 = 0.5f*(min_p1.getVector3fMap() + max_p1.getVector3fMap());\n \n    std::cout << \"型心c1(3x1):\\n\" << c1 << std::endl;\n \n    Eigen::Affine3f tm_inv_aff(tm_inv);\n    pcl::transformPoint(c1, c, tm_inv_aff);\n \n    Eigen::Vector3f whd, whd1;\n    whd1 = max_p1.getVector3fMap() - min_p1.getVector3fMap();\n    whd = whd1;\n    float sc1 = (whd1(0) + whd1(1) + whd1(2)) / 3;  //点云平均尺度，用于设置主方向箭头大小\n \n    std::cout << \"width1=\" << whd1(0) << endl;\n    std::cout << \"heght1=\" << whd1(1) << endl;\n    std::cout << \"depth1=\" << whd1(2) << endl;\n    std::cout << \"scale1=\" << sc1 << endl;\n \n    const Eigen::Quaternionf bboxQ1(Eigen::Quaternionf::Identity());\n    const Eigen::Vector3f    bboxT1(c1);\n    const Eigen::Quaternionf bboxQ(tm_inv.block<3, 3>(0, 0));\n    const Eigen::Vector3f    bboxT(c);\n \n    //变换到原点的点云主方向\n    PointType op;\n    op.x = 0.0;\n    op.y = 0.0;\n    op.z = 0.0;\n    Eigen::Vector3f px, py, pz;\n    Eigen::Affine3f tm_aff(tm);\n    pcl::transformVector(eigenVectorsPCA.col(0), px, tm_aff);\n    pcl::transformVector(eigenVectorsPCA.col(1), py, tm_aff);\n    pcl::transformVector(eigenVectorsPCA.col(2), pz, tm_aff);\n    PointType pcaX;\n    pcaX.x = sc1 * px(0);\n    pcaX.y = sc1 * px(1);\n    pcaX.z = sc1 * px(2);\n    PointType pcaY;\n    pcaY.x = sc1 * py(0);\n    pcaY.y = sc1 * py(1);\n    pcaY.z = sc1 * py(2);\n    PointType pcaZ;\n    pcaZ.x = sc1 * pz(0);\n    pcaZ.y = sc1 * pz(1);\n    pcaZ.z = sc1 * pz(2);\n \n    //初始点云的主方向\n    PointType cp;\n    cp.x = pcaCentroid(0);\n    cp.y = pcaCentroid(1);\n    cp.z = pcaCentroid(2);\n    PointType pcX;\n    pcX.x = sc1 * eigenVectorsPCA(0, 0) + cp.x;\n    pcX.y = sc1 * eigenVectorsPCA(1, 0) + cp.y;\n    pcX.z = sc1 * eigenVectorsPCA(2, 0) + cp.z;\n    PointType pcY;\n    pcY.x = sc1 * eigenVectorsPCA(0, 1) + cp.x;\n    pcY.y = sc1 * eigenVectorsPCA(1, 1) + cp.y;\n    pcY.z = sc1 * eigenVectorsPCA(2, 1) + cp.z;\n    PointType pcZ;\n    pcZ.x = sc1 * eigenVectorsPCA(0, 2) + cp.x;\n    pcZ.y = sc1 * eigenVectorsPCA(1, 2) + cp.y;\n    pcZ.z = sc1 * eigenVectorsPCA(2, 2) + cp.z;\n \n\t//Rectangular vertex \n\tpcl::PointCloud<PointType>::Ptr transVertexCloud(new pcl::PointCloud<PointType>);//存放变换后点云包围盒的6个顶点\n\tpcl::PointCloud<PointType>::Ptr VertexCloud(new pcl::PointCloud<PointType>);//存放原来点云中包围盒的6个顶点\n\ttransVertexCloud->width = 6;  \n\ttransVertexCloud->height = 1;     \n\ttransVertexCloud->is_dense = false;  \n\ttransVertexCloud->points.resize(transVertexCloud->width * transVertexCloud->height);  \n\ttransVertexCloud->points[0].x = max_p1.x;\n\ttransVertexCloud->points[0].y = max_p1.y;\n\ttransVertexCloud->points[0].z = max_p1.z;\n\ttransVertexCloud->points[1].x = max_p1.x;\n\ttransVertexCloud->points[1].y = max_p1.y;\n\ttransVertexCloud->points[1].z = min_p1.z;\n\ttransVertexCloud->points[2].x = max_p1.x;\n\ttransVertexCloud->points[2].y = min_p1.y;\n\ttransVertexCloud->points[2].z = min_p1.z;\n\ttransVertexCloud->points[3].x = min_p1.x;\n\ttransVertexCloud->points[3].y = max_p1.y;\n\ttransVertexCloud->points[3].z = max_p1.z;\n\ttransVertexCloud->points[4].x = min_p1.x;\n\ttransVertexCloud->points[4].y = min_p1.y;\n\ttransVertexCloud->points[4].z = max_p1.z;\n\ttransVertexCloud->points[5].x = min_p1.x;\n\ttransVertexCloud->points[5].y = min_p1.y;\n\ttransVertexCloud->points[5].z = min_p1.z;\n\tpcl::transformPointCloud(*transVertexCloud, *VertexCloud, tm_inv);\n\t\n\t// 逆变换回来的角度\n\tcout << whd1(0) << \" \"<< whd1(1) << \" \" << whd1(2) << endl;\n\tauto euler = bboxQ1.toRotationMatrix().eulerAngles(0, 1, 2); \n\tstd::cout << \"Euler from quaternion in roll, pitch, yaw\"<< std::endl << euler/3.14*180 << std::endl<<std::endl;\n\t\n\t//Output time consumption \n\tstd::cout << \"运行时间\" << time.getTime() << \"ms\" << std::endl;\n \n    //visualization\n    pcl::visualization::PCLVisualizer viewer;\n    pcl::visualization::PointCloudColorHandlerCustom<PointType> tc_handler(transformedCloud, 0, 255, 0); //设置点云颜色\n\t//Visual transformed point cloud\n    viewer.addPointCloud(transformedCloud, tc_handler, \"transformCloud\");\n    viewer.addCube(bboxT1, bboxQ1, whd1(0), whd1(1), whd1(2), \"bbox1\");\n    viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, \"bbox1\");\n    viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.0, 1.0, 0.0, \"bbox1\");\n \n    viewer.addArrow(pcaX, op, 1.0, 0.0, 0.0, false, \"arrow_X\");\n    viewer.addArrow(pcaY, op, 0.0, 1.0, 0.0, false, \"arrow_Y\");\n    viewer.addArrow(pcaZ, op, 0.0, 0.0, 1.0, false, \"arrow_Z\");\n \n    pcl::visualization::PointCloudColorHandlerCustom<PointType> color_handler(cloud, 255, 0, 0);  \n    viewer.addPointCloud(cloud, color_handler, \"cloud\");\n    viewer.addCube(bboxT, bboxQ, whd(0), whd(1), whd(2), \"bbox\");\n    viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, \"bbox\");\n    viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1.0, 0.0, 0.0, \"bbox\");\n \n    viewer.addArrow(pcX, cp, 1.0, 0.0, 0.0, false, \"arrow_x\");\n    viewer.addArrow(pcY, cp, 0.0, 1.0, 0.0, false, \"arrow_y\");\n    viewer.addArrow(pcZ, cp, 0.0, 0.0, 1.0, false, \"arrow_z\");\n \n    viewer.addCoordinateSystem(0.5f*sc1);\n    viewer.setBackgroundColor(0.0, 0.0, 0.0);\n \n\tviewer.addPointCloud(VertexCloud, \"temp_cloud\");\n\tviewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 10, \"temp_cloud\");\n    while (!viewer.wasStopped())\n    {\n          viewer.spinOnce();\n    }\n \n    return 0;\n}", "meta": {"hexsha": "3ad27d701207528661407c0ef237875c86c23736", "size": 10145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pcl/src/other/bounding_box_reference.cpp", "max_stars_repo_name": "lukechencqu/bluerov_zed_tracking", "max_stars_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-21T12:21:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T00:57:02.000Z", "max_issues_repo_path": "pcl/src/other/bounding_box_reference.cpp", "max_issues_repo_name": "lukechencqu/bluerov_zed_tracking", "max_issues_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcl/src/other/bounding_box_reference.cpp", "max_forks_repo_name": "lukechencqu/bluerov_zed_tracking", "max_forks_repo_head_hexsha": "75d87cfc183839615fada0731724cf0a230a0970", "max_forks_repo_licenses": ["Apache-2.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.975177305, "max_line_length": 160, "alphanum_fraction": 0.6616067028, "num_tokens": 3498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5543118990820971}}
{"text": "/**\n * @file   main.cpp\n * @author Simon Pintarelli <simon@thinkpadX1>\n * @date   Wed Oct 21 17:37:10 2015\n *\n * @brief  Example for Polar->Nodal basis transformation and quadrature\n *         in the nodal basis\n *\n *\n */\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <algorithm>\n\n#include \"quadrature/qhermite.hpp\"\n\n//#include \"spectral/hermite_to_nodal.hpp\"\n#include \"aux/eigen2hdf.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n#include \"spectral/polar_to_nodal.hpp\"\n\n\nusing namespace std;\nusing namespace boltzmann;\n\nnamespace po = boost::program_options;\n\n// obviously wrong ... But it is not used, see below.\nvoid test1(int K)\n{\n  typedef Eigen::VectorXd vec_t;\n\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, K, K, 2, true);\n  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  Polar2Nodal<polar_basis_t> p2n;\n  p2n.init(polar_basis, 0.5);\n\n  Mass mass(polar_basis);\n\n  std::vector<size_t> elems = {0, 1, 2, 3, 4, 5, 6};\n  // quadrature\n  QHermiteW quad(0.5, K);\n  auto& w = quad.wts();\n  auto& x = quad.pts();\n\n  // Achtung mit den Knoten und der Skalierung der Gewichte\n  QHermiteW quad1(1, K);\n  auto& xh = quad1.pts();\n\n  std::string fname = std::string(\"P2N\") + std::to_string(K) + \".h5\";\n  hid_t file = H5Fcreate(fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (size_t eidx : elems) {\n    Eigen::VectorXd cp(polar_basis.n_dofs());\n    cp.setZero();\n    cp(eidx) = 1.0;\n\n    const double mass_ref = mass.compute(cp.data());\n\n    Eigen::MatrixXd cn(K, K);\n    p2n.to_nodal(cn, cp);\n    eigen2hdf::save(file, \"cn\" + std::to_string(eidx), cn);\n\n    auto id = polar_basis.get_elem(eidx).id();\n\n    double sum = 0;\n    for (size_t q1 = 0; q1 < w.size(); ++q1) {\n      for (size_t q2 = 0; q2 < w.size(); ++q2) {\n        // (*) QUAD EXAMPLE\n        sum += cn(q1, q2) * std::sqrt(w[q1] * w[q2]) *\n               std::exp(-xh[q1] * xh[q1] / 2 - xh[q2] * xh[q2] / 2);\n      }\n    }\n    cout << id.to_string() << \"Sum: \" << setprecision(5) << scientific << sum << endl;\n    cout << id.to_string() << \"Ref: \" << setprecision(5) << scientific << mass_ref << \"\\n\\n\";\n  }\n\n  typedef Eigen::VectorXd vec_t;\n  Eigen::Map<const vec_t> xq(quad.points_data(), K);\n  Eigen::Map<const vec_t> wq(quad.weights_data(), K);\n\n  eigen2hdf::save(file, \"xq\", xq);\n  eigen2hdf::save(file, \"wq\", wq);\n\n  auto& N2H = p2n.get_h2n()->get_n2h();\n  auto& H2N = p2n.get_h2n()->get_h2n();\n\n  eigen2hdf::save(file, \"H2N\", H2N);\n  eigen2hdf::save(file, \"N2H\", N2H);\n\n  H5Fclose(file);\n}\n\n// Polar-Laguerre coefficients with exponential decay\nvoid test2(int K, const std::function<double(double)>& cfct)\n{\n  typedef Eigen::VectorXd vec_t;\n\n  typedef typename SpectralBasisFactoryKS::basis_type polar_basis_t;\n  polar_basis_t polar_basis;\n  SpectralBasisFactoryKS::create(polar_basis, K, K, 2, true);\n  SpectralBasisFactoryKS::write_basis_descriptor(polar_basis, \"spectral_basis.desc\");\n\n  Polar2Nodal<polar_basis_t> p2n;\n  p2n.init(polar_basis, 1.0);\n\n  unsigned int N = polar_basis.n_dofs();\n  Eigen::VectorXd cp(N);\n  for (unsigned int i = 0; i < N; ++i) {\n    cp(i) = cfct(float(i) / N);\n  }\n  Eigen::MatrixXd cn(K, K);\n  p2n.to_nodal(cn, cp);\n  Eigen::VectorXd cp2(N);\n  p2n.to_polar(cp2, cn);\n\n  auto diff = cp2;\n  diff.setZero();\n  for (unsigned int i = 0; i < N; ++i) {\n    diff(i) = std::abs(cp2(i) - cp(i));\n  }\n  cout << \" sum(err): \" << diff.sum() << endl;\n}\n\nint main(int argc, char* argv[])\n{\n  if (argc < 2) {\n    cout << \"usage: \" << argv[0] << \" K\\n\";\n    exit(1);\n  }\n  const int K = atoi(argv[1]);\n\n  cout << \"Test: P->N->P \"\n       << \"\\n\";\n  cout << \"Exponential decaying Polar-Laguerre coefficients: cp[i] = exp(-20*i/N)\"\n       << \"\\n\";\n  test2(K, [](double i) { return std::exp(-20 * i); });\n\n  cout << \"Constant coefficients: cp[i] = 1.0\"\n       << \"\\n\";\n  test2(K, [](double i) { return 1.0; });\n  return 0;\n}\n", "meta": {"hexsha": "c093071bca5eb3a01b7acfa3a26929cff238a1f0", "size": 4235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/P2N/main.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/P2N/main.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/P2N/main.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5, "max_line_length": 93, "alphanum_fraction": 0.6396694215, "num_tokens": 1405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.554311876656677}}
{"text": "\n// #include <iostream>\n// #include <string>\n// #include <boost/lexical_cast.hpp>\n// #include <fstream>\n// #include <iomanip>\n\n// #include \"quadrature/qmaxwell.hpp\"\n// #include \"quadrature/qmidpoint.hpp\"\n// #include \"quadrature/tensor_product_quadrature.hpp\"\n// #include \"quadrature/quadrature_handler.hpp\"\n\n// #include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n// #include \"matrix/assembly/velocity_radial_integrator.hpp\"\n// #include \"matrix/assembly/velocity_var_form.hpp\"\n// #include \"matrix/assembly/weight.hpp\"\n\n// #include \"spectral/laguerren.hpp\"\n// #include \"spectral/laguerrenw.hpp\"\n\n// using namespace std;\n// using namespace boltzmann;\n\n// // typedef boltzmann::QuadratureHandler<\n// //   boltzmann::TensorProductQuadratureC<boltzmann::QMidpoint, QMaxwell> > quad_type;\n\n// typedef double numeric_t;\n\n// template<typename MAP>\n// void print(const MAP& m, std::ofstream& fout, string title)\n// {\n//   fout << \"----- \" << title << endl;\n//   for (auto it = m.begin(); it != m.end(); ++it) {\n//     fout << it->first.first << \"\\t\"\n//          << it->first.second\n//          << \"\\t\"\n//          << setprecision(16) << it->second\n//          << endl;\n//   }\n// }\n\n// template<typename CONT>\n// void print_basis(const CONT& cont, std::ofstream& fout)\n// {\n//   for (int i = 0; i < cont.size(); ++i) {\n//     fout  << cont[i].get_id() << endl;\n//   }\n// }\n\n// // ----------------------------------------------------------------------\n// int main(int argc, char *argv[])\n// {\n//   const double beta = 2;\n\n//   if ( argc < 3) {\n//     cerr << \"info: \" << argv[0] << \" K q\"\n//          << endl\n//          << \"q: No. quad. points\\n\";\n//     return 1;\n//   }\n//   int K = atoi(argv[1]);\n//   int N = atoi(argv[2]);\n//   const int digits = 256;\n\n//   QMaxwell qmaxwell(1, N, digits);\n\n//   std::ofstream fout(\"quadrule_order\" + boost::lexical_cast<string>(N) + \"_\" +\n//   boost::lexical_cast<string>(digits) + \".dat\");\n//   for (unsigned int i = 0; i < qmaxwell.size(); ++i) {\n//     fout << setprecision(30) << qmaxwell.pts(i)\n//          << \"\\t\"\n//          << setprecision(30) << qmaxwell.wts(i)\n//          << endl;\n//   }\n//   fout.close();\n\n//   typedef boltzmann::SpectralBasisFactoryKS basis_factory_t;\n//   typedef typename basis_factory_t::basis_type basis_type;\n\n//   L2Weight weight(beta);\n\n//   basis_type basis;\n//   basis_factory_t::create(basis, K, K, beta);\n\n//   typedef typename std::tuple_element<1, typename basis_type::elem_t::container_t>::type rad_t;\n//   typedef typename basis_type::DimAcc::template get_vec<rad_t> accessor_t;\n\n//   const auto& radial_basis = accessor_t()(basis);\n\n//   LaguerreN<numeric_t> L(K);\n//   std::vector<numeric_t> r2(N);\n//   std::transform(qmaxwell.pts().begin(), qmaxwell.pts().end(), r2.begin(), [](double r) {return\n//   r*r;} );\n//   L.compute(r2);\n\n//   ofstream foutn(\"errors-normalized.dat\");\n//   for (auto elem = radial_basis.begin(); elem != radial_basis.end(); ++elem) {\n//     unsigned int n = elem->get_degree();\n//     unsigned int alpha = elem->get_order();\n//     unsigned int k = elem->get_id().k;\n//     unsigned int j = elem->get_id().j;\n//     const numeric_t* values = L.get(n, alpha);\n//     double I = 0;\n//     for (unsigned int q = 0; q < qmaxwell.size(); ++q) {\n//       const double r2j = std::pow(qmaxwell.pts(q), 4*j+ 2* (k%2) );\n//       I += r2j*values[q] * values[q] * qmaxwell.wts(q);\n//     }\n//     foutn << elem->get_id() << \"\\t\" << setw(30) << setprecision(20) << scientific <<\n//     std::abs(I-0.5) << endl;\n//   }\n//   foutn.close();\n\n//   ofstream foutnw(\"errors-normalized-weighted.dat\");\n//   LaguerreNW<numeric_t> LW(K);\n//   LW.compute(r2);\n//   for (auto elem = radial_basis.begin(); elem != radial_basis.end(); ++elem) {\n//     unsigned int n = elem->get_degree();\n//     unsigned int alpha = elem->get_order();\n//     unsigned int k = elem->get_id().k;\n//     unsigned int j = elem->get_id().j;\n//     const numeric_t* values = LW.get(n, alpha);\n//     double I = 0;\n//     for (unsigned int q = 0; q < qmaxwell.size(); ++q) {\n//       const double r = qmaxwell.pts(q);\n//       const double r2j = std::pow(r, 4*j+ 2* (k%2) );\n\n//       I += r2j*(values[q] * ::math::exp(r*r*0.5))* (values[q] * ::math::exp(r*r*0.5)) *\n//       qmaxwell.wts(q);\n//     }\n//     foutnw << elem->get_id() << \"\\t\" << setw(30) << setprecision(20) << scientific <<\n//     std::abs(I-0.5) << endl;\n//   }\n//   foutnw.close();\n\n//   return 0;\n// }\n", "meta": {"hexsha": "176fb369a731fff05caa00c580c3e9496ff649d1", "size": 4432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/maxwell_quadrature/main2.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/maxwell_quadrature/main2.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/maxwell_quadrature/main2.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3503649635, "max_line_length": 98, "alphanum_fraction": 0.5692689531, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5542935742226008}}
{"text": "#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <memory>\n#include <Eigen/Dense>\n#include \"../include/sample_network.h\"\n#include \"../datasets/include/mnist.h\"\n\nusing namespace Eigen;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::vector;\n    using std::string;\n    using std::unordered_map;\n    using namespace MyDL;\n\n    int num_iters = 1000;\n    double learning_rate = 0.1;\n\n    int batch_size = 100;\n    int input_size = 28 * 28;\n    int hidden_size = 50;\n    int output_size = 10;\n\n    MatrixXd train_X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd test_X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd train_y = MatrixXd::Zero(batch_size, 10);\n    MatrixXd test_y = MatrixXd::Zero(batch_size, 10);\n\n    MnistEigenDataset mnist(batch_size);\n\n    TwoLayerNet net(input_size, hidden_size, output_size);\n\n    vector<MatrixXd> inputs, loss, val_inputs;\n    unordered_map<string, MatrixXd> grads;\n    double accuracy;\n\n    mnist.next_train(train_X, train_y, true);\n    inputs.push_back(train_X);\n    inputs.push_back(train_y);\n\n    grads = net.gradient(inputs);\n\n    // cout << \"--- parameter b1 ---\" << endl;\n    // cout << *(net.params[\"b1\"]) << endl;\n    // cout << \"--- parameter b1 update ---\" << endl;\n    // *(net.params[\"b1\"]) -= -learning_rate * grads[\"b1\"];\n    // MatrixXd dParam = grads[\"b1\"];\n    // *(net.params[\"b1\"]) -= -learning_rate * dParam;\n    // cout << *(net.params[\"b1\"]) << endl;\n    // cout << dParam << endl;\n    // *(net.params[\"b1\"]) -= MatrixXd::Ones(1, hidden_size); // こちらは更新される->gradsによる更新がおかしい？\n    // cout << *(net.params[\"b1\"]) << endl;\n\n    cout << \"--- parameter b1 ---\" << endl;\n    cout << net.params[\"b1\"] << endl;\n    cout << \"--- parameter b1 update ---\" << endl;\n    net.params[\"b1\"] -= -learning_rate * grads[\"b1\"];\n\n    MatrixXd dParam = grads[\"b1\"];\n    net.params[\"b1\"] -= -learning_rate * dParam;\n    cout << net.params[\"b1\"] << endl;\n    cout << dParam << endl;\n    net.params[\"b1\"] -= MatrixXd::Ones(1, hidden_size); // こちらは更新される->gradsによる更新がおかしい？\n    cout << net.params[\"b1\"] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "e056c135e41a64efeeb80a4e0362a494a139e36a", "size": 2134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_train_two_layer_net.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "test/test_train_two_layer_net.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_train_two_layer_net.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6388888889, "max_line_length": 92, "alphanum_fraction": 0.6152764761, "num_tokens": 615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.5542935534441783}}
{"text": "// Kolmogorov-Smirnov 1st order asymptotic distribution\n// Copyright Evan Miller 2020\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// The Kolmogorov-Smirnov test in statistics compares two empirical distributions,\n// or an empirical distribution against any theoretical distribution. It makes\n// use of a specific distribution which doesn't have a formal name, but which\n// is often called the Kolmogorv-Smirnov distribution for lack of anything\n// better. This file implements the limiting form of this distribution, first\n// identified by Andrey Kolmogorov in\n//\n// Kolmogorov, A. (1933) \"Sulla Determinazione Empirica di una Legge di\n// Distribuzione.\" Giornale dell' Istituto Italiano degli Attuari\n//\n// This limiting form of the CDF is a first-order Taylor expansion that is\n// easily implemented by the fourth Jacobi Theta function (setting z=0). The\n// PDF is then implemented here as a derivative of the Theta function. Note\n// that this derivative is with respect to x, which enters into \\tau, and not\n// with respect to the z argument, which is always zero, and so the derivative\n// identities in DLMF 20.4 do not apply here.\n//\n// A higher order order expansion is possible, and was first outlined by\n//\n// Pelz W, Good IJ (1976). \"Approximating the Lower Tail-Areas of the\n// Kolmogorov-Smirnov One-sample Statistic.\" Journal of the Royal Statistical\n// Society B.\n//\n// The terms in this expansion get fairly complicated, and as far as I know the\n// Pelz-Good expansion is not used in any statistics software. Someone could\n// consider updating this implementation to use the Pelz-Good expansion in the\n// future, but the math gets considerably hairier with each additional term.\n//\n// A formula for an exact version of the Kolmogorov-Smirnov test is laid out in\n// Equation 2.4.4 of\n//\n// Durbin J (1973). \"Distribution Theory for Tests Based on the Sample\n// Distribution Func- tion.\" In SIAM CBMS-NSF Regional Conference Series in\n// Applied Mathematics. SIAM, Philadelphia, PA.\n//\n// which is available in book form from Amazon and others. This exact version\n// involves taking powers of large matrices. To do that right you need to\n// compute eigenvalues and eigenvectors, which are beyond the scope of Boost.\n// (Some recent work indicates the exact form can also be computed via FFT, see\n// https://cran.r-project.org/web/packages/KSgeneral/KSgeneral.pdf).\n//\n// Even if the CDF of the exact distribution could be computed using Boost\n// libraries (which would be cumbersome), the PDF would present another\n// difficulty. Therefore I am limiting this implementation to the asymptotic\n// form, even though the exact form has trivial values for certain specific\n// values of x and n. For more on trivial values see\n//\n// Ruben H, Gambino J (1982). \"The Exact Distribution of Kolmogorov's Statistic\n// Dn for n <= 10.\" Annals of the Institute of Statistical Mathematics.\n// \n// For a good bibliography and overview of the various algorithms, including\n// both exact and asymptotic forms, see\n// https://www.jstatsoft.org/article/view/v039i11\n//\n// As for this implementation: the distribution is parameterized by n (number\n// of observations) in the spirit of chi-squared's degrees of freedom. It then\n// takes a single argument x. In terms of the Kolmogorov-Smirnov statistical\n// test, x represents the distribution of D_n, where D_n is the maximum\n// difference between the CDFs being compared, that is,\n//\n//   D_n = sup|F_n(x) - G(x)|\n//\n// In the exact distribution, x is confined to the support [0, 1], but in this\n// limiting approximation, we allow x to exceed unity (similar to how a normal\n// approximation always spills over any boundaries).\n//\n// As mentioned previously, the CDF is implemented using the \\tau\n// parameterization of the fourth Jacobi Theta function as\n//\n// CDF=theta_4(0|2*x*x*n/pi)\n//\n// The PDF is a hand-coded derivative of that function. Actually, there are two\n// (independent) derivatives, as separate code paths are used for \"small x\"\n// (2*x*x*n < pi) and \"large x\", mirroring the separate code paths in the\n// Jacobi Theta implementation to achieve fast convergence. Quantiles are\n// computed using a Newton-Raphson iteration from an initial guess that I\n// arrived at by trial and error.\n//\n// The mean and variance are implemented using simple closed-form expressions.\n// Skewness and kurtosis use slightly more complicated closed-form expressions\n// that involve the zeta function. The mode is calculated at run-time by\n// maximizing the PDF. If you have an analytical solution for the mode, feel\n// free to plop it in.\n//\n// The CDF and PDF could almost certainly be re-implemented and sped up using a\n// polynomial or rational approximation, since the only meaningful argument is\n// x * sqrt(n). But that is left as an exercise for the next maintainer.\n//\n// In the future, the Pelz-Good approximation could be added. I suggest adding\n// a second parameter representing the order, e.g.\n//\n// kolmogorov_smirnov_dist<>(100) // N=100, order=1\n// kolmogorov_smirnov_dist<>(100, 1) // N=100, order=1, i.e. Kolmogorov's formula\n// kolmogorov_smirnov_dist<>(100, 4) // N=100, order=4, i.e. Pelz-Good formula\n//\n// The exact distribution could be added to the API with a special order\n// parameter (e.g. 0 or infinity), or a separate distribution type altogether\n// (e.g. kolmogorov_smirnov_exact_distribution).\n//\n#ifndef BOOST_MATH_DISTRIBUTIONS_KOLMOGOROV_SMIRNOV_HPP\n#define BOOST_MATH_DISTRIBUTIONS_KOLMOGOROV_SMIRNOV_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/special_functions/jacobi_theta.hpp>\n#include <boost/math/tools/tuple.hpp>\n#include <boost/math/tools/roots.hpp> // Newton-Raphson\n#include <boost/math/tools/minima.hpp> // For the mode\n\nnamespace boost { namespace math {\n\nnamespace detail {\ntemplate <class RealType>\ninline RealType kolmogorov_smirnov_quantile_guess(RealType p) {\n    // Choose a starting point for the Newton-Raphson iteration\n    if (p > 0.9)\n        return RealType(1.8) - 5 * (1 - p);\n    if (p < 0.3)\n        return p + RealType(0.45);\n    return p + RealType(0.3);\n}\n\n// d/dk (theta2(0, 1/(2*k*k/M_PI))/sqrt(2*k*k*M_PI))\ntemplate <class RealType, class Policy>\nRealType kolmogorov_smirnov_pdf_small_x(RealType x, RealType n, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType value = RealType(0), delta = RealType(0), last_delta = RealType(0);\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    int i = 0;\n    RealType pi2 = constants::pi_sqr<RealType>();\n    RealType x2n = x*x*n;\n    if (x2n*x2n == 0.0) {\n        return static_cast<RealType>(0);\n    }\n    while (1) {\n        delta = exp(-RealType(i+0.5)*RealType(i+0.5)*pi2/(2*x2n)) * (RealType(i+0.5)*RealType(i+0.5)*pi2 - x2n);\n\n        if (delta == 0.0)\n            break;\n\n        if (last_delta != 0.0 && fabs(delta/last_delta) < eps)\n            break;\n\n        value += delta + delta;\n        last_delta = delta;\n        i++;\n    }\n\n    return value * sqrt(n) * constants::root_half_pi<RealType>() / (x2n*x2n);\n}\n\n// d/dx (theta4(0, 2*x*x*n/M_PI))\ntemplate <class RealType, class Policy>\ninline RealType kolmogorov_smirnov_pdf_large_x(RealType x, RealType n, const Policy&) {\n    BOOST_MATH_STD_USING\n    RealType value = RealType(0), delta = RealType(0), last_delta = RealType(0);\n    RealType eps = policies::get_epsilon<RealType, Policy>();\n    int i = 1;\n    while (1) {\n        delta = 8*x*i*i*exp(-2*i*i*x*x*n);\n\n        if (delta == 0.0)\n            break;\n\n        if (last_delta != 0.0 && fabs(delta / last_delta) < eps)\n            break;\n\n        if (i%2 == 0)\n            delta = -delta;\n\n        value += delta;\n        last_delta = delta;\n        i++;\n    }\n\n    return value * n;\n}\n\n}; // detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\n    class kolmogorov_smirnov_distribution\n{\n    public:\n        typedef RealType value_type;\n        typedef Policy policy_type;\n\n        // Constructor\n    kolmogorov_smirnov_distribution( RealType n ) : n_obs_(n)\n    {\n        RealType result;\n        detail::check_df(\n                \"boost::math::kolmogorov_smirnov_distribution<%1%>::kolmogorov_smirnov_distribution\", n_obs_, &result, Policy());\n    }\n\n    RealType number_of_observations()const\n    {\n        return n_obs_;\n    }\n\n    private:\n\n    RealType n_obs_; // positive integer\n};\n\ntypedef kolmogorov_smirnov_distribution<double> kolmogorov_k; // Convenience typedef for double version.\n\n#ifdef __cpp_deduction_guides\ntemplate <class RealType>\nkolmogorov_smirnov_distribution(RealType)->kolmogorov_smirnov_distribution<typename boost::math::tools::promote_args<RealType>::type>;\n#endif\n\nnamespace detail {\ntemplate <class RealType, class Policy>\nstruct kolmogorov_smirnov_quantile_functor\n{\n  kolmogorov_smirnov_quantile_functor(const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> dist, RealType const& p)\n    : distribution(dist), prob(p)\n  {\n  }\n\n  boost::math::tuple<RealType, RealType> operator()(RealType const& x)\n  {\n    RealType fx = cdf(distribution, x) - prob;  // Difference cdf - value - to minimize.\n    RealType dx = pdf(distribution, x); // pdf is 1st derivative.\n    // return both function evaluation difference f(x) and 1st derivative f'(x).\n    return boost::math::make_tuple(fx, dx);\n  }\nprivate:\n  const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> distribution;\n  RealType prob;\n};\n\ntemplate <class RealType, class Policy>\nstruct kolmogorov_smirnov_complementary_quantile_functor\n{\n  kolmogorov_smirnov_complementary_quantile_functor(const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> dist, RealType const& p)\n    : distribution(dist), prob(p)\n  {\n  }\n\n  boost::math::tuple<RealType, RealType> operator()(RealType const& x)\n  {\n    RealType fx = cdf(complement(distribution, x)) - prob;  // Difference cdf - value - to minimize.\n    RealType dx = -pdf(distribution, x); // pdf is the negative of the derivative of (1-CDF)\n    // return both function evaluation difference f(x) and 1st derivative f'(x).\n    return boost::math::make_tuple(fx, dx);\n  }\nprivate:\n  const boost::math::kolmogorov_smirnov_distribution<RealType, Policy> distribution;\n  RealType prob;\n};\n\ntemplate <class RealType, class Policy>\nstruct kolmogorov_smirnov_negative_pdf_functor\n{\n    RealType operator()(RealType const& x) {\n        if (2*x*x < constants::pi<RealType>()) {\n            return -kolmogorov_smirnov_pdf_small_x(x, static_cast<RealType>(1), Policy());\n        }\n        return -kolmogorov_smirnov_pdf_large_x(x, static_cast<RealType>(1), Policy());\n    }\n};\n} // namespace detail\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const kolmogorov_smirnov_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const kolmogorov_smirnov_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   // In the exact distribution, the upper limit would be 1.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   BOOST_MATH_STD_USING  // for ADL of std functions.\n\n   RealType n = dist.number_of_observations();\n   RealType error_result;\n   static const char* function = \"boost::math::pdf(const kolmogorov_smirnov_distribution<%1%>&, %1%)\";\n   if(false == detail::check_x_not_NaN(function, x, &error_result, Policy()))\n      return error_result;\n\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n\n   if (x < 0 || !(boost::math::isfinite)(x))\n   {\n      return policies::raise_domain_error<RealType>(\n         function, \"Kolmogorov-Smirnov parameter was %1%, but must be > 0 !\", x, Policy());\n   }\n\n   if (2*x*x*n < constants::pi<RealType>()) {\n       return detail::kolmogorov_smirnov_pdf_small_x(x, n, Policy());\n   }\n\n   return detail::kolmogorov_smirnov_pdf_large_x(x, n, Policy());\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& x)\n{\n    BOOST_MATH_STD_USING // for ADL of std function exp.\n   static const char* function = \"boost::math::cdf(const kolmogorov_smirnov_distribution<%1%>&, %1%)\";\n   RealType error_result;\n   RealType n = dist.number_of_observations();\n   if(false == detail::check_x_not_NaN(function, x, &error_result, Policy()))\n      return error_result;\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n   if((x < 0) || !(boost::math::isfinite)(x)) {\n      return policies::raise_domain_error<RealType>(\n         function, \"Random variable parameter was %1%, but must be between > 0 !\", x, Policy());\n   }\n\n   if (x*x*n == 0)\n       return 0;\n\n   return jacobi_theta4tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy());\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<kolmogorov_smirnov_distribution<RealType, Policy>, RealType>& c) {\n    BOOST_MATH_STD_USING // for ADL of std function exp.\n    RealType x = c.param;\n   static const char* function = \"boost::math::cdf(const complemented2_type<const kolmogorov_smirnov_distribution<%1%>&, %1%>)\";\n   RealType error_result;\n   kolmogorov_smirnov_distribution<RealType, Policy> const& dist = c.dist;\n   RealType n = dist.number_of_observations();\n\n   if(false == detail::check_x_not_NaN(function, x, &error_result, Policy()))\n      return error_result;\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n\n   if((x < 0) || !(boost::math::isfinite)(x))\n      return policies::raise_domain_error<RealType>(\n         function, \"Random variable parameter was %1%, but must be between > 0 !\", x, Policy());\n\n   if (x*x*n == 0)\n       return 1;\n\n   if (2*x*x*n > constants::pi<RealType>())\n       return -jacobi_theta4m1tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy());\n\n   return RealType(1) - jacobi_theta4tau(RealType(0), 2*x*x*n/constants::pi<RealType>(), Policy());\n} // cdf (complemented)\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const kolmogorov_smirnov_distribution<RealType, Policy>& dist, const RealType& p)\n{\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::quantile(const kolmogorov_smirnov_distribution<%1%>&, %1%)\";\n   // Error check:\n   RealType error_result;\n   RealType n = dist.number_of_observations();\n   if(false == detail::check_probability(function, p, &error_result, Policy()))\n      return error_result;\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n\n   RealType k = detail::kolmogorov_smirnov_quantile_guess(p) / sqrt(n);\n   const int get_digits = policies::digits<RealType, Policy>();// get digits from policy,\n   std::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations.\n\n   return tools::newton_raphson_iterate(detail::kolmogorov_smirnov_quantile_functor<RealType, Policy>(dist, p),\n           k, RealType(0), boost::math::tools::max_value<RealType>(), get_digits, m);\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<kolmogorov_smirnov_distribution<RealType, Policy>, RealType>& c) {\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::quantile(const kolmogorov_smirnov_distribution<%1%>&, %1%)\";\n   kolmogorov_smirnov_distribution<RealType, Policy> const& dist = c.dist;\n   RealType n = dist.number_of_observations();\n   // Error check:\n   RealType error_result;\n   RealType p = c.param;\n\n   if(false == detail::check_probability(function, p, &error_result, Policy()))\n      return error_result;\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n\n   RealType k = detail::kolmogorov_smirnov_quantile_guess(RealType(1-p)) / sqrt(n);\n\n   const int get_digits = policies::digits<RealType, Policy>();// get digits from policy,\n   std::uintmax_t m = policies::get_max_root_iterations<Policy>(); // and max iterations.\n\n   return tools::newton_raphson_iterate(\n           detail::kolmogorov_smirnov_complementary_quantile_functor<RealType, Policy>(dist, p),\n           k, RealType(0), boost::math::tools::max_value<RealType>(), get_digits, m);\n} // quantile (complemented)\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::mode(const kolmogorov_smirnov_distribution<%1%>&)\";\n   RealType n = dist.number_of_observations();\n   RealType error_result;\n   if(false == detail::check_df(function, n, &error_result, Policy()))\n      return error_result;\n\n    std::pair<RealType, RealType> r = boost::math::tools::brent_find_minima(\n            detail::kolmogorov_smirnov_negative_pdf_functor<RealType, Policy>(),\n            static_cast<RealType>(0), static_cast<RealType>(1), policies::digits<RealType, Policy>());\n    return r.first / sqrt(n);\n}\n\n// Mean and variance come directly from\n// https://www.jstatsoft.org/article/view/v008i18 Section 3\ntemplate <class RealType, class Policy>\ninline RealType mean(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::mean(const kolmogorov_smirnov_distribution<%1%>&)\";\n    RealType n = dist.number_of_observations();\n    RealType error_result;\n    if(false == detail::check_df(function, n, &error_result, Policy()))\n        return error_result;\n    return constants::root_half_pi<RealType>() * constants::ln_two<RealType>() / sqrt(n);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType variance(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n   static const char* function = \"boost::math::variance(const kolmogorov_smirnov_distribution<%1%>&)\";\n    RealType n = dist.number_of_observations();\n    RealType error_result;\n    if(false == detail::check_df(function, n, &error_result, Policy()))\n        return error_result;\n    return (constants::pi_sqr_div_six<RealType>()\n            - constants::pi<RealType>() * constants::ln_two<RealType>() * constants::ln_two<RealType>()) / (2*n);\n}\n\n// Skewness and kurtosis come from integrating the PDF\n// The alternating series pops out a Dirichlet eta function which is related to the zeta function\ntemplate <class RealType, class Policy>\ninline RealType skewness(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::skewness(const kolmogorov_smirnov_distribution<%1%>&)\";\n    RealType n = dist.number_of_observations();\n    RealType error_result;\n    if(false == detail::check_df(function, n, &error_result, Policy()))\n        return error_result;\n    RealType ex3 = RealType(0.5625) * constants::root_half_pi<RealType>() * constants::zeta_three<RealType>() / n / sqrt(n);\n    RealType mean = boost::math::mean(dist);\n    RealType var = boost::math::variance(dist);\n    return (ex3 - 3 * mean * var - mean * mean * mean) / var / sqrt(var);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n    BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::kurtosis(const kolmogorov_smirnov_distribution<%1%>&)\";\n    RealType n = dist.number_of_observations();\n    RealType error_result;\n    if(false == detail::check_df(function, n, &error_result, Policy()))\n        return error_result;\n    RealType ex4 = 7 * constants::pi_sqr_div_six<RealType>() * constants::pi_sqr_div_six<RealType>() / 20 / n / n;\n    RealType mean = boost::math::mean(dist);\n    RealType var = boost::math::variance(dist);\n    RealType skew = boost::math::skewness(dist);\n    return (ex4 - 4 * mean * skew * var * sqrt(var) - 6 * mean * mean * var - mean * mean * mean * mean) / var / var;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const kolmogorov_smirnov_distribution<RealType, Policy>& dist)\n{\n   static const char* function = \"boost::math::kurtosis_excess(const kolmogorov_smirnov_distribution<%1%>&)\";\n    RealType n = dist.number_of_observations();\n    RealType error_result;\n    if(false == detail::check_df(function, n, &error_result, Policy()))\n        return error_result;\n    return kurtosis(dist) - 3;\n}\n}}\n#endif\n", "meta": {"hexsha": "fd6a2350f3aeb6abf05e610c00ff2c67d4c9e6a8", "size": 21161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/kolmogorov_smirnov.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/kolmogorov_smirnov.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/kolmogorov_smirnov.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.322, "max_line_length": 145, "alphanum_fraction": 0.7162232409, "num_tokens": 5653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672181749422, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5542932731049599}}
{"text": "\n// solving A * X = B\n// A hermitian in packed storage\n// driver function hesv()\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/driver/hpsv.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/hermitian.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<cmplx_t, ublas::column_major> cm_t;\ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::lower, ublas::column_major> cherml_t;\ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::upper, ublas::column_major> chermu_t;\n\n\nint main() {\n\n  cherml_t hcal (3, 3);   // hermitian matrix\n  chermu_t hcau (3, 3);   // hermitian matrix \n  cm_t cx (3, 1);\n  cm_t cbl (3, 1), cbu (3, 1);  // RHS\n\n  std::vector<fortran_int_t> ipiv (3);\n\n  hcal (0, 0) = cmplx_t (3, 0);\n  hcal (1, 0) = cmplx_t (4, -2);\n  hcal (1, 1) = cmplx_t (5, 0);\n  hcal (2, 0) = cmplx_t (-7, -5);\n  hcal (2, 1) = cmplx_t (0, 3);\n  hcal (2, 2) = cmplx_t (2, 0);\n\n  hcau (0, 0) = cmplx_t (3, 0);\n  hcau (0, 1) = cmplx_t (4, 2);\n  hcau (0, 2) = cmplx_t (-7, 5);\n  hcau (1, 1) = cmplx_t (5, 0);\n  hcau (1, 2) = cmplx_t (0, -3);\n  hcau (2, 2) = cmplx_t (2, 0);\n\n  print_m (hcal, \"hcal\"); \n  cout << endl; \n  print_m (hcau, \"hcau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (hcal, cx);\n  cbu = prod (hcau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n//  int ierr = lapack::hpsv (hcal, cbl);\n//  no ipiv less version is currently provided, so fall back to using ipiv\n  int ierr = lapack::hpsv (hcal, ipiv, cbl);\n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  ierr = lapack::hpsv (hcau, ipiv, cbu); \n  if (ierr == 0) {\n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu, \"cxu\"); \n  }\n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n}\n\n", "meta": {"hexsha": "b1cb2e854fae71708c96a12a9f86cfd178d829eb", "size": 2317, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_hpsv.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_hpsv.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_hpsv.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.6489361702, "max_line_length": 79, "alphanum_fraction": 0.597324126, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.5542932687810881}}
{"text": "// Copyright (c) 2009 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 <cmath>\n#include <limits>\n\n#include <Eigen/SVD>\n#include <Eigen/Geometry>\n\n#include \"libmv/base/vector.h\"\n#include \"libmv/logging/logging.h\"\n#include \"libmv/multiview/euclidean_resection.h\"\n#include \"libmv/multiview/projection.h\"\n\nnamespace libmv {\nnamespace euclidean_resection {\n\nbool EuclideanResection(const Mat2X &x_camera, \n                        const Mat3X &X_world,\n                        Mat3 *R, Vec3 *t,\n                        ResectionMethod method) {\n  switch (method) {\n    case RESECTION_ANSAR_DANIILIDIS:\n      EuclideanResectionAnsarDaniilidis(x_camera, X_world, R, t);\n      break;\n    case RESECTION_EPNP:\n      return EuclideanResectionEPnP(x_camera, X_world, R, t);      \n      break;\n    default:\n      LOG(FATAL) << \"Unknown resection method.\";\n  }\n  return false;\n}\n\nbool EuclideanResection(const Mat &x_image, \n                        const Mat3X &X_world,\n                        const Mat3 &K,\n                        Mat3 *R, Vec3 *t,\n                        ResectionMethod method) {\n  CHECK(x_image.rows() == 2 || x_image.rows() == 3)\n    << \"Invalid size for x_image: \"\n    << x_image.rows() << \"x\" << x_image.cols();\n\n  Mat2X x_camera;\n  if (x_image.rows() == 2) {\n    EuclideanToNormalizedCamera(x_image, K, &x_camera);\n  } else if (x_image.rows() == 3) {\n    HomogeneousToNormalizedCamera(x_image, K, &x_camera);\n  }\n  return EuclideanResection(x_camera, X_world, R, t, method);\n}\n\nvoid AbsoluteOrientation(const Mat3X &X,\n                         const Mat3X &Xp,\n                         Mat3 *R,\n                         Vec3 *t) {\n  int num_points = X.cols();\n  Vec3 C  = X.rowwise().sum() / num_points;   // Centroid of X.\n  Vec3 Cp = Xp.rowwise().sum() / num_points;  // Centroid of Xp.\n\n  // Normalize the two point sets.\n  Mat3X Xn(3, num_points), Xpn(3, num_points);\n  for( int i = 0; i < num_points; ++i ){\n    Xn.col(i)  = X.col(i) - C;\n    Xpn.col(i) = Xp.col(i) - Cp;\n  }\n  \n  // Construct the N matrix (pg. 635).\n  double Sxx = Xn.row(0).dot(Xpn.row(0));\n  double Syy = Xn.row(1).dot(Xpn.row(1));\n  double Szz = Xn.row(2).dot(Xpn.row(2));\n  double Sxy = Xn.row(0).dot(Xpn.row(1));\n  double Syx = Xn.row(1).dot(Xpn.row(0));\n  double Sxz = Xn.row(0).dot(Xpn.row(2));\n  double Szx = Xn.row(2).dot(Xpn.row(0));\n  double Syz = Xn.row(1).dot(Xpn.row(2));\n  double Szy = Xn.row(2).dot(Xpn.row(1));\n\n  Mat4 N;\n  N << Sxx + Syy + Szz, Syz - Szy,        Szx - Sxz,        Sxy - Syx,\n       Syz - Szy,       Sxx - Syy - Szz,  Sxy + Syx,        Szx + Sxz,\n       Szx - Sxz,       Sxy + Syx,       -Sxx + Syy - Szz,  Syz + Szy,\n       Sxy - Syx,       Szx + Sxz,        Syz + Szy,       -Sxx - Syy + Szz;\n           \n  // Find the unit quaternion q that maximizes qNq. It is the eigenvector\n  // corresponding to the lagest eigenvalue.\n  Vec4 q = N.jacobiSvd(Eigen::ComputeFullU).matrixU().col(0);\n\n  // Retrieve the 3x3 rotation matrix.\n  Vec4 qq = q.array() * q.array();\n  double q0q1 = q(0) * q(1);\n  double q0q2 = q(0) * q(2);\n  double q0q3 = q(0) * q(3);\n  double q1q2 = q(1) * q(2);\n  double q1q3 = q(1) * q(3);\n  double q2q3 = q(2) * q(3);\n\n  (*R) << qq(0) + qq(1) - qq(2) - qq(3),\n          2 * (q1q2 - q0q3),\n          2 * (q1q3 + q0q2),\n          2 * (q1q2+ q0q3),\n          qq(0) - qq(1) + qq(2) - qq(3),\n          2 * (q2q3 - q0q1),\n          2 * (q1q3 - q0q2),\n          2 * (q2q3 + q0q1),\n          qq(0) - qq(1) - qq(2) + qq(3);\n\n  // Fix the handedness of the R matrix.\n  if (R->determinant() < 0) {\n    R->row(2) = -R->row(2);\n  }\n  // Compute the final translation.\n  *t = Cp - *R * C;\n}\n\n// Convert i and j indices of the original variables into their quadratic\n// permutation single index. It follows that t_ij = t_ji.\nstatic int IJToPointIndex(int i, int j, int num_points) {\n  // Always make sure that j is bigger than i. This handles t_ij = t_ji.\n  if (j < i) {\n    std::swap(i, j);\n  }\n  int idx;\n  int num_permutation_rows = num_points * (num_points - 1) / 2;\n\n  // All t_ii's are located at the end of the t vector after all t_ij's.\n  if (j == i) {\n    idx = num_permutation_rows + i;\n  } else {\n    int offset = (num_points - i - 1) * (num_points - i) / 2;\n    idx = (num_permutation_rows - offset + j - i - 1);\n  }\n  return idx;\n};\n\n// Convert i and j indexes of the solution for lambda to their linear indexes.\nstatic int IJToIndex(int i, int j, int num_lambda) {\n  if (j < i) {\n    std::swap(i, j);\n  }\n  int A = num_lambda * (num_lambda + 1) / 2;\n  int B = num_lambda - i;\n  int C = B * (B + 1) / 2;\n  int idx = A - C + j - i;\n  return idx;\n};\n\nstatic int Sign(double value) {\n  return (value < 0) ? -1 : 1;\n};\n\n// Organizes a square matrix into a single row constraint on the elements of\n// Lambda to create the constraints in equation (5) in \"Linear Pose Estimation\n// from Points or Lines\", by Ansar, A. and Daniilidis, PAMI 2003. vol. 25, no.\n// 5.\nstatic Vec MatrixToConstraint(const Mat &A,\n                              int num_k_columns,\n                              int num_lambda) {\n  Vec C(num_k_columns);\n  C.setZero();\n  int idx = 0;\n  for (int i = 0; i < num_lambda; ++i) {\n    for( int j = i; j < num_lambda; ++j) {\n      C(idx) = A(i, j);\n      if (i != j){\n        C(idx) += A(j, i);\n      }\n      ++ idx;\n    }\n  }\n  return C;\n}\n\n// Normalizes the columns of vectors.\nstatic void NormalizeColumnVectors(Mat3X *vectors) {\n  int num_columns = vectors->cols();\n  for (int i = 0; i < num_columns; ++i){\n    vectors->col(i).normalize();\n  }\n}\n\nvoid EuclideanResectionAnsarDaniilidis(const Mat2X &x_camera, \n                                       const Mat3X &X_world,               \n                                       Mat3 *R, \n                                       Vec3 *t) {\n  CHECK(x_camera.cols() == X_world.cols());\n  CHECK(x_camera.cols() > 3);\n\n  int num_points = x_camera.cols();\n\n  // Copy the normalized camera coords into 3 vectors and normalize them so\n  // that they are unit vectors from the camera center.\n  Mat3X x_camera_unit(3, num_points);\n  x_camera_unit.block(0, 0, 2, num_points) = x_camera;\n  x_camera_unit.row(2).setOnes();\n  NormalizeColumnVectors(&x_camera_unit);\n  \n  int num_m_rows = num_points * (num_points - 1) / 2;\n  int num_tt_variables = num_points * (num_points + 1) / 2;\n  int num_m_columns = num_tt_variables + 1;\n  Mat M(num_m_columns, num_m_columns);\n  M.setZero();\n  Matu ij_index(num_tt_variables, 2);\n\n  // Create the constraint equations for the t_ij variables (7) and arrange\n  // them into the M matrix (8). Also store the initial (i, j) indices.\n  int row=0;\n  for (int i = 0; i < num_points; ++i) {\n    for (int j = i+1; j < num_points; ++j) {\n      M(row, row) = -2 * x_camera_unit.col(i).dot(x_camera_unit.col(j));\n      M(row, num_m_rows + i) = x_camera_unit.col(i).dot(x_camera_unit.col(i));\n      M(row, num_m_rows + j) = x_camera_unit.col(j).dot(x_camera_unit.col(j));\n      Vec3 Xdiff = X_world.col(i) - X_world.col(j);\n      double center_to_point_distance = Xdiff.norm();\n      M(row, num_m_columns - 1) =\n          - center_to_point_distance * center_to_point_distance;\n      ij_index(row, 0) = i;\n      ij_index(row, 1) = j;\n      ++row;\n    }\n    ij_index(i + num_m_rows, 0) = i;\n    ij_index(i + num_m_rows, 1) = i;\n  }\n\n  int num_lambda = num_points + 1;  // Dimension of the null space of M.\n  Mat V = M.jacobiSvd(Eigen::ComputeFullV).matrixV().block(0, \n                                                           num_m_rows,\n                                                           num_m_columns,\n                                                           num_lambda);\n\n  // TODO(vess): The number of constraint equations in K (num_k_rows) must be\n  // (num_points + 1) * (num_points + 2)/2. This creates a performance issue\n  // for more than 4 points. It is fine for 4 points at the moment with 18\n  // instead of 15 equations.\n  int num_k_rows = num_m_rows + num_points *\n                   (num_points*(num_points-1)/2 - num_points+1);\n  int num_k_columns = num_lambda * (num_lambda + 1) / 2;\n  Mat K(num_k_rows, num_k_columns);\n  K.setZero();\n\n  // Construct the first part of the K matrix corresponding to (t_ii, t_jk) for\n  // i != j.\n  int counter_k_row = 0;\n  for (int idx1 = num_m_rows; idx1 < num_tt_variables; ++idx1) {\n    for (int idx2 = 0; idx2 < num_m_rows; ++idx2) {\n\n      unsigned int i = ij_index(idx1, 0);\n      unsigned int j = ij_index(idx2, 0);\n      unsigned int k = ij_index(idx2, 1);\n\n      if( i != j && i != k ){\n        int idx3 = IJToPointIndex(i, j, num_points);\n        int idx4 = IJToPointIndex(i, k, num_points);\n\n        K.row(counter_k_row) =\n            MatrixToConstraint(V.row(idx1).transpose() * V.row(idx2)-\n                               V.row(idx3).transpose() * V.row(idx4),\n                               num_k_columns,\n                               num_lambda);\n        ++counter_k_row;\n      }\n    }\n  }\n\n  // Construct the second part of the K matrix corresponding to (t_ii,t_jk) for\n  // j==k.\n  for (int idx1 = num_m_rows; idx1 < num_tt_variables; ++idx1) {\n    for (int idx2 = idx1 + 1; idx2 < num_tt_variables; ++idx2) {\n      unsigned int i = ij_index(idx1, 0);\n      unsigned int j = ij_index(idx2, 0);\n      unsigned int k = ij_index(idx2, 1);\n\n      int idx3 = IJToPointIndex(i, j, num_points);\n      int idx4 = IJToPointIndex(i, k, num_points);\n\n      K.row(counter_k_row) =\n          MatrixToConstraint(V.row(idx1).transpose() * V.row(idx2)-\n                             V.row(idx3).transpose() * V.row(idx4),\n                             num_k_columns,\n                             num_lambda);\n      ++counter_k_row;\n    }\n  }\n  Vec L_sq = K.jacobiSvd(Eigen::ComputeFullV).matrixV().col(num_k_columns - 1);\n\n  // Pivot on the largest element for numerical stability. Afterwards recover\n  // the sign of the lambda solution.\n  double max_L_sq_value = fabs(L_sq(IJToIndex(0, 0, num_lambda)));\n  int max_L_sq_index = 1;\n  for (int i = 1; i < num_lambda; ++i) {\n    double abs_sq_value = fabs(L_sq(IJToIndex(i, i, num_lambda)));\n    if (max_L_sq_value < abs_sq_value) {\n      max_L_sq_value = abs_sq_value;\n      max_L_sq_index = i;\n    }\n  }\n  // Ensure positiveness of the largest value corresponding to lambda_ii.\n  L_sq = L_sq * Sign(L_sq(IJToIndex(max_L_sq_index,\n                                    max_L_sq_index,\n                                    num_lambda)));\n  \n  \n  Vec L(num_lambda);\n  L(max_L_sq_index) = sqrt(L_sq(IJToIndex(max_L_sq_index,\n                                          max_L_sq_index,\n                                          num_lambda)));\n  \n  for (int i = 0; i < num_lambda; ++i) {\n    if (i != max_L_sq_index) {\n      L(i) = L_sq(IJToIndex(max_L_sq_index, i, num_lambda)) / L(max_L_sq_index);\n    }\n  }\n\n  // Correct the scale using the fact that the last constraint is equal to 1.\n  L = L / (V.row(num_m_columns - 1).dot(L));\n  Vec X = V * L;\n  \n  // Recover the distances from the camera center to the 3D points Q.\n  Vec d(num_points);\n  d.setZero();\n  for (int c_point = num_m_rows; c_point < num_tt_variables; ++c_point) {\n    d(c_point - num_m_rows) = sqrt(X(c_point));\n  }\n\n  // Create the 3D points in the camera system.\n  Mat X_cam(3, num_points);\n  for (int c_point = 0; c_point < num_points; ++c_point ) {\n    X_cam.col(c_point) = d(c_point) * x_camera_unit.col(c_point);\n  }\n  // Recover the camera translation and rotation.\n  AbsoluteOrientation(X_world, X_cam, R, t);\n}\n\n// Selects 4 virtual control points using mean and PCA.\nvoid SelectControlPoints(const Mat3X &X_world, \n                         Mat *X_centered, \n                         Mat34 *X_control_points) {\n  size_t num_points = X_world.cols();\n\n  // The first virtual control point, C0, is the centroid.\n  Vec mean, variance;\n  MeanAndVarianceAlongRows(X_world, &mean, &variance);\n  X_control_points->col(0) = mean;\n\n  // Computes PCA\n  X_centered->resize (3, num_points);\n  for (size_t c = 0; c < num_points; c++) {\n    X_centered->col(c) = X_world.col (c) - mean;\n  }\n  Mat3 X_centered_sq = (*X_centered) * X_centered->transpose();\n  Eigen::JacobiSVD<Mat3> X_centered_sq_svd(X_centered_sq, Eigen::ComputeFullU);\n  Vec3 w = X_centered_sq_svd.singularValues();\n  Mat3 u = X_centered_sq_svd.matrixU();\n  for (size_t c = 0; c < 3; c++) {\n    double k = sqrt (w (c) / num_points);\n    X_control_points->col (c + 1) = mean + k * u.col (c);\n  }\n}\n\n// Computes the barycentric coordinates for all real points\nvoid ComputeBarycentricCoordinates(const Mat3X &X_world_centered, \n                                   const Mat34 &X_control_points,\n                                   Mat4X *alphas) {\n  size_t num_points = X_world_centered.cols();\n  Mat3 C2 ;\n  for (size_t c = 1; c < 4; c++) {\n    C2.col(c-1) = X_control_points.col(c) - X_control_points.col(0);\n  }\n\n  Mat3 C2inv = C2.inverse();\n  Mat3X a = C2inv * X_world_centered;\n\n  alphas->resize(4, num_points);\n  alphas->setZero();\n  alphas->block(1, 0, 3, num_points) = a;\n  for (size_t c = 0; c < num_points; c++) {\n    (*alphas)(0, c) = 1.0 - alphas->col(c).sum();\n  }\n}\n\n// Estimates the coordinates of all real points in the camera coordinate frame\nvoid ComputePointsCoordinatesInCameraFrame(\n    const Mat4X &alphas, \n    const Vec4 &betas,\n    const Eigen::Matrix<double, 12, 12> &U,\n    Mat3X *X_camera) {\n  size_t num_points = alphas.cols();\n\n  // Estimates the control points in the camera reference frame.\n  Mat34 C2b; C2b.setZero();\n  for (size_t cu = 0; cu < 4; cu++) {\n    for (size_t c = 0; c < 4; c++) {\n      C2b.col(c) += betas(cu) * U.block(11 - cu, c * 3, 1, 3).transpose();\n    }\n  }\n\n  // Estimates the 3D points in the camera reference frame\n  X_camera->resize(3, num_points);\n  for (size_t c = 0; c < num_points; c++) {\n    X_camera->col(c) = C2b * alphas.col(c);\n  }\n\n  // Check the sign of the z coordinate of the points (should be positive)\n  uint num_z_neg = 0;\n  for (size_t i = 0; i < X_camera->cols(); ++i) {\n    if ((*X_camera)(2,i) < 0) {\n      num_z_neg++;\n    }\n  }\n\n  // If more than 50% of z are negative, we change the signs\n  if (num_z_neg > 0.5 * X_camera->cols()) {\n    C2b = -C2b;\n    *X_camera = -(*X_camera);\n  }    \n}\n\nbool EuclideanResectionEPnP(const Mat2X &x_camera,\n                            const Mat3X &X_world, \n                            Mat3 *R, Vec3 *t) {\n  CHECK(x_camera.cols() == X_world.cols());\n  CHECK(x_camera.cols() > 3);\n  size_t num_points = X_world.cols();\n \n  // Select the control points.\n  Mat34 X_control_points;\n  Mat X_centered;\n  SelectControlPoints(X_world, &X_centered, &X_control_points);\n  \n  // Compute the barycentric coordinates.\n  Mat4X alphas(4, num_points);\n  ComputeBarycentricCoordinates(X_centered, X_control_points, &alphas);\n   \n  // Estimates the M matrix with the barycentric coordinates\n  Mat M(2 * num_points, 12);\n  Eigen::Matrix<double, 2, 12> sub_M;\n  for (size_t c = 0; c < num_points; c++) {\n    double a0 = alphas(0, c);\n    double a1 = alphas(1, c);\n    double a2 = alphas(2, c);\n    double a3 = alphas(3, c);\n    double ui = x_camera(0, c);\n    double vi = x_camera(1, c);\n    M.block(2*c, 0, 2, 12) << a0, 0, \n                              a0*(-ui), a1, 0,\n                              a1*(-ui), a2, 0, \n                              a2*(-ui), a3, 0,\n                              a3*(-ui), 0, \n                              a0, a0*(-vi), 0,\n                              a1, a1*(-vi), 0,\n                              a2, a2*(-vi), 0,\n                              a3, a3*(-vi);\n  }\n  \n  // TODO(julien): Avoid the transpose by rewriting the u2.block() calls.\n  Eigen::JacobiSVD<Mat> MtMsvd(M.transpose()*M, Eigen::ComputeFullU);\n  Eigen::Matrix<double, 12, 12> u2 = MtMsvd.matrixU().transpose();\n\n  // Estimate the L matrix.\n  Eigen::Matrix<double, 6, 3> dv1;\n  Eigen::Matrix<double, 6, 3> dv2;\n  Eigen::Matrix<double, 6, 3> dv3;\n  Eigen::Matrix<double, 6, 3> dv4;\n\n  dv1.row(0) = u2.block(11, 0, 1, 3) - u2.block(11, 3, 1, 3);\n  dv1.row(1) = u2.block(11, 0, 1, 3) - u2.block(11, 6, 1, 3);\n  dv1.row(2) = u2.block(11, 0, 1, 3) - u2.block(11, 9, 1, 3);\n  dv1.row(3) = u2.block(11, 3, 1, 3) - u2.block(11, 6, 1, 3);\n  dv1.row(4) = u2.block(11, 3, 1, 3) - u2.block(11, 9, 1, 3);\n  dv1.row(5) = u2.block(11, 6, 1, 3) - u2.block(11, 9, 1, 3);\n  dv2.row(0) = u2.block(10, 0, 1, 3) - u2.block(10, 3, 1, 3);\n  dv2.row(1) = u2.block(10, 0, 1, 3) - u2.block(10, 6, 1, 3);\n  dv2.row(2) = u2.block(10, 0, 1, 3) - u2.block(10, 9, 1, 3);\n  dv2.row(3) = u2.block(10, 3, 1, 3) - u2.block(10, 6, 1, 3);\n  dv2.row(4) = u2.block(10, 3, 1, 3) - u2.block(10, 9, 1, 3);\n  dv2.row(5) = u2.block(10, 6, 1, 3) - u2.block(10, 9, 1, 3);\n  dv3.row(0) = u2.block( 9, 0, 1, 3) - u2.block( 9, 3, 1, 3);\n  dv3.row(1) = u2.block( 9, 0, 1, 3) - u2.block( 9, 6, 1, 3);\n  dv3.row(2) = u2.block( 9, 0, 1, 3) - u2.block( 9, 9, 1, 3);\n  dv3.row(3) = u2.block( 9, 3, 1, 3) - u2.block( 9, 6, 1, 3);\n  dv3.row(4) = u2.block( 9, 3, 1, 3) - u2.block( 9, 9, 1, 3);\n  dv3.row(5) = u2.block( 9, 6, 1, 3) - u2.block( 9, 9, 1, 3);\n  dv4.row(0) = u2.block( 8, 0, 1, 3) - u2.block( 8, 3, 1, 3);\n  dv4.row(1) = u2.block( 8, 0, 1, 3) - u2.block( 8, 6, 1, 3);\n  dv4.row(2) = u2.block( 8, 0, 1, 3) - u2.block( 8, 9, 1, 3);\n  dv4.row(3) = u2.block( 8, 3, 1, 3) - u2.block( 8, 6, 1, 3);\n  dv4.row(4) = u2.block( 8, 3, 1, 3) - u2.block( 8, 9, 1, 3);\n  dv4.row(5) = u2.block( 8, 6, 1, 3) - u2.block( 8, 9, 1, 3);\n\n  Eigen::Matrix<double, 6, 10> L;\n  for (size_t r = 0; r < 6; r++) {\n    L.row(r) << dv1.row(r).dot(dv1.row(r)),\n          2.0 * dv1.row(r).dot(dv2.row(r)),\n                dv2.row(r).dot(dv2.row(r)),\n          2.0 * dv1.row(r).dot(dv3.row(r)),\n          2.0 * dv2.row(r).dot(dv3.row(r)),\n                dv3.row(r).dot(dv3.row(r)),\n          2.0 * dv1.row(r).dot(dv4.row(r)),\n          2.0 * dv2.row(r).dot(dv4.row(r)),\n          2.0 * dv3.row(r).dot(dv4.row(r)),\n                dv4.row(r).dot(dv4.row(r));\n  }  \n  Vec6 rho;\n  rho << (X_control_points.col(0) - X_control_points.col(1)).squaredNorm(),\n         (X_control_points.col(0) - X_control_points.col(2)).squaredNorm(),\n         (X_control_points.col(0) - X_control_points.col(3)).squaredNorm(),\n         (X_control_points.col(1) - X_control_points.col(2)).squaredNorm(),\n         (X_control_points.col(1) - X_control_points.col(3)).squaredNorm(),\n         (X_control_points.col(2) - X_control_points.col(3)).squaredNorm();\n \n  // There are three possible solutions based on the three approximations of L\n  // (betas). Below, each one is solved for then the best one is chosen.\n  Mat3X X_camera;\n  Mat3 K; K.setIdentity();\n  vector<Mat3> Rs(3);\n  vector<Vec3> ts(3);\n  Vec rmse(3);\n\n  // TODO(julien): Document where the \"1e-3\" magical constant comes from below.\n\n  // Find the first possible solution for R, t corresponding to:\n  // Betas          = [b00 b01 b11 b02 b12 b22 b03 b13 b23 b33]\n  // Betas_approx_1 = [b00 b01     b02         b03]\n  Vec4 betas = Vec4::Zero();\n  Eigen::Matrix<double, 6, 4> l_6x4;\n  for (size_t r = 0; r < 6; r++) {\n    l_6x4.row(r) << L(r, 0), L(r, 1), L(r, 3), L(r, 6); \n  }\n  Eigen::JacobiSVD<Mat> svd_of_l4(l_6x4, \n                                  Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Vec4 b4 = svd_of_l4.solve(rho);\n  if ((l_6x4 * b4).isApprox(rho, 1e-3)) {\n    if (b4(0) < 0) {\n      b4 = -b4;\n    } \n    b4(0) =  std::sqrt(b4(0));\n    betas << b4(0), b4(1) / b4(0), b4(2) / b4(0), b4(3) / b4(0);\n    ComputePointsCoordinatesInCameraFrame(alphas, betas, u2, &X_camera);\n    AbsoluteOrientation(X_world, X_camera, &Rs[0], &ts[0]);\n    rmse(0) = RootMeanSquareError(x_camera, X_world, K, Rs[0], ts[0]);\n  } else {\n    LOG(ERROR) << \"First approximation of beta not good enough.\";\n    ts[0].setZero();\n    rmse(0) = std::numeric_limits<double>::max();\n  }\n \n  // Find the second possible solution for R, t corresponding to:\n  // Betas          = [b00 b01 b11 b02 b12 b22 b03 b13 b23 b33]\n  // Betas_approx_2 = [b00 b01 b11]\n  betas.setZero();\n  Eigen::Matrix<double, 6, 3> l_6x3;\n  l_6x3 = L.block(0, 0, 6, 3);\n  Eigen::JacobiSVD<Mat> svdOfL3(l_6x3, \n                                Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Vec3 b3 = svdOfL3.solve(rho);\n  VLOG(2) << \" rho = \" << rho;\n  VLOG(2) << \" l_6x3 * b3 = \" << l_6x3 * b3;\n  if ((l_6x3 * b3).isApprox(rho, 1e-3)) {\n    if (b3(0) < 0) {\n      betas(0) = std::sqrt(-b3(0));\n      betas(1) = (b3(2) < 0) ? std::sqrt(-b3(2)) : 0;\n    } else {\n      betas(0) = std::sqrt(b3(0));\n      betas(1) = (b3(2) > 0) ? std::sqrt(b3(2)) : 0;\n    }\n    if (b3(1) < 0) {\n      betas(0) = -betas(0);\n    }\n    betas(2) = 0;\n    betas(3) = 0;\n    ComputePointsCoordinatesInCameraFrame(alphas, betas, u2, &X_camera);\n    AbsoluteOrientation(X_world, X_camera, &Rs[1], &ts[1]);\n    rmse(1) = RootMeanSquareError(x_camera, X_world, K, Rs[1], ts[1]);\n  } else {\n    LOG(ERROR) << \"Second approximation of beta not good enough.\";\n    ts[1].setZero();\n    rmse(1) = std::numeric_limits<double>::max();\n  }\n  \n  // Find the third possible solution for R, t corresponding to:\n  // Betas          = [b00 b01 b11 b02 b12 b22 b03 b13 b23 b33]\n  // Betas_approx_3 = [b00 b01 b11 b02 b12]\n  betas.setZero();\n  Eigen::Matrix<double, 6, 5> l_6x5;\n  l_6x5 = L.block(0, 0, 6, 5);\n  Eigen::JacobiSVD<Mat> svdOfL5(l_6x5, \n                                Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Vec5 b5 = svdOfL5.solve(rho);\n  if ((l_6x5 * b5).isApprox(rho, 1e-3)) {\n    if (b5(0) < 0) {\n      betas(0) = std::sqrt(-b5(0));\n      if (b5(2) < 0) {\n        betas(1) = std::sqrt(-b5(2));\n      } else {\n        b5(2) = 0;\n      }\n    } else {\n      betas(0) = std::sqrt(b5(0));\n      if (b5(2) > 0) {\n        betas(1) = std::sqrt(b5(2));\n      } else {\n        b5(2) = 0;\n      }\n    }\n    if (b5(1) < 0) {\n      betas(0) = -betas(0);\n    }\n    betas(2) = b5(3) / betas(0);\n    betas(3) = 0;\n    ComputePointsCoordinatesInCameraFrame(alphas, betas, u2, &X_camera);\n    AbsoluteOrientation(X_world, X_camera, &Rs[2], &ts[2]);\n    rmse(2) = RootMeanSquareError(x_camera, X_world, K, Rs[2], ts[2]);\n  } else {\n    LOG(ERROR) << \"Third approximation of beta not good enough.\";\n    ts[2].setZero();\n    rmse(2) = std::numeric_limits<double>::max();\n  }\n  \n  // Finally, with all three solutions, select the (R, t) with the best RMSE.\n  VLOG(2) << \"RMSE for solution 0: \" << rmse(0);\n  VLOG(2) << \"RMSE for solution 1: \" << rmse(0);\n  VLOG(2) << \"RMSE for solution 2: \" << rmse(0);\n  size_t n = 0;\n  if (rmse(1) < rmse(0)) {\n    n = 1;\n  }\n  if (rmse(2) < rmse(n)) {\n    n = 2;\n  }\n  if (rmse(n) == std::numeric_limits<double>::max()) {\n    LOG(ERROR) << \"All three possibilities failed. Reporting failure.\";\n    return false;\n  }\n\n  VLOG(1) << \"RMSE for best solution #\" << n << \": \" << rmse(n);\n  *R = Rs[n];\n  *t = ts[n];\n\n  // TODO(julien): Improve the solutions with non-linear refinement.\n  return true;\n}\n\n} // namespace resection\n} // namespace libmv\n", "meta": {"hexsha": "6d918a1a8bc772a23351cdc3126098b88a1c0966", "size": 23835, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmv/multiview/euclidean_resection.cc", "max_stars_repo_name": "cvfish/libmv-1", "max_stars_repo_head_hexsha": "b9aac30a9ca6bc8362c09a0e191040964f7c6de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T09:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:03:20.000Z", "max_issues_repo_path": "src/libmv/multiview/euclidean_resection.cc", "max_issues_repo_name": "Matthias-Fauconneau/libmv", "max_issues_repo_head_hexsha": "531c79bf95fddaaa70707d1abcd4fdafda16bbf0", "max_issues_repo_licenses": ["MIT"], "max_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/euclidean_resection.cc", "max_forks_repo_name": "Matthias-Fauconneau/libmv", "max_forks_repo_head_hexsha": "531c79bf95fddaaa70707d1abcd4fdafda16bbf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-08T20:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T12:59:11.000Z", "avg_line_length": 36.0045317221, "max_line_length": 80, "alphanum_fraction": 0.5730648206, "num_tokens": 8133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640463, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5542932572520534}}
{"text": "// Software License Agreement (BSD-3-Clause)\n//\n// Copyright 2018 The University of North Carolina at Chapel Hill\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\n//    copyright notice, this list of conditions and the following\n//    disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived\n//    from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\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,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n// OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//! @author Jeff Ichnowski\n\n#pragma once\n#ifndef NIGH_METRIC_IMPL_SO2_HPP\n#define NIGH_METRIC_IMPL_SO2_HPP\n\n#include <type_traits>\n#include <cmath>\n#include <Eigen/Dense>\n#include \"constants.hpp\"\n\nnamespace unc::robotics::nigh::impl::so2 {\n    template <typename S>\n    std::enable_if_t<std::is_floating_point_v<S>, S>\n    angularDistance(S a, S b) {\n        S d = std::fmod(std::abs(a - b), impl::PI<S> * 2);\n        return std::min(d, impl::PI<S>*2 - d);\n    }\n\n    template <int p, typename A, typename B>\n    std::common_type_t<typename A::Scalar, typename B::Scalar>\n    angularDistance(const Eigen::ArrayBase<A>& a, const Eigen::ArrayBase<B>& b) {\n        using Scalar = std::common_type_t<typename A::Scalar, typename B::Scalar>;\n        Eigen::Array<Scalar, A::RowsAtCompileTime, A::ColsAtCompileTime> r = (a - b).cwiseAbs();\n        r -= (r / (2*impl::PI<Scalar>)).floor() * (2*impl::PI<Scalar>);\n        r = (r < -impl::PI<Scalar>).select(r + 2*impl::PI<Scalar>, r);\n        r = (r >  impl::PI<Scalar>).select(r - 2*impl::PI<Scalar>, r);\n        return r.matrix().template lpNorm<p>();\n    }\n\n    template <int p, typename A, typename B>\n    auto angularDistance(const Eigen::MatrixBase<A>& a, const Eigen::MatrixBase<B>& b) {\n        return angularDistance<p>(a.array(), b.array());\n    }\n\n        // Returns the argument bound to the range -PI..PI\n    template <typename Scalar>\n    std::enable_if_t<std::is_floating_point_v<Scalar>, Scalar>\n    bound(Scalar a) {\n        if ((a = std::fmod(a, PI<Scalar>*2)) <= -PI<Scalar>)\n            return a + PI<Scalar>*2;\n        return (a > PI<Scalar>) ? a - PI<Scalar>*2 : a;\n    }\n\n    // computes the counter-clockwise distance from a to b\n    template <typename Scalar>\n    Scalar ccwDist(Scalar a, Scalar b) {\n        Scalar d = std::fmod(b - a, PI<Scalar>*2);\n        return d < 0 ? d + PI<Scalar>*2 : d;\n    }\n\n    // This method is exactly the same ad ccwDist except that two\n    // overlapping values are considered 2*PI instead of 0.\n    template <typename Scalar>\n    Scalar ccwRange(Scalar a, Scalar b) {\n        Scalar d = std::fmod(b - a, PI<Scalar>*2);\n        return d <= 0 ? d + PI<Scalar>*2 : d;\n    }\n\n    template <typename Scalar>\n    Scalar antipode(Scalar a) {\n        return a <= 0 ? (a + PI<Scalar>) : (a - PI<Scalar>);\n    }\n\n    // Finds a split on a set of SO(2) values normalized to the range\n    // [-pi,pi].  The split divides the values into two evenly sized\n    // (_N/2) sets, and maximizes the distance of the bounds to the\n    // split.\n    template <typename Iter>\n    auto split(Iter first, Iter last) {\n        using Scalar = typename std::iterator_traits<Iter>::value_type;\n        std::size_t n = std::distance(first, last);\n        assert(n > 1); // can only split more than 1 element\n\n        // The loop finds the `i` at which half elements are to the\n        // left of the line bisecting line it define.  To find it we\n        // test for `j = i + N/2`, that the ccw distance to `[j] < pi`\n        // and `[j+1] > pi`.  The \"best\" split is the one that\n        // maximizes the distance between the points closest to the\n        // split, thus `[i]`, `[i+1]`, `[j]`, and `[j+1]`.\n\n        // distances: pi-D(i,j), D(i,j+1)-pi, D(i,i+1)\n        //\n        //        i\n        //        |@@@\n        //        |@@@@\n        //   -----X@@@@\n        //   ####/|\\@@@\n        //    ##/ | \\@\n        //     j    j+1\n\n        //          /\n        // j+1 ----X\n        //     ###/|\\     |\n        //     ##/ |@\\    |\n        //     #/  |@@\\   |\n        //     i       j\n\n        //        j+1 j\n        //      ###| /@\n        //     ####|/@@@\n        //     ####X@@@@\n        //     ###/ \\@@@\n        //      #/   \\@\n        //      i\n\n        std::sort(first, last);\n        Scalar dBest = -1, split = 0;\n        Iter i1 = first;\n        Iter j1 = first + n/2;\n        do {\n            Iter i0 = i1;\n            Iter j0 = j1;\n            if (++i1 == last) i1 = first;\n            if (++j1 == last) j1 = first;\n            Scalar d0 = PI<Scalar> - so2::ccwDist(*i0, *j0); // vals[i], vals[j%n]);\n            Scalar d1 = PI<Scalar> - so2::ccwDist(*j1, *i0); // vals[(j+1)%n], vals[i]);\n\n            if (d0 >= 0 && d1 >= 0) {\n                Scalar di = so2::ccwDist(*i0, *i1); // vals[i], vals[(i+1)%n]);\n                // Scalar split = vals[i] + std::min(di, d1) * 0.5;\n\n                Scalar range = 2*PI<Scalar> - (d0+d1);\n\n                if (range < PI<Scalar>) {\n                    // The range of values is less than half a circle.\n                    // split halfway between i0 and i1\n                    if (range > dBest) {\n                        dBest = range;\n                        split = *i0 + di * 0.5;\n                    }\n                } else {\n                    // The range of values is more than half a circle\n                    // split considering both sides of split plane.\n                    // we cannot split halfway between i0 and i1 since\n                    // it could result in moving j1 to the other side\n                    // of the split.\n                    //\n                    // An easy split to do would be i0 + min(di,d1)/2,\n                    // since that would be halfway from the split to\n                    // the next bound.  This is also guaranteed to be\n                    // in the bounds.\n                    //\n                    // A possibly better split is to try to maximize\n                    // the sum of square distances from the split.\n                    //\n                    // define x as the split offset from i0.  The\n                    // distances from the split plane are thus:\n                    //\n                    //   i0 to split = x\n                    //   split to i1 = di - x\n                    //   j0 to split = d0 + x\n                    //   split to j1 = d1 - x\n                    //\n                    // summing the square of the above quantities,\n                    // then differentiating and solving for 0, we get:\n                    //\n                    // x = (di + d1 - d0) / 4;\n\n                    // Compute the range as the sum of distances from\n                    // the split.  We add PI so that we prefer\n                    // splitting these axes over axes that are already\n                    // split.\n                    Scalar dSum = PI<Scalar> + (di+d0+d1)/2; // std::min({di, d0, d1});\n                    if (dSum > dBest) {\n                        dBest = dSum;\n                        split = *i0 + std::min(di, d1) * Scalar(0.5);\n                    }\n                }\n            }\n        } while (i1 != first);\n\n        //if (sBest > PI<Scalar>) sBest -= 2*PI<Scalar>;\n        split = so2::bound(split);\n\n        assert(0 <= dBest && dBest <= 2*PI<Scalar>);\n        assert(-PI<Scalar> <= split && split <= PI<Scalar>);\n\n        return std::make_pair(dBest, split);\n    }\n\n    template <typename Container>\n    auto split(Container& container) {\n        return split(container.begin(), container.end());\n    }\n}\n\n#endif\n", "meta": {"hexsha": "05fe47b2f31f1574daf33ddf07dc780ceb192ea4", "size": 8704, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nigh/impl/so2.hpp", "max_stars_repo_name": "mengyu-fu/nigh", "max_stars_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2018-12-09T16:38:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:31:51.000Z", "max_issues_repo_path": "src/nigh/impl/so2.hpp", "max_issues_repo_name": "mengyu-fu/nigh", "max_issues_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-03-27T01:02:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T15:47:59.000Z", "max_forks_repo_path": "src/nigh/impl/so2.hpp", "max_forks_repo_name": "mengyu-fu/nigh", "max_forks_repo_head_hexsha": "da16672bf5b083c019d72b7f3df476c672bb78b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-03-27T23:09:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T15:57:46.000Z", "avg_line_length": 39.2072072072, "max_line_length": 96, "alphanum_fraction": 0.5274586397, "num_tokens": 2200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.5542932532174721}}
{"text": "/*\n * Author: Patrick Schmidt\n */\n\n#include \"CohomologyBasis.hh\"\n\n#include <HomologyInference/Genus.hh>\n#include <HomologyInference/Utils/BarycentricPoint.hh>\n#include <HomologyInference/Utils/CotanWeights.hh>\n#include <HomologyInference/Utils/Timer.hh>\n#include <Eigen/SparseCholesky>\n#include <queue>\n\nnamespace HomologyInference\n{\n\nstd::vector<ExternalProperty<HEH, double>>\ncohomology_basis(\n        const PrimalLoops& _loops,\n        const TriMesh& _mesh)\n{\n    Timer timer(__FUNCTION__);\n\n    // Set up linear system\n    const int n_fields = _loops.size();\n    const int n_constr = _mesh.n_faces() + _mesh.n_vertices() + n_fields;\n    const int n_edges = _mesh.n_edges();\n    std::vector<Triplet> triplets;\n    MatXd rhs = MatXd::Zero(n_constr, n_fields);\n\n    // 1 if canonical direction, -1 otherwise\n    auto he_sign = [&] (const HEH& heh)\n    {\n        const auto& eh = _mesh.edge_handle(heh);\n        const auto& heh0 = _mesh.halfedge_handle(eh, 0);\n        return (heh == heh0) ? 1.0 : -1.0;\n    };\n\n    // Closedness condition:\n    // Integral along every contractible loop is zero.\n    for (auto f : _mesh.faces())\n    {\n        for (auto h : f.halfedges())\n            triplets.push_back(Triplet(f.idx(), h.edge().idx(), he_sign(h)));\n    }\n\n    // Harmonicity condition:\n    // Laplace of field is zero at every vertex\n    int offset = _mesh.n_faces();\n    for (auto v : _mesh.vertices())\n    {\n        if (v.is_boundary())\n        {\n            for (auto h : v.outgoing_halfedges())\n                if (h.edge().is_boundary())\n                    triplets.push_back(Triplet(offset + v.idx(), h.edge().idx(), he_sign(h) * 1.0 / _mesh.calc_edge_length(h.edge())));\n        }\n        else\n        {\n            for (auto h : v.outgoing_halfedges())\n                triplets.push_back(Triplet(offset + v.idx(), h.edge().idx(), he_sign(h) * cotan_weight(_mesh, h)));\n        }\n    }\n\n    // Duality condition:\n    // Integral of field i along loop i is 1. All others are 0.\n    offset += _mesh.n_vertices();\n    for (int i = 0; i < _loops.size(); ++i)\n    {\n        for (auto heh : _loops[i].hehs)\n        {\n            const auto& eh = _mesh.edge_handle(heh);\n            triplets.push_back(Triplet(offset + i, eh.idx(), he_sign(heh)));\n        }\n    }\n    rhs.block(offset, 0, n_fields, n_fields) = MatXd::Identity(n_fields, n_fields);\n\n    SparseMatrix A(n_constr, n_edges);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n\n    // Solve A^T*A * x = A^T*b via sparse Cholesky\n    const SparseMatrix AtA = A.transpose() * A;\n    const MatXd Atrhs = A.transpose() * rhs;\n    Eigen::SimplicialLDLT<SparseMatrix> solver;\n    solver.compute(AtA);\n    ISM_ASSERT(solver.info() == Eigen::Success);\n    MatXd x = solver.solve(Atrhs);\n    ISM_ASSERT(solver.info() == Eigen::Success);\n    ISM_ASSERT_EQ(x.rows(), n_edges);\n    ISM_ASSERT_EQ(x.cols(), n_fields);\n\n    double residual = (A * x - rhs).norm();\n    ISM_DEBUG_VAR(residual);\n\n    // Convert to halfedge properties\n    auto gradients = std::vector<ExternalProperty<HEH, double>>(n_fields, ExternalProperty<HEH, double>(_mesh));\n    for (int i = 0; i < n_fields; ++i)\n        for (auto h : _mesh.halfedges())\n            gradients[i][h] = he_sign(h) * x(h.edge().idx(), i);\n\n    return gradients;\n}\n\nExternalProperty<VH, double>\nintegrate_field_real(\n        const ExternalProperty<HEH, double>& _gradient,\n        const TriMesh& _mesh,\n        const VH _seed_vh,\n        const double _seed_value)\n{\n    // Flood fill starting from first vertex\n    ExternalProperty<VH, double> u(_mesh, NAN_DOUBLE); // integrated function\n    ExternalProperty<VH, bool> visited(_mesh, false);\n\n    std::queue<SHEH> queue;\n    for (auto h : _mesh.voh_range(_seed_vh))\n        queue.push(h);\n    u[_seed_vh] = _seed_value;\n    visited[_seed_vh] = true;\n\n    while (!queue.empty())\n    {\n        const auto h = queue.front();\n        queue.pop();\n\n        if (visited[h.to()])\n            continue;\n\n        u[h.to()] = u[h.from()] + _gradient[h];\n        visited[h.to()] = true;\n\n        for (auto h_enq : h.to().outgoing_halfedges())\n        {\n            if (!visited[h_enq.to()])\n                queue.push(h_enq);\n        }\n    }\n\n    return u;\n}\n\nstd::vector<ExternalProperty<VH, double>>\nintegrated_fields_real(\n        const std::vector<ExternalProperty<HEH, double>>& _gradients,\n        const TriMesh& _mesh,\n        const VH _seed_vh,\n        const double _seed_value)\n{\n    std::vector<ExternalProperty<VH, double>> result;\n    for (const auto& g : _gradients)\n        result.push_back(integrate_field_real(g, _mesh, _seed_vh, _seed_value));\n    return result;\n}\n\nExternalProperty<VH, Complex>\nintegrate_field_complex(\n        const ExternalProperty<HEH, double>& _gradient,\n        const TriMesh& _mesh,\n        const VH _seed_vh,\n        const Complex _seed_value)\n{\n    ExternalProperty<VH, double> u_real = integrate_field_real(_gradient, _mesh, _seed_vh, 0.0);\n    ExternalProperty<VH, Complex> u_complex(_mesh, NAN_DOUBLE);\n    for (const auto& v : _mesh.vertices())\n    {\n        const double angle = u_real[v] * 2 * M_PI;\n        const Complex rot = std::polar(1.0, angle);\n        u_complex[v] = rot * _seed_value;\n    }\n    return u_complex;\n}\n\nstd::vector<ExternalProperty<VH, Complex>>\nintegrated_fields_complex(\n        const std::vector<ExternalProperty<HEH, double>>& _gradients,\n        const TriMesh& _mesh,\n        const VH _seed_vh,\n        const Complex _seed_value)\n{\n    Timer timer(__FUNCTION__);\n\n    std::vector<ExternalProperty<VH, Complex>> result;\n    for (const auto& g : _gradients)\n        result.push_back(integrate_field_complex(g, _mesh, _seed_vh, _seed_value));\n    return result;\n}\n\nExternalProperty<HEH, double>\ndifferentiate_field(\n        const ExternalProperty<VH, Complex>& _u,\n        const TriMesh& _mesh)\n{\n    ExternalProperty<HEH, double> gradient(_mesh);\n    for (const auto& heh : _mesh.halfedges())\n    {\n        const VH vh0 = _mesh.from_vertex_handle(heh);\n        const VH vh1 = _mesh.to_vertex_handle(heh);\n        const Complex u0 = _u[vh0];\n        const Complex u1 = _u[vh1];\n        const Complex rot = u1 / u0;\n        const double angle_diff = std::arg(rot) / (2 * M_PI);\n        gradient[heh] = angle_diff;\n    }\n    return gradient;\n}\n\nstd::vector<ExternalProperty<HEH, double>>\ndifferentiate_fields(\n        const std::vector<ExternalProperty<VH, Complex>>& _us,\n        const TriMesh& _mesh)\n{\n    Timer timer(__FUNCTION__);\n\n    std::vector<ExternalProperty<HEH, double>> result;\n    for (const auto& u : _us)\n        result.push_back(differentiate_field(u, _mesh));\n    return result;\n}\n\ndouble\nintegrate_loop(\n        const ExternalProperty<HEH, double>& _gradient,\n        const PrimalLoop& _loop)\n{\n    double res = 0.0;\n    for (auto h : _loop.hehs)\n        res += _gradient[h];\n    return res;\n}\n\nMatXd\nintegrate_loops(\n        const std::vector<ExternalProperty<HEH, double>>& _fields,\n        const PrimalLoops& _loops)\n{\n    ISM_ASSERT(_loops.size() == _fields.size());\n    const int n = _loops.size();\n    MatXd M_integrated = MatXd::Zero(n, n);\n    for (int row = 0; row < n; ++row)\n        for (int col = 0; col < n; ++col)\n            M_integrated(row, col) = integrate_loop(_fields[col], _loops[row]);\n    return M_integrated;\n}\n\nExternalProperty<HEH, double>\ncombine_fields(\n        const TriMesh& _mesh,\n        const VecXi& _coeffs,\n        const std::vector<ExternalProperty<HEH, double>>& _fields)\n{\n    const VecXd coeffs_d = _coeffs.cast<double>();\n    return combine_fields(_mesh, coeffs_d, _fields);\n}\n\nExternalProperty<HEH, double>\ncombine_fields(\n        const TriMesh& _mesh,\n        const VecXd& _coeffs,\n        const std::vector<ExternalProperty<HEH, double>>& _fields)\n{\n    ISM_ASSERT_EQ(_coeffs.size(), _fields.size());\n    ExternalProperty<HEH, double> field(_mesh, 0.0);\n    for (int i = 0; i < _coeffs.size(); ++i)\n    {\n        const auto& input_field = _fields[i];\n        ISM_ASSERT(input_field.size_okay(_mesh));\n        for (const auto& heh : _mesh.halfedges())\n            field[heh] += _coeffs[i] * input_field[heh];\n    }\n    return field;\n}\n\nstd::vector<ExternalProperty<HEH, double>>\ntransform_fields(\n        const TriMesh& _mesh,\n        const MatXi& _M,\n        const std::vector<ExternalProperty<HEH, double>>& _fields)\n{\n    ISM_ASSERT_EQ(_M.cols(), _fields.size());\n    ISM_ASSERT(!_fields.empty());\n    std::vector<ExternalProperty<HEH, double>> result;\n    for (int row = 0; row < _M.rows(); ++row)\n    {\n        const VecXi M_row = _M.row(row);\n        ExternalProperty<HEH, double> field = combine_fields(_mesh, M_row, _fields);\n        result.push_back(field);\n    }\n    return result;\n}\n\n}\n", "meta": {"hexsha": "865bfa565cdb812a3ffbf27a70730033dbbf3276", "size": 8676, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/HomologyInference/CohomologyBasis.cc", "max_stars_repo_name": "jsb/HomologyInference", "max_stars_repo_head_hexsha": "a8b6f9ecad375072bd45e96e08c906c8332c3e4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-08T06:53:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:41:01.000Z", "max_issues_repo_path": "src/HomologyInference/CohomologyBasis.cc", "max_issues_repo_name": "jsb/HomologyInference", "max_issues_repo_head_hexsha": "a8b6f9ecad375072bd45e96e08c906c8332c3e4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HomologyInference/CohomologyBasis.cc", "max_forks_repo_name": "jsb/HomologyInference", "max_forks_repo_head_hexsha": "a8b6f9ecad375072bd45e96e08c906c8332c3e4f", "max_forks_repo_licenses": ["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.7123287671, "max_line_length": 135, "alphanum_fraction": 0.6254034117, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.554272727287159}}
{"text": "#include <fstream>\r\n#include <armadillo>\r\n#include <thread>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\n// Armadillo documentation is available at:\r\n// http://arma.sourceforge.net/docs.html\r\n\r\n\r\nbool intersect(const vec& origin, const vec& direction, const vec& center, double radius, vec& normal, vec& hit) {\r\n\tvec oc = origin - center;\r\n\tdouble a = dot(direction, direction);\r\n\tdouble b = 2.0*dot(direction, oc);\r\n\tdouble c = dot(oc, oc) - radius*radius;\r\n\r\n\tdouble delta = b*b - 4.0*a*c;\r\n\tif (delta < 0.0) {\r\n\t\treturn false;\r\n\t}\r\n\tdouble t1 = (-b + sqrt(delta)) / (2.0*a);\r\n\tdouble t2 = (-b - sqrt(delta)) / (2.0*a);\r\n\tdouble t = (t1 < t2) ? t1 : t2;\r\n\r\n\thit = origin + direction*t;\r\n\tnormal = hit - center;\r\n\treturn true;\r\n}\r\n\r\nint main() {\r\n\tvec centro_esfera = { 0.0, 0.0, 10.0 };\r\n\tvec origin = { 0.0, 0.0, 0.0 };\r\n\tdouble intensidade = 0.9;\r\n\tvec posicao_luz = { 0.0, 4.0, 4.0 };\r\n\tvec radiancia_luz = { intensidade, intensidade, intensidade };\r\n\tmat k;\r\n\tk << 1000.0 << 0.0 << 400.0 << endr\r\n\t\t<< 0.0 << -1000.0 << 300.0 << endr\r\n\t\t<< 0.0 << 0.0 << 1.0;\r\n\tmat invk = k.i();\r\n\r\n\tofstream output;\r\n\toutput.open(\"imagem.pgm\");\r\n\toutput << \"P3\" << endl;\r\n\toutput << \"800 600\" << endl;\r\n\toutput << \"255\" << endl;\r\n\r\n\tfor (int linha = 0; linha < 600; linha++) {\r\n\t\tfor (int coluna = 0; coluna < 800; coluna++) {\r\n\t\t\tvec r = { double(coluna), double(linha), 1.0 };\r\n\t\t\tvec normal, hit;\r\n\t\t\t\r\n\t\t\tr = invk * r;\r\n\t\t\tr *= 5.0 / r(2);\r\n\t\t\tif (intersect(origin, r, centro_esfera, 2.0, normal, hit)) {\r\n\t\t\t\tnormal /= norm(normal);\r\n\t\t\t\tvec l = posicao_luz - hit;\r\n\t\t\t\tl /= norm(l);\r\n\r\n\t\t\t\tvec cor = { 255.0, 0.0, 0.0 };\r\n\t\t\t\tcor = (cor % radiancia_luz)*std::max(0.0, dot(normal, l));\r\n\t\t\t\toutput << std::min(255, int(cor(0))) << \" \" \r\n\t\t\t\t\t   << std::min(255, int(cor(1))) << \" \"\r\n\t\t\t\t\t   << std::min(255, int(cor(2))) << \" \";\r\n\t\t\t} else {\r\n\t\t\t\toutput << \"255 255 255 \";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\toutput.close();\r\n\treturn 0;\r\n}", "meta": {"hexsha": "db00fff452dd41af560afb85cf8e06d6ed0a4998", "size": 1920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example1.cpp", "max_stars_repo_name": "thiago-farias/cg_armadillo_project", "max_stars_repo_head_hexsha": "da5b9f17c465822ed61e3aa9daac4f95489d8cf1", "max_stars_repo_licenses": ["Apache-2.0"], "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/example1.cpp", "max_issues_repo_name": "thiago-farias/cg_armadillo_project", "max_issues_repo_head_hexsha": "da5b9f17c465822ed61e3aa9daac4f95489d8cf1", "max_issues_repo_licenses": ["Apache-2.0"], "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/example1.cpp", "max_forks_repo_name": "thiago-farias/cg_armadillo_project", "max_forks_repo_head_hexsha": "da5b9f17c465822ed61e3aa9daac4f95489d8cf1", "max_forks_repo_licenses": ["Apache-2.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.301369863, "max_line_length": 115, "alphanum_fraction": 0.5447916667, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5541719610354205}}
{"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#include <Eigen/Core>\n#include <smooth/bundle.hpp>\n#include <smooth/feedback/compat/ipopt.hpp>\n#include <smooth/feedback/ocp.hpp>\n#include <smooth/se2.hpp>\n\n#include <chrono>\n#include <iostream>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\ntemplate<typename T>\nusing X = smooth::Bundle<smooth::SE2<T>, Eigen::Vector3<T>>;\n\ntemplate<typename T>\nusing U = Eigen::Vector2<T>;\n\ntemplate<typename T>\nusing Vec = Eigen::VectorX<T>;\n\n/// @brief Objective function\nconst auto obj = []<typename T>(T tf, const X<T> &, const X<T> &, const Vec<T> & q) -> T {\n  return tf + q.x();\n};\n\n/// @brief Dynamics\nconst auto f = []<typename T>(T, const X<T> & x, const U<T> & u) -> smooth::Tangent<X<T>> {\n  smooth::Tangent<X<T>> ret;\n  ret.segment(0, 3) = x.template part<1>();\n  ret(3)            = u.x();\n  ret(4)            = T(0);\n  ret(5)            = u.y();\n  return ret;\n};\n\n/// @brief Integrals\nconst auto g = []<typename T>(T, const X<T> &, const U<T> & u) -> Vec<T> {\n  return Vec<T>{{u.squaredNorm()}};\n};\n\n/// @brief Running constraints\nconst auto cr = []<typename T>(T, const X<T> &, const U<T> & u) -> Vec<T> { return u; };\n\n/// @brief End constraints\nconst auto ce = []<typename T>(T tf, const X<T> & x0, const X<T> & xf, const Vec<T> &) -> Vec<T> {\n  const smooth::SE2<T> target(smooth::SO2<T>(-0.5), Eigen::Vector2<T>{2, 0.5});\n  Vec<T> ret(10);\n  ret << tf, x0.template part<0>().log(), x0.template part<1>(), xf.template part<0>() - target;\n  return ret;\n};\n\n/// @brief Range to std::vector\nconst auto r2v = []<std::ranges::range R>(const R & r) {\n  return std::vector(std::ranges::begin(r), std::ranges::end(r));\n};\n\nint main()\n{\n  // define optimal control problem\n  smooth::feedback::\n    OCP<X<double>, U<double>, decltype(obj), decltype(f), decltype(g), decltype(cr), decltype(ce)>\n      ocp{\n        .nx    = smooth::Dof<X<double>>,\n        .nu    = smooth::Dof<U<double>>,\n        .nq    = 1,\n        .ncr   = 2,\n        .nce   = 10,\n        .theta = obj,\n        .f     = f,\n        .g     = g,\n        .cr    = cr,\n        .crl   = Vec<double>{{-1, -1}},\n        .cru   = Vec<double>{{1, 1}},\n        .ce    = ce,\n        .cel   = Vec<double>{{3, 0, 0, 0, 0, 0, 0, 0, 0, 0}},\n        .ceu   = Vec<double>{{15, 0, 0, 0, 0, 0, 0, 0, 0, 0}},\n      };\n\n  const auto xl = []<typename T>(T) -> X<T> { return X<T>::Identity(); };\n  const auto ul = []<typename T>(T) -> U<T> { return Eigen::Vector2<T>::Constant(0.01); };\n\n  assert(smooth::feedback::check_ocp(ocp));\n\n  const auto flatocp = smooth::feedback::flatten_ocp(ocp, xl, ul);\n\n  assert(smooth::feedback::check_ocp(flatocp));\n\n  // target optimality\n  const double target_err = 1e-6;\n\n  // define mesh\n  smooth::feedback::Mesh<5, 10> mesh;\n\n  // declare solution variable\n  std::vector<smooth::feedback::OCPSolution<X<double>, U<double>>> sols;\n  std::optional<smooth::feedback::NLPSolution> nlpsol;\n\n  const auto t0 = std::chrono::high_resolution_clock::now();\n\n  for (auto iter = 0u; iter < 10; ++iter) {\n    std::cout << \"---------- ITERATION \" << iter << \" ----------\" << std::endl;\n    std::cout << \"mesh: \" << mesh.N_ivals() << \" intervals, \" << mesh.N_colloc()\n              << \" collocation pts\" << std::endl;\n\n    // transcribe optimal control problem to nonlinear programming problem\n    const auto nlp = smooth::feedback::ocp_to_nlp(flatocp, mesh);\n\n    // solve nonlinear programming problem\n    std::cout << \"solving...\" << std::endl;\n    nlpsol = smooth::feedback::solve_nlp_ipopt(\n      nlp,\n      nlpsol,\n      {\n        {\"print_level\", 5},\n      },\n      {\n        {\"linear_solver\", \"mumps\"}, {\"hessian_approximation\", \"limited-memory\"},\n        // {\"derivative_test\", \"first-order\"},\n        // {\"print_timing_statistics\", \"yes\"},\n      },\n      {\n        {\"tol\", 1e-6},\n      });\n\n    // convert solution of nlp insto solution of ocp\n    auto flatsol = smooth::feedback::nlpsol_to_ocpsol(flatocp, mesh, nlpsol.value());\n\n    // store unflattened solution\n    sols.push_back(smooth::feedback::unflatten_ocpsol<X<double>, U<double>>(flatsol, xl, ul));\n\n    // calculate errors\n    auto errs = smooth::feedback::mesh_dyn_error(\n      flatocp.nx, flatocp.f, mesh, flatsol.t0, flatsol.tf, flatsol.x, flatsol.u);\n\n    std::cout << \"interval errors \" << errs.transpose() << std::endl;\n\n    if (errs.maxCoeff() > target_err) {\n      smooth::feedback::mesh_refine(mesh, errs, 0.1 * target_err);\n      nlpsol = smooth::feedback::ocpsol_to_nlpsol(flatocp, mesh, flatsol);\n    } else {\n      break;\n    }\n  }\n\n  const auto dur = std::chrono::high_resolution_clock::now() - t0;\n\n  std::cout << \"TOTAL TIME: \" << std::chrono::duration_cast<std::chrono::milliseconds>(dur).count()\n            << \"ms\" << std::endl;\n\n#ifdef ENABLE_PLOTTING\n  using namespace matplot;\n\n  const auto [nodes, weights] = mesh.all_nodes_and_weights();\n\n  const auto tt       = linspace(0., sols.back().tf, 500);\n  const auto tt_nodes = r2v(sols.back().tf * nodes);\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(\n      transform(tt, [&](double t) { return sol.x(t).part<0>().r2().x(); }),\n      transform(tt, [&](double t) { return sol.x(t).part<0>().r2().y(); }),\n      \"-r\")\n      ->line_width(lw);\n  }\n  legend(std::vector<std::string>{\"path\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.x(t).part<1>().x(); }), \"-r\")->line_width(lw);\n    plot(tt, transform(tt, [&](double t) { return sol.x(t).part<1>().y(); }), \"-g\")->line_width(lw);\n    plot(tt, transform(tt, [&](double t) { return sol.x(t).part<1>().z(); }), \"-b\")->line_width(lw);\n  }\n  legend({\"vx\", \"vy\", \"wz\"});\n\n  figure();\n  hold(on);\n  plot(tt_nodes, transform(tt_nodes, [](auto) { return 0; }), \"xk\")->marker_size(10);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_dyn(t).x(); }), \"-r\")->line_width(lw);\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_dyn(t).y(); }), \"-b\")->line_width(lw);\n  }\n  legend({\"nodes\", \"lambda_x\", \"lambda_y\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&](double t) { return sol.lambda_cr(t).x(); }), \"-r\")->line_width(lw);\n  }\n  legend(std::vector<std::string>{\"lambda_{cr}\"});\n\n  figure();\n  hold(on);\n  for (auto it = 0u; const auto & sol : sols) {\n    int lw = it++ + 1 < sols.size() ? 1 : 2;\n    plot(tt, transform(tt, [&sol](double t) { return sol.u(t).x(); }), \"-r\")->line_width(lw);\n    plot(tt, transform(tt, [&sol](double t) { return sol.u(t).y(); }), \"-b\")->line_width(lw);\n  }\n  legend({\"throttle\", \"steering\"});\n\n  show();\n#endif\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "8bb8371a2e78140cc13c82c836882ffd9abf4869", "size": 8116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/colloc_se2.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "examples/colloc_se2.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "examples/colloc_se2.cpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 33.9581589958, "max_line_length": 100, "alphanum_fraction": 0.5979546575, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5540032648364959}}
{"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 * Gicp.cpp\n *\n *  Created on: Jan 31, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech \n */\n\n#include <Eigen/LU> // for inverse and determinant\n\n#include <memory>\n#include <iostream>\n#include \"mrob/pc_registration.hpp\" // GICP function is defined here\n\n\nusing namespace mrob;\n\nint PCRegistration::gicp(const Eigen::Ref<const MatX> X, const Eigen::Ref<const MatX> Y,\n           const Eigen::Ref<const MatX> covX, const Eigen::Ref<const MatX> covY, SE3 &T, double tol)\n{\n    assert(X.cols() == 3  && \"PCRegistration::Gicp: Incorrect sizing, we expect Nx3\");\n    assert(X.rows() >= 3  && \"PCRegistration::Gicp: Incorrect sizing, we expect at least 3 correspondences (not aligned)\");\n    assert(Y.rows() == X.rows()  && \"PCRegistration::Gicp: Same number of correspondences\");\n    uint_t N = X.rows();\n    // TODO precalculation of T by reduced Arun\n    // TODO different number of iterations and convergence criterion\n\n    // Initialize Jacobian and Hessian\n    Mat61 J = Mat61::Zero();\n    Mat6 H = Mat6::Zero();\n    uint_t iters = 0;\n    double deltaUpdate = 1e3;\n    do\n    {\n        J.setZero();\n        H.setZero();\n        // not vectoried operations (due to Jacobian)\n        for ( uint_t i = 0; i < N ; ++i)\n        {\n            // 1) Calculate residual r = y - Tx and the inverse of joint covariance\n            Mat31 Txi = T.transform(X.row(i));\n            Mat31 r = Y.row(i).transpose() - Txi;\n            Mat3 Li = (covY.block<3,3>(3*i,0) + T.R() * covX.block<3,3>(3*i,0) * T.R().transpose()).inverse();\n\n            // 2) Calculate Jacobian for residual Jf = df1/d xi = r1' Li * Jr, where Jr = [(Tx)^ ; -I])\n            Mat<3,6> Jr;\n            Jr << hat3(Txi) , -Mat3::Identity();\n            Mat<1,6> Ji = r.transpose() * Li * Jr;\n            J += Ji;//Eigen manages this for us\n\n            // 3) Hessian Hi ~ Jr' * Li * Jr\n            Mat6 Hi = Jr.transpose() * Li * Jr;\n            H += Hi;\n        }\n        // 4) Update Solution\n        Mat61 dxi = -H.inverse()*J;\n        T.update_lhs(dxi); //Left side update\n        deltaUpdate = dxi.norm();\n        iters++;\n\n    }while(deltaUpdate > tol && iters < 20);\n\n    return iters; // number of iterations\n}\n", "meta": {"hexsha": "f52a83a5f59e4dba3cab5b4455a05d51aae800b1", "size": 2886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/gicp.cpp", "max_stars_repo_name": "nosmokingsurfer/mrob", "max_stars_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-09-22T15:33:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T17:27:39.000Z", "max_issues_repo_path": "src/PCRegistration/gicp.cpp", "max_issues_repo_name": "nosmokingsurfer/mrob", "max_issues_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T15:47:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:56:44.000Z", "max_forks_repo_path": "src/PCRegistration/gicp.cpp", "max_forks_repo_name": "nosmokingsurfer/mrob", "max_forks_repo_head_hexsha": "7e92c1747373d5acf32895e688b568ae8244072e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T15:59:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T20:15:16.000Z", "avg_line_length": 36.075, "max_line_length": 123, "alphanum_fraction": 0.6053361053, "num_tokens": 790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.5540032495750146}}
{"text": "/*\n * Copyright 2009-2019 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 \"../../../include/votca/csg/potentialfunctions/potentialfunctioncbspl.h\"\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <votca/tools/table.h>\n\nusing namespace std;\nusing namespace votca::tools;\n\nnamespace votca {\nnamespace csg {\n\nPotentialFunctionCBSPL::PotentialFunctionCBSPL(const string &name, Index nlam,\n                                               double min, double max)\n    : PotentialFunction(name, nlam, min, max) {\n\n  /* Here nlam_ is the total number of coeff values that are to be optimized\n   * To ensure that potential and force go to zero smoothly near cut-off,\n   * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to\n   * cut-off and beyond take a value of zero.\n   *\n   * Since region less than rmin is not sampled sufficiently for stability\n   * first  nexcl_ coefficients are not optimized instead their values are\n   * extrapolated from first statistically significant knot values near rmin\n   */\n\n  Index nknots;\n\n  nknots = lam_.size();\n\n  nbreak_ = nknots - 2;\n\n  dr_ = (cut_off_) / (double(nbreak_ - 1));\n\n  // break point locations\n  // since ncoeff = nbreak +2 , r values for last two coefficients are also\n  // computed\n  rbreak_ = Eigen::VectorXd::Zero(nknots);\n\n  for (Index i = 0; i < nknots; i++) {\n    rbreak_(i) = double(i) * dr_;\n  }\n\n  // exclude knots corresponding to r <=  min_\n  nexcl_ = std::min((Index)(min_ / dr_), nbreak_ - 2) + 1;\n\n  // account for finite numerical division of  min_/ dr_\n  // e.g. 0.24/0.02 may result in 11.99999999999999\n  if (rbreak_(nexcl_) == min_) {\n    nexcl_++;\n  }\n\n  // fixing last 4 knots to zeros is reasonable\n  ncutcoeff_ = 4;\n\n  // check if we have enough parameters to optimize\n  if ((Index(lam_.size()) - nexcl_ - ncutcoeff_) < 1) {\n    throw std::runtime_error(\n        \"In potential \" + name_ +\n        \": no parameters to optimize!\\n\"\n        \"All the knot values fall in the range of either excluded (due to high \"\n        \"repulsive region) or cut-off region.\\n\"\n        \"This issue can be resolved by one or combination of following steps:\\n\"\n        \"1. Make sure you are using large-enough cut-off for this CG \"\n        \"potential.\\n\"\n        \"2. Make sure the CG-MD runs are sufficiently Index and CG-MD RDF are \"\n        \"statistically reliable.\\n\"\n        \"3. Use more knot values.\\n\");\n  }\n\n  M_ = Eigen::MatrixXd::Zero(4, 4);\n  M_(0, 0) = 1.0;\n  M_(0, 1) = 4.0;\n  M_(0, 2) = 1.0;\n  M_(0, 3) = 0.0;\n  M_(1, 0) = -3.0;\n  M_(1, 1) = 0.0;\n  M_(1, 2) = 3.0;\n  M_(1, 3) = 0.0;\n  M_(2, 0) = 3.0;\n  M_(2, 1) = -6.0;\n  M_(2, 2) = 3.0;\n  M_(2, 3) = 0.0;\n  M_(3, 0) = -1.0;\n  M_(3, 1) = 3.0;\n  M_(3, 2) = -3.0;\n  M_(3, 3) = 1.0;\n  M_ /= 6.0;\n}\n\nIndex PotentialFunctionCBSPL::getOptParamSize() const {\n\n  return lam_.size() - nexcl_ - ncutcoeff_;\n}\n\nvoid PotentialFunctionCBSPL::setParam(string filename) {\n\n  Table param;\n  param.Load(filename);\n  lam_.setZero();\n\n  if (param.size() != lam_.size()) {\n\n    throw std::runtime_error(\"In potential \" + name_ +\n                             \": parameters size mismatch!\\n\"\n                             \"Check input parameter file \\\"\" +\n                             filename + \"\\\" \\nThere should be \" +\n                             boost::lexical_cast<string>(lam_.size()) +\n                             \" parameters\");\n  } else {\n    // force last  ncutcoeff_ to zero\n    Index nonzero = lam_.size() - ncutcoeff_;\n    lam_.head(nonzero) = param.y().head(nonzero);\n  }\n}\n\nvoid PotentialFunctionCBSPL::SaveParam(const string &filename) {\n\n  extrapolExclParam();\n\n  Table param;\n  param.SetHasYErr(false);\n  param.resize(lam_.size());\n\n  // write extrapolated knots with flag 'o'\n  // points close to rmin can also be stastically not reliable\n  // so flag 3 more points next to rmin as 'o'\n  for (Index i = 0; i < nexcl_ + 3; i++) {\n    param.set(i, rbreak_(i), lam_(i), 'o');\n  }\n\n  for (Index i = nexcl_ + 3; i < lam_.size(); i++) {\n    param.set(i, rbreak_(i), lam_(i), 'i');\n  }\n\n  param.Save(filename);\n}\n\nvoid PotentialFunctionCBSPL::SavePotTab(const string &filename, double step,\n                                        double rmin, double rcut) {\n  extrapolExclParam();\n  PotentialFunction::SavePotTab(filename, step, rmin, rcut);\n}\n\nvoid PotentialFunctionCBSPL::SavePotTab(const string &filename, double step) {\n  extrapolExclParam();\n  PotentialFunction::SavePotTab(filename, step);\n}\n\nvoid PotentialFunctionCBSPL::extrapolExclParam() {\n\n  double u0 = lam_(nexcl_);\n  double m = (lam_(nexcl_ + 1) - lam_(nexcl_)) /\n             (rbreak_(nexcl_ + 1) - rbreak_(nexcl_));\n  double r0 = rbreak_(nexcl_);\n\n  /* If the slope m is positive then the potential core\n   * will be attractive. So, artificially forcing core to be\n   * repulsive by setting m = -m\n   */\n  if (m > 0) {\n    cout << name_ << \" potential's extrapolated core is attractive!\" << endl;\n    cout << \"Artifically enforcing repulsive core.\\n\" << endl;\n    m *= -1.0;\n  }\n  // using linear extrapolation\n  // u(r) = ar + b\n  // a = m\n  // b = - m*r0 + u0\n  // m = (u1-u0)/(r1-r0)\n\n  double a = m;\n  double b = -1.0 * m * r0 + u0;\n  for (Index i = 0; i < nexcl_; i++) {\n    lam_(i) = a * rbreak_(i) + b;\n  }\n}\n\nvoid PotentialFunctionCBSPL::setOptParam(Index i, double val) {\n\n  lam_(i + nexcl_) = val;\n}\n\ndouble PotentialFunctionCBSPL::getOptParam(Index i) const {\n\n  return lam_(i + nexcl_);\n}\n\ndouble PotentialFunctionCBSPL::CalculateF(double r) const {\n\n  if (r <= cut_off_) {\n\n    double u = 0.0;\n    Index indx = std::min((Index)(r / dr_), nbreak_ - 2);\n    double rk = (double)indx * dr_;\n    double t = (r - rk) / dr_;\n\n    Eigen::Vector4d R = Eigen::Vector4d::Zero();\n    R(0) = 1.0;\n    R(1) = t;\n    R(2) = t * t;\n    R(3) = t * t * t;\n    Eigen::Vector4d B = lam_.segment<4>(indx);\n    u += ((R.transpose() * M_) * B).value();\n    return u;\n\n  } else {\n    return 0.0;\n  }\n}\n\n// calculate first derivative w.r.t. ith parameter\ndouble PotentialFunctionCBSPL::CalculateDF(Index i, double r) const {\n\n  // since first  nexcl_ parameters are not optimized for stability reasons\n\n  if (r <= cut_off_) {\n\n    Index i_opt = i + nexcl_;\n    Index indx;\n    double rk;\n\n    indx = std::min((Index)(r / dr_), nbreak_ - 2);\n    rk = (double)indx * dr_;\n\n    if (i_opt >= indx && i_opt <= indx + 3) {\n\n      Eigen::Vector4d R = Eigen::Vector4d::Zero();\n\n      double t = (r - rk) / dr_;\n\n      R(0) = 1.0;\n      R(1) = t;\n      R(2) = t * t;\n      R(3) = t * t * t;\n\n      Eigen::Vector4d RM = R.transpose() * M_;\n\n      return RM(i_opt - indx);\n\n    } else {\n      return 0.0;\n    }\n\n  } else {\n    return 0.0;\n  }\n}\n\n// calculate second derivative w.r.t. ith parameter\ndouble PotentialFunctionCBSPL::CalculateD2F(Index, Index, double) const {\n\n  return 0.0;\n}\n\n}  // namespace csg\n}  // namespace votca\n", "meta": {"hexsha": "4d491277b3d83950f46efef40e41d8ec171a708c", "size": 7387, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libcsg/potentialfunctions/potentialfunctioncbspl.cc", "max_stars_repo_name": "BuildJet/csg", "max_stars_repo_head_hexsha": "c02f06ff316eef38564c8e0160bcaf4a6c7f160d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libcsg/potentialfunctions/potentialfunctioncbspl.cc", "max_issues_repo_name": "BuildJet/csg", "max_issues_repo_head_hexsha": "c02f06ff316eef38564c8e0160bcaf4a6c7f160d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libcsg/potentialfunctions/potentialfunctioncbspl.cc", "max_forks_repo_name": "BuildJet/csg", "max_forks_repo_head_hexsha": "c02f06ff316eef38564c8e0160bcaf4a6c7f160d", "max_forks_repo_licenses": ["Apache-2.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.9598540146, "max_line_length": 81, "alphanum_fraction": 0.6103966428, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5540032432663965}}
{"text": "#include \"ros/ros.h\"\n#include \"geometry_msgs/Vector3.h\"\n#include \"sensor_msgs/Joy.h\"\n#include \"create_driver/vicon_driver.h\"\n#include \"geometry_msgs/Twist.h\"\n\n#include \"create_controller/ControlMsgs.h\"\n\n#include <string>\n#include <vector>\n#include <map>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <cmath>\n\n#define PI 3.141592\nusing namespace Eigen;\nusing namespace std;\nVector3d position(-5,-5,-5);\n\n\nvoid position_callback(const geometry_msgs::Vector3::ConstPtr& msg)\n{\n\tposition(0) = msg->x;\n\tposition(1) = msg->y;\n\tposition(2) = msg->z;\n}\n\nint main(int argc, char **argv)\n{\n\t// ROS Initalization\n\tros::init(argc, argv, \"falcon_ellipse_feedback\");\n\t\n\tros::NodeHandle n;\n\tros::NodeHandle private_n(\"~\");\n\n\t// List of robot names\n\tvector<string> robot_names;\n\tXmlRpc::XmlRpcValue robot_list;\n\tprivate_n.getParam(\"robot_list\", robot_list);\n\tROS_ASSERT(robot_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < robot_list.size(); i++) \n\t{\n\t\tROS_ASSERT(robot_list[i].getType() == XmlRpc::XmlRpcValue::TypeString);\n\t\trobot_names.push_back(static_cast<string>(robot_list[i]));\n\t}\n\n\t// Number of robots\n\tconst int num_robots = robot_names.size();\n\n\t\n\t// ROS Subscribers\n\tmap<string, create_driver::ViconStream> vicon;\n\tvector<string>::iterator name_it;\n\tvector<ros::Subscriber> sub;\n\tfor (name_it = robot_names.begin(); name_it != robot_names.end(); name_it++)\n\t{\n\t\tvicon.insert(pair<string, create_driver::ViconStream>(*name_it, create_driver::ViconStream()));\n\t\tsub.push_back(n.subscribe(\"/\" + *name_it + \"/tf\", 10, &create_driver::ViconStream::callback, &vicon[*name_it]));\n\t}\n\n\tsub.push_back(n.subscribe(\"position\", 10, position_callback));\n\n\tros::Publisher joy_pub = n.advertise<sensor_msgs::Joy>(\"joy\", 10);\n\tros::Publisher force_pub = n.advertise<geometry_msgs::Vector3>(\"force\", 10);\n\n\t// ROS loop\n\tros::Rate loop_rate(1000); // 1 kHz\n\tbool uninitialized = true;\n\twhile (ros::ok())\n\t{\n\t\tros::spinOnce();\n\n\t\tVector3d joy(position(0)/0.06,  position(1)/0.06, (2.0*(position(2)-0.073))/0.1035 - 1.0);\n\n\t\tVector3d force;\n\t\tdouble resistance;\n\n\t\tdouble p[num_robots];\n\t\tdouble q[num_robots];\n\n\t\tfor (int i = 0; i < num_robots; i++) {\n\t\t\tp[i] = cos(vicon[robot_names[i]].theta());\n\t\t\tq[i] = sin(vicon[robot_names[i]].theta());\n\t\t}\n\n\t\tdouble p_bar = 0.0;\n\t\tdouble q_bar = 0.0;\n\n\t\tfor (int i = 0; i < num_robots; i++) {\n\t\t\tp_bar += p[i]/num_robots;\n\t\t\tq_bar += q[i]/num_robots;\n\t\t}\n\n\t\tdouble r = sqrt(pow(p_bar, 2) + pow(q_bar, 2))/2.0;\n\n\t\tdouble phi = atan2(q_bar, p_bar);\n\n\t\tdouble b = 0.2;\n\n\t\tdouble a = sqrt(pow(r, 2) + pow(b, 2));\n\n\t\tdouble x = joy(0) - r*cos(phi);\n\t\tdouble y = joy(1) - r*sin(phi);\n\n\t\tdouble x_barE = x * cos(phi) + y*sin(phi);\n\t\tdouble y_barE = -x * sin(phi) + y*cos(phi);\n\n\t\tdouble c = pow(x_barE,2) / pow(a,2) + pow(y_barE,2) / pow(b,2);\n\n\t\tdouble lowerbound = 1.0;\n\t\tdouble upperbound = 25.0;\n\t\tdouble gain = 0.0;\n\t\tif(lowerbound < c && c < upperbound){\n\t\t\tgain = (-500)*(pow(upperbound,2) - pow(lowerbound,2) )*(pow(c,2) - pow(lowerbound,2) ) / pow((pow(c,2) - pow(upperbound,2) ),3);\n\n\t\t} \n\t\t\n\t\tdouble v_bar1 = -2 * x_barE/pow(a,2);\n\t\tdouble v_bar2 = -2 * y_barE/pow(b,2);\n\n\t\tdouble v_bar_norm = sqrt(pow(v_bar1, 2) + pow(v_bar2, 2));\n\n\t\tVector3d v_bar(v_bar1*cos(phi)-v_bar2*sin(phi), v_bar1*sin(phi)+v_bar2*cos(phi), 0);\n\t\tforce = gain*v_bar_norm*v_bar;\n\t\t// if (joy.norm()<0.25) {\n\t\t// \tresistance =1;\n\t\t// } else {\n\t\t// \tdouble radius = joy.norm() - 0.25;\n\n\t\t// \tdouble sum_etheta = fabs(etheta[0])+ fabs(etheta[1])+fabs(etheta[2])+fabs(etheta[3]);\n\t\t// \tresistance = 1; // + 6 * (radius * sum_etheta);\n\t\t// \tprintf(\"%f\\n\", sum_etheta);\n\t\t// }\n\t\t\n\t\t// for (int i = 0; i < 3; i++)\n\t\t// {\n\t\t// \tforce(i) = -5*joy(i)*resistance;\n\t\t// }\n\n\t\tgeometry_msgs::Vector3 fmsg;\n\t\tfmsg.x = force(0);\n\t\tfmsg.y = force(1);\n\t\tfmsg.z = -joy(2)*5;\n\t\tforce_pub.publish(fmsg);\n\n\t\t// Deadband\n\t\tif (joy.norm() < 0.25) {\n\t\t\tfor (int i = 0; i < 2; ++i)\n\t\t\t{\n\t\t\t\tjoy(i) =0;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tsensor_msgs::Joy jmsg;\n\t\tjmsg.axes.resize(3);\n\t\tjmsg.axes[0] = -joy(0);//position(0)/0.06; // -1.0 to 1.0\n\t\tjmsg.axes[1] = joy(1);//position(1)/0.06;\n\t\tjmsg.axes[2] = joy(2);//(2.0*(position(2)-0.073))/0.1035 - 1.0;//32767\n\t\tjoy_pub.publish(jmsg);\n\n\t\t\n\t\t\n\n\t\tloop_rate.sleep();\n\t}\n\t\n\treturn 0;\n}", "meta": {"hexsha": "ea5630d7aa180e16c07b0c9ee94fa7c1ab82da3d", "size": 4266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/novint_falcon_driver/src/falcon_ellipse_feedback.cpp", "max_stars_repo_name": "rsthomp/UTDchess-RospyXbee", "max_stars_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T01:52:06.000Z", "max_issues_repo_path": "src/novint_falcon_driver/src/falcon_ellipse_feedback.cpp", "max_issues_repo_name": "RachaelT/UTDchess-RospyXbee", "max_issues_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/novint_falcon_driver/src/falcon_ellipse_feedback.cpp", "max_forks_repo_name": "RachaelT/UTDchess-RospyXbee", "max_forks_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6589595376, "max_line_length": 131, "alphanum_fraction": 0.6317393343, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.5540032369577782}}
{"text": "/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/ublas/assignment.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include \"specialtypes.hpp\"\n#include \"ublas_cholesky.hpp\"\n#include \"posterior_mcmc.hpp\"\n\nnamespace bnu = boost::numeric::ublas;\n \nint determinant_sign(const bnu::permutation_matrix<std::size_t>& pm)\n{\n  int pm_sign=1;\n  std::size_t size = pm.size();\n  for (std::size_t i = 0; i < size; ++i)\n    if (i != pm(i))\n      pm_sign *= -1.0; // swap_rows would swap a pair of rows here, so we change sign\n  return pm_sign;\n}\n \ndouble determinant(bnu::matrix<double>& m ) {\n  bnu::permutation_matrix<std::size_t> pm(m.size1());\n  double det = 1.0;\n  if( bnu::lu_factorize(m,pm) ) {\n    det = 0.0;\n  } else {\n    for(int i = 0; i < m.size1(); i++) \n      det *= m(i,i); // multiply by elements on diagonal\n    det = det * determinant_sign( pm );\n  }\n  return det;\n}\n\n\ndouble gauss(const vectord& x, const vectord& mu, const matrixd& sigma)\n{\n  const double tpi = boost::math::constants::two_pi<double>();\n  double n = static_cast<double>(x.size());\n  const vectord vd = x-mu;\n  matrixd invS = sigma;\n  bayesopt::utils::inverse_cholesky(sigma,invS);\n  matrixd sig = sigma;\n\n  return pow(tpi,n/2)*pow(determinant(sig),0.5)*exp(-0.5*inner_prod(vd,prod(invS,vd)));\n}\n\nclass Posterior: public bayesopt::RBOptimizable\n{\n  double evaluate(const vectord& x)\n  {\n    vectord mu1(2), mu2(2), mu3(2);\n    matrixd s1(2,2), s2(2,2), s3(2,2);\n\n    mu1 <<= 0,0;\n    mu2 <<= 1,1;\n    mu3 <<= -4,2;\n    \n    s1 <<= 1,0, \n      0,1;\n\n    s2 <<= 4,0,\n      0,0.6;\n\n    s3 <<= 4,0,\n      0,0.6;\n  \n    return gauss(x,mu1,s1) + gauss(x,mu2,s2) + gauss(x,mu3,s3);\n  }\n};\n  \nint main()\n{\n  randEngine reng;\n  Posterior post;\n  bayesopt::MCMCSampler sampler(&post,2,reng);\n  vectord x = zvectord(2);\n  sampler.run(x);\n  sampler.printParticles();\n\n  return 0;\n}\n", "meta": {"hexsha": "7418530ce4e022685bb3129fced84c15bdb72c53", "size": 2870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/tests/testmcmc.cpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/tests/testmcmc.cpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/tests/testmcmc.cpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 27.3333333333, "max_line_length": 87, "alphanum_fraction": 0.6289198606, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367524, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.5539058503779931}}
{"text": "/**\n * @file gravity_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 <math.h>\n#include <fpu.hpp>\n#include <Eigen/Core>\n#include \"board.hpp\"\n\n/**\n * @brief IMUの測定値から重力の影響を取り除くフィルタ\n */\nclass GravityFilter {\npublic:\n    /**\n     * @brief 内部状態をリセットする\n     */\n    void reset(void) {\n        _initialized = false;\n    }\n\n    /**\n     * @brief フィルタに新たな入力を与えて出力を更新する\n     * @param accel 加速度センサーの測定値\n     * @param gyro ジャイロスコープの測定値\n     */\n    void update(const Eigen::Vector3f& accel, const Eigen::Vector3f& gyro) {\n        using namespace Eigen;\n\n        static constexpr float GYRO_GAIN_P = 1.0;\n        static constexpr float GYRO_GAIN_I = 0.001;\n        static constexpr float GRAVITY_LOW_THRESHOLD = 0.0625f;\n        static constexpr float GRAVITY_COMPENSATION = 0.001f;\n\n        if (!_initialized) {\n            // 重力加速度ベクトルを初期化する\n            _initialized = true;\n            _gravity = accel;\n            _gyro_error_integ = Vector3f::Zero();\n        }\n\n        // 加速度ベクトルと重力加速度ベクトルの成す角度を求める\n        Vector3f gyro_error;\n        float gravity_scale = fpu::sqrt(_gravity.squaredNorm());\n        if (GRAVITY_LOW_THRESHOLD < gravity_scale) {\n            gyro_error = accel.cross(_gravity) / (gravity_scale * gravity_scale);\n            _gyro_error_integ += gyro_error;\n        }\n        else {\n            // 重力が異様に小さいときは加速度センサーによる角速度の補正を減らす\n            gyro_error = Vector3f::Zero();\n            _gyro_error_integ *= fpu::max(1.0f - 1.0f / IMU_OUTPUT_RATE, 0.0f);\n        }\n\n        // 角速度を加速度センサーから得た角度誤差で補正する\n        Vector3f delta_omega = GYRO_GAIN_P * gyro_error + GYRO_GAIN_I * _gyro_error_integ;\n        _compensated_gyro = gyro + delta_omega;\n\n        // 重力ベクトルを回転する\n        Matrix3f Rt = rotationMatrixTransposed(_compensated_gyro * (1.0f / IMU_OUTPUT_RATE));\n        _gravity = Rt * _gravity;\n\n        // 重力加速度ベクトルの大きさを徐々に加速度の大きさに近づける\n        // 重力が小さいときは大きさではなくベクトルそのものを使って補正する\n        float accel_scale = fpu::sqrt(accel.squaredNorm());\n        if (GRAVITY_LOW_THRESHOLD < fpu::min(accel_scale, gravity_scale)) {\n            _gravity *= ((1.0f - GRAVITY_COMPENSATION) + GRAVITY_COMPENSATION * accel_scale / gravity_scale);\n        }\n        else {\n            _gravity = (1.0f - GRAVITY_COMPENSATION) * _gravity + GRAVITY_COMPENSATION * accel;\n        }\n\n        // 加速度ベクトルから重力の影響を除去する\n        _compensated_accel = accel - _gravity;\n    }\n\n    /**\n     * @brief 重力加速度ベクトル(の反力)を取得する\n     * @return 重力加速度ベクトル(の反力) X, Y, Z [m/s^2]\n     */\n    const Eigen::Vector3f& gravity(void) const {\n        return _gravity;\n    }\n\n    /**\n     * @brief 重力を除去済みの加速度を取得する\n     * @return 加速度 X, Y, Z [m/s^2]\n     */\n    const Eigen::Vector3f& acceleration(void) const {\n        return _compensated_accel;\n    }\n\n    /**\n     * @brief 重力で補正済みの角速度を取得する\n     * @return 角速度 X, Y, Z [rad/s]\n     */\n    const Eigen::Vector3f& angularVelocity(void) const {\n        return _compensated_gyro;\n    }\n\nprivate:\n    static Eigen::Matrix3f rotationMatrixTransposed(const Eigen::Vector3f& gyro) {\n        float z = gyro.z();\n        float y = gyro.y();\n        float x = gyro.x();\n        return Eigen::Matrix3f{\n            {1.0f, x * y + z, x * z - y},\n            {-z, 1.0f - x * y * z, x + y * z},\n            {y, -x, 1.0f},\n        };\n    }\n\n    bool _initialized = false;\n    Eigen::Vector3f _gravity;\n    Eigen::Vector3f _compensated_accel;\n    Eigen::Vector3f _compensated_gyro;\n    Eigen::Vector3f _gyro_error_integ;\n};\n", "meta": {"hexsha": "08cbdfa42d02d8bf880a7c72270862c9b66417f5", "size": 3494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FPGA/App/software/controller/source/filter/gravity_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/gravity_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/gravity_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": 28.1774193548, "max_line_length": 109, "alphanum_fraction": 0.6004579279, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5539049349715968}}
{"text": "/**\n  This file creates a one-layer neural network to calculate the beat from 16\n  inputs.\n\n  We want range of tempo: 35 - 250 bpm //TODO\n*/\n#include \"exception.hh\"\n#include \"network.hh\"\n#include \"timer.hh\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <random>\n#include <utility>\n\n#include <sys/resource.h>\n#include <sys/time.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nconstexpr size_t batch_size = 1;\nconstexpr size_t input_size = 16;\n\n/* use squared error as loss function */\nfloat loss_function( const float target, const float actual )\n{\n  return ( target - actual ) * ( target - actual );\n}\n\n/* partial derivative of loss with respect to neural network output */\nfloat compute_pd_loss_wrt_output( const float target, const float actual )\n{\n  return -2 * ( target - actual );\n}\n\n/* compute input */\nMatrix<float, batch_size, input_size> gen_time( float tempo, float offset )\n{\n  Matrix<float, batch_size, input_size> ret_mat;\n  for ( auto i = 0; i < 16; i++ ) {\n    ret_mat( i ) = tempo * i + offset;\n  }\n  return ret_mat;\n}\n\nfloat learning_rate = 0.00001;\n\nvoid program_body()\n{\n  /* remove limit on stack size */\n  const rlimit limits { RLIM_INFINITY, RLIM_INFINITY };\n  CheckSystemCall( \"setrlimit\", setrlimit( RLIMIT_STACK, &limits ) );\n\n  /* seed C RNG for Eigen random weight initialization */\n  srand( Timer::timestamp_ns() );\n\n  /* construct neural network on heap */\n  auto nn = make_unique<Network<float, batch_size, input_size, 1>>();\n  nn->layer0.initializeWeightsRandomly();\n\n  int tempo = 50;\n  float offset = 0;\n  for ( tempo = 70; tempo > 50; tempo-- ) {\n    /* test true function */\n    int i = 0;\n    while ( true ) {\n      if ( i == 5 )\n        break;\n      i += 1;\n      /* step 1: construct a unique problem instance */\n      Matrix<float, batch_size, input_size> input = gen_time( tempo, offset );\n\n      /* step 2: forward propagate and calculate loss functiom */\n      nn->apply( input );\n      cout << \"nn maps input: tempo: \" << tempo << \" offset \" << offset << \" => \" << nn->output()( 0, 0 ) << endl;\n\n      /* step 3: backpropagate error */\n      nn->computeDeltas();\n      nn->evaluateGradients( input );\n\n      const float pd_loss_wrt_output = compute_pd_loss_wrt_output( tempo, nn->output()( 0, 0 ) );\n      cout << \"Original loss: \" << pd_loss_wrt_output << \"\\n\";\n\n      // TODO: static eta -> dynamic eta\n      auto four_third_lr = 4.0 / 3 * learning_rate;\n      auto two_third_lr = 2.0 / 3 * learning_rate;\n\n      /* calculate three loss */\n      float current_loss = loss_function( nn->output()( 0, 0 ), tempo );\n      Matrix<float, input_size, 1> current_weights;\n      for ( int j = 0; j < 16; j++ ) {\n        current_weights( j ) = nn->layer0.weights()( j );\n      }\n      auto current_biase = nn->layer0.biases()( 0 );\n\n      /* loss for 4/3 eta */\n      for ( int j = 0; j < 16; j++ ) {\n        nn->layer0.weights()( j ) -= four_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, j );\n      }\n      nn->layer0.biases()( 0 ) -= four_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 16 );\n      nn->apply( input );\n      auto loss_four_third_lr = loss_function( nn->output()( 0, 0 ), tempo );\n\n      /* loss for 2/3 eta */\n      for ( int j = 0; j < 16; j++ ) {\n        nn->layer0.weights()( j )\n          = current_weights( j ) - two_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, j );\n      }\n      nn->layer0.biases()( 0 )\n        = current_biase - two_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 16 );\n      nn->apply( input );\n      auto loss_two_third_lr = loss_function( nn->output()( 0, 0 ), tempo );\n\n      cout << current_loss << \" \" << loss_four_third_lr << \" \" << loss_two_third_lr << endl;\n      auto min_loss = min( min( current_loss, loss_four_third_lr ), loss_two_third_lr );\n      if ( min_loss == current_loss ) {\n        learning_rate *= 2.0 / 3;\n        for ( int j = 0; j < 16; j++ ) {\n          nn->layer0.weights()( j ) = current_weights( j );\n        }\n        nn->layer0.biases()( 0 ) = current_biase;\n      } else if ( min_loss == loss_four_third_lr ) {\n        learning_rate *= 4.0 / 3;\n        for ( int j = 0; j < 16; j++ ) {\n          nn->layer0.weights()( j )\n            = current_weights( j ) - four_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, j );\n        }\n        nn->layer0.biases()( 0 )\n          = current_biase - four_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 16 );\n      } else {\n        for ( int j = 0; j < 16; j++ ) {\n          nn->layer0.weights()( j )\n            = current_weights( j ) - two_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, j );\n        }\n        nn->layer0.biases()( 0 )\n          = current_biase - two_third_lr * pd_loss_wrt_output * nn->getEvaluatedGradient( 0, 16 );\n      }\n      cout << \"weights: \" << nn->layer0.weights() << endl;\n      cout << \"biase: \" << nn->layer0.biases()( 0 ) << endl;\n    }\n  }\n  for ( int i = 40; i < 80; i++ ) {\n    Matrix<float, batch_size, input_size> input = gen_time( i, 0 );\n    nn->apply( input );\n    cout << \"input: \" << i << \" output: \" << nn->output()( 0, 0 ) << endl;\n    // cout << nn->output()( 0, 0 ) << endl;\n    //  cout << i << endl;\n  }\n  cout << \"yay!\" << endl;\n}\n\nint main( int argc, char*[] )\n{\n  try {\n    if ( argc <= 0 ) {\n      abort();\n    }\n\n    program_body();\n\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "40f54ffaa53fde75b48ab4f3f843bc537420f2d8", "size": 5465, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/predict_tempo_no_noise.cc", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/frontend/predict_tempo_no_noise.cc", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frontend/predict_tempo_no_noise.cc", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5297619048, "max_line_length": 114, "alphanum_fraction": 0.5873741995, "num_tokens": 1572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5538169852751292}}
{"text": "#include \"problemes.h\"\n#include \"chiffres.h\"\n#include \"utilitaires.h\"\n\n#include <boost/rational.hpp>\n#include <fstream>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef boost::rational<nombre> fraction;\n\nENREGISTRER_PROBLEME(112, \"Bouncy numbers\") {\n    // Working from left-to-right if no digit is exceeded by the digit to its left it is called an \n    // increasing number; for example, 134468.\n    //\n    // Similarly if no digit is exceeded by the digit to its right it is called a decreasing number;\n    // for example, 66420.\n    // \n    // We shall call a positive integer that is neither increasing nor decreasing a \"bouncy\" number; \n    // for example, 155349.\n    // \n    // Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers\n    // below one-thousand (525) are bouncy. In fact, the least number for which the proportion of \n    // bouncy numbers first reaches 50% is 538.\n    // \n    // Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the \n    // proportion of bouncy numbers is equal to 90%.\n    //\n    // Find the least number for which the proportion of bouncy numbers is exactly 99%.\n    fraction limite(99, 100);\n    nombre ratio_numerateur = 0;\n    nombre ratio_denominateur = 0;\n\n    nombre resultat = 0;\n    for (nombre n = 1;; ++n) {\n        const auto chiffres = chiffres::extraire_chiffres(n);\n        ++ratio_denominateur;\n        if (!std::is_sorted(chiffres.begin(), chiffres.end())\n            && !std::is_sorted(chiffres.rbegin(), chiffres.rend()))\n            ++ratio_numerateur;\n        if (ratio_numerateur >= limite * ratio_denominateur) {\n            resultat = n;\n            break;\n        }\n    }\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "ff35d222ccd95ba2dd0267cac963248c5bd53bd7", "size": 1789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme112.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme112.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme112.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5102040816, "max_line_length": 102, "alphanum_fraction": 0.6646171045, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.5537448736016877}}
{"text": "#include <fstream>\n\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/Snap_rounding_traits_2.h>\n#include <CGAL/Snap_rounding_2.h>\n#include <CGAL/Snap_rounding_traits_2.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/RegularGridGraphicsItem.h>\n#include <CGAL/Qt/SegmentsGraphicsItem.h>\n#include <CGAL/Qt/PolylinesGraphicsItem.h>\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n\n// for viewportsBbox\n#include <CGAL/Qt/utility.h>\n \n// the two base classes\n#include \"ui_Snap_rounding_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel K;\ntypedef CGAL::Snap_rounding_traits_2<K>     Traits;\n\ntypedef K::Point_2 Point_2;\ntypedef K::Segment_2 Segment_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\n\n\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Snap_rounding_2\n{\n  Q_OBJECT\n  \nprivate:  \n  \n  QGraphicsScene scene;  \n\n  CGAL::Qt::RegularGridGraphicsItem<K> * rgi;\n\n  CGAL::Qt::GraphicsViewPolylineInput<K> * pi;\n\n  std::list<Segment_2> input;\n  std::list<std::list<Point_2> > output;\n\n  typedef CGAL::Qt::SegmentsGraphicsItem<std::list<Segment_2> > InputSegmentsGraphicsItem;\n  typedef CGAL::Qt::PolylinesGraphicsItem<std::list<std::list<Point_2> > > OutputPolylinesGraphicsItem;\n  InputSegmentsGraphicsItem * isgi;\n  OutputPolylinesGraphicsItem *plgi;\n  double delta;\n  \npublic:\n  MainWindow();\n              \n  void resize(){\n  this->graphicsView->setSceneRect(QRectF(0,0,20, 20));\n  this->graphicsView->fitInView(0,0, 20, 20, Qt::KeepAspectRatio);\n  }\n              \npublic Q_SLOTS:\n\n  void processInput(CGAL::Object o);\n\n  void on_actionLoadSegments_triggered();\n\n  void on_actionClear_triggered();\n\n  void on_actionSaveSegments_triggered();\n\n  void on_actionRecenter_triggered();\n\n  void on_actionShowGrid_toggled(bool checked);\n  void on_actionShowInput_toggled(bool checked);\n  void on_actionShowSnappedSegments_toggled(bool checked);\n\n  void deltaChanged(double);\n\n  virtual void open(QString fileName);\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow(), delta(1.0)\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  isgi = new InputSegmentsGraphicsItem(&input);\n  scene.addItem(isgi);\n\n  plgi = new OutputPolylinesGraphicsItem(&output);\n  scene.addItem(plgi);\n\n // inputs polylines with 2 points\n  pi = new CGAL::Qt::GraphicsViewPolylineInput<K>(this, &scene, 2, false);\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n\t\t   this, SLOT(processInput(CGAL::Object)));\n  \n  scene.installEventFilter(pi);\n\n  // Manual handling of actions\n  //\n\n\n  QObject::connect(this->doubleSpinBox, SIGNAL(valueChanged(double)),\n\t\t   this, SLOT(deltaChanged(double)));\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()), \n\t\t   this, SLOT(close()));\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  this->graphicsView->setScene(&scene);\n  // Turn the vertical axis upside down\n  this->graphicsView->matrix().scale(1, -1);\n  this->graphicsView->setMouseTracking(true);\n\n  rgi = new CGAL::Qt::RegularGridGraphicsItem<K>(delta, delta);\n\n    QObject::connect(this, SIGNAL(changed()),\n                     rgi, SLOT(modelChanged()));\n\n    QObject::connect(this, SIGNAL(changed()),\n                     isgi, SLOT(modelChanged()));\n\n    QObject::connect(this, SIGNAL(changed()),\n                     plgi, SLOT(modelChanged()));\n\n\n  rgi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  rgi->setEdgesPen(QPen(Qt::gray, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(rgi);\n\n  plgi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\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_Snap_rounding_2.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n\t  this, SLOT(open(QString)));\n}\n\n\n\nvoid\nMainWindow::deltaChanged(double d)\n{\n  if(delta == d){\n    return;\n  }\n  delta = d;\n  output.clear();\n  CGAL::snap_rounding_2<Traits,std::list<Segment_2>::const_iterator,std::list<std::list<Point_2> > >(input.begin(), input.end(), output, delta, true, false);\n  rgi->setDelta(delta, delta);\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n\n  std::list<Point_2> points;\n  if(CGAL::assign(points, o)){\n    if(points.size() == 2) {\n      input.push_back(Segment_2(points.front(), points.back()));\n      output.clear();\n      CGAL::snap_rounding_2<Traits,std::list<Segment_2>::const_iterator,std::list<std::list<Point_2> > >(input.begin(), input.end(), output, delta, true, false);\n    }\n    else {\n      std::cerr << points.size() << std::endl;\n    }\n  }\n  Q_EMIT( changed());\n}\n\n/* \n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n * \n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  input.clear();\n  output.clear();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionShowGrid_toggled(bool checked)\n{\n  rgi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionShowInput_toggled(bool checked)\n{\n  isgi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\n\n\nvoid\nMainWindow::on_actionShowSnappedSegments_toggled(bool checked)\n{\n  plgi->setVisible(checked);\n  Q_EMIT( changed());\n}\n\n\n\n\nvoid\nMainWindow::on_actionLoadSegments_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n\t\t\t\t\t\t  tr(\"Open segment file\"),\n                                                  \".\",\n                                                  tr(\"Edge files (*.edg);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n  if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n  {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n    std::vector<std::vector<Point_2> > mls;\n    CGAL::read_multi_linestring_WKT(ifs, mls);\n    for(const std::vector<Point_2>& ls : mls)\n    {\n      if(ls.size() > 2)\n        continue;\n      Segment_2 seg(ls[0], ls[1]);\n      input.push_back(seg);\n    }\n#endif\n  }\n  else {\n    std::copy(std::istream_iterator<Segment_2>(ifs),\n              std::istream_iterator<Segment_2>(),\n              std::back_inserter(input));\n  }\n  output.clear();\n  CGAL::snap_rounding_2<Traits,std::list<Segment_2>::const_iterator,std::list<std::list<Point_2> > >(input.begin(), input.end(), output, delta, true, false);\n  ifs.close();\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  on_actionRecenter_triggered();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionSaveSegments_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n\t\t\t\t\t\t  tr(\"Save points\"),\n                                                  \".\",\n                                                  tr(\"Edge files (*.edg);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                   #endif\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    std::ofstream ofs(qPrintable(fileName));\n    ofs.precision(12);\n    if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n    {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      std::vector<std::vector<Point_2> >mls;\n      for(const Segment_2& seg : input)\n      {\n        std::vector<Point_2> ls(2);\n        ls[0] = seg.source();\n        ls[1] = seg.target();\n        mls.push_back(ls);\n      }\n      CGAL::write_multi_linestring_WKT(ofs, mls);\n#endif\n    }\n    else\n      std::copy(input.begin(), input.end(),  std::ostream_iterator<Segment_2>(ofs, \"\\n\"));\n  }\n\n}\n\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(isgi->boundingRect());\n  this->graphicsView->fitInView(isgi->boundingRect(), Qt::KeepAspectRatio);  \n}\n\n\n#include \"Snap_rounding_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(\"Snap_rounding_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  // See https://doc.qt.io/qt-5/qdir.html#Q_INIT_RESOURCE\n  CGAL_QT_INIT_RESOURCES;\n  Q_INIT_RESOURCE(Snap_rounding_2);\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  mainWindow.resize();\n  return app.exec();\n}\n", "meta": {"hexsha": "cd337a2b4700a434fca3d13d6f55554a5db43f50", "size": 9670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/Snap_rounding_2/Snap_rounding_2.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/Snap_rounding_2/Snap_rounding_2.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/Snap_rounding_2/Snap_rounding_2.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 26.5659340659, "max_line_length": 161, "alphanum_fraction": 0.643123061, "num_tokens": 2432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.5537350048324831}}
{"text": "/*\n ___ ___ __     __ ____________\n|   |   |  |   |__|__|__   ___/  Ubiquitous Internet @ IIT-CNR\n|   |   |  |  /__/  /  /  /      Stateful FaaS Model Latency Simulator\n|   |   |  |/__/  /   /  /       https://github.com/ccicconetti/markovsim/\n|_______|__|__/__/   /__/\n\nLicensed under the MIT License <http://opensource.org/licenses/MIT>.\nCopyright (c) 2021 Claudio Cicconetti <https://ccicconetti.github.io/>\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/*\nDetermine the min number of containers required for a given number of clients,\nwhich alternate between having a stateful (= they prefer having a dedicated\ncontainer) vs. stateless nature (= they are OK with being assigned to a pool\nof shared stateless containers), so that the system is stable and the\nprobability that a stateful container is assigned to a shared pool of\nstateless containers is below a given threshold (epsilon).\n*/\n\n#include \"Support/chrono.h\"\n#include \"Support/glograii.h\"\n\n#include <boost/program_options.hpp>\n\n#include <glog/logging.h>\n\n#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\nnamespace po = boost::program_options;\n\ndouble compute_C_F_max(const size_t C_k, const size_t N_k,\n                       const double lambda_k, const double mu_L) {\n  return C_k * (mu_L - lambda_k * N_k / C_k) / (mu_L - lambda_k);\n}\n\ndouble binom(const size_t n, const size_t k) {\n  // prepare input\n  std::vector<double> myVec1(k);\n  std::vector<double> myVec2(k);\n  for (size_t i = n - k + 1, j = 0; i <= n; i++, j++) {\n    myVec1[j] = i;\n  }\n  for (size_t i = k, j = 0; i >= 1; i--, j++) {\n    myVec2[j] = i;\n  }\n\n  // compute return value\n  double ret = 1.0;\n  for (size_t i = 0; i < k; i++) {\n    ret *= myVec1[i] / myVec2[i];\n  }\n  return ret;\n}\n\ndouble P_0(const size_t N_k, const double q_L, const double q_F) {\n  return std::pow(q_L / (q_F + q_L), N_k);\n}\n\ndouble P_i(const size_t N_k, const size_t i, const double q_L,\n           const double q_F) {\n  return P_0(N_k, q_L, q_F) * binom(N_k, i) * std::pow(q_F / q_L, i);\n}\n\n/**\n * \\return the probability that a function requiring a dedicated container\n * is assigned instead to a pool of shared stateless containers.\n */\ndouble compute_P_v(const size_t C_F_max, const size_t N_k, const double q_L,\n                   const double q_F) {\n  assert(C_F_max > 0);\n  assert(N_k > 0);\n\n  double ret = 0;\n\n  VLOG(2) << \"q_L = \" << q_L << \", q_F = \" << q_F << \" N_k = \" << N_k << \", P0 \"\n          << P_0(N_k, q_L, q_F);\n\n  for (size_t i = C_F_max; i <= N_k; i++) {\n    ret += P_i(N_k, i, q_L, q_F);\n  }\n\n  return ret / (1 - P_0(N_k, q_L, q_F));\n}\n\nint main(int argc, char *argv[]) {\n  uiiit::support::GlogRaii myGlogRaii(argv[0]);\n\n  size_t N_k; // number of clients\n  double inv_mu_F;\n  double inv_mu_L;\n  double lambda_k;\n  double q_F;\n  double q_L;\n  double epsilon;\n\n#ifndef NDEBUG\n  assert(std::abs(binom(10, 4)) - 210.0 < 0.1);\n  assert(std::abs(binom(20, 10)) - 184756.0 < 0.1);\n  assert(std::abs(binom(30, 10)) - 30045015.0 < 0.1);\n#endif\n\n  po::options_description myDesc(\"Allowed options\");\n  // clang-format off\n  myDesc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"arrival-rate\",\n     po::value<double>(&lambda_k)->default_value(0.075),\n     \"Arrival rate, in Hz.\")\n    (\"clients\",\n     po::value<size_t>(&N_k)->default_value(70),\n     \"Number of clients\")\n    (\"service-time-full\",\n     po::value<double>(&inv_mu_F)->default_value(1.0),\n     \"Service time for clients assigned a dedicated container, in s.\")\n    (\"service-time-less\",\n     po::value<double>(&inv_mu_L)->default_value(3.0),\n     \"Service time for clients sharing a pool of non-dedicated containers, in s.\")\n    (\"q-full\",\n     po::value<double>(&q_F)->default_value(20),\n     \"Transition rate of clients in a stateless state.\")\n    (\"q-less\",\n     po::value<double>(&q_L)->default_value(80),\n     \"Transition rate of clients in a stateful state.\")\n    (\"epsilon\",\n     po::value<double>(&epsilon)->default_value(0.01),\n     \"Maximum accepted probability that a client in stateful state is served by a shared container.\")\n    ;\n  // clang-format on\n\n  try {\n    po::variables_map myVarMap;\n    po::store(po::parse_command_line(argc, argv, myDesc), myVarMap);\n    po::notify(myVarMap);\n\n    if (myVarMap.count(\"help\")) {\n      std::cout << myDesc << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    if (inv_mu_F <= 0) {\n      throw std::runtime_error(\"Invalid service time (full): \" +\n                               std::to_string(inv_mu_F));\n    }\n    double mu_F = 1.0 / inv_mu_F;\n    if (inv_mu_L <= 0) {\n      throw std::runtime_error(\"Invalid service time (less): \" +\n                               std::to_string(inv_mu_L));\n    }\n    double mu_L = 1.0 / inv_mu_L;\n\n    if (q_F <= 0) {\n      throw std::runtime_error(\"Invalid transition rate (full): \" +\n                               std::to_string(q_F));\n    }\n    if (q_L <= 0) {\n      throw std::runtime_error(\"Invalid transition rate (less): \" +\n                               std::to_string(q_L));\n    }\n    if (epsilon <= 0 or epsilon >= 1) {\n      throw std::runtime_error(\"Invalid epsilon: \" + std::to_string(epsilon));\n    }\n\n    for (size_t C_k = 1; C_k <= N_k; C_k++) {\n      // maximum number of containers that can be dedicated to stateful use\n      // while allowing the stateless clients to remain stable\n      // note: the number can be negative, in which case the system will not be\n      // stable for stateless clients even though they are left with _all_ the\n      /// containers\n      auto C_F_max_real = compute_C_F_max(C_k, N_k, lambda_k, mu_L);\n      auto C_F_max_int =\n          static_cast<size_t>(C_F_max_real < 0 ? 0 : C_F_max_real);\n\n      if (C_F_max_int == 0) {\n        VLOG(1) << \"C_F_max = \" << C_F_max_real << \": system unstable\";\n        continue;\n      }\n\n      // probability that a stateful container \"overflows\" to the pool\n      // of shared stateless containers\n      auto P_v = compute_P_v(C_F_max_int, N_k, q_L, q_F);\n\n      VLOG(1) << \"mu_F = \" << mu_F << \", mu_L = \" << mu_L << \", C_k = \" << C_k\n              << \", C_F_max = \" << C_F_max_real << \", P_v = \" << P_v;\n\n      // if the probability is below threshold, quit\n      if (P_v <= epsilon) {\n        std::cout << C_k << ' ' << (static_cast<double>(C_k) / N_k) << ' '\n                  << (C_k / (N_k * q_F / (q_F + q_L))) << std::endl;\n        break;\n      }\n    }\n\n    return EXIT_SUCCESS;\n\n  } catch (const std::exception &aErr) {\n    LOG(ERROR) << \"Exception caught: \" << aErr.what();\n\n  } catch (...) {\n    LOG(ERROR) << \"Unknown exception caught\";\n  }\n\n  return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "d80aee6ccd6e95fd3471df2d84aa622244f50d90", "size": 7641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Executables/sfm-provisioning.cpp", "max_stars_repo_name": "ccicconetti/markovsim", "max_stars_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Executables/sfm-provisioning.cpp", "max_issues_repo_name": "ccicconetti/markovsim", "max_issues_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Executables/sfm-provisioning.cpp", "max_forks_repo_name": "ccicconetti/markovsim", "max_forks_repo_head_hexsha": "a90c24ed63788d67428be7b1bbc798a58718520b", "max_forks_repo_licenses": ["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.5131578947, "max_line_length": 101, "alphanum_fraction": 0.627273917, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.5537349913651549}}
{"text": "#include <boost/lexical_cast.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <cmath>\r\n#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\nusing boost::lexical_cast;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Generate the n'th term in the Fibonacci sequence.\r\ncpp_int fib(cpp_int n) {\r\n\tstatic map<cpp_int, cpp_int> memory;\r\n\tif(n <= 1) {\r\n\t\treturn n;\r\n\t}\r\n\tif(memory.count(n) > 0) {\r\n\t\treturn memory[n];\r\n\t}\r\n\tcpp_int ret = fib(n - 1) + fib(n - 2);\r\n\tmemory[n] = ret;\r\n\treturn ret;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tint index = 1;\r\n\tint num_digits = 0;\r\n\twhile(num_digits != 1000) {\r\n\t\tstring s = lexical_cast<string>(fib(index++));\r\n\t\tnum_digits = s.size();\r\n\t}\r\n\tcout << (index - 1) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "692bab6f118d6ee10a5e3bb58dfece95a39de451", "size": 759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/25/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/25/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/1-50/25/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 21.6857142857, "max_line_length": 53, "alphanum_fraction": 0.6337285903, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.5537337819350527}}
{"text": "#include <math.h>\n#include <EigenUnsupported/Eigen/KroneckerProduct>\n#include \"Core/Utilities/QProgInfo/QCircuitInfo.h\"\n#include \"Core/Utilities/Tools/MatrixDecomposition.h\"\n#include <chrono>\n#include \"Core/Utilities/QProgInfo/Visualization/QVisualization.h\"\n#include \"QAlg/Base_QCircuit/AmplitudeEncode.h\"\n\nUSING_QPANDA\nusing namespace std;\nusing namespace chrono;\n\n#define PRINT_TRACE 0\n#if PRINT_TRACE\n#define PTrace printf\n#define PTraceMat(mat) (std::cout << (mat) << endl)\n#define PTraceCircuit(cir) (std::cout << cir << endl)\n#else\n#define PTrace\n#define PTraceMat(mat)\n#define PTraceCircuit(cir)\n#endif\n\n#define MAX_MATRIX_PRECISION 1e-10\n\nusing MatrixSequence = std::vector<MatrixUnit>;\nusing DecomposeEntry = std::pair<int, MatrixSequence>;\n\nusing ColumnOperator = std::vector<DecomposeEntry>;\nusing MatrixOperator = std::vector<ColumnOperator>;\n\nusing SingleGateUnit = std::pair<MatrixSequence, QStat>;\n\nstatic void upper_partition(int order, MatrixOperator &entries)\n{\n\tauto index = (int)std::log2(entries.size() + 1) - (int)std::log2(order) - 1;\n\n\tfor (auto cdx = 0; cdx < order - 1; ++cdx)\n\t{\n\t\tfor (auto rdx = 0; rdx < order - cdx - 1; ++rdx)\n\t\t{\n\t\t\tauto entry = entries[cdx][rdx];\n\n\t\t\tentry.first += order;\n\t\t\tentry.second[index] = MatrixUnit::SINGLE_P1;\n\n\t\t\tentries[cdx + order].emplace_back(entry);\n\t\t}\n\t}\n\n    return;\n}\n\n\nstatic bool entry_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint lj = ((cdx - 1) >> (udx - 1)) & 1;\n\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if 1 ≤ j ≤ m and cj = lj' = 1 , return true\n\tauto mat = units[units.size() - udx];\n\treturn udx >= 1\n\t\t&& udx <= M\n\t\t&& lj\n\t\t&& mat == MatrixUnit::SINGLE_P1;\n}\n\nstatic bool steps_requirement(const MatrixSequence& units, int udx, int cdx)\n{\n\tint M = 1;\n\twhile (cdx)\n\t{\n\t\tcdx >>= 1;\n\t\tM += cdx ? 1 : 0;\n\t}\n\n\t//if j = n and none of cn...cm+1 is 1 , return true\n\tif (units.size() != udx)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\tauto iter = std::find(units.begin(), units.end() - M, MatrixUnit::SINGLE_P1);\n\t\treturn (units.end() - M) == iter;\n\t}\n}\n\nstatic void under_partition(int order, MatrixOperator& entries)\n{\n\tauto qubits = (int)std::log2(entries.size() + 1);\n\n\tfor (auto cdx = 1; cdx < order; ++cdx)\n\t{\n\t\tif (cdx & 1)\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto value = entries[0][rdx + order - 1].first ^ cdx;\n\t\t\t\tauto entry = make_pair(value, entries[cdx - 1][rdx + order - cdx].second);\n\n\t\t\t\tentries[cdx].emplace_back(entry);\n\t\t\t}\n\n\t\t\tauto &units = entries[cdx].back().second;\n\t\t\tfor (auto idx = 0; idx < (int)std::log2(order); ++idx)\n\t\t\t{\n\t\t\t\tunits[qubits - idx - 1] = ((cdx >> idx) & 1) ?\n\t\t\t\t\tMatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (auto rdx = 0; rdx < order; ++rdx)\n\t\t\t{\n\t\t\t\tauto range = (int)std::log2(order) + 1;\n\t\t\t\tauto refer = entries[0][rdx + order - 1].second;\n\t\t\t\tauto entry = entries[0][rdx + order - 1].first ^ cdx;\n\n\t\t\t\tMatrixSequence units(refer.begin() + qubits - range, refer.end());\n\n\t\t\t\tfor (auto udx = 1; udx <= range; ++udx)  /*udx = j , cdx = L*/\n\t\t\t\t{\n\t\t\t\t\tbool steps_accord = steps_requirement(units, udx, cdx + 1);\n\t\t\t\t\tbool entry_accord = entry_requirement(units, udx, cdx + 1);\n\n\t\t\t\t\tunits[range - udx] = steps_accord ? MatrixUnit::SINGLE_P1 :\n\t\t\t\t\t\tentry_accord ? MatrixUnit::SINGLE_P0 : units[range - udx];\n\t\t\t\t}\n\n\t\t\t\tfor (auto idx = 0; idx < qubits - range; ++idx)\n\t\t\t\t{\n\t\t\t\t\tunits.insert(units.begin(), MatrixUnit::SINGLE_I2);\n\t\t\t\t}\n\n\t\t\t\tentries[cdx].emplace_back(make_pair(entry, units));\n\t\t\t}\n\n\t\t\tauto refer_opt = entries[0][2 * order - 2].second;\n\t\t\tfor (auto idx = 0; idx < qubits; ++idx)\n\t\t\t{\n\t\t\t\tif ((cdx >> idx) & 1)\n\t\t\t\t{\n\t\t\t\t\trefer_opt[qubits - idx - 1] = MatrixUnit::SINGLE_P1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tentries[cdx].back().second = refer_opt;\n\t\t}\n\t}\n\n    return;\n}\n\nstatic void controller(MatrixSequence &sequence, const EigenMatrix2c U2, EigenMatrixXc &matrix)\n{\n\tEigenMatrix2c P0;\n\tEigenMatrix2c P1;\n\tEigenMatrix2c I2;\n\n\tP0 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0);\n\tP1 << Eigen::dcomplex(0, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\tI2 << Eigen::dcomplex(1, 0), Eigen::dcomplex(0, 0),\n\t\t  Eigen::dcomplex(0, 0), Eigen::dcomplex(1, 0);\n\n\tstd::map<MatrixUnit, std::function<EigenMatrix2c()>> mapping =\n\t{\n\t\t{ MatrixUnit::SINGLE_P0, [&]() {return P0; } },\n\t\t{ MatrixUnit::SINGLE_P1, [&]() {return P1; } },\n\t\t{ MatrixUnit::SINGLE_I2, [&]() {return I2; } },\n\t\t{ MatrixUnit::SINGLE_V2, [&]() {return U2 - I2; } }\n\t};\n\n\tauto order = sequence.size();\n\tEigenMatrixXc Un = EigenMatrixXc::Identity(1, 1);\n\tEigenMatrixXc In = EigenMatrixXc::Identity(1ull << order, 1ull << order);\n\n\tfor (const auto &val : sequence)\n\t{\n\t\tEigenMatrix2c M2 = mapping.find(val)->second();\n\t\tUn = Eigen::kroneckerProduct(Un, M2).eval();\n\t}\n\n\tmatrix = In + Un;\n    return;\n}\n\nstatic void recursive_partition(const EigenMatrixXc& sub_matrix, MatrixOperator &entries)\n{\n    Eigen::Index order = sub_matrix.rows();\n    if (1 == order)\n    {\n        return;\n    }\n    else\n    {\n        EigenMatrixXc corner = sub_matrix.topLeftCorner(order / 2, order / 2);\n\n        recursive_partition(corner, entries);\n\n        upper_partition(order / 2, entries);\n        under_partition(order / 2, entries);\n    }\n\n    return;\n}\n\nstatic void decomposition(EigenMatrixXc& matrix, MatrixOperator& entries, std::vector<SingleGateUnit>& cir_units)\n{\n\tfor (auto cdx = 0; cdx < entries.size(); ++cdx)\n\t{\n\t\tauto opts = entries[cdx].size();\n\t\tfor (auto idx = 0; idx < opts; ++idx)\n\t\t{\n\t\t\tauto rdx = entries[cdx][idx].first;\n\t\t\tauto opt = entries[cdx][idx].second;\n\n\t\t\tif ((EigenComplexT(0, 0) == matrix(rdx, cdx) && (idx != opts - 1)) ||\n\t\t\t\t(EigenComplexT(1, 0) == matrix(cdx + 1, cdx) && (idx == opts - 1)))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEigenMatrix2c C2; /*placeholder*/\n\t\t\t\tC2 << EigenComplexT(0, 1), EigenComplexT(0, 1),\n\t\t\t\t\tEigenComplexT(0, 1), EigenComplexT(0, 1);\n\n\t\t\t\tEigenMatrixXc Cn;\n\t\t\t\tcontroller(opt, C2, Cn);\n\n\t\t\t\tQnum indices(2);\n\t\t\t\tfor (Eigen::Index index = 0; index < (1ull << opt.size()); ++index)\n\t\t\t\t{\n\t\t\t\t\tif (Cn(rdx, index) != EigenComplexT(0, 0))\n\t\t\t\t\t{\n\t\t\t\t\t\tindices[index == rdx] = index;\n\t\t\t\t\t}  \n\t\t\t\t}\n\n\t\t\t\tEigenComplexT C0 = matrix(indices[0], cdx);  /*The entry to be eliminated */\n\t\t\t\tEigenComplexT C1 = matrix(indices[1], cdx);  /*The corresponding entry */\n\n\t\t\t\tEigenComplexT V11, V12, V21, V22;\n\n\t\t\t\tif (indices[0] < indices[1])\n\t\t\t\t{\n\t\t\t\t\tV11 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tV11 = -C0 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV12 = C1 / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV21 = std::conj(C1) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t\tV22 = std::conj(C0) / std::sqrt(std::norm(C0) + std::norm(C1));\n\t\t\t\t}\n\n\t\t\t\tEigenMatrix2c V2;\n\t\t\t\tV2 << V11, V12, V21, V22;\n\n\t\t\t\tEigenMatrixXc Un;\n\t\t\t\tcontroller(opt, V2, Un);\n\n\t\t\t\tmatrix = Un * matrix;\n\n\t\t\t\tQStat M2 = { (qcomplex_t)V11 ,(qcomplex_t)V12 ,(qcomplex_t)V21 ,(qcomplex_t)V22 };\n\t\t\t\tcir_units.insert(cir_units.begin(), std::make_pair(opt, M2));\n\t\t\t}\n\t\t}\n\t}\n\n\tEigenMatrix2c V2 = matrix.bottomRightCorner(2, 2);\n\tif (EigenMatrixXc::Identity(2, 2) != V2)\n\t{\n\t\tQStat M2 = { (qcomplex_t)((EigenComplexT)1.0 / V2(0,0)), (qcomplex_t)(V2(0,1)),\n\t\t\t\t\t (qcomplex_t)(V2(1,0)) , (qcomplex_t)((EigenComplexT)1.0 / V2(1,1))};\n\n\t\tauto entry = entries.back().back().second;\n\t\tcir_units.insert(cir_units.begin(), std::make_pair(entry, M2));\n\t}\n}\n\nstatic void initialize(EigenMatrixXc& matrix, MatrixOperator& entries)\n{\n    auto qubits = (int)std::log2(matrix.rows());\n\n    MatrixSequence Cns(qubits, MatrixUnit::SINGLE_I2);\n    Cns.back() = MatrixUnit::SINGLE_V2;\n    entries.front().emplace_back(make_pair(1, Cns));\n\n    ColumnOperator& column = entries.front();\n    for (auto idx = 1; idx < qubits; ++idx)\n    {\n        size_t path = 1ull << idx;\n        for (auto opt = 0; opt < (1 << idx) - 1; ++opt)\n        {\n            auto entry = column[opt].first;\n            auto units = column[opt].second;\n\n            // 1 : none of cn−1, . . . , c1 equals 1\n            // * : otherwise\n            auto iter = std::find(units.end() - idx, units.end(), MatrixUnit::SINGLE_P1);\n\n            units[units.size() - 1 - idx] = (units.end() == iter) ?\n                MatrixUnit::SINGLE_P1 : MatrixUnit::SINGLE_I2;\n\n            column.emplace_back(make_pair(entry + path, units));\n        }\n\n        MatrixSequence Lns(qubits, MatrixUnit::SINGLE_I2);\n        Lns[qubits - idx - 1] = MatrixUnit::SINGLE_V2;\n\n        column.emplace_back(make_pair((1ull << idx), Lns));\n    }\n\n    return;\n}\n\nstatic void general_scheme(EigenMatrixXc& matrix, std::vector<SingleGateUnit>& cir_units)\n{\n\tMatrixOperator entries;\n\tfor (auto idx = 1; idx < matrix.cols(); ++idx)\n\t{\n\t\tColumnOperator Co;\n\t\tentries.emplace_back(Co);\n\t}\n\n\tinitialize(matrix, entries);\n \trecursive_partition(matrix, entries);\n\tdecomposition(matrix, entries, cir_units);\n\n    return;\n}\n\nstatic void circuit_insert(QVec& qubits, std::vector<SingleGateUnit>& cir_units, QCircuit &circuit)\n{\n\tstd::sort(qubits.begin(), qubits.end(), [&](Qubit *a, Qubit *b)\n\t{\n\t\treturn a->getPhysicalQubitPtr()->getQubitAddr()\n\t\t\t < b->getPhysicalQubitPtr()->getQubitAddr();\n\t});\n\n\tauto rank = qubits.size();\n\tfor (auto &val : cir_units)\n\t{\n\t\tQVec control;\n\t\tQCircuit cir;\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_P0 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcir << X(qubits[qdx]);\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse if (MatrixUnit::SINGLE_P1 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcontrol.emplace_back(qubits[qdx]);\n\t\t\t}\n\t\t\telse\n\t\t\t{}\n\t\t}\n\n\t\tfor (auto qdx = 0; qdx < rank; qdx++)\n\t\t{\n\t\t\tif (MatrixUnit::SINGLE_V2 == val.first[qdx])\n\t\t\t{\n\t\t\t\tcircuit << cir\n\t\t\t\t\t    << U4(val.second, qubits[qdx]).control(control).dagger()\n\t\t\t\t\t\t<< cir;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/*******************************************************************\n*                      class DiagonalMatrixDecompose\n********************************************************************/\nclass DiagonalMatrixDecompose\n{\npublic:\n\tDiagonalMatrixDecompose() {}\n\t~DiagonalMatrixDecompose() {}\n\n\n\tQCircuit decompose(const QVec& qubits, const QStat& src_mat)\n\t{\n\t\t//check param\n\t\tif (!is_unitary_matrix(src_mat))\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, the input matrix is not a unitary-matrix.\");\n\t\t}\n\n\t\tconst auto mat_dimension = sqrt(src_mat.size());\n\t\tconst auto need_qubits_num = ceil(log2(mat_dimension));\n\t\tif (need_qubits_num > qubits.size())\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed on HQRDecompose, no enough qubits.\");\n\t\t}\n\n\t\tQCircuit decompose_result_cir;\n\t\tm_qubits = qubits;\n\t\tQVec controlqvec = qubits;\n\t\tcontrolqvec.pop_back();\n\t\tQStat tmp_mat22; //2*2 unitary matrix\n\t\tconst size_t tmp_base_unitary_cnt = mat_dimension / 2;\n\t\tlong pre_index = -1;\n\t\tfor (size_t i = 0; i < tmp_base_unitary_cnt; ++i)\n\t\t{\n\t\t\tif (0 == i)\n\t\t\t{\n\t\t\t\tQCircuit index_cir_zero = index_to_circuit(0, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir_zero;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQCircuit index_cir = index_to_merge_circuit(i, pre_index, controlqvec);\n\t\t\t\tdecompose_result_cir << index_cir;\n\t\t\t}\n\n\t\t\ttmp_mat22.clear();\n\t\t\tconst size_t tmp_row = (2 * i * mat_dimension) + (2 * i);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + 1]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension]);\n\t\t\ttmp_mat22.push_back(src_mat[tmp_row + mat_dimension + 1]);\n\t\t\tQGate tmp_u4 = U4(tmp_mat22, qubits.back()).control(controlqvec);\n\t\t\tQGATE_SPACE::U4* p_gate = dynamic_cast<QGATE_SPACE::U4*>(tmp_u4.getQGate());\n\t\t\tif ((abs(p_gate->getAlpha()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getBeta()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getGamma()) > MAX_MATRIX_PRECISION)\n\t\t\t\t|| (abs(p_gate->getDelta()) > MAX_MATRIX_PRECISION))\n\t\t\t{\n\t\t\t\tdecompose_result_cir << tmp_u4;\n\t\t\t}\n\n\t\t\tpre_index = i;\n\t\t}\n\n\t\treturn decompose_result_cir;\n\t}\n\nprotected:\n\tQCircuit index_to_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif (0 == index % 2)\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t pre_index = index - 1;\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\t\t\tpre_index /= 2;\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\n\tQCircuit index_to_merge_circuit(size_t index, long pre_index, QVec& controlqvec)\n\t{\n\t\tif (0 == index)\n\t\t{\n\t\t\tQCERR_AND_THROW_ERRSTR(run_fail, \"Error: failed to build merge-index-circuit, the index must be >0.\");\n\t\t}\n\n\t\tsize_t tmp_pre_index = pre_index;\n\t\tif (pre_index < 0)\n\t\t{\n\t\t\ttmp_pre_index = 1;\n\t\t}\n\t\t\n\t\tQCircuit ret_cir;\n\t\tsize_t data_qubits_cnt = controlqvec.size();\n\t\tfor (size_t i = 0; i < data_qubits_cnt; ++i)\n\t\t{\n\t\t\tif ((index % 2) != (tmp_pre_index % 2))\n\t\t\t{\n\t\t\t\tret_cir << X(controlqvec[data_qubits_cnt - i - 1]);\n\t\t\t}\n\n\t\t\tindex /= 2;\n\n\t\t\tif (pre_index > 0)\n\t\t\t{\n\t\t\t\ttmp_pre_index /= 2;\n\t\t\t}\n\t\t}\n\n\t\treturn ret_cir;\n\t}\n\nprivate:\n\tQVec m_qubits;\n};\n\n\n/*******************************************************************\n*                      public interface\n********************************************************************/\nQCircuit QPanda::matrix_decompose_qr(QVec qubits, const QStat& src_mat)\n{\n\tauto order = std::sqrt(src_mat.size());\n\tEigenMatrixXc tmp_mat = EigenMatrixXc::Map(&src_mat[0], order, order);\n\n    return matrix_decompose_qr(qubits, tmp_mat);\n}\n\nQCircuit QPanda::matrix_decompose_qr(QVec qubits, EigenMatrixXc& src_mat)\n{\n\tif (!src_mat.isUnitary(MAX_MATRIX_PRECISION))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"Non-unitary matrix.\");\n\t}\n\n\tif (qubits.size() != log2(src_mat.cols()))\n\t{\n\t\tQCERR_AND_THROW_ERRSTR(invalid_argument, \"The qubits number is error or the input matrix is not a 2^n-dimensional matrix.\");\n\t}\n\n\tQCircuit output_circuit;\n    //QR decompose\n    std::vector<SingleGateUnit> cir_units;\n    general_scheme(src_mat, cir_units);\n    circuit_insert(qubits, cir_units, output_circuit);\n\t\n\treturn output_circuit;\n}\n\nQCircuit QPanda::diagonal_matrix_decompose(const QVec& qubits, const QStat& src_mat)\n{\n\treturn DiagonalMatrixDecompose().decompose(qubits, src_mat);\n}\n", "meta": {"hexsha": "89c1e459c7728828f866e3b550445064fba7004b", "size": 14769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_stars_repo_name": "Guogggg/QPanda-2", "max_stars_repo_head_hexsha": "dc8191a438c01307eaf29937cc52d324cd50d31e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-12T01:26:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T01:26:18.000Z", "max_issues_repo_path": "Core/Utilities/Tools/MatrixDecomposition.cpp", "max_issues_repo_name": "Guogggg/QPanda-2", "max_issues_repo_head_hexsha": "dc8191a438c01307eaf29937cc52d324cd50d31e", "max_issues_repo_licenses": ["Apache-2.0"], "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/Utilities/Tools/MatrixDecomposition.cpp", "max_forks_repo_name": "Guogggg/QPanda-2", "max_forks_repo_head_hexsha": "dc8191a438c01307eaf29937cc52d324cd50d31e", "max_forks_repo_licenses": ["Apache-2.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.8199300699, "max_line_length": 126, "alphanum_fraction": 0.6215722121, "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.5536643165945576}}
{"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// Jonathan Driedger, Thomas Prätzlich, and Meinard Müller\n// Let It Bee — Towards NMF-Inspired Audio Mosaicing\n// Proceedings of ISMIR 2015\n\n#pragma once\n\n#include \"STFT.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nnamespace fluid {\nnamespace algorithm {\n\nusing _impl::asEigen;\nusing _impl::asFluid;\nusing Eigen::Array;\nusing Eigen::ArrayXd;\nusing Eigen::ArrayXXd;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nclass NMFCross\n{\n\npublic:\n  // pass iteration number; returns true if able to continue (i.e. not\n  // cancelled)\n  using ProgressCallback = std::function<bool(index)>;\n\n  NMFCross(index nIterations) : mIterations(nIterations) {}\n\n  static void synthesize(const RealMatrixView h, const ComplexMatrixView w,\n                         ComplexMatrixView out)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    MatrixXd  H = asEigen<Matrix>(h);\n    MatrixXcd W = asEigen<Matrix>(w);\n    MatrixXcd V = H * W;\n    out <<= asFluid(V);\n  }\n\n  void process(const RealMatrixView X, RealMatrixView H1, RealMatrixView W0,\n               index r, index p, index c) const\n  {\n    index nFrames = X.extent(0);\n    index nBins = X.extent(1);\n    index rank = W0.extent(0);\n    nBins = W0.extent(1);\n    MatrixXd W = asEigen<Matrix>(W0).transpose();\n    MatrixXd H;\n    H = MatrixXd::Random(rank, nFrames) * 0.5 +\n        MatrixXd::Constant(rank, nFrames, 0.5);\n    MatrixXd V = asEigen<Matrix>(X).transpose();\n    multiplicativeUpdates(V, W, H, r, p, c);\n    MatrixXd HT = H.transpose();\n    H1 <<= asFluid(HT);\n  }\n\n  void addProgressCallback(ProgressCallback&& callback)\n  {\n    mCallbacks.emplace_back(std::move(callback));\n  }\n\nprivate:\n  index                         mIterations;\n  std::vector<ProgressCallback> mCallbacks;\n\n  std::vector<index> topC(Eigen::VectorXd vec, index c) const\n  {\n    using namespace std;\n    vector<double> stdVec(vec.data(), vec.data() + vec.size());\n    sort(stdVec.begin(), stdVec.end());\n    vector<index> idx(asUnsigned(vec.size()));\n    iota(idx.begin(), idx.end(), 0);\n    sort(idx.begin(), idx.end(),\n         [&vec](index i1, index i2) { return vec[i1] > vec[i2]; });\n    auto result = std::vector<index>(idx.begin(), idx.begin() + c);\n    return result;\n  }\n\n  Eigen::MatrixXd promoteContinuity(MatrixXd& H, index size) const\n  {\n    index    halfSize = (size - 1) / 2;\n    MatrixXd kernel = MatrixXd::Identity(size, size);\n    MatrixXd padded = MatrixXd::Zero(H.rows() + size, H.cols() + size);\n    MatrixXd output = MatrixXd::Zero(H.rows(), H.cols());\n    padded.block(halfSize, halfSize, H.rows(), H.cols()) = H;\n    for (index i = 0; i < H.rows(); i++)\n    {\n      for (index j = 0; j < H.cols(); j++)\n      {\n        output(i, j) =\n            padded.block(i, j, size, size).cwiseProduct(kernel).sum();\n      }\n    }\n    return output;\n  }\n\n  Eigen::MatrixXd enforceTemporalSparseness(MatrixXd& H, index size,\n                                            index iteration) const\n  {\n    index    halfSize = (size - 1) / 2;\n    MatrixXd padded = MatrixXd::Zero(H.rows(), H.cols() + size);\n    MatrixXd output = MatrixXd::Zero(H.rows(), H.cols());\n    padded.block(0, halfSize, H.rows(), H.cols()) = H;\n    for (index i = 0; i < H.rows(); i++)\n    {\n      for (index j = 0; j < H.cols(); j++)\n      {\n        VectorXd        neighborhood = padded.row(i).segment(j, size);\n        VectorXd::Index maxIndex{0};\n        neighborhood.maxCoeff(&maxIndex);\n        if (int(maxIndex) != halfSize)\n        { output(i, j) = H(i, j) * (1 - ((iteration + 1) / mIterations)); }\n        else\n        {\n          output(i, j) = H(i, j);\n        }\n      }\n    }\n    return output;\n  }\n\n\n  Eigen::MatrixXd restrictPolyphony(MatrixXd& H, ArrayXd& energyInW, index size,\n                                    index iteration) const\n  {\n    MatrixXd output = MatrixXd::Zero(H.rows(), H.cols());\n    for (index k = 0; k < H.cols(); k++)\n    {\n      ArrayXd wCol = H.col(k).array() * energyInW.array();\n      output.col(k) = H.col(k) * (1 - ((iteration + 1) / mIterations));\n      auto top = topC(wCol, size);\n      for (auto t : top) { output(t, k) = H(t, k); }\n    }\n    return output;\n  }\n  void multiplicativeUpdates(MatrixXd& V, MatrixXd& W, MatrixXd& H, index r,\n                             index p, index c) const\n  {\n    using namespace std;\n    using namespace Eigen;\n    double const epsilon = std::numeric_limits<double>::epsilon();\n    MatrixXd     ones = MatrixXd::Ones(V.rows(), V.cols());\n    W = W.array().max(epsilon).matrix();\n    // ArrayXd wNorm = W.colwise().sum();\n    // W.array().rowwise() /= wNorm.transpose());\n    ArrayXd energyInW = W.array().square().colwise().sum();\n    for (index i = 0; i < mIterations; i++)\n    {\n      if ((i % 1) == 0)\n      { // TODO: original version seems to work better with one in 5 iterations\n        H = enforceTemporalSparseness(H, r, i);\n        H = restrictPolyphony(H, energyInW, p, i);\n        H = promoteContinuity(H, c);\n      }\n      ArrayXXd V2 = (W * H).array().max(epsilon);\n      ArrayXXd hnum = (W.transpose() * (V.array() / V2).matrix()).array();\n      ArrayXXd hden = (W.transpose() * ones).array();\n      H = (H.array() * hnum / hden.max(epsilon)).matrix();\n      // MatrixXd R = W * H;\n      // R = R.cwiseMax(epsilon);\n      // double divergence = (V.cwiseProduct(V.cwiseQuotient(R)) - V + R).sum();\n      for (auto& cb : mCallbacks)\n        if (!cb(i + 1)) return;\n    }\n    V = W * H;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "2840418d3a37a5e8592d4d5f9ce75272d93939bd", "size": 6037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NMFCross.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/NMFCross.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/NMFCross.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": 31.9417989418, "max_line_length": 80, "alphanum_fraction": 0.6007950969, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.5536643063708996}}
{"text": "#ifndef HAMILTONIANS_XXXXMG_HPP\n#define HAMILTONIANS_XXXXMG_HPP\n#include <Eigen/Eigen>\n#include <nlohmann/json.hpp>\n\nclass XXXMG\n{\nprivate:\n\tint n_;\n\npublic:\n\n\tXXXMG(int n)\n\t\t: n_(n)\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\", \"XXXXMG\"},\n\t\t\t{\"n\", n_},\n\t\t};\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::Scalar operator()(const State& smp) const\n\t{\n\t\tconstexpr double J1 = 1.0;\n\t\tconstexpr double J2 = 0.5;\n\t\ttypename State::Scalar s = 0.0;\n\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(0)*smp.sigmaAt(1);\n\t\t\ts += -J1/2*yysign; //zz\n\t\t\ts += J1/2*(1.0+yysign)*smp.ratio(0, 1); //xx+yy\n\t\t}\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(n_-2)*smp.sigmaAt(n_-1);\n\t\t\ts += -J1/2*yysign; //zz\n\t\t\ts += J1/2*(1.0+yysign)*smp.ratio(n_-2, n_-1); //xx+yy\n\t\t}\t\n\t\t//Nearest-neighbor\n\t\tfor(int i = 1; i < (n_-3); i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt(i+1);\n\t\t\ts += -J1*yysign; //zz\n\t\t\ts += J1*(1.0+yysign)*smp.ratio(i, i+1); //xx+yy\n\t\t}\n\t\t//Next-nearest-neighbor\n\t\tfor(int i = 0; i < n_-3; i++)\n\t\t{\n\t\t\tdouble yysign = -smp.sigmaAt(i)*smp.sigmaAt(i+2);\n\t\t\ts += -J2*yysign; //zz\n\t\t\ts += J2*(1.0+yysign)*smp.ratio(i, i+2); //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\tconstexpr double J1 = 1.0;\n\t\tconstexpr double J2 = 0.5;\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*(1.0 - sgn*1.0);\n\t\t\tm[col] += J1*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*(1.0 - sgn*1.0);\n\t\t\tm[col] += J2*sgn;\n\t\t}\n\t\treturn m;\n\t}\n};\n#endif//HAMILTONIANS_XXXXMG_HPP\n", "meta": {"hexsha": "a7dea7195d048175920001916442e2b9c70ce237", "size": 1861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XXXMG.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/XXXMG.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/XXXMG.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.1477272727, "max_line_length": 58, "alphanum_fraction": 0.5357334766, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5536328675167085}}
{"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#ifndef quantlib_gaussian_copula_policy_hpp\n#define quantlib_gaussian_copula_policy_hpp\n\n#include <vector>\n#include <numeric>\n#include <algorithm>\n\n#include <boost/bind.hpp>\n\n#include <ql/utilities/disposable.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n\nnamespace QuantLib {\n\n    /*! Gaussian Latent Model's copula policy. Its simplicity is a result of \n      the convolution stability of the Gaussian distribution.\n    */\n    /* This is the only case that would have allowed the policy to be static, \n    but other copulas will need parameters and initialization.*/\n    struct GaussianCopulaPolicy {\n\n        typedef int initTraits;\n\n        explicit GaussianCopulaPolicy(\n            const std::vector<std::vector<Real> >& factorWeights = \n                std::vector<std::vector<Real> >(), \n            const initTraits& dummy = int())\n        : numFactors_(factorWeights.size() + factorWeights[0].size())\n        {\n            /* check factors in LM are normalized. */\n            for(Size iLVar=0; iLVar<factorWeights.size(); iLVar++) {\n                Real factorsNorm = \n                    std::inner_product(factorWeights[iLVar].begin(), \n                        factorWeights[iLVar].end(), \n                        factorWeights[iLVar].begin(), 0.);\n                QL_REQUIRE(factorsNorm < 1., \n                    \"Non normal random factor combination.\");\n            }\n            /* check factor matrix is squared .......... */\n        }\n\n        /*! Number of independent random factors. \n        This is the only methos that ould stop the class from being static, it\n        is needed for the MC generator construction.\n        */\n        Size numFactors() const {\n            return numFactors_;\n        }\n\n        //! returns a copy of the initialization arguments\n        initTraits getInitTraits() const {\n            return initTraits();\n        }\n\n        /*! Cumulative probability of the indexed latent variable \n            @param iVariable The index of the latent variable requested.\n        */\n        Probability cumulativeY(Real val, Size iVariable) const {\n            return cumulative_(val);\n        }\n        //! Cumulative probability of the idiosyncratic factors (all the same)\n        Probability cumulativeZ(Real z) const {\n            return cumulative_(z);\n        }\n        /*! Probability density of a given realization of values of the systemic\n          factors (remember they are independent). In the normal case, since \n          they all follow the same law it is just a trivial product of the same \n          density. \n          Intended to be used in numerical integration of an arbitrary function \n          depending on those values.\n        */\n        Probability density(const std::vector<Real>& m) const {\n            return std::accumulate(m.begin(), m.end(), 1., \n                boost::bind(std::multiplies<Real>(), _1, \n                    boost::bind(density_, _2)));\n        }\n        /*! Returns the inverse of the cumulative distribution of the (modelled) \n          latent variable (as indexed by iVariable). The normal stability avoids\n          the convolution of the factors' distributions\n        */\n        Real inverseCumulativeY(Probability p, Size iVariable) const {\n            return InverseCumulativeNormal::standard_value(p);\n        }\n        /*! Returns the inverse of the cumulative distribution of the \n        idiosyncratic factor (identically distributed for all latent variables)\n        */\n        Real inverseCumulativeZ(Probability p) const {\n            return InverseCumulativeNormal::standard_value(p);\n        }\n        /*! Returns the inverse of the cumulative distribution of the \n          systemic factor iFactor.\n        */\n        Real inverseCumulativeDensity(Probability p, Size iFactor) const {\n            return InverseCumulativeNormal::standard_value(p);\n        }\n        //! \n        //to use this (by default) version, the generator must be a uniform one.\n        Disposable<std::vector<Real> > \n            allFactorCumulInverter(const std::vector<Real>& probs) const {\n            std::vector<Real> result;\n            result.resize(probs.size());\n            std::transform(probs.begin(), probs.end(), result.begin(), \n                boost::bind(&InverseCumulativeNormal::standard_value, _1));\n            return result;\n        }\n    private:\n        mutable Size numFactors_;\n        // no op =\n        static const NormalDistribution density_;\n        static const CumulativeNormalDistribution cumulative_;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "c8802f1da090f496507bdfdc62f65f8f33e77ec8", "size": 5352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/math/gaussiancopulapolicy.hpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/experimental/math/gaussiancopulapolicy.hpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/math/gaussiancopulapolicy.hpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 39.6444444444, "max_line_length": 81, "alphanum_fraction": 0.6350896861, "num_tokens": 1089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.6513548782017745, "lm_q1q2_score": 0.553632866644644}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_OWENS_T_HPP\r\n#define STAN_MATH_PRIM_SCAL_FUN_OWENS_T_HPP\r\n\r\n#include <stan/math/prim/meta.hpp>\r\n#include <boost/math/special_functions/owens_t.hpp>\r\n\r\nnamespace stan {\r\nnamespace math {\r\n\r\n/**\r\n * Return the result of applying Owen's T function to the\r\n * specified arguments.\r\n *\r\n * Used to compute the cumulative density function for the skew normal\r\n * distribution.\r\n *\r\n   \\f[\r\n   \\mbox{owens\\_t}(h, a) =\r\n   \\begin{cases}\r\n     \\mbox{owens\\_t}(h, a) & \\mbox{if } -\\infty\\leq h, a \\leq \\infty \\\\[6pt]\r\n     \\textrm{NaN} & \\mbox{if } h = \\textrm{NaN or } a = \\textrm{NaN}\r\n   \\end{cases}\r\n   \\f]\r\n\r\n   \\f[\r\n   \\frac{\\partial\\, \\mbox{owens\\_t}(h, a)}{\\partial h} =\r\n   \\begin{cases}\r\n     \\frac{\\partial\\, \\mbox{owens\\_t}(h, a)}{\\partial h} & \\mbox{if }\r\n -\\infty\\leq h, a\\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } h = \\textrm{NaN\r\n or } a = \\textrm{NaN} \\end{cases} \\f]\r\n\r\n   \\f[\r\n   \\frac{\\partial\\, \\mbox{owens\\_t}(h, a)}{\\partial a} =\r\n   \\begin{cases}\r\n     \\frac{\\partial\\, \\mbox{owens\\_t}(h, a)}{\\partial a} & \\mbox{if }\r\n -\\infty\\leq h, a\\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } h = \\textrm{NaN\r\n or } a = \\textrm{NaN} \\end{cases} \\f]\r\n\r\n   \\f[\r\n   \\mbox{owens\\_t}(h, a) = \\frac{1}{2\\pi} \\int_0^a\r\n \\frac{\\exp(-\\frac{1}{2}h^2(1+x^2))}{1+x^2}dx \\f]\r\n\r\n   \\f[\r\n   \\frac{\\partial \\, \\mbox{owens\\_t}(h, a)}{\\partial h} =\r\n -\\frac{1}{2\\sqrt{2\\pi}} \\operatorname{erf}\\left(\\frac{ha}{\\sqrt{2}}\\right)\r\n   \\exp\\left(-\\frac{h^2}{2}\\right)\r\n   \\f]\r\n\r\n   \\f[\r\n   \\frac{\\partial \\, \\mbox{owens\\_t}(h, a)}{\\partial a} =\r\n \\frac{\\exp\\left(-\\frac{1}{2}h^2(1+a^2)\\right)}{2\\pi (1+a^2)} \\f]\r\n *\r\n * @param h First argument\r\n * @param a Second argument\r\n * @return Owen's T function applied to the arguments.\r\n */\r\ninline double owens_t(double h, double a) { return boost::math::owens_t(h, a); }\r\n}  // namespace math\r\n}  // namespace stan\r\n\r\n#endif\r\n", "meta": {"hexsha": "111c3c2f6a243f7d4c19ab540d8671b2f0a2fd84", "size": 1885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/fun/owens_t.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/scal/fun/owens_t.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/scal/fun/owens_t.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": 30.4032258065, "max_line_length": 81, "alphanum_fraction": 0.5846153846, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.5536328600904866}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// BendingEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Implements the bending energy from [Grinspun et al. 2003: Discrete Shells].\n//  We provide analytical gradients for the energy, but resort to automatic\n//  differentiation for Hessians.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  05/25/2019 15:43:17\n////////////////////////////////////////////////////////////////////////////////\n#ifndef BENDINGENERGY_HH\n#define BENDINGENERGY_HH\n\n#include <cmath>\n#include <Eigen/Dense>\n#include <array>\n#include <MeshFEM/AutomaticDifferentiation.hh>\n\n// Bending energy contributed by a single \"hinge\" (mesh edge) between two\n// triangles.\n// The triangle points are indexed as follows:\n//            p0-----p1            n1   n2\n//              \\ 1 / \\             ^   ^\n//               \\ /`.2\\             \\ /\n//               p2   `.\\             o\n//                      p3\n// We call the complement of the dihedral angle \"theta\". Then the bending energy is given by\n//      0.5 (theta - theta_bar)^2 ||e_bar||/h_bar\n// (we expect the code using this class to scale everything by the bending stiffness).\n\n// Get the indices corresponding to the four vertices in the hinge stencil for halfedge \"he\".\n//  p0-he->p1\n//    \\ 1 /2|\n//     \\ /`.|\n//     p2  p3\n// Note: \"he\" lies in triangle 2.\ntemplate<class HalfEdge>\nstd::array<int, 4> bendingHingeStencil(const HalfEdge &he) {\n    assert(he.isPrimary() && !he.isBoundary());\n    return {{ he.tail().index(),\n              he.tip ().index(),\n              he.opposite().next().tip().index(),\n              he           .next().tip().index() }};\n}\n\n// Templated by real number type \"_Real\" for autodiff.\ntemplate<class _Real>\nstruct HingeEnergy {\n    using Real = _Real;\n    using Pt = Eigen::Matrix<_Real, 3, 1>;\n    using Vec = Pt;\n\n    // Reference configuration quantities\n    // (We don't need autodiff types for these...)\n    double e_bar_len, h_bar;\n    double theta_bar;\n\n    // Deformed configuration quantities\n    Eigen::Matrix<Real, 3, 4> deformed_pts;\n    Real theta, e_len;\n    Real squared_dbl_A1, squared_dbl_A2;\n    Vec N1, N2; // un-normalized triangle normals (cross products of edge vectors)\n    Real e_01_dot_ehat, e_02_dot_ehat;\n    Real e_11_dot_ehat, e_12_dot_ehat;\n\n    // Copy the reference configuration quantities from an existing class of a different type\n    template<class _Real2>\n    HingeEnergy(HingeEnergy<_Real2> h2) : e_bar_len(h2.e_bar_len), h_bar(h2.h_bar), theta_bar(h2.theta_bar) {\n        e_bar_len      = h2.e_bar_len;\n        h_bar          = h2.h_bar;\n        theta_bar      = h2.theta_bar;\n\n        theta          = h2.theta;\n        e_len          = h2.e_len;\n        squared_dbl_A1 = h2.squared_dbl_A1;\n        squared_dbl_A2 = h2.squared_dbl_A2;\n        N1             = h2.N1;\n        N2             = h2.N2;\n        e_01_dot_ehat  = h2.e_01_dot_ehat;\n        e_02_dot_ehat  = h2.e_02_dot_ehat;\n\n        e_11_dot_ehat  = h2.e_11_dot_ehat;\n        e_12_dot_ehat  = h2.e_12_dot_ehat;\n    }\n\n    HingeEnergy(Eigen::Ref<const Pt> ref_p0,\n                Eigen::Ref<const Pt> ref_p1,\n                Eigen::Ref<const Pt> ref_p2,\n                Eigen::Ref<const Pt> ref_p3) {\n        Vec e = ref_p1 - ref_p0;\n        e_bar_len = e.norm();\n        e /= e_bar_len;\n\n        Vec ref_n1 = (ref_p2 - ref_p0).cross(ref_p1 - ref_p0),\n            ref_n2 = (ref_p1 - ref_p0).cross(ref_p3 - ref_p0);\n        double dbl_A1 = ref_n1.norm(),\n               dbl_A2 = ref_n2.norm();\n        h_bar = (dbl_A1 + dbl_A2) / (6.0 * e_bar_len); // 1/6 (h1 + h2) = 1/6 (b * h1 + b * h2) / b = 1/6(2 A1 + 2 A2) / b\n\n        // Note: n1, n2 needn't be normalized since atan2 is invariant to uniform scaling of its arguments.\n        theta_bar = atan2(ref_n2.cross(ref_n1).dot(e), ref_n1.dot(ref_n2)); // Note: can't use std::atan2 since this breaks ADL for autodiff types\n\n        setDeformedConfiguration(ref_p0, ref_p1, ref_p2, ref_p3);\n    }\n\n    void setDeformedConfiguration(Eigen::Ref<const Pt> p0,\n                                  Eigen::Ref<const Pt> p1,\n                                  Eigen::Ref<const Pt> p2,\n                                  Eigen::Ref<const Pt> p3) {\n        deformed_pts.col(0) = p0;\n        deformed_pts.col(1) = p1;\n        deformed_pts.col(2) = p2;\n        deformed_pts.col(3) = p3;\n\n        Vec e = p1 - p0;\n        e_len = e.norm();\n        e /= e_len;\n\n        N1 = (p2 - p0).cross(p1 - p0),\n        N2 = (p1 - p0).cross(p3 - p0);\n\n        squared_dbl_A1 = N1.squaredNorm();\n        squared_dbl_A2 = N2.squaredNorm();\n\n        // Note: n1, n2 needn't be normalized since atan2 is invariant to uniform scaling of its arguments.\n        theta = atan2(N2.cross(N1).dot(e), N1.dot(N2)); // Note: can't use std::atan2 since this breaks ADL for autodiff types\n\n        e_01_dot_ehat = e.dot(p1 - p2);\n        e_02_dot_ehat = e.dot(p1 - p3); // really the negation of e_02 based on the labeling in the derivation figure...\n\n        e_11_dot_ehat = e.dot(p2 - p0);\n        e_12_dot_ehat = e.dot(p3 - p0);\n\n        // Effectively disable this hinge's energy in degenerate configurations since\n        // these will introduce large and pseudorandom values into the gradient and Hessian,\n        // breaking the optimization.\n        if ((e_len < 1e-9) || (squared_dbl_A1 < 1e-16) || (squared_dbl_A2 < 1e-16)) {\n            e.setZero();\n            e[0] = 1.0;\n            theta = theta_bar;\n            squared_dbl_A1 = 1.0;\n            squared_dbl_A2 = 1.0;\n            N1.setZero();\n            N2.setZero();\n            e_01_dot_ehat = e_02_dot_ehat = e_11_dot_ehat = e_12_dot_ehat = 0.0;\n        }\n    }\n\n    // Gradient of theta with respect to the matrix [p0 | p1 | p2 | p3].\n    Eigen::Matrix<Real, 3, 4> gradTheta() const {\n        Eigen::Matrix<Real, 3, 4> result;\n        result.col(0) = (e_01_dot_ehat / squared_dbl_A1) * N1 + (e_02_dot_ehat / squared_dbl_A2) * N2;\n        result.col(1) = (e_11_dot_ehat / squared_dbl_A1) * N1 + (e_12_dot_ehat / squared_dbl_A2) * N2;\n        result.col(2) = (-e_len / squared_dbl_A1) * N1;\n        result.col(3) = (-e_len / squared_dbl_A2) * N2;\n        return result;\n    }\n\n    using HessType = Eigen::Matrix<Real, 12, 12>;\n    HessType hessTheta() const {\n        HessType result;\n        using ADType = Eigen::AutoDiffScalar<Eigen::Matrix<Real, 12, 1>>;\n        HingeEnergy<ADType> diff_he(*this);\n\n        Eigen::Matrix<ADType, 3, 4> ad_deformed_pts = deformed_pts;\n\n        for (size_t j = 0; j < 12; ++j) {\n            ad_deformed_pts.data()[j].derivatives().setZero();\n            ad_deformed_pts.data()[j].derivatives()[j] = 1.0;\n        }\n\n        diff_he.setDeformedConfiguration(ad_deformed_pts.col(0),\n                                         ad_deformed_pts.col(1),\n                                         ad_deformed_pts.col(2),\n                                         ad_deformed_pts.col(3));\n        auto diff_g = diff_he.gradTheta();\n\n        for (size_t i = 0; i < 12; ++i)\n            result.row(i) = diff_g.data()[i].derivatives().transpose();\n\n        return result;\n    }\n\n    Real energy() const {\n        // Note: this is 1/2 the energy in [Grinspun 2003]\n        return 0.5 * (theta - theta_bar) * (theta - theta_bar) * e_bar_len / h_bar;\n    }\n\n    Eigen::Matrix<Real, 3, 4> gradient() const {\n        return ((theta - theta_bar) * e_bar_len / h_bar) * gradTheta();\n    }\n\n    HessType hessian() const {\n        auto g = gradTheta();\n        auto gFlattened = Eigen::Map<Eigen::Matrix<Real, 12, 1>>(g.data());\n        return (e_bar_len / h_bar) * (\n                gFlattened * gFlattened.transpose() +\n                (theta - theta_bar) * hessTheta());\n    }\n};\n\n#endif /* end of include guard: BENDINGENERGY_HH */\n", "meta": {"hexsha": "321829f63358506dabf826d7d086da2e88983183", "size": 7862, "ext": "hh", "lang": "C++", "max_stars_repo_path": "BendingEnergy.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": "BendingEnergy.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": "BendingEnergy.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": 38.5392156863, "max_line_length": 146, "alphanum_fraction": 0.556982956, "num_tokens": 2271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.55363222070509}}
{"text": "#pragma once\n\n#include \"calotypes/KernelDensityEstimation.hpp\"\n#include \"calotypes/WeightedSamplers.hpp\"\n#include \"calotypes/DataSelector.hpp\"\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\nnamespace calotypes\n{\n\n// TODO Possibly expose ability to seed the engine directly, or give an engine reference?\n/*! \\brief Performs importance resampling to redraw samples from a set drawn according\n * to a proposal distribution to approximate a target distribution. */\ntemplate < class Data,\n\t\t   class Engine = boost::random::mt19937,\n\t\t   class Resampler = LowVarianceWeightedSampling<Engine> >\nvoid ImportanceResample( const std::vector<Data>& samples,\n\t\t\t\t\t\t const typename ProbabilityDensityFunction<Data>::Ptr& proposal,\n\t\t\t\t\t\t const typename ProbabilityDensityFunction<Data>::Ptr& target,\n\t\t\t\t\t\t unsigned int numSamples, std::vector<Data>& resampled )\n{\n\t// 1. Calculate resampling weights according to target(x)/proposal(x)\n\tstd::vector<double> weights( samples.size() );\n// \tstd::cout << \"weights: \" << std::endl;\n\tfor( unsigned int i = 0; i < samples.size(); i++ )\n\t{\n\t\tweights[i] = (*target)( samples[i] ) / (*proposal)( samples[i] );\n// \t\tstd::cout << \"\\t \" << samples[i].name << \" (\" << weights[i] << \")\" << std::endl;\n\t}\n\t\n\t// 2. Resample based on the weights\n\tEngine engine;\n\tboost::random::random_device rng;\n\tengine.seed( rng );\n\tstd::vector<unsigned int> resampleIndices;\n\tResampler::Sample( weights, numSamples, resampleIndices, engine );\n\t\n\t// 3. Return the samples\n\t// TODO Verify that numSamples = resampleIndices.size()?\n\tresampled.resize( numSamples );\n\tfor( unsigned int i = 0; i < numSamples; i++ )\n\t{\n\t\tresampled[i] = samples[ resampleIndices[i] ];\n\t}\n}\n\ntemplate <class Data>\nclass ImportanceDataSelector\n: public DataSelector<Data>\n{\npublic:\n\t\n\ttypedef std::shared_ptr<ImportanceDataSelector> Ptr;\n\ttypedef std::vector<Data> Dataset;\n\t\n\tImportanceDataSelector( const typename ProbabilityDensityFunction<Data>::Ptr& prop,\n\t\t\t\t\t\t\tconst typename ProbabilityDensityFunction<Data>::Ptr& tar )\n\t: proposal( prop ), target( tar ) {}\n\t\n\tvirtual void SelectData( const Dataset& data, unsigned int subsetSize, Dataset& subset )\n\t{\n\t\tImportanceResample( data, proposal, target, subsetSize, subset );\n\t}\n\t\nprivate:\n\t\n\ttypename ProbabilityDensityFunction<Data>::Ptr proposal;\n\ttypename ProbabilityDensityFunction<Data>::Ptr target;\n};\n\n} // end namespace calotypes\n", "meta": {"hexsha": "e24e786ca81a4073928ad96265d52623cca5df40", "size": 2415, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/calotypes/ImportanceResampling.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/ImportanceResampling.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/ImportanceResampling.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": 32.6351351351, "max_line_length": 89, "alphanum_fraction": 0.7233954451, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.553632207714934}}
{"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/camera/projection_matrix_utils.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <glog/logging.h>\n\n#include \"theia/math/matrix/rq_decomposition.h\"\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\nvoid IntrinsicsToCalibrationMatrix(const double focal_length,\n                                   const double skew,\n                                   const double aspect_ratio,\n                                   const double principal_point_x,\n                                   const double principal_point_y,\n                                   Matrix3d* calibration_matrix) {\n  *calibration_matrix <<\n      focal_length, skew, principal_point_x,\n      0, focal_length * aspect_ratio, principal_point_y,\n      0, 0, 1.0;\n}\n\nvoid CalibrationMatrixToIntrinsics(const Matrix3d& calibration_matrix,\n                                   double* focal_length,\n                                   double* skew,\n                                   double* aspect_ratio,\n                                   double* principal_point_x,\n                                   double* principal_point_y) {\n  CHECK_NE(calibration_matrix(2, 2), 0);\n  *focal_length = calibration_matrix(0, 0) / calibration_matrix(2, 2);\n  *skew = calibration_matrix(0, 1) / calibration_matrix(2, 2);\n  *aspect_ratio = calibration_matrix(1, 1) / calibration_matrix(0, 0);\n  *principal_point_x = calibration_matrix(0, 2) / calibration_matrix(2, 2);\n  *principal_point_y = calibration_matrix(1, 2) / calibration_matrix(2, 2);\n}\n\nbool DecomposeProjectionMatrix(const Matrix3x4d pmatrix,\n                               Matrix3d* calibration_matrix,\n                               Vector3d* rotation,\n                               Vector3d* position) {\n  RQDecomposition<Matrix3d> rq(pmatrix.block<3, 3>(0, 0));\n\n  Matrix3d rotation_matrix = ProjectToRotationMatrix(rq.matrixQ());\n\n  const double k_det = rq.matrixR().determinant();\n  if (k_det == 0) {\n    return false;\n  }\n\n  Matrix3d& kmatrix = *calibration_matrix;\n  if (k_det > 0) {\n    kmatrix = rq.matrixR();\n  } else {\n    kmatrix = -rq.matrixR();\n  }\n\n  // Fix the matrix such that all internal parameters are greater than 0.\n  for (int i = 0; i < 3; ++i) {\n    if (kmatrix(i, i) < 0) {\n      kmatrix.col(i) *= -1.0;\n      rotation_matrix.row(i) *= -1.0;\n    }\n  }\n\n  // Solve for t.\n  const Vector3d t =\n      kmatrix.triangularView<Eigen::Upper>().solve(pmatrix.col(3));\n\n  // c = - R' * t, and flip the sign according to k_det;\n  if (k_det > 0) {\n    *position = - rotation_matrix.transpose() * t;\n  } else {\n    *position = rotation_matrix.transpose() * t;\n  }\n\n  const Eigen::AngleAxisd rotation_aa(rotation_matrix);\n  *rotation = rotation_aa.angle() * rotation_aa.axis();\n\n  return true;\n}\n\nbool ComposeProjectionMatrix(const Matrix3d& calibration_matrix,\n                             const Vector3d& rotation,\n                             const Vector3d& position,\n                             Matrix3x4d* pmatrix) {\n  const double rotation_angle = rotation.norm();\n  if (rotation_angle == 0) {\n    pmatrix->block<3, 3>(0, 0) = Matrix3d::Identity();\n  } else {\n    pmatrix->block<3, 3>(0, 0) = Eigen::AngleAxisd(\n        rotation_angle, rotation / rotation_angle).toRotationMatrix();\n  }\n\n  pmatrix->col(3) = - (pmatrix->block<3, 3>(0, 0) *  position);\n  *pmatrix = calibration_matrix * (*pmatrix);\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "d66f220fa687f919318b707048ddbaed603c0844", "size": 5258, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/camera/projection_matrix_utils.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/camera/projection_matrix_utils.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/camera/projection_matrix_utils.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": 37.8273381295, "max_line_length": 78, "alphanum_fraction": 0.6475846329, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5536179852817847}}
{"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_2_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOG_2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Generates constant Log_2 : \\f$\\log(2)\\f$.\n\n    @par Semantic:\n\n    @code\n    T r = Log_2<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(0.6931471805599453094172321214581765680755001343602553);\n    @endcode\n\n\n**/\n  template<typename T> T Log_2();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Generates constant Log_2. (\\f$\\log(2)\\f$)\n\n      Generate the  constant log_2.\n\n      @return The Log_2 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::log_2_> log_2 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/log_2.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": "7a86f791d45bf5a68c5dd816a80ab233bf33a682", "size": 1346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/log_2.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_2.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_2.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.0655737705, "max_line_length": 100, "alphanum_fraction": 0.588410104, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.5536179779330804}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n//\n// *** System\n//\n#include <iostream>\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n\n//\n// *** ViennaCL\n//\n\n// #define VIENNACL_DEBUG_ALL\n// #define VIENNACL_DEBUG_BUILD\n// #define VIENNACL_HAVE_UBLAS 1\n// #define VIENNACL_DEBUG_CUSTOM_OPERATION\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/inner_prod.hpp\"\n#include \"viennacl/linalg/norm_1.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/norm_inf.hpp\"\n#include \"viennacl/generator/custom_operation.hpp\"\n\nusing namespace boost::numeric;\n\ntemplate <class TYPE>\nbool readVectorFromFile ( const std::string & filename, boost::numeric::ublas::vector<TYPE> & vec ) {\n    std::ifstream file ( filename.c_str() );\n\n    if ( !file ) return false;\n\n    unsigned int size;\n    file >> size;\n\n    if ( size > 20000 )  //keep execution times short\n        size = 20000;\n    vec.resize ( size );\n    for ( unsigned int i = 0; i < size; ++i ) {\n        TYPE element;\n        file >> element;\n        vec[i] = element;\n    }\n\n    return true;\n}\n\ntemplate <typename ScalarType>\nScalarType diff ( ScalarType & s1, viennacl::scalar<ScalarType> & s2 ) \n{\n    viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n    if ( s1 != s2 )\n        return ( s1 - s2 ) / std::max ( fabs ( s1 ), fabs ( s2 ) );\n    return 0;\n}\n\ntemplate< typename NumericT,unsigned int Alignment, typename Epsilon >\nint test ( Epsilon const& epsilon, std::string vecfile ) {\n    int retval = EXIT_SUCCESS;\n\n    viennacl::scalar<NumericT>  vcl_res ( 0 );\n    ublas::vector<NumericT> vec;\n    ublas::vector<NumericT> vec2;\n\n    NumericT res;\n\n    viennacl::generator::gpu_symbolic_scalar<0,NumericT> symres;\n    viennacl::generator::symbolic_vector<1,NumericT,Alignment> symv;\n    viennacl::generator::symbolic_vector<2,NumericT,Alignment> symv2;\n    viennacl::generator::cpu_symbolic_scalar<3,NumericT> symscal;\n    viennacl::generator::cpu_symbolic_scalar<2,NumericT> symscal2;\n\n\n    if ( !readVectorFromFile<NumericT> ( vecfile, vec ) ) {\n        std::cout << \"Error reading vec file\" << std::endl;\n        retval = EXIT_FAILURE;\n    }\n// \n    std::cout << \"Running tests for vector of size \" << vec.size() << std::endl;\n\tstd::cout << \"----- Alignment \" << Alignment << \" -----\" << std::endl;\n// \n    viennacl::vector<NumericT,Alignment> vcl_vec ( vec.size() );\n    viennacl::vector<NumericT,Alignment> vcl_vec2 ( vec.size() );\n// \n    vec2 = vec;\n    viennacl::copy ( vec.begin(), vec.end(), vcl_vec.begin() );\n    viennacl::copy ( vec2.begin(), vec2.end(), vcl_vec2.begin() );\n\n//     --------------------------------------------------------------------------\n\n    std::cout << \"testing inner product...\" << std::endl;\n\t\n    res = ublas::inner_prod ( vec, vec2 );\n    viennacl::ocl::enqueue ( viennacl::generator::custom_operation(symres = inner_prod ( symv, symv2 ), \"inner_prod\") ( vcl_res, vcl_vec, vcl_vec2 ) );\n    //std::cout << viennacl::generator::custom_operation(symres = inner_prod ( symv, symv2 ), \"inner_prod\") .kernels_source_code() << std::endl;\n    if ( fabs ( diff ( res, vcl_res ) ) > epsilon ) {\n        std::cout << \"# Error at operation: inner product\" << std::endl;\n        std::cout << \"  Diff \" << fabs ( diff ( res, vcl_res ) ) << std::endl;\n        retval = EXIT_FAILURE;\n    }\n\n    std::cout << \"testing inner product division...\" << std::endl;\n    res = ublas::inner_prod ( vec, vec2 ) /ublas::inner_prod ( vec, vec );\n    viennacl::ocl::enqueue ( viennacl::generator::custom_operation ( symres = inner_prod ( symv, symv2 ) /inner_prod ( symv,symv ), \"inner_prod_division\" ) ( vcl_res, vcl_vec, vcl_vec2 ) );\n    if ( fabs ( diff ( res, vcl_res ) ) > epsilon ) {\n        std::cout << \"# Error at operation: inner_prod_division\" << std::endl;\n        std::cout << \"  diff: \" << fabs ( diff ( res, vcl_res ) ) << std::endl;\n        retval = EXIT_FAILURE;\n    }\n\n    std::cout << \"testing scalar / inner product...\" << std::endl;\n    res = 4/ublas::inner_prod ( vec, vec );\n    viennacl::ocl::enqueue ( viennacl::generator::custom_operation ( symres = symscal2/inner_prod ( symv,symv ),\"scalar_division\" ) ( vcl_res, vcl_vec, 4.0f ) );\n    //std::cout << viennacl::generator::custom_operation ( symres = symscal2/inner_prod ( symv,symv ), \"scalar_division\" ).kernels_source_code() << std::endl;\n    if ( fabs ( diff ( res, vcl_res ) ) > epsilon ) {\n        std::cout << \"# Error at operation: scalar over inner product\" << std::endl;\n        std::cout << \"  diff: \" << fabs ( diff ( res, vcl_res ) ) << std::endl;\n        retval = EXIT_FAILURE;\n    }\n\n    std::cout << \"testing inner_prod - ( scal - inner_prod ) \" << std::endl;\n    res = ublas::inner_prod ( vec, vec2 ) - ( 5.0f - inner_prod ( vec,vec2 ) );\n    viennacl::ocl::enqueue ( viennacl::generator::custom_operation ( symres = inner_prod ( symv, symv2 ) - ( symscal - inner_prod ( symv,symv2 ) ), \"inner_prod_minus_scal_minus_inprod\" ) ( vcl_res, vcl_vec, vcl_vec2, 5.0f ) );\n    if ( fabs ( diff ( res, vcl_res ) ) > epsilon ) {\n        std::cout << \"# Error at operation: inner_prod minus ( scal minus inner_prod ) \" << std::endl;\n        std::cout << \"  diff: \" << fabs ( diff ( res, vcl_res ) ) << std::endl;\n        retval = EXIT_FAILURE;\n    }\n\n    return retval;\n}\n\n\nint main() {\n    std::cout << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"## Test :: Inner Product\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n\n    int retval = EXIT_SUCCESS;\n\n    std::string vecfile ( \"../examples/testdata/rhs65025.txt\" );\n\n    std::cout << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n    {\n        typedef float NumericT;\n        NumericT epsilon = 1.0E-4;\n        std::cout << \"# Testing setup:\" << std::endl;\n        std::cout << \"  eps:     \" << epsilon << std::endl;\n        std::cout << \"  numeric: float\" << std::endl;\n        retval = test<NumericT,1> ( epsilon, vecfile );\n//  \t\tretval = test<NumericT,4> ( epsilon, vecfile, resultfile );\n//        retval = test<NumericT,16> ( epsilon, vecfile, resultfile );\n        if ( retval == EXIT_SUCCESS )\n            std::cout << \"# Test passed\" << std::endl;\n        else\n            return retval;\n    }\n}\n", "meta": {"hexsha": "c9e063ac6e40de7c111ca90e1793bd5ec6e2faed", "size": 7345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/generator_inner_product.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "tests/src/generator_inner_product.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/generator_inner_product.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": 39.7027027027, "max_line_length": 226, "alphanum_fraction": 0.5628318584, "num_tokens": 1990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.5536179684372595}}
{"text": "\r\n/*\r\n\t\r\n\tpclub03.cpp\r\n\t\r\n\tpclub01.cppから派生。01は以下のもの。\r\n\t@Programming Club, Imaplus, Nov 16, 2019\r\n\tInstant Test for kdatasettest00.cpp\r\n\t\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2019-2020 Koji Yamamoto\r\n\t\r\n\tTODO:　\r\n\t度数分布表をつくる。kstatを見て。\r\n\t　別に、連続変数用の機能をつける。\r\n\t　　start/end, width, bin を指定する方式。\r\n\t　　自動で、スタージェスの公式を使う方式。\r\n\t　　階級の端点の表を与える方式。\r\n\tヒストグラムを描く。\r\n\tSVGにする。\r\n\t\r\n*/\r\n\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#include <k09/kdataset01.cpp>\r\n#include <k09/kstat02.cpp>\r\n#include <k09/koutputfile00.cpp>\r\n#include <iostream> \r\n#include <iomanip>\r\n#include <algorithm>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n\r\n/* ********** Namespace Declarations/Directives ********** */\r\n\r\nusing namespace std;\r\n\r\n\r\n/* ********** Class Declarations ********** */\r\n\r\n\r\n/* ********** Enum Definitions ********** */\r\n\r\n\r\n/* ********** Function Declarations ********** */\r\n\r\nint main( int, char *[]);\r\n\r\nvoid drawHistogramToSvg(\r\n\tconst std::string &,\r\n\tconst std::vector <double> &, const std::vector <double> &,\r\n\tconst std::vector <int> &,\r\n\tbool = false\r\n);\r\n\r\nstd::vector <double>\r\ngetGridPoints( double, double, int = 4, bool = true, bool = true);\r\n\r\n\r\n/* ********** Class Definitions ********** */\r\n\r\n\r\n/* ********** Global Variables ********** */\r\n\r\n\r\n/* ********** Definitions of Static Member Variables ********** */\r\n\r\n\r\n/* ********** Function Definitions ********** */\r\n\r\nint main( int, char *[])\r\n{\r\n\t\r\n\tvector <double> dvec;\r\n\tvector <double> dvecclean;\r\n\r\n\t{\r\n\t\tDataset ds;\r\n\t\tbool b;\r\n\r\n\t\tcout << \"Reading data...\";\r\n\t\tb = ds.readCsvFile( \"jhpsmerged_191029_v403.csv\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\r\n\t\tcout << \"Fixing variable types...\";\r\n\t\tint nnum, nmis;\r\n\t\tds.fixVariableType( nnum, nmis);\t\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t\tcout << \"Getting numeric vector before specifying missing...\";\r\n\t\tb = ds.getNumericVectorWithoutMissing( dvec, \"v403\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t\tcout << \"Specifying missing cases...\";\r\n\t\tds.specifyValid( \r\n\t\t\t\"v403\",\r\n\t\t\t[]( double v)->bool{ return ( v < 99999.0);}\r\n\t\t);\r\n\t\tcout << \"Done.\" << endl;\r\n\r\n\t\tcout << \"Getting numeric vector excl. missing...\";\r\n\t\tb = ds.getNumericVectorWithoutMissing( dvecclean, \"v403\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t}\r\n\r\n\tcout << endl;\r\n\tcout << \"***************************************************\" << endl;\r\n\tcout << \"JHPS 2009 Household Income incl. Tax\" << endl;\r\n\tcout << \"Calculated by mean() and median()\" << endl;\r\n\tcout << \"Mean:   \" << setprecision( 15) << mean( dvecclean)   << \" (Ten Thousand Yen)\" << endl;\r\n\tcout << \"Median: \" << median( dvecclean) << \" (Ten Thousand Yen)\" << endl;\r\n\tcout << \"***************************************************\" << endl;\r\n\tcout << \"FYI: Mean from \\\"dirty\\\" data: \" << setprecision( 15) << mean( dvec) << endl;\r\n\r\n\r\n\t// 度数分布表\r\n\r\n\tcout << endl;\r\n\tcout << \"Number of unique values: \" << countUniqueValues( dvecclean) << endl;\r\n\tcout << \"FYI Number of unique values in \\\"dirty\\\" vector: \" << countUniqueValues( dvec) << endl << endl;\r\n\r\n\r\n\tRecodeTable <double, int> rt;\r\n\trt.setAutoTableFromContVar( dvecclean); \r\n\r\n\tcout << \"RecodeTable:\" << endl;\r\n\trt.print( cout, \",\"); \r\n\tcout << endl;\r\n\r\n\tFreqType <int, int> ft;\r\n\tft.setFreqFromRecodeTable( dvecclean, rt);\r\n\r\n\tft.printPadding( cout);\r\n\r\n\r\n\t// ヒストグラムをつくりたい。\r\n\r\n\tvector <int> codes;\r\n\tvector <int> counts;\r\n\tvector <double> leftvec;\r\n\tvector <double> rightvec;\r\n\tft.getVectors( codes, counts);\r\n\tft.getRangeVectors( leftvec, rightvec);\r\n\r\n\tdrawHistogramToSvg( \"pclub03out01.svg\", leftvec, rightvec, counts);\r\n\tdrawHistogramToSvg( \"pclub03out02.svg\", leftvec, rightvec, counts, true); // アニメバージョン\r\n\r\n\treturn 0;\r\n\r\n\r\n\r\n\t// 今のRecodeTableには、左端・右端がない（無限大）という指定ができない。\r\n\r\n\t// FreqTypeにはすごく小さい機能だけを持たせることにして、\r\n\t// 別にFreqTableTypeか何かをつくって、そこに、RecodeTableを持たせたり、\r\n\t// それをもとにしたFreqを作らせたりしてもよいかも。\r\n\r\n\t/*\r\n\t度数分布表をつくる。kstatを見て。\r\n\t　別に、連続変数用の機能をつける。\r\n\t　　start/end, width, bin を指定する方式。\r\n\t　　自動で、スタージェスの公式を使う方式？\r\n\t　　※Stataでは、min{ sqrt(N), 10*ln(N)/ln(10)}らしいので、それでいく。\r\n\t　　階級の端点の表を与える方式。\r\n\t*/\r\n\r\n\r\n/*\r\n\t// ちょうどいい間隔と基準点の実験。\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -12.34, 567.8);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\t\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -12.34, 567.8, 4, false, false);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\t\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -1234.5, 567.8);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -1234.5, 567.8, 5);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( 123.5, 5678.9);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -80001.0, -299.9);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n\r\n\t{\r\n\t\tvector <double> gridpoints = getGridPoints( -80001.0, -299.9, 5);\r\n\t\tfor ( auto d : gridpoints){\r\n\t\t\tcout << d << endl;\r\n\t\t}\r\n\t\tcout << endl;\r\n\t}\r\n*/\r\n}\r\n\r\nvoid drawHistogramToSvg(\r\n\tconst std::string &fn,\r\n\tconst std::vector <double> &leftvec, const std::vector <double> &rightvec,\r\n\tconst std::vector <int> &counts,\r\n\tbool animated /*= false*/\r\n)\r\n{\r\n\r\n\tusing namespace std;\r\n\r\n\t// SVGのviewBoxについて：アスペクト比が違っているとわかりにくい。\r\n\t// （強制的に余白がつくられたりするか、強制的に拡大縮小して円が歪んだりする）ので、\r\n\t// svgタグのサイズとviewBoxのサイズを合わせたい。\r\n\r\n\tstruct Cambus;\r\n\tstruct Point;\r\n\t\r\n\tstruct Point {\r\n\r\n\t\tdouble x, y;\r\n\r\n\t\tPoint( void)\r\n\t\t : x( std::numeric_limits<double>::quiet_NaN()),\r\n\t\t   y( std::numeric_limits<double>::quiet_NaN())\r\n\t\t{}\r\n\t\t\r\n\t\tPoint( double x0, double y0) : x( x0), y( y0)\r\n\t\t{}\r\n\r\n\t};\r\n\r\n\tstruct Cambus {\r\n\r\n\t\t// 実際の座標系では、y座標は大きいほど「下」の位置を示す。\r\n\t\t// 論理座標系では、y座標は大きいほど「上」の位置を示す。\r\n\r\n\t\tdouble actuXMin, actuYMin, actuXMax, actuYMax; // 実際の座標系での、枠の範囲\r\n\t\tdouble actuWidth, actuHeight; // 同上\r\n\r\n\t\tdouble theoXMin, theoYMin, theoXMax, theoYMax; // 論理座標系での、枠の範囲\r\n\t\tdouble theoWidth, theoHeight; // 同上\r\n\r\n\t\tvoid setTheoretical( double xmin0, double ymin0, double xmax0, double ymax0)\r\n\t\t{\r\n\t\t\ttheoXMin = xmin0; theoYMin = ymin0; theoXMax = xmax0; theoYMax = ymax0; \r\n\t\t\ttheoWidth = xmax0 - xmin0; theoHeight = ymax0 - ymin0; \r\n\t\t}\r\n\r\n\t\tvoid setActual( double xmin0, double ymin0, double xmax0, double ymax0)\r\n\t\t{\r\n\t\t\tactuXMin = xmin0; actuYMin = ymin0; actuXMax = xmax0; actuYMax = ymax0; \r\n\t\t\tactuWidth = xmax0 - xmin0; actuHeight = ymax0 - ymin0; \r\n\t\t}\r\n\r\n\t\t// 論理座標系表現から実際の座標系表現を作成。\r\n\t\tPoint getActualFromTheoretical( const Point &poi0)\r\n\t\t{\r\n\t\t\t\r\n\t\t\tdouble x0 = poi0.x;\r\n\t\t\tdouble y0 = poi0.y;\r\n\t\t\tPoint ret;\r\n\t\t\tret.x = ( x0 - theoXMin) / theoWidth  * actuWidth  + actuXMin; \r\n\t\t\tret.y = ( theoYMax - y0) / theoHeight * actuHeight + actuYMin; \r\n\t\t\treturn ret;\r\n\r\n\t\t}\r\n\r\n\t\t// x座標のみを算出→論理座標系表現から実際の座標系表現を作成。\r\n\t\tdouble getXActualFromTheoretical( double x0)\r\n\t\t{\r\n\r\n\t\t\tdouble retx = ( x0 - theoXMin) / theoWidth  * actuWidth  + actuXMin; \r\n\t\t\treturn retx;\r\n\r\n\t\t}\r\n\r\n\t\t// y座標のみを算出→論理座標系表現から実際の座標系表現を作成。\r\n\t\tdouble getYActualFromTheoretical( double y0)\r\n\t\t{\r\n\t\t\t\r\n\t\t\tdouble rety = ( theoYMax - y0) / theoHeight * actuHeight + actuYMin; \r\n\t\t\treturn rety;\r\n\r\n\t\t}\r\n\r\n\t\t// 実際の座標系での中点のxを返す。\r\n\t\tdouble getActualMidX( void)\r\n\t\t{\r\n\r\n\t\t\treturn ( actuXMin + actuWidth / 2);\r\n\r\n\t\t}\r\n\t\r\n\t\t// 実際の座標系での中点のyを返す。\r\n\t\tdouble getActualMidY( void)\r\n\t\t{\r\n\r\n\t\t\treturn ( actuYMin + actuHeight / 2);\r\n\r\n\t\t}\r\n\t\r\n\t};\r\n\r\n\t\r\n\tvector <string> svglines;\r\n\tCambus cam;\r\n\r\n\r\n\t// SVG領域の大きさと、座標系のある領域の大きさを指定することで、それらしく計算してほしい。\r\n\r\n\t// ちょうどいい間隔のグリッド線の点と、範囲を得る。\r\n\r\n\t// x軸\r\n\tdouble xminval = leftvec.front();\r\n\tdouble xmaxval = rightvec.back();\r\n\tvector <double> xgridpoints = getGridPoints( xminval, xmaxval);\r\n\tfor ( auto d : xgridpoints){\r\n\t\tcout << d << endl;\r\n\t}\r\n\tcout << endl;\r\n\t// y軸\r\n\tdouble ymaxval = *( max_element( counts.begin(), counts.end()));\r\n\tvector <double> ygridpoints = getGridPoints( 0, ymaxval);\r\n\tfor ( auto d : ygridpoints){\r\n\t\tcout << d << endl;\r\n\t}\r\n\tcout << endl;\r\n\t\r\n\t// 描画範囲は、Gridpointsのさらに5%外側にする。\r\n\tdouble theoWidthTemp = xgridpoints.back() - xgridpoints.front();\r\n\tdouble theoXMin = xgridpoints.front() - 0.05 * theoWidthTemp;\r\n\tdouble theoXMax = xgridpoints.back() + 0.05 * theoWidthTemp;\r\n\t\r\n\tdouble theoHeightTemp = ygridpoints.back() - ygridpoints.front();\r\n\tdouble theoYMin = ygridpoints.front() - 0.05 * theoHeightTemp;\r\n\tdouble theoYMax = ygridpoints.back() + 0.05 * theoHeightTemp;\r\n\t\r\n\r\n\r\n\r\n\r\n\t// SVGファイル化の開始\r\n\r\n\tcam.setActual( 50, 50, 450, 450);\r\n\tcam.setTheoretical( theoXMin, theoYMin, theoXMax, theoYMax);\r\n\r\n\tsvglines.push_back( R\"(<?xml version=\"1.0\" encoding=\"UTF-8\" ?>)\"); // This should be exactly in the first line.\r\n\tsvglines.push_back( R\"(<svg width=\"500px\" height=\"500px\" viewBox=\"0 0 500 500\" xmlns=\"http://www.w3.org/2000/svg\">)\");\r\n\tsvglines.push_back( R\"(<rect x=\"0\" y=\"0\" width=\"500\" height=\"500\" fill=\"whitesmoke\" stroke-width=\"0\" />)\");\r\n\r\n\r\n\t// 背景の描画開始\r\n\r\n\t// 背景色だけ塗る。\r\n\tsvglines.push_back( R\"(  <rect x=\"50\" y=\"50\" width=\"400\" height=\"400\" fill=\"gainsboro\" stroke-width=\"0\" />)\");\r\n\r\n\t// x軸の目盛を示すグリッド線\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke=\")\" << \"silver\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke-width=\")\" << 1 << R\"(\")\"\r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : xgridpoints){\r\n\r\n\t\tPoint theoP1( v, theoYMax); // top\r\n\t\tPoint theoP2( v, theoYMin); // bottom \r\n\t\tPoint actuP1 = cam.getActualFromTheoretical( theoP1);\r\n\t\tPoint actuP2 = cam.getActualFromTheoretical( theoP2);\r\n\r\n\t\tstringstream ss;\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<line)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x1=\")\" << actuP1.x << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y1=\")\" << actuP1.y << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x2=\")\" << actuP2.x << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y2=\")\" << actuP2.y << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(/>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\r\n\t// y軸の目盛を示すグリッド線\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke=\")\" << \"silver\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke-width=\")\" << 1 << R\"(\")\"\r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : ygridpoints){\r\n\r\n\t\tPoint theoP1( theoXMin, v); // left\r\n\t\tPoint theoP2( theoXMax, v); // right \r\n\t\tPoint actuP1 = cam.getActualFromTheoretical( theoP1);\r\n\t\tPoint actuP2 = cam.getActualFromTheoretical( theoP2);\r\n\r\n\t\tstringstream ss;\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<line)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x1=\")\" << actuP1.x << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y1=\")\" << actuP1.y << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x2=\")\" << actuP2.x << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y2=\")\" << actuP2.y << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(/>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// 背景の描画終了\r\n\r\n\t// メインの情報の描画開始\r\n\r\n\t// 度数を示すバー。\r\n\t// 注：これを目盛グリッド線よりもあとに描くべし。グリッド線を「上書き」してほしいから。\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke=\")\" << \"Gray\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(fill=\")\" << \"Gray\" << R\"(\")\" \r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( int i = 0; i < counts.size(); i++){\r\n\r\n\t\tPoint theoP1( leftvec[ i], counts[ i]); // left-top\r\n\t\tPoint theoP2( rightvec[ i], 0); // right-bottom \r\n\t\tPoint actuP1 = cam.getActualFromTheoretical( theoP1);\r\n\t\tPoint actuP2 = cam.getActualFromTheoretical( theoP2);\r\n\r\n\r\n\t\tif ( animated == true){\r\n\r\n\t\t\t// 以下はアニメ用\r\n\t\t\t// SVGアニメをパワポに貼っても動かないらしい。\r\n\t\t\t\r\n\t\t\tstringstream ss;\r\n\t\t\t\r\n\t\t\tss << \"    \"\r\n\t\t\t<< R\"(<rect)\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(x=\")\" << actuP1.x << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(y=\")\" << actuP1.y << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(width=\")\" << ( actuP2.x - actuP1.x) << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(height=\")\" << ( actuP2.y - actuP1.y) << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(>)\";\r\n\t\t\tsvglines.push_back( ss.str());\r\n\t\t\t\r\n\t\t\tss.str( \"\");\r\n\t\t\tss << R\"(      <animate attributeName=\"height\" begin=\"0s\" dur=\"1s\" from=\"0\" to=\")\" << ( actuP2.y - actuP1.y) << R\"(\" repeatCount=\"1\"/>)\";\r\n\t\t\tsvglines.push_back( ss.str());\r\n\r\n\t\t\tss.str( \"\");\r\n\t\t\tss << R\"(      <animate attributeName=\"y\" begin=\"0s\" dur=\"1s\" from=\")\" << actuP2.y << R\"(\" to=\")\" << actuP1.y << R\"(\" repeatCount=\"1\"/>)\";\r\n\t\t\tsvglines.push_back( ss.str());\r\n\t\t\t\r\n\t\t\tsvglines.push_back( R\"(</rect>)\");\r\n\r\n\t\t} else {\r\n\r\n\t\t\tstringstream ss;\r\n\t\t\tss << \"    \"\r\n\t\t\t<< R\"(<rect)\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(x=\")\" << actuP1.x << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(y=\")\" << actuP1.y << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(width=\")\" << ( actuP2.x - actuP1.x) << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(height=\")\" << ( actuP2.y - actuP1.y) << R\"(\")\"\r\n\t\t\t<< \" \"\r\n\t\t\t<< R\"(/>)\";\r\n\t\t\tsvglines.push_back( ss.str());\r\n\r\n\t\t}\r\n\t\t\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// メインの情報の描画終了\r\n\r\n\r\n\r\n\t// 周辺情報記載の開始\r\n\r\n\t// TODO: フォントサイズを自動調整→優先順位が低い。フォントサイズ固定でもいい。\r\n\r\n\t// x軸の目盛のヒゲ\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke=\")\" << \"Black\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke-width=\")\" << 1 << R\"(\")\"\r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : xgridpoints){\r\n\r\n\t\tdouble actuX = cam.getXActualFromTheoretical( v);\r\n\r\n\t\tdouble tickheight = 5; // とりあえずの値。\r\n\t\t\r\n\t\tstringstream ss;\r\n\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<line)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x1=\")\" << actuX << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y1=\")\" << cam.actuYMax << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x2=\")\" << actuX << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y2=\")\" << ( cam.actuYMax + tickheight) << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(/>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\r\n\t// TODO: 軸の単位の記載→優先順位は低い。\r\n\r\n\t// textタグで、IEやWordはdominant-baselineが効かないらしい。\r\n\t// （指定してもdominant-baseline=\"alphabetic\"扱いになる。）\r\n\r\n\t// x軸の目盛のラベル\r\n\tdouble xlabelfontsize = 14; // とりあえずの値。\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(font-family=\")\" << \"Arial,san-serif\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(font-size=\")\" << xlabelfontsize << R\"(\")\" \r\n\t\t   << \" \"\r\n\t\t   << R\"(text-anchor=\"middle\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(dominant-baseline=\"alphabetic\")\" // こうしないとIEやWordで崩れる。。\r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : xgridpoints){\r\n\r\n\t\tPoint theoP( v, 0); // 本当はy軸の座標は要らないのだが。。\r\n\r\n\t\tPoint actuP = cam.getActualFromTheoretical( theoP);\r\n\r\n\t\tdouble ticklabelmargin = 10; // とりあえずの値。\r\n\t\t\r\n\t\tstringstream ss;\r\n\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<text)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x=\")\" << actuP.x << R\"(\")\" // 左右方向に中央揃えをする前提で座標を指定。\r\n\t\t<< \" \"\r\n\t\t// 描画領域の下端からmarginだけ離す。\r\n\t\t// alphabeticの基線は、このフォントの場合、本当のフォント下端より20%上なので、その分をずらしている。\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMax + ticklabelmargin + xlabelfontsize * 0.8)) << R\"(\")\" \r\n\t\t<< \">\"\r\n\t\t<< v // 桁数はどうなるのか。。 \r\n\t\t<< R\"(</text>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// y軸の目盛のヒゲ\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke=\")\" << \"Black\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(stroke-width=\")\" << 1 << R\"(\")\"\r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : ygridpoints){\r\n\r\n\t\tdouble actuY = cam.getYActualFromTheoretical( v);\r\n\r\n/*\t\tPoint theoP( 0, v); // 本当はy軸の座標は要らないのだが。。\r\n\r\n\t\tPoint actuP = cam.getActualFromTheoretical( theoP);\r\n*/\r\n\t\tdouble tickwidth = 5; // とりあえずの値。\r\n\t\t\r\n\t\tstringstream ss;\r\n\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<line)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x1=\")\" << cam.actuXMin << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y1=\")\" << actuY /*actuP.y*/ << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x2=\")\" << ( cam.actuXMin - tickwidth) << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(y2=\")\" << actuY /*actuP.y*/ << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(/>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\t// y軸の目盛ラベル\r\n\t/*\r\n\t文字列を回転させる方法を探った→svgtest04.svgとsvgtest05.svg\r\n\t　svgtest04.svgで2つの方法を試したが、もっとシンプルにしたかった。\r\n\t　svgtest05.svgで、transform属性を使えばよいことがわかった。\r\n\t*/\r\n\t// y軸の目盛のラベル\r\n\tdouble ylabelfontsize = 14; // とりあえずの値。\r\n\t// <g>で属性一括指定：開始\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tss << \"  \"\r\n\t\t   << R\"(<g)\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(font-family=\")\" << \"Arial,san-serif\" << R\"(\")\"\r\n\t\t   << \" \"\r\n\t\t   << R\"(font-size=\")\" << ylabelfontsize << R\"(\")\" \r\n\t\t   << \" \"\r\n\t\t   << R\"(text-anchor=\"middle\")\" // 文字列の左右方向の中心で位置決めする。\r\n\t\t   << \" \"\r\n\t\t   << R\"(dominant-baseline=\"alphabetic\")\" \r\n\t\t   << R\"(>)\";\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\tfor ( auto v : ygridpoints){\r\n\r\n\t\tdouble actuY = cam.getYActualFromTheoretical( v);\r\n\r\n\t\tdouble ticklabelmargin = 10; // とりあえずの値。\r\n\r\n\t\t// alphabetic基線に合わせるために20%ずらしている。\r\n\t\tdouble xplace = std::round( cam.actuXMin - ticklabelmargin - ylabelfontsize * 0.2);\r\n\t\t\r\n\t\tstringstream ss;\r\n\r\n\t\tss << \"    \"\r\n\t\t<< R\"(<text)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x=\")\" << xplace << R\"(\")\" // 描画領域の左端からmarginだけ離す。\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << actuY << R\"(\")\" // 上下方向に中央揃えをする前提で座標を指定。\r\n\t\t<< \" \"\r\n\t\t<< R\"(transform=\"rotate(270 )\" << xplace << \" \" << actuY << \")\" << R\"(\")\" // 回転の中心が各点で異なるので、一括指定できない。\r\n\t\t<< \">\"\r\n\t\t<< v // 桁数はどうなるのか。。 \r\n\t\t<< R\"(</text>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\t// <g>で属性一括指定：終了\r\n\t{\r\n\t\tsvglines.push_back( \"  </g>\");\r\n\t}\r\n\r\n\r\n\r\n\t// Title \r\n\r\n\t// グラフタイトル\r\n\tstring title = \"Frequency from pclub03.cpp\"s;\r\n\t{\r\n\t\tstringstream ss;\r\n\t\tdouble fontsize = std::floor( cam.actuWidth * 0.7 / title.size() * 2.0); // 描画領域の幅のうち、7割を占めるぐらいのサイズ\r\n\t\tif ( fontsize >= cam.actuYMin * 0.7){ // 余白の高さの70%より大きいのはダメ\r\n\t\t\tfontsize = cam.actuYMin * 0.7;\r\n\t\t}\r\n\t\tss << \"  \"\r\n\t\t<< R\"(<text)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x=\")\" << ( std::round( cam.getActualMidX())) << R\"(\")\" // 中央揃えをするので。\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMin * 0.9)) << R\"(\")\" // 余白のうち10%浮かせる。\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-family=\")\" << \"Arial,san-serif\" << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-size=\")\" << fontsize << R\"(\")\" \r\n\t\t<< \" \"\r\n\t\t<< R\"(text-anchor=\"middle\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(dominant-baseline=\"text-after-edge\")\"\r\n\t\t<< \">\"\r\n\t\t<< title \r\n\t\t<< R\"(</text>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\t}\r\n\r\n\r\n\t// x軸タイトルを書く。\r\n\tstring xaxislabel = \"Household Income\";\r\n\t{\r\n\r\n\t\tdouble fontsize = 20; // とりあえずの値。\r\n\t\tdouble xaxislabelmargin = 30; // とりあえずの値。\r\n\t\t\r\n\t\tstringstream ss;\r\n\r\n\t\tss << \"  \"\r\n\t\t<< R\"(<text)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x=\")\" << ( std::round( cam.getActualMidX())) << R\"(\")\" // 中央揃えをするので。\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << ( std::round( cam.actuYMax + xaxislabelmargin + fontsize)) << R\"(\")\" // 描画領域の下端からmarginだけ離す。\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-family=\")\" << \"Arial,san-serif\" << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-size=\")\" << fontsize << R\"(\")\" \r\n\t\t<< \" \"\r\n\t\t<< R\"(text-anchor=\"middle\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(dominant-baseline=\"text-after-edge\")\" // これでないとIEやWordで崩れる。\r\n\t\t<< \">\"\r\n\t\t<< xaxislabel \r\n\t\t<< R\"(</text>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\r\n\r\n\t// y軸タイトルを書く。\r\n\tstring yaxislabel = \"#Cases\";\r\n\t{\r\n\r\n\t\tdouble fontsize = 20; // とりあえずの値。\r\n\t\tdouble yaxislabelmargin = 30; // とりあえずの値。\r\n\t\t\r\n\t\tstringstream ss;\r\n\t\tdouble x = std::round( cam.actuXMin - yaxislabelmargin);\r\n\t\tdouble y = std::round( cam.getActualMidY());\r\n\r\n\t\tss << \"  \"\r\n\t\t<< R\"(<text)\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(x=\")\" << x << R\"(\")\" // 描画領域の左端からmarginだけ離す。\r\n\t\t<< \" \"\r\n\t\t<< R\"(y=\")\" << y << R\"(\")\" // 中央揃えをするので。\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-family=\")\" << \"Arial,san-serif\" << R\"(\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(font-size=\")\" << fontsize << R\"(\")\" \r\n\t\t<< \" \"\r\n\t\t<< R\"(text-anchor=\"middle\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(dominant-baseline=\"text-after-edge\")\"\r\n\t\t<< \" \"\r\n\t\t<< R\"(transform=\"rotate(270 )\" << x << \" \" << y << \")\" << R\"(\")\" \r\n\t\t<< \">\"\r\n\t\t<< yaxislabel \r\n\t\t<< R\"(</text>)\";\r\n\r\n\t\tsvglines.push_back( ss.str());\r\n\r\n\t}\r\n\r\n\t// 周辺情報記載の終了\r\n\r\n\r\n\r\n\t// 枠線を描く。最後にすべき。\r\n\t// fillは透過させる。\r\n\tsvglines.push_back( R\"(  <rect x=\"50\" y=\"50\" width=\"400\" height=\"400\" fill-opacity=\"0\" stroke=\"Black\" stroke-width=\"1\" />)\");\r\n\r\n\r\n\tsvglines.push_back( R\"(</svg>)\");\r\n\r\n\tstring detector = \"<!-- \" \r\n\t                  u8\"\\u6587\\u5B57\\u30B3\\u30FC\\u30C9\\u8B58\\u5225\\u7528\" // 「文字コード識別用」というUTF-8文字列\r\n\t                  \" -->\";\r\n\tsvglines.push_back( detector);\r\n\r\n\tkoutputfile outsvg( fn);\r\n\toutsvg.open( false, false, true);\r\n\toutsvg.writeLines( svglines);\r\n\toutsvg.close();\r\n\r\n}\r\n\r\n// [min0, max0]に、いい感じの間隔で点をとる。\r\n// k0個以上で最小の点を返す。\r\n// newminがtrueのとき、得られた間隔に乗る新しいminも返す。\r\n// newmaxがtrueのとき、得られた間隔に乗る新しいmaxも返す。\r\nstd::vector <double>\r\ngetGridPoints( double min0, double max0, int k0 /*= 4*/, bool newmin /*= true*/, bool newmax /*= true*/)\r\n{\r\n\r\n\tusing namespace std;\r\n\r\n\tvector <double> ret;\r\n\t\r\n\t// この数以上の最小の点を返すようにする。\r\n\tint minnpoints = k0; \r\n\r\n\t// error\r\n\tif ( min0 >= max0){ \r\n\t\talert( \"getGripPoints()\");\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tdouble max0ab = abs( max0);\r\n\tdouble min0ab = abs( min0);\r\n\r\n\t// max0abとmin0abのうち大きい方は何桁？（その値マイナス1）\r\n\tdouble digits_m1 = floor( log10( max( max0ab, min0ab)));\r\n\r\n\t// 基準となる10のべき乗値\r\n\tdouble base10val = pow( 10.0, digits_m1);\r\n\r\n\t// 候補となる、intervalの先頭の桁の値\r\n\tvector <double> headcands = { 5.0, 2.5, 2.0, 1.0};\r\n\r\n\tdouble interval;\r\n\r\n\tbool loop = true;\r\n\twhile ( loop){\r\n\r\n\t\tfor ( auto h : headcands){\r\n\r\n\t\t\tret.clear();\r\n\t\t\tinterval = base10val * h;\r\n\r\n\t\t\t// setting startpoint; to avoid startpoint being \"-0\", we do a little trick.\r\n\t\t\tdouble startpoint = ceil( min0 / interval);\r\n\t\t\tif ( startpoint > -1.0 && startpoint < 1.0){\r\n\t\t\t\tstartpoint = 0.0;\r\n\t\t\t}\r\n\t\t\tstartpoint *= interval;\r\n\r\n\t\t\tfor ( double p = startpoint; p <= max0; p += interval){\r\n\t\t\t\tret.push_back( p);\r\n\t\t\t}\r\n\t\t\tif ( ret.size() >= minnpoints){\r\n\t\t\t\tloop = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tbase10val /= 10.0;\r\n\r\n\t}\r\n\r\n\tif ( newmin == true){\r\n\t\tdouble oldmin = ret.front();\r\n\t\tif ( oldmin == min0){\r\n\t\t\t// if the first point already obtained is equal to min0\r\n\t\t\t// do nothing\r\n\t\t} else {\r\n\t\t\tret.insert( ret.begin(), oldmin - interval);\r\n\t\t}\r\n\t}\r\n\r\n\tif ( newmax == true){\r\n\t\tdouble oldmax = ret.back();\r\n\t\tif ( oldmax == max0){\r\n\t\t\t// if the last point already obtained is equal to max0\r\n\t\t\t// do nothing\r\n\t\t} else {\r\n\t\t\tret.push_back( oldmax + interval);\r\n\t\t}\r\n\t}\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n", "meta": {"hexsha": "35f06c05fc0ccfc58c5a66900b208e096cb0a327", "size": 21961, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/pclub/pclub03.cpp", "max_stars_repo_name": "kojiynet/koli", "max_stars_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "k09/pclub/pclub03.cpp", "max_issues_repo_name": "kojiynet/koli", "max_issues_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "k09/pclub/pclub03.cpp", "max_forks_repo_name": "kojiynet/koli", "max_forks_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2954314721, "max_line_length": 142, "alphanum_fraction": 0.52770821, "num_tokens": 9014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.5535453480984756}}
{"text": "\n/*\nsimplexSizeGenerator.cpp - This file is part of the Bayesembler (v1.1.1)\n\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Lasse Maretty and Jonas Andreas Sibbesen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/lexical_cast.hpp>\n#include <simplexSizeGenerator.h>\n\n\ntypedef boost::random::gamma_distribution<> gamma_distribution_t;\ntypedef boost::random::variate_generator<boost::random::mt19937*, boost::random::gamma_distribution<> > gamma_sampler_t;\ntypedef boost::random::mt19937* mt_rng_pt_t;\ntypedef boost::random::uniform_01<boost::random::mt19937*> uniform_01_sampler_t;\n\nint SimplexSizeGenerator::sampleSimplexSize(double pi, double gamma, int count_plus_size) {\n\t\n\tassert(count_plus_size <= num_transcripts);\n\tassert(pi >= double_underflow);\n\tassert(pi <= double_almost_one);\n\tassert(gamma > double_underflow);\n\n\t// Init binomial distribution over simplex sizes\n\tvector <double> simplex_prob_vector;\n    simplex_prob_vector.reserve(num_transcripts - count_plus_size + 1);\n\t\n\t// Cardinality of equivalence class of size |s+| is one\n\tdouble cardinal_eq_z_log = 0;\n\t\n\t// Calculate probability of member of equivalence class\n\tdouble prob_z_log = count_plus_size*log(pi) + (num_transcripts-count_plus_size)*log(1-pi);\n\t\n\t// Probability of assignment given the binary vector\n\tdouble prob_t_log = boost::math::lgamma(count_plus_size*gamma) - boost::math::lgamma(num_fragments + count_plus_size*gamma);\n\t\n\t// Full probability of the binary vector\t\t\n\tdouble prob_eq_z_log = cardinal_eq_z_log + prob_z_log + prob_t_log;\n\tdouble row_sum = prob_eq_z_log;\n\t\n\tsimplex_prob_vector.push_back(row_sum);\n    \t\n\tfor (int i = count_plus_size + 1; i < num_transcripts + 1; i++) {\n\t\t\n\t\t// Calculate cardinality of equivalence class\n\t\tcardinal_eq_z_log = boost::math::lgamma(num_transcripts-count_plus_size+1)-(boost::math::lgamma(i-count_plus_size+1)+boost::math::lgamma(num_transcripts - i + 1));\n\t\t\n\t\t// Calculate probability of member of equivalence class\n\t\tprob_z_log = i*log(pi) + (num_transcripts-i)*log(1-pi);\n\t\t\n\t\t// Probability of assignment given the binary vector\n\t\tprob_t_log = boost::math::lgamma(i*gamma) - boost::math::lgamma(num_fragments + i*gamma);\n\t\t\n\t\t// Full probability of the binary vector\n\t\tprob_eq_z_log = cardinal_eq_z_log + prob_z_log + prob_t_log;\n\t\t\n\t\trow_sum += log(1 + exp(prob_eq_z_log - row_sum));\n\t\tsimplex_prob_vector.push_back(row_sum);\n                \n    \tif (double_compare(simplex_prob_vector.back(), *(simplex_prob_vector.rbegin() + 1))) {\n            \n            break;     \n        }\n\t}\n\t\n\t// Row-normalise and transform back from log-space\n\tfor (int i = 0; i < simplex_prob_vector.size(); i++) {\n\t\t\n\t    simplex_prob_vector[i] = exp(simplex_prob_vector[i] - row_sum);\n        \n\t}\n    \n    assert (simplex_prob_vector.back() > double_almost_one);\n    \n\tuniform_01_sampler_t sample_uniform_01(mt_rng_pt);\n\t\n\tint b = int(upper_bound(simplex_prob_vector.begin(), simplex_prob_vector.end(), sample_uniform_01()) - simplex_prob_vector.begin()) + count_plus_size;\n    \n\treturn b;\t\t\n}\n\n\nbool SimplexSizeGenerator::isFixed() {\n\t\n\treturn is_fixed;\n\t\n}\n\n/* SIMPLEX-SIZE GENERATOR CLASS */\nFixedBinomialFixedGammaSimplexSizeGenerator::FixedBinomialFixedGammaSimplexSizeGenerator(double pi_in, double gamma_in, int num_transcripts_in, mt_rng_pt_t mt_rng_pt_in, int num_fragments_in) {\n\n    // Set members \n    pi = pi_in;\n    gamma = gamma_in;\n    num_transcripts = num_transcripts_in;\n    is_fixed = true;\n    mt_rng_pt = mt_rng_pt_in;\n    num_fragments = num_fragments_in;\n    \n    simplex_prob_matrix = vector<vector<double> >(num_transcripts, vector<double>());\n    \n    // Loop over count plus sizes \n    for (int i=0; i < num_transcripts; i++) {\n        \n        int count_plus_size = i + 1;\n        \n    \t// Init binomial distribution over simplex sizes\n    \tvector < double> simplex_prob_vector;\n\t\n    \t// Cardinality of equivalence class of size |s+| is zero\n    \tdouble cardinal_eq_z_log = 0;\n\t\n    \t// Calculate probability of member of equivalence class\n    \tdouble prob_z_log = count_plus_size*log(pi) + (num_transcripts-count_plus_size)*log(1-pi);\n\t\n    \t// Probability of assignment given the binary vector\n    \tdouble prob_t_log = boost::math::lgamma(count_plus_size*gamma) - boost::math::lgamma(num_fragments + count_plus_size*gamma);\n\t\n    \t// Full probability of the binary vector\t\t\n    \tdouble prob_eq_z_log = cardinal_eq_z_log + prob_z_log + prob_t_log;\n    \tdouble row_sum = prob_eq_z_log;\n\t\n    \tsimplex_prob_vector.push_back(row_sum);\n\t\n    \tfor (int j = count_plus_size + 1; j < num_transcripts + 1; j++) {\n\t\t\n    \t\t// Calculate cardinality of equivalence class\n    \t\tcardinal_eq_z_log = boost::math::lgamma(num_transcripts-count_plus_size+1)-(boost::math::lgamma(j-count_plus_size+1)+boost::math::lgamma(num_transcripts - j + 1));\n\t\t\n    \t\t// Calculate probability of member of equivalence class\n    \t\tprob_z_log = j*log(pi) + (num_transcripts-j)*log(1-pi);\n\t\t\n    \t\t// Probability of assignment given the binary vector\n    \t\tprob_t_log = boost::math::lgamma(j*gamma) - boost::math::lgamma(num_fragments + j*gamma);\n\t\t\n    \t\t// Full probability of the binary std::vector<char> v;\n    \t\tprob_eq_z_log = cardinal_eq_z_log + prob_z_log + prob_t_log;\n\t\t    \n            row_sum += log(1 + exp(prob_eq_z_log - row_sum));\n    \t\tsimplex_prob_vector.push_back(row_sum);\n            \n            if (double_compare(simplex_prob_vector.back(), *(simplex_prob_vector.rbegin() + 1))) {\n\n                break;     \n            }\n    \t}\n    \n    \t// Row-normalise and transform back from log-space\n    \tfor (int j = 0; j < simplex_prob_vector.size(); j++) {\n\t\t\n    \t    simplex_prob_vector[j] = exp(simplex_prob_vector[j] - row_sum);\n        \n    \t}\n\n        assert (simplex_prob_vector.back() > double_almost_one);\n        \n        simplex_prob_matrix[i] = simplex_prob_vector;\n        \n    }\n}\n\nstring FixedBinomialFixedGammaSimplexSizeGenerator::getParameterString(){\n        \n    string parameter_str;       \n    parameter_str += \"pi\";\n    parameter_str += boost::lexical_cast<string>(pi);\n    parameter_str += \"gamma\";\n    parameter_str += boost::lexical_cast<string>(gamma);\n    \n    return parameter_str;\n}\n\n// Initialise simplex probability matrix\npair<int, double> FixedBinomialFixedGammaSimplexSizeGenerator::initSimplexSize(int count_plus_size, double gamma) {\n            \n    int b = sampleSimplexSize(pi, gamma, count_plus_size);\n    \n    return pair<int, double>(b, pi);\n}\n\n// Samples a simplex size from the simplex size probability matrix\npair<int, double> FixedBinomialFixedGammaSimplexSizeGenerator::generateSimplexSize(int expression_plus_size, int count_plus_size, double gamma) {\n           \n    int b = sampleSimplexSize(pi, gamma, count_plus_size);\n    \n    return pair<int, double>(b, pi);\n}\n\nint FixedBinomialFixedGammaSimplexSizeGenerator::sampleSimplexSize(double pi, double gamma, int count_plus_size) {\n\t\n    uniform_01_sampler_t sample_uniform_01(mt_rng_pt);\n    \n    int b = int(upper_bound(simplex_prob_matrix[count_plus_size-1].begin(), simplex_prob_matrix[count_plus_size-1].end(), sample_uniform_01()) - simplex_prob_matrix[count_plus_size-1].begin()) + count_plus_size;\n        \n    return b;        \n\n}\n\n\nFixedBinomialSimplexSizeGenerator::FixedBinomialSimplexSizeGenerator(double pi_in, int num_transcripts_in, mt_rng_pt_t mt_rng_pt_in, int num_fragments_in) {\n\n\t// Set members \n\tpi = pi_in;\n\tnum_transcripts = num_transcripts_in;\n\tis_fixed = true;\n\tmt_rng_pt = mt_rng_pt_in;\n\tnum_fragments = num_fragments_in;\t    \n}\n\nstring FixedBinomialSimplexSizeGenerator::getParameterString(){\n    \t\n    string parameter_str;       \n\tparameter_str += \"pi\";\n    parameter_str += boost::lexical_cast<string>(pi);\n    \n    return parameter_str;\n}\n\n// Initialise simplex probability matrix\npair<int, double> FixedBinomialSimplexSizeGenerator::initSimplexSize(int count_plus_size, double gamma) {\n\t\n\t\t\n\tint b = sampleSimplexSize(pi, gamma, count_plus_size);\n\t\t\t\n\treturn pair<int, double>(b, pi);\n}\n\n// Samples a simplex size from the simplex size probability matrix\npair<int, double> FixedBinomialSimplexSizeGenerator::generateSimplexSize(int expression_plus_size, int count_plus_size, double gamma) {\n\t\t\n\tint b = sampleSimplexSize(pi, gamma, count_plus_size);\n\t\t\t\n\treturn pair<int, double>(b, pi);\n}\n\nBetaBinomialSimplexSizeGenerator::BetaBinomialSimplexSizeGenerator(double alpha_in, double beta_in, int num_transcripts_in, mt_rng_pt_t mt_rng_pt_in, int num_fragments_in, int slice_iterations_in, double slice_window_size_in) {\n\t\n\talpha = alpha_in;\n\tbeta = beta_in;\n\tnum_transcripts = num_transcripts_in;\n\tis_fixed = false;\n\tmt_rng_pt = mt_rng_pt_in;\n\tnum_fragments = num_fragments_in;\n\tslice_iterations = slice_iterations_in;\n    slice_window_size = slice_window_size_in;\n\t\n}\n\nstring BetaBinomialSimplexSizeGenerator::getParameterString(){\n    \n\tstring parameter_str;       \n\tparameter_str += \"alpha\";\n    parameter_str += boost::lexical_cast<string>(alpha);\n\tparameter_str += \"_\";\n\tparameter_str += \"beta\";\n    parameter_str += boost::lexical_cast<string>(beta);\n    \n    return parameter_str;\n}\n\npair<int, double> BetaBinomialSimplexSizeGenerator::initSimplexSize(int count_plus_size, double gamma) {\n\t\t\t\n\t// Sample pi from beta-prior\n\tgamma_distribution_t gamma_dist_alpha(alpha,1);\n\tgamma_distribution_t gamma_dist_beta(beta,1);\n\t\n\tgamma_sampler_t sample_gamma_alpha(mt_rng_pt, gamma_dist_alpha);\n\tgamma_sampler_t sample_gamma_beta(mt_rng_pt, gamma_dist_beta);\n\t\n\tdouble sample_alpha = sample_gamma_alpha();\n\tdouble sample_beta = sample_gamma_beta();\n\t\n\tdouble pi = sample_alpha / (sample_alpha + sample_beta);\n\t\t\n\tif (pi > double_almost_one) {\n\t\t\n\t\tpi = double_almost_one;\n\t}\n    \n\tif (pi < double_precision) {\n\t\t\n\t\tpi = double_precision;\t\n\t}\n\t\n\tint b = sampleSimplexSize(pi, gamma, count_plus_size);\n\t\t\t\n\treturn pair<int, double>(b, pi);\n\t\n}\n\npair<int, double> BetaBinomialSimplexSizeGenerator::generateSimplexSize(int expression_plus_size, int count_plus_size, double gamma) {\n\t\n\tdouble pi = samplePi(expression_plus_size);\n\t\n\tif (pi > double_almost_one) {\n\t\t\n\t\tpi = double_almost_one;\t\n\t}\n    \n\tif (pi < double_precision) {\n\t\t\n\t\tpi = double_precision;\n\t}\n\t\t\n\tint b = sampleSimplexSize(pi, gamma, count_plus_size);\t\n\t\n\treturn pair<int, double>(b, pi);\n}\n\ndouble BetaBinomialSimplexSizeGenerator::posteriorPiLogDensity(int expression_plus_size, double pi) {\n        \n\treturn ((alpha + expression_plus_size - 1)*log(pi) + (beta + num_transcripts - expression_plus_size - 1)*log(1-pi) - log(1 - exp(num_transcripts*log(1-pi))));\n    \n}\n\ndouble BetaBinomialSimplexSizeGenerator::samplePi(int expression_plus_size) {\n\t\t\n\t// Init gamma and uniform sampler\n\tuniform_01_sampler_t sample_uniform_01(mt_rng_pt);\n\t\n\tdouble pi_current = sample_uniform_01();\n\tdouble pi = pi_current;\n    \t\t\n\tif (pi_current < double_precision) {\n\t\t\n\t\tpi_current = double_precision;\n\t\t\n\t}\n\t\n\tif (pi_current > double_almost_one) {\n\t\t\n\t\tpi_current = double_almost_one;\n\t\t\n\t}\n\t\t\n\t// Output all samples for convergence assessment\n\t// ofstream pi_slice_out(\"pi_slice_out.txt\", ios::app);\n\t\n\tfor (int i=0; i < slice_iterations; i++) {\n\t\t\n\t\t// Sample height\t\n\t\tdouble y = posteriorPiLogDensity(expression_plus_size, pi_current) + log(1-sample_uniform_01());\n\t\t\t\t\n\t\t// Find slice by \"step-out\"\n\t\tdouble left = pi_current - sample_uniform_01() * slice_window_size;\n\t\tdouble right = left + slice_window_size;\n\t\t\n\t\tint j = 1;\n\t\tint k = 1;\n\t\t\n\t\t// Truncate distribution at zero\n\t\tif (left < double_precision) {\t\t\t\n\t\t\tleft = double_precision;\n\t\t\tj = 0;\n\t\t}\n\t\t\n\t\t// Truncate distribution at one\n\t\tif (right > double_almost_one) {\n\t\t\tright = double_almost_one;\n\t\t\tk = 0;\n\t\t}\n\t\t\n\t\t// Expand window to the left\t\t\n\t\twhile (j == 1 && y < (posteriorPiLogDensity(expression_plus_size, left))) {\n\t\t\tleft = left - slice_window_size;\n            \n\t\t\tif (left < double_precision) {\n\t\t\t\tleft = double_precision;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Expand window to the right\n\t\twhile (k == 1 && y < (posteriorPiLogDensity(expression_plus_size, right))) {\n\t\t\tright = right + slice_window_size;\n            \n\t\t\tif (right > double_almost_one) {\t\t\t\t\n\t\t\t\tright = double_almost_one;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n        \n\t\t// Sample from the window and step-in window boundaries until in slice\n\t\tpi = sample_uniform_01()*(right-left) + left;\n\t\t\n\t\twhile ( y >= (posteriorPiLogDensity(expression_plus_size, pi))) {\n\t\t\t            \n            if (pi < pi_current) {\n\t\t\t\t\n\t\t\t\tleft = pi;\n\t\t\t\tpi = sample_uniform_01()*(right-left) + left;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tright = pi;\n\t\t\t\tpi = sample_uniform_01()*(right-left) + left;\t\t\t\n\t\t\t}                \n\t\t}\n\t\t\n\t\tpi_current = pi;\n\t\t// pi_slice_out << pi << endl;\n\t}\n\t\n\t// pi_slice_out.close();\n\t\n\treturn pi;\n}", "meta": {"hexsha": "2fc7947ada378400fb1bda156bbb2d7f074a4290", "size": 13867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simplexSizeGenerator.cpp", "max_stars_repo_name": "bhurwitz33/bayesembler", "max_stars_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T15:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-10T15:43:12.000Z", "max_issues_repo_path": "src/simplexSizeGenerator.cpp", "max_issues_repo_name": "bhurwitz33/bayesembler", "max_issues_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simplexSizeGenerator.cpp", "max_forks_repo_name": "bhurwitz33/bayesembler", "max_forks_repo_head_hexsha": "b1d8200d5ffa2ae3476391d9f35f26e5f14f517f", "max_forks_repo_licenses": ["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.9516129032, "max_line_length": 227, "alphanum_fraction": 0.7147905098, "num_tokens": 3484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5534694201874785}}
{"text": "#include <sequential-line-search/gaussianprocessregressor.h>\n#include <sequential-line-search/utils.h>\n#include <iostream>\n#include <cmath>\n#include <Eigen/LU>\n#include <nlopt-util.hpp>\n\n//#define NOISELESS\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    using namespace sequential_line_search;\n    \n    const bool   useLogNormalPrior     = true;\n    const double a_prior_mu            = std::log(0.500);\n    const double a_prior_sigma_squared = 0.10;\n#ifdef NOISELESS\n    const double b_fixed               = 1e-06;\n#else\n    const double b_prior_mu            = std::log(0.001);\n    const double b_prior_sigma_squared = 0.10;\n#endif\n    const double r_prior_mu            = std::log(0.500);\n    const double r_prior_sigma_squared = 0.10;\n    \n    double calc_grad_a_prior(const double a)\n    {\n        return (a_prior_mu - a_prior_sigma_squared - std::log(a)) / (a_prior_sigma_squared * a);\n    }\n    \n#ifndef NOISELESS\n    double calc_grad_b_prior(const double b)\n    {\n        return (b_prior_mu - b_prior_sigma_squared - std::log(b)) / (b_prior_sigma_squared * b);\n    }\n#endif\n    \n    double calc_grad_r_i_prior(const Eigen::VectorXd &r, const int index)\n    {\n        return (r_prior_mu - r_prior_sigma_squared - std::log(r(index))) / (r_prior_sigma_squared * r(index));\n    }\n    \n    double calc_a_prior(const double a)\n    {\n        return std::log(utils::log_normal(a, a_prior_mu, a_prior_sigma_squared));\n    }\n    \n#ifndef NOISELESS\n    double calc_b_prior(const double b)\n    {\n        return std::log(utils::log_normal(b, b_prior_mu, b_prior_sigma_squared));\n    }\n#endif\n    \n    double calc_r_i_prior(const Eigen::VectorXd &r, const int index)\n    {\n        return std::log(utils::log_normal(r(index), r_prior_mu, r_prior_sigma_squared));\n    }\n    \n    double calc_grad_a(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n    {\n        const MatrixXd C_grad_a = Regressor::calc_C_grad_a(X, a, b, r);\n        const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_a * C_inv * y;\n        const double term2 = - 0.5 * (C_inv * C_grad_a).trace();\n        return term1 + term2 + (useLogNormalPrior ? calc_grad_a_prior(a) : 0.0);\n    }\n    \n#ifndef NOISELESS\n    double calc_grad_b(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n    {\n        const MatrixXd C_grad_b = Regressor::calc_C_grad_b(X, a, b, r);\n        const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_b * C_inv * y;\n        const double term2 = - 0.5 * (C_inv * C_grad_b).trace();\n        return term1 + term2 + (useLogNormalPrior ? calc_grad_b_prior(b) : 0.0);\n    }\n#endif\n    \n    double calc_grad_r_i(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r, const int index)\n    {\n        const MatrixXd C_grad_r_i = Regressor::calc_C_grad_r_i(X, a, b, r, index);\n        const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_r_i * C_inv * y;\n        const double term2 = - 0.5 * (C_inv * C_grad_r_i).trace();\n        return term1 + term2 + (useLogNormalPrior ? calc_grad_r_i_prior(r, index) : 0.0);\n    }\n    \n    VectorXd calc_grad(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n    {\n        const unsigned D = X.rows();\n        \n        VectorXd grad(D + 2);\n        grad(0) = calc_grad_a(X, C_inv, y, a, b, r);\n#ifdef NOISELESS\n        grad(1) = 0.0;\n#else\n        grad(1) = calc_grad_b(X, C_inv, y, a, b, r);\n#endif\n        \n        for (unsigned i = 2; i < D + 2; ++ i)\n        {\n            const unsigned index = i - 2;\n            grad(i) = calc_grad_r_i(X, C_inv, y, a, b, r, index);\n        }\n        \n        return grad;\n    }\n    \n    struct Data\n    {\n        const MatrixXd X;\n        const VectorXd y;\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 unsigned N = X.cols();\n        \n        const double   a = x[0];\n#ifdef NOISELESS\n        const double   b = b_fixed;\n#else\n        const double   b = x[1];\n#endif\n        const VectorXd r = Eigen::Map<const VectorXd>(&x[2], x.size() - 2);\n        \n        const MatrixXd C     = Regressor::calc_C(X, a, b, r);\n        const MatrixXd C_inv = C.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, C_inv, y, a, b, r);\n            for (unsigned i = 0; i < g.rows(); ++ i) grad[i] = g(i);\n        }\n        \n        const double term1 = - 0.5 * y.transpose() * C_inv * y;\n        const double term2 = - 0.5 * std::log(C.determinant());\n        const double term3 = - 0.5 * N * std::log(2.0 * M_PI);\n        \n        // Computing the regularization terms from a prior assumptions\n        const double a_prior = calc_a_prior(a);\n#ifdef NOISELESS\n        const double b_prior = 1.0;\n#else\n        const double b_prior = calc_b_prior(b);\n#endif\n        const double r_prior = [&r]()\n        {\n            double sum = 0.0;\n            for (unsigned i = 0; i < r.rows(); ++ i) sum += calc_r_i_prior(r, i);\n            return sum;\n        }();\n        const double regularization = useLogNormalPrior ? (a_prior + b_prior + r_prior) : 0.0;\n        \n        return term1 + term2 + term3 + regularization;\n    }\n}\n\nnamespace sequential_line_search\n{\n    GaussianProcessRegressor::GaussianProcessRegressor(const MatrixXd& X, const VectorXd& y)\n    {\n        this->X = X;\n        this->y = y;\n        \n        if (X.rows() == 0) return;\n        \n        compute_MAP();\n        \n        C     = calc_C(X, a, b, r);\n        C_inv = C.inverse();\n    }\n    \n    GaussianProcessRegressor::GaussianProcessRegressor(const Eigen::MatrixXd &X, const Eigen::VectorXd &y, double a, double b, const Eigen::VectorXd &r)\n    {\n        this->X = X;\n        this->y = y;\n        this->a = a;\n        this->b = b;\n        this->r = r;\n        \n        C     = calc_C(X, a, b, r);\n        C_inv = C.inverse();\n    }\n    \n    double GaussianProcessRegressor::estimate_y(const VectorXd &x) const\n    {\n        const VectorXd k = calc_k(x, X, a, b, r);\n        return k.transpose() * C_inv * y;\n    }\n    \n    double GaussianProcessRegressor::estimate_s(const VectorXd &x) const\n    {\n        const VectorXd k = calc_k(x, X, a, b, r);\n        return std::sqrt(a + b - k.transpose() * C_inv * k);\n    }\n    \n    void GaussianProcessRegressor::compute_MAP()\n    {\n        const unsigned D = X.rows();\n        \n        Data data{ X, y };\n        \n        const VectorXd x_ini = VectorXd::Constant(D + 2, 1e+00);\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, 300);\n        const VectorXd x_loc = nloptutil::solve(x_glo, upper, lower, objective, nlopt::LD_TNEWTON, &data, 1000);\n        \n        a = x_loc(0);\n        b = x_loc(1);\n        r = x_loc.block(2, 0, D, 1);\n        \n#ifdef NOISELESS\n        b = b_fixed;\n#endif\n    }\n}\n", "meta": {"hexsha": "f4c597a7036114005b5638454d05767a057675a5", "size": 7577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gaussianprocessregressor.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/gaussianprocessregressor.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/gaussianprocessregressor.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": 32.6594827586, "max_line_length": 153, "alphanum_fraction": 0.5828164181, "num_tokens": 2109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.5534694158601597}}
{"text": "/**\n * \\file LinkwitzRileyFilter.cpp\n */\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include \"LinkwitzRileyFilter.h\"\n#include \"IIRFilter.h\"\n\nnamespace ATK\n{\n  template<typename DataType>\n  LinkwitzRileyLowPassCoefficients<DataType>::LinkwitzRileyLowPassCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void LinkwitzRileyLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType omega = boost::math::constants::pi<DataType>() * cut_frequency;\n    DataType kappa = omega / std::tan(omega / input_sampling_rate);\n    DataType 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(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void LinkwitzRileyHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType omega = boost::math::constants::pi<DataType>() * cut_frequency;\n    DataType kappa = omega / std::tan(omega / input_sampling_rate);\n    DataType 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 class LinkwitzRileyLowPassCoefficients<float>;\n  template class LinkwitzRileyLowPassCoefficients<double>;\n  template class LinkwitzRileyHighPassCoefficients<float>;\n  template class LinkwitzRileyHighPassCoefficients<double>;\n  \n  template class IIRFilter<LinkwitzRileyLowPassCoefficients<float> >;\n  template class IIRFilter<LinkwitzRileyLowPassCoefficients<double> >;\n  template class IIRFilter<LinkwitzRileyHighPassCoefficients<float> >;\n  template class IIRFilter<LinkwitzRileyHighPassCoefficients<double> >;\n}\n", "meta": {"hexsha": "cd620d31c9583d086ff133c3aaa45e1482577b7c", "size": 2301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/LinkwitzRileyFilter.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/LinkwitzRileyFilter.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/LinkwitzRileyFilter.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": 34.8636363636, "max_line_length": 97, "alphanum_fraction": 0.7201216862, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.553216200528986}}
{"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_EULER_FUNCTIONS_SCALAR_GAMMA_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_GAMMA_HPP_INCLUDED\n#include <nt2/euler/functions/gamma.hpp>\n#include <nt2/euler/functions/details/gamma_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/three.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/copysign.hpp>\n#include <nt2/include/functions/scalar/floor.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n#include <nt2/include/functions/scalar/is_even.hpp>\n#include <nt2/include/functions/scalar/is_ltz.hpp>\n#include <nt2/include/functions/scalar/sinpi.hpp>\n#include <nt2/include/functions/scalar/stirling.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/functions/scalar/is_nan.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( gamma_, tag::cpu_\n                            , (A0)\n                            , (scalar_< floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      if (is_eqz(a0)) return copysign(Inf<A0>(), a0);\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if( nt2::is_nan(a0) || (a0 == nt2::Minf<A0>()) ) return nt2::Nan<A0>();\n      if (a0 == nt2::Inf<A0>()) return a0;\n      #endif\n\n      A0 x = a0;\n      A0 q = nt2::abs(x);\n      if(x < A0(-33.0))\n      {\n        A0 st = nt2::stirling(q);\n        A0 p =  nt2::floor(q);\n        bool iseven =  nt2::is_even((int32_t)p);\n        if (p == q) return nt2::Nan<A0>();\n        A0 z = q - p;\n        if( z > nt2::Half<A0>() )\n        {\n          p += nt2::One<A0>();\n          z = q - p;\n        }\n        z = q*nt2::sinpi(z);\n        if( nt2::is_eqz(z) ) return nt2::Nan<A0>();\n        st = nt2::Pi<A0>()/(nt2::abs(z)*st);\n        return iseven  ? -st : st;\n      }\n      A0 z = nt2::One<A0>();\n      while( x >= nt2::Three<A0>() )\n      {\n        x -= nt2::One<A0>();\n        z *= x;\n      }\n      while( nt2::is_ltz(x) )\n      {\n        z /= x;\n        x += nt2::One<A0>();\n      }\n      while( x < nt2::Two<A0>() )\n      {\n        if( nt2::is_eqz(x)) return nt2::Nan<A0>();\n        z /= x;\n        x +=  nt2::One<A0>();\n      }\n      if( x == nt2::Two<A0>() ) return(z);\n      x -= nt2::Two<A0>();\n      return z*details::gamma_kernel<A0>::gamma1(x);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "c85273cf5bf40089cf9d0a8bff1a830e0e00edd6", "size": 3107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/gamma.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/euler/include/nt2/euler/functions/scalar/gamma.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/euler/include/nt2/euler/functions/scalar/gamma.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.3645833333, "max_line_length": 80, "alphanum_fraction": 0.5455423238, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.5532116268361958}}
{"text": "#include <vector>\n#include <boost/math/distributions/beta.hpp>\n#include \"beta_dist.h\"\n\nstochastic::BetaDistribution::BetaDistribution(double alpha, double beta)\n  : Distribution(),\n    alpha_{alpha},\n    beta_{beta},\n    distribution_{alpha, beta_}\n{}\n\nstd::vector<double> stochastic::BetaDistribution::cumulative_dist_func(\n    const std::vector<double>& locations) const {\n  std::vector<double> evaluations(locations.size());\n\n  for (unsigned int i = 0; i < locations.size(); ++i) {\n    evaluations[i] = cdf(distribution_, locations[i]);\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> stochastic::BetaDistribution::inv_cumulative_dist_func(\n    const std::vector<double>& probabilities) const {\n  std::vector<double> evaluations(probabilities.size());\n\n  for (unsigned int i = 0; i < probabilities.size(); ++i) {\n    evaluations[i] = quantile(distribution_, probabilities[i]);\n  }\n\n  return evaluations;\n}\n", "meta": {"hexsha": "ba86f0f92278d70cb2826809fbff3bcb5a3af331", "size": 911, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/beta_dist.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/beta_dist.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/beta_dist.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 27.6060606061, "max_line_length": 75, "alphanum_fraction": 0.7124039517, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.682573740869499, "lm_q1q2_score": 0.5532116143376659}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2016 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\r\n\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <boost/geometry/core/radius.hpp>\r\n#include <boost/geometry/core/srs.hpp>\r\n\r\n#include <boost/geometry/util/condition.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/flattening.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace formula\r\n{\r\n\r\n/*!\r\n\\brief The intersection of two geodesics as proposed by Sjoberg.\r\n\\author See\r\n    - [Sjoberg02] Lars E. Sjoberg, Intersections on the sphere and ellipsoid, 2002\r\n      http://link.springer.com/article/10.1007/s00190-001-0230-9\r\n    - [Sjoberg07] Lars E. Sjoberg, Geodetic intersection on the ellipsoid, 2007\r\n      http://link.springer.com/article/10.1007/s00190-007-0204-7\r\n*/\r\ntemplate\r\n<\r\n    typename CT,\r\n    template <typename, bool, bool, bool, bool, bool> class Inverse,\r\n    unsigned int Order = 4\r\n>\r\nclass sjoberg_intersection\r\n{\r\n    typedef Inverse<CT, false, true, false, false, false> inverse_type;\r\n    typedef typename inverse_type::result_type inverse_result;\r\n\r\npublic:\r\n    template <typename T1, typename T2, typename Spheroid>\r\n    static inline bool apply(T1 const& lona1, T1 const& lata1,\r\n                             T1 const& lona2, T1 const& lata2,\r\n                             T2 const& lonb1, T2 const& latb1,\r\n                             T2 const& lonb2, T2 const& latb2,\r\n                             CT & lon, CT & lat,\r\n                             Spheroid const& spheroid)\r\n    {\r\n        CT const lon_a1 = lona1;\r\n        CT const lat_a1 = lata1;\r\n        CT const lon_a2 = lona2;\r\n        CT const lat_a2 = lata2;\r\n        CT const lon_b1 = lonb1;\r\n        CT const lat_b1 = latb1;\r\n        CT const lon_b2 = lonb2;\r\n        CT const lat_b2 = latb2;\r\n\r\n        CT const alpha1 = inverse_type::apply(lon_a1, lat_a1, lon_a2, lat_a2, spheroid).azimuth;\r\n        CT const alpha2 = inverse_type::apply(lon_b1, lat_b1, lon_b2, lat_b2, spheroid).azimuth;\r\n\r\n        return apply(lon_a1, lat_a1, alpha1, lon_b1, lat_b1, alpha2, lon, lat, spheroid);\r\n    }\r\n    \r\n    template <typename Spheroid>\r\n    static inline bool apply(CT const& lon1, CT const& lat1, CT const& alpha1,\r\n                             CT const& lon2, CT const& lat2, CT const& alpha2,\r\n                             CT & lon, CT & lat,\r\n                             Spheroid const& spheroid)\r\n    {\r\n        // coordinates in radians\r\n\r\n        // TODO - handle special cases like degenerated segments, equator, poles, etc.\r\n\r\n        CT const c0 = 0;\r\n        CT const c1 = 1;\r\n        CT const c2 = 2;\r\n\r\n        CT const pi = math::pi<CT>();\r\n        CT const pi_half = pi / c2;\r\n        CT const f = detail::flattening<CT>(spheroid);\r\n        CT const one_minus_f = c1 - f;\r\n        CT const e_sqr = f * (c2 - f);\r\n        \r\n        CT const sin_alpha1 = sin(alpha1);\r\n        CT const sin_alpha2 = sin(alpha2);\r\n\r\n        CT const tan_beta1 = one_minus_f * tan(lat1);\r\n        CT const tan_beta2 = one_minus_f * tan(lat2);\r\n        CT const beta1 = atan(tan_beta1);\r\n        CT const beta2 = atan(tan_beta2);\r\n        CT const cos_beta1 = cos(beta1);\r\n        CT const cos_beta2 = cos(beta2);\r\n        CT const sin_beta1 = sin(beta1);\r\n        CT const sin_beta2 = sin(beta2);\r\n\r\n        // Clairaut constants (lower-case in the paper)\r\n        int const sign_C1 = math::abs(alpha1) <= pi_half ? 1 : -1;\r\n        int const sign_C2 = math::abs(alpha2) <= pi_half ? 1 : -1;\r\n        // Cj = 1 if on equator\r\n        CT const C1 = sign_C1 * cos_beta1 * sin_alpha1;\r\n        CT const C2 = sign_C2 * cos_beta2 * sin_alpha2;\r\n\r\n        CT const sqrt_1_C1_sqr = math::sqrt(c1 - math::sqr(C1));\r\n        CT const sqrt_1_C2_sqr = math::sqrt(c1 - math::sqr(C2));\r\n\r\n        // handle special case: segments on the equator\r\n        bool const on_equator1 = math::equals(sqrt_1_C1_sqr, c0);\r\n        bool const on_equator2 = math::equals(sqrt_1_C2_sqr, c0);\r\n        if (on_equator1 && on_equator2)\r\n        {\r\n            return false;\r\n        }\r\n        else if (on_equator1)\r\n        {\r\n            CT const dL2 = d_lambda_e_sqr(sin_beta2, c0, C2, sqrt_1_C2_sqr, e_sqr);\r\n            CT const asin_t2_t02 = asin(C2 * tan_beta2 / sqrt_1_C2_sqr);\r\n            lat = c0;\r\n            lon = lon2 - asin_t2_t02 + dL2;\r\n            return true;\r\n        }\r\n        else if (on_equator2)\r\n        {\r\n            CT const dL1 = d_lambda_e_sqr(sin_beta1, c0, C1, sqrt_1_C1_sqr, e_sqr);\r\n            CT const asin_t1_t01 = asin(C1 * tan_beta1 / sqrt_1_C1_sqr);\r\n            lat = c0;\r\n            lon = lon1 - asin_t1_t01 + dL1;\r\n            return true;\r\n        }\r\n\r\n        CT const t01 = sqrt_1_C1_sqr / C1;\r\n        CT const t02 = sqrt_1_C2_sqr / C2;\r\n\r\n        CT const asin_t1_t01 = asin(tan_beta1 / t01);\r\n        CT const asin_t2_t02 = asin(tan_beta2 / t02);\r\n        CT const t01_t02 = t01 * t02;\r\n        CT const t01_t02_2 = c2 * t01_t02;\r\n        CT const sqr_t01_sqr_t02 = math::sqr(t01) + math::sqr(t02);\r\n\r\n        CT t = tan_beta1;\r\n        int t_id = 0;\r\n\r\n        // find the initial t using simplified spherical solution\r\n        // though not entirely since the reduced latitudes and azimuths are spheroidal\r\n        // [Sjoberg07]\r\n        CT const k_base = lon1 - lon2 + asin_t2_t02 - asin_t1_t01;\r\n        \r\n        {\r\n            CT const K = sin(k_base);\r\n            CT const d1 = sqr_t01_sqr_t02;\r\n            //CT const d2 = t01_t02_2 * math::sqrt(c1 - math::sqr(K));\r\n            CT const d2 = t01_t02_2 * cos(k_base);\r\n            CT const D1 = math::sqrt(d1 - d2);\r\n            CT const D2 = math::sqrt(d1 + d2);\r\n            CT const K_t01_t02 = K * t01_t02;\r\n\r\n            CT const T1 = K_t01_t02 / D1;\r\n            CT const T2 = K_t01_t02 / D2;\r\n            CT asin_T1_t01 = 0;\r\n            CT asin_T1_t02 = 0;\r\n            CT asin_T2_t01 = 0;\r\n            CT asin_T2_t02 = 0;\r\n\r\n            // test 4 possible results\r\n            CT l1 = 0, l2 = 0, dl = 0;\r\n            bool found = check_t<0>( T1,\r\n                                    lon1,  asin_T1_t01 = asin(T1 / t01), asin_t1_t01,\r\n                                    lon2,  asin_T1_t02 = asin(T1 / t02), asin_t2_t02,\r\n                                    t, l1, l2, dl, t_id)\r\n                      || check_t<1>(-T1,\r\n                                    lon1, -asin_T1_t01                 , asin_t1_t01,\r\n                                    lon2, -asin_T1_t02                 , asin_t2_t02,\r\n                                    t, l1, l2, dl, t_id)\r\n                      || check_t<2>( T2,\r\n                                    lon1,  asin_T2_t01 = asin(T2 / t01), asin_t1_t01,\r\n                                    lon2,  asin_T2_t02 = asin(T2 / t02), asin_t2_t02,\r\n                                    t, l1, l2, dl, t_id)\r\n                      || check_t<3>(-T2,\r\n                                    lon1, -asin_T2_t01                 , asin_t1_t01,\r\n                                    lon2, -asin_T2_t02                 , asin_t2_t02,\r\n                                    t, l1, l2, dl, t_id);\r\n\r\n            boost::ignore_unused(found);\r\n        }\r\n        \r\n        // [Sjoberg07]\r\n        //int const d2_sign = t_id < 2 ? -1 : 1;\r\n        int const t_sign = (t_id % 2) ? -1 : 1;\r\n        // [Sjoberg02]\r\n        CT const C1_sqr = math::sqr(C1);\r\n        CT const C2_sqr = math::sqr(C2);\r\n        \r\n        CT beta = atan(t);\r\n        CT dL1 = 0, dL2 = 0;\r\n        CT asin_t_t01 = 0;\r\n        CT asin_t_t02 = 0;\r\n\r\n        for (int i = 0; i < 10; ++i)\r\n        {\r\n            CT const sin_beta = sin(beta);\r\n\r\n            // integrals approximation\r\n            dL1 = d_lambda_e_sqr(sin_beta1, sin_beta, C1, sqrt_1_C1_sqr, e_sqr);\r\n            dL2 = d_lambda_e_sqr(sin_beta2, sin_beta, C2, sqrt_1_C2_sqr, e_sqr);\r\n\r\n            // [Sjoberg07]\r\n            /*CT const k = k_base + dL1 - dL2;\r\n            CT const K = sin(k);\r\n            CT const d1 = sqr_t01_sqr_t02;\r\n            //CT const d2 = t01_t02_2 * math::sqrt(c1 - math::sqr(K));\r\n            CT const d2 = t01_t02_2 * cos(k);\r\n            CT const D = math::sqrt(d1 + d2_sign * d2);\r\n            CT const t_new = t_sign * K * t01_t02 / D;\r\n            CT const dt = math::abs(t_new - t);\r\n            t = t_new;\r\n            CT const new_beta = atan(t);\r\n            CT const dbeta = math::abs(new_beta - beta);\r\n            beta = new_beta;*/\r\n\r\n            // [Sjoberg02] - it converges faster\r\n            // Newton�Raphson method\r\n            asin_t_t01 = asin(t / t01);\r\n            asin_t_t02 = asin(t / t02);\r\n            CT const R1 = asin_t_t01 + dL1;\r\n            CT const R2 = asin_t_t02 + dL2;\r\n            CT const cos_beta = cos(beta);\r\n            CT const cos_beta_sqr = math::sqr(cos_beta);\r\n            CT const G = c1 - e_sqr * cos_beta_sqr;\r\n            CT const f1 = C1 / cos_beta * math::sqrt(G / (cos_beta_sqr - C1_sqr));\r\n            CT const f2 = C2 / cos_beta * math::sqrt(G / (cos_beta_sqr - C2_sqr));\r\n            CT const abs_f1 = math::abs(f1);\r\n            CT const abs_f2 = math::abs(f2);\r\n            CT const dbeta = t_sign * (k_base - R2 + R1) / (abs_f1 + abs_f2);\r\n \r\n            if (math::equals(dbeta, CT(0)))\r\n            {\r\n                break;\r\n            }\r\n\r\n            beta = beta - dbeta;\r\n            t = tan(beta);\r\n        }\r\n        \r\n        // t = tan(beta) = (1-f)tan(lat)\r\n        lat = atan(t / one_minus_f);\r\n\r\n        CT const l1 = lon1 + asin_t_t01 - asin_t1_t01 + dL1;\r\n        //CT const l2 = lon2 + asin_t_t02 - asin_t2_t02 + dL2;\r\n        lon = l1;\r\n\r\n        return true;\r\n    }\r\n\r\nprivate:\r\n    /*! Approximation of dLambda_j [Sjoberg07], expanded into taylor series in e^2\r\n        Maxima script:\r\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);\r\n        dL_j(c_j, B_j, B) := -e2 * c_j * dLI_j(c_j, B_j, B);\r\n        S: taylor(dLI_j(c_j, sinB_j, sinB), e2, 0, 3);\r\n        assume(c_j < 1);\r\n        assume(c_j > 0);\r\n        L1: factor(integrate(sqrt(-x ^ 2 - c_j ^ 2 + 1) / (x ^ 2 + c_j ^ 2 - 1), x));\r\n        L2: factor(integrate(((x ^ 2 - 1)*sqrt(-x ^ 2 - c_j ^ 2 + 1)) / (x ^ 2 + c_j ^ 2 - 1), x));\r\n        L3: factor(integrate(((x ^ 4 - 2 * x ^ 2 + 1)*sqrt(-x ^ 2 - c_j ^ 2 + 1)) / (x ^ 2 + c_j ^ 2 - 1), x));\r\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));\r\n    */\r\n    static inline CT d_lambda_e_sqr(CT const& sin_betaj, CT const& sin_beta,\r\n                                    CT const& Cj, CT const& sqrt_1_Cj_sqr,\r\n                                    CT const& e_sqr)\r\n    {\r\n        if (Order == 0)\r\n        {\r\n            return 0;\r\n        }\r\n\r\n        CT const c2 = 2;\r\n        \r\n        CT const asin_B = asin(sin_beta / sqrt_1_Cj_sqr);\r\n        CT const asin_Bj = asin(sin_betaj / sqrt_1_Cj_sqr);\r\n        CT const L0 = (asin_B - asin_Bj) / c2;\r\n\r\n        if (Order == 1)\r\n        {\r\n            return -Cj * e_sqr * L0;\r\n        }\r\n\r\n        CT const c1 = 1;\r\n        CT const c16 = 16;\r\n\r\n        CT const X = sin_beta;\r\n        CT const Xj = sin_betaj;\r\n        CT const Cj_sqr = math::sqr(Cj);\r\n        CT const Cj_sqr_plus_one = Cj_sqr + c1;\r\n        CT const one_minus_Cj_sqr = c1 - Cj_sqr;\r\n        CT const sqrt_Y = math::sqrt(-math::sqr(X) + one_minus_Cj_sqr);\r\n        CT const sqrt_Yj = math::sqrt(-math::sqr(Xj) + one_minus_Cj_sqr);\r\n        CT const L1 = (Cj_sqr_plus_one * (asin_B - asin_Bj) + X * sqrt_Y - Xj * sqrt_Yj) / c16;\r\n\r\n        if (Order == 2)\r\n        {\r\n            return -Cj * e_sqr * (L0 + e_sqr * L1);\r\n        }\r\n\r\n        CT const c3 = 3;\r\n        CT const c5 = 5;\r\n        CT const c128 = 128;\r\n\r\n        CT const E = Cj_sqr * (c3 * Cj_sqr + c2) + c3;\r\n        CT const X_sqr = math::sqr(X);\r\n        CT const Xj_sqr = math::sqr(Xj);\r\n        CT const F = X * (-c2 * X_sqr + c3 * Cj_sqr + c5);\r\n        CT const Fj = Xj * (-c2 * Xj_sqr + c3 * Cj_sqr + c5);\r\n        CT const L2 = (E * (asin_B - asin_Bj) + F * sqrt_Y - Fj * sqrt_Yj) / c128;\r\n\r\n        if (Order == 3)\r\n        {\r\n            return -Cj * e_sqr * (L0 + e_sqr * (L1 + e_sqr * L2));\r\n        }\r\n\r\n        CT const c8 = 8;\r\n        CT const c9 = 9;\r\n        CT const c10 = 10;\r\n        CT const c15 = 15;\r\n        CT const c24 = 24;\r\n        CT const c26 = 26;\r\n        CT const c33 = 33;\r\n        CT const c6144 = 6144;\r\n\r\n        CT const G = Cj_sqr * (Cj_sqr * (Cj_sqr * c15 + c9) + c9) + c15;\r\n        CT const H = -c10 * Cj_sqr - c26;\r\n        CT const I = Cj_sqr * (Cj_sqr * c15 + c24) + c33;\r\n        CT const J = X_sqr * (X * (c8 * X_sqr + H)) + X * I;\r\n        CT const Jj = Xj_sqr * (Xj * (c8 * Xj_sqr + H)) + Xj * I;\r\n        CT const L3 = (G * (asin_B - asin_Bj) + J * sqrt_Y - Jj * sqrt_Yj) / c6144;\r\n\r\n        // Order 4 and higher\r\n        return -Cj * e_sqr * (L0 + e_sqr * (L1 + e_sqr * (L2 + e_sqr * L3)));\r\n    }\r\n\r\n    static inline CT fj(CT const& cos_beta, CT const& cos2_beta, CT const& Cj, CT const& e_sqr)\r\n    {\r\n        CT const c1 = 1;\r\n        CT const Cj_sqr = math::sqr(Cj);\r\n        return Cj / cos_beta * math::sqrt((c1 - e_sqr * cos2_beta) / (cos2_beta - Cj_sqr));\r\n    }\r\n\r\n    template <int TId>\r\n    static inline bool check_t(CT const& t,\r\n                               CT const& lon_a1, CT const& asin_t_t01, CT const& asin_t1_t01,\r\n                               CT const& lon_b1, CT const& asin_t_t02, CT const& asin_t2_t02,\r\n                               CT & current_t, CT & current_lon1, CT & current_lon2, CT & current_dlon,\r\n                               int & t_id)\r\n    {\r\n        CT const lon1 = lon_a1 + asin_t_t01 - asin_t1_t01;\r\n        CT const lon2 = lon_b1 + asin_t_t02 - asin_t2_t02;\r\n\r\n        // TODO - true angle difference\r\n        CT const dlon = math::abs(lon2 - lon1);\r\n\r\n        bool are_equal = math::equals(dlon, CT(0));\r\n        \r\n        if ((TId == 0) || are_equal || dlon < current_dlon)\r\n        {\r\n            current_t = t;\r\n            current_lon1 = lon1;\r\n            current_lon2 = lon2;\r\n            current_dlon = dlon;\r\n            t_id = TId;\r\n        }\r\n\r\n        return are_equal;\r\n    }\r\n};\r\n\r\n}}} // namespace boost::geometry::formula\r\n\r\n\r\n#endif // BOOST_GEOMETRY_FORMULAS_SJOBERG_INTERSECTION_HPP\r\n", "meta": {"hexsha": "187f0e25a9418b73a3271ea5a8c66133aa1fd880", "size": 14697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/sjoberg_intersection.hpp", "max_stars_repo_name": "lucasaugustscode/veroo-delivery-app", "max_stars_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T16:14:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:17:40.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/sjoberg_intersection.hpp", "max_issues_repo_name": "lucasaugustscode/veroo-delivery-app", "max_issues_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/sjoberg_intersection.hpp", "max_forks_repo_name": "lucasaugustscode/veroo-delivery-app", "max_forks_repo_head_hexsha": "a1653525b77ac66c8dfc971163c75a731998a652", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-09T02:53:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T03:32:31.000Z", "avg_line_length": 38.0751295337, "max_line_length": 128, "alphanum_fraction": 0.5047968973, "num_tokens": 4573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694177, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5531631678632618}}
{"text": "/*\n*  @file \t\tex7.cpp\n*  @details  \tThis file is the solution to exercise 7.\n*  @author    \tAlexander Rettkowski\n*  @date      \t28.06.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 exercise5\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\texercise5::edge,\n\t(int, startNode)\n\t(int, endNode)\n\t(int, length)\n)\n\nnamespace exercise5\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 longest shortest path from node 0.\n* @param numberOfNodes Number of nodes in the graph.\n* @param graph The graph represented as a vector auf edge-vectors.\n*/\nstd::pair<int, int> dijkstra( int numberOfNodes, std::vector< std::vector< std::pair<int, int> > > graph)\n{\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>(0, 0));\n\tdistanceTo[0] = 0;\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}\n\t\t}\n\t}\n\n\tstd::pair<int, int> solution(-1, -1);\n\tfor (int i = 0; i < numberOfNodes; i++)\n\t{\n\t\tif (distanceTo[i] > solution.second)\n\t\t{\n\t\t\tsolution.second = distanceTo[i];\n\t\t\tsolution.first = i;\n\t\t}\n\t\tif ((distanceTo[i] == solution.second) && (i > solution.first))\n\t\t{\n\t\t\tsolution.first = i;\n\t\t}\n\t}\n\n\treturn solution;\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 exercise5::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 = std::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\texercise5::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\tstd::pair<int, int> solution = dijkstra(numberOfNodes, edges);\n\tint vertex = solution.first, distance = solution.second;\n\n\tstd::cout << \"RESULT VERTEX \" << vertex << std::endl;\n\tstd::cout << \"RESULT DIST \" << distance << std::endl;\n\n\ttimer::cpu_times time = boostTimer.elapsed();\n\tstd::cout << \"CPU TIME: \" << (time.user + time.system) / 1e9 << \"s\\n\";\n\tstd::cout << \"WALL CLOCK TIME: \" << time.wall / 1e9 << \"s\\n\";\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "cdf4a7eba3313297a9125d60e10b5379dca2745e", "size": 4882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rettkowski/ex7.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/ex7.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/ex7.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": 28.0574712644, "max_line_length": 123, "alphanum_fraction": 0.7011470709, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5531631610674399}}
{"text": "#ifndef _SIAR_ARM_HPP_\n#define _SIAR_ARM_HPP_\n\n\n#include \"math.h\"\n#include <functions/linear_interpolator.hpp>\n#include <string>\n#include <queue>\n#include <vector>\n#include <boost/concept_check.hpp>\n\n#define L1 0.0475\n#define L2 0.215\n#define L3 0.155\n#define L4 0.080\n#include \"siar_functions.hpp\"\n\n\nclass SiarArm{\n\n  public:\n    \n    // Linear interpolators data\n  int n_motors;\n  std::vector<functions::LinearInterpolator *> pos_mot_interpol_, mot_pos_interpol_;\n  std::vector<double> length;\n  \n  SiarArm(const std::string &mot_arm_file, const std::string &pos_arm_file) {\n    load_data(mot_arm_file, pos_arm_file);\n  }\n  \n  bool load_data(const std::string &mot_arm_file, const std::string &pos_arm_file) {\n    n_motors = 5;\n    for (int i = 0; i < n_motors; i++) {\n      std::ostringstream mot_arm, pos_arm;\n      mot_arm << mot_arm_file << i;\n      pos_arm << pos_arm_file << i;\n      pos_mot_interpol_.push_back(new functions::LinearInterpolator(mot_arm.str(), pos_arm.str()));\n    }\n    length.push_back(0.035); // TODO: read it from file?\n    length.push_back(0.186);\n    length.push_back(0.140);\n    length.push_back(0.0651);\n    length.push_back(0.04297);\n    \n  }\n  \n  ~SiarArm() {\n    for(int i = 0; i < pos_mot_interpol_; i++) {\n      delete pos_mot_interpol_[i];\n    }\n    for(int i = 0; i < mot_pos_interpol_; i++) {\n      delete mot_pos_interpol_[i];\n    }\n  }\n    \n  bool inverseKinematics(double x, double y, double z, std::vector <double> &result)\n  {\n    bool coordenadas_correctas = true;\n\n    // a1 = atan2(Z,X)\n\n// a3 = acos(Z^2+X^2+(Y-L1)^2-L2^2-L3^2)\n\n// d = sqrt(L2^2 + L3^2 -2*L2*L3*cos(a3))\n\n// a2 = acos((y-L1)/d)\n\n// donde L1 = 35.06; L2 = 186; L3 =140.05\n\n// a1,2,3 son los ángulos de la primera, segunda y tercera articulación.\n\n    \n    result[0] = atan2(z, x);\n    result[2] = acos(z*z+ x*x + pow(y-length[0],2.0) - length[2]*length[2] - length[3]*length[3]);\n    double d = sqrt(length[1]*length[1] + length[2]*length[2] - 2.0 * length[1] * length[2] * cos(result[2]);\n    result[1] = acos((y - length[0])/d;\n    //ROS_INFO(\"x: %f; y: %f;z: %f\",x,y,z);\n    //ROS_INFO(\"q1: %f, q2: %f, q3: %f, q4: %f, q5:%f\",q1,q2,q3,q4,q5);\n  }\n  \n  void rad2motor(const std::vector<double> &angles, std::vector<int> &commands) {\n    commands.resize(n_motors);\n    for (int i = 0; i < n_motors; i++) {\n      functions::LinearInterpolator &interpol = *pos_mot_interpol_[i];\n      commands[i] = interpol(angles[i]);\n    }\n  }\n\n  void motor2rad(const std::vector<int> &commands, std::vector<double> &angles) {\n    angles.resize(n_motors);\n    for (int i = 0; i < n_motors; i++) {\n      functions::LinearInterpolator &interpol = *mot_pos_interpol_[i];\n      angles[i] = interpol(commands[i]);\n    }\n  }\n  \n  void forwardKinematics(const std::vector  <int> &joint_values, double &x, double &y, double &z)\n  {\n    \n//       X = cos(a1) *(L2*sin(a2)+L3*sin(a2+a3))\n// Y = L1 + (L2*cos(a2)+L3*cos(a2+a3))\n// Z = -1 * sin(a1) *(L2*sin(a2)+L3*sin(a2+a3))\n// Donde Y es positiva desde la base en dirección a la primera articulación, X es ortogonal  a Y en el plano proyectado por el dibujo y Z va desde el plano hacia dentro.\n\n    std::vector<double> angles;\n    motor2rad(joint_values, angles);\n    double a1 = joint_values[0];\n    double a2 = joint_values[1];\n    double a3 = joint_values[2];\n    double L1 = length[0];\n    double L2 = length[1];\n    double L3 = length[2];\n    x = cos(a1) * (L2*sin(a2) + L3*sin(a2 + a3));\n    y = L1 + L2*cos(a2) + L3*cos(a2 + a3);\n    z = -sin(a1) * (L2*sin(a2) + L3*sin(a2 + a3));\n  }\n\n  std::vector<std::vector<int> > straightInterpol(double x, double y, double z, uint8_t n_points, const std::vector<int> &curr_pos)\n  {\n    doble a_x, a_y, a_z;\n    forwardKinematics(curr_pos, a_x, a_y, a_z);\n    doble i_x, i_y, i_z;  \n    i_x = (x - a_x)/(n_points+1);\t  \n    i_y = (y - a_y)/(n_points+1);\n    i_z = (z - a_z)/(n_points+1);\n    \n    std::vector<std::vector<int> > ret;\n    \n    std::vector<double> angles;\n    std::vector<int> commands;\n    for( int i = 0; i < n_points+1; i++)\t\n    {\t\n      a_x += i_x;\n      a_y += i_y;\n      a_z += i_z;\n      \t\t      \n      inverseKinematics(a_x, a_y, a_z, angles);\n      rad2motor(angles, commands);\n      ret.push_back(commands);\n    }\n\n  }\n  \n  bool checkJointLimits(const boost::array<int16_t, 5> joint_values)\n  {\n    bool ret_val = true;\n    \n    for (int i = 0; i < n_motors && ret_val; i++) {\n      double max, min;\n      functions::LinearInterpolator &curr_inter = *mot_pos_interpol_[i];\n      min = curr_inter.upper_bound(0);\n      max = curr_inter.lower_bound(2000); // Usually the commands are in the [0, 2000] range\n       \n      ret_val &= joint_values[i] > min && joint_values[i] < max;\n      \n    }\n    \n    return ret_val;\n  }\n\n  bool checkTemperatureAndStatus(const boost::array<uint8_t,5> &herculex_temperature, const boost::array<uint8_t,5> &herculex_status) {\n    bool ret_val = true;\n    for(int i = 0; i < 5; i++)\n    {\n      if (herculex_temperature[i]<0 && herculex_temperature[i]>50)\n      {\n        ROS_ERROR(\"TEMPERATURE OF THE %d LINK IS OUT OF RANGE: %d\", i, herculex_temperature[i]);\n        ret_val = false;\n      }\n//       if (herculex_status[i]!=1)    // TODO: Check this!!\n//       {\n//         ROS_ERROR(\"%d LINK STATUS: %d\", i, herculex_status[i]);\n//         ret_val = false;\n//       }\n    }\n    return ret_val;  \n  }\n  \n};\n#endif /* _SIAR_ARM_H_ */\n", "meta": {"hexsha": "cacce1fbc8e429f95e78b538a2176d5a0d697cc4", "size": 5379, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "siar_driver/include/siar_driver/siar_arm.hpp", "max_stars_repo_name": "robotics-upo/siar_packages", "max_stars_repo_head_hexsha": "2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T08:52:23.000Z", "max_issues_repo_path": "siar_driver/include/siar_driver/siar_arm.hpp", "max_issues_repo_name": "robotics-upo/siar_packages", "max_issues_repo_head_hexsha": "2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "siar_driver/include/siar_driver/siar_arm.hpp", "max_forks_repo_name": "robotics-upo/siar_packages", "max_forks_repo_head_hexsha": "2b9b3e7acbc9bc5845b03d63eb18dbc50bfd3c98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-20T16:08:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-22T04:26:12.000Z", "avg_line_length": 29.5549450549, "max_line_length": 169, "alphanum_fraction": 0.6055028816, "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.5531196384686186}}
{"text": "#pragma once\n\n// deal.II includes ------------------------------------------------------------\n#include <deal.II/base/numbers.h>\n#include <deal.II/base/tensor.h>\n//#include <deal.II/base/quadrature_lib.h>\n// system includes -------------------------------------------------------------\n#include <map>\n// own includes ----------------------------------------------------------------\n#include <quadrature/trig_int.hpp>\n\n\nnamespace boltzmann {\n\nnamespace local_ {\n// ----------------------------------------------------------------------\ninline bool\nis_zero(const dealii::Tensor<2, 2, double>& t2)\n{\n  const double tol = 1e-16;\n  return std::abs(t2[0][0]) < tol && std::abs(t2[0][1]) < tol && std::abs(t2[1][0]) < tol &&\n         std::abs(t2[1][1]) < tol;\n}\n\n// ----------------------------------------------------------------------\ninline bool\nis_zero(const dealii::Tensor<1, 2, double>& t1)\n{\n  const double tol = 1e-16;\n  return std::abs(t1[0]) < tol && std::abs(t1[1]) < tol;\n}\n\n}  // end namespace local_\n\ntemplate <int DIM>\nclass VelocityAngularIntegrator;\n\n/**\n * @brief helper class for system matrix assembly\n *\n */\ntemplate <>\nclass VelocityAngularIntegrator<2>\n{\n public:\n  typedef double numeric_t;\n  typedef dealii::Tensor<2, 2, numeric_t> T2_t;\n  typedef dealii::Tensor<1, 2, numeric_t> T1_t;\n  typedef std::pair<unsigned int, unsigned int> key_t;\n\n private:\n  typedef std::map<key_t, numeric_t> map_S0_t;\n  typedef std::map<key_t, T1_t> map_T1_t;\n  typedef std::map<key_t, T2_t> map_T2_t;\n\n public:\n  VelocityAngularIntegrator() { /* empty */}\n  template <typename BASIS>\n  void init(const BASIS& angular_basis);\n\n  map_S0_t::const_iterator begin_s0() const;\n  map_S0_t::const_iterator end_s0() const;\n  map_T1_t::const_iterator begin_t1() const;\n  map_T1_t::const_iterator end_t1() const;\n  map_T2_t::const_iterator begin_t2() const;\n  map_T2_t::const_iterator end_t2() const;\n\n  const map_S0_t& get_s0() const { return ms0; }\n  const map_T1_t& get_s1() const { return mt1; }\n  const map_T1_t& get_t1() const { return mt1; }\n  const map_T2_t& get_t2() const { return mt2; }\n\n  //  void write_to_file(std::string fname) const;\n private:\n  map_S0_t ms0;\n  map_T1_t mt1;\n  map_T2_t mt2;\n};\n\n// ---------------------------------------------------------------------------\ntemplate <typename BASIS>\nvoid\nVelocityAngularIntegrator<2>::init(const BASIS& angular_basis)\n{\n  auto make_t1 = [](int l1, int t1, int l2, int t2) {\n    T1_t m1;\n    m1[0] = trig_int(COS, 1, {(TRIG)t1, (TRIG)t2}, {l1, l2});\n    m1[1] = trig_int(SIN, 1, {(TRIG)t1, (TRIG)t2}, {l1, l2});\n    return m1;\n  };\n\n  auto make_t2 = [](int l1, int t1, int l2, int t2) {\n    T2_t m2;\n    for (int tp = 0; tp < 2; ++tp) {\n      for (int t = 0; t < 2; ++t) {\n        m2[tp][t] = trig_int((TRIG)tp, 1, {(TRIG)t, (TRIG)t1, (TRIG)t2}, {1, l1, l2});\n      }\n    }\n    return m2;\n  };\n\n  for (auto it1 = angular_basis.begin(); it1 != angular_basis.end(); ++it1) {\n    int l1 = it1->get_id().l;\n    int t1 = it1->get_id().t;\n    unsigned int ix1 = it1 - angular_basis.begin();\n    for (auto it2 = angular_basis.begin(); it2 != angular_basis.end(); ++it2) {\n      int l2 = it2->get_id().l;\n      int t2 = it2->get_id().t;\n      unsigned int ix2 = it2 - angular_basis.begin();\n      // S0\n      double s0 = trig_int((TRIG)t1, l1, {(TRIG)t2}, {l2});\n      if (std::abs(s0) > 1e-16) ms0[std::make_pair(ix1, ix2)] = s0;\n      // T1\n      T1_t m1 = make_t1(l1, t1, l2, t2);\n      if (!local_::is_zero(m1)) mt1[std::make_pair(ix1, ix2)] = m1;\n      // T2\n      T2_t m2 = make_t2(l1, t1, l2, t2);\n      if (!local_::is_zero(m2)) mt2[std::make_pair(ix1, ix2)] = m2;\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "25a9ffc82f25ada4cc623449a033913859a928ea", "size": 3663, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/assembly/velocity_angular_integrator.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_angular_integrator.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_angular_integrator.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": 29.5403225806, "max_line_length": 92, "alphanum_fraction": 0.5561015561, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.5531196176133751}}
{"text": "/**\n * @file   main_advection_dir.cpp\n * @author Simon Pintarelli <simon@thinkpadX1>\n * @date   Wed Mar 30 18:30:47 2016\n *\n * @brief  solve advection equation separately for each direction (quad points)\n *\n *\n */\n\n// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <base/timer.hpp>\n#include <fft/fft2.hpp>\n#include <fft/fft2_r2c.hpp>\n#include <ridgelet/init_fftw.hpp>\n#include <ridgelet/ridgelet_cell_array.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\n#include <omp.h>\n#include <operators/operators.hpp>\n#include <solver/cg.hpp>\n#include <solver/ridgelet_solver.hpp>\n#include <spectral/quadrature/gauss_hermite_roots.hpp>\n\nusing namespace std;\ntypedef FFTr2c<PlannerR2C> fft_t;\n// TODO: check if RT coeffs are real valued in this case\ntypedef RT<double, RidgeletFrame, fft_t> RT_t;\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int Jx, Jy, rho_x, rho_y;\n  double dt;\n  unsigned int f;\n  int K;\n\n  unsigned int cg_maxit;\n  double cg_reltol;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(3), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(3), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"dt,t\", po::value<double>(&dt)->default_value(0.1), \"dt\")\n      (\"deg,K\", po::value<int>(&K)->default_value(10), \"poly. deg.\")\n      (\"f\", po::value<unsigned int>(&f)->default_value(2), \"grid out factor\")\n      (\"maxiter\", po::value<unsigned int>(&cg_maxit)->default_value(40), \"cg::maxiter\")\n      (\"reltol\", po::value<double>(&cg_reltol)->default_value(1e-4), \"cg::reltol\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << \"CMD::\";\n  for (int i = 0; i < argc; ++i) {\n    cout << argv[i] << \" \";\n  }\n  cout << \"\\n\";\n\n  cout << setw(20) << \"Jx\"\n       << \": \" << Jx << \"\\n\"\n       << setw(20) << \"Jy\"\n       << \": \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x\"\n       << \": \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y\"\n       << \": \" << rho_y << \"\\n\"\n       << setw(20) << \"K\"\n       << \": \" << K << \"\\n\"\n       << setw(20) << \"dt\"\n       << \": \" << dt << \"\\n\";\n\n  RidgeletFrame rf(Jx, Jy, rho_x, rho_y);\n  const unsigned int Nx = rf.Nx();  // #cols\n  const unsigned int Ny = rf.Ny();  // #rows\n  cout << \"Nx: \" << Nx << \"\\n\";\n  cout << \"Ny: \" << Ny << \"\\n\";\n\n  fft_t fft;\n  init_fftw(fft, FFTW_MEASURE, rf);\n  fft.get_plan().create_and_get_plan(f * Ny, f * Nx, PlannerR2C::INV);\n  fft.get_plan().create_and_get_plan(f * Ny, f * Nx, PlannerR2C::FWD);\n\n  std::vector<double> vi(K);\n  boltzmann::gauss_hermite_roots(vi, K);\n\n  Eigen::ArrayXd xi = Eigen::ArrayXd::LinSpaced(Nx + 1, 0, 1).segment(0, Nx);\n  Eigen::ArrayXd yi = Eigen::ArrayXd::LinSpaced(Ny + 1, 0, 1).segment(0, Ny);\n\n  array_t F =\n      (xi.transpose().replicate(Ny, 1)).binaryExpr(yi.replicate(1, Nx), [](double x, double y) {\n        return std::exp(-300 * (std::pow(x - 0.5, 2) + std::pow(y - 0.5, 2)));\n      });\n\n  RT_t rt(rf);\n\n  complex_array_t Fh(Ny, Nx);\n  fft.ft(Fh, F, false);\n  typedef RidgeletCellArray<rt_coeff_t> rca_t;\n  rca_t rt_cell_array(rf);\n  auto& rt_coeffs = rt_cell_array.coeffs();\n  rt.rt(rt_coeffs, Fh);\n\n  hid_t file = H5Fcreate(\"advection_dir.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  cout << \"write results to `advection_dir.h5`\"\n       << \"\\n\";\n  cout << \"max thread: \" << omp_get_max_threads() << \"\\n\";\n  cout << \"RT_SOLVER::tol  : \" << cg_reltol << \"\\n\";\n  cout << \"RT_SOLVER::maxit: \" << cg_maxit << \"\\n\";\n\n  eigen2hdf::save(file, \"F\", F);\n  eigen2hdf::save(file, \"Fh\", Fh);\n  cout << \"dt:\" << dt << \"\\n\";\n  const double Lx = 1;\n  const double Ly = 1;\n\n  Eigen::MatrixXi ITER_MAT(K, K);\n  Eigen::MatrixXd RELRES_MAT(K, K);  // rel. residual\n  Eigen::MatrixXd TIME_MAT(K, K);    // [GCycle]\n\n#pragma omp parallel for\n  for (int qx = 0; qx < K; ++qx) {\n    for (int qy = 0; qy < K; ++qy) {\n      const double vx = vi[qx];\n      const double vy = vi[qy];\n      AhAOp AhA(vx, vy, Lx, Ly, Nx, Ny, dt);\n      // preconditioned operator\n      RDTSCTimer timer;\n\n      PTransportOp<RT_t> A(rt, AhA, vx, vy);\n      TransportOperator T(vx, vy, Lx, Ly, Nx, Ny, dt);  // required for rhs\n      // T'*Fh\n      complex_array_t Bh(Ny, Nx);\n      T.apply(Bh, Fh, true /* hermitian transpose */);\n      rca_t b(rf);\n      rt.rt(b.coeffs(), Bh);\n      RidgeletSolver<rt_coeff_t> rt_solver(rf, vx, vy);\n      rca_t x(rf);\n      x.resize(rt_cell_array);\n      x = rt_cell_array;\n      timer.start();\n      rt_solver.solve(x, A, b, cg_reltol, cg_maxit);\n      auto nc_solve = timer.stop();\n\n      RELRES_MAT(qx, qy) = rt_solver.relres();\n      ITER_MAT(qx, qy) = rt_solver.iter();\n      TIME_MAT(qx, qy) = nc_solve / 1e9;\n\n      // #pragma omp critical\n      //       {\n      //         cout << \"vx: \" << vx << \"\\n\";\n      //         cout << \"vy: \" << vy << \"\\n\";\n      //         cout << \"RidgeletSolver took: \" << nc_solve / 1e9 << \" Gcycles\\n\";\n      //         cout << \"cg::relres: \" << rt_solver.relres() << \"\\n\";\n      //         cout << \"cg::iter: \" << rt_solver.iter() << \"\\n\\n\";\n      //       }\n      // write arrays to hdf5\n      complex_array_t tmp(Ny, Nx);\n      rt.irt(tmp, x.coeffs());\n      array_t sol(f * Ny, f * Nx);\n      complex_array_t solh(f * Ny, f * Nx);\n      solh.setZero();\n      ftcut(solh, Ny / 2, Nx / 2) = ftcut(tmp, Ny / 2, Nx / 2);\n      // ftcut(solh, Ny, Nx) = tmp;\n      fft.ift(sol, solh);\n      char buf[256];\n      std::sprintf(buf, \"%d_%d\", qx, qy);\n#pragma omp critical\n      {\n        hid_t group = H5Gcreate(file, buf, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n        eigen2hdf::save(group, \"sol\", sol);\n        eigen2hdf::save(group, \"solh_ftcut\", solh);\n        eigen2hdf::save(group, \"solh\", tmp);\n        H5Gclose(group);\n      }\n    }\n  }\n\n  eigen2hdf::save(file, \"cg_relres\", RELRES_MAT);\n  eigen2hdf::save(file, \"cg_iter\", ITER_MAT);\n  eigen2hdf::save(file, \"cg_time\", TIME_MAT);\n\n  H5Fclose(file);\n\n  return 0;\n}\n", "meta": {"hexsha": "67295c2a540e0e9d4e2782d5ab81b4aef3d2f8c1", "size": 6587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/phase_space/main_advection_dir.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/phase_space/main_advection_dir.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/phase_space/main_advection_dir.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": 31.8212560386, "max_line_length": 96, "alphanum_fraction": 0.5726430849, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.5530672278085295}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*!\n Copyright (C) 2005, 2006, 2007, 2009 StatPro Italia srl\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// 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#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\n\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        // set up dates\n        Calendar calendar = TARGET();\n        Date todaysDate(15, May, 1998);\n        Date settlementDate(17, May, 1998);\n        Settings::instance().evaluationDate() = todaysDate;\n\n        // our options\n        Option::Type type(Option::Put);\n        Real underlying = 36;\n        Real strike = 40;\n        Spread dividendYield = 0.00;\n        Rate riskFreeRate = 0.06;\n        Volatility volatility = 0.20;\n        Date maturity(17, May, 1999);\n        DayCounter dayCounter = Actual365Fixed();\n\n        std::cout << \"Option type = \"  << type << std::endl;\n        std::cout << \"Maturity = \"        << maturity << std::endl;\n        std::cout << \"Underlying price = \"        << underlying << std::endl;\n        std::cout << \"Strike = \"                  << strike << std::endl;\n        std::cout << \"Risk-free interest rate = \" << io::rate(riskFreeRate)\n                  << std::endl;\n        std::cout << \"Dividend yield = \" << io::rate(dividendYield)\n                  << std::endl;\n        std::cout << \"Volatility = \" << io::volatility(volatility)\n                  << std::endl;\n        std::cout << std::endl;\n        std::string method;\n        std::cout << std::endl ;\n\n        // write column headings\n        Size widths[] = { 35, 14, 14, 14 };\n        std::cout << std::setw(widths[0]) << std::left << \"Method\"\n                  << std::setw(widths[1]) << std::left << \"European\"\n                  << std::setw(widths[2]) << std::left << \"Bermudan\"\n                  << std::setw(widths[3]) << std::left << \"American\"\n                  << std::endl;\n\n        std::vector<Date> exerciseDates;\n        for (Integer i=1; i<=4; i++)\n            exerciseDates.push_back(settlementDate + 3*i*Months);\n\n        boost::shared_ptr<Exercise> europeanExercise(\n                                         new EuropeanExercise(maturity));\n\n        boost::shared_ptr<Exercise> bermudanExercise(\n                                         new BermudanExercise(exerciseDates));\n\n        boost::shared_ptr<Exercise> americanExercise(\n                                         new AmericanExercise(settlementDate,\n                                                              maturity));\n\n        Handle<Quote> underlyingH(\n            boost::shared_ptr<Quote>(new SimpleQuote(underlying)));\n\n        // bootstrap the yield/dividend/vol curves\n        Handle<YieldTermStructure> flatTermStructure(\n            boost::shared_ptr<YieldTermStructure>(\n                new FlatForward(settlementDate, riskFreeRate, dayCounter)));\n        Handle<YieldTermStructure> flatDividendTS(\n            boost::shared_ptr<YieldTermStructure>(\n                new FlatForward(settlementDate, dividendYield, dayCounter)));\n        Handle<BlackVolTermStructure> flatVolTS(\n            boost::shared_ptr<BlackVolTermStructure>(\n                new BlackConstantVol(settlementDate, calendar, volatility,\n                                     dayCounter)));\n        boost::shared_ptr<StrikedTypePayoff> payoff(\n                                        new PlainVanillaPayoff(type, strike));\n        boost::shared_ptr<BlackScholesMertonProcess> bsmProcess(\n                 new BlackScholesMertonProcess(underlyingH, flatDividendTS,\n                                               flatTermStructure, flatVolTS));\n\n        // options\n        VanillaOption europeanOption(payoff, europeanExercise);\n        VanillaOption bermudanOption(payoff, bermudanExercise);\n        VanillaOption americanOption(payoff, americanExercise);\n\n        // Analytic formulas:\n\n        // Black-Scholes for European\n        method = \"Black-Scholes\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                     new AnalyticEuropeanEngine(bsmProcess)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // semi-analytic Heston for European\n        method = \"Heston semi-analytic\";\n        boost::shared_ptr<HestonProcess> hestonProcess(\n            new HestonProcess(flatTermStructure, flatDividendTS,\n                              underlyingH, volatility*volatility,\n                              1.0, volatility*volatility, 0.001, 0.0));\n        boost::shared_ptr<HestonModel> hestonModel(\n                                              new HestonModel(hestonProcess));\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                     new AnalyticHestonEngine(hestonModel)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // semi-analytic Bates for European\n        method = \"Bates semi-analytic\";\n        boost::shared_ptr<BatesProcess> batesProcess(\n            new BatesProcess(flatTermStructure, flatDividendTS,\n                             underlyingH, volatility*volatility,\n                             1.0, volatility*volatility, 0.001, 0.0,\n                             1e-14, 1e-14, 1e-14));\n        boost::shared_ptr<BatesModel> batesModel(new BatesModel(batesProcess));\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                                new BatesEngine(batesModel)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // Barone-Adesi and Whaley approximation for American\n        method = \"Barone-Adesi/Whaley\";\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                       new BaroneAdesiWhaleyApproximationEngine(bsmProcess)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << \"N/A\"\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Bjerksund and Stensland approximation for American\n        method = \"Bjerksund/Stensland\";\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BjerksundStenslandApproximationEngine(bsmProcess)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << \"N/A\"\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Integral\n        method = \"Integral\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                                             new IntegralEngine(bsmProcess)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // Finite differences\n        Size timeSteps = 801;\n        method = \"Finite differences\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                 new FDEuropeanEngine<CrankNicolson>(bsmProcess,\n                                                     timeSteps,timeSteps-1)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                 new FDBermudanEngine<CrankNicolson>(bsmProcess,\n                                                     timeSteps,timeSteps-1)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                 new FDAmericanEngine<CrankNicolson>(bsmProcess,\n                                                     timeSteps,timeSteps-1)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Jarrow-Rudd\n        method = \"Binomial Jarrow-Rudd\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<JarrowRudd>(bsmProcess,timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<JarrowRudd>(bsmProcess,timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<JarrowRudd>(bsmProcess,timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n        method = \"Binomial Cox-Ross-Rubinstein\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<CoxRossRubinstein>(bsmProcess,\n                                                                   timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<CoxRossRubinstein>(bsmProcess,\n                                                                   timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<CoxRossRubinstein>(bsmProcess,\n                                                                   timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Additive equiprobabilities\n        method = \"Additive equiprobabilities\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<AdditiveEQPBinomialTree>(bsmProcess,\n                                                                   timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<AdditiveEQPBinomialTree>(bsmProcess,\n                                                                   timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<AdditiveEQPBinomialTree>(bsmProcess,\n                                                                   timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Binomial Trigeorgis\n        method = \"Binomial Trigeorgis\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<Trigeorgis>(bsmProcess,timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<Trigeorgis>(bsmProcess,timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                new BinomialVanillaEngine<Trigeorgis>(bsmProcess,timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Binomial Tian\n        method = \"Binomial Tian\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<Tian>(bsmProcess,timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<Tian>(bsmProcess,timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                      new BinomialVanillaEngine<Tian>(bsmProcess,timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Binomial Leisen-Reimer\n        method = \"Binomial Leisen-Reimer\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n              new BinomialVanillaEngine<LeisenReimer>(bsmProcess,timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n              new BinomialVanillaEngine<LeisenReimer>(bsmProcess,timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n              new BinomialVanillaEngine<LeisenReimer>(bsmProcess,timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Binomial method: Binomial Joshi\n        method = \"Binomial Joshi\";\n        europeanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                    new BinomialVanillaEngine<Joshi4>(bsmProcess,timeSteps)));\n        bermudanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                    new BinomialVanillaEngine<Joshi4>(bsmProcess,timeSteps)));\n        americanOption.setPricingEngine(boost::shared_ptr<PricingEngine>(\n                    new BinomialVanillaEngine<Joshi4>(bsmProcess,timeSteps)));\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << bermudanOption.NPV()\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // Monte Carlo Method: MC (crude)\n        timeSteps = 1;\n        method = \"MC (crude)\";\n        Size mcSeed = 42;\n        boost::shared_ptr<PricingEngine> mcengine1;\n        mcengine1 = MakeMCEuropeanEngine<PseudoRandom>(bsmProcess)\n            .withSteps(timeSteps)\n            .withAbsoluteTolerance(0.02)\n            .withSeed(mcSeed);\n        europeanOption.setPricingEngine(mcengine1);\n        // Real errorEstimate = europeanOption.errorEstimate();\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // Monte Carlo Method: QMC (Sobol)\n        method = \"QMC (Sobol)\";\n        Size nSamples = 32768;  // 2^15\n\n        boost::shared_ptr<PricingEngine> mcengine2;\n        mcengine2 = MakeMCEuropeanEngine<LowDiscrepancy>(bsmProcess)\n            .withSteps(timeSteps)\n            .withSamples(nSamples);\n        europeanOption.setPricingEngine(mcengine2);\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << europeanOption.NPV()\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << \"N/A\"\n                  << std::endl;\n\n        // Monte Carlo Method: MC (Longstaff Schwartz)\n        method = \"MC (Longstaff Schwartz)\";\n        boost::shared_ptr<PricingEngine> mcengine3;\n        mcengine3 = MakeMCAmericanEngine<PseudoRandom>(bsmProcess)\n            .withSteps(100)\n            .withAntitheticVariate()\n            .withCalibrationSamples(4096)\n            .withAbsoluteTolerance(0.02)\n            .withSeed(mcSeed);\n        americanOption.setPricingEngine(mcengine3);\n        std::cout << std::setw(widths[0]) << std::left << method\n                  << std::fixed\n                  << std::setw(widths[1]) << std::left << \"N/A\"\n                  << std::setw(widths[2]) << std::left << \"N/A\"\n                  << std::setw(widths[3]) << std::left << americanOption.NPV()\n                  << std::endl;\n\n        // End test\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        return 0;\n\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": "1015e877b6b01e2dc02357882663e5e1c2add537", "size": 20271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/Examples/EquityOption/EquityOption.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/EquityOption/EquityOption.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/EquityOption/EquityOption.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": 48.8457831325, "max_line_length": 80, "alphanum_fraction": 0.5478762765, "num_tokens": 4743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.5530513460097476}}
{"text": "/** MIT License\n\nCopyright (c) 2018 Benjamin Bercovici and Jay McMahon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/**\n * @file   RigidBodyKinematics.hpp\n * @Author Benjamin Bercovici (bebe0705@colorado.edu)\n * @date   July, 2017\n * @brief  Header of the RigidBodyKinematics libary\n *\n * Rigid Body Kinematics library implementating a handful of useful rigid body routines\n */\n\n\n#ifndef RIGIDBODYKINEMATICS_HPP\n#define RIGIDBODYKINEMATICS_HPP\n\n#include <armadillo>\n\nnamespace RBK {\n\n\n/**\nConverts MRP to DCM\n@param sigma MRP vector\n@return dcm DCM matrix\n*/\n\tarma::mat::fixed<3,3> mrp_to_dcm(const arma::vec::fixed<3> & mrp);\n\n/**\nConverts DCM to MRP.\n@param dcm DCM\n@param short_rot True if short rotation is desired (default), false otherwise\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> dcm_to_mrp(const arma::mat::fixed<3,3> & dcm, const bool short_rot = true);\n\n/**\nConverts Quaternions to MRP.\n@param Q Unit Quaternion\n@param short_rot True if short rotation is desired (default), false otherwise\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> quat_to_mrp(const arma::vec::fixed<4> & Q , const bool short_rot = true);\n\n/**\nConverts a set of 321 Euler angles to DCM\n@param euler_angles 321 sequence of Euler angles (rad)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> euler321_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nConverts a set of (longitude,latitude) angles to DCM\n@param (longitude,latitude) angles (rad)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> longitude_latitude_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nConverts a set of 321 Euler angles to mrp\n@param euler_angles 321 sequence of Euler angles (rad)\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> euler321_to_mrp(const arma::vec::fixed<3> & euler_angles);\n\n/**\nComputes the time derivative of the attitude set\nassuming torque free rotational dynamics and MRP as attitude coordinate\n@param[in] t Current time\n@param[in] attitude_set mrp + angular velocities\n@param[in] inertia inertia matrix\n@param[in] L external torque (defaults to (0,0,0))\n@return time derivative of the input attitude set\n*/\n\tarma::vec::fixed<6> dXattitudedt(double t, const arma::vec::fixed<6> & attitude_set, const arma::mat::fixed<3,3> & inertia,\n\t\tconst arma::vec::fixed<3> & L = arma::zeros<arma::vec>(3)) ;\n\n/**\nComputes the time derivative of the angular velocity set\n@param[in] t Current time\n@param[in] attitude_set mrp + angular velocities\n@param[in] inertia inertia matrix\n@param[in] L external torque (defaults to (0,0,0))\n@return time derivative of the input angular velocity\n*/\n\tarma::vec::fixed<3> domegadt(double t, \n\t\tconst arma::vec::fixed<6> & attitude_set, \n\t\tconst arma::mat::fixed<3,3> & inertia,\n\t\tconst arma::vec::fixed<3> & L = arma::zeros<arma::vec>(3)) ;\n\n/**\nComputes the time derivative of a mrp set given\na corresponding angular velocity\n@param t Current time\n@param attitude_set mrp + angular velocities\n@return time derivative of the input mrp\n*/\n\tarma::vec::fixed<3> dmrpdt(double t, const arma::vec::fixed<6> & attitude_set );\n\n\n/**\nReturns the shadow set of the input mrp if crossing\nsurface is reached\n@param mrp MRP set\n@param force_switch if true, will force the switching of the MRP to its shadow without checking its norm\n@return mrp or its shadow set\n\n*/\n\tarma::vec::fixed<3> shadow_mrp(const arma::vec::fixed<3> & mrp, bool force_switch = false) ;\n\n\n/**\nConverts MRP to quaternions\n@param sigma MRP vector\n@return quat Unit quaternion\n*/\n\tarma::vec::fixed<4> mrp_to_quat(const arma::vec::fixed<3> & mrp);\n\n\n/**\nConverts a set of 321 Euler angles to DCM\n@param euler_angles 321 sequence of Euler angles (deg)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> euler321d_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n/**\nConverts a set of 321 Euler angles to mrp\n@param euler_angles 321 sequence of Euler angles (deg)\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> euler321d_to_mrp(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nConverts a set of 313 Euler angles to DCM\n@param euler_angles 313 sequence of Euler angles (deg)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> euler313d_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n/**\nConverts a set of 313 Euler angles to mrp\n@param euler_angles 313 sequence of Euler angles (deg)\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> euler313d_to_mrp(const arma::vec::fixed<3> & euler_angles);\n\n/**\nConverts a set of 321 Euler angles expressed in degrees to DCM\n@param euler_angles 321 sequence of Euler angles (deg)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> euler321d_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n/**\nConverts a set of 321 Euler angles expressed in degrees to mrp\n@param euler_angles 321 sequence of Euler angles (deg)\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> euler321d_to_mrp(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nConverts a set of 313 Euler angles to mrp\n@param euler_angles 313 sequence of Euler angles (rad)\n@return mrp MRP set\n*/\n\tarma::vec::fixed<3> euler313_to_mrp(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nConverts a set of 313 Euler angles to DCM\n@param euler_angles 313 sequence of Euler angles (rad)\n@return dcm DCM\n*/\n\tarma::mat::fixed<3,3> euler313_to_dcm(const arma::vec::fixed<3> & euler_angles);\n\n\n/**\nReturns the matrix tilde[x] of the linear operator v|---> cross(x,v)\n@param vec 3-by-1 vector\n@return M Skew-symmetric matrix of the said linear operator\n*/\n\tarma::mat::fixed<3,3> tilde(const arma::vec::fixed<3> & vec);\n\n/**\nMatrix of the elemental rotation about the first axis of the current frame\n@param angle Rotation angle (rad)\n@return M Elemental rotation matrix\n*/\n\tarma::mat::fixed<3,3> M1(const double angle);\n\n/**\nMatrix of the elemental rotation about the second axis of the current frame\n@param angle Rotation angle (rad)\n@return M Elemental rotation matrix\n*/\n\tarma::mat::fixed<3,3> M2(const double angle);\n\n/**\nMatrix of the elemental rotation about the third axis of the current frame\n@param angle Rotation angle (rad)\n@return M Elemental rotation matrix\n*/\n\tarma::mat::fixed<3,3> M3(const double angle);\n\n/**\nConverts a DCM to the corresponding set of Euler angles\n@param m DCM\n@return angles Sequence of 321 Euler angles angles [yaw,pitch,roll]\n*/\n\tarma::vec::fixed<3> dcm_to_euler321(const arma::mat::fixed<3,3> & dcm);\n\n/**\nConverts a DCM to the corresponding set of Euler angles\n@param m DCM\n@return angles Sequence of 313 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> dcm_to_euler313(const arma::mat::fixed<3,3> & dcm);\n\n/**\nConverts a MRP to the corresponding set of Euler angles\n@param sigma MRP vector\n@return angles Sequence of 313 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> mrp_to_euler313(const arma::vec::fixed<3> & mrp);\n\n/**\nConverts a MRP to the corresponding set of Euler angles\n@param sigma MRP vector\n@return angles Sequence of 321 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> mrp_to_euler321(const arma::vec::fixed<3> & mrp);\n\n/**\nConverts a DCM to the corresponding set of Euler angles in degrees\n@param m DCM\n@return angles Sequence of 321 Euler angles angles [yaw,pitch,roll]\n*/\n\tarma::vec::fixed<3> dcm_to_euler321d(const arma::mat::fixed<3,3> & dcm);\n\n/**\nConverts a DCM to the corresponding set of Euler angles in degrees\n@param m DCM\n@return angles Sequence of 313 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> dcm_to_euler313d(const arma::mat::fixed<3,3> & dcm);\n\n/**\nConverts a MRP to the corresponding set of Euler angles in degrees\n@param sigma MRP vector\n@return angles Sequence of 313 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> mrp_to_euler313d(const arma::vec::fixed<3> & mrp);\n\n/**\nConverts a MRP to the corresponding set of Euler angles in degrees\n@param sigma MRP vector\n@return angles Sequence of 321 Euler angles angles [right ascension,inclination,longitude]\n*/\n\tarma::vec::fixed<3> mrp_to_euler321d(const arma::vec::fixed<3> & mrp);\n\n/**\nConverts a DCM to a quaternion corresponding to the short-path rotation\n@param dcm DCM\n@return Q Unit quaternion\n*/\n\tarma::vec::fixed<4> dcm_to_quat(const arma::mat::fixed<3,3> & dcm) ;\n\n/**\nConverts a dcm to the principal rotation vector\n@param dcm DCM\n@return prv Principal rotation vector\n*/\n\tarma::vec::fixed<3> dcm_to_prv(const arma::mat::fixed<3,3> & dcm) ;\n\n/**\nConverts a PRV to the corresponding DCM\n@param prv Principal rotation vector\n@return DCM\n*/\n\n\tarma::mat::fixed<3,3> prv_to_dcm(const arma::vec::fixed<3> & prv);\n\n\n/**\nConverts a PRV to a well-behaved MRP set\n@param prv Principal rotation vector\n@return MRP set\n*/\n\n\tarma::vec::fixed<3> prv_to_mrp(const arma::vec::fixed<3> & prv);\n\n/**\nReturns the B matrix in the evaluation of the MRP's time derivative (sigma_dot = 1/4 * Bmat(sigma) * omega)\n@param mrp MRP set\n@return instantiated B mtrix\n*/\n\tarma::mat::fixed<3,3> Bmat(const arma::vec::fixed<3> & mrp);\n\n/**\nReturns the partial derivative of mrp_dot with respect to the mrp\n@param attitude_set attitude set comprised of the mrp set and its associated angular velocity\n@return partial derivative of mrp_dot with respect to the mrp  \n*/\n\tarma::mat::fixed<3,3> partial_mrp_dot_partial_mrp(const arma::vec::fixed<6> & attitude_set);\n\n\n\n}\n\n\n#endif\n\n\n", "meta": {"hexsha": "5efcd84824b9b5a3ce28208ed874b0a3ef817de3", "size": 10235, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/RigidBodyKinematics.hpp", "max_stars_repo_name": "bbercovici/RigidBodyKinematics", "max_stars_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/RigidBodyKinematics.hpp", "max_issues_repo_name": "bbercovici/RigidBodyKinematics", "max_issues_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/RigidBodyKinematics.hpp", "max_forks_repo_name": "bbercovici/RigidBodyKinematics", "max_forks_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.191740413, "max_line_length": 124, "alphanum_fraction": 0.7425500733, "num_tokens": 2830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.5530299073404624}}
{"text": "#ifndef MOCHIMOCHI_AROW_HPP_\n#define MOCHIMOCHI_AROW_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\nclass AROW {\nprivate :\n  const std::size_t kDim;\n  const double kR;\n\nprivate :\n  Eigen::VectorXd _covariances;\n  Eigen::VectorXd _means;\n\npublic :\n  AROW(const std::size_t dim, const double r)\n    : kDim(dim),\n      kR(r),\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(r)>::max() > 0, \"Hyper Parameter Error. (r > 0)\");\n    assert(dim > 0);\n    assert(r > 0);\n\n  }\n\n  virtual ~AROW() { }\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 beta = 1.0 / (confidence + kR);\n    const auto alpha = std::max(0.0, 1.0 - label * margin) * beta;\n\n    functions::enumerate(feature.data(), feature.data() + feature.size(), 0,\n                         [&](const int index, const double value) {\n                           const auto v = _covariances[index] * value;\n                           _means[index] += alpha * label * v;\n                           _covariances[index] -= beta * v * v;\n                         });\n    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(\"r\", const_cast<double&>(kR));\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(\"r\", const_cast<double&>(kR));\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_AROW_HPP_\n", "meta": {"hexsha": "ca1f1cab34bd8d05a2e4007098429a1b006103eb", "size": 4188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mochimochi/classifier/binary/arow.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/arow.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/arow.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": 32.4651162791, "max_line_length": 107, "alphanum_fraction": 0.650191022, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.5530298904966895}}
{"text": "#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <memory>\n#include <array>\n\n#include <Eigen/Core>\n#include <gflags/gflags.h>\n#include <ceres/ceres.h>\n\n\ntemplate<typename T>\nclass Ellipse\n{\npublic:\n    Ellipse() : Ellipse(0, 0, 1, 1)\n    {\n    }\n\n    explicit Ellipse(T h, T k, T a, T b)\n    {\n        m_data[0] = h;\n        m_data[1] = k;\n        m_data[2] = a;\n        m_data[3] = b;\n    }\n\n    explicit Ellipse(const T* data)\n    {\n        std::copy(data, data + 4, m_data.begin());\n    }\n\n    explicit Ellipse(const Ellipse& other) : Ellipse(other.params())\n    {        \n    }\n\n    Ellipse& operator= (const Ellipse &other)\n    {\n        std::copy(other.m_data.begin(), other.m_data.end(), m_data.begin());\n        return *this;\n    }\n\n    const T* params() const\n    {\n        return m_data.data();\n    }\n\n    T* params()\n    {\n        return m_data.data();\n    }\n\n    T h() const\n    {\n        return m_data[0];\n    } \n\n    T k() const\n    {\n        return m_data[1];\n    }\n\n    T a() const\n    {\n        return m_data[2];\n    }\n\n    T b() const\n    {\n        return m_data[3];\n    }\n\n    void set_bounds(ceres::Problem& problem)\n    {\n        problem.SetParameterLowerBound(params(), 2, 1e-5);\n        problem.SetParameterLowerBound(params(), 3, 1e-5);\n    }\n\n    std::string to_string()\n    {\n        std::stringstream buff;\n        buff << \"(h=\" << h() << \", k=\" << k() << \", a=\" << a() << \", b=\" << b() << \")\";\n        return buff.str();\n    }\n\nprivate:\n    std::array<T, 4> m_data;\n};\n\n/** Sample functor which simply computes the residual.\n *  Used for numeric differentiation.\n */\nstruct NumericEllipseCostFunctor\n{\n    NumericEllipseCostFunctor(const Eigen::Vector2d &observed_point) : observed_point(observed_point) {}\n    bool operator()(const double *const parameters, double *residuals) const\n    {\n        Ellipse<double> ellipse(parameters);\n\n        // compute the cost\n        const double dx = observed_point.x() - ellipse.h();\n        const double dy = observed_point.y() - ellipse.k();\n        const double a2 = ellipse.a() * ellipse.a();\n        const double b2 = ellipse.b() * ellipse.b();\n        residuals[0] = (dx * dx) / a2 + (dy * dy) / b2 - 1;\n        return true;\n    }\n\n    Eigen::Vector2d observed_point;\n};\n\n/** Slightly more advanced functor which is templated, allowing\n *  Ceres to automatically compute the Jacobian using\n *  templates.\n */\nstruct AutoEllipseCostFunctor\n{\n    AutoEllipseCostFunctor(const Eigen::Vector2d &observed_point) : observed_point(observed_point) {}\n\n    /** Ceres will create a version of this with a special\n     *  autodiff type for determining the Jacobian\n     *  and another with doubles for residual computation\n     */\n    template <typename T>\n    bool operator()(const T *const parameters, T *residuals) const\n    {\n        Ellipse<T> ellipse(parameters);\n\n        T dx = T(observed_point.x()) - ellipse.h();\n        T dy = T(observed_point.y()) - ellipse.k();\n        T a2 = ellipse.a() * ellipse.a();\n        T b2 = ellipse.b() * ellipse.b();\n        residuals[0] = (dx * dx) / a2 + (dy * dy) / b2 - T(1.0);\n        return true;\n    }\n\n    Eigen::Vector2d observed_point;\n};\n\n/** If the analytic gradient is simple to compute or if perfomance is a concern,\n *  it can be best to compute the Jacobians by hand, as shown here. The template\n *  arguments indicate to Ceres the number of residuals, and the number of\n *  parameters. This can also be determined dynamically using the base\n *  class `CostFunction`.\n */\nstruct AnalyticEllipseCostFunction : public ceres::SizedCostFunction<1, 4>\n{\n    AnalyticEllipseCostFunction(const Eigen::Vector2d &observed_point) : observed_point(observed_point) {}\n    virtual ~AnalyticEllipseCostFunction() {}\n\n    /** This function performs double duty: it both computes the residuals and,\n     *  at other times, will also compute the Jacobians. This is communicated\n     *  via potential `nullptr` values in `jacobians`. While somewhat awkward,\n     *  this allows for re-use of sub-expressions for increased efficiency.\n     *  The sizes of the arrays are indicated via the template argument\n     *  above.\n     *\n     *  \\param parameters an array of parameter arrays\n     *  \\param residuals an array of residuals values\n     *  \\param jacobians an array of Jacobian matrices. Each matrix is in row-major order.\n     *  \\return whether the evaluation was successful\n     */\n    virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const\n    {\n        Ellipse<double> ellipse(parameters[0]);\n\n        // We can re-use all of these later\n        const double dx = observed_point.x() - ellipse.h();\n        const double dy = observed_point.y() - ellipse.k();\n        const double dx2 = dx * dx;\n        const double dy2 = dy * dy;\n        const double a2 = ellipse.a() * ellipse.a();\n        const double b2 = ellipse.b() * ellipse.b();\n        residuals[0] = dx2 / a2 + dy2 / b2 - 1;\n\n        // will be null if only evaluating residuals\n        if (jacobians != nullptr)\n        {\n            // if some parameters are being held constant,\n            // then individual Jacobian matrices will also be null\n            // to avoid unneeded computation\n            if (jacobians[0] != nullptr)\n            {\n                using jacobian_t = Eigen::Matrix<double, 1, 4, Eigen::RowMajor>;\n                Eigen::Map<jacobian_t> jac(jacobians[0]);\n                jac(0, 0) = (-2 * dx) / a2;\n                jac(0, 1) = (-2 * dy) / b2;\n                jac(0, 2) = (-2 * dx2) / (a2 * ellipse.a());\n                jac(0, 3) = (-2 * dy2) / (b2 * ellipse.b());\n            }\n        }\n\n        return true;\n    }\n\n    Eigen::Vector2d observed_point;\n};\n\n/** We can inject our own code into the optimization process to do\n *  custom logging and the like. This class writes intermediate values\n *  to a CSV file.\n */\nclass CSVCallback : public ceres::IterationCallback\n{\npublic:\n    explicit CSVCallback(const std::string &path, const double *params, int num_observations)\n        : m_params(params), m_num_observations(num_observations), m_output(path)\n    {\n        m_output << \"Cost,h,k,a,b\" << std::endl;\n    }\n\n    ~CSVCallback() {}\n\n    ceres::CallbackReturnType operator()(const ceres::IterationSummary &summary)\n    {\n        Ellipse<double> ellipse(m_params);\n        m_output << summary.cost / m_num_observations << \",\" << ellipse.h() << \",\" << ellipse.k() << \",\" << ellipse.a() << \",\" << ellipse.b() << std::endl;\n        return ceres::CallbackReturnType::SOLVER_CONTINUE;\n    }\n\nprivate:\n    const double *m_params;\n    const int m_num_observations;\n    std::ofstream m_output;\n};\n\n/** Creates a dataset consisting of noisy samples from an arc of an\n *  axis-aligned ellipse.\n * \n *  \\param num_observations the number of observations to sample\n *  \\param params the ellipse parameters\n *  \\param start_angle the starting angle of the arc in radians\n *  \\param end_angle the ending angle of the arc in radians\n *  \\param noise_sigma the sigma of the Gaussian used for noise\n *  \\return a matrix of points\n */\nEigen::Matrix2Xd create_dataset(int num_observations,\n                                const Ellipse<double> &ellipse,\n                                double start_angle = -0.5,\n                                double end_angle = 2.0,\n                                double noise_sigma = 0.05)\n{\n    Eigen::RowVectorXd angles = Eigen::RowVectorXd::LinSpaced(num_observations, start_angle, end_angle);\n    Eigen::Matrix2Xd data(2, num_observations);\n    data.row(0) = (ellipse.a() * angles.array().cos()) + ellipse.h();\n    data.row(1) = (ellipse.b() * angles.array().sin()) + ellipse.k();\n    std::random_device rd{};\n    std::mt19937 gen{rd()};\n    std::normal_distribution<> d{0, noise_sigma};\n    for (auto i = 0; i < data.cols(); ++i)\n    {\n        data(0, i) += d(gen);\n        data(1, i) += d(gen);\n    }\n\n    return data;\n}\n\n// Setup the problem using numeric differentiation.\nvoid setup_numeric(ceres::Problem &problem, const Eigen::Matrix2Xd &dataset, double *params)\n{\n    std::cout << \"Numeric differentiation: \" << std::endl;\n    using cost_t = ceres::NumericDiffCostFunction<NumericEllipseCostFunctor,\n                                                  ceres::CENTRAL, // method to use\n                                                  1,              // # residuals\n                                                  4>;             // # params\n    for (auto i = 0; i < dataset.cols(); ++i)\n    {\n        ceres::CostFunction *cost_function =\n            new cost_t(new NumericEllipseCostFunctor(dataset.col(i)));\n        problem.AddResidualBlock(cost_function, nullptr, params);\n    }\n}\n\n// Setup the problem using automatic differentiation.\nvoid setup_autodiff(ceres::Problem &problem, const Eigen::Matrix2Xd &dataset, double *params)\n{\n    std::cout << \"Automatic differentiation: \" << std::endl;\n    using cost_t = ceres::AutoDiffCostFunction<AutoEllipseCostFunctor,\n                                               1,   // # residuals\n                                               4>;  // # params\n    for (auto i = 0; i < dataset.cols(); ++i)\n    {\n        ceres::CostFunction *cost_function =\n            new cost_t(new AutoEllipseCostFunctor(dataset.col(i)));\n        problem.AddResidualBlock(cost_function, nullptr, params);\n    }\n}\n\n// Setup the problem using analytic differentiation.\nvoid setup_analytic(ceres::Problem &problem, const Eigen::Matrix2Xd &dataset, double *params)\n{\n    std::cout << \"Analytic differentiation: \" << std::endl;\n    for (auto i = 0; i < dataset.cols(); ++i)\n    {\n        ceres::CostFunction *cost_function = new AnalyticEllipseCostFunction(dataset.col(i));\n        problem.AddResidualBlock(cost_function, nullptr, params);\n    }\n}\n\n// Perform a gradient check\nint check_gradients(const Eigen::Matrix2Xd &dataset, double *params, double tolerance)\n{\n    // First we create an instance of the cost function we want to check\n    Eigen::Vector2d observed_point = dataset.col(0);\n    auto cost_function = std::make_shared<AnalyticEllipseCostFunction>(observed_point);\n\n    const double *parameters[] = {params};\n\n    // We can use this object to customise the checking process\n    ceres::NumericDiffOptions numeric_diff_options;\n    ceres::GradientChecker gradient_checker(cost_function.get(), nullptr, numeric_diff_options);\n\n    // We perform a probe. If unsuccessful, we can view the erroneous\n    // gradients by writing the error log to the console\n    ceres::GradientChecker::ProbeResults results;\n    if (!gradient_checker.Probe(parameters, tolerance, &results))\n    {\n        std::cerr << \"An error has occurred:\\n\"\n                  << results.error_log;\n        return EXIT_FAILURE;\n    }\n\n    std::cout << \"Gradients correct!\" << std::endl;\n    return EXIT_SUCCESS;\n}\n\nDEFINE_string(mode, \"numeric\", \"Mode for the program (one of 'numeric', 'autodiff', 'analytic', 'check_grad')\");\nDEFINE_int32(num_observations, 100, \"Number of observations\");\nDEFINE_bool(verbose, false, \"Output a verbose summary of the optimization\");\nDEFINE_bool(dump_data, false, \"Whether to dump the data to a csv\");\n\nint main(int argc, char **argv)\n{\n    gflags::SetUsageMessage(\"Ceres Example\");\n    gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n    Ellipse<double> initial(0.1, 0.3, 0.9, 1.2);\n    Ellipse<double> target(-0.3, 0.5, 4.3, 2.1);\n    Ellipse<double> ellipse;\n    Eigen::Matrix2Xd dataset = create_dataset(FLAGS_num_observations, target);\n\n    if (FLAGS_dump_data)\n    {\n        std::ofstream output(FLAGS_mode + \"_data.csv\");\n        output << \"x,y\" << std::endl;\n        for (auto i = 0; i < dataset.cols(); ++i)\n        {\n            output << dataset(0, i) << \",\" << dataset(1, i) << std::endl;\n        }\n    }\n\n    ceres::Problem problem;\n    ellipse = initial;\n\n    if (\"autodiff\" == FLAGS_mode)\n    {\n        setup_autodiff(problem, dataset, ellipse.params());\n    }\n    else if (\"numeric\" == FLAGS_mode)\n    {\n        setup_numeric(problem, dataset, ellipse.params());\n    }\n    else if (\"analytic\" == FLAGS_mode)\n    {\n        setup_analytic(problem, dataset, ellipse.params());\n    }\n    else if (\"check_grad\" == FLAGS_mode)\n    {\n        return check_gradients(dataset, ellipse.params(), 1e-9);\n    }\n    else\n    {\n        std::cout << \"Unrecognized mode: \" << FLAGS_mode << std::endl;\n        return 1;\n    }\n\n    // we can set upper and lower bounds for all parameters\n    ellipse.set_bounds(problem);\n\n    // The solver has a wide variety customization options\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = true;\n    options.num_threads = 8;\n\n    // Here we add our own custom callback for logging to a file\n    options.update_state_every_iteration = true;\n    std::shared_ptr<CSVCallback> callback = std::make_shared<CSVCallback>(FLAGS_mode + \"_fit.csv\", ellipse.params(), FLAGS_num_observations);\n    options.callbacks.push_back(callback.get());\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    if (FLAGS_verbose)\n    {\n        std::cout << summary.FullReport() << std::endl;\n    }\n    else\n    {\n        std::cout << summary.BriefReport() << std::endl;\n    }\n\n    std::cout << \"Initial: \" << initial.to_string() << std::endl\n              << \"Final: \" << ellipse.to_string() << std::endl\n              << \"Target: \" << target.to_string() << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "ff1df3f66ca8dd540b81e906cab0dedaf2ca59ff", "size": 13465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ceres_example.cpp", "max_stars_repo_name": "matajoh/ceres_example", "max_stars_repo_head_hexsha": "722b018221ee8833b761fb4adbb7eef44bc14238", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-05-13T12:33:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T13:37:45.000Z", "max_issues_repo_path": "ceres_example.cpp", "max_issues_repo_name": "johnolafenwa/ceres_example", "max_issues_repo_head_hexsha": "722b018221ee8833b761fb4adbb7eef44bc14238", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ceres_example.cpp", "max_forks_repo_name": "johnolafenwa/ceres_example", "max_forks_repo_head_hexsha": "722b018221ee8833b761fb4adbb7eef44bc14238", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-14T02:49:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:49:51.000Z", "avg_line_length": 32.9217603912, "max_line_length": 155, "alphanum_fraction": 0.6113627924, "num_tokens": 3343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.5530298809050433}}
{"text": "#ifndef GUARD_CIRCUIT_SIMULATOR_HPP\n#define GUARD_CIRCUIT_SIMULATOR_HPP\n\n#include <sstream>\n#include <iostream>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n\ntemplate <typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\nstruct Functor\n{\n\t// Information that tells the caller the numeric type (eg. double) and size (input / output dim)\n\ttypedef _Scalar Scalar;\n\tenum\n\t{ // Required by numerical differentiation module\n\t\tInputsAtCompileTime = NX,\n\t\tValuesAtCompileTime = NY\n\t};\n\t// Tell the caller the matrix sizes associated with the input, output, and jacobian\n\ttypedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n\ttypedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n\ttypedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n\t// Local copy of the number of inputs\n\tint m_inputs, m_values;\n\n\t// Two constructors:\n\tFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\tFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n\t// Get methods for users to determine function input and output dimensions\n\tint inputs() const { return m_inputs; }\n\tint values() const { return m_values; }\n};\nstruct ConductanceFunc : Functor<double>\n{\n\t// Simple constructor\n\tdouble time = 0;\n\tCircuit::Schematic *schem;\n\tCircuit::ParamTable *param;\n\tdouble timestep;\n\tint NUM_NODES = 0;\n\tConductanceFunc(Circuit::Schematic *schem, Circuit::ParamTable *param, double time, double timestep, int NUM_NODES) : Functor<double>(schem->nonLinearComps.size(), schem->nonLinearComps.size())\n\t{\n\t\tthis->schem = schem;\n\t\tthis->param = param;\n\t\tthis->timestep = timestep;\n\t\tthis->time = time;\n\t\tthis->NUM_NODES = NUM_NODES;\n\t}\n\n\tint operator()(const Eigen::VectorXd &vDiff, Eigen::VectorXd &fvec) const\n\t{\n\t\tEigen::VectorXd voltage(NUM_NODES);\n\t\tEigen::VectorXd current(NUM_NODES);\n\t\tEigen::MatrixXd conductance(NUM_NODES, NUM_NODES);\n\t\tfor (int i = 0; i < vDiff.size(); i++)\n\t\t{\n\t\t\tschem->nonLinearComps[i]->setConductance(param, timestep, vDiff(i));\n\t\t}\n\t\tCircuit::Math::getConductanceTRAN(schem, conductance, param, time, timestep);\n\t\tCircuit::Math::getCurrentTRAN(schem, current, conductance, param, time, timestep);\n\t\tCircuit::Math::solveMatrix(conductance, voltage, current);\n\n\t\tfor (int i = 0; i < vDiff.size(); i++)\n\t\t{\n\t\t\tdouble vPos = (schem->nonLinearComps[i]->getPosNode()->getId() != -1) ? voltage(schem->nonLinearComps[i]->getPosNode()->getId()) : 0;\n\t\t\tdouble vNeg = (schem->nonLinearComps[i]->getNegNode()->getId() != -1) ? voltage(schem->nonLinearComps[i]->getNegNode()->getId()) : 0;\n\t\t\tfvec(i) = vPos - vNeg - vDiff(i);\n\t\t}\n\n\t\treturn 0;\n\t}\n\tint getVdif(const Eigen::VectorXd &vDiff, Eigen::VectorXd &fvec) const\n\t{\n\n\t\tEigen::VectorXd voltage(NUM_NODES);\n\t\tEigen::VectorXd current(NUM_NODES);\n\t\tEigen::MatrixXd conductance(NUM_NODES, NUM_NODES);\n\n\t\tfor (int i = 0; i < vDiff.size(); i++)\n\t\t{\n\t\t\tschem->nonLinearComps[i]->setConductance(param, timestep, vDiff(i));\n\t\t}\n\t\tCircuit::Math::getConductanceTRAN(schem, conductance, param, time, timestep);\n\t\tCircuit::Math::getCurrentTRAN(schem, current, conductance, param, time, timestep);\n\t\tCircuit::Math::solveMatrix(conductance, voltage, current);\n\n\t\tfor (int i = 0; i < vDiff.size(); i++)\n\t\t{\n\t\t\tdouble vPos = (schem->nonLinearComps[i]->getPosNode()->getId() != -1) ? voltage(schem->nonLinearComps[i]->getPosNode()->getId()) : 0;\n\t\t\tdouble vNeg = (schem->nonLinearComps[i]->getNegNode()->getId() != -1) ? voltage(schem->nonLinearComps[i]->getNegNode()->getId()) : 0;\n\t\t\tfvec(i) = vPos - vNeg;\n\t\t}\n\n\t\treturn 0;\n\t}\n\tvoid getVoltageVector(const Eigen::VectorXd &vDiff, Eigen::VectorXd &fvec)\n\t{\n\t\tEigen::VectorXd current(NUM_NODES);\n\t\tEigen::MatrixXd conductance(NUM_NODES, NUM_NODES);\n\n\t\tfor (int i = 0; i < vDiff.size(); i++)\n\t\t{\n\t\t\tschem->nonLinearComps[i]->setConductance(param, timestep, vDiff(i));\n\t\t}\n\n\t\tCircuit::Math::getConductanceTRAN(schem, conductance, param, time, timestep);\n\t\tCircuit::Math::getCurrentTRAN(schem, current, conductance, param, time, timestep);\n\t\tCircuit::Math::solveMatrix(conductance, fvec, current);\n\t}\n};\n\nclass Circuit::Simulator\n{\nprivate:\n\tSchematic *schem;\n\tdouble tranStopTime;\n\tdouble tranSaveStart;\n\tdouble tranStepTime;\n\tstd::stringstream spiceStream;\n\tstd::stringstream csvStream;\n\n\tvoid spicePrintTitle()\n\t{\n\t\tspiceStream << \"Time\";\n\t\tfor (auto node_pair : schem->nodes)\n\t\t{\n\t\t\tspiceStream << \"\\tV(\" << node_pair.first << \")\";\n\t\t}\n\t\tfor (auto comp_pair : schem->comps)\n\t\t{\n\t\t\tspiceStream << \"\\tI(\" << comp_pair.first << \")\";\n\t\t}\n\t\tspiceStream << \"\\n\";\n\t}\n\tvoid csvPrintTitle()\n\t{\n\t\tcsvStream << \"Time\";\n\t\tfor (auto node_pair : schem->nodes)\n\t\t{\n\t\t\tcsvStream << \",V(\" << node_pair.first << \")\";\n\t\t}\n\t\tfor (auto comp_pair : schem->comps)\n\t\t{\n\t\t\tcsvStream << \",I(\" << comp_pair.first << \")\";\n\t\t}\n\t\tcsvStream << \"\\n\";\n\t}\n\n\tvoid printStep(int n)\n\t{\n\t\tParamTable *param = schem->tables[n];\n\t\tif (param->lookup.size() == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tfor (auto x : param->lookup)\n\t\t{\n\t\t\tspiceStream << \"Step Information:\";\n\t\t\tcsvStream << \"Step Information:\";\n\t\t\tfor (std::pair<std::string, double> var : param->lookup)\n\t\t\t{\n\t\t\t\tcsvStream << \" \" << var.first << \"=\" << var.second;\n\t\t\t\tspiceStream << \" \" << var.first << \"=\" << var.second;\n\t\t\t}\n\t\t\tcsvStream << \" Run: \" << n + 1 << \"/\" << schem->tables.size() << std::endl;\n\t\t\tspiceStream << \" Run: \" << n + 1 << \"/\" << schem->tables.size() << std::endl;\n\t\t}\n\t}\n\tvoid spicePrint(ParamTable *param, double time, double timestep)\n\t{\n\t\tspiceStream << time;\n\t\tfor (auto node_pair : schem->nodes)\n\t\t{\n\t\t\tspiceStream << \"\\t\" << node_pair.second->voltage;\n\t\t}\n\t\tfor (auto comp_pair : schem->comps)\n\t\t{\n\t\t\tspiceStream << \"\\t\" << comp_pair.second->getCurrent(param, time, timestep);\n\t\t}\n\t\tspiceStream << \"\\n\";\n\t}\n\tvoid csvPrint(ParamTable *param, double time, double timestep)\n\t{\n\t\tcsvStream << time;\n\t\tfor (auto node_pair : schem->nodes)\n\t\t{\n\t\t\tcsvStream << \",\" << node_pair.second->voltage;\n\t\t}\n\t\tfor (auto comp_pair : schem->comps)\n\t\t{\n\t\t\tcsvStream << \",\" << comp_pair.second->getCurrent(param, time, timestep);\n\t\t}\n\t\tcsvStream << \"\\n\";\n\t}\n\npublic:\n\tenum SimulationType\n\t{\n\t\tOP,\n\t\tTRAN,\n\t\tDC,\n\t\tSMALL_SIGNAL\n\t};\n\n\tconst SimulationType type;\n\n\tenum OutputFormat\n\t{\n\t\tCSV,\n\t\tSPACE // actually tab separated\n\t};\n\n\tusing enumPair = std::pair<SimulationType, std::string>;\n\n\tstd::map<SimulationType, std::string> simulationTypeMap = {\n\t\tenumPair(OP, \"OP\"),\n\t\tenumPair(TRAN, \"TRAN\"),\n\t\tenumPair(DC, \"DC\"),\n\t\tenumPair(SMALL_SIGNAL, \"SMALL_SIGNAL\"),\n\t};\n\n\tSimulator(Schematic *schem, SimulationType type) : schem(schem), type(type) {}\n\tSimulator(Schematic *schem, SimulationType type, double tranStopTime, double tranSaveStart = 0, double tranStepTime = 0) : Simulator(schem, type)\n\t{\n\t\tif (tranStepTime == 0)\n\t\t{\n\t\t\ttranStepTime = tranStopTime / 1000.0; // default of a thousand cycles\n\t\t}\n\t\tthis->tranStopTime = tranStopTime;\n\t\tthis->tranSaveStart = tranSaveStart;\n\t\tthis->tranStepTime = tranStepTime;\n\t}\n\n\tvoid run(std::ostream &dst, OutputFormat format)\n\t{\n\t\tconst unsigned int NUM_NODES = schem->nodes.size() - 1;\n\t\tconst unsigned int NUM_V_GUESS = schem->nonLinearComps.size();\n\n\t\tEigen::VectorXd voltage(NUM_NODES);\n\t\tEigen::VectorXd vGuess(NUM_V_GUESS);\n\t\tEigen::VectorXd current(NUM_NODES);\n\t\tEigen::MatrixXd conductance(NUM_NODES, NUM_NODES);\n\n\t\tif (format == SPACE)\n\t\t{\n\t\t\tspiceStream.str(\"\");\n\t\t\tspicePrintTitle();\n\t\t}\n\t\telse if (format == CSV)\n\t\t{\n\t\t\tcsvStream.str(\"\");\n\t\t\tcsvPrintTitle();\n\t\t}\n\t\tParamTable *param;\n\t\tfor (size_t i = 0; i < schem->tables.size(); i++)\n\t\t{\n\t\t\tparam = schem->tables[i];\n\t\t\tprintStep(i);\n\n\t\t\tfor_each(schem->nodes.begin(), schem->nodes.end(), [&](const auto node_pair) {\n\t\t\t\tif (node_pair.second->getId() != -1)\n\t\t\t\t{\n\t\t\t\t\tnode_pair.second->voltage = 0.0;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (type == OP)\n\t\t\t{\n\t\t\t\tCircuit::Math::getConductanceOP(schem, conductance, param);\n\t\t\t\tCircuit::Math::getCurrentOP(schem, current, conductance, param);\n\t\t\t\tCircuit::Math::solveMatrix(conductance, voltage, current);\n\n\t\t\t\tdst << \"\\t-----Operating Point-----\\t\\n\";\n\t\t\t\tif (param->lookup.size() > 0)\n\t\t\t\t{\n\t\t\t\t\tdst << \"Step Information: \";\n\t\t\t\t\tfor (std::pair<std::string, double> var : param->lookup)\n\t\t\t\t\t{\n\t\t\t\t\t\tdst << \" \" << var.first << \"=\" << var.second;\n\t\t\t\t\t}\n\t\t\t\t\tdst << \" Run: \" << i + 1 << \"/\" << schem->tables.size() << std::endl;\n\t\t\t\t}\n\t\t\t\tdst << std::endl;\n\t\t\t\tfor_each(schem->nodes.begin(), schem->nodes.end(), [&](const auto node_pair) {\n\t\t\t\t\tif (node_pair.second->getId() != -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tnode_pair.second->voltage = voltage[node_pair.second->getId()];\n\t\t\t\t\t\tdst << \"V(\" << node_pair.first << \")\\t\\t\" << node_pair.second->voltage << \"\\t\\tnode_voltage\\n\";\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tfor_each(schem->comps.begin(), schem->comps.end(), [&](const auto comp_pair) {\n\t\t\t\t\tdst << \"I(\" << comp_pair.first << \")\\t\\t\" << comp_pair.second->getCurrent(param, 0, -1) << \"\\t\\tdevice_current\\n\";\n\t\t\t\t});\n\t\t\t}\n\t\t\telse if (type == TRAN)\n\t\t\t{\n\t\t\t\tif (!schem->nonLinear)\n\t\t\t\t{\n\t\t\t\t\tEigen::SparseMatrix<double> sparse;\n\n\t\t\t\t\tfor (double t = 0; t <= tranStopTime; t += tranStepTime)\n\t\t\t\t\t{\n\t\t\t\t\t\tMath::progressBar(t / tranStopTime, i, schem->tables.size());\n\t\t\t\t\t\tMath::getConductanceTRAN(schem, conductance, param, t, tranStepTime);\n\t\t\t\t\t\tMath::getCurrentTRAN(schem, current, conductance, param, t, tranStepTime);\n\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCircuit::Math::solveMatrix(conductance, voltage, current);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (const std::exception &e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::cerr << \"error solving skipping timestep\" << std::endl;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor_each(schem->nodes.begin(), schem->nodes.end(), [&](const auto node_pair) {\n\t\t\t\t\t\t\tif (node_pair.second->getId() != -1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnode_pair.second->voltage = voltage[node_pair.second->getId()];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (t >= tranSaveStart)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (format == SPACE)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tspicePrint(param, t, tranStepTime);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (format == CSV)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcsvPrint(param, t, tranStepTime);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (double t = 0; t <= tranStopTime; t += tranStepTime)\n\t\t\t\t\t{\n\t\t\t\t\t\t//Math::progressBar(t / tranStopTime, i, schem->tables.size());\n\t\t\t\t\t\tMath::init_vector(vGuess);\n\t\t\t\t\t\tConductanceFunc functor(schem, param, t, tranStepTime, NUM_NODES);\n\t\t\t\t\t\tEigen::NumericalDiff<ConductanceFunc> numDiff(functor);\n\n\t\t\t\t\t\tif (schem->itType == Schematic::IterationType::Levenberg)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tEigen::LevenbergMarquardt<Eigen::NumericalDiff<ConductanceFunc>, double> lm(numDiff);\n\t\t\t\t\t\t\tlm.parameters.maxfev = 1000;\n\t\t\t\t\t\t\tlm.parameters.xtol = 1.0e-10;\n\t\t\t\t\t\t\tlm.minimize(vGuess);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (schem->itType == Schematic::IterationType::Newton)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (size_t i = 0; i < 1000; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tEigen::MatrixXd jaq(NUM_V_GUESS, NUM_V_GUESS);\n\t\t\t\t\t\t\t\tnumDiff.df(vGuess, jaq);\n\t\t\t\t\t\t\t\tEigen::VectorXd vErrVec(NUM_V_GUESS);\n\t\t\t\t\t\t\t\tfunctor(vGuess, vErrVec);\n\t\t\t\t\t\t\t\tEigen::MatrixXd inverseJaq = jaq.transpose().inverse();\n\t\t\t\t\t\t\t\tfor (size_t x = 0; x < NUM_V_GUESS; x++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfor (size_t y = 0; y < NUM_V_GUESS; y++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (std::isnan(inverseJaq(x, y)))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tinverseJaq(x, y) = 1e-200;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (!std::isfinite(inverseJaq(x, y)))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tinverseJaq(x, y) = 1e200;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstd::cerr<<t<<\",\"<<i<<\",\"<<vGuess[0]<<\",\"<<vGuess[1]<<\",\"<<vErrVec.norm()<<std::endl;\n\t\t\t\t\t\t\t\tvGuess = vGuess - 0.005 * (inverseJaq * vErrVec);\n\t\t\t\t\t\t\t}\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\tstd::cerr << \"unknown iteration type\" << std::endl;\n\t\t\t\t\t\t\tstd::terminate();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tEigen::VectorXd vErrVec(NUM_V_GUESS);\n\t\t\t\t\t\tfunctor.getVoltageVector(vGuess, voltage);\n\t\t\t\t\t\tfor_each(schem->nodes.begin(), schem->nodes.end(), [&](const auto node_pair) {\n\t\t\t\t\t\t\tif (node_pair.second->getId() != -1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnode_pair.second->voltage = voltage[node_pair.second->getId()];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (t >= tranSaveStart)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (format == SPACE)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tspicePrint(param, t, tranStepTime);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (format == CSV)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcsvPrint(param, t, tranStepTime);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstd::cerr << std::endl;\n\t\t\t}\n\t\t\tif (format == SPACE && type != OP)\n\t\t\t{\n\t\t\t\tdst << spiceStream.str();\n\t\t\t\tspiceStream.str(\"\");\n\t\t\t}\n\t\t\telse if (format == CSV && type != OP)\n\t\t\t{\n\t\t\t\tdst << csvStream.str();\n\t\t\t\tcsvStream.str(\"\");\n\t\t\t}\n\t\t}\n\t}\n};\n\n#endif\n", "meta": {"hexsha": "03100e53dbd8bd8884b6fa25bf140fed6a41e55f", "size": 12404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/circuit_simulator.hpp", "max_stars_repo_name": "neeldug/404CircuitSim", "max_stars_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/circuit_simulator.hpp", "max_issues_repo_name": "neeldug/404CircuitSim", "max_issues_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/circuit_simulator.hpp", "max_forks_repo_name": "neeldug/404CircuitSim", "max_forks_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-06T20:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T20:27:56.000Z", "avg_line_length": 29.117370892, "max_line_length": 194, "alphanum_fraction": 0.6220574008, "num_tokens": 3699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5530256547589529}}
{"text": "/*======================================================================\nCopyright 2019 Google LLC\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    https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n======================================================================*/\n\n\n#include <cmath>\n\n#include <Eigen/Dense>\n#include \"PCV_Types.h\"\n\n#include \"traj_circle.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nstatic double hz_;\nstatic double r_,wr_;\nstatic double a_,wa_;\nstatic double ramp_,t_;\n\n\nvoid\ninit_traj_circle(double r,\n                 double wr,\n                 double a,\n                 double wa,\n                 double hz,\n                 double ramp)\n{\n  r_  = r;\n  wr_ = wr;\n  a_  = a;\n  wa_ = wa;\n  hz_ = hz;\n  ramp_ = ramp;\n\n  t_=0.0;\n}\n\nvoid\ntraj_circle(Vector3d &x, Vector3d &xd, Vector3d &xdd)\n{\n  double wr,wa;\n\n   if( t_<ramp_ )\n   { wr = t_/ramp_ * wr_;\n     wa = t_/ramp_ * wa_;\n   }\n   else\n   { wr = wr_;\n     wa = wa_;\n   }\n\n    x[0] =  r_*      cos( wr*t_ ) - r_ ;\n   xd[0] = -r_*wr*   sin( wr*t_ ) ;\n  xdd[0] = -r_*wr*wr*cos( wr*t_ ) ;\n\n    x[1] =  r_*      sin( wr*t_ ) ;\n   xd[1] =  r_*wr*   cos( wr*t_ ) ;\n  xdd[1] = -r_*wr*wr*sin( wr*t_ ) ;\n\n    x[2] =  a_*   (1-cos( wa*t_ ));\n   xd[2] =  a_*wa*   sin( wa*t_ ) ;\n  xdd[2] =  a_*wa*wa*cos( wa*t_ ) ;\n\n\n  t_ += 1.0/hz_;\n\n}\n", "meta": {"hexsha": "d94ed8211af76eb6a1ccf5dffcbe76e6b5fe4f11", "size": 1738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "traj_circle.cpp", "max_stars_repo_name": "google/powered-caster-vehicle", "max_stars_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T17:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T08:34:10.000Z", "max_issues_repo_path": "traj_circle.cpp", "max_issues_repo_name": "google/powered-caster-vehicle", "max_issues_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "traj_circle.cpp", "max_forks_repo_name": "google/powered-caster-vehicle", "max_forks_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T18:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T23:17:59.000Z", "avg_line_length": 21.1951219512, "max_line_length": 72, "alphanum_fraction": 0.5454545455, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.5529712005792213}}
{"text": "#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"glog/logging.h\"\n\nnamespace py = pybind11;\n\nstd::tuple<Eigen::Vector3d, double> GetRotationVector(Eigen::Ref<Eigen::Vector3d> v1, Eigen::Ref<Eigen::Vector3d> v2) {\n    auto rotationVector = Eigen::AngleAxisd(Eigen::Quaterniond::FromTwoVectors(v1, v2));\n    return std::make_tuple(rotationVector.axis(), rotationVector.angle());\n}\n\n// The input 3D points are stored as columns.\nEigen::Affine3d Find3DAffineTransform(Eigen::Matrix3Xd in, Eigen::Matrix3Xd out) {\n    // Default output\n    Eigen::Affine3d A;\n    A.linear() = Eigen::Matrix3d::Identity(3, 3);\n    A.translation() = Eigen::Vector3d::Zero();\n\n    if (in.cols() != out.cols()) throw \"Find3DAffineTransform(): input data mis-match\";\n\n    // First find the scale, by finding the ratio of sums of some distances,\n    // then bring the datasets to the same scale.\n    double dist_in = 0, dist_out = 0;\n    for (int col = 0; col < in.cols() - 1; col++) {\n        dist_in += (in.col(col + 1) - in.col(col)).norm();\n        dist_out += (out.col(col + 1) - out.col(col)).norm();\n    }\n    if (dist_in <= 0 || dist_out <= 0) return A;\n    double scale = dist_out / dist_in;\n    out /= scale;\n\n    // Find the centroids then shift to the origin\n    Eigen::Vector3d in_ctr = Eigen::Vector3d::Zero();\n    Eigen::Vector3d out_ctr = Eigen::Vector3d::Zero();\n    for (int col = 0; col < in.cols(); col++) {\n        in_ctr += in.col(col);\n        out_ctr += out.col(col);\n    }\n    in_ctr /= in.cols();\n    out_ctr /= out.cols();\n    for (int col = 0; col < in.cols(); col++) {\n        in.col(col) -= in_ctr;\n        out.col(col) -= out_ctr;\n    }\n\n    // SVD\n    Eigen::MatrixXd Cov = in * out.transpose();\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Cov, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // Find the rotation\n    double d = (svd.matrixV() * svd.matrixU().transpose()).determinant();\n    if (d > 0)\n        d = 1.0;\n    else\n        d = -1.0;\n    Eigen::Matrix3d I = Eigen::Matrix3d::Identity(3, 3);\n    I(2, 2) = d;\n    Eigen::Matrix3d R = svd.matrixV() * I * svd.matrixU().transpose();\n\n    // The final transform\n    A.linear() = scale * R;\n    A.translation() = scale * (out_ctr - R * in_ctr);\n\n    return A;\n}\n\nEigen::AngleAxisd EstimatePalmAngleFromBase(const std::vector<Eigen::Vector3d>& landmark_list,\n                                            const Eigen::MatrixXd& base) {\n    // Calculate a maybe stable vectors that penetrating palm perpendicularly.\n    Eigen::Vector3d rotationVectorSum;\n    auto PALM_PLAIN_INDICES = {5, 9, 13, 17};\n\n    for (size_t i = 0; i < PALM_PLAIN_INDICES.size() - 1; i++) {\n        auto a = landmark_list[i] - landmark_list[0];\n        auto b = landmark_list[i + 1] - landmark_list[0];\n        rotationVectorSum += Eigen::AngleAxisd(Eigen::Quaterniond::FromTwoVectors(a, b)).axis();\n    }\n    auto meanPalmVector = rotationVectorSum / (PALM_PLAIN_INDICES.size() - 1);\n\n    // Calculate unit direction vectors perpendicular to palm vector.\n    Eigen::Vector3d fingerVector = ((landmark_list[9] - landmark_list[0]) + (landmark_list[13] - landmark_list[0]))/2.0;\n    fingerVector /= fingerVector.norm();\n    Eigen::Vector3d thumbVector = fingerVector.cross(meanPalmVector);\n    thumbVector /= thumbVector.norm();\n\n    // Calculate rotation vector that rotate axis.\n    Eigen::MatrixXd vectors(3,3);\n    vectors.col(0) = thumbVector;\n    vectors.col(1) = fingerVector;\n    vectors.col(2) = meanPalmVector;\n\n    // std::cout << vectors << std::endl;\n    const auto& A = Find3DAffineTransform(base, vectors);\n    auto rotation = Eigen::AngleAxisd(A.linear());\n    return std::move(rotation);\n}\n\n\nstd::tuple<Eigen::Vector3d, double> EstimatePalmRotation(\n    const std::vector<Eigen::Vector3d>& landmark_list,\n    const std::string& direction) {\n    Eigen::Matrix3d baseMatrix;\n    // This base is \n    // (1) Fingers ar pointing to camera.\n    // (2) \n    if (direction == \"Right\") {\n        baseMatrix << 1, 0, 0,\n                    0, -1, 0,\n                    0, 0, -1;\n    } else if (direction == \"Left\") {\n        baseMatrix << 1, 0, 0,\n                    0, -1, 0,\n                    0, 0, 1;\n    }        \n    auto rotation = EstimatePalmAngleFromBase(landmark_list, baseMatrix);\n    return std::make_tuple(rotation.axis(), rotation.angle());\n}\n\nstd::vector<std::tuple<Eigen::Vector3d, double>> GetRelativeAnglesFromXYPlane(\n    const std::vector<Eigen::Vector3d>& landmarkList, const std::vector<int>& ids\n) {\n    std::vector<Eigen::Vector3d> positions;\n    for (auto id : ids) {\n        positions.push_back(landmarkList[id]);\n    }\n    \n    // Get the direction of the finger.\n    Eigen::Vector3d base = positions.back() - positions.front();\n    base[2] = 0;\n\n    std::vector<Eigen::Vector3d> finger_diffs = { base };\n    for (size_t i = 0; i < positions.size() - 1; i++)\n    {\n        finger_diffs.push_back(positions[i + 1] - positions[i]);\n    }\n\n    std::vector<std::tuple<Eigen::Vector3d, double>> rotations;\n    for (size_t i = 0; i < finger_diffs.size() - 1; i++)\n    {\n        rotations.push_back(GetRotationVector(finger_diffs[i + 1], finger_diffs[i]));\n    }\n    return std::move(rotations);\n}\n\nstd::map<std::string, std::vector<std::tuple<Eigen::Vector3d, double>>> GetFingers(\n    const std::vector<Eigen::Vector3d>& landmark_list, const std::map<std::string, std::vector<int>>& fingerIndicesMap) {\n    std::map<std::string, std::vector<std::tuple<Eigen::Vector3d, double>>> fingerNameToRotations;\n\n    // Normalize Vector by hand pose.\n    Eigen::Matrix3d baseMatrix;\n    baseMatrix << 1, 0, 0,\n                  0, 1, 0,\n                  0, 0, 1;\n    auto rotation = EstimatePalmAngleFromBase(landmark_list, baseMatrix);\n    std::vector<Eigen::Vector3d> directionNormalizedLandmarks;\n    for (const auto& point : landmark_list) {\n        directionNormalizedLandmarks.push_back(rotation.inverse() * point);\n    }\n\n    // Get the rotations for each fingers.\n    for (const auto& tuple : fingerIndicesMap) {\n        fingerNameToRotations[std::get<0>(tuple)] = GetRelativeAnglesFromXYPlane(\n            directionNormalizedLandmarks, std::get<1>(tuple)\n        );\n    }\n\n    return fingerNameToRotations;\n}\n\nPYBIND11_MODULE(landmark_utils, m) {\n    // m.def(\"get_shortest_rotvec_between_two_vector\", &GetRotationVector);\n    m.def(\"get_shortest_rotvec_between_two_vector\", &GetRotationVector, py::return_value_policy::move);\n    m.def(\"get_fingers\", &GetFingers, py::return_value_policy::move);\n    m.def(\"estimate_palm_rotation\", &EstimatePalmRotation, py::return_value_policy::move);\n}", "meta": {"hexsha": "ea9c124a970d15389f5b7a42470c438bff6767f7", "size": 6676, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pikapi/landmark_utils.cc", "max_stars_repo_name": "xiong-jie-y/pika", "max_stars_repo_head_hexsha": "f570a9df443ed36ecd7313e0747b77a3152e343f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-27T20:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-28T01:43:39.000Z", "max_issues_repo_path": "pikapi/landmark_utils.cc", "max_issues_repo_name": "xiong-jie-y/pika", "max_issues_repo_head_hexsha": "f570a9df443ed36ecd7313e0747b77a3152e343f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pikapi/landmark_utils.cc", "max_forks_repo_name": "xiong-jie-y/pika", "max_forks_repo_head_hexsha": "f570a9df443ed36ecd7313e0747b77a3152e343f", "max_forks_repo_licenses": ["Apache-2.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.8839779006, "max_line_length": 121, "alphanum_fraction": 0.6351108448, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.5529711941035329}}
{"text": "#pragma once\n\n#include <Eigen/Sparse>\n#include <cilantro/space_transformations.hpp>\n#include <cilantro/nearest_neighbors.hpp>\n#include <cilantro/correspondence.hpp>\n\nnamespace cilantro {\n    // Values interpreted as weights\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    void resampleTransformations(const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                 const std::vector<NeighborSet<ScalarT>> &new_to_old_map,\n                                 RigidTransformationSet<ScalarT,EigenDim> &new_transforms)\n    {\n        new_transforms.resize(new_to_old_map.size());\n\n        ScalarT total_weight;\n\n#pragma omp parallel for shared (new_transforms) private (total_weight)\n        for (size_t i = 0; i < new_transforms.size(); i++) {\n            total_weight = (ScalarT)0.0;\n            new_transforms[i].linear().setZero();\n            new_transforms[i].translation().setZero();\n            for (size_t j = 0; j < new_to_old_map[i].size(); j++) {\n                total_weight += new_to_old_map[i][j].value;\n                new_transforms[i].linear() += new_to_old_map[i][j].value*old_transforms[new_to_old_map[i][j].index].linear();\n                new_transforms[i].translation() += new_to_old_map[i][j].value*old_transforms[new_to_old_map[i][j].index].translation();\n            }\n\n            if (total_weight == (ScalarT)0.0) {\n                new_transforms[i].setIdentity();\n            } else {\n                total_weight = (ScalarT)(1.0)/total_weight;\n                new_transforms[i].linear() *= total_weight;\n                new_transforms[i].linear() = new_transforms[i].rotation();\n                new_transforms[i].translation() *= total_weight;\n            }\n        }\n    }\n\n    // Values interpreted as weights\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    inline RigidTransformationSet<ScalarT,EigenDim> resampleTransformations(const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                                                            const std::vector<NeighborSet<ScalarT>> &new_to_old_map)\n    {\n        RigidTransformationSet<ScalarT,EigenDim> new_transforms;\n        resampleTransformations<ScalarT,EigenDim>(old_transforms, new_to_old_map, new_transforms);\n        return new_transforms;\n    }\n\n    // Values interpreted as distances\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    void resampleTransformations(const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                 const std::vector<NeighborSet<ScalarT>> &new_to_old_map,\n                                 ScalarT distance_sigma,\n                                 RigidTransformationSet<ScalarT,EigenDim> &new_transforms)\n    {\n        new_transforms.resize(new_to_old_map.size());\n\n        const ScalarT sigma_inv_sq = (ScalarT)(1.0)/(distance_sigma*distance_sigma);\n        ScalarT curr_weight, total_weight;\n\n#pragma omp parallel for shared (new_transforms) private (curr_weight, total_weight)\n        for (size_t i = 0; i < new_transforms.size(); i++) {\n            total_weight = (ScalarT)0.0;\n            new_transforms[i].linear().setZero();\n            new_transforms[i].translation().setZero();\n            for (size_t j = 0; j < new_to_old_map[i].size(); j++) {\n                curr_weight = std::exp(-(ScalarT)(0.5)*new_to_old_map[i][j].value*sigma_inv_sq);\n                total_weight += curr_weight;\n                new_transforms[i].linear() += curr_weight*old_transforms[new_to_old_map[i][j].index].linear();\n                new_transforms[i].translation() += curr_weight*old_transforms[new_to_old_map[i][j].index].translation();\n            }\n\n            if (total_weight == (ScalarT)0.0) {\n                new_transforms[i].setIdentity();\n            } else {\n                total_weight = (ScalarT)(1.0)/total_weight;\n                new_transforms[i].linear() *= total_weight;\n                new_transforms[i].linear() = new_transforms[i].rotation();\n                new_transforms[i].translation() *= total_weight;\n            }\n        }\n    }\n\n    // Values interpreted as distances\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    inline RigidTransformationSet<ScalarT,EigenDim> resampleTransformations(const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                                                            const std::vector<NeighborSet<ScalarT>> &new_to_old_map,\n                                                                            ScalarT distance_sigma)\n    {\n        RigidTransformationSet<ScalarT,EigenDim> new_transforms;\n        resampleTransformations<ScalarT,EigenDim>(old_transforms, new_to_old_map, distance_sigma, new_transforms);\n        return new_transforms;\n    }\n\n    template <typename ScalarT, ptrdiff_t EigenDim, NeighborhoodType NT>\n    void resampleTransformations(const KDTree<ScalarT,EigenDim,KDTreeDistanceAdaptors::L2> &old_support_kd_tree,\n                                 const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                 const ConstVectorSetMatrixMap<ScalarT,EigenDim> &new_support,\n                                 const NeighborhoodSpecification<ScalarT> &nh,\n                                 ScalarT distance_sigma,\n                                 RigidTransformationSet<ScalarT,EigenDim> &new_transforms)\n    {\n        new_transforms.resize(new_support.cols());\n        const ScalarT sigma_inv_sq = (ScalarT)(1.0)/(distance_sigma*distance_sigma);\n\n        NeighborSet<ScalarT> nn;\n        ScalarT curr_weight, total_weight;\n\n#pragma omp parallel for shared (new_transforms) private (nn, curr_weight, total_weight)\n        for (size_t i = 0; i < new_transforms.size(); i++) {\n            old_support_kd_tree.template search<NT>(new_support.col(i), nh, nn);\n\n            total_weight = (ScalarT)0.0;\n            new_transforms[i].linear().setZero();\n            new_transforms[i].translation().setZero();\n            for (size_t j = 0; j < nn.size(); j++) {\n                curr_weight = std::exp(-(ScalarT)(0.5)*nn[j].value*sigma_inv_sq);\n                total_weight += curr_weight;\n                new_transforms[i].linear() += curr_weight*old_transforms[nn[j].index].linear();\n                new_transforms[i].translation() += curr_weight*old_transforms[nn[j].index].translation();\n            }\n\n            if (total_weight == (ScalarT)0.0) {\n                new_transforms[i].setIdentity();\n            } else {\n                total_weight = (ScalarT)(1.0)/total_weight;\n                new_transforms[i].linear() *= total_weight;\n                new_transforms[i].linear() = new_transforms[i].rotation();\n                new_transforms[i].translation() *= total_weight;\n            }\n        }\n    }\n\n    template <typename ScalarT, ptrdiff_t EigenDim, NeighborhoodType NT>\n    inline RigidTransformationSet<ScalarT,EigenDim> resampleTransformations(const KDTree<ScalarT,EigenDim,KDTreeDistanceAdaptors::L2> &old_support_kd_tree,\n                                                                            const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                                                            const ConstVectorSetMatrixMap<ScalarT,EigenDim> &new_support,\n                                                                            const NeighborhoodSpecification<ScalarT> &nh,\n                                                                            ScalarT distance_sigma)\n    {\n        RigidTransformationSet<ScalarT,EigenDim> new_transforms;\n        resampleTransformations<ScalarT,EigenDim,NT>(old_support_kd_tree, old_transforms, new_support, nh, distance_sigma, new_transforms);\n        return new_transforms;\n    }\n\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    void resampleTransformations(const KDTree<ScalarT,EigenDim,KDTreeDistanceAdaptors::L2> &old_support_kd_tree,\n                                 const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                 const ConstVectorSetMatrixMap<ScalarT,EigenDim> &new_support,\n                                 const NeighborhoodSpecification<ScalarT> &nh,\n                                 ScalarT distance_sigma,\n                                 RigidTransformationSet<ScalarT,EigenDim> &new_transforms)\n    {\n        switch (nh.type) {\n            case NeighborhoodType::KNN:\n                resampleTransformations<ScalarT,EigenDim,NeighborhoodType::KNN>(old_support_kd_tree, old_transforms, new_support, nh, distance_sigma, new_transforms);\n                break;\n            case NeighborhoodType::RADIUS:\n                resampleTransformations<ScalarT,EigenDim,NeighborhoodType::RADIUS>(old_support_kd_tree, old_transforms, new_support, nh, distance_sigma, new_transforms);\n                break;\n            case NeighborhoodType::KNN_IN_RADIUS:\n                resampleTransformations<ScalarT,EigenDim,NeighborhoodType::KNN_IN_RADIUS>(old_support_kd_tree, old_transforms, new_support, nh, distance_sigma, new_transforms);\n                break;\n        }\n    }\n\n    template <typename ScalarT, ptrdiff_t EigenDim>\n    inline RigidTransformationSet<ScalarT,EigenDim> resampleTransformations(const KDTree<ScalarT,EigenDim,KDTreeDistanceAdaptors::L2> &old_support_kd_tree,\n                                                                            const RigidTransformationSet<ScalarT,EigenDim> &old_transforms,\n                                                                            const ConstVectorSetMatrixMap<ScalarT,EigenDim> &new_support,\n                                                                            const NeighborhoodSpecification<ScalarT> &nh,\n                                                                            ScalarT distance_sigma)\n    {\n        RigidTransformationSet<ScalarT,EigenDim> new_transforms;\n        resampleTransformations<ScalarT,EigenDim>(old_support_kd_tree, old_transforms, new_support, nh, distance_sigma, new_transforms);\n        return new_transforms;\n    }\n\n    template <typename ScalarT>\n    inline ScalarT sqrtHuberLoss(ScalarT x, ScalarT delta = (ScalarT)1.0) {\n        const ScalarT x_abs = std::abs(x);\n        if (x_abs > delta) {\n            return std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta));\n        } else {\n            return std::sqrt((ScalarT)(0.5))*x_abs;\n        }\n    }\n\n    template <typename ScalarT>\n    inline ScalarT sqrtHuberLossDerivative(ScalarT x, ScalarT delta = (ScalarT)1.0) {\n        const ScalarT x_abs = std::abs(x);\n        if (x < (ScalarT)0.0) {\n            if (x_abs > delta) {\n                return -delta/((ScalarT)(2.0)*std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta)));\n            } else {\n                return -std::sqrt((ScalarT)(0.5));\n            }\n        } else {\n            if (x_abs > delta) {\n                return delta/((ScalarT)(2.0)*std::sqrt(delta*(x_abs - (ScalarT)(0.5)*delta)));\n            } else {\n                return std::sqrt((ScalarT)0.5);\n            }\n        }\n    }\n\n    template <typename ScalarT>\n    void computeRotationTerms(ScalarT a, ScalarT b, ScalarT c,\n                              Eigen::Matrix<ScalarT,3,3> &rot_coeffs,\n                              Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_da,\n                              Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_db,\n                              Eigen::Matrix<ScalarT,3,3> &d_rot_coeffs_dc)\n    {\n        const ScalarT sina = std::sin(a);\n        const ScalarT cosa = std::cos(a);\n        const ScalarT sinb = std::sin(b);\n        const ScalarT cosb = std::cos(b);\n        const ScalarT sinc = std::sin(c);\n        const ScalarT cosc = std::cos(c);\n\n        rot_coeffs(0,0) = cosc*cosb;\n        rot_coeffs(1,0) = -sinc*cosa + cosc*sinb*sina;\n        rot_coeffs(2,0) = sinc*sina + cosc*sinb*cosa;\n        rot_coeffs(0,1) = sinc*cosb;\n        rot_coeffs(1,1) = cosc*cosa + sinc*sinb*sina;\n        rot_coeffs(2,1) = -cosc*sina + sinc*sinb*cosa;\n        rot_coeffs(0,2) = -sinb;\n        rot_coeffs(1,2) = cosb*sina;\n        rot_coeffs(2,2) = cosb*cosa;\n\n        d_rot_coeffs_da(0,0) = (ScalarT)0.0;\n        d_rot_coeffs_da(1,0) = sinc*sina + cosc*sinb*cosa;\n        d_rot_coeffs_da(2,0) = sinc*cosa - cosc*sinb*sina;\n        d_rot_coeffs_da(0,1) = (ScalarT)0.0;\n        d_rot_coeffs_da(1,1) = -cosc*sina + sinc*sinb*cosa;\n        d_rot_coeffs_da(2,1) = -cosc*cosa - sinc*sinb*sina;\n        d_rot_coeffs_da(0,2) = (ScalarT)0.0;\n        d_rot_coeffs_da(1,2) = cosb*cosa;\n        d_rot_coeffs_da(2,2) = -cosb*sina;\n\n        d_rot_coeffs_db(0,0) = -cosc*sinb;\n        d_rot_coeffs_db(1,0) = cosc*cosb*sina;\n        d_rot_coeffs_db(2,0) = cosc*cosb*cosa;\n        d_rot_coeffs_db(0,1) = -sinc*sinb;\n        d_rot_coeffs_db(1,1) = sinc*cosb*sina;\n        d_rot_coeffs_db(2,1) = sinc*cosb*cosa;\n        d_rot_coeffs_db(0,2) = -cosb;\n        d_rot_coeffs_db(1,2) = -sinb*sina;\n        d_rot_coeffs_db(2,2) = -sinb*cosa;\n\n        d_rot_coeffs_dc(0,0) = -sinc*cosb;\n        d_rot_coeffs_dc(1,0) = -cosc*cosa - sinc*sinb*sina;\n        d_rot_coeffs_dc(2,0) = cosc*sina - sinc*sinb*cosa;\n        d_rot_coeffs_dc(0,1) = cosc*cosb;\n        d_rot_coeffs_dc(1,1) = -sinc*cosa + cosc*sinb*sina;\n        d_rot_coeffs_dc(2,1) = sinc*sina + cosc*sinb*cosa;\n        d_rot_coeffs_dc(0,2) = (ScalarT)0.0;\n        d_rot_coeffs_dc(1,2) = (ScalarT)0.0;\n        d_rot_coeffs_dc(2,2) = (ScalarT)0.0;\n    }\n\n    template <typename ScalarT, typename CorrValueT = ScalarT>\n    bool estimateDenseWarpFieldCombinedMetric3(const ConstVectorSetMatrixMap<ScalarT,3> &dst_p,\n                                               const ConstVectorSetMatrixMap<ScalarT,3> &dst_n,\n                                               const ConstVectorSetMatrixMap<ScalarT,3> &src_p,\n                                               const CorrespondenceSet<CorrValueT> &correspondences,\n                                               const std::vector<NeighborSet<ScalarT>> &regularization_neighborhoods,\n                                               RigidTransformationSet<ScalarT,3> &transforms,\n                                               ScalarT point_to_point_weight,\n                                               ScalarT point_to_plane_weight,\n                                               ScalarT stiffness_weight,\n                                               ScalarT huber_boundary = (ScalarT)(1e-6),\n                                               size_t max_gn_iter = 10,\n                                               ScalarT gn_conv_tol = (ScalarT)1e-5,\n                                               size_t max_cg_iter = 1000,\n                                               ScalarT cg_conv_tol = (ScalarT)1e-5)\n    {\n        if (dst_p.cols() != dst_n.cols() || (point_to_point_weight == (ScalarT)0.0 && point_to_plane_weight == (ScalarT)0.0)) {\n            transforms.resize(src_p.cols());\n            transforms.setIdentity();\n            return false;\n        }\n\n//        if (point_to_point_weight == (ScalarT)0.0) {\n//            // Do point-to-plane\n//            return estimateWarpFieldDensePointToPlane3D<ScalarT,CorrValueT>(dst_p, dst_n, src_p, correspondences, regularization_neighborhoods, transforms, stiffness_weight/point_to_plane_weight, max_iter, convergence_tol);\n//        }\n//\n//        if (point_to_plane_weight == (ScalarT)0.0) {\n//            // Do point-to-point\n//            return estimateWarpFieldDensePointToPoint3D<ScalarT,CorrValueT>(dst_p, src_p, correspondences, regularization_neighborhoods, transforms, stiffness_weight/point_to_point_weight, max_iter, convergence_tol);\n//        }\n\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT stiffness_weight_sqrt = std::sqrt(stiffness_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 6*src_p.cols();\n        const size_t num_data_term_equations = 4*correspondences.size();\n\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 6*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        const size_t num_regularization_equations = 6*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n        const size_t num_non_zeros = 6*num_data_term_equations + 2*num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns,num_equations);\n        At.reserve(num_non_zeros);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Outer pointers\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n#pragma omp parallel for\n        for (size_t i = 0; i < num_data_term_equations + 1; i++) {\n            outer_ptr[i] = 6*i;\n        }\n#pragma omp parallel for\n        for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n            outer_ptr[num_data_term_equations + i] = 6*num_data_term_equations + 2*i;\n        }\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (Euler angles and translation offsets per point)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(num_unknowns);\n        tforms_vec.setZero();\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,BlockDiagonalPreconditioner<ScalarT,6>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,3,3> rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc;\n        Eigen::Matrix<ScalarT,3,1> trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n            // Data term\n#pragma omp parallel for shared (At, b) private (eq_ind, nz_ind, rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc, trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s)\n            for (size_t i = 0; i < correspondences.size(); i++) {\n                const auto d = dst_p.col(correspondences[i].indexInFirst);\n                const auto n = dst_n.col(correspondences[i].indexInFirst);\n                const auto s = src_p.col(correspondences[i].indexInSecond);\n                const size_t offset = 6*correspondences[i].indexInSecond;\n\n                computeRotationTerms(tforms_vec[offset], tforms_vec[offset + 1], tforms_vec[offset + 2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n                const auto trans_coeffs = tforms_vec.template segment<3>(offset + 3);\n\n                trans_s = rot_coeffs.transpose()*s + trans_coeffs - d;\n                d_rot_da_s = d_rot_coeffs_da.transpose()*s;\n                d_rot_db_s = d_rot_coeffs_db.transpose()*s;\n                d_rot_dc_s = d_rot_coeffs_dc.transpose()*s;\n\n                eq_ind = 4*i;\n                nz_ind = 24*i;\n\n                // Point to plane\n                values[nz_ind] = (n.dot(d_rot_da_s))*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset;\n                values[nz_ind] = (n.dot(d_rot_db_s))*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 1;\n                values[nz_ind] = (n.dot(d_rot_dc_s))*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 2;\n                values[nz_ind] = n[0]*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 3;\n                values[nz_ind] = n[1]*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 4;\n                values[nz_ind] = n[2]*point_to_plane_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 5;\n                b[eq_ind++] = -(n.dot(trans_s))*point_to_plane_weight_sqrt;\n\n                // Point to point\n                values[nz_ind] = d_rot_da_s[0]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset;\n                values[nz_ind] = d_rot_db_s[0]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 1;\n                values[nz_ind] = d_rot_dc_s[0]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 2;\n                values[nz_ind] = point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 3;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 4;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 5;\n                b[eq_ind++] = -(trans_s[0])*point_to_point_weight_sqrt;\n\n                values[nz_ind] = d_rot_da_s[1]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset;\n                values[nz_ind] = d_rot_db_s[1]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 1;\n                values[nz_ind] = d_rot_dc_s[1]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 2;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 3;\n                values[nz_ind] = point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 4;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 5;\n                b[eq_ind++] = -(trans_s[1])*point_to_point_weight_sqrt;\n\n                values[nz_ind] = d_rot_da_s[2]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset;\n                values[nz_ind] = d_rot_db_s[2]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 1;\n                values[nz_ind] = d_rot_dc_s[2]*point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 2;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 3;\n                values[nz_ind] = (ScalarT)0.0;\n                inner_ind[nz_ind++] = offset + 4;\n                values[nz_ind] = point_to_point_weight_sqrt;\n                inner_ind[nz_ind++] = offset + 5;\n                b[eq_ind++] = -(trans_s[2])*point_to_point_weight_sqrt;\n            }\n\n            // Regularization term\n#pragma omp parallel for shared (At, b) private (eq_ind, nz_ind, weight, diff, d_sqrt_huber_loss)\n            for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                eq_ind = num_data_term_equations + reg_eq_ind[i];\n                nz_ind = 6*num_data_term_equations + 2*reg_eq_ind[i];\n\n                for (size_t j = 1; j < regularization_neighborhoods[i].size(); j++) {\n                    size_t s_offset = 6*regularization_neighborhoods[i][0].index;\n                    size_t n_offset = 6*regularization_neighborhoods[i][j].index;\n                    weight = stiffness_weight_sqrt*std::sqrt(regularization_neighborhoods[i][j].value);\n\n                    if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                    diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 1;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 1;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 2;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 2;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 3] - tforms_vec[n_offset + 3];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 3;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 3;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 4] - tforms_vec[n_offset + 4];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 4;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 4;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 5] - tforms_vec[n_offset + 5];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 5;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 5;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                }\n            }\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb = At*b;\n\n//            solver.compute(AtA);\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < src_p.cols(); i++) {\n                curr_delta_sq = delta.template segment<6>(6*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n//            std::cout << iter << \": \" << std::sqrt(max_delta_sq) << std::endl;\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n        }\n\n        // Convert to output format\n        transforms.resize(src_p.cols());\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear() = (Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 2],Eigen::Matrix<ScalarT,3,1>::UnitZ()) *\n                                      Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 1],Eigen::Matrix<ScalarT,3,1>::UnitY()) *\n                                      Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 0],Eigen::Matrix<ScalarT,3,1>::UnitX())).matrix();\n            transforms[i].linear() = transforms[i].rotation();\n            transforms[i].translation() = tforms_vec.template segment<3>(6*i + 3);\n        }\n\n        return has_converged;\n    }\n\n    template <typename ScalarT>\n    bool estimateSparseWarpFieldCombinedMetric3(const ConstVectorSetMatrixMap<ScalarT,3> &dst_p,\n                                                const ConstVectorSetMatrixMap<ScalarT,3> &dst_n,\n                                                const ConstVectorSetMatrixMap<ScalarT,3> &src_p,\n                                                size_t num_ctrl_points,\n                                                const std::vector<NeighborSet<ScalarT>> &src_to_ctrl_neighborhoods,\n                                                const std::vector<NeighborSet<ScalarT>> &regularization_neighborhoods,\n                                                RigidTransformationSet<ScalarT,3> &transforms,\n                                                ScalarT point_to_point_weight,\n                                                ScalarT point_to_plane_weight,\n                                                ScalarT stiffness_weight,\n                                                ScalarT huber_boundary = (ScalarT)(1e-6),\n                                                size_t max_gn_iter = 10,\n                                                ScalarT gn_conv_tol = (ScalarT)1e-5,\n                                                size_t max_cg_iter = 1000,\n                                                ScalarT cg_conv_tol = (ScalarT)1e-5)\n    {\n        if (dst_p.cols() != dst_n.cols() || dst_p.cols() != src_p.cols() || src_to_ctrl_neighborhoods.size() != src_p.cols() || (point_to_point_weight == (ScalarT)0.0 && point_to_plane_weight == (ScalarT)0.0)) {\n            transforms.resize(num_ctrl_points);\n            transforms.setIdentity();\n            return false;\n        }\n\n//        if (point_to_point_weight == (ScalarT)0.0) {\n//            // Do point-to-plane\n//            return estimateWarpFieldSparsePointToPlane3D<ScalarT>(dst_p, dst_n, src_p, src_to_ctrl_neighborhoods, ctrl_regularization_neighborhoods, ctrl_transforms, stiffness_weight/point_to_plane_weight, max_iter, convergence_tol);\n//        }\n//\n//        if (point_to_plane_weight == (ScalarT)0.0) {\n//            // Do point-to-point\n//            return estimateWarpFieldSparsePointToPoint3D<ScalarT>(dst_p, src_p, src_to_ctrl_neighborhoods, ctrl_regularization_neighborhoods, ctrl_transforms, stiffness_weight/point_to_point_weight, max_iter, convergence_tol);\n//        }\n\n        const ScalarT point_to_point_weight_sqrt = std::sqrt(point_to_point_weight);\n        const ScalarT point_to_plane_weight_sqrt = std::sqrt(point_to_plane_weight);\n        const ScalarT stiffness_weight_sqrt = std::sqrt(stiffness_weight);\n        const ScalarT gn_conv_tol_sq = gn_conv_tol*gn_conv_tol;\n\n        // Compute number of equations and unknowns\n        const size_t num_unknowns = 6*num_ctrl_points;\n        const size_t num_data_term_equations = 4*src_p.cols();\n\n        std::vector<size_t> reg_eq_ind(regularization_neighborhoods.size());\n        size_t num_reg_arcs = 0;\n        if (!regularization_neighborhoods.empty()) {\n            reg_eq_ind[0] = 0;\n            num_reg_arcs = std::max((size_t)0, regularization_neighborhoods[0].size() - 1);\n        }\n        for (size_t i = 1; i < regularization_neighborhoods.size(); i++) {\n            reg_eq_ind[i] = reg_eq_ind[i-1] + 6*std::max((size_t)0, regularization_neighborhoods[i-1].size() - 1);\n            num_reg_arcs += std::max((size_t)0, regularization_neighborhoods[i].size() - 1);\n        }\n\n        std::vector<size_t> nz_coeff_ind(src_to_ctrl_neighborhoods.size() + 1);\n        nz_coeff_ind[0] = 0;\n        for (size_t i = 1; i < src_to_ctrl_neighborhoods.size() + 1; i++) {\n            nz_coeff_ind[i] = nz_coeff_ind[i-1] + 24*src_to_ctrl_neighborhoods[i-1].size();\n        }\n\n        const size_t num_regularization_equations = 6*num_reg_arcs;\n        const size_t num_equations = num_data_term_equations + num_regularization_equations;\n        const size_t num_non_zeros = nz_coeff_ind.back() + 2*num_regularization_equations;\n\n        // Jacobian\n        Eigen::SparseMatrix<ScalarT> At(num_unknowns,num_equations);\n        At.reserve(num_non_zeros);\n        // Values\n        ScalarT * const values = At.valuePtr();\n        // Outer pointers\n        std::vector<NeighborSet<ScalarT>> src_to_ctrl_sorted(src_to_ctrl_neighborhoods);\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const outer_ptr = At.outerIndexPtr();\n#pragma omp parallel for\n        for (size_t i = 0; i < src_to_ctrl_neighborhoods.size(); i++) {\n            std::sort(src_to_ctrl_sorted[i].begin(), src_to_ctrl_sorted[i].end(), typename Neighbor<ScalarT>::IndexLessComparator());\n            const size_t offset = 6*src_to_ctrl_neighborhoods[i].size();\n            outer_ptr[4*i] = nz_coeff_ind[i];\n            outer_ptr[4*i + 1] = nz_coeff_ind[i] + offset;\n            outer_ptr[4*i + 2] = nz_coeff_ind[i] + offset + offset;\n            outer_ptr[4*i + 3] = nz_coeff_ind[i] + offset + offset + offset;\n        }\n        outer_ptr[num_data_term_equations] = nz_coeff_ind.back();\n#pragma omp parallel for\n        for (size_t i = 1; i < num_regularization_equations + 1; i++) {\n            outer_ptr[num_data_term_equations + i] = nz_coeff_ind.back() + 2*i;\n        }\n        // Inner indices\n        typename Eigen::SparseMatrix<ScalarT>::StorageIndex * const inner_ind = At.innerIndexPtr();\n\n        // Vector of (negative) residuals\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> b(num_equations);\n\n        // Vector of unknowns (Euler angles and translation offsets per point)\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> tforms_vec(num_unknowns);\n        tforms_vec.setZero();\n\n        // Sum of control point influences\n        std::vector<ScalarT> total_weight(src_to_ctrl_sorted.size());\n#pragma omp parallel for shared (total_weight)\n        for (size_t i = 0; i < src_to_ctrl_sorted.size(); i++) {\n            total_weight[i] = (ScalarT)0.0;\n            for (size_t j = 0; j < src_to_ctrl_sorted[i].size(); j++) {\n                total_weight[i] += src_to_ctrl_sorted[i][j].value;\n            }\n        }\n\n        Eigen::SparseMatrix<ScalarT> AtA;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> Atb;\n\n        // Conjugate Gradient solver\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IncompleteCholesky<ScalarT,Eigen::Lower|Eigen::Upper>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::IdentityPreconditioner> solver;\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,Eigen::DiagonalPreconditioner<ScalarT>> solver;\n//        Eigen::ConjugateGradient<Eigen::SparseMatrix<ScalarT>,Eigen::Lower|Eigen::Upper,BlockDiagonalPreconditioner<ScalarT,6>> solver;\n        solver.setMaxIterations(max_cg_iter);\n        solver.setTolerance(cg_conv_tol);\n\n        // Temporaries\n        Eigen::Matrix<ScalarT,3,3> rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc;\n        Eigen::Matrix<ScalarT,3,1> trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s;\n        Eigen::Matrix<ScalarT,3,1> angles_curr, trans_curr;\n        Eigen::Matrix<ScalarT,Eigen::Dynamic,1> delta;\n        ScalarT weight, diff, d_sqrt_huber_loss, curr_delta_sq, max_delta_sq;\n        size_t eq_ind, nz_ind;\n\n        bool has_converged = false;\n        size_t iter = 0;\n        while (iter < max_gn_iter) {\n            // Data term\n#pragma omp parallel for shared (At, b) private (eq_ind, nz_ind, weight, angles_curr, trans_curr, rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc, trans_s, d_rot_da_s, d_rot_db_s, d_rot_dc_s)\n            for (size_t i = 0; i < src_p.cols(); i++) {\n                // Compute weighted influence from control nodes\n                angles_curr.setZero();\n                trans_curr.setZero();\n                for (size_t j = 0; j < src_to_ctrl_sorted[i].size(); j++) {\n                    const size_t offset = 6*src_to_ctrl_sorted[i][j].index;\n                    angles_curr += src_to_ctrl_sorted[i][j].value*tforms_vec.template segment<3>(offset);\n                    trans_curr += src_to_ctrl_sorted[i][j].value*tforms_vec.template segment<3>(offset + 3);\n                }\n                if (total_weight[i] != (ScalarT)0.0) {\n                    weight = (ScalarT)(1.0)/total_weight[i];\n                    angles_curr *= weight;\n                    trans_curr *= weight;\n                }\n\n                const auto d = dst_p.col(i);\n                const auto n = dst_n.col(i);\n                const auto s = src_p.col(i);\n\n                computeRotationTerms(angles_curr[0], angles_curr[1], angles_curr[2], rot_coeffs, d_rot_coeffs_da, d_rot_coeffs_db, d_rot_coeffs_dc);\n\n                trans_s = rot_coeffs.transpose()*s + trans_curr - d;\n                d_rot_da_s = d_rot_coeffs_da.transpose()*s;\n                d_rot_db_s = d_rot_coeffs_db.transpose()*s;\n                d_rot_dc_s = d_rot_coeffs_dc.transpose()*s;\n\n                eq_ind = 4*i;\n\n                for (size_t j = 0; j < src_to_ctrl_sorted[i].size(); j++) {\n                    const size_t offset = 6*src_to_ctrl_sorted[i][j].index;\n                    weight = (total_weight[i] == (ScalarT)0.0) ? (ScalarT)0.0 : src_to_ctrl_sorted[i][j].value/total_weight[i];\n//                    weight = src_to_ctrl_sorted[i][j].value/total_weight[i];\n\n                    // Point to plane\n                    nz_ind = outer_ptr[eq_ind] + 6*j;\n                    values[nz_ind] = (n.dot(d_rot_da_s))*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset;\n                    values[nz_ind] = (n.dot(d_rot_db_s))*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 1;\n                    values[nz_ind] = (n.dot(d_rot_dc_s))*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 2;\n                    values[nz_ind] = n[0]*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 3;\n                    values[nz_ind] = n[1]*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 4;\n                    values[nz_ind] = n[2]*weight*point_to_plane_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 5;\n\n                    // Point to point\n                    nz_ind = outer_ptr[eq_ind + 1] + 6*j;\n                    values[nz_ind] = d_rot_da_s[0]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset;\n                    values[nz_ind] = d_rot_db_s[0]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 1;\n                    values[nz_ind] = d_rot_dc_s[0]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 2;\n                    values[nz_ind] = weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 3;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 4;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 5;\n\n                    nz_ind = outer_ptr[eq_ind + 2] + 6*j;\n                    values[nz_ind] = d_rot_da_s[1]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset;\n                    values[nz_ind] = d_rot_db_s[1]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 1;\n                    values[nz_ind] = d_rot_dc_s[1]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 2;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 3;\n                    values[nz_ind] = weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 4;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 5;\n\n                    nz_ind = outer_ptr[eq_ind + 3] + 6*j;\n                    values[nz_ind] = d_rot_da_s[2]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset;\n                    values[nz_ind] = d_rot_db_s[2]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 1;\n                    values[nz_ind] = d_rot_dc_s[2]*weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 2;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 3;\n                    values[nz_ind] = (ScalarT)0.0;\n                    inner_ind[nz_ind++] = offset + 4;\n                    values[nz_ind] = weight*point_to_point_weight_sqrt;\n                    inner_ind[nz_ind++] = offset + 5;\n                }\n\n                weight = (total_weight[i] == (ScalarT)0.0) ? (ScalarT)0.0 : (ScalarT)1.0;\n//                weight = (ScalarT)1.0;\n\n                // Point to plane\n                b[eq_ind] = -(n.dot(trans_s))*weight*point_to_plane_weight_sqrt;\n                // Point to point\n                b[eq_ind + 1] = -(trans_s[0])*weight*point_to_point_weight_sqrt;\n                b[eq_ind + 2] = -(trans_s[1])*weight*point_to_point_weight_sqrt;\n                b[eq_ind + 3] = -(trans_s[2])*weight*point_to_point_weight_sqrt;\n            }\n\n            // Regularization term\n#pragma omp parallel for shared (At, b) private (eq_ind, nz_ind, weight, diff, d_sqrt_huber_loss)\n            for (size_t i = 0; i < regularization_neighborhoods.size(); i++) {\n                eq_ind = num_data_term_equations + reg_eq_ind[i];\n                nz_ind = nz_coeff_ind.back() + 2*reg_eq_ind[i];\n\n                for (size_t j = 1; j < regularization_neighborhoods[i].size(); j++) {\n                    size_t s_offset = 6*regularization_neighborhoods[i][0].index;\n                    size_t n_offset = 6*regularization_neighborhoods[i][j].index;\n                    weight = stiffness_weight_sqrt*std::sqrt(regularization_neighborhoods[i][j].value);\n\n                    if (n_offset < s_offset) std::swap(s_offset, n_offset);\n\n                    diff = tforms_vec[s_offset + 0] - tforms_vec[n_offset + 0];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 1] - tforms_vec[n_offset + 1];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 1;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 1;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 2] - tforms_vec[n_offset + 2];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 2;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 2;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 3] - tforms_vec[n_offset + 3];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 3;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 3;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 4] - tforms_vec[n_offset + 4];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 4;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 4;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n\n                    diff = tforms_vec[s_offset + 5] - tforms_vec[n_offset + 5];\n                    d_sqrt_huber_loss = weight*sqrtHuberLossDerivative<ScalarT>(diff, huber_boundary);\n                    values[nz_ind] = d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = s_offset + 5;\n                    values[nz_ind] = -d_sqrt_huber_loss;\n                    inner_ind[nz_ind++] = n_offset + 5;\n                    b[eq_ind++] = -weight*sqrtHuberLoss<ScalarT>(diff, huber_boundary);\n                }\n            }\n\n\n//            Eigen::SparseMatrix<double> AtA = (At*At.transpose()).template cast<double>();\n//            Eigen::VectorXd Atb = (At*b).template cast<double>();\n//\n//            ScalarT shift = std::sqrt(std::numeric_limits<ScalarT>::epsilon());\n//            Eigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver;\n//            solver.compute(AtA);\n//            while (solver.info() != Eigen::Success) {\n//                solver.setShift(shift);\n//                solver.compute(AtA);\n//                shift *= 5.0;\n//            }\n//            delta = solver.solve(Atb).template cast<ScalarT>();\n//            tforms_vec += delta;\n\n\n            // Solve linear system using CG\n            AtA = At*At.transpose();\n            Atb = At*b;\n\n//            solver.compute(AtA);\n            if (iter == 0) solver.analyzePattern(AtA);\n            solver.factorize(AtA);\n            delta = solver.solve(Atb);\n            tforms_vec += delta;\n\n            iter++;\n\n            // Check for convergence\n            max_delta_sq = (ScalarT)0.0;\n#pragma omp parallel for private (curr_delta_sq) reduction (max: max_delta_sq)\n            for (size_t i = 0; i < num_ctrl_points; i++) {\n                curr_delta_sq = delta.template segment<6>(6*i).squaredNorm();\n                if (curr_delta_sq > max_delta_sq) max_delta_sq = curr_delta_sq;\n            }\n\n//            std::cout << iter << \": \" << std::sqrt(max_delta_sq) << std::endl;\n\n            if (max_delta_sq < gn_conv_tol_sq) {\n                has_converged = true;\n                break;\n            }\n\n        }\n\n        // Convert to output format\n        transforms.resize(num_ctrl_points);\n#pragma omp parallel for\n        for (size_t i = 0; i < transforms.size(); i++) {\n            transforms[i].linear() = (Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 2],Eigen::Matrix<ScalarT,3,1>::UnitZ()) *\n                                      Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 1],Eigen::Matrix<ScalarT,3,1>::UnitY()) *\n                                      Eigen::AngleAxis<ScalarT>(tforms_vec[6*i + 0],Eigen::Matrix<ScalarT,3,1>::UnitX())).matrix();\n            transforms[i].linear() = transforms[i].rotation();\n            transforms[i].translation() = tforms_vec.template segment<3>(6*i + 3);\n        }\n\n        return has_converged;\n    }\n\n    template <typename ScalarT, typename CorrValueT = ScalarT>\n    bool estimateSparseWarpFieldCombinedMetric3(const ConstVectorSetMatrixMap<ScalarT,3> &dst_p,\n                                                const ConstVectorSetMatrixMap<ScalarT,3> &dst_n,\n                                                const ConstVectorSetMatrixMap<ScalarT,3> &src_p,\n                                                const CorrespondenceSet<CorrValueT> &corr,\n                                                size_t num_ctrl_points,\n                                                const std::vector<NeighborSet<ScalarT>> &src_to_ctrl_neighborhoods,\n                                                const std::vector<NeighborSet<ScalarT>> &regularization_neighborhoods,\n                                                RigidTransformationSet<ScalarT,3> &transforms,\n                                                ScalarT point_to_point_weight,\n                                                ScalarT point_to_plane_weight,\n                                                ScalarT stiffness_weight,\n                                                ScalarT huber_boundary = (ScalarT)(1e-6),\n                                                size_t max_gn_iter = 10,\n                                                ScalarT gn_conv_tol = (ScalarT)1e-5,\n                                                size_t max_cg_iter = 1000,\n                                                ScalarT cg_conv_tol = (ScalarT)1e-5)\n    {\n        VectorSet<ScalarT,3> dst_p_corr(3, corr.size());\n        VectorSet<ScalarT,3> dst_n_corr(3, corr.size());\n        VectorSet<ScalarT,3> src_p_corr(3, corr.size());\n        std::vector<NeighborSet<ScalarT>> src_to_ctrl_neighborhoods_corr(corr.size());\n#pragma omp parallel for\n        for (size_t i = 0; i < corr.size(); i++) {\n            dst_p_corr.col(i) = dst_p.col(corr[i].indexInFirst);\n            dst_n_corr.col(i) = dst_n.col(corr[i].indexInFirst);\n            src_p_corr.col(i) = src_p.col(corr[i].indexInSecond);\n            src_to_ctrl_neighborhoods_corr[i] = src_to_ctrl_neighborhoods[corr[i].indexInSecond];\n        }\n        return estimateSparseWarpFieldCombinedMetric3<ScalarT>(dst_p_corr, dst_n_corr, src_p_corr, num_ctrl_points,\n                                                               src_to_ctrl_neighborhoods_corr,\n                                                               regularization_neighborhoods,\n                                                               transforms,\n                                                               point_to_point_weight, point_to_plane_weight,\n                                                               stiffness_weight, huber_boundary,\n                                                               max_gn_iter, gn_conv_tol,\n                                                               max_cg_iter, cg_conv_tol);\n    }\n}\n", "meta": {"hexsha": "24154f8eee2cfe839f2f5b7401b1dee959c5e03a", "size": 51278, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cilantro/non_rigid_registration_utilities.hpp", "max_stars_repo_name": "eglrp/cilantro", "max_stars_repo_head_hexsha": "669da069c3ec06006d1347eca7b67cd93a9e9801", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cilantro/non_rigid_registration_utilities.hpp", "max_issues_repo_name": "eglrp/cilantro", "max_issues_repo_head_hexsha": "669da069c3ec06006d1347eca7b67cd93a9e9801", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cilantro/non_rigid_registration_utilities.hpp", "max_forks_repo_name": "eglrp/cilantro", "max_forks_repo_head_hexsha": "669da069c3ec06006d1347eca7b67cd93a9e9801", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-22T06:53:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-22T06:53:28.000Z", "avg_line_length": 54.4352441614, "max_line_length": 235, "alphanum_fraction": 0.5680408752, "num_tokens": 12265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.5528576827738294}}
{"text": "#include \"gaussian.h\"\n#include \"bvnl.h\"\n#include <algorithm>\n#include <boost/math/special_functions/erf.hpp>\n\nconst I epsilon_interval(-std::numeric_limits<double>::epsilon(),\n\t\t\t\t\t\t std::numeric_limits<double>::epsilon());\n\n// Add a certain number of epsilons as error to an interval\nI nudge(const I& x, int epsilons) {\n  I eps = (double)epsilons * epsilon_interval;\n  return x * (1.0 + eps) + eps;\n}\n\nI erf(const I& x) { \n\t// Built in erf should have an error of <= epsilon.\n\t// We overestimate with 10 epsilons.\n\treturn nudge(I(erf(x.lower()), erf(x.upper())), 10);\n}\n\nI erf_inv(const I& x) { \n\t// erf_inv has an error of <= 2 epsilons according to Boost docs.\n\t// We overestimate with 20 epsilons.\n\treturn nudge(I(boost::math::erf_inv(x.lower()),\n\t\t\t\t   boost::math::erf_inv(x.upper())), 20);\n}\n\nconst I sqrt2 = sqrt(I(2.0));\n\nI Phi(const I& x) {\n  return (1.0 + erf(x/sqrt2))/2.0;\n}\n\nI Phi_inv(const I& x) {\n  return sqrt2*erf_inv(2.0*x-1.0);\n}\n\n\nI bvnl(const I& dh, const I& dk, const I& r) {\n  if (empty(dh) || empty(dk) || empty(r)) return I::empty();\n  // Assumes Fact: bvnl is monotone in all three parameters\n  I ans = I(bvnl_down(dh.lower(), dk.lower(), r.lower()), \n\t\t\tbvnl_up(dh.upper(), dk.upper(), r.upper()));\n  return ans;\n}\n\nI Gamma(const I& q1, const I& q2, const I& rho) {\n  return bvnl(Phi_inv(q1), Phi_inv(q2), rho);\n}\n\ndouble Gamma_up(double q1, double q2, double rho) {\n\t// Assumes Fact: Gamma is monotone in all three parameters\n\treturn bvnl_up(Phi_inv(q1).upper(), Phi_inv(q2).upper(), rho);\n}\n\n\n// Naive implementation of Lambda_{\\trho}(r1, r2)\n// Has unnecessary loss of precision due to repeated occurrences of r1 and r2\nI Lambda_naive(const I& r1, const I &r2, const I& trho) {\n  return 2.0*Gamma((1.0-r1)/2.0, (1.0-r2)/2.0, trho) + (r1+r2)/2.0;\n}\n\n\ndouble Lambda_up(double r1, double r2, double trho) {\n\t// TODO assumes something about error\n\treturn 2.0*Gamma_up((1.0-r1)/2.0 + 1e-15, (1.0-r2)/2.0 + 1e-15, trho) + (r1+r2)/2.0 + 1e-15;\n}\n\n\n// Upper bound on Lambda which gives a good approximation for trho close to 0.\n// Precondition: trho.upper() >= 0\ndouble Lambda_up_near_zero(const I& r1, const I& r2, const I& trho) {\n\t// Assumes Lemma 2.7, which implies Lambda_trho(r1, r2) <= (1+r1*r2)/2 + 4*|trho|\n\treturn ((1.0+r1*r2) / 2.0 + 4.0 * trho).upper();\n}\n\n// The \"g\" function from Lemma 5.5 of the paper\nI Lambda_g(const I& r, const I& trho) {\n  return 1.0 - 2.0*Phi(Phi_inv((1.0-r)/2.0) / trho);\n}\n\n// More accurate implementation of Lambda_{\\trho}(r1, r2).\n// Uses Lemma 5.5 of paper which characterizes the extreme points of\n// Lambda_{\\trho}(I_1, I_2).  In fact for performance reasons we only\n// use it for the upper bound, which is what we need a good estimate\n// on in order to get a good lower bound on alpha.  For the lower\n// bound on Lambda we just use the naive bound.\nI Lambda_precise(const I& r1, const I &r2, const I& trho) {\n  I ans = Lambda_naive(r1, r2, trho);\n\n  double r1_lo = r1.lower(), r1_hi = r1.upper();\n  double r2_lo = r2.lower(), r2_hi = r2.upper();\n\n  // The four combinations of extreme points for r1, r2.\n  // Assumes Fact: Lambda is monotone in trho\n  double ub = std::max(std::max(Lambda_up(r1_lo, r2_lo, trho.upper()),\n\t\t\t\t\t\t\t\tLambda_up(r1_lo, r2_hi, trho.upper())),\n\t\t\t\t\t   std::max(Lambda_up(r1_hi, r2_lo, trho.upper()),\n\t\t\t\t\t\t\t\tLambda_up(r1_hi, r2_hi, trho.upper())));\n\n  if (posgt(trho, 0.0)) {\n\t  // When trho is (possibly) positive, Lambda is convex and there\n\t  // are five more possibilities for the upper bound.\n\t  I z;\n\t  \n\t  // r1 at extreme point, r2 = g(r1)\n\t  z = hull(z, Lambda_naive(r1_lo, \n\t\t\t\t\t\t\t   intersect(r2, Lambda_g(r1_lo, trho.upper())), \n\t\t\t\t\t\t\t   trho.upper()));\n\t  z = hull(z, Lambda_naive(r1_hi, \n\t\t\t\t\t\t\t   intersect(r2, Lambda_g(r1_hi, trho.upper())), \n\t\t\t\t\t\t\t   trho.upper()));\n\t  \n\t  // r2 at extreme point, r1 = g(r2)\n\t  z = hull(z, Lambda_naive(intersect(r1, Lambda_g(r2_lo, trho.upper())),\n\t\t\t\t\t\t\t   r2_lo,\n\t\t\t\t\t\t\t   trho.upper()));\n\t  z = hull(z, Lambda_naive(intersect(r1, Lambda_g(r2_hi, trho.upper())),\n\t\t\t\t\t\t\t   r2_hi,\n\t\t\t\t\t\t\t   trho.upper()));\n\t  \n\t  // (0, 0)\n\t  if (poseq(r1, 0.0) && poseq(r2, 0.0))\n\t\t  z = hull(z, Lambda_up(0.0, 0.0, trho.upper()));\n\t  \n\t  // If trho is close to zero, the computation of the \"g\" function\n\t  // of Lemma 5.5 is quite unstable and sometimes gives poor\n\t  // bounds.  To safeguard against these cases we also use the\n\t  // upper bound provided by Lemma 2.7 which gives good bounds for\n\t  // trho close to 0.\n\t  ub = std::max(ub, std::min(z.upper(), Lambda_up_near_zero(r1, r2, trho)));\n  }\n  \n  return intersect(ans, I(0.0, std::min(ub, 1.0)));\n}\n\n\nI Lambda(const I& r1, const I& r2, const I& trho) {\n\treturn Lambda_precise(r1, r2, trho);\n}\n", "meta": {"hexsha": "1348b8f0d0d43ef59802dd03562a0923ae7c0e80", "size": 4687, "ext": "cc", "lang": "C++", "max_stars_repo_path": "proof/gaussian.cc", "max_stars_repo_name": "austrin/max-bisection-analysis", "max_stars_repo_head_hexsha": "8dd8c39693a86a6132c89f42f45dbd9bfef4ae46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T07:56:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T07:56:57.000Z", "max_issues_repo_path": "proof/gaussian.cc", "max_issues_repo_name": "austrin/max-bisection-analysis", "max_issues_repo_head_hexsha": "8dd8c39693a86a6132c89f42f45dbd9bfef4ae46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "proof/gaussian.cc", "max_forks_repo_name": "austrin/max-bisection-analysis", "max_forks_repo_head_hexsha": "8dd8c39693a86a6132c89f42f45dbd9bfef4ae46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-09T03:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-09T03:45:47.000Z", "avg_line_length": 33.2411347518, "max_line_length": 93, "alphanum_fraction": 0.6398549179, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.5528576777096629}}
{"text": "#pragma once\n\n#include <boost/multi_array.hpp>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n// ------------------------------------------------------------\n#include \"base/hash_specializations.hpp\"\n#include \"laguerren_impl.hpp\"\n\ntemplate <typename NUMERIC>\nclass LaguerreNW\n{\n public:\n  typedef NUMERIC numeric_t;\n\n public:\n  LaguerreNW(int K)\n      : Y_(K + 1)\n      , K_(K)\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};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreNW<NUMERIC>::compute(const std::vector<numeric_t> &x)\n{\n  compute(x.data(), x.size());\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nvoid\nLaguerreNW<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#pragma omp parallel for\n    for (size_t xi = 0; xi < n; ++xi) {\n      numeric_t expw = ::math::exp(-0.5 * x[xi]);\n      Y_[alpha][0][xi] = boost::math::laguerren(0, alpha, x[xi]) * expw;\n      Y_[alpha][1][xi] = boost::math::laguerren(1, alpha, x[xi]) * expw;\n    }\n\n    for (unsigned int k = 2; k <= K_ / 2; ++k) {\n#pragma omp parallel for\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}\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC>\nconst NUMERIC *\nLaguerreNW<NUMERIC>::get(unsigned int k, unsigned int alpha) const\n{\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\nLaguerreNW<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 << \" LaguerreNW uses \" << nentries * sizeof(NUMERIC) / 1e6 << \" MB\" << std::endl;\n}\n", "meta": {"hexsha": "0bef48d57d6e288153dd420ea9f25400408e85c3", "size": 2596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/laguerrenw.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/laguerrenw.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/laguerrenw.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": 25.4509803922, "max_line_length": 93, "alphanum_fraction": 0.5396764253, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.5528576675813294}}
{"text": "// Wheel-NeuralNetwork.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"NeuralNetwork.h\"\n#include \"CSVParser.h\"\n#define PRINT(x) std::cout << x << std::endl\nint main()\n{\n\tDataPreprocessing::CSVParser data_parser(\"data.csv\");\n\tauto data = data_parser.GetParsedResult();\n\n\t//Optimal layers for XOR problem: 2 3 2\n\n\tstd::vector<Layer> layers;\n\tlayers.emplace_back(2);\n\tlayers.emplace_back(4);\n\t//layers.emplace_back(2);\n\n\tlayers.emplace_back(1);\n\n\t//std::vector<float> inputs{1,1};\n\t//std::vector<float> target{ 0 };\n\tNeuralNetwork nn(layers);\n\tsrand((unsigned int)time(NULL));\n\tfor (int i = 0; i < 50000; i++) {\n\t\tstd::vector<float> inputs;\n\t\tstd::vector<float> target;\n\t\tint x2 = ((double)rand() / (RAND_MAX)) > 0.5 ? 1 : 0;\n\t\tint x1 = ((double)rand() / (RAND_MAX)) > 0.5 ? 1 : 0;\n\t\t\n\t\tint y = 1;\n\n\t\t//XOR\n\t\tif (x1 == x2)\n\t\t\ty = 1;\n\t\telse\n\t\t{\n\t\t\ty = 0;\n\t\t}\n\n\t\t////OR\n\t\t//if (x1 == 1 || x2 == 1)\n\t\t//\ty = 1;\n\t\t//else\n\t\t//{\n\t\t//\ty = 0;\n\t\t//}\n\n\t\t////AND\n\t\t//if (x1 == 1 && x2 == 1)\n\t\t//\ty = 1;\n\t\t//else\n\t\t//{\n\t\t//\ty = 0;\n\t\t//}\n\n\t\t/*PRINT(\"Inputs:\");\n\t\tPRINT(x1);\n\t\tPRINT(x2);\n\t\tPRINT(\"LABEL\");\n\t\tPRINT(y);*/\n\t\tinputs.emplace_back(x1);\n\t\tinputs.emplace_back(x2);\n\n\t\ttarget.emplace_back(y);\n\n\t\tnn.SetInput(inputs);\n\t\tnn.Train(inputs, target);\n\t}\n\n\t/*nn.SetInput(inputs);\n\tnn.Train(inputs, target);*/\n\n\t/*for (int j = 0; j < 300; j++) {\n\t\tfor (int i = 1; i < data.size(); ++i)\n\t\t{\n\t\t\tstd::vector<float> inputs;\n\t\t\tstd::vector<float> target;\n\t\t\tinputs.emplace_back(std::atof(data[i][0].c_str()));\n\t\t\tinputs.emplace_back(std::atof(data[i][1].c_str()));\n\n\t\t\tint label = std::atoi(data[i][2].c_str());\n\t\t\ttarget.emplace_back(label);\n\t\t\tstd::cout << \"training... \" << std::endl;\n\t\t\tnn.SetInput(inputs);\n\t\t\tnn.Train(inputs, target);\n\n\t\t}\n\t}*/\n\n\tstd::vector<std::vector<float>> all_data_to_predict;\n\tall_data_to_predict.emplace_back(std::vector<float>{ 0, 1 });\n\tall_data_to_predict.emplace_back(std::vector<float>{ 1, 0 });\n\tall_data_to_predict.emplace_back(std::vector<float>{ 1, 1 });\n\tall_data_to_predict.emplace_back(std::vector<float>{ 0, 0 });\n\n\tfor (int i = 0; i < all_data_to_predict.size(); ++i)\n\t{\n\t\tstd::cout << \"prediction: \" << nn.predict(all_data_to_predict[i])[0] << std::endl;\n\t}\n}\n", "meta": {"hexsha": "ed096fa4fb6a7d2cbb347d56bf2bcf63d98314fc", "size": 2280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wheel-DLFramework/main.cpp", "max_stars_repo_name": "KenKenhehe/Wheel-DeeplearningFramework", "max_stars_repo_head_hexsha": "df2ab038c3a1ed703f2e4236a96525fab49db6ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Wheel-DLFramework/main.cpp", "max_issues_repo_name": "KenKenhehe/Wheel-DeeplearningFramework", "max_issues_repo_head_hexsha": "df2ab038c3a1ed703f2e4236a96525fab49db6ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Wheel-DLFramework/main.cpp", "max_forks_repo_name": "KenKenhehe/Wheel-DeeplearningFramework", "max_forks_repo_head_hexsha": "df2ab038c3a1ed703f2e4236a96525fab49db6ab", "max_forks_repo_licenses": ["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.9230769231, "max_line_length": 109, "alphanum_fraction": 0.6074561404, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.552857665995168}}
{"text": "/*\n * Copyright 2018 Esref Ozdemir\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 <algorithm>\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\n#include \"convex_stats.hpp\"\n#include <utils.hpp>\n\nusing namespace feature;\n\nnamespace bg = boost::geometry;\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point;\ntypedef bg::model::multi_point<point> multi_point;\n\n/**\n * Find the convex hull of Player sequence between [begin, end) and return the\n * indices of Player objects that are on the convex hull.\n */\n/**\n * @brief Find the convex hull of a Player range [begin, end) and return the\n * indices of Player objects that are on the convex hull.\n *\n * This function computes the convex hull of Player objects given in [begin,\n * end) and then finds the indices of points on the hull by doing an \\f$O(NK)\\f$\n * time worst-case search where \\f$K\\f$ is the size of the convex hull and\n * \\f$N\\f$ is the number of total players.\n *\n * @param begin Beginning of the player range [begin, end).\n * @param end End of the player range [begin, end).\n *\n * @return Indices of the players on the convex hull.\n *\n * @todo Reduce index finding time complexity to \\f$O(KlogN)\\f$ by sorting the\n * points. We should do this if \\f$NK \\gg KlogN\\f$ which is not the case for\n * small \\f$N\\f$.\n */\nstatic std::vector<int> convex_indices(player_cit begin, player_cit end) {\n    // construct points\n    multi_point points;\n    for (auto it = begin; it != end; ++it) {\n        bg::append(points, point(it->x, it->y));\n    }\n    // compute convex hull\n    multi_point hull;\n    bg::convex_hull(points, hull);\n\n    // find the index of each point on the hull by searching for it in the\n    // original range.\n    std::vector<int> indices;\n    // bg::convex_hull puts the first point twice. Don't count it in the end.\n    for (auto it = boost::begin(hull); it != std::prev(boost::end(hull));\n         ++it) {\n        auto point_it = std::find_if(\n            boost::begin(points), boost::end(points), [it](const point& p) {\n                return close(p.get<0>(), it->get<0>()) &&\n                       close(p.get<1>(), it->get<1>());\n            });\n        indices.push_back(std::distance(boost::begin(points), point_it));\n    }\n\n    return indices;\n}\n\n/**\n * Constructs a sequence of Point objects from Player objects at the given\n * indices of the given Player sequence starting at begin.\n */\n\n/**\n * @brief Construct a vector of point types at the given indices and return it.\n *\n * This function filters the Players at the given indices in the range that\n * starts at begin and returns them as a vector of point types.\n *\n * @param indices Indices of points to return as a separate vector.\n * @param begin Beginning of a Player range.\n */\nstatic std::vector<point> points_from_indices(const std::vector<int>& indices,\n                                              player_cit begin) {\n    std::vector<point> res(indices.size());\n    std::transform(indices.begin(), indices.end(), res.begin(),\n                   [begin](const int i) {\n                       auto player = std::next(begin, i);\n                       return point(player->x, player->y);\n                   });\n\n    return res;\n}\n\nnamespace feature {\nnamespace details {\n\nvoid convex_stats(player_cit begin, player_cit end,\n                  std::vector<double>::iterator speed_begin,\n                  const std::string& prefix, std::vector<double>& features) {\n    // initialize features with default values\n    double min_x = feature::default_value();\n    double min_y = feature::default_value();\n    double max_x = feature::default_value();\n    double max_y = feature::default_value();\n    double max_dist = feature::default_value();\n    double min_dist = feature::default_value();\n    double max_speed = feature::default_value();\n    point center(feature::default_value(), feature::default_value());\n\n    // if there are at least 3 points (no convex hull of 2 or less points)\n    if (std::distance(begin, end) > 2) {\n        // get convex indices and corresponding points\n        std::vector<int> indices = convex_indices(begin, end);\n        std::vector<point> convex_points = points_from_indices(indices, begin);\n\n        min_x = std::numeric_limits<double>::max();\n        min_y = std::numeric_limits<double>::max();\n        max_x = std::numeric_limits<double>::lowest();\n        max_y = std::numeric_limits<double>::lowest();\n        center = point(0, 0);\n        double size = static_cast<double>(convex_points.size());\n\n        // calculate min/max x/y and center\n        for (const auto& point : convex_points) {\n            min_x = std::min(min_x, point.get<0>());\n            min_y = std::min(min_y, point.get<1>());\n            max_x = std::max(max_x, point.get<0>());\n            max_y = std::max(max_y, point.get<1>());\n\n            center.set<0>(center.get<0>() + point.get<0>() / size);\n            center.set<1>(center.get<1>() + point.get<1>() / size);\n        }\n\n        // farDistance, closestDistance\n        max_dist = std::numeric_limits<double>::lowest();\n        min_dist = std::numeric_limits<double>::max();\n        for (const auto& point : convex_points) {\n            double distance = dist(point.get<0>(), point.get<1>(),\n                                   center.get<0>(), center.get<1>());\n            max_dist = std::max(max_dist, distance);\n            min_dist = std::min(min_dist, distance);\n        }\n\n        // maxSpeed\n        max_speed = std::numeric_limits<double>::lowest();\n        for (int i : indices) {\n            double speed = *std::next(speed_begin, i);\n            max_speed = std::max(max_speed, speed);\n        }\n    }\n    // write the results\n    features[name_to_index(prefix + \"ConvexMaxX\")] = max_x;\n    features[name_to_index(prefix + \"ConvexMinX\")] = min_x;\n    features[name_to_index(prefix + \"ConvexMaxY\")] = max_y;\n    features[name_to_index(prefix + \"ConvexMinY\")] = min_y;\n    features[name_to_index(prefix + \"ConvexCenterX\")] = center.get<0>();\n    features[name_to_index(prefix + \"ConvexCenterY\")] = center.get<1>();\n    features[name_to_index(prefix + \"ConvexMaxSpeed\")] = max_speed;\n    features[name_to_index(prefix + \"ConvexFarDistance\")] = max_dist;\n    features[name_to_index(prefix + \"ConvexClosestDistance\")] = min_dist;\n}\n\n}; // namespace details\n}; // namespace feature\n", "meta": {"hexsha": "4a8be02801ceeff687667a02650eabb773ff1bfc", "size": 6930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_feature/src/feature/stats/convex_stats.cpp", "max_stars_repo_name": "eozd/SIU-2018", "max_stars_repo_head_hexsha": "81df1760be6a26c48d4140511ab194ffc8d700d7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-27T04:07:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T04:07:56.000Z", "max_issues_repo_path": "cpp_feature/src/feature/stats/convex_stats.cpp", "max_issues_repo_name": "eozd/SIU-2018", "max_issues_repo_head_hexsha": "81df1760be6a26c48d4140511ab194ffc8d700d7", "max_issues_repo_licenses": ["Apache-2.0"], "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_feature/src/feature/stats/convex_stats.cpp", "max_forks_repo_name": "eozd/SIU-2018", "max_forks_repo_head_hexsha": "81df1760be6a26c48d4140511ab194ffc8d700d7", "max_forks_repo_licenses": ["Apache-2.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.7150837989, "max_line_length": 80, "alphanum_fraction": 0.6388167388, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5527838322858459}}
{"text": "\n#include \"pressio_apps.hpp\"\n#include <random>\n#include <Eigen/SVD>\n\nusing gen_t\t   = std::mt19937;\nusing rand_distr_t = std::uniform_real_distribution<double>;\n\nconstexpr double eps = 1e-7;\nstd::string checkStr {\"PASSED\"};\n\n// range of Prandtl number\nconstexpr std::array<double,2> Pr_range{{1.0, 5.0}};\n\n// range of Reynolds number\nconstexpr std::array<double,2> Re_range{{10., 100.0}};\n\nvoid readMatrixFromFile(std::string filename,\n\t\t\tstd::vector<std::vector<double>> & A0,\n\t\t\tint ncols){\n  assert( A0.empty() );\n  std::ifstream source;\n  source.open( filename, std::ios_base::in);\n  std::string line, colv;\n  std::vector<double> tmpv(ncols);\n  while (std::getline(source, line) ){\n    std::istringstream in(line);\n    for (int i=0; i<ncols; i++){\n      in >> colv;\n      tmpv[i] = atof(colv.c_str());\n    }\n    A0.emplace_back(tmpv);\n  }\n  source.close();\n}\n\nint main(int argc, char *argv[]){\n  using fom_t\t = ::pressio::apps::SteadyLinAdvDiff2dEpetra;\n\n  int rank;\n  MPI_Init(&argc,&argv);\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n  Epetra_MpiComm Comm(MPI_COMM_WORLD);\n  assert(Comm.NumProc() == 1);\n\n  //---------------------------------------\n  // generate random samples of Parameters\n\n  // random number generator (seeded)\n  unsigned int seed = 1343234343;\n  std::mt19937 engine(seed);\n  rand_distr_t distr(0., 1.0);\n  auto genPr = [&distr, &engine](){\n\t\t auto c1 = Pr_range[1]-Pr_range[0];\n\t\t auto c2 = Pr_range[0];\n\t\t return c1 * distr(engine) + c2;\n\t     };\n\n  auto genRe = [&distr, &engine](){\n\t\t auto c1 = Re_range[1]-Re_range[0];\n\t\t auto c2 = Re_range[0];\n\t\t return c1 * distr(engine) + c2;\n\t     };\n\n  // number of sample to take\n  constexpr int nSamples = 5;\n\n  // fill for Prandtl\n  std::vector<double> PrS(nSamples);\n  std::generate(PrS.begin(), PrS.end(), genPr);\n\n  // fill for Reynolds\n  std::vector<double> ReS(nSamples);\n  std::generate(ReS.begin(), ReS.end(), genRe);\n\n  if(rank==0){\n    auto it1 = PrS.begin();\n    auto it2 = ReS.begin();\n    for( ;it2<ReS.end(); it1++, it2++)\n      std::cout << std::setprecision(15)\n\t\t<< *it1 << \" \" << *it2\n\t\t<< \"\\n\";\n  }\n\n  //---------------------------------------\n  // fix discretization for all samples\n  const int Nx = 11, Ny = Nx*2-1;\n\n  /* # of dofs is != Nx*Ny because of how we solve pdd */\n  const int numDof = (Nx-2)*Ny;\n\n  // create as many app objects as samples\n  std::vector<fom_t> vecObjs;\n  for (auto i=0; i<nSamples; i++){\n    vecObjs.emplace_back(Comm,Nx, Ny, PrS[i], ReS[i]);\n  }\n\n  // solve all problems\n  for (auto & it : vecObjs){\n    it.assembleMatrix();\n    it.fillRhs();\n    it.solve();\n  }\n\n  // collect all solutions into matrix\n  // I can do this this easily because we know # ranks = 1\n  using eig_mat = Eigen::MatrixXd;\n  eig_mat A(numDof, nSamples);\n  int j=0;\n  for (const auto & it : vecObjs){\n    auto T = it.getState();\n    for (auto i=0; i<numDof; i++)\n      A(i,j) = (*T)[i];\n    j++;\n  }\n\n  // do SVD\n  Eigen::JacobiSVD<eig_mat> svd(A, Eigen::ComputeThinU);\n  auto U = svd.matrixU();\n  std::cout << std::setprecision(15) << U << std::endl;\n\n  // read gold basis from file\n  std::vector<std::vector<double>> goldU;\n  readMatrixFromFile(\"gold_basis.txt\", goldU, nSamples);\n\n  // check that computed matches gold\n  assert( (size_t) goldU.size() == (size_t) U.rows() );\n  for (auto i=0; i<U.rows(); i++)\n    for (j=0; j<nSamples; j++)\n      if ( std::abs(goldU[i][j] - U(i,j)) > eps ) checkStr = \"FAILED\";\n\n  MPI_Finalize();\n  std::cout << checkStr <<  std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "193a0711dd516f51b183ae2023d3255945d58702", "size": 3477, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/WIP/apps/generate_basis_epetra_example/main.cc", "max_stars_repo_name": "Pressio/pressio", "max_stars_repo_head_hexsha": "e07eb1ed71266490217f2f7a3aad5e1acfecfd4a", "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": "tests/WIP/apps/generate_basis_epetra_example/main.cc", "max_issues_repo_name": "Pressio/pressio", "max_issues_repo_head_hexsha": "e07eb1ed71266490217f2f7a3aad5e1acfecfd4a", "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": "tests/WIP/apps/generate_basis_epetra_example/main.cc", "max_forks_repo_name": "nittaya1990/pressio", "max_forks_repo_head_hexsha": "22fad15ffc00f3e4d880476a5e60b227ac714ef4", "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": 25.5661764706, "max_line_length": 70, "alphanum_fraction": 0.6036813345, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.552783809772476}}
{"text": "#include \"neural_network.h\"\n\n#include <cuda_runtime.h>\n#include <helper_cuda.h>\n#include <helper_functions.h>\n\n#include <armadillo>\n\n#include \"cublas_v2.h\"\n#include \"gpu_func.h\"\n#include \"iomanip\"\n#include \"mpi.h\"\n#include \"utils/common.h\"\n\n#define MPI_SAFE_CALL(call)                                                  \\\n  do {                                                                       \\\n    int err = call;                                                          \\\n    if (err != MPI_SUCCESS) {                                                \\\n      fprintf(stderr, \"MPI error %d in file '%s' at line %i\", err, __FILE__, \\\n              __LINE__);                                                     \\\n      exit(1);                                                               \\\n    }                                                                        \\\n  } while (0)\n\nreal norms(NeuralNetwork& nn) {\n  real norm_sum = 0;\n\n  for (int i = 0; i < nn.num_layers; ++i) {\n    norm_sum += arma::accu(arma::square(nn.W[i]));\n  }\n\n  return norm_sum;\n}\n\nvoid write_cpudata_tofile(NeuralNetwork& nn, int iter) {\n  std::stringstream s;\n  s << \"Outputs/CPUmats/SequentialW0-\" << iter << \".mat\";\n  nn.W[0].save(s.str(), arma::raw_ascii);\n  std::stringstream t;\n  t << \"Outputs/CPUmats/SequentialW1-\" << iter << \".mat\";\n  nn.W[1].save(t.str(), arma::raw_ascii);\n  std::stringstream u;\n  u << \"Outputs/CPUmats/Sequentialb0-\" << iter << \".mat\";\n  nn.b[0].save(u.str(), arma::raw_ascii);\n  std::stringstream v;\n  v << \"Outputs/CPUmats/Sequentialb1-\" << iter << \".mat\";\n  nn.b[1].save(v.str(), arma::raw_ascii);\n}\n\nvoid write_diff_gpu_cpu(NeuralNetwork& nn, int iter,\n                        std::ofstream& error_file) {\n  arma::Mat<real> A, B, C, D;\n\n  std::stringstream s;\n  s << \"Outputs/CPUmats/SequentialW0-\" << iter << \".mat\";\n  A.load(s.str(), arma::raw_ascii);\n  real max_errW0 = arma::norm(nn.W[0] - A, \"inf\") / arma::norm(A, \"inf\");\n  real L2_errW0 = arma::norm(nn.W[0] - A, 2) / arma::norm(A, 2);\n\n  std::stringstream t;\n  t << \"Outputs/CPUmats/SequentialW1-\" << iter << \".mat\";\n  B.load(t.str(), arma::raw_ascii);\n  real max_errW1 = arma::norm(nn.W[1] - B, \"inf\") / arma::norm(B, \"inf\");\n  real L2_errW1 = arma::norm(nn.W[1] - B, 2) / arma::norm(B, 2);\n\n  std::stringstream u;\n  u << \"Outputs/CPUmats/Sequentialb0-\" << iter << \".mat\";\n  C.load(u.str(), arma::raw_ascii);\n  real max_errb0 = arma::norm(nn.b[0] - C, \"inf\") / arma::norm(C, \"inf\");\n  real L2_errb0 = arma::norm(nn.b[0] - C, 2) / arma::norm(C, 2);\n\n  std::stringstream v;\n  v << \"Outputs/CPUmats/Sequentialb1-\" << iter << \".mat\";\n  D.load(v.str(), arma::raw_ascii);\n  real max_errb1 = arma::norm(nn.b[1] - D, \"inf\") / arma::norm(D, \"inf\");\n  real L2_errb1 = arma::norm(nn.b[1] - D, 2) / arma::norm(D, 2);\n\n  int ow = 15;\n\n  if (iter == 0) {\n    error_file << std::left << std::setw(ow) << \"Iteration\" << std::left\n               << std::setw(ow) << \"Max Err W0\" << std::left << std::setw(ow)\n               << \"Max Err W1\" << std::left << std::setw(ow) << \"Max Err b0\"\n               << std::left << std::setw(ow) << \"Max Err b1\" << std::left\n               << std::setw(ow) << \"L2 Err W0\" << std::left << std::setw(ow)\n               << \"L2 Err W1\" << std::left << std::setw(ow) << \"L2 Err b0\"\n               << std::left << std::setw(ow) << \"L2 Err b1\"\n               << \"\\n\";\n  }\n\n  error_file << std::left << std::setw(ow) << iter << std::left << std::setw(ow)\n             << max_errW0 << std::left << std::setw(ow) << max_errW1\n             << std::left << std::setw(ow) << max_errb0 << std::left\n             << std::setw(ow) << max_errb1 << std::left << std::setw(ow)\n             << L2_errW0 << std::left << std::setw(ow) << L2_errW1 << std::left\n             << std::setw(ow) << L2_errb0 << std::left << std::setw(ow)\n             << L2_errb1 << \"\\n\";\n}\n\n/* CPU IMPLEMENTATIONS */\nvoid feedforward(NeuralNetwork& nn, const arma::Mat<real>& X,\n                 struct cache& cache) {\n  cache.z.resize(2);\n  cache.a.resize(2);\n\n  // std::cout << W[0].n_rows << \"\\n\";tw\n  assert(X.n_rows == nn.W[0].n_cols);\n  cache.X = X;\n  int N = X.n_cols;\n\n  arma::Mat<real> z1 = nn.W[0] * X + arma::repmat(nn.b[0], 1, N);\n  cache.z[0] = z1;\n\n  arma::Mat<real> a1;\n  sigmoid(z1, a1);\n  cache.a[0] = a1;\n\n  assert(a1.n_rows == nn.W[1].n_cols);\n  arma::Mat<real> z2 = nn.W[1] * a1 + arma::repmat(nn.b[1], 1, N);\n  cache.z[1] = z2;\n\n  arma::Mat<real> a2;\n  softmax(z2, a2);\n  cache.a[1] = cache.yc = a2;\n}\n\n/*\n * Computes the gradients of the cost w.r.t each param.\n * MUST be called after feedforward since it uses the bpcache.\n * @params y : C x N one-hot column vectors\n * @params bpcache : Output of feedforward.\n * @params bpgrads: Returns the gradients for each param\n */\nvoid backprop(NeuralNetwork& nn, const arma::Mat<real>& y, real reg,\n              const struct cache& bpcache, struct grads& bpgrads) {\n  bpgrads.dW.resize(2);\n  bpgrads.db.resize(2);\n  int N = y.n_cols;\n\n  // std::cout << \"backprop \" << bpcache.yc << \"\\n\";\n  arma::Mat<real> diff = (1.0 / N) * (bpcache.yc - y);\n  bpgrads.dW[1] = diff * bpcache.a[0].t() + reg * nn.W[1];\n  bpgrads.db[1] = arma::sum(diff, 1);\n  arma::Mat<real> da1 = nn.W[1].t() * diff;\n\n  arma::Mat<real> dz1 = da1 % bpcache.a[0] % (1 - bpcache.a[0]);\n\n  bpgrads.dW[0] = dz1 * bpcache.X.t() + reg * nn.W[0];\n  bpgrads.db[0] = arma::sum(dz1, 1);\n}\n\n/*\n * Computes the Cross-Entropy loss function for the neural network.\n */\nreal loss(NeuralNetwork& nn, const arma::Mat<real>& yc,\n          const arma::Mat<real>& y, real reg) {\n  int N = yc.n_cols;\n  real ce_sum = -arma::accu(arma::log(yc.elem(arma::find(y == 1))));\n\n  real data_loss = ce_sum / N;\n  real reg_loss = 0.5 * reg * norms(nn);\n  real loss = data_loss + reg_loss;\n  // std::cout << \"Loss: \" << loss << \"\\n\";\n  return loss;\n}\n\n/*\n * Returns a vector of labels for each row vector in the input\n */\nvoid predict(NeuralNetwork& nn, const arma::Mat<real>& X,\n             arma::Row<real>& label) {\n  struct cache fcache;\n  feedforward(nn, X, fcache);\n  label.set_size(X.n_cols);\n\n  for (int i = 0; i < X.n_cols; ++i) {\n    arma::uword row;\n    fcache.yc.col(i).max(row);\n    label(i) = row;\n  }\n}\n\n/*\n * Computes the numerical gradient\n */\nvoid numgrad(NeuralNetwork& nn, const arma::Mat<real>& X,\n             const arma::Mat<real>& y, real reg, struct grads& numgrads) {\n  real h = 0.00001;\n  struct cache numcache;\n  numgrads.dW.resize(nn.num_layers);\n  numgrads.db.resize(nn.num_layers);\n\n  for (int i = 0; i < nn.num_layers; ++i) {\n    numgrads.dW[i].resize(nn.W[i].n_rows, nn.W[i].n_cols);\n\n    for (int j = 0; j < nn.W[i].n_rows; ++j) {\n      for (int k = 0; k < nn.W[i].n_cols; ++k) {\n        real oldval = nn.W[i](j, k);\n        nn.W[i](j, k) = oldval + h;\n        feedforward(nn, X, numcache);\n        real fxph = loss(nn, numcache.yc, y, reg);\n        nn.W[i](j, k) = oldval - h;\n        feedforward(nn, X, numcache);\n        real fxnh = loss(nn, numcache.yc, y, reg);\n        numgrads.dW[i](j, k) = (fxph - fxnh) / (2 * h);\n        nn.W[i](j, k) = oldval;\n      }\n    }\n  }\n\n  for (int i = 0; i < nn.num_layers; ++i) {\n    numgrads.db[i].resize(nn.b[i].n_rows, nn.b[i].n_cols);\n\n    for (int j = 0; j < nn.b[i].size(); ++j) {\n      real oldval = nn.b[i](j);\n      nn.b[i](j) = oldval + h;\n      feedforward(nn, X, numcache);\n      real fxph = loss(nn, numcache.yc, y, reg);\n      nn.b[i](j) = oldval - h;\n      feedforward(nn, X, numcache);\n      real fxnh = loss(nn, numcache.yc, y, reg);\n      numgrads.db[i](j) = (fxph - fxnh) / (2 * h);\n      nn.b[i](j) = oldval;\n    }\n  }\n}\n\n/*\n * Train the neural network nn\n */\nvoid train(NeuralNetwork& nn, const arma::Mat<real>& X,\n           const arma::Mat<real>& y, real learning_rate, real reg,\n           const int epochs, const int batch_size, bool grad_check,\n           int print_every, int debug) {\n  int N = X.n_cols;\n  int iter = 0;\n  int print_flag = 0;\n\n  for (int epoch = 0; epoch < epochs; ++epoch) {\n    int num_batches = (N + batch_size - 1) / batch_size;\n\n    for (int batch = 0; batch < num_batches; ++batch) {\n      int last_col = std::min((batch + 1) * batch_size - 1, N - 1);\n      arma::Mat<real> X_batch = X.cols(batch * batch_size, last_col);\n      arma::Mat<real> y_batch = y.cols(batch * batch_size, last_col);\n\n      struct cache bpcache;\n      feedforward(nn, X_batch, bpcache);\n\n      struct grads bpgrads;\n      backprop(nn, y_batch, reg, bpcache, bpgrads);\n\n      if (print_every > 0 && iter % print_every == 0) {\n        if (grad_check) {\n          struct grads numgrads;\n          numgrad(nn, X_batch, y_batch, reg, numgrads);\n          assert(gradcheck(numgrads, bpgrads));\n        }\n\n        std::cout << \"Loss at iteration \" << iter << \" of epoch \" << epoch\n                  << \"/\" << epochs << \" = \"\n                  << loss(nn, bpcache.yc, y_batch, reg) << \"\\n\";\n      }\n\n      // Gradient descent step\n      for (int i = 0; i < nn.W.size(); ++i) {\n        nn.W[i] -= learning_rate * bpgrads.dW[i];\n      }\n\n      for (int i = 0; i < nn.b.size(); ++i) {\n        nn.b[i] -= learning_rate * bpgrads.db[i];\n      }\n\n      /* Debug routine runs only when debug flag is set. If print_every is zero,\n         it saves for the first batch of each epoch to avoid saving too many\n         large files. Note that for the first time, you have to run debug and\n         serial modes together. This will run the following function and write\n         out files to CPUmats folder. In the later runs (with same parameters),\n         you can use just the debug flag to\n         output diff b/w CPU and GPU without running CPU version */\n      if (print_every <= 0) {\n        print_flag = batch == 0;\n      } else {\n        print_flag = iter % print_every == 0;\n      }\n\n      if (debug && print_flag) {\n        write_cpudata_tofile(nn, iter);\n      }\n\n      iter++;\n    }\n  }\n}\n\n/*\n * TODO\n * Train the neural network nn of rank 0 in parallel. Your MPI implementation\n * should mainly be in this function.\n */\nstruct NNcache{\n real *W1, *W2, *b1, *b2;\n real *a1, *y_pred;\n real *dW1, *dW2, *db1, *db2;\n real *da1, *dz1, *diff;// diff derivative of cross entropy\n  /*\n  M:number of featrues,\n  H:number of neurons in hidden layer,\n  C:number of classes, 10\n  */\n NNcache(int M, int H, int C, int batch_size){\n   cudaMalloc((void**)&W1,sizeof(real)*H*M);\n   cudaMalloc((void**)&W2,sizeof(real)*C*H);\n   cudaMalloc((void**)&b1,sizeof(real)*H);\n   cudaMalloc((void**)&b2,sizeof(real)*C);\n   cudaMalloc((void**)&a1,sizeof(real)*H*batch_size);\n   cudaMalloc((void**)&y_pred,sizeof(real)*C*batch_size);\n   cudaMalloc((void**)&diff,sizeof(real)*C*batch_size);\n   cudaMalloc((void**)&dW1,sizeof(real)*H*M);\n   cudaMalloc((void**)&dW2,sizeof(real)*C*H);\n   cudaMalloc((void**)&db1,sizeof(real)*H);\n   cudaMalloc((void**)&db2,sizeof(real)*C);\n   cudaMalloc((void**)&da1,sizeof(real)*H*batch_size);\n   cudaMalloc((void**)&dz1,sizeof(real)*H*batch_size);\n }\n\n ~NNcache(){\n   cudaFree(W1);\n   cudaFree(W2);\n   cudaFree(b1);\n   cudaFree(b2);\n   cudaFree(a1);\n   cudaFree(y_pred);\n   cudaFree(diff);\n   cudaFree(dW1);\n   cudaFree(dW2);\n   cudaFree(db1);\n   cudaFree(db2);\n   cudaFree(da1);\n   cudaFree(dz1);\n }\n};\n\nvoid parallel_feedforward(NeuralNetwork &nn, real *d_X, NNcache &nncache, int size_per_proc){\n    int M = nn.H[0];\n    int H = nn.H[1];\n    int C = nn.H[2];\n    real alpha = 1.0, beta = 1.0;\n\n    /*layer 1  z1 = W1 * X + arma::repmat(b1, 1, N); a1 = sigmoid(z1)*/\n    gpu_repmat(nncache.b1, nncache.a1, H, size_per_proc);\n    myGEMM(nncache.W1, d_X, nncache.a1, &alpha,&beta, H, size_per_proc, M );\n    gpu_sigmoid(nncache.a1,H,size_per_proc);\n    /*layer 2 z2 = W2 * a1 + arma::repmat(b2, 1, N); y_pred = a2 = softmax(z2)*/\n    gpu_repmat(nncache.b2, nncache.y_pred, C, size_per_proc);\n    myGEMM(nncache.W2, nncache.a1, nncache.y_pred, &alpha,&beta, C, size_per_proc, H);\n    gpu_softmax(nncache.y_pred, C, size_per_proc);\n}\n\nvoid parallel_backprop(NeuralNetwork& nn, real *d_X, real *d_Y, real reg, NNcache &nncache,int batch_size, int size_per_proc, int num_procs){\n    int M = nn.H[0];\n    int H = nn.H[1];\n    int C = nn.H[2];\n    real ratio = 1.0/(real)batch_size;\n    reg = reg /num_procs; //change it in the parallel_train functino\n    //reg = 0.0;\n    /*diff = (1.0 / N) * (bpcache.yc - y)*/\n    gpu_addmat(nncache.y_pred,d_Y,nncache.diff, ratio, -ratio, C, size_per_proc);\n\n    /*bpgrads.dW[2] = diff * bpcache.a[1].t() + reg * nn.W[2];*/\n    real alpha = 1.0;\n    cudaMemcpy(nncache.dW2, nncache.W2, sizeof(real) * C * H, cudaMemcpyDeviceToDevice);\n    myGEMMT(nncache.diff,nncache.a1,nncache.dW2,&alpha,&reg,C,H,size_per_proc,false,true);\n\n    /*db2 = arma::sum(diff, 1)*/\n    gpu_row_sum(nncache.diff, nncache.db2, C, size_per_proc);\n\n    /* da1 = nncache.W2.t() * diff;*/\n    real beta = 0.0;\n    myGEMMT(nncache.W2,nncache.diff,nncache.da1,&alpha,&beta,H,size_per_proc,C,true,false);\n\n    /* dz1 = da1 .* nncache.a1 .* (1 - nncache.a1);*/\n    gpu_sigmoid_backprop(nncache.da1,nncache.a1,nncache.dz1,H,size_per_proc);\n\n    /*dW1 = dz1 * X.t() + reg * nncache.W1;*/\n    cudaMemcpy(nncache.dW1, nncache.W1, sizeof(real) * H * M, cudaMemcpyDeviceToDevice);\n    myGEMMT(nncache.dz1, d_X, nncache.dW1, &alpha, &reg, H, M, size_per_proc,false,true);\n\n    /* db1 = arma::sum(dz1, 1);*/\n    gpu_row_sum(nncache.dz1, nncache.db1, H, size_per_proc);\n}\n\nvoid parallel_gradientdecent(NeuralNetwork& nn, NNcache &nncache, real learning_rate){\n    int M = nn.H[0];\n    int H = nn.H[1];\n    int C = nn.H[2];\n\n    //update nncache params can change two mat params in-place\n    gpu_addmat(nncache.W1,nncache.dW1,nncache.W1,1.0,-learning_rate,H,M);\n    gpu_addmat(nncache.W2,nncache.dW2,nncache.W2,1.0,-learning_rate,C,H);\n    gpu_addmat(nncache.b1,nncache.db1,nncache.b1,1.0,-learning_rate,H,1);\n    gpu_addmat(nncache.b2,nncache.db2,nncache.b2,1.0,-learning_rate,C,1);\n}\n\nvoid parallel_train(NeuralNetwork& nn, const arma::Mat<real>& X,\n                    const arma::Mat<real>& y, real learning_rate, real reg,\n                    const int epochs, const int batch_size, bool grad_check,\n                    int print_every, int debug) {\n  int rank, num_procs;\n  MPI_SAFE_CALL(MPI_Comm_size(MPI_COMM_WORLD, &num_procs));\n  MPI_SAFE_CALL(MPI_Comm_rank(MPI_COMM_WORLD, &rank));\n\n  int N = (rank == 0) ? X.n_cols : 0;\n  MPI_SAFE_CALL(MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD));\n\n  std::ofstream error_file;\n  error_file.open(\"Outputs/CpuGpuDiff.txt\");\n  int print_flag = 0;\n\n  /* HINT: You can obtain a raw pointer to the memory used by Armadillo Matrices\n     for storing elements in a column major way. Or you can allocate your own\n     array memory space and store the elements in a row major way. Remember to\n     update the Armadillo matrices in NeuralNetwork &nn of rank 0 before\n     returning from the function. */\n\n  // TODO\n  /*\n  M:number of featrues,\n  H:number of neurons in hidden layer,\n  C:number of classes, 10\n  */\n  int M = nn.H[0];\n  int H = nn.H[1];\n  int C = nn.H[2];\n\n  int num_batches = (N + batch_size - 1) / batch_size;\n  std::vector<real *> d_X_batches(num_batches);\n  std::vector<real *> d_Y_batches(num_batches);\n  \n  //subdivide input batch of images and `MPI_scatter()' to each MPI node\n  for (int batch = 0; batch < num_batches; ++batch) {\n      int start_col = batch*batch_size;\n      int last_col = std::min((batch + 1) * batch_size - 1, N - 1);\n      int this_batch_size = last_col - start_col + 1;\n      int nsample_per_proc = (this_batch_size + num_procs -1) / num_procs;\n\n      int scounts_X[num_procs], scounts_Y[num_procs], displs_X[num_procs], displs_Y[num_procs];\n\n      for(int i = 0; i < num_procs; i++){\n        scounts_X[i] = M*std::min(nsample_per_proc,this_batch_size - i*nsample_per_proc);\n        scounts_Y[i] = C*std::min(nsample_per_proc,this_batch_size - i*nsample_per_proc);\n        displs_X[i] = i*M*nsample_per_proc;\n        displs_Y[i] = i*C*nsample_per_proc;\n      }\n    \n      arma::Mat<real> X_batch(M,scounts_X[rank]/M);\n      MPI_SAFE_CALL(MPI_Scatterv(X.colptr(start_col),scounts_X,displs_X,MPI_FP,X_batch.memptr(),\n      scounts_X[rank],MPI_FP,0,MPI_COMM_WORLD));\n      arma::Mat<real> Y_batch(C ,scounts_Y[rank]/C);\n      MPI_SAFE_CALL(MPI_Scatterv(y.colptr(start_col),scounts_Y,displs_Y,MPI_FP,Y_batch.memptr(),\n      scounts_Y[rank],MPI_FP,0,MPI_COMM_WORLD));\n\n      // data host to device , 3 processors\n      cudaMalloc((void **)&d_X_batches[batch], scounts_X[rank] * sizeof(real));\n      cudaMalloc((void **)&d_Y_batches[batch], scounts_Y[rank] * sizeof(real));\n      cudaMemcpy(d_X_batches[batch], X_batch.memptr(), scounts_X[rank]* sizeof(real), cudaMemcpyHostToDevice);\n      cudaMemcpy(d_Y_batches[batch], Y_batch.memptr(), scounts_Y[rank] * sizeof(real), cudaMemcpyHostToDevice); \n  }\n  /* iter is a variable used to manage debugging. It increments in the inner\n     loop and therefore goes from 0 to epochs*num_batches */\n  int iter = 0;\n  //allocate deivice memory for nn parameters and host memory for derivatives\n  NNcache nncache(M,H,C,batch_size);\n  real *h_dW1 = (real *)malloc(H * M * sizeof(real));\n  real *h_dW2 = (real *)malloc(C * H * sizeof(real));\n  real *h_db1 = (real *)malloc(H * sizeof(real));\n  real *h_db2 = (real *)malloc(C * sizeof(real));\n\n  //copy data from host to devices\n  cudaMemcpy(nncache.W1, nn.W[0].memptr(),H*M*sizeof(real),cudaMemcpyHostToDevice);\n  cudaMemcpy(nncache.W2, nn.W[1].memptr(),C*H*sizeof(real),cudaMemcpyHostToDevice);\n  cudaMemcpy(nncache.b1, nn.b[0].memptr(),H*sizeof(real),cudaMemcpyHostToDevice);\n  cudaMemcpy(nncache.b2, nn.b[1].memptr(),C*sizeof(real),cudaMemcpyHostToDevice);\n\n  \n  for (int epoch = 0; epoch < epochs; ++epoch) {\n\n    for (int batch = 0; batch < num_batches; ++batch) {\n      /*\n       * Possible implementation:\n       * 1. subdivide input batch of images and `MPI_scatter()' to each MPI node\n       * 2. compute each sub-batch of images' contribution to network\n       * coefficient updates\n       * 3. reduce the coefficient updates and broadcast to all nodes with\n       * `MPI_Allreduce()'\n       * 4. update local network coefficient at each node\n       */\n\n      // TODO\n      int start_col = batch*batch_size;\n      int last_col = std::min((batch + 1) * batch_size - 1, N - 1);\n      int this_batch_size = last_col - start_col + 1;\n      int nsample_per_proc = (this_batch_size + num_procs -1) / num_procs;\n      //used for 3 GPU\n      int nsample_this_proc = std::min(nsample_per_proc,this_batch_size-rank*nsample_per_proc);\n            \n      //training\n      //forwards\n      parallel_feedforward(nn,d_X_batches[batch] ,nncache,nsample_this_proc);\n\n      //backprop\n      parallel_backprop(nn,d_X_batches[batch], d_Y_batches[batch],reg, nncache, this_batch_size, nsample_this_proc, num_procs);\n\n      // cudaMemcpy's, cudaMemcpyDeviceToHost\n      cudaMemcpy(h_dW1, nncache.dW1, H * M * sizeof(real), cudaMemcpyDeviceToHost);\n      cudaMemcpy(h_dW2, nncache.dW2, C * H * sizeof(real), cudaMemcpyDeviceToHost);\n      cudaMemcpy(h_db1, nncache.db1, H * sizeof(real), cudaMemcpyDeviceToHost);\n      cudaMemcpy(h_db2, nncache.db2, C * sizeof(real), cudaMemcpyDeviceToHost);\n\n      // // MPI_Allreduce\n      arma::Mat<real> dW1(size(nn.W[0]), arma::fill::zeros);\n      MPI_SAFE_CALL(MPI_Allreduce(h_dW1, dW1.memptr(), H * M, MPI_FP, MPI_SUM, MPI_COMM_WORLD));\n      arma::Mat<real> dW2(size(nn.W[1]), arma::fill::zeros);\n      MPI_SAFE_CALL(MPI_Allreduce(h_dW2, dW2.memptr(), C * H, MPI_FP, MPI_SUM, MPI_COMM_WORLD));\n      arma::Col<real> db1(size(nn.b[0]), arma::fill::zeros);\n      MPI_SAFE_CALL(MPI_Allreduce(h_db1, db1.memptr(), H, MPI_FP, MPI_SUM, MPI_COMM_WORLD));\n      arma::Col<real> db2(size(nn.b[1]), arma::fill::zeros);\n      MPI_SAFE_CALL(MPI_Allreduce(h_db2, db2.memptr(), C, MPI_FP, MPI_SUM, MPI_COMM_WORLD));\n\n      // // cudaMemcpy's, cudaMemcpyHostToDevice\n      cudaMemcpy(nncache.dW1, dW1.memptr(), H * M * sizeof(real), cudaMemcpyHostToDevice);\n      cudaMemcpy(nncache.dW2, dW2.memptr(), C * H * sizeof(real), cudaMemcpyHostToDevice);\n      cudaMemcpy(nncache.db1, db1.memptr(), H * sizeof(real), cudaMemcpyHostToDevice);\n      cudaMemcpy(nncache.db2, db2.memptr(), C * sizeof(real), cudaMemcpyHostToDevice);\n      //add regularization term\n    //  gpu_addmat(nncache.dW1,nncache.W1,nncache.dW1,1.0,reg,H,M);\n     // gpu_addmat(nncache.dW2,nncache.W2,nncache.dW2,1.0,reg,C,H);\n      // // Gradient descent step\n      // nn.W[0] -= learning_rate * dW1;\n      // nn.W[1] -= learning_rate * dW2;\n      // nn.b[0] -= learning_rate * db1;\n      // nn.b[1] -= learning_rate * db2;\n      parallel_gradientdecent(nn,nncache,learning_rate);\n\n      // +-*=+-*=+-*=+-*=+-*=+-*=+-*=+-*=+*-=+-*=+*-=+-*=+-*=+-*=+-*=+-*= //\n      //                    POST-PROCESS OPTIONS                          //\n      // +-*=+-*=+-*=+-*=+-*=+-*=+-*=+-*=+*-=+-*=+*-=+-*=+-*=+-*=+-*=+-*= //\n      if (print_every <= 0) {\n        print_flag = batch == 0;\n      } else {\n        print_flag = iter % print_every == 0;\n      }\n\n      if (debug && rank == 0 && print_flag) {\n        // TODO\n        // Copy data back to the CPU\n        cudaMemcpy(nn.W[0].memptr(), nncache.W1, H * M * sizeof(real), cudaMemcpyDeviceToHost);\n        cudaMemcpy(nn.W[1].memptr(), nncache.W2, C * H * sizeof(real), cudaMemcpyDeviceToHost);\n        cudaMemcpy(nn.b[0].memptr(), nncache.b1, H * sizeof(real), cudaMemcpyDeviceToHost);\n        cudaMemcpy(nn.b[1].memptr(), nncache.b2, C * sizeof(real), cudaMemcpyDeviceToHost);\n\n        /* The following debug routine assumes that you have already updated the\n         arma matrices in the NeuralNetwork nn.  */\n        write_diff_gpu_cpu(nn, iter, error_file);\n      }\n\n      iter++;\n    }\n  }\n\n  // TODO\n  // Copy data back to the CPU\n  cudaMemcpy(nn.W[0].memptr(), nncache.W1, H * M * sizeof(real), cudaMemcpyDeviceToHost);\n  cudaMemcpy(nn.W[1].memptr(), nncache.W2, C * H * sizeof(real), cudaMemcpyDeviceToHost);\n  cudaMemcpy(nn.b[0].memptr(), nncache.b1, H * sizeof(real), cudaMemcpyDeviceToHost);\n  cudaMemcpy(nn.b[1].memptr(), nncache.b2, C * sizeof(real), cudaMemcpyDeviceToHost);\n  error_file.close();\n\n  // TODO\n  // Free memory\n  free(h_dW1);\n  free(h_dW2);\n  free(h_db1);\n  free(h_db2);\n  for(int batch = 0; batch < num_batches; ++batch) {\n    cudaFree(d_X_batches[batch]);\n    cudaFree(d_Y_batches[batch]);\n  }\n}\n\n// cudaMalloc's\n// MPI_Scatter. See this page for details on this function: https://www.open-mpi.org/doc/v4.1/\n// cudaMemcpy's, cudaMemcpyHostToDevice\n// loop over epochs and batches\n// here you use your GPU kernels including myGEMM, sigmoid, softmax, etc\n// cudaMemcpy's, cudaMemcpyDeviceToHost\n// MPI_Allreduce\n// cudaMemcpy's, cudaMemcpyHostToDevice\n// Gradient descent step\n// At the end, you copy back the nn coefficients from GPU to CPU and run some cudaFree's.\n\n", "meta": {"hexsha": "cd51832e545ae13d1125fed9a8a8a66df5da54c0", "size": 22712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/fp/fp1/neural_network.cpp", "max_stars_repo_name": "Alexhuyi/cme213-spring-2021", "max_stars_repo_head_hexsha": "3cc49d369f1041c0cf4f960cb6efa28c04acdf60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework/fp/fp1/neural_network.cpp", "max_issues_repo_name": "Alexhuyi/cme213-spring-2021", "max_issues_repo_head_hexsha": "3cc49d369f1041c0cf4f960cb6efa28c04acdf60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework/fp/fp1/neural_network.cpp", "max_forks_repo_name": "Alexhuyi/cme213-spring-2021", "max_forks_repo_head_hexsha": "3cc49d369f1041c0cf4f960cb6efa28c04acdf60", "max_forks_repo_licenses": ["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.7275747508, "max_line_length": 141, "alphanum_fraction": 0.6031613244, "num_tokens": 7145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.5527818173033674}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2012 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 adaptiverungekutta.hpp\n    \\brief Runge-Kutta ODE integration\n\n    Runge Kutta method with adaptive stepsize as described in\n    Numerical Recipes in C, Chapter 16.2\n*/\n\n#ifndef quantlib_adaptive_runge_kutta_hpp\n#define quantlib_adaptive_runge_kutta_hpp\n\n#include <ql/types.hpp>\n#include <ql/errors.hpp>\n#include <ql/utilities/disposable.hpp>\n#include <boost/function.hpp>\n#include <vector>\n#include <cmath>\n\nnamespace QuantLib {\n\n    template <class T = Real>\n    class AdaptiveRungeKutta {\n      public:\n        typedef boost::function<\n          Disposable<std::vector<T> >(const Real,\n                                      const std::vector<T>&)> OdeFct;\n        typedef boost::function<T(const Real, const T)> OdeFct1d;\n\n        /*! The class is constructed with the following inputs:\n            - eps       prescribed error for the solution\n            - h1        start step size\n            - hmin      smallest step size allowed\n        */\n\n        AdaptiveRungeKutta(const Real eps=1.0e-6,\n                           const Real h1=1.0e-4,\n                           const Real hmin=0.0)\n        : eps_(eps), h1_(h1), hmin_(hmin),\n          a2(0.2), a3(0.3), a4(0.6), a5(1.0), a6(0.875),\n          b21(0.2), b31(3.0/40.0), b32(9.0/40.0), b41(0.3), b42(-0.9), b43(1.2),\n          b51(-11.0/54.0), b52(2.5), b53(-70.0/27.0), b54(35.0/27.0),\n          b61(1631.0/55296.0), b62(175.0/512.0), b63(575.0/13824.0),\n          b64(44275.0/110592.0), b65(253.0/4096.0),\n          c1(37.0/378.0), c3(250.0/621.0), c4(125.0/594.0), c6(512.0/1771.0),\n          dc1(c1-2825.0/27648.0), dc3(c3-18575.0/48384.0),\n          dc4(c4-13525.0/55296.0), dc5(-277.0/14336.0), dc6(c6-0.25),\n          ADAPTIVERK_MAXSTP(10000), ADAPTIVERK_TINY(1.0E-30),\n          ADAPTIVERK_SAFETY(0.9), ADAPTIVERK_PGROW(-0.2),\n          ADAPTIVERK_PSHRINK(-0.25), ADAPTIVERK_ERRCON(1.89E-4) {}\n\n        /*! Integrate the ode from \\f$ x1 \\f$ to \\f$ x2 \\f$ with\n            initial value condition \\f$ f(x1)=y1 \\f$.\n\n            The ode is given by a function \\f$ F: R \\times K^n\n            \\rightarrow K^n \\f$ as \\f$ f'(x) = F(x,f(x)) \\f$, $K=R,\n            C$ */\n        Disposable<std::vector<T> > operator()(const OdeFct& ode,\n                                               const std::vector<T>& y1,\n                                               const Real x1,\n                                               const Real x2);\n        T operator()(const OdeFct1d& ode,\n                     const T y1,\n                     const Real x1,\n                     const Real x2);\n\n    private:\n        void rkqs(std::vector<T>& y,\n                  const std::vector<T>& dydx,\n                  Real& x,\n                  const Real htry,\n                  const Real eps,\n                  const std::vector<Real>& yScale,\n                  Real &hdid,\n                  Real &hnext,\n                  const OdeFct& derivs);\n        void rkck(const std::vector<T>& y,\n                  const std::vector<T>& dydx,\n                  Real x,\n                  const Real h,\n                  std::vector<T>& yout,\n                  std::vector<T>& yerr,\n                  const OdeFct& derivs);\n\n        const std::vector<T> yStart_;\n        const Real eps_, h1_, hmin_;\n        const Real a2,a3,a4,a5,a6,\n                   b21,b31,b32,b41,b42,b43,b51,b52,b53,b54,b61,b62,b63,b64,b65,\n                   c1,c3,c4,c6,dc1,dc3,dc4,dc5,dc6;\n        const double ADAPTIVERK_MAXSTP, ADAPTIVERK_TINY, ADAPTIVERK_SAFETY,\n                   ADAPTIVERK_PGROW, ADAPTIVERK_PSHRINK, ADAPTIVERK_ERRCON;\n    };\n\n\n\n    template<class T>\n    Disposable<std::vector<T> > AdaptiveRungeKutta<T>::operator()(\n                                                     const OdeFct& ode,\n                                                     const std::vector<T>& y1,\n                                                     const Real x1,\n                                                     const Real x2) {\n        Size n = y1.size();\n        std::vector<T> y(y1);\n        std::vector<Real> yScale(n);\n        Real x = x1;\n        Real h = h1_* (x1<=x2 ? 1 : -1);\n        Real hnext,hdid;\n\n        for (Size nstp=1; nstp<=ADAPTIVERK_MAXSTP; nstp++) {\n            std::vector<T> dydx=ode(x,y);\n            for (Size i=0;i<n;i++)\n                yScale[i] = std::abs(y[i])+std::abs(dydx[i]*h)+ADAPTIVERK_TINY;\n            if ((x+h-x2)*(x+h-x1) > 0.0)\n                h=x2-x;\n            rkqs(y,dydx,x,h,eps_,yScale,hdid,hnext,ode);\n\n            if ((x-x2)*(x2-x1) >= 0.0)\n                return y;\n\n            if (std::fabs(hnext) <= hmin_)\n                QL_FAIL(\"Step size (\" << hnext << \") too small (\"\n                        << hmin_ << \" min) in AdaptiveRungeKutta\");\n            h=hnext;\n        }\n        QL_FAIL(\"Too many steps (\" << ADAPTIVERK_MAXSTP\n                << \") in AdaptiveRungeKutta\");\n    }\n\n    namespace detail {\n\n        template <class T>\n        struct OdeFctWrapper {\n            typedef typename AdaptiveRungeKutta<T>::OdeFct1d OdeFct1d;\n            OdeFctWrapper(const OdeFct1d& ode1d)\n            : ode1d_(ode1d) {}\n            Disposable<std::vector<T> > operator()(const Real x,\n                                                   const std::vector<T>& y) {\n                std::vector<T> res(1,ode1d_(x,y[0]));\n                return res;\n            }\n            const OdeFct1d& ode1d_;\n        };\n\n    }\n\n    template<class T>\n    T AdaptiveRungeKutta<T>::operator()(const OdeFct1d& ode,\n                                        const T y1,\n                                        const Real x1,\n                                        const Real x2) {\n        return operator()(detail::OdeFctWrapper<T>(ode),\n                          std::vector<T>(1,y1),x1,x2)[0];\n    }\n\n    template<class T>\n    void AdaptiveRungeKutta<T>::rkqs(std::vector<T>& y,\n                                     const std::vector<T>& dydx,\n                                     Real& x,\n                                     const Real htry,\n                                     const Real eps,\n                                     const std::vector<Real>& yScale,\n                                     Real& hdid,\n                                     Real& hnext,\n                                     const OdeFct& derivs) {\n        Size n=y.size();\n        Real errmax,htemp,xnew;\n        std::vector<T> yerr(n),ytemp(n);\n\n        Real h=htry;\n\n        for(;;) {\n            rkck(y,dydx,x,h,ytemp,yerr,derivs);\n            errmax=0.0;\n            for (Size i=0;i<n;i++)\n                errmax=std::max(errmax,std::abs(yerr[i]/yScale[i]));\n            errmax/=eps;\n            if (errmax>1.0) {\n                htemp=ADAPTIVERK_SAFETY*h*std::pow(errmax,ADAPTIVERK_PSHRINK);\n                h = (h>=0.0 ? std::max(htemp,h/10) : std::min(htemp,h/10));\n                xnew=x+h;\n                if (xnew==x)\n                    QL_FAIL(\"Stepsize (\" << xnew\n                            << \") underflow in AdaptiveRungeKutta::rkqs\");\n                continue;\n            } else {\n                if (errmax>ADAPTIVERK_ERRCON)\n                    hnext=ADAPTIVERK_SAFETY*h*std::pow(errmax,ADAPTIVERK_PGROW);\n                else\n                    hnext=5.0*h;\n                x+=(hdid=h);\n                for (Size i=0;i<n;i++)\n                    y[i]=ytemp[i];\n                break;\n            }\n        }\n    }\n\n    template <class T>\n    void AdaptiveRungeKutta<T>::rkck(const std::vector<T>& y,\n                                     const std::vector<T>& dydx,\n                                     Real x,\n                                     const Real h,\n                                     std::vector<T>& yout,\n                                     std::vector<T> &yerr,\n                                     const OdeFct& derivs) {\n\n        Size n=y.size();\n        std::vector<T> ak2(n),ak3(n),ak4(n),ak5(n),ak6(n),ytemp(n);\n\n        // first step\n        for (Size i=0;i<n;i++)\n            ytemp[i]=y[i]+b21*h*dydx[i];\n\n        // second step\n        ak2=derivs(x+a2*h,ytemp);\n        for (Size i=0;i<n;i++)\n            ytemp[i]=y[i]+h*(b31*dydx[i]+b32*ak2[i]);\n\n        // third step\n        ak3=derivs(x+a3*h,ytemp);\n        for (Size i=0;i<n;i++)\n            ytemp[i]=y[i]+h*(b41*dydx[i]+b42*ak2[i]+b43*ak3[i]);\n\n        // fourth step\n        ak4=derivs(x+a4*h,ytemp);\n        for (Size i=0;i<n;i++)\n            ytemp[i]=y[i]+h*(b51*dydx[i]+b52*ak2[i]+b53*ak3[i]+b54*ak4[i]);\n\n        // fifth step\n        ak5=derivs(x+a5*h,ytemp);\n        for (Size i=0;i<n;i++)\n            ytemp[i]=y[i]+h*(b61*dydx[i]+b62*ak2[i]+b63*ak3[i]+b64*ak4[i]+b65*ak5[i]);\n\n        // sixth step\n        ak6=derivs(x+a6*h,ytemp);\n        for (Size i=0;i<n;i++) {\n            yout[i]=y[i]+h*(c1*dydx[i]+c3*ak3[i]+c4*ak4[i]+c6*ak6[i]);\n            yerr[i]=h*(dc1*dydx[i]+dc3*ak3[i]+dc4*ak4[i]+dc5*ak5[i]+dc6*ak6[i]);\n        }\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "cd99b3d689b17e12a819d823ec5f4e28858074e2", "size": 9691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/ode/adaptiverungekutta.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": "ql/math/ode/adaptiverungekutta.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/math/ode/adaptiverungekutta.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": 36.9885496183, "max_line_length": 86, "alphanum_fraction": 0.4706428645, "num_tokens": 2749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.5527818153562218}}
{"text": "// Copyright (C) 2013  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n#include <dlib/python.h>\n#include <dlib/statistics.h>\n\nusing namespace dlib;\nnamespace py = pybind11;\n\ntypedef std::vector<std::pair<unsigned long,double> > sparse_vect;\n\nstruct cca_outputs\n{\n    matrix<double,0,1> correlations;\n    matrix<double> Ltrans;\n    matrix<double> Rtrans;\n};\n\ncca_outputs _cca1 (\n    const std::vector<sparse_vect>& L,\n    const std::vector<sparse_vect>& R,\n    unsigned long num_correlations,\n    unsigned long extra_rank,\n    unsigned long q,\n    double regularization\n) \n{ \n    pyassert(num_correlations > 0 && L.size() > 0 && R.size() > 0 && L.size() == R.size() && regularization >= 0,\n        \"Invalid inputs\");\n\n    cca_outputs temp;\n    temp.correlations = cca(L,R,temp.Ltrans,temp.Rtrans,num_correlations,extra_rank,q,regularization); \n    return temp;\n}\n\n// ----------------------------------------------------------------------------------------\n\nunsigned long sparse_vector_max_index_plus_one (\n    const sparse_vect& v\n)\n{\n    return max_index_plus_one(v);\n}\n\nmatrix<double,0,1> apply_cca_transform (\n    const matrix<double>& m,\n    const sparse_vect& v\n)\n{\n    pyassert((long)max_index_plus_one(v) <= m.nr(), \"Invalid Inputs\");\n    return sparse_matrix_vector_multiply(trans(m), v);\n}\n\nvoid bind_cca(py::module& m)\n{\n    py::class_<cca_outputs>(m, \"cca_outputs\")\n        .def_readwrite(\"correlations\", &cca_outputs::correlations)\n        .def_readwrite(\"Ltrans\", &cca_outputs::Ltrans)\n        .def_readwrite(\"Rtrans\", &cca_outputs::Rtrans);\n\n    m.def(\"max_index_plus_one\", sparse_vector_max_index_plus_one, py::arg(\"v\"),\n\"ensures    \\n\\\n    - returns the dimensionality of the given sparse vector.  That is, returns a    \\n\\\n      number one larger than the maximum index value in the vector.  If the vector    \\n\\\n      is empty then returns 0.   \"\n    );\n\n\n    m.def(\"apply_cca_transform\", apply_cca_transform, py::arg(\"m\"), py::arg(\"v\"),\n\"requires    \\n\\\n    - max_index_plus_one(v) <= m.nr()    \\n\\\nensures    \\n\\\n    - returns trans(m)*v    \\n\\\n      (i.e. multiply m by the vector v and return the result)   \" \n    );\n\n\n    m.def(\"cca\", _cca1, py::arg(\"L\"), py::arg(\"R\"), py::arg(\"num_correlations\"), py::arg(\"extra_rank\")=5, py::arg(\"q\")=2, py::arg(\"regularization\")=0,\n\"requires    \\n\\\n    - num_correlations > 0    \\n\\\n    - len(L) > 0     \\n\\\n    - len(R) > 0     \\n\\\n    - len(L) == len(R)    \\n\\\n    - regularization >= 0    \\n\\\n    - L and R must be properly sorted sparse vectors.  This means they must list their  \\n\\\n      elements in ascending index order and not contain duplicate index values.  You can use \\n\\\n      make_sparse_vector() to ensure this is true.  \\n\\\nensures    \\n\\\n    - This function performs a canonical correlation analysis between the vectors    \\n\\\n      in L and R.  That is, it finds two transformation matrices, Ltrans and    \\n\\\n      Rtrans, such that row vectors in the transformed matrices L*Ltrans and    \\n\\\n      R*Rtrans are as correlated as possible (note that in this notation we    \\n\\\n      interpret L as a matrix with the input vectors in its rows).  Note also that    \\n\\\n      this function tries to find transformations which produce num_correlations    \\n\\\n      dimensional output vectors.    \\n\\\n    - Note that you can easily apply the transformation to a vector using     \\n\\\n      apply_cca_transform().  So for example, like this:     \\n\\\n        - apply_cca_transform(Ltrans, some_sparse_vector)    \\n\\\n    - returns a structure containing the Ltrans and Rtrans transformation matrices    \\n\\\n      as well as the estimated correlations between elements of the transformed    \\n\\\n      vectors.    \\n\\\n    - This function assumes the data vectors in L and R have already been centered    \\n\\\n      (i.e. we assume the vectors have zero means).  However, in many cases it is    \\n\\\n      fine to use uncentered data with cca().  But if it is important for your    \\n\\\n      problem then you should center your data before passing it to cca().   \\n\\\n    - This function works with reduced rank approximations of the L and R matrices.    \\n\\\n      This makes it fast when working with large matrices.  In particular, we use    \\n\\\n      the dlib::svd_fast() routine to find reduced rank representations of the input    \\n\\\n      matrices by calling it as follows: svd_fast(L, U,D,V, num_correlations+extra_rank, q)     \\n\\\n      and similarly for R.  This means that you can use the extra_rank and q    \\n\\\n      arguments to cca() to influence the accuracy of the reduced rank    \\n\\\n      approximation.  However, the default values should work fine for most    \\n\\\n      problems.    \\n\\\n    - The dimensions of the output vectors produced by L*#Ltrans or R*#Rtrans are \\n\\\n      ordered such that the dimensions with the highest correlations come first. \\n\\\n      That is, after applying the transforms produced by cca() to a set of vectors \\n\\\n      you will find that dimension 0 has the highest correlation, then dimension 1 \\n\\\n      has the next highest, and so on.  This also means that the list of estimated \\n\\\n      correlations returned from cca() will always be listed in decreasing order. \\n\\\n    - This function performs the ridge regression version of Canonical Correlation    \\n\\\n      Analysis when regularization is set to a value > 0.  In particular, larger    \\n\\\n      values indicate the solution should be more heavily regularized.  This can be    \\n\\\n      useful when the dimensionality of the data is larger than the number of    \\n\\\n      samples.    \\n\\\n    - A good discussion of CCA can be found in the paper \\\"Canonical Correlation    \\n\\\n      Analysis\\\" by David Weenink.  In particular, this function is implemented    \\n\\\n      using equations 29 and 30 from his paper.  We also use the idea of doing CCA    \\n\\\n      on a reduced rank approximation of L and R as suggested by Paramveer S.    \\n\\\n      Dhillon in his paper \\\"Two Step CCA: A new spectral method for estimating    \\n\\\n      vector models of words\\\".   \" \n        \n        );\n}\n\n\n\n", "meta": {"hexsha": "9c13f536a0f1f3fdc6c6417e86092f1f1e823a7c", "size": 6123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib-19.9/tools/python/src/cca.cpp", "max_stars_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_stars_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dlib-19.9/tools/python/src/cca.cpp", "max_issues_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_issues_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlib-19.9/tools/python/src/cca.cpp", "max_forks_repo_name": "BasileAmeeuw/IA-project-orientation-and-mood-detection", "max_forks_repo_head_hexsha": "02b674ca0a347642f460916880a73b374446b40b", "max_forks_repo_licenses": ["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.6934306569, "max_line_length": 150, "alphanum_fraction": 0.6581740977, "num_tokens": 1564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.5527818134090758}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"NumericalAlgorithms/Spectral/SwshInterpolation.hpp\"\n\n#include <array>\n#include <boost/math/special_functions/binomial.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n\n#include \"DataStructures/ComplexDataVector.hpp\"\n#include \"DataStructures/ComplexModalVector.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/SpinWeighted.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshCoefficients.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshCollocation.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshTransform.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/StaticCache.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n/// \\cond\n\nnamespace Spectral {\nnamespace Swsh {\n\nSpinWeightedSphericalHarmonic::SpinWeightedSphericalHarmonic(\n    const int spin, const size_t l, const int m) noexcept\n    : spin_{spin}, l_{l}, m_{m} {\n  overall_prefactor_ = 1.0;\n  const double double_l = l;\n  const double double_m = m;\n  const double double_spin = spin;\n  if (std::abs(m) > std::abs(spin)) {\n    for (size_t i = 0; i < static_cast<size_t>(std::abs(m) - std::abs(spin));\n         ++i) {\n      const double double_i = i;\n      overall_prefactor_ *= (double_l + std::abs(double_m) - double_i) /\n                            (double_l - (std::abs(double_spin) + double_i));\n    }\n  } else if (std::abs(spin) > std::abs(m)) {\n    for (size_t i = 0; i < static_cast<size_t>(std::abs(spin) - std::abs(m));\n         ++i) {\n      const double double_i = i;\n      overall_prefactor_ *= (double_l - (std::abs(double_m) + double_i)) /\n                            (double_l + std::abs(double_spin) - double_i);\n    }\n  }\n  // if neither is greater (they are equal), then the prefactor is 1.0\n  overall_prefactor_ *= (2.0 * l + 1.0) / (4.0 * M_PI);\n  overall_prefactor_ = sqrt(overall_prefactor_);\n  overall_prefactor_ *= (m % 2) == 0 ? 1.0 : -1.0;\n\n  // gcc warns about the casts in ways that are impossible to satisfy\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n  if (static_cast<int>(l) < std::abs(spin)) {\n    if (spin < 0) {\n      r_prefactors_ =\n          std::vector<double>(l + static_cast<size_t>(std::abs(spin)) + 1, 0.0);\n    }\n  } else {\n    // the casts in the reserve are in correct order, but clang-format\n    // erroneously requests a change\n    // NOLINTNEXTLINE(misc-misplaced-widening-cast)\n    r_prefactors_.reserve(static_cast<size_t>(static_cast<int>(l) - spin + 1));\n    for (int r = 0; r <= (static_cast<int>(l) - spin); ++r) {\n      if (r + spin - m >= 0 and static_cast<int>(l) - r + m >= 0) {\n        r_prefactors_.push_back(\n            boost::math::binomial_coefficient<double>(\n                static_cast<size_t>(static_cast<int>(l) - spin),\n                static_cast<size_t>(r)) *\n            boost::math::binomial_coefficient<double>(\n                static_cast<size_t>(static_cast<int>(l) + spin),\n                static_cast<size_t>(spin - m + r)) *\n            (((static_cast<int>(l) - r - spin) % 2) == 0 ? 1.0 : -1.0));\n      } else {\n        r_prefactors_.push_back(0.0);\n      }\n    }\n  }\n#pragma GCC diagnostic pop\n}\n\nvoid SpinWeightedSphericalHarmonic::evaluate(\n    const gsl::not_null<ComplexDataVector*> result, const DataVector& theta,\n    const DataVector& phi, const DataVector& sin_theta_over_2,\n    const DataVector& cos_theta_over_2) const noexcept {\n  result->destructive_resize(theta.size());\n  *result = 0.0;\n  DataVector theta_factor{theta.size()};\n  for (int r = 0; r <= (static_cast<int>(l_) - spin_); ++r) {\n    if (2 * static_cast<int>(l_) > 2 * r + spin_ - m_) {\n      theta_factor = pow(cos_theta_over_2, 2 * r + spin_ - m_) *\n                     pow(sin_theta_over_2,\n                         2 * static_cast<int>(l_) - (2 * r + spin_ - m_));\n    } else if (2 * static_cast<int>(l_) < 2 * r + spin_ - m_) {\n      theta_factor = pow(cos_theta_over_2 / sin_theta_over_2,\n                         2 * r + spin_ - m_ - 2 * static_cast<int>(l_)) *\n                     pow(cos_theta_over_2, 2 * l_);\n    } else {\n      theta_factor = pow(cos_theta_over_2, 2 * l_);\n    }\n    *result += gsl::at(r_prefactors_, r) * theta_factor;\n  }\n  // optimization note: this has not been compared with a complex `exp`\n  // function, and it is not obvious which should be faster in practice.\n  *result *=\n      overall_prefactor_ *\n      (std::complex<double>(1.0, 0.0) * cos(static_cast<double>(m_) * phi) +\n       std::complex<double>(0.0, 1.0) * sin(static_cast<double>(m_) * phi));\n}\n\nComplexDataVector SpinWeightedSphericalHarmonic::evaluate(\n    const DataVector& theta, const DataVector& phi,\n    const DataVector& sin_theta_over_2,\n    const DataVector& cos_theta_over_2) const noexcept {\n  ComplexDataVector result{theta.size(), 0.0};\n  evaluate(make_not_null(&result), theta, phi, sin_theta_over_2,\n           cos_theta_over_2);\n  return result;\n}\n\nstd::complex<double> SpinWeightedSphericalHarmonic::evaluate(\n    const double theta, const double phi) const noexcept {\n  std::complex<double> accumulator = 0.0;\n  const double cos_theta_over_two = cos(0.5 * theta);\n  const double sin_theta_over_two = sin(0.5 * theta);\n  double theta_factor;\n  for (int r = 0; r <= (static_cast<int>(l_) - spin_); ++r) {\n    if (2 * static_cast<int>(l_) > 2 * r + spin_ - m_) {\n      theta_factor = pow(cos_theta_over_two, 2 * r + spin_ - m_) *\n                     pow(sin_theta_over_two,\n                         2 * static_cast<int>(l_) - (2 * r + spin_ - m_));\n    } else if (2 * static_cast<int>(l_) < 2 * r + spin_ - m_) {\n      theta_factor = pow(cos_theta_over_two / sin_theta_over_two,\n                         2 * r + spin_ - m_ - 2 * static_cast<int>(l_)) *\n                     pow(cos_theta_over_two, 2 * l_);\n    } else {\n      theta_factor = pow(cos_theta_over_two, 2 * l_);\n    }\n    accumulator += gsl::at(r_prefactors_, r) *\n                   std::complex<double>(cos(static_cast<double>(m_) * phi),\n                                        sin(static_cast<double>(m_) * phi)) *\n                   theta_factor;\n  }\n  accumulator *= overall_prefactor_;\n  return accumulator;\n}\n\nvoid SpinWeightedSphericalHarmonic::pup(PUP::er& p) noexcept {\n  p | spin_;\n  p | l_;\n  p | m_;\n  p | overall_prefactor_;\n  p | r_prefactors_;\n}\n\n// A function for indexing a desired element in one of the caches stored\n// in `ClenshawRecurrenceConstants`.\n// Useful for accessing the `beta_constant`, `alpha_constant`, or\n// `alpha_prefactor` recurrence constants.\nsize_t clenshaw_cache_index(const size_t l_max, const int spin, const int l,\n                            const int m) noexcept {\n  return goldberg_mode_index(l_max - 2, static_cast<size_t>(l - 2), m) -\n         static_cast<size_t>(square(spin));\n}\n\n// see the detailed doxygen for `SwshInterpolator` for full mathematical details\n// of the recurrence constant computations\ntemplate <int Spin>\nstruct ClenshawRecurrenceConstants {\n  ClenshawRecurrenceConstants() = default;\n\n  explicit ClenshawRecurrenceConstants(size_t l_max) noexcept\n      : alpha_prefactor{square(l_max + 1) -\n                        square(static_cast<size_t>(std::abs(Spin)))},\n        alpha_constant{square(l_max + 1) -\n                       square(static_cast<size_t>(std::abs(Spin)))},\n        beta_constant{square(l_max + 1) -\n                      square(static_cast<size_t>(std::abs(Spin)))},\n        harmonic_at_l_min_prefactors{2 * l_max + 1},\n        harmonic_at_l_min_plus_one_recurrence_prefactors{2 * l_max + 1},\n        harmonic_m_recurrence_prefactors{2 * l_max + 1} {\n    ASSERT(static_cast<int>(l_max) > Spin,\n           \"l_max must be greater than the spin-weight when computing \"\n           \"ClenshawRecurrenceConstants\");\n    double l_plus_k;\n    double l_min_plus_k;\n    double a;\n    double b;\n    int l_min;\n    double prefactor_accumulator;\n    lambda.reserve(2 * l_max + 1);\n    for (int m = -static_cast<int>(l_max); m <= static_cast<int>(l_max); ++m) {\n      a = static_cast<double>(std::abs(Spin + m));\n      b = static_cast<double>(std::abs(Spin - m));\n      l_min = std::max(std::abs(m), std::abs(Spin));\n\n      // gcc warns about an optimization that doesn't work if we overflow. None\n      // of this will overflow provided l_max is not unreasonably high (less\n      // than ~10^5 will not overflow).\n      for (int l = l_min + 2; l <= static_cast<int>(l_max); ++l) {\n        // start caching at 2 greater than the l_min for a given m. Those are\n        // the last terms needed by (descending) Clenshaw sum.\n        l_plus_k = static_cast<double>(l) - 0.5 * (a + b);\n        alpha_prefactor[clenshaw_cache_index(l_max, Spin, l, m)] =\n            0.5 * sqrt((2.0 * l + 1.0) * (2.0 * l - 1.0) /\n                       (l_plus_k * (l_plus_k + a + b) * (l_plus_k + a) *\n                        (l_plus_k + b)));\n        alpha_constant[clenshaw_cache_index(l_max, Spin, l, m)] =\n            alpha_prefactor[clenshaw_cache_index(l_max, Spin, l, m)] *\n            ((square(a) - square(b)) / (2.0 * l - 2.0));\n        alpha_prefactor[clenshaw_cache_index(l_max, Spin, l, m)] *= (2.0 * l);\n        beta_constant[clenshaw_cache_index(l_max, Spin, l, m)] =\n            -sqrt((2.0 * l + 1.0) * (l_plus_k + a - 1.0) *\n                  (l_plus_k + b - 1.0) * (l_plus_k - 1.0) *\n                  (l_plus_k + a + b - 1.0) /\n                  ((2.0 * l - 3.0) * l_plus_k * (l_plus_k + a + b) *\n                   (l_plus_k + a) * (l_plus_k + b))) *\n            (2.0 * l) / (2.0 * l - 2.0);\n      }\n      lambda.push_back(Spin >= -m ? 0 : Spin + m);\n\n      // pre-compute the prefactors for the lowest order harmonics for each m\n      prefactor_accumulator = 1.0;\n      l_min_plus_k = -0.5 * (std::abs(Spin + m) + b) + l_min;\n      for (int i = 1; i <= b; ++i) {\n        if (l_min_plus_k + a + i > 0.0) {\n          prefactor_accumulator *= static_cast<double>(l_min_plus_k + a + i);\n        }\n        if (l_min_plus_k + i > 0.0) {\n          prefactor_accumulator /= static_cast<double>(l_min_plus_k + i);\n        }\n      }\n      prefactor_accumulator =\n          sqrt(prefactor_accumulator * (2.0 * l_min + 1.0) / (4.0 * M_PI));\n      prefactor_accumulator *=\n          ((m + gsl::at(lambda, m + static_cast<int>(l_max))) % 2) == 0 ? 1.0\n                                                                        : -1.0;\n      // this is the right order of the casts, other orders give the wrong\n      // answer NOLINTNEXTLINE(misc-misplaced-widening-cast)\n      harmonic_at_l_min_prefactors[static_cast<size_t>(\n          m + static_cast<int>(l_max))] = prefactor_accumulator;\n\n      // pre-compute the prefactors for bootstrapping the second-to-lowest order\n      // harmonics for each m\n\n      // this is the right order of the casts, other orders give the wrong\n      // answer NOLINTNEXTLINE(misc-misplaced-widening-cast)\n      harmonic_at_l_min_plus_one_recurrence_prefactors[static_cast<size_t>(\n          m + static_cast<int>(l_max))] =\n          sqrt((2.0 * (l_min) + 3.0) * (l_min_plus_k + 1.0) *\n               (l_min_plus_k + a + b + 1.0) /\n               ((2.0 * (l_min) + 1.0) * (l_min_plus_k + a + 1.0) *\n                (l_min_plus_k + b + 1.0)));\n    }\n    // separate loop because we'll need the lambdas entirely populated for this\n    // set of prefactors\n    int lambda_difference;\n    for (int m = -static_cast<int>(l_max); m <= static_cast<int>(l_max); ++m) {\n      if (std::abs(m) > std::abs(Spin)) {\n        l_min = std::max(std::abs(m), std::abs(Spin));\n        a = std::abs(Spin + m);\n        b = std::abs(Spin - m);\n        l_min_plus_k = -0.5 * (std::abs(Spin + m) + b) + l_min;\n\n        prefactor_accumulator =\n            sqrt((2.0 * std::abs(m) + 1.0) * (l_min_plus_k + a + b - 1.0) *\n                 (l_min_plus_k + a + b) /\n                 ((2.0 * std::abs(m) - 1.0) * (l_min_plus_k + a) *\n                  (l_min_plus_k + b)));\n        // there is an extra `1` in these expressions to account for the -1 out\n        // front of the recurrence relations.\n        lambda_difference = gsl::at(lambda, m + static_cast<int>(l_max)) + 1;\n        if (m > 0) {\n          lambda_difference -= gsl::at(lambda, m - 1 + static_cast<int>(l_max));\n        } else {\n          lambda_difference -= gsl::at(lambda, m + 1 + static_cast<int>(l_max));\n        }\n        prefactor_accumulator *= lambda_difference % 2 == 0 ? 1.0 : -1.0;\n        // this is the right order of the casts, other orders give the wrong\n        // answer NOLINTNEXTLINE(misc-misplaced-widening-cast)\n        harmonic_m_recurrence_prefactors[static_cast<size_t>(\n            m + static_cast<int>(l_max))] = prefactor_accumulator;\n      }\n    }\n  }\n\n  /// Serialization for Charm++.\n  void pup(PUP::er& p) noexcept {  // NOLINT\n    p | alpha_prefactor;\n    p | alpha_constant;\n    p | beta_constant;\n    p | lambda;\n    p | harmonic_at_l_min_prefactors;\n    p | harmonic_at_l_min_plus_one_recurrence_prefactors;\n    p | harmonic_m_recurrence_prefactors;\n  }\n\n  // Tables are stored in a triangular Goldberg style\n  DataVector alpha_prefactor;\n  DataVector alpha_constant;\n  DataVector beta_constant;\n  std::vector<int> lambda;\n  DataVector harmonic_at_l_min_prefactors;\n  DataVector harmonic_at_l_min_plus_one_recurrence_prefactors;\n  DataVector harmonic_m_recurrence_prefactors;\n};\n\n// A lazy static cache interface for retrieving `ClenshawRecurrenceConstants`.\ntemplate <int Spin>\nconst ClenshawRecurrenceConstants<Spin>& cached_clenshaw_factors(\n    const size_t l_max) noexcept {\n  const static auto lazy_clenshaw_cache =\n      make_static_cache<CacheRange<0, collocation_maximum_l_max>>(\n          [](const size_t local_l_max) noexcept {\n            return ClenshawRecurrenceConstants<Spin>{local_l_max};\n          });\n  return lazy_clenshaw_cache(l_max);\n}\n\nSwshInterpolator::SwshInterpolator(const DataVector& theta,\n                                   const DataVector& phi,\n                                   const size_t l_max) noexcept\n    : l_max_{l_max},\n      raw_libsharp_coefficient_buffer_{\n          size_of_libsharp_coefficient_vector(l_max)},\n      raw_goldberg_coefficient_buffer_{square(l_max + 1)} {\n  cos_m_phi_ = std::vector<DataVector>(l_max + 1);\n  sin_m_phi_ = std::vector<DataVector>(l_max + 1);\n  cos_theta_ = cos(theta);\n  sin_theta_ = sin(theta);\n  cos_theta_over_two_ = cos(0.5 * theta);\n  sin_theta_over_two_ = sin(0.5 * theta);\n  // evaluate cos(m phi) and sin(m phi) via recurrence\n  cos_m_phi_[0] = DataVector{phi.size(), 1.0};\n  sin_m_phi_[0] = DataVector{phi.size(), 0.0};\n  const DataVector m_phi_beta = sin(phi);\n  const DataVector m_phi_alpha = 2.0 * square(sin(0.5 * phi));\n  for (size_t m = 1; m <= l_max; ++m) {\n    cos_m_phi_[m] = cos_m_phi_[m - 1] - (m_phi_alpha * cos_m_phi_[m - 1] +\n                                         m_phi_beta * sin_m_phi_[m - 1]);\n    sin_m_phi_[m] = sin_m_phi_[m - 1] - (m_phi_alpha * sin_m_phi_[m - 1] -\n                                         m_phi_beta * cos_m_phi_[m - 1]);\n  }\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::interpolate(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> interpolated,\n    const SpinWeighted<ComplexModalVector, Spin>& goldberg_modes) const\n    noexcept {\n  interpolated->destructive_resize(cos_theta_.size());\n  interpolated->data() = 0.0;\n\n  // used only if s=0;\n  SpinWeighted<ComplexDataVector, Spin> cached_base_harmonic;\n\n  // used during both recurrence legs\n  SpinWeighted<ComplexDataVector, Spin> current_cached_harmonic;\n  SpinWeighted<ComplexDataVector, Spin> current_cached_harmonic_l_plus_one;\n\n  // perform the Clenshaw sums over positive m >= 0.\n  for (int m = 0; m <= static_cast<int>(l_max_); ++m) {\n    if (std::abs(Spin) >= std::abs(m)) {\n      direct_evaluation_swsh_at_l_min(make_not_null(&current_cached_harmonic),\n                                      m);\n      evaluate_swsh_at_l_min_plus_one(\n          make_not_null(&current_cached_harmonic_l_plus_one),\n          current_cached_harmonic, m);\n    } else {\n      evaluate_swsh_m_recurrence_at_l_min(\n          make_not_null(&current_cached_harmonic), m);\n      evaluate_swsh_at_l_min_plus_one(\n          make_not_null(&current_cached_harmonic_l_plus_one),\n          current_cached_harmonic, m);\n    }\n    if (Spin == 0 and m == 0) {\n      cached_base_harmonic = current_cached_harmonic;\n    }\n    clenshaw_sum(interpolated, current_cached_harmonic,\n                 current_cached_harmonic_l_plus_one, goldberg_modes, m);\n  }\n  // perform the Clenshaw sums over m < 0.\n  for (int m = -1; m >= -static_cast<int>(l_max_); --m) {\n    // initialize the recurrence for negative m\n    if (m == -1 and Spin == 0) {\n      current_cached_harmonic = cached_base_harmonic;\n    }\n    if (std::abs(Spin) >= std::abs(m)) {\n      direct_evaluation_swsh_at_l_min(make_not_null(&current_cached_harmonic),\n                                      m);\n      evaluate_swsh_at_l_min_plus_one(\n          make_not_null(&current_cached_harmonic_l_plus_one),\n          current_cached_harmonic, m);\n    } else {\n      evaluate_swsh_m_recurrence_at_l_min(\n          make_not_null(&current_cached_harmonic), m);\n      evaluate_swsh_at_l_min_plus_one(\n          make_not_null(&current_cached_harmonic_l_plus_one),\n          current_cached_harmonic, m);\n    }\n    clenshaw_sum(interpolated, current_cached_harmonic,\n                 current_cached_harmonic_l_plus_one, goldberg_modes, m);\n  }\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::interpolate(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> interpolated,\n    const SpinWeighted<ComplexDataVector, Spin>& libsharp_collocation) const\n    noexcept {\n  SpinWeighted<ComplexModalVector, Spin> libsharp_modes;\n  // this function is 'const', but modifies the internal buffer. The reason to\n  // allow it to be 'const' anyways is that no interface makes any assumption\n  // about the starting state of the internal buffer; it is kept exclusively to\n  // save allocations.\n  libsharp_modes.set_data_ref(raw_libsharp_coefficient_buffer_.data(),\n                              raw_libsharp_coefficient_buffer_.size());\n  swsh_transform(l_max_, 1, make_not_null(&libsharp_modes),\n                 libsharp_collocation);\n  SpinWeighted<ComplexModalVector, Spin> goldberg_modes;\n  libsharp_to_goldberg_modes(make_not_null(&goldberg_modes), libsharp_modes,\n                             l_max_);\n  interpolate(interpolated, goldberg_modes);\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::direct_evaluation_swsh_at_l_min(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> harmonic,\n    const int m) const noexcept {\n  const auto& clenshaw_factors = cached_clenshaw_factors<Spin>(l_max_);\n  // for this evaluation, we don't worry about recurrence because it will only\n  // be called for m between -s and +s, and s should always be small. In\n  // principle, it is probably true that a more complicated recurrence exists\n  // for this case, but would require a bit of derivation work\n  harmonic->data() =\n      // clang-tidy: this is the right order of the casts, other orders give the\n      // wrong answer\n      // NOLINTNEXTLINE(misc-misplaced-widening-cast)\n      clenshaw_factors.harmonic_at_l_min_prefactors[static_cast<size_t>(\n          m + static_cast<int>(l_max_))] *\n      (std::complex<double>(1.0, 0.0) * gsl::at(cos_m_phi_, std::abs(m)) +\n       std::complex<double>(0.0, 1.0) * (m >= 0 ? 1.0 : -1.0) *\n           gsl::at(sin_m_phi_, std::abs(m))) *\n      pow(sin_theta_over_two_, static_cast<size_t>(std::abs(Spin + m))) *\n      pow(cos_theta_over_two_, static_cast<size_t>(std::abs(Spin - m)));\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::evaluate_swsh_at_l_min_plus_one(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> harmonic,\n    const SpinWeighted<ComplexDataVector, Spin>& harmonic_at_l_min,\n    const int m) const noexcept {\n  const auto& clenshaw_factors = cached_clenshaw_factors<Spin>(l_max_);\n  const double a = std::abs(Spin + m);\n  const double b = std::abs(Spin - m);\n  harmonic->data() =\n      clenshaw_factors\n          // clang-tidy: this is the right order of the casts, other orders give\n          // the wrong answer\n          // NOLINTNEXTLINE(misc-misplaced-widening-cast)\n          .harmonic_at_l_min_plus_one_recurrence_prefactors[static_cast<size_t>(\n              m + static_cast<int>(l_max_))] *\n      harmonic_at_l_min.data() *\n      (a + 1.0 + 0.5 * (a + b + 2.0) * (cos_theta_ - 1.0));\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::evaluate_swsh_m_recurrence_at_l_min(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> harmonic,\n    const int m) const noexcept {\n  const auto& clenshaw_factors = cached_clenshaw_factors<Spin>(l_max_);\n  harmonic->data() =\n      // this is the right order of the casts, other orders give the wrong\n      // answer\n      // NOLINTNEXTLINE(misc-misplaced-widening-cast)\n      clenshaw_factors.harmonic_m_recurrence_prefactors[static_cast<size_t>(\n          m + static_cast<int>(l_max_))] *\n      (sin_theta_ / 2.0) * harmonic->data();\n  if (m > 0) {\n    harmonic->data() *= (std::complex<double>(1.0, 0.0) * cos_m_phi_[1] +\n                         std::complex<double>(0.0, 1.0) * sin_m_phi_[1]);\n  } else {\n    harmonic->data() *= (std::complex<double>(1.0, 0.0) * cos_m_phi_[1] -\n                         std::complex<double>(0.0, 1.0) * sin_m_phi_[1]);\n  }\n}\n\ntemplate <int Spin>\nvoid SwshInterpolator::clenshaw_sum(\n    const gsl::not_null<SpinWeighted<ComplexDataVector, Spin>*> interpolation,\n    const SpinWeighted<ComplexDataVector, Spin>& l_min_harmonic,\n    const SpinWeighted<ComplexDataVector, Spin>& l_min_plus_one_harmonic,\n    const SpinWeighted<ComplexModalVector, Spin>& goldberg_modes,\n    const int m) const noexcept {\n  // Since we need various combinations of the three-term recurrence constants\n  // up to two orders higher, we write recurrence results to a cyclic\n  // three-element cache\n  std::array<ComplexDataVector, 3> recurrence_cache;\n  recurrence_cache[2] = ComplexDataVector{interpolation->size(), 0.0};\n  recurrence_cache[1] = ComplexDataVector{interpolation->size(), 0.0};\n  recurrence_cache[0] = ComplexDataVector{interpolation->size(), 0.0};\n  const auto& clenshaw_factors = cached_clenshaw_factors<Spin>(l_max_);\n\n  for (auto l = static_cast<int>(l_max_);\n       l > std::max(std::abs(Spin), std::abs(m)); l--) {\n    // We want to define some cache_offset so that we can index the three\n    // elements of recurrence_cache with indices cache_offset%3,\n    // (cache_offset+1)%3, and (cache_offset+2)%3, and so that cache_offset\n    // decreases by one on each iteration. The \"obvious\" way to do this is to\n    // choose cache_offset = l - l_max, so that cache_offset starts at zero and\n    // then decreases each iteration. However, this gives negative values of\n    // cache_offset, and C++ modular arithmetic doesn't behave the way we'd want\n    // for that process at negative values. But note that adding any multiple of\n    // 3 to the \"obvious\" value of cache_offset will give identical indexing,\n    // and choosing this multiple of 3 large enough (i.e. larger than l_max)\n    // guarantees that the new cache_offset is positive for all l. So we choose\n    // to add 3*l_max to the \"obvious\" value of cache_offset; in other words we\n    // define cache_offset = l + 2 l_max.\n    // In future, if this trick needs to be re-implemented in another use-case,\n    // it should instead be factored out into a separate rotating cache utility.\n    const int cache_offset = (l + 2 * static_cast<int>(l_max_));\n    // gcc warns about the casts in ways that are impossible to satisfy\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n    gsl::at(recurrence_cache, (cache_offset) % 3) =\n        goldberg_modes.data()[square(static_cast<size_t>(l)) +\n                              static_cast<size_t>(l + m)];\n    if (l < static_cast<int>(l_max_)) {\n      gsl::at(recurrence_cache, (cache_offset) % 3) +=\n          (clenshaw_factors\n               .alpha_constant[clenshaw_cache_index(l_max_, Spin, l + 1, m)] +\n           cos_theta_ * clenshaw_factors.alpha_prefactor[clenshaw_cache_index(\n                            l_max_, Spin, l + 1, m)]) *\n          gsl::at(recurrence_cache, (cache_offset + 1) % 3);\n    }\n    if (l < static_cast<int>(l_max_) - 1) {\n      gsl::at(recurrence_cache, (cache_offset) % 3) +=\n          clenshaw_factors\n              .beta_constant[clenshaw_cache_index(l_max_, Spin, l + 2, m)] *\n          gsl::at(recurrence_cache, (cache_offset + 2) % 3);\n    }\n  }\n  const int l_min = std::max(std::abs(Spin), std::abs(m));\n  const int cache_offset = (l_min + 2 * static_cast<int>(l_max_));\n\n  if (l_max_ >=\n      static_cast<size_t>(std::max(std::abs(Spin), std::abs(m))) + 2) {\n    *interpolation +=\n        l_min_harmonic *\n            goldberg_modes.data()[square(static_cast<size_t>(l_min)) +\n                                  static_cast<size_t>(l_min + m)] +\n        l_min_plus_one_harmonic *\n            gsl::at(recurrence_cache, (cache_offset + 1) % 3) +\n        l_min_harmonic * gsl::at(recurrence_cache, (cache_offset + 2) % 3) *\n            clenshaw_factors.beta_constant[clenshaw_cache_index(\n                l_max_, Spin, std::max(std::abs(Spin), std::abs(m)) + 2, m)];\n  } else {\n    *interpolation +=\n        l_min_harmonic *\n            goldberg_modes.data()[square(static_cast<size_t>(l_min)) +\n                                  static_cast<size_t>(l_min + m)] +\n        l_min_plus_one_harmonic *\n            gsl::at(recurrence_cache, (cache_offset + 1) % 3);\n  }\n#pragma GCC diagnostic pop\n}\n\nvoid SwshInterpolator::pup(PUP::er& p) noexcept {\n  p | l_max_;\n  p | cos_theta_;\n  p | sin_theta_;\n  p | cos_theta_over_two_;\n  p | sin_theta_over_two_;\n  p | sin_m_phi_;\n  p | cos_m_phi_;\n  p | raw_libsharp_coefficient_buffer_;\n  p | raw_goldberg_coefficient_buffer_;\n}\n\n#define GET_SPIN(data) BOOST_PP_TUPLE_ELEM(0, data)\n\n#define INTERPOLATION_INSTANTIATION(r, data)                                  \\\n  template struct ClenshawRecurrenceConstants<GET_SPIN(data)>;                \\\n  template const ClenshawRecurrenceConstants<GET_SPIN(data)>&                 \\\n  cached_clenshaw_factors<GET_SPIN(data)>(const size_t l_max) noexcept;       \\\n  template void SwshInterpolator::interpolate<GET_SPIN(data)>(                \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          interpolated,                                                       \\\n      const SpinWeighted<ComplexModalVector, GET_SPIN(data)>& goldberg_modes) \\\n      const noexcept;                                                         \\\n  template void SwshInterpolator::interpolate<GET_SPIN(data)>(                \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          interpolated,                                                       \\\n      const SpinWeighted<ComplexDataVector, GET_SPIN(data)>&                  \\\n          libsharp_collocation) const noexcept;                               \\\n  template void                                                               \\\n  SwshInterpolator::direct_evaluation_swsh_at_l_min<GET_SPIN(data)>(          \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          harmonic,                                                           \\\n      const int m) const noexcept;                                            \\\n  template void                                                               \\\n  SwshInterpolator::evaluate_swsh_at_l_min_plus_one<GET_SPIN(data)>(          \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          harmonic,                                                           \\\n      const SpinWeighted<ComplexDataVector, GET_SPIN(data)>&                  \\\n          harmonic_at_l_min,                                                  \\\n      const int m) const noexcept;                                            \\\n  template void                                                               \\\n  SwshInterpolator::evaluate_swsh_m_recurrence_at_l_min<GET_SPIN(data)>(      \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          harmonic,                                                           \\\n      const int m) const noexcept;                                            \\\n  template void SwshInterpolator::clenshaw_sum<GET_SPIN(data)>(               \\\n      const gsl::not_null<SpinWeighted<ComplexDataVector, GET_SPIN(data)>*>   \\\n          interpolation,                                                      \\\n      const SpinWeighted<ComplexDataVector, GET_SPIN(data)>& l_min_harmonic,  \\\n      const SpinWeighted<ComplexDataVector, GET_SPIN(data)>&                  \\\n          l_min_plus_one_harmonic,                                            \\\n      const SpinWeighted<ComplexModalVector, GET_SPIN(data)>& goldberg_modes, \\\n      const int m) const noexcept;\n\nGENERATE_INSTANTIATIONS(INTERPOLATION_INSTANTIATION, (-2, -1, 0, 1, 2))\n\n#undef INTERPOLATION_INSTANTIATION\n#undef GET_SPIN\n\n}  // namespace Swsh\n}  // namespace Spectral\n/// \\endcond\n", "meta": {"hexsha": "a3d522b5e8127d993991f18a2f01c0ac4974e7b7", "size": 29160, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/Spectral/SwshInterpolation.cpp", "max_stars_repo_name": "keefemitman/spectre", "max_stars_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumericalAlgorithms/Spectral/SwshInterpolation.cpp", "max_issues_repo_name": "keefemitman/spectre", "max_issues_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalAlgorithms/Spectral/SwshInterpolation.cpp", "max_forks_repo_name": "keefemitman/spectre", "max_forks_repo_head_hexsha": "a8c3e387addc34d8a4544728f405991e6c9e5e38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9212598425, "max_line_length": 80, "alphanum_fraction": 0.6223251029, "num_tokens": 7860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.5526624653538253}}
{"text": "#include \"multi_cg/multi_cg.hpp\"\n\n#include <Eigen/Core>\n\n#include <iostream>\n\nusing namespace Eigen;\n\nstruct BlockVector;\n\nstruct BlockVector {\n    MatrixXcd vec;\n\n    typedef std::complex<double> value_type;\n\n    void block_axpy(std::vector<std::complex<double>> alphas, BlockVector const &X, size_t num) {\n        DiagonalMatrix<std::complex<double>,Dynamic,Dynamic> D = Map<VectorXcd>(alphas.data(), num).asDiagonal();\n        vec.leftCols(num) += X.vec.leftCols(num) * D;\n    }\n\n    void block_axpy_scatter(std::vector<std::complex<double>> alphas, BlockVector const &X, std::vector<size_t> ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            vec.col(ids[i]) += alphas[i] * X.vec.col(i);\n        }\n    }\n\n    // rhos[i] = dot(X[i], Y[i])\n    void block_dot(BlockVector const &Y, std::vector<std::complex<double>> &rhos, size_t num) {\n        VectorXcd result = (vec.leftCols(num).adjoint() * Y.vec.leftCols(num)).diagonal();\n        VectorXcd::Map(rhos.data(), result.size()) = result;\n    }\n\n    // X[:, i] = Z[:, i] + alpha[i] * X[:, i] for i < num_unconverged\n    void block_xpby(BlockVector const &Z, std::vector<std::complex<double>> alphas, size_t num) {\n        DiagonalMatrix<std::complex<double>,Dynamic,Dynamic> D = Map<VectorXcd>(alphas.data(), num).asDiagonal();\n        vec.leftCols(num) = Z.vec.leftCols(num) + vec.leftCols(num) * D;\n    }\n\n    void copy(BlockVector const &X, size_t num) {\n        vec.leftCols(num) = X.vec.leftCols(num);\n    }\n\n    void fill(std::complex<double> val) {\n        vec.fill(val);\n    }\n\n    auto cols() {\n        return vec.cols();\n    }\n\n    void repack(std::vector<size_t> const &ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            auto j = ids[i];\n            if (j != i) {\n                vec.col(i) = vec.col(j);\n            }\n        }\n    }\n};\n\n// This is a linear but special operator A(X)\n// producing AX + XD where D_ii = shifts[i] is a diagonal matrix.\n// So column-wise it performs (A + shift[i])X[:, i]\n// the multiply function basically does a gemv on every column with a different shift\n// so alpha * A(X) + beta * Y.\nstruct PosDefMatrixShifted {\n    DiagonalMatrix<double, Dynamic, Dynamic> A;\n    VectorXd shifts;\n\n    void multiply(double alpha, BlockVector const &u, double beta, BlockVector &v, size_t num) {\n        v.vec.leftCols(num) = alpha * A * u.vec.leftCols(num) + alpha * u.vec.leftCols(num) * shifts.head(num).asDiagonal() + beta * v.vec.leftCols(num);\n    }\n\n    void repack(std::vector<size_t> const &ids) {\n        for (size_t i = 0; i < ids.size(); ++i) {\n            auto j = ids[i];\n            if (j != i) {\n                shifts[i] = shifts[j];\n            }\n        }\n    }\n};\n\nstruct IdentityPreconditioner {\n    void apply(BlockVector &C, BlockVector const &B) {\n        C = B;\n    }\n    void repack(std::vector<size_t> const &ids) {\n        // nothing to do;\n    }\n};\n\nint main() {\n    size_t m = 40;\n    size_t n = 10;\n\n    auto A_shifts = VectorXd::LinSpaced(n, 1, n);\n    auto A_diag = VectorXd::LinSpaced(m, 1, m);\n\n    auto A = PosDefMatrixShifted{\n        A_diag.asDiagonal(),\n        A_shifts\n    };\n\n    auto P = IdentityPreconditioner{};\n\n    auto U = BlockVector{MatrixXcd::Zero(m, n)};\n    auto C = BlockVector{MatrixXcd::Zero(m, n)};\n    auto X = BlockVector{MatrixXcd::Random(m, n)};\n    auto B = BlockVector{MatrixXcd::Random(m, n)};\n    auto R = B;\n\n    auto tol = 1e-10;\n\n    auto resnorms = sirius::cg::multi_cg(\n        A, P,\n        X, R, U, C,\n        100, tol, false\n    );\n\n    // check the residual norms according to the algorithm\n    for (size_t i = 0; i < resnorms.size(); ++i) {\n        std::cout << \"shift \" << i << \" needed \" << resnorms[i].size() << \" iterations \" << std::abs(resnorms[i].back()) << \"\\n\";\n\n        if (std::abs(resnorms[i].back()) > tol) {\n            return 1;\n        }\n    }\n\n    // True residual norms might be different! because of rounding errors.\n    VectorXd true_resnorms = (A_diag.asDiagonal() * X.vec + X.vec * A_shifts.asDiagonal() - B.vec).colwise().norm();\n\n    for (Eigen::Index i = 0; i < true_resnorms.size(); ++i) {\n        std::cout << \"true resnorm \" << i << \": \" << true_resnorms[i] << '\\n';\n        if (true_resnorms[i] > tol * 100) {\n            return 2;\n        }\n    }\n}", "meta": {"hexsha": "43b06a72bc8e5c0d6a61a43a32d4b0613729ac32", "size": 4270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/unit_tests/multi_cg/test_multi_cg_complex.cpp", "max_stars_repo_name": "simonpp/SIRIUS", "max_stars_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T08:48:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T08:48:55.000Z", "max_issues_repo_path": "apps/unit_tests/multi_cg/test_multi_cg_complex.cpp", "max_issues_repo_name": "simonpintarelli/SIRIUS", "max_issues_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "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": "apps/unit_tests/multi_cg/test_multi_cg_complex.cpp", "max_forks_repo_name": "simonpintarelli/SIRIUS", "max_forks_repo_head_hexsha": "f4b5c4810af2a3ea1e67992d65750535227da84b", "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.7194244604, "max_line_length": 153, "alphanum_fraction": 0.5723653396, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.5526624596697258}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2018 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//[eigen_eg\n#include <iostream>\n#include <boost/multiprecision/cpp_complex.hpp>\n#include <boost/multiprecision/eigen.hpp>\n#include <Eigen/Dense>\n\nint main()\n{\n   using namespace Eigen;\n   typedef boost::multiprecision::cpp_complex_quad complex_type;\n   //\n   // We want to solve Ax = b for x,\n   // define A and b first:\n   //\n   Matrix<complex_type, 2, 2> A, b;\n   A << complex_type(2, 3), complex_type(-1, -2), complex_type(-1, -4), complex_type(3, 6);\n   b << 1, 2, 3, 1;\n   std::cout << \"Here is the matrix A:\\n\" << A << std::endl;\n   std::cout << \"Here is the right hand side b:\\n\" << b << std::endl;\n   //\n   // Solve for x:\n   //\n   Matrix<complex_type, 2, 2> x = A.fullPivHouseholderQr().solve(b);\n   std::cout << \"The solution is:\\n\" << x << std::endl;\n   //\n   // Compute the error in the solution by using the norms of Ax - b and b:\n   //\n   complex_type::value_type relative_error = (A*x - b).norm() / b.norm();\n   std::cout << \"The relative error is: \" << relative_error << std::endl;\n   return 0;\n}\n//]\n\n/*\n//[eigen_out\nHere is the matrix A:\n(2,3) (-1,-2)\n(-1,-4)   (3,6)\nHere is the right hand side b:\n1 2\n3 1\nThe solution is:\n(0.6,-0.6)   (0.7,-0.7)\n(0.64,-0.68) (0.58,-0.46)\nThe relative error is: 2.63132e-34\n//]\n*/\n", "meta": {"hexsha": "a70e3fbcf527f14e5a5c5261351e7e3ee173affe", "size": 1487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/multiprecision/example/eigen_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/multiprecision/example/eigen_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/multiprecision/example/eigen_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": 28.0566037736, "max_line_length": 91, "alphanum_fraction": 0.5965030262, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.5526624539856263}}
{"text": "#include \"graycode.h\"\n#include <iostream>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <boost/math/special_functions/round.hpp>\n\nbool CalculateGP(cv::Mat& absPhase, std::vector<cv::Mat> &images, int startGray, int endGray, int startPhase)\n{\n    cv::Mat gray_code(absPhase.rows, absPhase.cols, CV_8UC1);\n    cv::Mat phase(absPhase.rows, absPhase.cols, CV_8UC1);\n    cv::Mat mask(absPhase.rows, absPhase.cols, CV_8UC1);\n\n    if(!CalculateGrayCodeImg(gray_code, images, startGray, endGray))\n    {\n        std::cout << \"Error creating gray code image\";\n        return false;\n    }\n    cv::imwrite(\"graycode.jpg\", gray_code);\n\n    CalculateAbsolutePhase(phase, images, startPhase);\n\n    cv::imwrite(\"phase.jpg\", phase);\n\n    MaskEvaluation(mask, images[startPhase], images[startPhase+1], images[startPhase+2], images[startPhase+3], 5, 255, 10); //defults\n    BinaryAndOperation(phase, mask);\n    BinaryAndOperation(gray_code, mask);\n\n    cv::imwrite(\"phase2.jpg\", phase);\n\n    EvaluateAbsPhase(absPhase, phase, gray_code);\n\n    return false;\n}\n\nbool CalculateGrayCodeImg( cv::Mat& code_img, std::vector<cv::Mat>& images, long StartIndex, long EndIndex )\n{\n    unsigned char *normal = NULL;\n    unsigned char *invers = NULL;\n    unsigned char *result = NULL;\n    long           j, h, BitPlane;\n    unsigned long  k;\n\n    // Check if we have correct amount of images\n    if( static_cast<long>(images.size()) <= EndIndex || (EndIndex-StartIndex+1)!=16 )\n    {\n        std::cout << \"not enough images provided\\n\";\n        return false;\n    }\n\n    for( int i=StartIndex; i<=EndIndex; i++ )\n    {\n        if( images[i].type() != CV_8UC1 )\n        {\n\t\t\tcv::cvtColor(images[i], images[i], CV_BGR2GRAY);\n            //std::cout << \"Wrong image type\\n\";\n            //return false;\n        }\n    }\n\n    unsigned int width = images[0].cols;\n    unsigned int height = images[0].rows;\n\n    // Image size and format test\n    if( code_img.type() != CV_8UC1 || code_img.cols != width || code_img.rows != height )\n    {\n        std::cout << \"wrong format of gray image\\n\";\n        return false;\n    }\n\n    for( unsigned int i=0; i < height; i++ )\n    {\n        result = (unsigned char*)code_img.row(i).data;\n        memset(result, 0, code_img.cols );\n\n        for( j=0; j<=7; j++ )\n        {\n            normal = (unsigned char*)images[2*j+StartIndex].row(i).data;\n            invers = (unsigned char*)images[2*j+1+StartIndex].row(i).data;\n            BitPlane = 1 << (7-j);\n\n            for( k=0; k < width; k++ )\n            {\n                if (normal[k] > invers[k]){\n                    result[k] = (unsigned char)( result[k] | BitPlane );\n                }\n            }\n        }\n\n        for( k=0; k < width; k++ )\n        {\n            h = result[k];\n            // inverse graycode calculation\n            result[k] = (unsigned char)( LinearCode( h & 255 ) );\n        }\n    }\n    return true;\n}\n\nbool CalculateAbsolutePhase(cv::Mat& phase_img, std::vector<cv::Mat>& images, int offset)\n{\n    unsigned char *P;\n    unsigned char *Q;\n    unsigned char *S;\n    unsigned char *T;\n    unsigned char *result;\n\n    long\ti,j;\n    long\tA,B;\n    double\tScale;\n    long\tImgWidth, ImgHeight;\n\n    ImgWidth = images[0].cols;\n    ImgHeight = images[0].rows;\n\n    if( phase_img.type() != CV_8UC1 || phase_img.cols != ImgWidth || phase_img.rows != ImgHeight )\n    {\n        std::cout << \"wrong format of phase image\";\n        return false;\n    }\n\n    Scale = 128.0/M_PI;\n\n    // all rows\n    for( i=0; i<ImgHeight; i++ )\n    {\n        P = images[offset+0].row( i ).data;\n        Q = images[offset+1].row( i ).data;\n        S = images[offset+2].row( i ).data;\n        T = images[offset+3].row( i ).data;\n        result = (unsigned char*)phase_img.row( i ).data;\n        // all columns\n        for( j=0; j<ImgWidth; j++ ) {\n            A = S[j] - P[j];\n            B = T[j] - Q[j];\n            if ((A == 0) && (B == 0)) result[j] = (unsigned char)(0);\n            else result[j] = (unsigned char)boost::math::lround(atan2((double)A, (double)B)*Scale);\n        }\n    }\n    return true;\n}\n\nvoid MaskEvaluation(cv::Mat& Mask, const cv::Mat& Phase1, const cv::Mat& Phase2, const cv::Mat& Phase3, const cv::Mat& Phase4,\n                           int DynamicThreshold, int MaximumThreshold, int SinusThreshold )\n{\n    unsigned char* P;\n    unsigned char* Q;\n    unsigned char* S;\n    unsigned char* T;\n    unsigned char* R;\n    long W,H,I,J;\n    long Min,Max;\n\n    W = (long)(Mask.cols);\n    H = (long)(Mask.rows);\n\n    for (I = 0; I < H; I++)\n    {\n        P = (unsigned char*) Phase1.row(I).data;\n        Q = (unsigned char*) Phase2.row(I).data;\n        S = (unsigned char*) Phase3.row(I).data;\n        T = (unsigned char*) Phase4.row(I).data;\n        R = (unsigned char*) Mask.row(I).data;\n\n        for (J = 0; J < W; J++)\n        {\n            Min = (*P);\n            Max = (*P);\n            if ((*Q) < Min) Min = (*Q); else if ((*Q) > Max) Max = (*Q);\n            if ((*S) < Min) Min = (*S); else if ((*S) > Max) Max = (*S);\n            if ((*T) < Min) Min = (*T); else if ((*T) > Max) Max = (*T);\n\n            if( (Max-Min)>=DynamicThreshold )\n            {\n                if( MaximumThreshold==255 ) {\n                    if( (*P) <MaximumThreshold && (*Q)<MaximumThreshold && (*S)<MaximumThreshold && (*T)<MaximumThreshold )\n                        *R = (unsigned char)(255);\n                    else if( abs( ( (*P) + (*S) ) - ( (*Q) + (*T) ) ) <= SinusThreshold )\t//ist die Phase sinusf\\F6rmig?\n                        *R = (unsigned char)(255);\n                    else\n                        *R = (unsigned char)(0);\n                }\n                else {\n                    if( (*P)<=MaximumThreshold && (*Q)<=MaximumThreshold && (*S)<=MaximumThreshold && (*T)<=MaximumThreshold )\n                        *R = (unsigned char)(255);\n                    else\n                        *R = (unsigned char)(0);\n                }\n            }\n            else *R = (unsigned char)(0);\n\n            P++; Q++; S++; T++; R++;\n        }\n    }\n}\n\nunsigned int BinaryAND(cv::Mat& dst, const cv::Mat& src)\n{\n    unsigned char *S;\n    unsigned char *D;\n    long i;\n    long j;\n    long H, W;\n    unsigned int errval;\n\n    W = (long)( dst.cols );\n    H = (long)( dst.rows );\n\n    // rows\n    for( i = 0; i < H; i++)\n    {\n        D = (unsigned char*) dst.row(i).data;\n        S = (unsigned char*) src.row(i).data;\n        // cols\n        for (j = 0; j < W; j++)\n        {\n            unsigned char dval = (D[j]);\n            unsigned char sval = (S[j]);\n            D[j] = dval & sval;\n            //D[j] &= S[j];\n        }\n    }\n    return 0;\n}\n\n\nvoid EvaluateAbsPhase(cv::Mat& AbsPhase, cv::Mat& Phase, cv::Mat& GCode)\n{\n    unsigned char* GC;\n    unsigned char* Ph;\n    unsigned short* APh;\n    long I,j;\n    long c,p,PRI;\n    long W,H;\n\n    W = (long)(GCode.cols);\n    H = (long)(GCode.rows);\n\n    PRI = 64;\n\n    for(j=0; j < H  ; j++)\n    {\n        GC = (unsigned char*)GCode.row(j).data;\n        Ph = (unsigned char*)Phase.row(j).data;\n        APh = (unsigned short*)AbsPhase.row(j).data;\n\n        for (I = 0; I < W; I++)\n        {\n            c = (*GC);\n            p = (char)(*Ph);\n            if ((c < 1)||(c > 254))\n            {\n                *APh = 0;\n            }\n            else\n            {\n                if (p < -PRI)\n                {\n                    if (c & 1)\n                    {\n                        c++;\n                    }\n                }\n                else\n                {\n                    if (p > PRI)\n                    {\n                        if (!(c & 1))\n                        {\n                            c--;\n                        }\n                    }\n                }\n                *APh = (unsigned short)(((c >> 1) << 8) + p);\n            }\n            GC++; Ph++; APh++;\n        }// endfor\n    }// end for j\n}\n\nunsigned long LinearCode(unsigned long n)\n{\n    unsigned long idiv;\n    int ish = 1;\n    unsigned long ans = n;\n\n    for(;;)\n    {\n        ans ^= ( idiv = ans >> ish );\n        if( idiv <= 1 || ish == 16 )\n            return ans;\n        ish <<= 1;\n    }\n}\n\ndouble BLInterpolate(double x, double y, const cv::Mat &Phase)\n{\n    //bilinear interpolation\n    double dx = x-(int)x;\n    double dy = y-(int)y;\n\n    short ptl = Phase.at<short>((int)y , (int)x);\n    short ptr = Phase.at<short>((int)y, (int)x+1);\n    short pbl = Phase.at<short>((int)y+1, (int)x);\n    short pbr = Phase.at<short>((int)y+1, (int)x+1);\n\n    double weight_tl = (1.0 - dx) * (dy);\n    double weight_tr = (dx)       * (dy);\n    double weight_bl = (1.0 - dx) * (1.0 - dy);\n    double weight_br = (dx)       * (1.0 - dy);\n\n    return (ptl*weight_tl)+(ptr*weight_tr)+(pbl*weight_bl)+(pbr*weight_br);\n}\n\nunsigned int BinaryAndOperation(cv::Mat& dst, const cv::Mat& src)\n{\n    unsigned char *S;\n    unsigned char *D;\n    long i;\n    long j;\n    long H, W;\n    unsigned int errval;\n\n    // check image compatibility\n    //if( (errval = CompatImages( dst, src, PIX_8BIT ) ) != OK ) return errval;\n\n    W = (long)( dst.cols );\n    H = (long)( dst.rows );\n\n    // rows\n    for( i = 0; i < H; i++)\n    {\n        D = (unsigned char*) dst.row(i).data;\n        S = (unsigned char*) src.row(i).data;\n        // cols\n        for (j = 0; j < W; j++)\n        {\n            unsigned char dval = (D[j]);\n            unsigned char sval = (S[j]);\n            D[j] = dval & sval;\n            //D[j] &= S[j];\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "3ede5cadb18c622b3fda1a30acead6e5d994ce4e", "size": 9486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graycode.cpp", "max_stars_repo_name": "for-aiur/scan3d", "max_stars_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graycode.cpp", "max_issues_repo_name": "for-aiur/scan3d", "max_issues_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-04T06:41:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T06:41:01.000Z", "max_forks_repo_path": "graycode.cpp", "max_forks_repo_name": "for-aiur/scan3d", "max_forks_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_forks_repo_licenses": ["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.4956521739, "max_line_length": 133, "alphanum_fraction": 0.4792325532, "num_tokens": 2660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.5526229737732709}}
{"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: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/estimators/estimate_uncalibrated_absolute_pose.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <ceres/rotation.h>\n#include <memory>\n#include <vector>\n\n#include \"theia/sfm/camera/projection_matrix_utils.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/estimators/feature_correspondence_2d_3d.h\"\n#include \"theia/sfm/pose/four_point_focal_length.h\"\n#include \"theia/sfm/types.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::Matrix3d;\nusing Eigen::Vector3d;\n\n// An estimator for computing the uncalibrated absolute pose from 4 feature\n// correspondences. The feature correspondences should be normalized such that\n// the principal point is at (0, 0).\nclass UncalibratedAbsolutePoseEstimator\n    : public Estimator<FeatureCorrespondence2D3D, Matrix3x4d> {\n public:\n  UncalibratedAbsolutePoseEstimator() {}\n\n  // 3 correspondences are needed to determine the absolute pose.\n  double SampleSize() const { return 4; }\n\n  // Estimates candidate absolute poses from correspondences.\n  bool EstimateModel(\n      const std::vector<FeatureCorrespondence2D3D>& correspondences,\n      std::vector<Matrix3x4d>* absolute_poses) const {\n    const std::vector<Eigen::Vector2d> features = {correspondences[0].feature,\n                                                   correspondences[1].feature,\n                                                   correspondences[2].feature,\n                                                   correspondences[3].feature};\n    const std::vector<Eigen::Vector3d> world_points = {\n        correspondences[0].world_point,\n        correspondences[1].world_point,\n        correspondences[2].world_point,\n        correspondences[3].world_point};\n\n    const int num_solutions =\n        FourPointPoseAndFocalLength(features, world_points, absolute_poses);\n    return num_solutions > 0;\n  }\n\n  // The error for a correspondences given an absolute pose. This is the squared\n  // reprojection error.\n  double Error(const FeatureCorrespondence2D3D& correspondence,\n               const Matrix3x4d& absolute_pose) const {\n    // The reprojected point is computed as R * (X - c) where R is the camera\n    // rotation, c is the position, and X is the 3D point.\n    const Eigen::Vector2d reprojected_feature =\n        (absolute_pose * correspondence.world_point.homogeneous())\n            .eval()\n            .hnormalized();\n    return (reprojected_feature - correspondence.feature).squaredNorm();\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(UncalibratedAbsolutePoseEstimator);\n};\n\n}  // namespace\n\nbool EstimateUncalibratedAbsolutePose(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence2D3D>& normalized_correspondences,\n    UncalibratedAbsolutePose* absolute_pose,\n    RansacSummary* ransac_summary) {\n  UncalibratedAbsolutePoseEstimator absolute_pose_estimator;\n  std::unique_ptr<SampleConsensusEstimator<UncalibratedAbsolutePoseEstimator> >\n      ransac = CreateAndInitializeRansacVariant(\n          ransac_type, ransac_params, absolute_pose_estimator);\n  // Estimate the absolute pose.\n  Matrix3x4d projection_matrix;\n  const bool success = ransac->Estimate(\n      normalized_correspondences, &projection_matrix, ransac_summary);\n\n  // Recover the focal length and pose.\n  Eigen::Matrix3d calibration_matrix;\n  Eigen::Vector3d rotation;\n  DecomposeProjectionMatrix(projection_matrix,\n                            &calibration_matrix,\n                            &rotation,\n                            &absolute_pose->position);\n\n  // Convert angle-axis rotation to rotation matrix.\n  ceres::AngleAxisToRotationMatrix(\n      rotation.data(),\n      ceres::ColumnMajorAdapter3x3(absolute_pose->rotation.data()));\n\n  absolute_pose->focal_length =\n      calibration_matrix(0, 0) / calibration_matrix(2, 2);\n\n  return success;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "101b702409f377a0212c05827cab2e34834da161", "size": 5802, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_uncalibrated_absolute_pose.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_uncalibrated_absolute_pose.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_uncalibrated_absolute_pose.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": 40.8591549296, "max_line_length": 80, "alphanum_fraction": 0.7257842123, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5526229661409883}}
{"text": "#include <vector>\n\n#include <glm/glm.hpp>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n\n#include \"Types.h\"\n#include \"Dynamic.h\"\n\nnamespace{\n    using namespace BalloonFEM;\n    const Vec3 v[4] = {Vec3(0), Vec3(1, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)};\n    const Mat3x2 m[3][3] = {\n        { Mat3x2(v[1], v[0]), Mat3x2(v[2], v[0]), Mat3x2(v[3], v[0])},\n        { Mat3x2(v[0], v[1]), Mat3x2(v[0], v[2]), Mat3x2(v[0], v[3])},\n        { -Mat3x2(v[1], v[1]), -Mat3x2(v[2], v[2]), -Mat3x2(v[3], v[3])}\n    };\n}\n\nnamespace BalloonFEM\n{\n    void Engine::computeFilmForces(ObjState &state, Vvec3 &f_sum)\n    {\n        Vvec3 &pos = state.world_space_pos;\n\n\t\t/* compute film elastic force */\n\n\t\tfor (MIter f = m_tetra->films.begin(); f != m_tetra->films.end(); f++)\n\t\t{\n\t\t\tfor (PIter p = f->pieces.begin(); p != f->pieces.end(); p++)\n\t\t\t{\n\t\t\t\tiVec3 &id = p->v_id;\n\t\t\t\tVec3 &v0 = pos[id[0]];\n\t\t\t\tVec3 &v1 = pos[id[1]];\n\t\t\t\tVec3 &v2 = pos[id[2]];\n\n\t\t\t\t/* calculate deformation in world space */\n\t\t\t\tMat3x2 Ds = Mat3x2(v0 - v2, v1 - v2);\n\n\t\t\t\t/* calculate deformation gradient */\n\t\t\t\tMat3x2 F = Ds * p->Bm;\n\n\t\t\t\t/* calculate Piola for this tetra */\n\t\t\t\tMat3x2 P = m_film_model->Piola(F);\n\n\t\t\t\t/* calculate forces contributed from this tetra */\n\t\t\t\tMat3x2 H = - p->volume() * P * transpose(p->Bm);\n\n\t\t\t\tf_sum[id[0]] += H[0];\n\t\t\t\tf_sum[id[1]] += H[1];\n\t\t\t\tf_sum[id[2]] -= H[0] + H[1];\n\t\t\t}\n\t\t}\n        \n    }\n\n    SpMat Engine::computeFilmDiffMat(ObjState &state)\n    {\n       \tprintf(\"building film force differential matrix \\n\");\n\t\t/* project from constrained freedom state to world space */\n\t\tVvec3 &pos = state.world_space_pos; \n\n\t    std::vector<T> coefficients;\n\t\tcoefficients.clear();\n\t\tsize_t count_film = 0;\n\t\tfor (size_t i = 0; i < m_tetra->films.size(); i++)\n\t\t\tcount_film += m_tetra->films[i].pieces.size();\n\t\tcoefficients.reserve( 9 * 9 * count_film);\n\n\t\tfor (MIter f = m_tetra->films.begin(); f != m_tetra->films.end(); f++)\n        {\n\t\t\tfor (PIter p = f->pieces.begin(); p != f->pieces.end(); p++)\n\t\t\t{\n\t\t\t\t/* assgin world space position */\n\t\t\t\tiVec3 &id = p->v_id;\n\t\t\t\tVec3 &v0 = pos[id[0]];\n\t\t\t\tVec3 &v1 = pos[id[1]];\n\t\t\t\tVec3 &v2 = pos[id[2]];\n\n\t\t\t\t/* calculate deformation in world space */\n\t\t\t\tMat3x2 Ds = Mat3x2(v0 - v2, v1 - v2);\n\n\t\t\t\t/* calculate deformation gradient */\n\t\t\t\tMat3x2 F = Ds * p->Bm;\n\n\t\t\t\t/* i is index of vertex, j is index of dimention */\n\t\t\t\tfor (size_t i = 0; i < 3; i++)\n\t\t\t\tfor (size_t j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\t/* calculate delta deformation in world space */\n\t\t\t\t\tMat3x2 dDs = m[i][j];\n\n\t\t\t\t\t/* calculate delta deformation gradient */\n\t\t\t\t\tMat3x2 dF = dDs * p->Bm;\n\n\t\t\t\t\t/* calculate delta Piola */\n\t\t\t\t\tMat3x2 dP = m_film_model->StressDiff(F, dF);\n\n\t\t\t\t\t/* calculate forces contributed from this tetra */\n\t\t\t\t\tMat3x2 dH = - p->volume() * dP * transpose(p->Bm);\n\n\t\t\t\t\tfor (size_t w = 0; w < 2; w++)\n\t\t\t\t\tfor (size_t l = 0; l < 3; l++)\n\t\t\t\t\t\tcoefficients.push_back(T(3 * id[w] + l, 3 * id[i] + j, dH[w][l]));\n\n\t\t\t\t\tVec3 df_3 = - dH[0] - dH[1];\n\t\t\t\t\tfor (size_t l = 0; l < 3; l++)\n\t\t\t\t\t\tcoefficients.push_back(T(3 * id[2] + l, 3 * id[i] + j, df_3[l]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tSpMat E( 3 * pos.size(), 3 * pos.size());\n\t\tE.setFromTriplets(coefficients.begin(), coefficients.end());\n\n        return E;\n    }\n}\n", "meta": {"hexsha": "ddc11b9d1839fe91f860442cd2fd4af902b62342", "size": 3240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Dynamic_Film.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_Film.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_Film.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": 27.0, "max_line_length": 77, "alphanum_fraction": 0.5524691358, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5525957558113849}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <numeric>\n#include <queue>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) (a).begin(), (a).end()\n#define AALL(a, n) (a), ((a) + (n))\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n#define MODNUM (INT(1e9 + 7))\n#define MOD(x) ((x) % MODNUM)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconst int INF = 2e9;\nconst double EPS = 1e-10;\nconst double PI = acos(-1.0);\n\nconst int dx[] = {-1, 0, 1, 0};\nconst int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nint sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nint sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T>\nvoid chmax(T& m, T x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T>\nvoid chmin(T& m, T x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nT square(T x) {\n\treturn x * x;\n}\n\ninline int toInt(string s) {\n\tint v;\n\tistringstream sin(s);\n\tsin >> v;\n\treturn v;\n}\n\n// modを取りつつ二項係数を計算する関数を返す\nauto make_mod_comb(long long mod) {\n\tconst int COMB_MAX = 1100000;\n\tvector<long long> fact(COMB_MAX);\n\tvector<long long> fact_inv(COMB_MAX);\n\tvector<long long> inv(COMB_MAX);\n\n\tfact[0] = fact[1] = 1;\n\tfact_inv[0] = fact_inv[1] = 1;\n\tinv[1] = 1;\n\n\tfor(int i = 2; i < COMB_MAX; i++) {\n\t\tfact[i] = (fact[i - 1] * i) % mod;\n\t\tinv[i] = mod - (inv[mod % i] * (mod / i)) % mod;\n\t\tfact_inv[i] = (fact_inv[i - 1] * inv[i]) % mod;\n\t}\n\n\treturn [mod = mod, fact = move(fact), fact_inv = move(fact_inv)](\n\t\t\t   const long long n, const long long r) {\n\t\tif(n < r || n < 0 || r < 0) {\n\t\t\treturn 0LL;\n\t\t}\n\t\treturn (fact[n] * ((fact_inv[r] * fact_inv[n - r]) % mod)) % mod;\n\t};\n}\n\nint main() {\n\tint r1, c1, r2, c2;\n\tscanf(\"%d %d %d %d\", &r1, &c1, &r2, &c2);\n\tauto mod_comb = make_mod_comb(MODNUM);\n\tll result = 0;\n\tRANGE(i, r1, r2 + 1) {\n\t\tRANGE(j, c1, c2 + 1) { result = MOD(result + mod_comb(i + j, i)); }\n\t}\n\tprintf(\"%lld\\n\", result);\n\treturn 0;\n}", "meta": {"hexsha": "cdc057bde92b58f0abb96cac4e8e85c2c03daef6", "size": 2410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC154/F.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/ABC154/F.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/ABC154/F.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": 21.5178571429, "max_line_length": 76, "alphanum_fraction": 0.5904564315, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.5525094056627184}}
{"text": "#include \"sargparse/File.h\"\n#include \"sargparse/Parameter.h\"\n\n#include \"stl/STLParser.h\"\n#include \"global_parameters.h\"\n\n#include \"tetrahedron.h\"\n#include \"transformer.h\"\n\n#include <iostream>\n#include <vector>\n#include <armadillo>\n\nvoid print_mass_properties();\nsargp::Command cmd { \"mass_properties\", \"show mass properties\", print_mass_properties };\n\nauto totalMass = cmd.Parameter<std::optional<double>>({}, \"total_mass\", \"total mass of the object (used to calculate mass properties)\");\nauto density = cmd.Parameter<std::optional<double>>({}, \"density\", \"density of the object (used to calculate mass properties)\");\nauto tensorPerspectiveOrigin = cmd.Flag(\"tensor_from_origin\", \"print the tensor from the perspective of the origin frame\");\n\n\nauto skew(arma::colvec3 const& v)\n{\n    return arma::mat33 {\n        { 0, -v(2), v(1) },\n        { v(2), 0, -v(0) },\n        { -v(1), v(0), 0 },\n    };\n}\n\nvoid print_mass_properties()\n{\n    if (not inFiles) {\n        throw std::runtime_error(\"in has to be specified!\");\n    }\n\n    kinematicTree::visual::stl::STLParser parser;\n    kinematicTree::visual::mesh::Mesh mesh;\n    for (auto const& file : *inFiles) {\n        std::cout << \"loading : \" << file << \"\\n\";\n        auto subMesh = parser.parse(file);\n\t\tfor (auto const& facet : subMesh.getFacets()) {\n\t\t\tmesh.addFacet(facet);\n\t\t}\n    }\n\n\tauto transform = getTransform();\n    transform.print(\"applying transform\");\n    mesh.applyTransform(transform);\n\n    arma::mat33 inertia_tensor = arma::zeros(3, 3);\n    double totalVolume {};\n    arma::colvec3 com {};\n\n    for (auto const& facet : mesh.getFacets()) {\n        if (facet.mVertices.size() < 3) {\n            continue;\n        }\n        auto const& base = facet.mVertices[0];\n        for (auto i { 1 }; i < facet.mVertices.size() - 1; ++i) {\n            auto tetrahedron = Tetrahedron { { base, facet.mVertices[i], facet.mVertices[i + 1] } };\n\n            totalVolume += tetrahedron.volume;\n            com += tetrahedron.com * tetrahedron.volume;\n            inertia_tensor += tetrahedron.normed_inertia_tensor;\n        }\n    }\n\n    com = com / totalVolume;\n\n    std::cout << \"volume: \" << totalVolume << \"\\n\";\n    com.print(\"COM\");\n    std::cout << \"\\n\\n\";\n\n    if (*density) {\n        auto totMass = totalVolume * **density;\n        std::cout << \"properties by given density: (\" << **density << \")\\n\\n\";\n        std::cout << \"total mass: \" << totMass << \"\\n\";\n        arma::mat33 I = inertia_tensor * **density;\n\n        if (not *tensorPerspectiveOrigin) {\n            // move the inertia_tensor to the COM\n            I += totMass * skew(com) * skew(com);\n        }\n\n        I.print(\"inertia tensor\");\n    }\n\n    if (*totalMass) {\n        auto density = **totalMass / totalVolume;\n        std::cout << \"properties by given total mass: (\" << **totalMass << \")\\n\\n\";\n        std::cout << \"density: \" << density << \"\\n\";\n        arma::mat33 I = inertia_tensor * density;\n\n        // move the inertia_tensor to the COM\n        if (not *tensorPerspectiveOrigin) {\n            I += **totalMass * skew(com) * skew(com);\n        }\n\n        I.print(\"inertia tensor\");\n    }\n}\n", "meta": {"hexsha": "ce1f5162569d04895b788639563871860df35a66", "size": 3120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mass_properties.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/mass_properties.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/mass_properties.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": 30.2912621359, "max_line_length": 136, "alphanum_fraction": 0.5916666667, "num_tokens": 814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.5524879063931263}}
{"text": "#include <dirent.h>\r\n#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n#include <utility>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/LU>\r\n#include <Eigen/Geometry>\r\n\r\n#include <opencv2/opencv.hpp>\r\n#define pi acos(-1)\r\n\r\nconst int G_land_num = 74;\r\nconst int G_train_pic_id_num = 3300;\r\nconst int G_nShape = 47;\r\nconst int G_nVerts = 11510;\r\nconst int G_nFaces = 11540;\r\nconst int G_test_num = 77;\r\nconst int G_iden_num = 77;\r\nconst int G_inner_land_num = 59;\r\nconst int G_line_num = 50;\r\nconst int G_jaw_land_num = 20;\r\n#define normalization\r\nstruct Target_type {\r\n\tEigen::VectorXf exp;\r\n\tEigen::RowVector3f tslt;\r\n\tEigen::Matrix3f rot;\r\n\tEigen::MatrixX2f dis;\r\n\r\n};\r\n\r\nstruct DataPoint\r\n{\r\n\tcv::Mat image;\r\n\tcv::Rect face_rect;\r\n\tstd::vector<cv::Point2d> landmarks;\r\n\t//std::vector<cv::Point2d> init_shape;\r\n\tTarget_type shape, init_shape;\r\n\tEigen::VectorXf user;\r\n\tEigen::RowVector2f center;\r\n\tEigen::MatrixX2f land_2d;\r\n#ifdef posit\r\n\tfloat f;\r\n#endif // posit\r\n#ifdef normalization\r\n\tEigen::MatrixX3f s;\r\n#endif\r\n\r\n\tEigen::VectorXi land_cor;\r\n};\r\n\r\n\r\nvoid load_lv(std::string name, DataPoint &temp) {\r\n\tstd::cout << \"load coefficients...file:\" << name << \"\\n\";\r\n\tFILE *fp;\r\n\tfopen_s(&fp, name.c_str(), \"rb\");\r\n\r\n\ttemp.user.resize(G_iden_num);\r\n\tfor (int j = 0; j < G_iden_num; j++)\r\n\t\tfread(&temp.user(j), sizeof(float), 1, fp);\r\n\tstd::cout << temp.user << \"\\n\";\r\n\tsystem(\"pause\");\r\n\ttemp.land_2d.resize(G_land_num, 2);\r\n\tfor (int i_v = 0; i_v < G_land_num; i_v++) {\r\n\t\tfread(&temp.land_2d(i_v, 0), sizeof(float), 1, fp);\r\n\t\tfread(&temp.land_2d(i_v, 1), sizeof(float), 1, fp);\r\n\t}\r\n\r\n\r\n\tfread(&temp.center(0), sizeof(float), 1, fp);\r\n\tfread(&temp.center(1), sizeof(float), 1, fp);\r\n\r\n\ttemp.shape.exp.resize(G_nShape);\r\n\tfor (int i_shape = 0; i_shape < G_nShape; i_shape++)\r\n\t\tfread(&temp.shape.exp(i_shape), sizeof(float), 1, fp);\r\n\r\n\tfor (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++)\r\n\t\tfread(&temp.shape.rot(i, j), sizeof(float), 1, fp);\r\n\r\n\tfor (int i = 0; i < 3; i++) fread(&temp.shape.tslt(i), sizeof(float), 1, fp);\r\n\r\n\ttemp.land_cor.resize(G_land_num);\r\n\tfor (int i_v = 0; i_v < G_land_num; i_v++) fread(&temp.land_cor(i_v), sizeof(int), 1, fp);\r\n\r\n\ttemp.s.resize(2, 3);\r\n\tfor (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++)\r\n\t\tfread(&temp.s(i, j), sizeof(float), 1, fp);\r\n\r\n\ttemp.shape.dis.resize(G_land_num, 2);\r\n\tfor (int i_v = 0; i_v < G_land_num; i_v++) {\r\n\t\tfread(&temp.shape.dis(i_v, 0), sizeof(float), 1, fp);\r\n\t\tfread(&temp.shape.dis(i_v, 1), sizeof(float), 1, fp);\r\n\t}\r\n\tstd::cout << temp.shape.dis << \"\\n\";\r\n\tsystem(\"pause\");\r\n\tfclose(fp);\r\n\tputs(\"load successful!\");\r\n}\r\n\r\n\r\n//assume the be could not be more than 90\r\nvoid cal_uler_angle(Eigen::Matrix3f R) {\r\n\tEigen::Vector3f x, y, z,t;\r\n\tx = R.row(0).transpose();\r\n\ty = R.row(1).transpose();\r\n\tz = R.row(2).transpose();\r\n\tfloat al, be, ga, gaw;\r\n\tif (fabs(1 - z(2)*z(2)) < 1e-3) {\r\n\t\tga=gaw=be = 0;\r\n\t\tal = acos(x(0));\r\n\t\tif (y(0) < 0) al = 2 * pi - al;\r\n\t}\r\n\telse {\r\n\t\t\r\n\t\tbe = acos(z(2));\r\n\t\tal = acos(std::max(std::min(float(1.0),z(1) / sqrt(1 - z(2)*z(2))),float(-1.0)));\r\n\t\t\r\n\t\tif (z(0) < 0) al = 2 * pi - al;//according to the sin(al)\r\n\r\n\r\n\t\tt(0) = cos(al), t(1) = sin(al), t(2) = 0;\r\n\t\tt.normalize();\r\n\t\tx.normalize();\r\n\t\t//t.normalized();\r\n\t\tga = acos(t.dot(x));\r\n\t\tgaw = acos(std::max(std::min(float(1.0), -y(2) / sqrt(1 - z(2)*z(2))), float(-1.0)));\r\n\r\n\t\tprintf(\"%.10f %.10f %.10f\\n\", -y(2), sqrt(1 - z(2)*z(2)), -y(2) / sqrt(1 - z(2)*z(2)));\r\n\t\tif (x(2) < 0) ga = 2 * pi - ga, gaw = 2 * pi - gaw;//according to the sin(ga)\r\n\t}\r\n\tstd::cout << R << \"\\n----------------------\\n\";\r\n\tprintf(\"%.10f %.10f %.10f %.10f %.10f\\n\",z(2), al/pi*180, be / pi * 180, ga / pi * 180, gaw / pi * 180);\r\n\tsystem(\"pause\");\r\n}\r\n\r\nEigen::Matrix3f get_r_from_angle(float angle, int axis) {\r\n\tEigen::Matrix3f ans;\r\n\tans.setZero();\r\n\tans(axis, axis) = 1;\r\n\tint idx_x = 0, idx_y = 1;\r\n\tif (axis == 0)\r\n\t\tidx_x = 1, idx_y = 2;\r\n\telse\r\n\t\tif (axis == 2)\r\n\t\t\tidx_x = 0, idx_y = 1;\r\n\t\telse\r\n\t\t\tidx_x = 0, idx_y = 2;\r\n\tans(idx_x, idx_x) = cos(angle), ans(idx_x, idx_y) = -sin(angle), ans(idx_y, idx_x) = sin(angle), ans(idx_y, idx_y) = cos(angle);\r\n\treturn ans;\r\n}\r\n\r\nEigen::Matrix3f get_r_from_angle(const Eigen::Vector3f &angle) {\r\n\tEigen::Matrix3f ans;\r\n\tfloat Sa = sin(angle(0)), Ca = cos(angle(0)), Sb = sin(angle(1)),\r\n\t\tCb = cos(angle(1)), Sc = sin(angle(2)), Cc = cos(angle(2));\r\n\r\n\tans(0, 0) = Ca * Cc - Sa * Cb*Sc;\r\n\tans(0, 1) = -Sa * Cc - Ca * Cb*Sc;\r\n\tans(0, 2) = Sb * Sc;\r\n\tans(1, 0) = Ca * Sc + Sa * Cb*Cc;\r\n\tans(1, 1) = -Sa * Sc + Ca * Cb*Cc;\r\n\tans(1, 2) = -Sb * Cc;\r\n\tans(2, 0) = Sa * Sb;\r\n\tans(2, 1) = Ca * Sb;\r\n\tans(2, 2) = Cb;\r\n\treturn ans;\r\n}\r\nvoid test_r(DataPoint data) {\r\n\tEigen::Matrix3f rot;\r\n\trot = get_r_from_angle(data.shape.tslt(2), 2)*get_r_from_angle(data.shape.tslt(1), 0)*get_r_from_angle(data.shape.tslt(0), 2);\r\n\tstd::cout << rot << \"\\n\";\r\n\tstd::cout << get_r_from_angle(data.shape.tslt) << \"\\n\";\r\n\tsystem(\"pause\");\r\n}\r\n\r\nint main() {\r\n\r\n\tDataPoint data;\r\n\tdata.shape.tslt << 1, 20, 0.5;\r\n\ttest_r(data);\r\n\t//load_lv(\"./test/pose_4_t108.lv\",data);//data/test_debug_lv_005_04_03_051_05\r\n\t//cal_uler_angle(data.shape.rot);\r\n\t\r\n\treturn 0;\r\n}\r\n//g++ -Wall -std=c++11 `pkg-config --cflags opencv` -o deal deal_falut.cpp `pkg-config --libs opencv`", "meta": {"hexsha": "de3ec3afab229f12c593d07a538f2639123f8789", "size": 5248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hhhaha/tri/uler_angle.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": "hhhaha/tri/uler_angle.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": "hhhaha/tri/uler_angle.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": 28.064171123, "max_line_length": 130, "alphanum_fraction": 0.5866996951, "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.5524878897083544}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXcf A = MatrixXcf::Random(4,4);\nHessenbergDecomposition<MatrixXcf> hd(4);\nhd.compute(A);\ncout << \"The matrix H in the decomposition of A is:\" << endl << hd.matrixH() << endl;\nhd.compute(2*A); // re-use hd to compute and store decomposition of 2A\ncout << \"The matrix H in the decomposition of 2A is:\" << endl << hd.matrixH() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "44db0effea1d66f135a63bb68c4ad3dffee447a7", "size": 490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_compute.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_compute.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_compute.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7894736842, "max_line_length": 86, "alphanum_fraction": 0.6857142857, "num_tokens": 141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.5524878843696815}}
{"text": "/*\n * Copyright (c) 2013-2014 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef MATRIX_INVERSION_HPP\n#define MATRIX_INVERSION_HPP\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#if defined(BOOST_UBLAS_TYPE_CHECK)\n#define MATRIX_INVERSION_SAVE BOOST_UBLAS_TYPE_CHECK\n#undef BOOST_UBLAS_TYPE_CHECK\n#define BOOST_UBLAS_TYPE_CHECK 0\n#include <boost/numeric/ublas/lu.hpp>\n#undef BOOST_UBLAS_TYPE_CHECK\n#define BOOST_UBLAS_TYPE_CHECK MATRIX_INVERSION_SAVE\n#else\n#define BOOST_UBLAS_TYPE_CHECK 0\n#include <boost/numeric/ublas/lu.hpp>\n#undef BOOST_UBLAS_TYPE_CHECK\n#endif\n\n\n#ifdef USE_LAPACK\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/blas/blas3.hpp>\nnamespace bnb = boost::numeric::bindings;\n#endif\n\n#ifdef USE_ATLAS\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\nnamespace bnb = boost::numeric::bindings;\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T>\nbool invert(const ub::matrix<T>& a, ub::matrix<T>& b) {\n\tub::matrix<T> tmp(a);\n\tub::permutation_matrix<> pm(tmp.size1());\n\n\tif (ub::lu_factorize(tmp, pm) != 0) return false;\n\n\tb = ub::identity_matrix<T>(tmp.size1());\n\n\ttry {\n\t\tub::lu_substitute(tmp, pm, b);\n\t}\n\tcatch (...) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n// special version for double\n#if defined(USE_LAPACK) || defined(USE_ATLAS)\ntemplate <>\nbool invert(const ub::matrix<double>& a, ub::matrix<double>& b) {\n\tub::matrix<double, ub::column_major> tmp(a);\n\tub::permutation_matrix<int> pm(tmp.size1());\n\n\t#ifdef USE_LAPACK\n\tif (bnb::lapack::getrf(tmp, pm) != 0) return false;\n\tif (bnb::lapack::getri(tmp, pm) != 0) return false;\n\t#endif\n\t#ifdef USE_ATLAS\n\tif (bnb::atlas::getrf(tmp, pm) != 0) return false;\n\tif (bnb::atlas::getri(tmp, pm) != 0) return false;\n\t#endif\n\n\tb = tmp;\n\n\treturn true;\n}\n#endif // defined(USE_LAPACK) || defined(USE_ATLAS)\n\n\ntemplate <class T>\nbool linear_equation(const ub::matrix<T>& a, const ub::vector<T>& b, ub::vector<T>& x) {\n\tub::matrix<T> tmp(a);\n\tub::permutation_matrix<> pm(tmp.size1());\n\n\tif (ub::lu_factorize(tmp, pm) != 0) return false;\n\n\tx = b;\n\n\tub::lu_substitute(tmp, pm, x);\n\n\treturn true;\n}\n\n// special version for double\n#if defined(USE_LAPACK) || defined(USE_ATLAS)\ntemplate <>\nbool linear_equation(const ub::matrix<double>& a, const ub::vector<double>& b, ub::vector<double>& x) {\n\tub::matrix<double, ub::column_major> tmp(a);\n\t// int i;\n\t// int size = tmp.size1();\n\tub::matrix<double, ub::column_major> tmp2(tmp.size1(), 1);\n\n\t// for (i=0; i<size; i++) tmp2(i, 0) = b(i);\n\t// ub::column(tmp2, 0).assign(b);\n\tub::column(tmp2, 0) = b;\n\n\t#ifdef USE_LAPACK\n\tif (bnb::lapack::gesv(tmp, tmp2) != 0) return false;\n\t#endif\n\t#ifdef USE_ATLAS\n\tif (bnb::atlas::gesv(tmp, tmp2) != 0) return false;\n\t#endif\n\n\t// for (i=0; i<size; i++) x(i) = tmp2(i, 0);\n\tx = ub::column(tmp2, 0);\n\n\treturn true;\n}\n#endif // defined(USE_LAPACK) || defined(USE_ATLAS)\n\ntemplate <class T>\nvoid mm_mult(const ub::matrix<T>& a, const ub::matrix<T>& b, ub::matrix<T>& c) {\n\tc = ub::prod(a, b);\n}\n\n// special version for double\n#if defined(USE_LAPACK) || defined(USE_ATLAS)\ntemplate <>\nvoid mm_mult(const ub::matrix<double>& a, const ub::matrix<double>& b, ub::matrix<double>& c) {\n\tub::matrix<double, ub::column_major> ca(a);\n\tub::matrix<double, ub::column_major> cb(a);\n\tub::matrix<double, ub::column_major> cc(c);\n\n\t#ifdef USE_LAPACK\n\t\tbnb::blas::gemm(ca, cb, cc);\n\t#endif\n\t#ifdef USE_ATLAS\n\t\tbnb::atlas::gemm(ca, cb, cc);\n\t#endif\n\n\tc = cc;\n}\n#endif // defined(USE_LAPACK) || defined(USE_ATLAS)\n\n} // namespace kv\n\n#endif // MATRIX_INVERSION_HPP\n", "meta": {"hexsha": "f534fab06ecb43fc233454d9a9ba41297aaeccba", "size": 3749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/matrix-inversion.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/matrix-inversion.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/matrix-inversion.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": 24.1870967742, "max_line_length": 103, "alphanum_fraction": 0.6945852227, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.5523914691818396}}
{"text": "/// @file  linalg.hpp\n/// @brief Linear algebra routines.\n\n#pragma once\n#ifndef ORDGEO_LINALG_LINALG_HPP\n#define ORDGEO_LINALG_LINALG_HPP\n\n#include <ordgeo/config.hpp>\n#include <Eigen/Eigen>\n#include <exception>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace ORDGEO_NAMESPACE {\nnamespace linalg {\n\n/// An exception to throw in case of mathematical error in some linear algebra\n/// routine.\nstruct LinAlgErr : public std::runtime_error {\n\tvirtual ~LinAlgErr() = default;\n\n\t/// Build an LinAlgErr with the specified message.\n\tLinAlgErr(std::string message)\n\t\t: std::runtime_error(\"ordgeo::LinAlgErr: \" + message) {\n\t}\n};\n\n/// The eigenvalues and eigenvectors of a matrix\nstruct EigResult {\n\tvirtual ~EigResult() = default;\n\n\t/// The eigenvalues\n\tEigen::ArrayXcd eig;\n\n\t/// The eigenvectors\n\tEigen::EigenSolver<Eigen::MatrixXd>::EigenvectorsType vec;\n};\n\n/// Iterates over nonzero entries in a dense vector.\ntemplate<typename T>\nstruct DenseNZIterator {\n\tDenseNZIterator(const T& vector) : _vec(vector), _idx(-1) { ++(*this); }\n\tvirtual ~DenseNZIterator() = default;\n\tvoid operator++() {\n\t\t++_idx;\n\t\twhile (_idx < _vec.size() && _vec[_idx] == 0) {\n\t\t\t++_idx;\n\t\t}\n\t}\n\toperator bool() const {\n\t\treturn _idx < _vec.size();\n\t}\n\tsize_t index() const {\n\t\treturn static_cast<size_t>(_idx);\n\t}\n\n\tconst T& _vec;\n\tint _idx;\n};\n\n/// Compute the eigenvalues and eigenvectors of a matrix.\n/// Throws LinAlgErr on failure.\nEigResult eigendecomposition(const Eigen::MatrixXd& matrix,\n\tbool assumeSelfAdjoint = false);\n\n/// Ask whether a matrix is positive semidefinite.\n/// This tests whether the eigenvalues are non-negative, to within eps\n/// precision.\n/// Any PSD matrix is a valid n x n distance matrix for some Euclidean space\n/// R^d, with d <= n - 1.\nbool isPSD(const Eigen::MatrixXd& matrix, double eps = 1e-12);\n\n/// Attempt to project a matrix onto the PSD cone.\n/// Throws LinAlgErr in case of failure.\n/// This will produce a PSD matrix which is as close as possible to the input\n/// matrix. This is often used with methods which compute matrices to satisfy\n/// some loss minimization objective without constraining those matrices to be\n/// distance matrices. The output from such a method can be projected onto the\n/// PSD cone to obtain the PSD solution which is as close as possible to the\n/// solution with minimal loss. This is sometimes faster than constraining the\n/// optimization problem to stay within the PSD cone.\nEigen::MatrixXd projectOntoPSDCone(const Eigen::MatrixXd& matrix,\n\tbool assumeSelfAdjoint);\n\n/// Project a matrix onto the nearest matrix of the specified rank.\n/// This works by setting the smallest eigenvalues to zero.\nEigen::MatrixXd projectOntoLowRank(const Eigen::MatrixXd& matrix, size_t rank);\n\n/// Project a matrix onto the nuclear norm ball.\n/// This has the effect of reducing its rank.\n///\n/// [1] Efficient Projections onto the .1-Ball for Learning in High Dimensions.\n///     John Duchi, Shai Shalev-Shwartz, Yoram Singer, and Tushar Chandra.\n///     International Conference on Machine Learning (ICML 2008)\n///     http://www.cs.berkeley.edu/~jduchi/projects/DuchiSiShCh08.pdf\nEigen::MatrixXd projectOntoNuclearNorm(const Eigen::MatrixXd& matrix,\n\tdouble lambda);\n\n/// Project a matrix onto the unit sphere.\n/// All vectors are scaled to unit length.\nEigen::MatrixXd projectOntoUnitSphere(const Eigen::MatrixXd& matrix);\n\n/// A position match is a rotation/reflection, translation, and scaling of a\n/// position matrix so that its points are as close as possible to the positions\n/// of the corresponding rows in some target matrix.\n/// This is also known as a Procrustes transformation.\nstruct PositionMatch {\n\tvirtual ~PositionMatch() = default;\n\n\t/// Finds a Procrustes transformation which minimizes the sum of squared\n\t/// distances between corresponding rows of target and testee.\n\t///\n\t/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory\n\t///     and applications. Springer.\n\tstatic std::shared_ptr<PositionMatch> Create(const Eigen::MatrixXd& target,\n\t\tconst Eigen::MatrixXd& testee);\n\n\t/// Transforms a matrix in-place into the target space.\n\tvirtual void transform(Eigen::MatrixXd& matrix) = 0;\n\n\t/// Return the rotation matrix.\n\tvirtual Eigen::MatrixXd rotationMatrix() const = 0;\n\n\t/// Return the translation vector.\n\tvirtual Eigen::VectorXd translationVector() const = 0;\n\n\t/// Return the scaling factor.\n\tvirtual double scalingFactor() const = 0;\n};\n\n/// Find the distance scaling which minimizes the difference between two\n/// distance matrices, in a least-squares sense.\ndouble distScalingFactor(const Eigen::MatrixXd& dhat,\n\tconst Eigen::MatrixXd& dtrue);\n\n/// Select the specified rows of a matrix.\ntemplate<typename mat_type>\nmat_type selectRows(const mat_type& X, std::vector<size_t> rows) {\n\tmat_type result(rows.size(), X.cols());\n\tfor (size_t ii = 0; ii < rows.size(); ii++) {\n\t\tresult.row(ii) = X.row(rows[ii]);\n\t}\n\treturn result;\n}\ntemplate<>\nEigen::SparseMatrix<double, Eigen::RowMajor> selectRows(\n\tconst Eigen::SparseMatrix<double, Eigen::RowMajor>& X,\n\tstd::vector<size_t> rows);\n\n/// Convert a position matrix into a Euclidean distance matrix.\ntemplate<typename mat_type>\nEigen::MatrixXd posToDist(const mat_type& X) {\n\tEigen::MatrixXd B = X * X.transpose();\n\tEigen::VectorXd c = B.diagonal();\n\tEigen::VectorXd one = Eigen::VectorXd::Ones(X.rows());\n\treturn (c * one.transpose() + one * c.transpose() - 2 * B).cwiseSqrt();\n}\n\n/// Convert a position matrix into a Cosine distance matrix.\ntemplate<typename mat_type>\nEigen::MatrixXd posToCosineDist(const mat_type& X) {\n\tEigen::MatrixXd dists(X.rows(), X.rows());\n\tEigen::VectorXd norm(X.rows());\n\tfor (Eigen::Index ii = 0; ii < X.rows(); ii++) {\n\t\tnorm(ii) = X.row(ii).norm();\n\t}\n\tfor (Eigen::Index ii = 0; ii < X.rows(); ii++) {\n\t\tauto a = X.row(ii);\n\t\tfor (Eigen::Index jj = 0; jj < ii; jj++) {\n\t\t\tauto b = X.row(jj);\n\t\t\tdists(ii,jj) = 1.0 - (a.dot(b) / (norm(ii) + norm(jj)));\n\t\t\tdists(jj,ii) = dists(ii,jj);\n\t\t}\n\t}\n\treturn dists;\n}\n\n/// Convert a position matrix into a Jaccard distance matrix.\ntemplate<typename M, typename V, typename IT>\nEigen::MatrixXd posToJaccardDist(const M& X) {\n\tEigen::MatrixXd dists(X.rows(), X.rows());\n\tfor (Eigen::Index ii = 0; ii < X.rows(); ii++) {\n\t\tV a = X.row(ii);\n\t\tfor (Eigen::Index jj = 0; jj < ii; jj++) {\n\t\t\tV b = X.row(jj);\n\n\t\t\tIT ita(a), itb(b);\n\t\t\tdouble inBoth = 0, total = 0;\n\t\t\twhile (ita && itb) {\n\t\t\t\ttotal++;\n\t\t\t\tif (ita.index() < itb.index()) {\n\t\t\t\t\t++ita;\n\t\t\t\t} else if (ita.index() > itb.index()) {\n\t\t\t\t\t++itb;\n\t\t\t\t} else {\n\t\t\t\t\tinBoth++;\n\t\t\t\t\t++ita;\n\t\t\t\t\t++itb;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (; ita; ++ita) {\n\t\t\t\ttotal++;\n\t\t\t}\n\t\t\tfor (; itb; ++itb) {\n\t\t\t\ttotal++;\n\t\t\t}\n\n\t\t\tdists(ii,jj) = total ? (total - inBoth) / total : INFINITY;\n\t\t\tdists(jj,ii) = dists(ii,jj);\n\t\t}\n\t}\n\treturn dists;\n}\n\n/// Center a matrix\nEigen::MatrixXd centerMatrix(const Eigen::MatrixXd& X);\n\n/// Center a position matrix about the origin, and scale it to unit diameter\nEigen::MatrixXd normalizePos(const Eigen::MatrixXd& X);\n\n/// Transform a vector by isotonic regression so its values are changed by the\n/// smallest amount possible to appear in the specified order.\n///\n/// Implements the PAVA algorithm with uniform weights, as described here:\n/// http://stat.wikia.com/wiki/Isotonic_regression\nEigen::VectorXd isotonicRegression(const Eigen::VectorXd& V,\n\tconst Eigen::VectorXd& weights, const std::vector<Eigen::Index>& order);\n\n/// Calculate the Euclidean distance between two points.\ninline double dist(const Eigen::MatrixXd& X, Eigen::Index a, Eigen::Index b) {\n\tassert(a < X.rows());\n\tassert(b < X.rows());\n\treturn (X.row(a) - X.row(b)).norm();\n}\n\n/// Calculate the squared Euclidean distance between two points.\ninline double sqDist(const Eigen::MatrixXd& X, Eigen::Index a, Eigen::Index b) {\n\tassert(a < X.rows());\n\tassert(b < X.rows());\n\treturn (X.row(a) - X.row(b)).squaredNorm();\n}\n\n/// Get pairwise squared Euclidean distances from a dissimilarity kernel.\nEigen::MatrixXd sqDistsFromKernel(const Eigen::MatrixXd& K);\n\n/// Calculate the squared Euclidean distance between two points from a kernel.\ninline double sqDistFromKernel(const Eigen::MatrixXd K, Eigen::Index a,\n\tEigen::Index b) {\n\tassert(K.rows() == K.cols());\n\tassert(a < K.rows());\n\tassert(b < K.rows());\n\treturn K(a,a) + K(b,b) - 2 * K(a,b);\n}\n\n/// Get an embedding from a dissimilarity kernel via SVD\nEigen::MatrixXd embeddingFromKernelSVD(const Eigen::MatrixXd& K, size_t nDim);\n\n/// Compute a kernel matrix from a given position/feature matrix.\ntemplate<typename mat_type>\nEigen::MatrixXd kernelForFeatures(const mat_type& mat) {\n\tEigen::Index nObj = mat.rows();\n\tEigen::MatrixXd kernel = Eigen::MatrixXd::Zero(nObj, nObj);\n\tfor (Eigen::Index ii = 0; ii < nObj; ii++) {\n\t\tfor (Eigen::Index jj = 0; jj <= ii; jj++) {\n\t\t\tkernel(ii,jj) = mat.row(ii).dot(mat.row(jj));\n\t\t\tif (ii != jj) {\n\t\t\t\tkernel(jj,ii) = kernel(ii,jj);\n\t\t\t}\n\t\t}\n\t}\n\treturn kernel;\n}\n\n/// Find the intersection of spheres with k-dimensional center coordinates.\n/// The sphere centers are given as the columns of centers.\n/// The quality variable is negative if the spheres do not intersect,\n/// zero if they intersect in R^k, and positive if they intersect in R^(k+1).\n/// Citation: Thm. 3.3 from\n///     H.X. Huang, Z.-A. Liang, and P. M. Pardalos,\n///     \"Some Properties for the Euclidean Distance Matrix and Positive\n///     Semidefinite Matrix Completion Problems,\"\n///     J Glob Optim, vol. 25, no. 1, pp. 3–21, 2003.\nEigen::VectorXd sphereIntersection(const Eigen::MatrixXd& centers,\n\tconst Eigen::VectorXd& radii, double& quality);\n\n\n} // end namespace linalg\n} // end namespace ORDGEO_NAMESPACE\n#endif /* ORDGEO_LINALG_LINALG_HPP */\n", "meta": {"hexsha": "b8875699359ebffadb5d6a4f1bc59493e26481bd", "size": 9666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ordgeo/linalg/linalg.hpp", "max_stars_repo_name": "jesand/ordgeo", "max_stars_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T10:29:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T10:29:04.000Z", "max_issues_repo_path": "include/ordgeo/linalg/linalg.hpp", "max_issues_repo_name": "jesand/ordgeo", "max_issues_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ordgeo/linalg/linalg.hpp", "max_forks_repo_name": "jesand/ordgeo", "max_forks_repo_head_hexsha": "370725ad551e3926e9c508ec23deec9cbe8fc346", "max_forks_repo_licenses": ["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.2164948454, "max_line_length": 80, "alphanum_fraction": 0.6983240223, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5523914546512549}}
{"text": "#include <iostream>\n#include <nbsimMyFunctions.h>\n#include <nbsimExceptionMacro.h>\n#include \"nbsimParticle.h\"\n#include \"nbsimMassiveParticle.h\"\n#include \"nbsimSolarSystemData.ipp\"\n#include <Eigen/Dense>\n#include <CLI/CLI.hpp>\n#include <chrono>\n#include <omp.h>\n\nint main(int argc, char** argv){\n    CLI::App app{\"solar system simulator\"};\n    double step_size, total_time;\n    app.add_option(\"-s,--timestep\", step_size,  \"step size, unit:year\");\n    app.add_option(\"-t,--totaltime\", total_time,  \"duration of simulation, unit:year\");\n\n    std::string planet_name[9];\n    Eigen::Vector3d init_position, init_velocity, r_com(0,0,0), p_total(0,0,0);\n    double mu,mu_total=0;\n    std::shared_ptr<nbsim::MassiveParticle> planet_ptr[9];\n    CLI11_PARSE(app, argc, argv);\n\n    std::clock_t c_start = std::clock();\n    auto t_start = std::chrono::high_resolution_clock::now();\n    omp_set_num_threads(16);\n\n    #pragma omp parallel for\n    for (int i=0; i<9; i++) {\n\t\tplanet_name[i]=nbsim::solarSystemData[i].name;\n\t\tinit_position=nbsim::solarSystemData[i].position;\n\t\tinit_velocity=nbsim::solarSystemData[i].velocity;\n        mu=nbsim::solarSystemData[i].mu;\n        mu_total+=mu;\n        std::shared_ptr<nbsim::MassiveParticle> ptr_particle_i(new nbsim::MassiveParticle(init_position, init_velocity, mu/6.67408e-11));\n\t\tplanet_ptr[i]=ptr_particle_i;\n\t}\n    \n    for (int i=0; i<9; i++){\n\t\tfor (int j=0; j<9; j++){\n\t\t\tplanet_ptr[i]->addAttractor(planet_ptr[j]);\n            if (planet_ptr[i]==planet_ptr[j]){\n                planet_ptr[i]->removeAttractor(planet_ptr[j]);\n            }\n\t\t}\n\t}  \n    #pragma omp parallel\n    for (double test_time=0; test_time<total_time; test_time+=step_size){\n        \n        #pragma omp for \n\t\tfor (int i=0;i<9;i++){\n\t\t\tplanet_ptr[i]->calculateAcceleration();\n\t\t}\n        #pragma omp for nowait\n\t\tfor (int i=0;i<9;i++){\n\t\t\tplanet_ptr[i]->integrateTimestep(step_size);\n\t\t}\t\n\t}\n    #pragma omp parallel for\n    for (int i=0;i<9;i++){\n        r_com+=nbsim::solarSystemData[i].mu*(planet_ptr[i]->getPosition());\n        p_total+=nbsim::solarSystemData[i].mu*(planet_ptr[i]->getVelocity());\n    }\n    std::clock_t c_end = std::clock();\n    auto t_end = std::chrono::high_resolution_clock::now();\n    \n    r_com=r_com/mu_total;\n    \n    for (int i=0;i<9;i++){\n\t\tstd::cout<<planet_name[i]<<\"\\n original position:\"<<nbsim::solarSystemData[i].position<<\"\\n current position:\"<<planet_ptr[i]->getPosition()<<std::endl;\n        \n    }\n    std::cout<<\"\\n r_com is:\"<<r_com<<std::endl;\n    std::cout<<\"\\n p_total is:\"<<p_total<<std::endl;\n    std::cout << std::fixed << std::setprecision(2) << \"CPU time used: \"\n              << 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << \" ms\\n\"\n              << \"Wall clock time passed: \"\n              << std::chrono::duration<double, std::milli>(t_end-t_start).count()\n              << \" ms\\n\";\n    return 0;\n}", "meta": {"hexsha": "8d30523ea2326b8a48c1918d214f7f19eb935e54", "size": 2868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_stars_repo_name": "zys711/cpp_Assignment2", "max_stars_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_issues_repo_name": "zys711/cpp_Assignment2", "max_issues_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_forks_repo_name": "zys711/cpp_Assignment2", "max_forks_repo_head_hexsha": "f705f8a53d358c85f2d7e7d1a36536492d448a8e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4074074074, "max_line_length": 154, "alphanum_fraction": 0.6328451883, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5523914546512549}}
{"text": "#define DEBUG 1\n/**\n * File    : L.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/1/31 16:50:07\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// ----- main() -----\n\nchar to_char(int x)\n{\n  return x + 'A';\n}\n\nbool query(int const &x, int const &y)\n{\n  cout << \"? \" << to_char(x) << \" \" << to_char(y) << endl;\n  char a;\n  cin >> a;\n  return a == '<';\n}\n\ntemplate <typename Iter, typename Comp>\nvoid merge_sort(Iter begin, Iter end, Comp cmp);\n\ntemplate <typename Iter, typename Comp>\nvoid merge_sort_impl(Iter begin, Iter end, Comp cmp, random_access_iterator_tag)\n{\n  int N{static_cast<int>(end - begin)};\n  if (N <= 1)\n  {\n    return;\n  }\n  auto mid{begin + N / 2};\n  merge_sort(begin, mid, cmp);\n  merge_sort(mid, end, cmp);\n  vector<typename Iter::value_type> temp(N);\n  merge(begin, mid, mid, end, temp.begin(), cmp);\n  copy(temp.begin(), temp.end(), begin);\n}\n\ntemplate <typename Iter, typename Comp>\nvoid merge_sort(Iter begin, Iter end, Comp cmp)\n{\n  merge_sort_impl(begin, end, cmp, typename std::iterator_traits<Iter>::iterator_category());\n}\n\nbool check_vector(vector<int> const &V, int x, int y)\n{\n  for (auto e : V)\n  {\n    if (e == x)\n    {\n      return true;\n    }\n    else if (e == y)\n    {\n      return false;\n    }\n  }\n  assert(false);\n  return true;\n}\n\nint main()\n{\n  int N, Q;\n  cin >> N >> Q;\n  vector<int> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    V[i] = i;\n  }\n  if (Q == 1000)\n  {\n    sort(V.begin(), V.end(), query);\n    cout << \"! \";\n    for (auto i = 0; i < N; ++i)\n    {\n      cout << to_char(V[i]);\n    }\n    cout << endl;\n  }\n  else if (Q == 100)\n  {\n    merge_sort(V.begin(), V.end(), query);\n    cout << \"! \";\n    for (auto i = 0; i < N; ++i)\n    {\n      cout << to_char(V[i]);\n    }\n    cout << endl;\n  }\n  else\n  {\n    vector<vector<int>> W;\n    do\n    {\n      W.push_back(V);\n    } while (next_permutation(V.begin(), V.end()));\n    while (static_cast<int>(W.size()) > 1)\n    {\n      auto cnt{static_cast<int>(W.size())};\n      int ind_x = -1, ind_y = -1;\n      for (auto x = 0; x < N; ++x)\n      {\n        for (auto y = x + 1; y < N; ++y)\n        {\n          int tmp{0};\n          for (auto const &v : W)\n          {\n            if (check_vector(v, x, y))\n            {\n              ++tmp;\n            }\n          }\n          auto c_tmp{static_cast<int>(W.size()) - tmp};\n          auto t{max(tmp, c_tmp)};\n          if (cnt > t)\n          {\n            cnt = t;\n            ind_x = x;\n            ind_y = y;\n          }\n        }\n      }\n      assert(ind_x != -1 && ind_y != -1);\n      if (!query(ind_x, ind_y))\n      {\n        swap(ind_x, ind_y);\n      }\n      vector<vector<int>> U;\n      for (auto const &v : W)\n      {\n        if (check_vector(v, ind_x, ind_y))\n        {\n          U.push_back(v);\n        }\n      }\n      swap(U, W);\n    }\n    auto const &v{W[0]};\n    cout << \"! \";\n    for (auto i = 0; i < N; ++i)\n    {\n      cout << to_char(v[i]);\n    }\n    cout << endl;\n  }\n}\n", "meta": {"hexsha": "489097051b1a5c809cf64b4e12740eef34272ac3", "size": 7650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0131_language-test-202001/L.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/0131_language-test-202001/L.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/0131_language-test-202001/L.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.25, "max_line_length": 93, "alphanum_fraction": 0.5389542484, "num_tokens": 2395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5523279180266119}}
{"text": "#include \"wanglandau.h\"\n#include <limits>\n#include <iostream>\n#include <fstream>\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n\nnamespace wanglandau{\n\nWangLandau::WangLandau(int hsize, double flatness,\n                       double final_factor, int initial_threshold,\n                       double normalization, int normalization_origin)\n  :hsize_(hsize), hist_(hsize), g_(hsize),\n   flatness_(flatness), factor_(1.0), final_(final_factor),\n   threshold_(initial_threshold), stage_(1),\n   normalization_(normalization), normalization_origin_(normalization_origin)\n{\n}\n\nbool WangLandau::check_flat(bool verbose = false)\n{\n  long hmin = std::numeric_limits<long>::max();\n  int count = 0;\n  long hsum = 0;\n  for(int i=0; i<hsize_; ++i){\n    if(hist_[i] == 0) continue;\n    ++count;\n    hsum += hist_[i];\n    hmin = std::min(hmin, hist_[i]);\n  }\n  const double mean = static_cast<double>(hsum)/count;\n  const double fn = hmin / mean;\n  if(count < threshold_ || fn < flatness_){\n    if(verbose){\n      std::cout << \"Histogram is not flat. \"\n               << \"[ hmin = \" << hmin\n               << \", mean = \" << mean\n               << \", flatness = \" << fn\n               << \", nonzero bin = \" << count\n               << \", threshold = \" << threshold_\n               << \", factor = \" << factor_\n               << \"]\" << std::endl;\n    }\n    return false;\n  }else{\n    if(verbose){\n      std::cout << \"Histogram is     flat. \"\n               << \"[ hmin = \" << hmin\n               << \", mean = \" << mean\n               << \", flatness = \" << fn\n               << \", nonzero bin = \" << count\n               << \", threshold = \" << threshold_\n               << \", factor = \" << factor_\n               << \"]\" << std::endl;\n    }\n    threshold_ = count;\n    return true;\n  }\n}\n\nvoid WangLandau::update(bool verbose=false)\n{\n  bool flat = check_flat(verbose);\n  if(flat){\n\n    /*\n     * save and reset\n     */\n\n    std::string filename(\"hist-\");\n    filename += boost::lexical_cast<std::string>(stage_);\n    filename += \".dat\";\n    std::ofstream ofs(filename.c_str());\n    ofs << \"# $1 : index\" << std::endl;\n    ofs << \"# $2 : log of DoS\" << std::endl;\n    ofs << \"# $3 : population\" << std::endl;\n\n    const double offset = normalization_ - g_[normalization_origin_];\n    for(int i=0; i<hsize_; ++i){\n      g_[i] += offset;\n      if(hist_[i] != 0)\n        ofs << i << \" \" << g_[i] << \" \" << hist_[i] << std::endl;\n      hist_[i] = 0;\n    }\n\n    std::cout << \"# \" <<  stage_ << \" iteration (factor = \" << factor_ << \" ) finished.\" << std::endl;\n    factor_ *= 0.5;\n    ++stage_;\n  }\n}\n\n} // end of namespace wanglandau\n", "meta": {"hexsha": "e73b7a88e78047791e281d1b6bd831e498bb761d", "size": 2617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wanglandau.cpp", "max_stars_repo_name": "yomichi/Potts-WL", "max_stars_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wanglandau.cpp", "max_issues_repo_name": "yomichi/Potts-WL", "max_issues_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wanglandau.cpp", "max_forks_repo_name": "yomichi/Potts-WL", "max_forks_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_forks_repo_licenses": ["BSL-1.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.1397849462, "max_line_length": 102, "alphanum_fraction": 0.5231180741, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.5522987059346367}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n\n#include <fstream>\n#include <vector>\n#include <unordered_map>\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2017_11 : problem\n{\n\tadvent_2017_11() noexcept : problem(2017, 11) {\n\t}\n\nprotected:\n\tenum struct compass\n\t{\n\t\tn,\n\t\tne,\n\t\tse,\n\t\ts,\n\t\tsw,\n\t\tnw,\n\t};\n\n\tcompass str_to_direction(const std::string& str) {\n\t\tif(str == \"n\") {\n\t\t\treturn compass::n;\n\t\t} else if(str == \"ne\") {\n\t\t\treturn compass::ne;\n\t\t} else if(str == \"se\") {\n\t\t\treturn compass::se;\n\t\t} else if(str == \"s\") {\n\t\t\treturn compass::s;\n\t\t} else if(str == \"sw\") {\n\t\t\treturn compass::sw;\n\t\t} else if(str == \"nw\") {\n\t\t\treturn compass::nw;\n\t\t} else {\n\t\t\t__assume(0);\n\t\t}\n\t}\n\n\tstd::vector<compass> directions;\n\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\tstd::string line;\n\t\tstd::getline(fin, line);\n\t\tstd::vector<std::string> raw_directions;\n\t\tboost::split(raw_directions, line, [](char c) { return c == ','; });\n\t\tstd::transform(std::begin(raw_directions), std::end(raw_directions), std::back_inserter(directions), [&](const std::string& str) {\n\t\t\treturn str_to_direction(str);\n\t\t});\n\t}\n\n\tstd::size_t greatest_distance = 0;\n\tstd::size_t current_distance = 0;\n\n\tstruct hex_coord\n\t{\n\t\tstd::ptrdiff_t x, y, z;\n\n\t\thex_coord& operator+=(compass d) noexcept {\n\t\t\tswitch(d) {\n\t\t\tcase compass::n:      ++y; --z; break;\n\t\t\tcase compass::ne: ++x;      --z; break;\n\t\t\tcase compass::se: ++x; --y;      break;\n\t\t\tcase compass::s:      --y; ++z; break;\n\t\t\tcase compass::sw: --x;      ++z; break;\n\t\t\tcase compass::nw: --x; ++y;      break;\n\t\t\t}\n\t\t\treturn *this;\n\t\t}\n\t};\n\n\tstd::size_t distance_from_origin(hex_coord c) {\n\t\treturn gsl::narrow<std::size_t>((std::abs(c.x) + std::abs(c.y) + std::abs(c.z)) / 2);\n\t}\n\n\tvoid precompute() override {\n\t\thex_coord position{ 0, 0, 0 };\n\t\tstd::for_each(std::begin(directions), std::end(directions), [&](compass d) {\n\t\t\tposition += d;\n\t\t\tcurrent_distance = distance_from_origin(position);\n\t\t\tgreatest_distance = std::max(greatest_distance, current_distance);\n\t\t});\n\t}\n\n\tstd::string part_1() override {\n\t\treturn std::to_string(current_distance);\n\t}\n\n\tstd::string part_2() override {\n\t\treturn std::to_string(greatest_distance);\n\t}\n};\n\nREGISTER_SOLVER(2017, 11);\n", "meta": {"hexsha": "97f26d52fd4b68e890d7ae7cb17ff0f803cc10a6", "size": 2200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2017/day-11.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2017/day-11.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2017/day-11.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2222222222, "max_line_length": 132, "alphanum_fraction": 0.625, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355186, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.5521953762192975}}
{"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// @sect3{Include files}  \n\n// 前面几个（很多）include文件已经在前面的例子中使用过了，所以我们在这里不再解释它们的含义。\n\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/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/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <fstream> \n#include <iostream> \n\n// 这是新的，但是：在前面的例子中，我们从线性求解器得到了一些不需要的输出。如果我们想抑制它，我们必须包括这个文件，并在程序的某个地方添加一行字（见下面的main()函数）。\n\n#include <deal.II/base/logstream.h> \n\n// 最后一步，和以前的程序一样，是将所有deal.II的类和函数名导入全局命名空间中。\n\nusing namespace dealii; \n// @sect3{The <code>Step4</code> class template}  \n\n// 这又是前面例子中的 <code>Step4</code> 类。唯一不同的是，我们现在把它声明为一个带有模板参数的类，而模板参数当然是我们要解决拉普拉斯方程的空间维度。当然，几个成员变量也取决于这个维度，特别是Triangulation类，它必须分别表示四边形或六面体。除此以外，一切都和以前一样。\n\ntemplate <int dim> \nclass Step4 \n{ \npublic: \n  Step4(); \n  void run(); \n\nprivate: \n  void make_grid(); \n  void setup_system(); \n  void assemble_system(); \n  void solve(); \n  void output_results() const; \n\n  Triangulation<dim> triangulation; \n  FE_Q<dim>          fe; \n  DoFHandler<dim>    dof_handler; \n\n  SparsityPattern      sparsity_pattern; \n  SparseMatrix<double> system_matrix; \n\n  Vector<double> solution; \n  Vector<double> system_rhs; \n}; \n// @sect3{Right hand side and boundary values}  \n\n// 在下文中，我们又声明了两个类，表示右手边和非均质的Dirichlet边界值。两者都是一个二维空间变量的函数，所以我们也将它们声明为模板。\n\n// 这些类中的每一个都是从一个共同的、抽象的基类Function派生出来的，它声明了所有函数都必须遵循的共同接口。特别是，具体的类必须重载 <code>value</code> 函数，该函数接收二维空间中的一个点作为参数，并将该点的值作为 <code>double</code> 变量返回。\n\n//  <code>value</code> 函数需要第二个参数，我们在这里将其命名为 <code>component</code>  : 这只适用于矢量值函数，你可能想访问点 <code>p</code> 处的矢量的某个分量。然而，我们的函数是标量的，所以我们不需要担心这个参数，在函数的实现中也不会使用它。在库的头文件中，Function基类对 <code>value</code> 函数的声明中，分量的默认值为0，所以我们在访问右侧的 <code>value</code> 函数时，只需要一个参数，即我们要评估函数的点。然后，对于标量函数，可以简单地省略分量的值。\n\n// 函数对象在库中很多地方都有使用（例如，在 step-3 中我们使用了一个 Functions::ZeroFunction 实例作为 VectorTools::interpolate_boundary_values) 的参数，这是我们定义一个继承自Function的新类的第一个教程。由于我们只调用 Function::value(), ，我们可以只用一个普通的函数（这就是 step-5 中的做法），但由于这是一个教程，为了举例说明，我们继承了Function。\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\ntemplate <int dim> \nclass BoundaryValues : public Function<dim> \n{ \npublic: \n  virtual double value(const Point<dim> & p, \n                       const unsigned int component = 0) const override; \n}; \n\n// 如果你不熟悉上述函数声明中的关键字 \"virtual \"和 \"override \"是什么意思，你可能会想看看你最喜欢的C++书籍或在线教程，如http:www.cplusplus.com/doc/tutorial/polymorphism/ 。从本质上讲，这里发生的事情是Function<dim>是一个 \"抽象 \"基类，它声明了某种 \"接口\"--一组可以在这类对象上调用的函数。但它实际上并没有*实现*这些函数：它只是说 \"Function对象是这样的\"，但它实际上是什么样的函数，则留给实现了`value()`函数的派生类。\n\n// 从另一个类中派生出一个类，通常称为 \"is-a \"关系函数。在这里，`RightHandSide`类 \"是一个 \"函数类，因为它实现了Function基类所描述的接口。(\"value() \"函数的实际实现在下面的代码块中)。那么`virtual`关键字意味着 \"是的，这里的函数可以被派生类覆盖\"，而`override`关键字意味着 \"是的，这实际上是一个我们知道已经被声明为基类一部分的函数\"。覆盖 \"关键字不是严格必要的，但它是防止打字错误的一个保险。如果我们把函数的名字或一个参数的类型弄错了，编译器会警告我们说：\"你说这个函数覆盖了基类中的一个函数，但实际上我不知道有任何这样的函数有这个名字和这些参数。\"\n\n// 但回到这里的具体案例。在本教程中，我们选择2D中的函数 $4(x^4+y^4)$ ，或者3D中的 $4(x^4+y^4+z^4)$ 作为右手边。我们可以用空间维度上的if语句来写这个区别，但这里有一个简单的方法，通过使用一个短循环，也允许我们在一维（或四维，如果你想这样做）中使用相同的函数。 幸运的是，编译器在编译时就知道循环的大小（记住，在你定义模板时，编译器不知道 <code>dim</code> 的值，但当它后来遇到语句或声明 <code>RightHandSide@<2@></code> 时，它将采取模板，用2替换所有出现的dim，并编译出结果函数）。 换句话说，在编译这个函数的时候，主体将被执行的次数是已知的，编译器可以将循环所需的开销降到最低；结果将和我们马上使用上面的公式一样快。\n\n// 最后要注意的是， <code>Point@<dim@></code> 表示二维空间中的一个点，它的各个组成部分（即 $x$ 、 $y$ 、...坐标）可以像C和C++中一样用（）运算符访问（事实上，[]运算符也同样有效），索引从0开始。\n\ntemplate <int dim> \ndouble RightHandSide<dim>::value(const Point<dim> &p, \n                                 const unsigned int /*component*/) const \n{ \n  double return_value = 0.0; \n  for (unsigned int i = 0; i < dim; ++i) \n    return_value += 4.0 * std::pow(p(i), 4.0); \n\n  return return_value; \n} \n\n// 作为边界值，我们选择二维的 $x^2+y^2$ ，三维的 $x^2+y^2+z^2$ 。这恰好等于从原点到我们想评估函数的点的矢量的平方，而不考虑维度。所以这就是我们的返回值。\n\ntemplate <int dim> \ndouble BoundaryValues<dim>::value(const Point<dim> &p, \n                                  const unsigned int /*component*/) const \n{ \n  return p.square(); \n} \n\n//  @sect3{Implementation of the <code>Step4</code> class}  \n\n// 接下来是利用上述函数的类模板的实现。和以前一样，我们将把所有东西写成模板，这些模板有一个形式参数 <code>dim</code> ，在我们定义模板函数时，我们假设这个参数是未知的。只有在以后，编译器才会发现 <code>Step4@<2@></code> (in the <code>main</code> 函数的声明，实际上），并在编译整个类时将 <code>dim</code> 替换成2，这个过程被称为 \"模板的实例化\"。这样做的时候，它也会用 <code>RightHandSide@<dim@></code> 的实例替换 <code>RightHandSide@<2@></code> ，并从类模板中实例化后一个类。\n\n// 事实上，编译器也会在 <code>main()</code> 中找到一个 <code>Step4@<3@></code> 声明。这将导致它再次回到一般的 <code>Step4@<dim@></code> 模板，替换所有出现的 <code>dim</code> ，这次是3，并第二次编译这个类。注意这两个实例  <code>Step4@<2@></code>  和  <code>Step4@<3@></code>  是完全独立的类；它们唯一的共同特征是它们都是从同一个通用模板中实例化出来的，但是它们不能相互转换，例如，它们没有共享代码（两个实例都是完全独立编译的）。\n\n//  @sect4{Step4::Step4}  \n\n// 在这个介绍之后，这里是  <code>Step4</code>  类的构造函数。它指定了所需的有限元素的多项式程度，并将DoFHandler与三角形关联起来，就像在前面的例子程序中一样，  step-3  。\n\ntemplate <int dim> \nStep4<dim>::Step4() \n  : fe(1) \n  , dof_handler(triangulation) \n{} \n// @sect4{Step4::make_grid}  \n\n// 网格的创建在本质上是与维度有关的东西。然而，只要领域在二维或三维中足够相似，库就可以为你抽象。在我们的例子中，我们想再次在二维的正方形 $[-1,1]\\times [-1,1]$ 上求解，或者在三维的立方体 $[-1,1] \\times [-1,1] \\times [-1,1]$ 上求解；两者都可以被称为 GridGenerator::hyper_cube(), ，因此我们可以在任何维度上使用同一个函数。当然，在二维和三维中创建超立方体的函数有很大的不同，但这是你不需要关心的事情。让库来处理这些困难的事情。\n\ntemplate <int dim> \nvoid Step4<dim>::make_grid() \n{ \n  GridGenerator::hyper_cube(triangulation, -1, 1); \n  triangulation.refine_global(4); \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// @sect4{Step4::setup_system}  \n\n// 这个函数看起来和前面的例子完全一样，尽管它执行的动作在细节上有很大的不同，如果 <code>dim</code> 刚好是3。从用户的角度来看，唯一显著的区别是所产生的单元格数量，在三个空间维度中比两个空间维度中要高得多\n\ntemplate <int dim> \nvoid Step4<dim>::setup_system() \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()); \n  DoFTools::make_sparsity_pattern(dof_handler, dsp); \n  sparsity_pattern.copy_from(dsp); \n\n  system_matrix.reinit(sparsity_pattern); \n\n  solution.reinit(dof_handler.n_dofs()); \n  system_rhs.reinit(dof_handler.n_dofs()); \n} \n// @sect4{Step4::assemble_system}  \n\n// 与前面的例子不同，我们现在想使用一个非恒定的右侧函数和非零边界值。这两个任务都是很容易实现的，只需在矩阵和右手边的组合中增加几行代码即可。\n\n// 更有趣的是，我们将矩阵和右手边的向量维度独立组装起来的方式：与二维的情况根本没有区别。由于这个函数中使用的重要对象（正交公式、FEValues）也通过模板参数的方式依赖于维度，它们可以为这个函数所编译的维度正确设置一切。通过使用模板参数声明所有可能依赖于维度的类，库可以为你完成几乎所有的工作，你不需要关心大多数事情。\n\ntemplate <int dim> \nvoid Step4<dim>::assemble_system() \n{ \n  QGauss<dim> quadrature_formula(fe.degree + 1); \n\n// 我们希望有一个非恒定的右手，所以我们使用上面声明的类的一个对象来生成必要的数据。由于这个右侧对象只在本函数中局部使用，所以我们在这里把它声明为一个局部变量。\n\n  RightHandSide<dim> right_hand_side; \n\n// 与之前的例子相比，为了评估非恒定右手函数，我们现在还需要我们目前所在单元上的正交点（之前，我们只需要FEValues对象中的形状函数的值和梯度，以及正交权重， FEValues::JxW() ）。我们可以通过给FEValues对象添加#update_quadrature_points标志来让它为我们做事。\n\n  FEValues<dim> fe_values(fe, \n                          quadrature_formula, \n                          update_values | update_gradients | \n                            update_quadrature_points | update_JxW_values); \n\n// 然后我们再次定义与前面程序中相同的缩写。这个变量的值当然取决于我们现在使用的维度，但是FiniteElement类为你做了所有必要的工作，你不需要关心与维度有关的部分。\n\n  const unsigned int dofs_per_cell = fe.n_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// 接下来，我们又要在所有的单元格上进行循环，并汇集局部贡献。 请注意，一个单元在两个空间维度上是一个四边形，但在三维上是一个六面体。事实上， <code>active_cell_iterator</code> 的数据类型是不同的，这取决于我们所处的维度，但对外界来说，它们看起来是一样的，你可能永远不会看到区别。在任何情况下，真正的类型是通过使用`auto`来隐藏的。\n\n  for (const auto &cell : dof_handler.active_cell_iterators()) \n    { \n      fe_values.reinit(cell); \n      cell_matrix = 0; \n      cell_rhs    = 0; \n\n// 现在我们要把本地矩阵和右手边组合起来。这个过程和前面的例子完全一样，但是现在我们重新调整循环的顺序（我们可以安全地这样做，因为它们是相互独立的），并尽可能地合并本地矩阵和本地向量的循环，使事情变得更快。\n\n// 组装右手边与我们在 step-3 中的做法有唯一的区别：我们没有使用值为1的常数右手边，而是使用代表右手边的对象并在正交点对其进行评估。\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            const auto &x_q = fe_values.quadrature_point(q_index); \n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q) \n                            right_hand_side.value(x_q) *        // f(x_q) \n                            fe_values.JxW(q_index));            // dx \n          } \n\n// 作为对这些循环的最后说明：当我们将局部贡献集合到 <code>cell_matrix(i,j)</code> 时，我们必须将形状函数 $i$ 和 $j$ 在点号q_index的梯度相乘并与标量权重JxW相乘。这就是实际发生的情况。  <code>fe_values.shape_grad(i,q_index)</code> 返回一个 <code>dim</code> 维向量，由 <code>Tensor@<1,dim@></code> 对象表示，将其与 <code>fe_values.shape_grad(j,q_index)</code> 的结果相乘的运算器*确保两个向量的 <code>dim</code> 分量被适当收缩，结果是一个标量浮点数，然后与权重相乘。在内部，这个操作符*确保对向量的所有 <code>dim</code> 分量都能正确发生，无论 <code>dim</code> 是2、3还是其他空间维度；从用户的角度来看，这并不值得费心，然而，如果想独立编写代码维度，事情就会简单很多。\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            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// 作为这个函数的最后一步，我们希望在这个例子中拥有非均质的边界值，与之前的例子不同。这是一个简单的任务，我们只需要用一个描述我们想使用的边界值的类的对象（即上面声明的 <code>BoundaryValues</code> 类）来替换那里使用的 Functions::ZeroFunction 。\n\n// 函数 VectorTools::interpolate_boundary_values() 只对标有边界指标0的面起作用（因为我们在下面的第二个参数中说该函数应该对其起作用）。如果有的面的边界指标不是0，那么函数interpolate_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  MatrixTools::apply_boundary_values(boundary_values, \n                                     system_matrix, \n                                     solution, \n                                     system_rhs); \n} \n// @sect4{Step4::solve}  \n\n// 解决线性方程组是在大多数程序中看起来几乎相同的事情。特别是，它与维度无关，所以这个函数是从前面的例子中逐字复制的。\n\ntemplate <int dim> \nvoid Step4<dim>::solve() \n{ \n  SolverControl            solver_control(1000, 1e-12); \n  SolverCG<Vector<double>> solver(solver_control); \n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity()); \n\n// 不过我们做了一个补充：由于我们抑制了线性求解器的输出，我们必须手工打印迭代次数。\n\n  std::cout << \"   \" << solver_control.last_step() \n            << \" CG iterations needed to obtain convergence.\" << std::endl; \n} \n// @sect4{Step4::output_results}  \n\n// 这个函数也做了  step-3  中各自的工作。这里也没有改变维度的独立性。\n\n// 由于程序将同时运行拉普拉斯求解器的2D和3D版本，我们使用文件名中的维度为每次运行生成不同的文件名（在一个更好的程序中，我们将检查 <code>dim</code> 是否可以有2或3以外的其他值，但为了简洁起见，我们在这里忽略了这一点）。\n\ntemplate <int dim> \nvoid Step4<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, \"solution\"); \n\n  data_out.build_patches(); \n\n  std::ofstream output(dim == 2 ? \"solution-2d.vtk\" : \"solution-3d.vtk\"); \n  data_out.write_vtk(output); \n} \n\n//  @sect4{Step4::run}  \n\n// 这是一个对所有事情都有最高级别控制的函数。除了一行额外的输出外，它与前面的例子相同。\n\ntemplate <int dim> \nvoid Step4<dim>::run() \n{ \n  std::cout << \"Solving problem in \" << dim << \" space dimensions.\" \n            << std::endl; \n\n  make_grid(); \n  setup_system(); \n  assemble_system(); \n  solve(); \n  output_results(); \n} \n// @sect3{The <code>main</code> function}  \n\n// 这是主函数。它看起来也大多像 step-3 中的内容，但如果你看下面的代码，注意我们是如何首先创建一个 <code>Step4@<2@></code> 类型的变量（迫使编译器用 <code>dim</code> replaced by <code>2</code> 编译类模板）并运行一个2d模拟，然后我们用3d做整个事情。\n\n// 在实践中，这可能不是你经常做的事情（你可能要么想解决一个2D的问题，要么想解决一个3D的问题，但不会同时解决这两个问题）。然而，它展示了一种机制，我们可以在一个地方简单地改变我们想要的维度，从而迫使编译器为我们要求的维度重新编译独立的类模板。这里的重点在于，我们只需要改变一个地方。这使得在计算速度较快的2D环境下调试程序变得非常简单，然后将一个地方切换到3，在3D环境下运行计算量大得多的程序，进行 \"真实 \"的计算。\n\n// 这两个区块中的每一个都用大括号括起来，以确保 <code>laplace_problem_2d</code> 这个变量在我们继续为3D情况分配内存之前就已经超出了范围（并释放了它所持有的内存）。如果没有额外的大括号， <code>laplace_problem_2d</code> 变量只会在函数结束时被销毁，也就是在运行完3d问题后被销毁，而且会在3d运行时不必要地占用内存，而实际使用它。\n\nint main() \n{ \n  { \n    Step4<2> laplace_problem_2d; \n    laplace_problem_2d.run(); \n  } \n\n  { \n    Step4<3> laplace_problem_3d; \n    laplace_problem_3d.run(); \n  } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "a2f4e4674b5577442f2f16d565a3bb8a1a1308d2", "size": 13802, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-4/step-4.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-4/step-4.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-4/step-4.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.3219373219, "max_line_length": 457, "alphanum_fraction": 0.69489929, "num_tokens": 6843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.552195349977157}}
{"text": "\n#include <boost/math/special_functions/factorials.hpp>\n#include \"gauss_distribution.hpp\"\n\nnamespace bayesopt\n{\n\n  GaussianDistribution::GaussianDistribution(randEngine& eng): \n    ProbabilityDistribution(eng)\n  {\n    mean_ = 0.0;  std_ = 1.0;\n  }\n\n\n  GaussianDistribution::~GaussianDistribution(){}\n\n  double GaussianDistribution::negativeExpectedImprovement(double min,\n\t\t\t\t\t\t\t   size_t g)\n  {\n  \n    using boost::math::factorial;\n\n    const double diff = min - mean_;\n    const double z = diff / std_;\n    const double pdf_z = boost::math::pdf(d_,z);\n    const double cdf_z = boost::math::cdf(d_,z);\n  \n    if (g == 1)\n      return -1.0 * ( diff * cdf_z + std_ * pdf_z );\n    else\n      {\n\tconst double fg = factorial<double>(g);\n\n\tdouble Tm2 = cdf_z;\n\tdouble Tm1 = pdf_z;\n\tdouble sumEI = pow(z,static_cast<double>(g))*Tm2 - g*pow(z,static_cast<double>(g-1))*Tm1;\n\n\tfor (size_t ii = 2; ii < g; ++ii) \n\t  {\n\t    double Tact = (ii-1)*Tm2 - pdf_z*pow(z,static_cast<double>(ii-1));\n\t    sumEI += pow(-1.0,static_cast<double>(ii))* \n\t      (fg / ( factorial<double>(ii)*factorial<double>(g-ii) ) )*\n\t      pow(z,static_cast<double>(g-ii))*Tact;\n\t  \n\t    //roll-up\n\t    Tm2 = Tm1;   Tm1 = Tact;\n\t  }\n\treturn -1.0 * pow(std_,static_cast<double>(g)) * sumEI;\n      }\n  \n  }  // negativeExpectedImprovement\n\n  double GaussianDistribution::lowerConfidenceBound(double beta)\n  {    \n    return mean_ - beta*std_;\n  }  // lowerConfidenceBound\n\n\n  double GaussianDistribution::negativeProbabilityOfImprovement(double min,\n\t\t\t\t\t\t\t\tdouble epsilon)\n  {\n    return -cdf(d_,(min - mean_ + epsilon)/std_);\n  }  // negativeProbabilityOfImprovement\n\n\n  double GaussianDistribution::sample_query()\n  { \n    randNFloat sample(mtRandom,normalDist(mean_,std_));\n    return sample();\n  } // sample_query\n\n}\n", "meta": {"hexsha": "b281ed393cae4e7d5960105b85d7ffec1a64625d", "size": 1784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/src/gauss_distribution.cpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/src/gauss_distribution.cpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/src/gauss_distribution.cpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 24.4383561644, "max_line_length": 90, "alphanum_fraction": 0.6479820628, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.5521336299134181}}
{"text": "#include <iostream>\n#include <array>\n#include <vector>\n#include <fstream>\n#include <cmath>\n#include <iterator>\n\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/function_input_iterator.hpp>\n#include <boost/log/trivial.hpp>\n\n#include <range/v3/algorithm.hpp>\n\n#include \"maikel/hmm/hidden_markov_model.h\"\n#include \"maikel/hmm/algorithm.h\"\n#include \"maikel/hmm/io.h\"\n#include \"maikel/function_profiler.h\"\n\n\nenum Exit_Error_Codes {\n  exit_success = 0,\n  exit_not_enough_arguments = 1,\n  exit_io_error = 2,\n  exit_argument_error = 3\n};\n\ntemplate <class float_type, class index_type>\n  void accumulate_scaling_and_write_alpha_to_file(\n      std::vector<index_type> const& sequence,\n      maikel::hmm::hidden_markov_model<float_type> const& model)\n  {\n    std::size_t states = model.states();\n//    std::vector<Eigen::RowVectorXd> alphas(T, Eigen::RowVectorXd(states));\n    std::ofstream alphas(\"alphas.bin\", std::ofstream::binary);\n    BOOST_LOG_TRIVIAL(info) << \"Starting forward algorithm with storing scaling factors into std::vector.\";\n    BOOST_LOG_TRIVIAL(info) << \"Use accumulate on a view::transformed scaling list.\";\n    float_type logprob = 0.0;\n    std::size_t datalen = sizeof(float_type)*states;\n    { MAIKEL_PROFILER;\n      std::ostreambuf_iterator<char> out(alphas);\n      for (auto&& scaled_alpha : maikel::hmm::forward(sequence, model)) {\n        logprob += std::log(scaled_alpha.first);\n        std::copy_n(reinterpret_cast<const char*>(scaled_alpha.second.data()), datalen, out);\n      }\n    }\n    std::cout << -logprob << std::endl;\n  }\n\ntemplate <class T>\nvoid read_alphas_from_bin(const maikel::hmm::hidden_markov_model<T>& hmm)\n{\n  MAIKEL_PROFILER;\n  std::ifstream alphas(\"alphas.bin\", std::ifstream::binary);\n  Eigen::Matrix<T, 1, Eigen::Dynamic> alpha(hmm.states());\n  std::size_t data_len = sizeof(T)*alpha.size();\n  std::istreambuf_iterator<char> in(alphas), end;\n  while (in != end) {\n    std::copy_n(in, data_len, reinterpret_cast<char*>(alpha.data()));\n    std::advance(in, data_len+1);\n  }\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace std;\n  using namespace maikel::hmm;\n\n  if (argc < 3) {\n    cerr << \"Usage: \" << argv[0] << \" <model.dat> <sequence.dat>\\n\";\n    return exit_not_enough_arguments;\n  }\n  using float_type = double;\n  using index_type = uint8_t;\n\n  // read model\n  ifstream model_input(argv[1]);\n  auto model = read_hidden_markov_model<float_type>(model_input);\n\n  vector<int> symbols { 0,1 };\n  map<int,index_type> symbol_to_index = maikel::map_from_symbols<index_type>(symbols);\n  ifstream sequence_input(argv[2]);\n  vector<index_type> sequence = read_sequence(sequence_input, symbol_to_index);\n\n  {\n    MAIKEL_NAMED_PROFILER(\"v2::forward\");\n    float_type scaling = 0;\n    for (auto&& alpha : forward(begin(sequence), end(sequence), model)) {\n      scaling += log(alpha.first);\n    }\n    cout << -scaling << endl;\n  }\n  maikel::function_profiler::print_statistics(cout);\n\n  return exit_success;\n}\n", "meta": {"hexsha": "99f22f557929db5ac67961bab3371e6a7eae2ef9", "size": 2975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "forward.cpp", "max_stars_repo_name": "maikel/hidden-markov-model", "max_stars_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T07:16:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T07:16:01.000Z", "max_issues_repo_path": "forward.cpp", "max_issues_repo_name": "maikel/Hidden-Markov-Model", "max_issues_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "forward.cpp", "max_forks_repo_name": "maikel/Hidden-Markov-Model", "max_forks_repo_head_hexsha": "db97cd0344a3cb55afdd2d341fd2c5c326f6476a", "max_forks_repo_licenses": ["Apache-2.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.9895833333, "max_line_length": 107, "alphanum_fraction": 0.701512605, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5520821842461835}}
{"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: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/seven_point_fundamental_matrix.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"theia/math/polynomial.h\"\n#include \"theia/sfm/pose/util.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix;\n\nnamespace {\n\n// Sets up the constraint y^t * F * x = 0 such that M * F_v = 0 where M is a 7x9\n// matrix and F_v is the vector containing the entries of F.\nMatrix<double, 7, 9> SetupEpipolarConstraint(\n    const std::vector<Eigen::Vector2d>& image1_points,\n    const std::vector<Eigen::Vector2d>& image2_points) {\n  Matrix<double, 7, 9> epipolar_constraint;\n  for (int i = 0; i < 7; i++) {\n    // Fill matrix with the epipolar constraint from q'_t*E*q = 0. Where q is\n    // from the first image, and q' is from the second.\n    epipolar_constraint.row(i) <<\n        image2_points[i].x() * image1_points[i].x(),\n        image2_points[i].y() * image1_points[i].x(),\n        image1_points[i].x(),\n        image2_points[i].x() * image1_points[i].y(),\n        image2_points[i].y() * image1_points[i].y(),\n        image1_points[i].y(),\n        image2_points[i].x(),\n        image2_points[i].y(),\n        1.0;\n  }\n\n  return epipolar_constraint;\n}\n\n}  // namespace\n\nbool SevenPointFundamentalMatrix(\n    const std::vector<Eigen::Vector2d>& image1_points,\n    const std::vector<Eigen::Vector2d>& image2_points,\n    std::vector<Eigen::Matrix3d>* fundamental_matrices) {\n  CHECK_EQ(image1_points.size(), 7);\n  CHECK_EQ(image2_points.size(), 7);\n  CHECK_NOTNULL(fundamental_matrices)->clear();\n\n  std::vector<Eigen::Vector2d> norm_img1_points(image1_points.size());\n  std::vector<Eigen::Vector2d> norm_img2_points(image2_points.size());\n\n  // Normalize the image points.\n  Eigen::Matrix3d img1_norm_mat, img2_norm_mat;\n  NormalizeImagePoints(image1_points, &norm_img1_points, &img1_norm_mat);\n  NormalizeImagePoints(image2_points, &norm_img2_points, &img2_norm_mat);\n\n  const Matrix<double, 7, 9>& epipolar_constraint =\n      SetupEpipolarConstraint(norm_img1_points, norm_img2_points);\n\n  const Eigen::FullPivLU<Matrix<double, 7, 9> > lu(epipolar_constraint);\n  if (lu.dimensionOfKernel() != 2) {\n    return false;\n  }\n\n  // Represent F in terms of its null space such that F = x * F1' + (1 - x) * F2\n  // where F1 and F2 are vectors in the null space of F. Note that this can also\n  // be parameterized such that:\n  //   F = x * F1' + (1 - x) * F2 = x * (F1' - F2) + F2 = x * F1 + F2.\n  const Matrix<double, 9, 2>& null_space = lu.kernel();\n  const Matrix<double, 9, 1> F1_vec = null_space.col(0) - null_space.col(1);\n  const Eigen::Map<const Eigen::Matrix3d> F1(F1_vec.data());\n  const Eigen::Map<const Eigen::Matrix3d> F2(null_space.col(1).data());\n\n  // This is the cubic equation resulting from det(x * F1 + F2) = 0.\n  Eigen::VectorXd determinant_constraint(4);\n  determinant_constraint(0) =\n      -(F2(1, 2) * F2(2, 1) - F2(1, 1) * F2(2, 2)) * F2(0, 0) +\n      (F2(0, 2) * F2(2, 1) - F2(0, 1) * F2(2, 2)) * F2(1, 0) -\n      (F2(0, 2) * F2(1, 1) - F2(0, 1) * F2(1, 2)) * F2(2, 0);\n  determinant_constraint(1) =\n      -(F2(1, 2) * F2(2, 1) - F2(1, 1) * F2(2, 2)) * F1(0, 0) +\n      (F2(0, 2) * F2(2, 1) - F2(0, 1) * F2(2, 2)) * F1(1, 0) -\n      (F2(0, 2) * F2(1, 1) - F2(0, 1) * F2(1, 2)) * F1(2, 0) +\n      (F1(2, 2) * F2(1, 1) - F1(2, 1) * F2(1, 2) - F1(1, 2) * F2(2, 1) +\n       F1(1, 1) * F2(2, 2)) *\n          F2(0, 0) -\n      (F1(2, 2) * F2(0, 1) - F1(2, 1) * F2(0, 2) - F1(0, 2) * F2(2, 1) +\n       F1(0, 1) * F2(2, 2)) *\n          F2(1, 0) +\n      (F1(1, 2) * F2(0, 1) - F1(1, 1) * F2(0, 2) - F1(0, 2) * F2(1, 1) +\n       F1(0, 1) * F2(1, 2)) *\n          F2(2, 0);\n  determinant_constraint(2) =\n      (F1(2, 2) * F2(1, 1) - F1(2, 1) * F2(1, 2) - F1(1, 2) * F2(2, 1) +\n       F1(1, 1) * F2(2, 2)) *\n          F1(0, 0) -\n      (F1(2, 2) * F2(0, 1) - F1(2, 1) * F2(0, 2) - F1(0, 2) * F2(2, 1) +\n       F1(0, 1) * F2(2, 2)) *\n          F1(1, 0) +\n      (F1(1, 2) * F2(0, 1) - F1(1, 1) * F2(0, 2) - F1(0, 2) * F2(1, 1) +\n       F1(0, 1) * F2(1, 2)) *\n          F1(2, 0) -\n      (F1(1, 2) * F1(2, 1) - F1(1, 1) * F1(2, 2)) * F2(0, 0) +\n      (F1(0, 2) * F1(2, 1) - F1(0, 1) * F1(2, 2)) * F2(1, 0) -\n      (F1(0, 2) * F1(1, 1) - F1(0, 1) * F1(1, 2)) * F2(2, 0);\n  determinant_constraint(3) =\n      -(F1(1, 2) * F1(2, 1) - F1(1, 1) * F1(2, 2)) * F1(0, 0) +\n      (F1(0, 2) * F1(2, 1) - F1(0, 1) * F1(2, 2)) * F1(1, 0) -\n      (F1(0, 2) * F1(1, 1) - F1(0, 1) * F1(1, 2)) * F1(2, 0);\n\n  // Solve the cubic equation for x.\n  Eigen::VectorXd roots;\n  FindPolynomialRoots(determinant_constraint, &roots, NULL);\n\n  for (int i = 0; i < roots.size(); i++) {\n    // Compose the fundamental matrix solution from the null space and\n    // determinant constraint: F = x * F1 + F2;\n    fundamental_matrices->emplace_back(img2_norm_mat.transpose() *\n                                       (roots(i) * F1 + F2) * img1_norm_mat);\n  }\n  return fundamental_matrices->size() > 0;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "f7af7091e09aa3908e611f1d3894b0211c23a05c", "size": 6734, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/seven_point_fundamental_matrix.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/seven_point_fundamental_matrix.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/seven_point_fundamental_matrix.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.8260869565, "max_line_length": 80, "alphanum_fraction": 0.6134541135, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5520821842461835}}
{"text": "/// \\file   interval.hpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-01-31\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\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///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#ifndef ESL_MATHEMATICS_INTERVAL_HPP\n#define ESL_MATHEMATICS_INTERVAL_HPP\n\n#include <sstream>\n#include <type_traits>\n\n#include <boost/serialization/serialization.hpp>\n\n\nnamespace esl::mathematics {\n    ///\n    /// \\brief  A set of numbers lying between a lower and upper endpoint. The\n    ///         endpoints may be included in the set or not, if the lower is\n    ///         included the interval is left_closed_, and if the upper is\n    ///         included  the interval is right_closed_.\n    ///\n    /// \\tparam number_t_\n    /// \\tparam left_closed_\n    /// \\tparam right_closed_\n    template<typename number_t_,\n             bool left_closed_  = true,\n             bool right_closed_ = true>\n    struct interval\n    {\n        ///\n        /// \\brief Specifies whether the interval includes the lower value\n        ///\n        /// \\return\n        constexpr static bool left_closed()\n        {\n            return left_closed_;\n        }\n\n        ///\n        /// \\brief Specifies whether the interval includes the upper value\n        ///\n        /// \\return\n        constexpr static bool right_closed()\n        {\n            return right_closed_;\n        }\n\n        static_assert(std::is_floating_point<number_t_>::value\n                      // TODO: || esl::is_rational<number_t_>::value\n                      || std::is_integral<number_t_>::value);\n\n        number_t_ lower;\n        number_t_ upper;\n\n\n        ///\n        /// \\brief  default interval constructor sets the lower and upper bound\n        ///         to time_point(0)\n        ///\n        constexpr interval()\n        : lower(0)\n        , upper(0)\n        {\n\n        }\n\n        ///\n        /// \\brief  constructs an interval from `lower` to `upper`\n        ///\n        /// \\param lower    lower bound\n        /// \\param upper    upper bound\n        constexpr interval(number_t_ lower, number_t_ upper)\n        : lower(lower)\n        , upper(upper)\n        {\n\n        }\n\n        ///\n        /// \\return true iff the interval contains no elements\n        ///\n        [[nodiscard]] constexpr bool empty() const\n        {\n            if(lower > upper) {\n                return true;\n            }\n\n            if(lower == upper) {\n                return left_closed_ || right_closed_;\n            }\n\n            // (lower < upper) is implied\n            if(1 == upper - lower){\n               return left_closed_ && right_closed_;\n            }\n\n            return false;\n        }\n\n        ///\n        /// \\return true iff interval contains exactly one element\n        ///\n        [[nodiscard]] constexpr bool singleton() const\n        {\n            bool sufficient_ = !left_closed_ && !right_closed_ && lower == upper;\n            if(std::is_floating_point<number_t_>::value || sufficient_) {\n                // || TODO: esl::is_rational<number_t_>::value\n                return sufficient_;\n            }\n\n            // is_integral is implied from here\n            bool asymmetric_ =\n                (1 == upper - lower) && (left_closed_ != right_closed_);\n            bool symmetric_ =\n                (2 == upper - lower) && (left_closed_ && right_closed_);\n            return (upper > lower) && (asymmetric_ || symmetric_);\n        }\n\n        ///\n        /// \\return true iff the interval is singleton or empty\n        ///\n        [[nodiscard]] constexpr bool degenerate() const\n        {\n            return empty() || singleton();\n        }\n\n        ///\n        /// \\param value element to test\n        /// \\return true iff element is in contained in interval\n        ///\n        [[nodiscard]] constexpr bool contains(number_t_ value) const\n        {\n            return (lower < value || (left_closed_ && lower == value))\n                   && (upper > value || (right_closed_ && upper == value));\n        }\n\n        ///\n        /// \\brief  renders the interval to a string as detailed in the class's\n        ///         ostream operator implementation\n        ///\n        /// \\return\n        [[nodiscard]] std::string representation() const\n        {\n            std::stringstream stream_;\n            stream_ << *this;\n            return stream_.str();\n        }\n\n        ///\n        /// \\brief  renders the interval using '[' and ']' to denote open lower\n        ///         and upper bounds respectively, and '(' and ')' for closed\n        ///         lower and upper bounds.\n        ///\n        /// \\param stream\n        /// \\param self\n        /// \\return\n        friend std::ostream &\n        operator<<(std::ostream &stream,\n                   const interval<number_t_, left_closed_, right_closed_> &self)\n        {\n            stream << (left_closed_ ? '[' : '(');\n            stream << self.lower << ',' << self.upper;\n            stream << (right_closed_ ? ']' : ')');\n            return stream;\n        }\n\n        ///\n        /// \\tparam archive_t\n        /// \\param archive\n        /// \\param version\n        template<class archive_t>\n        void serialize(archive_t &archive, const unsigned int version)\n        {\n            (void)version;\n            archive &BOOST_SERIALIZATION_NVP(lower);\n            archive &BOOST_SERIALIZATION_NVP(upper);\n        }\n    };\n}  // namespace esl\n\n#endif  // ESL_MATHEMATICS_INTERVAL_HPP\n", "meta": {"hexsha": "3a8c2b5a38fb69466695fddc219bb609d44dbfa6", "size": 6256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "esl/mathematics/interval.hpp", "max_stars_repo_name": "fagan2888/ESL", "max_stars_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T18:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T18:18:08.000Z", "max_issues_repo_path": "esl/mathematics/interval.hpp", "max_issues_repo_name": "fagan2888/ESL", "max_issues_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/mathematics/interval.hpp", "max_forks_repo_name": "fagan2888/ESL", "max_forks_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_forks_repo_licenses": ["Apache-2.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.1243781095, "max_line_length": 81, "alphanum_fraction": 0.5298913043, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.6791787121629465, "lm_q1q2_score": 0.5520821842461834}}
{"text": "/* Copyright 2018 Ignacio Torroba (ignaciotb@kth.se)\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef UTILS_MATRICES_HPP\n#define UTILS_MATRICES_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/operation_blocked.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <boost/scoped_ptr.hpp>\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/inverse_chi_squared.hpp>\n\nnamespace matrices{\n\n    template<typename T>\n    T matDeterminant(const boost::numeric::ublas::matrix<T>& mat_A){\n        using namespace boost::numeric::ublas;\n        matrix<T> mLu(mat_A);\n        permutation_matrix<std::size_t> pivots(mat_A.size1());\n\n        auto isSingular = lu_factorize(mLu, pivots);\n        if (isSingular){\n            return static_cast<T>(0);\n        }\n\n        T det = static_cast<T>(1);\n        for (std::size_t i = 0; i < pivots.size(); ++i){\n            if (pivots(i) != i){\n                det *= static_cast<T>(-1);\n            }\n            det *= mLu(i, i);\n        }\n        return det;\n    }\n\n    template<typename T>\n    bool InvertMatrix (const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse) {\n        using namespace boost::numeric::ublas;\n        matrix<T> A(input);\n        // Perform LU-factorization\n        permutation_matrix<std::size_t> pm(A.size1());\n        int res = lu_factorize(A,pm);\n        if( res != 0 )\n            return false;\n        inverse.assign(identity_matrix<T>(A.size1()));\n        lu_substitute(A, pm, inverse);\n        return true;\n    }\n\n    template<typename T>\n    boost::numeric::ublas::matrix<T> Cholesky(const boost::numeric::ublas::matrix<T>& mat_A){\n        // TODO_NACHO: check for matrix conditions to use cholesky\n        int n = mat_A.size1();\n        boost::numeric::ublas::matrix<T> chol_triang(n, n);\n        for(unsigned int i=0; i< mat_A.size1(); i++){\n            for(unsigned int j=0; j< i + 1; j++){\n                double s = 0;\n                for(unsigned int k = 0; k<j; k++){\n                    s += chol_triang(i * n + k) * chol_triang(j * n + k);\n                }\n                chol_triang(i * n + j) = (i = j)?\n                            std::sqrt(mat_A(i * n + i) - s):\n                            (1.0 / chol_triang(j * n + j) * (mat_A(i * n + j) - s));\n            }\n        }\n        return chol_triang;\n    }\n\n    template<typename T>\n    boost::numeric::ublas::matrix<T> matTriangDeterminant(const boost::numeric::ublas::matrix<T>& mat_A){\n        int n = mat_A.size1();\n        T det;\n        for(unsigned int i=0; i< mat_A.size1(); i++){\n            for(unsigned int j=0; j< mat_A.size2(); j++){\n                det *= (i == j)? mat_A(i,j): 1;\n            }\n        }\n        return det;\n    }\n}\n\n#endif // UTILS_MATRICES_HPP\n", "meta": {"hexsha": "40c565ea48eb323ab3ce44a7ccf9dee9854f72f3", "size": 4499, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "auv_ekf_localization/include/utils_matrices/utils_matrices.hpp", "max_stars_repo_name": "nilsbore/smarc_navigation", "max_stars_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2020-01-24T10:24:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T10:22:41.000Z", "max_issues_repo_path": "auv_ekf_localization/include/utils_matrices/utils_matrices.hpp", "max_issues_repo_name": "nilsbore/smarc_navigation", "max_issues_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 20.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T09:46:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-07T09:40:26.000Z", "max_forks_repo_path": "auv_ekf_localization/include/utils_matrices/utils_matrices.hpp", "max_forks_repo_name": "nilsbore/smarc_navigation", "max_forks_repo_head_hexsha": "97d0a30498e72506e7472c98c5fa0d86d19f0f04", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-01-25T14:42:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T15:18:28.000Z", "avg_line_length": 44.1078431373, "max_line_length": 758, "alphanum_fraction": 0.6465881307, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.5520821780882718}}
{"text": "/*\n * resampling.hpp\n *\n *  Created on: Mar 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\nnamespace math {\n\n/**\n * Different strategies for upsampling a discrete field\n */\nenum class UpsamplingStrategy {\n\tNEAREST = 0, ///@see upsampleX2_nearest for details\n\tLINEAR = 1 ///@see upsampleX2_linear for details\n};\n\n/**\n * Different strategies for downsampling a discrete field\n */\nenum class DownsamplingStrategy {\n\tAVERAGE = 0, ///@see downsampleX2_average for details\n\tLINEAR = 1 ///@see downsampleX2_linear for details\n};\n\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension.\n * @param field input field\n * @param upsampling_strategy -- which upsampling strategy to use.\n * @return upsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> upsampleX2(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field,\n\t\tUpsamplingStrategy upsampling_strategy = UpsamplingStrategy::NEAREST);\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension.\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> upsampleX2(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field,\n\t\tUpsamplingStrategy upsampling_strategy = UpsamplingStrategy::NEAREST);\n\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension.\n * This procedure uses a simple box filter / no interpolation, i.e. simply copies the value to it's immediate \"children\"\n * in the upsampled version.\n * Conceptual example:\n * ⎡1  2⎤\n * ⎣3  4⎦\n * yields\n * ⎡1  1  2  2⎤\n * ⎢1  1  2  2⎥\n * ⎢3  3  4  4⎥\n * ⎣3  3  4  4⎦\n * @param field input field\n * @return upsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> upsampleX2_nearest(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension using the\n * nearest-neighbor (NEAREST) strategy.\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> upsampleX2_nearest(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& field);\n\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension.\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> upsampleX2_nearest(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension using bilinear\n * filtering. This procedure uses a simple tent filter in each dimension to compute the values, i.e. bilinear filtering.\n * Conceptual example:\n * The influence coefficients for the voxels in the output field (o) fall off linearly from 1.0 at the\n * current input voxel (X) to 0.0 at it's neighbors (O).\n *    o     o    o     o    o     o\n *       O┈┈┈┈┈┈┈┈┈┈O┈┈┈┈┈┈┈┈┈┈O\n *    o  ┊  o    o     o    o  ┊  o\n *       ┊                     ┊\n *    o  ┊  o    o     o    o  ┊  o\n *       O          X          O\n *    o  ┊  o    o     o    o  ┊  o\n *       ┊                     ┊\n *    o  ┊  o    o     o    o  ┊  o\n *       O┈┈┈┈┈┈┈┈┈┈O┈┈┈┈┈┈┈┈┈┈O\n *    o     o    o     o    o     o\n *  Boundary voxels are processed as if the boundary values of the input repeat infinitely.\n *\n * @param field input field\n * @return upsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> upsampleX2_linear(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n/**\n * Upsample the field such that the output is a field 2X larger than the original in each dimension using bilinear\n * interpolation (LINEAR) strategy.\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> upsampleX2_linear(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field.\n * @param field input field\n * @param downsampling_strategy strategy to use for downsampling\n * @return downsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> downsampleX2(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field,\n\t\tDownsamplingStrategy downsampling_strategy = DownsamplingStrategy::AVERAGE);\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field.\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> downsampleX2(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field,\n\t\tDownsamplingStrategy downsampling_strategy = DownsamplingStrategy::AVERAGE);\n\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field. Uses a simple box filter, i.e. each \"downsampled\" value will be the\n * average of it's source values in the input.\n *\n * Conceptual example (for 2d case):\n * ⎡1  2  4  5⎤\n * ⎢2  3  5  6⎥\n * ⎢1  3  6  7⎥\n * ⎣3  5  7  8⎦\n * yields\n * ⎡2  5⎤\n * ⎣3  7⎦\n *\n * @param field input field\n * @return downsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> downsampleX2_average(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field using simple averaging (AVERAGE strategy).\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> downsampleX2_average(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field. Uses a tent filter, i.e. each \"downsampled\" value will be influenced by\n * values of the input weighted by the inverse ratio of their distance to the neighbor values.\n *\n * Conceptual example:\n * The influence coefficients for the source voxels in the input field (x) fall off linearly from 1.0 at the current\n * target voxel (X) to 0.0 at it's neighbors (O).\n *    o     o    o     o    o     o\n *       O┈┈┈┈┈┈┈┈┈┈O┈┈┈┈┈┈┈┈┈┈O\n *    o  ┊  o    o     o    o  ┊  o\n *       ┊                     ┊\n *    o  ┊  o    o     o    o  ┊  o\n *       O          X          O\n *    o  ┊  o    o     o    o  ┊  o\n *       ┊                     ┊\n *    o  ┊  o    o     o    o  ┊  o\n *       O┈┈┈┈┈┈┈┈┈┈O┈┈┈┈┈┈┈┈┈┈O\n *    o     o    o     o    o     o\n *  Boundary voxels are processed as if the boundary values of the input repeat infinitely.\n *\n * @param field input field\n * @return downsampled field\n */\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> downsampleX2_linear(\n\t\tconst Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>& field);\n/**\n * Downsample the provided matrix using a box filter such that each dimension of the downsampled field is half the\n * corresponding dimension of the input field using bilinear interpolation (LINEAR strategy).\n * @overload\n */\ntemplate<typename Scalar>\nEigen::Tensor<Scalar, 3, Eigen::ColMajor> downsampleX2_linear(\n\t\tconst Eigen::Tensor<Scalar, 3, Eigen::ColMajor>& field);\n\n} // namespace math\n", "meta": {"hexsha": "d8b318aa18721510e9b49f127e57db392dc731ef", "size": 8523, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/resampling.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/resampling.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/resampling.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": 38.5656108597, "max_line_length": 120, "alphanum_fraction": 0.6855567289, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042768, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5520821736890256}}
{"text": "#include <chrono>\n#include <iostream>\n#include <limits>\n#include <Eigen/Dense>\n#include \"dopri.h\"\n#include \"kepler.h\"\n#include \"elements.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::Vector3d;\nusing std::pow;\nusing std::sqrt;\n\nnamespace dopri {\n    void gravity(int *n, double *x, double *y, double *f, double *rpar, int *ipar) {\n        auto r = sqrt(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);\n        auto r3 = r*r*r;\n        f[0] = y[3];\n        f[1] = y[4];\n        f[2] = y[5];\n        f[3] = -rpar[0] * y[0] / r3;\n        f[4] = -rpar[0] * y[1] / r3;\n        f[5] = -rpar[0] * y[2] / r3;\n    }\n\n    void solout_dummy(int *nr, double *xold, double *x, double *y, int *n, double *con,\n                      int *icomp, int *nd, double *rpar, int *ipar, int *irtrn, double *xout){};\n\n    void integrate(void (*func)(int *, double *, double *, double *, double *, int *),\n            double *x, VectorXd *rv, double xend, double rpar[], int ipar[],\n            double reltol = 1e-6, double abstol = 1e-8) {\n        int n = rv->size();\n        double rtol[] = {reltol};\n        double atol[] = {abstol};\n        int itol = 0;\n        int iout = 0;\n        int lwork = 11*n+8*n+21;\n        int liwork = n + 21;\n        double work[lwork];\n        memset(work, 0, sizeof(work));\n        int iwork[liwork];\n        memset(iwork, 0, sizeof(iwork));\n        int idid = 0;\n        c_dop853(&n, func, x, rv->data(), &xend, rtol, atol, &itol, &solout_dummy,\n            &iout, work, &lwork, iwork, &liwork, rpar, ipar, &idid);\n    }\n\n    void benchmark(int times) {\n        auto mu = 3.986004418e5;\n        Vector3d r(8.59072560e+02, -4.13720368e+03, 5.29556871e+03);\n        Vector3d v(7.37289205e+00, 2.08223573e+00, 4.39999794e-01);\n        VectorXd rv(r.size()+v.size());\n        rv << r, v;\n        VectorXd rv0(rv);\n        auto el = elements::elements(r, v, mu);\n        auto x = 0.0;\n        double rpar[] = {mu};\n        int ipar[] = {0};\n        auto xend = kepler::period(el[0], mu);\n        auto best = std::numeric_limits<double>::infinity();\n        auto worst = -std::numeric_limits<double>::infinity();\n        double all = 0;\n        for (auto i=0; i < times; i++) {\n            auto begin = std::chrono::high_resolution_clock::now();\n            integrate(&gravity, &x, &rv0, xend, rpar, ipar);\n            auto end = std::chrono::high_resolution_clock::now();\n            auto current = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count()/1e9;\n            all += current;\n            if (current < best) {\n                best = current;\n            }\n            if (current > worst) {\n                worst = current;\n            }\n            rv0 = rv;\n            x = 0;\n        }\n        std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n    }\n}\n", "meta": {"hexsha": "7c7ff8374daaa287de8971e0b8e2fba14b98a8c4", "size": 2808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/cppdopri.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/cppdopri.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/cppdopri.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 34.6666666667, "max_line_length": 103, "alphanum_fraction": 0.5032051282, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.5520821736890256}}
{"text": "#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <boost/mpl/string.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/size_t.hpp>\n\nusing namespace std;\nusing namespace boost;\n\n///////////////////////////////////////////////////////////////////////////////\n// exponentiation calculations\ntemplate <int accum, int base, int exp> struct POWER_CORE : POWER_CORE<accum * base, base, exp - 1>{};\n\ntemplate <int accum, int base>\nstruct POWER_CORE<accum, base, 0>\n{\n    enum : int { val = accum };\n};\n\ntemplate <int base, int exp> struct POWER : POWER_CORE<1, base, exp>{};\n\n///////////////////////////////////////////////////////////////////////////////\n// # of digit calculations\ntemplate <int depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_CORE<depth + 1, i / 10>{};\n\ntemplate <int depth>\nstruct NUM_DIGITS_CORE<depth, 0>\n{\n    enum : int { val = depth};\n};\n\ntemplate <int i> struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{};\n\ntemplate <>\nstruct NUM_DIGITS<0>\n{\n    enum : int { val = 1 };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Convert digit to character (1 -> '1')\ntemplate <int i>\nstruct DIGIT_TO_CHAR\n{\n    enum : char{ val = i + 48 };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Find the digit at a given offset into a number of the form 0000000017\ntemplate <unsigned int i, int place> // place -> [0 .. 10]\nstruct DIGIT_AT\n{\n    enum : char{ val = (i / POWER<10, place>::val) % 10 };\n};\n\nstruct NULL_CHAR\n{\n    enum : char{ val = '\\0' };\n};\n\n///////////////////////////////////////////////////////////////////////////////\n// Convert the digit at a given offset into a number of the form '0000000017' to a character\ntemplate <unsigned int i, int place> // place -> [0 .. 9]\n    struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT<i, place>::val >{};\n\n///////////////////////////////////////////////////////////////////////////////\n// Convert the digit at a given offset into a number of the form '17' to a character\n\n// Template description, with specialization to generate null characters for out of range offsets\ntemplate <unsigned int i, int offset, int numDigits, bool inRange>\n    struct OFFSET_CHAR_CORE_CHECKED{};\ntemplate <unsigned int i, int offset, int numDigits>\n    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, false> : NULL_CHAR{};\ntemplate <unsigned int i, int offset, int numDigits>\n    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, true>  : ALT_CHAR<i, (numDigits - offset) - 1 >{};\n\n// Perform the range check and pass it on\ntemplate <unsigned int i, int offset, int numDigits>\n    struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, offset < numDigits>{};\n\n// Calc the number of digits and pass it on\ntemplate <unsigned int i, int offset>\n    struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS<i>::val>{};\n\n///////////////////////////////////////////////////////////////////////////////\n// Integer to char* template. Works on unsigned ints.\ntemplate <unsigned int i>\nstruct IntToStr\n{\n    const static char str[];\n    typedef typename mpl::string<\n    OFFSET_CHAR<i, 0>::val,\n    OFFSET_CHAR<i, 1>::val,\n    OFFSET_CHAR<i, 2>::val,\n    OFFSET_CHAR<i, 3>::val,\n    OFFSET_CHAR<i, 4>::val,\n    OFFSET_CHAR<i, 5>::val,\n    /*OFFSET_CHAR<i, 6>::val,\n    OFFSET_CHAR<i, 7>::val,\n    OFFSET_CHAR<i, 8>::val,\n    OFFSET_CHAR<i, 9>::val,*/\n    NULL_CHAR::val>::type type;\n};\n\ntemplate <unsigned int i>\nconst char IntToStr<i>::str[] =\n{\n    OFFSET_CHAR<i, 0>::val,\n    OFFSET_CHAR<i, 1>::val,\n    OFFSET_CHAR<i, 2>::val,\n    OFFSET_CHAR<i, 3>::val,\n    OFFSET_CHAR<i, 4>::val,\n    OFFSET_CHAR<i, 5>::val,\n    OFFSET_CHAR<i, 6>::val,\n    OFFSET_CHAR<i, 7>::val,\n    OFFSET_CHAR<i, 8>::val,\n    OFFSET_CHAR<i, 9>::val,\n    NULL_CHAR::val\n};\n\ntemplate <bool condition, class Then, class Else>\nstruct IF\n{\n    typedef Then RET;\n};\n\ntemplate <class Then, class Else>\nstruct IF<false, Then, Else>\n{\n    typedef Else RET;\n};\n\n\ntemplate < typename Str1, typename Str2 >\nstruct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};\ntemplate <typename Str1, typename Str2, typename Str3 >\nstruct concat3 : mpl::insert_range<Str1, typename mpl::end<Str1>::type, typename concat<Str2, Str3 >::type > {};\n\ntypedef typename mpl::string<'f','i','z','z'>::type fizz;\ntypedef typename mpl::string<'b','u','z','z'>::type buzz;\ntypedef typename mpl::string<'\\r', '\\n'>::type mpendl;\ntypedef typename concat<fizz, buzz>::type fizzbuzz;\n\n// discovered boost mpl limitation on some length\n\ntemplate <int N>\nstruct FizzBuzz\n{\n    typedef typename concat3<typename FizzBuzz<N - 1>::type, typename IF<N % 15 == 0, typename fizzbuzz::type, typename IF<N % 3 == 0, typename fizz::type, typename IF<N % 5 == 0, typename buzz::type, typename IntToStr<N>::type >::RET >::RET >::RET, typename mpendl::type>::type type;\n};\n\ntemplate <>\nstruct FizzBuzz<1>\n{\n    typedef mpl::string<'1','\\r','\\n'>::type type;\n};\n\nint main(int argc, char** argv)\n{\n    const int n = 7;\n    std::cout << mpl::c_str<FizzBuzz<n>::type>::value << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "d00cefbbe21fbe65ef79a119d07581faa98ff4a0", "size": 5101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/fizzbuzz-6.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/fizzbuzz-6.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++/fizzbuzz-6.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 30.9151515152, "max_line_length": 284, "alphanum_fraction": 0.599882376, "num_tokens": 1302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.5520821622525347}}
{"text": "/**\n * @file    MatrixPseudoInverse.cpp\n * @brief   Functions for matrix pseudo inverse, and matrix square root.\n * @author  Jianzhu Huai\n */\n\n#ifndef INCLUDE_OKVIS_MATRIX_PSEUDO_INVERSE_HPP\n#define INCLUDE_OKVIS_MATRIX_PSEUDO_INVERSE_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include <okvis/assert_macros.hpp>\n\nnamespace okvis {\n\n/**\n * \\brief Compute the square root of a matrix using the LDLt decomposition for\n * square, positive semidefinite matrices\n *\n * To reconstruct the input matrix, \\f$ \\mathbf A \\f$, from the returned matrix,\n * \\f$ \\mathbf S \\f$, use, \\f$ \\mathbf A = \\mathbf S \\mathbf S^T \\f$.\n *\n *\n * @param inMatrix      The square matrix whose square root should be computed.\n * @param outMatrixSqrt The output square root.\n */\ntemplate <typename DERIVED1, typename DERIVED2>\n/*Eigen::ComputationInfo*/ void\ncomputeMatrixSqrt(const Eigen::MatrixBase<DERIVED1> &inMatrix,\n                  const Eigen::MatrixBase<DERIVED2> &outMatrixSqrt) {\n  OKVIS_ASSERT_EQ_DBG(std::runtime_error, inMatrix.rows(), inMatrix.cols(),\n                      \"This method is only valid for square input matrices\");\n\n  DERIVED2 &result = const_cast<DERIVED2 &>(outMatrixSqrt.derived());\n\n  // This is tricky. Using the output matrix type causes the input matrix\n  // type to be upgraded to a real numeric matrix. This is useful if,\n  // for example, the inMatrix is something like Eigen::Matrix3d::Identity(),\n  // which is not an actual matrix. Using DERIVED1 as the template argument\n  // in that case will cause a firestorm of compiler errors.\n  Eigen::LDLT<DERIVED2> ldlt(inMatrix.derived());\n  result = ldlt.matrixL();\n  result = ldlt.transpositionsP().transpose() * result;\n  result *= ldlt.vectorD().array().sqrt().matrix().asDiagonal();\n\n  // return ldlt.info();\n}\n\nclass MatrixPseudoInverse\n{\npublic:\n  OKVIS_DEFINE_EXCEPTION(Exception,std::runtime_error)\n  /**\n   * @brief Pseudo inversion of a symmetric matrix.\n   * @warning   This uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n   *            (negative Eigenvalues are set to zero).\n   * @tparam Derived Matrix type (auto-deducible).\n   * @param[in] a Input Matrix\n   * @param[out] result Output, i.e. pseudo-inverse.\n   * @param[in] epsilon The tolerance.\n   * @param[out] rank Optional rank.\n   * @return\n   */\n  template<typename Derived>\n  static bool pseudoInverseSymm(\n      const Eigen::MatrixBase<Derived>&a,\n      const Eigen::MatrixBase<Derived>&result, double epsilon =\n          std::numeric_limits<typename Derived::Scalar>::epsilon(), int * rank = 0);\n\n  /**\n   * @brief Pseudo inversion and square root (Cholesky decomposition) of a symmetric matrix.\n   * @warning   This uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n   *            (negative Eigenvalues are set to zero). Also if the input is positive semi-definite,\n   *            its zero eigenvalues are at the lower part of the diagonal.\n   * @tparam Derived Matrix type (auto-deducible).\n   * @param[in] a Input Matrix, \\f$A\\f$.\n   * @param[out] result Output, \\f$L\\f$, i.e. the Cholesky decomposition of a pseudo-inverse, \\f$A^{-1} = L L^*\\f$.\n   * @param[in] epsilon The tolerance.\n   * @param[out] rank The rank, if of interest.\n   * @return\n   */\n  template<typename Derived>\n  static bool pseudoInverseSymmSqrt(\n      const Eigen::MatrixBase<Derived>&a,\n      const Eigen::MatrixBase<Derived>&result, double epsilon =\n          std::numeric_limits<typename Derived::Scalar>::epsilon(),\n      int* rank = NULL);\n\n  /**\n   * @brief Pseudo square root (Cholesky decomposition) of a symmetric matrix.\n   * @warning   This uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n   *            (negative Eigenvalues are set to zero). Also if the input is positive semi-definite,\n   *            its zero eigenvalues are at the lower part of the diagonal.\n   * @tparam Derived Matrix type (auto-deducible).\n   * @param[in] a Input Matrix, \\f$A\\f$.\n   * @param[out] result Output, \\f$L\\f$, i.e. the Cholesky decomposition of a pseudo-inverse, \\f$A = L L^*\\f$.\n   * @param[in] epsilon The tolerance.\n   * @param[out] rank The rank, if of interest.\n   * @return\n   */\n  template<typename Derived>\n  static bool pseudoSymmSqrt(\n      const Eigen::MatrixBase<Derived>&a,\n      const Eigen::MatrixBase<Derived>&result, double epsilon =\n          std::numeric_limits<typename Derived::Scalar>::epsilon(),\n      int* rank = NULL);\n\n  /**\n   * @brief Block-wise pseudo inversion of a symmetric matrix with non-zero diagonal blocks.\n   * @warning   This uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n   *            (negative Eigenvalues are set to zero).\n   * @tparam Derived Matrix type (auto-deducible).\n   * @tparam blockDim The block size of the diagonal blocks.\n   * @param[in] M_in Input Matrix\n   * @param[out] M_out Output, i.e. thepseudo-inverse.\n   * @param[in] epsilon The tolerance.\n   * @return\n   */\n  template<typename Derived, int blockDim>\n  static void blockPinverse(\n      const Eigen::MatrixBase<Derived>& M_in,\n      const Eigen::MatrixBase<Derived>& M_out, double epsilon =\n          std::numeric_limits<typename Derived::Scalar>::epsilon());\n\n\n  /**\n   * @brief Block-wise pseudo inversion and square root (Cholesky decomposition)\n   *        of a symmetric matrix with non-zero diagonal blocks.\n   * @warning   This uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n   *            (negative Eigenvalues are set to zero).\n   * @tparam Derived Matrix type (auto-deducible).\n   * @tparam blockDim The block size of the diagonal blocks.\n   * @param[in] M_in Input Matrix\n   * @param[out] M_out Output, i.e. the Cholesky decomposition of a pseudo-inverse.\n   * @param[in] epsilon The tolerance.\n   * @return\n   */\n  template<typename Derived, int blockDim>\n  static void blockPinverseSqrt(\n      const Eigen::MatrixBase<Derived>& M_in,\n      const Eigen::MatrixBase<Derived>& M_out, double epsilon =\n          std::numeric_limits<typename Derived::Scalar>::epsilon());\n\n};\n\n// Pseudo inversion of a symmetric matrix.\n// attention: this uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n// (negative Eigenvalues are set to zero)\ntemplate<typename Derived>\nbool MatrixPseudoInverse::pseudoInverseSymm(\n    const Eigen::MatrixBase<Derived>&a, const Eigen::MatrixBase<Derived>&result,\n    double epsilon, int * rank) {\n\n  OKVIS_ASSERT_TRUE_DBG(Exception, a.rows() == a.cols(),\n                        \"matrix supplied is not quadratic\");\n\n  Eigen::SelfAdjointEigenSolver<Derived> saes(a);\n\n  typename Derived::Scalar tolerance = epsilon * a.cols()\n      * saes.eigenvalues().array().maxCoeff();\n\n  const_cast<Eigen::MatrixBase<Derived>&>(result) = (saes.eigenvectors())\n      * Eigen::VectorXd(\n          (saes.eigenvalues().array() > tolerance).select(\n              saes.eigenvalues().array().inverse(), 0)).asDiagonal()\n      * (saes.eigenvectors().transpose());\n\n  if (rank) {\n    *rank = 0;\n    for (int i = 0; i < a.rows(); ++i) {\n      if (saes.eigenvalues()[i] > tolerance)\n        (*rank)++;\n    }\n  }\n\n  return true;\n}\n\n// Pseudo inversion and square root (Cholesky decomposition) of a symmetric matrix.\n// attention: this uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n// (negative Eigenvalues are set to zero)\ntemplate<typename Derived>\nbool MatrixPseudoInverse::pseudoInverseSymmSqrt(\n    const Eigen::MatrixBase<Derived>&a, const Eigen::MatrixBase<Derived>&result,\n    double epsilon, int * rank) {\n\n  OKVIS_ASSERT_TRUE_DBG(Exception, a.rows() == a.cols(),\n                        \"matrix supplied is not quadratic\");\n\n  Eigen::SelfAdjointEigenSolver<Derived> saes(a);\n\n  typename Derived::Scalar tolerance = epsilon * a.cols()\n      * saes.eigenvalues().array().maxCoeff();\n\n  const_cast<Eigen::MatrixBase<Derived>&>(result) = (saes.eigenvectors())\n      * Eigen::VectorXd(\n          Eigen::VectorXd(\n              (saes.eigenvalues().array() > tolerance).select(\n                  saes.eigenvalues().array().inverse(), 0)).array().sqrt())\n          .asDiagonal();\n\n  if (rank) {\n    *rank = 0;\n    for (int i = 0; i < a.rows(); ++i) {\n      if (saes.eigenvalues()[i] > tolerance)\n        (*rank)++;\n    }\n  }\n\n  return true;\n}\n\ntemplate <typename Derived>\nbool MatrixPseudoInverse::pseudoSymmSqrt(\n    const Eigen::MatrixBase<Derived> &a,\n    const Eigen::MatrixBase<Derived> &result, double epsilon, int *rank) {\n\n  OKVIS_ASSERT_TRUE_DBG(Exception, a.rows() == a.cols(),\n                        \"matrix supplied is not quadratic\");\n\n  Eigen::SelfAdjointEigenSolver<Derived> saes(a);\n\n  typename Derived::Scalar tolerance =\n      epsilon * a.cols() * saes.eigenvalues().array().maxCoeff();\n\n  const_cast<Eigen::MatrixBase<Derived> &>(result) =\n      (saes.eigenvectors()) *\n      Eigen::VectorXd(\n          Eigen::VectorXd((saes.eigenvalues().array() > tolerance)\n                              .select(saes.eigenvalues().array(), 0))\n              .array()\n              .sqrt())\n          .asDiagonal();\n\n  if (rank) {\n    *rank = 0;\n    for (int i = 0; i < a.rows(); ++i) {\n      if (saes.eigenvalues()[i] > tolerance)\n        (*rank)++;\n    }\n  }\n\n  return true;\n}\n\n// Block-wise pseudo inversion of a symmetric matrix with non-zero diagonal blocks.\n// attention: this uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n// (negative Eigenvalues are set to zero)\ntemplate<typename Derived, int blockDim>\nvoid MatrixPseudoInverse::blockPinverse(\n    const Eigen::MatrixBase<Derived>& M_in,\n    const Eigen::MatrixBase<Derived>& M_out, double epsilon) {\n\n  OKVIS_ASSERT_TRUE_DBG(Exception, M_in.rows() == M_in.cols(),\n                        \"matrix supplied is not quadratic\");\n\n  const_cast<Eigen::MatrixBase<Derived>&>(M_out).resize(M_in.rows(),\n                                                        M_in.rows());\n  const_cast<Eigen::MatrixBase<Derived>&>(M_out).setZero();\n  for (int i = 0; i < M_in.cols(); i += blockDim) {\n    Eigen::Matrix<double, blockDim, blockDim> inv;\n    const Eigen::Matrix<double, blockDim, blockDim> in = M_in\n        .template block<blockDim, blockDim>(i, i);\n    //const Eigen::Matrix<double,blockDim,blockDim> in1=0.5*(in+in.transpose());\n    pseudoInverseSymm(in, inv, epsilon);\n    const_cast<Eigen::MatrixBase<Derived>&>(M_out)\n        .template block<blockDim, blockDim>(i, i) = inv;\n  }\n}\n\n// Block-wise pseudo inversion and square root (Cholesky decomposition)\n// of a symmetric matrix with non-zero diagonal blocks.\n// attention: this uses Eigen-decomposition, it assumes the input is symmetric positive semi-definite\n// (negative Eigenvalues are set to zero)\ntemplate<typename Derived, int blockDim>\nvoid MatrixPseudoInverse::blockPinverseSqrt(\n    const Eigen::MatrixBase<Derived>& M_in,\n    const Eigen::MatrixBase<Derived>& M_out, double epsilon) {\n\n  OKVIS_ASSERT_TRUE_DBG(Exception, M_in.rows() == M_in.cols(),\n                        \"matrix supplied is not quadratic\");\n\n  const_cast<Eigen::MatrixBase<Derived>&>(M_out).resize(M_in.rows(),\n                                                        M_in.rows());\n  const_cast<Eigen::MatrixBase<Derived>&>(M_out).setZero();\n  for (int i = 0; i < M_in.cols(); i += blockDim) {\n    Eigen::Matrix<double, blockDim, blockDim> inv;\n    const Eigen::Matrix<double, blockDim, blockDim> in = M_in\n        .template block<blockDim, blockDim>(i, i);\n    //const Eigen::Matrix<double,blockDim,blockDim> in1=0.5*(in+in.transpose());\n    pseudoInverseSymmSqrt(in, inv, epsilon);\n    const_cast<Eigen::MatrixBase<Derived>&>(M_out)\n        .template block<blockDim, blockDim>(i, i) = inv;\n  }\n}\n\n} // namespace okvis\n#endif // INCLUDE_OKVIS_MATRIX_PSEUDO_INVERSE_HPP\n", "meta": {"hexsha": "3998a5582bf2efef1efb631a1e02fd7e7f7815ab", "size": 11796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "okvis_kinematics/include/okvis/kinematics/MatrixPseudoInverse.hpp", "max_stars_repo_name": "wbl1997/okvis", "max_stars_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T15:31:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T15:31:53.000Z", "max_issues_repo_path": "okvis_kinematics/include/okvis/kinematics/MatrixPseudoInverse.hpp", "max_issues_repo_name": "wbl1997/okvis", "max_issues_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "okvis_kinematics/include/okvis/kinematics/MatrixPseudoInverse.hpp", "max_forks_repo_name": "wbl1997/okvis", "max_forks_repo_head_hexsha": "65e30d6ab25380d65c96c665485148e2ab55e93e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T16:49:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T09:00:03.000Z", "avg_line_length": 39.32, "max_line_length": 115, "alphanum_fraction": 0.6695489997, "num_tokens": 2943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.5519686961669507}}
{"text": "#include <iostream>\n//#include <boost/multiprecision/cpp_int.hpp>\n// using namespace boost::multiprecision;\nconst int mx = 1e6 + 5;\nconst long int inf = 2e9;\ntypedef long long ll;\n#define rep(i, n) for (i = 0; i < n; i++)\n#define repp(i, a, b) for (i = a; i <= b; i++)\n#define pii pair<int, int>\n#define vpii vector<pii>\n#define vi vector<int>\n#define vll vector<ll>\n#define r(x) scanf(\"%d\", &x)\n#define rs(s) scanf(\"%s\", s)\n#define gc getchar_unlocked\n#define pc putchar_unlocked\n#define mp make_pair\n#define pb push_back\n#define lb lower_bound\n#define ub upper_bound\n#define endl \"\\n\"\n#define fast                          \\\n    ios_base::sync_with_stdio(false); \\\n    cin.tie(NULL);                    \\\n    cout.tie(NULL);\nusing namespace std;\nvoid in(int &x) {\n    register int c = gc();\n    x = 0;\n    int neg = 0;\n    for (; ((c < 48 || c > 57) && c != '-'); c = gc())\n        ;\n    if (c == '-') {\n        neg = 1;\n        c = gc();\n    }\n    for (; c > 47 && c < 58; c = gc()) {\n        x = (x << 1) + (x << 3) + c - 48;\n    }\n    if (neg)\n        x = -x;\n}\nvoid out(int n) {\n    int N = n, rev, count = 0;\n    rev = N;\n    if (N == 0) {\n        pc('0');\n        return;\n    }\n    while ((rev % 10) == 0) {\n        count++;\n        rev /= 10;\n    }\n    rev = 0;\n    while (N != 0) {\n        rev = (rev << 3) + (rev << 1) + N % 10;\n        N /= 10;\n    }\n    while (rev != 0) {\n        pc(rev % 10 + '0');\n        rev /= 10;\n    }\n    while (count--) pc('0');\n}\nll parent[mx], arr[mx], node, edge;\nvector<pair<ll, pair<ll, ll>>> v;\nvoid initial() {\n    int i;\n    rep(i, node + edge) parent[i] = i;\n}\nint root(int i) {\n    while (parent[i] != i) {\n        parent[i] = parent[parent[i]];\n        i = parent[i];\n    }\n    return i;\n}\nvoid join(int x, int y) {\n    int root_x = root(x);  // Disjoint set union by rank\n    int root_y = root(y);\n    parent[root_x] = root_y;\n}\nll kruskal() {\n    ll mincost = 0, i, x, y;\n    rep(i, edge) {\n        x = v[i].second.first;\n        y = v[i].second.second;\n        if (root(x) != root(y)) {\n            mincost += v[i].first;\n            join(x, y);\n        }\n    }\n    return mincost;\n}\nint main() {\n    fast;\n    while (1) {\n        int i, j, from, to, cost, totalcost = 0;\n        cin >> node >> edge;  // Enter the nodes and edges\n        if (node == 0 && edge == 0)\n            break;  // Enter 0 0 to break out\n        initial();  // Initialise the parent array\n        rep(i, edge) {\n            cin >> from >> to >> cost;\n            v.pb(mp(cost, mp(from, to)));\n            totalcost += cost;\n        }\n        sort(v.begin(), v.end());\n        // rep(i,v.size())\n        // \tcout<<v[i].first<<\"  \";\n        cout << kruskal() << endl;\n        v.clear();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "b7b830668799c127545bd0deaeee06620edbd098", "size": 2735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graph/kruskal.cpp", "max_stars_repo_name": "shoniavika/C-Plus-Plus", "max_stars_repo_head_hexsha": "acfe6751237f69578a63c8e4cbea07a0bc7f0630", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T10:35:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T10:35:11.000Z", "max_issues_repo_path": "graph/kruskal.cpp", "max_issues_repo_name": "LalitGsk/C-Plus-Plus", "max_issues_repo_head_hexsha": "62562abce3c347ca5ac3665c56ab092dc12891db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph/kruskal.cpp", "max_forks_repo_name": "LalitGsk/C-Plus-Plus", "max_forks_repo_head_hexsha": "62562abce3c347ca5ac3665c56ab092dc12891db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T07:59:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T07:59:12.000Z", "avg_line_length": 23.5775862069, "max_line_length": 58, "alphanum_fraction": 0.4643510055, "num_tokens": 856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.55193225816593}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\n#include <ostream>\n\n//NOLINTNEXTLINE\nint main()\n{\n  namespace ublas = boost::numeric::ublas;\n\n  try {\n    using value   = float;\n    using layout  = ublas::layout::first_order; // storage format\n    using tensor  = ublas::tensor_dynamic<value,layout>;\n//    constexpr auto ones  = ublas::ones<value,layout>{};\n    constexpr auto zeros = ublas::zeros<value,layout>{};\n\n    // creates a three-dimensional tensor with extents 3,4 and 2\n    // tensor A stores single-precision floating-point number according\n    // to the first-order storage format\n\n    tensor A = zeros(3,4,2);\n\n    // initializes the tensor with increasing values along the first-index\n    // using a single index.\n    auto vf = 1.0f;\n    for(auto i = 0u; i < A.size(); ++i, vf += 1.0f)\n      A[i] = vf;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"A=\" << A << \";\" << std::endl << std::endl;\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of access-tensor.\" << std::endl;\n  }\n\n\n  try {\n    using value   = std::complex<boost::multiprecision::cpp_bin_float_double_extended>;\n    using layout  = ublas::layout::last_order; // storage format\n    using tensor  = ublas::tensor_dynamic<value,layout>;\n    using shape   = typename tensor::extents_type;\n    constexpr auto zeros = ublas::zeros<value,layout>{};\n\n\n    // creates a four-dimensional tensor with extents 5,4,3 and 2\n    // tensor A stores complex floating-point extended double precision numbers\n    // according to the last-order storage format\n    // and initializes it with the default value.\n\n    //NOLINTNEXTLINE\n    tensor B = zeros(5,4,3,2);\n\n    // initializes the tensor with increasing values along the last-index\n    // using a single-index\n    auto vc = value(0,0);\n    for(auto i = 0u; i < B.size(); ++i, vc += value(1,1))\n      B[i] = vc;\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"B=\" << B << \";\" << std::endl << std::endl;\n\n\n    auto C = tensor(B.extents());\n    // computes the complex conjugate of elements of B\n    // using multi-index notation.\n    for(auto i = 0u; i < B.size(0); ++i)\n      for(auto j = 0u; j < B.size(1); ++j)\n        for(auto k = 0u; k < B.size(2); ++k)\n          for(auto l = 0u; l < B.size(3); ++l)\n            C.at(i,j,k,l) = std::conj(B.at(i,j,k,l));\n\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"C=\" << C << \";\" << std::endl << std::endl;\n\n\n\n    // computes the complex conjugate of elements of B\n    // using iterators.\n    auto D = tensor(B.extents());\n    std::transform(B.begin(), B.end(), D.begin(), [](auto const& b){ return std::conj(b); });\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"D=\" << D << \";\" << std::endl << std::endl;\n\n    // reshaping tensors.\n    auto new_extents = B.extents().base();\n    std::next_permutation( new_extents.begin(), new_extents.end() );\n    auto E = reshape( D, shape(new_extents)  );\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"E=\" << E << \";\" << std::endl << std::endl;\n\n\n  } catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of access-tensor.\" << std::endl;\n  }\n}\n", "meta": {"hexsha": "97e797fb87ea3e2bc0941163eade6db9974595c8", "size": 4237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tensor/access_tensor.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "examples/tensor/access_tensor.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "examples/tensor/access_tensor.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 36.2136752137, "max_line_length": 93, "alphanum_fraction": 0.5555817796, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.5519214994703951}}
{"text": "#include \"integration.hpp\"\n#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\nusing namespace std;\n\nvoid explicitEulerStep(PhysicalSystem *system, double dt) {\n    forwardEulerStep(system, dt);\n}\n\nvoid forwardEulerStep(PhysicalSystem *system, double dt) {\n    int n = system->getDOFs();\n    VectorXd x0(n), v0(n);\n    system->getState(x0, v0);\n    MatrixXd M(n,n);\n    system->getInertia(M);\n    VectorXd f0(n);\n    system->getForces(f0);\n    VectorXd a0(n); // acceleration\n    for (int i = 0; i < n; i++)\n        a0(i) = f0(i)/M(i,i);\n    VectorXd x1 = x0 + v0*dt;\n    VectorXd v1 = v0 + a0*dt;\n    system->setState(x1, v1);\n}\n\nVectorXd solve(const MatrixXd &A, const VectorXd &b) {\n    SparseMatrix<double> spA = A.sparseView();\n    ConjugateGradient< SparseMatrix<double> > solver;\n    solver.setTolerance(1e-3);\n    return solver.compute(spA).solve(b);\n}\n\nvoid backwardEulerStep(PhysicalSystem *system, double dt) {\n    int n = system->getDOFs();\n    VectorXd x0(n), v0(n);\n    system->getState(x0, v0);\n    static MatrixXd M(n,n);\n    system->getInertia(M);\n    VectorXd f(n);\n    static MatrixXd Jx(n,n), Jv(n,n);\n    system->getForces(f);\n    system->getJacobians(Jx, Jv);\n    MatrixXd A = (M - Jx*dt*dt - Jv*dt);\n    VectorXd b = (f + Jx*v0*dt)*dt;\n    VectorXd v1 = v0 + solve(A, b);\n    system->setState(x0 + v1*dt, v1);\n}\n", "meta": {"hexsha": "c441a239ce5c09fdff067dfc4dfab3c8276b212f", "size": 1367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/2_MassSpring_Implicit/integration.cpp", "max_stars_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_stars_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T08:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T09:29:04.000Z", "max_issues_repo_path": "C++/2_MassSpring_Implicit/integration.cpp", "max_issues_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_issues_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/2_MassSpring_Implicit/integration.cpp", "max_forks_repo_name": "mmmovania/ConstrainedDynamicsExperiments", "max_forks_repo_head_hexsha": "9ebcd7256037fb50785bb2a1ddb7473b034a0c5b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8979591837, "max_line_length": 59, "alphanum_fraction": 0.6349670812, "num_tokens": 433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.5518935224274389}}
{"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 *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n *          University Press, February 2002.\n *      Torok, J.S. Analytical Mechanics: with an Introduction to Dynamical Systems, John Wiley and\n *          Sons, Inc., 2000.\n *      Vallado, D.A. Fundamentals of astro and Applications. Microcosm Press, 2001.\n *\n */\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n#include <boost/math/special_functions/sign.hpp>\n\n#include \"tudat/math/basic/basicMathematicsFunctions.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n#include \"tudat/math/basic/coordinateConversions.h\"\n\nnamespace tudat\n{\n\nnamespace coordinate_conversions\n{\n\n//! Convert cylindrical to Cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const double radius,\n                                               const double azimuthAngle, const double z )\n{\n    // Create Cartesian coordinates vector.\n    Eigen::Vector3d cartesianCoordinates;\n\n    // If radius < 0, then give warning.\n    if ( radius < 0.0 )\n    {\n        std::cerr << \"Warning: cylindrical radial coordinate is negative!, This could give incorrect results!\" << std::endl;\n    }\n\n    // Compute and set Cartesian coordinates.\n    cartesianCoordinates << radius * std::cos( azimuthAngle ),   // x-coordinate\n                            radius * std::sin( azimuthAngle ),   // y-coordinate\n                            z;                                   // z-coordinate\n\n    return cartesianCoordinates;\n}\n\n//! Convert cylindrical to cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const Eigen::Vector3d& cylindricalCoordinates )\n{\n    // Create Cartesian coordinates vector.\n    Eigen::Vector3d cartesianCoordinates;\n\n    // If radius < 0, then give warning.\n    if ( cylindricalCoordinates( 0 ) < 0.0 )\n    {\n        std::cerr << \"Warning: cylindrical radial coordinate is negative!, This could give incorrect results!\" << std::endl;\n    }\n\n    // Compute and set Cartesian coordinates.\n    cartesianCoordinates\n            << cylindricalCoordinates( 0 )\n               * std::cos( cylindricalCoordinates( 1 ) ),    // x-coordinate\n               cylindricalCoordinates( 0 )\n               * std::sin( cylindricalCoordinates( 1 ) ),    // y-coordinate\n               cylindricalCoordinates( 2 );                  // z-coordinate\n\n    return cartesianCoordinates;\n}\n\n//! Convert cylindrical to Cartesian state.\nEigen::Vector6d convertCylindricalToCartesianState(\n        const Eigen::Vector6d& cylindricalState )\n{\n    // Create Cartesian state vector, initialized with zero entries.\n    Eigen::Vector6d cartesianState = Eigen::Vector6d::Zero( );\n\n    // Get azimuth angle, theta.\n    double azimuthAngle = cylindricalState( 1 );\n\n    // Compute and set Cartesian coordinates.\n    cartesianState.head( 3 ) = convertCylindricalToCartesian(\n                Eigen::Vector3d( cylindricalState.head( 3 ) ) );\n\n    // If r = 0 AND Vtheta > 0, then give warning and assume Vtheta=0.\n    if ( std::fabs(cylindricalState( 0 )) <= std::numeric_limits< double >::epsilon( )\n         && std::fabs(cylindricalState( 4 )) > std::numeric_limits< double >::epsilon( ) )\n    {\n        std::cerr << \"Warning: cylindrical velocity Vtheta (r*thetadot) does not equal zero while the radius (r) is zero! Vtheta is taken equal to zero!\" << std::endl;\n\n        // Compute and set Cartesian velocities.\n        cartesianState.tail( 3 )\n                << cylindricalState( 3 ) * std::cos( azimuthAngle ),   // xdot\n                   cylindricalState( 3 ) * std::sin( azimuthAngle ),   // ydot\n                   cylindricalState( 5 );                              // zdot\n    }\n\n    else\n    {\n        // Compute and set Cartesian velocities.\n        cartesianState.tail( 3 )\n                << cylindricalState( 3 ) * std::cos( azimuthAngle )\n                   - cylindricalState( 4 ) * std::sin( azimuthAngle ),   // xdot\n                   cylindricalState( 3 ) * std::sin( azimuthAngle )\n                   + cylindricalState( 4 ) * std::cos( azimuthAngle ),   // ydot\n                   cylindricalState( 5 );                                // zdot\n    }\n\n    return cartesianState;\n}\n\n//! Convert Cartesian to cylindrical coordinates.\nEigen::Vector3d convertCartesianToCylindrical( const Eigen::Vector3d& cartesianCoordinates )\n{\n    // Create cylindrical coordinates vector.\n    Eigen::Vector3d cylindricalCoordinates;\n\n    // Declare new variable, the azimuth angle.\n    double azimuthAngle;\n\n    // Compute azimuth angle, theta.\n    /* If x = 0, then azimuthAngle = pi/2 (y>0) or 3*pi/2 (y<0) or 0 (y=0),\n       else azimuthAngle = arctan(y/x).\n    */\n    using mathematical_constants::PI;\n    if ( std::fabs(cartesianCoordinates( 0 ) ) <= std::numeric_limits< double >::epsilon( ) )\n    {\n        azimuthAngle = basic_mathematics::computeModulo(\n                    static_cast< double >( boost::math::sign( cartesianCoordinates( 1 ) ) )\n                    * 0.5 * PI, 2.0 * PI );\n    }\n\n    else\n    {\n        azimuthAngle = basic_mathematics::computeModulo(\n                    std::atan2( cartesianCoordinates( 1 ),\n                                cartesianCoordinates( 0 ) ), 2.0 * PI );\n    }\n\n    // Compute and set cylindrical coordinates.\n    cylindricalCoordinates <<\n        std::sqrt( pow( cartesianCoordinates( 0 ), 2 )\n                   + pow( cartesianCoordinates( 1 ), 2 ) ), // Radius\n        azimuthAngle,                                       // Azimuth angle, theta\n        cartesianCoordinates( 2 );                          // z-coordinate\n\n    return cylindricalCoordinates;\n}\n\n//! Convert Cartesian to cylindrical state.\nEigen::Vector6d convertCartesianToCylindricalState(\n        const Eigen::Vector6d& cartesianState )\n{\n    // Create cylindrical state vector, initialized with zero entries.\n    Eigen::Vector6d cylindricalState = Eigen::Vector6d::Zero( );\n\n    // Compute and set cylindrical coordinates.\n    cylindricalState.head( 3 ) = convertCartesianToCylindrical(\n                Eigen::Vector3d( cartesianState.head( 3 ) ) );\n\n    // Compute and set cylindrical velocities.\n    /* If radius = 0, then Vr = sqrt(xdot^2+ydot^2) and Vtheta = 0,\n       else Vr = (x*xdot+y*ydot)/radius and Vtheta = (x*ydot-y*xdot)/radius.\n    */\n    if ( cylindricalState( 0 ) <= std::numeric_limits< double >::epsilon( ) )\n    {\n        cylindricalState.tail( 3 ) <<\n            std::sqrt( pow( cartesianState( 3 ), 2 ) + pow( cartesianState( 4 ), 2 ) ), // Vr\n            0.0,                                                                        // Vtheta\n            cartesianState( 5 );                                                        // Vz\n    }\n\n    else\n    {\n        cylindricalState.tail( 3 ) <<\n            ( cartesianState( 0 ) * cartesianState( 3 )\n              + cartesianState( 1 ) * cartesianState( 4 ) ) / cylindricalState( 0 ),    // Vr\n            ( cartesianState( 0 ) * cartesianState( 4 )\n              - cartesianState( 1 ) * cartesianState( 3 ) ) / cylindricalState( 0 ),    // Vtheta\n                cartesianState( 5 );                                                    // Vz\n    }\n\n    return cylindricalState;\n}\n\n//! Compute matrix by which to precompute a spherical gradient vector to obtain the Cartesian gradient\nEigen::Matrix3d getSphericalToCartesianGradientMatrix( const Eigen::Vector3d& cartesianCoordinates )\n{\n    // Compute radius.\n    const double radius = std::sqrt( cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n                                     + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 )\n                                     + cartesianCoordinates( 2 ) * cartesianCoordinates( 2 ) );\n\n    // Compute square of distance within xy-plane.\n    const double xyDistanceSquared = cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n            + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 );\n\n    // Compute distance within xy-plane.\n    const double xyDistance = std::sqrt( xyDistanceSquared );\n\n    // Compute transformation matrix.\n    const Eigen::Matrix3d transformationMatrix = (\n                Eigen::Matrix3d( 3, 3 ) <<\n                cartesianCoordinates( 0 ) / radius,\n                - cartesianCoordinates( 0 ) * cartesianCoordinates( 2 ) / ( radius * radius * xyDistance ),\n                - cartesianCoordinates( 1 ) / xyDistanceSquared,\n                cartesianCoordinates( 1 ) / radius,\n                - cartesianCoordinates( 1 ) * cartesianCoordinates( 2 ) / ( radius * radius * xyDistance ),\n                + cartesianCoordinates( 0 ) / xyDistanceSquared,\n                cartesianCoordinates( 2 ) / radius,\n                xyDistance / ( radius * radius ),   0.0\n                ).finished( );\n    return transformationMatrix;\n}\n\n//! Convert spherical to Cartesian gradient.\nEigen::Vector3d convertSphericalToCartesianGradient( const Eigen::Vector3d& sphericalGradient,\n                                                     const Eigen::Vector3d& cartesianCoordinates )\n{\n\n\n    // Return Cartesian gradient.\n    return getSphericalToCartesianGradientMatrix( cartesianCoordinates ) * sphericalGradient;\n}\n\nEigen::Matrix3d getDerivativeOfSphericalToCartesianGradient( const Eigen::Vector3d& sphericalGradient,\n                                                             const Eigen::Vector3d& cartesianCoordinates,\n                                                             std::vector< Eigen::Matrix3d >& subMatrices )\n{\n    Eigen::Matrix3d totalPartialMatrix;\n    totalPartialMatrix.setZero( );\n\n    Eigen::Matrix3d currentPartialMatrix;\n\n    // Precomputed quantities\n    double radius = cartesianCoordinates.norm( );\n    const double xyDistanceSquared = cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n            + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 );\n    const double xyDistance = std::sqrt( xyDistanceSquared );\n    const double radiusSquaredXyDistance = xyDistance * radius * radius;\n\n    // Precompute partials\n    Eigen::Vector3d oneOverRPartial = -cartesianCoordinates / ( radius * radius * radius );\n    Eigen::Vector3d oneOverRSquaredPartial = -2.0 * cartesianCoordinates / ( radius * radius * radius * radius );\n    Eigen::Vector3d oneOverXyDistancePartial =\n            -( Eigen::Vector3d( ) << cartesianCoordinates( 0 ), cartesianCoordinates( 1 ), 0.0 ).finished( )/\n            ( xyDistanceSquared * xyDistance );\n    Eigen::Vector3d oneOverXyDistanceSquaredPartial =\n            -2.0 * ( Eigen::Vector3d( ) << cartesianCoordinates( 0 ), cartesianCoordinates( 1 ), 0.0 ).finished( )/\n            ( xyDistanceSquared * xyDistanceSquared );\n    Eigen::Vector3d oneOverRSquaredXyDistancePartial =\n            oneOverRSquaredPartial / xyDistance + oneOverXyDistancePartial / ( radius * radius );\n\n\n    Eigen::Vector3d xyDistancePartial =\n            ( Eigen::Vector3d( ) << cartesianCoordinates( 0 ), cartesianCoordinates( 1 ), 0.0 ).finished( ) / xyDistance;\n\n    // Compute partials w.r.t x, y and z components.\n    for( unsigned int i = 0; i < 3; i++ )\n    {\n        currentPartialMatrix.setZero( );\n        switch( i )\n        {\n        case 0:\n        {\n            currentPartialMatrix << 1.0 / radius + cartesianCoordinates( 0 ) * oneOverRPartial ( 0 ),\n                    - cartesianCoordinates( 2 ) / radiusSquaredXyDistance -\n                    cartesianCoordinates( 0 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 0 ),\n                    - cartesianCoordinates( 1 ) * oneOverXyDistanceSquaredPartial( 0 ),\n                    cartesianCoordinates( 1 ) * oneOverRPartial( 0 ),\n                     - cartesianCoordinates( 1 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 0 ),\n                    1.0 / ( xyDistanceSquared ) + cartesianCoordinates( 0 ) * oneOverXyDistanceSquaredPartial( 0 ),\n                     cartesianCoordinates( 2 ) * oneOverRPartial( 0 ),\n                    xyDistance * oneOverRSquaredPartial( 0 ) + 1.0 / ( radius * radius ) * xyDistancePartial( 0 ),\n                    0.0 ;\n            break;\n        }\n        case 1:\n        {\n            currentPartialMatrix << cartesianCoordinates( 0 ) * oneOverRPartial ( 1 ),\n                    - cartesianCoordinates( 0 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 1 ),\n                    -1.0 / ( xyDistanceSquared ) - cartesianCoordinates( 1 ) * oneOverXyDistanceSquaredPartial( 1 ),\n                    1.0 / radius + cartesianCoordinates( 1 ) * oneOverRPartial ( 1 ),\n                    - cartesianCoordinates( 2 ) / radiusSquaredXyDistance -\n                    cartesianCoordinates( 1 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 1 ),\n                    cartesianCoordinates( 0 ) * oneOverXyDistanceSquaredPartial( 1 ),\n                     cartesianCoordinates( 2 ) * oneOverRPartial( 1 ),\n                    xyDistance * oneOverRSquaredPartial( 1 ) + 1.0 / ( radius * radius ) * xyDistancePartial( 1 ),\n                    0.0 ;\n            break;\n        }\n        case 2:\n        {\n            currentPartialMatrix <<  cartesianCoordinates( 0 ) * oneOverRPartial ( 2 ),\n                    - cartesianCoordinates( 0 ) / radiusSquaredXyDistance -\n                    cartesianCoordinates( 0 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 2 ),\n                    - cartesianCoordinates( 1 ) * oneOverXyDistanceSquaredPartial( 2 ),\n                    cartesianCoordinates( 1 ) * oneOverRPartial( 2 ),\n                    - cartesianCoordinates( 1 ) / radiusSquaredXyDistance -\n                    cartesianCoordinates( 1 ) * cartesianCoordinates( 2 ) * oneOverRSquaredXyDistancePartial( 2 ),\n                    cartesianCoordinates( 0 ) * oneOverXyDistanceSquaredPartial( 2 ),\n                     1.0 / radius + cartesianCoordinates( 2 ) * oneOverRPartial( 2 ),\n                    xyDistance * oneOverRSquaredPartial( 2 ) +  + 1.0 / ( radius * radius ) * xyDistancePartial( 2 ),\n                    0.0 ;\n            break;\n        }\n        }\n\n        // Save computed matrix\n        if( subMatrices.size( ) == 3 )\n        {\n            subMatrices[ i ] = currentPartialMatrix;\n        }\n\n        // Add current entry to results.\n        totalPartialMatrix.block( 0, i, 3, 1 ) = currentPartialMatrix * sphericalGradient;\n    }\n\n    return totalPartialMatrix;\n}\n\nEigen::Matrix3d getDerivativeOfSphericalToCartesianGradient( const Eigen::Vector3d& sphericalGradient,\n                                                             const Eigen::Vector3d& cartesianCoordinates )\n{\n    static std::vector< Eigen::Matrix3d > subMatrices( 3 );\n    return getDerivativeOfSphericalToCartesianGradient(\n                sphericalGradient, cartesianCoordinates, subMatrices );\n}\n\n//! Convert spherical to Cartesian state.\nEigen::Vector6d convertSphericalToCartesianState(\n        const Eigen::Vector6d& sphericalState )\n{\n    // Create Cartesian state vector, initialized with zero entries.\n    Eigen::Vector6d convertedCartesianState = Eigen::Vector6d::Zero( );\n\n    // Create local variables.\n    const double radius = sphericalState( 0 );\n    const double azimuthAngle = sphericalState( 1 );\n    const double elevationAngle = sphericalState( 2 );\n\n    // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n    const double cosineOfElevationAngle = std::cos( elevationAngle );\n    const double sineOfElevationAngle = std::sin( elevationAngle );\n    const double cosineOfAzimuthAngle = std::cos( azimuthAngle );\n    const double sineOfAzimuthAngle = std::sin( azimuthAngle );\n\n    // Set up transformation matrix for spherical to cylindrical conversion.\n    Eigen::Matrix3d transformationMatrixSphericalToCylindrical = Eigen::Matrix3d::Zero( );\n    transformationMatrixSphericalToCylindrical( 0, 0 ) = cosineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 0, 2 ) = -sineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 1, 1 ) = 1.0;\n    transformationMatrixSphericalToCylindrical( 2, 0 ) = sineOfElevationAngle;\n    transformationMatrixSphericalToCylindrical( 2, 2 ) = cosineOfElevationAngle;\n\n    // Set up transformation matrix for cylindrical to Cartesian conversion.\n    Eigen::Matrix3d transformationMatrixCylindricalToCartesian = Eigen::Matrix3d::Zero( );\n    transformationMatrixCylindricalToCartesian( 0, 0 ) = cosineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 0, 1 ) = -sineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 1, 0 ) = sineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 1, 1 ) = cosineOfAzimuthAngle;\n    transformationMatrixCylindricalToCartesian( 2, 2 ) = 1.0;\n\n    // Compute transformation matrix for spherical to Cartesian conversion.\n    const Eigen::Matrix3d transformationMatrixSphericalToCartesian\n            = transformationMatrixCylindricalToCartesian\n            * transformationMatrixSphericalToCylindrical;\n\n    // Perform transformation of position coordinates.\n    convertedCartesianState( 0 ) = radius * cosineOfAzimuthAngle * cosineOfElevationAngle;\n    convertedCartesianState( 1 ) = radius * sineOfAzimuthAngle * cosineOfElevationAngle;\n    convertedCartesianState( 2 ) = radius * sineOfElevationAngle;\n\n    // Perform transformation of velocity vector.\n    convertedCartesianState.segment( 3, 3 ) =\n        transformationMatrixSphericalToCartesian * sphericalState.segment( 3, 3 );\n\n    // Return Cartesian state vector.\n    return convertedCartesianState;\n}\n\n//! Convert Cartesian to spherical state.\nEigen::Vector6d convertCartesianToSphericalState(\n        const Eigen::Vector6d& cartesianState )\n{\n    // Create spherical state vector, initialized with zero entries.\n    Eigen::Vector6d convertedSphericalState = Eigen::Vector6d::Zero( );\n\n    // Compute radius.\n    convertedSphericalState( 0 ) = cartesianState.segment( 0, 3 ).norm( );\n\n    // Check if radius is nonzero.\n    /*\n     * If r > 0, the elevation and azimuth angles are computed using trigonometric relationships.\n     * If r = 0, the coordinates are at the origin, the elevation and azimuth angles equal to zero.\n     * Since the state vector was initialized with zeroes, this is already the case.\n     */\n    if ( convertedSphericalState( 0 ) > std::numeric_limits< double >::epsilon( ) )\n    {\n        // Compute elevation and azimuth angles using trigonometric relationships.\n        // Azimuth angle.\n        convertedSphericalState( 1 ) = std::atan2( cartesianState( 1 ), cartesianState( 0 ) );\n        // Elevation angle.\n        convertedSphericalState( 2 ) = std::asin( cartesianState( 2 )\n                                                   / convertedSphericalState( 0 ) );\n    }\n\n    // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n    const double cosineOfElevationAngle = std::cos( convertedSphericalState( 2 ) );\n    const double sineOfElevationAngle = std::sin( convertedSphericalState( 2 ) );\n    const double cosineOfAzimuthAngle = std::cos( convertedSphericalState( 1 ) );\n    const double sineOfAzimuthAngle = std::sin( convertedSphericalState( 1 ) );\n\n    // Set up transformation matrix for cylindrical to spherical conversion.\n    Eigen::Matrix3d transformationMatrixCylindricalToSpherical = Eigen::Matrix3d::Zero( );\n    transformationMatrixCylindricalToSpherical( 0, 0 ) = cosineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 0, 2 ) = sineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 1, 1 ) = 1.0;\n    transformationMatrixCylindricalToSpherical( 2, 0 ) = -sineOfElevationAngle;\n    transformationMatrixCylindricalToSpherical( 2, 2 ) = cosineOfElevationAngle;\n\n    // Set up transformation matrix for Cartesian to cylindrical conversion.\n    Eigen::Matrix3d transformationMatrixCartesianToCylindrical = Eigen::Matrix3d::Zero( );\n    transformationMatrixCartesianToCylindrical( 0, 0 ) = cosineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 0, 1 ) = sineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 1, 0 ) = -sineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 1, 1 ) = cosineOfAzimuthAngle;\n    transformationMatrixCartesianToCylindrical( 2, 2 ) = 1.0;\n\n    // Compute transformation matrix for Cartesian to spherical conversion.\n    const Eigen::Matrix3d transformationMatrixCartesianToSpherical\n            = transformationMatrixCylindricalToSpherical\n            * transformationMatrixCartesianToCylindrical;\n\n    // Perform transformation of velocity vector.\n    convertedSphericalState.segment( 3, 3 )\n            = transformationMatrixCartesianToSpherical * cartesianState.segment( 3, 3 );\n\n    // Return spherical state vector.\n    return convertedSphericalState;\n}\n\n} // namespace coordinate_conversions\n\n} // namespace tudat\n", "meta": {"hexsha": "f832c7147fa9982cdb5ed2ef17c60d62e8ff5a04", "size": 21231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/basic/coordinateConversions.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/basic/coordinateConversions.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/basic/coordinateConversions.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7643171806, "max_line_length": 167, "alphanum_fraction": 0.6421270783, "num_tokens": 4953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5518935068943788}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <boost/make_shared.hpp>\n\n#include <iostream>\n#include <fstream>\n\nusing namespace QuantLib;\n\n\nvoid spreads() {\n\n    // set up market data\n\n    Date refDate = Date(14, October, 2013);\n    Date settlDate = TARGET().advance(refDate, 2, Days);\n    Settings::instance().evaluationDate() = refDate;\n    \n    boost::shared_ptr<SimpleQuote> rateLevel0(new SimpleQuote(0.025));\n    boost::shared_ptr<SimpleQuote> rateLevel(new SimpleQuote(0.03));\n    Handle<Quote> forward0(rateLevel0);\n    Handle<Quote> forward(rateLevel);\n    Handle<YieldTermStructure> yts0(\n        boost::make_shared<FlatForward>(refDate, forward0, Actual365Fixed()));\n    Handle<YieldTermStructure> yts(\n        boost::make_shared<FlatForward>(refDate, forward, Actual365Fixed()));\n\n    boost::shared_ptr<IborIndex> euribor6m(new Euribor(6 * Months, yts));\n\n    // swap and bond\n\n    boost::shared_ptr<VanillaSwap> swap =\n        MakeVanillaSwap(20 * Years, euribor6m, 0.04).receiveFixed(false);\n    Leg fix = swap->leg(0);\n    fix.push_back(\n        boost::shared_ptr<CashFlow>(new Redemption(1.0, fix.back()->date())));\n\n    for (Size i = 0; i < fix.size(); i++) {\n        std::cout << fix[i]->date() << \"  \\t\" << fix[i]->amount() << std::endl;\n    }\n\n    boost::shared_ptr<PricingEngine> discountingEngine(\n        new DiscountingSwapEngine(yts0, boost::none, settlDate, settlDate));\n    swap->setPricingEngine(discountingEngine);\n\n    std::cout << \"swap npv = \" << swap->NPV() << std::endl;\n    std::cout << \"swap bps = \" << swap->floatingLegBPS() << std::endl;\n\n    // tabulate zSpread against asset swap spread\n\n    std::ofstream out1;\n    out1.open(\"spreads1c.dat\");\n\n    Real zSpread = 0.0;\n    while (zSpread <= 0.10) {\n\n        Real bondNpv = CashFlows::npv(\n            fix, *yts, zSpread, Actual365Fixed(), Continuous,\n            NoFrequency, false, settlDate, settlDate);\n\n        Real swapNpv = swap->NPV();\n        Real swapBps = swap->floatingLegBPS();\n\n        Real aswSpread = (1.0 - (bondNpv + swapNpv)) / swapBps / 10000.0;\n\n        out1 << zSpread * 10000.0 << \" \" << aswSpread * 10000.0 << std::endl;\n\n        zSpread += 0.0001;\n    }\n\n    out1.close();\n\n    // tabulate da/dz against zSpread level\n\n    out1.open(\"spreads2c.dat\");\n\n    zSpread = 0.0;\n    while (zSpread <= 0.10) {\n\n        Real bondNpv = CashFlows::npv(\n            fix, *yts, zSpread, Actual365Fixed(), Continuous,\n            NoFrequency, false, settlDate, settlDate);\n\n        Real bondNpvP =\n            CashFlows::npv(fix, *yts, zSpread + 0.0001, Actual365Fixed(),\n                           Continuous, NoFrequency,\n                           false, settlDate, settlDate);\n\n        // Real bondNpv = CashFlows::npv(\n        //     fix, *yts, zSpread, Actual360(), Compounding::Compounded,\n        //     Frequency::Annual, false, settlDate, settlDate);\n\n        // Real bondNpvP =\n        //     CashFlows::npv(fix, *yts, zSpread + 0.0001, Actual360(),\n        //                    Compounding::Compounded, Frequency::Annual,\n        //                    false, settlDate, settlDate);\n\n        Real swapNpv = swap->NPV();\n        Real swapBps = swap->floatingLegBPS();\n\n        Real aswSpread = (1.0 - (bondNpv + swapNpv)) / swapBps / 10000.0;\n        Real aswSpreadP = (1.0 - (bondNpvP + swapNpv)) / swapBps / 10000.0;\n\n        out1 << zSpread * 10000.0 << \" \" << (aswSpreadP - aswSpread) * 10000.0\n             << std::endl;\n\n        zSpread += 0.0001;\n    }\n\n    out1.close();\n\n    // tabulate da/dy against zSpread level\n\n    out1.open(\"spreads3c.dat\");\n\n    zSpread = 0.0;\n    while (zSpread <= 0.10) {\n\n        Real swapNpv = swap->NPV();\n        Real swapBps = swap->floatingLegBPS();\n        Real bondNpv = CashFlows::npv(\n            fix, *yts, zSpread, Actual365Fixed(), Continuous,\n            NoFrequency, false, settlDate, settlDate);\n\n        rateLevel0->setValue(rateLevel0->value() + 0.0001);\n        rateLevel->setValue(rateLevel->value() + 0.0001);\n\n        Real bondNpvP = CashFlows::npv(\n            fix, *yts, zSpread, Actual365Fixed(), Continuous,\n             NoFrequency, false, settlDate, settlDate);\n\n        Real swapNpvP = swap->NPV();\n        Real swapBpsP = swap->floatingLegBPS();\n\n        rateLevel0->setValue(rateLevel0->value() - 0.0001);\n        rateLevel->setValue(rateLevel->value() - 0.0001);\n\n        Real aswSpread = (1.0 - (bondNpv + swapNpv)) / swapBps / 10000.0;\n        Real aswSpreadP = (1.0 - (bondNpvP + swapNpvP)) / swapBpsP / 10000.0;\n\n        out1 << zSpread * 10000.0 << \" \" << (aswSpreadP - aswSpread) * 10000.0\n             << std::endl;\n\n        zSpread += 0.0001;\n    }\n\n    out1.close();\n}\n\nint main(int, char * []) { spreads(); }\n", "meta": {"hexsha": "397077c955b15dcb095bf5e424fb1ec629827945", "size": 4686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/AswZSpreads/AswZSpreads.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/AswZSpreads/AswZSpreads.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/AswZSpreads/AswZSpreads.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": 31.0331125828, "max_line_length": 79, "alphanum_fraction": 0.585787452, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.5518935068943788}}
{"text": "#include <omp.h>\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <set>\n#include <tuple>\n\n#include \"qpp.h\"\n\nusing namespace qpp;\nusing uint = unsigned int;\n\nstruct SimStateDmat {\n  cmat state = cmat::Zero(1, 1);\n  int num_qubits = 0;\n  SimStateDmat() { state << 1; }\n};\n\ntypedef SimStateDmat* state_t;\n\nextern \"C\" state_t empty_dmat() { return new SimStateDmat; }\n\nextern \"C\" void discard_dmat(state_t s) { delete s; }\n\nextern \"C\" int qinit_dmat(state_t s) {\n  s->state = kron(s->state, prj(0_ket));\n  return s->num_qubits++;\n}\n\nenum Gate : int {\n  X = 0,\n  Y = 1,\n  Z = 2,\n  H = 3,\n  CNOT = 4,\n  CZ = 5,\n  TOF = 6,\n  FRED = 7,\n  PHASE = 8,\n  CPHASE = 9\n};\n\nextern \"C\" void unitary1_dmat(state_t s, Gate g, uint q) {\n  cmat u;\n  switch (g) {\n    case X:\n      u = gt.X;\n      break;\n    case Y:\n      u = gt.Y;\n      break;\n    case Z:\n      u = gt.Z;\n      break;\n    case H:\n      u = gt.H;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q});\n}\n\nextern \"C\" void unitary2_dmat(state_t s, Gate g, uint q1, uint q2) {\n  cmat u;\n  switch (g) {\n    case CNOT:\n      u = gt.CNOT;\n      break;\n    case CZ:\n      u = gt.CZ;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q1, q2});\n}\n\nextern \"C\" void unitary3_dmat(state_t s, Gate g, uint q1, uint q2, uint q3) {\n  cmat u;\n  switch (g) {\n    case TOF:\n      u = gt.TOF;\n      break;\n    case FRED:\n      u = gt.FRED;\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q1, q2, q3});\n}\n\nextern \"C\" void punitary1_dmat(state_t s, Gate g, uint q, double p) {\n  cmat u = std::polar(1.0, M_PI * p) * gt.RZ(2 * M_PI * p);\n  switch (g) {\n    case PHASE:\n      break;\n    default:\n      abort();\n  }\n  s->state = apply(s->state, u, {q});\n}\n\nextern \"C\" void punitary2_dmat(state_t s, Gate g, uint q1, uint q2, double p) {\n  cmat u = std::polar(1.0, M_PI * p) * gt.RZ(2 * M_PI * p);\n  switch (g) {\n    case CPHASE:\n      break;\n    default:\n      abort();\n  }\n  s->state = applyCTRL(s->state, u, {q1}, {q2});\n}\n\nextern \"C\" void measure_dmat(state_t s, uint q, bool outcome) {\n  cmat p = cmat::Zero(2, 2);\n  if (outcome) {\n    p << 1, 0, 0, 0;\n  } else {\n    p << 0, 0, 0, 1;\n  }\n  s->state = apply(s->state, p, {q});\n}\n\ninline bool is_pure(const cmat& t) {\n  return std::norm((t * t).trace() - std::complex<double>(1.0f)) < 1e-5;\n}\n\nextern \"C\" bool separable_dmat(state_t s, const uint* const qs, uint n) {\n  if (n == s->num_qubits) {\n    return is_pure(s->state);\n  }\n  std::set<idx> target;\n  for (idx i = 0; i < s->num_qubits; ++i) {\n    target.insert(i);\n  }\n  for (int i = 0; i < n; ++i) {\n    target.erase(qs[i]);\n  }\n  return is_pure(ptrace(s->state, std::vector<idx>(target.begin(), target.end())));\n}\n\nextern \"C\" state_t clone_dmat(state_t s) {\n  state_t t = new SimStateDmat;\n  t->state = s->state;\n  t->num_qubits = s->num_qubits;\n  return t;\n}\n\ninline uint swap_bits(uint x, uint p1, uint p2) {\n  const uint y = ((x >> p1) & 1) ^ ((x >> p2) & 1);\n  return x ^ ((y << p1) | (y << p2));\n}\n\ninline void swap(cmat& state, const idx numdims, const uint* const q1, const uint* const q2, uint n) {\n  using namespace Eigen;\n  PermutationMatrix<Dynamic, Dynamic> perm(1UL << numdims);\n\n#ifdef HAS_OPENMP\n#pragma omp parallel for\n#endif\n  for (idx i = 0; i < 1UL << numdims; ++i) {\n    idx j = i;\n    for (uint k = 0; k < n; ++k) {\n      j = swap_bits(j, q2[k], q1[k]);\n    }\n    perm.indices()[i] = j;\n  }\n\n  state = perm * state * perm.transpose();\n}\n\nextern \"C\" void sum_dmat(state_t s1, state_t s2, const uint* const q1, const uint* const q2, uint nqs) {\n  while (s1->num_qubits > s2->num_qubits) {\n    s2->state = kron(s2->state, prj(0_ket));\n    s2->num_qubits++;\n  }\n  while (s2->num_qubits > s1->num_qubits) {\n    s1->state = kron(s1->state, prj(0_ket));\n    s1->num_qubits++;\n  }\n  swap(s2->state, s2->num_qubits, q1, q2, nqs);\n  s1->state += s2->state;\n  delete s2;\n}\n\nextern \"C\" void print_dmat(state_t s) {\n  if (s->state.size() <= 1) {\n    std::cout << \"(empty)\" << std::endl;\n  } else {\n    std::cout << disp(s->state) << std::endl;\n  }\n}\n", "meta": {"hexsha": "abc0661e0bd4133b4b780c64e854c19cd1a80b89", "size": 4081, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qpp_stub/stub_dmat.cpp", "max_stars_repo_name": "psg-mit/twist-popl22", "max_stars_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2022-01-22T20:12:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T18:25:53.000Z", "max_issues_repo_path": "qpp_stub/stub_dmat.cpp", "max_issues_repo_name": "psg-mit/twist-popl22", "max_issues_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qpp_stub/stub_dmat.cpp", "max_forks_repo_name": "psg-mit/twist-popl22", "max_forks_repo_head_hexsha": "fa495479ff021fb8793ae20d8cf786ed048f503d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T02:27:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T07:48:28.000Z", "avg_line_length": 20.9282051282, "max_line_length": 104, "alphanum_fraction": 0.5584415584, "num_tokens": 1506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.5518935059715406}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templateauxilliaries_solver1d_hpp\n#define quantlib_templateauxilliaries_solver1d_hpp\n\n#include <ql/types.hpp>\n#include <boost/function.hpp>\n\n\nnamespace TemplateAuxilliaries {\n\n    //! Template for 1-D solution f(x) = 0, s.t. x \\in [a,b] via secant method\n    template <class Type>\n    Type solve1d( const boost::function<Type (Type)>& f, Type xTol, Type a, Type b, size_t nTrials = 10 ) {\n        Type fa = f(a);\n        Type fb = f(b);\n        if (fa*fb>0) {  // we need new arguments enclosing the solution\n            b = (a + b);\n            a = b / 4.0;\n            for (size_t k=0; k<nTrials; ++k) {\n                fa = f(a);\n                fb = f(b);\n                if (fa*fb<=0) break;\n                a = a/2.0;\n                b = b*2.0;\n            }\n        }\n        QL_REQUIRE(fa*fb<=0,\"Solve1d: Can't find intervall enclosing a solution\");\n        if (a>b) { // swap a <-> b\n            Type tmp = a; a = b; b = tmp;\n            tmp = fa; fa = fb; fb = tmp;\n        }\n        Type m = (fb - fa)/(b-a);\n        Type x1 = a;\n        Type y1 = fa;\n        Type s = - y1/m;\n        while (fabs(s)>xTol) {\n            Type x0=x1, y0=y1;\n            // find a new solution\n            x1 = x0 + s;\n            if ((x1<a)||(x1>b)) x1 = (a + b)/2.0;\n            y1 = f(x1);\n            m  = (y1-y0)/(x1-x0);\n            s  = -y1/m;\n            // update intervalls\n            if (fa*y1>=0) {\n                a  = x1;\n                fa = y1;\n            } else {\n                b  = x1;\n                fb = y1;\n            }\n        }\n        return x1;\n    }\n    \n}\n\n#endif  /* ifndef quantlib_solve1d_hpp */\n", "meta": {"hexsha": "8203eff91bdc42b154df221c308392293e3398c4", "size": 1773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/solver1dT.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/auxilliaries/solver1dT.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/auxilliaries/solver1dT.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": 26.4626865672, "max_line_length": 107, "alphanum_fraction": 0.4404963339, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.551702884572939}}
{"text": "// Copyright (c) 2020 Marcus Valtonen Örnhag\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \"get_fitzgibbon_cvpr_2001.hpp\"\n#include <float.h>  // For DBL_MAX\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n#include \"posedata.hpp\"\n#include \"radial.hpp\"\n\nnamespace HomLib {\nnamespace FitzgibbonCVPR2001 {\n    inline Eigen::Matrix3d vec2asym(const Eigen::Vector3d& t);\n\n    HomLib::PoseData get(const Eigen::MatrixXd& x1n, const Eigen::MatrixXd& x2n) {\n        // This is a five point method\n        int n_points = 5;\n\n        // Make homogenous\n        Eigen::MatrixXd x1 = x1n.colwise().homogeneous();\n        Eigen::MatrixXd x2 = x2n.colwise().homogeneous();\n\n        // Compute the distance to center point\n        Eigen::MatrixXd z1(3, n_points);\n        z1 << Eigen::MatrixXd::Zero(2, n_points), x1n.colwise().squaredNorm();\n        Eigen::MatrixXd z2(3, n_points);\n        z2 << Eigen::MatrixXd::Zero(2, n_points), x2n.colwise().squaredNorm();\n\n        // Initialize D0, D1 and D2\n        Eigen::MatrixXd D0(9, 9);\n        D0.setZero();\n        Eigen::MatrixXd D1(9, 9);\n        D1.setZero();\n        Eigen::MatrixXd D2(9, 9);\n        D2.setZero();\n\n        Eigen::Matrix3d Bx2, Bz2;\n        Eigen::Matrix3d e1, e2;\n        Eigen::Vector3d tmp;\n\n        for (int k = 0; k < n_points; k++) {\n            tmp = x2.col(k);\n            Bx2 = HomLib::FitzgibbonCVPR2001::vec2asym(tmp);\n            tmp = z2.col(k);\n            Bz2 = HomLib::FitzgibbonCVPR2001::vec2asym(tmp);\n\n            // D0\n            e1 = Bx2.row(0).transpose() * x1.col(k).transpose();\n            e2 = Bx2.row(1).transpose() * x1.col(k).transpose();\n            D0.row(2*k) = Eigen::Map<Eigen::VectorXd>(e1.data(), 9);\n            if (k < 4) {  // Assure it is 9x9\n                D0.row(2*k + 1) = Eigen::Map<Eigen::VectorXd>(e2.data(), 9);\n            }\n            // D1\n            e1 = Bx2.row(0).transpose() * z1.col(k).transpose() + Bz2.row(0).transpose() * x1.col(k).transpose();\n            e2 = Bx2.row(1).transpose() * z1.col(k).transpose() + Bz2.row(1).transpose() * x1.col(k).transpose();\n            D1.row(2*k) = Eigen::Map<Eigen::VectorXd>(e1.data(), 9);\n            if (k < 4) {\n                D1.row(2*k + 1) = Eigen::Map<Eigen::VectorXd>(e2.data(), 9);\n            }\n\n            // D2\n            e1 = Bz2.row(0).transpose() * z1.col(k).transpose();\n            e2 = Bz2.row(1).transpose() * z1.col(k).transpose();\n            D2.row(2*k) = Eigen::Map<Eigen::VectorXd>(e1.data(), 9);\n            if (k < 4) {\n                D2.row(2*k + 1) = Eigen::Map<Eigen::VectorXd>(e2.data(), 9);\n            }\n        }\n\n        // Create generalized eigenvalue problem\n        Eigen::MatrixXd A(18, 18);\n        Eigen::MatrixXd B(18, 18);\n        A.setZero();\n        B.setZero();\n\n        A.topLeftCorner(9, 9) = -D0;\n        A.bottomRightCorner(9, 9) = Eigen::MatrixXd::Identity(9, 9);\n        B.topLeftCorner(9, 9) = D1;\n        B.topRightCorner(9, 9) = D2;\n        B.bottomLeftCorner(9, 9) = Eigen::MatrixXd::Identity(9, 9);\n\n        Eigen::GeneralizedEigenSolver<Eigen::MatrixXd> ges;\n        ges.compute(A, B, true);\n        Eigen::VectorXcd l;\n        Eigen::MatrixXd X;\n        l = ges.eigenvalues();\n        Eigen::MatrixXcd eigvecs;\n        eigvecs = ges.eigenvectors();\n        X = eigvecs.real().topRows(9);\n\n        // Extract correct solution\n        Eigen::Matrix3d Htmp;\n        Eigen::MatrixXd z(3, 5);\n        double res;\n        double minres = DBL_MAX;\n        HomLib::PoseData posedata;\n        double ltmp;\n        Eigen::Array<bool, 1, 18> is_ok;\n        is_ok = l.array().isFinite() && l.array().imag() == 0;\n\n        for (int k = 0; k < 18; k++) {\n            if (is_ok(k)) {\n                ltmp = l(k).real();\n                Htmp = Eigen::Map<Eigen::Matrix3d>(X.col(k).data(), 3, 3);\n                z = Htmp * radialundistort(x1.colwise().hnormalized(), ltmp).colwise().homogeneous();\n                res = (x2.colwise().hnormalized() - radialdistort(z.colwise().hnormalized(), ltmp)).squaredNorm();\n                if (res < minres) {\n                    minres = res;\n                    posedata.homography = Htmp;\n                    posedata.distortion_parameter = ltmp;\n                }\n            }\n        }\n\n        return posedata;\n    }\n\n    // TODO(marcusvaltonen): Refactor -> helpers when necessary\n    inline Eigen::Matrix3d vec2asym(const Eigen::Vector3d& t) {\n        Eigen::Matrix3d t_hat;\n        t_hat << 0, -t(2), t(1),\n                 t(2), 0, -t(0),\n                -t(1), t(0), 0;\n        return t_hat;\n    }\n}  // namespace FitzgibbonCVPR2001\n}  // namespace HomLib\n", "meta": {"hexsha": "81bdbf9a8e7ef641bbeff6afbfcd3b93e90d7639", "size": 5677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/fitzgibbon_cvpr_2001/get_fitzgibbon_cvpr_2001.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/solvers/fitzgibbon_cvpr_2001/get_fitzgibbon_cvpr_2001.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/solvers/fitzgibbon_cvpr_2001/get_fitzgibbon_cvpr_2001.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": 38.619047619, "max_line_length": 114, "alphanum_fraction": 0.5721331689, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5515966071655597}}
{"text": "#include <Engine/MeshEdit/Simulate.h>\n#include <windows.h>\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\nusing namespace Ubpa;\nusing namespace std;\nusing namespace Eigen;\n\nvoid Simulate::SetFast(){\n\tisfast = true;\n}\n\nvoid Simulate::Clear() {\n\tthis->positions.clear();\n}\n\nbool Simulate::Init() {\n\tisfast = true;\n\tm = positions.size(); // number of vertices\n\ts = edgelist.size() / 2;  // number of springs\n\tg = 9.8;\n\titeration = 10;\n\tstiff = 1e5;\n\n\tthis->velocity.resize(positions.size());\n\tfor (int i = 0; i < positions.size(); i++)\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tthis->velocity[i][j] = 0;\n\n\t// init l\n\tfor (int i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tpointf3 v1 = positions[index1];\n\t\tpointf3 v2 = positions[index2];\n\t\tl.push_back((v1 - v2).norm());\n\t}\n\n\tmass.resize(3 * positions.size());\n\tf_int.resize(3 * positions.size());\n\tfor (int i = 0; i < 3 * positions.size(); i++) {\n\t\tf_int[i] = 0.0;\n\t\tmass[i] = 1;\n\t}\n\n\tx.resize(3 * m); // vector x, initialized to be y\n\ty.resize(3 * m); // vector y = 2q_n - q_n-1\n\tx_pre.resize(3 * m);\n\tfor (int i = 0; i < m; i++) {\n\t\tx.segment(3 * i, 3) << positions[i][0], positions[i][1], positions[i][2];\n\t\ty.segment(3 * i, 3) = x.segment(3 * i, 3);\n\t\tx_pre.segment(3 * i, 3) = x.segment(3 * i, 3);\n\t}\n\t\n\t// init Mass\n\tM = MatrixXd::Identity(m * 3, m * 3);\n\n\t// init f_ext, i.e. gravity\n\tf_ext.resize(3 * m);\n\tfor (int i = 0; i < m; i++)\n\t\tf_ext.segment(3 * i, 3) = Vector3d(0, -mass[i] * g, 0);\n\n\tL = MatrixXd::Zero(m * 3, m * 3);\n\tbuildL();\n\tJ = MatrixXd::Zero(m * 3, s * 3);\n\tbuildJ();\n\n\tFixPoint();\n\tbuildK();\n\tgetb();\n\n\t// prefactorization\n\tMatrixXd A_;\n\tA_.resize(K.rows(), K.rows());\n\tA_ = K * (M + h * h * L) * K.transpose();\n\n\tA = A_.sparseView();\n\tLLT_.compute(A);\n\n\treturn true;\n}\n\nvoid Simulate::SetLeftFix() {\n\t// 固定网格x坐标最小点\n\tfixed_id.clear();\n\tdouble x = 100000;\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (positions[i][0] < x)\n\t\t{\n\t\t\tx = positions[i][0];\n\t\t}\n\t}\n\n\tfor (int i = 0; i < positions.size(); i++)\n\t{\n\t\tif (abs(positions[i][0] - x) < 1e-5)\n\t\t{\n\t\t\tfixed_id.push_back(i);\n\t\t}\n\t}\n\n\tInit();\n}\n\nvoid Simulate::FixPoint() {\n\tfixed_id.push_back(10);\n \tfixed_id.push_back(120);\n}\n\nvoid Simulate::buildK() {\n\tK = MatrixXd::Zero(m * 3 - 3 * fixed_id.size(), m * 3);\n\tset<int> fix(fixed_id.begin(), fixed_id.end());\n\tfor (int i = 0, j = 0; i < m * 3; i++) {\n\t\tif (fix.find(i / 3) == fix.end()) {\n\t\t\tK(j++, i) = 1;\n\t\t}\n\t}\n}\n\nvoid Simulate::buildL() {\n\t// L is 3m * 3m matrix\n\tMatrixXd temp = MatrixXd::Zero(m, m);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tVectorXd Ai = VectorXd::Zero(m);\n\t\tAi(index1) += 1;\n\t\tAi(index2) -= 1;\n\t\ttemp += stiff * Ai * Ai.transpose();\n\t}\n\n\t// kronecker product, L = kronecker(temp, I3)\n\tMatrix3d I3 = Matrix3d::Identity();\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j < m; j++)\n\t\t\tL.block(i * 3, j * 3, 3, 3) = temp(i, j) * I3;\n}\n\nvoid Simulate::buildJ() {\n\t// J is 3m * 3s matrix\n\tMatrixXd temp = MatrixXd::Zero(m, s);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tVectorXd Ai = VectorXd::Zero(m);\n\t\tVectorXd Si = VectorXd::Zero(s);\n\t\tAi(index1) += 1;\n\t\tAi(index2) -= 1;\n\t\tSi(i) += 1;\n\t\ttemp += stiff * Ai * Si.transpose();\n\t}\n\n\t// kronecker product, J = kronecker(temp, I3)\n\tMatrix3d I3 = Matrix3d::Identity();\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j < s; j++)\n\t\t\tJ.block(i * 3, j * 3, 3, 3) = temp(i, j) * I3;\n}\n\nvoid Simulate::local() {\n\td = VectorXd::Ones(s * 3);\n\n\tfor (size_t i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tVector3d p1 = x.segment(3 * index1, 3);\n\t\tVector3d p2 = x.segment(3 * index2, 3);\n\n\t\td.segment(3 * i, 3) = l[i] * (p1 - p2) / (p1 - p2).norm();\n\t}\n\n\tcout << \"Local Step\" << endl;\n}\n\nvoid Simulate::global() {\n\tVectorXd RHS = K * (h * h * J * d + M * y + h * h * f_ext - (M + h * h * L) * b);\n\tVectorXd xf = LLT_.solve(RHS);\n\tx = K.transpose() * xf + b;\n\tcout << \"Global Step\" << endl;\n}\n\nvoid Simulate::getb() {\n\tb = x - K.transpose() * K * x;\n}\n\nvoid Simulate::UpdatePos() {\n\tfor (int i = 0; i < m * 3; i++)\n\t\tpositions[i / 3][i % 3] = x(i);\n}\n\nvoid Simulate::SimulateOnce() {\n\tif (!isfast) {\n\t\tbuildX();\n\t\tbuildV();\n\t} else {\n\t\t//update y, y = 2q_n - q_n-1\n\t\ty = 2 * x - x_pre;\n\t\tx_pre = x;\n\t\tsize_t step = 0;\n\t\twhile (step++ < iteration) {\n\t\t\tlocal();\n\t\t\tglobal();\n\t\t}\n\t}\n\tUpdatePos();\n\tcout << \"Simulate Once\" << endl;\n}\n\nbool Simulate::Run() {\n\tSimulateOnce();\n\treturn true;\n}\n\nvoid Simulate::buildX() {\n\tstd::vector<double> y(m * 3);\n\tfor (int i = 0; i < x.size(); i++)\n\t\ty[i] = x(i) + h * velocity[i / 3][i % 3] + h * h / mass[i] * f_ext[i];\n\txk = y;\n\tint i = 0;\n\tdo {\n\t\tCalForce();\n\t\tGetGX();\n\t\tCalDiff();\n\t\tCalGxM();\n\t\tEigen::MatrixXd t = G_inverse * gx_m;\n\t\txk_1.clear();\n\t\txk_1.resize(gx.size());\n\t\tfor (int i = 0; i < gx.size(); i++)\n\t\t\txk_1[i] = xk[i] - t(i, 0);\n\t\ti++;\n\t\tUpdateX();\n\t\txk.resize(3 * m);\n\t\tfor (int i = 0; i < m * 3; i++)\n\t\t\txk[i] = x(i);\n\t} while (!isConv() && i <= 10);\n}\n\nvoid Simulate::UpdateX() {\n\tEigen::MatrixXd xt;\n\txt.resize((xk_1.size()), 1);\n\tfor (int i = 0; i < xk_1.size(); i++)\n\t\txt(i, 0) = xk_1[i];\n\n\tEigen::MatrixXd t = K.transpose() * xt;\n\tfor (int i = 0; i < x.size(); i++)\n\t\tx(i) = t(i, 0) + b[i];\n}\n\nvoid Simulate::CalGxM() {\n\tgx_m.resize(gx.size(), 1);\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tgx_m(i, 0) = gx[i];\n}\n\nbool Simulate::isConv() {\n\tdouble delta = 0.01;\n\tstd::vector<double> zero(gx.size(), delta);\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tif (abs(gx[i]) > zero[i])\n\t\t\treturn false;\n\treturn true;\n}\n\nvoid Simulate::GetGX() {\n\tstd::vector<double> y(xk.size());\n\tgx.resize(xk.size());\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t\ty[i] = xk[i] + h * velocity[i / 3][i % 3] + h * h / mass[i] * f_ext[i];\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t\tgx[i] = mass[i] * (xk[i] - y[i]) - h * h * f_int[i];\n\n\tEigen::MatrixXd t(gx.size(), 1);\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tt(i, 0) = gx[i];\n\n\tt = K * t;\n\n\tgx.clear();\n\tgx.resize(t.rows());\n\tfor (int i = 0; i < gx.size(); i++)\n\t\tgx[i] = t(i, 0);\n\n\tEigen::MatrixXd xt;\n\txt.resize((xk.size()), 1);\n\n\tfor (int i = 0; i < xk.size(); i++)\n\t\txt(i, 0) = xk[i];\n\n\tt = K * xt;\n\txk.clear();\n\txk.resize(t.rows());\n\tfor (int i = 0; i < xk.size(); i++)\n\t\txk[i] = t(i, 0);\n}\n\nvoid Simulate::CalDiff() {\n\tstd::vector<Eigen::Triplet<double> > triple;\n\tEigen::MatrixXd I = MatrixXd::Identity(3, 3);\n\tfor (int i = 0; i < s; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tpointf3 v1 = pointf3(x(3 * index1 + 0), x(3 * index1 + 1), x(3 * index1 + 2));\n\t\tpointf3 v2 = pointf3(x(3 * index2 + 0), x(3 * index2 + 1), x(3 * index2 + 2));\n\t\tvecf3 r = v1 - v2;\n\t\tVector3d t;\n\t\tt << r[0], r[1], r[2];\n\n\t\tEigen::MatrixXd dif;\n\t\tdif.resize(3, 3);\n\t\tdif = stiff * (l[i] / r.norm() - 1) * I - stiff * l[i]\n\t\t\t/ ((r.norm()) * (r.norm()) * (r.norm())) * t * t.transpose();\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tfor (int k = 0; k < 3; k++) {\n\t\t\t\ttriple.push_back(Eigen::Triplet<double>(3 * index1 + j, 3 * index1 + k, -h * h * dif(j, k)));\n\t\t\t\ttriple.push_back(Eigen::Triplet<double>(3 * index2 + k, 3 * index2 + j, -h * h * dif(j, k)));\n\t\t\t}\n\t}\n\n\tfor (int i = 0; i < m * 3; i++)\n\t\ttriple.push_back(Eigen::Triplet<double>(i, i, mass[i]));\n\n\tEigen::MatrixXd diff_;\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> LU_;\n\n\tdiff.setZero();\n\tdiff.resize(m * 3, m * 3);\n\tdiff.setFromTriplets(triple.begin(), triple.end());\n\n\tdiff_ = K * diff * K.transpose();\n\tdiff = diff_.sparseView();\n\n\tI = MatrixXd::Identity(gx.size(), gx.size());\n\tLU_.analyzePattern(diff);\n\tLU_.factorize(diff);\n\tG_inverse = LU_.solve(I);\n}\n\nvoid Simulate::buildV() {\n\tfor (int i = 0; i < x.size(); i++)\n\t\tvelocity[i / 3][i % 3] = (x(i) - positions[i / 3][i % 3]) / h;\n}\n\nvoid Simulate::CalForce() {\n\tf_int.clear();\n\tf_int.resize(3 * positions.size());\n\tfor (int i = 0; i < edgelist.size() / 2; i++) {\n\t\tsize_t index1 = edgelist[2 * i];\n\t\tsize_t index2 = edgelist[2 * i + 1];\n\t\tpointf3 v1 = pointf3(x(3 * index1 + 0), x(3 * index1 + 1), x(3 * index1 + 2));\n\t\tpointf3 v2 = pointf3(x(3 * index2 + 0), x(3 * index2 + 1), x(3 * index2 + 2));\n\t\tvecf3 r = v1 - v2;\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tf_int[3 * index1 + j] += -stiff * (r.norm() - l[i]) * r[j] / r.norm();\n\t\t\tf_int[3 * index2 + j] += stiff * (r.norm() - l[i]) * r[j] / r.norm();\n\t\t}\n\t}\n}", "meta": {"hexsha": "650a5ced00052f2baf641bd8a2bb6161fb074fd9", "size": 8412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Simulate.cpp", "max_stars_repo_name": "L-JIN/USTC-CG", "max_stars_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_stars_repo_licenses": ["MIT"], "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/Simulate.cpp", "max_issues_repo_name": "L-JIN/USTC-CG", "max_issues_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_issues_repo_licenses": ["MIT"], "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/Simulate.cpp", "max_forks_repo_name": "L-JIN/USTC-CG", "max_forks_repo_head_hexsha": "d42bcaa1f91cf5ec15b3914585c85e854bc02377", "max_forks_repo_licenses": ["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.0465753425, "max_line_length": 97, "alphanum_fraction": 0.5376842606, "num_tokens": 3317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.6654105720171531, "lm_q1q2_score": 0.5515846409883903}}
{"text": "// Copyright 2004-5 The Trustees of Indiana University.\n// Copyright 2002 Brad King and Douglas Gregor\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n\n#ifndef BOOST_GRAPH_PAGE_RANK_HPP\n#define BOOST_GRAPH_PAGE_RANK_HPP\n\n#include <boost/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <vector>\n\nnamespace boost { namespace graph {\n\nstruct n_iterations\n{\n  explicit n_iterations(std::size_t n) : n(n) { }\n\n  template<typename RankMap, typename Graph>\n  bool \n  operator()(const RankMap&, const Graph&)\n  {\n    return n-- == 0;\n  }\n\n private:\n  std::size_t n;\n};\n\nnamespace detail {\n  template<typename Graph, typename RankMap, typename RankMap2>\n  void page_rank_step(const Graph& g, RankMap from_rank, RankMap2 to_rank,\n                      typename property_traits<RankMap>::value_type damping,\n                      incidence_graph_tag)\n  {\n    typedef typename property_traits<RankMap>::value_type rank_type;\n\n    // Set new rank maps \n    BGL_FORALL_VERTICES_T(v, g, Graph) put(to_rank, v, rank_type(1 - damping));\n\n    BGL_FORALL_VERTICES_T(u, g, Graph) {\n      rank_type u_rank_out = damping * get(from_rank, u) / out_degree(u, g);\n      BGL_FORALL_ADJ_T(u, v, g, Graph)\n        put(to_rank, v, get(to_rank, v) + u_rank_out);\n    }\n  }\n\n  template<typename Graph, typename RankMap, typename RankMap2>\n  void page_rank_step(const Graph& g, RankMap from_rank, RankMap2 to_rank,\n                      typename property_traits<RankMap>::value_type damping,\n                      bidirectional_graph_tag)\n  {\n    typedef typename property_traits<RankMap>::value_type damping_type;\n    BGL_FORALL_VERTICES_T(v, g, Graph) {\n      typename property_traits<RankMap>::value_type rank(0);\n      BGL_FORALL_INEDGES_T(v, e, g, Graph)\n        rank += get(from_rank, source(e, g)) / out_degree(source(e, g), g);\n      put(to_rank, v, (damping_type(1) - damping) + damping * rank);\n    }\n  }\n} // end namespace detail\n\ntemplate<typename Graph, typename RankMap, typename Done, typename RankMap2>\nvoid\npage_rank(const Graph& g, RankMap rank_map, Done done, \n          typename property_traits<RankMap>::value_type damping,\n          typename graph_traits<Graph>::vertices_size_type n,\n          RankMap2 rank_map2)\n{\n  typedef typename property_traits<RankMap>::value_type rank_type;\n\n  rank_type initial_rank = rank_type(rank_type(1) / n);\n  BGL_FORALL_VERTICES_T(v, g, Graph) put(rank_map, v, initial_rank);\n\n  bool to_map_2 = true;\n  while ((to_map_2 && !done(rank_map, g)) ||\n         (!to_map_2 && !done(rank_map2, g))) {\n    typedef typename graph_traits<Graph>::traversal_category category;\n\n    if (to_map_2) {\n      detail::page_rank_step(g, rank_map, rank_map2, damping, category());\n    } else {\n      detail::page_rank_step(g, rank_map2, rank_map, damping, category());\n    }\n    to_map_2 = !to_map_2;\n  }\n\n  if (!to_map_2) {\n    BGL_FORALL_VERTICES_T(v, g, Graph) put(rank_map, v, get(rank_map2, v));\n  }\n}\n\ntemplate<typename Graph, typename RankMap, typename Done>\nvoid\npage_rank(const Graph& g, RankMap rank_map, Done done, \n          typename property_traits<RankMap>::value_type damping,\n          typename graph_traits<Graph>::vertices_size_type n)\n{\n  typedef typename property_traits<RankMap>::value_type rank_type;\n\n  std::vector<rank_type> ranks2(num_vertices(g));\n  page_rank(g, rank_map, done, damping, n,\n            make_iterator_property_map(ranks2.begin(), get(vertex_index, g)));\n}\n\ntemplate<typename Graph, typename RankMap, typename Done>\ninline void\npage_rank(const Graph& g, RankMap rank_map, Done done, \n          typename property_traits<RankMap>::value_type damping = 0.85)\n{\n  page_rank(g, rank_map, done, damping, num_vertices(g));\n}\n\ntemplate<typename Graph, typename RankMap>\ninline void\npage_rank(const Graph& g, RankMap rank_map)\n{\n  page_rank(g, rank_map, n_iterations(20));\n}\n\n// TBD: this could be _much_ more efficient, using a queue to store\n// the vertices that should be reprocessed and keeping track of which\n// vertices are in the queue with a property map. Baah, this only\n// applies when we have a bidirectional graph.\ntemplate<typename MutableGraph>\nvoid\nremove_dangling_links(MutableGraph& g)\n{\n  typename graph_traits<MutableGraph>::vertices_size_type old_n;\n  do {\n    old_n = num_vertices(g);\n\n    typename graph_traits<MutableGraph>::vertex_iterator vi, vi_end;\n    for (tie(vi, vi_end) = vertices(g); vi != vi_end; /* in loop */) {\n      typename graph_traits<MutableGraph>::vertex_descriptor v = *vi++;\n      if (out_degree(v, g) == 0) {\n        clear_vertex(v, g);\n        remove_vertex(v, g);\n      }\n    }\n  } while (num_vertices(g) < old_n);\n}\n\n} } // end namespace boost::graph\n\n#endif // BOOST_GRAPH_PAGE_RANK_HPP\n", "meta": {"hexsha": "78ae766d283761df34ab85fcff497116d379d81a", "size": 4971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/page_rank.hpp", "max_stars_repo_name": "schinmayee/nimbus", "max_stars_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T19:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-10T02:53:56.000Z", "max_issues_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/page_rank.hpp", "max_issues_repo_name": "schinmayee/nimbus", "max_issues_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/physbam/physbam-lib/External_Libraries/Archives/boost/boost/graph/page_rank.hpp", "max_forks_repo_name": "schinmayee/nimbus", "max_forks_repo_head_hexsha": "170cd15e24a7a88243a6ea80aabadc0fc0e6e177", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T02:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-31T00:12:01.000Z", "avg_line_length": 32.2792207792, "max_line_length": 79, "alphanum_fraction": 0.7008650171, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.551565466046533}}
{"text": "#ifndef TVMTL_MANIFOLD_EUC_HPP\n#define TVMTL_MANIFOLD_EUC_HPP\n\n#include <cmath>\n#include <Eigen/Core>\n\n#include \"enumerators.hpp\"\n\nnamespace tvmtl {\n\n// Specialization EUCLIDIAN\ntemplate < int N >\nstruct Manifold< EUCLIDIAN, N > {\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\n\n\t// Scalar type of manifold\n\ttypedef double scalar_type;\n\ttypedef double dist_type;\n\ttypedef std::vector<double>\t\t\t\t\t\tweight_list; \n\t\n\n\t// Value Typedef\n\ttypedef Eigen::Matrix< scalar_type, N, 1>   value_type;\n\ttypedef value_type&\t\t\t    ref_type;\n\ttypedef const value_type&\t\t    cref_type;\n\ttypedef std::vector<value_type, Eigen::aligned_allocator<value_type> >\tvalue_list; \n\n\t\n\t// Tangent space typedefs\n\ttypedef Eigen::Matrix < scalar_type, N, N> tm_base_type;\n\ttypedef tm_base_type& tm_base_ref_type;\n\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, N>     deriv2_type;\n\ttypedef deriv2_type&\t\t\t     deriv2_ref_type;\n\ttypedef\tEigen::Matrix<scalar_type, N, N>     restricted_deriv2_type;\n\n\n\t// Manifold distance functions (for IRLS)\n\tinline static dist_type dist_squared(cref_type x, cref_type y);\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\n\t// Manifold exponentials und logarithms ( for Proximal point)\n\ttemplate <typename DerivedX, typename DerivedY, typename DerivedZ>\n\tinline static void exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedZ>& 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\t\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\t\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\n\n\t// Projection to manifold\n\tinline static void projector(ref_type x);\t\n\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/*-----IMPLEMENTATION EUCLIDIAN----------*/\n\n// Static constants, Outside definition to avoid linker error\n\ntemplate <int N>\nconst MANIFOLD_TYPE Manifold < EUCLIDIAN, N>::MyType = EUCLIDIAN; \n\ntemplate <int N>\nconst int Manifold < EUCLIDIAN, N>::manifold_dim = N; \n\ntemplate <int N>\nconst int Manifold < EUCLIDIAN, N>::value_dim = N; \n\ntemplate <int N>\nconst bool Manifold < EUCLIDIAN, N>::non_isometric_embedding = false; \n\n\n\n// Squared Euclidian distance function\ntemplate <int N>\ninline typename Manifold < EUCLIDIAN, N>::dist_type Manifold < EUCLIDIAN, N>::dist_squared( cref_type x, cref_type y ){\n    //value_type v = x-y;\n    return (x-y).squaredNorm();\n}\n\n\n\n// Derivative of Squared Euclidian distance w.r.t. first argument\ntemplate <int N>\ninline void Manifold < EUCLIDIAN, N>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result =  2 * (x-y); \n}\n// Derivative of Squared Euclidian distance w.r.t. second argument\ntemplate <int N>\ninline void Manifold < EUCLIDIAN, N>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result = 2 * (y-x); \n}\n\n\n\n\n// Second Derivative of Squared Euclidian distance w.r.t first argument\ntemplate <int N>\ninline void Manifold < EUCLIDIAN, N>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    result = 2 * deriv2_type::Identity();\n}\n// Second Derivative of Squared Euclidian distance w.r.t first and second argument\ntemplate <int N>\ninline void Manifold < EUCLIDIAN, N>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    result = -2 * deriv2_type::Identity();\n}\n// Second Derivative of Squared Euclidian distance w.r.t second argument\ntemplate <int N>\ninline void Manifold < EUCLIDIAN, N>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    result = 2 * deriv2_type::Identity();\n}\n\n\n\n// Exponential and Logarithm Map\ntemplate <int N>\ntemplate <typename DerivedX, typename DerivedY, typename DerivedZ>\ninline void Manifold <EUCLIDIAN, N>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedZ>& result){\n    result=x+y;\n}\n\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::log(cref_type x, cref_type y, ref_type result){\n    result = y-x;\n}\n\n// Tangent Plane restriction\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    result = tm_base_type::Identity();\n}\n\n// Projector, cut off values outside [0,1] (if noise is added)\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::projector(ref_type x){\n    for(int i=0; i<N; ++i){\n\tif(x[i] > 1.0) x[i] = 1.0;\n\tif(x[i] < 0) x[i] = 0;\n    }\n}\n\n// Convex combination along geodesic\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::convex_combination(cref_type x, cref_type y, double t, ref_type result){\n    result = x + t * (y-x);\n}\n\n// Karcher mean implementations\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::karcher_mean(ref_type x, const value_list& v, double tol, int maxit){\n    value_type L = value_type::Zero();\n    for(int i = 0; i < v.size(); ++i)\n\tL += v[i];\n    x = L / v.size();\n}\n\ntemplate <int N>\ninline void Manifold <EUCLIDIAN, N>::weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol, int maxit){\n    value_type L = value_type::Zero();\n    for(int i = 0; i < v.size(); ++i)\n\tL += w[i]*v[i];\n    x = L / v.size();\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<EUCLIDIAN, N>::karcher_mean(V& x, const Args&... args){\n    int numArgs = sizeof...(args);\n    variadic_karcher_mean_gradient(x, args...);\n    x /= numArgs;\n}\n\ntemplate <int N>\ntemplate <typename V>\ninline void Manifold<EUCLIDIAN, N>::variadic_karcher_mean_gradient(V& x, const V& y){\n    x = y;\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<EUCLIDIAN, N>::variadic_karcher_mean_gradient(V& x, const V& y1, const Args& ... args){\n    V temp = x;\n    variadic_karcher_mean_gradient(temp, args...);\n    x = y1 + temp;\n}\n\n} // end namespace tvmtl\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "967d78f0c2214c9bf87172fcaab9ca8f0aacb8b3", "size": 7366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/manifold_euc.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_euc.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_euc.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": 31.3446808511, "max_line_length": 154, "alphanum_fraction": 0.7299755634, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.6825737473266734, "lm_q1q2_score": 0.5515654597365766}}
{"text": "#include <fstream>\n#include <iostream>\n#include <unordered_set>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/graphviz.hpp>\n\nclass ShortestPathHeuristic {\n public:\n  ShortestPathHeuristic(size_t dimx, size_t dimy,\n                        const std::unordered_set<Location>& obstacles)\n      : m_shortestDistance(nullptr), m_dimx(dimx), m_dimy(dimy) {\n    searchGraph_t searchGraph;\n\n    // add vertices\n    for (size_t x = 0; x < dimx; ++x) {\n      for (size_t y = 0; y < dimy; ++y) {\n        boost::add_vertex(searchGraph);\n      }\n    }\n\n    // add edges\n    for (size_t x = 0; x < dimx; ++x) {\n      for (size_t y = 0; y < dimy; ++y) {\n        Location l(x, y);\n        if (obstacles.find(l) == obstacles.end()) {\n          Location right(x + 1, y);\n          if (x < dimx - 1 && obstacles.find(right) == obstacles.end()) {\n            auto e =\n                boost::add_edge(locToVert(l), locToVert(right), searchGraph);\n            searchGraph[e.first].weight = 1;\n          }\n          Location below(x, y + 1);\n          if (y < dimy - 1 && obstacles.find(below) == obstacles.end()) {\n            auto e =\n                boost::add_edge(locToVert(l), locToVert(below), searchGraph);\n            searchGraph[e.first].weight = 1;\n          }\n        }\n      }\n    }\n\n    writeDotFile(searchGraph, \"searchGraph.dot\");\n\n    m_shortestDistance = new distanceMatrix_t(boost::num_vertices(searchGraph));\n    distanceMatrixMap_t distanceMap(*m_shortestDistance, searchGraph);\n    // The following generates a clang-tidy error, see\n    // https://svn.boost.org/trac10/ticket/10830\n    boost::floyd_warshall_all_pairs_shortest_paths(\n        searchGraph, distanceMap,\n        boost::weight_map(boost::get(&Edge::weight, searchGraph)));\n  }\n\n  ~ShortestPathHeuristic() { delete m_shortestDistance; }\n\n  int getValue(const Location& a, const Location& b) {\n    vertex_t idx1 = locToVert(a);\n    vertex_t idx2 = locToVert(b);\n    return (*m_shortestDistance)[idx1][idx2];\n  }\n\n private:\n  size_t locToVert(const Location& l) const { return l.x + m_dimx * l.y; }\n\n  Location idxToLoc(size_t idx) {\n    int x = idx % m_dimx;\n    int y = idx / m_dimx;\n    return Location(x, y);\n  }\n\n private:\n  typedef boost::adjacency_list_traits<boost::vecS, boost::vecS,\n                                       boost::undirectedS>\n      searchGraphTraits_t;\n  typedef searchGraphTraits_t::vertex_descriptor vertex_t;\n  typedef searchGraphTraits_t::edge_descriptor edge_t;\n\n  struct Vertex {};\n\n  struct Edge {\n    int weight;\n  };\n\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n                                Vertex, Edge>\n      searchGraph_t;\n  typedef boost::exterior_vertex_property<searchGraph_t, int>\n      distanceProperty_t;\n  typedef distanceProperty_t::matrix_type distanceMatrix_t;\n  typedef distanceProperty_t::matrix_map_type distanceMatrixMap_t;\n\n  class VertexDotWriter {\n   public:\n    explicit VertexDotWriter(const searchGraph_t& graph, size_t dimx)\n        : m_graph(graph), m_dimx(dimx) {}\n\n    void operator()(std::ostream& out, const vertex_t& v) const {\n      static const float DX = 100;\n      static const float DY = 100;\n      out << \"[label=\\\"\";\n      int x = v % m_dimx;\n      int y = v / m_dimx;\n      out << \"\\\" pos=\\\"\" << x * DX << \",\" << y * DY << \"!\\\"]\";\n    }\n\n   private:\n    const searchGraph_t& m_graph;\n    size_t m_dimx;\n  };\n\n  class EdgeDotWriter {\n   public:\n    explicit EdgeDotWriter(const searchGraph_t& graph) : m_graph(graph) {}\n\n    void operator()(std::ostream& out, const edge_t& e) const {\n      out << \"[label=\\\"\" << m_graph[e].weight << \"\\\"]\";\n    }\n\n   private:\n    const searchGraph_t& m_graph;\n  };\n\n private:\n  void writeDotFile(const searchGraph_t& graph, const std::string& fileName) {\n    VertexDotWriter vw(graph, m_dimx);\n    EdgeDotWriter ew(graph);\n    std::ofstream dotFile(fileName);\n    boost::write_graphviz(dotFile, graph, vw, ew);\n  }\n\n private:\n  distanceMatrix_t* m_shortestDistance;\n  size_t m_dimx;\n  size_t m_dimy;\n};\n", "meta": {"hexsha": "a1a21bb9bcb4ac12aeb1988afc7cae9ef8ccefd5", "size": 4120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/shortest_path_heuristic.hpp", "max_stars_repo_name": "VSumanth99/libMultiRobotPlanning", "max_stars_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 350.0, "max_stars_repo_stars_event_min_datetime": "2018-07-23T12:33:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:28:36.000Z", "max_issues_repo_path": "example/shortest_path_heuristic.hpp", "max_issues_repo_name": "VSumanth99/libMultiRobotPlanning", "max_issues_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-08-08T19:57:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T18:16:41.000Z", "max_forks_repo_path": "example/shortest_path_heuristic.hpp", "max_forks_repo_name": "VSumanth99/libMultiRobotPlanning", "max_forks_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 147.0, "max_forks_repo_forks_event_min_datetime": "2018-07-23T12:53:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:21:03.000Z", "avg_line_length": 29.8550724638, "max_line_length": 80, "alphanum_fraction": 0.6291262136, "num_tokens": 1081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.6584174938590245, "lm_q1q2_score": 0.5515036263886207}}
{"text": "/// @file\n/// @copyright The code is licensed under the BSD License\n///            <http://opensource.org/licenses/BSD-2-Clause>,\n///            Copyright (c) 2013-2015 Alexandre Hamez.\n/// @author Alexandre Hamez\n\n#pragma once\n\n#include <string>\n#include <set>\n#include <unordered_map>\n#include <vector>\n\n#include <boost/variant.hpp>\n\n#include \"support/pn/types.hh\"\n#include \"support/properties/formulae.hh\"\n\nnamespace pnmc { namespace mc { namespace classic {\n\n/*------------------------------------------------------------------------------------------------*/\n\nstruct integer_constant\n{\n  int value;\n};\nstruct integer_sum;\nstruct integer_product;\nstruct integer_difference;\nstruct integer_division;\nstruct integer_tokens\n{\n  std::size_t pos;\n};\n\nusing integer_ast = boost::variant< integer_constant\n                                  , boost::recursive_wrapper<integer_sum>\n                                  , boost::recursive_wrapper<integer_product>\n                                  , boost::recursive_wrapper<integer_difference>\n                                  , boost::recursive_wrapper<integer_division>\n                                  , integer_tokens>;\n\nstruct integer_sum\n{\n  std::vector<integer_ast> expressions;\n};\n\nstruct integer_product\n{\n  std::vector<integer_ast> expressions;\n};\n\nstruct integer_difference\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_division\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\nstruct invariant;\nstruct impossibility;\nstruct possibility;\n\nstruct true_ {};\nstruct false_ {};\nstruct negation;\nstruct conjunction;\nstruct disjunction;\nstruct exclusive_disjonction;\nstruct implication;\nstruct equivalence;\n\nstruct integer_eq;\nstruct integer_ne;\nstruct integer_lt;\nstruct integer_le;\nstruct integer_gt;\nstruct integer_ge;\n\nusing boolean_ast = boost::variant< boost::recursive_wrapper<invariant>\n                                  , boost::recursive_wrapper<impossibility>\n                                  , boost::recursive_wrapper<possibility>\n                                  , true_\n                                  , false_\n                                  , boost::recursive_wrapper<negation>\n                                  , boost::recursive_wrapper<conjunction>\n                                  , boost::recursive_wrapper<disjunction>\n                                  , boost::recursive_wrapper<exclusive_disjonction>\n                                  , boost::recursive_wrapper<implication>\n                                  , boost::recursive_wrapper<equivalence>\n                                  , boost::recursive_wrapper<integer_eq>\n                                  , boost::recursive_wrapper<integer_ne>\n                                  , boost::recursive_wrapper<integer_lt>\n                                  , boost::recursive_wrapper<integer_le>\n                                  , boost::recursive_wrapper<integer_gt>\n                                  , boost::recursive_wrapper<integer_ge>>;\n\nstruct invariant\n{\n  boolean_ast expression;\n};\n\nstruct impossibility\n{\n  boolean_ast expression;\n};\n\nstruct possibility\n{\n  boolean_ast expression;\n};\n\nstruct negation\n{\n  boolean_ast expression;\n};\n\nstruct conjunction\n{\n  std::vector<boolean_ast> expressions;\n};\n\nstruct disjunction\n{\n  std::vector<boolean_ast> expressions;\n};\n\nstruct exclusive_disjonction\n{\n  std::vector<boolean_ast> expressions;\n};\n\nstruct implication\n{\n  boolean_ast lhs_expression;\n  boolean_ast rhs_expression;\n};\n\nstruct equivalence\n{\n  boolean_ast lhs_expression;\n  boolean_ast rhs_expression;\n};\n\nstruct integer_eq\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_ne\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_lt\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_le\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_gt\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\nstruct integer_ge\n{\n  integer_ast lhs_expression;\n  integer_ast rhs_expression;\n};\n\n/*------------------------------------------------------------------------------------------------*/\n\ninteger_ast\nmake_ast( const properties::integer_expression&\n        , const std::unordered_map<std::string, pn::valuation_type>& bounds);\n\n/*------------------------------------------------------------------------------------------------*/\n\nboolean_ast\nmake_ast( const properties::boolean_expression&, bool has_deadlock\n        , const std::set<std::string>& dead_transitions\n        , const std::unordered_map<std::string, pn::valuation_type>& bounds);\n\n/*------------------------------------------------------------------------------------------------*/\n\n}}} // namespace pnmc::mc::classic\n", "meta": {"hexsha": "341b438917b24a94fc4dbd2b7c75c2554ebc326f", "size": 4899, "ext": "hh", "lang": "C++", "max_stars_repo_path": "pnmc/mc/classic/reachability_ast.hh", "max_stars_repo_name": "ahamez/pnmc", "max_stars_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-02-05T20:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T01:20:24.000Z", "max_issues_repo_path": "pnmc/mc/classic/reachability_ast.hh", "max_issues_repo_name": "ahamez/pnmc", "max_issues_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "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": "pnmc/mc/classic/reachability_ast.hh", "max_forks_repo_name": "ahamez/pnmc", "max_forks_repo_head_hexsha": "cee5f2e01edc2130278ebfc13f0f859230d65680", "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.0147058824, "max_line_length": 100, "alphanum_fraction": 0.581139008, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5514662967688703}}
{"text": "#ifndef KALMAN_FILTER_MULTIARM_BANDIT_HPP\n#define KALMAN_FILTER_MULTIARM_BANDIT_HPP\n\n#include <assert.h>\n#include <vector>\n#include <random>\n#include <utility>\n\n#include <Eigen/Eigenvalues>\n\n#include <arc_utilities/arc_helpers.hpp>\n#include <arc_utilities/pretty_print.hpp>\n#include <arc_utilities/eigen_helpers.hpp>\n\nnamespace smmap\n{\n    template <typename Generator = std::mt19937_64>\n    class KalmanFilterMANB\n    {\n        public:\n            KalmanFilterMANB(\n                    const Eigen::VectorXd& prior_mean = Eigen::VectorXd::Zero(1),\n                    const Eigen::VectorXd& prior_var = Eigen::VectorXd::Ones(1))\n                : num_bandits_(prior_mean.rows())\n                , arm_mean_(prior_mean)\n                , arm_var_(prior_var)\n            {\n                assert(arm_mean_.cols() == arm_var_.cols());\n            }\n\n            /**\n             * @brief selectArmToPull Perform Thompson sampling on the bandits,\n             *                        and select the bandit with the largest sample.\n             * @param generator\n             * @return\n             */\n            ssize_t selectArmToPull(Generator& generator)\n            {\n                // Sample from the current distribuition\n                std::normal_distribution<double> normal_dist(0.0, 1.0);\n\n                ssize_t best_arm = -1;\n                double best_sample = -std::numeric_limits<double>::infinity();\n                for (ssize_t arm_ind = 0; arm_ind < num_bandits_; arm_ind++)\n                {\n                    const double sample = std::sqrt(arm_var_(arm_ind)) * normal_dist(generator) + arm_mean_(arm_ind);\n\n                    if (sample > best_sample)\n                    {\n                        best_arm = arm_ind;\n                        best_sample = sample;\n                    }\n                }\n\n                assert(best_arm >= 0);\n                return best_arm;\n            }\n\n            bool generateAllModelActions() const\n            {\n                return false;\n            }\n\n            /**\n             * @brief updateArms\n             * @param transition_variance\n             * @param arm_pulled\n             * @param observed_reward\n             * @param observation_variance\n             */\n            void updateArms(\n                    const Eigen::VectorXd& transition_variance,\n                    const ssize_t arm_pulled,\n                    const double observed_reward,\n                    const double observation_variance)\n            {\n                for (ssize_t arm_ind = 0; arm_ind < num_bandits_; arm_ind++)\n                {\n                    if (arm_ind != arm_pulled)\n                    {\n                        arm_var_(arm_ind) += transition_variance(arm_ind);\n                    }\n                    else\n                    {\n                        arm_mean_(arm_ind) = ((arm_var_(arm_ind) + transition_variance(arm_ind)) * observed_reward + observation_variance * arm_mean_(arm_ind))\n                                            / (arm_var_(arm_ind) + transition_variance(arm_ind) + observation_variance);\n\n                        arm_var_(arm_ind) = (arm_var_(arm_ind) + transition_variance(arm_ind)) * observation_variance\n                                           / (arm_var_(arm_ind) + transition_variance(arm_ind) + observation_variance);\n                    }\n                }\n            }\n\n            const Eigen::VectorXd& getMean() const\n            {\n                return arm_mean_;\n            }\n\n            Eigen::VectorXd getMean()\n            {\n                return arm_mean_;\n            }\n\n            const Eigen::VectorXd& getVariance() const\n            {\n                return arm_var_;\n            }\n\n            Eigen::VectorXd getVariance()\n            {\n                return arm_var_;\n            }\n\n        private:\n            ssize_t num_bandits_;\n\n            Eigen::VectorXd arm_mean_;\n            Eigen::VectorXd arm_var_;\n    };\n\n    template<typename Generator = std::mt19937_64>\n    class KalmanFilterMANDB\n    {\n        public:\n            KalmanFilterMANDB(\n                    const Eigen::VectorXd& prior_mean = Eigen::VectorXd::Ones(1),\n                    const Eigen::MatrixXd& prior_covar = Eigen::MatrixXd::Identity(1, 1))\n                : arm_mean_(prior_mean)\n                , arm_covar_(prior_covar)\n            {\n                assert(arm_covar_.rows() == arm_covar_.cols());\n                assert(arm_covar_.rows() == arm_mean_.rows());\n            }\n\n            /**\n             * @brief selectArmToPull Perform Thompson sampling on the bandits,\n             *                        and select the bandit with the largest sample.\n             * @param generator\n             * @return\n             */\n            ssize_t selectArmToPull(Generator& generator)\n            {\n                // Sample from the current distribuition\n                arc_helpers::MultivariteGaussianDistribution distribution(arm_mean_, arm_covar_);\n                const Eigen::VectorXd sample = distribution(generator);\n\n                // Find the arm with the highest sample\n                ssize_t best_arm = -1;\n                sample.maxCoeff(&best_arm);\n\n                return best_arm;\n            }\n\n            bool generateAllModelActions() const\n            {\n                return true;\n            }\n\n            /**\n             * @brief updateArms\n             * @param transition_covariance\n             * @param arm_pulled\n             * @param obs_reward\n             * @param obs_var\n             */\n            void updateArms(\n                    const Eigen::MatrixXd& transition_covariance,\n                    const Eigen::MatrixXd& observation_matrix,\n                    const Eigen::VectorXd& observed_reward,\n                    const Eigen::MatrixXd& observation_covariance)\n            {\n                #pragma GCC diagnostic push\n                #pragma GCC diagnostic ignored \"-Wconversion\"\n                const Eigen::MatrixXd& C = observation_matrix;\n\n                // Kalman predict\n                const Eigen::VectorXd& predicted_mean = arm_mean_;                      // No change to mean\n                const auto predicted_covariance = arm_covar_ + transition_covariance;   // Add process noise\n\n                // Kalman update - symbols from wikipedia article\n                const auto innovation = observed_reward - C * predicted_mean;                                            // tilde y_k\n                const auto innovation_covariance = C * predicted_covariance.selfadjointView<Eigen::Lower>() * C.transpose() + observation_covariance;    // S_k\n                const auto kalman_gain = predicted_covariance.selfadjointView<Eigen::Lower>() * C.transpose() * innovation_covariance.inverse();         // K_k\n\n                arm_mean_ = predicted_mean + kalman_gain * innovation;                                                              // hat x_k|k\n                arm_covar_ = predicted_covariance - kalman_gain * C * predicted_covariance.selfadjointView<Eigen::Lower>();         // P_k|k\n                #pragma GCC diagnostic pop\n\n                // Numerical problems fixing\n                arm_covar_ = ((arm_covar_ + arm_covar_.transpose()) * 0.5).selfadjointView<Eigen::Lower>();\n\n                assert(!(arm_mean_.unaryExpr([] (const double &val) { return std::isnan(val); })).any() && \"NaN Found in arm_mean_ in kalman banidt!\");\n                assert(!(arm_mean_.unaryExpr([] (const double &val) { return std::isinf(val); })).any() && \"Inf Found in arm_mean_ in kalman banidt!\");\n                assert(!(arm_covar_.unaryExpr([] (const double &val) { return std::isinf(val); })).any() && \"NaN Found in arm_covar_ in kalman bandit!\");\n                assert(!(arm_covar_.unaryExpr([] (const double &val) { return std::isinf(val); })).any() && \"Inf Found in arm_covar_ in kalman bandit!\");\n            }\n\n            const Eigen::VectorXd& getMean() const\n            {\n                return arm_mean_;\n            }\n\n            Eigen::VectorXd getMean()\n            {\n                return arm_mean_;\n            }\n\n            const Eigen::MatrixXd& getCovariance() const\n            {\n                return arm_covar_;\n            }\n\n            Eigen::MatrixXd getCovariance()\n            {\n                return arm_covar_;\n            }\n\n        private:\n            Eigen::VectorXd arm_mean_;\n            Eigen::MatrixXd arm_covar_;\n    };\n}\n\n#endif // KALMAN_FILTER_MULTIARM_BANDIT_HPP\n", "meta": {"hexsha": "326fd423e4570839a44c35d311ba0d82b66e176a", "size": 8505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "smmap/include/smmap/kalman_filter_multiarm_bandit.hpp", "max_stars_repo_name": "UM-ARM-Lab/mab_ms", "max_stars_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T12:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:43:27.000Z", "max_issues_repo_path": "smmap/include/smmap/kalman_filter_multiarm_bandit.hpp", "max_issues_repo_name": "UM-ARM-Lab/mab_ms", "max_issues_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smmap/include/smmap/kalman_filter_multiarm_bandit.hpp", "max_forks_repo_name": "UM-ARM-Lab/mab_ms", "max_forks_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T03:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:12:23.000Z", "avg_line_length": 37.8, "max_line_length": 159, "alphanum_fraction": 0.5115814227, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.5514662964408867}}
{"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_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TENPOWER_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/ten.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/any.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/is_ltz.hpp>\n#include <boost/simd/function/simd/is_odd.hpp>\n#include <boost/simd/function/simd/multiplies.hpp>\n#include <boost/simd/function/simd/rec.hpp>\n#include <boost/simd/function/simd/shift_right.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/mpl/equal_to.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD(tenpower_\n                             , (typename A0, typename X)\n                             , bd::cpu_\n                             , bs::pack_<bd::int_<A0>, X>\n                             )\n   {\n      using result = bd::as_floating_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        result res = One<result>();\n        result base = Ten<result>();\n        A0 exp = bs::abs(a0);\n        while(any(exp))\n        {\n          //       res *= if_else(is_odd(exp), base, One<result>()); TO DO\n          res =  res * if_else(is_odd(exp), base, One<result>());\n          //  exp >>= 1; TODO\n          exp =  shift_right(exp, 1);\n          base = sqr(base);\n        }\n        return if_else(is_ltz(a0), bs::rec(res), res);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD(tenpower_\n                             , (typename A0, typename X)\n                             , bd::cpu_\n                             , bs::pack_<bd::uint_<A0>, X>\n                             )\n   {\n      using result = bd::as_floating_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        result res = One<result>();\n        result base = Ten<result>();\n        A0 exp = a0;\n        while(any(exp))\n        {\n          res = res*if_else(is_odd(exp), base, One<result>()); // TODO\n//          res *= if_else(is_odd(exp), base, One<result>());\n          //  exp >>= 1; TODO\n          exp =  shift_right(exp, 1);\n          base = sqr(base);\n        }\n        return res;\n      }\n   };\n\n} } }\n\n\n#endif\n\n", "meta": {"hexsha": "3b0c92508fd5db3bb73f0d1f40df45b722de90da", "size": 2978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/tenpower.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/tenpower.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/tenpower.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4606741573, "max_line_length": 100, "alphanum_fraction": 0.5466756212, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.5514662909989416}}
{"text": "#ifndef MATH_DUAL_HPP\n#define MATH_DUAL_HPP\n\n#ifndef _E_of\n#define _E_of(X) X \"E\"\n//#define _E_of(X) X \"\\u0190\"\n#endif\n\n#include <boost/operators.hpp>\n\nnamespace Math {\n\ttemplate<typename>\n\t\tstruct quat;\n\n\ttemplate<typename R = float>\n\tstruct dual: public boost::operators<dual<R>> {\n\t\tquat<R> u, v;\n\n\t\t/** Additive inverse */\n\t\tdual<R> operator-(void) const;\n\t\t/** Multiplicative inverse */\n\t\tdual<R> operator!(void) const;\n\t\t/** Distributes conjugation to members */\n\t\tdual<R> operator~(void) const;\n\t\t/** Cast operator, as Euclidean norm */\n\t\texplicit operator R(void) const;\n\t\t/** Squared Euclidean norm */\n\t\tR operator()(void) const;\n\t\t/** Distributes equality test */\n\t\tbool operator==(dual<R> const &rhs) const;\n\t\t/** Apply (lhs * rhs * ~lhs) */\n\t\tdual<R> operator()(quat<R> const &rhs) const;\n\t\tdual<R> operator()(dual<R> const &rhs) const;\n\n\t\tdual<R>& operator=(quat<R> const &rhs) {\n\t\t\tu = rhs; v = 0;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator=(dual<R> const &rhs) = default;\n\t\tdual<R>& operator+=(R const &rhs) {\n\t\t\tu.w += rhs;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator+=(dual<R> const &rhs) {\n\t\t\tu += rhs.u;\n\t\t\tv += rhs.v;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator-=(dual<R> const &rhs) {\n\t\t\tu -= rhs.u;\n\t\t\tv -= rhs.v;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator*=(dual<R> const &rhs) {\n\t\t\tauto const& p = rhs.u, q = rhs.v;\n \t\t\tauto const r = u, s = v;\n\t\t\treturn *this = {\n\t\t\t\tr.w*p.w - r.x*p.x - r.y*p.y - r.z*p.z,\n\t\t\t\tr.w*p.x + r.x*p.w + r.y*p.z - r.z*p.y,\n\t\t\t\tr.w*p.y - r.x*p.z + r.y*p.w + r.z*p.x,\n\t\t\t\tr.w*p.z + r.x*p.y - r.y*p.x + r.z*p.w,\n\t\t\t\ts.w*p.w - s.x*p.x - s.y*p.y - s.z*p.z\n\t\t\t\t\t+ r.w*q.w - r.x*q.x - r.y*q.y - r.z*q.z,\n\t\t\t\ts.x*p.w + s.w*p.x - s.z*p.y + s.y*p.z\n\t\t\t\t\t+ r.x*q.w + r.w*q.x - r.z*q.y + r.y*q.z,\n\t\t\t\ts.y*p.w + s.z*p.x + s.w*p.y - s.x*p.z\n\t\t\t\t\t+ r.y*q.w + r.z*q.x + r.w*q.y - r.x*q.z,\n\t\t\t\ts.z*p.w - s.y*p.x + s.x*p.y + s.w*p.z\n\t\t\t\t\t+ r.z*q.w - r.y*q.x + r.x*q.y + r.w*q.z\n\t\t\t};\n\t\t}\n\t\tdual<R>& operator*=(quat<R> const &rhs) {\n\t\t\tu *= rhs;\n\t\t\tv *= rhs;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator*=(R const &rhs) {\n\t\t\tu *= rhs;\n\t\t\tv *= rhs;\n\t\t\treturn *this;\n\t\t}\n\t\tdual<R>& operator/=(R const &rhs) {\n\t\t\tu /= rhs;\n\t\t\tv /= rhs;\n\t\t\treturn *this;\n\t\t}\n\n\t\tdual(void) = default;\n\t\tdual(dual<R> const&) = default;\n\t\tdual(dual<R> &&) = default;\n\t\tdual(R uw, R ux = 0, R uy = 0, R uz = 0,\n\t\t\t\tR vw = 0, R vx = 0, R vy = 0, R vz = 0):\n\t\t\tu(uw, ux, uy, uz), v(vw, vx, vy, vz) {}\n\t\tdual(const quat<R> &u, const quat<R> v = {0}):\n\t\t\tu(u), v(v) {}\n\t};\n\t\n\ttemplate<typename R>\n\tdual<R> dual<R>::operator-(void) const {\n\t\treturn {-u, -v};\n\t}\n\ttemplate<typename R>\n\tdual<R> dual<R>::operator!(void) const {\n\t\tdual<R> conj = ~*this;\n\t\treturn conj/conj();\n\t}\n\ttemplate<typename R>\n\tdual<R> dual<R>::operator~(void) const {\n\t\treturn {{u.w,-u.x,-u.y,-u.z},\n\t\t\t{-v.w, v.x, v.y, v.z}};\n\t}\n\ttemplate<typename R>\n\tdual<R>::operator R(void) const {\n\t\treturn sqrt((*this)());\n\t}\n\ttemplate<typename R>\n\tR dual<R>::operator()(void) const {\n\t\treturn u()+v();\n\t}\n\n\ttemplate<typename R>\n\tbool dual<R>::operator==(dual<R> const& rhs) const {\n\t\treturn u == rhs.u && v == rhs.v;\n\t}\n\ttemplate<typename R>\n\tdual<R> dual<R>::operator()(quat<R> const& rhs) const {\n\t\treturn *this * rhs * ~*this;\n\t}\n\ttemplate<typename R>\n\tdual<R> dual<R>::operator()(dual<R> const& rhs) const {\n\t\treturn *this * rhs * ~*this;\n\t}\n}\n\n#endif\n", "meta": {"hexsha": "bd940552ee51ac36ccbd9f924f77a3bea962d2d2", "size": 3308, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/dual.hpp", "max_stars_repo_name": "XPCX/CitaDel", "max_stars_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/dual.hpp", "max_issues_repo_name": "XPCX/CitaDel", "max_issues_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/dual.hpp", "max_forks_repo_name": "XPCX/CitaDel", "max_forks_repo_head_hexsha": "91de98a9e1507691df00e2c0a9dfb4e999fc9505", "max_forks_repo_licenses": ["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.3235294118, "max_line_length": 56, "alphanum_fraction": 0.5423216445, "num_tokens": 1212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.551445237543719}}
{"text": "#include <CGAL/Cartesian.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_4_hyperbolic_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>\n#include <CGAL/Hyperbolic_octagon_translation.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Periodic_2_Delaunay_triangulation_traits_2.h>\n#include <CGAL/Periodic_2_Delaunay_triangulation_2.h>\n#include <CGAL/determinant.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Timer.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_smallint.hpp>\n#include <boost/random/variate_generator.hpp>\n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<>           Traits;\ntypedef Traits::FT                                                              NT;\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_2<Traits>            Triangulation;\ntypedef CGAL::Hyperbolic_octagon_translation_matrix<NT>                         Octagon_matrix;\ntypedef Triangulation::Point                                                    Point;\ntypedef Triangulation::Vertex_handle                                            Vertex_handle;\ntypedef Traits::Side_of_original_octagon                                        Side_of_original_octagon;\n\ntypedef CGAL::Cartesian<double>::Point_2                                        Point_double;\ntypedef CGAL::Creator_uniform_2<double, Point_double >                          Creator;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt             EKernel;\ntypedef CGAL::Delaunay_triangulation_2<EKernel>                                 Euclidean_triangulation;\ntypedef CGAL::Periodic_2_Delaunay_triangulation_traits_2<EKernel>               Ptraits;\ntypedef CGAL::Periodic_2_Delaunay_triangulation_2<Ptraits>                      PEuclidean_triangulation;\n\ntypedef double                                                                  dNT;\ntypedef CGAL::Cartesian<dNT>                                                    dKernel;\ntypedef CGAL::Delaunay_triangulation_2<dKernel>                                 dTriangulation;\n\nint main(int argc, char** argv)\n{\n  int N, iters;\n  iters = 1;\n  if(argc < 2)\n  {\n    std::cout << \"usage: \" << argv[0] << \" [number_of_points_to_insert] [optional: number_of_iterations]\" << std::endl;\n    std::cout << \"Defaulting to values: 10000000, 10...\" << std::endl;\n    N = 1000000;\n    iters = 10;\n  } else {\n    N = atoi(argv[1]);\n    if (argc < 3)\n      iters = 1;\n    else\n      iters = atoi(argv[2]);\n  }\n\n\n  Side_of_original_octagon pred;\n\n  std::cout << \"---- for best results, make sure that you have compiled me in Release mode ----\" << std::endl;\n\n  double extime1 = 0.0;\n  double extime2 = 0.0;\n  double extime3 = 0.0;\n\n  for(int exec = 1; exec <= iters; ++exec)\n  {\n    std::vector<Point> pts;\n    std::vector<Point_double> dpts;\n    CGAL::Random_points_in_disc_2<Point_double, Creator> g(0.85);\n\n    int cnt = 0;\n    std::cout << \"================ iteration \" << exec << \" : generating points ================\" << std::endl;\n    do\n    {\n      Point_double pd = *(++g);\n      Point pt = Point(pd.x(), pd.y());\n      if(pred(pt) != CGAL::ON_UNBOUNDED_SIDE)\n      {\n        pts.push_back(pt);\n        dpts.push_back(pd);\n        ++cnt;\n      }\n    }\n    while(cnt < N);\n\n    if(cnt < N)\n    {\n      std::cout << \"Failed to generate all the random points! Exiting...\" << std::endl;\n      return -1;\n    }\n\n    std::cout << \"Inserting into hyperbolic periodic  CORE  triangulation...    \"; std::cout.flush();\n    Triangulation tr;\n    CGAL::Timer t1;\n    t1.start();\n    tr.insert(pts.begin(), pts.end());\n    t1.stop();\n    extime1 += t1.time();\n    std::cout << \"DONE! (# of vertices = \" << tr.number_of_vertices() << \", time = \" << t1.time() << \" secs)\" << std::endl;\n\n    std::cout << \"inserting into Euclidean non-periodic  CORE  triangulation... \"; std::cout.flush();\n    Euclidean_triangulation etr;\n    CGAL::Timer t2;\n    t2.start();\n    etr.insert(pts.begin(), pts.end());\n    t2.stop();\n    extime2 += t2.time();\n    std::cout << \"DONE! (# of vertices = \" << etr.number_of_vertices() << \", time = \" << t2.time() << \" secs)\" << std::endl;\n\n    std::cout << \"Inserting into Euclidean non-periodic DOUBLE triangulation... \"; std::cout.flush();\n    dTriangulation dtr;\n    CGAL::Timer t3;\n    t3.start();\n    dtr.insert(dpts.begin(), dpts.end());\n    t3.stop();\n    extime3 += t3.time();\n    std::cout << \"DONE! (# of vertices = \" << dtr.number_of_vertices() << \", time = \" << t3.time() << \" secs)\" << std::endl;\n  }\n\n  double diters(iters);\n  extime1 /= diters;\n  extime2 /= diters;\n  extime3 /= diters;\n\n  std::cout << \"Hyperbolic periodic      CORE  triangulation: average time = \" << extime1 << std::endl;\n  std::cout << \"Euclidean  non-periodic  CORE  triangulation: average time = \" << extime2 << std::endl;\n  std::cout << \"Euclidean  non-periodic DOUBLE triangulation: average time = \" << extime3 << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "36f7e697b914e1cf0fcccc0729fd4ca478f45f44", "size": 5073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_hyperbolic_vs_euclidean.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_hyperbolic_vs_euclidean.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/benchmark/Periodic_4_hyperbolic_triangulation_2/bench_p4ht2_hyperbolic_vs_euclidean.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": 38.7251908397, "max_line_length": 124, "alphanum_fraction": 0.6037847428, "num_tokens": 1355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973931, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.5513608033973534}}
{"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/convolvedstudentt.hpp>\n#include <ql/errors.hpp>\n#include <ql/math/factorial.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/functional.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#include <boost/math/distributions/students_t.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nnamespace QuantLib {\n\n    CumulativeBehrensFisher::CumulativeBehrensFisher(const std::vector<Integer>& degreesFreedom,\n                                                     const std::vector<Real>& factors)\n    : degreesFreedom_(degreesFreedom), factors_(factors), polyConvolved_(std::vector<Real>(1, 1.))\n\n    {\n        QL_REQUIRE(degreesFreedom.size() == factors.size(),\n            \"Incompatible sizes in convolution.\");\n        for (int i : degreesFreedom) {\n            QL_REQUIRE(i % 2 != 0, \"Even degree of freedom not allowed\");\n            QL_REQUIRE(i >= 0, \"Negative degree of freedom not allowed\");\n        }\n        for(Size i=0; i<degreesFreedom_.size(); i++)\n            polynCharFnc_.push_back(polynCharactT((degreesFreedom[i]-1)/2));\n        // adjust the polynomial coefficients by the factors in the linear\n        //   combination:\n        for(Size i=0; i<degreesFreedom_.size(); i++) {\n            Real multiplier = 1.;\n            for(Size k=1; k<polynCharFnc_[i].size(); k++) {\n                multiplier *= std::abs(factors_[i]);\n                polynCharFnc_[i][k] *= multiplier;\n            }\n        }\n        //convolution, here it is a product of polynomials and exponentials\n        for (auto& i : polynCharFnc_)\n            polyConvolved_ = convolveVectorPolynomials(polyConvolved_, i);\n        // trim possible zeros that might have arised:\n        auto it = polyConvolved_.rbegin();\n        while (it != polyConvolved_.rend()) {\n            if (*it == 0.) {\n                polyConvolved_.pop_back();\n                it = polyConvolved_.rbegin();\n              }else{\n                  break;\n              }\n          }\n          // cache 'a' value (the exponent)\n          for(Size i=0; i<degreesFreedom_.size(); i++)\n              a_ += std::sqrt(static_cast<Real>(degreesFreedom_[i]))\n                * std::abs(factors_[i]);\n          a2_ = a_ * a_;\n    }\n\n    std::vector<Real> CumulativeBehrensFisher::polynCharactT(Natural n) const {\n        Natural nu = 2 * n +1;\n        std::vector<Real> low(1,1.), high(1,1.);\n        high.push_back(std::sqrt(static_cast<Real>(nu)));\n        if(n==0) return low;\n        if(n==1) return high;\n\n        for(Size k=1; k<n; k++) {\n            std::vector<Real> recursionFactor(1,0.); // 0 coef\n            recursionFactor.push_back(0.); // 1 coef\n            recursionFactor.push_back(nu/((2.*k+1.)*(2.*k-1.))); // 2 coef\n            std::vector<Real> lowUp =\n                convolveVectorPolynomials(recursionFactor, low);\n            //add them up:\n            for(Size i=0; i<high.size(); i++)\n                lowUp[i] += high[i];\n            low = high;\n            high = lowUp;\n        }\n        return high;\n    }\n\n    std::vector<Real> CumulativeBehrensFisher::convolveVectorPolynomials(\n        const std::vector<Real>& v1,\n        const std::vector<Real>& v2) const {\n    #if defined(QL_EXTRA_SAFETY_CHECKS)\n        QL_REQUIRE(!v1.empty() && !v2.empty(),\n            \"Incorrect vectors in polynomial.\");\n    #endif\n\n        const std::vector<Real>& shorter = v1.size() < v2.size() ? v1 : v2;\n        const std::vector<Real>& longer = (v1 == shorter) ? v2 : v1;\n\n        Size newDegree = v1.size()+v2.size()-2;\n        std::vector<Real> resultB(newDegree+1, 0.);\n        for(Size polyOrdr=0; polyOrdr<resultB.size(); polyOrdr++) {\n            for(Size i=std::max<Integer>(0, polyOrdr-longer.size()+1);\n                i<=std::min(polyOrdr, shorter.size()-1); i++)\n                resultB[polyOrdr] += shorter[i]*longer[polyOrdr-i];\n        }\n        return resultB;\n    }\n\n    Probability CumulativeBehrensFisher::operator()(const Real x) const {\n        // 1st & 0th terms with the table integration\n        Real integral = polyConvolved_[0] * std::atan(x/a_);\n        Real squared = a2_ + x*x;\n        Real rootsqr = std::sqrt(squared);\n        Real atan2xa = std::atan2(-x,a_);\n        if(polyConvolved_.size()>1)\n            integral += polyConvolved_[1] * x/squared;\n\n        for(Size exponent = 2; exponent <polyConvolved_.size(); exponent++) {\n            integral -= polyConvolved_[exponent] *\n                Factorial::get(exponent-1) * std::sin((exponent)*atan2xa)\n                    /std::pow(rootsqr, static_cast<Real>(exponent));\n         }\n        return .5 + integral / M_PI;\n    }\n\n    Probability\n    CumulativeBehrensFisher::density(const Real x) const {\n        Real squared = a2_ + x*x;\n        Real integral = polyConvolved_[0] * a_ / squared;\n        Real rootsqr = std::sqrt(squared);\n        Real atan2xa = std::atan2(-x,a_);\n        for(Size exponent=1; exponent <polyConvolved_.size(); exponent++) {\n            integral += polyConvolved_[exponent] *\n                Factorial::get(exponent) * std::cos((exponent+1)*atan2xa)\n                    /std::pow(rootsqr, static_cast<Real>(exponent+1) );\n        }\n        return integral / M_PI;\n    }\n\n\n\n    InverseCumulativeBehrensFisher::InverseCumulativeBehrensFisher(\n        const std::vector<Integer>& degreesFreedom,\n        const std::vector<Real>& factors,\n        Real accuracy)\n    : normSqr_(std::inner_product(factors.begin(), factors.end(),\n        factors.begin(), 0.)),\n      accuracy_(accuracy), distrib_(degreesFreedom, factors) { }\n\n    Real InverseCumulativeBehrensFisher::operator()(const Probability q) const {\n        Probability effectiveq;\n        Real sign;\n        // since the distrib is symmetric solve only on the right side:\n        if(q==0.5) {\n            return 0.;\n        }else if(q < 0.5) {\n            sign = -1.;\n            effectiveq = 1.-q;\n        }else{\n            sign = 1.;\n            effectiveq = q;\n        }\n        Real xMin =\n            InverseCumulativeNormal::standard_value(effectiveq) * normSqr_;\n        // inversion will fail at the Brent's bounds-check if this is not enough\n        // (q is very close to 1.), in a bad combination fails around 1.-1.e-7\n        Real xMax = 1.e6;\n        return sign *\n            Brent().solve([&](Real x){ return distrib_(x) - effectiveq; },\n                          accuracy_, (xMin+xMax)/2., xMin, xMax);\n    }\n\n}\n", "meta": {"hexsha": "240801f7d228a5b63f027555fe651fb67be580cf", "size": 7466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/convolvedstudentt.cpp", "max_stars_repo_name": "mshojatalab/QuantLib", "max_stars_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/math/convolvedstudentt.cpp", "max_issues_repo_name": "mshojatalab/QuantLib", "max_issues_repo_head_hexsha": "7801a0fb3226bc1b001e310bacdd35ddb2e51661", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-24T02:22:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T02:22:30.000Z", "max_forks_repo_path": "ql/experimental/math/convolvedstudentt.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": 39.7127659574, "max_line_length": 98, "alphanum_fraction": 0.5900080364, "num_tokens": 1907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.5513607951826903}}
{"text": "#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"tictoc.hpp\"\n#include \"initial_homography_estimation.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace fovis\n{\n\n#define dump(var) //(cerr<<\" \"#var<<\" =[\\n\"<< setprecision (12)<<var<<\"];\"<<endl)\nEigen::ArrayXf InitialHomographyEstimator::flattenMatrix(Eigen::MatrixXf &m)\n{\n  return Eigen::Map<Eigen::ArrayXf>(m.data(), m.rows() * m.cols());\n}\n\nstatic void \ngrayToEigen(const uint8_t * grayData, int width, int height, int stride,\n    int downsampleFactor, Eigen::MatrixXf* result)\n{\n  Eigen::MatrixXf& eig_imf = *result;\n  if (downsampleFactor > 0) {\n    int cols = width >> downsampleFactor;\n    int rows = height >> downsampleFactor;\n    eig_imf = Eigen::MatrixXf::Zero(rows, cols);\n    for (int y = 0; y < height; y++) {\n      int ey = y >> downsampleFactor;\n      for (int x = 0; x < width; x++) {\n        int ex = x >> downsampleFactor;\n        eig_imf(ey, ex) += grayData[y * stride + x];\n      }\n    }\n    double pixelFactor = (1 << downsampleFactor);\n    eig_imf /= pixelFactor * pixelFactor;\n  }\n  else {\n    eig_imf.resize(height, width);\n    const uint8_t* row_start = grayData;\n    for(int row=0; row<height; row++) {\n      for(int col=0; col<width; col++) {\n        eig_imf(row, col) = row_start[col];\n      }\n      row_start += stride;\n    }\n  }\n}\n\nvoid InitialHomographyEstimator::setTestImage(const uint8_t * grayData, int width, int height, int stride, int downsampleFactor)\n{\n  grayToEigen(grayData, width, height, stride, downsampleFactor, &testImage);\n}\n\nvoid InitialHomographyEstimator::setTemplateImage(const uint8_t * grayData, int width, int height, int stride,\n    int downsampleFactor)\n{\n  grayToEigen(grayData, width, height, stride, downsampleFactor, &templateImage);\n  template_rows = templateImage.rows();\n  template_cols = templateImage.cols();\n\n  //compute template gradients\n  Eigen::MatrixXf templateDx, templateDy;\n  computeGradient(templateImage, &templateDx, &templateDy);\n\n  templateDxRow = flattenMatrix(templateDx);\n  templateDyRow = flattenMatrix(templateDy);\n\n  //setup the utility matrices\n  Eigen::MatrixXf x = VectorXf::LinSpaced(template_cols, 0, template_cols - 1).transpose().replicate(template_rows, 1);\n  Eigen::MatrixXf y = VectorXf::LinSpaced(template_rows, 0, template_rows - 1).replicate(1, template_cols);\n  xx = flattenMatrix(x);\n  yy = flattenMatrix(y);\n\n  templatePoints.resize(3, xx.rows());\n  templatePoints.row(0) = xx;\n  templatePoints.row(1) = yy;\n  templatePoints.row(2).setOnes();\n\n  xx += 1;\n  yy += 1;\n\n}\n\ndouble InitialHomographyEstimator::computeError(const Eigen::MatrixXf &error)\n{\n  return error.norm() / sqrt((double) error.rows() * error.cols());\n}\n\nEigen::Matrix3f InitialHomographyEstimator::track(const Eigen::Matrix3f & initH, int nIters, double * finalRMS)\n{\n\n  double minError = INFINITY;\n  Eigen::Matrix3f H = initH;\n  Eigen::Matrix3f bestH = H;\n  int bestIter = 0;\n  int lastImproved = 0;\n  double lastRMS = INFINITY;\n\n  for (int iter = 0; iter < nIters; iter++) {\n    tictoc(\"track_iter\");\n    tictoc(\"warpPoints\");\n    Eigen::MatrixXf warpedHomogeneousPoints;\n    warpedHomogeneousPoints = H * templatePoints;\n    tictoc(\"warpPoints\");\n\n    tictoc(\"constructWarpedImage\");\n    warpedTestImage = constructWarpedImage(testImage, warpedHomogeneousPoints);\n    tictoc(\"constructWarpedImage\");\n\n    errorIm = warpedTestImage - templateImage;\n    Eigen::VectorXf errorRow;\n    errorRow = flattenMatrix(errorIm);\n\n    double rmsError = computeError(errorRow);\n\n    if (rmsError < minError) {\n      minError = rmsError;\n      bestH = H;\n      bestIter = iter;\n    }\n\n    tictoc(\"computeJacobian\");\n    tictoc(\"computeGradient\");\n    Eigen::MatrixXf warpedTestImageDx, warpedTestImageDy;\n    computeGradient(warpedTestImage, &warpedTestImageDx, &warpedTestImageDy);\n    tictoc(\"computeGradient\");\n\n    Eigen::ArrayXf warpedTestImageDxRow, warpedTestImageDyRow;\n    warpedTestImageDxRow = flattenMatrix(warpedTestImageDx);\n    warpedTestImageDyRow = flattenMatrix(warpedTestImageDy);\n\n    Eigen::MatrixXf Jt = computeJacobian(templateDxRow + warpedTestImageDxRow, templateDyRow + warpedTestImageDyRow);\n    tictoc(\"computeJacobian\");\n\n    //compute the psuedo-inverse\n    tictoc(\"update\");\n    tictoc(\"svd_pinv\");\n    Eigen::JacobiSVD<MatrixXf> svd(Jt, ComputeThinU | ComputeThinV);\n    Eigen::VectorXf sigma = svd.singularValues();\n    Eigen::MatrixXf U = svd.matrixU();\n    Eigen::MatrixXf V = svd.matrixV();\n    int r = 0;\n    for (r = 0; r < sigma.rows(); r++) { //singular values are in decreasing order\n      if (sigma(r) < 1e-7) //TODO:better way to get the tolerance?\n        break;\n      else\n        sigma(r) = 1.0 / sigma(r);\n    }\n    Eigen::MatrixXf Jt_plus;\n    if (r == 0)\n      Jt_plus = Eigen::MatrixXf::Zero(Jt.cols(), Jt.rows());\n    else {\n      Jt_plus = V.block(0, 0, V.rows(), r) * sigma.head(r).asDiagonal() * U.block(0, 0, U.rows(), r).transpose();\n    }\n    tictoc(\"svd_pinv\");\n\n    // this doesn't seem to work :-/\n    //    tictoc(\"manual_pinv\");\n    //    Eigen::Matrix3f JtT_Jt = Jt.transpose() * Jt;\n    //    Eigen::MatrixXf Jt_plus = JtT_Jt.inverse() * Jt;\n    //    tictoc(\"manual_pinv\");\n\n    Eigen::VectorXf lie_d = -2 * Jt_plus * errorRow;\n    tictoc(\"update\");\n\n    tictoc(\"lieToH\");\n    H = H * lieToH(lie_d);\n    tictoc(\"lieToH\");\n\n    if (rmsError < lastRMS)\n      lastImproved = iter;\n\n    tictoc(\"track_iter\");\n\n    //        cout << iter << \") rmsError= \" << rmsError << \" minError = \" << minError << \" d.norm() =\" << lie_d.norm() << endl;\n    //    exit(1);\n    if (lie_d.norm() < 1e-6 || (rmsError - minError > 3 && iter - bestIter > 2) || iter - bestIter > 4 || iter\n        - lastImproved > 2) {\n      //      printf(\"breaking after %d iters\\n\", iter);\n      break;\n    }\n    lastRMS = rmsError;\n\n  }\n  if (finalRMS != NULL)\n    *finalRMS = minError;\n  return bestH;\n\n}\n\nvoid InitialHomographyEstimator::computeGradient(const Eigen::MatrixXf &image, Eigen::MatrixXf *dxp, Eigen::MatrixXf *dyp)\n{\n  Eigen::MatrixXf & dx = *dxp;\n  Eigen::MatrixXf & dy = *dyp;\n  dx = Eigen::MatrixXf::Zero(image.rows(), image.cols());\n  dy = Eigen::MatrixXf::Zero(image.rows(), image.cols());\n\n  dx.block(0, 1, dx.rows(), dx.cols() - 2) = image.block(0, 2, dx.rows(), dx.cols() - 2) - image.block(0, 0, dx.rows(),\n      dx.cols() - 2);\n  //handle border\n\n  dy.block(1, 0, dy.rows() - 2, dy.cols()) = image.block(2, 0, dy.rows() - 2, dy.cols()) - image.block(0, 0, dy.rows()\n      - 2, dy.cols());\n  //normalize\n  dx /= 2.0;\n  dy /= 2.0;\n\n  //handle borders\n  dx.col(0) = image.col(1) - image.col(0);\n  dx.col(image.cols() - 1) = image.col(image.cols() - 1) - image.col(image.cols() - 2);\n  dy.row(0) = image.row(1) - image.row(0);\n  dy.row(image.rows() - 1) = image.row(image.rows() - 1) - image.row(image.rows() - 2);\n\n}\n\nEigen::MatrixXf InitialHomographyEstimator::computeJacobian(const Eigen::ArrayXf &dx, const Eigen::ArrayXf &dy) const\n{\n  Eigen::MatrixXf Jt(dx.rows(), 3);\n  Jt.col(0) = dx;\n  Jt.col(1) = dy;\n  Jt.col(2) = dx * yy - dy * xx;\n  return Jt;\n}\n\nEigen::Matrix3f InitialHomographyEstimator::lieToH(const Eigen::VectorXf &lie) const\n{\n  //TODO: support more parameters?\n  Eigen::Matrix3f M;\n  M << 0, lie(2), lie(0),\n      -lie(2), 0, lie(1),\n       0, 0, 0;\n  return M.exp();\n}\n\nEigen::MatrixXf InitialHomographyEstimator::constructWarpedImage(const Eigen::MatrixXf &srcImage,\n    const Eigen::MatrixXf &warpedPoints) const\n{\n  Eigen::MatrixXf warped = Eigen::MatrixXf(template_rows, template_cols);\n\n  const double defaultValue = 128;\n  //Bilinear interpolation\n  for (int i = 0; i < warpedPoints.cols(); i++) {\n    double val;\n    Eigen::Vector2f pt = warpedPoints.col(i).head(2) / warpedPoints(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) < srcImage.cols() - 1 && 0 <= pt(1) && pt(1) < srcImage.rows() - 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 * srcImage(fipt(1), fipt(0)) + x1 * y2 * srcImage(fipt(1), fipt(0) + 1) + x2 * y1 * srcImage(\n          fipt(1) + 1, fipt(0)) + x1 * y1 * srcImage(fipt(1) + 1, fipt(0) + 1);\n\n    }\n    else if (0 <= fipt(0) && fipt(0) < srcImage.cols() && 0 <= fipt(1) && fipt(1) < srcImage.rows()) {\n      val = srcImage(fipt(1), fipt(0));\n    }\n    else if (0 <= cipt(0) && cipt(0) < srcImage.cols() && 0 <= cipt(1) && cipt(1) < srcImage.rows()) {\n      val = srcImage(cipt(1), cipt(0));\n    }\n    else\n      val = defaultValue; //templateImage(i / template_cols, i % template_cols); //default to the same as template, so error is 0\n\n    warped(i % template_rows, i / template_rows) = val; //Eigen is Column-major\n  }\n  return warped;\n}\n\n}\n", "meta": {"hexsha": "68c8ddded5363d699d19e5c8398c1bd0c9b20b23", "size": 8840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libfovis/libfovis/initial_homography_estimation.cpp", "max_stars_repo_name": "vatanaksoytezer/zephyr", "max_stars_repo_head_hexsha": "3880dbdb62ec7908d4eed1bc173544979925997c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/initial_homography_estimation.cpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-16T22:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-16T22:01:11.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/initial_homography_estimation.cpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-10T14:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T13:50:24.000Z", "avg_line_length": 32.0289855072, "max_line_length": 129, "alphanum_fraction": 0.6369909502, "num_tokens": 2825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.6442251064863698, "lm_q1q2_score": 0.5513607915542048}}
{"text": "#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <set>\n#include <vector>\n\n#include <future>\n#include <thread>\n\n#include <Eigen/Dense>\n\n#include <gmpxx.h>\n\n#include \"Expression.h\"\n\n//int THREADS_NUM = std::thread::hardware_concurrency();\nconstexpr int THREADS_NUM = 4;\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::NumericSimplify(Indices const & indices, bool print_matrix) const {\n  assert(!this->IsZero());\n\n  std::bitset<64> bs(0);\n  bs[2 * indices.size()] = true;\n  size_t number_of_combinations = bs.to_ulong();\n\n  auto thread_function = [expression=*this,noc=number_of_combinations,indices=indices] (size_t thread_counter, auto coefficient, auto sum) mutable -> void {\n    std::set<size_t> coefficient_set;\n    std::set<ScalarSum> sum_set;\n    for (size_t counter = thread_counter * noc / THREADS_NUM; counter < (thread_counter + 1) * noc / THREADS_NUM; ++counter) {\n      std::vector<size_t> numbers (indices.size());\n      std::bitset<64> binary_representation(counter);\n      for (size_t digit_counter = 0; digit_counter < indices.size(); ++digit_counter) {\n        unsigned int binary_digit_a = static_cast<unsigned int>(binary_representation[2 * digit_counter + 1]);\n        unsigned int binary_digit_b = static_cast<unsigned int>(binary_representation[2 * digit_counter]);\n        *(numbers.rbegin() + digit_counter) = 2 * binary_digit_a + binary_digit_b;\n      }\n\n      ScalarSum sum_tmp = expression.EvaluateIndices(indices, numbers);\n      if (!sum_tmp.IsZero()) {\n        coefficient_set.merge(sum_tmp.CoefficientSet());\n        sum_set.insert(sum_tmp);\n      }\n    }\n    coefficient.set_value(coefficient_set);\n    sum.set_value(sum_set);\n  };\n\n  std::vector<std::thread> t (THREADS_NUM);\n\n  std::vector<std::promise<std::set<size_t>>> coefficients_promises (THREADS_NUM);\n  std::vector<std::promise<std::set<ScalarSum>>> sums_promises (THREADS_NUM);\n\n  std::vector<std::future<std::set<size_t>>> coefficients_futures (THREADS_NUM);\n  std::vector<std::future<std::set<ScalarSum>>> sums_futures (THREADS_NUM);\n\n  for (int thread_counter = 0; thread_counter < THREADS_NUM; ++thread_counter) {\n    coefficients_futures[thread_counter] = coefficients_promises[thread_counter].get_future();\n    sums_futures[thread_counter] = sums_promises[thread_counter].get_future();\n    std::cout << \"Launching thread \" << thread_counter << std::endl;\n    t[thread_counter] = std::thread(thread_function, thread_counter, std::move(coefficients_promises[thread_counter]),\n                                                                     std::move(sums_promises[thread_counter]));\n  }\n\n  for (int thread_counter = 0; thread_counter < THREADS_NUM; ++thread_counter) {\n    t[thread_counter].join();\n    std::cout << \"Joined thread \" << thread_counter << std::endl;\n  }\n\n  std::set<ScalarSum> sum_set;\n  std::set<size_t> coefficient_set;\n\n  for (int thread_counter = 0; thread_counter < THREADS_NUM; ++thread_counter) {\n    coefficient_set.merge(coefficients_futures.at(thread_counter).get());\n    sum_set.merge(sums_futures.at(thread_counter).get());\n  }\n\n  std::map<size_t, size_t> coefficient_map;\n  std::for_each(coefficient_set.begin(), coefficient_set.end(), [n=0,&coefficient_map](auto a) mutable { coefficient_map[a] = n++; });\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  std::cout << \"Thus the problem of finding linear dependencies is equivalent to the problem of finding the null space for a \" << sum_set.size() << \" by \" << coefficient_map.size() << \" matrix.\" << 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  if (print_matrix) {\n    std::cout << kq << std::endl;\n  }\n\n  std::set<size_t> coeff_removed; \n\n  for (int column_counter = 0; column_counter < kq.cols(); ++column_counter) {\n    for (int row_counter = kq.rows() - 1; row_counter >= 0; --row_counter) {\n      if (kq(row_counter, column_counter) == 0 ) {\n        continue;\n      } else if (std::find(coeff_removed.begin(), coeff_removed.end(), row_counter) != coeff_removed.end()) {\n        continue;\n      } else {\n        coeff_removed.insert(row_counter);\n        break;\n      }\n    }\n  }\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  Expression ret (*this);\n  std::for_each(coeff_removed.begin(), coeff_removed.end(), [&ret, &coefficient_rmap] (auto a) { ret.EliminateVariable(coefficient_rmap.at(a)); });\n  ret.CanonicalisePrefactors();\n  ret.RedefineScalars();\n\n  return Expression(ret);\n}\n", "meta": {"hexsha": "555c5314f2974b5b5ffacb51b246a4919e01ccca", "size": 5743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NumericSimplify.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/NumericSimplify.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/NumericSimplify.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": 40.1608391608, "max_line_length": 208, "alphanum_fraction": 0.6850078356, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.5512695910474458}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n// THIS IS NOT MEANT TO BE COMPILED - ONLY FOR INCLUSION IN DOCUMENTATION.\n\n#include <boost/math/differentiation/autodiff.hpp>\n\nnamespace boost { namespace math { namespace differentiation {\n\n// Type for variables and constants.\ntemplate<typename RealType, size_t Order, size_t... Orders>\nusing autodiff_fvar = typename detail::nest_fvar<RealType,Order,Orders...>::type;\n\n// Function returning a variable of differentiation.\ntemplate<typename RealType, size_t Order, size_t... Orders>\nautodiff_fvar<RealType,Order,Orders...> make_fvar(const RealType& ca);\n\n// Type of combined autodiff types.\ntemplate<typename RealType, typename... RealTypes>\nusing promote = typename detail::promote_args_n<RealType,RealTypes...>::type;\n\nnamespace detail {\n\n// Single autodiff variable. Independent variables are created by nesting.\ntemplate<typename RealType, size_t Order>\nclass fvar\n{\n  public:\n\n    // Query return value of function to get the derivatives.\n    template<typename... Orders>\n    get_type_at<RealType, sizeof...(Orders)-1> derivative(Orders... orders) const;\n\n    // All of the arithmetic and comparison operators are overloaded.\n    template<typename RealType2, size_t Order2>\n    fvar& operator+=(const fvar<RealType2,Order2>&);\n\n    fvar& operator+=(const root_type&);\n\n    // ...\n};\n\n// Standard math functions are overloaded and called via argument-dependent lookup (ADL).\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> floor(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> exp(const fvar<RealType,Order>&);\n\n// ...\n\n} // namespace detail\n\n} } } // namespace boost::math::differentiation\n/**/\n", "meta": {"hexsha": "a871bafc3dfa1de7166882ed720a3c4c02a7dd38", "size": 1887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/synopsis.cpp", "max_stars_repo_name": "kedarbhat/autodiff", "max_stars_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-17T08:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T21:19:42.000Z", "max_issues_repo_path": "example/synopsis.cpp", "max_issues_repo_name": "kedarbhat/autodiff", "max_issues_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/synopsis.cpp", "max_forks_repo_name": "kedarbhat/autodiff", "max_forks_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5344827586, "max_line_length": 89, "alphanum_fraction": 0.738208797, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.5512403022818904}}
{"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     tilt_calibration.cpp\n * \\author   Collin Johnson\n *\n * Definition of calibrate_laser_pitch.\n */\n\n#include \"calibration/laser/tilt_calibration.h\"\n#include \"math/regression.h\"\n#include <boost/range/iterator_range.hpp>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace calibration\n{\n\nusing Measurements = std::vector<Point<double>>;\n\n\ntilt_calibration_results_t calibrate_laser_tilt(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                                std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                                int lineStartIndex,\n                                                int lineEndIndex,\n                                                double pitchStepSize,\n                                                double maxPitch,\n                                                double rollStepSize,\n                                                double maxRoll);\nMeasurements extract_line_measurements(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                       std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                       int lineStartIndex,\n                                       int lineEndIndex);\nPoint<double> apply_tilt(const Point<double>& point, double pitch, double roll);\n\n\ntilt_calibration_results_t calibrate_laser_pitch(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                                 std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                                 int lineStartIndex,\n                                                 int lineEndIndex,\n                                                 double minStepSize,\n                                                 double maxPitch)\n{\n    return calibrate_laser_tilt(beginLaser, endLaser, lineStartIndex, lineEndIndex, minStepSize, maxPitch, 0.0, 0.0);\n}\n\n\ntilt_calibration_results_t calibrate_laser_roll(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                                std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                                int lineStartIndex,\n                                                int lineEndIndex,\n                                                double minStepSize,\n                                                double maxRoll)\n{\n    return calibrate_laser_tilt(beginLaser, endLaser, lineStartIndex, lineEndIndex, 0.0, 0.0, minStepSize, maxRoll);\n}\n\n\ntilt_calibration_results_t calibrate_laser_tilt(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                                std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                                int lineStartIndex,\n                                                int lineEndIndex,\n                                                double pitchStepSize,\n                                                double maxPitch,\n                                                double rollStepSize,\n                                                double maxRoll)\n{\n    assert(lineEndIndex > lineStartIndex + 5);\n    assert(endLaser > beginLaser);\n\n    std::cout << \"Beginning tilt calibration for \" << std::distance(beginLaser, endLaser) << \" laser scans using \"\n              << \"indices \" << lineStartIndex << \"->\" << lineEndIndex << \" for fitting the line.\\n\";\n\n    tilt_calibration_results_t results;\n\n    double minError = std::numeric_limits<double>::max();\n\n    Measurements measurements = extract_line_measurements(beginLaser, endLaser, lineStartIndex, lineEndIndex);\n    Measurements pitchMeasurements = measurements;\n\n    auto pitchLine = math::total_least_squares(measurements.begin(), measurements.end());\n\n    for (double pitch = 0.0, roll = 0.0; pitch >= -maxPitch && roll >= -maxRoll;\n         pitch -= pitchStepSize, roll -= rollStepSize) {\n        std::transform(measurements.begin(),\n                       measurements.end(),\n                       pitchMeasurements.begin(),\n                       [pitch, roll](Point<double> point) {\n                           return apply_tilt(point, pitch, roll);\n                       });\n\n        double error = 0;\n\n        for (auto point : pitchMeasurements) {\n            error += distance_to_line(point, pitchLine);\n        }\n\n        tilt_t tilt(pitch, roll);\n        error /= pitchMeasurements.size();\n        results.tiltErrors.emplace_back(tilt, error);\n\n        std::cout << \"Pitch: \" << pitch << \" Roll:\" << roll << \" Line: \" << pitchLine << \" Error:\" << error << '\\n';\n\n        if (error < minError) {\n            results.bestTilt = tilt;\n            minError = error;\n        }\n    }\n\n    std::cout << \"Finished tilt calibration: Pitch:\" << results.bestTilt.pitch << \" Roll:\" << results.bestTilt.roll\n              << '\\n';\n\n    return results;\n}\n\n\nMeasurements extract_line_measurements(std::vector<polar_laser_scan_t>::const_iterator beginLaser,\n                                       std::vector<polar_laser_scan_t>::const_iterator endLaser,\n                                       int lineStartIndex,\n                                       int lineEndIndex)\n{\n    Measurements measurements;\n    measurements.reserve(std::distance(beginLaser, endLaser) * (lineEndIndex - lineStartIndex));\n    cartesian_laser_scan_t cartesian;\n\n    for (auto& scan : boost::make_iterator_range(beginLaser, endLaser)) {\n        polar_scan_to_cartesian_scan(scan, cartesian);\n\n        std::copy(cartesian.scanPoints.begin() + lineStartIndex,\n                  cartesian.scanPoints.begin() + lineEndIndex,\n                  std::back_inserter(measurements));\n    }\n\n    std::cout << \"INFO: tilt_calibration: Using \" << measurements.size() << \" measurements for fitting.\\n\";\n\n    return measurements;\n}\n\n\nPoint<double> apply_tilt(const Point<double>& point, double pitch, double roll)\n{\n    return Point<double>(point.x * std::cos(pitch), point.y * std::cos(roll));\n}\n\n}   // namespace calibration\n}   // namespace vulcan\n", "meta": {"hexsha": "0567c6e4b59b320e240872abbe8fbe8843a5ecea", "size": 6469, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calibration/laser/tilt_calibration.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/calibration/laser/tilt_calibration.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/calibration/laser/tilt_calibration.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 41.735483871, "max_line_length": 117, "alphanum_fraction": 0.5571185655, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.5512402909812056}}
{"text": "/**\n * \\file PanFilter.cpp\n */\n\n#include <ATK/Tools/PanFilter.h>\n\n#include <cmath>\n#include <complex>\n#include <cstdint>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <ATK/Core/TypeTraits.h>\n\nnamespace ATK\n{\n  template<typename DataType_>\n  PanFilter<DataType_>::PanFilter(gsl::index nb_channels)\n  :Parent(nb_channels, 2 * nb_channels)\n  {\n  }\n  \n  template<typename DataType_>\n  void PanFilter<DataType_>::set_pan_law(PAN_LAWS law)\n  {\n    this->law = law;\n  }\n  \n  template<typename DataType_>\n  typename PanFilter<DataType_>::PAN_LAWS PanFilter<DataType_>::get_pan_law() const\n  {\n    return law;\n  }\n  \n  template<typename DataType_>\n  void PanFilter<DataType_>::set_pan(double pan)\n  {\n    if(pan < -1 || pan > 1)\n    {\n      throw std::out_of_range(\"Pan must be a value between -1 and 1\");\n    }\n    this->pan = pan;\n  }\n\n  template<typename DataType_>\n  double PanFilter<DataType_>::get_pan() const\n  {\n    return pan;\n  }\n\n  template<typename DataType_>\n  void PanFilter<DataType_>::process_impl(gsl::index size) const\n  {\n    double left_coeff = 1;\n    double right_coeff = 1;\n    \n    switch(law)\n    {\n    case PAN_LAWS::SINCOS_0_CENTER:\n      left_coeff = std::sqrt(2) * std::cos((pan + 1) / 4 * boost::math::constants::pi<double>());\n      right_coeff = std::sqrt(2) * std::sin((pan + 1) / 4 * boost::math::constants::pi<double>());\n      break;\n    case PAN_LAWS::SINCOS_3_CENTER:\n      left_coeff = std::cos((pan + 1) / 4 * boost::math::constants::pi<double>());\n      right_coeff = std::sin((pan + 1) / 4 * boost::math::constants::pi<double>());\n      break;\n    case PAN_LAWS::SQUARE_0_CENTER:\n      left_coeff = std::sqrt(2) * std::sqrt((1 - pan) / 2);\n      right_coeff = std::sqrt(2) * std::sqrt((1 + pan) / 2);\n      break;\n    case PAN_LAWS::SQUARE_3_CENTER:\n      left_coeff = std::sqrt((1 - pan) / 2);\n      right_coeff = std::sqrt((1 + pan) / 2);\n      break;\n    case PAN_LAWS::LINEAR_TAPER:\n      left_coeff = (1 - pan) / 2;\n      right_coeff = (1 + pan) / 2;\n      break;\n    case PAN_LAWS::BALANCE:\n      left_coeff = pan < 0 ? 1 : 1 - pan;\n      right_coeff = pan > 0 ? 1 : 1 + pan;\n      break;\n    }\n    \n    assert(2 * nb_input_ports == nb_output_ports);\n\n    for (gsl::index channel = 0; channel < nb_input_ports; ++channel)\n    {\n      const DataType* ATK_RESTRICT input = converted_inputs[channel];\n      DataType* ATK_RESTRICT output0 = outputs[2 * channel];\n      DataType* ATK_RESTRICT output1 = outputs[2 * channel + 1];\n      for(gsl::index i = 0; i < size; ++i)\n      {\n        output0[i] = static_cast<DataType>(static_cast<typename TypeTraits<DataType>::Scalar>(left_coeff) * input[i]);\n        output1[i] = static_cast<DataType>(static_cast<typename TypeTraits<DataType>::Scalar>(right_coeff) * input[i]);\n      }\n    }\n  }\n  \n#if ATK_ENABLE_INSTANTIATION\n  template class PanFilter<std::int16_t>;\n  template class PanFilter<std::int32_t>;\n  template class PanFilter<std::int64_t>;\n  template class PanFilter<float>;\n  template class PanFilter<std::complex<float>>;\n  template class PanFilter<std::complex<double>>;\n#endif\n  template class PanFilter<double>;\n}\n", "meta": {"hexsha": "cbe29db7f7ba727b902cc2bdaccfaf240193b58a", "size": 3118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/PanFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Tools/PanFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Tools/PanFilter.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": 28.3454545455, "max_line_length": 119, "alphanum_fraction": 0.637908916, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5512402802151782}}
{"text": "/* Copyright (C) 5/23/18 Julian Stobbe - All Rights Reserved\n * You may use, distribute and modify this code under the\n * terms of the MIT license.\n *\n * You should have received a copy of the MIT license with\n * this file.\n */\n\n\n#ifndef VALUATION_NETWORK_SIM_HPP\n#define VALUATION_NETWORK_SIM_HPP\n\n#define USE_ACTUAL_CONN 0\n\n#include <type_traits>\n#include <cmath>\n#include <cstdlib>\n#include <type_traits>\n#include <string>\n#include <unordered_map>\n#include <limits>\n#include <random>\n#include <vector>\n\n#include \"trng/chi_square_dist.hpp\"\n\n#include \"Utils.hpp\"\n\n#ifdef USE_MPI\n\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n\n#endif\n\n#include \"Config.hpp\"\n#include \"StudentT.hpp\"\n#include \"MVarNormal.hpp\"\n#include \"Sampler.hpp\"\n#include \"StatAcc.hpp\"\n#include \"BlackScholesNetwork.hpp\"\n#include \"RndGraphGen.hpp\"\n\n\ntypedef typename std::conditional<USE_EIGEN_ACC, Eigen::MatrixXd, double>::type AccType;\ntypedef typename std::map<int, std::unordered_map<std::string, Eigen::MatrixXd>> ResultType;\n\n\nstruct SimulationParameters\n{\n    const long iterations, N_networks;\n    NetworkType net_t;\n};\n\nconstexpr int deg_of_freedom = 8;\n//const std::string io_deg_str(\"In/Out degree distribution\");\n\nclass NetwSim {\n    friend class Py_ER_Net;\nprivate:\n\n#ifdef USE_MPI\n    const boost::mpi::communicator local;\n    const boost::mpi::communicator world;\n    const bool isGenerator;\n#endif\n\n    trng::yarn2 gen_u;\n    trng::uniform01_dist<> u_dist;\n    Student_t_dist t_dist;\n    Multivariate_Normal_Dist mvndist;\n    //std::vector<double> dbg_weights;\n    double last_weight;\n\n    NetworkType net_t;\n    int N;\n    bool initialized;\n    double T;              // maturity\n    double r;              // interest\n    double p;\n    double val;\n    double S0scalar;\n    double sigmaScalar;\n    double default_prob_scale;\n    int setM;\n    const double tmp[2][2] = {{1, 0},\n                              {0, 1}};\n    long Num_Samples;\n    long Num_Networks;\n\n    BlackScholesNetwork* bsn;\n    Eigen::MatrixXd iSigma;\n    Eigen::VectorXd sigma;\n    Eigen::VectorXd Z;                 // Multivariate normal, used to generate lognormal assets\n    Eigen::VectorXd var_h;\n    Eigen::VectorXd S0;\n    Eigen::VectorXd debt;\n    Eigen::MatrixXd io_deg_dist;\n    Eigen::MatrixXd avg_rc_sums;\n    std::pair<double, double> avg_io_deg;\n\n    std::map<int, std::unordered_map<std::string, Eigen::MatrixXd> > results;\n    double connectivity;\n\n\n    // last result, returned by observe\n    void reset_network();\n\n    Eigen::MatrixXd in_out_degree(Eigen::MatrixXd* M);\n\n    void init_2DFixed_BS(const double vs01, const double vs10, const double vr01, const double vr10)\n    {\n        connectivity = 1;\n        Eigen::MatrixXd M = Eigen::MatrixXd::Zero(2, 4);\n        Utils::fixed_2d(&M, vs01, vs10, vr01, vr10);\n        io_deg_dist = Utils::in_out_degree(&M);\n        avg_io_deg = Utils::avg_io_deg(&M);\n        avg_rc_sums = Utils::avg_row_col_sums(&M);\n        bsn->re_init(M, S0, debt, sigma);\n    }\n\n    template <typename F>\n    void init_BS(F gen_function) {\n        if (val < 0 || val >= 1) throw std::logic_error(\"Row sum is not in [0,1)\");\n        if (p < 0 || p > 1) throw std::logic_error(\"p is not a probability\");\n        connectivity = N * p;\n        Eigen::MatrixXd M = Eigen::MatrixXd::Zero(N, 2 * N);\n        gen_function(&M, gen_u, p, val, setM);\n        //Utils::gen_fixed_degree(&M, gen_u, p, val, which_to_set);\n        io_deg_dist += Utils::in_out_degree(&M);\n        avg_io_deg = Utils::avg_io_deg(&M);\n        avg_rc_sums += Utils::avg_row_col_sums(&M);\n        bsn->re_init(M, S0, debt, sigma);\n    }\n\n//TODO: config struct\npublic:\n    /*!\n     * @brief               (re-)initializes network to given parameters\n     * @param N             Size of network\n     * @param p             Probability of cross holding\n     * @param val           total value in/being held by other firms\n     * @param which_to_set  Flag to disable connections between parts of the network. Can be 0/1/2. 2: cross debt is 0, 1: cross equity is 0, 0: none is 0\n     * @TODO: config struct\n     */\n    void init_network(const int N_, const double p_, const double val_, const int which_to_set, const double T_,\\\n        const double r_, const double S0_, const double sigma_, const double default_prob_scale_, const NetworkType net_t_);\n\n    void init_2D_network(BSParameters& bs_params, const double vs01, const double vs10, const double vr01, const double vr10);\n\n    virtual ~NetwSim(){\n        if(bsn != nullptr)\n            delete bsn;\n    }\n\n    /*!\n     * @brief               Constructs the Black Scholes Model using random cross holdings.\n     * @param local         local MPI communicator (between producers/consumers only)\n     * @param world         global MPI communicator\n     * @param isGenerator   Flag for generator/consumer ranks\n     */\n#ifdef USE_MPI\n    NetwSim(const boost::mpi::communicator local, const boost::mpi::communicator world, const bool isGenerator):\n            local(local), world(world), isGenerator(isGenerator), Z_dist(&tmp[0][0], &tmp[1][1]), chi_dist(deg_of_freedom), t_dist(deg_of_freedom)\n#else\n    NetwSim():\n            Z_dist(&tmp[0][0], &tmp[1][1]), chi_dist(deg_of_freedom), t_dist(deg_of_freedom), initialized(false)\n#endif\n    {\n        bsn = nullptr;\n        iSigma = Eigen::MatrixXd::Zero(1,1);\n        Z = Eigen::VectorXd::Zero(1,1);\n        var_h = Eigen::VectorXd::Zero(1,1);\n    }\n\n    /*!\n     * @brief               Constructs the Black Scholes Model using random cross holdings.\n     * @param local         local MPI communicator (between producers/consumers only)\n     * @param world         global MPI communicator\n     * @param isGenerator   Flag for generator/consumer ranks\n     * @param N             Size of network\n     * @param p             Probability of connection between firms\n     * @param val\n     * @param which_to_set  Flag to disable connections between parts of the network. Can be 0/1/2. 2: cross debt is 0, 1: cross equity is 0, 0: none is 0\n     * @param T             maturity\n     * @param r             interest rate\n     */\n#ifdef USE_MPI\n    NetwSim(const boost::mpi::communicator local, const boost::mpi::communicator world, const bool isGenerator,\n               long N, double p, double val, int which_to_set, const double T, const double r, const double S0, const NetworkType net_t_) :\n            local(local), world(world), isGenerator(isGenerator),\n#else\n    NetwSim(long N_, double p_, double val, int which_to_set, const double T_, const double r_, const double S0_, const double sigma_, const double default_scale_, const NetworkType net_t_) :\n#endif\n            val(val), T(T_), r(r_), S0scalar(S0_), sigmaScalar(sigma_), default_prob_scale(default_scale_)\\\n        , Z_dist(&tmp[0][0], &tmp[1][1]), chi_dist(deg_of_freedom), t_dist(deg_of_freedom), net_t(net_t_)\n    {\n        gen_u.seed();\n        bsn = nullptr;\n        init_network(N_, p_, val, which_to_set, T_, r_, S0_, sigma_, default_scale_, net_t_);\n    }\n\n\n    inline ResultType run_valuation(const SimulationParameters sim_params)\n    {\n        return run_valuation(sim_params.iterations, sim_params.N_networks);\n    }\n\n    /*!\n     * @brief       Runs a series of example simulations\n     * @param N_in  Size of network\n     */\n    ResultType run_valuation(const long N_Samples = 2000, const long N_networks = 100, const bool fix_degree = false);\n\n    /*!\n     * @brief   Draws a random number from a multivariate lognormal distribution\n     * @return  Random sample from a multivariate lognormal distribution\n     */\n    const Eigen::MatrixXd draw_from_dist();\n\n\n    const Eigen::MatrixXd transformZ(const Eigen::Ref<const Eigen::MatrixXd>& Z) const;\n\n    double get_weight();\n\n    /*!\n     * @brief       Runs a single simulation of the Black Scholes model to find the fix point valuation.\n     * @param St_in Initial asset value\n     * @return      Valuation of firms at maturity T\n     */\n    auto run(const Eigen::Ref<const Eigen::VectorXd>& St_in)//Eigen::VectorXd St)\n    {\n        //Eigen::VectorXd St = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(St_in.data(), St_in.size());\n        bsn->set_St(St_in);\n        bsn->run_valuation(1000);\n    }\n\n    /*!\n     * @brief   Compute \\f$\\Delta\\f$ using the covariance matrix of the normal distribution\n     * @return  \\f$\\Delta\\f$\n     */\n    const Eigen::MatrixXd delta_v2();\n\n    /*!\n     * @brief   Computes the sum over all elements of the cross holdings matrix\n     * @return  \\f$\\sum_{ij} M_{ij}\\f$\n     */\n    std::vector<double> sumM() {\n        std::vector<double> res{(bsn->get_M()).sum()};\n        return res;\n    }\n\n    Eigen::MatrixXd get_M()\n    {\n        return bsn->get_M();\n    }\n\n    auto test_out()\n    {\n        auto v_o = bsn->get_valuation();\n        auto s_o = bsn->get_solvent();\n        std::cout << \"output after sample: \" << std::endl;\n        LOG(INFO) << \"Valuation: \\n\" << v_o;\n        LOG(INFO) << \"solvent: \\n\" << s_o;\n        LOG(INFO) << \"St: \\n\" << bsn->get_assets();\n        LOG(INFO) << \"debt: \\n\" << bsn->get_debt();\n        LOG(INFO) << \"M: \\n\" << bsn->get_M();\n        std::cout << \"------\" << std::endl;\n        Eigen::MatrixXd out = Eigen::MatrixXd::Constant(1,1,0);\n        return out;\n    }\n\n\nprivate:\n\n    trng::yarn2 gen_z;\n    trng::yarn2 gen_chi;\n    trng::chi_square_dist<double> chi_dist;\n    trng::correlated_normal_dist<> Z_dist;\n\n\npublic:\n    Eigen::MatrixXd get_io_deg_dist() const\n    {\n        return io_deg_dist;\n    }\n\n    Eigen::MatrixXd get_avg_row_col_sums() const\n    {\n        return avg_rc_sums;\n    }\n\n    void set_weight();\n    //}\n\n};\n\n\n#endif //VALUATION_NETWORK_SIM_HPP\n", "meta": {"hexsha": "662037e9c8eb0fdc46964cb9cedb40792ae6d0c3", "size": 9657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NetwSim.hpp", "max_stars_repo_name": "Atomtomate/sys_risk", "max_stars_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NetwSim.hpp", "max_issues_repo_name": "Atomtomate/sys_risk", "max_issues_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NetwSim.hpp", "max_forks_repo_name": "Atomtomate/sys_risk", "max_forks_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_forks_repo_licenses": ["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.19, "max_line_length": 191, "alphanum_fraction": 0.6387076732, "num_tokens": 2517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.5512402742975072}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010-2019, 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    SO4.cpp\n * @brief   4*4 matrix representation of SO(4)\n * @author  Frank Dellaert\n * @author  Luca Carlone\n */\n\n#include <gtsam/base/concepts.h>\n#include <gtsam/base/timing.h>\n#include <gtsam/geometry/SO4.h>\n#include <gtsam/geometry/Unit3.h>\n\n#include <Eigen/Eigenvalues>\n#include <boost/random.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nnamespace gtsam {\n\n// /* *************************************************************************\n// */ static Vector3 randomOmega(boost::mt19937 &rng) {\n//   static boost::uniform_real<double> randomAngle(-M_PI, M_PI);\n//   return Unit3::Random(rng).unitVector() * randomAngle(rng);\n// }\n\n// /* *************************************************************************\n// */\n// // Create random SO(4) element using direct product of lie algebras.\n// SO4 SO4::Random(boost::mt19937 &rng) {\n//   Vector6 delta;\n//   delta << randomOmega(rng), randomOmega(rng);\n//   return SO4::Expmap(delta);\n// }\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nMatrix4 SO4::Hat(const Vector6& xi) {\n  // skew symmetric matrix X = xi^\n  // Unlike Luca, makes upper-left the SO(3) subgroup.\n  Matrix4 Y = Z_4x4;\n  Y(0, 1) = -xi(5);\n  Y(0, 2) = +xi(4);\n  Y(1, 2) = -xi(3);\n  Y(0, 3) = -xi(2);\n  Y(1, 3) = +xi(1);\n  Y(2, 3) = -xi(0);\n  return Y - Y.transpose();\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nVector6 SO4::Vee(const Matrix4& X) {\n  Vector6 xi;\n  xi(5) = -X(0, 1);\n  xi(4) = +X(0, 2);\n  xi(3) = -X(1, 2);\n  xi(2) = -X(0, 3);\n  xi(1) = +X(1, 3);\n  xi(0) = -X(2, 3);\n  return xi;\n}\n\n//******************************************************************************\n/* Exponential map, porting MATLAB implementation by Luca, which follows\n * \"SOME REMARKS ON THE EXPONENTIAL MAP ON THE GROUPS SO(n) AND SE(n)\" by\n * Ramona-Andreaa Rohan */\ntemplate <>\nGTSAM_EXPORT\nSO4 SO4::Expmap(const Vector6& xi, ChartJacobian H) {\n  using namespace std;\n  if (H) throw std::runtime_error(\"SO4::Expmap Jacobian\");\n\n  // skew symmetric matrix X = xi^\n  const Matrix4 X = Hat(xi);\n\n  // do eigen-decomposition\n  auto eig = Eigen::EigenSolver<Matrix4>(X);\n  Eigen::Vector4cd e = eig.eigenvalues();\n  using std::abs;\n  sort(e.data(), e.data() + 4, [](complex<double> a, complex<double> b) {\n    return abs(a.imag()) > abs(b.imag());\n  });\n\n  // Get a and b from eigenvalues +/i ai and +/- bi\n  double a = e[0].imag(), b = e[2].imag();\n  if (!e.real().isZero() || e[1].imag() != -a || e[3].imag() != -b) {\n    throw runtime_error(\"SO4::Expmap: wrong eigenvalues.\");\n  }\n\n  // Build expX = exp(xi^)\n  Matrix4 expX;\n  using std::cos;\n  using std::sin;\n  const auto X2 = X * X;\n  const auto X3 = X2 * X;\n  double a2 = a * a, a3 = a2 * a, b2 = b * b, b3 = b2 * b;\n  if (a != 0 && b == 0) {\n    double c2 = (1 - cos(a)) / a2, c3 = (a - sin(a)) / a3;\n    return SO4(I_4x4 + X + c2 * X2 + c3 * X3);\n  } else if (a == b && b != 0) {\n    double sin_a = sin(a), cos_a = cos(a);\n    double c0 = (a * sin_a + 2 * cos_a) / 2,\n           c1 = (3 * sin_a - a * cos_a) / (2 * a), c2 = sin_a / (2 * a),\n           c3 = (sin_a - a * cos_a) / (2 * a3);\n    return SO4(c0 * I_4x4 + c1 * X + c2 * X2 + c3 * X3);\n  } else if (a != b) {\n    double sin_a = sin(a), cos_a = cos(a);\n    double sin_b = sin(b), cos_b = cos(b);\n    double c0 = (b2 * cos_a - a2 * cos_b) / (b2 - a2),\n           c1 = (b3 * sin_a - a3 * sin_b) / (a * b * (b2 - a2)),\n           c2 = (cos_a - cos_b) / (b2 - a2),\n           c3 = (b * sin_a - a * sin_b) / (a * b * (b2 - a2));\n    return SO4(c0 * I_4x4 + c1 * X + c2 * X2 + c3 * X3);\n  } else {\n    return SO4();\n  }\n}\n\n//******************************************************************************\n// local vectorize\nstatic SO4::VectorN2 vec4(const Matrix4& Q) {\n  return Eigen::Map<const SO4::VectorN2>(Q.data());\n}\n\n// so<4> generators\nstatic std::vector<Matrix4, Eigen::aligned_allocator<Matrix4> > G4(\n    {SO4::Hat(Vector6::Unit(0)), SO4::Hat(Vector6::Unit(1)),\n     SO4::Hat(Vector6::Unit(2)), SO4::Hat(Vector6::Unit(3)),\n     SO4::Hat(Vector6::Unit(4)), SO4::Hat(Vector6::Unit(5))});\n\n// vectorized generators\nstatic const Eigen::Matrix<double, 16, 6> P4 =\n    (Eigen::Matrix<double, 16, 6>() << vec4(G4[0]), vec4(G4[1]), vec4(G4[2]),\n     vec4(G4[3]), vec4(G4[4]), vec4(G4[5]))\n        .finished();\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nMatrix6 SO4::AdjointMap() const {\n  // Elaborate way of calculating the AdjointMap\n  // TODO(frank): find a closed form solution. In SO(3) is just R :-/\n  const Matrix4& Q = matrix_;\n  const Matrix4 Qt = Q.transpose();\n  Matrix6 A;\n  for (size_t i = 0; i < 6; i++) {\n    // Calculate column i of linear map for coeffcient of Gi\n    A.col(i) = SO4::Vee(Q * G4[i] * Qt);\n  }\n  return A;\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO4::VectorN2 SO4::vec(OptionalJacobian<16, 6> H) const {\n  const Matrix& Q = matrix_;\n  if (H) {\n    // As Luca calculated, this is (I4 \\oplus Q) * P4\n    *H << Q * P4.block<4, 6>(0, 0), Q * P4.block<4, 6>(4, 0),\n        Q * P4.block<4, 6>(8, 0), Q * P4.block<4, 6>(12, 0);\n  }\n  return gtsam::vec4(Q);\n}\n\n///******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nSO4 SO4::ChartAtOrigin::Retract(const Vector6& xi, ChartJacobian H) {\n  if (H) throw std::runtime_error(\"SO4::ChartAtOrigin::Retract Jacobian\");\n  gttic(SO4_Retract);\n  const Matrix4 X = Hat(xi / 2);\n  return SO4((I_4x4 + X) * (I_4x4 - X).inverse());\n}\n\n//******************************************************************************\ntemplate <>\nGTSAM_EXPORT\nVector6 SO4::ChartAtOrigin::Local(const SO4& Q, ChartJacobian H) {\n  if (H) throw std::runtime_error(\"SO4::ChartAtOrigin::Retract Jacobian\");\n  const Matrix4& R = Q.matrix();\n  const Matrix4 X = (I_4x4 - R) * (I_4x4 + R).inverse();\n  return -2 * Vee(X);\n}\n\n//******************************************************************************\nGTSAM_EXPORT Matrix3 topLeft(const SO4& Q, OptionalJacobian<9, 6> H) {\n  const Matrix4& R = Q.matrix();\n  const Matrix3 M = R.topLeftCorner<3, 3>();\n  if (H) {\n    const Vector3 m1 = M.col(0), m2 = M.col(1), m3 = M.col(2),\n                  q = R.topRightCorner<3, 1>();\n    *H << Z_3x1, Z_3x1, q, Z_3x1, -m3, m2,  //\n        Z_3x1, -q, Z_3x1, m3, Z_3x1, -m1,   //\n        q, Z_3x1, Z_3x1, -m2, m1, Z_3x1;\n  }\n  return M;\n}\n\n//******************************************************************************\nGTSAM_EXPORT Matrix43 stiefel(const SO4& Q, OptionalJacobian<12, 6> H) {\n  const Matrix4& R = Q.matrix();\n  const Matrix43 M = R.leftCols<3>();\n  if (H) {\n    const auto &m1 = R.col(0), m2 = R.col(1), m3 = R.col(2), q = R.col(3);\n    *H << Z_4x1, Z_4x1, q, Z_4x1, -m3, m2,  //\n        Z_4x1, -q, Z_4x1, m3, Z_4x1, -m1,   //\n        q, Z_4x1, Z_4x1, -m2, m1, Z_4x1;\n  }\n  return M;\n}\n\n//******************************************************************************\n\n}  // end namespace gtsam\n", "meta": {"hexsha": "3e6ae485eeea5362047e291c364a524bc4752b5c", "size": 7533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/SO4.cpp", "max_stars_repo_name": "mindThomas/gtsam", "max_stars_repo_head_hexsha": "09b0f03542bfbec5cca62645a60c5d1d4f8fc48c", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/geometry/SO4.cpp", "max_issues_repo_name": "mindThomas/gtsam", "max_issues_repo_head_hexsha": "09b0f03542bfbec5cca62645a60c5d1d4f8fc48c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/SO4.cpp", "max_forks_repo_name": "mindThomas/gtsam", "max_forks_repo_head_hexsha": "09b0f03542bfbec5cca62645a60c5d1d4f8fc48c", "max_forks_repo_licenses": ["BSD-3-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.1923076923, "max_line_length": 81, "alphanum_fraction": 0.4918359219, "num_tokens": 2446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5511744055075456}}
{"text": "/*=========================================================================\n\n  Program:   Small Body Geophysical Analysis\n  Module:    SBGATMassProperties.hpp\n\n  Class derived from VTK's vtkPolyDataAlgorithm by Benjamin Bercovici  \n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n/**\n\\file SBGATMassProperties.hpp\n\\class  SBGATMassProperties\n\\author Benjamin Bercovici \n\\author Jay McMahon\n\\brief  Computes volume, area, shape index, center of mass,\ninertia tensor and principal axes of a polyhedral mesh of constant density\n\\details Computes the volume, the surface area, and the\nnormalized shape index, center of mass and inertia tensor of a topologically-closed, constant-density polyhedron.\nThis class will always use results expressed in `meters` as their distance unit (e.g center-of-mass coordinates in meters, volume in m^3,...) . Unit consistency is enforced through the use of the SetScaleMeters()\nand SetScaleKiloMeters() method. \n\nSee \"Inertia of Any Polyhedron\" by Anthony R. Dobrovolskis, Icarus 124, 698–704 (1996) Article No. 0243\nfor further details.  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n\\copyright MIT License, Benjamin Bercovici and Jay McMahon\n*/\n\n#ifndef SBGATMassProperties_h\n#define SBGATMassProperties_h\n\n#include <vtkFiltersCoreModule.h> // For export macro\n#include <vtkPolyDataAlgorithm.h>\n#include <armadillo>\n#include <SBGATFilter.hpp>\n\nclass VTKFILTERSCORE_EXPORT SBGATMassProperties : public SBGATFilter{\npublic:\n  /**\n   * Constructs with initial values of zero.\n   */\n  static SBGATMassProperties *New();\n\n  vtkTypeMacro(SBGATMassProperties,vtkPolyDataAlgorithm);\n  void PrintSelf(std::ostream& os, vtkIndent indent) override;\n  void PrintHeader(std::ostream& os, vtkIndent indent) override;\n  void PrintTrailer(std::ostream& os, vtkIndent indent) override;\n\n  /**\n   * Compute and return the volume (m^3)\n   */\n  double GetVolume() const { return this->Volume;}\n\n  /**\n   * Compute and return the projected volume.\n   * Typically you should compare this volume to the value returned by GetVolume\n   * if you get an error (GetVolume()-GetVolumeProjected())*10000 that is greater\n   * than GetVolume() this should identify a problem:\n   * * Either the polydata is not closed\n   * * Or the polydata contains triangle that are flipped\n   */\n  double GetVolumeProjected() const { return this->VolumeProjected;}\n\n  /**\n   * Compute and return the volume projected on to each axis aligned plane.\n   */\n  double GetVolumeX() { return this->VolumeX;}\n  double GetVolumeY() { return this->VolumeY;}\n  double GetVolumeZ() { return this->VolumeZ;}\n\n  /**\n   * Compute and return the weighting factors for the maximum unit\n   * normal component (MUNC).\n   */\n  double GetKx() const { return this->Kx;}\n  double GetKy() const { return this->Ky;}\n  double GetKz() const { return this->Kz;}\n\n  /**\n   * Compute and return the area in m^2\n   */\n  double GetSurfaceArea()  const{ return this->SurfaceArea;\n  }\n\n  /**\n   * Compute and return the min cell area in m^2\n   */\n  double GetMinCellArea()  const{ return this->MinCellArea;\n  }\n\n  /**\n   * Compute and return the max cell area in m^2\n   */\n  double GetMaxCellArea()  const{ return this->MaxCellArea;\n  }\n\n\n  /**\n  Checks whether the polydata is topologically closed or open\n  If closed, the sum of the oriented surface area should be equal to zero\n  */\n  bool CheckClosed() const{ return this -> IsClosed;}\n\n  /**\n   * Compute and return the normalized shape index. This characterizes the\n   * deviation of the shape of an object from a sphere. A sphere's NSI\n   * is one. This number is always >= 1.0.\n   */\n  double GetNormalizedShapeIndex() const\n  { return this->NormalizedShapeIndex;\n  }\n\n\n  /**\n  * Compute and return the coordinates of the center of mass (m)\n  * evaluated in the frame of origin assuming a constant density distribution\n  * across the shape\n  */\n  const arma::vec::fixed<3> & GetCenterOfMass() const {\n   return this -> center_of_mass;\n }\n\n  /**\n  * Compute and return the coordinates of the center of mass (m)\n  * evaluated in the frame of origin assuming a constant density distribution\n  * across the shape\n  */\n void GetCenterOfMass(double * com) const{\n\n  com[0] = this -> center_of_mass(0);\n  com[1] = this -> center_of_mass(1);\n  com[2] = this -> center_of_mass(2);\n}\n\n  /**\n  * Compute and return the dimensionless inertia tensor\n  * evaluated in the frame of origin assuming a constant density distribution\n  * across the shape. The normalization applied to the inertia tensor is I_norm = I / (mass * r_avg ^ 2) where r_avg = cbrt(3/4*Volume/pi)\n  */\narma::mat::fixed<3,3> GetNormalizedInertiaTensor() const {\n return this -> inertia_tensor;\n}\n\n  /**\n  * Compute and return the dimensionless inertia tensor\n  * evaluated in the frame of origin assuming a constant density distribution\n  * across the shape. The normalization applied to the inertia tensor is I_norm = I / (rho) where rho is the density\n  */\narma::mat::fixed<3,3> GetUnitDensityInertiaTensor() const{\n return unit_density_inertia_tensor;\n}\n\n\n  /**\n  * Compute and return the dcm orienting the principal axes of the small body relative to \n  the body coordinates frame. That is, denoting P the principal frame and B the frame in which the\n  coordinates of the body are currently expressed, this method returns [PB]\n  @return [PB] direction cosine matrix\n  */\narma::mat::fixed<3,3> GetPrincipalAxes() const{\n return this -> principal_axes;\n}\n\n  /**\n  Computes and returns the principal dimensions (m) of the ellipsoid associated with the inertia tensor \n  tensor, sorted from the longest (smallest inertia) to shortest (largest inertia)\n  @return principal dimensions associated with inertia tensor (m)\n  */\narma::vec::fixed<3> GetPrincipalDimensions() const {\n return this -> principal_dimensions;\n}\n\n\n  /**\n  * Compute and return the normalized inertia moments assuming uniform density distribution\n  * across the shape, sorted from the smallest inertia to the largest.\n  * The normalization applied to the inertia tensor is I_norm = I / (mass * r_avg ^ 2) where r_avg = cbrt(3/4*Volume/pi)\n  */\narma::vec::fixed<3> GetNormalizedInertiaMoments() const {\n return normalized_principal_moments;\n}\n\n  /**\n  * Compute and return the inertia moments assuming uniform unit density distribution\n  * across the shape, sorted from the smallest inertia to the largest.\n  */\narma::vec::fixed<3> GetUnitDensityInertiaMoments() const {\n return unit_density_principal_moments;\n}\n\n  /**\n  Return the average radius of the shape (that is, the radius of a sphere occupying the same volume) (m)\n  */\ndouble GetAverageRadius() const {\n return this -> r_avg;\n}\n\n\n\n\n    /**\n    Computes the mass properties of the provided shape and saves the results to a JSON file\n    @param shape pointer to considered shape\n    @param path savepath (ex: \"mass_properties.json\")\n    */\nstatic void ComputeAndSaveMassProperties(vtkSmartPointer<vtkPolyData> shape,std::string path);\n\n\n  /**\n  Save the computed mass properties to a JSON file\n  @param path savepath (ex: \"mass_properties.json\")\n\n  */\nvoid SaveMassProperties(std::string path) const ;\n\n/**\n  Return signed contribution to total volume of tetrahedron subtended by facet\n  f (m^3)\n  @param f facet index\n  @return signed volume of tetrahedron subtended by facet\n  */\ndouble GetDeltaV(const int & f) const;\n\n  /**\n  Return coordinates of the tetrahedron's center-of-mass (m)\n  @param f facet index\n  @return coordinates of tetrahedron\n  */\narma::vec::fixed<3> GetDeltaCM(const int & f) const ;\n\n  /**\n  Return the unit-density tetrahedron's inertia tensor divided by tetrahedron's signed volume (m^2)\n  @param f facet index\n  @return tetrahedron's inertia tensor divided by tetrahedron's signed volume\n  */\narma::mat::fixed<3,3> GetDeltaIOverDeltaV(const int & f) const ;\n\n/**\nReturn the parametrization of the the unit-density tetrahedron's inertia tensor\n@param f facet index\n@return parametrization of the tetrahedron's inertia tensor\n*/\narma::vec::fixed<6> GetDeltaIf(const int & f) const;\n\n\nprotected:\n  SBGATMassProperties();\n  ~SBGATMassProperties() override;\n\n  int RequestData(vtkInformation* request,\n    vtkInformationVector** inputVector,\n    vtkInformationVector* outputVector) override;\n\n  \n\n  arma::vec::fixed<3> center_of_mass;\n  arma::mat::fixed<3,3> inertia_tensor;\n  arma::mat::fixed<3,3> principal_axes;\n\n  arma::vec::fixed<3> normalized_principal_moments;\n  arma::vec::fixed<3> unit_density_principal_moments;\n  arma::mat::fixed<3,3> unit_density_inertia_tensor;\n  arma::vec::fixed<3> principal_dimensions;\n\n\n  double  SurfaceArea;\n  double  MinCellArea;\n  double  MaxCellArea;\n  double  Volume;\n  double  VolumeProjected; \n  double  VolumeX;\n  double  VolumeY;\n  double  VolumeZ;\n  double  Kx;\n  double  Ky;\n  double  Kz;\n  double  NormalizedShapeIndex;\n  double r_avg;\n  bool IsClosed;\n\n\n\nprivate:\n  SBGATMassProperties(const SBGATMassProperties&) = delete;\n  void operator=(const SBGATMassProperties&) = delete;\n};\n\n#endif\n\n\n", "meta": {"hexsha": "78934b901601b1855c37b343403f98e31255ec47", "size": 9360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATMassProperties.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATMassProperties.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATMassProperties.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 31.6216216216, "max_line_length": 212, "alphanum_fraction": 0.721474359, "num_tokens": 2333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.5511743661615496}}
{"text": "// ----------------------------------------------------------------------------\n// FILENAME: timetest.cpp\n//\n// DESCRIPTION:\n//    This file contians the function that used for save the running time of\n//    computing polynomial real root isolation\n//\n// AUTHOR: Xinlong Yi\n//\n// ----------------------------------------------------------------------------\n\n#include \"budan.h\"\n#include \"poly.h\"\n#include \"range.h\"\n#include \"vincent.h\"\n#include <boost/numeric/interval/utility_fwd.hpp>\n#include <chrono>\n#include <time.h>\n\nstatic const int kTESTDEGREE = 7;\nstatic const int digit = 4; // number of digit after point\nstatic const int digit_control = std::pow(10, digit); // controler of digit\n\nstatic const double max_root = 10000;\n// static const double max_root = std::pow(2, kTESTDEGREE);\n\n/**\n * Get random double in range min to max\n */\ndouble rand_double(double min, double max) {\n  double f = (double)rand() / RAND_MAX;\n  f = min + f * (max - min);\n  f = std::ceil(f * digit_control) / digit_control;\n  return f;\n}\n\nint main() {\n  srand(time(NULL));\n\n  // Get random polynomial\n  double *coeffs = new double[kTESTDEGREE];\n\n  double budan_total = 0, vincent_total = 0;\n\n  for (int i = 0; i < 1000; i++) {\n\n    for (size_t i = 0; i <= kTESTDEGREE; i++) {\n      coeffs[i] = rand_double(-max_root, max_root);\n    }\n\n    Poly<kTESTDEGREE + 1> tt(coeffs, kTESTDEGREE);\n\n    std::cout << tt << std::endl;\n\n    // save roots\n    Range *roots = new Range[kTESTDEGREE];\n\n    // Budan\n    auto budan_start = std::chrono::high_resolution_clock::now();\n    BudanRootIsolate(coeffs, kTESTDEGREE, roots);\n    auto budan_end = std::chrono::high_resolution_clock::now();\n\n    // Vincent\n    auto vincent_start = std::chrono::high_resolution_clock::now();\n    VincentRootIsolate(coeffs, kTESTDEGREE, roots);\n    auto vincent_end = std::chrono::high_resolution_clock::now();\n\n    //     Time\n    auto budan_duration = std::chrono::duration_cast<std::chrono::microseconds>(\n        budan_end - budan_start);\n    auto vincent_duration =\n        std::chrono::duration_cast<std::chrono::microseconds>(vincent_end -\n                                                              vincent_start);\n\n    budan_total += budan_duration.count();\n    vincent_total += vincent_duration.count();\n  }\n\n  std::cout << \"Budan Theorem takes \" << budan_total / 1000.0 << \" us for \"\n            << kTESTDEGREE - 1 << \" degree\" << std::endl;\n\n  std::cout << \"Continued Fraction takes \" << vincent_total / 1000.0\n            << \" us for \" << kTESTDEGREE - 1 << \" degree\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b2b7afd39bcd07f5aabb71cb6006bbbbb8a0ae76", "size": 2562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/timetest.cpp", "max_stars_repo_name": "willyii/PolynomialRootFinding", "max_stars_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/timetest.cpp", "max_issues_repo_name": "willyii/PolynomialRootFinding", "max_issues_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-13T00:53:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-13T00:53:54.000Z", "max_forks_repo_path": "src/timetest.cpp", "max_forks_repo_name": "willyii/PolynomialRootFinding", "max_forks_repo_head_hexsha": "18c7edd8fadf3dc48d2dc6480f0cf6f624cea80f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T12:54:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T12:54:48.000Z", "avg_line_length": 29.4482758621, "max_line_length": 80, "alphanum_fraction": 0.5991412959, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.5511204742613527}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_HPP\n#define STAN_MATH_PRIM_MAT_FUN_QUAD_FORM_HPP\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/prim/mat/fun/dot_product.hpp>\n#include <stan/math/prim/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/transpose.hpp>\n\nnamespace stan {\n  namespace math {\n    /**\n     * Compute B^T A B\n     **/\n    template<int RA, int CA, int RB, int CB, typename T>\n    inline Eigen::Matrix<T, CB, CB>\n    quad_form(const Eigen::Matrix<T, RA, CA>& A,\n              const Eigen::Matrix<T, RB, CB>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n      return multiply(transpose(B), multiply(A, B));\n    }\n\n    template<int RA, int CA, int RB, typename T>\n    inline T\n    quad_form(const Eigen::Matrix<T, RA, CA>& A,\n              const Eigen::Matrix<T, RB, 1>& B) {\n      check_square(\"quad_form\", \"A\", A);\n      check_multiplicable(\"quad_form\", \"A\", A, \"B\", B);\n      return dot_product(B, multiply(A, B));\n    }\n\n  }\n}\n\n#endif\n\n", "meta": {"hexsha": "1d8eb09be4a05741ef2d16c29636d52d41378331", "size": 1267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/quad_form.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/quad_form.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/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": 30.1666666667, "max_line_length": 57, "alphanum_fraction": 0.6574585635, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.5511062110372822}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2015  IBM Corporation and others\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 <boost/math/distributions/chi_squared.hpp>\n#include \"MathUtils.hpp\"\n#include \"LocException.hpp\"\n\ndouble MathUtils::quantileChiSquaredDistribution(int degreeOfFreedom, double cumulativeDensity){\n    boost::math::chi_squared chi_sq(degreeOfFreedom);\n    double x = boost::math::quantile(chi_sq, cumulativeDensity);\n    return x;\n}\n\nDirectionalStatistics MathUtils::computeDirectionalStatistics(std::vector<double> orientations){\n    size_t n = orientations.size();\n    if(n==0){\n        BOOST_THROW_EXCEPTION(LocException(\"The size of input orientation vector is zero.\"));\n    }\n    double x = 0, y = 0;\n    for(auto ori : orientations){\n        x += std::cos(ori);\n        y += std::sin(ori);\n    }\n    x /= n;\n    y /= n;\n    double meanOri = std::atan2(y,x);\n    double R = std::sqrt(x*x + y*y);\n    double v = 1.0 - R;\n    DirectionalStatistics oristat(meanOri, v);\n    return oristat;\n}\n\nWrappedNormalParameter MathUtils::computeWrappedNormalParameters(const std::vector<double>& orientations){\n\n    size_t n = orientations.size();\n    \n    DirectionalStatistics dstats = MathUtils::computeDirectionalStatistics(orientations);\n    \n    double mu = dstats.circularMean();\n    double R = 1.0 - dstats.circularVariance();\n    \n    double R2 = R*R>1.0/n? R*R : 1.0/n;\n    double Re2 = (double)n/(n-1)*(R2 - 1.0/n);\n    \n    double sigma2 = std::log(1.0/Re2);\n    double sigma =  sigma2>0? std::sqrt(sigma2) : 0.0;\n    \n    WrappedNormalParameter param(mu, sigma);\n    return param;\n}\n", "meta": {"hexsha": "309da58553088c915d0bf8a44130275453a1fb48", "size": 2787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/utils/MathUtils.cpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-06-13T20:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T17:29:32.000Z", "max_issues_repo_path": "ble-cpp/src/utils/MathUtils.cpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T07:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T18:20:15.000Z", "max_forks_repo_path": "ble-cpp/src/utils/MathUtils.cpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T07:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T10:03:48.000Z", "avg_line_length": 39.8142857143, "max_line_length": 106, "alphanum_fraction": 0.6677430929, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.5510392226624865}}
{"text": "#include <tagloc/tracking.h>\n#include <Eigen/Dense>\n#define USE_MATH_DEFINES\n#include <math.h>\n#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char** argv){\n\tEigen::MatrixXd t = Eigen::MatrixXd::Zero(2,1);\t\n\tEigen::MatrixXd r = Eigen::MatrixXd::Zero(2,1);\t\n\tr<<10,10;\n\tdouble th = M_PI/4;\n\tEigen::MatrixXd R = Eigen::MatrixXd::Zero(2,2);\n\tR<<cos(th),-sin(th),sin(th),cos(th);\n\tEigen::MatrixXd P = Eigen::MatrixXd::Zero(2,2);\t\n\tP<<4,0,0,1;\n\tP = R*P*R.transpose();\n\tcout<<P<<endl;\n\n\tEigen::MatrixXd cp;\n\t\n\tcout<<\"---\"<<endl;\t\n\tcp = RSN::closest_pt_ellipse(t,P,r,1);\n\tcout<<\"Expect something along [1,1]\"<<endl;\t\n\tcout<<cp<<endl;\n\t\n\tcout<<\"---\"<<endl;\t\n\tr<<-10,-10;\n\tcp = RSN::closest_pt_ellipse(t,P,r,1);\n\tcout<<\"Expect reflection of above\"<<endl;\t\n\tcout<<cp<<endl;\n\n\n\tcout<<\"---\"<<endl;\t\n\tr<<-10,-10;\n\tcout<<\"x:\"<<endl;\n\tcout<<r<<endl;\n\tth = 0;\n\tR<<cos(th),-sin(th),sin(th),cos(th);\n\tP<<4,0,0,1;\n\tP = R*P*R.transpose();\n\tcout<<P<<endl;\n\tcout<<\"cp:\"<<endl;\n\tcp = RSN::closest_pt_ellipse(t,P,r,1);\n\tcout<<cp<<endl;\n\t\n\tcout<<\"---\"<<endl;\t\n\tcout<<\"Same as above, but with target shifted to [20,0]\"<<endl;\t\n\tt<<20,0;\n\tr<<-10,-10;\n\tcout<<\"x:\"<<endl;\n\tcout<<r<<endl;\n\tth = 0;\n\tR<<cos(th),-sin(th),sin(th),cos(th);\n\tP<<4,0,0,1;\n\tP = R*P*R.transpose();\n\tcout<<P<<endl;\n\tcout<<\"cp:\"<<endl;\n\tcp = RSN::closest_pt_ellipse(t,P,r,1);\n\tcout<<cp<<endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "b22d68588de94bc8bbeab963710eebe07fe14214", "size": 1363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ellipsetest.cpp", "max_stars_repo_name": "jodavaho/tracking", "max_stars_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T00:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T09:01:59.000Z", "max_issues_repo_path": "src/ellipsetest.cpp", "max_issues_repo_name": "jodavaho/tracking", "max_issues_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T16:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T16:14:20.000Z", "max_forks_repo_path": "src/ellipsetest.cpp", "max_forks_repo_name": "jodavaho/tracking", "max_forks_repo_head_hexsha": "0f67736e7adacd9d92e315134af1438ae673eeda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.296875, "max_line_length": 65, "alphanum_fraction": 0.5935436537, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.5510087268280226}}
{"text": "#include \"forward_dynamics.h\"\n\n#include <Eigen/Cholesky>\n#include <iit/rbd/robcogen_commons.h>\n\nusing namespace iit::rbd;\n\n// Initialization of static-const data\nconst ur5::rcg::ForwardDynamics::ExtForces\n    ur5::rcg::ForwardDynamics::zeroExtForces(Force::Zero());\n\nur5::rcg::ForwardDynamics::ForwardDynamics(InertiaProperties& inertia, MotionTransforms& transforms) :\n    inertiaProps( & inertia ),\n    motionTransforms( & transforms )\n{\n    shoulder_v.setZero();\n    shoulder_c.setZero();\n    upper_arm_v.setZero();\n    upper_arm_c.setZero();\n    forearm_v.setZero();\n    forearm_c.setZero();\n    wrist_1_v.setZero();\n    wrist_1_c.setZero();\n    wrist_2_v.setZero();\n    wrist_2_c.setZero();\n    wrist_3_v.setZero();\n    wrist_3_c.setZero();\n\n    vcross.setZero();\n    Ia_r.setZero();\n\n}\n\nvoid ur5::rcg::ForwardDynamics::fd(\n    JointState& qdd,\n    const JointState& qd,\n    const JointState& tau,\n    const ExtForces& fext/* = zeroExtForces */)\n{\n    \n    shoulder_AI = inertiaProps->getTensor_shoulder();\n    shoulder_p = - fext[SHOULDER];\n    upper_arm_AI = inertiaProps->getTensor_upper_arm();\n    upper_arm_p = - fext[UPPER_ARM];\n    forearm_AI = inertiaProps->getTensor_forearm();\n    forearm_p = - fext[FOREARM];\n    wrist_1_AI = inertiaProps->getTensor_wrist_1();\n    wrist_1_p = - fext[WRIST_1];\n    wrist_2_AI = inertiaProps->getTensor_wrist_2();\n    wrist_2_p = - fext[WRIST_2];\n    wrist_3_AI = inertiaProps->getTensor_wrist_3();\n    wrist_3_p = - fext[WRIST_3];\n    // ---------------------- FIRST PASS ---------------------- //\n    // Note that, during the first pass, the articulated inertias are really\n    //  just the spatial inertia of the links (see assignments above).\n    //  Afterwards things change, and articulated inertias shall not be used\n    //  in functions which work specifically with spatial inertias.\n    \n    // + Link shoulder\n    //  - The spatial velocity:\n    shoulder_v(AZ) = qd(SHOULDER_PAN);\n    \n    //  - The bias force term:\n    shoulder_p += vxIv(qd(SHOULDER_PAN), shoulder_AI);\n    \n    // + Link upper_arm\n    //  - The spatial velocity:\n    upper_arm_v = (motionTransforms-> fr_upper_arm_X_fr_shoulder) * shoulder_v;\n    upper_arm_v(AZ) += qd(SHOULDER_LIFT);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(upper_arm_v, vcross);\n    upper_arm_c = vcross.col(AZ) * qd(SHOULDER_LIFT);\n    \n    //  - The bias force term:\n    upper_arm_p += vxIv(upper_arm_v, upper_arm_AI);\n    \n    // + Link forearm\n    //  - The spatial velocity:\n    forearm_v = (motionTransforms-> fr_forearm_X_fr_upper_arm) * upper_arm_v;\n    forearm_v(AZ) += qd(ELBOW);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(forearm_v, vcross);\n    forearm_c = vcross.col(AZ) * qd(ELBOW);\n    \n    //  - The bias force term:\n    forearm_p += vxIv(forearm_v, forearm_AI);\n    \n    // + Link wrist_1\n    //  - The spatial velocity:\n    wrist_1_v = (motionTransforms-> fr_wrist_1_X_fr_forearm) * forearm_v;\n    wrist_1_v(AZ) += qd(WR1);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(wrist_1_v, vcross);\n    wrist_1_c = vcross.col(AZ) * qd(WR1);\n    \n    //  - The bias force term:\n    wrist_1_p += vxIv(wrist_1_v, wrist_1_AI);\n    \n    // + Link wrist_2\n    //  - The spatial velocity:\n    wrist_2_v = (motionTransforms-> fr_wrist_2_X_fr_wrist_1) * wrist_1_v;\n    wrist_2_v(AZ) += qd(WR2);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(wrist_2_v, vcross);\n    wrist_2_c = vcross.col(AZ) * qd(WR2);\n    \n    //  - The bias force term:\n    wrist_2_p += vxIv(wrist_2_v, wrist_2_AI);\n    \n    // + Link wrist_3\n    //  - The spatial velocity:\n    wrist_3_v = (motionTransforms-> fr_wrist_3_X_fr_wrist_2) * wrist_2_v;\n    wrist_3_v(AZ) += qd(WR3);\n    \n    //  - The velocity-product acceleration term:\n    motionCrossProductMx<Scalar>(wrist_3_v, vcross);\n    wrist_3_c = vcross.col(AZ) * qd(WR3);\n    \n    //  - The bias force term:\n    wrist_3_p += vxIv(wrist_3_v, wrist_3_AI);\n    \n    \n    // ---------------------- SECOND PASS ---------------------- //\n    Matrix66 IaB;\n    Force pa;\n    \n    // + Link wrist_3\n    wrist_3_u = tau(WR3) - wrist_3_p(AZ);\n    wrist_3_U = wrist_3_AI.col(AZ);\n    wrist_3_D = wrist_3_U(AZ);\n    \n    compute_Ia_revolute(wrist_3_AI, wrist_3_U, wrist_3_D, Ia_r);  // same as: Ia_r = wrist_3_AI - wrist_3_U/wrist_3_D * wrist_3_U.transpose();\n    pa = wrist_3_p + Ia_r * wrist_3_c + wrist_3_U * wrist_3_u/wrist_3_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_wrist_3_X_fr_wrist_2, IaB);\n    wrist_2_AI += IaB;\n    wrist_2_p += (motionTransforms-> fr_wrist_3_X_fr_wrist_2).transpose() * pa;\n    \n    // + Link wrist_2\n    wrist_2_u = tau(WR2) - wrist_2_p(AZ);\n    wrist_2_U = wrist_2_AI.col(AZ);\n    wrist_2_D = wrist_2_U(AZ);\n    \n    compute_Ia_revolute(wrist_2_AI, wrist_2_U, wrist_2_D, Ia_r);  // same as: Ia_r = wrist_2_AI - wrist_2_U/wrist_2_D * wrist_2_U.transpose();\n    pa = wrist_2_p + Ia_r * wrist_2_c + wrist_2_U * wrist_2_u/wrist_2_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_wrist_2_X_fr_wrist_1, IaB);\n    wrist_1_AI += IaB;\n    wrist_1_p += (motionTransforms-> fr_wrist_2_X_fr_wrist_1).transpose() * pa;\n    \n    // + Link wrist_1\n    wrist_1_u = tau(WR1) - wrist_1_p(AZ);\n    wrist_1_U = wrist_1_AI.col(AZ);\n    wrist_1_D = wrist_1_U(AZ);\n    \n    compute_Ia_revolute(wrist_1_AI, wrist_1_U, wrist_1_D, Ia_r);  // same as: Ia_r = wrist_1_AI - wrist_1_U/wrist_1_D * wrist_1_U.transpose();\n    pa = wrist_1_p + Ia_r * wrist_1_c + wrist_1_U * wrist_1_u/wrist_1_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_wrist_1_X_fr_forearm, IaB);\n    forearm_AI += IaB;\n    forearm_p += (motionTransforms-> fr_wrist_1_X_fr_forearm).transpose() * pa;\n    \n    // + Link forearm\n    forearm_u = tau(ELBOW) - forearm_p(AZ);\n    forearm_U = forearm_AI.col(AZ);\n    forearm_D = forearm_U(AZ);\n    \n    compute_Ia_revolute(forearm_AI, forearm_U, forearm_D, Ia_r);  // same as: Ia_r = forearm_AI - forearm_U/forearm_D * forearm_U.transpose();\n    pa = forearm_p + Ia_r * forearm_c + forearm_U * forearm_u/forearm_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_forearm_X_fr_upper_arm, IaB);\n    upper_arm_AI += IaB;\n    upper_arm_p += (motionTransforms-> fr_forearm_X_fr_upper_arm).transpose() * pa;\n    \n    // + Link upper_arm\n    upper_arm_u = tau(SHOULDER_LIFT) - upper_arm_p(AZ);\n    upper_arm_U = upper_arm_AI.col(AZ);\n    upper_arm_D = upper_arm_U(AZ);\n    \n    compute_Ia_revolute(upper_arm_AI, upper_arm_U, upper_arm_D, Ia_r);  // same as: Ia_r = upper_arm_AI - upper_arm_U/upper_arm_D * upper_arm_U.transpose();\n    pa = upper_arm_p + Ia_r * upper_arm_c + upper_arm_U * upper_arm_u/upper_arm_D;\n    ctransform_Ia_revolute(Ia_r, motionTransforms-> fr_upper_arm_X_fr_shoulder, IaB);\n    shoulder_AI += IaB;\n    shoulder_p += (motionTransforms-> fr_upper_arm_X_fr_shoulder).transpose() * pa;\n    \n    // + Link shoulder\n    shoulder_u = tau(SHOULDER_PAN) - shoulder_p(AZ);\n    shoulder_U = shoulder_AI.col(AZ);\n    shoulder_D = shoulder_U(AZ);\n    \n    \n    \n    // ---------------------- THIRD PASS ---------------------- //\n    shoulder_a = (motionTransforms-> fr_shoulder_X_fr_base).col(LZ) * (ur5::rcg::g);\n    qdd(SHOULDER_PAN) = (shoulder_u - shoulder_U.dot(shoulder_a)) / shoulder_D;\n    shoulder_a(AZ) += qdd(SHOULDER_PAN);\n    \n    upper_arm_a = (motionTransforms-> fr_upper_arm_X_fr_shoulder) * shoulder_a + upper_arm_c;\n    qdd(SHOULDER_LIFT) = (upper_arm_u - upper_arm_U.dot(upper_arm_a)) / upper_arm_D;\n    upper_arm_a(AZ) += qdd(SHOULDER_LIFT);\n    \n    forearm_a = (motionTransforms-> fr_forearm_X_fr_upper_arm) * upper_arm_a + forearm_c;\n    qdd(ELBOW) = (forearm_u - forearm_U.dot(forearm_a)) / forearm_D;\n    forearm_a(AZ) += qdd(ELBOW);\n    \n    wrist_1_a = (motionTransforms-> fr_wrist_1_X_fr_forearm) * forearm_a + wrist_1_c;\n    qdd(WR1) = (wrist_1_u - wrist_1_U.dot(wrist_1_a)) / wrist_1_D;\n    wrist_1_a(AZ) += qdd(WR1);\n    \n    wrist_2_a = (motionTransforms-> fr_wrist_2_X_fr_wrist_1) * wrist_1_a + wrist_2_c;\n    qdd(WR2) = (wrist_2_u - wrist_2_U.dot(wrist_2_a)) / wrist_2_D;\n    wrist_2_a(AZ) += qdd(WR2);\n    \n    wrist_3_a = (motionTransforms-> fr_wrist_3_X_fr_wrist_2) * wrist_2_a + wrist_3_c;\n    qdd(WR3) = (wrist_3_u - wrist_3_U.dot(wrist_3_a)) / wrist_3_D;\n    wrist_3_a(AZ) += qdd(WR3);\n    \n    \n}\n", "meta": {"hexsha": "a4430d40c24b93e202a4419b8a7cb62dedf057c0", "size": 8387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rcgen/cpp/forward_dynamics.cpp", "max_stars_repo_name": "kmarkus/ublx-ur5_sim", "max_stars_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-07T11:39:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-07T11:39:31.000Z", "max_issues_repo_path": "rcgen/cpp/forward_dynamics.cpp", "max_issues_repo_name": "kmarkus/ublx-ur5_sim", "max_issues_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-11-10T16:03:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T16:03:37.000Z", "max_forks_repo_path": "rcgen/cpp/forward_dynamics.cpp", "max_forks_repo_name": "kmarkus/ublx-ur5_sim", "max_forks_repo_head_hexsha": "51efa12446a7ef9ab5e3e783ce2a6409a3db390f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-07T10:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T10:57:43.000Z", "avg_line_length": 38.1227272727, "max_line_length": 156, "alphanum_fraction": 0.666149994, "num_tokens": 2749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.5510087052582561}}
{"text": "#include <QTime>\n#include <QApplication>\n#include <QAction>\n#include <QStringList>\n\n#include \"opengl_tools.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polylines_item.h\"\n#include \"Scene_polyhedron_selection_item.h\"\n#include \"Polyhedron_type.h\"\n\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include <CGAL/convex_hull_3.h>\n#include <boost/iterator/transform_iterator.hpp>\nusing namespace CGAL::Three;\nclass Polyhedron_demo_convex_hull_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\")\npublic:\n    void init(QMainWindow* mainWindow,\n              Scene_interface* scene_interface)\n    {\n        mw = mainWindow;\n        scene = scene_interface;\n        actions_map[\"actionConvexHull\"] = getActionFromMainWindow(mw, \"actionConvexHull\");\n        actions_map[\"actionConvexHull\"]->setProperty(\"subMenuName\",\n                                                     \"3D Convex Hulls\");\n        autoConnectActions();\n\n    }\n\n  // used by Polyhedron_demo_plugin_helper\n  QStringList actionsNames() const {\n    return QStringList() << \"actionConvexHull\";\n  }\n\n  bool applicable(QAction*) const {\n    return \n      qobject_cast<Scene_polyhedron_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_polylines_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex())) ||\n      qobject_cast<Scene_polyhedron_selection_item*>(scene->item(scene->mainSelectionIndex()));\n  }\n\npublic Q_SLOTS:\n  void on_actionConvexHull_triggered();\n\n}; // end Polyhedron_demo_convex_hull_plugin\n\n// for transform iterator\nstruct Get_point {\n  typedef const Polyhedron::Point_3& result_type;\n  result_type operator()(const Polyhedron::Vertex_handle v) const\n  { return v->point(); }\n};\n\nvoid Polyhedron_demo_convex_hull_plugin::on_actionConvexHull_triggered()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  \n  Scene_polyhedron_item* poly_item = \n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  Scene_points_with_normal_item* pts_item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n  \n  Scene_polylines_item* lines_item = \n    qobject_cast<Scene_polylines_item*>(scene->item(index));\n  \n  Scene_polyhedron_selection_item* selection_item = \n    qobject_cast<Scene_polyhedron_selection_item*>(scene->item(index));\n\n  if(poly_item || pts_item || lines_item || selection_item)\n  {\n    // wait cursor\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    \n    QTime time;\n    time.start();\n    std::cout << \"Convex hull...\";\n\n    // add convex hull as new polyhedron\n    Polyhedron *pConvex_hull = new Polyhedron;\n    if(selection_item) {\n      CGAL::convex_hull_3(\n        boost::make_transform_iterator(selection_item->selected_vertices.begin(), Get_point()),\n        boost::make_transform_iterator(selection_item->selected_vertices.end(), Get_point()),\n        *pConvex_hull);\n    }\n    else if ( poly_item ){\n      Polyhedron* pMesh = poly_item->polyhedron();  \n      CGAL::convex_hull_3(pMesh->points_begin(),pMesh->points_end(),*pConvex_hull);\n    }\n    else{\n      if (pts_item)\n        CGAL::convex_hull_3(pts_item->point_set()->begin(),pts_item->point_set()->end(),*pConvex_hull);\n      else{\n        std::size_t nb_points=0;\n        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();\n            it != lines_item->polylines.end();\n            ++it)  nb_points+=it->size();\n\n        std::vector<Kernel::Point_3> all_points;\n        all_points.reserve( nb_points );\n\n        for(std::list<std::vector<Kernel::Point_3> >::const_iterator it = lines_item->polylines.begin();\n            it != lines_item->polylines.end();\n            ++it)  std::copy(it->begin(), it->end(),std::back_inserter( all_points ) );\n        \n        CGAL::convex_hull_3(all_points.begin(),all_points.end(),*pConvex_hull);\n      }\n    }\n    std::cout << \"ok (\" << time.elapsed() << \" ms)\" << std::endl;\n\n    Scene_polyhedron_item* new_item = new Scene_polyhedron_item(pConvex_hull);\n    new_item->setName(tr(\"%1 (convex hull)\").arg(scene->item(index)->name()));\n    new_item->setColor(Qt::magenta);\n    new_item->setRenderingMode(FlatPlusEdges);\n    scene->addItem(new_item);\n\n    // default cursor\n    QApplication::restoreOverrideCursor();\n  }\n}\n\n#include \"Convex_hull_plugin.moc\"\n", "meta": {"hexsha": "fac1be2b18133758f159bef1e38934e50e4daeb8", "size": 4654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.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/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.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/Polyhedron/demo/Polyhedron/Plugins/Convex_hull/Convex_hull_plugin.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": 34.7313432836, "max_line_length": 104, "alphanum_fraction": 0.7004727116, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.5509643819199032}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// sum_kahan.hpp\r\n//\r\n//  Copyright 2010 Gaetano Mendola, 2011 Simon West. 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_SUM_KAHAN_HPP_EAN_26_07_2010\r\n#define BOOST_ACCUMULATORS_STATISTICS_SUM_KAHAN_HPP_EAN_26_07_2010\r\n\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/sum.hpp>\r\n#include <boost/accumulators/statistics/weighted_sum_kahan.hpp>\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n\r\n#if _MSC_VER > 1400\r\n# pragma float_control(push)\r\n# pragma float_control(precise, on)\r\n#endif\r\n\r\ntemplate<typename Sample, typename Tag>\r\nstruct sum_kahan_impl\r\n  : accumulator_base\r\n{\r\n    typedef Sample result_type;\r\n\r\n    ////////////////////////////////////////////////////////////////////////////\r\n    // sum_kahan_impl\r\n    /**\r\n        @brief Kahan summation algorithm\r\n\r\n        The Kahan summation algorithm reduces the numerical error obtained with standard\r\n        sequential sum.\r\n\r\n    */\r\n    template<typename Args>\r\n    sum_kahan_impl(Args const & args)\r\n      : sum(args[parameter::keyword<Tag>::get() | Sample()]),\r\n        compensation(boost::numeric_cast<Sample>(0.0))\r\n    {\r\n    }\r\n\r\n    template<typename Args>\r\n    void \r\n#if BOOST_ACCUMULATORS_GCC_VERSION > 40305\r\n    __attribute__((optimize(\"no-associative-math\")))\r\n#endif\r\n    operator ()(Args const & args)\r\n    {\r\n        const Sample myTmp1 = args[parameter::keyword<Tag>::get()] - this->compensation;\r\n        const Sample myTmp2 = this->sum + myTmp1;\r\n        this->compensation = (myTmp2 - this->sum) - myTmp1;\r\n        this->sum = myTmp2;\r\n    }\r\n\r\n    result_type result(dont_care) const\r\n    {\r\n      return this->sum;\r\n    }\r\n\r\nprivate:\r\n    Sample sum;\r\n    Sample compensation;\r\n};\r\n\r\n#if _MSC_VER > 1400\r\n# pragma float_control(pop)\r\n#endif\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::sum_kahan\r\n// tag::sum_of_weights_kahan\r\n// tag::sum_of_variates_kahan\r\n//\r\nnamespace tag\r\n{\r\n\r\n    struct sum_kahan\r\n      : depends_on<>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef impl::sum_kahan_impl< mpl::_1, tag::sample > impl;\r\n    };\r\n\r\n    struct sum_of_weights_kahan\r\n      : depends_on<>\r\n    {\r\n        typedef mpl::true_ is_weight_accumulator;\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::sum_kahan_impl<mpl::_2, tag::weight> impl;\r\n    };\r\n\r\n    template<typename VariateType, typename VariateTag>\r\n    struct sum_of_variates_kahan\r\n      : depends_on<>\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef mpl::always<accumulators::impl::sum_kahan_impl<VariateType, VariateTag> > impl;\r\n    };\r\n\r\n} // namespace tag\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::sum_kahan\r\n// extract::sum_of_weights_kahan\r\n// extract::sum_of_variates_kahan\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::sum_kahan> const sum_kahan = {};\r\n    extractor<tag::sum_of_weights_kahan> const sum_of_weights_kahan = {};\r\n    extractor<tag::abstract_sum_of_variates> const sum_of_variates_kahan = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_kahan)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_weights_kahan)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_variates_kahan)\r\n} // namespace extract\r\n\r\nusing extract::sum_kahan;\r\nusing extract::sum_of_weights_kahan;\r\nusing extract::sum_of_variates_kahan;\r\n\r\n// sum(kahan) -> sum_kahan\r\ntemplate<>\r\nstruct as_feature<tag::sum(kahan)>\r\n{\r\n    typedef tag::sum_kahan type;\r\n};\r\n\r\n// sum_of_weights(kahan) -> sum_of_weights_kahan\r\ntemplate<>\r\nstruct as_feature<tag::sum_of_weights(kahan)>\r\n{\r\n    typedef tag::sum_of_weights_kahan type;\r\n};\r\n\r\n// So that sum_kahan can be automatically substituted with\r\n// weighted_sum_kahan when the weight parameter is non-void.\r\ntemplate<>\r\nstruct as_weighted_feature<tag::sum_kahan>\r\n{\r\n    typedef tag::weighted_sum_kahan type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::weighted_sum_kahan>\r\n  : feature_of<tag::sum>\r\n{};\r\n\r\n// for the purposes of feature-based dependency resolution,\r\n// sum_kahan provides the same feature as sum\r\ntemplate<>\r\nstruct feature_of<tag::sum_kahan>\r\n  : feature_of<tag::sum>\r\n{\r\n};\r\n\r\n// for the purposes of feature-based dependency resolution,\r\n// sum_of_weights_kahan provides the same feature as sum_of_weights\r\ntemplate<>\r\nstruct feature_of<tag::sum_of_weights_kahan>\r\n  : feature_of<tag::sum_of_weights>\r\n{\r\n};\r\n\r\ntemplate<typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::sum_of_variates_kahan<VariateType, VariateTag> >\r\n  : feature_of<tag::abstract_sum_of_variates>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "a1f74d90329ae80415fe174bbc6e9d56d34d73c7", "size": 5074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/accumulators/statistics/sum_kahan.hpp", "max_stars_repo_name": "dyzmapl/BumpTop", "max_stars_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "trunk/win/Source/Includes/Boost/accumulators/statistics/sum_kahan.hpp", "max_issues_repo_name": "dyzmapl/BumpTop", "max_issues_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-11-07T04:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:34:12.000Z", "max_forks_repo_path": "trunk/win/Source/Includes/Boost/accumulators/statistics/sum_kahan.hpp", "max_forks_repo_name": "dyzmapl/BumpTop", "max_forks_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 26.8465608466, "max_line_length": 96, "alphanum_fraction": 0.6499802917, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.55096436710516}}
{"text": "/**\n * @file layer_main.cc\n * @brief Solves CD BVP for exact solution with an internal layer\n * @author Philippe Peter\n * @date July 2020\n * @copyright Developed at SAM, ETH Zurich\n */\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <memory>\n#include <string>\n\n#include \"cd_tools.h\"\n#include \"standard_fem.h\"\n#include \"supg.h\"\n#include \"upwind.h\"\n\nint main() {\n  // parameter functions:\n  // boundary conditions\n  const auto g = [](const Eigen::Vector2d &x) {\n    return x(0) > x(1) ? 1.0 : 0.0;\n  };\n  // velocity field\n  const auto v = [](const Eigen::Vector2d &x) {\n    return Eigen::Vector2d(1.0, 1.0);\n  };\n  // diffusion coefficient\n  const auto eps = [](const Eigen::Vector2d &x) { return 10E-10; };\n  // source function\n  const auto f = [](const Eigen::Vector2d &x) { return 0.0; };\n\n  // Read Mesh from file\n  std::string mesh_file = CURRENT_SOURCE_DIR \"/meshes/mesh_square.msh\";\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh_p = reader.mesh();\n\n  // Construct dofhanlder for linear finite element space on the mesh.\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  // Compute solutions using Standard FE, Upwind, SUPG method\n  Eigen::VectorXd sol_standard =\n      ConvectionDiffusion::SolveCDBVPStandardFem(fe_space, eps, v, f, g);\n  lf::fe::MeshFunctionFE sol_standard_mf(fe_space, sol_standard);\n\n  Eigen::VectorXd sol_stable =\n      ConvectionDiffusion::SolveCDBVPUpwind(fe_space, eps, v, f, g);\n  lf::fe::MeshFunctionFE sol_upwind_mf(fe_space, sol_stable);\n\n  Eigen::VectorXd sol_supg =\n      ConvectionDiffusion::SolveCDBVPSupg(fe_space, eps, v, f, g);\n  lf::fe::MeshFunctionFE sol_supg_mf(fe_space, sol_supg);\n\n  // Output solution along the curve gamma\n  auto gamma = [](double t) { return Eigen::Vector2d(t, 1 - t); };\n  ConvectionDiffusion::SampleMeshFunction(\"results_standard_FEM.txt\", mesh_p,\n                                          gamma, sol_standard_mf, 300);\n  ConvectionDiffusion::SampleMeshFunction(\"results_upwind.txt\", mesh_p, gamma,\n                                          sol_upwind_mf, 300);\n  ConvectionDiffusion::SampleMeshFunction(\"results_supg.txt\", mesh_p, gamma,\n                                          sol_supg_mf, 300);\n\n  // Plot\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_layer.py \" CURRENT_BINARY_DIR);\n  return 0;\n}", "meta": {"hexsha": "5bdfb2fb867e5824f0b8354b8afa5813ad14ca7d", "size": 2538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/ConvectionDiffusion/layer_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "lecturecodes/ConvectionDiffusion/layer_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "lecturecodes/ConvectionDiffusion/layer_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 34.7671232877, "max_line_length": 78, "alphanum_fraction": 0.6698187549, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.5509366446642434}}
{"text": "#pragma once\n\n#include <cstdint>\n#include <cmath>\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n#include <crest/geometry/indexed_mesh.hpp>\n#include <crest/util/eigen_extensions.hpp>\n#include <crest/quadrature/triquad.hpp>\n#include <crest/basis/basis.hpp>\n\nnamespace crest\n{\n    /**\n     * A standard linear Lagrangian basis\n     */\n    template <typename Scalar>\n    class LagrangeBasis2d : public Basis<Scalar, LagrangeBasis2d<Scalar>>\n    {\n    public:\n        explicit LagrangeBasis2d(const IndexedMesh<Scalar, int> & mesh) : _mesh(mesh) {}\n\n        virtual std::vector<int> boundary_nodes() const override { return _mesh.boundary_vertices(); }\n        virtual std::vector<int> interior_nodes() const override { return _mesh.compute_interior_vertices(); }\n\n        virtual Assembly<Scalar> assemble() const override;\n\n        virtual int num_dof() const override { return _mesh.num_vertices(); }\n\n        template <typename Function2d>\n        VectorX<Scalar> interpolate(const Function2d &f) const;\n\n        template <typename Function2d>\n        VectorX<Scalar> interpolate_boundary(const Function2d &f) const;\n\n        template <int QuadStrength, typename Function2d>\n        VectorX<Scalar> load(const Function2d &f) const;\n\n        template <int QuadStrength, typename Function2d>\n        Scalar error_l2(const Function2d &f, const VectorX<Scalar> & weights) const;\n\n        template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n        Scalar error_h1_semi(const Function2d_x & f_x,\n                             const Function2d_y & f_y,\n                             const VectorX<Scalar> & weights) const;\n\n    private:\n        const IndexedMesh<double, int> & _mesh;\n    };\n\n    namespace detail\n    {\n        template <typename Scalar>\n        struct assembly_triplets {\n            std::vector<Eigen::Triplet<Scalar>> stiffness_triplets;\n            std::vector<Eigen::Triplet<Scalar>> mass_triplets;\n        };\n\n        template <typename Scalar>\n        assembly_triplets<Scalar> assemble_linear_lagrangian_system_triplets(\n                const crest::IndexedMesh<Scalar, int> & mesh);\n    }\n\n    /*\n     * IMPLEMENTATION BELOW\n     */\n\n    template <typename Scalar>\n    detail::assembly_triplets<Scalar> detail::assemble_linear_lagrangian_system_triplets(\n            const crest::IndexedMesh<Scalar, int> & mesh)\n    {\n        const static Eigen::Matrix<Scalar, 3, 3> M_LOCAL_REF = (1.0 / 24.0) * (Eigen::Matrix3d()\n                <<\n                2.0, 1.0, 1.0,\n                1.0, 2.0, 1.0,\n                1.0, 1.0, 2.0\n        ).finished().cast<Scalar>();\n\n        const static Eigen::Matrix<Scalar, 3, 3> A11 = (1.0 / 2.0) * (Eigen::Matrix3d()\n                <<\n                1.0, 0.0, -1.0,\n                0.0, 0.0, 0.0,\n                -1.0, 0.0, 1.0\n        ).finished().cast<Scalar>();\n\n        const static Eigen::Matrix<Scalar, 3, 3> A12 = (1.0 / 2.0) * (Eigen::Matrix3d()\n                <<\n                0.0, 1.0, -1.0,\n                1.0, 0.0, -1.0,\n                -1.0, -1.0, 2.0\n        ).finished().cast<Scalar>();\n\n        const static Eigen::Matrix<Scalar, 3, 3> A22 = (1.0 / 2.0) * (Eigen::Matrix3d()\n                <<\n                0.0, 0.0, 0.0,\n                0.0, 1.0, -1.0,\n                0.0, -1.0, 1.0\n        ).finished().cast<Scalar>();\n\n        std::vector<Eigen::Triplet<Scalar>> mass_triplets;\n        std::vector<Eigen::Triplet<Scalar>> stiffness_triplets;\n        mass_triplets.reserve(3 * mesh.num_elements());\n        stiffness_triplets.reserve(3 * mesh.num_elements());\n\n        for (const auto & element : mesh.elements())\n        {\n            const auto a = mesh.vertices()[element.vertex_indices[0]];\n            const auto b = mesh.vertices()[element.vertex_indices[1]];\n            const auto c = mesh.vertices()[element.vertex_indices[2]];\n\n            const auto v1 = a - c;\n            const auto v2 = b - c;\n\n            const Eigen::Matrix2d jacobian = (Eigen::Matrix2d() << v1.x, v2.x, v1.y, v2.y).finished();\n            const Eigen::Matrix2d jacobian_inverse = jacobian.inverse();\n            const Eigen::Matrix2d C = jacobian_inverse * jacobian_inverse.transpose();\n            const auto abs_det_jacobian = std::abs(jacobian.determinant());\n\n            const Eigen::Matrix<Scalar, 3, 3> A_local = abs_det_jacobian * (C(0, 0) * A11 + C(0, 1) * A12 + C(1, 1) * A22);\n            const Eigen::Matrix<Scalar, 3, 3> M_local = abs_det_jacobian * M_LOCAL_REF;\n\n            typedef Eigen::Triplet<Scalar> T;\n            for (size_t i = 0; i < 3; ++i)\n            {\n                for (size_t j = 0; j < 3; ++j)\n                {\n                    const auto I = element.vertex_indices[i];\n                    const auto J = element.vertex_indices[j];\n                    mass_triplets.emplace_back(T(I, J, M_local(i, j)));\n                    stiffness_triplets.emplace_back(T(I, J, A_local(i, j)));\n                }\n            }\n        }\n\n        return detail::assembly_triplets<Scalar> {\n                std::move(stiffness_triplets),\n                std::move(mass_triplets)\n        };\n    }\n\n    template <typename Scalar>\n    Assembly<Scalar> LagrangeBasis2d<Scalar>::assemble() const\n    {\n        const auto triplets = detail::assemble_linear_lagrangian_system_triplets(_mesh);\n\n        Assembly<Scalar> assembly;\n\n        // Stiffness\n        assembly.stiffness = Eigen::SparseMatrix<Scalar>(num_dof(), num_dof());\n        assembly.stiffness.setFromTriplets(triplets.stiffness_triplets.cbegin(), triplets.stiffness_triplets.cend());\n\n        // Mass\n        assembly.mass = Eigen::SparseMatrix<Scalar>(num_dof(), num_dof());\n        assembly.mass.setFromTriplets(triplets.mass_triplets.cbegin(), triplets.mass_triplets.cend());\n\n        return assembly;\n    }\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d>\n    VectorX<Scalar> LagrangeBasis2d<Scalar>::load(const Function2d & f) const\n    {\n        Eigen::VectorXd load(_mesh.num_vertices());\n        load.setZero();\n\n        // See triquad.hpp for the mapping used here\n        const auto a_basis = [] (auto x, auto  ) { return Scalar(0.5) * x + Scalar(0.5); };\n        const auto b_basis = [] (auto  , auto y) { return Scalar(0.5) * y + Scalar(0.5); };\n        const auto c_basis = [] (auto x, auto y) { return Scalar(0.5) * (-x - y); };\n\n        for (const auto element : _mesh.elements())\n        {\n            const auto z0 = element.vertex_indices[0];\n            const auto z1 = element.vertex_indices[1];\n            const auto z2 = element.vertex_indices[2];\n\n            const auto & a = _mesh.vertices()[z0];\n            const auto & b = _mesh.vertices()[z1];\n            const auto & c = _mesh.vertices()[z2];\n            const auto transform = triquad_transform(a, b, c);\n            const auto transformed_f = [&f, &transform] (auto x, auto y)\n            {\n                const auto coords = transform.transform_from_reference(x, y);\n                return f(coords.x, coords.y);\n            };\n\n            const auto absdet = transform.absolute_determinant();\n\n            load(z0) += absdet * triquad_ref<QuadStrength, Scalar>(\n                    [&] (auto x, auto y) { return transformed_f(x, y) * a_basis(x, y); }\n            );\n            load(z1) += absdet * triquad_ref<QuadStrength, Scalar>(\n                    [&] (auto x, auto y) { return transformed_f(x, y) * b_basis(x, y); }\n            );\n            load(z2) += absdet * triquad_ref<QuadStrength, Scalar>(\n                    [&] (auto x, auto y) { return transformed_f(x, y) * c_basis(x, y); }\n            );\n        }\n\n        return load;\n    }\n\n    template <typename Scalar>\n    template <typename Function2d>\n    VectorX<Scalar> LagrangeBasis2d<Scalar>::interpolate(const Function2d & f) const\n    {\n        // Simple nodal interpolation\n        auto result = VectorX<Scalar>(_mesh.num_vertices());\n        for (int i = 0; i < _mesh.num_vertices(); ++i)\n        {\n            const auto vertex = _mesh.vertices()[i];\n            result(i) = f(vertex.x, vertex.y);\n        }\n        return result;\n    }\n\n    template <typename Scalar>\n    template <typename Function2d>\n    VectorX<Scalar> LagrangeBasis2d<Scalar>::interpolate_boundary(const Function2d & f) const\n    {\n        // Simple nodal interpolation\n        auto result = VectorX<Scalar>(_mesh.num_boundary_vertices());\n        const auto & boundary_indices = _mesh.boundary_vertices();\n        for (int i = 0; i < _mesh.num_boundary_vertices(); ++i)\n        {\n            const auto vertex_index = boundary_indices[i];\n            const auto vertex = _mesh.vertices()[vertex_index];\n            result(i) = f(vertex.x, vertex.y);\n        }\n        return result;\n    }\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d>\n    Scalar LagrangeBasis2d<Scalar>::error_l2(const Function2d &f, const VectorX<Scalar> & weights) const\n    {\n        Scalar error_squared = Scalar(0);\n\n        // See triquad.hpp for the mapping used here\n        const auto basis0 = [] (auto x, auto  ) { return Scalar(0.5) * x + Scalar(0.5); };\n        const auto basis1 = [] (auto  , auto y) { return Scalar(0.5) * y + Scalar(0.5); };\n        const auto basis2 = [] (auto x, auto y) { return Scalar(0.5) * (-x - y); };\n\n#pragma omp parallel for reduction(+:error_squared)\n        for (int element_index = 0; element_index < _mesh.num_elements(); ++element_index)\n        {\n            const auto element = _mesh.elements()[element_index];\n            const auto z0 = element.vertex_indices[0];\n            const auto z1 = element.vertex_indices[1];\n            const auto z2 = element.vertex_indices[2];\n\n            const auto w0 = weights(z0);\n            const auto w1 = weights(z1);\n            const auto w2 = weights(z2);\n\n            const auto & a = _mesh.vertices()[z0];\n            const auto & b = _mesh.vertices()[z1];\n            const auto & c = _mesh.vertices()[z2];\n            const auto transform = triquad_transform(a, b, c);\n            const auto f_ref = [&f, &transform] (auto x, auto y)\n            {\n                const auto coords = transform.transform_from_reference(x, y);\n                return f(coords.x, coords.y);\n            };\n\n            // Computes the square of the difference of f and f_h in the reference triangle\n            const auto diff_ref_squared = [&] (auto x, auto y)\n            {\n                const auto f_h_ref = w0 * basis0(x, y) +\n                                     w1 * basis1(x, y) +\n                                     w2 * basis2(x, y);\n\n                const auto diff = f_ref(x, y) - f_h_ref;\n                return diff * diff;\n            };\n\n            const auto absdet = transform.absolute_determinant();\n            error_squared += absdet * triquad_ref<QuadStrength, Scalar>(diff_ref_squared);\n        }\n\n        return std::sqrt(error_squared);\n    };\n\n\n    template <typename Scalar>\n    template <int QuadStrength, typename Function2d_x, typename Function2d_y>\n    Scalar LagrangeBasis2d<Scalar>::error_h1_semi(const Function2d_x & f_x,\n                                                  const Function2d_y & f_y,\n                                                  const VectorX<Scalar> & weights) const\n    {\n        Scalar error_squared = Scalar(0);\n\n        // See triquad.hpp for the mapping used here\n        const auto basis0_x = Scalar(0.5);\n        const auto basis0_y = Scalar(0.0);\n        const auto basis1_x = Scalar(0.0);\n        const auto basis1_y = Scalar(0.5);\n        const auto basis2_x = Scalar(-0.5);\n        const auto basis2_y = Scalar(-0.5);\n\n#pragma omp parallel for reduction(+:error_squared)\n        for (int element_index = 0; element_index < _mesh.num_elements(); ++element_index)\n        {\n            const auto element = _mesh.elements()[element_index];\n            const auto z0 = element.vertex_indices[0];\n            const auto z1 = element.vertex_indices[1];\n            const auto z2 = element.vertex_indices[2];\n\n            const auto w0 = weights(z0);\n            const auto w1 = weights(z1);\n            const auto w2 = weights(z2);\n\n            const auto & a = _mesh.vertices()[z0];\n            const auto & b = _mesh.vertices()[z1];\n            const auto & c = _mesh.vertices()[z2];\n            const auto transform = triquad_transform(a, b, c);\n\n            const auto f_grad_ref = [&f_x, &f_y, &transform] (auto x, auto y)\n            {\n                const auto coords = transform.transform_from_reference(x, y);\n                Eigen::Matrix<Scalar, 2, 1> grad;\n                grad(0) = f_x(coords.x, coords.y);\n                grad(1) = f_y(coords.x, coords.y);\n                return grad;\n            };\n\n            // Since we have linear elements, the gradients are constants\n            Eigen::Matrix<Scalar, 2, 1> f_h_grad_ref;\n            f_h_grad_ref(0) = w0 * basis0_x +\n                              w1 * basis1_x +\n                              w2 * basis2_x;\n            f_h_grad_ref(1) = w0 * basis0_y +\n                              w1 * basis1_y +\n                              w2 * basis2_y;\n\n            // Due to change of variables, we have to left-apply J^-T\n            const Eigen::Matrix<Scalar, 2, 2> J_inv_t = transform.jacobian().inverse().transpose();\n            const Eigen::Matrix<Scalar, 2, 1> f_h_grad_ref_transformed = J_inv_t * f_h_grad_ref;\n\n            // Computes the square of the difference of grad(f) and grad(f_h)\n            // in the reference triangle\n            const auto diff_squared = [&] (auto x, auto y)\n            {\n                // Note that J_inv_t cancels with J_t for f_grad_ref\n                const Eigen::Matrix<Scalar, 2, 1> diff = f_grad_ref(x, y) - f_h_grad_ref_transformed;\n                return diff.dot(diff);\n            };\n\n            const auto absdet = transform.absolute_determinant();\n            error_squared += absdet * triquad_ref<QuadStrength, Scalar>(diff_squared);\n        }\n\n        return std::sqrt(error_squared);\n    };\n}\n", "meta": {"hexsha": "cd0fda5ef1e5be800f6760abebc8ffbb546bd116", "size": 14007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/basis/lagrange_basis2d.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/basis/lagrange_basis2d.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/basis/lagrange_basis2d.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": 39.125698324, "max_line_length": 123, "alphanum_fraction": 0.5632183908, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.5509366395077875}}
{"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\ntemplate <typename T>\nstd::unordered_map<size_t, T> group_count(std::vector<T>& v) {\n\tstd::unordered_map<size_t, T> c;\n\tfor(T& e : v) {\n\t\tc[e]++;\n\t}\n\treturn c;\n}\n\ndouble memo[301][301][301];\n\ndouble solve(int n, int c1, int c2, int c3) {\n\tif(memo[c1][c2][c3] >= 0) {\n\t\treturn memo[c1][c2][c3];\n\t}\n\tif(c1 == 0 && c2 == 0 && c3 == 0) {\n\t\treturn 0.0;\n\t}\n\n\treturn memo[c1][c2][c3] =\n\t\t\t   ((c1 > 0 ? (solve(n, c1 - 1, c2, c3) * c1) : 0.0) +\n\t\t\t\t(c2 > 0 ? (solve(n, c1 + 1, c2 - 1, c3) * c2) : 0.0) +\n\t\t\t\t(c3 > 0 ? (solve(n, c1, c2 + 1, c3 - 1) * c3) : 0.0) + n) /\n\t\t\t   static_cast<double>(c1 + c2 + c3);\n}\n\nint main() {\n\tint n;\n\tcin >> n;\n\tVI a(n);\n\tREP(i, n) { cin >> a[i]; }\n\tunordered_map<size_t, int> cnt = group_count(a);\n\tFILL(memo, -1);\n\tcout << PRECISION(15) << solve(n, cnt[1], cnt[2], cnt[3]) << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "4f5d01af4c37260eb23d4dbed5c2b4dd5e8d24d7", "size": 2390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/Educational_DP_Contest/J.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/Educational_DP_Contest/J.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/Educational_DP_Contest/J.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": 21.9266055046, "max_line_length": 76, "alphanum_fraction": 0.5983263598, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.6477982315512488, "lm_q1q2_score": 0.5506098343080754}}
{"text": "/*!\n  \\file gpp_math.cpp\n  \\rst\n  These comments are getting to be of some length, so here's a table of contents:\n\n  1. FILE OVERVIEW\n  2. IMPLEMENTATION NOTES\n  3. MATHEMATICAL OVERVIEW\n\n     a. GAUSSIAN PROCESSES\n     b. SAMPLING FROM GPs\n     c. EXPECTED IMPROVEMENT\n\n  4. CODE DESIGN/LAYOUT OVERVIEW:\n\n     a. class GaussianProcess\n     b. class ExpectedImprovementEvaluator, OnePotentialSampleExpectedImprovementEvaluator\n     c. function ComputeOptimalPointsToSampleWithRandomStarts()\n\n  5. CODE HIERARCHY / CALL-TREE\n\n  **1. FILE OVERVIEW**\n\n  Implementations of functions for Gaussian Processes (mean, variance of GPs and their gradients) and for\n  computing and optimizing Expected Improvement (EI).\n\n  **2. IMPLEMENTATION NOTES**\n\n  See gpp_math.hpp file docs and gpp_common.hpp for a few important implementation notes\n  (e.g., restrict, memory allocation, matrix storage style, etc), as well as citation details.\n\n  Additionally, the matrix looping idioms used in this file deserve further mention: see gpp_common.hpp\n  header comments, item 7 for further details.  In summary, using matrix-vector-multiply as an example, we do::\n\n    for (int i = 0; i < m; ++i) {\n      y[i] = 0;\n      for (int j = 0; j < n; ++j) {\n        y[i] += A[j]*x[j];\n      }\n      A += n;\n    }\n\n  **3. MATHEMATICAL OVERVIEW**\n\n  Next, we provide a high-level discussion of GPs and the EI optimization process used in this file.  See\n  Rasmussen & Williams for more details on the former and Scott Clark's thesis for details on the latter.  This segment\n  is more focused on concepts and mathematical ideas.  We subsequently discuss how the classes and functions\n  in this file map onto these mathematical concepts.  If it wasn't clear, please read the file comments for\n  gpp_math.hpp before continuing (a conceptual overview).\n\n  **3a. GAUSSIAN PROCESSES**\n\n  First, a Gaussian Process (GP) is defined as a collection of normally distributed random variables (RVs); these\n  RVs are not independent nor identically-distributed (i.e., all normal but different mean/var) in general.  Since\n  the GP is a collection of RVs, it defines a distribution over FUNCTIONS.  So drawing from the GP realizes\n  one particular function.\n\n  Now let X = training data; these are our experimental independent variables\n  let f = training data observed values; this is our (SCALAR) dependent-variable\n  So for ``(X_i, f_i)`` pairs, we say:\n\n  ``f ~ GP(0, cov(X,X)) /equiv N(0, cov(X,X))``\n\n  the training data, f, is distributed like a (multi-variate) Gaussian with mean 0 and ``variance = cov(X,X)``.\n  Drawing from this GP requires conditioning on the result satisfying the training data.  That is, the realized\n  function must pass through all points ``(X,f)``.  Between these, \"essentially any\" behavior is possible, although certain\n  behaviors are more likely as specified via ``cov(X,X)``.\n  Note that the GP has 0 mean (and no signal variance) to specify that it passes through X,f exactly.  Nonzero mean\n  would shift the entire distribution so that it passes through ``(X,f+mu)``.\n\n  In the following, K(X,X) is the covariance function.  It's given as an input to this whole process and is critical\n  in informing the behavior of the GP.  The covariance function describes how related we (a priori) believe prior\n  points are to each other.\n  In code, the covariance function is specified through the CovarianceInterface class.\n\n  In a noise-free setting (signal noise modifies ``K`` to become ``K + \\sigma^2 * Id``, ``Id`` being identity), the joint\n  distribution of training inputs, ``f``, and test outputs, ``fs``, is::\n\n    [ f  ]  ~ N( 0, [ K(X,X)   K(X,Xs)  ]  = [ K     Ks  ]         (Equation 1, Rasmussen & Williams 2.18)\n    [ fs ]          [ K(Xs,X)  K(Xs,Xs) ]    [ Ks^T  Kss ]\n\n  where the test outputs are drawn from the prior.\n\n  | ``K(X,X)`` and ``K(Xs,Xs)`` are computed in BuildCovarianceMatrix()\n  | ``K(X,Xs)`` is computed by BuildMixCovarianceMatrix(); and ``K(Xs,X)`` is its transpose.\n  | ``K + \\sigma^2`` is computed in BuildCovarianceMatrixWithNoiseVariance(); almost all practical uses of GPs and EI will\n\n  be over data with nonzero noise variance.  However this is immaterial to the rest of the discussion here.\n\n  **3b. SAMPLING FROM GPs**\n\n  So to obtain the posterior distribution, fs, we again sample this joint prior and throw out any function\n  realizations that do not satisfy the observations (i.e., pass through all ``(X,f)`` pairs).  This is expensive.\n\n  Instead, we can use math to compute the posterior by conditioning it on the prior:\n\n  ``fs | Xs,X,f ~ N( mus, Vars)``\n\n  where ``mus = K(Xs,X) * K(X,X)^-1 * f = Ks^T * K^-1 * f,  (Equation 2, Rasmussen & Williams 2.19)``\n  which is computed in GaussianProcess::ComputeMeanOfPoints.\n\n  and  ``Vars = K(Xs,Xs) - K(Xs,X) * K(X,X)^-1 * K(X,Xs) = Kss - Ks^T * K^-1 * Ks, (Equation 3, Rasumussen & Williams 2.19)``\n  which is implemented in GaussianProcess::ComputeVarianceOfPoints (and provably SPD).\n\n  Now we can draw from this multi-variate Gaussian by:\n\n  ``y = mus + L * w    (Equation 4)``\n\n  where ``L * L^T = Vars`` (cholesky-factorization) and w is a vector of samples from ``N(0,1)``\n  Note that if our GP has 10 dimensions (variables), then y contains 10 sample values.\n\n  **3c. EXPECTED IMPROVEMENT**\n\n  .. Note:: these comments are copied in Python: interfaces/expected_improvement_interface.py\n\n  Then the improvement for this single sample is::\n\n    I = { best_known - min(y)   if (best_known - min(y) > 0)      (Equation 5)\n        {          0               else\n\n  And the expected improvement, EI, can be computed by averaging repeated computations of I; i.e., monte-carlo integration.\n  This is done in ExpectedImprovementEvaluator::ComputeExpectedImprovement(); we can also compute the gradient. This\n  computation is needed in the optimization of q,p-EI.\n\n  There is also a special, analytic case of EI computation that does not require monte-carlo integration. This special\n  case can only be used to compute 1,0-EI (and its gradient). Still this can be very useful (e.g., the heuristic\n  optimization in gpp_heuristic_expected_improvement_optimization.hpp estimates q,0-EI by repeatedly solving\n  1,0-EI).\n\n  From there, since EI is taken from a sum of gaussians, we expect it to be reasonably smooth\n  and apply multistart, restarted gradient descent to find the optimum.  The use of gradient descent\n  implies the need for all of the various \"grad\" functions, e.g., GP::ComputeGradMeanOfPoints().\n  This is handled starting in the highest level functions of file, ComputeOptimalPointsToSample().\n\n  **4. CODE OVERVIEW**\n\n  Finally, we give some further details about how the previous ideas map into the code.  We begin with an overview\n  of important classes and functions in this file, and end by going over the call stack for the EI optimization entry point.\n\n  **4a. First, the GaussianProcess (GP) class**\n\n  The GaussianProcess class abstracts the handling of GPs and their properties; quickly going over the functionality: it\n  provides methods for computing mean, variance, cholesky of variance, and their gradients (wrt spatial dimensions).\n  GP also allows the user to sample function values from it, distributed according to the GP prior.  Lastly GP provides\n  the ability to change the hyperparameters of its covariance function (although currently you cannot change the\n  covariance function; this would not be difficult to add).\n\n  Computation-wise, GaussianProcess also makes precomputation and preallocation convenient.  The class tracks all of its\n  inputs (e.g., ``X``, ``f``, noise var, covariance) as well as quantities that are derivable from *only* these inputs; e.g.,\n  ``K``, cholesky factorization of ``K``, ``K^-1*y``.  Thus repeated calculations with the GP over the same training data avoids\n  (very expensive) factorizations of ``K``.\n\n  A last note about GP: it uses the State idiom laid out in gpp_common.hpp.  The associated state is PointsToSampleState.\n  PointsToSampleState tracks the current \"test\" data set, points_to_sample--the set of currently running experiments,\n  possibly including the current point(s) being optimized. In the q,p-EI terminology, PointsToSampleState tracks the\n  union of ``points_to_sample`` and ``points_being_sampled``. PointsToSampleState preallocates all vectors needed by GP's\n  member functions; it also precomputes (per ``points_to_sample`` update) some derived quantities that are used repeatedly\n  by GP member functions.\n\n  In current usage, users generally will not need to access GaussianProcess's member functions directly; instead these are\n  used indirectly when users compute or optimize EI.  Plotting/visualization might be one reason to call GP members directly.\n\n  **4b. Next, the ExpectedImprovementEvaluator and OnePotentialSampleExpectedImprovementEvaulator classes**\n\n  ExpectedImprovementEvaluator abstracts the computation of EI and its gradient.  This class references a single\n  GaussianProcess that it uses to compute EI/grad EI as described above.  Equations 4, 5 above detailed the EI computation;\n  further details can be found below in the call tree discussion as well as in the implementation docs for these\n  functions.  The gradient of EI is implemented similarly; see implementation docs for details on the one subtlety.\n\n  OnePotentialSample is a special case of ExpectedImprovementEvaluator. With ``num_to_sample = 1`` and ``num_being_sampled = 0``\n  (only occurs in 1,0-EI evaluation/optimization), there is only one experiment to worry about and no concurrent events.\n  This simplifies the EI computation substantially (multi-dimensional Gaussians become a simple one dimensional case)\n  and we can write EI analytically in terms of the PDF and CDF of a N(0,1) normal distribution (which are evaluated\n  numerically by boost). No monte-carlo necessary!\n\n  ExpectedImprovementEvaluator and OnePotentialSample have corresponding State classes as well.  These are similar\n  to each other except OnePotentialSample does not have a NormalRNG pointer (since it does no MC integration) and some\n  temporaries are dropped since they have size 1.  But for the general EI's State, the NormalRNG pointer must reference\n  a different object for each thread!  Notably, both EI State classes construct their own GaussianProcess::StateType\n  object for use with GP members.  As long as there is only one EI state per thread, This ensures thread safety since there\n  is never a reason (or a way) for multiple threads to accidentally use the same GP state.  Finally, the EI state classes\n  hold some pre-allocated vectors for use as local temporaries by EI and GradEI computation.\n\n  **4c. And finally, we discuss selecting optimal experiments with ComputeOptimalPointsToSampleWithRandomStarts()**\n\n  This function is the top of the hierarchy for EI optimization.  It encompasses a multistart, restarted gradient descent\n  method.  Since this is not a convex optimization problem, there could be multiple local optima (or even 0 optima).  So\n  we start GD from multiple locations (multistart) as a heuristic in hopes of finding the global optima.\n\n  See the file comments of gpp_optimization.hpp for more details on the base gradient descent implementation and the restart\n  component of restarted gradient descent.\n\n  **5. CODE HIERARCHY / CALL-TREE**\n\n  For obtaining multiple new points to sample (q,p-EI), we have two main paths for optimization: multistart gradient\n  descent and 'dumb' search. The optimization hierarchy looks like (these optimization functions are in the header;\n  they are templates):\n  ComputeOptimalPointsToSampleWithRandomStarts<...>(...)  (selects random points; defined in math.hpp)\n\n  * Solves q,p-EI.\n  * Selects random starting locations based on random sampling from the domain (e.g., latin hypercube)\n  * This calls:\n\n    ComputeOptimalPointsToSampleViaMultistartGradientDescent<...>(...)  (multistart gradient descent)\n\n    * Switches into analytic OnePotentialSample case when appropriate\n    * Multithreaded over starting locations\n    * Optimizes with restarted gradient descent; collects results and updates the solution as new optima are found\n    * This calls:\n\n      MultistartOptimizer<...>::MultistartOptimize(...) for multistarting (see gpp_optimization.hpp) which in turn uses\n      GradientDescentOptimizer::Optimize<ObjectiveFunctionEvaluator, Domain>() (see gpp_optimization.hpp)\n\n  ComputeOptimalPointsToSampleViaLatinHypercubeSearch<...>(...)  (defined in gpp_math.hpp)\n\n  * Estimates q,p-EI with a 'dumb' search.\n  * Selects random starting locations based on random sampling from the domain (e.g., latin hypercube)\n  * This calls:\n\n    EvaluateEIAtPointList<...>(...)\n\n    * Evaluates EI at each starting location\n    * Switches into analytic OnePotentialSample case when appropriate\n    * Multithreaded over starting locations\n    * This calls:\n\n      MultistartOptimizer<...>::MultistartOptimize(...) for multistarting (see gpp_optimization.hpp)\n\n  ComputeOptimalPointsToSample<...>(...)  (defined in gpp_math.cpp)\n\n  * Solves q,p-EI\n  * Tries ComputeOptimalPointsToSampleWithRandomStarts() first.\n  * If that fails, switches to ComputeOptimalPointsToSampleViaLatinHypercubeSearch().\n\n  So finally we will overview the function calls for EI calculation.  We limit our discussion to the general MC case;\n  the analytic case is similar and simpler.\n  ExpectedImprovementEvaluator::ComputeExpectedImprovement()  (computes EI)\n\n  * Computes GP.mean, GP.variance, cholesky(GP.variance)\n  * MC integration: samples from the GP repeatedly (Equation 4) and computes the improvement (Equation 5), averaging the result\n    See function comments for more details.\n  * Calls out to GP::ComputeMeanOfPoints(), GP:ComputeVarianceOfPoints, ComputeCholeskyFactorL, NormalRNG::operator(),\n    and TriangularMatrixVectorMultiply\n\n  ExpectedImprovementEvaluator::ComputeGradExpectedImprovement()  (computes gradient of EI)\n\n  * Compute GP.mean, variance, cholesky(variance), grad mean, grad variance, grad cholesky variance\n  * MC integration: Equation 4, 5 as before to compute improvement each step\n    Only have grad EI contributions when improvement > 0.\n    Care is needed because only the point yielding the largest improvement contributes to the gradient.\n    See function comments for more details.\n\n  We will not detail the call tree once inside of GaussianProcess.  The mathematical formulas for the mean and variance\n  were already described above (Equation 2, 3).  Function docs (in this file) further detail/cite the formulas and\n  relevant derivations for gradients of these quantities.  Suffice to say there's a lot of linear algebra.  Read on\n  (to those fcn docs) for further details but this does little to expose the important concepts behind EI and GP.\n\\endrst*/\n\n#include \"gpp_math.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\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_covariance.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_geometry.hpp\"\n#include \"gpp_linear_algebra.hpp\"\n#include \"gpp_linear_algebra-inl.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_random.hpp\"\n\nnamespace optimal_learning {\n\n/*!\\rst\n  .. NOTE:: These comments have been copied into build_mix_covariance_matrix in python_version/python_utils.py.\n\n  Compute the \"mix\" covariance matrix, ``Ks``, of ``X`` and ``Xs`` (``points_sampled`` and ``points_to_sample``, respectively).\n  Matrix is computed as:\n\n  ``A_{i,j} = covariance(X_i, Xs_j).``\n\n  Result is not guaranteed to be SPD and need not even be square.\n\n  Generally, this is called from other functions with \"points_sampled\" and \"points_to_sample\" as the\n  input lists and not any arbitrary list of points; hence the very specific input name.  But this\n  is not a requirement.\n\n  Point lists cannot contain duplicates with each other or within themselves.\n\n  \\param\n    :covariance: the CovarianceFunction object encoding assumptions about the GP's behavior on our data\n    :points_sampled[dim][num_sampled]: list of points, ``X``\n    :points_to_sample[dim][num_to_sample]: list of points, ``Xs``\n    :dim: spatial dimension of a point\n    :num_sampled: number of points in points_sampled\n    :num_to_sample: number of points in points_to_sample\n  \\output\n    :cov_matrix[num_sampled*(num_derivatives_sampled+1)][num_to_sample*(num_derivatives_to_sample+1)]: computed \"mix\" covariance matrix\n\\endrst*/\nOL_NONNULL_POINTERS void BuildMixCovarianceMatrix(const CovarianceInterface& covariance,\n                                                  double const * restrict points_sampled,\n                                                  double const * restrict points_to_sample,\n                                                  int dim, int num_sampled, int num_to_sample,\n                                                  int const * restrict derivatives_sampled,\n                                                  int num_derivatives_sampled,\n                                                  int const * restrict derivatives_to_sample,\n                                                  int num_derivatives_to_sample,\n                                                  double * restrict cov_matrix) noexcept {\n  // calculate the covariance matrix defined in gpp_covariance.hpp\n  double * cov_temp = new double[(num_derivatives_sampled+1)*(num_derivatives_to_sample+1)]();\n  for (int j = 0; j < num_to_sample; ++j) { //col\n    for (int i = 0; i < num_sampled; ++i) { //row\n      covariance.Covariance(points_sampled + i*dim, derivatives_sampled, num_derivatives_sampled,\n                            points_to_sample + j*dim, derivatives_to_sample, num_derivatives_to_sample,\n                            cov_temp);\n      for (int m = 0; m < num_derivatives_sampled+1; ++m){\n          for (int n = 0; n < num_derivatives_to_sample+1; ++n){\n              int row = i*(num_derivatives_sampled+1) + m;\n              int col = j*(num_derivatives_to_sample+1) + n;\n              cov_matrix[row+col*num_sampled*(num_derivatives_sampled+1)] = cov_temp[m+n*(num_derivatives_sampled+1)];\n          }\n      }\n    }\n  }\n  delete [] cov_temp;\n}\n\nnamespace {  // utilities for A_{k,j,i}*x_j and building covariance matrices\n\n/*!\\rst\n  Helper function to perform the following math (in index notation)::\n\n    y_{k,i} = A_{k,j,i} * x_j\n    0 <= i < dim_one, 0 <= j < dim_two, 0 <= k < dim_three\n\n  This is nothing more than dim_one matrix-vector products ``A_{k,j} * x_j``, and could be implemented using a\n  single GeneralMatrixMatrixMultiply if A were stored (full) block diagonal (but this wastes a lot of space).\n\n  \\param\n    :tensor[dim_three][dim_two][dim_one]: tensor multiplicand\n    :vector[dim_two]: vector multiplicand\n    :dim_one: first dimension of tensor\n    :dim_two: second dimension of tensor\n    :dim_three: third dimension of tensor\n  \\output\n    :answer[dim_three][dim_one]: result matrix\n\\endrst*/\nOL_NONNULL_POINTERS void SpecialTensorVectorMultiply(double const * restrict tensor,\n                                                     double const * restrict vector,\n                                                     int dim_one, int dim_two, int dim_three,\n                                                     double * restrict answer) noexcept {\n  for (int i = 0; i < dim_one; ++i) {\n    GeneralMatrixVectorMultiply(tensor, 'N', vector, 1.0, 0.0, dim_three, dim_two, dim_three, answer);\n    tensor += dim_two*dim_three;\n    answer += dim_three;\n  }\n}\n\n/*!\\rst\n  .. NOTE:: These comments have been copied into build_covariance_matrix in python_version/python_utils.py.\n\n  Compute the covariance matrix, ``K``, of a list of points, ``X_i``.  Matrix is computed as:\n\n  ``A_{i,j} = covariance(X_i, X_j)``.\n\n  Result is SPD assuming covariance operator is SPD and points are unique.\n\n  Generally, this is called from other functions with \"points_sampled\" as the input and not any\n  arbitrary list of points; hence the very specific input name.\n\n  Point list cannot contain duplicates.  Doing so (or providing nearly duplicate points) can lead to\n  semi-definite matrices or very poor numerical conditioning.\n\n  \\param\n    :covariance: the CovarianceFunction object encoding assumptions about the GP's behavior on our data\n    :points_sampled[dim][num_sampled]: list of points\n    :dim: spatial dimension of a point\n    :num_sampled: number of points\n  \\output\n    :cov_matrix[num_sampled][num_sampled]: computed covariance matrix, LOWER TRIANGLE\n\\endrst*/\nOL_NONNULL_POINTERS void BuildCovarianceMatrix(const CovarianceInterface& covariance,\n                                               double const * restrict points_sampled,\n                                               int dim, int num_sampled,\n                                               int const * restrict derivatives,\n                                               int num_derivatives,\n                                               double * restrict cov_matrix) noexcept {\n  // we only work with lower triangular parts of symmetric matrices, so only fill half of it\n  double * cov_temp = new double[(num_derivatives+1)*(num_derivatives+1)]();\n  for (int i = 0; i < num_sampled; ++i) { // col\n    for (int j = i; j < num_sampled; ++j) { //row\n      covariance.Covariance(points_sampled + j*dim, derivatives, num_derivatives,\n                            points_sampled + i*dim, derivatives, num_derivatives,\n                            cov_temp);\n      for (int m = 0; m < num_derivatives+1; ++m){\n          for (int n = 0; n < num_derivatives+1; ++n){\n              int row = j*(num_derivatives+1) + m;\n              int col = i*(num_derivatives+1) + n;\n              if (row>=col){\n                  cov_matrix[row+col*num_sampled*(num_derivatives+1)] = cov_temp[m+n*(num_derivatives+1)];\n              }\n          }\n      }\n    }\n  }\n  delete [] cov_temp;\n}\n\n/*!\\rst\n  Same as BuildCovarianceMatrix, except noise variance ``(\\sigma_n^2)`` is added to the main diagonal.\n\n  Only additional inputs listed; see BuildCovarianceMatrix() for other arguments.\n\n  \\param\n    :noise_variance[num_sampled]: i-th entry is amt of noise variance to add to i-th diagonal entry; i.e., noise measuring i-th point\n\\endrst*/\nOL_NONNULL_POINTERS void BuildCovarianceMatrixWithNoiseVariance(const CovarianceInterface& covariance,\n                                                                double const * restrict noise_variance,\n                                                                double const * restrict points_sampled,\n                                                                int dim, int num_sampled,\n                                                                int const * restrict derivatives,\n                                                                int num_derivatives,\n                                                                double * restrict cov_matrix) noexcept {\n  // we only work with lower triangular parts of symmetric matrices, so only fill half of it\n  double * cov_temp = new double[Square(num_derivatives+1)]();\n  for (int i = 0; i < num_sampled; ++i) { // col\n    for (int j = i; j < num_sampled; ++j) { //row\n      covariance.Covariance(points_sampled + j*dim, derivatives, num_derivatives,\n                            points_sampled + i*dim, derivatives, num_derivatives,\n                            cov_temp);\n      for (int m = 0; m < num_derivatives+1; ++m){\n          for (int n = 0; n < num_derivatives+1; ++n){\n              int row = j*(num_derivatives+1) + m;\n              int col = i*(num_derivatives+1) + n;\n              if (row>=col){\n                  cov_matrix[row+col*num_sampled*(num_derivatives+1)] = cov_temp[m+n*(num_derivatives+1)];\n              }\n              if (row == col){\n                  cov_matrix[row+col*num_sampled*(num_derivatives+1)] += noise_variance[m];\n              }\n          }\n      }\n    }\n  }\n  delete [] cov_temp;\n}\n\n}  // end unnamed namespace\n\nvoid GaussianProcess::BuildCovarianceMatrixWithNoiseVariance() noexcept {\n  optimal_learning::BuildCovarianceMatrixWithNoiseVariance(*covariance_ptr_, noise_variance_.data(),\n                                                           points_sampled_.data(), dim_, num_sampled_,\n                                                           derivatives_.data(), num_derivatives_,\n                                                           K_chol_.data());\n}\n\n/*!\\rst\n    :cov_matrix[num_sampled][num_to_sample]: computed \"mix\" covariance matrix\n\\endrst*/\nvoid GaussianProcess::BuildMixCovarianceMatrix(double const * restrict points_to_sample,\n                                               int num_to_sample,\n                                               int const * restrict derivatives_to_sample,\n                                               int num_derivatives_to_sample,\n                                               double * restrict covariance_matrix) const noexcept {\n  optimal_learning::BuildMixCovarianceMatrix(*covariance_ptr_, points_sampled_.data(),\n                                             points_to_sample, dim_, num_sampled_,\n                                             num_to_sample, derivatives_.data(), num_derivatives_,\n                                             derivatives_to_sample, num_derivatives_to_sample,\n                                             covariance_matrix);\n}\n\nvoid GaussianProcess::RecomputeDerivedVariables() {\n  // resize if needed\n  if (unlikely(static_cast<int>(K_inv_y_.size()) != num_sampled_*(num_derivatives_+1))) {\n    K_chol_.resize(Square(num_sampled_*(num_derivatives_+1)));\n    K_inv_y_.resize(num_sampled_*(num_derivatives_+1));\n  }\n\n  // recompute derived quantities\n  BuildCovarianceMatrixWithNoiseVariance();\n  int leading_minor_index = ComputeCholeskyFactorL(num_sampled_*(num_derivatives_+1), K_chol_.data());\n  if (unlikely(leading_minor_index != 0)) {\n    OL_THROW_EXCEPTION(SingularMatrixException,\n                       \"Covariance matrix (K) singular. Check for duplicate points_sampled \"\n                       \"(with 0 noise) and/or extreme hyperparameter values.\",\n                       K_chol_.data(), num_sampled_*(num_derivatives_+1), leading_minor_index);\n  }\n\n  mean_ = 0.0;\n  for (int i=0; i<num_sampled_; ++i){\n     mean_ += points_sampled_value_[i*(num_derivatives_+1)];\n  }\n  mean_ /= num_sampled_;\n\n  std::copy(points_sampled_value_.begin(), points_sampled_value_.end(), K_inv_y_.begin());\n  for (int i=0; i<num_sampled_; ++i){\n     K_inv_y_[i*(num_derivatives_+1)] -= mean_;\n  }\n  CholeskyFactorLMatrixVectorSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1), K_inv_y_.data());\n}\n\nGaussianProcess::GaussianProcess(const CovarianceInterface& covariance_in,\n                                 double const * restrict points_sampled_in,\n                                 double const * restrict points_sampled_value_in,\n                                 double const * restrict noise_variance_in,\n                                 int const * restrict derivatives_in,\n                                 int num_derivatives_in,\n                                 int dim_in, int num_sampled_in)\n    : dim_(dim_in),\n      num_sampled_(num_sampled_in),\n      mean_(0.0),\n      covariance_ptr_(covariance_in.Clone()),\n      points_sampled_(points_sampled_in, points_sampled_in + num_sampled_in*dim_in),\n      points_sampled_value_(points_sampled_value_in, points_sampled_value_in + num_sampled_in*(num_derivatives_in+1)),\n      derivatives_(derivatives_in, derivatives_in + num_derivatives_in),\n      num_derivatives_(num_derivatives_in),\n      noise_variance_(noise_variance_in, noise_variance_in + num_derivatives_in+1),\n      K_chol_(Square(num_sampled_in*(1+num_derivatives_in))),\n      K_inv_y_(num_sampled_in*(1+num_derivatives_in)),\n      normal_rng_(kDefaultSeed) {\n  RecomputeDerivedVariables();\n}\n\nGaussianProcess::GaussianProcess(const GaussianProcess& source)\n    : dim_(source.dim_),\n      num_sampled_(source.num_sampled_),\n      mean_(source.mean_),\n      covariance_ptr_(source.covariance_ptr_->Clone()),\n      points_sampled_(source.points_sampled_),\n      points_sampled_value_(source.points_sampled_value_),\n      derivatives_(source.derivatives_),\n      num_derivatives_(source.num_derivatives_),\n      noise_variance_(source.noise_variance_),\n      K_chol_(source.K_chol_),\n      K_inv_y_(source.K_inv_y_),\n      normal_rng_(source.normal_rng_) {\n}\n\n/*!\\rst\n  Sets up precomputed quantities needed for mean, variance, and gradients thereof.  These quantities are:\n\n  ``Ks := Ks_{k,i} = cov(X_k, Xs_i)`` (used by mean, variance)\n\n  Then if we need gradients:\n\n  | ``K^-1 * Ks := solution X of K_{k,l} * X_{l,i} = Ks{k,i}`` (used by variance, grad variance)\n  | ``gradient of Ks := C_{d,k,i} = \\pderiv{Ks_{k,i}}{Xs_{d,i}}`` (used by grad mean, grad variance)\n\\endrst*/\nvoid GaussianProcess::FillPointsToSampleState(StateType * points_to_sample_state) const {\n  BuildMixCovarianceMatrix(points_to_sample_state->points_to_sample.data(),\n                           points_to_sample_state->num_to_sample,\n                           points_to_sample_state->gradients.data(),\n                           points_to_sample_state->num_gradients_to_sample,\n                           points_to_sample_state->K_star.data());\n\n  if (points_to_sample_state->precomputed){\n    // to save on duplicate storage, precompute K^-1 * Ks\n    std::copy(points_to_sample_state->K_star.begin(), points_to_sample_state->K_star.end(),\n              points_to_sample_state->K_inv_times_K_star.begin());\n    CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1),\n                                     points_to_sample_state->num_to_sample*(points_to_sample_state->num_gradients_to_sample+1),\n                                     points_to_sample_state->K_inv_times_K_star.data());\n  }\n  // if we needs to taking derivative w.r.t. points_to_sample\n  if (points_to_sample_state->num_derivatives > 0) {\n    double * restrict gKs_temp = points_to_sample_state->grad_K_star.data();\n    double * restrict grad_cov_temp = new double[dim_*(points_to_sample_state->num_gradients_to_sample+1)*(num_derivatives_+1)]();\n    // also precompute C_{d,k,i} = \\pderiv{Ks_{k,i}}{Xs_{d,i}}, stored in grad_K_star\n    for (int i = 0; i < points_to_sample_state->num_derivatives; ++i) { // dim * num_sample_ * num_derivatives\n      for (int j = 0; j < num_sampled_; ++j) {\n        covariance_ptr_->GradCovariance(points_to_sample_state->points_to_sample.data() + i*dim_, points_to_sample_state->gradients.data(),\n                                        points_to_sample_state->num_gradients_to_sample,\n                                        points_sampled_.data() + j*dim_, derivatives_.data(), num_derivatives_,\n                                        grad_cov_temp);\n        for (int m = 0; m < points_to_sample_state->num_gradients_to_sample+1; ++m){\n            for (int n = 0; n < num_derivatives_+1; ++n){\n              int row = n + j*(num_derivatives_+1);\n              int col = m + i*(points_to_sample_state->num_gradients_to_sample+1);\n              for (int d = 0; d <dim_; ++d){\n                gKs_temp[d + row*dim_ + col*dim_*num_sampled_*(num_derivatives_+1)] =\n                       grad_cov_temp[d+m*dim_+n*dim_*(points_to_sample_state->num_gradients_to_sample+1)];\n              }\n            }\n        }\n      }\n    }\n    delete [] grad_cov_temp;\n\n    if (points_to_sample_state->precomputed_grad_K_inv_times_K_star){\n      const int row = num_sampled_*(num_derivatives_+1);\n      const int col = points_to_sample_state->num_derivatives*(points_to_sample_state->num_gradients_to_sample+1);\n      double * restrict gKs_temp = points_to_sample_state->grad_K_star.data();\n      double * restrict g_kinv_Ks_temp = points_to_sample_state->grad_K_inv_times_K_star.data();\n      for (int index = 0; index < col; index++){\n        std::vector<double> transpose_temp(row*dim_, 0.0);\n        MatrixTranspose(gKs_temp + index*row*dim_, dim_, row, transpose_temp.data());\n        CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), row, dim_, transpose_temp.data());\n        MatrixTranspose(transpose_temp.data(), row, dim_, g_kinv_Ks_temp + index*dim_*row);\n      }\n    }\n  }\n}\n\n/*!\\rst\n  Calculates the mean (from the GPP) of a set of points:\n\n  ``mus = Ks^T * K^-1 * y``\n\n  See Rasmussen and Willians page 19 alg 2.1\n\\endrst*/\nvoid GaussianProcess::ComputeMeanOfPoints(const StateType& points_to_sample_state,\n                                          double * restrict mean_of_points) const noexcept {\n  for (int i=0; i<points_to_sample_state.num_to_sample; ++i){\n    for (int j = 0; j<points_to_sample_state.num_gradients_to_sample+1; ++j){\n        if (j==0){\n            mean_of_points[i*(points_to_sample_state.num_gradients_to_sample+1)+j] = mean_;\n        }\n        else{\n            mean_of_points[i*(points_to_sample_state.num_gradients_to_sample+1)+j] = 0;\n        }\n    }\n  }\n  GeneralMatrixVectorMultiply(points_to_sample_state.K_star.data(), 'T', K_inv_y_.data(),\n                              1.0, 1.0, num_sampled_*(num_derivatives_+1),\n                              points_to_sample_state.num_to_sample*(points_to_sample_state.num_gradients_to_sample+1),\n                              num_sampled_*(num_derivatives_+1), mean_of_points);\n}\n\n\n/*!\\rst\n  Calculates the mean (from the GPP) of a set of points:\n\n  ``mus = Ks^T * K^-1 * y``\n\n  See Rasmussen and Willians page 19 alg 2.1\n\\endrst*/\nvoid GaussianProcess::ComputeMeanOfAdditionalPoints(double const * discrete_pts,\n                                                    int num_pts, int const * gradients_discrete_pts,\n                                                    int num_gradients_discrete_pts,\n                                                    double * restrict mean_of_points) const noexcept {\n  std::vector<double> kt(num_sampled_*(num_derivatives_+1)*num_pts*(num_gradients_discrete_pts+1), 0.0);\n  BuildMixCovarianceMatrix(discrete_pts, num_pts,\n                           gradients_discrete_pts, num_gradients_discrete_pts,\n                           kt.data());\n  for (int i=0; i<num_pts; ++i){\n      for (int j = 0; j<num_gradients_discrete_pts+1; ++j){\n          if (j==0){\n              mean_of_points[i*(num_gradients_discrete_pts+1)+j] = mean_;\n          }\n          else{\n              mean_of_points[i*(num_gradients_discrete_pts+1)+j] = 0;\n          }\n      }\n  }\n\n  GeneralMatrixVectorMultiply(kt.data(), 'T', K_inv_y_.data(), 1.0, 1.0, num_sampled_*(num_derivatives_+1),\n                              num_pts*(num_gradients_discrete_pts+1), num_sampled_*(num_derivatives_+1),\n                              mean_of_points);\n}\n\n/*!\\rst\n  Gradient of the mean of a GP.  Note that the output storage skips known zeros (see declaration docs for details).\n  See Scott Clark's PhD thesis for more spelled out mathematical details, but this is a reasonably straightforward\n  differentiation of:\n\n  ``mus = Ks^T * K^-1 * y``\n\n  wrt ``Xs`` (so only Ks contributes derivative terms)\n\\endrst*/\nvoid GaussianProcess::ComputeGradMeanOfPoints(const StateType& points_to_sample_state,\n                                              double * restrict grad_mu) const noexcept {\n  SpecialTensorVectorMultiply(points_to_sample_state.grad_K_star.data(), K_inv_y_.data(),\n                              points_to_sample_state.num_derivatives*(points_to_sample_state.num_gradients_to_sample+1),\n                              num_sampled_*(num_derivatives_+1), dim_, grad_mu);\n}\n\n/*!\\rst\n  Mathematically, we are computing Covars (Covar_star), the GP covariance.  Vars is defined at the top of this file (Equation 3)\n  and in Rasmussen & Williams, Equation 2.19:\n\n  | ``L * L^T = K``\n  | ``V = L^-1 * Ks``\n  | ``W = L^-1 * Kt``\n  | ``Vars = Kst - (V^T * W)``\n\n  This quantity is:\n\n  ``Kst``: the covariance between two sets of test points based on the prior distribution\n\n  minus\n\n  ``V^T * W``: the information observations give us about the objective function\n\n  For more information, see:\n  http://en.wikipedia.org/wiki/Schur_complement\n\n  \\param\n    :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n    :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n    :num_pts: number of points in discrete_pts\n  \\output\n    :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n    :var_star[num_to_sample][num_pts]: covariance of GP evaluated at ``points_to_sample`` and ``discrete_pts``\n\\endrst*/\n\nvoid GaussianProcess::ComputeCovarianceOfPoints(StateType * points_to_sample_state,\n                                                double const * restrict discrete_pts,\n                                                int num_pts, int const * restrict gradients_discrete_pts,\n                                                int num_gradients_discrete_pts, bool precomputed, double const * ktd,\n                                                double * restrict var_star) const noexcept {\n  // optimized code that avoids formation of K_inv\n  const int num_to_sample = points_to_sample_state->num_to_sample;\n  const int num_gradients_to_sample = points_to_sample_state->num_gradients_to_sample;\n\n  // Vars = Kst\n  optimal_learning::BuildMixCovarianceMatrix(*covariance_ptr_,\n                                             points_to_sample_state->points_to_sample.data(), discrete_pts, dim_,\n                                             num_to_sample, num_pts,\n                                             points_to_sample_state->gradients.data(), num_gradients_to_sample,\n                                             gradients_discrete_pts, num_gradients_discrete_pts,\n                                             var_star);\n  if (precomputed){\n    GeneralMatrixMatrixMultiply(points_to_sample_state->K_star.data(), 'T',\n                                ktd, -1.0, 1.0, num_to_sample*(num_gradients_to_sample+1),\n                                num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), var_star);\n  }\n  else {\n    // Compute K_t\n    double * kt = new double[num_sampled_*(num_derivatives_+1)*num_pts*(num_gradients_discrete_pts+1)]();\n    BuildMixCovarianceMatrix(discrete_pts, num_pts, gradients_discrete_pts, num_gradients_discrete_pts, kt);\n    if (points_to_sample_state->precomputed){\n        // compute as Ks^T * (K\\ Ks), the 2nd term of which has been precomputed\n        // this is cheaper than computing V^T * V when K \\ Ks is already available\n        GeneralMatrixMatrixMultiply(points_to_sample_state->K_inv_times_K_star.data(), 'T',\n                                    kt, -1.0, 1.0, num_to_sample*(num_gradients_to_sample+1),\n                                    num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), var_star);\n    } else {\n        std::copy(points_to_sample_state->K_star.begin(), points_to_sample_state->K_star.end(),\n                  points_to_sample_state->V.begin());\n\n        // V := L^-1 * K_star\n        TriangularMatrixMatrixSolve(K_chol_.data(), 'N', num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample+1),\n                                    num_sampled_*(num_derivatives_+1),\n                                    points_to_sample_state->V.data());\n\n        // W := L^-1 * K_t\n        TriangularMatrixMatrixSolve(K_chol_.data(), 'N', num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1),\n                                    num_sampled_*(num_derivatives_+1), kt);\n\n        // compute V^T W = (L^-1 * Ks)^T * (L^-1 * Kt).\n        GeneralMatrixMatrixMultiply(points_to_sample_state->V.data(), 'T', kt,\n                                    -1.0, 1.0, num_to_sample*(num_gradients_to_sample+1),\n                                    num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), var_star);\n    }\n    delete [] kt;\n  }\n}\n\n/*!\\rst\n  Mathematically, we are computing Covars (Covar_star), the GP covariance.  Vars is defined at the top of this file (Equation 3)\n  and in Rasmussen & Williams, Equation 2.19:\n\n  | ``L * L^T = K``\n  | ``V = L^-1 * Ks``\n  | ``W = L^-1 * Kt``\n  | ``Vars = Kst - (V^T * W)``\n\n  This quantity is:\n\n  ``Kst``: the covariance between two sets of test points based on the prior distribution\n\n  minus\n\n  ``V^T * W``: the information observations give us about the objective function\n\n  For more information, see:\n  http://en.wikipedia.org/wiki/Schur_complement\n\n  \\param\n    :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n    :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n    :num_pts: number of points in discrete_pts\n  \\output\n    :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n    :var_star[num_to_sample][num_pts]: covariance of GP evaluated at ``points_to_sample`` and ``discrete_pts``\n\\endrst*/\n\nvoid GaussianProcess::ComputeTrain(double const * restrict discrete_pts,\n                  int num_pts, int const * restrict gradients_discrete_pts,\n                  int num_gradients_discrete_pts, double * restrict var_star) const noexcept {\n   BuildMixCovarianceMatrix(discrete_pts, num_pts, gradients_discrete_pts, num_gradients_discrete_pts, var_star);\n   CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), var_star);\n}\n\n/*!\\rst\n  Mathematically, we are computing Vars (Var_star), the GP variance.  Vars is defined at the top of this file (Equation 3)\n  and in Rasmussen & Williams, Equation 2.19:\n\n  | ``L * L^T = K``\n  | ``V = L^-1 * Ks``\n  | ``Vars = Kss - (V^T * V)``\n\n  This quantity is:\n\n  ``Kss``: the covariance between test points based on the prior distribution\n\n  minus\n\n  ``V^T * V``: the information observations give us about the objective function\n\n  Notice that Vars is clearly symmetric.  ``Kss`` is SPD. And\n  ``V^T * V = (V^T * V)^T`` is symmetric (and is in fact SPD).\n\n  ``V^T * V = Ks^T * K^-1 * K_s`` is SPD because:\n\n  ``X^T * A * X`` is SPD when A is SPD AND ``X`` has full rank (``X`` need not be square)\n\n  ``Ks`` has full rank as long as ``K`` & ``Kss`` are SPD; ``K^-1`` is SPD because ``K`` is SPD.\n\n  It turns out that ``Vars`` is SPD.\n\n  In Equation 1 (Rasmussen & Williams 2.18), it is clear that the combined covariance matrix\n  is SPD (as long as no duplicate points and the covariance function is valid).  A matrix of the form::\n\n    [ A   B ]\n    [ B^T C ]\n\n  is SPD if and only if ``A`` is SPD AND ``(C - B^T * A^-1 * B)`` is SPD.  Here, ``A = K, B = Ks, C = Kss``.\n  This (aka Schur Complement) can be shown readily::\n\n    [ A   B ] = [  I            0 ] * [  A    0                ] * [ I   A^-1 * B ]\n    [ B^T C ]   [ (A^-1 * B)^T  I ] * [  0 (C - B^T * A^-1 * B)]   [ 0       I    ]\n\n  This factorization is valid because ``A`` is SPD (and thus invertible).  Then by the ``X^T * A * X`` rule for SPD-ness,\n  we know the block-diagonal matrix in the center is SPD.  Hence the SPD-ness of ``V^T * V`` follows readily.\n\n  For more information, see:\n  http://en.wikipedia.org/wiki/Schur_complement\n\n  [num_to_sample * num_gradients_to_sample] [num_to_sample*(the number of gradients in the bracket below)]\n\\endrst*/\nvoid GaussianProcess::ComputeVarianceOfPoints(StateType * points_to_sample_state,\n                                              int const * restrict gradients_to_sample_part2,\n                                              int num_gradients_to_sample_part2,\n                                              double * restrict var_star) const noexcept {\n  // optimized code that avoids formation of K_inv\n  const int num_to_sample = points_to_sample_state->num_to_sample;\n  const int num_gradients_to_sample = points_to_sample_state->num_gradients_to_sample;\n\n  // Vars = Kss\n  optimal_learning::BuildMixCovarianceMatrix(*covariance_ptr_,\n                                             points_to_sample_state->points_to_sample.data(), points_to_sample_state->points_to_sample.data(),\n                                             dim_, num_to_sample, num_to_sample,\n                                             points_to_sample_state->gradients.data(), num_gradients_to_sample,\n                                             gradients_to_sample_part2, num_gradients_to_sample_part2,\n                                             var_star);\n\n  double * cov_temp_part2 = new double[(num_sampled_*(num_derivatives_+1)*num_to_sample*(num_gradients_to_sample_part2+1))]();\n  BuildMixCovarianceMatrix(points_to_sample_state->points_to_sample.data(), num_to_sample,\n                           gradients_to_sample_part2, num_gradients_to_sample_part2, cov_temp_part2);\n\n  // following block computes Vars -= V^T*V, with the exact method depending on what quantities were precomputed\n  if (unlikely(points_to_sample_state->precomputed == false)) {\n    std::copy(points_to_sample_state->K_star.begin(), points_to_sample_state->K_star.end(),\n              points_to_sample_state->V.begin());\n\n    // V := L^-1 * K_star\n    TriangularMatrixMatrixSolve(K_chol_.data(), 'N', num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample+1),\n                                num_sampled_*(num_derivatives_+1),\n                                points_to_sample_state->V.data());\n\n    TriangularMatrixMatrixSolve(K_chol_.data(), 'N', num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample_part2+1),\n                                num_sampled_*(num_derivatives_+1),\n                                cov_temp_part2);\n\n    // compute V^T V = (L^-1 * Ks)^T * (L^-1 * Ks).\n    GeneralMatrixMatrixMultiply(points_to_sample_state->V.data(), 'T', cov_temp_part2,\n                                -1.0, 1.0, num_to_sample*(num_gradients_to_sample+1),\n                                num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample_part2+1), var_star);\n  } else {\n    // compute as Ks^T * (K\\ Ks), the 2nd term of which has been precomputed\n    // this is cheaper than computing V^T * V when K \\ Ks is already available\n    GeneralMatrixMatrixMultiply(points_to_sample_state->K_inv_times_K_star.data(), 'T',\n                                cov_temp_part2, -1.0, 1.0, num_to_sample*(num_gradients_to_sample+1),\n                                num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample_part2+1), var_star);\n  }\n  delete [] cov_temp_part2;\n}\n\n/*!\\rst\n  **CORE IDEA**\n\n  Similar to ComputeGradCholeskyVarianceOfPoints() below, except this function does not account for the cholesky decomposition.  That is,\n  it produces derivatives wrt ``Xs_{d,p}`` (``points_to_sample``) of:\n\n  ``Vars = Kss - (V^T * V) = Kss - Ks^T * K^-1 * Ks`` (see ComputeVarianceOfPoints)\n\n  .. NOTE:: normally ``Xs_p`` would be the ``p``-th point of Xs (all dimensions); here ``Xs_{d,p}`` more explicitly\n      refers to the ``d``-th spatial dimension of the ``p``-th point.\n\n  This function only returns the derivative wrt a single choice of ``p``, as specified by ``diff_index``.\n\n  Expanded index notation:\n\n  ``Vars_{i,j} = Kss_{i,j} - Ks^T_{i,l} * K^-1_{l,k} * Ks_{k,j}``\n\n  Recall ``Ks_{k,i} = cov(X_k, Xs_i) = cov(Xs_i, Xs_k)`` where ``Xs`` is ``points_to_sample`` and ``X`` is ``points_sampled``.\n  (Note this is not equivalent to saying ``Ks = Ks^T``, although this would be true if ``|Xs| == |X|``.)\n  As a result of this symmetry, ``\\pderiv{Ks_{k,i}}{Xs_{d,i}} = \\pderiv{Ks_{i,k}}{Xs_{d,i}}`` (that's ``d(cov(Xs_i, X_k))/d(Xs_i)``)\n\n  We are being more strict with index labels than is standard to clearly specify tensor dimensions.  To be clear:\n  1. ``i,j`` range over ``num_to_sample``\n  2. ``l,k`` are the only non-free indices; they range over ``num_sampled``\n  3. ``d,p`` describe the SPECIFIC point being differentiated against in ``Xs`` (``points_to_sample``): ``d`` over dimension, ``p``\\* over ``num_to_sample``\n\n  \\*NOTE: ``p`` is *fixed*! Unlike all other indices, ``p`` refers to a *SPECIFIC* point in the range ``[0, ..., num_to_sample-1]``.\n          Thus, ``\\pderiv{Ks_{k,i}}{Xs_{d,i}}`` is a 3-tensor (``A_{d,k,i}``) (repeated ``i`` is not summation since they denote\n          components of a derivative) while ``\\pderiv{Ks_{i,l}}{Xs_{d,p}}`` is a 2-tensor (``A_{d,l}``) b/c only\n          ``\\pderiv{Ks_{i=p,l}}{Xs_{d,p}}`` is nonzero, and ``{d,l}`` are the only remaining free indices.\n\n  Then differentiating against ``Xs_{d,p}`` (recall that this is a specific point b/c p is fixed):\n\n  | ``\\pderiv{Vars_{i,j}}{Xs_{d,p}} = \\pderiv{K_ss{i,j}}{Xs_{d,p}} -``\n  | ``(\\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   +  K_s{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}})``\n\n  Many of these terms are analytically known to be 0: ``\\pderiv{Ks_{i,l}}{Xs_{d,p}} = 0`` when ``p != i`` (see NOTE above).\n  A similar statement holds for the other gradient term.\n\n  Observe that the second term in the parens, ``Ks_{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}}``, can be reordered\n  to \"look\" like the first term.  We use three symmetries: ``K^-1{l,k} = K^-1{k,l}``, ``Ks_{i,l} = Ks_{l,i}``, and\n\n  ``\\pderiv{Ks_{k,j}}{Xs_{d,p}} = \\pderiv{Ks_{j,k}}{Xs_{d,p}}``\n\n  Then we can write:\n\n  ``K_s{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}} = \\pderiv{Ks_{j,k}}{Xs_{d,p}} * K^-1_{k,l} * K_s{l,i}``\n\n  Now left and right terms have the same index ordering (i,j match; k,l are not free and thus immaterial)\n\n  The final result, accounting for analytic zeros is given here for convenience::\n\n    DVars_{d,i,j} \\equiv \\pderiv{Vars_{i,j}}{Xs_{d,p}} =``\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} - 2*\\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   :  WHEN p == i == j\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} -   \\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   :  WHEN p == i != j\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} -   \\pderiv{Ks_{j,k}}{Xs_{d,p}} * K^-1_{k,l} * K_s{l,i}   :  WHEN p == j != i\n      {                                    0                                                   :  otherwise\n\n  The first item has a factor of 2 b/c it gets a contribution from both parts of the sum since ``p == i`` and ``p == j``.\n  The ordering ``DVars_{d,i,j}`` is significant: this is the ordering (d changes the fastest) in storage.\n\n  **OPTIMIZATIONS**\n\n  Implementing this formula naively results in a large amount of redundant computation, so we now describe the optimizations\n  present in our implementation.\n\n  The first thing to notice is that the result, ``\\pderiv{Vars_{i,j}}{Xs_{d,p}}``, has a lot of 0s.  In particular, only the\n  ``p``-th block row and ``p``-th block column have nonzero entries (blocks are size ``dim``, indexed ``d``).  Currently,\n  we will not be taking advantage of this sparsity because the consumer of DVars, ComputeGradCholeskyVarianceOfPoints(),\n  is not implemented with sparsity in mind.\n\n  Similarly, the next thing to notice is that if we ignore the case ``p == i == j``, then we see that the expressions for\n  ``p == i`` and ``p == j`` are actually identical (e.g., take the ``p == j`` case and exchange ``j = i`` and ``k = l``).\n\n  So think of ``DVars`` as a block matrix; each block has dimension entries, and the blocks are indexed over\n  ``i`` (rows), ``j`` (cols).  Then we see that the code is block-symmetric: ``DVars_{d,i,j} = Dvars_{d,j,i}``.\n  So we can compute it by filling in the ``p``-th block column and then copy that data into the ``p``-th block row.\n\n  Additionally, the derivative terms represent matrix-matrix products:\n  ``C_{l,j} = K^-1_{l,k} * Ks_{k,j}`` (and ``K^-1_{k,l} * Ks_{l,i}``, which is just a change of index labels) is\n  a matrix product.  We compute this using back-substitutions to avoid explicitly forming ``K^-1``.  ``C_{l,j}``\n  is ``num_sampled`` X ``num_to_sample``.\n\n  Then ``D_{d,i=p,j} = \\pderiv{Ks_{i=p,l}}{Xs_{d,p}} * C_{l,j}`` is another matrix product (result size ``dim * num_to_sample``)\n  (``i = p`` indicates that index ``i`` collapses out since this deriv term is zero if ``p != i``).\n  Note that we store ``\\pderiv{Ks_{i=p,l}}{Xs_{d,p}} = \\pderiv{Ks_{l,i=p}}{Xs_{d,p}}`` as ``A_{d,l,i}``\n  and grab the ``i = p``-th block.\n\n  Again, only the ``p``-th point of ``points_to_sample`` is differentiated against; ``p`` specfied in ``diff_index``.\n\\endrst*/\n\nvoid GaussianProcess::ComputeGradCovarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                            double const * restrict discrete_pts, int num_pts,\n                                                            int const * restrict gradients_discrete_pts,\n                                                            int num_gradients_discrete_pts,\n                                                            bool precomputed, double const * kt,\n                                                            double * restrict grad_var) const noexcept {\n  const int num_to_sample = points_to_sample_state->num_to_sample;\n  const int num_gradients_to_sample = points_to_sample_state->num_gradients_to_sample;\n\n  // we only visit a small subset of the entries in this matrix; need to ensure the others are zero'd\n  std::fill(grad_var, grad_var + dim_*num_to_sample*(num_gradients_to_sample+1)*num_pts*(num_gradients_discrete_pts+1), 0.0);\n\n  // Compute: \\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j} (the second term in DVvars, above).\n  // Retrieve C_{l,j} = K^-1_{l,k} * Ks_{k,j}, from C stored in K_inv_times_K_star\n  // Retrieve \\pderiv{Ks_{l,i=p}}{Xs_{d,p}} from state struct (stored as A_{d,l,p}), use in matrix product\n  // Result is computed as: A_{d,l,p} * C_{l,j}.  (Again, recall that p is fixed, so this output is over a matrix indexed {d,j}.)\n  double * temp = new double[dim_*num_pts*(num_gradients_discrete_pts+1)*(num_gradients_to_sample+1)]();\n\n  if (precomputed){\n    int index = 0;\n    for (int i=0; i<num_gradients_to_sample+1; ++i){\n        index = diff_index*(num_gradients_to_sample+1) + i;\n        GeneralMatrixMatrixMultiply(points_to_sample_state->grad_K_star.data() +\n                                    index*dim_*num_sampled_*(num_derivatives_+1), 'N', kt, 1.0, 0.0,\n                                    dim_, num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), temp);\n        temp += dim_*num_pts*(num_gradients_discrete_pts+1);\n    }\n  }\n  else{\n    int index = 0;\n    for (int i=0; i<num_gradients_to_sample+1; ++i){\n        index = diff_index*(num_gradients_to_sample+1) + i;\n        GeneralMatrixMatrixMultiply(points_to_sample_state->grad_K_inv_times_K_star.data() +\n                                    index*dim_*num_sampled_*(num_derivatives_+1), 'N', kt, 1.0, 0.0,\n                                    dim_, num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), temp);\n        temp += dim_*num_pts*(num_gradients_discrete_pts+1);\n    }\n  }\n  temp -= dim_*num_pts*(num_gradients_discrete_pts+1)*(num_gradients_to_sample+1);\n\n  std::vector<double> grad_cov_temp(dim_*(num_gradients_to_sample+1)*(num_gradients_discrete_pts+1), 0.0);\n  int row = 0;\n  int col = 0;\n  // Fill the p-th block column of the output (p = diff_index); we will then copy this into the p-th block column.\n  for (int j = 0; j < num_pts; ++j) {\n      // Compute the leading term: \\pderiv{K_ss{i=p,j}}{Xs_{d,p}}.\n      covariance_ptr_->GradCovariance(points_to_sample_state->points_to_sample.data() + diff_index*dim_,\n                                      points_to_sample_state->gradients.data(), num_gradients_to_sample,\n                                      discrete_pts + j*dim_, gradients_discrete_pts, num_gradients_discrete_pts,\n                                      grad_cov_temp.data());\n      for (int m = 0; m < num_gradients_to_sample+1; ++m){\n          for (int n = 0; n < num_gradients_discrete_pts+1; ++n){\n              for (int d = 0 ; d < dim_; ++d){\n                  row = m + diff_index * (num_gradients_to_sample+1);\n                  col = n + j * (num_gradients_discrete_pts+1);\n                  grad_var[d + row*dim_ + col*dim_*num_to_sample*(num_gradients_to_sample+1)] =\n                       grad_cov_temp[d + dim_*m + n*dim_*(num_gradients_to_sample+1)]-\n                       temp[d + dim_ * col + dim_*num_pts*(num_gradients_discrete_pts+1) * m]; // Flip the sign, add leading term in.\n              }\n          }\n      }\n  }\n  delete[] temp;\n}\n\n/*!\\rst\n  This is just a thin wrapper that calls ComputeGradCovarianceOfPointsPerPoint() in a loop ``num_derivatives`` times.\n\n  See ComputeGradVarianceOfPointsPerPoint()'s function comments and implementation for more mathematical details\n  on the derivation, algorithm, optimizations, etc.\n\\endrst*/\n\nvoid GaussianProcess::ComputeGradCovarianceOfPoints(StateType * points_to_sample_state,\n                                                    double const * restrict discrete_pts,\n                                                    int num_pts, int const * restrict gradients_discrete_pts,\n                                                    int num_gradients_discrete_pts, bool precomputed, double const * ktd,\n                                                    double * restrict grad_var) const noexcept {\n    int block_size = (points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1)*\n                     dim_*num_pts*(num_gradients_discrete_pts+1);\n\n    if (precomputed == false) {\n      // Compute K_t\n      double * kt = new double[num_sampled_*(num_derivatives_+1)*num_pts*(num_gradients_discrete_pts+1)]();\n      BuildMixCovarianceMatrix(discrete_pts, num_pts, gradients_discrete_pts, num_gradients_discrete_pts, kt);\n      if(points_to_sample_state->precomputed_grad_K_inv_times_K_star) {\n        for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n            ComputeGradCovarianceOfPointsPerPoint(points_to_sample_state, k, discrete_pts, num_pts,\n                                                  gradients_discrete_pts, num_gradients_discrete_pts,\n                                                  false, kt, grad_var);\n            grad_var += block_size;\n        }\n      }\n      else {\n        // Compute K^-1 * K_t\n        CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1), num_pts*(num_gradients_discrete_pts+1), kt);\n        for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n            ComputeGradCovarianceOfPointsPerPoint(points_to_sample_state, k, discrete_pts, num_pts,\n                                                  gradients_discrete_pts, num_gradients_discrete_pts,\n                                                  true, kt, grad_var);\n            grad_var += block_size;\n        }\n      }\n      delete [] kt;\n    }\n    else{\n        for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n            ComputeGradCovarianceOfPointsPerPoint(points_to_sample_state, k, discrete_pts, num_pts,\n                                                  gradients_discrete_pts, num_gradients_discrete_pts,\n                                                  true, ktd, grad_var);\n            grad_var += block_size;\n        }\n    }\n}\n\n/*!\\rst\n  **CORE IDEA**\n\n  Similar to ComputeGradCholeskyVarianceOfPoints() below, except this function does not account for the cholesky decomposition.  That is,\n  it produces derivatives wrt ``Xs_{d,p}`` (``points_to_sample``) of:\n\n  ``Vars = Kss - (V^T * V) = Kss - Ks^T * K^-1 * Ks`` (see ComputeVarianceOfPoints)\n\n  .. NOTE:: normally ``Xs_p`` would be the ``p``-th point of Xs (all dimensions); here ``Xs_{d,p}`` more explicitly\n      refers to the ``d``-th spatial dimension of the ``p``-th point.\n\n  This function only returns the derivative wrt a single choice of ``p``, as specified by ``diff_index``.\n\n  Expanded index notation:\n\n  ``Vars_{i,j} = Kss_{i,j} - Ks^T_{i,l} * K^-1_{l,k} * Ks_{k,j}``\n\n  Recall ``Ks_{k,i} = cov(X_k, Xs_i) = cov(Xs_i, X_k)`` where ``Xs`` is ``points_to_sample`` and ``X`` is ``points_sampled``.\n  (Note this is not equivalent to saying ``Ks = Ks^T``, although this would be true if ``|Xs| == |X|``.)\n  As a result of this symmetry, ``\\pderiv{Ks_{k,i}}{Xs_{d,i}} = \\pderiv{Ks_{i,k}}{Xs_{d,i}}`` (that's ``d(cov(Xs_i, X_k))/d(Xs_i)``)\n\n  We are being more strict with index labels than is standard to clearly specify tensor dimensions.  To be clear:\n  1. ``i,j`` range over ``num_to_sample``\n  2. ``l,k`` are the only non-free indices; they range over ``num_sampled``\n  3. ``d,p`` describe the SPECIFIC point being differentiated against in ``Xs`` (``points_to_sample``): ``d`` over dimension, ``p``\\* over ``num_to_sample``\n\n  \\*NOTE: ``p`` is *fixed*! Unlike all other indices, ``p`` refers to a *SPECIFIC* point in the range ``[0, ..., num_to_sample-1]``.\n          Thus, ``\\pderiv{Ks_{k,i}}{Xs_{d,i}}`` is a 3-tensor (``A_{d,k,i}``) (repeated ``i`` is not summation since they denote\n          components of a derivative) while ``\\pderiv{Ks_{i,l}}{Xs_{d,p}}`` is a 2-tensor (``A_{d,l}``) b/c only\n          ``\\pderiv{Ks_{i=p,l}}{Xs_{d,p}}`` is nonzero, and ``{d,l}`` are the only remaining free indices.\n\n  Then differentiating against ``Xs_{d,p}`` (recall that this is a specific point b/c p is fixed):\n\n  | ``\\pderiv{Vars_{i,j}}{Xs_{d,p}} = \\pderiv{K_ss{i,j}}{Xs_{d,p}} -``\n  | ``(\\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   +  K_s{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}})``\n\n  Many of these terms are analytically known to be 0: ``\\pderiv{Ks_{i,l}}{Xs_{d,p}} = 0`` when ``p != i`` (see NOTE above).\n  A similar statement holds for the other gradient term.\n\n  Observe that the second term in the parens, ``Ks_{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}}``, can be reordered\n  to \"look\" like the first term.  We use three symmetries: ``K^-1{l,k} = K^-1{k,l}``, ``Ks_{i,l} = Ks_{l,i}``, and\n\n  ``\\pderiv{Ks_{k,j}}{Xs_{d,p}} = \\pderiv{Ks_{j,k}}{Xs_{d,p}}``\n\n  Then we can write:\n\n  ``K_s{i,l} * K^-1_{l,k} * \\pderiv{Ks_{k,j}}{Xs_{d,p}} = \\pderiv{Ks_{j,k}}{Xs_{d,p}} * K^-1_{k,l} * K_s{l,i}``\n\n  Now left and right terms have the same index ordering (i,j match; k,l are not free and thus immaterial)\n\n  The final result, accounting for analytic zeros is given here for convenience::\n\n    DVars_{d,i,j} \\equiv \\pderiv{Vars_{i,j}}{Xs_{d,p}} =``\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} - 2*\\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   :  WHEN p == i == j\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} -   \\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j}   :  WHEN p == i != j\n      { \\pderiv{K_ss{i,j}}{Xs_{d,p}} -   \\pderiv{Ks_{j,k}}{Xs_{d,p}} * K^-1_{k,l} * Ks_{l,i}   :  WHEN p == j != i\n      {                                    0                                                   :  otherwise\n\n  The first item has a factor of 2 b/c it gets a contribution from both parts of the sum since ``p == i`` and ``p == j``.\n  The ordering ``DVars_{d,i,j}`` is significant: this is the ordering (d changes the fastest) in storage.\n\n  **OPTIMIZATIONS**\n\n  Implementing this formula naively results in a large amount of redundant computation, so we now describe the optimizations\n  present in our implementation.\n\n  The first thing to notice is that the result, ``\\pderiv{Vars_{i,j}}{Xs_{d,p}}``, has a lot of 0s.  In particular, only the\n  ``p``-th block row and ``p``-th block column have nonzero entries (blocks are size ``dim``, indexed ``d``).  Currently,\n  we will not be taking advantage of this sparsity because the consumer of DVars, ComputeGradCholeskyVarianceOfPoints(),\n  is not implemented with sparsity in mind.\n\n  Similarly, the next thing to notice is that if we ignore the case ``p == i == j``, then we see that the expressions for\n  ``p == i`` and ``p == j`` are actually identical (e.g., take the ``p == j`` case and exchange ``j = i`` and ``k = l``).\n\n  So think of ``DVars`` as a block matrix; each block has dimension entries, and the blocks are indexed over\n  ``i`` (rows), ``j`` (cols).  Then we see that the code is block-symmetric: ``DVars_{d,i,j} = Dvars_{d,j,i}``.\n  So we can compute it by filling in the ``p``-th block column and then copy that data into the ``p``-th block row.\n\n  Additionally, the derivative terms represent matrix-matrix products:\n  ``C_{l,j} = K^-1_{l,k} * Ks_{k,j}`` (and ``K^-1_{k,l} * Ks_{l,i}``, which is just a change of index labels) is\n  a matrix product.  We compute this using back-substitutions to avoid explicitly forming ``K^-1``.  ``C_{l,j}``\n  is ``num_sampled`` X ``num_to_sample``.\n\n  Then ``D_{d,i=p,j} = \\pderiv{Ks_{i=p,l}}{Xs_{d,p}} * C_{l,j}`` is another matrix product (result size ``dim * num_to_sample``)\n  (``i = p`` indicates that index ``i`` collapses out since this deriv term is zero if ``p != i``).\n  Note that we store ``\\pderiv{Ks_{i=p,l}}{Xs_{d,p}} = \\pderiv{Ks_{l,i=p}}{Xs_{d,p}}`` as ``A_{d,l,i}``\n  and grab the ``i = p``-th block.\n\n  Again, only the ``p``-th point of ``points_to_sample`` is differentiated against; ``p`` specfied in ``diff_index``.\n\\endrst*/\nvoid GaussianProcess::ComputeGradVarianceOfPointsPerPoint(StateType * points_to_sample_state,\n                                                          int diff_index,\n                                                          double * restrict grad_var) const noexcept {\n  const int num_to_sample = points_to_sample_state->num_to_sample;\n  const int num_gradients_to_sample = points_to_sample_state->num_gradients_to_sample;\n\n  // we only visit a small subset of the entries in this matrix; need to ensure the others are zero'd\n  std::fill(grad_var, grad_var + dim_*Square(num_to_sample*(num_gradients_to_sample+1)), 0.0);\n\n  // Compute: \\pderiv{Ks_{i,l}}{Xs_{d,p}} * K^-1_{l,k} * Ks_{k,j} (the second term in DVvars, above).\n  // Retrieve C_{l,j} = K^-1_{l,k} * Ks_{k,j}, from C stored in K_inv_times_K_star\n  // Retrieve \\pderiv{Ks_{l,i=p}}{Xs_{d,p}} from state struct (stored as A_{d,l,p}), use in matrix product\n  // Result is computed as: A_{d,l,p} * C_{l,j}.  (Again, recall that p is fixed, so this output is over a matrix indexed {d,j}.)\n  // Fill the p-th block column of the output (p = diff_index); we will then copy this into the p-th block column.\n\n  double * restrict grad_var_target_column = grad_var + (dim_*num_to_sample*(num_gradients_to_sample+1)*\n                                                         diff_index*(num_gradients_to_sample+1));\n  for (int i = 0; i<num_gradients_to_sample+1; ++i){ //col\n      int col = diff_index*(num_gradients_to_sample+1)+i;\n\n      GeneralMatrixMatrixMultiply(points_to_sample_state->grad_K_star.data() + col*dim_*num_sampled_*(num_derivatives_+1), 'N',\n                                  points_to_sample_state->K_inv_times_K_star.data(), 1.0, 0.0, dim_,\n                                  num_sampled_*(num_derivatives_+1), num_to_sample*(num_gradients_to_sample+1), grad_var_target_column);\n\n      for (int j = 0; j < num_to_sample; ++j) {//row\n          for (int n = 0; n < num_gradients_to_sample+1; ++n){//row\n              for (int d = 0; d<dim_; d++){\n                  grad_var_target_column[d] *= -1.0;\n              }\n              grad_var_target_column += dim_;\n          }\n      }\n  }\n\n  for (int m = 0; m < num_gradients_to_sample+1; ++m){\n      for (int n = m; n < num_gradients_to_sample+1; ++n){\n          for (int d = 0; d<dim_; d++){\n              int row = diff_index*(num_gradients_to_sample+1) + m;\n              int col = diff_index*(num_gradients_to_sample+1) + n;\n              grad_var[d+row*dim_+col*dim_*num_to_sample*(1+num_gradients_to_sample)] += grad_var[d+col*dim_+row*dim_*num_to_sample*(1+num_gradients_to_sample)];\n              grad_var[d+col*dim_+row*dim_*num_to_sample*(1+num_gradients_to_sample)] = grad_var[d+row*dim_+col*dim_*num_to_sample*(1+num_gradients_to_sample)];\n          }\n      }\n  }\n\n  std::vector<double> temp_grad_cov(dim_*Square(num_gradients_to_sample+1), 0.0);\n  //add the leading term in.\n  for (int j = 0; j < num_to_sample; ++j) {\n      // Compute the leading term: \\pderiv{K_ss{i=p,j}}{Xs_{d,p}}.\n      covariance_ptr_->GradCovariance(points_to_sample_state->points_to_sample.data() + diff_index*dim_,\n                                      points_to_sample_state->gradients.data(), num_gradients_to_sample,\n                                      points_to_sample_state->points_to_sample.data() + j*dim_,\n                                      points_to_sample_state->gradients.data(), num_gradients_to_sample,\n                                      temp_grad_cov.data());\n\n      for (int m = 0; m < num_gradients_to_sample+1; ++m){\n          for (int n = 0; n < num_gradients_to_sample+1; ++n){\n              int row = j*(num_gradients_to_sample+1)+m;\n              int col = diff_index*(num_gradients_to_sample+1)+n;\n              for (int d = 0; d < dim_; ++d){\n                  if (j == diff_index){\n                      //diff_index is the row for temp_grad_cov.\n                      grad_var[d+row*dim_+col*dim_*num_to_sample*(num_gradients_to_sample+1)] +=\n                            temp_grad_cov[d+n*dim_+m*dim_*(num_gradients_to_sample+1)] +\n                            temp_grad_cov[d+m*dim_+n*dim_*(num_gradients_to_sample+1)];\n                  } else{\n                      grad_var[d+row*dim_+col*dim_*num_to_sample*(num_gradients_to_sample+1)] +=\n                                       temp_grad_cov[d+n*dim_+m*dim_*(num_gradients_to_sample+1)];\n                  }\n              }\n          }\n      }\n  }\n\n  // copy column into the row\n  for (int i = 0; i<num_gradients_to_sample+1; ++i){ //row\n      int row = diff_index*(num_gradients_to_sample+1)+i;\n      for (int j = 0; j < num_to_sample; ++j) {\n          // Skip the diagonal block (we'd just be copying it onto itself).\n          for (int n = 0; n < num_gradients_to_sample+1; ++n){\n              int col = j*(num_gradients_to_sample+1)+n;\n              if (j != diff_index) {\n                  // From function comments, the matrix is block-symmetric so we just copy directly.\n                  for (int m = 0; m < dim_; ++m) {\n                        grad_var[m+dim_*row+dim_*(num_gradients_to_sample+1)*num_to_sample*col] =\n                           grad_var[m+dim_*col+dim_*(num_gradients_to_sample+1)*num_to_sample*row];\n                  }\n              }\n          }\n      }\n  }\n}\n\n/*!\\rst\n  This is just a thin wrapper that calls ComputeGradVarianceOfPointsPerPoint() in a loop ``num_derivatives`` times.\n\n  See ComputeGradVarianceOfPointsPerPoint()'s function comments and implementation for more mathematical details\n  on the derivation, algorithm, optimizations, etc.\n\\endrst*/\nvoid GaussianProcess::ComputeGradVarianceOfPoints(StateType * points_to_sample_state,\n                                                  double * restrict grad_var) const noexcept {\n  int block_size = Square(points_to_sample_state->num_to_sample*(points_to_sample_state->num_gradients_to_sample+1))*dim_;\n  for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n    ComputeGradVarianceOfPointsPerPoint(points_to_sample_state, k, grad_var);\n    grad_var += block_size;\n  }\n}\n\n/*!\\rst\n  Differentiates the cholesky factorization of the GP variance.\n\n  | ``Vars = Kss - (V^T * V)``  (see ComputeVarianceOfPoints)\n  | ``C * C^T = Vars``\n\n  This function differentiates ``C`` wrt the ``p``-th point of ``points_to_sample``; ``p`` specfied in ``diff_index``\n\n  Just as users of a lower triangular matrix ``L[i][j]`` should not access the upper triangle (``j > i``), users of\n  the result of this function, ``grad_chol[d][i][j]``, should not access the upper *block* triangle with ``j > i``.\n\n  See Smith 1995 for full details of computing gradients of the cholesky factorization\n  ** store in the UPPER triangle.\n\\endrst*/\nvoid GaussianProcess::ComputeGradCholeskyVarianceOfPointsPerPoint(StateType * points_to_sample_state,\n                                                                  int diff_index, double const * restrict chol_var,\n                                                                  double * restrict grad_chol) const noexcept {\n    ComputeGradVarianceOfPointsPerPoint(points_to_sample_state, diff_index, grad_chol);\n\n    // TODO(GH-173): Try reorganizing Smith's algorithm to use an ordering analogous to the gaxpy\n    // formulation of cholesky (currently it's organized like the outer-product version which results in\n    // more memory accesses).\n\n    int num_to_sample = points_to_sample_state->num_to_sample;\n    const int num_gradients_to_sample = points_to_sample_state->num_gradients_to_sample;\n\n    num_to_sample *= (1+num_gradients_to_sample);\n    // input is upper block triangular, zero the lower block triangle\n    for (int i = 0; i < num_to_sample; ++i) { //col\n        int end_index = dim_*num_to_sample;\n        // In GV_{mji}, each j > i specifies a lower diagonal block; each block has dim_ elements.\n        // So we start on the (i+1)-th block and go to the end of this block column.\n        for (int j = (i+1)*dim_; j < end_index; ++j) { //row\n            grad_chol[j] = 0.0;\n        }\n        grad_chol += num_to_sample*dim_;\n    }\n    grad_chol -= num_to_sample*num_to_sample*dim_;\n\n    // Loop annotations match those in ComputeCholeskyFactorL() to describe what each segment differentiates and how.\n    // In the following comments, L_{ij} := chol_var[j*num_to_sample + i] is the cholesky factorization of the variance,\n    // and GV_{mij} := grad_chol[j*num_to_sample*dim_ + i*dim_ + m] is the gradient of variance (input),\n    // and GL_{mij} := grad_chol[j*num_to_sample*dim_ + i*dim_ + m] is the gradient of cholesky of variance (on exit)\n    // Define macros specifying the data layout assumption on L_{ij} and GV_{mij}. The macro simplifies complex indexing\n    // so that OL_CHOL_VAR(i, j) reads just like L_{ij}, for example.\n#define OL_CHOL_VAR(i, j) chol_var[((j)*num_to_sample + (i))]\n#define OL_GRAD_CHOL(m, i, j) grad_chol[((j)*num_to_sample*dim_ + (i)*dim_ + (m))]\n\n    for (int k = 0; k < num_to_sample; ++k) {\n        // L_kk := L_{kk}\n        const double L_kk = OL_CHOL_VAR(k, k);\n\n        if (likely(L_kk > kMinimumStdDev)) {\n            // differentiates L_kk := L_{kk}\n            // GL_{mkk} = 0.5 * GV_{mkk}/L_{kk}\n            for (int m = 0; m < dim_; ++m) {\n                OL_GRAD_CHOL(m, k, k) = 0.5*OL_GRAD_CHOL(m, k, k)/L_kk;\n            }\n\n            // differentiates L_{jk} = L_{jk}/L_{kk}\n            // GL_{mkj} = (GV_{mkj} - L_{jk}*GV_{mkk})/L_{kk}\n            for (int j = k+1; j < num_to_sample; ++j) {\n                for (int m = 0; m < dim_; ++m) {\n                    OL_GRAD_CHOL(m, k, j) = (OL_GRAD_CHOL(m, k, j) - OL_CHOL_VAR(j, k)*OL_GRAD_CHOL(m, k, k))/L_kk;\n                }\n            }  // end for j: num_to_sample\n\n            // differentiates L_{ij} = L_{ij} - L_{ik}*L_{jk}\n            // GL_{mji} = GV_{mji} - GV_{mki}*L_{jk} - L_{ik}*GV_{mkj}\n            for (int j = k+1; j < num_to_sample; ++j) {\n                for (int i = j; i < num_to_sample; ++i) {\n                    for (int m = 0; m < dim_; ++m) {\n                        OL_GRAD_CHOL(m, j, i) = OL_GRAD_CHOL(m, j, i)\n                        - OL_GRAD_CHOL(m, k, i)*OL_CHOL_VAR(j, k) - OL_CHOL_VAR(i, k)*OL_GRAD_CHOL(m, k, j);\n                    }\n                }  // end for i: num_to_sample\n            }  // end for j: num_to_sample\n        } else {\n            OL_ERROR_PRINTF(\"Grad Cholesky failed; matrix singular. k=%d\\n\", k);\n        }  // end if: L_kk is not \"too small\"\n    }  // end for k: sie_of_to_sample\n#undef OL_CHOL_VAR\n#undef OL_GRAD_CHOL\n}\n\n/*!\\rst\n  This is just a thin wrapper that calls ComputeGradCholeskyVarianceOfPointsPerPoint() in a loop ``num_derivatives`` times.\n\n  See ComputeGradCholeskyVarianceOfPointsPerPoint()'s function comments and implementation for more mathematical\n  details on the algorithm.\n\\endrst*/\nvoid GaussianProcess::ComputeGradCholeskyVarianceOfPoints(StateType * points_to_sample_state,\n                                                          double const * restrict chol_var,\n                                                          double * restrict grad_chol) const noexcept {\n    int block_size = Square(points_to_sample_state->num_to_sample * (points_to_sample_state->num_gradients_to_sample+1))*dim_;\n    for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        ComputeGradCholeskyVarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, grad_chol);\n        grad_chol += block_size;\n    }\n}\n\n/*!\\rst\nCompute the derivatives of the inverse of the cholesky factor wrt to the points to sample.\n\\endrst*/\nvoid GaussianProcess::ComputeGradInverseCholeskyVarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                                         double const * restrict chol_var,\n                                                                         double const * restrict var,\n                                                                         double const * restrict cov,\n                                                                         double const * restrict discrete_pts,\n                                                                         int num_pts, bool precomputed, double const * kt,\n                                                                         double * restrict grad_chol) const noexcept {\n    int num_to_sample = points_to_sample_state->num_to_sample;\n    int num_to_sample_gradients = num_to_sample*(1+points_to_sample_state->num_gradients_to_sample);\n\n    std::vector<double> grad_chol_temp(Square(num_to_sample_gradients) * dim_);\n    ComputeGradCholeskyVarianceOfPointsPerPoint(points_to_sample_state, diff_index, chol_var, grad_chol_temp.data());\n\n    std::vector<double> grad_cov(num_to_sample_gradients * (num_pts+num_to_sample_gradients) * dim_);\n    ComputeGradCovarianceOfPointsPerPoint(points_to_sample_state, diff_index, discrete_pts, num_pts, nullptr, 0,\n                                          precomputed, kt, grad_cov.data());\n    ComputeGradVarianceOfPointsPerPoint(points_to_sample_state, diff_index, grad_cov.data()+num_to_sample_gradients*num_pts*dim_);\n    for (int i = 0; i < dim_; ++i) {\n         //part 1\n         double* temp = new double[num_to_sample_gradients*(num_to_sample+num_pts)]();\n\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_pts; ++l){\n                 temp[j+l*num_to_sample_gradients] = grad_cov[i + j*dim_ + l*dim_*num_to_sample_gradients];\n             }\n         }\n\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_to_sample; ++l){\n                 temp[j+(l+num_pts)*num_to_sample_gradients] = grad_cov[i + j*dim_ + (l*(1+points_to_sample_state->num_gradients_to_sample)+num_pts)*dim_*num_to_sample_gradients];\n             }\n         }\n         TriangularMatrixMatrixSolve(chol_var,'N',num_to_sample_gradients,num_pts+num_to_sample,num_to_sample_gradients,temp);\n\n         //part 2\n         // let L_{d,i,j,k} = grad_chol_decomp, d over dim_, i, j over num_union, k over num_to_sample\n         // we want to compute: agg_dx_{d,*,*,k} = -L_{d,*,*,k}^{-1} * dL_{d,*,*,k} * L_{d,*,*,k}^{-1} * Cov(*,*)\n         // TODO(GH-92): Form this as one GeneralMatrixVectorMultiply() call by storing data as L_{d,i,k,j} if it's faster.\n\n         double* temp_chol = new double[num_to_sample_gradients*num_to_sample_gradients]();\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = j; l < num_to_sample_gradients; ++l){\n                 temp_chol[l+j*num_to_sample_gradients] = grad_chol_temp[i + j*dim_ + l*dim_*num_to_sample_gradients];\n             }\n         }\n         TriangularMatrixMatrixSolve(chol_var,'N',num_to_sample_gradients, num_to_sample_gradients, num_to_sample_gradients, temp_chol);\n\n         double* temp_cov = new double[num_to_sample_gradients*(num_pts+num_to_sample)]();\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_pts; ++l){\n                 temp_cov[j+l*num_to_sample_gradients] = cov[j+l*num_to_sample_gradients];\n             }\n         }\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_to_sample; ++l){\n                 temp_cov[j+(l+num_pts)*num_to_sample_gradients] = var[j+l*num_to_sample_gradients];\n             }\n         }\n\n         TriangularMatrixMatrixSolve(chol_var,'N',num_to_sample_gradients, num_pts+num_to_sample, num_to_sample_gradients, temp_cov);\n\n         GeneralMatrixMatrixMultiply(temp_chol, 'N', temp_cov, -1.0, 1.0, num_to_sample_gradients, num_to_sample_gradients, num_pts+num_to_sample, temp);\n\n         delete[] temp_cov;\n         delete[] temp_chol;\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_pts+num_to_sample; ++l){\n                 //grad_chol[i + j*dim_ + l*dim_*num_to_sample + k*dim_*num_to_sample*num_pts] = temp[j+l*num_to_sample];\n                 grad_chol[i + j*dim_ + l*dim_*num_to_sample_gradients] = temp[j+l*num_to_sample_gradients];\n             }\n         }\n         delete[] temp;\n    }\n}\n\n/*!\\rst\nCompute the derivatives of the inverse of the cholesky factor wrt to the points to sample.\n\\endrst*/\nvoid GaussianProcess::ComputeGradInverseCholeskyVarianceOfPoints(StateType * points_to_sample_state,\n                                                                 double const * restrict chol_var,\n                                                                 double const * restrict var,\n                                                                 double const * restrict cov,\n                                                                 double const * restrict discrete_pts,\n                                                                 int num_pts, bool precomputed, double const * ktd,\n                                                                 double * restrict grad_chol) const noexcept {\n  int block_size = (points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1)*\n                   dim_*(num_pts+points_to_sample_state->num_to_sample);\n\n  if (precomputed == false) {\n    // Compute K_t\n    double * kt = new double[num_sampled_*(num_derivatives_+1)*num_pts]();\n    BuildMixCovarianceMatrix(discrete_pts, num_pts, nullptr, 0, kt);\n    if(points_to_sample_state->precomputed_grad_K_inv_times_K_star) {\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        ComputeGradInverseCholeskyVarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, var, cov,\n                                                           discrete_pts, num_pts, false, kt, grad_chol);\n        grad_chol += block_size;\n      }\n    }\n    else {\n      // Compute K^-1 * K_t\n      CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1), num_pts, kt);\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        ComputeGradInverseCholeskyVarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, var, cov,\n                                                           discrete_pts, num_pts, true, kt, grad_chol);\n        grad_chol += block_size;\n      }\n    }\n    delete [] kt;\n  }\n  else{\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        ComputeGradInverseCholeskyVarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, var, cov,\n                                                           discrete_pts, num_pts, true, ktd, grad_chol);\n        grad_chol += block_size;\n      }\n  }\n}\n\n/*!\\rst\nCompute the derivatives of the inverse of the cholesky factor wrt to the points to sample.\n\\endrst*/\nvoid GaussianProcess::ComputeGradInverseCholeskyCovarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                                         double const * restrict chol_var,\n                                                                         double const * restrict grad_chol_pt,\n                                                                         double const * restrict chol_inv_times_cov,\n                                                                         double const * restrict discrete_pts,\n                                                                         int num_pts, bool precomputed, double const * kt,\n                                                                         double * restrict grad_inverse_chol) const noexcept {\n    int num_to_sample = points_to_sample_state->num_to_sample;\n    int num_to_sample_gradients = num_to_sample*(1+points_to_sample_state->num_gradients_to_sample);\n    std::vector<double> grad_cov(num_to_sample_gradients * num_pts * dim_);\n\n    ComputeGradCovarianceOfPointsPerPoint(points_to_sample_state, diff_index, discrete_pts, num_pts, nullptr, 0,\n                                          precomputed, kt, grad_cov.data());\n\n    for (int i = 0; i < dim_; ++i) {\n         //part 1\n         double* temp = new double[num_to_sample_gradients*num_pts]();\n\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_pts; ++l){\n                 temp[j+l*num_to_sample_gradients] = grad_cov[i + j*dim_ + l*dim_*num_to_sample_gradients];\n             }\n         }\n\n         TriangularMatrixMatrixSolve(chol_var,'N', num_to_sample_gradients, num_pts, num_to_sample_gradients, temp);\n\n         //part 2\n         // let L_{d,i,j,k} = grad_chol_decomp, d over dim_, i, j over num_union, k over num_to_sample\n         // we want to compute: agg_dx_{d,*,*,k} = -L_{d,*,*,k}^{-1} * dL_{d,*,*,k} * L_{d,*,*,k}^{-1} * Cov(*,*)\n         // TODO(GH-92): Form this as one GeneralMatrixVectorMultiply() call by storing data as L_{d,i,k,j} if it's faster.\n\n         double* temp_chol = new double[num_to_sample_gradients*num_to_sample_gradients]();\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = j; l < num_to_sample_gradients; ++l){\n                 temp_chol[l+j*num_to_sample_gradients] = grad_chol_pt[i + j*dim_ + l*dim_*num_to_sample_gradients];\n             }\n         }\n         TriangularMatrixMatrixSolve(chol_var,'N',num_to_sample_gradients, num_to_sample_gradients, num_to_sample_gradients, temp_chol);\n\n         GeneralMatrixMatrixMultiply(temp_chol, 'N', chol_inv_times_cov, -1.0, 1.0, num_to_sample_gradients, num_to_sample_gradients, num_pts, temp);\n\n         delete[] temp_chol;\n         for (int j = 0; j < num_to_sample_gradients; ++j){\n             for (int l = 0; l < num_pts; ++l){\n                 //grad_chol[i + j*dim_ + l*dim_*num_to_sample + k*dim_*num_to_sample*num_pts] = temp[j+l*num_to_sample];\n                 grad_inverse_chol[i + j*dim_ + l*dim_*num_to_sample_gradients] = temp[j+l*num_to_sample_gradients];\n             }\n         }\n         delete[] temp;\n    }\n}\n\n/*!\\rst\nCompute the derivatives of the inverse of the cholesky factor wrt to the points to sample.\n\\endrst*/\nvoid GaussianProcess::ComputeGradInverseCholeskyCovarianceOfPoints(StateType * points_to_sample_state,\n                                                                 double const * restrict chol_var,\n                                                                 double const * restrict grad_chol,\n                                                                 double const * restrict chol_inv_times_cov,\n                                                                 double const * restrict discrete_pts,\n                                                                 int num_pts, bool precomputed, double const * ktd,\n                                                                 double * restrict grad_inverse_chol) const noexcept {\n  int block_size = (points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1)* dim_*num_pts;\n\n  if (precomputed == false) {\n    // Compute K_t\n    double * kt = new double[num_sampled_*(num_derivatives_+1)*num_pts]();\n    BuildMixCovarianceMatrix(discrete_pts, num_pts, nullptr, 0, kt);\n    if(points_to_sample_state->precomputed_grad_K_inv_times_K_star) {\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        double const * restrict grad_chol_pt = grad_chol + k*Square((points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1))*dim_;\n        ComputeGradInverseCholeskyCovarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, grad_chol_pt, chol_inv_times_cov,\n                                                             discrete_pts, num_pts, false, kt, grad_inverse_chol);\n        grad_inverse_chol += block_size;\n      }\n    }\n    else {\n      // Compute K^-1 * K_t\n      CholeskyFactorLMatrixMatrixSolve(K_chol_.data(), num_sampled_*(num_derivatives_+1), num_pts, kt);\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        double const * restrict grad_chol_pt = grad_chol + k*Square((points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1))*dim_;\n        ComputeGradInverseCholeskyCovarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, grad_chol_pt, chol_inv_times_cov,\n                                                             discrete_pts, num_pts, true, kt, grad_inverse_chol);\n        grad_inverse_chol += block_size;\n      }\n    }\n    delete [] kt;\n  }\n  else {\n      for (int k = 0; k < points_to_sample_state->num_derivatives; ++k) {\n        double const * restrict grad_chol_pt = grad_chol + k*Square((points_to_sample_state->num_to_sample)*(points_to_sample_state->num_gradients_to_sample+1))*dim_;\n        ComputeGradInverseCholeskyCovarianceOfPointsPerPoint(points_to_sample_state, k, chol_var, grad_chol_pt, chol_inv_times_cov,\n                                                             discrete_pts, num_pts, true, ktd, grad_inverse_chol);\n        grad_inverse_chol += block_size;\n      }\n  }\n}\n\nvoid GaussianProcess::AddPointsToGP(double const * restrict new_points,\n                                    double const * restrict new_points_value,\n//                                    double const * restrict new_points_noise_variance,\n                                    int num_new_points) {\n  // update sizes\n  num_sampled_ += num_new_points;\n\n  // update state variables\n  points_sampled_.resize(num_sampled_*dim_);\n  std::copy_backward(new_points, new_points + num_new_points*dim_, points_sampled_.end());\n\n  points_sampled_value_.resize(num_sampled_*(num_derivatives_+1));\n  std::copy_backward(new_points_value, new_points_value + num_new_points*(num_derivatives_+1), points_sampled_value_.end());\n\n//  noise_variance_.resize(num_sampled_);\n//  std::copy_backward(new_points_noise_variance, new_points_noise_variance + num_new_points, noise_variance_.end());\n\n  // recompute derived quantities\n  // TODO(GH-192): Insert the new covariance (and cholesky covariance) rows into the current matrix  (O(N^2))\n  // instead of recomputing everything (O(N^3)).\n  RecomputeDerivedVariables();\n}\n\n/*!\\rst\n  Samples function values from a GPP given a list of points.\n\n  Samples by: ``function_value = gpp_mean + gpp_variance * w``, where ``w`` is a single draw from N(0,1).\n\n  We only draw one point at a time (i.e., ``num_to_sample`` fixed at 1).  We want multiple draws from the same GPP;\n  drawing many points per step would be akin to sampling multiple GPPs. Thus gpp_mean, gpp_variance, and w all have size 1.\n\n  If the GPP does not receive any data, then on the first step, gpp_mean = 0 and gpp_variance is just the \"covariance\"\n  of a single point. Then we iterate through the remaining points in points_sampled, generating gpp_mean, gpp_variance,\n  and a sample function value.\n\\endrst*/\nvoid GaussianProcess::SamplePointFromGP(double const * restrict point_to_sample,\n//                                      double noise_variance_this_point,\n                                        double * results) noexcept {\n  double * gpp_variance = new double[Square(1+num_derivatives_)]();\n  double * gpp_mean = new double[1+num_derivatives_]();\n  const int num_to_sample = 1;  // we will only draw 1 point at a time from the GP\n  double * random_sample = new double[1+num_derivatives_]();\n  for (int i = 0; i < 1+num_derivatives_; ++i){\n      random_sample[i] = normal_rng_();\n      results[i] = 0;\n  }\n\n  if (unlikely(num_sampled_ == 0)) {\n    BuildCovarianceMatrix(*covariance_ptr_, point_to_sample, dim_, num_to_sample,\n                          derivatives_.data(), num_derivatives_, gpp_variance);\n    ComputeCholeskyFactorL(1+num_derivatives_, gpp_variance);\n    TriangularMatrixVectorMultiply(gpp_variance, 'N', num_derivatives_+1, random_sample);\n    for (int i = 0; i < 1+num_derivatives_; ++i){\n        results[i] += random_sample[i];\n    }\n    //return std::sqrt(gpp_variance) * normal_rng_() + std::sqrt(noise_variance_this_point)*normal_rng_();  // first draw has mean 0\n  } else {\n    int num_derivatives = 0;\n    StateType points_to_sample_state(*this, point_to_sample, num_to_sample, derivatives_.data(), num_derivatives_, num_derivatives);\n\n    ComputeMeanOfPoints(points_to_sample_state, gpp_mean);\n    ComputeVarianceOfPoints(&points_to_sample_state, derivatives_.data(), num_derivatives_, gpp_variance);\n    ComputeCholeskyFactorL(1+num_derivatives_, gpp_variance);\n    TriangularMatrixVectorMultiply(gpp_variance, 'N', 1+num_derivatives_, random_sample);\n    for (int i = 0; i < 1+num_derivatives_; ++i){\n        results[i] += gpp_mean[i] + random_sample[i];\n    }\n    //return gpp_mean + std::sqrt(gpp_variance) * normal_rng_() + std::sqrt(noise_variance_this_point)*normal_rng_();\n  }\n  delete [] random_sample;\n  delete [] gpp_mean;\n  delete [] gpp_variance;\n}\n\n/*!\\rst\n  Sample only function values for a list of points\n\\endrst*/\nint GaussianProcess::SamplePointsFromGP(double const * restrict points_to_sample,\n                                        int const num_sample,\n                                        double * results) noexcept {\n  double * gpp_variance = new double[Square(num_sample)]();\n  double * gpp_mean = new double[num_sample]();\n\n  double * random_sample = new double[num_sample]();\n  for (int i = 0; i < num_sample; ++i){\n      random_sample[i] = normal_rng_();\n      results[i] = 0;\n  }\n\n  if (unlikely(num_sampled_ == 0)) {\n    BuildCovarianceMatrix(*covariance_ptr_, points_to_sample, dim_, num_sample,\n                          nullptr, 0, gpp_variance);\n    ComputeCholeskyFactorL(num_sample, gpp_variance);\n    TriangularMatrixVectorMultiply(gpp_variance, 'N', num_sample, random_sample);\n    for (int i = 0; i < num_sample; ++i){\n        results[i] += random_sample[i];\n    }\n  } else {\n    int num_derivatives = 0;\n    StateType points_to_sample_state(*this, points_to_sample, num_sample, nullptr, 0, num_derivatives);\n\n    ComputeMeanOfPoints(points_to_sample_state, gpp_mean);\n    ComputeVarianceOfPoints(&points_to_sample_state, nullptr, 0, gpp_variance);\n    ComputeCholeskyFactorL(num_sample, gpp_variance);\n    TriangularMatrixVectorMultiply(gpp_variance, 'N', num_sample, random_sample);\n    for (int i = 0; i < num_sample; ++i){\n        results[i] += gpp_mean[i] + random_sample[i];\n    }\n  }\n  delete [] random_sample;\n  delete [] gpp_mean;\n  delete [] gpp_variance;\n\n  int best_point = -1;\n  double best = results[0];\n  for (int i = 0; i < num_sample; ++i){\n      if (results[i] < best){\n          best_point = i;\n          best = results[i];\n      }\n  }\n  return best_point;\n}\n\n\n/*!\\rst\n  Approximate the global optima of the GP.\n\\endrst*/\nvoid GaussianProcess::SampleGlobalOptimaFromGP(int const num_optima,\n                              int const inner_number,\n                              const TensorProductDomain& domain,\n                              double * points_optima) noexcept {\n  UniformRandomGenerator uniform_generator(rand()%10000);\n  std::vector<double> inner_points(inner_number*dim_, 0.0);\n  std::vector<double> inner_value(inner_number, 0.0);\n  int index = -1;\n\n  for (int i = 0; i < num_optima; ++i){\n    domain.GenerateUniformPointsInDomain(inner_number, &uniform_generator, inner_points.data());\n    index = SamplePointsFromGP(inner_points.data(), inner_number, inner_value.data());\n    for (int j = 0; j < dim_; ++j){\n        points_optima[i * dim_ + j] = inner_points[index * dim_ + j];\n    }\n  }\n}\n\nvoid GaussianProcess::SetExplicitSeed(EngineType::result_type seed) noexcept {\n  normal_rng_.SetExplicitSeed(seed);\n}\n\nvoid GaussianProcess::SetRandomizedSeed(EngineType::result_type seed) noexcept {\n  normal_rng_.SetRandomizedSeed(seed, 0);  // this is intended for single-threaded use only, so thread_id = 0\n}\n\nvoid GaussianProcess::ResetToMostRecentSeed() noexcept {\n  normal_rng_.ResetToMostRecentSeed();\n}\n\nGaussianProcess * GaussianProcess::Clone() const {\n  return new GaussianProcess(*this);\n}\n\nvoid PointsToSampleState::SetupState(const GaussianProcess& gaussian_process, double const * restrict points_to_sample_in,\n                                     int num_to_sample_in, int num_gradients_to_sample_in, int num_derivatives_in,\n                                     bool precomputed_in /*=true*/, bool precomputed_grad_K_inv_times_K_star_in /*= false*/) {\n  if (precomputed != precomputed_in){\n    precomputed = precomputed_in;\n  }\n  if (precomputed_grad_K_inv_times_K_star != precomputed_grad_K_inv_times_K_star_in){\n    precomputed_grad_K_inv_times_K_star = precomputed_grad_K_inv_times_K_star_in;\n  }\n  // resize data depending on to sample points\n  if (unlikely(num_to_sample != num_to_sample_in || num_derivatives != num_derivatives_in || num_gradients_to_sample != num_gradients_to_sample_in)) {\n    // update sizes\n    num_to_sample = num_to_sample_in;\n    num_derivatives = num_derivatives_in;\n    num_gradients_to_sample = num_gradients_to_sample_in;\n    // resize vectors\n    points_to_sample.resize(dim*num_to_sample);\n    K_star.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n    grad_K_star.resize(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim);\n    grad_K_inv_times_K_star.resize(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim);\n    V.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n    K_inv_times_K_star.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n  }\n\n  // resize data depending on sampled points\n  if (unlikely(num_sampled != gaussian_process.num_sampled())) {\n    num_sampled = gaussian_process.num_sampled();\n    K_star.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n    grad_K_star.resize(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim);\n    grad_K_inv_times_K_star.resize(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim);\n    V.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n    K_inv_times_K_star.resize((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1)));\n  }\n\n  // set new points to sample\n  std::copy(points_to_sample_in, points_to_sample_in + dim*num_to_sample, points_to_sample.begin());\n\n  gaussian_process.FillPointsToSampleState(this);\n}\n\nPointsToSampleState::PointsToSampleState(const GaussianProcess& gaussian_process,\n                                         double const * restrict points_to_sample_in,\n                                         int num_to_sample_in, int const * restrict gradients_in,\n                                         int num_gradients_to_sample_in, int num_derivatives_in,\n                                         bool precomputed_in /*=true*/, bool precomputed_grad_K_inv_times_K_star_in /*= false*/)\n    : dim(gaussian_process.dim()),\n      num_sampled(gaussian_process.num_sampled()),\n      num_to_sample(num_to_sample_in),\n      num_derivatives(num_derivatives_in),\n      precomputed(precomputed_in),\n      precomputed_grad_K_inv_times_K_star(precomputed_grad_K_inv_times_K_star_in),\n      gradients(gradients_in, gradients_in+num_gradients_to_sample_in),\n      num_gradients_to_sample(num_gradients_to_sample_in),\n      num_gradients_sampled(gaussian_process.num_derivatives()),\n      points_to_sample(dim*num_to_sample),\n      K_star((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1))),\n      grad_K_star(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim),\n      grad_K_inv_times_K_star(num_derivatives*(num_sampled*(num_gradients_sampled+1)*(num_gradients_to_sample+1))*dim),\n      V((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1))),\n      K_inv_times_K_star((num_to_sample*(num_gradients_to_sample+1))*(num_sampled*(num_gradients_sampled+1))) {\n  SetupState(gaussian_process, points_to_sample_in, num_to_sample_in, num_gradients_to_sample_in, num_derivatives_in);\n}\n\nPointsToSampleState::PointsToSampleState(PointsToSampleState&& OL_UNUSED(other)) = default;\n\nExpectedImprovementEvaluator::ExpectedImprovementEvaluator(const GaussianProcess& gaussian_process_in,\n                                                           int num_mc_iterations, double best_so_far)\n    : dim_(gaussian_process_in.dim()),\n      num_mc_iterations_(num_mc_iterations),\n      best_so_far_(best_so_far),\n      gaussian_process_(&gaussian_process_in) {\n}\n\nExpectedImprovementEvaluator::ExpectedImprovementEvaluator(ExpectedImprovementEvaluator&& other)\n    : dim_(other.dim()),\n      num_mc_iterations_(other.num_mc_iterations()),\n      best_so_far_(other.best_so_far()),\n      gaussian_process_(other.gaussian_process()){\n}\n\n/*!\\rst\n  Let ``Ls * Ls^T = Vars`` and ``w`` = vector of IID normal(0,1) variables\n  Then:\n\n  ``y = mus + Ls * w``  (Equation 4, from file docs)\n\n  simulates drawing from our GP with mean mus and variance Vars.\n\n  Then as given in the file docs, we compute the improvement:\n  Then the improvement for this single sample is::\n\n    I = { best_known - min(y)   if (best_known - min(y) > 0)      (Equation 5 from file docs)\n        {          0               else\n\n  This is implemented as ``max_{y} (best_known - y)``.  Notice that improvement takes the value 0 if it would be negative.\n\n  Since we cannot compute ``min(y)`` directly, we do so via monte-carlo (MC) integration.  That is, we draw from the GP\n  repeatedly, computing improvement during each iteration, and averaging the result.\n\n  See Scott's PhD thesis, sec 6.2.\n\n  .. Note:: comments here are copied to _compute_expected_improvement_monte_carlo() in python_version/expected_improvement.py\n\\endrst*/\ndouble ExpectedImprovementEvaluator::ComputeExpectedImprovement(StateType * ei_state) const {\n  int num_union = ei_state->num_union;\n  gaussian_process_->ComputeMeanOfPoints(ei_state->points_to_sample_state, ei_state->to_sample_mean.data());\n  gaussian_process_->ComputeVarianceOfPoints(&(ei_state->points_to_sample_state),\n                                             ei_state->points_to_sample_state.gradients.data(),\n                                             ei_state->points_to_sample_state.num_gradients_to_sample,\n                                             ei_state->cholesky_to_sample_var.data());\n\n  //Adding the variance of measurement noise to the covariance matrix\n  for (int i = 0;i < num_union; i++){\n       ei_state->cholesky_to_sample_var[i + i*num_union] += 1.0e-6;\n  }\n\n  int leading_minor_index = ComputeCholeskyFactorL(num_union, ei_state->cholesky_to_sample_var.data());\n\n  if (unlikely(leading_minor_index != 0)) {\n    OL_THROW_EXCEPTION(SingularMatrixException, \"GP-Variance matrix singular. Check for duplicate points_to_sample/being_sampled or points_to_sample/being_sampled duplicating points_sampled with 0 noise.\", ei_state->cholesky_to_sample_var.data(), num_union, leading_minor_index);\n  }\n\n  double aggregate = 0.0;\n  ei_state->normal_rng->ResetToMostRecentSeed();\n  for (int i = 0; i < num_mc_iterations_; ++i) {\n    double improvement_this_step = 0.0;\n    for (int j = 0; j < num_union; ++j) {\n      ei_state->EI_this_step_from_var[j] = (*(ei_state->normal_rng))();  // EI_this_step now holds \"normals\"\n    }\n\n    TriangularMatrixVectorMultiply(ei_state->cholesky_to_sample_var.data(), 'N', num_union,\n                                   ei_state->EI_this_step_from_var.data());\n    for (int j = 0; j < num_union; ++j) {\n      double EI_total = best_so_far_ - (ei_state->to_sample_mean[j] + ei_state->EI_this_step_from_var[j]);\n      if (EI_total > improvement_this_step) {\n        improvement_this_step = EI_total;\n      }\n    }\n\n    if (improvement_this_step > 0.0) {\n      aggregate += improvement_this_step;\n    }\n  }\n\n  return aggregate/static_cast<double>(num_mc_iterations_);\n}\n\n/*!\\rst\n  Computes gradient of EI (see ExpectedImprovementEvaluator::ComputeGradExpectedImprovement) wrt points_to_sample (stored in\n  ``union_of_points[0:num_to_sample]``).\n\n  Mechanism is similar to the computation of EI, where points' contributions to the gradient are thrown out of their\n  corresponding ``improvement <= 0.0``.\n\n  Thus ``\\nabla(\\mu)`` only contributes when the ``winner`` (point w/best improvement this iteration) is the current point.\n  That is, the gradient of ``\\mu`` at ``x_i`` wrt ``x_j`` is 0 unless ``i == j`` (and only this result is stored in\n  ``ei_state->grad_mu``).  The interaction with ``ei_state->grad_chol_decomp`` is harder to know a priori (like with\n  ``grad_mu``) and has a more complex structure (rank 3 tensor), so the derivative wrt ``x_j`` is computed fully, and\n  the relevant submatrix (indexed by the current ``winner``) is accessed each iteration.\n\n  .. Note:: comments here are copied to _compute_grad_expected_improvement_monte_carlo() in python_version/expected_improvement.py\n\\endrst*/\nvoid ExpectedImprovementEvaluator::ComputeGradExpectedImprovement(StateType * ei_state, double * restrict grad_EI) const {\n  const int num_union = ei_state->num_union;\n  gaussian_process_->ComputeMeanOfPoints(ei_state->points_to_sample_state, ei_state->to_sample_mean.data());\n  gaussian_process_->ComputeGradMeanOfPoints(ei_state->points_to_sample_state, ei_state->grad_mu.data());\n  gaussian_process_->ComputeVarianceOfPoints(&(ei_state->points_to_sample_state),\n                                               ei_state->points_to_sample_state.gradients.data(),\n                                               ei_state->points_to_sample_state.num_gradients_to_sample,\n                                               ei_state->cholesky_to_sample_var.data());\n\n  //Adding the variance of measurement noise to the covariance matrix\n  for (int i = 0;i < num_union; i++){\n       ei_state->cholesky_to_sample_var[i + i*num_union] += 1.0e-6;\n  }\n\n  int leading_minor_index = ComputeCholeskyFactorL(num_union, ei_state->cholesky_to_sample_var.data());\n  if (unlikely(leading_minor_index != 0)) {\n    OL_THROW_EXCEPTION(SingularMatrixException, \"GP-Variance matrix singular. Check for duplicate points_to_sample/being_sampled or points_to_sample/being_sampled duplicating points_sampled with 0 noise.\", ei_state->cholesky_to_sample_var.data(), num_union, leading_minor_index);\n  }\n\n  gaussian_process_->ComputeGradCholeskyVarianceOfPoints(&(ei_state->points_to_sample_state),\n                                                         ei_state->cholesky_to_sample_var.data(),\n                                                         ei_state->grad_chol_decomp.data());\n\n\n  std::fill(ei_state->aggregate.begin(), ei_state->aggregate.end(), 0.0);\n  double aggregate_EI = 0.0;\n  ei_state->normal_rng->ResetToMostRecentSeed();\n  for (int i = 0; i < num_mc_iterations_; ++i) {\n    for (int j = 0; j < num_union; ++j) {\n      ei_state->EI_this_step_from_var[j] = (*(ei_state->normal_rng))();  // EI_this_step now holds \"normals\"\n      ei_state->normals[j] = ei_state->EI_this_step_from_var[j];  // orig value of normals needed if improvement_this_step > 0.0\n    }\n\n    // compute EI_this_step_from_far = cholesky * normals   as  EI = cholesky * EI\n    // b/c normals currently held in EI_this_step_from_var\n    TriangularMatrixVectorMultiply(ei_state->cholesky_to_sample_var.data(), 'N', num_union,\n                                   ei_state->EI_this_step_from_var.data());\n\n    double improvement_this_step = 0.0;\n    int winner = num_union + 1;  // an out of-bounds initial value\n    for (int j = 0; j < num_union; ++j) {\n      double EI_total = best_so_far_ - (ei_state->to_sample_mean[j] + ei_state->EI_this_step_from_var[j]);\n      if (EI_total > improvement_this_step) {\n        improvement_this_step = EI_total;\n        winner = j;\n      }\n    }\n\n    if (improvement_this_step > 0.0) {\n      // improvement > 0.0 implies winner will be valid; i.e., in 0:ei_state->num_to_sample\n      aggregate_EI += improvement_this_step;\n\n      // recall that grad_mu only stores \\frac{d mu_i}{d Xs_i}, since \\frac{d mu_j}{d Xs_i} = 0 for i != j.\n      // hence the only relevant term from grad_mu is the one describing the gradient wrt winner-th point,\n      // and this term only arises if the winner (for most improvement) index is less than num_to_sample\n      if (winner < ei_state->num_to_sample) {\n        for (int k = 0; k < dim_; ++k) {\n          ei_state->aggregate[winner*dim_ + k] -= ei_state->grad_mu[winner*dim_ + k];\n        }\n      }\n\n      // let L_{d,i,j,k} = grad_chol_decomp, d over dim_, i, j over num_union, k over num_to_sample\n      // we want to compute: agg_dx_{d,k} = L_{d,i,j=winner,k} * normals_i\n      // TODO(GH-92): Form this as one GeneralMatrixVectorMultiply() call by storing data as L_{d,i,k,j} if it's faster.\n      double const * restrict grad_chol_decomp_winner_block = ei_state->grad_chol_decomp.data() + winner*dim_*(num_union);\n      for (int k = 0; k < ei_state->num_to_sample; ++k) {\n        GeneralMatrixVectorMultiply(grad_chol_decomp_winner_block, 'N', ei_state->normals.data(), -1.0, 1.0,\n                                    dim_, num_union, dim_, ei_state->aggregate.data() + k*dim_);\n        grad_chol_decomp_winner_block += dim_*Square(num_union);\n      }\n    }  // end if: improvement_this_step > 0.0\n  }  // end for i: num_mc_iterations_\n\n  for (int k = 0; k < ei_state->num_to_sample*dim_; ++k) {\n    grad_EI[k] = ei_state->aggregate[k]/static_cast<double>(num_mc_iterations_);\n  }\n}\n\nvoid ExpectedImprovementState::SetCurrentPoint(const EvaluatorType& ei_evaluator,\n                                               double const * restrict points_to_sample) {\n  // update points_to_sample in union_of_points\n  std::copy(points_to_sample, points_to_sample + num_to_sample*dim, union_of_points.data());\n\n  // evaluate derived quantities for the GP\n  points_to_sample_state.SetupState(*ei_evaluator.gaussian_process(), union_of_points.data(),\n                                    num_union, 0, num_derivatives, (num_derivatives>0));\n}\n\nExpectedImprovementState::ExpectedImprovementState(const EvaluatorType& ei_evaluator,\n                                                   double const * restrict points_to_sample,\n                                                   double const * restrict points_being_sampled,\n                                                   int num_to_sample_in, int num_being_sampled_in,\n                                                   bool configure_for_gradients, NormalRNGInterface * normal_rng_in)\n    : dim(ei_evaluator.dim()),\n      num_to_sample(num_to_sample_in),\n      num_being_sampled(num_being_sampled_in),\n      num_derivatives(configure_for_gradients ? num_to_sample : 0),\n      num_union(num_to_sample + num_being_sampled),\n      union_of_points(BuildUnionOfPoints(points_to_sample, points_being_sampled, num_to_sample, num_being_sampled, dim)),\n      points_to_sample_state(*ei_evaluator.gaussian_process(), union_of_points.data(), num_union,\n                             nullptr, 0, num_derivatives, configure_for_gradients),\n      normal_rng(normal_rng_in),\n      to_sample_mean(num_union),\n      grad_mu(dim*num_derivatives),\n      cholesky_to_sample_var(Square(num_union)),\n      grad_chol_decomp(dim*Square(num_union)*num_derivatives),\n      EI_this_step_from_var(num_union),\n      aggregate(dim*num_derivatives),\n      normals(num_union) {\n}\n\nExpectedImprovementState::ExpectedImprovementState(ExpectedImprovementState&& OL_UNUSED(other)) = default;\n\nvoid ExpectedImprovementState::SetupState(const EvaluatorType& ei_evaluator,\n                                          double const * restrict points_to_sample) {\n  if (unlikely(dim != ei_evaluator.dim())) {\n    OL_THROW_EXCEPTION(InvalidValueException<int>, \"Evaluator's and State's dim do not match!\", dim, ei_evaluator.dim());\n  }\n\n  // update quantities derived from points_to_sample\n  SetCurrentPoint(ei_evaluator, points_to_sample);\n}\n\nOnePotentialSampleExpectedImprovementEvaluator::OnePotentialSampleExpectedImprovementEvaluator(\n    const GaussianProcess& gaussian_process_in,\n    double best_so_far)\n    : dim_(gaussian_process_in.dim()),\n      best_so_far_(best_so_far),\n      normal_(0.0, 1.0),\n      gaussian_process_(&gaussian_process_in) {\n}\n\nOnePotentialSampleExpectedImprovementEvaluator::OnePotentialSampleExpectedImprovementEvaluator(OnePotentialSampleExpectedImprovementEvaluator&& other)\n    : dim_(other.dim()),\n      best_so_far_(other.best_so_far()),\n      normal_(0.0, 1.0),\n      gaussian_process_(other.gaussian_process()){\n}\n\n///*!\\rst\n//  Uses analytic formulas to compute EI when ``num_to_sample = 1`` and ``num_being_sampled = 0`` (occurs only in 1,0-EI).\n//  In this case, the single-parameter (posterior) GP is just a Gaussian.  So the integral in EI (previously eval'd with MC)\n//  can be computed 'exactly' using high-accuracy routines for the pdf & cdf of a Gaussian random variable.\n//\n//  See Ginsbourger, Le Riche, and Carraro.\n//\\endrst*/\ndouble OnePotentialSampleExpectedImprovementEvaluator::ComputeExpectedImprovement(StateType * ei_state) const {\n  double to_sample_mean;\n  double to_sample_var;\n\n  gaussian_process_->ComputeMeanOfPoints(ei_state->points_to_sample_state, &to_sample_mean);\n  gaussian_process_->ComputeVarianceOfPoints(&(ei_state->points_to_sample_state),\n                                             ei_state->points_to_sample_state.gradients.data(),\n                                             ei_state->points_to_sample_state.num_gradients_to_sample,\n                                             &to_sample_var);\n  to_sample_var = std::sqrt(std::fmax(kMinimumVarianceEI, to_sample_var));\n\n  double temp = best_so_far_ - to_sample_mean;\n  double EI = temp*boost::math::cdf(normal_, temp/to_sample_var) + to_sample_var*boost::math::pdf(normal_, temp/to_sample_var);\n\n  return std::fmax(0.0, EI);\n}\n\n///*!\\rst\n//  Differentiates OnePotentialSampleExpectedImprovementEvaluator::ComputeExpectedImprovement wrt\n//  ``points_to_sample`` (which is just ONE point; i.e., 1,0-EI).\n//  Again, this uses analytic formulas in terms of the pdf & cdf of a Gaussian since the integral in EI (and grad EI)\n//  can be evaluated exactly for this low dimensional case.\n//\n//  See Ginsbourger, Le Riche, and Carraro.\n//\\endrst*/\nvoid OnePotentialSampleExpectedImprovementEvaluator::ComputeGradExpectedImprovement(\n    StateType * ei_state,\n    double * restrict exp_grad_EI) const {\n  double to_sample_mean;\n  double to_sample_var;\n\n  double * restrict grad_mu = ei_state->grad_mu.data();\n  gaussian_process_->ComputeMeanOfPoints(ei_state->points_to_sample_state, &to_sample_mean);\n  gaussian_process_->ComputeGradMeanOfPoints(ei_state->points_to_sample_state, grad_mu);\n  gaussian_process_->ComputeVarianceOfPoints(&(ei_state->points_to_sample_state),\n                                             ei_state->points_to_sample_state.gradients.data(),\n                                             ei_state->points_to_sample_state.num_gradients_to_sample,\n                                             &to_sample_var);\n  to_sample_var = std::fmax(kMinimumVarianceGradEI, to_sample_var);\n  double sigma = std::sqrt(to_sample_var);\n\n  double * restrict grad_chol_decomp = ei_state->grad_chol_decomp.data();\n  // there is only 1 point, so gradient wrt 0-th point\n  gaussian_process_->ComputeGradCholeskyVarianceOfPoints(&(ei_state->points_to_sample_state), &sigma, grad_chol_decomp);\n\n  double mu_diff = best_so_far_ - to_sample_mean;\n  double C = mu_diff/sigma;\n  double pdf_C = boost::math::pdf(normal_, C);\n  double cdf_C = boost::math::cdf(normal_, C);\n\n  for (int i = 0; i < dim_; ++i) {\n    double d_C = (-sigma*grad_mu[i] - grad_chol_decomp[i]*mu_diff)/to_sample_var;\n    double d_A = -grad_mu[i]*cdf_C + mu_diff*pdf_C*d_C;\n    double d_B = grad_chol_decomp[i]*pdf_C + sigma*(-C)*pdf_C*d_C;\n\n    exp_grad_EI[i] = d_A + d_B;\n  }\n}\n\nvoid OnePotentialSampleExpectedImprovementState::SetCurrentPoint(const EvaluatorType& ei_evaluator,\n                                                                 double const * restrict point_to_sample_in) {\n  // update current point in union_of_points\n  std::copy(point_to_sample_in, point_to_sample_in + dim, point_to_sample.data());\n\n  // evaluate derived quantities\n  points_to_sample_state.SetupState(*ei_evaluator.gaussian_process(), point_to_sample.data(),\n                                    num_to_sample, 0, num_derivatives, (num_derivatives>0));\n}\n\nOnePotentialSampleExpectedImprovementState::OnePotentialSampleExpectedImprovementState(\n    const EvaluatorType& ei_evaluator,\n    double const * restrict point_to_sample_in,\n    bool configure_for_gradients)\n    : dim(ei_evaluator.dim()),\n      num_derivatives(configure_for_gradients ? num_to_sample : 0),\n      point_to_sample(point_to_sample_in, point_to_sample_in + dim),\n      points_to_sample_state(*ei_evaluator.gaussian_process(), point_to_sample.data(), num_to_sample,\n                             nullptr, 0, num_derivatives, configure_for_gradients),\n      grad_mu(dim*num_derivatives),\n      grad_chol_decomp(dim*num_derivatives) {\n}\n\nOnePotentialSampleExpectedImprovementState::OnePotentialSampleExpectedImprovementState(\n    const EvaluatorType& ei_evaluator,\n    double const * restrict points_to_sample,\n    double const * restrict OL_UNUSED(points_being_sampled),\n    int OL_UNUSED(num_to_sample_in),\n    int OL_UNUSED(num_being_sampled_in),\n    bool configure_for_gradients,\n    NormalRNGInterface * OL_UNUSED(normal_rng_in))\n    : OnePotentialSampleExpectedImprovementState(ei_evaluator, points_to_sample, configure_for_gradients) {\n}\n\nOnePotentialSampleExpectedImprovementState::OnePotentialSampleExpectedImprovementState(\n    OnePotentialSampleExpectedImprovementState&& OL_UNUSED(other)) = default;\n\nvoid OnePotentialSampleExpectedImprovementState::SetupState(const EvaluatorType& ei_evaluator,\n                                                            double const * restrict point_to_sample_in) {\n  if (unlikely(dim != ei_evaluator.dim())) {\n    OL_THROW_EXCEPTION(InvalidValueException<int>, \"Evaluator's and State's dim do not match!\", dim, ei_evaluator.dim());\n  }\n\n  SetCurrentPoint(ei_evaluator, point_to_sample_in);\n}\n\n/*!\\rst\n  Routes the EI computation through MultistartOptimizer + NullOptimizer to perform EI function evaluations at the list of input\n  points, using the appropriate EI evaluator (e.g., monte carlo vs analytic) depending on inputs.\n\\endrst*/\nvoid EvaluateEIAtPointList(const GaussianProcess& gaussian_process, const ThreadSchedule& thread_schedule,\n                           double const * restrict initial_guesses, double const * restrict points_being_sampled,\n                           int num_multistarts, int num_to_sample, int num_being_sampled, double best_so_far,\n                           int max_int_steps, bool * restrict found_flag, NormalRNG * normal_rng,\n                           double * restrict function_values, double * restrict best_next_point) {\n  if (unlikely(num_multistarts <= 0)) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"num_multistarts must be > 1\", num_multistarts, 1);\n  }\n\n  using DomainType = DummyDomain;\n  DomainType dummy_domain;\n  bool configure_for_gradients = false;\n  if (num_to_sample == 1 && num_being_sampled == 0) {\n    // special analytic case when we are not using (or not accounting for) multiple, simultaneous experiments\n    OnePotentialSampleExpectedImprovementEvaluator ei_evaluator(gaussian_process, best_so_far);\n\n    std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> ei_state_vector;\n    SetupExpectedImprovementState(ei_evaluator, initial_guesses, thread_schedule.max_num_threads,\n                                  configure_for_gradients, &ei_state_vector);\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(ei_state_vector[0].GetProblemSize(), -1.0, initial_guesses);\n\n    NullOptimizer<OnePotentialSampleExpectedImprovementEvaluator, DomainType> null_opt;\n    typename NullOptimizer<OnePotentialSampleExpectedImprovementEvaluator, DomainType>::ParameterStruct null_parameters;\n    MultistartOptimizer<NullOptimizer<OnePotentialSampleExpectedImprovementEvaluator, DomainType> > multistart_optimizer;\n    multistart_optimizer.MultistartOptimize(null_opt, ei_evaluator, null_parameters, dummy_domain,\n                                            thread_schedule, initial_guesses, num_multistarts,\n                                            ei_state_vector.data(), function_values, &io_container);\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  } else {\n    ExpectedImprovementEvaluator ei_evaluator(gaussian_process, max_int_steps, best_so_far);\n\n    std::vector<typename ExpectedImprovementEvaluator::StateType> ei_state_vector;\n    SetupExpectedImprovementState(ei_evaluator, initial_guesses, points_being_sampled, num_to_sample,\n                                  num_being_sampled, thread_schedule.max_num_threads,\n                                  configure_for_gradients, normal_rng, &ei_state_vector);\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(ei_state_vector[0].GetProblemSize(), -1.0, initial_guesses);\n\n    NullOptimizer<ExpectedImprovementEvaluator, DomainType> null_opt;\n    typename NullOptimizer<ExpectedImprovementEvaluator, DomainType>::ParameterStruct null_parameters;\n    MultistartOptimizer<NullOptimizer<ExpectedImprovementEvaluator, DomainType> > multistart_optimizer;\n    multistart_optimizer.MultistartOptimize(null_opt, ei_evaluator, null_parameters, dummy_domain,\n                                            thread_schedule, initial_guesses, num_multistarts,\n                                            ei_state_vector.data(), function_values, &io_container);\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  }\n}\n\n/*!\\rst\n  This is a simple wrapper around ComputeOptimalPointsToSampleWithRandomStarts() and\n  ComputeOptimalPointsToSampleViaLatinHypercubeSearch(). That is, this method attempts multistart gradient descent\n  and falls back to latin hypercube search if gradient descent fails (or is not desired).\n\n  TODO(GH-77): Instead of random search, we may want to fall back on the methods in\n  ``gpp_heuristic_expected_improvement_optimization.hpp`` if gradient descent fails; esp for larger q\n  (even ``q \\approx 4``), latin hypercube search does a pretty terrible job.\n  This is more for general q,p-EI as these two things are equivalent for 1,0-EI.\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalPointsToSample(const GaussianProcess& gaussian_process,\n                                  const GradientDescentParameters& optimizer_parameters,\n                                  const DomainType& domain, const ThreadSchedule& thread_schedule,\n                                  double const * restrict points_being_sampled,\n                                  int num_to_sample, int num_being_sampled, double best_so_far,\n                                  int max_int_steps, bool lhc_search_only,\n                                  int num_lhc_samples, bool * restrict found_flag,\n                                  UniformRandomGenerator * uniform_generator,\n                                  NormalRNG * normal_rng, double * restrict best_points_to_sample) {\n  if (unlikely(num_to_sample <= 0)) {\n    return;\n  }\n\n  std::vector<double> next_points_to_sample(gaussian_process.dim()*num_to_sample);\n\n  bool found_flag_local = false;\n  if (lhc_search_only == false) {\n\n    ComputeOptimalPointsToSampleWithRandomStarts(gaussian_process, optimizer_parameters,\n                                                 domain, thread_schedule, points_being_sampled,\n                                                 num_to_sample, num_being_sampled,\n                                                 best_so_far, max_int_steps,\n                                                 &found_flag_local, uniform_generator, normal_rng,\n                                                 next_points_to_sample.data());\n  }\n\n  // if gradient descent EI optimization failed OR we're only doing latin hypercube searches\n  if (found_flag_local == false || lhc_search_only == true) {\n    if (unlikely(lhc_search_only == false)) {\n      OL_WARNING_PRINTF(\"WARNING: %d,%d-EI opt DID NOT CONVERGE\\n\", num_to_sample, num_being_sampled);\n      OL_WARNING_PRINTF(\"Attempting latin hypercube search\\n\");\n    }\n\n    if (num_lhc_samples > 0) {\n\n      // Note: using a schedule different than \"static\" may lead to flakiness in monte-carlo EI optimization tests.\n      // Besides, this is the fastest setting.\n      ThreadSchedule thread_schedule_naive_search(thread_schedule);\n      thread_schedule_naive_search.schedule = omp_sched_static;\n      ComputeOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process, domain,\n                                                          thread_schedule_naive_search,\n                                                          points_being_sampled,\n                                                          num_lhc_samples, num_to_sample,\n                                                          num_being_sampled, best_so_far,\n                                                          max_int_steps,\n                                                          &found_flag_local, uniform_generator,\n                                                          normal_rng, next_points_to_sample.data());\n\n      // if latin hypercube 'dumb' search failed\n      if (unlikely(found_flag_local == false)) {\n        OL_ERROR_PRINTF(\"ERROR: %d,%d-EI latin hypercube search FAILED on\\n\", num_to_sample, num_being_sampled);\n      }\n    } else {\n      OL_WARNING_PRINTF(\"num_lhc_samples <= 0. Skipping latin hypercube search\\n\");\n    }\n  }\n\n  // set outputs\n  *found_flag = found_flag_local;\n  std::copy(next_points_to_sample.begin(), next_points_to_sample.end(), best_points_to_sample);\n}\n\n// template explicit instantiation definitions, see gpp_common.hpp header comments, item 6\ntemplate void ComputeOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const GradientDescentParameters& optimizer_parameters,\n    const TensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled, int num_to_sample,\n    int num_being_sampled, double best_so_far, int max_int_steps, bool lhc_search_only,\n    int num_lhc_samples, bool * restrict found_flag, UniformRandomGenerator * uniform_generator,\n    NormalRNG * normal_rng, double * restrict best_points_to_sample);\ntemplate void ComputeOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const GradientDescentParameters& optimizer_parameters,\n    const SimplexIntersectTensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled,\n    int num_to_sample, int num_being_sampled, double best_so_far, int max_int_steps,\n    bool lhc_search_only, int num_lhc_samples, bool * restrict found_flag,\n    UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng, double * restrict best_points_to_sample);\n\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "c444db6bedefcf9290d71a586cea654158a44f57", "size": 128428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_math.cpp", "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_math.cpp", "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_math.cpp", "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": 54.6967632027, "max_line_length": 279, "alphanum_fraction": 0.6531519606, "num_tokens": 31868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711718571774, "lm_q2_score": 0.6477982247516797, "lm_q1q2_score": 0.5506098162191844}}
{"text": "/** @file\n *****************************************************************************\n\n Sample parameters for the lattice-based vector encryption scheme for the\n lattice-based R1CS ppSNARG. The LWE parameters are chosen to provide 80-bits\n of security, and correctness error 2^{-40} for verifying QAPs with degree up\n to 10000 (over a finite field of size ~10000). Parameter selection based on\n the security analysis in [LP10].\n\n The plaintext dimension is chosen based on the number of queries needed to\n acheive soundness error 2^{-40} for the QAP-based linear PCP for verifying\n R1CS systems with up to 10000 constraints (and a field of size ~10000).\n\n References:\n\n  [LP10]: Richard Lindner and Chris Peikert. Better Key Sizes (and Attacks) for\n          LWE-Based Encryption. In CT-RSA, 2011.\n\n *****************************************************************************\n * @author     Samir Menon, Brennan Shacklett, and David J. Wu\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n\n#ifndef LWE_PARAM_HPP_\n#define LWE_PARAM_HPP_\n\n#include <math.h>\n#include <stdint.h>\n#include <NTL/ZZ.h>\n\nnamespace LWE {\n\n// Lattice dimension (parameters chosen to ensure 80-bits of security)\nconst uint32_t n = 1455;\n\n// Noise distribution standard deviation\nconst double stddev = 6.0;\n\n// 15 queries (~ 2^-40 soundness error for circuits of size < 10000)\nconst uint32_t l = 15;\nconst uint32_t pt_dim = l*4;\n\n// Plaintext modulus\nconst uint64_t p_int = 65537;\nconst NTL::ZZ p(p_int);\n\n// Ciphertext modulus\nconst NTL::ZZ q(1ul << 58);\n}\n\n#endif // LWE_PARAM_HPP_\n", "meta": {"hexsha": "4319e2a92518f7d60ef74f06d435bacfb2bf1a9b", "size": 1636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lattice_snarg/algebra/lattice/lwe_params.hpp", "max_stars_repo_name": "dwu4/lattice-snarg", "max_stars_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:49:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-02T03:16:15.000Z", "max_issues_repo_path": "lattice_snarg/algebra/lattice/lwe_params.hpp", "max_issues_repo_name": "dwu4/lattice-snarg", "max_issues_repo_head_hexsha": "f5ef3e75d7200ee2b794d04b102fc7502b149628", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lattice_snarg/algebra/lattice/lwe_params.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": 31.4615384615, "max_line_length": 79, "alphanum_fraction": 0.6320293399, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5505676776469173}}
{"text": "#include <learning/independences/discrete/chi_square.hpp>\n#include <factors/discrete/discrete_indices.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n\nnamespace learning::independences::discrete {\n\ndouble ChiSquare::pvalue(const std::string& v1, const std::string& v2) const {\n    std::vector<std::string> dummy_v2{v2};\n    auto [cardinality, strides] = factors::discrete::create_cardinality_strides(m_df, v1, dummy_v2);\n    auto joint_counts = factors::discrete::joint_counts(m_df, v1, dummy_v2, cardinality, strides);\n\n    auto v1_marg = factors::discrete::marginal_counts(joint_counts, 0, cardinality, strides);\n    auto v2_marg = factors::discrete::marginal_counts(joint_counts, 1, cardinality, strides);\n\n    auto inv_obs = 1. / joint_counts.sum();\n\n    double statistic = 0;\n    for (int i = 0; i < cardinality(0); ++i) {\n        for (int j = 0; j < cardinality(1); ++j) {\n            auto expected = static_cast<double>(v1_marg(i) * v2_marg(j)) * inv_obs;\n\n            if (expected != 0) {\n                auto index = i + j * strides(1);\n\n                auto d = joint_counts(index) - expected;\n                statistic += d * d / expected;\n            }\n        }\n    }\n\n    auto df = (cardinality(0) - 1) * (cardinality(1) - 1);\n\n    boost::math::chi_squared_distribution chidist(static_cast<double>(df));\n    return cdf(complement(chidist, statistic));\n}\n\ndouble ChiSquare::pvalue(const std::string& v1, const std::string& v2, const std::string& ev) const {\n    std::vector<std::string> dummy_vars{v2, ev};\n    auto [cardinality, strides] = factors::discrete::create_cardinality_strides(m_df, v1, dummy_vars);\n    auto joint_counts = factors::discrete::joint_counts(m_df, v1, dummy_vars, cardinality, strides);\n\n    auto evidence_marg = factors::discrete::marginal_counts(joint_counts, 2, cardinality, strides);\n\n    auto evidence_configurations = cardinality(2);\n    auto vars_configurations = strides(2);\n\n    double statistic = 0;\n\n    for (auto k = 0; k < evidence_configurations; ++k) {\n        if (evidence_marg(k) == 0) continue;\n\n        auto offset = k * vars_configurations;\n        auto evidence_segment = joint_counts.segment(offset, vars_configurations);\n\n        auto v1_marg = factors::discrete::marginal_counts(evidence_segment, 0, cardinality, strides);\n        auto v2_marg = factors::discrete::marginal_counts(evidence_segment, 1, cardinality, strides);\n\n        auto inv_obs = 1. / evidence_marg(k);\n\n        for (int i = 0; i < cardinality(0); ++i) {\n            for (int j = 0; j < cardinality(1); ++j) {\n                auto expected = static_cast<double>(v1_marg(i) * v2_marg(j)) * inv_obs;\n\n                if (expected != 0) {\n                    auto index = offset + i + j * strides(1);\n\n                    auto d = joint_counts(index) - expected;\n                    statistic += d * d / expected;\n                }\n            }\n        }\n    }\n\n    auto df = (cardinality(0) - 1) * (cardinality(1) - 1) * cardinality(2);\n\n    boost::math::chi_squared_distribution chidist(static_cast<double>(df));\n    return cdf(complement(chidist, statistic));\n}\n\ndouble ChiSquare::pvalue(const std::string& v1, const std::string& v2, const std::vector<std::string>& ev) const {\n    std::vector<std::string> dummy_vars{v2};\n    dummy_vars.reserve(ev.size() + 1);\n    dummy_vars.insert(dummy_vars.end(), ev.begin(), ev.end());\n\n    auto [cardinality, strides] = factors::discrete::create_cardinality_strides(m_df, v1, dummy_vars);\n    auto joint_counts = factors::discrete::joint_counts(m_df, v1, dummy_vars, cardinality, strides);\n\n    auto evidence_configurations = cardinality.tail(ev.size()).prod();\n    auto vars_configurations = cardinality(0) * cardinality(1);\n\n    double statistic = 0;\n\n    for (auto k = 0; k < evidence_configurations; ++k) {\n        auto offset = k * vars_configurations;\n\n        int total_sum = 0;\n        auto marginal_v1 = VectorXi::Zero(cardinality(0)).eval();\n        auto marginal_v2 = VectorXi::Zero(cardinality(1)).eval();\n\n        for (auto i = 0; i < cardinality(0); ++i) {\n            for (auto j = 0; j < cardinality(1); ++j) {\n                auto c = joint_counts(offset + i + j * strides(1));\n                marginal_v1(i) += c;\n                marginal_v2(j) += c;\n                total_sum += c;\n            }\n        }\n\n        if (total_sum == 0) continue;\n\n        auto inv_obs = 1. / static_cast<double>(total_sum);\n\n        for (auto i = 0; i < cardinality(0); ++i) {\n            for (auto j = 0; j < cardinality(1); ++j) {\n                auto expected = static_cast<double>(marginal_v1(i) * marginal_v2(j)) * inv_obs;\n\n                if (expected != 0) {\n                    auto c = joint_counts(offset + i + j * strides(1));\n                    auto d = c - expected;\n\n                    statistic += d * d / expected;\n                }\n            }\n        }\n    }\n\n    auto df = (cardinality(0) - 1) * (cardinality(1) - 1) * evidence_configurations;\n\n    boost::math::chi_squared_distribution chidist(static_cast<double>(df));\n    return cdf(complement(chidist, statistic));\n}\n\n}  // namespace learning::independences::discrete", "meta": {"hexsha": "f85b464607d3f71df597228d99bf6f0fc2b3c452", "size": 5126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/independences/discrete/chi_square.cpp", "max_stars_repo_name": "davenza/PyBNesian", "max_stars_repo_head_hexsha": "3ed65e6a24d8e16ee00bf8c47ab6828692463499", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/independences/discrete/chi_square.cpp", "max_issues_repo_name": "davenza/PyBNesian", "max_issues_repo_head_hexsha": "3ed65e6a24d8e16ee00bf8c47ab6828692463499", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/independences/discrete/chi_square.cpp", "max_forks_repo_name": "davenza/PyBNesian", "max_forks_repo_head_hexsha": "3ed65e6a24d8e16ee00bf8c47ab6828692463499", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 38.5413533835, "max_line_length": 114, "alphanum_fraction": 0.6102223956, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.5505676743826637}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2014 Anton Bikineev\n//  Copyright 2014 Christopher Kormanyos\n//  Copyright 2014 John Maddock\n//  Copyright 2014 Paul Bristow\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_MATH_DETAIL_HYPERGEOMETRIC_SERIES_HPP\n#define BOOST_MATH_DETAIL_HYPERGEOMETRIC_SERIES_HPP\n\n#include <cmath>\n#include <cstdint>\n#include <boost/math/tools/series.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/policies/error_handling.hpp>\n\n  namespace boost { namespace math { namespace detail {\n\n  // primary template for term of Taylor series\n  template <class T, unsigned p, unsigned q>\n  struct hypergeometric_pFq_generic_series_term;\n\n  // partial specialization for 0F1\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 0u, 1u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& b, const T& z)\n       : n(0), term(1), b(b), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= ((1 / ((b + n) * (n + 1))) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T b, z;\n  };\n\n  // partial specialization for 1F0\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 1u, 0u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& a, const T& z)\n       : n(0), term(1), a(a), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= (((a + n) / (n + 1)) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T a, z;\n  };\n\n  // partial specialization for 1F1\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 1u, 1u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& a, const T& b, const T& z)\n       : n(0), term(1), a(a), b(b), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= (((a + n) / ((b + n) * (n + 1))) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T a, b, z;\n  };\n\n  // partial specialization for 1F2\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 1u, 2u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& a, const T& b1, const T& b2, const T& z)\n       : n(0), term(1), a(a), b1(b1), b2(b2), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= (((a + n) / ((b1 + n) * (b2 + n) * (n + 1))) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T a, b1, b2, z;\n  };\n\n  // partial specialization for 2F0\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 2u, 0u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& a1, const T& a2, const T& z)\n       : n(0), term(1), a1(a1), a2(a2), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= (((a1 + n) * (a2 + n) / (n + 1)) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T a1, a2, z;\n  };\n\n  // partial specialization for 2F1\n  template <class T>\n  struct hypergeometric_pFq_generic_series_term<T, 2u, 1u>\n  {\n    typedef T result_type;\n\n    hypergeometric_pFq_generic_series_term(const T& a1, const T& a2, const T& b, const T& z)\n       : n(0), term(1), a1(a1), a2(a2), b(b), z(z)\n    {\n    }\n\n    T operator()()\n    {\n      BOOST_MATH_STD_USING\n      const T r = term;\n      term *= (((a1 + n) * (a2 + n) / ((b + n) * (n + 1))) * z);\n      ++n;\n      return r;\n    }\n\n  private:\n    unsigned n;\n    T term;\n    const T a1, a2, b, z;\n  };\n\n  // we don't need to define extra check and make a polinom from\n  // series, when p(i) and q(i) are negative integers and p(i) >= q(i)\n  // as described in functions.wolfram.alpha, because we always\n  // stop summation when result (in this case numerator) is zero.\n  template <class T, unsigned p, unsigned q, class Policy>\n  inline T sum_pFq_series(detail::hypergeometric_pFq_generic_series_term<T, p, q>& term, const Policy& pol)\n  {\n    BOOST_MATH_STD_USING\n    std::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n\n    const T result = boost::math::tools::sum_series(term, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n\n    policies::check_series_iterations<T>(\"boost::math::hypergeometric_pFq_generic_series<%1%>(%1%,%1%,%1%)\", max_iter, pol);\n    return result;\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_0F1_generic_series(const T& b, const T& z, const Policy& pol)\n  {\n    detail::hypergeometric_pFq_generic_series_term<T, 0u, 1u> s(b, z);\n    return detail::sum_pFq_series(s, pol);\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_1F0_generic_series(const T& a, const T& z, const Policy& pol)\n  {\n    detail::hypergeometric_pFq_generic_series_term<T, 1u, 0u> s(a, z);\n    return detail::sum_pFq_series(s, pol);\n  }\n\n  template <class T, class Policy>\n  inline T log_pochhammer(T z, unsigned n, const Policy pol, int* s = 0)\n  {\n     BOOST_MATH_STD_USING\n#if 0\n     if (z < 0)\n     {\n        if (n < -z)\n        {\n           if(s)\n            *s = (n & 1 ? -1 : 1);\n           return log_pochhammer(T(-z + (1 - (int)n)), n, pol);\n        }\n        else\n        {\n           int cross = itrunc(ceil(-z));\n           return log_pochhammer(T(-z + (1 - cross)), cross, pol, s) + log_pochhammer(T(cross + z), n - cross, pol);\n        }\n     }\n     else\n#endif\n     {\n        if (z + n < 0)\n        {\n           T r = log_pochhammer(T(-z - n + 1), n, pol, s);\n           if (s)\n              *s *= (n & 1 ? -1 : 1);\n           return r;\n        }\n        int s1, s2;\n        T r = boost::math::lgamma(T(z + n), &s1, pol) - boost::math::lgamma(z, &s2, pol);\n        if(s)\n           *s = s1 * s2;\n        return r;\n     }\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_1F1_generic_series(const T& a, const T& b, const T& z, const Policy& pol, long long& log_scaling, const char* function)\n  {\n     BOOST_MATH_STD_USING\n     T sum(0), term(1), upper_limit(sqrt(boost::math::tools::max_value<T>())), diff;\n     T lower_limit(1 / upper_limit);\n     unsigned n = 0;\n     long long log_scaling_factor = lltrunc(boost::math::tools::log_max_value<T>()) - 2;\n     T scaling_factor = exp(T(log_scaling_factor));\n     T term_m1 = 0;\n     long long local_scaling = 0;\n     //\n     // When a is very small, then (a+n)/n => 1 faster than\n     // z / (b+n) => 1, as a result the series starts off\n     // converging, then at some unspecified time very gradually\n     // starts to diverge, potentially resulting in some very large\n     // values being missed.  As a result we need a check for small\n     // a in the convergence criteria.  Note that this issue occurs\n     // even when all the terms are positive.\n     //\n     bool small_a = fabs(a) < 0.25;\n\n     unsigned summit_location = 0;\n     bool have_minima = false;\n     T sq = 4 * a * z + b * b - 2 * b * z + z * z;\n     if (sq >= 0)\n     {\n        T t = (-sqrt(sq) - b + z) / 2;\n        if (t > 1)  // Don't worry about a minima between 0 and 1.\n           have_minima = true;\n        t = (sqrt(sq) - b + z) / 2;\n        if (t > 0)\n           summit_location = itrunc(t);\n     }\n\n     if (summit_location > boost::math::policies::get_max_series_iterations<Policy>() / 4)\n     {\n        //\n        // Skip forward to the location of the largest term in the series and\n        // evaluate outwards from there:\n        //\n        int s1, s2;\n        term = log_pochhammer(a, summit_location, pol, &s1) + summit_location * log(z) - log_pochhammer(b, summit_location, pol, &s2) - lgamma(T(summit_location + 1), pol);\n        //std::cout << term << \" \" << log_pochhammer(boost::multiprecision::mpfr_float(a), summit_location, pol, &s1) + summit_location * log(boost::multiprecision::mpfr_float(z)) - log_pochhammer(boost::multiprecision::mpfr_float(b), summit_location, pol, &s2) - lgamma(boost::multiprecision::mpfr_float(summit_location + 1), pol) << std::endl;\n        local_scaling = lltrunc(term);\n        log_scaling += local_scaling;\n        term = s1 * s2 * exp(term - local_scaling);\n        //std::cout << term << \" \" << exp(log_pochhammer(boost::multiprecision::mpfr_float(a), summit_location, pol, &s1) + summit_location * log(boost::multiprecision::mpfr_float(z)) - log_pochhammer(boost::multiprecision::mpfr_float(b), summit_location, pol, &s2) - lgamma(boost::multiprecision::mpfr_float(summit_location + 1), pol) - local_scaling) << std::endl;\n        n = summit_location;\n     }\n     else\n        summit_location = 0;\n\n     T saved_term = term;\n     long long saved_scale = local_scaling;\n\n     do\n     {\n        sum += term;\n        //std::cout << n << \" \" << term * exp(boost::multiprecision::mpfr_float(local_scaling)) << \" \" << rising_factorial(boost::multiprecision::mpfr_float(a), n) * pow(boost::multiprecision::mpfr_float(z), n) / (rising_factorial(boost::multiprecision::mpfr_float(b), n) * factorial<boost::multiprecision::mpfr_float>(n)) << std::endl;\n        if (fabs(sum) >= upper_limit)\n        {\n           sum /= scaling_factor;\n           term /= scaling_factor;\n           log_scaling += log_scaling_factor;\n           local_scaling += log_scaling_factor;\n        }\n        if (fabs(sum) < lower_limit)\n        {\n           sum *= scaling_factor;\n           term *= scaling_factor;\n           log_scaling -= log_scaling_factor;\n           local_scaling -= log_scaling_factor;\n        }\n        term_m1 = term;\n        term *= (((a + n) / ((b + n) * (n + 1))) * z);\n        if (n - summit_location > boost::math::policies::get_max_series_iterations<Policy>())\n           return boost::math::policies::raise_evaluation_error(function, \"Series did not converge, best value is %1%\", sum, pol);\n        ++n;\n        diff = fabs(term / sum);\n     } while ((diff > boost::math::policies::get_epsilon<T, Policy>()) || (fabs(term_m1) < fabs(term)) || (small_a && n < 10));\n\n     //\n     // See if we need to go backwards as well:\n     //\n     if (summit_location)\n     {\n        //\n        // Backup state:\n        //\n        term = saved_term * exp(T(local_scaling - saved_scale));\n        n = summit_location;\n        term *= (b + (n - 1)) * n / ((a + (n - 1)) * z);\n        --n;\n        \n        do\n        {\n           sum += term;\n           //std::cout << n << \" \" << term * exp(boost::multiprecision::mpfr_float(local_scaling)) << \" \" << rising_factorial(boost::multiprecision::mpfr_float(a), n) * pow(boost::multiprecision::mpfr_float(z), n) / (rising_factorial(boost::multiprecision::mpfr_float(b), n) * factorial<boost::multiprecision::mpfr_float>(n)) << std::endl;\n           if (n == 0)\n              break;\n           if (fabs(sum) >= upper_limit)\n           {\n              sum /= scaling_factor;\n              term /= scaling_factor;\n              log_scaling += log_scaling_factor;\n              local_scaling += log_scaling_factor;\n           }\n           if (fabs(sum) < lower_limit)\n           {\n              sum *= scaling_factor;\n              term *= scaling_factor;\n              log_scaling -= log_scaling_factor;\n              local_scaling -= log_scaling_factor;\n           }\n           term_m1 = term;\n           term *= (b + (n - 1)) * n / ((a + (n - 1)) * z);\n           if (summit_location - n > boost::math::policies::get_max_series_iterations<Policy>())\n              return boost::math::policies::raise_evaluation_error(function, \"Series did not converge, best value is %1%\", sum, pol);\n           --n;\n           diff = fabs(term / sum);\n        } while ((diff > boost::math::policies::get_epsilon<T, Policy>()) || (fabs(term_m1) < fabs(term)));\n     }\n\n     if (have_minima && n && summit_location)\n     {\n        //\n        // There are a few terms starting at n == 0 which\n        // haven't been accounted for yet...\n        //\n        unsigned backstop = n;\n        n = 0;\n        term = exp(T(-local_scaling));\n        do\n        {\n           sum += term;\n           //std::cout << n << \" \" << term << \" \" << sum << std::endl;\n           if (fabs(sum) >= upper_limit)\n           {\n              sum /= scaling_factor;\n              term /= scaling_factor;\n              log_scaling += log_scaling_factor;\n           }\n           if (fabs(sum) < lower_limit)\n           {\n              sum *= scaling_factor;\n              term *= scaling_factor;\n              log_scaling -= log_scaling_factor;\n           }\n           //term_m1 = term;\n           term *= (((a + n) / ((b + n) * (n + 1))) * z);\n           if (n > boost::math::policies::get_max_series_iterations<Policy>())\n              return boost::math::policies::raise_evaluation_error(function, \"Series did not converge, best value is %1%\", sum, pol);\n           if (++n == backstop)\n              break; // we've caught up with ourselves.\n           diff = fabs(term / sum);\n        } while ((diff > boost::math::policies::get_epsilon<T, Policy>())/* || (fabs(term_m1) < fabs(term))*/);\n     }\n     //std::cout << sum << std::endl;\n     return sum;\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_1F2_generic_series(const T& a, const T& b1, const T& b2, const T& z, const Policy& pol)\n  {\n    detail::hypergeometric_pFq_generic_series_term<T, 1u, 2u> s(a, b1, b2, z);\n    return detail::sum_pFq_series(s, pol);\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_2F0_generic_series(const T& a1, const T& a2, const T& z, const Policy& pol)\n  {\n    detail::hypergeometric_pFq_generic_series_term<T, 2u, 0u> s(a1, a2, z);\n    return detail::sum_pFq_series(s, pol);\n  }\n\n  template <class T, class Policy>\n  inline T hypergeometric_2F1_generic_series(const T& a1, const T& a2, const T& b, const T& z, const Policy& pol)\n  {\n    detail::hypergeometric_pFq_generic_series_term<T, 2u, 1u> s(a1, a2, b, z);\n    return detail::sum_pFq_series(s, pol);\n  }\n\n  } } } // namespaces\n\n#endif // BOOST_MATH_DETAIL_HYPERGEOMETRIC_SERIES_HPP\n", "meta": {"hexsha": "82a0a6fbee2982e9bc84f74d2437b03ce5338dfc", "size": 14266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/detail/hypergeometric_series.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/detail/hypergeometric_series.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/detail/hypergeometric_series.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": 32.8709677419, "max_line_length": 366, "alphanum_fraction": 0.5755642787, "num_tokens": 4113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.5505073132105556}}
{"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    long long int n, C; cin >> n >> C;\n    vector<pair<long long int, long long int>> v;\n    for (int i = 0; i < n; i++) {\n        long long int a, b, c; cin >> a >> b >> c;\n        v.emplace_back(a - 1, c), v.emplace_back(b, -c);\n    }\n    sort(v.begin(), v.end());\n    cpp_int ans = 0;\n    long long int p = 0, t = 0;\n    for (auto [x, y] : v) {\n        if (x != t) ans += min(C, p) * (x - t), t = x;\n        p += y;\n    }\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "38286058dbe7ef34af9df614a3c90faf95654bbd", "size": 645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc188/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/abc188/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/abc188/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": 26.875, "max_line_length": 56, "alphanum_fraction": 0.5286821705, "num_tokens": 205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5505073108185159}}
{"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 qle/math/stabilisedglls.hpp\n    \\brief Numerically stabilised general linear least squares\n    \\ingroup math\n*/\n\n#ifndef quantext_stabilised_glls_hpp\n#define quantext_stabilised_glls_hpp\n\n#include <ql/math/array.hpp>\n#include <ql/math/comparison.hpp>\n#include <ql/math/generallinearleastsquares.hpp>\n\n#include <boost/accumulators/accumulators.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/make_shared.hpp>\n#include <boost/type_traits.hpp>\n\n#include <vector>\n\nnamespace QuantExt {\nusing namespace QuantLib;\nusing namespace boost::accumulators;\n\n//! Numerically stabilised general linear least squares\n/*! The input data is lineaerly transformed before performing the linear least squares fit.\n  The linear least squares fit on the transformed data is done using the\n  GeneralLinearLeastSquares class.\n    \\ingroup math\n */\n\nclass StabilisedGLLS {\npublic:\n    enum Method {\n        None,      // No stabilisation\n        MaxAbs,    // Divide x and y values by max of abs of values (per x coordinate, y)\n        MeanStdDev // Subtract mean and divide by std dev (per x coordinate, y)\n    };\n    template <class xContainer, class yContainer, class vContainer>\n    StabilisedGLLS(const xContainer& x, const yContainer& y, const vContainer& v, const Method method = MeanStdDev);\n\n    const Array& transformedCoefficients() const { return glls_->coefficients(); }\n    const Array& transformedResiduals() const { return glls_->residuals(); }\n    const Array& transformedStandardErrors() const { return glls_->standardErrors(); }\n    const Array& transformedError() const { return glls_->error(); }\n\n    //! Transformation parameters (u => (u + shift) * multiplier for u = x, y)\n    const Array& xMultiplier() const { return xMultiplier_; }\n    const Array& xShift() const { return xShift_; }\n    const Real yMultiplier() const { return yMultiplier_; }\n    const Real yShift() const { return yShift_; }\n\n    Size size() const { return glls_->residuals().size(); }\n    Size dim() const { return glls_->coefficients().size(); }\n\n    //! evaluate regression function in terms of original x, y\n    template <class xType, class vContainer>\n    Real eval(xType x, vContainer& v, typename boost::enable_if<typename boost::is_arithmetic<xType>::type>::type* = 0);\n\n    //! evaluate regression function in terms of original x, y\n    template <class xType, class vContainer>\n    Real eval(xType x, vContainer& v,\n              typename boost::disable_if<typename boost::is_arithmetic<xType>::type>::type* = 0);\n\nprotected:\n    Array a_, err_, residuals_, standardErrors_, xMultiplier_, xShift_;\n    Real yMultiplier_, yShift_;\n    Method method_;\n    boost::shared_ptr<GeneralLinearLeastSquares> glls_;\n\n    template <class xContainer, class yContainer, class vContainer>\n    void calculate(\n        xContainer x, yContainer y, vContainer v,\n        typename boost::enable_if<typename boost::is_arithmetic<typename xContainer::value_type>::type>::type* = 0);\n\n    template <class xContainer, class yContainer, class vContainer>\n    void calculate(\n        xContainer x, yContainer y, vContainer v,\n        typename boost::disable_if<typename boost::is_arithmetic<typename xContainer::value_type>::type>::type* = 0);\n};\n\ntemplate <class xContainer, class yContainer, class vContainer>\ninline StabilisedGLLS::StabilisedGLLS(const xContainer& x, const yContainer& y, const vContainer& v,\n                                      const Method method)\n    : a_(v.end() - v.begin(), 0.0), err_(v.end() - v.begin(), 0.0), residuals_(y.end() - y.begin()),\n      standardErrors_(v.end() - v.begin()), method_(method) {\n    calculate(x, y, v);\n}\n\ntemplate <class xContainer, class yContainer, class vContainer>\nvoid StabilisedGLLS::calculate(\n    xContainer x, yContainer y, vContainer v,\n    typename boost::enable_if<typename boost::is_arithmetic<typename xContainer::value_type>::type>::type*) {\n\n    std::vector<Real> xData(x.end() - x.begin(), 0.0), yData(y.end() - y.begin(), 0.0);\n    xMultiplier_ = Array(1, 1.0);\n    xShift_ = Array(1, 0.0);\n    yMultiplier_ = 1.0;\n    yShift_ = 0.0;\n\n    switch (method_) {\n    case None:\n        break;\n    case MaxAbs: {\n        Real mx = 0.0, my = 0.0;\n        for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n            mx = std::max(std::abs(x[i]), mx);\n        }\n        if (!close_enough(mx, 0.0))\n            xMultiplier_[0] = 1.0 / mx;\n        for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n            my = std::max(std::abs(y[i]), my);\n        }\n        if (!close_enough(my, 0.0))\n            yMultiplier_ = 1.0 / my;\n        break;\n    }\n    case MeanStdDev: {\n        accumulator_set<Real, stats<tag::mean, tag::variance> > acc;\n        for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n            acc(x[i]);\n        }\n        xShift_[0] = -mean(acc);\n        Real tmp = variance(acc);\n        if (!close_enough(tmp, 0.0))\n            xMultiplier_[0] = 1.0 / std::sqrt(tmp);\n        accumulator_set<Real, stats<tag::mean, tag::variance> > acc2;\n        for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n            acc2(y[i]);\n        }\n        yShift_ = -mean(acc2);\n        Real tmp2 = variance(acc2);\n        if (!close_enough(tmp2, 0.0))\n            yMultiplier_ = 1.0 / std::sqrt(tmp2);\n        break;\n    }\n    default:\n        QL_FAIL(\"unknown stabilisation method\");\n    }\n\n    for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n        xData[i] = (x[i] + xShift_[0]) * xMultiplier_[0];\n    }\n    for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n        yData[i] = (y[i] + yShift_) * yMultiplier_;\n    }\n\n    glls_ = boost::make_shared<GeneralLinearLeastSquares>(xData, yData, v);\n}\n\ntemplate <class xContainer, class yContainer, class vContainer>\nvoid StabilisedGLLS::calculate(\n    xContainer x, yContainer y, vContainer v,\n    typename boost::disable_if<typename boost::is_arithmetic<typename xContainer::value_type>::type>::type*) {\n\n    QL_REQUIRE(x.end() - x.begin() > 0, \"StabilisedGLLS::calculate(): x container is empty\");\n    QL_REQUIRE(x[0].end() - x[0].begin() > 0, \"StabilisedGLLS:calculate(): x contains empty point(s)\");\n\n    std::vector<Array> xData(x.end() - x.begin(), Array(x[0].end() - x[0].begin(), 0.0));\n    std::vector<Real> yData(y.end() - y.begin(), 0.0);\n    xMultiplier_ = Array(x[0].end() - x[0].begin(), 1.0);\n    xShift_ = Array(x[0].end() - x[0].begin(), 0.0);\n    yMultiplier_ = 1.0;\n    yShift_ = 0.0;\n\n    switch (method_) {\n    case None:\n        break;\n    case MaxAbs: {\n        Array m(x[0].end() - x[0].begin(), 0.0);\n        Real my = 0.0;\n        for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n            for (Size j = 0; j < m.size(); ++j) {\n                m[j] = std::max(std::abs(x[i][j]), m[j]);\n            }\n        }\n        for (Size j = 0; j < m.size(); ++j) {\n            if (!close_enough(m[j], 0.0))\n                xMultiplier_[j] = 1.0 / m[j];\n        }\n        for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n            my = std::max(std::abs(y[i]), my);\n        }\n        if (!close_enough(my, 0.0))\n            yMultiplier_ = 1.0 / my;\n        break;\n    }\n    case MeanStdDev: {\n        std::vector<accumulator_set<Real, stats<tag::mean, tag::variance> > > acc(x[0].end() - x[0].begin());\n        for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n            for (Size j = 0; j < acc.size(); ++j) {\n                acc[j](x[i][j]);\n            }\n        }\n        for (Size j = 0; j < acc.size(); ++j) {\n            xShift_[j] = -mean(acc[j]);\n            Real tmp = variance(acc[j]);\n            if (!close_enough(tmp, 0.0))\n                xMultiplier_[j] = 1.0 / std::sqrt(tmp);\n        }\n        accumulator_set<Real, stats<tag::mean, tag::variance> > acc2;\n        for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n            acc2(y[i]);\n        }\n        yShift_ = -mean(acc2);\n        Real tmp2 = variance(acc2);\n        if (!close_enough(tmp2, 0.0))\n            yMultiplier_ = 1.0 / std::sqrt(tmp2);\n        break;\n    }\n    default:\n        QL_FAIL(\"unknown stabilisation method\");\n        break;\n    }\n\n    for (Size i = 0; i < static_cast<Size>(x.end() - x.begin()); ++i) {\n        for (Size j = 0; j < xMultiplier_.size(); ++j) {\n            xData[i][j] = (x[i][j] + xShift_[j]) * xMultiplier_[j];\n        }\n    }\n    for (Size i = 0; i < static_cast<Size>(y.end() - y.begin()); ++i) {\n        yData[i] = (y[i] + yShift_) * yMultiplier_;\n    }\n\n    glls_ = boost::make_shared<GeneralLinearLeastSquares>(xData, yData, v);\n}\n\ntemplate <class xType, class vContainer>\nReal StabilisedGLLS::eval(xType x, vContainer& v,\n                          typename boost::enable_if<typename boost::is_arithmetic<xType>::type>::type*) {\n    QL_REQUIRE(v.size() == glls_->dim(),\n               \"StabilisedGLLS::eval(): v size (\" << v.size() << \") must be equal to dim (\" << glls_->dim());\n    Real tmp = 0.0;\n    for (Size i = 0; i < v.size(); ++i) {\n        tmp += glls_->coefficients()[i] * v[i]((x + xShift_[0]) * xMultiplier_[0]);\n    }\n    return tmp / yMultiplier_ - yShift_;\n}\n\ntemplate <class xType, class vContainer>\nReal StabilisedGLLS::eval(xType x, vContainer& v,\n                          typename boost::disable_if<typename boost::is_arithmetic<xType>::type>::type*) {\n    QL_REQUIRE(v.size() == glls_->dim(),\n               \"StabilisedGLLS::eval(): v size (\" << v.size() << \") must be equal to dim (\" << glls_->dim());\n    Real tmp = 0.0;\n    for (Size i = 0; i < v.size(); ++i) {\n        xType xNew(x.end() - x.begin());\n        for (Size j = 0; j < static_cast<Size>(x.end() - x.begin()); ++j) {\n            xNew[j] = (x[j] + xShift_[j]) * xMultiplier_[j];\n        }\n        tmp += glls_->coefficients()[i] * v[i](xNew);\n    }\n    return tmp / yMultiplier_ - yShift_;\n}\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "7284400473ee462b9cb4b12bed1a17defe463b11", "size": 10794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/math/stabilisedglls.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/stabilisedglls.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/stabilisedglls.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 38.8273381295, "max_line_length": 120, "alphanum_fraction": 0.6026496202, "num_tokens": 3065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.5505073035994685}}
{"text": "#include \"ECF_base.h\"\r\n#include \"floatingpoint/FloatingPoint.h\"\r\n#include \"AlgCuckooSearch.h\"\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <boost/random.hpp>\r\n#include <ctime>\r\n#include <cstdlib>\r\n#include <vector>\r\n\r\n\r\nCuckooSearch::CuckooSearch()\r\n{\r\n\tname_ = \"CuckooSearch\";\r\n\tselBestOp = static_cast<SelectionOperatorP> (new SelBestOp);\r\n}\r\n\r\n\r\nvoid CuckooSearch::registerParameters(StateP state)\r\n{\r\n\tregisterParameter(state, \"pa\", (voidP) new double(0.75), ECF::DOUBLE);\r\n}\r\n\r\n\r\nbool CuckooSearch::initialize(StateP state)\r\n{\r\n\tselBestOp->initialize(state);\r\n\r\n\tvoidP pDiscovery = getParameterValue(state, \"pa\");\r\n\tpa = *((double*)pDiscovery.get());\r\n\tif (pa < 0 || pa > 1)\r\n\t{\r\n\t\tECF_LOG_ERROR(state, \"Error - pa must be in interval [0,1]\");\r\n\t\tthrow \"\";\r\n\t}\r\n\r\n\t// reading boudaries and problem dimension\r\n\tvoidP lBound = state->getGenotypes()[0]->getParameterValue(state, \"lbound\");\r\n\tlbound = *((double*)lBound.get());\r\n\tvoidP uBound = state->getGenotypes()[0]->getParameterValue(state, \"ubound\");\r\n\tubound = *((double*)uBound.get());\r\n\tvoidP sptr = state->getGenotypes()[0]->getParameterValue(state, \"dimension\");\r\n\tnumDimension = *((uint*)sptr.get());\r\n\r\n\t// algorithm accepts a single FloatingPoint or Binary genotype \r\n\t// or a genotype derived from the abstract RealValueGenotype class\r\n\tGenotypeP activeGenotype = state->getGenotypes()[0];\r\n\tRealValueGenotypeP rv = boost::dynamic_pointer_cast<RealValueGenotype> (activeGenotype);\r\n\tif(!rv) {\r\n\t\tECF_LOG_ERROR(state, \"Error: Cuckoo Search algorithm accepts only a RealValueGenotype derived genotype! (FloatingPoint or Binary)\");\r\n\t\tthrow (\"\");\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nbool CuckooSearch::advanceGeneration(StateP state, DemeP deme)\r\n{\r\n\tdouble sigma = 0.696574502;\r\n\tboost::mt19937 rng;\r\n\tboost::normal_distribution<> nd(0.0, 1.0);\r\n\tboost::variate_generator<boost::mt19937&,\r\n\tboost::normal_distribution<> > var_nor(rng, nd);\r\n\r\n\tIndividualP best = selBestOp->select(*deme);\r\n\tFloatingPointP bestFp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (best->getGenotype(0));\r\n\r\n\t// cuckoos via Levy flights (by Mantegna's algorithm)\r\n\t// new individual is added to population only if it is better than original individual\r\n\tfor (uint i = 0; i < deme->size(); i++) {\r\n\t\tIndividualP trial = (IndividualP)deme->at(i)->copy();\r\n\t\tFloatingPointP trialFp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (trial->getGenotype(0));\r\n\t\tfor (uint j = 0; j < numDimension; j++)\t{\r\n\t\t\tdouble u = var_nor() * sigma;\r\n\t\t\tdouble v = var_nor();\r\n\t\t\tdouble step = u / pow(fabs(v), 2 / (double)3);\r\n\t\t\tdouble randn = var_nor();\r\n\t\t\tdouble diff = trialFp->realValue[j] - bestFp->realValue[j];\r\n\t\t\tdouble stepsize = 0.01 * step * diff;\r\n\t\t\ttrialFp->realValue[j] = trialFp->realValue[j] + stepsize*randn;\r\n\t\t\tif (trialFp->realValue[j] > ubound)\r\n\t\t\t\ttrialFp->realValue[j] = ubound;\r\n\t\t\tif (trialFp->realValue[j] < lbound)\r\n\t\t\t\ttrialFp->realValue[j] = lbound;\r\n\t\t}\r\n\t\tevaluate(trial);\r\n\t\tif (trial->fitness->isBetterThan(deme->at(i)->fitness))\r\n\t\t\treplaceWith(deme->at(i), trial);\r\n\t}\r\n\r\n\t// copy all individuals\r\n\tstd::vector<IndividualP> nest1;\r\n\tstd::vector<IndividualP> nest2;\r\n\tfor (uint i = 0; i < deme->size(); i++) {\r\n\t\tIndividualP indCp = (IndividualP)deme->at(i)->copy();\r\n\t\tnest1.push_back(indCp);\r\n\t\tnest2.push_back(indCp);\r\n\t}\r\n\r\n\t// replace some individuals/nests by constructing new nests\r\n\t// nest is replaced only if it is better than original\r\n\trandom_shuffle(nest1.begin(), nest1.end());\r\n\trandom_shuffle(nest2.begin(), nest2.end());\r\n\tdouble randNum = (double)rand() / RAND_MAX;\r\n\tfor (uint i = 0; i < deme->size(); i++) {\r\n\t\tIndividualP trial = (IndividualP)deme->at(i)->copy();\r\n\t\tFloatingPointP trialFp1 = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (nest1.at(i)->getGenotype(0));\r\n\t\tFloatingPointP trialFp2 = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (nest2.at(i)->getGenotype(0));\r\n\t\tFloatingPointP trialFp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (trial->getGenotype(0));\r\n\r\n\t\tfor (uint j = 0; j < numDimension; j++) {\r\n\t\t\tif ((double)rand() / RAND_MAX < pa) {\r\n\t\t\t\tdouble stepsize = (trialFp1->realValue[j] - trialFp2->realValue[j])*randNum;\r\n\t\t\t\ttrialFp->realValue[j] += stepsize;\r\n\t\t\t\tif (trialFp->realValue[j] > ubound)\r\n\t\t\t\t\ttrialFp->realValue[j] = ubound;\r\n\t\t\t\tif (trialFp->realValue[j] < lbound)\r\n\t\t\t\t\ttrialFp->realValue[j] = lbound;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tevaluate(trial);\r\n\t\tif (trial->fitness->isBetterThan(deme->at(i)->fitness))\r\n\t\t\treplaceWith(deme->at(i), trial);\r\n\t}\r\n\treturn true;\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "c68d76f219918a960dc0402a3d73505b0ad3bf3c", "size": 4548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ECF/AlgCuckooSearch.cpp", "max_stars_repo_name": "KarlaSalamun/ECF", "max_stars_repo_head_hexsha": "4bd21cf43d09435f034259a6b59129b1df6ad1b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ECF/AlgCuckooSearch.cpp", "max_issues_repo_name": "KarlaSalamun/ECF", "max_issues_repo_head_hexsha": "4bd21cf43d09435f034259a6b59129b1df6ad1b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ECF/AlgCuckooSearch.cpp", "max_forks_repo_name": "KarlaSalamun/ECF", "max_forks_repo_head_hexsha": "4bd21cf43d09435f034259a6b59129b1df6ad1b3", "max_forks_repo_licenses": ["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.9846153846, "max_line_length": 135, "alphanum_fraction": 0.6816182938, "num_tokens": 1326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.5504550666668827}}
{"text": "// Author: Daisuke Kanaizumi\n// Affiliation: Department of Applied Mathematics, Waseda University\n \n#ifndef QGAMMA_HPP\n#define QGAMMA_HPP\n\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/complex.hpp>\n#include <kv/constants.hpp>\n#include <limits>\n#include <algorithm>\n#include <kv/Heine.hpp>\n#include <kv/Pochhammer.hpp>\n#include <kv/qPochhammerVer2.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> q_gamma(const interval<T>& z,const interval<T>& q){\n   // q must be positive\n   // verification program for q-gamma function\n   interval<T>res;\n   if(q<1 && q>0){\n     if(pow(q,z)<1){\n       res=pow(1-q,1-z)*Karpelevich(interval<T>(pow(q,z)),interval<T>(q));\n     }\n     else{\n       res=Euler(interval<T>(q))*pow(1-q,1-z)/infinite_qPochhammer(interval<T>(pow(q,z)),interval<T>(q));\n     }\n     /*if(abs(res).upper()==std::numeric_limits<T>::infinity()){\n       // Use asymptotic expansion \n       // M Mansour (2006) An asymptotic expansion of the q-gamma function Γ q (x), Journal of Nonlinear Mathematical Physics, 13:4, 479-483, DOI: 10.2991/jnmp.2006.13.4.2\n       res=sqrt(1+q)*pow(1-q,0.5-z)*Euler(interval<T>(q*q))*pow(1-q*q,0.5)/infinite_qPochhammer(interval<T>(pow(q*q,0.5)),interval<T>(q*q))*interval<T>(1.,(exp(pow(q,z)/(1-q-pow(q,z)))).upper());\n       }*/\n\n   }\n   if(q>1){ // Moak q-gamma function\n     if(pow(q,-z)<1){\n       res=pow(q-1,1-z)*pow(q,z*(z-1)/2)*Karpelevich(interval<T>(pow(q,-z)),interval<T>(1/q));\n     }\n     else{\n       res=Euler(interval<T>(1/q))*pow(q-1,1-z)*pow(q,z*(z-1)/2)/infinite_qPochhammer(interval<T>(pow(q,-z)),interval<T>(1/q));\n     }\n   }\n   return res;\n }\n\n  template <class T> complex<interval<T> >q_gamma(const complex<interval<T> >& z,const interval<T>& q){\n    complex<interval<T> >res;\n    if(q<1 && q>0){\n      res=Euler(interval<T>(q))*pow(1-q,1-z)/infinite_qPochhammer(complex<interval<T> >(pow(q,z)),interval<T>(q));\n    }\n    if(q>1){\n      res=Euler(interval<T>(1/q))*pow(q-1,1-z)*pow(q,z*(z-1)/2)/infinite_qPochhammer(complex<interval<T> >(pow(q,-z)),interval<T>(1/q));\n    }\n    return res;\n }\ntemplate <class T> ub::matrix<interval<T> >MExp(const ub::matrix<interval<T> >& A){\n  int n,M;\n  M=100;\n  n=A.size1();//A:square matrix\n  ub::matrix< interval<T> > B(n, n),res(n, n),sum(n, n),pro(n,n);\n  interval<T> error,norm;\n  T b;\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      sum(i,j)=0.;\n      if(i==j)pro(i,j)=1.;\n      else pro(i,j)=0.;\n    }\n  }\n  for(int N=0;N<=M;N++){\n    sum+=(1./Pochhammer(interval<T>(1.,1.),N))*pro;\n    pro=prod(pro,A);\n  }\n  norm=abs(A(0,0));\n  for(int i1=0;i1<n;i1++){\n    for(int j1=0;j1<n;j1++){\n      if (A(i1,j1)>abs(norm)) norm=abs(A(i1,j1));\n    }\n  }\n\n  error=exp(norm)*pow(norm,M+1)/Pochhammer(interval<T>(1.,1.),M+1);\n  b=(abs(error)).upper();\n\n  for(int k1=0;k1<n;k1++){\n    for(int l1=0;l1<n;l1++){\n      B(k1,l1).assign(-1.,1.);\n      B(k1,l1)=b*B(k1,l1);\n    }\n  }\n  res=sum+B;\n  return res;\n}\ntemplate <class T> ub::matrix<interval<T> >q_gamma(const ub::matrix<interval<T> >& A,const interval<T>& q){\n  int n;\n  n=A.size1();//A:square matrix\n  interval<T>buf;\n  ub::matrix< interval<T> > I(n, n),B(n, n),res(n, n),exp(n,n),inv(n,n),qp(n,n),qa(n,n),AA(n,n);\n  \n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      if(i==j){\n\tI(i,j)=1.;\n\tinv(i,j)=1.;\n      }\n      else{ \n\tI(i,j)=0.;\n\tinv(i,j)=0.;\n      }\n    }      \n  }\n  AA=log(q)*A;\n  qa=MExp(AA);\n  qp=infinite_qPochhammer(ub::matrix<interval<T> > (qa), interval<T> (q));\n//std::cout<<qp<<std::endl;\n  for(int i1=0;i1<n;i1++){\n    buf=1./qp(i1,i1);\n    for(int j1=0;j1<n;j1++){\n      qp(i1,j1)*=buf;\n      inv(i1,j1)*=buf;\n    }\n \n    for(int j2=0;j2<n;j2++){\n      if(i1!=j2){\n\tbuf=qp(j2,i1);\n\tfor(int k=0;k<n;k++){\n\t  qp(j2,k)-=qp(i1,k)*buf;\n\t  inv(j2,k)-=inv(i1,k)*buf;\n\t}\n      }\n    }\n  }\n  B=I-A;\n  B=log(1-q)*B;\n  std::cout<<B<<std::endl;\n  exp=MExp(B);\n  res=infinite_qPochhammer(interval<T>(q),interval<T>(q))\n    *prod(inv,exp);\n  return res;\n}\n  template <class T> complex<interval<T> >qgamma_Gauss_multi(const complex<interval<T> >& z,const interval<T>& q, int  p=3){\n  if(q<1 && q>0){\n    // M Mansour (2006) An asymptotic expansion of the q-gamma function Γ q (x), Journal of Nonlinear Mathematical Physics, 13:4, 479-483, DOI: 10.2991/jnmp.2006.13.4.2\n    // G Gasper , M Rahman, Basic Hypergeometric Series 2nd Edition, Cambridge University Press, 2004.\n    interval<T> pq,pro2;\n    pq=(1-pow(q,p))/(1-q);//pq OK\n    complex<interval<T> >res,pro1;    \n    pro1=1.;\n    pro2=1.;   \n    for(int i=0;i<=p-1;i++){\n      pro1=pro1*q_gamma(complex<interval<T> >((z+i)/p),interval<T>(pow(q,p)));\n      // pro1 OK\n    }\n    for(int j=1;j<=p-1;j++){\n      interval<T> jj;\n      jj=j;\n      pro2=pro2*q_gamma(interval<T> (jj/p),interval<T>(pow(q,p)));      \n    }\n\n    res=pro1*pow(pq,z-1)/pro2;\n    return res;\n  }  \n  else{\n    throw std::domain_error(\"implemented for 0<q<1\");\n  }\n}\ntemplate <class T> complex<interval<T> >qgamma_Legendre(const complex<interval<T> >& z,const interval<T>& q){\n  if(q<1 && q>0){\n    interval<T>qg;\n    qg=q_gamma(interval<T>(0.5),interval<T>(q*q));\n    complex<interval<T> >res;    \n    \n    res=q_gamma(complex<interval<T> >(z*0.5),interval<T>(q*q))\n      *q_gamma(complex<interval<T> >((z+1)*0.5),interval<T>(q*q))\n      *pow(1+q,z-1)/qg;         \n  \n    return res;\n  }  \n  else{\n    throw std::domain_error(\"implemented for 0<q<1\");\n  }\n}\n  template <class T> complex<interval<T> >qgamma_shift(const complex<interval<T> >& z,const interval<T>& q, int p=3){\n    // computing the q-gamma function with functional equation\n    // G Gasper , M Rahman, Basic Hypergeometric Series 2nd Edition, Cambridge University Press, 2004.\n    complex<interval<T> >pro;\n    pro=1.;    \n    for(int i=1;i<=p;i++){\n      pro=pro*(1-pow(q,z-i))/(1-q);\n    }\n    pro=pro*q_gamma(complex<interval<T> >(z-p),interval<T>(q));\n  }\n  template <class T> interval<T> q_digamma(const interval<T>& x,const interval<T>& q){\n    // q,x must be positive\n   // verification program for q-digamma function\n   // Reference: Kamel Brahim (2009), Turan-Type Inequalities for some q-Special Functions\n   // Journal of inequalities in pure and applied mathematics, Volume 10\n   interval<T>res,sum,qq,first,ratio;\n   T rad;\n   int N=100;\n   sum=0.;\n   qq=1.;\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 (x<=0){\n     throw std::domain_error(\"implemented for positive x\");\n   }\n   for(int n=1;n<=N-1;n++){\n     qq=qq*q;\n     sum=sum+pow(q,n*x)/(1-qq);\n   }\n   qq=qq*q;\n   first=pow(q,N*x)/(1-qq);\n   ratio=(1-qq)*pow(q,x)/(1-qq*q);\n if(abs(ratio)<1){\n      rad=(first/(1-ratio)).upper();\n      res=-log(1-q)+log(q)*(sum+rad*interval<T>(-1.,1.));\n      return res;\n    }\n    else{\n      std::cout<<\"ratio is more than 1\"<<std::endl;\n    } \n }\n template <class T> interval<T> q_beta(const interval<T>& a,const interval<T>& b,const interval<T>& q){\n   // q must be positive\n   // verification program for q-beta function\n   interval<T>res;\n   res=q_gamma(interval<T>(a),interval<T>(q))*q_gamma(interval<T>(b),interval<T>(q))/q_gamma(interval<T>(a+b),interval<T>(q));\n   return res;\n }\n  template <class T> complex<interval<T> >q_beta(const complex<interval<T> >& a,const complex<interval<T> >& b,const interval<T>& q){\n   // q must be positive\n   // verification program for q-beta function\n    complex<interval<T> >res;\n    res=q_gamma(complex<interval<T> >(a),interval<T>(q))*q_gamma(complex<interval<T> >(b),interval<T>(q))/q_gamma(complex<interval<T> >(a+b),interval<T>(q));\n    return res;\n  }\n template <class T> interval<T> symmetric_q_gamma(const interval<T>& z,const interval<T>& q){\n   // verification program for symmetric q-gamma function\n   // reference\n   // Brahim and Sidomou, On Some Symmetric q-Special Functions, 2013\n   interval<T>res;\n   res=pow(q,-(z-1)*(z-2)/2)*q_gamma(interval<T>(z),interval<T>(q*q));\n   return res;\n }\n template <class T> interval<T> symmetric_q_beta(const interval<T>& a,const interval<T>& b,const interval<T>& q){\n   // q,a,b must be positive\n   // verification program for symmetric q-beta function\n   // reference\n   // Brahim and Sidomou, On Some Symmetric q-Special Functions, 2013\n   interval<T>res;\n   res=symmetric_q_gamma(interval<T>(a),interval<T>(q))*symmetric_q_gamma(interval<T>(b),interval<T>(q))/symmetric_q_gamma(interval<T>(a+b),interval<T>(q));\n   return res;\n }\n  template <class T> complex<interval<T> >symmetric_q_gamma(const complex<interval<T> >& z,const interval<T>& q){\n   // verification program for symmetric q-gamma function\n   // reference\n   // Brahim and Sidomou, On Some Symmetric q-Special Functions, 2013\n    complex<interval<T> >res;\n    res=pow(q,-(z-1)*(z-2)/2)*q_gamma(complex<interval<T> >(z),interval<T>(q*q));\n   return res;\n }\n  template <class T> complex<interval<T> >incomplete_q_gamma(const complex<interval<T> >& z,const complex<interval<T> >& a,const interval<T>& q){\n    // verification program for incomplete q-gamma function\n    // expansion formula is used\n    // reference\n    // Ahmed Salem, A q-analogue of the exponential integral, 2013\n    // warning: \"a\" should neither be negative integer nor zero\n    complex<interval<T> >res,qq;\n    qq=q;\n    res=pow(z*(1-q),a)*q_gamma(complex<interval<T> >(a),interval<T>(q))\n      *Heine(complex<interval<T> >(z*(1-q)),complex<interval<T> >(pow(q,a)),complex<interval<T> >(0.),interval<T>(q),complex<interval<T> >(qq));\n    return res;\n  }\n template <class T> complex<interval<T> >elliptic_gamma(const complex<interval<T> >& z,const interval<T> & p ,const interval<T> & q){\n    // verification program for elliptic gamma function\n    // reference: M. A. Bershtein, A. I. Shechechkin (arXiv, 2016)\n    // q-deformed Painlev\\`e \\tau function and q-deformed conformal blocks, Appendix A\n    complex<interval<T> >res;\n    /* if (abs(z)>=1){\n      throw std::domain_error(\"implemented only for |z|<1\");\n      }*/\n    if (abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    if (abs(p)>=1){\n      throw std::domain_error(\"absolute value of p must be under 1\");\n    }\n    res=inf_elliptic_Pochhammer(complex<interval<T> >(p*q/z),complex<interval<T> >(p),complex<interval<T> >(q))\n      /inf_elliptic_Pochhammer(complex<interval<T> >(z),complex<interval<T> >(p),complex<interval<T> >(q));\n    return res;\n  }\n  template <class T> complex<interval<T> > modified_Jacobi_theta(const complex<interval<T> >&a,const interval<T> &q){\n    complex<interval<T> >res;\n    res=infinite_qPochhammer(complex<interval<T> >(a),interval<T>(q))\n      *infinite_qPochhammer(complex<interval<T> >(q/a),interval<T>(q));\n    return res;\n  } \n  template <class T> interval<T>  modified_Jacobi_theta(const interval<T> &a,const interval<T> &q){\n    interval<T> res;\n    res=qPVer2(interval<T> (a),interval<T>(q))\n      *qPVer2(interval<T> (q/a),interval<T>(q));\n    return res;\n  }\n  template <class T> complex<interval<T> >elliptic_gamma_tilde(const complex<interval<T> >& z,const interval<T> & p ,const interval<T> & q){\n    complex<interval<T> >res;\n    if (abs(z)>=1){\n      throw std::domain_error(\"implemented only for |z|<1\");\n    }\n    if (abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    if (abs(p)>=1){\n      throw std::domain_error(\"absolute value of p must be under 1\");\n    }\n    res=infinite_qPochhammer(interval<T> (q),interval<T> (q))/infinite_qPochhammer(interval<T> (p),interval<T> (p))\n      *pow(modified_Jacobi_theta(q,p),1-log(z)/log(q))*elliptic_gamma(complex<interval<T> >(z),interval<T>(p),interval<T>(q));\n    return res;\n  }\n  template <class T> complex<interval<T> >elliptic_gamma_shift(const complex<interval<T> >& z,const interval<T> & p ,const interval<T> & q,int n){\n    complex<interval<T> >res,pro1,pro2;\n    interval<T> r;\n    r=pow(q,n);\n    if (abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    if (abs(p)>=1){\n      throw std::domain_error(\"absolute value of p must be under 1\");\n    }\n    for(int i=1;i<=n-1;i++){\n      pro1=pro1*elliptic_gamma_tilde(complex<interval<T> >(i/T(n)),interval<T>(p),interval<T>(r));\n    }\n    for(int j=0;j<=n-1;j++){\n      pro2=pro2*elliptic_gamma_tilde(complex<interval<T> >((z+j)/T(n)),interval<T>(p),interval<T>(r));\n    }\n    res=pow(modified_Jacobi_theta(r,p)/modified_Jacobi_theta(q,p),z-1)*pro2/pro1;\n    return res;\n  }\n template <class T> complex<interval<T> >elliptic_gamma_shift2(const complex<interval<T> >& z,const interval<T> & p ,const interval<T> & q,int n){\n    complex<interval<T> >res,pro1,pro2;\n    interval<T> r;\n    r=pow(q,n);\n    if (abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    if (abs(p)>=1){\n      throw std::domain_error(\"absolute value of p must be under 1\");\n    }\n    for(int i=1;i<=n-1;i++){\n      pro1=pro1*elliptic_gamma_tilde(complex<interval<T> >(T(i)/T(n)),interval<T>(p),interval<T>(r));\n    }\n    for(int j=0;j<=n-1;j++){\n      pro2=pro2*elliptic_gamma_shift(complex<interval<T> >((z+T(j))/T(n)),interval<T>(p),interval<T>(r),int(n));\n    }\n    res=pow(modified_Jacobi_theta(r,p)/modified_Jacobi_theta(q,p),z-1)*pro2/pro1;\n    return res;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "9168a6bbc97c36ca6d8478b7da268989b3c7a25f", "size": 13359, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qgamma.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": "qgamma.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": "qgamma.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": 36.4005449591, "max_line_length": 195, "alphanum_fraction": 0.618085186, "num_tokens": 4342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.5503741303919625}}
{"text": "#define DEBUG 1\n/**\n * File    : E.cpp\n * Author  : Kazune Takahashi\n * Created : 12/14/2019, 10:43:31 PM\n * Powered by Visual Studio Code\n */\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n// ----- boost -----\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\nll MOD{0};\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 -----\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{x % 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) 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};\nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const Mint &a) { return stream << a.x; }\n\n// ----- main() -----\n\n// I wrote this code referring to yataka1999-san's solution\n// https://atcoder.jp/contests/agc035/submissions/6380939\n\nMint solve_even(ll N, ll K);\nMint solve_odd(ll N, ll K);\n\nMint solve_even(ll N, ll K)\n{\n  Mint ans{1};\n  for (auto t = 0LL; t < 2; t++)\n  {\n    auto L{(N - t + 1) / 2};\n    vector<Mint> to(L + 1), from(L + 1);\n    to[0] = 1;\n    for (auto i = 0LL; i < L; i++)\n    {\n      swap(to, from);\n      to = vector<Mint>(L + 1);\n      for (auto j = 0LL; j <= i; j++)\n      {\n        to[j + 1] += from[j];\n        to[0] += from[j];\n      }\n      for (auto j = K / 2 + 1; j <= i + 1; j++)\n      {\n        to[j] = 0;\n      }\n    }\n    Mint sum{0};\n    for (auto j = 0LL; j <= L; j++)\n    {\n      sum += to[j];\n    }\n    ans *= sum;\n  }\n  return ans;\n}\n\nMint solve_odd(ll N, ll K)\n{\n  vector<vector<vector<Mint>>> from(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));\n  vector<vector<vector<Mint>>> to(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));\n  to[0][0][N] = 1;\n  for (auto i = 0LL; i < N; i++)\n  {\n    swap(to, from);\n    to = vector<vector<vector<Mint>>>(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));\n    auto even{i / 2 + 1};\n    auto odd{(i + 1) / 2};\n    for (auto j = 0LL; j <= even; j++)\n    {\n      for (auto k = 0LL; k <= odd; k++)\n      {\n        for (auto t = i; t <= N; t++)\n        {\n          if (from[j][k][t] == 0)\n          {\n            continue;\n          }\n          auto dst{(t % 2 == i % 2) ? N : t};\n          to[0][j][dst] += from[j][k][t];\n          if (t != i)\n          {\n            dst = j >= K / 2 + 1 ? min(t, i - 2 * k + K) : t;\n            to[k + 1][j][dst] += from[j][k][t];\n          }\n        }\n      }\n    }\n  }\n  Mint ans{0};\n  for (auto j = 0LL; j <= N; j++)\n  {\n    for (auto k = 0LL; k <= N; k++)\n    {\n      ans += to[j][k][N];\n    }\n  }\n  return ans;\n}\n\nint main()\n{\n  ll N, K;\n  cin >> N >> K >> MOD;\n  if (K % 2 == 0)\n  {\n    cout << solve_even(N, K) << endl;\n  }\n  else\n  {\n    cout << solve_odd(N, K) << endl;\n  }\n}\n", "meta": {"hexsha": "ac9ebc8b578e6af2bb9321bd6e83c0c9855f1b8e", "size": 4353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/0714_AGC035/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/0714_AGC035/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/0714_AGC035/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": 21.6567164179, "max_line_length": 95, "alphanum_fraction": 0.5010337698, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.5503238094522193}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <libv/lma/time/tictoc.hpp>\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\n\nVector llt(Matrix u, Vector x)\n{\n  for(int i = 0 ; i < u.rows() ; ++i)\n  {\n    for(int k = 0 ; k < i ; ++k)\n      u(i,i) -= u(k,i) * u(k,i);\n    \n    assert(u(i,i)>0);\n    u(i,i) = std::sqrt(u(i,i));\n    \n    for(int j = i + 1; j < u.cols() ; ++j)\n    {\n      for(int k = 0 ; k < i ; ++k)\n        u(i,j) -= u(k,i) * u(k,j);\n      u(i,j) /= u(i,i);\n    }\n  }\n\n  for(int j = 0 ; j < x.size() ; ++j)\n  {\n    for(int i = 0 ; i < j ; ++i)\n      x(j) -= u(i,j) * x(i);\n    x(j) /= u(j,j);\n  }\n  \n  for(int j = x.size() - 1 ; j >=0  ; --j)\n  {\n    for(int i = j+1 ; i < x.size() ; ++i)\n      x(j) -= u(j,i) * x(i);\n    x(j) /= u(j,j);\n  }\n\n  return x;\n}\n\nint main()\n{\n  size_t n = 10;\n  Matrix a(n,n);\n  Vector b(n),x(n);\n\n  a = Matrix::Random(n,n);\n  a = (a + a.transpose()).eval();\n\n  for(size_t i = 0 ; i < n ; ++i)\n  {\n    if (a(i,i)<0) a(i,i) = - a(i,i);\n    a(i,i) += 10.0;\n    x(i) = i+1;\n  }\n  \n  b = a * x;\n  \n  for(size_t i = 0 ; i < n ; ++i)\n    for(size_t j = 0 ; j < n ; ++j)\n    {\n      if (j<i) a(i,j) = 0;\n    }\n  std::cout << a << std::endl;\n  std::cout << \" determinant \" << a.determinant() << std::endl;\n//   std::cout << \"\\nb = \" << b.transpose() << std::endl;\n  \n  size_t N = 1000000;\n//   size_t N = 1; \n  \n  utils::Tic<true> tic(\"llt\");\n  for(size_t i = 0 ; i < N; ++i)\n    x = llt(a,b);\n  tic.disp();\n  std::cout << \"\\nX = \" << x.transpose() << std::endl;\n\n  Vector X;\n  \n  utils::Tic<true> tic2(\"LLT\");\n  for(size_t i = 0 ; i < N ; ++i)\n  {\n    Eigen::LLT<Matrix,Eigen::Upper> LLT(a);\n    X = LLT.solve(b);\n  }\n  tic2.disp();\n//   std::cout << \"\\nX = \" << x.transpose() << std::endl;\n  \n//   std::cout << \"A * x = \" << (a * x).transpose() << std::endl;\n  \n//   Matrix L = LLT.matrixL();\n//   Matrix U = LLT.matrixU();\n//   std::cout << \"\\nL =\\n\" << L << std::endl;\n//   std::cout << \"\\nU =\\n\" << U << std::endl;\n  std::cout << \"\\nX = \" << X.transpose() << std::endl;\n//   std::cout << \" CHECK \" << (a*X - b).transpose() << std::endl;\n  \n  return x == X;\n}\n", "meta": {"hexsha": "ba687dcee5840c6e2b6892dfcbe969434094bc9b", "size": 2147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/llt.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/llt.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/llt.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": 21.0490196078, "max_line_length": 66, "alphanum_fraction": 0.4336283186, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.5503237974273961}}
{"text": "/*\n * KMeans.cpp\n *\n *  Created on: Mar 12, 2016\n *      Author: zxi\n */\n\n#include \"Clustering.h\"\n#include <Eigen/Eigenvalues>\n\n#include <iostream>\n#include <algorithm>\n#include <cfloat>\n#include <ctime>\n\nnamespace masc {\nnamespace clustering {\n\n#define TIMING(code, verbosity, output) \\\n  { \\\n    auto s = clock(); \\\n    (code); \\\n    auto e = clock(); \\\n    if (this->m_verbosity >= (verbosity) ) \\\n      std::cout<< (output) << \" takes \" << (e-s)*1.0 / CLOCKS_PER_SEC << \" s\" << std::endl; \\\n  } \\\n\ntemplate<class T>\nVectorXi ClusteringBase<T>::labelsInertia(const MatrixXd& X,\n    const MatrixXd& centriods, VectorXd* distances, double* inertia) {\n\n  const int n_samples = X.rows();\n  const int n_k = centriods.rows();\n\n  *distances = VectorXd(n_samples);\n  *inertia = 0.0;\n\n  VectorXi labels(n_samples);\n\n  for (int i = 0; i < n_samples; ++i) {\n    double min_dist = FLT_MAX;\n    int label = -1;\n    for (int j = 0; j < n_k; ++j) {\n      double dist = (X.row(i) - centriods.row(j)).norm();\n      if (dist < min_dist) {\n        label = j;\n        min_dist = dist;\n      }\n    }\n\n    *inertia += min_dist;\n    labels(i) = label;\n    (*distances)(i) = min_dist;\n  }\n\n  return labels;\n}\n\ntemplate<class T>\nKMeansBase<T>::KMeansBase(int n_clusters, int n_init, int max_iter, double tol) :\n    m_n_clusters(n_clusters), m_n_init(n_init), m_max_iter(max_iter), m_tol(tol) {\n//TODO\n}\n\ntemplate<class T>\nKMeansBase<T>::~KMeansBase() {\n  // nothing to do here\n}\n\ntemplate<class T>\nMatrixXd KMeansBase<T>::initCentroids(const MatrixXd& X) {\n  const int n_samples = X.rows();\n  const int n_features = X.cols();\n\n  MatrixXd centroids(m_n_clusters, n_features);\n\n  MatrixXd best_centroids;\n  VectorXd distences;\n  double best_score = FLT_MAX;\n\n  std::uniform_int_distribution<int> dist(0, n_samples);\n\n  for (int r = 0; r < m_n_init; ++r) {\n\n    for (int i = 0; i < m_n_clusters; ++i) {\n      int sample = dist(this->m_rd);\n      centroids.row(i) = X.row(sample);\n    }\n\n    double score;\n    this->labelsInertia(X, centroids, &distences, &score);\n\n    if (score < best_score) {\n      best_score = score;\n      best_centroids = centroids;\n    }\n\n  }\n\n  return best_centroids;\n}\n\ntemplate<class T>\nMatrixXd KMeansBase<T>::updateCenters(const MatrixXd& X,\n    const VectorXi& labels) {\n  const int n_samples = X.rows();\n  const int n_features = X.cols();\n\n  MatrixXd centroids = Eigen::MatrixXd::Zero(m_n_clusters, n_features);\n  VectorXi count = Eigen::VectorXi::Zero(m_n_clusters);\n\n  for (int i = 0; i < n_samples; ++i) {\n    centroids.row(labels[i]) += X.row(i);\n    count(labels[i]) += 1;\n  }\n\n  for (int i = 0; i < m_n_clusters; ++i) {\n    if (count(i) > 0)\n      centroids.row(i) /= count(i);\n  }\n\n  return centroids;\n}\n\ntemplate<class T>\nT& KMeansBase<T>::fit(const MatrixXd& X) {\n  auto centers = this->initCentroids(X);\n\n  if (this->m_verbosity >= 2)\n    std::cout << \"KMeansBase::fit - init centers = \" << std::endl << centers << std::endl;\n\n  VectorXd distances;\n\n  double best_inertia = FLT_MAX / 2.0;\n  VectorXi best_labels;\n  MatrixXd best_centers;\n\n  for (int i = 0; i < m_max_iter; ++i) {\n    auto old_centers = centers;\n    double inertia = 0.0;\n    auto labels = this->labelsInertia(X, old_centers, &distances, &inertia);\n    centers = this->updateCenters(X, labels);\n\n    if (this->m_verbosity >= 1)\n      std::cout << \"KMeansBase::fit - iter \" << i << \" inertia = \" << inertia << std::endl;\n\n    if (inertia < best_inertia) {\n      best_inertia = inertia;\n      best_labels = labels;\n      best_centers = centers;\n    }\n\n    auto shift = (old_centers - centers).norm();\n\n    if (shift * shift < this->m_tol) {\n      if (this->m_verbosity >= 1)\n        std::cout << \"KMeansBase::fit - Converged at iteration \" << i << std::endl;\n      break;\n    }\n  }\n\n  this->m_cluster_centers = best_centers;\n  this->m_labels = this->labelsInertia(X, best_centers, &distances,\n      &best_inertia);\n  this->m_inertia = best_inertia;\n\n  return static_cast<T&>(*this);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// KMeans\n///////////////////////////////////////////////////////////////////////////////\nKMeans::KMeans(int n_clusters, int n_init, int max_iter, double tol) :\n    KMeansBase<KMeans>(n_clusters, n_init, max_iter, tol) {\n\n}\n\nKMeans::~KMeans() {\n  //TODO\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// SpectralClustering\n///////////////////////////////////////////////////////////////////////////////\nSpectralClustering::SpectralClustering(int n_clusters, double gamma,\n    AffinityType affinity_type) :\n    KMeansBase<SpectralClustering>(n_clusters), m_affinity_type(affinity_type), m_gamma(\n        gamma) {\n//TODO\n}\n\nSpectralClustering::~SpectralClustering() {\n  //TODO\n}\n\nMatrixXd SpectralClustering::constructAffinityMatrix(const MatrixXd& X,\n    AffinityType affinity_type) {\n\n  const int n_samples = X.rows();\n\n  MatrixXd W(n_samples, n_samples);\n\n  switch (affinity_type) {\n  case AffinityType::RBF:\n\n    // compute pairwise distance\n    for (int i = 0; i < n_samples; ++i) {\n      W(i, i) = 1.0;\n      for (int j = i + 1; j < n_samples; ++j) {\n        double dist = (X.row(i) - X.row(j)).norm();\n        W(i, j) = W(j, i) = exp(-(this->m_gamma) * dist * dist);\n      }\n    }\n\n    break;\n  default:\n    std::cerr << \"Unsupported affinity type \" << (int) affinity_type\n        << std::endl;\n    break;\n  }\n\n  return W;\n}\n\nSpectralClustering& SpectralClustering::fit(const MatrixXd& X) {\n  const int n_samples = X.rows();\n  const int n_features = X.cols();\n\n  // Affinity matrix\n  MatrixXd W;\n  TIMING(W = this->constructAffinityMatrix(X, this->m_affinity_type), 1,\n      \"SpectralClustering::fit - construct affinity matrix\");\n\n  // Degree matrix\n  MatrixXd D = W.rowwise().sum().asDiagonal();\n\n  // Laplacian matrix\n  MatrixXd L = D - W;\n\n  Eigen::SelfAdjointEigenSolver<MatrixXd> es(n_samples);\n  TIMING(es.compute(L), 1, \"SpectralClustering::fit - compute eigen vectors\");\n\n  const MatrixXd& evs = es.eigenvectors();\n\n  // embedded matrix (n_samples * k)\n  MatrixXd embed(n_samples, m_n_clusters);\n\n  for (int i = 0; i < m_n_clusters; ++i)\n    embed.col(i) = evs.col(i);\n\n  // run kmeans clustering on embed\n  TIMING(KMeansBase<SpectralClustering>::fit(embed), 1,\n      \"SpectralClustering::fit - kmeans clustering\");\n\n  return *this;\n}\n\n} /* namespace clustering */\n} /* namespace masc */\n", "meta": {"hexsha": "253e02f94bbaa0752a9a36c07cfacc20ec511fd9", "size": 6383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libclustering/Clustering.cpp", "max_stars_repo_name": "xizhonghua/clustering", "max_stars_repo_head_hexsha": "59b81726c95222354a5aa681752309e359ab40ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libclustering/Clustering.cpp", "max_issues_repo_name": "xizhonghua/clustering", "max_issues_repo_head_hexsha": "59b81726c95222354a5aa681752309e359ab40ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libclustering/Clustering.cpp", "max_forks_repo_name": "xizhonghua/clustering", "max_forks_repo_head_hexsha": "59b81726c95222354a5aa681752309e359ab40ff", "max_forks_repo_licenses": ["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.55, "max_line_length": 93, "alphanum_fraction": 0.6022246593, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.5502184440436777}}
{"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/*\nSolutions for testdata were generated with Scilab line:\n\nM=fscanfMat('nsm1.example');e=spec(M);e=gsort(e);rr=real(e);ii=imag(e);e=cat(1, rr, ii); s=strcat(string(e), ' ');write('tmp', s);\n*/\n\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n//#define VIENNACL_DEBUG_ALL\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <vector>\n\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/qr-method.hpp\"\n\n#include <examples/benchmarks/benchmark-utils.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\ntypedef float ScalarType;\n\nconst ScalarType EPS = 0.0001f;\n\nvoid read_matrix_size(std::fstream& f, std::size_t& sz)\n{\n    if(!f.is_open())\n    {\n        throw std::invalid_argument(\"File is not opened\");\n    }\n\n    f >> sz;\n}\n\ntemplate <typename MatrixLayout>\nvoid read_matrix_body(std::fstream& f, viennacl::matrix<ScalarType, MatrixLayout>& A)\n{\n    if(!f.is_open())\n    {\n        throw std::invalid_argument(\"File is not opened\");\n    }\n\n    boost::numeric::ublas::matrix<ScalarType> h_A(A.size1(), A.size2());\n\n    for(std::size_t i = 0; i < h_A.size1(); i++) {\n        for(std::size_t j = 0; j < h_A.size2(); j++) {\n            ScalarType val = 0.0;\n            f >> val;\n            h_A(i, j) = val;\n        }\n    }\n\n    viennacl::copy(h_A, A);\n}\n\nvoid read_vector_body(std::fstream& f, std::vector<ScalarType>& v) {\n    if(!f.is_open())\n        throw std::invalid_argument(\"File is not opened\");\n\n    for(std::size_t i = 0; i < v.size(); i++)\n    {\n            ScalarType val = 0.0;\n            f >> val;\n            v[i] = val;\n    }\n}\n\ntemplate <typename MatrixLayout>\nbool check_tridiag(viennacl::matrix<ScalarType, MatrixLayout>& A_orig)\n{\n    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());\n    viennacl::copy(A_orig, A);\n\n    for (unsigned int i = 0; i < A.size1(); i++) {\n        for (unsigned int j = 0; j < A.size2(); j++) {\n            if ((std::abs(A(i, j)) > EPS) && ((i - 1) != j) && (i != j) && ((i + 1) != j))\n            {\n                // std::cout << \"Failed at \" << i << \" \" << j << \" \" << A(i, j) << \"\\n\";\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\ntemplate <typename MatrixLayout>\nbool check_hessenberg(viennacl::matrix<ScalarType, MatrixLayout>& A_orig)\n{\n    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());\n    viennacl::copy(A_orig, A);\n\n    for (std::size_t i = 0; i < A.size1(); i++) {\n        for (std::size_t j = 0; j < A.size2(); j++) {\n            if ((std::abs(A(i, j)) > EPS) && (i > (j + 1)))\n            {\n                // std::cout << \"Failed at \" << i << \" \" << j << \" \" << A(i, j) << \"\\n\";\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\nScalarType matrix_compare(ublas::matrix<ScalarType>& res,\n                            ublas::matrix<ScalarType>& ref)\n{\n    ScalarType diff = 0.0;\n    ScalarType mx = 0.0;\n\n    for(std::size_t i = 0; i < res.size1(); i++)\n    {\n        for(std::size_t j = 0; j < res.size2(); j++)\n        {\n            diff = std::max(diff, std::abs(res(i, j) - ref(i, j)));\n            mx = std::max(mx, res(i, j));\n        }\n    }\n\n    return diff / mx;\n}\n\nScalarType vector_compare(std::vector<ScalarType> & res,\n                          std::vector<ScalarType> & ref)\n{\n    std::sort(ref.begin(), ref.end());\n    std::sort(res.begin(), res.end());\n\n    ScalarType diff = 0.0;\n    ScalarType mx = 0.0;\n    for(size_t i = 0; i < res.size(); i++)\n    {\n        diff = std::max(diff, std::abs(res[i] - ref[i]));\n        mx = std::max(mx, res[i]);\n    }\n\n    return diff / mx;\n}\n\ntemplate <typename MatrixLayout>\nvoid matrix_print(viennacl::matrix<ScalarType, MatrixLayout>& A)\n{\n    for (unsigned int i = 0; i < A.size1(); i++) {\n        for (unsigned int j = 0; j < A.size2(); j++)\n           std::cout << std::fixed << A(i, j) << \"\\t\";\n        std::cout << \"\\n\";\n    }\n}\n\ntemplate <typename MatrixLayout>\nvoid test_eigen(const std::string& fn, bool is_symm)\n{\n    std::cout << \"Reading...\" << \"\\n\";\n    std::size_t sz;\n    // read file\n    std::fstream f(fn.c_str(), std::fstream::in);\n    //read size of input matrix\n    read_matrix_size(f, sz);\n\n    if (viennacl::is_row_major<MatrixLayout>::value)\n      std::cout << \"Testing row-major matrix of size \" << sz << \"-by-\" << sz << std::endl;\n    else\n      std::cout << \"Testing column-major matrix of size \" << sz << \"-by-\" << sz << std::endl;\n\n    viennacl::matrix<ScalarType> A_input(sz, sz), A_ref(sz, sz), Q(sz, sz);\n    // reference vector with reference values from file\n    std::vector<ScalarType> eigen_ref_re(sz);\n    // calculated real eigenvalues\n    std::vector<ScalarType> eigen_re(sz);\n    // calculated im. eigenvalues\n    std::vector<ScalarType> eigen_im(sz);\n\n    // read input matrix from file\n    read_matrix_body(f, A_input);\n    // read reference eigenvalues from file\n    read_vector_body(f, eigen_ref_re);\n\n\n    f.close();\n\n    A_ref = A_input;\n\n    std::cout << \"Calculation...\" << \"\\n\";\n\n    Timer timer;\n    timer.start();\n    // Start the calculation\n    if(is_symm)\n        viennacl::linalg::qr_method_sym(A_input, Q, eigen_re);\n    else\n        viennacl::linalg::qr_method_nsm(A_input, Q, eigen_re, eigen_im);\n/*\n\n    std::cout << \"\\n\\n Matrix A: \\n\\n\";\n    matrix_print(A_input);\n    std::cout << \"\\n\\n\";\n\n    std::cout << \"\\n\\n Matrix Q: \\n\\n\";\n    matrix_print(Q);\n    std::cout << \"\\n\\n\";\n*/\n\n    double time_spend = timer.get();\n\n    std::cout << \"Verification...\" << \"\\n\";\n\n    bool is_hessenberg = check_hessenberg(A_input);\n    bool is_tridiag = check_tridiag(A_input);\n\n    ublas::matrix<ScalarType> A_ref_ublas(sz, sz), A_input_ublas(sz, sz), Q_ublas(sz, sz), result1(sz, sz), result2(sz, sz);\n    viennacl::copy(A_ref, A_ref_ublas);\n    viennacl::copy(A_input, A_input_ublas);\n    viennacl::copy(Q, Q_ublas);\n\n    // compute result1 = ublas::prod(Q_ublas, A_input_ublas);   (terribly slow when using ublas directly)\n    for (std::size_t i=0; i<result1.size1(); ++i)\n      for (std::size_t j=0; j<result1.size2(); ++j)\n      {\n        ScalarType value = 0;\n        for (std::size_t k=0; k<Q_ublas.size2(); ++k)\n          value += Q_ublas(i, k) * A_input_ublas(k, j);\n        result1(i,j) = value;\n      }\n    // compute result2 = ublas::prod(A_ref_ublas, Q_ublas);   (terribly slow when using ublas directly)\n    for (std::size_t i=0; i<result2.size1(); ++i)\n      for (std::size_t j=0; j<result2.size2(); ++j)\n      {\n        ScalarType value = 0;\n        for (std::size_t k=0; k<A_ref_ublas.size2(); ++k)\n          value += A_ref_ublas(i, k) * Q_ublas(k, j);\n        result2(i,j) = value;\n      }\n\n\n    ScalarType prods_diff = matrix_compare(result1, result2);\n    ScalarType eigen_diff = vector_compare(eigen_re, eigen_ref_re);\n\n\n    bool is_ok = is_hessenberg;\n\n    if(is_symm)\n        is_ok = is_ok && is_tridiag;\n\n    is_ok = is_ok && (eigen_diff < EPS);\n    is_ok = is_ok && (prods_diff < EPS);\n\n    // std::cout << A_ref << \"\\n\";\n    // std::cout << A_input << \"\\n\";\n    // std::cout << Q << \"\\n\";\n    // std::cout << eigen_re << \"\\n\";\n    // std::cout << eigen_im << \"\\n\";\n    // std::cout << eigen_ref_re << \"\\n\";\n    // std::cout << eigen_ref_im << \"\\n\";\n\n    // std::cout << result1 << \"\\n\";\n    // std::cout << result2 << \"\\n\";\n    // std::cout << eigen_ref << \"\\n\";\n    // std::cout << eigen << \"\\n\";\n\n    printf(\"%6s [%dx%d] %40s time = %.4f\\n\", is_ok?\"[[OK]]\":\"[FAIL]\", (int)A_ref.size1(), (int)A_ref.size2(), fn.c_str(), time_spend);\n    printf(\"tridiagonal = %d, hessenberg = %d prod-diff = %f eigen-diff = %f\\n\", is_tridiag, is_hessenberg, prods_diff, eigen_diff);\n    std::cout << std::endl << std::endl;\n\n    if (!is_ok)\n      exit(EXIT_FAILURE);\n\n}\n\nint main()\n{\n\n  test_eigen<viennacl::row_major>(\"../../examples/testdata/eigen/symm5.example\", true);\n // test_eigen<viennacl::row_major>(\"../../examples/testdata/eigen/symm3.example\", true);  // Computation of this matrix takes very long\n\n  test_eigen<viennacl::column_major>(\"../../examples/testdata/eigen/symm5.example\", true);\n//  test_eigen<viennacl::column_major>(\"../../examples/testdata/eigen/symm3.example\", true);\n\n#ifdef VIENNACL_WITH_OPENCL\n  test_eigen<viennacl::row_major>(\"../../examples/testdata/eigen/nsm2.example\", false);\n#endif\n  //test_eigen<viennacl::row_major>(\"../../examples/testdata/eigen/nsm2.example\", false);\n  //test_eigen(\"../../examples/testdata/eigen/nsm3.example\", false);\n  //test_eigen(\"../../examples/testdata/eigen/nsm4.example\", false); //Note: This test suffers from round-off errors in single precision, hence disabled\n\n  std::cout << std::endl;\n  std::cout << \"------- Test completed --------\" << std::endl;\n  std::cout << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "514cd48e23eafdb29230e711c4072e4096d6f5c4", "size": 9499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/qr_method.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/qr_method.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/qr_method.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": 30.3482428115, "max_line_length": 152, "alphanum_fraction": 0.5617433414, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.5501946393287571}}
{"text": "#ifndef __PROBABILITY_DISTRIBUTIONS__ASYMMETRIC_DISTRIBUTION_IMPL_HPP__\n#define __PROBABILITY_DISTRIBUTIONS__ASYMMETRIC_DISTRIBUTION_IMPL_HPP__\n\n#include \"asymmetric_distribution.hpp\"\n\n#include \"const_slice.hpp\"\n#include \"slice.hpp\"\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/exponential_distribution.hpp>\n#include <cmath>\n\nnamespace ProbabilityDistributions {\n  template <class Dist, class D, class W, class T>\n  AsymmetricDistribution<Dist,D,W,T>::AsymmetricDistribution(T p, T mu, T eps,\n      T tol):\n    fixed_mu_(false),\n    fixed_p_(false),\n    mu_(mu),\n    eps_(eps),\n    tol_(tol) {\n      set_mu(mu);\n      set_p(p);\n    }\n\n  template <class Dist, class D, class W, class T>\n  void AsymmetricDistribution<Dist,D,W,T>::init() {\n    set_p(p_);\n  }\n\n  template <class Dist, class D, class W, class T>\n  void AsymmetricDistribution<Dist,D,W,T>::set_p(T p) {\n    assert(p > 0);\n    assert(p < 1);\n    p_ = p;\n    static_cast<Dist*>(this)->updated_p();\n  }\n\n  template <class Dist, class D, class W, class T>\n  template <class RNG>\n  void AsymmetricDistribution<Dist,D,W,T>::sample(MA::Array<D>& samples,\n      size_t n_samples, RNG& rng) const {\n    MA::Size::SizeType size(2);\n    size[0] = n_samples;\n    size[1] = 1;\n    samples.resize(size);\n\n    boost::random::uniform_real_distribution<T> dist(0, 1);\n    auto gamma_plus = static_cast<Dist const*>(this)->create_gamma_plus();\n    auto gamma_minus = static_cast<Dist const*>(this)->create_gamma_minus();\n\n    D* ptr = samples.get_pointer();\n\n    for (size_t j = 0; j < n_samples; j++) {\n      if (dist(rng) < p_)\n        ptr[j] = mu_ - gamma_minus(rng);\n      else\n        ptr[j] = mu_ + gamma_plus(rng);\n    }\n  }\n\n  template <class Dist, class D, class W, class T>\n  T AsymmetricDistribution<Dist,D,W,T>::log_likelihood(\n      MA::ConstArray<D> const& data, MA::ConstArray<W> const& weight) const {\n    check_data_and_weight(data, weight);\n\n    D const* ptr = data.get_pointer();\n\n    T ll = 0;\n    T const_likelihood = static_cast<Dist const*>(this)->constant_likelihood() +\n      (std::log(p_) + std::log(1-p_))/2;\n\n    for (size_t j = 0; j < data.total_size(); j++) {\n      T w = weight(j);\n      T s = ptr[j];\n      T local_likelihood = const_likelihood;\n      if (s < mu_)\n        local_likelihood += static_cast<Dist const*>(this)->negative_ll(s, mu_);\n      else\n        local_likelihood += static_cast<Dist const*>(this)->positive_ll(s, mu_);\n      ll += w * local_likelihood;\n    }\n\n    return ll;\n  }\n\n  template <class Dist, class D, class W, class T>\n  void AsymmetricDistribution<Dist,D,W,T>::MLE(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes) {\n    check_data_and_weight(data, weight);\n    assert(data.size()[0] == indexes.size());\n\n    static_cast<Dist*>(this)->init_MLE(data, weight, indexes);\n\n    if (fixed_p_)\n      static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n    else {\n      T step  = eps_;\n\n      T center_p = p_, left_p = center_p - step, right_p = center_p + step;\n\n      set_p(center_p);\n      static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n      T center_ll = log_likelihood(data, weight), left_ll, right_ll;\n\n      if (left_p > 0) {\n        set_p(left_p);\n        static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n        left_ll = log_likelihood(data, weight);\n      }\n      else\n        left_ll = -INFINITY;\n\n      if (right_p < 1) {\n        set_p(right_p);\n        static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n        right_ll = log_likelihood(data, weight);\n      }\n        right_ll = -INFINITY;\n\n      while (1) {\n        if (std::abs(center_ll - left_ll)  < tol_ &&\n            std::abs(right_ll  - left_ll)  < tol_ &&\n            std::abs(center_ll - right_ll) < tol_)\n          break;\n\n        if (center_ll > left_ll && center_ll > right_ll) {\n          if (step < tol_) {\n            set_p(center_p);\n            break;\n          }\n\n          step *= 1e-1;\n          left_p = center_p - step;\n          right_p = center_p + step;\n\n          if (left_p > 0) {\n            set_p(left_p);\n            static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n            left_ll = log_likelihood(data, weight);\n          }\n          else\n            left_ll = -INFINITY;\n\n          if (right_p < 1) {\n            set_p(right_p);\n            static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n            right_ll = log_likelihood(data, weight);\n          }\n          else\n            right_ll = -INFINITY;\n        }\n        else if (left_ll > right_ll) {\n          right_p = center_p;\n          center_p = left_p;\n          right_ll = center_ll;\n          center_ll = left_ll;\n\n          left_p = center_p - step;\n\n          if (left_p > 0) {\n            set_p(left_p);\n            static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n            left_ll = log_likelihood(data, weight);\n          }\n          else\n            left_ll = -INFINITY;\n        }\n        else {\n          left_p = center_p;\n          center_p = right_p;\n          left_ll = center_ll;\n          center_ll = right_ll;\n\n          right_p = center_p + step;\n\n          if (right_p < 1) {\n            set_p(right_p);\n            static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n            right_ll = log_likelihood(data, weight);\n          }\n          else\n            right_ll = -INFINITY;\n        }\n      }\n\n      static_cast<Dist*>(this)->MLE_fixed_p(data, weight, indexes);\n    }\n\n    static_cast<Dist*>(this)->end_MLE();\n  }\n\n  template <class Dist, class D, class W, class T>\n  T AsymmetricDistribution<Dist,D,W,T>::fix_step(T p, T step) const {\n    while (p_ + step <= 0 || p_ + step >= 1)\n      step *= 0.99;\n    return step;\n  }\n\n  template <class Dist, class D, class W, class T>\n  void AsymmetricDistribution<Dist,D,W,T>::check_data_and_weight(\n      MA::ConstArray<D> const& data, MA::ConstArray<W> const& weight) const {\n    assert(data.size().size() == 2);\n    assert(data.size()[0] > 0);\n    assert(data.size()[1] == 1);\n    assert(weight.size().size() == 1);\n    assert(weight.size()[0] == data.size()[0]);\n  }\n};\n\n#endif\n", "meta": {"hexsha": "dcaca00d629a19ba90759ba7ceb9249a7d827167", "size": 6200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/asymmetric_distribution_impl.hpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/asymmetric_distribution_impl.hpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/asymmetric_distribution_impl.hpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2452830189, "max_line_length": 80, "alphanum_fraction": 0.5866129032, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.5501946240453173}}
{"text": "// Copyright (c) 2011 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 <Eigen/Geometry> \n\n#include \"libmv/multiview/affine.h\"\n#include \"libmv/multiview/similarity.h\"\n#include \"libmv/multiview/similarity_parameterization.h\"\n\nnamespace libmv {\n\n// Parametrization\n// s*cos -s*sin  tx\n// s*sin  s*cos  ty\n// 0      0      1\n\n// It gives the following system A x = B :\n// |-Y1  Y1 1 0 | | s*sin |   | X2 |\n// | X1  Y1 0 1 | | s*cos |   | Y2 |\n//                | tx    | =\n//                | ty    |\n// \nbool Similarity2DFromCorrespondencesLinear(const Mat &x1, const Mat &x2,\n                                           Mat3 *M,\n                                           double expected_precision) {\n  assert(2 == x1.rows());\n  assert(2 <= x1.cols());\n  assert(x1.rows() == x2.rows());\n  assert(x1.cols() == x2.cols());\n\n  const int n = x1.cols();\n  Mat A = Mat::Zero(2*n, 4);\n  Mat b = Mat::Zero(2*n, 1);\n  for (int i = 0; i < n; ++i) {\n    const int j= i * 2;\n    A(j,0) = -x1(1,i);\n    A(j,1) =  x1(0,i);\n    A(j,2) =  1.0;\n    //A(j,3) =  0.0;\n\n    A(j+1,0) = x1(0,i);\n    A(j+1,1) = x1(1,i);\n    //A(j+1,2) = 0.0;\n    A(j+1,3) = 1.0;\n\n    b(j,0)   = x2(0,i);\n    b(j+1,0) = x2(1,i);\n  }\n  // Solve Ax=B\n  Vec x = A.fullPivLu().solve(b);\n  if ((A * x).isApprox(b, expected_precision))  {\n    Similarity2DSCParameterization<double>::To(x, M);    \n    return true;\n  } else {\n    return false;\n  }\n}\n\nbool Similarity3DFromCorrespondencesLinear(const Mat &x1,\n                                          const Mat &x2,\n                                          Mat4 *H,\n                                          double expected_precision) {\n   // TODO(julien) Compare to *H = umeyama (x1, x2, true);\n   // and keep the best one (quality&speed)   \n  if (Affine3DFromCorrespondencesLinear(x1, x2, H, expected_precision)) {\n    // Ensures that R is orthogonal (using SDV decomposition)\n    Eigen::JacobiSVD<Mat> svd(H->block<3,3>(0, 0), Eigen::ComputeThinU | \n                                                   Eigen::ComputeThinV);\n    double scale = svd.singularValues()(0);\n    Mat3 sI3 = scale * Mat3::Identity();\n    H->block<3,3>(0, 0) = svd.matrixU() * sI3 * svd.matrixV().transpose();\n    if (H->block<3,3>(0, 0).determinant() < 0)\n      H->block<3,3>(0, 0) = -H->block<3,3>(0, 0);  \n    return true;\n  }\n  return false;\n}\n\nbool ExtractSimilarity2DCoefficients(const Mat3 &M,\n                                     Vec2   *tr,\n                                     double *angle,\n                                     double *scale) {\n  Vec4 p;\n  Similarity2DSAParameterization<double>::From(M, &p);  \n  *scale = p(0);\n  *angle = p(1);  \n  *tr << p(2), p(3);\n  return true;\n}\n} // namespace libmv\n", "meta": {"hexsha": "fe779befa1dc6ff08d31b768fb87526231b95217", "size": 3746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmv/multiview/similarity.cc", "max_stars_repo_name": "jackyspeed/libmv", "max_stars_repo_head_hexsha": "aae2e0b825b1c933d6e8ec796b8bb0214a508a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T09:20:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:03:20.000Z", "max_issues_repo_path": "src/libmv/multiview/similarity.cc", "max_issues_repo_name": "jackyspeed/libmv", "max_issues_repo_head_hexsha": "aae2e0b825b1c933d6e8ec796b8bb0214a508a84", "max_issues_repo_licenses": ["MIT"], "max_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/similarity.cc", "max_forks_repo_name": "jackyspeed/libmv", "max_forks_repo_head_hexsha": "aae2e0b825b1c933d6e8ec796b8bb0214a508a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-08T20:57:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T12:59:11.000Z", "avg_line_length": 34.6851851852, "max_line_length": 79, "alphanum_fraction": 0.5718099306, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.5501761614547359}}
{"text": "/**\n * See https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169\n */\n\n#include <cassert>\n#include <limits>\n#include <algorithm>\n#include <set>\n\n#include <boost/variant/static_visitor.hpp>\n\n#include <common/Geometry.h>\n#include <common/geometry/Circle.h>\n\n#include <common/geometry/collision.h>\n\nusing namespace std;\n\nnamespace geometry {\n\nbool collision(Circle const &c1, Circle const &c2) {\n\treturn distance(c1.center, c2.center) <= (c1.radius + c2.radius);\n}\n\nMinMax minmaxProjection(Polygon const &polygon, Vector axis) {\n\tMinMax minmax = {numeric_limits<Scalar>::max(), numeric_limits<Scalar>::lowest()};\n\tfor(Point const & point : polygon) {\n\t\tauto d = (point - Point{0,0}) * axis;\n\t\tminmax.min = min(minmax.min, d);\n\t\tminmax.max = max(minmax.max, d);\n\t}\n\treturn minmax;\n}\n\n\nbool gapAlongAxis(Vector axis, Polygon const &p1, Polygon const &p2) {\n\tMinMax r1 = minmaxProjection(p1, axis);\n\tMinMax r2 = minmaxProjection(p2, axis);\n\n\treturn (r1.max < r2.min) || (r2.max < r1.min);\n}\n\nvoid getNormals(std::set<Vector> &normals, Polygon const &polygon) {\n\tif (polygon.empty())\n\t\treturn;\n\n\tPoint prev = polygon.back();\n\tfor(auto const & curr : polygon) {\n\t\tnormals.insert(leftNormal(unit(curr - prev)));\n\t\tprev = curr;\n\t}\n}\n\nbool collision(Polygon const &p1, Polygon const &p2) {\n\tstd::set<Vector> normals;\n\tgetNormals(normals, p1);\n\tgetNormals(normals, p2);\n\n\tfor (auto const &n : normals) {\n\t\tif (gapAlongAxis(n, p1, p2))\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n// TODO na zacatek nekam pridam kruh\n\n// Does not detect full containing\nbool collision(Polygon const &polygon, Circle const &circle) {\n\n\t// Near vertex\n\tfor(Point const & vertex : polygon) {\n\t\tif (distance(vertex, circle.center) <= circle.radius)\n\t\t\treturn true;\n\t}\n\n\t// Something is wrong down there\n\tassert(polygon.size() >= 3);\n\tPoint const * lineFrom = &polygon.back();\n\tfor (Point const & lineTo : polygon ) {\n\n\t\tScalar const t = projection(circle.center, *lineFrom, lineTo);\n\t\tif (t >= 0 && t <= 1) {\n\t\t\tPoint const projectedCenter = *lineFrom + t*(lineTo - *lineFrom);\n\t\t\tif (size(projectedCenter - circle.center) <= circle.radius)\n\t\t\t\t\treturn true;\n\t\t}\n\t\tlineFrom = &lineTo;\n\t}\n\n\treturn false;\n}\n\nbool collision(Circle const &circle, Polygon const &polygon) {\n\treturn collision(polygon, circle);\n}\n\nnamespace {\n\ntemplate < typename Object1 >\nclass CollisionVisitor1 : public boost::static_visitor<bool>{\n\tObject1 const & object1;\npublic:\n\texplicit CollisionVisitor1(Object1 const & object1) :\n\t\tobject1(object1) {\n\t}\n\n\ttemplate < typename Object2 >\n\tbool operator()(Object2 const & object2) {\n\t\treturn collision(object1, object2);\n\t}\n};\n\n}\n\nbool collision(Polygon const &polygon, Object2D const &object) {\n\tCollisionVisitor1<Polygon> visitor{polygon};\n\treturn boost::apply_visitor(visitor, object);\n}\n\nbool collision(Circle const &circle, Object2D const &object) {\n\tCollisionVisitor1<Circle> visitor{circle};\n\treturn boost::apply_visitor(visitor, object);\n}\n\nnamespace {\nclass CollisionVisitor2 : public boost::static_visitor<bool>{\n\tObject2D const & object1;\npublic:\n\texplicit CollisionVisitor2(Object2D const & object1) :\n\t\tobject1(object1) {\n\t}\n\n\ttemplate < typename Object2 >\n\tbool operator()(Object2 const & object2) {\n\t\tCollisionVisitor1<Object2> visitor{object2};\n\t\treturn boost::apply_visitor(visitor, object1);\n\t}\n};\n}\n\nbool collision(Object2D const &object1, Object2D const &object2) {\n\tCollisionVisitor2 visitor{object1};\n\treturn boost::apply_visitor(visitor, object2);\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "8588205286ef05478b40afbb80b4f2ebc081b89e", "size": 3537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/common/geometry/collision.cpp", "max_stars_repo_name": "h0nzZik/toogashada", "max_stars_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/common/geometry/collision.cpp", "max_issues_repo_name": "h0nzZik/toogashada", "max_issues_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-06-10T11:02:58.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-10T11:02:58.000Z", "max_forks_repo_path": "source/common/geometry/collision.cpp", "max_forks_repo_name": "h0nzZik/toogashada", "max_forks_repo_head_hexsha": "da24b08b2701b0d6534d19add20383cd7b5ed185", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7382550336, "max_line_length": 120, "alphanum_fraction": 0.711620017, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.5501525964811065}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include <Eigen/Dense>\n#include <atomic>\n\nstd::atomic_size_t Ncalls(0);\n\nusing CEGO::EArray;\n\n/**\n# Sadus, https://doi.org/10.1063/1.5041320, erratum: missing exponent of m\nn is the repulsive exponent (the 12 of 12-6 LJ)\nm is the attractive exponent (the 6 of 12-6 LJ)\n*/\ntemplate <typename T>\nauto B2_LennardJones(T Tstar, double n, double m){\n    auto F = [&](auto y) {\n        auto the_sum = 0.0;\n        for (auto i = 0; i < 200; ++i) {\n            auto my_factorial = [](auto k) { return tgamma(k + 1); };\n            the_sum += tgamma((i * m - 3.0) / n) / my_factorial(i) * pow(y, i);\n        }\n        return pow(y, 3.0/(n - m)) * (tgamma((n - 3.0) / n) - 3.0/n*the_sum);\n    };\n    auto yn = pow(n/(n-m), n)*pow((n-m)/m,m)*pow(Tstar, -(n-m)); // y**n, Eq. 9\n    auto y = pow(yn, 1.0/n);\n    return 2*EIGEN_PI/3*F(y);\n}\n\nclass FitClass {\npublic:\n    EArray<double> m_T, B2, m_LHS, m_x;\n    FitClass(const std::size_t Npts)\n    {\n        double Tmin = 0.1, Tmax = 10000;\n        m_T = EArray<double>::LinSpaced(Npts, log10(Tmin), log10(Tmax)).exp();\n        B2.resize(m_T.size());\n        for (auto i = 0; i < m_T.size(); ++i) {\n            B2(i) = B2_LennardJones(m_T(i), 12, 6);\n        }\n        // Set variables for fitting\n        m_LHS = B2;\n        m_x = 1/m_T;\n    }\n    template <typename TYPE> \n    auto eval_RHS(const EArray<double>& x, const EArray<TYPE> &c) \n    {\n        std::decay_t<decltype(x)> val(x.size()); val.setZero();\n        for (auto i = 0; i < c.size(); i += 2) {\n            double a = c[i];\n            double e = c[i + 1];\n            val += a*x.pow(e);\n        }\n        return val.eval();\n    }\n    template <typename TYPE> TYPE objective(const EArray<TYPE>& c) {\n        return ((eval_RHS(m_x, c) - m_LHS)).square().sum();\n    }\n    template <typename TYPE> EArray<TYPE> abs_rel_deviations(const EArray<TYPE>& c) {\n        return (eval_RHS(m_x, c) - m_LHS).eval();\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const auto &c = dynamic_cast<const CEGO::NumericalIndividual<CEGO::numberish>*>(pind)->get_coeff_array<CEGO::numberish>();\n        return objective(c);\n    }\n};\n\nint do_one()\n{\n    //std::srand((unsigned int)time(0));\n    std::size_t Nterms = 3;\n\n    //EArray<CEGO::numberish> c1(3); c1 << 1.0, 2, 3;\n    //EArray<CEGO::numberish> c2(3); c2 << 2.0, 3, 4;\n    //EArray<CEGO::numberish> c3(3); c3 << 3.0, 4, 5;\n    //auto oo = (c1 - c2).eval();\n    //auto o2 = (c3 - c2).eval();\n    //auto o3 = (o2*0.7).eval();\n\n    // Construct the bounds\n    std::vector<CEGO::Bound> bounds;\n    for (auto i = 0; i < Nterms; ++i) {\n        bounds.push_back(CEGO::Bound(std::make_pair(-1000.0, 1000.0)));\n        bounds.push_back(CEGO::Bound(std::make_pair(0.0, 10.0))); \n    }    \n    std::size_t Npts = 100;\n    FitClass rp(Npts);\n   \n    auto Ncalls = 0;\n    CEGO::CostFunction<CEGO::numberish> cost_wrapper = [&rp](const CEGO::AbstractIndividual*pind) {return rp.objective(pind); };\n    auto Ntotal_individuals = 1000;\n    auto Nlayers = 7;\n    auto layers = CEGO::Layers<CEGO::numberish>(cost_wrapper, bounds.size(), Ntotal_individuals/Nlayers, Nlayers, 3);\n    layers.parallel = false;\n    layers.parallel_threads = 6;\n    layers.set_bounds(bounds);\n    layers.set_generation_mode(CEGO::GenerationOptions::LHS);\n    layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution_best1bin);\n    auto f = [&rp](const CEGO::EArray<double>& c) {return rp.objective<double>(c); };\n    //auto f2 = [&rp](const CEGO::EArray<std::complex< double >>& c) {return rp.objective<std::complex<double>>(c); };\n    //layers.add_gradient(f, f2);\n\n    auto flags = layers.get_evolver_flags();\n    flags[\"Nelite\"] = 1;\n    flags[\"Fmin\"] = 0.1;\n    flags[\"Fmax\"] = 1.1;\n    flags[\"CR\"] = 0.9;\n    layers.set_evolver_flags(flags);\n\n    std::vector<double> best_costs; \n    const double VTR = 2e-4;\n    auto startTime = std::chrono::system_clock::now();\n    bool success = false;\n    for (auto counter = 0; counter < 15000; ++counter) {\n        layers.do_generation();\n\n        /*if (counter % 1000 == 0) {\n            layers.gradient_minimizer();\n        }*/\n        \n        auto [best_cost, best_coeffs] = layers.get_best();\n        if (counter % 50 == 0) {\n            std::cout << counter << \": best: \" << best_cost << std::endl;\n            //std::cout << counter << \": best coeffs: \" << c << \"||\" << std::endl;\n            //std::cout << counter << \": obj again: \" << rp.objective(c) << \"||\" << std::endl;\n        }\n        if (best_cost < VTR) { success = true;  break; }\n    }\n    auto best_layer = layers.get_best();\n    auto best_coeffs = std::get<1>(best_layer);\n    //std::cout << rp.abs_rel_deviations(best_coeffs) << std::endl;\n    auto endTime = std::chrono::system_clock::now();\n    double elap = std::chrono::duration<double>(endTime - startTime).count();\n    std::cout << \"run:\" << elap << \" s\\n\";\n    std::cout << \"NFE:\" << Ncalls << std::endl;\n    return success;\n}\n\nint main() {\n    int N = (CEGO::is_CI() ? 3 : 100);\n    int good = 0;\n    for (auto i = 0; i < N; ++i) {\n        good += do_one();\n    }\n    std::cout << \"success:\" << good << \"/\" << N << std::endl;\n}", "meta": {"hexsha": "eb86225f42678328ec23519cb4672edf8809f027", "size": 5169, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/fit_LennardJones_virial.cxx", "max_stars_repo_name": "usnistgov/CEGO", "max_stars_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/fit_LennardJones_virial.cxx", "max_issues_repo_name": "usnistgov/CEGO", "max_issues_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/fit_LennardJones_virial.cxx", "max_forks_repo_name": "usnistgov/CEGO", "max_forks_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 35.6482758621, "max_line_length": 130, "alphanum_fraction": 0.5649061714, "num_tokens": 1685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.5501525798638566}}
{"text": "#include \"discretization.hpp\"\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"eigenIntegration.hpp\"\n#include <eigen3/unsupported/Eigen/src/MatrixFunctions/MatrixExponential.h>\n\nvoid eulerLinearDiscretization(Model &model,\n                               double ts,\n                               const Model::state_vector_t &x_eq,\n                               const Model::input_vector_t &u_eq,\n                               Model::state_matrix_t &A,\n                               Model::control_matrix_t &B)\n{\n    Model::state_matrix_t A_c;\n    Model::control_matrix_t B_c;\n    model.computeJacobians(x_eq, u_eq, A_c, B_c);\n\n    A = Model::state_matrix_t::Identity() + ts * A_c;\n    B = ts * B_c;\n}\n\nvoid exactLinearDiscretization(Model &model,\n                               double ts,\n                               const Model::state_vector_t &x_eq,\n                               const Model::input_vector_t &u_eq,\n                               Model::state_matrix_t &A,\n                               Model::control_matrix_t &B,\n                               Model::state_vector_t &z)\n{\n    Model::state_matrix_t A_c;\n    Model::control_matrix_t B_c;\n    Model::state_vector_t f;\n    model.computeJacobians(x_eq, u_eq, A_c, B_c);\n    model.computef(x_eq, u_eq, f);\n\n    Eigen::MatrixXd E;\n    E.resize(Model::state_dim + Model::input_dim, Model::state_dim + Model::input_dim);\n    E.setZero();\n    E.topLeftCorner(Model::state_dim, Model::state_dim) << A_c;\n    E.topRightCorner(Model::state_dim, Model::input_dim) << B_c;\n    Eigen::MatrixXd expE = (E * ts).exp();\n\n    A = expE.topLeftCorner(Model::state_dim, Model::state_dim);\n    B = expE.topRightCorner(Model::state_dim, Model::input_dim);\n    z = f - A * x_eq - B * u_eq;\n}\n\nclass ODEMultipleShootingVariableTime\n{\nprivate:\n    Model::input_vector_t u_t0, u_t1;\n    double T, dt;\n    Model &model;\n\npublic:\n    using ode_matrix_t = Eigen::Matrix<double, Model::state_dim, 1 + Model::state_dim + 2 * Model::input_dim + 2>;\n\n    ODEMultipleShootingVariableTime(\n        const Model::input_vector_t &u_t0,\n        const Model::input_vector_t &u_t1,\n        const double &T,\n        double dt,\n        Model &model)\n        : u_t0(u_t0), u_t1(u_t1), T(T), dt(dt), model(model) {}\n\n    void 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        const Model::input_vector_t u = u_t0 + t / dt * (u_t1 - u_t0);\n\n        Model::state_vector_t f;\n        Model::state_matrix_t A_bar;\n        Model::control_matrix_t B_bar;\n        model.computef(x, u, f);\n        model.computeJacobians(x, u, A_bar, B_bar);\n        A_bar *= T;\n        B_bar *= T;\n\n        const Model::state_matrix_t Phi_A_xi = V.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        dVdt.block<Model::state_dim, 1>(0, cols) = T * f;\n        cols += 1;\n\n        // A_bar\n        dVdt.block<Model::state_dim, Model::state_dim>(0, cols) = A_bar * Phi_A_xi;\n        cols += Model::state_dim;\n\n        // B_bar\n        const double alpha = (dt - t) / dt;\n        dVdt.block<Model::state_dim, Model::input_dim>(0, cols) = Phi_A_xi_inverse * B_bar * alpha;\n        cols += Model::input_dim;\n\n        // C_bar\n        const double beta = t / dt;\n        dVdt.block<Model::state_dim, Model::input_dim>(0, cols) = Phi_A_xi_inverse * B_bar * beta;\n        cols += Model::input_dim;\n\n        // S_bar\n        dVdt.block<Model::state_dim, 1>(0, cols) = Phi_A_xi_inverse * f;\n        cols += 1;\n\n        // z_bar\n        dVdt.block<Model::state_dim, 1>(0, cols) = Phi_A_xi_inverse * (-A_bar * x - B_bar * u);\n\n        assert(cols + 1 == size_t(dVdt.cols()));\n    }\n};\n\nvoid multipleShootingVariableTime(\n    Model &model,\n    double T,\n    const Eigen::MatrixXd &X,\n    const Eigen::MatrixXd &U,\n    Model::state_matrix_v_t &A_bar,\n    Model::control_matrix_v_t &B_bar,\n    Model::control_matrix_v_t &C_bar,\n    Model::state_vector_v_t &S_bar,\n    Model::state_vector_v_t &z_bar)\n{\n    const size_t K = X.cols();\n\n    const double dt = 1. / double(K - 1);\n    using namespace boost::numeric::odeint;\n    runge_kutta4<ODEMultipleShootingVariableTime::ode_matrix_t, double, ODEMultipleShootingVariableTime::ode_matrix_t, double, vector_space_algebra> stepper;\n\n    for (size_t k = 0; k < K - 1; k++)\n    {\n        ODEMultipleShootingVariableTime::ode_matrix_t V;\n        V.setZero();\n        V.col(0) = X.col(k);\n        V.block<Model::state_dim, Model::state_dim>(0, 1).setIdentity();\n\n        ODEMultipleShootingVariableTime odeMultipleShooting(U.col(k), U.col(k + 1), T, dt, model);\n\n        integrate_adaptive(stepper, odeMultipleShooting, V, 0., dt, dt / 4.);\n\n        size_t cols = 1;\n\n        A_bar[k] = V.block<Model::state_dim, Model::state_dim>(0, cols);\n        cols += Model::state_dim;\n\n        B_bar[k] = A_bar[k] * V.block<Model::state_dim, Model::input_dim>(0, cols);\n        cols += Model::input_dim;\n\n        C_bar[k] = A_bar[k] * V.block<Model::state_dim, Model::input_dim>(0, cols);\n        cols += Model::input_dim;\n\n        S_bar[k] = A_bar[k] * V.block<Model::state_dim, 1>(0, cols);\n        cols += 1;\n\n        z_bar[k] = A_bar[k] * V.block<Model::state_dim, 1>(0, cols);\n    }\n}\n\nclass ODEMultipleShooting\n{\nprivate:\n    Model::input_vector_t u_t0, u_t1;\n    double dt;\n    Model &model;\n\npublic:\n    using ode_matrix_t = Eigen::Matrix<double, Model::state_dim, 1 + Model::state_dim + 2 * Model::input_dim + 1>;\n\n    ODEMultipleShooting(\n        const Model::input_vector_t &u_t0,\n        const Model::input_vector_t &u_t1,\n        double dt,\n        Model &model)\n        : u_t0(u_t0), u_t1(u_t1), dt(dt), model(model) {}\n\n    void 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        const Model::input_vector_t u = u_t0 + t / dt * (u_t1 - u_t0);\n\n        Model::state_vector_t f;\n        Model::state_matrix_t A_bar;\n        Model::control_matrix_t B_bar;\n        model.computef(x, u, f);\n        model.computeJacobians(x, u, A_bar, B_bar);\n\n        const Model::state_matrix_t Phi_A_xi = V.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        dVdt.block<Model::state_dim, 1>(0, cols) = f;\n        cols += 1;\n\n        // A_bar\n        dVdt.block<Model::state_dim, Model::state_dim>(0, cols) = A_bar * Phi_A_xi;\n        cols += Model::state_dim;\n\n        // B_bar\n        const double alpha = (dt - t) / dt;\n        dVdt.block<Model::state_dim, Model::input_dim>(0, cols) = Phi_A_xi_inverse * B_bar * alpha;\n        cols += Model::input_dim;\n\n        // C_bar\n        const double beta = t / dt;\n        dVdt.block<Model::state_dim, Model::input_dim>(0, cols) = Phi_A_xi_inverse * B_bar * beta;\n        cols += Model::input_dim;\n\n        // z_bar\n        dVdt.block<Model::state_dim, 1>(0, cols) = Phi_A_xi_inverse * (f - A_bar * x - B_bar * u);\n\n        assert(cols + 1 == size_t(dVdt.cols()));\n    }\n};\n\nvoid multipleShooting(\n    Model &model,\n    double T,\n    const Eigen::MatrixXd &X,\n    const Eigen::MatrixXd &U,\n    Model::state_matrix_v_t &A_bar,\n    Model::control_matrix_v_t &B_bar,\n    Model::control_matrix_v_t &C_bar,\n    Model::state_vector_v_t &z_bar)\n{\n    const size_t K = X.cols();\n\n    const double dt = T / double(K - 1);\n    using namespace boost::numeric::odeint;\n    runge_kutta4<ODEMultipleShooting::ode_matrix_t, double, ODEMultipleShooting::ode_matrix_t, double, vector_space_algebra> stepper;\n\n    for (size_t k = 0; k < K - 1; k++)\n    {\n        ODEMultipleShooting::ode_matrix_t V;\n        V.setZero();\n        V.col(0) = X.col(k);\n        V.block<Model::state_dim, Model::state_dim>(0, 1).setIdentity();\n\n        ODEMultipleShooting odeMultipleShooting(U.col(k), U.col(k + 1), dt, model);\n\n        integrate_adaptive(stepper, odeMultipleShooting, V, 0., dt, dt / 4.);\n\n        size_t cols = 1;\n\n        A_bar[k] = V.block<Model::state_dim, Model::state_dim>(0, cols);\n        cols += Model::state_dim;\n\n        B_bar[k] = A_bar[k] * V.block<Model::state_dim, Model::input_dim>(0, cols);\n        cols += Model::input_dim;\n\n        C_bar[k] = A_bar[k] * V.block<Model::state_dim, Model::input_dim>(0, cols);\n        cols += Model::input_dim;\n\n        z_bar[k] = A_bar[k] * V.block<Model::state_dim, 1>(0, cols);\n    }\n}", "meta": {"hexsha": "ea6efbfe5cd8f2d0c81a2362d99b5deb046d5a41", "size": 8495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "socp_mpc/src/discretization.cpp", "max_stars_repo_name": "boyali/SCpp", "max_stars_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "socp_mpc/src/discretization.cpp", "max_issues_repo_name": "boyali/SCpp", "max_issues_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "socp_mpc/src/discretization.cpp", "max_forks_repo_name": "boyali/SCpp", "max_forks_repo_head_hexsha": "3bc49a169e7edfb0144575dfa55807df40eea58d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-18T12:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-18T12:58:00.000Z", "avg_line_length": 32.9263565891, "max_line_length": 157, "alphanum_fraction": 0.5992937022, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.5501120506560551}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\n// http://ankokudan.org/d/dl/pdf/pdf-eigennote.pdf\n\nEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> exp( Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> &output)\n{\n    std::cout << \"output.rows() = \" << output.rows() << std::endl;\n    std::cout << \"output.cols() = \" << output.cols() << std::endl;\n    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> o = output;\n    for(int i=0; i<output.cols(); i++)\n      {\n        o(0, i) = 1.0/(1.0 + exp(o(0, i)));\n      }\n    return o;\n}\n\nint main(void)\n{\n  Eigen::Matrix<float, 2,2> m1 = Eigen::Matrix<float, 2, 2>::Random(2,2);\n  Eigen::Matrix<float, 2,2> m2;\n  Eigen::Matrix<float, 2,2> m3;\n  Eigen::Matrix<float, 2, 1> v1;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> A;\n  Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> B;\n\n  m2 <<\n    1, 0,\n    1, 2;\n\n  m3 <<\n    0, 1,\n    2, 0;\n\n  v1 << 1, 4;\n\n  std::cout << \"m1 = \" << m1 << std::endl;\n  std::cout << \"m2 = \" << m2 << std::endl;\n  std::cout << \"m3 = \" << m3 << std::endl;\n  std::cout << \"m2 - m3 = \" << m2 - m3 << std::endl;\n  std::cout << \"m2 * m3 = \" << m2 * m3 << std::endl;\n  std::cout << \"v1 = \" << v1 << std::endl;\n\n  std::cout << \"m2.size() = \" << m2.size() << std::endl;\n  std::cout << \"v1.rows() = \" << v1.rows() << std::endl;\n  std::cout << \"v1.cols() = \" << v1.cols() << std::endl;\n\n  std::cout << \"v1 * m3 = \" << v1.transpose() * m3 << std::endl;\n  A = v1.transpose() * m3;\n\n  std::cout << \"v1.rows() = \" << v1.rows() << std::endl;\n  std::cout << \"v1.cols() = \" << v1.cols() << std::endl;\n  std::cout << \"A.rows() = \" << A.rows() << std::endl;\n  std::cout << \"A.cols() = \" << A.cols() << std::endl;\n\n  B = exp(A);\n\n  std::cout << \"B.rows() = \" << B.rows() << std::endl;\n  std::cout << \"B.cols() = \" << B.cols() << std::endl;\n  std::cout << \"B = \" << B << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "101a57e90b7f89f545eaea25574f19827f7b4c2b", "size": 1905, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/old/test.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/old/test.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/old/test.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": 28.4328358209, "max_line_length": 119, "alphanum_fraction": 0.5091863517, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.5501027791496762}}
{"text": "#ifndef LATTICE_BETHELATTICE_HPP\n#define LATTICE_BETHELATTICE_HPP\n\n#include <string>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n\nnamespace lattice {\n\nclass BetheLattice {\npublic:\n  static std::string name() { return \"Bethe Lattice\";}\n  BetheLattice(unsigned int LatticeSize , unsigned int NeighboringNumber) : num_stage(LatticeSize), n_adj(NeighboringNumber) {}\n  void create_table(std::vector<std::vector < int > >& table){\n    for(int stage = 0; stage < num_stage+1 ; ++stage){\n      int num_each_stage = calc_num_each_stage(stage);\n      for(int tagg = 0; tagg < num_each_stage ; ++tagg){\n        int number  = numberize(stage,tagg);\n        if(stage == num_stage){\n          for(int i = 0; i < n_adj - 1; ++i){\n            table[number][i] = number;\n          }\n        }\n        else if(stage == 0){\n          for(int i = 0; i < n_adj; ++i){\n            table[number][i] = i+1;\n            table[i+1][n_adj-1] = number;\n          }\n        }\n        else{\n          for(int i = 0; i < n_adj - 1; ++i){\n            int pair_number = numberize(stage+1, tagg*(n_adj-1)+i);\n            table[number][i] = pair_number;\n            table[pair_number][n_adj-1] = number;\n          }\n        }\n      }\n    }\n  }\n\n  int numberize(const int stage, const int tagg){// j <= std::pow(n_adj-1,i-1)* n_adj - 1\n    if(stage ==0) return 0;\n    else return BetheCalc(stage) + 1 + tagg;\n  }\n\n  int latticize(int d, const int l){ //d selects stage_number or tagg_number (0, 1) ex. 0 denotes stage, 1 denotes tagg_number\n    int stage = num_stage;\n    int tagg = 1;\n    int result = 0;\n    while(tagg != 0){\n      tagg = l % BetheCalc(stage);\n      --stage;\n      if(stage < 2) break;\n    }\n    if(stage < 2){\n      if(l == 0){\n        if(d==0) result = 0;\n        else result = 0;\n      }\n      else{\n        if(d==0)result = stage;\n        else result= l;\n      }\n    }\n   return result;\n  }\n\n  int set_num_particles(int Ns){\n    if(Ns == 0) return  1;\n    else return BetheCalc(Ns+1) + 1;\n  }\n\n  int BetheCalc(int stage ){ //N_t => 0 \n    int num_t = 0;\n    for(int k = 1 ; k <= stage-1; ++k){\n     num_t += calc_num_each_stage(k);\n    }\n    return num_t;\n  }\n\n  int calc_num_each_stage(int stage){\n    double temp;\n    double stage_t = boost::lexical_cast<double>(stage);\n    double n_adj_t = boost::lexical_cast<double>(n_adj);\n    if(stage == 0) temp = 1;\n    else temp = n_adj_t * std::pow(n_adj_t-1, stage_t-1) ;\n    return boost::lexical_cast<int>(temp);\n }\n\n  int number_adjacent() {return n_adj;} \n\nprivate:\n  unsigned int num_stage;\n  unsigned int n_adj;\n\n};//Bethe lattice end\n\n} // end namespace\n\n#endif //LATTICE_BETHELATTICE_HPP\n", "meta": {"hexsha": "153c3aa1c3ee50552bb92381a0f736ff2c5e888f", "size": 2638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lattice/bethelattice.hpp", "max_stars_repo_name": "FIshikawa/ExpressiveMonteCarlo", "max_stars_repo_head_hexsha": "d10e35f564ab1b8bdddc353c2d340647f1bc7aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/lattice/bethelattice.hpp", "max_issues_repo_name": "FIshikawa/ExpressiveMonteCarlo", "max_issues_repo_head_hexsha": "d10e35f564ab1b8bdddc353c2d340647f1bc7aa9", "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": "include/lattice/bethelattice.hpp", "max_forks_repo_name": "FIshikawa/ExpressiveMonteCarlo", "max_forks_repo_head_hexsha": "d10e35f564ab1b8bdddc353c2d340647f1bc7aa9", "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": 26.1188118812, "max_line_length": 127, "alphanum_fraction": 0.5754359363, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.550102762104002}}
{"text": "#pragma once\n\n/**\n * Reduced product of a numerical domain and the congruence domain.\n **/\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/domains/combined_domains.hpp>\n#include <crab/domains/congruences.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/support/stats.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace crab {\nnamespace domains {\n\n/*\n *  The reduce operator based on \"Static Analysis of Arithmetical\n *  Congruences\" by P. Granger published in International Journal of\n *  Computer Mathematics, 1989.\n */\ntemplate <typename Number> class interval_congruence {\npublic:\n  using interval_congruence_t = interval_congruence<Number>;\n\nprivate:\n  using interval_t = ikos::interval<Number>;\n  using congruence_t = ikos::congruence<Number>;\n  using bound_t = ikos::bound<Number>;\n\nprivate:\n  interval_t m_first;\n  congruence_t m_second;\n\nprivate:\n  interval_congruence(bool is_bottom)\n      : m_first(is_bottom ? interval_t::bottom() : interval_t::top()),\n        m_second(is_bottom ? congruence_t::bottom() : congruence_t::top()) {}\n\npublic:\n  static interval_congruence_t top() { return interval_congruence(false); }\n\n  static interval_congruence_t bottom() { return interval_congruence(true); }\n\nprivate:\n  inline Number abs(Number x) { return x < 0 ? -x : x; }\n\n  // operator % can return a negative number\n  // mod(a, b) always returns a positive number\n  inline Number mod(Number a, Number b) {\n    Number m = a % b;\n    if (m < 0)\n      return m + b;\n    else\n      return m;\n  }\n\n  // R(c,a) is the least element of c greater or equal than a\n  inline Number R(congruence_t c, Number a) {\n    Number m = c.get_modulo();\n    Number p = c.get_remainder();\n    return a + mod(p - a, abs(m));\n  }\n\n  // L(c,a) is the greatest element of c smaller or equal than a\n  inline Number L(congruence_t c, Number a) {\n    Number m = c.get_modulo();\n    Number p = c.get_remainder();\n    return a - mod(a - p, abs(m));\n  }\n\npublic:\n  interval_congruence(Number n)\n      : m_first(interval_t(n)), m_second(congruence_t(n)) {}\n\n  interval_congruence(interval_t i, congruence_t c) : m_first(i), m_second(c) {\n    reduce();\n  }\n\n  interval_congruence(interval_t i)\n      : m_first(i), m_second(congruence_t::top()) {\n    reduce();\n  }\n\n  interval_congruence(congruence_t c)\n      : m_first(interval_t::top()), m_second(c) {\n    reduce();\n  }\n\n  interval_congruence(const interval_congruence &other)\n      : m_first(other.m_first), m_second(other.m_second) {}\n\n  interval_congruence(interval_congruence &&other)\n      : m_first(std::move(other.m_first)), m_second(std::move(other.m_second)) {\n  }\n\n  interval_congruence_t &operator=(const interval_congruence_t &other) {\n    if (this != &other) {\n      m_first = other.m_first;\n      m_second = other.m_second;\n    }\n    return *this;\n  }\n\n  interval_congruence_t &operator=(interval_congruence_t &&other) {\n    if (this != &other) {\n      m_first = std::move(other.m_first);\n      m_second = std::move(other.m_second);\n    }\n    return *this;\n  }\n\n  bool is_bottom() { return m_first.is_bottom() || m_second.is_bottom(); }\n\n  bool is_top() { return m_first.is_top() && m_second.is_top(); }\n\n  interval_t &first() { return m_first; }\n  const interval_t &first() const { return m_first; }\n\n  congruence_t &second() { return m_second; }\n  const congruence_t &second() const { return m_second; }\n\n  /*\n     Let (i,c) be a pair of interval and congruence these are the\n     main rules described by Granger:\n\n     if (c.is_bottom() || i.is_bottom()) (bottom(), bottom());\n     if (c = 0Z+a and a \\notin i)        (bottom(), bottom());\n     if (c = 0Z+a)                       ([a,a]   , c);\n     if (i=[a,b] and R(c,a) > L(c,b))    (bottom(), bottom());\n     if (i=[a,b])                        ([R(c,a), L(c,b)], c);\n     if (i=[a,+oo])                      ([R(c,a), +oo], c);\n     if (i=[-oo,b])                      ([-oo, L(c,b)], c);\n     otherwise                           (i,c)\n   */\n\n  void reduce() {\n    interval_t &i = first();\n    congruence_t &c = second();\n\n    if (i.is_bottom() || c.is_bottom()) {\n      i = interval_t::bottom();\n      c = congruence_t::bottom();\n    }\n\n    // congruence is top and interval is a singleton\n    if (c.is_top()) {\n      boost::optional<Number> n = i.singleton();\n      if (n) {\n        c = congruence_t(*n);\n      }\n      return;\n    }\n\n    Number modulo = c.get_modulo();\n    if (modulo == 0) {\n      // congruence is a singleton so we refine the interval\n      interval_t a(c.get_remainder());\n      if (!(a <= i)) {\n        i = interval_t::bottom();\n        c = congruence_t::bottom();\n      } else {\n        i = a;\n      }\n    } else {\n      // refine lower and upper bounds of the interval using\n      // congruences\n      bound_t lb = i.lb();\n      bound_t ub = i.ub();\n\n      if (lb.is_finite() && ub.is_finite()) {\n        Number x = R(c, *(lb.number()));\n        Number y = L(c, *(ub.number()));\n        if (x > y) {\n          i = interval_t::bottom();\n          c = congruence_t::bottom();\n        } else if (x == y) {\n          i = interval_t(x);\n          c = congruence_t(x);\n        } else {\n          i = interval_t(bound_t(x), bound_t(y));\n        }\n      } else if (lb.is_finite()) {\n        Number x = R(c, *(lb.number()));\n        i = interval_t(bound_t(x), bound_t::plus_infinity());\n      } else if (ub.is_finite()) {\n        Number y = L(c, *(ub.number()));\n        i = interval_t(bound_t::minus_infinity(), bound_t(y));\n      } else {\n        // interval is top\n      }\n    }\n  }\n\n  void write(crab_os &o) const {\n    o << \"(\" << m_first << \", \" << m_second << \")\";\n  }\n\npublic:\n  interval_congruence_t operator+(interval_congruence_t x) {\n    return interval_congruence_t(m_first.operator+(x.first()),\n                                 m_second.operator+(x.second()));\n  }\n\n  interval_congruence_t operator-(interval_congruence_t x) {\n    return interval_congruence_t(m_first.operator-(x.first()),\n                                 m_second.operator-(x.second()));\n  }\n\n  interval_congruence_t operator*(interval_congruence_t x) {\n    return interval_congruence_t(m_first.operator*(x.first()),\n                                 m_second.operator*(x.second()));\n  }\n\n  interval_congruence_t operator/(interval_congruence_t x) {\n    return interval_congruence_t(m_first.operator/(x.first()),\n                                 m_second.operator/(x.second()));\n  }\n\n  interval_congruence_t operator|(interval_congruence_t other) {\n    return interval_congruence_t(m_first | other.m_first,\n                                 m_second | other.m_second);\n  }\n\n  interval_congruence_t operator&(interval_congruence_t other) {\n    return interval_congruence_t(m_first & other.m_first,\n                                 m_second & other.m_second);\n  }\n\npublic:\n  // division and remainder operations\n\n  interval_congruence_t SDiv(interval_congruence_t x) {\n    return interval_congruence_t(m_first.SDiv(x.first()),\n                                 m_second.SDiv(x.second()));\n  }\n\n  interval_congruence_t UDiv(interval_congruence_t x) {\n    return interval_congruence_t(m_first.UDiv(x.first()),\n                                 m_second.UDiv(x.second()));\n  }\n\n  interval_congruence_t SRem(interval_congruence_t x) {\n    return interval_congruence_t(m_first.SRem(x.first()),\n                                 m_second.SRem(x.second()));\n  }\n\n  interval_congruence_t URem(interval_congruence_t x) {\n    return interval_congruence_t(m_first.URem(x.first()),\n                                 m_second.URem(x.second()));\n  }\n\n  // bitwise operations\n\n  interval_congruence_t Trunc(unsigned width) {\n    return interval_congruence_t(m_first.Trunc(width), m_second.Trunc(width));\n  }\n\n  interval_congruence_t ZExt(unsigned width) {\n    return interval_congruence_t(m_first.ZExt(width), m_second.ZExt(width));\n  }\n\n  interval_congruence_t SExt(unsigned width) {\n    return interval_congruence_t(m_first.SExt(width), m_second.SExt(width));\n  }\n\n  interval_congruence_t And(interval_congruence_t x) {\n    return interval_congruence_t(m_first.And(x.first()),\n                                 m_second.And(x.second()));\n  }\n\n  interval_congruence_t Or(interval_congruence_t x) {\n    return interval_congruence_t(m_first.Or(x.first()),\n                                 m_second.Or(x.second()));\n  }\n\n  interval_congruence_t Xor(interval_congruence_t x) {\n    return interval_congruence_t(m_first.Xor(x.first()),\n                                 m_second.Xor(x.second()));\n  }\n\n  interval_congruence_t Shl(interval_congruence_t x) {\n    return interval_congruence_t(m_first.Shl(x.first()),\n                                 m_second.Shl(x.second()));\n  }\n\n  interval_congruence_t LShr(interval_congruence_t x) {\n    return interval_congruence_t(m_first.LShr(x.first()),\n                                 m_second.LShr(x.second()));\n  }\n\n  interval_congruence_t AShr(interval_congruence_t x) {\n    return interval_congruence_t(m_first.AShr(x.first()),\n                                 m_second.AShr(x.second()));\n  }\n};\n\ntemplate <typename Number>\ninline crab::crab_os &operator<<(crab::crab_os &o,\n                                 const interval_congruence<Number> &v) {\n  v.write(o);\n  return o;\n}\n\n// Reduced product of a numerical domain with interval x congruences.\ntemplate <typename NumAbsDom>\nclass numerical_congruence_domain final\n    : public abstract_domain_api<numerical_congruence_domain<NumAbsDom>> {\n\n  using rnc_domain_t = numerical_congruence_domain<NumAbsDom>;\n  using abstract_domain_t = abstract_domain_api<rnc_domain_t>;\n\npublic:\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;  \n  using number_t = typename NumAbsDom::number_t;\n  using varname_t = typename NumAbsDom::varname_t;\n\n  using congruence_domain_t = ikos::congruence_domain<number_t, varname_t>;\n  using interval_congruence_t = interval_congruence<number_t>;\n\nprivate:\n  using reduced_domain_product2_t =\n      reduced_domain_product2<number_t, varname_t, NumAbsDom, congruence_domain_t>;\n\n  reduced_domain_product2_t m_product;\n\n  numerical_congruence_domain(const reduced_domain_product2_t &product)\n      : m_product(product) {}\n\n  void reduce_variable(const variable_t &v) {\n    crab::CrabStats::count(domain_name() + \".count.reduce\");\n    crab::ScopedCrabStats __st__(domain_name() + \".reduce\");\n\n    if (is_bottom()) {\n      return;\n    }\n\n    auto i = m_product.first()[v]; // project on intervals\n    auto c = m_product.second().to_congruence(v);\n    interval_congruence_t val(i, c);\n\n    if (val.is_bottom()) {\n      set_to_bottom();\n    } else {\n      if (val.first() != i) {\n        // FIXME: method set is not part of the abstract_domain API so\n        // it might not compile.\n        m_product.first().set(v, val.first());\n      }\n\n      if (val.second() != c) {\n        // FIXME: method set is not part of the abstract_domain API so\n        // it might not compile.\n        m_product.second().set(v, val.second());\n      }\n    }\n  }\n\npublic:\n  rnc_domain_t make_top() const override {\n    reduced_domain_product2_t dom_prod;\n    return rnc_domain_t(dom_prod.make_top());\n  }\n\n  rnc_domain_t make_bottom() const override {\n    reduced_domain_product2_t dom_prod;\n    return rnc_domain_t(dom_prod.make_bottom());\n  }\n\n  void set_to_top() override {\n    reduced_domain_product2_t dom_prod;\n    rnc_domain_t abs(dom_prod.make_top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    reduced_domain_product2_t dom_prod;\n    rnc_domain_t abs(dom_prod.make_bottom());\n    std::swap(*this, abs);\n  }\n\n  numerical_congruence_domain() : m_product() {}\n\n  numerical_congruence_domain(const rnc_domain_t &other)\n      : m_product(other.m_product) {}\n\n  rnc_domain_t &operator=(const rnc_domain_t &other) {\n    if (this != &other)\n      m_product = other.m_product;\n\n    return *this;\n  }\n\n  bool is_bottom() const override { return m_product.is_bottom(); }\n\n  bool is_top() const override { return m_product.is_top(); }\n\n  bool operator<=(const rnc_domain_t &other) const override {\n    return m_product <= other.m_product;\n  }\n\n  bool operator==(const rnc_domain_t &other) const {\n    return m_product == other.m_product;\n  }\n\n  void operator|=(const rnc_domain_t &other) override {\n    m_product |= other.m_product;\n  }\n\n  rnc_domain_t operator|(const rnc_domain_t &other) const override {\n    return rnc_domain_t(m_product | other.m_product);\n  }\n\n  rnc_domain_t operator&(const rnc_domain_t &other) const override {\n    return rnc_domain_t(m_product & other.m_product);\n  }\n\n  rnc_domain_t operator||(const rnc_domain_t &other) const override {\n    return rnc_domain_t(m_product || other.m_product);\n  }\n\n  rnc_domain_t widening_thresholds(\n      const rnc_domain_t &other,\n      const iterators::thresholds<number_t> &ts) const override {\n    return rnc_domain_t(m_product.widening_thresholds(other.m_product, ts));\n  }\n\n  rnc_domain_t operator&&(const rnc_domain_t &other) const override {\n    return rnc_domain_t(m_product && other.m_product);\n  }\n\n  // pre: x is already reduced\n  void set(const variable_t &v, interval_congruence_t x) {\n    m_product.first().set(v, x.first());\n    m_product.second().set(v, x.second());\n  }\n\n  interval_congruence_t get(const variable_t &v) {\n    return interval_congruence_t(m_product.first()[v],\n                                 m_product.second().to_congruence(v));\n  }\n\n  interval_t operator[](const variable_t &v) override {\n    interval_congruence_t x = get(v);\n    return x.first();\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    m_product += csts;\n\n    if (!is_bottom()) {\n      for (auto const &cst : csts) {\n        for (auto const &v : cst.variables()) {\n          reduce_variable(v);\n          if (is_bottom()) {\n            return;\n          }\n        }\n      }\n    }\n  }\n\n  void operator-=(const variable_t &v) override { m_product -= v; }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    m_product.assign(x, e);\n    reduce_variable(x);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.apply(op, x, y, z);\n    reduce_variable(x);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    m_product.apply(op, x, y, k);\n    reduce_variable(x);\n  }\n\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const rnc_domain_t &invariant) override {\n    m_product.backward_assign(x, e, invariant.m_product);\n    // reduce the variables in the right-hand side\n    for (auto const &v : e.variables())\n      reduce_variable(v);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t k,\n                      const rnc_domain_t &invariant) override {\n    m_product.backward_apply(op, x, y, k, invariant.m_product);\n    // reduce the variables in the right-hand side\n    reduce_variable(y);\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const rnc_domain_t &invariant) override {\n    m_product.backward_apply(op, x, y, z, invariant.m_product);\n    // reduce the variables in the right-hand side\n    reduce_variable(y);\n    reduce_variable(z);\n  }\n\n  // cast operators\n\n  void apply(int_conv_operation_t op, const variable_t &dst,\n             const variable_t &src) override {\n    m_product.apply(op, dst, src);\n    reduce_variable(dst);\n  }\n\n  // bitwise operators\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.apply(op, x, y, z);\n    reduce_variable(x);\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    m_product.apply(op, x, y, k);\n    reduce_variable(x);\n  }\n\n  void select(const variable_t &lhs, const linear_constraint_t &cond,\n              const linear_expression_t &e1,\n              const linear_expression_t &e2) override {\n    m_product.select(lhs, cond, e1, e2);\n    reduce_variable(lhs);\n  }\n\n  /// numerical_congruence_domain implements only standard abstract\n  /// operations of a numerical domain so it is intended to be used as\n  /// a leaf domain in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(rnc_domain_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(rnc_domain_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(rnc_domain_t)\n\n  void forget(const variable_vector_t &variables) override {\n    m_product.forget(variables);\n  }\n\n  void project(const variable_vector_t &variables) override {\n    m_product.project(variables);\n  }\n\n  void expand(const variable_t &var, const variable_t &new_var) override {\n    m_product.expand(var, new_var);\n  }\n\n  void normalize() override { m_product.normalize(); }\n\n  void minimize() override { m_product.minimize(); }\n\n  void write(crab_os &o) const override { m_product.write(o); }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    return m_product.to_linear_constraint_system();\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    return m_product.to_disjunctive_linear_constraint_system();\n  }\n\n  std::string domain_name() const override { return m_product.domain_name(); }\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    m_product.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    m_product.intrinsic(name, inputs, outputs);\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 rnc_domain_t &invariant) override {\n    m_product.backward_intrinsic(name, inputs, outputs, invariant.m_product);\n  }\n  /* end intrinsics operations */\n\n}; // class numerical_congruence_domain\n\ntemplate <typename NumAbsDom>\nstruct abstract_domain_traits<numerical_congruence_domain<NumAbsDom>> {\n  using number_t = typename NumAbsDom::number_t;\n  using varname_t = typename NumAbsDom::varname_t;\n};\n\n} // end namespace domains\n} // namespace crab\n", "meta": {"hexsha": "860dc0c0e859738180492379cb894c5e7abcee1a", "size": 18996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/combined_congruences.hpp", "max_stars_repo_name": "seahorn/crab", "max_stars_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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/combined_congruences.hpp", "max_issues_repo_name": "seahorn/crab", "max_issues_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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/combined_congruences.hpp", "max_forks_repo_name": "seahorn/crab", "max_forks_repo_head_hexsha": "82e3d9c94a3b112d4db344e34ae9f789b51d0ec0", "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": 30.9885807504, "max_line_length": 83, "alphanum_fraction": 0.6560854917, "num_tokens": 4772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.6654105587468141, "lm_q1q2_score": 0.5501027596560936}}
{"text": "#include \"multivariate_guassian.hpp\"\n\n#include \"multinomial.hpp\"\n#include \"utils.hpp\"\n\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace FilterModel {\n\nMultivariateGuassian::MultivariateGuassian(const std::vector<double> mean_in,\n                                           const std::vector<std::vector<double>> covariance_in)\n    : mean(mean_in.size()), covariance(covariance_in.size(), covariance_in.size()) {\n    for (int i = 0; i < mean_in.size(); ++i) {\n        mean[i] = mean_in.at(i);\n    }\n\n    for (int i = 0; i < covariance_in.size(); ++i) {\n        const std::vector<double>& row = covariance_in.at(i);\n        for (int j = 0; j < row.size(); ++j) {\n            covariance(i, j) = row.at(j);\n            covariance(j, i) = row.at(j);\n        }\n    }\n\n    covariance_inverse = covariance.inverse();\n};\n\nMultivariateGuassian MultivariateGuassian::from_multinomial(int n, const std::vector<double>& p) {\n    std::vector<double> mean;\n    for (double pi : p) {\n        mean.push_back(n * pi);\n    }\n\n    std::vector<std::vector<double>> covariance;\n    for (int row = 0; row < p.size(); ++row) {\n        std::vector<double> covariance_row;\n        for (int column = 0; column < row; ++column) {\n            covariance_row.push_back(-n * p.at(row) * p.at(column));\n        }\n        covariance_row.push_back(n * p.at(row) * (1.0 - p.at(row)));\n        covariance.push_back(covariance_row);\n    }\n\n    MultivariateGuassian out(mean, covariance);\n\n    return out;\n}\n\nMultivariateGuassian MultivariateGuassian::from_multinomial(const Multinomial& m) {\n    std::vector<double> new_p(m.p);\n    new_p.pop_back();\n    return MultivariateGuassian::from_multinomial(m.n, new_p);\n}\n\ndouble MultivariateGuassian::density(std::vector<double> point) const {\n    if (point.size() != mean.size()) {\n        BOOST_LOG_TRIVIAL(fatal) << \"MultivariateGuassian density input must have the same number \"\n                                    \"of dimensions as the distribution.\";\n        assert(false);\n    }\n\n    // TODO(joschnei): There has to be a better way to do this copy.\n    Eigen::VectorXd x(point.size());\n    for (int i = 0; i < point.size(); ++i) {\n        x[i] = point.at(i);\n    }\n\n    Eigen::VectorXd diff = (x - mean).eval();\n    Eigen::RowVectorXd mult1 = (diff.transpose() * covariance_inverse).eval();\n    double mult2 = (mult1 * diff).eval()(0, 0);\n    double det = covariance.determinant();\n    double val = std::exp(-1.0 / 2.0 * mult2) / std::sqrt(std::pow(2 * M_PI, mean.size()) * det);\n    return val;\n}\n\nvoid MultivariateGuassian::shift_hyperplanes(std::vector<std::vector<double>>& hyperplanes) {\n    for (std::vector<double>& hyperplane : hyperplanes) {\n        double constant = hyperplane.back();\n        for (int i = 0; i < hyperplane.size() - 1; ++i) {\n            constant -= hyperplane.at(i) * mean[i];\n        }\n        hyperplane[hyperplane.size() - 1] = constant;\n    }\n}\n\nstd::vector<std::vector<double>> MultivariateGuassian::get_covariance() const {\n    std::vector<std::vector<double>> out;\n    for (int row_index = 0; row_index < covariance.rows(); ++row_index) {\n        std::vector<double> row;\n        for (int column_index = 0; column_index < covariance.cols(); ++column_index) {\n            row.push_back(covariance(row_index, column_index));\n        }\n        out.push_back(row);\n    }\n    return out;\n}\n\nstd::vector<double> MultivariateGuassian::get_mean() const {\n    std::vector<double> out;\n    for (int i = 0; i < mean.size(); ++i) {\n        out.push_back(mean[i]);\n    }\n    return out;\n}\n\n}  // namespace FilterModel\n", "meta": {"hexsha": "c7b088de894c078e8cb78648f14bf0218084f82a", "size": 3557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/multivariate_guassian.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++/multivariate_guassian.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++/multivariate_guassian.cpp", "max_forks_repo_name": "skinnersBoxy/input-filter", "max_forks_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9351851852, "max_line_length": 99, "alphanum_fraction": 0.6058476244, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.5501027344806187}}
{"text": "#pragma once\n#include \"profile.hpp\"\n#include \"mesh.hpp\"\n#include <Eigen/Sparse>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include \"transformation.hpp\"\n#undef TEST_SPARSE\n\n\nnamespace gd {\n\nUSING_PART_OF_NAMESPACE_EIGEN;\n\ntemplate<class Mesh>\nclass PoissonSolver1d;\n\t\t\nconst double ProfileNumerical1d_epsilon = 1e-5;\ntemplate<class Mesh>\n\tclass ProfileNumerical1d : public Profile {\n\tint n;\n\tMesh mesh;\n\tDensity* density;\n\tPoissonSolver1d<Mesh> solver;\n\tVectorXd solution;\n\tTransformation1d_in_3d* transformation;\n\tdouble G;\npublic:\n\t\n\tProfileNumerical1d(int n, Density* density, Transformation1d_in_3d* transformation, double G, double u1, double u2) : mesh(u1, u2, n, transformation), density(density), solver(density, &mesh, G), solution(mesh.get_dof()), transformation(transformation), G(G) {\n\t\tsolver.solve_(solution, 1., 1., 0.);\n\t}\n\tvirtual double densityr(double r) {\n\t\treturn density->densityr(r);\n\t}\n\tvirtual double densityR(double) {\n\t\treturn 0;\n\t}\n\tvirtual double I(double, double) {\n\t\treturn 0;\n\t}  \n\tvirtual double dphidr(double r) {\n\t\tdouble u = transformation->inverse_transform(r);\n\t\t//double u = atan(r) * 2 / M_PI;\n\t\t//double jacobian = M_PI/2 / pow(cos(u*M_PI/2), 2);\n\t\t//double du\n\t\t//return mesh.gradient(solution, u) / jacobian;\n\t\treturn mesh.gradient(solution, u) / transformation->drdu(u); //jacobian;\n\t}\n\tvirtual double potentialr(double r) {\n\t\t//double u = atan(r) * 2 / M_PI;\n\t\tdouble u = transformation->inverse_transform(r);\n\t\treturn mesh.eval(solution, u);\n\t}\n};\n\ntemplate<class Mesh>\nclass PoissonSolver1d {\npublic:\n\ttypedef Mesh mesh_type;\n\tDensity* density;\n\tMesh* mesh;\n\tVectorXd lasta;\n\tdouble G;\n\t\n\tPoissonSolver1d(Density* density, Mesh* mesh, double G) : density(density), mesh(mesh), lasta(mesh->get_dof()), G(G) {\n\t}\n\t\n\tdouble operator()(double x) {\n\t\treturn mesh->eval(lasta, x);\n\t}\n\t\n\tdouble gradient(double x) {\n\t\treturn mesh->gradient(lasta, x);\n\t}\n\t\n\tvoid solve(double_vector v, double scale1, double scale2, double boundary_value=0) {\n\t\tVectorXd v_copy = VectorXd::Map(v.data().begin(), v.size());\n\t\tsolve_(v_copy, scale1, scale2, boundary_value);\n\t}\n\tvoid solve_(VectorXd& v, double scale1, double scale2, double boundary_value=0) {\n\t\t\n\t\t/*\n\t\tsolve 'a' from the linear system Ma=x using FEM (Galerkin method)\n\t\tsuch that \\Phi(r) = \\sum_i a_i \\phi_i(r) is the solution to the \n\t\tpoisson eq: \\delta^2 \\Phi(r) = 4 pi G rho(r) \n\t\t*/\n\t\tint dof = mesh->get_dof();\n#ifdef TEST_SPARSE\n\t\tEigen::DynamicSparseMatrix<double> Ms(dof, dof);\n#else\n\t\tMatrixXd M = MatrixXd::Zero(dof, dof);\n#endif\n\t\tVectorXd x = VectorXd::Zero(dof);\n\t\t\n\t\tint dof_per_cell = Mesh::dof_per_cell;\n\t\tfor(int cell_index = 0; cell_index < mesh->get_n_cells(); cell_index++) {\n\t\t\tfor(int i = 0; i < dof_per_cell; i++) {\n\t\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\t\t//M(cell_index*(dof_per_cell-1)+i, cell_index*(dof_per_cell-1)+j) = integrate dphi_i * dphi_j\n#ifdef TEST_SPARSE\n\t\t\t\t\tMs.coeffRef(mesh->dof_index(cell_index, i), mesh->dof_index(cell_index, j)) +=\n#else\n\t\t\t\t\tM(mesh->dof_index(cell_index, i), mesh->dof_index(cell_index, j)) +=\n#endif\n\t\t\t\t\t\tmesh->integrate_gradshape(cell_index, i, j) * scale1; // * r * r;\n\t\t\t\t\t\t/*integrate dphi_i * dphi_j*/\n\t\t\t\t}\n\t\t\t\t//x(mesh->index(cell_index, i)) += integrate phi_i * 4 * M_PI * density->densityr(r) dr;\n\t\t\t\t//auto f = [&](double r) { return this->density->densityr(r) * r * r; }; //*/ };\n\t\t\t\tauto f = [&](double u) {\n\t\t\t\t\tdouble r = this->mesh->transformation->transform(u);\n\t\t\t\t\t//double r = tan(u*M_PI/2);\n\t\t\t\t\t//double s = sin(u*M_PI/2);\n\t\t\t\t\t//double c = cos(u*M_PI/2);\n\t\t\t\t\t//return this->density->densityr(r) * 2 * M_PI*M_PI * s*s/pow(c,4);\n\t\t\t\t\treturn this->density->densityr(r) * this->mesh->transformation->d3xdu(u);\n\t\t\t\t};\n\t\t\t\t//double G = 1;\n\t\t\t\t//cout << mesh->dof_index(cell_index, i) << \" = \" << (-4 * M_PI * G * mesh->integrate_shape(cell_index, i, f)) << endl;\n\t\t\t\tx(mesh->dof_index(cell_index, i)) += -(4 * M_PI) * G * mesh->integrate_shape(cell_index, i, f) * scale2;\n\t\t\t}\n\t\t}\n\t\t// set boundary condition, Phi(r_end) = 0\n\t\tfor(int i = 1; i < Mesh::dof_per_cell; i++) {\n#ifdef TEST_SPARSE\n\t\t\tMs.coeffRef(dof-1-i,dof-1) = boundary_value;\n\t\t\tMs.coeffRef(dof-1,dof-1-i) = boundary_value;\n#else\n\t\t\tM(dof-1-i,dof-1) = boundary_value;\n\t\t\tM(dof-1,dof-1-i) = boundary_value;\n#endif\n\t\t}\n\t\t\n#ifdef TEST_SPARSE\n\t\tMs.coeffRef(dof-1,dof-1) = 1;\n#else\n\t\tM(dof-1,dof-1) = 1;\n#endif\n\n#ifdef TEST_SPARSE\n\t\ttypedef Eigen::SparseMatrix<double> SparseMatrixType;\n\t\tSparseMatrixType M(Ms);\n#endif\n\t\tx(dof-1) = 0;\n\t\t\n\t\t//cout << M << endl;\n\t\t//cout << \"next\" << endl << x << endl;\n\t\t// solve 'a'\n#ifdef TEST_SPARSE\n\t\tVectorXd a = x;\n\t\tEigen::SparseLLT<SparseMatrixType,Eigen::Cholmod> sparseLLT(M);\n\t\tsparseLLT.solveInPlace(a);\n#else\n\t\t//VectorXd a = M.inverse() * x;\n\t\tVectorXd a(dof);\n\t\tM.llt().solve(x, &a);\n#endif\n\t\tlasta = a;\n\t\t// copy to v \n\t\t//VectorXd::Map(v.data().begin(), v.size()) = a;\n\t\tv = a;\n\t\t//cout << \"x: \" << endl <<  (x) << endl;\n\t\t\n\t\t//cout << \"solution: \" << endl <<  (a) << endl;\n\t\t//cout << \"test\" << endl <<  (M * a) << endl;\n\t}\n};\n\n}", "meta": {"hexsha": "c20598ee77dd01ab91cb5f365d8b57b5d7bff959", "size": 5022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/poisson_fem2.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/poisson_fem2.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/poisson_fem2.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": 29.5411764706, "max_line_length": 261, "alphanum_fraction": 0.6495420151, "num_tokens": 1641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.5500969934600004}}
{"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n#include <chrono>\n#include <NTL/ZZ_pX.h> // contains ZZ_p.h and ZZ.h\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace NTL;\n\nvoid check_p(ZZ_p &ans, long p, vector<ZZ_p> coeffs);\nvoid findF(ZZ_pX &F, ZZ_pX &f, long rtp);\nvoid poly_eval(ZZ_pX &h, ZZ_pX &f, ZZ_pX &g);\nvoid evalF(vector<ZZ_p> &FVals, ZZ_pX &F, long rtp, long prtp);\n\nZZ p;\nZZ mod;\nuint64_t start;\nbool stopchecking;\n\nvoid dumb_check(ZZ_p &ans, long p){\n    for(long i = 0; i < p; i++){\n        mul(ans, ans, i);\n        if(i % 1024 == 0){\n            if(80000 < duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - start){\n                stopchecking = true;\n                return;\n            }\n        }\n    }\n}\nint main(){\n    stopchecking = false;\n    for(long i = 1024; i <= 1099511627776; i*=2){\n        NextPrime(p, ZZ(i));\n        long p1;\n        conv(p1, p);\n        mul(mod, p, p);\n        ZZ_p ans;\n        ans.init(mod);\n        vector<ZZ_p> coeffs(2);\n        coeffs[0].init(mod);\n        coeffs[1].init(mod);\n        coeffs[0] = 0;\n        coeffs[1] = 1;\n        start = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n        dumb_check(ans, p1);\n        uint64_t time = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - start;\n        if(stopchecking){\n            break;\n        }\n        //cout << \"final answer: \" << answer << endl;\n        cout << time << \", \";\n    }\n    cout << endl;\n}\n\n\n\n// TODO: init all ZZ_p variables\nvoid check_p(ZZ_p &ans, long p, vector<ZZ_p> coeffs){\n    ZZ_pX f;\n    for(int i = 0; i < coeffs.size(); i++){\n        SetCoeff(f, i, coeffs[i]);\n    }\n\n    long rtp = sqrt(p-1); // rtp = floor(sqrt(p-1))\n    ZZ_pX F;\n    findF(F, f, rtp);\n\n    long prtp = (p-1)/rtp;\n    vector<ZZ_p> FVals(prtp);\n    evalF(FVals, F, rtp, prtp); // prtp := floor((p-1)/floor(sqrt(p-1)))\n\n    ZZ_p out(1);\n    out.init(mod);\n    for(long i = rtp*prtp+1; i < p; i++){\n        mul(out, out, eval(f, ZZ_p(i)));\n    }\n    for(long i = 0; i < FVals.size(); i++){\n        mul(out, out, FVals[i]);\n    }\n\n    ans = out;\n}\n\n// return F = f(X+1)f(X+2)...f(X+rtp) mod p\nvoid findF(ZZ_pX &F, ZZ_pX &f, long rtp){\n    vector<ZZ_pX> FTree(2*rtp); // rtp leaves -> 2*rtp nodes\n\n    long leftmost = 1 << ((int)ceil(log2(rtp))); // bottom leftmost node in tree\n\n    // Initialize the leaves in FTree: [X+1, X+2, ..., X+rtp]\n    for (long i = leftmost; i < 2 * rtp; i++) { // leaves on lowest layer\n        ZZ_pX leaf;\n        SetCoeff(leaf, 0, i - leftmost + 1);\n        SetCoeff(leaf, 1, 1);\n        poly_eval(leaf, f, leaf); // leaf = f(leaf())\n        FTree[i] = leaf;\n    }\n    for (long i = rtp; i < leftmost; i++) { // leaves on second lowest layer\n        ZZ_pX leaf;\n        SetCoeff(leaf, 0, i + rtp - leftmost + 1);\n        SetCoeff(leaf, 1, 1);\n        poly_eval(leaf, f, leaf); // leaf = f(leaf())\n        FTree[i] = leaf;\n    }\n\n    // Calculate the rest of the product tree FTree\n    for (long i = rtp - 1; i > 0; i--) {\n        FTree[i] = FTree[2*i] * FTree[2*i+1]; // parent is product of leaves\n        // TODO doesn't work:\n        // delete FTree[2*i];\n        // delete FTree[2*i+1];\n    }\n    \n    F = FTree[1];\n}\n\n// calculate h = f(g(x))\nvoid poly_eval(ZZ_pX &h, ZZ_pX &f, ZZ_pX &g){\n    ZZ_pX out(LeadCoeff(f));\n    for(int i = deg(f)-1; i >= 0; i--){\n        mul(out, out, g);\n        add(out, out, coeff(f, i));\n    }\n    h = out;\n}\n\n// evaluate F at 0, rtp, ..., (prtp-1)*rtp\nvoid evalF(vector<ZZ_p> &FVals, ZZ_pX &F, long rtp, long prtp){\n    vector<ZZ_pX> FValTree(2*prtp);\n\n    long leftmost = 1 << ((int)ceil(log2(prtp))); // bottom leftmost node in tree\n\n    // Initialize the leaves in FValTree: [X, X-rtp, ..., X-rtp*(prtp-1)]\n    for (long i = leftmost; i < 2 * prtp; i++) { // leaves on lowest layer\n        ZZ_pX leaf;\n        SetCoeff(leaf, 0, -rtp*(i - leftmost));\n        SetCoeff(leaf, 1, 1);\n        FValTree[i] = leaf;\n    }\n    for (long i = prtp; i < leftmost; i++) { // leaves on second lowest layer\n        ZZ_pX leaf;\n        SetCoeff(leaf, 0, -rtp*(i + prtp - leftmost));\n        SetCoeff(leaf, 1, 1);\n        FValTree[i] = leaf;\n    }\n\n    // Calculate the rest of the product tree FValTree\n    for (long i = prtp - 1; i > 0; i--) {\n        FValTree[i] = FValTree[2*i] * FValTree[2*i+1]; // parent is product of leaves\n    }\n    \n    // Reduce F mod polynomials in FValTree\n    rem(FValTree[1], F, FValTree[1]);\n    for (long i = 1; i < prtp; i++) {\n        rem(FValTree[2*i], FValTree[i], FValTree[2*i]);\n        rem(FValTree[2*i+1], FValTree[i], FValTree[2*i+1]);\n    }\n    \n    for (long i = leftmost; i < 2 * prtp; i++) { // leaves on lowest layer\n        FVals[i - leftmost].init(mod);\n        FVals[i - leftmost] = ConstTerm(FValTree[i]);\n    }\n    for (long i = prtp; i < leftmost; i++) { // leaves on second lowest layer\n        FVals[i + prtp - leftmost].init(mod);\n        FVals[i + prtp - leftmost] = ConstTerm(FValTree[i]);\n    }\n\n}\n", "meta": {"hexsha": "2f10eb6113caa39dac93a8eed09cd9d13e0e8732", "size": 5028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/check_rem_tree.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_rem_tree.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_rem_tree.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.2325581395, "max_line_length": 108, "alphanum_fraction": 0.5379872713, "num_tokens": 1684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.5500969768658579}}
{"text": "/**\n * @file sspdriver_main.cc\n * @brief NPDE homework ExtendedMUSCL code\n * @author Oliver Rietmann\n * @date 04.08.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iostream>\n\n#include \"extendedmuscl.h\"\n\nusing namespace ExtendedMUSCL;\n\n// Bump function, raised by 1\nstatic auto bump = [](double x) {\n  return ((x >= 0.25) && (x <= 0.75))\n             ? (2.0 - std::pow(std::cos(M_PI * (2 * (x - 0.25))), 2))\n             : 1.0;\n};\n\nint main() {\n  // First run: Solve ODE\n  // Settings for the ODE\n  double T = 1.0;\n  double y0 = 1.0;\n  double yT_exact = std::exp(T);\n  auto f = [](double y) { return y; };\n\n  // Choose time-steps 2^(-4), ..., 2^(-10)\n  Eigen::VectorXd tau(7);\n  tau << 0x1p-4, 0x1p-5, 0x1p-6, 0x1p-7, 0x1p-8, 0x1p-9, 0x1p-10;\n\n  // Compute error of approx. solution at time T for all timestep-sizes in tau\n  int N = tau.size();\n  Eigen::VectorXd error(N);\n  for (int n = 0; n < N; ++n) {\n    int steps = (int)(T / tau(n) + 0.5);\n    double y = y0;\n    for (int i = 0; i < steps; ++i) y = sspEvolop(f, y, tau(n));\n    error(n) = std::abs(yT_exact - y);\n  }\n\n  // Print the errors at each timestep\n  Eigen::MatrixXd table(3, N);\n  table.row(0) = tau;\n  table.row(1) = error;\n  table.row(2) = error.unaryExpr([](double x) { return std::log2(x); });\n  Eigen::IOFormat tableFormat(2, 0, \" \", \"\\n\", \" \", \" \", \" \", \" \");\n  std::cout << \"tau \\t error \\t log_2(error)\" << std::endl;\n  std::cout << table.transpose().format(tableFormat) << std::endl;\n\n  // Second run: Write solution for bump initial data to file\n  std::cout << \"Writing MUSCL FV solution at t=0.2 to file 'musclsol_02.csv'\"\n            << std::endl;\n  storeMUSCLSolution(\"musclsol_02.csv\", bump, 0.2, 100);\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/musclsol_02.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_musclsolution.py \" CURRENT_BINARY_DIR\n              \"/musclsol_02.csv \" CURRENT_BINARY_DIR \"/musclsol_02.eps\");\n  std::cout << \"Writing MUSCL FV solution at t = 1.0 to file 'musclsol_10.csv'\"\n            << std::endl;\n  storeMUSCLSolution(\"musclsol_10.csv\", bump, 1.0, 100);\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/musclsol_10.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_musclsolution.py \" CURRENT_BINARY_DIR\n              \"/musclsol_10.csv \" CURRENT_BINARY_DIR \"/musclsol_10.eps\");\n\n  // Third run: convergence study\n  studyCvgMUSCLSolution(bump, 0.2);\n  studyCvgMUSCLSolution(bump, 1.0);\n\n  return 0;\n}\n", "meta": {"hexsha": "20ec746cecc4260210cd94b360e4e69ed629cf64", "size": 2529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExtendedMUSCL/templates/extendedmuscl_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ExtendedMUSCL/templates/extendedmuscl_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ExtendedMUSCL/templates/extendedmuscl_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 32.8441558442, "max_line_length": 79, "alphanum_fraction": 0.6117042309, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.5500739108729195}}
{"text": "//           Copyright Matthew Pulver 2018 - 2019.\n// Distributed under the Boost Software License, Version 1.0.\n//      (See accompanying file LICENSE_1_0.txt or copy at\n//           https://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n#define BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n\n#include <boost/config.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions.hpp>\n#include <boost/math/tools/promotion.hpp>\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <functional>\n#include <limits>\n#include <numeric>\n#include <ostream>\n#include <type_traits>\n\n// Automatic Differentiation v1\nnamespace boost { namespace math { namespace differentiation { inline namespace autodiff_v1 {\n\nnamespace detail {\n\ntemplate<typename RealType, typename... RealTypes>\nstruct promote_args_n { using type = typename boost::math::tools::promote_args_2<RealType,\n    typename promote_args_n<RealTypes...>::type>::type; };\n\ntemplate<typename RealType>\nstruct promote_args_n<RealType> { using type = typename boost::math::tools::promote_arg<RealType>::type; };\n\n} // namespace detail\n\ntemplate<typename RealType, typename... RealTypes>\nusing promote = typename detail::promote_args_n<RealType,RealTypes...>::type;\n\nnamespace detail {\n\ntemplate<typename RealType, size_t Order>\nclass fvar;\n\ntemplate <typename>\nstruct get_depth : std::integral_constant<size_t, 0> {};\n\ntemplate <typename RealType, size_t Order>\nstruct get_depth<fvar<RealType,Order>> : std::integral_constant<size_t,get_depth<RealType>::value+1> {};\n\ntemplate <typename>\nstruct get_order_sum : std::integral_constant<size_t, 0> {};\n\ntemplate <typename RealType, size_t Order>\nstruct get_order_sum<fvar<RealType,Order>> : std::integral_constant<size_t,get_order_sum<RealType>::value+Order> {};\n\n// Get non-fvar<> root type T of autodiff_fvar<T,O0,O1,O2,...>.\ntemplate<typename RealType>\nstruct get_root_type { using type = RealType; };\n\ntemplate<typename RealType, size_t Order>\nstruct get_root_type<fvar<RealType,Order>> { using type = typename get_root_type<RealType>::type; };\n\n// Get type from descending Depth levels into fvar<>.\ntemplate<typename RealType, size_t Depth>\nstruct type_at { using type = RealType; };\n\ntemplate<typename RealType, size_t Order, size_t Depth>\nstruct type_at<fvar<RealType,Order>,Depth> { using type =\n    typename std::conditional<Depth==0, fvar<RealType,Order>, typename type_at<RealType,Depth-1>::type>::type; };\n\ntemplate<typename RealType, size_t Depth>\nusing get_type_at = typename type_at<RealType,Depth>::type;\n\n// Satisfies Boost's Conceptual Requirements for Real Number Types.\n// https://www.boost.org/libs/math/doc/html/math_toolkit/real_concepts.html\ntemplate<typename RealType, size_t Order>\nclass fvar\n{\n    std::array<RealType,Order+1> v;\n\n  public:\n\n    using root_type = typename get_root_type<RealType>::type; // RealType in the root fvar<RealType,Order>.\n\n    fvar() = default;\n\n    // Initialize a variable or constant.\n    fvar(const root_type&, const bool is_variable);\n\n    // RealType(cr) | RealType | RealType is copy constructible.\n    fvar(const fvar&) = default;\n\n    // Be aware of implicit casting from one fvar<> type to another by this copy constructor.\n    template<typename RealType2, size_t Order2>\n    fvar(const fvar<RealType2,Order2>&);\n\n    // RealType(ca) | RealType | RealType is copy constructible from the arithmetic types.\n    explicit fvar(const root_type&); // Initialize a constant. (No epsilon terms.)\n\n    template<typename RealType2>\n    fvar(const RealType2& ca); // Supports any RealType2 for which static_cast<root_type>(ca) compiles.\n\n    // r = cr | RealType& | Assignment operator.\n    fvar& operator=(const fvar&) = default;\n\n    // r = ca | RealType& | Assignment operator from the arithmetic types.\n    // Handled by constructor that takes a single parameter of generic type.\n    //fvar& operator=(const root_type&); // Set a constant.\n\n    // r += cr | RealType& | Adds cr to r.\n    template<typename RealType2, size_t Order2>\n    fvar& operator+=(const fvar<RealType2,Order2>&);\n\n    // r += ca | RealType& | Adds ar to r.\n    fvar& operator+=(const root_type&);\n\n    // r -= cr | RealType& | Subtracts cr from r.\n    template<typename RealType2, size_t Order2>\n    fvar& operator-=(const fvar<RealType2,Order2>&);\n\n    // r -= ca | RealType& | Subtracts ca from r.\n    fvar& operator-=(const root_type&);\n\n    // r *= cr | RealType& | Multiplies r by cr.\n    template<typename RealType2, size_t Order2>\n    fvar& operator*=(const fvar<RealType2,Order2>&);\n\n    // r *= ca | RealType& | Multiplies r by ca.\n    fvar& operator*=(const root_type&);\n\n    // r /= cr | RealType& | Divides r by cr.\n    template<typename RealType2, size_t Order2>\n    fvar& operator/=(const fvar<RealType2,Order2>&);\n\n    // r /= ca | RealType& | Divides r by ca.\n    fvar& operator/=(const root_type&);\n\n    // -r | RealType | Unary Negation.\n    fvar operator-() const;\n\n    // +r | RealType& | Identity Operation.\n    const fvar& operator+() const;\n\n    // cr + cr2 | RealType | Binary Addition\n    template<typename RealType2, size_t Order2>\n    promote<fvar,fvar<RealType2,Order2>> operator+(const fvar<RealType2,Order2>&) const;\n\n    // cr + ca | RealType | Binary Addition\n    fvar operator+(const root_type&) const;\n\n    // ca + cr | RealType | Binary Addition\n    template<typename RealType2, size_t Order2>\n    friend fvar<RealType2,Order2>\n        operator+(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr - cr2 | RealType | Binary Subtraction\n    template<typename RealType2, size_t Order2>\n    promote<fvar,fvar<RealType2,Order2>> operator-(const fvar<RealType2,Order2>&) const;\n\n    // cr - ca | RealType | Binary Subtraction\n    fvar operator-(const root_type&) const;\n\n    // ca - cr | RealType | Binary Subtraction\n    template<typename RealType2, size_t Order2>\n    friend fvar<RealType2,Order2>\n        operator-(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr * cr2 | RealType | Binary Multiplication\n    template<typename RealType2, size_t Order2>\n    promote<fvar,fvar<RealType2,Order2>> operator*(const fvar<RealType2,Order2>&) const;\n\n    // cr * ca | RealType | Binary Multiplication\n    fvar operator*(const root_type&) const;\n\n    // ca * cr | RealType | Binary Multiplication\n    template<typename RealType2, size_t Order2>\n    friend fvar<RealType2,Order2>\n        operator*(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr / cr2 | RealType | Binary Subtraction\n    template<typename RealType2, size_t Order2>\n    promote<fvar,fvar<RealType2,Order2>> operator/(const fvar<RealType2,Order2>&) const;\n\n    // cr / ca | RealType | Binary Subtraction\n    fvar operator/(const root_type&) const;\n\n    // ca / cr | RealType | Binary Subtraction\n    template<typename RealType2, size_t Order2>\n    friend fvar<RealType2,Order2>\n        operator/(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr == cr2 | bool | Equality Comparison\n    template<typename RealType2, size_t Order2> // This only compares the root term. All other terms are ignored.\n    bool operator==(const fvar<RealType2,Order2>&) const;\n\n    // cr == ca | bool | Equality Comparison\n    bool operator==(const root_type&) const;\n\n    // ca == cr | bool | Equality Comparison\n    template<typename RealType2, size_t Order2> // This only compares the root term. All other terms are ignored.\n    friend bool operator==(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr != cr2 | bool | Inequality Comparison\n    template<typename RealType2, size_t Order2>\n    bool operator!=(const fvar<RealType2,Order2>&) const;\n\n    // cr != ca | bool | Inequality Comparison\n    bool operator!=(const root_type&) const;\n\n    // ca != cr | bool | Inequality Comparison\n    template<typename RealType2, size_t Order2>\n    friend bool operator!=(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr <= cr2 | bool | Less than equal to.\n    template<typename RealType2, size_t Order2>\n    bool operator<=(const fvar<RealType2,Order2>&) const;\n\n    // cr <= ca | bool | Less than equal to.\n    bool operator<=(const root_type&) const;\n\n    // ca <= cr | bool | Less than equal to.\n    template<typename RealType2, size_t Order2>\n    friend bool operator<=(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr >= cr2 | bool | Greater than equal to.\n    template<typename RealType2, size_t Order2>\n    bool operator>=(const fvar<RealType2,Order2>&) const;\n\n    // cr >= ca | bool | Greater than equal to.\n    bool operator>=(const root_type&) const;\n\n    // ca >= cr | bool | Greater than equal to.\n    template<typename RealType2, size_t Order2>\n    friend bool operator>=(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr < cr2 | bool | Less than comparison.\n    template<typename RealType2, size_t Order2>\n    bool operator<(const fvar<RealType2,Order2>&) const;\n\n    // cr < ca | bool | Less than comparison.\n    bool operator<(const root_type&) const;\n\n    // ca < cr | bool | Less than comparison.\n    template<typename RealType2, size_t Order2>\n    friend bool operator<(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // cr > cr2 | bool | Greater than comparison.\n    template<typename RealType2, size_t Order2>\n    bool operator>(const fvar<RealType2,Order2>&) const;\n\n    // cr > ca | bool | Greater than comparison.\n    bool operator>(const root_type&) const;\n\n    // ca > cr | bool | Greater than comparison.\n    template<typename RealType2, size_t Order2>\n    friend bool operator>(const typename fvar<RealType2,Order2>::root_type&, const fvar<RealType2,Order2>&);\n\n    // Will throw std::out_of_range if Order < order.\n    template<typename... Orders>\n    get_type_at<RealType, sizeof...(Orders)> at(size_t order, Orders... orders) const;\n\n    template<typename... Orders>\n    get_type_at<fvar, sizeof...(Orders)> derivative(Orders... orders) const;\n\n    fvar inverse() const; // Multiplicative inverse.\n\n    static constexpr size_t depth = get_depth<fvar>::value; // Number of nested std::array<RealType,Order>.\n\n    static constexpr size_t order_sum = get_order_sum<fvar>::value;\n\n    explicit operator root_type() const; // Must be explicit, otherwise overloaded operators are ambiguous.\n\n    fvar& set_root(const root_type&);\n\n    // Use when function returns derivatives.\n    fvar apply(const std::function<root_type(size_t)>&) const;\n\n    // Use when function returns derivative(i)/factorial(i) (slightly more efficient than apply().)\n    fvar apply_with_factorials(const std::function<root_type(size_t)>&) const;\n\n    // Same as apply() but uses horner method. May be more accurate in some cases but not as good with inf derivatives.\n    fvar apply_with_horner(const std::function<root_type(size_t)>&) const;\n\n    // Same as apply_with_factorials() but uses horner method.\n    fvar apply_with_horner_factorials(const std::function<root_type(size_t)>&) const;\n\nprivate:\n\n    RealType epsilon_inner_product(size_t z0, size_t isum0, size_t m0,\n        const fvar& cr, size_t z1, size_t isum1, size_t m1, size_t j) const;\n\n    fvar epsilon_multiply(size_t z0, size_t isum0, const fvar& cr, size_t z1, size_t isum1) const;\n\n    fvar epsilon_multiply(size_t z0, size_t isum0, const root_type& ca) const;\n\n    fvar inverse_apply() const;\n\n    fvar& multiply_assign_by_root_type(bool is_root, const root_type&);\n\n    template<typename RealType2, size_t Orders2>\n    friend class fvar;\n\n    template<typename RealType2, size_t Order2>\n    friend std::ostream& operator<<(std::ostream&, const fvar<RealType2,Order2>&);\n\n// C++11 Compatibility\n#ifdef BOOST_NO_CXX17_IF_CONSTEXPR\n    template<typename RootType>\n    void fvar_cpp11(std::true_type, const RootType& ca, const bool is_variable);\n\n    template<typename RootType>\n    void fvar_cpp11(std::false_type, const RootType& ca, const bool is_variable);\n\n    template<typename... Orders>\n    get_type_at<RealType, sizeof...(Orders)> at_cpp11(std::true_type, size_t order, Orders... orders) const;\n\n    template<typename... Orders>\n    get_type_at<RealType, sizeof...(Orders)> at_cpp11(std::false_type, size_t order, Orders... orders) const;\n\n    template<typename SizeType>\n    fvar epsilon_multiply_cpp11(std::true_type,\n        SizeType z0, size_t isum0, const fvar& cr, size_t z1, size_t isum1) const;\n\n    template<typename SizeType>\n    fvar epsilon_multiply_cpp11(std::false_type,\n        SizeType z0, size_t isum0, const fvar& cr, size_t z1, size_t isum1) const;\n\n    template<typename SizeType>\n    fvar epsilon_multiply_cpp11(std::true_type, SizeType z0, size_t isum0, const root_type& ca) const;\n\n    template<typename SizeType>\n    fvar epsilon_multiply_cpp11(std::false_type, SizeType z0, size_t isum0, const root_type& ca) const;\n\n    template<typename RootType>\n    fvar& multiply_assign_by_root_type_cpp11(std::true_type, bool is_root, const RootType& ca);\n\n    template<typename RootType>\n    fvar& multiply_assign_by_root_type_cpp11(std::false_type, bool is_root, const RootType& ca);\n\n    template<typename RootType>\n    fvar& set_root_cpp11(std::true_type, const RootType& root);\n\n    template<typename RootType>\n    fvar& set_root_cpp11(std::false_type, const RootType& root);\n#endif\n};\n\n// C++11 compatibility\n#ifdef BOOST_NO_CXX17_IF_CONSTEXPR\n#  define BOOST_AUTODIFF_IF_CONSTEXPR\n#else\n#  define BOOST_AUTODIFF_IF_CONSTEXPR constexpr\n#endif\n\n// Standard Library Support Requirements\n\n// fabs(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fabs(const fvar<RealType,Order>&);\n\n// abs(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> abs(const fvar<RealType,Order>&);\n\n// ceil(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> ceil(const fvar<RealType,Order>&);\n\n// floor(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> floor(const fvar<RealType,Order>&);\n\n// exp(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> exp(const fvar<RealType,Order>&);\n\n// pow(cr, ca) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> pow(const fvar<RealType,Order>&,const typename fvar<RealType,Order>::root_type&);\n\n// pow(ca, cr) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> pow(const typename fvar<RealType,Order>::root_type&,const fvar<RealType,Order>&);\n\n// pow(cr1, cr2) | RealType\ntemplate<typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1,Order1>,fvar<RealType2,Order2>>\n    pow(const fvar<RealType1,Order1>&, const fvar<RealType2,Order2>&);\n\n// sqrt(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sqrt(const fvar<RealType,Order>&);\n\n// log(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> log(const fvar<RealType,Order>&);\n\n// frexp(cr1, &i) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> frexp(const fvar<RealType,Order>&, int*);\n\n// ldexp(cr1, i) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> ldexp(const fvar<RealType,Order>&, int);\n\n// cos(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> cos(const fvar<RealType,Order>&);\n\n// sin(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sin(const fvar<RealType,Order>&);\n\n// asin(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> asin(const fvar<RealType,Order>&);\n\n// tan(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> tan(const fvar<RealType,Order>&);\n\n// atan(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> atan(const fvar<RealType,Order>&);\n\n// fmod(cr1,cr2) | RealType\ntemplate<typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1,Order1>,fvar<RealType2,Order2>>\n    fmod(const fvar<RealType1,Order1>&, const fvar<RealType2,Order2>&);\n\n// round(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> round(const fvar<RealType,Order>&);\n\n// iround(cr1) | int\ntemplate<typename RealType, size_t Order>\nint iround(const fvar<RealType,Order>&);\n\n// trunc(cr1) | RealType\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> trunc(const fvar<RealType,Order>&);\n\n// itrunc(cr1) | int\ntemplate<typename RealType, size_t Order>\nint itrunc(const fvar<RealType,Order>&);\n\n// Additional functions\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> acos(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> acosh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> asinh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> atanh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> cosh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> erf(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> erfc(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> lambert_w0(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sinc(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sinh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> tanh(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nlong lround(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nlong long llround(const fvar<RealType,Order>&);\n\ntemplate<typename RealType, size_t Order>\nlong double truncl(const fvar<RealType,Order>&);\n\n// Compile-time test for fvar<> type.\ntemplate<typename>\nstruct is_fvar : std::false_type {};\n\ntemplate<typename RealType, size_t Order>\nstruct is_fvar<fvar<RealType,Order>> : std::true_type {};\n\ntemplate<typename RealType, size_t Order, size_t... Orders> // specialized for fvar<> below.\nstruct nest_fvar { using type = fvar<typename nest_fvar<RealType,Orders...>::type,Order>; };\n\ntemplate<typename RealType, size_t Order>\nstruct nest_fvar<RealType,Order> { using type = fvar<RealType,Order>; };\n\n} // namespace detail\n\ntemplate<typename RealType, size_t Order, size_t... Orders>\nusing autodiff_fvar = typename detail::nest_fvar<RealType,Order,Orders...>::type;\n\ntemplate<typename RealType, size_t Order, size_t... Orders>\nautodiff_fvar<RealType,Order,Orders...> make_fvar(const RealType& ca)\n{\n    return autodiff_fvar<RealType,Order,Orders...>(ca, true);\n}\n\nnamespace detail {\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>::fvar(const root_type& ca, const bool is_variable)\n{\n    if constexpr (is_fvar<RealType>::value)\n    {\n        v.front() = RealType(ca, is_variable);\n        if constexpr (0 < Order)\n            std::fill(v.begin()+1, v.end(), static_cast<RealType>(0));\n    }\n    else\n    {\n        v.front() = ca;\n        if constexpr (0 < Order)\n            v[1] = static_cast<root_type>(static_cast<int>(is_variable));\n        if constexpr (1 < Order)\n            std::fill(v.begin()+2, v.end(), static_cast<RealType>(0));\n    }\n}\n#endif\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nfvar<RealType,Order>::fvar(const fvar<RealType2,Order2>& cr)\n{\n    for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)\n        v[i] = static_cast<RealType>(cr.v[i]);\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)\n        std::fill(v.begin()+(Order2+1), v.end(), static_cast<RealType>(0));\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>::fvar(const root_type& ca)\n:    v{{static_cast<RealType>(ca)}}\n{\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2>\nfvar<RealType,Order>::fvar(const RealType2& ca)\n:    v{{static_cast<RealType>(ca)}} // Can cause compiler error if RealType2 cannot be cast to root_type.\n{\n}\n\n/*\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator=(const root_type& ca)\n{\n    v.front() = static_cast<RealType>(ca);\n    if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order)\n        std::fill(v.begin()+1, v.end(), static_cast<RealType>(0));\n    return *this;\n}\n*/\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nfvar<RealType,Order>& fvar<RealType,Order>::operator+=(const fvar<RealType2,Order2>& cr)\n{\n    for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)\n        v[i] += cr.v[i];\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator+=(const root_type& ca)\n{\n    v.front() += ca;\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nfvar<RealType,Order>& fvar<RealType,Order>::operator-=(const fvar<RealType2,Order2>& cr)\n{\n    for (size_t i=0 ; i<=Order ; ++i)\n        v[i] -= cr.v[i];\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator-=(const root_type& ca)\n{\n    v.front() -= ca;\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nfvar<RealType,Order>& fvar<RealType,Order>::operator*=(const fvar<RealType2,Order2>& cr)\n{\n    const promote<RealType,RealType2> zero(0);\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order <= Order2)\n        for (size_t i=0, j=Order ; i<=Order ; ++i, --j)\n            v[j] = std::inner_product(v.cbegin(), v.cend()-i, cr.v.crbegin()+i, zero);\n    else\n    {\n        for (size_t i=0, j=Order ; i<=Order-Order2 ; ++i, --j)\n            v[j] = std::inner_product(cr.v.cbegin(), cr.v.cend(), v.crbegin()+i, zero);\n        for (size_t i=Order-Order2+1, j=Order2-1 ; i<=Order ; ++i, --j)\n            v[j] = std::inner_product(cr.v.cbegin(), cr.v.cbegin()+(j+1), v.crbegin()+i, zero);\n    }\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator*=(const root_type& ca)\n{\n    return multiply_assign_by_root_type(true, ca);\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nfvar<RealType,Order>& fvar<RealType,Order>::operator/=(const fvar<RealType2,Order2>& cr)\n{\n    const RealType zero(0);\n    v.front() /= cr.v.front();\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)\n        for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, --j, --k)\n            (v[i] -= std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, v.crbegin()+k, zero)) /= cr.v.front();\n    else if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order2)\n        for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, j&&--j, --k)\n            (v[i] -= std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, v.crbegin()+k, zero)) /= cr.v.front();\n    else\n        for (size_t i=1 ; i<=Order ; ++i)\n            v[i] /= cr.v.front();\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::operator/=(const root_type& ca)\n{\n    std::for_each(v.begin(), v.end(), [&ca](RealType& x) { x /= ca; });\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::operator-() const\n{\n    fvar<RealType,Order> retval;\n    for (size_t i=0 ; i<=Order ; ++i)\n        retval.v[i] = -v[i];\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nconst fvar<RealType,Order>& fvar<RealType,Order>::operator+() const\n{\n    return *this;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\npromote<fvar<RealType,Order>,fvar<RealType2,Order2>>\n    fvar<RealType,Order>::operator+(const fvar<RealType2,Order2>& cr) const\n{\n    promote<fvar<RealType,Order>,fvar<RealType2,Order2>> retval;\n    for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)\n        retval.v[i] = v[i] + cr.v[i];\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)\n        for (size_t i=Order+1 ; i<=Order2 ; ++i)\n            retval.v[i] = cr.v[i];\n    else if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)\n        for (size_t i=Order2+1 ; i<=Order ; ++i)\n            retval.v[i] = v[i];\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::operator+(const root_type& ca) const\n{\n    fvar<RealType,Order> retval(*this);\n    retval.v.front() += ca;\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> operator+(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return cr + ca;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\npromote<fvar<RealType,Order>,fvar<RealType2,Order2>>\n    fvar<RealType,Order>::operator-(const fvar<RealType2,Order2>& cr) const\n{\n    promote<fvar<RealType,Order>,fvar<RealType2,Order2>> retval;\n    for (size_t i=0 ; i<=std::min(Order,Order2) ; ++i)\n        retval.v[i] = v[i] - cr.v[i];\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)\n        for (size_t i=Order+1 ; i<=Order2 ; ++i)\n            retval.v[i] = -cr.v[i];\n    else if BOOST_AUTODIFF_IF_CONSTEXPR (Order2 < Order)\n        for (size_t i=Order2+1 ; i<=Order ; ++i)\n            retval.v[i] = v[i];\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::operator-(const root_type& ca) const\n{\n    fvar<RealType,Order> retval(*this);\n    retval.v.front() -= ca;\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> operator-(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return -cr += ca;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\npromote<fvar<RealType,Order>,fvar<RealType2,Order2>>\n    fvar<RealType,Order>::operator*(const fvar<RealType2,Order2>& cr) const\n{\n    const promote<RealType,RealType2> zero(0);\n    promote<fvar<RealType,Order>,fvar<RealType2,Order2>> retval;\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)\n        for (size_t i=0, j=Order, k=Order2 ; i<=Order2 ; ++i, j&&--j, --k)\n            retval.v[i] = std::inner_product(v.cbegin(), v.cend()-j, cr.v.crbegin()+k, zero);\n    else\n        for (size_t i=0, j=Order2, k=Order ; i<=Order ; ++i, j&&--j, --k)\n            retval.v[i] = std::inner_product(cr.v.cbegin(), cr.v.cend()-j, v.crbegin()+k, zero);\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::operator*(const root_type& ca) const\n{\n    return fvar<RealType,Order>(*this) *= ca;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> operator*(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return cr * ca;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\npromote<fvar<RealType,Order>,fvar<RealType2,Order2>>\n    fvar<RealType,Order>::operator/(const fvar<RealType2,Order2>& cr) const\n{\n    const promote<RealType,RealType2> zero(0);\n    promote<fvar<RealType,Order>,fvar<RealType2,Order2>> retval;\n    retval.v.front() = v.front() / cr.v.front();\n    if BOOST_AUTODIFF_IF_CONSTEXPR (Order < Order2)\n    {\n        for (size_t i=1, j=Order2-1 ; i<=Order ; ++i, --j)\n            retval.v[i] = (v[i] -\n                std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero)) / cr.v.front();\n        for (size_t i=Order+1, j=Order2-Order-1 ; i<=Order2 ; ++i, --j)\n            retval.v[i] =\n                -std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero) / cr.v.front();\n    }\n    else if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order2)\n        for (size_t i=1, j=Order2-1, k=Order ; i<=Order ; ++i, j&&--j, --k)\n            retval.v[i] =\n                (v[i] - std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+k, zero)) / cr.v.front();\n    else\n        for (size_t i=1 ; i<=Order ; ++i)\n            retval.v[i] = v[i] / cr.v.front();\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::operator/(const root_type& ca) const\n{\n    return fvar<RealType,Order>(*this) /= ca;\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> operator/(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    fvar<RealType,Order> retval;\n    retval.v.front() = ca / cr.v.front();\n    if BOOST_AUTODIFF_IF_CONSTEXPR (0 < Order)\n    {\n        const RealType zero(0);\n        for (size_t i=1, j=Order-1 ; i<=Order ; ++i, --j)\n            retval.v[i] = -std::inner_product(cr.v.cbegin()+1, cr.v.cend()-j, retval.v.crbegin()+(j+1), zero)\n                / cr.v.front();\n    }\n    return retval;\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator==(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() == cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator==(const root_type& ca) const\n{\n    return v.front() == ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator==(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca == cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator!=(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() != cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator!=(const root_type& ca) const\n{\n    return v.front() != ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator!=(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca != cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator<=(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() <= cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator<=(const root_type& ca) const\n{\n    return v.front() <= ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator<=(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca <= cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator>=(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() >= cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator>=(const root_type& ca) const\n{\n    return v.front() >= ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator>=(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca >= cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator<(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() < cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator<(const root_type& ca) const\n{\n    return v.front() < ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator<(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca < cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\ntemplate<typename RealType2, size_t Order2>\nbool fvar<RealType,Order>::operator>(const fvar<RealType2,Order2>& cr) const\n{\n    return v.front() > cr.v.front();\n}\n\ntemplate<typename RealType, size_t Order>\nbool fvar<RealType,Order>::operator>(const root_type& ca) const\n{\n    return v.front() > ca;\n}\n\ntemplate<typename RealType, size_t Order>\nbool operator>(const typename fvar<RealType,Order>::root_type& ca, const fvar<RealType,Order>& cr)\n{\n    return ca > cr.v.front();\n}\n\n/*** Other methods and functions ***/\n\n// f : order -> derivative(order)\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::apply(const std::function<root_type(size_t)>& f) const\n{\n    const fvar<RealType,Order> epsilon = fvar<RealType,Order>(*this).set_root(0);\n    fvar<RealType,Order> epsilon_i = fvar<RealType,Order>(1); // epsilon to the power of i\n    fvar<RealType,Order> accumulator = fvar<RealType,Order>(f(0));\n    for (size_t i=1 ; i<=order_sum ; ++i)\n    {    // accumulator += (epsilon_i *= epsilon) * (f(i) / boost::math::factorial<root_type>(i));\n        epsilon_i = epsilon_i.epsilon_multiply(i-1, 0, epsilon, 1, 0);\n        accumulator += epsilon_i.epsilon_multiply(i, 0, f(i) / boost::math::factorial<root_type>(i));\n    }\n    return accumulator;\n}\n\n// f : order -> derivative(order)/factorial(order)\n// Use this when the computation of the derivatives already includes the factorial terms. E.g. See atan().\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>\n    fvar<RealType,Order>::apply_with_factorials(const std::function<root_type(size_t)>& f) const\n{\n    const fvar<RealType,Order> epsilon = fvar<RealType,Order>(*this).set_root(0);\n    fvar<RealType,Order> epsilon_i = fvar<RealType,Order>(1); // epsilon to the power of i\n    fvar<RealType,Order> accumulator = fvar<RealType,Order>(f(0));\n    for (size_t i=1 ; i<=order_sum ; ++i)\n    {    // accumulator += (epsilon_i *= epsilon) * f(i);\n        epsilon_i = epsilon_i.epsilon_multiply(i-1, 0, epsilon, 1, 0);\n        accumulator += epsilon_i.epsilon_multiply(i, 0, f(i));\n    }\n    return accumulator;\n}\n\n// f : order -> derivative(order)\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::apply_with_horner(const std::function<root_type(size_t)>& f) const\n{\n    const fvar<RealType,Order> epsilon = fvar<RealType,Order>(*this).set_root(0);\n    fvar<RealType,Order> accumulator(static_cast<root_type>(f(order_sum)/boost::math::factorial<root_type>(order_sum)));\n    for (size_t i=order_sum ; i-- ;)\n        (accumulator *= epsilon) += f(i) / boost::math::factorial<root_type>(i);\n    return accumulator;\n}\n\n// f : order -> derivative(order)/factorial(order)\n// Use this when the computation of the derivatives already includes the factorial terms. E.g. See atan().\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>\n    fvar<RealType,Order>::apply_with_horner_factorials(const std::function<root_type(size_t)>& f) const\n{\n    const fvar<RealType,Order> epsilon = fvar<RealType,Order>(*this).set_root(0);\n    fvar<RealType,Order> accumulator(f(order_sum));\n    for (size_t i=order_sum ; i-- ;)\n        (accumulator *= epsilon) += f(i);\n    return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate<typename RealType, size_t Order>\ntemplate<typename... Orders>\nget_type_at<RealType,sizeof...(Orders)> fvar<RealType,Order>::at(size_t order, Orders... orders) const\n{\n    if constexpr (0 < sizeof...(Orders))\n        return v.at(order).at(orders...);\n    else\n        return v.at(order);\n}\n#endif\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// Can throw \"std::out_of_range: array::at: __n (which is 7) >= _Nm (which is 7)\"\ntemplate<typename RealType, size_t Order>\ntemplate<typename... Orders>\nget_type_at<fvar<RealType,Order>,sizeof...(Orders)> fvar<RealType,Order>::derivative(Orders... orders) const\n{\n    static_assert(sizeof...(Orders) <= depth, \"Number of parameters to derivative(...) cannot exceed fvar::depth.\");\n    return at(orders...) * (... * boost::math::factorial<root_type>(orders));\n}\n#endif\n\ntemplate<typename RealType, size_t Order>\nRealType fvar<RealType,Order>::epsilon_inner_product(size_t z0, size_t isum0, size_t m0,\n    const fvar<RealType,Order>& cr, size_t z1, size_t isum1, size_t m1, size_t j) const\n{\n    static_assert(is_fvar<RealType>::value, \"epsilon_inner_product() must have 1 < depth.\");\n    RealType accumulator = RealType();\n    const size_t i0_max = m1 < j ? j-m1 : 0;\n    for (size_t i0=m0, i1=j-m0 ; i0<=i0_max ; ++i0, --i1)\n        accumulator += v.at(i0).epsilon_multiply(z0, isum0+i0, cr.v.at(i1), z1, isum1+i1);\n    return accumulator;\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::epsilon_multiply(size_t z0, size_t isum0,\n    const fvar<RealType,Order>& cr, size_t z1, size_t isum1) const\n{\n    const RealType zero(0);\n    const size_t m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n    const size_t m1 = order_sum + isum1 < Order + z1 ? Order + z1 - (order_sum + isum1) : 0;\n    const size_t i_max = m0 + m1 < Order ? Order - (m0 + m1) : 0;\n    fvar<RealType,Order> retval = fvar<RealType,Order>();\n    if constexpr (is_fvar<RealType>::value)\n        for (size_t i=0, j=Order ; i<=i_max ; ++i, --j)\n            retval.v[j] = epsilon_inner_product(z0, isum0, m0, cr, z1, isum1, m1, j);\n    else\n        for (size_t i=0, j=Order ; i<=i_max ; ++i, --j)\n            retval.v[j] = std::inner_product(v.cbegin()+m0, v.cend()-(i+m1), cr.v.crbegin()+(i+m0), zero);\n    return retval;\n}\n#endif\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\n// When called from outside this method, z0 should be non-zero. Otherwise if z0=0 then it will give an\n// incorrect result of 0 when the root value is 0 and ca=inf, when instead the correct product is nan.\n// If z0=0 then use the regular multiply operator*() instead.\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::epsilon_multiply(size_t z0, size_t isum0,\n    const root_type& ca) const\n{\n    fvar<RealType,Order> retval(*this);\n    const size_t m0 = order_sum + isum0 < Order + z0 ? Order + z0 - (order_sum + isum0) : 0;\n    if constexpr (is_fvar<RealType>::value)\n        for (size_t i=m0 ; i<=Order ; ++i)\n            retval.v[i] = retval.v[i].epsilon_multiply(z0, isum0+i, ca);\n    else\n        for (size_t i=m0 ; i<=Order ; ++i)\n            if (retval.v[i] != static_cast<RealType>(0))\n                retval.v[i] *= ca;\n    return retval;\n}\n#endif\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::inverse() const\n{\n    return operator root_type() == 0 ? inverse_apply() : 1 / *this;\n}\n\n// This gives log(0.0) = depth(1)(-inf,inf,-inf,inf,-inf,inf)\n// 1 / *this: log(0.0) = depth(1)(-inf,inf,-inf,-nan,-nan,-nan)\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fvar<RealType,Order>::inverse_apply() const\n{\n    root_type derivatives[order_sum+1]; // LCOV_EXCL_LINE This causes a false negative on lcov coverage test.\n    const root_type x0 = static_cast<root_type>(*this);\n    *derivatives = 1 / x0;\n    for (size_t i=1 ; i<=order_sum ; ++i)\n        derivatives[i] = -derivatives[i-1] * i / x0;\n    return apply([&derivatives](size_t j) { return derivatives[j]; });\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::multiply_assign_by_root_type(bool is_root, const root_type& ca)\n{\n    auto itr = v.begin();\n    if constexpr (is_fvar<RealType>::value)\n    {\n        itr->multiply_assign_by_root_type(is_root, ca);\n        for (++itr ; itr!=v.end() ; ++itr)\n            itr->multiply_assign_by_root_type(false, ca);\n    }\n    else\n    {\n        if (is_root || *itr != 0)\n            *itr *= ca; // Skip multiplication of 0 by ca=inf to avoid nan. Exception: root value is always multiplied.\n        for (++itr ; itr!=v.end() ; ++itr)\n            if (*itr != 0)\n                *itr *= ca;\n    }\n    return *this;\n}\n#endif\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>::operator root_type() const\n{\n    return static_cast<root_type>(v.front());\n}\n\n#ifndef BOOST_NO_CXX17_IF_CONSTEXPR\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order>& fvar<RealType,Order>::set_root(const root_type& root)\n{\n    if constexpr (is_fvar<RealType>::value)\n        v.front().set_root(root);\n    else\n        v.front() = root;\n    return *this;\n}\n#endif\n\n// Standard Library Support Requirements\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> fabs(const fvar<RealType,Order>& cr)\n{\n    const typename fvar<RealType,Order>::root_type zero(0);\n    return cr < zero ? -cr\n        : cr == zero ? fvar<RealType,Order>() // Canonical fabs'(0) = 0.\n        : cr; // Propagate NaN.\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> abs(const fvar<RealType,Order>& cr)\n{\n    return fabs(cr);\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> ceil(const fvar<RealType,Order>& cr)\n{\n    using std::ceil;\n    return fvar<RealType,Order>(ceil(static_cast<typename fvar<RealType,Order>::root_type>(cr)));\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> floor(const fvar<RealType,Order>& cr)\n{\n    using std::floor;\n    return fvar<RealType,Order>(floor(static_cast<typename fvar<RealType,Order>::root_type>(cr)));\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> exp(const fvar<RealType,Order>& cr)\n{\n    using std::exp;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    const root_type d0 = exp(static_cast<root_type>(cr));\n    return cr.apply_with_horner([&d0](size_t) { return d0; });\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> pow(const fvar<RealType,Order>& x,const typename fvar<RealType,Order>::root_type& y)\n{\n    using std::pow;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    root_type derivatives[order+1];\n    const root_type x0 = static_cast<root_type>(x);\n    size_t i = 0;\n    root_type coef = 1;\n    for (; i<=order && coef!=0 ; ++i)\n    {\n        derivatives[i] = coef * pow(x0, y-i);\n        coef *= y - i;\n    }\n    return x.apply([&derivatives,i](size_t j) { return j < i ? derivatives[j] : 0; });\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> pow(const typename fvar<RealType,Order>::root_type& x,const fvar<RealType,Order>& y)\n{\n    using std::log;\n    return exp(y*log(x));\n}\n\ntemplate<typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1,Order1>,fvar<RealType2,Order2>>\n    pow(const fvar<RealType1,Order1>& x, const fvar<RealType2,Order2>& y)\n{\n    return exp(y*log(x));\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sqrt(const fvar<RealType,Order>& cr)\n{\n    using std::sqrt;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    root_type derivatives[order+1];\n    const root_type x = static_cast<root_type>(cr);\n    *derivatives = sqrt(x);\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(*derivatives);\n    else\n    {\n        root_type numerator = 0.5;\n        root_type powers = 1;\n        derivatives[1] = numerator / *derivatives;\n        for (size_t i=2 ; i<=order ; ++i)\n        {\n            numerator *= -0.5 * ((i<<1)-3);\n            powers *= x;\n            derivatives[i] = numerator / (powers * *derivatives);\n        }\n        return cr.apply([&derivatives](size_t i) { return derivatives[i]; });\n    }\n}\n\n// Natural logarithm. If cr==0 then derivative(i) may have nans due to nans from inverse().\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> log(const fvar<RealType,Order>& cr)\n{\n    using std::log;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = log(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        const auto d1 = make_fvar<root_type,order-1>(static_cast<root_type>(cr)).inverse(); // log'(x) = 1 / x\n        return cr.apply_with_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> frexp(const fvar<RealType,Order>& cr, int* exp)\n{\n    using std::frexp;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    frexp(static_cast<root_type>(cr), exp);\n    return cr * std::exp2(-*exp);\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> ldexp(const fvar<RealType,Order>& cr, int exp)\n{\n    return cr * std::exp2(exp);\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> cos(const fvar<RealType,Order>& cr)\n{\n    using std::cos;\n    using std::sin;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    const root_type d0 = cos(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (fvar<RealType,Order>::order_sum == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        const root_type d1 = -sin(static_cast<root_type>(cr));\n        const root_type derivatives[4] { d0, d1, -d0, -d1 };\n        return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&3]; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sin(const fvar<RealType,Order>& cr)\n{\n    using std::sin;\n    using std::cos;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    const root_type d0 = sin(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (fvar<RealType,Order>::order_sum == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        const root_type d1 = cos(static_cast<root_type>(cr));\n        const root_type derivatives[4] { d0, d1, -d0, -d1 };\n        return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&3]; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> asin(const fvar<RealType,Order>& cr)\n{\n    using std::asin;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = asin(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto d1 = make_fvar<root_type,order-1>(static_cast<root_type>(cr)); // asin'(x) = 1 / sqrt(1-x*x).\n        d1 = sqrt(1-(d1*=d1)).inverse(); // asin(1): d1 = depth(1)(inf,inf,-nan,-nan,-nan)\n        //d1 = sqrt((1-(d1*=d1)).inverse()); // asin(1): d1 = depth(1)(inf,-nan,-nan,-nan,-nan)\n        return cr.apply_with_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> tan(const fvar<RealType,Order>& cr)\n{\n    return sin(cr) / cos(cr);\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> atan(const fvar<RealType,Order>& cr)\n{\n    using std::atan;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = atan(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto d1 = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        d1 = ((d1*=d1)+=1).inverse(); // atan'(x) = 1 / (x*x+1).\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType1, size_t Order1, typename RealType2, size_t Order2>\npromote<fvar<RealType1,Order1>,fvar<RealType2,Order2>>\n    fmod(const fvar<RealType1,Order1>& cr1, const fvar<RealType2,Order2>& cr2)\n{\n    using std::trunc;\n    const auto numer = static_cast<typename fvar<RealType1,Order1>::root_type>(cr1);\n    const auto denom = static_cast<typename fvar<RealType2,Order2>::root_type>(cr2);\n    return cr1 - cr2 * trunc(numer/denom);\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> round(const fvar<RealType,Order>& cr)\n{\n    using std::round;\n    return fvar<RealType,Order>(round(static_cast<typename fvar<RealType,Order>::root_type>(cr)));\n}\n\ntemplate<typename RealType, size_t Order>\nint iround(const fvar<RealType,Order>& cr)\n{\n    using boost::math::iround;\n    return iround(static_cast<typename fvar<RealType,Order>::root_type>(cr));\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> trunc(const fvar<RealType,Order>& cr)\n{\n    using std::trunc;\n    return fvar<RealType,Order>(trunc(static_cast<typename fvar<RealType,Order>::root_type>(cr)));\n}\n\ntemplate<typename RealType, size_t Order>\nint itrunc(const fvar<RealType,Order>& cr)\n{\n    using boost::math::itrunc;\n    return itrunc(static_cast<typename fvar<RealType,Order>::root_type>(cr));\n}\n\ntemplate<typename RealType, size_t Order>\nstd::ostream& operator<<(std::ostream& out, const fvar<RealType,Order>& cr)\n{\n    out << \"depth(\" << cr.depth << ')';\n    for (size_t i=0 ; i<cr.v.size() ; ++i)\n        out << (i?',':'(') << cr.v[i];\n    return out << ')';\n}\n\n// Additional functions\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> acos(const fvar<RealType,Order>& cr)\n{\n    using std::acos;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = acos(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = -sqrt(1-(x*=x)).inverse(); // acos'(x) = -1 / sqrt(1-x*x).\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> acosh(const fvar<RealType,Order>& cr)\n{\n    using std::acosh;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = acosh(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = sqrt((x*=x)-1).inverse(); // acosh'(x) = 1 / sqrt(x*x-1).\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> asinh(const fvar<RealType,Order>& cr)\n{\n    using std::asinh;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = asinh(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = sqrt((x*=x)+1).inverse(); // asinh'(x) = 1 / sqrt(x*x+1).\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> atanh(const fvar<RealType,Order>& cr)\n{\n    using std::atanh;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = atanh(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = (1-(x*=x)).inverse(); // atanh'(x) = 1 / (1-x*x)\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> cosh(const fvar<RealType,Order>& cr)\n{\n    using std::cosh;\n    using std::sinh;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    const root_type d0 = cosh(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (fvar<RealType,Order>::order_sum == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        const root_type derivatives[2] { d0, sinh(static_cast<root_type>(cr)) };\n        return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&1]; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> erf(const fvar<RealType,Order>& cr)\n{\n    using std::erf;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = erf(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = 2*boost::math::constants::one_div_root_pi<root_type>()*exp(-(x*=x)); // 2/sqrt(pi)*exp(-x*x)\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> erfc(const fvar<RealType,Order>& cr)\n{\n    using std::erfc;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    const root_type d0 = erfc(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        auto x = make_fvar<root_type,order-1>(static_cast<root_type>(cr));\n        const auto d1 = -2*boost::math::constants::one_div_root_pi<root_type>()*exp(-(x*=x)); // erfc'(x)=-erf'(x)\n        return cr.apply_with_horner_factorials([&d0,&d1](size_t i) { return i ? d1.at(i-1)/i : d0; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> lambert_w0(const fvar<RealType,Order>& cr)\n{\n    using boost::math::lambert_w0;\n    using std::exp;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    root_type derivatives[order+1];\n    *derivatives = lambert_w0(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(*derivatives);\n    else\n    {\n        const root_type expw = exp(*derivatives);\n        derivatives[1] = 1 / (static_cast<root_type>(cr) + expw);\n        if BOOST_AUTODIFF_IF_CONSTEXPR (order == 1)\n            return cr.apply([&derivatives](size_t i) { return derivatives[i]; });\n        else\n        {\n            root_type d1powers = derivatives[1] * derivatives[1];\n            const root_type x = derivatives[1] * expw;\n            derivatives[2] = d1powers * (-1 - x);\n            std::array<root_type,order> coef {{ -1, -1 }}; // as in derivatives[2].\n            for (size_t n=3 ; n<=order ; ++n)\n            {\n                coef[n-1] = coef[n-2] * -static_cast<root_type>(2*n-3);\n                for (size_t j=n-2 ; j!=0 ; --j)\n                    (coef[j] *= -static_cast<root_type>(n-1)) -= (n+j-2) * coef[j-1];\n                coef[0] *= -static_cast<root_type>(n-1);\n                d1powers *= derivatives[1];\n                derivatives[n] = d1powers * std::accumulate(coef.crend()-(n-1), coef.crend(), coef[n-1],\n                    [&x](const root_type& a, const root_type& b) { return a*x + b; });\n            }\n            return cr.apply([&derivatives](size_t i) { return derivatives[i]; });\n        }\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sinc(const fvar<RealType,Order>& cr)\n{\n    if (cr != 0)\n        return sin(cr) / cr;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    constexpr size_t order = fvar<RealType,Order>::order_sum;\n    root_type taylor[order+1] { 1 }; // sinc(0) = 1\n    if BOOST_AUTODIFF_IF_CONSTEXPR (order == 0)\n        return fvar<RealType,Order>(*taylor);\n    else\n    {\n        for (size_t n=2 ; n<=order ; n+=2)\n            taylor[n] = (1-static_cast<int>(n&2)) / boost::math::factorial<root_type>(n+1);\n        return cr.apply_with_factorials([&taylor](size_t i) { return taylor[i]; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> sinh(const fvar<RealType,Order>& cr)\n{\n    using std::sinh;\n    using std::cosh;\n    using root_type = typename fvar<RealType,Order>::root_type;\n    const root_type d0 = sinh(static_cast<root_type>(cr));\n    if BOOST_AUTODIFF_IF_CONSTEXPR (fvar<RealType,Order>::order_sum == 0)\n        return fvar<RealType,Order>(d0);\n    else\n    {\n        const root_type derivatives[2] { d0, cosh(static_cast<root_type>(cr)) };\n        return cr.apply_with_horner([&derivatives](size_t i) { return derivatives[i&1]; });\n    }\n}\n\ntemplate<typename RealType, size_t Order>\nfvar<RealType,Order> tanh(const fvar<RealType,Order>& cr)\n{\n    const fvar<RealType,Order> exp2cr = exp(cr*2);\n    return (exp2cr - 1) /= (exp2cr + 1);\n}\n\ntemplate<typename RealType, size_t Order>\nlong lround(const fvar<RealType,Order>& cr)\n{\n    using std::lround;\n    return lround(static_cast<typename fvar<RealType,Order>::root_type>(cr));\n}\n\ntemplate<typename RealType, size_t Order>\nlong long llround(const fvar<RealType,Order>& cr)\n{\n    using std::llround;\n    return llround(static_cast<typename fvar<RealType,Order>::root_type>(cr));\n}\n\ntemplate<typename RealType, size_t Order>\nlong double truncl(const fvar<RealType,Order>& cr)\n{\n    using std::truncl;\n    return truncl(static_cast<typename fvar<RealType,Order>::root_type>(cr));\n}\n\n} } } } } // namespace boost::math::differentiation::autodiff_v1::detail\n\nnamespace std {\n\n/// boost::math::tools::digits<RealType>() is handled by this std::numeric_limits<> specialization,\n/// and similarly for max_value, min_value, log_max_value, log_min_value, and epsilon.\ntemplate <typename RealType, size_t Order>\nclass numeric_limits<boost::math::differentiation::detail::fvar<RealType,Order>>\n    : public numeric_limits<typename boost::math::differentiation::detail::fvar<RealType,Order>::root_type>\n{ };\n\n} // namespace std\n\nnamespace boost { namespace math { namespace tools {\n\n// See boost/math/tools/promotion.hpp\ntemplate <typename RealType0, size_t Order0, typename RealType1, size_t Order1>\nstruct promote_args_2<differentiation::detail::fvar<RealType0,Order0>,differentiation::detail::fvar<RealType1,Order1>>\n{\n    using type = differentiation::detail::fvar<typename promote_args_2<RealType0,RealType1>::type,\n#ifndef BOOST_NO_CXX14_CONSTEXPR\n        std::max(Order0,Order1)>;\n#else\n        Order0 < Order1 ? Order1 : Order0>;\n#endif\n};\n\ntemplate <typename RealType0, size_t Order0, typename RealType1>\nstruct promote_args_2<differentiation::detail::fvar<RealType0,Order0>,RealType1>\n{\n    using type = differentiation::detail::fvar<typename promote_args_2<RealType0,RealType1>::type,Order0>;\n};\n\ntemplate <typename RealType0, typename RealType1, size_t Order1>\nstruct promote_args_2<RealType0,differentiation::detail::fvar<RealType1,Order1>>\n{\n    using type = differentiation::detail::fvar<typename promote_args_2<RealType0,RealType1>::type,Order1>;\n};\n\n} } } // namespace boost::math::tools\n\n#ifdef BOOST_NO_CXX17_IF_CONSTEXPR\n#include \"autodiff_cpp11.hpp\"\n#endif\n\n#endif // BOOST_MATH_DIFFERENTIATION_AUTODIFF_HPP\n", "meta": {"hexsha": "8be0a3b60f79be0e8db1a33ff53cfa460967f5b9", "size": 59266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/differentiation/autodiff.hpp", "max_stars_repo_name": "kedarbhat/autodiff", "max_stars_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-17T08:13:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T21:19:42.000Z", "max_issues_repo_path": "include/boost/math/differentiation/autodiff.hpp", "max_issues_repo_name": "kedarbhat/autodiff", "max_issues_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/math/differentiation/autodiff.hpp", "max_forks_repo_name": "kedarbhat/autodiff", "max_forks_repo_head_hexsha": "bc402a608dea51d8834bcabe957e9490e68713b9", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2927127985, "max_line_length": 120, "alphanum_fraction": 0.6871224648, "num_tokens": 16852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.5500224405511858}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint main() {\n    cpp_int a, b, c, d; cin >> a >> b >> c >> d;\n    cpp_int x = (b / d) + (b / c) - (b / lcm(c, d)), y = ((a - 1) / d) + ((a - 1) / c) - ((a - 1) / lcm(c, d));\n    cout << (b - a + 1) - (x - y) << endl;\n}\n", "meta": {"hexsha": "34a93c138dc7150c60532e1b7790d2e318b8dd25", "size": 399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc131/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/abc131/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/abc131/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": 30.6923076923, "max_line_length": 111, "alphanum_fraction": 0.5313283208, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.5500070596269341}}
{"text": "#include \"boostengine.hpp\"\n\n#include <boost/numeric/odeint.hpp>\n\nvoid BoostEngine::reset(Length_t new_state)\n{\n    m_height = new_state;\n    m_momentum = 0 * si::kilograms * si::meters / si::seconds;\n}\n\nauto BoostEngine::update(const Time_t dt) -> std::pair<Length_t, Speed_t>\n{\n    using namespace boost::numeric::odeint;\n    using stepper_type\n        = symplectic_rkn_sb3a_mclachlan<Length_t, Momentum_t, double, Speed_t, Force_t, Time_t, vector_space_algebra>;\n\n    // integrate_const(\n    //         stepper_type() ,\n    //         std::make_pair(\n    //                 [this](const Momentum_t& p, Speed_t& dqdt){ dqdt =  p / currentMass(); },\n    //                 [this](const Length_t& q, Force_t& dpdt) { dpdt = currentThrust() - gravity(q); }),\n    //         std::make_pair(boost::ref(m_height), boost::ref(m_momentum)),\n    //         0.0 * si::seconds , dt , dt);\n\n    integrate_n_steps(stepper_type(),\n                      std::make_pair([this](const Momentum_t& p, Speed_t& dqdt) { dqdt = p / currentMass(); },\n                                     [this](const Length_t& q, Force_t& dpdt) { dpdt = totalForce(q); }),\n                      std::make_pair(boost::ref(m_height), boost::ref(m_momentum)), 0.0 * si::seconds, dt, 1);\n\n    return {m_height, m_momentum / currentMass()};\n}\n", "meta": {"hexsha": "a45662121942ad72faf3facfd07470fd03a3b95c", "size": 1300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/boostengine.cpp", "max_stars_repo_name": "julienlopez/QmlMoonLander", "max_stars_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-30T03:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-30T03:04:27.000Z", "max_issues_repo_path": "src/boostengine.cpp", "max_issues_repo_name": "julienlopez/QmlMoonLander", "max_issues_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/boostengine.cpp", "max_forks_repo_name": "julienlopez/QmlMoonLander", "max_forks_repo_head_hexsha": "fe3d7555abfc36a814f2205a0965198f5fca87d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.625, "max_line_length": 118, "alphanum_fraction": 0.5907692308, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.5500070432492946}}
